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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
8957532ae5224c1242990f09e6a4d412bacd8692 | C++ | aadarshasubedi/Learning-CPlusPlus-by-Creating-Games-w-UE4 | /Ch 3 - If, Else and Switch/Ex0 - IfElse/Source.cpp | UTF-8 | 296 | 3.71875 | 4 | [] | no_license | #include<iostream>
#include<string>
using namespace std;
int main()
{
cout << "Enter two number integers, separated by a space " << endl;
int x, y;
cin >> x >> y;
if (x > y)
{
cout << "x is greater than y." << endl;
}
else
{
cout << "y is greater than x." << endl;
}
return 0;
} | true |
02d4ed6ed6402ba13ccdfc0178ebdf0537238a83 | C++ | niuxu18/logTracker-old | /second/download/CMake/CMake-gumtree/Kitware_CMake_repos_basic_block_block_307.cpp | UTF-8 | 288 | 2.828125 | 3 | [] | no_license | (typ->status & _LINKED_TYPE)
{
assert(argp != 0);
return(
Next_Choice(typ->left ,field,argp->left) ||
Next_Choice(typ->right,field,argp->right) );
}
else
{
assert(typ->next != 0);
return typ->next(field,(void *)argp);
} | true |
7cb1856aa8cf4fbcc57a98c2b87a7866f8b92e71 | C++ | Axel542/PhysicsEngine | /Physics Engine Source/PhysicsEngine/Box.h | UTF-8 | 1,827 | 3.09375 | 3 | [
"MIT"
] | permissive | #pragma once
#include "Rigidbody.h"
#include "PhysicsObject.h"
#include <Gizmos.h>
using namespace aie;
//Child of Rigidbody.
class Box : public Rigidbody
{
public:
//Constructors and Destructors.
Box();
Box(glm::vec2 position, glm::vec2 velocity,
float mass,const float extenseX,
const float extenseY,
const glm::vec4 RGBAValues);
Box(glm::vec2 position, glm::vec2 velocity,
float mass, glm::vec2 extenseX, glm::vec2 extenseY,
glm::vec4 RGBAValues);
~Box();
//Makes the shape using the gizmos.
void makeGizmo( );
//virtual bool checkCollision(PhysicsObject* other) override;
//Gets the x and y extenses.
const float getExtenseX() const { return m_extenseX; }
const float getExtenseY() const { return m_extenseY; }
//Sets and gets both extenses
void setExtense(glm::vec2 extense);
const glm::vec2 getExtense() const { return{ m_extenseX, m_extenseY }; }
//Sets and gets colour
void setColour(glm::vec4 RGBAValues);
const glm::vec4 getColour() const { return m_colour; }
//Sets and checks whether the shape is filled.
bool getFilled() { return isFilled; }
void setFilled(bool filled) { isFilled = filled; }
//Sets where the box can rotate or not.
void setOOBB(bool oobb) { isOOBB = oobb; }
//Resolves the collisions slightly differently.
//then the basic function.
void resolveCollisionBox(Rigidbody* actor2, glm::vec2 normal);
protected:
//Protected variables.
glm::vec4 m_colour = { 0,1,0,1 }; //Boxes colour
float m_extenseX = 1.0f; // X extense
float m_extenseY = 1.0f; // Y extense
glm::vec2 DEFAULT_POSITION = { 0,0 }; //Default position variable
glm::vec2 DEFAULT_VELOCITY = { 0,0 }; //Default velocity.
float DEFAULT_MASS = 1.0f; // Default mass.
bool isFilled = false; //Checks if the box is filled.
bool isOOBB = false; //Checks if the box is able to rotate.
};
| true |
df9909add6366cddb32c61b790132c291d9051ee | C++ | ctyin/ese421_arduinos | /HW_Point2Point_Starter.ino | UTF-8 | 2,876 | 2.546875 | 3 | [] | no_license | #include <Romi32U4.h>
Romi32U4LCD lcd;
Romi32U4Buzzer buzzer;
Romi32U4ButtonA buttonA;
Romi32U4ButtonB buttonB;
Romi32U4ButtonC buttonC;
Romi32U4Motors motors;
Romi32U4Encoders encoders;
const char beepButtonA[] PROGMEM = "!c32";
const char beepButtonB[] PROGMEM = "!e32";
const char beepButtonC[] PROGMEM = "!g32";
// This function watches for button presses. If a button is
// pressed, it beeps a corresponding beep and it returns 'A',
// 'B', or 'C' depending on what button was pressed. If no
// button was pressed, it returns 0. This function is meant to
// be called repeatedly in a loop.
char buttonMonitor()
{
if (buttonA.getSingleDebouncedPress())
{
buzzer.playFromProgramSpace(beepButtonA);
return 'A';
}
if (buttonB.getSingleDebouncedPress())
{
buzzer.playFromProgramSpace(beepButtonB);
return 'B';
}
if (buttonC.getSingleDebouncedPress())
{
buzzer.playFromProgramSpace(beepButtonC);
return 'C';
}
return 0;
}
// define data structure for robot pose
struct robotPose{
double X;
double Y;
double Q;
};
//
// this is dummy code -- will be replaced by actual pose measurement
//
struct robotPose getPose() {
struct robotPose measuredP;
measuredP.X = 0.8516*millis()/25.0;
measuredP.Y = measuredP.X/1.732;
measuredP.Q = 30.0;
return measuredP;
}
void setup() {
lcd.clear();
Serial.begin(115200); // Serial COM at hight baud rate
delay(2000);
}
void loop() {
const float x_error = 0.1;
const float y_error = 0.1;
struct robotPose P = getPose(); // pretend this gives actual pose
static int index = 0;
static float x_way_pts[7] = {5, 10, 15, 20, 25}; // first way point is the starting position
static float y_way_pts[7] = {30, 20, 15, 50, 100};
static float last_x = 0;
static float last_y = 0;
static unsigned long millisLast = millis();
float deltaT = 0.05;
while ((millis() - millisLast) < 1000 * deltaT) {}
millisLast = millis();
static byte motorsGo = 0;
switch(buttonMonitor()) {
case 'A':
break;
case 'B':
motorsGo = 1-motorsGo;
break;
case 'C':
break;
}
if (abs(P.X - x_way_pts[index]) < x_error and abs(P.Y - y_way_pts[index]) < y_error) {
// TODO: turn towards new waypoint
last_x = x_way_pts[index];
last_y = y_way_pts[index];
index++;
}
// Doing some math to calculate the diff between the shortest path line
float slope = (y_way_pts[index] - last_y) / (x_way_pts[index] - last_x);
float intercept = last_y - slope * last_x;
// Using a manipulated point-to-line distance formula
float dist_err = (-1 * slope * P.X + P.Y - intercept) / sqrt(pow(slope, 2) + 1);
int pwmDel = (int) (2.2 * dist_err);
pwmDel = constrain(pwmDel, -100, 100);
int pwmAvg = 50;
if (
}
| true |
a7b7f110990737c832133147cbb312797c93001f | C++ | vladdy-moses/ulstu-ivk-os-2019 | /labworks/lw04/Badamshin/badamshin lab4.2/main.cpp | UTF-8 | 403 | 2.59375 | 3 | [] | no_license | #include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
using namespace std;
int main()
{
int fd;
char name[]="/home/student/Documents/labs/aaa.fifo";
char resstring [30];
mknod(name, S_IFIFO | 0666, 0);
fd = open(name, O_RDONLY);
read(fd, resstring, 25);
close(fd);
cout << resstring <<"\n";
return 0;
}
| true |
059a486790ab20d71fb6dbed9363fc2fe93f935e | C++ | TenFifteen/SummerCamp | /lbc_lintcodeII/397-longest-increasing-continuous-subsequence.cc | UTF-8 | 944 | 3.53125 | 4 | [] | no_license | /*
题目大意:
最长连续上升子序列
解题思路:
见代码。
遇到的问题:
没有。
*/
class Solution {
public:
/**
* @param A an array of Integer
* @return an integer
*/
int longestIncreasingContinuousSubsequence(vector<int>& A) {
// Write your code here
if (A.size() < 2) return A.size();
int len = 1;
int last = 0, index = 1;
while (index < A.size()) {
if (A[index] > A[index-1]) {
index++;
len = max(index-last, len);
} else {
last = index++;
}
}
last = A.size()-1, index = last-1;
while (index >= 0) {
if (A[index] > A[index+1]) {
index--;
len = max(last-index, len);
} else {
last = index--;
}
}
return len;
}
}; | true |
15e5f43f4d99df94a48fe45f251d3445051ef4e2 | C++ | jobinrjohnson/red_channel_extract | /src/VideoProcessor.cpp | UTF-8 | 1,722 | 2.75 | 3 | [] | no_license | //
// Created by Jobin Johnson on 09/03/20.
//
#include <sys/time.h>
#include "../include/VideoProcessor.hpp"
using namespace cv;
void VideoProcessor::setCaptureDevice(int device) {
this->videoInputDeviceID = device;
}
std::string VideoProcessor::getFileName() {
struct timeval tp;
gettimeofday(&tp, NULL);
long int ms = tp.tv_sec * 1000 + tp.tv_usec / 1000;
char fileName[60];
sprintf(fileName, "recorded/video_%ld.mp4", ms);\
return fileName;
}
void VideoProcessor::capture() {
cv::VideoCapture input(this->videoInputDeviceID);
if (!input.isOpened()) {
std::cout << "Error while opening video stream";
return;
}
int extension = static_cast<int>(input.get(CV_CAP_PROP_FOURCC));
Size size = Size((int) input.get(CV_CAP_PROP_FRAME_WIDTH),
(int) input.get(CV_CAP_PROP_FRAME_HEIGHT));
std::string fileName = this->getFileName();
std::cout << std::endl << "Saving file to " << fileName << std::endl;
cv::VideoWriter videoOutput(
fileName,
VideoWriter::fourcc('m', 'p', '4', 'v'),
input.get(CV_CAP_PROP_FPS),
size,
false
);
long int i = 0;
while (i++ < input.get(CV_CAP_PROP_FPS) * this->getDuraion()) {
cv::Mat frame;
input >> frame;
if (frame.empty()) {
std::cout << "Unable to read frame";
break;
}
// Extract red
cv::Mat redFrame;
extractChannel(frame, redFrame, 2);
// Gaussian Blur
Mat blurred;
GaussianBlur(redFrame, blurred, Size(5, 5), 0, 0);
videoOutput.write(blurred);
}
videoOutput.release();
input.release();
} | true |
637a4b7574d9b2c94c724b9a5a34950a74aa5a94 | C++ | shixv/test | /cpp/05cpp/MyString.h | GB18030 | 740 | 3.34375 | 3 | [] | no_license | #include <iostream>
using std::ostream;
using std::istream;
class MyString
{
private:
char *str; //ڶϿһַĿռ䣬 strָռַ
int len; //ַij
public:
MyString();
MyString(int len);
MyString(const char *str);
MyString(const MyString& another);
~MyString();
//ز[]
char &operator[](int n);
//ز=
MyString &operator=(MyString &);
//ز<<
friend ostream &operator<<(ostream &os,const MyString &str);
//ز>>
friend istream &operator>>(istream &is,const MyString &str);
//ز== =
bool operator==(const MyString &);
bool operator!=(const MyString &);
};
| true |
d74625b6d7e6418213181c045740a2bdc0a55ed1 | C++ | MissGrass/Lanqiao | /算法训练/2 最大最小公倍数 .cpp | GB18030 | 614 | 3.453125 | 3 | [] | no_license | /*
֪һNʴ1~NѡǵСΪ١
ʽ
һN
ʽ
һʾҵС
9
504
ݹģԼ
1 <= N <= 106
*/
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
int main() {
long long n,ads;
cin >> n;
if(n <= 2)
ads = n;
else if(n % 2 == 1)
ads = n*(n-1)*(n-2);
else if(n % 3 != 0)
ads = n*(n-1)*(n-3) ;
else
ads = (n-1)*(n-2)*(n-3);
cout << ads << endl;
return 0;
}
| true |
d8f344acaf69154b632037e69a310558b87ba575 | C++ | anchal441/codes | /A_08/reverserecursion.cpp | UTF-8 | 275 | 2.96875 | 3 | [] | no_license | #include <iostream>
using namespace std;
void reverse(int index,int arr[]){
if(index<0){
return;
}
cout<<arr[index]<<" ";
reverse(index-1,arr);
}
int main(){
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++){
cin>>arr[i];
}
reverse(n-1,arr);
} | true |
d25dee865f6c72adb58e1505bfca336a1464a9f9 | C++ | rock-core/base-types | /src/samples/Temperature.hpp | UTF-8 | 726 | 2.65625 | 3 | [] | no_license | #ifndef __BASE_SAMPLES_TEMPERATURE_HH__
#define __BASE_SAMPLES_TEMPERATURE_HH__
#include <base/Temperature.hpp>
#include <base/Time.hpp>
namespace base
{
namespace samples
{
struct Temperature : public base::Temperature
{
/** The sample timestamp */
base::Time time;
Temperature() : base::Temperature() { }
Temperature(base::Time const& time, base::Temperature temp)
: base::Temperature(temp.getKelvin())
, time(time) { }
static Temperature fromKelvin(base::Time const& time, double kelvin);
static Temperature fromCelsius(base::Time const& time, double celsius);
};
}
}
#endif
| true |
05755c82b49a02c4ea28d815b1a7bbbd88c720f1 | C++ | G0uth4m/daily-coding-problem | /189 - distinct_subarr.cpp | UTF-8 | 1,354 | 3.9375 | 4 | [] | no_license | /*
This problem was asked by Google.
Given an array of elements, return the length of the longest subarray where all its elements are distinct.
For example, given the array [5, 1, 3, 5, 2, 3, 4, 1], return 5 as the longest subarray of distinct elements is [5, 2, 3, 4, 1].
*/
#include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;
// O(n); O(n)
int lds(vector<int>& A) {
int left = 0;
int right = 0;
int res = 0;
unordered_set<int> set;
while (right < A.size()) {
if (set.find(A[right]) != set.end()) {
res = max(right - left, res);
while (A[left] != A[right]) {
set.erase(A[left]);
left++;
}
set.erase(A[left]);
left++;
} else {
set.insert(A[right]);
right++;
}
}
return max(right - left, res);
}
// O(n); O(n)
int lds2(vector<int>& A) {
int left = 0;
int right = 0;
int res = 0;
unordered_set<int> set;
while (right < A.size()) {
if (set.find(A[right]) == set.end()) {
set.insert(A[right++]);
res = max(res, right - left);
} else {
set.erase(A[left++]);
}
}
return res;
}
int main() {
vector<int> A = {5, 1, 3, 5, 2, 3, 4, 1};
cout << lds2(A) << endl;
} | true |
f1a22292a13e07983037301c3aa40b99c0f3d1d5 | C++ | huntekah/Gra_w_statki | /Gra_w_statki/main.cpp | WINDOWS-1250 | 2,075 | 2.671875 | 3 | [] | no_license | /*
Projekt stworzony na zajcia z Programowania Obiektowo Orientowanego,
przez Mateusza Lewandowskiego (122599) i Krzysztofa Jurkiewicza (122546).
Gra jest grywalna dla rnych rozdzielczoci,lecz projektowana bya domylnie pod rozdzielczo 1280x720,
i wtedy dziaa najlepiej
Sztuczna inteligencja ustawia swoje statki na jednym, lub dwch kratkach gdy takie rozoenie
zmusza gracza do wikszej losowoci jego ruchw (osabia przewag czowieka, jak jest intelekt).
Gracz dostaje fory w postaci 2-sekundowego udostpnienia mapy przeciwnika.
Wprowadza to element pamiciowy do gry i nieznacznie zwiksza szanse gracza(czowieka) na wygran.
Statki rysowane s "kratka pp kratce" dziki czemu mog przyjmowa rne ksztaty.
maxymalna ilo statkw i wykorzystanych kratek ograniczona jest ich kosztem oraz iloci punktw
jakie moemy na nie wyda
*/
#include "driver.h"
const int szer_okna = 3*1280/10;
const int wys_okna = 3*720/10;
void zamknij_program();
void fgra_1_vs_1();
void fgra_1_vs_ai();
void fwczytaj();
#define ROZMIAR_PLANSZY_DEFINE 10
ALLEGRO_DISPLAY *ekran;
int main(int argc, char **argv)
{
if (!al_init()) {
fprintf(stderr, "failed to initialize allegro!\n");
return -1;
}
al_set_app_name("Gra w statki");
al_install_keyboard();
al_install_mouse();
silnik(szer_okna, wys_okna);
return 0;
}
void zamknij_program()
{
exit(0);
}
void fgra_1_vs_1() {
gra moja_gra(ROZMIAR_PLANSZY_DEFINE, 0);
moja_gra.rozpocznij_gre_1vs1();
al_rest(0.5);
}
void fgra_1_vs_ai() {
gra moja_gra(ROZMIAR_PLANSZY_DEFINE, 1);
moja_gra.rozpocznij_gre_1vsAI();
al_rest(0.5);
}
void fwczytaj() {
int rozmiar;
bool ai;
std::ifstream odczyt;
std::ifstream* ptr;
std::ifstream test("plik_zapisu.txt");
if (test.good()) {
test.close();
odczyt.open("plik_zapisu.txt", std::ios_base::in);
odczyt >> rozmiar;
odczyt >> ai;
ptr = &odczyt;
gra moja_gra(rozmiar, ai);
moja_gra.odczyt = 1;
moja_gra.wczytaj_gre(ptr);
if (ai)moja_gra.rozpocznij_gre_1vsAI();
else moja_gra.rozpocznij_gre_1vs1();
al_rest(0.5);
}
test.close();
} | true |
4f549f5ed9718495ce077375ae8468dded47387f | C++ | HippoCracker/Qt | /PayrollSystem/mainwindow.cpp | UTF-8 | 979 | 2.734375 | 3 | [
"MIT"
] | permissive | #include "mainwindow.h"
#include "ui_mainwindow.h"
#include "adminwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
adminUsername = "admin";
adminPassword = "admin";
employeeDirectory = new EmployeeDirectory();
connect(ui->loginBtn, SIGNAL(clicked(bool)), this, SLOT(loginBtnClicked()));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::loginBtnClicked()
{
QString username = ui->usernameTxt->text();
QString password = ui->passwordTxt->text();
bool isValid = validate(username, password);
if (isValid) {
displayAdminWorkWindow();
} else {
}
}
bool MainWindow::validate(QString username, QString password)
{
bool isEqual = (username == adminUsername) &&
(password == adminPassword);
return isEqual;
}
void MainWindow::displayAdminWorkWindow()
{
AdminWindow adminWindow;
adminWindow.show();
}
| true |
0bbe68d09f3b3d0a376bd6bf567e85a9b5de9e0d | C++ | jjunCoder/ProblemSolving | /1292/1292/소스.cpp | UTF-8 | 557 | 2.6875 | 3 | [] | no_license | /*
2016.9.19
BaekJoon Online Judge
Problem Solving
Seong Joon Seo (ID: jjunCoder)
Problem
#1292
쉽게 푸는 문제
*/
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> v,ps;
for (int i = 1; i <= 50; i++) {
for (int j = 0; j < i; j++) {
v.push_back(i);
}
}
int sum = 0;
for (int i = 0; i < v.size(); i++) {
sum += v[i];
ps.push_back(sum);
}
cin.sync_with_stdio(false);
int a, b;
cin >> a >> b;
if (a == 1) {
printf("%d", ps[b - 1]);
}
else {
printf("%d", ps[b - 1] - ps[a - 2]);
}
return 0;
} | true |
736eaf06c40c9503703e310b079453219466da0b | C++ | Matt-Puentes/rationalNumbers | /rational.cpp | UTF-8 | 3,949 | 3.46875 | 3 | [] | no_license | // rational.cpp Andrew Levy Matthew Puentes
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <cctype>
#include "rational.h"
int gcd(int a, int b) {
int c;
while (a != 0) {
c = a;
a = b % a;
b = c;
}
return b;
}
double getDouble(int x) {
double a = x;
return a;
}
Rational::Rational() {
numerator = 0;
denominator = 1;
}
Rational::Rational(const int wholeNumber) {
numerator = wholeNumber;
denominator = 1;
}
void Rational::giveValue() {
std::cout << numerator;
std::cout << "/";
std::cout << denominator << std::endl;
}
void Rational::simplify() {
if (denominator == 0) {
perror("ERROR: Denominator = 0");
exit(0);
}
int factor = gcd(numerator, denominator);
numerator = numerator / factor;
denominator = denominator / factor;
if (denominator != abs(denominator)) {
denominator = abs(denominator);
numerator = 0 - numerator;
}
}
Rational::Rational(const int num, const int den) {
numerator = num;
denominator = den;
}
std::ostream& operator <<(std::ostream& stream, const Rational &a){
stream << a.numerator << "/" << a.denominator;
return stream;
}
std::istream& operator >>(std::istream& stream, Rational &a){
int num;
char c;
int denum;
stream >> std::ws;
if(!(std::isdigit(stream.peek())) && stream.peek() != '-'){
throw devide_by_zero_exception();
}
stream >> num;
if(stream.peek() != '/'){
a = * (new Rational(num));
return stream;
}
stream >> c >> denum;
a = *(new Rational(num, denum));
return stream;
}
const Rational Rational::operator +(const Rational &a) const {
int sumNum = numerator * a.denominator + a.numerator * denominator;
int sumDen = denominator * a.denominator;
Rational rat(sumNum, sumDen);
rat.simplify();
return rat;
}
const Rational Rational::operator -(const Rational &a) const {
int sumNum = numerator * a.denominator - a.numerator * denominator;
int sumDen = denominator * a.denominator;
Rational rat(sumNum, sumDen);
rat.simplify();
return rat;
}
const Rational Rational::operator *(const Rational &a) const {
int sumNum = numerator * a.numerator;
int sumDen = denominator * a.denominator;
Rational rat(sumNum, sumDen);
rat.simplify();
return rat;
}
const Rational Rational::operator /(const Rational &a) const {
int sumNum = numerator * a.denominator;
int sumDen = denominator * a.numerator;
Rational rat(sumNum, sumDen);
rat.simplify();
return rat;
}
const bool Rational::operator ==(const Rational &a) const {
double A, B;
A = getDouble(numerator) / getDouble(denominator);
B = getDouble(a.numerator) / getDouble(a.denominator);
if (A == B) {
return true;
} else {
return false;
}
}
const bool Rational::operator !=(const Rational &a) const {
double A, B;
A = getDouble(numerator) / getDouble(denominator);
B = getDouble(a.numerator) / getDouble(a.denominator);
if (A == B) {
return false;
} else {
return true;
}
}
const bool Rational::operator <(const Rational &a) const {
double A, B;
A = getDouble(numerator) / getDouble(denominator);
B = getDouble(a.numerator) / getDouble(a.denominator);
if (A < B) {
return true;
} else {
return false;
}
}
const bool Rational::operator >(const Rational &a) const {
double A, B;
A = getDouble(numerator) / getDouble(denominator);
B = getDouble(a.numerator) / getDouble(a.denominator);
if (A >= B) {
return true;
} else {
return false;
}
}
const bool Rational::operator <=(const Rational &a) const {
double A, B;
A = getDouble(numerator) / getDouble(denominator);
B = getDouble(a.numerator) / getDouble(a.denominator);
if (A < B) {
return true;
} else {
return false;
}
}
const bool Rational::operator >=(const Rational &a) const {
double A, B;
A = getDouble(numerator) / getDouble(denominator);
B = getDouble(a.numerator) / getDouble(a.denominator);
if (A >= B) {
return true;
} else {
return false;
}
}
double Rational::toDouble() {
double n, d, y;
n = numerator;
d = denominator;
y = n / d;
return y;
}
| true |
b5b0a934917e5937d0fd0c991ce5a3128c1534ab | C++ | radioroy/directionFinding | /DF_tone_test/DF_tone_test.ino | UTF-8 | 576 | 2.890625 | 3 | [] | no_license | // Roy Gross
// 3 - 8 - 2020
// eighth tester program
// switching between ant 1 and ant 2 because of delay problem (#2)
// no LEDs in this program
// - using tone for higher switching rate
// - I was running into the speed limit of a loop with delays
// - tone operates different than delay - switching rate of up to 8MHz (overkill)
const int k3 = 10; // pin k3
void setup() {
// put your setup code here, to run once:
pinMode(k3, OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
tone(k3,5000); // switching rate of 5 KHz
}
| true |
e814ff0d8ebdf943b2d405ae4f9ae0ed8e01f08b | C++ | PanosGeorgiadis/AccelDevTools | /boost_asio_tcp_example/inc/RawData.h | UTF-8 | 3,208 | 3.078125 | 3 | [] | no_license | #pragma once
#include <stdint.h>
#include <string>
#include <vector>
#include "Generic/noncopyable.h"
namespace Server {
namespace CeosProtocol {
class RawData :
public Infra::Generic::NonCopyable
{
public:
explicit RawData(uint32_t maxLength) :
m_data(maxLength),
m_pStart(m_data.data()),
m_pData(m_pStart)
{
}
RawData(const RawData& other) :
m_data(other.m_data),
m_pStart(m_data.data()),
m_pData(m_pStart)
{
Advance<unsigned char>(other.AdvancedByteSize());
}
RawData(RawData&& other) :
m_data(std::move(other.m_data)),
m_pStart(other.m_pStart),
m_pData(other.m_pData)
{
other.m_pStart = nullptr;
other.m_pData = nullptr;
}
RawData& operator=(const RawData& other)
{
if (&other!=this)
{
m_data = other.m_data;
m_pStart = m_data.data();
m_pData = m_pStart;
Advance<unsigned char>(other.AdvancedByteSize());
}
return *this;
}
RawData& operator=(RawData&& other)
{
if (&other!=this)
{
m_data = std::move(other.m_data);
m_pStart = other.m_pStart;
m_pData = other.m_pData;
other.m_pStart = nullptr;
other.m_pData = nullptr;
}
return *this;
}
public:
template <typename T>
T Read() const
{
CheckAdvance<T>();
T value = *(reinterpret_cast<T*>(m_pData));
Advance<T>();
return value;
}
std::wstring Read(size_t length) const
{
std::wstring result;
for (size_t i = 0; i < length; ++i)
result.push_back(Read<char>());
return result;
}
template <typename T>
void Write(T value)
{
CheckAdvance<T>();
*reinterpret_cast<T*>(m_pData) = value;
Advance<T>();
}
template <>
void Write(std::wstring value)
{
for (size_t i = 0; i < value.length(); ++i)
Write<char>(static_cast<char>(value[i]));
}
void Reset() const
{
m_pData = m_pStart;
}
void* Data(size_t byteIndex=0) const
{
return reinterpret_cast<char*>(m_pStart) + byteIndex;
}
size_t ByteSize() const
{
return m_data.size();
}
private:
template <typename T>
void Advance() const
{
Advance<T>(1U);
}
template <typename T>
void Advance(size_t count) const
{
m_pData = reinterpret_cast<T*>(m_pData) + count;
}
template <typename T>
void CheckAdvance() const
{
CheckAdvance<T>(1);
}
template <typename T>
void CheckAdvance(size_t count) const
{
auto targetSize = AdvancedByteSize() + sizeof(T) * count;
if (targetSize > ByteSize())
throw std::out_of_range("Advanced to far in rawdata");
}
size_t AdvancedByteSize() const
{
return static_cast<unsigned char*>(m_pData) - static_cast<unsigned char*>(m_pStart);
}
private:
std::vector<unsigned char> m_data;
void* m_pStart;
mutable void* m_pData;
};
} // namespace Ceos
} // namespace Server
| true |
15dc37af5d1e1d8f14e3831507873fce404d2d5e | C++ | AnthonyCusimano/VectorMath | /A_Quaternion.cpp | UTF-8 | 7,152 | 3.0625 | 3 | [] | no_license | #include "A_Quaternion.h"
const float A_Quaternion::S_QuaternionNormalThreshold = 0.0001f;
A_Quaternion::A_Quaternion() {
this->dimensions[0] = 0.0f;
this->dimensions[1] = 0.0f;
this->dimensions[2] = 0.0f;
this->dimensions[3] = 0.0f;
}
A_Quaternion::A_Quaternion(A_Quaternion* const _AQ) {
this->dimensions[0] = _AQ->dimensions[0];
this->dimensions[1] = _AQ->dimensions[1];
this->dimensions[2] = _AQ->dimensions[2];
this->dimensions[3] = _AQ->dimensions[3];
}
A_Quaternion::A_Quaternion(A_Vector4* const _AV) {
this->dimensions[0] = _AV->getX();
this->dimensions[1] = _AV->getY();
this->dimensions[2] = _AV->getZ();
this->dimensions[3] = _AV->getW();
}
A_Quaternion::A_Quaternion(float const _n) {
this->dimensions[0] = _n;
this->dimensions[1] = _n;
this->dimensions[2] = _n;
this->dimensions[3] = _n;
}
A_Quaternion::A_Quaternion(float const _x, float const _y, float const _z, float const _w) {
this->dimensions[0] = _x;
this->dimensions[1] = _y;
this->dimensions[2] = _z;
this->dimensions[3] = _w;
}
A_Quaternion::A_Quaternion(A_Vector3 const *_AV, float const _w) {
this->dimensions[0] = _AV->getX();
this->dimensions[1] = _AV->getY();
this->dimensions[2] = _AV->getZ();
this->dimensions[3] = _w;
}
const A_Quaternion A_Quaternion::GetQuaternion(float _angle, A_Vector3 _axis) const{
return A_Quaternion(_axis.getX(), _axis.getY(), _axis.getZ(), _angle);
}
const A_Quaternion A_Quaternion::GetQuaternion(float _x, float _y, float _z, float _w) const{
return A_Quaternion(_x, _y, _z, _w);
}
const A_Vector4 A_Quaternion::GetVector4()const {
A_Vector4 T_Result;
T_Result.SetAll(this->dimensions[0], this->dimensions[1], this->dimensions[2], this->dimensions[3]);
return T_Result;
}
const float A_Quaternion::GetMagnatude() {
float T_Mag = this->dimensions[0] * this->dimensions[0];
T_Mag += (this->dimensions[1] * this->dimensions[1]);
T_Mag += (this->dimensions[2] * this->dimensions[2]);
T_Mag += (this->dimensions[3] * this->dimensions[3]);
T_Mag = ::sqrtf(T_Mag);
return T_Mag;
}
void A_Quaternion::Normalize() {
//before normalizing the quaternion checking
//to see it is outside of the "normal threshold"
//first, squaring the quaternion
float T_Squared = (this->dimensions[0] * this->dimensions[0]) +
(this->dimensions[1] * this->dimensions[1]) +
(this->dimensions[2] * this->dimensions[2]) +
(this->dimensions[3] * this->dimensions[3]);
//next find the absolute value of T_Squared
if (T_Squared - 1.0f < 0.0f) T_Squared *= -1.0f;
//now compare T_Squared with the threshold
if (T_Squared != 0.0f && T_Squared > A_Quaternion::S_QuaternionNormalThreshold) {
//if it is outside of the threshold, normalize
float T_Mag = this->GetMagnatude();
this->dimensions[0] /= T_Mag;
this->dimensions[1] /= T_Mag;
this->dimensions[2] /= T_Mag;
this->dimensions[3] /= T_Mag;
}
//else, don't normalize
}
const float A_Quaternion::GetNormal() {
float T_Mag = this->GetMagnatude();
this->dimensions[0] /= T_Mag;
this->dimensions[1] /= T_Mag;
this->dimensions[2] /= T_Mag;
this->dimensions[3] /= T_Mag;
return T_Mag;
}
void A_Quaternion::Conjugate() {
this->dimensions[0] *= -1.0f;
this->dimensions[1] *= -1.0f;
this->dimensions[2] *= -1.0f;
}
const A_Quaternion A_Quaternion::GetConjugate() {
A_Quaternion T_Result;
T_Result.dimensions[0] = this->dimensions[0] * -1.0f;
T_Result.dimensions[1] = this->dimensions[1] * -1.0f;
T_Result.dimensions[2] = this->dimensions[2] * -1.0f;
T_Result.dimensions[3] = this->dimensions[3];
return T_Result;
}
void A_Quaternion::SetFromEuler(A_Vector3 const &_Euler) {
float T_cosRoll, T_cosPitch, T_cosYaw, T_sinRoll, T_cosPitch2, T_cosYaw2;
//I would like to formally apologize to anyone reading this code in the future for the breakdown in naming conventions here
float T_CosPitchxT_CosYaw, T_CosPitch2xT_CosYaw, T_CosPitchxT_CosYaw2, T_cosPitch2xT_CosYaw;
float T_roll, T_pitch, T_yaw;
T_roll = _Euler.getX() * 0.5f;
T_pitch = _Euler.getY() * 0.5f;
T_yaw = _Euler.getZ() * 0.5f;
T_cosRoll = ::cosf(T_roll);
T_cosPitch = ::cosf(T_pitch);
T_cosYaw = ::cosf(T_yaw);
T_sinRoll = ::sinf(T_roll);
T_cosPitch2 = ::cosf(T_pitch);
T_cosYaw2 = ::cosf(T_yaw);
//these variables done this way to avoid making the same multiplication multiple times down below
//consider trying a different way to ease up on memory slightly while slightly slowing down arithmetic
//move variable declaration above
T_CosPitchxT_CosYaw/*T_CYxCZ*/ = T_cosPitch * T_cosYaw;
T_CosPitch2xT_CosYaw/*2CP2xCY*/ = T_cosPitch2 * T_cosYaw2;
T_CosPitchxT_CosYaw2/*T_CYxSZ*/ = T_cosPitch * T_cosYaw2;
T_cosPitch2xT_CosYaw/*T_SYxCZ*/ = T_cosPitch2 * T_cosYaw;
/*w = cx * cycz + sx * sysz;
x = sx * cycz - cx * sysz;
y = cx * sycz + sx * cysz;
z = cx * cysz - sx * sycz;*/
this->dimensions[0] = (T_sinRoll * T_CosPitchxT_CosYaw) - (T_cosRoll * T_CosPitch2xT_CosYaw);
this->dimensions[1] = (T_cosRoll * T_cosPitch2xT_CosYaw) + (T_sinRoll * T_CosPitchxT_CosYaw2);
this->dimensions[2] = (T_cosRoll * T_CosPitchxT_CosYaw2) - (T_sinRoll * T_cosPitch2xT_CosYaw);
this->dimensions[3] = (T_cosRoll * T_CosPitchxT_CosYaw) + (T_sinRoll * T_cosPitch2xT_CosYaw);
}
void A_Quaternion::SetFromEuler(float const _rollX, float const _pitchY, float const _yawZ) {
float T_cosRoll, T_cosPitch, T_cosYaw, T_sinRoll, T_cosPitch2, T_cosYaw2;
//I would like to formally apologize to anyone reading this code in the future for the breakdown in naming conventions here
float T_CosPitchxT_CosYaw, T_CosPitch2xT_CosYaw, T_CosPitchxT_CosYaw2, T_cosPitch2xT_CosYaw;
float T_roll, T_pitch, T_yaw;
T_roll = _rollX * 0.5f;
T_pitch = _pitchY * 0.5f;
T_yaw = _yawZ * 0.5f;
T_cosRoll = ::cosf(T_roll);
T_cosPitch = ::cosf(T_pitch);
T_cosYaw = ::cosf(T_yaw);
T_sinRoll = ::sinf(T_roll);
T_cosPitch2 = ::cosf(T_pitch);
T_cosYaw2 = ::cosf(T_yaw);
//these variables done this way to avoid making the same multiplication multiple times down below
//consider trying a different way to ease up on memory slightly while slightly slowing down arithmetic
//move variable declaration above
T_CosPitchxT_CosYaw/*T_CYxCZ*/ = T_cosPitch * T_cosYaw;
T_CosPitch2xT_CosYaw/*2CP2xCY*/ = T_cosPitch2 * T_cosYaw2;
T_CosPitchxT_CosYaw2/*T_CYxSZ*/ = T_cosPitch * T_cosYaw2;
T_cosPitch2xT_CosYaw/*T_SYxCZ*/ = T_cosPitch2 * T_cosYaw;
/*w = cx * cycz + sx * sysz;
x = sx * cycz - cx * sysz;
y = cx * sycz + sx * cysz;
z = cx * cysz - sx * sycz;*/
this->dimensions[0] = (T_sinRoll * T_CosPitchxT_CosYaw) - (T_cosRoll * T_CosPitch2xT_CosYaw);
this->dimensions[1] = (T_cosRoll * T_cosPitch2xT_CosYaw) + (T_sinRoll * T_CosPitchxT_CosYaw2);
this->dimensions[2] = (T_cosRoll * T_CosPitchxT_CosYaw2) - (T_sinRoll * T_cosPitch2xT_CosYaw);
this->dimensions[3] = (T_cosRoll * T_CosPitchxT_CosYaw) + (T_sinRoll * T_cosPitch2xT_CosYaw);
}
A_Quaternion::~A_Quaternion() {
} | true |
9c41115f19f27542633cb85794cc8b891f95e4db | C++ | AliHashemi-ai/LeetCode-Solutions | /C++/reverse-substrings-between-each-pair-of-parentheses.cpp | UTF-8 | 531 | 3.359375 | 3 | [
"MIT"
] | permissive | // Time: O(n^2)
// Space: O(n)
class Solution {
public:
string reverseParentheses(string s) {
vector<string> stk = {""};
for (const auto& c : s) {
if (c == '(') {
stk.emplace_back();
} else if (c == ')') {
auto end = move(stk.back()); stk.pop_back();
reverse(end.begin(), end.end());
stk.back() += end;
} else {
stk.back().push_back(c);
}
}
return stk[0];
}
};
| true |
c6c46cb855a84285773573ab89ebe336cf836f0a | C++ | AnkitBhagasra/Euler | /1-25/euler013.cpp | UTF-8 | 587 | 2.828125 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream fin("euler013.txt");
string num[100];
for (int n = 0; n < 100; n++)
getline(fin, num[n]);
string sum(15, '\0');
for (int n = 0; n < sum.size() - 2; n++) {
int tSum = 0;
for (int m = 0; m < 100; m++)
tSum += num[m][n]-'0';
sum[n] += tSum/100;
sum[n+1] += tSum/10%10;
sum[n+2] += tSum%10;
}
for (int n = sum.size() - 1; n > 0; n--) {
if (sum[n] >= 10) {
sum[n] -= 10;
sum[n-1]++;
}
}
for (int n = 0; n < 10; n++)
cout << int(sum[n]);
cout << "\n";
}
| true |
19897e59536f91ff547de1f5ad88980bdbadc6f0 | C++ | blackenwhite/Competitive-Coding | /DAA-2/disjoint_set_cc.cpp | UTF-8 | 2,886 | 3.0625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
long long int countOps;
struct Node
{
int rank;
int parent;
};
struct Edge
{
int start;
int end;
};
class disjointSet
{
public:
Node *disjSet;
int n;
static int opCount;
disjointSet(int n)
{
opCount = 0;
disjSet = new Node[n];
this->n = n;
for(int i = 0; i < n; i++)
{
disjSet[i].parent = i;
disjSet[i].rank = 0;
}
// opCount += (2*n);
}
int find(int child)
{
opCount++;
if(disjSet[child].parent != child)
{
opCount++;
disjSet[child].parent = find(disjSet[child].parent);
}
return disjSet[child].parent;
}
void Union(int a,int b)
{
int parentA = find(a);
int parentB = find(b);
if(disjSet[parentA].rank < disjSet[parentB].rank)
{
disjSet[parentA].parent = parentB;
opCount += 2;
}
else if(disjSet[parentA].rank > disjSet[parentB].rank)
{
disjSet[parentB].parent = parentA;
opCount += 2;
}
else
{
disjSet[parentA].parent = parentB;
disjSet[parentB].rank++;
opCount += 3;
}
}
bool isUnion(int a,int b)
{
return find(a) == find(b);
}
void print()
{
unordered_map<int,set<int>> connectedComponents;
for(int i = 0; i < n; i++)
{
opCount++;
connectedComponents[disjSet[i].parent].insert(i);
}
cout << endl;
for(auto it : connectedComponents)
{
for(auto it1 : it.second)
{
cout << it1 << " ";
}
cout << endl;
}
}
};
int disjointSet::opCount = 0;
int main()
{
int t;
// cin >> t;"input.txt"
ifstream input("input.txt");
ofstream output("output2.txt");
input >> t;
int k = 1;
while(k <= t)
{
countOps = 0;
int n,m;
input >> n >> m;
Edge *graph = new Edge[m];
disjointSet ds(n);
//Initialize rank n parent for n elements
for(int i = 0; i < m; i++)
{
input >> (graph[i].start) >> (graph[i].end);
}
// countOps += 2*m;
for(int i = 0; i < m; i++)
{
countOps++;
if(!ds.isUnion(graph[i].start,graph[i].end))
{
countOps++;
ds.Union(graph[i].start,graph[i].end);
}
}
printf("\nGRAPH %d : ",k);
ds.print();
cout << "\nNumber of Operations: " << disjointSet::opCount + countOps << endl;
output << (n+m) << " " << disjointSet::opCount + countOps << endl;
k++;
}
return 0;
} | true |
ee4810c14f8b9d9ae462c4b91c9e59c72c593ff9 | C++ | Kamfeth/Polski-SPOJ | /Łatwe/C++/Dodawanie liczb całkowitych/DodawanieLiczbCałkowitych.cpp | UTF-8 | 219 | 2.84375 | 3 | [] | no_license | #include <iostream>
int main() {
int firstNumber;
int secondNumber;
int thirdNumber;
std::cin >> firstNumber >> secondNumber >> thirdNumber;
std::cout << firstNumber + secondNumber + thirdNumber;
}
| true |
54c6e1a5ab2c4f138ccf4023e1b6bdeddc3cae30 | C++ | areyykarthik/Zhukouski_Pavel_BSU_Projects | /Other Programming (C++)/Probe_Variant_2_KR/Probe_Variant_2_KR/Footballer.h | WINDOWS-1251 | 1,975 | 3.203125 | 3 | [] | no_license | #pragma once
#include<iostream>
#include<string>
#include<exception>
#pragma warning (disable: 4996)
using namespace std;
enum class Specialization { goalkeeper, defender, midfielder, striker };
class FootballerException
: public exception {
public:
FootballerException(const char *message)
: exception(message) {}
};
class Footballer
{
private:
static int next_ID;
const int ID;
string FIO;
string BirthDate;
Specialization Spec = Specialization::striker;
string FootballClub = "";
string ContractExpDate = "";
int GamesNum = 0;
double AverRate = 0.0; // ,
void Clone(Footballer&);
public:
Footballer(static int anext_ID, const int aID, string aFIO, string aBirthDate, Specialization aSpec = Specialization::striker,
string aFootballClub = "", string aContractExpDate = "", int aGamesNum = 0, double anAverRate = 0.0) : FIO(aFIO), BirthDate(aBirthDate), Spec(aSpec),
FootballClub(aFootballClub), ContractExpDate(aContractExpDate), GamesNum(aGamesNum), AverRate(anAverRate), ID(next_ID++)
{
if (FIO.empty())
throw FootballerException("The name of the footballer can't be empty!");
if (GamesNum < 0)
throw FootballerException("The number of games of the footballer can't be < 0!");
if (AverRate < 0.0)
throw FootballerException("Avreage rate can't be < 0!");
}
Footballer(Footballer&);
virtual ~Footballer();
const int GetID() const;
string GetFIO() const;
string GetBirthDate() const;
Specialization GetSpec() const;
string GetFootballClub() const;
string GetContractExpDate() const;
int GetGamesNum() const;
double GetAverRate() const;
void NewSeason();
void NewGame(int GameRate);
Footballer& operator = (Footballer&);
bool CompareGamesNum(string, Footballer&);
bool CompareAverRate(string, Footballer&);
friend ostream& operator << (ostream&, Footballer&);
}; | true |
e25a7c8ddcd59c7196797957dbf151e624eda52e | C++ | keithw/ahab | /opq.cpp | UTF-8 | 5,225 | 2.6875 | 3 | [] | no_license | #ifndef OPQ_CPP
#define OPQ_CPP
#include <pthread.h>
#include "opq.hpp"
#include "exceptions.hpp"
#include "mutexobj.hpp"
#include <typeinfo>
#include <stdio.h>
template <class T>
Queue<T>::Queue( int s_max_size )
: count( 0 ),
max_size( s_max_size ),
head( NULL ),
tail( NULL ),
output( NULL ),
enqueue_callback( NULL )
{
unixassert( pthread_mutex_init( &mutex, NULL ) );
unixassert( pthread_cond_init( &write_activity, NULL ) );
unixassert( pthread_cond_init( &read_activity, NULL ) );
}
template <class T>
void Queue<T>::set_enqueue_callback( void (*s_enqueue_callback)(void *obj),
void *s_obj)
{
MutexLock x( &mutex );
enqueue_callback = s_enqueue_callback;
obj = s_obj;
}
template <class T>
Queue<T>::~Queue()
{
{
MutexLock x( &mutex );
QueueElement<T> *ptr = head;
while ( ptr ) {
T *op = ptr->element;
QueueElement <T> *next = ptr->next;
delete op;
delete ptr;
ptr = next;
}
unixassert( pthread_cond_destroy( &read_activity ) );
unixassert( pthread_cond_destroy( &write_activity ) );
}
unixassert( pthread_mutex_destroy( &mutex ) );
}
template <class T>
QueueElement<T> *Queue<T>::enqueue( T *h )
{
MutexLock x( &mutex );
if ( output ) {
ahabassert( !head );
ahabassert( !tail );
return output->enqueue( h );
}
while ( max_size && (count >= max_size) ) {
unixassert( pthread_cond_wait( &read_activity, &mutex ) );
}
QueueElement<T> *op = new QueueElement<T>( h );
op->prev = NULL;
op->next = head;
if ( head ) {
head->prev = op;
head = op;
} else {
head = tail = op;
}
count++;
unixassert( pthread_cond_signal( &write_activity ) );
if ( enqueue_callback ) {
(*enqueue_callback)(obj);
}
return op;
}
template <class T>
QueueElement<T> *Queue<T>::leapfrog_enqueue( T *h,
T *leapfrog_type )
{
MutexLock x( &mutex );
if ( output ) {
ahabassert( !head );
ahabassert( !tail );
return output->leapfrog_enqueue( h, leapfrog_type );
}
while ( max_size && (count >= max_size) ) {
unixassert( pthread_cond_wait( &read_activity, &mutex ) );
}
QueueElement<T> *op = new QueueElement<T>( h );
QueueElement<T> *ptr = tail;
while ( (ptr != NULL) && ( typeid( ptr->element ) !=
typeid( h ) ) ) {
ptr = tail->prev;
}
if ( ptr ) {
op->next = ptr->next;
ptr->next = op;
op->prev = ptr;
if ( op->next ) {
op->next->prev = op;
} else {
tail = op;
}
} else {
head = tail = op;
op->prev = op->next = NULL;
}
count++;
unixassert( pthread_cond_signal( &write_activity ) );
if ( enqueue_callback ) {
(*enqueue_callback)(obj);
}
return op;
}
template <class T>
void Queue<T>::remove_specific( QueueElement<T> *op )
{
MutexLock x( &mutex );
ahabassert( count > 0 );
if ( op->prev ) {
op->prev->next = op->next;
} else {
head = op->next;
}
if ( op->next ) {
op->next->prev = op->prev;
} else {
tail = op->prev;
}
delete op;
count--;
unixassert( pthread_cond_signal( &read_activity ) );
}
template <class T>
T *Queue<T>::dequeue( bool wait )
{
QueueElement<T> *ret_elem;
T *ret;
MutexLock x( &mutex );
if ( (!wait) && (count == 0 ) ) {
return NULL;
}
while ( count == 0 ) {
unixassert( pthread_cond_wait( &write_activity, &mutex ) );
}
ret_elem = tail;
tail = tail->prev;
if ( tail ) {
tail->next = NULL;
} else {
ahabassert( count == 1 );
head = NULL;
}
ret = ret_elem->element;
delete ret_elem;
count--;
unixassert( pthread_cond_signal( &read_activity ) );
return ret;
}
template <class T>
void Queue<T>::flush( void )
{
MutexLock x( &mutex );
if ( output ) {
ahabassert( !head );
ahabassert( !tail );
return output->flush();
}
QueueElement<T> *ptr = head;
while ( ptr ) {
T *op = ptr->element;
QueueElement <T> *next = ptr->next;
delete op;
delete ptr;
ptr = next;
}
head = tail = NULL;
count = 0;
}
template <class T>
void Queue<T>::flush_type( T *h )
{
MutexLock x( &mutex );
if ( output ) {
ahabassert( !head );
ahabassert( !tail );
return output->flush_type( h );
}
QueueElement<T> *ptr = head;
while ( ptr ) {
T *op = ptr->element;
bool deleting = ( typeid( op ) == typeid( h ) );
QueueElement <T> *next = ptr->next;
if ( deleting ) {
if ( ptr->prev ) {
ptr->prev->next = ptr->next;
} else {
ahabassert( ptr == head );
head = ptr->next;
}
if ( ptr->next ) {
ptr->next->prev = ptr->prev;
} else {
assert( ptr == tail );
tail = ptr->prev;
}
delete op;
delete ptr;
count--;
}
ptr = next;
}
}
template <class T>
void Queue<T>::hookup( Queue<T> *s_output )
{
MutexLock x( &mutex );
ahabassert( !output );
output = s_output;
/* move anything already in our queue */
QueueElement<T> *ptr = head;
while ( ptr ) {
T *op = ptr->element;
QueueElement <T> *next = ptr->next;
output->enqueue( op ); /* this can block for a long time */
delete ptr;
ptr = next;
}
head = tail = NULL;
count = 0;
}
#endif
| true |
fc45b22325ee8c312d07dbc54a33d3660a7b033f | C++ | kimnamlhn/OPP-HCMUS | /Tuần 3/18120468/18120468/main.cpp | UTF-8 | 1,850 | 3.765625 | 4 | [] | no_license | #include "CLine.h"
#include "CRectangle.h"
#include "Dice.h"
#include "DynamicArray.h"
#include "Random.h"
int CRectangle::countRectangle = 0;
int CLine::countLine = 0;
int main()
{
//Đường thẳng
CLine line1({ 2,3 }, { 3,4 });
cout << "Display line 1: ";
line1.displayLine();
//copy đường thẳng 1 vào đường thẳng 2
cout << "Copy line 1 into line 2: " << endl;
CLine line2 = line1;
cout << "Display line 2: ";
line2.displayLine();
//số lượng đường thẳng tạo ra
cout << "Number of line created: " << CLine::countLine << endl;
cout << endl;
//hình chữ nhật
CRectangle rec1({ 1,2 }, { 2,3 });
cout << "Display rectangle 1: ";
rec1.displayRectangle();
//copy hình chữ nhât 1 vào hình chữ nhât 2
cout << "Copy rectangle 1 into rectangle 2: " << endl;
CRectangle rec2 = rec1;
cout << "Display rectangle 2: ";
rec2.displayRectangle();
//số lượng hình chữ nhât tạo ra
cout << "Number of rectangle created: " << CRectangle::countRectangle << endl;
cout << endl;
//Random
Random ran1;
//random một số nguyên ngẫu nhiên
cout << "Random an interger: " << ran1.Next() << endl;
//random một số nguyên từ 0 đến số nguyên max được nhập vào
//test max = 100
cout << "Random with upper limit number: " << ran1.Next(100) << endl;
cout << endl;
//Dice
Dice dic1;
//gieo xúc sắc
cout << "Roll dice: " << dic1.roll() << endl;
cout << "Roll dice: " << dic1.roll() << endl;
//số lần gieo xúc sắc
cout << "Number of dice rolling: " << dic1.getRollCount() << endl;
cout << endl;
//Mảng động
//tạo một mảng để test
int temp[5] = { 1,2,3,4,5 };
DynamicArray arr1(temp, 5);
cout << "Create an dynamic array and copy: " << endl;
cout << "Display array: " << endl;
arr1.printArray();
return 0;
} | true |
96e4296e98a5ef326e96561639fe5ee5ae47e8a4 | C++ | NicoFlorschuetz/Bachelorthesis | /lib/simulation.cpp | UTF-8 | 5,504 | 2.703125 | 3 | [] | no_license | #include <simulation.h>
FDIR_Master::FDIR_Master(){
setup_pins();
}
Protocol::Protocol(){
}
bool Protocol::isMessageValid(){
return (buffer[0] != 0);
}
//create new message
static Message Protocol::receive(){
Message new_message;
new_message.id_board = buffer[0];
new_message.failureCode = buffer[1];
new_message.failureSolved = buffer[2];
new_message.value = buffer[3];
return new_message;
}
//create new setup Message
static Setup_Message Protocol::receiveSetup(){
Setup_Message new_setup_Message;
new_setup_Message.keepAlivePin = buffer[1];
new_setup_Message.fdirActions = buffer[2];
new_setup_Message.fdirActionParam = buffer[3];
return new_setup_Message;
}
//get data via I2C
void Protocol::readData(int id){
Wire.requestFrom(id,7);
int x = 0;
while(x<=Wire.available()) {
buffer[x] = Wire.read();
x++;
}
}
//send message to slave via I2C
void Protocol::sendMessage(int id, MessageToSlave msg){
Wire.beginTransmission(id);
Wire.write(msg);
Wire.endTransmission();
}
//main function
void Board::execute(void){
if(healthstatus.health == 1) {
const static struct Message resetMessage;
protocol.readData(id);
if (protocol.isMessageValid())
{
message = protocol.receive();
Serial.print(message.id_board);
Serial.print(message.failureCode);
Serial.print(message.failureSolved);
Serial.println(message.value);
failureLevel = handler.detect(id, message);
if(fdirActions != NULL) {
if(failureLevel.LevelNull) {
fdirActions->reset();
}else if (failureLevel.LevelThree) {
healthstatus.health = false;
//fdirActions->execute();
}
}
message = resetMessage;
}else if(!protocol.isMessageValid()) {
setup_Message = protocol.receiveSetup();
Serial.print(setup_Message.keepAlivePin);
Serial.print(setup_Message.fdirActions);
Serial.println(setup_Message.fdirActionParam);
this->fdirActions = FdirActionFactory::getFdirAction(setup_Message.fdirActions, setup_Message.keepAlivePin);
}
}
}
//analyse failure with the help of the received message
FailureAnalysis FailureHandler::detect(int id, Message message){
FailureAnalysis fehlerAnalyse;
switch (message.failureCode) {
case 0:
fehlerAnalyse.LevelNull = true;
break;
case 1:
fehlerAnalyse.LevelOne = true;
break;
case 2:
fehlerAnalyse.LevelTwo = true;
break;
case 3:
fehlerAnalyse.LevelThree = true;
break;
case 4:
fehlerAnalyse.LevelFour = true;
break;
}
return fehlerAnalyse;
}
//set the reset mode
FdirAction* FdirActionFactory::getFdirAction(FDIR_ACTION_t fdirActions, int param){
FdirAction *ret;
switch(fdirActions)
{
case STANDARD_FDIR:
ret = new PinReset(param); //--> Pin
break;
case WIRE_FDIR:
ret = new WireReset(param); // --> id
break;
default:
break;
}
return ret;
}
//shut down collapsed board
void PinReset::execute(void){
digitalWrite(pin, LOW);
}
void PinReset::reset(void){
//not used
}
//send message to slave
void WireReset::execute(){
if(messageSent == false) {
protocol.sendMessage(this->id, RETURN_MSG);
messageSent = true;
}
}
//set messageSent to false, so Master can send message just for one time
void WireReset::reset(){
messageSent = false;
}
//add new Board to schedule
bool FDIR_Master::reg(Executable *e){
schedule[anzahlBoards]= e;
}
//iterates over 127 possible addresses and wait for request from slave
//and create new board object for each address
void FDIR_Master::searchForAddresses(){
delay(1000);
for(int search_address = 1; search_address < 127; search_address++) {
Wire.beginTransmission(search_address);
if(Wire.endTransmission() == 0) {
Board * const board = new Board(search_address);
boards[anzahlBoards] = board;
reg (dynamic_cast<Executable*>(board));
anzahlBoards++;
}
delay(5);
}
}
//for each board in scheduling
void FDIR_Master::doScheduling(){
for(int i = 0; i< anzahlBoards; i++)
{
schedule[i]->execute();
}
}
//first setup for pins
void FDIR_Master::setup_pins(){
digitalWrite(40, LOW);
digitalWrite(30, LOW);
pinMode(40, OUTPUT);
pinMode(30, OUTPUT);
digitalWrite(40, LOW);
digitalWrite(30, LOW);
}
| true |
177d29903cfc65d7a546b402264dc6df321250ea | C++ | PowerTravel/acg | /include/Camera.hpp | UTF-8 | 1,676 | 2.984375 | 3 | [] | no_license | #ifndef CAMERA_HPP
#define CAMERA_HPP
#include "Group.hpp"
#include "Hmat.hpp"
#include "TransformMatrix.hpp"
#ifndef CAMERA_PTR
#define CAMRA_PTR
class Camera;
typedef std::shared_ptr<Camera> camera_ptr;
#endif //CAMERA_PTR
/*
* Class: Camera
* Purpose: A camera.
* Misc: Derived from group.
*/
class Camera : public Group
{
public:
Camera();
Camera(Vec3 eye, Vec3 at, Vec3 up);
virtual ~Camera();
// Take a visitor
void acceptVisitor(NodeVisitor& v);
// Manipulation of position and orientation
void lookAt(Vec3 v);
void lookAt(Vec3 eye, Vec3 at, Vec3 up);
void rotateAroundOrigin(float angle, Vec3 axis);
void translate(Vec3 t);
// Getters of the view and projection matrices
Hmat getProjectionMat();
Hmat getViewMat();
// Support is given for perspective and orthographic projection
void setPerspectiveProjection(float fovy=45.f, float near=-1.f, float far=-1000.f);
void setOrthographicProjection(float left=-4.f, float right=4.f, float bottom=-2.f, float top=2.f, float near = -100.f, float far =100.f );
private:
Hmat _P; // Projection matrix
TransformMatrix _V; // View matrix
// Variables related to perspective projection
float _fovy, _aspect, _near, _far;
// Variables related to position and orientation
Vec3 _eye, _at, _up;
// The actual implementation of perspective and orthographic projection
void perspective();
void orthographic( float left, float right, float bottom,
float top, float near, float far);
// Helperfunction to get the aspect directly from the viewport via glut. A violation of dependance I don't like but meh...
void setAspect();
};
#endif // CAMERA_HPP
| true |
805783dbfa4a49320bcce821fcbf2de29a43adec | C++ | Jimut123/code-backup | /4rth_Sem_c++_backup/PRACTICE/Syllabus/references.cpp | UTF-8 | 372 | 3.03125 | 3 | [
"MIT"
] | permissive | #include<iostream>
using namespace std;
int main()
{
int i = 10;
int &j = i;
cout<<endl<<"i = "<<i<<" j = "<<j;
j = 20;
cout<<endl<<"i = "<<i<<" j = "<<j;
i = 30;
cout<<endl<<"i = "<<i<<" j = "<<j;
i++;
cout<<endl<<"i = "<<i<<" j = "<<j;
j++;
cout<<endl<<"i = "<<i<<" j = "<<j;
cout<<endl<<"address of i = "<<&i<<" address of j = "<<&j<<endl;
return 0;
}
| true |
4f84b72a0b53f0f18de7f1eae957ca6dd2edec03 | C++ | LibelulaV/Game_2D | /polygon/spaceship.cpp | UTF-8 | 1,144 | 2.8125 | 3 | [] | no_license | #include "spaceship.h"
#include "entity.h"
#include "../include/u-gine.h"
CSpaceship::CSpaceship(double x, double y, double width, double height, double angle, double rotateSpeed, double speed) : CEntity(ET_SPACESHIP, x, y, 255, 255, 255, 255) {
m_height = height;
m_width = width;
m_angle = angle;
m_rotateSpeed = rotateSpeed;
m_speed = speed;
}
void CSpaceship::SetAngle(double angle) {
m_angle = angle;
}
double CSpaceship::GetAngle() const {
return m_angle;
}
double CSpaceship::GetHeight() const {
return m_height;
}
double CSpaceship::GetWidth() const {
return m_width;
}
double CSpaceship::GetRotateSpeed() const {
return m_rotateSpeed;
}
double CSpaceship::GetSpeed() const {
return m_speed;
}
void CSpaceship::Run() {
}
void CSpaceship::Draw() {
Renderer::Instance().PushMatrix();
Renderer::Instance().TranslateMatrix(this->GetX(), this->GetY(), 0);
Renderer::Instance().RotateMatrix(m_angle, 0, 0, -1);
Renderer::Instance().SetColor(this->GetR(), this->GetG(), this->GetB(), this->GetA());
Renderer::Instance().DrawTriangle(-m_width / 2, -m_height / 2, m_width, m_height);
Renderer::Instance().PopMatrix();
}
| true |
49833f7e4b9c96f4effc2e1b2ef6e5e60dae9ec4 | C++ | alekssandrans/OOP | /Company/Manager.cpp | UTF-8 | 1,228 | 3.125 | 3 | [] | no_license | #include "Manager.h"
#include<iostream>
Manager:: Manager(const char* name, unsigned yearsOfWork,unsigned programsCount,unsigned salesCount,const char* nickname,unsigned sharesCount)
:Employee(name,yearsOfWork),
Programmer(name,yearsOfWork,programsCount),
Seller(name,yearsOfWork,salesCount),
nickname(NULL),sharesCount(0)
{
this->setNickName(nickname);
this->setSharesCount(sharesCount);
}
Manager:: Manager(const Manager& other)
:Employee(other),
Programmer(other),
Seller(other)
{
this->setNickName(other.nickname);
this->setSharesCount(other.sharesCount);
}
Manager& Manager:: operator=(const Manager& other)
{
if(this!=&other)
{
Programmer:: operator=(other);
Seller:: operator=(other);
this->setNickName(other.nickname);
this->setSharesCount(other.sharesCount);
}
return *this;
}
Manager:: ~Manager()
{
delete [] this->nickname;
}
void Manager:: setNickName(const char* nickname)
{
delete [] this->nickname;
copy(this->nickname,nickname);
}
void Manager:: setSharesCount(unsigned sharesCount)
{
if(sharesCount>=0)
this->sharesCount=sharesCount;
}
| true |
5622c8dd6086dc4478421bf32cdd93264a109321 | C++ | Nikhil-Vinay/DS_And_Algo | /Graph/krushkal.cpp | UTF-8 | 1,795 | 3.625 | 4 | [] | no_license | /** MST stands for minimum spanning tree ***/
/* MST is calculated for undirected weighted and connected graph only **/
/* Number of MST edges = total number of vertices -1 */
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
class edge
{
public:
int u;
int v;
int wt;
edge(int _u,int _v, int _wt):u(_u), v(_v), wt(_wt) {}
};
int GetParent(int *parent, int u)
{
if (parent[u] == u) {
return u;
}
GetParent(parent, parent[u]);
}
bool cmp(const edge &edge1, const edge &edge2)
{
return edge1.wt < edge2.wt;
}
void krushkal(vector<edge> &graph, vector<edge> &output, int n)
{
// sort edges with help of weight
sort(graph.begin(), graph.end(), cmp);
// create parent array, all nodes will be parent of self in beginning
int* parent = new int[n];
for(int i = 0; i < n; i++) {
parent[i] = i;
}
int cnt = 0;
int i = 0;
while(cnt < n-1) { // pick n-1 edges
int u = graph[i].u;
int v = graph[i].v;
int p1 = GetParent(parent, u);
int p2 = GetParent(parent, v);
if(p1 == p2) {
} else {
output.push_back(graph[i]);
parent[p1] = parent[p2];
cnt++;
}
i++;
}
}
int main()
{
int n, e;
cout<<"Enter number of vertices:"<<endl;
cin>>n;
cout<<"Enter number of edges:"<<endl;
cin>>e;
vector<edge> graph;
vector<edge> output;
int i = 0;
int u, v, wt;
cout<<"Enter edge as u v wt"<<endl;
while(i < e) {
cout<<"Enter edge number: "<<i+1<<endl;
cin>>u>>v>>wt;
graph.push_back(edge(u, v, wt));
i++;
}
krushkal(graph, output, n);
cout<<"MST edges are: "<<endl;
for(int i = 0; i < output.size(); i++) {
cout<<output[i].u<<"---"<<output[i].v<<"---"<<output[i].wt<<endl;
}
}
| true |
ca3c9602f370444e0b6b16c96af25d4579c0b04f | C++ | wilmer05/maratones | /libreria/trie.cpp | UTF-8 | 536 | 2.640625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
char cad[100];
struct trie{
trie *nx[30];
trie(){
for(int i=0;i<30;i++)
nx[i]=NULL;
}
void insert(char *s){
if(*s=='\0') return;
if(nx[*s-'a']==NULL){
nx[*s-'a'] = new trie;
}
(*nx[*s-'a']).insert(s+1);
}
};
void recorro(trie &a){
for(int i=0;i<30;i++){
if(a.nx[i]!=NULL){
char t = 'a'+i;
cout << t;
recorro(*(a.nx[i]));
cout << " ";
}
}
}
int main(){
trie a;
cin >> cad;
a.insert(cad);
cin >> cad;
a.insert(cad);
recorro(a);
return 0;
}
| true |
cb391a9f11cbcba459fc67d4264d49fde6e444c7 | C++ | cbm-fles/flesnet | /lib/monitoring/MonitorSink.cpp | UTF-8 | 4,600 | 2.828125 | 3 | [] | no_license | // SPDX-License-Identifier: GPL-3.0-only
// (C) Copyright 2021 GSI Helmholtzzentrum für Schwerionenforschung
// Original author: Walter F.J. Mueller <w.f.j.mueller@gsi.de>
#include "MonitorSink.hpp"
#include <algorithm>
#include <chrono>
#include <iomanip>
#include <sstream>
namespace cbm {
/*! \class MonitorSink
\brief Monitor sink - abstract base class
This class provides an abstract interface for the Monitor sink layer.
Concrete implementations are
- MonitorSinkFile: concrete sink for file output (in InfluxDB line format)
- MonitorSinkInflux1: concrete sink for InfluxDB V1 output
*/
//-----------------------------------------------------------------------------
/*! \brief Constructor
\param monitor back reference to Monitor
\param path path for output
*/
MonitorSink::MonitorSink(Monitor& monitor, const std::string& path)
: fMonitor(monitor), fSinkPath(path) {}
//-----------------------------------------------------------------------------
/*! \brief Removes protocol characters from a string
\param str input string
\returns input with blank, '=', and ',' characters removed
For simplicity and efficiency protocol meta characters are simply removed
and not escaped. Tag and field key names as well as field values simply
should never contain them.
*/
std::string MonitorSink::CleanString(const std::string& str) {
std::string res = str;
res.erase(std::remove(res.begin(), res.end(), ' '), res.end());
res.erase(std::remove(res.begin(), res.end(), '='), res.end());
res.erase(std::remove(res.begin(), res.end(), ','), res.end());
return res;
}
//-----------------------------------------------------------------------------
/*! \brief Escapes string delimiter character '"' of a string
\param str input string
\returns string with all '"' characters escaped with a backslash
*/
std::string MonitorSink::EscapeString(std::string_view str) {
std::string res(str);
size_t pos = 0;
while ((pos = res.find('"', pos)) != std::string::npos) {
res.replace(pos, 1, "\\\"");
pos += 2;
}
return res;
}
//-----------------------------------------------------------------------------
/*! \brief Return tagset string for a Metric `point` in InfluxDB line format
*/
std::string MonitorSink::InfluxTags(const Metric& point) {
std::string res;
for (auto& tag : point.fTagset) {
res += res.empty() ? "" : ",";
res += CleanString(tag.first) + "=" + CleanString(tag.second);
}
return res;
}
//-----------------------------------------------------------------------------
/*! \brief Return field string for a Metric `point` in InfluxDB line format
*/
template <class... Ts> struct overloaded : Ts... { using Ts::operator()...; };
template <class... Ts> overloaded(Ts...) -> overloaded<Ts...>;
std::string MonitorSink::InfluxFields(const Metric& point) {
std::stringstream ss;
ss.precision(16); // ensure full double precision
for (auto& field : point.fFieldset) {
if (ss.tellp() != 0)
ss << ",";
auto& key = field.first;
auto& val = field.second;
ss << CleanString(key) << "=";
// use overloaded visitor pattern as described in cppreference.com
visit(overloaded{
[&ss](bool arg) { // case bool
ss << (arg ? "true" : "false");
},
[&ss](int32_t arg) { // case int32_t
ss << arg << "i";
},
[&ss](uint32_t arg) { // case uint32_t
ss << arg << "i";
},
[&ss](int64_t arg) { // case int64_t
ss << arg << "i";
},
[&ss](uint64_t arg) { // case uint64_t
ss << arg << "i";
},
[&ss](float arg) { // case float
ss << arg;
},
[&ss](double arg) { // case double
ss << arg;
},
[this, &ss](std::string_view arg) { // case string + string_view
ss << '"' << EscapeString(arg) << '"';
}},
val);
}
return ss.str();
}
//-----------------------------------------------------------------------------
/*! \brief Return Metric `point` in InfluxDB line format
*/
std::string MonitorSink::InfluxLine(const Metric& point) {
std::chrono::duration<long, std::nano> timestamp_ns =
point.fTimestamp - std::chrono::system_clock::time_point();
std::string res = point.fMeasurement;
res += "," + InfluxTags(point);
res += " " + InfluxFields(point);
res += " " + std::to_string(timestamp_ns.count());
return res;
}
} // end namespace cbm
| true |
78b7f58ea70b929a19662a3450cba99cdc6b980f | C++ | puannalita19/CPP_TonyGaddis | /PC_10/ch 10 no 2.cpp | UTF-8 | 798 | 3.640625 | 4 | [] | no_license | #include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <cstring>
using namespace std;
void Backward (char *);
int main()
{
char word[41];
cout << "This program will display the letters of a word entered in backwards order"
"follwed by a period." << endl;
cout << "Please enter a word not over 40 letters:" << endl;
// display word entered backwards
cin >> word;
cout << "The entered word displayed in reverse is: " << word << endl;
Backward(word);
cout << endl;
system("Pause");
return 0;
}
void Backward (char *sentencePtr)
{
char *p = sentencePtr;
while ( *p != '\0' )
++p;
while ( p != sentencePtr )
cout.put ( *--p );
}
| true |
5f6cb0bc5c4a8318bbd14008d3c39b4e2169f6a2 | C++ | caiyaodeng/DataIndex | /include/Kernel/FreeSpace/FreeSpace.h | UTF-8 | 1,611 | 2.5625 | 3 | [] | no_license | #ifndef _INTERFACE_FREE_SPACE_H_
#define _INTERFACE_FREE_SPACE_H_
namespace NS_DataIndex {
/**
* 说明:空闲空间管理口接口
* 创建人:蔡曜镫
* 更新时间:2016/1/29*/
virtual
class FreeSpace {
public:
FreeSpace (){}
virtual
~FreeSpace (){}
/**
* 说明:申请空闲块
* 参数:存储的数据长度,接收块数组
* 返回值:申请成功的块数
* 更新时间:2016/1/29*/
virtual
BLOCK_NUM getFreeBlock (const B_SIZE LengthIn, BLOCK_SERIAL_NUM *&iBlockSetOut) = 0;
/**
* 说明:释放空闲块
* 参数:块数量,要释放的块数组
* 返回值:是否释放成功
* 更新时间:2016/1/29*/
virtual
bool returnBlock (const BLOCK_NUM iBlockIn, const BLOCK_NUM *iBlockSetIn) = 0;
/**
* 说明:获取已使用空闲块量
* 参数:无
* 返回值:已使用空闲块量
* 更新时间:2016/1/29*/
virtual
SYS_SIZE getUsedBlockNum () = 0;
/**
* 说明:空闲块扩充
* 参数:无
* 返回值:扩充成功返回本次扩充量/失败返回-1
* 更新时间:2016/1/29*/
virtual
BLOCK_NUM expandFreeSpace () = 0;
/**
* 说明:获取已扩充量
* 参数:无
* 返回值:已扩充量
* 更新时间:2016/1/29*/
virtual
BLOCK_NUM getExtendedSpace () = 0;
};
}
#endif | true |
f445dc0aa3904c15e3749e5361a84d94d9a5ab59 | C++ | bruchs/BattleTank | /BTGame/Source/BTGame/TankBarrel.cpp | UTF-8 | 686 | 2.515625 | 3 | [] | no_license | // Fill out your copyright notice in the Description page of Project Settings.
#include "TankBarrel.h"
void UTankBarrel::Elevate(float RelativeSpeed)
{
// Move The Barrel The Right Amount This Frame.
// Clamp The Relative Speed So The Barrel Always Move At The Same Speed.
RelativeSpeed = FMath::Clamp(RelativeSpeed, -1.0F, 1.0F);
float ElevationChange = RelativeSpeed * UTankBarrel::MaxDegreePerSecond * GetWorld()->DeltaTimeSeconds;
float NewElevation = RelativeRotation.Pitch + ElevationChange;
float FinalElevation = FMath::Clamp(NewElevation, UTankBarrel::MinElevationDegree, UTankBarrel::MaxElevationDegree);
SetRelativeRotation(FRotator(FinalElevation, 0.0F, 0.0F));
} | true |
2470ae9d04ec50969cc75fb4a1f8619fec124fe3 | C++ | yujincheng08/bisoncpp | /bisonc++/terminal/nameorvalue.cc | UTF-8 | 181 | 2.640625 | 3 | [] | no_license | #include "terminal.ih"
ostream &Terminal::nameOrValue(ostream &out) const
{
if (isReserved())
return out << d_readableLiteral;
return out << setw(3) << value();
}
| true |
5a30dc3107967b5fe86db3516bbc1db5b630b174 | C++ | AnubhavShukla09/AlgoPractiseQuestions | /UniqueNumber2.cpp | UTF-8 | 742 | 2.78125 | 3 | [] | no_license | #include<bits/stdc++.h>
#define ll long long
#define el endl
using namespace std;
int indexOfSetbit(int element) {
int pos = 0;
while(element > 0) {
if(( element & 1) == 1) {
break;
}
pos++;
element = element >> 1;
}
return pos;
}
int main() {
int n;
cin >> n;
int ar[n];
int grpA = 0, grpB = 0, XOR = 0;
for(int i=0; i<n; i++) {
cin >> ar[i];
XOR ^= ar[i];
}
int posSetbit = indexOfSetbit(XOR);
int posBit;
for(int i=0; i<n; i++) {
if( indexOfSetbit(ar[i]) == posSetbit ) {
grpA ^= ar[i];
} else {
grpB ^= ar[i];
}
}
cout << grpB << " " << grpA << el;
return 0;
} | true |
e95a85a884b971c99120aac523c2125510643927 | C++ | dreamplayer-zhang/FastImaging | /src/stp/gridder/aw_projection.h | UTF-8 | 9,644 | 2.59375 | 3 | [
"Apache-2.0"
] | permissive | /** @file aw_projection.h
* @brief Classes and function prototypes of aw_projection.
*/
#ifndef AW_PROJECTION_H
#define AW_PROJECTION_H
#include "../common/fft.h"
#include "../common/matstp.h"
#include "../common/spline.h"
#include "../types.h"
#include <armadillo>
namespace stp {
/**
* @brief The WideFieldImaging class
*
* Implements most functions related to W-Projection and A-Projection
*/
class WideFieldImaging {
public:
/**
* @brief Default constructor
*/
WideFieldImaging() = default;
/**
* @brief WideFieldImaging constructor initilization
* @param[in] kernel_size (uint): W-Kernel size (work area size)
* @param[in] cell_size (double): Cell size
* @param[in] oversampling (uint): Kernel oversampling ratio
* @param[in] scaling_factor (double): Scaling factor
* @param[in] w_proj (W_ProjectionPars): W-Projection parameters
* @param[in] r_fft (FFTRoutine): Selects FFT routine.
*/
WideFieldImaging(uint kernel_size, double cell_size, uint oversampling, double scaling_factor, const W_ProjectionPars& w_proj,
FFTRoutine r_fft = FFTRoutine::FFTW_ESTIMATE_FFT);
/**
* @brief Generate image-domain convolution kernel by multiplying image-domain anti-aliasing and W-kernels.
*
* Generating the image-domain convolution kernel in a separate function is useful for A-projection, because this kernel needs to be multiplied
* by A-kernel several times (for each timestep).
*
* @param[in] aa_kernel_img (arma::Col): Sampled image-domain anti-aliasing kernel.
* @param[in] input_w_value (real_t): Average W value used to compute W-kernel.
*/
void generate_image_domain_convolution_kernel(const real_t input_w_value, const arma::Col<real_t>& aa_kernel_img);
/**
* @brief Generate projected image-domain convolution kernel obtained by multiplying image-domain anti-aliasing and W-kernels.
*
* The projected image-domain convolution kernel is used for Hankel transform using the projection slice theorem.
*
* @param[in] aa_kernel_img (arma::Col): Sampled image-domain anti-aliasing kernel.
* @param[in] input_w_value (real_t): Average W value used to compute W-kernel.
*/
arma::Col<cx_real_t> generate_projected_image_domain_kernel(const real_t input_w_value, const arma::Col<real_t>& aa_kernel_img);
/**
* @brief Generate convolution kernel at oversampled-pixel offsets for W-Projection.
*
* @param[in] input_w_value (real_t): Average W value used to compute W-kernel.
* @param[in] aa_kernel_img (arma::Col<real_t>&): Sampled image-domain anti-aliasing kernel.
* @param[in] hankel_proj_slice (bool): Whether to use projection slice theorem for Hankel transform or not
*/
void generate_convolution_kernel_wproj(real_t input_w_value, const arma::Col<real_t>& aa_kernel_img, bool hankel_proj_slice = false);
/**
* @brief Generate convolution kernel at oversampled-pixel offsets for A-Projection.
*
* @param[in] a_kernel_img (arma::Mat): A-kernel (computed from beam pattern) used to generate A-projection convolution kernel.
*/
void generate_convolution_kernel_aproj(const arma::Mat<real_t>& a_kernel_img);
/**
* @brief Generate a cache of kernels at oversampled-pixel offsets for A/W-Projection.
*
* @return (arma::field<arma::mat>): Cache of convolution kernels associated to oversampling-pixel offsets.
*/
arma::field<arma::Mat<cx_real_t>> generate_kernel_cache();
/**
* @brief Get kernel truncation value in pixels.
*
* @return (uint): Kernel truncation value.
*/
uint get_trunc_conv_support() const
{
return truncated_wpconv_support;
}
// Upsampled convolution kernel
arma::Mat<cx_real_t> conv_kernel;
private:
/**
* @brief Auxiliary function to combine w_kernel and aa_img_domain_kernel values
*/
inline cx_real_t combine_2d_kernel_value(const arma::Col<real_t>& aa_kernel_img,
const size_t pixel_x, const size_t pixel_y, const real_t w_value, const real_t scaled_cell_size, const uint ctr_idx);
/**
* @brief Generate kernel diagonal radius points for interpolation.
*
* @param[in] arrsize (size_t): Kernel size.
*/
arma::Col<real_t> generate_hankel_radius_points(size_t arrsize);
/**
* @brief Compute Hankel transformation matrix.
*
* @param[in] arrsize (size_t): Hankel transform size.
*/
arma::Mat<real_t> dht(size_t arrsize); // Generate DHT Matrix
/**
* @brief Perform radial kernel interpolation in kernel half quadrant given the radius function values and radius points.
*
* @param[in] x_array (arma::Col): Radius points.
* @param[in] y_array (arma::Col): Radius function values.
* @param[in] trunc_at (real_t): Truncation percentage.
* @return (arma::Col): Interpolation values at kernel half quadrant
*/
template <bool isCubic, bool isDiagonal = false>
arma::Col<cx_real_t> RadialInterpolate(const arma::Col<real_t>& x_array, const arma::Col<cx_real_t>& y_array, real_t trunc_at)
{
assert(x_array.n_elem <= y_array.n_elem);
tk::spline<isCubic> m_spline_real;
tk::spline<isCubic> m_spline_imag;
if (trunc_at > real_t(0.0)) {
//truncate kernel at a certain percentage from maximum
real_t min_value = std::abs(y_array[0]) * trunc_at;
uint trunc_idx = wp.max_wpconv_support * oversampling;
real_t scale = real_t(1.0) / real_t(oversampling);
if (isDiagonal == true) {
scale = real_t(M_SQRT2) / real_t(oversampling * 2);
}
while (trunc_idx > oversampling) {
if (std::abs(y_array[trunc_idx]) > min_value) {
break;
}
trunc_idx -= oversampling;
}
truncated_wpconv_support = std::min(uint((std::ceil(real_t(trunc_idx) * scale))), wp.max_wpconv_support);
}
current_hankel_kernel_size = (truncated_wpconv_support * 2 + 1 + 1) * oversampling;
const size_t kernel_offset = current_hankel_kernel_size / 2;
const size_t final_kernel_size = kernel_offset + (kernel_offset * (kernel_offset - 1) / 2);
arma::Col<cx_real_t> tmp_kernel_half_quandrant(final_kernel_size);
// Extract real and imaginary parts
size_t n_elems = y_array.n_elem;
arma::Col<real_t> y_array_real(n_elems);
arma::Col<real_t> y_array_imag(n_elems);
for (size_t i = 0; i < n_elems; i++) {
y_array_real(i) = reinterpret_cast<const real_t(&)[2]>(y_array(i))[0];
y_array_imag(i) = reinterpret_cast<const real_t(&)[2]>(y_array(i))[1];
}
m_spline_real.set_points(x_array, y_array_real, false);
m_spline_imag.set_points(x_array, y_array_imag, false);
real_t new_x;
size_t k;
size_t ii = 0, j = 0;
for (size_t i = 0; i < final_kernel_size; i++, j++) {
if (j == kernel_offset) {
j = ++ii;
}
if (j == 0)
new_x = ii;
else if (ii == 0)
new_x = j;
else
new_x = std::sqrt(static_cast<real_t>(ii * ii + j * j));
// find where the interpolation is going to happen
if (isDiagonal == true) {
k = size_t(new_x * real_t(M_SQRT2));
// numeric imprecision due to the M_SQRT1_2 division don't allow this next step to be skipped
// the speed gain will still be enourmous in comparison with the previous algorithm (that searched the whole array)
if (new_x < x_array(k)) {
if (k > 0)
k--;
}
} else {
k = size_t(new_x);
if (k >= x_array.n_elem)
k = x_array.n_elem - 1;
}
/* kernel_half_quandrant is an array that stores all the interpolated values of half a quadrant of the final kernel
* in the following index order:
* .......
* .......
* .......
* ...0123
* ....456
* .....78
* ......9
*/
real_t val_re = m_spline_real(new_x, k, x_array[k], y_array_real[k]);
real_t val_im = m_spline_imag(new_x, k, x_array[k], y_array_imag[k]);
assert(arma::is_finite(val_re));
assert(arma::is_finite(val_im));
tmp_kernel_half_quandrant[i] = cx_real_t(val_re, val_im);
}
return tmp_kernel_half_quandrant;
}
uint max_hankel_kernel_size;
uint current_hankel_kernel_size;
uint truncated_wpconv_support;
real_t w_value;
uint array_size;
uint kernel_size;
real_t cell_size;
uint oversampling;
double scaling_factor;
W_ProjectionPars wp;
FFTRoutine r_fft;
MatStp<cx_real_t> comb_kernel;
arma::Col<cx_real_t> kernel_half_quandrant;
arma::Mat<real_t> DHT;
arma::Col<real_t> hankel_radius_points;
};
/**
* @brief Compute parallatic angle for beam rotation.
*
* @param[in] ha (real_t): Hour angle of the object, in decimal hours (0,24)
* @param[in] dec_rad (real_t): Declination of the object, in radians
* @param[in] ra_rad (real_t): Right Ascension of the object, in radians
* @return (real_t): Parallactic angle in radians
*/
real_t parangle(real_t ha, real_t dec_rad, real_t ra_rad);
}
#endif /* AW_PROJECTION_H */
| true |
7d019ed7f81f05db2083bbe3cb737c8373da5c65 | C++ | saberhosneydev/cpp | /FinalExam/src/mathoperators.cpp | UTF-8 | 404 | 3.5 | 4 | [] | no_license | #include <iostream>
#include <math.h>
using namespace std;
int main(){
cout << "Enter a number : ";
int N;
cin >> N;
cout << "N after adding " << (N+=2) << endl;
cout << "N after subtract " << (N -= 2) << endl;
cout << "N after dividing " << (N /= 2) << endl;
cout << "N after multiplying " << (N *= 2) << endl;
cout << "N after mod " << (N%=2) << endl;
return 0;
}
| true |
54e4712056f6bff92845cf8ef31ec56de09eeb53 | C++ | thisisziihee/algorithm | /inflearn/35_specialsort(구글).cpp | UHC | 1,161 | 3.453125 | 3 | [] | no_license | /*
N ԷµǸ Էµ ؾ Ѵ. ʿ ʿ ־ Ѵ. Ѵ.
Է¼ : ù ° ٿ N(5<=N<=100) ־, ٺ ־. 0 Էµ ʴ´.
¼ : ĵ Ѵ.
*/
#include<stdio.h>
int main() {
int n, num[101], i, j, minustemp, temp;
scanf("%d", &n);
for (i = 0; i < n; i++) {
scanf("%d", &num[i]);
}
// 1
/*int minusIdx = 0;
for (i = 0; i < n; i++) {
if (num[i] < 0) {
minustemp = num[i];
for (j = i-1; j >= minusIdx; j--) {
temp = j+1;
num[temp] = num[j];
}
num[minusIdx] = minustemp;
minusIdx++;
}
}*/
// 2
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i - 1; j++) {
if (num[j] > 0 && num[j + 1] < 0) {
temp = num[j];
num[j] = num[j + 1];
num[j + 1] = temp;
}
}
}
for (i = 0; i < n; i++) {
printf("%d ", num[i]);
}
} | true |
c0dd83a22220254cd466bd612f34f8689fe78f86 | C++ | shivanshcoder/Notes-code | /Code/Problem1_1.cpp | UTF-8 | 369 | 3.40625 | 3 | [] | no_license | #include<iostream>
using namespace std;
/* Lets take example as 3 + 4*/
#define squared(x) x*x //becomes 3+4*3+4
#define squared2(x) (x)*(x) //becomes (3+4) * (3+4)
#define squared3(x) (x*x) //becomes (3+4*3+4)
#define squared4(x) ((x)*(x)) //becomes ((3+4)*(3+4))
void main() {
int ans = 18 / squared(3 + 4);
cout << ans<< endl;
// system("pause");
} | true |
543937a6465072491ad4d4bb0a80fe1e43de34f6 | C++ | aaronschraner/VendMachine | /chardefs.ino | UTF-8 | 965 | 2.78125 | 3 | [] | no_license | #include "chardefs.h"
uint16_t sevsegTo14seg(uint8_t sevseg, uint8_t digit)
{
uint16_t temp=sevseg;
return digit ?
(((temp << 7)&0x3F00) | ((temp&0x01)<<6)):
((temp << 14) | (temp >> 2));
}
uint8_t charTo7seg(char c)
{
if(c >= '0' && c <= '9')
return SEVSEG_NUMS[c-'0'];
if(c >= 'A' && c <= 'F')
return SEVSEG_NUMS[c-'A'+10];
switch(c)
{
case ' ': return 0;
default: return 0b0001000;
}
}
uint16_t charTo14seg(char input)
{
if (input <= 'Z' && input >= 'A')
return lcLetters[input - 'A'];
else if (input >= '0' && input <= '9')
return anums[input - '0'];
else if (input >= 'a' && input <= 'z')
return lcLetters[32 + input - 'a'];
else //specific cases
{
switch (input)
{
case '_': return 0x8000 >> 7;
case '-': return 0x4000;
case ' ': return 0;
case '#': return 0b1111101000001011;
case '.': return 0x8000 >> 6;
}
}
return 0b0100111000001110;
}
| true |
b23c0e68cdc07ca0548b3d509896135232212666 | C++ | skononov/tiff2root | /tiff2root.cc | UTF-8 | 3,098 | 2.84375 | 3 | [] | no_license | #include <iostream>
#include <iomanip>
#include <cstdlib>
#include "TH2F.h"
#include "TString.h"
extern "C" {
#include "tiffio.h"
}
using std::endl;
using std::cout;
using std::cerr;
static const char * progname = "tiff2root";
static void Usage(int status=0)
{
cout << "Usage: " << progname << " file.tif [file.root]\n"
<< "\nConvert a TIFF file written by the RayCi software to\na ROOT 2D histogram (TH2F) and write it to ROOT file.\n";
exit(status);
}
int main(int argc, char* argv[])
{
uint32 imageWidth=0, imageLength=0;
uint32 config=0, nsamples=0, nbits=0;
uint64 scanLineSize=0;
tdata_t buf=0;
float *data=0;
progname = argv[0];
if (argc < 2) Usage();
const char* filename = argv[1];
const char* outfilename = 0;
if(argc>2) outfilename = argv[2];
//Open TIFF file
TIFF* tif = TIFFOpen(filename, "r");
if (!tif) {
cerr << progname << ": Can not open TIFF file " << filename << endl;
return 1;
}
cout << "File " << filename << " successfully opened" << endl;
//Skip to the second IFD/frame
if (!TIFFReadDirectory(tif)) {
cerr << progname << ": No second IFD" << endl;
return 2;
}
//Get frame properties
TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &imageWidth);
TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &imageLength);
TIFFGetField(tif, TIFFTAG_SAMPLESPERPIXEL, &nsamples);
TIFFGetField(tif, TIFFTAG_PLANARCONFIG, &config);
TIFFGetField(tif, TIFFTAG_BITSPERSAMPLE, &nbits);
scanLineSize = TIFFScanlineSize(tif);
cout << "Image width: " << imageWidth << "\n"
<< "Image length: " << imageLength << "\n"
<< "Planar configuration: " << config << "\n"
<< "Scan line size: " << scanLineSize << "\n"
<< "Samples per pixel: " << nsamples << "\n"
<< "Bits per sample: " << nbits << endl;
//Check number if samples
if (nsamples != 1) {
cerr << progname << ": number of samples per pixel (" << nsamples << ") is not 1" << endl;
return 10;
}
//Check scan line size
if (scanLineSize != nbits/8*imageWidth) {
cerr << progname << ": scan line size " << scanLineSize
<< " is not equal to bytes-per-sample times image width " << nbits/8*imageWidth << endl;
return 11;
}
//Allocate buffer memmory
buf = _TIFFmalloc(scanLineSize);
data = (float*)buf;
//Create 2D histogram to plot frame data
TH2F* himg = new TH2F("himg",filename,imageWidth,0.,1.*imageWidth,imageLength,0.,1.*imageLength);
//Read frame data
cout << "Reading TIFF frame data..." << endl;
for (uint32 row = 0; row < imageLength; row++) {
TIFFReadScanline(tif, buf, row, 0);
for(uint32 col = 0; col < imageWidth; col++)
himg->SetBinContent(col+1,row+1,data[col]);
}
_TIFFfree(buf);
TIFFClose(tif);
TString rootFilename;
if (outfilename)
rootFilename = outfilename;
else
rootFilename = filename;
rootFilename.ReplaceAll("#","N");
rootFilename.ReplaceAll(".tif",".root");
if (rootFilename==filename)
rootFilename += ".root";
himg->SaveAs(rootFilename);
cout << "TH2F histogram written to " << rootFilename << endl;
return 0;
}
| true |
c4953972d214dbd491acdf7e89470bca68261ea5 | C++ | nikzsaz/HackerRank | /TheLongestCommonSubsequence.cpp | UTF-8 | 1,020 | 2.859375 | 3 | [] | no_license | #include <iostream>
using namespace std;
int max(int a,int b){
return a>b?a:b;
}
void LCS(int s[],int s1[]){
}
int main() {
// here is the dp implementation of the LCS
int arr[101];
int arr1[101];
int n,m;
cin>>n>>m;
for(int i=0;i<n;i++){
cin>>arr[i];
}
for(int i=0;i<m;i++){
cin>>arr1[i];
}
int l=n;
int DP[l+1][m+1];
for(int i=0;i<=l;i++){
for(int j=0;j<=m;j++){
if(i==0||j==0){
DP[i][j]=0;
}else if(arr[i-1]==arr1[j-1]){
DP[i][j]=DP[i-1][j-1]+1;
}else{
DP[i][j]=max(DP[i-1][j],DP[i][j-1]);
}
}
}
int val[101];
int count=0;
int i=l;
int j=m;
while(i>0 && j>0){
if(arr[i-1]==arr1[j-1]){
val[count++]=arr[i-1];
i--;
j--;
}else if(DP[i-1][j]>DP[i][j-1]){
i--;
}else{
j--;
}
}
for(int i=count-1;i>=0;i--){
cout<<val[i]<<" ";
}
return 0;
}
| true |
2c441aee29b1222821efbb6e6cb100d5da3ff9ab | C++ | Sam071100/CPlusPlus-OOPS | /Tutorial29.cpp | UTF-8 | 547 | 3.765625 | 4 | [] | no_license | #include <iostream>
using namespace std;
class complex
{
int a,b;
public:
// Creating a default constructor.
complex();// Constructor Declaration
void printNumber()
{
cout <<"Your number is "<<a<<" + "<<b<<"i"<<endl;
}
};
complex ::complex() // Constructor definition this is a Default Constructor as it accepts no parameter.
{
a=10;
b=0;
cout <<"Checking the Constructor\n";
}
int main()
{
complex c1, c2, c3;
c1.printNumber();
c2.printNumber();
c3.printNumber();
return 0;
}
| true |
29b0effd3826f2663a420d3ab4ab8854c3115647 | C++ | smarchevsky/VisualEngine | /include/mesh.h | UTF-8 | 1,888 | 2.875 | 3 | [
"MIT"
] | permissive | #ifndef MESH_H
#define MESH_H
#include <initializer_list>
#include <memory>
#include <set>
#include <vector>
#include <glm/glm.hpp>
namespace Visual {
class MeshData;
typedef unsigned int GLuint;
typedef int GLsizei;
class Mesh {
public:
struct OBB { // object's bounding box
OBB() : min(FLT_MAX), max(-FLT_MAX) { center = glm::vec3(0), scale = glm::vec3(1); }
OBB(glm::vec3 _min, glm::vec3 _max) : min(_min), max(_max) { process(); }
void coverPoint(const glm::vec3 &v) { min = glm::min(v, min), max = glm::max(v, max); }
void process() { center = (min + max) * 0.5f, scale = (max - min) * 0.5f; }
glm::vec3 min;
glm::vec3 max;
glm::vec3 center;
glm::vec3 scale;
};
enum class Attribute { Vertex, // attributes of mesh
Normal,
TexCoord,
Binormal,
Color };
typedef std::set<Attribute> AttributeParams;
struct LODIndices {
size_t m_offset = 0;
size_t m_count = 0;
};
Mesh(Mesh &&rhc);
Mesh(const MeshData &data);
Mesh(const std::vector<MeshData> &data);
Mesh(const std::initializer_list<MeshData> &data);
Mesh(const Mesh &rhc) = delete;
Mesh &operator=(const Mesh &rhc) = delete;
~Mesh();
void bindAndDraw(size_t lodLevel = 0) const;
void bind() const;
void draw(size_t lodLevel = 0) const;
size_t getLodCount() const { return m_lodIndices.size(); };
const OBB &getOBB() const { return m_obb; }
private:
OBB m_obb;
std::vector<LODIndices> m_lodIndices;
GLuint m_VAO = 0, m_VBO = 0, m_EBO = 0;
};
class MeshPrimitive {
public:
static const Mesh &quad();
static const std::shared_ptr<Mesh> &cube();
static const std::shared_ptr<Mesh> &lodSphere();
};
} // namespace Visual
#endif // MESH_H
| true |
839d76898080609162aeea2260868d6b0293fae4 | C++ | tinglai/Algorithm-Practice | /LeetCode/Wildcard Mathcing/main.cpp | UTF-8 | 6,448 | 3.296875 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <cstring>
using namespace std;
/*
class Solution{
// there are several ways to solve this problem
// 1. To use DP works, it will either use a double vector (O(M * N) in space)
// where M is the length of s and N is the length of p
// or will run a double loop (O(MN) in time) but use one vector
//
// 2. KMP algorithm
// the problem is equivalent to match substring in p, separated by '*', with
// the string in s. For each matching, we can use KMP algorithm. This will use
// O(N) space for the partial separate table
public:
bool isMatch(const char *s, const char *p){
// the main idea of this problem is as follows
// denote f(i, j) as if if s[0:i] match p[0:j]
// when p[j] != '*', f(i, j) = f(i - 1, j - 1) && (p[j] == '?' || p[j] == s[j])
// when p[j] == '*', f(i, j) = f(i, j - 1) || f(i - 1, j)
// f(i, j - 1) is the case that p[j] = '*' means nothing (empty char)
// I simply check f(i - 1, j) here instead of checking all f(m, j) when m is belong [0, i - 1]
// because if f(i - 1, j) returns true, it means that some string
int sizeP = 0, sizeS = 0;
for(const char* i = s; *i != '\0'; i++){
sizeS++;
}
for(const char* i = p; *i != '\0'; i++){
if(*i == '*' && *(i + 1) == '*') continue;
sizeP++;
}
vector<bool> memo(sizeS + 1, false);
memo[0] = true;
vector<bool> temp(memo); // temp is the original memo
for(int i = 0; i < sizeP; i++){
// when i == i', memo[j - 1] means if substring of s[0:j - 1] match
// the subpattern of p[0:i],
// so to initialize, (when i == -1), means that the subpattern
// doesn't have anything there, we make all the memo to be false
// since there is no pattern to match
// memo[0] = true is a tool set up for corner case s[0:0]
for(int j = 1; j <= sizeS; j++){
if(p[i] == '*'){
memo[j] = temp[j] || memo[j - 1];
temp[j] = memo[j];
}
else{
memo[j] = temp[j - 1] && (p[i] == '?' || p[i] == s[j]);
temp[j] = memo[j];
}
}
}
return memo.back();
}
};
class Solution {
public:
bool isMatch(const char* s, const char* p){
const char* pStar=nullptr; // the most recent '*' position of p
const char* sMis=nullptr; // the most recent mismatch position of s
while(*s!='\0'){
if((*s==*p) || (*p=='?')){
s++;
p++;
}
else if(*p=='*'){
pStar=p;
p++; // then try to treat p as match no chars in s
sMis=s; // the mismatch position for s
}
else if(*pStar!='\0'){
p=pStar+1;
s=++sMis; // mismatch position matched by *p='*', most recent mismatch position go by 1
}
else return false;
}
while(*p=='*')p++;
return (*p=='\0');
}
};
*/
class Solution {
public:
bool isMatch(const char* s, const char* p){
// main idea:
// before '*' appears, everything is trivial
// just move forward the pointer s and p
// after '*' shows up,
// I separate the pattern p into some subpatterns, spaced by '*'
// for those subpatterns between '*', to check if s fit the
// first subpattern is equvalent to check if
// that subpattern exist in s
// because '*' can be any char including empty char
// I then find the first substring of s
// that satisfies the first subpattern, update s and go on
// searching for the following subpatterns until the
// last subpattern (here I used KMP algorithm which is
// not quite necessary, I just wanted to have a practice to
// impletment that algorithm)
// At that time I know that the searched substring s
// fits the searched subpattern of p and if I move forward
// pointer s, the fitting still holds (because of *)
// what I want is to make s and p go to '\0' together at the
// same time. For that purpose, I need to keep moving forward
// s and check if s exactly fit the last subpattern of p
// and after that, the problem is solved
// I'm not very sure about the time complexity
// but the KMP algorithm take nearly O(N + M) where N and M
// are the length of s and p correspondingly
// and the last step searching should be O(N + M) so I guess
// the time complexity should be O(N + M)
// the space complexity is O(1)
const char* lastS = nullptr;
const char* lastP = nullptr;
bool star = false;
while(*s != '\0'){
if(!star){
if(*p == '?' || *p == *s){
p++;
s++;
}
else if(*p == '*'){
star = true;
while(*p == '*') p++;
if(*p == '\0') return true;
lastS = s;
lastP = p;
}
else return false;
}
else{
if(*p == '*'){
while(*p == '*') p++;
if(*p == '\0') return true;
lastS = s;
lastP = p;
}
else if(*p == '?'){
s++;
p++;
}
else if(*p != '\0'){
int n = 0;
const char* itr = p;
while(*itr != '\0' && *itr != '*' && *itr != '?'){
itr++;
n++;
}
if(!help(s, p, n)) return false;
s += n;
p += n;
}
else{
if(*lastP != '\0'){
lastS++;
s = lastS;
p = lastP;
}
else return false;
}
}
}
while(*p == '*') p++;
return *p == '\0';
}
bool help(const char*& s, const char*& p, int n){
// KMP algorithm
vector<int> table(n, 0);
buildPartialSeparationTable(p, n, table);
int idx = 0;// number of chars that match
while(1){
if(idx == n) return true;
if(*(s + idx) == '\0') return false;
if(*(s + idx) == *(p + idx)){
idx++;
}
else{
if(idx == 0) s++;
else{
s += idx - table[idx - 1];
idx = 0;
}
}
}
}
void buildPartialSeparationTable(const char* p, int n, vector<int>& table){
// a help function for KMP algorithm
table.resize(n);
int longgestPre = 0;
for(int i = 1; i < n; i++){
while(longgestPre > 0 && p[longgestPre] != p[i]){
longgestPre = table[longgestPre - 1];
}
if(p[longgestPre] == p[i]){
table[i] = table[i - 1] + 1;
longgestPre = table[i];
}
else table[i] = 0;
}
}
};
int main(){
//const char* s = "abefcdgiescdfimde";
const char* s = "hi";
//const char* s = "baababbaaaaabbababbbbbabaabaabaaabbaabbbbbbaabbbaaabbabbaabaaaaabaabbbaabbabababaaababbaaabaababbabaababbaababaabbbaaaaabbabbabababbbbaaaaaabaabbbbaababbbaabbaabbbbbbbbabbbabababbabababaaababbaaababaabb";
//const char* p = "ab*cd?i*de";
const char* p = "*?";
//const char* p = "*ba***b***a*ab**b***bb*b***ab**aa***baba*b***bb**a*abbb*aa*b**baba**aa**b*b*a****aabbbabba*b*abaaa*aa**b";
Solution soln;
bool result = soln.isMatch(s, p);
if(result) cout << "yes" << endl;
else cout << "no" << endl;
}
| true |
c8bafe4b0cbc032718e7ea238aec8f26f4d09ca1 | C++ | aaronmaynard/CPlusPlus | /CS 1337 - Computer Science I (C++)/Chapter 3/Average Rainfall/Main.cpp | UTF-8 | 1,164 | 4.25 | 4 | [] | no_license | /*
Write a program that calculates the average rainfall for three months. The program
should ask the user to enter the name of each month, such as June or July, and the
amount of rain (in inches) that fell each month. The program should display a
message similar to the following:
The average rainfall for June, July, and August is 6.72 inches.
Author: Aaron Maynard
*/
#include<iostream>
#include<iomanip>
#include<string>
using namespace std;
int main()
{
string month1, month2, month3;
double rain1, rain2, rain3;
double average;
cout << "Enter the name of the month: ";
cin >> month1;
cout << "Enter the rainfall (in inches): ";
cin >> rain1;
cout << "Enter the name of the month: ";
cin >> month2;
cout << "Enter the rainfall (in inches): ";
cin >> rain2;
cout << "Enter the name of the month: ";
cin >> month3;
cout << "Enter the rainfall (in inches): ";
cin >> rain3;
average = (rain1 + rain2 + rain3) / 3;
cout << setprecision(2) << fixed;
cout << "The average rainfall for " << month1 << ", " << month2 << ", and " << month3 << " is: " << average << endl << endl;
return 0;
}
| true |
90f78eb1f663b106ccecbab2a3f3f21e3eb84f46 | C++ | ucam-comparch-loki/lokisim | /src/Tile/Tile.h | UTF-8 | 3,978 | 2.59375 | 3 | [
"MIT"
] | permissive | /*
* Tile.h
*
* Base class for all types of tile on the Loki chip.
*
* Exposes an interface to each of the global networks on chip. There are no
* routers in the Tile component, however; this is left to the global networks.
*
* All tiles must have the same interface, but particular networks may be unused
* on particular tiles.
*
* Created on: 4 Oct 2016
* Author: db434
*/
#ifndef SRC_TILE_TILE_H_
#define SRC_TILE_TILE_H_
#include <vector>
#include "../LokiComponent.h"
#include "../Network/Interface.h"
#include "../Network/NetworkTypes.h"
using sc_core::sc_module_name;
using std::vector;
class Chip;
class DataBlock;
class Tile: public LokiComponent {
//============================================================================//
// Ports
//============================================================================//
public:
ClockInput clock;
// All ports are sinks of one network or another. The input ports are sinks or
// the global network, and the outgoing ports are sinks of the local network.
// Data network.
sc_port<network_sink_ifc<Word>> iData;
sc_port<network_sink_ifc<Word>> oData;
// Credit network.
sc_port<network_sink_ifc<Word>> iCredit;
sc_port<network_sink_ifc<Word>> oCredit;
// Memory request network.
sc_port<network_sink_ifc<Word>> iRequest;
sc_port<network_sink_ifc<Word>> oRequest;
// Memory response network.
sc_port<network_sink_ifc<Word>> iResponse;
sc_port<network_sink_ifc<Word>> oResponse;
//============================================================================//
// Constructors and destructors
//============================================================================//
public:
Tile(const sc_module_name& name, const TileID id);
virtual ~Tile();
//============================================================================//
// Methods
//============================================================================//
public:
virtual uint numComponents() const;
virtual uint numCores() const;
virtual uint numMemories() const;
// Get information about the given Identifiers based on the configuration of
// the Tile.
virtual bool isCore(ComponentID id) const;
virtual bool isMemory(ComponentID id) const;
virtual uint componentIndex(ComponentID id) const;
virtual uint coreIndex(ComponentID id) const;
virtual uint memoryIndex(ComponentID id) const;
bool isComputeTile(TileID id) const;
// Store the given instructions or data into the component at the given index.
virtual void storeInstructions(vector<Word>& instructions, const ComponentID& component);
virtual void storeData(const DataBlock& data);
// Dump the contents of a component to stdout.
virtual void print(const ComponentID& component, MemoryAddr start, MemoryAddr end);
// Debug access methods which bypass all networks and have zero latency.
virtual Word readWordInternal(const ComponentID& component, MemoryAddr addr);
virtual Word readByteInternal(const ComponentID& component, MemoryAddr addr);
virtual void writeWordInternal(const ComponentID& component, MemoryAddr addr, Word data);
virtual void writeByteInternal(const ComponentID& component, MemoryAddr addr, Word data);
virtual int readRegisterInternal(const ComponentID& component, RegisterIndex reg) const;
virtual bool readPredicateInternal(const ComponentID& component) const;
virtual void networkSendDataInternal(const NetworkData& flit);
virtual void networkSendCreditInternal(const NetworkCredit& flit);
virtual void magicMemoryAccess(MemoryOpcode opcode, MemoryAddr address, ChannelID returnChannel, Word payload = 0);
protected:
// Return a pointer to the chip to which this tile belongs.
Chip& chip() const;
//============================================================================//
// Local state
//============================================================================//
public:
TileID id;
};
#endif /* SRC_TILE_TILE_H_ */
| true |
eaf3a7295d07c3306de9ea28202a58c15294b95a | C++ | jbendtsen/muscles | /Muscles/font.cpp | UTF-8 | 5,956 | 2.546875 | 3 | [] | no_license | #include <ft2build.h>
#include FT_FREETYPE_H
#include FT_BITMAP_H
#include "muscles.h"
#define FLOAT_FROM_16_16(n) ((float)((n) >> 16) + (float)((n) & 0xffff) / 65536.0)
FT_Library library = nullptr;
Font_Face load_font_face(const char *path) {
if (!library) {
if (FT_Init_FreeType(&library) != 0) {
fprintf(stderr, "Failed to load freetype\n");
return nullptr;
}
}
FT_Face face;
if (FT_New_Face(library, path, 0, &face) != 0) {
fprintf(stderr, "Error loading font \"%s\"\n", path);
return nullptr;
}
return (FT_Face)face;
}
int next_pow2(int x) {
x--;
int n = 2;
while (x >>= 1)
n <<= 1;
return n;
}
void make_font_render(FT_Face face, float size, RGBA& color, int dpi_w, int dpi_h, Font_Render& render) {
sdl_destroy_texture(&render.tex);
float req_size = size * 64.0;
int pts = (int)(req_size + 0.5);
render.pts = pts;
FT_Set_Char_Size(face, 0, render.pts, dpi_w, dpi_h);
float pt_w = (float)(render.pts * dpi_w) / (72.0 * 64.0);
float pt_h = (float)(render.pts * dpi_h) / (72.0 * 64.0);
float em_units = (float)face->units_per_EM;
int max_w = (int)(1.5 + pt_w * (float)face->max_advance_width / em_units);
int max_h = (int)(1.5 + pt_h * (float)face->max_advance_height / em_units);
if (max_w <= 0)
return;
int n_cols = 16;
int w = max_w * n_cols + 1;
int tex_w = next_pow2(w);
n_cols = tex_w / max_w;
int n_rows = (1 + (N_CHARS-1) / n_cols);
int h = max_h * n_rows + 1;
int tex_h = next_pow2(h);
Texture tex = sdl_create_texture(nullptr, tex_w, tex_h);
void *data = sdl_lock_texture(tex);
for (int c = MIN_CHAR; c <= MAX_CHAR; c++) {
FT_Load_Char(face, c, FT_LOAD_RENDER);
FT_Bitmap bmp = face->glyph->bitmap;
int left = face->glyph->bitmap_left;
int top = face->glyph->bitmap_top;
int idx = c - MIN_CHAR;
Glyph *gl = &render.glyphs[idx];
*gl = {
/*atlas_x*/ (idx % n_cols) * max_w,
/*atlas_y*/ (idx / n_cols) * max_h,
/*img_w*/ (int)bmp.width,
/*img_h*/ (int)bmp.rows,
/*box_w*/ (float)FLOAT_FROM_16_16(face->glyph->linearHoriAdvance),
/*box_h*/ (float)FLOAT_FROM_16_16(face->glyph->linearVertAdvance),
/*left*/ left,
/*top*/ top
};
int off = 0;
for (int i = 0; i < gl->img_h; i++) {
u32 *p = &((u32*)data)[((gl->atlas_y + i) * tex_w) + gl->atlas_x];
for (int j = 0; j < gl->img_w; j++, off++) {
float lum = (float)bmp.buffer[off];
*p++ =
((u32)(color.r * 255.0) << 24) |
((u32)(color.g * 255.0) << 16) |
((u32)(color.b * 255.0) << 8) |
(u32)(color.a * lum);
}
}
}
sdl_unlock_texture(tex);
render.tex = tex;
}
void destroy_font_face(Font_Face face) {
FT_Done_Face((FT_Face)face);
}
void ft_quit() {
FT_Done_FreeType(library);
}
void Font_Render::draw_text_simple(void *renderer, const char *text, float x, float y) {
Rect_Int src, dst;
y += text_height();
int len = strlen(text);
for (int i = 0; i < len; i++) {
if (text[i] < MIN_CHAR || text[i] > MAX_CHAR)
continue;
Glyph *gl = &glyphs[text[i] - MIN_CHAR];
src.x = gl->atlas_x;
src.y = gl->atlas_y;
src.w = gl->img_w;
src.h = gl->img_h;
dst.x = x + gl->left;
dst.y = y - gl->top;
dst.w = src.w;
dst.h = src.h;
sdl_apply_texture(tex, dst, &src, renderer);
x += gl->box_w;
}
}
void Font_Render::draw_text(void *renderer, const char *text, float x, float y, Render_Clip& clip, int tab_cols, bool multiline) {
bool clip_top = (clip.flags & CLIP_TOP) != 0;
bool clip_bottom = (clip.flags & CLIP_BOTTOM) != 0;
bool clip_left = (clip.flags & CLIP_LEFT) != 0;
bool clip_right = (clip.flags & CLIP_RIGHT) != 0;
if ((clip_right && x > clip.x_upper) || (clip_bottom && y > clip.y_upper))
return;
float x_start = x;
Rect_Int src, dst;
bool draw = true;
int col = 0;
int offset = 0;
int len = strlen(text);
float height = text_height();
y += height;
if (clip_top && y < clip.y_lower) {
for (offset = 0; offset < len && y < clip.y_lower; offset++) {
if (text[offset] == '\n')
y += height;
}
if (offset >= len)
return;
}
for (int i = offset; i < len; i++, col++) {
if (text[i] == '\t') {
int add = tab_cols - (col % tab_cols);
x += (float)add * glyph_for(' ')->box_w;
col += add - 1;
continue;
}
if (multiline && text[i] == '\n') {
x = x_start;
y += height;
col = -1;
draw = true;
continue;
}
if (!draw || text[i] < MIN_CHAR || text[i] > MAX_CHAR)
continue;
Glyph *gl = &glyphs[text[i] - MIN_CHAR];
float advance = gl->box_w;
src.x = gl->atlas_x;
src.y = gl->atlas_y;
src.w = gl->img_w;
src.h = gl->img_h;
float y_off = 0;
if (clip_left) {
if (x + gl->img_w < clip.x_lower) {
x += advance;
continue;
}
float delta = (float)x - clip.x_lower;
if (delta < 0) {
src.x = ((float)src.x - delta + 0.5);
src.w = ((float)src.w + delta + 0.5);
x -= delta;
advance += delta;
}
}
if (clip_bottom) {
if (y + gl->img_h < clip.y_lower) {
x += advance;
continue;
}
float delta = (float)y - gl->top - clip.y_lower;
if (delta < 0) {
src.y = ((float)src.y - delta + 0.5);
src.h = ((float)src.h + delta + 0.5);
y_off = -delta;
}
}
dst.x = x + gl->left;
dst.y = y + y_off - gl->top;
if (clip_right) {
int w = clip.x_upper - dst.x;
src.w = w < src.w ? w : src.w;
}
if (clip_bottom) {
int h = clip.y_upper - dst.y;
src.h = h < src.h ? h : src.h;
}
dst.w = src.w;
dst.h = src.h;
sdl_apply_texture(tex, dst, &src, renderer);
x += advance;
if (clip_right && x > clip.x_upper)
draw = false;
}
}
Font::Font(Font_Face f, float sz, RGBA& color, int dpi_w, int dpi_h) {
face = f;
size = sz;
this->color = color;
prev_scale = 1.0;
make_font_render((FT_Face)face, size, color, dpi_w, dpi_h, render);
}
void Font::adjust_scale(float scale, int dpi_w, int dpi_h) {
if (scale != prev_scale) {
make_font_render((FT_Face)face, size * scale, color, dpi_w, dpi_h, render);
prev_scale = scale;
}
}
| true |
1940951b160b479cdbde7d2d075be02976e3598e | C++ | hydrogen69/Probelm-solved | /CodeForces/535A/17605884_AC_31ms_16kB.cpp | UTF-8 | 592 | 2.984375 | 3 | [] | no_license |
#include<bits/stdc++.h>
using namespace std;
int main()
{
string str1[20]={ "zero","one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"};//0 to 19
string str2[8]={"twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"};
int a;
int temp;
cin>>a;
if(a<20)cout<<str1[a]<<endl;
else
{
temp=a/10;
cout<<str2[temp-2];
if(a%10!=0)
cout<<"-"<<str1[a%10];
cout<<endl;
}
}
| true |
4bf2f3c7941d8a99cab88cee3783739cfca00665 | C++ | algo-imp/algorithm-practice | /backtrack_subsets.cpp | UTF-8 | 1,467 | 3.453125 | 3 | [] | no_license | /*
* backtrack_subsets.cpp
* Reference: Chapter 7 - The Algorithm Design Manual
* Created on: May 12, 2014
* Author: vietnguyen
*/
#include <iostream>
using namespace std;
class Subset{
private:
int NMAX = 100;
int MAXCANDIDATES = 2;
bool finished = false; /* found all solution yet */
public:
void backtrack (int a[], int k, int input){
int c[MAXCANDIDATES]; /* candidate for next position */
int ncandidates; /* next position candidate count */
int i; /* counter */
if (is_a_solution(a,k,input)){
process_solution(a, k , input);
}else{
k = k + 1;
construct_candidates (a, k, input, c, &ncandidates);
for (i = 0; i< ncandidates; i++){
a[k] = c[i];
make_move(a,k,input);
backtrack(a,k,input);
unmake_move(a,k,input);
if(finished) return;
}
}
}
void make_move(int a[], int k, int n){
}
void unmake_move(int a[], int k, int n){
}
bool is_a_solution(int a[], int k, int n){
return (k==n); /* is k == n? */
}
void construct_candidates(int a[], int k, int n, int c[], int *ncandidates){
c[0] = true;
c[1] = false;
*ncandidates = 2;
}
void process_solution(int a[], int k, int n){
int i; /* counter */
cout << "{";
for (i = 1; i<=k; i++){
if (a[i] == true) cout << i ;
else cout << " ";
if(i < k) cout << ", ";
}
cout << "}\n";
}
void generate_subsets(int n){
int a[NMAX];
backtrack(a,0,n);
}
};
int main(){
Subset s;
s.generate_subsets(10);
}
| true |
5ffa398a3bd15766e629c9a70aee62ae51c897e4 | C++ | NekoSilverFox/CPP | /214 - 排序 - 基数排序(错)/214 - 排序 - 基数排序.cpp | GB18030 | 2,941 | 3.09375 | 3 | [
"Apache-2.0"
] | permissive | #include<iostream>
using namespace std;
template<typename T>
int GetArrayLength(T& arr)
{
return sizeof(arr) / sizeof(arr[0]);
}
template<typename T>
int PrintArray(T& arr)
{
int length_arr = GetArrayLength(arr);
cout << "length : " << length_arr << endl;
for (int i = 0; i < length_arr; i++)
{
cout << arr[i] << " ";
}
cout << endl;
return length_arr;
}
int GetMaxElemArray(int arr[], int length_arr)
{
int max_ele = arr[0];
for (int i = 0; i < length_arr; i++)
{
if (max_ele < arr[i]) max_ele = arr[i];
}
return max_ele;
}
int GetSortTime(int max_num)
{
int time_sort = 0;
while (max_num)
{
max_num /= 10;
time_sort++;
}
return time_sort;
}
void RadixSort(int arr[], const int length_arr, const int time_sort) // 4
{
int temp_arr[10]; //
int num_insert; //
int division_num_10 = 1; // Ե10
int i_insert_arrN2_backet = 0;
// how many backet need
int** arrN2_backet = new int* [time_sort];
for (int i = 0; i < time_sort; i++)
{
arrN2_backet[i] = new int[10];
}
// make the all the number in the arrN2_backet to 0
for (int i = 0; i < time_sort; i++)
{
for (int j = 0; j < 10; j++) arrN2_backet[i][j] = 0;
}
// put the arr[] number in the arrN2_backet
for (int time = 0; time < time_sort; time++)
{
for (int i = 0; i < 10; i++) temp_arr[i] = 0; //ȫΪ 0
// ȡǰλϵֵ
for (int i = 0; i < length_arr; i++)
{
num_insert = arr[i];
num_insert = num_insert / division_num_10 % 10;
cout << num_insert << " ";
temp_arr[num_insert]++;
}
cout << endl;
for (int i = 0; i < 10; i++)
{
int subscript = 0; // ±
if (temp_arr[i] != 0)
{
for (int j = 0; j < temp_arr[i]; j++, subscript++)
{
//arr_need[subscript] = arr_need[subscript] + i * division_num_10;
arrN2_backet[i_insert_arrN2_backet][subscript] = i;
}
}
}
division_num_10 *= 10;
}
for (int i = 0; i < length_arr; i++) arr[i] = 0;
division_num_10 = 1;
int i_insert = 0, i = 0, j = 0;
int subscript = i_insert;
for (int i_insert = 0; i_insert < length_arr; i_insert++)
{
if (arrN2_backet[i][j] != 0)
{
// arr[i_insert] = arr[i_insert] + j
for (int k = 0; k < arrN2_backet[i][j]; k++, subscript++) arr[i_insert] = arr[i_insert] + j * division_num_10;
}
j++;
subscript = i_insert;
if (10 == j)
{
j = 0;
i++;
division_num_10 *= 10;
}
}
/*
for (int i_insert = 0; i < length_arr; i_insert++)
{
for (int i = 0; i < time_sort; i++)
{
for (int j = 0; j < 10; j++)
{
}
}
arr[i] =
}
*/
}
int main()
{
int arr[] = { 1244, 4576, 3634, 1111, 7656, 7767,3343, 8878, 9869, 1480, 3800,5790, 5769 };
int length_arr = GetArrayLength(arr);
int max_num = GetMaxElemArray(arr, length_arr);
int time_sort = GetSortTime(max_num);
PrintArray(arr);
RadixSort(arr, length_arr, time_sort);
PrintArray(arr);
} | true |
1af0f187d9e741645d668983a40f21d651930b3e | C++ | iiyiyi/solution-book-till-2020 | /Number Theory/欧拉函数欧拉表/BZOJ2818.cpp | UTF-8 | 746 | 2.515625 | 3 | [] | no_license | #include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int MAXN=10000000+50;
typedef long long ll;
int n;
int prime[MAXN],pnum=0;
int phi[MAXN];
ll sum[MAXN];
void get_phi(int maxn)
{
memset(phi,0,sizeof(phi));
memset(sum,0,sizeof(sum));
phi[1]=sum[1]=1;
for (int i=2;i<=maxn;i++)
{
if (phi[i]==0)
{
prime[++pnum]=i;
phi[i]=i-1;
}
for (int j=1;j<=pnum;j++)
{
if (i*prime[j]>maxn) break;
if (i%prime[j]==0) phi[i*prime[j]]=phi[i]*prime[j];
else phi[i*prime[j]]=phi[i]*(prime[j]-1);
}
sum[i]=sum[i-1]+phi[i];
}
}
int main()
{
scanf("%d",&n);
get_phi(n);
ll ans=0;
for (int i=1;i<=pnum;i++)
{
ans+=sum[n/prime[i]]*2-1;
}
printf("%lld",ans);
return 0;
}
| true |
1f933bc8b820df54a205e1f96f420adffac36b4f | C++ | learnin-tap/LeetCode_practice | /daily/C++版本/26. 删除排序数组中的重复项.cpp | GB18030 | 325 | 2.96875 | 3 | [] | no_license | class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int sum=0;
nums.push_back(-9999); //Ϊԭһܼӵsumȥ
for(int i=1;i<nums.size();i++)
if(nums[i]!=nums[i-1])
nums[sum++]=nums[i-1];
return sum;
}
};
| true |
98db1fd550852f6bab7796967276fc20a0152d7c | C++ | alaneos777/club | /project euler/776.cpp | UTF-8 | 1,463 | 2.53125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
using lli = __int128_t;
using ld = long double;
const vector<int> digits = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
const int LEN = digits.size();
lli mem_f[20][200][2][200];
lli mem_g[20][200][2][200];
vector<lli> ten(LEN+1);
lli f(int pos, int sum, bool canUseAll, int target){
if(pos == LEN) return sum == target;
lli& ans = mem_f[pos][sum][canUseAll][target];
if(ans != -1) return ans;
ans = 0;
int limit = canUseAll ? 9 : digits[pos];
for(int d = 0; d <= limit; ++d){
if(sum + d > target) break;
ans += f(pos+1, sum+d, canUseAll | (d < digits[pos]), target);
}
return ans;
}
lli g(int pos, int sum, bool canUseAll, int target){
if(pos == LEN) return 0;
lli& ans = mem_g[pos][sum][canUseAll][target];
if(ans != -1) return ans;
ans = 0;
int limit = canUseAll ? 9 : digits[pos];
for(int d = 0; d <= limit; ++d){
if(sum + d > target) break;
ans += d*ten[LEN-1-pos]*f(pos+1, sum+d, canUseAll | (d < digits[pos]), target) + g(pos+1, sum+d, canUseAll | (d < digits[pos]), target);
}
return ans;
}
int main(){
memset(mem_f, -1, sizeof(mem_f));
memset(mem_g, -1, sizeof(mem_g));
ten[0] = 1;
for(int i = 1; i <= LEN; ++i){
ten[i] = 10 * ten[i-1];
}
ld ans = 0;
for(int i = 1; i <= 9*LEN; ++i){
ans += g(0, 0, false, i) / ld(i);
}
int digits = (int)log10l(ans);
cout << fixed << setprecision(12) << ans/powl(10, digits) << "e" << digits << "\n";
return 0;
} | true |
15fbf06f15171417f17f9e1e9fd69ea2b84a738a | C++ | hdsmtiger/Solution4LeetCode | /Distinct Subsequences.cpp | UTF-8 | 943 | 2.734375 | 3 | [] | no_license | class Solution {
public:
int numDistinct(string S, string T) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int lengthS = S.size();
int lengthT = T.size();
if(lengthS < lengthT)
return 0;
int indexS =0, indexT = 0;
long long* lastcount = new long long[lengthS+1];
long long* curcount = new long long[lengthS+1];
lastcount[lengthS] = 0;
curcount[lengthS] = 0;
for(int i=lengthS - 1; i>=0; i--)
{
lastcount[i] = lastcount[i+1];
if(S.at(i) == T.at(lengthT-1))
lastcount[i]++;
curcount[i] = 0;
}
for(int i=2; i<=lengthT; i++)
{
curcount[lengthS - i + 1] = 0;
for(int j=lengthS-i; j>=0; j--)
{
curcount[j] = curcount[j+1];
if(T.at(lengthT - i) == S.at(j))
{
curcount[j] += lastcount[j+1];
}
}
long long* temp = curcount;
curcount = lastcount;
lastcount = temp;
}
return lastcount[0];
}
};
| true |
b1a636bb82765d9db20ee8cce6aa4b9ed6c56e3d | C++ | codecsp/SGPA_Calculator | /subjects.h | UTF-8 | 4,563 | 2.609375 | 3 | [] | no_license | #include<iostream>
#include<string>
using namespace std ;
#include"structHeader.h"
#include<string.h>
#include <sstream>
#include<fstream>
//#include"branch.h"
//#include"pointer.h"
fstream fi;
string lin;
int countsubject;/*typedef struct sub
{
char subname[50];
int credit;
}SUB;
*/
void getgrades()
{
cout<<"\n\n\n\t\tPlease enter your sweet name : ";
// cin>>soham;
getline(cin,soham);
int i=0;
while(i<subjectcount)
{
cout<<"Enter "<<stu[i].subname<<" Grade (EX. AA or AB likewise) :";
cin>>stu[i].gd;
if(strcmp(stu[i].gd,c10)==0)
stu[i].rslt=10;
else if(strcmp(stu[i].gd,c9)==0)
stu[i].rslt=9;
else if(strcmp(stu[i].gd,c8)==0)
stu[i].rslt=8;
else if(strcmp(stu[i].gd,c7)==0)
stu[i].rslt=7;
else if(strcmp(stu[i].gd,c6)==0)
stu[i].rslt=6;
else if(strcmp(stu[i].gd,c5)==0)
stu[i].rslt=5;
else if(strcmp(stu[i].gd,c4)==0)
stu[i].rslt=4;
else if(strcmp(stu[i].gd,c3)==0)
stu[i].rslt=0;
else
stu[i].rslt=0;
i++;
}
system("pause");
}
void result()
{
int creditsum=0,i;
int tmp;
i=0;
while(i<subjectcount)
{
creditsum+=stu[i].credit;
i++;
}
double gradesum=0.0;
i=0;
while(i<subjectcount)
{
tmp=stu[i].rslt*stu[i].credit;
gradesum+=tmp;
i++;
}
double sgpa=gradesum/creditsum;
cout<<"\nscored credits : "<<gradesum;
cout<<"\ntotal credits : "<<creditsum;
cout<<"\n\nCongratulations...."<<soham<<" !!! Your SGPA is "<<sgpa<<endl;
// string line;
lin=soham;
fi.open("sgpa.txt",ios::app|ios::in|ios::out);
fi <<lin<<" "<<sgpa<< endl;
fi.close();
system("pause");
}
void histor()
{
fi.open("sgpa.txt",ios::app|ios::in|ios::out);
fi.seekg(0, ios::beg);
cout<<"\n\nName "<<setw(20)<<"SGPA\n\n";
while (fi)
{
getline(fi, lin);
cout << lin << endl;
}
fi.close();
system("pause");
}
class subject
{
int subcount;
public :
subject()
{
subcount=0;
}
void getsub();
void menu();
int getsubcount()
{
return subcount;
}
void presub();
};
//pointer p1;
void subject::getsub()
{
string li;
cout<<"\nEnter total subjects (integer only): ";
cin>>subcount;
/* while (getline(cin, li))
{
stringstream ss(li);
if (ss >> subcount)
{
if (ss.eof())
{ // Success
break;
}
}
}
*/
// subcount=10;
// SUB stu[subcount];
subjectcount=subcount;
countsubject=subcount;
int i=0;
while(i<subcount)
{
cout<<endl;
cout<<"Enter subject "<<i+1<<" name :" ;
fflush(stdin);
getline(cin, stu[i].subname);
// getline (cin,mystr);
cout<<"enter it's credits (Integer only) : ";
cin>>stu[i].credit;
i++;
}
}
void subject::menu()
{
int opt;
system("color f0");
subject s1;
while(1)
{
system("cls");
cout<<"\n\n\n\n***************************** If your branch is not added, add here "<<__DATE__<<","<<__TIME__<<" *************************\n\n";
cout<<"\n\n\n\t\tNOTE : Please enter subject credentials at first";
cout<<"\n\n\n\t\t1.Enter subject credentials ";
cout<<"\n\t\t2.Enter Obtained Grades";
cout<<"\n\t\t3.calculate Result";
cout<<"\n\t\t4.History";
cout<<"\n\t\t5.Exit";
cout<<"\n\n ";
cout << "\nEnter proper option : " ;
string sline;
//int opt;
while (getline(cin, sline))
{
stringstream ss(sline);
if (ss >> opt)
{
if (ss.eof())
{ // Success
break;
}
}
// cout << "\nEnter proper option : " ;
}
if(opt>4)
break ;
switch(opt)
{
case 1 : s1.getsub(); break ;
//case 2 : branch h;
// h.history();break;
case 2 : getgrades();break;
// goto LOOP;
case 3 : result(); break;
case 4 : histor(); break;
case 5 : return ;
}
}
}
| true |
87b31e3a7ae0144b5357c2babd6b1794814b2b53 | C++ | SOFTK2765/PS | /BOJ/11586.cpp | UTF-8 | 738 | 2.765625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int n;
char a[101][101];
void rev1()
{
for(int i=0;i<n;i++)
for(int j=0;j<=(n-1)/2;j++)
{
char tmp = a[i][j];
a[i][j] = a[i][n-1-j];
a[i][n-1-j] = tmp;
}
return;
}
void rev2()
{
for(int i=0;i<n;i++)
for(int j=0;j<=(n-1)/2;j++)
{
char tmp = a[j][i];
a[j][i] = a[n-1-j][i];
a[n-1-j][i] = tmp;
}
return;
}
int main()
{
scanf("%d", &n);
for(int i=0;i<n;i++)
scanf("%s", a[i]);
int k;
scanf("%d", &k);
if(k==2) rev1();
else if(k==3) rev2();
for(int i=0;i<n;i++)
printf("%s\n", a[i]);
return 0;
} | true |
38e3fcf404f1715121319a24aa331a0b6bb9800e | C++ | dengxinlong/Algorithm_4 | /chapter_1/1.3/Bag/bag.h | UTF-8 | 255 | 2.671875 | 3 | [] | no_license | #include <iostream>
using namespace std;
template<class T>
class Bag
{
public:
Bag()
{}
void add(T item)
{
;
}
bool isEmpty(void)
{
;
}
int size(void)
{
return 0;
}
private:
}; | true |
6cd43f296c9a19cf9bde6d0c9db3ded6bf948b87 | C++ | WIZARD-CXY/misc | /c++/class.cc | UTF-8 | 946 | 3.734375 | 4 | [] | no_license | #include <iostream>
using namespace std;
class Base1 { //基类Base1定义
public:
void display() const {
cout << "Base1::display()" << endl;
}
};
class Base2: public Base1 { //公有派生类Base2定义
public:
void display() const {
cout << "Base2::display()" << endl;
}
};
class Derived: public Base2 { //公有派生类Derived定义
public:
void display() const {
cout << "Derived::display()" << endl;
}
};
void fun(Base1 *ptr) { //参数为指向基类对象的指针
ptr->display(); //"对象指针->成员名"
}
int main() { //主函数
Base1 base1; //声明Base1类对象
Base2 base2; //声明Base2类对象
Derived derived; //声明Derived类对象
fun(&base1); //用Base1对象的指针调用fun函数
fun(&base2); //用Base2对象的指针调用fun函数
fun(&derived); //用Derived对象的指针调用fun函数
return 0;
}
| true |
b78528763dad320062c5232dcf52e097ef505429 | C++ | Wouter-Engelen/vpw | /cat4/huizenjacht/cpp/WouterE.cpp | UTF-8 | 3,203 | 2.546875 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
struct pos { int x, y; };
struct range { int min, max; };
struct segment { int max, lazy; };
int n, k, power2;
vector<pos> ps;
vector<int> ypx, ymx;
int dist_p(int l, int r) {
return abs((ps.at(ypx.at(l)).y + ps.at(ypx.at(l)).x) - (ps.at(ypx.at(r)).y + ps.at(ypx.at(r)).x));;
}
int dist_m(int l, int r) {
return abs((ps.at(ymx.at(l)).y - ps.at(ymx.at(l)).x) - (ps.at(ymx.at(r)).y - ps.at(ymx.at(r)).x));
}
void range_update(vector<segment>& segment_tree, int from, int to, int dx, int node = 1, int node_min = 0, int node_max = n - 1) {
if (segment_tree[node].lazy != 0) {
segment_tree[node].max += segment_tree[node].lazy;
if (node_min != node_max) {
segment_tree[node * 2].lazy += segment_tree[node].lazy;
segment_tree[node * 2 + 1].lazy += segment_tree[node].lazy;
}
segment_tree[node].lazy = 0;
}
if (to < node_min || from > node_max) {
return;
}
else if (from <= node_min && node_max <= to) {
segment_tree[node].max += dx;
if (node_min != node_max) {
segment_tree[node * 2].lazy += dx;
segment_tree[node * 2 + 1].lazy += dx;
}
}
else {
int d = (node_min + node_max) / 2;
range_update(segment_tree, from, to, dx, node * 2, node_min, d);
range_update(segment_tree, from, to, dx, node * 2 + 1, d + 1, node_max);
segment_tree[node].max = max(segment_tree[node * 2].max, segment_tree[node * 2 + 1].max);
}
}
int range_max(vector<segment>& segment_tree) {
return segment_tree[1].max;
}
bool possible(int max_dist) {
vector<range> groups(n);
int left = 0, right = 0;
while (left < n) {
while (right < n && dist_p(left, right) <= max_dist) {
groups.at(ypx.at(right)).min = left;
right++;
}
groups.at(ypx.at(left)).max = left;
left++;
}
vector<segment> frequencies(2 * power2, { 0, 0 });
left = 0, right = 0;
while (right < n) {
while (right < n && dist_m(left, right) <= max_dist) {
range_update(frequencies, groups.at(ymx.at(right)).min, groups.at(ymx.at(right)).max, 1);
right++;
}
if (range_max(frequencies) >= k) return true;
range_update(frequencies, groups.at(ymx.at(left)).min, groups.at(ymx.at(left)).max, -1);
left++;
}
return false;
}
int solve() {
int index = 0;
int jump = 1 << 30;
while (jump > 0) {
if (!possible(index + jump)) index += jump;
jump /= 2;
}
return index + 1;
}
int main() {
int nr;
cin >> nr;
for (int i = 1; i <= nr; i++) {
cin >> n >> k;
ps = vector<pos>(n);
for (int j = 0; j < n; j++) cin >> ps.at(j).x >> ps.at(j).y;
ypx.clear();
ymx.clear();
for (int j = 0; j < n; j++) ypx.push_back(j);
for (int j = 0; j < n; j++) ymx.push_back(j);
sort(ypx.begin(), ypx.end(), [](int l, int r) {
return ps.at(l).y + ps.at(l).x < ps.at(r).y + ps.at(r).x;
});
sort(ymx.begin(), ymx.end(), [](int l, int r) {
return ps.at(l).y - ps.at(l).x < ps.at(r).y - ps.at(r).x;
});
power2 = n - 1; // Calculates smallest power of 2 greater than n (needed for segment tree)
power2 |= power2 >> 1;
power2 |= power2 >> 2;
power2 |= power2 >> 4;
power2 |= power2 >> 8;
power2 |= power2 >> 16;
power2++;
std::cout << i << " " << solve() << endl;
}
}
| true |
b83e878882c02b366421518c081df9e99cf23b09 | C++ | zyclam/c- | /exercise 4/ex6-2.cpp | GB18030 | 677 | 2.796875 | 3 | [] | no_license | #include <iostream>
#include<cmath>
#include<stdio.h>
using namespace std;
int main()
{
int x,y;
int t=1;
while(1)
{
cin>>x>>y;
if (x==0 && y==0)
break;
for(int i=x; i<=y,i++)
{
sum= pow(i,2)+i+41;//ʽӼ
if (sum<2)
{
t=0;
}
for (int i = 2; i < sqrt(sum)+1; i++)
if (sum%i == 0)
{
t = 0;
break;
}
}
if (t)
cout << "OK" << endl;
else
cout << "Sorry" << endl;
}
}
| true |
4069ee115f5b165bf279ff7f67f00ba9f06c8c9e | C++ | fengrenchang86/PKU | /3386/2694167_WA.cpp | UTF-8 | 190 | 2.640625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main ()
{
int a,b,c,d,e;
cin>>a>>b>>c>>d>>e;
if ( a <= d && c <=e || c <= b && a <= c )cout<<"Yes"<<endl;
else cout<<"No"<<endl;
return 0;
} | true |
855301b14cb2e7ec97b5a50c774ae60ca6ce3f99 | C++ | Karodips/OOPLaba1 | /N6.cpp | UTF-8 | 341 | 2.78125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main(){
setlocale(LC_ALL, "Russian");
double dollar;
cin >> dollar;
cout << "Фунтов: " << dollar*(1/1.1487) << " Немецких марок: " << dollar*(1/0.584) << " Йен: " << dollar*(1/0.00955) << " Франков: " << dollar*(1/0.172) << endl;
system("pause");
return 0;
}
| true |
4eb822ac52369191bc4c0c3e589add2ba6183069 | C++ | yuanzheng/BYU | /cs240_C++_Projects/WebCrawler/inc/StopWordTree.h | UTF-8 | 2,012 | 3.40625 | 3 | [] | no_license | #ifndef STOPWORDTREE_H
#define STOPWORDTREE_H
#include "StopWord.h"
/*
* StopWordTree implements the StopWord binary search tree for load and store the stop word.
* Each word shown up in each page should be searched on this tree.
* By using BST data structure each word can be fast searched.
*/
class StopWordTree {
public:
//! No-arg constructor. Initializes an empty BST
WordTree();
//! Copy constructor. Makes a complete copy of its argument
WordTree(const WordTree & other);
//! Destructor
~WordTree();
//! Assignment operator. Makes a complete copy of its argument
//! @return Reference to oneself
WordTree& operator =(const WordTree & other);
//! @return a pointer to the root node of the tree, or NULL if the tree is empty.
StopWord * GetTree()const;
//! @return true if the BST is empty, or false if the BST is not empty
bool IsEmpty() const;
//! Removes all values from the BST
void Clear();
//! @return the number of values in the BST
int GetSize() const;
/*
* Inserts each stop word from the stopword.txt fileinto the BST.
* Searching the StopWord BST. each stop word are unique.
*
* @param word The new value being inserted
*
*/
void Insert(const std::string & word);
/*
* Searches the tree for the word on the StopWord BST tree.
*
* @param word The new word being searched for
*
* @return true if this word is found on the tree, otherwise is false.
*/
bool Find(const std::string & word) const;
private:
StopWord * root; // points to the root of StopWord BST
int size; // the size of BST, number of words
// these methods may be can assist above methods to build the tree and delete the tree.
void ParseTree(const StopWord * node);
StopWord * Addit(const std::string & v, StopWord * curNode);
void CleanTree(WordIndex * curNode);
StopWord * Search(const std::string & v, StopWord * curNode) const;
};
#endif
| true |
87b4d115d99c03093cbc6c7be3462620a716020d | C++ | davisking/dlib | /dlib/cuda/tensor_abstract.h | UTF-8 | 25,549 | 2.921875 | 3 | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | // Copyright (C) 2015 Davis E. King (davis@dlib.net)
// License: Boost Software License See LICENSE.txt for the full license.
#undef DLIB_DNn_TENSOR_ABSTRACT_H_
#ifdef DLIB_DNn_TENSOR_ABSTRACT_H_
#include "../matrix.h"
#include "../any/any_abstract.h"
namespace dlib
{
// ----------------------------------------------------------------------------------------
class tensor
{
/*!
WHAT THIS OBJECT REPRESENTS
This object represents a 4D array of float values, all stored contiguously
in memory. Importantly, it keeps two copies of the floats, one on the host
CPU side and another on the GPU device side. It automatically performs the
necessary host/device transfers to keep these two copies of the data in
sync.
All transfers to the device happen asynchronously with respect to the
default CUDA stream so that CUDA kernel computations can overlap with data
transfers. However, any transfers from the device to the host happen
synchronously in the default CUDA stream. Therefore, you should perform
all your CUDA kernel launches on the default stream so that transfers back
to the host do not happen before the relevant computations have completed.
If DLIB_USE_CUDA is not #defined then this object will not use CUDA at all.
Instead, it will simply store one host side memory block of floats.
Finally, the convention in dlib code is to interpret the tensor as a set of
num_samples() 3D arrays, each of dimension k() by nr() by nc(). Also,
while this class does not specify a memory layout, the convention is to
assume that indexing into an element at coordinates (sample,k,r,c) can be
accomplished via:
host()[((sample*t.k() + k)*t.nr() + r)*t.nc() + c]
THREAD SAFETY
Instances of this object are not thread-safe. So don't touch one from
multiple threads at the same time.
!*/
public:
virtual ~tensor();
long long num_samples(
) const;
/*!
ensures
- returns the number of 3D arrays of dimension k() by nr() by nc() there
are in this object.
!*/
long long k(
) const;
/*!
ensures
- returns the k dimension of this tensor. Generally, we think of a tensor
as containing num_samples() images of nr() by nc() rows and columns, each
with k() channels.
!*/
long long nr(
) const;
/*!
ensures
- returns the number of rows in this tensor.
!*/
long long nc(
) const;
/*!
ensures
- returns the number of columns in this tensor.
!*/
size_t size(
) const;
/*!
ensures
- returns num_samples()*k()*nr()*nc()
(i.e. the total number of floats in this tensor)
!*/
void async_copy_to_device(
) const;
/*!
ensures
- This function does not block.
- if (the host version of the data is newer than the device's copy) then
- Begins asynchronously copying host data to the device.
- A call to device() that happens before the transfer completes will
block until the transfer is complete. That is, it is safe to call
async_copy_to_device() and then immediately call device().
!*/
typedef float* iterator;
typedef const float* const_iterator;
iterator begin() { return host(); }
const_iterator begin() const { return host(); }
iterator end() { return host()+size(); }
const_iterator end() const { return host()+size(); }
/*!
ensures
- makes a tensor iterable just like the STL containers.
!*/
virtual const float* host(
) const = 0;
/*!
ensures
- returns a pointer to the host memory block of size() contiguous float
values or nullptr if size()==0.
- if (the host's copy of the data is out of date) then
- copies the data from the device to the host, while this is happening
the call to host() blocks.
!*/
virtual float* host(
) = 0;
/*!
ensures
- returns a pointer to the host memory block of size() contiguous float
values or nullptr if size()==0.
- if (the host's copy of the data is out of date) then
- copies the data from the device to the host, while this is happening
the call to host() blocks.
- Marks the device side data as out of date so that the next call to
device() will perform a host to device transfer. If you want to begin
the transfer immediately then you can call async_copy_to_device() after
calling host().
!*/
virtual float* host_write_only(
) = 0;
/*!
ensures
- This function returns the same pointer as host(), except that it never
performs a device to host memory copy. Instead, it immediately marks the
device side data as out of date, effectively discarding it. Therefore,
the values in the data pointed to by host_write_only() are undefined and
you should only call host_write_only() if you are going to assign to
every memory location in the returned memory block.
!*/
virtual const float* device(
) const = 0;
/*!
requires
- DLIB_USE_CUDA is #defined
ensures
- returns a pointer to the device memory block of size() contiguous float
values or nullptr if size()==0.
- if (the device's copy of the data is out of date) then
- copies the data from the host to the device, while this is happening
the call to device() blocks.
!*/
virtual float* device(
) = 0;
/*!
requires
- DLIB_USE_CUDA is #defined
ensures
- returns a pointer to the device memory block of size() contiguous float
values or nullptr if size()==0.
- if (the device's copy of the data is out of date) then
- copies the data from the host to the device, while this is happening
the call to device() blocks.
- Marks the host side data as out of date so that the next call to
host() will perform a device to host transfer.
!*/
virtual float* device_write_only(
) = 0;
/*!
requires
- DLIB_USE_CUDA is #defined
ensures
- This function returns the same pointer as device(), except that it never
performs a host to device memory copy. Instead, it immediately marks the
host side data as out of date, effectively discarding it. Therefore, the
values in the data pointed to by device_write_only() are undefined and
you should only call device_write_only() if you are going to assign to
every memory location in the returned memory block.
!*/
virtual const any& annotation(
) const = 0;
/*!
ensures
- returns a const reference to the any object in this tensor. The any
object can be used to store any additional annotation you like in a
tensor. However, it should be noted that the annotation() is ignored by
serialize() and therefore not saved when a tensor is serialized.
!*/
virtual any& annotation(
) = 0;
/*!
ensures
- returns a non-const reference to the any object in this tensor. The any
object can be used to store any additional annotation you like in a
tensor. However, it should be noted that the annotation() is ignored by
serialize() and therefore not saved when a tensor is serialized.
!*/
int device_id(
) const;
/*!
ensures
- returns the ID of the CUDA device that allocated this memory. I.e. the
number returned by cudaGetDevice() when the memory was allocated.
- If CUDA is not being used then this function always returns 0.
!*/
tensor& operator= (
float val
);
/*!
ensures
- sets all elements of this tensor equal to val.
- returns *this
!*/
tensor& operator*= (
float val
);
/*!
ensures
- pointwise multiplies all elements of *this tensor with val.
- returns *this
!*/
tensor& operator/= (
float val
);
/*!
ensures
- pointwise divides all elements of *this tensor with val.
- returns *this
!*/
template <typename EXP>
tensor& operator= (
const matrix_exp<EXP>& item
);
/*!
requires
- num_samples() == item.nr()
- k()*nr()*nc() == item.nc()
- item contains float values
ensures
- Assigns item to *this tensor by performing:
set_ptrm(host(), num_samples(), k()*nr()*nc()) = item;
!*/
template <typename EXP>
tensor& operator+= (
const matrix_exp<EXP>& item
);
/*!
requires
- num_samples() == item.nr()
- k()*nr()*nc() == item.nc()
- item contains float values
ensures
- Adds item to *this tensor by performing:
set_ptrm(host(), num_samples(), k()*nr()*nc()) += item;
!*/
template <typename EXP>
tensor& operator-= (
const matrix_exp<EXP>& item
);
/*!
requires
- num_samples() == item.nr()
- k()*nr()*nc() == item.nc()
- item contains float values
ensures
- Subtracts item from *this tensor by performing:
set_ptrm(host(), num_samples(), k()*nr()*nc()) -= item;
!*/
template <typename EXP>
void set_sample (
unsigned long long idx,
const matrix_exp<EXP>& item
);
/*!
requires
- idx < num_samples()
- k()*nr()*nc() == item.size()
- item contains float values
ensures
- Assigns item to the idx'th sample in *this by performing:
set_ptrm(host()+idx*item.size(), item.nr(), item.nc()) = item;
!*/
template <typename EXP>
void add_to_sample (
unsigned long long idx,
const matrix_exp<EXP>& item
);
/*!
requires
- idx < num_samples()
- k()*nr()*nc() == item.size()
- item contains float values
ensures
- Adds item to the idx'th sample in *this by performing:
set_ptrm(host()+idx*item.size(), item.nr(), item.nc()) += item;
!*/
protected:
// You can't move or copy another tensor into *this since that might modify the
// tensor's dimensions. If you want to do that sort of thing then use a
// resizable_tensor.
tensor(const tensor& item);
tensor& operator= (const tensor& item);
tensor(tensor&& item);
tensor& operator=(tensor&& item);
};
// ----------------------------------------------------------------------------------------
void memcpy (
tensor& dest,
const tensor& src
);
/*!
requires
- dest.size() == src.size()
ensures
- Copies the data in src to dest. If the device data is current on both src
and dest then the copy will happen entirely on the device side.
- It doesn't matter what GPU device is selected by cudaSetDevice(). You can
always copy tensor objects to and from each other regardless.
- This function blocks until the copy has completed.
!*/
// ----------------------------------------------------------------------------------------
bool is_vector (
const tensor& t
);
/*!
ensures
- returns true if and only if one of the following is true:
- t.size() == t.num_samples()
- t.size() == t.k()
- t.size() == t.nr()
- t.size() == t.nc()
!*/
// ----------------------------------------------------------------------------------------
const matrix_exp mat (
const tensor& t,
long long nr,
long long nc
);
/*!
requires
- nr >= 0
- nc >= 0
- nr*nc == t.size()
ensures
- returns a matrix M such that:
- M.nr() == nr
- m.nc() == nc
- for all valid r and c:
M(r,c) == t.host()[r*nc + c]
(i.e. the tensor is interpreted as a matrix laid out in memory
in row major order)
!*/
const matrix_exp mat (
const tensor& t
);
/*!
ensures
- if (t.size() != 0) then
- returns mat(t, t.num_samples(), t.size()/t.num_samples())
- else
- returns an empty matrix.
!*/
const matrix_exp image_plane (
const tensor& t,
long long sample = 0,
long long k = 0
);
/*!
requires
- t.size() != 0
- 0 <= sample < t.num_samples()
- 0 <= k < t.k()
ensures
- returns the k-th image plane from the sample-th image in t. That is,
returns a matrix M such that:
- M contains float valued elements.
- M.nr() == t.nr()
- M.nc() == t.nc()
- for all valid r and c:
- M(r,c) == t.host()[((sample*t.k() + k)*t.nr() + r)*t.nc() + c]
!*/
// ----------------------------------------------------------------------------------------
bool have_same_dimensions (
const tensor& a,
const tensor& b
);
/*!
ensures
- returns true if and only if all of the fallowing are satisfied:
- a.num_samples() == b.num_samples()
- a.k() == b.k()
- a.nr() == b.nr()
- a.nc() == b.nc()
!*/
// ----------------------------------------------------------------------------------------
class resizable_tensor : public tensor
{
/*!
WHAT THIS OBJECT REPRESENTS
This object is just a tensor with the additional ability to be resized.
!*/
public:
resizable_tensor(
);
/*!
ensures
- #size() == 0
- #num_samples() == 0
- #k() == 0
- #nr() == 0
- #nc() == 0
- #capacity() == 0
!*/
template <typename EXP>
resizable_tensor(
const matrix_exp<EXP>& item
);
/*!
requires
- item contains float values
ensures
- #num_samples() == item.nr()
- #k() == item.nc()
- #nr() == 1
- #nc() == 1
- Assigns item to *this tensor by performing:
set_ptrm(host(), num_samples(), k()*nr()*nc()) = item;
- #capacity() == size()
!*/
explicit resizable_tensor(
long long n_, long long k_ = 1, long long nr_ = 1, long long nc_ = 1
);
/*!
requires
- n_ >= 0
- k_ >= 0
- nr_ >= 0
- nc_ >= 0
ensures
- #size() == n_*k_*nr_*nc_
- #num_samples() == n_
- #k() == k_
- #nr() == nr_
- #nc() == nc_
- #capacity() == size()
!*/
// This object is copyable and movable
resizable_tensor(const resizable_tensor&) = default;
resizable_tensor(resizable_tensor&&) = default;
resizable_tensor& operator= (const resizable_tensor&) = default;
resizable_tensor& operator= (resizable_tensor&&) = default;
size_t capacity (
) const;
/*!
ensures
- returns the total number of floats allocated. This might be different
from the size() since calls to set_size() that make a tensor smaller
don't trigger reallocations. They simply adjust the nominal dimensions
while keeping the same allocated memory block. This makes calls to
set_size() very fast. If you need to deallocate a tensor then use
clear().
!*/
void clear(
);
/*!
ensures
- #size() == 0
- #num_samples() == 0
- #k() == 0
- #nr() == 0
- #nc() == 0
- #annotation().is_empty() == true
- #capacity() == 0
!*/
void copy_size (
const tensor& item
);
/*!
ensures
- resizes *this so that: have_same_dimensions(#*this, item)==true
!*/
void set_size(
long long n_, long long k_ = 1, long long nr_ = 1, long long nc_ = 1
);
/*!
requires
- n_ >= 0
- k_ >= 0
- nr_ >= 0
- nc_ >= 0
ensures
- #size() == n_*k_*nr_*nc_
- #num_samples() == n_
- #k() == k_
- #nr() == nr_
- #nc() == nc_
- #capacity() == max(#size(), capacity())
(i.e. capacity() never goes down when calling set_size().)
!*/
template <typename EXP>
resizable_tensor& operator= (
const matrix_exp<EXP>& item
);
/*!
requires
- item contains float values
ensures
- if (num_samples() == item.nr() && k()*nr()*nc() == item.nc()) then
- the dimensions of this tensor are not changed
- else
- #num_samples() == item.nr()
- #k() == item.nc()
- #nr() == 1
- #nc() == 1
- Assigns item to *this tensor by performing:
set_ptrm(host(), num_samples(), k()*nr()*nc()) = item;
!*/
};
void serialize(const tensor& item, std::ostream& out);
void deserialize(resizable_tensor& item, std::istream& in);
/*!
provides serialization support for tensor and resizable_tensor. Note that you can
serialize to/from any combination of tenor and resizable_tensor objects.
!*/
// ----------------------------------------------------------------------------------------
double dot(
const tensor& a,
const tensor& b
);
/*!
requires
- a.size() == b.size()
ensures
- returns the dot product between a and b when they are both treated as
a.size() dimensional vectors. That is, this function pointwise multiplies
the vectors together, then sums the result and returns it.
!*/
// ----------------------------------------------------------------------------------------
class alias_tensor_instance : public tensor
{
/*!
WHAT THIS OBJECT REPRESENTS
This object is a tensor that aliases another tensor. That is, it doesn't
have its own block of memory but instead simply holds pointers to the
memory of another tensor object. It therefore allows you to efficiently
break a tensor into pieces and pass those pieces into functions.
An alias_tensor_instance doesn't own the resources it points to in any sense.
So it is important to make sure that the underlying owning tensor doesn't get
destructed before any alias tensors which point to it are destructed.
!*/
// You can't default initialize this object. You can only get instances of it from
// alias_tensor::operator().
alias_tensor_instance(
);
};
class alias_tensor_const_instance
{
/*!
WHAT THIS OBJECT REPRESENTS
This is essentially a const version of alias_tensor_instance and therefore
represents a tensor. However, due to the mechanics of C++, this object
can't inherit from tensor. So instead it provides a get() and an implicit
conversion to const tensor.
!*/
public:
// non-const alias tensors are convertible to const ones.
alias_tensor_const_instance(const alias_tensor_instance& item);
// Methods that cast the alias to a tensor.
const tensor& get() const;
operator const tensor& ();
private:
// You can't default initialize this object. You can only get instances of it from
// alias_tensor::operator().
alias_tensor_const_instance();
};
class alias_tensor
{
/*!
WHAT THIS OBJECT REPRESENTS
This is a tool for creating tensor objects that alias other tensor objects.
That is, it allows you to make a tensor that references the memory space of
another tensor object rather than owning its own memory. This allows you
to do things like interpret a single tensor in different ways or even as a
group of multiple tensors.
!*/
public:
alias_tensor (
);
/*!
ensures
- #size() == 0
- #num_samples() == 0
- #k() == 0
- #nr() == 0
- #nc() == 0
!*/
alias_tensor (
long long n_, long long k_ = 1, long long nr_ = 1, long long nc_ = 1
);
/*!
requires
- n_ >= 0
- k_ >= 0
- nr_ >= 0
- nc_ >= 0
ensures
- #size() == n_*k_*nr_*nc_
- #num_samples() == n_
- #k() == k_
- #nr() == nr_
- #nc() == nc_
!*/
long long num_samples() const;
long long k() const;
long long nr() const;
long long nc() const;
size_t size() const;
alias_tensor_instance operator() (
tensor& t,
size_t offset = 0
) const;
/*!
requires
- offset+size() <= t.size()
ensures
- Returns a tensor that simply aliases the elements of t beginning with t's
offset'th element. Specifically, this function returns an aliasing
tensor T such that:
- T.size() == size()
- T.num_samples() == num_samples()
- T.k() == k()
- T.nr() == nr()
- T.nc() == nc()
- T.host() == t.host()+offset
- T.device() == t.device()+offset
- &T.annotation() == &t.annotation()
!*/
alias_tensor_const_instance operator() (
const tensor& t,
size_t offset = 0
) const;
/*!
requires
- offset+size() <= t.size()
ensures
- This function is identical to the above version of operator() except that
it takes and returns const tensors instead of non-const tensors.
!*/
};
void serialize(const alias_tensor& item, std::ostream& out);
void deserialize(alias_tensor& item, std::istream& in);
/*!
provides serialization support for alias_tensor.
!*/
// ----------------------------------------------------------------------------------------
}
#endif // DLIB_DNn_TENSOR_ABSTRACT_H_
| true |
ec71b5ae78fd782e7452e02de025d47a6c806a2b | C++ | ambideXtrous9/Data-Structures-and-Algorithms | /coef.cpp | UTF-8 | 841 | 3.25 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int coef(int ,int );
int coefDP(int ,int );
int main()
{
int n,k;
cout<<"ENTER THE NUMBER n = "<<endl;
cin>>n;
cout<<"ENTER THE NUMBER k = "<<endl;
cin>>k;
int num = coef(n,k);
cout<< "COEFFICIENT = "<<num<<endl;
num = coefDP(n,k);
cout<< "COEFFICIENT(DP) = "<<num<<endl;
return 0;
}
int coef(int n,int k)
{
if (k>n)
{
return 0;
}
if(k == 0 || k == n) //base case nc0 = ncn = 1
return 1;
return coef(n-1,k-1) + coef(n-1,k);
}
// bottom up DP approach as it has overlapping subproblem property
int coefDP(int n,int k)
{
if (k>n)
{
return 0;
}
int C[n+1][k+1];
for (int i = 0; i <= n; i++)
{
for (int j = 0; j <= min(i,k) ; j++)
{
if(j == 0 || j == i)
C[i][j] = 1;
else
C[i][j] = C[i-1][j-1] + C[i-1][j];
}
}
return C[n][k];
}
| true |
d6df1628e36e77fa3d5bb44fd32dcf380a579ebe | C++ | panipuri8/interesting-interview-questions | /competitive_p_snippets/maths.cpp | UTF-8 | 1,425 | 3.328125 | 3 | [] | no_license | /* Start of Math Templates */
ll factorial[MAXN];
ll inverse[MAXN];
ll inverseFactorial[MAXN];
ll modInverse(ll a, ll m) { //if a and m are coprime, find a^-1 in mod m
ll m0 = m;
ll y = 0, x = 1;
if (m == 1)
return 0;
while (a > 1) {
ll q = a / m;
ll t = m;
m = a % m, a = t;
t = y;
y = x - q * y;
x = t;
}
while (x < 0) x += m0;
return x;
}
ll power(ll base,ll exp) {
ll ans = 1;
while(exp) {
if(exp&1) ans = (ans * base)%MOD;
base = (base*base)%MOD;
exp>>=1;
}
return ans;
}
ll calculateInverseUsingFermatsLittleTheorem(int i) { //only if MOD is prime
return power((ll)i , MOD-2);
}
void calculateInverse() {
inverse[0] = 1;
inverse[1] = 1;
for(int i=2;i<MAXN;i++) {
ll quotient = (ll)(MOD/i);
ll remainder = (ll)(MOD%i);
inverse[i] = ((-quotient * inverse[remainder]) + MOD)%MOD;
// inverse[i] = calculateInverseUsingFermatsLittleTheorem(i);
}
}
void calculateFactorialAndInverseFactorial() {
factorial[0] = factorial[1] = 1;
inverseFactorial[0] = inverseFactorial[1] = 1;
for(int i=2;i<MAXN;i++) {
factorial[i] = (factorial[i-1] * i)%MOD;
inverseFactorial[i] = (inverseFactorial[i-1] * inverse[i])%MOD;
}
}
/*Combinations in O(1)*/
ll nCr(int n, int r) {
ll ans = factorial[n];
ans = (ans * inverseFactorial[n-r])%MOD;
ans = (ans * inverseFactorial[r])%MOD;
return ans;
}
/*End of Math Templates */ | true |
2566118ddfd32026dbfba1266b633fe644b649f6 | C++ | ScottVisser/pistuff | /co2/hexop.cpp | UTF-8 | 369 | 2.84375 | 3 | [] | no_license | #include <iostream>
#include <stdio.h>
#include <cstdlib>
#include <string.h>
#include <iomanip>
using namespace std;
int main(void)
{
// char *hex1;
// hex1 = new char[5];
char hex1[5] = {0x68, 0x65, 0x6c, 0x6c, 0x6f};
char hex2[3] = {0xFF, 0xFA, 0x00};
printf("%s\n",hex1);
printf("%X\n",hex1[1]);
std::cout << std::hex << hex1[1] << std::endl;
return 0;
}
| true |
b7a6126b56e51d7a03411e0a38b3a22eb1c8e93a | C++ | herbstluftwm/herbstluftwm | /src/indexingobject.h | UTF-8 | 4,130 | 3.109375 | 3 | [
"BSD-2-Clause"
] | permissive | #ifndef INDEXINGOBJECT_H
#define INDEXINGOBJECT_H
#include <cstddef>
#include <string>
#include <vector>
#include "attribute_.h"
#include "object.h"
/** an object that carries a vector of children objects, each accessible by its
* index
*/
template<typename T>
class IndexingObject : public Object {
public:
IndexingObject()
: count(this, "count", &IndexingObject<T>::sizeUnsignedLong)
{ }
void addIndexed(T* newChild) {
addIndexed(newChild, data.size());
}
void addIndexed(T* newChild, size_t index) {
// the current array size is the index for the new child
data.insert(data.begin() + index, newChild);
// add a child object at the specified index
addChild(newChild, std::to_string(index));
newChild->setIndexAttribute(index);
// update the index of all the later elements
for (size_t i = index + 1; i < data.size(); i++) {
addChild(data[i], std::to_string(i));
data[i]->setIndexAttribute(i);
}
}
~IndexingObject() override {
clearChildren();
}
void removeIndexed(size_t idx) {
if (idx >= data.size()) {
// index does not exist
return;
}
T* child = byIdx(idx);
data.erase(data.begin() + idx);
removeChild(std::to_string(idx));
// Update indices for remaining children
for (size_t new_idx = idx; new_idx < data.size(); new_idx++) {
std::string old_idx_str = std::to_string(new_idx + 1);
removeChild(old_idx_str);
addChild(data[new_idx], std::to_string(new_idx));
data[new_idx]->setIndexAttribute(new_idx);
}
delete child;
}
int index_of(T* child) {
for (size_t i = 0; i < data.size(); i++) {
if (&* data[i] == child) {
return i;
}
}
return -1;
}
T& operator[](size_t idx) {
return *data[idx];
}
T* byIdx(size_t idx) {
return idx < data.size() ? data[idx] : nullptr;
}
size_t size() {
return data.size();
}
// remove all "indexed" children
void clearChildren() {
for (size_t idx = 0; idx < data.size(); idx++) {
removeChild(std::to_string(idx));
}
for (auto child : data) {
delete child;
}
data.erase(data.begin(), data.end());
}
void indexChangeRequested(T* object, size_t newIndex) {
if (newIndex < data.size() && data[newIndex] == object) {
// nothing to do
return;
}
if (data.empty()) {
return;
}
if (newIndex >= data.size()) {
newIndex = data.size() - 1;
}
int oldIndexSigned = index_of(object);
if (oldIndexSigned < 0) {
return;
}
size_t oldIndex = static_cast<size_t>(oldIndexSigned);
if (newIndex == oldIndex) {
return;
}
// go from newIndex to oldIndex
int delta = (newIndex < oldIndex) ? 1 : -1;
T* lastValue = object;
for (size_t i = newIndex; i != oldIndex; i+= delta) {
// swap data[i] with lastValue
T* tmp = data[i];
data[i] = lastValue;
lastValue = tmp;
}
data[oldIndex] = lastValue;
// for each of these, update the index
for (size_t i = newIndex; i != oldIndex; i+= delta) {
data[i]->setIndexAttribute(i);
addChild(data[i], std::to_string(i));
}
data[oldIndex]->setIndexAttribute(oldIndex);
addChild(data[oldIndex], std::to_string(oldIndex));
indicesChanged.emit();
}
DynAttribute_<unsigned long> count;
Signal indicesChanged;
// iterators
typedef typename std::vector<T*>::iterator iterator_type;
iterator_type begin() { return data.begin(); }
iterator_type end() { return data.end(); }
private:
unsigned long sizeUnsignedLong() {
return static_cast<unsigned long>(data.size());
}
std::vector<T*> data;
};
#endif
| true |
96f4703bd4cab262ba2487c49d5b5e51c5f18381 | C++ | syedraza011/Project-C- | /Cart.cpp | UTF-8 | 4,279 | 3.234375 | 3 | [] | no_license | #pragma onc
#include "Cart.h"
#include <iostream>
#include "ItemTable.h"
#include<fstream>
#include <string>
#include<cmath>
#include<ctime>
using namespace std;
// This is the Default Constructor
// This does not take parameters
Cart::Cart()
{
}
// This takes the vectorOfAllItems and gives a vector
vector<Item> Cart::vectorOfAllItems()
{
vector<Item> allStoreItems;
return allStoreItems;
}
// This is to checkout the cart
// with the item that the customer wants to buy
void Cart::checkout()
{
// This is for the customer when he picks the item
cout << "\n----: Check out Menu :----\n";
string ID;
char uChoice = 'y';
int search=-1;
Customer temp;
double spending;
// This while loop is if the customer says yes
// The customer puts the item id
while (uChoice=='y')
{
cout << "Please enter an Item's ID : ";
cin >> ID;
search = aTable.search(ID);
if (search !=-1)
{
addToCart(search);
aTable.updateQunatity(search);
}
else
{
cout << "\nWrong id entered\n";
continue;
}
cout << "to continue press y/n : ";
cin >> uChoice;
tolower(uChoice);
}
// This is for if the customer has an id
// if its yes then the program will go through the if statement
cout << "Does the customer has an ID?? y/n : ";
cin >> uChoice;
tolower(uChoice);
if (uChoice == 'y')
{
// This prints out the customer id and the cout statement
cout << "Please enter Customer's ID : ";
cin >> ID;
spending = aCartTotal();
search = allCustomers.search(ID);
if (search != -1)
{
// This keeps track of the customer spendings
bool returned = false;
returned=allCustomers.updateSpendings(search, spending);
if (returned == true)
{
cout << "\nSuccessfully added for Reward Points\n";
//cout << "Name" << allCustomers.getCustomers[search].getName()<<" Spenidngs"<< allCustomers.getCustomers[search].getSpending()<<endl;
}
//temp = allCustomers.[search];
}
}
else {
aCartTotal();
}
}
// This to show how much is the total of all the items the customer is buying
double Cart::aCartTotal()
{
system("cls");
// This prints out the customer information
double total = 0.0;
//system("cls");
cout << "\n\t\t\t!!The Virtual Systems!!"<<endl;
cout << "\t\t2800 Victory BLVD Staten Island 10314" << endl;
dateAndTime();
// This prints out the item informations
cout << "\n\nQuantity Item Name\tUnit Price\tTotal"<<endl;
for (map<Item, int>::iterator it = aCartMap.begin(); it != aCartMap.end(); ++it)
{
cout <<" "<< it->second << "\t" << it->first.getName() << "\t\tx$" << it->first.getSellPrice() <<"\t\t"
<< "$" << it->second*it->first.getSellPrice() << endl;
total += it->second*it->first.getSellPrice();
}
// This gives the total information
cout << "\n\n"<<endl;
cout << "\tTotal Amount due is: $" << total << endl;
cout << "\tThank you for shopping!!!" << endl;
cout << "\n\n";
return total;
}
// This shows the date and time when the customer check out
void Cart::dateAndTime()
{
#pragma warning(disable : 4996).
time_t t = time(NULL);
tm* timePtr = localtime(&t);
cout << "\t\t" << "Date: " << (timePtr->tm_mon) + 1 << "/" << (timePtr->tm_mday) << "/" << (timePtr->tm_year) + 1900 ;
cout <<"\t"<< "Time: " << (timePtr->tm_hour) << ":" << (timePtr->tm_min) << ":" << (timePtr->tm_sec) << endl;
}
// This is to add more items to the cart if the customer wants to add more items
void Cart::addToCart(int index)
{
Item temp = aTable.getAllStoreItems()[index];
int counter = 0;
string name;
if (aCartMap.find(temp) == aCartMap.end())
{
aCartMap[temp] = 1; //initilaize with one while inserting to map
}
else
{
counter=aCartMap[temp];
counter++; //update counter if the word alresdy existed
aCartMap[temp] = counter; //update the Item count the value of the map
}
cout << "\n" << endl;
//map iterator initialized to treverse through
for (map<Item, int>::iterator it = aCartMap.begin(); it != aCartMap.end(); ++it)
{
cout << it->second<< " " << it->first.getName() << "\tX " << it->first.getSellPrice() << " \n" << endl;
}// ending iterator loop which is being used to print
}
| true |
18a3467511fe9358639005afe4d0093d8dd89f82 | C++ | sukeyisme/sukey_code | /SocketWithThreadPool/tcp_svr_socket.cpp | UTF-8 | 516 | 2.734375 | 3 | [] | no_license | #include "tcp_svr_socket.h"
CTcpSvrSocket::CTcpSvrSocket()
{
}
CTcpSvrSocket::~CTcpSvrSocket()
{
}
bool CTcpSvrSocket::OnAccept()
{
CTcpSvrSocket *pSocket = new CTcpSvrSocket;
if (!Accept(pSocket)) {
delete pSocket;
pSocket = NULL;
return false;
}
cout << "accept" << endl;
return true;
}
bool CTcpSvrSocket::OnReceive()
{
char buf[512];
int ret = Receive(buf, 512);
if (0 == ret) {
Close();
return false;
}
buf[ret] = '\0';
Send(buf, strlen(buf));
cout << buf << endl;
return true;
} | true |
b61d0de429b92be1c314c6b5c2566c257cccaaed | C++ | mmmaxou/imac-cpp | /TP3/ImageRGBU8.cpp | UTF-8 | 628 | 2.890625 | 3 | [] | no_license | #include "ImageRGBU8.hpp"
/// Constructor
ImageRGBU8::ImageRGBU8() : _width(0), _height(0), _data()
{
}
ImageRGBU8::ImageRGBU8(const unsigned int w,
const unsigned int h)
: _width(w),
_height(h),
_data(w * h * 3)
{
std::cout << "Constructeur par VALEURS" << std::endl;
std::fill(_data.begin(),
_data.end(),
255);
}
ImageRGBU8::ImageRGBU8(const unsigned int w,
const unsigned int h,
const std::vector<unsigned char> &data)
: _width(w),
_height(h),
_data(data)
{
}
/// Destructor
ImageRGBU8::~ImageRGBU8() {} | true |
7cb37fc4784c2dd1c5faeaa1170cbdcab6e0d231 | C++ | vincentrolypoly/Malice | /Front-End-Compiler/Nodes/callNode.cpp | UTF-8 | 960 | 2.625 | 3 | [] | no_license |
#include "callNode.hpp"
#include "actualParamsNode.hpp"
#include "functionDeclNode.hpp"
#include <iostream>
#include "../CFG.hpp"
#include "../checkInterface.hpp"
callNode::callNode(string name, actualParamsNode *p, int line) {
callName = name;
actualParams = p;
lineNo = line;
callTo = NULL;
}
void callNode::printVal() {
cout<<"call name:" << callName <<endl;
cout<<"params:";
actualParams->printVal();
cout<<endl;
}
void callNode::setCallTo(functionDeclNode* f){
callTo = f;
}
functionDeclNode* callNode::getCallTo(){
return callTo;
}
actualParamsNode* callNode::getParams() {
return actualParams;
}
void callNode::accept(CheckInterface *c, SymbolTable *currentST) {
c->check(this, currentST);
}
string callNode::getName() {
return callName;
}
void callNode::destroyAST() {
actualParams->destroyAST();
delete actualParams;
}
int callNode::weight(){
//Always do calls first
return 10000;
}
| true |
927841c9f2cee4694c759edcc3d6980c1eb1cfb7 | C++ | metaphysis/Code | /UVa Online Judge/volume003/315 Network/program2.cpp | UTF-8 | 2,207 | 2.671875 | 3 | [] | no_license | // Network
// UVa ID: 315
// Verdict: Accepted
// Submission Date: 2017-10-21
// UVa Run Time: 0.000s
//
// 版权所有(C)2017,邱秋。metaphysis # yeah dot net
#include <bits/stdc++.h>
using namespace std;
// 顶点数目。
const int MAXV = 110;
// 使用邻接表来表示图。
vector<set<int>> edges;
// dfn保存各顶点的深度优先数,如果顶点的dfn值为0,表明该顶点尚未被访问。
// ic记录各顶点是否为割顶,为1表示为割顶,为0表示不是割顶。
// dfstime为时间戳。
int dfn[MAXV], ic[MAXV], dfstime = 0;
// Tarjan算法。调用时从任意一个顶点开始,parent设置为-1,表示起点为根结点。
int dfs(int u, int parent)
{
int lowu = dfn[u] = ++dfstime, lowv, children = 0;
// 对未访问的非根结点进行深度优先遍历并比较low值以判断是否为割顶。
for (auto v : edges[u])
{
if (!dfn[v])
{
++children, lowu = min(lowu, lowv = dfs(v, u));
if (lowv >= dfn[u]) ic[u] = 1;
}
else if (v != parent)
lowu = min(lowu, dfn[v]);
}
// 如果为树的根结点且子孙结点数目少于两个,不是割顶。
if (parent < 0 && children == 1) ic[u] = 0;
// 将顶点u的最小深度优先数保存在数组中以便后续使用。
return lowu;
}
int main(int argc, char *argv[])
{
cin.tie(0); cout.tie(0); ios::sync_with_stdio(false);
string line;
while (getline(cin, line))
{
int n = stoi(line);
if (n == 0) break;
edges.assign(n + 1, set<int>());
istringstream iss;
while (getline(cin, line), line != "0")
{
iss.clear(); iss.str(line);
int start, next;
iss >> start;
while (iss >> next)
edges[start].insert(next), edges[next].insert(start);
}
dfstime = 0;
memset(ic, 0, sizeof(ic));
memset(dfn, 0, sizeof(dfn));
dfs(1, -1);
int count = 0;
for (int i = 1; i <= n; i++)
if (ic[i])
count++;
cout << count << '\n';
}
return 0;
}
| true |
f41903372ec3b25cdd0930baf82bcf5e545e77bb | C++ | windystrife/UnrealEngine_NVIDIAGameWorks | /Engine/Source/ThirdParty/nvTextureTools/nvTextureTools-2.0.6/src/src/nvimage/PsdFile.h | UTF-8 | 1,296 | 2.609375 | 3 | [
"MIT",
"LicenseRef-scancode-proprietary-license",
"LGPL-2.0-or-later",
"GPL-1.0-or-later"
] | permissive | // This code is in the public domain -- castanyo@yahoo.es
#ifndef NV_IMAGE_PSDFILE_H
#define NV_IMAGE_PSDFILE_H
#include <nvcore/Stream.h>
namespace nv
{
enum PsdColorMode
{
PsdColorMode_Bitmap = 0,
PsdColorMode_GrayScale = 1,
PsdColorMode_Indexed = 2,
PsdColorMode_RGB = 3,
PsdColorMode_CMYK = 4,
PsdColorMode_MultiChannel = 7,
PsdColorMode_DuoTone = 8,
PsdColorMode_LabColor = 9
};
/// PSD header.
struct PsdHeader
{
uint32 signature;
uint16 version;
uint8 reserved[6];
uint16 channel_count;
uint32 height;
uint32 width;
uint16 depth;
uint16 color_mode;
bool isValid() const
{
return signature == 0x38425053; // '8BPS'
}
bool isSupported() const
{
if (version != 1) {
nvDebug("*** bad version number %u\n", version);
return false;
}
if (channel_count > 4) {
return false;
}
if (depth != 8) {
return false;
}
if (color_mode != PsdColorMode_RGB) {
return false;
}
return true;
}
};
inline Stream & operator<< (Stream & s, PsdHeader & head)
{
s << head.signature << head.version;
for (int i = 0; i < 6; i++) {
s << head.reserved[i];
}
return s << head.channel_count << head.height << head.width << head.depth << head.color_mode;
}
} // nv namespace
#endif // NV_IMAGE_PSDFILE_H
| true |
4f42823134223f4c73bfb18b36a02c7dd042f3e3 | C++ | Badstu/leetcode-exercises | /acwing/chapter3/852.cpp | UTF-8 | 1,290 | 2.890625 | 3 | [] | no_license | #include <cstring>
#include <iostream>
#include <queue>
using namespace std;
const int N = 2010, M = 10010;
int n, m;
int h[N], e[M], ne[M], w[M], idx;
int dist[N], cnt[N];
bool st[N];
void add(int x, int y, int z) {
e[idx] = y;
ne[idx] = h[x];
w[idx] = z;
h[x] = idx++;
}
bool spfa() {
// memset(dist, 0x3f, sizeof dist);
// dist[1] = 0;
// 不再从1开始走,所有点的距离都是0;
queue<int> q;
for (int i = 0; i < n; i++) {
st[i] = true;
q.push(i);
}
while (q.size()) {
int t = q.front();
q.pop();
st[t] = false;
for (int i = h[t]; i != -1; i = ne[i]) {
int j = e[i];
if (dist[j] > dist[t] + w[i]) { //给负权边写的
dist[j] = dist[t] + w[i];
cnt[j] = cnt[t] + 1;
if (cnt[j] >= n) return true;
if(!st[j]){
q.push(j);
st[j] = true;
}
}
}
}
return false;
}
int main() {
memset(h, -1, sizeof h);
cin >> n >> m;
int x, y, z;
for (int i = 0; i < m; i++) {
cin >> x >> y >> z;
add(x, y, z);
}
if(spfa()) cout << "Yes";
else
cout << "No";
return 0;
} | true |
e9b7f12fe35b4f155455d2babba287a24641dda5 | C++ | Jack10907314/LeetCode | /Contest/Biweekly Contest 45/1750. Minimum Length of String After Deleting Similar Ends.cpp | UTF-8 | 735 | 3.1875 | 3 | [] | no_license | class Solution {
public:
int minimumLength(string s) {
if(s == "")
return 0;
if(s.size() == 1)
return 1;
/*while( s.size() > 1 && s.front() == s.back())
{
char a = s.front();
while(s.size()!=0 && s.front() == a )
s.erase(0,1);
while(s.size()!=0 && s.back() == a)
s.pop_back();
}*/
int l = 0;
int r = s.size()-1;
while(s[l] == s[r] && r-l>0)
{
char a = s[l];
while(r>=l && s[l] == a)
++l;
while(r>=l && s[r] == a)
--r;
}
cout << "l:"<<l<<" r:"<<r<<endl;
return r-l+1;
}
}; | true |
f393403e6e9ae737d4955ef7cf587429f89aa565 | C++ | thorstel/Advent-of-Code-2017 | /src/day11.cpp | UTF-8 | 1,661 | 3.4375 | 3 | [
"MIT"
] | permissive | #include <tuple>
#include "default_includes.hpp"
#include "solution.hpp"
// Using the "3D" cube representation for the hex grid, the distance
// between two positions is
//
// d = max(|x2 - x1|, |y2 - y1|, |z2 - z1|).
//
// Since we start at position (0, 0, 0), we only need the end position
// to determine the distance.
static constexpr int distance(const std::tuple<int, int, int>& pos)
{
const auto [x, y, z] = pos;
return std::max({std::abs(x), std::abs(y), std::abs(z)});
}
template<>
void solve<Day11>(std::istream& ins, std::ostream& outs)
{
if (!ins.good())
{
outs << "Failed to open input file!" << std::endl;
return;
}
// this step is to strip some potential whitespaces, not really
// needed for a 'clean' input.
std::string input;
ins >> input;
const std::unordered_map<std::string, std::tuple<int, int, int>> deltas {{
{"n", {-1, 1, 0}}, {"ne", {0, 1, -1}}, {"nw", {-1, 0, 1}},
{"s", { 1, -1, 0}}, {"sw", {0, -1, 1}}, {"se", { 1, 0, -1}}
}};
const std::tuple<int, int, int> start {0, 0, 0};
std::tuple<int, int, int> pos {start};
std::istringstream iss {input};
int max_dist {0};
for (std::string dir; std::getline(iss, dir, ',');)
{
const auto [x, y, z] = deltas.at(dir);
std::get<0>(pos) += x;
std::get<1>(pos) += y;
std::get<2>(pos) += z;
max_dist = std::max(max_dist, distance(pos));
}
outs << "(Part 1) Distance = " << distance(pos) << std::endl
<< "(Part 2) Max distance = " << max_dist << std::endl;
}
| true |
3d15d16964dc9fd2e0727001d4d934473aa21606 | C++ | Shubhamag12/Data-Structures-and-Algorithms | /codeforces/gcdSum.cpp | UTF-8 | 521 | 2.671875 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int gcd(int a, int b){
if(b==0)
return a;
gcd(max(a-b,b),min(a-b,b));
}
int count(int n){
int su=0;
while(n!=0){
su+=n%10;
n=n/10;
}
return su;
}
int main(){
int n;
cin>>n;
int sum=0;
sum=count(n);
int y;
y=gcd(n,sum);
if(y!=1)
cout<< n;
else{
while(y==1){
n++;
sum=count(n);
y=gcd(n,sum);
}
cout<< n;
}
} | true |
35aed3f7f516b6e887695fd3c90d928aa538f560 | C++ | BhushanSure/BhushanLearning | /C++/OOPS/Deep_Copy/deep.h | UTF-8 | 942 | 3.328125 | 3 | [] | no_license | #ifndef DEEP_H
#define DEEP_H
#include <iostream>
#include <cassert>
#include <cstring>
/*
One answer to shallow copy problem in case of dynamically allocated variable is to do a deep copy
on any non-null pointers being copied. A deep copy allocates memory for the copy and then copies
the actual value, so that the copy lives in distinct memory from the source. This way, the copy
and source are distinct and will not affect each other in any way. Doing deep copies requires that
we write our own copy constructors and overloaded assignment operators.
*/
class Deep
{
private:
char *m_data;
int m_length;
public:
void deepCopy(const Deep& source);
// Copy constructor
Deep(const Deep& source);
// Assignment operator
Deep& operator=(const Deep & source);
// destructor
~Deep();
//Constructor
Deep(const char *source = "");
char *getString();
int getLength();
};
#endif // DEEP_H
| true |
043a3112d7f3f18d1f826fc36fb43a0bfd721fad | C++ | jc4250/coding | /ccl/flatten-a-multilevel-doubly-linked-list.cpp | UTF-8 | 825 | 3.484375 | 3 | [] | no_license | //https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list/
/*
// Definition for a Node.
class Node {
public:
int val;
Node* prev;
Node* next;
Node* child;
};
*/
class Solution {
public:
stack<Node *> st;
void flattenList(Node* head) {
if (head == NULL) return;
if (head->next == NULL && !st.empty()) {
head->next = st.top();
head->next->prev = head;
st.pop();
}
if (head->child != NULL) {
if (head->next != NULL) st.push(head->next);
head->next = head->child;
head->next->prev = head;
head->child = NULL;
}
flattenList(head->next);
}
Node* flatten(Node* head) {
flattenList(head);
return head;
}
}; | true |
84c7fe4a7bfafa81f53af69c87d4859c672be0cb | C++ | Checkmate50/posit-arith | /double_suite/add_test.cpp | UTF-8 | 7,141 | 2.8125 | 3 | [] | no_license | #include "../src/util.hpp"
#include <iostream>
#include <fstream>
#include <random>
#include <filesystem>
#include <fenv.h>
namespace fs = std::filesystem;
const int RANDOM_COUNT = 1024;
std::string genplus(double d1, double d2) {
return double_op("\"+\"", d1, d2, d1 + d2);
}
template<typename T>
void generate_rounding_function(std::ofstream& ofile, T f) {
const int originalRounding = fegetround();
fesetround(FE_TONEAREST);
ofile << "rounding_mode = \"TONEAREST\"\n";
f(ofile);
fesetround(FE_TOWARDZERO);
ofile << "rounding_mode = \"TOWARDZERO\"\n";
f(ofile);
fesetround(FE_UPWARD);
ofile << "rounding_mode = \"UPWARD\"\n";
f(ofile);
fesetround(FE_DOWNWARD);
ofile << "rounding_mode = \"DOWNWARD\"\n";
f(ofile);
fesetround(originalRounding);
}
template<typename T>
void generate_rounding_function(std::ofstream& ofile, T f, std::mt19937_64& eng,
std::uniform_int_distribution<unsigned long long>& distr) {
const int originalRounding = fegetround();
fesetround(FE_TONEAREST);
ofile << "rounding_mode = \"TONEAREST\"\n";
f(ofile, eng, distr);
fesetround(FE_TOWARDZERO);
ofile << "rounding_mode = \"TOWARDZERO\"\n";
f(ofile, eng, distr);
fesetround(FE_UPWARD);
ofile << "rounding_mode = \"UPWARD\"\n";
f(ofile, eng, distr);
fesetround(FE_DOWNWARD);
ofile << "rounding_mode = \"DOWNWARD\"\n";
f(ofile, eng, distr);
fesetround(originalRounding);
}
void generate_basics(std::ofstream& ofile) {
ofile << genplus(1., 1.);
ofile << genplus(1., 2.);
ofile << genplus(2., 1.);
ofile << genplus(-1., 1.);
ofile << genplus(1., -1.);
ofile << genplus(-1., -2.);
ofile << genplus(-.2, -.1);
ofile << genplus(.10001, .1);
ofile << genplus(.10001, -.1000001);
ofile << genplus(.1000000000000000001, .10000000000000001); // actually equal
ofile << genplus(-.01, -.011);
ofile << genplus(100.123, -100.124); // some rounding required
ofile << genplus(123.321, 123.321);
ofile << genplus(-123.3211, 123.321);
ofile << genplus(1.001e64, -1e64); // big lads
ofile << genplus(1.001e-64, 1e-64); // smol lads
ofile << genplus(-1.001e-64, -1e-64);
ofile << '\n';
}
void generate_rounding_basics(std::ofstream& ofile) {
generate_rounding_function(ofile, generate_basics);
}
void generate_exceptionals(std::ofstream& ofile) {
ofile << genplus(0., 0.);
ofile << genplus(-0., 0.); // -0 shenanigans
ofile << genplus(.1, -0.);
ofile << genplus(get_double_inf(), get_double_inf()); // infinity shenanigans
ofile << genplus(get_double_neginf(), get_double_inf());
ofile << genplus(get_double_inf(), get_double_neginf());
ofile << genplus(get_double_neginf(), get_double_inf());
ofile << genplus(get_double_max(), get_double_min()); // minimum/maximum
ofile << genplus(get_double_max(), get_double_inf());
ofile << genplus(get_double_min(), get_double_neginf());
ofile << genplus(get_double_max(), get_double_max());
ofile << genplus(get_double_min(), -get_double_min());
ofile << genplus(get_double_nan(), get_double_nan()); // basic nan
ofile << genplus(get_double_nan(), get_double_inf());
ofile << genplus(get_double_nan(), get_double_neginf());
ofile << genplus(get_double_nan(), -0.);
ofile << genplus(ll_to_double(0xFFFFFFFFFFFFFFFFull), ll_to_double(0xFFFFFFFFFFFFFFFFull)); // stupid nan encodings
ofile << genplus(ll_to_double(0x7FFFFFFFFFFFFFFFull), ll_to_double(0xFFFFFFFFFFFFFFFFull));
ofile << genplus(ll_to_double(0xFFFFFFFFFFFFFFFFull), get_double_inf());
ofile << genplus(ll_to_double(0x7FFFFFFFFFFFFFFFull), ll_to_double(0x3FFFFFFFFFFFFFFFull));
ofile << genplus(ll_to_double(0x8000000000000000ull), 0); // I think this is just -0, but let's check (it is!)
ofile << '\n';
}
void generate_rounding_exceptionals(std::ofstream& ofile) {
generate_rounding_function(ofile, generate_exceptionals);
}
void generate_full_random(std::ofstream& ofile, std::mt19937_64& eng,
std::uniform_int_distribution<unsigned long long>& distr) {
for (int i = 0; i < RANDOM_COUNT; i++)
ofile << genplus(get_full_double_random(distr, eng), get_full_double_random(distr, eng));
ofile << '\n';
}
void generate_rounding_full_random(std::ofstream& ofile, std::mt19937_64& eng,
std::uniform_int_distribution<unsigned long long>& distr) {
generate_rounding_function(ofile, generate_full_random, eng, distr);
}
void generate_smol_random(std::ofstream& ofile, std::mt19937_64& eng,
std::uniform_int_distribution<unsigned long long>& distr) {
for (int i = 0; i < RANDOM_COUNT; i++)
ofile << genplus(get_smol_double_random(distr, eng), get_smol_double_random(distr, eng));
ofile << '\n';
}
void generate_rounding_smol_random(std::ofstream& ofile, std::mt19937_64& eng,
std::uniform_int_distribution<unsigned long long>& distr) {
generate_rounding_function(ofile, generate_smol_random, eng, distr);
}
void generate_medium_random(std::ofstream& ofile, std::mt19937_64& eng,
std::uniform_int_distribution<unsigned long long>& distr) {
for (int i = 0; i < RANDOM_COUNT; i++)
ofile << genplus(get_medium_double_random(distr, eng), get_medium_double_random(distr, eng));
ofile << '\n';
}
void generate_rounding_medium_random(std::ofstream& ofile, std::mt19937_64& eng,
std::uniform_int_distribution<unsigned long long>& distr) {
generate_rounding_function(ofile, generate_medium_random, eng, distr);
}
void generate_large_random(std::ofstream& ofile, std::mt19937_64& eng,
std::uniform_int_distribution<unsigned long long>& distr) {
for (int i = 0; i < RANDOM_COUNT; i++)
ofile << genplus(get_large_double_random(distr, eng), get_large_double_random(distr, eng));
ofile << '\n';
}
void generate_rounding_large_random(std::ofstream& ofile, std::mt19937_64& eng,
std::uniform_int_distribution<unsigned long long>& distr) {
generate_rounding_function(ofile, generate_large_random, eng, distr);
}
int main() {
try {
if (!fs::is_directory("../test_bin") || !fs::exists("../test_bin")) { // Check if src folder exists
fs::create_directory("../test_bin"); // create src folder
}
std::ofstream ofile;
ofile.open("../test_bin/double_add_test.py");
{
ofile << get_python_header();
generate_rounding_basics(ofile);
generate_rounding_exceptionals(ofile);
auto eng = setup_random();
std::uniform_int_distribution<unsigned long long> distr;
generate_rounding_full_random(ofile, eng, distr);
generate_rounding_smol_random(ofile, eng, distr);
generate_rounding_medium_random(ofile, eng, distr);
generate_rounding_large_random(ofile, eng, distr);
}
ofile.close();
std::cout << "add_test SUCCESS" << std::endl;
} catch (const std::exception& ex) {
std::cout << "add_test FAILED" << std::endl;
std::cout << ex.what() << std::endl;
}
} | true |
b80fdfcf64f0bcb965cd467cc615d91f31da03da | C++ | BarryChenZ/LeetCode2 | /P229_MajorityElement_II.cpp | UTF-8 | 743 | 2.78125 | 3 | [] | no_license | class Solution {
public:
vector<int> majorityElement(vector<int>& nums) {
if(nums.size() <= 1) return nums;
vector<int> ans;
unordered_map<int,int> m;
int times = nums.size()/3;
for(int i = 0; i < nums.size(); i++){
if(m.find(nums[i]) == m.end()){
m[nums[i]] = 1;
if(m[nums[i]] > times) {
ans.push_back(nums[i]);
m[nums[i]] = -INT_MAX;
}
}
else{
m[nums[i]]++;
if(m[nums[i]] > times) {
ans.push_back(nums[i]);
m[nums[i]] = -INT_MAX;
}
}
}
return ans;
}
};
| true |
1c3aac3179031a7a5c04b0de2997cc881fa67f1b | C++ | s0metimes/aligothm | /week2/1541_lostBracket/1541_lostBracket_youngwoo.cpp | UTF-8 | 783 | 2.71875 | 3 | [] | no_license | #include <stdio.h>
#define MAX 50
char form[MAX+1];
int main(int argc, char const *argv[])
{
int i, len;
bool afterMinus = false;
scanf("%s", form);
for(i = 0; form[i] != '\0'; i++) {
len++;
if(afterMinus && form[i] == '+') form[i] = '-';
else if(form[i] == '-') afterMinus = true;
}
int sum = 0;
int num = 0;
int cnt = 1;
for(i = len - 1; i >= 0; i--) {
if(form[i] == '+') {
sum += num;
num = 0;
cnt = 1;
} else if(form[i] == '-') {
sum -= num;
num = 0;
cnt = 1;
} else {
num += (form[i]-'0') * cnt;
cnt *= 10;
}
}
sum += num;
printf("%d\n", sum);
return 0;
} | true |
f06ccda64ff56b41acbbcf38bb9c8f5ef8a14637 | C++ | leoxiaofei/uvpp | /include/uvpp/error.hpp | UTF-8 | 670 | 2.953125 | 3 | [
"MIT"
] | permissive | #pragma once
#include <stdexcept>
#include <string>
#include <uv.h>
#include <iostream>
namespace uvpp {
class Exception : public std::runtime_error
{
public:
Exception(const std::string& message)
: std::runtime_error(message)
{}
};
class Result
{
public:
Result(int c)
: m_error(c)
{
}
public:
operator bool() const
{
if (m_error != 0)
{
std::cout << "uv error: " << str() << std::endl;
}
return m_error == 0;
}
const char* str() const
{
return uv_strerror(m_error);
}
int error() const
{
return m_error;
}
bool success() const
{
return m_error == 0;
}
private:
int m_error;
};
}
| true |
c64897e64b2b86c4c363fc0196fc9828052d69d1 | C++ | lacarp99/NFL_Football_Source | /main.cpp | UTF-8 | 6,343 | 2.84375 | 3 | [] | no_license | #include <cstdio>
#include <cstdlib>
#include <iostream>
#include <random>
#include <time.h>
#include <fstream>
#include "readfromfile.h"
using namespace std;
int chosenTeam = 0;
int skill = NULL;
int slot;
int access = 1;
int tries = 3;
char createOrSignin;
string appdatapath;
string password;
struct newcoach {
string firstname;
string lastname;
} coach;
struct newTeam {
string quarterback;
string runningback;
string wideReceiver;
string tightEnd;
string lineBacker;
string offensiveLineman;
string defensiveLineman;
string cornerBack;
string safety;
int quarterbackskill;
int runningbackskill;
int wideReceiverskill;
int tightEndskill;
int lineBackerskill;
int offensiveLinemanskill;
int defensiveLinemanskill;
int cornerBackskill;
int safetyskill;
} team;
//Teams Names
const char* teams[] = {
"Arizona Cardinals",
"Atlanta Falcons",
"Baltimore Ravens",
"Buffalo Bills",
"Carolina Panthers",
"Chicago Bears",
"Cincinnati Bengals",
"Cleveland Browns",
"Dallas Cowboys",
"Denver Broncos",
"Detroit Lions",
"Green Bay Packers",
"Houston Texans",
"Indianapolis Colts",
"Jacksonville Jaguars",
"Kansas City Chiefs",
"Los Angeles Chargers",
"Los Angeles Rams",
"Miami Dolphins",
"Minnesota Vikings",
"New England Patriots",
"New Orleans Saints",
"New York Giants",
"New York Jets",
"Oakland Raiders",
"Philadelphia Eagles",
"Pittsburgh Steelers",
"San Francisco 49ers",
"Seattle Seahawks",
"Tampa Bay Buccaneers",
"Tennessee Titans",
"Washington Redskins",
};
//Possible Player Names
std::vector< string > names;
string encrypt(string input) {
string output;
const char* password = input.c_str();
for (int i = 0; password[i] != NULL; i++) {
output.push_back((char)((int)password[i] + 3));
}
return output;
}
string decrypt(string input) {
string output;
const char* password = input.c_str();
for (int i = 0; password[i] != NULL; i++) {
output.push_back((char)((int)password[i] - 3));
}
return output;
}
int main(int nNumberofArgs, char* pszArgs[])
{
//Setup
appdatapath = appData()+"NFL_Football\\";
cout << appdatapath << endl;
srand(time(NULL));
while (access != 2 && access != 4) {
if (access == 1 && tries >= 3) {
cout << "Sign in to your account or create a new one. [S/N]: " << endl;
cin >> createOrSignin;
cout << "What slot would you like to use? 1-3: ";
cin >> slot;
access = 1;
tries = 0;
}
if (((createOrSignin == 'S' || createOrSignin == 's') && access == 1) && tries <= 3) {
cout << "Password: ";
cin >> password;
if (decrypt(getStrings(appdatapath+"passwords.txt")[slot - 1]) == password) {
cout << "Access granted." << endl;
access = 2;
}
else {
cout << "Access denied." << endl;
access = 1;
tries++;
}
}
else if (createOrSignin == 'N' || createOrSignin == 'n') {
access = 4;
cout << "WARNING! Any data that was on this slot will be removed. Be sure this is the correct slot before creating a new password and team." << endl;
cout << "What would you like the password to be? ";
cin >> password;
switch (slot)
{
case 1:
writeStrings(appdatapath+"passwords.txt", vector< string > { encrypt(password), getStrings(appdatapath+"passwords.txt")[1], getStrings(appdatapath+"passwords.txt")[2] }, 3);
break;
case 2:
writeStrings(appdatapath+"passwords.txt", vector< string > { getStrings(appdatapath+"passwords.txt")[0], encrypt(password), getStrings(appdatapath+"passwords.txt")[2] }, 3);
break;
case 3:
writeStrings(appdatapath+"passwords.txt", vector< string > { getStrings(appdatapath+"passwords.txt")[1], getStrings(appdatapath+"passwords.txt")[2], encrypt(password) }, 3);
break;
}
}
}
if (access == 4) {
//Welcome Player
cout << "Welcome to NFL Football! Select a team from the following list:" << endl;
for (int i = 0; teams[i] != NULL; i++) {
cout << i + 1 << ". " << teams[i] << endl;
}
//Get player's team of choice
cout << endl << "Type the number of the team you would like to play as: ";
cin >> chosenTeam;
cout << "You chose: " << teams[chosenTeam - 1] << endl;
//Get name of player (coach)
cout << "What is the name of your coach?" << endl;
cout << "Coach: ";
cin >> coach.firstname;
cin >> coach.lastname;
cout << "Welcome Coach " << coach.lastname << " we're glad to have you here with the " << teams[chosenTeam - 1] << endl;
//Create team and save random names
for (int i = 0; i < 100; i++) {
names.push_back(getStrings(appdatapath + "personNames.txt")[i]);
}
team.quarterbackskill = rand() % 3;
srand(time(NULL));
team.runningbackskill = rand() % 3;
srand(time(NULL));
team.wideReceiverskill = rand() % 3;
srand(time(NULL));
team.tightEndskill = rand() % 3;
srand(time(NULL));
team.offensiveLinemanskill = rand() % 3;
srand(time(NULL));
team.lineBackerskill = rand() % 3;
srand(time(NULL));
team.defensiveLinemanskill = rand() % 3;
srand(time(NULL));
team.cornerBackskill = rand() % 3;
srand(time(NULL));
team.safetyskill = rand() % 3;
srand(time(NULL));
team.quarterback = names[ rand() % 99];
srand(time(NULL));
team.runningback = names[ rand() % 99];
srand(time(NULL));
team.wideReceiver = names[ rand() % 99];
srand(time(NULL));
team.tightEnd = names[ rand() % 99];
srand(time(NULL));
team.offensiveLineman = names[ rand() % 99];
srand(time(NULL));
team.lineBacker = names[ rand() % 99];
srand(time(NULL));
team.defensiveLineman = names[ rand() % 99];
srand(time(NULL));
team.cornerBack = names[ rand() % 99];
srand(time(NULL));
team.safety = names[ rand() % 99];
cout << "QB " << team.quarterback << " : " << team.quarterbackskill << endl;
cout << "RB " << team.runningback << " : " << team.runningbackskill << endl;
cout << "WR " << team.wideReceiver << " : " << team.wideReceiverskill << endl;
cout << "TE " << team.tightEnd << " : " << team.tightEndskill << endl;
cout << "OL " << team.offensiveLineman << " : " << team.offensiveLinemanskill << endl;
cout << "LB " << team.lineBacker << " : " << team.lineBackerskill << endl;
cout << "DL " << team.defensiveLineman << " : " << team.defensiveLinemanskill << endl;
cout << "CB " << team.cornerBack << " : " << team.cornerBackskill << endl;
cout << "S " << team.safety << " : " << team.safetyskill << endl;
}
//start game normally
return 0;
} | true |
6ade832078003a97beda6eeb8dac82296bcd58ac | C++ | VitoCastellana/SHAD | /include/shad/data_structures/object_identifier.h | UTF-8 | 8,974 | 2.65625 | 3 | [
"Apache-2.0"
] | permissive | //===------------------------------------------------------------*- C++ -*-===//
//
// SHAD
//
// The Scalable High-performance Algorithms and Data Structure Library
//
//===----------------------------------------------------------------------===//
//
// Copyright 2018 Battelle Memorial Institute
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy
// of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.
//
//===----------------------------------------------------------------------===//
#ifndef INCLUDE_SHAD_DATA_STRUCTURES_OBJECT_IDENTIFIER_H_
#define INCLUDE_SHAD_DATA_STRUCTURES_OBJECT_IDENTIFIER_H_
#include <atomic>
#include <limits>
#include "shad/runtime/runtime.h"
namespace shad {
/// @brief The ObjectIdentifier.
///
/// The most significant 12bits store the id of the Locality
/// where the object has been created. The remaining 48bits contain a unique
/// number identifying the object.
///
/// @warning Enforcing the previous policy is not responsibility of
/// ObjectIdentifier but of its users.
///
/// @tparam T The type of the object that must be uniquely identified.
template <typename T>
class ObjectIdentifier {
public:
/// Null value for the ObjectIdentifier. This value is used during
/// ObjectIdentifier creation when the ID can't be known yet or the ID is
/// invalid.
static const ObjectIdentifier<T> kNullID;
/// The number of bits used to store the Locality where the Object is stored.
static constexpr uint8_t kLocalityIdBitsize = 16u;
/// The number of bits in the RowID used for the row identifier in each
/// Locality.
static constexpr uint8_t kIdentifierBitsize = 48u;
/// @brief Constructor.
explicit constexpr ObjectIdentifier(uint64_t id) : id_(id) {}
/// @brief Constructor.
/// @param[in] locality The locality identifier part.
/// @param[in] localID The local identifier part.
ObjectIdentifier(const rt::Locality &locality, uint64_t localID) {
id_ = static_cast<uint32_t>(locality);
id_ <<= kIdentifierBitsize;
id_ |= localID;
}
/// @brief Copy Constructor
ObjectIdentifier(const ObjectIdentifier &oid) = default;
/// @brief Move constructor
ObjectIdentifier(ObjectIdentifier &&) noexcept = default;
/// @brief Move assignment
ObjectIdentifier &operator=(ObjectIdentifier &&) noexcept = default;
/// @brief Operator less than.
///
/// @param[in] lhs Left hand side of the operator.
/// @param[in] rhs Right hand side of the operator.
/// @return true if lhs < rhs, false otherwise.
friend bool operator<(const ObjectIdentifier &lhs,
const ObjectIdentifier &rhs) {
return lhs.id_ < rhs.id_;
}
/// @brief Assignment operator.
///
/// @param[in] rhs Right hand side of the operator.
ObjectIdentifier &operator=(const ObjectIdentifier &rhs) = default;
/// @brief Conversion operator to uint64_t
explicit operator uint64_t() const { return static_cast<uint64_t>(id_); }
/// @brief Get the Locality owing the Object.
/// @return The Locality owing the Object.
rt::Locality GetOwnerLocality() const {
return rt::Locality(uint32_t(id_ >> kIdentifierBitsize));
}
/// Get the Local part of the ObjectIdentifier.
///
/// @return The lowest ObjectIdentifier::kIdentifierBitsize bits of the
/// ObjectID.
size_t GetLocalID() const { return id_ & kIdentifierBitMask; }
private:
/// The Bitmask used to estract the Object Identifier.
static constexpr uint64_t kIdentifierBitMask =
((uint64_t(1) << kIdentifierBitsize) - 1);
uint64_t id_;
};
template <typename T>
const ObjectIdentifier<T> ObjectIdentifier<T>::kNullID =
ObjectIdentifier<T>(std::numeric_limits<uint64_t>::max());
template <typename T>
constexpr uint8_t ObjectIdentifier<T>::kIdentifierBitsize;
template <typename T>
constexpr uint64_t ObjectIdentifier<T>::kIdentifierBitMask;
/// @brief Operator greater than.
///
/// @tparam T The type of Object to which the identifier refers.
///
/// @param[in] lhs Left hand side of the operator.
/// @param[in] rhs Right hand side of the operator.
/// @return true if lhs > rhs, false otherwise.
template <typename T>
inline bool operator>(const ObjectIdentifier<T> &lhs,
const ObjectIdentifier<T> &rhs) {
return rhs < lhs;
}
/// @brief Operator less than or equal.
///
/// @tparam T The type of Object to which the identifier refers.
///
/// @param[in] lhs Left hand side of the operator.
/// @param[in] rhs Right hand side of the operator.
/// @return true if lhs <= rhs, false otherwise.
template <typename T>
inline bool operator<=(const ObjectIdentifier<T> &lhs,
const ObjectIdentifier<T> &rhs) {
return !(lhs > rhs);
}
/// @brief Operator greater than or equal.
///
/// @tparam T The type of Object to which the identifier refers.
///
/// @param[in] lhs Left hand side of the operator.
/// @param[in] rhs Right hand side of the operator.
/// @return true if lhs >= rhs, false otherwise.
template <typename T>
inline bool operator>=(const ObjectIdentifier<T> &lhs,
const ObjectIdentifier<T> &rhs) {
return !(lhs < rhs);
}
/// @brief Operator equal.
///
/// @tparam T The type of Object to which the identifier refers.
///
/// @param[in] lhs Left hand side of the operator.
/// @param[in] rhs Right hand side of the operator.
/// @return true if lhs == rhs, false otherwise.
template <typename T>
inline bool operator==(const ObjectIdentifier<T> &lhs,
const ObjectIdentifier<T> &rhs) {
return !(rhs < lhs) && !(lhs < rhs);
}
/// @brief Operator not equal.
///
/// @tparam T The type of Object to which the identifier refers.
///
/// @param[in] lhs Left hand side of the operator.
/// @param[in] rhs Right hand side of the operator.
/// @return true if lhs != rhs, false otherwise.
template <typename T>
inline bool operator!=(const ObjectIdentifier<T> &lhs,
const ObjectIdentifier<T> &rhs) {
return !(lhs == rhs);
}
/// @brief Output operator to streams.
///
/// @tparam T The type of Object to which the identifier refers.
///
/// @param[in] out The output stream.
/// @param[in] rhs Right hand side of the operator.
/// @return A reference to the used output stream.
template <typename T>
std::ostream &operator<<(std::ostream &out, const ObjectIdentifier<T> &rhs) {
auto node = rhs.GetOwnerLocality();
size_t objectId = rhs.GetLocalID();
return out << "NodeOwner[" << node << "] id = " << objectId;
}
/// @brief Object representing counters to obtain object IDs.
///
/// The ObjectIdentifier counter enforces that the most significant 12bits store
/// the id of the Locality where the object has been created. The remaining
/// 48bits contain a unique number identifying the object.
template <typename T>
class ObjectIdentifierCounter {
public:
/// @brief Get the singleton instance of the counter for the type T.
/// @return A reference to the singleton counter object for the type T.
static ObjectIdentifierCounter<T> &Instance() {
static ObjectIdentifierCounter<T> instance;
return instance;
}
/// @brief Operator post-increment.
ObjectIdentifier<T> operator++(int) {
uint64_t value = counter_.fetch_add(1);
return ObjectIdentifier<T>(value);
}
/// @brief Conversion operator to uint64_t
explicit operator uint64_t() const { return static_cast<uint64_t>(counter_); }
private:
ObjectIdentifierCounter() {
// note that in the following, the cast to uint32_t invokes the conversion
// operator of the rt::thisLocality object, but we need a uint64_t.
counter_ = static_cast<uint64_t>(static_cast<uint32_t>(rt::thisLocality()))
<< ObjectIdentifier<T>::kIdentifierBitsize;
}
std::atomic<uint64_t> counter_;
};
/// Output operator to streams.
///
/// @tparam T The type of Object to which the identifier refers.
///
/// @param[out] out The output stream.
/// @param[in] rhs Right hand side of the operator.
/// @return A reference to the used output stream.
template <typename T>
std::ostream &operator<<(std::ostream &out,
const ObjectIdentifierCounter<T> &rhs) {
uint64_t objectIdentifier = static_cast<uint64_t>(rhs);
uint64_t node = objectIdentifier >> ObjectIdentifier<T>::kIdentifierBitsize;
uint64_t objectId =
ObjectIdentifier<T>::kIdentifierBitMask & objectIdentifier;
return out << "NodeOwner[" << node << "] id = " << objectId;
}
} // namespace shad
#endif // INCLUDE_SHAD_DATA_STRUCTURES_OBJECT_IDENTIFIER_H_
| true |
79eba4e5a51b0474cadaf5e9e75eda6ef9cb95e4 | C++ | pingany/poj | /1067/3344535_WA.cc | UTF-8 | 239 | 2.921875 | 3 | [] | no_license | #include<iostream>
#include<cstdio>
using namespace std;
int p(int x,int y)
{
if(x==y || x==0 || y==0)return 1;
if((x-y)%2==0)return 1;
return 0;
}
int main()
{
int x,y;
while(cin>>x>>y)cout<<p(x,y)<<"\n";
return 0;
} | true |
36968821452e97b27b8d8b242b538d8ec714df63 | C++ | ELUMI/elumi-raytracer | /src/raytracer/AccDataStructImpl/HashDataStruct.cpp | UTF-8 | 3,439 | 2.5625 | 3 | [] | no_license | /*
* HashDataStruct.cpp
*
* Created on: Mar 23, 2012
* Author: ulvinge
*/
#include "HashDataStruct.h"
#include "HashDataStruct.h"
#include "ArrayDataStruct.h"
#include <vector>
using namespace std;
#include <glm/glm.hpp>
using namespace glm;
namespace raytracer {
HashDataStruct::HashDataStruct(float bucketsize, size_t n_buckets)
: hashpoint(bucketsize, n_buckets) {
}
HashDataStruct::~HashDataStruct() {
}
void getMaxMin(Triangle* t, vec3& min, vec3& max){
vector<vec3*> vertices = t->getVertices();
min= *(vertices[0]);
max= *(vertices[0]);
for(size_t j=1; j<vertices.size(); ++j){
min = glm::min(min, *(vertices[j]));
max = glm::max(max, *(vertices[j]));
}
}
void HashDataStruct::setData(Triangle** triangles,size_t size,AABB aabb){
for(size_t i=0; i<size; ++i){
Triangle* t = triangles[i];
vec3 min,max;
getMaxMin(t, min, max);
//hashpoint.addGrid(min, max, t);
float bucketsize = hashpoint.getBucketSize();
for(float x=min.x; x<max.x+bucketsize; x+=bucketsize){
for(float y=min.y; y<max.y+bucketsize; y+=bucketsize){
for(float z=min.z; z<max.z+bucketsize; z+=bucketsize){
HashedTriangle i;
size_t has2 = size_t(x / hashpoint.getBucketSize())
+(1<<10)*size_t(y / hashpoint.getBucketSize())
+(1<<(2*10))*size_t(z / hashpoint.getBucketSize());
i.hash = has2;
i.triangle = t;
hashpoint.addItem(vec3(x,y,z), i);
}
}
}
}
}
float getTMax(float p, float dir, float size){
if(dir > 0) {
return (1-mod(p,size))/dir;
} else {
return mod(p,size)/-dir;
}
}
IAccDataStruct::IntersectionData HashDataStruct::findClosestIntersection(Ray ray){
vec3 point = ray.getPosition();
vec3 dir = ray.getDirection();
float bucketsize = hashpoint.getBucketSize();
//http://www.cse.yorku.ca/~amana/research/grid.pdf
vec3 step = glm::sign(dir);
vec3 max;
max.x = getTMax(point.x, dir.x, bucketsize);
max.y = getTMax(point.y, dir.y, bucketsize);
max.z = getTMax(point.z, dir.z, bucketsize);
vec3 delta = vec3(bucketsize/dir.x, bucketsize/dir.y, bucketsize/dir.z);
ArrayDataStruct ads;
size_t length = size_t(10.0f/bucketsize); //some hueristic
while(--length) {
size_t hash = hashpoint.hash(point);
size_t has2 = size_t(point.x / hashpoint.getBucketSize())
+(1<<10)*size_t(point.y / hashpoint.getBucketSize())
+(1<<(2*10))*size_t(point.z / hashpoint.getBucketSize());
vector<HashedTriangle> list = hashpoint.getBucket(hash);
vector<Triangle*> goodlist;
for(size_t i=0; i<list.size(); ++i){
if(list[i].hash == has2) {
//goodlist.push_back(list[i].triangle);
}
goodlist.push_back(list[i].triangle);
}
if(goodlist.size()){
ads.setData(goodlist.data(),goodlist.size(),AABB());
IAccDataStruct::IntersectionData idata = ads.findClosestIntersection(Ray(point,dir));
if(idata.missed()){
return idata;
}
}
if (max.x < max.y) {
if (max.x < max.z) {
point.x += step.x;
max.x += delta.x;
} else {
point.z += step.z;
max.z += delta.z;
}
} else {
if (max.y < max.z) {
point.y += step.y;
max.y += delta.y;
} else {
point.z += step.z;
max.z += delta.z;
}
}
}
//not found
return IntersectionData::miss();
}
}
| true |
887358a866f69d41f44401e31ca2302d00ac5d1e | C++ | stephaneduarte/P3D_1718 | /Cell.h | UTF-8 | 290 | 2.65625 | 3 | [] | no_license | #ifndef __CELL__
#define __CELL__
#include "Object.h"
#include <vector>
class Cell
{
private:
std::vector<Object*> _objects;
BoundingBox * _bb;
public:
Cell();
~Cell();
std::vector<Object*> getObjects();
BoundingBox * getBoundingBox();
void addObject(Object * object);
};
#endif | true |
11118e7d3eab755c97c57df318d2e66e69f4162d | C++ | michaelrboyd/esp8266 | /master_writer/master_writer.ino | UTF-8 | 1,285 | 2.796875 | 3 | [
"MIT"
] | permissive | // Wire Master Writer
// by devyte
// based on the example of the same name by Nicholas Zambetti <http://www.zambetti.com>
// Demonstrates use of the Wire library
// Writes data to an I2C/TWI slave device
// Refer to the "Wire Slave Receiver" example for use with this
// This example code is in the public domain.
#include <Wire.h>
#include <PolledTimeout.h>
#define SDA_PIN 4
#define SCL_PIN 5
const int16_t I2C_MASTER = 0x42;
const int16_t I2C_SLAVE = 0x08;
void setup() {
Wire.begin(SDA_PIN, SCL_PIN, I2C_MASTER); // join i2c bus (address optional for master)
Serial.begin(115200); // start serial for output
Serial.print(SDA_PIN);
Serial.print(SCL_PIN);
}
byte x = 0;
char myMsg[8] = "x is ";
void loop() {
using periodic = esp8266::polledTimeout::periodicMs;
static periodic nextPing(1000);
if (nextPing) {
Serial.print("ESP8266..Master Writer");
Wire.beginTransmission(I2C_SLAVE); // transmit to device #8
Wire.write(myMsg, sizeof(myMsg)); // sends five bytes
Wire.write(x); // sends one byte
Serial.print(myMsg);
Wire.endTransmission(); // stop transmitting
/* Serial.print(SDA_PIN);
Serial.print(SCL_PIN);
Serial.print(I2C_MASTER);
Serial.print(I2C_SLAVE);
*/ Serial.println(x);
x++;
}
}
| true |
53842e3eb1e8b3b3fae59a0cf58a729e59cc4d2b | C++ | weaverjm3/JW_info_450_spring_2019 | /week2/practice2/practice2/practice2.cpp | UTF-8 | 477 | 3.65625 | 4 | [] | no_license | #include "pch.h"
#include <iostream>
using namespace std;
int main()
{
int i = 0;
int count = 0;
int num;
for (;;)
{
cout << "Please enter a number to find out if it is prime! (Enter 0 to quit): ";
cin >> num;
if (num == 0)
{
break;
}
else
{
for (i = 2; i < num; i++)
if (num % i == 0)
count++;
}
if (count > 1)
{
cout << "This is not a prime number" << endl;
}
else
{
cout << " This is a prime number" << endl;
}
}
} | true |
74bfcf4532801719c43050f7259f6530fb2d719f | C++ | avishq/myCollegeProjects | /Improved ACO/Codes/tsp_bb.cpp | UTF-8 | 1,857 | 2.625 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <climits>
#include <algorithm>
#include <fstream>
using namespace std;
int d_min = INT_MAX;
vector <int> v;
vector <int> v1;
vector <vector <int> > vv;
void tsp(int a[][100], int n, int i, int col[], int t, int cd, int sum, int c[])
{
// for (int j = 0; j < v.size(); j++) {
// cout << v[j];
// }
// cout << "= " << t << endl;
if (i == 0 && t == n) {
if (cd < d_min) {
d_min = cd;
v1.clear();
vv.clear();
for (int j = 0; j < v.size(); j++) {
v1.push_back(v[j]);
}
vv.push_back(v1);
} else if (cd == d_min) {
v1.clear();
for (int j = 0; j < v.size(); j++) {
v1.push_back(v[j]);
}
vv.push_back(v1);
}
return;
}
if (i == 0 && t != n && t != 0) {
return;
}
for (int j = 0; j < n; j++) {
if (a[i][j] != 99 && col[j] != 1) {
// cout << "cd = " << cd << "sum = " << sum << "d_min" << endl;
if (cd + sum <= d_min) {
v.push_back(j);
col[j] = 1;
tsp(a, n, j, col, t + 1, cd + a[i][j], sum - c[j] / 2, c);
v.pop_back();
col[j] = 0;
}
}
}
}
int main()
{
int a[100][100];
int b[100];
int c[100];
int sum = 0;
int n = 14;
int col[100];
// cin >> n;
ifstream f;
f.open("Output.txt");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
// cin >> a[i][j];
f >> a[i][j];
b[j] = a[i][j];
}
col[i] = 0;
sort(b, b + n);
sum = sum + b[0] + b[1];
c[i] = b[0] + b[1];
cout << "min is : " << c[i] << endl;
}
sum = sum / 2;
tsp(a, n, 0, col, 0, 0, sum - c[0] / 2, c);
cout << endl;
cout << d_min << endl;
cout << endl;
for (int i = 0; i < vv.size(); i++) {
for (int j = 0; j < vv[i].size(); j++)
{
cout << vv[i][j] << " ";
}
cout << endl;
}
cout << endl;
}
| true |
90ccc4ef82cd7ec5d29caccc980bf9da99b3cc6c | C++ | amitkvikram/COMPETITIVE-PROGRAMMING | /codeforces/69A.cpp | UTF-8 | 419 | 2.515625 | 3 | [] | no_license | #include "bits/stdc++.h"
using namespace std;
int main(int argc, char const *argv[]) {
int n;
cin>>n;
int a=0, b=0, c=0;
int sum1=0, sum2=0, sum3=0;
for(int i=0; i<n; i++){
cin>>a>>b>>c;
sum1+=a;
sum2+=b;
sum3+=c;
}
if(sum1==0 && sum2==0 && sum3==0){
cout<<"YES";
}
else cout<<"NO";
return 0;
}
| true |
0fc06ee0bcffe1671311cffb7ca9d9cff1d67af6 | C++ | kingsenge/machine_learning--bayes | /mc_test.cpp | UTF-8 | 3,437 | 2.796875 | 3 | [] | no_license | #include<stdio.h>
#include<map>
#include<string>
using namespace std;
map<string,double> gWordsVector;
map<string,double> gWordsVectorIllegal;
static double gnLegal = 4;
static double gnIllegal = 1;
static double gnP = 0.8;
typedef struct
{
const char * pContent[10];
int nLegal;
int nNumber;
}STTRANS;
void init()
{
gWordsVector["select"]= 0;
gWordsVector["customNo"] = 0;
gWordsVector["sellNo"] = 0;
gWordsVector["rentNo"] = 0;
gWordsVector["from"] = 0;
gWordsVector["where"] = 0;
gWordsVector["amount"] = 0;
gWordsVector["sharding"] = 0;
gWordsVector["date"] = 0;
gWordsVector["table"] = 0;
gWordsVector["do"] = 0;
gWordsVector["buy"] = 0;
gWordsVector["book"] = 0;
gWordsVector["sale"] = 0;
gWordsVector["read"] = 0;
gWordsVectorIllegal = gWordsVector;
}
void CalcProbability(STTRANS* pstTrans,int nNumber,int nOption)
{
map<string,double>* pVector;
if(nOption == 0)
pVector = &gWordsVectorIllegal;
else
pVector = &gWordsVector;
map<string,double>::iterator oIter = pVector->begin();
for(;oIter!=pVector->end();oIter++)
{
double nCounter = 0;
for(int i = 0;i<nNumber;i++)
{
if(pstTrans[i].nLegal != nOption)
continue;
for(int j =0;j<pstTrans[i].nNumber;j++)
{
if(oIter->first.compare(pstTrans[i].pContent[j])!=0)
continue;
nCounter++;
break;
}
}
if(nOption == 1)
oIter->second = (nCounter+1)/(gnLegal+2);
else
oIter->second = (nCounter+1)/(gnIllegal+2);
}
}
void test()
{
const char *p[] = {"select","date","from","table","where"};
double nResult = 1;
map<string,double>::iterator oIter;
for(int i=0;i<5;i++)
{
oIter = gWordsVectorIllegal.find(p[i]);
if(oIter!=gWordsVectorIllegal.end())
{
nResult*=oIter->second;
}
}
double nMol = nResult*(1-gnP);
printf("%f",nMol);
nResult = 1;
for(int i =0;i<5;i++)
{
oIter = gWordsVector.find(p[i]);
nResult*=oIter->second;
}
double nDel= nResult*gnP;
double nFinal = nMol/(nMol+nDel);
printf("probability = %f",nFinal);
}
int main()
{
STTRANS stTrans[10];
stTrans[0].nLegal = 0;
stTrans[0].nNumber = 5;
stTrans[0].pContent[0]="select";
stTrans[0].pContent[1]="amount";
stTrans[0].pContent[2]="from";
stTrans[0].pContent[3]="table";
stTrans[0].pContent[4]="where";
stTrans[1].nLegal = 1;
stTrans[1].nNumber = 10;
stTrans[1].pContent[0] = "customNo";
stTrans[1].pContent[1] = "sharding";
stTrans[1].pContent[2] = "buy";
stTrans[1].pContent[3] = "do";
stTrans[1].pContent[4] = "book";
stTrans[1].pContent[5] = "sale";
stTrans[1].pContent[6] = "amount";
stTrans[1].pContent[7] = "rentNo";
stTrans[1].pContent[8] = "sellNo";
stTrans[1].pContent[9] = "date";
stTrans[2].nLegal = 1;
stTrans[2].nNumber = 5;
stTrans[2].pContent[0] = "read";
stTrans[2].pContent[1] = "sharding";
stTrans[2].pContent[2] = "buy";
stTrans[2].pContent[3] = "do";
stTrans[2].pContent[4] = "book";
stTrans[3].nLegal = 1;
stTrans[3].nNumber = 5;
stTrans[3].pContent[0] = "rentNo";
stTrans[3].pContent[1] = "sellNo";
stTrans[3].pContent[2] = "buy";
stTrans[3].pContent[3] = "sharding";
stTrans[3].pContent[4] = "date";
stTrans[4].nLegal = 1;
stTrans[4].nNumber = 5;
stTrans[4].pContent[0] = "bool";
stTrans[4].pContent[1] = "table";
stTrans[4].pContent[2] = "customNo";
stTrans[4].pContent[3] = "sale";
stTrans[4].pContent[4] = "do";
init();
CalcProbability(stTrans,5,1);
CalcProbability(stTrans,5,0);
test();
return 0;
}
| true |
99243ccdc67b3197422e0ba806ec21404309d695 | C++ | grighth12/algorithm | /HYJ/boj/BackTracking/boj1497.cpp | UHC | 1,233 | 2.984375 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <string>
#include <cmath>
using namespace std;
int N, M;
vector<long long> v;
int result, maxbit;
long long a = 1;
int countBit(long long bit) {
int result = 0;
while (bit) {
result += bit & 1;
bit >>= 1;
}
return result;
}
void DFS(int index, long long check_num, int count) {
// ϴ ̾ƴ϶!!,
// ִ ؾߵǴ .!!!!
int Y = countBit(check_num);
if (maxbit < Y) {
maxbit = Y;
result = count;
}
else if (maxbit == Y) {
result = min(result, count);
}
if (index >= N) return;
DFS(index + 1, check_num | v[index + 1], count + 1);
DFS(index + 1, check_num, count);
}
int main() {
cin >> N >> M;
v = vector<long long>(N + 1);
for (int i = 0; i < M; i++) {
a *= 2;
}
for (int i = 1; i <= N; i++) {
string str;
cin >> str;
string check;
cin >> check;
long long num_check = 0;
for (int j = 0; j < check.length(); j++) {
if (check[j] == 'Y') {
num_check = (num_check | (1LL << j));
}
}
v[i] = num_check;
}
for (int i = 1; i <= N; i++) {
DFS(i, v[i], 1);
}
if (result== 0) {
cout << -1 << "\n";
}
else {
cout << result;
}
return 0;
} | true |