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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
8b56566a3de40613d63c19f4c67f338c7549e3d0 | C++ | makarenya/light_frame | /src/print.cpp | UTF-8 | 3,849 | 3.25 | 3 | [] | no_license | //
// Created by Alexey Makarenya on 2019-06-04.
//
#include <cstdlib>
#include <cmath>
#include "print.h"
size_t TPrint::print(const char* message, size_t length)
{
return write(reinterpret_cast<const uint8_t*>(message), length);
}
size_t TPrint::println(const char* message, size_t length)
{
size_t n = print(message, length);
n += println();
return n;
}
size_t TPrint::print(char c)
{
return write(c);
}
size_t TPrint::print(unsigned char b, int base)
{
return print((unsigned long) b, base);
}
size_t TPrint::print(int n, int base)
{
return print((long) n, base);
}
size_t TPrint::print(unsigned int n, int base)
{
return print((unsigned long) n, base);
}
size_t TPrint::print(long n, int base)
{
if (base == 0) {
return write(n);
} else if (base == 10) {
if (n < 0) {
int t = print('-');
n = -n;
return printNumber(n, 10) + t;
}
return printNumber(n, 10);
} else {
return printNumber(n, base);
}
}
size_t TPrint::print(unsigned long n, int base)
{
if (base == 0) {
return write(n);
} else {
return printNumber(n, base);
}
}
size_t TPrint::print(double n, int digits)
{
return printFloat(n, digits);
}
size_t TPrint::println() {
char lf = '\n';
return print(&lf, 1);
}
size_t TPrint::println(char c)
{
size_t n = print(c);
n += println();
return n;
}
size_t TPrint::println(unsigned char b, int base)
{
size_t n = print(b, base);
n += println();
return n;
}
size_t TPrint::println(int num, int base)
{
size_t n = print(num, base);
n += println();
return n;
}
size_t TPrint::println(unsigned int num, int base)
{
size_t n = print(num, base);
n += println();
return n;
}
size_t TPrint::println(long num, int base)
{
size_t n = print(num, base);
n += println();
return n;
}
size_t TPrint::println(unsigned long num, int base)
{
size_t n = print(num, base);
n += println();
return n;
}
size_t TPrint::println(double num, int digits)
{
size_t n = print(num, digits);
n += println();
return n;
}
size_t TPrint::printNumber(unsigned long n, uint8_t base)
{
char buf[8*sizeof(long)+1]; // Assumes 8-bit chars plus zero byte.
char* str = &buf[sizeof(buf)-1];
// prevent crash if called with base == 1
if (base<2) {
base = 10;
}
do {
unsigned long m = n;
n /= base;
char c = m-base*n;
(*str--) = c<10 ? c+'0' : c+'A'-10;
} while (n);
return print(str, str-&buf[sizeof(buf)-1]);
}
size_t TPrint::printFloat(double number, uint8_t digits)
{
size_t n = 0;
if (std::isnan(number)) {
return print("nan");
}
if (std::isinf(number)) {
return print("inf");
}
if (number>4294967040.0) {
return print("ovf"); // constant determined empirically
}
if (number<-4294967040.0) {
return print("ovf"); // constant determined empirically
}
// Handle negative numbers
if (number<0.0) {
n += print('-');
number = -number;
}
// Round correctly so that print(1.999, 2) prints as "2.00"
double rounding = 0.5;
for (uint8_t i = 0; i<digits; ++i) {
rounding /= 10.0;
}
number += rounding;
// Extract the integer part of the number and print it
auto int_part = (unsigned long) number;
double remainder = number-(double) int_part;
n += print(int_part);
// Print the decimal point, but only if there are digits beyond
if (digits>0) {
n += print(".");
}
// Extract digits from the remainder one at a time
while (digits-->0) {
remainder *= 10.0;
int toPrint = int(remainder);
n += print(toPrint);
remainder -= toPrint;
}
return n;
}
| true |
8eb1752e3dcb7b19e8527aa89df22d8defedbab5 | C++ | Boomgrape/L298N | /L298N.cpp | UTF-8 | 1,384 | 2.875 | 3 | [] | no_license | #include "L298N.h"
#ifndef LOW_PWM
#define LOW_PWM 0
L298N::L298N(){/*init constructor*/};
L298N::L298N(uint8_t ena,uint8_t n1,uint8_t n2,uint8_t n3,uint8_t n4,uint8_t enb){
this->ENA = ena;
this->ENB = enb;
this->N1 = n1;
this->N2 = n2;
this->N3 = n3;
this->N4 = n4;
}
void L298N::initmotor(){
pinMode(ENA,OUTPUT);
pinMode(ENB,OUTPUT);
pinMode(N1,OUTPUT);
pinMode(N2,OUTPUT);
pinMode(N3,OUTPUT);
pinMode(N4,OUTPUT);
}
void L298N::motorLeftForwardClock(uint8_t PWM){
analogWrite(ENA,PWM);
digitalWrite(N1,HIGH);
digitalWrite(N2,LOW);
}
void L298N::motorRightForwardClock(uint8_t PWM){
analogWrite(ENB,PWM);
digitalWrite(N3,HIGH);
digitalWrite(N4,LOW);
}
void L298N::motorLeftRevertClock(uint8_t PWM){
analogWrite(ENA,PWM);
digitalWrite(N1,LOW);
digitalWrite(N2,HIGH);
}
void L298N::motorRightRevertClock(uint8_t PWM){
analogWrite(ENB,PWM);
digitalWrite(N3,LOW);
digitalWrite(N4,HIGH);
}
void L298N::motorLeftbreak(uint8_t PWM){
analogWrite(ENA,PWM);
digitalWrite(N1,HIGH);
digitalWrite(N2,HIGH);
}
void L298N::motorRightbreak(uint8_t PWM){
analogWrite(ENB,PWM);
digitalWrite(N3,HIGH);
digitalWrite(N4,HIGH);
}
void L298N::motorLeftstop(){
analogWrite(ENA,LOW_PWM);
digitalWrite(N1,LOW);
digitalWrite(N2,LOW);
}
void L298N::motorRightstop(){
analogWrite(ENB,LOW_PWM);
digitalWrite(N3,LOW);
digitalWrite(N4,LOW);
}
#endif
| true |
d39ce1513b6ba3d7261b0034d1139b1944faf3c5 | C++ | diyajaiswal11/Competitive-Programming | /Leetcode/70.cpp | UTF-8 | 377 | 2.796875 | 3 | [] | no_license | //https://leetcode.com/problems/climbing-stairs/
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int climbStairs(int n) {
vector<int> a;
for(int i=0;i<=3;i++)
{
a.push_back(i);
}
for(int i=4;i<=n;i++)
{
a.push_back(a[i-1]+a[i-2]);
}
return a[n];
}
}; | true |
febca110b83f2acd98f74507b5fc5b84cf10e60a | C++ | CUASAS/pixel-gantry-control | /Gantry/External/Camera/test_camera.cpp | UTF-8 | 1,557 | 2.875 | 3 | [] | no_license | //
// Created by Caleb on 11/10/2022.
//
#include <iostream>
#include "interface.h"
#include "opencv2/opencv.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
void list_modes(int camera_id) {
int ret = InitDevice(camera_id, 0);
if (FAILED(ret)) return;
std::map<int, MediaMode> modes;
GetAvailableModes(camera_id, modes);
LStrHandle lsh;
GetCaptureDeviceName(camera_id, lsh);
std::cout << *lsh << std::endl;
for (auto [key, val]: modes) {
std::cout << key << ") " << val.width << "x" << val.height << " @ " << val.framerate << "fps\n";
}
CleanupDevice(camera_id);
}
void capture_image(int camera_id, int mode_id) {
int ret = InitDevice(camera_id, mode_id);
if (FAILED(ret)) return;
cv::namedWindow("MyWindow", cv::WINDOW_AUTOSIZE);
while (true) {
DoCapture(camera_id);
while (!IsCaptureDone(camera_id));
int *buffer;
int width, height;
ret = GetFrame(camera_id, &buffer, &width, &height);
cv::Mat img(height, width, CV_8UC4, (void *) buffer, width * sizeof(int));
cv::Mat gs;
cv::cvtColor(img, gs, cv::COLOR_BGR2GRAY);
cv::imshow("MyWindow", gs);
if (cv::waitKey(5)>0) {
break;
}
}
cv::destroyWindow("MyWindow");
}
int main(int argc, const char *argv[]) {
std::cout << "Hello World!\n";
int count;
CountCaptureDevices(&count);
std::cout << "count=" << count << std::endl;
list_modes(0);
capture_image(0, 0);
return 0;
}
| true |
fcbfb1333aeb50f86743154f467974f652432a0e | C++ | phamhoai0404/Code_Dau | /lap_trinh_huong_doi_tuong/kiem_tra_lan_2/pham_thi_hoai_058_bai_2.cpp | UTF-8 | 3,180 | 2.8125 | 3 | [] | no_license | #include<iostream>
#include<stdio.h>
#include<string.h>
#include<iomanip>
#include<windows.h>
using namespace std;
class PHIEU;
class date
{
private:
int d;
int m;
int y;
public:
void nhap();
void xuat();
friend class PHIEU;
};
class PERSON
{
private:
char tennv[20];
char chucvu[30];
public:
void nhap();
friend class PHIEU;
};
class PHONG
{
private:
char maphong[20];
char tenphong[20];
char truongphong[20];
public:
void nhap();
friend class PHIEU;
};
class TAISAN
{
private:
char ten[20];
int soluong;
char tinhtrang[20];
public:
void nhap();
void xuat();
friend class PHIEU;
};
class PHIEU
{
public:
char maphieu[20];
date ngaykiemke;
PERSON nhanvienkiemke;
PHONG taiphong;
TAISAN x[30];
int xn;
public:
void nhap();
void xuat();
int tong_so_luong()
{
int k=0;
for( int i=0;i<xn;i++)
k+=x[i].soluong;
return k;
}
};
void date::nhap()
{
cout<<"\tngay nhap: ";cin>>d;
cout<<"\tthang nhap : ";cin>>m;
cout<<"\tnam nhap: ";cin>>y;
}
void date:: xuat()
{
cout<<setw(8)<<d<<"/"<<m<<"/"<<y;
}
void PERSON::nhap()
{
cout<<"ten nhan vien kiem ke: ";fflush(stdin);gets(tennv);
cout<<"chuc vu: ";fflush(stdin);gets(chucvu);
}
void PHONG::nhap()
{
cout<<"kiem ke tai phong: ";fflush(stdin);gets(tenphong);
cout<<"ma phong: ";fflush(stdin);gets(maphong);
cout<<"truong phong: ";fflush(stdin);gets(truongphong);
}
void TAISAN:: nhap()
{
cout<<"\n\t+ ten tai san : ";fflush(stdin);gets(ten);
cout<<"\t+ so luong: ";cin>>soluong;
cout<<"\t+ tinh trang: ";fflush(stdin);gets(tinhtrang);
}
void TAISAN :: xuat()
{
cout<<setw(15)<<ten;
cout<<setw(20)<<soluong;
cout<<setw(20)<<tinhtrang<<endl<<endl;
}
void cot_mau()
{
cout<<setw(20)<<"ten tai san";
cout<<setw(20)<<"so luong";
cout<<setw(20)<<" tinh trang"<<endl<<endl;
}
void PHIEU::nhap()
{
cout<<"\nma phieu: ";fflush(stdin);gets(maphieu);
cout<<"ngay kiem ke: \n";ngaykiemke.nhap();
nhanvienkiemke.nhap();
taiphong.nhap();
cout<<"\n so luong tai san: ";cin>>xn;
for( int i=0;i<xn;i++)
{
cout<<"\n =====tai san thu: "<<i+1;
x[i].nhap();
}
}
void PHIEU::xuat()
{
cout<<"\n\n\t\t=========PHIEU KIEM KE TAI SAN==========="<<endl<<endl;
cout<<"\tMa phieu: "<<maphieu<<setw(20)<<"Ngay kiem ke:"<<right;ngaykiemke.xuat();
cout<<"\n\tNhan vien kiem ke: "<<nhanvienkiemke.tennv<<setw(20)<<"Chuc vu:"<<nhanvienkiemke.chucvu;
cout<<"\n\tKiem ke tai phong: "<<taiphong.tenphong<<setw(20)<<"Ma phong: "<<taiphong.maphong;
cout<<"\n\tTruong phong: "<<taiphong.truongphong<<endl<<endl;
cot_mau();
for( int i=0;i<xn;i++)
x[i].xuat();
cout<<"\n\n\t So tai khoan kiem ke: "<<xn;
cout<<"\t\t Tong so luong: "<<tong_so_luong()<<endl;
}
int main()
{
PHIEU x;
x.nhap();
system("cls");
x.xuat();
return 0;
}
| true |
aacdf46cce94c66154bca3872d68f8830d9817c1 | C++ | Zbyl/ArbitraryFormatSerializer | /arbitrary_format/utility/bit_packer.h | UTF-8 | 8,090 | 3.40625 | 3 | [
"Apache-2.0",
"BSL-1.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /////////////////////////////////////////////////////////////////////////////
/// ArbitraryFormatSerializer
/// Library for serializing data in arbitrary formats.
///
/// bit_packer.h
///
/// This file contains bit_packer that packs and unpacks values or tuples of values in bitfields.
///
/// Distributed under Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
/// (c) 2014 Zbigniew Skowron, zbychs@gmail.com
///
/////////////////////////////////////////////////////////////////////////////
#ifndef ArbitraryFormatSerializer_bit_packer_H
#define ArbitraryFormatSerializer_bit_packer_H
#include <arbitrary_format/utility/integer_of_size.h>
#include <arbitrary_format/utility/metaprogramming.h>
#include <type_traits>
#include <tuple>
namespace arbitrary_format
{
namespace binary
{
template<int... BitsSeq>
class bit_packer
{
static constexpr int bits_size = isec::sum_args<int, BitsSeq...>::value;
static_assert( (bits_size == 8) || (bits_size == 16) || (bits_size == 32) || (bits_size == 64), "Sum of bits must be a full 1, 2, 4 or 8 bytes.");
static constexpr int byte_size = bits_size / 8;
/// @brief Negates the value. It is needed, since ~(unsigned char) == (int), and we want it to be (unsigned char).
template<typename T>
static constexpr T neg(T value)
{
return static_cast<T>(~value);
}
/// @brief Shifts the value left. It is needed, since (unsigned char) << Bits == (int), and we want it to be (unsigned char).
template<int Bits, typename T>
static constexpr T shl(T value)
{
return static_cast<T>(value << Bits);
}
/// @brief Returns value with Bits least significant bits set.
template<typename T, int Bits>
static constexpr T lsbMask()
{
static_assert(std::is_unsigned<T>::value, "Type must be unsigned.");
return neg( shl<Bits>(neg(T())) );
}
public:
using packed_type = typename uint_of_size<byte_size>::type;
private:
template<typename T>
static T fsum()
{
return T();
}
template<typename T, typename... Ts>
static T fsum(T val, Ts... vals)
{
return val + fsum<T>(vals...);
}
/// Cuts specified number of bits from given position in a value, and casts them to given type. Ignores other bits.
/// Example:
/// bitsToVal<int, 4, 1>(00010011) will cast bits 1..4 (1001) to int, which will be -7.
/// bitsToVal<unsigned, 4, 1>(00010011) will cast bits 1..4 (1001) to unsigned int, which will be 9.
template<int Bits, int Shift, typename T>
static T bitsToVal(packed_type val, T dummy)
{
static_assert(Bits > 0, "Number of bits for each component must be greater than 0");
constexpr packed_type mask = lsbMask<packed_type, Bits>();
constexpr packed_type sign_mask = packed_type(1) << (Bits - 1);
packed_type result = (val >> Shift) & mask;
if ( std::is_signed<T>::value && (result & sign_mask) )
{
result |= neg(mask);
}
using resizedT = typename integer_of_size< std::is_signed<T>::value, byte_size>::type;
auto properlySignedResult = static_cast<resizedT>(result);
T finalVal = static_cast<T>(properlySignedResult);
return finalVal;
}
/// Overload of bitsToVal for bools
template<int Bits, int Shift>
static bool bitsToVal(packed_type val, bool dummy)
{
static_assert(Bits > 0, "Number of bits for each component must be greater than 0");
constexpr packed_type mask = lsbMask<packed_type, Bits>();
packed_type result = (val >> Shift) & mask;
if (result == 0)
return false;
if (result == 1)
return true;
BOOST_THROW_EXCEPTION(invalid_data());
}
/// Represents given value on given number of bits. Sets remaining bits of result to 0.
/// Example (assumes packed_type == uint16_t):
/// valToBits<int8_t, 4>(11111111) will represent -1 on 4 bits, which will be (00000000 00001111).
/// valToBits<int8_t, 9>(11111111) will represent -1 on 9 bits, which will be (00000001 11111111).
/// valToBits<uint8_t, 9>(11111111) will represent 256 on 9 bits, which will be (00000000 11111111).
template<int Bits, typename T>
static packed_type valToBits(T val)
{
static_assert(Bits > 0, "Number of bits for each component must be greater than 0");
constexpr packed_type mask = lsbMask<packed_type, Bits>();
using resizedT = typename integer_of_size< std::is_signed<T>::value, byte_size>::type;
resizedT resized_value = static_cast<resizedT>(val);
packed_type finalVal = static_cast<packed_type>(resized_value) & mask;
// throw if conversion was lossy
T reconstructedVal = bitsToVal<Bits, 0>(finalVal, T());
if (reconstructedVal != val)
{
BOOST_THROW_EXCEPTION((lossy_conversion() << typename cant_store_type_in_this_number_of_bytes<byte_size, T>::errinfo(val)));
}
return finalVal;
}
/// Overload of valToBits for bools
template<int Bits>
static packed_type valToBits(bool val)
{
static_assert(Bits > 0, "Number of bits for each component must be greater than 0");
return val ? 1 : 0;
}
template<int... Shifts, typename... Ts>
static packed_type pack(std::integer_sequence<int, Shifts...>, const Ts&... vals)
{
return fsum( (valToBits<BitsSeq>(vals) << Shifts ) ... );
}
template<typename... Ts, int... Shifts>
static void unpack(std::integer_sequence<int, Shifts...>, packed_type packed, Ts&... vals)
{
auto vars = std::tie(vals...);
auto values = std::make_tuple(bitsToVal<BitsSeq, Shifts>(packed, Ts())...);
vars = values;
}
template<typename... Ts, std::size_t... Ints>
static packed_type tuple_pack_impl(const std::tuple<Ts...>& vals, std::index_sequence<Ints...> Is)
{
packed_type val = pack(std::get<Ints>(vals)...);
return val;
}
/// Unpacks into a tuple of references.
template<typename... Ts, std::size_t... Ints>
static void tuple_unpack_impl(packed_type val, const std::tuple<Ts&...>& vals, std::index_sequence<Ints...> Is)
{
unpack(val, std::get<Ints>(vals)...);
}
/// Unpacks into a reference to a tuple of values.
template<typename... Ts, std::size_t... Ints>
static void tuple_unpack_impl(packed_type val, std::tuple<Ts...>& vals, std::index_sequence<Ints...> Is)
{
unpack(val, std::get<Ints>(vals)...);
}
public:
template<typename... Ts>
static packed_type pack(Ts... vals)
{
using bits_seq = std::integer_sequence<int, BitsSeq...>;
using shifts_seq = isec::push_front<int, isec::pop_back< isec::partial_sum<bits_seq> >, 0>;
//TypeDisplayer<isec::push_front<int, isec::pop_back< isec::partial_sum<bits_seq> >, 0>> td;
packed_type val = pack(shifts_seq(), vals...);
return val;
}
template<typename... Ts>
static void unpack(packed_type val, Ts&... vals)
{
using bits_seq = std::integer_sequence<int, BitsSeq...>;
using shifts_seq = isec::push_front<int, isec::pop_back< isec::partial_sum<bits_seq> >, 0>;
unpack(shifts_seq(), val, vals...);
}
template<typename... Ts>
static packed_type pack(const std::tuple<Ts...>& vals)
{
packed_type val = tuple_pack_impl(vals, std::index_sequence_for<Ts...>());
return val;
}
/// Unpacks into a tuple of references.
template<typename... Ts>
static void unpack(packed_type val, const std::tuple<Ts&...>& vals)
{
tuple_unpack_impl(val, vals, std::index_sequence_for<Ts...>());
}
/// Unpacks into a reference to a tuple of values.
template<typename... Ts>
static void unpack(packed_type val, std::tuple<Ts...>& vals)
{
tuple_unpack_impl(val, vals, std::index_sequence_for<Ts...>());
}
};
} // namespace binary
} // namespace arbitrary_format
#endif // ArbitraryFormatSerializer_bit_packer_H
| true |
a4b3db10a2e068b30ac6fc8e6170a2a7c41bb527 | C++ | mehrdadzakershahrak/Online-Explanation-Generation | /rovers/fastdownward/src/search/utils/timer.h | UTF-8 | 562 | 2.59375 | 3 | [
"MIT",
"GPL-1.0-or-later",
"GPL-3.0-or-later"
] | permissive | #ifndef UTILS_TIMER_H
#define UTILS_TIMER_H
#include "system.h"
#include <ostream>
namespace utils {
class Timer {
double last_start_clock;
double collected_time;
bool stopped;
#if OPERATING_SYSTEM == WINDOWS
LARGE_INTEGER frequency;
LARGE_INTEGER start_ticks;
#endif
double current_clock() const;
public:
Timer();
~Timer() = default;
double operator()() const;
double stop();
void resume();
double reset();
};
std::ostream &operator<<(std::ostream &os, const Timer &timer);
extern Timer g_timer;
}
#endif
| true |
c188f4e3753f0a18ae5eb52113e9ed1ffacf7c0e | C++ | fadymoh/Online-Judges-Problems-Solutions | /Uva/10534 - Wavio Sequence.cpp | UTF-8 | 842 | 2.59375 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
using namespace std;
int l[10001];
int a[10001];
int lis_arr[10001];
int lds_arr[10001];
int n;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
while (cin >> n, !cin.eof())
{
for (int i = 0; i < n; ++i)
cin >> a[i];
int lis = 0, lds = 0;
for (int i = 0; i < n; ++i)
{
int x = a[i];
int ind = lower_bound(l, l + lis, x) - l;
l[ind] = x;
if (ind + 1 >= lis)
lis = ind + 1;
lis_arr[i] = ind + 1;
}
for (int i = n - 1; i >= 0; --i)
{
int x = a[i];
int ind = lower_bound(l, l + lds, x) - l;
l[ind] = x;
if (ind + 1 >= lds)
lds = ind + 1;
lds_arr[i] = ind + 1;
}
int ans = 1;
for (int i = 0; i < n; ++i)
{
ans = max(ans, 2 * min(lis_arr[i], lds_arr[i]) - 1);
}
cout << ans << endl;
}
system("pause");
return 0;
} | true |
610394e6d172102a2024c3b49619250423f072f5 | C++ | fjols/RandomPointsSFML | /graph/graph/Graph.cpp | UTF-8 | 913 | 3.375 | 3 | [] | no_license | #include "Graph.h"
Graph::Graph()
{
m_points.setPrimitiveType(sf::Points); //Set primitive type
m_points.resize(m_iNumOfPoints); //Set the number of points
}
void Graph::SetPoints()
{
for (int i = 0; i < m_points.getVertexCount(); i++) {
m_points[i].position = sf::Vector2f(RandomNumber(), RandomNumber()); //Set the X and Y coordinates to the random numbers generated from RandomNumber().
m_points[i].color = sf::Color::Yellow; //Set a color.
std::cout << "Position X: " << m_points[i].position.x << std::endl << "Position Y: " << m_points[i].position.y << std::endl;
}
}
int Graph::RandomNumber()
{
return(rand() % 1000 + 1); //Return a random number from 1 to 1000.
}
void Graph::draw(sf::RenderTarget & target, sf::RenderStates states) const
{
states.texture = NULL; //Sets no texture.
target.draw(m_points, states); //Draws the points onto the window.
}
| true |
9ad1f4e78bade61bcb067c2ba57cb3187a986c83 | C++ | Videk/Kurs_Cpp | /Kurs_Cpp_13_1/main.cpp | UTF-8 | 780 | 3.46875 | 3 | [] | no_license | #include <iostream>
#include <time.h>
using namespace std;
int a, b = 1;
int wynik = 0;
clock_t start, stop;
double czas;
long int fib_iter(int n)
{
for(int i = 2; i <= n; i++)
{
wynik = a+b;
a = b;
b = wynik;
}
return wynik;
}
long int fib_rek(int n)
{
if(n == 1 || n == 2) return 1;
else return fib_rek(n-1) + fib_rek(n-2);
}
int main()
{
start = clock();
cout << fib_iter(60) << endl;
stop = clock();
czas = (stop-start)/CLOCKS_PER_SEC;
cout << "Czas wykonania funkcji iteracyjnej: " << czas << endl;
start = clock();
cout << fib_rek(60) << endl;
stop = clock();
czas = (stop-start)/CLOCKS_PER_SEC;
cout << "Czas wykonania funkcji rekutencyjnej: " << czas << endl;
return 0;
}
| true |
d136b1e16bd9708a908abd8ba6435a204576bf4d | C++ | LonellyAlly/Exercises | /(1006)Media-escolar.cpp | UTF-8 | 240 | 2.859375 | 3 | [] | no_license | #include<iostream>
#include<iomanip>
using namespace std;
int main(){
double A, B, C;
double Media;
cin >> A;
cin >> B;
cin >> C;
Media = (A*2.0 + B*3.0 + C*5)/10;
cout << "MEDIA = " << fixed << setprecision(1) << Media << "\n";
}
| true |
10669c92b56de93176d160fbbfc7ab4cb21d391f | C++ | kujaw/stroustrup_cpp | /chapter_03/03ex02_mil_to_km.cpp | UTF-8 | 350 | 3.6875 | 4 | [] | no_license | // converts miles to kilometers
#include <iostream>
using namespace std;
int main()
{
float miles;
float kilometers;
cout << "Enter the number of miles you want to be converted to kilometers: \n";
cin >> miles;
kilometers = miles * 1.609;
cout << miles << " miles = " << kilometers << " kilometers.\n";
return 0;
}
| true |
e9fa3a08cbbda6820381c0768deadaff9b1b9b22 | C++ | virginiasatyro/c-plus-plus | /udemy/intermediario/parte-3/main.cpp | UTF-8 | 1,167 | 3.734375 | 4 | [] | no_license | #include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
char* array = new char[100];
// NEW - gravando um bloco de memória - 100 caracteres na pilha.
// NEW retorna um ponteiro para um array recém criado.
// int argc - nnúmero de argumentos passados na linha de comando
// char *argv[] - argumentos - array de ponteiro para strings.
// primeiro argumento - é sempre o nome do próprio programa
// exemplo: 'não passando' nenhum argumento na linha de comando
cout << "argc: " << argc << endl; // 1
cout << "argv[0]: " << argv[0] << endl; // ./main
int n1 = 10, n2 = 20, n3 = 30;
int* parray[3] = {&n1, &n2, &n3}; // array de 3 ponteiros para inteiros
cout << *parray[0] << endl; // 10
cout << *parray[1] << endl; // 20
cout << *parray[2] << endl; // 30
// --------------------------------------------------
cout << "Quantidade de argumentos: " << argc << endl;
cout << "Argumentos passados: " << endl;
for(int i = 0; i < argc; i++)
cout << argv[i] << endl;
return 0;
}
/*
$ ./main python
execução do programa:
2 argumentos
./main e python
*/
| true |
6609ad2437ead88cbb09949b2822de9054a38394 | C++ | pratik30pp/DataStructuresVisualizer | /src/LinkedList.h | UTF-8 | 568 | 3 | 3 | [] | no_license | #pragma once
//-----------------------------------------------------------------------------
class Node;
class LinkedList
{
private:
Node** m_head;
int m_length;
public:
LinkedList() { m_head = nullptr; m_length = 0; }
~LinkedList() { delete m_head; m_head = nullptr; }
int GetLength() { return m_length; }
void Push(double data);
void Append(double data);
void InsertAfter(Node* prevNoderef, double data);
void DeleteNode(double key);
void Reverse();
void DeleteList();
};
//----------------------------------------------------------------------------- | true |
9008b3eb6cbb261828c43659b3a3137e5fe61c48 | C++ | thelvyn/CompileScore | /DataExtractor/src/Common/Context.h | UTF-8 | 611 | 3.21875 | 3 | [
"MIT"
] | permissive | #pragma once
namespace Context
{
//simplified context by type storage ( we don't need anything fancier for this application )
namespace Impl
{
template<typename T> struct Storage { static inline T* instance = nullptr; };
}
template<typename T> T* Get(){ return Impl::Storage<T>::instance; }
template<typename T>
class Scoped
{
public:
template<typename ... Args> Scoped(Args... args):value(args...){ Impl::Storage<T>::instance = &value; }
~Scoped(){ Impl::Storage<T>::instance = nullptr; }
T& Get() { return value; }
const T& Get() const { return value; }
private:
T value;
};
} | true |
b1105efc587955d208d007a86dc630df100d1186 | C++ | iorehovski/Game-snake | /project.h | UTF-8 | 4,396 | 2.671875 | 3 | [] | no_license | #include <SDL.h>
#include <SDL_ttf.h>
#include <SDL_image.h>
#include <iostream>
#include <vector>
#include <ctime>
#include <string>
#include <fstream>
using namespace std;
const int SCR_WIDTH = 630;
const int SCR_HEIGHT = 480;
const SDL_Color cWhite = { 255,255,255 };
const SDL_Color cYellow = { 255,255,0 };
struct Texture {
SDL_Texture* texture = nullptr;
SDL_Rect rect;
int x,y,w,h;
void loadImage(SDL_Renderer* render,char* directory);
void setPosition(int xx, int yy, int ww, int hh);
void setRandPosition();
void setRandPositionBigApple();
void copyImageInRender(SDL_Renderer* render);
};
void Texture::setPosition(int xx, int yy, int ww, int hh) {
x = xx;
y = yy;
w = ww;
h = hh;
rect = { x,y,w,h };
}
void Texture::setRandPosition() {
int a = 0, b = 0;
a = (rand() % 35 + 5) * 15;
b = (rand() % 25 + 5) * 15;
while (sqrt((a - x)^2 - (b-y)^2) < 15){
a = (rand() % 40) * 15;
b = (rand() % 25 + 4) * 15;
}
rect.x = x =a;
rect.y = y =b;
rect.h = h =15;
rect.w = w =15;
}
void Texture::setRandPositionBigApple() {
int a = 0, b = 0;
a = (rand() % 35 + 5) * 15;
b = (rand() % 25 + 5) * 15;
while (sqrt((a - x) ^ 2 - (b - y) ^ 2) < 20) {
a = (rand() % 40) * 15;
b = (rand() % 25 + 4) * 15;
}
rect.x = x = a;
rect.y = y = b;
rect.h = h = 30;
rect.w = w = 30;
}
void Texture::loadImage(SDL_Renderer* render, char* directory) {
texture = IMG_LoadTexture(render, directory);
}
void Texture::copyImageInRender(SDL_Renderer* render) {
SDL_RenderCopy(render, texture, NULL, &rect);
}
struct Text {
TTF_Font* font = TTF_OpenFont("BEBAS.ttf", 20);
SDL_Texture* textTexture = nullptr;
SDL_Rect textRect;
int x, y, w, h;
void setTextPosition(int xx, int yy, int ww, int hh);
void setTextTexture(SDL_Renderer* render, string text, SDL_Color color);
void copyTextInRender(SDL_Renderer* render);
};
void Text::setTextTexture(SDL_Renderer* render,string text, SDL_Color color) {
textTexture = SDL_CreateTextureFromSurface(render, TTF_RenderText_Solid(font, text.c_str(), color));
}
void Text::setTextPosition(int xx, int yy, int ww, int hh) {
x = xx;
y = yy;
w = ww;
h = hh;
textRect = { x,y,w,h };
}
void Text::copyTextInRender(SDL_Renderer* render) {
SDL_RenderCopy(render, textTexture, NULL, &textRect);
}
SDL_Window* CreateWindow(const char* title, SDL_Window* window,bool* run) {
window = SDL_CreateWindow(title, 380, 100, SCR_WIDTH, SCR_HEIGHT, SDL_WINDOW_SHOWN);
if (window == NULL) {
cout << SDL_GetError() << endl;
run = false;
}
return window;
}
void checkBeyond(SDL_Rect& rect) {
if (rect.x == -15) {
rect.x = 615;
}
else if (rect.x == 630) {
rect.x = -15;
}
if (rect.y == 480) {
rect.y = 45;
}
else if (rect.y == 30) {
rect.y = 465;
}
}
void event(SDL_Event occur, bool& run, int& actDir) {
if (SDL_PollEvent(&occur)) {
switch (occur.type) {
case SDL_QUIT:
run = false;
break;
case SDL_KEYDOWN:
switch (occur.key.keysym.sym) {
case SDLK_ESCAPE:
run = false;
break;
case SDLK_UP:
if (actDir != 2) {
actDir = 0;
}
break;
case SDLK_LEFT:
if (actDir != 3) {
actDir = 1;
}
break;
case SDLK_DOWN:
if (actDir != 0) {
actDir = 2;
}
break;
case SDLK_RIGHT:
if (actDir != 1) {
actDir = 3;
}
break;
}
break;
}
}
}
void eventExit(SDL_Event occur, bool& run) {
bool chose = true;
while (chose) {
while (SDL_PollEvent(&occur)) {
switch (occur.type) {
case SDL_QUIT:
run = false;
chose = false;
break;
case SDL_KEYDOWN:
switch (occur.key.keysym.sym) {
case SDLK_y:
run = true;
chose = false;
break;
case SDLK_n:
run = false;
chose = false;
break;
}
break;
}
}
}
}
void eventStart(SDL_Event occur, bool& run) {
bool chose = true;
while (chose) {
while (SDL_PollEvent(&occur)) {
switch (occur.type) {
case SDL_QUIT:
run = false;
chose = false;
break;
case SDL_KEYDOWN:
switch (occur.key.keysym.sym) {
case SDLK_SPACE:
run = true;
chose = false;
break;
case SDLK_ESCAPE:
run = false;
chose = false;
break;
}
break;
}
}
}
}
void moveSnakeHead(int actDir, SDL_Rect& snake) {
if (actDir == 0) {
snake.y -= 15;
}
if (actDir == 1) {
snake.x -= 15;
}
if (actDir == 2) {
snake.y += 15;
}
if (actDir == 3) {
snake.x += 15;
}
}
| true |
50a8b24379256ab89bd37b0cd82548b73d833a2a | C++ | xeroxx/mc_linuxrt | /src/timer.cpp | UTF-8 | 1,070 | 2.515625 | 3 | [
"BSD-2-Clause"
] | permissive | /*
* Copyright 2019-2020 mc_rtc development team
*/
#include "timer.h"
#include <cassert>
#include <cstring>
#include <iostream>
#include <sys/timerfd.h>
#include <unistd.h>
Timer::Timer(unsigned int usec)
{
fd_ = timerfd_create(CLOCK_MONOTONIC, 0);
if(fd_ == -1)
{
std::cerr << "timerfd_create failed: " << strerror(errno) << "\n";
throw(std::runtime_error("timerfd_create failed"));
}
struct itimerspec itval;
itval.it_interval.tv_sec = usec / 1000000;
itval.it_interval.tv_nsec = 1000 * (usec % 1000000);
itval.it_value.tv_sec = usec / 1000000;
itval.it_value.tv_nsec = 1000 * (usec % 1000000);
if(timerfd_settime(fd_, 0, &itval, nullptr) != 0)
{
std::cerr << "timerfd_settime failed: " << strerror(errno) << "\n";
throw(std::runtime_error("timerfd_settime failed"));
}
}
void Timer::wait()
{
uint64_t missed;
if(read(fd_, &missed, sizeof(missed)) < 0)
{
std::cerr << "read failed: " << strerror(errno) << "\n";
return;
}
if(missed != 1)
{
assert(missed > 0);
missed_ += (missed - 1);
}
}
| true |
9ddea602f78a7b14672cf35bb5f1637089faa9d7 | C++ | edbird/cpp-bitmap-lib | /src/bitmap.cpp | UTF-8 | 29,217 | 3.03125 | 3 | [] | no_license | #include "bitmap.hpp"
inline
uint64_t BMP::BITMAP::index(const LONG x, const LONG y) const
{
// note m_width_memory has unit of BYTE
// x has units of (index)
// y has units of (index)
// m_bit_count has units of BYTE
uint64_t index = ((m_bit_count / 8) * x + y * m_width_memory);
return index;
}
uint16_t BMP::BITMAP::ushort_rev(const uint16_t data) const
{
return ( ((data & 0xFF00) >> 0x08) |
((data & 0x00FF) << 0x08) );
}
uint32_t BMP::BITMAP::uint_rev(const uint32_t data) const
{
return (
((data & 0xFF000000) >> 0x18) |
((data & 0x00FF0000) >> 0x08) |
((data & 0x0000FF00) << 0x08) |
((data & 0x000000FF) << 0x18) );
}
uint64_t BMP::BITMAP::ulong_rev(const uint64_t data) const
{
return (
((data & 0xFF00000000000000) >> 0x38) |
((data & 0x00FF000000000000) >> 0x28) |
((data & 0x0000FF0000000000) >> 0x18) |
((data & 0x000000FF00000000) >> 0x08) |
((data & 0x00000000FF000000) << 0x08) |
((data & 0x0000000000FF0000) << 0x18) |
((data & 0x000000000000FF00) << 0x28) |
((data & 0x00000000000000FF) << 0x38) );
}
std::string BMP::BITMAP::filename_extension(const std::string& str, std::string* str_no_ext_p) const
// str_no_ext_p is a pointer to a string which holds the contents of str with the file extension
// and period removed from the end (no extension)
// if this is nullptr, then the argument is not set
{
std::string::size_type index{str.rfind('.')};
if(index != std::string::npos)
{
// TODO: test this
//std::cout << "filename is " << str.substr(0, str.size() - index) << " extension is " << str.substr(index + 1) << std::endl;
if(str_no_ext_p != nullptr)
{
str_no_ext_p->operator=(str.substr(0, str.size() - index)); // extract string without extension
}
return str.substr(index + 1);
}
else
{
//std::cerr << "no char '.' found" << std::endl; // this is just a test for now
if(str_no_ext_p != nullptr)
{
str_no_ext_p->operator=(str); // set string without extension to be full string
}
return std::string(""); // return empty string, no period found
}
}
inline
std::string BMP::BITMAP::filename_extension(const std::string& str) const
{
return filename_extension(str, nullptr);
}
// swap function for exception safety / efficiency
namespace BMP
{
void swap(BMP::BITMAP& l, BMP::BITMAP& r)
{
using std::swap;
swap(l.m_width, r.m_width);
swap(l.m_height, r.m_height);
swap(l.m_bit_count, r.m_bit_count);
swap(l.m_width_pad, r.m_width_pad);
swap(l.m_width_memory, r.m_width_memory);
swap(l.m_data, r.m_data);
}
}
// TODO: WARNING: bit_count ONLY WORKS FOR 24, 32 BIT IMAGES! (due to / 8 operation)
void BMP::BITMAP::reinitialize(const LONG width, const LONG height, const WORD bit_count)
{
m_width = width;
m_height = height;
m_bit_count = bit_count;
m_width_pad = (4 - ((LONG)(bit_count / 8) * width) % 4) % 4; // BYTES!
m_width_memory = (LONG)(bit_count / 8) * width + m_width_pad; // BYTES!
m_data.resize(m_width_memory * m_height);
//std::cout << "BITMAPBase: width=" << m_width << " height=" << m_height << " pad=" << m_width_pad << " width_mem=" << m_width_memory << std::endl;
}
BMP::BITMAP::BITMAP()
: m_width{0}
, m_height{0}
, m_bit_count{0}
, m_width_pad{0}
, m_width_memory{0}
, m_data(0)
{
}
BMP::BITMAP::BITMAP(const LONG width, const LONG height, const WORD bit_count)
: m_width{width}
, m_height{height}
, m_bit_count{bit_count}
, m_width_pad{(4 - ((LONG)(bit_count / 8) * width) % 4) % 4}
, m_width_memory{(bit_count / 8) * width + m_width_pad}
, m_data(m_width_memory * m_height)
//: BITMAP(0, 0, 0) // this is to save duplicate code
{
//reinitialize(width, height, bit_count); // this is to save duplicate code
//std::cout << "BITMAP: width=" << m_width << " height=" << m_height << " pad=" << m_width_pad << " width_mem=" << m_width_memory << std::endl;
// do nothing, file created in memory
//Clear(); // rgb clear?
}
BMP::BITMAP::BITMAP(const std::string& filename)
: BITMAP(0, 0, 0) // rather than inheriting, should this class have BITMAP as a data member?
{
Load(filename);
}
BMP::BITMAP::~BITMAP()
{
//std::cout << "BITMAP" << std::endl;
}
BMP::BITMAP::BITMAP(const BITMAP& bmpsurface)
: m_width{bmpsurface.m_width}
, m_height{bmpsurface.m_height}
, m_bit_count{bmpsurface.m_bit_count}
, m_width_pad{bmpsurface.m_width_pad}
, m_width_memory{bmpsurface.m_width_memory}
, m_data{bmpsurface.m_data}
{
}
BMP::BITMAP::BITMAP(BITMAP&& bmpsurface)
: BITMAP(0, 0, 0)
{
swap(*this, bmpsurface);
}
BMP::BITMAP& BMP::BITMAP::operator=(BITMAP bmpsurface)
{
swap(*this, bmpsurface);
return *this;
}
void BMP::BITMAP::Load(const std::string& filename)
{
std::string f_ext{filename_extension(filename)};
if(f_ext == std::string("bmp"))
{
LoadBITMAP(filename); // leave .bmp on for argument
}
else if(f_ext == std::string("png"))
{
std::cerr << "TODO" << std::endl;
//LoadPNG(filename); // leave .png on for argument
}
else
{
std::cerr << "Could not detect file type from filename extension. File not loaded!" << std::endl;
}
}
void BMP::BITMAP::SaveAs(const std::string& filename) const
{
std::string f_ext{filename_extension(filename)};
if(f_ext == std::string("bmp"))
{
SaveAsBitmap(filename); // leave .bmp on for argument
}
else if(f_ext == std::string("png"))
{
std::cerr << "TODO" << std::endl;
//SaveAsPNG(filename); // leave .png on for argument
}
else
{
std::cerr << "Could not detect file type from filename extension. Defaulting to bitmap file format" << std::endl;
SaveAsBitmap(filename); // leave .bmp on for argument
}
}
#include <cstring>
std::vector<unsigned char> BMP::BITMAP::SaveMem() const
{
// memory storage
std::vector<unsigned char> memory;
BITMAPFILEHEADER f_head;
f_head.bfType = ushort_rev(((WORD)'B' << 0x08) | ((WORD)'M' << 0x00));
f_head.bfSize = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + m_width_memory * m_height; //m_bit_count *
f_head.bfReserved1 = 0;
f_head.bfReserved2 = 0;
f_head.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
// build standard bitmap file header
BITMAPINFOHEADER i_head;
i_head.biSize = sizeof(BITMAPINFOHEADER);
i_head.biWidth = m_width;
i_head.biHeight = m_height;
i_head.biPlanes = 1;
i_head.biBitCount = m_bit_count;
i_head.biCompression = 0;
i_head.biSizeImage = m_width_memory * m_height;
i_head.biXPelsPerMeter = 0;
i_head.biYPelsPerMeter = 0;
i_head.biClrUsed = 0;
i_head.biClrImportant = 0;
// alloc
memory.resize(f_head.bfSize);
//std::copy(&f_head, &f_head + sizeof(f_head), memory.at(0));
//std::copy(&i_head, &i_head + sizeof(i_head), memory.at(0) + sizeof(f_head));
memcpy(memory.data() + 0, &f_head, sizeof(f_head));
memcpy(memory.data() + sizeof(f_head), &i_head, sizeof(i_head));
// write data
for(unsigned int y = 0; y < m_height; ++ y)
{
//outputfile.write((char*)(m_data + y * (3 * m_size_x)), 3 * m_size_x);
//outputfile.write((char*)(&m_data[y * m_width_memory]), m_width_memory);
//std::copy(&m_data[y * m_width_memory], m_data[y * m_width_memory + m_width_memory], memory.at(0) + sizeof(f_head) + sizeof(i_head));
memcpy(memory.data() + sizeof(f_head) + sizeof(i_head) + y * m_width_memory, m_data.data() + y * m_width_memory, m_width_memory);
// TODO: need to add a m_size_x_pad variable and m_x_pad variable, and include the padding in memory
// don't bother putting zeros for padding, just write whatever is in the memory array
//for(unsigned int p = 0; p < x_pad; ++ p)
// outputfile.put(0); // put as many zeros required for padding
}
return std::move(memory);
}
void BMP::BITMAP::LoadBITMAP(const std::string& filename)
{
std::ifstream inputfile(filename.c_str(), std::ios::binary);
if(!inputfile.is_open())
{
std::cerr << "Unable to open input file " << filename << std::endl;
}
else
{
BITMAPFILEHEADER f_head;
//f_head.bfType = ((WORD)'B' << 0x08) | ((WORD)'M' << 0x00);
//f_head.bfSize = uint_rev(sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + m_bit_count * m_width_memory * m_height);
//f_head.bfReserved1 = 0;
//f_head.bfReserved2 = 0;
//f_head.bfOffBits = uint_rev(sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER));
// build standard bitmap file header
BITMAPINFOHEADER i_head;
//i_head.biSize = uint_rev(sizeof(BITMAPINFOHEADER));
//i_head.biWidth = ulong_rev(m_width);
//i_head.biHeight = ulong_rev(m_height);
//i_head.biPlanes = ushort_rev(1);
//i_head.biBitCount = ushort_rev(m_bit_count);
//i_head.biCompression = 0;
//i_head.biSizeImage = uint_rev(m_bit_count * m_width_memory * m_height);
//i_head.biXPelsPerMeter = 0;
//i_head.biYPelsPerMeter = 0;
//i_head.biClrUsed = 0;
//i_head.biClrImportant = 0;
inputfile.read((char*)&f_head, sizeof(BITMAPFILEHEADER));
inputfile.read((char*)&i_head, sizeof(BITMAPINFOHEADER));
//std::cout << "BITMAPFILEHEADER: " << sizeof(BITMAPFILEHEADER) << std::endl;
//std::cout << "BITMAPINFOHEADER: " << sizeof(BITMAPINFOHEADER) << std::endl;
if(f_head.bfType == ushort_rev(((WORD)'B' << 0x08) | ((WORD)'M' << 0x00)))
{
std::streampos /*size_t*/ index_temp{inputfile.tellg()};
inputfile.seekg(0, std::ios::end);
/*size_t*/ std::streampos file_size{inputfile.tellg()};
if(f_head.bfSize != file_size)
{
std::cerr << "File head error: Head file size label does not match file size." << std::endl;
//std::cerr << "f_head.bfSize=" << f_head.bfSize << std::endl;
//std::cerr << file_size << std::endl;
//std::cerr << file_size << std::endl;
//std::cout << ((f_head.bfSize & 0xff000000) >> 24) << std::endl;
//std::cout << ((f_head.bfSize & 0x00ff0000) >> 16) << std::endl;
//std::cout << ((f_head.bfSize & 0x0000ff00) >> 8) << std::endl;
//std::cout << ((f_head.bfSize & 0x000000ff) >> 0) << std::endl;
}
else
{
inputfile.seekg(index_temp, std::ios::beg);
if(f_head.bfReserved1 != 0)
{
std::cerr << "Warning: bfReserved1 non-zero, ignore" << std::endl;
}
// don't care about this result
if(f_head.bfReserved2 != 0)
{
std::cerr << "Warning: bfReserved2 non-zero, ignore" << std::endl;
}
// don't care about this result
// get offset
//size_t bitmap_data_offset{uint_rev(f_head.bfOffBits)};
if(i_head.biSize != sizeof(BITMAPINFOHEADER))
{
std::cerr << "File info head error: Unexpected info head size value" << std::endl;
std::cerr << sizeof(BITMAPINFOHEADER) << std::endl;
std::cerr << i_head.biSize << std::endl;
}
else
{
if(i_head.biPlanes != 1)
{
std::cerr << "File info head error: Unexpected info head planes value" << std::endl;
}
else
{
if(i_head.biBitCount != 24)
{
std::cerr << "File info head error: Unexpected info head bit count value" << std::endl;
}
else
{
size_t expected_pad{(4 - ((LONG)(i_head.biBitCount / 8) * i_head.biWidth) % 4) % 4};
size_t expected_width_memory{((i_head.biBitCount / 8) * i_head.biWidth) + expected_pad};
size_t expected_size{expected_width_memory * i_head.biHeight};
if(file_size != expected_size + sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER))
{
std::cerr << "File info head error: Calculated file size does not match value calculated from header size, info header size, image width, height, depth." << std::endl;
//std::cerr << file_size << std::endl;
//std::cerr << expected_size + sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) << std::endl;
//std::cerr << i_head.biWidth << ", " << i_head.biHeight << ", " << expected_pad << std::endl;
// TODO: leave these debug statements in
}
else
{
if(i_head.biCompression != 0)
{
std::cerr << "Image is compressed, load abort" << std::endl;
}
else
{
if(i_head.biSizeImage != expected_size)
{
std::cerr << "File info head error: Calculated file size does not match value calculated from image width, height, depth." << std::endl;
}
else
{
if(i_head.biXPelsPerMeter)
{
#ifdef WARNINGS_ON
std::cerr << "Warning: Ignoring non-zero value for biXPelsPerMeter" << std::endl;
#endif
}
if(i_head.biYPelsPerMeter)
{
#ifdef WARNINGS_ON
std::cerr << "Warning: Ignoring non-zero value for biYPelsPerMeter" << std::endl;
#endif
}
if(i_head.biClrUsed)
{
std::cerr << "Warning: Ignoring non-zero value for color pallet, used" << std::endl;
}
if(i_head.biClrImportant)
{
std::cerr << "Warning: Ignoring non-zero value for color pallet, important" << std::endl;
}
// init memory
reinitialize(i_head.biWidth, i_head.biHeight, i_head.biBitCount);
// load memory
inputfile.seekg(f_head.bfOffBits);
//std::cout << "SEEK: " << f_head.bfOffBits << std::endl;
// read data
for(unsigned int y = 0; y < m_height; ++ y)
{
inputfile.read((char*)(&m_data[y * m_width_memory]), m_width_memory);
// TODO: need to add a m_size_x_pad variable and m_x_pad variable, and include the padding in memory
// don't bother putting zeros for padding, just write whatever is in the memory array
//for(unsigned int p = 0; p < x_pad; ++ p)
// outputfile.put(0); // put as many zeros required for padding
}
//outputfile.flush();
inputfile.close();
//std::clog << "Canvas read from input file " << filename << std::endl;
} // biSizeImage
} // biCompression
} // file_size
} // biBitCount
} // biPlanes
} // biSize
} // f_head.bfSize
} // f_head.bfType
else
{
std::cerr << "File format error: Missing 'B'|'M' from head." << std::endl;
}
}
}
void BMP::BITMAP::SaveAsBitmap(const std::string& filename) const
{
std::ofstream outputfile(filename.c_str(), std::ios::binary);
//outputfile.exceptions(std::ofstream::failbit | std::ofstream::badbit);
//try
//{
// outputfile.open(filename.c_str(), std::ios::binary);
//}
//catch(std::ofstream::failure ofstreamexcept)
//{
// //ofstreamexcept.
// //std::ios_base::failure& e
// std::cerr << ofstreamexcept.what() << std::endl;
//}
if(!outputfile.is_open())
{
std::cerr << "Unable to open output file " << filename << std::endl;
}
else
{
// compute the amount of padding required - this is because the bitmap file
// format must end on a 4 byte boundry for every line of pixels
//unsigned short x_pad = (4 - (3 * m_size_x) % 4) % 4;
//if((3 * m_size_x) % 4 == 0)
//{
// x_pad = 0;
//}
//else
//{
// x_pad = 4 - (3 * m_size_x) % 4;
//}
BITMAPFILEHEADER f_head;
f_head.bfType = ushort_rev(((WORD)'B' << 0x08) | ((WORD)'M' << 0x00));
f_head.bfSize = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + m_width_memory * m_height; //m_bit_count *
f_head.bfReserved1 = 0;
f_head.bfReserved2 = 0;
f_head.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
// build standard bitmap file header
BITMAPINFOHEADER i_head;
i_head.biSize = sizeof(BITMAPINFOHEADER);
i_head.biWidth = m_width;
i_head.biHeight = m_height;
i_head.biPlanes = 1;
i_head.biBitCount = m_bit_count;
i_head.biCompression = 0;
i_head.biSizeImage = m_width_memory * m_height;
i_head.biXPelsPerMeter = 0;
i_head.biYPelsPerMeter = 0;
i_head.biClrUsed = 0;
i_head.biClrImportant = 0;
outputfile.write((char*)&f_head, sizeof(BITMAPFILEHEADER));
outputfile.write((char*)&i_head, sizeof(BITMAPINFOHEADER));
/*
// build the standard bitmap file header
unsigned char h[54];
// BITMAP Header
h[0] = 'B'; h[1] = 'M'; // BM - these characters have to be here
int_to_char_array_reversed(14 + 40 + (3 * m_size_x + x_pad) * m_size_y, &h[2]); // Put total filesize into h[2], h[3], h[4], h[5]
h[6] = 0x00; h[7] = 0x00; h[8] = 0x00; h[9] = 0x00; // Reserved bytes, set to zero
h[10] = 0x36; h[11] = 0x00; h[12] = 0x00; h[13] = 0x00; // Pixel data offset, always starts at 0x36 == 54
// DIP Header
h[14] = 0x28; h[15] = 0x00; h[16] = 0x00; h[17] = 0x00; // Size of DIP header, endian reverse, 0x28 == 40
int_to_char_array_reversed(m_size_x, &h[18]); // Width of image (signed int)
int_to_char_array_reversed(m_size_y, &h[22]); // Height of image (signed int)
h[26] = 0x01; h[27] = 0x00; // Number of planes (1)
h[28] = 0x18; h[29] = 0x00; // 24 bits per pixel, 0x18 == 24
h[30] = 0x00; h[31] = 0x00; h[32] = 0x00; h[33] = 0x00; // Compression method (none)
int_to_char_array_reversed((3 * m_size_x + x_pad) * m_size_y, &h[34]); // Image size - same as file size - 54 bytes for header
for(int ix = 38; ix < 29 + 4 * 6; ++ ix) // X Res, Y Res, Colors in color pallet, More info on color pallet - just set all of this stuff to zero
h[ix] = 0x00; // 2016-04-21 Not sure why the hell I chose 29 + 4 * 6 but it doesnt matter if array initialized to zero
// 29 + 4 * 6 = 29 + 24 = 53 (should be <= )
// 54 - 38 = 16
// write header to file
outputfile.write((char*)h, 54);
*/
// write data
for(unsigned int y = 0; y < m_height; ++ y)
{
//outputfile.write((char*)(m_data + y * (3 * m_size_x)), 3 * m_size_x);
outputfile.write((char*)(&m_data[y * m_width_memory]), m_width_memory);
// TODO: need to add a m_size_x_pad variable and m_x_pad variable, and include the padding in memory
// don't bother putting zeros for padding, just write whatever is in the memory array
//for(unsigned int p = 0; p < x_pad; ++ p)
// outputfile.put(0); // put as many zeros required for padding
}
outputfile.flush();
outputfile.close();
//std::clog << "Canvas written to output file " << filename << std::endl;
}
}
void BMP::BITMAP::Clear()
{
for(unsigned int y{0}; y < m_height; ++ y)
{
for(unsigned int x{0}; x < m_width; ++ x)
{
//m_data[x + y * m_width_memory] &=
m_data[index(x, y) + 2] = 0x00;
m_data[index(x, y) + 1] = 0x00;
m_data[index(x, y) + 0] = 0x00;
}
}
}
/*
std::vector<uint8_t>& BMP::BITMAP::Data()
{
return m_data;
}
*/
void BMP::BITMAP::RGBFilterGeneric(const uint8_t r, const uint8_t g, const uint8_t b, FunctorKernel functorkernel)
{
for(unsigned int y{0}; y < m_height; ++ y)
{
for(unsigned int x{0}; x < m_width; ++ x)
{
functorkernel.operator()(&m_data[index(x, y) + 2], &m_data[index(x, y) + 2], &r);
functorkernel.operator()(&m_data[index(x, y) + 1], &m_data[index(x, y) + 1], &g);
functorkernel.operator()(&m_data[index(x, y) + 0], &m_data[index(x, y) + 0], &b);
}
}
}
void BMP::BITMAP::RGBFilterAND(const uint8_t r, const uint8_t g, const uint8_t b)
{
RGBFilterGeneric(r, g, b, FunctorKernel(KernelMode::AND));
}
void BMP::BITMAP::RGBFilterOR(const uint8_t r, const uint8_t g, const uint8_t b)
{
RGBFilterGeneric(r, g, b, FunctorKernel(KernelMode::OR));
}
void BMP::BITMAP::RGBFilterXOR(const uint8_t r, const uint8_t g, const uint8_t b)
{
RGBFilterGeneric(r, g, b, FunctorKernel(KernelMode::XOR));
}
void BMP::BITMAP::Resize(const int width, const int height)
{
BITMAP temp(width, height, m_bit_count);
for(int y{0}; y < height; ++ y)
{
for(int x{0}; x < width; ++ x)
{
int y_in{(m_height * y) / height};
int x_in{(m_width * x) / width};
temp.m_data[temp.index(x, y) + 2] = m_data[index(x_in, y_in) + 2];
temp.m_data[temp.index(x, y) + 1] = m_data[index(x_in, y_in) + 1];
temp.m_data[temp.index(x, y) + 0] = m_data[index(x_in, y_in) + 0];
}
}
*this = temp;
}
// TODO: want to implement using pixels (RGB)
// require get/set and pixel struct
// TODO: LONG vs int
void BMP::BITMAP::Translate(const int dx, const int dy)
{
BITMAP temp(m_width, m_height, m_bit_count);
//temp.Clear();
// assume init to zero?
// iterate over output
for(int y{0}; y < m_height; ++ y)
{
for(int x{0}; x < m_width; ++ x)
{
int y_in{y - dy};
int x_in{x - dx};
if(y_in >= m_height)
{
}
else if(y_in < 0)
{
}
else
{
if(x_in >= m_width)
{
}
else if(x_in < 0)
{
}
else
{
temp.m_data[temp.index(x, y) + 2] = m_data[index(x_in, y_in) + 2];
temp.m_data[temp.index(x, y) + 1] = m_data[index(x_in, y_in) + 1];
temp.m_data[temp.index(x, y) + 0] = m_data[index(x_in, y_in) + 0];
}
}
}
}
*this = temp;
}
/*
void BMP::BITMAP::OperatorKernelUnary(const BITMAP& bitmap, FunctorKernel kernel)
{
// iterate over output
for(int y{0}; y < m_height; ++ y)
{
for(int x{0}; x < m_width; ++ x)
{
// bounds check
if(y >= m_height)
{
}
else if(y >= bitmap.m_height)
{
}
else
{
if(x >= m_width)
{
}
else if(x >= bitmap.m_width)
{
}
else
{
kernel.operator()(&m_data[index(x, y) + 2], &bitmap.m_data[index(x, y) + 2]);
kernel.operator()(&m_data[index(x, y) + 1], &bitmap.m_data[index(x, y) + 1]);
kernel.operator()(&m_data[index(x, y) + 0], &bitmap.m_data[index(x, y) + 0]);
}
}
}
}
}
*/
// TODO: versions where x and y are translated
//void BMP::BITMAP::OperatorKernelUnary(const BITMAP& bitmap_l, const BITMAP& bitmap_r, FunctorKernel kernel, TranslationVector, TranslectorVector)
void BMP::BITMAP::OperatorKernelBinary(const BITMAP& bitmap_l, const BITMAP& bitmap_r, FunctorKernel kernel)
{
// iterate over output
LONG y_min{0};
LONG y_max{m_height};
if(y_max >= bitmap_l.m_height) y_max = bitmap_l.m_height;
if(y_max >= bitmap_r.m_height) y_max = bitmap_r.m_height;
for(LONG y{y_min}; y < y_max; ++ y)
{
LONG x_min{0};
LONG x_max{m_width};
if(x_max >= bitmap_l.m_width) x_max = bitmap_l.m_width;
if(x_max >= bitmap_r.m_width) x_max = bitmap_r.m_width;
for(LONG x{x_min}; x < x_max; ++ x)
{
void* const output_addr{&m_data[index(x, y)]};
const void* const input_addr_l{&bitmap_l.m_data[index(x, y)]};
const void* const input_addr_r{&bitmap_r.m_data[index(x, y)]};
PixelRGB &output_ref{*((PixelRGB* const)output_addr)};
const PixelRGB &input_ref_l{*((const PixelRGB* const)input_addr_l)};
const PixelRGB &input_ref_r{*((const PixelRGB* const)input_addr_r)};
kernel.operator()(output_ref, input_ref_l, input_ref_r);
}
}
}
void BMP::BITMAP::OperatorKernelUnary(const BITMAP& bitmap, FunctorKernel kernel)
{
// iterate over output
LONG y_min{0};
LONG y_max{m_height};
if(y_max >= bitmap.m_height) y_max = bitmap.m_height;
for(LONG y{y_min}; y < y_max; ++ y)
{
LONG x_min{0};
LONG x_max{m_width};
if(x_max >= bitmap.m_width) x_max = bitmap.m_width;
for(LONG x{x_min}; x < x_max; ++ x)
{
void* const output_addr{&m_data[index(x, y)]};
const void* const input_addr{&bitmap.m_data[index(x, y)]};
PixelRGB &output_ref{*((PixelRGB* const)output_addr)};
const PixelRGB &input_ref{*((const PixelRGB* const)input_addr)};
kernel.operator()(output_ref, input_ref);
}
}
}
// TODO delete
void BMP::BITMAP::Generic(const BITMAP& bitmap, FunctorKernel functorkernel)
{
// iterate over output
for(int y{0}; y < m_height; ++ y)
{
for(int x{0}; x < m_width; ++ x)
{
if(y >= m_height)
{
}
else if(y >= bitmap.m_height)
{
}
else
{
if(x >= m_width)
{
}
else if(x >= bitmap.m_width)
{
}
else
{
functorkernel.operator()(&m_data[index(x, y) + 2], &bitmap.m_data[index(x, y) + 2]);
functorkernel.operator()(&m_data[index(x, y) + 1], &bitmap.m_data[index(x, y) + 1]);
functorkernel.operator()(&m_data[index(x, y) + 0], &bitmap.m_data[index(x, y) + 0]);
}
}
}
}
}
void BMP::BITMAP::AND(const BITMAP& bitmap)
{
Generic(bitmap, FunctorKernel(KernelMode::AND));
}
void BMP::BITMAP::OR(const BITMAP& bitmap)
{
Generic(bitmap, FunctorKernel(KernelMode::OR));
}
void BMP::BITMAP::XOR(const BITMAP& bitmap)
{
Generic(bitmap, FunctorKernel(KernelMode::XOR));
}
| true |
edb48606a00feb96147736814038abc13da540a4 | C++ | AndelasOne/Iteratoren | /Source/iter_print.h | UTF-8 | 861 | 4 | 4 | [] | no_license |
#ifndef ITERATOREN_ITER_PRINT_H
#define ITERATOREN_ITER_PRINT_H
#include <cmath>
#include <iostream>
//copy assignment
// operatoren: !=, ++, *()
// vector.begin() vector.end() returns iterator
namespace Print
{
template<typename T>
void print(const T begin, const T end) {
for (T pos = begin; pos != end; pos++) {
std::cout << *pos << std::endl;
}
}
template<typename Container>
void print(Container const &c) {
print(c.begin(), c.end());
}
template<typename Container>
void print_half(Container const &c) {
print(c.begin(), c.begin() + std::ceil(c.size() / 2));
}
//cout overload to print values in the container
template <typename T>
void operator <<(std::ostream & out, T const & container){
print(container);
}
}
#endif //ITERATOREN_ITER_PRINT_H
| true |
b946c5dd028caedd50312c971e69c744bf9119c8 | C++ | Enrahim/publicProjects | /ShaderTestingFramework/ShaderTesterMain.h | UTF-8 | 2,544 | 2.828125 | 3 | [] | no_license | #ifndef SHADERTESTERMAIN_H
#define SHADERTESTERMAIN_H
#include <GL/glew.h>
#include <GL/gl.h>
#include <GL/glut.h>
#include "Camera.h"
#include "ShaderSystem.h"
/** Basic framework for shadertesting */
class ShaderMain {
/** Shader system */
ShaderSystem shaders;
/** Camera object */
Camera camera;
/** width of window */
int width;
/** height of window */
int height;
/** ID of texture */
GLuint textureID;
/** ID of texture buffer */
GLuint textureBufferID;
/** initializes the glut system */
void initGLUT(int argc, char* argv[]);
/** Initializes the openGL system */
void initGL();
/** Initializes assets */
void initAssets();
public:
/** run the program */
void run(int argc, char* argv[]);
/** Prints the instructions in a consolle window */
void printInstructions();
// Functions called by callback
/** Mouse function that handles gui draging */
void mouseButtonClick(int button, int state, int x, int y);
/** Mouse function that handles gui draging */
void mouseMove(int x, int y);
/** Handles specialkeys, used for camera controll */
void specialKeys(int key, int x, int y);
/** Handles + and -, used for camera controll */
void handleKeys(unsigned char key, int x, int y);
/** Display function. Should only be called by callback */
void display();
/** Timer function, updates animation. Should only be called by callback */
void tick(int v);
/** reshape function. Should only be called by callback */
void reshape(int w, int h) {
glViewport(0, h-height, width, height);
}
/** Default values */
ShaderMain() : width(800), height(800) {;}
};
extern ShaderMain mainobj;
// Callback functions calling object functions
/** Mouse function that handles gui sellecting */
void mouseButtonClick(int button, int state, int x, int y) {
mainobj.mouseButtonClick(button, state, x, y);
}
/** Mouse function that handles gui draging */
void mouseMove(int x, int y) {
mainobj.mouseMove(x, y);
}
/** Handles specialkeys, used for camera controll */
void specialKeys(int key, int x, int y) {
mainobj.specialKeys(key, x, y);
}
/** Handles + and -, used for camera controll */
void handleKeys(unsigned char key, int x, int y) {
mainobj.handleKeys(key, x, y);
}
/** Display function. Should only be called by callback */
void display() {
mainobj.display();
}
/** reshape function. Should only be called by callback */
void reshape(int w, int h) {
mainobj.reshape(w, h);
}
/** Timer function. Should onlyh be called by callback */
void tick(int v) {
mainobj.tick(v);
}
#endif | true |
b8a83afd7428a91336583c56c4aee8c0ac511a00 | C++ | avnyaswanth/DS_AND_ALGO | /ds_Algo/MergeSort.cpp | UTF-8 | 843 | 3.34375 | 3 | [] | no_license | #include<iostream>
using namespace std;
void merge(int *arr,int l,int m,int r)
{
int n1 = m-l+1;
int n2 = r-m;
int left_arr[n1];
int right_arr[n2];
for(int i=0;i<n1;i++)
left_arr[i] = arr[l+i];
for(int j=0;j<n2;j++)
right_arr[j] = arr[m+1+j];
int i,j,k;
i =0,j = 0,k=l;
while(i<n1&&j<n2)
{
if(left_arr[i]<=right_arr[j])
arr[k++] = left_arr[i++];
else
arr[k++] = right_arr[j++];
}
while(i<n1)
arr[k++] = left_arr[i++];
while(j<n2)
arr[k++] = right_arr[j++];
}
void mergesort(int *arr,int l,int r)
{
if(l<r)
{
int mid = (l+r-1)/2;
mergesort(arr,l,mid);
mergesort(arr,mid+1,r-1);
merge(arr,l,mid,r);
}
}
int main()
{
int arr[] = {9,8,7,6,5,4};
int n = sizeof(arr)/sizeof(arr[0]);
mergesort(arr,0,n-1);
for(int i=0;i<n;i++)
cout<<arr[i]<<ends;
}
| true |
b353b211e3c519c703ac6ffa95e0badbf4f51fdd | C++ | SenpaiPlz/HR-Gagnaskipan-2016-1 | /Gagna - Skil4b/jumpit.cpp | UTF-8 | 684 | 2.9375 | 3 | [] | no_license | #include <iostream>
#include "jumpit.h"
using namespace std;
const int PENALTY = 1000; // Used to assign a very high cost
int jumpIt(const int board[], int startIndex, int endIndex)
{
if(startIndex == endIndex)
{
return board[startIndex];
}
else if(startIndex+1 == endIndex)
{
return board[startIndex] + board[startIndex+1];
}
else
{
if(jumpIt(board,startIndex+1,endIndex) < jumpIt(board,startIndex+2,endIndex))
{
return board[startIndex] + jumpIt(board,startIndex+1,endIndex);
}
else
{
return board[startIndex] + jumpIt(board,startIndex+2,endIndex);
}
}
}
| true |
baacc84004b983095e7de6f44a84779217d9bcd0 | C++ | npj6/PL-2020-C | /p4/TablaSimbolos.h | UTF-8 | 480 | 2.625 | 3 | [] | no_license |
#include <string>
#include <vector>
using namespace std;
const int ENTERO=1;
const int REAL=2;
const int CLASSFUN=3;
struct Simbolo {
string nombre;
int tipo;
string nomtrad;
};
class TablaSimbolos {
public:
TablaSimbolos *padre;
vector<Simbolo> simbolos;
TablaSimbolos(TablaSimbolos *padre);
bool buscarAmbito(Simbolo s); // ver si está en el ámbito actual
bool anyadir(Simbolo s);
Simbolo* buscar(string nombre);
};
| true |
e0d53eb0ba85831087572aab63f3b8bdcbe1d4d4 | C++ | The-E/Starshatter-Experimental | /nGenEx/Camera.h | WINDOWS-1252 | 1,867 | 2.796875 | 3 | [] | no_license | /* Project nGenEx
Destroyer Studios LLC
Copyright 1997-2004. All Rights Reserved.
SUBSYSTEM: nGenEx.lib
FILE: Camera.h
AUTHOR: John DiCamillo
OVERVIEW
========
Camera class - Position and Point of View
*/
#ifndef Camera_h
#define Camera_h
// +--------------------------------------------------------------------+
#include "Types.h"
#include "Geometry.h"
// +--------------------------------------------------------------------+
class Camera
{
public:
static const char* TYPENAME() { return "Camera"; }
Camera(double x=0.0, double y=0.0, double z=0.0);
virtual ~Camera();
void Aim(double roll, double pitch, double yaw) { orientation.Rotate(roll, pitch, yaw); }
void Roll(double roll) { orientation.Roll(roll); }
void Pitch(double pitch) { orientation.Pitch(pitch); }
void Yaw(double yaw) { orientation.Yaw(yaw); }
void MoveTo(double x, double y, double z);
void MoveTo(const Point& p);
void MoveBy(double dx, double dy, double dz);
void MoveBy(const Point& p);
void Clone(const Camera& cam);
void LookAt(const Point& target);
void LookAt(const Point& target, const Point& eye, const Point& up);
bool Padlock(const Point& target, double alimit=-1, double e_lo=-1, double e_hi=-1);
Point Pos() const { return pos; }
Point vrt() const { return Point(orientation(0,0), orientation(0,1), orientation(0,2)); }
Point vup() const { return Point(orientation(1,0), orientation(1,1), orientation(1,2)); }
Point vpn() const { return Point(orientation(2,0), orientation(2,1), orientation(2,2)); }
const Matrix& Orientation() const { return orientation; }
protected:
Point pos;
Matrix orientation;
};
#endif Camera_h
| true |
71ddc52e4efc1cd18b0912f1aa3fad2c528e3902 | C++ | darkmanice/DS | /P1/P1S2E1/include/VisitanteEquipo.h | UTF-8 | 509 | 2.578125 | 3 | [] | no_license | #ifndef __Visitante_equipo__
#define __Visitante_equipo__
#include <string>
using namespace std;
class Bus;
class Disco;
class Tarjeta;
class VisitanteEquipo
{
public:
VisitanteEquipo();
//Obtener la informacion acumulada por el visitante
virtual string getInformacion()=0;
// Visitar Bus
virtual void visitarBus(Bus bus)=0;
// Visitar Disco
virtual void visitarDisco(Disco disco)=0;
// Visitar Tarjeta
virtual void visitarTarjeta(Tarjeta tarjeta)=0;
};
#endif | true |
6cee4611367adea0334d06b473f63f4ac0602ecd | C++ | Tracyee/vanity-number-generator | /vanity_phone_number_c++/lexicon.h | UTF-8 | 333 | 2.875 | 3 | [] | no_license | #include <string>
using namespace std;
struct Node;
class Lexicon {
Node* root;
Node* findNode(const string& str) const;
Node* getNode(const string& str);
public:
Lexicon();
~Lexicon();
void add(const string& word);
bool containsWord(const string& word) const;
bool containsPrefix(const string& prefix) const;
}; | true |
d6ecffa1f51309ec3d2ae41b5c9ac26e7bc2102c | C++ | Chewie23/verbose-journey | /CPP_BB/TicTacToe/RobotPlayer.h | UTF-8 | 419 | 2.703125 | 3 | [] | no_license | #pragma once
#include "AbstractPlayer.h"
#include <vector>
class RobotPlayer : public AbstractPlayer {
protected:
std::vector< int > move_vec; //keeps track of moves
public:
RobotPlayer(const char player) : AbstractPlayer(player) {} //In AbstractPlayer.h
static const char EMPTY;
void make_move(AbstractBoard* board);
void smart_move(AbstractBoard* board);
bool is_board_empty(AbstractBoard* board);
};
| true |
aaea97e35b599b1c0099a6075d5969d76e4548e2 | C++ | pa1012/Student-Management | /ArrayOfCourse.h | UTF-8 | 667 | 2.859375 | 3 | [] | no_license | #pragma once
#include"Course.h"
#include<vector>
#include<sstream>
#include<fstream>
#include"Convert.h"
using namespace std;
class ArrayOfCourse {
private:
vector <Course> Arr;
public:
void loadCourse();
void loadCourse(string year, int term);
bool isExisted(Course C);
bool isExisted(string courseID);
void tryOutput();
Course findACourse(string id);
vector<Course> returnCourses(string y, int term);
vector<Course> returnCourses();
void saveCourse();
void deleteAll(string year, int term);
void pushCourse(Course C);
int size();
string nameOfCourse(int i);
void removeCourse(string ID);
void editCourse(string ID, string what, string inform);
}; | true |
02f28c2f8dbccd673b1d63d9263656caef63b72a | C++ | EKnapik/SimpleRayTracer | /SimpleRayTracer/Scene/Scene.cpp | UTF-8 | 6,318 | 2.78125 | 3 | [] | no_license | //
// Scene.cpp
// SimpleRayTracer
//
// Created by Eric Knapik on 10/19/15.
// Copyright © 2015 EKnapik. All rights reserved.
//
#include "Scene.hpp"
#include <iostream>
Scene::Scene() {
this->baseBackground = new Background();
this->numObjects = 0;
this->numMeshes = 0;
}
Scene::Scene(Camera *camera) {
this->baseBackground = new Background();
this->numObjects = 0;
this->camera = camera;
this->light = new Light();
this->numObjects = 0;
this->numMeshes = 0;
}
Scene::~Scene() {
delete this->camera;
delete this->light;
delete[] this->objects;
delete[] this->meshes;
}
// MARCHES FOR GEOMETRICS AND PARTICLES
Geometric* Scene::intersectMarch(Ray *ray) {
float tmin = 0.0;
float tmax = 60.0;
float t = tmin;
float const precis = 0.0001;
int const steps = 100;
Geometric *returnShape = this->baseBackground;
if(numObjects == 0) {
return returnShape;
}
for(int i = 0; i < steps; i++) {
float dist = tmax;
float distTemp;
for(int j = 0; j < numObjects; j++) {
distTemp = objects[j]->getDistance(ray->pos + t*ray->dir);
if(distTemp < dist) {
dist = distTemp;
returnShape = objects[j];
}
}
if(dist < precis || t > tmax) {
break;
}
t += dist;
}
if( t>tmax ) {
return this->baseBackground;
}
returnShape->timeHit = t;
return returnShape;
}
// INTERSECTS THE GEOMETRICS AND THE PARTICLES
Geometric* Scene::intersectCast(Ray *ray) {
float resT = 10000.0; // infinity kinda
float tempT;
Geometric *returnShape = this->baseBackground;
for(int i = 0; i < this->numObjects; i++) {
tempT = objects[i]->getIntersect(ray);
if(tempT > 0 && tempT < resT) {
resT = tempT;
returnShape = objects[i];
returnShape->timeHit = resT;
}
}
return returnShape;
}
Geometric* Scene::kdTreeCast(Ray *ray) {
if(this->kdTree == NULL) {
return intersectCast(ray);
}
// this will be modified within the traversal
Geometric* retObj = this->kdTree->traverse(ray, ray->pos);
if(retObj == NULL) {
retObj = this->baseBackground;
}
return retObj;
}
// The naieve approach just recreate it.
void Scene::updateDataStrucutre() {
delete this->kdTree;
this->kdTree = new Kd3Node(MIN, MAX, MIN, MAX, MIN, MAX,
this->numObjects, this->objects, 0);
}
void Scene::addMeshObj(Mesh *meshObj) {
this->numMeshes++;
if(this->numMeshes <= 1) {
this->meshes = (Mesh**) malloc(sizeof(Mesh*));
} else {
this->meshes = (Mesh**) realloc(this->meshes, this->numMeshes*sizeof(Mesh*));
}
if(this->objects == NULL) {
delete[] this->meshes;
std::cerr << "Error (re)allocating memory for adding Mesh obj" << std::endl;
exit(1);
}
this->meshes[numMeshes-1] = meshObj;
int start = this->numObjects;
int i = 0;
this->numObjects += meshObj->numTriangles;
if(start < 1) {
this->objects = (Geometric**) malloc(sizeof(Geometric*));
} else {
this->objects = (Geometric**) realloc(this->objects, this->numObjects*sizeof(Geometric*));
}
if(this->objects == NULL) {
delete[] this->objects;
std::cerr << "Error reallocating memory for adding geometric obj from Mesh" << std::endl;
exit(1);
}
for( ; start < this->numObjects; start++) {
this->objects[start] = meshObj->triangles[i];
i++;
}
updateDataStrucutre();
}
void Scene::addGeometricObj(Geometric *geomObj) {
this->numObjects++;
if(this->numObjects <= 1) {
this->objects = (Geometric**) malloc(sizeof(Geometric*));
} else {
this->objects = (Geometric**) realloc(this->objects, this->numObjects*sizeof(Geometric*));
}
if(this->objects == NULL) {
delete[] this->objects;
std::cerr << "Error reallocating memory for adding geometric obj" << std::endl;
exit(1);
}
this->objects[this->numObjects-1] = geomObj;
updateDataStrucutre();
}
// The scene from Turner Whitted's ray tracing paper
Scene* createTurnerWhitted() {
Scene *scene = new Scene();
scene->camera = new Camera(glm::vec3(1.0, 1.3, 2.2), glm::vec3(1.0, 1.1, -1.0));
scene->light = new Light();
scene->numObjects = 3;
scene->objects = new Geometric *[scene->numObjects];
Plane *plane = new Plane();
plane->setxLimit(glm::vec2(-5, 3));
plane->setzLimit(glm::vec2(-10, 5));
scene->objects[0] = plane;
scene->objects[0]->ambCoeff = 0.15;
scene->objects[0]->diffCoeff = 0.95;
scene->objects[0]->specCoeff = 0.5;
scene->objects[0]->specExp = 20.0;
scene->objects[1] = new Sphere(glm::vec3(0.1, 1.0, -1.0), 0.65, glm::vec3(0.7));
scene->objects[1]->reflective = true;
scene->objects[1]->ambCoeff = 0.15;
scene->objects[1]->diffCoeff = 0.25;
scene->objects[1]->specCoeff = 1.0;
scene->objects[1]->specExp = 20.0;
scene->objects[1]->kT = 0;
scene->objects[1]->kR = 0.75;
scene->objects[2] = new Sphere(glm::vec3(1.2, 1.4, 0.2), 0.7, glm::vec3(1.0, 1.0, 1.0));
scene->objects[2]->transmitive = true;
scene->objects[2]->ambCoeff = 0.15;
scene->objects[2]->diffCoeff = 0.075;
scene->objects[2]->specCoeff = 0.2;
scene->objects[2]->specExp = 20.0;
scene->objects[2]->kT = 0.8;
scene->objects[2]->kR = 0.01;
scene->objects[2]->refractIndex = 0.95;
scene->kdTree = new Kd3Node(MIN, MAX, MIN, MAX, MIN, MAX,
scene->numObjects, scene->objects, 0);
return scene;
}
Scene* createMeshTest() {
Scene *scene = new Scene();
scene->camera = new Camera(glm::vec3(0.0, 2.0, 5.0), glm::vec3(0.0, 1.0, -1.0));
scene->light = new Light();
scene->numObjects = 1;
scene->objects = new Geometric *[scene->numObjects];
Plane *plane = new Plane();
scene->objects[0] = plane;
scene->objects[0]->ambCoeff = 0.15;
scene->objects[0]->diffCoeff = 0.95;
scene->objects[0]->specCoeff = 0.5;
scene->objects[0]->specExp = 20.0;
return scene;
}
| true |
90d70c5f2325efc6a07c5802bb8330226e04339e | C++ | Shubham6697/Deffodil | /merged two sorted array.cpp | UTF-8 | 429 | 2.734375 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main()
{
int n,m,total;
cin>>n;
int a[n];
for(int i=0;i<n;i++)
{
cin>>a[i];
}
cin>>m;
int b[m];
for(int i=0;i<m;i++)
{
cin>>b[i];
}
total=n+m;
int mer[total];
copy(a,a+n,mer);
copy(b,b+m,mer+n);
for(int i=0;i<total;i++)
{
cout<<mer[i];
}
return 0;
}
| true |
4790bc812d72b6473a5670711f750cb0a46b7bb8 | C++ | brianbbsu/program | /code archive/GJ/b008.cpp | UTF-8 | 768 | 2.59375 | 3 | [
"MIT"
] | permissive | /**********************************************************************************/
/* Problem: b008 "迴文 (**)" from 字串應用-字元拆解 */
/* Language: C++ */
/* Result: AC (4ms, 176KB) on ZeroJudge */
/* Author: briansu at 2016-08-27 15:51:17 */
/**********************************************************************************/
#include <iostream>
#include <math.h>
#include <string.h>
#include <iomanip>
using namespace std;
int main()
{
string n;
cin>>n;
string s;
for(int i=n.length()-1;i>=0;i--) s += n.substr(i,1);
cout<<((n==s)?"YES":"NO");
} | true |
1ea1e4c4798f76e967de0b99ef824d341a353fe1 | C++ | NicolasGripont/B3125 | /C++/TP_Héritage/src/ConvexPolygon.cpp | UTF-8 | 4,554 | 2.828125 | 3 | [] | no_license | /*************************************************************************
ConvexPolygon - Implementation file of the class <ConvexPolygon>
--------------------------------------------------------------------------
beginning : 12/01/2016 20:54:12
copyright : (C) 2016 by Nicolas GRIPONT, Rim EL IDRISSI MOKDAD
e-mail : nicolas.gripont@insa-lyon.fr , rim.el-idrissi-mokdad@insa-lyon.fr
*************************************************************************/
//---------- Implementation of the class <ConvexPolygon> (file ConvexPolygon.cpp)
//---------------------------------------------------------------- INCLUDE
//---------------------------------------------------------- Sytem include
#include <iostream>
using namespace std;
//------------------------------------------------------ Personnal include
#include "ConvexPolygon.h"
//------------------------------------------------------------------ Types
//-------------------------------------------------------------- Constants
//----------------------------------------------------------------- PUBLIC
//--------------------------------------------------------- Public methods
bool ConvexPolygon::Include(const Point & p) const
// Algorithm :
//
{
bool result = true;
int size = points.size();
int vect = 0, newVect;
Point a, b;
int X1, Y1, X2, Y2;
for( int i = 0; i < size; i++ )
{
a = points[i];
b = points[(i+1)%size];
X1 = a.GetX() - p.GetX();
Y1 = a.GetY() - p.GetY();
X2 = p.GetX() - b.GetX();
Y2 = p.GetY() - b.GetY();
newVect = X1 * Y2 - Y1 * X2;
if(newVect != 0)
{
if(vect/newVect < 0)
{
result = false;
break;
}
vect = newVect;
}
}
return result;
} //----- End of Include
string ConvexPolygon::ToString() const
// Algorithm :
//
{
string s;
for(int i = 0; i < nbTabs; i++)
{
s += "\t";
}
s += "PC ";
s += name;
for(vector<Point>::const_iterator it = points.begin(); it != points.end(); it++)
{
s += " ";
s += to_string((*it).GetX());
s += " ";
s += to_string((*it).GetY());
}
return s;
} //----- End of ToString
bool ConvexPolygon::IsValid() const
// Algorithm :
//
{
bool result = true;
int size = points.size();
int vect = 0, newVect;
Point a, b, c;
int X1, Y1, X2, Y2;
for( int i = 0; i < size; i++ )
{
a = points[i];
b = points[(i+1)%size];
c = points[(i+2)%size];
X1 = a.GetX() - b.GetX();
Y1 = a.GetY() - b.GetY();
X2 = b.GetX() - c.GetX();
Y2 = b.GetY() - c.GetY();
newVect = X1 * Y2 - Y1 * X2;
if(newVect != 0)
{
if(vect/newVect < 0)
{
result = false;
break;
}
vect = newVect;
}
}
return result;
} //----- End of IsValid
ConvexPolygon* ConvexPolygon::Clone() const
// Algorithm :
//
{
ConvexPolygon* clone = new ConvexPolygon(*this);
return clone;
} //----- End of Clone
//------------------------------------------------- Operators overloading
ConvexPolygon & ConvexPolygon::operator = (const ConvexPolygon & oneConvexPolygon)
// Algorithm :
//
{
name = oneConvexPolygon.name;
points = oneConvexPolygon.points;
return *this;
} //----- End of operator =
//--------------------------------------------- Constructors - destructor
ConvexPolygon::ConvexPolygon(const ConvexPolygon & oneConvexPolygon) :
SimpleShape(oneConvexPolygon)
// Algorithm :
//
{
#ifdef MAP
cout << "Appel au constructeur de copie de <ConvexPolygon>" << endl;
#endif
} //----- End of ConvexPolygon
ConvexPolygon::ConvexPolygon(const string & oneName, const vector<Point> & somePoints) :
SimpleShape(oneName,somePoints)
// Algorithm :
//
{
#ifdef MAP
cout << "Appel au constructeur de <ConvexPolygon>" << endl;
#endif
} //----- End of ConvexPolygon
ConvexPolygon::~ConvexPolygon()
// Algorithm :
//
{
#ifdef MAP
cout << "Appel au destructeur de <ConvexPolygon>" << endl;
#endif
} //----- End of ~ConvexPolygon
//---------------------------------------------------------------- PRIVATE
//------------------------------------------------------ Protected methods
//-------------------------------------------------------- Private methods
| true |
8b7115b55c7bdf97926327301dd2eb7c3137ea29 | C++ | OIegator/Movie-list-application | /film.h | UTF-8 | 364 | 2.625 | 3 | [] | no_license | #ifndef FILM_H
#define FILM_H
#include <QString>
class Film
{
public:
QString title;
QString director;
QString budget;
Film();
Film(QString title,QString director,QString budget);
QString getTitle() const { return title; }
QString getDir() const { return director; }
QString getBud()const { return budget; }
};
#endif // FILM_H
| true |
a2645cb87618a374dc1c456a2845a7f1775e312b | C++ | Heartbleed98/PAT | /PAT乙级/1072.cpp | GB18030 | 1,006 | 3.09375 | 3 | [] | no_license | /*
25min
mapǻԶ
*/
#include<iostream>
#include<string>
#include<vector>
#include<map>
#include<set>
using namespace std;
int main()
{
int n, m;
scanf("%d%d", &n,&m);
int count1 = 0, count2 = 0;
vector<string> v1;
vector<vector<string> > v2;
set<string> s1;
string str1;
for(int i = 0; i < m; i++)
{
cin>>str1;
s1.insert(str1);
}
int temp = 0;
string str2;
for(int i = 0; i < n; i++)
{
vector<string> v3;
cin>>str1;
cin>>temp;
v3.push_back(str1);
for(int i = 0; i < temp; i++)
{
cin>>str2;
if(s1.find(str2) != s1.end())
{
v3.push_back(str2);
}
}
v2.push_back(v3);
}
for(int i = 0; i < v2.size(); i++)
{
if(v2[i].size() == 1) continue;
else
{
count1++;
for(int j = 0; j < v2[i].size(); j++)
{
if(j == 0) cout<<v2[i][j]<<":";
else { cout<<" "<<v2[i][j]; count2++; }
}
cout<<endl;
}
}
cout<<count1<<" "<<count2<<endl;
return 0;
}
| true |
d9e50e2e167c9dff9ad6cad58d131f219c3ef2e0 | C++ | QuanlongCS/lanqiao | /分类的题目/第4章算法初步/4.6twoPointers/4.6双指针.cpp | GB18030 | 508 | 3.046875 | 3 | [] | no_license | #include <cstdio>
#include <iostream>
using namespace std;
int a[];//
int m;
int riot(){
for(int i=0;i<n;i++){
for(int j=i+1;j<n;j++){
if(a[i]+a[j]==m){
printf("%d %d = %d\n",a[i],a[j],m);
}
}
}
}
void twoPointers(){
while(i<j){// 0 ~ n-1
if(a[i]+a[j]==m){
printf("%d %d \n",i,j);
i++;
j--;
}else if(a[i]+a[j] <m){
i++;
}else{
j--;
}
}
}
int main(){
cin>>a[];
cin>>m;
riot();
return 0;
}
| true |
fa934e794bd4b4253b0ec407cbf2bb6867d3417e | C++ | zkmake520/Algorithms | /Merge sort for ListNode.cpp | GB18030 | 3,906 | 3.328125 | 3 | [] | no_license | #include<iostream>
#include<string>
#include<vector>
#include<cstdlib>
#include<time.h>
using namespace std;
struct ListNode{
int val;
ListNode *next;
}List[30];
class Solution{
public:
ListNode *sortList(ListNode *head){
int length = findLength(head); //listij
int width = 1;
ListNode headFirst ; //µͷָ룬Ϊԭheadָ
headFirst.next = head;
for(; width <= length; width =width*2){
ListNode *first = &headFirst; //first ʾleft֮ǰһָ
ListNode *ff = &headFirst;
for(int i =0;i < 8; i++){
ff = ff->next;
cout<<ff->val<<endl;
}
cout<<"\n"<<endl;
for(ListNode *i = headFirst.next; i != NULL;){
ListNode *left =i;
ListNode *middle,*right;
middle = right = left;
for(int j = 0; j < width-1; j++){ //ҳmiddleָ
if(middle->next == NULL)
break;
middle = middle->next;
}
for(int j = 0; j < 2*width-1;j++){ //ҳendָ
if(right->next == NULL)
break;
right = right->next;
}
for(int j = 0; j < 2*width; j++){ //ߵ i һmerge ʼλ
if(i == NULL)
break;
i = i->next;
}
MergeSort(first,left,middle,right);
for(int j = 0; j < 2*width; j++){ //ҳһ leftָǰһָ
if(first == NULL)
break;
first = first->next;
}
}
}
return headFirst.next;
}
void MergeSort(ListNode *first, ListNode *left, ListNode *middle, ListNode *right){
ListNode *rightBegin = middle->next;
ListNode *beg = left;
if(left == middle){
if(left->val <= right->val)
return;
else{
left->next = right->next;
right->next = left;
first->next = right;
return;
}
}
ListNode *last = rightBegin;
ListNode *lastRig = right->next;
while(left != last || rightBegin != lastRig){
if(left == last){
first->next = rightBegin;
rightBegin = rightBegin->next;
}
else if(rightBegin == lastRig){
first->next = left;
left = left->next;
}
else if(left != last && rightBegin!=lastRig && left->val < rightBegin->val){
first->next = left;
left = left->next;
}
else if(left != last && rightBegin!=lastRig && left->val >= rightBegin->val){
first->next = rightBegin;
rightBegin = rightBegin->next;
}
first = first->next;
if(left == last && rightBegin == lastRig) //ΪҪ
first->next = lastRig;
}
}
int findLength(ListNode *head){
ListNode *node = head;
int count = 0;
while(node != NULL){
count++;
node = node->next;
}
return count;
}
};
int main()
{
Solution sol;
srand( (unsigned)time( NULL ) );
for(int i =0;i < 9;i++){
List[i].val = rand()%12;
List[i].next = &List[i+1];
}
List[8].next = NULL;
ListNode *head = sol.sortList(&List[0]);
for(int i =0;i < 9; i++){
cout<<head->val<<endl;
head = head->next;
}
}
| true |
89a9bd5cd341d7f7d94c4891842f4fe9242009bc | C++ | Liu-YT/LeetCode | /剑指offer/把二叉树打印成多行.cpp | UTF-8 | 956 | 3.234375 | 3 | [] | no_license | /*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
vector<vector<int> > Print(TreeNode* pRoot) {
vector<vector<int>> ans;
if(pRoot == nullptr) {
return ans;
}
queue<TreeNode*> q;
q.push(pRoot);
int level = 1;
while(!q.empty()) {
ans.push_back(vector<int>());
int size = q.size();
for(int i = 0; i < size; i++) {
TreeNode* cur = q.front();
q.pop();
ans[level-1].push_back(cur->val);
if(cur->left) {
q.push(cur->left);
}
if(cur->right) {
q.push(cur->right);
}
}
++level;
}
return ans;
}
}; | true |
428504d5b1edf457f702639be47af994f9153e27 | C++ | ahmedsalamay/-Data-Structures-Project-C- | /7/Question 7 [[Data Structure]].cpp | UTF-8 | 971 | 3.015625 | 3 | [] | no_license | #include <iostream>
#include "tree.h"
#include "dictionary.h"
#include <string>
#include <fstream>
using namespace std;
int main()
{
dictionary hamada(10);
ifstream file("EnglishWords.csv");
string word = "";
char temp;
while (true)
{
file.get(temp);
if (file.eof()) break;
if (temp != '\n') word += tolower(temp);
else hamada.add(word), word = "";
}
file.close();
hamada.remove("pall");
short choice;
while (true)
{
puts("=================================================================");
puts("Welcome to the spelling dictionary :) :D :");
cout<<"\nEnter 1 to check the existance of a word in the dictionary, enter 0 to exist : ";
cin >> choice;
if (choice)
{
cout<<"Enter the word : ";
cin >> word;
for (unsigned int i = 0; i < word.size(); i++)word[i] = tolower(word[i]);
if (hamada.contains(word)) puts("\nok\n");
else puts("\nnot found\n");
}
else break;
}
puts("");
system("pause");
return 0;
}
| true |
376e3e632757d00ba91370e423e473be9632f6c4 | C++ | Wajov/PathTracer | /src/Environment.cpp | UTF-8 | 560 | 2.84375 | 3 | [] | no_license | #include "Environment.h"
Environment::Environment() :
texture(QImage()) {}
Environment::Environment(const Texture &texture) :
texture(texture) {}
Environment::~Environment() {}
bool Environment::isNull() const {
return texture.isNull();
}
QVector3D Environment::color(const QVector3D &direction) const {
if (texture.isNull())
return QVector3D(0.0f, 0.0f, 0.0f);
float u = 0.5f - std::atan2(-direction.z(), -direction.x()) / (PI * 2.0f);
float v = 0.5f - std::asin(direction.y()) / PI;
return texture.color(QVector2D(u, v));
} | true |
f91c19660665af318a04c1e460e4d539ca321ef7 | C++ | AntonyMoes/ACID | /src/exp_ball.cpp | UTF-8 | 1,300 | 2.515625 | 3 | [] | no_license | #include <exp_ball.h>
ExpBall::ExpBall(b2Vec2& pos, size_t exp) {
b2BodyDef body_def;
body_def.type = b2_kinematicBody;
body_def.fixedRotation = true;
body_def.position.Set(pos.x / SCALE, pos.y / SCALE);
auto world = SingleWorld::get_instance();
b2Body* body = world->CreateBody(&body_def);
b2PolygonShape shape;
shape.SetAsBox(sizes.x / 2 / SCALE, sizes.y / 2 / SCALE);
body->CreateFixture(&shape, 1.0f);
sf::Texture texture;
if (!texture.loadFromFile("../textures/fireball.jpg",
sf::IntRect(0, 0, sizes.x, sizes.y))) {
throw std::bad_typeid();
}
auto sprite = new sf::Sprite;
sprite->setTexture(texture);
sprite->setOrigin(sizes.x / 2, sizes.y / 2);
sprite->setColor(sf::Color(0, 255, 0));
auto collision_component = new CollisionComponent(body);
body->SetUserData(collision_component);
auto exp_component = new DropExpComponent(exp);
auto texture_component = new TextureComponent(sprite);
auto body_component = new BodyComponent(body);
auto death_component = new DeathComponent;
add_component(collision_component);
add_component(exp_component);
add_component(texture_component);
add_component(body_component);
add_component(death_component);
} | true |
f0de18cee4870c1510c1244c79d2fef13dba50b4 | C++ | baiyidujiang111/transmit-message-through-light | /src/main.cpp | GB18030 | 3,436 | 2.765625 | 3 | [] | no_license | #include<iostream>
#include"Decode.h"
#include"FileConvert.h"
#include<cstdio>
#include<cstdlib>
#include"code.h"
using namespace std;
using namespace cv;
int main()
{
int function;
cout << "function one:encode file to video" << endl;
cout << "function two:decode video to file" << endl;
cout << "Calculate bit error rate" << endl;
cout << "input function you choose" << endl;
cin >> function;
FileConvert converter;
if (function == 1)
{
//ѡַor//ַļĽӿڻûд
unsigned long size;
cout << "Please input size :";
cin >> size;//ҪļĴСλֽ
char filename[] = "in.bin";
converter.GenerateRandFile(filename, size);//ļ
unsigned char* bytes = converter.FileToByte(filename, &size);//ȡļɵByte
/*
һbytesͼĴ
// ʽΪ%05d.png
// imageSrcĿ¼
// */
Code::Main(bytes, size, "imageSrc\\", "png");
int fps = 10;//ÿ10֡
converter.PicTransToVideo(fps);
return 0;
} /*
//
// ֻ¼Ƶ
// */
else if (function == 2)
{
int indexptr = 0;//ڴ洢Ŀĵǰ±
Decode decoder;
int length;
converter.VideoTransToPic();
unsigned char* output=NULL;
int numOfPic=0;//ȡimageOutputĿ¼ļ
Mat img;
img = imread("imageOutput\\00001.png");//0ͼƬ
int type = decoder.getType(img);
if (type == SINGLE)//ֻеͼ
{
output = decoder.decode(img, SINGLE, length);
}
else //if (type == BEGIN)//ͼƬĵһͼƬ
{
Mat tmpimg;
decoder.rotate(img, tmpimg);
int tmplen;
length = decoder.getLength(tmpimg);
output = new unsigned char[length];//ڴݵ
unsigned char* tmp = decoder.decode(tmpimg, type, tmplen);//ǰάݴ
memcpy(output + indexptr, tmp, tmplen);//Ƶյ
indexptr += tmplen;
delete[]tmp;
}//endnormal
for (int i = 2; i <= numOfPic; i++)
{
string path = "imageOutput\\";
char filename[10];
sprintf_s(filename, "%05d.png", i);
img = imread(path + filename);
type = decoder.getType(img);
int tmplen;
unsigned char* tmp = decoder.decode(img, type, tmplen);//ǰάݴ
memcpy(output + indexptr, tmp, tmplen);//Ƶյ
indexptr += tmplen;
delete[]tmp;
}//ͼƬ
char filename[] = "out.bin";
converter.ByteToFile(output, filename, length);
}
else if (function == 3)
{
FileConvert file;
FILE *fp1, *fp2;
unsigned long num1=0,num2=0;
fopen_s(&fp1,"in.bin", "rb");
fopen_s(&fp2,"out.bin", "rb");
num1 = file.GetFileSize(fp1);
num2 = file.GetFileSize(fp1);
unsigned char* dst1 = new unsigned char[num1];
unsigned char* dst2 = new unsigned char[num2];
fread(dst1, sizeof(unsigned char), num1, fp1);
fread(dst2, sizeof(unsigned char), num1, fp2);
unsigned long totalnum=1, wrongnum=0,m=0;
while (totalnum<=(num1+1))
{
totalnum++;
if (dst1[m] != dst2[m]) wrongnum++;
m++;
}
double n;
n = 1 - (wrongnum / totalnum);
cout << "bit error rate is " << n << endl;
return 0;
}
}
| true |
f7851712732e19226b59712cc47dd5b1c1c61be4 | C++ | hishark/Algorithm | /PAT/PATA1046-环上两点的最短距离.cpp | GB18030 | 2,006 | 3.84375 | 4 | [] | no_license | /**
1046 Shortest Distance (20)20 ֣
The task is really simple: given N exits on a highway which forms a simple cycle, you are supposed to tell the shortest distance between any pair of exits.
Input Specification:
Each input file contains one test case. For each case, the first line contains an integer N (in [3, 10^5^]), followed by N integer distances D~1~ D~2~ ... D~N~, where D~i~ is the distance between the i-th and the (i+1)-st exits, and D~N~ is between the N-th and the 1st exits. All the numbers in a line are separated by a space. The second line gives a positive integer M (<=10^4^), with M lines follow, each contains a pair of exit numbers, provided that the exits are numbered from 1 to N. It is guaranteed that the total round trip distance is no more than 10^7^.
Output Specification:
For each test case, print your results in M lines, each contains the shortest distance between the corresponding given pair of exits.
Sample Input:
5 1 2 4 14 9
3
1 3
2 5
4 1
Sample Output:
3
10
7
**/
#include<stdio.h>
#include<iostream>
using namespace std;
/**
һҪעⷶΧMAXNĻ𰸴
д10001ֶδ֮һҪƷΧ
**/
const int MAXN = 100001;
int dis[MAXN];
int main() {
int K;
int sum = 0;
cin >> K;
//Ԥ
for(int i = 1; i <= K; i++) {
int distance;
cin >> distance;
dis[i] = sum + distance;
sum += distance;
}
int N;
cin >> N;
while(N--) {
int start, end;
cin >> start;
cin >> end;
//startһendСŶǵûλ
if(start > end) {
int temp = start;
start = end;
end = temp;
}
int minDis = dis[end - 1] - dis[start - 1];
if(sum - minDis < minDis) {
minDis = sum - minDis;
}
cout << minDis << endl;
}
return 0;
}
//TIME: 00:07:14
| true |
2db5822afa0bf0e3ab59281429b0fb464e3c484f | C++ | w5151381guy/code | /data structure/heapsort.cpp | UTF-8 | 1,274 | 3.75 | 4 | [] | no_license | #include<iostream>
using namespace std;
void heapify(int arr[],int i,int size)
{
int left,right,largest,temp;
left=2*i;
right=(2*i+1);
if((left<=size)&&arr[left]>arr[i]) //判斷子結點有沒有比父結點大
largest=left;
else
largest=i;
if((right<=size)&&(arr[right]>arr[largest])) //同上
largest=right;
if(largest!=i) //如果子結點比父結點大的話就做交換
{
temp=arr[i];
arr[i]=arr[largest];
arr[largest]=temp;
heapify(arr,largest,size);
}
}
void max_heap(int arr[],int size)
{
for(int i=size/2;i>=1;i--)
heapify(arr,i,size);
}
void heapsort(int arr[],int size)
{
int temp;
max_heap(arr,size);
for(int i=size;i>=2;i--)
{
temp = arr[i];
arr[i] = arr[1];
arr[1] = temp;
heapify(arr,1,i-1);
}
}
int main()
{
cout<<"Please enter the size of array:";
int size;
cin>>size;
cout<<"Please enter the element of array:";
int arr[size];
for(int i=1;i<=size;i++)
cin>>arr[i];
heapsort(arr,size);
cout<<"==========After Sorting=========="<<endl;
for(int i=size;i>=1;i--)
{
cout<<arr[i]<<" ";
}
return 0;
}
| true |
30f8352123a99f2e336a1078f061bb9c383ea576 | C++ | CSPshala/BeatWars | /Phat Beats/source/CEmitter.h | UTF-8 | 5,723 | 2.78125 | 3 | [] | no_license | ///////////////////////////////////////////////////////////////////////////
// File Name : "CEmitter.h"
//
// Purpose : To hold data for an emitter
///////////////////////////////////////////////////////////////////////////
#ifndef C_EMITTER_H
#define C_EMITTER_H
#include <list>
using std::list;
#include "CParticle.h"
#include "../ColorF.h"
class CEmitter
{
private:
//********MEMBERS**********//
std::vector<CParticle*> m_ListAliveParticles;
std::vector<CParticle*> m_ListDeadParticles;
std::vector<int> m_vTextureList;
// Data members
std::string m_szName;
RECT m_rectRange;
D3DXVECTOR2 m_tGravityPos;
float m_fGravitationalPull;
float m_fParticleDurationMin;
float m_fPatricleDurationMax;
float m_fLifeSpan;
float m_fSpawnRate;
short m_nMaxParticles;
short m_nNumParticlesToSpit;
// Options
bool m_bRandStartX;
bool m_bRandStartY;
bool m_bRandEndX;
bool m_bRandEndY;
// Start & Ends
tColorF m_tStartColor;
tColorF m_tEndColor;
D3DBLEND m_d3dSource;
D3DBLEND m_d3dDestination;
D3DXVECTOR2 m_vStartVelocity;
D3DXVECTOR2 m_vEndVelocity;
float m_fStartScale;
float m_fEndScale;
float m_fStartRotation;
float m_fEndRotation;
// Data
float m_fCurLife;
float m_fUpdate;
public:
CEmitter();
~CEmitter();
void RecycleParticle();
void Update(float fElapsedTime);
void Render();
// Accessors
inline std::vector<int>* GetTextureList(void) {return &m_vTextureList;}
inline const std::string& GetName(void) {return m_szName;}
inline const RECT& GetRange(void) {return m_rectRange;}
inline const D3DXVECTOR2& GetGravityPosition(void) {return m_tGravityPos;}
inline const float GetGravitationalPull(void) {return m_fGravitationalPull;}
inline const float GetParticleDurationMin(void) {return m_fParticleDurationMin;}
inline const float GetParticleDurationMax(void) {return m_fPatricleDurationMax;}
inline const float GetLifeSpan(void) {return m_fLifeSpan;}
inline const float GetSpawnRate(void) {return m_fSpawnRate;}
inline const float GetCurrentLife(void) {return m_fCurLife;}
inline const short GetMaxParticles(void) {return m_nMaxParticles;}
inline const short GetNumToSpit(void) {return m_nNumParticlesToSpit;}
inline const bool GetRandStartX(void) {return m_bRandStartX;}
inline const bool GetRandStartY(void) {return m_bRandStartY;}
inline const bool GetRandEndX(void) {return m_bRandEndX;}
inline const bool GetRandEndY(void) {return m_bRandEndY;}
inline const tColorF& GetStartColor(void) { return m_tStartColor;}
inline const tColorF& GetEndColor(void) { return m_tEndColor;}
inline const D3DBLEND GetSourceBlend(void) {return m_d3dSource;}
inline const D3DBLEND GetDestinationBlend(void) {return m_d3dDestination;}
inline const D3DXVECTOR2& GetStartVelocity(void) { return m_vStartVelocity;}
inline const D3DXVECTOR2& GetEndVelocity(void) { return m_vEndVelocity;}
inline const float GetStartScale(void) { return m_fStartScale;}
inline const float GetEndScale(void) { return m_fEndScale;}
inline const float GetStartRotation(void) { return m_fStartRotation;}
inline const float GetEndRotation(void) { return m_fEndRotation;}
// Mutators
inline const void SetName(const std::string szNewName) {m_szName = szNewName;}
inline const void SetRange(const RECT& rectNewRange) {m_rectRange = rectNewRange;}
inline const void SetGravityPosition(const D3DXVECTOR2& vNewPos){m_tGravityPos = D3DXVECTOR2(GetRange().left + vNewPos.x, GetRange().top + vNewPos.y);}
inline const void SetGravitationalPull(const float fNewPull) {m_fGravitationalPull = fNewPull;}
inline const void SetParticleDurationMin(const float fNewDurationMin) {m_fParticleDurationMin = fNewDurationMin;}
inline const void SetParticleDurationMax(const float fNewDurationMax) {m_fPatricleDurationMax = fNewDurationMax;}
inline const void SetLifeSpawn(const float fNewLife) {m_fLifeSpan = fNewLife;}
inline const void SetSpawnRate(const float fNewSpawnRate) {m_fSpawnRate = fNewSpawnRate;}
inline const void SetCurrentLife(const float fNewLife) {m_fCurLife = fNewLife;}
const void SetMaxParticles(const short nNewMaxParticles);
inline const void SetNumParticlesToSpit(const short nNewNumToSpit) {m_nNumParticlesToSpit = nNewNumToSpit;}
inline const void SetRandStartX(const bool bNewRandStartX) {m_bRandStartX = bNewRandStartX;}
inline const void SetRandStartY(const bool bNewRandStartY) {m_bRandStartY = bNewRandStartY;}
inline const void SetRandEndX(const bool bNewRandEndX) {m_bRandEndX = bNewRandEndX;}
inline const void SetRandEndY(const bool bNewRandEndY) {m_bRandEndY = bNewRandEndY;}
inline const void SetStartColor(const tColorF& tNewStartColor) {m_tStartColor = tNewStartColor;}
inline const void SetEndColor(const tColorF& tNewEndColor) {m_tEndColor = tNewEndColor;}
inline const void SetSourceBlend(const D3DBLEND nNewBlend) {m_d3dSource = nNewBlend;}
inline const void SetDestinationBlend(const D3DBLEND nNewBlend) {m_d3dDestination = nNewBlend;}
inline const void SetStartVelocity(const D3DXVECTOR2& vNewStartVelocity) {m_vStartVelocity = vNewStartVelocity;}
inline const void SetEndVelocity(const D3DXVECTOR2& vNewEndVelocity) {m_vEndVelocity = vNewEndVelocity;}
inline const void SetStartScale(const float fNewStartScale) {m_fStartScale = fNewStartScale;}
inline const void SetEndScale(const float fNewEndScale) {m_fEndScale = fNewEndScale;}
inline const void SetStartRotation(const float fNewStartRotation) {m_fStartRotation = fNewStartRotation;}
inline const void SetEndRotation(const float fNewEndRotation) {m_fEndRotation = fNewEndRotation;}
inline const void SetTick(const float fTick) {m_fUpdate = fTick;}
};
#endif | true |
3d61f86f3403553ba357dca7c8084c0941560bad | C++ | starsep/sik1 | /client.cpp | UTF-8 | 2,600 | 2.921875 | 3 | [] | no_license | #include "utility.h"
void usageClient(const char **argv) {
std::cerr << "Usage: " << argv[0] << " host [port]" << std::endl;
std::cerr.flush();
_exit(ExitCode::InvalidArguments);
}
std::pair<std::string, unsigned> getArguments(int argc, const char **argv) {
if (argc < 2 || argc > 3) {
std::cerr << "Bad number of arguments" << std::endl;
std::cerr.flush();
usageClient(argv);
}
std::string host = getHost(argv[1]);
if (host == INVALID_HOST) {
std::cerr << "Bad host" << std::endl;
std::cerr.flush();
usageClient(argv);
}
if (argc == 2) {
return std::make_pair(host, DEFAULT_PORT);
}
unsigned port = getPort(argv[2]);
if (port == INVALID_PORT) {
std::cerr << "Bad port number" << std::endl;
std::cerr.flush();
usageClient(argv);
}
return std::make_pair(host, port);
}
Socket connectClient(const std::string &host, unsigned port) {
addrinfo hints;
addrinfo *result;
_getaddrinfo(host.c_str(), std::to_string(port).c_str(), &hints, &result);
Socket sock =
_socket(result->ai_family, result->ai_socktype, result->ai_protocol);
_connect(sock, result->ai_addr, result->ai_addrlen);
freeaddrinfo(result);
return sock;
}
epoll_event *events;
void cleanup(ExitCode exitCode) {
delete[] events;
_exit(exitCode);
}
bool checkSocket(epoll_event &event, Socket sock) {
if (event.data.fd == sock) {
try {
std::string empty;
std::vector<std::string> msgs = receiveAll(sock, empty);
for (auto &msg : msgs) {
std::cout << msg << std::endl;
std::cout.flush();
}
} catch (BadNetworkDataException) {
std::cerr << "Incorrect data received from server. Exiting." << std::endl;
std::cerr.flush();
cleanup(ExitCode::BadData);
} catch (ClosedConnectionException) {
cleanup(ExitCode::Ok);
}
return true;
}
return false;
}
void checkStdin(Socket sock) {
std::string msg;
std::getline(std::cin, msg);
sendTo(sock, msg);
}
int main(int argc, const char **argv) {
std::pair<std::string, unsigned> p = getArguments(argc, argv);
std::string host = p.first;
unsigned port = p.second;
Socket sock = connectClient(host, port);
makeSocketNonBlocking(sock);
Epoll efd = _epoll_create();
addEpollEvent(efd, sock);
addEpollEvent(efd, STDIN);
events = new epoll_event[MAX_EVENTS_CLIENT];
while (true) {
int numberOfEvents = epoll_wait(efd, events, MAX_EVENTS_CLIENT, INFINITY);
for (int i = 0; i < numberOfEvents; i++) {
if (!checkSocket(events[i], sock)) {
checkStdin(sock);
}
}
}
} | true |
d3b3698090af8677aab5e9b65f30a02660be82e7 | C++ | sucharitha1999/Os-Project | /os project.cpp | UTF-8 | 1,297 | 2.5625 | 3 | [] | no_license | #include<stdio.h>
#include<conio.h>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
char a[10][5],temp[10];
int i,j,pt[50],wt[50],totwt=0,prt[10],temp1,n,temp2;
float avgwt;
printf("\n****************************\n");
printf("enter no of processes: ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("enter process%d name:",i+1);
scanf("%s",&a[i]);
printf("enter process time:");
scanf("%d",&pt[i]);
printf("enter priority:");
scanf("%d",&prt[i]);
}
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(prt[i]>prt[j])
{
temp1=prt[i];//the priority will be compared before arranging them in queue
prt[i]=prt[j];//first swap is for priorities
prt[j]=temp1;//second swap is for process time
temp2=pt[i];//third swap is for the proccess
pt[i]=pt[j];
pt[j]=temp2;
strcpy(temp,a[i]);
strcpy(a[i],a[j]);
strcpy(a[j],temp);
}
}
}
wt[0]=0;
for(i=1;i<n;i++)
{
wt[i]=wt[i-1]+pt[i-1];//calculating the waiting time of the proccess
totwt=totwt+wt[i];
}
avgwt=(float)totwt/n;//average of the waiting time
printf("p_name\t p_time\t priority\tw_time\n");
for(i=0;i<n;i++)
{
printf(" %s\t %d\t %d\t %d\n" ,a[i],pt[i],prt[i],wt[i]);
}
printf("total waiting time=%d\n avg waiting time=%f",totwt,avgwt);
getch();
}
| true |
cbe5a5300d3e8f20e1c075381e89e38e3154b6a4 | C++ | AdrianTanTeckKeng/RayTracingInOneWeekend | /3. Rays and camera/rays/main.cpp | UTF-8 | 1,550 | 3.453125 | 3 | [] | no_license | #include "color.h"
#include "ray.h"
#include "vec3.h"
#include <iostream>
// Simple function that returns the color of the background using a simple gradient function
color ray_color(const ray& r) {
vec3 unit_direction = unit_vector(r.direction());
// Normalize to range from 0 to 1
auto t = 0.5 * (unit_direction.y() + 1.0);
return (1.0 - t) * color(1.0, 1.0, 1.0) + t * color(0.5, 0.7, 1.0);
}
int main() {
// Set up image specifications;
const auto aspect_ratio = 16.0 / 9.0;
const int image_width = 400;
const int image_height = static_cast<int>(image_width / aspect_ratio);
// Set up camera specs
auto viewport_height = 2.0;
auto viewport_width = aspect_ratio * viewport_height;
auto focal_length = 1.0;
auto origin = point3(0, 0, 0);
auto horizontal = vec3(viewport_width, 0, 0);
auto vertical = vec3(0, viewport_height, 0);
auto lower_left_corner = origin - horizontal / 2 - vertical / 2 - vec3(0, 0, focal_length);
// Rendering image for camera
std::cout << "P3\n" << image_width << " " << image_height << "\n255\n";
for (int j = image_height - 1; j >= 0; --j) {
std::cerr << "\rScanlines remaining: " << j << ' ' << std::flush;
for (int i = 0; i < image_width; ++i) {
auto u = double(i) / (image_width - 1);
auto v = double(j) / (image_height - 1);
// Direction of ray from camera origin to the pixel on screen
ray r(origin, lower_left_corner + u * horizontal + v * vertical - origin);
color pixel_color = ray_color(r);
write_color(std::cout, pixel_color);
}
}
std::cerr << "\nDone.\n";
} | true |
8ce0d52ddf1401df9ab786b58afdf70fcd84765e | C++ | jamesavery/spiralcode-reference | /libgraph/graph.cc | UTF-8 | 15,050 | 3.328125 | 3 | [
"BSD-2-Clause",
"BSD-3-Clause"
] | permissive | #include "graph.hh"
// Returns true if edge existed prior to call, false if not
bool Graph::remove_edge(const edge_t& e)
{
node_t u = e.first, v = e.second;
vector<node_t> &nu(neighbours[u]), &nv(neighbours[v]);
bool value = false;
for(int i=0;i<nu.size();i++) if(nu[i] == v){ nu.erase(nu.begin()+i); value = true; break; }
for(int i=0;i<nv.size();i++) if(nv[i] == u){ nv.erase(nv.begin()+i); value = true; break; }
return value;
}
// Returns true if edge existed prior to call, false if not
// insert v right before suc_uv in the list of neighbours of u
// insert u right before suc_vu in the list of neighbours of v
bool Graph::insert_edge(const dedge_t& e, const node_t suc_uv, const node_t suc_vu)
{
if(edge_exists(e)) return true; // insert_edge must be idempotent
const node_t u = e.first, v = e.second;
assert(u>=0 && v>=0);
vector<node_t> &nu(neighbours[u]), &nv(neighbours[v]);
size_t oldsize[2] = {nu.size(),nv.size()};
vector<node_t>::iterator pos_uv = suc_uv<0? nu.end() : find(nu.begin(),nu.end(),suc_uv);
vector<node_t>::iterator pos_vu = suc_vu<0? nv.end() : find(nv.begin(),nv.end(),suc_vu);
nu.insert(pos_uv,v);
if(u!=v) nv.insert(pos_vu,u);
assert(nu.size() == oldsize[0]+1 && nv.size() == oldsize[1]+1);
return false;
}
bool Graph::edge_exists(const edge_t& e) const
{
const vector<node_t> &nu(neighbours[e.first]);
return find(nu.begin(),nu.end(),e.second) != nu.end();
}
// remove all vertices without edges from graph
void Graph::remove_isolated_vertices(){
vector<int> new_id(N);
int u_new = 0;
for(int u=0; u<N; u++)
if(!neighbours[u].empty())
new_id[u] = u_new++;
int N_new = u_new;
Graph g(N_new);
// cerr << "n new: " << N_new << endl;
for(int u=0; u<N; u++)
for(int v: neighbours[u])
g.neighbours[new_id[u]].push_back(new_id[v]);
*this = g;
}
// completely remove all vertices in sv from the graph
void Graph::remove_vertices(set<int> &sv){
const int N_naught(N);
for(int u: sv){
while(neighbours[u].size()){
const int v = neighbours[u][0];
remove_edge({u,v});
}
}
remove_isolated_vertices();
// let's see if the graph remained in a sane state
// cerr << "N: " << N << endl;
if(N_naught != sv.size() + N)
cerr << "removed more vertices than intended" << endl;
assert(is_connected());
}
// Successor to v in oriented neigbhours of u
node_t Graph::next(const node_t& u, const node_t& v) const
{
const vector<node_t>& nu(neighbours[u]);
for(int j=0;j<nu.size(); j++) if(nu[j] == v) return nu[(j+1)%nu.size()];
return -1; // u-v is not an edge in a triangulation
}
// Predecessor to v in oriented neigbhours of u
node_t Graph::prev(const node_t& u, const node_t& v) const
{
const vector<node_t>& nu(neighbours[u]);
for(int j=0;j<nu.size(); j++) if(nu[j] == v) return nu[(j-1+nu.size())%nu.size()];
return -1; // u-v is not an edge in a triangulation
}
// Successor to v in face containing directed edge u->v
node_t Graph::next_on_face(const node_t &u, const node_t &v) const
{
return prev(v,u);
}
// Predecessor to v in face containing directed edge u->v
node_t Graph::prev_on_face(const node_t &u, const node_t &v) const
{
return prev(u,v);
}
// TODO: Seems to not work
bool Graph::is_consistently_oriented() const
{
map<dedge_t,bool> seen_dedge;
set<dedge_t> work;
for(node_t u=0;u<N;u++)
for(auto v: neighbours[u])
work.insert({u,v});
while(!work.empty()){
const dedge_t e = *work.begin();
node_t u(e.first), v(e.second);
// Process CW face starting in u->v
const node_t u0 = u;
work.erase(dedge_t(u,v));
while(v != u0){
node_t w = next(v,u); // u--v--w is CW-most corner
u = v;
v = w;
if(work.find(dedge_t(u,v)) == work.end()){ // We have already processed arc u->v
// cerr << "Directed edge " << dedge_t(u,v) << " is part of two faces.\n";
return false;
}
work.erase(dedge_t(u,v));
}
}
// Every directed edge is part of exactly one face <-> orientation is consistent
return true;
}
// TODO: Doesn't need to be planar and oriented, but is easier to write if it is. Make it work in general.
bool Graph::has_separating_triangles() const
{
assert(is_oriented);
for(node_t u=0;u<N;u++){
const vector<node_t> &nu(neighbours[u]);
for(int i=0;i<nu.size();i++){
node_t t = nu[i];
node_t v = prev(u,t), w = next(u,t); // edges: u--t, u--v, u--w
if(edge_exists({t,w}) && edge_exists({t,v}) && edge_exists({v,w})) return true;
}
}
return false;
}
bool Graph::adjacency_is_symmetric() const
{
for(node_t u=0;u<N;u++){
const vector<node_t> &nu = neighbours[u];
for(int i=0;i<nu.size();i++){
const vector<node_t> &nv = neighbours[nu[i]];
bool symmetric = false;
for(int j=0;j<nv.size();j++) if(nv[j] == u) symmetric = true;
if(!symmetric) return false;
}
}
return true;
}
// TODO: Should make two functions: one that takes subgraph (empty is trivially connected) and one that works on full graph.
bool Graph::is_connected(const set<node_t> &subgraph) const
{
if(!subgraph.empty()){
node_t s = *subgraph.begin();
const vector<int> dist(shortest_paths(s));
for(set<node_t>::const_iterator u(subgraph.begin()); u!=subgraph.end();u++)
if(dist[*u] == INT_MAX) return false;
} else {
node_t s = 0; // Pick a node that is part of an edge
for(;neighbours[s].empty();s++) ;
assert(s < N);
const vector<int> dist(shortest_paths(s));
for(int i=0;i<dist.size();i++)
if(dist[i] == INT_MAX) return false;
}
return true;
}
list< list<node_t> > Graph::connected_components() const
{
vector<bool> done(N);
list<list<node_t> > components;
for(node_t u=0;u<N;u++)
if(!done[u]){
list<node_t> component;
done[u] = true;
component.push_back(u);
list<node_t> q(neighbours[u].begin(),neighbours[u].end());
while(!q.empty()){
node_t v = q.back(); q.pop_back(); done[v] = true;
component.push_back(v);
for(int i=0;i<neighbours[v].size();i++) if(!done[neighbours[v][i]]) q.push_back(neighbours[v][i]);
}
components.push_back(component);
}
return components;
}
vector<int> Graph::shortest_path(const node_t& source, const node_t& dest, const vector<int>& dist) const
{
// Fill in shortest paths -- move to own function.
node_t vi = source;
vector<node_t> path;
// fprintf(stderr,"Shortest path %d -> %d\n",source,dest);
for(int i=0;i<N;i++)
// fprintf(stderr,"%d: %d\n",i,dist[i]);
do {
path.push_back(vi);
const vector<node_t>& ns(neighbours[vi]);
// Find next vertex in shortest path
int kmin = 0;
for(int k=1, d=dist[ns[0]];k<ns.size();k++) {
// fprintf(stderr,"node %d has distance %d\n",ns[k],dist[ns[k]]);
if(dist[ns[k]] < d){
d = dist[ns[k]];
kmin = k;
}
}
// fprintf(stderr,"Choosing neighbour %d = %d\n",kmin,ns[kmin]);
vi = ns[kmin];
} while(vi != dest);
// cerr << face_t(path) << endl;
return path;
}
vector<int> Graph::shortest_paths(const node_t& source, const vector<bool>& used_edges,
const vector<bool>& used_nodes, const unsigned int max_depth) const
{
vector<int> distances(N,INT_MAX);
list<node_t> queue;
distances[source] = 0;
queue.push_back(source);
while(!queue.empty()){
node_t v = queue.front(); queue.pop_front();
const vector<node_t> &ns(neighbours[v]);
for(unsigned int i=0;i<ns.size();i++){
const edge_t edge(v,ns[i]);
if(!used_nodes[ns[i]] && !used_edges[edge.index()] && distances[ns[i]] == INT_MAX){
distances[ns[i]] = distances[v] + 1;
if(distances[ns[i]] < max_depth) queue.push_back(ns[i]);
}
}
}
return distances;
}
vector<int> Graph::shortest_paths(const node_t& source, const unsigned int max_depth) const
{
vector<int> distances(N,INT_MAX);
list<node_t> queue;
distances[source] = 0;
queue.push_back(source);
while(!queue.empty()){
node_t v = queue.front(); queue.pop_front();
const vector<node_t> &ns(neighbours[v]);
for(unsigned int i=0;i<ns.size();i++){
const edge_t edge(v,ns[i]);
if(distances[ns[i]] == INT_MAX){
distances[ns[i]] = distances[v] + 1;
if(distances[ns[i]] < max_depth) queue.push_back(ns[i]);
}
}
}
return distances;
}
// Returns NxN matrix of shortest distances (or INT_MAX if not connected)
vector<int> Graph::all_pairs_shortest_paths(const unsigned int max_depth) const
{
vector<int> distances(N*N);
vector<bool> dummy_edges(N*(N-1)/2), dummy_nodes(N);
for(node_t u=0;u<N;u++){
const vector<int> row(shortest_paths(u,dummy_edges,dummy_nodes,max_depth));
memcpy(&distances[u*N],&row[0],N*sizeof(unsigned int));
}
return distances;
}
vector<node_t> Graph::shortest_cycle(const node_t& s, const int max_depth) const
{
const vector<node_t> ns(neighbours[s]);
assert(ns.size() > 0);
face_t cycle;
int Lmax = 0;
for(int i=0;i<ns.size();i++){
face_t c(shortest_cycle(s,ns[i],max_depth));
if(c.size() >= Lmax){ Lmax = c.size(); cycle = c; }
}
return cycle;
}
vector<node_t> Graph::shortest_cycle(const node_t& s, const node_t& t, const int max_depth) const
{
vector<bool> used_edges(N*(N-1)/2);
vector<bool> used_nodes(N);
// Find shortest path t->s in G excluding edge (s,t)
used_edges[edge_t(s,t).index()] = true;
vector<int> distances(shortest_paths(t,used_edges,used_nodes,max_depth));
// If distances[s] is uninitialized, we have failed to reach s and there is no cycle <= max_depth.
if(distances[s] == INT_MAX) return vector<node_t>();
// Then reconstruct the cycle by moving backwards from s to t
vector<node_t> cycle(distances[s]+1);
node_t u = s, v = -1;
for(unsigned int i=0;i<distances[s]+1;i++){
const vector<node_t> &ns(neighbours[u]);
unsigned int dmin = INT_MAX;
for(unsigned int j=0;j<ns.size();j++)
if(distances[ns[j]] < dmin && (edge_t(u,ns[j]) != edge_t(s,t))){
dmin = distances[ns[j]];
v = ns[j];
}
u = v;
cycle[distances[s]-i] = u;
}
cycle[0] = s;
return cycle;
}
vector<node_t> Graph::shortest_cycle(const node_t& s, const node_t& t, const node_t& r, const int max_depth) const
{
// fprintf(stderr,"3: shortest_cycle(%d,%d,%d,max_depth=%d)\n",s,t,r,max_depth);
assert(s >= 0 && t >= 0 && r >= 0);
if(max_depth == 3){ // Triangles need special handling
vector<node_t> cycle(3);
node_t p=-1,q=-1;
cycle[0] = s;
for(int i=0;i<neighbours[s].size();i++) {
if(neighbours[s][i] == t){ p = t; q = r; break; }
if(neighbours[s][i] == r){ p = r; q = t; break; }
}
bool foundq = false, founds = false;
if(p<0) return vector<node_t>();
for(int i=0;i<neighbours[p].size();i++) if(neighbours[p][i] == q) foundq = true;
for(int i=0;i<neighbours[q].size();i++) if(neighbours[q][i] == s) founds = true;
if(!foundq || !founds) return vector<node_t>();
cycle[1] = p;
cycle[2] = q;
return cycle;
}
vector<bool> used_edges(N*(N-1)/2);
vector<bool> used_nodes(N);
// fprintf(stderr,"shortest_cycle(%d,%d,%d), depth = %d\n",s,t,r,max_depth);
// Find shortest path r->s in G excluding edge (s,t), (t,r)
used_edges[edge_t(s,t).index()] = true;
used_edges[edge_t(t,r).index()] = true;
vector<int> distances(shortest_paths(r,used_edges,used_nodes,max_depth));
// If distances[s] is uninitialized, we have failed to reach s and there is no cycle <= max_depth.
if(distances[s] == INT_MAX) return vector<node_t>();
// Else reconstruct the cycle by moving backwards from s to t
vector<node_t> cycle(distances[s]+2);
node_t u = s, v = -1;
for(unsigned int i=0;i<distances[s]+1;i++){
const vector<node_t> &ns(neighbours[u]);
unsigned int dmin = INT_MAX;
for(unsigned int j=0;j<ns.size();j++)
if(distances[ns[j]] < dmin && (edge_t(u,ns[j]) != edge_t(s,t))){
dmin = distances[ns[j]];
v = ns[j];
}
u = v;
cycle[distances[s]+1-i] = u;
}
cycle[0] = s;
cycle[1] = t;
return cycle;
}
vector<int> Graph::multiple_source_shortest_paths(const vector<node_t>& sources, const vector<bool>& used_edges,
const vector<bool>& used_nodes, const unsigned int max_depth) const
{
vector<int> distances(N,INT_MAX);
list<node_t> queue;
for(unsigned int i=0;i<sources.size();i++){
distances[sources[i]] = 0;
queue.push_back(sources[i]);
}
while(!queue.empty()){
node_t v = queue.front(); queue.pop_front();
const vector<node_t> &ns(neighbours[v]);
for(unsigned int i=0;i<ns.size();i++){
const edge_t edge(v,ns[i]);
if(!used_nodes[ns[i]] && !used_edges[edge.index()] && distances[ns[i]] == INT_MAX){
distances[ns[i]] = distances[v] + 1;
if(distances[ns[i]] < max_depth) queue.push_back(ns[i]);
}
}
}
return distances;
}
vector<int> Graph::multiple_source_shortest_paths(const vector<node_t>& sources, const unsigned int max_depth) const
{
return multiple_source_shortest_paths(sources,vector<bool>(N*(N-1)/2),vector<bool>(N),max_depth);
}
int Graph::max_degree() const
{
int max_d = 0;
for(node_t u=0;u<N;u++) if(neighbours[u].size() > max_d) max_d = neighbours[u].size();
return max_d;
}
int Graph::degree(const node_t& u) const {
return neighbours[u].size();
}
void Graph::update_from_edgeset(const set<edge_t>& edge_set)
{
// Instantiate auxiliary data strutures: sparse adjacency matrix and edge existence map.
map<node_t,set<node_t> > ns;
// fprintf(stderr,"Initializing edge map.\n");
// Update node count
N = 0;
for(set<edge_t>::const_iterator e(edge_set.begin()); e!= edge_set.end(); e++){
N = max(N,max(e->first,e->second)+1);
}
neighbours.resize(N);
for(set<edge_t>::const_iterator e(edge_set.begin()); e!= edge_set.end(); e++){
ns[e->first].insert(e->second);
ns[e->second].insert(e->first);
}
// fprintf(stderr,"Initializing adjacencies\n");
for(int u=0;u<N;u++)
neighbours[u] = vector<node_t>(ns[u].begin(),ns[u].end());
}
set<edge_t> Graph::undirected_edges() const {
set<edge_t> edges;
for(node_t u=0;u<N;u++)
for(int i=0;i<neighbours[u].size();i++)
edges.insert(edge_t(u,neighbours[u][i]));
return edges;
}
set<dedge_t> Graph::directed_edges() const {
set<dedge_t> edges;
for(node_t u=0;u<N;u++)
for(int i=0;i<neighbours[u].size();i++)
edges.insert(dedge_t(u,neighbours[u][i]));
return edges;
}
size_t Graph::count_edges() const {
// Don't use edge_set -- it's slow
size_t twoE = 0;
for(node_t u=0;u<N;u++)
twoE += neighbours[u].size();
return twoE/2;
}
ostream& operator<<(ostream& s, const Graph& g)
{
set<edge_t> edge_set = g.undirected_edges();
s << "Graph[Range["<<(g.N)<<"],\n\tUndirectedEdge@@#&/@{";
for(set<edge_t>::const_iterator e(edge_set.begin()); e!=edge_set.end(); ){
s << "{" << (e->first+1) << "," << (e->second+1) << "}";
if(++e != edge_set.end())
s << ", ";
}
s << "}]";
return s;
}
| true |
2207f93b3ef5fd0ef185319294560db3838dc62f | C++ | Diesmaster/boom | /beeldbuffer.cc | UTF-8 | 2,267 | 3.078125 | 3 | [] | no_license | //============================================================================
// Name : beeldbuffer.cc
//
// Dit file bevat de implementatie van de klasse beeldbuffer
// Deze klasse wordt gebruikt om een beeldschermweergave op te bouwen alvorens deze weer te geven.
//
// Behorend bij het bomenpracticum van het college Algoritmiek binnen de studie
// Informatica (en Economie). De student wordt geacht een aantal
// member functies van de klasse `binaireboom' uit te werken.
// Er staan al skeletten van deze functies in dit file.
//
// Auteur: Jeroen Laros
// Aangepast door: Tijn Witsenburg
// Verder aangepast door: Rudy van Vliet, 15 februari 2011 / 6 februari 2012
// Verder aangepast door: Erik Massop en Rudy van Vliet, 14/15/19 februari 2013
// Aangepast door : Nelleke Louwe Kooijmans, 21 januari 2015
//============================================================================
#include <iostream> // Gebruikt voor cout.
#include "beeldbuffer.h"
using namespace std;
beeldbuffer::beeldbuffer( int width, int height ) {
if (width > 0 && width < this->MAXWIDTH )
this->width = width;
else
this->width = 80;
if ( height > 0 && height < this->MAXHEIGHT )
this->height = height;
else
this->width = 80;
reset();
}
beeldbuffer::~beeldbuffer() {
// TODO Auto-generated destructor stub
}
int beeldbuffer::getWidth() {
return width;
}
void beeldbuffer::set( int x, int y, char value ) {
if ( ( x >= 0 ) && ( x < width ) && ( y >= 0 ) && ( y < height ) )
buffer[ x ][ y ] = value;
}
// Teken een horizontaal streepje in de buffer array.
// Argumenten: int xb ; x-coordinaat van het begin van het streepje.
// int xe ; x-coordinaat van het eind van het streepje.
// int y ; y-coordinaat van het streepje.
//
// Globale veranderingen: De array buffer[][] wordt veranderd.
//
// Notitie: Werkt alleen voor xb <= xe.
//
void beeldbuffer::horline(int xb, int xe, int y) {
int x;
buffer[xb][y] = '+';
for (x = xb + 1; x < xe; x++)
buffer[x][y] = '-';
buffer[xe][y] = '+';
}
void beeldbuffer::reset() {
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++)
buffer[x][y] = ' ';
}
void beeldbuffer::drukaf() {
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++)
cout << buffer[x][y];
cout << endl;
}
}
| true |
4ddcc19c2b4016a3fd6161a78031f93a1a98f4a3 | C++ | yuchengmao/learn-cpp | /myCode/设计模式/基本原则/开闭原则.cpp | UTF-8 | 1,713 | 3.578125 | 4 | [] | no_license | /**
* @file 开闭原则.cpp
* @author your name (you@domain.com)
* @brief
* @version 0.1
* @date 2021-06-28
*
* @copyright Copyright (c) 2021
*
* 添加新方法只需要增加代码而不需要修改
*/
#include <iostream>
using namespace std;
class AbstractCalculator
{
public:
virtual int getResult(int a, int b) = 0;
protected:
int mA, mB;
};
class Plus : public AbstractCalculator
{
public:
virtual int getResult(int a, int b)
{
this->mA = a;
this->mB = b;
cout << a << " + " << b
<< " = " << mA + mB
<< endl;
return mA + mB;
}
};
class Subtration : public AbstractCalculator
{
public:
virtual int getResult(int a, int b)
{
this->mA = a;
this->mB = b;
cout << a << " - " << b
<< " = " << mA - mB
<< endl;
return mA - mB;
}
};
class Multiply : public AbstractCalculator
{
public:
virtual int getResult(int a, int b)
{
this->mA = a;
this->mB = b;
cout << a << " * " << b
<< " = " << mA * mB
<< endl;
return mA * mB;
}
};
class Division : public AbstractCalculator
{
public:
virtual int getResult(int a, int b)
{
this->mA = a;
this->mB = b;
cout << a << " / " << b
<< " = " << mA / mB
<< endl;
return mA / mB;
}
};
int main()
{
AbstractCalculator *plus = new Plus;
plus->getResult(1, 2);
AbstractCalculator *sub = new Subtration;
sub->getResult(1, 2);
AbstractCalculator *mul = new Multiply;
mul->getResult(1, 2);
AbstractCalculator *div = new Division;
div->getResult(1, 2);
} | true |
dfae538f7e9d81a1a07a90a6ada92591de4aa76f | C++ | luk1684tw/Work-Collections | /資結final/final/UBikeHeapIMP.cpp | UTF-8 | 1,309 | 3.171875 | 3 | [] | no_license | #include "UBikeHeapIMP.h"
void UBikeHeapIMP::swap(const int a, const int b)
{
std::swap((*this)[a], (*this)[b]);
(*this)[a]->heapIndex = a;
(*this)[b]->heapIndex = b;
}
void UBikeHeapIMP::sift_up(int i)
{
while (i>1 && (*this)[i/2]->mileage > (*this)[i]->mileage) {
this->swap(i/2, i);
i /= 2;
}
}
void UBikeHeapIMP::sift_down(int i)
{
while (true) {
int cur = (*this)[i]->mileage;
int l = (2*i <= this->number) ? (*this)[2*i] ->mileage
: cur+1;
int r = (2*i+1 <= this->number) ? (*this)[2*i+1]->mileage
: cur+1;
if (cur <= l && cur <= r) return;
if (l <= r) {
this->swap(2*i, i);
i = 2*i;
} else {
this->swap(2*i+1, i);
i = 2*i+1;
}
}
}
void UBikeHeapIMP::addUBikePtr(UBike* ubptr)
{
(*this)[++number] = ubptr;
ubptr->heapIndex = number;
sift_up(number);
}
UBike* UBikeHeapIMP::removeUBikePtr(int heapIndex)
{
if (heapIndex > this->number) return nullptr;
auto retval = (*this)[heapIndex];
(*this)[heapIndex] = (*this)[number--];
(*this)[heapIndex]->heapIndex = heapIndex;
sift_up(heapIndex);
sift_down(heapIndex);
return retval;
}
| true |
740052410e5e2dce9022d0ac01d2009cad73d157 | C++ | LanguidCat/BaekJoon | /10814-나이순_정렬/10814.cpp | UTF-8 | 664 | 2.84375 | 3 | [] | no_license | #include <iostream>
#include <utility>
#include <vector>
#include <string>
#include <algorithm>
#define endl '\n'
using namespace std;
int main(){
cin.tie(NULL);
ios_base::sync_with_stdio(false);
//first.first = 나이, first.second = 순서, second = 이름
vector< pair< pair< int, int >, string > > v;
int N, num = 0;
cin >> N;
for(int i = 0; i < N; i++){
int age;
string name;
num++;
cin >> age >> name;
v.push_back(make_pair(make_pair(age, num), name));
}
sort(v.begin(), v.end());
for(int i = 0; i < N; i++){
cout << v[i].first.first << ' ' << v[i].second << endl;
}
return 0;
}
| true |
f73f198728a810e5c23afa50c614aa75d984f3aa | C++ | khanhtc1202/cp | /educative/count.cpp | UTF-8 | 376 | 3.25 | 3 | [] | no_license | #include <iostream>
using namespace std;
template <class T>
class Score
{
private:
T value;
public:
static int counter;
Score() {counter++;}
};
template<class T>
int Score<T>::counter = 0;
int main()
{
Score<int> x;
Score<int> y;
Score<double> z;
cout << Score<int>::counter<< endl;
cout << Score<double>::counter<< endl;
return 0;
}
| true |
9c69a559674eaedb6a753de52260cea4c24db439 | C++ | B3njym1n/leetcode | /leetcode973/main.cpp | UTF-8 | 724 | 2.9375 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<vector<int>> kClosest(vector<vector<int>>& points, int k) {
nth_element(begin(points), begin(points) + k - 1, end(points), [](const vector<int>& p1, const vector<int>& p2) {
return p1[0] * p1[0] + p1[1] * p1[1] < p2[0] * p2[0] + p2[1]*p2[1];
});
return {begin(points), begin(points) + k};
}
};
int main()
{
// vector<vector<int>> points {{1,3},{-2,-2}};
// int k = 1;
vector<vector<int>> points {{3,3},{5,-1},{-2,4}};
int k = 2;
Solution s;
auto ans = s.kClosest(points, k);
for (auto p : ans) {
cout << p[0] << ',' << p[1] << '\n';
}
return 0;
} | true |
6ad4476218cdfdf04078a00b6d2ecfb24c5025fd | C++ | piotrmoszkowicz-wfiis/WFiIS-PO-2019 | /LATO19_GR6_WK8_MOSZKOWICZ/lab08.h | UTF-8 | 1,678 | 3.453125 | 3 | [] | no_license | #pragma once
#include <iostream>
#include <string>
class ObiektMiotajacy {
public:
ObiektMiotajacy() {}
void Rzuc() const;
};
class ExceptTypeBoilerPlate {
public:
ExceptTypeBoilerPlate(const std::string& name, const ObiektMiotajacy* obiektMiotajacy) : m_name(name), m_obiektMiotajacy(obiektMiotajacy) {}
~ExceptTypeBoilerPlate() {
delete m_obiektMiotajacy;
}
void PrzedstawSie() const {
std::cout << "Nazywam sie " << m_name << std::endl;
}
std::string getName() const {
return m_name;
}
protected:
std::string m_name;
const ObiektMiotajacy* m_obiektMiotajacy;
};
class ExceptType1 : public ExceptTypeBoilerPlate {
public:
ExceptType1(const ObiektMiotajacy* obiektMiotajacy = nullptr, std::string name = "Except1") : ExceptTypeBoilerPlate(name, obiektMiotajacy) {}
};
class ExceptType2 : public ExceptTypeBoilerPlate {
public:
ExceptType2(const ObiektMiotajacy* obiektMiotajacy = nullptr, std::string name = "Except2") : ExceptTypeBoilerPlate(name, obiektMiotajacy) {}
};
class ExceptType3 : public ExceptType1 {
public:
ExceptType3(const ObiektMiotajacy* obiektMiotajacy = nullptr) : ExceptType1(obiektMiotajacy, "Except3") {}
};
class ExceptType4 : public ExceptType2 {
public:
ExceptType4(const ObiektMiotajacy* obiektMiotajacy = nullptr) : ExceptType2(obiektMiotajacy, "Except4") {}
};
inline void HandleExcept(ExceptType1* exception) {
std::cout << "Przetworz wyjatek Except1 o adresie: " << exception << std::endl;
throw;
}
inline void HandleExcept(ExceptType2* exception) {
std::cout << "Przetworz wyjatek Except2 o adresie: " << exception << std::endl;
throw;
} | true |
57269d53b141d6d9466035036f685d47165e90de | C++ | ngvozdiev/ncode-common | /src/ptr_queue_test.cc | UTF-8 | 6,627 | 3.078125 | 3 | [
"MIT"
] | permissive | #include <atomic>
#include <thread>
#include <map>
#include "gtest/gtest.h"
#include "ptr_queue.h"
namespace nc {
namespace {
template <typename T>
void Unused(T&&) {}
TEST(SmallQueue, Empty) {
PtrQueue<int, 2> small_queue;
ASSERT_EQ(0ul, small_queue.size());
}
TEST(SmallQueue, ProduceAfterClose) {
PtrQueue<int, 2> small_queue;
small_queue.Close();
// Producing a value after close should be a no-op.
ASSERT_FALSE(small_queue.ProduceOrBlock(make_unique<int>(1)));
ASSERT_EQ(0ul, small_queue.size());
}
TEST(SmallQueue, ConsumeAfterClose) {
PtrQueue<int, 2> small_queue;
small_queue.Close();
ASSERT_FALSE(small_queue.ConsumeOrBlock().get());
ASSERT_EQ(0ul, small_queue.size());
}
TEST(SmallQueue, ProduceConsumeOne) {
PtrQueue<int, 2> small_queue;
small_queue.ProduceOrBlock(make_unique<int>(1));
ASSERT_EQ(1ul, small_queue.size());
auto result = small_queue.ConsumeOrBlock();
ASSERT_EQ(1, *result);
ASSERT_EQ(0ul, small_queue.size());
}
TEST(SmallQueue, ProduceConsumeTwo) {
PtrQueue<int, 2> small_queue;
small_queue.ProduceOrBlock(make_unique<int>(1));
small_queue.ProduceOrBlock(make_unique<int>(2));
ASSERT_EQ(2ul, small_queue.size());
auto result_one = small_queue.ConsumeOrBlock();
auto result_two = small_queue.ConsumeOrBlock();
ASSERT_EQ(1, *result_one);
ASSERT_EQ(2, *result_two);
ASSERT_EQ(0ul, small_queue.size());
}
TEST(SmallQueue, ProduceConsumeSeq) {
PtrQueue<int, 2> small_queue;
for (int i = 1; i <= 10000; i++) {
small_queue.ProduceOrBlock(make_unique<int>(i));
if (i % 2 == 0) {
auto result_one = small_queue.ConsumeOrBlock();
auto result_two = small_queue.ConsumeOrBlock();
ASSERT_EQ(i - 1, *result_one);
ASSERT_EQ(i, *result_two);
}
}
ASSERT_EQ(0ul, small_queue.size());
}
TEST(SmallQueue, DrainQueue) {
PtrQueue<int, 2> small_queue;
small_queue.ProduceOrBlock(make_unique<int>(1));
small_queue.ProduceOrBlock(make_unique<int>(2));
std::vector<std::unique_ptr<int>> contents = small_queue.Drain();
ASSERT_EQ(2ul, contents.size());
ASSERT_EQ(1, *contents.front());
ASSERT_EQ(2, *contents.back());
ASSERT_EQ(0ul, small_queue.size());
}
TEST(SmallQueue, ProduceInvalidateConsume) {
PtrQueue<int, 4> small_queue;
small_queue.ProduceOrBlock(make_unique<int>(1));
small_queue.ProduceOrBlock(make_unique<int>(2));
small_queue.ProduceOrBlock(make_unique<int>(3));
small_queue.Invalidate([](const int& value) { return value == 1; });
small_queue.Invalidate([](const int& value) { return value == 2; });
auto result = small_queue.ConsumeOrBlock();
ASSERT_EQ(3, *result);
ASSERT_EQ(0ul, small_queue.size());
}
TEST(SmallQueue, EmptyTimeout) {
PtrQueue<int, 2> small_queue;
bool timed_out;
auto result = small_queue.ConsumeOrBlockWithTimeout(
std::chrono::milliseconds(500), &timed_out);
ASSERT_FALSE(result);
ASSERT_TRUE(timed_out);
}
TEST(SmallQueue, FullTimeout) {
PtrQueue<int, 2> small_queue;
ASSERT_TRUE(small_queue.ProduceOrBlock(make_unique<int>(1)));
ASSERT_TRUE(small_queue.ProduceOrBlock(make_unique<int>(2)));
bool timed_out;
ASSERT_FALSE(small_queue.ProduceOrBlockWithTimeout(
make_unique<int>(3), std::chrono::milliseconds(500), &timed_out));
ASSERT_TRUE(timed_out);
}
TEST(SmallQueue, ProduceKill) {
PtrQueue<int, 2> small_queue;
std::thread thread([&small_queue] {
std::this_thread::sleep_for(std::chrono::milliseconds(500));
small_queue.Close();
});
small_queue.ProduceOrBlock(make_unique<int>(1));
small_queue.ProduceOrBlock(make_unique<int>(2));
thread.join();
// There are still two elements in the queue
ASSERT_EQ(2ul, small_queue.size());
}
TEST(SmallQueue, ConsumeKill) {
PtrQueue<int, 2> small_queue;
std::thread thread([&small_queue] {
std::this_thread::sleep_for(std::chrono::milliseconds(500));
small_queue.Close();
});
// should block until the queue is closed.
auto result = small_queue.ConsumeOrBlock();
thread.join();
ASSERT_FALSE(result);
ASSERT_EQ(0ul, small_queue.size());
}
TEST(SmallQueue, InvalidateAllKill) {
PtrQueue<int, 2> small_queue;
std::thread thread([&small_queue] {
std::this_thread::sleep_for(std::chrono::milliseconds(500));
small_queue.Close();
});
small_queue.ProduceOrBlock(make_unique<int>(1));
small_queue.ProduceOrBlock(make_unique<int>(2));
small_queue.Invalidate([](const int& value) {
Unused(value);
return true;
});
auto result = small_queue.ConsumeOrBlock(); // will block until closed
thread.join();
ASSERT_FALSE(result);
ASSERT_EQ(0ul, small_queue.size());
}
TEST(LargeQueue, MultiProducer) {
auto large_queue = make_unique<PtrQueue<int, 1 << 20>>();
std::vector<std::thread> threads;
for (size_t thread_num = 0; thread_num < 16; thread_num++) {
threads.push_back(std::thread([&large_queue] {
for (size_t count = 0; count < ((1 << 20) / 16); count++) {
large_queue->ProduceOrBlock(make_unique<int>(count));
}
}));
}
for (auto& thread : threads) {
thread.join();
}
ASSERT_EQ(1ul << 20ul, large_queue->size());
std::map<int, int> model;
for (size_t count = 0; count < (1 << 20); count++) {
auto result = large_queue->ConsumeOrBlock();
int value = *result;
model[value] += 1;
}
for (size_t count = 0; count < (1 << 20) / 16; count++) {
ASSERT_EQ(model[count], 16);
}
ASSERT_EQ(0ul, large_queue->size());
}
TEST(LargeQueue, MultiProducerMultiConsumer) {
auto large_queue = make_unique<PtrQueue<uint64_t, 1 << 12>>();
std::vector<std::thread> producer_threads;
std::vector<std::thread> consumer_threads;
for (size_t thread_num = 0; thread_num < 16; thread_num++) {
producer_threads.push_back(std::thread([&large_queue] {
for (size_t count = 0; count < ((1 << 20) / 16); count++) {
large_queue->ProduceOrBlock(make_unique<uint64_t>(count));
}
}));
}
std::atomic<uint64_t> sum(0);
for (size_t thread_num = 0; thread_num < 16; thread_num++) {
consumer_threads.push_back(std::thread([&large_queue, &sum] {
for (size_t count = 0; count < ((1 << 20) / 16); count++) {
auto result = large_queue->ConsumeOrBlock();
std::atomic_fetch_add(&sum, (*result));
}
}));
}
for (auto& thread : producer_threads) {
thread.join();
}
for (auto& thread : consumer_threads) {
thread.join();
}
// n * (n - 1) / 2 for each of the 16 threads
ASSERT_EQ((((1 << 20ul) / 16ul) * (((1 << 20ul) / 16ul) - 1)) * 8ul, sum);
ASSERT_EQ(0ul, large_queue->size());
}
} // namespace
} // namespace nc
| true |
e3938a6a5e47e8a96f732b1502fc237b9b14df0c | C++ | arnoldruiz115/Edit-Distance-Calculator | /distcalc.cpp | UTF-8 | 2,300 | 3.375 | 3 | [
"MIT"
] | permissive | #include "distcalc.h"
#include <algorithm>
#include <iomanip>
void eDistance(string w1, string w2){
//get row and column size for matrix
int rows = w1.size() + 1;
int cols = w2.size() + 1;
//dynamically allocate matrix
int** eMatrix = new int*[rows];
for (int i = 0; i < rows; ++i){
eMatrix[i] = new int[cols];
}
//Fill in base values
eMatrix[0][0] = 0;
for (int i = 1; i < rows; ++i){
eMatrix[i][0] = i;
}
for (int i = 1; i < cols; ++i){
eMatrix[0][i] = i;
}
//adding one character to both words to match table
string word1 = "-" + w1;
string word2 = "-" + w2;
//Fill in matrix
for(int i = 1; i < rows; ++i){
for(int j = 1; j < cols; ++j){
if(word1[i]==word2[j]){
eMatrix[i][j] = eMatrix[i-1][j-1];
}
else{
eMatrix[i][j] = min({eMatrix[i-1][j-1],
eMatrix[i][j-1], eMatrix[i-1][j]})+1;
}
}
}
//Display the matrix
cout << "Matrix: \n";
string temp1 = "-" + w1;
string temp2 = " -" + w2;
for(int i = 0; i < cols+1; ++i){
cout << setw(2) << left << temp2[i] << " | ";
}
for(int i = 0; i < rows; ++i){
cout << endl;
cout << setw(2) << left << temp1[i] << " | ";
for(int j = 0; j < cols; ++j)
cout << setw(2) << left << eMatrix[i][j] << " | ";
}
cout << endl;
cout << "\nEdit distance is: " << eMatrix[rows-1][cols-1] << endl;
//Finding Alignment
int i = rows-1;
int j = cols-1;
int tempMin, diag, top, left;
bool diagMin = false;
string align1 = "";
string align2 = "";
while((i != 0) || (j != 0)){
//in case traversal is along the edge, dont check out of bounds
if(j == 0){diag = 999; left = 999;}
else if(i == 0){diag = 999; top = 999;}
else{
diag = eMatrix[i-1][j-1];
top = eMatrix[i-1][j];
left = eMatrix[i][j-1];
}
tempMin = min({diag, top, left});
if(tempMin == diag){
diagMin = true;
//Diagonal is Minimum
align1 += word1[i];
align2 += word2[j];
i--;
j--;
}
if(!diagMin){
if(tempMin == top) {
//top is minimum
align1 += word1[i];
align2 += "_";
i--;
}
else{
//left is minimum
align2 += word2[j];
align1 += '_';
j--;
}
}
diagMin = false;
}
reverse(align1.begin(), align1.end());
reverse(align2.begin(), align2.end());
cout << "\nAlignment: \n" << align1 << endl << align2 << endl;
}
| true |
ec18eaaf7eafa36c34ac76fd50e6ef33b76531d4 | C++ | arjun-khanduri/CG-Lab-Programs | /Lab8/main.cpp | UTF-8 | 3,278 | 2.734375 | 3 | [] | no_license | #include<stdio.h>
#include<GL/gl.h>
#include<GL/glu.h>
#include<GL/glut.h>
float x1, y1, x2, y2;
float xmin = 50, ymin = 50, xmax = 100, ymax = 100;
const int RIGHT = 8, LEFT = 2, TOP = 4, BOTTOM = 1;
int code0, code1, codeout;
int compute(float x, float y){
int code = 0;
if(x < xmin)
code |= LEFT;
else if(x > xmax)
code |= RIGHT;
if(y < ymin)
code |= BOTTOM;
else if(y > ymax)
code |= TOP;
return code;
}
void cohen(float x1, float y1, float x2, float y2){
bool done = false, accept = false;
code0 = compute(x1, y1);
code1 = compute(x2, y2);
float x, y;
do{
//printf("%d %d\n", code0, code1);
if((code0 | code1) == 0){
done = true;
accept = true;
}
else if(code0 & code1)
done = true;
else{
if(code0)
codeout = code0;
else
codeout = code0 ? code0 : code1;
if(codeout & BOTTOM){
y = ymin;
x = x1 + ((x2 - x1) / (y2 - y1)) * (ymin - y1);
}
else if(codeout & TOP){
y = ymax;
x = x1 + ((x2 - x1) / (y2 - y1)) * (ymax - y1);
}
else if(codeout & LEFT){
x = xmin;
y = y1 + ((y2 - y1) / (x2 - x1)) * (xmin - x1);
}
else{
x = xmax;
y = y1 + ((y2 - y1) / (x2 - x1)) * (xmax - x1);
}
if(codeout == code0){
x1 = x;
y1 = y;
code0 = compute(x1, y1);
}
if(codeout == code1){
x2 = x;
y2 = y;
code1 = compute(x2, y2);
}
}
}while(!done);
if(accept){
glTranslatef(100,100,0);
glColor3f(1.0,0.0,0.0);
glBegin(GL_LINE_LOOP);
glVertex2i(xmin, ymin);
glVertex2i(xmax, ymin);
glVertex2i(xmax, ymax);
glVertex2i(xmin, ymax);
glEnd();
glColor3f(0.0,1.0,0.0);
glBegin(GL_LINES);
glVertex2i(x1, y1);
glVertex2i(x2, y2);
glEnd();
}
}
void display(){
glClearColor(1,1,1,1);
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0,0.0,0.0);
glBegin(GL_LINE_LOOP);
glVertex2i(xmin, ymin);
glVertex2i(xmax, ymin);
glVertex2i(xmax, ymax);
glVertex2i(xmin, ymax);
glEnd();
glColor3f(0.0,0.0,1.0);
glBegin(GL_LINES);
glVertex2i(x1, y1);
glVertex2i(x2, y2);
glEnd();
cohen(x1, y1, x2, y2);
glFlush();
}
void init(){
glMatrixMode(GL_PROJECTION);
gluOrtho2D(0, 500, 0, 500);
glMatrixMode(GL_MODELVIEW);
}
int main(int argc, char** argv){
printf("Enter the line values\n");
scanf("%f %f %f %f", &x1, &y1, &x2, &y2);
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowSize(500, 500);
glutCreateWindow("Cohen Sutherland and Drawing Algorithm");
init();
glutDisplayFunc(display);
glutMainLoop();
return 0;
}
| true |
6c6f4af3ccc6172e3c19ed56995adfa904c0d6f3 | C++ | suancaiAmour/GraduationDesign | /调度器/os_demo/1_点灯实验/LCD/LCD.h | GB18030 | 7,221 | 2.625 | 3 | [] | no_license | #ifndef __LCD_H
#define __LCD_H
#include "sys.h"
using namespace periph;
#define WRITE_WAIT 0
/** @brief ͼɫ */
#define COLOR_WHITE RGB565(31,63,31)
#define COLOR_BLACK RGB565(0,0,0)
#define COLOR_BLUE RGB565(0,0,31)
#define COLOR_RED RGB565(31,0,0)
#define COLOR_PURPLE RGB565(31,0,31)
struct RGB565{
u16 code; /*!< ɫ */
operator u16&() {return code;}
finline RGB565(){}
finline RGB565(const u16 init_code):code(init_code){}
finline RGB565(const u8 r,const u8 g,const u8 b):code(((r&BitFromTo(4,0))<<(6+5))|((g&BitFromTo(5,0))<<5)|((b&BitFromTo(4,0)))) {}
};
class LCD_Screen{
private:
/********************************* źʱ *********************************
***/
#define rd pc6
#define wr pc7
#define rs pc8
#define cs pc9
#define bk pc10
#define port gpiob
static void IO_Init();
/** @brief LCD ƬѡźţƬѡźźLCDŲ; */
static void finline CS_Select() { cs.Reset(); }
static void finline CS_DeSelect() { cs.Set(); }
/** @brief select an index or status register */
static void finline RS_IndexSelect() { rs.Reset(); }
/** @brief select a control register */
static void finline RS_ControlSelect() { rs.Set(); }
static void finline WriteData(u16 const data){
port.Write(data);
#if (WRITE_WAIT>0)
for(int volatile i=WRITE_WAIT;i;i--);
#endif
wr.Reset(); /* д */
wr.Set();
}
static void finline PutDataOnPort(u16 const data) { port.Write(data); }
static void finline WritePulse() { wr.Reset(); wr.Set(); }
/** @brief ΪIO˫ģ
* Ĭд״̬ڶ֮ǰҪΪ״̬
*/
static void finline ReadBegin() {port.Set(PinAll); port.Config(INPUT, PULL_UP); }
/** @brief LCDжݺ
* IOûд״̬
*/
static void finline ReadEnd() { port.Config(OUTPUT, PUSH_PULL); }
static u16 finline ReadData() {
ReadBegin();
/* дֻΪʱܶȷֵ */
/* __nop() ܻᱻŻ */
rd.Reset();
for(int volatile register i=1;i;i--)
rd.Reset();
u16 t = port.Read();
rd.Set();
ReadEnd();
return t;
}
/** @brief */
static finline void BackLightOn() {pc10.Set();}
/** @brief Ĵַ */
static void finline WriteIndex(u16 const data) {
RS_IndexSelect();//дַ
WriteData(data);
RS_ControlSelect(); /* rs Ĭϸߵƽ */
}
/** @brief дĴ */
static void finline WriteReg(u16 const index, u16 const LCD_RegValue) {
WriteIndex(index);
WriteData(LCD_RegValue);
}
/** @brief Ĵ */
static u16 finline ReadReg(u8 const index) {
u16 t;
WriteIndex(index); //дҪļĴ
t= ReadData();
return t;
}
/***********ٲΪܹʼõĺ***********
***/
static void SlowWriteData(u16 data) {
port.Write(data);
Delay_us(2);
wr.Reset();
Delay_us(5);
wr.Set();
Delay_us(2);
}
static u16 SlowReadData() {
ReadBegin();
Delay_us(2);
rd.Reset();
Delay_us(5);
u16 t = port.Read();
rd.Set();
Delay_us(2);
ReadEnd();
return t;
}
static void finline SlowWriteIndex(u16 const data) {
RS_IndexSelect();//дַ
SlowWriteData(data);
RS_ControlSelect(); /* rs Ĭϸߵƽ */
}
static u16 SlowReadReg(u16 const index) {
u16 t;
SlowWriteIndex(index); //дҪļĴ
t= SlowReadData();
return t;
}
static void SlowWriteReg(u16 index, u16 data) {
SlowWriteIndex(index);
SlowWriteData(data);
}
/***
***********ٲΪܹʼõĺ***********/
#ifndef ILI93XX_CPP
#undef cs
#undef rs
#undef wr
#undef rd
#undef port
#endif
/***
********************************* źʱ *********************************/
static u16 BGR2RGB(u16 c) {
u16 r,g,b,rgb;
b=(c>>0)&0x1f;
g=(c>>5)&0x3f;
r=(c>>11)&0x1f;
rgb=(b<<11)|(g<<5)|(r<<0);
return(rgb);
}
u32 DeviceCode;
protected:
/** @brief ⲿûʹãΪֻΪͨԺһΪӿڶ
* ı͵ıʾľݵ岢ȷûֻɫʱ
* ֻҪʹ RGB565RGB555 RGB888 ȣЩͶͰȫƣ
* ˼Ҳȷ */
typedef RGB565 ColorType;
public:
/** @brief LCD ƬѡźţƬѡźźLCDŲ; */
static void finline Select() { CS_Select(); }
static void finline DeSelect() { CS_DeSelect(); }
LCD_Screen(){}
/** @brief ʼ LCDʼɺƬѡźΪ״̬ */
void Init();
void DisplayOn(); /* LCD ʾ */
void DisplayOff();
enum{
width = 240
, height = 320
, x_max = width-1
, y_max = height-1
};
/* ͼ */
//void FillRect(u16 xsta,u16 ysta,u16 xend,u16 yend,u16 color);
//void ClearScreen(u16 RGB_Code);
/** @brief ĺΪûԶ廭ͼõģΪĽӿ */
/** @{ */
/** @brief һд
* @note ֻûԶдãĿ
* Write_SetCursor WritePixelһüȡ
* һε Write_SetCursor WritePixel ֮ǰһд
*/
void Write_SetWindow(u16 x_start, u16 y_start, u16 x_end, u16 y_end);
void Write_SetCursor(u16 x, u16 y);
void WritePixel(u16 x, u16 y, ColorType color);
/** @broef ָɫдһص㣬֮ WritePixel() ()
* ͻʹõǰɫһص */
finline void WritePixel(const ColorType& color) { WriteData(color.code); }
/** @brief ѡдصϵɫֻܸ WritePixel() ()
* @note һüȡ */
finline void WritePixelPrepareColor(const ColorType& color) { PutDataOnPort(color.code); }
finline void WritePixel() { WritePulse(); }
/** @brief һ
* @note ֻûԶصãĿ
* Read_SetCursor ReadPixelһüȡ
* һε Read_SetCursor ReadPixel ֮ǰһ
*/
void Read_SetWindow(u16 x_start, u16 y_start, u16 x_end, u16 y_end);
ColorType ReadPixel(u16 x, u16 y);
/** @note д */
//void finline SkipPixel() { ReadPixel();/* dummy read */ WritePixel(ReadPixel()); }
//finline ColorType ReadPixel() { RGB565 r; r.code = ReadData(); return BGR2RGB(r);}
void Read_SetCursor(u16 x, u16 y);
/** @} */
};
#endif
| true |
16e857191bc5e5dcd4c6fed3a4979683792b97d1 | C++ | Douglasdai/PAT_algorithm | /第三章入门模拟/A1006.cpp | UTF-8 | 1,358 | 3.015625 | 3 | [] | no_license | #include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
//签入签出 比较时间
// 题解
struct pNode{
char id[20];
int hh,mm,ss;
}temp,ans1,ans2;
bool great(pNode a,pNode b){
if(a.hh !=b.hh) return a.hh>b.hh;
else if(a.mm !=b.mm) return a.mm>b.mm;
else return a.ss>b.ss;
}
int main(){
int M;
scanf("%d",&M);
ans1.hh =24,ans1.mm = 60,ans1.ss=60;
ans2.hh =0,ans2.mm = 0,ans2.ss=0;
for(int i=0;i<M;i++){
scanf("%s %d:%d:%d",&temp.id,&temp.hh,&temp.mm,&temp.ss);
if(great(temp,ans1)==false)ans1 =temp;
scanf("%d:%d:%d",ans2.hh,ans2.mm,ans2.ss);
if(great(temp,ans2)==false)ans2 =temp;
}
printf("%s %s\n",ans1.id,ans2.id);
return 0;
}
#include<cstdio>
#include<algorithm>
#include<string.h>
using namespace std;
struct ti{
char id[15];
int h;
int m;
int s;
};
bool cmp(ti a,ti b){
if(a.h !=b.h) return a.h>b.h;
else if(a.m !=b.m) return a.m>b.m;
else return a.s>b.s;
}
//法二 结构体排序
int main(){
int M;
scanf("%d",&M);
ti t[M],tl[M];
for(int i=0;i<M;i++){
scanf("%s %d:%d:%d %d:%d:%d",&t[i].id,&t[i].h,&t[i].m,&t[i].s,&tl[i].h,&tl[i].m,&tl[i].s);
strncpy(tl[i].id,t[i].id,15);
}
sort(t,t+M,cmp);
sort(tl,tl+M,cmp);
printf("%s %s",t[M-1].id,tl[0].id);
return 0;
} | true |
f21aa059b9f6771cd2fc4a6b8b7aaabbca20ba82 | C++ | baiyunping333/palisade-release-mirror | /src/core/include/math/binaryuniformgenerator.h | UTF-8 | 2,986 | 2.515625 | 3 | [
"BSD-2-Clause"
] | permissive | // @file binaryuniformgenerator.cpp This code provides generation of a uniform
// distribution of binary values (modulus 2). Discrete uniform generator relies
// on the built-in C++ generator for 32-bit unsigned integers defined in
// <random>.
// @author TPOC: contact@palisade-crypto.org
//
// @copyright Copyright (c) 2019, New Jersey Institute of Technology (NJIT)
// All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution. THIS SOFTWARE IS
// PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
// EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef LBCRYPTO_MATH_BINARYUNIFORMGENERATOR_H_
#define LBCRYPTO_MATH_BINARYUNIFORMGENERATOR_H_
#include <random>
#include "math/distributiongenerator.h"
namespace lbcrypto {
template <typename VecType>
class BinaryUniformGeneratorImpl;
typedef BinaryUniformGeneratorImpl<BigVector> BinaryUniformGenerator;
/**
* @brief A generator of the Binary Uniform Distribution.
*/
template <typename VecType>
class BinaryUniformGeneratorImpl : public DistributionGenerator<VecType> {
public:
/**
* @brief Basic constructor for Binary Uniform Generator.
*/
BinaryUniformGeneratorImpl() : DistributionGenerator<VecType>() {}
~BinaryUniformGeneratorImpl() {}
/**
* @brief Generates a random value within the Binary Uniform Distribution.
* @return A random value within this Binary Uniform Distribution.
*/
typename VecType::Integer GenerateInteger() const;
/**
* @brief Generates a vector of random values within the Binary Uniform
* Distribution.
* @return A vector of random values within this Binary Uniform Distribution.
*/
VecType GenerateVector(const usint size,
const typename VecType::Integer &modulus) const;
private:
static std::bernoulli_distribution m_distribution;
};
} // namespace lbcrypto
#endif // LBCRYPTO_MATH_BINARYUNIFORMGENERATOR_H_
| true |
07f6daf44f324f7e6222e34bb4b06561c232ebef | C++ | JerCaptain39/my_cpp_project | /Excises/Horton Beginning Visual C++ 2012 - 副本/Ivor Horton Website Code & Exercises/368084 Code from the Book/Chapter 09/Ex9_12/Can.h | UTF-8 | 631 | 2.921875 | 3 | [] | no_license | // Can.h for Ex9_10
#pragma once
#define _USE_MATH_DEFINES // For constants in math.h
#include <math.h>
#include "Container.h" // For CContainer definition
class CCan: public CContainer
{
public:
// Function to calculate the volume of a can
virtual double Volume() const override
{ return 0.25*M_PI*m_Diameter*m_Diameter*m_Height; }
// Constructor
explicit CCan(double hv = 4.0, double dv = 2.0): m_Height(hv), m_Diameter(dv){}
~CCan()
{ std::cout << "CCan destructor called" << std::endl; }
protected:
double m_Height;
double m_Diameter;
};
| true |
cfd5e0c86d4dc7ce485c2c06a7bb5f3794848dc2 | C++ | KTHVisualization/percMPI | /src/interfaceblockbuilder.h | UTF-8 | 5,794 | 2.84375 | 3 | [
"BSD-2-Clause"
] | permissive | #pragma once
#include <vector>
#include <functional>
#include "handles.h"
#include "unionfindblock.h"
#include "unionfindsubblock.h"
namespace perc {
namespace interfaceblockbuilder {
// Create the red blocks as red or grey subblocks.
// @returns size of white block within.
template <typename BlockType>
void buildRedBlocks(const vec3i& parentBlockSize, const vec3i& parentBlockOffset,
const vec3i& totalSize, std::vector<UnionFindSubBlock<BlockType>>& newBlocks,
ID*& newPointers, ind& pointerBlockSize, vec3i& whiteBlockSize,
vec3i& whiteBlockOffset, UnionFindBlock& parent,
std::function<BlockType()> blockConstructor) {
newBlocks.reserve(6);
// Find out white block size, offset and size to allocate for pointers.
pointerBlockSize = 0;
whiteBlockOffset = parentBlockOffset;
whiteBlockSize = parentBlockSize;
// Gather white size in all dimensions.
for (ind dim = 0; dim < 3; ++dim) {
// Low side.
if (whiteBlockOffset[dim] > 0) {
whiteBlockOffset[dim]++;
whiteBlockSize[dim]--;
}
// High side.
if (whiteBlockOffset[dim] + whiteBlockSize[dim] < totalSize[dim]) whiteBlockSize[dim] -= 2;
}
// Gather sizes in all dimensions.
for (ind dim = 0; dim < 3; ++dim) {
vec3i blockSize = whiteBlockSize;
blockSize[dim] = 1;
// Low side.
if (whiteBlockOffset[dim] > 0) pointerBlockSize += blockSize.prod();
// High side.
if (whiteBlockOffset[dim] + whiteBlockSize[dim] < totalSize[dim])
pointerBlockSize += blockSize.prod();
}
// Allocate memory.
newPointers = new ID[pointerBlockSize];
ID* pointerIterator = newPointers;
// Build blocks.
for (ind dim = 0; dim < 3; ++dim) {
vec3i blockSize = whiteBlockSize;
blockSize[dim] = 1;
// Lower slice.
if (whiteBlockOffset[dim] > 0) {
vec3i blockOffset = whiteBlockOffset;
blockOffset[dim] -= 1;
// Create block.
newBlocks.emplace_back(blockSize, blockOffset, totalSize, parent, blockConstructor(),
pointerIterator);
pointerIterator += blockSize.prod();
}
// Upper slice.
if (whiteBlockOffset[dim] + whiteBlockSize[dim] < totalSize[dim]) {
vec3i blockOffset = whiteBlockOffset;
// WhiteBlockSize has already been adapted for the red block
blockOffset[dim] += whiteBlockSize[dim];
// Create block.
newBlocks.emplace_back(blockSize, blockOffset, totalSize, parent, blockConstructor(),
pointerIterator);
pointerIterator += blockSize.prod();
}
}
}
// Create a green blocks as green or grey subblocks.
template <typename BlockType>
UnionFindSubBlock<BlockType> buildGreenBlock(const vec3i& direction, const vec3i& whiteBlockSize,
const vec3i& whiteBlockOffset, const vec3i& totalSize,
ID*& memoryPointer, UnionFindBlock& parent,
std::function<BlockType()> blockConstructor) {
vec3i blockOffset, blockSize;
static const ind ALL_ZERO = -1;
static const ind SEVERAL_NONZERO = -2;
ind nonZeroDim = ALL_ZERO;
for (ind dim = 0; dim < 3; ++dim) {
if (direction[dim] != 0) {
if (nonZeroDim == ALL_ZERO)
nonZeroDim = dim;
else {
nonZeroDim = SEVERAL_NONZERO;
break;
}
}
}
assert(nonZeroDim != ALL_ZERO && "Null vector input direction.");
// Corner block?
if (nonZeroDim == SEVERAL_NONZERO) {
// Little 3x3x3 corner block or 3x3xS edge.
for (ind dim = 0; dim < 3; ++dim) {
switch (direction[dim]) {
case 1:
blockOffset[dim] = whiteBlockOffset[dim] + whiteBlockSize[dim];
blockSize[dim] = 3;
break;
case -1:
blockOffset[dim] = whiteBlockOffset[dim] - 3;
blockSize[dim] = 3;
break;
case 0:
blockOffset[dim] = whiteBlockOffset[dim];
blockSize[dim] = whiteBlockSize[dim];
break;
default:
assert(false && "Only allowing direction within {-1, 0, 1}³.");
}
}
// Side or edge slice.
} else {
blockOffset = whiteBlockOffset;
blockSize = whiteBlockSize;
blockSize[nonZeroDim] = 1;
switch (direction[nonZeroDim]) {
case -1:
assert(whiteBlockOffset[nonZeroDim] >= 4 && "No green block fits here.");
blockOffset[nonZeroDim] = whiteBlockOffset[nonZeroDim] - 2;
break;
case 1:
assert(whiteBlockOffset[nonZeroDim] + whiteBlockSize[nonZeroDim] <
totalSize[nonZeroDim] - 3 &&
"No green block here.");
blockOffset[nonZeroDim] =
whiteBlockOffset[nonZeroDim] + whiteBlockSize[nonZeroDim] + 1;
break;
default:
assert(false && "Only allowing direction within {-1, 0, 1}³.");
}
}
auto block = UnionFindSubBlock<BlockType>(blockSize, blockOffset, totalSize, parent,
blockConstructor(), memoryPointer);
memoryPointer += blockSize.prod();
return block;
}
} // namespace interfaceblockbuilder
} // namespace perc | true |
ff094201bacf8ffbd638fd824948794400296310 | C++ | MatheusMRFM/Network-based-Procedural-Story-Generation | /Code/Lista.cpp | UTF-8 | 6,497 | 3 | 3 | [] | no_license | #include "Lista.hpp"
///**********************************************************************
///*************************** LISTA RELACAO ****************************
///**********************************************************************
ListaDE::ListaDE () {
this->first = NULL;
num_itens = 0;
}
//----------------------------------------------------------------------
ListaDE::~ListaDE () {
Item *aux;
for (Item *p = this->first; p != NULL; ) {
aux = p;
p = p->prox;
free(aux);
}
}
//----------------------------------------------------------------------
void ListaDE::insere_ordenado (int indice, float valor) {
Item* aux = (Item*) malloc (sizeof(Item));
aux->id = indice;
aux->f = valor;
num_itens++;
if (this->first == NULL) {
this->first = aux;
this->first->ant = NULL;
this->first->prox = NULL;
}
else if (this->first->f <= valor) {
aux->prox = this->first;
this->first->ant = aux;
aux->ant = NULL;
this->first = aux;
}
else {
Item* p;
for (p = this->first; p->prox != NULL; p = p->prox) {
if (p->f >= valor && p->prox->f < valor) {
aux->ant = p;
aux->prox = p->prox;
p->prox = aux;
aux->prox->ant = aux;
return;
}
}
if (p->f >= valor) {
aux->ant = p;
aux->prox = NULL;
p->prox = aux;
}
else {
aux->prox = p;
aux->ant = p->ant;
p->ant = aux;
if (aux->ant != NULL)
aux->ant->prox = aux;
}
}
}
//----------------------------------------------------------------------
void ListaDE::insere_fim (int indice, float valor) {
Item* aux = (Item*) malloc (sizeof(Item));
aux->id = indice;
aux->f = valor;
num_itens++;
if (this->first == NULL) {
this->first = aux;
aux->prox = NULL;
aux->ant = NULL;
}
else {
Item* p;
for (p = this->first; p->prox != NULL; p = p->prox) { }
p->prox = aux;
aux->prox = NULL;
aux->ant = p;
}
}
//----------------------------------------------------------------------
void ListaDE::insere_inicio (int indice, float valor) {
num_itens++;
Item* aux = (Item*) malloc (sizeof(Item));
aux->id = indice;
aux->f = valor;
aux->prox = this->first;
aux->ant = NULL;
this->first = aux;
if (aux->prox != NULL)
aux->prox->ant = aux;
}
//----------------------------------------------------------------------
Item* ListaDE::remove_topo () {
if (this->first != NULL) {
num_itens--;
Item* aux = this->first;
this->first = this->first->prox;
aux->prox = NULL;
if (this->first != NULL)
this->first->ant = NULL;
return aux;
}
return NULL;
}
//----------------------------------------------------------------------
Item* ListaDE::remove (int indice) {
Item* aux;
if (this->first->id == indice) {
num_itens--;
aux = this->first;
this->first = this->first->prox;
aux->prox = NULL;
if (this->first != NULL)
this->first->ant = NULL;
return aux;
}
Item *p;
if (this->first == NULL)
return NULL;
for (p = this->first; p->prox != NULL && p->prox->id != indice; p = p->prox) {}
if (p->prox == NULL)
return NULL;
else {
num_itens--;
aux = p->prox;
p->prox = aux->prox;
aux->ant = NULL;
aux->prox = NULL;
if (p->prox != NULL)
p->prox->ant = p;
}
return aux;
}
//----------------------------------------------------------------------
void ListaDE::imprime () {
printf("LISTA ORDENADA CRESCENTE: \n");
for (Item* p = this->first; p != NULL; p = p->prox) {
printf("(%d, %.1f)\n", p->id, p->f);
}
}
///*********************************************************************
///*************************** LISTA EVENTOS ***************************
///*********************************************************************
Lista_Evento::Lista_Evento () {
this->first = NULL;
num_itens = 0;
}
//----------------------------------------------------------------------
Lista_Evento::~Lista_Evento () {
Item_Evento *aux;
for (Item_Evento *p = this->first; p != NULL; ) {
aux = p;
p = p->prox;
free(aux);
}
}
//----------------------------------------------------------------------
bool Lista_Evento::atualiza_item (Item_Evento item) {
Item_Evento *aux;
for (aux = this->first; aux != NULL; aux = aux->prox) {
if (aux->id == item.id) {
for (int i = 0; i < MAX_PARTICIPANTES; i++) {
if (aux->participante[i] != item.participante[i])
break;
///Item encontrado
else if (i == MAX_PARTICIPANTES-1) {
aux->p = item.p;
return true;
}
}
}
}
return false;
}
//----------------------------------------------------------------------
void Lista_Evento::insere_ordenado (Item_Evento item) {
if (this->atualiza_item(item))
return;
Item_Evento* aux = (Item_Evento*) malloc (sizeof(Item_Evento));
aux->id = item.id;
aux->p = item.p;
for (int i = 0; i < MAX_PARTICIPANTES; i++)
aux->participante[i] = item.participante[i];
num_itens++;
if (this->first == NULL) {
this->first = aux;
this->first->ant = NULL;
this->first->prox = NULL;
}
else if (this->first->p <= aux->p) {
aux->prox = this->first;
this->first->ant = aux;
aux->ant = NULL;
this->first = aux;
}
else {
Item_Evento* p;
for (p = this->first; p->prox != NULL; p = p->prox) {
if (p->p >= aux->p && p->prox->p < aux->p) {
aux->ant = p;
aux->prox = p->prox;
p->prox = aux;
aux->prox->ant = aux;
return;
}
}
if (p->p >= item.p) {
aux->ant = p;
aux->prox = NULL;
p->prox = aux;
}
else {
aux->prox = p;
aux->ant = p->ant;
p->ant = aux;
if (aux->ant != NULL)
aux->ant->prox = aux;
}
}
}
//----------------------------------------------------------------------
Item_Evento* Lista_Evento::remove_topo () {
if (this->first != NULL) {
num_itens--;
Item_Evento* aux = this->first;
this->first = this->first->prox;
aux->prox = NULL;
if (this->first != NULL)
this->first->ant = NULL;
return aux;
}
return NULL;
}
//----------------------------------------------------------------------
void Lista_Evento::imprime () {
printf("LISTA ORDENADA: \n");
for (Item_Evento* p = this->first; p != NULL; p = p->prox) {
printf("Evento %d (%d, %d) - %.3f)\n", p->id, p->participante[0], p->participante[1], p->p);
}
}
//----------------------------------------------------------------------
| true |
f51bc7d72f776cf41040ef97745229d4605f7650 | C++ | mokolotron2000/OOPlab4 | /Date.cpp | WINDOWS-1251 | 2,078 | 3.828125 | 4 | [] | no_license |
#include <iostream>
#include <iomanip>
#include "Date.h"
Date::Date()
{
//std::cout << " dd mm yyyy"<< std::endl;
//std::cin >>day;
//
//std::cin >>mounth;
//set_mounth(mounth);
//set_day(day);
//std::cin >> year;
//set_year(year);
day = 1;
mounth = 1;
year = 1000;
}
Date::Date(int _day, int _mounth, int _year)
{
if (_day > 0 && _mounth > 0) {
if (_day < max_day(_mounth)) day = _day;
else std::cout << " ";
if (_mounth <= 12) mounth = _mounth;
else std::cout << "̳ ";
if (_year > 1000) year = _year;
else std::cout << "г ";
}
else std::cout << ", !";
}
Date::Date(const Date &obj) {
day = (obj.day);
mounth = (obj.mounth);
year = (obj.year);
}
void Date :: show() {
std::cout << std::setfill('0') << std::setw(2) << get_day()
<< '.' << std::setw(2) << get_mounth()
<< '.' << std::setw(2) << get_year();
}
Date::~Date()
{
}
int Date::max_day(int _mounth) {
int days[12] = { 31,28,31,30,31,30,31,31,30,31,30,31};
return days[_mounth - 1];
}
Date& Date::set_day(int _day) {
if (_day > 0 && _day < max_day(mounth))
day = _day;
else {
day = 1;
std::cout << ": . :" << std::endl;
std::cin >> _day;
set_day(_day);
}
return *this;
}
Date& Date::set_mounth(int _mounth) {
if (_mounth > 0 && _mounth <= 12)
mounth = _mounth;
else {
mounth = 1;
std::cout << ": . :" << std::endl;
std:: cin >> _mounth;
set_mounth(_mounth);
}
return *this;
}
Date& Date::set_year(int _year) {
if (_year > 1000)
year = _year;
else {
year = 1001;
std::cout << ": . :" << std::endl;
std::cin >> _year;
set_year(_year);
}
return *this;
}
| true |
1e986b05df0ff94be506ace7aa153a556505832e | C++ | DonaldWhyte/multidimensional-search-fyp | /index_structures/include/RecursivePyramidTree.h | UTF-8 | 2,923 | 3.234375 | 3 | [
"MIT"
] | permissive | #ifndef MDSEARCH_RECURSIVEPYRAMIDTREE_H
#define MDSEARCH_RECURSIVEPYRAMIDTREE_H
#include <vector>
#include <boost/unordered_map.hpp>
#include "IndexStructure.h"
namespace mdsearch
{
class RecursivePyramidTree; // forward declaration
/* Structure used for Pyramid tree buckets. */
struct RPTBucket
{
RecursivePyramidTree* subTree;
unsigned int removedDimension;
PointList points;
RealList pointSums;
RPTBucket() : subTree(NULL), removedDimension(0)
{
}
};
class RecursivePyramidTree : public IndexStructure
{
public:
RecursivePyramidTree(unsigned int numDimensions, const Region& boundary);
/* Clear all points currently stored in the structure. */
virtual void clear();
/* Insert point into the Pyramid Tree.
* Returns true if the point was inserted successfully and
* false if the point is already stored in the structure. */
virtual bool insert(const Point& point);
/* Remove point from the tree.
* Returns true if the point was removed successfully and
* false if the point was not being stored. */
virtual bool remove(const Point& point);
/* Update the value of an existing point.
* Returns true if the point was updated and false if the
* old point is not stored in the structure. */
virtual bool update(const Point& oldPoint, const Point& newPoint);
/* Return true if the given point is being stored in the structure. */
virtual bool pointExists(const Point& point);
/* Return spatial region the tree covers. */
const Region& getBoundary() const;
/* Return total number of points currently stored in the structure. */
unsigned int numPointsStored() const;
/* Return average number of points stored in a bucket. */
Real averagePointsPerBucket() const;
/* Return satdnard deviation of points in buckets. */
Real stdevPointsPerBucket() const;
/* Return mimimum and maximum number of points stored in a single bucket. */
unsigned int minPointsPerBucket() const;
unsigned int maxPointsPerBucket() const;
/* Return string reprensetation of Pyrmaid tree. */
std::string toString() const;
protected:
static const unsigned int MAX_BUCKET_NUMBER = 300000; // TODO: need?
virtual RPTBucket* getContainingBucket(const Point& point);
virtual int getPointIndexInBucket(const Point& point, const RPTBucket* bucket) const;
// Unordered_map for storing the points
// Key = hashed 1D representation of point,
// Vsalue = list of points in BUCKET
// Each key can contain MULTIPLE indices
typedef boost::unordered_map<Real, RPTBucket> OneDMap;
OneDMap hashMap;
// Entire region of space the Pyramid tree covers
// (points outside this region are ignored)
Region boundary;
Point minPoint;
Point maxPoint;
// Interval between buckets
unsigned int bucketInterval;
// Maximum size of a single bucket
unsigned int maxBucketSize;
// Median values of the data set.
Point medianPoint;
};
}
#endif | true |
aeb58c0ec5599a9a48f68d0a80a0341f67e628d1 | C++ | SikeX/Data-Structures-and-Algorithms | /Sum.cpp | UTF-8 | 198 | 2.90625 | 3 | [] | no_license | #include <cstdio>
int Sum()
{
int a, b, c, d;
printf("Please input\n");
scanf("%d%d%d%d",&a, &b, &c, &d);
return a*a + b*b + c*c + d*d;
}
int main(void)
{
printf("%d",Sum());
return 0;
} | true |
ca3550220333432e7be488eb3869ff77f7ec8f29 | C++ | awk6873/arduino-BalancingRobot | /Encoder_MPU6050_i2c_test/Encoder_MPU6050_i2c_test.ino | UTF-8 | 3,588 | 2.546875 | 3 | [] | no_license | #include <Wire.h>
// адреса I2C
// акселерометр/гироскоп
#define MPU6050_I2C_ADDR 0x68
// контроллер энкодеров
#define ENCODER_I2C_ADDR 0x73
// функция чтения данных из MPU6050
int MPU6050_read(byte registerAddress, int numBytes, byte data[]) {
int i, r;
Wire.beginTransmission(MPU6050_I2C_ADDR);
r = Wire.write(registerAddress); // устанавливаем начальный адрес, с которого будем читать
if (r != 1) return (-1);
r = Wire.endTransmission(false); // не отпускаем шину
if (r != 0) return r;
Wire.requestFrom(MPU6050_I2C_ADDR, numBytes, true); // устанавливаем кол-во читаемых регистров с освобождением шины
while(Wire.available() && i < numBytes) {
data[i++] = Wire.read();
}
if (i != numBytes) return (-2);
return (0);
}
// функция записи в регистр MPU6050
int MPU6050_write_reg(int registerAddress, const byte data)
{
int r;
Wire.beginTransmission(MPU6050_I2C_ADDR);
r = Wire.write(registerAddress); // устанавливаем начальный адрес
if (r != 1) return (-1);
r = Wire.write(data); // записываем данные
if (r != 1) return (-2);
r = Wire.endTransmission(true); // освобождаем шину
if (r != 0) return (r);
return (0);
}
// функция чтения данных из контроллера энкодеров
int Encoder_read(int numBytes, byte data[]) {
int i, r;
Wire.requestFrom(ENCODER_I2C_ADDR, numBytes); // устанавливаем кол-во читаемых регистров с освобождением шины
while(Wire.available() && i < numBytes) {
data[i++] = Wire.read();
}
if (i != numBytes) return (-2);
return (0);
}
void setup() {
// шина I2C и COM-порт
Wire.begin();
Serial.begin(115200);
// отключаем режим SLEEP в MPU6050 (регистр PWR_MGMT_1)
MPU6050_write_reg(0x6B, 0);
}
void loop() {
uint8_t res[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
int32_t enc1, enc2;
int8_t err;
uint8_t res_MPU6050[14];
int16_t accX;
int16_t accY;
int16_t accZ;
int16_t tempRaw;
int16_t gyroX;
int16_t gyroY;
int16_t gyroZ;
double accXangle; // Angle calculate using the accelerometer
double accYangle;
delay(500);
Serial.println(Encoder_read(10, res));
//if (i2cRead(0x73, 0, 10, res)) {
// enc1 = (long)(((uint32_t)res[0])<<24 | ((uint32_t)res[1])<<16 | ((uint32_t)res[2])<<8 | (uint32_t)res[3]);
enc1 = (res[0]<<24) | (res[1]<<16) | (res[2]<<8) | res[3];
enc2 = (res[4]<<24) | (res[5]<<16) | (res[6]<<8) | res[7];
err = (res[8]<<8) | res[9];
//}
Serial.print(enc1);
Serial.print(' ');
Serial.print(enc2);
Serial.print(' ');
Serial.print(err);
Serial.println();
Serial.println(MPU6050_read(0x3B, 14, res_MPU6050));
accX = ((res_MPU6050[0] << 8) | res_MPU6050[1]);
accY = ((res_MPU6050[2] << 8) | res_MPU6050[3]);
accZ = ((res_MPU6050[4] << 8) | res_MPU6050[5]);
tempRaw = ((res_MPU6050[6] << 8) | res_MPU6050[7]);
gyroX = ((res_MPU6050[8] << 8) | res_MPU6050[9]);
gyroY = ((res_MPU6050[10] << 8) | res_MPU6050[11]);
gyroZ = ((res_MPU6050[12] << 8) | res_MPU6050[13]);
//accYangle = atan(-1*accX/sqrt(pow(accY,2) + pow(accZ,2)))*RAD_TO_DEG;
//accXangle = atan(accY/sqrt(pow(accX,2) + pow(accZ,2)))*RAD_TO_DEG;
Serial.print(accY);
Serial.print(' ');
Serial.println(accX);
}
| true |
baef987af4ca6debf5e7f9847deed449e80245e8 | C++ | jeonyeohun/PS-With-CPP | /BOJ/P1922_NetworkConnection.cpp | UTF-8 | 1,010 | 3.109375 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int parent[1001];
int level[1001];
int findRoot(int x) {
if (parent[x] == x) return x;
else return findRoot(parent[x]);
}
bool merge(int a, int b) {
a = findRoot(a);
b = findRoot(b);
if (a == b) return false;
if (level[a] > level[b]) swap(a, b);
parent[a] = b;
if (level[a] == level[b]) level[b]++;
return true;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
int N, M;
cin >> N >> M;
vector<pair<int, pair<int, int>>> edges;
for (int i = 0; i <= N; i++) {
parent[i] = i;
}
for (int i = 0; i < M; i++) {
int a, b, c;
cin >> a >> b >> c;
edges.push_back({ c, {a, b} });
}
sort(edges.begin(), edges.end());
int cost = 0;
for (auto edge : edges) {
if (merge(edge.second.first, edge.second.second)) {
cost += edge.first;
}
}
cout << cost;
} | true |
d15511818a3f0b55ca9abd1992ecd4d8beeb3914 | C++ | drlongle/leetcode | /algorithms/problem_1235/solution.cpp | UTF-8 | 2,544 | 3.0625 | 3 | [] | no_license | /*
1235. Maximum Profit in Job Scheduling
Hard
We have n jobs, where every job is scheduled to be done from startTime[i] to endTime[i], obtaining a profit of profit[i].
You're given the startTime, endTime and profit arrays, you need to output the maximum profit you can take such that there are no 2 jobs in the subset with overlapping time range.
If you choose a job that ends at time X you will be able to start another job that starts at time X.
Example 1:
Input: startTime = [1,2,3,3], endTime = [3,4,5,6], profit = [50,10,40,70]
Output: 120
Explanation: The subset chosen is the first and fourth job.
Time range [1-3]+[3-6] , we get profit of 120 = 50 + 70.
Example 2:
Input: startTime = [1,2,3,4,6], endTime = [3,5,10,6,9], profit = [20,20,100,70,60]
Output: 150
Explanation: The subset chosen is the first, fourth and fifth job.
Profit obtained 150 = 20 + 70 + 60.
Example 3:
Input: startTime = [1,1,1], endTime = [2,3,4], profit = [5,6,4]
Output: 6
Constraints:
1 <= startTime.length == endTime.length == profit.length <= 5 * 10^4
1 <= startTime[i] < endTime[i] <= 10^9
1 <= profit[i] <= 10^4
*/
#include <algorithm>
#include <atomic>
#include <bitset>
#include <cassert>
#include <cmath>
#include <condition_variable>
#include <functional>
#include <future>
#include <iostream>
#include <iterator>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <thread>
#include <unordered_map>
#include <unordered_set>
#include <vector>
using namespace std;
#define ll long long
#define ull unsigned long long
class Solution {
public:
struct Interval {
Interval(int s, int e, int p): start(s), end(e), profit(p) {}
bool operator<(const Interval& other) const {
return start < other.start;
}
int start, end, profit;
};
int jobScheduling(vector<int>& startTime, vector<int>& endTime, vector<int>& profit) {
multimap<int, pair<int, int>> jobs;
int sz = startTime.size();
for (int i = 0; i < sz; ++i) {
jobs.insert({startTime[i], {endTime[i], profit[i]}});
}
int max_profit = 0;
for (auto it = jobs.rbegin(); it != jobs.rend(); ++it) {
auto nit = jobs.lower_bound(it->second.first);
max_profit = max(max_profit, it->second.second + (nit == jobs.end() ? 0 : nit->second.second));
it->second.second = max_profit;
}
return max_profit;
}
};
int main() {
Solution sol;
return 0;
}
| true |
390c510027c723ff96b4423c49ecb760f0904c37 | C++ | zxc123qwe456asd789/library | /prime/osak.hpp | UTF-8 | 973 | 2.875 | 3 | [
"CC0-1.0"
] | permissive | #pragma once
#include "factor-enumerate.hpp"
template <int MAX>
vector<int> osak(int n) {
static vector<int> f = factor_enumerate(MAX);
vector<int> ret;
while (f[n]) ret.push_back(f[n]), n /= f[n];
return ret;
}
template <int MAX>
vector<pair<int, int>> osak_table(int n) {
static vector<int> f = factor_enumerate(MAX);
vector<pair<int, int>> v;
for (; f[n]; n /= f[n]) {
if (v.empty() || v.back().first != f[n]) {
v.emplace_back(f[n], 1);
} else {
v.back().second++;
}
}
return v;
}
template <int MAX>
vector<int> osak_divisors(int n) {
if(n == 0) return {};
if(n == 1) return vector<int>(1, 1);
auto p = osak_table<MAX>(n);
vector<int> ds;
auto dfs = [&](auto r, int i, int c) {
if (i == (int)p.size()) {
ds.push_back(c);
return;
}
for (int j = 0; j <= p[i].second; j++) {
r(r, i + 1, c);
c *= p[i].first;
}
};
dfs(dfs, 0, 1);
sort(begin(ds), end(ds));
return ds;
} | true |
2544c5b37f8a668c8e312fffa85abfbf5752a99a | C++ | PeterZs/SLR | /libSLR/MemoryAllocators/Allocator.h | UTF-8 | 2,375 | 2.796875 | 3 | [] | no_license | //
// Allocator.h
//
// Created by 渡部 心 on 2015/06/29.
// Copyright (c) 2015年 渡部 心. All rights reserved.
//
#ifndef __SLR_Allocator__
#define __SLR_Allocator__
#include "../defines.h"
#include "../declarations.h"
namespace SLR {
class SLR_API Allocator {
public:
virtual ~Allocator() { }
template <typename T> using DeleterType = std::function<void(T*)>;
virtual void* alloc(uintptr_t size, uintptr_t align) = 0;
virtual void free(void* ptr) = 0;
template <typename T>
T* alloc(size_t numElems = 1, uintptr_t align = alignof(T)) {
return (T*)alloc(numElems * sizeof(T), align);
}
template <typename T, typename ...ArgTypes>
T* create(ArgTypes&&... args) {
T* ptr = alloc<T>();
new (ptr) T(std::forward<ArgTypes>(args)...);
return ptr;
}
template <typename T>
void destroy(T* ptr) {
ptr->~T();
free(ptr);
}
template <typename T, typename ...ArgTypes>
std::shared_ptr<T> createShared(ArgTypes&&... args) {
T* rawPtr = alloc<T>();
new (rawPtr) T(std::forward<ArgTypes>(args)...);
std::function<void(void*)> deleter = std::bind(&Allocator::destroy<T>, this, std::placeholders::_1);
return std::shared_ptr<T>(rawPtr, deleter);
}
template <typename T, typename ...ArgTypes>
std::unique_ptr<T, DeleterType<T>> createUnique(ArgTypes&&... args) {
T* rawPtr = alloc<T>();
new (rawPtr) T(std::forward<ArgTypes>(args)...);
DeleterType<T> deleter = std::bind(&Allocator::destroy<T>, this, std::placeholders::_1);
return std::unique_ptr<T, DeleterType<T>>(rawPtr, deleter);
}
};
class DefaultAllocator : public Allocator {
DefaultAllocator() { };
public:
void* alloc(uintptr_t size, uintptr_t align) override { return SLR_memalign(size, align); }
void free(void* ptr) override { SLR_freealign(ptr); }
static DefaultAllocator &instance() {
static DefaultAllocator s_instance;
return s_instance;
}
};
}
#endif /* __SLR_Allocator__ */
| true |
dea8b392a5238468c3413c083fa7622acb296223 | C++ | vicly565/Movie-Manager | /movie.h | UTF-8 | 2,641 | 3.453125 | 3 | [] | no_license | // ------------------------------------------------ movie.h -------------------------------------------------------
// Victor Ly & Kenneth Ven CSS343 Section C
// Creation Date: 3/09/2020
// Date of Last Modification: 3/14/2020
// --------------------------------------------------------------------------------------------------------------------
// Purpose: This header file is an abstract class for the movie type. This class is used for the dvd store inventory system
// and represents a movie within the business
// --------------------------------------------------------------------------------------------------------------------
//
// Specifications: Every movie contains a the stock of the movie, movie type, title, director, and release year.
//
// Every movie has these PUBLIC FUNCTIONS:
// virtual void display(); //method for printing out movie
//
// in addition to this function, all movies have getters and setters
// for all of its protected data values.
//
// Assumptions: This abstract class assumes that the user never intends on creating this base class, but instead
// assumes the user intends on creating one of the three subclasses (Comedy, Classic, or Drama).
//
// --------------------------------------------------------------------------------------------------------------------
#pragma once
#include <iostream>
using namespace std;
class Movie
{
public:
virtual ~Movie();
//Setter methods
virtual void setStock(int stock);
virtual void setDirector(string director);
virtual void setTitle(string title);
virtual void setReleaseYear(int releaseYear);
virtual void setTypeOfMovie(char c);
virtual void setMajorActor(string actor);
virtual void setReleaseMonth(int month);
//Getter methods
virtual int getStock()const;
virtual string getDirector()const;
virtual string getTitle()const;
virtual int getReleaseYear()const;
virtual char getTypeOfMovie()const;
virtual string getMajorActor() const;
virtual int getReleaseMonth()const;
//assignment operator overload
virtual Movie& operator=(const Movie& rhs);
//operator overloads as pure virtual to be implemented in subclasses
virtual bool operator==(const Movie& other) const = 0;
virtual bool operator!=(const Movie& other)const = 0;
virtual bool operator>(const Movie& other) const = 0;
virtual bool operator<(const Movie& other) const = 0;
//to print out movies
virtual void display();
protected:
//movie data
int stock;
string director;
string title;
int releaseYear;
char typeOfMovie;
string majorActor;
int releaseMonth;
};
| true |
5a69e9ca8761043e3bb022182bb103a632d9e1d7 | C++ | hao-lu/Board-Games | /Board Games/TicTacToeView.cpp | UTF-8 | 648 | 2.953125 | 3 | [] | no_license | //
// TicTacToeView.cpp
// Project 3
//
// Created by Hao Lu on 5/2/15.
// Copyright (c) 2015 Hao Lu. All rights reserved.
//
#include "TicTacToeView.h"
#include <ostream>
using namespace std;
void TicTacToeView::PrintBoard(ostream &s) const {
cout << "- 0 1 2" << endl;
for (int i = 0; i < BOARD_SIZE_3; i++) {
cout << i;
for (int j = 0; j < BOARD_SIZE_3; j++){
if (mTicTacToeBoard->mBoard[i][j] == 0)
cout << " .";
if (mTicTacToeBoard->mBoard[i][j] == 1)
cout << " X";
if (mTicTacToeBoard->mBoard[i][j] == -1)
cout << " O";
}
cout << "\n";
}
} | true |
c17cb3568f137ce1cd13bdf9e5e1967b19a7843d | C++ | tejasbedi1/the-ultimate-ds-algorithms-checklist | /Topic 11 Graphs/5. Directed Weighted Graph.cpp | UTF-8 | 891 | 3.453125 | 3 | [] | no_license | #include <bits/stdc++.h>
#include <iostream>
using namespace std;
class Graph
{
private:
int V;
vector<pair<int, int>> *vArray;
public:
Graph (int V)
{
vArray = new vector <pair<int, int>> [V];
this->V = V;
}
void addEdge(int a, int b, int c)
{
vArray[a].push_back(make_pair(b,c));
}
void display()
{
int i;
for (i = 0; i < V; i++)
{
cout<<"Node "<<i<<"- \n";
for (auto x : vArray[i])
{
cout<<"\t"<<"connects with node "<<x.first<<" weighted at "<<x.second<<endl;
}
cout<<endl;
}
}
};
int main()
{
int nodes = 4;
Graph graph(nodes);
// FIG
//https://www.geeksforgeeks.org/graph-implementation-using-stl-for-competitive-programming-set-2-weighted-graph/
graph.addEdge(0, 1, 10);
graph.addEdge(0, 2, 3);
graph.addEdge(0, 3, 2);
graph.addEdge(1, 3, 7);
graph.addEdge(2, 3, 6);
cout<<"\nDisplay All\n";
graph.display();
}
| true |
0f9051c2f9cd3c5aef9a628aaae289c01081b972 | C++ | AbraaoLincoln/The_C_World | /src/PO.cpp | UTF-8 | 518 | 2.65625 | 3 | [] | no_license | #include "../include/PO.h"
/**
* construct da clase PO
* incializa os registradores, memoria e a ula
* @param *regs, ponterio para um objeto do tipo Registradores
* @param *mem, ponterio para um objeto do tipo Memoria
* @param *ula, ponterio para um objeto do tipo Ula
*/
PO::PO(Registradores *regs, Memoria *mem, Ula *ula)
{
this->regs = regs;
this->mem = mem;
this->ula = ula;
};
/**
* get_opcode
* @return, retorna o codigo da operacao atual
*/
short PO::get_opcode()
{
return regs->RI;
} | true |
e8fee72a83c7f9d7e29f023966bd9fb1db0da647 | C++ | mizutoki79/AOJ | /ALDS_InttroductionToAlgorithmsAndDataStructures/ALDS1_6_A_SortⅡ-CountingSort.cpp | UTF-8 | 563 | 2.734375 | 3 | [] | no_license | using namespace std;
#include <iostream>
int main()
{
const int MAX_N = 2000000;
const int MAX_K = 10000;
int n;
cin >> n;
int *A = new int[n];
int *B = new int[n];
int C[MAX_K] = {};
for(int i = 0; i < n; i++)
{
cin >> A[i];
C[A[i]]++;
}
for(int i = 1; i < MAX_K; i++) C[i] += C[i - 1];
for(int i = n - 1; i >= 0; i--)
{
B[C[A[i]] - 1] = A[i];
C[A[i]]--;
}
for(int i = 0; i < n; i++)
{
if(i != 0) cout << " ";
cout << B[i];
}
cout << endl;
} | true |
b4e5640bc6772fdbc4c95519e95c4e6f731a787e | C++ | atharvjairath/Cplusplus | /Dynamic_Programming/MaxSumNonAdj.cpp | UTF-8 | 890 | 3.3125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
//https://www.pepcoding.com/resources/online-java-foundation/dynamic-programming-and-greedy/maximum-sum-non-adjacent-elements-official/ojquestion
int FindMaxSum(vector<int> arr,int n){
int include = arr[0],exclude= 0;
for(int i=1; i<n; i++) {
// save the current values in temp values
int prev_ex = exclude;
int prev_in = include;
// if we will include this element then we add on prev exclude
include = prev_ex + arr[i];
// if we will exclude this element then we need to take the max of prev includede and excluded
exclude = max(prev_in,prev_ex);
}
return max(include,exclude);
}
int main()
{
vector<int> arr = {5, 5, 10, 100, 10, 5};
cout<<FindMaxSum(arr, arr.size());
}
| true |
928bdfe7f8a6a76f3fb258604b1457007fecd7b8 | C++ | GlassyYang/leetcode-cplusplus | /solution1074.cpp | UTF-8 | 923 | 2.578125 | 3 | [] | no_license | //
// Created by zhang on 2021/5/29.
//
#include "common-header.h"
class Solution {
public:
// TODO 明天再做做
int numSubmatrixSumTarget(vector<vector<int>>& matrix, int target) {
const int m = matrix.size(), n = matrix[0].size();
int ans = 0;
int buf[n];
for (int i = 0; i < m; ++i) {
buf[0] = 0;
unordered_set<int> prefix{0};
for (int j = i; j < m; ++j) {
int pre = buf[0];
buf[0] += matrix[j][i];
for (int k = 1; k < n; ++k) {
int temp = buf[k];
buf[k] = buf[k] - pre + buf[k - 1] + matrix[j][k];
auto left = prefix.find(buf[k] - k);
if (left != prefix.end())ans++;
pre = temp;
prefix.insert(buf[k]);
}
}
}
return ans;
}
}; | true |
82341f9d01d05c319d6c6d0c7a26c981a0d25bc0 | C++ | Rurril/IT-DA-3rd | /study/C++2/Week6/BOJ_5639_양희웅.cpp | UTF-8 | 1,278 | 3.703125 | 4 | [] | no_license | #include <iostream>
using namespace std;
typedef struct Node
{
int data;
Node* left;
Node* right;
} Node;
Node* insert(Node* root, int data)
{
if (root == nullptr) {
root = new Node();
root->data = data;
root->left = nullptr;
root->right = nullptr;
}
else if (data < root->data) {
root->left = insert(root->left, data);
}
else if (data > root->data) {
root->right = insert(root->right, data);
}
return root;
}
void print(Node* root)
{
if (root->left != nullptr) {
print(root->left);
}
if (root->right != nullptr) {
print(root->right);
}
cout << root->data << endl;
}
int main(void)
{
Node* root = nullptr;
int data;
while(scanf("%d", &data) != EOF) {
root = insert(root, data);
}
// while (true) {
// cin >> data;
// if (data == 0) break;
// insert(root, data);
// }
// root = insert(root, 50);
// root = insert(root, 30);
// root = insert(root, 24);
// root = insert(root, 5);
// root = insert(root, 28);
// root = insert(root, 45);
// root = insert(root, 98);
// root = insert(root, 52);
// root = insert(root, 60);
print(root);
return 0;
} | true |
f831afec8faf76b21fd19f3dc9d5dd98de13c083 | C++ | zoidor/ComputerVision | /Barcode/BarcodeTest.cpp | UTF-8 | 2,297 | 2.859375 | 3 | [] | no_license | #include <cstdio>
#include <vector>
#include <array>
#include <algorithm>
#include <exception>
#include <opencv2/opencv.hpp>
//from https://www.pyimagesearch.com/2014/11/24/detecting-barcodes-images-python-opencv/
int main(int argc, char** argv )
{
if ( argc != 2 )
{
printf("usage: DisplayImage.out <Image_Path>\n");
return -1;
}
cv::Mat image(cv::imread( argv[1], 1));
if ( !image.data )
{
printf("No image data \n");
return -1;
}
cv::Mat imageBw;
cv::cvtColor(image, imageBw, cv::COLOR_BGR2GRAY);
cv::Mat gradX;
cv::Mat gradY;
int use_scharr_filter = CV_SCHARR;
cv::Sobel(imageBw, gradX, CV_32F, 1, 0, use_scharr_filter);
cv::Sobel(imageBw, gradY, CV_32F, 0, 1, use_scharr_filter);
cv::Mat gradient;
auto diff = gradX - gradY;
cv::convertScaleAbs(diff, gradient);
cv::Mat blurred;
cv::blur(gradient, blurred, cv::Size(9, 9));
cv::Mat thresholded;
cv::threshold(blurred, thresholded, 225.0, 255.0, cv::THRESH_BINARY);
cv::Mat kernel = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(21, 7));
cv::Mat closed;
cv::morphologyEx(thresholded, closed, cv::MORPH_CLOSE, kernel);
cv::erode(closed, closed, cv::Mat{}, cv::Point(-1, -1), 4);
cv::dilate(closed, closed, cv::Mat{}, cv::Point(-1, -1), 4);
std::vector<std::vector<cv::Point>> contours;
cv::findContours(closed, contours, cv::RETR_EXTERNAL,
cv::CHAIN_APPROX_SIMPLE);
if(contours.empty())
throw std::logic_error("I must have at least 1 contour");
auto sort_contours_op = [](const auto& polygon1, const auto& polygon2)
{
const bool not_oriented = false;
return cv::contourArea(polygon1, not_oriented) > cv::contourArea(polygon2, not_oriented);
};
std::sort(contours.begin(), contours.end(), sort_contours_op);
auto enclosing_rect = cv::minAreaRect(*contours.begin());
const int thickness = 3;
std::array<cv::Point2f, 4> rect_points; enclosing_rect.points(rect_points.begin());
for( int j = 0; j < rect_points.size(); j++ )
cv::line(image, rect_points[j], rect_points[(j + 1) % rect_points.size()], cv::Scalar(0, 255, 0), thickness);
cv::imshow("rectangles", image);
cv::waitKey(0);
return 0;
}
| true |
eeb8ef66a9942b0d8cc2a5c9541119a67a450973 | C++ | AJLeuer/Chess | /Source/Game/Square.h | UTF-8 | 2,055 | 2.71875 | 3 | [] | no_license | //
// Square.h
// Chess
//
// Created by Adam James Leuer on 3/12/15.
// Copyright (c) 2015 Adam James Leuer. All rights reserved.
//
#ifndef Chess_Square_h
#define Chess_Square_h
#include <cassert>
#include "Support.h"
#include "Piece.h"
using namespace std;
namespace Chess {
/* Forward declaring */
class Board;
struct Square {
protected:
const vec2 <int> position;
Board * board;
Piece * piece = nullptr;
friend class Game_Base;
friend class Game;
friend class Piece;
friend class Player;
friend class AI;
friend class Board;
friend class TemporarySquare;
friend class TemporaryBoard;
//Square() {}
void setCurrentPiece (Piece * pieceMovingTo);
void clearCurrentPiece (Piece * toClear);
void destroyCurrentPiece ();
inline Piece * getPieceMutable () { return piece; } //for debug only, remove later
public:
Square (const Square & other);
Square (const char file, const unsigned rank, Board * board);
Square (const char file, const unsigned rank, Board * board, Piece * piece);
Square (const char file, const unsigned rank, Board * board, const wchar_t pieceSymbol);
Square (const wchar_t pieceSymbol, const char file, const unsigned rank, Board * board) :
Square(file, rank, board, pieceSymbol) {}
virtual ~Square ();
Square & operator = (const Square & rhs) = delete;
void receiveMovingPiece (Piece * pieceMovingTo);
inline bool isEmpty () const { return piece == nullptr; }
inline bool isOccupied () const { return (!(isEmpty())); }
const RankAndFile getRankAndFile () const { return RankAndFile(position); }
const vec2 <int> copyPosition () const { return this->position; }
const vec2 <int> * getPositionPointer () const { return & this->position; }
inline const Board * getBoard () const { return board; }
inline const Piece * getPiece () const { return piece; }
friend std::ostream & operator << (std::ostream &, const Square &);
friend basic_ostream <wchar_t> & operator << (basic_ostream <wchar_t> &, const Square &);
};
}
#endif
| true |
0716a3846c08c4be4df856aacbc7fbd3dee318bf | C++ | tigershan1130/PhaseEngine | /D3D10App/Source/ThreadPool.cpp | UTF-8 | 2,100 | 2.75 | 3 | [] | no_license | //--------------------------------------------------------------------------------------
// File: ThreadPool.cpp
//
// Worker thread pooling
//
// Coded by Nate Orr
//--------------------------------------------------------------------------------------
#pragma unmanaged
#include "ThreadPool.h"
ThreadPool g_ThreadPool;
ThreadPool::ThreadPool()
{
m_nMaxNumThreads = MAXTHREADS;
m_Handles[TH_EMPTY] = CreateSemaphore(NULL,MAXQUEUE,MAXQUEUE,L"EmptySlot");
m_Handles[TH_WORK] = CreateSemaphore(NULL,0,MAXQUEUE,L"WorkToDo");
m_Handles[TH_EXIT] = CreateEvent(NULL,TRUE,FALSE,L"Exit");
InitializeCriticalSection(&CriticalSection);
for(int i=0;i<m_nMaxNumThreads;i++)
{
m_threadhandles[i] = (HANDLE) _beginthreadex( NULL, 0, ThreadExecute, this, 0, &m_Thrdaddr);
}
m_nTopIndex = 0;
m_nBottomIndex = 0;
nWorkInProgress=0;
}
ThreadPool::~ThreadPool()
{
}
unsigned _stdcall ThreadPool::ThreadExecute(void *Param){
((ThreadPool*)Param)->DoWork();
return(0);
}
void ThreadPool::DoWork()
{
WorkerThread* cWork;
while(GetWork(&cWork))
{
cWork->ThreadExecute();
InterlockedDecrement(&nWorkInProgress);
}
}
//Queues up another to work
BOOL ThreadPool::SubmitJob(WorkerThread* cWork)
{
InterlockedIncrement(&nWorkInProgress);
if(WaitForSingleObject(m_Handles[TH_EMPTY],INFINITE) != WAIT_OBJECT_0){
return(0);
}
EnterCriticalSection(&CriticalSection);
m_pQueue[m_nTopIndex] = cWork;
m_nTopIndex = (m_nTopIndex++) % (MAXQUEUE -1);
ReleaseSemaphore(m_Handles[TH_WORK],1,NULL);
LeaveCriticalSection(&CriticalSection);
return(1);
}
BOOL ThreadPool::GetWork(WorkerThread** cWork)
{
if((WaitForMultipleObjects(2,m_Handles,FALSE,INFINITE) - WAIT_OBJECT_0) == 1)
return 0;
EnterCriticalSection(&CriticalSection);
*cWork = m_pQueue[m_nBottomIndex];
m_nBottomIndex = (m_nBottomIndex++) % (MAXQUEUE -1);
ReleaseSemaphore(m_Handles[TH_EMPTY],1,NULL);
LeaveCriticalSection(&CriticalSection);
return 1;
}
void ThreadPool::DestroyPool(){
while(nWorkInProgress > 0){
Sleep(10);
}
SetEvent(m_Handles[TH_EXIT]);
DeleteCriticalSection(&CriticalSection);
}
| true |
1beb54d63d471191cca2ec2d1b0866cfd1abd8c3 | C++ | anubhawbhalotia/Competitive-Programming | /LeetCode/162. Find Peak Element.cpp | UTF-8 | 265 | 2.828125 | 3 | [
"MIT"
] | permissive | class Solution {
public:
int findPeakElement(vector<int>& nums) {
int l = 0, r = nums.size() - 1;
while(l < r)
{
int mid = (l + r) / 2;
if(nums[mid] < nums[0] + mid)
e = mid - 1;
}
}
}; | true |
7eea5bae9ba0f1c7dca5a10f655ebba270df79c0 | C++ | fieldkit/firmware | /third-party/wifi101/examples/WiFiChatServer/WiFiChatServer.ino | UTF-8 | 2,874 | 2.828125 | 3 | [
"BSD-3-Clause",
"LGPL-2.1-or-later"
] | permissive | /*
Chat Server
A simple server that distributes any incoming messages to all
connected clients. To use telnet to your device's IP address and type.
You can see the client's input in the serial monitor as well.
This example is written for a network using WPA encryption. For
WEP or WPA, change the WiFi.begin() call accordingly.
Circuit:
* WiFi shield attached
created 18 Dec 2009
by David A. Mellis
modified 31 May 2012
by Tom Igoe
*/
#include <SPI.h>
#include <WiFi101.h>
#include "arduino_secrets.h"
///////please enter your sensitive data in the Secret tab/arduino_secrets.h
char ssid[] = SECRET_SSID; // your network SSID (name)
char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP)
int keyIndex = 0; // your network key Index number (needed only for WEP)
int status = WL_IDLE_STATUS;
WiFiServer server(23);
bool alreadyConnected = false; // whether or not the client was connected previously
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
// don't continue:
while (true);
}
// attempt to connect to WiFi network:
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
// start the server:
server.begin();
// you're connected now, so print out the status:
printWiFiStatus();
}
void loop() {
// wait for a new client:
WiFiClient client = server.available();
// when the client sends the first byte, say hello:
if (client) {
if (!alreadyConnected) {
// clead out the input buffer:
client.flush();
Serial.println("We have a new client");
client.println("Hello, client!");
alreadyConnected = true;
}
if (client.available() > 0) {
// read the bytes incoming from the client:
char thisChar = client.read();
// echo the bytes back to the client:
server.write(thisChar);
// echo the bytes to the server as well:
Serial.write(thisChar);
}
}
}
void printWiFiStatus() {
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");
}
| true |
23150542c3750b47530a66c10653fff7a99d38e6 | C++ | arav-ind/99003118 | /Set 1/Account/account.cpp | UTF-8 | 771 | 3.3125 | 3 | [] | no_license | #include"account.h"
Account::Account():m_accNumber(""),m_accName(""),m_balance(0)
{
}
Account::Account(std::string num, std::string name, double bal): m_accNumber(num), m_accName(name), m_balance(bal)
{
}
Account::Account(std::string num,std::string name):m_accNumber(num), m_accName(name)
{
}
Account::Account(const Account &ref):m_accNumber(ref.m_accNumber),m_accName(ref.m_accName),m_balance(ref.m_balance)
{
}
void Account::debit(double amount)
{
m_balance -= amount;
}
void Account::credit(double amount)
{
m_balance += amount;
}
double Account::getBalance() const
{
return m_balance;
}
void Account::dispay() const
{
std::cout << "Account Number : " << m_accNumber
<< "Name :" << m_accName
<< "Balance: " << m_balance;
}
| true |
6167b0b2f4af6a3c8860ac5892b38ddd6de931c3 | C++ | tbrown91/NETSeq_simulator | /NETseq_simActivePromoterBacktrackTwoWindowsConstTermination/param_funcs.hpp | UTF-8 | 1,041 | 2.625 | 3 | [] | no_license | void choose_param(vector<double>& sample_params,const double min_param,const double max_param,const int num_params){
vector<double> possible_params (num_params,0.0);
for (int i=0;i<num_params;++i){
possible_params[i] = min_param + (max_param-min_param)*((double)i/(double)(num_params-1));
}
for (int i=0;i<num_params;++i){
int sample_int = gsl_rng_uniform_int(r,num_params-i);
sample_params[i] = possible_params[sample_int];
possible_params[sample_int] = possible_params[num_params-1-i];
}
}
void choose_intParam(vector<double>& sample_params,const int min_param,const int max_param,const int num_params){
vector<int> possible_params (num_params,0.0);
for (int i=0;i<num_params;++i){
possible_params[i] = floor(min_param + (max_param-min_param)*((double)i/(double)(num_params-1)));
}
for (int i=0;i<num_params;++i){
int sample_int = gsl_rng_uniform_int(r,num_params-i);
sample_params[i] = possible_params[sample_int];
possible_params[sample_int] = possible_params[num_params-1-i];
}
}
| true |
91089c4e646a36846e50c510cae42c8e79647768 | C++ | Bouts2019/PTA_DS_TOPIC | /7-1 最大子列和问题 (20 分)/code.cpp | UTF-8 | 392 | 2.71875 | 3 | [] | no_license | #include <iostream>
using namespace std;
int *arr = nullptr;
int main(int argc, char** argv)
{
ios::sync_with_stdio(false); cin.tie(0);
int k = 0;
cin >> k;
arr = new int[k];
int tmp = 0;
int max = 0;
for (int i = 0; i < k; i++)
{
cin >> arr[i];
if (arr[i] + tmp < 0) tmp = 0;
else
{
tmp += arr[i];
if (tmp > max) max = tmp;
}
}
cout << max << endl;
return 0;
}
| true |
400a3a688b975ece6d78988c77e761d32e2a0222 | C++ | KOTERATOR/ESP32-Pedal | /ESP32Pedal/Views/TextBox.h | UTF-8 | 3,696 | 3.1875 | 3 | [] | no_license | #pragma once
#include "../GFX/View.h"
class TextBox : public View
{
public:
String alphabet = " 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!\"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~";
size_t currentPos = 0, currentAlphabetChar = 0;
char prevChar = ' ';
String text;
bool editMode = false;
int8_t textSize = 1;
int16_t color;
HTextAlignment horizontalAlignment = HTextAlignment::Left;
VTextAlignment verticalAlignment = VTextAlignment::Top;
TextBox(ContainerSizeMode widthMode, ContainerSizeMode heightMode, String text = "", int textSize = 1, int16_t color = Color::WHITE, HTextAlignment horizontalAlignment = HTextAlignment::Center, VTextAlignment verticalAlignment = VTextAlignment::Center) : View(widthMode, heightMode, ContainerMode::NORMAL, Position(0,0), Size(128, 10)), text(text)
{
this->textSize = textSize;
this->horizontalAlignment = horizontalAlignment;
this->verticalAlignment = verticalAlignment;
this->color = color;
}
void onDraw(ViewGFX * gfx)
{
int16_t x1 = 0, y1 = 0;
Size bounds = gfx->getTextBounds(text, textSize);
if(horizontalAlignment == HTextAlignment::Left)
{
x1 = 0;
}
else if(horizontalAlignment == HTextAlignment::Right)
{
x1 = size.width - bounds.width;
}
else if(horizontalAlignment == HTextAlignment::Center)
{
x1 = (size.width - bounds.width)/2;
}
if(verticalAlignment == VTextAlignment::Top)
{
y1 = 0;
}
else if(verticalAlignment == VTextAlignment::Bottom)
{
y1 = size.height - bounds.height;
}
else if(verticalAlignment == VTextAlignment::Center)
{
y1 = (size.height - bounds.height)/2;
}
if(isSelected)
{
if(editMode)
{
text[currentPos] = alphabet[currentAlphabetChar];
}
gfx->drawTextWithInvertedChar(x1, y1, text, color, textSize, currentPos);
}
else
{
gfx->drawText(x1, y1, text, color, textSize);
}
//Size bounds = gfx.getTextBounds(text);
//gfx.drawText((size.width - bounds.width) / 2, (size.height - bounds.height) / 2 + 1, text, Color::WHITE);
//gfx.drawText(0, 10, text, color, textSize);
}
void onSelect()
{
if(isSelected && !editMode)
{
editMode = true;
currentAlphabetChar = 0;
prevChar = text[currentPos];
}
if(isSelected && editMode)
{
editMode = false;
}
isSelected = true;
}
void onNext()
{
if(editMode)
{
if(currentAlphabetChar + 1 < alphabet.length())
currentAlphabetChar++;
else
{
currentAlphabetChar = 0;
}
}
else
{
if(currentPos + 1 <= text.length())
currentPos++;
}
}
void onPrev()
{
if(editMode)
{
if(currentAlphabetChar > 0)
currentAlphabetChar--;
else
currentAlphabetChar = alphabet.length()-1;
}
else
{
if(currentPos > 0)
currentPos--;
}
}
bool onUnselect()
{
if(editMode)
{
editMode = false;
text[currentPos] = prevChar;
return false;
}
else
{
isSelected = false;
return true;
}
}
}; | true |
b73206edd7ccbb0d56d7c89bde13933e952a5065 | C++ | wewark/The-Maze | /Source/grue.cpp | UTF-8 | 2,590 | 2.984375 | 3 | [] | no_license | #include "grue.h"
#include <stdlib.h>
#include <time.h>
#include "helpers.h"
#include <iostream>
#include <queue>
using namespace std;
grue::grue(string nameX, Room* posX, int levelX) : Agent(nameX, posX, 0, levelX)
{
}
grue::~grue() {}
int grue::act(string path)
{
if (cur_pos == NULL)
return 0;
if (getHealth() <= 0)
return 0;
attack();
if (path == "random")
{
while (true) {
// Performance
int ranDirc = rand() % 5;
if (ranDirc == 1 && move("north") ||
ranDirc == 2 && move("south") ||
ranDirc == 3 && move("east") ||
ranDirc == 4 && move("west") ||
ranDirc == 0) // Won't move. (in case all rooms are full too)
return true;
}
}
else if (path == "chase")
{
// AI
string direction = chase(cur_pos);
if (direction != "wait")
move(direction);
}
return 0; //Never gonna reach here anyway.
}
// AI
// Using breadth first search
string grue::chase(Room* cur)
{
vis.assign(Game::mapHeight, vector<bool>(Game::mapWidth, false));
queue<pair<string,pair<int,int>>> q;
string dir[] = { "north", "south", "east", "west"};
if (cur->containsPlayer())
return "wait";
for (int i = 0; i < 4; i++)
{
if (cur->getLinked(dir[i]) &&
!cur->getLinked(dir[i])->isWall())
q.push(make_pair(dir[i], make_pair(cur->getLinked(dir[i])->getPosi(),
cur->getLinked(dir[i])->getPosj())));
if (cur->getLinked(dir[i]) &&
cur->getLinked(dir[i])->containsPlayer())
return "wait";
}
vis[cur->getPosi()][cur->getPosj()] = true;
while (!q.empty())
{
string cur_dir = q.front().first;
int cur_i = q.front().second.first, cur_j = q.front().second.second;
if (!vis[cur_i][cur_j])
{
vis[cur_i][cur_j] = true;
if (Game::rooms[cur_i][cur_j].containsPlayer())
return cur_dir;
else
for (int i = 0; i < 4; i++)
if (Game::rooms[cur_i][cur_j].getLinked(dir[i]) &&
!Game::rooms[cur_i][cur_j].getLinked(dir[i])->isWall())
q.push(make_pair(cur_dir, make_pair(Game::rooms[cur_i][cur_j].getLinked(dir[i])->getPosi(),
Game::rooms[cur_i][cur_j].getLinked(dir[i])->getPosj())));
}
q.pop();
}
return "north";
}
string grue::status()
{
cout << "Monster Name: " << name << ", Level: " << level << endl;
if (cur_pos != NULL)
cout << "at: " << cur_pos->getName() << endl;
else
cout << "Monster is not currently at any Room" << endl;
return "";
}
void grue::attack()
{
vector<Agent*> x = cur_pos->getSurroundAgent();
for(int i=0; i<x.size(); i++)
{
if(x[i]->getType() == "player1" ||
x[i]->getType() == "player2")
x[i]->setHealth(x[i]->getHealth()-getLevel());
}
}
| true |
99345811ff794859ab38cca91aaccc5628db85ef | C++ | chennj/HelloGame | /GameEngine/src/stuff/renderer/OrthographicCameraController.h | UTF-8 | 1,598 | 2.640625 | 3 | [] | no_license | #pragma once
#include "stuff\renderer\OrthographicCamera.h"
#include "stuff\core\Timestep.h"
#include "stuff\events\ApplicationEvent.h"
#include "stuff\events\KeyEvent.h"
#include "stuff\events\MouseEvent.h"
namespace SOMEENGINE
{
struct OrthographicCameraBounds
{
float Left, Right;
float Bottom, Top;
float GetWidth() { return Right - Left; }
float GetHeight() { return Top - Bottom; }
OrthographicCameraBounds& operator()(float l, float r, float b, float t)
{
this->Left = l;
this->Right = r;
this->Bottom = b;
this->Top = t;
return *this;
}
};
class OrthographicCameraController
{
private:
float _AspectRatio;
float _ZoomLevel = 1.0f;
OrthographicCamera _Camera;
OrthographicCameraBounds _Bounds;
bool _Rotation;
glm::vec3 _CameraPosition = { 0.0,0.0,0.0 };
float _CameraRotation = 0.0f;
float _CameraTranslationSpeed = 5.0f;
float _CameraRotationSpeed = 60.0f;
public:
OrthographicCameraController(float aspectRatio, bool rotation = false); // aspectratio * 2 units
public:
void OnUpdate(Timestep ts);
void OnEvent(Event& e);
void OnResize(float width, float height);
OrthographicCamera& GetCamera() { return _Camera; }
const OrthographicCamera& GetCamera() const { return _Camera; }
void SetZoomLevel(float level) { _ZoomLevel = level; CalculateView();}
float GetZoomLevel() const { return _ZoomLevel; }
const OrthographicCameraBounds& GetBounds()const { return _Bounds; }
private:
bool OnMouseScrolled(MouseScrolledEvent& e);
bool OnWindowResized(WindowResizeEvent& e);
void CalculateView();
};
} | true |
244d090b3fb828da079f767738bf7cf0d068e0ff | C++ | cmguo/QtJsonSerializer | /src/jsonserializer/typeconverters/qjsonmapconverter.cpp | UTF-8 | 2,042 | 2.53125 | 3 | [
"BSD-3-Clause"
] | permissive | #include "qjsonmapconverter_p.h"
#include "qjsonserializerexception.h"
#include <QtCore/QJsonObject>
const QRegularExpression QJsonMapConverter::mapTypeRegex(QStringLiteral(R"__(^(?:QMap|QHash)<\s*QString\s*,\s*(.*?)\s*>$)__"));
bool QJsonMapConverter::canConvert(int metaTypeId) const
{
return metaTypeId == QMetaType::QVariantMap ||
metaTypeId == QMetaType::QVariantHash ||
mapTypeRegex.match(QString::fromUtf8(getCanonicalTypeName(metaTypeId))).hasMatch();
}
QList<QJsonValue::Type> QJsonMapConverter::jsonTypes() const
{
return {QJsonValue::Object};
}
QJsonValue QJsonMapConverter::serialize(int propertyType, const QVariant &value, const QJsonTypeConverter::SerializationHelper *helper) const
{
auto metaType = getSubtype(propertyType);
auto cValue = value;
if(!cValue.convert(QVariant::Map)) {
throw QJsonSerializationException(QByteArray("Failed to convert type ") +
QMetaType::typeName(propertyType) +
QByteArray(" to a variant map. Make shure to register map types via QJsonSerializer::registerMapConverters"));
}
auto map = cValue.toMap();
QJsonObject object;
for(auto it = map.constBegin(); it != map.constEnd(); ++it)
object.insert(it.key(), helper->serializeSubtype(metaType, it.value(), it.key().toUtf8()));
return object;
}
QVariant QJsonMapConverter::deserialize(int propertyType, const QJsonValue &value, QObject *parent, const QJsonTypeConverter::SerializationHelper *helper) const
{
auto metaType = getSubtype(propertyType);
//generate the map
QVariantMap map;
auto object = value.toObject();
for(auto it = object.constBegin(); it != object.constEnd(); ++it)
map.insert(it.key(), helper->deserializeSubtype(metaType, it.value(), parent, it.key().toUtf8()));
return map;
}
int QJsonMapConverter::getSubtype(int mapType) const
{
int metaType = QMetaType::UnknownType;
auto match = mapTypeRegex.match(QString::fromUtf8(getCanonicalTypeName(mapType)));
if(match.hasMatch())
metaType = QMetaType::type(match.captured(1).toUtf8().trimmed());
return metaType;
}
| true |
69862266fa228afdff6f754ecc56684cb5b3c7e8 | C++ | lilingyu/didi2 | /didi2/main.cpp | UTF-8 | 1,765 | 3.1875 | 3 | [] | no_license | //解题思路:
/**
数字索引为begin,数字串长度n,数字最大和为maxsum
临时数字索引tmp_begin,数字串长度tmp_n,临时数字最大个tmp_maxsum
按顺序读取每一个字符,如果遇到数字,如果前面为字母,tmp_begin跟新为当前索引,数字串长度tmp_n加1,tmp_maxsum+=当前数字,如果tmp_maxsum大于maxsum,则用临时的数字索引,字符串长度,最大数更新最大的值
如果遇到字符,则tmp_begin,tmp_n,tmp_maxsum置为0
遍历一遍,将下标为begin长为n的数字串打印出来
**/
//
// main.cpp
// didi2
//
// Created by LiLingyu on 15/10/15.
// Copyright © 2015年 LiLingyu. All rights reserved.
//
#include <iostream>
#define MAXLEN 1000
void getmaxnum(char* a)
{
int begin = 0;
int n = 0;
int maxsum = 0;
int tmp_begin = -1;
int tmp_n = 0;
int tmp_maxsum = 0;
for (int i=0; ; i++) {
if (a[i]=='\0') {
break;
}
else if(a[i]>='0'&&a[i]<='9')//num
{
if (tmp_begin == -1) {
tmp_begin = i;
}
tmp_n++;
tmp_maxsum += a[i]-'0';
if (tmp_maxsum>maxsum) {
begin = tmp_begin;
n = tmp_n;
maxsum = tmp_maxsum;
}
}
else
{
tmp_begin = -1;
tmp_n = 0;
tmp_maxsum = 0;
}
}
for (int i=begin; i<begin+n; i++) {
printf("%c", a[i]);
}
printf("\n");
}
int main(int argc, const char * argv[]) {
char a[MAXLEN];
while (scanf("%s", a)!=EOF) {
getmaxnum(a);
}
return 0;
}
| true |
2345dd31c96df7ec6fa50a092329cb9b83bba5c9 | C++ | padhupradheep/basic_neo_relayboard_repo | /src/read.cpp | UTF-8 | 761 | 2.84375 | 3 | [] | no_license | #include<iostream>
#include <fcntl.h> // Contains file controls like O_RDWR
#include <termios.h> // Contains POSIX terminal control definitions
#include <unistd.h> // write(), read(), close()using namespace std;
#include <string.h>
#include <fstream>
#include <thread>
#include <math.h> /* pow */
#include <../include/SerialIO.h>
using namespace std;
int main(int argc, char const *argv[])
{
SerialIO m_serialPort;
// Setting up the serial communication
// int serial_port = open("/dev/ttyUSB0", O_RDWR | O_NONBLOCK);
unsigned char read_buf [32];
int num_bytes ;
while(m_serialPort.getSizeRXQueue() < 4)
{
usleep(2000);
}
cout<<"Waiting to read"<<endl;
num_bytes = m_serialPort.readNonBlocking((char*)&read_buf[4], 32);
cout<<num_bytes;
} | true |
debefc6553f09d519a0ee6d864208c9ea5ecdc74 | C++ | mirjalal/imtahan | /5.5.cpp | UTF-8 | 588 | 2.53125 | 3 | [] | no_license | // 5.5.cpp : Verilmiş mətndə verilmiş hərflə başlayan sözlərin sayını tapan proqram tərtib edin.
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int say = 0;
char herf[1], metn[1000];
char exclude[] = ",.!?\n\t@~'";
char *token;
cout << "Metni daxil edin: ";
cin >> metn;
cout << "Herfi daxil edin: ";
cin >> herf;
token = strtok_s(metn, exclude, NULL);
while (token != NULL)
{
if (token == herf)
say++;
token = strtok_s(NULL, exclude, NULL);
}
cout << """";
return 0;
}
| true |
63cd2cb0d030b8a124c879bdeae2ccb9a9ed982a | C++ | ap0h/Stablo | /binarno_stablo/Heap.h | UTF-8 | 2,369 | 3.484375 | 3 | [] | no_license | #pragma once
template<class T>
class Heap
{
private:
T * niz;
int duzina;
int br_elem; // ovo je promenljiva END koja drzi indeks poslednjeg cvora u stablu
void swap(T &a, T &b) { T pom = a; a = b; b = pom; }
public:
Heap(int n)
{
br_elem = 0;
duzina = n;
niz = new T[n];
}
Heap() :Heap(7)
{
}
void insert(T el)
{
int rod;
br_elem++;
int ptr = br_elem;
while (ptr > 1)
{
rod = ptr / 2;
if (el >= niz[rod])
{
niz[ptr] = el;
return;
}
niz[ptr] = niz[rod];
ptr = rod;
}
niz[1] = el;
}
int Delete()
{
T e = niz[1]; //pamtim koj brisem da bi ga vratila funkcija kad zavrsi sve
T posl = niz[br_elem];
br_elem--;
if (br_elem == -1)
throw "Heap je prazan!";
int rod = 1;
int levo = 2;
int desno = 3;
niz[1] = posl; // poslednji na mesto korena, jer njega brisem
while (desno <= br_elem) //sad uspotavljam svojstvo hipa ako je naruseno
{
if (niz[rod] < niz[levo] && niz[rod] <= niz[desno])//ako roditelj ima manju vrednost od dece onda izlazi iz funkcije sve je ok
{
return e;
}
if (niz[levo] < niz[desno])//ako jeste levi postaje roditelj
{
swap(niz[levo], niz[rod]);
rod = levo;
levo = 2 * rod;
desno = levo + 1;
}
else
{
swap(niz[desno], niz[rod]);
rod = desno;
levo = 2 * rod;
desno = levo + 1;
}
}
if (levo == br_elem && niz[rod] > niz[levo])
{
swap(niz[rod], niz[levo]);
}
return e;
}
void Sort(T *sortiran, int n)
{
//sortiran = new T[br_elem];
for (int i = 0; i < n; i++)
this->insert(sortiran[i]);
for (int i = 0; i < n; i++)
sortiran[i] = Delete();
}
void Update(int val, int add);
void ToMaxHeap()
{
}
};
template<class T>
void Heap<T>::Update(int val, int add)
{
int i = 1;
while (i <= br_elem && niz[i] != val)
i++;
if (i > br_elem) throw "Trazeni element ne postoji";
niz[i] += add;
if (i != 1)
{
if (niz[i] >= niz[i / 2]) return;
}
else
{
if (br_elem >= 3)
{
int rod = 1, levo = 2, desno = 3;
if (niz[levo] >= niz[desno])
{
swap(niz[desno], niz[rod]);
i = desno;
}
else
{
swap(niz[levo], niz[rod]);
i = levo;
}
}
}
bool dalje = true;
while (dalje)
{
if (niz[i] < niz[i / 2])
{
int pom = niz[i];
niz[i] = niz[i / 2];
niz[i / 2] = pom;
i /= 2;
}
else
dalje = false;
}
}
| true |
8dfa54fce3211000802b53e982d75b33c07e8aee | C++ | syoutetu/ColladaViewer_VC8 | /LinesElement.h | SHIFT_JIS | 617 | 2.515625 | 3 | [] | no_license |
#pragma once
#if !defined ___LinesElement_h___
#define ___LinesElement_h___
#include "BasePrimitive.h"
// <lines>Gg̏ۑNX
class LinesElement: public BasePrimitive
{
public:
LinesElement() {}
~LinesElement() {}
//============================================
// DomNodeReader C^[tF[X̎
//============================================
bool ValidElements(std::wstring& message) const { return BasePrimitive::ValidElements( message, L"lines" ); }
private:
};
typedef std::vector<LinesElement*> VECLINESELEM;
#endif //___LinesElement_h___ | true |
532a5e4ab4ac340dedfa49eb005239c8a7537729 | C++ | guoqing1988/Arduino | /StatsCounter/StatsCounter.ino | UTF-8 | 4,900 | 2.921875 | 3 | [] | no_license | #include <SoftwareSerial.h>
#include "LedControl.h"
// define the 7 segment LED display
#define NUM_LED_BOARDS 1
int LEDDataInPin = 7;
int LEDClkPin = 5;
int LEDLoadPin = 6;
LedControl lc=LedControl(LEDDataInPin,LEDClkPin,LEDLoadPin,NUM_LED_BOARDS);
// SoftwareSerial takes two parameters in the following order: RX pin, TX pin
// These are the pins that the Arduino will use to receive and transmit (repsectively)
// The Arduino RX pin should be connected to the Bluetooth TX pin
// The Arduino TX pin should be connected to the Bluetooth RX pin
// Therefore, it's easiest define variables to define which Arduino pins
// the bluetooth RX and TX pins are connected to.
// Then the SoftwareSerial port will be defined using the bluetoothTX pin
// for the Arduino RX pin, and the bluetoothRX pin for the Arduino TX pin.
int bluetoothTX = 10; // Note: pin 10 for the Arduino RX pin works on Uno, Mega, and Leonardo
int bluetoothRX = 11;
SoftwareSerial BT(bluetoothTX, bluetoothRX);
#define NUM_BUTTONS (2)
int buttonPins[NUM_BUTTONS] = { 2, 3 };
bool buttonState[NUM_BUTTONS];
bool lastButtonState[NUM_BUTTONS];
unsigned long lastDebounceTime[NUM_BUTTONS]; // the last time the output pin was toggled
unsigned long debounceDelay = 50; // the debounce time; increase if the output flickers
int count = 0;
void displayCount() {
// clear the display
lc.clearDisplay(0);
lc.setDigit(0, 0, count % 10, false);
if(count >= 10) {
lc.setDigit(0, 1, count / 10, false);
}
}
void setup()
{
// set up the pins for the buttons and initialize their prior state
for(int i = 0; i < NUM_BUTTONS; i++) {
pinMode(buttonPins[i], INPUT_PULLUP);
buttonState[i] = false;
lastButtonState[i] = false;
lastDebounceTime[i] = 0;
}
for(int i = 0; i < NUM_LED_BOARDS; i++) {
/*
The MAX72XX is in power-saving mode on startup,
we have to do a wakeup call
*/
lc.shutdown(i,false);
/* Set the brightness to a medium values */
lc.setIntensity(i,8);
/* and clear the display */
lc.clearDisplay(i);
}
displayCount();
// set digital pin to control as an output
pinMode(13, OUTPUT);
// set the data rate for the SoftwareSerial port
BT.begin(115200);
// Send test message to other device
BT.println("Hello from Arduino");
}
/*
This method will display the characters for the
word "Arduino" one after the other on digit 0.
*/
void writeArduinoOn7Segment() {
int delaytime = 1000;
lc.setChar(0,0,'a',false);
delay(delaytime);
lc.setRow(0,0,0x05);
delay(delaytime);
lc.setChar(0,0,'d',false);
delay(delaytime);
lc.setRow(0,0,0x1c);
delay(delaytime);
lc.setRow(0,0,B00010000);
delay(delaytime);
lc.setRow(0,0,0x15);
delay(delaytime);
lc.setRow(0,0,0x1D);
delay(delaytime);
lc.clearDisplay(0);
delay(delaytime);
}
void loop() {
for(int i = 0; i < NUM_BUTTONS; i++) {
// read the current state of the pin reading into a local variable
bool reading = (digitalRead(buttonPins[i]) == LOW ? true : false);
// check to see if you just pressed the button
// (i.e. the input went from LOW to HIGH), and you've waited long enough
// since the last press to ignore any noise:
// If the switch changed, due to noise or pressing:
if (reading != lastButtonState[i]) {
// reset the debouncing timer
lastDebounceTime[i] = millis();
}
if ((millis() - lastDebounceTime[i]) > debounceDelay) {
// whatever the reading is at, it's been there for longer than the debounce
// delay, so take it as the actual current state:
// if the button state has changed:
if (reading != buttonState[i]) {
buttonState[i] = reading;
// process the button press if the new state is pressed
if (buttonState[i]) {
// if this is an odd numbered button, decrement the count, otherwise increment the count
if((i % 2) == 0) {
count--;
}
else {
count++;
}
displayCount();
// transmit the new count over bluetooth
BT.print("count = ");
BT.println(count);
}
}
}
// save the reading. Next time through the loop, it'll be the lastButtonState:
lastButtonState[i] = reading;
}
}
//char a; // stores incoming character from other device
//void loop()
//{
// if (BT.available())
// // if text arrived in from BT serial...
// {
// a=(BT.read());
// if (a=='1')
// {
// digitalWrite(13, HIGH);
// BT.println(" LED on");
// }
// if (a=='2')
// {
// digitalWrite(13, LOW);
// BT.println(" LED off");
// }
// if (a=='?')
// {
// BT.println("Send '1' to turn LED on");
// BT.println("Send '2' to turn LED on");
// }
// // you can add more "if" statements with other characters to add more commands
// }
//}
| true |
c0ce4a2597f7348d45958dbb104f8eb1499dbc48 | C++ | SammyEnigma/CQCharts | /include/CQChartsArrowData.h | UTF-8 | 6,916 | 2.609375 | 3 | [
"MIT"
] | permissive | #ifndef CQChartsArrowData_H
#define CQChartsArrowData_H
#include <CQChartsLength.h>
#include <CQChartsAngle.h>
#include <CQUtilMeta.h>
class CQChartsNameValues;
/*!
* \brief Arrow Properties
* \ingroup Charts
*
* line width, front head, tail head, mid head
* angle, back angle, length and line ends
*/
class CQChartsArrowData {
public:
static void registerMetaType();
static int metaTypeId;
//---
CQUTIL_DEF_META_CONVERSIONS(CQChartsArrowData, metaTypeId)
public:
enum class HeadType {
NONE,
ARROW,
TRIANGLE,
STEALTH,
DIAMOND,
LINE
};
using Length = CQChartsLength;
using Angle = CQChartsAngle;
using Units = CQChartsUnits::Type;
public:
CQChartsArrowData() {
theadData_.visible = true;
}
explicit CQChartsArrowData(const QString &str) {
theadData_.visible = true;
(void) fromString(str);
}
//bool isRelative() const { return relative_; }
//void setRelative(bool b) { relative_ = b; }
const Length &lineWidth() const { return lineWidth_; }
void setLineWidth(const Length &l) { lineWidth_ = l; }
//---
// front head data
bool isFHead() const { return fheadData_.visible; }
void setFHead(bool b) { fheadData_.visible = b; }
HeadType fheadType() const { return fheadData_.type; }
void setFHeadType(HeadType type);
bool calcIsFHead() const { return (fheadType() != HeadType::NONE); }
const Angle &frontAngle() const { return fheadData_.angle; }
void setFrontAngle(const Angle &a) { fheadData_.angle = a; updateFrontBackAngle(); }
Angle calcFrontAngle() const { return (frontAngle().value() > 0 ? frontAngle() : Angle(45)); }
const Angle &frontBackAngle() const { return fheadData_.backAngle; }
void setFrontBackAngle(const Angle &a) { fheadData_.backAngle = a; }
Angle calcFrontBackAngle() const {
return (frontBackAngle().value() > 0 ? frontBackAngle() : Angle(90)); }
const Length &frontLength() const { return fheadData_.length; }
void setFrontLength(const Length &l) { fheadData_.length = l; }
Length calcFrontLength() const {
return (frontLength().value() > 0 ? frontLength() : Length::pixel(8)); }
bool isFrontLineEnds() const { return fheadData_.lineEnds; }
void setFrontLineEnds(bool b) { fheadData_.lineEnds = b; }
//---
// tail head data
bool isTHead() const { return theadData_.visible; }
void setTHead(bool b) { theadData_.visible = b; }
HeadType theadType() const { return theadData_.type; }
void setTHeadType(HeadType type);
bool calcIsTHead() const { return (theadType() != HeadType::NONE); }
const Angle &tailAngle() const { return theadData_.angle; }
void setTailAngle(const Angle &a) { theadData_.angle = a; updateTailBackAngle(); }
Angle calcTailAngle() const { return (tailAngle().value() > 0 ? tailAngle() : Angle(45)); }
const Angle &tailBackAngle() const { return theadData_.backAngle; }
void setTailBackAngle(const Angle &a) { theadData_.backAngle = a; }
Angle calcTailBackAngle() const {
return (tailBackAngle().value() > 0 ? tailBackAngle() : Angle(90));
}
const Length &tailLength() const { return theadData_.length; }
void setTailLength(const Length &l) { theadData_.length = l; }
Length calcTailLength() const {
return (tailLength().value() > 0 ? tailLength() : Length::pixel(8)); }
bool isTailLineEnds() const { return theadData_.lineEnds; }
void setTailLineEnds(bool b) { theadData_.lineEnds = b; }
//---
// mid head data
bool isMidHead() const { return midHeadData_.visible; }
void setMidHead(bool b) { midHeadData_.visible = b; }
HeadType midHeadType() const { return midHeadData_.type; }
void setMidHeadType(HeadType type);
bool calcIsMidHead() const { return (midHeadType() != HeadType::NONE); }
const Angle &midAngle() const { return midHeadData_.angle; }
void setMidAngle(const Angle &a) { midHeadData_.angle = a; updateMidBackAngle(); }
Angle calcMidAngle() const { return (midAngle().value() > 0 ? midAngle() : Angle(45)); }
const Angle &midBackAngle() const { return midHeadData_.backAngle; }
void setMidBackAngle(const Angle &a) { midHeadData_.backAngle = a; }
Angle calcMidBackAngle() const {
return (midBackAngle().value() > 0 ? midBackAngle() : Angle(90));
}
const Length &midLength() const { return midHeadData_.length; }
void setMidLength(const Length &l) { midHeadData_.length = l; }
Length calcMidLength() const {
return (midLength().value() > 0 ? midLength() : Length::pixel(8)); }
bool isMidLineEnds() const { return midHeadData_.lineEnds; }
void setMidLineEnds(bool b) { midHeadData_.lineEnds = b; }
//---
// consistent tail, mid and head angles
const Angle &angle() const { return tailAngle(); }
void setAngle(const Angle &a) { setFrontAngle(a); setTailAngle(a); }
const Angle &backAngle() const { return tailBackAngle(); }
void setBackAngle(const Angle &a) { setFrontBackAngle(a); setTailBackAngle(a); }
const Length &length() const { return tailLength(); }
void setLength(const Length &l) { setFrontLength(l); setTailLength(l); }
bool isLineEnds() const { return isTailLineEnds(); }
void setLineEnds(bool b) { setFrontLineEnds(b); setTailLineEnds(b); }
//---
bool isValid() const { return true; }
QString toString() const;
bool fromString(const QString &s);
void setNameValues(CQChartsNameValues &nameValues) const;
bool getNameValues(const CQChartsNameValues &nameValues);
//---
static bool getTypeAngles(const HeadType &type, Angle &angle, Angle &backAngle);
static bool checkTypeAngles(const HeadType &type, const Angle &angle, const Angle &backAngle);
static bool nameToData(const QString &name, HeadType &type, bool &lineEnds, bool &visible);
static bool dataToName(const HeadType &type, bool lineEnds, bool visible,
const Angle &angle, const Angle &backAngle, QString &name);
private:
void updateFrontBackAngle();
void updateTailBackAngle ();
void updateMidBackAngle ();
static bool getTypeBackAngle(const HeadType &type, const Angle &angle, Angle &backAngle);
private:
struct HeadData {
bool visible { false }; //!< draw arrow head
HeadType type { HeadType::NONE }; //!< arrow head type
Angle angle { -1 }; //!< arrow angle (default 45 if <= 0)
Angle backAngle { -1 }; //!< back angle (default 90 if <= 0)
Length length { "1V" }; //!< arrow length
bool lineEnds { false }; //!< lines at end
};
//bool relative_ { false }; //!< to point relative to from
Length lineWidth_ { Length::plot(-1) }; //!< connecting line width
HeadData fheadData_; //!< front head data
HeadData theadData_; //!< tail head data
HeadData midHeadData_; //!< mid head data
};
CQUTIL_DCL_META_TYPE(CQChartsArrowData)
#endif
| true |
eda9d7a5ac93576488c2f7355b5b58ef4c8cdb63 | C++ | 20080/Workspace2 | /subsequence.cpp | UTF-8 | 1,827 | 3.0625 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <bitset>
using namespace std;
vector<string> gss(string s) {
// write your code here
vector<string>ans;
for (int i = 0; i < (1 << s.size()); i++) {
string g = "", as = "";
bitset<64>b(i);
g = b.to_string();
// cout<<g<<endl;
int k = 0;
for (int i = 64 - s.size(); k < s.size(); i++) {
// cout<<g[i];
if (g[i] == '1')
as += s[k++];
else
k++;
}
// cout<<endl;
// int k=0;
// for(int j = 0; j<s.size();j++){
// if(i&1<<j){
// g+=s[j];
// }
// else
// k++;
// }
ans.push_back(as);
}
return ans;
}
int main() {
string s;
cin >> s;
vector<string> ans = gss(s);
int cnt = 0;
cout << '[';
for (string str : ans) {
if (cnt != ans.size() - 1)
cout << str << ", ";
else
cout << str;
cnt++;
}
cout << ']';
}
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<string> gss(string s) {
// write your code here
if (s.size() == 0) {
return {""};
}
char c = s[0];
string ss = s.substr(1);
vector<string>x = gss(ss);
vector<string>ans(1 << s.size());
int k = 0;
for (string a : x) {
ans[k++] = "" + a;
}
for (string a : x) {
ans[k++] = c + a;
}
return ans;
}
int main() {
string s;
cin >> s;
vector<string> ans = gss(s);
int cnt = 0;
cout << '[';
for (string str : ans) {
if (cnt != ans.size() - 1)
cout << str << ", ";
else
cout << str;
cnt++;
}
cout << ']';
} | true |