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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
ee31bd2a7d68ef6272fba2b8e0d3676c701cf7e3 | C++ | masakotoda/SakiPublic | /SakiColorGame/SakiColorGameServer/SakiColorGameServerEngine.cpp | UTF-8 | 1,738 | 2.6875 | 3 | [] | no_license | #include "stdafx.h"
#include "SakiColorGameTcpServer.h"
#include "SakiColorGameServerEngine.h"
CSakiColorGameServerEngine::CSakiColorGameServerEngine(void)
: m_nRedOwner(0)
, m_nGreenOwner(0)
, m_nBlueOwner(0)
{
m_pServer = new CSakiColorGameTcpServer(this);
::InitializeCriticalSection(&m_criticalSection);
}
CSakiColorGameServerEngine::~CSakiColorGameServerEngine(void)
{
::DeleteCriticalSection(&m_criticalSection);
}
void CSakiColorGameServerEngine::StartGame()
{
m_pServer->RunServer();
}
void CSakiColorGameServerEngine::EndGame()
{
m_pServer->ShutdownServer();
delete m_pServer;
}
void CSakiColorGameServerEngine::HandleMessage(CSakiColorGameTcpVisitor*pVisitor, const char* request, char* response, int size_response)
{
::EnterCriticalSection(&m_criticalSection);
strcpy_s(response, size_response, "OK");
if (strcmp(request, "Request Red") == 0)
{
if (m_nRedOwner != 0)
{
strcpy_s(response, size_response, "Someone else is using it.");
}
else
{
m_nRedOwner = pVisitor->GetVisitorId();
}
}
else if (strcmp(request, "Request Green") == 0)
{
if (m_nGreenOwner != 0)
{
strcpy_s(response, size_response, "Someone else is using it.");
}
else
{
m_nGreenOwner = pVisitor->GetVisitorId();
}
}
else if (strcmp(request, "Request Blue") == 0)
{
if (m_nBlueOwner != 0)
{
strcpy_s(response, size_response, "Someone else is using it.");
}
else
{
m_nBlueOwner = pVisitor->GetVisitorId();
}
}
else if (strcmp(request, "Return Red") == 0)
{
m_nRedOwner = 0;
}
else if (strcmp(request, "Return Green") == 0)
{
m_nGreenOwner = 0;
}
else if (strcmp(request, "Return Blue") == 0)
{
m_nBlueOwner = 0;
}
::LeaveCriticalSection(&m_criticalSection);
}
| true |
f67b3176b6a74c588fea21abb0c4c831bf4f6963 | C++ | wgnet/wds_qt | /qttools/src/assistant/3rdparty/clucene/src/CLucene/index/Term.h | UTF-8 | 4,544 | 2.578125 | 3 | [
"Apache-2.0",
"LGPL-2.1-only",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"LGPL-2.1-or-later",
"LicenseRef-scancode-unknown-license-reference",
"Qt-LGPL-exception-1.1",
"LGPL-3.0-only",
"GPL-3.0-only",
"GPL-2.0-only",
"GFDL-1.3-only",
"LicenseRef-scancode-digia-qt-preview",
"LicenseRef-scancod... | permissive | /*------------------------------------------------------------------------------
* Copyright (C) 2003-2006 Ben van Klinken and the CLucene Team
*
* Distributable under the terms of either the Apache License (Version 2.0) or
* the GNU Lesser General Public License, as specified in the COPYING file.
*
* Changes are Copyright (C) 2015 The Qt Company Ltd.
------------------------------------------------------------------------------*/
#ifndef _lucene_index_Term_
#define _lucene_index_Term_
#if defined(_LUCENE_PRAGMA_ONCE)
# pragma once
#endif
#include "CLucene/util/Misc.h"
#include "CLucene/util/StringIntern.h"
CL_NS_DEF(index)
/*
A Term represents a word from text. This is the unit of search. It is
composed of two elements, the text of the word, as a string, and the name of
the field that the text occured in, an interned string.
Note that terms may represent more than words from text fields, but also
things like dates, email addresses, urls, etc.
IMPORTANT NOTE:
Term inherits from the template class LUCENE_REFBASE which tries to do
some garbage collection by counting the references an instance has. As a result
of this construction you MUST use _CLDECDELETE(obj) when you want to delete an
of Term!
ABOUT intrn
intrn indicates if field and text are interned or not. Interning of Strings
is the process of converting duplicated strings to shared ones.
*/
class Term : LUCENE_REFBASE
{
private:
const TCHAR* _field;
bool internF; // Indicates if Term Field is interned(and therefore must be uninternd).
size_t cachedHashCode;
size_t textLen; // a cache of text len, this allows for a preliminary comparison of text lengths
#ifdef LUCENE_TERM_TEXT_LENGTH
TCHAR _text[LUCENE_TERM_TEXT_LENGTH + 1];
#else
TCHAR* _text;
size_t textLenBuf; //a cache of text len, this allows for a preliminary comparison of text lengths
#endif
void init();
public:
//uses the specified fieldTerm's field. this saves on intern'ing time.
Term(const Term* fieldTerm, const TCHAR* txt);
///Constructs a blank term
Term();
// TODO: need to be private, a few other things need to be changed first...
Term(const TCHAR* fld, const TCHAR* txt, bool internField);
/**
* Constructor. Constructs a Term with the given field and text. Field and
* text are not copied Field and text are deleted in destructor only if
* intern is false.
*/
Term(const TCHAR* fld, const TCHAR* txt);
///Destructor.
~Term();
///Returns the field of this term, an interned string. The field indicates
///the part of a document which this term came from.
const TCHAR* field() const; ///<returns reference
///Returns the text of this term. In the case of words, this is simply the
///text of the word. In the case of dates and other types, this is an
///encoding of the object as a string.
const TCHAR* text() const; ///<returns reference
///Resets the field and text of a Term.
inline void set(const TCHAR* fld, const TCHAR* txt)
{
set(fld, txt, true);
}
/**
* Optimized set of Term by reusing same field as this Term
* - avoids field.intern() overhead
* @param text The text of the new term
* (field is implicitly same as this Term instance)
*/
void set(const Term* term, const TCHAR* txt);
void set(const TCHAR* fld, const TCHAR* txt, bool internField);
/** Compares two terms, returning a negative integer if this
term belongs before the argument, zero if this term is equal to the
argument, and a positive integer if this term belongs after the argument.
The ordering of terms is first by field, then by text.*/
int32_t compareTo(const Term* other) const;
bool equals(const Term* other) const;
size_t textLength() const { return textLen; }
///Forms the contents of Field and term in some kind of tuple notation
///<field:text>
TCHAR* toString() const;
size_t hashCode();
class Equals:public CL_NS_STD(binary_function)<const Term*,const Term*,bool>
{
public:
bool operator()( const Term* val1, const Term* val2 ) const
{
return val1->equals(val2);
}
};
class Compare:LUCENE_BASE, public CL_NS(util)::Compare::_base //<Term*>
{
public:
bool operator()(Term* t1, Term* t2) const
{
return (t1->compareTo(t2) < 0);
}
size_t operator()(Term* t) const
{
return t->hashCode();
}
};
};
CL_NS_END
#endif
| true |
c6cb4ea14754ae128af56d427ec2b0160e220fed | C++ | duynhan39/Hackerrank | /acid naming.cpp | UTF-8 | 780 | 3 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main() {
int q;
cin>>q;
for(int each = 0; each < q; each++) {
string s = "";
cin>>s;
string head, tail;
head.assign(s, 0, 5);
tail.assign(s.end()-2, s.end());
int type = 0;
if(tail == "ic") {
type = 1;
if(head == "hydro") {
type = 2;
}
}
switch (type) {
case 0:
cout<<"not an acid"<<endl;
break;
case 1:
cout<<"polyatomic acid"<<endl;
break;
case 2:
cout<<"non-metal acid"<<endl;
break;
default:
break;
}
}
return 0;
}
| true |
817f6b9a7fea942136a29a4ebe4a0f8f079dff18 | C++ | shawnpringle/steemedit | /source/wxrichtextmdhandler.cpp | UTF-8 | 1,433 | 2.625 | 3 | [] | no_license | #include "wxrichtextmdhandler.h"
#include <iostream>
wxRichTextMDHandler::wxRichTextMDHandler(const wxString& name, const wxString& ext, int type)
: wxRichTextFileHandler(name, ext, type) {
//ctor
}
wxRichTextMDHandler::~wxRichTextMDHandler() {
//dtor
}
/// Can we handle this filename (if using files)? By default, checks the extension.
bool wxRichTextMDHandler::CanHandle(const wxString& filename) const {
return true;
}
/// Can we save using this handler?
bool wxRichTextMDHandler::CanSave() const {
return true;
}
/// Can we load using this handler?
bool wxRichTextMDHandler::CanLoad() const {
return false;
}
bool wxRichTextMDHandler::DoLoadFile(wxRichTextBuffer *buffer, wxInputStream& stream) {
return false;
}
bool wxRichTextMDHandler::DoSaveFile(wxRichTextBuffer *buffer, wxOutputStream& stream) {
wxRichTextCommand* cmd = buffer->GetBatchedCommand();
if (cmd == nullptr)
return false;
wxList action_list = cmd->GetActions();
for (wxObject * list_item : action_list) {
wxRichTextAction* action = dynamic_cast<wxRichTextAction*>(list_item);
if (action == nullptr) {
std::cerr << "OOPS!" << std::endl;
continue;
}
std::cerr << action->GetName() << std::endl;
// write to stream here.
}
// don't forget to override CanWrite() and return true here when this is finished.
return false;
}
| true |
a7f4f3b62fa64f24cace49cf9f17a93f6e0e8f78 | C++ | codedazzlers/DSA-Bootcamps | /Sawtantar/Strings/palindrome.cpp | UTF-8 | 419 | 3.3125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int length(string p)
{
int i = 0;
while (p[i])
{
i++;
}
return i;
}
int main()
{
string p, rev = "";
cout<<"Enter a value:";
cin >> p;
for (int j = length(p) - 1; j >= 0; j--)
rev += p[j];
{
if (rev == p)
cout << "It is a palindrome";
else
cout << "not a palindrome";
}
return 0;
} | true |
5ef1be08f248aa85630c53ebba6bbfe6707dda9b | C++ | kaitou-1412/A2OJ-Ladders | /Codeforces Division 2A/Ilya and Bank Account/main.cpp | UTF-8 | 372 | 2.75 | 3 | [] | no_license | #include <iostream>
#include <cmath>
using namespace std;
int main()
{
int n;
cin >> n;
if(n >= 0)
cout << n << "\n";
else
{
n = abs(n);
int v = ((n/10) < (10*(n/100) + n%10)) ? (n/10) : (10*(n/100) + n%10);
if(v == 0)
cout << "0\n";
else
cout << "-" << v << "\n";
}
return 0;
}
| true |
94edf3c9e450dd801077e93075ca5e2cfbf2c472 | C++ | fenix0111/Algorithm | /Leetcode/209. Minimum Size Subarray Sum/MinimumSizeSubarraySum.cpp | UTF-8 | 1,281 | 3.75 | 4 | [] | no_license | // Leetcode 209. Minimum Size Subarray Sum
// https://leetcode.com/problems/minimum-size-subarray-sum/description/
// Runtime: 8ms
// one pointer in front, another in rear.
// front pointer first move forward until sum of range [rear, front] is greater than or equal to s.
// then move rear pointer one step forward.
// repeat above steps until front pointer out of range or rear pointer passed the front pointer.
class Solution
{
public:
int minSubArrayLen(int s, vector<int>& nums)
{
if (nums.size() == 0)
{
return 0;
}
int front = 0;
int rear = 0;
int ret = INT_MAX;
int sum = 0;
while (front < nums.size() && rear <= front)
{
if (sum + nums[front] < s)
{
sum = sum + nums[front];
front++;
}
else
{
if (front - rear < ret)
{
ret = front - rear;
}
sum = sum - nums[rear];
rear++;
}
}
if (ret == INT_MAX)
{
ret = 0;
}
else
{
ret = ret + 1;
}
return ret;
}
};
| true |
0a6489141352fea35e766d08ceb62d8525212c32 | C++ | kirbyandrew/mr-signals | /src/apb_logic.h | UTF-8 | 3,234 | 2.953125 | 3 | [
"MIT"
] | permissive | /*
* apb_sensor.h
*
* Created on: Nov 23, 2018
* Author: ackpu
*/
#ifndef SRC_BASE_APB_SENSOR_H_
#define SRC_BASE_APB_SENSOR_H_
#include <vector>
#include "base/logic_interface.h"
#include "logic_collection.h"
#include "sensor_interface.h"
namespace mr_signals
{
/**
* A very simple APB logic implementation.
*
* The APB section is represented by a series of sensor inputs, listed in
* the order matching their physical implementation on the model railway.
*
* The logic maintains two 'tumbledown' sensors, one of which will become active
* when a train first enters the block of protected sensors in a direction
* opposite to which the sensor is 'protecting'.
*
* These sensors can then be included in all signals protecting
* the opposing direction of travel within the APB section.
*
* The sensors are then both cleared (set inactive) when none of the protected
* sensors are active.
*
* The sensors are enumerated in the following directions, with aliased access
* to the sensors in the following tumble-down directions
* Down (Up/Down roads)
* South (North/South roads)
* West (East/West routes)
*
* The logic will not work correctly if a train is in the block when the
* program is started (powered on).
*
* Example track arrangement
*
* | = signal between blocks (assumed to be on both sides for APB)
*
* --> = Down/South/West Direction
* <-- = Up/North/East Direction
* | sensor_1 | sensor_15 | sensor_3 |
*
* Logic_collection collection(1);
* Simple_apb apb_logic(collection, {&sensor_1, &sensor_15, & sensor 3});
*
* The add apb_logic.down_tumbledown() as a sensor to every signal protecting
* travel in the --> direction and apb_logic.up_tumbledown as a sensor to every
* signal protecting travel in the <--- direction
*/
class Simple_apb : public Logic_interface
{
public:
Simple_apb(Logic_collection& collection, std::initializer_list<Sensor_interface *> const & protected_sensors);
void loop() override;
Sensor_interface& down_tumbledown();
Sensor_interface& up_tumbledown();
protected:
std::vector<Sensor_interface*> protected_sensors_;
Sensor_base down_tumbledown_sensor;
Sensor_base up_tumbledown_sensor;
};
// Use otherwise regrettable #defines due to the lack of class function aliases
// TODO: Why aren't alias' working?
#define south_tumbledown down_tumbledown
#define north_tumbledown up_tumbledown
#define west_tumbledown down_tumbledown
#define east_tumbledown up_tumbledown
class Full_apb : public Logic_interface
{
public:
Full_apb(Logic_collection& collection, std::initializer_list<Sensor_interface *> const & protected_sensors);
void loop() override;
Sensor_interface& down_tumbledown_num(uint8_t num);
Sensor_interface& up_tumbledown_num(uint8_t num);
protected:
std::vector<Sensor_interface*> protected_sensors_;
std::vector<Sensor_interface*>::size_type num_sensors_; // protected_sensors_ count
// TODO: Should this be a vector or something else? Could even just be a simple array, are they iterated over?
std::vector<Sensor_base*> down_tumbledown_sensors_;
std::vector<Sensor_base*> up_tumbledown_sensors_;
};
}
#endif /* SRC_BASE_APB_SENSOR_H_ */
| true |
59e51338e43538a86164668e09a50bf248dd4ff0 | C++ | ncbi/sra-tools | /tools/loaders/sharq/hash/tiger.h | UTF-8 | 33,711 | 2.578125 | 3 | [
"LicenseRef-scancode-ncbi",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-us-govt-public-domain"
] | permissive | /*
* Chocobo1/Hash
*
* Copyright 2017-2020 by Mike Tzou (Chocobo1)
* https://github.com/Chocobo1/Hash
*
* Licensed under GNU General Public License 3 or later.
*
* @license GPL3 <https://www.gnu.org/licenses/gpl-3.0-standalone.html>
*/
#ifndef CHOCOBO1_TIGER_H
#define CHOCOBO1_TIGER_H
#include <array>
#include <cassert>
#include <climits>
#include <cmath>
#include <cstdint>
#include <initializer_list>
#include <string>
#include <type_traits>
#include <vector>
#if (__cplusplus > 201703L)
#include <version>
#endif
#ifndef USE_STD_SPAN_CHOCOBO1_HASH
#if (__cpp_lib_span >= 202002L)
#define USE_STD_SPAN_CHOCOBO1_HASH 1
#else
#define USE_STD_SPAN_CHOCOBO1_HASH 0
#endif
#endif
#if (USE_STD_SPAN_CHOCOBO1_HASH == 1)
#include <span>
#else
#include "gsl/span"
#endif
namespace Chocobo1
{
// Use these!!
// Tiger1_128();
// Tiger1_160();
// Tiger1_192();
// Tiger2_128();
// Tiger2_160();
// Tiger2_192();
}
namespace Chocobo1
{
// users should ignore things in this namespace
namespace Hash
{
#ifndef CONSTEXPR_CPP17_CHOCOBO1_HASH
#if __cplusplus >= 201703L
#define CONSTEXPR_CPP17_CHOCOBO1_HASH constexpr
#else
#define CONSTEXPR_CPP17_CHOCOBO1_HASH
#endif
#endif
#if (USE_STD_SPAN_CHOCOBO1_HASH == 1)
using IndexType = std::size_t;
#else
using IndexType = gsl::index;
#endif
#ifndef CHOCOBO1_HASH_BUFFER_IMPL
#define CHOCOBO1_HASH_BUFFER_IMPL
template <typename T, IndexType N>
class Buffer
{
public:
using value_type = T;
using index_type = IndexType;
using size_type = std::size_t;
constexpr Buffer() = default;
constexpr Buffer(const Buffer &) = default;
CONSTEXPR_CPP17_CHOCOBO1_HASH Buffer(const std::initializer_list<T> initList)
{
#if !defined(NDEBUG)
// check if out-of-bounds
static_cast<void>(m_array.at(m_dataEndIdx + initList.size() - 1));
#endif
for (const auto &i : initList)
{
m_array[m_dataEndIdx] = i;
++m_dataEndIdx;
}
}
template <typename InputIt>
constexpr Buffer(const InputIt first, const InputIt last)
{
for (InputIt iter = first; iter != last; ++iter)
{
this->fill(*iter);
}
}
constexpr T& operator[](const index_type pos)
{
return m_array[pos];
}
constexpr T operator[](const index_type pos) const
{
return m_array[pos];
}
CONSTEXPR_CPP17_CHOCOBO1_HASH void fill(const T &value, const index_type count = 1)
{
#if !defined(NDEBUG)
// check if out-of-bounds
static_cast<void>(m_array.at(m_dataEndIdx + count - 1));
#endif
for (index_type i = 0; i < count; ++i)
{
m_array[m_dataEndIdx] = value;
++m_dataEndIdx;
}
}
template <typename InputIt>
constexpr void push_back(const InputIt first, const InputIt last)
{
for (InputIt iter = first; iter != last; ++iter)
{
this->fill(*iter);
}
}
constexpr void clear()
{
m_array = {};
m_dataEndIdx = 0;
}
constexpr bool empty() const
{
return (m_dataEndIdx == 0);
}
constexpr size_type size() const
{
return m_dataEndIdx;
}
constexpr const T* data() const
{
return m_array.data();
}
private:
std::array<T, N> m_array {};
index_type m_dataEndIdx = 0;
};
#endif
namespace Tiger_NS
{
template <int V, int D> // version: [1, 2], digest size (bits): [128, 160, 192]
class Tiger
{
// https://www.cs.technion.ac.il/~biham/Reports/Tiger/
public:
using Byte = uint8_t;
using ResultArrayType = std::array<Byte, (D / 8)>;
#if (USE_STD_SPAN_CHOCOBO1_HASH == 1)
template <typename T, std::size_t Extent = std::dynamic_extent>
using Span = std::span<T, Extent>;
#else
template <typename T, std::size_t Extent = gsl::dynamic_extent>
using Span = gsl::span<T, Extent>;
#endif
constexpr Tiger();
constexpr void reset();
constexpr Tiger& finalize(); // after this, only `toArray()`, `toString()`, `toVector()`, `reset()` are available
std::string toString() const;
std::vector<Byte> toVector() const;
CONSTEXPR_CPP17_CHOCOBO1_HASH ResultArrayType toArray() const;
constexpr Tiger& addData(const Span<const Byte> inData);
constexpr Tiger& addData(const void *ptr, const std::size_t length);
template <std::size_t N>
constexpr Tiger& addData(const Byte (&array)[N]);
template <typename T, std::size_t N>
Tiger& addData(const T (&array)[N]);
template <typename T>
Tiger& addData(const Span<T> inSpan);
private:
constexpr void addDataImpl(const Span<const Byte> data);
static constexpr int BLOCK_SIZE = 64;
Buffer<Byte, (BLOCK_SIZE * 2)> m_buffer; // x2 for paddings
uint64_t m_sizeCounter = 0;
uint64_t m_h[3] = {};
static constexpr uint64_t tTable[4][256] =
{
{
0x02AAB17CF7E90C5E, 0xAC424B03E243A8EC, 0x72CD5BE30DD5FCD3, 0x6D019B93F6F97F3A, 0xCD9978FFD21F9193, 0x7573A1C9708029E2, 0xB164326B922A83C3, 0x46883EEE04915870,
0xEAACE3057103ECE6, 0xC54169B808A3535C, 0x4CE754918DDEC47C, 0x0AA2F4DFDC0DF40C, 0x10B76F18A74DBEFA, 0xC6CCB6235AD1AB6A, 0x13726121572FE2FF, 0x1A488C6F199D921E,
0x4BC9F9F4DA0007CA, 0x26F5E6F6E85241C7, 0x859079DBEA5947B6, 0x4F1885C5C99E8C92, 0xD78E761EA96F864B, 0x8E36428C52B5C17D, 0x69CF6827373063C1, 0xB607C93D9BB4C56E,
0x7D820E760E76B5EA, 0x645C9CC6F07FDC42, 0xBF38A078243342E0, 0x5F6B343C9D2E7D04, 0xF2C28AEB600B0EC6, 0x6C0ED85F7254BCAC, 0x71592281A4DB4FE5, 0x1967FA69CE0FED9F,
0xFD5293F8B96545DB, 0xC879E9D7F2A7600B, 0x860248920193194E, 0xA4F9533B2D9CC0B3, 0x9053836C15957613, 0xDB6DCF8AFC357BF1, 0x18BEEA7A7A370F57, 0x037117CA50B99066,
0x6AB30A9774424A35, 0xF4E92F02E325249B, 0x7739DB07061CCAE1, 0xD8F3B49CECA42A05, 0xBD56BE3F51382F73, 0x45FAED5843B0BB28, 0x1C813D5C11BF1F83, 0x8AF0E4B6D75FA169,
0x33EE18A487AD9999, 0x3C26E8EAB1C94410, 0xB510102BC0A822F9, 0x141EEF310CE6123B, 0xFC65B90059DDB154, 0xE0158640C5E0E607, 0x884E079826C3A3CF, 0x930D0D9523C535FD,
0x35638D754E9A2B00, 0x4085FCCF40469DD5, 0xC4B17AD28BE23A4C, 0xCAB2F0FC6A3E6A2E, 0x2860971A6B943FCD, 0x3DDE6EE212E30446, 0x6222F32AE01765AE, 0x5D550BB5478308FE,
0xA9EFA98DA0EDA22A, 0xC351A71686C40DA7, 0x1105586D9C867C84, 0xDCFFEE85FDA22853, 0xCCFBD0262C5EEF76, 0xBAF294CB8990D201, 0xE69464F52AFAD975, 0x94B013AFDF133E14,
0x06A7D1A32823C958, 0x6F95FE5130F61119, 0xD92AB34E462C06C0, 0xED7BDE33887C71D2, 0x79746D6E6518393E, 0x5BA419385D713329, 0x7C1BA6B948A97564, 0x31987C197BFDAC67,
0xDE6C23C44B053D02, 0x581C49FED002D64D, 0xDD474D6338261571, 0xAA4546C3E473D062, 0x928FCE349455F860, 0x48161BBACAAB94D9, 0x63912430770E6F68, 0x6EC8A5E602C6641C,
0x87282515337DDD2B, 0x2CDA6B42034B701B, 0xB03D37C181CB096D, 0xE108438266C71C6F, 0x2B3180C7EB51B255, 0xDF92B82F96C08BBC, 0x5C68C8C0A632F3BA, 0x5504CC861C3D0556,
0xABBFA4E55FB26B8F, 0x41848B0AB3BACEB4, 0xB334A273AA445D32, 0xBCA696F0A85AD881, 0x24F6EC65B528D56C, 0x0CE1512E90F4524A, 0x4E9DD79D5506D35A, 0x258905FAC6CE9779,
0x2019295B3E109B33, 0xF8A9478B73A054CC, 0x2924F2F934417EB0, 0x3993357D536D1BC4, 0x38A81AC21DB6FF8B, 0x47C4FBF17D6016BF, 0x1E0FAADD7667E3F5, 0x7ABCFF62938BEB96,
0xA78DAD948FC179C9, 0x8F1F98B72911E50D, 0x61E48EAE27121A91, 0x4D62F7AD31859808, 0xECEBA345EF5CEAEB, 0xF5CEB25EBC9684CE, 0xF633E20CB7F76221, 0xA32CDF06AB8293E4,
0x985A202CA5EE2CA4, 0xCF0B8447CC8A8FB1, 0x9F765244979859A3, 0xA8D516B1A1240017, 0x0BD7BA3EBB5DC726, 0xE54BCA55B86ADB39, 0x1D7A3AFD6C478063, 0x519EC608E7669EDD,
0x0E5715A2D149AA23, 0x177D4571848FF194, 0xEEB55F3241014C22, 0x0F5E5CA13A6E2EC2, 0x8029927B75F5C361, 0xAD139FABC3D6E436, 0x0D5DF1A94CCF402F, 0x3E8BD948BEA5DFC8,
0xA5A0D357BD3FF77E, 0xA2D12E251F74F645, 0x66FD9E525E81A082, 0x2E0C90CE7F687A49, 0xC2E8BCBEBA973BC5, 0x000001BCE509745F, 0x423777BBE6DAB3D6, 0xD1661C7EAEF06EB5,
0xA1781F354DAACFD8, 0x2D11284A2B16AFFC, 0xF1FC4F67FA891D1F, 0x73ECC25DCB920ADA, 0xAE610C22C2A12651, 0x96E0A810D356B78A, 0x5A9A381F2FE7870F, 0xD5AD62EDE94E5530,
0xD225E5E8368D1427, 0x65977B70C7AF4631, 0x99F889B2DE39D74F, 0x233F30BF54E1D143, 0x9A9675D3D9A63C97, 0x5470554FF334F9A8, 0x166ACB744A4F5688, 0x70C74CAAB2E4AEAD,
0xF0D091646F294D12, 0x57B82A89684031D1, 0xEFD95A5A61BE0B6B, 0x2FBD12E969F2F29A, 0x9BD37013FEFF9FE8, 0x3F9B0404D6085A06, 0x4940C1F3166CFE15, 0x09542C4DCDF3DEFB,
0xB4C5218385CD5CE3, 0xC935B7DC4462A641, 0x3417F8A68ED3B63F, 0xB80959295B215B40, 0xF99CDAEF3B8C8572, 0x018C0614F8FCB95D, 0x1B14ACCD1A3ACDF3, 0x84D471F200BB732D,
0xC1A3110E95E8DA16, 0x430A7220BF1A82B8, 0xB77E090D39DF210E, 0x5EF4BD9F3CD05E9D, 0x9D4FF6DA7E57A444, 0xDA1D60E183D4A5F8, 0xB287C38417998E47, 0xFE3EDC121BB31886,
0xC7FE3CCC980CCBEF, 0xE46FB590189BFD03, 0x3732FD469A4C57DC, 0x7EF700A07CF1AD65, 0x59C64468A31D8859, 0x762FB0B4D45B61F6, 0x155BAED099047718, 0x68755E4C3D50BAA6,
0xE9214E7F22D8B4DF, 0x2ADDBF532EAC95F4, 0x32AE3909B4BD0109, 0x834DF537B08E3450, 0xFA209DA84220728D, 0x9E691D9B9EFE23F7, 0x0446D288C4AE8D7F, 0x7B4CC524E169785B,
0x21D87F0135CA1385, 0xCEBB400F137B8AA5, 0x272E2B66580796BE, 0x3612264125C2B0DE, 0x057702BDAD1EFBB2, 0xD4BABB8EACF84BE9, 0x91583139641BC67B, 0x8BDC2DE08036E024,
0x603C8156F49F68ED, 0xF7D236F7DBEF5111, 0x9727C4598AD21E80, 0xA08A0896670A5FD7, 0xCB4A8F4309EBA9CB, 0x81AF564B0F7036A1, 0xC0B99AA778199ABD, 0x959F1EC83FC8E952,
0x8C505077794A81B9, 0x3ACAAF8F056338F0, 0x07B43F50627A6778, 0x4A44AB49F5ECCC77, 0x3BC3D6E4B679EE98, 0x9CC0D4D1CF14108C, 0x4406C00B206BC8A0, 0x82A18854C8D72D89,
0x67E366B35C3C432C, 0xB923DD61102B37F2, 0x56AB2779D884271D, 0xBE83E1B0FF1525AF, 0xFB7C65D4217E49A9, 0x6BDBE0E76D48E7D4, 0x08DF828745D9179E, 0x22EA6A9ADD53BD34,
0xE36E141C5622200A, 0x7F805D1B8CB750EE, 0xAFE5C7A59F58E837, 0xE27F996A4FB1C23C, 0xD3867DFB0775F0D0, 0xD0E673DE6E88891A, 0x123AEB9EAFB86C25, 0x30F1D5D5C145B895,
0xBB434A2DEE7269E7, 0x78CB67ECF931FA38, 0xF33B0372323BBF9C, 0x52D66336FB279C74, 0x505F33AC0AFB4EAA, 0xE8A5CD99A2CCE187, 0x534974801E2D30BB, 0x8D2D5711D5876D90,
0x1F1A412891BC038E, 0xD6E2E71D82E56648, 0x74036C3A497732B7, 0x89B67ED96361F5AB, 0xFFED95D8F1EA02A2, 0xE72B3BD61464D43D, 0xA6300F170BDC4820, 0xEBC18760ED78A77A
},
{
0xE6A6BE5A05A12138, 0xB5A122A5B4F87C98, 0x563C6089140B6990, 0x4C46CB2E391F5DD5, 0xD932ADDBC9B79434, 0x08EA70E42015AFF5, 0xD765A6673E478CF1, 0xC4FB757EAB278D99,
0xDF11C6862D6E0692, 0xDDEB84F10D7F3B16, 0x6F2EF604A665EA04, 0x4A8E0F0FF0E0DFB3, 0xA5EDEEF83DBCBA51, 0xFC4F0A2A0EA4371E, 0xE83E1DA85CB38429, 0xDC8FF882BA1B1CE2,
0xCD45505E8353E80D, 0x18D19A00D4DB0717, 0x34A0CFEDA5F38101, 0x0BE77E518887CAF2, 0x1E341438B3C45136, 0xE05797F49089CCF9, 0xFFD23F9DF2591D14, 0x543DDA228595C5CD,
0x661F81FD99052A33, 0x8736E641DB0F7B76, 0x15227725418E5307, 0xE25F7F46162EB2FA, 0x48A8B2126C13D9FE, 0xAFDC541792E76EEA, 0x03D912BFC6D1898F, 0x31B1AAFA1B83F51B,
0xF1AC2796E42AB7D9, 0x40A3A7D7FCD2EBAC, 0x1056136D0AFBBCC5, 0x7889E1DD9A6D0C85, 0xD33525782A7974AA, 0xA7E25D09078AC09B, 0xBD4138B3EAC6EDD0, 0x920ABFBE71EB9E70,
0xA2A5D0F54FC2625C, 0xC054E36B0B1290A3, 0xF6DD59FF62FE932B, 0x3537354511A8AC7D, 0xCA845E9172FADCD4, 0x84F82B60329D20DC, 0x79C62CE1CD672F18, 0x8B09A2ADD124642C,
0xD0C1E96A19D9E726, 0x5A786A9B4BA9500C, 0x0E020336634C43F3, 0xC17B474AEB66D822, 0x6A731AE3EC9BAAC2, 0x8226667AE0840258, 0x67D4567691CAECA5, 0x1D94155C4875ADB5,
0x6D00FD985B813FDF, 0x51286EFCB774CD06, 0x5E8834471FA744AF, 0xF72CA0AEE761AE2E, 0xBE40E4CDAEE8E09A, 0xE9970BBB5118F665, 0x726E4BEB33DF1964, 0x703B000729199762,
0x4631D816F5EF30A7, 0xB880B5B51504A6BE, 0x641793C37ED84B6C, 0x7B21ED77F6E97D96, 0x776306312EF96B73, 0xAE528948E86FF3F4, 0x53DBD7F286A3F8F8, 0x16CADCE74CFC1063,
0x005C19BDFA52C6DD, 0x68868F5D64D46AD3, 0x3A9D512CCF1E186A, 0x367E62C2385660AE, 0xE359E7EA77DCB1D7, 0x526C0773749ABE6E, 0x735AE5F9D09F734B, 0x493FC7CC8A558BA8,
0xB0B9C1533041AB45, 0x321958BA470A59BD, 0x852DB00B5F46C393, 0x91209B2BD336B0E5, 0x6E604F7D659EF19F, 0xB99A8AE2782CCB24, 0xCCF52AB6C814C4C7, 0x4727D9AFBE11727B,
0x7E950D0C0121B34D, 0x756F435670AD471F, 0xF5ADD442615A6849, 0x4E87E09980B9957A, 0x2ACFA1DF50AEE355, 0xD898263AFD2FD556, 0xC8F4924DD80C8FD6, 0xCF99CA3D754A173A,
0xFE477BACAF91BF3C, 0xED5371F6D690C12D, 0x831A5C285E687094, 0xC5D3C90A3708A0A4, 0x0F7F903717D06580, 0x19F9BB13B8FDF27F, 0xB1BD6F1B4D502843, 0x1C761BA38FFF4012,
0x0D1530C4E2E21F3B, 0x8943CE69A7372C8A, 0xE5184E11FEB5CE66, 0x618BDB80BD736621, 0x7D29BAD68B574D0B, 0x81BB613E25E6FE5B, 0x071C9C10BC07913F, 0xC7BEEB7909AC2D97,
0xC3E58D353BC5D757, 0xEB017892F38F61E8, 0xD4EFFB9C9B1CC21A, 0x99727D26F494F7AB, 0xA3E063A2956B3E03, 0x9D4A8B9A4AA09C30, 0x3F6AB7D500090FB4, 0x9CC0F2A057268AC0,
0x3DEE9D2DEDBF42D1, 0x330F49C87960A972, 0xC6B2720287421B41, 0x0AC59EC07C00369C, 0xEF4EAC49CB353425, 0xF450244EEF0129D8, 0x8ACC46E5CAF4DEB6, 0x2FFEAB63989263F7,
0x8F7CB9FE5D7A4578, 0x5BD8F7644E634635, 0x427A7315BF2DC900, 0x17D0C4AA2125261C, 0x3992486C93518E50, 0xB4CBFEE0A2D7D4C3, 0x7C75D6202C5DDD8D, 0xDBC295D8E35B6C61,
0x60B369D302032B19, 0xCE42685FDCE44132, 0x06F3DDB9DDF65610, 0x8EA4D21DB5E148F0, 0x20B0FCE62FCD496F, 0x2C1B912358B0EE31, 0xB28317B818F5A308, 0xA89C1E189CA6D2CF,
0x0C6B18576AAADBC8, 0xB65DEAA91299FAE3, 0xFB2B794B7F1027E7, 0x04E4317F443B5BEB, 0x4B852D325939D0A6, 0xD5AE6BEEFB207FFC, 0x309682B281C7D374, 0xBAE309A194C3B475,
0x8CC3F97B13B49F05, 0x98A9422FF8293967, 0x244B16B01076FF7C, 0xF8BF571C663D67EE, 0x1F0D6758EEE30DA1, 0xC9B611D97ADEB9B7, 0xB7AFD5887B6C57A2, 0x6290AE846B984FE1,
0x94DF4CDEACC1A5FD, 0x058A5BD1C5483AFF, 0x63166CC142BA3C37, 0x8DB8526EB2F76F40, 0xE10880036F0D6D4E, 0x9E0523C9971D311D, 0x45EC2824CC7CD691, 0x575B8359E62382C9,
0xFA9E400DC4889995, 0xD1823ECB45721568, 0xDAFD983B8206082F, 0xAA7D29082386A8CB, 0x269FCD4403B87588, 0x1B91F5F728BDD1E0, 0xE4669F39040201F6, 0x7A1D7C218CF04ADE,
0x65623C29D79CE5CE, 0x2368449096C00BB1, 0xAB9BF1879DA503BA, 0xBC23ECB1A458058E, 0x9A58DF01BB401ECC, 0xA070E868A85F143D, 0x4FF188307DF2239E, 0x14D565B41A641183,
0xEE13337452701602, 0x950E3DCF3F285E09, 0x59930254B9C80953, 0x3BF299408930DA6D, 0xA955943F53691387, 0xA15EDECAA9CB8784, 0x29142127352BE9A0, 0x76F0371FFF4E7AFB,
0x0239F450274F2228, 0xBB073AF01D5E868B, 0xBFC80571C10E96C1, 0xD267088568222E23, 0x9671A3D48E80B5B0, 0x55B5D38AE193BB81, 0x693AE2D0A18B04B8, 0x5C48B4ECADD5335F,
0xFD743B194916A1CA, 0x2577018134BE98C4, 0xE77987E83C54A4AD, 0x28E11014DA33E1B9, 0x270CC59E226AA213, 0x71495F756D1A5F60, 0x9BE853FB60AFEF77, 0xADC786A7F7443DBF,
0x0904456173B29A82, 0x58BC7A66C232BD5E, 0xF306558C673AC8B2, 0x41F639C6B6C9772A, 0x216DEFE99FDA35DA, 0x11640CC71C7BE615, 0x93C43694565C5527, 0xEA038E6246777839,
0xF9ABF3CE5A3E2469, 0x741E768D0FD312D2, 0x0144B883CED652C6, 0xC20B5A5BA33F8552, 0x1AE69633C3435A9D, 0x97A28CA4088CFDEC, 0x8824A43C1E96F420, 0x37612FA66EEEA746,
0x6B4CB165F9CF0E5A, 0x43AA1C06A0ABFB4A, 0x7F4DC26FF162796B, 0x6CBACC8E54ED9B0F, 0xA6B7FFEFD2BB253E, 0x2E25BC95B0A29D4F, 0x86D6A58BDEF1388C, 0xDED74AC576B6F054,
0x8030BDBC2B45805D, 0x3C81AF70E94D9289, 0x3EFF6DDA9E3100DB, 0xB38DC39FDFCC8847, 0x123885528D17B87E, 0xF2DA0ED240B1B642, 0x44CEFADCD54BF9A9, 0x1312200E433C7EE6,
0x9FFCC84F3A78C748, 0xF0CD1F72248576BB, 0xEC6974053638CFE4, 0x2BA7B67C0CEC4E4C, 0xAC2F4DF3E5CE32ED, 0xCB33D14326EA4C11, 0xA4E9044CC77E58BC, 0x5F513293D934FCEF,
0x5DC9645506E55444, 0x50DE418F317DE40A, 0x388CB31A69DDE259, 0x2DB4A83455820A86, 0x9010A91E84711AE9, 0x4DF7F0B7B1498371, 0xD62A2EABC0977179, 0x22FAC097AA8D5C0E
},
{
0xF49FCC2FF1DAF39B, 0x487FD5C66FF29281, 0xE8A30667FCDCA83F, 0x2C9B4BE3D2FCCE63, 0xDA3FF74B93FBBBC2, 0x2FA165D2FE70BA66, 0xA103E279970E93D4, 0xBECDEC77B0E45E71,
0xCFB41E723985E497, 0xB70AAA025EF75017, 0xD42309F03840B8E0, 0x8EFC1AD035898579, 0x96C6920BE2B2ABC5, 0x66AF4163375A9172, 0x2174ABDCCA7127FB, 0xB33CCEA64A72FF41,
0xF04A4933083066A5, 0x8D970ACDD7289AF5, 0x8F96E8E031C8C25E, 0xF3FEC02276875D47, 0xEC7BF310056190DD, 0xF5ADB0AEBB0F1491, 0x9B50F8850FD58892, 0x4975488358B74DE8,
0xA3354FF691531C61, 0x0702BBE481D2C6EE, 0x89FB24057DEDED98, 0xAC3075138596E902, 0x1D2D3580172772ED, 0xEB738FC28E6BC30D, 0x5854EF8F63044326, 0x9E5C52325ADD3BBE,
0x90AA53CF325C4623, 0xC1D24D51349DD067, 0x2051CFEEA69EA624, 0x13220F0A862E7E4F, 0xCE39399404E04864, 0xD9C42CA47086FCB7, 0x685AD2238A03E7CC, 0x066484B2AB2FF1DB,
0xFE9D5D70EFBF79EC, 0x5B13B9DD9C481854, 0x15F0D475ED1509AD, 0x0BEBCD060EC79851, 0xD58C6791183AB7F8, 0xD1187C5052F3EEE4, 0xC95D1192E54E82FF, 0x86EEA14CB9AC6CA2,
0x3485BEB153677D5D, 0xDD191D781F8C492A, 0xF60866BAA784EBF9, 0x518F643BA2D08C74, 0x8852E956E1087C22, 0xA768CB8DC410AE8D, 0x38047726BFEC8E1A, 0xA67738B4CD3B45AA,
0xAD16691CEC0DDE19, 0xC6D4319380462E07, 0xC5A5876D0BA61938, 0x16B9FA1FA58FD840, 0x188AB1173CA74F18, 0xABDA2F98C99C021F, 0x3E0580AB134AE816, 0x5F3B05B773645ABB,
0x2501A2BE5575F2F6, 0x1B2F74004E7E8BA9, 0x1CD7580371E8D953, 0x7F6ED89562764E30, 0xB15926FF596F003D, 0x9F65293DA8C5D6B9, 0x6ECEF04DD690F84C, 0x4782275FFF33AF88,
0xE41433083F820801, 0xFD0DFE409A1AF9B5, 0x4325A3342CDB396B, 0x8AE77E62B301B252, 0xC36F9E9F6655615A, 0x85455A2D92D32C09, 0xF2C7DEA949477485, 0x63CFB4C133A39EBA,
0x83B040CC6EBC5462, 0x3B9454C8FDB326B0, 0x56F56A9E87FFD78C, 0x2DC2940D99F42BC6, 0x98F7DF096B096E2D, 0x19A6E01E3AD852BF, 0x42A99CCBDBD4B40B, 0xA59998AF45E9C559,
0x366295E807D93186, 0x6B48181BFAA1F773, 0x1FEC57E2157A0A1D, 0x4667446AF6201AD5, 0xE615EBCACFB0F075, 0xB8F31F4F68290778, 0x22713ED6CE22D11E, 0x3057C1A72EC3C93B,
0xCB46ACC37C3F1F2F, 0xDBB893FD02AAF50E, 0x331FD92E600B9FCF, 0xA498F96148EA3AD6, 0xA8D8426E8B6A83EA, 0xA089B274B7735CDC, 0x87F6B3731E524A11, 0x118808E5CBC96749,
0x9906E4C7B19BD394, 0xAFED7F7E9B24A20C, 0x6509EADEEB3644A7, 0x6C1EF1D3E8EF0EDE, 0xB9C97D43E9798FB4, 0xA2F2D784740C28A3, 0x7B8496476197566F, 0x7A5BE3E6B65F069D,
0xF96330ED78BE6F10, 0xEEE60DE77A076A15, 0x2B4BEE4AA08B9BD0, 0x6A56A63EC7B8894E, 0x02121359BA34FEF4, 0x4CBF99F8283703FC, 0x398071350CAF30C8, 0xD0A77A89F017687A,
0xF1C1A9EB9E423569, 0x8C7976282DEE8199, 0x5D1737A5DD1F7ABD, 0x4F53433C09A9FA80, 0xFA8B0C53DF7CA1D9, 0x3FD9DCBC886CCB77, 0xC040917CA91B4720, 0x7DD00142F9D1DCDF,
0x8476FC1D4F387B58, 0x23F8E7C5F3316503, 0x032A2244E7E37339, 0x5C87A5D750F5A74B, 0x082B4CC43698992E, 0xDF917BECB858F63C, 0x3270B8FC5BF86DDA, 0x10AE72BB29B5DD76,
0x576AC94E7700362B, 0x1AD112DAC61EFB8F, 0x691BC30EC5FAA427, 0xFF246311CC327143, 0x3142368E30E53206, 0x71380E31E02CA396, 0x958D5C960AAD76F1, 0xF8D6F430C16DA536,
0xC8FFD13F1BE7E1D2, 0x7578AE66004DDBE1, 0x05833F01067BE646, 0xBB34B5AD3BFE586D, 0x095F34C9A12B97F0, 0x247AB64525D60CA8, 0xDCDBC6F3017477D1, 0x4A2E14D4DECAD24D,
0xBDB5E6D9BE0A1EEB, 0x2A7E70F7794301AB, 0xDEF42D8A270540FD, 0x01078EC0A34C22C1, 0xE5DE511AF4C16387, 0x7EBB3A52BD9A330A, 0x77697857AA7D6435, 0x004E831603AE4C32,
0xE7A21020AD78E312, 0x9D41A70C6AB420F2, 0x28E06C18EA1141E6, 0xD2B28CBD984F6B28, 0x26B75F6C446E9D83, 0xBA47568C4D418D7F, 0xD80BADBFE6183D8E, 0x0E206D7F5F166044,
0xE258A43911CBCA3E, 0x723A1746B21DC0BC, 0xC7CAA854F5D7CDD3, 0x7CAC32883D261D9C, 0x7690C26423BA942C, 0x17E55524478042B8, 0xE0BE477656A2389F, 0x4D289B5E67AB2DA0,
0x44862B9C8FBBFD31, 0xB47CC8049D141365, 0x822C1B362B91C793, 0x4EB14655FB13DFD8, 0x1ECBBA0714E2A97B, 0x6143459D5CDE5F14, 0x53A8FBF1D5F0AC89, 0x97EA04D81C5E5B00,
0x622181A8D4FDB3F3, 0xE9BCD341572A1208, 0x1411258643CCE58A, 0x9144C5FEA4C6E0A4, 0x0D33D06565CF620F, 0x54A48D489F219CA1, 0xC43E5EAC6D63C821, 0xA9728B3A72770DAF,
0xD7934E7B20DF87EF, 0xE35503B61A3E86E5, 0xCAE321FBC819D504, 0x129A50B3AC60BFA6, 0xCD5E68EA7E9FB6C3, 0xB01C90199483B1C7, 0x3DE93CD5C295376C, 0xAED52EDF2AB9AD13,
0x2E60F512C0A07884, 0xBC3D86A3E36210C9, 0x35269D9B163951CE, 0x0C7D6E2AD0CDB5FA, 0x59E86297D87F5733, 0x298EF221898DB0E7, 0x55000029D1A5AA7E, 0x8BC08AE1B5061B45,
0xC2C31C2B6C92703A, 0x94CC596BAF25EF42, 0x0A1D73DB22540456, 0x04B6A0F9D9C4179A, 0xEFFDAFA2AE3D3C60, 0xF7C8075BB49496C4, 0x9CC5C7141D1CD4E3, 0x78BD1638218E5534,
0xB2F11568F850246A, 0xEDFABCFA9502BC29, 0x796CE5F2DA23051B, 0xAAE128B0DC93537C, 0x3A493DA0EE4B29AE, 0xB5DF6B2C416895D7, 0xFCABBD25122D7F37, 0x70810B58105DC4B1,
0xE10FDD37F7882A90, 0x524DCAB5518A3F5C, 0x3C9E85878451255B, 0x4029828119BD34E2, 0x74A05B6F5D3CECCB, 0xB610021542E13ECA, 0x0FF979D12F59E2AC, 0x6037DA27E4F9CC50,
0x5E92975A0DF1847D, 0xD66DE190D3E623FE, 0x5032D6B87B568048, 0x9A36B7CE8235216E, 0x80272A7A24F64B4A, 0x93EFED8B8C6916F7, 0x37DDBFF44CCE1555, 0x4B95DB5D4B99BD25,
0x92D3FDA169812FC0, 0xFB1A4A9A90660BB6, 0x730C196946A4B9B2, 0x81E289AA7F49DA68, 0x64669A0F83B1A05F, 0x27B3FF7D9644F48B, 0xCC6B615C8DB675B3, 0x674F20B9BCEBBE95,
0x6F31238275655982, 0x5AE488713E45CF05, 0xBF619F9954C21157, 0xEABAC46040A8EAE9, 0x454C6FE9F2C0C1CD, 0x419CF6496412691C, 0xD3DC3BEF265B0F70, 0x6D0E60F5C3578A9E
},
{
0x5B0E608526323C55, 0x1A46C1A9FA1B59F5, 0xA9E245A17C4C8FFA, 0x65CA5159DB2955D7, 0x05DB0A76CE35AFC2, 0x81EAC77EA9113D45, 0x528EF88AB6AC0A0D, 0xA09EA253597BE3FF,
0x430DDFB3AC48CD56, 0xC4B3A67AF45CE46F, 0x4ECECFD8FBE2D05E, 0x3EF56F10B39935F0, 0x0B22D6829CD619C6, 0x17FD460A74DF2069, 0x6CF8CC8E8510ED40, 0xD6C824BF3A6ECAA7,
0x61243D581A817049, 0x048BACB6BBC163A2, 0xD9A38AC27D44CC32, 0x7FDDFF5BAAF410AB, 0xAD6D495AA804824B, 0xE1A6A74F2D8C9F94, 0xD4F7851235DEE8E3, 0xFD4B7F886540D893,
0x247C20042AA4BFDA, 0x096EA1C517D1327C, 0xD56966B4361A6685, 0x277DA5C31221057D, 0x94D59893A43ACFF7, 0x64F0C51CCDC02281, 0x3D33BCC4FF6189DB, 0xE005CB184CE66AF1,
0xFF5CCD1D1DB99BEA, 0xB0B854A7FE42980F, 0x7BD46A6A718D4B9F, 0xD10FA8CC22A5FD8C, 0xD31484952BE4BD31, 0xC7FA975FCB243847, 0x4886ED1E5846C407, 0x28CDDB791EB70B04,
0xC2B00BE2F573417F, 0x5C9590452180F877, 0x7A6BDDFFF370EB00, 0xCE509E38D6D9D6A4, 0xEBEB0F00647FA702, 0x1DCC06CF76606F06, 0xE4D9F28BA286FF0A, 0xD85A305DC918C262,
0x475B1D8732225F54, 0x2D4FB51668CCB5FE, 0xA679B9D9D72BBA20, 0x53841C0D912D43A5, 0x3B7EAA48BF12A4E8, 0x781E0E47F22F1DDF, 0xEFF20CE60AB50973, 0x20D261D19DFFB742,
0x16A12B03062A2E39, 0x1960EB2239650495, 0x251C16FED50EB8B8, 0x9AC0C330F826016E, 0xED152665953E7671, 0x02D63194A6369570, 0x5074F08394B1C987, 0x70BA598C90B25CE1,
0x794A15810B9742F6, 0x0D5925E9FCAF8C6C, 0x3067716CD868744E, 0x910AB077E8D7731B, 0x6A61BBDB5AC42F61, 0x93513EFBF0851567, 0xF494724B9E83E9D5, 0xE887E1985C09648D,
0x34B1D3C675370CFD, 0xDC35E433BC0D255D, 0xD0AAB84234131BE0, 0x08042A50B48B7EAF, 0x9997C4EE44A3AB35, 0x829A7B49201799D0, 0x263B8307B7C54441, 0x752F95F4FD6A6CA6,
0x927217402C08C6E5, 0x2A8AB754A795D9EE, 0xA442F7552F72943D, 0x2C31334E19781208, 0x4FA98D7CEAEE6291, 0x55C3862F665DB309, 0xBD0610175D53B1F3, 0x46FE6CB840413F27,
0x3FE03792DF0CFA59, 0xCFE700372EB85E8F, 0xA7BE29E7ADBCE118, 0xE544EE5CDE8431DD, 0x8A781B1B41F1873E, 0xA5C94C78A0D2F0E7, 0x39412E2877B60728, 0xA1265EF3AFC9A62C,
0xBCC2770C6A2506C5, 0x3AB66DD5DCE1CE12, 0xE65499D04A675B37, 0x7D8F523481BFD216, 0x0F6F64FCEC15F389, 0x74EFBE618B5B13C8, 0xACDC82B714273E1D, 0xDD40BFE003199D17,
0x37E99257E7E061F8, 0xFA52626904775AAA, 0x8BBBF63A463D56F9, 0xF0013F1543A26E64, 0xA8307E9F879EC898, 0xCC4C27A4150177CC, 0x1B432F2CCA1D3348, 0xDE1D1F8F9F6FA013,
0x606602A047A7DDD6, 0xD237AB64CC1CB2C7, 0x9B938E7225FCD1D3, 0xEC4E03708E0FF476, 0xFEB2FBDA3D03C12D, 0xAE0BCED2EE43889A, 0x22CB8923EBFB4F43, 0x69360D013CF7396D,
0x855E3602D2D4E022, 0x073805BAD01F784C, 0x33E17A133852F546, 0xDF4874058AC7B638, 0xBA92B29C678AA14A, 0x0CE89FC76CFAADCD, 0x5F9D4E0908339E34, 0xF1AFE9291F5923B9,
0x6E3480F60F4A265F, 0xEEBF3A2AB29B841C, 0xE21938A88F91B4AD, 0x57DFEFF845C6D3C3, 0x2F006B0BF62CAAF2, 0x62F479EF6F75EE78, 0x11A55AD41C8916A9, 0xF229D29084FED453,
0x42F1C27B16B000E6, 0x2B1F76749823C074, 0x4B76ECA3C2745360, 0x8C98F463B91691BD, 0x14BCC93CF1ADE66A, 0x8885213E6D458397, 0x8E177DF0274D4711, 0xB49B73B5503F2951,
0x10168168C3F96B6B, 0x0E3D963B63CAB0AE, 0x8DFC4B5655A1DB14, 0xF789F1356E14DE5C, 0x683E68AF4E51DAC1, 0xC9A84F9D8D4B0FD9, 0x3691E03F52A0F9D1, 0x5ED86E46E1878E80,
0x3C711A0E99D07150, 0x5A0865B20C4E9310, 0x56FBFC1FE4F0682E, 0xEA8D5DE3105EDF9B, 0x71ABFDB12379187A, 0x2EB99DE1BEE77B9C, 0x21ECC0EA33CF4523, 0x59A4D7521805C7A1,
0x3896F5EB56AE7C72, 0xAA638F3DB18F75DC, 0x9F39358DABE9808E, 0xB7DEFA91C00B72AC, 0x6B5541FD62492D92, 0x6DC6DEE8F92E4D5B, 0x353F57ABC4BEEA7E, 0x735769D6DA5690CE,
0x0A234AA642391484, 0xF6F9508028F80D9D, 0xB8E319A27AB3F215, 0x31AD9C1151341A4D, 0x773C22A57BEF5805, 0x45C7561A07968633, 0xF913DA9E249DBE36, 0xDA652D9B78A64C68,
0x4C27A97F3BC334EF, 0x76621220E66B17F4, 0x967743899ACD7D0B, 0xF3EE5BCAE0ED6782, 0x409F753600C879FC, 0x06D09A39B5926DB6, 0x6F83AEB0317AC588, 0x01E6CA4A86381F21,
0x66FF3462D19F3025, 0x72207C24DDFD3BFB, 0x4AF6B6D3E2ECE2EB, 0x9C994DBEC7EA08DE, 0x49ACE597B09A8BC4, 0xB38C4766CF0797BA, 0x131B9373C57C2A75, 0xB1822CCE61931E58,
0x9D7555B909BA1C0C, 0x127FAFDD937D11D2, 0x29DA3BADC66D92E4, 0xA2C1D57154C2ECBC, 0x58C5134D82F6FE24, 0x1C3AE3515B62274F, 0xE907C82E01CB8126, 0xF8ED091913E37FCB,
0x3249D8F9C80046C9, 0x80CF9BEDE388FB63, 0x1881539A116CF19E, 0x5103F3F76BD52457, 0x15B7E6F5AE47F7A8, 0xDBD7C6DED47E9CCF, 0x44E55C410228BB1A, 0xB647D4255EDB4E99,
0x5D11882BB8AAFC30, 0xF5098BBB29D3212A, 0x8FB5EA14E90296B3, 0x677B942157DD025A, 0xFB58E7C0A390ACB5, 0x89D3674C83BD4A01, 0x9E2DA4DF4BF3B93B, 0xFCC41E328CAB4829,
0x03F38C96BA582C52, 0xCAD1BDBD7FD85DB2, 0xBBB442C16082AE83, 0xB95FE86BA5DA9AB0, 0xB22E04673771A93F, 0x845358C9493152D8, 0xBE2A488697B4541E, 0x95A2DC2DD38E6966,
0xC02C11AC923C852B, 0x2388B1990DF2A87B, 0x7C8008FA1B4F37BE, 0x1F70D0C84D54E503, 0x5490ADEC7ECE57D4, 0x002B3C27D9063A3A, 0x7EAEA3848030A2BF, 0xC602326DED2003C0,
0x83A7287D69A94086, 0xC57A5FCB30F57A8A, 0xB56844E479EBE779, 0xA373B40F05DCBCE9, 0xD71A786E88570EE2, 0x879CBACDBDE8F6A0, 0x976AD1BCC164A32F, 0xAB21E25E9666D78B,
0x901063AAE5E5C33C, 0x9818B34448698D90, 0xE36487AE3E1E8ABB, 0xAFBDF931893BDCB4, 0x6345A0DC5FBBD519, 0x8628FE269B9465CA, 0x1E5D01603F9C51EC, 0x4DE44006A15049B7,
0xBF6C70E5F776CBB1, 0x411218F2EF552BED, 0xCB0C0708705A36A3, 0xE74D14754F986044, 0xCD56D9430EA8280E, 0xC12591D7535F5065, 0xC83223F1720AEF96, 0xC3A0396F7363A51F
}
};
};
template <int V, int D>
constexpr uint64_t Tiger<V, D>::tTable[4][256];
// helpers
template <typename T>
class Loader
{
// this class workaround loading data from unaligned memory boundaries
// also eliminate endianness issues
public:
explicit constexpr Loader(const uint8_t *ptr)
: m_ptr(ptr)
{
}
constexpr T operator[](const IndexType idx) const
{
static_assert(std::is_same<T, uint64_t>::value, "");
// handle specific endianness here
const uint8_t *ptr = m_ptr + (sizeof(T) * idx);
return ( (static_cast<T>(*(ptr + 0)) << 0)
| (static_cast<T>(*(ptr + 1)) << 8)
| (static_cast<T>(*(ptr + 2)) << 16)
| (static_cast<T>(*(ptr + 3)) << 24)
| (static_cast<T>(*(ptr + 4)) << 32)
| (static_cast<T>(*(ptr + 5)) << 40)
| (static_cast<T>(*(ptr + 6)) << 48)
| (static_cast<T>(*(ptr + 7)) << 56));
}
private:
const uint8_t *m_ptr;
};
template <typename R, typename T>
constexpr R ror(const T x, const unsigned int s)
{
static_assert(std::is_unsigned<R>::value, "");
static_assert(std::is_unsigned<T>::value, "");
return static_cast<R>(x >> s);
}
template <typename T>
constexpr T rotr(const T x, const unsigned int s)
{
static_assert(std::is_unsigned<T>::value, "");
if (s == 0)
return x;
return ((x >> s) | (x << ((sizeof(T) * 8) - s)));
}
//
template <int V, int D>
constexpr Tiger<V, D>::Tiger()
{
static_assert((CHAR_BIT == 8), "Sorry, we don't support exotic CPUs");
reset();
}
template <int V, int D>
constexpr void Tiger<V, D>::reset()
{
m_buffer.clear();
m_sizeCounter = 0;
m_h[0] = 0x0123456789ABCDEF;
m_h[1] = 0xFEDCBA9876543210;
m_h[2] = 0xF096A5B4C3B2E187;
}
template <int V, int D>
constexpr Tiger<V, D>& Tiger<V, D>::finalize()
{
m_sizeCounter += m_buffer.size();
// append 1 bit
m_buffer.fill((V == 1) ? 1 : (1 << 7));
// append paddings
const auto len = static_cast<int>(((2 * BLOCK_SIZE) - (m_buffer.size() + 8)) % BLOCK_SIZE);
m_buffer.fill(0, (len + 8));
// append size in bits
const uint64_t sizeCounterBits = m_sizeCounter * 8;
const uint32_t sizeCounterBitsL = ror<uint32_t>(sizeCounterBits, 0);
const uint32_t sizeCounterBitsH = ror<uint32_t>(sizeCounterBits, 32);
for (int i = 0; i < 4; ++i)
{
m_buffer[m_buffer.size() - 8 + i] = ror<Byte>(sizeCounterBitsL, (8 * i));
m_buffer[m_buffer.size() - 4 + i] = ror<Byte>(sizeCounterBitsH, (8 * i));
}
addDataImpl({m_buffer.data(), m_buffer.size()});
m_buffer.clear();
return (*this);
}
template <int V, int D>
std::string Tiger<V, D>::toString() const
{
const auto a = toArray();
std::string ret;
ret.resize(2 * a.size());
auto retPtr = &ret.front();
for (const auto c : a)
{
const Byte upper = ror<Byte>(c, 4);
*(retPtr++) = static_cast<char>((upper < 10) ? (upper + '0') : (upper - 10 + 'a'));
const Byte lower = c & 0xf;
*(retPtr++) = static_cast<char>((lower < 10) ? (lower + '0') : (lower - 10 + 'a'));
}
return ret;
}
template <int V, int D>
std::vector<typename Tiger<V, D>::Byte> Tiger<V, D>::toVector() const
{
const auto a = toArray();
return {a.begin(), a.end()};
}
template <int V, int D>
CONSTEXPR_CPP17_CHOCOBO1_HASH typename Tiger<V, D>::ResultArrayType Tiger<V, D>::toArray() const
{
const Span<const uint64_t> state(m_h);
const int dataSize = sizeof(typename decltype(state)::value_type);
ResultArrayType ret {};
auto retPtr = ret.data();
for (const auto i : state)
{
for (int j = 0, jMax = dataSize; j < jMax; ++j)
*(retPtr++) = ror<Byte>(i, (j * 8));
}
return ret;
}
template <int V, int D>
constexpr Tiger<V, D>& Tiger<V, D>::addData(const Span<const Byte> inData)
{
Span<const Byte> data = inData;
if (!m_buffer.empty())
{
const size_t len = std::min<size_t>((BLOCK_SIZE - m_buffer.size()), data.size()); // try fill to BLOCK_SIZE bytes
m_buffer.push_back(data.begin(), (data.begin() + len));
if (m_buffer.size() < BLOCK_SIZE) // still doesn't fill the buffer
return (*this);
addDataImpl({m_buffer.data(), m_buffer.size()});
m_buffer.clear();
data = data.subspan(len);
}
const size_t dataSize = data.size();
if (dataSize < BLOCK_SIZE)
{
m_buffer = {data.begin(), data.end()};
return (*this);
}
const size_t len = dataSize - (dataSize % BLOCK_SIZE); // align on BLOCK_SIZE bytes
addDataImpl(data.first(len));
if (len < dataSize) // didn't consume all data
m_buffer = {(data.begin() + len), data.end()};
return (*this);
}
template <int V, int D>
constexpr Tiger<V, D>& Tiger<V, D>::addData(const void *ptr, const std::size_t length)
{
// Span::size_type = std::size_t
return addData({static_cast<const Byte*>(ptr), length});
}
template <int V, int D>
template <std::size_t N>
constexpr Tiger<V, D>& Tiger<V, D>::addData(const Byte (&array)[N])
{
return addData({array, N});
}
template <int V, int D>
template <typename T, std::size_t N>
Tiger<V, D>& Tiger<V, D>::addData(const T (&array)[N])
{
return addData({reinterpret_cast<const Byte*>(array), (sizeof(T) * N)});
}
template <int V, int D>
template <typename T>
Tiger<V, D>& Tiger<V, D>::addData(const Span<T> inSpan)
{
return addData({reinterpret_cast<const Byte*>(inSpan.data()), inSpan.size_bytes()});
}
template <int V, int D>
constexpr void Tiger<V, D>::addDataImpl(const Span<const Byte> data)
{
assert((data.size() % BLOCK_SIZE) == 0);
m_sizeCounter += data.size();
for (size_t iter = 0, iend = static_cast<size_t>(data.size() / BLOCK_SIZE); iter < iend; ++iter)
{
const Loader<uint64_t> block(static_cast<const Byte *>(data.data() + (iter * BLOCK_SIZE)));
// TODO: tTable was here, move it back when static variable in constexpr function is allowed
uint64_t x[8] {};
for (int j = 0; j < 8; ++j)
x[j] = block[j];
const auto pass = [&x](uint64_t &a, uint64_t &b, uint64_t &c, const unsigned int mul) -> void
{
const auto round = [](uint64_t &a, uint64_t &b, uint64_t &c, const uint64_t x, const unsigned int mul) -> void
{
c ^= x;
a -= tTable[0][ror<Byte>(c, (0 * 8))] ^ tTable[1][ror<Byte>(c, (2 * 8))] ^ tTable[2][ror<Byte>(c, (4 * 8))] ^ tTable[3][ror<Byte>(c, (6 * 8))];
b += tTable[3][ror<Byte>(c, (1 * 8))] ^ tTable[2][ror<Byte>(c, (3 * 8))] ^ tTable[1][ror<Byte>(c, (5 * 8))] ^ tTable[0][ror<Byte>(c, (7 * 8))];
b *= mul;
};
round(a, b, c, x[0], mul);
round(b, c, a, x[1], mul);
round(c, a, b, x[2], mul);
round(a, b, c, x[3], mul);
round(b, c, a, x[4], mul);
round(c, a, b, x[5], mul);
round(a, b, c, x[6], mul);
round(b, c, a, x[7], mul);
};
const auto keySchedule = [&x]() -> void
{
x[0] -= x[7] ^ 0xA5A5A5A5A5A5A5A5;
x[1] ^= x[0];
x[2] += x[1];
x[3] -= x[2] ^ ((~x[1]) << 19);
x[4] ^= x[3];
x[5] += x[4];
x[6] -= x[5] ^ ((~x[4]) >> 23);
x[7] ^= x[6];
x[0] += x[7];
x[1] -= x[0] ^ ((~x[7]) << 19);
x[2] ^= x[1];
x[3] += x[2];
x[4] -= x[3] ^ ((~x[2]) >> 23);
x[5] ^= x[4];
x[6] += x[5];
x[7] -= x[6] ^ 0x0123456789ABCDEF;
};
// save_abc
uint64_t a = m_h[0];
uint64_t b = m_h[1];
uint64_t c = m_h[2];
uint64_t aa = m_h[0];
uint64_t bb = m_h[1];
uint64_t cc = m_h[2];
pass(a, b, c, 5);
keySchedule();
pass(c, a, b, 7);
keySchedule();
pass(b, c, a, 9);
// feedforward
m_h[0] = a ^ aa;
m_h[1] = b - bb;
m_h[2] = c + cc;
}
}
}
}
using Tiger1_128 = Hash::Tiger_NS::Tiger<1, 128>;
using Tiger1_160 = Hash::Tiger_NS::Tiger<1, 160>;
using Tiger1_192 = Hash::Tiger_NS::Tiger<1, 192>;
using Tiger2_128 = Hash::Tiger_NS::Tiger<2, 128>;
using Tiger2_160 = Hash::Tiger_NS::Tiger<2, 160>;
using Tiger2_192 = Hash::Tiger_NS::Tiger<2, 192>;
}
#endif // CHOCOBO1_TIGER_H
| true |
98e85bd7ab094e9b95029207873584bfa3de3668 | C++ | cyberplantru/pH-to-I2C-sample-code | /pHtoI2C_serial_test.ino | UTF-8 | 1,563 | 2.53125 | 3 | [] | no_license | #include <SoftwareSerial.h>
#include "Wire.h"
#define pHtoI2C 0x48
float voltage, data;
float pH;
byte highbyte, lowbyte, configRegister;
const int numReadings = 10;
float readings[numReadings]; // the readings from the analog input
int index = 0; // the index of the current reading
float total = 0; // the running total
float average = 0; // the average
void setup()
{
Wire.begin();
Serial.begin(9600);
}
void loop()
{
// Чтение pH
Wire.requestFrom(pHtoI2C, 3);
while(Wire.available()) // ensure all the data comes in
{
highbyte = Wire.read(); // high byte * B11111111
lowbyte = Wire.read(); // low byte
configRegister = Wire.read();
}
data = highbyte * 256;
data = data + lowbyte;
voltage = data * 2.048 ;
voltage = voltage / 327.68; // mV
total= total - readings[index];
readings[index] = ((-59.16 * voltage / (273.15 + 25)) + 7.0);
/*
pH = ((the slope of the electrode * voltage / (absolute zero + temp liquid)) + isopotential point)
for Calibration isopotential point change float 7.0 during the measurement.
for the slope of the electrode change float "-59.16" during the measurement pH 4.0 or pH 10.0
change float "25" for temperature compensation
*/
total= total + readings[index];
index = index + 1;
// if we're at the end of the array...
if (index >= numReadings)
// ...wrap around to the beginning:
index = 0;
average = total / numReadings;
pH = average;
Serial.println(pH);
delay(500);
}
| true |
21b813719ffca69622cd7753825a967b0730c4bb | C++ | danjia/voxelized-shadows-improved | /Source/Rendering/Overlay.hpp | UTF-8 | 1,022 | 2.5625 | 3 | [] | no_license | #pragma once
#define GL_GLEXT_PROTOTYPES 1 // Enables OpenGL 3 Features
#include <QGLWidget> // Links OpenGL Headers
#include <string>
using namespace std;
#include "Shader.hpp"
#include "Mesh.hpp"
#include "Camera.hpp"
#include "Texture.hpp"
class Overlay
{
public:
Overlay(const string &name, const string &shaderName, ShaderFeatureList shaderFeatures);
~Overlay();
// Overlay name (Shown in GUI)
string name() const { return name_; }
// Display settings
bool fullScreen() const { return fullScreen_; }
bool useBlending() const { return useBlending_; }
Texture* texture() const { return texture_; }
// Display setting setters
void setFullScreen(bool fullscreen);
void setUseBlending(bool blending);
void setTexture(Texture* texture);
// Draws the overlay to the current framebuffer
void draw(const Camera* camera);
private:
string name_;
Shader* shader_;
Texture* texture_;
bool fullScreen_;
bool useBlending_;
};
| true |
3cf3db535e0dd186ab89d4ad360cfce11e4c1ad1 | C++ | choreonoid/choreonoid | /src/Body/Imu.cpp | UTF-8 | 2,847 | 2.546875 | 3 | [
"Zlib",
"MIT"
] | permissive | #include "Imu.h"
#include "StdBodyFileUtil.h"
#include <cnoid/EigenArchive>
using namespace cnoid;
Imu::Imu()
: spec(new Spec)
{
spec->w_max.setConstant(std::numeric_limits<double>::max());
spec->dv_max.setConstant(std::numeric_limits<double>::max());
Imu::clearState();
}
Imu::Imu(const Imu& org, bool copyStateOnly)
: Device(org, copyStateOnly)
{
copyStateFrom(org);
if(!copyStateOnly){
spec.reset(new Spec);
if(org.spec){
spec->w_max = org.spec->w_max;
spec->dv_max = org.spec->dv_max;
} else {
spec->w_max.setConstant(std::numeric_limits<double>::max());
spec->dv_max.setConstant(std::numeric_limits<double>::max());
}
}
}
const char* Imu::typeName() const
{
return "Imu";
}
void Imu::copyStateFrom(const Imu& other)
{
w_ = other.w_;
dv_ = other.dv_;
}
void Imu::copyStateFrom(const DeviceState& other)
{
if(typeid(other) != typeid(Imu)){
throw std::invalid_argument("Type mismatch in the Device::copyStateFrom function");
}
copyStateFrom(static_cast<const Imu&>(other));
}
DeviceState* Imu::cloneState() const
{
return new Imu(*this, true);
}
Referenced* Imu::doClone(CloneMap*) const
{
return new Imu(*this);
}
void Imu::forEachActualType(std::function<bool(const std::type_info& type)> func)
{
if(!func(typeid(Imu))){
Device::forEachActualType(func);
}
}
void Imu::clearState()
{
w_.setZero();
dv_.setZero();
}
int Imu::stateSize() const
{
return 6;
}
const double* Imu::readState(const double* buf)
{
w_ = Eigen::Map<const Vector3>(buf);
dv_ = Eigen::Map<const Vector3>(buf + 3);
return buf + 6;
}
double* Imu::writeState(double* out_buf) const
{
Eigen::Map<Vector3>(out_buf) << w_;
Eigen::Map<Vector3>(out_buf + 3) << dv_;
return out_buf + 6;
}
bool Imu::readSpecifications(const Mapping* info)
{
read(info, "max_angular_velocity", spec->w_max);
read(info, "max_acceleration", spec->dv_max);
return true;
}
bool Imu::writeSpecifications(Mapping* info) const
{
if(!spec->w_max.isConstant(std::numeric_limits<double>::max())){
write(info, "max_angular_velocity", degree(spec->w_max));
}
if(!dv_max().isConstant(std::numeric_limits<double>::max())){
write(info, "max_acceleration", dv_max());
}
return true;
}
namespace {
StdBodyFileDeviceTypeRegistration<Imu>
registerHolderDevice(
"IMU",
[](StdBodyLoader* loader, const Mapping* info){
ImuPtr sensor = new Imu;
if(sensor->readSpecifications(info)){
return loader->readDevice(sensor, info);
}
return false;
},
[](StdBodyWriter* /* writer */, Mapping* info, const Imu* sensor)
{
return sensor->writeSpecifications(info);
});
}
| true |
3796a20010c7ffd35e2db30a706dd09d6f97195f | C++ | ITnull/VisualProject | /C_Plus/C_Plus/C_Plus.cpp | GB18030 | 439 | 2.578125 | 3 | [] | no_license | // C_Plus.cpp : ̨Ӧóڵ㡣
//
#include "stdafx.h"
#include<iostream>
using namespace std;
struct treeNode
{
int value;
treeNode *Left;
treeNode *Right;
};
enum Month{
One,Two,Three,Four,Five,Six,Seven,Eight,Night
};
int _tmain(int argc, _TCHAR* argv[])
{
enum Month obj = One;
//cout << obj << endl;
for (int i = 0; i < argc; i++)
cout << argv[i] << " "<<endl;
system("pause");
return 0;
}
| true |
aec93a1242591a1c64708b69689dcc1a9303dc22 | C++ | itpresidents/oF_bouncing_ball_objects_with_vectors | /ball_bounce_demo/src/testApp.cpp | UTF-8 | 3,045 | 2.9375 | 3 | [] | no_license | #include "testApp.h"
#include <iostream>
//--------------------------------------------------------------
void testApp::setup(){
ofBackground(20);
//let's populate our
for(int i = 0; i<3; i++){
ball b;
balls.push_back(b);
}
}
//--------------------------------------------------------------
void testApp::update(){
//iterate through all of the balls in the vector
for(int i = 0; i<balls.size(); i++){
balls[i].updateNum(i); // keep track of which number each ball is in the vector
balls[i].update();//update the position of the balls and check for collision with sides (all of this happens in the ball object's update method)
}
}
//--------------------------------------------------------------
void testApp::draw(){
//iterate through all of the balls in the vector
for(int i = 0; i<balls.size(); i++){
balls[i].draw();
}
ofDrawBitmapString("spacebar: add a ball", 100,ofGetHeight()-100);
ofDrawBitmapString("'f': remove ball from front of vector (first element)", 100,ofGetHeight()-75);
ofDrawBitmapString("'b': remove ball from back of vector (last element)", 100,ofGetHeight()-50);
}
//--------------------------------------------------------------
void testApp::keyPressed(int key){
//hit the spacebar to add a new ball to the vector
if(key == ' '){
ball b;
balls.push_back(b);
cout<<"there are now "<<balls.size()<<" balls"<<endl;//print # of palls
}
//hit 'f' to remove a ball from the front of the vector
if(key == 'f' && balls.size()!=0){
balls.erase(balls.begin());
cout<<"removed ball from the front of the vector"<<endl;
cout<<"there are now "<<balls.size()<<" balls"<<endl;
}
//hit 'b' to remove a ball from the back of the vector
if(key == 'b'&& balls.size()!=0){
balls.pop_back();
cout<<"removed ball from the back of the vector"<<endl;
cout<<"there are now "<<balls.size()<<" balls"<<endl;
}
}
//--------------------------------------------------------------
void testApp::keyReleased(int key){
}
//--------------------------------------------------------------
void testApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void testApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void testApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void testApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void testApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void testApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void testApp::dragEvent(ofDragInfo dragInfo){
} | true |
82c7624a62de7b673ba9c3de5184667107ff49f0 | C++ | oliverhamburger/Pizza-Tracker | /Driver.cpp | UTF-8 | 4,297 | 3.53125 | 4 | [] | no_license | //--------------------------------------------------------------------
//
// CS120 Final Project Driver.cpp
//
// Class definitions for the Driver class
//
// Author: Angelo Williams
// Date: 4/28/19
//
//--------------------------------------------------------------------
#include "Driver.h"
using namespace std;
Driver::Driver(string driverName)
// Pre: driverName, a string of the driver's name
// Post: Creates a new Driver object
{
name = driverName;
loggedIn = false;
totalDeliveries = 0;
totalMinDelivering = 0;
totalMinDriving = 0;
totalTips = 0;
driverStatus = 0;
}
void Driver::login() throw (logic_error)
// Pre: Driver is not logged in
// Post: Logs in the driver
{
if (loggedIn)
throw logic_error("Cannot log in an already logged in user.\n");
loggedIn = true;
}
void Driver::logout() throw (logic_error)
// Pre: Driver is not logged out
// Post: Logs out the driver
{
if (!loggedIn)
throw logic_error("Cannot log out an already logged out user.\n");
loggedIn = false;
}
void Driver::depart(Time time, Order* order) throw (logic_error)
// Pre: Driver is logged in
// Driver is at the restaurant
// Post: Sets a driver as out for delivery
// Records departure time
{
if (!loggedIn)
throw logic_error("A driver that is not logged in cannot make a delivery.\n");
if (driverStatus)
throw logic_error("A driver that is not at the restaurant cannot make a delivery.\n");
departureTime = time;
currentOrder = order;
currentOrder->depart();
driverStatus = 1;
}
void Driver::deliver(Time time, float tip) throw (logic_error)
// Pre: Driver is deliverying
// Tip must be non-negative
// Post: Sets a driver as returning from delivery
// Updates driver's stats
{
if (driverStatus != 1)
throw logic_error("A driver that is not out on a delivery cannot complete a delivery.\n");
if (tip < 0)
throw logic_error("A tip cannot be negative.\n");
totalTips += tip;
totalDeliveries += 1;
totalMinDelivering += time.elapsedMin(departureTime, time);
totalMinDriving += time.elapsedMin(departureTime, time);
departureTime = time;
currentOrder->deliver(time);
currentOrder = nullptr;
driverStatus = 2;
}
void Driver::arrive(Time time) throw (logic_error)
// Pre: Driver is returning from delivery
// Post: Sets a driver as back at the restaurant
// Updates driver's stats
{
if (driverStatus != 2)
throw logic_error("A driver that is not returning from a delivery cannot arrive at the restaurant.\n");
totalMinDriving += time.elapsedMin(departureTime, time);
driverStatus = 0;
}
string Driver::getName()
// Pre:
// Post: Returns the driver's name
{
return name;
}
void Driver::setName(string newName)
// Pre: newName, a string
// Post: Sets the driver's name to newName
{
name = newName;
}
bool Driver::isLoggedIn()
// Pre:
// Post: Returns true if the driver is logged in, false otherwise
{
return loggedIn;
}
int Driver::getTotalDeliveries()
// Pre:
// Post: Returns the total amount of deliveries
{
return totalDeliveries;
}
int Driver::getTotalMinDelivering()
// Pre:
// Post: Returns the total time spent deliverying
{
return totalMinDelivering;
}
int Driver::getTotalMinDriving()
// Pre:
// Post: Returns the total amount of time driving
{
return totalMinDriving;
}
float Driver::getTotalTips()
// Pre:
// Post: Returns the total amount of tips earned
{
return totalTips;
}
Order* Driver::getOrder() throw (logic_error)
// Pre: Driver is out for delivery
// Post: Returns the order being delivered
{
if (driverStatus == 0)
throw logic_error("A driver that is not out on a delivery cannot have an order.\n");
return currentOrder;
}
string Driver::toString()
// Pre:
// Post: Returns a string containing the driver's name, login status, and delivery status
{
string loginStr = (loggedIn ? "Logged in" : "Logged out");
string driverStatusStr;
if (driverStatus == 0)
driverStatusStr = "Currently at the restaurant";
else if (driverStatus == 1)
driverStatusStr = "Currently on a delivery. Left at " + departureTime.toString() + "\n" + " Current order: " + currentOrder->toString();
else if (driverStatus == 2)
driverStatusStr = "Currently returning to the restaurant";
return (" " + name + "\n " + loginStr + "\n " + driverStatusStr);
}
| true |
c023213964753762097d9116005e8a1bebaf8782 | C++ | Martin111997/Space_Invaders-WHS- | /Space_Invaders/Space_Invaders/Space_Invaders.cpp | ISO-8859-1 | 6,630 | 2.546875 | 3 | [] | no_license | #include "Space_Invaders.h"
using namespace std;
Space_Invaders::Space_Invaders(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
this->setFixedSize(Fenstergre_X, Fenstergre_Y); //Gre des MainWindow setzten
this->setWindowTitle("Space_Invaders"); //Fenstertitel
//---Label----
myLabel = new QLabel(this);
myLabel->setGeometry(10, 160, 160, 20); //x,y,w,h
QFont labelFont; // Gre der Schriftart auf dem Label setzen
labelFont.setPixelSize(14);
myLabel->setFont(labelFont);
//Timer
mytimer = new QTimer(this);
connect(mytimer, SIGNAL(timeout()), this, SLOT(mytimerSlot()), Qt::UniqueConnection);
mytimer->setInterval(10); //Timer wird alle 10ms erneuert => 100 Bilder pro Sekunde
mytimer->start(); //Gibt an, wann der Timer gestartet wird
//Gegnerkonstruktor 1
for (int sp = 0; sp < Gegner_Spalten; sp++) {
gegner[sp] = new Gegner(sp*(Fenstergre_X / Gegner_Spalten) + 10, 100, 70, 20); //x,y,b,h
}
//Gegnerkonstruktor 2
for (int sp_1 = 0; sp_1 < Gegner_Spalten_2; sp_1++) {
gegner2[sp_1] = new Gegner(sp_1*(Fenstergre_X / Gegner_Spalten_2) + 10, 60, 70, 20); //x,y,b,h
}
//Gegnerkonstruktor 3
for (int sp_2 = 0; sp_2 < Gegner_Spalten_3; sp_2++) {
gegner3[sp_2] = new Gegner(sp_2*(Fenstergre_X / Gegner_Spalten_2) + 10, 30, 70, 20); //x,y,b,h
}
//Hindernisskonstruktor
for (int sp1 = 0; sp1 < H_Spalten; sp1++) {
hindernisse[sp1] = new Hindernisse(sp1*(Fenstergre_X / H_Spalten) + 95, 600, 70, 30); //x,y,b,h
}
}
//void Space_Invaders::Spielerbewegung(QKeyEvent *event) {
// if (spieler_pos_x < 10) //verhindert das der Spieler aus dem Fenster geht, ist jetzt im KeyPressEvent
// {
// spieler_geschw_x = 0;
// }
// else if (spieler_pos_x > 990)
// {
// spieler_geschw_x = 0;
// }
//
//}
//Random Funktion, um zuflligen Schuss des Gegners auszulsen
void Space_Invaders::Gegner_Schussfunktion() {
}
//Erhht den Zhler spieler_treffer, wenn dieser getroffen wird
int Space_Invaders::Spieler_Treffer() {
if ((gegner_schuss_x > (spieler_pos_x - 15)) && (gegner_schuss_x < (spieler_pos_x + 15)) && (gegner_schuss_y > 970)) {
spieler_treffer++;
}
return spieler_treffer;
}
//Erhht die Punktzahl um 10 pro getroffenen Gegner, eventuell noch einen zeitabhngigen Wert einfgen, da sonst immer derselbe Highscore erreicht wird
int Space_Invaders::Punkte_erhhen() {
if (spieler_treffer++) {
punkte += 10;
}
return punkte;
}
//Wenn der Zhler Spieler_Treffer() grer oder gleich drei wird wird ein Label Game over gezeigt(hoffentlich)
int Space_Invaders::Game_Over() {
if (spieler_treffer >= 3) {
myLabel = new QLabel(this);
myLabel->setGeometry(10, 160, 160, 20);
myLabel->setText("Game Over");
}
return spieler_treffer;
}
void Space_Invaders::mytimerslot() {
//Prft,ob ein Gegnerreihe 1 getroffen wurde
for (int sp = 0; sp < Gegner_Spalten; sp++) {
if (gegner[sp]->st == sichtbar && ((spieler_schuss_y <= (gegner[sp]->y + gegner[sp]->h)) && (spieler_schuss_x >= gegner[sp]->x) && (spieler_schuss_x <= gegner[sp]->x + gegner[sp]->h)))
{
gegner[sp]->st == unsichtbar;
}
}
//Prft, ob Gegnerreihe 2 getroffen wurde
for (int sp_1 = 0; sp_1 < Gegner_Spalten_2; sp_1++) {
if (gegner2[sp_1]->st == sichtbar && ((spieler_schuss_y <= (gegner2[sp_1]->y + gegner2[sp_1]->h)) && (spieler_schuss_x >= gegner2[sp_1]->x) && (spieler_schuss_x <= gegner2[sp_1]->x + gegner2[sp_1]->h)))
{
gegner2[sp_1]->st == unsichtbar;
}
}
//Prft, ob Gegnerreihe 3 getroffen wurde
for (int sp_2 = 0; sp_2 < Gegner_Spalten_3; sp_2++) {
if (gegner3[sp_2]->st == sichtbar && ((spieler_schuss_y <= (gegner3[sp_2]->y + gegner3[sp_2]->h)) && (spieler_schuss_x >= gegner3[sp_2]->x) && (spieler_schuss_x <= gegner3[sp_2]->x + gegner3[sp_2]->h)))
{
gegner3[sp_2]->st == unsichtbar;
}
}
//Prft, ob ein Hinderniss getroffen wurde
for (int sp1 = 0; sp1 < H_Spalten; sp1++) {
if (hindernisse[sp1]->st == sichtbar && (spieler_schuss_y <= (hindernisse[sp1]->y1 + hindernisse[sp1]->h1) && spieler_schuss_y >= hindernisse[sp1]->y1))
{
hindernisse[sp1]->st == unsichtbar;
}
}
//Schuss lschen, wenn er das Fenster verlsst
if (spieler_schuss_y <= 0)
{
delete(this);
}
spieler_schuss_y -= Schussgeschwindigkeit;
repaint();
}
void Space_Invaders::keyPressEvent(QKeyEvent *event) {
//Spieler bewegt sich nach rechts
if ((event->key() == Qt::Key_Right) && (spieler_pos_x > 0) && (spieler_pos_x < 1170)) //!!!!!!!!!!!!!Spieler lsst sich nicht mehr bewegen, wenn er die Wand erreicht
{
spieler_pos_x += Spielergeschwindigkeit;
}
//Spieler bewegt sich nach links
if ((event->key() == Qt::Key_Left) && (spieler_pos_x > 0) && (spieler_pos_x < 1170)) //!!!!!!!!!!!!!Spieler lsst sich nicht mehr bewegen, wenn er die Wand erreicht
{
spieler_pos_x -= Spielergeschwindigkeit;
}
//Spieler schiet
if (event->key() == Qt::Key_Space)
{
spieler_schuss_y -= Schussgeschwindigkeit;
}
repaint();
}
void Space_Invaders::paintEvent(QPaintEvent *event) {
QPainter p(this);
//Spieler zeichnen
p.setPen(Qt::black);
p.setBrush(Qt::black);
p.drawRect(spieler_pos_x, spieler_pos_y, Spielerhhe, Spielerbreite);
//Schuss zeichnen
p.setPen(Qt::red);
p.setBrush(Qt::red);
p.drawRect(spieler_schuss_x, spieler_schuss_y, Schussbreite, Schusshhe);
//Gegnerreihe 1 zeichnen(Spalten)
for (int sp = 0; sp < Gegner_Spalten; sp++) {
if (gegner[sp]->st == sichtbar) {
p.setBrush(Qt::green);
p.drawRect(gegner[sp]->x, gegner[sp]->y, gegner[sp]->w, gegner[sp]->h);
}
}
//Gegnerreihe 2 zeichenen(Spalten)
for (int sp_1 = 0; sp_1 < Gegner_Spalten_2; sp_1++) {
if (gegner2[sp_1]->st == sichtbar) {
p.setBrush(Qt::red);
p.drawRect(gegner2[sp_1]->x, gegner2[sp_1]->y, gegner2[sp_1]->w, gegner2[sp_1]->h);
}
}
//Gegnerreihe 3 zeichnen(Spalten)
for (int sp_2 = 0; sp_2 < Gegner_Spalten_3; sp_2++) {
if (gegner3[sp_2]->st == sichtbar) {
p.setBrush(Qt::blue);
p.drawRect(gegner3[sp_2]->x, gegner3[sp_2]->y, gegner3[sp_2]->w, gegner3[sp_2]->h);
}
}
//Hindernisse zeichnen (Spalten)
for (int sp1 = 0; sp1 < H_Spalten; sp1++) {
if (hindernisse[sp1]->st == sichtbar) {
p.setBrush(Qt::green);
p.drawRect(hindernisse[sp1]->x1, hindernisse[sp1]->y1, hindernisse[sp1]->w1, hindernisse[sp1]->h1);
}
}
} | true |
afde652864b5ed39b5713e1fa7beef444a727809 | C++ | Shadowwws/AdventofCode2020 | /Day2/Day2.cpp | UTF-8 | 1,852 | 3.140625 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <chrono>
#include <string>
#include <fstream>
using namespace std;
using namespace std::chrono;
int countChar(string s, char c) {
int count = 0;
for (int i = 0; i < s.size(); i++)
if (s.at(i) == c)
count++;
return count;
}
int main(){
auto start = high_resolution_clock::now();
ifstream in;
in.open("Day2.txt");
string input[1000][4];
string tmp;
int first,second,third, resultat;
int i=0;
while (i<1000){
in >> tmp;
first = tmp.find('-');
input[i][0] = tmp.substr(0,first);
input[i][1] = tmp.substr(first+1,tmp.length());
in >> tmp;
input[i][2] = tmp.substr(0,1);
in >> tmp;
input[i][3] = tmp;
i++;
}
resultat = 0;
// Part 1
for (int j=0 ; j <1000 ; j++){
int a = stoi(input[j][0]);
int b = stoi(input[j][1]);
int count = countChar(input[j][3], (input[j][2].c_str())[0]);
if (count >= a && count <= b){
resultat ++;
}
}
cout << "Part 1 : " << resultat << endl;
//Part 2
resultat = 0;
for (int j=0 ; j <1000 ; j++){
int a = stoi(input[j][0]);
int b = stoi(input[j][1]);
if (input[j][3].at(a-1) == (input[j][2].c_str())[0] && input[j][3].at(b-1) != (input[j][2].c_str())[0]){
resultat ++;
}
if (input[j][3].at(a-1) != (input[j][2].c_str())[0] && input[j][3].at(b-1) == (input[j][2].c_str())[0]){
resultat ++;
}
}
cout << "Part 2 : " << resultat << endl;
auto stop = high_resolution_clock::now();
auto duration = duration_cast<microseconds>(stop - start);
cout << "Time taken by function: "
<< duration.count() << " microseconds" << endl;
return 0;
}
| true |
c7c7beb8e4c1ff4b2e41d8de919e9e3ad6b78ec8 | C++ | frankkopp/FrankyCPP | /src/common/ThreadPool.h | UTF-8 | 2,683 | 2.703125 | 3 | [] | no_license | // FrankyCPP
// Copyright (c) 2018-2021 Frank Kopp
//
// MIT License
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#ifndef FRANKYCPP_THREADPOOL_H
#define FRANKYCPP_THREADPOOL_H
#include <condition_variable>
#include <functional>
#include <future>
#include <iostream>
#include <queue>
#include <thread>
#include <vector>
/**
* ThreadPool implementation for executing functions in asynchronously with a
* predetermined number of threads.
*/
class ThreadPool {
using Task = std::function<void ()>;
std::vector<std::thread> mThreads{};
std::condition_variable mEventVar{};
std::mutex mEventMutex{};
bool mStopping = false;
std::queue<Task> mTasks{};
public:
/* Create a thread pool with the given number of threads. Threads are started
* directly and are waiting for tasks to be enqueued */
explicit ThreadPool (std::size_t numThreads);
/* stops the threads and removes the object */
~ThreadPool () { stop (); }
/* Enqueue a task to be executed in a thread. Task is usually provided as
* a lambda function */
template <class T>
auto enqueue (T task) -> std::future<decltype (task ())> {
auto wrapper = std::make_shared<std::packaged_task<decltype (task ()) ()>> (std::move (task));
{ // lock block
std::unique_lock<std::mutex> lock{ mEventMutex };
mTasks.emplace ([=] { (*wrapper) (); });
}
mEventVar.notify_one ();
return wrapper->get_future ();
}
/* Return the number of open (not started) tasks */
auto openTasks () { return mTasks.size (); }
private:
void start (std::size_t numThreads);
void stop ();
};
#endif // FRANKYCPP_THREADPOOL_H
| true |
503108581dfafb469bf61e4c80afa32482f0d0e8 | C++ | kimsezin/Algorithm | /프로그래머스_행렬테두리회전.cpp | UTF-8 | 1,603 | 3.03125 | 3 | [] | no_license | #include <string>
#include <vector>
using namespace std;
vector<int> solution(int rows, int columns, vector<vector<int>> queries) {
vector<int> answer;
vector<vector<int>> map(rows,vector<int>(columns));
int cnt = 1;
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
map[i][j] = cnt;
cnt++;
}
}
for (int k = 0; k < queries.size(); k++)
{
vector<vector<int>> copy_map = map;
int x1 = queries[k][0] - 1;
int y1 = queries[k][1] - 1;
int x2 = queries[k][2] - 1;
int y2 = queries[k][3] - 1;
int min_value = rows * columns;
for (int i = 1; i <= y2 - y1; i++)
{
map[x1][y1 + i] = copy_map[x1][y1 + i-1];
if (min_value > map[x1][y1 + i])
{
min_value = map[x1][y1 + i];
}
map[x2][y2 - i] = copy_map[x2][y2 - i+1];
if (min_value > map[x2][y2 - i])
{
min_value = map[x2][y2 - i];
}
}
for (int i = 0; i < x2 - x1; i++)
{
map[x1 + i][y1] = copy_map[x1 + i+1][y1];
if (min_value > map[x1 + i][y1])
{
min_value = map[x1 + i][y1];
}
map[x2 - i][y2] = copy_map[x2 - i-1][y2];
if (min_value > map[x2 - i][y2])
{
min_value = map[x2 - i][y2];
}
}
answer.push_back(min_value);
}
return answer;
}
int main()
{
solution(100, 97, { {1,1,100,97 }
});
} | true |
c149f390aed44056c1e84e01e7d2e43593a5b66e | C++ | tupieurods/SportProgramming | /CR104/CR104_A/main.cpp | UTF-8 | 513 | 2.71875 | 3 | [] | no_license | #include <stdio.h>
int main()
{
int n;
scanf("%d%*c", &n);
char str[59];
scanf("%s", str);
int c = n / 2 + 1;
int a[2] = {0, 0};
int index = 0;
for(int i = 1; i <= n; i++)
{
if(i == c)
{
index++;
}
if(str[i - 1] == '4' || str[i - 1] == '7')
{
a[index] += (int)(str[i - 1] - '0');
continue;
}
a[0] = -1;
break;
}
if(a[0] == a[1])
{
printf("YES\n");
}
else
{
printf("NO\n");
}
return 0;
} | true |
422bbb5e97ce498968fed5878b44b0f72d71cc9d | C++ | NitishShandilya/PracticeExercises | /VectorPractice.cpp | UTF-8 | 1,283 | 3.796875 | 4 | [] | no_license | #include <iostream>
using namespace std;
class RedoStructure
{
int a;
public:
RedoStructure():a(0){}
void setValue(const int newValue)
{ a = newValue; }
const int getValue() const
{ return a; }
};
class VectorPractice
{
RedoStructure *redoStructure;
int *structureNumbers;
public:
int size;
void allocate(const int size);
void resize(const int newSize);
void deallocate();
void print() const;
};
void VectorPractice::allocate(const int sizeToAllocate) {
redoStructure = (RedoStructure*)malloc(size*sizeof(class RedoStructure));
structureNumbers = (int*)malloc(size*sizeof(int));
size = sizeToAllocate;
}
void VectorPractice::resize(const int newSize) {
redoStructure = (RedoStructure*)realloc(redoStructure, newSize*sizeof(class RedoStructure));
structureNumbers = (int*)realloc(structureNumbers, newSize*sizeof(int));
size = newSize;
}
void VectorPractice::deallocate() {
if (redoStructure != NULL)
free(redoStructure);
if (structureNumbers != NULL)
free(structureNumbers);
}
void VectorPractice::print() const {
for (int i=0 ; i<size; ++i)
{
cout << "Address is: " << (redoStructure + i) << "Value is: " << (redoStructure + i)->getValue() << endl;
}
} | true |
8e5ade79fbb413cd69434bbdb8e663a7aa156dc5 | C++ | hello-sources/Coding-Training | /LeetCode/1817查找用户活跃分钟数.cpp | UTF-8 | 828 | 2.875 | 3 | [] | no_license | /**
* Note: The returned array must be malloced, assume caller calls free().
*/
int cmp(const void *a, const void *b) {
int *pa = *(int **)a, *pb = *(int **)b;
if (pa[0] == pb[0]) {
return pa[1] - pb[1];
}
return pa[0] - pb[0];
}
int* findingUsersActiveMinutes(int** logs, int logsSize, int* logsColSize, int k, int* returnSize){
int *res = (int *)malloc(sizeof(int) * k);
memset(res, 0, sizeof(int) * k);
qsort(logs, logsSize, sizeof(int *), cmp);
for (int i = 0; i < logsSize; ) {
int id = logs[i][0], cnt = 0;
while (i < logsSize && logs[i][0] == id) {
int time = logs[i][1];
while (i < logsSize && logs[i][0] == id && logs[i][1] == time) i++;
cnt++;
}
res[cnt - 1]++;
}
*returnSize = k;
return res;
} | true |
7d233c145a3e69df61e3a11e29412fd7f85e85c7 | C++ | kemot1709/Proi_Sklep | /Sklep.cpp | UTF-8 | 2,733 | 2.765625 | 3 | [] | no_license | #include "Sklep.h"
Sklep::Sklep(int n, int m, int o) {
int towar_ilosc = o;
sklep_ilosc_kas = n;
sklep_ilosc_pracownikow = m;
sklep_ilosc_klientow = 0;
sklep_stan = true;
sklep_utarg = 0;
sklep_klienci.clear();
sklep_kasy.reserve(n);
for(int i = 1; i <= n; i++) { // rezerwacja miejsca na kasy
sklep_kasy.push_back(Kasa(i));
}
sklep_pracownicy.reserve(m);
for(int i = 1; i <= m; i++) { // rezerwacja miejsca dla pracownikow
sklep_pracownicy.push_back(Pracownik(i));
}
sklep_towary.reserve(towar_ilosc);
int o1 = o / 3, o2 = o / 8, o3 = o / 5, o4 = o - o1 - o2 - o3;
int i = 0;
for(; i < o1; i++) { // rezerwacja miejsca na towary
sklep_towary.push_back(Towar_8(i));
}
for(; i < o1 + o2; i++) { // rezerwacja miejsca na towary
sklep_towary.push_back(Towar_51(i));
}
for(; i < o2 + o1 + o3; i++) { // rezerwacja miejsca na towary
sklep_towary.push_back(Towar_5(i));
}
for(; i < o; i++) { // rezerwacja miejsca na towary
sklep_towary.push_back(Towar_23(i));
}
}
int Sklep::sklep_f_ilosc_kas() {
return sklep_ilosc_kas;
}
int Sklep::sklep_f_ilosc_pracownikow() {
return sklep_ilosc_pracownikow;
}
int Sklep::sklep_f_ilosc_klientow() {
return sklep_ilosc_klientow;
}
bool Sklep::sklep_f_stan() {
return sklep_stan;
}
void Sklep::sklep_wszedl_klient() {
sklep_ilosc_klientow++;
sklep_klienci.push_back(sklep_ilosc_klientow);
}
void Sklep::sklep_nowy_dzien() {
sklep_klienci.clear(); // resetowanie stanu klientow
sklep_ilosc_klientow = 0;
for(int i = 0; i < sklep_ilosc_pracownikow; i++) { // resetowawnie stanu pracownikow
Pracownik prac = sklep_pracownik(i);
prac.pracownik_nowy_dzien();
sklep_akt_pracownik(i, prac);
}
for(int i = 0; i < sklep_ilosc_kas; i++) {
Kasa kasa = sklep_kasa(i);
kasa.kasa_reset();
kasa.kasa_f_zmien_sprzedawce(0);
sklep_akt_kasa(i, kasa);
}
}
Pracownik Sklep::sklep_pracownik(int n) {
return sklep_pracownicy[n];
}
Klient Sklep::sklep_klient(int n) {
return sklep_klienci[n];
}
Kasa Sklep::sklep_kasa(int n) {
return sklep_kasy[n];
}
Szkic_towar Sklep::sklep_towar(int n) {
return sklep_towary[n];
}
void Sklep::sklep_akt_pracownik(int i, Pracownik x) {
sklep_pracownicy[i] = x;
}
void Sklep::sklep_akt_klient(int i, Klient x) {
sklep_klienci [i] = x;
}
void Sklep::sklep_akt_kasa(int i, Kasa x) {
sklep_kasy[i] = x;
}
double Sklep::sklep_f_utarg() {
double ut = 0;
for(int i = 0; i < sklep_f_ilosc_kas(); i++) {
ut += sklep_kasy[i].kasa_f_utarg_netto();
}
sklep_utarg += ut;
return ut;
}
| true |
de7e7c8ad46d02b2c8786a5e36ee8b8e0cf16450 | C++ | EvanWang2015/Hackerrank | /StringConstruction.cpp | UTF-8 | 893 | 3.796875 | 4 | [] | no_license | /*
String Construction
Amanda has a string, s, of m lowercase letters that she wants to copy into a new string, p. She can perform the following operations any number of times to
construct string p:
1) Append a character to the end of string p at cost of 1 dollar.
2) Choose any substring of p and append it to the end of p at no charge.
*/
#include <bits/stdc++.h>
using namespace std;
int stringConstruction(string s){
// Complete this function
vector<int> sv;
sv.assign(26,0);
int op=0;
for(int i=0; i<s.size(); i++)
{
if(sv[s.at(i)-'a']==0)
{
sv[s.at(i)-'a']++;
op++;
}
}
return op;
}
int main() {
int q;
cin >> q;
for(int a0 = 0; a0 < q; a0++){
string s;
cin >> s;
int result = stringConstruction(s);
cout << result << endl;
}
return 0;
}
| true |
8e5fc3e9100fb771513b956fb3f9cd6c33acc1bc | C++ | oliverhuangchao/algorithm | /yelp/generalCase.cpp | UTF-8 | 533 | 2.9375 | 3 | [] | no_license | #include "basic.h"
void dfs(vector<string> &result,int step, string &path){
if(step == path.size()){
result.push_back(path);
return;
}
if(path[step] >= 97 && path[step] <= 122){
path[step] -= 32;
dfs(result,step+1,path);
path[step] += 32;
dfs(result,step+1,path);
}
else{
dfs(result,step+1,path);
}
return;
}
int main(){
string str;
cin>>str;
for(int i=0;i<str.size();i++){
if(str[i] < 97 && str[i] > 64)
str[i] += 32;
}
//print(str);
vector<string> res;
dfs(res,0,str);
print(res);
return 0;
}
| true |
f9d59e0291c9277b2308cefa5f237196b6815b45 | C++ | samlanth/Projet | /AS2018 etudiants/Brute.h | UTF-8 | 2,269 | 3.28125 | 3 | [] | no_license | ////////////////////////////////////////////////////////////
// Brute.h
//
// Déclaration de la classe CBrute qui représente
// un type de monstre
//
// Samuel Lanthier
// Création: 2018-05-15
// - CBrute - Dérive de CMonstre
////////////////////////////////////////////////////////////
#pragma once
#include <SFML/Graphics.hpp>
#include "Position.h"
#include "Carte.h"
#include "Personnage.h"
#include "Heros.h"
#include "Monstre.h"
//--------------------------------------------------------//
// CBrute
//--------------------------------------------------------//
// Dérive de la classe CMonstre;
class CBrute : public CMonstre
{
private:
// Ne possède aucun attribut
public:
////////////////////////////////////////////////////////////
// CBrute
//
// Un constructeur paramétrique qui prend les mêmes trois(3) paramètres
// et dans le même ordre que le constructeur paramétrique de la classe CMonstre;
//
// Intrants : Texture, position, et le nom
//
////////////////////////////////////////////////////////////
CBrute(sf::Texture& LaTexture, const CPosition& Pos, std::string nom);
////////////////////////////////////////////////////////////
// CBrute
//
// Redéfinit la méthode Attaquer qui prend une référence à un héros en paramètre
// et qui retourne true ou false
// La méthode Attaquer vérifie dans un premier temps si l’ennemi passé en paramètre
// est proche(voir la classe CPosition).Si c’est le cas, alors il y a une attaque.
// Si le Héros possède de la Défense, la Brute lui en enlève un point.
// Sinon, la Brute lui enlève un point de Vie
// Si le Héros est mort(s’il n’a plus de points de vie), la méthode retourne false,
// sinon elle retourne true.De plus, la méthode doit afficher à la console tous les
// détails de l’attaque ainsi que les caractéristiques finales du Héros
//
// Intrants : une référence à un héros en paramètre
// et qui retourne true ou false
//
// Extrant: Si le Héros est mort(s’il n’a plus de points de vie), la méthode retourne false,
// sinon elle retourne true
////////////////////////////////////////////////////////////
virtual bool Attaquer(CHeros& hero);
};
std::ostream& operator<<(std::ostream& os, const CBrute& h);
| true |
4f0b5db6a160bbda0f90c649abd6820ec333c764 | C++ | ronbaldona/CSE190S_Final | /Minimal/Player.h | UTF-8 | 2,057 | 2.765625 | 3 | [] | no_license | /* By Ronald Allan Baldonado
* Player class derived from Node.h
* Compatible with Scene Graph
*/
#pragma once
#ifndef _PLAYER_H_
#define _PLAYER_H_
#define GLFW_INCLUDE_GLEXT
#ifdef __APPLE__
#define GLFW_INCLUDE_GLCOREARB
#else
#include <GL/glew.h>
#endif
#include <GLFW/glfw3.h>
// Use of degrees is deprecated. Use radians instead.
#ifndef GLM_FORCE_RADIANS
#define GLM_FORCE_RADIANS
#endif
#include <glm/mat4x4.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <iostream>
#include <vector>
#include "Model.h"
#include "Bound.h"
class Player {
public:
/* Public functions */
Player(); // Default ctor
/* ctor for player object
* head - ptr to 3D head object
* hand - ptr to 3D hand object
* sword - ptr to 3D sword object
* playerType - true = Player 1, false = Player 2
*/
Player(Model * head, Model * hand, Model * sword, bool playerType);
~Player(); // Default dtor
int getScore();
// TODO: Add function to handle sword hits here
/* Player render function
* shader - glsl shader to send vertex and other info to for gfx
* P - projection matrix
* V - view matrix
* handTransform - hand transformation matrix
* headTransform - head transformation matrix
*/
void drawPlayer(Shader shader, glm::mat4 P, glm::mat4 V, glm::mat4 handTransform, glm::mat4 headTransform);
void drawPlayer(Shader shader, glm::mat4 P, glm::mat4 V, glm::mat4 hand_translate, glm::mat4 hand_rotate, glm::mat4 headTransform);
void drawBoundingBox(Shader shader, glm::mat4 P, glm::mat4 V, glm::mat4 handTransform);
float getSwordScaleFactor();
void updateBoundingBox(glm::mat4 transform_mat);
bool checkHit(Bound * toCompare);
private:
/* Private Data */
unsigned int score;
unsigned int playerType;
float sword_scale_factor; // Contains sword scale factor
std::vector<Model *> models; // Will store pointers to head and hand(s)
Bound * attack_box = NULL; // Sword hitbox
/* Private Functions */
void initialize(); // Resize and rotate everything to the correct position
};
#endif | true |
273f33f238d335bf394ccb4c408a75795e414115 | C++ | vanello/wifi-arsenal | /banjax/lib/metrics/metric.hpp | UTF-8 | 2,469 | 3.203125 | 3 | [] | no_license | /* -*- mode: C++; tab-width: 3; -*- */
/*
* Copyright 2011 NICTA
*
*/
#ifndef METRICS_METRIC_HPP
#define METRICS_METRIC_HPP
#include <net/buffer.hpp>
#include <boost/shared_ptr.hpp>
#include <iosfwd>
namespace metrics {
/**
* Alias for shared_ptr<metric>.
*/
typedef boost::shared_ptr<class metric> metric_sptr;
/**
* metric represents an estimation of some aspect of the network
* traffic. Concrete implementations may provide metrics for
* capacity/quality/utilization and so on.
*/
class metric {
public:
/**
* metric destructor.
*/
virtual ~metric() = 0;
/**
* Add a frame to the metric and update the metric statistics.
*
* \param b A shared_pointer to the buffer containing the frame.
*/
virtual void add(net::buffer_sptr b) = 0;
/**
* Return a pointer to a clone (deep copy) of this metric
* instance. The clone is allocated on the heap using new and
* the caller is responsible for ensuring it is deleted.
*
* \return A poiner to a new metric instance.
*/
virtual metric *clone() const = 0;
/**
* Compute the metric.
*
* \param time The 64 bit MAC time for the end of the time period.
* \param delta_us The time (in microseconds) since the start of the time period.
* \return The value of this metric as a double.
*/
virtual double compute(uint64_t time, uint32_t delta_us) = 0;
/**
* Reset the internal state of the metric.
*/
virtual void reset() = 0;
/**
* Write this object in human-readable form to ostream os.
*
* \param os A reference to the stream to write to.
*/
virtual void write(std::ostream& os) const = 0;
protected:
/**
* metric default constructor.
*/
metric();
/**
* metric copy constructor.
*/
metric(const metric& other);
/**
* metric copy constructor.
*/
metric& operator=(const metric& other);
};
/**
* operator to stream a metric to an ostream.
*
* \param os The stream to write to.
* \param m The metric to be streamed.
* \return A reference to the modified ostream.
*/
inline std::ostream& operator<<(std::ostream& os, const metric& m)
{
m.write(os);
return os;
}
}
#endif // METRICS_METRIC_HPP
| true |
1880d0d8485cdb8bc157cd05fb5e3ecb00000c6c | C++ | Seongmin-Hong/algorithm | /step4/5_test.cpp | UTF-8 | 1,245 | 3.109375 | 3 | [] | no_license | #include<stdio.h>
#include<math.h>
int pat() {
int i;
}
int bir(int x, int y) {
int arr1[8]{ 0, };
int arr2[8]{ 0, };
int j=0 , cnt = 0;
while (1) {
arr1[j] = x % 2;
x /= 2;
if (!x) break;
j++;
}
j = 0;
while (1) {
arr2[j] = y % 3;
y /= 3;
if (!y) break;
j++;
}
while (1) {
}
return 0;
}
int main() {
int n, m, sum_1 = 0, sum_2 = 0;
int i = 0, t = 10;
scanf("%d %d", &n, &m);
while (1) {
if (n%t) {
sum_1 += pow(2, i);
}
n /= t;
if (!n) break;
i++;
}
i = 0;
while (1) {
if (m%t) {
sum_2 += pow(3, i) * (m%t);
}
m /= t;
if (!m) break;
i++;
}
bir(sum_1, sum_2);
}
/*
#include<stdio.h>
int arr[31];
void pat(int a , int cnt, int n, int k) {
int i;
if (k < cnt) return;
if (a < n) {
arr[a] = 1;
pat(a + 1, cnt+1, n,k);
arr[a] = 0;
pat(a + 1, cnt, n,k);
}
if (k != cnt) return;
if (a == n) {
for (i = 0; i < n; i++) {
printf("%d", arr[i]);
}
printf("\n");
}
}
int main() {
int n, k;
scanf("%d %d", &n , &k);
pat(0,0,n,k);
}
*/ | true |
3d439b2af1421b3263e9e7b964d295c72224b879 | C++ | TLeonardUK/ZombieGrinder | /Source/Engine/Renderer/Null/Null_Texture.cpp | UTF-8 | 918 | 2.546875 | 3 | [] | no_license | // ===================================================================
// Copyright (C) 2013 Tim Leonard
// ===================================================================
#include "Engine/Renderer/Null/Null_Texture.h"
#include "Engine/Renderer/Textures/Pixelmap.h"
Null_Texture::Null_Texture(int width, int height, int pitch, TextureFormat::Type format, TextureFlags::Type flags)
: Texture(width, height, pitch, format)
, m_flags(flags)
{
}
Null_Texture::Null_Texture(Pixelmap* Pixelmap, TextureFlags::Type flags)
: Texture(Pixelmap)
, m_flags(flags)
{
}
Null_Texture::~Null_Texture()
{
if ((m_flags & TextureFlags::PersistSourceData) != 0)
{
m_Pixelmap = NULL;
}
}
void Null_Texture::Set_Pixelmap(Pixelmap* Pixelmap)
{
// Replace current buffer with new one.
if (Pixelmap != m_Pixelmap && (m_flags & TextureFlags::PersistSourceData) == 0)
{
SAFE_DELETE(m_Pixelmap);
m_Pixelmap = Pixelmap;
}
}
| true |
6d51d0c3e6269f413b2bbce40513cc413cacc7bb | C++ | hongyang1657/project_c | /serialTest2/serial.cc | UTF-8 | 4,064 | 2.609375 | 3 | [] | no_license | #include "serial.h"
const char *Serial_Dev = "/dev/ttyS0";
typedef struct {
char R_flag;
char W_flag;
int len;
char Data[255];
}Serial;
typedef struct {
int Forward;
int left;
int rotate;
unsigned char Check;
char Enter[3];
}Vehicle;
Vehicle Serial_Tx = {0,0,0,0,{"\r\n"}};
Serial Serial_D = {0,0,0,{0}};
int S_fd;
int wait_flag = 0;
int serial_send( int fd, char *Data );
int set_opt(int fd,int nSpeed,int nBits,char nEvent,int nStop);
void * Pthread_Serial( void *arg )
{
int n=0;
int ret;
struct termios oldstdio;
char Rx_Data[100];
char Tx_Data[50]={0};
S_fd = open( Serial_Dev, O_RDWR|O_NOCTTY );
if( -1==S_fd )
pthread_exit(NULL);
ret = set_opt(S_fd,115200,8,'N',1);
if(ret == -1)
{
pthread_exit(NULL);
}
while(1)
{
ret = read( S_fd, Rx_Data, 100);
if( ret >0 )
{
Serial_D.len = ret;
memset( Serial_D.Data, 0, Serial_D.len+3 );
memcpy( Serial_D.Data, Rx_Data, Serial_D.len );
printf("%s",Serial_D.Data);
}
else
{
usleep(100000);
sprintf( Tx_Data,"send %d\r\n", n++ );
serial_send( S_fd, Tx_Data );
//printf("send ok%d\r\n",n++);
}
}
pthread_exit(NULL);
}
int createSerialThread()
{
pthread_t pthread_id;
//Create a thread
pthread_create( &pthread_id, NULL, &Pthread_Serial, NULL );
usleep(1000);
if( -1==S_fd )
{
printf("error: cannot open serial dev\r\n");
return -1;
}
while(1)
{
usleep(1000);
}
return 0;
}
int serial_send( int fd, char *Data )
{
int string_num;
string_num = strlen(Data);
return write( S_fd,Data, string_num );
}
int set_opt(int fd,int nSpeed,int nBits,char nEvent,int nStop)
{
struct termios newtio,oldtio;
if(tcgetattr(fd,&oldtio)!=0)
{
perror("error:SetupSerial 3\n");
return -1;
}
bzero(&newtio,sizeof(newtio));
//使能串口接收
newtio.c_cflag |= CLOCAL | CREAD;
newtio.c_cflag &= ~CSIZE;
newtio.c_lflag &=~ICANON;//原始模式
//newtio.c_lflag |=ICANON; //标准模式
//设置串口数据位
switch(nBits)
{
case 7:
newtio.c_cflag |= CS7;
break;
case 8:
newtio.c_cflag |=CS8;
break;
}
//设置奇偶校验位
switch(nEvent)
{
case 'O':
newtio.c_cflag |= PARENB;
newtio.c_cflag |= PARODD;
newtio.c_iflag |= (INPCK | ISTRIP);
break;
case 'E':
newtio.c_iflag |= (INPCK | ISTRIP);
newtio.c_cflag |= PARENB;
newtio.c_cflag &= ~PARODD;
break;
case 'N':
newtio.c_cflag &=~PARENB;
break;
}
//设置串口波特率
switch(nSpeed)
{
case 2400:
cfsetispeed(&newtio,B2400);
cfsetospeed(&newtio,B2400);
break;
case 4800:
cfsetispeed(&newtio,B4800);
cfsetospeed(&newtio,B4800);
break;
case 9600:
cfsetispeed(&newtio,B9600);
cfsetospeed(&newtio,B9600);
break;
case 115200:
cfsetispeed(&newtio,B115200);
cfsetospeed(&newtio,B115200);
break;
case 460800:
cfsetispeed(&newtio,B460800);
cfsetospeed(&newtio,B460800);
break;
default:
cfsetispeed(&newtio,B9600);
cfsetospeed(&newtio,B9600);
break;
}
//设置停止位
if(nStop == 1)
newtio.c_cflag &= ~CSTOPB;
else if(nStop == 2)
newtio.c_cflag |= CSTOPB;
newtio.c_cc[VTIME] = 1;
newtio.c_cc[VMIN] = 0;
tcflush(fd,TCIFLUSH);
if(tcsetattr(fd,TCSANOW,&newtio)!=0)
{
perror("com set error\n");
return -1;
}
return 0;
}
| true |
8e36fb074f5182011cee56e79348fa057b26d3fa | C++ | Rukopet/CPP_modules | /day03/ex04/SuperTrap.hpp | UTF-8 | 399 | 2.546875 | 3 | [] | no_license | #ifndef EX04_SUPERTRAP_HPP
#define EX04_SUPERTRAP_HPP
#include "FragTrap.hpp"
#include "NinjaTrap.hpp"
class SuperTrap : public FragTrap, public NinjaTrap {
public:
SuperTrap(const std::string &name);
SuperTrap(SuperTrap const &other);
SuperTrap();
virtual ~SuperTrap();
SuperTrap &operator=(const SuperTrap& trap);
private:
std::string _announcePrefix();
};
#endif //EX04_SUPERTRAP_HPP
| true |
6b2363aeff34d09b3e1985c302c5b62eae6f73c3 | C++ | andrei828/Arduino | /Lab_Homeworks/4Digit7SegmentDisplayJoystick.ino | UTF-8 | 4,306 | 2.734375 | 3 | [] | no_license | #define LOCKED_DIGIT 1
#define BROWSE_DIGITS 0
// joystick pins
const int pinX = A0;
const int pinY = A1;
const int pinSW = 0;
// 4 digit 7 segment display pins
const int pinA = 12;
const int pinB = 8;
const int pinC = 5;
const int pinD = 3;
const int pinE = 2;
const int pinF = 11;
const int pinG = 6;
const int pinDP = 4;
const int pinD1 = 7;
const int pinD2 = 9;
const int pinD3 = 10;
const int pinD4 = 13;
// state variables
int currentDigit = 0;
int state = BROWSE_DIGITS;
// imutable variables
const int segSize = 8;
const int noOfDigits = 10;
const int noOfDisplays = 4;
// mutable values
int blink = 0;
int xValue = 0;
int yValue = 0;
int dpState = LOW;
int swState = LOW;
int lastSwState = LOW;
int joyStickToggleX = 0;
int joyStickToggleY = 0;
unsigned long lastIncreasing = 0;
unsigned long delayBlinkTime = 300;
// segments array, similar to before
int segments[segSize] = {
pinA, pinB, pinC, pinD, pinE, pinF, pinG, pinDP
};
// digits array, to switch between them easily
int digits[noOfDisplays] = {
pinD1, pinD2, pinD3, pinD4
};
// values of the four digits
unsigned int digitArray[noOfDisplays] = { 0, 0, 0, 0 };
// digits for 7 segement display
byte digitMatrix[noOfDigits + 1][segSize - 1] = {
// a b c d e f g
{1, 1, 1, 1, 1, 1, 0}, // 0
{0, 1, 1, 0, 0, 0, 0}, // 1
{1, 1, 0, 1, 1, 0, 1}, // 2
{1, 1, 1, 1, 0, 0, 1}, // 3
{0, 1, 1, 0, 0, 1, 1}, // 4
{1, 0, 1, 1, 0, 1, 1}, // 5
{1, 0, 1, 1, 1, 1, 1}, // 6
{1, 1, 1, 0, 0, 0, 0}, // 7
{1, 1, 1, 1, 1, 1, 1}, // 8
{1, 1, 1, 1, 0, 1, 1}, // 9
{0, 0, 0, 0, 0, 0, 0} // NULL
};
void displayNumber(byte digit, byte decimalPoint) {
for (int i = 0; i < segSize - 1; i++)
digitalWrite(segments[i], digitMatrix[digit][i]);
// write the decimalPoint to DP pin
digitalWrite(segments[segSize - 1], decimalPoint);
}
// activate the display no. received as param
void showDigit(int num) {
for (int i = 0; i < noOfDisplays; i++)
digitalWrite(digits[i], HIGH);
digitalWrite(digits[num], LOW);
}
void setup() {
pinMode(pinSW, INPUT_PULLUP);
for (int i = 0; i < segSize - 1; i++)
pinMode(segments[i], OUTPUT);
for (int i = 0; i < noOfDisplays; i++)
pinMode(digits[i], OUTPUT);
Serial.begin(9600);
}
void displayArray() {
for (int i = 0; i < noOfDisplays; i++) {
showDigit(i);
if (i == currentDigit)
displayNumber(digitArray[i], HIGH);
else
displayNumber(digitArray[i], LOW);
delay(5);
}
}
void loop() {
// input values
xValue = analogRead(pinX);
yValue = analogRead(pinY);
swState = digitalRead(pinSW);
// change push button state
if (swState != lastSwState) {
if (swState == LOW) {
dpState = !dpState;
}
}
lastSwState = swState;
// update output here
if (state == BROWSE_DIGITS) {
if (yValue < 400 && joyStickToggleY == 0) {
joyStickToggleY = 1;
if (++currentDigit > 3)
currentDigit = 0;
} else if (yValue > 600 && joyStickToggleY == 0) {
joyStickToggleY = 1;
if (--currentDigit < 0)
currentDigit = 3;
}
else if (yValue >= 400 && yValue <= 600) {
joyStickToggleY = 0;
}
// switch state
if (dpState == HIGH) {
dpState = !dpState;
state = LOCKED_DIGIT;
}
displayArray();
} else if (state == LOCKED_DIGIT) {
if (xValue < 400 && joyStickToggleX == 0) {
joyStickToggleX = 1;
if (++digitArray[currentDigit] > 9)
digitArray[currentDigit] = 0;
} else if (xValue > 600 && joyStickToggleX == 0) {
joyStickToggleX = 1;
if (--digitArray[currentDigit] < 0)
digitArray[currentDigit] = 9;
}
else if (xValue >= 400 && xValue <= 600) {
joyStickToggleX = 0;
}
// switch state
if (dpState == HIGH) {
blink = 0;
dpState = !dpState;
state = BROWSE_DIGITS;
}
if (blink == 0) {
displayArray();
} else {
for (int i = 0; i < noOfDisplays; i++) {
showDigit(i);
if (i == currentDigit)
displayNumber(10, HIGH);
else
displayNumber(digitArray[i], LOW);
delay(5);
}
}
if (millis() - lastIncreasing >= delayBlinkTime) {
blink = !blink;
lastIncreasing = millis();
}
}
}
| true |
be695b7a22fbd0d854e0d10742d679d2c3f81598 | C++ | redwanh25/cpp | /data structure/Linked List (Inserting a node at beginning) 2.cpp | UTF-8 | 599 | 3.6875 | 4 | [] | no_license | #include<iostream>
using namespace std;
struct node
{
int data;
node* link;
};
node* inser_t(node* head, int x)
{
node* temp = new node();
temp -> data = x;
temp -> link = head;
head = temp;
return head;
}
void print(node* head)
{
while(head != NULL){
cout<< head ->data <<" ";
head = head -> link;
}
cout<<endl;
}
int main()
{
node* head = NULL;
int n, x;
cin>> n ;
for(int i=1; i<=n; i++){
cin>> x;
head = inser_t(head, x);
print(head);
}
return 0;
}
| true |
1c513202dfc738df415eda8815a55d195f0fc4bd | C++ | DavidLee999/leetcode | /3Sum.cpp | UTF-8 | 1,239 | 2.890625 | 3 | [] | no_license | class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
int length = nums.size();
vector<vector<int> > res;
std::sort(nums.begin(), nums.end());
for (int i = 0; i < length; ++i)
{
int target = -nums[i];
int front = i + i;
int rear = length - 1;
while (front < rear)
{
int two_sum = nums[front] + nums[rear];
if (two_sum < )
}
for (int j = i + 1; j < length - 1; ++j)
{
for (int k = j + 1; k < length; ++k)
{
if (nums[j] + nums[k] == target)
{
res.push_back(vector<int> { nums[i], nums[j], nums[k] });
}
while (nums[k + 1] == nums[k])
++k;
}
while (nums[j + 1] == nums[j])
++j;
}
while (nums[i + 1] == nums[i])
++i;
}
return res;
}
};
| true |
a551302eb48abb2bdb1a6749fea8441a4c6d6566 | C++ | Prateek-Sethi/CODING_INTERVIEW_PREP | /5. ALGO/Recursion/swapAdjacentNodesInLinkedList.cpp | UTF-8 | 661 | 3.84375 | 4 | [
"CC0-1.0",
"LicenseRef-scancode-public-domain"
] | permissive | #include <iostream>
using namespace std;
struct Node
{
int val;
Node *next;
};
Node *newNode(int val)
{
Node *temp = new Node();
temp->val = val;
temp->next = NULL;
}
Node *insertNode(Node *head, int val)
{
Node *itr = head;
if (!head)
{
head->val = val;
head->next = NULL;
}
else
{
while (itr->next)
itr = itr->next;
Node *temp = newNode(val);
itr->next = temp;
}
return head;
}
void swapAdjacentNodes(Node *root)
{
Node *itr = root;
while (itr && itr->next)
{
swap(itr->val, itr->next->val);
itr = itr->next->next;
}
}
| true |
b4a51164acdff184dc17af854ef3076f3401d5ec | C++ | nisak0503/leetcode | /Company/Google/293.FlipGame/293.cpp | UTF-8 | 906 | 3.140625 | 3 | [] | no_license | class Solution {
public:
vector<string> generatePossibleNextMoves(string s) {
vector<string> res;
for(int i = 1; i < s.size(); ++i)
{
if(s[i] == s[i-1] && s[i] == '+')
{
string ss = s;
ss[i] = '-';
ss[i-1] = '-';
res.push_back(ss);
}
}
return res;
}
};
/*
第一次提交题目审题审错了,--是不能翻牌的
3ms, 0.28%
这个效率太低了
凑一下还是3ms, 0.28%
*/
class Solution {
public:
vector<string> generatePossibleNextMoves(string s) {
vector<string> res;
int len = s.size();
for(int i = 1; i < len; ++i)
{
if(s[i] == s[i-1] && s[i] == '+')
{
res.push_back(s.substr(0, i-1) + "--" + s.substr(i+1, len-i));
}
}
return res;
}
}; | true |
44073d3c3dc4d4db44873b22df99a5e9f52e7318 | C++ | huntmj01/CodingSamples | /C++/CS331 Intro to C++/HW4/Hunt_Matthew_CS331_HW4/Q2/Q2/Q2.cpp | UTF-8 | 1,200 | 3.609375 | 4 | [] | no_license | /*
* NAME: Matthew Hunt
* INSTRUCTOR: Dr. Yoo
* COURSE: CS 331
* DATE: 08/03/2018
* ASSIGNMENT: HW4_Q2
*/
#include "stdafx.h"
#include <vector>
#include <iostream>
#include <string>
using namespace std;
// rotateLeft template function - void rotateLeft (vector <T>& v)
template <typename Type>
void rotateLeft (vector<Type>& v)
{
Type valAtIndex1 = v.at(0);
v.push_back(valAtIndex1);
v.erase(v.begin());
}
// output template function - void output(vector<T> v)
template <typename Type>
void output(vector<Type> v)
{
for (unsigned int i = 0; i < v.size(); i++)
{
cout << v.at(i) << " ";
}
}
int main(int argc, char** argv)
{
// Create a vector v with "1 3 5 7"
vector<int> v;
v.push_back(1);
v.push_back(3);
v.push_back(5);
v.push_back(7);
for (int k = 0; k < v.size(); k++)
{
cout << k << ": ";
output(v);
cout << endl;
rotateLeft(v);
}
cout << endl;
string as[] = { "a", "b", "c", "d", "e" };
// Create a vector vs with "a b c d e"
vector<string> vs;
vs.push_back("a");
vs.push_back("b");
vs.push_back("c");
vs.push_back("d");
vs.push_back("e");
for (int k = 0; k < vs.size(); k++)
{
output(vs);
cout << endl;
rotateLeft(vs);
}
return 0;
} | true |
9746601c57a17a52724f630591b705fc4bce2f80 | C++ | chuang39/eos-contracts | /contracts/mev/mev.cpp | UTF-8 | 8,880 | 2.5625 | 3 | [
"BSD-3-Clause",
"Apache-2.0",
"MIT"
] | permissive | #include "mev.hpp"
uint64_t mstarttimes[4] = {1535760000, 1538352000, 1541030400, 1543622400};
uint32_t getstartmonth(uint32_t epochtime) {
for (int i = 0; i < 4; i++) {
if (epochtime <= mstarttimes[i]) {
return mstarttimes[i-1];
}
}
return mstarttimes[3];
}
void mev::create( account_name issuer,
asset maximum_supply )
{
require_auth( _self );
auto sym = maximum_supply.symbol;
eosio_assert( sym.is_valid(), "invalid symbol name" );
eosio_assert( maximum_supply.is_valid(), "invalid supply");
eosio_assert( maximum_supply.amount > 0, "max-supply must be positive");
stats statstable( _self, sym.name() );
auto existing = statstable.find( sym.name() );
eosio_assert( existing == statstable.end(), "token with symbol already exists" );
statstable.emplace( _self, [&]( auto& s ) {
s.supply.symbol = maximum_supply.symbol;
s.max_supply = maximum_supply;
s.issuer = issuer;
});
}
void mev::issue( account_name to, asset quantity, string memo )
{
auto sym = quantity.symbol;
eosio_assert( sym.is_valid(), "invalid symbol name" );
eosio_assert( memo.size() <= 256, "memo has more than 256 bytes" );
auto sym_name = sym.name();
stats statstable( _self, sym_name );
auto existing = statstable.find( sym_name );
eosio_assert( existing != statstable.end(), "token with symbol does not exist, create token before issue" );
const auto& st = *existing;
require_auth( st.issuer );
eosio_assert( quantity.is_valid(), "invalid quantity" );
eosio_assert( quantity.amount > 0, "must issue positive quantity" );
eosio_assert( quantity.symbol == st.supply.symbol, "symbol precision mismatch" );
eosio_assert( quantity.amount <= st.max_supply.amount - st.supply.amount, "quantity exceeds available supply");
statstable.modify( st, 0, [&]( auto& s ) {
s.supply += quantity;
});
add_balance( st.issuer, quantity, st.issuer );
if( to != st.issuer ) {
SEND_INLINE_ACTION( *this, transfer, {st.issuer,N(active)}, {st.issuer, to, quantity, memo} );
}
}
void mev::transfer( account_name from,
account_name to,
asset quantity,
string memo )
{
eosio_assert( from != to, "cannot transfer to self" );
require_auth( from );
eosio_assert( is_account( to ), "to account does not exist");
auto sym = quantity.symbol.name();
stats statstable( _self, sym );
const auto& st = statstable.get( sym );
require_recipient( from );
require_recipient( to );
eosio_assert( quantity.is_valid(), "invalid quantity" );
eosio_assert( quantity.amount > 0, "must transfer positive quantity" );
eosio_assert( quantity.symbol == st.supply.symbol, "symbol precision mismatch" );
eosio_assert( memo.size() <= 256, "memo has more than 256 bytes" );
sub_balance( from, quantity );
add_balance( to, quantity, from );
}
void mev::sub_balance( account_name owner, asset value ) {
accounts from_acnts( _self, owner );
const auto& from = from_acnts.get( value.symbol.name(), "no balance object found" );
eosio_assert( from.balance.amount >= value.amount, "overdrawn balance!" );
stake_summary_index stakes(N(eosvegasdivi), N(eosvegasdivi));
auto itr_stake = stakes.find(owner);
if (itr_stake != stakes.end()) {
uint64_t stakenum = 0;
eosio_assert( (from.balance.amount - itr_stake->stake.amount) >= value.amount, "overdrawn balance due to stake");
}
if( from.balance.amount == value.amount ) {
from_acnts.erase( from );
auto itr_holder = holders.find(owner);
if (itr_holder != holders.end()) {
holders.erase(itr_holder);
}
} else {
from_acnts.modify( from, owner, [&]( auto& a ) {
a.balance -= value;
});
}
}
void mev::add_balance( account_name owner, asset value, account_name ram_payer )
{
accounts to_acnts( _self, owner );
auto to = to_acnts.find( value.symbol.name() );
if( to == to_acnts.end() ) {
to_acnts.emplace( ram_payer, [&]( auto& a ){
a.balance = value;
});
auto itr_holder = holders.find(owner);
if (itr_holder == holders.end()) {
holders.emplace(_self, [&](auto &p){
p.owner = owner;
});
}
} else {
to_acnts.modify( to, 0, [&]( auto& a ) {
a.balance += value;
});
}
}
void mev::debug(account_name from) {
require_auth( _self );
stake_summary_index stakes(N(eosvegasdivi), N(eosvegasdivi));
auto itr_stake = stakes.find(from);
eosio_assert( itr_stake->stake.amount == 7273, "overdrawn balance due to stake ");
}
void mev::registerbb(account_name from, asset quantity) {
eosio_assert( is_account( from ), "User does not exist");
require_auth( from );
asset tempasset = asset(0, symbol_type(S(4, MEV)));
stats statstable( _self, tempasset.symbol.name() );
const auto& st = statstable.get( tempasset.symbol.name() );
eosio_assert( quantity.symbol.name() == tempasset.symbol.name(), "Symbol must be MEV" );
eosio_assert( quantity.is_valid(), "Invalid quantity" );
eosio_assert( quantity.amount > 0, "Must transfer positive quantity" );
eosio_assert( quantity.symbol == st.supply.symbol, "Symbol precision mismatch" );
auto amount = quantity.amount;
uint32_t cur_in_sec = now();
uint32_t month_in_sec = getstartmonth(cur_in_sec);
auto itr_rewardinfo = rentrys.find(month_in_sec);
eosio_assert( itr_rewardinfo != rentrys.end(), "Repurchase window is not open yet for this month.");
eosio_assert( cur_in_sec < itr_rewardinfo->expireat , "Repurchase window is closed for this month.");
//eosio_assert( _self == N(eosvegascoin) , "self is not eosvegascoin.");
rentrys.modify( itr_rewardinfo, 0, [&]( auto& p ) {
p.buybackshares += amount;
});
sub_balance( from, quantity );
add_balance( _self, quantity, st.issuer );
auto itr_buyback = bbregs.find(from);
eosio_assert( itr_buyback == bbregs.end(), "You have registered buyback for this month." );
itr_buyback = bbregs.emplace(_self, [&](auto &p){
p.owner = from;
p.shares = quantity;
});
}
void mev::cancelreward(account_name from) {
if (from != N(eosvegasjack) || from != _self) {
eosio_assert( false, "You don't have privilege to cancel reward." );
}
require_auth( _self );
}
void mev::rewardholders(const currency::transfer &t, account_name code) {
// memo should be like "time"
if (t.from != N(eosvegasjack)) {
return;
}
eosio_assert(t.quantity.symbol == string_to_symbol(4, "EOS"), "Only accepts EOS/MEV for deposits.");
eosio_assert(t.to == _self, "Transfer not made to this contract");
eosio_assert(t.quantity.is_valid(), "Invalid token transfer");
eosio_assert(t.quantity.amount > 0, "Quantity must be positive");
auto amount = t.quantity.amount;
string usercomment = t.memo;
string ucm = usercomment.substr(0, 10);
uint32_t startmonth = stoi(ucm);
auto itr_rewardinfo = rentrys.find(startmonth);
uint64_t bbshares = 0;
uint64_t bbprice = 0;
if (amount > itr_rewardinfo->buybackshares) {
}
// buyback
}
void mev::addrentry(uint32_t month, uint32_t status) {
require_auth(_self);
auto itr_entry = rentrys.find(month);
eosio_assert( itr_entry == rentrys.end(), "Reward entry already exists" );
rentrys.emplace( _self, [&]( auto& r ) {
r.startmonth = month;
r.expireat = month + 86400 * 7;
});
}
void mev::removerentry(uint32_t month) {
}
void mev::clear(const name from) {
require_auth(_self);
auto itr = rentrys.begin();
while (itr != rentrys.end()) {
itr = rentrys.erase(itr);
}
auto itr2 = bbregs.begin();
while (itr2 != bbregs.end()) {
itr2 = bbregs.erase(itr2);
}
}
void mev::test(const name from, string s) {
}
#define EOSIO_ABI_EX( TYPE, MEMBERS ) \
extern "C" { \
void apply(uint64_t receiver, uint64_t code, uint64_t action) { \
auto self = receiver; \
if(code == self || code == N(eosio.token)) { \
TYPE thiscontract(self); \
if (action == N(transfer) && code == N(eosio.token)) { \
currency::transfer tr = unpack_action_data<currency::transfer>(); \
if (tr.to == self) { \
thiscontract.rewardholders(tr, code); \
} \
return; \
} \
if (code != self) { \
return; \
} \
switch(action) { \
EOSIO_API(TYPE, MEMBERS) \
} \
} \
} \
}
EOSIO_ABI_EX( mev, (create)(issue)(transfer)(debug)(registerbb)(rewardholders)(addrentry)(removerentry)(clear)(test))
| true |
70f2fa75c9da5e7d049f65b584531824c0c827fe | C++ | Lyyua/CPPGame | /GameProject/Engine/Game/Player.cpp | GB18030 | 1,129 | 2.703125 | 3 | [] | no_license | #include "Player.h"
Player::Player()
{
}
Player::Player(Sprite _sprite)
{
mSprite = _sprite;
pos = mSprite.GetPos();
mSprite.SetScale(Vector3(0.1, 0.1, 0.1));
Rect* pRect = new Rect(mSprite.GetPos(), mSprite.GetSize(), Vector3(0, 0, 0));
rd.Initialize(-9.8, mSprite.GetPos(), mSprite.GetSize(), pRect, false);
flapForce = 750;
maxRot = 30;
}
void Player::Render()
{
mSprite.Render();
rd.Render();
}
void Player::Update()
{
HandleInput();
rd.Update();
}
void Player::HandleInput()
{
if (Keyboard::KeyDown(GLFW_KEY_SPACE))
{
Flap();
}
float newRot = (rd.GetVel().y / flapForce)*maxRot; //˶ʱǶ
mSprite.RotateTo(newRot);
rd.GetBoundRect()->RotateLocalTo(newRot);
}
void Player::Flap()
{
rd.AddForce(Vector3(0, flapForce, 0));
mSprite.RotateTo(maxRot);
rd.RotateLocalTo(maxRot);
}
Rigdbody& Player::GetRigdbody()
{
return rd;
}
Vector3* Player::GetPos()
{
return pos;
}
void Player::Reset()
{
mSprite.MoveTo(Vector3(Engine::SCREEN_WIDTH / 2, Engine::SCREEN_HEIGHT / 2, 0));
mSprite.RotateTo(0);
rd.RotateLocalTo(0);
rd.SetVel(Vector3(0, 0, 0));
}
Player::~Player()
{
} | true |
7443aedde67f0245e66283fd9c7ae489a6ffb5f2 | C++ | shubhankar-31/DS-using-cpp | /circular_LL O(1).cpp | UTF-8 | 2,534 | 3.6875 | 4 | [] | no_license | #include <iostream>
#include <cmath>
#include <cstdio>
#include <vector>
#include <array>
using namespace std;
class node
{ public:
int data;
node *next;
};
class circular_ll
{
private:
node *head,*tail;
int i = 1;
public:
circular_ll()
{
head = NULL;
tail = NULL;
}
void add_node(int );
void add_begin(int );
void display();
void search(int );
//simple return functions
int get_head()
{
return head->data;
}
int get_tail()
{
return tail->data;
}
};
void circular_ll::add_node(int n)
{
node *temp=new node;
temp->data = n;
if(head == NULL)
{
head = temp;
tail = temp;
temp->next=head;
}
else
{
tail->next = temp;
temp->next=head;
tail = temp;
}
}
void circular_ll::add_begin(int n)
{
node *temp=new node;
temp->data = n;
if(head == NULL)
{
head = temp;
tail = temp;
temp->next=head;
}
else
{temp->next=head;
tail->next=temp;
head=temp;
}
}
void circular_ll::display()
{
node *temp = head;
if(head==NULL)
{
cout<<"List is empty" ;
}
else
{cout<<"Nodes of circular Linked list \n\n";
do
{
cout << temp->data<<" ";
temp = temp->next;
} while (temp != head);
}
}
void circular_ll:: search(int key) {
node *temp = head;
bool check = 0;
if(head == NULL) {
cout<<"List is empty";
return;
}
else {
do{
if(temp->data == key) {
check = 1;
break;
}
temp = temp->next;
i++;
}while(temp != head);
if(check)
cout<<"\nkey is present in the list at the position : "<< i<<endl;
else
cout<<"\nkey is not present in the list";
}
}
int main()
{
circular_ll a;
a.add_node(1);
a.add_node(2);
a.add_node(5);
a.add_node(4);
a.add_begin(16);
a.display();
cout<<"\n\nhead of the cll is "<<a.get_head()<<endl;
cout<<"\ntail of the cll is "<<a.get_tail()<<endl;
a.search(5);
return 0;
}
| true |
f9647c5a7b66a0d19af6d26cab9f181e606626a9 | C++ | baaOff/temp | /backup/miner.h | UTF-8 | 1,373 | 2.9375 | 3 | [] | no_license | #ifndef MINER_H
#define MINER_H
#include "basegameentity.h"
#include "Locations.h"
class State;
const int comfortLevel = 5;
const int maxNuggets = 3;
const int thirstLevel = 5;
const int tirednessThreshold = 5;
class Miner : public BaseGameEntity
{
public:
Miner(int ID);
// this must be implemented
void update();
void changeState(State* pNewState);
locationType location() const { return mLocation; }
void changeLocation(const locationType loc) { mLocation=loc; }
int goldCarried() const { return mGoldCarried;}
void setGoldCarried(const int val) { mGoldCarried = val;}
void addToGoldCarried(const int val);
bool pocketsFull() const { return mGoldCarried >= maxNuggets;}
bool fatigued() const;
void decreaseFatigue() { fatigue -= 1;}
void increaseFatigue() { fatigue += 1;}
int wealth() const { return moneyInBank; }
void setWealth(const int val) { moneyInBank = val; }
void addToWealth(const int val);
bool thirsty() const;
void buyAndDrinkAWhiskey() { mThirst = 0; moneyInBank-=2; }
private:
locationType mLocation;
int mGoldCarried;
int moneyInBank;
int mThirst;
int fatigue;
State* pCurrentState;
};
#endif // MINER_H
| true |
1bb7095a6d51021f47d8be433e47a1a5f9004a76 | C++ | nkn-kzht/designpattern | /PrototypePattern_sample/sources/Manager.cc | UTF-8 | 568 | 2.5625 | 3 | [
"MIT"
] | permissive | /*
* Manager.cc
*
* Created on: 2016/03/22
* Author: parallels
*/
#include <Manager.h>
#include <IProduct.h>
namespace framework {
Manager Manager::instance_;
Manager::Manager() = default;
Manager::~Manager() = default;
Manager& Manager::getInstance() {
return instance_;
}
void Manager::register_product(const std::string& name, IProduct& proto) {
show_case_[name] = std::move(proto.createClone());
}
std::unique_ptr<IProduct> Manager::create(const std::string& name)
throw (std::out_of_range) {
return show_case_.at(name)->createClone();
}
}
| true |
64c9636f1947b63841ad557d523c9cfb030f214e | C++ | krishna-mathuria/competitive | /leetcode1010.cpp | UTF-8 | 260 | 2.53125 | 3 | [] | no_license | class Solution {
public:
int numPairsDivisibleBy60(vector<int>& time) {
vector<int> mp(60);
int res=0;
for (auto t : time) {
res += mp[(60 - t % 60) % 60];
mp[t % 60]++;
}
return res;
}
}; | true |
452ea5bef07d986ebbb2bbfb62dd1f5000a0ad8b | C++ | Vityoube/MMwGK_PROJEKT | /bottom.cpp | UTF-8 | 1,636 | 2.6875 | 3 | [] | no_license | #include "bottom.h"
Bottom::Bottom()
{
}
void Bottom::draw(){
// glEnable(GL_DEPTH_TEST);
// glDepthFunc(GL_LEQUAL);
// glEnable(GL_CULL_FACE);
// glCullFace(GL_BACK);
glColor4f(1.0f,1.0f,1.0f,1.0f);
glBegin(GL_QUADS);
glVertex3f(center_x-9,center_y,-2.0f);
glVertex3f(center_x+9,center_y,-2.0f);
glVertex3f(center_x+9,center_y, -20.0f);
glVertex3f(center_x-9,center_y,-20.0f);
glEnd();
}
GLuint Bottom::load_texture(FIBITMAP * bitmap){
GLuint tex_id=0;
int x=0, y=0;
int height,width;
RGBQUAD rgbquad;
FREE_IMAGE_TYPE image_type;
BITMAPINFOHEADER * header;
image_type=FreeImage_GetImageType(bitmap);
height=FreeImage_GetHeight(bitmap);
width=FreeImage_GetWidth(bitmap);
header=FreeImage_GetInfoHeader(bitmap);
int scanLineWidth=((3*width)%4 == 0) ? 3*width : ((3*width/4)*4)+4;
unsigned char * texels=(GLubyte*)calloc(height*scanLineWidth,sizeof(GLubyte));
for (x=0;x<width;x++)
for (y=0;y<height;y++){
FreeImage_GetPixelColor(bitmap,x,y,&rgbquad);
texels[y*scanLineWidth+3*x]=((GLbyte*)&rgbquad)[2];
texels[y*scanLineWidth+3*x+1]=((GLbyte*)&rgbquad)[1];
texels[y*scanLineWidth+3*x+2]=((GLbyte*)&rgbquad)[0];
}
glGenTextures(1,&tex_id);
glBindTexture(GL_TEXTURE_2D,tex_id);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D,0,GL_RGB,width,height,0,GL_RGB,GL_UNSIGNED_BYTE,texels);
free(texels);
FreeImage_Unload(bitmap);
return tex_id;
}
| true |
23f1b680adc968041fc6e1b53bf6d95d5ce1a980 | C++ | swolecoder/Techie-Delight | /Array/c++/zeroSumSubarray.cpp | UTF-8 | 592 | 3.59375 | 4 | [] | no_license | #include <iostream>
#include <unordered_set>
using namespace std;
bool zeroSumSubarray(int arr[], int n)
{
//set
unordered_set<int> set;
set.insert(0);
int sum = 0;
for (int i = 0; i < n; i++)
{
sum += arr[i];
if (set.find(sum) != set.end())
{
printf("Found");
return true;
}
set.insert(sum);
}
return false;
}
int main() {
int A[] = {4, 2, -3, -1, 0, 4};
int n = sizeof(A) / sizeof(A[0]);
zeroSumSubarray(A, n) ? cout << "Subarray exists" : cout << "Subarray do not exist";
} | true |
a932c1b7467bdaae1983eb3c3b3c560b8f45e3fe | C++ | clausmeyer/P5-Platooning | /Following_car/Arduino/Velocity_sensor/DCmotorpwm/DCmotorpwm.ino | UTF-8 | 2,741 | 2.515625 | 3 | [] | no_license | #include <TimerOne.h>
#define PWM_PIN 10
volatile byte magnet_counter = 0;
float velocity = 0.0;
unsigned int rpm = 0;
unsigned long timeold = 0;
unsigned long starttime = 0;
int period = 1; //100 ms
unsigned long time_last = 0;
double circumference = 0.2765; //27,65 cm
double magnets = 4.0;
//double result = 0;
//int PWM_PIN = 11; // assigns pin 12 to variable pwm
int speeddelay = 20;
unsigned long LOWcounter = 0;
unsigned long total_time = 0;
int last_magnetstate = 0;
void setup() {
Timer1.initialize(2000);
// Timer1.stop();
// Timer1.restart();
// Setup to 500Hz and 50% duty-cycle
// (To give ESCON a valid PWM at startup)
Timer1.pwm(PWM_PIN, 512, 20);
Serial.begin(9600);
//attachInterrupt(0, magnet_detect, RISING);//Initialize the intterrupt pin (Arduino digital pin 2)
pinMode(PWM_PIN, OUTPUT); // declares pin 12 as output
pinMode(6, OUTPUT); // declares pin A0 as input
pinMode(7, OUTPUT); // declares pin A0 as input
digitalWrite(7, HIGH);
digitalWrite(6, LOW);
pinMode(5, INPUT_PULLUP);
pinMode(2, INPUT_PULLUP);
//digitalWrite(6, LOW);
//digitalWrite(7, HIGH);
Timer1.setPwmDuty(PWM_PIN, 500);
}
void loop() {
if (millis() > time_last + period) {
if (digitalRead(2) == HIGH) {
LOWcounter++;
time_last = millis();
last_magnetstate = 0;
} else if (digitalRead(2) == LOW && last_magnetstate == 0) {
total_time = LOWcounter * period; //* (1/1000); //eks 200 ms
// Serial.print("Circumference/magnets = ");
// Serial.println((circumference/magnets),6);
//Serial.print("total time is");
//Serial.println(total_time);
// Serial.print("total time * 0,1 = ");
// Serial.println((total_time*0.1),4);
velocity = ((circumference / magnets) / (total_time)) * 3.6; //how much time it took to reach a magnet/HIGH
time_last = millis();
Serial.println(velocity, 8);
LOWcounter = 0;
last_magnetstate = 1;
}
//velocity = ((magnet_counter * (circumference / magnets)) * 10.0) * 3.6;
//time_last = millis();
//magnet_counter = 0;
}
//Serial.println("jeg kører altså");
/*
if (digitalRead(5) == LOW) {
digitalWrite(7, HIGH);
digitalWrite(6, LOW);
digitalWrite(PWM_PIN, HIGH); // sets pin 12 HIGH
delayMicroseconds(speeddelay); // waits for t1 uS (high time)
digitalWrite(PWM_PIN, LOW); // sets pin 12 LOW
delayMicroseconds(speeddelay); // waits for t2 uS (low time)
}*/
//Measure RPM
// if (magnet_counter >= 20) {
// rpm = 30 * 1000 / (millis() - timeold) * magnet_counter;
// timeold = millis();
// magnet_counter = 0;
// Serial.println(rpm,DEC);
// }
}
| true |
7912452e25b37ad88157c4049b204bb281fdee1d | C++ | JOOHOJANG/Problem_Solving | /boj_sources/6416.cpp | UTF-8 | 780 | 2.703125 | 3 | [] | no_license | #include <iostream>
#include <unordered_set>
using namespace std;
unordered_set<int> node;
int u, v;
int line;
int cnt = 1;
int main() {
while (1) {
cin >> u >> v;
if (u == -1 && v == -1) {
break;
}
if (u == 0 && v == 0) {
if (line == 0 || node.size() == line + 1) {
printf("Case %d is a tree.\n", cnt);
node.clear();
line = 0;
cnt++;
continue;
}
else {
printf("Case %d is not a tree.\n", cnt);
node.clear();
line = 0;
cnt++;
continue;
}
}
node.insert(u);
node.insert(v);
line++;
}
}
| true |
03ca77cf0a31eedb338e880fff9a7bdc7e2425a3 | C++ | benbraide/OOSL | /oosl/driver/numeric_driver.cpp | UTF-8 | 9,420 | 2.78125 | 3 | [] | no_license | #include "numeric_driver.h"
oosl::driver::numeric::~numeric() = default;
oosl::driver::object::entry_type *oosl::driver::numeric::cast(entry_type &entry, type_object_type &type, cast_option_type options){
if (OOSL_IS(options, cast_option_type::ref) || type.is_ref())
return object::cast(entry, type, options);//Reference cast
if (!OOSL_IS(options, cast_option_type::reinterpret)){
switch (type.id()){
case type_id_type::int8_:
return common::controller::active->temporary_storage().add_scalar(value<__int8>(entry));
case type_id_type::uint8_:
return common::controller::active->temporary_storage().add_scalar(value<unsigned __int8>(entry));
case type_id_type::int16_:
return common::controller::active->temporary_storage().add_scalar(value<__int16>(entry));
case type_id_type::uint16_:
return common::controller::active->temporary_storage().add_scalar(value<unsigned __int16>(entry));
case type_id_type::int32_:
return common::controller::active->temporary_storage().add_scalar(value<__int32>(entry));
case type_id_type::uint32_:
return common::controller::active->temporary_storage().add_scalar(value<unsigned __int32>(entry));
case type_id_type::int64_:
return common::controller::active->temporary_storage().add_scalar(value<__int64>(entry));
case type_id_type::uint64_:
return common::controller::active->temporary_storage().add_scalar(value<unsigned __int64>(entry));
/*case type_id_type::int128_:
return value_from_<__int128>(entry, to, destination);
case type_id_type::uint128_:
return value_from_<unsigned __int128>(entry, to, destination);*/
case type_id_type::float_:
return common::controller::active->temporary_storage().add_scalar(value<float>(entry));
case type_id_type::double_:
return common::controller::active->temporary_storage().add_scalar(value<double>(entry));
case type_id_type::ldouble:
return common::controller::active->temporary_storage().add_scalar(value<long double>(entry));
case type_id_type::string_:
return common::controller::active->temporary_storage().add_scalar(value<std::string>(entry));
case type_id_type::wstring_:
return common::controller::active->temporary_storage().add_scalar(value<std::wstring>(entry));
default:
break;
}
}
if (OOSL_IS(options, cast_option_type::reinterpret) && entry.type->is_integral() && type.is_strong_pointer())//Reinterpret cast
return common::controller::active->temporary_storage().add_scalar(value<uint64_type>(entry), type.reflect());
return object::cast(entry, type, options);
}
void oosl::driver::numeric::echo(entry_type &entry, output_writer_type &writer){
std::string target;
if (!OOSL_IS(entry.attributes, attribute_type::nan_)){
value(entry, type_id_type::string_, reinterpret_cast<char *>(&target));
target += suffix_(entry);
}
else//NaN
target = "NaN";
writer.write(target.c_str());
}
void oosl::driver::numeric::value(entry_type &entry, type_id_type to, char *destination){
if (OOSL_IS(entry.attributes, attribute_type::nan_)){//NaN
switch (to){
case type_id_type::string_:
*reinterpret_cast<std::string *>(destination) = "NaN";
break;
case type_id_type::wstring_:
*reinterpret_cast<std::wstring *>(destination) = L"NaN";
break;
default:
break;
}
throw error_type::not_implemented;
}
switch (entry.type->id()){
case type_id_type::int8_:
return value_from_<__int8>(entry, to, destination);
case type_id_type::uint8_:
return value_from_<unsigned __int8>(entry, to, destination);
case type_id_type::int16_:
return value_from_<__int16>(entry, to, destination);
case type_id_type::uint16_:
return value_from_<unsigned __int16>(entry, to, destination);
case type_id_type::int32_:
return value_from_<__int32>(entry, to, destination);
case type_id_type::uint32_:
return value_from_<unsigned __int32>(entry, to, destination);
case type_id_type::int64_:
return value_from_<__int64>(entry, to, destination);
case type_id_type::uint64_:
return value_from_<unsigned __int64>(entry, to, destination);
/*case type_id_type::int128_:
return value_from_<__int128>(entry, to, destination);
case type_id_type::uint128_:
return value_from_<unsigned __int128>(entry, to, destination);*/
case type_id_type::float_:
return value_from_<float>(entry, to, destination);
case type_id_type::double_:
return value_from_<double>(entry, to, destination);
case type_id_type::ldouble:
return value_from_<long double>(entry, to, destination);
default:
break;
}
throw error_type::not_implemented;
}
oosl::driver::object::entry_type *oosl::driver::numeric::evaluate_(entry_type &entry, operator_info_type &operator_info){
switch (entry.type->id()){
case type_id_type::int8_:
return evaluate_integral_<__int8>(entry, operator_info.id);
case type_id_type::uint8_:
return evaluate_integral_<unsigned __int8>(entry, operator_info.id);
case type_id_type::int16_:
return evaluate_integral_<__int16>(entry, operator_info.id);
case type_id_type::uint16_:
return evaluate_integral_<unsigned __int16>(entry, operator_info.id);
case type_id_type::int32_:
return evaluate_integral_<__int32>(entry, operator_info.id);
case type_id_type::uint32_:
return evaluate_integral_<unsigned __int32>(entry, operator_info.id);
case type_id_type::int64_:
return evaluate_integral_<__int64>(entry, operator_info.id);
case type_id_type::uint64_:
return evaluate_integral_<unsigned __int64>(entry, operator_info.id);
/*case type_id_type::int128_:
return (is_integral ? evaluate_integral_<__int128>(entry, operator_info.id) : evaluate_<__int128>(entry, operator_info.id));
case type_id_type::uint128_:
return (is_integral ? evaluate_integral_<unsigned __int128>(entry, operator_info.id) : evaluate_<unsigned __int128>(entry, operator_info.id));*/
case type_id_type::float_:
return evaluate_signed_<float>(entry, operator_info.id);
case type_id_type::double_:
return evaluate_signed_<double>(entry, operator_info.id);
case type_id_type::ldouble:
return evaluate_signed_<long double>(entry, operator_info.id);
default:
break;
}
return object::evaluate_(entry, operator_info);
}
oosl::driver::object::entry_type *oosl::driver::numeric::evaluate_(entry_type &entry, operator_info_type &operator_info, entry_type &operand){
auto operand_type = operand.type->driver()->type(operand);
if (!operand_type->is_numeric()){//Non-numeric operand
if (operator_info.id != operator_id_type::plus)//Not supported
return object::evaluate_(entry, operator_info, operand);
if (operand_type->is_string())
return concatenate_string_<std::string>(entry, operand, type_id_type::string_);
if (operand_type->is_wstring())
return concatenate_string_<std::wstring>(entry, operand, type_id_type::wstring_);
}
type_id_type id;
if (operator_info.id < operator_id_type::compound_plus || operator_info.id > operator_id_type::compound_right_shift)//Use bigger type
id = ((entry.type->id() < operand_type->id()) ? operand_type->id() : entry.type->id());
else//Force 'this' type
id = entry.type->id();
switch (id){
case type_id_type::int8_:
return evaluate_integral_<__int8>(entry, operator_info.id, operand);
case type_id_type::uint8_:
return evaluate_integral_<unsigned __int8>(entry, operator_info.id, operand);
case type_id_type::int16_:
return evaluate_integral_<__int16>(entry, operator_info.id, operand);
case type_id_type::uint16_:
return evaluate_integral_<unsigned __int16>(entry, operator_info.id, operand);
case type_id_type::int32_:
return evaluate_integral_<__int32>(entry, operator_info.id, operand);
case type_id_type::uint32_:
return evaluate_integral_<unsigned __int32>(entry, operator_info.id, operand);
case type_id_type::int64_:
return evaluate_integral_<__int64>(entry, operator_info.id, operand);
case type_id_type::uint64_:
return evaluate_integral_<unsigned __int64>(entry, operator_info.id, operand);
/*case type_id_type::int128_:
return (is_integral ? evaluate_integral_<__int128>(entry, operator_info.id, operand) : evaluate_<__int128>(entry, operator_info.id, operand));
case type_id_type::uint128_:
return (is_integral ? evaluate_integral_<unsigned __int128>(entry, operator_info.id, operand) : evaluate_<unsigned __int128>(entry, operator_info.id, operand));*/
case type_id_type::float_:
return evaluate_<float>(entry, operator_info.id, operand);
case type_id_type::double_:
return evaluate_<double>(entry, operator_info.id, operand);
case type_id_type::ldouble:
return evaluate_<long double>(entry, operator_info.id, operand);
default:
break;
}
return object::evaluate_(entry, operator_info, operand);
}
std::string oosl::driver::numeric::suffix_(entry_type &entry){
switch (entry.type->id()){
case type_id_type::int8_:
return "i8";
case type_id_type::uint8_:
return "ui8";
case type_id_type::int16_:
return "i16";
case type_id_type::uint16_:
return "ui16";
case type_id_type::int32_:
return "i32";
case type_id_type::uint32_:
return "ui32";
case type_id_type::int64_:
return "i64";
case type_id_type::uint64_:
return "ui64";
case type_id_type::int128_:
return "i128";
case type_id_type::uint128_:
return "ui128";
case type_id_type::float_:
return "f";
case type_id_type::ldouble:
return "l";
default:
break;
}
return "";
}
bool oosl::driver::numeric::is_(evaluation_option_type left, evaluation_option_type right){
return OOSL_IS(left, right);
}
| true |
1d006c8adc9c99f72782ab4ee745640d57ffacf8 | C++ | rameshg87/osmosys | /smldr/cpp/filesys.cpp | UTF-8 | 6,968 | 2.65625 | 3 | [] | no_license | /********************************************************************************
PART OF OSMOSYS OPERATING SYSTEM; CODE WRITTEN BY TEAM OSMOSYS
v1.1
********************************************************************************/
#include <filesys.h>
#include <common.h>
#include <video.h>
/* disk buffer declared in smldr.cpp */
extern char diskbuffer[33][512];
/* fat partition constructor
assigns values to various attributes of this partition
partition number is passed as argument */
fat_partition :: fat_partition (int part_index)
{
/* get the lba address of this partition by reading from mbr */
partition_lba = return_partition_lba (part_index);
/* read vbr for this partition */
read_sector (partition_lba,0);
/* various attributes at corresponding offset on vbr */
sectors_per_cluster = diskbuffer[0][0x0D];
number_of_reserved_sectors = return_word (diskbuffer,0,0x0E);
number_of_fat = diskbuffer[0][0x10];
sectors_per_fat = return_dword (diskbuffer,0,0x24);
root_dir_cluster = return_dword (diskbuffer,0,0x2C);
/* calculated attributes */
cluster_begin_lba = partition_lba + number_of_reserved_sectors + (number_of_fat * sectors_per_fat);
fat_begin_lba = partition_lba + number_of_reserved_sectors;
root_dir_lba = cluster_begin_lba + (root_dir_cluster - 0x02) * (sectors_per_cluster);
}
/* this function checks whether the directory entry is present on this cluster
takes in filename and the disk buffer index on which cluster lies as argument */
int fat_partition :: find_directory_entry (const char *filename,int db_index)
{
char *pointer;
int i,j;
/* loop the whole cluster */
for (j=0;j<sectors_per_cluster;j++)
for (i=0;i<16;i++)
{
/* get a pointer point to the beginning of the directory entry */
pointer = & (diskbuffer [db_index+j][i*32]);
/* check if this is a end of directory entry */
if ((*pointer) == 0x00)
return -1;
/* put a null character at the end for comparing string */
*(pointer + 11) = '\0';
/* compare the filename passed and the filename in the directory entry
quit if match found */
if (!strcmp (filename,pointer))
{ j++;
goto jump_outside_all_loop; }
}
jump_outside_all_loop:
/* both the sector number and index within the sector needs to be passed
because sectors_per_cluster can be greater than 1 */
return (j-1)*16+i;
}
/* function that returns cluster number of a file when filename, index of cluster
on the disk buffer and directory cluster number are passed */
int fat_partition :: return_file_cluster (const char *filename,int dir_cluster_db_index,int dir_cluster,int *filesize)
{
bool done = false;
int file_cluster,file_index,index_value;
int db_index = dir_cluster_db_index;
/* loop until a result is found */
while (done==false)
{
/* check if directory entry of the file is present on this cluster */
index_value = find_directory_entry (filename,db_index);
if (index_value < 0)
{
/* end of directory record has been reached and file not yet found hence return -1 */
done=true;
file_cluster=-1;
break;
}
else if (index_value == sectors_per_cluster * 16)
{
/* the cluster was searched completely but file was not found
we need to get the next cluster in and search for the directory entry again*/
dir_cluster = find_chain_cluster ((unsigned int)dir_cluster);
read_cluster (dir_cluster, db_index);
continue;
}
else
{
/* we found the entry for the file */
done=true;
/* find out the higher 16 bits of cluster number */
file_cluster=return_word (diskbuffer,db_index+(index_value*0x20)/0x200,(index_value*0x20)%0x200+0x14);
file_cluster |= return_word (diskbuffer,db_index+(index_value*0x20)/0x200,(index_value*0x20)%0x200+0x1A);
/* return the filesize if asked */
if (filesize != 0)
*filesize=return_dword (diskbuffer,db_index+index_value/128,(index_value%128)*32+0x1C);
break;
}
}
return file_cluster;
}
/* this function finds out the next cluster of the file given the current
cluster number by looking at fat 1 */
int fat_partition :: find_chain_cluster (int cluster)
{
/* find out the sector on which the chain value lies */
int chain_lba = fat_begin_lba + (cluster/128);
read_sector (chain_lba,9);
/* find out the chain value */
unsigned int return_value = return_dword (diskbuffer, 9, 4*(cluster & 0x7F));
return return_value;
}
/* this function reads clusters from disk given cluster number
and disk buffer index to which cluster is to be loaded */
void fat_partition :: read_cluster (int cluster,int dbindex)
{
int j,cluster_lba;
/* get cluster lba address */
cluster_lba = cluster_begin_lba + (cluster - 0x02) * (sectors_per_cluster);
/* read all the sectors within the cluster */
for (j=0;j<sectors_per_cluster;j++)
read_sector (cluster_lba+j,dbindex+j);
}
/* this function reads a sector given the lba address and disk buffer index
to which the sector is to be loaded */
void read_sector (int lba_address,int index)
{
int idx;
unsigned short int tmpword;
/* tell controller that we are going to give lba28 address */
outportb (0x1F1,0x00);
outportb (0x1F2,0x01);
/* lba address bits 7-0 */
outportb (0x1F3,(lba_address)&0xFF);
/* lba address bits 15-8 */
outportb (0x1F4,(lba_address>>8)&0xFF);
/* lba address bits 23-16 */
outportb (0x1F5,(lba_address>>16)&0xFF);
/* magic bit + drive number (master / slave) + lba address bits 27-24 */
outportb (0x1F6,0xE0 | ((lba_address>>24) & 0x0F));
/* read command */
outportb (0x1F7, 0x20);
/* wait for the controller to get ready */
while (!(inportb(0x1F7) & 0x08));
/* read the sector word by word and store it in disk buffer */
for (idx = 0; idx < 256; idx++)
{
tmpword = inportw(0x1F0);
diskbuffer [index][idx*2] = (tmpword & 0xFF);
diskbuffer [index][idx*2+1] = ((tmpword>>8) & 0xFF);
}
}
/* this function returns the lba address of a partition by looking at the partition table of the mbr and ebr */
int return_partition_lba (int index)
{
int lba=0;
int offset;
/* read the mbr */
read_sector (0,0);
/* calculate offset to the partition */
offset = 0x1be + (index/8) * 0x10 + 0x8;
/* get the lba address */
lba = return_dword (diskbuffer,0,offset);
/* if the partition is an extended partition */
if (index%8 != 0)
{
int logical_partition_number = index%8,offset;
printf ("\nllba=%x",lba);
/* read the first ebr */
read_sector (lba,0);
/* chain through the ebrs */
for (int i=1; i< logical_partition_number; i++)
{
offset = return_dword (diskbuffer,0,470);
lba = lba + offset;
read_sector (lba,0);
}
/* finally we have reached the required ebr */
lba = lba + return_dword (diskbuffer,0,454);
}
return lba;
}
| true |
da0faacb0907ef5bbb6e0704ac5a8f832be1bb04 | C++ | jatropj/plume-sph | /src/preproc/preprocess.h | UTF-8 | 4,711 | 3.140625 | 3 | [] | no_license | /*
* preprocess.h
*
* Created on: Mar 7, 2015
* Author: zhixuanc
*/
#ifndef PREPROCESS_H
#define PREPROCESS_H
#include <vector>
#include <iostream>
using namespace std;
#include <buckstr.h>
struct PartiHead
{
int xind, yind, zind, proc;
unsigned key[KEYLENGTH];
bool is_underground;
unsigned top_key[KEYLENGTH]; //key of the bucket above it, newly added, will be used only when the bucket is underground bucket.
// constructor
PartiHead (int i, int j, int k, unsigned keyi[])
{
xind = i;
yind = j;
zind = k; //This is newly added, as a new member int k is added
proc = 0;
for (i = 0; i < KEYLENGTH; i++)
key[i] = keyi[i];
is_underground = false;
for (i = 0; i < KEYLENGTH; i++)
top_key[i] = 0;
}
// constructor overload --> constructor for underground bucket
PartiHead (int i, int j, int k, unsigned keyi[], unsigned top_keyi[])
{
xind = i;
yind = j;
zind = k; //This is newly added, as a new member int k is added
proc = 0;
for (i = 0; i < KEYLENGTH; i++)
key[i] = keyi[i];
is_underground = true;
for (i = 0; i < KEYLENGTH; i++)
top_key[i] = top_keyi[i];
}
//The basic idea of this operator overload:
/*
* For underground bucket, use the top_key for comparison
* 1) 0.1 is smaller than 1, which is the minimum unit for keys
* 2) By adding 0.1, the underground bucket will always be the one after its top bucket in a sorted list
*/
bool operator < (const PartiHead & rhs) const
{
if (is_underground)
{
if (rhs.is_underground)
{
if ( top_key[0] < rhs.top_key[0] )
return true;
else if ( top_key[0] > rhs.top_key[0] )
return false;
else if ( (top_key[1] + 0.1)< (rhs.top_key[1] + 0.1)) //set the key of underground bucket to be a little bit larger than its above.
return true;
else
return false;
} //end of is rhs is underground
else
{
if ( top_key[0] < rhs.key[0] )
return true;
else if ( top_key[0] > rhs.key[0] )
return false;
else if ( (top_key[1] + 0.1) < rhs.key[1] )
return true;
else
return false;
}//end of is rhs is not underground
}// end of if bucket is underground
else
{
if (rhs.is_underground)
{
if ( key[0] < rhs.top_key[0] )
return true;
else if ( key[0] > rhs.top_key[0] )
return false;
else if ( key[1] < (rhs.top_key[1] + 0.1)) //set the key of underground bucket to be a little bit larger than its above.
return true;
else
return false;
}//end of is rhs is underground
else
{
if ( key[0] < rhs.key[0] )
return true;
else if ( key[0] > rhs.key[0] )
return false;
else if ( key[1] < rhs.key[1] )
return true;
else
return false;
}//end of is rhs is not underground
}// end of if bucket is not underground
}
// bool operator < (const PartiHead & rhs) const
// {
// if ( key[0] < rhs.key[0] )
// return true;
// else if ( key[0] > rhs.key[0] )
// return false;
// else if ( key[1] < rhs.key[1] )
// return true;
// else
// return false;
// }
};
//! Write Background mesh and particle data to HDF5 file
void createfunky(
//! Numboer of processes in a multiproc run
int ,
//! Size of Hash Table constants array
int,
//! Hash Table Constants
double *,
//! Background grid data
vector <BucketStruct> &,
//! partition table keys
vector <unsigned> &
);
//function that used to determine the type of bucket
void determine_bucket_type
(
//min of domain
double *,
//max of domain
double *,
// [xmin, xmax] of bucket
double *,
// [ymin, ymax] of bucket
double *,
// [zmin, zmax] of bucket
double *,
//return buckete type
int *,
//return bucket index
int *
);
#endif /* PREPROCESS_H_ */
| true |
98377fb224e918c72a12807b8fee181689b24945 | C++ | glandu2/DIFKdom | /DIFK/TemplateDefinitions.h | UTF-8 | 693 | 2.640625 | 3 | [] | no_license | #ifndef DIFK_TEMPLATEDEFINITIONS_H
#define DIFK_TEMPLATEDEFINITIONS_H
#include <vector>
#include <string>
#include "MemberType.h"
namespace DIFK {
class Block;
class TemplateDefinitions
{
public:
struct FieldDef {
std::string name;
ElementType type;
TemplateGuid guid; //valid only if type == ET_Template
std::vector<FieldDef*> members;
};
TemplateDefinitions();
~TemplateDefinitions();
FieldDef* getTemplateFromGuid(TemplateGuid* guid);
FieldDef* getTemplateFromName(const char* templateName);
Block* getBlockFromName(const char* name);
protected:
private:
std::vector<FieldDef*> templates;
};
} // namespace DIFK
#endif // DIFK_TEMPLATEDEFINITIONS_H
| true |
c7b87f4a81e40b163b185a6f0be03b573aba9972 | C++ | lnghia/Big-O-Coding | /orange/dp/session1/Minimum Indexed Character/code.cpp | UTF-8 | 671 | 2.828125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main(){
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int t;
string patt;
string str;
string ans = "No character present";
unordered_set<char> counting;
cin >> t;
while(t--){
if(!counting.empty()) counting.clear();
cin >> patt >> str;
ans = "No character present";
for(auto& c : str){
counting.insert(c);
}
for(auto& c : patt){
if(counting.find(c) != counting.end()){
ans = c;
break;
}
}
cout << ans << '\n';
}
return 0;
} | true |
a5083aaf8ec421a58e95a21cd17b3215a43de87d | C++ | sg-p4x347/RISC-Simulator | /RISC Simulator/GOTO.h | UTF-8 | 284 | 2.84375 | 3 | [] | no_license | #pragma once
#include <set>
enum ConditionalFlags {
True,
False,
Underflow,
Overflow,
Greater,
Equal,
Less
};
class GOTO {
public:
GOTO();
void SetFlag(ConditionalFlags flag);
bool Check(ConditionalFlags flag);
void Clear();
private:
std::set<ConditionalFlags> m_flags;
}; | true |
bdf62267b7c1b70bc89be994f2ce0597586a6021 | C++ | dishant-123/Data-structure- | /TreesCodes/implementing binary tree.cpp | UTF-8 | 2,602 | 3.671875 | 4 | [] | no_license | //all the leftnodes of any nodes is smaller and right nodes are greater;
#include<iostream>
#include<queue>
using namespace std;
struct BstNode{
int data;
BstNode *left;
BstNode *right;
};
BstNode * getNewNode(int data)
{
BstNode *newNode = new BstNode()
newNode->data=data;
newNode->left=newNode->right=NULL;
return newNode;
}
BstNode * Insert(BstNode *root,int data)
{
if(root==NULL)
root=getNewNode(data);
else if(data <= root->data)
root->left=Insert(root->left,data);
else
root->right=Insert(root->right,data);
return root;
}
bool search(BstNode *root,int data)
{
if(root==NULL)
{
return false;
}
else if(root->data==data){
return true;
}
else if(root->data>=data){
return search(root->left,data);
}
else {
return search(root->right,data);
}
}
int findMin(BstNode *root)
{
/*if(root->left==NULL)
return root->data;
else findMin(root->left);*/
//same using iterative
while(root->left!=NULL)
{
root=root->left;
}
return root->data;
}
int findMax(BstNode *root)
{
if(root->right==NULL)
return root->data;
else findMax(root->right);
}
int max(int a,int b)
{
if(a>=b)
return a;
return b;
}
int height(BstNode *root)
{
if(root==NULL)
return 0;
return 1+max(height(root->left),height(root->right));
}
void levelOrder(BstNode *root)
{
/*if(root==NULL)
return;*/
queue<BstNode *> Q;
Q.push(root);
//cout<<Q.empty();
while(Q.empty()!=1)
{
BstNode *first=Q.front();
Q.pop();
cout<<first->data<<" ";
if(first->left!=NULL)
Q.push(first->left);
if(first->right!=NULL)
Q.push(first->right);
}
}
//Data,left,right
void preOrder(BstNode *root)
{
if(root==NULL)
return ;
cout<<root->data<<" ";
preOrder(root->left);
preOrder(root->right);
}
void postOrder(BstNode *root)
{
if(root==NULL)
return ;
preOrder(root->left);
preOrder(root->right);
cout<<root->data<<" ";
}
void inOrder(BstNode *root)
{
if(root==NULL)
return ;
inOrder(root->left);
cout<<root->data<<" ";
inOrder(root->right);
}
int main()
{
BstNode *root=NULL;
root = Insert(root,15);
root = Insert(root,10);
root = Insert(root,20);
root = Insert(root,25);
root = Insert(root,17);
root = Insert(root,8);
root = Insert(root,12);
if(search(root,0)==true)
cout<<"Found"<<"\n";
else
cout<<"Not Found"<<"\n\n";
cout<<findMin(root)<<"\n\n";
cout<<findMax(root)<<"\n\n";
cout<<height(root)<<"\n\n";
//breadth first
cout<<"\n\n level order :- \n\n";
levelOrder(root);
cout<<"\n\n pre order :- \n\n";
preOrder(root);
cout<<"\n\n post order :- \n\n";
postOrder(root);
cout<<"\n\n in order :- \n\n";
inOrder(root);
}
| true |
8b61129ba0977dd274a46dbcaec8a94a8cd655be | C++ | Marukyu/RankCheck | /src/Shared/Utils/StringStream.cpp | UTF-8 | 559 | 2.65625 | 3 | [
"MIT"
] | permissive | #include "Shared/Utils/StringStream.hpp"
#include <iostream>
StringStream::StringStream()
{
myStreamRedirect = 0;
}
StringStream::~StringStream()
{
}
StringStream::StringStream(std::ostream & redirect)
{
myStreamRedirect = &redirect;
}
StringStream StringStream::Cout(std::cout);
std::string StringStream::str() const
{
sf::Lock locky(myMutex);
return myStream.str();
}
void StringStream::str(const std::string & data)
{
sf::Lock locky(myMutex);
myStream.str(data);
}
void StringStream::clear()
{
sf::Lock locky(myMutex);
myStream.clear();
}
| true |
2fbaeb39e718dc1626b8cc4262451b4d1c0b72e2 | C++ | apache/celix | /libs/promises/gtest/src/VoidPromisesTestSuite.cc | UTF-8 | 20,169 | 2.734375 | 3 | [
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | permissive | /**
*Licensed to the Apache Software Foundation (ASF) under one
*or more contributor license agreements. See the NOTICE file
*distributed with this work for additional information
*regarding copyright ownership. The ASF licenses this file
*to you under the Apache License, Version 2.0 (the
*"License"); you may not use this file except in compliance
*with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing,
*software distributed under the License is distributed on an
*"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
*specific language governing permissions and limitations
*under the License.
*/
#include <gtest/gtest.h>
#include <future>
#include "celix/PromiseFactory.h"
class VoidPromiseTestSuite : public ::testing::Test {
public:
~VoidPromiseTestSuite() noexcept override {
factory->wait();
}
std::shared_ptr<celix::DefaultExecutor> executor = std::make_shared<celix::DefaultExecutor>();
std::shared_ptr<celix::PromiseFactory> factory = std::make_shared<celix::PromiseFactory>(executor);
};
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-result"
#endif
TEST_F(VoidPromiseTestSuite, simplePromise) {
auto deferred = factory->deferred<void>();
std::thread t{[&deferred] () {
std::this_thread::sleep_for(std::chrono::milliseconds{50});
deferred.resolve();
}};
auto promise = deferred.getPromise();
EXPECT_TRUE(promise.getValue()); //block until ready
EXPECT_TRUE(promise.isDone()); //got value, so promise is done
EXPECT_ANY_THROW(promise.getFailure()); //succeeded, so no exception available
EXPECT_TRUE(promise.getValue()); //note multiple call are valid;
t.join();
}
TEST_F(VoidPromiseTestSuite, failingPromise) {
auto deferred = factory->deferred<void>();
auto cpy = deferred;
std::thread t{[&deferred] () {
deferred.fail(std::logic_error{"failing"});
}};
auto promise = deferred.getPromise();
EXPECT_THROW(promise.getValue(), celix::PromiseInvocationException);
EXPECT_TRUE(promise.getFailure() != nullptr);
t.join();
}
TEST_F(VoidPromiseTestSuite, failingPromiseWithExceptionPtr) {
auto deferred = factory->deferred<void>();
std::thread t{[&deferred]{
try {
std::string{}.at(1); // this generates an std::out_of_range
//or use std::make_exception_ptr
} catch (...) {
deferred.fail(std::current_exception());
}
}};
auto promise = deferred.getPromise();
EXPECT_THROW(promise.getValue(), celix::PromiseInvocationException);
EXPECT_TRUE(promise.getFailure() != nullptr);
t.join();
}
TEST_F(VoidPromiseTestSuite, onSuccessHandling) {
auto deferred = factory->deferred<void>();
bool called = false;
bool resolveCalled = false;
auto p = deferred.getPromise()
.onSuccess([&called]() {
called = true;
})
.onResolve([&resolveCalled]() {
resolveCalled = true;
});
deferred.resolve();
factory->wait();
EXPECT_EQ(true, called);
EXPECT_EQ(true, resolveCalled);
}
TEST_F(VoidPromiseTestSuite, onFailureHandling) {
auto deferred = factory->deferred<void>();
bool successCalled = false;
bool failureCalled = false;
bool resolveCalled = false;
auto p = deferred.getPromise()
.onSuccess([&]() {
successCalled = true;
})
.onFailure([&](const std::exception &e) {
failureCalled = true;
std::cout << "got error: " << e.what() << std::endl;
})
.onResolve([&resolveCalled]() {
resolveCalled = true;
});
try {
std::string{}.at(1); // this generates an std::out_of_range
//or use std::make_exception_ptr
} catch (...) {
deferred.fail(std::current_exception());
}
factory->wait();
EXPECT_EQ(false, successCalled);
EXPECT_EQ(true, failureCalled);
EXPECT_EQ(true, resolveCalled);
}
TEST_F(VoidPromiseTestSuite, onFailureHandlingLogicError) {
auto deferred = factory->deferred<void>();
std::atomic<bool> successCalled = false;
std::atomic<bool> failureCalled = false;
std::atomic<bool> resolveCalled = false;
auto p = deferred.getPromise()
.onSuccess([&]() {
successCalled = true;
})
.onFailure([&](const std::exception &e) {
failureCalled = true;
ASSERT_TRUE(0 == strcmp("Some Exception", e.what())) << std::string(e.what());
})
.onResolve([&]() {
resolveCalled = true;
});
deferred.fail(std::logic_error("Some Exception"));
factory->wait();
EXPECT_EQ(false, successCalled);
EXPECT_EQ(true, failureCalled);
EXPECT_EQ(true, resolveCalled);
}
TEST_F(VoidPromiseTestSuite, onFailureHandlingPromiseIllegalStateException) {
auto deferred = factory->deferred<void>();
std::atomic<bool> successCalled = false;
std::atomic<bool> failureCalled = false;
std::atomic<bool> resolveCalled = false;
auto p = deferred.getPromise()
.onSuccess([&]() {
successCalled = true;
})
.onFailure([&](const std::exception &e) {
failureCalled = true;
ASSERT_TRUE(0 == strcmp("Illegal state", e.what())) << std::string(e.what());
})
.onResolve([&]() {
resolveCalled = true;
});
deferred.fail(celix::PromiseIllegalStateException());
factory->wait();
EXPECT_EQ(false, successCalled);
EXPECT_EQ(true, failureCalled);
EXPECT_EQ(true, resolveCalled);
}
TEST_F(VoidPromiseTestSuite, onFailureHandlingPromiseInvocationException) {
auto deferred = factory->deferred<void>();
std::atomic<bool> successCalled = false;
std::atomic<bool> failureCalled = false;
std::atomic<bool> resolveCalled = false;
auto p = deferred.getPromise()
.onSuccess([&]() {
successCalled = true;
})
.onFailure([&](const std::exception &e) {
failureCalled = true;
ASSERT_TRUE(0 == strcmp("MyExceptionText", e.what())) << std::string(e.what());
})
.onResolve([&]() {
resolveCalled = true;
});
deferred.fail(celix::PromiseInvocationException("MyExceptionText"));
factory->wait();
EXPECT_EQ(false, successCalled);
EXPECT_EQ(true, failureCalled);
EXPECT_EQ(true, resolveCalled);
}
TEST_F(VoidPromiseTestSuite, resolveSuccessWith) {
auto deferred1 = factory->deferred<void>();
bool called = false;
deferred1.getPromise()
.onSuccess([&called]() {
called = true;
});
auto deferred2 = factory->deferred<int>();
deferred1.resolveWith(deferred2.getPromise());
deferred2.resolve(42);
factory->wait();
EXPECT_EQ(true, called);
auto deferred3 = factory->deferred<void>();
called = false;
deferred3.getPromise()
.onSuccess([&called]() {
called = true;
});
auto deferred4 = factory->deferred<void>();
deferred3.resolveWith(deferred4.getPromise());
deferred4.resolve();
factory->wait();
EXPECT_EQ(true, called);
}
TEST_F(VoidPromiseTestSuite, resolveFailureWith) {
auto deferred1 = factory->deferred<void>();
auto deferred2 = factory->deferred<void>();
std::atomic<bool> failureCalled = false;
std::atomic<bool> successCalled = false;
deferred2.getPromise()
.onSuccess([&]() {
successCalled = true;
})
.onFailure([&](const std::exception &e) {
failureCalled = true;
std::cout << "got error: " << e.what() << std::endl;
});
//currently deferred1 will be resolved in thread, and onSuccess is trigger on the promise of deferred2
//now resolving deferred2 with the promise of deferred1
deferred2.resolveWith(deferred1.getPromise());
auto p = deferred2.getPromise();
try {
std::string().at(1); // this generates an std::out_of_range
//or use std::make_exception_ptr
} catch (...) {
deferred1.fail(std::current_exception());
}
factory->wait();
EXPECT_EQ(false, successCalled);
EXPECT_EQ(true, failureCalled);
}
TEST_F(VoidPromiseTestSuite, returnPromiseOnSuccessfulResolveWith) {
auto deferred1 = factory->deferred<void>();
auto deferred2 = factory->deferred<void>();
celix::Promise<void> promise = deferred1.resolveWith(deferred2.getPromise());
EXPECT_FALSE(promise.isDone());
deferred2.resolve();
factory->wait();
EXPECT_TRUE(promise.isDone());
EXPECT_TRUE(promise.isSuccessfullyResolved());
}
TEST_F(VoidPromiseTestSuite, returnPromiseOnInvalidResolveWith) {
auto deferred1 = factory->deferred<void>();
auto deferred2 = factory->deferred<long>();
celix::Promise<void> promise = deferred1.resolveWith(deferred2.getPromise());
EXPECT_FALSE(promise.isDone());
deferred1.resolve(); //Rule is deferred1 is resolved, before the resolveWith the returned promise should fail
deferred2.resolve(42);
factory->wait();
EXPECT_TRUE(promise.isDone());
EXPECT_FALSE(promise.isSuccessfullyResolved());
EXPECT_THROW(std::rethrow_exception(promise.getFailure()), celix::PromiseIllegalStateException);
}
//gh-333 fix timeout test on macos
#ifndef __APPLE__
TEST_F(VoidPromiseTestSuite, resolveWithTimeout) {
auto promise1 = factory->deferredTask<void>([](auto d) {
std::this_thread::sleep_for(std::chrono::milliseconds{50});
try {
d.resolve();
} catch(...) {
//note resolve with throws an exception if promise is already resolved
}
});
std::atomic<bool> firstSuccessCalled = false;
std::atomic<bool> secondSuccessCalled = false;
std::atomic<bool> secondFailedCalled = false;
promise1
.onSuccess([&]() {
firstSuccessCalled = true;
})
.timeout(std::chrono::milliseconds{10})
.onSuccess([&]() {
secondSuccessCalled = true;
})
.onFailure([&](const std::exception&) {
secondFailedCalled = true;
});
promise1.wait();
factory->wait();
EXPECT_EQ(true, firstSuccessCalled);
EXPECT_EQ(false, secondSuccessCalled);
EXPECT_EQ(true, secondFailedCalled);
firstSuccessCalled = false;
secondSuccessCalled = false;
secondFailedCalled = false;
auto promise2 = factory->deferredTask<void>([](auto d) {
d.resolve();
});
promise2
.onSuccess([&]() {
firstSuccessCalled = true;
})
.timeout(std::chrono::milliseconds{250}) /*NOTE: more than the possible delay introduced by the executor*/
.onSuccess([&]() {
secondSuccessCalled = true;
})
.onFailure([&](const std::exception&) {
secondFailedCalled = true;
});
promise2.wait();
factory->wait();
EXPECT_EQ(true, firstSuccessCalled);
EXPECT_EQ(true, secondSuccessCalled);
EXPECT_EQ(false, secondFailedCalled);
}
#endif
TEST_F(VoidPromiseTestSuite, resolveWithSetTimeout) {
auto promise = factory->deferred<void>().getPromise().setTimeout(std::chrono::milliseconds{5});
factory->wait();
EXPECT_TRUE(promise.isDone());
EXPECT_FALSE(promise.isSuccessfullyResolved());
}
TEST_F(VoidPromiseTestSuite, resolveWithDelay) {
auto deferred1 = factory->deferred<void>();
std::atomic<bool> successCalled = false;
std::atomic<bool> failedCalled = false;
auto t1 = std::chrono::system_clock::now();
std::atomic<std::chrono::system_clock::time_point> t2{t1};
auto p = deferred1.getPromise()
.delay(std::chrono::milliseconds{50})
.onSuccess([&]() {
successCalled = true;
t2 = std::chrono::system_clock::now();
})
.onFailure([&](const std::exception&) {
failedCalled = true;
});
deferred1.resolve();
p.wait();
factory->wait();
EXPECT_EQ(true, successCalled);
EXPECT_EQ(false, failedCalled);
auto durationInMs = std::chrono::duration_cast<std::chrono::milliseconds>(t2.load() - t1);
EXPECT_GE(durationInMs, std::chrono::milliseconds{10});
}
TEST_F(VoidPromiseTestSuite, resolveWithRecover) {
auto deferred1 = factory->deferred<void>();
std::atomic<bool> successCalled = false;
deferred1.getPromise()
.recover([]{ return 42; })
.onSuccess([&]() {
successCalled = true;
});
try {
throw std::logic_error("failure");
} catch (...) {
deferred1.fail(std::current_exception());
}
factory->wait();
EXPECT_EQ(true, successCalled);
}
TEST_F(VoidPromiseTestSuite, chainAndMapResult) {
auto deferred1 = factory->deferred<void>();
std::thread t{[&deferred1]{
deferred1.resolve();
}};
int two = deferred1.getPromise()
.map<int>([]() {
return 2;
}).getValue();
t.join();
factory->wait();
EXPECT_EQ(2, two);
}
TEST_F(VoidPromiseTestSuite, chainWithThenAccept) {
auto deferred1 = factory->deferred<void>();
std::atomic<bool> called = false;
deferred1.getPromise()
.thenAccept([&](){
called = true;
});
deferred1.resolve();
factory->wait();
EXPECT_TRUE(called);
}
TEST_F(VoidPromiseTestSuite, promiseWithFallbackTo) {
auto deferred1 = factory->deferred<void>();
try {
throw std::logic_error("failure");
} catch (...) {
deferred1.fail(std::current_exception());
}
auto deferred2 = factory->deferred<void>();
deferred2.resolve();
long val = deferred1.getPromise().fallbackTo(deferred2.getPromise()).getValue();
EXPECT_TRUE(val);
}
TEST_F(VoidPromiseTestSuite, outOfScopeUnresolvedPromises) {
std::atomic<bool> called = false;
{
auto deferred1 = factory->deferred<void>();
deferred1.getPromise().onResolve([&]{
called = true;
});
//promise and deferred out of scope
}
factory->wait();
EXPECT_FALSE(called);
}
TEST_F(VoidPromiseTestSuite, chainPromises) {
auto success = [&](celix::Promise<void> p) -> celix::Promise<long> {
//TODO Promises::resolved(p.getValue() + p.getValue())
auto result = factory->deferred<long>();
p.getValue();
result.resolve(42);
return result.getPromise();
};
auto initial = factory->deferred<void>();
initial.resolve();
long result = initial.getPromise().then<long>(success).getValue();
EXPECT_EQ(42, result);
}
TEST_F(VoidPromiseTestSuite, chainFailedPromises) {
std::atomic<bool> called = false;
auto success = [](celix::Promise<void> p) -> celix::Promise<void> {
//nop
return p;
};
auto failed = [&](const celix::Promise<void>& /*p*/) -> void {
called = true;
};
auto deferred = factory->deferred<void>();
deferred.fail(std::logic_error{"fail"});
deferred.getPromise().then<void>(success, failed);
factory->wait();
EXPECT_TRUE(called);
}
TEST_F(VoidPromiseTestSuite, failedResolvedWithPromiseFactory) {
auto factory = celix::PromiseFactory{};
auto p1 = factory.failed<void>(std::logic_error{"test"});
EXPECT_TRUE(p1.isDone());
EXPECT_NE(nullptr, p1.getFailure());
auto p2 = factory.resolved();
EXPECT_TRUE(p2.isDone());
EXPECT_TRUE(p2.getValue());
}
TEST_F(VoidPromiseTestSuite, deferredTaskCall) {
auto t1 = std::chrono::system_clock::now();
auto promise = factory->deferredTask<void>([](auto deferred) {
std::this_thread::sleep_for(std::chrono::milliseconds{12});
deferred.resolve();
});
promise.wait();
auto t2 = std::chrono::system_clock::now();
auto durationInMs = std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1);
EXPECT_GT(durationInMs, std::chrono::milliseconds{10});
}
TEST_F(VoidPromiseTestSuite, testRobustFailAndResolve) {
std::atomic<int> failCount{};
std::atomic<int> successCount{};
auto failCb = [&failCount](const std::exception& /*e*/) {
failCount++;
};
auto successCb = [&successCount]() {
successCount++;
};
auto def = factory->deferred<void>();
def.getPromise().onFailure(failCb);
//Rule a second fail should not lead to an exception, to ensure a more robust usage.
//But also should only lead to a single resolve chain.
def.fail(std::logic_error{"error1"});
def.fail(std::logic_error{"error2"});
factory->wait();
EXPECT_EQ(failCount.load(), 1);
def = factory->deferred<void>();
def.getPromise().onSuccess(successCb);
//Rule a second resolve should not lead to an exception, to ensure a more robust usage.
//But also should only lead to a single resolve chain.
def.resolve();
def.resolve();
factory->wait();
EXPECT_EQ(successCount.load(), 1);
failCount = 0;
successCount = 0;
def = factory->deferred<void>();
def.getPromise().onSuccess(successCb).onFailure(failCb);
//Rule a resolve after fail should not lead to an exception, to ensure a more robust usage.
//But also should only lead to a single resolve chain.
def.fail(std::logic_error("error3"));
def.resolve();
factory->wait();
EXPECT_EQ(failCount.load(), 1);
EXPECT_EQ(successCount.load(), 0);
failCount = 0;
successCount = 0;
def = factory->deferred<void>();
def.getPromise().onSuccess(successCb).onFailure(failCb);
//Rule a fail after resolve should not lead to an exception, to ensure a more robust usage.
//But also should only lead to a single resolve chain.
def.resolve();
def.fail(std::logic_error("error3"));
factory->wait();
EXPECT_EQ(failCount.load(), 0);
EXPECT_EQ(successCount.load(), 1);
}
TEST_F(VoidPromiseTestSuite, testTryFailAndResolve) {
std::atomic<int> failCount{};
std::atomic<int> successCount{};
auto failCb = [&failCount](const std::exception& /*e*/) {
failCount++;
};
auto successCb = [&successCount]() {
successCount++;
};
//first resolve, then try rest
auto def = factory->deferred<void>();
def.getPromise().onSuccess(successCb).onFailure(failCb);
EXPECT_TRUE(def.tryResolve());
EXPECT_FALSE(def.tryFail(std::logic_error{"error"}));
EXPECT_FALSE(def.tryFail(std::make_exception_ptr(std::logic_error{"error"})));
factory->wait();
EXPECT_EQ(failCount.load(), 0);
EXPECT_EQ(successCount.load(), 1);
//first fail with exp ref, then try rest
failCount = 0;
successCount = 0;
def = factory->deferred<void>();
def.getPromise().onSuccess(successCb).onFailure(failCb);
EXPECT_TRUE(def.tryFail(std::logic_error{"error"}));
EXPECT_FALSE(def.tryResolve());
EXPECT_FALSE(def.tryFail(std::logic_error{"error"}));
EXPECT_FALSE(def.tryFail(std::make_exception_ptr(std::logic_error{"error"})));
factory->wait();
EXPECT_EQ(failCount.load(), 1);
EXPECT_EQ(successCount.load(), 0);
//first fail with exp ptr, then try rest
failCount = 0;
successCount = 0;
def = factory->deferred<void>();
def.getPromise().onSuccess(successCb).onFailure(failCb);
EXPECT_TRUE(def.tryFail(std::make_exception_ptr(std::logic_error{"error"})));
EXPECT_FALSE(def.tryResolve());
EXPECT_FALSE(def.tryFail(std::logic_error{"error"}));
EXPECT_FALSE(def.tryFail(std::make_exception_ptr(std::logic_error{"error"})));
factory->wait();
EXPECT_EQ(failCount.load(), 1);
EXPECT_EQ(successCount.load(), 0);
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif
| true |
b96fb98b509ca662fe68f969a23da44089eff588 | C++ | goopey7/BinarySearchTree | /main.cpp | UTF-8 | 252 | 2.6875 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include "BinaryTree.h"
int main()
{
BinaryTree tree;
tree.insert(20);
tree.insert(30);
tree.insert(10);
std::cout << tree.toString() << std::endl;
tree.remove(20);
std::cout << tree.toString() << std::endl;
return 0;
}
| true |
d1ce51a6030c25b06c8637924e97cff4445c136e | C++ | garrettsickles/CSCI262 | /labs/PostfixCalculator/postfix_calculator.cpp | UTF-8 | 2,805 | 3.390625 | 3 | [] | no_license | /*
postfix_calculator.cpp
For CSCI 262, Fall 2013, Lab 3.
Implementation of the postfix calculator. You should modify the code
everywhere you see a "TODO" comment!
*/
#include "postfix_calculator.h"
#include <iostream>
#include <sstream>
#include <string>
#include <cmath>
bool postfix_calculator::evaluate(std::string expr) {
std::istringstream input(expr);
std::string parse;
double parseNum;
double operand[2] = {0.0, 0.0};
_stack_underflow_flag = false;
_invalid_operator_flag = false;
_invalid_operator_string = "";
while (input >> parse) {
if(to_double(parse, parseNum)) _stack.push(parseNum);
else if(parse == "sin" || parse == "cos" || parse == "tan" || parse == "log" || parse == "ln" || parse == "sqrt") {
if(_stack.size() == 0)
_stack_underflow_flag = true;
else {
operand[0] = _stack.top();
_stack.pop();
if(parse == "sin") _stack.push(std::sin(operand[0]));
else if(parse == "cos") _stack.push(std::cos(operand[0]));
else if(parse == "tan") _stack.push(std::tan(operand[0]));
else if(parse == "log") _stack.push(std::log10(operand[0]));
else if(parse == "ln") _stack.push(std::log(operand[0]));
else if(parse == "sqrt")_stack.push(std::sqrt(operand[0]));
}
}
else if(parse == "*" || parse == "/" || parse == "-" || parse == "+" || parse == "^") {
if(_stack.size() <= 1)
_stack_underflow_flag = true;
else {
operand[1] = _stack.top();
_stack.pop();
operand[0] = _stack.top();
_stack.pop();
if (parse == "*") _stack.push(operand[0] * operand[1]);
else if (parse == "/") _stack.push(operand[0] / operand[1]);
else if (parse == "-") _stack.push(operand[0] - operand[1]);
else if (parse == "+") _stack.push(operand[0] + operand[1]);
else if (parse == "^") _stack.push(std::pow(operand[0], operand[1]));
}
}
else {
_invalid_operator_flag = true;
_invalid_operator_string = parse;
}
}
return(!(_stack_underflow_flag || _invalid_operator_flag));
}
void postfix_calculator::clear() {
while(!_stack.empty())
_stack.pop();
_stack_underflow_flag = false;
_invalid_operator_flag = false;
_invalid_operator_string = "";
}
double postfix_calculator::top() {
return(_stack.top() * !_stack.empty());
}
bool postfix_calculator::to_double(const std::string &s, double &d) {
std::istringstream cvt(s);
cvt >> d;
return !(cvt.fail()) && cvt.eof();
}
| true |
48e1909fed86212a4cfc167c83c2f14584c13611 | C++ | Waterx/Cpp_Learning | /mooc-homework/mooc4-4 ege/main.cpp | UTF-8 | 2,881 | 3.28125 | 3 | [] | no_license | #include"graphics.h"
#include<cstdlib>
using namespace std;
class Screen;
class MyRectangle;
class Screen {
public:
Screen();
Screen(int newWidth,int newHeight);
~Screen(){
closegraph();
}
int getWidth() {
return width;
}
int getHeight() {
return height;
}
int setWidth(int width) //return width
{
this->width = width;
return width;
}
int setHeight(int height) //return height
{
this->height = height;
return height;
}
private:
int width;
int height;
int exitWhenInvalidScreen(int width, int height);
};
Screen::Screen() {
width = 640;
height = 480;
initgraph(width,height);
outtextxy(10,10,"screen");
}
Screen::Screen(int newWidth, int newHeight) {
width = newWidth;
height = newHeight;
exitWhenInvalidScreen(width, height);
initgraph(width,height);
outtextxy(10,10,"screen");
}
int Screen::exitWhenInvalidScreen(int width, int height) {
if (width > 0 && height > 0 && width <= 1000 && height <= 1000)
{
return 1;
}
else
{
outtextxy(10,10,"invalid screen size");
exit(0);
}
}
//---------------------------------------------------------------------------------------------
class MyRectangle {
public:
MyRectangle();
MyRectangle(int x1, int y1, int x2, int y2, Screen* screen);
void setCoordinations(int nx1, int ny1, int nx2, int ny2);
int setScreen(Screen& screen);
void Draw();
private:
Screen* screen_;
int x1, y1, x2, y2;
};
MyRectangle::MyRectangle() {
x1 = 0;
y1 = 0;
x2 = 0;
y2 = 0;
outtextxy(10,30,"myrectangle");
}
MyRectangle::MyRectangle(int x1, int y1, int x2, int y2, Screen* screen) {
this->x1 = x1;
this->x2 = x2;
this->y1 = y1;
this->y2 = y2;
screen_ = screen;
outtextxy(10,30,"myrectangle");
}
void MyRectangle::setCoordinations(int nx1, int ny1, int nx2, int ny2) {
x1 = nx1;
x2 = nx2;
y1 = ny1;
y2 = ny2;
}
int MyRectangle::setScreen(Screen& screen) {
screen_ = &screen;
return 1;
}
void MyRectangle::Draw() {
int rwidth = x2 - x1;
int rheight = y2 - y1;;
if (rwidth <= 0 || rheight <= 0||rwidth>=screen_->getWidth()||rheight>=screen_->getHeight()) {
outtextxy(10,50,"invalid myrectangle");
}
else if (x1 == 0 || y1 == 0 || x2 == screen_->getWidth() || y2 == screen_->getHeight()) {
outtextxy(10,50,"invalid myrectangle");
}
else {
rectangle(x1,y1,x2,y2);
xyprintf(10,50,"%d,%d,%d,%d",x1,y1,rwidth,rheight);
}
}
//--------------------------------------------------------------------------------------
int main() {
int width = 640, height = 480;
initgraph(width,height);
width = getInteger("Screen width");
height = getInteger("Screen height");
Screen screen(width,height);
int leftX, leftY, rightX, rightY;
leftX = getInteger("leftX");
leftY = getInteger("leftY");
rightX = getInteger("rightX");
rightY = getInteger("rightY");
MyRectangle myRectangle1(leftX, leftY, rightX, rightY, &screen);
myRectangle1.Draw();
ege::getch();
return 0;
}
| true |
d111a83b6332496a1504f37505b52802bd89bfea | C++ | pavanpvl/cp_problems | /codechef/DSA/Qhouse.cpp | UTF-8 | 988 | 2.578125 | 3 | [] | no_license | #include <bits/stdc++.h>
#define DEBUG
using namespace std;
int find(int c, int d)
{
int l = 0, r = 1000, res{};
int m;
string s;
while (l <= r)
{
m = l + (r - l) / 2;
if (d)
cout << "? " << m << " " << c << endl
<< flush;
else
cout << "? " << c << " " << m << endl
<< flush;
cin >> s;
if (s == "YES")
{
res = m;
l = m + 1;
}
else
r = m - 1;
}
return res;
}
int main()
{
/* ios_base::sync_with_stdio(false);
cin.tie(NULL);
#ifndef ONLINE_JUDGE
freopen("/home/pavan/cp_problems/a.in", "r", stdin);
freopen("/home/pavan/cp_problems/a.out", "w", stdout);
#endif */
int a, b, c;
int x, y, res{};
x = 0;
y = 0;
a = find(x, 0);
b = find(y, 1);
c = find(2 * b, 1);
res = (a - 2 * b) * c + (4*b)*b;
cout << "! " << res << endl<<flush;
return 0;
} | true |
3477c1bd7c80b5ff7790ac51505bfd9c522407ab | C++ | deepakantony/rendering | /dray/images/prog04/extra_credit/fft.cc | UTF-8 | 2,955 | 2.9375 | 3 | [] | no_license | // To use this program, pass in a PPM file on stdin and it will send the
// Fourier transform to stdout. i.e.:
//
// ./fft < prog04.ppm > prog04-fft.ppm
//
// Depending on the intensities in your image, you may need to adjust the
// value on line 82.
#include <math.h>
#include <complex>
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
typedef complex< double > comp;
static const double pi = 3.141592653589793;
void fft( comp *data, int size, int stride ) {
for ( int index = 0; index < size; ++index ) {
int reversed = 0;
for ( int bit = 0; ( 1 << bit ) < size; ++bit )
reversed = ( reversed << 1 ) + ( ( index >> bit ) & 1 );
if ( index < reversed )
swap( data[ index * stride ], data[ reversed * stride ] );
}
for ( int pass = 1; pass < size; pass *= 2 ) {
double theta = -pi / pass;
double sin_half_theta = sin( 0.5 * theta );
comp recurrence( -2.0 * sin_half_theta * sin_half_theta, sin( theta ) );
comp omega( 1.0, 0.0 );
for ( int block = 0; block < pass; ++block ) {
for ( int butterfly = block; butterfly < size; butterfly += pass * 2 ) {
int top = butterfly * stride;
int bottom = ( butterfly + pass ) * stride;
comp shift( data[ bottom ] * omega );
data[ bottom ] = data[ top ] - shift;
data[ top ] += shift;
}
omega += omega * recurrence;
}
}
}
int main( int argc, char ** argv ) {
string magic;
int width, height, maximum;
cin >> magic >> width >> height >> maximum;
cin.get();
comp *data = new comp[ width * height ];
for ( int y = 0; y < height; ++y ) {
for ( int x = 0; x < width; ++x ) {
double luminance = cin.get() * 0.30;
luminance += cin.get() * 0.59;
luminance += cin.get() * 0.11;
data[ y * width + x ] = comp( luminance, 0.0 );
}
}
for ( int y = 0; y < height; ++y ) {
cerr << y << "\r";
fft( data + y * width, width, 1 );
}
for ( int x = 0; x < width; ++x ) {
cerr << x << " \r";
fft( data + x, height, width );
}
cout << "P6 " << width << " " << height << " 255 ";
double total = 0.0;
int counted = 0;
for ( int y = 0; y < height; ++y )
for ( int x = 0; x < width; ++x )
if ( ( x > 2 && x < width - 2 ) ||
( y > 2 && y < height - 2 ) ) {
double value = abs( data[ y * width + x ] );
if ( value > 0.0 ) {
total += log( value );
++counted;
}
}
double amplification = 20.0 / exp( total / counted );
for ( int y = 0; y < height; ++y )
for ( int x = 0; x < width; ++x ) {
int index = ( ( ( y + height / 2 ) % height ) * width +
( ( x + width / 2 ) % width ) );
double value = min( 255.0, abs( data[ index ] ) * amplification );
unsigned char grey = static_cast< unsigned char >( value );
cout.put( grey );
cout.put( grey );
cout.put( grey );
}
return 0;
}
| true |
adf38aa01ffd5c4389b9d2a05900940857c65256 | C++ | freddyox/screen_saver | /src/Owl.cpp | UTF-8 | 2,553 | 2.578125 | 3 | [
"MIT"
] | permissive | #include "../include/Owl.hh"
#include <cmath>
Owl::Owl(){
if (!fOwlSheet.loadFromFile("images/Bird_Owl_noBG.png")) {
std::cout << "Owl sheet not found..." << std::endl;
}
fChangeSprite = 0.1; // sec
fTime = 0.0;
fTempTime = 0.0;
fAlphaTime = 0.25;
fAlphaTimeTemp = 0.0;
fHootOnce = true;
// Make it easy to read
fOrientation["facing"] = 0;
fOrientation["left"] = 1;
fOrientation["farleft"] = 2;
fOrientation["awayleft"] = 3;
fOrientation["away"] = 4;
fOrientation["misc"] = 5;
fScale = 0.0;
int ncol = 8;
int nrow = 6;
int dcol = 760 / ncol; // hard-coded dimensions of the texture
int drow = 587 / nrow;
for(int col=0; col<ncol; col++){
for(int row=0; row<nrow; row++){
if(row==nrow-1 && col==5) break; // sprite ends here
int left = col*dcol;
int top = row*drow;
sf::Sprite test(fOwlSheet,sf::IntRect(left,top,dcol,drow));
test.setColor(sf::Color(150,150,150,200)); // initialize to zero
test.setScale(0.0,0.0);
sf::FloatRect box = test.getLocalBounds();
test.setOrigin(0.5*box.width,0.5*box.height);
fOwlMovesMap[row].push_back( test );
if(row==0) fOwlMoves.push_back( test );
}
}
fIndex = 0;
fDirIndex=0;
if (!buffer.loadFromFile("owl.wav")){
std::cout << "Error with the owl sounds" << std::endl;
}
fHoot.setBuffer(buffer);
fHoot.setVolume(50);
}
Owl::~Owl(){
;
}
void Owl::update(float dt, sf::Vector2f pos, bool dark, sf::Vector2f moonpos){
fTime += dt;
fTempTime += dt;
fAlphaTimeTemp += dt;
fItsDark = dark;
sf::Vector2f D = pos-moonpos;
float R = sqrt( D.x*D.x + D.y*D.y );
if( fItsDark ){
for(unsigned int i=0; i<fOwlMovesMap[fDirIndex].size(); i++) {
if( moonpos.x > 0.2*fX && moonpos.x<0.5*fX){
if(fAlphaTimeTemp>fAlphaTime) {
fDirIndex=0;
fScale+=0.03;
fAlphaTimeTemp = 0.0;
if(fScale>1.0) fScale=1.0;
}
}
if( moonpos.x > 0.5*fX && moonpos.x < 0.55*fX && fHootOnce){
fHoot.play();
fHootOnce = false;
}
if( moonpos.x>0.55*fX) fHootOnce = true;
if( moonpos.x > 0.6*fX ){
if(fAlphaTimeTemp>fAlphaTime) {
fDirIndex=4;
fScale-=0.02;
fAlphaTimeTemp = 0.0;
if(fScale<0.1) fScale=0.0;
}
}
fOwlMovesMap[fDirIndex][i].setScale(fScale,fScale);
fOwlMovesMap[fDirIndex][i].setPosition(sf::Vector2f(pos.x, pos.y-30));
}
if( fTempTime > fChangeSprite ){
fIndex++;
if( fIndex==fOwlMovesMap[fDirIndex].size() ) fIndex = 0;
fTempTime = 0.0;
}
}
}
| true |
d89bf322f3e56eb63d97f13e7443aac499f11067 | C++ | taniave/Club-de-Algoritmia | /MINHEAP_final.cpp | UTF-8 | 1,594 | 3.171875 | 3 | [] | no_license | //MINHEAP -> ordena 10 numeros
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e3 + 10;
int tree[maxn];
int sz = 0;
int getParent(int index){
return(index-1)/2;
}
int getLeftChild(int index){
return (index*2) + 1;
}
int getRightChild(int index){
return(index*2)+2;
}
bool hasParent(int index){
return getParent(index) >= 0;
}
bool hasLeftChild(int index){
return getLeftChild(index) < sz;
}
bool hasRightChild(int index){
return getRightChild(index) < sz;
}
void getMin(){
if(sz == 0)
printf("Esta vacio\n");
else
printf("%d\n",tree[0]);
}
void swap(int parent, int child){
int temp = tree[parent];
tree[parent]= tree[child];
tree[child] = temp;
}
void insert(int value){
int index = sz;
tree[sz] = value;
while(hasParent(index)){
if(tree[getParent(index)] > tree[index]){
swap(getParent(index),index);
index = getParent(index);
}else{
break;
}
}
++sz;
}
int erase(){
int temp = tree[0], index = 0, minChild;
tree[0] = tree[--sz];
while(hasLeftChild(index)){
minChild = getLeftChild(index);
if(hasRightChild(index) && tree[getRightChild(index)] < tree[minChild])
minChild = getRightChild(index);
if(tree[minChild] < tree[index]){
swap(index,minChild);
} else{
break;
}
index = minChild;
}
return temp;
}
int main(){
int num;
for(int i=0; i<10; i++){
scanf("%d",&num);
insert(num);
}
while(sz != 0){
printf("%d\n",erase());
}
return 0;
}
| true |
9a4e4d0034cfb12d86758ee35d49d7eaacb2e741 | C++ | leaflet757/CPP-SFML-Assignments | /Summer15 SFML Assignments/SFML Console Test/Main.cpp | UTF-8 | 2,045 | 3.359375 | 3 | [] | no_license | #include <SFML/Graphics.hpp>
#include <cstdio>
#include <thread>
#include <iostream>
#include <mutex>
#include <string>
using namespace std;
std::mutex _lock;
bool running = true;
long int testNum = 0;
long updateNumer = 0;
// Create Dummy Shape
sf::CircleShape shape(10.f);
void renderingFunction(sf::RenderWindow* window)
{
// activate the window's context
window->setActive(true);
window->setVerticalSyncEnabled(true);
// the rendering loop
while (running)
{
// set lock to finish rendering
_lock.lock();
// clear the buffers
window->clear();
// DEBUG
cout << "render " << testNum-- << endl;
// draw...
window->draw(shape);
// end the current frame (internally swaps the front and back buffers)
window->display();
// release lock for update thread
_lock.unlock();
}
}
void updateFunction(sf::RenderWindow* window)
{
// DEBUG
shape.setPosition(0, window->getSize().y / 2 - shape.getRadius());
shape.setFillColor(sf::Color::Green);
while (running)
{
// lock thread to finish updating
_lock.lock();
// Update logic...
cout << "logic " << testNum++ << endl;
cout << " update number: " << updateNumer++ << endl;
shape.setPosition(shape.getPosition().x + 1, shape.getPosition().y);
// release lock for rendering thread
_lock.unlock();
}
}
int main()
{
// create the window (remember: it's safer to create it in the main thread due to OS limitations)
sf::RenderWindow window(sf::VideoMode(800, 600), "Pong");
// deactivate its OpenGL context
window.setActive(false);
// launch the rendering & update thread
thread updateThread(updateFunction, &window);
thread renderingThread(renderingFunction, &window);
// Main thread to check for window closing
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed || sf::Keyboard::isKeyPressed(sf::Keyboard::Escape))
{
window.close();
running = false;
}
}
}
// stop threads
renderingThread.join();
updateThread.join();
return 0;
}
| true |
ce2fd57467c6a5e5174ab59f171b6c9ce526821e | C++ | glsubri/morninglight | /arduino/lib/AlarmManager/src/Alarm.h | UTF-8 | 1,220 | 3.734375 | 4 | [
"MIT"
] | permissive | #ifndef ALARM_H
#define ALARM_H
#include <Time.h>
/**
* @brief Data class used to store an Alarm
*
*/
class Alarm {
public:
/**
* @brief Construct a new default Alarm object
*
*/
Alarm();
/**
* @brief Construct a new specific Alarm object
*
* @param enabled Is the alarm on or off
* @param startTime The Start time of the alarm
* @param duration The duration of the alarm (in minutes)
*/
Alarm(bool enabled, Time startTime, unsigned int duration);
// Definition of == operator
bool operator==(const Alarm& other) const { return this->equals(other); }
// Definition of != operator
bool operator!=(const Alarm& other) const { return !this->equals(other); }
// All of these members are public because this is a data class
bool enabled;
Time startTime;
unsigned int duration; // minutes
private:
/**
* @brief Defines equality between current Alarm instance and another Alarm instance
*
* @param other The other Alarm instance to compare with
* @return true If both instances are equal
* @return false If they are not equal
*/
bool equals(const Alarm& other) const;
};
#endif | true |
62980612ee8fc38c898d181a639f524d643c7e55 | C++ | rosswarren/OpenGL-Terrain | /RawLoader.cpp | UTF-8 | 1,747 | 3.25 | 3 | [] | no_license | #include "RawLoader.h"
RawLoader::RawLoader(void) {
}
RawLoader::~RawLoader(void) {
}
// load a texture and return its OpengGL mapped integer
GLuint RawLoader::LoadTextureRAW(char * filename, int wrap, int width, int height) {
GLuint texture;
GLubyte * data;
FILE * file;
//char * folder = "Textures\\";
// open texture data
file = fopen(filename, "rb");
if (file == NULL) {
throw "File not found";
}
// allocate buffer
width = width;
height = height;
int memorySize = width * height * 3;
data = (GLubyte *)malloc(memorySize);
// read texture data
fread(data, memorySize, 1, file);
fclose(file);
// allocate a texture name
glGenTextures(1, &texture);
// select our current texture
glBindTexture(GL_TEXTURE_2D, texture);
// select modulate to mix texture with color for shading
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
// when texture area is small, bilinear filter the closest mipmap
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
// when texture area is large, bilinear filter the first mipmap
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// if wrap is true, the texture wraps over at the edges (repeat)
// ... false, the texture ends at the edges (clamp)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrap ? GL_REPEAT : GL_CLAMP);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrap ? GL_REPEAT : GL_CLAMP);
// build our texture mipmaps
gluBuild2DMipmaps(GL_TEXTURE_2D, 3, width, height, GL_RGB, GL_UNSIGNED_BYTE, data);
// free buffer
free(data);
std::cout << filename << " loaded \n";
return texture;
} | true |
c058724c897e3e670566f9b34166f09297229bb3 | C++ | R-droid101/DSA | /Graphs/sample.cpp | UTF-8 | 1,049 | 3 | 3 | [] | no_license | #include <stdio.h>
#include <iostream>
#include <conio.h>
using namespace std;
int a[20][20], q[20], visited[20], n, i, j, f = 0, r = -1;
void bfs(int v)
{
for (i = 1; i <= n; i++)
if (a[v][i] && !visited[i])
q[++r] = i;
if (f <= r)
{
visited[q[f]] = 1;
bfs(q[f++]);
}
}
void main()
{
int v;
cout << "Enter the number of vertices: " << endl;
cin >> n;
for (i = 1; i <= n; i++)
{
q[i] = 0;
visited[i] = 0;
}
cout << "Enter graph data in matrix form:" << endl;
for (i = 1; i <= n; i++)
{
for (j = 1; j <= n; j++)
{
cin >> a[i][j];
}
}
cout << "Enter the starting vertex: " << endl;
cin >> v;
bfs(v);
cout << "The node which are reachable are:" << endl;
for (i = 1; i <= n; i++)
{
if (visited[i])
cout << i;
else
{
cout << "BFS is not possible. All nodes are not reachable!" << endl;
break;
}
}
getch();
} | true |
33331c6716c7f13f48a744ce6391f63136f5ed82 | C++ | jpinto3/programming-work | /c++ projects/Project4/Weapon.h | UTF-8 | 304 | 2.8125 | 3 | [] | no_license | #ifndef WEAPON_H
#define WEAPON_H
#include <iostream>
using namespace std;
class Weapon {
private:
int stamina_required;
int hit;
string weapon_name;
public:
Weapon(string a, int b, int c);
string get_weapon_name();
int get_stamina_required();
int get_hit();
};
#endif
| true |
d4fbba11863b1fe0a56de931608203e5780be277 | C++ | kmulrey/LORA_master_integrate | /lora_daq-master/include/Socket_Calls.h | UTF-8 | 3,755 | 2.84375 | 3 | [] | no_license | /**
@author hershalpandya@gmail.com
*/
#pragma once
// These are all OS libraries. No equivalent in C++.
#include <sys/socket.h> // ip protocols for eg int values for AF_INET defined here.
#include <netdb.h> //has getaddrinfo(),struct addrinfo,etc.
#include <sys/fcntl.h> // fcntl(), O_NONBLOCK,etc
#include <sys/select.h> //select(), FD_SET(), etc.
/* delete the following library invocations if not used.
#include <sys/types.h> //definition of certain types size_t, useconds_t, etc.
*/
// For the sake of consistency, use C++ libraries only.
#include <string>
/*
* @class SOCKET_CALLS
* @brief manages sockets for TCP/IP Streaming
* This class is called by all the PCs (LORA MAIN / LASA PCs)
* Each PC will instantiate the class as per need:
** For LORA MAIN
*** 1 instance for communicating with LOFAR SERVER
*** 10 instances for communicating with 10 LASA CLIENTS
*** (There is a need to write a separate method for LORA to loop over all LASA PCs. Need to think where it goes in the organization.)
** For LASA PC
*** 1 instance to communicate with LORA server
*** 2/1 (old LASA/new LASA) instances to communicate with digitizer(s)
* General sequence for each instance will follow:
** Step 1: Load SOCKET INFO (machine name, port)
the IPV will be hardcoded as IPV4. and socktype to streaming socktype.
** Step 2:
*/
class SOCKET_CALLS
{
public:
// sc_active_socfd will store the socket each module should operate on
// only real use is, on the server side, when accept happens, the sockfd
// is switched from initial sockfd to listening sockfd
int sc_active_sockfd=0; // public to check status of fds.
//to Accept() another connection from the same socket.
int sc_active_spare_sockfd=0;
//add a default constructor
SOCKET_CALLS() {}
//result: populates sc_addr, sc_machine_name, sc_port_string
SOCKET_CALLS(const std::string&, const std::string&, bool);
//Methods For Clients and Servers
void Open();
int Receive(unsigned char*, size_t, int&, bool); //give references to data buffer (to store o/p from this method) & size of msg received (to store o/p from this method) & an int to hold errno given by read() method.
void Send(const unsigned char*, size_t, int&, bool); //give references to data (as i/p to this method) and size of sent msg(to store o/p from method).
void Close();
//Methods For Servers
void Bind();
void Listen();
void Accept();
bool Get_Accept_Status();
void Accept_Spare();
bool Get_Accept_Spare_Status();
private:
//sock file descriptors
int sc_init_sockfd=0;
int sc_listening_sockfd=0;
//hard coded to 200. Not sure why it was 200 in previous version of LORA_DAQ.
int sc_max_buffer_size = 200;
// machine name is self for server and server's for the client.
// port number needs to be passed as string.
std::string sc_machine_name, sc_port_string;
//non block flag is set for a socket file descriptor
//to make sure that read() should not block the current process i.e. rest of the code
//but it also makes sure that read() returns EWOULDBLOCK when fd is not ready for a read() operation
//which can be used to determine end of an incoming buffer. i.e. keep reading until errno is set to EWOULDBLOCK by read().
//if you dont do this, you wait another loop cycle to read remaining buffer(maintained by NIC i.e. Network Interface).
//nonblock is not required if you use select() to check for active sockfds but good to do it.
bool sc_nonblock=false;
// some fixed protocols. defining variables for maintainability in the future.
// can free up these constants if need be.
const int sc_ip_family = AF_INET; // fixed to ipv4
const int sc_sock_type = SOCK_STREAM; // fixed to streaming.
// will hold the found good addr
struct addrinfo sc_addr;
};
| true |
dbd728d34146cc0cf237b6123d206709964c3c40 | C++ | samgqroberts/pyxl | /src/WaveAnimation.cpp | UTF-8 | 2,415 | 3.078125 | 3 | [] | no_license | #include "WaveAnimation.h"
using namespace std;
WaveAnimation::WaveAnimation(
long numLines,
long numCols,
long duration,
long maxFrames,
long waveWidth,
long stayUp
) : Animation(numLines, numCols, duration, maxFrames){
this->waveWidth = waveWidth;
this->stayUp = stayUp;
}
WaveAnimation* WaveAnimation::create(
long numLines,
long numCols,
long duration,
long waveWidth,
long stayUp
) {
return new WaveAnimation(
numLines,
numCols,
duration,
numCols + waveWidth,
waveWidth,
stayUp
);
}
vector<vector<PixelState> >* WaveAnimation::fullWaveFrame(long frame) {
// wave (visible characters are the water) from left to right
vector<vector<PixelState> > * canvas =
new vector<vector<PixelState> > (numLines, vector<PixelState>(numCols, IMPARTIAL));
vector<long> waveColHeights;
waveColHeights.assign(numCols, 0);
long waveBack = frame - waveWidth;
for ( int c = 0 ; c < waveColHeights.size() ; c++ ) {
if (stayUp && c < waveBack + waveWidth / 2) {
waveColHeights[c] = numLines;
}
// must be in wave
else if (frame < c || c < waveBack) {
waveColHeights[c] = 0;
} else {
int distanceFromBack = c - waveBack;
int colHeight = sin( (float) distanceFromBack * PI / (float) waveWidth ) * numLines;
waveColHeights[c] = colHeight;
}
}
for ( int c = 0 ; c < waveColHeights.size() ; c++ ) {
for ( int l = 0 ; l < numLines ; l++ ) {
if ( waveColHeights[c] >= numLines - l ) {
canvas->at(l)[c] = ON;
} else {
canvas->at(l)[c] = OFF;
}
}
}
return canvas;
}
void WaveAnimation::applyFrame(vector<vector<PixelState> >* canvas, long frame) {
vector<vector<PixelState> >* currentFrame = fullWaveFrame(frame);
if (frame == 0) {
for (int l = 0; l < numLines; l++) {
for (int c = 0; c < numCols; c++) {
PixelState currentPixelState = currentFrame->at(l)[c];
if (currentPixelState == ON) {
canvas->at(l)[c] = currentPixelState;
}
}
}
} else {
vector<vector<PixelState> >* previousFrame = fullWaveFrame(frame - 1);
for (int l = 0; l < numLines; l++) {
for (int c = 0; c < numCols; c++) {
PixelState currentPixelState = currentFrame->at(l)[c];
if (currentPixelState != previousFrame->at(l)[c]) {
canvas->at(l)[c] = currentPixelState;
}
}
}
}
}
| true |
496d41c46f9815e7ed08aff8ef0c5de9588e2ce4 | C++ | OloieriAlexandru/Competitive-Programming-Training | /codeforces/1203F2.cpp | UTF-8 | 1,334 | 2.515625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
vector<pair<int,int>>positives_e;
vector<pair<int,int>>negatives_e;
int n, r, x, y, ans;
int main()
{
cin>>n>>r;
for (int i=1; i<=n; ++i)
{
cin>>x>>y;
if (y >= 0) positives_e.push_back(make_pair(x,y));
else negatives_e.push_back(make_pair(max(x,abs(y)),y));
}
sort(positives_e.begin(), positives_e.end(), [](pair<int,int> a, pair<int,int> b)
{
return a.first < b.first;
});
sort(negatives_e.begin(), negatives_e.end(), [](pair<int,int> a, pair<int,int> b)
{
return a.first + a.second > b.first + b.second;
});
for (int i=0; i<positives_e.size(); ++i)
{
if (r < positives_e[i].first) continue;
r += positives_e[i].second;
++ans;
}
int neg = negatives_e.size();
vector<vector<int>>dp(neg + 2, vector<int>(r + 2, 0));
dp[0][r] = ans;
for (int i=0;i<neg;++i)
{
for (int j = 0; j<=r;++j)
{
if (j >= negatives_e[i].first && j + negatives_e[i].second >= 0)
dp[i+1][j + negatives_e[i].second] = max(dp[i+1][j+negatives_e[i].second], dp[i][j] + 1);
dp[i+1][j] = max(dp[i+1][j], dp[i][j]);
}
}
for (int i=0;i<=r;++i)
ans = max(ans, dp[neg][i]);
cout<<ans<<'\n';
return 0;
}
| true |
225ecfffac6f5f9c6a17df9310acdaf650963a6b | C++ | justHusam/Competitive-Programming | /UVa/686 - Goldbach's Conjecture (II).cpp | UTF-8 | 582 | 2.578125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
const int N = 1 << 15;
bool isPrime[N];
int main(int argc, char **argv) {
memset(isPrime, true, sizeof isPrime);
isPrime[0] = isPrime[1] = false;
for (int i = 2; i * i < N; ++i)
if (isPrime[i])
for (int j = i * i; j < N; j += i)
isPrime[j] = false;
int n;
while (scanf("%d", &n) > 0 && n != 0) {
int a, b, res = 0;
if (n == 4)
puts("1");
else {
for (int i = n - 3, j = 3; i >= j; i -= 2, j += 2) {
if (i + j == n && isPrime[i] && isPrime[j])
++res;
printf("%d\n", res);
}
}
}
return 0;
}
| true |
ebebff1feaae229c7e62b2cafb4195757538c429 | C++ | MaximV88/RoboCup | /Robocup/BehaviorTree/SequenceNode.cpp | UTF-8 | 1,154 | 2.9375 | 3 | [
"MIT"
] | permissive | /************************************************************
* Student Name: TreeBots *
* Exercise Name: Ex6 *
* File description: Implementation of Nameable Class *
***********************************************************/
#include "SequenceNode.h"
using namespace behavior;
SequenceNode::SequenceNode() {
}
SequenceNode::~SequenceNode() {
}
void SequenceNode::initialize() {
//The iterator starts on the first member of the vector
m_cIterator = getChildren().begin();
}
StatusType SequenceNode::process() {
while (true) {
//Get the status of the current child
StatusType eStatus = (*m_cIterator)->tick();
//If the child is not successfull, return the status
if (eStatus != StatusTypeSuccess)
return eStatus;
//Otherwise check if reached end of vector
++m_cIterator;
//If at the end, we are successfull
if (m_cIterator == getChildren().end())
return StatusTypeSuccess;
}
} | true |
c52d1bb83bdca5acc5106c38af10c57945891870 | C++ | mdirshad17/MATHS | /Zalgo.cpp | UTF-8 | 779 | 2.984375 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
vector<int> Zalgo(string s)
{
int n = s.size();
int l = 0, r = 0;
std::vector<int> Z(n);
Z[0] = 0;
for (int i = 1; i < n; i++)
{
if (i > r)
{
l = r = i;
while (r < n && s[r - l] == s[r])
{
r++;
}
Z[i] = r - l;
r--;
} else
{
int k = i - l;
if (Z[k] < r - i + 1)
{
Z[i] = Z[k];
} else
{
l = i;
while (r < n && s[r - l] == s[r])
{
r++;
}
Z[i] = r - l;
r--;
}
}
}
return Z;
}
int main()
{
string s;
cin >> s;
vector<int> Z;
Z = Zalgo(s);
int maxz = 0;
int n = s.size();
for (int i = 0; i < Z.size(); ++i)
{
if (i + Z[i] == n)
{
maxz = max(maxz, Z[i]);
}
}
cout << maxz;
} | true |
3bd0e86344787edc10810a33f0aa8366733d533b | C++ | chienlisu/Leetcode2019 | /415. Add Strings.cpp | UTF-8 | 792 | 2.875 | 3 | [] | no_license | class Solution {
public:
string addStrings(string num1, string num2) {
int len1 = num1.length();
int len2 = num2.length();
if (len1 < len2)
{
string temp(len2-len1,'0');
num1 = temp + num1;
}
else if (len2 < len1)
{
string temp(len1-len2,'0');
num2 = temp + num2;
}
string ans = "";
bool add=false;
for (int i=num1.length()-1; i>=0; --i)
{
int curr = (num1[i]-'0') + (num2[i]-'0') + (add? 1:0);
add = curr >= 10? true:false;
char c = add? ('0' + curr - 10): ('0'+curr);
ans = c + ans;
}
if (add)
ans = '1'+ans;
return ans;
}
};
| true |
f778d26d34455800e2f439dd6b25f17ec6e078ec | C++ | jinbeomdev/daily-algorithm-problems | /[BOJ]1309/Source.cpp | UHC | 1,225 | 3.078125 | 3 | [] | no_license | //https://www.acmicpc.net/problem/1309
/*
η ĭ η Nĭ Ʒ 츮 ִ.
ڵ ִµ ڵ 츮 , ηε ηε پ ְ ġ . û ڵ ġ Ӹ ΰ ִ.
û Ӹ ʵ 츮 2*N 迭 ڸ ġϴ ˾Ƴ α ۼ ֵ . ڸ ġ ʴ 쵵 ϳ ģٰ Ѵ.
Է
ù° ٿ 츮 ũ N(1N100,000) ־.
ù° ٿ ڸ ġϴ 9901 Ͽ.
Է
4
41
*/
#include <iostream>
#include <cstring> //memset
using namespace std;
const int mod = 9901;
int dp[100001];
int main() {
int N;
memset(dp, 0, sizeof(dp));
cin >> N;
dp[0] = 1;
dp[1] = 3;
for (int i = 2; i <= N; i++) {
dp[i] = (2 * dp[i-1]) % mod + (dp[i - 2]) % mod;
}
cout << dp[N] % mod;
} | true |
ffb2b416bc37d71b9168879c7d02c90179d08743 | C++ | doycode/magic-cube-3d | /MagicCube3D/utilities.h | GB18030 | 1,492 | 2.96875 | 3 | [
"Apache-2.0"
] | permissive | #pragma once
//#ifndef __UTILITIES_H__
//#define __UTILETIES_H__
#include"stdafx.h"
//rotate direction
enum Axis{X, Y, Z};
//description of chunk position
enum ChunkIndex{NEGATIVE, MIDDLE, POSTIVE};
enum RotateDirection{CLOCKWISE, COUNTERCLOCKWISE, NOROTATE};
//description of the 6 aspects and the situation that no aspect
enum Aspect{FRONT, BACK, LEFT, RIGHT, UP, DOWN, NOASPECT};
//black, color of sheltered aspects which can be seen when rotation
enum Color{BLUE, GREEN, RED, ORANGE, WHITE, YELLOW, BLACK};
class GLPoint2f
{
public:
float x, y;
GLPoint2f(): x(0), y(0){}
GLPoint2f(float x, float y)
{
this->x = x;
this->y = y;
}
};
class GLPoint3f
{
public:
float x, y, z;
GLPoint3f(): x(0), y(0), z(0){}
GLPoint3f(float x, float y, float z)
{
this->x = x;
this->y = y;
this->z = z;
}
};
//selected situation
class TheSelected
{
public:
GLPoint2f selectedPoint;
Aspect aspect;
int aspectIndex;
TheSelected():aspectIndex(0), aspect(NOASPECT){}
};
//rotate infomation
class RotateInfo
{
public:
float angle;
char type;
bool reversed;//Ϊʾʱ
RotateInfo():type('F'),angle(0),reversed(false){}
RotateInfo& operator = (RotateInfo& info)
{
angle = info.angle;
type = info.type;
reversed = info.reversed;
return *this;
}
};
class Facelet
{
public:
Aspect asp;
int index;
Color color;
Facelet(): asp(NOASPECT), index(-1), color(BLACK){}
};
class Edge
{
public:
Facelet faceletMain;
Facelet faceletSide;
};
//#endif | true |
ad8912ba569cd6081d45c0220dd935c59b3ebaa8 | C++ | ZoranPandovski/al-go-rithms | /data_structures/Disjoint_Set_Union/Cpp/DSU_Path_Compress.cpp | UTF-8 | 729 | 3.234375 | 3 | [
"CC0-1.0"
] | permissive | #include<bits/stdc++.h>
using namespace std;
const int maxn = 1e5+5;
int p[maxn], size[maxn];
void initialize(int n){
for(int i = 1; i<=n; i++){
p[i] = i;
size[i] = 1;
}
return ;
}
int find(int u){
return p[u] = (p[u] == u ? u : find(p[u])); //path compression
}
//weighted union for maintaing balance
void join(int u, int v){
int uu = find(u), vv = find(v);
//they are already connected
if(uu == vv)
return ;
if(size[uu] < size[vv]){
p[uu] = vv;
size[vv] += size[uu];
} else{
p[vv] = uu;
size[uu] += size[vv];
}
return ;
}
int main(){
int n = 5;
initialize(n);
join(1, 2);
join(2, 3);
join(4, 5);
//finding in which connected component 2 lies
cout << find(2) << endl;
return 0;
} | true |
d769eccbc3648c609c8b5a0d46dce27a6f7472d7 | C++ | WenqinHuangfu/Parallelized_GEMM | /dgemm-pthread.cpp | UTF-8 | 3,032 | 3.015625 | 3 | [] | no_license | //
// dgemm-pthread.cpp
//
//
// Created by Nan Wu on 5/4/19.
//
#include <stdlib.h>
#include <sys/types.h>
#include <stdio.h>
#include <pthread.h>
#include <mkl.h>
#define thread_count 4
const char *dgemm_desc = "pthread, three-loop dgemm.";
const double BETA = 1.0;
const char *ntran = "N";
#if !defined(BLOCK_SIZE)
#define BLOCK_SIZE 40
#endif
#define min(a,b) (((a)<(b))?(a):(b))
struct Data{
int id;
int lda;
double *A;
double *B;
double *C;
};
void *runner(void *par) {
//printf("Enter working thread..\n");
Data *data = (Data *) par;
double *A = data->A;
double *B = data->B;
double *C = data->C;
int lda = data->lda;
int id = data->id;
int avecol = lda/thread_count;
int extra = lda%thread_count;
int cols = (id<extra) ? avecol+1 : avecol;
int col_start = (id<extra) ? (id*(avecol+1)) : (id-extra)*avecol+extra*(avecol+1);
int col_end = col_start + cols;
//printf("thread=%d created, computing from column %d to column %d\n",id,col_start,col_end);
for( int j = col_start; j < col_end; j += BLOCK_SIZE )
{
/*This gets the correct block size (for fringe blocks also)*/
int N = min( BLOCK_SIZE, col_end-j );
//double *b=(double*) malloc( lda * N * sizeof(double) );
double *c=(double*) malloc( lda * N * sizeof(double) );
//for( int kb = 0; kb < lda; kb++ )
// for( int nb = 0; nb < N; nb++ )
// {
// b[kb+nb*lda] = B[kb+j*lda+nb*lda];
// }
for( int mc = 0; mc < lda; mc++ )
for( int nc = 0; nc < N; nc++ )
{
c[mc+nc*lda] = C[mc+j*lda+nc*lda];
}
dgemm(ntran, ntran, &lda, &N, &lda, &BETA, A, &lda, B+j*lda, &lda, &BETA, c, &lda);
for( int mc = 0; mc < lda; mc++ )
for( int nc = 0; nc < N; nc++ )
{
C[mc+j*lda+nc*lda]=c[mc+nc*lda];
}
free(c);
//free(b);
}
//printf("end computation from id=%d\n",data->id);
free(data);
pthread_exit(0);
}
void square_dgemm( int lda, double *A, double *B, double *C)
{
//printf("Enter matrix multiplication using pthread..\n");
int thread;
//pthread_t *thread_handlers = (pthread_t *)malloc(thread_count*sizeof(pthread_t));
pthread_t thread_handlers[thread_count];
for (thread = 0; thread < thread_count; thread++){
Data *data = (Data *)malloc(sizeof(Data));
data->A = A;
data->B = B;
data->C = C;
data->lda = lda;
data->id = thread;
pthread_create(&(thread_handlers[thread]),NULL,runner,(void*)data);
//printf("thread=%d allocated successful\n",thread);
//pthread_join(thread_handlers[thread],NULL);
}
for (thread = 0; thread < thread_count; thread++){
//printf("start destroying thread = %d\n", thread);
pthread_join(thread_handlers[thread],NULL);
//printf("end destroying thread = %d\n", thread);
}
}
| true |
0fd8a3d309fdabeddc8862dbb714ee3ca9e4158f | C++ | tburtenshaw/worldview2 | /Project1/mytimezone.cpp | UTF-8 | 4,911 | 3.21875 | 3 | [] | no_license | #include "mytimezone.h"
#include <ctime>
#include <string>
#include <chrono>
unsigned long MyTimeZone::AsLocalTime(unsigned long unixtime)
{
return unixtime+tz_offset_second(unixtime);
}
//thanks https://stackoverflow.com/questions/32424125/c-code-to-get-local-time-offset-in-minutes-relative-to-utc
long MyTimeZone::tz_offset_second(time_t t) {
struct std::tm local;
struct std::tm utc;
localtime_s(&local, &t);
gmtime_s(&utc, &t);
long diff = ((local.tm_hour - utc.tm_hour) * 60 + (local.tm_min - utc.tm_min))
* 60L + (local.tm_sec - utc.tm_sec);
int delta_day = local.tm_mday - utc.tm_mday;
// If |delta_day| > 1, then end-of-month wrap
if ((delta_day == 1) || (delta_day < -1)) {
diff += 24L * 60 * 60;
}
else if ((delta_day == -1) || (delta_day > 1)) {
diff -= 24L * 60 * 60;
}
return diff;
}
unsigned long MyTimeZone::AdjustBasedOnLongitude(unsigned long unixtime, float longitude)
{
int naivetz;
naivetz = (int)((longitude + 7.5f) / 15.0f);
return unixtime+naivetz*3600;
}
std::string MyTimeZone::FormatUnixTime(unsigned long unixtime, int flags)
{
std::string output;
struct std::tm corrected;
time_t t;
t = unixtime;
gmtime_s(&corrected, &t);
std::string year, mon, mday, wday, delim;
year = std::to_string(corrected.tm_year + 1900);
delim = "-";
if (flags & FormatFlags::MONTH_SHORT) {
mon = monthnames[corrected.tm_mon];
delim = " ";
}
else {
mon = std::to_string(corrected.tm_mon + 1);
}
mday = std::to_string(corrected.tm_mday);
if (flags & FormatFlags::SHOW_DAY) {
wday = daynames[corrected.tm_wday] + " ";
}
else {
wday = "";
}
if (flags & FormatFlags::DMY) { //nz format
output = wday + mday + delim + mon + delim + year;
}
else if (flags & FormatFlags::MDY) { //us format
output = wday + mon + delim + mday + delim + year;
}
else { //y-m-d
output = wday + year + delim + mon + delim + mday;
}
if (flags & FormatFlags::SHOW_TIME) {
output = output + ((corrected.tm_hour > 9) ? " " : " 0") + std::to_string(corrected.tm_hour) + ((corrected.tm_min > 9) ? ":" : ":0") + std::to_string(corrected.tm_min);
}
return output;
}
unsigned long MyTimeZone::GetYearFromTimestamp(unsigned long unixtime)
{
unixtime += 31536000; //increase the date, so we start on a non-leap, after a leap year
const unsigned long fouryears = 31536000 * 3 + 31622400; //365,365,365,366 days
unsigned long olympiad = unixtime / fouryears; //which group of four years
unsigned long remainder = (unixtime - (olympiad * fouryears)) / 31536000;
if (remainder > 3) remainder = 3;
unsigned long yearcalc = olympiad * 4 + remainder + 1969; //from 1969 as we went forward a year previously
return yearcalc;
}
int MyTimeZone::GetDayOfWeek(unsigned long unixtime)
{
return ((unixtime / secondsperday) + 4) % 7;
}
int MyTimeZone::GetDaySince2010(unsigned long unixtime)
{
unsigned long u = (unixtime - 1262304000) / secondsperday;
return u;
}
time_t MyTimeZone::DateWithThisTime(time_t date, int h, int m, int s)
{
struct std::tm correctedTime;
localtime_s(&correctedTime, &date);
correctedTime.tm_hour = 0;
correctedTime.tm_min = 0;
correctedTime.tm_sec = 0;
return mktime(&correctedTime);
}
time_t MyTimeZone::AdvanceByDays(time_t date, int daysToAdvance)
{
auto tp = std::chrono::system_clock::from_time_t(date);
auto days = std::chrono::days(daysToAdvance);
tp += days;
// Convert back to unsigned long
return std::chrono::system_clock::to_time_t(tp);
}
std::string MyTimeZone::DisplayBestTimeUnits(unsigned long seconds)
{
if (seconds > 60 * 60 * 24*365) { //over one year
return std::to_string(seconds / (60 * 60 * 24*7)) + " weeks";
}
else if (seconds > 60 * 60 * 48) { //over two days
return std::to_string(seconds / (60 * 60 * 24)) + " days";
}
else if (seconds > 60 * 60) { //over one hour
return std::to_string(seconds / (60 * 60)) + " hours";
}
else if (seconds > 2*60) { //over two minutes
return std::to_string(seconds/60) + " minutes";
}
return std::to_string(seconds) + " seconds";
}
int MyTimeZone::DateFormatOptions::GetDateCustomFormat()
{
return combinedFlags;
}
int MyTimeZone::DateFormatOptions::GetDateOrder()
{
return combinedFlags;
}
void MyTimeZone::DateFormatOptions::SetDateOrder(int dOrder)
{
combinedFlags = (combinedFlags &~FormatFlags::DMY & ~FormatFlags::MDY & ~FormatFlags::YMD) |dOrder;
}
void MyTimeZone::DateFormatOptions::SetMonthFormat(int mf)
{
combinedFlags = (combinedFlags & ~FormatFlags::MONTH_SHORT & ~FormatFlags::MONTH_LONG & ~FormatFlags::MONTH_NUM) | mf;
}
| true |
cdf15feee994d297c3308b24e1a14e5ff2107646 | C++ | MasterZul/Example-C---Source-Code-Lesson | /C++/10 Class/Employee/EmployeeData.h | UTF-8 | 1,056 | 3.4375 | 3 | [] | no_license | #ifndef EMPLOYEEDATA_H
#define EMPLOYEEDATA_H
#include<string>
using namespace std;
class Employee{
private:
string name;
int idNumber;
string department;
string position;
public:
Employee(string,int,string,string);
Employee();
void setName(string n){ name = n;}
void setIdNumber(int i){ idNumber = i;}
void setDeparment(string d){ department = d;}
void setPosition(string p){ position = p;}
string getName() const { return name; }
int getIdNumber() const{ return idNumber; }
string getDeparment() const{ return department; }
string getPosition() const{ return position; }
void print(Employee&) const;
};
Employee::Employee(string n, int id,string depart, string posis ){
name = n;
idNumber = id;
department = depart;
position = posis;
}
Employee::Employee(){
name = "";
idNumber = 0;
deparment ="";
position = "";
}
void Employee::print(Employee &a) const{
cout<<"Name: "<<a.name<<endl;
cout<<"ID Number: "<<a.idNumber<<endl;
cout<<"Deparment: "<<a.department<<endl;
cout<<"Position: "<<a.position<<endl;
cout<<endl;
}
#endif
| true |
4acd71fbb7762dbd4ddbc31d04abb378e043d666 | C++ | mdub555/OS-Project-2 | /src/info/memory_info.cpp | UTF-8 | 1,374 | 3.09375 | 3 | [] | no_license | #include "memory_info.h"
#include <fstream>
#include <iostream>
#include <sstream>
#include <ncurses.h>
using namespace std;
MemoryInfo get_memory_info() {
// make initial struct
MemoryInfo info;
// open the file
ifstream meminfo_file(PROC_ROOT "/meminfo");
string line, name; // declare the line and name associated that line
if (meminfo_file) { // check if the file opened correctly
while (getline(meminfo_file, line)) {
istringstream linestream(line); // turn the line into an istringstream
linestream >> name; // populate the name of the line
name = name.substr(0, name.size()-1); // remove the trailing `:`
// depending on the name of the line, add the data to the correct variable
if (name == "MemTotal") {
linestream >> info.total_memory;
} else if (name == "MemFree") {
linestream >> info.free_memory;
} else if (name == "Buffers") {
linestream >> info.buffers_memory;
} else if (name == "Cached") {
linestream >> info.cached_memory;
} else if (name == "SwapTotal") {
linestream >> info.total_swap;
} else if (name == "SwapFree") {
linestream >> info.free_swap;
}
}
meminfo_file.close();
} else {
cerr << "Unable to open /proc/meminfo" << endl;
return MemoryInfo();
}
return info;
}
| true |
cceefd5c3b4221473339ae869cdb5db3ee2a6db1 | C++ | johndevwayne/ltm-plus-plus | /BigNum.cpp | UTF-8 | 738 | 2.71875 | 3 | [
"MIT"
] | permissive | /*
* BigNum.cpp
*
* Created on: Dec 21, 2012
*
* LICENSING: See LICENSE.txt or http://opensource.org/licenses/MIT
*/
#include "BigNum.h"
BigNum::BigNum(const std::vector<unsigned char> &bin) :
N(new mp_int) {
mp_init_size(*this, 1);
mp_read_signed_bin(*this, &bin[0], bin.size());
}
std::string BigNum::ToString(int radix) const {
int charsNeeded;
mp_radix_size(*this, radix, &charsNeeded);
std::auto_ptr<char> str(new char[charsNeeded]);
mp_toradix(*this, str.get(), radix);
std::string result(str.get());
return result;
}
const BigNum BigNum::NEGATIVE_ONE(-1L);
const BigNum BigNum::ZERO(0L);
const BigNum BigNum::ONE(1L);
const BigNum BigNum::TWO(2L);
const BigNum BigNum::TEN(10L);
| true |
be39a4da8cb53d8675deac0601990590488c4296 | C++ | JakubSokolowski/tsp-distributed-worker | /src/solvers/bnb/BranchAndBound.h | UTF-8 | 1,439 | 2.546875 | 3 | [] | no_license | #ifndef TSP_BRANCHANDBOUND_H
#define TSP_BRANCHANDBOUND_H
#include <iostream>
#include <limits>
#include <deque>
#include <stack>
#include <utility>
#include "LittleMatrix.h"
#include "../Solver.h"
#include "../Solution.h"
using std::stack;
using std::deque;
using std::pair;
using std::cout;
using std::endl;
struct Node {
int parent_key = -1;
uint lower_bound;
Edge path;
bool included = false;
};
class BranchAndBound: public Solver {
public:
explicit BranchAndBound(LittleMatrix &m);
BranchAndBound();
void AssignMatrix(const LittleMatrix &m);
void AddIndices(LittleMatrix &m);
Solution Solve(const GraphRepresentation& representation);
uint FindBranchingPositionAndRegret(const LittleMatrix &m, Edge &path, Position &pos);
void RemoveSubtour(LittleMatrix &m, int index, Edge &path);
uint VisitedNodesCount() { return (uint)tree_m.size(); }
Tour RetrieveNewTourFromTree(int index, uint begin);
void UpdateCurrentBestSolution(LittleMatrix &m);
void FindTour();
Tour GetLastTour() { return current_best_tour_m; }
uint GetLastCost() { return current_smallest_cost_m; }
bool IsOptimal() { return optimal; }
private:
uint infinity;
LittleMatrix initial_matrix_m;
uint current_smallest_cost_m = std::numeric_limits<uint>::max();
deque<Node> tree_m;
Tour current_best_tour_m;
bool optimal = 0;
};
#endif //TSP_BRANCHANDBOUND_H
| true |
8acb451aafa5314bc141044fcb3792dae1c4f129 | C++ | inglada/OTB | /Examples/DataRepresentation/Containers/TreeContainer.cxx | UTF-8 | 9,595 | 2.859375 | 3 | [] | no_license | /*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
Some parts of this code are derived from ITK. See ITKCopyright.txt
for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
// Software Guide : BeginLatex
//
// \index{itk::TreeContainer}
//
// This example shows how to use the \doxygen{itk}{TreeContainer} and the
// associated TreeIterators.
// The \doxygen{itk}{TreeContainer} implements the notion of tree and is
// templated over the type of node so it can virtually handle any
// objects. Each node is supposed to have only one parent so no cycle
// is present in the tree. No checking is done to ensure a cycle-free
// tree.
//
// Let's begin by including the appropriate header file.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
#include <itkTreeContainer.h>
#include "itkTreeContainer.h"
#include "itkChildTreeIterator.h"
#include "itkLeafTreeIterator.h"
#include "itkLevelOrderTreeIterator.h"
#include "itkInOrderTreeIterator.h"
#include "itkPostOrderTreeIterator.h"
#include "itkPreOrderTreeIterator.h"
#include "itkRootTreeIterator.h"
#include "itkTreeIteratorClone.h"
// Software Guide : EndCodeSnippet
int main(int, char*[])
{
// Software Guide : BeginLatex
// First, we create a tree of integers.
// The TreeContainer is templated over the type of nodes.
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef int NodeType;
typedef itk::TreeContainer<NodeType> TreeType;
TreeType::Pointer tree = TreeType::New();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
// Next we set the value of the root node using \code{SetRoot()}.
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
tree->SetRoot(0);
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
// Then we use the \code{Add()} function to add nodes to the tree
// The first argument is the value of the new node and the second
// argument is the value of the parent node. If two nodes have
// the same values then the first one is picked. In this particular
// case it is better to use an iterator to fill the tree.
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
tree->Add(1, 0);
tree->Add(2, 0);
tree->Add(3, 0);
tree->Add(4, 2);
tree->Add(5, 2);
tree->Add(6, 5);
tree->Add(7, 1);
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
// We define an \doxygen{itk}{LevelOrderTreeIterator} to parse the tree in level order.
// This particular iterator takes three arguments. The first one is the actual tree
// to be parsed, the second one is the maximum depth level and the third one is the
// starting node. The \code{GetNode()} function return a node given its value. Once
// again the first node that corresponds to the value is returned.
// Software Guide : EndLatex
std::cout << "LevelOrderTreeIterator:" << std::endl;
// Software Guide : BeginCodeSnippet
itk::LevelOrderTreeIterator<TreeType> levelIt(tree, 10, tree->GetNode(2));
levelIt.GoToBegin();
while (!levelIt.IsAtEnd())
{
std::cout << levelIt.Get() << " (" << levelIt.GetLevel() << ")" <<
std::endl;
++levelIt;
}
std::cout << std::endl;
// Software Guide : EndCodeSnippet
levelIt.GoToBegin();
// Software Guide : BeginLatex
// The TreeIterators have useful functions to test the property of the current
// pointed node. Among these functions: \code{IsLeaf{}} returns true if the current
// node is a leaf, \code{IsRoot{}} returns true if the node is a root,
// \code{HasParent{}} returns true if the node has a parent and
// \code{CountChildren{}} returns the number of children for this particular node.
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
levelIt.IsLeaf();
levelIt.IsRoot();
levelIt.HasParent();
levelIt.CountChildren();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
// The \doxygen{itk}{ChildTreeIterator} provides another way to iterate through a tree
// by listing all the children of a node.
// Software Guide : EndLatex
std::cout << "ChildTreeIterator:" << std::endl;
// Software Guide : BeginCodeSnippet
itk::ChildTreeIterator<TreeType> childIt(tree);
childIt.GoToBegin();
while (!childIt.IsAtEnd())
{
std::cout << childIt.Get() << std::endl;
++childIt;
}
std::cout << std::endl;
// Software Guide : EndCodeSnippet
childIt.GoToBegin();
// Software Guide : BeginLatex
// The \code{GetType()} function returns the type of iterator used.
// The list of enumerated types is as follow:
// PREORDER, INORDER, POSTORDER, LEVELORDER, CHILD, ROOT and LEAF.
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
if (childIt.GetType() != itk::TreeIteratorBase<TreeType>::CHILD)
{
std::cout << "[FAILURE]" << std::endl;
return EXIT_FAILURE;
}
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
// Every TreeIterator has a \code{Clone()} function which returns
// a copy of the current iterator. Note that the user should delete
// the created iterator by hand.
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
childIt.GoToParent();
itk::TreeIteratorBase<TreeType>* childItClone = childIt.Clone();
delete childItClone;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
// The \doxygen{itk}{LeafTreeIterator} iterates through the leaves of the tree.
// Software Guide : EndLatex
std::cout << "LeafTreeIterator:" << std::endl;
// Software Guide : BeginCodeSnippet
itk::LeafTreeIterator<TreeType> leafIt(tree);
leafIt.GoToBegin();
while (!leafIt.IsAtEnd())
{
std::cout << leafIt.Get() << std::endl;
++leafIt;
}
std::cout << std::endl;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
// The \doxygen{itk}{InOrderTreeIterator} iterates through the tree
// in the order from left to right.
// Software Guide : EndLatex
std::cout << "InOrderTreeIterator:" << std::endl;
// Software Guide : BeginCodeSnippet
itk::InOrderTreeIterator<TreeType> InOrderIt(tree);
InOrderIt.GoToBegin();
while (!InOrderIt.IsAtEnd())
{
std::cout << InOrderIt.Get() << std::endl;
++InOrderIt;
}
std::cout << std::endl;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
// The \doxygen{itk}{PreOrderTreeIterator} iterates through the tree
// from left to right but do a depth first search.
// Software Guide : EndLatex
std::cout << "PreOrderTreeIterator:" << std::endl;
// Software Guide : BeginCodeSnippet
itk::PreOrderTreeIterator<TreeType> PreOrderIt(tree);
PreOrderIt.GoToBegin();
while (!PreOrderIt.IsAtEnd())
{
std::cout << PreOrderIt.Get() << std::endl;
++PreOrderIt;
}
std::cout << std::endl;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
// The \doxygen{itk}{PostOrderTreeIterator} iterates through the tree
// from left to right but goes from the leaves to the root in the search.
// Software Guide : EndLatex
std::cout << "PostOrderTreeIterator:" << std::endl;
// Software Guide : BeginCodeSnippet
itk::PostOrderTreeIterator<TreeType> PostOrderIt(tree);
PostOrderIt.GoToBegin();
while (!PostOrderIt.IsAtEnd())
{
std::cout << PostOrderIt.Get() << std::endl;
++PostOrderIt;
}
std::cout << std::endl;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
// The \doxygen{itk}{RootTreeIterator} goes from one node to the
// root. The second arguments is the starting node. Here we go from the leaf
// node (value = 6) up to the root.
// Software Guide : EndLatex
std::cout << "RootTreeIterator:" << std::endl;
// Software Guide : BeginCodeSnippet
itk::RootTreeIterator<TreeType> RootIt(tree, tree->GetNode(6));
RootIt.GoToBegin();
while (!RootIt.IsAtEnd())
{
std::cout << RootIt.Get() << std::endl;
++RootIt;
}
std::cout << std::endl;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
// All the nodes of the tree can be removed by using the
// \code{Clear()} function.
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
tree->Clear();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
// We show how to use a TreeIterator to form a tree by creating nodes.
// The \code{Add()} function is used to add a node and put a value on it.
// The \code{GoToChild()} is used to jump to a node.
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
itk::PreOrderTreeIterator<TreeType> PreOrderIt2(tree);
PreOrderIt2.Add(0);
PreOrderIt2.Add(1);
PreOrderIt2.Add(2);
PreOrderIt2.Add(3);
PreOrderIt2.GoToChild(2);
PreOrderIt2.Add(4);
PreOrderIt2.Add(5);
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
// The \doxygen{itk}{TreeIteratorClone} can be used to have a generic copy of
// an iterator.
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk::TreeIteratorBase<TreeType> IteratorType;
typedef itk::TreeIteratorClone<IteratorType> IteratorCloneType;
itk::PreOrderTreeIterator<TreeType> anIterator(tree);
IteratorCloneType aClone = anIterator;
// Software Guide : EndCodeSnippet
return EXIT_SUCCESS;
}
| true |
ea06c6fd33a97259daace2807af7fec43daa959d | C++ | ilovelibai/C-Cpp-Notes | /src/object-lifecycle.cpp | UTF-8 | 5,458 | 3.609375 | 4 | [] | no_license | // File: object-lifecycle.cpp
// Brief: Demonstrate Object Lifecycle
#include <iostream>
#include <string>
#define DEBUG_TRACE
#ifdef DEBUG_TRACE
#pragma message "Logging Enabled"
#define TRACE(msg) \
std::cerr << __FILE__ << ":" << __LINE__ << ": - fun = " << __FUNCTION__ << " ; " << msg << "\n"
#else
#pragma message ("Logging disabled")
#define TRACE(msg)
#endif
class DummyClass{
public:
// Constructor
DummyClass(const std::string& name): _object_name(name){
TRACE(std::string("name = ") + name + " - I was created.");
}
// Copy constructor
DummyClass(const DummyClass& rhs){
TRACE("Enter copy constructor");
TRACE("name = " + _object_name + " - I was copied. ");
this->_object_name = rhs._object_name + "-COPIED";
}
// Move constructor
DummyClass( DummyClass&& rhs){
TRACE("Enter move constructor");
TRACE("name = " + _object_name + " - I was moved");
this->_object_name = rhs._object_name + "-MOVED";
}
// Copy assignment operator
DummyClass& operator= (const DummyClass& rhs){
TRACE("Enter copy assignment operator");
TRACE("name = " + _object_name + " - I was copied. ");
this->_object_name = rhs._object_name + "-COPIED";
return *this;
}
//DummyClass& operator= (DummyClass&& rhs) = delete;
// Move assignment operator
DummyClass& operator= (DummyClass&& rhs){
TRACE("Enter move assignment operator");
TRACE("name = " + _object_name + " - I was moved. ");
this->_object_name = rhs._object_name + "-MOVED";
return *this;
}
// Destructor
~DummyClass(){
TRACE(std::string("name = ") + _object_name + " - I was destroyed");
}
void speakWithUser(){
std::cout << "I am a dummy object called = " << _object_name << "\n";
}
private:
std::string _object_name;
};
// Object allocated on the static memory
// is deleted when the programs finishes.
DummyClass dummyGlobal("dummy-global");
auto testObject() -> DummyClass {
std::cerr << "\n" << " ==> ENTER FUNCTION testObject()" << "\n\n";
TRACE("Enter function");
auto d = DummyClass("local-dummy-in-function");
d.speakWithUser();
std::cerr << "\n" << " ==> EXIT FUNCTION testObject()" << "\n\n";
TRACE("Exit function");
// Object d is deleted here when it goes out scope
// and then a copy of it is returned from here.
// Therefore, the copy constructor is invoked.
return d;
}
auto makeDummyHeap() -> DummyClass* {
std::cerr << "\n" << " ==> ENTER FUNCTION makeDummyHeap()" << "\n\n";
// Object allocated in dynamic memory, so it survives this scope
// and is not deleted when returned from function.
DummyClass* ptr = new DummyClass("dummy-heap");
ptr->speakWithUser();
std::cerr << "\n" << " ==> EXIT FUNCTION makeDummyHeap()" << "\n\n";
return ptr;
};
int main(){
std::cerr << "\n" << "ENTER FUNCTION MAIN" << "\n\n";
TRACE("Main function started.");
// Object allocated on the stack -> auto storage class, it is
// destroyed when it goes out of scope
DummyClass dummy1("dummy1-stack");
dummy1.speakWithUser();
DummyClass* dummyInHeap = makeDummyHeap();
dummyInHeap->speakWithUser();
{
std::cerr << "\n" << " ---- ENTER LOCAL SCOPE " << "\n\n";
TRACE("Create local scope");
DummyClass dummy2("dummy2-stack-local-scope");
dummy2.speakWithUser();
dummyGlobal.speakWithUser();
dummyInHeap->speakWithUser();
TRACE("End local scope");
// Object dummy2 deleted here
std::cerr << "\n" << "EXIT LOCAL SCOPE " << "\n\n";
}
try {
std::cerr << "\n" << " ---- ENTER LOCAL EXCEPTION SCOPE " << "\n\n";
DummyClass dummyException("dummy2-stack-local-scope");
dummyException.speakWithUser();
throw std::runtime_error(" ERROR Throw a failure for testing deterministic destructor");
std::cerr << "\n" << " ---- EXIT LOCAL EXCEPTION SCOPE " << "\n\n";
} catch (const std::runtime_error& ex){
std::cerr << "\n" << " ---- ENTER EXCEPTION HANDLER" << "\n\n";
std::cerr << "Failure = " << ex.what() << "\n";
std::cerr << "\n" << " ---- EXIT EXCEPTION HANDLER" << "\n\n";
}
TRACE("Copy object returned from function");
DummyClass dummy2 = testObject();
dummy2.speakWithUser();
dummyInHeap->speakWithUser();
// Objects allocated on the heap must be released manually or a
// memory leak will happen. However, it is easy to forget to
// delete a heap-allocated object, so the this approach is error
// prone and better solution is to use C++11 smart pointers.
delete dummyInHeap;
std::cerr << "\n" << "EXIT FUNCTION MAIN" << "\n\n";
TRACE("Main function finished.");
return 0;
// Object dummy1 and dummyGlobal deleted here
}
| true |
dd91d7d0b8e637b0b4240d88a8a722befa64a88d | C++ | MonsieurWilson/cpplearn | /apue/ch4/lstat.cpp | UTF-8 | 1,047 | 2.84375 | 3 | [] | no_license | /**
* Copyright(C), 2017, Nsfocus
* Name:
* Author: Wilson Lan
* Description:
*/
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <iostream>
int main(int argc, const char **argv) {
struct stat buf;
std::string mode;
for (int i = 1; i < argc; ++i) {
std::cout << argv[i] << ": ";
if (lstat(argv[i], &buf) < 0) {
std::cerr << "lstat error" << std::endl;
continue;
}
if (S_ISREG(buf.st_mode)) {
mode = "regular";
} else if (S_ISDIR(buf.st_mode)) {
mode = "directory";
} else if (S_ISCHR(buf.st_mode)) {
mode = "character special";
} else if (S_ISBLK(buf.st_mode)) {
mode = "block special";
} else if (S_ISFIFO(buf.st_mode)) {
mode = "fifo";
} else if (S_ISSOCK(buf.st_mode)) {
mode = "socket";
} else {
mode = "** unknown mode **";
}
std::cout << mode << std::endl;
}
return 0;
}
| true |
1203762e6e02adf5da44ecc4b47082b22ed2471c | C++ | Adicesa05/Arduino | /Variable_LED_Blinker/Variable_LED_Blinker.ino | UTF-8 | 799 | 3.046875 | 3 | [] | no_license | int ledPin = 13; //declares variable(s)
int delayVar = 2000;
void setup() {
pinMode(LED_BUILTIN, OUTPUT); //turns on the LED
Serial.begin(9600); //always start this
}
void loop()
{
digitalWrite(ledPin, HIGH);
delay(delayVar); // the delay is = to 2000, changes made will also affect the delay
digitalWrite(ledPin, LOW);
delay(delayVar);
if (delayVar > 200) { //does something when this happens and stops the command below when it doesn't match
delayVar -= 200; //the delay starts at 2000 and -200 each time the loop happens
}
Serial.println(delayVar); //almost always turn this on, it turns on the serial so you can see what happens
}
| true |
bdc19aa63668b6871b01ad63a8b58d90b9985911 | C++ | tianskylan/Zombie-Simulator | /exceptions.h | UTF-8 | 744 | 3.203125 | 3 | [] | no_license | #pragma once
#include <exception>
class InvalidOp : public std::exception
{
public:
const char* what() const throw() { return "Invalid OP code or parameters."; }
};
class AccessViolation : public std::exception
{
public:
const char* what() const throw() { return "Machine tried to access outside available memory."; }
};
class FileIOError : public std::exception
{
public:
const char* what() const throw() { return "Specified file cannot be opened"; }
};
class WrongLineNumberError : public std::exception
{
public:
const char* what() const throw() { return "Cannot jump to the specified line number"; }
};
class MemoryAccessError : public std::exception
{
public:
const char* what() const throw() { return "Memory Access Failed"; }
}; | true |
2a5c6d4d9791c83039d4d298bfc1ddee6fccf0d1 | C++ | eglrp/Alchemy | /test/test_pooling_layer.cpp | UTF-8 | 1,116 | 2.640625 | 3 | [] | no_license | #include <alchemy.h>
using namespace alchemy;
int main()
{
Global::mode(Global::GPU);
Blob<float> input({2, 3, 6, 5});
Blob<float> output;
Filler<float>::uniform_fill(input.count(), input.mutable_data_cptr(), 0, 10.0);
print_cpu(input.count(), input.data_cptr());
PoolingLayer<float> poolingLayer(
LayerParameter()
.pooling_param(
PoolingParameter()
.kernel_size(2)
.type(MAX)
.stride(2)
)
);
poolingLayer.setup({ &input }, { &output });
std::cout << "#GPU: \n";
Global::mode(Global::GPU);
poolingLayer.Forward({ &input }, { &output });
// print_gpu(output.count(), output.data_gptr());
print_cpu(output.count(), output.data_cptr());
std::cout << "\n#CPU: \n";
Global::mode(Global::CPU);
poolingLayer.Forward({ &input }, { &output });
// print_gpu(output.count(), output.data_gptr());
print_cpu(output.count(), output.data_cptr());
return 0;
}
| true |
fb49deb58fa949dfd7e078efb174454b247a92d5 | C++ | Anubhav12345678/competitive-programming | /TILINGWITHDOMINOESVVIMP.cpp | UTF-8 | 1,764 | 4.21875 | 4 | [] | no_license | /*Given a 3 x n board, find the number of ways to fill it with 2 x 1 dominoes.
Example 1
Following are all the 3 possible ways to fill up a 3 x 2 board.
Example 2
Here is one possible way of filling a 3 x 8 board. You have to find all the possible ways to do so.
Examples :
Input : 2
Output : 3
Input : 8
Output : 153
Input : 12
Output : 2131
Recommended: Please try your approach on {IDE} first, before moving on to the solution.
Defining Subproblems:
At any point while filling the board, there are three possible states that the last column can be in:
An = No. of ways to completely fill a 3 x n board. (We need to find this)
Bn = No. of ways to fill a 3 x n board with top corner in last column not filled.
Cn = No. of ways to fill a 3 x n board with bottom corner in last column not filled.
Note: The following states are impossible to reach:
Finding Reccurences
Note: Even though Bn and Cn are different states, they will be equal for same ‘n’. i.e Bn = Cn
Hence, we only need to calculate one of them.
Calculating An:
A_{n} = A_{n-2} + B_{n-1} + C_{n-1}
A_{n} = A_{n-2} + 2*(B_{n-1})
Calculating Bn:
B_{n} = A_{n-1} + B_{n-2}
Final Recursive Relations are:
A_{n} = A_{n-2} + 2*(B_{n-1})
B_{n} = A_{n-1} + B_{n-2}
Base Cases:
A_0 = 1 A_1 = 0 B_0 = 0 B_1 = 1
*/
// C++ program to find no. of ways
// to fill a 3xn board with 2x1 dominoes.
#include <iostream>
using namespace std;
int countWays(int n)
{
int A[n + 1], B[n + 1];
A[0] = 1, A[1] = 0, B[0] = 0, B[1] = 1;
for (int i = 2; i <= n; i++) {
A[i] = A[i - 2] + 2 * B[i - 1];
B[i] = A[i - 1] + B[i - 2];
}
return A[n];
}
int main()
{
int n = 8;
cout << countWays(n);
return 0;
} | true |
6e0c9441511691f6b39e4be519949e6ffec99592 | C++ | joelmacias/CS135Lab | /lab8/bookex.cpp | UTF-8 | 1,738 | 3.8125 | 4 | [] | no_license | #include<iostream>
#include<cmath>
using namespace std;
int main(){
cout << "Enter a number: ";
int userInput;
cin >> userInput;
userInput = abs(userInput);
int counter = 10;
int total = 0;
// keep looping until original input is zero
while(userInput != 0){
// when this condition is true we know that we
// have gone over the highest place value of userInput
// Example:
// userInput = 123 // highest place value is the hundreds
// 123/1000 = 0.123 // we have gone over the highest place value
// so we can start printing the numbers starting at the highest place value
if(userInput/counter == 0){
// we need a stoping point so we dont get stuck in an infinite loop
// when counter == 0 we stop because we dont want to divide by zero,
// and we have already printed out all the digits of userInput
while(counter > 0){
// divid the counter by 10 so that we down one place value every iteration
counter = counter/10;
// if we enter the body of this if statement when counter == 0 then we will divide
// by zero, and cry
if(counter != 0){
// print out the digit in our current place value
cout << userInput/counter << endl;
// add said digit to our running total
total += userInput/counter;
// subtract current userinput by our current digit times current place value
// example:
// userInput == 123
// userInput = 123 - ((123/100) * 100)
// userInput = 123 - 100
// userInput == 23
userInput = userInput - ((userInput/counter) * counter);
}
}
}
// keep going a place value until we go one over userinput's hightest place value
counter = counter * 10;
}
cout << "sum of digits: " << total << endl;
}
| true |
751f91475154022cc8bdb63bc474028abab62282 | C++ | gsalmeida/Estrutura-de-Dados-II | /lista04_Arquivos/04/04.cpp | UTF-8 | 5,057 | 3 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
//argc deve ser o mesmo do método main para que a função
//funcione passando como parâmetros os nomes de todos os arquivos de uma vez apenas.
void concatena1(int argc, char *argvArquivos[]) {
// printf("\nArgc na função concatena: %d\n", argc);
FILE *arquivoResutlado;
if ((arquivoResutlado = fopen(argvArquivos[argc-1], "w+")) == NULL) {
printf("\n\nErro ao abrir ou criar o arquivo de resultado.\nArquivo não encontrado ou disco com blocos defeituosos.\n"); return;
}
//Este for isola o primeiro nome, que este refere-se ao nome do programa em execução, e o ultmo, que trata-se do nome do arquivo resultado (arquivoResutlado).
for(int a = 1; a < (argc -1); a++) {
FILE *arquivoAtual;
if ((arquivoAtual = fopen(argvArquivos[a], "r")) == NULL) {
printf("\n\nErro ao abrir o arquivo %s.\nArquivo não encontrado ou corrompido.\n", argvArquivos[a]);
return;
}
char strLinha[1000];
do {
fgets(strLinha, 999, arquivoAtual);
fputs(strLinha, arquivoResutlado);
// for(int a = 0; strLinha[a] != '\0'; a++) {
//// if((strLinha[a] >= 32) && (strLinha[a] != 127)) int qtdeCaractersNaoDeControle = 1; //Incrementa na variável qtdeCaractersNaoDeControle
// }
strcpy(strLinha, "");
} while(!feof(arquivoAtual));
fputs("\n", arquivoResutlado);
fclose(arquivoAtual);
// printf("\n%s\n", argvArquivos[a]);
}
fclose(arquivoResutlado);
}
void concatena2(int argc, char *argvArquivos[]) {
// printf("\nArgc na função concatena: %d\n", argc);
FILE *arquivoResutlado;
FILE *arquivoResutladoAux;
if ((arquivoResutlado = fopen(argvArquivos[argc-1], "r")) != NULL) {
if ((arquivoResutladoAux = fopen("arqAuxResultado.txt", "w+")) == NULL) {
printf("\n\nErro ao abrir ou criar o arquivo auxiliar de resultado.\nArquivo não encontrado ou disco com blocos defeituosos.\n"); return;
}
char strLinha[1000];
do {
fgets(strLinha, 999, arquivoResutlado);
fputs(strLinha, arquivoResutladoAux);
// for(int a = 0; strLinha[a] != '\0'; a++) {
//// if((strLinha[a] >= 32) && (strLinha[a] != 127)) int qtdeCaractersNaoDeControle = 1; //Incrementa na variável qtdeCaractersNaoDeControle
// }
strcpy(strLinha, "");
} while(!feof(arquivoResutlado));
fclose(arquivoResutlado);
fputs("\n", arquivoResutladoAux);
for(int a = 1; a < (argc -1); a++) {
FILE *arquivoAtual;
if ((arquivoAtual = fopen(argvArquivos[a], "r")) == NULL) {
printf("\n\nErro ao abrir o arquivo %s.\nArquivo não encontrado ou corrompido.\n", argvArquivos[a]);
return;
}
char strLinha[1000];
do {
fgets(strLinha, 999, arquivoAtual);
fputs(strLinha, arquivoResutladoAux);
// for(int a = 0; strLinha[a] != '\0'; a++) {
//// if((strLinha[a] >= 32) && (strLinha[a] != 127)) int qtdeCaractersNaoDeControle = 1; //Incrementa na variável qtdeCaractersNaoDeControle
// }
strcpy(strLinha, "");
} while(!feof(arquivoAtual));
fputs("\n", arquivoResutladoAux);
fclose(arquivoAtual);
// printf("\n%s\n", argvArquivos[a]);
}
fclose(arquivoResutladoAux);
if(remove(argvArquivos[argc-1]))
rename("arqResultado.txt", argvArquivos[argc-1]);
//copiar o arquivo arqAuxResultado.txt para o de resultado com o nome original.
//remover arqAuxResultado.txt
} else {
if ((arquivoResutlado = fopen(argvArquivos[argc-1], "w+")) == NULL) {
printf("\n\nErro ao abrir ou criar o arquivo de resultado.\nArquivo não encontrado ou disco com blocos defeituosos.\n"); return;
}
//Este for isola o primeiro nome, que este refere-se ao nome do programa em execução, e o ultmo, que trata-se do nome do arquivo resultado (arquivoResutlado).
for(int a = 1; a < (argc -1); a++) {
FILE *arquivoAtual;
if ((arquivoAtual = fopen(argvArquivos[a], "r")) == NULL) {
printf("\n\nErro ao abrir o arquivo %s.\nArquivo não encontrado ou corrompido.\n", argvArquivos[a]);
return;
}
char strLinha[1000];
do {
fgets(strLinha, 999, arquivoAtual);
fputs(strLinha, arquivoResutlado);
// for(int a = 0; strLinha[a] != '\0'; a++) {
//// if((strLinha[a] >= 32) && (strLinha[a] != 127)) int qtdeCaractersNaoDeControle = 1; //Incrementa na variável qtdeCaractersNaoDeControle
// }
strcpy(strLinha, "");
} while(!feof(arquivoAtual));
fputs("\n", arquivoResutlado);
fclose(arquivoAtual);
// printf("\n%s\n", argvArquivos[a]);
}
fclose(arquivoResutlado);
}
//Este for isola o primeiro nome, que este refere-se ao nome do programa em execução, e o ultmo, que trata-se do nome do arquivo resultado (arquivoResutlado).
}
int main(int argc, char *argv[]) {
// if (argc < 3) {
// printf("\nErro: Digite o nome dos dois arquivos como parâmetro para serem comparados.\n\n");
// return 1;
// }
// printf("\nArgc no MAIN: %d\n", argc);
concatena1(argc, argv);
// comparaBinarios(argv[1], argv[2]);
// for ( int i = 32; i < 127; i++ ) printf( "%c [%d]\n", i , i );
// for ( int i = 0; ( (i <= 127) && ((i < 32) || (i == 127)) ); i++ ) printf( "%c [%d]\n", i , i );
return 0;
}
| true |
3417223fbfd66fac4cddd194c419ead837d52ac4 | C++ | mfkiwl/ARTSLAM | /include/ukf/robot_control_input.h | UTF-8 | 1,213 | 2.75 | 3 | [] | no_license | /** @file robot_control_input.h
* @brief Declaration of class IMUControlInput
* @author Matteo Frosi
*/
#ifndef ARTSLAM_ROBOT_CONTROL_INPUT_H
#define ARTSLAM_ROBOT_CONTROL_INPUT_H
#include <slam_types.h>
/**
* @class IMUControlInput
* @brief This class is used hold the measurements of an IMU, used as control input for an Unscented Kalman Filter.
*/
class IMUControlInput {
public:
/**
* @brief Class constructor.
*/
IMUControlInput();
// ---------------------------------------------------------------
// ------------------- PARAMETERS AND VARIABLES ------------------
//----------------------------------------------------------------
double gyro_x; /**< Angular velocity w.r.t. the x axis */
double gyro_y; /**< Angular velocity w.r.t. the y axis */
double gyro_z; /**< Angular velocity w.r.t. the z axis */
double accel_x; /**< Acceleration w.r.t. the x axis */
double accel_y; /**< Acceleration w.r.t. the y axis */
double accel_z; /**< Acceleration w.r.t. the z axis */
uint64_t timestamp; /**< Timestamp (in nanoseconds) of the control input */
};
#endif //ARTSLAM_ROBOT_CONTROL_INPUT_H
| true |
f8b2b1666f5a9dc2b72b6b0e7c4c74158e5826fc | C++ | rezanour/randomoldstuff | /Main/Shooter1/ImportFile/utilities.cpp | UTF-8 | 459 | 2.75 | 3 | [] | no_license | #include "precomp.h"
void ReadFileToBuffer(_In_ const char* path, _Inout_ std::vector<uint8_t>& buffer)
{
buffer.clear();
std::ifstream inputfile(path, std::ios::in | std::ios_base::binary | std::ios::ate);
if (inputfile.is_open())
{
buffer.resize((uint32_t)inputfile.tellg());
inputfile.seekg(0, std::ios::beg);
inputfile.read(reinterpret_cast<char*>(buffer.data()), buffer.size());
inputfile.close();
}
} | true |
8898d35bc64f02042a2e34bc48306f20024e55f9 | C++ | PiotrPalczewski/Zadania-domowe | /zad 1.cpp | UTF-8 | 1,037 | 2.96875 | 3 | [] | no_license | #include <iostream>
#include <conio.h>
using namespace std;
int main() {
int a;
int b;
int c;
int d;
int e;
int f;
double x;
double y;
double W;
double Wy;
double Wx;
cout << "Wpisz zmienna a:" << endl;
cin >> a;
cout << "Wpisz zmienna b:" << endl;
cin >> b;
cout << "Wpisz zmienna c:" << endl;
cin >> c;
cout << "Wpisz zmienna d:" << endl;
cin >> d;
cout << "Wpisz zmienna e:" << endl;
cin >> e;
cout << "Wpisz zmienna f:" << endl;
cin >> f;
W = ((a*d) - (b*c));
Wx = ((e*d) - (b*f));
Wy = ((a*e) - (b*f));
x = (Wx / W);
y = (Wy / W);
if (W == 0 && (Wx != 0 || Wy != 0)) {
cout << "Dzialanie nieobliczalne! Wyznacznik glowny nie moze rownac sie 0 ";
}
else if (W == 0 && (Wx == 0 && Wy == 0)) {
cout << "Dzialanie sprzeczne!";
}
else {
cout << "Rozwiazanie ukladu rownan: " << endl;
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(3);
cout << "x = ";
cout.width(8);
cout << x << endl;
cout << "y = ";
cout.width(8);
cout << y;
}
_getch();
return 0;
} | true |
75757f7e108389fe2645e5f78bc6760bbc79e39f | C++ | coding-blocks-archives/Launchpad2_17_Summer_Pitampura | /17-Jun_04/reverse.cpp | UTF-8 | 287 | 2.96875 | 3 | [] | no_license | //Deepak Aggarwal, Coding Blocks
#include <iostream>
using namespace std;
int main() {
int arr[10];
//input val
for (int i = 0; i < 10; ++i) {
cin >> arr[i]; //[0, 9]
}
//reverse printing
for (int i = 9; i >= 0; --i){
cout << arr[i];
cout << " ";
// cout << arr[i] << " ";
}
} | true |
b26e5805b6e4a20a591af1b7105b989caabc69d6 | C++ | bbritva/CPP_D1 | /ex03/Weapon.hpp | UTF-8 | 310 | 2.78125 | 3 | [] | no_license | //
// Created by Gregorio Velva on 8/29/21.
//
#ifndef WEAPON_HPP
#define WEAPON_HPP
#include <string>
#include <iostream>
class Weapon
{
private:
std::string _type;
public:
Weapon();
Weapon(std::string type);
~Weapon();
void setType(std::string type);
const std::string &getType();
};
#endif //WEAPON_HPP
| true |
71a7ae092fa415ac40f0723e20efba4cce777ebd | C++ | idvr/starviewer | /starviewer/src/core/volumerepository.h | UTF-8 | 1,941 | 3.234375 | 3 | [] | no_license | #ifndef UDGVOLUMEREPOSITORY_H
#define UDGVOLUMEREPOSITORY_H
#include "repository.h"
#include "volume.h"
#include "identifier.h"
#include <QObject>
namespace udg {
/**
Aquesta classe és el repositori de volums. En aquesta classe es guarden tots els volums que hi ha oberts durant
l'execució del programa. Només hi haura una sola instància en tota la vida del programa d'aquesta classe.
Per fer-ho s'aplica el patró Singleton.
Per poder obtenir una instància del repositori hem de fer un include del fitxer volumerepository.h i fer una crida
al mètode VolumeRepository::getRepository(). Aquest ens retornarà un punter al repositori de volums.
Exemple:
\code
#include "volumerepository.h"
...
udg::VolumeRepository* m_volumeRepository;
m_volumeRepository = VolumeRepository::getRepository();
...
Volume* m_volume = m_volumeRepository->getVolume(id);
\endcode
*/
class VolumeRepository : public Repository<Volume> {
Q_OBJECT
public:
/// Afegeix un volum al repositori.
/// Ens retorna l'id del volum afegit per poder-lo obtenir més endavant.
Identifier addVolume(Volume *model);
/// Ens retorna un volum del repositori amb l'identificador que especifiquem.
Volume* getVolume(Identifier id);
/// Esborra un Volume de memòria i el treu del repositori
void deleteVolume(Identifier id);
/// Retorna el nombre de volums que hi ha al repositori
int getNumberOfVolumes();
/// Ens retorna l'única instància del repositori.
static VolumeRepository* getRepository()
{
static VolumeRepository repository;
return &repository;
}
/// El destructor allibera l'espai ocupat pels volums
~VolumeRepository(){};
signals:
void itemAdded(Identifier id);
void itemRemoved(Identifier id);
private:
/// Ha de quedar amagat perquè no poguem crear instàncies
VolumeRepository();
};
}
#endif
| true |