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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
fd757bb8b2ab2f8b7f4d49540b7fa025bb5d7ca7 | C++ | pawcio16m/Randlab_app | /include/Rectangle.h | UTF-8 | 354 | 2.5625 | 3 | [] | no_license | #pragma once
#include <opencv2/core/mat.hpp>
#include <opencv2/core/core.hpp>
#include "IShape.h"
class Rectangle : public IShape
{
public:
Rectangle(cv::Point p1, cv::Point p2)
: m_p1(p1),
m_p2(p2)
{}
virtual ~Rectangle() = default;
void drawMeInPict(cv::Mat&) override;
private:
cv::Point m_p1;
cv::Point m_p2;
};
| true |
24efa5cb0adf0678b6a6ff7a940cf661e43261f3 | C++ | kipa00/AplusB-mc | /compiler/main.cpp | UTF-8 | 4,519 | 2.640625 | 3 | [] | no_license | #include <cstdio>
#include "world.hpp"
#include "analyze.hpp"
#include "check.hpp"
#include "color.hpp"
const int BUFSIZE = 1048576;
byte data[BUFSIZE];
void traverse_world(const world &w, std::function<void(int, int, int)> f) {
int cx, cy, cz;
for (cz=0; cz<32; ++cz) {
for (cx=0; cx<32; ++cx) {
for (cy=0; cy<16; ++cy) {
if (w.has_world_data(cx, cy, cz)) {
int x, y, z;
for (z=0; z<16; ++z) {
for (x=0; x<16; ++x) {
for (y=0; y<16; ++y) {
f((cx << 4) | x, (cy << 4) | y, (cz << 4) | z);
}
}
}
}
}
}
}
}
void write_byte(FILE *fp, byte c) {
fwrite(&c, 1, 1, fp);
}
void write_int(FILE *fp, u32 x) {
write_byte(fp, x >> 24);
write_byte(fp, (x >> 16) & 255);
write_byte(fp, (x >> 8) & 255);
write_byte(fp, x & 255);
}
int main(int argc, char *argv[]) {
if (argc <= 1) {
fprintf(stderr, "Usage: %s <region file name> [input list]\n", argv[0]);
return -1;
} else if (argc == 2) {
fprintf(stderr, "Warning: no input specified\n");
}
vector<int> input_order;
for (int i=2; i<argc; ++i) {
int v = color_to_int(argv[i]);
if (v < 0) {
fprintf(stderr, "Error: unknown color '%s'\n", argv[i]);
return -1;
}
input_order.push_back(v);
}
FILE *fp = fopen(argv[1], "rb");
world w;
try {
w.init(fp);
} catch (int err) {
fprintf(stderr, "Compilation aborted.\n");
return -1;
}
fclose(fp);
int **u = new int *[16384], cnt = 0;
memset(u, 0, sizeof(int *) * 16384);
traverse_world(w, [&] (int x, int y, int z) {
if (is_redstone_component(w, x, y, z)) {
int **ptr = u + (((z >> 4) << 9) | ((x >> 4) << 4) | (y >> 4));
if (!*ptr) {
*ptr = new int[4096];
memset(*ptr, 0, sizeof(int) * 4096);
}
(*ptr)[((z & 15) << 8) | ((x & 15) << 4) | (y & 15)] = ++cnt;
}
});
fp = fopen("a.out", "wb");
traverse_world(w, [&] (int x, int y, int z) {
vector<int> info;
const int type = analyze(w, x, y, z, info);
if (type) {
int byte_type = 0;
if (type == 1) {
byte_type = 16 | (w.getXYZ(x, y, z) & 15);
} else {
byte_type = (type << 4) | (w.getXYZ(x, y, z) & POWERED ? 15 : 0);
}
write_byte(fp, byte_type);
for (const int &x : info) {
write_int(fp, x >= 0 ? u[x >> 12][x & 4095] : -1);
}
write_int(fp, -1);
if (type == 1 || type == 2) {
for (int i=0; i<wide_len; ++i) {
const int nx = x + wide_dx[i], ny = y + wide_dy[i], nz = z + wide_dz[i];
if (is_redstone_component(w, nx, ny, nz)) {
vector<int> temp;
analyze(w, nx, ny, nz, temp);
const int target = pack(x, y, z);
const int idx = pack(nx, ny, nz);
for (const int &v : temp) {
if (v == target) {
write_int(fp, u[idx >> 12][idx & 4095]);
break;
}
}
}
}
} else {
for (int i=0; i<narrow_len; ++i) {
int nx = x + narrow_dx[i], ny = y + narrow_dy[i], nz = z + narrow_dz[i];
if (is_redstone_component(w, nx, ny, nz)) {
const int idx = pack(nx, ny, nz);
write_int(fp, u[idx >> 12][idx & 4095]);
}
if (type != 10) {
switch (w.getXYZ(x, y, z) & 3) {
case EAST: --nx; break;
case WEST: ++nx; break;
case SOUTH: --nz; break;
case NORTH: ++nz; break;
}
if (is_redstone_component(w, nx, ny, nz) && !(nx == x && nz == z)) {
int idx = pack(nx, ny, nz);
write_int(fp, u[idx >> 12][idx & 4095]);
}
}
}
}
write_int(fp, -1);
}
});
write_byte(fp, -1);
vector<std::pair<int, int> > inputs[16], output;
traverse_world(w, [&] (int x, int y, int z) {
byte fetched = w.getXYZ(x, y, z);
if ((fetched & BLOCK_ONLY) == LEVER) {
int nx = x, ny = y, nz = z;
switch (fetched & 3) {
case EAST: --nx; break;
case WEST: ++nx; break;
case SOUTH: --nz; break;
case NORTH: ++nz; break;
}
byte facing = w.getXYZ(nx, ny, nz);
if ((facing & BLOCK_ONLY) == CONCRETE) {
inputs[facing & 15].emplace_back((z << 17) | (x << 8) | y, pack(x, y, z));
}
} else if ((fetched & BLOCK_ONLY) == REDSTONE_LAMP) {
output.emplace_back((z << 17) | (x << 8) | y, pack(x, y, z));
}
});
for (int i=0; i<16; ++i) {
sort(inputs[i].begin(), inputs[i].end());
}
sort(output.begin(), output.end());
for (const int &i : input_order) {
for (const auto &[_, idx] : inputs[i]) {
write_int(fp, u[idx >> 12][idx & 4095]);
}
write_int(fp, -1);
}
write_int(fp, -1);
for (const auto &[_, idx] : output) {
write_int(fp, u[idx >> 12][idx & 4095]);
}
write_int(fp, -1);
fclose(fp);
return 0;
}
| true |
9b0cd6b1cb6b736441cea37af9556435db5af329 | C++ | hannabizon/hannabizon | /zadania do wgrania c++/3I (1).cpp | UTF-8 | 807 | 3.359375 | 3 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
int main () {
int index_number;
int term;
string first_name;
string last_name;
string field_of_study;
cout << "What is your first name?" << endl;
cin >> first_name;
cout << "What is your last name?"<< endl;
cin >> last_name;
cout << "What is your index number?" << endl;
cin >> index_number;
cout << "What term are you on?" << endl;
cin >> term;
getchar(); // aby wczytac dwuczlonowa nazwe
cout << "What is your field of study?" << endl;
getline(cin, field_of_study); // aby wczytac dwuczlonowa nazwe
cout << "Hi " << first_name << " " << last_name << "! " << "Your index number is " << index_number << "." << endl;
cout << "You are on" << " " << term << " term on " << field_of_study << "." << endl;
return 0;
} | true |
44ff0e57ae6c0d0be0a364c5cd77a89199a87948 | C++ | 519984307/SimpleQTWebApp | /AppFramework/wellknown/appinfo.h | UTF-8 | 1,755 | 3.09375 | 3 | [] | no_license | #ifndef APPINFO_H
#define APPINFO_H
#include <QtCore>
class AppInfo
{
public:
static AppInfo& getInstance()
{
static AppInfo instance; // Guaranteed to be destroyed.
// Instantiated on first use.
return instance;
}
QString getAppConfigFileName(){
return appConfigFileName;
}
void setAppConfigFileName(QString _appConfigFileName){
appConfigFileName = _appConfigFileName;
}
QCoreApplication* getApp(){
return app;
}
void setApp(QCoreApplication* _app){
app = _app;
}
private:
AppInfo() {} // Constructor? (the {} brackets) are needed here.
// C++ 03
// ========
// Don't forget to declare these two. You want to make sure they
// are unacceptable otherwise you may accidentally get copies of
// your singleton appearing.
AppInfo(AppInfo const&); // Don't Implement
void operator=(AppInfo const&); // Don't implement
// C++ 11
// =======
// We can use the better technique of deleting the methods
// we don't want.
//public:
// AppInfo(AppInfo const&) = delete;
// void operator=(AppInfo const&) = delete;
// Note: Scott Meyers mentions in his Effective Modern
// C++ book, that deleted functions should generally
// be public as it results in better error messages
// due to the compilers behavior to check accessibility
// before deleted status
QString appConfigFileName;
QCoreApplication* app;
};
#endif // APPINFO_H
| true |
fa7efdf249eda80e7e7859c366f0ca3eef391bd3 | C++ | starplaton/Jaeho | /BOJ2170.cpp | UTF-8 | 647 | 2.65625 | 3 | [] | no_license | #include <iostream>https://github.com/starplaton/Jaeho
#include <algorithm>
#include <utility>
#include <cstdio>
using namespace std;
const int INF = 1e9 + 1;
int main() {
pair<int, int> map[1000000];
int N;
scanf("%d", &N);
for (int i = 0; i < N; i++)
{
int a, b;
scanf("%d %d", &a, &b);
map[i] = pair<int, int>(a, b);
}
sort(map, map+N);
int result = 0, left = -INF, right = -INF;
for (int i = 0; i < N; i++)
{
if (map[i].first > right) {
result += right - left;
right = map[i].second;
left = map[i].first;
}
else {
right = max(right, map[i].second);
}
}
result += right - left;
printf("%d", result);
}
| true |
ec17d1241f1e67b7378ea31982d8406d4781610c | C++ | f-schroeder/orvis | /lib/orvis/Material.cpp | UTF-8 | 4,629 | 2.890625 | 3 | [
"MIT"
] | permissive | #include "Material.hpp"
#include "Util.hpp"
#include <imgui.h>
Material::Material(glm::vec4 color, float roughness, float metallic, float ior)
{
setColor(color);
setRoughness(roughness);
setMetallic(metallic);
setIOR(ior);
}
glm::vec4 Material::getColor() const
{
if (util::getBit(m_isTextureBitset, MAT_COLOR_BIT))
{
std::cout << "WARNING: Attempting to get material color although it is a texture\n";
return glm::vec4(-1.0f);
}
else
{
return glm::unpackHalf4x16(glm::packUint2x32(m_albedo));
}
}
void Material::setColor(std::variant<glm::vec4, std::shared_ptr<Texture>> color)
{
if (std::holds_alternative<glm::vec4>(color))
{
//m_albedo = util::packHalf4x16(glm::max(glm::vec4(0.0f), std::get<glm::vec4>(color)));
m_albedo = glm::unpackUint2x32(glm::packHalf4x16(glm::max(glm::vec4(0.0f), std::get<glm::vec4>(color))));
util::setBit(m_isTextureBitset, MAT_COLOR_BIT, false);
}
else
{
m_albedo = glm::unpackUint2x32(std::get<std::shared_ptr<Texture>>(color)->handle());
util::setBit(m_isTextureBitset, MAT_COLOR_BIT, true);
}
}
void Material::setNormalMap(const std::shared_ptr<Texture>& normalMap)
{
m_normal = normalMap->handle();
util::setBit(m_isTextureBitset, MAT_NORMAL_BIT, true);
}
void Material::setAoMap(const std::shared_ptr<Texture>& aoMap)
{
m_ao = aoMap->handle();
util::setBit(m_isTextureBitset, MAT_AO_BIT, true);
}
float Material::getRoughness() const
{
if (util::getBit(m_isTextureBitset, MAT_ROUGHNESS_BIT))
{
std::cout << "WARNING: Attempting to get material roughness although it is a texture\n";
return -1.0f;
}
else
{
return glm::uintBitsToFloat(m_roughness.x);
}
}
void Material::setRoughness(std::variant<float, std::shared_ptr<Texture>> roughness)
{
if (std::holds_alternative<float>(roughness))
{
m_roughness.x = glm::floatBitsToUint(glm::clamp(std::get<float>(roughness), 0.0f, 1.0f));
util::setBit(m_isTextureBitset, MAT_ROUGHNESS_BIT, false);
}
else
{
m_roughness = glm::unpackUint2x32(std::get<std::shared_ptr<Texture>>(roughness)->handle());
util::setBit(m_isTextureBitset, MAT_ROUGHNESS_BIT, true);
}
}
float Material::getMetallic() const
{
if (util::getBit(m_isTextureBitset, MAT_METALLIC_BIT))
{
std::cout << "WARNING: Attempting to get material metallic although it is a texture\n";
return -1.0f;
}
else
{
return glm::uintBitsToFloat(m_metallic.x);
}
}
void Material::setMetallic(std::variant<float, std::shared_ptr<Texture>> metallic)
{
if (std::holds_alternative<float>(metallic))
{
m_metallic.x = glm::floatBitsToUint(glm::clamp(std::get<float>(metallic), 0.0f, 1.0f));
util::setBit(m_isTextureBitset, MAT_METALLIC_BIT, false);
}
else
{
m_metallic = glm::unpackUint2x32(std::get<std::shared_ptr<Texture>>(metallic)->handle());
util::setBit(m_isTextureBitset, MAT_METALLIC_BIT, true);
}
}
float Material::getIOR() const
{
return m_ior;
}
void Material::setIOR(float ior)
{
m_ior = glm::max(0.0f, ior);
}
bool Material::drawGuiWindow()
{
ImGui::SetNextWindowSize(ImVec2(300, 100), ImGuiSetCond_FirstUseEver);
ImGui::Begin("Material");
const bool changed = drawGuiContent();
ImGui::End();
return changed;
}
bool Material::drawGuiContent()
{
ImGui::PushID(this);
bool changed = false;
if (ImGui::CollapsingHeader(std::string("Material").c_str()))
{
if (!util::getBit(m_isTextureBitset, MAT_COLOR_BIT))
{
glm::vec4 color = getColor();
if (ImGui::ColorEdit4("Albedo", glm::value_ptr(color), ImGuiColorEditFlags_Float | ImGuiColorEditFlags_PickerHueWheel))
{
setColor(color);
changed = true;
}
}
if (!util::getBit(m_isTextureBitset, MAT_ROUGHNESS_BIT))
{
float r = getRoughness();
if (ImGui::SliderFloat("Roughness", &r, 0.0f, 1.0f))
{
setRoughness(r);
changed = true;
}
}
if (!util::getBit(m_isTextureBitset, MAT_METALLIC_BIT))
{
float m = getMetallic();
if (ImGui::SliderFloat("Metallic", &m, 0.0f, 1.0f))
{
setMetallic(m);
changed = true;
}
}
changed |= ImGui::DragFloat("IOR", &m_ior, 0.001f, 0.0f, 10.0f);
}
ImGui::PopID();
return changed;
}
| true |
b1a09856cb664d22f632ad9d224ac86d9d879e2d | C++ | laity-slf/PTA | /PAT (Advanced Level) Practice/1102 Invert a Binary Tree.cpp | GB18030 | 1,647 | 3.28125 | 3 | [] | no_license | #include<iostream>
#include<cstdio>
#include<queue>
using namespace std;
const int MAX = 110;
struct Node{
int lchild, rchild;
} node[MAX];
int n, num = 0; // ڵn, ڵnum
bool notRoot[MAX] = { false };
void print(int id) {
printf("%d", id);
num++;
if(num<n) printf(" ");
else printf("\n");
return;
}
int strToNum(char c) {
if(c=='-') return -1;
else {
notRoot[c-'0'] = true;
return c - '0';
}
return 0;
}
int findRoot(){
for(int i=0; i<n; i++) {
if(notRoot[i]==false) return i;
}
return 0;
}
void postOrder(int root) {
if(root==-1) return;
postOrder(node[root].lchild);
postOrder(node[root].rchild);
swap(node[root].lchild, node[root].rchild);
return;
}
void BFS(int root) {
queue<int> q;
q.push(root);
while(!q.empty()) {
int now = q.front();
q.pop();
print(now);
if(node[now].lchild!=-1) q.push(node[now].lchild);
if(node[now].rchild!=-1) q.push(node[now].rchild);
}
return;
}
void inOrder(int root) {
if(root==-1) return;
inOrder(node[root].lchild);
print(root);
inOrder(node[root].rchild);
return;
}
int main()
{
char lchild, rchild;
scanf("%d", &n);
for(int i=0; i<n; i++) {
scanf("%*c%c %c", &lchild, &rchild);
node[i].lchild = strToNum(lchild);
node[i].rchild = strToNum(rchild);
}
int root = findRoot();
postOrder(root); // , ת
BFS(root); //
num = 0;
inOrder(root); //
return 0;
}
| true |
3e8e3e4aad5f313fb74e4a8a86ece22038346da1 | C++ | zhouyujt/daxia | /system/windows/find_window.h | GB18030 | 1,631 | 2.65625 | 3 | [] | no_license | /*!
* Licensed under the MIT License.See License for details.
* Copyright (c) 2021 콭ĴϺ.
* All rights reserved.
*
* \file find_window.h
* \author 콭ĴϺ
* \date ʮһ 2021
*
* ڱ
*
*/
#ifdef _WIN32
#ifndef __DAXIA_SYSTEM_WINDOWS_FIND_WINDOW_H
#define __DAXIA_SYSTEM_WINDOWS_FIND_WINDOW_H
#include <memory>
#include "window.h"
namespace daxia
{
namespace system
{
namespace windows
{
class EnumWindow
{
public:
EnumWindow();
~EnumWindow();
public:
class iterator
{
friend EnumWindow;
public:
iterator();
~iterator();
private:
iterator(unsigned int cmd, std::shared_ptr<Window> window);
public:
iterator& operator++();
bool operator==(const iterator& iter) const;
bool operator!=(const iterator& iter) const;
const std::shared_ptr<Window> operator->() const;
const std::shared_ptr<Window> operator*() const;
std::shared_ptr<Window> operator->();
std::shared_ptr<Window> operator*();
iterator& operator=(const iterator& iter);
private:
unsigned int cmd_;
std::shared_ptr<Window> window_;
};
// STL
public:
// ZӶʼָwindowָwindow²㴰ڿʼ
iterator begin(const Window* window = nullptr);
iterator end();
// Zӵʼָwindowָwindowϲ㴰ڿʼ
iterator rbegin(const Window* window = nullptr);
iterator rend();
};
}
}
}
#endif // !__DAXIA_SYSTEM_WINDOWS_FIND_WINDOW_H
#endif // !_WIN32 | true |
ed8f2e5d7bf6749271b6b6ad32fb62bdbe3c13fd | C++ | brupelo/opentoonz | /toonz/sources/toonz/versioncontrolwidget.cpp | UTF-8 | 7,821 | 2.65625 | 3 | [
"BSD-3-Clause"
] | permissive |
#include "versioncontrolwidget.h"
#include <QLabel>
#include <QVBoxLayout>
#include <QSpinBox>
#include <QTimeEdit>
#include <QTextEdit>
#include <QDateTimeEdit>
#include <QRadioButton>
//=============================================================================
// DateChooserWidget
//-----------------------------------------------------------------------------
DateChooserWidget::DateChooserWidget(QWidget *parent)
: QWidget(parent), m_selectedRadioIndex(0)
{
QVBoxLayout *mainLayout = new QVBoxLayout;
mainLayout->setMargin(0);
mainLayout->setAlignment(Qt::AlignTop);
// Time
QHBoxLayout *timeLayout = new QHBoxLayout;
m_timeRadioButton = new QRadioButton;
m_timeRadioButton->setChecked(true);
connect(m_timeRadioButton, SIGNAL(clicked()), this, SLOT(onRadioButtonClicked()));
m_timeEdit = new QTimeEdit;
m_timeEdit->setDisplayFormat("hh:mm");
timeLayout->addWidget(m_timeRadioButton);
timeLayout->addWidget(m_timeEdit);
timeLayout->addWidget(new QLabel(tr("time ago.")));
timeLayout->addStretch();
mainLayout->addLayout(timeLayout);
// Days
QHBoxLayout *dayLayout = new QHBoxLayout;
m_dayRadioButton = new QRadioButton;
connect(m_dayRadioButton, SIGNAL(clicked()), this, SLOT(onRadioButtonClicked()));
m_dayEdit = new QSpinBox;
m_dayEdit->setRange(1, 99);
m_dayEdit->setValue(1);
m_dayEdit->setEnabled(false);
dayLayout->addWidget(m_dayRadioButton);
dayLayout->addWidget(m_dayEdit);
dayLayout->addWidget(new QLabel(tr("days ago.")));
dayLayout->addStretch();
mainLayout->addLayout(dayLayout);
// Weeks
QHBoxLayout *weekLayout = new QHBoxLayout;
m_weekRadioButton = new QRadioButton;
connect(m_weekRadioButton, SIGNAL(clicked()), this, SLOT(onRadioButtonClicked()));
m_weekEdit = new QSpinBox;
m_weekEdit->setRange(1, 99);
m_weekEdit->setValue(1);
m_weekEdit->setEnabled(false);
weekLayout->addWidget(m_weekRadioButton);
weekLayout->addWidget(m_weekEdit);
weekLayout->addWidget(new QLabel(tr("weeks ago.")));
weekLayout->addStretch();
mainLayout->addLayout(weekLayout);
// Custom date
QHBoxLayout *customDateLayout = new QHBoxLayout;
m_dateRadioButton = new QRadioButton;
connect(m_dateRadioButton, SIGNAL(clicked()), this, SLOT(onRadioButtonClicked()));
m_dateTimeEdit = new QDateTimeEdit;
m_dateTimeEdit->setDisplayFormat("yyyy-MM-dd hh:mm");
QDate now = QDate::currentDate();
m_dateTimeEdit->setMaximumDate(now);
m_dateTimeEdit->setDate(now);
m_dateTimeEdit->setEnabled(false);
m_dateTimeEdit->setCalendarPopup(true);
customDateLayout->addWidget(m_dateRadioButton);
customDateLayout->addWidget(m_dateTimeEdit);
customDateLayout->addWidget(new QLabel(tr("( Custom date )")));
customDateLayout->addStretch();
mainLayout->addLayout(customDateLayout);
setLayout(mainLayout);
}
//-----------------------------------------------------------------------------
void DateChooserWidget::disableAllWidgets()
{
m_timeEdit->setEnabled(false);
m_dayEdit->setEnabled(false);
m_weekEdit->setEnabled(false);
m_dateTimeEdit->setEnabled(false);
}
//-----------------------------------------------------------------------------
void DateChooserWidget::onRadioButtonClicked()
{
QObject *obj = sender();
QRadioButton *button = dynamic_cast<QRadioButton *>(obj);
if (!button)
return;
disableAllWidgets();
if (button == m_timeRadioButton) {
m_timeEdit->setEnabled(true);
m_selectedRadioIndex = 0;
} else if (button == m_dayRadioButton) {
m_dayEdit->setEnabled(true);
m_selectedRadioIndex = 1;
} else if (button == m_weekRadioButton) {
m_weekEdit->setEnabled(true);
m_selectedRadioIndex = 2;
} else if (button == m_dateRadioButton) {
m_dateTimeEdit->setEnabled(true);
m_selectedRadioIndex = 3;
}
}
//-----------------------------------------------------------------------------
QString DateChooserWidget::getRevisionString() const
{
QString timeString;
QString dateString;
QDate today = QDate::currentDate();
if (m_selectedRadioIndex == 0) // Time
{
QTime currentTime = QTime::currentTime();
QTime t = m_timeEdit->time();
int seconds = t.hour() * 60 * 60 + t.minute() * 60;
currentTime = currentTime.addSecs(-seconds);
timeString = currentTime.toString("hh:mm");
dateString = today.toString("yyyy-MM-dd");
} else if (m_selectedRadioIndex == 1) // Days
{
timeString = "00:00";
today = today.addDays(-(m_dayEdit->value()));
dateString = today.toString("yyyy-MM-dd");
} else if (m_selectedRadioIndex == 2) // Weeks
{
timeString = "00:00";
today = today.addDays(-(m_weekEdit->value() * 7));
dateString = today.toString("yyyy-MM-dd");
} else // Custom date
{
QTime time = m_dateTimeEdit->time();
timeString = time.toString("hh:mm");
QDate date = m_dateTimeEdit->date();
dateString = date.toString("yyyy-MM-dd");
}
return "{" + dateString + " " + timeString + "}";
}
//-----------------------------------------------------------------------------
//=============================================================================
// ConflictWidget
//-----------------------------------------------------------------------------
ConflictWidget::ConflictWidget(QWidget *parent)
: QWidget(parent), m_button1Text(tr("Mine")), m_button2Text(tr("Theirs"))
{
m_mainLayout = new QVBoxLayout;
m_mainLayout->setMargin(0);
m_mainLayout->setAlignment(Qt::AlignTop);
setLayout(m_mainLayout);
}
//-----------------------------------------------------------------------------
void ConflictWidget::setFiles(const QStringList &files)
{
DoubleRadioWidget *radio = 0;
int fileCount = files.size();
for (int i = 0; i < fileCount; i++) {
radio = new DoubleRadioWidget(m_button1Text, m_button2Text, files.at(i));
connect(radio, SIGNAL(valueChanged()), this, SLOT(onRadioValueChanged()));
m_mainLayout->addWidget(radio);
m_radios.insert(radio, -1);
}
m_mainLayout->addStretch();
}
//-----------------------------------------------------------------------------
void ConflictWidget::onRadioValueChanged()
{
DoubleRadioWidget *obj = dynamic_cast<DoubleRadioWidget *>(sender());
if (obj)
m_radios[obj] = obj->getValue();
if (!m_radios.values().contains(-1))
emit allConflictSetted();
}
//-----------------------------------------------------------------------------
QStringList ConflictWidget::getFilesWithOption(int option) const
{
QStringList files;
QMap<DoubleRadioWidget *, int>::const_iterator i;
for (i = m_radios.constBegin(); i != m_radios.constEnd(); ++i) {
if (i.value() == option)
files << i.key()->getText();
}
return files;
}
//=============================================================================
// DoubleRadioWidget
//-----------------------------------------------------------------------------
DoubleRadioWidget::DoubleRadioWidget(const QString &button1Text,
const QString &button2Text,
const QString &text, QWidget *parent)
: QWidget(parent)
{
QHBoxLayout *mainLayout = new QHBoxLayout;
mainLayout->setMargin(0);
m_firstButton = new QRadioButton(button1Text);
connect(m_firstButton, SIGNAL(clicked()), this, SIGNAL(valueChanged()));
m_secondButton = new QRadioButton(button2Text);
connect(m_secondButton, SIGNAL(clicked()), this, SIGNAL(valueChanged()));
m_label = new QLabel;
m_label->setFixedWidth(180);
m_label->setText(text);
mainLayout->addWidget(m_label);
mainLayout->addSpacing(20);
mainLayout->addWidget(m_firstButton);
mainLayout->addWidget(m_secondButton);
setLayout(mainLayout);
}
//-----------------------------------------------------------------------------
int DoubleRadioWidget::getValue() const
{
if (m_firstButton->isChecked())
return 0;
else if (m_secondButton->isChecked())
return 1;
else
return -1;
}
//-----------------------------------------------------------------------------
QString DoubleRadioWidget::getText() const
{
return m_label->text();
}
| true |
56f2e107cade00001584c1cb49418f4b6a391e4a | C++ | IIIcecream/icecream | /algorithm/include/recursion/WordSearch.h | WINDOWS-1252 | 435 | 2.78125 | 3 | [] | no_license | #pragma once
#include "IACM.h"
#include <vector>
#include <string>
using namespace std;
//
class WordSearch : public IACM
{
public:
WordSearch(vector<vector<char>>& board, string word) : m_board(board), m_sWord(word) {}
virtual bool solve() override;
private:
bool exist(vector<vector<char>>& board, string word, int i, int j, int pos);
private:
vector<vector<char>> m_board;
string m_sWord;
};
| true |
fe328a3ef0cca641c8bcdca334e4371483feb8a6 | C++ | sk7755/Algorithm | /src/Dynamic Programming/Optimal Binary Search Trees/Optimal_BST.cpp | UTF-8 | 1,759 | 3.078125 | 3 | [] | no_license | #include <iostream>
using namespace std;
inline double MIN(double a, double b)
{
return a < b ? a : b;
}
void optimal_BST(int n,double* p, double* q, double** dp, int** path)
{
double *w = new double[n + 1];
w[0] = 0;
for (int i = 1; i <= n; i++)
w[i] = w[i - 1] + p[i] + q[i];
for (int i = 1; i <= n+1; i++)
dp[i][i - 1] = q[i - 1];
for (int i = 1; i <= n; i++)
{
dp[i][i] = p[i] + (q[i - 1] + q[i])*2;
path[i][i] = i;
}
for (int l = 1; l < n; l++)
{
for (int i = 1; i+l <= n; i++)
{
int j = i + l;
double tmp = w[j] - w[i - 1] + q[i - 1];
dp[i][j] = dp[i][path[i][j - 1] -1] + dp[path[i][j - 1] +1][j];
path[i][j] = path[i][j-1];
for (int k = path[i][j-1] + 1; k <= path[i+1][j]; k++)
{
if (dp[i][j] > dp[i][k - 1] + dp[k + 1][j])
{
dp[i][j] = dp[i][k - 1] + dp[k + 1][j];
path[i][j] = k;
}
}
dp[i][j] += tmp;
}
}
delete[] w;
}
void print_BST(int** path, int i,int j)
{
if (i > j)
return;
cout << '(';
print_BST(path,i,path[i][j]-1);
cout << path[i][j];
print_BST(path, path[i][j] + 1, j);
cout << ')';
}
int main()
{
int n;
cin >> n;
double *p = new double[n+1];
double *q = new double[n+1];
for (int i = 1; i <= n; i++)
cin >> p[i];
for (int i = 0; i <= n; i++)
cin >> q[i];
double** dp = new double*[n + 2];
int** path = new int*[n + 2];
for (int i = 0; i <= n+1; i++)
{
dp[i] = new double[n + 2];
path[i] = new int[n + 2];
}
optimal_BST(n, p, q, dp, path);
cout << "Minimum Expectation Cost : " << dp[1][n] << endl;
cout << "Optimal Binary Search Tree" << endl;
print_BST(path, 1, n);
for (int i = 0; i <= n + 1; i++)
{
delete[] dp[i];
delete[] path[i];
}
delete[] dp;
delete[] path;
delete[] p;
delete[] q;
return 0;
} | true |
b30f39dcf21e9d0edde24ae0e81c029164ca9b70 | C++ | daxingyou/ysz | /YSZSever-master/Server/library/GDK/Timer/TimerMgr.h | UTF-8 | 2,344 | 2.625 | 3 | [] | no_license | /*****************************************************************************
Copyright (C), 2012-2100, ^^^^^^^^. Co., Ltd.
文 件 名: TimerMgr.h
作 者: Herry
版 本: 1.0
完成日期: 2012-9-24
说明信息: 计时管理器, 单线程版本, 限制在Word线程内使用
*****************************************************************************/
#pragma once
#include "Define.h"
struct TimerNode;
typedef std::map<uint32, TimerNode> TIMER_MAP;
// 计时对象
struct TimerNode
{
uint32 nInterval;
uint32 nEndTime;
CPacket *pPacket;
int32 iCount;
};
// 计时管理器
class CTimerMgr
{
private:
CTimerMgr(void);
~CTimerMgr(void);
public:
static CTimerMgr& GetInstance(void);
public:
uint32 SetTimer(uint32 nInterval, CPacket &cPacket, int32 iCount = -1);
int DestroyTimer(uint32 &nTimerID);
void Update(void);
void Destroy();
protected:
private:
uint32 m_nTimerID;
TIMER_MAP m_cTimerMap;
};
#define sTimerMgr CTimerMgr::GetInstance()
// 简单的计时器, 只计时
class CTimer
{
public:
CTimer(void) : m_nStartTime(0), m_nCycleTime(0)
{
}
~CTimer(void)
{
}
public:
// 获得开始时间
inline uint32 GetStartTime(void)
{
return m_nStartTime;
}
// 获得间隔周期
inline uint32 GetCycleTime(void)
{
return m_nCycleTime;
}
// 设置开始时间
inline void SetStartTime(void)
{
m_nStartTime = CTimeTools::GetSystemTimeToTick();
}
// 设置间隔时间
inline void SetCycleTime(uint32 nCycleTime)
{
m_nCycleTime = nCycleTime;
}
// 添加间隔周期
inline void AddCycleTime(uint32 nCycleTime)
{
m_nCycleTime += nCycleTime;
}
// 是否到达时间
inline bool IsTimeOut(void) const
{
return CTimeTools::GetSystemTimeToTick() - m_nStartTime >= m_nCycleTime;
}
// 获得剩余时间
inline uint32 GetResidualTime(void)const
{
int32 iTime = m_nCycleTime - (CTimeTools::GetSystemTimeToTick() - m_nStartTime);
if (iTime < 0)
{
return 0;
}
else if ((uint32)iTime > m_nCycleTime)
{
return m_nCycleTime;
}
return (uint32)iTime;
}
inline void Reset(void)
{
m_nStartTime = 0;
m_nCycleTime = 0;
}
protected:
uint32 m_nStartTime; // 开始时间 (单位毫秒)
uint32 m_nCycleTime; // 间隔时间 (单位毫秒)
};
| true |
836f1fc25d48bb91d1d5131d66c84cd15ad28b3b | C++ | vikashkumarjha/missionpeace | /lc/lc/2021_target/core/binary_search/lc_352_data_stream_as_disjoint_sets.cpp | UTF-8 | 1,636 | 3.515625 | 4 | [] | no_license | /*
Given a data stream input of non-negative integers a1, a2, ..., an, ..., summarize the numbers seen so far as a list of disjoint intervals.
For example, suppose the integers from the data stream are 1, 3, 7, 2, 6, ..., then the summary will be:
[1, 1]
[1, 1], [3, 3]
[1, 1], [3, 3], [7, 7]
[1, 3], [7, 7]
[1, 3], [6, 7]
*/
class SummaryRanges {
set<pair<int,int>> set0;
public:
SummaryRanges() {}
void addNum(int val) {
auto iter = set0.lower_bound({val, 0});
int left = val, right = val;
// only two intervals can overlap with val, lower_bound and the one before lower_bound
// check both and do possible merges
if (iter != set0.begin()) {
auto piter = prev(iter);
if (piter->second >= val-1) {
left = piter->first;
right = max(piter->second, val);
set0.erase(piter);
}
}
if (iter != set0.end()) {
if (iter->first <= val+1) {
// left has been correctly set, it's either val, or piter->left
right = iter->second;
set0.erase(iter);
}
}
set0.insert({left, right});
}
vector<vector<int>> getIntervals() {
vector<vector<int>> res;
for (auto [start, end] : set0) {
res.push_back({start, end});
}
return res;
}
};
/**
* Your SummaryRanges object will be instantiated and called as such:
* SummaryRanges* obj = new SummaryRanges();
* obj->addNum(val);
* vector<vector<int>> param_2 = obj->getIntervals();
*/
| true |
2a007195ec5d4634deb7645384024abe5de493c4 | C++ | hzqtc/zoj-solutions | /src/zoj1823.cpp | UTF-8 | 501 | 2.640625 | 3 | [] | no_license | #include <cstdio>
#include <cmath>
using namespace std;
int main()
{
typedef long long lint;
lint num,i,upbond;
while(scanf("%lld",&num) , num > 0)
{
i = 2;
upbond = (lint)sqrt((double)num);
while(num >= i && i <= upbond)
{
if(num % i)
{
if(i == 2)
i++;
else
i += 2;
}
else
{
printf("%lld\n",i);
num /= i;
upbond = (lint)sqrt((double)num);
}
}
printf("%lld\n",num);
putchar('\n');
}
return 0;
} | true |
89c0d0d566b5d3b43da2319509e5e8b0766babe8 | C++ | tgxworld/CS1020E | /tutorials/6/List.cpp | UTF-8 | 3,552 | 3.40625 | 3 | [] | no_license | #include <iostream>
#include <sstream>
#include "List.h"
using namespace std;
List::List(int skipInt) {
this->_size = 0;
this->_head = NULL;
this->_skipInt = skipInt;
}
KListNode* List::traverseTo(int index) {
if(index < 0 || index > this->_size) {
return NULL;
} else {
KListNode* ptr;
ptr = this->_head;
for(int i = 1; i < index; ++i) {
if(index - i >= this->_skipInt) {
ptr = ptr->getKNext();
i += this->_skipInt - 1;
} else {
ptr = ptr->getNext();
}
}
return ptr;
}
}
bool List::insertKListNode(int index, const int& newItem) {
int newLength = this->_size + 1;
if(index < 1 || index > newLength) {
return false;
} else {
KListNode* ptr = new KListNode(newItem, this->_skipInt);
KListNode* cur;
this->_size = newLength;
if(index == 1) {
ptr->setNext(this->_head);
cur = ptr;
for(int i = 0; i < this->_skipInt; ++i) {
cur = cur->getNext();
}
ptr->setKNext(cur);
this->_head = ptr;
} else {
KListNode* prev = this->traverseTo(index - 1);
ptr->setNext(prev->getNext());
prev->setNext(ptr);
int range = this->_size - this->_skipInt;
if(range > 0) {
ptr = this->_head;
while(ptr->getNext() != NULL && range != 0) {
cur = ptr;
for(int i = 0; i < this->_skipInt; ++i) {
cur = cur->getNext();
}
ptr->setKNext(cur);
ptr = ptr->getNext();
range--;
}
}
}
}
return true;
}
bool List::removeKListNode(int index) {
if(index < 1 || index > this->_size) {
return false;
} else {
KListNode* ptr;
if(index == 1) {
ptr = this->_head;
_head = (this->_head)->getNext();
} else {
KListNode *prev = traverseTo(index - 1);
ptr = prev->getNext();
prev->setNext(ptr->getNext());
int range = this->_size - this->_skipInt;
KListNode* newPtr;
if(range > 0) {
newPtr = this->_head;
int i = 1;
while(newPtr != NULL && i <= range) {
int rangeIndex = i + this->_skipInt;
if(rangeIndex >= index) {
if(rangeIndex >= this->_size) {
newPtr->setKNext(NULL);
} else {
KListNode* cur;
cur = newPtr;
for(int i = 0; i < this->_skipInt; ++i) {
cur = cur->getNext();
}
newPtr->setKNext(cur);
}
}
newPtr = newPtr->getNext();
i++;
}
}
}
delete ptr;
ptr = NULL;
--this->_size;
}
return true;
}
void List::pushBack(int &item) {
KListNode *ptr;
KListNode *newPtr = new KListNode(item, this->_skipInt);
ptr = this->_head;
if(ptr == NULL) {
newPtr->setNext(this->_head);
this->_head = newPtr;
this->_size++;
} else {
ptr = this->traverseTo(this->_size);
ptr->setNext(newPtr);
this->_size++;
int prevKIndex = this->_size - this->_skipInt;
if(prevKIndex > 0) {
KListNode* prevPtr = this->traverseTo(prevKIndex);
prevPtr->setKNext(newPtr);
}
}
}
void List::printList() {
ostringstream os;
os << "[ ";
KListNode* curr;
for(curr = this->_head; curr != NULL; curr = curr->getNext()) {
os << curr->getItem();
if(curr->getKNext() != NULL) { os << "/" << curr->getKNext()->getItem(); }
os << " ";
}
os << "]";
cout << os.str() << endl;
}
| true |
53abb734a696668cca85c2e9478f1723e0d3188c | C++ | BrinkOfMan/Software-Design | /hw10/steps.cpp | UTF-8 | 1,175 | 3.203125 | 3 | [] | no_license | #include"../react.h"
int func(int arg)
{
arg = arg + 2;
return arg;
}
int funcp(int *argp)
{
*argp = (*argp) + 2;
return *argp;
}
int main ()
{
int i = 17;
double f = -4.2;
int *ip = &i;
double *fp = &f;
print("Initial values: i is {i}, *ip is {ip}, f is {f}, *fp is {fp}\n", {{"i",i},{"ip",*ip},{"f",f},{"fp",*fp}});
i *= 3;
*fp *= 1.5;
print("After multiplying: i is {i}, *ip is {ip}, f is {f}, *fp is {fp}\n", {{"i",i},{"ip",*ip},{"f",f},{"fp",*fp}});
double f2 = 2.5;
fp = &f2;
i *= *ip;
print("i is {i}, *ip is {ip}, f is {f}, *fp is {fp}, f2 is {f2}\n", {{"i",i},{"ip",*ip},{"f",f},{"fp",*fp},{"f2",f2}});
print("func(i) returns {fi}", {{"fi", func(i)}});
print(", i is {i}, *ip is {ip}\n", {{"i", i}, {"ip", *ip}});
print("func(*ip) returns {fip}", {{"fip", func(*ip)}});
print(", i is {i}, *ip is {ip}\n", {{"i", i}, {"ip", *ip}});
print("funcp(ip) returns {fip}", {{"fip", funcp(ip)}});
print(", i is {i}, *ip is {ip}\n", {{"i", i}, {"ip", *ip}});
print("funcp(&i) returns {fi}", {{"fi", funcp(&i)}});
print(", i is {i}, *ip is {ip}\n", {{"i", i}, {"ip", *ip}});
}
| true |
667bcaabfcacb8b1c2ca2c0dc665b95074db6e1c | C++ | griels/gojsonsm | /src/cpp/rc4.cpp | UTF-8 | 2,125 | 2.515625 | 3 | [] | no_license | std::string KeySizeError::_ErrorByValue()
{
return "crypto/rc4: invalid key size " + strconv::Itoa(int(this));
}
std::tuple<Cipher *, moku::error> NewCipher(moku::slice<uint8_t> key)
{
Cipher c{};
uint8_t j{0};
int k{0};
k = len(key);
if (k < 1 || k > 256) {
return {nil, KeySizeError(k)};
}
{
int i{0};
for (i = 0; i < 256; i++) {
c.s[i] = uint32_t(i);
}
}
{
int i{0};
for (i = 0; i < 256; i++) {
j += uint8_t(c.s[i]) + key[i % k];
std::tie(c.s[i], c.s[j]) =
std::tuple<uint32_t, uint32_t>(c.s[j], c.s[i]);
}
}
return {&c, nil};
}
void Cipher::Reset()
{
{
int i{0};
for (i : moku::range_key<std::vector<uint32_t>>(this->s)) {
this->s[i] = 0;
}
}
std::tie(this->i, this->j) = std::tuple<uint8_t, uint8_t>(0, 0);
}
void Cipher::xorKeyStreamGeneric(moku::slice<uint8_t> dst,
moku::slice<uint8_t> src)
{
uint8_t i{0};
uint8_t j{0};
std::tie(i, j) = std::tuple<uint8_t, uint8_t>(this->i, this->j);
{
int k{0};
uint8_t v{0};
for (std::tie(k, v) :
moku::range_key_value<moku::slice<uint8_t>>(src)) {
i += 1;
j += uint8_t(this->s[i]);
std::tie(this->s[i], this->s[j]) =
std::tuple<uint32_t, uint32_t>(this->s[j], this->s[i]);
dst[k] = v ^ uint8_t(this->s[uint8_t(this->s[i] + this->s[j])]);
}
}
std::tie(this->i, this->j) = std::tuple<uint8_t, uint8_t>(i, j);
}
int main()
{
_main();
return 0;
}
void xorKeyStream(uint8_t *dst,
uint8_t *src,
int n,
std::vector<uint32_t> *state,
uint8_t *i,
uint8_t *j)
{
}
void Cipher::XORKeyStream(moku::slice<uint8_t> dst, moku::slice<uint8_t> src)
{
if (len(src) == 0) {
return;
}
xorKeyStream(&dst[0], &src[0], len(src), &this->s, &this->i, &this->j);
}
int main()
{
_main();
return 0;
}
| true |
b9f80489b8b299eb37835d7ef19088b98726f66b | C++ | welldias/stonedb | /src/data/code_list_adapter.h | UTF-8 | 3,674 | 2.90625 | 3 | [] | no_license | #ifndef __PROJECT_STONE_DATA_CODELISTADAPTER_H__
#define __PROJECT_STONE_DATA_CODELISTADAPTER_H__
#include <string>
#include <vector>
#include <cstdint>
#include "list_data_provider.h"
#include "list_data_provider_helper.h"
#include "../oci20/oci20.h"
namespace Data {
struct CodeEntry {
std::string owner ; //"owner" HIDDEN
std::string object_name ; //"object_name" "Name"
tm created ; //"created" "Created"
tm last_ddl_time; //"last_ddl_time" "Modified"
std::string status ; //"status" "Status"
CodeEntry();
bool deleted;
};
class CodeListAdapter : public ListDataProvider, ListDataProviderHelper {
public:
enum class MonoType {
Procedure,
Function,
Package,
PackageBody,
Java,
};
protected:
std::vector<CodeEntry> m_entries;
Oci20::Connect& m_connect;
MonoType m_monoType;
public:
CodeListAdapter(Oci20::Connect& connect, MonoType monoType);
const CodeEntry& Data(int row) const { return m_entries.at(row); }
virtual int GetRowCount() const { return (int)m_entries.size(); }
virtual int GetColCount() const { return 4; }
virtual ListDataProvider::ColumnType GetColumnType(int col) const {
switch (col) {
case 0: return ColumnType::String;
case 1: return ColumnType::Date;
case 2: return ColumnType::Date;
case 3: return ColumnType::String;
}
return ColumnType::String;
}
virtual void GetColHeader(int col, std::string& value) const {
value = "Unknown";
switch (col) {
case 0: value = "Name" ; return;
case 1: value = "Created" ; return;
case 2: value = "Modifies" ; return;
case 3: value = "Status" ; return;
}
}
virtual void GetString(int row, int col, std::string& value) const {
value = "Unknown";
switch (col) {
case 0: ToString(Data(row).object_name ,value); return;
case 1: ToString(Data(row).created ,value); return;
case 2: ToString(Data(row).last_ddl_time,value); return;
case 3: ToString(Data(row).status ,value); return;
}
}
bool IsVisibleRow(int row) const {
return !Data(row).deleted;
}
virtual int Compare(int row1, int row2, int col) const {
switch (col) {
case 0: return Comp(Data(row1).object_name ,Data(row2).object_name );
case 1: return Comp(Data(row1).created ,Data(row2).created);
case 2: return Comp(Data(row1).last_ddl_time,Data(row2).last_ddl_time);
case 3: return Comp(Data(row1).status ,Data(row2).status);
}
return 0;
}
virtual int GetMinDefColWidth(int col) const {
return !col ? 200 : ListDataProvider::GetMinDefColWidth(col);
}
virtual size_t Query();
virtual InfoType GetInfoType() const {
switch (m_monoType) {
case MonoType::Function: return InfoType::Function;
case MonoType::Package: return InfoType::Package;
case MonoType::PackageBody: return InfoType::PackageBody;
case MonoType::Procedure:
default:
return InfoType::Procedure;
}
}
};
}
#endif /*__PROJECT_STONE_DATA_CODELISTADAPTER_H__*/ | true |
cc8418749dc23fe72d27a58f3c5e3eb8b5837682 | C++ | wiliamhw/Data-Structure-Course | /Cpp/PFinal/ToT.cpp | UTF-8 | 644 | 3.0625 | 3 | [] | no_license | // https://www.hackerrank.com/contests/final-sd-2020/challenges/train-of-thought
#include <iostream>
#include <cstring>
using namespace std;
const int maxSize = 100000000;
int main(void)
{
bool *arr = new bool[maxSize];
memset(arr, false, sizeof(bool) * maxSize);
int N;
cin >> N;
while (N-- > 0) {
int input;
cin >> input;
// Input is duplicate
if (arr[input - 1] == true) {
cout << "SUSAH BANGED WOI!" << endl;
return 0;
}
else {
arr[input - 1] = true;
}
}
cout << "NAH GITU DONG, NGEGAS!" << endl;
return 0;
}
| true |
abac6103de936f38c4b4f246b6f695936220b64c | C++ | bromlu/CPong | /menu.hpp | UTF-8 | 2,894 | 2.90625 | 3 | [] | no_license | class Menu {
public:
Menu(int width, int height, sf::Font *font) {
loadAssets();
this->width = width;
this->height = height;
this->selected = 0;
this->lastMoved = now();
this->lastSelected = now();
title = Text("Spike Pong", width/2, height/5, 150, font, sf::Color::White);
by = Text("By Luke Brom", width/2, height/5 + 120, 40, font, sf::Color::White);
play = Text("Play", width/2, height/2 - 110, 75, font, sf::Color::White);
instructions = Text(" Instructions", width/2, height/2 - 35, 75, font, sf::Color::White);
thanks = Text("Thanks ", width/2, height/2 + 35, 75, font, sf::Color::White);
exit = Text("Exit", width/2, height/2 + 110, 75, font, sf::Color::White);
options[0] = Option(&play, 1, true);
options[1] = Option(&instructions, 2, false);
options[2] = Option(&thanks, 3, false);
options[3] = Option(&exit, 6, false);
}
void setLastSelected() {
this->lastSelected = now();
}
int update() {
if(now() - lastMoved > (0.2)){
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
{
options[selected].unselect();
selected--;
if(selected < 0) {
selected = 3;
}
options[selected].select();
move.play();
lastMoved = now();
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
{
options[selected].unselect();
selected++;
if(selected > 3) {
selected = 0;
}
options[selected].select();
move.play();
lastMoved = now();
}
}
if(now() - lastSelected > (0.5)){
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Return))
{
lastSelected = now();
select.play();
return options[selected].getState();
}
}
return 0;
}
void draw(sf::RenderWindow *window) {
title.draw(window);
by.draw(window);
for(int i = 0; i < 4; i++) {
options[i].draw(window);
}
}
private:
void loadAssets() {
moveBuffer.loadFromFile("assets/sfx_menu_move1.wav");
move.setBuffer(moveBuffer);
selectBuffer.loadFromFile("assets/sfx_menu_select1.wav");
select.setBuffer(selectBuffer);
}
Text title;
Text by;
Text play;
Text instructions;
Text thanks;
Text exit;
Option options[4];
sf::Sound move;
sf::Sound select;
sf::SoundBuffer moveBuffer;
sf::SoundBuffer selectBuffer;
int width;
int height;
int selected;
double lastMoved;
double lastSelected;
}; | true |
bb86a4c826059dbdf4b36bcedcd08b869af7509e | C++ | ryanchengguo/C-Plus-Plus-Application-Development-1 | /Exercise 6.26/Exercise 6.26/main.cpp | UTF-8 | 1,143 | 3.578125 | 4 | [] | no_license | //
// main.cpp
// Exercise 6.26
//
// Created by Ryan Guo on 5/25/19.
// Copyright © 2019 Ryan Guo. All rights reserved.
//
#include <iostream>
#include <iomanip>
using namespace std;
double celsius(double f);
double fahrenheit(double c);
int main() {
cout << fixed << setprecision(1);
cout << setw(5) << "Celsius" << setw(24) << "Fabrenbeit" << setw(17) << "Celsius" << setw(22) << "Fabrenbeit" << "\n\n";
for(double i = 1; i < 51; i++){
cout << setw(5) << i - 1 << setw(20) << fahrenheit(i - 1) << setw(20) << i + 50 << setw(20) << fahrenheit(i + 50) << "\n";
}
cout << "\n\n\n";
cout << setw(5) << "Fabrenbeit" << setw(18) << "Celsius" << setw(22) << "Fabrenbeit" << setw(17) << "Celsius" << "\n\n";
for(double i = 32; i < 107; i++){
cout << setw(5) << i << setw(20) << celsius(i) << setw(20) << i + 106 << setw(20) << celsius(i + 106) << "\n";
}
}
//5 and 9 should be 5.0 and 9.0 convert to double. otherwise 5 / 9 = 0 <------------
double celsius(double f){
return (f - 32.0) * (5.0 / 9.0);
}
double fahrenheit(double c){
return (c * 9.0 / 5.0) + 32.0;
}
| true |
2a618c06a915fa9ee4c34064cc30de122f4f009b | C++ | lazybones1/Algorithms | /백준알고리즘/단계별로 풀어보기/18. 스택/P_Number_10773.cpp | UTF-8 | 465 | 2.84375 | 3 | [] | no_license | #include <iostream>
#include <stack>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cout.tie(NULL); cin.tie(NULL);
int k;
cin>>k;
int ans = 0;
stack<int> s;
for(int i = 0; i<k; i++){
int command;
cin>>command;
if(command == 0){
s.pop();
}
else{
s.push(command);
}
}
int stackSize = s.size();
for(int i = 0; i<stackSize; i++){
ans += s.top();
s.pop();
}
cout<<ans;
return 0;
}
| true |
7abf3dc1d9c7fbf3b2f06577110a98eba77f5d1e | C++ | Jackbenfu/Jackbengine | /src/component/generic/stringComponent.hpp | UTF-8 | 611 | 2.546875 | 3 | [] | no_license | //
// stringComponent.hpp
// jackbengine
//
// Created by Damien Bendejacq on 31/07/2017.
// Copyright © 2017 Damien Bendejacq. All rights reserved.
//
#ifndef __STRING_COMPONENT_H__
#define __STRING_COMPONENT_H__
#include <string>
#include "component/component.hpp"
namespace Jackbengine {
class StringComponent : public Component
{
public:
explicit StringComponent(const std::string& value);
~StringComponent() override = default;
const std::string& get() const;
void set(const std::string& value);
private:
std::string m_value;
};
using String = StringComponent;
}
#endif // __STRING_COMPONENT_H__
| true |
2c56cea1c9026df9ec17496bf66eca619cfefcb3 | C++ | prolog/shadow-of-the-wyrm | /engine/calculators/source/unit_tests/PhysicalDamageCalculator_test.cpp | UTF-8 | 5,354 | 2.984375 | 3 | [
"MIT",
"Zlib"
] | permissive | #include "gtest/gtest.h"
CreaturePtr create_creature_with_weapon_and_15_str();
CreaturePtr create_creature_with_weapon_and_15_str()
{
CreaturePtr creature = std::make_shared<Creature>();
creature->set_strength(15);
ItemPtr weapon_item = ItemPtr(new MeleeWeapon());
Damage damage(3,4,2,DamageType::DAMAGE_TYPE_SLASH, {}, false, false, false, false, false, false, false, false, 0, {});
WeaponPtr weapon = std::dynamic_pointer_cast<Weapon>(weapon_item);
weapon->set_damage(damage);
creature->get_equipment().set_item(weapon_item, EquipmentWornLocation::EQUIPMENT_WORN_WIELDED);
return creature;
}
TEST(SW_World_Calculators_PhysicalDamageCalculator, calculate_base_damage_object)
{
PhysicalDamageCalculator pdc(AttackType::ATTACK_TYPE_MELEE_PRIMARY, PhaseOfMoonType::PHASE_OF_MOON_NEW);
CreaturePtr creature = create_creature_with_weapon_and_15_str();
Statistic addl_creature_damage(10);
creature->set_addl_damage(addl_creature_damage);
// The base damage object should just be the weapon's damage.
Damage base_damage = pdc.calculate_base_damage_object(creature);
WeaponPtr weapon = std::dynamic_pointer_cast<Weapon>(creature->get_equipment().get_item(EquipmentWornLocation::EQUIPMENT_WORN_WIELDED));
Damage expected_damage = weapon->get_damage();
// Should exclude the creature's add'l damage - that will be accounted for
// in the bonuses/penalties.
EXPECT_EQ(expected_damage, base_damage);
}
TEST(SW_World_Calculators_PhysicalDamageCalculator, calculate_base_damage_with_bonuses)
{
PhysicalDamageCalculator pdc(AttackType::ATTACK_TYPE_MELEE_PRIMARY, PhaseOfMoonType::PHASE_OF_MOON_NEW);
CreaturePtr creature = create_creature_with_weapon_and_15_str();
Statistic addl_creature_damage(10);
creature->set_addl_damage(addl_creature_damage);
Damage exp_base_damage = pdc.calculate_base_damage_object(creature);
int bonus = pdc.get_statistic_based_damage_modifier(creature);
bonus += creature->get_addl_damage().get_current();
exp_base_damage.set_modifier(exp_base_damage.get_modifier() + bonus);
EXPECT_EQ(exp_base_damage, pdc.calculate_base_damage_with_bonuses_or_penalties(creature));
Status s;
s.set_value(true);
creature->set_status(StatusIdentifiers::STATUS_ID_RAGE, s);
exp_base_damage.set_modifier(exp_base_damage.get_modifier() + (creature->get_level().get_current() * 2));
EXPECT_EQ(exp_base_damage, pdc.calculate_base_damage_with_bonuses_or_penalties(creature));
}
// For every 5 points of Str > 10, +1 dam.
TEST(SW_World_Calculators_PhysicalDamageCalculator, get_statistic_based_damage_modifier)
{
PhysicalDamageCalculator pdc(AttackType::ATTACK_TYPE_MELEE_PRIMARY, PhaseOfMoonType::PHASE_OF_MOON_NEW);
CreaturePtr creature = std::make_shared<Creature>();
creature->set_strength(3);
EXPECT_EQ(0, pdc.get_statistic_based_damage_modifier(creature));
creature->set_strength(16);
EXPECT_EQ(1, pdc.get_statistic_based_damage_modifier(creature));
creature->set_strength(47);
EXPECT_EQ(7, pdc.get_statistic_based_damage_modifier(creature));
}
// For every 10 points of Dual Wield, +10 damage to secondary attacks.
TEST(SW_World_Calculators_PhysicalDamageCalculator, get_dual_wield_modifier)
{
PhysicalDamageCalculator pdc_p(AttackType::ATTACK_TYPE_MELEE_PRIMARY, PhaseOfMoonType::PHASE_OF_MOON_NEW);
PhysicalDamageCalculator pdc_s(AttackType::ATTACK_TYPE_MELEE_SECONDARY, PhaseOfMoonType::PHASE_OF_MOON_NEW);
PhysicalDamageCalculator pdc_tu(AttackType::ATTACK_TYPE_MELEE_TERTIARY_UNARMED, PhaseOfMoonType::PHASE_OF_MOON_NEW);
PhysicalDamageCalculator pdc_r(AttackType::ATTACK_TYPE_RANGED, PhaseOfMoonType::PHASE_OF_MOON_NEW);
std::vector<PhysicalDamageCalculator> unaffected_types({ pdc_p, pdc_tu, pdc_r });
std::vector<std::pair<int, int>> expected_bonuses({ {0,0}, {11,1}, {28,2}, {30, 3}, {44, 4}, {52,5}, {63,6}, {77,7}, {89,8}, {94,9}, {100,10} });
CreaturePtr creature = std::make_shared<Creature>();
for (auto& value_and_bonus : expected_bonuses)
{
creature->get_skills().set_value(SkillType::SKILL_GENERAL_DUAL_WIELD, value_and_bonus.first);
EXPECT_EQ(value_and_bonus.second, pdc_s.get_skill_based_damage_modifier(creature));
for (auto& pdc : unaffected_types)
{
EXPECT_EQ(0, pdc.get_skill_based_damage_modifier(creature));
}
}
}
// For every 0.02 BAC, +1 dam.
TEST(SW_World_Calculators_PhysicalDamageCalculator, get_drunkenness_modifier)
{
PhysicalDamageCalculator pdc(AttackType::ATTACK_TYPE_MELEE_PRIMARY, PhaseOfMoonType::PHASE_OF_MOON_NEW);
CreaturePtr creature = create_creature_with_weapon_and_15_str();
Blood b;
b.set_litres(5);
b.set_grams_alcohol(1);
creature->set_blood(b);
Damage exp_base_damage = pdc.calculate_base_damage_object(creature);
int bonus = pdc.get_statistic_based_damage_modifier(creature);
int dr_bonus = static_cast<int>(creature->get_blood().get_blood_alcohol_content() * 100) / 2;
exp_base_damage.set_modifier(exp_base_damage.get_modifier() + bonus + dr_bonus);
EXPECT_EQ(exp_base_damage, pdc.calculate_base_damage_with_bonuses_or_penalties(creature));
// Go from 0.02 to 0.06, or +2 additional damage.
b.set_grams_alcohol(3);
creature->set_blood(b);
exp_base_damage.set_modifier(exp_base_damage.get_modifier() + 2);
EXPECT_EQ(exp_base_damage, pdc.calculate_base_damage_with_bonuses_or_penalties(creature));
} | true |
ffad0b571bea70e636ae32eac404a0aceb51c382 | C++ | vidit-virmani/CP | /vidit_123/codeforces/479-C/479-C-36733580.cpp | UTF-8 | 778 | 2.6875 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
struct node{
int ff;
int ss;
}q[5005];
bool cmp(node A,node B){
if(A.ff==B.ff){
return A.ss<B.ss;
}
return A.ff<B.ff;
}
int main(){
//1st attempt to understand the question :p
int n;
cin>>n;
for(int i=0;i<n;i++){
cin>>q[i].ff>>q[i].ss;
}
int ans=INT_MAX;
sort(q,q+n,cmp);
int lastmin=min(q[0].ff,q[0].ss);
for(int i=1;i<n;i++){
if(lastmin<=q[i].ff && lastmin<=q[i].ss){
lastmin=min(q[i].ff,q[i].ss);
}
else if(q[i].ff>=lastmin && lastmin>=q[i].ss){
lastmin=q[i].ff;
}
else if(q[i].ff<lastmin && q[i].ss>lastmin){
lastmin=q[i].ss;
}
}
cout<<lastmin;
return 0;
} | true |
cafb818c29cb2828eb57867a432677271c20a23d | C++ | itstechgaurav/cpp-term-work | /q14.cpp | UTF-8 | 2,166 | 3.28125 | 3 | [] | no_license | #include<iostream>
#include<stdlib.h>
using namespace std;
char sname[10][10];
class student {
int id,age,i;
char name[10], g;
float marks[5], avg, total;
void calc() {
total = 0;
for(i = 0; i < 5; i++) {
total+=marks[i];
}
avg = total/5;
// grades
if(avg >= 80) g = 'A';
else if(avg < 80 && avg >= 70) g = 'B';
else if(avg < 70 && avg >= 60) g = 'C';
else if(avg < 60 && avg >= 50) g = 'D';
else if(avg < 50 && avg >= 40) g = 'E';
else g = 'F';
}
public:
void read() {
cout << "Enter id: ";
cin >> id;
cout << "Enter name: ";
cin >> name;
cout << "Enter age: ";
cin >> age;
for(i = 0; i < 5; i++) {
cout << "Marks in " << sname[i] << ": ";
cin >> marks[i];
}
calc();
}
void write() {
cout.width(3);
cout << left << id;
cout.width(11);
cout << name;
cout.width(4);
cout << age;
for(i = 0; i < 5; i++) {
cout.width(7);
cout << marks[i] << " ";
}
cout.width(7);
cout << total;
cout.width(9);
cout << avg << " ";
cout.width(6);
cout << g << endl;
}
};
void tableHead() {
int i;
cout << endl<<endl;
cout.width(3);
cout << left << "ID ";
cout.width(11);
cout << "Name";
cout.width(4);
cout << "AGE";
for(i = 0; i < 5; i++) {
cout.width(7);
cout << sname[i] << " ";
}
cout.width(7);
cout << "Total ";
cout.width(9);
cout << "Average ";
cout.width(6);
cout << "Grade ";
cout << endl << "----------------------------------------------------------------\n";
}
int main() {
int i, n;
student stu[20];
cout << "Enter total students: ";
cin >> n;
for(i = 0; i < 5; i++) {
cout << "Enter subject name: ";
cin >> sname[i];
}
for(i = 0; i < n; i++) {
stu[i].read();
}
tableHead();
for(i = 0; i < n; i++) {
stu[i].write();
}
return 0;
} | true |
b8eea41fec1ec69b9de527e06fbcbddb61f2ecfb | C++ | HeElLyan/homeworkMPI | /Task11.cpp | UTF-8 | 1,944 | 2.65625 | 3 | [] | no_license | ////
//// Created by He Elvina on 29.09.2020.
////
//
//#include <mpi.h>
//#include <iostream>
//
//using namespace std;
//
//// Циклическая передача данных (6 баллов)
//// В коммуникаторе передаем сообщение от одного
//// процесса другому с нулевого до size-1.
//// Последний процесс отправляет сообщение нулевому.
//// На каждом процессе сообщение изменяется, если это число,
//// то можно прибавлять или умножать на что-то.
//
//int main(int argc, char** argv)
//{
// MPI_Init(&argc, &argv);
//
// int rank, size;
// int *sendbuf, *recvbuf;
//
// MPI_Comm_size(MPI_COMM_WORLD, &size);
// MPI_Comm_rank(MPI_COMM_WORLD, &rank);
//
// sendbuf = new int[1];
// recvbuf = new int[1];
//
// if (!rank) {
// sendbuf[0] = 1;
// //посылает первому процессу
// MPI_Send(sendbuf, 1, MPI_INT, rank + 1, rank + 1, MPI_COMM_WORLD);
// }
// else
// {
// //получают от предыдущего процесса
// MPI_Recv(recvbuf, 1, MPI_INT, rank - 1, rank, MPI_COMM_WORLD, MPI_STATUSES_IGNORE);
//
// sendbuf[0] = 2 * recvbuf[0];
//
// if (rank != size - 1)
// //отправляют следующему процессу
// MPI_Send(sendbuf, 1, MPI_INT, rank + 1, rank + 1, MPI_COMM_WORLD);
// else
// //последний ранк отправляет обратно первому
// MPI_Send(sendbuf, 1, MPI_INT, 0, 0, MPI_COMM_WORLD);
// }
//
// if (!rank) {
// MPI_Recv(recvbuf, 1, MPI_INT, size - 1, 0, MPI_COMM_WORLD, MPI_STATUSES_IGNORE);
// printf("Result = %d\n", recvbuf[0]);
// }
//
// MPI_Finalize();
// return EXIT_SUCCESS;
//} | true |
bcad5be66c00c0628f5b19ebb993f318c74cc987 | C++ | UTennessee-JICS/MPCC | /src/MPCC.cpp | UTF-8 | 32,415 | 2.890625 | 3 | [] | no_license | //Pearsons correlation coeficient for two vectors x and y
// r = sum_i( x[i]-x_mean[i])*(y[i]-y_mean[i]) ) /
// [ sqrt( sum_i(x[i]-x_mean[i])^2 ) sqrt(sum_i(y[i]-y_mean[i])^2 ) ]
// Matrix reformulation and algebraic simplification for improved algorithmic efficiency
// where A is matrix of X vectors and B is transposed matrix of Y vectors:
// R = [N sum(AB) - (sumA)(sumB)] /
// sqrt[ (N sumA^2 - (sum A)^2)[ (N sumB^2 - (sum B)^2) ]
//This code computes correlation coefficient between all row/column pairs of two matrices
// ./MPCC MatA_filename MatB_filename
#include "MPCC.h"
using namespace std;
#define __assume(cond) do { if (!(cond)) __builtin_unreachable(); } while (0)
#ifndef USING_R
#define __assume_aligned(var,size){ __builtin_assume_aligned(var,size); }
#else
#define __assume_aligned(var,size){ }
#endif
#define DEV_CHECKPT printf("Checkpoint: %s, line %d\n", __FILE__, __LINE__); fflush(stdout);
#ifndef NAIVE //default use matrix version
#define NAIVE 0
#endif
#ifndef DOUBLE //default to float type
#define DOUBLE 0
#endif
#ifdef NOMKL
// MKL substitute functions vSqr
void vSqr (int l, DataType* in, DataType* out) {
int i;
#pragma omp parallel for private(i)
for(i = 0; i < l; i++) { out[i] = in[i] * in[i]; }
}
// MKL substitute functions vMul
void vMul (int l, DataType* in1, DataType* in2, DataType* out) {
int i;
#pragma omp parallel for private(i)
for(i = 0; i < l; i++) { out[i] = in1[i] * in2[i]; }
}
// MKL substitute functions vSqrt
void vSqrt (int l, DataType* in, DataType* out) {
int i;
#pragma omp parallel for private(i)
for(i = 0; i < l; i++) { out[i] = sqrt(in[i]); }
}
// MKL substitute functions vDiv
void vDiv (int l, DataType* in1, DataType* in2, DataType* out) {
int i;
#pragma omp parallel for private(i)
for(i = 0; i < l; i++) { out[i] = in1[i] / in2[i]; }
}
// dgemm_wrap function for R_ext/Lapack.h dgemm
// Call dgemm_ function pointer using fortran name mangling
void dgemm_wrap(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA,
const enum CBLAS_TRANSPOSE TransB, const int M, const int N,
const int K, const double alpha, const double *A,
const int lda, const double *B, const int ldb,
const double beta, double *C, const int ldc){
F77_CALL(dgemm)("T", "N", &N, &M, &K, &alpha, B, &lda, A, &ldb, &beta, C, &N);
//F77_CALL(dgemm)("T", "N", &M, &N, &K, &alpha, A, &lda, B, &ldb, &beta, C, &ldc);
}
// daxpy_wrap function for R_ext/Lapack.h daxpy
// Call daxpy_ function pointer using fortran name mangling
void daxpy_wrap(const int N, const double alpha, const double *X,
const int incX, double *Y, const int incY){
F77_CALL(daxpy)(&N, &alpha, X, &incX, Y, &incY);
}
#endif
// vMul function when input matrix A == B
void vMulSameAB(int m, int p, DataType* in1, DataType* in2, DataType* out){
int i, j;
#pragma omp parallel for private(i, j)
for(i = 0; i < m; i++) {
for(j = 0; j < p; j++) {
out[i*m + j] = in1[i*m + j] * in2[j*m + i];
}
}
}
#ifndef USING_R
static DataType TimeSpecToSeconds(struct timespec* ts){
return (DataType)ts->tv_sec + (DataType)ts->tv_nsec / 1000000000.0;
}
static DataType TimeSpecToNanoSeconds(struct timespec* ts){
return (DataType)ts->tv_sec*1000000000.0 + (DataType)ts->tv_nsec;
}
// This function convert a string to datatype (double or float);
DataType convert_to_val(string text)
{
DataType val;
if(text=="nan" || text=="NaN" || text=="NAN"){ val = NANF;}
else{ val = atof(text.c_str());}
return val;
}
// This function initialized the matrices for m, n, p sized A and the B and result (C) matrices
// Not part of the R interface since R initializes the memory
void initialize(int &m, int &n, int &p, int seed,
DataType **A,
DataType **B,
DataType **C,
char* matA_filename,
char* matB_filename,
bool &transposeB)
{
// A is m x n (tall and skinny) row major order
// B is n x p (short and fat) row major order
// C, P is m x p (big and square) row major order
//if matA_filename exists, read in dimensions
// check for input file(s)
std::string text;
//DataType val;
fstream mat_A_file;
mat_A_file.open(matA_filename,ios::in);
if(mat_A_file.is_open()){
// if found then read
std::getline(mat_A_file, text);
m = convert_to_val(text);
std::getline(mat_A_file, text);
n = convert_to_val(text);
printf("m=%d n=%d\n",m,n);
mat_A_file.close();
}
//else use default value for m,n
*A = (DataType *)ALLOCATOR( m*n,sizeof( DataType ), 64 );
if (*A == NULL ) {
printf( "\n ERROR: Can't allocate memory for matrix A. Aborting... \n\n");
FREE(*A);
exit (0);
}
//if matB_filename exists, read in dimensions
// check for input file(s)
fstream mat_B_file;
int _n=n;
mat_B_file.open(matB_filename,ios::in);
if(mat_B_file.is_open()){
// if found then read
std::getline(mat_B_file, text);
_n = convert_to_val(text);
std::getline(mat_B_file, text);
p = convert_to_val(text);
printf("_n=%d p=%d\n",_n,p);
mat_B_file.close();
}
//check to see if we need to transpose B
transposeB=false;
if(_n !=n && n==p){//then transpose matrix B
p=_n;
_n=n;
transposeB=true;
printf("Transposing B for computational efficiency in GEMMs\n");
printf("transposed _n=%d p=%d\n",_n,p);
}
//check that inner dimension matches
assert(n==_n);
//else use default value for n,p
*B = (DataType *)ALLOCATOR( n*p,sizeof( DataType ), 64 );
if (*B == NULL ) {
printf( "\n ERROR: Can't allocate memory for matrix B. Aborting... \n\n");
FREE(*B);
exit (0);
}
printf("m=%d n=%d p=%d\n",m,n,p);
*C = (DataType *)ALLOCATOR( m*p,sizeof( DataType ), 64 );
if (*C == NULL ) {
printf( "\n ERROR: Can't allocate memory for matrix C. Aborting... \n\n");
FREE(*C);
exit (0);
}
__assume_aligned(A, 64);
__assume_aligned(B, 64);
__assume_aligned(C, 64);
//__assume(m%16==0);
//setup random numbers to create some synthetic matrices for correlation
// if input files do not exist
srand(seed);
DataType randmax_recip=1/(DataType)RAND_MAX;
//Input currently hard coded as binary files matrixA.dat and matrixB.dat
//Or text files input as command line parameters.
//with the form:
//int rows, cols
//float elems[rows:cols]
//If input files do not exist, generate synthetic matrices of given dimensions A[m,p] B[p,n]
// with randomly assigned elements from [0,1] and then add missing values
// in selected locations (currently denoted by the value 2)
//These matrices are of type single precision floating point values
// check for input file(s)
mat_A_file.open(matA_filename,ios::in);
if(mat_A_file.is_open()){
// if found then read
std::getline(mat_A_file, text);
//m = convert_to_val(text);
std::getline(mat_A_file, text);
//n = convert_to_val(text);
for(int i=0;i<m*n;++i){
std::getline(mat_A_file, text);
(*A)[i] = convert_to_val(text);
//if(isnan((*A)[i])){printf("A[%d]==NAN\n",i);}
}
mat_A_file.close();
}
else{ //else compute and then write matrix A
//random assignemnt of threads gives inconsistent values, so keep serial
int i;
#pragma omp parallel for private (i)
for (i=0; i<m*n; i++) {
(*A)[i]=(DataType)rand()*randmax_recip;
}
//add some missing value markers
//Note edge case: if missing data causes number of pairs compared to be <2, the result is divide by zero
(*A)[0] = MISSING_MARKER;
(*A)[m*n-1] = MISSING_MARKER;
(*A)[((m-1)*n-1)]= MISSING_MARKER;
//write matrix to file
mat_A_file.open(matA_filename,ios::out);
mat_A_file << m;
mat_A_file << n;
for(int i=0;i<m*n;++i) mat_A_file << (*A)[i] << '\n';
mat_A_file.close();
}
//ceb Should write out matrix and read in for future use.
// check for input file(s)
mat_B_file.open(matB_filename,ios::in);
if(mat_B_file.is_open()){
std::getline(mat_B_file, text);
//m = convert_to_val(text);
std::getline(mat_B_file, text);
//n = convert_to_val(text);
for(int i=0;i<n*p;++i){
std::getline(mat_B_file, text);
(*B)[i] = convert_to_val(text);
//if(isnan((*B)[i]) ){printf("B[%d]==NAN\n",i);}
}
mat_B_file.close();
}
else{ //else compute and then write matrix B
int i;
//random assignemnt of threads gives inconsistent values, so keep serial
#pragma omp parallel for private (i)
for (i=0; i<n*p; i++) {
(*B)[i]=(DataType)rand()*randmax_recip;
}
//add some missing value markers
//ceb if missing data causes number of pairs compared to be <2, the result is divide by zero
(*B)[0] = MISSING_MARKER;
(*B)[n*p-1] = MISSING_MARKER;
(*B)[((n-1)*p-1)]= MISSING_MARKER;
//write matrix to file
mat_B_file.open(matB_filename,ios::out);
mat_B_file << n;
mat_B_file << p;
for(int i=0; i<n*p; ++i) mat_B_file << (*B)[i];
mat_B_file.close();
}
#if 0
for (int i=0; i<m; i++) { for(int j=0;j<n;++j){printf("A[%d,%d]=%e\n",i,j,(*A)[i*n+j]);}}
for (int i=0; i<n; i++) { for(int j=0;j<p;++j){printf("B[%d,%d]=%e\n",i,j,(*B)[i*p+j]);}}
#endif
return;
};
#endif
#ifndef NOBLAS
//This function is the implementation of a matrix x matrix algorithm which computes a matrix of PCC values
//but increases the arithmetic intensity of the naive pairwise vector x vector correlation
//A is matrix of X vectors and B is transposed matrix of Y vectors:
//P = [ sum(AB) - (sumA)(sumB)/N ] /
// sqrt([ (sumA^2 -(1/N)(sum A)^2) ][ (sumB^2 - (1/N)(sum B)^2) ])
//
//P = [ N*sum(AB) - (sumA)(sumB)] /
// sqrt([ (N*sumA^2 - (sum A)^2) ][ (N*sumB^2 - (sum B)^2) ])
int pcc_matrix(int m, int n, int p,
DataType* A, DataType* B, DataType* P)
{
// Unused variable warning: int stride = ((n-1)/64 +1);
int i,j,k;
DataType alpha = 1.0;
DataType beta = 0.0;
int count = 1;
bool transposeB = true; //assume this is always true.
bool sameAB = (p == 0) ? true : false;
if(p == 0) p = m;
//info("before calloc\n",1);
//allocate and initialize and align memory needed to compute PCC
DataType *N = (DataType *) ALLOCATOR( m*p,sizeof( DataType ), 64 );
__assume_aligned(N, 64);
DataType* SA = ( DataType*)ALLOCATOR( m*p, sizeof(DataType), 64 );
__assume_aligned(SA, 64);
DataType* AA = ( DataType*)ALLOCATOR( m*n, sizeof(DataType), 64 );
__assume_aligned(AA, 64);
DataType* SAA = ( DataType*)ALLOCATOR( m*p, sizeof(DataType), 64 );
__assume_aligned(SAA, 64);
DataType* SB = sameAB ? SA : ( DataType*)ALLOCATOR( m*p, sizeof(DataType), 64 );
__assume_aligned(SB, 64);
DataType* BB = sameAB ? AA : ( DataType*)ALLOCATOR( n*p, sizeof(DataType), 64 );
__assume_aligned(BB, 64);
DataType* SBB = sameAB ? SAA : ( DataType*)ALLOCATOR( m*p, sizeof(DataType), 64 );
__assume_aligned(SBB, 64);
DataType* SAB = ( DataType*)ALLOCATOR( m*p, sizeof(DataType), 64 );
__assume_aligned(SAB, 64);
DataType* UnitA = ( DataType*)ALLOCATOR( m*n, sizeof(DataType), 64 );
__assume_aligned(UnitA, 64);
DataType* UnitB = sameAB ? UnitA : ( DataType*)ALLOCATOR( n*p, sizeof(DataType), 64 );
__assume_aligned(UnitB, 64);
DataType *amask=(DataType*)ALLOCATOR( m*n, sizeof(DataType), 64);
__assume_aligned(amask, 64);
DataType *bmask= sameAB ? amask : (DataType*)ALLOCATOR( n*p, sizeof(DataType), 64);
__assume_aligned(bmask, 64);
//info("after calloc\n",1);
//if any of the above allocations failed, then we have run out of RAM on the node and we need to abort
if ( (N == NULL) | (SA == NULL) | (AA == NULL) | (SAA == NULL) | (SB == NULL) | (BB == NULL) |
(SBB == NULL) | (SAB == NULL) | (UnitA == NULL) | (UnitB == NULL) | (amask == NULL) | (bmask == NULL)) {
err("ERROR: Can't allocate memory for intermediate matrices. Aborting...\n", 1);
FREE(N);
FREE(SA);
FREE(AA);
FREE(SAA);
FREE(SAB);
FREE(UnitA);
FREE(amask);
if(!sameAB) { //only do it when A and B are not same
FREE(SB);
FREE(BB);
FREE(SBB);
FREE(UnitB);
FREE(bmask);
}
#ifndef USING_R
exit(0);
#else
return(0);
#endif
}
//info("before deal missing data\n",1);
//deal with missing data
for (int ii=0; ii<count; ii++) {
//if element in A is missing, set amask and A to 0
#pragma omp parallel for private (i,k)
for (i=0; i<m; i++) {
for (k=0; k<n; k++) {
amask[ i*n + k ] = 1.0;
if (CHECKNA(A[i*n+k])) {
amask[i*n + k] = 0.0;
A[i*n + k] = 0.0; // set A to 0.0 for subsequent calculations of PCC terms
} else {
UnitA[i*n + k] = 1.0;
}
}
}
if (!sameAB) { //only do it when A and B are not same
//if element in B is missing, set bmask and B to 0
#pragma omp parallel for private (j,k)
for (j=0; j<p; j++) {
for (k=0; k<n; k++) {
bmask[ j*n + k ] = 1.0;
if (CHECKNA(B[j*n+k])) {
bmask[j*n + k] = 0.0;
B[j*n + k] = 0.0; // set B to 0.0 for subsequent calculations of PCC terms
} else {
UnitB[j*n + k] = 1.0;
}
}
}
}
GEMM(CblasRowMajor, CblasNoTrans, CblasTrans,
m, p, n, alpha, amask, n, bmask, n, beta, N, p);
//vsSqr(m*n,A,AA);
VSQR(m*n,A,AA);
//vsSqr(n*p,B,BB);
if (!sameAB) { VSQR(n*p,B,BB); } // Only perform VSQR when A and B are not same
//variables used for performance timing
//struct timespec startGEMM, stopGEMM;
//double accumGEMM;
//info("before PCC terms\n",1);
//Compute PCC terms and assemble
CBLAS_TRANSPOSE transB=CblasNoTrans;
int ldb=p;
if(transposeB){
transB=CblasTrans;
ldb=n;
}
//clock_gettime(CLOCK_MONOTONIC, &startGEMM);
//SA = A*UnitB
//Compute sum of A for each AB row col pair.
// This requires multiplication with a UnitB matrix which acts as a mask
// to prevent missing data in AB pairs from contributing to the sum
//cblas_sgemm(CblasRowMajor, CblasNoTrans, transB,
GEMM(CblasRowMajor, CblasNoTrans, transB,
m, p, n, alpha, A, n, UnitB, ldb, beta, SA, p);
//SB = UnitA*B
//Compute sum of B for each AB row col pair.
// This requires multiplication with a UnitA matrix which acts as a mask
// to prevent missing data in AB pairs from contributing to the sum
//cblas_sgemm(CblasRowMajor, CblasNoTrans, transB,
if (!sameAB) { //only do it when A and B are not same
GEMM(CblasRowMajor, CblasNoTrans, transB,
m, p, n, alpha, UnitA, n, B, ldb, beta, SB, p);
}
//SAA = AA*UnitB
//Compute sum of AA for each AB row col pair.
// This requires multiplication with a UnitB matrix which acts as a mask
// to prevent missing data in AB pairs from contributing to the sum
//cblas_sgemm(CblasRowMajor, CblasNoTrans, transB,
GEMM(CblasRowMajor, CblasNoTrans, transB,
m, p, n, alpha, AA, n, UnitB, ldb, beta, SAA, p);
//SBB = UnitA*BB
//Compute sum of BB for each AB row col pair.
// This requires multiplication with a UnitA matrix which acts as a mask
// to prevent missing data in AB pairs from contributing to the sum
//cblas_sgemm(CblasRowMajor, CblasNoTrans, transB,
if (!sameAB) { //only do it when A and B are not same
GEMM(CblasRowMajor, CblasNoTrans, transB,
m, p, n, alpha, UnitA, n, BB, ldb, beta, SBB, p);
}
FREE(UnitA);
FREE(AA);
if (!sameAB) { //only do it when A and B are not same
FREE(UnitB);
FREE(BB);
}
//SAB = A*B
//cblas_sgemm(CblasRowMajor, CblasNoTrans, transB,
GEMM(CblasRowMajor, CblasNoTrans, transB,
m, p, n, alpha, A, n, B, ldb, beta, SAB, p);
//clock_gettime(CLOCK_MONOTONIC, &stopGEMM);
//accumGEMM = (TimeSpecToSeconds(&stopGEMM)- TimeSpecToSeconds(&startGEMM));
//printf("All(5) GEMMs (%e)s GFLOPs=%e \n", accumGEMM, 5*(2/1.0e9)*m*n*p/accumGEMM);
DataType* SASB = ( DataType*)ALLOCATOR( m*p,sizeof(DataType), 64 );
DataType* NSAB = ( DataType*)ALLOCATOR( m*p,sizeof(DataType), 64 ); //ceb
DataType* SASA = ( DataType*)ALLOCATOR( m*p,sizeof(DataType), 64 );
DataType* NSAA = ( DataType*)ALLOCATOR( m*p,sizeof(DataType), 64 ); //ceb
DataType* SBSB = ( DataType*)ALLOCATOR( m*p,sizeof(DataType), 64 );
DataType* NSBB = ( DataType*)ALLOCATOR( m*p,sizeof(DataType), 64 ); //ceb
DataType* DENOM = ( DataType*)ALLOCATOR( m*p,sizeof(DataType), 64 );
DataType* DENOMSqrt =( DataType*)ALLOCATOR( m*p,sizeof(DataType), 64 );
//Compute and assemble composite terms
//SASB=SA*SB
if (!sameAB) {
VMUL(m*p,SA,SB,SASB);
} else {
vMulSameAB(m,p,SA,SB,SASB);
}
//NSAB=N*SAB
VMUL(m*p,N,SAB,NSAB); //ceb
//NSAB=(-1)NSAB+SASB (numerator)
AXPY(m*p,(DataType)(-1), SASB,1, NSAB,1); //ceb
//(SA)^2
VSQR(m*p,SA,SASA);
//N(SAA)
VMUL(m*p,N,SAA,NSAA); //ceb
//NSAA=NSAA-SASA (denominator term 1)
AXPY(m*p,(DataType)(-1), SASA,1, NSAA,1);
//(SB)^2
if (!sameAB) {
VSQR(m*p,SB,SBSB);
} else {
#pragma omp parallel for private(i, j)
for(int i = 0; i < m; i++) {
for(int j = 0; j < p; j++) {
SBSB[i*m + j] = SB[j*m + i] * SB[j*m + i];
}
}
}
//N(SBB)
if (!sameAB) {
VMUL(m*p,N,SBB,NSBB);
} else {
vMulSameAB(m, p, N, SBB, NSBB);
}
//NSBB=NSBB-SBSB (denominatr term 2)
AXPY(m*p,(DataType)(-1), SBSB,1, NSBB,1);
//DENOM=NSAA*NSBB (element wise multiplication)
VMUL(m*p,NSAA,NSBB,DENOM);
#pragma omp parallel for private (i)
for (int i = 0;i < m*p;++i) {
if(DENOM[i]==0.){DENOM[i]=1;}//numerator will be 0 so to prevent inf, set denom to 1
}
//sqrt(DENOM)
VSQRT(m*p,DENOM,DENOMSqrt);
//P=NSAB/DENOMSqrt (element wise division)
VDIV(m*p,NSAB,DENOMSqrt,P);
FREE(SASB);
FREE(NSAB);
FREE(SASA);
FREE(NSAA);
FREE(SBSB);
FREE(NSBB);
FREE(DENOM);
FREE(DENOMSqrt);
}
FREE(N);
FREE(SA);
FREE(SAA);
if (!sameAB) { //only do it when A and B are not same
FREE(SB);
FREE(SBB);
}
FREE(SAB);
return 0;
};
#endif
#ifndef NOMKL
#ifdef PCC_VECTOR
//This function uses bit arithmetic to mask vectors prior to performing a number of FMA's
//The intention is to improve upon the matrix x matrix missing data PCC algorithm by reducing uneccessary computations
// and maximizing the use of vector register arithmetic.
//A is matrix of X vectors and B is transposed matrix of Y vectors:
//P = [ N*sum(AB) - (sumA)(sumB)] /
// sqrt[ (N sumA^2 -(sum A)^2)[ ( N sumB^2 - (sum B)^2) ]
//P = (N*SAB - SA*SB)/Sqrt( (N*SAA - (SA)^2) * (N*SBB - (SB)^2) )
int pcc_vector(int m, int n, int p,
DataType* A, DataType* B, DataType* P)
{
int i,j,k;
int stride = ((n-1)/64 +1);
DataType alpha=1.0;
DataType beta=0.0;
int count =1;
bool transposeB = true; //assume this is always true.
//we need to compute terms using FMA and masking and then assemble terms to
// construct the PCC value for each row column pair
unsigned long zeros = 0;
unsigned long ones = ~0; //bitwise complement of 0 is all 1's (maxint)
//We wamt to perform operations on vectors of float or double precision values.
//By constructing a mask in the form of a vector of floats or doubles, in which
// the values we want to keep are masked by a number which translates to a 111..1 (i.e. maxint for 32 or 64 bit values),
// and the values we want to ignore are masked by a 000..0 bit string, we can simply apply a bitwise AND
// to get a resultant vector on which we can perform an FMA operation
//We also want to use this bitmask to compute a sum of non-missing data for each row-column pair
//We can create a bitmask for both A and B matrices by doing the following:
// Initialize an Amask and Bmask matrix to all 1 bit strings. While reading A or B,
// where there is a Nan bit string in A or B, place a 0 bit string in the corresponding mask matrix
//To compute the various terms, eg, sum of A, for i=1..m, j=1..p, SA[i,j] = Sum_k(A[i] & Bmask[j])
// reduce (sum) operation will have to be hand coded via openMP parallel reduce with pragma simd inside loop
// horizontal_add returns sum of components of vector but is not efficient. Breaks SIMD ideal
//How to create Amask and Bmask
//In the process of creating masks for A and B we can either replace Nans with 0 as we go in A and B, or we can then apply the masks to
// to the matrices after we compute them.
// We can create a matrix mask starting with a mask matrix containing all maxint bit strings except where A has missing data in which case the mask will contain a zero.
// We can set these mask values to zero in the appropriate locations by traversing A or B and applying the isnan function in an if statement.
// If false, then set Amask or Bmask respectively to ones at that location (masks initialized to zeros)
// (there may be a more efficent way to do this)
DataType* Amask = ( DataType*)ALLOCATOR( m*n, sizeof(DataType), 64 );
__assume_aligned(Amask, 64);
for(i=0; i<m*n; ++i){
if(isnan(A[i])){ A[i]=0;}
else{Amask[i]=ones;}
}
DataType* Bmask = ( DataType*)ALLOCATOR( n*p, sizeof(DataType), 64 );
__assume_aligned(Bmask, 64);
for(i=0; i<p*n; ++i){
if(isnan(B[i])){ B[i]=0;}
else{Bmask[i]=ones;}
}
//The masks can then be used by employing a bitwise (AND) &, between the elements of the mask and the elements of the matrix or vector we want to mask.
// The elements masked with a zero bit string will return a zero, the elements masked with the 1 bit string will return the original element.
//How to compute N?
// N[i,j] contains the number of valid pairs (no Nan's) of elements when comparing rows A[i] and B[j].
// If we apply a bitwise (AND) & to compare rows A[i] and B[j] the result will be a bit vector of 1's for all element
// comparisons that don't include Nan's and zero's elsewhere. To sum up the valid element pairs, we could simply loop over the
// resulting vector and count up the maxints.
//(There may be a faster way to sum values for N using bit ops)
//N contains the number of elements used in each row column PCC calculation (after missing values are removed)
DataType *N = (DataType *) ALLOCATOR( m*p,sizeof( DataType ), 64 );
__assume_aligned(N, 64);
for(i=0; i<m; ++i){
for(j=0; j<p; ++j){
for(k=0; k<n; ++k){
//if( (Amask[i*n+k] & Bmask[j*n+k]) > 0 ){ N[i*p+j]++; }
unsigned long* A_bitstring = reinterpret_cast<unsigned long* >(&(Amask[i*n+k]));
unsigned long* B_bitstring = reinterpret_cast<unsigned long* >(&(Bmask[j*n+k]));
unsigned long C_bitstring = *A_bitstring & *B_bitstring;
if( C_bitstring > 0){ N[i*p+j]++;}
}
}
}
//After computing masks and N, we want to replace Nan's in A and B with 0.
// We can do this by masking A with Amask and B with Bmask
//AA and BB can be computed simply by multiplying vector A[i] by vector A[i] and store in AA[i] via FMA, after A and B have had mask applied
DataType tmp;
//SAB may best be done by a GEMM operation, though the symmetric portion of the computation can be reduced by
// eliminating the lower triangular redundancy.
DataType* SAB = ( DataType*)ALLOCATOR( m*p, sizeof(DataType), 64 );
__assume_aligned(SAB, 64);
//#pragma omp parallel for reduction (+:sum)
for(i=0; i<m; ++i){
//for(j=i; j<p; ++j){//upper triangular computations only. Assuming p>=m
//for(j=; j<p; ++j){//upper triangular computations only. Assuming p>=m
for(j=0; j<p; ++j){
//#pragma SIMD
for(k=0;k<n;++k){
SAB[i*n+j] += A[i*n+k]*B[j*n+k];
}
}
}
DataType* SA = ( DataType*)ALLOCATOR( m*p, sizeof(DataType), 64 );
__assume_aligned(SA, 64);
//#pragma omp parallel for reduction (+:sum)
for(i=0; i<m; ++i){
for(j=0; j<p; ++j){
//#pragma SIMD
for(k=0;k<n;++k){
//tmp=(A[i*n+k] & Bmask[j*n+k]);
unsigned long* A_bitstring = reinterpret_cast<unsigned long* >(&(A[i*n+k]));
unsigned long* B_bitstring = reinterpret_cast<unsigned long* >(&(Bmask[j*n+k]));
unsigned long C_bitstring = *A_bitstring & *B_bitstring;
SA[i*n+j] += reinterpret_cast<DataType >(C_bitstring);
}
}
}
DataType* SB = ( DataType*)ALLOCATOR( m*p, sizeof(DataType), 64 );
__assume_aligned(SB, 64);
//#pragma omp parallel for reduction (+:sum)
for(j=0; j<p; ++j){
for(i=0; i<m; ++i){
//#pragma SIMD
for(k=0;k<n;++k){
//tmp=(B[j*n+k] & Amask[i*n+k]);
unsigned long* A_bitstring = reinterpret_cast<unsigned long* >(&(Amask[i*n+k]));
unsigned long* B_bitstring = reinterpret_cast<unsigned long* >(&(B[j*n+k]));
unsigned long C_bitstring = *A_bitstring & *B_bitstring;
SB[j*n+k] += reinterpret_cast<DataType >(C_bitstring);
}
}
}
DataType* SAA = ( DataType*)ALLOCATOR( m*p, sizeof(DataType), 64 );
__assume_aligned(SAA, 64);
//#pragma omp parallel for reduction (+:sum)
for(i=0; i<m; ++i){
for(j=0; j<p; ++j){
//#pragma SIMD
for(k=0;k<n;++k){
//tmp=(A[i*n+k] & Bmask[j*n+k]);
unsigned long* A_bitstring = reinterpret_cast<unsigned long* >(&(Amask[i*n+k]));
unsigned long* B_bitstring = reinterpret_cast<unsigned long* >(&(B[j*n+k]));
unsigned long C_bitstring = *A_bitstring & *B_bitstring;
tmp=reinterpret_cast<DataType >(C_bitstring);
SAA[i*n+j] += tmp*tmp;
}
}
}
DataType* SBB = ( DataType*)ALLOCATOR( m*p, sizeof(DataType), 64 );
__assume_aligned(SBB, 64);
//#pragma omp parallel for reduction (+:sum)
for(j=0; j<p; ++j){
for(i=0; i<m; ++i){
//#pragma SIMD
for(k=0;k<n;++k){
//tmp=(B[j*n+k] & Amask[i*n+k]);
unsigned long* A_bitstring = reinterpret_cast<unsigned long* >(&(Amask[i*n+k]));
unsigned long* B_bitstring = reinterpret_cast<unsigned long* >(&(B[j*n+k]));
unsigned long C_bitstring = *A_bitstring & *B_bitstring;
SBB[j*n+i] += reinterpret_cast<DataType >(C_bitstring);;
}
}
}
//allocate and initialize and align memory needed to compute PCC
//variables used for performance timing
struct timespec startGEMM, stopGEMM;
double accumGEMM;
//info("before PCC terms\n",1);
//Compute PCC terms and assemble
CBLAS_TRANSPOSE transB=CblasNoTrans;
int ldb=p;
if(transposeB){
transB=CblasTrans;
ldb=n;
}
clock_gettime(CLOCK_MONOTONIC, &startGEMM);
FREE(UnitA);
FREE(UnitB);
clock_gettime(CLOCK_MONOTONIC, &stopGEMM);
accumGEMM = (TimeSpecToSeconds(&stopGEMM)- TimeSpecToSeconds(&startGEMM));
//printf("All(5) GEMMs (%e)s GFLOPs=%e \n", accumGEMM, 5*(2/1.0e9)*m*n*p/accumGEMM);
DataType* SASB = ( DataType*)ALLOCATOR( m*p,sizeof(DataType), 64 );
DataType* NSAB = ( DataType*)ALLOCATOR( m*p,sizeof(DataType), 64 ); //ceb
DataType* SASA = ( DataType*)ALLOCATOR( m*p,sizeof(DataType), 64 );
DataType* NSAA = ( DataType*)ALLOCATOR( m*p,sizeof(DataType), 64 ); //ceb
DataType* SBSB = ( DataType*)ALLOCATOR( m*p,sizeof(DataType), 64 );
DataType* NSBB = ( DataType*)ALLOCATOR( m*p,sizeof(DataType), 64 ); //ceb
DataType* DENOM = ( DataType*)ALLOCATOR( m*p,sizeof(DataType), 64 );
DataType* DENOMSqrt =( DataType*)ALLOCATOR( m*p,sizeof(DataType), 64 );
//Compute and assemble composite terms
//SASB=SA*SB
VMUL(m*p,SA,SB,SASB);
//N*SAB
VMUL(m*p,N,SAB,NSAB); //ceb
//SAB=(-1)SASB+NSAB (numerator)
AXPY(m*p,(DataType)(-1), SASB,1, NSAB,1); //ceb
//(SA)^2
//vsSqr(m*p,SA,SASA);
VSQR(m*p,SA,SASA);
//N(SAA)
VMUL(m*p,N,SAA,NSAA); //ceb
//SAA=NSAA-SASA (denominator term 1)
AXPY(m*p,(DataType)(-1), SASA,1, NSAA,1);
//(SB)^2
//vsSqr(m*p,SB,SBSB);
VSQR(m*p,SB,SBSB);
//N(SBB)
VMUL(m*p,N,SBB,NSBB);
//SBB=NSBB-SBSB
AXPY(m*p,(DataType)(-1), SBSB,1, NSBB,1);
//DENOM=NSAA*NSBB (element wise multiplication)
VMUL(m*p,NSAA,NSBB,DENOM);
for(int i=0;i<m*p;++i){
if(DENOM[i]==0.){DENOM[i]=1;}//numerator will be 0 so to prevent inf, set denom to 1
}
//sqrt(DENOM)
VSQRT(m*p,DENOM,DENOMSqrt);
//P=SAB/DENOMSqrt (element wise division)
VDIV(m*p,SAB,DENOMSqrt,P);
FREE(SASA);
FREE(SASB);
FREE(SBSB);
FREE(NSAB);
FREE(NSAA);
FREE(NSBB);
FREE(DENOM);
FREE(DENOMSqrt);
}
FREE(N);
FREE(SA);
FREE(SAA);
FREE(SB);
FREE(SBB);
FREE(SAB);
return 0;
};
#endif
#endif
#ifndef USING_R
int main (int argc, char **argv) {
//ceb testing with various square matrix sizes
//16384 = 1024*16
//32768 = 2048*16
//40960 = 2560*16 too large (for skylake)
//set default values
int m=64;//16*1500;//24000^3 for peak performance on skylake
int n=16;
int p=32;
int count=1;
int seed =1;
char* matA_filename;//="matA.dat";
char* matB_filename;//="matB.dat";
if(argc>1){ matA_filename = argv[1]; }
if(argc>2){ matB_filename = argv[2]; }
struct timespec startPCC,stopPCC;
// A is n x p (tall and skinny) row major order
// B is p x m (short and fat) row major order
// R is n x m (big and square) row major order
DataType* A;
DataType* B;
DataType* R;
DataType* diff;
DataType* C;
DataType accumR;
bool transposeB=false;
initialize(m, n, p, seed, &A, &B, &R, matA_filename, matB_filename, transposeB);
//C = (DataType *)ALLOCATOR( m*p,sizeof( DataType ), 64 );
clock_gettime(CLOCK_MONOTONIC, &startPCC);
#if NAIVE
printf("naive PCC implmentation\n");
pcc_naive(m, n, p, A, B, R);
#else
printf("matrix PCC implmentation\n");
pcc_matrix(m, n, p, A, B, R);
//pcc_vector(m, n, p, A, B, R);
#endif
clock_gettime(CLOCK_MONOTONIC, &stopPCC);
accumR = (TimeSpecToSeconds(&stopPCC)- TimeSpecToSeconds(&startPCC));
#if 0
//read in results file for comparison
fstream test_file;
//test_file.open("results_6k_x_29k_values.txt",ios::in);
test_file.open("6kvs28k.txt",ios::in);
//test_file.open("flat.txt",ios::in);
if(test_file.is_open()){
float tmp;
// if found then read
int dim1,dim2;
test_file >> tmp;
dim1 = tmp;
test_file >> tmp;
dim2 = tmp;
printf("dim1=%d dim2=%d dim1*dim2=%d\n",dim1,dim2,dim1*dim2);
C = (DataType *)ALLOCATOR( dim1*dim2,sizeof( DataType ), 64 );
for(int i=0;i<dim1*dim2;++i) test_file >> C[i];
test_file.close();
}
#endif
#if 0
//write R matrix to file
fstream mat_R_file;
mat_R_file.open("MPCC_computed.txt",ios::out);
mat_R_file << m << '\n';
mat_R_file << p << '\n';
for(int i=0;i<m*p;++i) mat_R_file << R[i] << '\n';
mat_R_file.close();
#endif
DataType R_2norm = 0.0;
DataType C_2norm = 0.0;
DataType diff_2norm = 0.0;
DataType relativeNorm = 0.0;
#if 0
for (int i=0; i<m*p; i++) { C_2norm += C[i]*C[i]; }
C_2norm=sqrt(C_2norm);
for (int i=0; i<m*p; i++) { R_2norm += R[i]*R[i]; }
R_2norm=sqrt(R_2norm);
diff = (DataType *)ALLOCATOR( m*p,sizeof( DataType ), 64 );
for (int i=0; i<m*p; i++) {
diff[i]=pow(C[i]-R[i],2);
diff_2norm += diff[i];
}
diff_2norm = sqrt(diff_2norm);
relativeNorm = diff_2norm/R_2norm;
printf("R_2Norm=%e, C_2Norm=%e, diff_2norm=%e relativeNorm=%e\n", R_2norm, C_2norm, diff_2norm, relativeNorm);
printf("relative diff_2Norm = %e in %e s m=%d n=%d p=%d GFLOPs=%e \n", relativeNorm, accumR, m,n,p, (5*2/1.0e9)*m*n*p/accumR);
#endif
#if 0
//write R matrix to file
fstream diff_file;
diff_file.open("diff.txt",ios::out);
diff_file << m << '\n';
diff_file << p << '\n';
for(int i=0;i<m*p;++i) diff_file << R[i] << " " << C[i] << " " <<diff[i] << '\n';
diff_file.close();
#endif
printf("completed in %e seconds, size: m=%d n=%d p=%d GFLOPs=%e \n",accumR, m,n,p, (5*2/1.0e9)*m*n*p/accumR);
return 0;
}
#endif
| true |
370b908e661be38f38698780c006187adb5abdcf | C++ | Douraid-BEN-HASSEN/BTS | /CTraitementImage/CTraitementImage.cpp | UTF-8 | 642 | 2.921875 | 3 | [] | no_license | // CTraitementImage.cpp : Définit le point d'entrée pour l'application console.
//
#include "CTraitements.h"
int main()
{
Mat image;
image = imread("Image9Balles.png", IMREAD_COLOR);
if (image.empty())
{
cout << "Impossible de trouver l'image" << endl;
}
Mat image_base = image.clone();
CTraitements traitement;
traitement.Binarisation(image,150);
Mat img_ero = image.clone();
traitement.Erosion(img_ero);
waitKey(0);
traitement.VisualiserImage(image_base);
waitKey(0);
traitement.VisualiserImage(image);
waitKey(0);
traitement.VisualiserImage(img_ero);
waitKey(0);
return 0;
}
| true |
1b19f3d63ee05fd4c4f6c1e746316d506b8b79a2 | C++ | dhillonsh/cis431-project | /conv_layer.cpp | UTF-8 | 2,859 | 3.296875 | 3 | [] | no_license | #include <iostream>
#include <vector>
double calculate_block(std::vector<std::vector<std::vector<int>>> input, std::vector<std::vector<double>> filter, int row, int col, int stride) {
int i, j;
int input_row_start = row + stride - 1;
int input_row_end = input_row_start + filter.size();
int input_col_start = col + stride - 1;
int input_col_end = input_col_start + filter[0].size();
double value = 0.0;
for(i = input_row_start; i < input_row_end; i++) {
for(j = input_col_start; j < input_col_end; j++) {
value += ((double)filter[i - input_row_start][j - input_col_start] * (double)input[0][i][j]);
}
}
return value;
}
std::vector<std::vector<double>> conv_layer(std::vector<std::vector<std::vector<int>>> input, std::vector<std::vector<double>> filter, int stride) {
double i, j, k;
int filter_width = filter.size();
int filter_height = filter[0].size();
int input_width = input[0].size();
int input_height = input[0][0].size();
int output_matrix_width = input_width - filter_width + 1;
int output_matrix_height = input_height - filter_height + 1;
std::vector<std::vector<double>> output(output_matrix_width, std::vector<double>(output_matrix_height));
for(i = 0; i < output_matrix_width; i++) {
for(j = 0; j < output_matrix_height; j++) {
output[i][j] = calculate_block(input, filter, i, j, stride);
}
}
return output;
}
void print_output(std::vector<std::vector<double>> output) {
double i, j;
for(i = 0; i < output.size(); i++) {
for(j = 0; j < output[0].size(); j++) {
printf("[%f][%f]: %f\n", i, j, output[i][j]);
}
}
}
int main() {
std::vector<std::vector<std::vector<int>>> test_data =
{
{
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3},
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3},
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3},
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3},
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3},
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3},
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3},
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3},
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3},
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3},
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3},
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3},
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3},
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3},
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3},
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3}
}
};
std::vector<std::vector<double>> filter =
{
{1, 2, 1},
{1, 2, 1},
{1, 2, 1},
};
int stride = 1;
std::vector<std::vector<double>> test_output = conv_layer(test_data, filter, stride);
print_output(test_output);
return 0;
} | true |
3113e9bd5cd749b0f8dd70575c29dfc649218222 | C++ | kyle45/easy_threadpool | /task.h | UTF-8 | 225 | 2.546875 | 3 | [] | no_license | #ifndef TASK_H_
#define TASK_H_
class Task
{
public:
Task(void* _arg):arg(_arg){};
virtual ~Task(){}
virtual void* func(void *) = 0; //interface
void run(){func(arg);};
protected:
void* arg; // parameter
};
#endif
| true |
e50e16f216f82b45328cbaaa2a33a917057c7e6e | C++ | mkuric/SeismicDemo | /geolib/csFlexHeader.cc | UTF-8 | 12,113 | 2.984375 | 3 | [] | no_license |
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include "csFlexHeader.h"
#include "csException.h"
using namespace cseis_geolib;
const int csFlexHeader::MIN_BYTE_SIZE = 8;
csFlexHeader::csFlexHeader() {
init();
myByteSize = MIN_BYTE_SIZE;
myValue = new char[myByteSize];
myType = TYPE_INT;
}
void csFlexHeader::init() {
myValue = NULL;
myByteSize = 0;
}
void csFlexHeader::init( int byteSize ) {
myByteSize = byteSize;
myValue = new char[myByteSize];
}
csFlexHeader::csFlexHeader( cseis_geolib::type_t type, std::string value ) {
myByteSize = MIN_BYTE_SIZE;
myValue = new char[myByteSize];
myType = type;
setValueFromString( type, value );
}
csFlexHeader::csFlexHeader( csFlexHeader const& obj ) {
init( obj.myByteSize );
myType = obj.myType;
memcpy( myValue, obj.myValue, myByteSize );
}
csFlexHeader::csFlexHeader( double d ) {
init( MIN_BYTE_SIZE );
// fprintf(stdout,"Constructor double %x %f\n", myValue, d);
myType = TYPE_DOUBLE;
*((double*)myValue) = d;
}
csFlexHeader::csFlexHeader( float f ) {
init( MIN_BYTE_SIZE );
// fprintf(stdout,"Constructor float %x %f\n", myValue, f);
myType = TYPE_FLOAT;
*((float*)myValue) = f;
}
csFlexHeader::csFlexHeader( int i ) {
init( MIN_BYTE_SIZE );
// fprintf(stdout,"Constructor int %x %d\n", myValue, i );
myType = TYPE_INT;
*((int*)myValue) = i;
}
csFlexHeader::csFlexHeader( char c ) {
init( MIN_BYTE_SIZE );
// fprintf(stdout,"Constructor int %x %d\n", myValue, i );
myType = TYPE_CHAR;
myValue[0] = c;
myValue[1] = '\0';
}
csFlexHeader::csFlexHeader( csInt64_t i ) {
init( MIN_BYTE_SIZE );
myType = TYPE_INT64;
*((csInt64_t*)myValue) = i;
}
csFlexHeader::csFlexHeader( std::string& value ) {
// fprintf(stdout,"Constructor int %x %d\n", myValue, i );
int newByteSize = value.length()+1;
init( std::max( newByteSize, MIN_BYTE_SIZE ) );
myType = TYPE_STRING;
memcpy( myValue, value.c_str(), newByteSize-1 );
myValue[newByteSize-1] = '\0';
}
csFlexHeader::~csFlexHeader() {
// fprintf(stdout,"Destructor %x\n", myValue);
myType = TYPE_UNKNOWN;
if( myValue ) {
delete [] myValue;
myValue = NULL;
}
myByteSize = 0;
}
//-------------------------------------------------------------
int csFlexHeader::stringSize() {
if( myType != TYPE_STRING ) {
return 0;
}
else {
return strlen(myValue);
}
}
//-------------------------------------------------------------
void csFlexHeader::setValueFromString( cseis_geolib::type_t type, std::string value ) {
if( type == TYPE_INT ) {
setIntValue( atoi(value.c_str()) );
}
else if( type == TYPE_FLOAT ) {
setFloatValue( atof(value.c_str()) );
}
else if( type == TYPE_DOUBLE ) {
setDoubleValue( atof(value.c_str()) );
}
else if( type == TYPE_INT64 ) {
setInt64Value( atoi(value.c_str()) );
}
else if( type == TYPE_STRING ) {
setStringValue( value );
}
else if( type == TYPE_CHAR ) {
setCharValue( value[0] );
}
else {
throw( csException("csFlexHeader::setValueFromString: Unknown data type...") );
}
}
//-------------------------------------------------------------
csFlexHeader& csFlexHeader::operator=( const csFlexHeader& obj ) {
// fprintf(stdout,"Operator= %x\n", myValue );
if( obj.myType == TYPE_STRING && obj.myByteSize > myByteSize ) {
freeMemory();
myByteSize = obj.myByteSize;
myValue = new char[myByteSize];
}
myType = obj.myType;
memcpy( myValue, obj.myValue, obj.myByteSize );
return *this;
}
csFlexHeader& csFlexHeader::operator=( int i ) {
// fprintf(stdout,"Operator=(int) %x\n", myValue );
setIntValue( i );
return *this;
}
csFlexHeader& csFlexHeader::operator=( csInt64_t i ) {
// fprintf(stdout,"Operator=(int) %x\n", myValue );
setInt64Value( i );
return *this;
}
csFlexHeader& csFlexHeader::operator=( char c ) {
// fprintf(stdout,"Operator=(int) %x\n", myValue );
setCharValue( c );
return *this;
}
csFlexHeader& csFlexHeader::operator=( double d ) {
// fprintf(stdout,"Operator=(double) %x\n", myValue );
setDoubleValue( d );
return *this;
}
csFlexHeader& csFlexHeader::operator=( std::string& text ) {
setStringValue( text );
return *this;
}
//---------------------------------------------------------------------
//
bool csFlexHeader::operator==( const csFlexHeader& obj ) const {
switch( myType ) {
case TYPE_DOUBLE:
if( obj.myType != TYPE_STRING ) {
return( doubleValue_internal() == obj.doubleValue() );
}
break;
case TYPE_FLOAT:
if( obj.myType == TYPE_DOUBLE ) {
return( (double)floatValue_internal() == obj.doubleValue_internal() );
}
else if( obj.myType == TYPE_INT || obj.myType == TYPE_FLOAT ) {
return( floatValue_internal() == obj.floatValue() );
}
break;
case TYPE_INT:
if( obj.myType == TYPE_DOUBLE ) {
return( (double)intValue_internal() == obj.doubleValue_internal() );
}
else if( obj.myType == TYPE_FLOAT ) {
return( (float)intValue_internal() == obj.floatValue_internal() );
}
else if( obj.myType == TYPE_INT ) {
return( intValue_internal() == obj.intValue() );
}
break;
case TYPE_STRING:
if( obj.myType == TYPE_STRING ) {
return( !strcmp( myValue, obj.myValue) );
}
break;
}
return false;
}
//---------------------------------------------------------------------
bool csFlexHeader::operator!=( const csFlexHeader& obj ) const {
switch( myType ) {
case TYPE_DOUBLE:
return( doubleValue_internal() != obj.doubleValue() );
case TYPE_FLOAT:
if( obj.myType == TYPE_DOUBLE ) {
return( (double)floatValue_internal() != obj.doubleValue_internal() );
}
else {
return( floatValue_internal() != obj.floatValue() );
}
case TYPE_INT:
if( obj.myType == TYPE_DOUBLE ) {
return( (double)intValue_internal() != obj.doubleValue_internal() );
}
else if( obj.myType == TYPE_FLOAT ) {
return( (float)intValue_internal() != obj.floatValue_internal() );
}
else {
return( intValue_internal() != obj.intValue() );
}
case TYPE_STRING:
if( obj.myType == TYPE_STRING ) {
return( strcmp( myValue, obj.myValue) );
}
break;
}
return false;
}
//---------------------------------------------------------------------
bool csFlexHeader::operator>( const csFlexHeader& obj ) const {
switch( myType ) {
case TYPE_DOUBLE:
return( doubleValue_internal() > obj.doubleValue() );
case TYPE_FLOAT:
if( obj.myType == TYPE_DOUBLE ) {
return( (double)floatValue_internal() > obj.doubleValue_internal() );
}
else {
return( floatValue_internal() > obj.floatValue() );
}
case TYPE_INT:
if( obj.myType == TYPE_DOUBLE ) {
return( (double)intValue_internal() > obj.doubleValue_internal() );
}
else if( obj.myType == TYPE_FLOAT ) {
return( (float)intValue_internal() > obj.floatValue_internal() );
}
else {
return( intValue_internal() > obj.intValue() );
}
case TYPE_STRING:
if( obj.myType == TYPE_STRING ) {
return( strcmp( myValue, obj.myValue) > 0 );
}
break;
}
return false;
}
//---------------------------------------------------------------------
bool csFlexHeader::operator<( const csFlexHeader& obj ) const {
switch( myType ) {
case TYPE_DOUBLE:
return( doubleValue_internal() < obj.doubleValue() );
case TYPE_FLOAT:
if( obj.myType == TYPE_DOUBLE ) {
return( (double)floatValue_internal() < obj.doubleValue_internal() );
}
else {
return( floatValue_internal() < obj.floatValue() );
}
case TYPE_INT:
if( obj.myType == TYPE_DOUBLE ) {
return( (double)intValue_internal() < obj.doubleValue_internal() );
}
else if( obj.myType == TYPE_FLOAT ) {
return( (float)intValue_internal() < obj.floatValue_internal() );
}
else {
return( intValue_internal() < obj.intValue() );
}
case TYPE_STRING:
if( obj.myType == TYPE_STRING ) {
return( strcmp( myValue, obj.myValue) < 0 );
}
break;
}
return false;
}
//---------------------------------------------------------------------
bool csFlexHeader::operator<=( const csFlexHeader& obj ) const {
switch( myType ) {
case TYPE_DOUBLE:
return( doubleValue_internal() <= obj.doubleValue() );
case TYPE_FLOAT:
if( obj.myType == TYPE_DOUBLE ) {
return( (double)floatValue_internal() <= obj.doubleValue_internal() );
}
else {
return( floatValue_internal() <= obj.floatValue() );
}
case TYPE_INT:
if( obj.myType == TYPE_DOUBLE ) {
return( (double)intValue_internal() <= obj.doubleValue_internal() );
}
else if( obj.myType == TYPE_FLOAT ) {
return( (float)intValue_internal() <= obj.floatValue_internal() );
}
else {
return( intValue_internal() <= obj.intValue() );
}
case TYPE_STRING:
if( obj.myType == TYPE_STRING ) {
return( strcmp( myValue, obj.myValue) <= 0 );
}
break;
}
return false;
}
//---------------------------------------------------------------------
bool csFlexHeader::operator>=( const csFlexHeader& obj ) const {
switch( myType ) {
case TYPE_DOUBLE:
return( doubleValue_internal() >= obj.doubleValue() );
case TYPE_FLOAT:
if( obj.myType == TYPE_DOUBLE ) {
return( (double)floatValue_internal() >= obj.doubleValue_internal() );
}
else {
return( floatValue_internal() >= obj.floatValue() );
}
case TYPE_INT:
if( obj.myType == TYPE_DOUBLE ) {
return( (double)intValue_internal() >= obj.doubleValue_internal() );
}
else if( obj.myType == TYPE_FLOAT ) {
return( (float)intValue_internal() >= obj.floatValue_internal() );
}
else {
return( intValue_internal() >= obj.intValue() );
}
case TYPE_STRING:
if( obj.myType == TYPE_STRING ) {
return( strcmp( myValue, obj.myValue) >= 0 );
}
break;
}
return false;
}
/*
bool csFlexNumber::operator>( const csFlexNumber& obj ) const {
switch( myType ) {
case TYPE_DOUBLE:
return( doubleValue_internal() > obj.doubleValue() );
case TYPE_FLOAT:
if( obj.myType == TYPE_DOUBLE ) {
return( (double)floatValue_internal() > obj.doubleValue_internal() );
}
else {
return( floatValue_internal() > obj.floatValue() );
}
case TYPE_INT:
if( obj.myType == TYPE_DOUBLE ) {
return( (double)intValue_internal() > obj.doubleValue_internal() );
}
else if( obj.myType == TYPE_FLOAT ) {
return( (float)intValue_internal() > obj.floatValue_internal() );
}
else {
return( intValue_internal() > obj.intValue() );
}
}
return false;
}
*/
//---------------------------------------------------------------------
//
void csFlexHeader::dump() const {
fprintf(stdout," Type: %2d: ", myType );
if( myType == TYPE_INT ) {
fprintf(stdout," valueInt: %d\n", *((int*)myValue) );
}
else if( myType == TYPE_FLOAT ) {
fprintf(stdout," valueFloat: %f\n", *((float*)myValue) );
}
else if( myType == TYPE_DOUBLE ) {
fprintf(stdout," valueDouble: %f\n", *((double*)myValue) );
}
else if( myType == TYPE_INT64 ) {
fprintf(stdout," valueInt64: %lld\n", *((csInt64_t*)myValue) );
}
else if( myType == TYPE_CHAR ) {
fprintf(stdout," valueChar: '%c'\n", myValue[0] );
}
else { // if( myType == TYPE_STRING ) {
fprintf(stdout," valueString: '%s'\n", myValue);
}
}
std::string csFlexHeader::toString() const {
if( myType == TYPE_STRING || myType == TYPE_CHAR ) {
std::string text2 = myValue;
return text2;
}
char text[80];
if( myType == TYPE_INT ) {
sprintf(text,"%d", *((int*)myValue) );
}
else if( myType == TYPE_FLOAT ) {
sprintf(text,"%f", *((float*)myValue) );
}
else if( myType == TYPE_DOUBLE ) {
sprintf(text,"%f", *((double*)myValue) );
}
else if( myType == TYPE_INT64 ) {
sprintf(text,"%lld", *((csInt64_t*)myValue) );
}
else { //
sprintf(text," ???");
}
return text;
}
| true |
687ea8d51b6f040cb5c96a8c2ec125c48585e246 | C++ | DmitrySyr/diff_tasks | /otus_task_12/thread_wrapper.h | UTF-8 | 676 | 3.34375 | 3 | [] | no_license | #ifndef TH_WRAPPER_H_INCLUDED
#define TH_WRAPPER_H_INCLUDED
#include <thread>
class thread_wrapper{
std::thread this_thread{};
public:
thread_wrapper() = delete;
thread_wrapper( const thread_wrapper& ) = delete;
thread_wrapper( thread_wrapper&& old_thread )
{
if( this != &old_thread )
{
this->this_thread = std::move( old_thread.this_thread );
}
}
thread_wrapper( std::thread && new_thread ) :
this_thread( std::move( new_thread ) ) {}
~thread_wrapper()
{
if( this_thread.joinable() )
{
this_thread.join();
}
}
};
#endif // TH_WRAPPER_H_INCLUDED
| true |
e3e9873e414c6dd2f5fb5dc7bb0695c99704e671 | C++ | Sopel97/conference_db_gen | /conference_database_gen/src/ConferenceDatabase/Tables/Country.cpp | UTF-8 | 438 | 2.5625 | 3 | [] | no_license | #include "ConferenceDatabase/Tables/Country.h"
#include "Csv/CsvRecord.h"
Country::PrimaryKeyType Country::primaryKey() const
{
return m_countryId;
}
Record::IdType Country::countryId() const
{
return m_countryId;
}
const std::string& Country::countryName() const
{
return m_countryName;
}
CsvRecord Country::toCsvRecord() const
{
return CsvRecord(
std::to_string(m_countryId),
m_countryName
);
}
| true |
d415dc05e5419bcf30d2d7274c8959d8448d9b08 | C++ | wangjunjie1107/CodeTesting | /C++/96_黑马_类模板做函数参数.cpp | GB18030 | 1,104 | 3.5625 | 4 | [] | no_license | #define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string>
using namespace std;
//ģ ҲʹĬϲ
template<class T1, class T2>
class Person
{
public:
Person(T1 name, T2 age)
{
this->m_Age = age;
this->m_Name = name;
}
void showPerson()
{
cout << ": " << this->m_Name << " 䣺 " << this->m_Age << endl;
}
T1 m_Name;
T2 m_Age;
};
//1ָ
void doWork1(Person<string, int> & p1)
{
p1.showPerson();
}
void test01()
{
Person<string, int>p1("wangjunjie", 18);
doWork1(p1);
}
//2ģ廯
template<class T1,class T2>
void doWork2(Person<T1, T2> & p2)
{
p2.showPerson();
}
void test02()
{
Person<string, int>p2("wangjunjie", 18);
doWork1(p2);
}
//2ģ廯
template<class T>
void doWork3(T & p3)
{
p3.showPerson();
}
void test03()
{
Person<string, int>p3("wangjunjie", 18);
doWork3(p3);
}
int main()
{
cout << "ָ" << endl;
test01();
cout << "ģ廯" << endl;
test02();
cout << "ģ廯" << endl;
test03();
system("pause");
return EXIT_SUCCESS;
}
| true |
75336652d3c5fee75986dbc375c6052cde1ade99 | C++ | TKscoot/Dodo-Engine | /Dodo-Engine/code/entity/Entity.h | UTF-8 | 2,193 | 2.65625 | 3 | [
"MIT"
] | permissive | #pragma once
#include "dodopch.h"
#include "components/ECS.h"
#include "components/Transform.h"
namespace Dodo
{
namespace Entity
{
class CEntity
{
public:
CEntity();
CEntity(std::string _name);
~CEntity() {}
void Update() {}
void Destroy() { m_bActive = false; }
//template<typename T>
//bool hasComponent() const
//{
// return m_bitComponentBitSet[Components::getComponentTypeID<T>];
//}
template<typename T, typename... TArgs>
std::shared_ptr<T> AddComponent(TArgs&&... _args)
{
static_assert(std::is_base_of_v<Components::CComponent, T>,
"Invalid type T. T is not a component");
//T* c(new T(std::forward<TArgs>(_args)...));
//std::shared_ptr<T> sPtr{ c };
std::shared_ptr<T> component = std::make_shared<T>(std::forward<TArgs>(_args)...);
component->Initialize();
//sPtr->Initialize();
m_components[&typeid(*component)] = component;
m_components[&typeid(*component)]->entity = this;
return component;
}
template<typename T>
std::shared_ptr<T> GetComponent()
{
if (m_components.count(&typeid(T)) != 0)
{
auto c = std::dynamic_pointer_cast<T>(m_components[&typeid(T)]);
return c;
}
else
{
return nullptr;
}
}
std::unordered_map<const std::type_info*, std::shared_ptr<Components::CComponent>> GetAllComponents()
{
return m_components;
}
bool isActive() const { return m_bActive; }
void setActive(bool _val) { m_bActive = _val; }
void setName(std::string _name) { m_sName = _name; }
// Dont just use this if you're not knowing what you are doing
void SetID(size_t _id) { ID = _id; }
private:
size_t ID;
bool m_bActive = true;
std::string m_sName = "";
std::unordered_map<const std::type_info*, std::shared_ptr<Components::CComponent>> m_components = {};
//std::vector<Components::CComponent*> m_vecComponents = {};
//Components::ComponentArray m_arrComponentArray;
//Components::ComponentBitSet m_bitComponentBitSet;
};
class TestEnt : public CEntity
{
public:
void Update()
{
Environment::CLog::Message("This is the Test entity!");
}
};
}
}
| true |
d2bdcbf1f4b3e08663d3c0488f5b568b505de339 | C++ | vittorioromeo/Experiments | /Random/Old/testRange.cpp | UTF-8 | 1,167 | 3.5625 | 4 | [
"AFL-3.0",
"AFL-2.1",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | #include <iostream>
#include <vector>
#include <iterator>
#include <utility>
#include <tuple>
template <typename TItr>
class Range
{
private:
TItr itrBegin, itrEnd;
public:
inline constexpr Range(const TItr& mItrBegin, const TItr& mItrEnd) noexcept
: itrBegin{mItrBegin},
itrEnd{mItrEnd}
{
}
inline constexpr TItr begin() const noexcept { return itrBegin; }
inline constexpr TItr end() const noexcept { return itrEnd; }
};
template <typename T, typename... TArgs>
class RangeZip
{
};
template <typename T>
inline constexpr auto getReverseRange(const T& mContainer) noexcept
-> Range<decltype(mContainer.rbegin())>
{
return {mContainer.rbegin(), mContainer.rend()};
}
template <typename T>
inline constexpr auto getHalfRange(const T& mContainer) noexcept
-> Range<decltype(mContainer.begin())>
{
return {mContainer.begin(),
mContainer.begin() + (mContainer.end() - mContainer.begin()) / 2};
}
int main()
{
std::vector<int> test{1, 2, 3, 4};
for(const auto& i : getReverseRange(test)) std::cout << i << std::endl;
for(const auto& i : getHalfRange(test)) std::cout << i << std::endl;
} | true |
50c11c42ed7982be805a5c29440933b45eba4f7f | C++ | dpnom/opencv | /samples/cpp/travelsalesman.cpp | UTF-8 | 2,662 | 3.234375 | 3 | [
"BSD-3-Clause"
] | permissive | #include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
void DrawTravelMap(Mat &img, vector<Point> &p, vector<int> &n);
class TravelSalesman : public ml::SimulatedAnnealingSolver
{
private :
vector<Point> &posCity;
vector<int> &next;
RNG rng;
int d0,d1,d2,d3;
public:
TravelSalesman(vector<Point> &p,vector<int> &n):posCity(p),next(n)
{
rng = theRNG();
};
/** Give energy value for a state of system.*/
virtual double energy();
/** Function which change the state of system (random pertubation).*/
virtual void changedState();
/** Function to reverse to the previous state.*/
virtual void reverseChangedState();
};
void TravelSalesman::changedState()
{
d0 = rng.uniform(0,static_cast<int>(posCity.size()));
d1 = next[d0];
d2 = next[d1];
d3 = next[d2];
int d0Tmp = d0;
int d1Tmp = d1;
int d2Tmp = d2;
next[d0Tmp] = d2;
next[d2Tmp] = d1;
next[d1Tmp] = d3;
}
void TravelSalesman::reverseChangedState()
{
next[d0] = d1;
next[d1] = d2;
next[d2] = d3;
}
double TravelSalesman::energy()
{
double e=0;
for (size_t i = 0; i < next.size(); i++)
{
e += norm(posCity[i]-posCity[next[i]]);
}
return e;
}
void DrawTravelMap(Mat &img, vector<Point> &p, vector<int> &n)
{
for (size_t i = 0; i < n.size(); i++)
{
circle(img,p[i],5,Scalar(0,0,255),2);
line(img,p[i],p[n[i]],Scalar(0,255,0),2);
}
}
int main(void)
{
int nbCity=40;
Mat img(500,500,CV_8UC3,Scalar::all(0));
RNG &rng=theRNG();
int radius=static_cast<int>(img.cols*0.45);
Point center(img.cols/2,img.rows/2);
vector<Point> posCity(nbCity);
vector<int> next(nbCity);
for (size_t i = 0; i < posCity.size(); i++)
{
double theta = rng.uniform(0., 2 * CV_PI);
posCity[i].x = static_cast<int>(radius*cos(theta)) + center.x;
posCity[i].y = static_cast<int>(radius*sin(theta)) + center.y;
next[i]=(i+1)%nbCity;
}
TravelSalesman ts(posCity,next);
ts.setCoolingRatio(0.99);
ts.setInitialTemperature(100);
ts.setIterPerStep(10000*nbCity);
ts.setFinalTemperature(100*0.97);
DrawTravelMap(img,posCity,next);
imshow("Map",img);
waitKey(10);
for (int i = 0; i < 100; i++)
{
ts.run();
img = Mat::zeros(img.size(),CV_8UC3);
DrawTravelMap(img, posCity, next);
imshow("Map", img);
waitKey(10);
double ti=ts.getFinalTemperature();
cout<<ti <<" -> "<<ts.energy()<<"\n";
ts.setInitialTemperature(ti);
ts.setFinalTemperature(ti*0.97);
}
return 0;
}
| true |
9f15cd48a4938aaa0326bd1477d0ccb12914e8be | C++ | manalarora/coding-blocks-online-questions | /recurssion/recurssionSubsequence.cpp | UTF-8 | 694 | 3.265625 | 3 | [] | no_license | #include<iostream>
#include<set>
#include<cstring>
#include<cmath>
using namespace std;
void subsequences(char *in,char *out,int i,int j,set<string> &s){
//Base Case
if(in[i]=='\0'){
out[j] = '\0';
cout<<out<<" ";
//string temp(out); //Create a string object
//s.insert(temp); //insert into set s
return;
}
//Rec Case
subsequences(in,out,i+1,j,s);
out[j] = in[i];
subsequences(in,out,i+1,j+1,s);
}
int main(){
char a[100];
cin>>a;
string temp(a);
char out[100];
set<string> s;
cout<<pow(2,temp.size())<<endl;
subsequences(a,out,0,0,s);
int cnt = 0;
//for(string k:s){
// cout<<k<<" ";//
// cnt++;
//}
//cout<<cnt<<endl;
return 0;
} | true |
04eb2e58866f5a400da647bed190548fef8992c3 | C++ | vehiclecloud/CS218-CarTorrent | /src/CodingPacket.h | UTF-8 | 2,256 | 2.671875 | 3 | [] | no_license | /*
* CodingPacket.h
*
* Created on: Dec 3, 2017
* Author: Reggie
*/
#ifndef SRC_CODINGPACKET_H_
#define SRC_CODINGPACKET_H_
#include "NetworkCodingMessage_m.h"
class CodingPacket {
public:
CodingPacket(std::string pid, NetworkCodingMessage* ncm, simtime_t ts) {
m_packet_id = pid;
m_file_size = ncm->getFileSize();
m_gen = ncm->getGen();
m_num_blocks_gen = ncm->getNumBlocksGen();
m_block_size = ncm->getBlockSize();
m_coding_num = ncm->getCodingNum();
m_coeffs_size = ncm->getCoeffsArraySize();
m_coeffs = (unsigned char*) malloc(m_coeffs_size);
for (int i = 0; i < m_coeffs_size; i++)
m_coeffs[i] = ncm->getCoeffs(i);
m_sums_size = ncm->getSumsArraySize();
m_sums = (unsigned char*) malloc(m_sums_size);
for (int i = 0; i < m_sums_size; i++)
m_sums[i] = ncm->getSums(i);
m_timestamp = ts;
}
~CodingPacket() {
free(m_coeffs);
free(m_sums);
}
std::string getPacketId() const { return m_packet_id; }
long getFileSize() const { return m_file_size; }
int getGen() const { return m_gen; }
int getNumBlocksGen() const { return m_num_blocks_gen; }
int getBlockSize() const { return m_block_size; }
int getCodingNum() const { return m_coding_num; }
size_t getCoeffsSize() const { return m_coeffs_size; }
size_t getSumsSize() const { return m_sums_size; }
unsigned char* getCoeffs() const { return m_coeffs; }
unsigned char* getSums() const { return m_sums; }
simtime_t getTimestamp() const { return m_timestamp; }
void setTimestamp(simtime_t ts) { m_timestamp = ts; }
private:
std::string m_packet_id;
long m_file_size;
int m_gen;
int m_num_blocks_gen;
int m_block_size;
int m_coding_num;
unsigned char* m_coeffs;
unsigned char* m_sums;
simtime_t m_timestamp;
size_t m_coeffs_size;
size_t m_sums_size;
};
#endif /* SRC_CODINGPACKET_H_ */
| true |
5df6f905c61146cf4fb027f1bd53ed2a747c2d09 | C++ | mad0/NewSurvi | /Survival/GUISlot.cpp | UTF-8 | 397 | 2.53125 | 3 | [] | no_license | #include "GUISlot.h"
GUISlot::GUISlot() {
//std::cout << "Tworze slot...\n";
//slotItem = nullptr;
//empty = true;
//slot.setFillColor(sf::Color::Green);
//slot.setSize(sf::Vector2f(62, 64));
}
GUISlot::~GUISlot() {
//delete slotItem;
}
void GUISlot::setPosition(int _x, int _y) {
slot.setPosition(_x, _y);
}
void GUISlot::draw(){
}
GUISlot::GUISlot()
{
}
GUISlot::~GUISlot()
{
}
| true |
fb38dee43dc4e3f4e877902ef1f3d598aa863df2 | C++ | missdeer/WinCopy | /Exception.h | UTF-8 | 575 | 2.828125 | 3 | [
"MIT"
] | permissive | #pragma once
namespace ex
{
class WinException
: public std::runtime_error
{
public:
explicit WinException(const char* const what, const DWORD error = ::GetLastError())
: runtime_error(std::string(what) + ", error = " + std::to_string(error))
{
}
};
template<class ParamType>
inline void CheckZero(ParamType param, const char* const desc)
{
if (param)
return;
const DWORD lastError = ::GetLastError();
throw WinException(desc, lastError);
}
} // namespace ex | true |
5a3af3ea4f5ea34cb975258d09381ce382e76295 | C++ | jwvg0425/boj | /solutions/3058/3058.cpp11.cpp | UTF-8 | 482 | 2.796875 | 3 | [] | no_license | #include <stdio.h>
#include <algorithm>
#include <vector>
#include <string>
#include <iostream>
#include <stack>
#include <math.h>
#include <memory.h>
#include <queue>
void solve()
{
int min = 987654321;
int sum = 0;
for (int i = 0; i < 7; i++)
{
int k;
scanf("%d", &k);
if (k % 2 != 0)
continue;
min = std::min(min, k);
sum += k;
}
printf("%d %d\n", sum, min);
}
int main()
{
int t;
scanf("%d", &t);
for (int i = 0; i < t; i++)
solve();
return 0;
} | true |
620ddf98e745bdd92d66291ee7adb2a15ed20f57 | C++ | otomarukanta/3docr | /include/blob_extracter.h | UTF-8 | 499 | 2.65625 | 3 | [] | no_license | #include <vector>
#include <opencv2/opencv.hpp>
#include "blob.h"
#include "labeling.h"
class BlobExtracter {
public:
BlobExtracter(unsigned int w, unsigned int h) : width(w), height(h) {
label_img = new unsigned int[w * h];
labeling = new Labeling(w, h);
};
~BlobExtracter() {
delete [] label_img;
delete labeling;
}
void extract(const cv::Mat& src_img, std::vector<Blob>& blobs) ;
private:
Labeling *labeling;
unsigned int width;
unsigned int height;
unsigned int *label_img;
};
| true |
3541debd700ff8b9a08d82070d58b3cef59a5cfa | C++ | Codeon-GmbH/mulle-clang | /test/CXX/temp/temp.constr/temp.constr.constr/function-templates.cpp | UTF-8 | 1,933 | 3.03125 | 3 | [
"Apache-2.0",
"LLVM-exception",
"NCSA"
] | permissive | // RUN: %clang_cc1 -std=c++2a -x c++ -verify %s
template<typename T>
constexpr bool is_ptr_v = false;
template<typename T>
constexpr bool is_ptr_v<T*> = true;
template<typename T, typename U>
constexpr bool is_same_v = false;
template<typename T>
constexpr bool is_same_v<T, T> = true;
template<typename T> requires is_ptr_v<T> // expected-note {{because 'is_ptr_v<int>' evaluated to false}}
// expected-note@-1{{because 'is_ptr_v<char>' evaluated to false}}
auto dereference(T t) { // expected-note {{candidate template ignored: constraints not satisfied [with T = int]}}
// expected-note@-1{{candidate template ignored: constraints not satisfied [with T = char]}}
return *t;
}
static_assert(is_same_v<decltype(dereference<int*>(nullptr)), int>);
static_assert(is_same_v<decltype(dereference(2)), int>); // expected-error {{no matching function for call to 'dereference'}}
static_assert(is_same_v<decltype(dereference<char>('a')), char>); // expected-error {{no matching function for call to 'dereference'}}
template<typename T> requires (T{} + T{}) // expected-note {{because substituted constraint expression is ill-formed: invalid operands to binary expression ('A' and 'A')}}
auto foo(T t) { // expected-note {{candidate template ignored: constraints not satisfied [with T = A]}}
return t + t;
}
template<typename T> requires (!((T{} - T{}) && (T{} + T{})) || false)
// expected-note@-1{{because substituted constraint expression is ill-formed: invalid operands to binary expression ('A' and 'A')}}
// expected-note@-2{{and 'false' evaluated to false}}
auto bar(T t) { // expected-note {{candidate template ignored: constraints not satisfied [with T = A]}}
return t + t;
}
struct A { };
static_assert(foo(A{})); // expected-error {{no matching function for call to 'foo'}}
static_assert(bar(A{})); // expected-error {{no matching function for call to 'bar'}} | true |
f1693702f4a116918fd60d2a650f0e30406f4164 | C++ | julian533/PeTRA | /petra_central_control/include/petra_central_control/CCUState.h | UTF-8 | 826 | 3 | 3 | [] | no_license | #pragma once
#include <petra_central_control/default.h>
class CCUState
{
public:
enum Value
{
uninitialized = 0,
initialized = 1,
active = 2,
finished = 3
};
CCUState(Value value) : value_(value) {}
CCUState() : CCUState(uninitialized) {}
operator Value() const { return value_; }
explicit operator bool() = delete;
std::string ccu_state_to_string(CCUState state)
{
switch (state)
{
case CCUState::uninitialized:
return "Uninitialized";
case CCUState::initialized:
return "Initialized";
case CCUState::active:
return "Active";
case CCUState::finished:
return "Finished";
default:
return "";
}
}
private:
Value value_;
}; | true |
e21302857b3b55c85c22c69b9d06af5bdd6a43d2 | C++ | joaoabcoelho/euclid | /src/test.cxx | UTF-8 | 637 | 3.140625 | 3 | [] | no_license | #include <iostream>
#include <ctime>
#include <math.h>
using namespace std;
int main(){
float d;
float x = 1;
float y = 20;
int trials = 1e8;
clock_t startTime = clock();
for(int i=0; i<trials; i++){
d = sqrt(x*x + y*y);
}
clock_t endTime = clock();
clock_t clockTicksTaken = endTime - startTime;
double timeInSeconds = clockTicksTaken / (double) CLOCKS_PER_SEC;
cout << endl << " Clock: " << timeInSeconds*1e9/trials << " ns / computation." << endl << endl;
cout << " 200kx200k = " << timeInSeconds/trials*2e5*2e5 << " sec" << endl << endl;
return 0;
}
| true |
45710de85574e3cda43d1e4b6163ad219b1048d6 | C++ | CatBatRat/cis161cpp | /week5/peer_review/Kalafus/hackenbush.h | UTF-8 | 2,894 | 2.890625 | 3 | [] | no_license | /*
* Author: Jame J Kalafus
* Date: 02018-10-08
* Description: CS161+ Week 3 homework demonstrating sequence and selection.
*/
#include <iostream>
#include <limits>
#include <cmath>
#ifndef HACKENBUSH_H
#define HACKENBUSH_H
#ifndef CONST
#define CONST
const short int QUIT = 0;
const short int INVALID = -1;
const short int CONTINUE = 1;
#endif
const bool HACKENBUSH__ROUND_UP_REMOVED = true;
const bool HACKENBUSH__USER_PLAYS_FIRST = true;
const int HACKENBUSH__MAX_REMOVE = 3;
const int HACKENBUSH__MIN_REMOVE = 1;
const int HACKENBUSH__TERMINAL_STATE = 0;
const int HACKENBUSH__INITIAL_STATE = 11;
const int HACKENBUSH__MIN_GAME = HACKENBUSH__TERMINAL_STATE + HACKENBUSH__MAX_REMOVE + 1;
const int HACKENBUSH__MAX_GAME = std::numeric_limits<int>::max();
const short int HACKENBUSH__UN_INITIALIZED = INVALID; // needs pseudo-random initialization of game state
void hackenbushUserComputerInterface();
void hackenbushVerboseInstructions();
void hackenbushTerseInstructions();
void hackenbushQuitInstructions();
class Hackenbush
{
public:
Hackenbush()
{
}
void play();
private:
void initialize()
{
Hackenbush::game_state = HACKENBUSH__INITIAL_STATE; // TODO randomize initial state
Hackenbush::is_user_turn_register = HACKENBUSH__USER_PLAYS_FIRST;
}
void echo_game_state()
{
std::cout << "Sticks: " << Hackenbush::get_state() << std::endl;
for ( int counter = 0; counter < Hackenbush::get_state(); counter++ )
{
std::cout << "|";
}
std::cout << std::endl;
}
void echo_player_turn()
{
if ( Hackenbush::is_user_turn() )
{
std::cout << "It's your turn." << std::endl;
}
else
{
std::cout << "It's not your turn." << std::endl;
}
}
int get_user_move();
int get_computer_move();
int game_state = HACKENBUSH__UN_INITIALIZED;
int get_state()
{
return Hackenbush::game_state;
}
bool is_valid_move(int move)
{
if ( (Hackenbush::get_state()-move >= HACKENBUSH__TERMINAL_STATE) and ( (HACKENBUSH__MIN_REMOVE <= move) and (move <= HACKENBUSH__MAX_REMOVE) ) )
{
return true;
}
return false;
}
bool apply_move(int move)
{
bool result = Hackenbush::is_valid_move(move);
if ( result )
{
game_state -= move;
}
else
return result;
}
bool is_user_turn_register = HACKENBUSH__USER_PLAYS_FIRST;
bool is_user_turn()
{
return is_user_turn_register;
}
void toggle_turn()
{
if ( is_user_turn() == true )
{
is_user_turn_register = false;
}
else
{
is_user_turn_register = true;
}
}
bool is_game_over()
{
return ( Hackenbush::get_state() == HACKENBUSH__TERMINAL_STATE );
}
bool play_again()
{
std::cout << "Play again? (y/n) " << std::endl;
switch ( toolInputString()[0] )
{
case 'y': return true;
case 'n': return false;
}
return false;
}
};
#endif // HACKENBUSH_H
| true |
5cc74fcf790a3b0a3787501bd64941d8832fad07 | C++ | Gchenzhiyang/LP5562-RK | /src/LP5562-RK.h | UTF-8 | 39,217 | 3.234375 | 3 | [
"MIT"
] | permissive | #ifndef __LP5562_RK_H
#define __LP5562_RK_H
// Repository: https://github.com/rickkas7/LP5562-RK
// License: MIT
#include "Particle.h"
/**
* @brief Class for programming the LP5562 directly
*
* You'll need to read the datasheet to understand this, probably. There are a bunch of hardware
* limitations and a very small program size of 16 instructions to work with.
*
*/
class LP5562Program {
public:
/**
* @brief Construct a programming object. This is the program for a single engine.
*
* This object is small (36 bytes) so it's OK to allocate one on the stack.
*/
LP5562Program();
/**
* @brief Destructor.
*/
virtual ~LP5562Program();
/**
* @brief Add a wait command (ramp/wait with increment of 0)
*
* @param prescale false = 0.49 ms cycle time; true = 15.6 ms cycle time
*
* @param stepTime Wait this this many cycles (1 - 63)
*
* @param atInst (can omit) Normally instructions are added at the current end of the program
* but you can use the atInst parameter to set a specific instruction (0 - 15) in the program.
*
* Wait times vary depending on prescale. With prescale = false, .49 ms to 7.35 ms.
* With prescale = true, 15.6 ms to 982.8 ms. You can make even longer wait times by putting
* a wait in a loop. Since a loop can be executed up to 63 times, you can get a 62 second delay.
*/
bool addCommandWait(bool prescale, uint8_t stepTime, int atInst = -1) { return addCommandRamp(prescale, stepTime, false, 0); };
/**
* @brief Add a ramp
*
* @param prescale false = 0.49 ms cycle time; true = 15.6 ms cycle time
*
* @param stepTime Wait this this many cycles (1 - 63)
*
* @param decrease false = step up, true = step down
*
* @param numSteps Number of times the PWM is increased by 1.
*
* @param atInst (can omit) Normally instructions are added at the current end of the program
* but you can use the atInst parameter to set a specific instruction (0 - 15) in the program.
*
* Step times vary depending on prescale. With prescale = false, .49 ms to 7.35 ms.
* With prescale = true, 15.6 ms to 982.8 ms.
*
* The starting and ending point of the ramp depend on the current PWM value when you start,
* when you are incrementing or decrementing, and the number of steps.
*/
bool addCommandRamp(bool prescale, uint8_t stepTime, bool decrease, uint8_t numSteps, int atInst = -1);
/**
* @brief Set a specific PWM level
*
* @param level The level (0 = off, 255 = full brightness)
*
* @param atInst (can omit) Normally instructions are added at the current end of the program
* but you can use the atInst parameter to set a specific instruction (0 - 15) in the program.
*/
bool addCommandSetPWM(uint8_t level, int atInst = -1);
/**
* @brief Go to start of program (instruction 0)
*
* @param atInst (can omit) Normally instructions are added at the current end of the program
* but you can use the atInst parameter to set a specific instruction (0 - 15) in the program.
*
* This opcode is 0x0000, which is also what the uninitialize program bytes are set to. So
* as long as your program is 15 or fewer instructions, you don't need to add this to make
* your program auto-repeat.
*/
bool addCommandGoToStart(int atInst = -1);
/**
* @brief Loop and branch
*
* @param loopCount The number of times to loop (1 - 63)
*
* @param stepNum The step number to go to when looping (0 - 15)
*
* @param atInst (can omit) Normally instructions are added at the current end of the program
* but you can use the atInst parameter to set a specific instruction (0 - 15) in the program.
*
* After loopCount is reached, then the next statement is executed.
*
* Loops can be nested for loops larger than 63.
*
* One common thing is to put a wait in a loop, which allows you to wait up to 62 seconds.
*/
bool addCommandBranch(uint8_t loopCount, uint8_t stepNum, int atInst = -1);
/**
* @brief End program (instead of repeating)
*
* @param generateInterrupt Generate a software interrupt when reached if this parameter is true
*
* @param setPWMto0 If true, set the PWM to 0. If false, leave it unchanged.
*
* @param atInst (can omit) Normally instructions are added at the current end of the program
* but you can use the atInst parameter to set a specific instruction (0 - 15) in the program.
*
* This puts the engine into HOLD mode and stops execution of this engine.
*/
bool addCommandEnd(bool generateInterrupt, bool setPWMto0, int atInst = -1);
/**
* @brief Send a trigger to other engines. Used to synchronize the three engines.
*
* @param engineMask A mask of the engines to send to. Logical OR the values MASK_ENGINE_1,
* MASK_ENGINE_2, and MASK_ENGINE_3. You will only send to one or two, you should not send to
* yourself!
*
* @param atInst (can omit) Normally instructions are added at the current end of the program
* but you can use the atInst parameter to set a specific instruction (0 - 15) in the program.
*
* When you send a trigger, this instruction will block until the engines you sent to have
* hit a wait instruction. It will work if they hit the wait before you send, as well.
*/
bool addCommandTriggerSend(uint8_t engineMask, int atInst = -1);
/**
* @brief Wait for a trigger from another engine. Used to synchronize the three engines.
*
* @param engineMask A mask of the engines to wait on. MASK_ENGINE_1,
* MASK_ENGINE_2, and MASK_ENGINE_3 can be logically ORed together. You should not wait on
* your own engine. In most cases you should have one engine be the trigger sender and wait
* on the two other engines since you cannot simultaneously send and wait.
*
* @param atInst (can omit) Normally instructions are added at the current end of the program
* but you can use the atInst parameter to set a specific instruction (0 - 15).
*
*/
bool addCommandTriggerWait(uint8_t engineMask, int atInst = -1);
/**
* @brief Low level addCommand that takes a specific opcode. Normaly you'd use the high leve interface.
*
* @param cmd 16-bit program instruction word.
*
* @param atInst (can omit) Normally instructions are added at the current end of the program
* but you can use the atInst parameter to set a specific instruction (0 - 15) in the program.
*/
bool addCommand(uint16_t cmd, int atInst = -1);
/**
* @brief Add a delay in milliseconds
*
* @param milliseconds The number of milliseconds to delay (1 - 61916).
*
* There is no atInst option for this method because depending on the delay, it may add two
* instructions: a wait (for up to 1000 milliseconds), or a wait and a loop. Since it has
* a variable number of instructions, it can't be inserted into arbitrary code, only added
* at the end.
*
* When the delay is > 1000 milliseconds, the resolution is 1 second.
*/
bool addDelay(unsigned long milliseconds);
/**
* @brief Clear the current program
*/
void clear();
/**
* @brief Get the current step number
*
* Use this before you add a new command (like addCommandSetPWM) to remember the step number
* you are about to write. This can be used to overwrite the instruction using the atInst
* optional parameter.
*
* This is most commonly done so you can modify a program that's run on multiple engines
* with different PWM values.
*
* Also used to get the number of instructions after the last command has been written.
*/
uint8_t getStepNum() const { return nextInst; };
/**
* @brief Get access to the instruction buffer (16x 16-bit instruction words)
*/
const uint16_t *getInstructions() const { return instructions; };
protected:
/**
* @brief Maximum number of instructions is 16, imposed by the hardware.
*/
static const size_t MAX_INSTRUCTIONS = 16;
/**
* @brief The next instruction to write to, or after all have been written, the number
* of instructions in this program. Will always be 0 <= nextInst <= MAX_INSTRUCTIONS.
*/
uint8_t nextInst = 0;
/**
* @brief The array of program instructions. Each instruction is a 16-bit word.
*/
uint16_t instructions[MAX_INSTRUCTIONS];
};
/**
* @brief Class for the LP5562 LED driver
*
* Normally you create one of these as a global variable for each chip you have on your board.
*
* You must initialize any configuration parameters before calling begin(). This is typically done
* in setup().
*
* For example, to set the RGB and W current to 10 mA instead of 5 mA, use:
*
* ledDriver.withLEDCurrent(10.0).begin();
*
* You can chain the with options, fluent-style if desired:
*
* ledDriver.withLEDCurrent(10.0, 10.0, 10.0, 20.0).withExternalOscillator().begin();
*
*/
class LP5562 {
public:
/**
* @brief Construct the object
*
* @param addr The address. Can be 0 - 3 based on the address select pins, using the normal base
* address of 0x30 to make 0x30 to 0x33. Or you can pass in the full I2C address 0x00 - 0x7f.
*
* @param wire The I2C interface to use. Normally Wire, the primary I2C interface. Can be a
* different one on devices with more than one I2C interface.
*/
LP5562(uint8_t addr = 0x30, TwoWire &wire = Wire);
/**
* @brief Destructor. Not normally used as this is typically a globally instantiated object.
*/
virtual ~LP5562();
/**
* @brief Sets the LED current
*
* @param all The current for all LEDs (R, G, B, and W). You can set specific different currents with
* the other overload. The default is 5 mA. The range of from 0.1 to 25.5 mA in increments of 0.1 mA.
*
* This method returns a LP5562 object so you can chain multiple configuration calls together, fluent-style.
*/
LP5562 &withLEDCurrent(float all) { return withLEDCurrent(all, all, all, all); };
/**
* @brief Sets the LED current
*
* @param red The current for the red LED. The default is 5 mA. The range of from 0.1 to 25.5 mA in
* increments of 0.1 mA.
*
* @param green The current for the green LED. The default is 5 mA. The range of from 0.1 to 25.5 mA in
* increments of 0.1 mA.
*
* @param blue The current for the blue LED. The default is 5 mA. The range of from 0.1 to 25.5 mA in
* increments of 0.1 mA.
*
* @param white The current for the white LED. The default is 5 mA. The range of from 0.1 to 25.5 mA in
* increments of 0.1 mA.
*
* This method returns a LP5562 object so you can chain multiple configuration calls together, fluent-style.
*/
LP5562 &withLEDCurrent(float red, float green, float blue, float white = 0.1);
/**
* @brief Set external oscillator mode. Default is internal.
*
* This method returns a LP5562 object so you can chain multiple configuration calls together, fluent-style.
*/
LP5562 &withUseExternalOscillator(bool value = true) { useExternalOscillator = value; return *this; };
/**
* @brief Use Logarithmic Mode for PWM brightness. Default = true.
*
* This adjusts the PWM value for the perceived brightness from the human eye vs. actual linear values.
*
* This method returns a LP5562 object so you can chain multiple configuration calls together, fluent-style.
*/
LP5562 &withUseLogarithmicMode(bool value = true) { useLogarithmicMode = value; return *this; };
/**
* @brief Enable high frequency PWM. Default = false.
*
* Low frequency (default) is 256 Hz. High frequency is 558 Hz.
*
* This method returns a LP5562 object so you can chain multiple configuration calls together, fluent-style.
*/
LP5562 &withHighFrequencyMode(bool value = true) { highFrequencyMode = value; return *this; };
/**
* @brief Set up the I2C device and begin running.
*
* You cannot do this from STARTUP or global object construction time. It should only be done from setup
* or loop (once).
*
* Make sure you set the LED current using withLEDCurrent() before calling begin if your LED has a
* current other than the default of 5 mA.
*/
bool begin();
#ifdef ENABLE_TESTPGM
void testPgm1();
void testPgm2();
#endif /* ENABLE_TESTPGM */
/**
* @brief Sets the PWM for the red channel
*
* @param red value 0 - 255. 0 = off, 255 = full brightness.
*
* If you were previously using a program (setProgram, setBlink, setBlink2, or setBreathe,
* you must stop the program using useDirectRGB() before you can set the RGB values.
*/
void setR(uint8_t red);
/**
* @brief Sets the PWM for the green channel
*
* @param green value 0 - 255. 0 = off, 255 = full brightness.
*
* If you were previously using a program (setProgram, setBlink, setBlink2, or setBreathe,
* you must stop the program using useDirectRGB() before you can set the RGB values.
*/
void setG(uint8_t green);
/**
* @brief Sets the PWM for the blue channel
*
* @param blue value 0 - 255. 0 = off, 255 = full brightness.
*
* If you were previously using a program (setProgram, setBlink, setBlink2, or setBreathe,
* you must stop the program using useDirectRGB() before you can set the RGB values.
*/
void setB(uint8_t blue);
/**
* @brief Sets the PWM for the R, G, and B channels.
*
* @param red value 0 - 255. 0 = off, 255 = full brightness.
*
* @param green value 0 - 255. 0 = off, 255 = full brightness.
* @param blue value 0 - 255. 0 = off, 255 = full brightness.
*
* If you were previously using a program (setProgram, setBlink, setBlink2, or setBreathe,
* you must stop the program using useDirectRGB() before you can set the RGB values.
*/
void setRGB(uint8_t red, uint8_t green, uint8_t blue);
/**
* @brief Sets the PWM for the R, G, and B channels.
*
* @param rgb Value in the form of 0x00RRGGBB. Each of RR, GG, and BB are from
* 0x00 (off) to 0xFF (full brightness).
*
* If you were previously using a program (setProgram, setBlink, setBlink2, or setBreathe,
* you must stop the program using useDirectRGB() before you can set the RGB values.
*/
void setRGB(uint32_t rgb);
/**
* @brief Sets the W channel to the specified PWM value
*
* @param white value 0 - 255. 0 = off, 255 = full brightness.
*/
void setW(uint8_t white);
/**
* @brief Use direct mode on RGB LED. Changes the LED mapping register and if a program is running
* on the R, G, or B LEDs, stops it.
*
* If you call setProgram() or functions like setBlink(), setBlink2(), or setBreathe() you must
* call this before calling setRGB() or the program will continue to run and override your manual
* setting!
*/
void useDirectRGB();
/**
* @brief Use direct mode on W LED. Changes the LED mapping register and if a program is running
* on the W LED, stops it.
*
* If you call setProgram() or functions like setBlink(), setBlink2(), or setBreathe() you must
* call this before calling setW() or the program will continue to run and override your manual
* setting!
*/
void useDirectW();
/**
* @brief Set blinking mode on the RGB LED
*
* @param red value 0 - 255. 0 = off, 255 = full brightness.
*
* @param green value 0 - 255. 0 = off, 255 = full brightness.
* @param blue value 0 - 255. 0 = off, 255 = full brightness.
*
* @param msOn The number of milliseconds to be on (1 - 61916)
*
* @param msOff The number of milliseconds to be off (1 - 61916)
*/
void setBlink(uint8_t red, uint8_t green, uint8_t blue, unsigned long msOn, unsigned long msOff);
/**
* @brief Set blinking mode on the RGB LED
*
* @param rgb Value in the form of 0x00RRGGBB. Each of RR, GG, and BB are from
* 0x00 (off) to 0xFF (full brightness).
*
* @param msOn The number of milliseconds to be on (1 - 61916)
*
* @param msOff The number of milliseconds to be off (1 - 61916)
*/
void setBlink(uint32_t rgb, unsigned long msOn, unsigned long msOff) { setBlink((uint8_t)(rgb >> 16), (uint8_t)(rgb >> 8), (uint8_t)rgb, msOn, msOff); };
/**
* @brief Set alternating blink mode between two colors (no off phase)
*
* @param red1 value 0 - 255. 0 = off, 255 = full brightness.
*
* @param green1 value 0 - 255. 0 = off, 255 = full brightness.
* @param blue1 value 0 - 255. 0 = off, 255 = full brightness.
*
* @param ms1 The number of milliseconds to be the 1 color (1 - 61916)
*
* @param red2 value 0 - 255. 0 = off, 255 = full brightness.
*
* @param green2 value 0 - 255. 0 = off, 255 = full brightness.
* @param blue2 value 0 - 255. 0 = off, 255 = full brightness.
*
* @param ms2 The number of milliseconds to be the 2 color (1 - 61916)
*/
void setBlink2(uint8_t red1, uint8_t green1, uint8_t blue1, unsigned long ms1, uint8_t red2, uint8_t green2, uint8_t blue2, unsigned long ms2);
/**
* @brief Set alternating blink mode between two colors (no off phase)
*
* @param rgb1 Value in the form of 0x00RRGGBB. Each of RR, GG, and BB are from
* 0x00 (off) to 0xFF (full brightness).
*
* @param ms1 The number of milliseconds to be the 1 color (1 - 61916)
*
* @param rgb2 Value in the form of 0x00RRGGBB. Each of RR, GG, and BB are from
* 0x00 (off) to 0xFF (full brightness).
*
* @param ms2 The number of milliseconds to be the 2 color (1 - 61916)
*/
void setBlink2(uint32_t rgb1, unsigned long ms1, uint32_t rgb2, unsigned long ms2);
/**
* @brief Set breathing mode
*
* Because of hardware limitations, breathing mode can only be done for the 7 full brightness colors:
* red true, false, false
* green false, true, false
* blue false, false, true
* yellow true, true, false
* cyan false, true, true
* magenta true, false, true
* white true, true, true
*
* @param red true to breathe the red channel
*
* @param green true to breathe the green channel
*
* @param blue true to breathe the blue channel
*
* @param stepTimeHalfMs Amount of time between step changes from 1 to 63 in half millisecond increments.
*
* @param lowLevel Start at this level (0 - 255). Typically 0.
*
* @param highLevel End at this level (0 - 255). Typically 255. lowLevel must be < highLevel.
*/
void setBreathe(bool red, bool green, bool blue, uint8_t stepTimeHalfMs, uint8_t lowLevel, uint8_t highLevel);
/**
* @brief Set indicator mode
*
* Engine 1 = Blink
* Engine 2 = Fast Blink
* Engine 3 = Breathe
*/
void setIndicatorMode(unsigned long on1ms = 500, unsigned long off1ms = 500, unsigned long on2ms = 100, unsigned long off2ms = 100, uint8_t breatheTime = 20);
/**
* @brief Set ledMapping to program. Not normally necessary.
*
* @param red REG_LED_MAP_DIRECT (direct RGB, default), REG_LED_MAP_ENGINE_1, REG_LED_MAP_ENGINE_2, or REG_LED_MAP_ENGINE_3.
*
* @param green REG_LED_MAP_DIRECT (direct RGB, default), REG_LED_MAP_ENGINE_1, REG_LED_MAP_ENGINE_2, or REG_LED_MAP_ENGINE_3.
*
* @param blue REG_LED_MAP_DIRECT (direct RGB, default), REG_LED_MAP_ENGINE_1, REG_LED_MAP_ENGINE_2, or REG_LED_MAP_ENGINE_3.
*
* @param white REG_LED_MAP_DIRECT (direct RGB, default), REG_LED_MAP_ENGINE_1, REG_LED_MAP_ENGINE_2, or REG_LED_MAP_ENGINE_3.
*
* This method is used to map the LED to direct or program mode. This is used internally by
* setRGB, setBlink, setBlink2, or setBreathe so you don't normally need to call this yourself.
*/
bool setLedMapping(uint8_t red, uint8_t green, uint8_t blue, uint8_t white);
/**
* @brief Set the led mapping for the red LED. Typically used in indicator mode to set direct or program mode.
*
* @brief mode REG_LED_MAP_DIRECT (direct RGB, default), REG_LED_MAP_ENGINE_1, REG_LED_MAP_ENGINE_2, or REG_LED_MAP_ENGINE_3
*
* @brief value If using REG_LED_MAP_DIRECT, the intensity value 0 = off, 255 = full brightness
*/
bool setLedMappingR(uint8_t mode, uint8_t value = 0);
/**
* @brief Set the led mapping for the green LED. Typically used in indicator mode to set direct or program mode.
*
* @brief mode REG_LED_MAP_DIRECT (direct RGB, default), REG_LED_MAP_ENGINE_1, REG_LED_MAP_ENGINE_2, or REG_LED_MAP_ENGINE_3
*
* @brief value If using REG_LED_MAP_DIRECT, the intensity value 0 = off, 255 = full brightness
*/
bool setLedMappingG(uint8_t mode, uint8_t value = 0);
/**
* @brief Set the led mapping for the blue LED. Typically used in indicator mode to set direct or program mode.
*
* @brief mode REG_LED_MAP_DIRECT (direct RGB, default), REG_LED_MAP_ENGINE_1, REG_LED_MAP_ENGINE_2, or REG_LED_MAP_ENGINE_3
*
* @brief value If using REG_LED_MAP_DIRECT, the intensity value 0 = off, 255 = full brightness
*/
bool setLedMappingB(uint8_t mode, uint8_t value = 0);
/**
* @brief Set the led mapping for the white LED. Typically used in indicator mode to set direct or program mode.
*
* @brief mode REG_LED_MAP_DIRECT (direct RGB, default), REG_LED_MAP_ENGINE_1, REG_LED_MAP_ENGINE_2, or REG_LED_MAP_ENGINE_3
*
* @brief value If using REG_LED_MAP_DIRECT, the intensity value 0 = off, 255 = full brightness
*/
bool setLedMappingW(uint8_t mode, uint8_t value = 0);
/**
* @brief Get the value of the LED mapping register (0x70)
*/
uint8_t getLedMapping() { return readRegister(REG_LED_MAP); };
/**
* @brief Enable an engine mode on certain engines
*
* @param engineMask A mask of the engines to send to. Logical OR the values MASK_ENGINE_1,
* MASK_ENGINE_2, and MASK_ENGINE_3 or use MASK_ENGINE_ALL for all 3 engines.
*
* @param engineMode One of the constants: REG_ENGINE_DISABLED, REG_ENGINE_LOAD,
* REG_ENGINE_RUN, or REG_ENGINE_DIRECT.
*
* This is normally done automatically for you when entering program mode or direct mode.
*/
bool setEnable(uint8_t engineMask, uint8_t engineMode);
/**
* @brief Get the value of the enable register (0x00)
*/
uint8_t getEnable() { return readRegister(REG_ENABLE); };
/**
* @brief Convert an engine number 1 - 3 to an engineMask value
*
* @param engine An engine number 1 <= engine <= 3
*
* @return A mask value MASK_ENGINE_1, MASK_ENGINE_2, or MASK_ENGINE_3
*
* engine mask
* 1 0b001
* 2 0b010
* 3 0b100
*/
uint8_t engineNumToMask(size_t engine) const;
/**
* @brief Sets the operation mode register (0x01)
*
* @param engine The engine number to set (1, 2, or 3)
*
* @param engineMode The mode to set: REG_ENGINE_DISABLED, REG_ENGINE_LOAD (also resets PC), REG_ENGINE_RUN, REG_ENGINE_DIRECT
*/
bool setOpMode(size_t engine, uint8_t engineMode);
/**
* @brief Get the value of the operation mode register (0x01)
*/
uint8_t getOpMode() { return readRegister(REG_OP_MODE); };
/**
* @brief Get the value of the status/interrupt register
*
* Reading the status/interrupt register will clear any interrupts that are set.
*/
uint8_t getStatus() { return readRegister(REG_STATUS); };
/**
* @brief Clears a program on the specified engine
*
* @param engine An engine number 1 <= engine <= 3
*/
bool clearProgram(size_t engine) { return setProgram(engine, NULL, 0, false); };
/**
* @brief Clears programs on engines 1, 2, and 3 (all engines)
*/
bool clearAllPrograms();
/**
* @brief Sets a program on a specified engine from a LP5562Program object
*
* @param engine An engine number 1 <= engine <= 3
*
* @param program The program to set
*
* @param startRunning true to start the program running immediately or false to leave it in halt mode
*/
bool setProgram(size_t engine, const LP5562Program &program, bool startRunning) { return setProgram(engine, program.getInstructions(), program.getStepNum(), startRunning); };
/**
* @brief Sets a program on a specified engine from a from program words
*
* @param engine An engine number 1 <= engine <= 3
*
* @param instructions An array of uint16_t values containing up to 16 instructions. Can be NULL if numInstruction == 0.
*
* @param numInstruction The number of instruction words (0 - 15).
*
* @param startRunning true to start the program running immediately or false to leave it in halt mode.
*
* The unused instruction words (numInstruction to 16) are always set to 0 for safety. If you call this
* with numInstruction == 0 it clears the program (which is what clearProgram and clearAllPrograms do).
*/
bool setProgram(size_t engine, const uint16_t *instructions, size_t numInstruction, bool startRunning);
/**
* @brief Convert a current value in mA to the format used by the LP5562
*
* @param value Value in mA
*
* @return A uint8_t value in tenths of a mA. For example, passing 5 (mA) will return 50.
*/
uint8_t floatToCurrent(float value) const;
/**
* @brief Low-level call to read a register value
*
* @param reg The register to read (0x00 to 0x70)
*/
uint8_t readRegister(uint8_t reg);
/**
* @brief Low-level call to write a register value
*
* @param reg The register to read (0x00 to 0x70)
*
* @param value The value to set
*
* Note that setProgram bypasses this to write multiple bytes at once, to improve efficiency.
*/
bool writeRegister(uint8_t reg, uint8_t value);
static const uint8_t REG_ENABLE = 0x00; //!< Enable register (0x00)
static const uint8_t REG_ENABLE_LOG_EN = 0x80; //!< The logarithmic mode for PWM brightness when set (instead of linear)
static const uint8_t REG_ENABLE_CHIP_EN = 0x40; //!< Enable the chip. Power-up default is off. Make sure you set the current before enabling!
/**
* @brief Put the engine in hold mode (stops execution)
*
* This constant is also passed setEnable() to specify which enable mode you want the engine to be in.
*
* This value is shifted depending on the engine when storing directly in the enable register:
*
* Engine 1: Left shift 4
* Engine 2: Left shift 2
* Engine 3: No shift
*
* This is part of a set of mutually exclusive options (for a given engine):
* REG_ENABLE_HOLD, REG_ENABLE_STEP, REG_ENABLE_RUN, REG_ENABLE_EXEC.
*/
static const uint8_t REG_ENABLE_HOLD = 0b00;
/**
* @brief Put the engine in single step mode. It will run the current instruction, increment the PC, then hold.
*
* This constant is also passed setEnable() to specify which enable mode you want the engine to be in.
*
* This value is shifted depending on the engine when storing directly in the enable register:
*
* Engine 1: Left shift 4
* Engine 2: Left shift 2
* Engine 3: No shift
*
* This is part of a set of mutually exclusive options (for a given engine):
* REG_ENABLE_HOLD, REG_ENABLE_STEP, REG_ENABLE_RUN, REG_ENABLE_EXEC.
*/
static const uint8_t REG_ENABLE_STEP = 0b01;
/**
* @brief Put the engine in run mode. It will run the current code, until the code itself
* decides to halt or you change the run mode manually.
*
* This constant is also passed setEnable() to specify which enable mode you want the engine to be in.
*
* This value is shifted depending on the engine when storing directly in the enable register:
*
* Engine 1: Left shift 4
* Engine 2: Left shift 2
* Engine 3: No shift
*
* This is part of a set of mutually exclusive options (for a given engine):
* REG_ENABLE_HOLD, REG_ENABLE_STEP, REG_ENABLE_RUN, REG_ENABLE_EXEC.
*/
static const uint8_t REG_ENABLE_RUN = 0b10;
/**
* @brief Put the engine in direct execute mode. It will run the current instruction, then hold.
*
* This constant is also passed setEnable() to specify which enable mode you want the engine to be in.
*
* This value is shifted depending on the engine when storing directly in the enable register:
*
* Engine 1: Left shift 4
* Engine 2: Left shift 2
* Engine 3: No shift
*
* This is part of a set of mutually exclusive options (for a given engine):
* REG_ENABLE_HOLD, REG_ENABLE_STEP, REG_ENABLE_RUN, REG_ENABLE_EXEC.
*/
static const uint8_t REG_ENABLE_EXEC = 0b11;
static const uint8_t REG_OP_MODE = 0x01; //!< Operation mode register (0x01)
/**
* @brief Put the engine in disabled mode, and will no longer run.
*
* This constant is also passed setOpMode() to specify which operation mode you want it to be in.
*
* This value is shifted depending on the engine when storing directly in the enable register:
*
* Engine 1: Left shift 4
* Engine 2: Left shift 2
* Engine 3: No shift
*
* This is part of a set of mutually exclusive options (for a given engine):
* REG_ENGINE_DISABLED, REG_ENGINE_LOAD, REG_ENGINE_RUN, REG_ENGINE_DIRECT.
*/
static const uint8_t REG_ENGINE_DISABLED = 0b00; //!< Put the engine in disabled mode. This bit mask is shifted left depending on which engine you are setting in the op register.
/**
* @brief Put the engine in load mode. Required to load code. Handled automatically by setProgram().
*
* This constant is also passed setOpMode() to specify which operation mode you want it to be in.
*
* This value is shifted depending on the engine when storing directly in the enable register:
*
* Engine 1: Left shift 4
* Engine 2: Left shift 2
* Engine 3: No shift
*
* This is part of a set of mutually exclusive options (for a given engine):
* REG_ENGINE_DISABLED, REG_ENGINE_LOAD, REG_ENGINE_RUN, REG_ENGINE_DIRECT.
*/
static const uint8_t REG_ENGINE_LOAD = 0b01;
/**
* @brief Put the engine in run mode.
*
* This constant is also passed setOpMode() to specify which operation mode you want it to be in.
*
* This value is shifted depending on the engine when storing directly in the enable register:
*
* Engine 1: Left shift 4
* Engine 2: Left shift 2
* Engine 3: No shift
*
* This is part of a set of mutually exclusive options (for a given engine):
* REG_ENGINE_DISABLED, REG_ENGINE_LOAD, REG_ENGINE_RUN, REG_ENGINE_DIRECT.
*/
static const uint8_t REG_ENGINE_RUN = 0b10;
/**
* @brief Put the engine in direct mode.
*
* This constant is also passed setOpMode() to specify which operation mode you want it to be in.
*
* This value is shifted depending on the engine when storing directly in the enable register:
*
* Engine 1: Left shift 4
* Engine 2: Left shift 2
* Engine 3: No shift
*
* This is part of a set of mutually exclusive options (for a given engine):
* REG_ENGINE_DISABLED, REG_ENGINE_LOAD, REG_ENGINE_RUN, REG_ENGINE_DIRECT.
*/
static const uint8_t REG_ENGINE_DIRECT = 0b11; //!< Put the engine in disabled mode. This bit mask is shifted left depending on which engine you are setting in the op register.
static const uint8_t REG_B_PWM = 0x02; //!< Blue channel PWM direct register (0x02)
static const uint8_t REG_G_PWM = 0x03; //!< Green channel PWM direct register (0x03)
static const uint8_t REG_R_PWM = 0x04; //!< Red channel PWM direct register (0x04)
static const uint8_t REG_B_CURRENT = 0x05; //!< Blue channel current register in 0.1 mA units (0x05)
static const uint8_t REG_G_CURRENT = 0x06; //!< Green channel current register in 0.1 mA units (0x06)
static const uint8_t REG_R_CURRENT = 0x07; //!< Red channel current register in 0.1 mA units (0x07)
static const uint8_t REG_CONFIG = 0x08; //!< Config register
static const uint8_t REG_CONFIG_HF = 0x40; //!< Config register HF (high frequency mode) enabled bit
static const uint8_t REG_CONFIG_PS_EN = 0x20; //!< Config register powersave enabled bit
static const uint8_t REG_CONFIG_CLK_DET_EN = 0x02; //!< Config register clock detect enable bit
static const uint8_t REG_CONFIG_INT_CLK_EN = 0x01; //!< Config register internal clock bit
static const uint8_t REG_ENG1_PC = 0x09; //!< Program counter for engine 1 (0 - 15)
static const uint8_t REG_ENG2_PC = 0x0a; //!< Program counter for engine 2 (0 - 15)
static const uint8_t REG_ENG3_PC = 0x0b; //!< Program counter for engine 3 (0 - 15)
static const uint8_t REG_STATUS = 0x0c; //!< Status register
static const uint8_t REG_STATUS_EXT_CLK_USED = 0x08;//!< Status register external clock used bit
static const uint8_t REG_STATUS_ENG1_INT = 0x04; //!< Status register engine 1 generated an interrupt if bit is set
static const uint8_t REG_STATUS_ENG2_INT = 0x02; //!< Status register engine 2 generated an interrupt if bit is set
static const uint8_t REG_STATUS_ENG3_INT = 0x01; //!< Status register engine 3 generated an interrupt if bit is set
static const uint8_t REG_RESET = 0x0d; //!< Reset register. Write 0xff to clear all register to default values
static const uint8_t REG_W_PWM = 0x0e; //!< White channel PWM direct register (0x0e)
static const uint8_t REG_W_CURRENT = 0x0f; //!< Blue channel current register in 0.1 mA units (0x0f)
static const uint8_t REG_PROGRAM_1 = 0x10; //!< Engine 1 instructions 0x10 to 0x2f (0x20 bytes = 16 16-bit instructions)
static const uint8_t REG_PROGRAM_2 = 0x30; //!< Engine 2 instructions 0x30 to 0x4f (0x20 bytes = 16 16-bit instructions)
static const uint8_t REG_PROGRAM_3 = 0x50; //!< Engine 3 instructions 0x50 to 0x6f (0x20 bytes = 16 16-bit instructions)
static const uint8_t REG_LED_MAP = 0x70; //!< LED mapping engine (direct or assigned to an engine)
/**
* @brief Sets the LED to direct PWM setting mode
*
* This constant is also passed setLedMapping() to specify how you want to control a specific LED.
*
* This value is shifted depending on the engine when storing directly in the enable register:
*
* White LED: left shift 6
* Red LED: left shift 4
* Green LED: left shift 2
* Blue LED: don't shift
*
* This is part of a set of mutually exclusive values: REG_LED_MAP_DIRECT, REG_LED_MAP_ENGINE_1,
* REG_LED_MAP_ENGINE_2, and REG_LED_MAP_ENGINE_3.
*/
static const uint8_t REG_LED_MAP_DIRECT = 0b00;
/**
* @brief Sets the LED to be controlled by engine 1
*
* This constant is also passed setLedMapping() to specify how you want to control a specific LED.
*
* This value is shifted depending on the engine when storing directly in the enable register:
*
* White LED: left shift 6
* Red LED: left shift 4
* Green LED: left shift 2
* Blue LED: don't shift
*
* You can connect multiple LEDs to a single engine. For example, if you wanted to breathe
* cyan you could connect blue and green to a single engine that's ramping up and down. Or
* connect R, G, and B to have the LED run the program in white.
*
* This is part of a set of mutually exclusive values: REG_LED_MAP_DIRECT, REG_LED_MAP_ENGINE_1,
* REG_LED_MAP_ENGINE_2, and REG_LED_MAP_ENGINE_3.
*/
static const uint8_t REG_LED_MAP_ENGINE_1 = 0b01;
/**
* @brief Sets the LED to be controlled by engine 2
*
* This constant is also passed setLedMapping() to specify how you want to control a specific LED.
*
* This value is shifted depending on the engine when storing directly in the enable register:
*
* White LED: left shift 6
* Red LED: left shift 4
* Green LED: left shift 2
* Blue LED: don't shift
*
* You can connect multiple LEDs to a single engine. For example, if you wanted to breathe
* cyan you could connect blue and green to a single engine that's ramping up and down. Or
* connect R, G, and B to have the LED run the program in white.
*
* This is part of a set of mutually exclusive values: REG_LED_MAP_DIRECT, REG_LED_MAP_ENGINE_1,
* REG_LED_MAP_ENGINE_2, and REG_LED_MAP_ENGINE_3.
*/
static const uint8_t REG_LED_MAP_ENGINE_2 = 0b10;
/**
* @brief Sets the LED to be controlled by engine 3
*
* This constant is also passed setLedMapping() to specify how you want to control a specific LED.
*
* This value is shifted depending on the engine when storing directly in the enable register:
*
* White LED: left shift 6
* Red LED: left shift 4
* Green LED: left shift 2
* Blue LED: don't shift
*
* You can connect multiple LEDs to a single engine. For example, if you wanted to breathe
* cyan you could connect blue and green to a single engine that's ramping up and down. Or
* connect R, G, and B to have the LED run the program in white.
*
* This is part of a set of mutually exclusive values: REG_LED_MAP_DIRECT, REG_LED_MAP_ENGINE_1,
* REG_LED_MAP_ENGINE_2, and REG_LED_MAP_ENGINE_3.
*/
static const uint8_t REG_LED_MAP_ENGINE_3 = 0b11;
/**
* @brief Mask value to pass to set setEnable to change the enable mode for one or more engines at once.
*
* Logically OR MASK_ENGINE_1 | MASK_ENGINE_2 | MASK_ENGINE_3 as desired for which engines you want.
* You can also use MASK_ENGINE_ALL to act on all engines.
*/
static const uint8_t MASK_ENGINE_1 = 0b001;
/**
* @brief Mask value to pass to set setEnable to change the enable mode for one or more engines at once.
*
* Logically OR MASK_ENGINE_1 | MASK_ENGINE_2 | MASK_ENGINE_3 as desired for which engines you want.
* You can also use MASK_ENGINE_ALL to act on all engines.
*/
static const uint8_t MASK_ENGINE_2 = 0b010;
/**
* @brief Mask value to pass to set setEnable to change the enable mode for one or more engines at once.
*
* Logically OR MASK_ENGINE_1 | MASK_ENGINE_2 | MASK_ENGINE_3 as desired for which engines you want.
* You can also use MASK_ENGINE_ALL to act on all engines.
*/
static const uint8_t MASK_ENGINE_3 = 0b100;
/**
* @brief Mask value to pass to set setEnable to change the enable mode for all engines at once.
*
* The same as MASK_ENGINE_1 | MASK_ENGINE_2 | MASK_ENGINE_3.
*/
static const uint8_t MASK_ENGINE_ALL = 0b111;
protected:
/**
* @brief The I2C address (0x00 - 0x7f). Default is 0x30.
*
* If you passed in an address 0 - 3 into the constructor, 0x30 - 0x33 is stored here.
*/
uint8_t addr;
/**
* @brief The I2C interface to use. Default is Wire. Could be Wire1 on some devices.
*/
TwoWire &wire;
/**
* @brief Current to supply to the red LED. Default is 5 mA
*
* Make sure this is set before calling begin! Setting the value too high can destroy the LED!
* Note the hardware value is even higher, but the library sets it always and uses a safe
* default.
*/
uint8_t redCurrent = 50;
/**
* @brief Current to supply to the green LED. Default is 5 mA
*
* Make sure this is set before calling begin! Setting the value too high can destroy the LED!
* Note the hardware value is even higher, but the library sets it always and uses a safe
* default.
*/
uint8_t greenCurrent = 50;
/**
* @brief Current to supply to the blue LED. Default is 5 mA
*
* Make sure this is set before calling begin! Setting the value too high can destroy the LED!
* Note the hardware value is even higher, but the library sets it always and uses a safe
* default.
*/
uint8_t blueCurrent = 50;
/**
* @brief Current to supply to the white LED. Default is 5 mA
*
* Make sure this is set before calling begin! Setting the value too high can destroy the LED!
* Note the hardware value is even higher, but the library sets it always and uses a safe
* default.
*/
uint8_t whiteCurrent = 50;
/**
* @brief Whether to use the internal oscillator (true) or external (false). Default is internal.
*/
bool useExternalOscillator = false;
/**
* @brief Whether to use logarithmic mode for PWM values (true, default) or linear (false).
*
* Logarithmic varies the PWM values to their perceived brightness by the human eye.
*/
bool useLogarithmicMode = true;
/**
* @brief Whether to use low or high frequency for the PWM. Default is low (256 Hz).
*
* Low frequency (default) is 256 Hz. High frequency is 558 Hz.
*/
bool highFrequencyMode = false;
};
#endif /* __LP5562_RK_H */
| true |
04702df8d6d4179f8761b76df2971c49c3bf3582 | C++ | JpSilver/Headguard-of-Binding-Worlds | /Headguard-of-Binding-Worlds/ModelHandler.h | UTF-8 | 319 | 2.625 | 3 | [] | no_license | #ifndef MODELHANDLER_H
#define MODELHANDLER_H
#include <vector>
#include "Model.h"
using std::vector;
class ModelHandler{
public:
ModelHandler(){};
Model *addModel(Model model);
Model *getModel(string name);
Model *getModel(int index);
int getSize();
private:
vector<Model> models;
};
#endif //MODELHANDLER_H | true |
9822ed6a52ed2db62a9ba6b5eb46747cb97d760a | C++ | aliceyang16/Software_Labs | /Lab01 - 597609, 453828/Exercise 5 - Stop_Watch/StopWatch.cpp | UTF-8 | 874 | 3.515625 | 4 | [] | no_license | #include <iostream>
#include <time.h>
#include <StopWatch.h>
using namespace std;
StopWatch::StopWatch() // Constructor
{
}
// Starts the StopWatch when a request for it to start has been made
bool StopWatch::startStopWatch(char& button)
{
bool start = false;
if((button == 's') || (button == 'S'))
{
start = true;
}
return start;
}
// Fetches the current lap time when requested
void StopWatch::lapTime(double& time)
{
cout << "Lap Time: " << time << "s" << endl;
}
// Gets the total time after the user has requested to stop the stopwatch
void StopWatch::stopStopWatch(double& time)
{
cout << "Stop! \n" << endl;
cout << "Total Time: " << time << "s" << endl;
}
// returns the time recored to type double variable
double StopWatch::getProcessTime()
{
clock_t time = clock();
return static_cast<double>(time) / CLOCKS_PER_SEC;
} | true |
e47b34385a99891b2ab28c932c366f9ca087806d | C++ | tuan9999/Containers | /tests/map_tests.cpp | UTF-8 | 8,374 | 3.53125 | 4 | [] | no_license | //
// Created by Tuan Perera on 27.02.21.
//
#include <map>
#include "gtest/gtest.h"
#include "../library.h"
TEST(MapTest, ConstructorTests) {
std::string str = "Mapped";
ft::map<int, std::string> mf1;
std::map<int, std::string> ms1;
mf1.insert(ft::pair<int, std::string>(16, str));
ms1.insert(std::pair<int, std::string>(16, str));
mf1.insert(ft::pair<int, std::string>(23, str));
ms1.insert(std::pair<int, std::string>(23, str));
ft::map<int, std::string> mf2(mf1.begin(), mf1.end());
std::map<int, std::string> ms2(ms1.begin(), ms1.end());
ft::map<int, std::string>::iterator itf = mf2.begin();
std::map<int, std::string>::iterator its = ms2.begin();
while (itf != mf2.end()) {
ASSERT_TRUE((itf->first == its->first) && (itf->second == its->second)) << "Iterator constructor: Failed with ft: " << itf->first << " " << itf->second << " std: " << its->first << " " << its->second << "\n";
itf++;
its++;
}
}
TEST(MapTest, IteratorTests) {
std::string str = "Mapped";
ft::map<int, std::string> mf1;
std::map<int, std::string> ms1;
mf1.insert(ft::pair<int, std::string>(16, str));
ms1.insert(std::pair<int, std::string>(16, str));
mf1.insert(ft::pair<int, std::string>(23, str));
ms1.insert(std::pair<int, std::string>(23, str));
ft::map<int, std::string>::iterator itf = mf1.begin();
std::map<int, std::string>::iterator its = ms1.begin();
while (itf != mf1.end()) {
ASSERT_TRUE((itf->first == its->first) && (itf->second == its->second)) << "Iterator: Failed with ft: " << itf->first << " " << itf->second << " std: " << its->first << " " << its->second << "\n";
itf++;
its++;
}
ft::map<int, std::string>::reverse_iterator ritf = mf1.rbegin();
std::map<int, std::string>::reverse_iterator rits = ms1.rbegin();
while (ritf != mf1.rend()) {
ASSERT_TRUE((ritf->first == rits->first) && (ritf->second == rits->second)) << "Iterator: Failed with ft: " << ritf->first << " " << ritf->second << " std: " << rits->first << " " << rits->second << "\n";
ritf++;
rits++;
}
}
TEST(MapTest, CapacityTests) {
std::string str = "Mapped";
ft::map<int, std::string> mf1;
std::map<int, std::string> ms1;
mf1.insert(ft::pair<int, std::string>(16, str));
ms1.insert(std::pair<int, std::string>(16, str));
mf1.insert(ft::pair<int, std::string>(23, str));
ms1.insert(std::pair<int, std::string>(23, str));
ASSERT_TRUE(mf1.empty() == ms1.empty()) << "Empty: Failed with ft: " << mf1.empty() << " std: " << ms1.empty() << "\n";
ASSERT_TRUE(mf1.size() == ms1.size()) << "Size: Failed with ft: " << mf1.size() << " std: " << ms1.size() << "\n";
}
TEST(MapTest, OperatorTests) {
std::string str = "Mapped";
ft::map<int, std::string> mf1;
std::map<int, std::string> ms1;
mf1.insert(ft::pair<int, std::string>(16, str));
ms1.insert(std::pair<int, std::string>(16, str));
mf1.insert(ft::pair<int, std::string>(23, str));
ms1.insert(std::pair<int, std::string>(23, str));
ASSERT_TRUE(mf1[16] == ms1[16]) << "Operator[]: Failed with ft: " << mf1[16] << " std: " << ms1[16] << "\n";
}
TEST(MapTest, InsertEraseTests) {
std::string str = "Mapped";
ft::map<int, std::string> mf1;
std::map<int, std::string> ms1;
mf1.insert(ft::pair<int, std::string>(16, str));
ms1.insert(std::pair<int, std::string>(16, str));
mf1.insert(ft::pair<int, std::string>(23, str));
ms1.insert(std::pair<int, std::string>(23, str));
ft::map<int, std::string> mf2;
std::map<int, std::string> ms2;
mf2.insert(mf1.begin(), mf1.end());
ms2.insert(ms1.begin(), ms1.end());
ft::map<int, std::string>::iterator itf = mf2.begin();
std::map<int, std::string>::iterator its = ms2.begin();
while (itf != mf2.end()) {
ASSERT_TRUE((itf->first == its->first) && (itf->second == its->second)) << "Insert iterator: Failed with ft: " << itf->first << " " << itf->second << " std: " << its->first << " " << its->second << "\n";
itf++;
its++;
}
mf2.erase(mf2.begin());
ms2.erase(ms2.begin());
itf = mf2.begin();
its = ms2.begin();
while (itf != mf2.end()) {
ASSERT_TRUE((itf->first == its->first) && (itf->second == its->second)) << "Erase iterator: Failed with ft: " << itf->first << " " << itf->second << " std: " << its->first << " " << its->second << "\n";
itf++;
its++;
}
mf2.erase(23);
ms2.erase(23);
ASSERT_TRUE(mf2.size() == ms2.size());
}
TEST(MapTest, SwapTests) {
std::string str = "Mapped";
ft::map<int, std::string> mf1;
std::map<int, std::string> ms1;
mf1.insert(ft::pair<int, std::string>(16, str));
ms1.insert(std::pair<int, std::string>(16, str));
mf1.insert(ft::pair<int, std::string>(23, str));
ms1.insert(std::pair<int, std::string>(23, str));
ft::map<int, std::string> mf2;
std::map<int, std::string> ms2;
mf2.insert(ft::pair<int, std::string>(12, str));
ms2.insert(std::pair<int, std::string>(12, str));
mf2.insert(ft::pair<int, std::string>(89, str));
ms2.insert(std::pair<int, std::string>(89, str));
mf2.swap(mf1);
ms2.swap(ms1);
ft::map<int, std::string>::iterator itf = mf2.begin();
std::map<int, std::string>::iterator its = ms2.begin();
while (its != ms2.end()) {
ASSERT_TRUE((itf->first == its->first) && (itf->second == its->second)) << "Insert iterator: Failed with ft: " << itf->first << " " << itf->second << " std: " << its->first << " " << its->second << "\n";
itf++;
its++;
}
}
TEST(MapTest, FindTests) {
std::string str = "Mapped";
ft::map<int, std::string> mf1;
std::map<int, std::string> ms1;
mf1.insert(ft::pair<int, std::string>(16, str));
ms1.insert(std::pair<int, std::string>(16, str));
mf1.insert(ft::pair<int, std::string>(23, str));
ms1.insert(std::pair<int, std::string>(23, str));
ft::map<int, std::string>::iterator itf = mf1.find(16);
std::map<int, std::string>::iterator its = ms1.find(16);
ASSERT_TRUE((itf->first == its->first) && (itf->second == its->second)) << "Find: Failed with ft: " << itf->first << " " << itf->second << " std: " << its->first << " " << its->second << "\n";
}
TEST(MapTest, CountTest) {
std::string str = "Mapped";
ft::map<int, std::string> mf1;
std::map<int, std::string> ms1;
mf1.insert(ft::pair<int, std::string>(16, str));
ms1.insert(std::pair<int, std::string>(16, str));
mf1.insert(ft::pair<int, std::string>(23, str));
ms1.insert(std::pair<int, std::string>(23, str));
ASSERT_TRUE(mf1.count(16) == ms1.count(16)) << "Count: Failed with ft: " << mf1.count(16) << " std: " << ms1.count(16) << "\n";
}
TEST(MapTest, BoundTest) {
std::string str = "Mapped";
ft::map<int, std::string> mf1;
std::map<int, std::string> ms1;
mf1.insert(ft::pair<int, std::string>(16, str));
ms1.insert(std::pair<int, std::string>(16, str));
mf1.insert(ft::pair<int, std::string>(23, str));
ms1.insert(std::pair<int, std::string>(23, str));
ft::map<int, std::string>::iterator itf = mf1.lower_bound(16);
std::map<int, std::string>::iterator its = ms1.lower_bound(16);
ASSERT_TRUE((itf->first == its->first) && (itf->second == its->second)) << "Lower Bound: Failed with ft: " << itf->first << " " << itf->second << " std: " << its->first << " " << its->second << "\n";
itf = mf1.upper_bound(16);
its = ms1.upper_bound(16);
ASSERT_TRUE((itf->first == its->first) && (itf->second == its->second)) << "Upper Bound: Failed with ft: " << itf->first << " " << itf->second << " std: " << its->first << " " << its->second << "\n";
}
TEST(MapTest, EqualRangeTest) {
std::string str = "Mapped";
ft::map<int, std::string> mf1;
std::map<int, std::string> ms1;
mf1.insert(ft::pair<int, std::string>(16, str));
ms1.insert(std::pair<int, std::string>(16, str));
mf1.insert(ft::pair<int, std::string>(23, str));
ms1.insert(std::pair<int, std::string>(23, str));
ft::pair<ft::map<int, std::string>::iterator, ft::map<int, std::string>::iterator>itpair = mf1.equal_range(16);
std::pair<std::map<int, std::string>::iterator, std::map<int, std::string>::iterator>stitpair = ms1.equal_range(16);
ASSERT_TRUE((itpair.first->first == stitpair.first->first) && (itpair.first->second == stitpair.first->second) && (itpair.second->first == stitpair.second->first) && (itpair.second->second == stitpair.second->second)) << "Equal range: Failed with ft: " << itpair.first->first << " " << itpair.first->second << "; " << itpair.second->first << " " << itpair.second->second << " std: " << stitpair.first->first << " " << stitpair.first->second << "; " << stitpair.second->first << " " << stitpair.second->second << "\n";
}
| true |
7e4c18857c24a7e8d0b39ffc796be294644e187a | C++ | stroupo/hash-maps | /tests/ranges.cc | UTF-8 | 1,183 | 3.34375 | 3 | [] | no_license | #include <doctest/doctest.h>
#include <iostream>
#include <iterator>
#include <type_traits>
using namespace std;
template <typename T, bool Constant>
struct range_iterator {
range_iterator(T n) : n_{n} {}
range_iterator& operator++() { return (++n_, *this); }
T operator*() const { return n_; }
bool operator==(range_iterator it) const { return n_ == it.n_; }
bool operator!=(range_iterator it) const { return !(*this == it); }
T n_;
};
struct range {
using value_type = int;
using iterator = range_iterator<int, false>;
using const_iterator = range_iterator<int, true>;
range(int first, int last) : first_{first}, last_{last} {}
iterator begin() { return first_; }
iterator end() { return last_; }
int first_;
int last_;
};
template <int First, int Last>
struct static_range {
// using value_type = int;
using iterator = range_iterator<int, false>;
using const_iterator = range_iterator<int, true>;
iterator begin() { return First; }
iterator end() { return Last; }
};
TEST_CASE("Ranges") {
for (auto x : range{1, 10}) cout << x << "\t";
cout << endl;
for (auto x : static_range<1, 10>{}) cout << x << "\t";
cout << endl;
} | true |
7359e619cd9656c1a287c08fc0809e9e9369e493 | C++ | wafemand/list-testing | /postnikova_anastasia.h | UTF-8 | 6,743 | 3.53125 | 4 | [] | no_license | #ifndef LIST_MY_LIST_H
#define LIST_MY_LIST_H
#include <memory>
#include <list>
template <typename T>
struct my_list {
private:
struct node_without_data {
node_without_data *left;
node_without_data *right;
node_without_data() : left(nullptr), right(nullptr) {}
node_without_data(node_without_data *left, node_without_data *right) : left(left), right(right) {}
virtual ~node_without_data() {}
};
struct node : node_without_data {
T data;
node(const T &value, node_without_data *left, node_without_data *right): node_without_data(left, right), data(value) {}
~node() {}
};
node_without_data fake_node;
public:
my_list();
my_list(const my_list &other);
~my_list();
bool empty() const;
void clear();
void push_back(const T& value);
T pop_back();
T& back();
void push_front(const T& value);
T pop_front();
T& front();
private:
template <typename V>
struct my_iterator : std::iterator<std::bidirectional_iterator_tag, V, ptrdiff_t, V*, V&> {
node_without_data *cur_pos;
my_iterator() : cur_pos(nullptr) {}
explicit my_iterator(node_without_data *cur_pos) : cur_pos(cur_pos) {}
my_iterator(const my_iterator &it) : cur_pos(it.cur_pos) {}
my_iterator& operator++() {
cur_pos = cur_pos->right;
return *this;
}
my_iterator operator++(int) {
my_iterator result = *this;
++(*this);
return result;
}
my_iterator& operator--() {
cur_pos = cur_pos->left;
return *this;
}
my_iterator operator--(int) {
my_iterator result = *this;
--(*this);
return result;
}
bool operator==(my_iterator const &other) const {
return cur_pos == other.cur_pos;
}
bool operator!=(my_iterator const &other) const {
return !(*this == other);
}
T& operator*() const {
return static_cast<node*>(cur_pos)->data;
}
};
public:
typedef my_iterator<T> iterator;
typedef std::reverse_iterator<iterator> reverse_iterator;
typedef my_iterator<T const> const_iterator;
typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
iterator begin() {
return iterator(fake_node.right);
}
iterator end() {
return iterator(&fake_node);
}
reverse_iterator rbegin() {
return reverse_iterator(end());
}
reverse_iterator rend() {
return reverse_iterator(begin());
}
const_iterator begin() const {
return const_iterator(fake_node.right);
}
const_iterator end() const {
return const_iterator(&fake_node);
}
const_reverse_iterator rbegin() const {
return const_reverse_iterator(end());
}
const_reverse_iterator rend() const {
return reverse_iterator(begin());
}
// before pos
iterator insert(iterator pos, T const &value) {
node *new_node = new node(value, pos.cur_pos->left, pos.cur_pos);
pos.cur_pos->left->right = new_node;
pos.cur_pos->left = new_node;
return iterator(new_node);
}
iterator erase(iterator pos) {
node *cur_node = static_cast<node*>(pos.cur_pos);
cur_node->left->right = cur_node->right;
cur_node->right->left = cur_node->left;
iterator result(cur_node->right);
delete cur_node;
return result;
}
iterator erase(iterator beg_pos, iterator end_pos) {
iterator tmp(beg_pos);
while (beg_pos != end_pos) {
erase(tmp++);
}
return end_pos;
}
void splice(iterator pos, my_list &other, iterator beg_pos, iterator end_pos) {
node_without_data *cur_node = pos.cur_pos;
iterator end_p = end_pos;
node_without_data *tmp = end_pos.cur_pos->left;
beg_pos.cur_pos->left->right = end_pos.cur_pos;
end_p.cur_pos->left->right = pos.cur_pos;
end_pos.cur_pos->left = beg_pos.cur_pos->left;
beg_pos.cur_pos->left = pos.cur_pos->left;
pos.cur_pos->left->right = beg_pos.cur_pos;
pos.cur_pos->left = tmp;
}
template <typename TT>
friend void swap(my_list<TT> &first, my_list<TT> &second);
};
template <typename T>
my_list<T>::my_list() : fake_node() {
fake_node.left = fake_node.right = &fake_node;
}
template <typename T>
my_list<T>::my_list(const my_list &other) {
my_list();
for (auto i = other.begin(); i != other.end(); i++) {
push_back(*i);
}
}
template <typename T>
my_list<T>::~my_list() {
clear();
}
template <typename T>
void my_list<T>::clear() {
while (!empty()) {
pop_back();
}
}
template <typename T>
bool my_list<T>::empty() const {
return &fake_node == fake_node.left;
}
template <typename T>
void my_list<T>::push_back(const T &value) {
node *new_node = new node(value, fake_node.left, &fake_node);
fake_node.left->right = new_node;
fake_node.left = new_node;
}
template <typename T>
T& my_list<T>::back() {
return static_cast<node *>(fake_node.left)->data;
}
template <typename T>
T my_list<T>::pop_back() {
node *cur_node = static_cast<node*>(fake_node.left);
T data(cur_node->data);
fake_node.left = cur_node->left;
cur_node->left->right = &fake_node;
delete cur_node;
return data;
}
template <typename T>
void my_list<T>::push_front(const T &value) {
node *new_node = new node(value, &fake_node, fake_node.right);
fake_node.right->left = new_node;
fake_node.right = new_node;
}
template <typename T>
T& my_list<T>::front() {
return static_cast<node *>(fake_node.right)->data;
}
template <typename T>
T my_list<T>::pop_front() {
node *cur_node = static_cast<node*>(fake_node.right);
T data(cur_node->data);
fake_node.right = cur_node->right;
cur_node->right->left = &fake_node;
delete cur_node;
return data;
}
template <typename TT>
void swap(my_list<TT> &first, my_list<TT> &second) {
typename my_list<TT>::node_without_data *f_l = first.fake_node.left,
*f_r = second.fake_node.right,
*s_l = second.fake_node.left,
*s_r = second.fake_node.right;
first.fake_node.left->right = &second.fake_node;
first.fake_node.left = s_l;
first.fake_node.right->left = &second.fake_node;
first.fake_node.right = s_r;
second.fake_node.left->right = &first.fake_node;
second.fake_node.left = f_l;
second.fake_node.right->left = &first.fake_node;
second.fake_node.right = f_r;
}
#endif //LIST_MY_LIST_H
| true |
664c1eebbcf6664bc935adc5fd244499c95a816e | C++ | ANARCYPHER/coding-interview-solutions | /src/cpp/binary-tree-next-pointers/bst.cpp | UTF-8 | 3,541 | 4.25 | 4 | [] | no_license | /**
* Given a binary tree:
*
* struct TreeLinkNode {
* TreeLinkNode *left;
* TreeLinkNode *right;
* TreeLinkNode *next;
* }
*
* Populate each next pointer to point to its next right node. If there is no
* next right node, the next pointer should be set to NULL.
*
* Note: each "pointer" is already initialized with NULL.
*
* Explanation: the secret is to use the previous level that you just finished
* completing the "next" pointers to complete the next "next" pointers.
* So, you start with the root and you make the next pointer of the left child
* point to the right child. Then, you move to the next level and you get the
* nodes of this next level traversing the previous one using the next pointers
* you just filled.
*
* In the code below I make the "next" pointer of the left child point to the
* right child in one iteration. Then in this same iteration I store in a
* variable the address of the "next" pointer of the right child if this right
* child is not NULL, otherwise I store the address of the "next" pointer of the
* left child. So, in the next iteration I can use this address to fill this
* "next" pointer with the node I'm currently at. Example:
*
* o o'
* / \ / \
* l r l' r'
*
* In one iteration we are checking the children of o, in the next one we are
* checking the children of o'. So in the next iteration I need to make r point
* to l', that is why I store the adress of the "next" pointer of r to fill it
* in the next iteration.
*/
#include <iostream>
#include <queue>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode *next;
TreeNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
};
void populateNextPointers(TreeNode *root) {
TreeNode *curr = root, *newCurr = NULL;
TreeNode **n = NULL;
while (curr != NULL) {
while (curr != NULL) {
// Get the first not NULL node of this level.
if (newCurr == NULL) newCurr = curr->left ? curr->left : curr->right;
// If we stored a pointer to a "next" pointer try to fill it with a not
// NULL node.
if (n != NULL) *n = curr->left ? curr->left : curr->right;
// If we have a left node try to point it to the right node.
if (curr->left) curr->left->next = curr->right;
// Store the pointer to the "next" pointer so we can fill it with the next
// not NULL node.
if (curr->right) {
n = &(curr->right->next);
}
else if (curr->left) {
n = &(curr->left->next);
}
curr = curr->next;
}
// Move to next level
curr = newCurr;
newCurr = NULL;
n = NULL;
}
}
void specialTraversal(TreeNode *root) {
TreeNode *curr = root, *newLeft = NULL;
while (curr != NULL) {
newLeft = curr->left;
while (curr != NULL) {
cout << curr->val << " ";
curr = curr->next;
}
curr = newLeft;
}
}
int main () {
TreeNode *root = NULL;
// // Complete binary tree
// root = new TreeNode(1);
// root->left = new TreeNode(2);
// root->right = new TreeNode(3);
// root->left->left = new TreeNode(4);
// root->left->right = new TreeNode(5);
// root->right->left = new TreeNode(6);
// root->right->right = new TreeNode(7);
// Not a omplete binary tree
root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->left->left = new TreeNode(4);
root->right->right = new TreeNode(7);
populateNextPointers(root);
specialTraversal(root);
return 0;
} | true |
7112fb40bc70c61dd8b01c3d35a8cc16b0806a32 | C++ | Andrey562895/ADS-4 | /test/tests.cpp | UTF-8 | 771 | 2.828125 | 3 | [] | no_license | #include "gtest/gtest.h"
#include <string>
#include "tpqueue.h"
TEST(lab4,test1_1)
{
TPQueue<SYM> pqueue;
pqueue.push(SYM{'a',4});
pqueue.push(SYM{'b',7});
SYM c1=pqueue.pop();
SYM c2=pqueue.pop();
ASSERT_EQ(c1.ch,'b');
ASSERT_EQ(c2.ch,'a');
}
TEST(lab4,test1_2)
{
TPQueue<SYM> pqueue;
pqueue.push(SYM{'a',4});
pqueue.push(SYM{'b',4});
SYM c1=pqueue.pop();
SYM c2=pqueue.pop();
ASSERT_EQ(c1.ch,'a');
ASSERT_EQ(c2.ch,'b');
}
TEST(lab4,test1_3)
{
TPQueue<SYM> pqueue;
pqueue.push(SYM{'a',4});
pqueue.push(SYM{'b',4});
pqueue.push(SYM{'c',9});
SYM c1=pqueue.pop();
SYM c2=pqueue.pop();
SYM c3=pqueue.pop();
ASSERT_EQ(c1.ch,'c');
ASSERT_EQ(c2.ch,'a');
ASSERT_EQ(c3.ch,'b');
} | true |
85c59fd741372916d3c4c60e790a76894a253f4e | C++ | AnantaYudica/simple | /include/iter/RandomAccess.h | UTF-8 | 12,687 | 2.53125 | 3 | [
"MIT"
] | permissive | #ifndef ITERATOR_RANDOM_ACCESS_H_
#define ITERATOR_RANDOM_ACCESS_H_
#include <iterator>
#include "../id_const/Validation.h"
#include "../Handle.h"
#include "../Iterator.h"
#include "Bidirectional.h"
namespace simple
{
namespace iter
{
struct RandomAccessIDConst : simple::iter::BidirectionalIDConst {};
struct AdditionHandleIDConst : simple::iter::RandomAccessIDConst {};
struct SubtractionHandleIDConst : simple::iter::RandomAccessIDConst {};
struct DistanceHandleIDConst : simple::iter::RandomAccessIDConst {};
template<typename Tidc, typename T, typename D = std::ptrdiff_t,
typename P = T*, typename R = T&,
typename C = std::random_access_iterator_tag,
typename IT = std::iterator<C, T, D, P, R>>
class RandomAccess :
public simple::iter::Bidirectional<Tidc, T, D, P, R, C, IT>,
public simple::Handle<simple::iter::
AdditionHandleIDConst, void, P*, const D&>,
public simple::Handle<simple::iter::
SubtractionHandleIDConst, void, P*, const D&>,
public simple::Handle<simple::iter::
DistanceHandleIDConst, D, const P, const P>,
public virtual simple::Iterator<Tidc, C, T, D, P, R, IT>
{
public:
typedef typename simple::id_const::Validation<Tidc>::Type IDConstType;
typedef C CategoryType;
typedef T ValueType;
typedef D DistanceType;
typedef P PointerType;
typedef R ReferenceType;
typedef typename simple::Handle<simple::iter::AdditionHandleIDConst,
void, P*, const D&>::FunctionType AdditionHandleType;
typedef typename simple::Handle<simple::iter::SubtractionHandleIDConst,
void, P*, const D&>::FunctionType SubtractionHandleType;
typedef typename simple::Handle<simple::iter::SubtractionHandleIDConst,
void, P*, const D&>::FunctionType DistanceHandleType;
private:
typedef simple::iter::Bidirectional<Tidc,
T, D, P, R, C, IT> BaseBidirectionalType;
typedef simple::Handle<simple::iter::AdditionHandleIDConst,
void, P*, const D&> BaseAdditionHandleType;
typedef simple::Handle<simple::iter::SubtractionHandleIDConst,
void, P*, const D&> BaseSubtractionHandleType;
typedef simple::Handle<simple::iter::DistanceHandleIDConst,
D, const P, const P> BaseDistanceHandleType;
typedef simple::Iterator<Tidc, C, T, D, P, R, IT> BaseIteratorType;
private:
void AdditionDefaultHandle(P* d_ptr, const D& distance);
void SubtractionDefaultHandle(P* d_ptr, const D& distance);
D DistanceDefaultHandle(const P a, const P b);
private:
DistanceHandleType m_distance_handle;
public:
RandomAccess();
RandomAccess(P ptr);
RandomAccess(const RandomAccess<Tidc, T, D, P, R, C, IT>& cpy);
RandomAccess(RandomAccess<Tidc, T, D, P, R, C, IT>&& mov);
public:
void Set(...) = delete;
void SetAdditionHandle(AdditionHandleType addition_handle);
void SetAdditionHandle(const RandomAccess<Tidc, T, D, P, R, C, IT>& cpy);
void SetSubtractionHandle(SubtractionHandleType subtraction_handle);
void SetSubtractionHandle(const RandomAccess<Tidc, T, D, P, R, C, IT>& cpy);
void SetDistanceHandle(DistanceHandleType distance_handle);
void SetDistanceHandle(const RandomAccess<Tidc, T, D, P, R, C, IT>& cpy);
void SetHandle(const RandomAccess<Tidc, T, D, P, R, C, IT>& cpy);
public:
RandomAccess<Tidc, T, D, P, R, C, IT>&
operator=(const RandomAccess<Tidc, T, D, P, R, C, IT>& cpy);
RandomAccess<Tidc, T, D, P, R, C, IT>& operator=(P ptr);
RandomAccess<Tidc, T, D, P, R, C, IT>& operator+=(const D& off);
RandomAccess<Tidc, T, D, P, R, C, IT>& operator-=(const D& off);
RandomAccess<Tidc, T, D, P, R, C, IT> operator+(const D& off) const;
RandomAccess<Tidc, T, D, P, R, C, IT> operator-(const D& off) const;
D operator-(const RandomAccess<Tidc, T, D, P, R, C, IT>& b) const;
R operator[](const D& off);
const R operator[](const D& off) const;
bool operator<(const RandomAccess<Tidc, T, D, P, R, C, IT>& b) const;
bool operator>(const RandomAccess<Tidc, T, D, P, R, C, IT>& b) const;
bool operator<=(const RandomAccess<Tidc, T, D, P, R, C, IT>& b) const;
bool operator>=(const RandomAccess<Tidc, T, D, P, R, C, IT>& b) const;
};
template<typename Tidc, typename T, typename D, typename P,
typename R, typename C, typename IT>
void RandomAccess<Tidc, T, D, P, R, C, IT>::
AdditionDefaultHandle(P* d_ptr, const D& distance)
{
if (d_ptr != nullptr)
*d_ptr += distance;
}
template<typename Tidc, typename T, typename D, typename P,
typename R, typename C, typename IT>
void RandomAccess<Tidc, T, D, P, R, C, IT>::
SubtractionDefaultHandle(P* d_ptr, const D& distance)
{
if (d_ptr != nullptr)
*d_ptr -= distance;
}
template<typename Tidc, typename T, typename D, typename P,
typename R, typename C, typename IT>
D RandomAccess<Tidc, T, D, P, R, C, IT>::
DistanceDefaultHandle(const P a, const P b)
{
return (a > b ? a - b : b - a);
}
template<typename Tidc, typename T, typename D, typename P,
typename R, typename C, typename IT>
RandomAccess<Tidc, T, D, P, R, C, IT>::RandomAccess() :
BaseIteratorType(nullptr),
BaseAdditionHandleType(AdditionDefaultHandle),
BaseSubtractionHandleType(SubtractionDefaultHandle),
BaseDistanceHandleType(DistanceDefaultHandle)
{}
template<typename Tidc, typename T, typename D, typename P,
typename R, typename C, typename IT>
RandomAccess<Tidc, T, D, P, R, C, IT>::RandomAccess(P ptr) :
BaseIteratorType(ptr),
BaseBidirectionalType(ptr),
BaseAdditionHandleType(AdditionDefaultHandle),
BaseSubtractionHandleType(SubtractionDefaultHandle),
BaseDistanceHandleType(DistanceDefaultHandle)
{}
template<typename Tidc, typename T, typename D, typename P,
typename R, typename C, typename IT>
RandomAccess<Tidc, T, D, P, R, C, IT>::
RandomAccess(const RandomAccess<Tidc, T, D, P, R, C, IT>& cpy) :
BaseIteratorType(cpy),
BaseBidirectionalType(cpy),
BaseAdditionHandleType(cpy),
BaseSubtractionHandleType(cpy),
BaseDistanceHandleType(cpy)
{}
template<typename Tidc, typename T, typename D, typename P,
typename R, typename C, typename IT>
RandomAccess<Tidc, T, D, P, R, C, IT>::
RandomAccess(RandomAccess<Tidc, T, D, P, R, C, IT>&& mov) :
BaseIteratorType(mov),
BaseBidirectionalType(mov),
BaseAdditionHandleType(mov),
BaseSubtractionHandleType(mov),
BaseDistanceHandleType(mov)
{}
template<typename Tidc, typename T, typename D, typename P,
typename R, typename C, typename IT>
void RandomAccess<Tidc, T, D, P, R, C, IT>::
SetAdditionHandle(AdditionHandleType addition_handle)
{
BaseAdditionHandleType::operator=(addition_handle);
}
template<typename Tidc, typename T, typename D, typename P,
typename R, typename C, typename IT>
void RandomAccess<Tidc, T, D, P, R, C, IT>::
SetAdditionHandle(const RandomAccess<Tidc, T, D, P, R, C, IT>& cpy)
{
BaseAdditionHandleType::operator=(cpy);
}
template<typename Tidc, typename T, typename D, typename P,
typename R, typename C, typename IT>
void RandomAccess<Tidc, T, D, P, R, C, IT>::
SetSubtractionHandle(SubtractionHandleType subtraction_handle)
{
BaseSubtractionHandleType::operator=(subtraction_handle);
}
template<typename Tidc, typename T, typename D, typename P,
typename R, typename C, typename IT>
void RandomAccess<Tidc, T, D, P, R, C, IT>::
SetSubtractionHandle(const RandomAccess<Tidc, T, D, P, R, C, IT>& cpy)
{
BaseSubtractionHandleType::operator=(cpy);
}
template<typename Tidc, typename T, typename D, typename P,
typename R, typename C, typename IT>
void RandomAccess<Tidc, T, D, P, R, C, IT>::
SetDistanceHandle(DistanceHandleType distance_handle)
{
BaseDistanceHandleType::operator=(distance_handle);
}
template<typename Tidc, typename T, typename D, typename P,
typename R, typename C, typename IT>
void RandomAccess<Tidc, T, D, P, R, C, IT>::
SetDistanceHandle(const RandomAccess<Tidc, T, D, P, R, C, IT>& cpy)
{
BaseDistanceHandleType::operator=(cpy);
}
template<typename Tidc, typename T, typename D, typename P,
typename R, typename C, typename IT>
void RandomAccess<Tidc, T, D, P, R, C, IT>::
SetHandle(const RandomAccess<Tidc, T, D, P, R, C, IT>& cpy)
{
SetAdditionHandle(cpy);
SetSubtractionHandle(cpy);
SetDistanceHandle(cpy);
}
template<typename Tidc, typename T, typename D, typename P,
typename R, typename C, typename IT>
RandomAccess<Tidc, T, D, P, R, C, IT>& RandomAccess<Tidc, T, D, P, R, C, IT>::
operator=(const RandomAccess<Tidc, T, D, P, R, C, IT>& cpy)
{
BaseBidirectionalType::operator=(cpy);
SetHandle(cpy);
return *this;
}
template<typename Tidc, typename T, typename D, typename P,
typename R, typename C, typename IT>
RandomAccess<Tidc, T, D, P, R, C, IT>&
RandomAccess<Tidc, T, D, P, R, C, IT>::operator=(P ptr)
{
BaseIteratorType::operator=(ptr);
return *this;
}
template<typename Tidc, typename T, typename D, typename P,
typename R, typename C, typename IT>
RandomAccess<Tidc, T, D, P, R, C, IT>&
RandomAccess<Tidc, T, D, P, R, C, IT>::operator+=(const D& off)
{
if (static_cast<BaseAdditionHandleType&>(*this))
BaseAdditionHandleType::operator()(&m_ptr, off);
else
AdditionDefaultHandle(&m_ptr, off);
return *this;
}
template<typename Tidc, typename T, typename D, typename P,
typename R, typename C, typename IT>
RandomAccess<Tidc, T, D, P, R, C, IT>&
RandomAccess<Tidc, T, D, P, R, C, IT>::operator-=(const D& off)
{
if (static_cast<BaseSubtractionHandleType&>(*this))
BaseSubtractionHandleType::operator()(&m_ptr, off);
else
SubtractionDefaultHandle(&m_ptr, off);
return *this;
}
template<typename Tidc, typename T, typename D, typename P,
typename R, typename C, typename IT>
RandomAccess<Tidc, T, D, P, R, C, IT>
RandomAccess<Tidc, T, D, P, R, C, IT>::operator+(const D& off) const
{
RandomAccess<Tidc, T, D, P, R, C, IT> cpy(*this);
cpy += off;
return cpy;
}
template<typename Tidc, typename T, typename D, typename P,
typename R, typename C, typename IT>
RandomAccess<Tidc, T, D, P, R, C, IT>
RandomAccess<Tidc, T, D, P, R, C, IT>::operator-(const D& off) const
{
RandomAccess<Tidc, T, D, P, R, C, IT> cpy(*this);
cpy -= off;
return cpy;
}
template<typename Tidc, typename T, typename D, typename P,
typename R, typename C, typename IT>
D RandomAccess<Tidc, T, D, P, R, C, IT>::
operator-(const RandomAccess<Tidc, T, D, P, R, C, IT>& b) const
{
if (static_cast<BaseDistanceHandleType&>(*this))
return BaseDistanceHandleType::operator()(m_ptr, b.m_ptr);
return DistanceDefaultHandle(m_ptr, b.m_ptr);
}
template<typename Tidc, typename T, typename D, typename P,
typename R, typename C, typename IT>
R RandomAccess<Tidc, T, D, P, R, C, IT>::operator[](const D& off)
{
RandomAccess<Tidc, T, D, P, R, C, IT> cpy(*this);
cpy += off;
return *cpy;
}
template<typename Tidc, typename T, typename D, typename P,
typename R, typename C, typename IT>
const R RandomAccess<Tidc, T, D, P, R, C, IT>::operator[](const D& off) const
{
const RandomAccess<Tidc, T, D, P, R, C, IT> cpy(*this);
cpy += off;
return *cpy;
}
template<typename Tidc, typename T, typename D, typename P,
typename R, typename C, typename IT>
bool RandomAccess<Tidc, T, D, P, R, C, IT>::
operator<(const RandomAccess<Tidc, T, D, P, R, C, IT>& b) const
{
return (b - *this) > 0;
}
template<typename Tidc, typename T, typename D, typename P,
typename R, typename C, typename IT>
bool RandomAccess<Tidc, T, D, P, R, C, IT>::
operator>(const RandomAccess<Tidc, T, D, P, R, C, IT>& b) const
{
return b < *this;
}
template<typename Tidc, typename T, typename D, typename P,
typename R, typename C, typename IT>
bool RandomAccess<Tidc, T, D, P, R, C, IT>::
operator<=(const RandomAccess<Tidc, T, D, P, R, C, IT>& b) const
{
return !(*this > b);
}
template<typename Tidc, typename T, typename D, typename P,
typename R, typename C, typename IT>
bool RandomAccess<Tidc, T, D, P, R, C, IT>::
operator>=(const RandomAccess<Tidc, T, D, P, R, C, IT>& b) const
{
return !(*this < b);
}
}
}
#endif //!ITERATOR_RANDOM_ACCESS_H_
| true |
ea953fd8d2957d78a6f1839df529438603a11072 | C++ | dw-liedji/Cours-alogrithme-et-poo | /exams/code/l1.cpp | UTF-8 | 342 | 3.796875 | 4 | [
"MIT"
] | permissive | #include <iostream>
using namespace std;
class calculer
{
int x, y;
public:
void val(int, int);
int somme()
{
return (x + y);
}
};
void calculer::val(int a, int b)
{
x = a;
y = b;
}
int main()
{
calculer calculer;
calculer.val(5, 10);
cout << "La somme = " << calculer.somme();
return 0;
} | true |
a87d6ba01b48c6d540518f9dcee5e61dafd6b096 | C++ | pmusau17/carma-utils | /carma_utils/include/carma_utils/timers/Timer.h | UTF-8 | 2,404 | 3.03125 | 3 | [
"Apache-2.0"
] | permissive | #pragma once
/*
* Copyright (C) 2020-2021 LEIDOS.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
#include <ros/time.h>
#include <ros/timer.h>
namespace carma_utils
{
namespace timers
{
/**
* @brief A timer class interface which will trigger the provided callback after the requested duration.
* This class provides a mechanism for separating the initialization of ROS style timers from the implementation.
*
* Timer objects can additionally have a user defined ID field to help track timers.
*/
class Timer
{
protected:
uint32_t id_ = 0;
public:
/**
* @brief Destructor
*/
virtual ~Timer(){};
/**
* @brief Initialize a timer to trigger the provided callback after the provided duration
*
* @param duration The duration the timer will wait for before a callback is triggered
* @param callback The callback to trigger after duration has elapsed
* @param oneshot If true the timer will only trigger one. If false it will trigger repeatedly with duration length
* increments
* @param autostart If true the timer will immediately start after this function is called. Otherwise the start()
* function must be called
*/
virtual void initializeTimer(ros::Duration duration, std::function<void(const ros::TimerEvent&)> callback,
bool oneshot = false, bool autostart = true) = 0;
/**
* @brief Start the timer coutdown
*/
virtual void start() = 0;
/**
* @brief Stop the timer coutdown
*/
virtual void stop() = 0;
/**
* @brief Get the timer id. It is up to the user to ensure uniqueness of the ID.
*
* @return The id of this timer
*/
virtual uint32_t getId()
{
return id_;
}
/**
* @brief Set the id of this timer
*
* @param id The id to set
*/
virtual void setId(uint32_t id)
{
id_ = id;
}
};
} // namespace timers
} // namespace carma_utils | true |
95e1a4129be89bcc9f0322be95feca8c4b7ef334 | C++ | llGuy/msdev | /cpp/gl_math/vector_output.h | UTF-8 | 628 | 2.8125 | 3 | [] | no_license | #ifndef VECTOR_OUTPUT_HEADER
#define VECTOR_OUTPUT_HEADER
#include <algorithm>
#include <iostream>
#include <iterator>
#include "vector.h"
#include "matrix.h"
template<typename _Ty, uint32_t _Dm>
std::ostream& operator<<(std::ostream& os, vec<_Ty, _Dm>& v)
{
std::copy(v.Begin(), v.End(), std::ostream_iterator<_Ty>(os, " "));
return os;
}
template<typename _Ty, uint32_t _Dm>
std::ostream& operator<<(std::ostream& os, matrix<_Ty, _Dm>& m)
{
uint32_t index = 0;
std::for_each(m.Begin(), m.End(), [&](_Ty& v) { os << v << ((index++) % _Dm == _Dm - 1 ? "\n" : " "); });
return os;
}
#endif
| true |
4281a1d06f240235ef0dbd1f8fb8280c6a922e0e | C++ | changtingwai/leetcode | /House Robber/House Robber/源.cpp | UTF-8 | 486 | 2.953125 | 3 | [] | no_license | #include <iostream>
#include <stdlib.h>
#include <vector>
using namespace std;
class Solution {
public:
int rob(vector<int>& nums) {
if(nums.size()==0)
return 0;
int i;
int dp[100];
dp[0]=nums[0];
dp[1]=max(nums[0],nums[1]);
for(i=2;i<nums.size();i++)
dp[i]=max(nums[i]+dp[i-2],dp[i-1]);
return dp[nums.size()-1];
}
};
int main()
{
Solution s;
int a[]={1,2};
vector<int> v(a,a+2);
cout<<s.rob(v);
system("pause");
return 0;
} | true |
ef129c9915097a80a34a2ff5377d15a4e4d5da76 | C++ | jitingcn/c_study | /codes/c++ primer plus/3.7.1 身高单位转换.cpp | UTF-8 | 570 | 4 | 4 | [] | no_license | // 3.7.1
// 用户使用一个整数指出自己的身高(单位为英寸),然后将身高转换为英尺和英寸.
// 使用下划线字符指示输入位置.并使用一个const符号常量来表示转换因子
// 1 foot = 12 inch
#include <iostream>
using namespace std;
int main(){
const int inch = 12;
int inchs;
int in;
int ft;
cout << "Please enter your height:______(in)\b\b\b\b\b\b\b\b\b\b";
cin >> inchs;
in = inchs % inch;
ft = inchs / inch;
cout << "Ok, your height is " << ft << " ft " << in << " in.\n";
return 0;
} | true |
34a233c438676e3d0c4bc6f27c28d4f16072240d | C++ | ggyool/study-alone | /ps/boj_cpp/11576.cpp | UTF-8 | 493 | 2.6875 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
int main(void){
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int a, b, n;
cin >> a >> b >> n;
int sum=0, num;
for(int i=0; i<n; ++i){
cin >> num;
sum = sum*a + num;
}
vector<int> v;
while(sum>0){
v.push_back(sum%b);
sum /= b;
}
int len = v.size();
for(int i=0; i<len; ++i){
cout << v[len-i-1] << ' ';
}
return 0;
} | true |
0858cdb7f7424f444cff0accfb539aabb58f9695 | C++ | krupa852/Decision_Tree | /decision_tree.cpp | UTF-8 | 17,004 | 2.703125 | 3 | [] | no_license | #include <unordered_map>
#include <set>
#include <list>
#include <algorithm>
#include<iostream>
#include <cmath>
#include <vector>
#include <fstream>
#include <sstream>
#include<map>
#include <string>
class node;
using namespace std;
vector<string> Attributes;
vector<int> attribute_num;
int attribute_no =0;
//find binary attributes in data
class binary_attribute
{
public:
bool binary;
map<string, int> val_count;
void init()
{
binary = false;
}
};
class target_info
{
public:
int count_true;//the number of True for target attribute for records with the value
int count_false;//the number of False for target attribute for records with the value
int count;//the total number of occurence for the value of the specified attribtue
void init()
{
count =0;count_true =0;count_false =0;
}
};
class child_node
{
public:
string branch;
node *child;
};
class node
{
public:
string name;
vector<child_node> children;
void print() {
cout << "name:" << this->name << "\nlen:" << this->name.length() << endl;
}
};
vector<binary_attribute> attr_binary;
vector<vector<string>> Read_File(string file_name);
bool inputchoice_valid(vector<int> possible_choice_no,int choice_no);
node Decision_Tree(vector<vector<string>> datatable, int target_num, string target, vector<int> attribute_list,vector<string> attributes, vector<string> target_value);
string highest_count_targetattr_val(vector<vector<string>> datatable, int target_num);
int find_attribute_for_bestsplit(vector<vector<string>> ,int target_num, vector<int> attribute_list,vector<string> target_value);
float count_before_entropy(vector<vector<string>> datatable, int target_num);
float count_after_entropy(vector<vector<string>> datatable, int attribute_num, int target_num,vector<string> target_value);
void split(vector<vector<string>> datatable,map<string, vector<int>> &split_datatable, int attribute_num,vector<child_node> &children);
void print_split_datatable(vector<vector<string>> datatable,map<string, vector<int>> split_datatable,node Node);
vector<vector<string>> form_datatable_by_index(vector<vector<string>> datatable, vector<int> index_vector);
void print_datatable(vector<vector<string>> new_datatable);
void Output_Tree(ofstream & output, node root, string target, vector<string> target_value,int &num);
int delete_pos(int attribute_num,vector<int> attribute_list);
vector<vector<string>> Read_File(string file_name)
{
ifstream infile(file_name);
vector<vector<string>> attributevals;
string attribute_names;
string word;
vector<vector<string>> info;
int record_num =0;
string line;
/* code to extract features/Attribute names in file */
getline(infile, attribute_names);
istringstream ss(attribute_names);
while( ss >> word)
{
Attributes.push_back(word);
attribute_num.push_back(attribute_no++);
};
string Class_Label = Attributes[Attributes.size()-1];
/* for(int i=0;i<Attributes.size();i++)
cout<<Attributes[i]<<endl;
for(int i=0;i<attribute_num.size();i++)
cout<<attribute_num[i]<<endl;*/
for(int i =0; i < attribute_no; i++)
{
binary_attribute temp;
attr_binary.push_back(temp);
}
/*code to extract attribute values from file */
while(getline(infile, line))//read file line by line
{
istringstream iss(line);
int iterate_attribute =0;
vector<string> tokens;
copy(istream_iterator<string>(iss),
istream_iterator<string>(),
back_inserter(tokens));
vector<string> attributeval;
for(int i=0;i<tokens.size();i++)
{
if(attr_binary[iterate_attribute].val_count.find(tokens[i]) == attr_binary[iterate_attribute].val_count.end()){//not found
attr_binary[iterate_attribute].val_count[tokens[i]] = 1;
}else{
attr_binary[iterate_attribute].val_count[tokens[i]]++;
}
iterate_attribute++;
attributeval.push_back((tokens[i]));
}
attributevals.push_back(attributeval);
}
//get binary attributes
for(int i = 0; i < attribute_no; i++){
if(attr_binary[i].val_count.size()==2)
{
attr_binary[i].binary = true;
}
else
{
attr_binary[i].binary = false;
}
}
//print datatable
/*for(int i=0;i<attributevals.size();i++)
{
for(int j=0;j<attributevals[i].size();j++)
{cout<<attributevals[i][j];}
cout<<endl;
}*/
return attributevals;
}
bool inputchoice_valid(vector<int> possible_choice_no,int choice_no){
for(auto i = possible_choice_no.begin(); i!=possible_choice_no.end();i++){
if((*i)==choice_no){
return true;
}
}
return false;
}
//check whether all records in the datatable belongs to one catergory or not
bool check_label(vector<vector<string>> datatable,int target_num, string &name)
{
for(auto i = datatable.begin(); i != datatable.end();i++)
{
if(i == datatable.begin())
{
name = (*i)[target_num];
}
string temp = (*i)[target_num];
if(name!=temp)
{
return false;
}
}
return true;
}
node Decision_Tree(vector<vector<string>> datatable, int target_num,string target, vector<int> attribute_list,vector<string> attributes, vector<string> target_value){
node *Node;
Node = new node;
string name;
if(check_label(datatable,target_num,name))
{ //all records have the same label
Node->name = name;
}
else if(attribute_list.size() == 0)
{ //the attribute list is empty
Node->name = highest_count_targetattr_val(datatable,target_num);
}
else
{ // determine the attribute test condition
//get attribute which gets best split
int attribute_num = find_attribute_for_bestsplit(datatable,target_num,attribute_list, target_value);
Node->name = attributes[attribute_num];
//split the datatable based on the determined attribute and name new branch.
map<string, vector<int>> split_datatable;//first represents the value of the attribute. second represents the index of records in original datatable with the value for the attribute
split(datatable,split_datatable,attribute_num,Node->children);
// print_split_datatable(datatable, split_datatable,*Node);
//remove the used attribute from attribute list and attributes
int position = delete_pos(attribute_num,attribute_list);
attribute_list.erase(attribute_list.begin()+ position);
//test stopping point for each splitted datatable
for(auto v: split_datatable)
{//for each splitted datatable
//find the child_node
auto k =Node->children.begin();
for(auto j =Node->children.begin(); j != Node->children.end(); j++)
{
if((*j).branch == v.first)
{
k = j;
break;
}
}
//form new datatable using index
vector<vector<string>> new_datatable = form_datatable_by_index(datatable, v.second);
//print_datatable(new_datatable);
node *child_Node;
child_Node = new node;
string name;
if(check_label(new_datatable,target_num,name))
{//all records in the current splitted databases belong to the same label
child_Node->name = name;
(*k).child = child_Node;
}
else if(attribute_list.size()==0)
{//attribute list is empty
child_Node->name = highest_count_targetattr_val(new_datatable, target_num);
(*k).child = child_Node;
}
else if(new_datatable.size()==0)
{//no sample
child_Node->name = "no sample";
(*k).child = child_Node;
}
else
{//recursively call Decision_Tree
(*child_Node) = Decision_Tree(new_datatable, target_num,target,attribute_list, attributes, target_value);
(*k).child = child_Node;
}
}
}
return *Node;
}
//get the position of the element attribute_num in a vector
int delete_pos(int attribute_num,vector<int> attribute_list)
{
int position = -1;
for(auto i = attribute_list.begin(); i!=attribute_list.end();i++)
{
position++;
if((*i)==attribute_num){
return position;
}
}
cout <<"failed to find the position of the attribute to be deleted"<<endl;
return -1;
}
//form datatable using index
vector<vector<string>> form_datatable_by_index(vector<vector<string>> datatable, vector<int> index_vector)
{
vector<vector<string>> new_datatable;
for(auto i = index_vector.begin(); i != index_vector.end(); i++)
{
auto j = datatable.begin()+(*i);
vector<string> record;
for(auto m=(*j).begin(); m != (*j).end(); m++)
{
record.push_back(*m);
}
new_datatable.push_back(record);
}
return new_datatable;
}
//split datatable based on the determined attribute and store the newly splitted datatable in the form of index of the original datatable and name branch.
void split(vector<vector<string>> datatable,map<string, vector<int>> &split_datatable, int attribute_num, vector<child_node> &children)
{
int index= 0;
for(auto i = datatable.begin(); i != datatable.end(); i++)
{ //scan original datatable
if(split_datatable.find((*i)[attribute_num])==split_datatable.end())
{ //the value of the attribute has not been found yet
child_node child_Node_ref;
child_Node_ref.branch = (*i)[attribute_num];//name the branch
children.push_back(child_Node_ref);
}
split_datatable[(*i)[attribute_num]].push_back(index);//save records to corresponding splitted datatable
index++;
}
}
//for testing the splitted datatables
void print_split_datatable(vector<vector<string>> datatable,map<string, vector<int>> split_datatable, node Node)
{
for(auto v: split_datatable)
{
cout << "datatable "<< v.first<<":"<< endl;
for(auto i = v.second.begin(); i != v.second.end(); i++)
{
for(int j =0; j< 4;j++)
{
cout << datatable[*i][j]<< " ";
}
cout << endl;
}
}
}
//for testing datatable
void print_datatable(vector<vector<string>> new_datatable)
{
cout << "print datatable:"<<endl;
for(auto i = new_datatable.begin(); i != new_datatable.end(); i++)
{
for(auto j = (*i).begin(); j != (*i).end(); j++){
cout << (*j)<<" ";
}
cout << endl;
}
}
//get the name of the highest count targetattribute value
string highest_count_targetattr_val(vector<vector<string>> datatable, int target_num)
{
//records the occurence of different attribute's values
map<string,int> values;
for(auto i = datatable.begin(); i != datatable.end();i++)
{
if(values.find((*i)[target_num])==values.end())
{ //the value is not found
values[(*i)[target_num]] = 1;
}else
{
values[(*i)[target_num]]++;
}
}
//get the value which occurs most frequently
int count =0 ;
string high_cnt_val;
for(auto v:values)
{
if(v.second> count)
{
count = v.second;
high_cnt_val = v.first;
}
}
return high_cnt_val;
}
//get attribute which gets best split
int find_attribute_for_bestsplit(vector<vector<string>> datatable,int target_num, vector<int> attribute_list, vector<string> target_value){
map<int, float> info_gain;//store information gain for all attributes of attribute list
float before_entropy = count_before_entropy(datatable,target_num);
float after_entropy = 0;
for(auto i = attribute_list.begin(); i != attribute_list.end(); i++)
{
//count and save information gain for each of the attribute in attribute list
after_entropy = count_after_entropy(datatable, (*i), target_num, target_value);
info_gain[(*i)] = before_entropy-after_entropy;
}
//find the best split attribute by the highest information gain
int best_split_attribute_num=-1;
float max_info_gain =0;
for(auto v: info_gain){
if(v.second>=max_info_gain)
{
max_info_gain = v.second;
best_split_attribute_num=v.first;
}
}
if(best_split_attribute_num==-1)
{
cout << "not found best split"<<endl;
if(attribute_list.size()==0)
cout << "attribute_list is empty"<<endl;
}
return best_split_attribute_num;
}
//calculate entropy before splitting
float count_before_entropy(vector<vector<string>> datatable, int target_num)
{
float bef_entropy_value = 0.0;
map<string, int> before;//first:value for target,second:count its occurence
int count=0;//store the number of records in the datatable
for(auto i = datatable.begin(); i != datatable.end(); i++)
{//calculate the occurence of possible value for target attribute
if(before.find((*i)[target_num])==before.end())
{
before[(*i)[target_num]] =1;
}
else
{
before[(*i)[target_num]]++;
}
count++;
}
/* for (auto itr = before.begin(); itr != before.end(); itr++)
cout << itr->first
<< '\t' << itr->second << '\n';*/
//calculate the probability of all possible value of target attribute
for(auto v: before)
{
float probability = float(v.second)/float(count);
if(probability == 0)
{
;
}
else
{
bef_entropy_value += -(probability)*log2(probability);
}
}
return bef_entropy_value;
}
float count_after_entropy(vector<vector<string>> datatable, int attribute_num, int target_num, vector<string> target_value)
{
//get target_info on the information for different values of the specified attribute
int count = 0;//the number of records in the current datatable
map<string,target_info> spec_attr_info;//first:the value of the specified attribute,second: target_info on the value of the attribute
for(auto i = datatable.begin(); i != datatable.end(); i++)
{
if(spec_attr_info.find((*i)[attribute_num])==spec_attr_info.end())
{//not found yet
spec_attr_info[(*i)[attribute_num]].count = 1;
if((*i)[target_num]==target_value[0])
{
spec_attr_info[(*i)[attribute_num]].count_true =1;
}
else
{
spec_attr_info[(*i)[attribute_num]].count_false = 1;
}
}
else
{
spec_attr_info[(*i)[attribute_num]].count++;
if((*i)[target_num]==target_value[0])
{
spec_attr_info[(*i)[attribute_num]].count_true++;
}else
{
spec_attr_info[(*i)[attribute_num]].count_false++;
}
}
count++;
}
//calculate the entropy based on the collected target_info
float entropy =0;
for(auto v:spec_attr_info){
float probability_of_attribute_value =float(v.second.count)/float(count);
float probability_of_targetval_T = float(v.second.count_true)/float(v.second.count);
float probability_of_targetval_F = float(v.second.count_false)/float(v.second.count);
if(probability_of_targetval_T ==0 ||probability_of_targetval_F == 0){
entropy = 0;
}else
{
entropy +=(-probability_of_attribute_value)*(probability_of_targetval_T*log2(probability_of_targetval_T)+probability_of_targetval_F*log2(probability_of_targetval_F));
}
}
return entropy;
}
//print the tree in a file.
void Output_Tree(ofstream & output, node root, string target, vector<string> target_value, int &num)
{
if(root.children.size()==0)
{//end node
output<< target << " is "<< root.name<<"."<<endl;
}
else
{
output << endl;
for(auto a = root.children.begin(); a != root.children.end(); a++)
{
int temp = num;
int k =num;
while(temp)
{
output << " ";
temp--;
}
output << "if "<< root.name<< " is "<< (*a).branch<<", then"<<" ";
num++;
Output_Tree(output, *((*a).child),target, target_value,num);
num = k;
}
}
}
int main(int argc, char* argv[])
{
vector<vector<string> > Train_data;
// parse the input arguments
if(argc<2)
{
fprintf(stderr,"incorrect number of arguments, terminating the program...\n");
return 0;
}
string train_file_name = string(argv[1]);
Train_data = Read_File(train_file_name);
//choose target attribute
cout << "Please choose an attribute (by number) as the prediction attribute: " << endl;
map<int, int> target_map;
int choice_num=0;
vector<int> possible_choice_no;
for(int i =0; i < attribute_no;i++)
{
if(attr_binary[i].binary ==true)
{
choice_num++;
cout << choice_num<<"."<< Attributes[i]<<endl;
possible_choice_no.push_back(choice_num);
target_map[choice_num] = i;
}
}
int choice_no;
cout << "your choice:"<<endl;
cin >> choice_no;
//check whether choice is valid
bool valid;
valid = inputchoice_valid(possible_choice_no,choice_no);
if(valid==false)
{
cout <<"choice is invalid."<<endl;
return 0;
}
//get related parameters for Decision_Tree
//the target related info from choice_num
int target_num = target_map[choice_no];
string target = Attributes[target_num];
//get the attribute list
attribute_num.erase(attribute_num.begin() + target_num);
//get possible target value
vector<string> target_value;
for(auto v:attr_binary[target_num].val_count)
target_value.push_back(v.first);
node root = Decision_Tree(Train_data,target_num,target,attribute_num,Attributes,target_value);
ofstream output;
output.open("Tree.txt");
int num =0;
Output_Tree(output,root,target, target_value,num);
output.close();
return 0;
}
| true |
26f48f4b6b4100c4f7cca6a07f70d91a8b425280 | C++ | lygztq/mdfs | /include/mdfs/common/writable.hpp | UTF-8 | 711 | 2.75 | 3 | [] | no_license | #ifndef MDFS_COMMON_WRITABLE_HPP_
#define MDFS_COMMON_WRITABLE_HPP_
#include <iostream>
#include <string>
#include <fstream>
namespace mdfs { namespace common {
// can (store to/load from) disk using fstream
struct WritableInterface {
virtual void store(std::ofstream & ofs) const = 0;
virtual void load(std::ifstream & ifs) = 0;
virtual ~WritableInterface() {}
};
// can (output to/input from) a stream
struct SerializableInterface : public WritableInterface
{
virtual void fromStream(std::istream & is) = 0;
virtual void toStream(std::ostream & os) const = 0;
virtual ~SerializableInterface() {}
};
} // namespace common
} // namespace mdfs
#endif // MDFS_COMMON_WRITABLE_HPP_
| true |
3a77082e0d9d2ff1b8ba75ce68393265dbf860b0 | C++ | InamulRehman/CplusplusPrograms | /Input_Output/Dividing/divide.cpp | UTF-8 | 419 | 3.359375 | 3 | [
"MIT"
] | permissive | #include <iostream>
using namespace std;
int main ()
{
int dividend, divisor, quotient, remainder;
cout << "Enter Dividend: " << flush;
cin >> dividend;
cout << "Enter Divisor " << flush;
cin >> divisor;
quotient = dividend/ divisor;
remainder = dividend % divisor;
cout << "Quotient is: " << quotient << endl;
cout << "Remainder is: " << remainder << endl;
return 0;
} | true |
7f42da5a6a42823f8669f433e489886b9db840e2 | C++ | dcastro123/PiscineCPP | /d01/ex00/Pony.hpp | UTF-8 | 385 | 2.90625 | 3 | [] | no_license | #ifndef PONY_HPP
# define PONY_HPP
# include <string>
# include <iostream>
class Pony
{
public:
Pony();
~Pony();
void setBreed(std::string);
void setName(std::string);
void setColor(std::string);
std::string getBreed(void);
std::string getName(void);
std::string getColor(void);
private:
std::string _breed;
std::string _name;
std::string _color;
};
#endif
| true |
0a3bc331524b18d2dd04bb4b1f4fa65aa4a45b6e | C++ | ClaudiaVisentin/eeros-framework | /test/control/saturation/SaturationTestContainer.cpp | UTF-8 | 4,146 | 2.78125 | 3 | [
"Apache-2.0"
] | permissive | #include <eeros/control/Saturation.hpp>
#include <iostream>
#include <random>
#include <climits>
#include <ctime>
#include <functional>
#include <type_traits>
#include <array>
#include "../../Utils.hpp"
template <typename C, typename T, unsigned int N>
class SaturationBlockTest {
public:
SaturationBlockTest() : randomIndex(0) {
std::default_random_engine generator;
generator.seed(std::time(0));
std::uniform_int_distribution<int> distribution(-1000000, 1000000);
auto rand = std::bind(distribution, generator);
for(unsigned int i = 0; i < randomBufferLength; i++) {
random[i] = rand();
if(std::is_floating_point<T>::value) random[i] /= 1000.0;
}
uut.getIn().connect(data);
uut.enable();
}
int run() {
int error = 0;
for(unsigned int t = 0; t < nofTests; t++) {
C value, lowerLimit, upperLimit, ref;
for(unsigned int i = 0; i < N; i++) {
value[i] = getRandom();
lowerLimit[i] = -getRandom(true);
upperLimit[i] = getRandom(true);
ref[i] = value[i]; if(value[i] > upperLimit[i]) ref[i] = upperLimit[i]; if(value[i] < lowerLimit[i]) ref[i] = lowerLimit[i];
}
data.getSignal().setValue(value);
uut.setLimit(lowerLimit, upperLimit);
uut.run();
C res = uut.getOut().getSignal().getValue();
for(unsigned int i = 0; i < N; i++) {
if(!Utils::compareApprox(ref[i], res[i], 0.001)) {
error++;
std::cout << "test " << t << ", element " << i << ": Failure (" << value[i] << " -> " << res[i] << " but should be " << ref[i] << " [" << lowerLimit[i] << '/' << upperLimit[i] << ']' << ")" << std::endl;
}
else {
std::cout << "test " << t << ", element " << i << ": OK (" << value[i] << " -> " << res[i] << " [" << lowerLimit[i] << '/' << upperLimit[i] << ']' << ")" << std::endl;
}
}
}
return error;
}
protected:
T getRandom(bool noNegativeNumbers = false) {
T r = random[randomIndex++ % randomBufferLength];
if(noNegativeNumbers && r < 0) r = -r;
return r;
}
static constexpr unsigned int nofTests = 100;
static constexpr unsigned int randomBufferLength = nofTests * 3 * N;
T random[randomBufferLength];
unsigned int randomIndex;
eeros::control::Output<C> data;
eeros::control::Saturation<C> uut;
};
int main(int argc, char* argv[]) {
using namespace eeros::math;
SaturationBlockTest<Matrix<3, 1, int>, int, 3 * 1> m3x1iTester;
SaturationBlockTest<Matrix<1, 2, long>, long, 1 * 2> m1x2lTester;
SaturationBlockTest<Matrix<2, 2, float>, float, 2 * 2> m2x2fTester;
SaturationBlockTest<Matrix<3, 2, double>, double, 3 * 2> m3x2dTester;
SaturationBlockTest<std::array<int, 7>, int, 7> a7iTester;
SaturationBlockTest<std::array<long, 3>, long, 3> a3lTester;
SaturationBlockTest<std::array<float, 5>, float, 5> a5fTester;
SaturationBlockTest<std::array<double, 4>, double, 4> a4dTester;
if(argc == 5 && *(argv[1]) == 'm') { // container: eeros matrix
unsigned int m = atoi(argv[2]); // number of rows
unsigned int n = atoi(argv[3]); // number of cols
char t = *(argv[4]); // element type
if(m == 3 && n == 1 && t == 'i') return m3x1iTester.run();
else if(m == 1 && n == 2 && t == 'l') return m1x2lTester.run();
else if(m == 2 && n == 2 && t == 'f') return m2x2fTester.run();
else if(m == 3 && n == 2 && t == 'd') return m3x2dTester.run();
else {
std::cout << "illegal matrix dimension or type (" << m << 'x' << n << '/' << t << "), only 3x1/i, 1x2/l, 2x2/f and 3x2/d are available." << std::endl;
}
}
else if(argc == 4 && *(argv[1]) == 'a') {
unsigned int n = atoi(argv[2]); // number of elements
char t = *(argv[3]); // element type
if(n == 7 && t == 'i') return a7iTester.run();
else if(n == 3 && t == 'l') return a7iTester.run();
else if(n == 5 && t == 'f') return a7iTester.run();
else if(n == 4 && t == 'd') return a7iTester.run();
else {
std::cout << "illegal array dimension or type (" << n << '/' << t << "), only 7/i, 3/l, 5/f and 4/d are available." << std::endl;
}
}
else {
std::cout << "illegal number of arguments" << std::endl;
}
return -1;
}
| true |
1966d6b975770d3fdeace8c46c244b385ff532bb | C++ | thecheebo/Cpp-Code-Samples | /SampleProblems/InDJarrMakeuptreenode.cpp | UTF-8 | 996 | 2.921875 | 3 | [] | no_license | You have the DSNode class shown on page 8 of the exam, as well as the Array class shown
on page 9 of the exam. You want to write a function makeTrees, which has one parameter,
an Array<int> named sets. This array will be indexed from 1 through sets.size(), representing a collection of disjoint sets implemented with union-by-size. You want to return a
value of type Array<DSNode*> (you are allowed to create this one new array in your function,
but no other additional new arrays besides that one), which will implement the exact same
collection of disjoint sets as the parameter array – only using actual uptree nodes rather than
simply array cells. Your returned array should be indexed from 1 through sets.size(), and
each cell should point to a DSNode containing that cell’s index as the node key. Those DSNode
objects should have their variables initialized in such a way that they exactly implement the
same uptrees represented by the parameter array (i.e. do not compress any paths).
| true |
abfea1c3fd86f146980ae32fecbfb8fd95d3b8ba | C++ | PratAm/Program | /c++/diamond1.cpp | UTF-8 | 781 | 3.484375 | 3 | [] | no_license | #include<iostream>
using namespace std;
class Base
{
public:
void doSomething(){}
};
class Derived1:public virtual Base
{
public:
void doSomething(){}
};
class Derived2:public virtual Base
{
public:
void doSomething(){}
};
class Base1
{
public:
virtual void doSomething(){}
};
class Derived3:public Derived1,public Derived2,public Base1
{
public:
void doSomething(){}
};
int main()
{
Base obj;
Derived1 objDerived1;
Derived2 objDerived2;
Derived3 objDerived3;
cout<<"\n Size of Base: "<<sizeof(obj);
cout<<"\n Size of Derived1: "<<sizeof(objDerived1);
cout<<"\n Size of Derived2: "<<sizeof(objDerived2);
cout<<"\n Size of Derived3: "<<sizeof(objDerived3);
cout <<endl;
return 0;
}
| true |
166c29926bfe6ce633444f807ad0812e9fbe7ff8 | C++ | jaishreedhage/Competitive-coding | /G4G/flattening_a_linked_list.cpp | UTF-8 | 1,027 | 3.5625 | 4 | [] | no_license | /* Node structure used in the program
struct Node{
int data;
struct Node * next;
struct Node * bottom ;
}; */
/* Function which returns the root of
the flattened linked list. */
Node *flatten(Node *root)
{
// Your code here
Node *t1 = root->next, *t2, *t3, *prev, *t5;
while(t1!=NULL){
t2 = t1, t3 = root, prev = NULL;
while(t3!=NULL && t2!=NULL){
if(t3->data<t2->data){
prev = t3;
t3 = t3->bottom;
}
else{
t5 = t2->bottom;
if(prev==NULL){
t2->bottom = t3;
t3 = t2;
root = t3;
}
else{
prev->bottom = t2;
t2->bottom = t3;
t3 = t2;
}
t2 = t5;
}
}
if(t2!=NULL){
prev->bottom = t2;
}
t1 = t1->next;
}
return root;
}
//easy qsn. Have to use merging idea basically
| true |
7bfc078ff89d051f4ae8e9055de9e624616e77f8 | C++ | nyChers/ACM-Learning | /exercises/枚举法/2.吹气球.cpp | UTF-8 | 1,065 | 3.140625 | 3 | [] | no_license | #include<iostream>
#include<cmath>
#include <vector>
#define PI 3.14
using namespace std;
struct ball {
int x;
int y;
int z;
double r;
// ball(){
// x=0;y=0;z=0;
// }
ball(int a,int b, int c){
x = a;
y = b;
z = c;
r = 0.0;
}
};
int main() {
int n;
cin>>n;
int x1,x2,y1,y2,z1,z2;
cin>>x1>>y1>>z1;
cin>>x2>>y2>>z2;
vector<ball> B;
for(int i=0; i<n; i++){
int a,b,c;
cin>>a>>b>>c;
ball x(a,b,c);
B.push_back(x);
}
int max_x,max_y,max_z;
double max_r;
double sum = 0;
for(int i; i<n; i++){
max_x = min(B[i].x-x1,x2-B[i].x);
max_y = min(B[i].y-y1,y2-B[i].y);
max_z = min(B[i].z-z1,z2-B[i].z);
int t = min(max_x,max_y);
max_r = min(t,max_z);
for(int j=0; j<n; j++){
if(j==i)
continue;
double temp_r = sqrt((B[i].x-B[j].x)*(B[i].x-B[j].x) + (B[i].y-B[j].y)*(B[i].y-B[j].y) +(B[i].z-B[j].z) *(B[i].z-B[j].z))-B[j].r;
if(temp_r<max_r)
max_r = temp_r;
}
B[i].r = max_r;
sum += pow(max_r,3) * PI * 4/3.0;
}
double V = (x2-x1)*(y2-y1)*(z2-z1);
double v2 = V-sum;
cout<<int (v2+0.5)<<endl;
return 0;
} | true |
1ea018258b6b80870155bd6046c3b3ac368cc7e0 | C++ | VAMK-embedded-project-2019A/Development-Board-Application | /src/buttonpoll.cpp | UTF-8 | 1,953 | 3 | 3 | [] | no_license | #include "buttonpoll.h"
#include <iostream>
#include <chrono>
#include <thread>
#include <unistd.h> // lseek()
#include <poll.h> // poll()
ButtonPoll::~ButtonPoll()
{
for(auto &button : _buttons)
close(button._fd);
}
void ButtonPoll::addButton(uint8_t pin, TriggerEdge edge)
{
_buttons.push_back(Button(pin, static_cast<uint8_t>(edge)));
}
bool ButtonPoll::isButtonPressed()
{
return !_pressed_index_queue.empty();
}
uint8_t ButtonPoll::getNextPressedPin()
{
std::unique_lock<std::mutex> button_poll_lock(_mutex);
if(_pressed_index_queue.empty())
return 0xff;
uint8_t pin = _buttons.at(_pressed_index_queue.front())._gpio_pin;
_pressed_index_queue.pop();
button_poll_lock.unlock();
return pin;
}
void ButtonPoll::start()
{
const int BUTTON_COUNT = _buttons.size();
std::vector<bool> first_interrupt(BUTTON_COUNT, true);
std::chrono::milliseconds timeout{700};
std::unique_lock<std::mutex> button_poll_lock(_mutex, std::defer_lock);
while(true)
{
struct pollfd *fdset = new pollfd[BUTTON_COUNT];
for(int i=0; i<BUTTON_COUNT; i++)
{
fdset[i].fd = _buttons[i]._fd;
fdset[i].events = POLLPRI;
}
// blocking until at least one fd ready, or timeout
int ready_count = poll(fdset, BUTTON_COUNT, timeout.count());
if(ready_count < 0)
{
std::cout << std::endl << "poll() failed!" << std::endl;
goto NEXT_POLL;
}
if(ready_count == 0)
goto NEXT_POLL;
for(int i=0; i<BUTTON_COUNT; i++)
{
if(fdset[i].revents & POLLPRI)
{
lseek(fdset[i].fd, 0, SEEK_SET);
const int BUFFER_SIZE{1};
int buf[BUFFER_SIZE];
read(fdset[i].fd, &buf, BUFFER_SIZE);
// do nothing for 1st interrupt
if(first_interrupt.at(i))
{
first_interrupt[i] = false;
continue;
}
button_poll_lock.lock();
_pressed_index_queue.push(i);
button_poll_lock.unlock();
}
}
NEXT_POLL:
delete[] fdset;
std::this_thread::sleep_for(std::chrono::seconds(1) - timeout);
}
}
| true |
928cb1a7c97449656f10caf966c61781463a88a3 | C++ | niti1987/Quadcopter | /Libraries/Rim Sound/include/rim/sound/util/rimSoundMIDIInputStream.h | UTF-8 | 6,672 | 2.578125 | 3 | [] | no_license | /*
* rimSoundMIDIInputStream.h
* Rim Sound
*
* Created by Carl Schissler on 5/30/13.
* Copyright 2013 __MyCompanyName__. All rights reserved.
*
*/
#ifndef INCLUDE_RIM_SOUND_MIDI_INPUT_STREAM_H
#define INCLUDE_RIM_SOUND_MIDI_INPUT_STREAM_H
#include "rimSoundUtilitiesConfig.h"
#include "rimSoundMIDIMessage.h"
#include "rimSoundMIDIEvent.h"
#include "rimSoundMIDIBuffer.h"
//##########################################################################################
//*********************** Start Rim Sound Utilities Namespace ****************************
RIM_SOUND_UTILITIES_NAMESPACE_START
//******************************************************************************************
//##########################################################################################
//********************************************************************************
//********************************************************************************
//********************************************************************************
/// A class which represents a stream-readable source for MIDI data.
class MIDIInputStream
{
public:
//********************************************************************************
//********************************************************************************
//********************************************************************************
//****** Destructor
/// Destroy this MIDI input stream and release any resourcees associated with it.
virtual ~MIDIInputStream()
{
}
//********************************************************************************
//********************************************************************************
//********************************************************************************
//****** MIDI Reading Methods
/// Read the specified number of MIDI events from the input stream into the output buffer.
/**
* This method attempts to read the specified number of MIDI events from the
* stream into the buffer and then returns the total number of events that
* were successfully read. The stream's current position is incremented by the
* return value.
*
* The timestamps of the returned MIDI events are specified relative to the start
* of the stream.
*/
RIM_INLINE Size read( MIDIBuffer& buffer, Size numEvents )
{
return this->readEvents( buffer, numEvents );
}
//********************************************************************************
//********************************************************************************
//********************************************************************************
//****** Public Seek Status Accessor Methods
/// Return whether or not seeking is allowed in this input stream.
virtual Bool canSeek() const = 0;
/// Return whether or not this input stream's current position can be moved by the specified signed event offset.
/**
* This event offset is specified as the signed number of MIDI events to move
* in the stream.
*/
virtual Bool canSeek( Int64 relativeEventOffset ) const = 0;
/// Move the current event position in the stream by the specified signed amount of events.
/**
* This method attempts to seek the position in the stream by the specified amount of MIDI events.
* The method returns the signed amount that the position in the stream was changed
* by. Thus, if seeking is not allowed, 0 is returned. Otherwise, the stream should
* seek as far as possible in the specified direction and return the actual change
* in position.
*/
virtual Int64 seek( Int64 relativeEventOffset ) = 0;
//********************************************************************************
//********************************************************************************
//********************************************************************************
//****** Stream Size Accessor Methods
/// Return the number of MIDI events remaining in the MIDI input stream.
/**
* The value returned must only be a lower bound on the total number of MIDI
* events in the stream. For instance, if there are events remaining, the method
* should return at least 1. If there are no events remaining, the method should
* return 0. This behavior is allowed in order to support never-ending streams
* which might not have a defined endpoint.
*/
virtual Size getEventsRemaining() const = 0;
/// Return whether or not this MIDI input stream has any events remaining in the stream.
RIM_INLINE Bool hasEventsRemaining() const
{
return this->getEventsRemaining() > Size(0);
}
/// Return the current position of the stream in events relative to the start of the stream.
/**
* The returned value indicates the event index of the current read
* position within the MIDI stream. For unbounded streams, this indicates
* the number of samples that have been read by the stream since it was opened.
*/
virtual Index getPosition() const = 0;
protected:
//********************************************************************************
//********************************************************************************
//********************************************************************************
//****** Protected MIDI Stream Methods
/// Read the specified number of MIDI events from the input stream into the output buffer.
/**
* This method attempts to read the specified number of MIDI events from the
* stream into the buffer and then returns the total number of events that
* were successfully read. The stream's current position is incremented by the
* return value.
*
* The timestamps of the returned MIDI events are specified relative to the start
* of the stream.
*/
virtual Size readEvents( MIDIBuffer& buffer, Size numEvents ) = 0;
};
//##########################################################################################
//*********************** End Rim Sound Utilities Namespace ******************************
RIM_SOUND_UTILITIES_NAMESPACE_END
//******************************************************************************************
//##########################################################################################
#endif // INCLUDE_RIM_SOUND_MIDI_INPUT_STREAM_H
| true |
f1a5a4694fbd583d4362265a7a531f103c04cb75 | C++ | Leesuhuck/C- | /Bank.h | UHC | 3,803 | 3.578125 | 4 | [] | no_license | #pragma once
#include <string>
#include <iostream>
class Bank
{
private:
int ParsonOneMoney;
std::string ParsonOneID;
public:
void deposit(std::string id); //Ա
void withdraw(void); //
void balance(void); // ܾ
//?
Bank(int Money, std::string ID) {
ParsonOneMoney = Money;
ParsonOneID = ID;
}
void setBankOne() {
int a;
std::string c;
std::cout << " ¹ȣ Էϼ : ";
std::cin >> a;
ParsonOneMoney == a;
std::cout << " ¹ȣ Էϼ : ";
std::cin >> c;
ParsonOneID == c;
}
int getBankOneMoney() {
return ParsonOneMoney;
}
std::string getBankOneID() {
return ParsonOneID;
}
};
class BankTwo
{
private:
int ParsonTwoMoney;
std::string ParsonTwoID;
public:
void deposit2(void); //Ա
void withdraw2(void); //
void balance2(void); // ܾ
//?
BankTwo(int Money, std::string ID) {
ParsonTwoMoney = Money;
ParsonTwoID = ID;
}
void setBankTwo() {
int a;
std::string c;
std::cout << " ¹ȣ Էϼ : ";
std::cin >> a;
ParsonTwoMoney = a;
std::cin >> ParsonTwoMoney;
std::cout << " ¹ȣ Էϼ : ";
std::cin >> c;
ParsonTwoID = c;
}
int getBankTwoMoney() {
return ParsonTwoMoney;
}
std::string getBankTwoID() {
return ParsonTwoID;
}
};
//Աݵ
void Bank::deposit(std::string id) { //ذ
int copyMoney;
if (id== ParsonOneID) {
std::cout << "=======ó========" << std::endl;
std::cout << "Account : " << ParsonOneID << std::endl;
std::cout << "Transaction : " << copyMoney << std::endl;
std::cout << "New Balance : " << ParsonOneMoney + copyMoney << std::endl;
}
else {
}
copyMoney = 0;
}
void BankTwo::deposit2(void) {
std::string copyID;
int copyMoney;
if (copyID == ParsonTwoID) {
std::cout << "=======ó========" << std::endl;
std::cout << "Account : " << ParsonTwoID << std::endl;
std::cout << "Transaction : " << copyMoney << std::endl;
std::cout << "New Balance : " << ParsonTwoMoney + copyMoney << std::endl;
}
else {
}
copyMoney = 0;
}
//
void Bank::withdraw(void) {
std::string copyID;
int drawMoney;
if (copyID == ParsonOneID) {
std::cout << "=======ó========" << std::endl;
std::cout << "Account : " << ParsonOneID << std::endl;
std::cout << "Transaction : " << drawMoney << std::endl;
std::cout << "New Balance : " << ParsonOneMoney - drawMoney << std::endl;
}
else {
std::cout << "¹ȣ ߸Ǿϴ." << std::endl;
}
drawMoney = 0;
}
void BankTwo::withdraw2(void) {
std::string copyID;
int drawMoney;
if (copyID == ParsonTwoID) {
std::cout << "=======ó========" << std::endl;
std::cout << "Account : " << ParsonTwoID << std::endl;
std::cout << "Transaction : " << drawMoney << std::endl;
std::cout << "New Balance : " << ParsonTwoMoney - drawMoney << std::endl;
}
else {
std::cout << "¹ȣ ߸Ǿϴ." << std::endl;
}
drawMoney = 0;
}
//ܾ
void Bank::withdraw(void) {
std::string copyID;
if (copyID == ParsonOneID) {
std::cout << "=======ó========" << std::endl;
std::cout << "Account : " << ParsonOneID << std::endl;
std::cout << "Transaction : balance" << std::endl;
std::cout << "New Balance : " << ParsonOneMoney << std::endl;
}
else {
std::cout << "¹ȣ ߸Ǿϴ." << std::endl;
}
}
//° Ű ѹ ߴ;
//ο Ӽ, | true |
27bc7c21eaa1110fdf629f65bf663ae86fb6f510 | C++ | parmj/MysticalEscapadeMUD | /lib/combat/src/CombatManager.cpp | UTF-8 | 4,868 | 3 | 3 | [
"MIT"
] | permissive | #include "CombatManager.h"
CombatManager::CombatManager(){}
Combat& CombatManager::createCombat(const std::string& player1Name, const std::string& player2Name) {
Combat newCombat{player1Name, player2Name};
this->combatList.emplace_back(newCombat);
return combatList.back();
}
void CombatManager::deleteCombat(const std::string& eitherName){
combatList.erase(std::remove_if(combatList.begin(), combatList.end(),
[&eitherName](Combat& x){return x.hasPlayer(eitherName);}),
combatList.end());
}
bool CombatManager::playerIsInCombat(const std::string& eitherName) const{
auto it = std::find_if(combatList.begin(), combatList.end(), [&eitherName](const Combat& x){return x.hasPlayer(eitherName);});
return it != combatList.end();
}
Combat& CombatManager::getCombatWithPlayer(const std::string& playerName){
for(auto& combat : combatList){
if (combat.hasPlayer(playerName)){
return combat;
}
}
return nullCombat;
}
std::vector<std::pair<std::string, std::vector<std::string>>> CombatManager::resolveCombatStep() {
roundTick();
return std::move(getCombatCommands());
}
void CombatManager::roundTick(){
for (auto& combat : combatList) {
combat.decrementRoundTime();
if(combat.getRoundTime() < 0)
combat.resetRoundTime();
}
}
std::vector<std::pair<std::string, std::vector<std::string>>> CombatManager::getCombatCommands() {
std::vector<std::pair<std::string, std::vector<std::string>>> commandList;
for (auto &combat : combatList) {
if(combat.getRoundTime() <= 0){
/* //temporary implementation
std::vector<std::string> tempVector1;
std::vector<std::string> tempVector2;
auto player1Command = combat.getCommand(0);
auto player2Command = combat.getCommand(1);
tempVector1.push_back(player1Command);
tempVector2.push_back(player2Command);*/
auto player1Pair = std::make_pair(combat.getPlayer(0), combat.getCommand(0));
auto player2Pair = std::make_pair(combat.getPlayer(1), combat.getCommand(1));
if(!player1Pair.second.empty() && player1Pair.second.at(0) == "flee"){
commandList.push_back(player2Pair);
commandList.push_back(player1Pair);
} else {
commandList.push_back(player1Pair);
commandList.push_back(player2Pair);
}
combat.clearCommands();
}
}
return std::move(commandList);
}
bool CombatManager::createInvite(const std::string& inviterName, const std::string& invitedName){
for(auto& combat : combatList){
if(combat.hasPlayer(inviterName) || combat.hasPlayer(invitedName)){
return false;
}
}
//auto invite = std::make_tuple(inviterName, invitedName, TimeStamp::getTimeStamp());
auto invite = std::make_tuple(inviterName, invitedName, 0);
pendingInvites.emplace_back(invite);
return true;
}
void CombatManager::removeInvite(const std::string& eitherName){
pendingInvites.erase(std::remove_if(pendingInvites.begin(), pendingInvites.end(),
[&eitherName](std::tuple<std::string, std::string, long>& x){return std::get<0>(x) == eitherName || std::get<1>(x) == eitherName;}),
pendingInvites.end());
}
/*void CombatManager::clearStaleInvites() {
pendingInvites.erase(std::remove_if(pendingInvites.begin(), pendingInvites.end(),
[](std::tuple<std::string, std::string, long>& x){return std::get<2>(x) == 0;}), //for now: remove if timestamp = 0. change later
pendingInvites.end());
}*/
bool CombatManager::confirmInvite(const std::string& invitedName){
for(auto& invite : pendingInvites){
auto& invited = std::get<1>(invite);
if(invited == invitedName){
auto& inviter = std::get<0>(invite);
auto& combat = getCombatWithPlayer(inviter);
if (combat.hasPlayer(inviter)){ //if inviter is now in combat, challenge invalidated
return false;
}
createCombat(inviter, invited);
removeInvite(invitedName);
return true;
}
}
return false;
}
std::string CombatManager::printCombats() const{
std::string result = "Combat List:\n";
for(auto combat : combatList){
result += combat.getPlayer(0) + " vs. ";
result += combat.getPlayer(1) + "\n";
}
return result;
}
std::string CombatManager::printInvites() const{
std::string result = "Invite List:\n";
for(auto& invite : pendingInvites){
result += std::get<0>(invite) + ", " + std::get<1>(invite) + "\n";
}
return result;
} | true |
b2d99d109394dbd8438366c8999ca5367d184e35 | C++ | masterchef2209/coding-solutions | /codes/spoj/BITMAP.cpp | UTF-8 | 718 | 2.546875 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin>>t;
while(t--)
{
int n,m;
cin>>n>>m;
int arr[n][m];
vector< pair<int,int> >pp;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
char a;
cin>>a;
arr[i][j]=a-'0';
if(arr[i][j]==1)
pp.push_back(make_pair(i,j));
}
}
// for(int k=0;k<pp.size();k++)
// {
// cout<<pp[k].first<<" "<<pp[k].second<<endl;
// }
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
int mm=INT_MAX;
for(int k=0;k<pp.size();k++)
{
int xx=abs(pp[k].first-i)+abs(pp[k].second-j);
if(xx<mm)
{
mm=xx;
}
}
cout<<mm<<" ";
}
cout<<endl;
}
}
return 0;
} | true |
3d92dda6bfd867866e1e23b35904b507cd2bd410 | C++ | Hannibal96/Network-Load-Balanace-Project | /main.cpp | UTF-8 | 20,658 | 2.671875 | 3 | [] | no_license | //
// Created by Neria on 06/08/2019.
//
#include "defs.h"
#include "Server.h"
#include "Dispacher.h"
#include "Job.h"
#include "JBuffer.h"
#include <iomanip>
#define VEC_SIZE 1000000
using namespace std;
/***************************************************
**************** declerations ********************
***************************************************/
void PrintServerStatus(Server** servers, int server_num, int t);
void PrintEndSimulation(Server** servers, int server_num, Dispatcher &dispatcher, JBuffer &buffer);
void PrintInfo(int sim_time, int servers_num, double gamma, string algo, int HighTH, int LowTH);
void ParseArguments(int argc, char *argv[], map<string, double >& numeric_data, map<string, string>& verbal_data);
double InitServersAndGetGamma(string servers_verb, double *server_rate, int servers_num, double load);
int main(int argc, char *argv[])
{
/***************************************************
******************* parsing ***********************
***************************************************/
map<string, double > numeric_data;
map<string, string> verbal_data;
ParseArguments(argc, argv, numeric_data, verbal_data);
int server_num = (int)numeric_data["Servers"], sim_time = (int)numeric_data["Time"];
int sample_rate = sim_time/(VEC_SIZE);
if(sample_rate == 0)
sample_rate = 1;
int print_time = std::numeric_limits<int>::max();
if ( numeric_data.find("PrintTime") != numeric_data.end() )
print_time = (int)numeric_data["PrintTime"];
string algo = verbal_data["Algorithm"];
int POC = -1;
if ( algo == "POC" ) {
POC = (int) numeric_data["POC"];
if(!POC){
cout << "-E- POC algo was chosen but no POC parameter was entered" << endl;
exit(1);
}
if(POC >= server_num){
cout << "-E- POC parameter bigger or equal to number of servers, use smaller POC or JSQ" << endl;
exit(1);
}
}
int high_threshold = (int)numeric_data["HighTH"];
int low_threshold = (int)numeric_data["LowTH"];
/***************************************************
**************** define output *********************
***************************************************/
string name = "./../results/";
name += "Servers-"+verbal_data["Servers"]+"-"+verbal_data["Algorithm"]+"-"+to_string((int)numeric_data["POC"])+
"-Load-"+(verbal_data["Load"])+
"-Buffer-Low="+to_string(low_threshold)+"-High="+to_string(high_threshold)+
"-Policy="+verbal_data["Policy"]+"-"+to_string((int)numeric_data["Policy"])+
"-Time-"+to_string(sim_time);
ofstream sim_print;
sim_print.open(name+"_print.log");
ofstream sim_val;
sim_val.open (name+"_values.log");
//std::cout.rdbuf(sim_print.rdbuf()); //redirect std::cout to out.txt!
if (not (sim_val.is_open() && sim_print.is_open())) {
cout << "-E- output was not correctly set" << endl;
exit(1);
}
vector<double> load;
double min_load = numeric_data["Load_Min"], max_load = numeric_data["Load_Max"], step_load = numeric_data["Load_Step"];
for( double i=min_load; i<=max_load+step_load/2; i = i+step_load )
load.push_back(i);
for(int i=0; i<load.size() ;i++) {
double curr_load = load[i];
/***************************************************
***************** initializing ********************
***************************************************/
double server_rate[server_num];
double gamma = InitServersAndGetGamma(verbal_data["Servers"], server_rate, server_num, curr_load);
Dispatcher *dispatcher;
if (algo == "Random") dispatcher = new Dispatcher(0, server_num, gamma);
else if (algo == "RoundRobin") dispatcher = new RrDispatcher(0, server_num, gamma);
else if (algo == "POC") dispatcher = new PocDispatcher(0, server_num, gamma);
else if (algo == "JSQ") dispatcher = new JsqDispatcher(0, server_num, gamma);
else if (algo == "JIQ") dispatcher = new JiqDispatcher(0, server_num, gamma);
else if (algo == "PI") dispatcher = new PiDispatcher(0, server_num, gamma);
else if (algo == "Optimal") dispatcher = new OptDispatcher(0, server_num, gamma);
else {
cout << "-E- Worng algorithm " << endl;
exit(1);
}
Server **servers = new Server *[server_num];
for (int n = 0; n < server_num; n++) {
servers[n] = new Server(n, server_rate[n]);
}
JBuffer buffer;
bool buffer_exist = not(high_threshold == low_threshold && high_threshold == 0);
if (buffer_exist) {
buffer = JBuffer(1001, server_num, high_threshold, low_threshold, verbal_data["Policy"]);
} else {
buffer = JBuffer(1001,
server_num); // deafulting buffer, not affecting simulator
}
unsigned long long total_queued_jobs = 0;
unsigned long long total_buffered_jobs_overtime = 0;
/***************************************************
****************** main loop **********************
***************************************************/
PrintInfo(sim_time, server_num, gamma, algo, high_threshold, low_threshold);
for (int curr_time = 1; curr_time <= sim_time; curr_time++) {
int arrivals = dispatcher->get_arrivals(); // get arrivals
for (int a = 0; a < arrivals; a++) { // send to destinations
Job job = Job(curr_time);
int destination = -1;
if (algo == "POC") {
assert(POC != -1 && "-W- Assert, main loop : POC was not initialized");
destination = dynamic_cast<PocDispatcher *>(dispatcher)->get_destination(servers, POC);
} else if (algo == "Optimal") {
destination = dynamic_cast<OptDispatcher *>(dispatcher)->get_destination(servers);
} else {
destination = dispatcher->get_destination();
}
assert(destination != -1 && "-W- Assert, main loop : destination was not initialized");
bool reRoute = buffer.CheckReRoute(*servers[destination]);
if (reRoute) { // route to buffer
assert(buffer_exist && "-W- Assert, ReRoute : buffer dosen't exist but enter buffer condition");
dispatcher->update_routing_table(-1);
buffer.AddJob(job);
}
else { // regular routing + reroute from buffer
// LowTH
bool returnToRoute = buffer.CheckReturnToRoute(*servers[destination]);
//LowTH
if (returnToRoute) {
assert(buffer_exist &&
"-W- Assert, returnToRoute : buffer dosen't exist but enter buffer condition");
if(buffer.GetPolicy() == "--Victim") {
while (buffer.GetQueuedJobs()) {
Job returned_job = buffer.SendJob(curr_time, destination);
servers[destination]->AddJob(returned_job);
if (algo == "RoundRobin") {
dynamic_cast<RrDispatcher *>(dispatcher)->update_server_route();
} else {
dispatcher->update_server_route(destination);
}
}
}
else if (buffer.GetPolicy() == "--Jester"){
int jesters = (int)numeric_data["Policy"];
while (buffer.GetQueuedJobs() && jesters > 0 ) {
Job returned_job = buffer.SendJob(curr_time, destination);
servers[destination]->AddJob(returned_job);
if (algo == "RoundRobin") {
dynamic_cast<RrDispatcher *>(dispatcher)->update_server_route();
} else {
dispatcher->update_server_route(destination);
}
jesters --;
}
}
else if(buffer.GetPolicy() == "--WaterBoarding"){
int water_boarding_th = (int)numeric_data["Policy"];
while (buffer.GetQueuedJobs() && servers[destination]->GetQueuedJobs() < water_boarding_th ) {
Job returned_job = buffer.SendJob(curr_time, destination);
servers[destination]->AddJob(returned_job);
if (algo == "RoundRobin") {
dynamic_cast<RrDispatcher *>(dispatcher)->update_server_route();
} else {
dispatcher->update_server_route(destination);
}
}
}
else{
assert(false && "-W- Assert, ReturnToRoute : buffer's dosen't existing policy");
}
}
dispatcher->update_routing_table(destination);
servers[destination]->AddJob(job);
if (algo == "RoundRobin") {
dynamic_cast<RrDispatcher *>(dispatcher)->update_server_route();
} else {
dispatcher->update_server_route(destination);
}
}
}
for (int n = 0; n < server_num; n++) { // serve jobs and update dispatcher information
pair<int, bool> finished_jobs = servers[n]->FinishJob(curr_time);
if (algo == "JSQ") {
dynamic_cast<JsqDispatcher *>(dispatcher)->update_server_finish(n, finished_jobs.first);
} else if (algo == "JIQ" || algo == "PI") {
dynamic_cast<JiqDispatcher *>(dispatcher)->update_server_finish(n, finished_jobs);
}
}
/***************************************************
**************** sample states *******************
***************************************************/
for (int n = 0; n < server_num; n++) {
total_queued_jobs += servers[n]->GetQueuedJobs();
total_buffered_jobs_overtime += buffer.GetQueuedJobs();
//total_buffered_jobs_overtime += JBuffer::total_buffered_jobs;
}
if (curr_time % sample_rate == 0 && load.size() == 1) {
sim_val <<
" " << curr_time <<
" " << (double)Server::total_serving_time / (Server::total_served_jobs + !(Server::total_served_jobs)) <<
" " << (double)(total_queued_jobs + total_buffered_jobs_overtime) / curr_time <<
" " << buffer.GetQueuedJobs() <<
/* " " << (double)(dispatcher->get_routing_map()[0] + buffer.get_routing_table()[0]) / curr_time <<
" " << (double)(dispatcher->get_routing_map()[1] + buffer.get_routing_table()[1]) / curr_time <<
" " << (double)(dispatcher->get_routing_map()[2] + buffer.get_routing_table()[2]) / curr_time <<
" " << (double)(dispatcher->get_routing_map()[3] + buffer.get_routing_table()[3]) / curr_time <<
" " << (double)(dispatcher->get_routing_map()[4] + buffer.get_routing_table()[4]) / curr_time << */
endl;
}
if (curr_time % print_time == 0) {
PrintServerStatus(servers, server_num, curr_time);
cout << buffer << endl;
}
}
if ( load.size() > 1 ) {
sim_val <<
" " << curr_load <<
" " << (double)Server::total_serving_time / (Server::total_served_jobs + !(Server::total_served_jobs)) <<
" " << (double)(total_queued_jobs + total_buffered_jobs_overtime) / sim_time <<
" " << buffer.GetMaximalQueue() << endl;
}
/***************************************************
***************** conclusions ********************
***************************************************/
PrintEndSimulation(servers, server_num, *dispatcher, buffer);
/***************************************************
******************** Free ************************
***************************************************/
for (int n = 0; n < server_num; n++) {
delete servers[n];
}
delete dispatcher;
if ( load.size() > 1){
Server::total_serving_time = 0;
Server::total_served_jobs = 0;
JBuffer::total_buffered_jobs = 0;
JBuffer::total_waiting = 0;
Job::number_of_jobs = 0;
Job::jobs_completion_maps = map<int,pair<int,int>>();
Dispatcher::total_dispatched_jobs = 0;
}
}
sim_print.close();
sim_val.close();
return 0;
}
/***************************************************
***************** functions **********************
***************************************************/
void PrintServerStatus(Server** servers, int server_num, int t)
{
cout << "********************" << endl;
cout << "**** Time:" << t << " *******" << endl;
cout << "********************" << endl;
cout << "Time: " << t << endl;
for (int n = 0; n < server_num; n++) {
cout << *servers[n] << endl;
}
}
void PrintEndSimulation(Server** servers, int server_num , Dispatcher &dispatcher, JBuffer& buffer)
{
cout << "***************************************************" << endl
<< "*************** Simulation End ********************" << endl
<< "***************************************************" << endl;
int total_queued_jobs = 0;
for (int n = 0; n < server_num; n++) {
cout << *servers[n] << endl;
total_queued_jobs += servers[n]->GetQueuedJobs();
}
cout << dispatcher << endl;
cout << buffer << endl;
assert(total_queued_jobs+Server::total_served_jobs+buffer.GetQueuedJobs() == Dispatcher::total_dispatched_jobs &&
"-W- Assert, Served Jobs + Queued Jobs != Total Dispatched Jobs" );
cout << "======================" << endl;
cout << "Total serving time average: " << (double)Server::total_serving_time/Server::total_served_jobs << endl;
cout << "======================" << endl;
}
void PrintInfo(int sim_time, int servers_num, double gamma, string algo, int HighTH, int LowTH)
{
cout << "***************************************************" << endl
<< "*********** Stating simulation with ***************" << endl
<< "***************************************************" << endl;
cout << "--- " << servers_num << " servers" << endl;
cout << "--- incoming rate of " << gamma << endl;
cout << "--- under load balancing of " << algo << endl;
if(HighTH == LowTH && HighTH == 0)
cout << "--- no buffer in usage" << endl;
else
cout << "--- with buffer configurations of: " << HighTH << " high threshold, and " << LowTH << " low threshold" << endl;
cout << "--- for " << sim_time << " time units" << endl;
}
void ParseArguments(int argc, char *argv[], map<string, double >& numeric_data, map<string, string>& verbal_data)
{
for(int i=1; i<argc; i++){
string converted_arg = argv[i];
if(converted_arg == "--Time") {
numeric_data["Time"] = atoi(argv[++i]);
}
else if(converted_arg == "--PrintTime") {
numeric_data["PrintTime"] = atoi(argv[++i]);
}
else if(converted_arg == "--Servers") {
numeric_data["Servers"] = atoi(argv[++i]);
verbal_data["Servers"] = argv[++i];
}
else if(converted_arg == "--Dispatchers") { // Currently testing only one, to expand to multiple need
numeric_data["Dispatchers"] = atoi(argv[++i]); // to make small adjustment from the server parsing
verbal_data["Algorithm"] = argv[++i];
if( verbal_data["Algorithm"] == "POC" )
numeric_data["POC"] = atoi(argv[++i]);
}
else if(converted_arg == "--Load") {
verbal_data["Load"] = argv[++i];
string a = verbal_data["Load"];
a.erase(0,1);
size_t pos = a.find(",");
string min = a.substr(0, pos);
a.erase(0, pos + 1);
pos = a.find(",");
string max = a.substr(0, pos);
a.erase(0, pos + 1);
pos = a.find("}");
string step = a.substr(0, pos);
a.erase(0, pos + 1);
numeric_data["Load_Min"] = stod(min);
numeric_data["Load_Max"] = stod(max);
numeric_data["Load_Step"] = stod(step);
}
else if(converted_arg == "--Buffer") { // Likewise
numeric_data["Buffers"] = atoi(argv[++i]);
//verbal_data["Buffer"] = argv[++i];
converted_arg = argv[++i];
if( converted_arg == "--LowTH" ){
numeric_data["LowTH"] = atoi(argv[++i]);
}
else {
cout << "-E- Wrong LowTH Buffer argument and/or order" << endl;
exit(1);
}
converted_arg = argv[++i];
if(converted_arg == "--HighTH"){
numeric_data["HighTH"] = atoi(argv[++i]);
}
else {
cout << "-E- Wrong HighTH Buffer argument and/or order" << endl;
exit(1);
}
converted_arg = argv[++i];
if(converted_arg == "--Jester" || converted_arg == "--WaterBoarding" ||
converted_arg == "--Victim"){
verbal_data["Policy"] = converted_arg;
if(converted_arg == "--WaterBoarding" || converted_arg == "--Jester"){
numeric_data["Policy"] = atoi(argv[++i]);
}
}
else if(numeric_data["HighTH"] != 0) {
cout << "-E- Wrong Policy Buffer argument and/or order" << endl;
exit(1);
} else{
verbal_data["Policy"] = "Deafault";
}
}
else if(converted_arg == "--Help"){
cout << "-Help message:" << endl;
cout << "--Example: \n\t"
"--Servers 25 10x0.1,10x0.2,5x0.5, --Dispatchers 1 POC 2 --Time 1000000 --Load {0.5,1.0,0.025}"
<< endl;
exit(0);
}
else {
cout << "-E- Wrong argument inserted" << endl;
exit(1);
}
}
}
double InitServersAndGetGamma(string servers_verb, double *server_rate, int servers_num, double load)
{
double total_serving_rates = 0.0;
int offset = 0 ;
string delimiter = ",", inner_delimiter = "x";
size_t pos = 0;
size_t sub_pos = 0;
std::string token_dual;
while ((pos = servers_verb.find(delimiter)) != std::string::npos) {
token_dual = servers_verb.substr(0, pos);
sub_pos = token_dual.find(inner_delimiter);
int number = stoi(token_dual.substr(0, sub_pos));
token_dual.erase(0, sub_pos + delimiter.length());
sub_pos = token_dual.find(inner_delimiter);
double value = stod(token_dual.substr(0, sub_pos));
for(int i=0;i<number;i++) {
server_rate[offset + i] = 1/(1-value+(value/0.5));
total_serving_rates += (1/server_rate[offset + i]) - 1;
}
offset += number;
servers_verb.erase(0, pos + delimiter.length());
}
if(offset != servers_num) {
cout << "-E- number of servers dosen't consist with server rate info" << endl;
exit(1);
}
return load * total_serving_rates;
}
| true |
7587776e3355474fd05ea8f7b9910b14ddae4adf | C++ | LeeWooSang/Server_Programming | /숙제 1번/SimpleGame/SimpleGame/Player.cpp | UTF-8 | 1,611 | 2.8125 | 3 | [] | no_license | #include "stdafx.h"
#include "Player.h"
#include "Renderer.h"
Player::Player()
: GameObject(), m_HpBar_width(0), m_HpBar_height(0), m_Speed(0), m_TextureID(0)
{
}
Player::~Player()
{
}
void Player::ProcessInput()
{
if (GetAsyncKeyState(VK_RIGHT) & 0x0001)
m_X += 100;
//if (GetAsyncKeyState(VK_RIGHT) & 0x8000)
// //m_X += m_Speed * m_ElapsedTime;
if (GetAsyncKeyState(VK_LEFT) & 0x0001)
m_X -= 100;
//if (GetAsyncKeyState(VK_LEFT) & 0x8000)
// m_X -= m_Speed * m_ElapsedTime;
if (GetAsyncKeyState(VK_UP) & 0x0001)
m_Y += 100;
//if (GetAsyncKeyState(VK_UP) & 0x8000)
// m_Y += m_Speed * m_ElapsedTime;
if (GetAsyncKeyState(VK_DOWN) & 0x0001)
m_Y -= 100;
//if (GetAsyncKeyState(VK_DOWN) & 0x8000)
// m_Y -= m_Speed * m_ElapsedTime;
}
bool Player::Initialize(Renderer* pRenderer)
{
m_X = -50.f;
m_Y = -350.f;
m_Size = 100.f;
m_Color[0] = 1.f;
m_Color[1] = 1.f;
m_Color[2] = 1.f;
m_Color[3] = 1.f;
m_BuildLevel = 0.1f;
m_HpBar_width = m_Size;
m_HpBar_height = m_Size / 10.f;
m_Speed = 100.f;
m_TextureID = pRenderer->CreatePngTexture("./Textures/PNGs/Horse.png");
return true;
}
void Player::Update(float elapsedTime)
{
float elapsedTimeInSecond = elapsedTime * 0.001f;
m_ElapsedTime = elapsedTimeInSecond;
int size = 350;
if (m_X >= size)
m_X = size;
else if (m_X <= -size)
m_X = -size;
if (m_Y >= size)
m_Y = size;
else if (m_Y <= -size)
m_Y = -size;
}
void Player::Render(Renderer* pRenderer)
{
int i = 0;
pRenderer->DrawTexturedRect(m_X, m_Y, m_Z, m_Size, m_Color[i++], m_Color[i++], m_Color[i++], m_Color[i++], m_TextureID, m_BuildLevel);
}
| true |
83dd27dc51b7aadcd79837e7f68dac90aad9384d | C++ | pyettra/tecprog_3 | /Pessoa.cpp | UTF-8 | 1,699 | 3.59375 | 4 | [] | no_license | #include <stdio.h>
#include <string.h>
#include "Pessoa.h"
#include <iostream>
using std::cout;
using std::endl;
// Não colocamos o valor default na implementação do método, apenas na assinatura que consta no header da classe
Pessoa::Pessoa(int diaN, int mesN, int anoN, char* nome) {
diaP = diaN;
mesP = mesN;
anoP = anoN;
strcpy(nomeP, nome);
// Aqui, aumentamos o encapsulamento dos métodos.
// Como sabemos que precisamos calcular a idade de cada Pessoa, podemos incluir a chamada desse método
// dentro do construtor do objeto Pessoa. Isso porque os parâmetros desse método
Calcula_Idade(8, 3, 2020);
}
void Pessoa::Calcula_Idade(int diaAt, int mesAt, int anoAt) {
idadeP = anoAt - anoP;
if (mesP < mesAt) {
idadeP = idadeP - 1;
} else {
if (mesP == mesAt) {
if (diaP < diaAt) {
idadeP = idadeP - 1;
}
}
}
// COUT
// No C++ é parte da prática utilizar o cout como comando de print.
// Para isso, como estamos utilizando o Visual Studio para digitar esses belos códigos,
// é necessário que importemos a biblioteca iostream. Também devemos especificar que
// estamos utilizando o cout e o endl. Enquanto o cout indica o início de uma saída de dados
// o endl mostra o final.
// Podemos ter também a utilização de entrada de dados, com o comando cin. Podemos testar essa abordagem
// em um outro momento.
// Então, subtituindo o printf("A pessoa %s estaria com %d anos\n", nomeP, idadeP); temos:
cout <<"A pessoa "<<nomeP<<" teria "<<idadeP<<" anos"<< endl;
}
int Pessoa::informaIdade() {
return idadeP;
}
| true |
0e4ac5653c8c5b2b0fe1a16b55e0a9a016283c3a | C++ | LockieJames/ap-assignment2 | /starter_code/Menu.cpp | UTF-8 | 9,085 | 3.390625 | 3 | [] | no_license |
#include "Menu.h"
Menu::Menu(){
}
Menu::~Menu() {
}
/*
* Beginning message welcoming players to Qwirkle.
*/
void Menu::startMessage() {
std::cout << "\n" << "Welcome to Qwirkle!" << std::endl;
std::cout << "-------------------" << std::endl;
}
/*
* Shows list of options available to user.
*/
void Menu::menuOptions() {
std::cout << "Menu" << std::endl;
std::cout << "----" << std::endl;
std::cout << "1. New Game" << std::endl;
std::cout << "2. Load Game" << std::endl;
std::cout << "3. Highscores" << std::endl;
std::cout << "4. Show Student Information" << std::endl;
std::cout << "5. Quit" << std::endl << std::endl;
std::cout << PROMPT;
}
/*
* First part of output for starting a new game.
*/
void Menu::newGamePt1() {
std::cout << "----------------------------------" << std::endl;
std::cout << "Starting a New Game" << std::endl;
}
/*
* Output for asking how many players are willing to player (up to 4).
*/
void Menu::numOfPlayers() {
std::cout << "Number of players(MAX 4): " << std::endl << PROMPT;
}
/*
* Output for user to input names of players who are playing.
*/
void Menu::newGameNames(int playerNo) {
std::cout << "Enter a name for player " << playerNo;
std::cout << " (uppercase characters only)" << std::endl << PROMPT;
}
/*
* Second part of output ending player set name selection.
*/
void Menu::newGamePt2() {
std::cout << "Let's Play!" << std::endl;
std::cout << "----------------------------------" << std::endl;
}
/*
* Output for asking user for the save file of the game they want to play.
*/
void Menu::loadGame() {
std::cout << "Enter the filename from which to load the game" << std::endl;
std::cout << PROMPT;
}
/*
* Output to indicate that saving file was successful.
*/
void Menu::loadGameSuccess() {
std::cout << "Qwirkle game successfully loaded" << std::endl;
}
/*
* Shows list of output of the students involved in developing this software.
*/
void Menu::stuInfo() {
std::cout << "----------------------------------" << std::endl;
for (int i = 0; i < NUM_STUDENTS; i++) {
std::cout << name[i] << std::endl;
std::cout << stu_id[i] << std::endl;
std::cout << email[i] << std::endl;
if (i < NUM_STUDENTS - 1) {
std::cout << std::endl;
}
}
std::cout << "----------------------------------" << std::endl;
}
/*
* Simple output for displaying a goodbye message.
*/
void Menu::quit() {
std::cout << "Goodbye" << std::endl;
}
/*
* Shows current board state, score of the player, and the hand of the player
* with helpful, visual output of the tiles in the player's hand.
*/
void Menu::printGameInfo(
std::vector<Player *>* players,
int currentPlayer, Board* gameBoard
) {
std::cout << players->at(currentPlayer)->getName() << ", it's your turn";
std::cout << std::endl;
for (auto i : *players) {
std::cout << "Score for " << i->getName() << " is: ";
std::cout << i->getScore() << std::endl;
}
gameBoard->printBoard(std::cout, true);
std::cout << "Your hand is " << std::endl;
std::cout << "Input values: ";
std::cout << players->at(currentPlayer)->getHand()->getTiles(true, false);
std::cout << std::endl;
std::cout << "Visually are: ";
std::cout << players->at(currentPlayer)->getHand()->getTiles(true, true);
std::cout << std::endl;
}
/*
* Function checks the score of each player once game finishes, displaying
* the player who had the highest score.
*/
void Menu::gameFinish(std::vector<Player *>* players) {
int finalScore = 0;
int index = 0;
std::cout << "Game Over" << std::endl;
for (auto player : *players) {
std::cout << "Score for " << player->getName() << ": ";
std::cout << player->getScore() << std::endl;
}
for (int i = 0; i < (int) players->size(); i++) {
if (players->at(i)->getScore() > finalScore) {
finalScore = players->at(i)->getScore();
index = i;
}
}
std::cout << "Player " << players->at(index)->getName();
std::cout << " won!" << std::endl;
}
/*
* List of commands that may aid the player in proceeding with their turn or do
* other arious tasks, such as saving the current state of the game.
*/
void Menu::getHelp() {
std::cout << "HELP!" << std::endl;
std::cout << "Feeling a little stuck? Here are your options: ";
std::cout << std::endl;
std::cout << "Write: " << std::endl;
std::cout << "place (colour of the tile you want to place)";
std::cout << "(shape you want to place) at ";
std::cout << "(selected row)(selected column)";
std::cout << std::endl;
std::cout << "\t This could for instance look like";
std::cout << " \033[38;5;126m\"place P4 at D5\"\033[0m" << std::endl;
std::cout << "\t Be careful however, you are allowed to place tiles only";
std::cout << " next to one that already exists" << std::endl;
std::cout << "\t and has the same shape or colour!" << std::endl;
std::cout << "\t Additionally, you can place only the tiles that are in";
std::cout << " you hand!" << std::endl << std::endl;
std::cout << "replace (colour of tile)(shape of tile)" << std::endl;
std::cout << "\t This will replace the tile you choose and you will get a";
std::cout << " new one from the bag." << std::endl;
std::cout << "\t Could look like \033[38;5;126m\"replace Y2\"\033[0m";
std::cout << std::endl << std::endl;
std::cout << "save (filename)" << std::endl;
std::cout << "\t Will save the game into the file you provided.";
std::cout << std::endl << std::endl;
std::cout << "quit" << std::endl;
std::cout << "\t Will quit the game." << std::endl << std::endl;
std::cout << "^D" << std::endl;
std::cout << "\t Will quit the game as well." << std::endl << std::endl;
std::cout << "help" << std::endl;
std::cout << "\t Opens this." << std::endl << std::endl;
}
/*
* Function is responsible for changing the colour of the respective tile
* from white text to their respective colour text.
*/
std::string Menu::printColour(Colour colour, std::ostream &destination) {
std::string finalColour;
if (typeid(destination).name() == typeid(std::cout).name()) {
if (colour == RED) {
finalColour = "\033[38;5;160mR\033[0m";
} else if (colour == ORANGE) {
finalColour = "\033[38;5;202mO\033[0m";
} else if (colour == YELLOW) {
finalColour = "\033[38;5;226mY\033[0m";
} else if (colour == GREEN) {
finalColour = "\033[38;5;40mG\033[0m";
} else if (colour == BLUE) {
finalColour = "\033[38;5;33mB\033[0m";
} else if (colour == PURPLE) {
finalColour = "\033[38;5;55mP\033[0m";
}
} else {
finalColour = colour;
}
return finalColour;
}
/*
* Function is responsible for changing the shape of the respective tile
* from a white symbol to their respective unicode symbol.
*/
std::string Menu::printShape(Shape shape, std::ostream &destination) {
std::string finalColour;
if (typeid(destination).name() == typeid(std::cout).name()) {
if (shape == CIRCLE) {
finalColour = "\u25CF";
} else if (shape == STAR_4) {
finalColour = "\u2726";
} else if (shape == DIAMOND) {
finalColour = "\u25C6";
} else if (shape == SQUARE) {
finalColour = "\u25A0";
} else if (shape == STAR_6) {
finalColour = "\u2736";
} else if (shape == CLOVER) {
finalColour = "\u2724";
}
} else {
finalColour = shape;
}
return finalColour;
}
/*
* If invalid input has been parsed, error message is displayed instead.
*/
void Menu::invalidInput() {
std::cout << "Invalid input!" << std::endl;
}
/*
* If a invalid play has been made, error message is displayed instead.
*/
void Menu::invalidPlay() {
std::cout << "Invalid play!" << std::endl;
}
/*
* Output that indicates that a save file has been successfully made.
*/
void Menu::gameSaved(){
std::cout << "Game successfully saved" << std::endl;
}
/*
* Function responsible for printing out a given string.
*/
void Menu::printString(std::string strToPrint){
std::cout << strToPrint << std::endl;
}
/*
* Function is reponsible for printing out the highscore of each player
* that has ever made a highscore.
*/
void Menu::printHighscores(Highscore * hs)
{
std::cout << "Highscores!" << std::endl;
std::cout << "----------------------------------" << std::endl;
for(int i = 0; i < hs->getSize(); i++)
{
std::cout << i + 1 << ". " << hs->getHighscoreName(i) << " ";
std::cout << hs->getHighscore(i) << std::endl;
}
std::cout << "----------------------------------" << std::endl;
}
/*
* Visual function that displays the prompt per assignment specification
*/
void Menu::printUserInputPrompt(){
std::cout << PROMPT;
}
| true |
ee5f4570dc7491b6e4d5b5ecc1813621ed9b0d6c | C++ | insertinterestingnamehere/libdynd | /tests/types/test_tuple_type.cpp | UTF-8 | 2,699 | 2.625 | 3 | [
"BSL-1.0",
"BSD-2-Clause"
] | permissive | //
// Copyright (C) 2011-16 DyND Developers
// BSD 2-Clause License, see LICENSE.txt
//
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <dynd/array.hpp>
#include <dynd/gtest.hpp>
#include <dynd/json_parser.hpp>
#include <dynd/types/fixed_string_type.hpp>
#include <dynd/types/tuple_type.hpp>
using namespace std;
using namespace dynd;
TEST(TupleType, CreateSimple) {
ndt::type tp;
const ndt::tuple_type *tt;
// Tuple with one field
tp = ndt::make_type<ndt::tuple_type>({ndt::make_type<int32_t>()});
EXPECT_EQ(tuple_id, tp.get_id());
EXPECT_EQ(scalar_kind_id, tp.get_base_id());
EXPECT_EQ(0u, tp.get_data_size());
EXPECT_EQ(4u, tp.get_data_alignment());
EXPECT_FALSE(tp.is_pod());
EXPECT_FALSE(tp.extended<ndt::tuple_type>()->is_variadic());
EXPECT_EQ(0u, (tp.get_flags() & (type_flag_blockref | type_flag_destructor)));
tt = tp.extended<ndt::tuple_type>();
ASSERT_EQ(1, tt->get_field_count());
EXPECT_EQ(ndt::make_type<int32_t>(), tt->get_field_type(0));
// Roundtripping through a string
EXPECT_EQ(tp, ndt::type(tp.str()));
// Tuple with two fields
tp = ndt::make_type<ndt::tuple_type>({ndt::make_type<int16_t>(), ndt::make_type<double>()});
EXPECT_EQ(tuple_id, tp.get_id());
EXPECT_EQ(scalar_kind_id, tp.get_base_id());
EXPECT_EQ(0u, tp.get_data_size());
EXPECT_EQ((size_t)alignof(double), tp.get_data_alignment());
EXPECT_FALSE(tp.is_pod());
EXPECT_FALSE(tp.extended<ndt::tuple_type>()->is_variadic());
EXPECT_EQ(0u, (tp.get_flags() & (type_flag_blockref | type_flag_destructor)));
tt = tp.extended<ndt::tuple_type>();
ASSERT_EQ(2, tt->get_field_count());
EXPECT_EQ(ndt::make_type<int16_t>(), tt->get_field_type(0));
EXPECT_EQ(ndt::make_type<double>(), tt->get_field_type(1));
// Roundtripping through a string
EXPECT_EQ(tp, ndt::type(tp.str()));
}
TEST(TupleType, Equality) {
EXPECT_EQ(ndt::type("(int32, float16, int32)"), ndt::type("(int32, float16, int32)"));
EXPECT_NE(ndt::type("(int32, float16, int32)"), ndt::type("(int32, float16, int32, ...)"));
}
TEST(TupleType, Assign) {
nd::array a, b;
a = parse_json("(int32, float64, string)", "[12, 2.5, \"test\"]");
b = nd::empty("(float64, float32, string)");
b.vals() = a;
EXPECT_JSON_EQ_ARR("[12, 2.5, \"test\"]", b);
}
TEST(TupleType, Properties) {
ndt::type tp =
ndt::make_type<ndt::tuple_type>({ndt::make_type<int>(), ndt::make_type<dynd::string>(), ndt::make_type<float>()});
EXPECT_ARRAY_EQ((nd::array{3 * sizeof(size_t), 3 * sizeof(size_t), 3 * sizeof(size_t)}),
tp.p<std::vector<uintptr_t>>("metadata_offsets"));
}
TEST(TupleType, IDOf) { EXPECT_EQ(tuple_id, ndt::id_of<ndt::tuple_type>::value); }
| true |
091f6bfa8a6a8cc74fb59e341aac65cb8eebb412 | C++ | Yann-P/Quidditch-OpenGL | /src/GoldenSnitch.cpp | UTF-8 | 4,480 | 3 | 3 | [
"MIT"
] | permissive | /**
* \file GoldenSnitch.cpp
* \author Julien Lepasquier
* \date 20/03/2017
*
*/
#include "GoldenSnitch.h"
#include <cmath>
using namespace std;
#define MAIN_SPEED 0.3
#define PARASITE_SPEED 3
#define MAXDISTANCE 100
GoldenSnitch::GoldenSnitch(glm::vec3 position) : Drawable(
new Shader("../shaders/snitch.v.glsl", "../shaders/snitch.f.glsl"),
new Mesh("../blend/snitch.blend"),
new Texture("../texture/snitch.tga")
) {
_position = position;
_fixed = false;
}
bool GoldenSnitch::detectCollision(const glm::vec3 & object)
{
if (GoldenSnitch::getDistanceFromCharacter()<10){
return true;
}
return false;
}
void GoldenSnitch::update(long int t) {
if(_input->isDown(GLFW_KEY_P)){
_fixed = !_fixed;
}
if (!_fixed){
_position.x += cos(t/2000);
if (_position.y >=25)
{
_position.y += sin(t/1000) * 0.5;
}
else
{
_position.y = 25;
}
_position.z += sin(t/1600);
}
if(detectCollision(_character->getPosition())) {
std::cout << "FIN DE JEU" << std::endl;
_position.x = _character->getPosition().x;
_position.y = _character->getPosition().y;
_position.z = _character->getPosition().z;
}
}
void GoldenSnitch::setCharacter(const Character * character) {
_character = character;
}
float GoldenSnitch::getDistanceFromCharacter() {
glm::vec3 charPos = _character->getPosition();
glm::vec3 snitchPos = this->getPosition();
float d = 0;
d += (charPos.x - snitchPos.x)*(charPos.x - snitchPos.x);
d += (charPos.y - snitchPos.y)*(charPos.y - snitchPos.y);
d += (charPos.z - snitchPos.z)*(charPos.z - snitchPos.z);
return sqrt(d);
}
bool GoldenSnitch::newMovementIsParasite(int parasitesRate) {
int isParasite = rand()%100;
if (isParasite < parasitesRate) {
return true;
} else {
return false;
}
}
void GoldenSnitch::flee() {
glm::vec3 charPos = _character->getPosition();
glm::vec3 snitchPos = this->getPosition();
glm::vec3 diff = charPos-snitchPos;
bool isParasite = newMovementIsParasite(5);
if (isParasite) {
int newDir = rand()%6;
_path.push( std::make_pair(newDir, PARASITE_SPEED));
}
else
{
if (diff.x < diff.y) {
int newDir = rand()%2;
} else {
int newDir = rand()%2+2;
}
int newDir = 1;
_path.push( std::make_pair(newDir, MAIN_SPEED));
}
}
void GoldenSnitch::createRandomPath() {
int n = rand()%100 + 1000;
int newDir = rand()%6;
for (int i=0 ; i<n ; i++) {
int isParasite = newMovementIsParasite(5);
if (isParasite) {
newDir = rand()%6;
_path.push( std::make_pair(newDir, PARASITE_SPEED));
}
else
{
_path.push( std::make_pair(newDir, MAIN_SPEED));
}
}
}
void GoldenSnitch::updatePosition(int direction, float speed) {
//std::cout << "cc " << direction << " " << speed << std::endl;
switch (direction) {
// GO RIGHT
case 0:
_position.x += speed;
//_angle.x += glm::half_pi<float>();
break;
// GO LEFT
case 1:
_position.x -= speed;
//_angle.x -= glm::half_pi<float>();
break;
// GO UP
case 2:
_position.y += speed;
break;
// GO DOWN
case 3:
_position.y -= speed;
break;
// GO FORWARD
case 4:
_position.z += speed;
break;
// GO FORWARD
default:
_position.z -= speed;
break;
}
}
void GoldenSnitch::draw(long int t) {
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, *_texture);
glUseProgram(*_shader);
glUniform1i(glGetUniformLocation(*_shader, "textureBalai"), 0);
GLuint modelTag = glGetUniformLocation(*_shader, "model");
GLuint viewTag = glGetUniformLocation(*_shader, "view");
GLuint projectionTag = glGetUniformLocation(*_shader, "projection");
glm::mat4 view(_camera->getViewMatrix());
glm::mat4 projection(glm::perspective(_camera->getZoom(), (float)1000/(float)800, 0.1f, 10000.0f));
glm::mat4 model;
model = glm::translate(model, _position);
model = glm::rotate(model, _angle.x, glm::vec3(1.f, 0, 0));
model = glm::rotate(model, _angle.y, glm::vec3(0, 1.f,0));
model = glm::rotate(model, _angle.z, glm::vec3(0, 0, 1.f));
model = glm::scale(model, glm::vec3(2, 2, 2));
glUniformMatrix4fv(modelTag, 1, GL_FALSE, glm::value_ptr(model));
glUniformMatrix4fv(viewTag, 1, GL_FALSE, glm::value_ptr(view));
glUniformMatrix4fv(projectionTag, 1, GL_FALSE, glm::value_ptr(projection));
glBindVertexArray(_vao);
glDrawElements(GL_TRIANGLES, _mesh->getNbIndices(), GL_UNSIGNED_INT, 0);
glBindTexture(GL_TEXTURE_2D, 0);
glBindVertexArray(0);
}
| true |
643607323e8434994e24294ecb791a21627280a1 | C++ | ZGWJ/PAT | /c/A1012.cpp | UTF-8 | 1,322 | 2.703125 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;
struct Student{
int ID;
int grade[4];
}stu[2010];
char course[4]={'A','C','M','E'};
int Rank[1000000][4]={0};
int now;
bool cmp(Student a,Student b){
return a.grade[now]>b.grade[now];
}
int main(){
int n,m;
scanf("%d %d",&n,&m);
for (int i=0; i<n; i++) {
scanf("%d %d %d %d",&stu[i].ID,&stu[i].grade[1],&stu[i].grade[2],&stu[i].grade[3]);
stu[i].grade[0]=stu[i].grade[1]+stu[i].grade[2]+stu[i].grade[3];
}
for (now=0; now<4; now++) {
sort(stu, stu+n, cmp);
Rank[stu[0].ID][now]=1;
for (int i=1; i<n; i++) {
if (stu[i].grade[now]==stu[i-1].grade[now]) {
Rank[stu[i].ID][now]=Rank[stu[i-1].ID][now];
}else{
Rank[stu[i].ID][now]=i+1;
}
}
}
int query;
for (int i=0; i<m; i++) {
scanf("%d",&query);
if (Rank[query][0]==0) {
printf("N/A\n");
}else{
int k=0;
for (int j=0; j<4; j++) {
if (Rank[query][j]<Rank[query][k]) {
k=j;
}
}
printf("%d %c\n",Rank[query][k],course[k]);
}
}
return 0;
} | true |
9cf4e461b0cb3cf9ee0354dda88bd2e0c92b762c | C++ | pturon/game-programming | /metroidvania/metroidvania/src/MenuManager.cpp | UTF-8 | 1,318 | 2.875 | 3 | [] | no_license | #include "../include/MenuManager.h"
void MenuManager::showDeathMenu() {
currentMenu = death;
}
void MenuManager::showWinMenu() {
currentMenu = win;
}
void MenuManager::init() {
currentMenu = noMenu;
font = TTF_OpenFont("assets/Bebas-Regular.ttf", 64);
color = { 255,255,255 };
background = TextureManager::loadTexture("assets/menu_background.png");
}
void MenuManager::update() {
switch (currentMenu) {
case win:
break;
case death:
break;
case none:
break;
default:
break;
}
}
void MenuManager::render() {
if (currentMenu == win) {
SDL_Rect destRect = { 0,0,WINDOW_WIDTH, WINDOW_HEIGHT };
SDL_Rect srcRect = { 0,0,32,32 };
TextureManager::draw(background, srcRect, destRect, SDL_FLIP_NONE);
destRect = { 280,200 ,WINDOW_WIDTH, WINDOW_HEIGHT };
std::string str = "Gewonnen";
char* char_type = (char*)str.c_str();
TextureManager::drawText(char_type, destRect, font, color);
}
else if (currentMenu == death) {
SDL_Rect destRect = { 0,0,WINDOW_WIDTH, WINDOW_HEIGHT };
SDL_Rect srcRect = { 0,0,32,32 };
TextureManager::draw(background, srcRect, destRect, SDL_FLIP_NONE);
destRect = { 290,200 ,WINDOW_WIDTH, WINDOW_HEIGHT };
std::string str = "Verloren";
char* char_type = (char*)str.c_str();
TextureManager::drawText(char_type, destRect, font, color);
}
} | true |
c5c7631bd8e309c40a85463509b5cd08e6ff1e64 | C++ | tobme/TrafficSimulator | /Map.h | UTF-8 | 1,134 | 2.75 | 3 | [] | no_license | #pragma once
#include "DrawableShape.h"
#include "IObject.h"
#include "CarStates.h"
#include<vector>
#include <SFML/Graphics.hpp>
namespace map {
class Map
{
public:
Map();
Map(unsigned int width, unsigned int height);
~Map();
template<typename T>
void add(unsigned int x, unsigned int y, T item);
bool isWalkable(const sf::Vector2f& pos) const;
const sf::Vector2f toTheLeft(const sf::Vector2f& pos, object::cars::Direction dir) const;
const sf::Vector2f toTheRight(const sf::Vector2f& pos, object::cars::Direction dir) const;
const sf::Vector2f toTheUp(const sf::Vector2f& pos, object::cars::Direction dir) const;
const sf::Vector2f toTheDown(const sf::Vector2f& pos, object::cars::Direction dir) const;
private:
using PropMap = std::vector< std::vector<base::IObject*> >;
graphics::DrawableShape* posToDrawableObject(const sf::Vector2f& pos) const;
PropMap m_map;
unsigned int m_width;
unsigned int m_height;
};
template <typename T>
inline void Map::add(unsigned int x, unsigned int y, T item)
{
m_map[x][y] = item;
}
//using Map = std::vector< std::vector<base::IObject*> >;
} | true |
24c21396e9936e2ec556b48287123f3db98f9dc1 | C++ | YanB25/MyToyCode | /designPattern/order.cpp | UTF-8 | 1,407 | 3.671875 | 4 | [] | no_license | #include <iostream>
using namespace std;
class Account {
public:
Account() : money(0) {}
Account(double m) : money(m) {}
void MoneyIn(double m) { money += m; cout << "money is " << money << endl; }
void MoneyOut(double m) { money -= m; cout << "money is " << money << endl;}
private:
double money;
};
class Command {
public:
Command(Account& account) : account_(account) {}
virtual void excute(double) = 0;
virtual ~Command(){}
protected:
Account& account_;
};
class PutInMoneyCommand : public Command {
public:
using Command::Command;
virtual void excute(double m) { account_.MoneyIn(m); }
};
class PutOutMoneyCommand : public Command {
public:
using Command::Command;
virtual void excute(double m) { account_.MoneyOut(m); }
};
class Invoker {
public:
void setCommand(Command* c) { command_ = c; }
Command* getCommand() { return command_; }
void call(double m) { command_->excute(m); }
private:
Command* command_;
};
int main() {
Account account(100);
Command* moneyIn = new PutInMoneyCommand(account);
Command* moneyOut = new PutOutMoneyCommand(account);
Invoker* invoker = new Invoker();
invoker->setCommand(moneyIn);
invoker->call(20);
delete invoker->getCommand();
invoker->setCommand(moneyOut);
invoker->call(14);
delete invoker->getCommand();
delete invoker;
return 0;
}
| true |
93b55ab40f65fe4b768664ebd23835d51bbb858b | C++ | Williams3DWorld/OpenGL-Game-Engine | /GBufferPass.h | UTF-8 | 3,170 | 2.734375 | 3 | [] | no_license | #ifndef __G_BUFFER_H__
#define __G_BUFFER_H__
#include "Pass.h" // Get access to abstract header
#include "GBufferData.h" // Get GBuffer data
#define ATTACHMENT_POSITION 0 // Define position attachment index
#define ATTACHMENT_NORMAL 1 // Define normal attachment index
#define ATTACHMENT_ALBEDO 2 // Define albedo attachment index
#define ATTACHMENT_SPECROUGH 3 // Define specular + roughness attachment index
#define ATTACHMENT_METALNESS 4 // Define metalness attachment index
#define ATTACHMENT_EMISSIVE 5 // Define emissive attachment index
#define ATTACHMENT_POSITION_SS 6 // Define normal screen space attachment index
#define ATTACHMENT_NORMAL_SS 7 // Define position screen space attachment index
// This class will store the g buffer pass in screenspace coords
class GBufferPass : public Pass
{
private:
size_t _num_attachments; // The number of attachments
public:
// Constructor
inline GBufferPass(GLuint shader_program, size_t width, size_t height)
{
Create(shader_program, width, height); // Create the post effect
}
// Initialise gbuffer
inline void Create(GLuint shader_program, size_t width, size_t height)
{
_shader_programs.push_back(shader_program); // Assign shader program
// Generate frame buffer object and it's attachments
_g_buffer_data = new Fbo(width, height, { new FboAttachment(width, height, GL_RGB16F, GL_RGB, GL_FLOAT, GL_COLOR_ATTACHMENT0, false, true), // Position colour attachment
new FboAttachment(width, height, GL_RGB16F, GL_RGB, GL_FLOAT, GL_COLOR_ATTACHMENT1), // World Normal colour attachment
new FboAttachment(width, height, GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE, GL_COLOR_ATTACHMENT2), // Albedo colour attachment
new FboAttachment(width, height, GL_RGB, GL_RGB, GL_FLOAT, GL_COLOR_ATTACHMENT3), // Specular + roughness colour attachment
new FboAttachment(width, height, GL_RGB, GL_RGB, GL_FLOAT, GL_COLOR_ATTACHMENT4), // Metalness colour attachment
new FboAttachment(width, height, GL_RGB, GL_RGB, GL_UNSIGNED_BYTE, GL_COLOR_ATTACHMENT5), // Emissive colour attachment
new FboAttachment(width, height, GL_RGB16F, GL_RGB, GL_FLOAT, GL_COLOR_ATTACHMENT6, false, true), // Position screen space attachment
new FboAttachment(width, height, GL_RGB16F, GL_RGB, GL_FLOAT, GL_COLOR_ATTACHMENT7) }, true); // Normal screen space attachment
_rbo = new Rbo(width, height, GL_DEPTH_COMPONENT, GL_DEPTH_ATTACHMENT, 1); // Generate render buffer object
_fbos.push_back(_g_buffer_data); // Assign fbo GBuffer data
_num_attachments = _fbos[0]->GetAttachments().size(); // Pre-calculate the number of attachments
}
// Virtual functions
inline virtual void Update(double delta) {}
inline virtual void Render()
{
glUseProgram(_shader_programs[0]); // Use shader program
for (size_t i = 0; i < _num_attachments; i++) // For each attachment...
{
glActiveTexture(GL_TEXTURE0 + i); // Assign active texture
glBindTexture(GL_TEXTURE_2D, _fbos[0]->GetAttachments()[i]->_texture); // Bind texture attachments
}
}
};
#endif | true |
9abf79fb75ed4f0140ca3ff9a348d04a4737f1ee | C++ | taro-masuda/leetcode | /0017_LetterCombinationsOfAPhoneNumber.cpp | UTF-8 | 1,378 | 3.109375 | 3 | [
"MIT"
] | permissive | class Solution {
private:
vector<vector<char>> num2abc = {{'\0','\0','\0','\0'},{'\0','\0','\0','\0'},
{'a', 'b', 'c','\0'}, {'d', 'e', 'f','\0'},
{'g', 'h', 'i','\0'}, {'j', 'k', 'l','\0'},
{'m', 'n', 'o','\0'}, {'p', 'q', 'r', 's'},
{'t', 'u', 'v','\0'}, {'w', 'x', 'y', 'z'}};
public:
vector<string> addLetters(vector<string> in, const char* s){
vector<string> out;
int s_num = *s - '0';
if (in.size() == 0) {
for (int j = 0; j < num2abc[s_num].size(); j++) {
if (num2abc[s_num][j] == '\0') break;
string toPush = string(1, num2abc[s_num][j]);
out.push_back(toPush);
}
} else {
for (int i = 0; i < in.size(); i++) {
for (int j = 0; j < num2abc[s_num].size(); j++) {
if (num2abc[s_num][j] == '\0') break;
string toPush = string(1, num2abc[s_num][j]);
out.push_back(in[i] + toPush);
}
}
}
return out;
}
vector<string> letterCombinations(string digits) {
vector<string> v = {};
for (int i = 0; i < digits.size(); i++){
char a = digits[i];
v = addLetters(v, &a);
}
return v;
}
};
| true |
bae7a10f30564c75c64f2826b240419b3f5c3848 | C++ | stevenireeves/GP_upsamp | /interp/cpp_pipeline/test.cpp | UTF-8 | 523 | 3.1875 | 3 | [] | no_license | #include <stdio.h>
#include <iostream>
extern "C"
{
void interpolate(float *img_in, float *img_out, const int *upsample_ratio, const int *in_size);
}
int main(){
float imgin[16] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
float imgout[256] = {};
int size[3] = {4, 4, 1};
int upsample[2] = {4, 4};
std::cout<<"Begin interpolate" << std::endl;
interpolate(imgin, imgout, upsample, size);
for(int i = 0; i < 256; i++) std::cout << imgout[i] << std::endl;
std::cout<<"End interpolate" << std::endl;
}
| true |
66650e92a3257638d6287f06342a328b08c595a4 | C++ | oliverpecha/Stanford-SEE | /CS106B/Chapter09 (Backtracking Algorithms) Book Exercises/121314. Nim/Nim.cpp | UTF-8 | 16,673 | 3.625 | 4 | [] | no_license | /*
* File: Nim.cpp
* ------------------------------------------
* This program simulates a simple variant of the game of Nim. In this
* version, the game starts with a pile of 13 coins on a table.
* Players then take turns removing 1, 2, or 3 coins from the pile.
* The player who takes the last coin loses.
*
* 12. Rewrite the simple Nim game so that it uses the generalized minimax
* algorithm presented in Figure 9-6. Your program should not change the code
* for findBestMove or evaluatePosition. Your job is to come up with an appropriate
* definition of the Move type and the various game-specific methods so that the
* program still plays a perfect game of Nim.
*
* 13. Modify the code for the simple Nim game you wrote for exercise 11 so that
* it plays a different variant of Nim. In this version, the pile begins with 17 coins.
* On each turn, players alternate taking one, two, three, or four coins from the pile.
* In the simple Nim game, the coins the players took away were simply ignored; in this
* game, the coins go into a pile for each player. The player whose pile contains an even
* number of coins after the last coin is taken wins the game.
*
* 14. In the most common variant of Nim, the coins are not combined into a single pile
* but are instead arranged in three rows like this: A move in this game consists of
* taking any number of coins, subject to the condition that all the coins must come from
* the same row. The player who takes the last coin loses.
*
* Write a program that uses the minimax algorithm to play a perfect game of three-pile Nim.
* The starting configuration shown here is a typical one, but your program should be
* general enough so that you can easily change either the number of rows or the number of
* coins in each row.
*/
#include <iostream>
#include <string>
#include "error.h"
#include "simpio.h"
#include "strlib.h"
#include "console.h"
using namespace std;
/*
* Constant: VARIANT
* --------------------------------------------
* G_VARIANT, Indicates which exercise to run. The rest of variants get configurated by InitGame();
*/
const int G_VARIANT = 12;
const int N_COINS = 0;
const int MAX_MOVE = 0;
const int ROWS = 3;
const int MAX_X_ROW = 5;
/* Constants */
const int NO_GOOD_MOVE = -1; /* Marker indicating there is no good move */
const int MAX_DEPTH = 3;
const int WINNING_POSITION = 1000;
const int LOSING_POSITION = -WINNING_POSITION;
/*
* Type: Player
* --------------------------------------------
* This enumerated type differentiates the human and computer players.
*/
enum Player { HUMAN, COMPUTER, EVEN };
/*
* Method: opponent
* Usage: Player other = opponent (player);
* --------------------------------------------
* Returns the opponent of the player. The opponent of the computer
* is the human player and vice versa.
*/
Player opponent (Player player) {
return (player == HUMAN)? COMPUTER : HUMAN;
}
/*
* Constant: STARTING_PLAYER
* --------------------------------------------
* Indicates which player should start the game.
*/
const Player STARTING_PLAYER = HUMAN;
/*
* Type: Move
* --------------------------------------------
* This struct serves the necessary steps to make a move.
*/
struct Move {
int nTaken;
string toString() {
return to_string(nTaken);
}
};
/*
* Type: Move
* --------------------------------------------
* Overloads operator for printing Moves to the console
*/
std::ostream & operator<<(std::ostream & os, Move p1);
/*
* Class: SimpleNim
* --------------------------------------------
* The SimpleNim class implements the simple version of Nim.
*/
class SimpleNim {
public:
/*
* Method: play
* Usage: game.play();
* --------------------------------------------
* Plays one game of Nim with the human player.
*/
void play() {
initGame();
while (!gameIsOver()) {
displayGame();
if (getCurrentPlayer() == HUMAN) {
makeMove(getUserMove());
} else {
Move move = getComputerMove();
displayMove(move);
makeMove(move);
}
switchTurn();
}
announceResult();
}
void oldPlay() {
nCoins = N_COINS;
whoseTurn = STARTING_PLAYER;
while (nCoins > 1) {
cout << "There are " << nCoins << " coins in the pile." << endl;
if (whoseTurn == HUMAN) {
nCoins -= oldGetUserMove();
} else {
int nTaken = oldGetComputerMove();
cout << "I'll take " << nTaken << "." << endl;
nCoins -= nTaken;
}
whoseTurn = opponent(whoseTurn);
}
announceResult();
}
/*
* Method: print Instructions
* Usage: game.print Instructions ();
* --------------------------------------------
* This method explains the rules of the game to the user.
*/
void printInstructions() {
cout << "Welcome to the game of Nim!\n" << endl;
cout << "In this variation of the game (exercise " << G_VARIANT << "), " << endl;
cout << "we will start with a pile of " << nCoins << " coins on the table." << endl;
cout << "On each turn, you and I will alternately take between 1 and" << endl;
cout << maxMove << " coins from the table. The player who" << endl;
cout << "takes the last coin loses."<< endl << endl;
}
private:
/*
* Method: getComputerMove
* Usage: int nTaken = getComputerMove ();
* --------------------------------------------
* Figures out what move is best for the computer player and returns
* the number of coins taken. The method first calls findGoodMove
* to see if a winning move exists. If none does, the program takes
* only one coin to give the human player more chances to make a mistake.
*/
Move getComputerMove() {
Move result = findBestMove();
if (result.nTaken == NO_GOOD_MOVE) {
result.nTaken = 1;
return result;
}
else return result;
//return (nTaken == NO_GOOD_MOVE) ? result.nTaken = 1 : result.nTaken = nTaken; //<----------------------------------- ADJUST
}
int oldGetComputerMove() {
int nTaken = findGoodMove (nCoins);
return (nTaken == NO_GOOD_MOVE) ? 1 : nTaken;
}
/*
* Method: findGoodMove
* Usage: int nTaken = findGoodMove (nCoins);
* --------------------------------------------
* This method looks for a winning move, given the specified number
* of coins. If there is a winning move in that position, the method
* returns that value; if not, the method returns the constant
* NO_GOOD_MOVE. This method depends on the recursive insight that a
* good move is one that leaves your opponent in a bad position and a bad
* position is one that offers no good moves.
*/
int findGoodMove (int nCoins) {
int limit = (nCoins < maxMove) ? nCoins: maxMove;
for (int nTaken = 1; nTaken <= limit; nTaken++) {
if (isBadPosition (nCoins - nTaken)) return nTaken;
}
return NO_GOOD_MOVE;
}
/*
* Method: isBadPosition
* Usage: if (isBadPosition (nCoins))
* --------------------------------------------
* This method returns true if nCoins is a bad position.
* A bad position is one in which there is no good move.
* Being left with a single coin is clearly a bad position
* and represents the simple case of the recursion.
*/
bool isBadPosition (int nCoins) {
if (nCoins == 1) return true;
return findGoodMove (nCoins) == NO_GOOD_MOVE;
}
/*
* Method: getUserMove
* Usage: int nTaken = getUserMove();
* --------------------------------------------
* Asks the user to enter a move and returns the number of coins taken.
* If the move is not legal, the user is asked to reenter a valid move.
*/
Move getUserMove() {
Move result;
while (true) {
int nTaken;
if (G_VARIANT == 14) nTaken = getInteger("\nHow many would you like to take from the current pile? ");
else nTaken = getInteger("\nHow many would you like to take? ");
updateCoinPile();
int limit = (nCoins < maxMove) ? nCoins : maxMove;
result.nTaken = nTaken;
if (nTaken > 0 && nTaken <= limit) return result;
if (maxMove == 1) cout << "That's cheating! You may only remove 1 coin" << endl;
else {
cout << " between 1 and " << limit << "." << endl;
cout << "That's cheating! Please choose a number";
cout << " between 1 and " << limit << "." << endl;
}
cout << "There are " << nCoins << " coins in the pile." << endl;
}
return result;
}
int oldGetUserMove() {
while (true) {
int nTaken = getInteger("How many would you like? ");
int limit = (nCoins < maxMove) ? nCoins : maxMove;
if (nTaken > 0 && nTaken <= limit) return nTaken;
cout << "That's cheating! Please choose a number";
cout << " between 1 and " << limit << "." << endl;
cout << "There are " << nCoins << " coins in the pile." << endl;
}
return false;
}
/*
* Method: announceResult
* Usage: announceResult();
* --------------------------------------------
* This method announces the final result of the game.
*/
void announceResult () {
if (nCoins == 0) {
cout << "That was the last coin. You lose." << endl;
} else {
cout << "There is only one coin left." << endl;
}
if (G_VARIANT == 13) {
cout << "You removed total of " << removedPile[0] << " coins. I took: " << removedPile[1] << endl;
if (whoIsEven() == COMPUTER) {
cout << "I win." << endl;
} else if (whoIsEven() == HUMAN) {
cout << "I lose." << endl;
} else cout << "We are even." << endl;
}
else if (G_VARIANT == 12 || G_VARIANT == 14) {
if (whoseTurn == COMPUTER) {
cout << "I lose." << endl;
} else if (whoseTurn == HUMAN) {
cout << "I win." << endl;
}
}
}
/*
* Method: findBestMove
* Usage: Move move = findBestMove();
* Move move = findBestMove (depth, rating);
* --------------------------------------------
* Finds the best move for the current player and returns that move as the
* value of the function. The second form is used for later recursive calls
* and includes two parameters. The depth parameter is used to limit the
* depth of the search for games that are too difficult to analyze. The
* reference parameter rating is used to store the rating of the best move.
*/
Move findBestMove() {
int rating;
return findBestMove (0, rating);
}
Move findBestMove (int depth, int & rating) {
Vector<Move> moveList;
Move bestMove;
int minRating = WINNING_POSITION + 1;
generateMoveList(moveList);
if (moveList.isEmpty()) error ("No moves available");
for (Move move : moveList) {
makeMove(move);
int moveRating = evaluatePosition(depth + 1);
if (moveRating < minRating) {
bestMove = move;
minRating = moveRating;
}
retractMove (move) ;
}
rating = -minRating;
return bestMove;
}
void generateMoveList(Vector<Move> & moveList){
updateCoinPile();
int limit = (nCoins < maxMove) ? nCoins: maxMove;
for (int nTaken = 1; nTaken <= limit; nTaken++) {
Move result;
result.nTaken = nTaken;
moveList.add(result);
}
}
/*
* Method: evaluatePosition
* Usage: int rating = evaluatePosition (depth);
* --------------------------------------------
* Evaluates a position by finding the rating of the best move starting at
* that point. The depth parameter is used to limit the search depth.
*/
int evaluatePosition(int depth) {
if (gameIsOver() || depth >= MAX_DEPTH) {
return evaluateStaticPosition();
}
int rating;
findBestMove(depth, rating);
return rating;
}
int evaluateStaticPosition() {
if ((G_VARIANT == 12 || G_VARIANT == 14) && nCoins == 1) return -10;
else if (G_VARIANT == 13 && nCoins == 0 && whoIsEven() == COMPUTER ) return -10;
//else if (G_VARIANT == 14) {
// }
else return 10;
}
/*
* Methods to help play public function
* --------------------------------------------
* Evaluates a position by finding the rating of the best move starting at
* that point. The depth parameter is used to limit the search depth.
*/
void initGame(){
if (G_VARIANT == 12) {
nCoins = 13;
maxMove = 3;
} else if (G_VARIANT == 13) {
nCoins = 17;
maxMove = 4;
} else if (G_VARIANT == 14) {
int nXrow = MAX_X_ROW - 1 * (ROWS - 1);
Vector<int> tempRow;
for (int y = 0; y < ROWS; ++y) {
int tempColumn = 0;
for (int x = 0; x < nXrow; ++x) {
tempColumn += 1;
}
nXrow++;
tempRow.add(tempColumn);
}
coinPile = tempRow;
updateCoinPile();
}
printInstructions();
whoseTurn = STARTING_PLAYER;
Vector<int> initializer {0,0};
removedPile = initializer;
}
bool gameIsOver() {
int playtill = 1 ;
if (G_VARIANT == 13) playtill = 0;
if (nCoins > playtill) return false;
else return true;
}
void displayGame(){
cout << "There are " << nCoins << " coins in the table. " << endl;
if (G_VARIANT == 13) cout << "So far, you have removed " << removedPile[HUMAN] << " coins, and I have removed " << removedPile[COMPUTER] << ". "<< endl;
if (G_VARIANT == 14) {
updateCoinPile();
cout << "They are distributed in " << coinPile.size() << " piles. " << endl;
cout <<"You may remove as many as you would like from the last one, \nwhich now holds " << maxMove << " coins."<< endl;
}
}
void displayMove(Move move){
cout << "I'll take " << move.nTaken << "." << endl;
}
void makeMove(Move move) {
if (getCurrentPlayer() == HUMAN) {
removedPile[HUMAN] += move.nTaken;
}
else removedPile[COMPUTER] += move.nTaken;
if (G_VARIANT == 14) coinPile[getCurrentRow()] -= move.nTaken;
nCoins -= move.nTaken;
}
void retractMove(Move move){
nCoins += move.nTaken;
removedPile[COMPUTER] -= move.nTaken;
if (G_VARIANT == 14) {
int currentRow = getCurrentRow();
int nExpected = MAX_X_ROW - ROWS + currentRow + 1;
if (coinPile[getCurrentRow()] == nExpected) {
// means the last coin is at the end of the current pile, and the revert move should go to the upper pile
currentRow++;
}
coinPile[currentRow] += move.nTaken;
}
}
void updateCoinPile() {
if (G_VARIANT == 14) {
nCoins = 0;
for (int var = 0; var < coinPile.size(); ++var) {
nCoins += coinPile[var];
}
maxMove = coinPile[getCurrentRow()];
}
}
int getCurrentRow() {
for (int var = coinPile.size() - 1; var >= 0 ; --var) {
if (coinPile[var] > 0) return var;
}
return 0;
}
Player getCurrentPlayer() {
return whoseTurn;
}
void switchTurn() {
whoseTurn = opponent(whoseTurn);
}
Player whoIsEven(){
Player winner = HUMAN;
if (removedPile[HUMAN] % 2 == 0 && removedPile[COMPUTER] % 2 == 0) winner = EVEN;
else if (removedPile[HUMAN] % 2 != 0 && removedPile[COMPUTER] % 2 == 0) winner = COMPUTER;
return winner;
}
/* Instance variables */
int nCoins; /* Number of coins left on the table */
int coinsInRow;
int maxMove;
Player whoseTurn; /* Identifies which player moves next */
Vector<int> removedPile; /* Pile of number of coins each player removed from on the table */
Vector<int> coinPile;
};
/* Main program */
int main() {
SimpleNim game;
game.play();
return 0;
}
/* Overloads operator for printing Moves to the console*/
std::ostream & operator<<(std::ostream & os, Move p1) {
return os << p1.toString();
}
| true |
bf1d81678c778d02e78ee8a5bee73d6aa66e25cb | C++ | jfbaltazar/PROG-proj2 | /Board.h | UTF-8 | 418 | 3.171875 | 3 | [] | no_license | #pragma once
#include <string>
#include <vector>
class Board {
public:
explicit Board(unsigned size);
char getLetter(const int &x, const int &y) const;
void setLetter(const int &x, const int &y, char letter);
unsigned getSize() const;
bool validPos(const int &x, const int &y) const;
void show(std::ostream &out) const;
private:
std::vector<std::vector<char>> board;
unsigned size;
}; | true |
8a85a145befb6fd3d90954d596ee7fd3b00665af | C++ | Ubpa/RenderLab | /src/Engine/Light/SpotLight.cpp | UTF-8 | 1,110 | 2.703125 | 3 | [
"MIT"
] | permissive | #include <Engine/Light/SpotLight.h>
using namespace Ubpa;
using namespace std;
float SpotLight::Fwin(float d, float radius) {
float ratio = d / radius;
float ratio2 = ratio * ratio;
float ratio4 = ratio2 * ratio2;
float falloff = std::max(0.f, 1.f - ratio4);
return falloff * falloff;
}
const rgbf SpotLight::Sample_L(const pointf3 & p, normalf & wi, float & distToLight, float & PD) const {
const auto d = p.cast_to<vecf3>();
float dist2 = d.norm2();
distToLight = sqrt(dist2);
float falloff = Fwin(distToLight, radius);
if (falloff == 0.f) {
PD = 0;
return rgbf(0.f);
}
wi = -(d / distToLight).cast_to<normalf>();
PD = 1.0f;
return Falloff(wi) * intensity * color / dist2 * falloff;
}
float SpotLight::Falloff(const normalf & wi) const {
float rAngle = to_radian(angle);
float cosAngle = cos(rAngle / 2);
float cosFalloffAngle = cos(rAngle * fullRatio / 2);
float cosTheta = wi[1];
if (cosTheta < cosAngle) return 0;
if (cosTheta > cosFalloffAngle) return 1;
float delta = (cosTheta - cosAngle) /
(cosAngle - cosFalloffAngle);
return (delta * delta) * (delta * delta);
}
| true |
c0f4a731f0edb7814d17d6f5ccc75e99920d8158 | C++ | bsuir-labs/getmanskaya | /Lab2/main.cpp | UTF-8 | 3,939 | 3.640625 | 4 | [] | no_license | #define _CRT_SECURE_NO_WARNINGS 1
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <algorithm>
#include <cstring>
#include <ctype.h>
using namespace std;
int rangeReadInt(int minimal, int maximal, const char* prompt);
void flush_stdin();
int recursiveFind(const int* array, int left, int right, int element);
int nonrecursiveFind(const int* array, unsigned size, int element);
void generateArray(int* array, unsigned size);
void printArray(int* array, unsigned size);
// Menu choice function
int getMainMenuChoice();
// Main menu options
void menu_RecursiveImpl(const int* array, const unsigned size);
void menu_NonRecursiveImpl(const int* array, const unsigned size);
int main()
{
const unsigned kSize = 20;
int array[kSize];
generateArray(array, kSize);
bool stopRequested = false;
while (!stopRequested)
{
switch (getMainMenuChoice()) {
case 1: generateArray(array, kSize); break;
case 2: menu_RecursiveImpl(array, kSize); break;
case 3: menu_NonRecursiveImpl(array, kSize); break;
case 4:
stopRequested = true;
printf("GoodBye! Have a nice day!\n");
break;
default: printf("Something went wrong.");
}
getc(stdin);
}
return 0;
}
int rangeReadInt(int minimal, int maximal, const char *prompt)
{
bool ok = false;
int result;
do
{
printf("%s", prompt);
ok = scanf("%d", &result) == 1;
ok &= result >= minimal && result <= maximal;
flush_stdin();
if (!ok)
printf("Please, input a value between %d and %d (inclusive)\n", minimal, maximal);
} while (!ok);
return result;
}
void flush_stdin()
{
char c;
while ((c = getc(stdin)) != '\n' && c != EOF);
}
int getMainMenuChoice()
{
int choice = 0;
int point = 0;
printf("*** MAIN MENU ***\n\n");
printf("Number | Action\n");
printf("---------------\n");
printf("%6d | Regenerate array\n", ++point);
printf("%6d | Recursive binary search\n", ++point);
printf("%6d | Non-recursive binary search\n", ++point);
printf("%6d | Quit\n", ++point);
choice = rangeReadInt(1, point, "Your choice > ");
return choice;
}
int recursiveFind(const int* array, int left, int right, int element)
{
if (left == right)
{
if (array[left] == element)
return left;
else
return -1;
}
int mid = (left + right) / 2;
if (element > array[mid])
return recursiveFind(array, mid + 1, right, element);
else
return recursiveFind(array, left, mid, element);
}
int nonrecursiveFind(const int* array, unsigned size, int element)
{
int left = 0, right = size - 1;
while (left < right)
{
int mid = (left + right) / 2;
if (element > array[mid])
left = mid + 1;
else
right = mid;
}
if (array[left] == element) return left;
return -1;
}
void generateArray(int* array, unsigned size)
{
srand(time(nullptr));
for (unsigned i = 0; i < size; ++i)
array[i] = rand() % 50 - 20;
std::sort(array, array + size);
printf("Generated array:\n");
printArray(array, size);
}
void printArray(int* array, unsigned size)
{
for (unsigned i = 0; i < size; ++i)
printf("%4d", array[i]);
printf("\n");
}
void menu_RecursiveImpl(const int* array, const unsigned size)
{
int elementToFind = rangeReadInt(-100, 100, "Specify element to find: ");
int result = recursiveFind(array, 0, size - 1, elementToFind);
printf("\t\tRecursive result: %d\n", result);
}
void menu_NonRecursiveImpl(const int* array, const unsigned size)
{
int elementToFind = rangeReadInt(-100, 100, "Specify element to find: ");
int result = nonrecursiveFind(array, size, elementToFind);
printf("\t\tNon-recursive result: %d\n", result);
}
| true |
cf8076ea28730fcc0d65f8edd262eac5d21739ec | C++ | oborges/CPP | /strings/extractExtension.cpp | UTF-8 | 632 | 3.34375 | 3 | [] | no_license | //string_view usage demo
#include <string>
#include <iostream>
using namespace std;
string_view extractExtension(string_view fileName)
{
return fileName.substr(fileName.rfind('.'));
}
int main()
{
string fileName = R"(./my file.ext)";
cout << "C++ string: " << extractExtension(fileName) << endl;
const char* cString = R"(./my file.ext)";
cout << "C string: " << extractExtension(cString) << endl;
cout << "Literal: " << extractExtension(R"(./my file.ext)") << endl;
//sv string_view literal
auto sv = "My string_view"sv;
cout << "string_view literal: " << sv << endl;
return 0;
} | true |
ed49640dc7977bab351e53c1d0644ec877e3e2f6 | C++ | phrimm136/Study | /Bookshelf/C++ Primer Plus/Chapter 8/Exercise 2.cpp | UTF-8 | 914 | 3.921875 | 4 | [] | no_license | #include <iostream>
#include <string>
struct CandyBar
{
std::string brandname;
double weight;
int calories;
};
void set(CandyBar &, std::string brandname = "Millennium Munch", double weight = 2.85, int calories = 350);
void print(const CandyBar &);
int main(int argc, char *argv[])
{
CandyBar bar1, bar2;
std::string brandname;
double weight;
int calories;
std::cout << "Insert a name, weight, and calories for a candy bar: ";
std::cin >> brandname >> weight >> calories;
set(bar1);
set(bar2, brandname, weight, calories);
print(bar1);
print(bar2);
return 0;
}
void set(CandyBar &bar, std::string brandname, double weight, int calories)
{
bar.brandname = brandname;
bar.weight = weight;
bar.calories = calories;
}
void print(const CandyBar &bar)
{
std::cout << bar.brandname << "\n" << bar.weight << "\n" << bar.calories << "\n\n";
}
| true |
7f4475ddfed39a82ab5f356308a79c60cf04d46c | C++ | cevinclein/IP-Projects | /Uebung 8/Aufgabe2.cc | UTF-8 | 6,242 | 3.765625 | 4 | [] | no_license | #include <iostream>
//Enhält Aufgabe 2a und 2b, habe private Methoden definiert, auch Listen-Elemente
//sind privat, sowie Variablen eben. Alles andere wie gefordert in die Klasse
//geschrieben
//Signatur Interface, nur Definitionen
class IntList
{
public:
// Konstruktor, erzeugt eine leere Liste
IntList();
//Copy-Konstruktor
IntList(const IntList& il);
//Zuweisung
IntList& operator=(const IntList& other);
// Destruktor, loescht gesamten Listeninhalt
~IntList();
// Gibt Anzahl der Elemente zurueck
int getCount();
// Gibt zurueck, ob die Liste leer ist
bool isEmpty();
// Gibt die Liste aus
void print();
// Fuegt die Zahl 'element' an der (beliebigen) Position 'position' ein
void insert(int element, int position);
// Loescht das Element an der Position 'position'
void remove(int position);
// Gibt den Wert des Elements an der Position 'position' zurueck
int getElement(int position);
private:
int _count;
struct IntListElem;
IntListElem* first;
};
//Im Folgenden Implementierung der Methoden, man kann Signatur und
//Implementierung auch in Dateien auslagern wenn man will oder wenn es
//Sinn macht.
//Listenelement, in Klasse definiert
struct IntList::IntListElem
{
IntListElem* next;
int value;
};
//Init
IntList::IntList()
{
this->_count = 0;
this->first = nullptr;
}
//Destruktor, löscht alle dynamisch erzeugten Elemente der
//Liste, wenn Umgebung verlassen wird
IntList::~IntList()
{
while(this->first != nullptr)
{
this->remove(0);
}
std::cout << "Destruktor: Liste gelöscht!" << std::endl;
}
int IntList::getCount()
{
return this->_count;
}
//Standart-Position 0, wenn position nicht angegeben wird!
void IntList::insert(int element, int position = 0)
{
//position nur kleiner gleich als Liste, größer Null
if(position <= this->_count && position >= 0)
{
//Alle Listenelemente dynamisch erzeugt.
IntListElem* el = new IntListElem;
el->value = element;
//Aus Skript
if (position == 0)
{
el->next = this->first;
this->first = el;
}
else
{
//Listenelement an Position i finden, Zeiger umbiegen, p einfügen
//insert aus Skript
int i = 0;
for(IntListElem* p = this->first; p != nullptr; p = p->next)
{
i++;
if(position == i)
{
el->next = p->next;
p->next = el;
break;
}
}
}
this->_count++;
}
else
{
std::cout << "Falsch!" << std::endl;
}
}
void IntList::remove(int position)
{
//position mit erlaubten Werten
if(position <= this->_count && position >= 0)
{
//zu löschendes Element
IntListElem* p;
//Aus Skript
if(position == 0)
{
p = this->first;
if(p != nullptr)
{
this->first = p->next;
p = nullptr;
delete p;
this->_count--;
}
}
else
{
int i = 0;
//Gehe solange next bis i = position, lösche p mit der
//dynamischen Speicherverwaltung, biege Zeiger um
for(p = this->first; p != nullptr; p = p->next)
{
i++;
if(position == i)
{
p->next = p->next->next;
p = nullptr;
delete p;
this->_count--;
break;
}
}
}
}
else
{
std::cout << "Falsch!" << std::endl;
}
}
//Ausgabe der gesamten Liste
void IntList::print()
{
std::cout << "IntList" << std::endl << "{" << std::endl;
int i = 0;
for(IntListElem* p = this->first; p != nullptr; p = p->next)
{
std::cout << " " << i << ": " << p->value << std::endl;
i++;
}
std::cout << "}" << std::endl;
}
//Ausgabe einzelnes Element
int IntList::getElement(int position)
{
int i = 0;
for(IntListElem* p = this->first; p != nullptr; p = p->next)
{
if(position == i)
{
return p->value;
}
i++;
}
return 0;
}
bool IntList::isEmpty()
{
return this->_count == 0 ? true : false;
}
//Zuweisung
IntList& IntList::operator=(const IntList& other)
{
//Nicht sich selbst zuweisen
if(this != &other)
{
//Liste Leeren, alle dyn. erzeugten Elemente löschen
while(this->first != nullptr)
{
this->remove(0);
}
//Elemente von other übergeben
int i = 0; for (IntListElem* p = other.first; p != 0; p = p->next)
{
this->insert(p->value, i);
i++;
}
}
return *this;
}
//Copy-Konstruktor, für neue Instanzen usw...
IntList::IntList(const IntList& il)
{
int i = 0; for (IntListElem* p = il.first; p != 0; p = p->next)
{
this->insert(p->value, i);
i++;
}
this->_count = il._count;
}
int main()
{
IntList list;
list.insert(30);
list.insert(20);
list.insert(10);
list.print();
list.remove(2);
std::cout << "Element auf index[2] entfernt" << std::endl;
list.print();
list.insert(30, 2);
std::cout << "Element 30 auf index[2] gesetzt" << std::endl;
list.print();
list.insert(40, 3);
std::cout << "Element 40 auf index[3] gesetzt" << std::endl;
list.print();
IntList copy(list);
std::cout << "Copy-Konstrukt. Kopieren von list in copy" << std::endl;
std::cout << "copy, ";
copy.print();
copy.remove(0);
std::cout << "Element auf index[0] entfernt, von copy" << std::endl;
std::cout << "copy, ";
copy.print();
list.print();
copy = list;
std::cout << "copy = list" << std::endl;
std::cout << "copy, ";
copy.print();
return 0;
} | true |
d47e6d39120681b30f3ec3e572c975fb6c31b643 | C++ | tuw-robotics/tuw_marker_detection | /tuw_aruco/aruco-2.0.10/src/markerlabelers/dictionary_based.cpp | UTF-8 | 4,456 | 2.609375 | 3 | [
"BSD-2-Clause"
] | permissive | #include "dictionary_based.h"
#include <bitset>
#include <opencv2/imgproc/imgproc.hpp>
namespace aruco{
void DictionaryBased::setParams(const Dictionary &dic,float max_correction_rate){
_dic=dic;
max_correction_rate=max(0.f,min(1.0f,max_correction_rate));
_maxCorrectionAllowed=float(_dic.tau())*max_correction_rate;
}
std::string DictionaryBased::getName()const{
return aruco::Dictionary::getTypeString( _dic.getType());
}
void DictionaryBased::toMat(uint64_t code,int nbits_sq,cv::Mat &out) {
out.create(nbits_sq,nbits_sq,CV_8UC1);
bitset<64> bs(code);
int curbit=0;
for(int r=0;r<nbits_sq;r++){
uchar *pr=out.ptr<uchar>(r);
for(int c=0;c<nbits_sq;c++)
pr[c] = bs[curbit];
}
}
int hamm_distance(uint64_t a,uint64_t b){
uint64_t v=a&b;
uint64_t mask=0x1;
int d=0;
for(int i=0;i<63;i++){
d+= mask&v;
v=v<<1;
}
return d;
}
bool DictionaryBased::detect(const cv::Mat &in, int & marker_id,int &nRotations) {
assert(in.rows == in.cols);
cv::Mat grey;
if (in.type() == CV_8UC1) grey = in;
else cv::cvtColor(in, grey, CV_BGR2GRAY);
// threshold image
cv::threshold(grey, grey, 125, 255, cv::THRESH_BINARY | cv::THRESH_OTSU);
vector<uint64_t> ids;
//get the ids in the four rotations (if possible)
if ( !getInnerCode( grey,_dic.nbits(),ids)) return false;
//find the best one
for(int i=0;i<4;i++){
if ( _dic.is(ids[i])){//is in the set?
nRotations=i;//how many rotations are and its id
marker_id=_dic[ids[i]];
return true;//bye bye
}
}
//you get here, no valid id :(
//lets try error correction
if(_maxCorrectionAllowed>0){//find distance to map elements
for(auto ci:_dic.getMapCode()){
for(int i=0;i<4;i++){
if (hamm_distance(ci.first,ids[i])<_maxCorrectionAllowed){
marker_id=ci.second;
nRotations=i;
return true;
}
}
}
}
else return false;
}
bool DictionaryBased::getInnerCode(const cv::Mat &thres_img,int total_nbits,vector<uint64_t> &ids){
int bits_a=sqrt(total_nbits);
int bits_a2=bits_a+2;
// Markers are divided in (bits_a+2)x(bits_a+2) regions, of which the inner bits_axbits_a belongs to marker info
// the external border shoould be entirely black
int swidth = thres_img.rows / bits_a2;
for (int y = 0; y < bits_a2; y++) {
int inc = bits_a2-1;
if (y == 0 || y == bits_a2-1)
inc = 1; // for first and last row, check the whole border
for (int x = 0; x < bits_a2; x += inc) {
cv::Mat square = thres_img(cv::Rect(x*swidth, y*swidth, swidth, swidth));
if (cv::countNonZero(square) > (swidth * swidth) / 2)
return false; // can not be a marker because the border element is not black!
}
}
// now,
// get information(for each inner square, determine if it is black or white)
// now,
cv::Mat _bits = cv::Mat::zeros(bits_a, bits_a, CV_8UC1);
// get information(for each inner square, determine if it is black or white)
for (int y = 0; y < bits_a; y++) {
for (int x = 0; x < bits_a; x++) {
int Xstart = (x + 1) * (swidth);
int Ystart = (y + 1) * (swidth);
cv::Mat square = thres_img(cv::Rect(Xstart, Ystart, swidth, swidth));
int nZ = cv::countNonZero(square);
if (nZ > (swidth * swidth) / 2)
_bits.at< uchar >(y, x) = 1;
}
}
//now, get the 64bits ids
int nr=0;
do{
ids.push_back(touulong(_bits));
_bits=rotate(_bits);
nr++;
}while(nr<4);
return true;
}
//convert matrix of (0,1)s in a 64 bit value
uint64_t DictionaryBased::touulong(const cv::Mat &code){
std::bitset<64> bits;
int bidx=0;
for (int y = code.rows-1; y >=0 ; y--)
for (int x = code.cols-1; x >=0; x--)
bits[bidx++]=code.at<uchar>(y,x);
return bits.to_ullong();
}
cv::Mat DictionaryBased::rotate(const cv::Mat &in) {
cv::Mat out;
in.copyTo(out);
for (int i = 0; i < in.rows; i++) {
for (int j = 0; j < in.cols; j++) {
out.at< uchar >(i, j) = in.at< uchar >(in.cols - j - 1, i);
}
}
return out;
}
}
| true |
a365028e1453af5df39d7610203552adc055e167 | C++ | lucasvictorsp/ArduinoDataLogLibary | /string.cpp | UTF-8 | 152 | 2.828125 | 3 | [
"MIT"
] | permissive | String floatToString(float f){
String stringOne = String(5.698, 3); // using a float and the decimal places
return stringOne;
}
| true |
09eadfc244b6190a87eb5b3e600b6499b3ebecc0 | C++ | CodeBlueDev/DungeonKeeperGoldTrainer | /DKH/DKH.cpp | UTF-8 | 1,186 | 2.78125 | 3 | [] | no_license | #pragma once
#include <Windows.h>
DWORD* GoldBaseAddress = (DWORD*)0x0074B6B0;
DWORD GoldDisplayOffset = 0x499082;
DWORD GoldValueOffset = 0x499086;
WORD GoldAdded = 25000;
bool isAttached = true;
bool isRunning = true;;
DWORD __stdcall GoldIncrease()
{
DWORD* goldDisplayAddress = (DWORD*)(*GoldBaseAddress+GoldDisplayOffset);
DWORD* goldValueAddress = (DWORD*)(*GoldBaseAddress+GoldValueOffset);
bool keyPressed;
while(isAttached)
{
DWORD oldProtection;
while(GetAsyncKeyState(VK_NUMPAD0) && !keyPressed)
{
keyPressed = true;
VirtualProtect(goldDisplayAddress, 8, PAGE_EXECUTE_READWRITE, &oldProtection);
*goldDisplayAddress += GoldAdded;
*goldValueAddress += GoldAdded;
VirtualProtect(goldDisplayAddress, 8, oldProtection, &oldProtection);
}
keyPressed = false;
Sleep(100);
}
isRunning = false;
return 1;
}
bool WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpvReserved)
{
switch(dwReason)
{
case DLL_PROCESS_ATTACH:
CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)GoldIncrease, NULL, NULL, NULL);
break;
case DLL_PROCESS_DETACH:
isAttached = false;
while(isRunning)
{
Sleep(100);
}
break;
}
return true;
} | true |