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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
d5a198bd8b50c2a7e822b558e430c7ea428ea984 | C++ | TLeonardUK/ZombieGrinder | /Source/Generic/Math/Noise/Noise.cpp | UTF-8 | 3,511 | 3.078125 | 3 | [] | no_license | // ===================================================================
// Copyright (C) 2013 Tim Leonard
// ===================================================================
// A lot of the code in this file is based off code provided at;
// https://code.google.com/p/battlestar-tux/
// Full credit to them!
// ===================================================================
#include "Generic/Math/Noise/Noise.h"
float Noise::Sample_2D(float octaves, float persistence, float scale, float x, float y)
{
float total = 0;
float frequency = scale;
float amplitude = 1;
// We have to keep track of the largest possible amplitude,
// because each octave adds more, and we need a value in [-1, 1].
float maxAmplitude = 0;
for (int i = 0; i < octaves; i++)
{
total += Raw_Sample_2D(x * frequency, y * frequency) * amplitude;
frequency *= 2;
maxAmplitude += amplitude;
amplitude *= persistence;
}
return total / maxAmplitude;
}
float Noise::Sample_3D(float octaves, float persistence, float scale, float x, float y, float z)
{
float total = 0;
float frequency = scale;
float amplitude = 1;
// We have to keep track of the largest possible amplitude,
// because each octave adds more, and we need a value in [-1, 1].
float maxAmplitude = 0;
for (int i = 0; i < octaves; i++)
{
total += Raw_Sample_3D(x * frequency, y * frequency, z * frequency) * amplitude;
frequency *= 2;
maxAmplitude += amplitude;
amplitude *= persistence;
}
return total / maxAmplitude;
}
float Noise::Sample_4D(float octaves, float persistence, float scale, float x, float y, float z, float w)
{
float total = 0;
float frequency = scale;
float amplitude = 1;
// We have to keep track of the largest possible amplitude,
// because each octave adds more, and we need a value in [-1, 1].
float maxAmplitude = 0;
for (int i = 0; i < octaves; i++)
{
total += Raw_Sample_4D( x * frequency, y * frequency, z * frequency, w * frequency ) * amplitude;
frequency *= 2;
maxAmplitude += amplitude;
amplitude *= persistence;
}
return total / maxAmplitude;
}
float Noise::Sample_2D_In_Range(float octaves, float persistence, float scale, float loBound, float hiBound, float x, float y)
{
return Sample_2D(octaves, persistence, scale, x, y) * (hiBound - loBound) / 2 + (hiBound + loBound) / 2;
}
float Noise::Sample_3D_In_Range(float octaves, float persistence, float scale, float loBound, float hiBound, float x, float y, float z)
{
return Sample_3D(octaves, persistence, scale, x, y, z) * (hiBound - loBound) / 2 + (hiBound + loBound) / 2;
}
float Noise::Sample_4D_In_Range(float octaves, float persistence, float scale, float loBound, float hiBound, float x, float y, float z, float w)
{
return Sample_4D(octaves, persistence, scale, x, y, z, w) * (hiBound - loBound) / 2 + (hiBound + loBound) / 2;
}
float Noise::Raw_Sample_2D_In_Range(float loBound, float hiBound, float x, float y)
{
return Raw_Sample_2D(x, y) * (hiBound - loBound) / 2 + (hiBound + loBound) / 2;
}
float Noise::Raw_Sample_3D_In_Range(float loBound, float hiBound, float x, float y, float z)
{
return Raw_Sample_3D(x, y, z) * (hiBound - loBound) / 2 + (hiBound + loBound) / 2;
}
float Noise::Raw_Sample_4D_In_Range(float loBound, float hiBound, float x, float y, float z, float w)
{
return Raw_Sample_4D(x, y, z, w) * (hiBound - loBound) / 2 + (hiBound + loBound) / 2;
}
| true |
86de27b49f7f602fb2792c89bad66a5c2f4f7cdc | C++ | 0xc0dec/solo | /vendor/glm/0.9.8.4/glm/gtx/fast_square_root.inl | UTF-8 | 2,611 | 3.015625 | 3 | [
"Zlib"
] | permissive | /// @ref gtx_fast_square_root
/// @file glm/gtx/fast_square_root.inl
namespace glm
{
// fastSqrt
template <typename genType>
GLM_FUNC_QUALIFIER genType fastSqrt(genType x)
{
GLM_STATIC_ASSERT(std::numeric_limits<genType>::is_iec559, "'fastSqrt' only accept floating-point input");
return genType(1) / fastInverseSqrt(x);
}
template <typename T, precision P, template <typename, precision> class vecType>
GLM_FUNC_QUALIFIER vecType<T, P> fastSqrt(vecType<T, P> const & x)
{
return detail::functor1<T, T, P, vecType>::call(fastSqrt, x);
}
// fastInversesqrt
template <typename genType>
GLM_FUNC_QUALIFIER genType fastInverseSqrt(genType x)
{
# ifdef __CUDACC__ // Wordaround for a CUDA compiler bug up to CUDA6
tvec1<T, P> tmp(detail::compute_inversesqrt<tvec1, genType, lowp, detail::is_aligned<lowp>::value>::call(tvec1<genType, lowp>(x)));
return tmp.x;
# else
return detail::compute_inversesqrt<tvec1, genType, highp, detail::is_aligned<highp>::value>::call(tvec1<genType, lowp>(x)).x;
# endif
}
template <typename T, precision P, template <typename, precision> class vecType>
GLM_FUNC_QUALIFIER vecType<T, P> fastInverseSqrt(vecType<T, P> const & x)
{
return detail::compute_inversesqrt<vecType, T, P, detail::is_aligned<P>::value>::call(x);
}
// fastLength
template <typename genType>
GLM_FUNC_QUALIFIER genType fastLength(genType x)
{
GLM_STATIC_ASSERT(std::numeric_limits<genType>::is_iec559, "'fastLength' only accept floating-point inputs");
return abs(x);
}
template <typename T, precision P, template <typename, precision> class vecType>
GLM_FUNC_QUALIFIER T fastLength(vecType<T, P> const & x)
{
GLM_STATIC_ASSERT(std::numeric_limits<T>::is_iec559, "'fastLength' only accept floating-point inputs");
return fastSqrt(dot(x, x));
}
// fastDistance
template <typename genType>
GLM_FUNC_QUALIFIER genType fastDistance(genType x, genType y)
{
return fastLength(y - x);
}
template <typename T, precision P, template <typename, precision> class vecType>
GLM_FUNC_QUALIFIER T fastDistance(vecType<T, P> const & x, vecType<T, P> const & y)
{
return fastLength(y - x);
}
// fastNormalize
template <typename genType>
GLM_FUNC_QUALIFIER genType fastNormalize(genType x)
{
return x > genType(0) ? genType(1) : -genType(1);
}
template <typename T, precision P, template <typename, precision> class vecType>
GLM_FUNC_QUALIFIER vecType<T, P> fastNormalize(vecType<T, P> const & x)
{
return x * fastInverseSqrt(dot(x, x));
}
}//namespace glm
| true |
6a9ce067674c56fc43308dc97c62c077f2750c2e | C++ | acsearle/mania | /mania/capture.hpp | UTF-8 | 655 | 2.96875 | 3 | [] | no_license | //
// capture.hpp
// mania
//
// Created by Antony Searle on 7/8/19.
// Copyright © 2019 Antony Searle. All rights reserved.
//
#ifndef capture_hpp
#define capture_hpp
#include <tuple>
#include <utility>
namespace manic {
// Make a tuple that perfect-captures the arguments.
//
// If an argument is a (const) reference, the tuple will store a (const)
// reference. If the argument is an rvalue, the tuple will hold a move-
// constructed value.
template<typename... Args>
std::tuple<Args...> capture(Args&&... args) {
return std::tuple<Args...>(std::forward<Args>(args)...);
}
}
#endif /* capture_hpp */
| true |
12eecb8e9ec484d2957ac0f5b225d122efdee727 | C++ | 0000duck/FabEngine | /FabEngine/inc/Mouse.h | UTF-8 | 1,239 | 2.609375 | 3 | [] | no_license | #pragma once
#include <DirectXComponentsPCH.h>
#include "IComponent.h"
using namespace DirectX;
namespace Fab
{
enum class MouseButtonName
{
LEFT, RIGHT, MIDDLE, WHOLE
};
enum class MouseButtonState
{
PRESSED, RELEASED
};
struct MouseButton
{
MouseButtonName Name;
MouseButtonState State;
MouseButton(MouseButtonName name)
: Name(name)
, State(MouseButtonState::RELEASED)
{
}
bool MouseButton::operator==(MouseButtonName name) const {
return name == Name;
}
};
class Mouse : public IComponent {
public:
Mouse();
~Mouse();
void Update(MSG* message, float deltaTime, float totalTime);
void Initialise() override;
float GetDistanceX();
float GetDistanceY();
XMFLOAT2 GetPosition();
MouseButtonState GetState(MouseButtonName name);
private:
void UpdateState(MouseButtonName name, MouseButtonState state);
private:
D3D11RenderSystem& _renderSystem;
XMFLOAT2 _position;
XMFLOAT2 _oldPosition;
XMFLOAT2 _centerPosition;
float _distanceX;
float _distanceY;
std::vector<MouseButton> _mouseButtons;
};
} | true |
011adc5dd6861d97655dc299b2156e8dba745a31 | C++ | jvujcic/RP1 | /Cetvrtak/Vjezbe03/copy_konstruktor.cpp | UTF-8 | 946 | 3.390625 | 3 | [] | no_license | #include <iostream>
#include <cstring>
using namespace std;
struct MyString {
char *str;
MyString() {
str = new char[1];
str[0] = '\0';
}
MyString(const char *s) {
str = new char(strlen(s));
strcpy(str, s);
}
MyString(const MyString &mystr) {
str = new char[strlen(mystr.str)];
strcpy(str, mystr.str);
}
void append(MyString S) {
char *temp = new char[strlen(str) + strlen(S.str) + 1];
strcpy(temp, str);
strcat(temp, S.str);
delete [] str;
str = temp;
}
~MyString() {
delete [] str;
}
void printToStdout() {
cout << str << endl;
}
};
void test(MyString S) {
if(strlen(S.str) > 0)
S.str[0] = 'A';
}
int main() {
MyString A("rp1"), B("pmf");
test(B); // S.MyString(B)
B.printToStdout();
A.append(B);
A.printToStdout();
return 0;
} | true |
67a0dbd85f3d14fc5c359564d3155e67b30445fe | C++ | aidandan/algorithm | /5动态规划/1088滑雪.cpp | GB18030 | 1,790 | 3.28125 | 3 | [] | no_license | //http://bailian.openjudge.cn/practice/1088/
#include <algorithm>
#include <iostream>
using namespace std;
struct section
{//
int x, y;//
int h;//߶
bool operator<(section s1)
{
return h < s1.h;
}
};
const int R = 100, C = 100;
//ÿ
section sec[R * C] = { 0 };
int a[R][C] = { 0 }; //
//ÿΪյ·߳
int len[R][C] = { 0 };
int find(section s[], int a[R][C], int r, int c)
{
int n = r * c; //Ԫظ
int i, j, max = 0; //·
for (i = 0; i < r; i++)
{//ʼ
for (j = 0; j < c; j++)
{
len[i][j] = 1;
}
}
//Ȱ߶ȴС
sort(s, s + n); //ܹؼ
for (i = 0; i < n; i++)
{
int x = s[i].x, y = s[i].y;
if (y > 0 && a[y][x] > a[y - 1][x])
{//Դ滬
if (len[y][x] < len[y - 1][x] + 1)
{
len[y][x] = len[y - 1][x] + 1;
}
}
if (y < r - 1 && a[y][x] > a[y + 1][x])
{//Դ滬
if (len[y][x] < len[y + 1][x] + 1)
{
len[y][x] = len[y + 1][x] + 1;
}
}
if (x > 0 && a[y][x] > a[y][x - 1])
{//Դ滬
if (len[y][x] < len[y][x - 1] + 1)
{
len[y][x] = len[y][x - 1] + 1;
}
}
if (x< c - 1 && a[y][x] > a[y][x + 1])
{//Դ滬
if (len[y][x] < len[y][x + 1] + 1)
{
len[y][x] = len[y][x + 1] + 1;
}
}
}
for (i = 0; i < r; i++)
{
for (j = 0; j < c; j++)
{
if (max < len[i][j])
{
max = len[i][j];
}
}
}
return max;
}
int main()
{
int r, c, i, j, n = 0;
cin >> r >> c;
for (i = 0; i < r; i++)
{
for (j = 0; j < c; j++)
{
cin >> a[i][j];
sec[n].y = i; //
sec[n].x = j; //
sec[n].h = a[i][j]; //߶
n++;
}
}
cout << find(sec, a, r, c);
return 0;
}
| true |
5b6073aba0931a716a0b2f47d786c7c3885a8cda | C++ | TheMarlboroMan/cheap-shooter | /class/aplicacion/decoracion/decoracion_explosion.cpp | UTF-8 | 1,738 | 2.796875 | 3 | [] | no_license | #include "decoracion_explosion.h"
Decoracion_explosion::Decoracion_explosion(float p_x, float p_y, DLibH::Vector_2d p_v):Decoracion(), duracion(0.5f)
{
this->vector_mov=p_v;
this->x=p_x;
this->y=p_y;
this->establecer_caracteristicas();
this->establecer_representacion();
}
Decoracion_explosion::~Decoracion_explosion()
{
}
void Decoracion_explosion::procesar_turno(float p_delta)
{
Decoracion::procesar_turno(p_delta);
this->duracion-=p_delta;
if(this->duracion < 0) this->duracion=0;
this->actualizar_representacion();
}
void Decoracion_explosion::establecer_caracteristicas()
{
this->w=32;
this->h=32;
this->posicion=DLibH::Herramientas_SDL::nuevo_sdl_rect(this->x, this->y, this->w, this->h);
}
void Decoracion_explosion::establecer_representacion()
{
this->establecer_representacion_bitmap_dinamica(DLibV::Gestor_recursos_graficos::obtener(Recursos::G_TILE_JUEGO));
Representable::establecer_posicion(this->x,this->y, this->w, this->h);
this->establecer_recorte(0, 0, 0, 0);
this->actualizar_representacion();
}
void Decoracion_explosion::actualizar_representacion()
{
if(this->duracion>0.4f)
{
Representable::establecer_recorte(0, 160, this->w, this->h);
Representable::establecer_alpha(33);
}
else if(this->duracion > 0.3f)
{
Representable::establecer_recorte(32, 160, this->w, this->h);
Representable::establecer_alpha(66);
}
else if(this->duracion > 0.2f)
{
Representable::establecer_recorte(64, 160, this->w, this->h);
Representable::establecer_alpha(132);
}
else if(this->duracion > 0.1f)
{
Representable::establecer_recorte(96, 160, this->w, this->h);
Representable::establecer_alpha(200);
}
}
bool Decoracion_explosion::es_finalizado()
{
return this->duracion==0;
}
| true |
afa153a2b349603dbf61e5a70c416f29fc711789 | C++ | Pentagon03/competitive-programming | /algorithmic-engagements/2002-2/tar.cc | UTF-8 | 845 | 2.828125 | 3 | [] | no_license | #include <cstdio>
#include <vector>
#include <algorithm>
int solve(const std::vector<int>& h, int n, int k) {
std::vector<int> cost(n);
for (int i = 0; i < n; ++i) {
if (i == n - 1 || h[i] >= h[i + 1]) cost[i] = 0;
else cost[i] = h[i + 1] - h[i];
}
int ret = 1;
for (int i = 0, cnt = 0, j = 0; i < n; ++i) {
if (j < i) j = i;
while (j < n && cnt + cost[j] <= k) {
cnt += cost[j++];
}
if (j == n && j - i > ret) ret = j - i;
if (j != n && j - i + 1 > ret) ret = j - i + 1;
if (i != j) cnt -= cost[i];
}
return ret;
}
int main() {
int n, k;
scanf("%d%d", &n, &k);
std::vector<int> h(n);
for (int i = 0; i < n; ++i) {
scanf("%d", &h[i]);
}
int ret = solve(h, n, k);
std::reverse(h.begin(), h.end());
ret = std::max(ret, solve(h, n, k));
printf("%d\n", ret);
return 0;
}
| true |
6b8c9fe3bfe7ab5379424a80d575412c6c07dba3 | C++ | chib0/ITC | /CoffeeShop/main.cpp | UTF-8 | 1,883 | 2.84375 | 3 | [] | no_license | // compile in debug settings
// In this process they need to change the executable file so that the program will show the shoe shop menu (which is also declared in menus.h)
#include <stdio.h>
#include "menus.h"
#include <windows.h>
#include <stdlib.h>
COORD pos;
__declspec(noinline) void SaveCursor() {
HANDLE screen = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO bi;
GetConsoleScreenBufferInfo(screen, &bi);
pos = bi.dwCursorPosition;
}
__declspec(noinline) void RevertCursor() {
HANDLE screen = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleCursorPosition(screen, pos);
}
__declspec(noinline) void clear_cursor () {
RevertCursor();
printf(" \r\n");
printf(" ");
RevertCursor();
}
int main(void)
{
printf("Wellcome to the ShopManager2000!! \r\nPlease select items from the menu\r\n\r\n");
size_t subtotal = 0;
menu_options ¤t = options[0];
printf ("%s:\r\n", current.title);
for (int i = 0; i < current.size; ++i) {
printf("\t%d: %s\t\t\t | $%d \r\n", i, current.strings[i], current.prices[i]);
}
printf("\r\n\t%d: %s\r\n", 999, "Terminate");
printf("Enter next choice: ");
SaveCursor();
int choice;
do {
RevertCursor();
scanf("%d", &choice);
clear_cursor();
if (choice < current.size) {
subtotal += current.prices[choice];
} else if (choice != 999) {
printf("\r\n Invalid Choice, try again");
}
} while (choice != 999);
system("cls");
printf("\r\n\r\n Thank you! subtotal was: %d", subtotal);
getc(stdin);
return 0;
}
| true |
ebecea92431e0de784221fea81f2a55c7ed568c9 | C++ | dahegarty/budgettracker | /budgettracker/expenseItem.h | UTF-8 | 1,225 | 2.859375 | 3 | [] | no_license | //
// expenseItem.h
// budgettracker
//
// Created by Domnall Hegarty on 2/18/16.
// Copyright © 2016 Landward Lemon Technologies. All rights reserved.
//
#ifndef expenseItem_h
#define expenseItem_h
#include <string>
using namespace std;
class expenseItem{
private:
//date
string date;
//price
double price;
//category
enum expenseCategory{
food = 1,
bills = 2,
personal = 3
};
expenseCategory category;
//object purchased
string object;
//vendor
string vendor;
public:
void setDate(string d){
date = d;
}
string getDate(){
return date;
}
void setPrice(double p){
price = p;
}
double getPrice(){
return price;
}
void setCategory(expenseCategory c){
category = c;
}
expenseCategory getCategory(){
return category;
}
void setObject(string o){
object = o;
}
string getObject(){
return object;
}
void setVendor(string v){
vendor = v;
}
string getVendor(){
return vendor;
}
};
#endif /* expenseItem_h */
| true |
b8e03574632d396886eaeaeb8ef127b6081257a0 | C++ | kaocodes/cpp-routeplanning | /src/backup.cpp | UTF-8 | 372 | 3.21875 | 3 | [] | no_license | /* First Idea without sorting for NextNode() function:
float sum = NULL;
RouteModel::Node* pointer;
for(RouteModel::Node* open_node : this->open_list){
if((open_node->g_value + open_node->h_value) < sum || sum == NULL){
sum = open_node->g_value + open_node->h_value;
*pointer = *open_node;
}
}
return pointer;*/ | true |
b44a973eb8a02aadc5f9e693399229d35424f584 | C++ | linhlevandlu/FAMLab_2017_Thanh | /MAELab/imageModel/Line.h | UTF-8 | 1,632 | 2.703125 | 3 | [] | no_license | /*
Morphometry with Automatic Extraction of Landmarks (MAELab)
Copyright (C) 2017 Le Van Linh (van-linh.le@u-bordeaux.fr)
Created on: Sep 15, 2016
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/.
*/
#ifndef LINE_H_
#define LINE_H_
class Line
{
private:
Point begin;
Point end;
int dx; // slope of x
int dy; // slope of y
double length;
std::vector<double> equation;
bool isPoint();
double lengthOfLine();
std::vector<double> equationOfLine();
public:
Line();
Line(const Line&);
Line(Point, Point);
virtual ~Line();
Point getBegin();
Point getEnd();
double getLength();
std::vector<double> getEquation();
void setBegin(Point);
void setEnd(Point);
double perpendicularDistance(Point);
double angleLines(Line);
Point intersection(Line);
bool checkBelongPoint(Point);
vector<Point> interParallel(Line line1, Line line2, double distance1,
double distance2, int width, int height);
};
typedef Line* ptr_Line;
double distancePoints(Point p1, Point p2);
#endif /* LINE_H_ */
| true |
af04f240dacec5c86db2f34335b88e5d58cfb2a0 | C++ | Michael-Lfx/vuk | /include/vuk/SampledImage.hpp | UTF-8 | 1,762 | 2.8125 | 3 | [
"MIT"
] | permissive | #pragma once
#include "vuk/Types.hpp"
#include "vuk/Image.hpp"
#include "Pool.hpp"
#include <optional>
namespace vuk {
// high level type around binding a sampled image with a sampler
struct SampledImage {
struct Global {
vuk::ImageView iv;
vuk::SamplerCreateInfo sci = {};
vuk::ImageLayout image_layout;
};
struct RenderGraphAttachment {
Name attachment_name;
vuk::SamplerCreateInfo sci = {};
std::optional<vuk::ImageViewCreateInfo> ivci = {};
vuk::ImageLayout image_layout;
};
union {
Global global = {};
RenderGraphAttachment rg_attachment;
};
bool is_global;
SampledImage(Global g) : global(g), is_global(true) {}
SampledImage(RenderGraphAttachment g) : rg_attachment(g), is_global(false) {}
SampledImage(const SampledImage& o) {
*this = o;
}
SampledImage& operator=(const SampledImage& o) {
if (o.is_global) {
global = {};
global = o.global;
} else {
rg_attachment = {};
rg_attachment = o.rg_attachment;
}
is_global = o.is_global;
return *this;
}
};
// the returned values are pointer stable until the frame gets recycled
template<>
struct PooledType<vuk::SampledImage> {
plf::colony<vuk::SampledImage> values;
size_t needle = 0;
PooledType(Context&) {}
vuk::SampledImage& acquire(PerThreadContext& ptc, vuk::SampledImage si);
void reset(Context&) { needle = 0; }
void free(Context&) {} // nothing to free, this is non-owning
};
inline vuk::SampledImage& PooledType<vuk::SampledImage>::acquire(PerThreadContext&, vuk::SampledImage si) {
if (values.size() < (needle + 1)) {
needle++;
return *values.emplace(std::move(si));
} else {
auto it = values.begin();
values.advance(it, needle++);
*it = si;
return *it;
}
}
}
| true |
f74c489e508cc24f528457065e9a9d4ff5f963ff | C++ | HargovindArora/Programming | /Graphs/kosaraju2_SCC.cpp | UTF-8 | 1,419 | 3.21875 | 3 | [] | no_license | #include<iostream>
#include<cstring>
#include<vector>
using namespace std;
void dfs(vector<int> graph[], int i, bool *visited, vector<int> &stack){
visited[i] = true;
for(auto nbr:graph[i]){
if(!visited[nbr]){
dfs(graph, nbr, visited, stack);
}
}
stack.push_back(i);
}
void dfs2(vector<int> rev_graph[], int i, bool *visited){
visited[i] = true;
cout << i << " ";
for(auto nbr:rev_graph[i]){
if(!visited[nbr]){
dfs2(rev_graph, nbr, visited);
}
}
}
void solve(vector<int> graph[], vector<int> rev_graph[], int n){
bool visited[n];
memset(visited, 0, n);
vector<int> stack;
for(int i=0; i<n; i++){
if(!visited[i]){
dfs(graph, i, visited, stack);
}
}
memset(visited, 0, n);
char component = 'A';
for(int x=stack.size()-1; x>=0; x--){
int node = stack[x];
if(!visited[node]){
cout << "Component " << component << " -> ";
dfs2(rev_graph, node, visited);
cout << endl;
component++;
}
}
}
int main(){
int n;
cin >> n;
vector<int> graph[n];
vector<int> rev_graph[n];
int m;
cin >> m;
while(m--){
int x, y;
cin >> x >> y;
graph[x].push_back(y);
rev_graph[y].push_back(x);
}
solve(graph, rev_graph, n);
return 0;
} | true |
5fab132434a1225a8b2d5beec29806180d17bd9c | C++ | dtsadok-tw/auroraShapes1 | /src/auroraShapes1.cpp | UTF-8 | 3,785 | 2.984375 | 3 | [
"MIT"
] | permissive | #include "auroraShapes1.h"
void auroraShapes1::setup(){
white = ofColor(255, 255, 255);
color1 = ofColor(64, 64, ofRandom( 128, 255 ) );
color2 = ofColor(ofRandom( 128, 255 ), 64, 64 );
color3 = ofColor(64, ofRandom( 128, 255 ), ofRandom( 128, 255 ) );
color4 = ofColor(64, 64, ofRandom( 128, 255 ) );
}
void auroraShapes1::update(){
beat();
int newScene = getSceneNumber();
if (newScene != currentScene) //transition?
{
//triggerAudioFor(newScene);
currentScene = newScene;
}
}
void auroraShapes1::draw(){
ofBackground(0);
ofTranslate(ofGetWidth()/2, ofGetHeight()/2);
//ofScale(50*scale, 50*scale);
//ofScale(50, 50);
switch (currentScene) {
case 1:
drawScene1();
break;
case 2:
drawScene2();
break;
case 3:
drawScene3();
break;
case 4:
drawScene4();
break;
default:
ofBackground(0);
break;
}
}
//simulate heartbeat
void auroraShapes1::beat(){
if (ofGetFrameNum() % 45 < 5)
scale = 0.95;
else
scale = 1.00;
}
int auroraShapes1::getSceneNumber(){
int sceneTimesLength = sizeof(sceneTimes)/sizeof(sceneTimes[0]);
for (int i=sceneTimesLength-1; i >= 0; i--)
{
if (ofGetElapsedTimeMillis() >= sceneTimes[i])
return i;
}
}
void auroraShapes1::drawScene1(){
ofBackground(0);
ofSetColor(white);
ofPolyline line;
int radius = 80*scale;
line.arc(0, 0, radius, radius, 0, 360, 100);
line.draw();
}
void auroraShapes1::drawScene2(){
ofBackground(color2);
ofSetColor(white);
int radius = 40*scale;
ofPolyline circle1, circle2;
circle1.arc(2*radius, 2*radius, radius, radius, 0, 360, 100);
circle1.draw();
circle2.arc(-2*radius, -2*radius, radius, radius, 0, 360, 100);
circle2.draw();
}
void auroraShapes1::drawScene3(){
ofBackground(color3);
ofSetColor(white);
int numCircles = 4;
int radius = 25*scale;
int centers[4][2] = {{-1, 1}, {1, 1}, {1, -1}, {-1, -1}};
for (int i=0; i< numCircles; i++)
{
ofPolyline circle;
circle.arc(centers[i][0]*4*radius, centers[i][1]*4*radius,
radius, radius, 0, 360, 100);
circle.draw();
}
}
void auroraShapes1::drawScene4(){
ofSetColor(0);
}
void auroraShapes1::drawRandomCircle(float r0, float r1) {
ofPolyline line;
for (float j=0; j < TWO_PI+0.1; j+= 0.05) {
float r = ofRandom(r0, r1);
float x = r * cos(j);
float y = r * sin(j);
//line.addVertex(x, y); //pointy
line.curveTo(x, y); //curvy
}
line.draw();
}
//start, end: 0-11 (end > start)
void auroraShapes1::drawArc12(int radius, int start, int end) {
ofPolyline line;
float rscale = 1/15.0;
float angleBegin = 0, angleEnd = 0;
if (start != 12) angleBegin = (start * 360/12) % 360;
if (end != 12) angleEnd = (end * 360/12) % 360;
line.arc(0, 0, radius * rscale, radius * rscale, angleBegin, angleEnd, 100);
line.draw();
}
void auroraShapes1::drawCircles(){
ofSetColor(color1);
drawRandomCircle(0.85, 0.85);
ofSetColor(color2);
drawRandomCircle(0.85, 1.0);
ofSetColor(color3);
drawRandomCircle(1.0, 1.25);
ofSetColor(color4);
drawRandomCircle(1.25, 1.25);
}
void auroraShapes1::drawPattern(){
int last = 0;
int digits[] = {3, 1, 4, 1, 5, 9};
for (int i=0; i < 7; i++)
{
int start = last;
int end = (last+digits[i]); // % 12;
last = end;
drawArc12(i+1, start, end);
}
}
void auroraShapes1::gotMessage(ofMessage msg){
}
| true |
b91ca33f00522323579ec4ceba43c07cb9dd1f10 | C++ | AhuntSun/C-CLI | /最後的小组项目/小组项目/上位机/小组项目3上位机/BZ.h | GB18030 | 2,532 | 2.890625 | 3 | [] | no_license | #pragma once
namespace СĿ3λ {
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
/// <summary>
/// BZ ժҪ
/// </summary>
public ref class BZ : public System::Windows::Forms::Form
{
public:
BZ(void)
{
InitializeComponent();
//
//TODO: ڴ˴ӹ캯
//
}
protected:
/// <summary>
/// ʹõԴ
/// </summary>
~BZ()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::TextBox^ textBox1;
protected:
private:
/// <summary>
///
/// </summary>
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
/// <summary>
/// ֧ķ - Ҫ
/// ʹô༭Ĵ˷ݡ
/// </summary>
void InitializeComponent(void)
{
this->textBox1 = (gcnew System::Windows::Forms::TextBox());
this->SuspendLayout();
//
// textBox1
//
this->textBox1->Font = (gcnew System::Drawing::Font(L"", 15, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(134)));
this->textBox1->Location = System::Drawing::Point(17, 13);
this->textBox1->Multiline = true;
this->textBox1->Name = L"textBox1";
this->textBox1->Size = System::Drawing::Size(337, 312);
this->textBox1->TabIndex = 0;
this->textBox1->Text = L"\r\n ϵͳʵʱʾ\r\nλIJ\r\nͼУҿ\r\nʾʵʱݵƽֵϵ\r\nͳݴݿ⣬\r\nͨ"
L"鿴ݿ\r\n洢ʷݡ";
this->textBox1->TextChanged += gcnew System::EventHandler(this, &BZ::textBox1_TextChanged);
//
// BZ
//
this->AutoScaleDimensions = System::Drawing::SizeF(8, 15);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->BackColor = System::Drawing::SystemColors::ButtonShadow;
this->ClientSize = System::Drawing::Size(379, 350);
this->Controls->Add(this->textBox1);
this->Name = L"BZ";
this->Text = L"BZ";
this->ResumeLayout(false);
this->PerformLayout();
}
#pragma endregion
private: System::Void textBox1_TextChanged(System::Object^ sender, System::EventArgs^ e) {
}
};
}
| true |
34c0d6a97bef3904e4f916c4d77ad6a061aeb4d3 | C++ | materlai/leetcode | /011_container_most_water.cpp | UTF-8 | 803 | 3.3125 | 3 | [] | no_license | /*
leetcode algorithm 011: container with most water
*/
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <vector>
using namespace std;
class Solution {
public:
int maxArea(vector<int>& height)
{
/* can not pass time limited with O(n*n) */
int first_index=0;
int last_index=height.size()-1;
int max_container_count=0;
while(first_index<last_index){
int container_count;
if(height[first_index]< height[last_index] ){
container_count= (last_index-first_index)* height[first_index];
first_index++;
}else{
container_count=(last_index-first_index)* height[last_index];
last_index--;
}
if(container_count > max_container_count)
max_container_count=container_count;
}
return max_container_count;
}
};
| true |
c82f5c88c35aeb81da1e0641c5e0c2d4287cca2c | C++ | johanngan/particle_reco | /Cut_optimization/ROOT_Util/loadObj.h | UTF-8 | 4,714 | 2.96875 | 3 | [] | no_license | //
// loadObj.h
// ROOT_Util/
//
// Created by Johann Gan on 6/2/17
//
//
// Template function. Opens a file and reads in a specified object. Returns a unique_ptr to the object.
//////////////////////////////////////
#ifndef LOADOBJ_H_
#define LOADOBJ_H_
//////////////////////////////////////
// Dependencies
#include <string>
#include <memory>
#include <iostream>
#include <TROOT.h>
#include <TFile.h>
#include <TDirectoryFile.h>
//////////////////////////////////////
using namespace std;
//////////////////////////////////////
// Supporting function templates
//
// Behavior determined via SFINAE tests
// releaseOwnership releases the object from the ownership of any enclosing directories.
// Implementation 1: if U::CloneTree exists.
// For when U is TTree of TNtuple.
template <class U>
unique_ptr<U> releaseOwnership_imp(unique_ptr<U> theObj, int highpriority1, int highpriority2, decltype(&U::CloneTree) test = 0)
{
gROOT->cd();
theObj.reset( (U*)theObj->CloneTree() );
return theObj;
}
// Implementation 2: if U::CloneTree does not exist, but U::SetDirectory exists.
// Primarily for when U is a histogram class.
template <class U>
unique_ptr<U> releaseOwnership_imp(unique_ptr<U> theObj, int highpriority, long lowpriority, decltype(&U::SetDirectory) test = 0)
{
theObj->SetDirectory(0);
return theObj;
}
// Implementation 3: if neither U::CloneTree nor u::SetDirectory exist.
// Default method for various non-tree/non-histogram classes.
template <class U>
unique_ptr<U> releaseOwnership_imp(unique_ptr<U> theObj, long lowpriority1, long lowpriority2)
{
return theObj;
}
// releaseOwnership definition
template <class U>
unique_ptr<U> releaseOwnership(unique_ptr<U> theObj)
{
return releaseOwnership_imp( move(theObj), 0, 0 );
}
//====================================//
// doOpen opens a file of a specific class type if an Open method exists, and returns a nullptr if it doesn't.
// Implementation 1: U::Open exists
template <class U>
unique_ptr<U> doOpen_imp(const string& name, int highpriority, decltype(U::Open("")) test = 0)
{
unique_ptr<U> newObj( (U*)U::Open(name.c_str()) );
return newObj;
}
// Implementation 2: U::Open does not exist
template <class U>
unique_ptr<U> doOpen_imp(const string& name, long lowpriority)
{
cout << "ERROR: Specified class type does not have method: Open().\n";
return nullptr;
}
// doOpen definition
template <class U>
unique_ptr<U> doOpen(const string& name)
{
return doOpen_imp<U>(name, 0);
}
//////////////////////////////////////
//Actual definition of loadObj
template <class T>
unique_ptr<T> loadObj(const string& objName, const string& fileName = "", const string& directoryName = "")
{
// Opens a file and reads in a specified object. Returns a unique_ptr to the object.
//
// directoryName and fileName are optional parameters. They default to empty strings.
//
// (1) If both directoryName and fileName are non-empty, the following directory structure is assumed:
//
// --TFile
// ----TDirectoryFile
// ------TObject
//
// (2) If directoryName is empty but fileName if non-empty, the following directory structure is assumed:
//
// --TFile
// ----TObject
//
// (3) If fileName are empty, the following directory structure is assumed (even if directoryName is non-empty):
//
// --TObject
//
// For (3), it is assumed the object can be opened directly from a file via an Open() method (e.g. a TASImage or a TFile),
// and that objName contains the path to the object file, rather than just the name.
// Determine the mode
bool has_directory = true;
if(directoryName.empty())
has_directory = false;
bool has_file = true;
if(fileName.empty())
has_file = false;
// Retrieve the object in the proper manner
unique_ptr<TFile> file;
if(has_file)
{
file.reset ( new TFile(fileName.c_str()) );
// Check for validity of file
if(!file->IsOpen())
{
cout << "ERROR: File could not be opened. Check the validity of the file name.\n";
return nullptr;
}
}
unique_ptr<TDirectoryFile> tdf;
unique_ptr<T> objptr;
if(has_file && has_directory)
{
tdf.reset( (TDirectoryFile*)file->Get(directoryName.c_str()) );
// Check for validity of directory
if(tdf)
{
objptr.reset( (T*)tdf->Get(objName.c_str()) );
}
else
{
cout << "ERROR: Directory could not be opened. Check the validity of the directory name.\n";
return nullptr;
}
}
else if(has_file)
{
objptr.reset( (T*)file->Get(objName.c_str()) );
}
else
{
objptr = doOpen<T>(objName);
}
// Check for validity of object
if(!objptr)
{
cout << "ERROR: Object could not be loaded.\n";
return nullptr;
}
objptr = releaseOwnership<T>( move(objptr) );
return objptr;
}
#endif
| true |
c636339bd67a8dd564d26bcd6d0655d732d234ef | C++ | yury-dymov/legacy_l2tradebot | /dialog/ui_recipeshopiteminfo.cpp | UTF-8 | 3,030 | 2.625 | 3 | [] | no_license | #include "recipeshopiteminfo.h"
RecipeShopItemInfo::RecipeShopItemInfo (int recipeId, int mp, int maxMp)
{
bool available = true;
table_ = new QTableWidget (0, 2);
QList <QString> labels;
labels.push_back ("Item");
labels.push_back ("Amount");
table_->setHorizontalHeaderLabels (QStringList (labels));
table_->verticalHeader ()->hide ();
table_->setColumnWidth (0, 230);
table_->setColumnWidth (1, 100);
Recipe_s rec = Data::recipe (recipeId);
for (unsigned int i = 0; i < rec.items.size (); ++i)
{
table_->setRowCount (table_->rowCount () + 1);
QTableWidgetItem * wiName = new QTableWidgetItem;
wiName->setText (Data::itemName (rec.items[i].itemId).c_str ());
wiName->setFlags (Qt::ItemIsSelectable | Qt::ItemIsEnabled);
table_->setItem (table_->rowCount () - 1, 0, wiName);
QTableWidgetItem * wiCount = new QTableWidgetItem;
int count = 0;
for (unsigned int j = 0; j < Data::bag.size (); ++j)
{
if (Data::bag[j].itemId == rec.items[i].itemId)
{
count = Data::bag[j].count;
break;
}
}
if (count < rec.items[i].count)
{
available = false;
}
wiCount->setText (QString (DataFunc::number (count).c_str ()) + " / " + QString (DataFunc::number (rec.items[i].count).c_str ()));
wiCount->setFlags (Qt::ItemIsSelectable | Qt::ItemIsEnabled);
table_->setItem (table_->rowCount () - 1, 1, wiCount);
}
recipeLabel_ = new QLabel (QString ("Recipe: ") + QString (Data::recipeName (recipeId).c_str ()));
mpLabel_ = new QLabel (QString ("Creator MP: ") + QString (DataFunc::number (mp).c_str ()) + " / " + QString (DataFunc::number (maxMp).c_str ()));
prevButton_ = new QPushButton ("Back");
connect (prevButton_, SIGNAL (pressed ()), SLOT (slotPressed ()));
craftButton_ = new QPushButton ("Craft");
craftButton_->setEnabled (available);
connect (craftButton_, SIGNAL (pressed ()), SLOT (slotPressed ()));
cancelButton_ = new QPushButton ("Cancel");
connect (cancelButton_, SIGNAL (pressed ()), SLOT (reject ()));
buttonLayout_ = new QHBoxLayout;
buttonLayout_->addWidget (prevButton_);
buttonLayout_->addWidget (craftButton_);
buttonLayout_->addWidget (cancelButton_);
vla_ = new QVBoxLayout;
vla_->addWidget (recipeLabel_);
vla_->addWidget (mpLabel_);
vla_->addWidget (table_);
vla_->addLayout (buttonLayout_);
this->setLayout (vla_);
this->setWindowTitle ("Create Item");
this->move (400, 300);
this->setFixedSize (360, 300);
this->show ();
}
RecipeShopItemInfo::~RecipeShopItemInfo ()
{
for (int i = 0; i < table_->rowCount (); ++i)
{
for (int j = 0; j < table_->columnCount (); ++j)
{
delete table_->item (i, j);
}
}
delete recipeLabel_;
delete mpLabel_;
delete table_;
delete craftButton_;
delete cancelButton_;
delete prevButton_;
delete buttonLayout_;
delete vla_;
}
void RecipeShopItemInfo::slotPressed ()
{
if (sender () == craftButton_)
{
selection_ = 0;
accept ();
}
else if (sender () == prevButton_)
{
selection_ = 1;
accept ();
}
}
int RecipeShopItemInfo::selection () const
{
return selection_;
}
| true |
c0f9f7c5288735cfed9bd3526b4b13f28f75da78 | C++ | alexandraback/datacollection | /solutions_5690574640250880_0/C++/pvtGero/main.cpp | UTF-8 | 1,911 | 2.78125 | 3 | [] | no_license | #include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
int c, R, C, M;
bool found;
void print(char gg[][51]){
printf("Case #%d:\n", c);
for(int i = 0; i < R; i++){
for(int j = 0; j < C; j++){
if(gg[i][j] != '\0') printf("%c", i == 0 && j == 0 ? gg[i][j] : '.');
else printf("%c", '*');
}
printf("\n");
}
}
int fill(char gg[][51], int x, int y){
int count = 0;
for(int k = x - 1; k <= x + 1; k++){
for(int l = y - 1; l <= y + 1; l++){
if(k >= 0 && k < R && l >= 0 && l < C && gg[k][l] != '.' && gg[k][l] != 'c'){
gg[k][l] = '.';
count++;
}
}
}
return count;
}
bool solve(int i, int j, int mines, char grid[][51]){
char newGrid[51][51];
for(int k = 0; k < R; k++){
for(int l = 0; l < C; l++){
newGrid[k][l] = grid[k][l];
}
}
int count = fill(newGrid, i, j);
bool done = mines - count == M;
//print(newGrid);
if(done)
print(newGrid);
if(!done && j + 1 < C && newGrid[i][j + 1] != 'c'){
char temp = newGrid[i][j + 1];
newGrid[i][j + 1] = 'c';
done = solve(i, j + 1, mines - count, newGrid);
newGrid[i][j + 1] = temp;
}
if(!done && i + 1 < R && newGrid[i + 1][j] != 'c'){
char temp = newGrid[i + 1][j];
newGrid[i + 1][j] = 'c';
done = solve(i + 1, j, mines - count, newGrid);
newGrid[i + 1][j] = temp;
}
if(!done && j - 1 >= 0 && newGrid[i][j - 1] != 'c'){
char temp = newGrid[i][j - 1];
newGrid[i][j - 1] = 'c';
done = solve(i, j - 1, mines - count, newGrid);
newGrid[i][j - 1] = temp;
}
return done;
}
int main (int argc, char *argv[])
{
int TC;
scanf("%d", &TC);
for(c = 1; c <= TC; c++){
scanf("%d %d %d", &R, &C, &M);
char grid[51][51];
memset(grid, '\0', sizeof grid);
grid[0][0] = 'c';
if(R*C - 1 == M){
print(grid);
}
else{
int mines = R*C - 1;
if(!solve(0, 0, mines, grid))
printf("Case #%d:\nImpossible\n", c);
else{
}
}
}
return 0;
}
| true |
8591ed5dcd200e2e8276b75d60eec4455468462e | C++ | neer1304/CS-Reference | /CPP/Generic_Programming/stl/mapstr.cpp | UTF-8 | 678 | 3.515625 | 4 | [] | no_license |
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main ()
{
map<string, string> strMap;
strMap["Sunday"] = "0";
strMap["Monday"] = "1";
strMap["Tuesday"] = "2";
strMap["Wednesday"] = "3";
strMap["Thursday"] = "4";
strMap["Friday"] = "5";
strMap.insert(pair<string, string>("Saturday", "6"));
cout<<endl;
cout<<"Display the details: ";
map<string, string>::iterator p;
cout<<endl;
for (p = strMap.begin(); p != strMap.end(); p++)
{
cout<<"English:"<<p->first;
cout<<"\t#:"<<p->second;
cout<<endl;
}
cout<<endl;
return 0;
}
| true |
f9c4286cd24bdbd90f27ef4b51a0ba0a4dbfdc44 | C++ | Willz789/Eksamensprojekt | /PolyTank/PolyTank/Body.h | UTF-8 | 1,015 | 2.625 | 3 | [] | no_license | #pragma once
#include "ConvexShape.h"
#include <memory>
class Body {
public:
Body(std::unique_ptr<ConvexShape>&& pShape, DirectX::FXMVECTOR initPos, DirectX::FXMVECTOR initRot);
virtual ~Body() = default;
DirectX::XMVECTOR getPosition() const;
DirectX::XMVECTOR getRotation() const;
DirectX::XMMATRIX getTransform() const;
void setPosition(DirectX::FXMVECTOR newPos);
void setRotation(DirectX::FXMVECTOR newRot);
virtual float getMass() const = 0;
virtual float getInvMass() const = 0;
virtual void move(DirectX::FXMVECTOR translation);
virtual void addForce(DirectX::FXMVECTOR force) = 0;
virtual void update(float dt) = 0;
ConvexShape* getShape();
void updateWorldShape();
const AABB& getBoundingBox() const;
bool checkCollision(const Body& other, DirectX::XMVECTOR* pResolution) const;
protected:
std::unique_ptr<ConvexShape> pShape;
std::unique_ptr<TransformedShape> pWorldShape;
AABB boundingBox;
bool transformDirty;
DirectX::XMFLOAT3 position;
DirectX::XMFLOAT4 rotation;
};
| true |
906b99105e6dd65fac2c1f5fc05ff91dc6780c58 | C++ | barjinderpaul/Programming | /STL/searching binary search.cpp | UTF-8 | 710 | 3.453125 | 3 | [] | no_license | //searching
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main(){
int value,t,n,numberToFind;
cin>>t;
while(t-- > 0){
cin>>n;
vector<int> a;
for(int i=0;i<n;i++)
{
cin>>value;
a.push_back(value);
}
cin>>numberToFind;
sort(a.begin(),a.end()); //sorting because binary search needs sorting
cout<<endl<<"sorted array";
for(int i=0;i<n;i++)
cout<<a[i]<<" ";
if(binary_search(a.begin(),a.end(),numberToFind))
{
cout<<"element found at :";
cout<<lower_bound(a.begin(),a.end(),numberToFind) - a.begin()<<endl;
}
else
cout<<"Next Higher element found at "<<lower_bound(a.begin(),a.end(),numberToFind) - a.begin() <<endl;
}
}
| true |
f3f074bbed290dfa6c10394a88614691bfcc0192 | C++ | faroos3/CSCI2600_S17_lab_work | /lab10/first_LCD_thing/first_LCD_thing.ino | UTF-8 | 3,676 | 2.78125 | 3 | [] | no_license | #include <LiquidCrystal.h>
/******************************************************************************************************************/
/*********** LCD Initialization Code - Don't change unless you want stuff to stop working! ********************/
/******************************************************************************************************************/
/*
* void init_LCD(); Call this function to set up the LCD screen for use
* void LCD_off(); Call this function to turn off the backlight of the screen. Note that this leaves the LCD still on, but not visible
* void LCD_on(); Call this function to turn the backlight back on. The LCD starts on by default
*
*
*
*
*
*
*
*/
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(48, 46, 44, 42, 40, 38, 36, 34, 32, 30, 28);
int __counter = 0; //Global counter variable for contrast PWM
void init_LCD(){__init_LCD();}
void __init_LCD(){
pinMode(24, OUTPUT); //K
pinMode(26, OUTPUT); //A
pinMode(54, OUTPUT); //VSS
pinMode(52, OUTPUT); //VDD
pinMode(50, OUTPUT); //Contrasty pin
digitalWrite(24, LOW); //Backlight
digitalWrite(26, HIGH); //Backlight
digitalWrite(54, LOW); //GND
digitalWrite(52, HIGH); //VDD
// set up the LCD's number of columns and rows:
lcd.begin(16, 2);
// Timer0 is used for millis() - we'll just interrupt
// in the middle and call the compA
OCR0A = 0x01;
TIMSK0 |= _BV(OCIE0A);
}
SIGNAL(TIMER0_COMPA_vect)
{
__counter++;
if (__counter > 14){
digitalWrite(50,HIGH);
__counter = 0;
}
else if (__counter > 3){
digitalWrite(50, LOW);
}
}
//turn lcd backlight off
void lcd_off(){
digitalWrite(26, LOW); //Backlight
}
//turn lcd backlight on
void lcd_on(){
digitalWrite(26, HIGH); //Backlight
}
/*******************************************************************************************************************/
/*******************************************************************************************************************/
/*******************************************************************************************************************/
unsigned long seconds;
bool timer_started;
unsigned long time;
void start_timer(){
time = millis();
}
void setup() {
// initialize the serial communications:
Serial.begin(9600);
init_LCD();
bool timer_started = false;
seconds = 0;
}
void printTime()
{
long hours = seconds % 3600;
long remain = seconds - (hours * 3600);
long minutes = remain % 60;
remain = remain - (minutes * 60);
long seconds = remain;
String output = String(hours) + ':' + String(minutes) + ':' + String(seconds);
lcd.clear();
lcd.print(output);
}
void loop() {
String message = Serial.readString();// read a string sent from the computer
if(message == "start"){
start_timer();
timer_started = true;
}
else if(message == "end"){
timer_started = false;
}
else if (message[0] == 't')
{
// Initial
String hoursStr = String(message[1]) + String(message[2]);
String minStr = String(message[3]) + String(message[4]);
int hours = hoursStr.toInt();
int mins = minStr.toInt();
seconds = 3600 * hours + 60 * mins;
Serial.print(seconds);
//printTime();
}
//message = set_timer(message);
//Serial.print("hello world");//prints hello world to the serial monitor
lcd.home();
//lcd.print(message);
//lcd.print(String(hour));
//lcd.setCursor(0, 1);
//lcd.clear();
if(timer_started){
seconds++;
printTime();
}
else
{
// blinky
}
delay(1000);
}
| true |
3a22b730b669ad139733ac562f139955f7ef67fa | C++ | endiliey/competitive-programming | /Codeforces/782B.cpp | UTF-8 | 772 | 2.53125 | 3 | [] | no_license | #include <bits/stdc++.h>
#define all(c) c.begin(), c.end()
#define epsilon 1e-7
#define N 60010
typedef long long ll;
using namespace std;
ll x[N];
ll v[N];
bool check(double t, int n)
{
double top = -1e9;
double bot = 1e9;
for (int i = 0; i < n; i++)
{
top = max(top, x[i] - v[i] * t);
bot = min(bot, x[i] + v[i] * t);
}
return top >= bot;
}
int main()
{
ios_base::sync_with_stdio(false);
int n;
cin >> n;
for (int i = 0; i < n; i++)
{
int foo;
cin >> foo;
x[i] = foo;
}
for (int i = 0; i < n; i++)
{
int bar;
cin >> bar;
v[i] = bar;
}
double low, hi;
for (low = 0, hi = 1e9; hi - low > epsilon;)
{
double mid = low + (hi - low) / 2;
if (check(mid, n))
low = mid;
else
hi = mid;
}
printf("%.7f", (low + hi) / 2);
}
| true |
912649d94661f23fd3d26d2464eb76b9a60f12e6 | C++ | Dsxv/competitveProgramming | /atCoder/ABC/152/d.cpp | UTF-8 | 484 | 2.671875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std ;
#define int long long
pair<int,int> gf(int n){
vector<int> v ;
while(n){
v.push_back(n%10) ;
n/=10 ;
}
return {v.back(),v[0]} ;
}
int32_t main(){
int a[11][11] = {} ;
int n ;
cin >> n ;
for(int i = 1 ; i <= n ; i++){
pair<int,int> p = gf(i) ;
a[p.first][p.second]++ ;
}
int ans = 0 ;
for(int i = 1 ; i <= 10 ; i++){
for(int j = 1 ; j <= 10 ; j++){
ans += a[i][j]*a[j][i] ;
}
}
cout << ans ;
return 0 ;
}
| true |
c67940c05a1035ff978a88071f9c97683836a542 | C++ | imtiazrayman/LinkedListDatastructsCpp | /cppLinkedList/main.cpp | UTF-8 | 6,610 | 3.8125 | 4 | [] | no_license | #include <iostream>
#include "Node.h"
using namespace std;
int main() {
cout<<"here are the tests, we assume all the print_list function works, otherwise no test will pass\n";
cout<<"press 1 for head_insert test"<<endl;
cout<<"press 2 for list_length test"<<endl;
cout<<"press 3 for list_get_tail, both const and non const test"<<endl;
cout<<"press 4 for list_tail_insert"<<endl;
cout<<"press 5 for list_insert"<<endl;
cout<<"press 6 for list_search"<<endl;
cout<<"press 7 for list locate"<<endl;
cout<<"press 8 for list_head_remove"<<endl;
cout<<"press 9 for list_remove"<<endl;
cout<<"press 10 for list_clear"<<endl;
cout<<"press 11 for list copy"<<endl;
int choice;
cin>>choice;
if(choice==1)
{
cout<<"creates a Node* to null and then inserts 5,4,3,2,1 at head, in that order\n";
Node* head=NULL;
for(int i=5; i>0; i--)
{
list_head_insert(head,i);
}
print_list(head);
}
if(choice==2)
{
cout<<"creates a Node* to null and then inserts 5,4,3,2,1 at head, in that order, each time checking length\n";
Node* head=NULL;
if(list_length(head)==0)
{
cout<<"0 length correct"<<endl;
}
for(int i=5; i>0; i--)
{
list_head_insert(head,i);
cout<<"current length: "<<list_length(head)<<endl;
}
cout<<"Final length: "<<list_length(head)<<endl;
}
if(choice==3)
{
cout<<"creates a Node* to null and then inserts 5,4,3,2,1 at head, in that order, each grabbing the tail and checking if it's correct\n";
Node* head=NULL;
Node* headConst=NULL;
cout<<"empty list, list_get_tail should be null "<<list_get_tail(head)<<endl;
cout<<"empty list, list_get_tail should be null (const) "<<list_get_tail(headConst)<<endl;
for(int i=5; i>0; i--)
{
list_head_insert(head,i);
}
cout<<"at the end of all the inserts, tail should be value 5"<<endl;
cout<<"non-const list_get_tail: "<<list_get_tail(head)->data()<<endl;
const Node* tailConst= list_get_tail(head);
cout<<"const list_get_tail: "<<tailConst->data();
}
if(choice==4)
{
cout<<"creates a Node* to null and then tail inserts 5,4,3,2,1 at head, in that order\n";
Node* head=NULL;
for(int i=5; i>0; i--)
{
list_tail_insert(head,i);
}
print_list(head);
}
if(choice==5)
{
Node* head=NULL;
cout<<"\n creates a Node* to null and then inserts 5,4,3,2,1 using list_head_insert, then grabs the 3rd one and inserts 599 after it\n";
Node* toInsertAfter;
for(int i=5; i>0; i--)
{
list_head_insert(head,i);
}
cout<<"list before insert"<<endl;
print_list(head);
cout<<endl;
toInsertAfter=head->link()->link();
cout<<"list after insert"<<endl;
list_insert(toInsertAfter,599);
print_list(head);
}
if(choice==6)
{
cout<<"creates a Node* to null and then inserts 5,4,3,2,1 at head, in that order\n";
Node* head=NULL;
for(int i=5; i>0; i--)
{
list_head_insert(head,i);
}
cout<<"Now searchers for 0,1,2,3,4,5 in that order and prints out their values"<<endl;
for(int i=0; i<6; i++)
{
cout<<"looking for "<<i<<" data should be this value if it exists: ";
Node* found= list_search(head, i);
if(found)
{
cout<<found->data()<<endl;
}
else
{
cout<<"NULL"<<endl;
}
}
cout<<"CONST TEST: Now searchers for 0,1,2,3,4,5 in that order and prints out their values"<<endl;
for(int i=0; i<6; i++)
{
cout<<"looking for "<<i<<" data should be this value if it exists: ";
const Node* foundC= list_search(head, i);
if(foundC)
{
cout<<foundC->data()<<endl;
}
else
{
cout<<"NULL"<<endl;
}
}
}
/*
if(choice==7)
{
cout<<"creates a Node* to null and then inserts 5,4,3,2,1 at head, in that order\n";
Node* head=NULL;
for(int i=5; i>0; i--)
{
list_head_insert(head,i);
}
cout<<"now finds the items at locations from 0 to 5 including 5 (which should be null)"<<endl;
for(int i=0; i<6; i++)
{
Node* atPosition= list_locate(head,i);
if(atPosition)
{
cout<<"at position "<<i<<" value is "<<atPosition->data()<<endl;
}
else
{
cout<<"at position "<<i<<" value is NULL"<<endl;
}
}
}
if(choice==8)
{
cout<<"creates a Node* to null and then inserts 5,4,3,2,1 at head, in that order\n";
Node* head=NULL;
for(int i=5; i>0; i--)
{
list_head_insert(head,i);
}
cout<<"now removes the head 6 times and prints out the values of the node removed"<<endl;
for(int i=0; i<6; i++)
{
Node* removed=list_head_remove(head);
if(removed)
{
cout<<"removed node value is "<<removed->data()<<endl;
}
else
{
cout<<"removed node value is NULL"<<endl;
}
}
}
if(choice==9)
{
Node* head=NULL;
cout<<"calls remove on empty list"<<endl;
list_remove(head);
head=new Node(5);
cout<<"calls remove on one item list passing in head, should be unchanged"<<endl;
list_remove(head);
head=NULL; //MEMORY LEAK ;)
cout<<"\nNow resets head, creates a Node* to null and then inserts 5,4,3,2,1 at head, in that order\n";
for(int i=5; i>0; i--)
{
list_head_insert(head,i);
}
cout<<"our list pre remove"<<endl;
print_list(head);
cout<<"\nnow removes the node after the 3 and prints out the values of the node removed (4)"<<endl;
list_remove(list_search(head,3));
cout<<"our list\n";
print_list(head);
}
if(choice==10)
{
cout<<"creates a Node* to null and then inserts 5,4,3,2,1 at head, in that order\n";
Node* head=NULL;
for(int i=5; i>0; i--)
{
list_head_insert(head,i);
}
cout<<"Now clears the list, memory leaks checked by hand"<<endl;
list_clear(head);
if(head==NULL)
{
cout<<"test passed!"<<endl;
}
else
{
cout<<"Test failed!"<<endl;
}
}
if(choice==11)
{
cout<<"creates a Node* to null and then inserts 5,4,3,2,1 at head, in that order\n";
Node* head=NULL;
for(int i=5; i>0; i--)
{
list_head_insert(head,i);
}
Node* head2=NULL;
list_copy(head, head2);
cout<<"copied list should have same values"<<endl;
print_list(head2);
cout<<"now changing original lists first item, copied list should stay the same"<<endl;
head->set_data(53);
print_list(head2);
}*/
} | true |
e4cb72a068fea446a83590024d71c6bf64e2644d | C++ | drbaird2/Restart | /BRDFs/Lambertian.cpp | UTF-8 | 2,170 | 2.6875 | 3 | [] | no_license | #include "Lambertian.h"
#include "../Utilities/Constants.h"
#include "../Samplers/Multijittered.h"
/*******************************************************************
* Constructors
*
*******************************************************************/
Lambertian::Lambertian():
BRDF(),
kd(0.0),
cd(0.0)
{}
Lambertian::Lambertian(const Lambertian& lamb):
BRDF(lamb),
kd(lamb.kd),
cd(lamb.cd)
{}
Lambertian& Lambertian::operator=(const Lambertian& rhs)
{
if (this == &rhs)
{
return *this;
}
BRDF::operator=(rhs);
kd = rhs.kd;
cd = rhs.cd;
return *this;
}
Lambertian::~Lambertian()
{}
shared_ptr<Lambertian> Lambertian::clone(){
return make_shared<Lambertian>(*this);
}
Color Lambertian::func(const Record& recentHits, const Vec3& wo, const Vec3& wi) const{
return cd * kd * invPI;
}
/*******************************************************************
* SampleFunc - When light strikes a diffuse surface it will scatter
* into a hemisphere
*
*******************************************************************/
Color Lambertian::sampleFunc(const Record& recentHits, const Vec3& wo, Vec3& wi, float& pdf) const{
Vec3 w = recentHits.sceneNormal;
Vec3 v = Vec3(0.0034, 1.0, 0.0071) ^ w;
v.unit_vector();
Vec3 u = v ^ w;
Point3 sp = samplerPtr->sampleHemisphere();
wi = sp.xPoint * u + sp.yPoint * v + sp.zPoint * w;
wi.unit_vector();
pdf = recentHits.sceneNormal * wi * invPI;
return kd * cd * invPI;
}
Color Lambertian::rho(const Record& recentHits, const Vec3& wo) const{
return cd * kd;
}
void Lambertian::setKa(const double ka){
kd = ka;
}
void Lambertian::setKd(const double kkd){
kd = kkd;
}
void Lambertian::setCd(const Color& c){
cd = c;
}
void Lambertian::setCd(const double r, const double g, const double b){
cd.red = r;
cd.blue = b;
cd.green = g;
}
void Lambertian::setCd(const double c){
cd.red = c;
cd.green = c;
cd.blue = c;
}
void Lambertian::setSampler(shared_ptr<Sampler> sp)
{
samplerPtr = sp;
samplerPtr->mapSamplesToHemisphere(1);
}
void Lambertian::setSamples(const int numSamples)
{
samplerPtr = make_shared<MultiJittered>(numSamples);
samplerPtr->mapSamplesToHemisphere(1);
} | true |
a4ad34756fe298a51f61dd6fc87427be55dffd4e | C++ | felipefoschiera/Competitive-Programming | /Contests/Escola de Inverno UFRGS 2018/Dia 1/B - Babel.cpp | UTF-8 | 1,498 | 2.65625 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <map>
using namespace std;
#define INF 0x3f3f3f3f
typedef long long ll;
typedef pair<string, string> ss;
typedef pair<int, ss> iss;
typedef vector<ss> vss;
typedef map<string, int> msi;
map<string, vss> LG;
msi dist;
int dijkstra(const string &s, const string &t){
for(auto vtx : LG)
dist[vtx.first] = INF;
dist[s] = 0;
priority_queue<iss, vector<iss>, greater<iss> > Q;
Q.push({0, {s, ""}});
while(!Q.empty()){
string u = Q.top().second.first, x = Q.top().second.second;
Q.pop();
for(auto vtx : LG[u]){
string v = vtx.first, y = vtx.second;
int w = (int) y.size();
if(x[0] == y[0]) continue;
if(dist[v] > dist[u] + w){
dist[v] = dist[u] + w;
Q.push({dist[v], {v, y}});
}
}
}
return dist[t];
}
int main(){
int M;
string O, D, i1, i2, P;
ios_base::sync_with_stdio(false);
cin.tie(0);
while(cin >> M, M != 0){
cin >> O >> D;
LG.clear();
dist.clear();
dist[O] = dist[D] = INF;
for(int i = 0; i < M; i++){
cin >> i1 >> i2 >> P;
LG[i1].push_back({i2, P});
LG[i2].push_back({i1, P});
}
int ans = dijkstra(D, O);
if(ans != INF)
cout << ans << endl;
else
cout << "impossivel" << endl;
}
return 0;
}
| true |
e819ad01d5dea9d347d118e8730548a558db99df | C++ | ryotgm0417/AtCoder | /problems/C/abc059c.cpp | UTF-8 | 1,758 | 2.53125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
#define rep(i,n) for (int i=0; i < (int)(n); i++)
#define rep2(i, s, n) for (int i = (s); i < (int)(n); i++)
using ll = long long;
using VL = vector<ll>;
using VVL = vector<vector<ll>>;
using P = pair<ll, ll>;
// chmin, chmax関数
template<typename T, typename U, typename Comp=less<>>
bool chmax(T& xmax, const U& x, Comp comp={}) {
if(comp(xmax, x)) {
xmax = x;
return true;
}
return false;
}
template<typename T, typename U, typename Comp=less<>>
bool chmin(T& xmin, const U& x, Comp comp={}) {
if(comp(x, xmin)) {
xmin = x;
return true;
}
return false;
}
//---------------------------
int main(){
ll n, tmp=0;
cin >> n;
VL sum(n);
rep(i,n){
ll a;
cin >> a;
tmp += a;
sum[i] = tmp;
}
ll ans = (ll)1 << 60; // INF
// even is pos, odd is neg
ll accum = 0, cnt = 0;
if(sum[0] <= 0){
accum = 1 - sum[0];
cnt = abs(accum);
}
rep2(i,1,n){
ll x = sum[i] + accum;
if(i%2==0 && x <= 0){
accum += abs(x) + 1;
cnt += abs(x) + 1;
}else if(i%2==1 && x >= 0){
accum -= abs(x) + 1;
cnt += abs(x) + 1;
}
}
chmin(ans, cnt);
// even is neg, odd is pos
accum = 0, cnt = 0;
if(sum[0] >= 0){
accum = - 1 - sum[0];
cnt = abs(accum);
}
rep2(i,1,n){
ll x = sum[i] + accum;
if(i%2==0 && x >= 0){
accum -= abs(x) + 1;
cnt += abs(x) + 1;
}else if(i%2==1 && x <= 0){
accum += abs(x) + 1;
cnt += abs(x) + 1;
}
}
chmin(ans, cnt);
cout << ans << endl;
return 0;
} | true |
1396ff39ae484356a5ac5da1b33c371462be51cd | C++ | aocsa/stDBMStarTree | /arboretum/test/PBMTree/Texture.h | UTF-8 | 5,124 | 2.71875 | 3 | [
"BSD-2-Clause"
] | permissive |
//Includes
#include <graphics.hpp>
#include <math.h>
#include <arboretum/stBasicObjects.h>
//Typedefs
typedef stBasicArrayObject<float> stArray;
typedef float TipoDescrMatrix[4][5]; // [ang][dist]
typedef float TipoRungMatrix[4][5][16]; // [ang][dist][degrau]
//Definitions
class TTextureExtractorMCO;
class TDescriptors;
class TDescriptorsDistanceEvaluator;
//--------------------------------------------------------------------------------
/*
TTextureExtractorMCO
This class extracts the features of a given bitmap image.
*/
class TTextureExtractorMCO{
private:
void Reset();
float CoocurMatrix[4][5][16][16]; // [ang][dist][i][j]
public:
TTextureExtractorMCO(){};
~TTextureExtractorMCO(){};
/**
* ExtractFeatures
* Calculate the image texture descriptors, returning them in
* an object of type TDescriptors, created in the process.
* The retured object not belongs to this class after calling the
* function.
*/
TDescriptors* ExtractFeatures(Graphics::TBitmap *image);
bool BuildMCO(Graphics::TBitmap *image);
stArray * GetEntropy(int angles=4, int distances=5);
stArray * GetHomogen(int angles=4, int distances=5);
}; //end class TTextureExtractorMCO
//--------------------------------------------------------------------------------
/*
TDescriptors
This class stores the image feature as texture descriptors
*/
class TDescriptors{
private:
unsigned char *Serialized;
public:
//Entropy
TipoDescrMatrix EntropyMatrix;
//homogeneity
TipoDescrMatrix HomogenMatrix;
//Uniformity or energy
TipoDescrMatrix UniformMatrix;
//Third order moment or distortion
TipoDescrMatrix Moment3Matrix;
//Variance or contrast
TipoDescrMatrix VarianceMatrix;
//Inverse variance or inverse contrast
TipoDescrMatrix VarInvMatrix;
//degree (gradient)
TipoRungMatrix RungMatrix;
TDescriptors();
/**
* This constructor copies the values of the object pointed by obj
*/
TDescriptors(TDescriptors *obj);
~TDescriptors(){
if (Serialized != NULL){
delete [] Serialized;
}//end if
};
float GetEntropy(int ang, int dist){
return EntropyMatrix[ang][dist];
}
float GetHomogen(int ang, int dist){
return HomogenMatrix[ang][dist];
}
float GetUniform(int ang, int dist){
return UniformMatrix[ang][dist];
}
float GetMoment3(int ang, int dist){
return Moment3Matrix[ang][dist];
}
float GetVariance(int ang, int dist){
return VarianceMatrix[ang][dist];
}
float GetVarInv(int ang, int dist){
return VarInvMatrix[ang][dist];
}
float GetRung(int ang, int dist, int degree){
return RungMatrix[ang][dist][degree];
}
// The following methods are required by the stObject interface.
/**
* Creates a perfect clone of this object. This method is required by
* stObject interface.
*
* @return A new instance of TCity wich is a perfect clone of the original
* instance.
*/
TDescriptors * Clone(){
return new TDescriptors(this);
}//end Clone
/**
* Checks to see if this object is equal to other. This method is required
* by stObject interface.
*
* @param obj Another instance of TCity.
* @return True if they are equal or false otherwise.
*/
bool IsEqual(TDescriptors *obj);
/**
* Returns the size of the serialized version of this object in bytes.
* This method is required by stObject interface.
*/
unsigned long GetSerializedSize(void){
return (sizeof(float) * ( (6*(4*5)) + (4*5*16) ) );
}//end GetSerializedSize
/**
* Returns the serialized version of this object.
* This method is required by stObject interface.
*
*/
const unsigned char * Serialize();
/**
* Rebuilds a serialized object.
* This method is required by stObject interface.
*
* @param data The serialized object.
* @param datasize The size of the serialized object in bytes.
* @warning If you don't know how to serialize an object, this methos may
* be a good example.
*/
void Unserialize (const unsigned char *data, unsigned long datasize);
};
//--------------------------------------------------------------------------------
/*
TDescriptorsDistanceEvaluator
This class calculates the distance between two TDescriptors objects
*/
class TDescriptorsDistanceEvaluator {
private:
float distance(TipoDescrMatrix feature1, TipoDescrMatrix feature2);
float distance(TipoRungMatrix feature1, TipoRungMatrix feature2);
public:
TDescriptorsDistanceEvaluator(){};
~TDescriptorsDistanceEvaluator(){};
double GetDistance(TDescriptors *obj1, TDescriptors *obj2);
};//end class TDescriptorsDistanceEvaluator
| true |
90c30887ca82d8365da1b921b5fa2770d0e8dc5e | C++ | ShuhengLi/LeetCode | /Leetcode/Palindrome Linked List.cpp | UTF-8 | 534 | 3.828125 | 4 | [] | no_license | /*
Given a singly linked list, determine if it is a palindrome.
Auth
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool isPalindrome(ListNode* head) {
if (!head) return true;
vector<int> v;
while (head != NULL) {
v.push_back(head->val);
head = head->next;
}
int l = 0, r = v.size() - 1;
while (l <= r) {
if (v[l] != v[r]) return false;
l++;
r--;
}
return true;
}
}; | true |
e681e290a173c0b31b8765dc7023dc4c4e168e06 | C++ | dma117/Labs_CPlusPlus | /HashMap_lab/HashMap/main.cpp | UTF-8 | 1,628 | 3.328125 | 3 | [] | no_license | #include <iostream>
#include "hash_map.hpp"
#define CATCH_CONFIG_MAIN
#include "../catch.hpp"
TEST_CASE("allocator constructors", "[allocator]") {
SECTION("allocate") {
{
fefu::allocator<int> alloc;
int* place = alloc.allocate();
*place = 2;
REQUIRE(*place == 2);
}
}
SECTION("deallocate") {
{
fefu::allocator<int> alloc;
auto ptr = alloc.allocate(100);
alloc.deallocate(ptr, 100);
}
}
}
TEST_CASE("constructors", "[hash_map]") {
SECTION("default") {
{
fefu::hash_map<int, int> hm;
REQUIRE(hm.empty() == true);
REQUIRE(hm.bucket_count() == 0);
REQUIRE(hm.size() == 0);
}
}
SECTION("with parameters") {
{
fefu::hash_map<int, int> hm(13);
REQUIRE(hm.empty() == true);
REQUIRE(hm.bucket_count() == 13);
REQUIRE(hm.size() == 0);
}
{
fefu::hash_map<int, int> hm({ {1, -1}, {3, -80}, {2, 7} }, 3);
REQUIRE(hm.empty() == false);
REQUIRE(hm.bucket_count() == 3);
REQUIRE(hm.size() == 3);
REQUIRE(hm.find(1)->second == -1);
REQUIRE(hm.find(3)->second == -80);
}
}
}
TEST_CASE("insert an element", "[hash_map]") {
{
fefu::hash_map<int, int> hm(13);
hm.insert(std::make_pair(1, 2));
REQUIRE(hm.find(1)->second == 2);
REQUIRE(hm.empty() == false);
REQUIRE(hm.bucket_count() == 13);
REQUIRE(hm.size() == 1);
}
}
| true |
962e9c0f09d454dbc8ca50d006448da8aea33afa | C++ | SW0000J/PS | /BOJ/6000/6064.cpp | UTF-8 | 608 | 2.765625 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
using namespace std;
int gcd(int x, int y) {
while (y != 0) {
int rem = x % y;
x = y;
y = rem;
}
return x;
}
int lcm(int x, int y) {
return (x * y) / gcd(x, y);
}
int main() {
ios::sync_with_stdio(false);
cout.tie(NULL);
cin.tie(NULL);
int T; cin >> T;
for (int tc = 0; tc < T; tc++) {
int M;
int N;
int x;
int y;
cin >> M >> N >> x >> y;
while (x <= lcm(M, N) && x != y) {
if (x < y) {
x += M;
}
else {
y += N;
}
}
if (x != y) {
cout << -1 << "\n";
}
else {
cout << x << "\n";
}
}
return 0;
} | true |
c0149c4ac15606ac4d4a67c49b1ef0374a916977 | C++ | SeonJongYoo/Algorithm | /BOJ/ForCodingTest-CPP/DynamicProgramming/LongestGrowthSeq4.cpp | UTF-8 | 1,171 | 2.8125 | 3 | [] | no_license | // 가장 긴 증가하는 부분수열 4
#include <iostream>
#include <vector>
using namespace std;
int n;
const int MAX = 1001;
int A[MAX];
int dp[MAX];
int parent[MAX];
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> n;
for (int i = 0; i < n; i++)
cin >> A[i];
dp[0] = 1;
for (int i = 1; i < n; i++) {
int tmp = A[i];
for (int j = i-1; j > -1; j--) {
if (tmp > A[j]) {
if (dp[j] + 1 > dp[i]) {
dp[i] = dp[j] + 1;
parent[i] = j;
}
} else if (dp[i] == 0) {
dp[i] = 1;
parent[i] = i;
}
}
}
int res = 0, idx = 0;
for (int i = 0; i < n; i++) {
if (dp[i] > res) {
idx = i;
res = dp[i];
}
}
vector<int> v;
vector<int>::reverse_iterator rit;
while (idx != parent[idx]) {
v.push_back(A[idx]);
idx = parent[idx];
}
v.push_back(A[idx]);
cout << res << "\n";
for (rit = v.rbegin(); rit != v.rend(); rit++) cout << *rit << " ";
return 0;
} | true |
ffe905a1de11da8f9ec7b87d5ff51a43d1145080 | C++ | MarkPrecursor/OpenCV_Practice | /Stitcher_test/main.cpp | UTF-8 | 1,027 | 2.65625 | 3 | [] | no_license | #include <iostream>
#include "opencv2/highgui.hpp"
#include "opencv2/stitching.hpp"
using namespace cv;
using namespace std;
int main()
{
string srcFile[6]={"1.JPG","2.JPG","3.JPG","4.JPG","5.JPG","6.JPG"};
string dstFile="result.jpg";
vector<Mat> imgs;
for(int i=0;i<6;++i)
{
Mat img=imread(srcFile[i]);
if (img.empty())
{
cout<<"Can't read image '"<<srcFile[i]<<"'\n";
system("pause");
return -1;
}
imgs.push_back(img);
}
cout<<"Please wait..."<<endl;
Mat pano;
Stitcher stitcher = Stitcher::createDefault(false);
Stitcher::Status status = stitcher.stitch(imgs, pano);
if (status != Stitcher::OK)
{
cout<<"Can't stitch images, error code=" <<int(status)<<endl;
system("pause");
return -1;
}
imwrite(dstFile, pano);
// namedWindow("Result");
// imshow("Result",pano);
waitKey(0);
// destroyWindow("Result");
system("pause");
return 0;
}
| true |
9d75a109924045f1f83fddc52208cb7ef887ad71 | C++ | mwpowellhtx/simple-pacman-game | /src/cpp/pacmangameconsole/actor_base.hpp | UTF-8 | 1,227 | 2.9375 | 3 | [
"MIT"
] | permissive | #ifndef _ACTOR_BASE_HPP_
#define _ACTOR_BASE_HPP_
#include "positioned.h"
#include <functional>
#include <vector>
namespace pacman {
template<
class Derived
, class Input
>
class actor_base
: public positioned {
public:
typedef Input input_type;
typedef Derived derived_type;
private:
input_type _input;
public:
bool alive;
// TODO: TBD: a proper signal/slot would be better here: i.e. Boost.Signals2
std::vector<std::function<void(derived_type &)>> _moving;
protected:
actor_base(coordinates const & p)
: positioned(p)
, _input()
, _moving()
, alive(true) {
}
~actor_base() {
_moving.clear();
}
public:
void on_moving(std::function<void(derived_type &)> const & callback) {
_moving.push_back(callback);
}
virtual Input & get_input() {
return _input;
}
virtual void moving() {
for (auto & callback : _moving) {
callback(dynamic_cast<derived_type &>(*this));
}
}
};
}
#endif //_ACTOR_BASE_HPP_
| true |
35701f62128db5a6325c61e0d45f2838d598951d | C++ | WhiZTiM/coliru | /Archive2/04/f320ce2cacfc1a/main.cpp | UTF-8 | 417 | 3.609375 | 4 | [] | no_license | #include <iostream>
#include <type_traits> // for std::result_of
template<typename Function, Function f>
struct A
{
using function_type = Function;
template<typename... ArgTypes>
typename std::result_of<Function(ArgTypes...)>::type call(ArgTypes... args)
{
return f(args...);
}
};
void func(int i) { std::cout << "Integer: " << i << ".\n"; }
int main()
{
A<decltype(&func), func> a;
a.call(42);
} | true |
f656595f3fbae4615303c491a0701fe797d7fae6 | C++ | Draklob/TicTacToe_SFML | /TicTacToe/SFML_TEMPLATE/SplashState.cpp | UTF-8 | 1,000 | 2.703125 | 3 | [] | no_license | #include "SplashState.h"
#include "DEFINITIONS.h"
#include "MainMenuState.h"
#include <sstream>
#include <iostream>
SplashState::SplashState(GameDataRef data) : _data( data )
{
}
SplashState::~SplashState()
{
}
void SplashState::Init()
{
this->_data->assets.LoadTexture("Splash State Background", SPLASH_SCENE_BACKGROUND_FILEPATH );
_background.setTexture( this->_data->assets.GetTexture("Splash State Background"));
}
void SplashState::HandleInput()
{
sf::Event event;
while( this->_data->window.pollEvent( event ))
{
if( sf::Event::Closed == event.type )
this->_data->window.close();
}
}
void SplashState::Update(float dt)
{
if( this->_clock.getElapsedTime().asSeconds() > SPLASH_STATE_SHOW_TIME )
{
// Switch to the Main Menu
this->_data->machine.AddState( StateRef( new MainMenuState( _data)), true);
}
}
void SplashState::Draw(float dt)
{
this->_data->window.clear( sf::Color::Red );
this->_data->window.draw( this->_background );
this->_data->window.display();
}
| true |
35df746713f28dc1539bcfa0b668bbf4a5924bbc | C++ | Phelixh/MTH_4300 | /_src_/HW4/problem_1.cpp | UTF-8 | 1,731 | 3.71875 | 4 | [] | no_license | #include <iostream>
void modify(long** px, long n, long s){
int x, shift = 0;
// initialize a new array measure with new length size
long *y;
y = new long[s];
// itterating through the original array that we defiend
for (int i = 0; i < n ; ++i){
x = (*px)[i];
// if x is 0 we add three zeros and adjust our shift method
if (x == 0){
for (int j = 0; j < 3; ++j){
y[i+shift] = 1;
++shift; // we compute the shift from our initial i-th position
}
--shift; //one space is accounted for with the original zero, we subtract that
}
else if (x != 5){
y[i+shift] = (*px)[i]; // if not five we simply add to the sequence
}
else {
--shift; // if equal to five we move back one space on the shfit
}
}
// delete the memory of old values for *px and reassin to y-address
delete[] *px;
*px = y;
}
int main() {
long n, x, s, zeros = 0, fives=0;
std::cout << "How many elements would you like to enter" << "\n";
std::cin >> n;
// define our intial sequence as a pointer to array
long *arr;
arr = new long[n];
// insert values into sequence-array and counts the zero/five appearances
std::cout << "Enter your elements into the array" << "\n";
for(int i = 0; i < n; ++i){
std::cin >> x;
if (x == 0){
++zeros;
}
else if (x == 5){
++fives;
}
*(arr+i) = x;
}
s = n + 2*zeros - fives;
// modify our existing list with new size of 3x0 (000) less number of fives
modify(&arr, n, s);
std::cout << "This is your modified array" << "\n";
// print our the elements in our array
for (int j = 0; j < s; ++j){
std::cout << *(arr + j) << " ";
}
std::cout << "\n";
return 0;
}
| true |
11aa7554e5c19416703b83cd75c1a904219a28f1 | C++ | YuePanEdward/PCSNet | /operators/IdxsGather.cc | UTF-8 | 2,453 | 2.546875 | 3 | [] | no_license | #include <tensorflow/core/framework/op.h>
#include <tensorflow/core/framework/shape_inference.h>
#include <tensorflow/core/framework/op_kernel.h>
using namespace tensorflow;
template<typename FLT_TYPE,typename INT_TYPE>
void idxsGather(
FLT_TYPE *feats, // [m,f]
INT_TYPE *nidxs, // [s]
INT_TYPE m,
INT_TYPE s,
INT_TYPE f,
FLT_TYPE *feats_gather // [s,f]
);
REGISTER_OP("IdxsGather")
.Input("feats: float32") //[s,f]
.Input("nidxs: int32") //[s]
.Input("nlens: int32") //[m]
.Output("feats_gather: float32")//[m,f]
.SetShapeFn([](::tensorflow::shape_inference::InferenceContext* c) {
::tensorflow::shape_inference::ShapeHandle feats_shape;
::tensorflow::shape_inference::ShapeHandle nidxs_shape;
::tensorflow::shape_inference::ShapeHandle nlens_shape;
TF_RETURN_IF_ERROR(c->WithRank(c->input(0),2,&feats_shape));
TF_RETURN_IF_ERROR(c->WithRank(c->input(1),1,&nidxs_shape));
TF_RETURN_IF_ERROR(c->WithRank(c->input(1),1,&nlens_shape));
std::initializer_list<shape_inference::DimensionOrConstant> dims=
{c->Dim(nlens_shape,0),c->Dim(feats_shape,1)};
c->set_output(0,c->MakeShape(dims));
return Status::OK();
});
class IdxsGatherOp: public OpKernel
{
public:
explicit IdxsGatherOp(OpKernelConstruction* context) : OpKernel(context)
{
}
void Compute(OpKernelContext* context) override
{
const Tensor& feats=context->input(0);//[s,f]
const Tensor& nidxs=context->input(1);//[s]
const Tensor& nlens=context->input(2);//[m]
int s=feats.dim_size(0),f=feats.dim_size(1),m=nlens.dim_size(0);
OP_REQUIRES(context,nidxs.dim_size(0)==s,errors::InvalidArgument("nidxs dim 0"));
std::initializer_list<int64> dims={m,f};
Tensor *feats_gather=NULL;
OP_REQUIRES_OK(context,context->allocate_output(0,TensorShape(dims),&feats_gather));
auto feats_p=const_cast<float*>(feats.shaped<float,2>({s,f}).data());
auto nidxs_p=const_cast<int*>(nidxs.shaped<int,1>({s}).data());
auto nlens_p=const_cast<int*>(nlens.shaped<int,1>({m}).data());
auto feats_gather_p=feats_gather->shaped<float,2>({m,f}).data();
idxsGather(feats_p,nidxs_p,m,s,f,feats_gather_p);
}
};
REGISTER_KERNEL_BUILDER(Name("IdxsGather").Device(DEVICE_GPU), IdxsGatherOp); | true |
5c3064c2c741d0a06c7a51b02768397735f122d4 | C++ | JohnDelNorte/battleShip | /Computer.h | UTF-8 | 865 | 2.734375 | 3 | [] | no_license | #ifndef COM_H
#define COM_H
#include<fstream>
#include<string>
#include"Coord.h"
#include"BattleShip.h"
#include"Sub.h"
#include"Frigate.h"
#include"Cruiser.h"
#include"Destroyer.h"
using namespace std;
class Computer
{
public:
void placeShips();//computer will place its ships randomly;
void printGrid();//for diagnostic.
int getLifeCount(){return totalLife;}
int getRand();
Coord shoot();
bool checkShot(int r, int c);
char tellShot(int r, int c);
bool lost();
private:
bool first;
BattleShip b;
Cruiser c;
Frigate f;
Sub s;
Destroyer d;
char freeSquare='.';
char hit='X';
char miss='0';
Ship *s0=&b;
Ship *s1=&c;
Ship *s2=&f;
Ship *s3=&s;
Ship *s4=&d;
char cBoard [10][10];
char pBoard [10][10];
Ship* ships[5]{s0,s1,s2,s3,s4};
int totalLife;
bool isGoodCoord(Coord &c,char orientation, int shipSize);
};
#endif | true |
e6aa1cfb680cf8d8bb021a8090aee55d0c328f9b | C++ | LimGeon/algorithm | /LimGeon/16236.cpp | UHC | 1,892 | 2.53125 | 3 | [] | no_license | #include <stdio.h>
#include <queue>
#include <windows.h>
using namespace std;
void initVisited();
typedef struct CUR {
int y, x;
int size;
int time;
}CUR;
int map[21][21];
int visited[21][21];
int dx[4] = { 0,-1,1,0 };
int dy[4] = { -1,0,0,1 };
int allTime = 0;
int sharkExp = 0;
int n;
int newStart = 0;
queue<CUR> q;
int main()
{
int startX, startY;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", &map[i][j]);
if (map[i][j] == 9) {
startY = i;
startX = j;
map[i][j] = 0;
}
}
}
CUR StartShark = { startY,startX,2,0 };
q.push(StartShark);
while (!q.empty()) {
CUR NowShark = q.front();
printf("%d %d %d\n", NowShark.y+1, NowShark.x+1, NowShark.time);
q.pop();
for (int i = 0; i < 4; i++) {
CUR NextShark = { NowShark.y + dy[i],NowShark.x + dx[i],NowShark.size,NowShark.time+1 };
if (0 <= NextShark.y && NextShark.y < n && 0 <= NextShark.x && NextShark.x < n) {
if (0 < map[NextShark.y][NextShark.x] && map[NextShark.y][NextShark.x] < NextShark.size) {
//Sleep(1000);
allTime += NextShark.time;
sharkExp++;
map[NextShark.y][NextShark.x] = 0;
if (sharkExp == NextShark.size) {
sharkExp = 0;
NextShark.size++;
}
while (!q.empty()) q.pop();
newStart = 1;
if (q.empty() == 1) printf("ť ϴ.\n");
NextShark.time = 0;
q.push(NextShark);
initVisited();
}
else if ((map[NextShark.y][NextShark.x] == 0 || map[NextShark.y][NextShark.x] == NextShark.size) && visited[NextShark.y][NextShark.x]==0) {
q.push(NextShark);
visited[NextShark.y][NextShark.x] = 1;
}
}
if (newStart == 1) {
newStart = 0;
break;
}
}
}
printf("%d", allTime);
return 0;
}
void initVisited() {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
visited[i][j] = 0;
}
}
} | true |
1d3b921c7a80437916ad1c971139a07f21a41057 | C++ | 2505Fredy/Trabajo-final-de-semestre | /Persona.cpp | UTF-8 | 2,799 | 2.984375 | 3 | [] | no_license | #include "Persona.h"
PersonaJuridica::PersonaJuridica(string &_nombreComercial, string &_razonSocial, string &_domicilioFiscal, string &_nroRUC, string &_fin){
nacionalidad= "PERUANA";
tipoIdentificacion= "RUC";
nombreComercial= _nombreComercial;
razonSocial= _razonSocial;
domicilioFiscal= _domicilioFiscal;
nroRUC= _nroRUC;
fin= _fin;
}
PersonaNatural::PersonaNatural(string &_nombresyApellidos, string &_nroDNI, string &_domicilio, int _edad){
nacionalidad= "PERUANA";
tipoIdentificacion= "DNI";
nombresyApellidos= _nombresyApellidos;
nroDNI= _nroDNI;
domicilio= _domicilio;
edad= _edad;
}
void PersonaJuridica::mostrarInfo(){
cout << "NACIONALIDAD : " << nacionalidad << endl;
cout << "NOMBRE COMERCIAL : " << nombreComercial << endl;
cout << "RAZ\340N SOCIAL : " << razonSocial << endl;
cout << "DOMICILIO FISCAL : " << domicilioFiscal << endl;
cout << "N\351MERO DE " << tipoIdentificacion << " : " << nroRUC << endl;
cout << "FINALIDAD : " << fin << endl;
}
void PersonaNatural::mostrarInfo(){
cout << "NACIONALIDAD : " << nacionalidad << endl;
cout << "NOMBRES Y APELLIDOS : " << nombresyApellidos << endl;
cout << "N\351MERO DE " << tipoIdentificacion << " : " << nroDNI << endl;
cout << "EDAD : " << edad << endl;
}
//Gets Persona
string Persona::getTipoIdentificacion(){
return tipoIdentificacion;
}
//Gets PersonaJuridica
string PersonaJuridica::getNombreComercial(){
return nombreComercial;
}
string PersonaJuridica::getRazonSocial(){
return razonSocial;
}
string PersonaJuridica::getDomicilioFiscal(){
return nroRUC;
}
string PersonaJuridica::getNroRUC(){
return nroRUC;
}
string PersonaJuridica::getFin(){
return fin;
}
//Sets PersonaJuridica
void PersonaJuridica::setNombreComercial(string &nombreComercial_){
nombreComercial= nombreComercial_;
}
void PersonaJuridica::setRazonSocial(string &razonSocial_){
razonSocial= razonSocial_;
}
void PersonaJuridica::setDomicilioFiscal(string &domicilioFiscal_){
domicilioFiscal= domicilioFiscal_;
}
//Gets PersonaNatural
string PersonaNatural::getNombresyApellidos(){
return nombresyApellidos;
}
string PersonaNatural::getNroDNI(){
return nroDNI;
}
string PersonaNatural::getDomicilio(){
return domicilio;
}
int PersonaNatural::getEdad(){
return edad;
}
//Sets PersonaNatural
void PersonaNatural::setNombresyApellidos(string &nombresyApellidos_){
nombresyApellidos= nombresyApellidos_;
}
void PersonaNatural::setNroDNI(string &nroDNI_){
nroDNI= nroDNI_;
}
void PersonaNatural::setDomicilio(string &domicilio_){
domicilio= domicilio_;
}
void PersonaNatural::setEdad(int edad_){
edad= edad_;
}
| true |
15e369985d90090ca3b63af028f5492516317ab5 | C++ | FilipBor/Lab1 | /homework quadratic formula complex solution.cpp | UTF-8 | 3,231 | 4.09375 | 4 | [] | no_license | #include <iostream>
#include <cmath>
int main(){
std::cout <<"Welcome to the quadratic formula solver!"<<std::endl;
float a; // variable for storing coefficient a
float b; // variable for storing coefficient b
float c; // variable for storing coefficient c
std::cout <<"Please input coefficient a\n"; // asking user to input coefficient a by using cout
std::cin >>a; // read input with cin and store it in variable a
std::cout <<"Please input coefficient b\n"; // asking user to input coefficient b by using cout
std::cin >>b; // read input with cin and store it in variable b
std::cout <<"Please input coefficient c\n"; // asking user to input coefficient c by using cout
std::cin >>c; // read input with cin and store it in variable c
if(a == 0 && b == 0) // first pattern of solving quadratic formula
{
std::cout<< "Your x can't be defined " <<std::endl; // printing x value
}
else if ( a == 0) // second pattern of solving quadratic formula
{
float x = -c/b; //variable to compute and store x value
std::cout<< "Your x is: " << x <<std::endl; // printing x value
}
else if ( b == 0 && ((a < 0 && c > 0) || ( a > 0 && c < 0))) // third pattern of solving quadratic formula
{
float x = sqrtf (-c/a); //variable to compute and store x value
std::cout<< "Your x is: " << x <<std::endl; // printing x value
}
else if ( b == 0 && ((a > 0 && c > 0) || ( a < 0 && c < 0))) // continuation of the third pattern
{
std::cout<< "Your x can't be defined " <<std::endl; // printing x value
}
else if ( c == 0 && (b == 0 || a == 0) ) // fourth pattern of solving quadratic formula
{
float x = 0; //variable to store x value
std::cout<<"Your x is: "<< x <<std::endl; // printing x value
}
else if ( c == 0) // continuation of fourth pattern
{
float x1 = 0; // variable to store x1 value
float x2 = -b/a; // variable to compute and store x2 value
std::cout<<"Your x values are: "<< x1; std::cout <<" and "<< x2 <<std::endl; // printing values of both x1 and x2
}
else if (a != 0 && b != 0 && c != 0) // fifth pattern of solving quadratic formula
{
float discriminant = powf(b,2)-4*a*c; // variable to store and compute discriminant value
if(discriminant > 0) // course of action regarding the value of discriminant
{
float x1 = (-b+sqrtf(discriminant))/(2*a); // variable to compute and store x1 value
float x2 = (-b-sqrtf(discriminant))/(2*a); // variable to compute and store x2 value
std::cout<<"Your x values are: "<< x1; std::cout <<" and "<< x2 <<std::endl; // printing both x1 and x2 values
}
else if(discriminant == 0) // course of action regarding the value of discriminant
{
float x0 = -b/(2*a); // variable to store and compute x0 value
std::cout<<"Your x is: "<< x0 <<std::endl; // printing x0 value
}
else if(discriminant < 0) // course of action regarding the value of discriminant
{
std::cout<<"Your x can't be defined"<<std::endl; // printing x value
}
}
return 0;
} | true |
e78864c2b329b11a5d4a9d5251043d5c91488861 | C++ | moskalenko9381/OOPgame | /myOOPGame/consolelogger.h | UTF-8 | 293 | 2.609375 | 3 | [] | no_license | #ifndef CONSOLELOGGER_H
#define CONSOLELOGGER_H
#include "logger.h"
class ConsoleLogger: public Logger
{
std::ostream* output;
int type;
public:
ConsoleLogger();
void write(const std::string& change);
Logger* getNext();
int getTypeLog();
};
#endif // CONSOLELOGGER_H
| true |
92e75d892b75db1f955bc71639a30ba6f18f862f | C++ | AntarikshaKar/C-Primer-5th-Edition | /Chapter 1/1.16.cpp | UTF-8 | 215 | 2.984375 | 3 | [
"MIT"
] | permissive | #include <iostream>
int main()
{
int inp=0,sum=0;
std::cout<<"Enter integer values for sum and non integer to close the program"<<std::endl;
while(std::cin>>inp){
sum+=inp;
}
std::cout<<"sum="<<sum;
return 0;
} | true |
7975db056402155b53f660491d6efeabd58e7763 | C++ | workOnCarrier/AccGrind | /framework/InputRouter.cpp | UTF-8 | 1,230 | 2.5625 | 3 | [] | no_license |
#include "InputRouter.h"
#include <iostream>
namespace AccGrind {
InputRouter::InputRouter ( KeyInputSource &inputSrc, HostInputHandler &InputHandler ): m_InputSource(inputSrc), m_InputHandler(InputHandler){
}
InputRouter::~InputRouter ( ){}
void InputRouter::process (){
std::ostream& outStream = m_InputSource.getOutputStream();
while ( m_InputSource.hasMoreData() ){
std::vector<std::string> optionVector;
m_InputHandler.getOptions(optionVector);
int optionIndex = 0;
for ( auto a:optionVector ) {
outStream << " "<< a.c_str() << std::endl;
}
outStream << "---------> choose option with input :" ;
std::string usrInput = m_InputSource.getNextInput();
outStream << "------------------------- handling input :" << usrInput << std::endl;
bool isInputHandled = m_InputHandler.handleInput ( usrInput );
if ( !isInputHandled ){
outStream << "Error: Input not supported -- stopping processing loop" << usrInput << std::endl;
break;
}// else {continue; // the loop }
}
}
}
| true |
8b6be83a742240b3c3b7e91edad1ddfefb7b2fe4 | C++ | Elavarasi-P/Window_with_Menus_and_Controls | /WP5/Source.cpp | UTF-8 | 3,593 | 2.546875 | 3 | [] | no_license | #ifndef UNICODE
#define UNICODE
#endif
#include <windows.h>
#define FILE_MENU_NEW 1
#define FILE_MENU_OPEN 2
#define FILE_MENU_EXIT 3
#define CHANGE_TITLE 4
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
void AddMenus(HWND hwnd);
void AddControls(HWND hwnd);
HMENU hMenu;
HWND hEdit;
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PWSTR pCmdLine, int nCmdShow)
{
// Register the window class.
const wchar_t CLASS_NAME[] = L"Sample Window Class";
WNDCLASS wc = { };
wc.lpfnWndProc = WindowProc;
wc.hInstance = hInstance;
wc.lpszClassName = CLASS_NAME;
if (!RegisterClass(&wc))
return -1;
// Create the window.
HWND hwnd = CreateWindowEx(
0, // Optional window styles.
CLASS_NAME, // Window class
L"Windows Programming", // Window text
WS_OVERLAPPEDWINDOW, // Window style
// Size and position
// CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
100, 100, 500, 500,
NULL, // Parent window
NULL, // Menu
hInstance, // Instance handle
NULL // Additional application data
);
if (hwnd == NULL)
{
return 0;
}
ShowWindow(hwnd, nCmdShow);
// Run the message loop.
MSG msg = { };
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
case WM_COMMAND:
switch (wParam)
{
case FILE_MENU_EXIT:
DestroyWindow(hwnd);
break;
case FILE_MENU_NEW:
MessageBeep(MB_ICONINFORMATION);
break;
case CHANGE_TITLE:
wchar_t text[100];
GetWindowTextW(hEdit, text, 100);
SetWindowTextW(hwnd, text);
break;
}
case WM_CREATE:
AddMenus(hwnd);
AddControls(hwnd);
break;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd, &ps);
FillRect(hdc, &ps.rcPaint, (HBRUSH)(COLOR_WINDOW + 1));
EndPaint(hwnd, &ps);
}
return 0;
}
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
void AddMenus(HWND hwnd)
{
hMenu = CreateMenu();
HMENU hFileMenu = CreateMenu();
HMENU hSubMenu = CreateMenu();
AppendMenu(hSubMenu, MF_STRING, NULL, L"SubMenu Item");
AppendMenu(hFileMenu, MF_STRING, FILE_MENU_NEW, L"New");
AppendMenu(hFileMenu, MF_POPUP, (UINT_PTR)hSubMenu, L"Open Submenu");
AppendMenu(hFileMenu, MF_SEPARATOR, NULL, NULL);
AppendMenu(hFileMenu, MF_STRING, FILE_MENU_EXIT, L"Exit");
AppendMenu(hMenu, MF_POPUP, (UINT_PTR)hFileMenu, L"File");
AppendMenu(hMenu, MF_STRING, NULL, L"Help");
SetMenu(hwnd, hMenu);
}
void AddControls(HWND hwnd)
{
CreateWindowW(L"Static", L"Enter Text Here:", WS_VISIBLE | WS_CHILD | WS_BORDER | SS_CENTER, 175, 100, 125, 50, hwnd, NULL, NULL, NULL);
hEdit=CreateWindowEx(0,L"Edit", L"...", WS_VISIBLE | WS_CHILD|WS_VSCROLL|WS_BORDER|ES_MULTILINE|ES_AUTOVSCROLL|ES_AUTOHSCROLL, 175, 155, 125, 50, hwnd, NULL, NULL, NULL);
//SendMessage(hwndEdit, WM_SETTEXT, 0, (LPARAM)lpszLatin);
CreateWindowW(L"Button", L"Change Title", WS_VISIBLE | WS_CHILD, 190, 210, 100, 25, hwnd, (HMENU)CHANGE_TITLE, NULL, NULL);
}
| true |
d2bafc78e6a8807ea90a5f00771d041676b124bd | C++ | ayates1306/first-dev | /cplusplus/day13/string.cc | UTF-8 | 3,633 | 3.984375 | 4 | [] | no_license | #include <iostream>
#include <string.h>
// example string class
// will learn about [] operator overloading
using namespace std;
class String
{
public:
// constructors
String(); // basic constructor
String(const char*); // constructor from const char*
// copy constructor
// destructor
~String();
String& operator=(const String &);
String operator+(const String &);
char& operator[](unsigned int offset);
char operator[](unsigned int offset) const;
const char*GetString() const {return theStr;}
private:
String(int); // private constructor
char *theStr;
unsigned int itsLen;
};
// constant offset operator
char String::operator[](unsigned int offset) const
{
if (offset < itsLen)
{
return theStr[offset];
}
return theStr[itsLen-1];
}
char& String::operator[](unsigned int pos)
{
if (pos < itsLen)
return theStr[pos];
else
return theStr[itsLen-1];
}
String::String(int len)
{
theStr = new char[len+1];
for (int i=0;i<len;i++)
{
theStr[i] = '\0';
}
itsLen = len;
cout << "Constructor(int), theStr @ "<< hex << theStr << "\n";
}
String::String(const char*str)
{
itsLen = strlen(str);
theStr = new char[itsLen+1];
cout << "String created in constr str* " << hex << (long) theStr << "\n";
cout << "const str is at " << hex << (long)str << " and its len was "<< dec << itsLen << endl;
for (unsigned int i=0; i<itsLen;i++)
{
theStr[i] = str[i];
}
theStr[itsLen]='\0';
}
String::String() // basic constructor
{
itsLen = 1;
theStr = new char[1];
theStr[0] = '\0';
cout << "Constructor, void, @" << (unsigned long)theStr << "\n";
}
String::~String()
{
cout << "Destructor, theStr @ "<< hex << (long int)theStr<<"\n";
if (theStr != NULL)
{
delete [] theStr;
theStr = NULL;
}
}
String String::operator+(const String &rhs)
{
int TotalLen = itsLen + rhs.itsLen;
String temp(TotalLen+1);
for (unsigned i=0; i<itsLen; i++)
{
temp[i] = theStr[i];
}
for (unsigned i=0; i<rhs.itsLen; i++)
{
temp[itsLen+i] = rhs[i];
}
temp[TotalLen]='\0';
return temp;
}
String& String::operator=(const String &rhs)
{
cout << "assignment operator, this is "<<(long int)this << " &rhs @"<<(long int)&rhs<< "\n";
if (this == &rhs)
{
cout << " this == &rhs\n";
return *this;
}
// free this
// new str based on len of rhs
// copy str from rhs to this
delete [] theStr;
theStr = new char[rhs.itsLen+1];
itsLen = rhs.itsLen;
for (unsigned int i=0; i<rhs.itsLen; i++)
{
theStr[i] = rhs[i];
}
theStr[itsLen] = '\0';
cout << "copied in operator =, new str @ " <<(unsigned long) theStr << "\n";
return *this;
}
int main()
{
String first = "hello";
cout << "first made, @" << hex << (long int)&first << "\n";
cout << "First says " << first.GetString() << "\n";
String second = "second";
cout << "Second made, @"<< hex << (long int)&second << "\n";
cout << "Second says " << second.GetString() << "\n";
first = second; // aka first = first.operator=(second);
cout << "copied\n";
cout << "First says " << first.GetString() << "\n";
first = "thirdly";
cout << "first made, @" << hex << (long int)&first << "\n";
cout << "First says " << first.GetString() << "\n";
first[3] = 'x'; // aka first.operator[](int);
cout << "First says " << first.GetString() << "\n";
cout << "Third element of first string is " << first[3] << endl;
// addition operator
// aka first.operator+(second)
String third = first+second;
cout << "After adding, third is " << third.GetString() << endl;
return 0;
}
| true |
ee96d6367767fb63fdb012b4b146181831c026ae | C++ | Ef55/tfl | /examples/kaleidoscope/src/AST.hpp | UTF-8 | 3,581 | 3.109375 | 3 | [
"BSL-1.0"
] | permissive | #pragma once
#include <string>
#include <vector>
#include <memory>
#include <optional>
class ExprAST;
class PrototypeAST;
class FunctionAST;
template<typename R>
class ASTVisitor {
public:
virtual R number(double v) = 0;
virtual R variable(std::string const& name) = 0;
virtual R binary(char op, ExprAST const& left, ExprAST const& right) = 0;
virtual R call(std::string const& callee, std::vector<ExprAST> const& args) = 0;
};
namespace internal {
class ExprASTImpl {
public:
virtual ~ExprASTImpl() = default;
virtual void visit(ASTVisitor<void>& visitor) const = 0;
};
}
class ExprAST final {
std::shared_ptr<internal::ExprASTImpl> _ast;
ExprAST(internal::ExprASTImpl* ptr);
template<typename R>
struct VoidedASTVisitor: ASTVisitor<void> {
ASTVisitor<R>* underlying;
std::optional<R> result;
VoidedASTVisitor(ASTVisitor<R>& under): underlying(&under), result(std::nullopt) {}
void number(double v) override {
result = std::optional{underlying->number(v)};
}
void variable(std::string const& name) override {
result = std::optional{underlying->variable(name)};
}
void binary(char op, ExprAST const& left, ExprAST const& right) override {
result = std::optional{underlying->binary(op, left, right)};
}
void call(std::string const& callee, std::vector<ExprAST> const& args) override {
result = std::optional{underlying->call(callee, args)};
}
};
public:
static ExprAST number(double v);
static ExprAST variable(std::string const& name);
static ExprAST op(char op, ExprAST const& left, ExprAST const& right);
static ExprAST call(std::string const& callee, std::vector<ExprAST> const& args);
template<typename R>
R visit(ASTVisitor<R>& visitor) const {
VoidedASTVisitor<R> vvis{visitor};
_ast->visit(vvis);
return vvis.result.value();
}
};
class PrototypeAST final {
std::string _name;
std::vector<std::string> _args;
public:
PrototypeAST(std::string const& name, std::vector<std::string> const& args = {});
inline std::string const& name() const { return _name; };
inline std::vector<std::string> const& args() const { return _args; };
};
class FunctionAST final {
PrototypeAST _proto;
ExprAST _body;
public:
FunctionAST(PrototypeAST const& proto, ExprAST const& body);
inline PrototypeAST const& prototype() const { return _proto; };
inline ExprAST const& body() const { return _body; };
};
namespace internal {
class NumberExprAST: public ExprASTImpl {
double _val;
public:
NumberExprAST(double v);
virtual void visit(ASTVisitor<void>& visitor) const override;
};
class VariableExprAST: public ExprASTImpl {
std::string _name;
public:
VariableExprAST(std::string const& name);
virtual void visit(ASTVisitor<void>& visitor) const override;
};
class BinaryExprAST: public ExprASTImpl {
char _op;
ExprAST _left;
ExprAST _right;
public:
BinaryExprAST(char op, ExprAST const& left, ExprAST const& right);
virtual void visit(ASTVisitor<void>& visitor) const override;
};
class CallExprAST: public ExprASTImpl {
std::string _callee;
std::vector<ExprAST> _args;
public:
CallExprAST(std::string const& callee, std::vector<ExprAST> const& args);
virtual void visit(ASTVisitor<void>& visitor) const override;
};
}
| true |
71e3587b0587813edff596790a7dfec3f9b49e98 | C++ | jregenstein/line-maze-bot | /line_maze/line_maze_advanced.ino | UTF-8 | 6,386 | 3.03125 | 3 | [] | no_license | /**Line maze solver
* Jacob Regenstein
*
* Uses left turn rule
*
*
*/
#include "MeOrion.h"
//motor1 is right motor, motor 2 is left motor. I'd like to change this but it works as is and I don't want to introduce bugs
MeDCMotor motor1(M1);
MeDCMotor motor2(M2);
MeBuzzer buzzer;
#define NOTE_A4 440
//leftTurnCount remembers how many left turns it did, +1 for left turn, -1 for right turn. This is to handle cycles
int leftTurnCount = 0;
//number of left turns before we will make a right turn
const int THRESHOLD = 8;
uint8_t motorSpeed = 100;
//Default linear speed, in cm/s
double linearSpeed = 10.0;
//Default angular speed, in deg/s
double angularSpeed = 120.0;
//Scaling factor to convert the motor speed, in cm/s, to a value to send to controllers
double motSpeedLinearScalar = 7.5;
//scaling factor to convert angular rate, in deg/s, to a value to send the controllers
double motSpeedAngularScalar = .65;
//light sensors numbered consecutively, from left to right
MeLightSensor lightSensor1(PORT_1);
MeLightSensor lightSensor2(PORT_6);
MeLightSensor lightSensor3(PORT_5);
MeLightSensor lightSensor4(PORT_2);
//stops all motors
void stop(){
motor1.stop();
motor2.stop();
}
//moves the vehicle forward or backwards at the specified speed, in cm/s
void setLinearVel(double vel){
if(0==vel){
stop();
}else{
motor1.run((int)(vel*motSpeedLinearScalar));
motor2.run(-(int)(vel*motSpeedLinearScalar));
}
}
//sets linear forward speed, with a bias to one side or the other. Positive bias causes a curve to the left
void setLinearVel(double vel, double bias){
if(0==vel){
stop();
}else{
motor1.run((int)((vel + bias)*motSpeedLinearScalar));
motor2.run(-(int)((vel - bias)*motSpeedLinearScalar));
}
}
//turns the vehicle at the specified number of degrees per second. Left turn is positive
void setAngularVel(double vel){
if(0==vel){
stop();
}else{
motor1.run((int)(vel*motSpeedAngularScalar));
Serial.println((int)(vel*motSpeedAngularScalar));
motor2.run((int)(vel*motSpeedAngularScalar));
}
}
//moves forward the specified number of cm
void move(double x){
stop();
setLinearVel(linearSpeed);
delay((int)(1000.0*(x / linearSpeed)));
stop();
delay(100);
}
//turns by a given angle, in degrees
void turn(double theta){
stop();
if(theta>0){
setAngularVel(angularSpeed);
}else if(theta<0){
setAngularVel(-angularSpeed);
}
delay(abs((1000.0*(theta / angularSpeed))));
stop();
delay(100);
}
//returns true if sensor 1 (leftmost sensor) detects a white surface. The following functions do the same, sensors are numbered sequentially left to right.
boolean sensor1(){
return lightSensor1.read() > 500;
}
boolean sensor2(){
return lightSensor2.read() > 500;
}
boolean sensor3(){
return lightSensor3.read() > 500;
}
boolean sensor4(){
return lightSensor4.read() > 500;
}
//keeps the robot on the line. calls evaluateIntersection when it reaches one. It requires lines that are thicker than the two sensors, otherwise it will think it's hit a dead end
void lineFollow(){
setLinearVel(10);
//go until we reach an intersection
while(sensor1() && sensor4()){
//if we're off to the left turn right
if(!sensor3()&& sensor2()){
setLinearVel(10,-5);
while(!sensor3()&& sensor2()){
//delay(5);
}
setLinearVel(10);
}
//if we're off to the right turn left
if(!sensor2()&& sensor3()){
setLinearVel(10,5);
while(!sensor2()&& sensor3()){
//delay(5);
}
setLinearVel(10);
}
if(sensor2() && sensor3()){
uTurn();
setLinearVel(10);
}
delay(10);
}
//call evaluateIntersection()
evaluateIntersection();
}
//called when we get to an intersection
void evaluateIntersection(){
//move farward just a bit so we can make sure the sensors are over the intersection
move(0.5);
boolean backleft = !sensor1();
boolean backright = !sensor4();
//move forward so we can either turn onto lines or detect if we're at the goal.
move(4);
boolean frontleft = !sensor1();
boolean frontright = !sensor4();
//check if we've reached the goal
if(frontleft && frontright) celebrate();
//if we can turn left, turn left
move(4);
if(backleft){
leftTurnCount = 0;
lineFollow();
}
if(leftTurnCount>THRESHOLD && backright){
leftTurnCount = 0;
right();
}
left();
lineFollow();
//if we can't turn left decide if we should turn right or straight
}else{
//if we can go straight, go straight
if(!sensor2() || !sensor3()){
lineFollow();
//if not turn right
}else{
right();
lineFollow();
}
}
}
//turns to the left, then calls lineFollow
void left(){
//update the counter by +1 for recording one more left turn
leftTurnCount += 1;
//get off the line
turn(80);
setAngularVel(angularSpeed);
//turn until we see the next line
while(sensor2() || sensor3()){
//delay(10);
}
stop();
lineFollow();
}
//turns to the right, then calls lineFollow
void right(){
//update the counter by -1 for recording one more right turn
leftTurnCount -= 1;
//make sure the turn counter doesn't go negative
if(leftTurnCount<0) leftTurnCount = 0;
//get off the line
turn(-80);
setAngularVel(-angularSpeed);
//turn until we see the next line
while(sensor2() || sensor3()){
//delay(10);
}
stop();
lineFollow();
}
//turns around, stops on line. Called within lineFollow
void uTurn(){
//update the counter by -2 for recording one more uturn
leftTurnCount -= 2;
//make sure the counter doesn't go negative
if(leftTurnCount<0) leftTurnCount = 0;
move(14);
turn(160);
setAngularVel(angularSpeed);
while(sensor2() || sensor3()){
//delay(10);
}
stop();
}
//behavior when reach goal
void celebrate(){
for (int n=0; n<6; n++){
buzzer.tone(NOTE_A4,300);
delay(100);
buzzer.noTone();
}
//We don't want this loop to end, otherwise the loop function will call lineFollow() again
while(true){
turn(45);
turn(-45);
turn(-45);
turn(45);
}
}
void setup() {
// put your setup code here, to run once:
// initialize serial communications at 9600 bps
Serial.begin(9600);
}
void loop() {
//don't actually need to loop this, but it doesn't really matter. Linefollow will never terminate.
lineFollow();
}
| true |
4f667d10e0dbbe50f623be8886fd5a57a0509220 | C++ | aanchaliitd/Practice2 | /ComputeMeanModeMinMax.cpp | UTF-8 | 1,172 | 3.640625 | 4 | [] | no_license | #include <iostream>
#include <unordered_map>
#include <algorithm>
#include <vector>
using namespace std;
class TempTracker {
public:
TempTracker() : _sum(0), _count(0), _min(INT_MAX), _max(INT_MIN), _modeTemp(-1), _tempCount(111) {}
void insert(int temp) {
_tempCount[temp]++;
_sum += temp;
_count++;
_min = min(_min, temp);
_max = max(_max, temp);
if (_tempCount[_modeTemp] < _tempCount[temp]) {
_modeTemp = temp;
}
}
int getMax() {
return _max;
}
int getMin() {
return _min;
}
double getMean() {
return (_sum / _count);
}
int getMode() {
return _modeTemp;
}
private:
double _sum;
int _count;
int _min;
int _max;
int _modeTemp;
vector<int> _tempCount;
};
int main ()
{
TempTracker t;
t.insert(4);
t.insert(7);
t.insert(7);
t.insert(10);
cout << "Get max temp : " << t.getMax()
<< " Get min temp : " << t.getMin()
<< " Get mean temp : " << t.getMean()
<< " Get mode temp : " << t.getMode() << endl;
return 0;
}
| true |
f905110c69b5c83e7e8ceb123c24cd18af371a40 | C++ | juwh/ctci6 | /test/ch07_object_oriented_design/q06_jigsaw/main.cpp | UTF-8 | 779 | 3.25 | 3 | [] | no_license | #pragma region Interview Question
/*
7.6 Jigsaw: Implement an NxN jigsaw puzzle. Design the data structures and explain an algorithm to
solve the puzzle. You can assume that you have a fitsWith method which, when passed two
puzzle edges, returns true if the two edges belong together.
*/
#pragma endregion
#pragma region Hints
/*
Hints:
#192. A common trick when solving a jigsaw puzzle is to separate edge and non-edge pieces.
How will you represent this in an object-oriented manner?
#238. Think about how you might record the position of a piece when you find it. Should it be
stored by row and location?
#283. Which will be the easiest pieces to match first? Can you start with those? Which will be
the next easiest, once you've nailed those down?
*/
#pragma endregion | true |
dcd22cbba5f2e906af00dfac92b9595cb1da3da4 | C++ | thuylinh-uit/Object-Oriented-Programming | /Thi TH CK/Apollo.cpp | UTF-8 | 392 | 2.75 | 3 | [] | no_license | #include "Apollo.h"
Apollo::Apollo()
{
this->alpha = 10;
this->loaiPT = "Van chuyen chuyen cho";
this->N = 15 + rand() % 16;
}
int Apollo::tieuThuNL(int T)
{
return (alpha + N) * T;
}
void Apollo::xuat(int T)
{
PhiThuyen::xuat();
cout << "So luong nguoi: " << N << endl;
cout << "So nhien lieu tieu thu: " << tieuThuNL(T) << endl;
}
Apollo::~Apollo()
{
}
| true |
a3f7d35fdde6baf42b646826c7dcfe5746e75bca | C++ | maple-ysd/data_structure_and_algorithm | /UnionFind/WeightedQuickUnion.h | GB18030 | 1,570 | 3.578125 | 4 | [] | no_license | #ifndef WEIGHTEDQUICKUNION_H_
#define WEIGHTEDQUICKUNION_H_
#include <iostream>
class WeightedQuickUnion
{
public:
WeightedQuickUnion(int n);
~WeightedQuickUnion() { delete arr; delete weight; }
int count() { return sz; }
bool connected(int p, int q) { return find(p) == find(q); }
int find(int p);
void Union(int p, int q);
private:
int *arr;
int sz; // ͨ
int capacity; // С
int *weight; // ɭֽڵʱȽϣڵٵɭָڽڵɭ
};
WeightedQuickUnion::WeightedQuickUnion(int n)
{
if (n <= 0)
{
std::cout << "the connected component in WeightedQuickUnion construction must be positive.\n";
std::exit(EXIT_FAILURE);
}
arr = new int[n];
weight = new int[n];
if (!arr || !weight)
{
std::cout << "memory allocation in WeightedQuickUnion construction failed.\n";
std::exit(EXIT_FAILURE);
}
for (int i = 0; i < n; ++i)
{
arr[i] = i;
weight[i] = 1;
}
sz = capacity = n;
}
int WeightedQuickUnion::find(int p)
{
while (p != arr[p])
p = arr[p];
return p;
}
// Ologn
void WeightedQuickUnion::Union(int p, int q)
{
int fp = find(p);
int fq = find(q);
if (fp == fq) return;
if (weight[fp] < weight[fq])
{
arr[fp] = fq;
weight[fq] += weight[fp];
}
else
{
arr[fq] = fp;
weight[fp] += weight[fq];
}
--sz;
}
#endif // WEIGHTEDQUICKUNION_H_
| true |
325dcbd31e7795bf36bbf5f090b52c341b1f4990 | C++ | Forwil/myusaco | /3.4/rockers.cpp | UTF-8 | 916 | 2.640625 | 3 | [] | no_license | /*
ID: forwil11
PROG: rockers
LANG: C++
*/
#include<algorithm>
#include<iostream>
#include<fstream>
#include<string>
#include<cstring>
#include<vector>
#include<cmath>
#define FILE "rockers"
#define MAX(a,b) (((a)>(b))?(a):(b))
#define MIN(a,b) (((a)>(b))?(b):(a))
using namespace std;
int n,m,t,ans,arr[30];
ifstream fin(FILE".in");
ofstream fout(FILE".out");
void search(int now,int nowm,int remind,int used)
{
if(used + (n - now) < ans)
return ;
if(used > ans)
ans = used;
if(now == n || remind == 0)
return ;
if(nowm >= arr[now])
{
if (m == arr[now])
search(now + 1,m,remind - 1,used + 1);
else
search(now + 1,nowm - arr[now],remind,used +1);
}
else
if(m >= arr[now])
search(now,m,remind - 1,used);
search(now + 1,nowm,remind,used);
}
int main(void){
int x;
fin >> n >> m >> t;
for(int i=0;i<n;i++)
fin >> arr[i];
search(0,m,t,0);
fout << ans << endl;
return 0;
}
| true |
32611fc2ab1eabe6951fd3b794704e35ad165b8f | C++ | NguyenTheAn/nn-cpp | /lib/matrix/matrix.cpp | UTF-8 | 11,163 | 3.28125 | 3 | [] | no_license | #include "matrix.h"
#ifdef _DEBUG
#define LOG(x) std::cout << x << std::endl
#endif // _DEBUG
Matrix::Matrix() : m_Rows(0), m_Columns(0), m_Matrix() {
}
Matrix::Matrix(unsigned int rows, unsigned int columns, double initValue) : m_Rows(rows), m_Columns(columns), m_Matrix(rows*columns) {
if (initValue == -1)
Randomize();
else
std::fill(m_Matrix.begin(), m_Matrix.end(), initValue);
}
Matrix::Matrix(const Matrix & matrix) : m_Rows(matrix.m_Rows), m_Columns(matrix.m_Columns), m_Matrix(matrix.m_Matrix) {
}
Matrix::Matrix(Matrix && matrix) : m_Rows(matrix.m_Rows), m_Columns(matrix.m_Columns), m_Matrix(std::move(matrix.m_Matrix)) {
}
Matrix::Matrix(const std::vector<double>& data) : m_Rows(data.size()), m_Columns(1), m_Matrix(data) {
}
Matrix::Matrix(const std::vector<double>& data, unsigned int rows, unsigned int columns)
: m_Rows(rows), m_Columns(columns), m_Matrix(data) {
}
#ifdef _DEBUG
Matrix::Matrix(const std::vector<std::vector<double>>& matrix) : m_Rows(matrix.size()), m_Columns(matrix[0].size()), m_Matrix(matrix.size()*matrix[0].size()) {
for (unsigned int i = 0; i < m_Rows; ++i)
{
for (unsigned int j = 0; j < m_Columns; ++j)
{
(*this)(i, j) = matrix[i][j];
}
}
}
#endif // _DEBUG
Matrix & Matrix::operator=(const Matrix & matrix) {
m_Rows = matrix.m_Rows; m_Columns = matrix.m_Columns;
m_Matrix = matrix.m_Matrix;
return *this;
}
Matrix & Matrix::operator=(Matrix && matrix) {
m_Rows = matrix.m_Rows; m_Columns = matrix.m_Columns; m_Matrix = std::move(matrix.m_Matrix);
return *this;
}
Matrix::~Matrix() {
}
double Matrix::Sum() const {
double sum = 0.0;
return std::accumulate(m_Matrix.begin(), m_Matrix.end(), sum);
}
void Matrix::Randomize(double min, double max) {
std::random_device randomDevice;
std::mt19937 engine(randomDevice());
std::uniform_real_distribution<double> valueDistribution(min, max);
for (unsigned int i = 0; i < m_Rows*m_Columns; ++i)
{
m_Matrix[i] = valueDistribution(engine);
}
}
void Matrix::ZeroOut() {
std::fill(m_Matrix.begin(), m_Matrix.end(), 0);
}
std::vector<double> Matrix::GetColumnVector() const {
#ifdef _DEBUG
if (m_Columns != 1)
throw MatrixError("Number of columns has to be 1 in order to make column vector!");
#endif // _DEBUG
return m_Matrix;
}
std::vector<double> Matrix::GetColumn(unsigned int col) {
std::vector<double> data;
for (int i=0; i< m_Rows; i++){
data.push_back(m_Matrix[col + i*m_Rows]);
}
return data;
}
std::vector<double> Matrix::GetRow(unsigned int row) {
std::vector<double> data;
for (int i=0; i< m_Columns; i++){
data.push_back(m_Matrix[row*m_Columns + i]);
}
return data;
}
void Matrix::AddRow(std::vector<double> in){
m_Matrix.insert(m_Matrix.end(), in.begin(), in.end());
m_Rows++;
}
void Matrix::SaveMatrix(std::ofstream & outfile) const {
outfile.write((char*)(&m_Rows), sizeof(m_Rows));
outfile.write((char*)(&m_Columns), sizeof(m_Columns));
outfile.write((char*)&m_Matrix[0], sizeof(double)*m_Rows*m_Columns);
}
double & Matrix::operator()(unsigned int row, unsigned int column) {
#ifdef _DEBUG
if ((column + row*m_Columns) >= m_Rows*m_Columns)
throw MatrixError("Index out of range!");
#endif // _DEBUG
return m_Matrix[column + row*m_Columns];
}
const double & Matrix::operator()(unsigned int row, unsigned int column) const {
#ifdef _DEBUG
if ((column + row*m_Columns) >= m_Rows*m_Columns)
throw MatrixError("Index out of range!");
#endif // _DEBUG
return m_Matrix[column + row*m_Columns];
}
double & Matrix::operator[](const std::pair<unsigned int, unsigned int>& index) {
#ifdef _DEBUG
if ((index.second + index.first*m_Columns) >= m_Rows*m_Columns)
throw MatrixError("Index out of range!");
#endif // _DEBUG
return m_Matrix[index.second + index.first*m_Columns];
}
const double & Matrix::operator[](const std::pair<unsigned int, unsigned int>& index) const {
#ifdef _DEBUG
if ((index.second + index.first*m_Columns) >= m_Rows*m_Columns)
throw MatrixError("Index out of range!");
#endif // _DEBUG
return m_Matrix[index.second + index.first*m_Columns];
}
Matrix & Matrix::operator+=(const Matrix & other) {
#ifdef _DEBUG
if (!HasSameDimension(other))
throw MatrixError("Matrices do not have the same dimension!");
#endif // _DEBUG
std::transform(m_Matrix.begin(), m_Matrix.end(), other.m_Matrix.begin(), m_Matrix.begin(), std::plus<double>());
return *this;
}
Matrix & Matrix::operator+=(double scalar) {
std::for_each(m_Matrix.begin(), m_Matrix.end(), [scalar](double& x) { x += scalar; });
return *this;
}
Matrix & Matrix::operator-=(const Matrix & other) {
#ifdef _DEBUG
if (!HasSameDimension(other))
throw MatrixError("Matrices do not have the same dimension!");
#endif // _DEBUG
std::transform(m_Matrix.begin(), m_Matrix.end(), other.m_Matrix.begin(), m_Matrix.begin(), std::minus<double>());
return *this;
}
Matrix & Matrix::operator-=(double scalar) {
std::for_each(m_Matrix.begin(), m_Matrix.end(), [scalar](double& x) { x -= scalar; });
return *this;
}
Matrix & Matrix::operator*=(double scalar) {
std::for_each(m_Matrix.begin(), m_Matrix.end(), [scalar](double& x) { x *= scalar; });
return *this;
}
Matrix & Matrix::operator*=(const Matrix & other) {
#ifdef _DEBUG
if (m_Columns != other.m_Rows)
throw MatrixError("Number of columns of the left matrix has to match number of rows of the right matrix!");
#endif // _DEBUG
*this = *this * other;
return *this;
}
Matrix & Matrix::operator/=(double scalar) {
#ifdef _DEBUG
if (scalar == 0)
throw MatrixError("Cannot divide by zero!");
#endif // _DEBUG
std::for_each(m_Matrix.begin(), m_Matrix.end(), [scalar](double& x) { x /= scalar; });
return *this;
}
Matrix & Matrix::ElementWise(const Matrix & other) {
#ifdef _DEBUG
if (!HasSameDimension(other))
throw MatrixError("Matrices do not have the same dimension!");
#endif // _DEBUG
std::transform(m_Matrix.begin(), m_Matrix.end(), other.m_Matrix.begin(), m_Matrix.begin(), std::multiplies<double>());
return *this;
}
Matrix & Matrix::Transpose() {
if (m_Rows != 1 && m_Columns != 1)
{
std::vector<double> transposedMatrix(m_Rows*m_Columns);
for (unsigned int i = 0; i < m_Rows; ++i)
{
for (unsigned int j = 0; j < m_Columns; ++j)
{
transposedMatrix[i + j*m_Rows] = m_Matrix[j + i*m_Columns];
}
}
m_Matrix = std::move(transposedMatrix);
}
std::swap(m_Rows, m_Columns);
return *this;
}
Matrix Matrix::LoadMatrix(std::ifstream & infile) {
unsigned int rows, columns;
infile.read((char*)&rows, sizeof(rows));
infile.read((char*)&columns, sizeof(columns));
Matrix matrix(rows, columns);
double* m = new double[rows*columns];
infile.read((char*)m, sizeof(double)*rows*columns);
std::vector<double> mat(m, m + rows*columns);
matrix.m_Matrix = std::move(mat);
delete[] m;
return matrix;
}
Matrix Matrix::OneHot(unsigned int one, unsigned int size) {
Matrix matrix(1, size, 0);
matrix(0, one) = 1;
return matrix;
}
Matrix Matrix::ElementWise(const Matrix & left, const Matrix & right) {
#ifdef _DEBUG
if (!left.HasSameDimension(right))
throw MatrixError("Matrices do not have the same dimension!");
#endif // _DEBUG
Matrix result(left);
std::transform(result.m_Matrix.begin(), result.m_Matrix.end(), right.m_Matrix.begin(), result.m_Matrix.begin(), std::multiplies<double>());
return result;
}
Matrix Matrix::Transpose(const Matrix & matrix) {
Matrix result(matrix);
if (matrix.m_Rows != 1 && matrix.m_Columns != 1)
{
for (unsigned int i = 0; i < matrix.m_Rows; ++i)
{
for (unsigned int j = 0; j < matrix.m_Columns; ++j)
{
result.m_Matrix[i + j*matrix.m_Rows] = matrix.m_Matrix[j + i*matrix.m_Columns];
}
}
}
std::swap(result.m_Rows, result.m_Columns);
return result;
}
Matrix Matrix::BuildColumnMatrix(unsigned int rows, double value) {
Matrix matrix(rows, 1);
std::fill(matrix.m_Matrix.begin(), matrix.m_Matrix.end(), value);
return matrix;
}
Matrix Matrix::Max(const Matrix & first, const Matrix & second) {
#ifdef _DEBUG
if (!first.HasSameDimension(second))
throw MatrixError("Matrices do not have the same dimension!");
#endif // _DEBUG
Matrix result{ first };
std::transform(result.m_Matrix.begin(), result.m_Matrix.end(), second.m_Matrix.begin(), result.m_Matrix.begin(), [](double a, double b) { return std::max(a, b); });
return result;
}
bool Matrix::HasSameDimension(const Matrix & other) const {
return m_Rows == other.m_Rows && m_Columns == other.m_Columns;
}
std::ostream & operator<<(std::ostream & out, const Matrix & m) {
for (unsigned int i = 0; i < m.m_Rows; ++i)
{
for (unsigned int j = 0; j < m.m_Columns; ++j)
{
out << m.m_Matrix[j + i*m.m_Columns] << " ";
}
out << std::endl;
}
return out;
}
Matrix operator+(const Matrix & left, const Matrix & right) {
#ifdef _DEBUG
if (!left.HasSameDimension(right))
throw MatrixError("Matrices do not have the same dimension!");
#endif // _DEBUG
Matrix result(left);
std::transform(result.m_Matrix.begin(), result.m_Matrix.end(), right.m_Matrix.begin(), result.m_Matrix.begin(), std::plus<double>());
return result;
}
Matrix operator*(const Matrix & matrix, double scalar) {
Matrix result(matrix);
std::for_each(result.m_Matrix.begin(), result.m_Matrix.end(), [scalar](double& x) { x *= scalar; });
return result;
}
Matrix operator*(double scalar, const Matrix & matrix) {
Matrix result(matrix);
std::for_each(result.m_Matrix.begin(), result.m_Matrix.end(), [scalar](double& x) { x *= scalar; });
return result;
}
Matrix operator-(const Matrix & left, const Matrix & right) {
#ifdef _DEBUG
if (!left.HasSameDimension(right))
throw MatrixError("Matrices do not have the same dimension!");
#endif // _DEBUG
Matrix result(left);
std::transform(result.m_Matrix.begin(), result.m_Matrix.end(), right.m_Matrix.begin(), result.m_Matrix.begin(), std::minus<double>());
return result;
}
Matrix operator-(double scalar, const Matrix & matrix) {
Matrix result(matrix.m_Rows, matrix.m_Columns);
result.Map([scalar](double x) { return scalar - x; });
return result;
}
Matrix operator*(const Matrix & left, const Matrix & right) {
#ifdef _DEBUG
if (left.m_Columns != right.m_Rows)
throw MatrixError("Number of columns of the left matrix has to match number of rows of the right matrix!");
#endif // _DEBUG
Matrix result(left.m_Rows, right.m_Columns, 0);
for (unsigned int i = 0; i < left.m_Rows; ++i)
for (unsigned int k = 0; k < left.m_Columns; ++k)
for (unsigned int j = 0; j < right.m_Columns; ++j)
result(i, j) += left(i, k) * right(k, j);
return result;
}
Matrix operator/(const Matrix & matrix, double scalar) {
#ifdef _DEBUG
if (scalar == 0)
throw MatrixError("Cannot divide by zero!");
#endif // _DEBUG
Matrix result(matrix);
std::for_each(result.m_Matrix.begin(), result.m_Matrix.end(), [scalar](double& x) { x /= scalar; });
return result;
}
Matrix operator/(const Matrix & left, const Matrix & right) {
#ifdef _DEBUG
if (!left.HasSameDimension(right))
throw MatrixError("Matrices do not have the same dimension!");
#endif // _DEBUG
Matrix result{ left };
std::transform(result.m_Matrix.begin(), result.m_Matrix.end(), right.m_Matrix.begin(), result.m_Matrix.begin(), std::divides<double>());
return result;
} | true |
dfb4c4612467aeb544bd89c4349fb05fde350e21 | C++ | stevykimpe/oogl | /src/oogl/OOGLException.cpp | UTF-8 | 5,461 | 3.1875 | 3 | [] | no_license | ////////////////////////////////////////////////////////////////////////////////////////////////////
///! \file OOGLException.hpp
///! \brief This file contains the definition of the class oogl::OOGLException and its features.
///! The class oogl::OOGLException is the class used by the framework to send exceptions
///! regarding the other classes of this graphic framework.
///! \author Stevy Kimpe
///! \version 1.0.0
////////////////////////////////////////////////////////////////////////////////////////////////////
#include "OOGLException.hpp" // Inclusion of the header file which declares the class and
// features which get defined here.
//==================================================================================================
// Set the static member with default value.
//==================================================================================================
std::function<std::string(void)> oogl::OOGLException::s_getExternalExceptionMessage
= [] (void) { return std::string(""); }; // Default : no additional message to return
// The map associating exception codes to exception
// messages is defined at the end of the file.
//==================================================================================================
// Class constructor implementation
//==================================================================================================
oogl::OOGLException::OOGLException(oogl::ExceptionCode exceptionCode) noexcept :
m_code(exceptionCode), MessagedException(oogl::OOGLException::getMessageFromCode(exceptionCode))
{}
//==================================================================================================
// Copy constructor implementation
//==================================================================================================
oogl::OOGLException::OOGLException(OOGLException const & exception) noexcept :
m_code(exception.m_code), MessagedException(exception)
{}
//==================================================================================================
// Move constructor implementation
//==================================================================================================
oogl::OOGLException::OOGLException(OOGLException && exception) noexcept :
m_code(exception.m_code), MessagedException(std::move(exception))
{}
//==================================================================================================
// Method that returns the exception message
//==================================================================================================
const char * oogl::OOGLException::what() const throw()
{
return (
std::string(oogl::MessagedException::what()) + "\n"
+ oogl::OOGLException::s_getExternalExceptionMessage()
).c_str();
}
//==================================================================================================
// Set the external function that details graphic library error message
//==================================================================================================
void oogl::OOGLException::setExternalErrorFunction(std::function<std::string(void)> getError)
{
s_getExternalExceptionMessage = getError;
}
//==================================================================================================
// Return the message associated in the map
//==================================================================================================
std::string oogl::OOGLException::getMessageFromCode(oogl::ExceptionCode code) noexcept
{
return oogl::OOGLException::s_mapExceptionCodeMessage.at(code);
}
//==================================================================================================
// Build the map associating the exception codes to exception messages
//==================================================================================================
std::map<oogl::ExceptionCode, std::string> oogl::OOGLException::s_mapExceptionCodeMessage =
{
{
oogl::ExceptionCode::NO_EXCEPTION,
"No detailed exception message."
}, {
oogl::ExceptionCode::OOGL_HANDLER_ALREADY_CREATED,
"A graphic library handler already exist ; you cannot create another one."
}, {
oogl::ExceptionCode::OOGL_HANDLER_NOT_CREATED,
"A graphic library handler must have been created before being either accessed or deleted."
}, {
oogl::ExceptionCode::LIB_ALREADY_INIT,
"A graphic library has already been initialized ; it cannot be initialized twice."
}, {
oogl::ExceptionCode::LIB_NOT_INIT,
"Trying to exit an unitialized library."
}, {
oogl::ExceptionCode::OOGLHANDLER_NULL_OBJ_TRACK,
std::string("A trackable object, i.e. an object the graphic library handler will track")
+ std::string("to be able to free all memory space, should not be given through the null")
+ std::string("pointer.")
}, {
oogl::ExceptionCode::WIN_ALREADY_CREATED,
std::string("The call of the method \\create\\ is make several times for a unique window.")
+ std::string(" A Window instance can only call this method once without calling")
+ std::string(" \\destroy\\.")
}, {
oogl::ExceptionCode::WIN_NOT_CREATED,
"The Window instance which calls \\destroy\\ has not called \\create\\ before."
}
};
| true |
78087a3c66bb255cab098615591a4db5980f8b49 | C++ | Akira-Hayasaka/YES-NO | /addons/ofxColor/examples/ofxColorDemo/src/testApp.cpp | UTF-8 | 1,535 | 2.65625 | 3 | [] | no_license | #include "testApp.h"
#include "ofxColor.h"
void testApp::setup(){
ofxColorf myColor(.1, .2, .3);
cout << "ofxColorf myColor(.1, .2, .3);" << endl;
cout << myColor << endl << endl;
myColor.setRange(255);
cout << "myColor.setRange(255);" << endl;
cout << myColor << endl << endl;
myColor.setMode(OF_COLOR_HSV);
cout << "myColor.setMode(OF_COLOR_HSV);" << endl;
cout << myColor << endl << endl;
myColor.normalize();
cout << "myColor.normalize();" << endl;
cout << myColor << endl << endl;
myColor.setMode(OF_COLOR_RGB);
cout << "myColor.setMode(OF_COLOR_RGB);" << endl;
cout << myColor << endl << endl;
myColor.reset();
cout << "myColor.reset();" << endl;
cout << myColor << endl << endl;
myColor.set(.1, .2, .3).setRange(255).setMode(OF_COLOR_HSV).normalize().setMode(OF_COLOR_RGB);
cout << "myColor.set(.1, .2, .3).setRange(255).setMode(OF_COLOR_HSV).normalize().setMode(OF_COLOR_RGB);" << endl;
cout << myColor << endl << endl;
myColor.setRed(1.1).clamp();
cout << "myColor.setRed(1.1).clamp();" << endl;
cout << myColor << endl << endl;
ofxColorf target;
target.set(0, 1, 0).setRange(255);
cout << "target.set(0, 1, 0).setRange(255);" << endl;
myColor.lerp(target, .8);
cout << "myColor.lerp(target, .8);" << endl;
cout << myColor << endl << endl;
cout << "myColor.set(0, 1, 0).distance(target.set(255, 0, 0);" << endl;
cout << myColor.set(0, 1, 0).distance(target.set(255, 0, 0)) << endl;
}
void testApp::update(){
}
void testApp::draw(){
}
| true |
2f657d50b115819f75d4b2bef3d90dfc04d24462 | C++ | dtbinh/sedgewick_cpp | /test/sort_spec.cpp | UTF-8 | 2,516 | 2.640625 | 3 | [] | no_license | #include <list>
#include <random>
#include "Binary_insertion_sort.h"
#include "Bubblesort.h"
#include "Heap_sort.h"
#include "Insertion_sort.h"
#include "Insertion_sort_x.h"
// #include "LSD_radix_sort.h"
#include "Mergesort_bu.h"
#include "Mergesort.h"
#include "Mergesort_x.h"
// #include "MSD_radix_sort.h"
#include "Quicksort_3_string.h"
#include "Quicksort_3_way.h"
#include "Quicksort.h"
#include "Quicksort_x.h"
#include "Selection_sort.h"
#include "Shellsort.h"
#include "gtest/gtest.h"
#define SORT_TEST_FACTORY(Sort_namespace) TYPED_TEST(Sort_test, Sort_namespace)\
{\
auto v = random_vector<TypeParam>();\
Sort_namespace::sort(v);\
EXPECT_TRUE(std::is_sorted(v.begin(), v.end()));\
}
namespace {
using namespace ::testing;
template<typename Item_t>
using Dist_t = typename std::conditional<
std::is_floating_point<Item_t>::value,
std::uniform_real_distribution<Item_t>,
std::uniform_int_distribution<Item_t>
>::type;
template<typename Item_t>
struct Sort_test : public ::testing::Test {};
template<typename Item_t>
std::vector<Item_t> random_vector(std::size_t num_elems = 1000)
{
std::random_device rd{};
auto gen = std::default_random_engine{rd()};
auto dist = Dist_t<Item_t>(0, 100);
auto v = std::vector<Item_t>(num_elems);
for (auto i = 0; i < num_elems; ++i) {
v[i] = dist(gen);
}
return v;
}
// add back std::string later
typedef ::testing::Types<char, int, unsigned int, long, float, double> Test_types;
TYPED_TEST_CASE(Sort_test, Test_types);
// TODO: turn into macro to reuse for different sort algorithms
// TYPED_TEST(Sort_test, insertion_sort)
// {
// auto v = random_vector<TypeParam>();
// Insertion_sort::sort(v);
// EXPECT_TRUE(std::is_sorted(v.begin(), v.end()));
// }
SORT_TEST_FACTORY(Binary_insertion_sort)
SORT_TEST_FACTORY(Bubblesort)
SORT_TEST_FACTORY(Heap_sort)
SORT_TEST_FACTORY(Insertion_sort)
SORT_TEST_FACTORY(Insertion_sort_x)
// SORT_TEST_FACTORY(LSD_radix_sort)
SORT_TEST_FACTORY(Mergesort_bu)
SORT_TEST_FACTORY(Mergesort)
// SORT_TEST_FACTORY(Mergesort_x)
// SORT_TEST_FACTORY(MSD_radix_sort)
// SORT_TEST_FACTORY(Quicksort_3_string)
// SORT_TEST_FACTORY(Quicksort_3_way)
SORT_TEST_FACTORY(Quicksort)
SORT_TEST_FACTORY(Quicksort_x)
SORT_TEST_FACTORY(Selection_sort)
SORT_TEST_FACTORY(Shellsort)
} | true |
21d6c20ecebf2dd12825013d970662c3416e6b72 | C++ | ChanceHenderson/Tanks | /engine/include/collider.h | UTF-8 | 383 | 2.703125 | 3 | [] | no_license | #pragma once
#include "drawable.h"
namespace CollisionType
{
enum ctypes
{
Tank, Projectile, Wall
};
}
class Collider : public Drawable
{
protected:
int ctype;
public:
Collider(const char* _image, int layer);
Collider(int w, int h, int layer);
static void do_collision();
int get_ctype();
~Collider();
protected:
virtual void receive_collision(Collider* other) = 0;
};
| true |
bbb6d22fc201216b7588559eceed09433fb79742 | C++ | bharatgudihal/Engine | /Engine/Profiling/Accumulator_Inl.h | UTF-8 | 357 | 2.859375 | 3 | [] | no_license | #pragma once
namespace Engine {
namespace Profiling {
inline Accumulator& Accumulator::operator+=(float time) {
sum += time;
count++;
minTime = minTime > time ? time : minTime;
maxTime = maxTime < time ? time : minTime;
return *this;
}
inline float Accumulator::average() const{
return static_cast<float>(sum / count);
}
}
} | true |
cfb5badad74e2b36a8586085536f6d1fd954362c | C++ | aitakaitov/ZOS | /FileSystem.h | UTF-8 | 7,419 | 3.109375 | 3 | [] | no_license | #ifndef ZOS_FILESYSTEM_H
#define ZOS_FILESYSTEM_H
#include <string>
#include <array>
#include <fstream>
#include <vector>
#define FILENAME_MAX_SIZE 8
#define EXTENSION_MAX_SIZE 3
const int32_t BYTES_PER_INODE = 8192; // there will be 1 inode per BYTES_PER_INODE bytes in FS
const int32_t BLOCK_SIZE = 2048; // data block size in bytes
const int32_t FS_NAME_LENGTH = 12;
struct superblock {
char name[FS_NAME_LENGTH]; // file system name // +------------------------+
int32_t diskSize; // total FS size in bytes // | SUPERBLOCK | 44 bytes
int32_t blockSize; // data block size in bytes // +------------------------+
int32_t blockCount; // data block count // | INODE BITMAP | 1 bit per inode
int32_t inodeCount; // number of inodes // +------------------------+
int32_t inodeMapStartAddress; // inode bitmap start address // | INODES | 40 bytes per inode
int32_t blockMapStartAddress; // data block bitmap start address // +------------------------+
int32_t inodeStartAddress; // inode start address // | BLOCK BITMAP | 1 bit per block
int32_t blockStartAddress; // data block start address // +------------------------+
}; // | BLOCKS | BLOCK_SIZE per block
// +------------------------+
struct inode {
int32_t nodeid; // inode ID
bool isDirectory; // is it a directory?
int8_t references; // number of references to the inode
int32_t fileSize; // file size in bytes
int32_t direct1; // direct references to data blocks
int32_t direct3;
int32_t direct2;
int32_t direct4;
int32_t direct5;
int32_t indirect1; // 1.st order indirect reference to data block ( this -> data block)
int32_t indirect2; // 2.nd order indirect reference to data block ( this -> data block -> data block)
};
struct directoryItem {
int32_t inode; // i-node reference
char itemName[FILENAME_MAX_SIZE + EXTENSION_MAX_SIZE + 1]; // 8 bytes name, 3 bytes extension, 1 byte \0
};
class FileSystem {
public:
superblock *sb; // Superblock loaded into memory
std::fstream fsFile; // File with the FS
std::string currentPath = "/"; // We always start in root directory
int currentInodeAddress; // Address of inode we are currently in
~FileSystem();
// fsIO.cpp
int writeToFS(char *bytes, int length, int32_t address); // Writes to FS
int readFromFS(char *bytes, int length, int32_t address); // Reads from FS
// fsInit.cpp
int createRoot(); // Creates root directory when the FS is created
int loadFileSystem(std::string path); // Loads the file system if it exists
int createFileSystem(std::string path, int sizeBytes); // Creates and loads the file system if it does not exist yet
// cli.cpp
int commandLineLoop(); // Infinite command loop
int processCommand(std::string command); // Processes commands
// createFileOrDir.cpp
int createFileOrDir(std::string path, bool isDirectory, FILE *file = NULL); // Creates a file or a directory
// list.cpp
std::vector<directoryItem> getAllDirItemsFromDirect(int blockAddress); // Fetches all directoryItems from a directly referenced block
int list(int inodeAddress); // Lists items in a directory
// removeDirectory.cpp
int removeDirectory(std::string path); // removes a directory
// findDirITemInInode.cpp
int findDirItemInInode(const std::string& name, inode ind); // returns an address of a directory item in an inode
int searchDirect(int address, const char *name); // searches a direct block for directoryItem
// addDirItemToInode.cpp
int addDirItemToInode(char *name, char *extension, int inodeAddress, int inodeReference); // Adds a directoryItem to an inode
int addDirItemToDirect(char *name, char *extension, int blockAddress, int inodeReference); // Finds an empty place in a direct block and places a directoryItem in it
// removeDirItemFromInode.cpp
void removeDirItemFromInode(const std::string& name, int inodeAddress); // Removes a directoryItem from inode
// createInode.cpp
int createInode(int inodeIndex, int blockIndex, int parentInodeAddress, FILE *bytes, bool isDirectory); // Creates an inode, be it file or directory
int fillBlock(int blockAddress, char *bytes, int length); // Fills a block with data from an external file
int getBlocksNecessary(int sizeBytes); // Calculates number of blocks necessary to store a file
// bitmapOperations.cpp
int toggleBitInBitmap(int bitIndex, int bitmapAddress, int bitmapSize);
// ln.cpp
int ln(std::string pathToFile, std::string pathToLink); // creates a hardlink
// getInodeAddressForPath.cpp
int getInodeAddressForPath(std::string path); // returns address of an inode specified by a path
// getFreeInode.cpp
int getFreeInode(); // returns an index of a free inode
int getFreeInodesNum(); // returns count of free inodes
// getFreeBlock.cpp
int getFreeBlock(); // returns an index of a free block
int getFreeBlocksNum(); // returns count of free blocks
// removeFile.cpp
int removeFile(std::string path); // removes a file, check for number of references
int fillDirectWithDI(int blockAddress, std::vector<directoryItem> &dirItems); // Fills a direct block with directoryItems
int defragmentDirects(inode &ind); // Defragments the direct blocks of an directory inode
// outcp.cpp
int outcp(std::string filePath, const std::string& outputPath); // Copies a file to an external location
// cd.cpp
int cd(std::string path); // changes working directory
// getAbsolutePathToInode.cpp
std::string getAbsolutePathToInode(int inodeAddress); // returns an absolute path to an inode, if the inode exists
// info.cpp
int info(std::string path); // prints out info about a file/dir
// cat.cpp
int cat(std::string path); // Write out a file
// moveFile.cpp
int moveFile(std::string filePath, std::string newPath); // moves a file
// copyFile.cpp
int copyFile(std::string sourcePath, std::string destinationPath); // copies a file
};
#endif //ZOS_FILESYSTEM_H
| true |
ec6a7b62537560d0d537a701e398d58bab326283 | C++ | blockspacer/HelenaFramework | /Helena/Concurrency/Internal.hpp | UTF-8 | 1,441 | 2.578125 | 3 | [
"MIT"
] | permissive | #ifndef HELENA_CONCURRENCY_INTERNAL_HPP
#define HELENA_CONCURRENCY_INTERNAL_HPP
#include <Helena/Defines.hpp>
#include <type_traits>
namespace Helena::Concurrency::Internal {
#ifdef __cpp_lib_hardware_interference_size
inline constexpr std::size_t cache_line = std::hardware_destructive_interference_size;
#else
inline constexpr std::size_t cache_line = 64;
#endif
template <typename T, typename = std::enable_if_t<std::is_integral_v<T>>>
[[nodiscard]] inline constexpr T log2(const T value) noexcept;
template <typename T, typename = std::enable_if_t<std::is_integral_v<T>>>
[[nodiscard]] inline constexpr T increment(const T value) noexcept;
template <typename T, typename = std::enable_if_t<std::is_integral_v<T>>>
[[nodiscard]] inline constexpr T decrement(const T value) noexcept;
template <typename T, typename = std::enable_if_t<std::is_integral_v<T>>>
[[nodiscard]] inline constexpr T or_equal(const T value, const T align) noexcept;
template <typename T, typename... Args, typename = std::enable_if_t<std::is_integral_v<T>>>
[[nodiscard]] inline constexpr T or_equal(const T value, const T align, Args&&... rest) noexcept;
template <typename T, typename = std::enable_if_t<std::is_integral_v<T>>>
[[nodiscard]] inline constexpr T round_up_to_power_of_2(const T value) noexcept;
}
#include <Helena/Concurrency/Internal.ipp>
#endif // HELENA_CONCURRENCY_INTERNAL_HPP
| true |
3547f0f87b9b63529d1bf7c5831896c11f328970 | C++ | TomHarte/CLK | /Components/KonamiSCC/KonamiSCC.hpp | UTF-8 | 1,867 | 2.625 | 3 | [
"MIT"
] | permissive | //
// KonamiSCC.hpp
// Clock Signal
//
// Created by Thomas Harte on 06/01/2018.
// Copyright 2018 Thomas Harte. All rights reserved.
//
#ifndef KonamiSCC_hpp
#define KonamiSCC_hpp
#include "../../Outputs/Speaker/Implementation/SampleSource.hpp"
#include "../../Concurrency/AsyncTaskQueue.hpp"
namespace Konami {
/*!
Provides an emulation of Konami's Sound Creative Chip ('SCC').
The SCC is a primitive wavetable synthesis chip, offering 32-sample tables,
and five channels of output. The original SCC uses the same wave for channels
four and five, the SCC+ supports different waves for the two channels.
*/
class SCC: public ::Outputs::Speaker::SampleSource {
public:
/// Creates a new SCC.
SCC(Concurrency::AsyncTaskQueue<false> &task_queue);
/// As per ::SampleSource; provides a broadphase test for silence.
bool is_zero_level() const;
/// As per ::SampleSource; provides audio output.
void get_samples(std::size_t number_of_samples, std::int16_t *target);
void set_sample_volume_range(std::int16_t range);
static constexpr bool get_is_stereo() { return false; }
/// Writes to the SCC.
void write(uint16_t address, uint8_t value);
/// Reads from the SCC.
uint8_t read(uint16_t address);
private:
Concurrency::AsyncTaskQueue<false> &task_queue_;
// State from here on down is accessed ony from the audio thread.
int master_divider_ = 0;
std::int16_t master_volume_ = 0;
int16_t transient_output_level_ = 0;
struct Channel {
int period = 0;
int amplitude = 0;
int tone_counter = 0;
int offset = 0;
} channels_[5];
struct Wavetable {
std::uint8_t samples[32];
} waves_[4];
std::uint8_t channel_enable_ = 0;
void evaluate_output_volume();
// This keeps a copy of wave memory that is accessed from the
// main emulation thread.
std::uint8_t ram_[128];
};
}
#endif /* KonamiSCC_hpp */
| true |
f9421740d3f8166a8e168e9240f6de8340c7e890 | C++ | tupieurods/SportProgramming | /Div1/CR215_Div1_A/main.cpp | UTF-8 | 2,477 | 2.71875 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
char str[100009];
int sums[100009][3];
int len, m;
void ReadData()
{
scanf("%s%*c", str);
len = strlen(str);
scanf("%d", &m);
}
int getSum(int id, int l, int r)
{
return sums[r][id] - sums[l - 1][id];
}
void Solve()
{
memset(sums, 0, sizeof(sums));
for(int i = 0; i < len; i++)
{
for(int j = 0; j < 3; j++)
{
sums[i + 1][j] = sums[i][j];
}
sums[i + 1][(int)(str[i] - 'x')]++;
}
int localSum[3];
for(int i = 0; i < m; i++)
{
int l, r;
scanf("%d %d%*c", &l, &r);
int cnt = r - l + 1;
if(cnt < 3)
{
printf("YES\n");
continue;
}
int modRez = cnt % 3;
int divRez = cnt / 3;
for(int j = 0; j < 3; j++)
{
localSum[j] = getSum(j, l, r) - divRez;
}
bool answer = false;
switch(modRez)
{
case 0:
{
//answer = localSum[0] == divRez && localSum[1] == divRez && localSum[2] == divRez;
answer = localSum[0] == 0 && localSum[1] == 0 && localSum[2] == 0;
break;
}
case 1:
{
/*for(int j = 0; j < 3; j++)
{
if(localSum[j] < divRez)
{
break;
}
localSum[j] -= divRez;
}*/
answer = localSum[0] == 0 && localSum[1] == 1 && localSum[2] == 0
|| localSum[0] == 1 && localSum[1] == 0 && localSum[2] == 0
|| localSum[0] == 0 && localSum[1] == 0 && localSum[2] == 1;
break;
}
case 2:
{
/*for(int j = 0; j < 3; j++)
{
if(localSum[j] < divRez)
{
break;
}
localSum[j] -= divRez;
}*/
answer = localSum[0] == 0 && localSum[1] == 1 && localSum[2] == 1
|| localSum[0] == 1 && localSum[1] == 0 && localSum[2] == 1
|| localSum[0] == 1 && localSum[1] == 1 && localSum[2] == 0;
break;
break;
}
default:
{
throw;
}
}
if(answer)
{
printf("YES\n");
}
else
{
printf("NO\n");
}
}
}
void WriteData()
{
printf("\n");
}
int main()
{
int QWE = 1;
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
scanf("%d%*c", &QWE);
#endif
for(int T = 0; T < QWE; T++)
{
ReadData();
Solve();
WriteData();
}
return 0;
} | true |
2823a41898da5d127ef1c101a66db39f2e04aee3 | C++ | jiama843/cs246_review | /testScripts/RAIIPtrs.cc | UTF-8 | 1,049 | 3.84375 | 4 | [] | no_license | #include <iostream>
#include <string>
#include <memory>
using namespace std;
class realObject{
int id;
string s;
public:
realObject(int id, string s): id{id}, s{s}{}
int getId(){
return id;
}
string getS(){
return s;
}
};
class Obj{
public:
int id;
string *p;
};
class uniqueObj{
public:
unique_ptr<Obj> unique_obj = make_unique<Obj>();
virtual void print(){
cout << "unique_obj id: " << unique_obj->id << endl;
}
};
class sharedObj{
public:
shared_ptr<Obj> shared_obj = make_shared<Obj>();
virtual void print(){
cout << "shared_obj id: " << shared_obj->id << endl;
}
};
int main(){
uniqueObj u;
//unique_ptr<Obj> cannotCopy = u.unique_obj; //Cannot copy unique_ptrs
sharedObj s;
//shared_ptr<Obj> canMoveShared = s.shared_obj;
u.print();
s.print();
unique_ptr<Obj> canMoveUnique = std::move(u.unique_obj); //You can move unique_ptrs
cout << canMoveUnique->id << endl;
unique_ptr<realObject> realPtr = make_unique<realObject>(1, "Hello");
cout << realPtr->getS() << endl;
}
| true |
ffe6c70f1726424600d1451f765bed31fe690d8b | C++ | sz-zdy/LeetCode | /Q402_RemoveKDigits.cpp | UTF-8 | 1,493 | 3.390625 | 3 | [] | no_license | /*
* @Author: ShenZheng
* @Date: 2019-09-11 08:32:36
* @Last Modified by: ShenZheng
* @Last Modified time: 2019-09-11 14:30:32
*/
#include <iostream>
#include <stack>
using namespace std;
class Solution1 {
public:
string removeKdigits(string num, int k) {
stack<char> sta;
sta.push(num[0]);
for(int i = 1; i < num.size(); i++){
while(!sta.empty() && num[i] < sta.top() && k > 0){
sta.pop();
k--;
}
if(!(sta.empty() && num[i] == '0'))
sta.push(num[i]);
}
string result = "";
while(!sta.empty()){
result = sta.top() + result;
sta.pop();
}
result = result.substr(0,result.size()-k);
return (result=="" ? "0":result);
}
};
class Solution {
public:
string removeKdigits(string num, int k) {
string result = "";
for(int i = 0; i < num.size(); i++){
while(result.size()>0 && num[i] < result.back() && k > 0){
result.pop_back();
k--;
}
if(!(result.empty() && num[i]=='0')){
result.push_back(num[i]);
}
cout<<result<<endl;
}
result = result.substr(0,result.size()-k);
return (result==""?"0":result);
}
};
int main(){
string num = "10200";
int k = 1;
string result = Solution().removeKdigits(num,k);
cout<<result<<endl;
return 0;
} | true |
8538959f10e3b25a10cc520dd1b2425b12a06175 | C++ | Altu-Bitu/AltuBitu_YY | /0917/2841.cpp | UTF-8 | 1,478 | 3.765625 | 4 | [] | no_license | #include <iostream>
#include <stack>
#include <vector>
using namespace std;
/**
* 각 줄마다 외계인이 누르고 있는 프렛을 스택에 저장하기
* 매 입력에 대해 이번에 누를 프렛이 해당 줄에서 가장 높은 프렛이어야 함
*
* 1. 이번에 눌러야 할 프렛보다 높은 프렛에서 손가락을 전부 떼기
* 2. 만약 이번에 눌러야 할 프렛을 누르고 있지 않다면 누르기
*/
int main() {
int n, p, guitar_string, fret, ans = 0; //ans 가 손을 움직인 횟수 n 음의 수 p 프랫 수
cin >> n >> p;
vector<stack<int>> guitar(7); //1번 줄부터 6번줄 까지
while (n--) {
//입력
cin >> guitar_string >> fret; //줄의 번호와 fret이라는 변수에 현재 프랫 저장
//연산
while (!guitar[guitar_string].empty() && guitar[guitar_string].top() > fret) { //프렛에서 손가락 떼기 - 현재 무엇인가 누른 상태인데 가장 높은 프랫이 fret보다 높을때
ans++; //손가락을 움직인 횟수 +1
guitar[guitar_string].pop(); //가장 높은 프랫 pop
}
if (guitar[guitar_string].empty() || guitar[guitar_string].top() != fret) { //프렛 누르기 - 비어있거나 가장 높은 프랫이 fret이 아닐때
ans++; //손가락을 움직인 횟수 +1
guitar[guitar_string].push(fret); //새로운 fret 입력
}
}
//출력
cout << ans;
} | true |
52ef54423b6769d583626f0fc9adee0fb109124b | C++ | ozakiryota/tsukuba2019 | /src/imu_bias_estimation.cpp | UTF-8 | 4,421 | 2.890625 | 3 | [] | no_license | #include <ros/ros.h>
#include <sensor_msgs/Imu.h>
#include <geometry_msgs/Quaternion.h>
#include <tf/tf.h>
#include <tf/transform_broadcaster.h>
class ImuBiasEstimation{
private:
ros::NodeHandle nh;
/*subscribe*/
ros::Subscriber sub_imu;
/*publish*/
ros::Publisher pub_bias;
/*const*/
const double timelimit = 30.0; //[s]
/*objects*/
std::vector<sensor_msgs::Imu> record;
sensor_msgs::Imu average;
ros::Time time_started;
/*flags*/
bool imu_is_moving = false;
bool initial_algnment_is_done = false;
public:
ImuBiasEstimation();
void Callback(const sensor_msgs::ImuConstPtr& msg);
void ComputeAverage(void);
bool JudgeMoving(void);
void Publication(void);
};
ImuBiasEstimation::ImuBiasEstimation()
{
sub_imu = nh.subscribe("/imu/data", 1, &ImuBiasEstimation::Callback, this);
pub_bias = nh.advertise<sensor_msgs::Imu>("/imu/bias", 1);
}
void ImuBiasEstimation::Callback(const sensor_msgs::ImuConstPtr& msg)
{
if(!initial_algnment_is_done){
double time;
if(record.size()<10){
time = 0.0;
time_started = ros::Time::now();
}
else{
try{
time = (ros::Time::now() - time_started).toSec();
}
catch(std::runtime_error& ex) {
ROS_ERROR("Exception: [%s]", ex.what());
}
imu_is_moving = JudgeMoving();
}
if(imu_is_moving || time>timelimit){
initial_algnment_is_done = true;
if(time>timelimit) std::cout << "time > " << timelimit << "[s]" << std::endl;
else std::cout << "Moved at " << time << "[s]" << std::endl;
std::cout << "bias = " << std::endl << average.angular_velocity.x << std::endl << average.angular_velocity.y << std::endl << average.angular_velocity.z << std::endl;
}
else{
record.push_back(*msg);
ComputeAverage();
}
}
else Publication();
}
void ImuBiasEstimation::ComputeAverage(void)
{
average.angular_velocity.x = 0.0;
average.angular_velocity.y = 0.0;
average.angular_velocity.z = 0.0;
average.linear_acceleration.x = 0.0;
average.linear_acceleration.y = 0.0;
average.linear_acceleration.z = 0.0;
for(size_t i=0;i<record.size();i++){
average.angular_velocity.x += record[i].angular_velocity.x/(double)record.size();
average.angular_velocity.y += record[i].angular_velocity.y/(double)record.size();
average.angular_velocity.z += record[i].angular_velocity.z/(double)record.size();
average.linear_acceleration.x += record[i].linear_acceleration.x/(double)record.size();
average.linear_acceleration.y += record[i].linear_acceleration.y/(double)record.size();
average.linear_acceleration.z += record[i].linear_acceleration.z/(double)record.size();
}
}
bool ImuBiasEstimation::JudgeMoving(void)
{
const float threshold_w = 0.05;
const float threshold_a = 0.5;
if(fabs(record[record.size()-1].angular_velocity.x - average.angular_velocity.x)>threshold_w){
std::cout << "Moved-wx: " << record[record.size()-1].angular_velocity.x - average.angular_velocity.x << std::endl;
return true;
}
if(fabs(record[record.size()-1].angular_velocity.y - average.angular_velocity.y)>threshold_w){
std::cout << "Moved-wy: " << record[record.size()-1].angular_velocity.y - average.angular_velocity.y << std::endl;
return true;
}
if(fabs(record[record.size()-1].angular_velocity.z - average.angular_velocity.z)>threshold_w){
std::cout << "Moved-wz: " << record[record.size()-1].angular_velocity.z - average.angular_velocity.z << std::endl;
return true;
}
if(fabs(record[record.size()-1].linear_acceleration.x - average.linear_acceleration.x)>threshold_a){
std::cout << "Moved-ax: " << record[record.size()-1].linear_acceleration.x - average.linear_acceleration.x << std::endl;
return true;
}
if(fabs(record[record.size()-1].linear_acceleration.y - average.linear_acceleration.y)>threshold_a){
std::cout << "Moved-ay: " << record[record.size()-1].linear_acceleration.y - average.linear_acceleration.y << std::endl;
return true;
}
if(fabs(record[record.size()-1].linear_acceleration.z - average.linear_acceleration.z)>threshold_a){
std::cout << "Moved-az: " << record[record.size()-1].linear_acceleration.z - average.linear_acceleration.z << std::endl;
return true;
}
return false;
}
void ImuBiasEstimation::Publication(void)
{
/*publish*/
average.header = record[record.size()-1].header;
pub_bias.publish(average);
}
int main(int argc, char**argv)
{
ros::init(argc, argv, "imu_bias_estimation");
ImuBiasEstimation imu_bias_estimation;
ros::spin();
}
| true |
e884f7a4ed1998172b0db1765511033301c33835 | C++ | LaZoark/NIU_programming | /C++程式設計/ch06/ex06_01.cpp | BIG5 | 712 | 3.53125 | 4 | [] | no_license | #include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int value=255; // ܼ
int *piVal,*piVal1; //ŧiӾƫAܼ
piVal= &value; //Vvalue ܼƦ}
piVal1=piVal; //piVal1VpiVal}
cout<<"value ="<<value<<" *piVal="<<*piVal<<"*piVal1="<<*piVal1<<endl;
*piVal=300; //s]wpiValܼƪƤe
cout<<"value ="<<value<<" *piVal="<<*piVal<<" *piVal1="<<*piVal1<<endl;
*piVal1=500; //s]wpiVal1ܼƪƤe
cout<<"value ="<<value<<" *piVal="<<*piVal<<" *piVal1="<<*piVal1<<endl;
system("pause");
return 0;
}
| true |
65025b0dc6a385a5ffed97b56de0939d5d3c026b | C++ | mirmik/nos | /nos/fprint/spec.h | UTF-8 | 3,092 | 3.03125 | 3 | [] | no_license | #ifndef NOS_FPRINT_SPEC_H
#define NOS_FPRINT_SPEC_H
/**
@file
*/
#include <ctype.h>
#include <nos/util/buffer.h>
#include <string.h>
namespace nos
{
enum class alignment
{
left,
right,
center
};
enum class text_case
{
upper,
lower,
none
};
struct basic_spec
{
alignment align = alignment::left;
text_case tcase = text_case::none;
int width = 0;
char fill = ' ';
const char *analyze(const char *ptr)
{
if (*ptr == '0')
{
fill = '0';
}
if (isdigit(*ptr))
{
width = strtoul(ptr, (char **)&ptr, 10);
return ptr;
}
switch (*ptr)
{
case '<':
align = alignment::left;
break;
case '>':
align = alignment::right;
break;
case '^':
align = alignment::center;
break;
case 'f':
fill = *++ptr;
break;
}
return ++ptr;
}
};
struct integer_spec : public basic_spec
{
bool hexmode = false;
integer_spec(const nos::buffer &opts)
{
const char *ptr = opts.begin();
const char *end = opts.end();
while (ptr != end)
{
if (*ptr == 'x')
{
hexmode = true;
ptr++;
continue;
}
if (*ptr == 'X')
{
hexmode = true;
tcase = text_case::upper;
ptr++;
continue;
}
ptr = analyze(ptr);
}
}
};
struct float_spec : public basic_spec
{
int after_dot = -1;
float_spec(const nos::buffer &opts)
{
const char *ptr = opts.begin();
const char *end = opts.end();
while (ptr != end)
{
if (*ptr == '.')
{
ptr++;
after_dot = strtoul(ptr, (char **)&ptr, 10);
continue;
}
ptr = analyze(ptr);
}
}
};
struct text_spec : public basic_spec
{
text_spec(const nos::buffer &opts)
{
const char *ptr = opts.begin();
const char *end = opts.end();
while (ptr != end)
{
switch (*ptr)
{
case 'u':
tcase = text_case::upper;
break;
case 'l':
tcase = text_case::lower;
break;
default:
ptr = analyze(ptr);
continue;
}
ptr++;
}
}
};
}
#endif
| true |
9eb03516e9de581a845cf5bedcda54048d083cb5 | C++ | nickoala/LC512 | /test/LC512.cpp | UTF-8 | 4,716 | 2.640625 | 3 | [
"MIT"
] | permissive | #include "LC512.h"
#include <Wire.h>
const uint16_t HighestAddr = 0xffff;
const uint16_t WriteSize = 64;
const uint16_t ReadSize = 128;
enum ee_result ee_write(
uint8_t i2c,
uint16_t* addr, byte* bs, size_t len,
unsigned int ms
) {
if ( *addr + len > HighestAddr + 1 ) return ExceedRomCapacity;
while ( len > 0 ) {
// Actual number of bytes to write in this round:
// length to page boundary, or length of data left,
// whichever is shorter.
//
int n = min( WriteSize - *addr % WriteSize, (int) len );
Wire.beginTransmission( i2c );
Wire.write( *addr >> 8 );
Wire.write( *addr & 0xff );
Wire.write( bs, n );
if ( byte x = Wire.endTransmission() )
return (enum ee_result) x;
bs += n;
*addr += n;
len -= n;
// Wait for it to finish before next operation.
if ( ms > 0 ) {
delay( ms ); // delay a fixed number of milliseconds
}
else {
unsigned long t = millis();
while (1) { // poll for acknowledge
delay( 1 ); // every 1 ms
Wire.beginTransmission( i2c );
if ( Wire.endTransmission() == 0 )
break;
else if ( millis() - t > 20 )
return Timeout;
}
}
}
return Success;
}
enum ee_result ee_addr( uint8_t i2c, uint16_t addr ) {
Wire.beginTransmission( i2c );
Wire.write( addr >> 8 );
Wire.write( addr & 0xff );
return (enum ee_result) Wire.endTransmission();
}
enum ee_result ee_read(
uint8_t i2c,
uint16_t* addr, byte* bs, size_t len
) {
if ( *addr + len > HighestAddr + 1 ) return ExceedRomCapacity;
// Skip if no buffer
if ( !bs ) {
*addr += len;
return ee_addr( i2c, *addr );
}
while ( len > 0 ) {
int n = min( (int) ReadSize, (int) len );
if ( n != Wire.requestFrom( i2c, (uint8_t) n ))
return UnexpectedDataLength;
unsigned long t = millis();
for ( int i=0; i < n; i++ ) {
if ( Wire.available() ) {
*bs++ = Wire.read();
(*addr)++;
len--;
t = millis(); // update read time
}
else if ( millis() - t > 20 ) {
return Timeout;
}
}
}
return Success;
}
enum ee_result ee_uint8(
uint8_t i2c,
uint16_t* addr, uint8_t* xs, size_t len
) {
return ee_read( i2c, addr, (byte*) xs, len );
}
enum ee_result ee_int8(
uint8_t i2c,
uint16_t* addr, int8_t* xs, size_t len
) {
return ee_read( i2c, addr, (byte*) xs, len );
}
enum ee_result ee_uint16(
uint8_t i2c,
uint16_t* addr, uint16_t* xs, size_t len
) {
return ee_read( i2c, addr, (byte*) xs, 2*len );
}
enum ee_result ee_int16(
uint8_t i2c,
uint16_t* addr, int16_t* xs, size_t len
) {
return ee_read( i2c, addr, (byte*) xs, 2*len );
}
enum ee_result ee_uint32(
uint8_t i2c,
uint16_t* addr, uint32_t* xs, size_t len
) {
return ee_read( i2c, addr, (byte*) xs, 4*len );
}
enum ee_result ee_int32(
uint8_t i2c,
uint16_t* addr, int32_t* xs, size_t len
) {
return ee_read( i2c, addr, (byte*) xs, 4*len );
}
enum ee_result ee_float(
uint8_t i2c,
uint16_t* addr, float* xs, size_t len
) {
return ee_read( i2c, addr, (byte*) xs, sizeof(float)*len );
}
enum ee_result ee_double(
uint8_t i2c,
uint16_t* addr, double* xs, size_t len
) {
return ee_read( i2c, addr, (byte*) xs, sizeof(double)*len );
}
enum ee_result ee_uint8_(
uint8_t i2c,
uint16_t* addr, uint8_t* xs, size_t len,
unsigned int ms
) {
return ee_write( i2c, addr, (byte*) xs, len, ms );
}
enum ee_result ee_int8_(
uint8_t i2c,
uint16_t* addr, int8_t* xs, size_t len,
unsigned int ms
) {
return ee_write( i2c, addr, (byte*) xs, len, ms );
}
enum ee_result ee_uint16_(
uint8_t i2c,
uint16_t* addr, uint16_t* xs, size_t len,
unsigned int ms
) {
return ee_write( i2c, addr, (byte*) xs, 2*len, ms );
}
enum ee_result ee_int16_(
uint8_t i2c,
uint16_t* addr, int16_t* xs, size_t len,
unsigned int ms
) {
return ee_write( i2c, addr, (byte*) xs, 2*len, ms );
}
enum ee_result ee_uint32_(
uint8_t i2c,
uint16_t* addr, uint32_t* xs, size_t len,
unsigned int ms
) {
return ee_write( i2c, addr, (byte*) xs, 4*len, ms );
}
enum ee_result ee_int32_(
uint8_t i2c,
uint16_t* addr, int32_t* xs, size_t len,
unsigned int ms
) {
return ee_write( i2c, addr, (byte*) xs, 4*len, ms );
}
enum ee_result ee_float_(
uint8_t i2c,
uint16_t* addr, float* xs, size_t len,
unsigned int ms
) {
return ee_write( i2c, addr, (byte*) xs, sizeof(float)*len, ms );
}
enum ee_result ee_double_(
uint8_t i2c,
uint16_t* addr, double* xs, size_t len,
unsigned int ms
) {
return ee_write( i2c, addr, (byte*) xs, sizeof(double)*len, ms );
}
| true |
e98fa3a9ebff766e39f286c7e332f8f69a6b60cd | C++ | Grifo89/Algorithms | /insertion-sort/insertion-sort.cpp | UTF-8 | 800 | 4.25 | 4 | [] | no_license | // Insertion sort in C++
#include <iostream>
using namespace std;
// Function to print an array
void printArray(int array[], int size){
for (int i = 0; i < size; i++) {
cout << array[i] << " ";
}
cout << endl;
}
void insertionSort(int array[], int size) {
for (int step = 1; step < size; step++) {
int key = array[step];
int j = step - 1;
// Compare key with each element on the left of it until
// an elemnt smaller than it is found.
while (j > 0 && array[j] > key) {
array[j + 1] = array[j];
j = j - 1;
}
array[j + 1] = key;
}
}
int main() {
int arr[] = {12, 11, 4, 3, 7, 9};
int N = sizeof(arr) / sizeof(arr[0]);
insertionSort(arr, N);
printArray(arr, N)
return 0
} | true |
4de059eb74cc1459029c30759dcc0b0d5c78b4f5 | C++ | akm-sabbir/hackerrank | /data_structure/Stacks/simple_text_editor.cpp | UTF-8 | 1,653 | 3.140625 | 3 | [] | no_license | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include<sstream>
#include<stack>
using namespace std;
stack<pair<string,int>> stacks;
string container;
pair<string,int> append(string str){
container.append(str);
//stacks.push(make_pair(str,1));
return make_pair(str,1);
}
pair<string,int> deletes(int k){
string sub = container.substr(container.size()-k,container.size());
// stacks.push(make_pair(sub,2));
container = container.substr(0,container.size()-k);
return make_pair(sub,2);
}
void undo(){
pair<string,int> temp = stacks.top();
if(temp.second == 1)
deletes(temp.first.size());
if(temp.second == 2)
append(temp.first);
stacks.pop();
}
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int N;
string str;
getline(cin, str);
//int table[100][30];
std::string::size_type sz;
N = std::stoi(str, &sz);
string op, s;
//cout << N << endl;
//trieTree<int> *root = new trieTree<int>(30);
//root->init();
int setting = 0;
int number;
int n ;
while (setting < N){
getline(cin, str);
stringstream iss(str);
iss >> n;
if(n == 1){
iss >> s;
stacks.push(append(s));
}
if(n == 2){
iss >> number;
stacks.push(deletes(number));
}
if(n == 3){
iss >> number;
cout << container[number-1] << endl;
}
if(n == 4)
undo();
setting++;
}
return 0;
}
| true |
383023d445c490f9ef908891d789e2347a66c27d | C++ | Naomi1745698/BigPrac | /racer.cpp | UTF-8 | 729 | 2.984375 | 3 | [] | no_license | #include <string>
#include "racer.h"
racer::racer() : spaceship() {
//default racer constructor equals spacceship default constructor
}
racer::racer(std::string rsName, int rsHealth, int rsFuel) : spaceship(rsName, rsFuel, rsFuel) {
//spaceship constructor with defined name, health & fuel
name = rsName;
hullHealth = rsHealth;
fuel = rsFuel;
rowCoordinate = 0;
columnCoordinate = 0;
ID = 'r';
}
racer::~racer() {
//default racer destructor
}
int racer::getHealth() {
return hullHealth;
}
int racer::getResources() {
return fuel;
}
void racer::setHealth(int health) {
hullHealth = (hullHealth + health);
}
void racer::setResources(int ssFuel) {
fuel = (fuel + ssFuel);
} | true |
32db509b0f0f60c4d8f7ce0bf1769ef5e976e830 | C++ | pradeepelamurugu/Competative-programming | /Find All Numbers Disappeared in an Array-leetcode.cpp | UTF-8 | 534 | 3.015625 | 3 | [] | no_license | //link: https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/
class Solution {
public:
vector<int> findDisappearedNumbers(vector<int>& nums) {
vector<int> ans;
// sort(nums.begin(),nums.end());
unordered_set<int> set;
for(auto j:nums){
set.insert(j);
}
for(int i=0;i<nums.size();i++){
if(set.find(i+1)==set.end()){
ans.push_back(i+1);
}
}
return ans;
}
};
| true |
3ff958f247f930af6296ad0f128f441e048064db | C++ | shieldnet/BOJ_shieldnet | /2740.cpp | UTF-8 | 974 | 2.9375 | 3 | [] | no_license | #include <cstdio>
#include <iostream>
#include <vector>
using namespace std;
typedef long long LL;
typedef vector< vector<LL> > Matrix;
Matrix operator* (const Matrix& a, const Matrix& b) {
int n = a.size();
int m = a[0].size();
int l = b[0].size();
Matrix c(n, vector<LL>(l));
for (int i = 0; i < n; i++) {
for (int j = 0; j < l; j++) {
for (int k = 0; k < m; k++) {
c[i][j] += a[i][k] * b[k][j];
}
}
}
return c;
}
int main() {
int n, m;
scanf("%d%d", &n, &m);
Matrix a(n, vector<LL>(m));
for (int r = 0; r < n; r++) {
for (int c = 0; c < m; c++) {
scanf("%d", &a[r][c]);
}
}
scanf("%d%d", &n, &m);
Matrix b(n, vector<LL>(m));
for (int r = 0; r < n; r++) {
for (int c = 0; c < m; c++) {
scanf("%d", &b[r][c]);
}
}
Matrix ret = a*b;
for (int r = 0; r < ret.size(); r++) {
for (int c = 0; c < ret[0].size(); c++) {
printf("%d ", ret[r][c]);
}
printf("\n");
}
return 0;
} | true |
b795be4a8dc576d743a902ac48f8d41af130d527 | C++ | Sparkle17/Polygon | /Polygon.cpp | UTF-8 | 1,562 | 3.5 | 4 | [] | no_license | #include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include "Geometry.h"
using namespace std;
int main(int argc, char* argv[])
{
cout << "Polygon projector" << endl;
cout << argc << endl;
if (argc < 4) {
cout <<
"usage: Polygon.exe X Y Z" << endl <<
"where x, y, z - coordinates of the projected point" << endl <<
"Polygon.txt - text file with coordinates of the polygon points" << endl <<
"Polygon.txt file format:" << endl <<
"first line: number of vertexes (n)" << endl <<
"next n lines each contains three coordinates (x, y, z) separated by space" << endl;
return 0;
}
try {
ifstream inputFile("Polygon.txt", ifstream::in);
if (inputFile.bad())
throw runtime_error("can't open vertex file Polygon.txt");
int numberOfPoints;
inputFile >> numberOfPoints;
if (numberOfPoints < 2)
throw runtime_error("polygon must contain at least 2 points");
vector<Point> points(numberOfPoints);
for (auto& p : points) {
if (inputFile.eof())
throw runtime_error("invalid input file format");
inputFile >> p.x >> p.y >> p.z;
}
Polygon poly(move(points));
Point projected{ stod(argv[1]), stod(argv[2]), stod(argv[3]) };
auto result = poly.calculateProjection(projected);
cout << "Number of solutions: " << result.size() << endl;
for (auto& sol : result)
cout << sol.to_string() << endl;
}
catch (exception& e) {
cout << "exception caught: " << e.what() << endl;
return -1;
}
catch (...) {
cout << "unknown exception caught" << endl;
return -1;
}
return 0;
}
| true |
ecdc2197b098260238dcda488044e8363d895be6 | C++ | ytatsukawa716/intermediate_model | /sort.h | UTF-8 | 1,820 | 3.484375 | 3 | [] | no_license | #ifndef SORT_H
#define SORT_H
#include <vector>
template<typename _T>
_T _MAX(_T x, _T y) { return x < y ? y : x; }
template<typename _T>
_T _MIN(_T x, _T y) { return x > y ? y : x; }
class Sort {
public:
std::vector<int> number;
template<typename _T>
void ascending_sort(std::vector<_T>& A) {
int left = 0;
int right = A.size() - 1;
_Create_number(A.size());
ascendingsort(&A, left, right);
}
template<typename _T>
void descending_sort(std::vector<_T>& A) {
int left = 0;
int right = A.size() - 1;
_Create_number(A.size());
descendingsort(&A, left, right);
}
private:
template<typename _T>
_T med3(_T x, _T y, _T z) { return _MIN(_MAX(x, y), z); }
void _Create_number(int size) {
number = std::vector<int>(size);
for (int i = 0; i < size; i++) number[i] = i;
}
template<typename _T>
void ascendingsort(std::vector<_T>* A, int left, int right) {
if (left < right) {
_T pivot = med3((*A)[left], (*A)[left + (right - left) / 2], (*A)[right]);
int l = left;
int r = right;
while (true) {
while ((*A)[l] < pivot) l++;
while ((*A)[r] > pivot) r--;
if (l >= r) break;
std::swap((*A)[l], (*A)[r]);
std::swap(number[l], number[r]);
l++;
r--;
}
ascendingsort(A, left, l - 1);
ascendingsort(A, r + 1, right);
}
}
template<typename _T>
void descendingsort(std::vector<_T>* A, int left, int right) {
if (left < right) {
_T pivot = med3((*A)[left], (*A)[left + (right - left) / 2], (*A)[right]);
int l = left;
int r = right;
while (true) {
while ((*A)[l] > pivot) l++;
while ((*A)[r] < pivot) r--;
if (l >= r) break;
std::swap((*A)[l], (*A)[r]);
std::swap(number[l], number[r]);
l++;
r--;
}
descendingsort(A, left, l - 1);
descendingsort(A, r + 1, right);
}
}
};
#endif //SORT_H
| true |
850f7bc6f505d257fca31d305c2668f7567b45da | C++ | emrebarisc/AdvancedRayTracing | /Sources/7 - Object Lights, Path Tracing/RandomGenerator.cpp | UTF-8 | 5,135 | 3.078125 | 3 | [] | no_license | /*
* Advanced ray-tracer algorithm
* Emre Baris Coskun
* 2018
*/
#include "RandomGenerator.h"
#include <random>
#include "Math.h"
std::random_device randomDevice; //Will be used to obtain a seed for the random number engine
std::mt19937 randomGenerator(randomDevice()); //Standard mersenne_twister_engine seeded with randomDevice()
std::uniform_real_distribution<float> uniformDistribution(0.0f, 1.0f);
std::normal_distribution<float> gaussianDistribution(0.0f, 1.0f);
std::uniform_int_distribution<unsigned int> uniformIntDistribution;
std::uniform_int_distribution<unsigned int> uniformUnsignedIntDistribution;
// Return random value in [0, 1]
float RandomGenerator::GetRandomFloat()
{
return uniformDistribution(randomGenerator);
}
// Return random value in [0, 1]
float RandomGenerator::GetGaussianRandomFloat()
{
return gaussianDistribution(randomGenerator);
}
// Return random value in [0, max]
float RandomGenerator::GetRandomFloat(float max)
{
return GetRandomFloat() * max;
}
// Return random value in [0, max]
float RandomGenerator::GetGaussianRandomFloat(float max)
{
return GetGaussianRandomFloat() * max;
}
// Return random value in [min, max]
float RandomGenerator::GetRandomFloat(float min, float max)
{
return GetRandomFloat() * (max - min) + min;
}
// Return random value in [min, max]
float RandomGenerator::GetGaussianRandomFloat(float min, float max)
{
return GetGaussianRandomFloat() * (max - min) + min;
}
// Return random value in [-MAX_INT, MAX_INT]
int RandomGenerator::GetRandomInt()
{
return uniformIntDistribution(randomGenerator);
}
// Return random value in [0, max]
int RandomGenerator::GetRandomInt(int max)
{
int randomValue = GetRandomInt();
return randomValue % max;
}
// Return random value in [min, max]
int RandomGenerator::GetRandomInt(int min, int max)
{
return GetRandomInt() % (max - min) + min;
}
// Return random value in [0, MAX_INT]
unsigned int RandomGenerator::GetRandomUInt()
{
return uniformUnsignedIntDistribution(randomGenerator);
}
// Return random unsigned integer in [0, max]
unsigned int RandomGenerator::GetRandomUInt(unsigned int max)
{
unsigned int randomValue = GetRandomUInt();
return randomValue % max;
}
// Return random unsigned integer in [min, max]
unsigned int RandomGenerator::GetRandomUInt(unsigned int min, unsigned int max)
{
return GetRandomUInt() % (max - min) + min;
}
// RandomGenerator unit test
// bool RandomGenerator::UnitTest()
// {
// for(unsigned int i = 0; i < 1000; i++)
// {
// float randomFloat = RandomGenerator::GetRandomFloat();
// if(randomFloat < 0 || randomFloat > 1)
// {
// std::cout << "Error in GetRandomFloat." << std::endl;
// return false;
// }
// srand(time(NULL));
// float min = (float)rand()/(float)(RAND_MAX);
// float max = min + (float)rand()/(float)(RAND_MAX);
// randomFloat = RandomGenerator::GetRandomFloat(max);
// if(randomFloat < 0 || randomFloat > max)
// {
// std::cout << "Error in GetRandomFloat(max)." << std::endl;
// return false;
// }
// randomFloat = RandomGenerator::GetRandomFloat(min, max);
// if(randomFloat < min || randomFloat > max)
// {
// std::cout << "Error in GetRandomFloat(min, max)." << std::endl;
// return false;
// }
// int randomInt = RandomGenerator::GetRandomInt();
// if(randomInt < -MAX_INT || randomInt > MAX_INT)
// {
// std::cout << "Error in GetRandomInt. " << randomInt << std::endl;
// return false;
// }
// randomInt = RandomGenerator::GetRandomInt((int)max);
// if(randomInt < -MAX_INT || randomInt > (int)max)
// {
// std::cout << "Error in GetRandomInt(max). " << randomInt << std::endl;
// return false;
// }
// randomInt = RandomGenerator::GetRandomInt((int)min, (int)max);
// if(randomInt < (int)min || randomInt > (int)max)
// {
// std::cout << "Error in GetRandomInt(min, max). " << randomInt << std::endl;
// return false;
// }
// unsigned int randomUInt = RandomGenerator::GetRandomUInt();
// if(randomUInt < 0 || randomUInt > MAX_UINT)
// {
// std::cout << "Error in GetRandomUInt. " << randomUInt << std::endl;
// return false;
// }
// randomUInt = RandomGenerator::GetRandomUInt((unsigned int)max);
// if(randomUInt < 0 || randomUInt > (unsigned int)max)
// {
// std::cout << "Error in GetRandomUInt(max). " << randomUInt << std::endl;
// return false;
// }
// randomUInt = RandomGenerator::GetRandomUInt((unsigned int)min, (unsigned int)max);
// if(randomUInt < (unsigned int)min || randomUInt > (unsigned int)max)
// {
// std::cout << "Error in GetRandomUInt(min, max). " << randomUInt << std::endl;
// return false;
// }
// }
// return true;
// } | true |
c2c8e79100eae998b183dea283afa6468f371580 | C++ | fedjakova-anastasija/OOD | /ChartDrawer/ChartDrawer/HarmonicOscillations.cpp | UTF-8 | 1,706 | 2.96875 | 3 | [] | no_license | #include "stdafx.h"
#include "HarmonicOscillations.h"
HarmonicOscillations::HarmonicOscillations(HarmonicOscillationTypes harmonicOscillationsType, double amplitude, double frequency, double phase)
: m_amplitude(amplitude)
, m_frequency(frequency)
, m_phase(phase)
, m_harmonicOscillationsType(harmonicOscillationsType)
{
}
double HarmonicOscillations::CalculateValue(double x) const
{
auto function = std::sinl;
if (m_harmonicOscillationsType == HarmonicOscillationTypes::Cos)
{
function = std::cosl;
}
auto calculatedValue = m_amplitude * function(m_frequency * x + m_phase);
return calculatedValue;
}
sig::connection HarmonicOscillations::DoOnHarmonicOscillationsChange(const HarmonicOscillationsChangeSignal::slot_type& handler)
{
return m_harmonicOscillationsChanged.connect(handler);
}
HarmonicOscillationTypes HarmonicOscillations::GetHarmonicOscillationsType() const
{
return m_harmonicOscillationsType;
}
void HarmonicOscillations::SetHarmonicOscillationsType(HarmonicOscillationTypes harmonicOscillationsType)
{
m_harmonicOscillationsType = harmonicOscillationsType;
m_harmonicOscillationsChanged();
}
double HarmonicOscillations::GetAmplitude() const
{
return m_amplitude;
}
void HarmonicOscillations::SetAmplitude(double amplitude)
{
m_amplitude = amplitude;
m_harmonicOscillationsChanged();
}
double HarmonicOscillations::GetFrequency() const
{
return m_frequency;
}
void HarmonicOscillations::SetFrequency(double frequency)
{
m_frequency = frequency;
m_harmonicOscillationsChanged();
}
double HarmonicOscillations::GetPhase() const
{
return m_phase;
}
void HarmonicOscillations::SetPhase(double phase)
{
m_phase = phase;
m_harmonicOscillationsChanged();
} | true |
9d233a1808ce93e7712aa730eded34061ff8fae7 | C++ | GunniMueller/GMHUBDB | /src/hubDB/include_stud/btree.h | UTF-8 | 1,471 | 2.71875 | 3 | [] | no_license | #ifndef _BTREE_H_
#define _BTREE_H_
#include <global.h>
#include <bufferMgr.h>
class BTree
{
public:
friend ostream & operator<<(ostream & stream,BTree & btree);
/*
* Durchsucht den B-Baum nach dem gegebenen key.
*
* Rueckgabewert: gefundenes Tupel oder NULL
*/
Tuple* find(int *key);
/*
* Einfuegen des gegebenen Tupels in den B-Baum.
*
* Rueckgabewert: true, falls insert erfolgreich war
* false, falls ein Tupel mit der gegebenen id existiert
*/
bool insert(Tuple &tuple);
/*
* Entfernt das Tupel mit dem gegebenen Key aus dem B-Baum.
*
* Rueckgabewert: true, falls Entfernen erfolgreich war
* false, falls kein Tupel mit der gegebenen id existiert
*/
bool remove(int &key);
/*
* Statische Methode zum Testen des B-Baums. Die Testroutine soll
* saemtliche Funktionalitaeten des B-Baums in geeigneter Weise
* demonstrieren und testen. Die Implementierung dieser Methode ist in
* einer separaten Datei mit dem Namen btree_test.cpp abzugeben.
*
* Wenn
* das Flag details den Wert true hat, sollen neben den Statusmeldungen
* der einzelnen Testschritte (OKAY, FAILED) weitere Details ueber den
* internen Zustand der wichtigsten Variablen des Filemanagers ausgegeben
* werden.
*/
static void test(bool details);
};
typedef BTree * BTreePtr;
#endif /* _BTREE_H_ */
| true |
fc1865c9ef61225e21f43a1f3b29d68f31921770 | C++ | bayertom/detectproj | /libalgo/source/structures/point/Point3DCartesian.hpp | UTF-8 | 1,998 | 2.53125 | 3 | [] | no_license | // Description: 3D cartesian point
// Copyright (c) 2010 - 2016
// Tomas Bayer
// Charles University in Prague, Faculty of Science
// bayertom@natur.cuni.cz
// This library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this library. If not, see <http://www.gnu.org/licenses/>.
#ifndef Point3DCartesian_HPP
#define Point3DCartesian_HPP
#include <string.h>
//Include correct version of the library
#if CPP11_SUPPORT == 0
#include "libalgo/source/const/Const.h"
#else
#include "libalgo/source/const2/Const.h"
#endif
//Set point ID to 0, initialize static variable
template <typename T>
unsigned int Point3DCartesian <T>::points_cart_id_counter = 0;
template <typename T>
Point3DCartesian <T> & Point3DCartesian <T> ::operator = ( const Point3DCartesian <T> &p )
{
if ( this != &p )
{
point_id = p.point_id;
point_label = p.point_label;
x = p.x;
y = p.y;
z = p.z;
}
return *this;
}
template <typename T>
bool Point3DCartesian <T>::operator == ( const Point3DCartesian <T> &p ) const
{
return ( x - p.x ) * ( x - p.x ) + ( y - p.y ) * ( y - p.y ) < MIN_POSITION_DIFF * MIN_POSITION_DIFF;
}
template <typename T>
void Point3DCartesian <T>::print ( std::ostream * output ) const
{
//Print point
*output << std::fixed << std::setprecision ( 10 );
*output << point_id << " " << x << " " << y << " " << z << '\n';
}
#endif
| true |
22acab17f0b32c49d4866691f2fda871c879ac2d | C++ | fibasile/BrainControl | /sketch/RobotController/RobotController.ino | UTF-8 | 1,547 | 3.0625 | 3 | [
"MIT"
] | permissive | #include "ZumoMotors.h"
#define LED_PIN 13 // user LED pin
#define MAX_SPEED 400 // max motor speed
#define PULSE_WIDTH_DEADBAND 25 // pulse width difference from 1500 us (microseconds) to ignore (to compensate for control centering offset)
#define PULSE_WIDTH_RANGE 350 // pulse width difference from 1500 us to be treated as full scale input (for example, a value of 350 means
// any pulse width <= 1150 us or >= 1850 us is considered full scale)
#define DIR_LEFT 0
#define DIR_UP 1
#define DIR_DOWN 2
#define DIR_RIGHT 3
char inChar;
int left_speed;
int right_speed;
void setup()
{
Serial.begin(57600);
pinMode(LED_PIN, OUTPUT);
}
void stop(){
ZumoMotors::setSpeeds(0, 0);
}
void move(int dir){
left_speed=0;
right_speed=0;
switch (dir){
case DIR_LEFT:
left_speed = 0;
right_speed = 150;
break;
case DIR_UP:
left_speed = 100;
right_speed = 100;
break;
case DIR_DOWN:
left_speed = -100;
right_speed = -100;
break;
case DIR_RIGHT:
left_speed =150;
right_speed = 0;
break;
default:
break;
}
ZumoMotors::setSpeeds(left_speed,right_speed);
delay(2000);
stop();
}
void loop()
{
while (Serial.available()){
inChar = Serial.read();
Serial.print(inChar);
switch (inChar){
case '0':
move(DIR_LEFT);
break;
case '1':
move(DIR_UP);
break;
case '2':
move(DIR_DOWN);
break;
case '3':
move(DIR_RIGHT);
break;
default:
break;
}
}
}
| true |
9fc8134fa906c9c917ea130acc2cdffce9ab39bb | C++ | sasarog/MasClass | /Test/Test.cpp | WINDOWS-1251 | 1,287 | 3.1875 | 3 | [] | no_license |
#include <iostream>
#include <iomanip>
using namespace std;
#define massize 20 //
void main() {
setlocale(0, "russian");
srand(time(0));
//
int mas1[massize];
int mas2[massize];
int mas3[massize];
//
for (int i = 0; i < massize; i++) {
mas1[i] = rand() % 30 - 15;
mas2[i] = rand() % 30 - 15;
mas3[i] = rand() % 30 - 15;
}
//
cout << "| mas1 | mas2 | mas3 |\n______________________\n";
for (int i = 0; i < massize; i++) {
cout << '|' << setw(6) << mas1[i] <<
'|' << setw(6) << mas2[i] <<
'|' << setw(6) << mas3[i] << '|' << endl;
}
cout << "______________________\n";
//
int summ1 = 0, summ2 = 0, summ3 = 0;
for (int i = 0; i < massize; i++) {
summ1 += mas1[i];
summ2 += mas2[i];
summ3 += mas3[i];
}
//
if (summ1 > summ2) {
if (summ1 > summ3) {
cout << " 1 ";
}
else {
cout << " 3 ";
}
}
else {
if (summ2 > summ3) {
cout << " 2 ";
}
else {
cout << " 3 ";
}
}
} | true |
8befc7072f91f9c061ec04b6c03ff0f3af075435 | C++ | CyCelsLab/Multi-aster-swaming | /cytosim/src/test/testmap.cc | UTF-8 | 1,650 | 2.546875 | 3 | [] | no_license | //RCS: $Id: testmap.cc,v 2.3 2005/01/10 17:27:47 foethke Exp $
//-----------------------------tesmap.cc-------------------------
#include "map.h"
#include "random.h"
#include <cstdio>
#include "smath.h"
void trivialTest()
{
real min[] = {0,0,0};
real max[] = {3,3,3};
int size[] = {3,3,3};
Map<1, real> map1;
map1.setDimensions( min, max, size );
map1.allocateEdgeTypeArray();
map1.allocateRegionArray();
map1.dump();
printf("\n");
Map<2, real> map2;
map2.setDimensions( min, max, size );
map2.allocateEdgeTypeArray();
map2.allocateRegionArray();
map2.dump();
printf("\n");
map2.deleteAll();
map2.setDimensions( min, max, size );
map2.setPeriodic();
map2.allocateEdgeTypeArray();
map2.allocateRegionArray();
map2.dump();
printf("\n");
Map<3, real> map3;
map3.setDimensions( min, max, size );
map3.allocateCellArray();
map3.allocateEdgeTypeArray();
map3.allocateRegionArray();
map3.dump();
}
void realtest()
{
printf("Real test...");
real min[] = {-10,-10};
real max[] = { 10, 10};
int size[] = { 10, 10};
Map<2, float> map;
map.setDimensions(min, max, size);
map.setPeriodic();
map.allocateCellArray();
real w[2];
map.clear();
for(int cc=0; cc<120*120; ++cc) {
w[0] = 12*RNG.sreal();
w[1] = 12*RNG.sreal();
++map( w );
}
FILE * test = fopen("testmap.out","w");
map.write(test, 0);
fclose(test);
printf("wrote file testmap.out\n");
}
int main()
{
trivialTest();
realtest();
return 0;
}
| true |
552f0f7ed5185aeb78ced7f9941f92471bcd58ee | C++ | tectronics/safe-haven | /JRX/Source/JRXCharacter.h | UTF-8 | 919 | 2.765625 | 3 | [] | no_license | /*
Class: JRXCharacter
Purpose: Represent a character rendered to the screen
Author: Jehanlos Roman
*/
#ifndef JRX_CHARACTER_H
#define JRX_CHARACTER_H
#include "JRXSpriteAnimated.h"
namespace JRX
{
class JRXCharacter : public JRXSpriteAnimated
{
public:
JRXCharacter( JRXShader* shader, JRXTexture* texture, int id, int x, int y, int width, int height, int xoffset, int yoffset, int xadvance );
// Safely releases the buffers
virtual ~JRXCharacter();
public:
virtual bool Update( float deltaTime );
// Loads the model into the buffers
virtual bool LoadModel( const char* filePath );
///// Accessors
int Id() const { return m_id; }
int XAdvance() const { return m_xadvance; }
private:
int m_id;
int m_x;
int m_y;
int m_width;
int m_height;
int m_xoffset;
int m_yoffset;
int m_xadvance;
};
} // namespace JRX
#endif // JRX_CHARACTER_H | true |
8b2003274e4f534a75d7f4ae80511f984126a274 | C++ | kodakandlaavinash/DoOrDie | /src/Practice/Websites/GeeksForGeeks/BitMagic/Page 2/CountSetBitsInInteger.h | UTF-8 | 1,084 | 2.53125 | 3 | [] | no_license | /*
* CountSetBitsInInteger.h
*
* Created on: Aug 28, 2013
* Author: Avinash
*/
//
// Testing Status
//
#include <string>
#include <vector>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <ctime>
#include <list>
#include <map>
#include <set>
#include <bitset>
#include <functional>
#include <utility>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string.h>
#include <hash_map>
#include <stack>
#include <queue>
#include <limits.h>
using namespace std;
using namespace __gnu_cxx;
#define null NULL
#define PRINT_NEW_LINE printf("\n")
//int main(){
// return -1;
//}
#ifndef COUNTSETBITSININTEGER_H_
#define COUNTSETBITSININTEGER_H_
int CountSetBitsInNumber(int userInput){
int setBitCounter = 0;
while(userInput){
if(userInput%2){
setBitCounter++;
}
userInput /= 2;
}
return setBitCounter;
}
int CountSetBitsAlgo(int userInput){
int setBitCounter = 0;
while(userInput){
userInput = userInput & (userInput-1);
setBitCounter++;
}
return setBitCounter;
}
#endif /* COUNTSETBITSININTEGER_H_ */
| true |
88fca9831c242278ba4212ff656cb6cebcbbc923 | C++ | delicatedx/test | /vector.cpp | UTF-8 | 330 | 3.5 | 4 | [] | no_license | #include<iostream>
#include<vector>//vector 为类模板
#include<string>
using namespace std;
int main()
{
vector<int> vec = {4,3,2,1,6};
for(auto e: vec) //auto为自动类型 随e而自动定义;该循环为范围循环语句,既循环vec内每个元素
cout<<e<<endl;
return 0;
} | true |
4c5733688c5235cf6514f5554f9e2a9e36ea008b | C++ | RealChaser/Cpp_IDioms | /Cpp_IDioms/31_Safe_Bool3.cpp | UHC | 621 | 3.578125 | 4 | [] | no_license | #include <iostream>
using namespace std;
// C++11 explicit
struct Testable
{
// bool Ͻ ȯ ʰ ȯ .
// , if ( t ) ɶ Ͻ bool ȯȴ.
explicit operator bool() const { return false; }
};
struct AnotherTestable
{
explicit operator bool() const { return true; }
};
int main(void)
{
Testable t;
//bool b1 = t; // error. bool Ͻ ȯ ȵ.
bool b2 = static_cast<bool>(t); //
if ( t ) {} // ok.. ǵ ڵ..
AnotherTestable at;
//if (t == at) {} // ?
//if (t < 0) {} // ?
return 0;
} | true |
c45f65ea150dd5589d4d3828c52f82f3a3f0df2a | C++ | Shakti-chaudhary/Cpp-Learn-Code-with-harry- | /14-Friend_function_in_class.cpp | UTF-8 | 809 | 3.546875 | 4 | [] | no_license | #include <iostream>
using namespace std;
/* commplex numbers
11 + 5i
15 + 8i
-------
26 + 13i
*/
class complex
{
int a, b;
public:
void setdata(int n, int m)
{
a = n;
b = m;
}
void printdata()
{
cout << "Your number is : " << a << " and +i is : " << b << endl;
}
// **************************** Freind function *********************************
friend complex addcomplex(complex o1, complex o2);
};
complex addcomplex(complex o1, complex o2)
{
complex o3;
o3.setdata((o1.a + o2.a), (o1.b + o2.b));
return o3;
}
int main()
{
complex A1, A2, sum;
A1.setdata(45, 345);
A1.printdata();
A2.setdata(13, 151);
A2.printdata();
sum = addcomplex(A1, A2);
sum.printdata();
return 0;
} | true |
7b758b7f1ce00774d2ede34ef11d3ceb76214dc9 | C++ | TanveerMH/C-Codes | /try254.cpp | UTF-8 | 297 | 3.515625 | 4 | [] | no_license | #include <iostream>
using namespace std;
void odd(int);
void even(int);
int main ()
{
int num;
cout<<"Enter any number";
cin>>num;
even(num);
return 0;
}
void even(int a )
{
if ( a%2==0)
cout<<"\nEven number";
else odd(a);
}
void odd(int)
{
cout<<"\nOdd number";
}
| true |
f9060296179e97ae7370fdb572228e252664facd | C++ | paschalidoud/RoCKInCamp | /vision_tasks/object_classification/src/soc_test/main.cpp | UTF-8 | 2,744 | 2.734375 | 3 | [] | no_license | /*
* main.cpp
*
* Created on: Sep 7, 2013
* Author: aitor
*/
#include "ros/ros.h"
#include "sensor_msgs/PointCloud2.h"
#include "std_msgs/String.h"
#include "soc_msg_and_serv/segment_and_classify.h"
class SOCDemo
{
private:
int kinect_trials_;
int service_calls_;
ros::NodeHandle n_;
std::string camera_topic_;
bool KINECT_OK_;
void
checkCloudArrive (const sensor_msgs::PointCloud2::ConstPtr& msg)
{
KINECT_OK_ = true;
}
void
checkKinect ()
{
ros::Subscriber sub_pc = n_.subscribe (camera_topic_, 1, &SOCDemo::checkCloudArrive, this);
ros::Rate loop_rate (1);
kinect_trials_ = 0;
while (!KINECT_OK_ && ros::ok ())
{
std::cout << "Checking kinect status..." << std::endl;
ros::spinOnce ();
loop_rate.sleep ();
kinect_trials_++;
if(kinect_trials_ >= 5)
{
std::cout << "Kinect is not working..." << std::endl;
return;
}
}
KINECT_OK_ = true;
std::cout << "Kinect is up and running" << std::endl;
}
void
callService (const sensor_msgs::PointCloud2::ConstPtr& msg)
{
if( (service_calls_ % (30 * 5)) == 0) // classify only every n-th incoming frame, e.g. (at 30 Hz) every 5 seconds
{
std::cout << "going to call service..." << std::endl;
ros::ServiceClient client = n_.serviceClient<soc_msg_and_serv::segment_and_classify>("segment_and_classify");
soc_msg_and_serv::segment_and_classify srv;
srv.request.cloud = *msg;
if (client.call(srv))
{
std::cout << "Found categories:" << static_cast<int>(srv.response.categories_found.size()) << std::endl;
for(size_t i=0; i < srv.response.categories_found.size(); i++)
{
std::cout << " => " << srv.response.categories_found[i] << std::endl;
}
}
else
{
std::cout << "service call failed" << std::endl;
}
}
service_calls_++;
}
public:
SOCDemo()
{
KINECT_OK_ = false;
camera_topic_ = "/camera/depth/points";
kinect_trials_ = 5;
}
bool initialize(int argc, char ** argv)
{
checkKinect();
return KINECT_OK_;
}
void run()
{
ros::Subscriber sub_pc = n_.subscribe (camera_topic_, 1, &SOCDemo::callService, this);
ros::spin();
/*ros::Rate loop_rate (5);
while (ros::ok () && (service_calls_ < 5)) //only calls 5 times
{
ros::spinOnce ();
loop_rate.sleep ();
}*/
}
};
int
main (int argc, char ** argv)
{
ros::init (argc, argv, "SOC_demo");
SOCDemo m;
m.initialize (argc, argv);
m.run();
return 0;
}
| true |
6e3c71064a61519093d4145942fdb7376010f75a | C++ | JeffreyTeo/SP4 | /Base/Source/Save.h | UTF-8 | 983 | 2.515625 | 3 | [] | no_license | #ifndef SAVE_H
#define SAVE_H
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include "Player.h"
#include "Shop.h"
#include "LevelDetails.h"
#include "AllLevelDetails.h"
using namespace std;
class Save
{
public:
Save(void);
~Save(void);
//In case of emergency(Lua files Deleted!)
void SaveEveryThing(int FileNumber);
//Boolean String Conversion
string BoolToStringConversion(bool convert);
//Save AllLevelDetails
void SaveLevelStuff(vector<AllLevelDetails*> theLevelDetailsHolder, int maxleveltutorial, int maxlevel, int maxdifficulty);
//Save Playerinfo
void SavePlayer(Player* playerinfo);
//Save Music
void SaveMusic(float sound);
//Save Shop
void SaveShop(Shop* shopinfo);
//Lua Open Table
string OpenTable(string text);
//Lua Save Table Indiv
string SaveTableIndiv(string text, int integertosave = 0, string booltosave = "", string stringtosave = "");
//Lua Close Table
string CloseTable(bool close = false);
private:
};
#endif | true |
a40c0eca4d59708a20d62059badf0e0224f1ad0f | C++ | mirucar/airlinesres | /3_led_siren.ino | UTF-8 | 401 | 2.609375 | 3 | [] | no_license | const int LEDdizisi[] = {5, 6, 7};
void setup() {
for(int i=0; i<3; i++) {
pinMode(LEDdizisi[i], OUTPUT);
}
}
void loop() {
for(int i=0; i<3; i++) {
digitalWrite(LEDdizisi[i], HIGH);
delay(70);
digitalWrite(LEDdizisi[i], LOW);
}
for(int j=2; j>-1; j--) {
digitalWrite(LEDdizisi[j], HIGH);
delay(70);
digitalWrite(LEDdizisi[j], LOW);
}
}
| true |
e986631204e73eb399615da27b1d83635022ffaa | C++ | nilune/2019-Study-Institute | /ParallelProgram/base/hello_pth.cpp | UTF-8 | 1,192 | 3.171875 | 3 | [] | no_license | #include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
int size;
typedef struct {
int rank;
} thread_args;
void *thread_func(void *arg) {
pthread_t this_thread;
this_thread = pthread_self();
auto *point = (thread_args*) arg;
printf("Thread = %lu; size = %d; rank = %d\n", this_thread, size, point->rank);
return nullptr;
}
int main(int argc, char *argv[]) {
int err;
if (argc != 2) {
size = 4;
} else {
size = atoi(argv[1]);
}
pthread_t threads[size];
thread_args threads_args[size];
for (int i = 0; i < size; i++) {
threads_args[i].rank = i;
err = pthread_create(
&threads[i],
(pthread_attr_t *) nullptr,
thread_func,
&threads_args[i]
);
if (err != 0) {
printf("Error on thread create, return value = %d\n", err);
exit(-1);
}
}
pthread_t this_thread;
this_thread = pthread_self();
printf("Thread = %lu; size = %d; rank = main\n", this_thread, size);
for (int i = 0; i < size; i++) {
pthread_join(threads[i], (void **) nullptr);
}
return 0;
} | true |
4730f1235ffc77ce611f974becc31f2f54f09211 | C++ | Meridor6919/OLC-game-jam-2019 | /OLC game jam 2019/Bullet.h | UTF-8 | 3,049 | 2.90625 | 3 | [] | no_license | #pragma once
#include "Object.h"
class Bullet :
public Object
{
float life_time = 2.0f;
float fading_time = 1.0f;
DirectX::XMVECTORF32 color = { 0.0f,0.0f,0.0f,1.0f };
DirectX::SimpleMath::Vector2 orientation_point;
DirectX::SimpleMath::Vector2 direction;
DirectX::SimpleMath::Vector4 hitbox;
public:
Bullet(DirectX::SimpleMath::Vector2 orientation_point, DirectX::SimpleMath::Vector2 direction) : Object(orientation_point)
{
this->orientation_point = orientation_point;
this->direction = direction;
}
virtual bool Draw(DirectX::PrimitiveBatch<DirectX::VertexPositionColor> *primitive_batch, DirectX::XMVECTORF32 background_color, float delta_time)
{
const float size = 20.0f;
DirectX::SimpleMath::Vector3 v1(orientation_point.x, orientation_point.y, 1.0f);
DirectX::SimpleMath::Vector3 v2(orientation_point.x-size*direction.x, orientation_point.y + size*direction.y, 0.0f);
DirectX::VertexPositionColor vc1(v1, color);
DirectX::VertexPositionColor vc2(v2, { 0.f, 0.f, 0.f, 0.f });
primitive_batch->DrawLine(vc1, vc2);
if (fading)
{
fading_time -= delta_time;
if (fading_time < 0)
{
return false;
}
else
{
DirectX::SimpleMath::Vector4 v_2(color);
v_2.w -= delta_time / fading_time;
color = { v_2.x, v_2.y, v_2.z, v_2.w };
}
}
else
{
life_time -= delta_time;
if (life_time < 0)
{
fading = true;
}
}
return true;
}
void Update(float delta_time)
{
float modifier = sqrt(1 / (direction.x*direction.x + direction.y * direction.y));
orientation_point.x += direction.x*modifier*300.0f*delta_time;
orientation_point.y -= direction.y*modifier*delta_time*300.0f;
}
virtual bool Collision(DirectX::SimpleMath::Vector4 object)
{
DirectX::SimpleMath::Vector2 vertexes[4] = { {object.x, object.y},
{object.x, object.w},
{object.z, object.y},
{object.z, object.w},
};
for (int i = 0; i < 4; ++i)
{
bool b1 = ((vertexes[(i + 1) % 4].y - vertexes[i].y) * (orientation_point.x - vertexes[(i + 1) % 4].x) - (vertexes[(i + 1) % 4].x - vertexes[i].x) * (orientation_point.y - vertexes[(i + 1) % 4].y)) > 0;
bool b2 = ((vertexes[(i + 1) % 4].y - vertexes[i].y) * ((orientation_point.x - (100.0f*direction.x)) - vertexes[(i + 1) % 4].x) - (vertexes[(i + 1) % 4].x - vertexes[i].x) * ((orientation_point.y - (100.0f*direction.y)) - vertexes[(i + 1) % 4].y)) > 0;
bool b3 = (((orientation_point.y - (100.0f*direction.y)) - orientation_point.y) * (vertexes[i].x - (orientation_point.x - (100.0f*direction.x))) - ((orientation_point.x - (100.0f*direction.x)) - orientation_point.x) * (vertexes[i].y - (orientation_point.y - (100.0f*direction.y)))) > 0;
bool b4 = (((orientation_point.y - (100.0f*direction.y)) - orientation_point.y) * (vertexes[(i + 1) % 4].x - (orientation_point.x - (100.0f*direction.x))) - ((orientation_point.x - (100.0f*direction.x)) - orientation_point.x) * (vertexes[(i + 1) % 4].y - (orientation_point.y - (100.0f*direction.y)))) > 0;
if (b1 != b2 && b3 != b4)
return true;
}
return false;
}
};
| true |
9c8c40c30d8f3c7632a74732ea51d78f4cb57a98 | C++ | UncreativeIdea/Learning | /Create/Source.cpp | UTF-8 | 373 | 3.859375 | 4 | [] | no_license | #include <iostream>
int main()
{
std::cout << "Enter an interger: ";
int num{ 0 };
std::cin >> num;
std::cout << "Double that number is: " << num * 2 << '\n';
std::cout << "Triple that number is: " << num * 3 << '\n';
std::cout << "Plus one of that number is: " << num + 1 << '\n';
std::cout << "Minus one of that number is: " << num - 1 << '\n';
return 0;
} | true |