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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
ef15991d3ee9d70946faf1bf478b0befb02ce201 | C++ | pblottiere/dominus | /src/lib/net/client.hpp | UTF-8 | 403 | 2.796875 | 3 | [
"MIT"
] | permissive | #ifndef CLIENT_HPP
#define CLIENT_HPP
#include <string>
class Client
{
public:
Client( const std::string &ip, const int port );
bool connect();
int port() const;
std::string ip() const;
bool send( const std::string &message );
bool close();
private:
const int _port;
const std::string _ip;
int _socket;
};
#endif
| true |
768c229b0f22369260c7a2e071b80d285c8100d5 | C++ | recap/datafluo | /vlport-df/modules/Wave/WaveParameters/WaveParameters.cpp | UTF-8 | 2,189 | 2.609375 | 3 | [] | no_license | #include <string>
#include <fstream>
#include <sstream>
#include "LogManager.H"
#include "TimeLag.H"
#include "CommonDefines.h"
#include "IModule.h"
#include <string.h>
#include <stdio.h>
#include <ftw.h>
#define HERE(NUM) cout << "HERE " << #NUM << endl
#define HERE2(VAR) cout<< "HERE " << #VAR << ": " << VAR << endl
using namespace std;
class WaveParameters : public IModule {
private:
string host;
int min;
int max;
int step;
public:
WaveParameters(){
INIT_SYNCHRONIZE();
for(int i = 0; i < MAXPORTS; i++){
rx_ports[i] = NULL;
tx_ports[i] = NULL;
min = max = step = -1;
}
tx_ports[1] = new MessageQueue("tasknumber");
};
virtual ~WaveParameters() throw() {
}
void init(vector<string>* rParam);
void start();
void stop();
};
void WaveParameters::stop(){}
void WaveParameters::init(vector<string>* rParam){
//1 = min
//2 = max
//3 = step
//4 = _host
LOG_PTAG(Info) << "WaveParameters init!";
min = atoi(rParam->at(1).c_str());
max = atoi(rParam->at(2).c_str());
step = atoi(rParam->at(3).c_str());
if(min < 0)
LOG_PTAG(Error) << "wrong min value: " << min;
if(max < 0)
LOG_PTAG(Error) << "wrong max value: " << max;
if(step < 0)
LOG_PTAG(Error) << "wrong step value: " << step;
LOG_PTAG(Info) << "WaveParams mim: " << min << " max: " << max << " step: " << step << endl;
//LOG_PTAG(Info) << "_host: " << host;
}
void WaveParameters::start() {
LOG_PTAG(Info) << "WaveParameters start()";
TimeLag timing;
timing.start("WaveParameters");
for(int i = min; i < max; i += step) {
stringstream msgstr;
msgstr << "Raw://" << i;
string message(msgstr.str());
MessageQueue::Message* om1 = new MessageQueue::Message();
om1->mMessageId.assign("NONE");
om1->mDataLength = message.size();
om1->mpData = (void*)malloc(om1->mDataLength);
memcpy(om1->mpData,message.c_str(),om1->mDataLength);
char* s = (char*)om1->mpData;
s[om1->mDataLength] = '\0';
LOG_PTAG(Detail) << "Wrting Params: " << s << endl;
tx_ports[1]->Write(om1);
}//for
tx_ports[1]->Write(NULL);
timing.finish("WaveParameters");
};
REGISTER_MODULE(WaveParameters);
//end_of_file
| true |
9e2b1b807a10969ae2448e5f15c63a6612b353de | C++ | derossm/cuda-doom | /derma/misc/backup_boilerplate.h | UTF-8 | 46,246 | 3.359375 | 3 | [] | no_license |
/*
//=====
// shift (assignment) by const-ref
template<typename U>
requires (std::is_integral_v<U> || ::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
constexpr inline Byte<T, N>& operator>>=(const U& other) noexcept
{
if constexpr (::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
{
bits = static_cast<T>(static_cast<T>(bits) >> static_cast<T>(other.bits));
return *this;
}
bits = static_cast<T>(static_cast<U>(bits) >> other);
return *this;
}
template<typename U>
requires (std::is_integral_v<U> || ::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
constexpr inline Byte<T, N>& operator<<=(const U& other) noexcept
{
if constexpr (::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
{
bits = static_cast<T>(static_cast<T>(bits) << static_cast<T>(other.bits));
return *this;
}
bits = static_cast<T>(static_cast<U>(bits) << other);
return *this;
}
// shift (assignment) by forwarding-ref
template<typename U>
requires (std::is_integral_v<U> || ::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
constexpr inline Byte<T, N>& operator<<=(U&& other) noexcept
{
if constexpr (::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
{
bits = static_cast<T>(static_cast<T>(bits) << static_cast<T>(other.bits));
return *this;
}
bits = static_cast<T>(static_cast<U>(bits) << other);
return *this;
}
template<typename U>
requires (std::is_integral_v<U> || ::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
constexpr inline Byte<T, N>& operator>>=(U&& other) noexcept
{
if constexpr (::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
{
bits = static_cast<T>(static_cast<T>(bits) >> static_cast<T>(other.bits));
return *this;
}
bits = static_cast<T>(static_cast<U>(bits) >> other);
return *this;
}
// shift (non-assignment) by const-ref
template<typename U>
requires (std::is_integral_v<U> || ::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
constexpr inline U operator<<(const U& other) const noexcept
{
if constexpr (::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
{
return static_cast<T>(bits) << static_cast<T>(other.bits);
}
return static_cast<U>(bits) << other;
}
template<typename U>
requires (std::is_integral_v<U> || ::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
constexpr inline U operator>>(const U& other) const noexcept
{
if constexpr (::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
{
return static_cast<T>(bits) >> static_cast<T>(other.bits);
}
return static_cast<U>(bits) >> other;
}
// shift (non-assignment) by forwarding-ref
template<typename U>
requires (std::is_integral_v<U> || ::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
constexpr inline U operator<<(U&& other) const noexcept
{
if constexpr (::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
{
return static_cast<T>(bits) << static_cast<T>(other.bits);
}
return static_cast<U>(bits) << other;
}
template<typename U>
requires (std::is_integral_v<U> || ::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
constexpr inline U operator>>(U&& other) const noexcept
{
if constexpr (::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
{
return static_cast<T>(bits) >> static_cast<T>(other.bits);
}
return static_cast<U>(bits) >> other;
}
//=====
// comparison by const-ref
template<typename U>
requires (std::is_integral_v<U> || ::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
constexpr inline bool operator==(const U& rhs) const noexcept
{
if constexpr (::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
{
return (static_cast<T>(bits) == static_cast<T>(rhs.bits)) == 0;
}
return (static_cast<U>(bits) == rhs) == 0;
}
template<typename U>
requires (std::is_integral_v<U> || ::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
constexpr inline bool operator!=(const U& rhs) const noexcept
{
if constexpr (::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
{
return (static_cast<T>(bits) != static_cast<T>(rhs.bits)) != 0;
}
return (static_cast<U>(bits) != rhs) != 0;
}
template<typename U>
requires (std::is_integral_v<U> || ::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
constexpr inline bool operator< (const U& rhs) const noexcept
{
if constexpr (::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
{
return (static_cast<T>(bits) < static_cast<T>(rhs.bits)) < 0;
}
return (static_cast<U>(bits) < rhs) < 0;
}
template<typename U>
requires (std::is_integral_v<U> || ::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
constexpr inline bool operator<=(const U& rhs) const noexcept
{
if constexpr (::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
{
return (static_cast<T>(bits) <= static_cast<T>(rhs.bits)) <= 0;
}
return (static_cast<U>(bits) <= rhs) <= 0;
}
template<typename U>
requires (std::is_integral_v<U> || ::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
constexpr inline bool operator> (const U& rhs) const noexcept
{
if constexpr (::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
{
return (static_cast<T>(bits) > static_cast<T>(rhs.bits)) > 0;
}
return (static_cast<U>(bits) > rhs) > 0;
}
template<typename U>
requires (std::is_integral_v<U> || ::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
constexpr inline bool operator>=(const U& rhs) const noexcept
{
if constexpr (::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
{
return (static_cast<T>(bits) >= static_cast<T>(rhs.bits)) >= 0;
}
return (static_cast<U>(bits) >= rhs) >= 0;
}
template<typename U>
requires (std::is_integral_v<U> || ::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
constexpr inline auto operator<=>(const U& rhs) const noexcept
{
if constexpr (::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
{
return static_cast<T>(bits) <=> static_cast<T>(rhs.bits);
}
return static_cast<U>(bits) <=> rhs;
}
template<typename U>
requires (std::is_integral_v<U> || ::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
constexpr inline bool operator||(const U& rhs) const noexcept
{
if constexpr (::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
{
return (static_cast<T>(bits) || static_cast<T>(rhs.bits));
}
return (static_cast<U>(bits) || rhs);
}
template<typename U>
requires (std::is_integral_v<U> || ::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
constexpr inline bool operator&&(const U& rhs) const noexcept
{
if constexpr (::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
{
return (static_cast<T>(bits) && static_cast<T>(rhs.bits));
}
return (static_cast<U>(bits) && rhs);
}
// comparison by forwarding-ref
template<typename U>
requires (std::is_integral_v<U> || ::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
constexpr inline bool operator==(U&& rhs) const noexcept
{
if constexpr (::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
{
return (static_cast<T>(bits) == static_cast<T>(rhs.bits)) == 0;
}
return (static_cast<U>(bits) == rhs) == 0;
}
template<typename U>
requires (std::is_integral_v<U> || ::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
constexpr inline bool operator!=(U&& rhs) const noexcept
{
if constexpr (::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
{
return (static_cast<T>(bits) != static_cast<T>(rhs.bits)) != 0;
}
return (static_cast<U>(bits) != rhs) != 0;
}
template<typename U>
requires (std::is_integral_v<U> || ::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
constexpr inline bool operator< (U&& rhs) const noexcept
{
if constexpr (::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
{
return (static_cast<T>(bits) < static_cast<T>(rhs.bits)) < 0;
}
return (static_cast<U>(bits) < rhs) < 0;
}
template<typename U>
requires (std::is_integral_v<U> || ::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
constexpr inline bool operator<=(U&& rhs) const noexcept
{
if constexpr (::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
{
return (static_cast<T>(bits) <= static_cast<T>(rhs.bits)) <= 0;
}
return (static_cast<U>(bits) <= rhs) <= 0;
}
template<typename U>
requires (std::is_integral_v<U> || ::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
constexpr inline bool operator> (U&& rhs) const noexcept
{
if constexpr (::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
{
return (static_cast<T>(bits) > static_cast<T>(rhs.bits)) > 0;
}
return (static_cast<U>(bits) > rhs) > 0;
}
template<typename U>
requires (std::is_integral_v<U> || ::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
constexpr inline bool operator>=(U&& rhs) const noexcept
{
if constexpr (::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
{
return (static_cast<T>(bits) >= static_cast<T>(rhs.bits)) >= 0;
}
return (static_cast<U>(bits) >= rhs) >= 0;
}
template<typename U>
requires (std::is_integral_v<U> || ::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
constexpr inline auto operator<=>(U&& rhs) const noexcept
{
if constexpr (::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
{
return static_cast<T>(bits) <=> static_cast<T>(rhs.bits);
}
return static_cast<U>(bits) <=> rhs;
}
template<typename U>
requires (std::is_integral_v<U> || ::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
constexpr inline bool operator||(U&& rhs) const noexcept
{
if constexpr (::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
{
return (static_cast<T>(bits) || static_cast<T>(rhs.bits));
}
return (static_cast<U>(bits) || rhs);
}
template<typename U>
requires (std::is_integral_v<U> || ::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
constexpr inline bool operator&&(U&& rhs) const noexcept
{
if constexpr (::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
{
return (static_cast<T>(bits) && static_cast<T>(rhs.bits));
}
return (static_cast<U>(bits) && rhs);
}
//=====
// assignment by const-ref
template<typename U>
requires (std::is_integral_v<U> || ::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
constexpr inline Byte<T, N>& operator=(const U& other) noexcept
{
if constexpr (::std::is_same_v<U, Byte<T, N>>)
{
if (this == &other)
{
return *this;
}
bits = other.bits;
return *this;
}
else if constexpr (::std::is_class_v<U>)
{
bits = static_cast<T>(other.bits);
return *this;
}
bits = static_cast<T>(other);
return *this;
}
// assignment by forwarding-ref
template<typename U>
requires (std::is_integral_v<U> || ::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
constexpr inline Byte<T, N>& operator=(U&& other) noexcept
{
if constexpr (::std::is_same_v<U, Byte<T, N>>)
{
if (this == &other)
{
return *this;
}
bits = other.bits;
return *this;
}
else if constexpr (::std::is_class_v<U>)
{
bits = static_cast<T>(other.bits);
return *this;
}
bits = static_cast<T>(other);
return *this;
}
//=====
// bitwise (assignment) by const-ref
template<typename U>
requires (std::is_integral_v<U> || ::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
constexpr inline U operator|(const U& other) const noexcept
{
if constexpr (::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
{
return static_cast<T>(bits) | static_cast<T>(other.bits);
}
return static_cast<U>(bits) | other;
}
template<typename U>
requires (std::is_integral_v<U> || ::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
constexpr inline U operator&(const U& other) const noexcept
{
if constexpr (::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
{
return static_cast<T>(bits) & static_cast<T>(other.bits);
}
return static_cast<U>(bits) & other;
}
template<typename U>
requires (std::is_integral_v<U> || ::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
constexpr inline U operator^(const U& other) const noexcept
{
if constexpr (::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
{
return static_cast<T>(bits) ^ static_cast<T>(other.bits);
}
return static_cast<U>(bits) ^ other;
}
// bitwise (non-assignment) by forwarding-ref
template<typename U>
requires (std::is_integral_v<U> || ::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
constexpr inline U operator|(U&& other) const noexcept
{
if constexpr (::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
{
return static_cast<T>(bits) | static_cast<T>(other.bits);
}
return static_cast<U>(bits) | other;
}
template<typename U>
requires (std::is_integral_v<U> || ::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
constexpr inline U operator&(U&& other) const noexcept
{
if constexpr (::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
{
return static_cast<T>(bits) & static_cast<T>(other.bits);
}
return static_cast<U>(bits) & other;
}
template<typename U>
requires (std::is_integral_v<U> || ::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
constexpr inline U operator^(U&& other) const noexcept
{
if constexpr (::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
{
return static_cast<T>(bits) ^ static_cast<T>(other.bits);
}
return static_cast<U>(bits) ^ other;
}
//=====
// arithmetic (non-assignment) by const-ref
template<typename U>
requires (std::is_integral_v<U> || ::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
constexpr inline U operator+(const U& other) const noexcept
{
if constexpr (::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
{
return static_cast<T>(bits) + static_cast<T>(other.bits);
}
return static_cast<U>(bits) + other;
}
template<typename U>
requires (std::is_integral_v<U> || ::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
constexpr inline U operator-(const U& other) const noexcept
{
if constexpr (::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
{
return static_cast<T>(bits) - static_cast<T>(other.bits);
}
return static_cast<U>(bits) - other;
}
template<typename U>
requires (std::is_integral_v<U> || ::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
constexpr inline U operator*(const U& other) const noexcept
{
if constexpr (::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
{
return static_cast<T>(bits) * static_cast<T>(other.bits);
}
return static_cast<U>(bits) * other;
}
template<typename U>
requires (std::is_integral_v<U> || ::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
constexpr inline U operator/(const U& other) const noexcept
{
if constexpr (::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
{
return static_cast<T>(bits) / static_cast<T>(other.bits);
}
return static_cast<U>(bits) / other;
}
template<typename U>
requires (std::is_integral_v<U> || ::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
constexpr inline U operator%(const U& other) const noexcept
{
if constexpr (::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
{
return static_cast<T>(bits) / static_cast<T>(other.bits);
}
return static_cast<U>(bits) % other;
}
// arithmetic (non-assignment) by forwarding-ref
template<typename U>
requires (std::is_integral_v<U> || ::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
constexpr inline U operator+(U&& other) const noexcept
{
if constexpr (::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
{
return static_cast<T>(bits) + static_cast<T>(other.bits);
}
return static_cast<U>(bits) + other;
}
template<typename U>
requires (std::is_integral_v<U> || ::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
constexpr inline U operator-(U&& other) const noexcept
{
if constexpr (::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
{
return static_cast<T>(bits) - static_cast<T>(other.bits);
}
return static_cast<U>(bits) - other;
}
template<typename U>
requires (std::is_integral_v<U> || ::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
constexpr inline U operator*(U&& other) const noexcept
{
if constexpr (::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
{
return static_cast<T>(bits) * static_cast<T>(other.bits);
}
return static_cast<U>(bits) * other;
}
template<typename U>
requires (std::is_integral_v<U> || ::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
constexpr inline U operator/(U&& other) const noexcept
{
if constexpr (::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
{
return static_cast<T>(bits) / static_cast<T>(other.bits);
}
return static_cast<U>(bits) / other;
}
template<typename U>
requires (std::is_integral_v<U> || ::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
constexpr inline U operator%(U&& other) const noexcept
{
if constexpr (::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
{
return static_cast<T>(bits) / static_cast<T>(other.bits);
}
return static_cast<U>(bits) % other;
}
//=====
// bitwise (assignment) by const-ref
template<typename U>
requires (std::is_integral_v<U> || ::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
constexpr inline Byte<T, N>& operator|=(const U& other) noexcept
{
if constexpr (::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
{
bits |= other.bits;
return *this;
}
bits |= static_cast<T>(other);
return *this;
}
template<typename U>
requires (std::is_integral_v<U> || ::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
constexpr inline Byte<T, N>& operator&=(const U& other) noexcept
{
if constexpr (::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
{
bits &= other.bits;
return *this;
}
bits &= static_cast<T>(other);
return *this;
}
template<typename U>
requires (std::is_integral_v<U> || ::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
constexpr inline Byte<T, N>& operator^=(const U& other) noexcept
{
if constexpr (::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
{
bits ^= other.bits;
return *this;
}
bits ^= static_cast<T>(other);
return *this;
}
// bitwise (assignment) by forwarding-ref
template<typename U>
requires (std::is_integral_v<U> || ::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
constexpr inline Byte<T, N>& operator|=(U&& other) noexcept
{
if constexpr (::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
{
bits |= other.bits;
return *this;
}
bits |= static_cast<T>(other);
return *this;
}
template<typename U>
requires (std::is_integral_v<U> || ::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
constexpr inline Byte<T, N>& operator&=(U&& other) noexcept
{
if constexpr (::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
{
bits &= other.bits;
return *this;
}
bits &= static_cast<T>(other);
return *this;
}
template<typename U>
requires (std::is_integral_v<U> || ::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
constexpr inline Byte<T, N>& operator^=(U&& other) noexcept
{
if constexpr (::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
{
bits ^= other.bits;
return *this;
}
bits ^= static_cast<T>(other);
return *this;
}
// arithmetic (assignment) by const-ref
template<typename U>
requires (std::is_integral_v<U> || ::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
constexpr inline Byte<T, N>& operator+=(const U& other) noexcept
{
if constexpr (::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
{
bits = static_cast<T>(static_cast<T>(bits) + static_cast<T>(other.bits));
return *this;
}
bits = static_cast<T>(static_cast<U>(bits) + other);
return *this;
}
template<typename U>
requires (std::is_integral_v<U> || ::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
constexpr inline Byte<T, N>& operator-=(const U& other) noexcept
{
if constexpr (::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
{
bits = static_cast<T>(static_cast<T>(bits) - static_cast<T>(other.bits));
return *this;
}
bits = static_cast<T>(static_cast<U>(bits) - other);
return *this;
}
template<typename U>
requires (std::is_integral_v<U> || ::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
constexpr inline Byte<T, N>& operator*=(const U& other) noexcept
{
if constexpr (::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
{
bits = static_cast<T>(static_cast<T>(bits) * static_cast<T>(other.bits));
return *this;
}
bits = static_cast<T>(static_cast<U>(bits) * other);
return *this;
}
template<typename U>
requires (std::is_integral_v<U> || ::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
constexpr inline Byte<T, N>& operator/=(const U& other) noexcept
{
if constexpr (::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
{
bits = static_cast<T>(static_cast<T>(bits) / static_cast<T>(other.bits));
return *this;
}
bits = static_cast<T>(static_cast<U>(bits) / other);
return *this;
}
template<typename U>
requires (std::is_integral_v<U> || ::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
constexpr inline Byte<T, N>& operator%=(const U& other) noexcept
{
if constexpr (::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
{
bits = static_cast<T>(static_cast<T>(bits) % static_cast<T>(other.bits));
return *this;
}
bits = static_cast<T>(static_cast<U>(bits) % other);
return *this;
}
// arithmetic (assignment) by forwarding-ref
template<typename U>
requires (std::is_integral_v<U> || ::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
constexpr inline Byte<T, N>& operator+=(U&& other) noexcept
{
if constexpr (::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
{
bits = static_cast<T>(static_cast<T>(bits) + static_cast<T>(other.bits));
return *this;
}
bits = static_cast<T>(static_cast<U>(bits) + other);
return *this;
}
template<typename U>
requires (std::is_integral_v<U> || ::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
constexpr inline Byte<T, N>& operator-=(U&& other) noexcept
{
if constexpr (::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
{
bits = static_cast<T>(static_cast<T>(bits) - static_cast<T>(other.bits));
return *this;
}
bits = static_cast<T>(static_cast<U>(bits) - other);
return *this;
}
template<typename U>
requires (std::is_integral_v<U> || ::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
constexpr inline Byte<T, N>& operator*=(U&& other) noexcept
{
if constexpr (::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
{
bits = static_cast<T>(static_cast<T>(bits) * static_cast<T>(other.bits));
return *this;
}
bits = static_cast<T>(static_cast<U>(bits) * other);
return *this;
}
template<typename U>
requires (std::is_integral_v<U> || ::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
constexpr inline Byte<T, N>& operator/=(U&& other) noexcept
{
if constexpr (::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
{
bits = static_cast<T>(static_cast<T>(bits) / static_cast<T>(other.bits));
return *this;
}
bits = static_cast<T>(static_cast<U>(bits) / other);
return *this;
}
template<typename U>
requires (std::is_integral_v<U> || ::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
constexpr inline Byte<T, N>& operator%=(U&& other) noexcept
{
if constexpr (::std::is_same_v<U, Byte<T, N>> || ::std::is_class_v<U>)
{
bits = static_cast<T>(static_cast<T>(bits) % static_cast<T>(other.bits));
return *this;
}
bits = static_cast<T>(static_cast<U>(bits) % other);
return *this;
}
//==============================================================================
// friends
//=====
// comparison by const-ref
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
friend constexpr inline bool operator==(const U& lhs, const Byte<T, N>& rhs) noexcept;
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
friend constexpr inline bool operator!=(const U& lhs, const Byte<T, N>& rhs) noexcept;
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
friend constexpr inline bool operator< (const U& lhs, const Byte<T, N>& rhs) noexcept;
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
friend constexpr inline bool operator<=(const U& lhs, const Byte<T, N>& rhs) noexcept;
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
friend constexpr inline bool operator> (const U& lhs, const Byte<T, N>& rhs) noexcept;
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
friend constexpr inline bool operator>=(const U& lhs, const Byte<T, N>& rhs) noexcept;
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
friend constexpr inline auto operator<=>(const U& lhs, const Byte<T, N>& rhs) noexcept;
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
friend constexpr inline bool operator||(const U& lhs, const Byte<T, N>& rhs) noexcept;
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
friend constexpr inline bool operator&&(const U& lhs, const Byte<T, N>& rhs) noexcept;
// comparison by forwarding-ref
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
friend constexpr inline bool operator==(U&& lhs, Byte<T, N>&& rhs) noexcept;
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
friend constexpr inline bool operator!=(U&& lhs, Byte<T, N>&& rhs) noexcept;
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
friend constexpr inline bool operator< (U&& lhs, Byte<T, N>&& rhs) noexcept;
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
friend constexpr inline bool operator<=(U&& lhs, Byte<T, N>&& rhs) noexcept;
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
friend constexpr inline bool operator> (U&& lhs, Byte<T, N>&& rhs) noexcept;
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
friend constexpr inline bool operator>=(U&& lhs, Byte<T, N>&& rhs) noexcept;
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
friend constexpr inline auto operator<=>(U&& lhs, Byte<T, N>&& rhs) noexcept;
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
friend constexpr inline bool operator||(U&& lhs, Byte<T, N>&& rhs) noexcept;
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
friend constexpr inline bool operator&&(U&& lhs, Byte<T, N>&& rhs) noexcept;
//=====
// bitwise (non-assignment) by const-ref
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
friend constexpr inline U operator|(const U& lhs, const Byte<T, N>& rhs) noexcept;
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
friend constexpr inline U operator&(const U& lhs, const Byte<T, N>& rhs) noexcept;
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
friend constexpr inline U operator^(const U& lhs, const Byte<T, N>& rhs) noexcept;
// bitwise (non-assignment) by forwarding-ref
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
friend constexpr inline U operator|(U&& lhs, Byte<T, N>&& rhs) noexcept;
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
friend constexpr inline U operator&(U&& lhs, Byte<T, N>&& rhs) noexcept;
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
friend constexpr inline U operator^(U&& lhs, Byte<T, N>&& rhs) noexcept;
//=====
// arithmetic (non-assignment) by const-ref
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
friend constexpr inline U operator+(const U& lhs, const Byte<T, N>& rhs) noexcept;
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
friend constexpr inline U operator-(const U& lhs, const Byte<T, N>& rhs) noexcept;
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
friend constexpr inline U operator*(const U& lhs, const Byte<T, N>& rhs) noexcept;
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
friend constexpr inline U operator/(const U& lhs, const Byte<T, N>& rhs) noexcept;
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
friend constexpr inline U operator%(const U& lhs, const Byte<T, N>& rhs) noexcept;
// arithmetic (non-assignment) by forwarding-ref
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
friend constexpr inline U operator+(U&& lhs, Byte<T, N>&& rhs) noexcept;
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
friend constexpr inline U operator-(U&& lhs, Byte<T, N>&& rhs) noexcept;
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
friend constexpr inline U operator*(U&& lhs, Byte<T, N>&& rhs) noexcept;
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
friend constexpr inline U operator/(U&& lhs, Byte<T, N>&& rhs) noexcept;
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
friend constexpr inline U operator%(U&& lhs, Byte<T, N>&& rhs) noexcept;
//=====
// bitwise (assignment) by const-ref
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
friend constexpr inline U& operator|=(U& lhs, const Byte<T, N>& rhs) noexcept;
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
friend constexpr inline U& operator&=(U& lhs, const Byte<T, N>& rhs) noexcept;
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
friend constexpr inline U& operator^=(U& lhs, const Byte<T, N>& rhs) noexcept;
// bitwise (assignment) by forwarding-ref
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
friend constexpr inline U& operator|=(U&& lhs, Byte<T, N>&& rhs) noexcept;
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
friend constexpr inline U& operator&=(U&& lhs, Byte<T, N>&& rhs) noexcept;
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
friend constexpr inline U& operator^=(U&& lhs, Byte<T, N>&& rhs) noexcept;
//=====
// arithmetic (assignment) by const-ref
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
friend constexpr inline U& operator+=(U& lhs, const Byte<T, N>& rhs) noexcept;
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
friend constexpr inline U& operator-=(U& lhs, const Byte<T, N>& rhs) noexcept;
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
friend constexpr inline U& operator*=(U& lhs, const Byte<T, N>& rhs) noexcept;
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
friend constexpr inline U& operator/=(U& lhs, const Byte<T, N>& rhs) noexcept;
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
friend constexpr inline U& operator%=(U& lhs, const Byte<T, N>& rhs) noexcept;
// arithmetic (assignment) by forwarding-ref
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
friend constexpr inline U& operator+=(U&& lhs, Byte<T, N>&& rhs) noexcept;
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
friend constexpr inline U& operator-=(U&& lhs, Byte<T, N>&& rhs) noexcept;
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
friend constexpr inline U& operator*=(U&& lhs, Byte<T, N>&& rhs) noexcept;
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
friend constexpr inline U& operator/=(U&& lhs, Byte<T, N>&& rhs) noexcept;
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
friend constexpr inline U& operator%=(U&& lhs, Byte<T, N>&& rhs) noexcept;
};
//=====
// comparison by const-ref
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
constexpr inline bool operator==(const U& lhs, const Byte<T, N>& rhs) noexcept
{
return (lhs == static_cast<U>(rhs.bits)) == 0;
}
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
constexpr inline bool operator!=(const U& lhs, const Byte<T, N>& rhs) noexcept
{
return (lhs != static_cast<U>(rhs.bits)) != 0;
}
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
constexpr inline bool operator< (const U& lhs, const Byte<T, N>& rhs) noexcept
{
return (lhs < static_cast<U>(rhs.bits)) < 0;
}
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
constexpr inline bool operator<=(const U& lhs, const Byte<T, N>& rhs) noexcept
{
return (lhs <= static_cast<U>(rhs.bits)) <= 0;
}
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
constexpr inline bool operator> (const U& lhs, const Byte<T, N>& rhs) noexcept
{
return (lhs > static_cast<U>(rhs.bits)) > 0;
}
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
constexpr inline bool operator>=(const U& lhs, const Byte<T, N>& rhs) noexcept
{
return (lhs >= static_cast<U>(rhs.bits)) >= 0;
}
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
constexpr inline auto operator<=>(const U& lhs, const Byte<T, N>& rhs) noexcept
{
return lhs <=> static_cast<U>(rhs.bits);
}
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
constexpr inline bool operator||(const U& lhs, const Byte<T, N>& rhs) noexcept
{
return (lhs || static_cast<U>(rhs.bits));
}
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
constexpr inline bool operator&&(const U& lhs, const Byte<T, N>& rhs) noexcept
{
return (lhs && static_cast<U>(rhs.bits));
}
// comparison by forwarding-ref
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
constexpr inline bool operator==(U&& lhs, Byte<T, N>&& rhs) noexcept
{
return (lhs == static_cast<U>(rhs.bits)) == 0;
}
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
constexpr inline bool operator!=(U&& lhs, Byte<T, N>&& rhs) noexcept
{
return (lhs != static_cast<U>(rhs.bits)) != 0;
}
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
constexpr inline bool operator< (U&& lhs, Byte<T, N>&& rhs) noexcept
{
return (lhs < static_cast<U>(rhs.bits)) < 0;
}
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
constexpr inline bool operator<=(U&& lhs, Byte<T, N>&& rhs) noexcept
{
return (lhs <= static_cast<U>(rhs.bits)) <= 0;
}
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
constexpr inline bool operator> (U&& lhs, Byte<T, N>&& rhs) noexcept
{
return (lhs > static_cast<U>(rhs.bits)) > 0;
}
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
constexpr inline bool operator>=(U&& lhs, Byte<T, N>&& rhs) noexcept
{
return (lhs >= static_cast<U>(rhs.bits)) >= 0;
}
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
constexpr inline auto operator<=>(U&& lhs, Byte<T, N>&& rhs) noexcept
{
return lhs <=> static_cast<U>(rhs.bits);
}
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
constexpr inline bool operator||(U&& lhs, Byte<T, N>&& rhs) noexcept
{
return (lhs || static_cast<U>(rhs.bits));
}
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
constexpr inline bool operator&&(U&& lhs, Byte<T, N>&& rhs) noexcept
{
return (lhs && static_cast<U>(rhs.bits));
}
//=====
// bitwise (non-assignment) by const-ref
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
constexpr inline U operator|(const U& lhs, const Byte<T, N>& rhs) noexcept
{
return lhs | static_cast<U>(rhs.bits);
}
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
constexpr inline U operator&(const U& lhs, const Byte<T, N>& rhs) noexcept
{
return lhs & static_cast<U>(rhs.bits);
}
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
constexpr inline U operator^(const U& lhs, const Byte<T, N>& rhs) noexcept
{
return lhs ^ static_cast<U>(rhs.bits);
}
// bitwise (non-assignment) by forwarding-ref
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
constexpr inline U operator|(U&& lhs, Byte<T, N>&& rhs) noexcept
{
return lhs | static_cast<U>(rhs.bits);
}
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
constexpr inline U operator&(U&& lhs, Byte<T, N>&& rhs) noexcept
{
return lhs & static_cast<U>(rhs.bits);
}
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
constexpr inline U operator^(U&& lhs, Byte<T, N>&& rhs) noexcept
{
return lhs ^ static_cast<U>(rhs.bits);
}
//=====
// arithmetic (non-assignment) by const-ref
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
constexpr inline U operator+(const U& lhs, const Byte<T, N>& rhs) noexcept
{
return lhs + static_cast<U>(rhs.bits);
}
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
constexpr inline U operator-(const U& lhs, const Byte<T, N>& rhs) noexcept
{
return lhs - static_cast<U>(rhs.bits);
}
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
constexpr inline U operator*(const U& lhs, const Byte<T, N>& rhs) noexcept
{
return lhs * static_cast<U>(rhs.bits);
}
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
constexpr inline U operator/(const U& lhs, const Byte<T, N>& rhs) noexcept
{
return lhs / static_cast<U>(rhs.bits);
}
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
constexpr inline U operator%(const U& lhs, const Byte<T, N>& rhs) noexcept
{
return lhs % static_cast<U>(rhs.bits);
}
// arithmetic (non-assignment) by forwarding-ref
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
constexpr inline U operator+(U&& lhs, Byte<T, N>&& rhs) noexcept
{
return lhs + static_cast<U>(rhs.bits);
}
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
constexpr inline U operator-(U&& lhs, Byte<T, N>&& rhs) noexcept
{
return lhs - static_cast<U>(rhs.bits);
}
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
constexpr inline U operator*(U&& lhs, Byte<T, N>&& rhs) noexcept
{
return lhs * static_cast<U>(rhs.bits);
}
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
constexpr inline U operator/(U&& lhs, Byte<T, N>&& rhs) noexcept
{
return lhs / static_cast<U>(rhs.bits);
}
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
constexpr inline U operator%(U&& lhs, Byte<T, N>&& rhs) noexcept
{
return lhs % static_cast<U>(rhs.bits);
}
//=====
// bitwise (assignment) by const-ref
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
constexpr inline U& operator|=(U& lhs, const Byte<T, N>& rhs) noexcept
{
return lhs |= static_cast<U>(rhs.bits);
}
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
constexpr inline U& operator&=(U& lhs, const Byte<T, N>& rhs) noexcept
{
return lhs &= static_cast<U>(rhs.bits);
}
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
constexpr inline U& operator^=(U& lhs, const Byte<T, N>& rhs) noexcept
{
return lhs ^= static_cast<U>(rhs.bits);
}
// bitwise (assignment) by forwarding-ref
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
constexpr inline U& operator|=(U&& lhs, Byte<T, N>&& rhs) noexcept
{
return lhs |= static_cast<U>(rhs.bits);
}
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
constexpr inline U& operator&=(U&& lhs, Byte<T, N>&& rhs) noexcept
{
return lhs &= static_cast<U>(rhs.bits);
}
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
constexpr inline U& operator^=(U&& lhs, Byte<T, N>&& rhs) noexcept
{
return lhs ^= static_cast<U>(rhs.bits);
}
//=====
// arithmetic (assignment) by const-ref
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
constexpr inline U& operator+=( U& lhs, const Byte<T, N>& rhs) noexcept
{
return lhs += static_cast<U>(rhs.bits);
}
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
constexpr inline U& operator-=( U& lhs, const Byte<T, N>& rhs) noexcept
{
return lhs -= static_cast<U>(rhs.bits);
}
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
constexpr inline U& operator*=( U& lhs, const Byte<T, N>& rhs) noexcept
{
return lhs *= static_cast<U>(rhs.bits);
}
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
constexpr inline U& operator/=( U& lhs, const Byte<T, N>& rhs) noexcept
{
return lhs /= static_cast<U>(rhs.bits);
}
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
constexpr inline U& operator%=( U& lhs, const Byte<T, N>& rhs) noexcept
{
return lhs %= static_cast<U>(rhs.bits);
}
// arithmetic (assignment) by forwarding-ref
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
constexpr inline U& operator+=(U& lhs, Byte<T, N>&& rhs) noexcept
{
return lhs += static_cast<U>(rhs.bits);
}
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
constexpr inline U& operator-=(U& lhs, Byte<T, N>&& rhs) noexcept
{
return lhs -= static_cast<U>(rhs.bits);
}
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
constexpr inline U& operator*=(U& lhs, Byte<T, N>&& rhs) noexcept
{
return lhs *= static_cast<U>(rhs.bits);
}
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
constexpr inline U& operator/=(U& lhs, Byte<T, N>&& rhs) noexcept
{
return lhs /= static_cast<U>(rhs.bits);
}
template<typename T, size_t N, typename U>
requires (std::is_integral_v<U> && !::std::is_same_v<U, Byte<T, N>>)
constexpr inline U& operator%=(U& lhs, Byte<T, N>&& rhs) noexcept
{
return lhs %= static_cast<U>(rhs.bits);
}
*/ | true |
7b7d7c45f9f20f99725ec80c94f31b69f61a5ac5 | C++ | aliddell/bertini_real | /include/curve.hpp | UTF-8 | 25,318 | 2.59375 | 3 | [
"FSFAP",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | #ifndef CURVE_H
#define CURVE_H
/** \file curve.hpp */
#include <cstddef>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <math.h>
#include <gmp.h>
#include <time.h>
#include <float.h>
#include <limits.h>
#include <mpfr.h>
#include <mpf2mpfr.h>
#include <set>
#include "bertini_headers.hpp"
#include "checkSelfConjugate.hpp"
#include "fileops.hpp"
#include "data_type.hpp"
#include "isosingular.hpp"
#include "programConfiguration.hpp"
#include "nullspace.hpp"
#include "solver_sphere.hpp"
/**
\brief 1-cell.
the edge data type. has three indices: left, right, midpt.
*/
class Edge : public Cell
{
int left_; ///< index into vertices
int right_; ///< index into vertices
std::vector< int > removed_points_;
public:
typedef std::vector< int >::iterator removed_iterator;
typedef std::vector< int >::const_iterator removed_const_iterator;
/**
\return get an iterator to the beginning of the set of removed points, which were merged away in the merge operation.
*/
inline removed_iterator removed_begin() {return removed_points_.begin();}
/**
\return get an iterator to the beginning of the set of removed points, which were merged away in the merge operation.
*/
inline removed_const_iterator removed_begin() const {return removed_points_.begin();}
/**
\return get an iterator to the end of the set of removed points, which were merged away in the merge operation.
*/
inline removed_iterator removed_end() {return removed_points_.end();}
/**
\return get an iterator to the end of the set of removed points, which were merged away in the merge operation.
*/
inline removed_const_iterator removed_end() const {return removed_points_.end();}
/**
\brief adds a point as a removed point. tacks on to the end of the vector
\param new_removed_point the index of the point to add
\return the index of the point
*/
int add_removed_point(int new_removed_point)
{
removed_points_.push_back(new_removed_point);
return new_removed_point;
}
/**
\brief get the right point
\return the index of the right point
*/
inline int right() const
{
return right_;
}
/**
\brief set the left point
\param new_right the new index of the left point
\return the index of the left point
*/
int right(int new_right)
{
return right_ = new_right;
}
/**
\brief get the left point
\return the index of the left point
*/
inline int left() const
{
return left_;
}
/**
\brief set the left point
\param new_left the new index of the left point
\return the index of the left point
*/
int left(int new_left)
{
return left_ = new_left;
}
/**
default constructor
*/
Edge() : Cell()
{
left_ = right_ = -1;
}
/**
\brief construct edge from left mid and right indices
\param new_left the new left index for constructed edge
\param new_midpt the new mid index for constructed edge
\param new_right the new right index for constructed edge
*/
Edge(int new_left, int new_midpt, int new_right)
{
left(new_left);
right(new_right);
midpt(new_midpt);
}
/**
check whether the edge is degenerate
\return true if the edge is degenerate, false if not.
*/
inline bool is_degenerate() const
{
if ((left() == right()) && (left()==midpt()) && (right()==midpt()))
return true;
else
return false;
}
/**
\brief send to a single target
\param target to whom to send this edge
\param mpi_config the current state of parallelism
*/
void send(int target, ParallelismConfig & mpi_config) const
{
int * buffer = new int[4];
buffer[0] = left();
buffer[1] = midpt();
buffer[2] = right();
buffer[3] = removed_points_.size();
MPI_Send(buffer, 4, MPI_INT, target, EDGE, mpi_config.comm());
delete [] buffer;
buffer = new int[removed_points_.size()];
for (unsigned int ii=0; ii!=removed_points_.size(); ii++) {
buffer[ii] = removed_points_[ii];
}
MPI_Send(buffer, removed_points_.size(), MPI_INT, target, EDGE, mpi_config.comm());
delete [] buffer;
}
/**
\brief receive from a single source
\param source from whom to receive this edge
\param mpi_config the current state of parallelism
*/
void receive(int source, ParallelismConfig & mpi_config)
{
MPI_Status statty_mc_gatty;
int * buffer = new int[4];
MPI_Recv(buffer, 4, MPI_INT, source, EDGE, mpi_config.comm(), &statty_mc_gatty);
left(buffer[0]);
midpt(buffer[1]);
right(buffer[2]);
int temp_num_removed = buffer[3];
delete [] buffer;
buffer = new int[temp_num_removed];
MPI_Recv(buffer, temp_num_removed, MPI_INT, source, EDGE, mpi_config.comm(), &statty_mc_gatty);
for (int ii=0; ii<temp_num_removed; ii++) {
removed_points_.push_back(buffer[ii]);
}
delete [] buffer;
}
/**
\brief get edge from input stream. this function is defunct, and needs implementation apparently.
\param is the stream from whom to read
*/
virtual void read_from_stream( std::istream &is )
{
is >> left_ >> midpt_ >> right_;
}
friend std::ostream & operator<<(std::ostream & out, const Edge & E){
out << E.left_ << " " << E.midpt_ << " " << E.right_;
return out;
}
};
/**
\brief A bertini_real cell curve Decomposition.
includes methods to add vertices, look up vertices, etc
*/
class Curve : public Decomposition
{
std::vector< std::vector<int > > sample_indices_; ///< the indices of the vertices for the samples on the edges.
std::vector<Edge> edges_; ///< The edges (1-cells) computed by Bertini_real
size_t num_edges_; ///< How many edges this Decomposition currently has. This could also be inferred from edges.size()
public:
/**
query how many samples there are on an edge
\throws out of range if there aren't as many edges as needed to do the lookup.
\param edge_index the index of the edge, for which to query.
\return the number of samples on edge i
*/
unsigned int num_samples_on_edge(unsigned int edge_index) const
{
if (edge_index >= sample_indices_.size()) {
throw std::out_of_range("trying to access sample_indices_ of out of range index");
}
return sample_indices_[edge_index].size();
}
/**
get the index of sample on edge, at index position
\throws out of range if there aren't as many edges as needed to do the lookup, or if there aren't that many samples..
\param edge_index the index of the edge, for which to query.
\param vertex_index the position of the vertex you want the index of.
\return the index of the point, in the vertex set
*/
int sample_index(unsigned int edge_index, unsigned int vertex_index) const
{
if (edge_index>=num_edges()) {
std::stringstream ss;
ss << "when accessing sample index, trying to access EDGE index out of range" << "\n" << "edge_index: " << edge_index << " vertex_index: " << vertex_index;
throw std::out_of_range(ss.str());
}
if (vertex_index >= sample_indices_[edge_index].size()) {
std::stringstream ss;
ss << "when accessing sample index, trying to access VERTEX index out of range" << "\n" << "edge_index: " << edge_index << " vertex_index: " << vertex_index;
throw std::out_of_range(ss.str());
}
return sample_indices_[edge_index][vertex_index];
}
/**
\brief get the number of edges in the curve
\return the number of edges in the Decomposition
*/
unsigned int num_edges() const
{
return num_edges_;
}
/**
\brief get an edge of the curve. they are stored in the order in which they were computed.
\param index the index of the edge you want.
\return the ith edge
*/
Edge get_edge(unsigned int index) const
{
if (index>=num_edges_) {
throw std::out_of_range("trying to get Edge out of range");
}
return edges_[index];
}
/**
\brief Get the set of all Vertex indices to which this Decomposition refers.
This set is computed by reading all the edges.
\return a std::set of ALL the Vertex indices occuring in this Decomposition.
*/
std::set< int > all_edge_indices() const
{
std::set< int > index_set;
for (auto iter=edges_.begin(); iter!=edges_.end(); iter++) {
index_set.insert(iter->left());
index_set.insert(iter->midpt());
index_set.insert(iter->right());
}
return index_set;
}
/**
\brief Commit an edge to the curve.
Increments the edge counter, and pushes the edge to the pack of the vector of edges.
\return the index of the edge just added.
\param new_edge the edge to add.
*/
int add_edge(Edge new_edge)
{
num_edges_++;
edges_.push_back(new_edge);
return num_edges_-1; // -1 to correct for the fencepost problem
}
/**
\brief Read a Decomposition from text file.
This function takes in the name of a folder containing a Decomposition to set up, and parses the two folders "containing_folder/decomp" and "containing_folder/E.edge". Note that the VertexSet is set up separately from decompositions.
\return the number 1. Seems stupid.
\param containing_folder The name of the folder containing the Decomposition.
*/
int setup(boost::filesystem::path containing_folder);
/**
\brief open a folder as an edges file, and parse it into the vector of edges in this Decomposition.
\return the number of edges added
\param INfile the name of the file to open and read as an edge file.
*/
int setup_edges(boost::filesystem::path INfile);
/**
\brief Write all the edges in this Decomposition to a file.
the format is
[
num_edges
left mid right
]
\param outputfile The name of the file to write to.
*/
void print_edges(boost::filesystem::path outputfile) const;
/**
\brief print the complete curve Decomposition, including the base Decomposition class.
\param base The name of the base folder to print the Decomposition to.
*/
void print(boost::filesystem::path base) const;
/**
\brief Search this Decomposition for an nondegenerate edge with input point index as midpoint.
\param ind The index to search for.
\return The index of the found edge, or -10 if no edge had the point as midpoint.
*/
int nondegenerate_edge_w_midpt(int ind) const
{
for (unsigned int ii=0; ii<num_edges_; ii++){
if (this->edges_[ii].midpt() == ind){
if (edges_[ii].is_degenerate()) {
continue;
}
return ii;
}
}
return -10;
}
/**
\brief Search this Decomposition for an nondegenerate edge with input point index as left point.
\param ind The index to search for.
\return The index of the found edge, or -11 if no edge had the point as left point.
*/
int nondegenerate_edge_w_left(int ind) const
{
for (unsigned int ii=0; ii<num_edges_; ii++){
if (this->edges_[ii].left() == ind){
if (edges_[ii].is_degenerate()) {
continue;
}
return ii;
}
}
return -11;
}
/**
\brief Search this Decomposition for an nondegenerate edge with input point index as right point.
\param ind The index to search for.
\return The index of the found edge, or -12 if no edge had the point as right point.
*/
int nondegenerate_edge_w_right(int ind) const
{
for (unsigned int ii=0; ii<num_edges_; ii++){
if (this->edges_[ii].right() == ind){
if (edges_[ii].is_degenerate()) {
continue;
}
return ii;
}
}
return -12;
}
/**
\brief Search this Decomposition for any edge (degenerate or not) with input point index as mid point.
\param ind The index to search for.
\return The index of the found edge, or -10 if no edge had the point as mid point.
*/
int edge_w_midpt(int ind) const
{
for (unsigned int ii=0; ii<num_edges_; ii++){
if (this->edges_[ii].midpt() == ind){
return ii;
}
}
return -10;
}
/**
\brief Search this Decomposition for any edge (degenerate or not) with input point index as left point.
\param ind The index to search for.
\return The index of the found edge, or -11 if no edge had the point as left point.
*/
int edge_w_left(int ind) const
{
for (unsigned int ii=0; ii<num_edges_; ii++){
if (this->edges_[ii].left() == ind){
return ii;
}
}
return -11;
}
/**
\brief Search this Decomposition for any edge (degenerate or not) with input point index as right point.
\param ind The index to search for.
\return The index of the found edge, or -12 if no edge had the point as right point.
*/
int edge_w_right(int ind) const
{
for (unsigned int ii=0; ii<num_edges_; ii++){
if (this->edges_[ii].right() == ind){
return ii;
}
}
return -12;
}
/**
\brief Search this Decomposition for any edge (degenerate or not) with input point index as a removed point.
\param ind The index to search for.
\return The index of the found edge, or -13 if no edge had the point as a removed point.
*/
int edge_w_removed(int ind) const
{
for (unsigned int ii=0; ii<num_edges_; ii++){
for (auto iter=edges_[ii].removed_begin(); iter!=edges_[ii].removed_end(); ++iter) {
if (*iter == ind){
return ii;
}
}
}
return -13;
}
/**
\brief Find candidates for merging, by finding vertices with type NEW.
\return a vector of integers containing the indices of edges to merge together into a single new edge.
\param V The Vertex set to which the Decomposition refers.
*/
std::vector<int> get_merge_candidate(const VertexSet & V) const;
/**
\brief Merge method for curves, to remove edges with NEW type points.
\todo Make this function callable even outside the interslice method.
\param W_midpt Skeleton witness set coming from the precedin(containing) interslice call.
\param V the Vertex set to which this Decomposition refers.
\param pi_in The linear projection being used to decompose.
\param program_options The current state of Bertini_real
\param solve_options The current solver configuration.
*/
void merge(WitnessSet & W_midpt, VertexSet & V,
vec_mp * pi_in,
BertiniRealConfig & program_options,
SolverConfiguration & solve_options);
/**
\brief The main call for decomposing an indepentent curve.
Includes deflation, etc.
\param V The Vertex set which runs through everything.
\param W_curve The input witness set for the curve, computed probably by Bertini's tracktype:1.
\param pi A set of pointers to vec_mp's containing the projection being used.
\param program_options The current state of Bertini_real.
\param solve_options The current state of the solver routines.
*/
void main(VertexSet & V,
WitnessSet & W_curve,
vec_mp *pi,
BertiniRealConfig & program_options,
SolverConfiguration & solve_options);
/**
\brief the main function for computing the self-intersection of a non-self-conjugate dimension 1 component.
\param W the witness set
\param V the Vertex set being passed around. C indexes into here.
\param num_vars the total number of variables in the problem.
\param program_options main structure holding configuration
\param solve_options the current state of the solver.
*/
void computeCurveNotSelfConj(const WitnessSet & W,
VertexSet &V,
int num_vars,
BertiniRealConfig & program_options,
SolverConfiguration & solve_options);
/**
\brief the main function for computing cell decom for a curve. only for use on a self-conjugate component.
\param W WitnessSet containing linears, patches, points, etc. much info and calculation performed from this little guy.
\param pi the set of projections to use. in this case, there should be only 1.
\param V Vertex set structure into which to place collected data.
\param options program configuration.
\param solve_options solver configuration.
*/
void computeCurveSelfConj(const WitnessSet & W,
vec_mp *pi,
VertexSet &V,
BertiniRealConfig & options,
SolverConfiguration & solve_options);
/**
\brief The main method for slicing above critical points, halfway between them, and connecting the dots.
This method peforms three functions. It slices the curve halfway between the critical points, and tracks the midpoints-upstairs to the bounding critical values, added new points where necessary. It also calls merge if desired.
\return SUCCESSFUL
\param W_curve The main witness set for the curve.
\param W_crit_real Witness set containing the real critical points for the curve, previously computed.
\param pi The projection being used to decompose.
\param program_options The current state of Bertini_real
\param solve_options The current state of the solver.
\param V The Vertex set being used to contain the computed points.
*/
int interslice(const WitnessSet & W_curve,
const WitnessSet & W_crit_real,
vec_mp *pi,
BertiniRealConfig & program_options,
SolverConfiguration & solve_options,
VertexSet & V);
/**
\brief Compute actual critical points of the curve, by regeneration and the left-nullspace method.
\return SUCCESSFUL
\param W_curve Witness set for the curve, from which we will regenerate
\param pi the linear projection being used.
\param program_options The current state of Bertini_real
\param solve_options The current state of the solver.
\param W_crit_real The computed value, containing the real critical points of the curve.
*/
int compute_critical_points(const WitnessSet & W_curve,
vec_mp *pi,
BertiniRealConfig & program_options,
SolverConfiguration & solve_options,
WitnessSet & W_crit_real);
/**
\brief Compute the intersection of the curve with a sphere containing the supplied critical points.
Calling the sphere intersection solver, this method finds the points of intersection between the sphere and curve.
\return SUCCESSFUL flag.
\param W_crit_real The previously computed real critical points.
\param W supplied witness set for the curve.
\param program_options The current state of Bertini_real
\param solve_options The current state of the solver.
*/
int get_sphere_intersection_pts(WitnessSet *W_crit_real,
const WitnessSet & W,
BertiniRealConfig & program_options,
SolverConfiguration & solve_options);
/**
\brief send a curve to a single MPI target
\param target Who to send to.
\param mpi_config The state of MPI.
*/
void send(int target, ParallelismConfig & mpi_config) const;
/**
\brief receive a curve from a single MPI source
\param source Who to receive from.
\param mpi_config The state of MPI.
*/
void receive(int source, ParallelismConfig & mpi_config);
/**
\brief Initialize a curve for sampling by the adaptive method.
\see Curve::adaptive_sampler
\ingroup samplermethods
\return The number 0.
*/
int adaptive_set_initial_sample_data();
/**
\brief Sample a curve using adaptive method based on convergence of the distance between next estimated point, and next computed point.
\todo Add a better summary of the adaptive curve method.
\ingroup samplermethods
\param V the Vertex set containing the points of the Decomposition.
\param sampler_options The current state of the sampler program.
\param solve_options The current state of the solver and tracker configuration.
*/
void adaptive_sampler_movement(VertexSet &V,
sampler_configuration & sampler_options,
SolverConfiguration & solve_options);
/**
\brief Sample a curve using adaptive method based on distance between computed samples, and a maximum number of refinement passes.
\todo Add a better summary of the adaptive curve method.
\ingroup samplermethods
\param V the Vertex set containing the points of the Decomposition.
\param sampler_options The current state of the sampler program.
\param solve_options The current state of the solver and tracker configuration.
*/
void adaptive_sampler_distance(VertexSet &V,
sampler_configuration & sampler_options,
SolverConfiguration & solve_options);
/**
\brief sets up refinement flags to YES for every interval, for first pass of adaptive refinement.
\param num_refinements The number of intervals to refine.
\param refine_flags The mutable vector of bools indicating whether to refine a particular interval.
\param current_indices Indices of points between which to refine (or not).
\param V The Vertex set storing the points.
\param current_edge The index of which edge is being refined.
\param sampler_options The current state of the program.
*/
void adaptive_set_initial_refinement_flags(int & num_refinements,
std::vector<bool> & refine_flags,
std::vector<int> & current_indices,
VertexSet &V,
int current_edge, sampler_configuration & sampler_options);
/**
\brief Initialize for the fixed-number curve sampler method.
\param target_num_samples The number of samples per edge, including boundary points.
\return The number 0.
*/
int fixed_set_initial_sample_data(int target_num_samples);
/**
\brief Sample a curve so it has an equal number of points per edge, including boundary points.
\todo Add a description ofthe method with picture right here.
\param V the Vertex set containing the points computed.
\param sampler_options The current state of the sampler program.
\param solve_options The current state of the solver.
\param target_num_samples The number of points to get on each edge, including boundary points.
*/
void fixed_sampler(VertexSet &V,
sampler_configuration & sampler_options,
SolverConfiguration & solve_options,
int target_num_samples);
/**
\brief Dump the curve's sampler data to a file.
\param samplingName The name of the file to write.
*/
void output_sampling_data(boost::filesystem::path samplingName) const;
/**
\brief Reset the curve to an empty set.
*/
void reset()
{
Decomposition::reset();
this->clear();
this->init();
}
/**
constructor
*/
Curve() : Decomposition()
{
this->init();
}
/**
assignment operator
*/
Curve & operator=(const Curve& other){
this->init();
this->copy(other);
return *this;
}
/**
copy constructor
*/
Curve(const Curve & other){
this->init();
this->copy(other);
}
/**
destructor
*/
~Curve()
{
this->clear();
}
protected:
/**
clear the contents. not a complete reset.
*/
void clear()
{
edges_.clear();
num_edges_ = 0;
}
/**
get ready!
*/
void init(){
num_edges_ = 0;
set_dimension(1);
}
/**
copy the contents from one to the other.
*/
void copy(const Curve & other)
{
Decomposition::copy(other);
this->edges_ = other.edges_;
this->num_edges_ = other.num_edges_;
}
}; // end Curve
/**
writes the input file for the diagonal homotopy used in curve case to find the intersection points.
\param outputFile the name of the file to create
\param funcInputx the name of the first input file
\param funcInputy the name of the second input file
\param configInput the name of the config file to use
\param L the linears for the problem
\param num_vars the number of variables in the problem, including the homogeneous ones.
*/
void diag_homotopy_input_file(boost::filesystem::path outputFile,
boost::filesystem::path funcInputx,
boost::filesystem::path funcInputy,
boost::filesystem::path configInput,
vec_mp L,
int num_vars);
/**
writes the start file for the diagonal homotopy used in curve case to find the intersection points.
\param startFile the name of the start file to write
\param W the input witness set
*/
void diag_homotopy_start_file(boost::filesystem::path startFile,
const WitnessSet & W);
/**
\brief Check whether a projection is valid or not, by testing the rank of the jacobian at a random point.
\return a boolean integer indicating whether the projection is valid.
\param W witness set containing required information
\param projection The linear projection being checked.
\param solve_options The current state of the solver.
*/
int verify_projection_ok(const WitnessSet & W,
vec_mp * projection,
SolverConfiguration & solve_options);
/**
\brief Check whether a projection is valid or not, by testing the rank of the jacobian at a random point.
\return a boolean integer indicating whether the projection is valid.
\param W witness set containing required information
\param randomizer The way the system is randomized.
\param projection The linear projection being checked.
\param solve_options The current state of the solver.
*/
int verify_projection_ok(const WitnessSet & W,
std::shared_ptr<SystemRandomizer> randomizer,
vec_mp * projection,
SolverConfiguration & solve_options);
#endif
| true |
093b6921ee4c2da84692600cfca18d8efffe34b1 | C++ | TWANG006/G-LS3U | /AIA/aia_cpu.cpp | UTF-8 | 7,087 | 2.65625 | 3 | [
"MIT"
] | permissive | #include "aia_cpu.h"
#include <time.h>
#include <random>
#include <functional>
#include <omp.h>
#include <mkl.h>
namespace AIA{
AIA_CPU_Dn::~AIA_CPU_Dn()
{}
void AIA_CPU_Dn::operator()(// Outputs
std::vector<double>& v_phi,
std::vector<double>& v_deltas,
double &runningtime,
int &iIters,
double &dErr,
// Inputs
const std::vector<cv::Mat>& v_f,
int iMaxIterations,
double dMaxErr,
int iNumThreads)
{
omp_set_num_threads(iNumThreads);
/* If the number of frames != the number of initial deltas, randomly generate
deltas */
if (v_f.size() != v_deltas.size())
{
// Mimic the real randomness by varying the seed
std::default_random_engine generator;
generator.seed(time(nullptr));
// Random numbers picked from standard normal distribution g(0,1)
std::normal_distribution<double> distribution(0.0, 1.0);
v_deltas.clear();
v_deltas.push_back(0);
for (int i = 0; i < v_f.size() - 1; i++)
{
v_deltas.push_back(distribution(generator));
}
}
// Assign values for m_N & m_M
m_M = v_f.size();
m_N = v_f[0].cols * v_f[0].rows;
m_rows = v_f[0].rows;
m_cols = v_f[0].cols;
// Allocate space for m_v_b & m_v_phi
v_phi.resize(m_N);
std::vector<double> v_b_phi(m_N * 3, 0);
std::vector<double> v_b_delta(m_M * 3, 0);
std::vector<double> v_A(9, 0);
dErr = dMaxErr * 2.0;
iIters = 0;
std::vector<double> v_deltaOld = v_deltas;
double start = omp_get_wtime();
/* Begin the real algorithm */
while (dErr > dMaxErr && iIters < iMaxIterations)
{
v_deltaOld = v_deltas;
// Step 1: pixel-by-pixel iterations
computePhi(v_A, v_b_phi, v_phi, v_deltas, v_f);
// Step 2: frame-by-frame iterations
computeDelta(v_A, v_b_delta, v_deltas, v_phi, v_f);
// Step 3: update & check convergence criterion
iIters++;
dErr = computeMaxError(v_deltas, v_deltaOld);
}
double end = omp_get_wtime();
runningtime = 1000.0*(end - start);
/* One more round to calculate phi once delta is good enough */
computePhi(v_A, v_b_phi, v_phi, v_deltas, v_f);
#pragma omp parallel for
for (int i = 0; i < v_phi.size(); i++)
{
v_phi[i] += v_deltas[0];
v_phi[i] = atan2(sin(v_phi[i]), cos(v_phi[i]));
}
for (int i = v_deltas.size() - 1; i >= 0; i--)
{
v_deltas[i] -= v_deltas[0];
v_deltas[i] = atan2(sin(v_deltas[i]), cos(v_deltas[i]));
}
}
void AIA_CPU_Dn::computePhi(std::vector<double>& v_A,
std::vector<double>& v_b_phi,
std::vector<double>& v_phi,
const std::vector<double>& v_deltas,
const std::vector<cv::Mat>& v_f)
{
/* pixel-by-pixel iterations */
/* Construct m_v_A only once and use accross multiple RHS vectors m_v_b */
// Save the Cholesky factorized version of m_v_A
double dA3 = 0, dA4 = 0, dA6 = 0, dA7 = 0, dA8 = 0;
for (int i = 0; i < m_M; i++)
{
double cos_delta = cos(v_deltas[i]);
double sin_delta = sin(v_deltas[i]);
dA3 += cos_delta; dA4 += cos_delta*cos_delta;
dA6 += sin_delta; dA7 += cos_delta*sin_delta; dA8 += sin_delta*sin_delta;
}
v_A[0] = m_M; v_A[1] = 0; v_A[2] = 0;
v_A[3] = dA3; v_A[4] = dA4; v_A[5] = 0;
v_A[6] = dA6; v_A[7] = dA7; v_A[8] = dA8;
/* Construct the RHS's m_v_b[N-by-3] */
#pragma omp parallel for
for (int j = 0; j < m_N; j++)
{
int y = j / m_cols;
int x = j % m_cols;
double b0 = 0, b1 = 0, b2 = 0;
for (int i = 0; i < m_M; i++)
{
double dI = static_cast<double>(v_f[i].at<uchar>(y, x));
b0 += dI;
b1 += dI * cos(v_deltas[i]);
b2 += dI * sin(v_deltas[i]);
}
v_b_phi[j * 3 + 0] = b0;
v_b_phi[j * 3 + 1] = b1;
v_b_phi[j * 3 + 2] = b2;
}
/* Solve the Ax = b */
/*int infor = LAPACKE_dpotrf(LAPACK_COL_MAJOR, 'U', 3, m_v_A1.data(), 3);
if (infor > 0) {
std::cout << "The element of the PhiA diagonal factor " << std::endl;
std::cout << "D(" << infor << "," << infor << ") is zero, so that D is singular;\n" << std::endl;
std::cout << "the solution could not be computed.\n" << std::endl;
}
LAPACKE_dpotrs(LAPACK_COL_MAJOR, 'U', 3, m_N, m_v_A1.data(), 3, m_v_b_phi.data(), 3);*/
int info = LAPACKE_dposv(LAPACK_COL_MAJOR, 'U', 3, m_N, v_A.data(), 3, v_b_phi.data(), 3);
/* Check for the positive definiteness */
if (info > 0) {
printf("The leading minor of order %i is not positive ", info);
printf("definite;\nThe solution could not be computed.\n");
exit(1);
}
#pragma omp parallel for
for (int j = 0; j < m_N; j++)
{
v_phi[j] = atan2(-v_b_phi[j * 3 + 2], v_b_phi[j * 3 + 1]);
}
}
void AIA_CPU_Dn::computeDelta(std::vector<double>& v_A,
std::vector<double>& v_b_delta,
std::vector<double>& v_deltas,
const std::vector<double>& v_phi,
const std::vector<cv::Mat>& v_f)
{
/* Frame-by-frame iterations */
/* Construct m_v_A only once and use accross multiple RHS vectors m_v_b */
double dA3 = 0, dA4 = 0, dA6 = 0, dA7 = 0, dA8 = 0;
#pragma omp parallel for default(shared) reduction(+: dA3, dA4, dA6, dA7, dA8)
for (int j = 0; j < m_N; j++)
{
double cos_phi = cos(v_phi[j]);
double sin_phi = sin(v_phi[j]);
dA3 += cos_phi;
dA4 += cos_phi*cos_phi;
dA6 += sin_phi;
dA7 += cos_phi*sin_phi;
dA8 += sin_phi*sin_phi;
}
v_A[0] = m_N; v_A[1] = 0; v_A[2] = 0;
v_A[3] = dA3; v_A[4] = dA4; v_A[5] = 0;
v_A[6] = dA6; v_A[7] = dA7; v_A[8] = dA8;
/* Construct the RHS's m_v_b[M-by-3] */
for (int i = 0; i < m_M; i++)
{
double b0 = 0, b1 = 0, b2 = 0;
#pragma omp parallel for default(shared) reduction(+: b0, b1, b2)
for (int j = 0; j < m_N; j++)
{
int y = j / m_cols;
int x = j % m_cols;
double dI = static_cast<double>(v_f[i].at<uchar>(y, x));
double cos_phi = cos(v_phi[j]);
double sin_phi = sin(v_phi[j]);
b0 += dI;
b1 += dI * cos_phi;
b2 += dI * sin_phi;
}
v_b_delta[i * 3 + 0] = b0;
v_b_delta[i * 3 + 1] = b1;
v_b_delta[i * 3 + 2] = b2;
}
/* Solve the Ax = b */
/* Solve the Ax = b */
//int infor = LAPACKE_dpotrf(LAPACK_COL_MAJOR, 'U', 3, m_v_A2.data(), 3);
//if (infor > 0) {
// std::cout << "The element of the DeltaA diagonal factor " << std::endl;
// std::cout << "D(" << infor << "," << infor << ") is zero, so that D is singular;\n" << std::endl;
// std::cout << "the solution could not be computed.\n" << std::endl;
//}
//LAPACKE_dpotrs(LAPACK_COL_MAJOR, 'U', 3, m_M, m_v_A2.data(), 3, m_v_b_delta.data(), 3);
int info = LAPACKE_dposv(LAPACK_COL_MAJOR, 'U', 3, m_M, v_A.data(), 3, v_b_delta.data(), 3);
/* Check for the positive definiteness */
if (info > 0) {
printf("The leading minor of order %i is not positive ", info);
printf("definite;\nThe solution could not be computed.\n");
exit(1);
}
for (int i = 0; i < m_M; i++)
{
v_deltas[i] = atan2(-v_b_delta[i * 3 + 2], v_b_delta[i * 3 + 1]);
}
}
double AIA_CPU_Dn::computeMaxError(const std::vector<double> &v_delta,
const std::vector<double> &v_deltaOld)
{
std::vector<double> v_abs;
for (int i = 0; i < v_delta.size(); i++)
{
v_abs.push_back(abs(v_delta[i] - v_deltaOld[i]));
}
std::sort(v_abs.begin(), v_abs.end(), std::greater<double>());
return v_abs[0];
}
} // namespace AIA | true |
a08b3ef2ecf2b431ad4721ae39e66fcef2512853 | C++ | hankrof/jctvc_document_system_fetcher | /token.h | UTF-8 | 1,906 | 3 | 3 | [] | no_license | #ifndef HM_RESULT_TOKEN_H
#define HM_RESULT_TOKEN_H
#include <string>
#include <vector>
#include <memory>
#include <map>
#include <unordered_map>
class Token
{
public:
Token(const std::string &value);
virtual ~Token() = 0;
virtual const std::string& value() const final;
virtual std::string& value() final;
private:
std::string _value;
};
class TokenUndefined : public Token
{
public:
TokenUndefined();
};
class TokenWord : public Token
{
public:
TokenWord(const std::string &value);
};
class TokenNumber : public Token
{
public:
TokenNumber(const std::string &value);
};
class TokenLeftSquareBracket : public Token
{
public:
TokenLeftSquareBracket();
};
class TokenRightSquareBracket : public Token
{
public:
TokenRightSquareBracket();
};
class TokenLeftParenthese : public Token
{
public:
TokenLeftParenthese();
};
class TokenRightParenthese : public Token
{
public:
TokenRightParenthese();
};
class TokenColon : public Token
{
public:
TokenColon();
};
class TokenComma : public Token
{
public:
TokenComma();
};
class TokenDivision : public Token
{
public:
TokenDivision();
};
class TokenPlus : public Token
{
public:
TokenPlus();
};
class TokenMultiplication : public Token
{
public:
TokenMultiplication();
};
class TokenAssignment : public Token
{
public:
TokenAssignment();
};
class TokenDot : public Token
{
public:
TokenDot();
};
class TokenEOF : public Token
{
public:
TokenEOF();
};
typedef std::shared_ptr<Token> TokenPtr;
class TokenFactory
{
public:
TokenFactory();
TokenPtr createToken(int c, const std::string &value = std::string("")) const;
private:
void initAsciiTokenTable();
TokenFactory& operator=(const TokenFactory&);
mutable std::unordered_map<int, TokenPtr> _availableAsciiTokenTable;
};
#endif | true |
005697a23ff493dc970f4f3b83e78dacf702c5bc | C++ | DianeHemi/Modules_CPP | /cpp00/ex01/phoneBook.cpp | UTF-8 | 3,061 | 3.21875 | 3 | [] | no_license | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* phoneBook.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: dchampda <dchampda@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/03/18 15:15:08 by dchampda #+# #+# */
/* Updated: 2021/03/23 12:07:20 by dchampda ### ########.fr */
/* */
/* ************************************************************************** */
#include "ClassContact.hpp"
std::string ft_width(std::string data)
{
std::string str;
if (data.length() > 10)
{
data.resize(9);
str += data + ".|";
}
else
{
str.resize(10 - data.length(), ' ');
str += data + "|";
}
return str;
}
void ft_write_data(Contact entry)
{
std::string str;
std::string data;
data = entry.get_index();
str += ft_width(data);
data = entry.get_firstName();
str += ft_width(data);
data = entry.get_lastName();
str += ft_width(data);
data = entry.get_nickname();
str += ft_width(data);
std::cout << str << std::endl;
}
bool ft_isdigit(std::string choice)
{
int i;
i = 0;
while (choice[i])
{
if (!std::isdigit(choice[i]))
return false;
i++;
}
return true;
}
void ft_search_entry(Contact *entry)
{
int i;
std::string choice;
i = -1;
std::cout << " id|first name| last name| nickname|" << std::endl;
while (++i < 8)
{
if (!entry[i].get_firstName().empty())
ft_write_data(entry[i]);
else
break ;
}
if (i > 0)
{
std::cout << "\nType an id to get detailed data, or 'B' to go back : " << std::endl;
std::getline(std::cin, choice);
if (choice == "B")
return ;
else if (!choice.empty() && ft_isdigit(choice)
&& std::stoi(choice) <= i - 1)
entry[std::stoi(choice)].get_entry();
else
std::cout << "Invalid input" << std::endl;
}
else
std::cout << "\nYour phonebook is empty :(" << std::endl;
}
void ft_add_entry(Contact *entry, int *index)
{
if (*index < 8)
{
if (entry[*index].set_entry())
*index += 1;
else
std::cout << "Error : You need to fill this entry" << std::endl;
}
else
std::cout << "Error : Max number of entries reached" \
<< std::endl;
}
int main(void)
{
std::string command;
Contact entry[8];
int index;
index = 0;
std::cout << "Welcome to your awesome phonebook !" << std::endl;
while (1)
{
std::cout << \
"\033[94;1m\nEnter a command (ADD, SEARCH, EXIT)\033[0m" \
<< std::endl;
std::getline(std::cin, command);
if (command == "ADD")
ft_add_entry(entry, &index);
else if (command == "SEARCH")
ft_search_entry(entry);
else if (command == "EXIT")
return 0;
else
command = "";
}
return 0;
}
| true |
6126dbadcf2fc2c96bf87e88e25bcd83b123ea38 | C++ | breakstate/42_abstract_vm | /src/Parser.cpp | UTF-8 | 3,286 | 2.875 | 3 | [] | no_license | #include "../hdr/Parser.hpp"
Parser::Parser( void ) {
}
Parser::Parser( const Parser & srcObj ) {
this->operator=(srcObj);
}
Parser & Parser::operator=( Parser const & rhs ) {
this->_stackObject = rhs._stackObject;
this->_parseErrors = rhs._parseErrors;
return (*this);
}
Parser::~Parser( void ) {
}
void Parser::execute( std::vector<program> program) {
for (unsigned int i = 0; i < program.size(); i++){
if (program[i].lineContents[0].compare("push") == 0){
inputOverflow( interpretType(program[i].type), program[i].value);
this->_stackObject.push( this->interpretType(program[i].type), program[i].value );
}
else if (program[i].lineContents[0].compare("pop") == 0)
this->_stackObject.pop();
else if (program[i].lineContents[0].compare("dump") == 0)
this->_stackObject.dump();
else if (program[i].lineContents[0].compare("assert") == 0){
inputOverflow( interpretType(program[i].type), program[i].value);
this->_stackObject.assert( this->interpretType(program[i].type), program[i].value );
}
else if (program[i].lineContents[0].compare("add") == 0)
this->_stackObject.add();
else if (program[i].lineContents[0].compare("sub") == 0)
this->_stackObject.sub();
else if (program[i].lineContents[0].compare("mul") == 0)
this->_stackObject.mul();
else if (program[i].lineContents[0].compare("div") == 0)
this->_stackObject.div();
else if (program[i].lineContents[0].compare("mod") == 0)
this->_stackObject.mod();
else if (program[i].lineContents[0].compare("print") == 0)
this->_stackObject.print();
else if (program[i].lineContents[0].compare("exit") == 0)
return;
else if (program[i].lineContents[0].compare(";;") == 0){
;
}
}
throw AVMException("AVMException::exit: No exit instruction found");
}
void Parser::inputOverflow( eOperandType type, std::string value ) {
char* p;
long double result = strtold(value.c_str(), &p);
if ((*p))
throw AVMException("AVMXecption::Parser: failed to convert value");
switch (type){
case INT8:
if (result > std::numeric_limits<int8_t>::max() || result < std::numeric_limits<int8_t>::min())
throw AVMException("AVMException::INT8: over/underflow detected");
break;
case INT16:
if (result > std::numeric_limits<int16_t>::max() || result < std::numeric_limits<int16_t>::min())
throw AVMException("AVMException::INT16: over/underflow detected");
break;
case INT32:
if (result > std::numeric_limits<int32_t>::max() || result < std::numeric_limits<int32_t>::min())
throw AVMException("AVMException::INT32: over/underflow detected");
break;
case FLOAT:
if (result > std::numeric_limits<float_t>::max() || result < (-std::numeric_limits<float_t>::max()))
throw AVMException("AVMException::FLOAT: over/underflow detected parser"); // debug WHY IN THE HELL IS THIS THROWING?
break;
case DOUBLE:
if (result > std::numeric_limits<double_t>::max() || result < (-std::numeric_limits<double_t>::max()))
throw AVMException("AVMException::DOUBLE: over/underflow detected");
break;
}
}
eOperandType Parser::interpretType( std::string value ) {
if (value == "int8")
return INT8;
else if (value == "int16")
return INT16;
else if (value == "int32")
return INT32;
else if (value == "float")
return FLOAT;
else
return DOUBLE;
} | true |
3e803973429b56afda1a6b28ffcdf652d472611f | C++ | AlexanderJDupree/CS162 | /week7/library/library.cpp | UTF-8 | 2,556 | 3.390625 | 3 | [] | no_license | // Implementation for Library class
#include "library.h"
Library::Library() : bookIDs(0), videoIDs(0), musicIDs(0) {}
// Inspectors
const Book& Library::getBook(const size_t& ID)
{
if (ID > SIZE)
{
throw "Invalid ID";
}
return books[ID];
}
const Video& Library::getVideo(const size_t& ID)
{
if (ID > SIZE)
{
throw "Invalid ID";
}
return videos[ID];
}
const Music& Library::getMusic(const size_t& ID)
{
if (ID > SIZE)
{
throw "Invalid ID";
}
return albums[ID];
}
// Mutators
void Library::setBook(const std::string& title, const std::string& author,
const std::string& genre, const int& year, const size_t& ID)
{
if (ID < SIZE)
{
books[ID].setTitle(title)->setAuthor(author)->setGenre(genre)->setYear(year);
}
return;
}
void Library::setVideo(const std::string& title, const std::string& actor,
const std::string& genre, const int& year, const size_t& ID)
{
if (ID < SIZE)
{
videos[ID].setTitle(title)->setLeadActor(actor)->setGenre(genre)->setYear(year);
}
return;
}
void Library::setMusic(const std::string& title, const std::string& artist,
const int& numTracks, const size_t& ID)
{
if (ID < SIZE)
{
albums[ID].setTitle(title)->setArtist(artist)->setNumTracks(numTracks);
}
return;
}
// Member Functions
std::stringstream& Library::listBooks(std::stringstream* stream)
{
*stream << "TITLE\tAUTHOR\tYEAR\tGENRE\tID\n";
for (size_t i = 0; i < bookIDs; i++)
{
*stream << books[i].getTitle() << '\t' << books[i].getAuthor() << '\t'
<< books[i].getYear() << '\t' << books[i].getGenre() << '\t'
<< i << std::endl;
}
return *stream;
}
std::stringstream& Library::listVideos(std::stringstream* stream)
{
*stream << "TITLE\tLEAD ACTOR\tYEAR\tGENRE\tID\n";
for (size_t i = 0; i < videoIDs; i++)
{
*stream << videos[i].getTitle() << '\t' << videos[i].getLeadActor()
<< '\t' << videos[i].getYear() << '\t' << videos[i].getGenre()
<< '\t' << i << std::endl;
}
return *stream;
}
std::stringstream& Library::listMusic(std::stringstream* stream)
{
*stream << "TITLE\tARTIST\tTRACKS\tID\n";
for (size_t i = 0; i < musicIDs; i++)
{
*stream << albums[i].getTitle() << '\t' << albums[i].getArtist()
<< '\t' << albums[i].getNumTracks() << '\t' << i << std::endl;
}
return *stream;
} | true |
e1105c1ee423551f271da9a406a5d1c3dee184f1 | C++ | snacchus/DeferredRenderer | /src/content/pooled.hpp | UTF-8 | 2,589 | 3.171875 | 3 | [] | no_license | #ifndef CONTENT_POOLED_HPP
#define CONTENT_POOLED_HPP
#include "Content.hpp"
#include "core/ObjectRegistry.hpp"
namespace content
{
namespace detail
{
template<typename T>
T* find_int(const object_type& type, const std::string& name)
{
return instance<ObjectRegistry>()->findTNFirst<T>(name);
}
template<>
inline NamedObject* find_int<NamedObject>(const object_type& type, const std::string& name)
{
return instance<ObjectRegistry>()->findTNFirst(type.id, name);
}
}
NamedObject* get_pooled(const object_type& type, const std::string& name);
inline NamedObject* get_pooled(std::type_index tid, const std::string& name)
{
return get_pooled(type_registry::findById(tid), name);
}
inline NamedObject* get_pooled(const std::string& typeName, const std::string& name)
{
return get_pooled(type_registry::findByName(typeName), name);
}
template<typename T>
T* get_pooled(const std::string& name)
{
T* obj = instance<ObjectRegistry>()->findTNFirst<T>(name);
if (!obj) {
auto ptr = instance<Content>()->getFromDisk<T>(name);
if (ptr) {
return instance<ObjectRegistry>()->add(std::move(ptr));
}
}
return obj;
}
namespace detail
{
template<typename T>
T* get_pooled_int(const object_type& type, const std::string& name)
{
return get_pooled<T>(name);
}
template<>
inline NamedObject* get_pooled_int<NamedObject>(const object_type& type, const std::string& name)
{
return get_pooled(type, name);
}
template<typename T>
T* get_pooled_json_int(const object_type& type, const nlohmann::json& json)
{
if (json.is_string()) {
return get_pooled_int<T>(type, json);
} else if (json.is_object()) {
std::string name = instance<Content>()->getObjectName(json);
T* obj = find_int<T>(type, name);
if (obj) return obj;
auto ptr = json_to_object<T>(type, json);
if (ptr) {
ptr->setName(name);
return instance<ObjectRegistry>()->add(std::move(ptr));
}
}
return nullptr;
}
}
template<typename T>
T* get_pooled_json(const nlohmann::json& json)
{
return detail::get_pooled_json_int<T>(type_registry::get<T>(), json);
}
NamedObject* get_pooled_json(const object_type& type, const nlohmann::json& json);
inline NamedObject* get_pooled_json(std::type_index tid, const nlohmann::json& json)
{
return get_pooled_json(type_registry::findById(tid), json);
}
inline NamedObject* get_pooled_json(const std::string& typeName, const nlohmann::json& json)
{
return get_pooled_json(type_registry::findByName(typeName), json);
}
}
#endif // CONTENT_POOLED_HPP | true |
1b6230093a75173151991a2520390888a26313a8 | C++ | marco-gallegos/cpp-codeblocks | /programacion/medallero/main.cpp | UTF-8 | 1,917 | 3.609375 | 4 | [] | no_license | #include <iostream>
using namespace std;
int V_ORO=50;
int V_PLATA=30;
int V_BRONCE=25;
class medallero
{
public:
int oro,plata,bronce,puntaje,sum;
string pais;
void sum_med()
{
sum=oro+plata+bronce;
cout<<pais<<" tiene "<<sum<<" medallas"<<endl;
}
void prom()
{
int prom=(oro+plata+bronce)/2;
cout<<pais<<" tiene en promedio "<<prom<<" medallas"<<endl;
}
medallero(int oro,int plata,int bronce,string pais)
{
this->oro=oro;
this->plata=plata;
this->bronce=bronce;
this->pais=pais;
puntaje=(oro*V_ORO)+(plata*V_PLATA)+(bronce*V_BRONCE);
}
void ver_puntaje()
{
cout<<pais<<" tiene un puntaje de "<<puntaje<<endl;
}
};
void pr_p_tipo(medallero a,medallero b,medallero c,medallero d)
{
cout<<"se han entregado en promedio "<<(a.bronce+b.bronce+c.bronce+d.bronce)/4<<" medallas de bronce"<<endl;
cout<<"se han entregado en promedio "<<(a.plata+b.plata+c.plata+d.plata)/4<<" medallas de plata"<<endl;
cout<<"se han entregado en promedio "<<(a.oro+b.oro+c.oro+d.oro)/4<<" medallas de oro"<<endl;
}
void med_entr(medallero a,medallero b,medallero c,medallero d)
{
cout<<"se han entregado "<<a.sum+b.sum+c.sum+d.sum<<" medallas"<<endl;
}
int main()
{
medallero eu(45,45,20,"estados unidos");
medallero alem(30,55,30,"alemania");
medallero cuba(20,30,70,"cuba");
medallero mex(28,50,40,"mexico");
eu.sum_med();
alem.sum_med();
cuba.sum_med();
mex.sum_med();
cout<<"-----------------"<<endl;
eu.prom();
alem.prom();
cuba.prom();
mex.prom();
cout<<"-----------------"<<endl;
eu.ver_puntaje();
alem.ver_puntaje();
cuba.ver_puntaje();
mex.ver_puntaje();
cout<<"-----------------"<<endl;
med_entr(eu,alem,cuba,mex);
cout<<"-----------------"<<endl;
pr_p_tipo(eu,alem,cuba,mex);
}
| true |
6e55a36e5d82eda559186f41c2d5689948216149 | C++ | luzhen-linux/test | /133.clone-graph.cpp | UTF-8 | 2,768 | 3.609375 | 4 | [] | no_license | /*
* [133] Clone Graph
*
* https://leetcode.com/problems/clone-graph/description/
*
* algorithms
* Medium (25.18%)
* Total Accepted: 145.1K
* Total Submissions: 576.3K
* Testcase Example: '{}'
*
*
* Clone an undirected graph. Each node in the graph contains a label and a
* list of its neighbors.
*
*
*
*
* OJ's undirected graph serialization:
*
*
* Nodes are labeled uniquely.
*
*
* We use # as a separator for each node, and , as a separator for node label
* and each neighbor of the node.
*
*
*
*
* As an example, consider the serialized graph {0,1,2#1,2#2,2}.
*
*
*
* The graph has a total of three nodes, and therefore contains three parts as
* separated by #.
*
* First node is labeled as 0. Connect node 0 to both nodes 1 and 2.
* Second node is labeled as 1. Connect node 1 to node 2.
* Third node is labeled as 2. Connect node 2 to node 2 (itself), thus forming
* a self-cycle.
*
*
*
*
* Visually, the graph looks like the following:
*
* 1
* / \
* / \
* 0 --- 2
* / \
* \_/
*
*
*
*
*/
/**
* Definition for undirected graph.
* struct UndirectedGraphNode {
* int label;
* vector<UndirectedGraphNode *> neighbors;
* UndirectedGraphNode(int x) : label(x) {};
* };
*/
#ifdef TEST
#include <unordered_map>
#include <map>
#include <algorithm>
#include <iostream>
using namespace std;
struct UndirectedGraphNode {
int label;
vector<UndirectedGraphNode *> neighbors;
UndirectedGraphNode(int x) : label(x) {};
};
#endif
class Solution {
public:
static UndirectedGraphNode *cloneGraph(UndirectedGraphNode *src,
map<UndirectedGraphNode*, UndirectedGraphNode*> &map) {
if (!src)
return NULL;
if (!(map.find(src)==map.end()))
return map[src];
UndirectedGraphNode* dest = new UndirectedGraphNode(src->label);
if (!dest)
return NULL;
map[src] = dest;
for (auto n: src->neighbors) {
UndirectedGraphNode* neighbor = cloneGraph(n, map);
if (neighbor)
dest->neighbors.push_back(neighbor);
}
return dest;
}
static UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
map<UndirectedGraphNode*, UndirectedGraphNode*> map;
return cloneGraph(node, map);
}
};
#ifdef TEST
void pr_node(UndirectedGraphNode *node)
{
if (!node) return;
cout << node->label << endl;
for (auto n: node->neighbors) {
if (n!=node)
pr_node(n);
}
}
int main()
{
vector<UndirectedGraphNode> node{0,1,2};
node[0].neighbors.push_back(&node[1]);
node[0].neighbors.push_back(&node[2]);
node[1].neighbors.push_back(&node[2]);
node[2].neighbors.push_back(&node[2]);
UndirectedGraphNode *ret = Solution::cloneGraph(&node[0]);
pr_node(ret);
return 0;
}
#endif
| true |
40486c730c812faf9f19dedaa7be4faaf18fbbce | C++ | mrzv/henson | /include/chaiscript/dispatchkit/operators.hpp | UTF-8 | 13,093 | 2.765625 | 3 | [
"BSD-3-Clause-LBNL"
] | permissive | // This file is distributed under the BSD License.
// See "license.txt" for details.
// Copyright 2009-2012, Jonathan Turner (jonathan@emptycrate.com)
// Copyright 2009-2016, Jason Turner (jason@emptycrate.com)
// http://www.chaiscript.com
#ifndef CHAISCRIPT_OPERATORS_HPP_
#define CHAISCRIPT_OPERATORS_HPP_
#include "../chaiscript_defines.hpp"
#include "register_function.hpp"
namespace chaiscript
{
namespace bootstrap
{
namespace operators
{
namespace detail
{
/// \todo make this return a decltype once we drop gcc 4.6
template<typename L, typename R>
auto assign(L l, R r) -> L&
{
return (l = r);
}
template<typename L, typename R>
auto assign_bitwise_and(L l, R r) -> decltype((l &= r))
{
return (l &= r);
}
template<typename L, typename R>
auto assign_xor(L l, R r) -> decltype((l^=r))
{
return (l ^= r);
}
template<typename L, typename R>
auto assign_bitwise_or(L l, R r) -> decltype((l |= r))
{
return (l |= r);
}
template<typename L, typename R>
auto assign_difference(L l, R r) -> decltype(( l -= r))
{
return (l -= r);
}
template<typename L, typename R>
auto assign_left_shift(L l, R r) -> decltype(( l <<= r))
{
return (l <<= r);
}
template<typename L, typename R>
auto assign_product(L l, R r) -> decltype(( l *= r ))
{
return (l *= r);
}
template<typename L, typename R>
auto assign_quotient(L l, R r) -> decltype(( l /= r ))
{
return (l /= r);
}
template<typename L, typename R>
auto assign_remainder(L l, R r) -> decltype(( l %= r ))
{
return (l %= r);
}
template<typename L, typename R>
auto assign_right_shift(L l, R r) -> decltype(( l >>= r))
{
return (l >>= r);
}
/// \todo make this return a decltype once we drop gcc 4.6
template<typename L, typename R>
auto assign_sum(L l, R r) -> L&
{
return (l += r);
}
template<typename L>
auto prefix_decrement(L l) -> decltype(( --l ))
{
return (--l);
}
template<typename L>
auto prefix_increment(L l) -> decltype(( ++l ))
{
return (++l);
}
template<typename L, typename R>
auto equal(L l, R r) -> decltype(( l == r ))
{
return (l == r);
}
template<typename L, typename R>
auto greater_than(L l, R r) -> decltype(( l > r ))
{
return (l > r);
}
template<typename L, typename R>
auto greater_than_equal(L l, R r) -> decltype(( l >= r ))
{
return (l >= r);
}
template<typename L, typename R>
auto less_than(L l, R r) -> decltype(( l < r ))
{
return (l < r);
}
template<typename L, typename R>
auto less_than_equal(L l, R r) -> decltype(( l <= r ))
{
return (l <= r);
}
template<typename L>
auto logical_compliment(L l) -> decltype(( !l ))
{
return (!l);
}
template<typename L, typename R>
auto not_equal(L l, R r) -> decltype(( l != r ))
{
return (l != r);
}
template<typename L, typename R>
auto addition(L l, R r) -> decltype(( l + r ))
{
return (l + r);
}
template<typename L>
auto unary_plus(L l) -> decltype(( +l ))
{
return (+l);
}
template<typename L, typename R>
auto subtraction(L l, R r) -> decltype(( l - r ))
{
return (l - r);
}
template<typename L>
auto unary_minus(L l) -> decltype(( -l ))
{
#ifdef CHAISCRIPT_MSVC
#pragma warning(push)
#pragma warning(disable : 4146)
return (-l);
#pragma warning(pop)
#else
return (-l);
#endif
}
template<typename L, typename R>
auto bitwise_and(L l, R r) -> decltype(( l & r ))
{
return (l & r);
}
template<typename L>
auto bitwise_compliment(L l) -> decltype(( ~l ))
{
return (~l);
}
template<typename L, typename R>
auto bitwise_xor(L l, R r) -> decltype(( l ^ r ))
{
return (l ^ r);
}
template<typename L, typename R>
auto bitwise_or(L l, R r) -> decltype(( l | r ))
{
return (l | r);
}
template<typename L, typename R>
auto division(L l, R r) -> decltype(( l / r ))
{
return (l / r);
}
template<typename L, typename R>
auto left_shift(L l, R r) -> decltype(( l << r ))
{
return l << r;
}
template<typename L, typename R>
auto multiplication(L l, R r) -> decltype(( l * r ))
{
return l * r;
}
template<typename L, typename R>
auto remainder(L l, R r) -> decltype(( l % r ))
{
return (l % r);
}
template<typename L, typename R>
auto right_shift(L l, R r) -> decltype(( l >> r ))
{
return (l >> r);
}
}
template<typename T>
ModulePtr assign(ModulePtr m = std::make_shared<Module>())
{
m->add(chaiscript::fun(&detail::assign<T &, const T&>), "=");
return m;
}
template<typename T>
ModulePtr assign_bitwise_and(ModulePtr m = std::make_shared<Module>())
{
m->add(chaiscript::fun(&detail::assign_bitwise_and<T &, const T&>), "&=");
return m;
}
template<typename T>
ModulePtr assign_xor(ModulePtr m = std::make_shared<Module>())
{
m->add(chaiscript::fun(&detail::assign_xor<T &, const T&>), "^=");
return m;
}
template<typename T>
ModulePtr assign_bitwise_or(ModulePtr m = std::make_shared<Module>())
{
m->add(chaiscript::fun(&detail::assign_bitwise_or<T &, const T&>), "|=");
return m;
}
template<typename T>
ModulePtr assign_difference(ModulePtr m = std::make_shared<Module>())
{
m->add(chaiscript::fun(&detail::assign_difference<T &, const T&>), "-=");
return m;
}
template<typename T>
ModulePtr assign_left_shift(ModulePtr m = std::make_shared<Module>())
{
m->add(chaiscript::fun(&detail::assign_left_shift<T &, const T&>), "<<=");
return m;
}
template<typename T>
ModulePtr assign_product(ModulePtr m = std::make_shared<Module>())
{
m->add(chaiscript::fun(&detail::assign_product<T &, const T&>), "*=");
return m;
}
template<typename T>
ModulePtr assign_quotient(ModulePtr m = std::make_shared<Module>())
{
m->add(chaiscript::fun(&detail::assign_quotient<T &, const T&>), "/=");
return m;
}
template<typename T>
ModulePtr assign_remainder(ModulePtr m = std::make_shared<Module>())
{
m->add(chaiscript::fun(&detail::assign_remainder<T &, const T&>), "%=");
return m;
}
template<typename T>
ModulePtr assign_right_shift(ModulePtr m = std::make_shared<Module>())
{
m->add(chaiscript::fun(&detail::assign_right_shift<T &, const T&>), ">>=");
return m;
}
template<typename T>
ModulePtr assign_sum(ModulePtr m = std::make_shared<Module>())
{
m->add(chaiscript::fun(&detail::assign_sum<T &, const T&>), "+=");
return m;
}
template<typename T>
ModulePtr prefix_decrement(ModulePtr m = std::make_shared<Module>())
{
m->add(chaiscript::fun(&detail::prefix_decrement<T &>), "--");
return m;
}
template<typename T>
ModulePtr prefix_increment(ModulePtr m = std::make_shared<Module>())
{
m->add(chaiscript::fun(&detail::prefix_increment<T &>), "++");
return m;
}
template<typename T>
ModulePtr equal(ModulePtr m = std::make_shared<Module>())
{
m->add(chaiscript::fun(&detail::equal<const T&, const T&>), "==");
return m;
}
template<typename T>
ModulePtr greater_than(ModulePtr m = std::make_shared<Module>())
{
m->add(chaiscript::fun(&detail::greater_than<const T&, const T&>), ">");
return m;
}
template<typename T>
ModulePtr greater_than_equal(ModulePtr m = std::make_shared<Module>())
{
m->add(chaiscript::fun(&detail::greater_than_equal<const T&, const T&>), ">=");
return m;
}
template<typename T>
ModulePtr less_than(ModulePtr m = std::make_shared<Module>())
{
m->add(chaiscript::fun(&detail::less_than<const T&, const T&>), "<");
return m;
}
template<typename T>
ModulePtr less_than_equal(ModulePtr m = std::make_shared<Module>())
{
m->add(chaiscript::fun(&detail::less_than_equal<const T&, const T&>), "<=");
return m;
}
template<typename T>
ModulePtr logical_compliment(ModulePtr m = std::make_shared<Module>())
{
m->add(chaiscript::fun(&detail::logical_compliment<const T &>), "!");
return m;
}
template<typename T>
ModulePtr not_equal(ModulePtr m = std::make_shared<Module>())
{
m->add(chaiscript::fun(&detail::not_equal<const T &, const T &>), "!=");
return m;
}
template<typename T>
ModulePtr addition(ModulePtr m = std::make_shared<Module>())
{
m->add(chaiscript::fun(&detail::addition<const T &, const T &>), "+");
return m;
}
template<typename T>
ModulePtr unary_plus(ModulePtr m = std::make_shared<Module>())
{
m->add(chaiscript::fun(&detail::unary_plus<const T &>), "+");
return m;
}
template<typename T>
ModulePtr subtraction(ModulePtr m = std::make_shared<Module>())
{
m->add(chaiscript::fun(&detail::subtraction<const T &, const T &>), "-");
return m;
}
template<typename T>
ModulePtr unary_minus(ModulePtr m = std::make_shared<Module>())
{
m->add(chaiscript::fun(&detail::unary_minus<const T &>), "-");
return m;
}
template<typename T>
ModulePtr bitwise_and(ModulePtr m = std::make_shared<Module>())
{
m->add(chaiscript::fun(&detail::bitwise_and<const T &, const T &>), "&");
return m;
}
template<typename T>
ModulePtr bitwise_compliment(ModulePtr m = std::make_shared<Module>())
{
m->add(chaiscript::fun(&detail::bitwise_compliment<const T &>), "~");
return m;
}
template<typename T>
ModulePtr bitwise_xor(ModulePtr m = std::make_shared<Module>())
{
m->add(chaiscript::fun(&detail::bitwise_xor<const T &, const T &>), "^");
return m;
}
template<typename T>
ModulePtr bitwise_or(ModulePtr m = std::make_shared<Module>())
{
m->add(chaiscript::fun(&detail::bitwise_or<const T &, const T &>), "|");
return m;
}
template<typename T>
ModulePtr division(ModulePtr m = std::make_shared<Module>())
{
m->add(chaiscript::fun(&detail::division<const T &, const T &>), "/");
return m;
}
template<typename T>
ModulePtr left_shift(ModulePtr m = std::make_shared<Module>())
{
m->add(chaiscript::fun(&detail::left_shift<const T &, const T &>), "<<");
return m;
}
template<typename T>
ModulePtr multiplication(ModulePtr m = std::make_shared<Module>())
{
m->add(chaiscript::fun(&detail::multiplication<const T &, const T &>), "*");
return m;
}
template<typename T>
ModulePtr remainder(ModulePtr m = std::make_shared<Module>())
{
m->add(chaiscript::fun(&detail::remainder<const T &, const T &>), "%");
return m;
}
template<typename T>
ModulePtr right_shift(ModulePtr m = std::make_shared<Module>())
{
m->add(chaiscript::fun(&detail::right_shift<const T &, const T &>), ">>");
return m;
}
}
}
}
#endif
| true |
4cc4a9ea564156ca37c48ce47e6819af1df87b68 | C++ | clauswitt/CppComponentSystem | /CppComponentSystem/Core/Shader.cpp | UTF-8 | 4,333 | 2.640625 | 3 | [
"MIT"
] | permissive | //
// HS_Shader.cpp
// HitSoccer
//
// Created by Sid on 16/07/14.
// Copyright (c) 2014 whackylabs. All rights reserved.
//
#include "Shader.h"
#include <cassert>
#include <iostream>
static bool CompileShader(GLuint *shader, GLenum type, const File &file)
{
GLint status;
std::string sourceStr = file.GetContents();
// std::cout << sourceStr << std::endl;
assert(sourceStr.size()); //Failed to load vertex shader
const GLchar *source = (GLchar *)sourceStr.c_str();
*shader = glCreateShader(type);
glShaderSource(*shader, 1, &source, NULL);
glCompileShader(*shader);
#if defined(DEBUG)
GLint logLength;
glGetShaderiv(*shader, GL_INFO_LOG_LENGTH, &logLength);
if (logLength > 0) {
GLchar *log = (GLchar *)malloc(logLength);
glGetShaderInfoLog(*shader, logLength, &logLength, log);
std::cout << "Shader compile log:\n" << log << std::endl;
free(log);
}
#endif
glGetShaderiv(*shader, GL_COMPILE_STATUS, &status);
if (status == 0) {
glDeleteShader(*shader);
return false;
}
return true;
}
static bool LinkProgram(GLuint prog)
{
GLint status;
glLinkProgram(prog);
#if defined(DEBUG)
GLint logLength;
glGetProgramiv(prog, GL_INFO_LOG_LENGTH, &logLength);
if (logLength > 0) {
GLchar *log = (GLchar *)malloc(logLength);
glGetProgramInfoLog(prog, logLength, &logLength, log);
std::cout << "Program link log:\n" << log << std::endl;
free(log);
}
#endif
glGetProgramiv(prog, GL_LINK_STATUS, &status);
if (status == 0) {
return false;
}
return true;
}
__unused static bool ValidateProgram(GLuint prog)
{
GLint logLength, status;
glValidateProgram(prog);
glGetProgramiv(prog, GL_INFO_LOG_LENGTH, &logLength);
if (logLength > 0) {
GLchar *log = (GLchar *)malloc(logLength);
glGetProgramInfoLog(prog, logLength, &logLength, log);
std::cout << "Program validate log:\n" << log << std::endl;
free(log);
}
glGetProgramiv(prog, GL_VALIDATE_STATUS, &status);
if (status == 0) {
return false;
}
return true;
}
Shader::Shader() :
program_(0)
{}
Shader::~Shader()
{
if (program_) {
glDeleteProgram(program_);
program_ = 0;
}
}
bool Shader::Load(const File &vshFile, const File &fshFile,
std::function<void(GLuint)> bindAttribCompletion,
std::function<void(GLuint)> bindUniformCompletion)
{
GLuint vertShader, fragShader;
// Create shader program.
program_ = glCreateProgram();
// Create and compile vertex shader.
bool status = CompileShader(&vertShader, GL_VERTEX_SHADER, vshFile);
if (!status) {
std::cout << "Failed to compile vertex shader" << std::endl;
return false;
}
// Create and compile fragment shader.
status = CompileShader(&fragShader, GL_FRAGMENT_SHADER, fshFile);
if (!status) {
std::cout << "Failed to compile fragment shader" << std::endl;
return false;
}
// Attach vertex shader to program.
glAttachShader(program_, vertShader);
// Attach fragment shader to program.
glAttachShader(program_, fragShader);
// Bind attribute locations.
// This needs to be done prior to linking.
bindAttribCompletion(program_);
// Link program.
status = LinkProgram(program_);
if (!status) {
std::cout << "Failed to link program: " << program_ << std::endl;
if (vertShader) {
glDeleteShader(vertShader);
vertShader = 0;
}
if (fragShader) {
glDeleteShader(fragShader);
fragShader = 0;
}
if (program_) {
glDeleteProgram(program_);
program_ = 0;
}
return false;
}
bindUniformCompletion(program_);
// Release vertex and fragment shaders.
if (vertShader) {
glDetachShader(program_, vertShader);
glDeleteShader(vertShader);
}
if (fragShader) {
glDetachShader(program_, fragShader);
glDeleteShader(fragShader);
}
return true;
}
void Shader::Enable() const
{
glUseProgram(program_);
}
| true |
705436f2fd83690e36bf58d8003b4ea9bc6b054c | C++ | xtl-murphy/Stitches2 | /Src/Utils/Ref.hpp | UTF-8 | 2,138 | 2.8125 | 3 | [] | no_license |
/**
* Ref
* @version 1.0
* @since 1.0
* <p>
* Created by Murphy at 2020/8/9 2:05
**/
#pragma once
#include "Stitches.hpp"
NS_STITCHES_BEGIN
#define SAFE_DELETE(p) do { delete (p); (p) = nullptr; } while(0)
#define SAFE_DELETE_ARRAY(p) do { if(p) { delete[] (p); (p) = nullptr; } } while(0)
#define SAFE_FREE(p) do { if(p) { free(p); (p) = nullptr; } } while(0)
#define SAFE_RELEASE(p) do { if(p) { (p)->release(); } } while(0)
#define SAFE_RELEASE_NULL(p) do { if(p) { (p)->release(); (p) = nullptr; } } while(0)
#define SAFE_RETAIN(p) do { if(p) { (p)->retain(); } } while(0)
#define BREAK_IF(cond) if(cond) break
class Ref
{
public:
/**
* Retains the ownership.
*
* This increases the Ref's reference count.
*
* @see release, autorelease
* @js NA
*/
void retain();
/**
* Releases the ownership immediately.
*
* This decrements the Ref's reference count.
*
* If the reference count reaches 0 after the decrement, this Ref is
* destructed.
*
* @see retain, autorelease
* @js NA
*/
void release();
/**
* Releases the ownership sometime soon automatically.
*
* This decrements the Ref's reference count at the end of current
* autorelease pool block.
*
* If the reference count reaches 0 after the decrement, this Ref is
* destructed.
*
* @returns The Ref itself.
*
* @see AutoreleasePool, retain, release
* @js NA
* @lua NA
*/
Ref* autorelease();
/**
* Returns the Ref's current reference count.
*
* @returns The Ref's reference count.
* @js NA
*/
unsigned int getReferenceCount() const;
protected:
/**
* Constructor
*
* The Ref's reference count is 1 after construction.
* @js NA
*/
Ref();
public:
/**
* Destructor
*
* @js NA
* @lua NA
*/
virtual ~Ref();
protected:
/// count of references
unsigned int _referenceCount;
friend class AutoreleasePool;
};
NS_STITCHES_END
| true |
e6864579d2be279d93fefaa6e91ae8a61ac11edb | C++ | 1468362286/Algorithm | /CodeForces/912D/14290347_AC_140ms_13876kB.cpp | UTF-8 | 1,479 | 2.734375 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <algorithm>
#include <map>
#include <queue>
#include <utility>
using namespace std;
inline double max(double a,double b){return a>b?a:b;}
inline double min(double a,double b){return a>b?b:a;}
const int dx[]={1,0,-1,0};
const int dy[]={0,1,0,-1};
struct node
{
int x,y;
double z;
friend bool operator<(const node &a,const node &b)
{
return a.z<b.z;
}
node(int x,int y,double z):x(x),y(y),z(z){}
node(){};
};
int n,m,r,k;
double ans=0;
priority_queue<node> q;
map<pair<int,int>,int > mp;
inline bool check(int x,int y)
{
return x>=1&&x<=n&&y>=1&&y<=m&&mp.count(make_pair(x,y))==0;
}
inline double solve(int x,int y)
{
/*
double x1=min(1.00*x,n-x+1.00);
x1=min(x1,n-1.00*r+1);
x1=min(x1,1.00*r);
double y1=min(1.00*y,m-y+1.00);
y1=min(y1,m-1.00*r+1);
y1=min(y1,1.00*r);
*/
double x1=min(n+1.0,x+r*1.0)-max(x*1.0,r*1.0);
double y1=min(m+1.0,y+r*1.0)-max(y*1.0,r*1.0);
return x1*y1/1.00/(n-r+1)/(m-r+1);
}
int main()
{
//freopen("in.txt","r",stdin);
while(cin>>n>>m>>r>>k)
{
while(!q.empty()) q.pop();
mp.clear();
q.push(node(r,r,solve(r,r)));
mp[make_pair(r,r)]=1;
while(k--)
{
node now = q.top();
int x=now.x,y=now.y;
double z=now.z;
ans+=z;
q.pop();
for(int i = 0 ; i < 4 ; i++)
{
int nx=x+dx[i];
int ny=y+dy[i];
if(check(nx,ny))
{
mp[make_pair(nx,ny)]=1;
q.push(node(nx,ny,solve(nx,ny)));
}
}
}
printf("%.12lf\n",ans);
}
return 0;
} | true |
33b91e52838fd0b7aff51ddbb6da065f514eef6f | C++ | crequierme/ParticleSystem | /Model.cpp | UTF-8 | 4,379 | 2.59375 | 3 | [] | no_license | //********************************************************************************
/*
Model.cpp
CPSC 8170 Physically Based Animation
Donald H. House 8/23/2018
Modified by Caroline Requierme (crequie@clemson.edu), 9/22/2018
Implementation for Particle System Simulation
*/
//********************************************************************************
#include "Model.h"
#include "Vector.h"
#include "Particle.h"
#include "ParticleList.h"
#include "ParticleGenerator.h"
#include <cstdlib>
#include <cstdio>
#include <cmath>
using namespace std;
//-----------------------------------------------------------------
/*
Model::Model()
* PURPOSE : Default constructor
* INPUTS : None
* OUTPUTS : None, initiates the simulation
*/
//-----------------------------------------------------------------
Model::Model(){
initSimulation();
}
//-----------------------------------------------------------------
/*
Model::initSimulation()
* PURPOSE : Initiate the particle system and simulation properties
* INPUTS : NONE, uses class variables
* OUTPUTS : NONE, defines class variables
*/
//-----------------------------------------------------------------
void Model::initSimulation(){
h = 0.01; // simulation timestep
dispinterval = 1; // display interval
drag = 0.2;
//***** DEFINE PARTICLE LIST HERE *********************
numParticles = 50000; // total number of particles in the system
numGenerators = 3;
generators = new ParticleGenerator [numGenerators];
//*****************************************************
//***** DEFINE PARTICLE GENERATORS HERE ****************
Vector3d x;
x.set(0.0, 10.0, 0.0);
float start_t = 0.0;
float stop_t = 4.5;
int gen_r = 5000;
pg = ParticleGenerator(numParticles, x, start_t, stop_t, gen_r);
float mean_s = 5.0;
float s_range = 1.0;
float mean_ls = 1.5;
float ls_range = 0.5;
float rad = 12.0;
pg.setSpeedParams(mean_s, s_range);
pg.setLifespanParams(mean_ls, ls_range);
pg.setRadius(rad);
//--------------------------------------------------------
Vector3d x2;
x2.set(10.0, 0.0, 0.0);
float start_t2 = 0.0;
float stop_t2 = 3.5;
int gen_r2 = 4000;
pg2 = ParticleGenerator(numParticles, x2, start_t2, stop_t2, gen_r2);
float mean_s2 = 20.0;
float s_range2 = 8.0;
float mean_ls2 = 1.0;
float ls_range2 = 0.5;
float rad2 = 6.0;
pg2.setSpeedParams(mean_s2, s_range2);
pg2.setLifespanParams(mean_ls2, ls_range2);
pg2.setRadius(rad2);
//--------------------------------------------------------
Vector3d x3;
x3.set(-18.0, -5.0, 4.0);
float start_t3 = 0.0;
float stop_t3 = 2.5;
int gen_r3 = 3000;
pg3 = ParticleGenerator(numParticles, x3, start_t3, stop_t3, gen_r3);
float mean_s3 = 12.0;
float s_range3 = 3.0;
float mean_ls3 = 0.8;
float ls_range3 = 0.2;
float rad3 = 3.0;
pg3.setSpeedParams(mean_s3, s_range3);
pg3.setLifespanParams(mean_ls3, ls_range3);
pg3.setRadius(rad3);
generators[0] = pg;
generators[1] = pg2;
generators[2] = pg3;
//*****************************************************
for (int i = 0; i < numGenerators; i++){
ParticleList *pl = generators[i].getParticleList();
pl->clear();
}
running = false; // flag to mark simulation is running
t = 0.0; // current time
n = 0; // current step
}
//-----------------------------------------------------------------
/*
Model::timeStep()
* PURPOSE : Perform one time step in the simulation
* INPUTS : None
* OUTPUTS : None, updates particles
*/
//-----------------------------------------------------------------
void Model::timeStep(){
if(running){
for (int i = 0; i < numGenerators; i++)
{
generators[i].generateParticles(t, h); // generate particles
generators[i].testAndDeactivate(h, t); // deactivate dead particles
generators[i].computeAccelerations(drag); // compute accelerations of particles
generators[i].integrate(h); // Euler integration
n = n + 1; // update time
t = n * h;
}
}
}
//-----------------------------------------------------------------
/*
Model::startSimulation()
* PURPOSE : Start the simulation
* INPUTS : None
* OUTPUTS : None, changes state of boolean flag
*/
//-----------------------------------------------------------------
void Model::startSimulation(){
running = true;
}
| true |
375a7d45f70e0f18e50c25709970fc1f8828c642 | C++ | EinsVision/ModernCpp | /m9_9.cpp | UHC | 1,474 | 3.59375 | 4 | [] | no_license | #include "projects.h"
class Fraction_cp
{
private:
int numerator;
int denominator;
public:
Fraction_cp(const int& num_in, const int& deno_in = 1)
:numerator(num_in), denominator(deno_in)
{
cout << "constructor called" << endl;
assert(deno_in != 0);
}
Fraction_cp(const Fraction_cp& fr)
:numerator(fr.numerator), denominator(fr.denominator)
{ // instance !
cout << "Copy constructor called" << endl;
cout << ", copy constructor ȣ " << endl;
cout << "private ű ȴ." << endl;
}
friend ostream& operator << (ostream& out, const Fraction_cp& f)
{
out << f.numerator << " / " << f.denominator << endl;
return out;
}
};
Fraction_cp returnFraction_cp()
{
Fraction_cp temp(1, 2);
cout <<"&temp address: "<< &temp << endl;
return temp;
}
void Projects_9::m9_9()
{
// 9.9 , ʱȭ ȯ ȭ
Fraction_cp fr(4, 7);
cout << fr << endl;
Fraction_cp copy(fr);
// Fraction_cp copy = fr;
cout << copy << endl;
Fraction_cp copy_dir(Fraction_cp(3, 9));
cout << copy_dir << endl;
cout << " ڰ ʴ´. " << endl;
Fraction_cp returnCP = returnFraction_cp();
cout << returnCP << endl;
cout << "&returnCP address: " << &returnCP << endl;
cout << "Debug mode ϶ ּҰ ٸ" << endl;
cout << "Release mode ϶ ּҰ . " << endl;
} | true |
589d0b122ac3c4cabc2d74e1b6ccb5139bcf5fc9 | C++ | antipeon/cpp-labs | /lab-01/regular_polygon.cpp | UTF-8 | 940 | 3.265625 | 3 | [] | no_license | #include "regular_polygon.h"
#include <cmath>
#include <stdexcept>
#include "vector.h"
using geometry::RegularPolygon;
RegularPolygon::RegularPolygon(const std::vector<Point>& points)
: Polygon(points) {
const auto points_number = points.size();
edge_length = Vector(points[0], points[1]).Length();
for (size_t i = 0; i < points_number; ++i) {
const double cur_length =
Vector(points[i], points[(i + 1) % points_number]).Length();
if (edge_length != cur_length) {
throw std::runtime_error("not regular polygon");
}
}
}
double RegularPolygon::CalculatePerimeter() const {
return points.size() * edge_length;
}
double RegularPolygon::CalculateSquare() const {
const double pi = M_PI;
const int32_t points_number = points.size();
const double R = edge_length / 2 / std::sin(pi / points_number);
const double r = R * std::cos(pi / points_number);
return CalculatePerimeter() * r / 2;
}
| true |
2df45eead0d912c5ff93fc26bb0db3df3ef32642 | C++ | wdavidcalsin/fractal-tree-SFML-vscode | /main.cpp | UTF-8 | 1,317 | 3.28125 | 3 | [] | no_license | #include <SFML/Graphics.hpp>
#include <cmath>
using namespace sf;
const double PI = 3.141592;
const double R = 0.57;
const double O = 45;
sf::Color treeColor = sf::Color::Blue;
void createTreeRecursive(sf::VertexArray &tree, sf::Vector2f point, float angle, float lenght)
{
if (lenght < 3)
return;
tree.append(sf::Vertex(point, treeColor));
float newX = point.x + (cos((2.f * PI / 360.f) * angle) * lenght);
float newY = point.y - (sin((2.f * PI / 360.f) * angle) * lenght);
sf::Vector2f nextPoint(newX, newY);
tree.append(sf::Vertex(nextPoint, treeColor));
createTreeRecursive(tree, nextPoint, angle + O, lenght * R);
createTreeRecursive(tree, nextPoint, angle - O, lenght * R);
}
sf::VertexArray createTree()
{
sf::VertexArray ret(sf::PrimitiveType::Lines);
createTreeRecursive(ret, sf::Vector2f(250, 450), 90, 200);
return ret;
}
int main()
{
sf::RenderWindow window({800, 600}, "SFML Tree", sf::Style::Close);
auto tree = createTree();
while (window.isOpen())
{
for (sf::Event event; window.pollEvent(event);)
{
if (event.type == sf::Event::Closed)
window.close();
}
window.clear();
window.draw(tree);
window.display();
}
return EXIT_SUCCESS;
}
| true |
1d9e45a4da99bd3f4998b4fbede6cb41b650b7f3 | C++ | acaly/MimiEditor | /MimiEditor/LocalFileWindows.cpp | UTF-8 | 3,415 | 2.640625 | 3 | [] | no_license | #include "File.h"
#include <utility>
#include <cassert>
#include <Windows.h>
//C++ file stream is not designed for binary nor for string (with encoding). Use Windows API instead.
namespace
{
using namespace Mimi;
class WindowsFileReader : public IFileReader
{
public:
HANDLE hFile;
std::size_t Size;
public:
virtual ~WindowsFileReader()
{
::CloseHandle(hFile);
hFile = INVALID_HANDLE_VALUE;
}
public:
virtual std::size_t GetSize() override
{
assert(Size < SIZE_MAX);
return static_cast<std::size_t>(Size);
}
virtual std::size_t GetPosition() override
{
LARGE_INTEGER li;
li.QuadPart = 0;
LARGE_INTEGER newPtr;
if (!::SetFilePointerEx(hFile, li, &newPtr, FILE_CURRENT))
{
return SIZE_MAX;
}
assert(li.QuadPart < SIZE_MAX);
return static_cast<std::size_t>(newPtr.QuadPart);
}
virtual Result<> Read(std::uint8_t* buffer, std::size_t bufferLen, std::size_t* numRead) override
{
bool ret;
if (bufferLen > MAXDWORD)
{
return ErrorCodes::InvalidArgument;
}
DWORD toRead = static_cast<DWORD>(bufferLen);
DWORD totalRead = 0;
DWORD numReadValue;
do
{
ret = ::ReadFile(hFile, buffer, toRead, &numReadValue, 0);
toRead -= numReadValue;
totalRead += numReadValue;
} while (ret && toRead > 0 && numReadValue > 0);
//TODO GetLastError of ReadFile
if (numRead)
{
*numRead = totalRead;
}
if (totalRead > 0)
{
return true;
}
else
{
return ErrorCodes::Unknown;
}
}
virtual Result<> Skip(std::size_t num) override
{
assert(num <= Size);
LARGE_INTEGER li;
li.QuadPart = num;
if (::SetFilePointerEx(hFile, li, 0, FILE_CURRENT))
{
return true;
}
else
{
return ErrorCodes::Unknown;
}
}
virtual Result<> Reset() override
{
LARGE_INTEGER li;
li.QuadPart = 0;
if (::SetFilePointerEx(hFile, li, 0, FILE_BEGIN))
{
return true;
}
else
{
return ErrorCodes::Unknown;
}
}
};
class WindowsFile : public IFile
{
public:
WindowsFile(String path)
: Path(path.ToUtf16String())
{
}
public:
String Path;
public:
virtual bool IsReadonly() override
{
return false;
}
virtual String GetIdentifier() override
{
return Path;
}
virtual Result<IFileReader*> Read() override
{
HANDLE h = ::CreateFile(reinterpret_cast<LPCWSTR>(Path.Data),
GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
if (h == INVALID_HANDLE_VALUE)
{
DWORD e = ::GetLastError();
if (e == ERROR_FILE_NOT_FOUND)
{
return ErrorCodes::FileNotFound;
}
return ErrorCodes::Unknown;
}
LARGE_INTEGER size;
if (!::GetFileSizeEx(h, &size))
{
DWORD e = ::GetLastError();
::CloseHandle(h);
return ErrorCodes::Unknown;
}
if (size.QuadPart >= SIZE_MAX)
{
return ErrorCodes::FileTooLarge;
}
WindowsFileReader* reader = new WindowsFileReader();
reader->hFile = h;
reader->Size = static_cast<std::size_t>(size.QuadPart);
return static_cast<IFileReader*>(reader);
}
virtual Result<IFileWriter*> Write(std::size_t pos) override
{
return ErrorCodes::NotImplemented;
}
virtual Result<IFileWatcher*> StartWatch() override
{
return ErrorCodes::NotImplemented;
}
};
}
Mimi::Result<Mimi::IFile*> Mimi::IFile::CreateFromPath(String path)
{
return new WindowsFile(std::move(path));
}
| true |
8dfda0d57fa1bb9b61223c5ab765809f386f313d | C++ | sanjayaherath/Child-Watch | /sketches/SMS_1/SMS_1.ino | UTF-8 | 1,487 | 2.6875 | 3 | [] | no_license | #include <Sim800l.h>
#include <SoftwareSerial.h> //is necesary for the library!!
Sim800l Sim800l; //to declare the library
String numberSms, textSms;
bool error;
String number = "+94719688884";
int motPin = 3;
void setup() {
Sim800l.begin(); // initializate the library.
Serial.begin(9600);
pinMode(motPin, OUTPUT);
Sim800l.delAllSms(); //clean memory of sms;
}
void loop() {
checkSms();
delay(1000);
}
void checkSms() {
textSms = Sim800l.readSms(1);
if (textSms.indexOf("OK") != -1) {
if (textSms.length() > 7) {
numberSms = Sim800l.getNumberSms(1);
Serial.println(numberSms);
if (numberSms.equals(number)) {
Serial.println("match");
playSmsAlarm();
}
Sim800l.delAllSms();
}
}
}
void sendMessage() { // send sms to contacts
char* sendsmstext = "match";
error = Sim800l.sendSms(number, sendsmstext);
if (error) {
digitalWrite(motPin, HIGH);
delay(800);
digitalWrite(motPin, LOW);
}
}
void playAlarm() { //alarm notification motor
for (int i = 0; i < 5; i++) {
digitalWrite(motPin, HIGH);
delay(600);
digitalWrite(motPin, LOW);
delay(1000);
}
}
void playSmsAlarm() { //sms received notification motor
for (int i = 0; i < 5; i++) {
digitalWrite(motPin, HIGH);
delay(400);
digitalWrite(motPin, LOW);
delay(200);
digitalWrite(motPin, HIGH);
delay(400);
digitalWrite(motPin, LOW);
delay(1000);
}
}
| true |
f940e1f973412120a80ee5bbe1e76248620fdfa1 | C++ | Shingyee/CreativeCoding_2019Summer_ZXYfinalwork | /arduino/sketch_jul03c.ino | UTF-8 | 1,570 | 2.890625 | 3 | [] | no_license | #include <dht11.h> //引用dht11库文件,使得下面可以调用相关参数
#define DHT11PIN 11 //定义温湿度针脚号为11号引脚
dht11 DHT11; //实例化一个对象
const int P = A0; //电位器的引脚
const int U = 2;
int sensorValue = 0; //电位器电压值
int outputValue = 0;
void setup() { //设置
Serial.begin(9600); //设置波特率参数
pinMode(DHT11PIN, OUTPUT); //定义输出口
}
void loop() { //循环
int chk = DHT11.read(DHT11PIN); //将读取到的值赋给chk
int tem = (float)DHT11.temperature; //将温度值赋值给tem
int hum = (float)DHT11.humidity; //将湿度值赋给hum
//Serial.print("Tempeature:"); //打印出Tempeature:
Serial.println(tem); //打印温度结果
//Serial.print("Humidity:"); //打印出Humidity:
//Serial.print(hum); //打印出湿度结果
//Serial.println("%"); //打印出%
delay(1000); //延时一段时间
if (tem > 28) {
sensorValue = analogRead(P);
outputValue = map(sensorValue, 0, 1023, 0, 255);
analogWrite(U, outputValue);
delay(1000);
}
else
{
analogWrite(U, 0);
delay(1000);
}
}
| true |
6a24898e63d2f68ba2354ba2d84a6bee2d219b53 | C++ | iThinkEmo/ComputerGraphics2017 | /ComputerGraphics/Circle.cpp | ISO-8859-1 | 844 | 3.390625 | 3 | [] | no_license | /*********************************************************
Materia: Grficas Computacionales
Fecha: 18 de agosto del 2017
Autor: A01169073 Aldo A. Reyna Gmez
*********************************************************/
#include "Circle.h" //Si es un archivo fuente que ya existe, se usa "", si es librera que se vincula de otro lado, se usa <>
Circle::Circle() { // De la case Circle, voy a implementar el constructor Circle
_radius = 1.0;
_colour = "red";
}
Circle::Circle(double r) {
_radius = r;
_colour = "verde";
}
Circle::Circle(double r, string c){
_radius = r;
_colour = c;
}
double Circle::GetRadius() {
return _radius;
}
double Circle::GetArea() {
return 3.14159*_radius*_radius;
}
string Circle::GetColor(){
return _colour;
}
void Circle::SetRadius(double r){
_radius = r;
}
void Circle::SetColor(string c){
_colour = c;
}
| true |
b4e530d805edf5bead3f6f29ec0e71a790861f9d | C++ | xijujie/PAT--Advanced-Level--Practice | /1053.cpp | UTF-8 | 1,182 | 2.640625 | 3 | [] | no_license | #include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
const int maxn = 100;
int weight[maxn], s;
vector<int> node[maxn], tmp;
vector<vector<int> > ans;
bool cmp(vector<int> &a, vector<int> &b) {
int l = min(a.size(), b.size());
for (int i = 0; i < l; ++i) {
if (a[i] != b[i]) return a[i] > b[i];
}
return a.size() > b.size();
}
void dfs(int root, int nows) {
if (node[root].size() == 0) {
if (nows == s) ans.push_back(tmp);
return;
}
for (int i = 0; i < node[root].size(); ++i) {
int w = weight[node[root][i]];
if (nows + w <= s) {
tmp.push_back(w);
dfs(node[root][i], nows + w);
tmp.pop_back();
}
}
}
int main() {
//freopen("in.txt", "r", stdin);
int n, m, id, k, t;
scanf("%d%d%d", &n, &m, &s);
for (int i = 0; i < n; ++i) {
scanf("%d", &weight[i]);
}
for (int i = 0; i < m; ++i) {
scanf("%d%d", &id, &k);
for (int j = 0; j < k; ++j) {
scanf("%d", &t);
node[id].push_back(t);
}
}
dfs(0, weight[0]);
sort(ans.begin(), ans.end(), cmp);
for (int i = 0; i < ans.size(); ++i) {
printf("%d", weight[0]);
for (int j = 0; j < ans[i].size(); ++j) printf(" %d", ans[i][j]);
printf("\n");
}
return 0;
} | true |
05138c0b7989ed0288062c5b37ddbbd919bc2b24 | C++ | mirabl/j | /longest-string-chain.cpp | UTF-8 | 1,211 | 2.921875 | 3 | [] | no_license | class Solution {
public:
bool pred(string& s, string& t) {
int n = t.size();
if (t.size() != s.size() + 1) {
return false;
}
int i = 0;
int j = 0;
while (i < n - 1 && s[i] == t[j]) {
i++;
j++;
}
if (i == n - 1) {
return true;
}
j++;
while (i < n - 1 && j < n) {
if (s[i] != t[j]) {
return false;
}
i++;
j++;
}
return true;
}
int l(map<int, vector<int>>& G, int i) {
int best = 1;
for (int j: G[i]) {
best = max(best, 1 + l(G, j));
}
return best;
}
int longestStrChain(vector<string>& words) {
int n = words.size();
map<int, vector<int>> G;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (pred(words[i], words[j])) {
G[i].push_back(j);
}
}
}
int b = 0;
for (int i = 0; i < n; i++) {
b = max(b, l(G, i));
}
return b;
}
};
| true |
71109e2b329e9c3c8b92278f81cd71fd35b59221 | C++ | JangHyeonJun/AlgorithmStudy | /Algorithms/programmers_12953.cpp | UTF-8 | 488 | 2.796875 | 3 | [] | no_license | //#include <string>
//#include <vector>
//#include <algorithm>
//using namespace std;
//
//int solution(vector<int> arr) {
// sort(arr.begin(), arr.end());
// int num = 1;
// for(int i=0; i<arr.size(); i++)
// {
// if (num % arr[i] != 0)
// {
// int sum1 = num;
// int sum2 = arr[i];
// while (true)
// {
// if (sum1 == sum2)
// break;
// else if (sum1 < sum2)
// sum1 += num;
// else
// sum2 += arr[i];
// }
// num = sum1;
// }
// }
// return num;
//} | true |
eacb989460e22bdd6c0726b0ff0d5b87eb66b2bd | C++ | CarlaOnate/Tec-EstructuraDatos-Algoritmos-Feb-Jun-2021 | /Templates_ClassAct/exampleMain.cpp | UTF-8 | 507 | 3.34375 | 3 | [] | no_license | //
// Created by Carla Onate on 08/02/21.
//
#include <iostream>
using namespace std;
template <class T>
T suma(T n1, T n2, T n3){
return n1 + n2 +n3;
}
template <class D>
D sumaFrac(D n1, D n2, D d1, D d2){
return (n1 + n2)/(d1 + d2);
}
//Todo: Make clase fraction separate form main and sum those fractions with a template
template <class T>
int exampleMain() {
int a = 2, b = 10, c = 4;
double a1 = 1.1, a2 = 2.2, a3 = 3.3;
T doubleSum = suma(a1,a2,a3);
T intSum = suma(a,b,c);
}
| true |
9d9328bf4ba63de80c5c0bae4ce239aa19885305 | C++ | andyyzhengg/LeapPass | /LeapPassGui/PassListener.cpp | UTF-8 | 6,600 | 2.78125 | 3 | [] | no_license | //
// PassListener.cpp
// LeapPass
//
// Created by Andy Zheng on 3/28/14.
// Copyright (c) 2014 Andy Zheng. All rights reserved.
//
#include "PassListener.h"
using namespace Leap;
PassListener::PassListener(bool save) : _save(save)
{
for(int i = 0; i < 4; ++i)
{
pins[i] = false;
}
}
void
PassListener::onInit(const Controller& controller) {}
void
PassListener::onConnect(const Controller& controller)
{
controller.enableGesture(Gesture::TYPE_SWIPE);
}
void
PassListener::onDisconnect(const Controller& controller){}
void
PassListener::onExit(const Controller& controller) {}
void
PassListener::onFrame(const Controller& controller)
{
const Frame frame = controller.frame();
const Frame prevFrame = controller.frame(1);
if (!frame.hands().isEmpty())
{
//Only works on the first hand
const Hand hand = frame.hands()[0];
const FingerList fingers = hand.fingers();
//If the fist is closed we store the last symbol that was shown to the Leap Motion.
if (fingers.count() <= 1 && !finished)
{
//If the last move was not a fist we proceed
if(!lastMoveFist)
{
if(numPins < 4)
{
password+=lastSymbol;
std::cout << lastSymbol << std::endl;
lastMoveFist = true;
pins[numPins++] = true;
}
}else
{
//Otherwise we check if someone closed their fist/ used one finger to backspace.
Gesture gesture = frame.gestures()[0];
if(Gesture::TYPE_SWIPE == gesture.type())
{
SwipeGesture swipe = gesture;
if((swipe.direction()[0] < 0.0) && (swipe.state() == Gesture::STATE_START))
{
if(numPins > 0)
{
password.pop_back();
pins[--numPins] = false;
std::cout << password << std::endl;
}
}
}
}
}
else if(fingers.count() == 5 && !finished)
{
//If the hand is opened (five fingers out) then this signals us to terminate and store/check password
std::cout << "\nPassword is: " << password << std::endl;
if(_save)
{
std::hash<std::string> out; // Password is stored in a text file as a hash.
std::size_t str_out = out(password);
std::ofstream outFile;
outFile.open("pass.txt");
if(outFile.is_open())
{
outFile << str_out;
outFile.close();
}
else
{
std::cerr << "Error opening pass.txt" << std::endl;
}
finished = true;
}else
{
std::ifstream inFile;
inFile.open("pass.txt");
if(inFile.is_open())
{
std::size_t str_in;
inFile >> str_in;
if(str_in == std::hash<std::string>()(password))
{
finished = true;
std::cout << "Success!" << std::endl;
}else
{
std::cout << "Wrong! Try again." << std::endl;
password.clear();
for(int i = 0; i < 4; ++i)
{
pins[i] = false;
}
numPins = 0;
}
}else
{
finished = true;
std::cerr << "Error opening pass.txt" << std::endl;
}
}
}else
{
//Get symbol, should only be able to change symbol if it is a valid symbol
if(lastMoveFist)
{
lastSymbol = getSymbol(fingers);
if(lastSymbol != '\0')
lastMoveFist = false;
}
}
}
}
void
PassListener::onFocusGained(const Controller& controller) {}
void
PassListener::onFocusLost(const Controller& controller) {}
/* Return a char based on the hand symbol. Based on sign language. */
char
PassListener::getSymbol(const Leap::FingerList& fingers)
{
char retChar = {};
float angle = {};
float avgFingerSpd = 0.0;
Vector *fingersVector = new Vector[fingers.count()];
for(int i = 0; i < fingers.count(); ++i)
{
fingersVector[i] = fingers[i].direction();
avgFingerSpd+=fingers[i].tipVelocity()[0];
avgFingerSpd+=fingers[i].tipVelocity()[1];
avgFingerSpd+=fingers[i].tipVelocity()[2];
avgFingerSpd /= 3;
}
avgFingerSpd /= fingers.count();
if(avgFingerSpd < 5.0 && avgFingerSpd > -5.0)
{
switch(fingers.count())
{
//1 and 5 are used for special signals.
case 2:
angle = fingersVector[0].angleTo(fingersVector[1]);
if(angle <= .75)
{
retChar = '2';
}
else if((angle > .75) && (fingers[0].tipPosition().distanceTo(fingers[1].tipPosition()) > 150.0))
{
retChar = 'y';
}else
{
retChar = 'l';
}
std::cout << "angle from 0 to 1: " << angle << " distance between 0 and 1: " << fingers[0].tipPosition().distanceTo(fingers[1].tipPosition()) << std::endl;
break;
case 3:
angle = fingersVector[1].angleTo(fingersVector[2]);
if((angle > .5) && (fingers[1].tipPosition().distanceTo(fingers[2].tipPosition()) > 100.0))
{
retChar = '7';
}else
{
retChar = '3';
}
std::cout << "angle from 1 to 2: " << angle << " distance between 1 and 2: " << fingers[1].tipPosition().distanceTo(fingers[2].tipPosition()) << std::endl;
break;
case 4:
retChar = '4';
break;
default:
break;
}
}
delete [] fingersVector;
return retChar;
}
| true |
a0334ac25603cb0e5d5bf5d8bd7b76858f27db72 | C++ | renatosamperio/process_visualisation | /src/main.cpp | UTF-8 | 4,224 | 2.734375 | 3 | [] | no_license | #include <QApplication>
#include <iostream>
#include <memory>
#include <vector>
#include "boost/program_options.hpp"
#include "Poco/ThreadPool.h"
#include "Poco/Runnable.h"
#include "mainwindow.h"
#include "remotedatafeeder.h"
namespace
{
const size_t ERROR_IN_COMMAND_LINE = 1;
const size_t SUCCESS = 0;
const size_t ERROR_UNHANDLED_EXCEPTION = 2;
}
typedef enum {
plot_mem = 0x01,
plot_cpu = 0x02,
plot_max = 0x02
} item_validator;
class GUIinThread : public Poco::Runnable
{
public:
GUIinThread(std::shared_ptr<RemoteDataFeeder> observer, int plotOtions):
m_dataObserver(observer),
m_plotOtions(plotOtions)
{
}
int addPlot(std::vector<std::shared_ptr<MainWindow>> &plots, int ind, int a, PlotType plotType)
{
std::shared_ptr<MainWindow> newPlot(new MainWindow);
plots.push_back( std::move(newPlot) );
plots[ind]->setupObserver( m_dataObserver, a, plotType);
plots[ind]->show();
return ind+1;
}
virtual void run()
{
int argc = 1;
QByteArray argvStr = QString("").toLatin1();
char* argv = argvStr.data();
QApplication app(argc, &argv);
// Wait until data is available to run time series timeSeriesPlotter
while (!m_dataObserver->isReceivingData());
// Setting up time series plotter with new incoming data feeds
int processSize = m_dataObserver->data()->getProcessSize();
// std::cout << " - Monitoring "<< processSize << " process(es) "<<endl;
// Setting up step value
int step = 0;
int plot_options = m_plotOtions;
int plot_value = plot_max; //MAX PLOT VALUE
while (plot_options > 0)
{
if (plot_options & plot_value){
step++;
plot_options = (plot_options ^ plot_value);
}
plot_value >>= 1;
}
// Plotting for desired processes
std::vector<std::shared_ptr<MainWindow>> my_plots;
for (int i=0, a=0; i<processSize*step; i+=step, a++)
{
int curr_ind = i;
// Add memory plot
if (m_plotOtions & plot_mem)
curr_ind = addPlot(my_plots, curr_ind, a, kMemory);
// Add cpu usage plot
if (m_plotOtions & plot_cpu)
curr_ind = addPlot(my_plots, curr_ind, a, kCPU);
}
app.exec();
}
private:
std::shared_ptr<RemoteDataFeeder> m_dataObserver;
int m_plotOtions;
};
int main(int argc, char *argv[])
{
std::string appName = argv[0];
int plotOtions = 0;
std::string endpoint ="";
try
{
namespace po = boost::program_options;
po::options_description desc("Options");
desc.add_options()
("help,h", "Print help messages")
("memory,m", "Plot total memory")
("cpu,c", "Plot cpu usage")
("endpoint,n", po::value<std::string>()->required(), "tcp://server::port") ;
po::positional_options_description positionalOptions;
positionalOptions.add("memory", 1);
positionalOptions.add("cpu", 1);
po::variables_map vm;
try
{
po::store(po::command_line_parser(argc, argv).options(desc)
.positional(positionalOptions).run(),
vm);
if ( vm.count("help") )
{
std::cout << "usage: ./proval -m -c"
<< std::endl << std::endl;
return SUCCESS;
}
po::notify(vm);
}
catch(boost::program_options::required_option& e)
{
std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
return ERROR_IN_COMMAND_LINE;
}
catch(boost::program_options::error& e)
{
std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
return ERROR_IN_COMMAND_LINE;
}
if ( vm.count("endpoint") )
{
endpoint = vm["endpoint"].as<std::string>();
}
if ( vm.count("memory") )
{
plotOtions |= plot_mem;
}
if ( vm.count("cpu") )
{
plotOtions |= plot_cpu;
}
}
catch(std::exception& e)
{
std::cerr << "Unhandled Exception reached the top of main: "
<< e.what() << ", application will now exit" << std::endl;
return ERROR_UNHANDLED_EXCEPTION;
}
std::shared_ptr<RemoteDataFeeder> dataObserver( new RemoteDataFeeder(endpoint) );
GUIinThread timeseries(dataObserver, plotOtions);
Poco::ThreadPool::defaultPool().start(*dataObserver);
Poco::ThreadPool::defaultPool().start(timeseries);
Poco::ThreadPool::defaultPool().joinAll();
return 0;
}
| true |
bb3eb28e84d09f8b82a0e2752fef7e130e96b719 | C++ | TitoCarpio/Practica-PED | /Guia2/Ejercicio1.cpp | UTF-8 | 2,099 | 3.640625 | 4 | [] | no_license | #include <iostream>
#include <conio.h>
#include <string.h>
using namespace std;
// variable global que utilizaremos para controlar los for y manejar el arreglo de notas
int n = 0;
// Resgistro donde almacenaremos todos los datos del usuario
struct Estudiante{
string nombre;
string apellido;
string estado = "Indefinido";
float notas[];
};
/*variable del mismo tipo de nuestro registro, de ambito global para poder hacer
**uso de ella en cualquiera de nuestras variables */
struct Estudiante estudiante;
// lista de todas las variables a usar
void Ingresar_datos();
void notas(int );
float promedio();
void mostrar(float);
int main(){
float prome = 0;
Ingresar_datos();
cout<<"\t Cuantas notas desea ingresar: ";
cin>>n;
notas(n);
prome = promedio();
mostrar(prome);
getch();
return 0;
}
// Funcion con la que pedimos datos al usurio
void Ingresar_datos(){
cout<<"\t Ingrse su nombre: ";
cin>>estudiante.nombre;
cin.ignore();
cout<<endl;
cout<<"\t Ingrese su apellido: ";
cin>>estudiante.apellido;
cin.ignore();
}
// Funcion con la que pedimos las notas al usurio
void notas(){
for(int i=0;i<n;i++){
cout<<"\t Ingrese la nota "<<i+1<<":";
cin>>estudiante.notas[i];
}
}
// funcion que calcula el promedio de las notas y verifica el estado del usuario
float promedio(){
float prom = 0;
for(int i = 0;i<n;i++){
prom = (prom + estudiante.notas[i]);
}
prom = prom/n;
if(prom >= 6){
estudiante.estado = "Aprobado";
}else{
estudiante.estado = "Reprobado";
}
return prom;
}
// Funcion que muestra toda la informacion del usuario
void mostrar(float promedio){
cout<<"_______________________________________________"<<endl;
cout<<"\t Nombre del Alumno: "<<estudiante.nombre<<" "<<estudiante.apellido<<endl;
cout<<"\t Obtuvo notas de:";
for(int i=0;i<n;i++){
cout<<"["<<estudiante.notas[i]<<"] ";
}
cout<<endl;
cout<<"\t Promedio Final: "<<promedio<<endl;
cout<<"\t Estado: "<<estudiante.estado<<endl;
} | true |
dc208e49bbec704a219c3e1686a8208b5499e545 | C++ | JanDeng25/Online-Judge | /leetcode OJ/377. Combination Sum IV.cpp | UTF-8 | 736 | 2.96875 | 3 | [] | no_license | class Solution {
public:
/*
//iteration
int combinationSum4(vector<int>& nums, int target) {
vector<int> dp(target+1, 0);
dp[0] = 1;
for(int i = 0; i <= target; i++){
for(int j = 0; j < nums.size(); j++){
if(i - nums[j] >= 0)
{
dp[i] += dp[i - nums[j]];
}
}
}
return dp[target];
}
*/
//Recursion
int combinationSum4(vector<int>& nums, vector<int>& v, int target) {
if (target <= 0)
return !target;
if (v[target] == -1) {
v[target] = 0;
for (int i = 0; i < nums.size(); i++) {
v[target] += combinationSum4(nums, v, target - nums[i]);
}
}
return v[target];
}
int combinationSum4(vector<int>& nums, int target) {
vector<int> v(target + 1, -1);
return combinationSum4(nums, v, target);
}
}; | true |
4d06e765e4b85135c47142775fb44d8c7979effd | C++ | xiexiangyi0/GoogleCodeJam | /GCJ_Japan_2011_Qualification/A/main.cpp | UTF-8 | 787 | 3.078125 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
#define dump(x) cerr << #x << " = " << (x) << endl;
int solve(int M, int C, int W, vector<int>& A, vector<int>& B) {
for (int i = C - 1; i >= 0; i--) {
if (W <= B[i]) {
W += A[i] - 1;
} else if (W <= A[i] + B[i] - 1) {
W -= B[i];
}
}
return W;
}
int main() {
int T, M, C, W, tmpA, tmpB;
cin >> T;
for (int i = 1; i <= T; i++) {
cin >> M >> C >> W;
vector<int> A;
vector<int> B;
for (int j = 0; j < C; j++) {
cin >> tmpA >> tmpB;
A.push_back(tmpA);
B.push_back(tmpB);
}
int answer = solve(M, C, W, A, B);
cout << "Case #" << i << ": " << answer << endl;
}
}
| true |
1d77c92a0e835c4d5821216d4616a790af5cd64b | C++ | lja9702/JinAh-BOJ | /BaekjoonOnline/14916_change.cpp | UTF-8 | 288 | 2.734375 | 3 | [] | no_license | #include <cstdio>
int main(){
bool flag = 0;
int res = 0, n;
scanf("%d", &n);
for(int i = n / 5;i >= 0;i--){
int temp = n - i * 5;
if(!(temp % 2)){
res = i + temp / 2;
flag = 1;
break;
}
}
if(flag) printf("%d\n", res);
else printf("-1\n");
}
| true |
f4eac7c595adae315ca14b125e1a6634f6996121 | C++ | dkdlel/DongA-University | /Algorithm/과제12(바둑집 계산)/go.cpp | UHC | 1,932 | 3.0625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
ifstream fcin("go.inp");
ofstream fcout("go.out");
enum { UP, DOWN, LEFT, RIGHT };
class Go {
public:
int n1 = 0, cnt = 0, nextx = 0, nexty = 0, black_cnt = 0, white_cnt = 0, black_room = 0, white_room = 0; // n1 : n x n, cnt :
vector < vector < char > > board; // ٵ
vector < vector < bool > > visited; // 湮 ߴ ߴ
void Input();
void Sol(int x, int y);
void FindNext(int x, int y, int n);
};
void Go::Input() {
fcin >> n1;
for (int i = 0; i < n1; i++) {
board.resize(n1);
visited.resize(n1);
for (int j = 0; j < n1; j++) {
board[i].resize(n1);
visited[i].resize(n1);
fcin >> board[i][j];
}
}
}
void Go::FindNext(int x , int y, int n) {
if (n == UP) { //
nextx = x - 1; nexty = y;
}
else if (n == DOWN) { // Ʒ
nextx = x + 1; nexty = y;
}
else if (n == LEFT) { //
nextx = x; nexty = y - 1;
}
else { //
nextx = x; nexty = y + 1;
}
}
void Go::Sol(int x, int y) {
visited[x][y] = true; cnt++;
for (int i = 0; i < 4; i++) { // , Ʒ, ,
FindNext(x, y, i); // ǥ ã
if (nextx >= 0 && nexty >= 0 && nextx < n1 && nexty < n1 && !visited[nextx][nexty]) {
// && && Ʒ &&
if (board[nextx][nexty] == 'B') black_cnt++;
else if (board[nextx][nexty] == 'W') white_cnt++;
else Sol(nextx, nexty);
}
}
}
int main() {
Go go;
go.Input();
for (int i = 0; i < go.n1; i++) {
for (int j = 0; j < go.n1; j++) {
if (go.board[i][j] == '.' && !go.visited[i][j]) {
go.Sol(i, j);
if (go.black_cnt == 0) go.white_room += go.cnt; //
else if (go.white_cnt == 0) go.black_room += go.cnt; //
go.cnt = 0; go.black_cnt = 0; go.white_cnt = 0;
}
}
}
fcout << go.black_room << ' ' << go.white_room << '\n';
return 0;
} | true |
3046ad8cd0f43760af98a6de779c0f5c9938843e | C++ | AxelLavielle/Barde | /Server/ServerSocket/ThreadPoolGenerator.cpp | UTF-8 | 2,922 | 2.640625 | 3 | [] | no_license | /*
==============================================================================
ThreadPool.cpp
Created: 21 Jun 2018 12:56:47pm
Author: anthony
==============================================================================
*/
#include "ThreadPoolGenerator.hh"
ThreadPoolGenerator::ThreadPoolGenerator()
{
}
ThreadPoolGenerator::~ThreadPoolGenerator()
{
}
void ThreadPoolGenerator::init()
{
unsigned int n = std::thread::hardware_concurrency();
std::cout << n << " concurrent threads are supported." << std::endl;
while (n != 0)
{
_generatorThreads.push_back(std::thread(&ThreadPoolGenerator::generationManager, this));
n--;
}
}
void ThreadPoolGenerator::addClient(const Client & client)
{
_clientsMutex.lock();
_clients.push_back(client);
_sem.notify();
_clientsMutex.unlock();
CmdManager::sendResponseMessage(OK_REQUEST, PLAY_REQUEST, 0, client, "OK : playing.\r\n");
}
void ThreadPoolGenerator::removeClient(const Client & client)
{
_clientsMutex.lock();
_clients.remove(client);
_clientsMutex.unlock();
CmdManager::sendResponseMessage(OK_REQUEST, STOP_REQUEST, 0, client, "OK : stop playing.\r\n");
}
void ThreadPoolGenerator::generationManager()
{
std::list<Client>::iterator it;
std::list<Client> clients;
Client client;
Midi midiData;
while (42)
{
_clientsMutex.lock();
if (_clients.size() == 0)
{
_clientsMutex.unlock();
_sem.wait();
_clientsMutex.lock();
}
client = _clients.front();
_clients.pop_front();
_clientsMutex.unlock();
while (client.needGeneration())
{
midiData = _musicGenerator.createMusic(client.getMp());
char *tmp = new char[midiData.getMidiSize() + 2 + sizeof(int)];
tmp[0] = 0x0;
tmp[1] = 0x0;
tmp[2] = 0x0;
tmp[3] = 0x4; //This depends of the endieness !!
std::memcpy(&tmp[4], midiData.getMidiArray(), midiData.getMidiSize());
tmp[midiData.getMidiSize() + 4] = '\r';
tmp[midiData.getMidiSize() + 5] = '\n';
//Need to check the return of send
if (send(client.getFd(), tmp, midiData.getMidiSize() + 2 + sizeof(int), MSG_NOSIGNAL) == -1)
break; //If the client is disconnected or other error, he don't need generation
delete[] midiData.getMidiArray();
client.addGeneration();
delete[] tmp;
}
}
}
void ThreadPoolGenerator::refreshClient(const Client & client)
{
std::list<Client>::iterator it;
_clientsMutex.lock();
for (it = _clients.begin(); it != _clients.end(); ++it)
{
*it = client;
}
_clientsMutex.unlock();
CmdManager::sendResponseMessage(OK_REQUEST, REFRESH_REQUEST, 0, client, "OK : playing with music parameters updated.\r\n");
}
| true |
bf6748010f9fdcbbed21ea500d836646b2de69dc | C++ | shantanugoel/remember | /src/storage/storage_impl_simple_file.cc | UTF-8 | 2,259 | 2.578125 | 3 | [
"MIT"
] | permissive | #include "src/storage/storage_impl_simple_file.h"
#include <ctime>
#include <filesystem>
#include <fstream>
#include <iostream>
#include "CLI/CLI.hpp"
#include "json/json.hpp"
#include "src/model/model.h"
namespace rmbr {
void to_json(nlohmann::json& j, const ModelItemV1& item) {
j = nlohmann::json{{"what", item.what}, {"tags", item.tags}};
}
void from_json(const nlohmann::json& j, ModelItemV1& item) {
j.at("what").get_to(item.what);
j.at("tags").get_to(item.tags);
}
bool StorageSimpleFile::Initialize(CLI::App& app) {
app.add_option("--storage-file", file_path_, "File to store data");
app.parse(app.remaining_for_passthrough());
file_.open(file_path_, file_.in);
// If File doesn't exist, try to create it
if (!file_.is_open()) {
file_.open(file_path_, file_.out | file_.trunc);
// TODO: Error handling
}
initialized_ = file_.is_open();
file_.close();
return initialized_;
}
bool StorageSimpleFile::LoadModel() {
// TODO: Prevent loading model again if already loaded?
if (initialized_) {
try {
file_.open(file_path_, file_.in);
file_ >> model_json_;
model_loaded_ = true;
} catch (nlohmann::json::exception& e) {
// TODO: Warn about malformed file & conditionally abort?
model_json_.clear();
}
}
file_.close();
model_loaded_ = true;
return model_loaded_;
}
uint64_t StorageSimpleFile::Store(const ModelItemV1& item) {
model_json_.emplace_back(item);
std::filesystem::path from(file_path_);
std::string to_filename =
"." + from.filename().string() + "." + std::to_string(std::time(nullptr));
std::filesystem::path to(file_path_);
to.replace_filename(to_filename);
std::filesystem::copy_file(from, to,
std::filesystem::copy_options::overwrite_existing);
file_.open(file_path_, file_.out | file_.trunc);
if (file_.is_open()) {
file_ << model_json_;
}
file_.close();
return 0;
}
// TODO: Allow "reload" to re-read data from filesystem in case files were
// modified externally
ModelItemV1 StorageSimpleFile::Retrieve(uint64_t id) {
auto data = model_json_.find(std::to_string(id));
ModelItemV1 item;
if (data != model_json_.end()) {
item = *data;
}
return item;
}
} // namespace rmbr | true |
f4feac7845e343064d7be34eb28b46be947ef00a | C++ | jstnchng/raytracer | /raytracer1.0/headerfiles/plane.h | UTF-8 | 536 | 2.546875 | 3 | [] | no_license | #ifndef __PLANE_H__
#define __PLANE_H__
#include "surface.h"
#include "vector.h"
#include "point.h"
#include "intersection.h"
using namespace std;
class Plane: public Surface {
public:
Vector normal;
double distanceToOrigin;
public:
Plane(){};
~Plane();
Plane(Vector &n, double d);
void init(Vector &n, double d);
Plane planeFromPoints(Point &p1, Point &p2, Point &p3);
virtual Intersection intersect(Ray &ray, bool using_bbox, bool render_bbox);
virtual void print();
virtual BBox create_bbox();
};
#endif | true |
456415fbc8a73609a82e1ef2a35d6aae013dfd40 | C++ | xh286/leetcode | /215-Kth-Largest-Element-in-an-Array/solution.cpp | UTF-8 | 1,709 | 3.34375 | 3 | [] | no_license | class Solution {
private:
int my_partition(vector<int>& a, int low, int high, int pivot) // choose pivot, partition and return pivot position
{
// assert(a.size() > high && high >= low);
int pivot_value = a[pivot];
a[pivot] = a[low]; // a[low] is now free space
while(low < high)
{
while(low < high && a[high] >= pivot_value) high--;
a[low] = a[high]; // now a[high] is free space
while(low < high && a[low] <= pivot_value) low++;
a[high] = a[low]; // now a[low] is free space
}
// assert(low == high); Actually the loop is pretty clean! Better than binary search!
a[low] = pivot_value;
return low;
}
public:
int findKthLargest(vector<int>& nums, int k) {
// Quickselect. Non-trivial.
// Ending condition? Something equals zero
int n = nums.size();
int low = 0, high = n-1;
std::default_random_engine generator;
while(low<=high)
{
std::uniform_int_distribution<int> distribution(0, high-low);
int pivot = my_partition(nums, low, high, low + distribution(generator));
// [low...pivot-1] <= pivot, [pivot+1...high] >= pivot.
int rl_include_pivot = high - pivot + 1; // length to the right, including pivot
if(rl_include_pivot > k)
{
low = pivot + 1;
}
else if (rl_include_pivot < k)
{
k -= rl_include_pivot;
high = pivot - 1;
}
else
{
return nums[pivot];
}
}
return 0;
}
}; | true |
93c4be4377b2747906bfc30c295a813f0a288a84 | C++ | vivekkalia/defendaman | /Assets/C++_Scripts/Server/ServerTCP.cpp | UTF-8 | 12,739 | 2.796875 | 3 | [] | no_license | #include "ServerTCP.h"
using namespace Networking;
using namespace json11;
/**
* Initialize server socket and address
* @author Jerry Jia
* @date 2016-03-11
* @param port port number
* @return -1 on failure, 0 on success
*/
int ServerTCP::InitializeSocket(short port)
{
int err = -1;
int optval = 1; /* set SO_REUSEADDR on a socket to true (1) */
/* Create a TCP streaming socket */
if ((_TCPAcceptingSocket = socket(AF_INET, SOCK_STREAM, 0)) == -1 )
{
fatal("InitializeSocket: socket() failed\n");
return _TCPAcceptingSocket;
}
/* Allows other sockets to bind() to this port, unless there is an active listening socket bound to the port already. */
setsockopt(_TCPAcceptingSocket, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval));
/* Fill in server address information */
memset(&_ServerAddress, 0, sizeof(struct sockaddr_in));
_ServerAddress.sin_family = AF_INET;
_ServerAddress.sin_port = htons(port);
_ServerAddress.sin_addr.s_addr = htonl(INADDR_ANY); // Accept connections from any client
/* bind server address to accepting socket */
if ((err = bind(_TCPAcceptingSocket, (struct sockaddr *)&_ServerAddress, sizeof(_ServerAddress))) == -1)
{
std::cout << "InitializeSocket: bind() failed with errno " << errno << std::endl;
return err;
}
/* Listen for connections */
listen(_TCPAcceptingSocket, MAXCONNECTIONS);
return 0;
}
/**
* Calls accept on a player's socket. Sets the returning socket and client address structure to the player.
* Add connected player to the list of players
* @author Jerry Jia, Martin Minkov
* @date 2016-03-11
* @param player player object
* @return -1 on failure, 0 on success
*/
int ServerTCP::Accept(Player * player)
{
unsigned int ClientLen = sizeof(player->connection);
/* Accepts a connection from the client */
if ((player->socket = accept(_TCPAcceptingSocket, (struct sockaddr *)&player->connection, &ClientLen)) == -1)
{
std::cerr << "Accept() failed with errno" << errno << std::endl;
return -1;
}
player->isReady = false;
player->playerClass = 0;
player->team = 0;
//Add player to list
int id = getPlayerId(inet_ntoa(player->connection.sin_addr));
player->id = id;
_PlayerTable.insert(std::pair<int, Player>(id, *player));
newPlayer = *player;
return player->id;
}
/**
* Static function used by client_library.cpp to create a reading thread to handle one client
* @author Jerry Jia
* @date 2016-03-11
* @param server ServerTCP object
* @return ServerTCP::Receive() address
*/
void * ServerTCP::CreateClientManager(void * server)
{
return ((ServerTCP *)server)->Receive();
}
/**
* Continuosly recieves messages from a specific client
* @author Jerry Jia, Martin Minkov
* @date 2016-03-11
* @return 0 for thread execution code
*/
void * ServerTCP::Receive()
{
Player tmpPlayer = newPlayer;
int BytesRead;
char * buf; /* buffer read from one recv call */
buf = (char *)malloc(PACKETLEN); /* allocates memory */
while (1)
{
BytesRead = recv (tmpPlayer.socket, buf, PACKETLEN, 0);
/* recv() failed */
if(BytesRead < 0)
{
if(errno == EINTR)
continue;
printf("recv() failed with errno: %d", errno);
return 0;
}
/* client disconnected */
if(BytesRead == 0)
{
sprintf(buf, "Player %d has left the lobby \n", tmpPlayer.id);
printf("%s", buf);
//Send all players that this player has left
this->ServerTCP::Broadcast(buf);
//Remove player from player list
_PlayerTable.erase(tmpPlayer.id);
return 0;
}
//Handle Data Received
this->ServerTCP::CheckServerRequest(tmpPlayer, buf);
}
free(buf);
return 0;
}
/*
Sends a message to all the clients
@author Jerry Jia, Gabriella Chueng
@date 2016-03-11
@param message [description]
Revision:
Date Author Description
2016-03-10 Gabriel Lee Add functionality to add exception to broadcast
*/
void ServerTCP::Broadcast(const char* message, sockaddr_in * excpt)
{
Player tmpPlayer;
std::cout << "In BroadCast(): " << message << std::endl;
for(const auto &pair : _PlayerTable)
{
tmpPlayer = pair.second;
if(send(tmpPlayer.socket, message, PACKETLEN, 0) == -1)
{
std::cerr << "Broadcast() failed for player id: " << pair.first << std::endl;
std::cerr << "errno: " << errno << std::endl;
return;
}
}
}
/**
* Sends a message to a specific client
* @author Martin Minkov, Scott Plummer
* @date 2016-03-11
* @param player Player to send
* @param message message to send
*/
void ServerTCP::sendToClient(Player player, const char * message)
{
if(send(player.socket, message, PACKETLEN, 0) == -1)
{
std::cerr << "Broadcast() failed for player id: " << player.id << std::endl;
std::cerr << "errno: " << errno << std::endl;
return;
}
}
/*
Prepares the PlayerList with 24 invalid players, required to make sure
that the socket is set to -1 if the socket is not being used for the
function SelectRecv.
Programmer: Vivek Kalia, Tyler Trepanier-Bracken
*/
void ServerTCP::PrepareSelect() // UNTESTED!!!!! DO NOT USE YET!
{
/*
Player _bad;
//Initialize all components to be invalid!
_bad.socket = -1;
bzero((char *)&_bad.connection, sizeof(struct sockaddr_in));
_bad.id = -1;
memset(_bad.username, 0, sizeof(_bad.username));
_bad.team = -1;
_bad.playerClass = -1;
_bad.isReady = false;
fprintf(stderr, "[UDP Socket:%d]\n", _UDPReceivingSocket);
_maxfd = _UDPReceivingSocket;
_maxi = -1;
//Initialize the Player list to bad values.
std::vector<Player> _clients(24, _bad); //TODO Define 24 as a constant variable
_PlayerList = _clients;
FD_ZERO(&_allset);
FD_SET(_UDPReceivingSocket, &_allset);
*/
}
/*
Thread that forever reads in data from all clients.
Programmer: Unknown
Revisions: Vivek Kalia, Tyler Trepanier-Bracken 2016/03/09
Added in select functionality
*/
int ServerTCP::SetSocketOpt()
{
/*
// UNTESTED!!!!!!!!
// set SO_REUSEADDR so port can be resused imemediately after exit, i.e., after CTRL-c
int flag = 1;
if (setsockopt (_UDPReceivingSocket, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag)) == -1)
{
fatal("setsockopt");
return -1;
}*/
return 0;
}
/**
* Parse client json message and determines server logic
* @author Jerry Jia, Martin Minkov, Scott Plummer, Dylan Blake
* @date 2016-03-11
* @param player Player that recives the message
* @param buffer json message
*/
void ServerTCP::CheckServerRequest(Player player, char * buffer)
{
std::string error;
Json json = Json::parse(buffer, error).array_items()[0];
if (json["DataType"].int_value() != Networking)
return;
switch(json["ID"].int_value())
{
//Player joining team request
case TeamChangeRequest:
std::cout << "Team change: " << json[TeamID].int_value() << std::endl;
_PlayerTable[player.id].team = json[TeamID].int_value();
this->ServerTCP::Broadcast(buffer);
break;
//Player joining class request
case ClassChangeRequest:
std::cout << "Class change: " << json[ClassID].int_value() << std::endl;
_PlayerTable [player.id].playerClass = json[ClassID].int_value();
this->ServerTCP::Broadcast(buffer);
break;
//Player making a ready request
case ReadyRequest:
std::cout << "Ready change: " << (json[Ready].int_value() ? "ready" : "not ready") << std::endl;
_PlayerTable[player.id].isReady = (json[Ready].int_value() ? true : false);
this->ServerTCP::Broadcast(buffer);
break;
//New Player has joined lobby
case PlayerJoinedLobby:
std::cout << "New Player Change: " << json[UserName].string_value() << std::endl;
strcpy(_PlayerTable[player.id].username, json[UserName].string_value().c_str());
//Send player a table of players
sendToClient(player, constructPlayerTable().c_str());
//Create packet and send to everyone
this->ServerTCP::Broadcast(UpdateID(_PlayerTable[player.id]).c_str());
break;
case PlayerLeftLobby:
std::cout << "Player: " << json[PlayerID].int_value() << " has left the lobby" << std::endl;
_PlayerTable.erase(json[PlayerID].int_value());
this->ServerTCP::Broadcast(buffer);
break;
case GameStart:
std::cout << "Player: " << json[PlayerID].int_value() << " has started the game" << std::endl;
//All players in lobby are ready
if (this->ServerTCP::AllPlayersReady())
{
this->ServerTCP::Broadcast(buffer);
this->ServerTCP::Broadcast(generateMapSeed().c_str());
kill(getpid(), SIGTERM);
}
break;
}
}
/**
* Takes in a buffer holding the JSON string received from the client and formats the data into
* the variables that are passed in to be used in other function
* @author Martin Minkov
* @date 2016-03-11
* @param buffer [description]
* @param DataType [description]
* @param ID [description]
* @param IDValue [description]
* @param username [description]
*/
void ServerTCP::parseServerRequest(char* buffer, int& DataType, int& ID, int& IDValue, std::string& username)
{
std::string packet(buffer);
std::string error;
//Parse buffer as JSON array
Json json = Json::parse(packet, error).array_items()[0];
//Parse failed
if (!error.empty())
{
printf("Failed: %s\n", error.c_str());
return;
}
//Parsing data in JSON object
DataType = json["DataType"].int_value();
ID = json["ID"].int_value();
IDValue = json["TeamID"].int_value(); //Check if player is making a team request
if (IDValue == 0)
IDValue = json["ClassID"].int_value(); //Check if player is making a class request
username = json["UserName"].string_value();
}
/**
* Check if all the players within _ClientTable are ready
* @author ???
* @date 2016-03-11
* @return true if all the players are ready, false otherwise
*/
bool ServerTCP::AllPlayersReady()
{
Player tmpPlayer;
for(const auto &pair : _PlayerTable)
{
tmpPlayer = pair.second;
if(tmpPlayer.isReady == false)
{
printf("Player %d is not ready\n", tmpPlayer.id);
return false;
} else {
printf("Player %d is ready\n", tmpPlayer.id);
}
}
return true;
}
/**
* Constructs a json message containing an array of current player's statuses
* @author Martin Minkov, Scott Plummer, Jerry Jia
* @date 2016-03-11
* @return the constructed json table
*/
std::string ServerTCP::constructPlayerTable()
{
std::string packet = "[{\"DataType\" : 6, \"ID\" : 6, \"LobbyData\" : [";
for (auto it = _PlayerTable.begin(); it != _PlayerTable.end();)
{
std::string tempUserName((it->second).username);
packet += "{";
packet += "PlayerID: " + std::to_string(it->first);
packet += ", UserName : \"" + tempUserName + "\"";
packet += ", TeamID : " + std::to_string((it->second).team);
packet += ", ClassID : " + std::to_string((it->second).playerClass);
packet += ", Ready : " + std::to_string(Server::isReadyToInt(it->second));
packet += (++it == _PlayerTable.end() ? "}" : "},");
}
packet += "]";
packet += "}]";
std::cout << "THIS IS OUR PACKET THAT WE ARE SENDING" << packet << std::endl;
return packet;
}
/**
* Returns the registered player list from the game lobby
* @author Martin Minkov, Scott Plummer
* @date 2016-03-11
* @param player player object
* @return updated json with the player's id
*/
std::string ServerTCP::UpdateID(const Player& player)
{
char buf[PACKETLEN];
std::cout << player.username << std::endl;
sprintf(buf, "[{\"DataType\" : 6, \"ID\" : 4, \"PlayerID\" : %d, \"UserName\" : \"%s\"}]", player.id, player.username);
std::string temp(buf);
std::cout << "IN UPDATE ID: " << temp << std::endl;
return temp;
}
/**
* [ServerTCP::generateMapSeed description]
* @author ???
* @date 2016-03-11
* @return [description]
*/
std::string ServerTCP::generateMapSeed()
{
int mapSeed;
srand (time (NULL));
mapSeed = rand ();
std::string packet = "[{\"DataType\" : 3, \"ID\" : 0, \"Seed\" : " + std::to_string(mapSeed) +"}]";
return packet;
}
/**
* ???
*/
std::map<int, Player> ServerTCP::getPlayerTable()
{
return _PlayerTable;
}
/**
* [ServerTCP::getPlayerId description]
* @author ???
* @date 2016-03-11
* @param ipString [description]
* @return [description]
*/
int ServerTCP::getPlayerId(std::string ipString)
{
std::size_t index = ipString.find_last_of(".");
return stoi(ipString.substr(index+1));
}
| true |
932faa8de4efc4222b881d86f150f8a542452101 | C++ | LynnnnnnnYang/LeetCode_Solution | /PalindromeNumber.cpp | UTF-8 | 901 | 3.59375 | 4 | [] | no_license | // @Source : https://leetcode.com/problems/palindrome-number/
// @Author : LynnnnnnnYang
// @Date : 2016-08-09
/**********************************************************************************
* 9.Palindrome Number
* Determine whether an integer is a palindrome.
* Do this without extra space.
**********************************************************************************/
#include <iostream>
using namespace std;
class Solution {
public:
bool isPalindrome(int x)
{
// Special Cases
if(x<0) return 0;
int base;
for(base=1;x/base>9;base*=10);
while(x)
{
if(x/base != x%10) return 0;
x = (x % base) / 10;
base /= 100;
}
return 1;
}
};
int PalindromeNumber_main()
//int main()
{
Solution sol;
int n;
cin >> n;
cout<<n<<" is Palindrome number? "<<sol.isPalindrome(n)<<endl;
system("pause");
return 0;
} | true |
96c7acff99e0d26cf258af7623319613a441a4eb | C++ | sushaoxiang911/interview | /LeetCodeMobileProblems/CombinationSumOnce/combination_sum_once.cpp | UTF-8 | 1,250 | 3.296875 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void recursion (vector<vector<int> > &ans, vector<int> &candidates, vector<int> &num, int k,
int sum, int target) {
if (k >= candidates.size() || sum > target)
return;
int current_can = candidates[k];
int i = k;
while (candidates[i] == current_can)
++i;
recursion(ans, candidates, num, i, sum, target);
num.push_back(current_can);
sum += current_can;
if (sum == target) {
ans.push_back(num);
}
recursion(ans, candidates, num, k+1, sum, target);
num.pop_back();
}
vector<vector<int> > find_combination(vector<int> &candidates, int target) {
sort(candidates.begin(), candidates.end());
vector<vector<int> > ans;
vector<int> num;
int sum = 0;
recursion(ans, candidates, num, 0, sum, target);
return ans;
}
int main() {
vector<int> candidates {10, 1, 2, 7, 6, 1, 5};
vector<vector<int> > result = find_combination (candidates, 8);
cout << "result: " << endl;
for (int i = 0; i < result.size(); ++i) {
for (int j = 0; j < result[i].size(); ++j) {
cout << result[i][j] << " ";
}
cout << endl;
}
}
| true |
550c7e3ddb211a79ad99036e7f20dc728da58833 | C++ | snowyoneill/CTCI | /4.8/4.8.cpp | UTF-8 | 1,378 | 3.640625 | 4 | [] | no_license | #include <iostream>
#include "BinaryTree.h"
template <class T>
bool treesMatch(Node<T> *n1, Node<T> *n2)
{
if(n1 == NULL && n2 == NULL) return true;
/*
* if((n1 == NULL && n2 != NULL) || (n1 != NULL && n2 == NULL))
* unnecessary as we have already checked above if the 2 nodes are equal.
*/
if(n1 == NULL || n2 == NULL)
return false;
if(n1->val != n2->val) return false;
return treesMatch(n1->left, n2->left) && treesMatch(n1->right, n2->right);
}
template <class T>
bool isSubTree(Node<T> *T1, Node<T> *T2)
{
if(T1 == NULL) return true;
if(T1->val == T2->val)
return treesMatch(T1, T2);
return isSubTree(T1->left, T2) || isSubTree(T1->right, T2);
}
int main()
{
{
Node<int> bTree1(1), bTree2(1);
bTree1.left = new Node<int>(2);
bTree1.right = new Node<int>(3);
bTree2.left = new Node<int>(2);
bTree2.right = new Node<int>(3);
bTree2.left->left = new Node<int>(4);
std::cout << treesMatch(&bTree1, &bTree2) << std::endl;
}
//------------------------------------------------------
{
Node<int> bTree1(2), bTree2(1);
bTree1.left = new Node<int>(1);
bTree1.right = new Node<int>(10);
bTree1.left->left = new Node<int>(2);
bTree1.left->right = new Node<int>(3);
bTree2.left = new Node<int>(2);
bTree2.right = new Node<int>(3);
std::cout << isSubTree(&bTree1, &bTree2) << std::endl;
}
return 0;
} | true |
ebcd7bd6537f543f34c475dd9f4b2c21348396a1 | C++ | Jin22/Chamber-Crawler-3000 | /A5CC3K/A5CC3K-master-50c858ec25aff912f0d47906ff55d0f7a4192e67/grid.cc | UTF-8 | 4,597 | 2.953125 | 3 | [] | no_license | #include "grid.h"
#include "posn.h"
#include <fstream>
#include "entity.h"
#include "player.h"
#include "treasure.h"
using namespace std;
const char * MyMapNotFoundException::what() const noexcept {
return "Tried to load a non existent map";
}
Grid::Grid(): theGrid{vector<vector<Cell>>()}, chambers{vector<vector<Cell *>>()},
td(new TextDisplay()),level{0} {}
void Grid::init(const string &fname, const int n) {
vector<vector<Cell>> newGrid; // Temporary vector used to build the new grid
string s;
ifstream inFile(fname);
if (!inFile.is_open()) {
throw MyMapNotFoundException();
}
int row = 0;
while (getline(inFile, s)) {
int col = 0;
newGrid.push_back(vector<Cell>());
vector<Cell> &v = newGrid.back();
for (auto it = s.begin(); it != s.end(); it++) {
switch (*it) {
case '|' : v.push_back(Cell(row, col, Terrain::VertWall)); break;
case '-' : v.push_back(Cell(row, col, Terrain::HoriWall)); break;
case '.' : v.push_back(Cell(row, col, Terrain::ChamFloor)); break;
case '#' : v.push_back(Cell(row, col, Terrain::PassFloor)); break;
case '+' : v.push_back(Cell(row, col, Terrain::Door)); break;
default : v.push_back(Cell(row, col, Terrain::Empty)); break;
}
col++;
}
row++;
}
theGrid.swap(newGrid);
level = n;
findChambers();
td->buildDisplay(*this);
}
// Helper function for find_Chambers. Recursively sets cell and all
// chamberFloor neighbours of cell to be in chamber n.
void Grid::assignChamber(Posn p, int n) {
Cell &cell = getCell(p);
if (cell.getTerrain() != Terrain::ChamFloor || cell.getChamber() != 0) {
return;
} else {
cell.setChamber(n);
int r = cell.getRow(), c = cell.getCol();
// in a properly formed map, Chamber floors will never be on the edges
for (int i = (r - 1); i <= (r + 1); i++) {
for (int j = (c - 1); j <= (c + 1); j++) {
assignChamber({i, j}, n);
}
}
}
}
// Helper function for init. Used after Grid is setup to sort cells into
// chambers
void Grid::findChambers() {
vector<vector<Cell *>> newChambers; // Tmp vector for new chambers
for (auto row = theGrid.begin(); row != theGrid.end(); row++) {
for (auto col = row->begin(); col != row->end(); col++) {
if (col->getTerrain() == Terrain::ChamFloor &&
col->getChamber() == 0) { // current cell is chamFloor and not sorted
int nextChamberNum = newChambers.size() + 1;
assignChamber({col->getRow(), col->getCol()}, nextChamberNum);
newChambers.push_back(vector<Cell *>());
newChambers.back().push_back(&(*col));
} else if (col->getChamber() != 0) {
newChambers[col->getChamber() - 1].push_back(&(*col));
}
}
}
chambers.swap(newChambers);
}
vector<vector<Cell *>> & Grid::getChambers() {
return chambers;
}
int Grid::getLevel() const {
return level;
}
void Grid::levelUp() {
level++;
}
void Grid::moveEntity(Posn src, Posn dest) {
Cell &sCell = getCell(src);
Cell &dCell = getCell(dest);
shared_ptr<Entity> onSrc = sCell.getOccupant();
shared_ptr<Entity> onDest = dCell.getOccupant();
shared_ptr<Treasure> putOnSrc;
if (Player*p = dynamic_cast<Player *>(onSrc.get())) {
putOnSrc = p->getOnGold();
p->setOnGold(nullptr);
}
if (onDest) {
onDest->beSteppedOn(*onSrc);
}
dCell.setOccupant(onSrc);
onSrc->setPos(dest);
sCell.setOccupant(putOnSrc);
td->update(getCell(src));
td->update(getCell(dest));
}
void Grid::placeEntity(const shared_ptr<Entity> &e, Posn placeHere) {
e->setPos(placeHere);
getCell(placeHere).setOccupant(e);
td->update(getCell(placeHere));
}
void Grid::removeEntity(Posn remFrom) {
getCell(remFrom).getOccupant()->setPos({-1, -1});
getCell(remFrom).setOccupant(nullptr);
td->update(getCell(remFrom));
}
int Grid::getWidth() const {
if (theGrid.size()) {
return theGrid[0].size();
}else {
return 0;
}
}
int Grid::getHeight() const {
return theGrid.size();
}
Cell & Grid::getCell(Posn p) {
return theGrid[p.r][p.c];
}
void Grid::placeStairs(Posn p) {
getCell(p).makeStairs();
td->update(getCell(p));
}
bool Grid::hasUsable(Posn p) const {
return theGrid[p.r][p.c].hasUsable();
}
ostream &operator<<(ostream &out, const Grid &g) {
return out << *(g.td);
}
bool Grid::canStep(Posn p, const Entity &e) const{
return theGrid[p.r][p.c].canStepHere(e);
}
void Grid::clear() {
int size = theGrid.size();
for (int i = 0; i < size; ++i) {
theGrid[i].clear();
}
theGrid.clear();
}
| true |
04e9fed2aa8654dc6d5aaf8b76e1b6df9dc8821e | C++ | marththex/Data_Structures | /MarcusChong_5/RollOver.cpp | UTF-8 | 2,244 | 3.0625 | 3 | [] | no_license | #include <iostream>
#include <string>
#include "RollOver.h"
using namespace std;
RollOver::RollOver()
{
id = -1;
id2 = -1;
advisor = -1;
name = "";
level = "";
major = "";
department = "";
GPA = -1.0;
undo = -1;
}
RollOver::RollOver(int m_id, string m_name, string m_level, string m_major, double m_GPA, int m_advisor, int m_undo)//STUDENT
{
id = m_id;
id2 = -1;
advisor = m_advisor;
name = m_name;
level = m_level;
major = m_major;
department ="NO DEPARTMENT";
GPA = m_GPA;
undo = m_undo;
}
RollOver::RollOver(int m_id, string m_name, string m_level, string m_department, int m_undo)//FACULTY
{
id = m_id;
id2 = -1;
advisor = -1;
name = m_name;
level = m_level;
major = "NO MAJOR";
department = m_department;
GPA = -1.0;
undo = m_undo;
}
RollOver::RollOver(int m_id, int m_id2, int m_undo)//FACULTY
{
id = m_id;
id2 = m_id2;
advisor = -1;
name = "NO NAME";
level = "NO LEVEL";
major = "NO MAJOR";
department = "NO DEPARTMENT";
GPA = -1.0;
undo = m_undo;
}
RollOver::RollOver(int m_id, int m_id2, int m_advisor, int m_undo)//FACULTY
{
id = m_id;
id2 = m_id2;
advisor = m_advisor;
name = "NO NAME";
level = "NO LEVEL";
major = "NO MAJOR";
department = "NO DEPARTMENT";
GPA = -1.0;
undo = m_undo;
}
RollOver::~RollOver()
{
}
int RollOver::getID()
{
return id;
}
int RollOver::getID2()
{
return id2;
}
string RollOver::getName()
{
return name;
}
string RollOver::getLevel()
{
return level;
}
string RollOver::getMajor()
{
return major;
}
double RollOver::getGPA()
{
return GPA;
}
int RollOver::getAdvisor()
{
return advisor;
}
string RollOver::getDepartment()
{
return department;
}
int RollOver::getUndo()
{
return undo;
}
void RollOver::setID(int m_id)
{
id = m_id;
}
void RollOver::setID2(int m_id2)
{
id2 = m_id2;
}
void RollOver:: setName(string m_name)
{
name = m_name;
}
void RollOver:: setLevel(string m_level)
{
level = m_level;
}
void RollOver:: setMajor(string m_major)
{
major = m_major;
}
void RollOver:: setGPA(double m_GPA)
{
GPA = m_GPA;
}
void RollOver:: setAdvisor(int m_advisor)
{
advisor = m_advisor;
}
void RollOver:: setDepartment(string m_department)
{
department = m_department;
}
void RollOver::setUndo(int m_undo)
{
undo = m_undo;
}
| true |
f44015f8b38c95ec5a91f50efadffa1c13427cd9 | C++ | brhaka/libftTester | /tests/ft_strrchr_test.cpp | UTF-8 | 676 | 2.5625 | 3 | [] | no_license | extern "C"
{
#define new tripouille
#include "libft.h"
#undef new
}
#include "sigsegv.hpp"
#include "check.hpp"
#include "leaks.hpp"
#include <string.h>
int iTest = 1;
int main(void)
{
signal(SIGSEGV, sigsegv);
title("ft_strrchr\t: ")
char s[] = "tripouille";
char s2[] = "ltripouiel";
/* 1 */ check(ft_strrchr(s, 't') == s); showLeaks();
/* 2 */ check(ft_strrchr(s, 'l') == s + 8); showLeaks();
/* 3 */ check(ft_strrchr(s2, 'l') == s2 + 9); showLeaks();
/* 4 */ check(ft_strrchr(s, 'z') == 0); showLeaks();
/* 5 */ check(ft_strrchr(s, 0) == s + strlen(s)); showLeaks();
/* 6 */ check(ft_strrchr(s, 't' + 256) == s); showLeaks();
write(1, "\n", 1);
return (0);
} | true |
dfd08ce62c70b22543cd37cb8c0c682f4d75e909 | C++ | wo315/peercode | /hw2/mass_spring_705.hpp | UTF-8 | 4,950 | 3.421875 | 3 | [] | no_license | /**
* @file mass_spring.hpp
* Implementation of mass-spring system using Graph
*/
#include <fstream>
#include <chrono>
#include <thread>
#include "CME212/Util.hpp"
#include "CME212/Color.hpp"
#include "CME212/Point.hpp"
#include "Graph.hpp"
// Gravity in meters/sec^2
static constexpr double grav = 9.81;
/** Custom structure of data to store with Nodes */
struct NodeData {
Point vel; //< Node velocity
double mass; //< Node mass
NodeData() : vel(0), mass(1) {}
};
// Define the Graph type
using GraphType = Graph<NodeData, double>;
using Node = typename GraphType::node_type;
using Edge = typename GraphType::edge_type;
/** Change a graph's nodes according to a step of the symplectic Euler
* method with the given node force.
* @param[in,out] g Graph
* @param[in] t The current time (useful for time-dependent forces)
* @param[in] dt The time step
* @param[in] force Function object defining the force per node
* @return the next time step (usually @a t + @a dt)
*
* @tparam G::node_value_type supports ???????? YOU CHOOSE
* @tparam F is a function object called as @a force(n, @a t),
* where n is a node of the graph and @a t is the current time.
* @a force must return a Point representing the force vector on
* Node n at time @a t.
*/
template <typename G, typename F>
double symp_euler_step(G& g, double t, double dt, F force) {
// Compute the t+dt position
for (auto it = g.node_begin(); it != g.node_end(); ++it) {
auto n = *it;
// Update the position of the node according to its velocity
// x^{n+1} = x^{n} + v^{n} * dt
n.position() += n.value().vel * dt;
}
// Compute the t+dt velocity
for (auto it = g.node_begin(); it != g.node_end(); ++it) {
auto n = *it;
// v^{n+1} = v^{n} + F(x^{n+1},t) * dt / m
n.value().vel += force(n, t) * (dt / n.value().mass);
}
return t + dt;
}
class Force{
public:
template <typename Node>
Force(Node p):force_(p){};
virtual Point operator()(double t) {
(void)t;
return Point(0); }
protected:
Node force_;
};
class GravityForce: public Force{
public:
template <typename Node>
GravityForce(Node n1): Force(n1){ };
virtual Point operator()(double t){
(void)t;
return force_.value().mass * Point(0,0,-grav);
}
};
class MassSpringForce: public Force{
public:
template <typename Node>
MassSpringForce(Node n1): Force(n1){};
virtual Point operator()(double t){
(void)t;
unsigned K=100;
Point f_spring=Point(0);
Point n_pos=force_.position();
for(auto it=force_.edge_begin(); it!=force_.edge_end(); ++it){
Node j=(*it).node2();
Point j_pos=j.position();
double L=(*it).value();
Point temp=-(K*(n_pos-j_pos)/norm(n_pos-j_pos))*(norm(n_pos-j_pos)-L);
f_spring=f_spring+temp;
}
return f_spring;
}
};
class DampingForce: public Force{
public:
template <typename Node>
DampingForce(Node n1): Force(n1), c(1.0){};
DampingForce(Node n1, double x): Force(n1), c(x){};
virtual Point operator()(double t){
(void)t;
return -force_.value().vel * c;
}
private:
double c;
};
struct CombinedForce{
CombinedForce(std::vector<Force*> f): forcevec(f){};
Point operator()(Node n, double t){
(void)t;
Point total=n.position();
for (auto it=forcevec.begin(); it!=forcevec.end(); ++it){
auto cur=*it;
total=total+cur(1.0);
}
return total;
}
private:
std::vector<Force*> forcevec;
};
template<typename force1, typename force2>
CombinedForce make_combined_force(force1 f1, force2 f2){
std::vector<Force*> f;
f.push_back(&f1);
f.push_back(&f2);
return CombinedForce(f);
}
template<typename force1, typename force2, typename force3>
CombinedForce make_combined_force(force1 f1, force2 f2, force3 f3){
std::vector<Force*> f;
f.push_back(&f1);
f.push_back(&f2);
f.push_back(&f3);
return CombinedForce(f);
}
// This does not work. But I cannot figure out why..
/** Force function object for HW2 #1. */
struct Problem1Force {
/** Return the force applying to @a n at time @a t.
*
* For HW2 #1, this is a combination of mass-spring force and gravity,
* except that points at (0, 0, 0) and (1, 0, 0) never move. We can
* model that by returning a zero-valued force. */
template <typename NODE>
Point operator()(NODE n, double t) {
(void)t;
if(n.position()==Point(0,0,0)||n.position()==Point(1,0,0)){
return Point(0,0,0);
}
unsigned K=100;
Point f_spring=Point(0);
Point n_pos=n.position();
for(auto it=n.edge_begin(); it!=n.edge_end(); ++it){
Node j=(*it).node2();
Point j_pos=j.position();
double L=(*it).value();
Point temp=-(K*(n_pos-j_pos)/norm(n_pos-j_pos))*(norm(n_pos-j_pos)-L);
f_spring=f_spring+temp;
}
Point cur=n.value().mass*Point(0,0,-grav);
Point f=f_spring+cur;
return f;
}
};
| true |
4fd9ff2bb5f1516a8b4f2785fc0af047b96d5098 | C++ | akotadi/Competitive-Programming | /Interview/Reference/binaryTreeIterativePostorderTraversal.cpp | UTF-8 | 1,192 | 3.796875 | 4 | [] | no_license | /**
* Binary Tree Iterative Postorder Traversal algorithm, visit the nodes
* according to the requirement, recursively uses the memory stack to
* visit all the nodes
*
* @Complexity
* Time O(n)
* Space O(n)
*
* @Identify:
*
* @Practice:
* - Binary Tree Postorder Traversal
*/
vector<int> postorderTraversal(TreeNode *root) {
auto result = vector<int>();
if (!root) return result;
auto traverse = stack<TreeNode *>();
TreeNode *current = root, * last = nullptr;
while (current || !traverse.empty()) {
if (current) {
traverse.push(current);
current = current -> left;
} else {
auto check = traverse.top();
if (check->right && last != check->right)
current = check -> right;
else {
result.push_back(check->val);
last = check;
traverse.pop();
}
}
}
return result;
}
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
| true |
b57c8a30ea9b9dc21470f70059fccfa2d3d57ee8 | C++ | WillPickard/commerce-simulation | /Product.cpp | UTF-8 | 2,094 | 3.1875 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <iomanip>
#include <sstream>
#include "Product.h"
using namespace std;
void Product::setDescription(const string & description){
description_ = description;
};
void Product::setSKU(const string & sku){
sku_ = sku;
};
void Product::setQuantity(int quantity){
quantity_ = quantity;
};
void Product::setTargetQuantity(int quantity){
targetQuantity_ = quantity;
};
void Product::setPrice(float price){
price_ = price;
};
void Product::setSize(float size){
size_ = size;
};
void Product::setUnits(const string & units){
units_ = units;
};
const string & Product::getDescription() const {
return description_;
};
const string & Product::getSKU() const {
return sku_;
};
float Product::getPrice() const {
return price_;
};
int Product::getQuantity() const {
return quantity_;
};
int Product::getTargetQuantity() const {
return targetQuantity_;
};
const string & Product::getUnits() const {
return units_;
};
float Product::getSize() const {
return size_;
};
void Product::getInfo() {
string desc;
string sku;
int quant;
float pric;
float siz;
string unts;
cout << "Description:"; cin >> desc;
setDescription(desc);
cout << "SKU:"; cin >> sku;
setSKU(sku);
cout << "Quantity:"; cin >> quant;
setQuantity(quant);
cout << "Price:"; cin >> pric;
setPrice(pric);
cout << "Size:"; cin >> siz;
setSize(siz);
cout << "Units:"; cin >> unts;
setUnits(unts);
cout << listItem() << endl << endl;
}
string Product::listItem() const {
ostringstream returnString;
returnString << setw(4) << getQuantity()
<< " of " << left << setw(20) << getDescription();
ostringstream amountString;
amountString << " (" << setw(4) << getSize() << " " << setw(6) << getUnits() << ")";
returnString << setw(8) << amountString.str()
<< " at $";
returnString << fixed << setprecision(2);
returnString << setiosflags(ios::right|ios::fixed) << setw(6) << getPrice()
<< " (" << setw(5) << getSKU() << ")";
return returnString.str();
};
| true |
a497db44c59c43f73b4fe0c6d7e56413d8a65751 | C++ | imclab/newton | /tools/sfccon/Huff1.cpp | UTF-8 | 10,815 | 2.53125 | 3 | [] | no_license | /**************************************************************************
* *
* HUFF1.C: Huffman Compression Program. *
* 14-August-1990 Bill Demas Version 1.0 *
* *
* This program compresses a file using the Huffman codes. *
* *
* USAGE: HUFF1 <input file> <output file> *
* *
* (DISK to DISK: Input direct from disk, output direct to disk) *
**************************************************************************/
#include <vector>
#include <map>
#include "compress.h"
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#define VERBOSE /* If defined, prints verbose
program progress when it's
running... */
short father[512];
unsigned short code[256], heap_length;
unsigned long compress_charcount, heap[257];
unsigned char code_length[256];
long frequency_count[512];
//FILE *ifile, *ofile;
void reheap (unsigned short heap_entry);
/**************************************************************************
MAIN ()
This is the main program. It performs the Huffman encoding procedure in
5 separate steps.
I know that this program can be made more compact & faster, but I was more
interested in UNDERSTANDABILITY !!!
**************************************************************************/
/*
void main (argc, argv)
int argc;
char *argv[];
{
unsigned short generate_code_table ();
void build_code_tree (), build_initial_heap ();
void compress_image (), compression_report ();
void get_frequency_count ();
if (argc == 3)
{
printf ("\nHUFF1: Huffman Code Compression Program.");
printf ("\n 14-Aug-90 Bill Demas. Version 1.0\n\n");
if ((ifile = fopen (argv[1], "rb")) != NULL)
{
fseek (ifile, 0L, 2);
file_size = (unsigned long) ftell (ifile);
#ifdef VERBOSE
printf ("(1) Getting Frequency Counts.\n");
#endif
fseek (ifile, 0L, 0);
get_frequency_count ();
#ifdef VERBOSE
printf ("(2) Building Initial Heap.\n");
#endif
build_initial_heap ();
#ifdef VERBOSE
printf ("(3) Building the Code Tree.\n");
#endif
build_code_tree ();
#ifdef VERBOSE
printf ("(4) Generating the Code Table.\n");
#endif
if (!generate_code_table ())
printf ("ERROR! Code Value Out of Range. Cannot Compress.\n");
else
{
#ifdef VERBOSE
printf ("(5) Compressing & Creating the Output File.\n");
#endif
if ((ofile = fopen (argv[2], "wb")) != NULL)
{
fwrite (&file_size, sizeof (file_size), 1, ofile);
fwrite (code, 2, 256, ofile);
fwrite (code_length, 1, 256, ofile);
fseek (ifile, 0L, 0);
compress_image ();
fclose (ofile);
}
else
printf("\nERROR: Couldn't create output file %s\n", argv[2]);
#ifdef VERBOSE
compression_report ();
#endif
}
fclose (ifile);
}
else
printf ("\nERROR: %s -- File not found!\n", argv[1]);
}
else
printf ("Usage: HUFF1 <input filename> <output filename>\n\n");
}
*/
/**************************************************************************
COMPRESS_IMAGE ()
This function performs the actual data compression.
**************************************************************************/
template<class T>
void compress_image (std::vector<unsigned char>& ofile, const T* ifile, int ifile_size)
{
register unsigned int thebyte = 0;
register short loop1;
register unsigned short current_code;
unsigned short current_length, dvalue;
unsigned long curbyte = 0;
short curbit = 7;
for (int loop = 0; loop < ifile_size; loop++)
{
dvalue = (unsigned short) ifile[loop];
current_code = code[dvalue];
current_length = (unsigned short) code_length[dvalue];
for (loop1 = current_length-1; loop1 >= 0; --loop1)
{
if ((current_code >> loop1) & 1)
thebyte |= (unsigned char) (1 << curbit);
if (--curbit < 0)
{
ofile.push_back(thebyte);
thebyte = 0;
curbyte++;
curbit = 7;
}
}
}
ofile.push_back(thebyte);
compress_charcount = ++curbyte;
}
/**************************************************************************
COMPRESSION_REPORT ()
This function displays the results of the compression sequence.
**************************************************************************/
/*
void compression_report ()
{
float savings;
unsigned short header_charcount;
unsigned long output_characters;
header_charcount = 768 + sizeof (file_size);
output_characters = (unsigned long) header_charcount +
compress_charcount;
printf ("\nRaw characters : %ld\n", file_size);
printf ("Header characters : %d\n", header_charcount);
printf ("Compressed characters : %ld\n", compress_charcount);
printf ("Total output characters : %ld\n", output_characters);
savings = 100 - ((float) output_characters / (float) file_size) * 100;
printf ("\nPercentage savings : %3.2f%%\n", savings);
}
*/
/**************************************************************************
GENERATE_CODE_TABLE ()
This function generates the compression code table.
**************************************************************************/
unsigned short generate_code_table ()
{
register unsigned short loop;
register unsigned short current_length;
register unsigned short current_bit;
unsigned short bitcode;
short parent;
for (loop = 0; loop < 256; loop++)
if (frequency_count[loop])
{
current_length = bitcode = 0;
current_bit = 1;
parent = father[loop];
while (parent)
{
if (parent < 0)
{
bitcode += current_bit;
parent = -parent;
}
parent = father[parent];
current_bit <<= 1;
current_length++;
}
code[loop] = bitcode;
if (current_length > 16)
return (0);
else
code_length[loop] = (unsigned char) current_length;
}
else
code[loop] = code_length[loop] = 0;
return (1);
}
/**************************************************************************
BUILD_CODE_TREE ()
This function builds the compression code tree.
**************************************************************************/
void build_code_tree ()
{
register unsigned short findex;
register unsigned long heap_value;
while (heap_length != 1)
{
heap_value = heap[1];
heap[1] = heap[heap_length--];
reheap (1);
findex = heap_length + 255;
frequency_count[findex] = frequency_count[heap[1]] +
frequency_count[heap_value];
father[heap_value] = findex;
father[heap[1]] = -findex;
heap[1] = findex;
reheap (1);
}
father[256] = 0;
}
/**************************************************************************
REHEAP ()
This function creates a "legal" heap from the current heap tree structure.
**************************************************************************/
void reheap (unsigned short heap_entry)
{
register unsigned short index;
register unsigned short flag = 1;
unsigned long heap_value;
heap_value = heap[heap_entry];
while ((heap_entry <= (heap_length >> 1)) && (flag))
{
index = heap_entry << 1;
if (index < heap_length)
if (frequency_count[heap[index]] >= frequency_count[heap[index+1]])
index++;
if (frequency_count[heap_value] < frequency_count[heap[index]])
flag--;
else
{
heap[heap_entry] = heap[index];
heap_entry = index;
}
}
heap[heap_entry] = heap_value;
}
/**************************************************************************
BUILD_INITIAL_HEAP ()
This function builds a heap from the initial frequency count data.
**************************************************************************/
void build_initial_heap ()
{
register unsigned short loop;
heap_length = 0;
for (loop = 0; loop < 256; loop++) {
if (frequency_count[loop]) {
heap[++heap_length] = (unsigned long) loop;
int hei = heap[1];
hei = hei;
}
}
for (loop = heap_length; loop > 0; loop--)
reheap (loop);
}
/**************************************************************************
GET_FREQUENCY_COUNT ()
This function counts the number of occurrences of each byte in the data
that are to be compressed.
**************************************************************************/
/*
void get_frequency_count ()
{
register unsigned long loop;
for (loop = 0; loop < file_size; loop++)
frequency_count[getc (ifile)]++;
}
*/
namespace comp {
void huff_getCodeMap(std::map<unsigned char, comp::HuffCode >& codeMap, const std::map<unsigned char, int>& frequency_count_in)
{
FORI(512) {
if (i<256 && frequency_count_in.count(i)) {
frequency_count[i] = frequency_count_in.find(i)->second;
} else {
frequency_count[i] = 0;
}
}
build_initial_heap ();
build_code_tree ();
if (!generate_code_table()) {
assert(0);
fprintf(stderr, "auuu too large in huffman!\n");
exit(1);
}
codeMap.clear();
FORI(256) {
HuffCode c;
c.code = code[i];
c.length = code_length[i];
if (c.length) codeMap[i] = c;
}
}
void huff_compress(std::vector<unsigned char>& ofile, std::map<unsigned char, comp::HuffCode >& codeMap, const unsigned char* ifile, int ifile_size) {
FORI(256) code[i]=0;
FORI(256) code_length[i]=0;
std::map<unsigned char, comp::HuffCode >::const_iterator iter;
for (iter=codeMap.begin(); iter!=codeMap.end(); iter++) {
int blah = iter->first;
const HuffCode& c = iter->second;
code[blah] = c.code;
code_length[blah] = c.length;
}
compress_image (ofile, ifile, ifile_size);
}
};
| true |
abc80f5cc9bf667e7f64bb1e6f440e69d49f0e6e | C++ | PurvaKar/40-Days-of-Code | /Day 27/Rotate List.cpp | UTF-8 | 766 | 3.328125 | 3 | [] | no_license | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
ListNode* Solution::rotateRight(ListNode* A, int B)
{
ListNode* temp = A;
ListNode* t =A;
int i, len=0;
if(temp==NULL)
return A;
while(temp->next!=NULL)
{
len++;
temp=temp->next;
}
len++;
B=B%len;
if(B==0)
return A;
else
{
len=len-B;
temp=A;
for(i=1;i<len;i++)
{
temp=temp->next;
}
t=temp->next;
temp->next=NULL;
temp=t;
while(t->next!=NULL)
{
t=t->next;
}
t->next=A;
A=temp;
}
return A;
}
| true |
40fa3e9c22e4e4158160a200d373a466bf6848c8 | C++ | tungfaifong/usrv | /src/unit_manager.cpp | UTF-8 | 2,133 | 2.84375 | 3 | [] | no_license | // Copyright (c) 2022 TungFai Fong <iam@tungfaifong.com>
#include "unit_manager.h"
#include <chrono>
#include <string>
#include "interfaces/logger_interface.h"
#include "util/time.h"
#include "unit.h"
NAMESPACE_OPEN
void UnitManager::Init(intvl_t interval)
{
_loop.Init(interval, [self = shared_from_this()](intvl_t interval){
return self->_Update(interval);
});
}
bool UnitManager::Register(const std::string & key, std::shared_ptr<Unit> && unit)
{
if(_units.find(key) != _units.end())
{
return false;
}
unit->OnRegister(shared_from_this());
_units[key] = std::move(unit);
return true;
}
std::shared_ptr<Unit> UnitManager::Get(const std::string & key)
{
if(_units.find(key) == _units.end())
{
return nullptr;
}
return _units[key];
}
bool UnitManager::Run()
{
auto ret = true;
ret = _Init() && _Start();
if(ret)
{
_loop.Run();
}
_Stop();
_Release();
_loop.Release();
return ret;
}
void UnitManager::SetExit(bool exit)
{
_loop.SetExit(exit);
}
intvl_t UnitManager::Interval()
{
return _loop.Interval();
}
void UnitManager::LoopNotify()
{
_loop.Notify();
}
bool UnitManager::_Init()
{
for(auto & [key, unit] : _units)
{
if(!unit->Init())
{
LOGGER_ERROR("UnitManager::Init {} fail", key);
return false;
}
LOGGER_INFO("UnitManager::Init {} success", key);
}
LOGGER_INFO("UnitManager::Init All units success");
return true;
}
bool UnitManager::_Start()
{
for (auto & [key, unit] : _units)
{
if (!unit->Start())
{
LOGGER_ERROR("UnitManager::_Start {} fail", key);
return false;
}
LOGGER_INFO("UnitManager::_Start {} success", key);
}
LOGGER_INFO("UnitManager::_Start All units success");
return true;
}
bool UnitManager::_Update(intvl_t interval)
{
auto busy = false;
for (auto & [key, unit] : _units)
{
busy |= unit->Update(interval);
}
return busy;
}
void UnitManager::_Stop()
{
for (auto & [key, unit] : _units)
{
unit->Stop();
LOGGER_INFO("UnitManager::_Stop {} success", key);
}
LOGGER_INFO("UnitManager::_Stop All units success");
}
void UnitManager::_Release()
{
for(auto & [key, unit] : _units)
{
unit->Release();
}
}
NAMESPACE_CLOSE
| true |
bb8965e093b35e3a5bfcb1d15bc1c518f6968098 | C++ | nareshenoy/base | /src/script/project_euler/12.cpp | UTF-8 | 642 | 3.109375 | 3 | [] | no_license | #include <iostream>
//int num_fac[20000];
int GetNumOfFactors(int n) {
int count = 0, i;
for(i = 1;i <= n;i ++) {
if(n % i == 0) count ++;
}
return count;
}
int main() {
int i = 1, num_fac;
int tri_num;
/*for(i = 0;i < 20000;i ++) {
num_fac[i] = -1;
}
i = 1;*/
while(1) {
if(i % 100 == 0) cout << i << endl;
tri_num = i * (i + 1) / 2;
if(i % 2 == 0) {
num_fac = GetNumOfFactors(i/2) * GetNumOfFactors(i + 1) - 1;
}
else {
num_fac = GetNumOfFactors((i + 1)/2) * GetNumOfFactors(i) - 1;
}
if(num_fac > 500) {
cout << tri_num << endl;
break;
}
i ++;
}
return 0;
}
| true |
f34c0484b674d0f6515adb15151012def8e5f9cd | C++ | sedevc/CarReg | /cars.cpp | UTF-8 | 1,583 | 3.359375 | 3 | [] | no_license |
#include "cars.h"
using namespace std;
bool cars::setRegnr(string y){ //accessors
if (y.size() != 6) {
cout << " (Wrong format! 6 chars )" << endl;
return false;
}
int tmp13 = 0, tmp46 = 0;
char tempChar[6];
for (int i = 0; i < 6; i++) { //convert string to char
tempChar[i] = y[i];
}
for (int i = 0; i < 3; i++) { //check if first 3 bytes is a-z or A-Z
for (int k = 65; k < 123; k++) {
if (k > 90 && k < 97) {
continue;
}
if ((int)tempChar[i] == k) {
tmp13++;
}
}
}
for (int i = 3; i < 6; i++) { //check if 3 last bytes is 0-9
for (int k = 48; k < 58; k++) {
if ((int)tempChar[i] == k) {
tmp46++;
}
}
}
if (tmp13 != 3 || tmp46 != 3) { //check if tempchar cont. 3chars and 3 digit.
cout << " (Wrong format! )" << endl;
return false;
}
regnr = y;
return true;
}
void cars::setManuf(string x){
manuf = x;
}
void cars::setModel(string x){
model = x;
}
void cars::setColor(string x){
color = x;
}
bool cars::setAwd(string x){
if (x == "yes" || x == "YES" || x == "no" || x == "NO") {
awd = x;
return true;
}
else{
cout << " Wrong format! (yes/no)" << endl;
return false;
}
}
bool cars::setPrice(int x){
if (x < 1) {
cout << " Price to low!" << endl;
return false;
}
price = x;
return true;
}
void cars::printDetail(){
cout << "Manufacturer: " << manuf << endl;
cout << "Model: " << model << endl;
cout << "Reg nr: " << regnr << endl;
cout << "Color: " << color << endl;
cout << "AWD: "; cout << awd << endl;
cout << "Price: " << price << endl << endl;
}
| true |
5f21ed9cace8678494597da7a696f8c2bbbc105d | C++ | TerrySoba/BlobbyThing | /src/MultiSpline.h | UTF-8 | 1,524 | 2.984375 | 3 | [] | no_license | /*
* MultiSpline.h
*
* Created on: 20.04.2012
* Author: yoshi252
*/
#ifndef MULTISPLINE_H_
#define MULTISPLINE_H_
#include "Spline.h"
#include <vector>
#include <array>
template <size_t _dimensions>
class MultiSpline {
public:
MultiSpline() {}
/*! \brief Set points for multispline
*
* The first element of the Matrix will be interpreted as the time variable.
* The following variables as the coordinate of the point in space.
*/
void setPoints(std::vector<Eigen::Matrix<double, _dimensions+1, 1>> coords) {
std::vector<Eigen::Vector2d> singleSplinePoints(coords.size());
// now create a spline for every dimension
for (size_t dim = 0; dim < _dimensions; dim++) {
for (size_t i = 0; i < coords.size(); i++) {
singleSplinePoints[i][0] = coords[i][0];
singleSplinePoints[i][1] = coords[i][dim+1];
}
splines[dim].setPoints(singleSplinePoints);
}
}
/*! \brief evaluate spline at given time
*
* See explanation of Spline::evaluate() for details.
*/
Eigen::Matrix<double, _dimensions, 1> evaluate(double time) {
Eigen::Matrix<double, _dimensions, 1> ret;
for (size_t dim = 0; dim < _dimensions; dim++) {
ret(dim) = splines[dim].evaluate(time);
}
return ret;
}
private:
Spline splines[_dimensions];
};
typedef MultiSpline<2> Spline2d;
typedef MultiSpline<3> Spline3d;
#endif /* MULTISPLINE_H_ */
| true |
6068fe8390cc199265ca1e733d010b8059f08265 | C++ | Guadalupe-Moreno/PAYMN | /Programas_C++/Factorial/factorial_b.cpp | UTF-8 | 355 | 2.75 | 3 | [] | no_license | #include<stdlib.h>
#include<stdio.h>
main(){
long int x, n, m;
printf("\n Dame un numero entero 'n':\n");
scanf("%i", &n);
x=0;
m=1;
while (x<n){
x=x+1;
m=m*x;
}
printf("\n\t Para n= %i", n);
printf("\n\t El factorial n! es: %i\n", m);
system("pause");
}
| true |
2f0b32ca3063cd033a7f77f5a88020b8be4df663 | C++ | douysu/algorithm | /algorithm_hufan/algorithm4_6.cpp | WINDOWS-1252 | 169 | 2.8125 | 3 | [] | no_license | #include <stdio.h>
//ݹ飬nĽ׳
int cal(int n){
if(n==1){
return 1;
}
return n*cal(n-1);
}
int main(){
int n=5;
printf("%d",cal(n));
return 0;
} | true |
6ee4f425c95d731fee8bd40dd049b351d05e4be5 | C++ | haebinKahng/codint_test_cpp | /9.모두의약수_솔루션.cpp | UTF-8 | 341 | 2.53125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
freopen("input.txt", "rt", stdin);
int n,i,j,a[1001];
scanf("%d", &n);
for (i=1;i<=n;i++)
{
a[i] = 0;
}
for (i=1;i<=n;i++)
{
for (j=i;j<=n;j+=i)//j=j+i
{
a[j]+=1;
//a[j]++;
}
}
for (i=1;i<=n;i++)
{
cout<<a[i]<<" ";
}
}
| true |
ba41dfa2e8fb7ba17ab321dbe834db5075ffa7ba | C++ | kuba34/PAMSI_project1 | /introsort.hpp | UTF-8 | 830 | 3.046875 | 3 | [] | no_license | #ifndef INTROSORT_HPP
#define INTROSORT_HPP
#include <vector>
#include "quicksort.hpp"
template<class T>
void heapify(std::vecor<T> &vec, const int left, const int right) {
int j, i=left;
while (i<=right/2)
{
j=2*i;
if (j+1<=right && vec[j+1]>vec[j])
j=j+1;
if (vec[i]<vec[j]) {
T tmp = vec[0];
vec[0] = vec[i];
vec[i] = tmp;
}
else
break;
i=j;
}
}
template<class T>
void heapsort(std::vector<T> &vec, const int left, const int right) {
int i;
for (i=N/2;i>0;i--) {
heapify(vec-1,i,N);
}
for (i=N-1; i>0; --i) {
T tmp = vec[0];
vec[0] = vec[i];
vec[i] = tmp;
heapify(vec-1,1,i);
}
}
template<class T>
void introsort(std::vector<T> &vec) {
}
| true |
d368b2a8ac78125b0f5da9e96bf1f9ca3ee06c18 | C++ | rein4ce/DeferredEngine | /src/Engine/Core/Camera.cpp | UTF-8 | 2,147 | 2.890625 | 3 | [] | no_license | #include "platform.h"
#include "Camera.h"
#include "Utils.h"
CCamera::CCamera(void) :
CObject3D(),
dV(Vector3(0,0,1)),
dU(Vector3(0,1,0))
{
position = Vector3(0,0,0);
rotation = Vector3(0,0,0);
forward = Vector3(0,0,1);
up = Vector3(0,1,0);
right = Vector3(1,0,0);
near = 0.1f;
far = 1000.0f;
CreateOrthographicView();
width = 0;
height = 0;
}
CCamera::~CCamera(void)
{
}
//////////////////////////////////////////////////////////////////////////
void CCamera::SetView()
{
float pitch = rotation.x * ToRad;
float yaw = rotation.y * ToRad;
float roll = rotation.z * ToRad;
D3DXMatrixRotationYawPitchRoll(&matRotation, yaw, pitch, roll);
D3DXVec3TransformCoord((D3DXVECTOR3*)&forward, (D3DXVECTOR3*)&dV, &matRotation);
D3DXVec3TransformCoord((D3DXVECTOR3*)&up, (D3DXVECTOR3*)&dU, &matRotation);
D3DXVec3Normalize((D3DXVECTOR3*)&forward, (D3DXVECTOR3*)&forward);
D3DXVec3Cross((D3DXVECTOR3*)&right, (D3DXVECTOR3*)&up, (D3DXVECTOR3*)&forward);
D3DXVec3Normalize((D3DXVECTOR3*)&right, (D3DXVECTOR3*)&right);
Vector3 at = position + forward;
D3DXMatrixLookAtLH(&matView, (D3DXVECTOR3*)&position, (D3DXVECTOR3*)&at, (D3DXVECTOR3*)&up);
}
//////////////////////////////////////////////////////////////////////////
void CCamera::CreateOrthographicView()
{
D3DXMATRIX m;
D3DXMatrixOrthoOffCenterLH(&m, -width/2, +width/2, -height/2, +height/2, near, far);
matrixProjection = Matrix4(m);
}
//////////////////////////////////////////////////////////////////////////
CPerspectiveCamera::CPerspectiveCamera( float fov, int width, int height, float near, float far ) : CCamera()
{
this->fov = fov;
this->near = near;
this->far = far;
SetViewOffset(width, height);
}
//////////////////////////////////////////////////////////////////////////
void CPerspectiveCamera::UpdateProjectionMatrix()
{
matrixProjection = Matrix4::MakePerspective(fov, aspect, near, far);
}
//////////////////////////////////////////////////////////////////////////
void CCamera::SetViewOffset( int width, int height )
{
this->width = width;
this->height = height;
this->aspect = (float)width / height;
UpdateProjectionMatrix();
} | true |
2f558d794b147c6bf3f322baace5c0baec0b06e5 | C++ | arangodb/arangodb | /3rdParty/boost/1.78.0/boost/hana/fwd/filter.hpp | UTF-8 | 2,636 | 2.828125 | 3 | [
"BSL-1.0",
"Apache-2.0",
"BSD-3-Clause",
"ICU",
"Zlib",
"GPL-1.0-or-later",
"OpenSSL",
"ISC",
"LicenseRef-scancode-gutenberg-2020",
"MIT",
"GPL-2.0-only",
"CC0-1.0",
"LicenseRef-scancode-autoconf-simple-exception",
"LicenseRef-scancode-pcre",
"Bison-exception-2.2",
"LicenseRef-scancode... | permissive | /*!
@file
Forward declares `boost::hana::filter`.
@copyright Louis Dionne 2013-2017
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
#ifndef BOOST_HANA_FWD_FILTER_HPP
#define BOOST_HANA_FWD_FILTER_HPP
#include <boost/hana/config.hpp>
#include <boost/hana/core/when.hpp>
namespace boost { namespace hana {
//! Filter a monadic structure using a custom predicate.
//! @ingroup group-MonadPlus
//!
//! Given a monadic structure and a predicate, `filter` returns a new
//! monadic structure containing only those elements that satisfy the
//! predicate. This is a generalization of the usual `filter` function
//! for sequences; it works for any MonadPlus. Intuitively, `filter` is
//! somewhat equivalent to:
//! @code
//! filter(xs, pred) == flatten(transform(xs, [](auto x) {
//! return pred(x) ? lift<Xs>(x) : empty<Xs>();
//! })
//! @endcode
//! In other words, we basically turn a monadic structure containing
//! `[x1, ..., xn]` into a monadic structure containing
//! @code
//! [
//! pred(x1) ? [x1] : [],
//! pred(x2) ? [x2] : [],
//! ...
//! pred(xn) ? [xn] : []
//! ]
//! @endcode
//! and we then `flatten` that.
//!
//!
//! Signature
//! ---------
//! Given a `MonadPlus` `M` and an `IntegralConstant` `Bool` holding a
//! value of type `bool`, the signature is
//! @f$ \mathtt{filter} : M(T) \times (T \to \mathtt{Bool}) \to M(T) @f$.
//!
//! @param xs
//! The monadic structure to filter.
//!
//! @param pred
//! A function called as `pred(x)` for each element `x` in the monadic
//! structure and returning whether that element should be __kept__ in
//! the resulting structure. In the current version of the library, the
//! predicate has to return an `IntegralConstant` holding a value
//! convertible to a `bool`.
//!
//!
//! Example
//! -------
//! @include example/filter.cpp
#ifdef BOOST_HANA_DOXYGEN_INVOKED
constexpr auto filter = [](auto&& xs, auto&& pred) {
return tag-dispatched;
};
#else
template <typename M, typename = void>
struct filter_impl : filter_impl<M, when<true>> { };
struct filter_t {
template <typename Xs, typename Pred>
constexpr auto operator()(Xs&& xs, Pred&& pred) const;
};
BOOST_HANA_INLINE_VARIABLE constexpr filter_t filter{};
#endif
}} // end namespace boost::hana
#endif // !BOOST_HANA_FWD_FILTER_HPP
| true |
3b76d19d3c1f7ff7dab866711732021f809df9bb | C++ | jaan1729/Neural-Network | /include/Layer.hpp | UTF-8 | 1,751 | 3.34375 | 3 | [] | no_license | //Layer is implemented using vector of Neurons
//Values of layers are returned in Matrix data structure which is implemented in Matrix.hpp
//Matrix data structure is helpful to perform matrix operations over the values.
//All the matrix related methods are implemented in matrix.hpp or util.hpp
//The decla=erations are implemented in ../src/Layer.cpp
#ifndef __LAYER_HPP_
#define _LAYER_HPP_
#include<iostream>
#include "Neuron.hpp"
#include<vector>
#include "Matrix.hpp"
#include "util.hpp"
using namespace std;
class Layer{
public:
Layer(int size, string activation);
Layer(int size);
void printToConsole(bool activated);
//This method prints all the Neuron values of the layer. This is helpful for analyzing the network performance.
//With boolean argument 'activated' we can specify to print wheather activated or normal values
void setLayerVal(const vector<double>& values);
//By passing values vector to setLayerVal, it is easy to set all neuron values of the neurons.
//It helps to set given input values to first layer and setting other layer values after multiplying previous layer values with weight matrix during forward propagation.
Matrix getLayerVal();
//It returns Matrix of layer values. This is used to get input layer values to calculate values of second layer.
double getLayerSize(){return this->size;}
Matrix getActivatedLayerVal();
//It returns Matrix of activated Neuron values of the layer. It helps during forward propagation
Matrix getDerivedLayerVal();
//It helps during backward propagation.
private:
double size;
vector<Neuron> neurons;
string activation;
};
#endif | true |
9a3ffc7785ca5aa5a4880ca45260a3c198427210 | C++ | silentst0rm/PandaMini_MarlinUI | /motionscreen.h | UTF-8 | 3,388 | 2.6875 | 3 | [] | no_license | #ifndef MOTIONSCREEN_H
#define MOTIONSCREEN_H
#include "screen.h"
#include "motionunit.h"
#include "screentask.h"
#include <lvstyle.hpp>
class LVButton;
class LVLabel;
class LVImage;
/**
* @brief 运动控制界面
*
* TODO: 为单位按钮添加设置功能
* TODO: 设置运动速度
*
*/
class MotionScreen : public Screen
{
LV_OBJECT
protected:
float m_unit; //!< 移动单位
bool m_showQuestionMark = false; //!< 轴位置不清楚时显示 ???
float m_butUnits[4]; //!< 记录四个按钮的单位
float m_fastSpeed; //!< 快速度
float m_slowSpeed; //!< 慢速度
ScreenTask * m_positionQueryTask = nullptr; //!< 位置查询任务
LVButton * m_butHomeX = nullptr;
LVButton * m_butHomeY = nullptr;
LVButton * m_butHomeZ = nullptr;
LVButton * m_butHome = nullptr;
LVObject * m_selectHit = nullptr;
LVButton * m_but05mm = nullptr;
LVButton * m_but1mm = nullptr;
LVButton * m_but10mm = nullptr;
LVButton * m_but50mm = nullptr;
LVLabel * m_lab05mm = nullptr;
LVLabel * m_lab1mm = nullptr;
LVLabel * m_lab10mm = nullptr;
LVLabel * m_lab50mm = nullptr;
LVImage * m_imgXPosArc = nullptr;
LVImage * m_imgXNegArc = nullptr;
LVImage * m_imgYPosArc = nullptr;
LVImage * m_imgYNegArc = nullptr;
LVImage * m_imgZPosArc = nullptr;
LVImage * m_imgZNegArc = nullptr;
LVButton * m_butXPos = nullptr;
LVButton * m_butXNeg = nullptr;
LVButton * m_butYPos = nullptr;
LVButton * m_butYNeg = nullptr;
LVButton * m_butZPos = nullptr;
LVButton * m_butZNeg = nullptr;
LVLabel * m_labXPos = nullptr;
LVLabel * m_labYPos = nullptr;
LVLabel * m_labZPos = nullptr;
LVStyle styleDisBut;
LVStyle styleDisButSelect;
LVStyle styleHit;
// LVStyle styleArcRed;
// LVStyle styleArcBlue;
// LVStyle styleArcCyan;
LVStyle styleMotoOff;
LVStyle styleButTransp;
public:
MotionScreen();
~MotionScreen();
float unit() const;
void setUnit(float unit);
void setUnit(MotionUnit mu);
/**
* @brief 当单位按钮被点击时
* @param obj
* @return
*/
lv_res_t onButMMClicked (struct _lv_obj_t * obj);
/**
* @brief 移动按钮被按下
* @param obj
* @return
*/
lv_res_t onButMoveClicked (struct _lv_obj_t * obj);
lv_res_t onButHomeClicked (struct _lv_obj_t * obj);
/**
* @brief 把单位放置在按钮的自由数中
* @param but
* @param unit
*/
void setButtonUnit(LVButton * but, LVLabel *lab, float unit);
/**
* @brief 获取按钮中存储的单位
* @param but
* @return
*/
float getButtonUnit(LVButton * but);
/**
* @brief 记录选中的单位
* @param but
*/
void storeSelectUnit(LVButton * but);
/**
* @brief 恢复选中的单位按钮状态
*/
void restoreSelectUnit();
float fastSpeed() const;
void setFastSpeed(float fastSpeed);
float slowSpeed() const;
void setSlowSpeed(float slowSpeed);
protected:
// Screen interface
virtual void onLangChanged() override;
virtual void onThemeChanged() override;
virtual bool initScreen() override;
virtual bool beforeShow() override;
virtual void beforeCleanScreen() override;
virtual void afterCleanScreen() override;
};
#endif // MOTIONSCREEN_H
| true |
001a8ceb1e8a3dfed8cf232696b416c9d1667698 | C++ | Nviviri/Pi_In_The_Sky | /Examples/cpMQTT/TemperatureConverter.cpp | UTF-8 | 1,377 | 2.828125 | 3 | [] | no_license | #include "MQTTconfig.h"
#include "TemperatureConverter.h"
#include "Topic.h"
#include <string>
#include <iostream>
#define CERR std::cerr << className_ << "::" << __func__ << "()\n "
TemperatureConverter::TemperatureConverter(const std::string& appname,
const std::string& clientname,
const std::string& host,
int port):
CommandProcessor(appname, clientname, host, port),
className_{__func__},
mqttID_{HOSTNAME + appname + clientname}
{
CERR << " connect() host = '" << host
<< "' port = " << port
<< " id = " << mqttID_
<< " topic root = "<< MQTT_TOPIC_ROOT << std::endl;
registerCommand("c2f", std::bind(&TemperatureConverter::c2f, this,
std::placeholders::_1));
}
void TemperatureConverter::c2f(const std::vector<std::string>& commandParameters)
{
// for (auto cmd: commandParameters)
// std::cerr << "### "<< cmd << std::endl;
if (commandParameters.size() == 1)
{
double temp_celsius{std::stod(commandParameters[0])};
std::string temp_fahrenheit {
std::to_string(temp_celsius * 9.0 / 5.0 + 32.0)};
publishReturn("c2f", temp_fahrenheit);
}
else
{
publishError("c2f", "number of parameters != 1");
}
}
| true |
5efd0bcd08e207ca90fbcd0708436f118011fb36 | C++ | friepasc/zed-3d-social-distancing | /src/GLViewer.cpp | UTF-8 | 30,838 | 2.671875 | 3 | [
"MIT"
] | permissive | #include "GLViewer.hpp"
#include <random>
#include "cuUtils.h"
#if defined(_DEBUG) && defined(_WIN32)
#error "This sample should not be built in Debug mode, use RelWithDebInfo if you want to do step by step."
#endif
// Function that calculate the number of unrespected distance in the time interval [current - $SOCIAL_DISTANCE_THRESHOLD_TIME seconds]
std::map<int,float> checkPeoplesDistance(std::map<int,std::deque<DistanceData>> input, sl::Timestamp current)
{
// Iterate through each ID
std::map<int,float> output;
std::map<int,std::deque<DistanceData>>::iterator itT = input.begin();
// Iterate through each current ID and Check its queue
while (itT != input.end())
{
// Get each queue for the current ID
std::deque<DistanceData> queue = input[itT->first];
int count_off_distance = 0;
int max_count = 0;
// Iterate through the deque and calculate the percentage of frames where the distance was below the limit.
// This percentage indicates if the ID was close to another ID, during the $SOCIAL_DISTANCE_THRESHOLD_TIME
for (int i=0;i<queue.size();i++)
{
// Calculate the last timestamp to take into account (current - $SOCIAL_DISTANCE_THRESHOLD_TIME) in ms.
// If the current timestamp of the queue object is after this limit, we can take it into account for distance comparison.
unsigned long long past_ts = current.getMilliseconds() - (unsigned long long)(SOCIAL_DISTANCE_THRESHOLD_TIME * 1000.f);
if (queue.at(i).ts_ms> past_ts) {
if (queue.at(i).distance<SOCIAL_DISTANCE_THRESHOLD)
count_off_distance++;
max_count++; // number of total frames.
}
}
// Make sure we have enough detection , otherwise values are not precise enough
if (max_count>4)
output[itT->first] = 100*count_off_distance / max_count;
else {
output[itT->first] = 0;
}
itT++; // increment to next ID
}
return output;
}
GLchar* VERTEX_SHADER =
"#version 330 core\n"
"layout(location = 0) in vec3 in_Vertex;\n"
"layout(location = 1) in vec4 in_Color;\n"
"uniform mat4 u_mvpMatrix;\n"
"out vec4 b_color;\n"
"void main() {\n"
" b_color = in_Color;\n"
" gl_Position = u_mvpMatrix * vec4(in_Vertex, 1);\n"
"}";
GLchar* FRAGMENT_SHADER =
"#version 330 core\n"
"in vec4 b_color;\n"
"layout(location = 0) out vec4 out_Color;\n"
"void main() {\n"
" out_Color = b_color;\n"
"}";
GLViewer* currentInstance_ = nullptr;
float const colors2[5][3] ={
{.231f, .909f, .69f},
{.098f, .686f, .816f},
{.412f, .4f, .804f},
{1, .725f, .0f},
{.989f, .388f, .419f}
};
inline sl::float4 generateColorClass(int idx) {
int const offset = idx % 5;
sl::float4 clr(colors2[offset][0], colors2[offset][1], colors2[offset][2],0.8);
return clr;
}
inline sl::float4 generateColorClassFromState(bool state) {
sl::float4 clr;
if (state) {
clr = sl::float4(0.9, 0.1, 0.2,0.8);
}
else {
clr = sl::float4(.2f, .9f, .5f,0.8);
}
return clr;
}
GLViewer::GLViewer() : available(false) {
currentInstance_ = this;
clearInputs();
}
GLViewer::~GLViewer() {}
void GLViewer::exit() {
if (currentInstance_) {
pointCloud_.close();
available = false;
}
}
bool GLViewer::isAvailable() {
if (available)
glutMainLoopEvent();
return available;
}
void CloseFunc(void) { if (currentInstance_) currentInstance_->exit(); }
void GLViewer::init(int argc, char **argv, sl::CameraParameters param) {
glutInit(&argc, argv);
int wnd_w = glutGet(GLUT_SCREEN_WIDTH);
int wnd_h = glutGet(GLUT_SCREEN_HEIGHT);
int width = wnd_w*0.9;
int height = wnd_h*0.9;
if (width > param.image_size.width && height > param.image_size.height) {
width = param.image_size.width;
height = param.image_size.height;
}
camera_parameters = param;
windowSize.width = width;
windowSize.height = height;
glutInitWindowSize(windowSize.width, windowSize.height);
glutInitWindowPosition(wnd_w*0.05, wnd_h*0.05);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
glutCreateWindow("ZED Object Detection Viewer");
glViewport(0,0,width,height);
GLenum err = glewInit();
if (GLEW_OK != err)
std::cout << "ERROR: glewInit failed: " << glewGetErrorString(err) << "\n";
glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_CONTINUE_EXECUTION);
glEnable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_LINE_SMOOTH);
glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);
pointCloudSize = param.image_size;
bool err_pc = pointCloud_.initialize(pointCloudSize);
if (!err_pc)
std::cout << "ERROR: Failed to initialized point cloud"<<std::endl;
// Compile and create the shader for 3D objects
shader.it = Shader(VERTEX_SHADER, FRAGMENT_SHADER);
shader.MVP_Mat = glGetUniformLocation(shader.it.getProgramId(), "u_mvpMatrix");
// Create the rendering camera
setRenderCameraProjection(param,0.5f,200000);
// Create the bounding box object
BBox_obj.init();
BBox_obj.setDrawingType(GL_QUADS);
// Clear trajectories
#ifdef WITH_TRAJECTORIES
trajectories.clear();
#endif
// Set background color (black)
bckgrnd_clr = sl::float3(0, 0, 0);
// Set OpenGL settings
glDisable(GL_DEPTH_TEST); //avoid occlusion with bbox
// Map glut function on this class methods
glutDisplayFunc(GLViewer::drawCallback);
glutReshapeFunc(GLViewer::reshapeCallback);
glutKeyboardFunc(GLViewer::keyPressedCallback);
glutKeyboardUpFunc(GLViewer::keyReleasedCallback);
glutCloseFunc(CloseFunc);
available = true;
}
void GLViewer::setRenderCameraProjection(sl::CameraParameters params,float znear, float zfar) {
// Just slightly up the ZED camera FOV to make a small black border
float fov_y = (params.v_fov+0.5f) * M_PI / 180.f;
float fov_x = (params.h_fov+0.5f) * M_PI / 180.f;
projection_(0, 0) = 1.0f / tanf(fov_x * 0.5f);
projection_(1, 1) = 1.0f / tanf(fov_y * 0.5f);
projection_(2, 2) = -(zfar + znear) / (zfar - znear);
projection_(3, 2) = -1;
projection_(2, 3) = -(2.f * zfar * znear) / (zfar - znear);
projection_(3, 3) = 0;
projection_(0, 0) = 1.0f / tanf(fov_x * 0.5f); //Horizontal FoV.
projection_(0, 1) = 0;
projection_(0, 2) = 2.0f * ((params.image_size.width - 1.0f * params.cx) / params.image_size.width) - 1.0f; //Horizontal offset.
projection_(0, 3) = 0;
projection_(1, 0) = 0;
projection_(1, 1) = 1.0f / tanf(fov_y * 0.5f); //Vertical FoV.
projection_(1, 2) = -(2.0f * ((params.image_size.height - 1.0f * params.cy) / params.image_size.height ) - 1.0f); //Vertical offset.
projection_(1, 3) = 0;
projection_(2, 0) = 0;
projection_(2, 1) = 0;
projection_(2, 2) = -(zfar + znear) / (zfar - znear); //Near and far planes.
projection_(2, 3) = -(2.0f * zfar * znear) / (zfar - znear); //Near and far planes.
projection_(3, 0) = 0;
projection_(3, 1) = 0;
projection_(3, 2) = -1;
projection_(3, 3) = 0.0f;
}
void GLViewer::render() {
if (available) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glClearColor(bckgrnd_clr.r, bckgrnd_clr.g, bckgrnd_clr.b, 1.f);
mtx.lock();
update();
draw();
printText();
mtx.unlock();
glutSwapBuffers();
glutPostRedisplay();
}
}
void GLViewer::updateData(sl::Mat image, sl::Mat depth, sl::Objects &obj, sl::Timestamp image_ts) {
if (mtx.try_lock()) {
// Update Image/Depth (into a point cloud)
pointCloud_.pushNewPC(image,depth,camera_parameters);
// Clear frames object
BBox_obj.clear();
std::vector<sl::ObjectData> objs = obj.object_list;
objectsName.clear();
//Detect if people are close to each other with less than $SOCIAL_DISTANCE_THRESHOLD meters
#ifdef SOCIAL_DISTANCE_DETECTION
// calculate min distance for this frame
for (int i = 0; i < objs.size(); i++)
{
float min_distance = 1000000.0; //Fake first distance.
DistanceData dist_data;
dist_data.ts_ms = obj.timestamp.getMilliseconds();
dist_data.distance = min_distance;
// For each object, calculate the minimum distance to another person.
// Store that min distance into a Distance data object that contains the distance and the timestamp
// Push it into the queue (deque) for that ID
for (int j= 0; j < objs.size(); j++) {
if (i!=j) {
//get both position
auto posA = objs[i].position;
auto posB = objs[j].position;
//Calculate distance (euclidean distance)
float distance = sqrt(pow(posA.x-posB.x,2) + pow(posA.y-posB.y,2) +pow(posA.z-posB.z,2));
//if the distance is below the current min distance , that's our new min distance.
if (distance<min_distance) {
dist_data.distance = distance;
min_distance = distance;
}
}
}
min_dist_warn_map[objs[i].id].push_back(dist_data);
if (min_dist_warn_map[objs[i].id].size()>SOCIAL_DISTANCE_THRESHOLD_TIME * 60) //make sure it does not increase to much. We don't need really more that the threshold time
min_dist_warn_map[objs[i].id].pop_front();
}
// Create the map that links ID and percentage of "under distance limit".
std::map<int,float> dist_warn_map;
dist_warn_map = checkPeoplesDistance(min_dist_warn_map,obj.timestamp);
#endif
// For each object
for (int i = 0; i < objs.size(); i++) {
// Only show tracked objects
if (objs[i].tracking_state == sl::OBJECT_TRACKING_STATE::OK && objs[i].id>=0) {
auto bb_ = objs[i].bounding_box;
auto pos_ = objs[i].position;
ObjectExtPosition ext_pos_;
ext_pos_.position = pos_;
ext_pos_.timestamp = obj.timestamp;
#ifdef WITH_TRAJECTORIES
trajectories[objs[i].id].push_back(ext_pos_);
#endif
#ifdef SOCIAL_DISTANCE_DETECTION
// Red or Green : depends on percentage of frames where a distance below the limit was detected
if (dist_warn_map[objs[i].id]>SOCIAL_DISTANCE_THRESHOLD_PERCENT) {
print_message = true;
print_message_count=0;
}
auto clr_id = generateColorClassFromState(dist_warn_map[objs[i].id]>75);
#else
auto clr_id = generateColorClass(objs[i].id);
#endif
// Draw boxes
if (g_showBox && bb_.size()>0) {
BBox_obj.addBoundingBox(bb_,clr_id);
}
#if defined(SOCIAL_DISTANCE_DETECTION)
g_showLabel=false;
#endif
// Draw Labels
if (g_showLabel) {
if ( bb_.size()>0) {
objectsName.emplace_back();
objectsName.back().name_lineA = "ID : "+ std::to_string(objs[i].id);
std::stringstream ss_vel;
ss_vel << std::fixed << std::setprecision(1) << objs[i].velocity.norm();
objectsName.back().name_lineB = ss_vel.str()+" m/s";
objectsName.back().color = clr_id;
objectsName.back().position = pos_;
objectsName.back().position.y =(bb_[0].y + bb_[1].y + bb_[2].y + bb_[3].y)/4.f +0.2f;
}
}
}
}
#ifdef WITH_TRAJECTORIES
// Calculate trajectories from current object positions.
// Store in a map with ID linked to Position/Timestamp queue
// The queue will be progressively removed from its last element to create a fading effect on the trajectories.
std::map<int, std::deque<ObjectExtPosition>>::iterator itT = trajectories.begin();
while (itT != trajectories.end())
{
trajectories_obj[itT->first].clear();
Simple3DObject tmp = trajectories_obj[itT->first];
if (!tmp.isInit())
tmp.init();
tmp.setDrawingType(GL_LINES);
std::vector<sl::float3> pts;
for (int k=0;k<itT->second.size();k++)
{
pts.push_back(itT->second.at(k).position);
}
#ifdef SOCIAL_DISTANCE_DETECTION
auto clr_id = generateColorClass(dist_warn_map[itT->first]>SOCIAL_DISTANCE_THRESHOLD_PERCENT);
#else
auto clr_id = generateColorClass(itT->first);
#endif
if(!pts.empty())
tmp.addPoints(pts,clr_id);
trajectories_obj[itT->first] = tmp;
itT++;
}
// Remove old data from trajectories, based on timestamp comparison
itT = trajectories.begin();
while (itT != trajectories.end())
{
if (itT->second.empty()) {
trajectories.erase(itT++);
}
else{
if (itT->second.front().timestamp.getMilliseconds()<image_ts.getMilliseconds() - line_fading_time_ms)
itT->second.pop_front();
itT++;
}
}
#endif
f_count ++;
mtx.unlock();
}
}
void GLViewer::update() {
if (keyStates_['q'] == KEY_STATE::UP || keyStates_['Q'] == KEY_STATE::UP || keyStates_[27] == KEY_STATE::UP) {
currentInstance_->exit();
return;
}
// Update point cloud
pointCloud_.update();
// Update BBox
BBox_obj.pushToGPU();
//Clear inputs
clearInputs();
}
void GLViewer::draw() {
const sl::Transform vpMatrix = projection_; //simplification : proj * view = proj
glPointSize(1.0);
pointCloud_.draw(vpMatrix);
glUseProgram(shader.it.getProgramId());
glUniformMatrix4fv(shader.MVP_Mat, 1, GL_TRUE, vpMatrix.m);
#ifdef WITH_TRAJECTORIES
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glLineWidth(3.f);
for (std::pair<int, Simple3DObject> element : trajectories_obj) {
element.second.pushToGPU();
element.second.draw(vpMatrix);
}
#endif
glLineWidth(1.f);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
BBox_obj.draw(vpMatrix);
glUseProgram(0);
#if defined(SOCIAL_DISTANCE_DETECTION)
if (print_message ||print_message_count<50) {
sl::Resolution wnd_size(glutGet(GLUT_WINDOW_WIDTH), glutGet(GLUT_WINDOW_HEIGHT));
glColor4f(1.0,0.0,0.0, 1.f);
std::string message = std::string("WARNING : Social Distance Not Respected ! ");
glWindowPos2f(20, wnd_size.height - 50);
const char* message_c = message.c_str();
int len = (int)strlen(message_c);
for (int i = 0; i < len; i++)
glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, message_c[i]);
print_message_count++;
}
if (print_message_count>50){
print_message=false;
print_message_count = 100;
}
#endif
}
sl::float2 compute3Dprojection(sl::float3 &pt, const sl::Transform &cam, sl::Resolution wnd_size) {
sl::float4 pt4d(pt.x, pt.y, pt.z, 1.);
auto proj3D_cam = pt4d * cam;
sl::float2 proj2D;
proj2D.x = ((proj3D_cam.x / pt4d.w) * wnd_size.width) / (2.f * proj3D_cam.w) + wnd_size.width / 2.f;
proj2D.y = ((proj3D_cam.y / pt4d.w) * wnd_size.height) / (2.f * proj3D_cam.w) + wnd_size.height / 2.f;
return proj2D;
}
void GLViewer::printText() {
const sl::Transform vpMatrix = projection_;
sl::Resolution wnd_size(glutGet(GLUT_WINDOW_WIDTH), glutGet(GLUT_WINDOW_HEIGHT));
for (auto it : objectsName) {
auto pt2d = compute3Dprojection(it.position, vpMatrix, wnd_size);
glColor4f(it.color.r, it.color.g, it.color.b, 1.f);
const auto *string = it.name_lineA.c_str();
glWindowPos2f(pt2d.x-40, pt2d.y+20);
int len = (int)strlen(string);
for (int i = 0; i < len; i++)
glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, string[i]);
string = it.name_lineB.c_str();
glWindowPos2f(pt2d.x-40, pt2d.y);
len = (int)strlen(string);
for (int i = 0; i < len; i++)
glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, string[i]);
}
}
void GLViewer::clearInputs() {
for (unsigned int i = 0; i < 256; ++i)
if (keyStates_[i] != KEY_STATE::DOWN)
keyStates_[i] = KEY_STATE::FREE;
}
void GLViewer::drawCallback() {
currentInstance_->render();
}
void GLViewer::reshapeCallback(int width, int height) {
glViewport(0, 0, width, height);
}
void GLViewer::keyPressedCallback(unsigned char c, int x, int y) {
currentInstance_->keyStates_[c] = KEY_STATE::DOWN;
glutPostRedisplay();
}
void GLViewer::keyReleasedCallback(unsigned char c, int x, int y) {
currentInstance_->keyStates_[c] = KEY_STATE::UP;
}
void GLViewer::idle() {
glutPostRedisplay();
}
Simple3DObject::Simple3DObject() {
is_init=false;
}
Simple3DObject::~Simple3DObject() {
if (vaoID_ != 0) {
glDeleteBuffers(3, vboID_);
glDeleteVertexArrays(1, &vaoID_);
vaoID_=0;
is_init=false;
}
}
bool Simple3DObject::isInit()
{
return is_init;
}
void Simple3DObject::init() {
vaoID_ = 0;
isStatic_=false;
drawingType_ = GL_TRIANGLES;
rotation_.setIdentity();
shader.it = Shader(VERTEX_SHADER, FRAGMENT_SHADER);
shader.MVP_Mat = glGetUniformLocation(shader.it.getProgramId(), "u_mvpMatrix");
is_init=true;
}
void Simple3DObject::addPoints(std::vector<sl::float3> pts,sl::float4 base_clr)
{
for (int k=0;k<pts.size();k++) {
sl::float3 pt = pts.at(k);
vertices_.push_back(pt.x);
vertices_.push_back(pt.y);
vertices_.push_back(pt.z);
colors_.push_back(base_clr.r);
colors_.push_back(base_clr.g);
colors_.push_back(base_clr.b);
colors_.push_back(1.f);
int current_size_index = (vertices_.size()/3 -1);
indices_.push_back(current_size_index);
indices_.push_back(current_size_index+1);
}
}
void Simple3DObject::addBoundingBox(std::vector<sl::float3> bbox,sl::float4 base_clr){
float grad_distance = 0.3;
for (int p=0;p<4;p++) {
int indexA = p;
int indexB = p+1;
if (indexB>3)
indexB=0;
vertices_.push_back(bbox[indexA].x);
vertices_.push_back(bbox[indexA].y);
vertices_.push_back(bbox[indexA].z);
colors_.push_back(base_clr.r);
colors_.push_back(base_clr.g);
colors_.push_back(base_clr.b);
colors_.push_back(base_clr.a);
vertices_.push_back(bbox[indexB].x);
vertices_.push_back(bbox[indexB].y);
vertices_.push_back(bbox[indexB].z);
colors_.push_back(base_clr.r);
colors_.push_back(base_clr.g);
colors_.push_back(base_clr.b);
colors_.push_back(base_clr.a);
vertices_.push_back(bbox[indexB].x);
vertices_.push_back(bbox[indexB].y-grad_distance);
vertices_.push_back(bbox[indexB].z);
colors_.push_back(base_clr.r);
colors_.push_back(base_clr.g);
colors_.push_back(base_clr.b);
colors_.push_back(0);
vertices_.push_back(bbox[indexA].x);
vertices_.push_back(bbox[indexA].y-grad_distance);
vertices_.push_back(bbox[indexA].z);
colors_.push_back(base_clr.r);
colors_.push_back(base_clr.g);
colors_.push_back(base_clr.b);
colors_.push_back(0);
indices_.push_back((int)indices_.size());
indices_.push_back((int)indices_.size());
indices_.push_back((int)indices_.size());
indices_.push_back((int)indices_.size());
}
for (int p=4;p<8;p++) {
int indexA = p;
int indexB = p+1;
if (indexB>7)
indexB=4;
vertices_.push_back(bbox[indexA].x);
vertices_.push_back(bbox[indexA].y);
vertices_.push_back(bbox[indexA].z);
colors_.push_back(base_clr.r);
colors_.push_back(base_clr.g);
colors_.push_back(base_clr.b);
colors_.push_back(base_clr.a);
vertices_.push_back(bbox[indexB].x);
vertices_.push_back(bbox[indexB].y);
vertices_.push_back(bbox[indexB].z);
colors_.push_back(base_clr.r);
colors_.push_back(base_clr.g);
colors_.push_back(base_clr.b);
colors_.push_back(base_clr.a);
vertices_.push_back(bbox[indexB].x);
vertices_.push_back(bbox[indexB].y+grad_distance);
vertices_.push_back(bbox[indexB].z);
colors_.push_back(base_clr.r);
colors_.push_back(base_clr.g);
colors_.push_back(base_clr.b);
colors_.push_back(0);
vertices_.push_back(bbox[indexA].x);
vertices_.push_back(bbox[indexA].y+grad_distance);
vertices_.push_back(bbox[indexA].z);
colors_.push_back(base_clr.r);
colors_.push_back(base_clr.g);
colors_.push_back(base_clr.b);
colors_.push_back(0);
indices_.push_back((int)indices_.size());
indices_.push_back((int)indices_.size());
indices_.push_back((int)indices_.size());
indices_.push_back((int)indices_.size());
}
}
void Simple3DObject::pushToGPU() {
if (!isStatic_ || vaoID_ == 0) {
if (vaoID_ == 0) {
glGenVertexArrays(1, &vaoID_);
glGenBuffers(3, vboID_);
}
glShadeModel(GL_SMOOTH);
if (vertices_.size()>0) {
glBindVertexArray(vaoID_);
glBindBuffer(GL_ARRAY_BUFFER, vboID_[0]);
glBufferData(GL_ARRAY_BUFFER, vertices_.size() * sizeof(float), &vertices_[0], isStatic_ ? GL_STATIC_DRAW : GL_DYNAMIC_DRAW);
glVertexAttribPointer(Shader::ATTRIB_VERTICES_POS, 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(Shader::ATTRIB_VERTICES_POS);
}
if (colors_.size()>0) {
glBindBuffer(GL_ARRAY_BUFFER, vboID_[1]);
glBufferData(GL_ARRAY_BUFFER, colors_.size() * sizeof(float), &colors_[0], isStatic_ ? GL_STATIC_DRAW : GL_DYNAMIC_DRAW);
glVertexAttribPointer(Shader::ATTRIB_COLOR_POS, 4, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(Shader::ATTRIB_COLOR_POS);
}
if (indices_.size()>0) {
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vboID_[2]);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices_.size() * sizeof(unsigned int), &indices_[0], isStatic_ ? GL_STATIC_DRAW : GL_DYNAMIC_DRAW);
}
glBindVertexArray(0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
}
void Simple3DObject::clear() {
vertices_.clear();
colors_.clear();
indices_.clear();
}
void Simple3DObject::setDrawingType(GLenum type) {
drawingType_ = type;
}
void Simple3DObject::draw(const sl::Transform& vp) {
if (indices_.size() && vaoID_) {
glBindVertexArray(vaoID_);
glDrawElements(drawingType_, (GLsizei)indices_.size(), GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
}
}
void Simple3DObject::translate(const sl::Translation& t) {
position_ = position_ + t;
}
void Simple3DObject::setPosition(const sl::Translation& p) {
position_ = p;
}
void Simple3DObject::setRT(const sl::Transform& mRT) {
position_ = mRT.getTranslation();
rotation_ = mRT.getOrientation();
}
void Simple3DObject::rotate(const sl::Orientation& rot) {
rotation_ = rot * rotation_;
}
void Simple3DObject::rotate(const sl::Rotation& m) {
this->rotate(sl::Orientation(m));
}
void Simple3DObject::setRotation(const sl::Orientation& rot) {
rotation_ = rot;
}
void Simple3DObject::setRotation(const sl::Rotation& m) {
this->setRotation(sl::Orientation(m));
}
const sl::Translation& Simple3DObject::getPosition() const {
return position_;
}
sl::Transform Simple3DObject::getModelMatrix() const {
sl::Transform tmp;
tmp.setOrientation(rotation_);
tmp.setTranslation(position_);
return tmp;
}
Shader::Shader(GLchar* vs, GLchar* fs) {
if (!compile(verterxId_, GL_VERTEX_SHADER, vs)) {
std::cout << "ERROR: while compiling vertex shader" << std::endl;
}
if (!compile(fragmentId_, GL_FRAGMENT_SHADER, fs)) {
std::cout << "ERROR: while compiling fragment shader" << std::endl;
}
programId_ = glCreateProgram();
glAttachShader(programId_, verterxId_);
glAttachShader(programId_, fragmentId_);
glBindAttribLocation(programId_, ATTRIB_VERTICES_POS, "in_vertex");
glBindAttribLocation(programId_, ATTRIB_COLOR_POS, "in_texCoord");
glLinkProgram(programId_);
GLint errorlk(0);
glGetProgramiv(programId_, GL_LINK_STATUS, &errorlk);
if (errorlk != GL_TRUE) {
std::cout << "ERROR: while linking Shader :" << std::endl;
GLint errorSize(0);
glGetProgramiv(programId_, GL_INFO_LOG_LENGTH, &errorSize);
char *error = new char[errorSize + 1];
glGetShaderInfoLog(programId_, errorSize, &errorSize, error);
error[errorSize] = '\0';
std::cout << error << std::endl;
delete[] error;
glDeleteProgram(programId_);
}
}
Shader::~Shader() {
if (verterxId_ != 0)
glDeleteShader(verterxId_);
if (fragmentId_ != 0)
glDeleteShader(fragmentId_);
if (programId_ != 0)
glDeleteShader(programId_);
}
GLuint Shader::getProgramId() {
return programId_;
}
bool Shader::compile(GLuint &shaderId, GLenum type, GLchar* src) {
shaderId = glCreateShader(type);
if (shaderId == 0) {
std::cout << "ERROR: shader type (" << type << ") does not exist" << std::endl;
return false;
}
glShaderSource(shaderId, 1, (const char**)&src, 0);
glCompileShader(shaderId);
GLint errorCp(0);
glGetShaderiv(shaderId, GL_COMPILE_STATUS, &errorCp);
if (errorCp != GL_TRUE) {
std::cout << "ERROR: while compiling Shader :" << std::endl;
GLint errorSize(0);
glGetShaderiv(shaderId, GL_INFO_LOG_LENGTH, &errorSize);
char *error = new char[errorSize + 1];
glGetShaderInfoLog(shaderId, errorSize, &errorSize, error);
error[errorSize] = '\0';
std::cout << error << std::endl;
delete[] error;
glDeleteShader(shaderId);
return false;
}
return true;
}
GLchar* POINTCLOUD_VERTEX_SHADER =
"#version 330 core\n"
"layout(location = 0) in vec4 in_VertexRGBA;\n"
"uniform mat4 u_mvpMatrix;\n"
"out vec4 b_color;\n"
"void main() {\n"
// Decompose the 4th channel of the XYZRGBA buffer to retrieve the color of the point (1float to 4uint)
" uint vertexColor = floatBitsToUint(in_VertexRGBA.w); \n"
" vec3 clr_int = vec3((vertexColor & uint(0x000000FF)), (vertexColor & uint(0x0000FF00)) >> 8, (vertexColor & uint(0x00FF0000)) >> 16);\n"
" b_color = vec4(clr_int.r / 255.0f, clr_int.g / 255.0f, clr_int.b / 255.0f, 1.f);"
" gl_Position = u_mvpMatrix * vec4(in_VertexRGBA.xyz, 1);\n"
"}";
GLchar* POINTCLOUD_FRAGMENT_SHADER =
"#version 330 core\n"
"in vec4 b_color;\n"
"layout(location = 0) out vec4 out_Color;\n"
"void main() {\n"
" out_Color = b_color;\n"
"}";
PointCloud::PointCloud() : hasNewPCL_(false) {}
PointCloud::~PointCloud() {
close();
}
void PointCloud::close() {
if (matGPU_.isInit()) {
matGPU_.free();
cudaGraphicsUnmapResources(1, &bufferCudaID_, 0);
glDeleteBuffers(1, &bufferGLID_);
}
}
bool PointCloud::initialize(sl::Resolution res) {
glGenBuffers(1, &bufferGLID_);
glBindBuffer(GL_ARRAY_BUFFER, bufferGLID_);
glBufferData(GL_ARRAY_BUFFER, res.area() * 4 * sizeof(float), 0, GL_DYNAMIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
shader.it = Shader(POINTCLOUD_VERTEX_SHADER, POINTCLOUD_FRAGMENT_SHADER);
shader.MVP_Mat = glGetUniformLocation(shader.it.getProgramId(), "u_mvpMatrix");
matGPU_.alloc(res, sl::MAT_TYPE::F32_C4, sl::MEM::GPU);
cudaError_t err = cudaGraphicsGLRegisterBuffer(&bufferCudaID_, bufferGLID_, cudaGraphicsRegisterFlagsNone);
err = cudaGraphicsMapResources(1, &bufferCudaID_, 0);
err = cudaGraphicsResourceGetMappedPointer((void**)&xyzrgbaMappedBuf_, &numBytes_, bufferCudaID_);
return (err==cudaSuccess);
}
void PointCloud::pushNewPC(sl::Mat &image, sl::Mat& depth, sl::CameraParameters cam_params)
{
if (matGPU_.isInit()) {
// CUDA code to convert Image + Z Buffer into single point cloud
// It was possible to do it also on a GLSL shader, but... just a choice.
hasNewPCL_ = triangulateImageandZ(matGPU_,image,depth,cam_params);
}
}
void PointCloud::update() {
if (hasNewPCL_ && matGPU_.isInit()) {
cudaMemcpy(xyzrgbaMappedBuf_, matGPU_.getPtr<sl::float4>(sl::MEM::GPU), numBytes_, cudaMemcpyDeviceToDevice);
hasNewPCL_ = false;
}
}
void PointCloud::draw(const sl::Transform& vp) {
if (matGPU_.isInit()) {
glUseProgram(shader.it.getProgramId());
glUniformMatrix4fv(shader.MVP_Mat, 1, GL_TRUE, vp.m);
glBindBuffer(GL_ARRAY_BUFFER, bufferGLID_);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, 0);
glDrawArrays(GL_POINTS, 0, matGPU_.getResolution().area());
glBindBuffer(GL_ARRAY_BUFFER, 0);
glUseProgram(0);
}
}
| true |
f2f72186baf44fbe82b70ab45810f07f8c7430ea | C++ | paladin-705/InternetRadioPlayer | /src/RadioServer.cpp | UTF-8 | 895 | 2.59375 | 3 | [] | no_license | #include "RadioServer.h"
RadioServer::RadioServer()
{
qDebug() << "Starting server...";
server = new QTcpServer();
if(server->listen(QHostAddress::Any, _serverPort))
qDebug() << "Server listen port: " << _serverPort;
else
qCritical() << "Server starting error: " << server->serverError();
connect(server, SIGNAL(newConnection()), this, SLOT(slotNewConnection()));
}
RadioServer::~RadioServer()
{
delete server;
}
void RadioServer::slotNewConnection()
{
while (server->hasPendingConnections())
{
QTcpSocket *clientSocket = server->nextPendingConnection();
connect(clientSocket, SIGNAL(readyRead()), this, SLOT(slotReadyRead()));
connect(clientSocket, SIGNAL(disconnected()), clientSocket, SLOT(deleteLater()));
}
}
void RadioServer::slotReadyRead()
{
QTcpSocket *clientSocket = (QTcpSocket*)sender();
emit parseCommand(clientSocket);
}
| true |
73166219adcc24aa26f3cc68d28492abdeba985e | C++ | houwenqi/Tool-program | /c-mysql/MYSQLtest.cpp | UTF-8 | 3,379 | 3.15625 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h> //sleep函数
#include "mysql.h"
//数据结构定义
MYSQL mysql;
MYSQL_RES *res;
MYSQL_ROW row;
void DoSQL(char* sql)
{
int retcode = 0;
retcode = mysql_real_query(&mysql,sql,(unsigned int)strlen(sql));//如果查询成功,函数返回零。如果发生一个错误,函数返回非零。
if( retcode != 0 )
{
printf("mysql_real_query is failed:%s\n",mysql_error(&mysql));
}
}
int CMYSQL()
{
//需要执行的语句
char* insert1 = "insert into testtable values(1,'xiaohong','girl')";
char* insert2 = "insert into testtable values(2,'xiaogang','boy')";
char* create = "create table testtable(id int,name varchar(20),sex varchar(10))";
char* query = "select * from testtable";
//执行创建语句
DoSQL(create);
sleep(1);
//执行插入语句
DoSQL(insert1);
sleep(1);
DoSQL(insert2);
sleep(1);
//执行查询语句
DoSQL(query);
//处理查询结果
res = mysql_store_result(&mysql);//如果成功,返回具有多个结果的MYSQL_RES结果集合。如果出现错误,返回NULL
while( row = mysql_fetch_row(res) )
{
for(int i=0;i<mysql_num_fields(res);i++)
{
printf("%s\n",row[i] );
}
printf("\n");
}
mysql_free_result(res);
return 0;
}
int STMT()
{
//创建MYSQL_STMT句柄
MYSQL_STMT* stmt = mysql_stmt_init(&mysql);
//sql语句
char* select = "select * from testtable where id = ? ;";
//语句准备
if( mysql_stmt_prepare(stmt,select,strlen(select)))//如果成功处理了语句,返回0。如果出现错误,返回非0值。
{
printf("mysql_stmt_prepare is failed:%s\n",mysql_error(&mysql));
return -5;
}
//输入参数
int id;
char name[20]="";
char sex[10]="";
printf("id: ");
scanf("%d",&id);
//参数准备
MYSQL_BIND params[3];
memset(params,0,sizeof(params));
params[0].buffer_type = MYSQL_TYPE_LONG;
params[0].buffer = &id;
params[1].buffer_type = MYSQL_TYPE_STRING;
params[1].buffer = name;
params[1].buffer_length = 50;
params[2].buffer_type = MYSQL_TYPE_STRING;
params[2].buffer = sex;
params[2].buffer_length = 20;
//绑定参数
mysql_stmt_bind_param(stmt,params);
//将结果集中的列与数据缓冲和长度缓冲关联(绑定)起来
mysql_stmt_bind_result(stmt,params);
//执行与句柄相关的预处理语句
mysql_stmt_execute(stmt);
//对结果的缓冲处理
mysql_stmt_store_result(stmt);
//具体数据读取
while( mysql_stmt_fetch(stmt) == 0 )
{
printf("%d %s %s\n",id,name,sex );
}
mysql_stmt_close(stmt);
return 0;
}
int main()
{
//初始化
mysql_init(&mysql);
//连接数据库
if( !mysql_real_connect(&mysql,"172.16.1.23","Cserver","wkl1409624367","test",0,NULL,0))//如果连接成功,返回MYSQL*连接句柄。如果连接失败,返回NULL。
{
printf("mysql_real_connect is failed:%s\n",mysql_error(&mysql));
return -3;
}
//第一步,调用普通CMYSQL函数,向数据库插入三条数据,并查询查询结果;
int ret = 0;
ret = CMYSQL();
if( ret != 0 )
{
printf("Do CMYSQL failed\n");
return -1;
}
//第二步,调用CMYSQL预处理函数,查询数据库信息并展示,增加一条数据;
ret = STMT();
if( ret != 0 )
{
printf("Do STMT failed\n");
return -2;
}
mysql_close(&mysql);
return 0;
} | true |
20d4c5b636948a974470797f11f9cb64335fb201 | C++ | porfirioribeiro/resplacecode | /CPP/xCalc_old/panels/ivapanel.h | UTF-8 | 1,247 | 2.515625 | 3 | [] | no_license | #ifndef IVAPANEL_H
#define IVAPANEL_H
#include <QtGui>
#include "ui_ivapanel.h"
class IvaPanel: public QWidget {
Q_OBJECT
Q_DISABLE_COPY(IvaPanel)
public:
explicit IvaPanel(QWidget *parent = 0) :
QWidget(parent) {
ui.setupUi(this);
doCalc();
}
public slots:
void doCalc() {
double inicial = ui.iva_Inicial->value();
double descP = ui.iva_DescP->value();
double desc = inicial * (descP / 100);
double descT = inicial - desc;
double ivaP = ui.iva_IvaP->currentText().toDouble();
double iva = descT * (ivaP / 100);
double ivaT = descT + iva;
double lucroP = ui.iva_LucroP->value();
double lucro = ivaT * (lucroP / 100);
double final = ivaT + lucro;
ui.iva_Desc->setText(QString::number(desc));
ui.iva_DescT->setText(QString::number(descT));
ui.iva_Iva->setText(QString::number(iva));
ui.iva_IvaT->setText(QString::number(ivaT));
ui.iva_Lucro->setText(QString::number(lucro));
ui.iva_Final->setText(QString::number(final));
}
protected:
virtual void changeEvent(QEvent *e) {
switch (e->type()) {
case QEvent::LanguageChange:
ui.retranslateUi(this);
break;
default:
break;
}
}
private:
Ui::IvaPanel ui;
};
#endif // IVAPANEL_H
| true |
0bf1818667204c7dcf4bbc33ffd5f522d6f1473e | C++ | kylin0925/online_judge | /acm/c10000/acm10003f1.cpp | UTF-8 | 1,250 | 2.59375 | 3 | [] | no_license | /* @JUDGE_ID: 53xxxx 10003 C++ */
/* @BEGIN_OF_SOURCE_CODE */
#include <stdio.h>
int n;
int l;
int stick[100];
int m[60][60];
void sov()
{
int len,i,j;
int tmp;
for(len=2;len<=n;len++)
{
for(i=0;i<=n-len;i++)
{
m[i][i+len]=999999;
for(j=i+1;j<i+len;j++)
{
tmp=m[i][j]+m[j][len+i]+(stick[i+len]-stick[i]);
if(tmp<m[i][i+len]) m[i][i+len]=tmp;
}
}
}
}
int main(int argc, char* argv[])
{
int i,j;
while(scanf("%d",&l)==1)
{
if(l==0) break;
scanf("%d",&n);
stick[0]=0;
for(i=1;i<=n;i++)
{
scanf("%d",&stick[i]);
}
n++;
stick[n]=l;
sov();
printf("The minimum cutting is %d.\n",m[0][n]);
for(i=0;i<n;i++){ stick[i]=0;}
for(i=0;i<n;i++)for(j=0;j<n;m[i][j],j++);
}
return 0;
}
/* @END_OF_SOURCE_CODE */
| true |
b65dcf6892378b989092bddb76d4c7e9cc4c5525 | C++ | handahye/AlgorithmStudy | /SWExpert/D3/D3_삼성시의 버스 노선.cpp | UHC | 768 | 3.140625 | 3 | [] | no_license |
int main() {
cout << " ";
int T;
cin >> T;
for (int k = 1; k <= T; k++) {
int N, Q;
cin >> N >> Q;
int cow[100001];
int L[100001], R[100001];
int one[100001], two[100001], thr[100001];
for (int i = 1; i <= N; i++) { //N ǰ Է¹
cin >> cow[i];
}
for (int j = 0; j < Q; j++) { // Է¹
cin >> L[j] >> R[j];
one[j] = 0;
two[j] = 0;
thr[j] = 0;
for (int i = L[j]; i <= R[j]; i++) { //ǰ ϱ
if (cow[i] == 1) {
one[j]++;
}
else if (cow[i] == 2) {
two[j]++;
}
else {
thr[j]++;
}
}
}
//
cout << "#" << k << endl;
for (int j = 0; j < Q; j++) {
cout << one[j] << " " << two[j] << " " << thr[j] << endl;
}
}
return 0;
} | true |
d5cba0e703f652be06dc66e7135771f66bf91539 | C++ | telminov/my_notes_for_various-_programlanguages | /c++/teacher/3 class/3.cpp | UTF-8 | 1,845 | 4.15625 | 4 | [] | no_license | #include <iostream>
//целое без знака unsigned int
class Cat
{
public: //открытые переменные , иначе закрытые
void Meow(); //функцие не надо ни чего возвращать - void
int GetAge();
int setAge(int age);
private:
int itsAge;
};
int Cat::GetAge()
{
return itsAge;
}
int Cat::setAge(int age)
{
itsAge = age;
}
void Cat::Meow()
{
std::cout << "\n Meow ^^ .\n";
}
//теперь делаю класс Catty у которого будет конструктор и деструктор
//отличие от класса Cat только в строчке выше
//в main() покажу как использовать
class Catty
{
public: //открытые переменные , иначе закрытые
Catty(int initialAge); //конструктор
~Catty(); //деструктор
void Meow(); //функцие не надо ни чего возвращать - void
int GetAge();
int setAge(int age);
private:
int itsAge;
};
Catty::Catty(int initialAge){ //тот самый конструктор
itsAge = initialAge;
}
Catty::~Catty() //деструктор не делает ни чего
{}
int Catty::GetAge()
{
return itsAge;
}
int Catty::setAge(int age)
{
itsAge = age;
}
void Catty::Meow()
{
std::cout << "\n Meow ^^ I'm Catty .\n";
}
int main()
{
//обычный класс Cat
Cat Frisky;
Frisky.setAge(7);
Frisky.Meow();
std::cout << "\n Cat yars : "<<Frisky.GetAge();
Frisky.Meow();
std::cout << "\n \n";
//класс с конструктором и деструктором Catty
Catty Malinka(171);
Malinka.Meow();
std::cout << "\n Catty yars : "<<Malinka.GetAge()
<<"seted age ";
Malinka.setAge(7);
std::cout << "\n Cat yars when we use setAge(): "<<Malinka.GetAge();
Malinka.Meow();
return 0;
}
| true |
754b066a95aed7a1d4956a9bff393c100498ba41 | C++ | WonJoonPark/BOJ-Algorithm | /1600-1.cpp | UHC | 1,889 | 2.5625 | 3 | [] | no_license | #include<iostream>
#include<string>
#include<algorithm>
#include<vector>
#include<queue>
using namespace std;
int k, w, h;
int chesspan[200][200];
bool visit[200][200][31]; //k 0~30
int horsemovex[8] = { -1,-2,-2,-1,1,2,2,1 };
int horsemovey[8] = { -2,-1,1,2,2,1,-1,-2 };
int dx[4] = { 0,0,1,-1 }; //k Ҹ
int dy[4] = { 1,-1,0,0 };
int s = 0;
int mincount = 99999999;
bool fail = false;
struct xyk {
int x, y, kn,s;
};
queue<xyk> tmpq;
void inputs() { //1 ֹ
cin >> k >> w >> h;
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
cin >> chesspan[i][j];
}
}
}
bool boundcheck(int x, int y) {
if (x >= 0 && x < h && y >= 0 && y < w) return true;
else return false;
}
int bfs() {
while (1) {
int qsize = tmpq.size();
while (qsize--) {
if (tmpq.empty()) { fail = true; return 0; }
int nextx = tmpq.front().x;
int nexty = tmpq.front().y;
int nextk = tmpq.front().kn;
int nexts = tmpq.front().s;
tmpq.pop();
if (nextx == h - 1 && nexty == w - 1) {
return nexts; }
if (nextk != 0) {
for (int i = 0; i < 8; i++) {
int tx = nextx+ horsemovex[i]; int ty =nexty+ horsemovey[i];
if (boundcheck(tx, ty) && visit[tx][ty][nextk-1] == false && chesspan[tx][ty] != 1) {
tmpq.push({ tx,ty,nextk - 1,nexts +1 });
visit[tx][ty][nextk-1] = true;
}
}
}
for (int i = 0; i < 4; i++) {
int tx2=nextx +dx[i]; int ty2 =nexty+ dy[i];
if (boundcheck(tx2, ty2) && visit[tx2][ty2][nextk] == false && chesspan[tx2][ty2] != 1) {
tmpq.push({ tx2,ty2,nextk,nexts +1 });
visit[tx2][ty2][nextk] = true;
}
}
}
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
inputs();
tmpq.push({ 0,0,k,0 });
// 0,0 h-1,w-1
int r=bfs();
if (fail == true) { cout << -1 << "\n"; }
else cout <<r << "\n";
return 0;
} | true |
cc0e6befd88592092f791f52199952295aabcc11 | C++ | SergiPC/Ready_for_exam | /Programació02_All_in/Programació02_All_in/DLinkedList.h | WINDOWS-1252 | 7,679 | 3.375 | 3 | [] | no_license | // --------------------------------------------
// DLinkedList class
// --------------------------------------------
#ifndef __DLINKEDLIST_H__
#define __DLINKEDLIST_H__
#include <assert.h>
#include "Utilities.h"
#define NULL 0 // for not carrying the entire library
// node from a Double Linked List ----------------------
template<class DITTO>
struct DListNode
{
DITTO data;
DListNode<DITTO>* next;
DListNode<DITTO>* prev;
// Constructor -----------------------------------------
inline DListNode(const DITTO& new_data)
{
data = new_data;
next = prev = NULL;
}
// Destructor ------------------------------------------
~DListNode()
{}
};
// Manages a double linked list ------------------------
template<class DITTO>
class DLinkedList
{
public:
DListNode<DITTO>* head;
DListNode<DITTO>* bottom;
private:
unsigned int size; // number of nodes
public:
// Constructor -----------------------------------------
DLinkedList()
{
head = bottom = NULL;
size = 0;
}
// Destructor ------------------------------------------
~DLinkedList()
{
delAll();
}
// EXAMEN RECUPERACI PROGRAMACI 2 (3 JULIOL 2015)
// Mtode List::Flip de la llista enllaada per girar-la lordre:
void flip()
{
DListNode<DITTO>* tmp = head;
DListNode<DITTO>* tmp2 = bottom;
unsigned int middle = size / 2;
for (unsigned int i = 0; i < middle; i++)
{
swap(tmp->data, tmp2->data);
tmp = tmp->next;
tmp2 = tmp2->prev;
}
}
// FINAL EXAMEN RECUPERACI PROGRAMACI 2 (3 JULIOL 2015)
void swap(DITTO& a, DITTO& b)
{
DITTO tmp = a;
a = b;
b = tmp;
}
// EXAMEN FINAL PROGRAMACI 2 (9 JUNY 2015)
// DLinkedList :: Mtode a la classe de llista enllaada que insereixi una altre llista enllaada desprs
// de un index donat.Si la llista est buida ha de afegir tots els elements : ----------------------------
//insertAfter(0, mylist2)
void insertAfter(unsigned int index, const DLinkedList<DITTO>& other_list)
{
DListNode<DITTO>* tmp_my_list = at(index);
DListNode<DITTO>* tmp_other_list = other_list.head;
while (tmp_other_list != NULL)
{
DListNode<DITTO>* new_item = new DListNode<DITTO>(tmp_other_list->data);
//new_item->next = (tmp_my_list) ? tmp_my_list->next : NULL;
if (tmp_my_list != NULL)
new_item->next = tmp_my_list->next;
if (new_item->next != NULL)
new_item->next->prev = new_item;
else
bottom = new_item;
new_item->prev = tmp_my_list;
if (new_item->prev != NULL)
new_item->prev->next = new_item;
else
head = new_item;
tmp_my_list = new_item;
tmp_other_list = tmp_other_list->next;
}
}
// FINAL EXAMEN PARCIAL PROGRAMACI 2 (9 JUNY 2015)
// Some operators --------------------------------------
const DITTO& operator[](unsigned int index) const
{
long pos;
DListNode<DITTO>* tmp;
pos = 0;
tmp = head;
while (tmp != NULL)
{
if (pos == index)
break;
++pos;
tmp = tmp->next;
}
assert(tmp);
return(tmp->data);
}
DITTO& operator[](unsigned int index)
{
long pos;
DListNode<DITTO>* tmp;
pos = 0;
tmp = head;
while (tmp != NULL)
{
if (pos == index)
break;
++pos;
tmp = tmp->next;
}
assert(tmp);
return tmp->data;
}
const DLinkedList<DITTO>& operator +=(const DLinkedList<DITTO>& other_list)
{
DListNode<DITTO>* tmp = other_list.head;
while (tmp != NULL)
{
addNode(tmp->data);
tmp = tmp->next;
}
return(*this);
}
// Data management -------------------------------------
// Add its data to a DynArray.
void addToDynArray(DynArray<DITTO>& other_array)
{
if (other_array.num_elements + size > other_array.capacity)
other_array.alloc(other_array.num_elements + size);
for (unsigned int i = other_array.num_elements, unsigned int j = 0; i < (other_array.num_elements + size); i++, j++)
other_array.queue[other_array.num_elements++] = [j];
}
// Add new node at bottom
unsigned int addNode(const DITTO& new_data)
{
DListNode<DITTO>* new_node;
new_node = new DListNode<DITTO>(new_data);
if (head == NULL)
head = bottom = new_node;
else
{
new_node->prev = bottom;
bottom->next = new_node;
bottom = new_node;
}
return(++size); // ++size increments size and returns the incremented number
}
bool delNode(const DListNode<DITTO>* node)
{
if (node == NULL)
return false;
if (node->prev != NULL)
{
node->prev->next = node->next;
if (node->next != NULL)
node->next->prev = node->prev;
else
bottom = node->prev;
}
else
{
if (node->next) // only get in if node->next != NULL
{
node->next->prev = NULL;
head = node->next;
}
else
head = bottom = NULL;
}
delete node;
--size;
return true;
}
// Delete some nodes
unsigned int delNodes(int position, int num_nodes)
{
DListNode<DITTO>* tmp_node = head;
DListNode<DITTO>* tmp_next;
unsigned int deletedNodes = 0;
unsigned int needed_size = num_nodes + position;
if (position > size || num_nodes == 0) // if position isn't a valid number, or nummber of nodes deleted == 0
return deletedNodes;
for (int i = 0; i < position; i++) // searching node
tmp_node = tmp_node->next;
if (tmp_node == NULL)
return deletedNodes;
if (needed_size > size)
num_nodes = size - position;
for (int p = 0; p < num_nodes; p++)
{
if (tmp_node->prev != NULL)
{
tmp_node->prev->next = tmp_node->next;
if (tmp_node->next != NULL)
tmp_node->next->prev = tmp_node->prev;
else
bottom = tmp_node->prev;
}
else
{
if (tmp_node->next) // only get in if tmp_node->next != NULL
{
tmp_node->next->prev = NULL;
head = tmp_node->next;
}
else
head = bottom = NULL;
}
tmp_next = tmp_node->next;
delete tmp_node;
tmp_node = tmp_next;
--size;
}
return deletedNodes;
}
// Destroy and free for all!
void delAll()
{
DListNode<DITTO>* tmp_data;
DListNode<DITTO>* tmp_next;
tmp_data = head;
while (tmp_data != NULL)
{
tmp_next = tmp_data->next;
delete tmp_data;
tmp_data = tmp_next;
}
head = bottom = NULL;
size = 0;
}
// Set in order ----------------------------------------
int bubbleSort()
{
int ret = 0;
bool swapped = true;
while (swapped)
{
swapped = false;
DListNode<DITTO>* tmp = head;
while (tmp != NULL && tmp->next != NULL)
{
++ret;
if (tmp->data > tmp->next->data)
{
swap(tmp->data, tmp->next->data); // Swap Nodes -----
swapped = true;
}
tmp = tmp->next;
}
}
return ret;
}
// Utilities -------------------------------------------
unsigned int count()
{
return(size);
}
// returns the first apperance of data as count (-1 if not found)
int find(const DITTO& old_data)
{
DListNode<DITTO>* tmp = head;
int count = 0;
while (tmp != NULL)
{
if (tmp->data == old_data)
{
return(count);
}
++count;
tmp = tmp->next;
}
return (-1);
}
const DListNode<DITTO>* at(unsigned int index) const
{
long pos = 0;
DListNode<DITTO>* tmp = head;
while (tmp != NULL)
{
if (pos == index)
break;
++pos;
tmp = tmp->next;
/*
if (pos++ == index)
break;
tmp = tmp->next;
*/
}
return tmp;
}
// access to a node in a position in the list
DListNode<DITTO>* at(unsigned int index)
{
long pos = 0;
DListNode<DITTO>* tmp = head;
while (tmp != NULL)
{
if (pos == index)
break;
++pos;
tmp = tmp->next;
/*
if (pos++ == index)
break;
tmp = tmp->next;
*/
}
return tmp;
}
};
#endif // __DLINKEDLIST_H__ | true |
472c2c0389d8f76d64a2b8be2ed921156dbae425 | C++ | WenjieZhang1/leetcode | /divide.cpp | UTF-8 | 895 | 3.34375 | 3 | [] | no_license | # include <iostream>
using namespace std;
int divide(int dividend, int divisor) {
if(divisor==0 || (dividend==INT_MIN && divisor==-1)) return INT_MAX;
if(divisor==1) return dividend;
bool flag=((dividend>0 && divisor<0) || (dividend<0 && divisor>0));
long dividend_abs = abs((long)dividend);
long divisor_abs = abs((long)divisor);
int res=0;
while(dividend_abs >= divisor_abs){
for(int i=0; dividend_abs >= divisor_abs*(1<<i); ++i){
dividend_abs-= divisor_abs*(1<<i);
res+=(1<<i);
}
}
//cout<<flag<<'\n';
return flag? -res: res;
}
int main(){
//int dividend=1; int divisor=-1;
//bool flag=((dividend>0 && divisor<0) || (dividend<0 && divisor>0));
//cout<<flag<<endl;
int res=divide(1,-1);
cout<<res<<'\n';
return 0;
} | true |
1a7ebd253dcd088a9150584a11b1fd365445ffd3 | C++ | bp274/HackerRank | /Algorithms/Implementation/Birthday Chocolate.cpp | UTF-8 | 496 | 2.578125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin >> n ;
int s[n] ;
for(int i = 0; i < n; i++)
{
cin >> s[i] ;
}
int d, m ;
cin >> d >> m ;
int count=0, sum ;
for(int i=0; i<=n-m; i++)
{
sum=0 ;
for(int j=i; j<m+i; j++)
{
sum = sum + s[j] ;
}
if(sum == d)
{
count++ ;
}
}
cout << count ;
return 0;
}
| true |
49379711829b15a1f4f79f99303ade71b3b0d07f | C++ | MaltsevaNata/OOP | /Merge/Merge.cpp | UTF-8 | 7,144 | 3.4375 | 3 | [] | no_license | //
// Created by natas on 18.02.2019.
//
#include "Merge.h"
#include <iostream>
void MergeSort (int *arr, int begin, int end) {
if (begin < end)
{
MergeSort(arr, begin, (begin+end)/2);//сортировка левой части
MergeSort(arr, (begin+end)/2+1, end); //сортировка правой части
Merge(arr, begin, end); //слияние двух частей
}
}
void Merge(int *arr, int begin, int end) {
int middle = (begin + end)/2;
int start = begin;
int final = middle+1;
int *buf = new int[end+1];
for (int i = begin; i<=end; i++) {
if ((start<= middle) && ((final>end) || (arr[start] < arr[final]))) {
buf[i] = arr[start];
start++;
}
else {
buf[i] = arr[final];
final++;
}
}
for (int i = begin; i<=end; i++) {
arr[i] = buf[i];
}
delete[] buf;
}
void swap(int *arr, int first_index, int second_index) {
int temp = arr[first_index];
arr[first_index] = arr[second_index];
arr[second_index] = temp;
}
void Insert(int* arr, int size) {
int item;
int place;
for (int i = 1; i < size; i++)
{
item = arr[i];
place = i - 1;
while(place >= 0 && arr[place] > item)
{
arr[place+1] = arr[place];
place --;
}
arr[place+1] = item;
}
}
int CalcRun (int size) { // выбираем run, равный степени 2
bool flag = 0; // будет равно 1, если среди сдвинутых битов есть хотя бы один ненулевой
while (size >= 48) {
flag |= size & 1;
size >>= 1;
}
return size + flag;
}
void Add(int start, int size, List *&Subarray) {
List *temp = new List; //Выделяем память для нового элемента
temp->start_index = start; //Записываем в поля стека принимаемые элементы
temp->sub_size = size;
temp->next = Subarray->head; //Указываем, что следующий элемент это предыдущий
Subarray->head = temp; //Сдвигаем голову на позицию вперед
}
void ClearList(List *MyList)
{
while (MyList->head != NULL) //Пока по адресу не пусто
{
List *temp = MyList->head->next; //Временная переменная для хранения адреса следующего элемента
delete MyList->head; //Освобождаем адрес обозначающий начало
MyList->head = temp; //Меняем адрес на следующий
}
}
void timMerge(int * arr, List *&Subarray, int* buf) {
List *X = Subarray -> head;
int start_el = 0;
do {
Merge_sub(arr, X, buf, start_el);
start_el+=(X->sub_size);
X = X->next;
}
while (X != NULL);
}
void Merge_sub (int* arr, List *&Subarray, int* buf, int start_el) {
if (start_el == 0) {
for (int i = 0; i < Subarray->sub_size; i++) {
buf[i] = arr[Subarray->start_index + i];
}
}
else {
int temp[start_el];
for (int i = 0; i < start_el; i++) {
temp[i] = buf[i];
}
int index_temp = 0;
int index_sub = 0;
for (int i = 0; i < start_el + Subarray->sub_size; i++) {
if (index_temp <= start_el) {
if (index_sub <= Subarray->sub_size) {
if (temp[index_temp] < arr[Subarray->start_index + index_sub]) {
buf[i] = temp[index_temp];
index_temp++;
} else {
buf[i] = arr[Subarray->start_index + index_sub];
index_sub++;
}
} else {
//std::cout << "end of index_sub" << std::endl;
buf[i] = temp[index_temp];
}
} else {
if (index_sub <= Subarray->sub_size) {
//std::cout << "end of index_temp" << std::endl;
buf[i] = arr[Subarray->start_index + index_sub];
}
}
//std::cout << buf[i] << ' ';
}
//std::cout << std::endl;
}
}
void TimSort(int* arr, int size) {
int* start = arr;
int start_index = 0;
int run = CalcRun(size);
int end = run;
bool sorted = false;
//стек пар <индекс начала подмассива><размер подмассива>
List *Subarray = new List;
Subarray->head = NULL;
do {
Insert(start, run);
Add(start_index, run, Subarray);
if (end==size) sorted = true;
start += run;
start_index+=run;
end+=run;
if (end>size){
end = size;
run = end%run;
}
}
while (!sorted);
int *buf = new int[size+1];
for(int i = 0; i < 20; i++)
std::cout << arr[i] << ' ';
std::cout << std::endl;
timMerge(arr, Subarray, buf);
std::cout << " Merged ";
for(int i = 0; i < 20; i++)
arr[i] = buf[i] ;
std::cout << std::endl;
ClearList(Subarray); //Очищаем память.
delete Subarray->head;
delete Subarray;
}
void Show(List *MyList)
{
List *temp = MyList->head; //Объявляем указатель и Указываем ему, что его позиция в голове стека
//с помощью цикла проходим по всему стеку
while (temp != NULL) //выходим при встрече с пустым полем
{
std::cout << "Subarray "<< temp->start_index << " " << temp->sub_size << " "; //Выводим на экран элементы стека
temp = temp->next; //Переходим к следующему элементу
}
std::cout << std::endl;
}
/*
int Heap_2(int *arr, int size, int root = 0) {
if (root>=size) return;
if (2root >= size) return;
if (2root+1 >= size) return;
//
if (arr[2*root] < arr[2*root+1]) {
swap(arr, arr[2*root], arr[2*root+1]);
update_heap(arr, size, 2*root+1);
}
}
int update_heap(int *arr, int size, int root) {
if(2*root>=size) return;
if (2*root>=size-1) {
if (arr[root]<arr[2*root]) {
swap(arr[root], arr[2*root]);
return;
}
if (arr[root]<arr[2*root]) {
swap(arr[root], arr[2*root]);
return;
}
//тут что-тооо происходит
}
}
int Create_Heap(int* arr, int size, int root) {
for (root=size - 1; root > 0 ; root --) {
update_heap(arr, size, root);
}
}*/
| true |
0ee578ada1401891a13c81f01c01c8bb6db9554a | C++ | s-vde/talks | /testing-and-verifying-multithreaded-programs/examples/data_race.cpp | UTF-8 | 1,007 | 3.40625 | 3 | [] | no_license |
#include <thread>
//------------------------------------------------------------------
void thread0(std::mutex& m, int& x, int& y)
{
// m.lock();
int x_local = x;
// m.unlock();
if (x_local == 1) // datarace: line 23
{
y = 1; // datarace: line 25
}
pthread_exit(0);
}
//------------------------------------------------------------------
void thread1(std::mutex& m, int& x, int& y, int& z)
{
// m.lock();
x = 1; // datarace: line 9
// m.unlock();
z = x + y; // datarace: line 13
pthread_exit(0);
}
//------------------------------------------------------------------
int main()
{
int x, y, z;
std::mutex m;
std::thread t0(thread0, std::ref(m), std::ref(x), std::ref(y));
std::thread t1(thread1, std::ref(m), std::ref(x), std::ref(y), std::ref(z));
t0.join();
t1.join();
return 0;
}
//------------------------------------------------------------------
| true |
864f6a4886c320fa73d6d0ff52ef4154aaf5bf27 | C++ | RiyaGupta89/C-Coding-problems-for-beginners | /simpleInput.cpp | UTF-8 | 336 | 3.375 | 3 | [] | no_license | // Print all the numbers before the cumulative sum become negative.
#include<iostream>
using namespace std;
int main() {
int n;
int sum = 0;
while(true) {
cin>>n;
sum = sum + n;
if(sum >= 0) {
cout<<n<<endl;
}
else {
break;
}
}
return 0;
} | true |
aeb43fa4ff13dd060340012b3887467d6a6d7f7e | C++ | itzranjeet/Sensor_Fusion | /sensor_fusion/include/sensor_fusion/console_logger.hpp | UTF-8 | 1,787 | 2.546875 | 3 | [] | no_license | #include <iostream>
#include "logger_base.h"
#include "console_logger.h"
namespace sensor_fusion
{
template<typename... Args>
auto& ConsoleLogger::GetTypeLookupMap(Args&&... args)
{
static log_function_lookup_based_on_type type_lookup_;
type_lookup_[LogMessageType :: error] = [&args...](){
std::cout << "STD_ERROR: ";
printf(args...);
std::cout << std::endl;
};
type_lookup_[LogMessageType :: debug] = [&args...]() {
std::cout << "STD_DEBUG: ";
printf(args...);
std::cout << std::endl;
};
type_lookup_[LogMessageType :: warn] = [&args...]() {
std::cout << "STD_WARNING: ";
printf(args...);
std::cout << std::endl;
};
type_lookup_[LogMessageType :: info] = [&args...](){
std::cout << "STD_INFO: ";
printf(args...);
std::cout << std::endl;
};
return type_lookup_;
}
} //namespace sensor_fusion
| true |
78850f06525587bd39f49cefa704c752cab156cc | C++ | jrucl2d/Algorithm-Homework | /week5-1.cpp | UHC | 2,246 | 3.6875 | 4 | [] | no_license | #include <iostream> // 2015112083
#include <vector>
#include <fstream>
#include <string>
using namespace std;
#define NOWAY -1
int dp[5][5]; // (i,j) µ ִ
struct map {
int right;
int down;
};
void GetInfo(map** tour) {
ifstream file; // Է Ʈ
file.open("map_info.txt"); //
// Է¹ޱ
char info[50]; // 5*5 = 25 ʿ ؼ right, down Է
int index = 0;
while (!file.eof()) {
string s;
getline(file, s); // о.
info[index++] = s[0]; // s[0] right
info[index++] = s[2]; // s[2] down ִ.
}
index = 0;
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
char tmp1 = info[index++];
char tmp2 = info[index++];
if (tmp1 >= '0' && tmp1 <= '9') // right ̸ ְ
tour[i][j].right = tmp1 - '0';
else // ٴ 'n' -1 ־
tour[i][j].right = NOWAY;
if (tmp2 >= '0' && tmp2 <= '9')
tour[i][j].down = tmp2 - '0';
else
tour[i][j].down = NOWAY;
}
}
}
void DP(map** tour) { // O(n^2) ð
// Է( ã 1ۿ )
dp[0][0] = 0;
for (int i = 1; i < 5; i++) {
dp[i][0] = dp[i - 1][0] + tour[i - 1][0].down;
dp[0][i] = dp[0][i - 1] + tour[0][i - 1].right;
}
// 忡 ݺ
for (int i = 1; i < 5; i++) {
for (int j = 1; j < 5; j++) {
// ( or ) ̵ ū 츦 dp
if (dp[i - 1][j] + tour[i - 1][j].down > dp[i][j - 1] + tour[i][j - 1].right)
dp[i][j] = dp[i - 1][j] + tour[i - 1][j].down;
else dp[i][j] = dp[i][j - 1] + tour[i][j - 1].right;
}
}
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++)
cout << dp[i][j] << "\t";
cout << endl;
}
}
int main() {
map** tour = new map * [5]; // map 迭 Ҵ
for (int i = 0; i < 5; i++)
tour[i] = new map[5];
GetInfo(tour); // Ͽ Է¹
DP(tour); // ˰
} | true |
3b2584fd1fba1298327beebb370fa0adcde189d1 | C++ | sovaai/sova-engine | /src/InfEngine2/InfEngine/InfFunctions/FunctionsRegistry.hpp | UTF-8 | 15,325 | 2.546875 | 3 | [
"Apache-2.0"
] | permissive | #ifndef __FunctionsRegistry_hpp__
#define __FunctionsRegistry_hpp__
#include <InfEngine2/InfEngine/InfFunctions/InfInternalFunction.hpp>
#include <InfEngine2/InfEngine/InfFunctions/InfExternalFunction.hpp>
/**
* Реестр функций языка DL.
*/
class FunctionsRegistry
{
public:
/** Конструктор реестра. */
FunctionsRegistry() { Create(); }
/** Открытие реестра. */
virtual InfEngineErrors Create();
/** Закрытие открытого ранее реестра. */
virtual void Close() = 0;
/** Получение числа зарегистрированных функций. */
unsigned int GetFunctionsNumber() const { return vFuncNameIndex.GetNamesNumber(); }
/**
* Поиск зарегистрированной функции.
* @param aFuncName - имя переменной.
* @param aFuncNameLength - длина имени переменной.
* @param aFuncId - идентификатор найденной переменной.
*/
InfEngineErrors Search( const char * aFuncName, unsigned int aFuncNameLength, unsigned int & aFuncId ) const;
/**
* Получение имени функции по идентификатору.
* @param aFuncId - идентификатор функции.
*/
const char * GetFuncNameById( unsigned int aFuncId ) const { return vFuncNameIndex.GetName( aFuncId ); }
/**
* Получение имени функции по идентификатору.
* @param aFuncId - идентификатор функции.
* @param aFuncNameLength - длина имени функции.
*/
const char * GetFuncNameById( unsigned int aFuncId, unsigned int & aFuncNameLength ) const
{
return vFuncNameIndex.GetName( aFuncId, aFuncNameLength );
}
/**
* Возвращает адрес реализации функции.
* @param aFuncId - идентификатор функции.
*/
virtual const FDLFucntion GetFunction( unsigned int aFuncId ) const;
/**
* Возвращает указатель на тип функции.
* @param aFuncId - идентификатор функции.
*/
virtual const DLFunctionResType * GetFunctionResType( unsigned int aFuncId ) const = 0;
/**
* Возвращает указатель на количество аргументов у заданной функции.
* @param aFuncId - идентификатор функции.
*/
virtual const unsigned int * GetFunctionArgCount( unsigned int aFuncId ) const = 0;
/**
* Возвращает указатель на информацию об аргументе функции.
* @param aFuncId - идентификатор функции.
* @param aArgNum - номер аргумента.
*/
virtual const DLFucntionArgInfo * GetFunctionArgInfo( unsigned int aFuncId, unsigned int aArgNum ) const = 0;
/**
* Возвращает истинное значение, если у функции переменное число аргументов.
* @param aFuncId - идентификатор функции.
*/
virtual bool HasVarArgs( unsigned int aFuncId ) const = 0;
/**
* Получение MD5 чексуммы реестра (без учёта версий).
* @param aDigest - чексумма реестра.
*/
virtual void GetMD5Digits( unsigned char aDigest[16] ) const = 0;
/**
* Проверяет, загружена ли группа функций для эмулирования оператора If.
*/
virtual bool IfGroupIsLoaded() const = 0;
/**
* Возвращает указатель на вектор флагов, описвающих свойства функции.
* @param aFuncId - идентификатор функции.
*/
virtual const DLFunctionOptions * GetOptions( unsigned int aFuncId ) const = 0;
/**
* Возвращает указатель на информацию о функции.
* @param aFuncId - идентификатор функции.
*/
virtual const DLFunctionInfo * GetFunctionInfo( unsigned int aFuncId ) const = 0;
protected:
/** Индекс имен функций. */
NanoLib::NameIndex vFuncNameIndex;
/** Индекс альтернативных имен функций. */
NanoLib::NameIndex vFuncShortNameIndex;
};
/**
* Реестр функций языка DL, используемый для компиляции списка функций.
*/
class FunctionsRegistryWR : public FunctionsRegistry
{
public:
FunctionsRegistryWR() {}
private:
FunctionsRegistryWR( const FunctionsRegistryWR& );
FunctionsRegistryWR& operator=( const FunctionsRegistryWR& );
public:
/** Открытие реестра. */
virtual InfEngineErrors Create();
/** Возвращает размер места, необходимого для сохранения объекта. */
unsigned int GetNeedMemorySize() const;
/**
* Сохранение реестра в fstorage.
* @param aFStorage - открытый fstorage.
*/
InfEngineErrors Save( fstorage * aFStorage ) const;
/** Закрытие открытого ранее реестра. */
virtual void Close();
/**
* Регистрация новой внешней функции. Если такая функция уже существует, то будет возвращен
* код ошибки #INF_ENGINE_UNSUCCESS.
* @param aFilePath - адрес динамической библиотеки. содержащие функцию.
* @param aFuncId - зарегистрированный идентификатор функции.
*/
InfEngineErrors RegistryNew( const char * aFilePath, unsigned int & aFuncId )
{
ReturnWithTraceExt( Registry( aFilePath, aFuncId ), INF_ENGINE_SUCCESS );
}
/**
* Регистрация новой внутренней функции. Если такая функция уже существует, то будет возвращен
* код ошибки #INF_ENGINE_UNSUCCESS.
* @param aDLFunctionInfo - описание функции.
* @param aFuncId - зарегистрированный идентификатор функции.
*/
InfEngineErrors RegistryNew( const DLFunctionInfo * aDLFunctionInfo, unsigned int & aFuncId )
{
ReturnWithTraceExt( Registry( aDLFunctionInfo, aFuncId ), INF_ENGINE_SUCCESS );
}
/**
* Регистрация внешней функции. Если такая функция уже существует, то будет возвращен ее идентификатор.
* @param aFilePath - адрес динамической библиотеки, содержащие функцию.
* @param aFuncId - зарегистрированный идентификатор функции.
*/
InfEngineErrors Registry( const char * aFilePath, unsigned int & aFuncId );
/**
* Регистрация внутренней функции. Если такая функция уже существует, то будет возвращен ее идентификатор.
* @param aDLFunctionInfo - описание функции.
* @param aFuncId - зарегистрированный идентификатор функции.
*/
InfEngineErrors Registry( const DLFunctionInfo * aDLFunctionInfo, unsigned int & aFuncId );
/**
* Регистрация всех внешних функций, перечисленных в заданном конфигурационном файле.
* @param aFilePath - адрес файла со списком адресов динамических библиотек, содержащих DL-функции.
* @param aRootDir - адрес каталога, в котором находятся динамические библиотеки с DL-функциями.
*/
InfEngineErrors RegistryAll( const char * aFilePath, const char * aRootDir );
/**
* Получение MD5 чексуммы реестра (без учёта версий).
* @param aDigest - чексумма реестра.
*/
virtual void GetMD5Digits( unsigned char aDigest[16] ) const;
/**
* Возвращает указатель на тип реализации функции.
* @param aFuncId - идентификатор функции.
*/
virtual const DLFunctionType * GetFunctionType( unsigned int aFuncId ) const;
/**
* Возвращает указатель на тип функции.
* @param aFuncId - идентификатор функции.
*/
virtual const DLFunctionResType * GetFunctionResType( unsigned int aFuncId ) const;
/**
* Возвращает казатель на количество аргументов у заданной функции.
* @param aFuncId - идентификатор функции.
*/
virtual const unsigned int * GetFunctionArgCount( unsigned int aFuncId ) const;
/**
* Возвращает казатель на информацию об аргументе функции.
* @param aFuncIf - идентификатор функции.
* @param aArgNum - номер аргумента.
*/
virtual const DLFucntionArgInfo * GetFunctionArgInfo( unsigned int aFuncId, unsigned int aArgNum ) const;
/**
* Возвращает истинное значение, если у функции переменное число аргументов.
* @param aFuncId - идентификатор функции.
*/
virtual bool HasVarArgs( unsigned int aFuncId ) const;
/**
* Проверяет, загружена ли группа функций для эмулирования оператора If.
*/
virtual bool IfGroupIsLoaded() const;
/**
* Возвращает указатель на вектор флагов, описвающих свойства функции.
* @param aFuncIf - идентификатор функции.
*/
virtual const DLFunctionOptions * GetOptions( unsigned int aFuncId ) const;
/**
* Возвращает указатель на информацию о функции.
* @param aFuncId - идентификатор функции.
*/
virtual const DLFunctionInfo * GetFunctionInfo( unsigned int aFuncId ) const;
private:
/**
* Регистрация функции. Если такая функция уже существует, то будет возвращен ее идентификатор.
* @param aFunction - функция.
* @param aFuncId - зарегистрированный идентификатор функции.
*/
InfEngineErrors Registry( InfFunction * aFunction, unsigned int aFuncId );
private:
/** Список функций. */
avector<InfFunction*> vFunctions;
/** Локальный аллокатор */
nMemoryAllocator vLocalAllocator;
/** Текущее MD5 состояние. */
MD5_CTX vMD5State;
/** MD5 чексумма. */
unsigned char vMD5Digest[16];
/** Флаг наличия группы функций для эмулирования оператора If */
bool vIfGroupIsLoaded { false };
};
/**
* Реестр функций языка DL, используемый для загрузки списка функций.
*/
class FunctionsRegistryRO : public FunctionsRegistry
{
public:
FunctionsRegistryRO() {}
private:
FunctionsRegistryRO( const FunctionsRegistryRO& );
FunctionsRegistryRO& operator=( const FunctionsRegistryRO& );
public:
/** Закрытие открытого ранее реестра. */
virtual void Close();
/**
* Открытие реестра без копирования данных в память.
* @param aFStorage - открытый fstorage.
* @param aRootDir - корневой каталог для функций.
* @param aConfigPath - путь к конфигурационному файлу функций.
*/
InfEngineErrors Open( fstorage * aFStorage, const char * aRootDir, const char * aConfigPath );
/** Возвращает исинное значение, если индекс был успешно открыт. */
bool IsOpened() const;
/**
* Возвращает адрес реализации функции.
* @param aFuncId - идентификатор функции.
*/
virtual const FDLFucntion GetFunction( unsigned int aFuncId ) const;
/**
* Возвращает указатель на тип функции.
* @param aFuncId - идентификатор функции.
*/
virtual const DLFunctionResType * GetFunctionResType( unsigned int aFuncId ) const;
/**
* Возвращает казатель на количество аргументов у заданной функции.
* @param aFuncIf - идентификатор функции.
*/
virtual const unsigned int * GetFunctionArgCount( unsigned int aFuncId ) const;
/**
* Возвращает казатель на информацию об аргументе функции.
* @param aFuncIf - идентификатор функции.
* @param aArgNum - номер аргумента.
*/
virtual const DLFucntionArgInfo * GetFunctionArgInfo( unsigned int aFuncId, unsigned int aArgNum ) const;
/**
* Возвращает истинное значение, если у функции переменное число аргументов.
* @param aFuncId - идентификатор функции.
*/
virtual bool HasVarArgs( unsigned int aFuncId ) const;
/**
* Получение MD5 чексуммы реестра (без учёта версий).
* @param aDigest - чексумма реестра.
*/
virtual void GetMD5Digits( unsigned char aDigest[16] ) const;
/**
* Проверяет, загружена ли группа функций для эмулирования оператора If.
*/
virtual bool IfGroupIsLoaded() const;
/**
* Возвращает указатель на вектор флагов, описвающих свойства функции.
* @param aFuncIf - идентификатор функции.
*/
virtual const DLFunctionOptions * GetOptions( unsigned int aFuncId ) const;
/**
* Возвращает указатель на информацию о функции.
* @param aFuncId - идентификатор функции.
*/
virtual const DLFunctionInfo * GetFunctionInfo( unsigned int aFuncId ) const;
/**
* Загрузка реализаций DL функций в память.
* @param aRootDir - корневой каталог для функций.
* @param aConfigPath - путь к конфигурационному файлу функций.
*/
InfEngineErrors LoadDynamicLibraries( const char * aRootDir, const char * aConfigPath );
private:
/** Признак успешного открытия индекса. */
bool vIsOpened { false };
/** Список функций только для чтения. */
InfFunctionManipulator ** vFunctionsRO { nullptr };
/** Локальный аллокатор */
nMemoryAllocator vLocalAllocator;
/** MD5 чексумма. */
const unsigned char * vMD5Digest { nullptr };
/** Флаг наличия группы функций для эмулирования оператора If */
bool vIfGroupIsLoaded { false };
};
#endif // __FunctionsRegistry_hpp__
| true |
eb12a209f1fec874a0ede14b77946d825ffe644c | C++ | leisheyoufu/study_exercise | /algorithm/leetcode/107_Binary_Tree_Level_Order_Traversal_II/main.cpp | UTF-8 | 1,658 | 3.671875 | 4 | [] | no_license | /*
107. Binary Tree Level Order Traversal II
Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its bottom-up level order traversal as:
[
[15,7],
[9,20],
[3]
]
*/
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<queue>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
public:
vector<vector<int> > levelOrderBottom(TreeNode* root)
{
vector<vector<int> > ret(0, vector<int>());
if(!root) {
return ret;
}
queue<TreeNode*> q;
q.push(root);
int curr = 0;
int total = 0;
int last = 1;
vector<int> line;
while(!q.empty()) {
TreeNode *temp = q.front();
q.pop();
line.push_back(temp->val);
if(temp->left) {
total ++;
q.push(temp->left);
}
if(temp->right) {
total++;
q.push(temp->right);
}
curr ++;
if(curr == last) {
last = total;
total = 0;
curr = 0;
ret.push_back(line);
line.clear();
}
}
reverse(ret.begin(), ret.end());
return ret;
}
};
int main()
{
Solution sln;
system("pause");
return 0;
}
| true |
6f52761098abdca83e5ce2e57b23ea6a6660221e | C++ | better-712/Compilers-project | /spl_project4/visitor.hpp | UTF-8 | 4,038 | 2.640625 | 3 | [] | no_license | //
// Created by 10578 on 11/4/2019.
//
#ifndef __VISITOR_HPP__
#define __VISITOR_HPP__
#include "ast.hpp"
namespace SPL {
class Exp_Info;
template<typename T, typename S, typename E>
class AST_Visitor {
public:
/* Internal Nodes */
virtual T visit(Program_Node *node) = 0;
virtual T visit(ExtDefList_Node *node) = 0;
virtual T visit(ExtDef_Node *node) = 0;
virtual T visit(ExtDecList_Node *node) = 0;
virtual T visit(Specifier_Node *node) = 0;
virtual T visit(StructSpecifier_Node *node) = 0;
virtual T visit(CompSt_Node *node) = 0;
virtual T visit(StmtList_Node *node) = 0;
virtual T visit(DefList_Node *node) = 0;
virtual T visit(DecList_Node *node) = 0;
virtual T visit(VarList_Node *node) = 0;
virtual T visit(Args_Node *node) = 0;
/* Declaration Node */
virtual T visit(ID_VarDec_Node *node) = 0;
virtual T visit(Array_VarDec_Node *node) = 0;
virtual T visit(FunDec_Node *node) = 0;
virtual T visit(ParamDec_Node *node) = 0;
/* Statement Node */
virtual S visit(Exp_Stmt_Node *node) = 0;
virtual S visit(CompSt_Stmt_Node *node) = 0;
virtual S visit(Return_Stmt_Node *node) = 0;
virtual S visit(If_Stmt_Node *node) = 0;
virtual S visit(While_Stmt_Node *node) = 0;
/* Expression Node */
virtual E visit(Parentheses_Exp_Node *node) = 0;
virtual E visit(ID_Parentheses_Exp_Node *node) = 0;
virtual E visit(Bracket_Exp_Node *node) = 0;
virtual E visit(Dot_Exp_Node *node) = 0;
virtual E visit(Binary_Exp_Node *node) = 0;
virtual E visit(Unary_Exp_Node *node) = 0;
virtual E visit(Leaf_Exp_Node *node) = 0;
/* Definition Node */
virtual T visit(Def_Node *node) = 0;
virtual T visit(Dec_Node *node) = 0;
/* Leaf Node */
virtual void visit(Leaf_Node *node) = 0;
/* Empty Node */
virtual void visit(Empty_ExtDefList_Node *node) = 0;
virtual void visit(Empty_StmtList_Node *node) = 0;
virtual void visit(Empty_DefList_Node *node) = 0;
virtual void visit(Empty_DecList_Node *node) = 0;
};
class Visitor : public AST_Visitor<void, void, Exp_Info *> {
public:
/* Internal Nodes */
void visit(Program_Node *node) override;
void visit(ExtDefList_Node *node) override;
void visit(ExtDef_Node *node) override;
void visit(ExtDecList_Node *node) override;
void visit(Specifier_Node *node) override;
void visit(StructSpecifier_Node *node) override;
void visit(CompSt_Node *node) override;
void visit(StmtList_Node *node) override;
void visit(DefList_Node *node) override;
void visit(DecList_Node *node) override;
void visit(VarList_Node *node) override;
void visit(Args_Node *node) override;
/* Declaration Node */
void visit(ID_VarDec_Node *node) override;
void visit(Array_VarDec_Node *node) override;
void visit(FunDec_Node *node) override;
void visit(ParamDec_Node *node) override;
/* Statement Node */
void visit(Exp_Stmt_Node *node) override;
void visit(CompSt_Stmt_Node *node) override;
void visit(Return_Stmt_Node *node) override;
void visit(If_Stmt_Node *node) override;
void visit(While_Stmt_Node *node) override;
/* Expression Node */
Exp_Info *visit(Parentheses_Exp_Node *node) override;
Exp_Info *visit(ID_Parentheses_Exp_Node *node) override;
Exp_Info *visit(Bracket_Exp_Node *node) override;
Exp_Info *visit(Dot_Exp_Node *node) override;
Exp_Info *visit(Binary_Exp_Node *node) override;
Exp_Info *visit(Unary_Exp_Node *node) override;
Exp_Info *visit(Leaf_Exp_Node *node) override;
/* Definition Node */
void visit(Def_Node *node) override;
void visit(Dec_Node *node) override;
/* Leaf Node */
void visit(Leaf_Node *node) override;
/* Empty Node */
void visit(Empty_ExtDefList_Node *node) override {};
void visit(Empty_StmtList_Node *node) override {};
void visit(Empty_DefList_Node *node) override {};
void visit(Empty_DecList_Node *node) override {};
/* Help function */
void visit_children(AST_Node *node);
void check(AST_Node *node);
};
}
#endif //__VISITOR_HPP__
| true |
f670ec598001b9064f9c03c95352656c2609e0c4 | C++ | zpiao1/CPP-Primer | /Code8-2-2_1.cpp | UTF-8 | 518 | 3.203125 | 3 | [] | no_license | #include <fstream>
#include <string>
using namespace std;
int main()
{
// file1 is truncated in each of these cases
ofstream out("file1"); // out and trunc are implicit
ofstream out2("file1", ofstream::out); // trunc is implicit
ofstream out3("file1", ofstream::out | ofstream::trunc);
// to preserve the file's contents, we must explicitly specify app mode
ofstream app("file2", ofstream::app); // out is implicit
ofstream app2("file2", ofstream::out | ofstream::app);
return 0;
} | true |
5f62538501c81c61348c5f81d4a8640350efd816 | C++ | HerculesShek/cpp-practise | /src/ch4/precedence/demo03.cc | UTF-8 | 170 | 2.8125 | 3 | [
"MIT"
] | permissive | #include <iostream>
using namespace std;
int main()
{
short short_value = 32767;
short_value += 1;
cout << "short_value: " << short_value << endl;
return 0;
}
| true |
0ef266f27ddeb4daf6954c0ba28e4340f2d17cc4 | C++ | ilovethisid/Assignments | /MainSystem.cpp | UTF-8 | 1,303 | 2.84375 | 3 | [] | no_license | #include <stdio.h>
#include <iostream>
#include <conio.h>
#include <Windows.h>
#include "Window.h"
#include "Stats.h"
#include "Units.h"
#include "Properties.h"
using namespace std;
// function headers
void gamestart(Window, Stats);
void gameover();
void pickCard(NumUnits, Window, Stats);
// structure
int main(void)
{
Stats stats = Stats();
Window win = Window(stats);
gamestart(win, stats);
return 0;
}
void gamestart(Window win, Stats stats)
{
bool isGameover = false;
NumUnits numUnits = NumUnits();
while (!isGameover)
{
win.gotoxy(0, 20);
pickCard(numUnits, win, stats);
win.getCommand(stats);
}
gameover();
}
void gameover()
{
}
// ingame functions
void pickCard(NumUnits numUnits, Window win, Stats stats)
{
win.gotoxy(win.commandPanel.x, win.commandPanel.y);
cout << "Picking a card..." << endl;
Units newUnit = Farmer();
cout << "You picked " << newUnit.name << endl;
numUnits.farmer++;
while (!_kbhit())
{
// wait until any key is pressed
}
FlushConsoleInputBuffer(GetStdHandle(STD_INPUT_HANDLE));
stats.totalIncome.money += newUnit.income.money;
stats.totalIncome.food += newUnit.income.food;
stats.totalIncome.mineral += newUnit.income.mineral;
win.refresh(stats);
} | true |
a97a6e3ba19a36569a8d9ebbfe017c4e8ac5ff55 | C++ | Lucria/MyKattisSolutions | /ReachableRoads.cpp | UTF-8 | 2,035 | 2.5625 | 3 | [] | no_license | // Created by Jerry
#include <iostream>
#include <iomanip>
#include <cmath>
#include <math.h>
#include <algorithm>
#include <vector>
#include <string.h>
#include <string>
#include <sstream>
#include <list>
#include <stack>
#include <set>
#include <queue>
#include <map>
#include <unordered_map>
#include <unordered_set>
using namespace std;
typedef vector<int> vi;
typedef long long ll;
#define M_PI 3.14159265358979323846
void check(int i, vector<list<int>> &al, vector<bool> &visited) {
visited[i] = true;
for (auto j : al[i]) {
if (!visited[j]) {
check(j, al, visited);
}
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr); cout.tie(nullptr);
int numcities; cin >> numcities;
for (int i = 0; i < numcities; i++) {
vector<list<int>> al;
int numendpoints; cin >> numendpoints;
al.resize(numendpoints);
int r; cin >> r;
for (int j = 0; j < r; j++) {
int a, b; cin >> a >> b;
// cout << "DEBUGGING" << a << " " << b << endl;
al[a].push_back(b);
al[b].push_back(a);
}
queue <int> temp;
vector<bool> visited;
visited.resize(numendpoints, false);
// temp.push(0);
// while(!temp.empty()) {
// int current = temp.front();
// temp.pop();
// // cout << current << endl;
// for (auto i = al[current].begin(); i != al[current].end(); i++) {
// // cout << *i << endl;
// if (!visited[*i]) {
// visited[*i] = true;
// temp.push(*i);
// }
// }
// }
// cout << "DEBUG" << endl;
int counter = 0;
for (int i = 0; i < numendpoints; i++) {
if (!visited[i]) {
counter++;
// visited[i] = true;
check(i, al, visited);
}
}
cout << counter - 1 << endl;
}
return 0;
} | true |
4fa4e034d2f69a50f976629cbd906cb9c9da6fbf | C++ | njoy/GNDStk | /src/GNDStk/Node/src/sort.hpp | UTF-8 | 2,458 | 3.375 | 3 | [
"BSD-2-Clause"
] | permissive |
// -----------------------------------------------------------------------------
// Helpers
// Private, for use by sort(). Could lead to surprises for users if not used
// in the proper sort() context. In particular, less() assumes that any child
// nodes it inspects were sorted already; if they weren't, then transitivity
// in sort()'s strict weak ordering requirement would in general be violated,
// leading to undefined behavior. I suppose less() could chuck this assumption
// and instead take it upon itself to sort its child nodes, recursively, before
// proceeding with the relevant comparisons. This would render the full sort()
// as s-l-o-w as molasses, and would trash up the principle that less() should
// compare nodes, not mess with them. As it stands, our full node.sort() does
// things in the right order, so that less() works as it should in that context.
// -----------------------------------------------------------------------------
private:
// less
static bool less(const Node &a, const Node &b)
{
if (a.name < b.name) return true;
if (b.name < a.name) return false;
if (a.metadata.size() < b.metadata.size()) return true;
if (b.metadata.size() < a.metadata.size()) return false;
if (a.children.size() < b.children.size()) return true;
if (b.children.size() < a.children.size()) return false;
for (auto i = a.metadata.begin(),
j = b.metadata.begin(); i != a.metadata.end(); ++i, ++j) {
if (*i < *j) return true;
if (*j < *i) return false;
}
for (auto i = a.children.begin(),
j = b.children.begin(); i != a.children.end(); ++i, ++j) {
if (less(**i,**j)) return true;
if (less(**j,**i)) return false;
}
return false;
}
// sort_metadata
void sort_metadata()
{
std::sort(
metadata.begin(),
metadata.end()
);
}
// sort_childptr
void sort_childptr()
{
std::sort(
children.begin(),
children.end(),
[](const childPtr &a, const childPtr &b) { return less(*a,*b); }
);
}
// -----------------------------------------------------------------------------
// sort
// -----------------------------------------------------------------------------
public: // undo the above private
Node &sort()
{
// recurse to children *first*
for (auto &c : children)
c->sort();
// sort metadata pairs
sort_metadata();
// sort children pointers
sort_childptr();
// done
return *this;
}
| true |
af56fadf4f79075aff0b1d695feb0c033d8808e3 | C++ | LiamPilot/LightSaber | /src/utils/QueryApplication.h | UTF-8 | 1,362 | 2.515625 | 3 | [
"Apache-2.0"
] | permissive | #pragma once
#include <vector>
#include "utils/SystemConf.h"
class Query;
class TaskProcessorPool;
class TaskDispatcher;
class PerformanceMonitor;
/*
* \brief This is the query application that is going to be executed once
* the @setup is called first and the @processData function gets invoked.
*
* A query application can have multiple @Queries.
* */
class QueryApplication {
private:
int m_numOfThreads;
std::vector<std::shared_ptr<Query>> m_queries;
int m_numOfQueries;
/*
* At the top level, the input stream will be will
* be dispatched to the most upstream queries
*/
int m_numberOfUpstreamQueries;
std::shared_ptr<TaskQueue> m_queue;
std::shared_ptr<TaskProcessorPool> m_workerPool;
std::vector<std::shared_ptr<TaskDispatcher>> m_dispatchers;
std::unique_ptr<PerformanceMonitor> m_performanceMonitor;
std::thread m_performanceMonitorThread;
void setDispatcher(std::shared_ptr<TaskDispatcher> dispatcher);
public:
QueryApplication(std::vector<std::shared_ptr<Query>> &queries);
void processData(std::vector<char> &values, long latencyMark = -1);
void setup();
std::shared_ptr<TaskQueue> getTaskQueue();
int getTaskQueueSize();
std::vector<std::shared_ptr<Query>> getQueries();
std::shared_ptr<TaskProcessorPool> getTaskProcessorPool();
int numberOfQueries();
int numberOfUpStreamQueries();
}; | true |
15e233a6d56446ca7b61634ac1aa9dd3ccccdea8 | C++ | jandrea/CHROMIETracking | /Geometry/PixelTelescope/plugins/DDTelescopePlanesAlgo.h | UTF-8 | 1,743 | 2.703125 | 3 | [] | no_license | #ifndef DD_TelescopePlanesAlgo_h
#define DD_TelescopePlanesAlgo_h
//////////////////////////////////////////////////////////////////////////////////////////
// DDTelescopePlanesAlgo
// Description: Places pixel telescope planes inside a given telescope arm.
// The planes can be tilted (rotation around CMS_X) then skewed (rotation around CMS_Y).
// The planes are all centered in (CMS_X,CMS_Y) = (0,0) and shifted along CMS_Z by deltaZ.
// Author: Gabrielle Hugo
//////////////////////////////////////////////////////////////////////////////////////////
#include <map>
#include <string>
#include <vector>
#include "DetectorDescription/Core/interface/DDTypes.h"
#include "DetectorDescription/Core/interface/DDAlgorithm.h"
class DDTelescopePlanesAlgo : public DDAlgorithm {
public:
DDTelescopePlanesAlgo();
~DDTelescopePlanesAlgo() override;
void initialize(const DDNumericArguments & nArgs,
const DDVectorArguments & vArgs,
const DDMapArguments & mArgs,
const DDStringArguments & sArgs,
const DDStringVectorArguments & vsArgs) override;
void execute(DDCompactView& cpv) override;
private:
int n; // Number of telescope planes.
double tiltAngle; // Rotation around CMS_X. Angle is counted in the counter-trigonometric sense. Angle = 0 on (XY) plane. Must be in [0° 90°].
double skewAngle; // Rotation around CMS_Y. Angle is counted in the trigonometric sense. Angle = 0 on (XY) plane. Must be in [0° 90°].
double deltaZ; // Distance in Z between the centers of 2 consecutive planes.
std::string idNameSpace; // Namespace of this and ALL sub-parts.
std::string childName; // Child name (ie, telescope plane name).
};
#endif
| true |
8fd836b87f68d05e25d6519257a4b874e55c7fcd | C++ | gan-ta/Algorithm | /BackJoonOnline/14226스티커.cpp | UTF-8 | 1,178 | 2.984375 | 3 | [] | no_license | #include <cstdio>
#include <queue>
using namespace std;
typedef struct imo{
int total;
int storage;
int depth;
}imo;
int visited[2001][2001];
queue<imo> q;
int main()
{
int s;
int res = 0;
scanf("%d", &s);
imo start;
start.total = 1;
start.storage = 0;
start.depth = 0;
q.push(start);
visited[1][0] = 1;
while (1)
{
imo search;
imo s1, s2, s3;
search = q.front();
q.pop();
if (search.total == s)
{
res = search.depth;
break;
}
s1.total = search.total;
s1.storage = search.total;
s1.depth = search.depth + 1;
if (visited[s1.total][s1.storage] == 0)
{
visited[s1.total][s1.storage] = 1;
q.push(s1);
}
s2.total = search.total + search.storage;
s2.storage = search.storage;
s2.depth = search.depth + 1;
if(s2.total < 2001)
{
if (visited[s2.total][s2.storage] == 0)
{
visited[s2.total][s2.storage] = 1;
q.push(s2);
}
}
s3.total = search.total - 1;
s3.storage = search.storage;
s3.depth = search.depth + 1;
if (s3.total > 0)
{
if (visited[s3.total][s3.storage] == 0)
{
visited[s3.total][s3.storage] = 1;
q.push(s3);
}
}
}
printf("%d\n", res);
return 0;
} | true |
4041cc7a06d25782fc8a2b5c924bbb7e656f04ba | C++ | BenjaminHb/WHU_CS_WebLearn | /src/Problem_203.cpp | UTF-8 | 703 | 2.640625 | 3 | [
"MIT"
] | permissive | /**
* File Name: Problem_203.cpp
* Project Name: WHU_CS_WebLearn
* Author: Benjamin Zhang
* Created Time: 01/13/2019 19:35
* Version: 0.0.1.20190113
*
* Copyright (c) Benjamin Zhang 2019
* All rights reserved.
**/
#include<stdio.h>
#include<stdlib.h>
int main()
{
int no;
while(scanf("%d",&no)==1)
{
int num=0,loop=0,tmp;
while(no-->0)
{
scanf("%d",&tmp);
if(loop==0)
{
loop++;
num=tmp;
}
else
{
if(tmp==num) loop++;
else loop--;
}
}
printf("%d\n",num);
}
return 0;
} | true |
8d65809a15561040f63b4dd90a93b3c3b86ab8c5 | C++ | aracitdev/AsciiCmd | /src/Drawables/Rectangle.cpp | UTF-8 | 938 | 2.796875 | 3 | [] | no_license | #include <AsciiCmd/Drawables/Rectangle.h>
#include <AsciiCmd/RenderTarget.h>
namespace AsciiCmd
{
Rectangle::Rectangle(Vector2<uint32_t> size)
{
shapeSize=size;
}
void Rectangle::Draw(RenderTarget* target)
{
Vector2<int32_t> counter;
for(counter.x=0; (uint32_t)counter.x < shapeSize.x; counter.x++)
for(counter.y=0; (uint32_t)counter.y < shapeSize.y; counter.y++)
{
if(counter.x == 0 || counter.y == 0 || (uint32_t)counter.x == shapeSize.x-1 || (uint32_t)counter.y == shapeSize.y-1)
target->PutPixel(counter + pos, outlineChar,outlineColor);
else
target->PutPixel(counter + pos, fillChar, fillColor);
}
}
Vector2<uint32_t> Rectangle::GetSize(void)
{
return shapeSize;
}
void Rectangle::SetSize(Vector2<uint32_t> sz)
{
shapeSize=sz;
}
}
| true |
04a5ac88362a07b503c183f1c1ab878813b8b235 | C++ | seanamax/orchidflow | /test/unittest/test_tuple.cpp | UTF-8 | 1,857 | 3.109375 | 3 | [] | no_license | //
// Created by chris on 17-10-8.
//
#include "../lib/catch.h"
#include "../../include/tuple.h"
using namespace std;
using namespace orchidflow;
TEST_CASE("Test Tuple class", "test all Tuple class functions.") {
// test constructor function with {}。
Tuple<int> a({1, 2, 3});
REQUIRE(a[0] == 1);
REQUIRE(a[1] == 2);
REQUIRE(a[2] == 3);
a[1] = 10;
REQUIRE(a[1] == 10);
REQUIRE(a.ndim() == 3);
decltype(a) b = a;
REQUIRE(b[1] == 10);
REQUIRE(b.ndim() == 3);
decltype(a) c = {1, 2, 3};
REQUIRE(c[0] == 1);
REQUIRE(c[1] == 2);
REQUIRE(c[2] == 3);
decltype(a) d(std::move(c));
REQUIRE(d[0] == 1);
REQUIRE(d[1] == 2);
REQUIRE(d[2] == 3);
REQUIRE(c.begin() == nullptr);
REQUIRE(c.ndim() == 0);
decltype(a) e = std::move(d);
REQUIRE(e[0] == 1);
REQUIRE(e[1] == 2);
REQUIRE(e[2] == 3);
REQUIRE(d.begin() == nullptr);
REQUIRE(d.ndim() == 0);
}
TEST_CASE("Test Shape class", "test all Tuple class functions") {
Shape a({1, 2, 3});
REQUIRE(a[0] == 1);
REQUIRE(a[1] == 2);
REQUIRE(a[2] == 3);
a[1] = 10;
REQUIRE(a[1] == 10);
REQUIRE(a.ndim() == 3);
REQUIRE(a.num_elements() == 30);
decltype(a) b = a;
REQUIRE(b[1] == 10);
REQUIRE(b.ndim() == 3);
REQUIRE(b.num_elements() == 30);
decltype(a) c = {1, 2, 3};
REQUIRE(c[0] == 1);
REQUIRE(c[1] == 2);
REQUIRE(c[2] == 3);
decltype(a) d(std::move(c));
REQUIRE(d[0] == 1);
REQUIRE(d[1] == 2);
REQUIRE(d[2] == 3);
REQUIRE(c.begin() == nullptr);
REQUIRE(c.ndim() == 0);
REQUIRE(c.num_elements() == 0);
decltype(a) e = std::move(d);
REQUIRE(e[0] == 1);
REQUIRE(e[1] == 2);
REQUIRE(e[2] == 3);
REQUIRE(d.begin() == nullptr);
REQUIRE(d.ndim() == 0);
REQUIRE(d.num_elements() == 0);
}
| true |
fb8d1182fc1694024b8f4d2c2b25e076199aaff1 | C++ | borgishmorg/bfu | /Sem_2/Lab_2/Task 1/include/Dish.hpp | UTF-8 | 484 | 2.703125 | 3 | [] | no_license | #ifndef __DISH__
#define __DISH__
#include <string>
namespace DataBaseNS
{
class Dish{
public:
Dish(std::string name, std::string type, std::string country);
~Dish();
const std::string & getName() const;
const std::string & getType() const;
const std::string & getCountry() const;
private:
std::string name_,
type_,
country_;
};
}
#endif | true |
89b1711d5bd8a1640e63c7746acef9b2ea9222f7 | C++ | edamame8888/edamame-s_ABC | /100-109/104/D/D.cpp | UTF-8 | 1,717 | 2.734375 | 3 | [] | no_license | #include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <ctime>
#define MOD (1e9+7)
using namespace std;
string S;
void solve(){
/*
dp[何番目の文字まで確認したか][状態]
状態 0: ABCのうち何も決めていない
状態 1: Aの位置のみ確定済み
状態 2: ABの位置のみ確定済み
状態 3: ABCの位置確定済み
*/
vector<vector<long>> dp = vector<vector<long>>(S.size()+1,vector<long>(4,0));
dp[0][0] = 1;
for(int i = 0; i < S.size(); i++){
switch (S[i]) {
case 'A':
dp[i+1][0] = dp[i][0] ;
dp[i+1][1] = dp[i][1] + dp[i][0] ;
dp[i+1][2] = dp[i][2] ;
dp[i+1][3] = dp[i][3] ;
break;
case 'B':
dp[i+1][0] = dp[i][0] ;
dp[i+1][1] = dp[i][1] ;
dp[i+1][2] = dp[i][2] + dp[i][1] ;
dp[i+1][3] = dp[i][3] ;
break;
case 'C':
dp[i+1][0] = dp[i][0] ;
dp[i+1][1] = dp[i][1] ;
dp[i+1][2] = dp[i][2] ;
dp[i+1][3] = dp[i][3] + dp[i][2] ;
break;
case '?':
dp[i+1][0] = dp[i][0] * 3;
dp[i+1][1] = 3 * dp[i][1] + dp[i][0] ;
dp[i+1][2] = 3 * dp[i][2] + dp[i][1] ;
dp[i+1][3] = 3 * dp[i][3] + dp[i][2] ;
break;
}
for(int j = 0; j < 4; j++) dp[i+1][j] = dp[i+1][j] % (int)MOD ;
}
cout << dp[S.size()][3] << endl;
}
int main(){
cin >> S;
solve();
return 0;
}
| true |
4d3b2d6eb20942df6835a26ea64a2757fc310f53 | C++ | israelfontes/Wall-e | /src/main.cpp | UTF-8 | 4,682 | 2.984375 | 3 | [] | no_license | #include <Arduino.h>
#include <Ultrasonic.h>
#include <Servo.h>
#include "DcMotor.hpp"
//Pino Servo
#define PIN_SERVO 10
//Pinos SR04
#define PIN_ECHO 9
#define PIN_TRIGGER 8
//Pinos Motor A
#define PINA1 2
#define PINA2 4
#define PIN_SPEED_A 3
//Pinos Motor B
#define PIN_B1 6
#define PIN_B2 7
#define PIN_SPEED_B 5
//Pinos leds
#define PIN_LED_PLAY 11
#define PIN_LED_STANDBY 12
#define PIN_LED_FOLLOW 13
#define PLAY 1
#define STANDBY 2
#define FOLLOW 3
#define SPEED_SEARCH 200 //Velocidade para procurar objeto
#define MAX_DISTANCE 90 //Distancia maxima onde o objeto pode estar
#define VAR_DISTANCE 4 //Variância padrão de distancia do objeto em cm
#define TURN_SPEED 200 //Velocidade para fazer a volta
void go(short speed);
void back(short speed);
void left();
void right();
void stop();
void search();
void enjoy();
void changeLeds(short led);
short distanceDefault = 40; //Distância padrão em cm
Servo servo;
short position;
Ultrasonic ultrasonic(PIN_TRIGGER, PIN_ECHO);
short speedDefault = 200;
void setup(){
pinMode(PINA1,OUTPUT);
pinMode(PINA2,OUTPUT);
pinMode(PIN_B1,OUTPUT);
pinMode(PIN_B2,OUTPUT);
pinMode(PIN_SPEED_A,OUTPUT);
pinMode(PIN_SPEED_B,OUTPUT);
pinMode(PIN_LED_PLAY,OUTPUT);
pinMode(PIN_LED_STANDBY,OUTPUT);
pinMode(PIN_LED_FOLLOW,OUTPUT);
servo.attach(PIN_SERVO);
servo.write(0);
Serial.begin(9600);
}
DcMotor motorA(PINA1, PINA2, PIN_SPEED_A, speedDefault);
DcMotor motorB(PIN_B1, PIN_B2, PIN_SPEED_B, speedDefault);
char inBluetooth = 'x';
bool ini = true;
void loop(){
if(Serial.available() || ini == true){ //Quando houver dados no bluetooth
inBluetooth = Serial.read();
if(ini == true){
inBluetooth = 'P';
ini = false;
}
if(inBluetooth == 'D'){ //Alterar distancia que o robo deve manter do objeto
while(!Serial.available()); //Aguardando uma distancia entre 1cm e a distancia maxima configurada
short temp = int(Serial.read());
if(temp > 1 && temp <= MAX_DISTANCE){
Serial.print("Mudou para: ");
Serial.println(temp);
distanceDefault = temp;
}
}else if(inBluetooth == 'E'){ //Se quiser brincar, digite E
changeLeds(PLAY);
enjoy();
}else if(inBluetooth == 'P'){
changeLeds(STANDBY);
stop();
while(!Serial.available() && Serial.read() != 'f');
}
}
changeLeds(FOLLOW);
short currentDistance = ultrasonic.read();
if(currentDistance > (distanceDefault + VAR_DISTANCE) && currentDistance < MAX_DISTANCE)
go(speedDefault);
else if(currentDistance < (distanceDefault - VAR_DISTANCE))
back(speedDefault);
else if(currentDistance > MAX_DISTANCE)
search();
else{
Serial.println("Achou");
stop();
}
delay(100);
}
void go(short speed){
motorA.goSpeed(speed);
motorB.goSpeed(speed);
Serial.println("GO");
}
void back(short speed){
motorA.backSpeed(speed);
motorB.backSpeed(speed);
Serial.println("BACK");
}
void left(){
motorA.goSpeed(TURN_SPEED);
motorB.backSpeed(TURN_SPEED);
Serial.println("LEFT");
}
void right(){
motorA.backSpeed(TURN_SPEED);
motorB.goSpeed(TURN_SPEED);
Serial.println("RITHG");
}
void search(){
short currentDistance = 160;
stop();
while(currentDistance > MAX_DISTANCE && inBluetooth != 'P'){
inBluetooth = Serial.read();
Serial.println("SEARCH");
currentDistance = ultrasonic.read();
motorA.backSpeed(SPEED_SEARCH);
motorB.goSpeed(SPEED_SEARCH);
delay(100);
}
}
void stop(){
motorA.stop();
motorB.stop();
delay(50);
}
void enjoy(){
stop();
while(inBluetooth != 'e'){ //Se quiser parar de brincar, digite e
while(!Serial.available());
inBluetooth = Serial.read();
if(inBluetooth == 'g') //Ir pra frente
go(speedDefault);
else if(inBluetooth == 'b') //Voltar
back(speedDefault);
else if(inBluetooth == 'r'){ //Direta
stop();
right();
}
else if(inBluetooth == 'l'){ //Esquerda
stop();
left();
}
else if(inBluetooth == 's') //Parar
stop();
}
stop();
}
void changeLeds(short led){
switch(led){
case 1:
digitalWrite(PIN_LED_PLAY, 1);
digitalWrite(PIN_LED_FOLLOW, 0);
digitalWrite(PIN_LED_STANDBY, 0);
break;
case 2:
digitalWrite(PIN_LED_PLAY, 0);
digitalWrite(PIN_LED_FOLLOW, 1);
digitalWrite(PIN_LED_STANDBY, 0);
break;
case 3:
digitalWrite(PIN_LED_PLAY, 0);
digitalWrite(PIN_LED_FOLLOW, 0);
digitalWrite(PIN_LED_STANDBY, 1);
break;
}
} | true |
a1006d2f2911a7afd32435de44a82ccb42ab1bee | C++ | SamanGharatchorlou/RougeLike | /RougeLike/Source/Objects/Abilities/AbilityHandler.h | UTF-8 | 777 | 2.5625 | 3 | [] | no_license | #pragma once
class Ability;
class Actor;
class EffectPool;
class InputManager;
enum class AbilityType;
enum class AbilityState;
class AbilityHandler
{
public:
AbilityHandler() { }
void init(EffectPool* effectPool, std::vector<Actor*>* targets);
Ability* get(AbilityType type);
void add(Ability* ability);
const std::vector<Ability*>& abilities() const { return mAbilities; }
void clear();
void handleInput(const InputManager* input);
void fastUpdate(float dt);
void slowUpdate(float dt);
void render();
private:
bool doesCollide(Ability* ability) const;
void activateCollisions(Ability* ability) const;
void handleState(Ability* ability, float dt);
private:
std::vector<Actor*>* mTargets;
EffectPool* mEffects;
std::vector<Ability*> mAbilities;
}; | true |
62c72cc3a9063eb80bd22deb8b937459df4e0ef9 | C++ | cmosnick/hpc-work | /homework3/src/mosnickThread.cpp | UTF-8 | 2,692 | 3.140625 | 3 | [] | no_license | #include "MosnickThread.hpp"
#include <iostream>
mosnick::MosnickThread::MosnickThread (unsigned int numResults, unsigned int step, unsigned int totalLines, const std::vector<float> *queryFloats) :
_numResults(numResults), _step(step), _totalLines(totalLines), _queryFloats(queryFloats){
// std::cout << "Constructing MosnickThread with N = (" << numResults << ")" << std::endl;
if(_numResults < 1){
std::cout << "numResults must be positive non-zero number" << std::endl;
}
if(_step < 1){
std::cout << "step must be 1 or greater" << std::endl;
}
// std::cout << "Step size: " << _step << std::endl;
}
// Destructor
mosnick::MosnickThread::~MosnickThread(){
std::cout << "Destructing MosnickThread" << std::endl;
// Do extra destruction
}
// Block partition method: will complete for testing against interleave analysis
void mosnick::MosnickThread::doWorkBlock(unsigned int startingIndex, unsigned int numberToProcess){
// return 0;
}
// Row interleave method
void mosnick::MosnickThread::doWorkInterleave(unsigned int startingIndex, const std::vector<std::pair<uint, std::vector<float> > > &lines){
if(startingIndex > _totalLines){
return;
}
unsigned int currentLine = startingIndex;
std::vector<std::pair<uint, float> > lineDistances;
while(currentLine < _totalLines){
float temp = compute_L1_norm(_queryFloats, &(lines[currentLine].second));
std::pair<uint, float> tempPair;
tempPair.first = currentLine;
tempPair.second = temp;
lineDistances.push_back(tempPair);
currentLine += _step;
}
// std::cout<< "Got full results" << std::endl;
// Sort to get top results (shortest distance)
std::vector<std::pair<uint, float> >::iterator middle = lineDistances.begin() + _numResults;
partial_sort(lineDistances.begin(), middle, lineDistances.end(), &MosnickThread::comp);
lineDistances.resize(_numResults);
results.clear();
for(int i=0 ; i < _numResults ; i++){
std::pair<uint, float> temp = lineDistances[i];
results.push_back(temp);
}
return;
}
// Computes the L1 norm between two vectors of floats
// Returns 0 on error or if vectors are exactly alike
float mosnick::MosnickThread::compute_L1_norm(const std::vector<float> *v1, const std::vector<float> *v2){
if(v1 && v2){
int s1 = (*v1).size(),
s2 = (*v2).size(),
i=0;
// Take smallest size
int size = (s1 < s2) ? s1:s2;
if(size != 4097){
std::cout << "\nSize = " << size << std::endl;
}
float sum = 0;
for( ; i < size ; i++){
sum += fabs( ((*v1)[i] - (*v2)[i]) );
}
return (float)sum/size;
}
return -1;
}
bool mosnick::MosnickThread::comp(const std::pair<uint, float> &el1, const std::pair<uint, float> &el2){
return (el1.second < el2.second);
}
| true |
0beb274629f26aa6da4d7c95f870aff89b9b71d5 | C++ | SumuduKMadushanka/Sorting_Algorithm | /shell_sort.cpp | UTF-8 | 881 | 3.65625 | 4 | [] | no_license | #include "shell_sort.h"
void shell_sort(int array[], int size)
{
int gap = size/2;
while (gap > 0)
{
for (int i = gap; i < size; i++)
{
int tmp = array[i];
int j = i;
while (j >= gap && array[j - gap] > tmp)
{
array[j] = array[j - gap];
j -= gap;
}
array[j] = tmp;
}
gap /= 2;
}
}
void shell_sort(std::vector<int> &vector)
{
int size = vector.size();
int gap = size/2;
while (gap > 0)
{
for (int i = gap; i < size; i++)
{
int tmp = vector[i];
int j = i;
while (j >= gap && vector[j - gap] > tmp)
{
vector[j] = vector[j - gap];
j -= gap;
}
vector[j] = tmp;
}
gap /= 2;
}
} | true |