blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 2
247
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
57
| license_type
stringclasses 2
values | repo_name
stringlengths 4
111
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
58
| visit_date
timestamp[ns]date 2015-07-25 18:16:41
2023-09-06 10:45:08
| revision_date
timestamp[ns]date 1970-01-14 14:03:36
2023-09-06 06:22:19
| committer_date
timestamp[ns]date 1970-01-14 14:03:36
2023-09-06 06:22:19
| github_id
int64 3.89k
689M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 25
values | gha_event_created_at
timestamp[ns]date 2012-06-07 00:51:45
2023-09-14 21:58:52
⌀ | gha_created_at
timestamp[ns]date 2008-03-27 23:40:48
2023-08-24 19:49:39
⌀ | gha_language
stringclasses 159
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 7
10.5M
| extension
stringclasses 111
values | filename
stringlengths 1
195
| text
stringlengths 7
10.5M
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b74f7ab01587caf3da455d65557f764308c4e07a
|
cf8182ecc88888719cfaff79751834500800151a
|
/src/shogun/structure/Factor.cpp
|
bbe14fb21220a8ee620992761bec8638d7e79e7e
|
[
"BSD-3-Clause",
"DOC",
"GPL-3.0-only"
] |
permissive
|
shogun-toolbox/shogun
|
17beb82a04fbf1179d300c4fcd16ee68850ad994
|
9b8d856971af5a295dd6ad70623ae45647a6334c
|
refs/heads/develop
| 2023-03-11T04:46:36.167073
| 2020-12-08T16:56:38
| 2020-12-08T16:56:38
| 1,555,094
| 2,938
| 1,246
|
BSD-3-Clause
| 2022-08-12T11:12:34
| 2011-04-01T10:44:32
|
C++
|
UTF-8
|
C++
| false
| false
| 7,644
|
cpp
|
Factor.cpp
|
/*
* This software is distributed under BSD 3-clause license (see LICENSE file).
*
* Authors: Shell Hu, Heiko Strathmann, Jiaolong Xu, Bjoern Esser,
* Sergey Lisitsyn
*/
#include <shogun/structure/Factor.h>
#include <utility>
using namespace shogun;
Factor::Factor() : SGObject()
{
init();
}
Factor::Factor(const std::shared_ptr<FactorType>& ftype,
SGVector<int32_t> var_index,
SGVector<float64_t> data) : SGObject()
{
auto table_factor = std::dynamic_pointer_cast<TableFactorType>(ftype);
require(table_factor, "Expected type of class TableFactorType");
init();
m_factor_type = table_factor;
m_var_index = var_index;
m_data = data;
m_is_data_dep = true;
ASSERT(m_factor_type != NULL);
ASSERT(m_factor_type->get_cardinalities().size() == m_var_index.size());
if (m_data.size() == 0)
m_is_data_dep = false;
if (table_factor->is_table() && m_is_data_dep)
m_energies.resize_vector(table_factor->get_num_assignments());
}
Factor::Factor(const std::shared_ptr<FactorType>& ftype,
SGVector<int32_t> var_index,
SGSparseVector<float64_t> data_sparse) : SGObject()
{
auto table_factor = std::dynamic_pointer_cast<TableFactorType>(ftype);
require(table_factor, "Expected type of class TableFactorType");
init();
m_factor_type = table_factor;
m_var_index = var_index;
m_data_sparse = data_sparse;
m_is_data_dep = true;
ASSERT(m_factor_type != NULL);
ASSERT(m_factor_type->get_cardinalities().size() == m_var_index.size());
if (m_data_sparse.num_feat_entries == 0)
m_is_data_dep = false;
if (table_factor->is_table() && m_is_data_dep)
m_energies.resize_vector(table_factor->get_num_assignments());
}
Factor::Factor(const std::shared_ptr<FactorType>& ftype,
SGVector<int32_t> var_index,
std::shared_ptr<FactorDataSource> data_source) : SGObject()
{
auto table_factor = std::dynamic_pointer_cast<TableFactorType>(ftype);
require(table_factor, "Expected type of class TableFactorType");
init();
m_factor_type = table_factor;
m_var_index = var_index;
m_data_source = std::move(data_source);
m_is_data_dep = true;
ASSERT(m_factor_type != NULL);
ASSERT(m_factor_type->get_cardinalities().size() == m_var_index.size());
ASSERT(m_data_source != NULL);
if (table_factor->is_table())
m_energies.resize_vector(table_factor->get_num_assignments());
}
Factor::~Factor()
{
}
std::shared_ptr<FactorType> Factor::get_factor_type() const
{
return m_factor_type;
}
void Factor::set_factor_type(std::shared_ptr<FactorType> ftype)
{
auto table_factor = std::dynamic_pointer_cast<TableFactorType>(ftype);
require(table_factor, "Expected type of class TableFactorType");
m_factor_type = std::move(table_factor);
}
const SGVector<int32_t> Factor::get_variables() const
{
return m_var_index;
}
const int32_t Factor::get_num_vars() const
{
return m_var_index.size();
}
void Factor::set_variables(SGVector<int32_t> vars)
{
m_var_index = vars.clone();
}
const SGVector<int32_t> Factor::get_cardinalities() const
{
return m_factor_type->get_cardinalities();
}
SGVector<float64_t> Factor::get_data() const
{
if (m_data_source != NULL)
return m_data_source->get_data();
return m_data;
}
SGSparseVector<float64_t> Factor::get_data_sparse() const
{
if (m_data_source != NULL)
return m_data_source->get_data_sparse();
return m_data_sparse;
}
void Factor::set_data(SGVector<float64_t> data_dense)
{
m_data = data_dense.clone();
m_is_data_dep = true;
}
void Factor::set_data_sparse(SGSparseVectorEntry<float64_t>* data_sparse,
int32_t dlen)
{
m_data_sparse = SGSparseVector<float64_t>(data_sparse, dlen);
m_is_data_dep = true;
}
bool Factor::is_data_dependent() const
{
return m_is_data_dep;
}
bool Factor::is_data_sparse() const
{
if (m_data_source != NULL)
return m_data_source->is_sparse();
return (m_data.size() == 0);
}
SGVector<float64_t> Factor::get_energies() const
{
if (is_data_dependent() == false && m_energies.size() == 0)
{
const SGVector<float64_t> ft_energies = m_factor_type->get_w();
ASSERT(ft_energies.size() == m_factor_type->get_num_assignments());
return ft_energies;
}
return m_energies;
}
float64_t Factor::get_energy(int32_t index) const
{
return get_energies()[index]; // note for data indep, we get m_w not m_energies
}
void Factor::set_energies(SGVector<float64_t> ft_energies)
{
require(m_factor_type->get_num_assignments() == ft_energies.size(),
"{}::set_energies(): ft_energies is not a valid energy table!", get_name());
m_energies = ft_energies;
}
void Factor::set_energy(int32_t ei, float64_t value)
{
require(ei >= 0 && ei < m_factor_type->get_num_assignments(),
"{}::set_energy(): ei is out of index!", get_name());
require(is_data_dependent(), "{}::set_energy(): \
energy table is fixed in data dependent factor!", get_name());
m_energies[ei] = value;
}
float64_t Factor::evaluate_energy(const SGVector<int32_t> state) const
{
int32_t index = m_factor_type->as<TableFactorType>()->index_from_universe_assignment(state, m_var_index);
return get_energy(index);
}
void Factor::compute_energies()
{
if (is_data_dependent() == false)
return;
// For some factor types the size of the energy table is determined only
// after an initialization step from training data.
if (m_energies.size() == 0)
m_energies.resize_vector(m_factor_type->as<TableFactorType>()->get_num_assignments());
const SGVector<float64_t> H = get_data();
const SGSparseVector<float64_t> H_sparse = get_data_sparse();
if (H_sparse.num_feat_entries == 0)
m_factor_type->as<TableFactorType>()->compute_energies(H, m_energies);
else
m_factor_type->as<TableFactorType>()->compute_energies(H_sparse, m_energies);
}
void Factor::compute_gradients(
const SGVector<float64_t> marginals,
SGVector<float64_t>& parameter_gradient,
float64_t mult) const
{
const SGVector<float64_t> H = get_data();
const SGSparseVector<float64_t> H_sparse = get_data_sparse();
if (H_sparse.num_feat_entries == 0)
m_factor_type->as<TableFactorType>()->compute_gradients(H, marginals, parameter_gradient, mult);
else
m_factor_type->as<TableFactorType>()->compute_gradients(H_sparse, marginals, parameter_gradient, mult);
}
void Factor::init()
{
SG_ADD((std::shared_ptr<SGObject>*)&m_factor_type, "type_name", "Factor type name");
SG_ADD(&m_var_index, "var_index", "Factor variable index");
SG_ADD(&m_energies, "energies", "Factor energies");
SG_ADD((std::shared_ptr<SGObject>*)&m_data_source, "data_source", "Factor data source");
SG_ADD(&m_data, "data", "Factor data");
SG_ADD(&m_data_sparse, "data_sparse", "Sparse factor data");
SG_ADD(&m_is_data_dep, "is_data_dep", "Factor is data dependent or not");
m_factor_type=NULL;
m_data_source=NULL;
m_is_data_dep = false;
}
FactorDataSource::FactorDataSource() : SGObject()
{
init();
}
FactorDataSource::FactorDataSource(SGVector<float64_t> dense)
: SGObject()
{
init();
m_dense = dense;
}
FactorDataSource::FactorDataSource(SGSparseVector<float64_t> sparse)
: SGObject()
{
init();
m_sparse = sparse;
}
FactorDataSource::~FactorDataSource()
{
}
bool FactorDataSource::is_sparse() const
{
return (m_dense.size() == 0);
}
SGVector<float64_t> FactorDataSource::get_data() const
{
return m_dense;
}
SGSparseVector<float64_t> FactorDataSource::get_data_sparse() const
{
return m_sparse;
}
void FactorDataSource::set_data(SGVector<float64_t> dense)
{
m_dense = dense.clone();
}
void FactorDataSource::set_data_sparse(SGSparseVectorEntry<float64_t>* sparse,
int32_t dlen)
{
m_sparse = SGSparseVector<float64_t>(sparse, dlen);
}
void FactorDataSource::init()
{
SG_ADD(&m_dense, "dense", "Shared data");
SG_ADD(&m_sparse, "sparse", "Shared sparse data");
}
|
82998e82eed90333434cb7e909924bf043bf0659
|
17e6891e863fba80ad6080f802351c9514f8f33d
|
/remove_invalid_paranthesis.cc
|
b2352bf8ed167598b0fb6f77df495801c57b7dc2
|
[] |
no_license
|
bbhavsar/ltc
|
de88aed97a31f7d5731ef1ab68875a8a95201ffa
|
f6a5617e652ced1513d48b4a1ad8204b28e3ddd1
|
refs/heads/master
| 2021-10-29T16:21:03.129286
| 2021-10-22T23:18:18
| 2021-10-22T23:23:43
| 127,701,900
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,405
|
cc
|
remove_invalid_paranthesis.cc
|
// https://leetcode.com/problems/remove-invalid-parentheses/solution/
#include "common.hh"
void recurse(const string& s, int idx, int left_count, int right_count, string expr,
int left_to_remove, int right_to_remove,
int& max, unordered_set<string>& result) {
if (idx == s.length()) {
if (left_count == right_count) {
if (expr.length() > max) {
max = expr.length();
result.clear();
}
if (expr.length() == max) {
result.insert(expr);
}
}
return;
}
if (s[idx] != '(' && s[idx] != ')') {
recurse(s, idx + 1, left_count, right_count, expr + s[idx], left_to_remove, right_to_remove,
max, result);
return;
}
// omit char
if ((s[idx] == '(' && left_to_remove > 0) || (s[idx] == ')' && right_to_remove > 0)) {
recurse(s, idx + 1, left_count, right_count, expr,
left_to_remove - (s[idx] == '(' ? 1 : 0),
right_to_remove - (s[idx] == ')' ? 1 : 0), max, result);
}
// include left
if (s[idx] == '(') {
recurse(s, idx + 1, left_count + 1, right_count, expr + '(', left_to_remove, right_to_remove,
max, result);
} else if (left_count > right_count) {
recurse(s, idx + 1, left_count, right_count + 1, expr + ')', left_to_remove,
right_to_remove, max, result);
}
}
vector<string> removeInvalidParens(const string& s) {
int left_to_remove = 0;
int right_to_remove = 0;
for (auto c : s) {
if (c == '(') {
left_to_remove++;
} else if (c == ')') {
if (left_to_remove > 0) {
left_to_remove--;
} else {
right_to_remove++;
}
}
}
unordered_set<string> result;
int max = 0;
recurse(s, 0, 0, 0, "", left_to_remove, right_to_remove, max, result);
return vector<string>(result.begin(), result.end());
}
void print(const string& s) {
auto vec = removeInvalidParens(s);
cout << "Printing result" << endl;
cout << s << ": ";
cout << "[ ";
for (auto r : vec) {
cout << r << ", ";
}
cout << " ]" << endl;
}
int main() {
vector<string> strs = { "()())()", "(a)())()", "()" };
for (auto s : strs) {
print(s);
}
return 0;
}
|
5ab94d7199e86fc52209fb3fef5fc2b2004cbfb0
|
26aeddd8cedbe39df14cd871eb850a79b4a9d75f
|
/TNFSH_Moodle/Task 5-4/task5-4.cpp
|
6f4e41ab37187e0e8d109da0dc75151d76bc46be
|
[] |
no_license
|
gnsJhenJie/Mycpp
|
9bfe4327be4543e5ce30e1f93dc4c6b8666bc21d
|
5a283ee62b0ea3641b750edac61cdbb076c2d0c0
|
refs/heads/master
| 2021-07-15T10:48:37.342366
| 2018-06-05T01:40:29
| 2018-06-05T01:40:29
| 113,577,431
| 2
| 4
| null | 2018-10-28T10:58:59
| 2017-12-08T13:29:31
|
C++
|
UTF-8
|
C++
| false
| false
| 525
|
cpp
|
task5-4.cpp
|
//Copyright 2017 gnsJhenJie.All right reserved.
#include<iostream>
using namespace std;
int main(){
int n;
cin >> n;
for (int i=1;i<=n;i++){
for (int j=1;j<=(n-i);j++){
cout <<".";
}
for (int k=1;k<=i;k++){
cout <<"*";
}
cout <<endl;
}
for (int l=n-1;l>=1;l--){
for (int m=1;m<=n-l;m++){
cout << ".";
}
for (int n=1;n<=l;n++){
cout <<"*";
}
cout <<endl;
}
return 0;
}
|
96b6f2df53ed8d9e15bcc41b2980808bbe03b399
|
54a9c34c604249770c81f2f2b15af7f23448e8cb
|
/src/test_gui/dlg4.h
|
ca44816dc5841e3bf8686d8b6bbb329e91223841
|
[
"Unlicense"
] |
permissive
|
blueantst/zpublic
|
3a51c1d1d5c0910d5ef5ad85feb4c617d6f5b049
|
17d798db89a9085200c2127e88ecf6b407393b3c
|
refs/heads/master
| 2020-12-11T06:13:25.796413
| 2013-12-30T09:09:39
| 2013-12-30T09:09:39
| 15,559,862
| 1
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,591
|
h
|
dlg4.h
|
#pragma once
#include "dlg4_handler.h"
#include "resource.h"
const int DLG4_ID_EDIT = 10086;
class CDlg4
: public CDialogImpl<CDlg4>
, public CDlg4Handler<CDlg4>
{
public:
enum
{
IDD = IDD_DIALOG4
};
BEGIN_MSG_MAP(CDlg4)
CHAIN_MSG_MAP(CDlg4Handler<CDlg4>)
MSG_WM_INITDIALOG(OnInitDialog)
COMMAND_ID_HANDLER(IDOK, OnOk)
COMMAND_ID_HANDLER(IDC_BUTTON1, OnClickBtn1)
ALT_MSG_MAP(DLG4_ID_EDIT)
MESSAGE_HANDLER(WM_CHAR, OnEditChar)
END_MSG_MAP()
private:
BOOL OnInitDialog(CWindow wndFocus, LPARAM)
{
CRect rect(200,100,400,130);
m_edit.Create(
L"edit",
this,
DLG4_ID_EDIT,
m_hWnd,
&rect);
CWindow btn1 = GetDlgItem(IDC_BUTTON1);
btn1.EnableWindow(FALSE);
return 1;
}
LRESULT OnOk(WORD, UINT, HWND, BOOL&)
{
EndDialog(IDOK);
return 0;
}
LRESULT OnClickBtn1(WORD, UINT, HWND hwnd, BOOL&)
{
static int x = 0;
CString strNum;
strNum.Format(L"num=%d", ++x);
CWindow static1 = GetDlgItem(IDC_STATIC1);
static1.SetWindowText(strNum);
CWindow btn1(hwnd);
btn1.EnableWindow(FALSE);
return 0;
}
LRESULT OnEditChar(UINT, WPARAM wparam, LPARAM, BOOL& bHandled)
{
if (isdigit((wchar_t)wparam))
{
bHandled = FALSE;
}
else
{
::MessageBeep(0xffffffff);
}
return 0;
}
private:
CContainedWindow m_edit;
};
|
63d5410b16c74f283c1df3523ee9e26ae4bddd94
|
84a73f877166e59fe3540a47045051f349cd4f77
|
/hw/firmware/3dcam/features.cpp
|
03e1b9ea17c7f403e44eb89f18b49ca86006011c
|
[] |
no_license
|
BaeJuneHyuck/3D-video
|
b5f80eb18cf5b332bc9e7bc866889d8b60675272
|
146f2b4b7272de4a49d0aefbee7d46d9f5f1852e
|
refs/heads/master
| 2022-12-27T07:01:17.846559
| 2020-09-30T22:02:38
| 2020-09-30T22:02:38
| 268,448,362
| 4
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,223
|
cpp
|
features.cpp
|
#include <ArduinoWebsockets.h>
#include "esp_timer.h"
#include "esp_camera.h"
#include "img_converters.h"
#include "Arduino.h"
#include "fb_gfx.h"
#include "SdFat.h"
#include "sdios.h"
#include "FreeStack.h"
using namespace websockets;
extern SdFat32 sd;
extern File32 file;
uint8_t sectorBuffer[512];
void format_card(WebsocketsClient& client) {
FatFormatter fatFormatter;
if (!fatFormatter.format(sd.card(), sectorBuffer, &Serial)) {
client.send("Format: failed.");
return;
}
client.send("Format: succeeded.");
}
void set_state(WebsocketsClient& client, String var, String value)
{
const char* variable = var.c_str();
int val = atoi(value.c_str());
sensor_t * s = esp_camera_sensor_get();
int res = 0;
if(!strcmp(variable, "framesize"))
{
if(s->pixformat == PIXFORMAT_JPEG) res = s->set_framesize(s, (framesize_t)val);
}
else if(!strcmp(variable, "quality")) res = s->set_quality(s, val);
else if(!strcmp(variable, "contrast")) res = s->set_contrast(s, val);
else if(!strcmp(variable, "brightness")) res = s->set_brightness(s, val);
else if(!strcmp(variable, "saturation")) res = s->set_saturation(s, val);
else if(!strcmp(variable, "gainceiling")) res = s->set_gainceiling(s, (gainceiling_t)val);
else if(!strcmp(variable, "colorbar")) res = s->set_colorbar(s, val);
else if(!strcmp(variable, "awb")) res = s->set_whitebal(s, val);
else if(!strcmp(variable, "agc")) res = s->set_gain_ctrl(s, val);
else if(!strcmp(variable, "aec")) res = s->set_exposure_ctrl(s, val);
else if(!strcmp(variable, "hmirror")) res = s->set_hmirror(s, val);
else if(!strcmp(variable, "vflip")) res = s->set_vflip(s, val);
else if(!strcmp(variable, "awb_gain")) res = s->set_awb_gain(s, val);
else if(!strcmp(variable, "agc_gain")) res = s->set_agc_gain(s, val);
else if(!strcmp(variable, "aec_value")) res = s->set_aec_value(s, val);
else if(!strcmp(variable, "aec2")) res = s->set_aec2(s, val);
else if(!strcmp(variable, "dcw")) res = s->set_dcw(s, val);
else if(!strcmp(variable, "bpc")) res = s->set_bpc(s, val);
else if(!strcmp(variable, "wpc")) res = s->set_wpc(s, val);
else if(!strcmp(variable, "raw_gma")) res = s->set_raw_gma(s, val);
else if(!strcmp(variable, "lenc")) res = s->set_lenc(s, val);
else if(!strcmp(variable, "special_effect")) res = s->set_special_effect(s, val);
else if(!strcmp(variable, "wb_mode")) res = s->set_wb_mode(s, val);
else if(!strcmp(variable, "ae_level")) res = s->set_ae_level(s, val);
else
{
client.send("Set_State: unknown state name.");
return;
}
if(!res)
client.send("Set_State: state changed.");
else
client.send("Set_State: failed.");
}
void show_state(WebsocketsClient& client)
{
static char json_response[1024];
sensor_t * s = esp_camera_sensor_get();
char * p = json_response;
*p++ = '{';
p+=sprintf(p, "\"framesize\":%u,", s->status.framesize);
p+=sprintf(p, "\"quality\":%u,", s->status.quality);
p+=sprintf(p, "\"brightness\":%d,", s->status.brightness);
p+=sprintf(p, "\"contrast\":%d,", s->status.contrast);
p+=sprintf(p, "\"saturation\":%d,", s->status.saturation);
p+=sprintf(p, "\"sharpness\":%d,", s->status.sharpness);
p+=sprintf(p, "\"special_effect\":%u,", s->status.special_effect);
p+=sprintf(p, "\"wb_mode\":%u,", s->status.wb_mode);
p+=sprintf(p, "\"awb\":%u,", s->status.awb);
p+=sprintf(p, "\"awb_gain\":%u,", s->status.awb_gain);
p+=sprintf(p, "\"aec\":%u,", s->status.aec);
p+=sprintf(p, "\"aec2\":%u,", s->status.aec2);
p+=sprintf(p, "\"ae_level\":%d,", s->status.ae_level);
p+=sprintf(p, "\"aec_value\":%u,", s->status.aec_value);
p+=sprintf(p, "\"agc\":%u,", s->status.agc);
p+=sprintf(p, "\"agc_gain\":%u,", s->status.agc_gain);
p+=sprintf(p, "\"gainceiling\":%u,", s->status.gainceiling);
p+=sprintf(p, "\"bpc\":%u,", s->status.bpc);
p+=sprintf(p, "\"wpc\":%u,", s->status.wpc);
p+=sprintf(p, "\"raw_gma\":%u,", s->status.raw_gma);
p+=sprintf(p, "\"lenc\":%u,", s->status.lenc);
p+=sprintf(p, "\"vflip\":%u,", s->status.vflip);
p+=sprintf(p, "\"hmirror\":%u,", s->status.hmirror);
p+=sprintf(p, "\"dcw\":%u,", s->status.dcw);
p+=sprintf(p, "\"colorbar\":%u,", s->status.colorbar);
*p++ = '}';
*p++ = 0;
client.send(json_response);
}
struct chunk_header
{
int64_t timestamp;
int64_t len;
};
extern char* file_buf;
int start_record(WebsocketsClient& client, int64_t record_time){
int64_t start_time = esp_timer_get_time();
camera_fb_t * fb = NULL;
size_t _jpg_buf_len = 0;
uint8_t * _jpg_buf = NULL;
client.send("Record: starting the record...");
if (!file.open("jpg_blob", O_RDWR | O_CREAT | O_TRUNC))
{
client.send("Record: file open failed.");
file.close();
return false;
}
int64_t last_frame = esp_timer_get_time();
int sum_frame_time = 0;
int frame_count = 0;
while(esp_timer_get_time() - start_time < record_time * 1000)
{
chunk_header header;
header.timestamp = esp_timer_get_time() - start_time;
fb = esp_camera_fb_get();
if (!fb) {
client.send("Record: failed to obtain a frame.");
file.close();
return false;
} else {
_jpg_buf_len = fb->len;
_jpg_buf = fb->buf;
}
header.len = _jpg_buf_len;
memcpy(file_buf, &header, sizeof(header));
memcpy(file_buf + sizeof(header), _jpg_buf, _jpg_buf_len);
if(file.write(file_buf, sizeof(header) + _jpg_buf_len) != sizeof(header) + _jpg_buf_len)
{
client.send("Record: write failed.");
esp_camera_fb_return(fb);
file.close();
return false;
}
file.flush();
esp_camera_fb_return(fb);
int64_t fr_end = esp_timer_get_time();
int64_t frame_time = (fr_end - last_frame) / 1000;
last_frame = fr_end;
sum_frame_time += frame_time;
frame_count++;
}
client.send(String("Record: avg frame time = ") + String((double)sum_frame_time / frame_count));
file.close();
return true;
}
|
6862971fa45275cfaaf746b756245a8e0a6ea4d5
|
0c52fa7265a2ed79a206bcea69267b6776ed45ca
|
/include/rho/algo/stat_util.ipp
|
76403c1a078ff199ee2c2a23af6576e237e98038
|
[
"LicenseRef-scancode-openssl",
"LicenseRef-scancode-ssleay-windows",
"LicenseRef-scancode-warranty-disclaimer",
"Zlib",
"MIT",
"BSD-3-Clause",
"RSA-MD",
"LicenseRef-scancode-public-domain"
] |
permissive
|
Rhobota/librho
|
532792a9429801c4c9170bd0d19e3dc34c84ae01
|
d540cba6227e15ac6ef3dcb6549ed9557f6fee04
|
refs/heads/master
| 2021-01-01T05:36:43.887317
| 2017-04-29T04:11:33
| 2017-04-29T04:11:33
| 68,876,855
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,851
|
ipp
|
stat_util.ipp
|
template <class T>
T mean(const std::vector<T>& v)
{
if (v.size() == 0)
throw eInvalidArgument("The mean is not defined over zero samples.");
T sum(0);
for (size_t i = 0; i < v.size(); i++)
sum += v[i];
sum /= T(v.size());
return sum;
}
template <class T>
T mean(const std::vector< std::vector<T> >& m)
{
T sum(0);
size_t count = 0;
for (size_t i = 0; i < m.size(); i++)
{
for (size_t j = 0; j < m[i].size(); j++)
sum += m[i][j];
count += m[i].size();
}
if (count == 0)
throw eInvalidArgument("The mean is not defined over zero samples.");
sum /= T(count);
return sum;
}
template <class T>
T variance(const std::vector<T>& v)
{
if (v.size() == 0)
throw eInvalidArgument("The variance is not defined over zero samples.");
if (v.size() == 1)
throw eInvalidArgument("The variance is not defined over one sample.");
T av = mean(v);
T sum(0);
for (size_t i = 0; i < v.size(); i++)
sum += (v[i]-av)*(v[i]-av);
sum /= T(v.size()-1);
return sum;
}
template <class T>
T variance(const std::vector< std::vector<T> >& m)
{
T sum(0);
size_t count = 0;
T av = mean(m);
for (size_t i = 0; i < m.size(); i++)
{
for (size_t j = 0; j < m[i].size(); j++)
sum += (m[i][j]-av)*(m[i][j]-av);
count += m[i].size();
}
if (count == 0)
throw eInvalidArgument("The variance is not defined over zero samples.");
if (count == 1)
throw eInvalidArgument("The variance is not defined over one sample.");
sum /= T(count-1);
return sum;
}
template <class T>
T stddev(const std::vector<T>& v)
{
return std::sqrt(variance(v));
}
template <class T>
T stddev(const std::vector< std::vector<T> >& m)
{
return std::sqrt(variance(m));
}
|
8e5f2b2f94a79d3399b70b927df96a1eb9653f7d
|
6a9dd9417ee3b67c5b59680b606eee3bdab767f1
|
/最大子列和/最大子列和/源.cpp
|
f49128eede66d13b4add06d11a58f72578ce5624
|
[] |
no_license
|
underkongkong/Data-structure
|
2b39bf98a33db248c57c5fcdc11b12cb217ecbe5
|
64a2881f648bbd262b5347490f78fabdd841fb1f
|
refs/heads/master
| 2022-07-19T20:59:45.730975
| 2022-06-18T18:21:27
| 2022-06-18T18:21:27
| 192,154,842
| 4
| 3
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 485
|
cpp
|
源.cpp
|
#include<iostream>
using namespace std;
int maxSum(int *p, int n)
{
int sum = 0;
int maxsum = 0;
int j, i;
for (i = 0; i < n; i++)
{
for (j = i; j < n; j++)
sum += p[j];
if (sum > maxsum)
maxsum = sum;
}
return maxsum;
}
int main()
{
int a;
cin >> a;
int *p = new int[a];
int m=0;
for (int i = 0; i < a; i++)
{
cin >> p[i];
if (p[i] < 0)
m++;
}
if (m == a)
throw"0";
int result=maxSum(p, a);
cout << result << endl;
system("pause");
return 0;
}
|
a03092336ceb95eaad66962f1080b8d964d6bd33
|
c8488e2b35051868b759387917070b40aa7976be
|
/prototype_schematic.ino
|
94179761a27d969a5ab2d5263de8081b6b88fb13
|
[] |
no_license
|
jkmingwen/protomato
|
19353f55f2d491b1244e0ba8293b2dc940068a8b
|
d711bb8fb79f879b927e025e5ff545ae80dd7499
|
refs/heads/master
| 2021-08-30T14:20:15.659402
| 2017-12-18T09:20:42
| 2017-12-18T09:20:42
| 114,614,950
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,220
|
ino
|
prototype_schematic.ino
|
// Declaring pin variables
int potPin = A0;
int ledPin[3] = {3, 4, 5};
int switchPin = 2;
int piezoPin = 9;
// Declaring initial component values (to detect changes in state)
int potVal;
int switchState_old = 0;
int switchState_new = 0;
// User determined values
int setLEDNumber;
int timePerLED = 1; // Default time per LED: 1 second/LED
void setup()
{
Serial.begin(9600);
pinMode(potPin, INPUT);
pinMode(switchPin, INPUT);
pinMode(ledPin[0], OUTPUT);
pinMode(ledPin[1], OUTPUT);
pinMode(ledPin[2], OUTPUT);
pinMode(piezoPin, OUTPUT);
}
void loop()
{
switchState_new = digitalRead(switchPin);
// potMin = 528, potMax = 1023
potVal = map(analogRead(potPin), 528, 1023, 0, 3);
// Setting LED indicators (pretty crude method -- optimize later)
// turns off all LEDs
for (int i = 0; i < sizeof(ledPin) / sizeof(int); i++)
{
digitalWrite(ledPin[i], LOW);
}
// turns on LEDs corresponding to potentiometer position
for (int i = 0; i < potVal; i ++)
{
digitalWrite(ledPin[i], HIGH);
}
// Pomodoro START function
// Executes timer function when switch is pressed
if (switchState_new != switchState_old)
{
if (switchState_new == HIGH)
{
if (potVal == 0) // Learn exception handling to replace this!
{
Serial.println("No duration selected!");
}
else
{
setLEDNumber = potVal;
Serial.print("Timer started for ");
Serial.print(timePerLED * setLEDNumber);
Serial.println(" seconds.");
for (int i = setLEDNumber - 1; i > -1; i = i - 1)
{
delay(1000 * timePerLED);
digitalWrite(ledPin[i], LOW);
if (i == 0)
{
Serial.println("Time's up!");
tone(piezoPin, 440);
delay(1000);
noTone(piezoPin);
}
}
}
}
delay(50); // For bounces
}
// Calibration of time indicated per LED
// Should simply display current setting with option to input change
// on LCD
while (Serial.available() > 0)
{
timePerLED = Serial.parseInt();
Serial.print("You have calibrated the timer for ");
Serial.print(timePerLED);
Serial.print(" seconds per LED.\n");
}
}
|
bdac3e19911386e4aa3681028b7a9bf379561d7e
|
19ae84c7197c48dbd8fc416b5a639f0fb5d09ee3
|
/PERIOD 4/A-TeamTron/Pettijohn_TronClone/Tron.cpp
|
9cca0e79fec1ae0cb8e6e1006735d27ec9a986e5
|
[] |
no_license
|
Kakoure/Computer-Science-1-PROJECTS-2016-2017
|
c53c616ee296d662e6d061ec04865365a7bd271a
|
29dbbfa6c0da36578bb7542fb93f06e6379e4895
|
refs/heads/master
| 2021-05-16T05:58:42.236444
| 2017-05-26T13:05:59
| 2017-05-26T13:05:59
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 34,783
|
cpp
|
Tron.cpp
|
#include "LoadBMP.h"
#include "Pixel.h"
#include "VirtualKeys.h"
#include <thread>
#include <ctime>
#include <mmsystem.h> /// WAV
#include <mciapi.h> /// MP3
#pragma comment(lib, "winmm.lib") /// WAV also maybe MP3
enum GAMESTATE { START_MENU, PLAYER_1, PLAYER_2, CONTROLS, OPTIONS, MAPOPTIONS, GAME, END };
enum DIRECTION { UP, RIGHT, DOWN, LEFT, PAUSE, SELECT, LEFTCLICK, RIGHTCLICK };
enum WIN { CONT, LOSE, TIE };
vector <int> PlayerColorChoices;
bool isRunning = true;
bool changeStates = true;
bool debug = false;
bool selectColor, finalizeColor;
char ** grid;
POINT click;
GAMESTATE Tron = START_MENU;
struct pass {
int VirtualKey;
bool isPressed;
bool isHeld;
DIRECTION move;
void reset() {
isPressed = false;
isHeld = false;
}
}playerInput1, playerInput2, mouseInput;
struct BUTTON {
int Left, Top, Right, Bottom;
void init(int x1, int y1, int x2, int y2) {
if (x1 < x2) {
Left = x1;
Right = x2;
}
else {
Left = x2;
Right = x1;
}
if (y1 < y2) {
Top = y1;
Bottom = y2;
}
else {
Top = y2;
Bottom = y1;
}
}
void init(BUTTON t) {
Left = t.Left;
Right = t.Right;
Top = t.Top;
Bottom = t.Bottom;
}
bool isPressed(POINT p) {
if (debug) {
cout << "Point.X : " << p.x << " Point.Y : " << p.y << endl;
cout << "LEFT : (" << Left << ")" << (Left <= p.x) << endl;
cout << "RIGHT : (" << Right << ")" << (p.x <= Right) << endl;
cout << "TOP : (" << Top << ")" << (Top <= p.y) << endl;
cout << "BOTTOM: (" << Bottom << ")" << (p.y <= Bottom) << endl;
}
return ((Left <= p.x) && (p.x <= Right)) && ((Top <= p.y) && (p.y <= Bottom));
}
void render(int color) {
setcolor(color);
bar(Left, Top, Right, Bottom);
}
bool isEqual(BUTTON t) {
return t.Left == Left && t.Right == Right && t.Bottom == Bottom && t.Top == Top;
}
}Playerselect[6];
struct PLAYERPOS {
int maxR;
int maxC;
int color;
int row;
int col;
pass *listener;
int unit;
char C;
void init(int startR, int startC, int unitSize, pass *input, int COLOR, int row1, int col1) {
color = COLOR;
row = startR;
col = startC;
unit = unitSize;
listener = input;
maxR = row1;
maxC = col1;
switch (color)
{
case BLUE:
C = 'B';
break;
case RED:
C = 'R';
break;
case GREEN:
C = 'G';
break;
case YELLOW:
C = 'Y';
break;
case MAGENTA:
C = 'M';
break;
}
render();
}
void tick() {
switch (listener->move) {
case UP:
row--;
return;
case DOWN:
row++;
return;
case LEFT:
col--;
return;
case RIGHT:
col++;
return;
}
}
void render() {
setcolor(color);
bar(col*(unit + 1), row*(unit + 1), (col + 1)*(unit + 1), (row + 1)*(unit + 1));
}
WIN collide(PLAYERPOS opponent) {
if (maxR < row || row < 0 || maxC < col || col < 0) {
return LOSE;
}
if (opponent.row == row && opponent.col == col) {
return TIE;
}
if (pix(opponent)) {
return LOSE;
}
return CONT;
}
bool pix(PLAYERPOS opponent) {
int X = (col) * (unit + 1) + (unit + 1) / 2;
int Y = (row) * (unit + 1) + (unit + 1) / 2;
return getpixel(X, Y) == color || getpixel(X, Y) == opponent.color;
}
void state() {
cout << "row : " << row << " col : " << col << endl;
}
}readyPlayer1, readyPlayer2;
struct ButtonHighlight {
int Left, Top, Right, Bottom;
int padding;
BUTTON inner;
void init(int x) {
padding = x / 2;
}
void pick(BUTTON t) {
inner.init(t);
Left = t.Left - padding;
Right = t.Right + padding;
Top = t.Top - padding;
Bottom = t.Bottom + padding;
}
void draw() {
render(WHITE);
}
void remove() {
render(BLACK);
}
void render(int color) {
setcolor(color);
rectangle(Left, Top, Right, Bottom);
rectangle(inner.Left, inner.Top, inner.Right, inner.Bottom);
floodfill(Left + 1, Top + 1, color);
}
}selected;
int GrDriver, GrMode, ErrorCode;
INPUT_RECORD irInBuf1, irInBuf2;
void gr_Start(int &GrDriver, int &GrMode, int &ErrorCode);
void PLAYER1();
void PLAYER2();
//void OPTIONS();
int z = 1000;
int s;
int p;
int q;
void MOUSE();
void TRON();
void BACKGROUND();
void getCursor(POINT &p, int VirtualKey);
bool mousePress(int);
bool KEYBOARD1(int);
bool KEYBOARD2(int);
void playSound(string, int);
void playSoundSFX(string, int);
void resetListeners();
void setColorPallet();
void drawPLAYER(int);
bool checkPLAYER(int);
void main() {
bool GmNotArt = (true);
if (GmNotArt) {
thread tron(TRON);
thread p1(PLAYER1);
thread p2(PLAYER2);
thread mouse(MOUSE);
thread audio(BACKGROUND);
audio.join();
tron.join();
mouse.join();
p1.join();
p2.join();
}
else {
CREATE("player2.bmp");
}
}
void gr_Start(int&GrDriver, int&GrMode, int&ErrorCode) {
GrDriver = VGA;
GrMode = VGAMAX;
initgraph(&GrDriver, &GrMode, "");
ErrorCode = graphresult();
if (ErrorCode != grOk) {
cout << "Error : " << ErrorCode << "/n";
}
}
void PLAYER1() {
while (isRunning) {
if (KEYBOARD1(VK_A)) {
if (playerInput1.move != RIGHT)
playerInput1.move = LEFT;
}
if (KEYBOARD1(VK_D)) {
if (playerInput1.move != LEFT)
playerInput1.move = RIGHT;
}
if (KEYBOARD1(VK_W)) {
if (playerInput1.move != DOWN)
playerInput1.move = UP;
}
if (KEYBOARD1(VK_S)) {
if (playerInput1.move != UP)
playerInput1.move = DOWN;
}
Sleep(10);
}
}
void PLAYER2() {
while (isRunning) {
if (KEYBOARD2(VK_LEFT)) {
if (playerInput2.move != RIGHT)
playerInput2.move = LEFT;
}
if (KEYBOARD2(VK_RIGHT)) {
if (playerInput2.move != LEFT)
playerInput2.move = RIGHT;
}
if (KEYBOARD2(VK_UP)) {
if (playerInput2.move != DOWN)
playerInput2.move = UP;
}
if (KEYBOARD2(VK_DOWN)) {
if (playerInput2.move != UP)
playerInput2.move = DOWN;
}
Sleep(10);
}
}
void MOUSE() {
while (isRunning) {
if (mousePress(VK_LBUTTON)) {
mouseInput.isPressed = true;
}
if (mousePress(VK_RBUTTON)) {
}
if (GetAsyncKeyState(VK_Z) & 0x8000 != 0 || GetAsyncKeyState(VK_NUMPAD0) & 0x8000 != 0)
{
z = 0;
}
if (Tron == GAME) {
do {
Sleep(10);
} while ((GetAsyncKeyState(VK_R) & 0x8000 != 0) || (GetAsyncKeyState(VK_M) & 0x8000 != 0) || (GetAsyncKeyState(VK_N) & 0x8000 != 0));
}
if (Tron == END) {
if (GetAsyncKeyState(VK_R) & 0x8000 != 0) {
changeStates = true;
Tron = GAME;
}
else if (GetAsyncKeyState(VK_M) & 0x8000 != 0) {
changeStates = true;
Tron = START_MENU;
}
else if (GetAsyncKeyState(VK_N) & 0x8000 != 0) {
isRunning = false;
}
}
Sleep(15);
}
}
void TRON() {
gr_Start(GrDriver, GrMode, ErrorCode);
int maxX = getmaxx();
int maxY = getmaxy();
int unitSize = 9;
int row = maxY / (unitSize + 1);
int col = maxX / (unitSize + 1);
grid = new char *[row];
for (int i = 0; i < row; i++) {
grid[i] = new char[col];
for (int j = 0; j < col; j++) {
grid[i][j] = '0';
}
}
// grid [row][col]
int P1Score = 0;
int P2Score = 0;
BUTTON start, end;
WIN P1, P2;
cout << boolalpha; /// prints out true and false as bool vars
resetListeners();
///{START_MENU, PLAYER1, PLAYER2, GAME, END};
BUTTON endTitleScreen;
BUTTON options;
BUTTON slowSpeed;
BUTTON normalSpeed;
BUTTON soupaSonicSpeed;
BUTTON restart;
BUTTON mainMenu;
BUTTON controls;
BUTTON back;
BUTTON player2controls;
BUTTON player1controls;
BUTTON scoreboard;
BUTTON player1Scoreboard;
BUTTON player2Scoreboard;
BUTTON normalMap;
BUTTON helloKitty;
BUTTON tundra;
BUTTON desert;
while (isRunning) {
switch (Tron) {
case START_MENU:
if (changeStates) {
setColorPallet();
cleardevice();
///BUTTON 1 START GAME BUTTON
int top, left, bottom, right;
top = (maxY / 1) / 3.45;
bottom = maxY / 5;
left = ((maxX / 2) / 2.32) / 2;
bottom = bottom - top;
top = ((maxY - title_Height) / 3) + title_Height;
bottom = top + bottom;
right = maxX - left +200;
start.init(left, top, right, bottom);
start.render(2);
//setbkcolor(15);
setcolor(WHITE);
//setcolor(2);
settextstyle(3, 0, 7);
outtextxy((right + left -58 - textwidth("START ")) / 2 + left, ( bottom - top- textheight("START ")) / 2 + top, "START ");
//putpixel(0, 0, 0);
//setbkcolor(BLACK);
///BUTTON 2 OPTIONS BUTTON
int top1, left1, bottom1, right1;
top1 = (maxY / 25) / 2; // Length to the Right
bottom1 = maxY / .666 ; // Length to the Left
left1 = ((maxX / 2.4) / 1.40) / 1; // Height going Up
bottom1 = (bottom1 - top1); // Thickness Left to Right
top1 = ((maxY - title_Height) / 11) + title_Height; // Left or Right
bottom1 = (top1 + bottom1 + 200); // Thickness Left to Right
right1 = (maxX - left1)/2.8; // Height going Down
options.init(top1, left1, bottom1, right1);
options.render(9);
//setbkcolor(9);
setcolor(WHITE);
settextstyle(3, 0, 7);
outtextxy((bottom1 + top1 -50 - textwidth("OPTIONS ")) / 2 + top1, (right1 - left1 - textheight("OPTIONS ")) / 2 + left1, "OPTIONS ");
//putpixel(0, 0, 0);
//setbkcolor(BLACK);
///BUTTON 3 CONTROLS BUTTON
int top2, left2, bottom2, right2;
top2 = (maxY / 25) / 2; // Length to the Right
bottom2 = maxY / .666; // Length to the Left
left2 =((maxX / 1.92) / 1.40); // Height going Up
bottom2 = (bottom2 - top2); // Thickness Left to Right
top2 = ((maxY - title_Height) / 11) + title_Height; // Left or Right
bottom2 = (top2 + bottom2 +200); // Thickness Left to Right
right2 = (maxX - left2) / 1.92; // Height going Down
controls.init(top2, left2, bottom2, right2);
controls.render(5);
//setbkcolor(8);
setcolor(WHITE);
settextstyle(3, 0, 7);
outtextxy((bottom2 + top2 +39 - textwidth("CONTROLS ")) /2 + top2, (right2 - left2 - textheight("CONTROLS ") )/ 2 + left2, "CONTROLS ");
drawTitle((maxX - title_Width) / 10, (maxY - title_Height) / 8);
//putpixel(0, 0, 0);
//setbkcolor(BLACK);
///BUTTON 10 END GAME BUTTON
int top9, left9, bottom9, right9;
top9 = (maxY / 1) / 3.45;
bottom9 = maxY / 5;
left9 = ((maxX / 2) / 2.32) / 2;
bottom9 = bottom9 - top9;
top9 = ((maxY - title_Height) / 1.209) + title_Height;
bottom9 = top9 + bottom9;
right9 = maxX - left9 + 200;
endTitleScreen.init(left9, top9, right9, bottom9);
endTitleScreen.render(4);
//setbkcolor(4);
setcolor(4);
setcolor(WHITE);
settextstyle(3, 0, 7);
outtextxy((right9 + left9 + 20 - textwidth("END GAME ")) / 2 + left9, (bottom9 - top9 - textheight("END GAME ")) / 2 + top9, "END GAME ");
//putpixel(0, 0, 0);
//setbkcolor(BLACK);
changeStates = false;
}
if (mouseInput.isPressed && start.isPressed(click)) {
s = 20; // speed
p = 0; // primary color
q = 8; // secondary color
changeStates = true;
Tron = PLAYER_1;//GAME;///
//cout << "SWITCH STATE \n";
}
else if (mouseInput.isPressed && endTitleScreen.isPressed(click)) {
isRunning = false;
}
else if (mouseInput.isPressed && options.isPressed(click)) {
changeStates = true;
Tron = OPTIONS;
}
else if (mouseInput.isPressed && controls.isPressed(click)) {
changeStates = true;
Tron = CONTROLS;
}
resetListeners();
break;
case PLAYER_1:
if (changeStates) {
selectColor = false;
finalizeColor = false;
cleardevice();
drawPLAYER(1);
}
changeStates = checkPLAYER(1);
resetListeners();
break;
case PLAYER_2:
if (changeStates) {
selectColor = false;
finalizeColor = false;
cleardevice();
drawPLAYER(2);
}
changeStates = checkPLAYER(2);
resetListeners();
break;
case CONTROLS:
if (changeStates) {
setColorPallet();
cleardevice();
///BUTTON PLAYER 1 CONTROLS TEXTBOX
int top10, left10, bottom10, right10;
top10 = (maxY / 1) / 3.45;
bottom10 = maxY / 5;
left10 = ((maxX / 2) / 2.32) / 2;
bottom10 = bottom10 - top10;
top10 = ((maxY - title_Height) / 11) + title_Height;
bottom10 = top10 + bottom10;
right10 = maxX - left10;
int RESIZE3 = 500;
player1controls.init(left10 + RESIZE3, top10, right10 - RESIZE3, bottom10);
player1controls.render(15);
//setbkcolor(15);
setcolor(WHITE);
settextstyle(3, 0, 6);
outtextxy((right10 - left10 - textwidth("PLAYER 1")) / 2 + left10, (bottom10 - top10 - textheight("PLAYER 1")) / 2 + top10, "PLAYER 1");
outtextxy((right10 - left10 - textwidth("MOVEMENT: W,A,S,D")) / 2 + left10, (bottom10 - top10 - textheight("MOVEMENT: W,A,S,D")) / 2 + top10 + 100, "MOVEMENT: W,A,S,D");
outtextxy((right10 - left10 - textwidth("START GAME: Z")) / 2 + left10, (bottom10 - top10 - textheight("START GAME: Z")) / 2 + top10 + 170, "START GAME: Z");
///BUTTON 12 PLAYER 2 CONTROLS TEXTBOX
int top11, left11, bottom11, right11;
top11 = (maxY / 1) / 3.45;
bottom11 = maxY / 5;
left11 = ((maxX / 2) / 2.32) / 2;
bottom11 = bottom11 - top11;
top11 = ((maxY - title_Height) / 2.6) + title_Height;
bottom11 = top11 + bottom11;
right11 = maxX - left11;
int RESIZE1 = 500;
player2controls.init(left11 + RESIZE1, top11, right11 - RESIZE1, bottom11);
player2controls.render(15);
//setbkcolor(15);
setcolor(WHITE);
settextstyle(3, 0, 6);
outtextxy((right11 - left11 - textwidth("PLAYER 2")) / 2 + left11, (bottom11 - top11 - textheight("PLAYER 2")) / 2 + top11, "PLAYER 2");
outtextxy((right11 - left11 - textwidth("MOVEMENT: ARROW KEYS")) / 2 + left11, (bottom11 - top11 - textheight("MOVEMENT: ARROW KEYS")) / 2 + top11 + 100, "MOVEMENT: ARROW KEYS");
outtextxy((right11 - left11 - textwidth("START GAME: NUMPAD 0")) / 2 + left11, (bottom11 - top11 - textheight("START GAME: NUMPAD 0")) / 2 + top11 + 170, "START GAME: NUMPAD 0");
//setlinestyle(3, 1, 1);
line(0, 640, 2000, 640);// SEPERATE IN GAME
outtextxy((right11 - left11 - textwidth("RESTART GAME: R")) / 2 + left11, (bottom11 - top11 - textheight("RESTART GAME: R")) / 2 + top11 + 270, "RESTART GAME: R");
outtextxy((right11 - left11 - textwidth("END GAME: N")) / 2 + left11, (bottom11 - top11 - textheight("END GAME: N")) / 2 + top11 + 350, "END GAME: N");
outtextxy((right11 - left11 - textwidth("BACK OUT TO MAIN MENU: M")) / 2 + left11, (bottom11 - top11 - textheight("BACK OUT TO MAIN MENU: M")) / 2 + top11 + 420, "BACK OUT TO MAIN MENU: M");
///BUTTON 13 BACK BUTTON
int top12, left12, bottom12, right12;
top12 = (maxY / 1) / 3.45;
bottom12 = maxY / 5;
left12 = ((maxX / 2) / 2.32) / 2;
bottom12 = bottom12 - top12;
top12 = ((maxY - title_Height) / 1.02) + title_Height;
bottom12 = top12 + bottom12;
right12 = maxX - left12;
int RESIZE2 = 600;
back.init(left12 + RESIZE2, top12, right12 - RESIZE2, bottom12);
back.render(14);
//setbkcolor(15);
setcolor(WHITE);
settextstyle(3, 0, 7);
outtextxy((right12 - left12 - textwidth("BACK")) / 2 + left12, (bottom12 - top12 - textheight("BACK")) / 2 + top12, "BACK");
changeStates = false;
resetListeners();
}
if (mouseInput.isPressed && back.isPressed(click)) {
changeStates = true;
Tron = START_MENU;
}
else if (mouseInput.isPressed && player1controls.isPressed(click)) {
changeStates = false;
}
else if (mouseInput.isPressed && player2controls.isPressed(click)) {
changeStates = false;
}
break;
case OPTIONS:
if (changeStates) {
setColorPallet();
cleardevice();
///BUTTON 4 SLOW SPEED
int top3, left3, bottom3, right3;
top3 = (maxY / 1) / 3.45;
bottom3 = maxY / 5;
left3 = ((maxX / 2) / 2.32) / 2;
bottom3 = bottom3 - top3;
top3 = ((maxY - title_Height) / 3) + title_Height;
bottom3 = top3 + bottom3;
right3 = maxX - left3;
slowSpeed.init(left3, top3, right3, bottom3);
slowSpeed.render(15);
//setbkcolor(15);
setcolor(WHITE);
settextstyle(3, 0, 7);
outtextxy((right3 - left3 - textwidth("SLOW")) / 2 + left3, (bottom3 - top3 - textheight("SLOW")) / 2 + top3, "SLOW");
//s = 70;
///BUTTON 5 NORMAL SPEED
int top4, left4, bottom4, right4;
top4 = (maxY / 25) / 2; // Length to the Right
bottom4 = maxY / .666; // Length to the Left
left4 = ((maxX / 2.4) / 1.40) / 1; // Height going Up
bottom4 = (bottom4 - top4); // Thickness Left to Right
top4 = ((maxY - title_Height) / 11) + title_Height; // Left or Right
bottom4 = (top4 + bottom4); // Thickness Left to Right
right4 = (maxX - left4) / 2.8; // Height going Down
normalSpeed.init(top4, left4, bottom4, right4);
normalSpeed.render(9);
//setbkcolor(9);
setcolor(9);
setcolor(WHITE);
settextstyle(3, 0, 7);
outtextxy((bottom4 - top4 - textwidth("NORMAL")) / 2 + top4, (right4 - left4 - textheight("NORMAL")) / 2 + left4, "NORMAL");
//s = 20;
///BUTTON 6 SUPERFAST SPEED
int top5, left5, bottom5, right5;
top5 = (maxY / 25) / 2; // Length to the Right
bottom5 = maxY / .666; // Length to the Left
left5 = ((maxX / 1.92) / 1.40) / 1; // Height going Up
bottom5 = (bottom5 - top5); // Thickness Left to Right
top5 = ((maxY - title_Height) / 11) + title_Height; // Left or Right
bottom5 = (top5 + bottom5); // Thickness Left to Right
right5 = (maxX - left5) / 1.92; // Height going Down
soupaSonicSpeed.init(top5, left5, bottom5, right5);
soupaSonicSpeed.render(8);
//setbkcolor(8);
setcolor(8);
setcolor(WHITE);
settextstyle(3, 0, 7);
outtextxy((bottom5 - top5 - textwidth("SOUPASONIC")) / 2 + top5, (right5 - left5 - textheight("SOUPASONIC")) / 2 + left5, "SOUPASONIC");
//s = 9;
///BUTTON 14 BACK BUTTON
int top13, left13, bottom13, right13;
top13 = (maxY / 1) / 3.45;
bottom13 = maxY / 5;
left13 = ((maxX / 2) / 2.32) / 2;
bottom13 = bottom13 - top13;
top13 = ((maxY - title_Height) / 1.02) + title_Height;
bottom13 = top13 + bottom13;
right13 = maxX - left13;
int RESIZE = 600;
back.init(left13 + RESIZE, top13, right13 - RESIZE, bottom13);
back.render(14);
//setbkcolor(15);
setcolor(WHITE);
settextstyle(3, 0, 7);
outtextxy((right13 - left13 - textwidth("BACK")) / 2 + left13, (bottom13 - top13 - textheight("BACK")) / 2 + top13, "BACK");
changeStates = false;
resetListeners();
}
if (mouseInput.isPressed && slowSpeed.isPressed(click)) {
s = 50;
changeStates = true;
Tron = MAPOPTIONS;
}
else if (mouseInput.isPressed && normalSpeed.isPressed(click)) {
s = 20;
changeStates = true;
Tron = MAPOPTIONS;
}
else if (mouseInput.isPressed && soupaSonicSpeed.isPressed(click)) {
s = 9;
changeStates = true;
Tron = MAPOPTIONS;
}
else if (mouseInput.isPressed && back.isPressed(click)) {
changeStates = true;
Tron = START_MENU;
}
break;
case MAPOPTIONS:
if (changeStates) {
setColorPallet();
cleardevice();
///BUTTON 18 NORMAL MAP
int top17, left17, bottom17, right17;
top17 = (maxY / 1) / 3.45;
bottom17 = maxY / 5;
left17 = ((maxX / 2) / 2.32) / 2;
bottom17 = bottom17 - top17;
top17 = ((maxY - title_Height) / 4.1) + title_Height;
bottom17 = top17 + bottom17;
right17 = maxX - left17;
normalMap.init(left17, top17, right17, bottom17);
normalMap.render(15);
//setfillstyle(1, 8);
//setbkcolor(15);
settextstyle(3, 0, 7);
outtextxy((right17 - left17 - textwidth("NORMAL MAP")) / 2 + left17, (bottom17 - top17 - textheight("NORMAL MAP")) / 2 + top17, "NORMAL MAP");
//putpixel(0, 0, 0);
//setbkcolor(BLACK);
///BUTTON 19 HELLO KITTY
int top18, left18, bottom18, right18;
top18 = (maxY / 1) / 3.45;
bottom18 = maxY / 5;
left18 = ((maxX / 2) / 2.32) / 2;
bottom18 = bottom18 - top18;
top18 = ((maxY - title_Height) / 2.5) + title_Height;
bottom18 = top18 + bottom18;
right18 = maxX - left18;
helloKitty.init(left18, top18, right18, bottom18);
helloKitty.render(13);
//setbkcolor(15);
setcolor(LIGHTMAGENTA);
setcolor(WHITE);
settextstyle(3, 0, 7);
outtextxy(( right18 - left18 - textwidth("HELLO KITTY MAP")) / 2 + left18, (bottom18 - top18 - textheight("HELLO KITTY MAP")) / 2 + top18, "HELLO KITTY MAP");
//putpixel(0, 0, 0);
//setbkcolor(BLACK);
///BUTTON 20 TUNDRA
int top19, left19, bottom19, right19;
top19 = (maxY / 1) / 3.45;
bottom19 = maxY / 5;
left19 = ((maxX / 2) / 2.32) / 2;
bottom19 = bottom19 - top19;
top19 = ((maxY - title_Height) / 1.8) + title_Height;
bottom19 = top19 + bottom19;
right19 = maxX - left19;
tundra.init(left19, top19, right19, bottom19);
//setfillstyle(1,3);
tundra.render(3);
//setbkcolor(15);
setcolor(3);
setcolor(WHITE);
settextstyle(3, 0, 7);
outtextxy((right19 - left19 - textwidth("TUNDRA MAP")) / 2 + left19, (bottom19 - top19 - textheight("TUNDRA MAP")) / 2 + top19, "TUNDRA MAP");
//putpixel(0, 0, 0);
//setbkcolor(BLACK);
///BUTTON 24 DESERT
int top23, left23, bottom23, right23;
top23 = (maxY / 1) / 3.45;
bottom23 = maxY / 5;
left23 = ((maxX / 2) / 2.32) / 2;
bottom23 = bottom23 - top23;
top23 = ((maxY - title_Height) / 1.41) + title_Height;
bottom23 = top23 + bottom23;
right23 = maxX - left23;
desert.init(left23, top23, right23, bottom23);
//setfillstyle(1,3);
desert.render(6);
//setbkcolor(15);
setcolor(WHITE);
settextstyle(3, 0, 7);
outtextxy((right23 - left23 - textwidth("DESERT MAP")) / 2 + left23, (bottom23 - top23 - textheight("DESERT MAP")) / 2 + top23, "DESERT MAP");
//putpixel(0, 0, 0);
//setbkcolor(BLACK);
///BUTTON 21 BACK BUTTON
int top13, left13, bottom13, right13;
top13 = (maxY / 1) / 3.45;
bottom13 = maxY / 5;
left13 = ((maxX / 2) / 2.32) / 2;
bottom13 = bottom13 - top13;
top13 = ((maxY - title_Height) / 1.02) + title_Height;
bottom13 = top13 + bottom13;
right13 = maxX - left13;
int RESIZE = 600;
back.init(left13 + RESIZE, top13, right13 - RESIZE, bottom13);
setcolor(YELLOW);
back.render(14);
//setbkcolor(15);
setcolor(WHITE);
settextstyle(3, 0, 7);
outtextxy((right13 - left13 - textwidth("BACK")) / 2 + left13, (bottom13 - top13 - textheight("BACK")) / 2 + top13, "BACK");
changeStates = false;
resetListeners();
}
if (mouseInput.isPressed && normalMap.isPressed(click)) {
p = 0;
q = 8;
changeStates = true;
Tron = PLAYER_1;//GAME;///
//cout << "SWITCH STATE \n";
}
else if (mouseInput.isPressed && helloKitty.isPressed(click)) {
setlinestyle(3, 1, 1);
p = 13;
q = 15;
changeStates = true;
Tron = PLAYER_1;
}
else if (mouseInput.isPressed && tundra.isPressed(click)) {
setlinestyle(3, 1, 1);
p = 3;
q = 15;
changeStates = true;
Tron = PLAYER_1;
}
else if (mouseInput.isPressed && desert.isPressed(click)) {
setlinestyle(3, 1, 1);
p = 6;
q = 14;
changeStates = true;
Tron = PLAYER_1;
}
else if (mouseInput.isPressed && back.isPressed(click)) {
changeStates = true;
Tron = OPTIONS;
}
break;
case GAME:
if (changeStates) {
drawGrid(unitSize, maxX, maxY, p , q);
playerInput1.move = RIGHT;
playerInput2.move = LEFT;
readyPlayer1.init((row / 2), 10, unitSize, &playerInput1, readyPlayer1.color, row, col);
readyPlayer2.init((row / 2), (col - 10), unitSize, &playerInput2, readyPlayer2.color, row, col);
changeStates = false;
int count = 0;
z = 1000;
while (count != z) {
Sleep(10);
}
}
readyPlayer1.tick();
readyPlayer2.tick();
P1 = readyPlayer1.collide(readyPlayer2);
P2 = readyPlayer2.collide(readyPlayer1);
if (P1 != CONT || P2 != CONT) {
if (P1 == P2) {
P1 = P2 = TIE;
}
changeStates = true;
Tron = END;
}
else {
readyPlayer1.render();
readyPlayer2.render();
}
resetListeners();
break;
case END:
if (changeStates) {
///BUTTON 7 MAIN MENU BUTTON
int top6, left6, bottom6, right6;
top6 = (maxY / 1) / 3.45;
bottom6 = maxY / 5;
left6 = ((maxX / 2) / 2.32) / 2;
bottom6 = bottom6 - top6;
top6 = ((maxY - title_Height) / 2) + title_Height;
bottom6 = top6 + bottom6;
right6 = maxX - left6;
mainMenu.init(left6, top6, right6, bottom6);
mainMenu.render(2);
//setbkcolor(15);
setcolor(WHITE);
settextstyle(3, 0, 7);
outtextxy((right6 - left6 - textwidth("MAIN MENU (M)")) / 2 + left6, (bottom6 - top6 - textheight("MAIN MENU (M)")) / 2 + top6, "MAIN MENU (M)");
/// BUTTON 8 END GAME BUTTON
int top7, left7, bottom7, right7;
top7 = (maxY / 1) / 3.45;
bottom7 = maxY / 5;
left7 = ((maxX / 2) / 2.32) / 2;
bottom7 = bottom7 - top7;
top7 = ((maxY - title_Height) / 1.537) + title_Height;
bottom7 = top7 + bottom7;
right7 = maxX - left7;
end.init(left7, top7, right7, bottom7);
end.render(4);
setcolor(WHITE);
settextstyle(3, 0, 7);
outtextxy((right7 - left7 - textwidth("END GAME (N)")) / 2 + left7, (bottom7 - top7 - textheight("END GAME (N)")) / 2 + top7, "END GAME (N)");
setbkcolor(BLACK);
///BUTTON 9 RESTART GAME BUTTON
int top8, left8, bottom8, right8;
top8 = (maxY / 1) / 3.45;
bottom8 = maxY / 5;
left8 = ((maxX / 2) / 2.32) / 2;
bottom8 = bottom8 - top8;
top8 = ((maxY - title_Height) / 1.25) + title_Height;
bottom8 = top8 + bottom8;
right8 = maxX - left8;
restart.init(left8, top8, right8, bottom8);
restart.render(15);
//setbkcolor(15);
setcolor(WHITE);
settextstyle(3, 0, 7);
outtextxy((right8 - left8 - textwidth("RESTART (R)")) / 2 + left8, (bottom8 - top8 - textheight("RESTART (R)")) / 2 + top8, "RESTART (R)");
///BUTTON 15 SCOREBOARD
int top14, left14, bottom14, right14;
top14 = (maxY / 1) / 2;
bottom14 = maxY / 5;
left14 = ((maxX / 2) / 2.32) / 2;
bottom14 = bottom14 - top14;
top14 = ((maxY - title_Height) / 4.3) + title_Height;
bottom14 = top14 + bottom14;
right14 = maxX - left14;
scoreboard.init(left14, top14, right14, bottom14);
scoreboard.render(15);
//setbkcolor(15);
setcolor(WHITE);
settextstyle(3, 0, 7);
outtextxy((right14 - left14 - textwidth("SCORE")) / 2 + left14, (bottom14 - top14 - textheight("SCORE")) / 2 + top14, "SCORE");
///BUTTON 16 SCOREBOARD PLAYER 2
int top15, left15, bottom15, right15;
top15 = (maxY / 1) / 3;
bottom15 = maxY / 5;
left15 = ((maxX / 2) / 1) / 2;
bottom15 = bottom15 - top15;
top15 = ((maxY - title_Height) / 4.3) + title_Height;
bottom15 = top15 + bottom15;
right15 = maxX - left15;
player2Scoreboard.init(left15 + 700, top15 - 275, right15 + 212 , bottom15 + 100);
player2Scoreboard.render(readyPlayer2.color);
//setbkcolor(15);
///BUTTON 17 SCOREBOARD PLAYER 1
int top16, left16, bottom16, right16;
top16 = (maxY / 1) / 3;
bottom16 = maxY / 5;
left16 = ((maxX / 2) / 1) / 2;
bottom16 = bottom16 - top16;
top16 = ((maxY - title_Height) / 4.3) + title_Height;
bottom16 = top16 + bottom16;
right16 = maxX - left16;
player1Scoreboard.init(left16 - 212 , top16 -275, right16 - 700, bottom16 +100 );
player1Scoreboard.render(readyPlayer1.color);
//setbkcolor(15);
mouseInput.reset();
int Xs = (maxX - title_Width) / 2;
int Ys = (maxY - title_Height) / 2;
string GAMEOVER = "";
if (P1 == LOSE) {
GAMEOVER = "PLAYER 2 HAS SLAIN PLAYER 1!";
P2Score++;
//Player2((maxX - player_Width) / 2, Ys - player_Height, readyPlayer2.color);
}
else if (P2 == LOSE) {
GAMEOVER = "PLAYER 1 HAS SLAIN PLAYER 2!";
P1Score++;
//Player1((maxX - player_Width) / 2, Ys - player_Height, readyPlayer1.color);
}
else {
GAMEOVER = "HOW EMBARRASSING!";
setcolor(WHITE);
}
setcolor(WHITE);
settextstyle(3, 0, 8);
outtextxy((right15 - 1450 + left16 - textwidth("00")) / 2 + left16 - 212, (bottom16 - top16 - textheight("00")) / 2 + top16 - 97, to_string(P1Score).c_str());//Player 1 score on scoreboard
setcolor(WHITE);
settextstyle(3, 0, 8);
outtextxy((right15 + left15 - textwidth("00")) / 2 + left15 - 25, (bottom15 - top15 - textheight("00")) / 2 + top15 - 97, to_string(P2Score).c_str());//Player 2 score o scoreboard
Ys -= textheight(GAMEOVER.c_str());
Xs = (maxX - textwidth(GAMEOVER.c_str())) / 2;
outtextxy(Xs, Ys, GAMEOVER.c_str());
putpixel(0, 0, CYAN);
setcolor(BLACK);
setbkcolor(BLACK);
cout << GAMEOVER << "\n";
changeStates = false;
}
if (mouseInput.isPressed && mainMenu.isPressed(click) ) {// END => START MENU
changeStates = true;
Tron = START_MENU;
}
else if (mouseInput.isPressed && restart.isPressed(click) ) {// END => GAME
changeStates = true;
Tron = GAME;
}
else if (mouseInput.isPressed && end.isPressed(click) ) {//COMPLETELY EXIT GAME
isRunning = false;
}
resetListeners();
break;
}
Sleep(s);
}
exit(0);
}
void BACKGROUND() {
string bkgMusic = "MortalKombat.mp3";
string sfxCrash = "Explosion+3.mp3";
bool game = false;
while (isRunning) {
while (Tron != END) {
playSoundSFX(bkgMusic, 216000);
game = true;
Sleep(2);
}
if (Tron == END && game) {
playSoundSFX(sfxCrash, 2000);
game = false;
}
Sleep(15);
}
}
void getCursor(POINT &p, int VirtualKey) {
while (true) {
if (GetCursorPos(&p)) {
if ((GetAsyncKeyState(VirtualKey) & 0x8000) != 0) {
do {} while ((GetAsyncKeyState(VirtualKey) & 0x8000) != 0);
return;
}
}
}
}
bool mousePress(int VirtualKey) {
if ((GetAsyncKeyState(VirtualKey) & 0x8000) != 0) {
GetCursorPos(&click);
mouseInput.VirtualKey = VirtualKey;
int count = 0;
do {
if (count++ > 1400) {
mouseInput.isHeld = true;
}
} while ((GetAsyncKeyState(VirtualKey) & 0x8000) != 0);
return true;
}
return false;
}
bool KEYBOARD1(int VirtualKey) {
if ((GetAsyncKeyState(VirtualKey) & 0x8000) != 0)
{
irInBuf1.EventType = KEY_EVENT;
playerInput1.VirtualKey = VirtualKey;
int count = 0;
do {
if (count++ > 200) {
playerInput1.isHeld = true;
}
}
while ((GetAsyncKeyState(VirtualKey) & 0x8000) != 0);
playerInput1.isPressed = true;
return true;
}
return false;
}
bool KEYBOARD2(int VirtualKey) {
if ((GetAsyncKeyState(VirtualKey) & 0x8000) != 0)
{
irInBuf2.EventType = KEY_EVENT;
playerInput2.VirtualKey = VirtualKey;
int count = 0;
do {
if (count++ > 200) {
playerInput2.isHeld = true;
}
} while ((GetAsyncKeyState(VirtualKey) & 0x8000) != 0);
playerInput2.isPressed = true;
return true;
}
return false;
}
void playSound(string fileName, int duration) {
if (fileName.substr(fileName.length() - 2) == "v") {
PlaySound(TEXT(fileName.c_str()), NULL, SND_ASYNC);
Sleep(duration);
PlaySound(TEXT(fileName.c_str()), 0, 0);
return;
}
string concat = "open " + fileName + " type mpegvideo alias MP3_Device";
LPCSTR a = concat.c_str();
mciSendString(a, NULL, 0, 0);
mciSendString("play MP3_Device", NULL, 0, 0);
Sleep(duration);
mciSendString("stop MP3_Device", NULL, 0, 0);
mciSendString("close MP3_Device", NULL, 0, 0);
}
void playSoundSFX(string fileName, int duration) {
int current = 0;
GAMESTATE stop = (Tron != END) ? END : START_MENU;
if (fileName.substr(fileName.length() - 2) == "v") {
PlaySound(TEXT(fileName.c_str()), NULL, SND_ASYNC);
while (current < duration && Tron != stop) {
current += 15;
Sleep(15);
}
PlaySound(TEXT(fileName.c_str()), 0, 0);
return;
}
string concat = "open " + fileName + " type mpegvideo alias MP3_Device";
LPCSTR a = concat.c_str();
mciSendString(a, NULL, 0, 0);
mciSendString("play MP3_Device", NULL, 0, 0);
while (current < duration && Tron != stop) {
current += 15;
Sleep(15);
}
mciSendString("stop MP3_Device", NULL, 0, 0);
mciSendString("close MP3_Device", NULL, 0, 0);
}
void resetListeners() {
playerInput1.reset();
playerInput2.reset();
mouseInput.reset();
}
void setColorPallet() {
PlayerColorChoices.clear();
PlayerColorChoices.push_back(RED); // 0
PlayerColorChoices.push_back(BLUE); // 1
PlayerColorChoices.push_back(DARKGRAY); // 2
PlayerColorChoices.push_back(MAGENTA); // 3
PlayerColorChoices.push_back(GREEN); // 4
PlayerColorChoices.push_back(LIGHTRED); // 5
PlayerColorChoices.push_back(YELLOW); // 6
}
void drawOptions() {
setColorPallet();
cleardevice();
}
void drawPLAYER(int playerNum) {
int Xf, Xs, Xt, Yf, Ys, Yt; // Xfirst, Xsecond, Xthird (three rows)
int padding = 25;
selected.init(padding);
int h = player_Height;
Yf = (getmaxy() - ((h * 3) + (padding * 2))) / 2;
Ys = Yf + h + padding;
Yt = Ys + h + padding;
Xf = (getmaxx() - 520) / 2;
padding = (padding * 2);
Xt = Xs = (getmaxx() - (h * 3 + (padding * 2))) / 2;
if (playerNum == 1) {
Player1O(Xf, Yf, CYAN);
}
else {
Player2O(Xf, Yf, CYAN);
}
int pointX = Xs;
for (int i = 0; i < 3; i++) {
Playerselect[i].init(pointX, Ys, pointX + h, Ys + h);
Playerselect[i + 3].init(pointX, Yt, pointX + h, Yt + h);
Playerselect[i].render(PlayerColorChoices.at(i));
Playerselect[i + 3].render(PlayerColorChoices.at(i + 3));
pointX += h + padding;
}
}
bool checkPLAYER(int playerNum) {
if (mouseInput.isPressed) {
for (int i = 0; i < 6; i++) {
if (Playerselect[i].isPressed(click)) {
if (selectColor) {
if (selected.inner.isEqual(Playerselect[i])) {
if (playerNum == 1) {
readyPlayer1.color = PlayerColorChoices.at(i);
PlayerColorChoices.erase(PlayerColorChoices.begin() + i);
Tron = PLAYER_2;
return true;
}
else {
readyPlayer2.color = PlayerColorChoices.at(i);
Tron = GAME;
return true;
}
}
else {
selected.remove();
selected.pick(Playerselect[i]);
selected.draw();
}
}
else {
selectColor = true;
selected.pick(Playerselect[i]);
selected.draw();
}
}
}
}
return false;
}
|
1948793f0a153811be280e2a14deacf48eb21785
|
d282110d4a0087614bf535737d1a8c7acd4930a4
|
/Wav.cpp
|
dba23518214487f8c82706e77b35350ba882aa6b
|
[] |
no_license
|
kashyapiitd/Wav
|
756c323f58e35a9f79171c3b63396dbaf50291bf
|
9299fc11ef54b1cbdc630d8fb367eb0a9856127b
|
refs/heads/master
| 2020-03-19T02:58:01.497149
| 2018-06-01T12:07:03
| 2018-06-01T12:09:55
| 135,680,635
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,823
|
cpp
|
Wav.cpp
|
#include "Wav.h"
Wav::Wav(){};
Wav::~Wav(){};
status Wav::read_wave_file(string filename)
{
/* Open the Wavfile in read mode*/
fstream wavfile;
wavfile.open(filename, ios::in | ios::binary);
if (wavfile.is_open())
{
wavfile.read(wav_header.chunk_id, 4);
wav_header.chunk_id[4] = 0;
if (strcmp(wav_header.chunk_id, "RIFF") != 0)
{
return status::INCORRECT_CHUNK_ID;
}
wavfile.read(reinterpret_cast<char *>(&wav_header.chunk_size), 4);
wavfile.read(wav_header.format, 4);
wav_header.format[4] = 0;
if (strcmp(wav_header.format, "WAVE") != 0)
{
return status::INCORRECT_FORMAT;
}
wavfile.read(wav_header.sub_chunk1_id, 3);
wav_header.sub_chunk1_id[3] = 0;
if (strcmp(wav_header.sub_chunk1_id, "fmt") != 0)
{
return status::INCORRECT_SUB_CHUNK1_ID;
}
wavfile.seekg(1, ios_base::cur);
wavfile.read(reinterpret_cast<char*> (&wav_header.sub_chunk1_size), 4);
if (wav_header.sub_chunk1_size != 16)
{
return status::INCORRECT_SUB_CHUNK1_SIZE;
}
wavfile.read(reinterpret_cast<char *> (&wav_header.audio_format), 2);
if (wav_header.audio_format != 1)
{
return status::INCORRECT_AUDIO_FORMAT;
}
wavfile.read(reinterpret_cast<char *> (&wav_header.number_channels), 2);
if (wav_header.number_channels != 1)
{
return status::INCORRECT_NUM_CHANNELS;
}
wavfile.read(reinterpret_cast<char *>(&wav_header.sampling_rate), 4);
wavfile.read(reinterpret_cast<char *>(&wav_header.byte_rate), 4);
wavfile.read(reinterpret_cast<char *>(&wav_header.block_align), 2);
wavfile.read(reinterpret_cast<char *>(&wav_header.bits_per_sample), 2);
bytes_per_sample = wav_header.bits_per_sample >> 3;
if (wav_header.byte_rate != (wav_header.sampling_rate * bytes_per_sample * wav_header.number_channels))
{
return status::INCORRECT_BYTE_RATE;
}
if (wav_header.block_align != (bytes_per_sample * wav_header.number_channels) )
{
return status::INCORRECT_BLOCK_ALIGN;
}
wavfile.read(wav_header.sub_chunk2_id, 4);
wav_header.sub_chunk2_id[4] = 0;
if (strcmp(wav_header.sub_chunk2_id, "data") != 0)
{
return status::INCORRECT_SUB_CHUNK2_ID;
}
wavfile.read(reinterpret_cast<char*> (&wav_header.sub_chunk2_size), 4);
number_samples = wav_header.sub_chunk2_size / bytes_per_sample;
if (bytes_per_sample == 2)
{
data = new short[number_samples];
}
else if (bytes_per_sample == 4)
{
data = new int[number_samples];
}
cout << number_samples <<" "<< wav_header.sub_chunk2_size<<" " << bytes_per_sample << endl;
wavfile.read(reinterpret_cast<char*> (data), wav_header.sub_chunk2_size);
return status::SUCESS;
}
else
{
return status::FILE_NOT_OPENED;
}
}
|
f10a7eb85a6e452d6e71071e659fa50b96f2350f
|
e6d306682ef842808f67f7f4475e964aac1bb4fc
|
/include/fakeit/ActionSequence.hpp
|
b1f6018a139427655c0ca6f7ef95eba4c0823a97
|
[
"MIT"
] |
permissive
|
eranpeer/FakeIt
|
34f72d7e10fc4383bcd717ec52e595741bd01832
|
cb39d8a053876f74dfeed66dd335d3041f142095
|
refs/heads/master
| 2023-08-28T18:32:13.281184
| 2023-04-17T19:46:35
| 2023-04-17T19:46:35
| 12,526,458
| 1,216
| 220
|
MIT
| 2023-08-27T13:48:38
| 2013-09-01T20:36:44
|
C++
|
UTF-8
|
C++
| false
| false
| 2,846
|
hpp
|
ActionSequence.hpp
|
/*
* ActionSequence.hpp
* Copyright (c) 2014 Eran Pe'er.
*
* This program is made available under the terms of the MIT License.
*
* Created on Aug 30, 2014
*/
#pragma once
#include <vector>
#include "fakeit/DomainObjects.hpp"
#include "fakeit/ActualInvocation.hpp"
#include "fakeit/Action.hpp"
#include "fakeit/invocation_matchers.hpp"
#include "fakeit/ActualInvocationHandler.hpp"
#include "mockutils/Finally.hpp"
#include "mockutils/MethodInvocationHandler.hpp"
namespace fakeit {
/**
* Represents a list of recorded actions created by one stubbing line:
* When(Method(mock,foo)).Return(1).Throw(e).AlwaysReturn(2);
* ^--------Action-Sequence---------^
*/
template<typename R, typename ... arglist>
struct ActionSequence : ActualInvocationHandler<R,arglist...> {
ActionSequence() {
clear();
}
void AppendDo(Action<R, arglist...> *action) {
append(action);
}
virtual R handleMethodInvocation(ArgumentsTuple<arglist...> & args) override
{
std::shared_ptr<Destructible> destructablePtr = _recordedActions.front();
Destructible &destructable = *destructablePtr;
Action<R, arglist...> &action = dynamic_cast<Action<R, arglist...> &>(destructable);
std::function<void()> finallyClause = [&]() -> void {
if (action.isDone())
{
_recordedActions.erase(_recordedActions.begin());
_usedActions.push_back(destructablePtr);
}
};
Finally onExit(finallyClause);
return action.invoke(args);
}
private:
struct NoMoreRecordedAction : Action<R, arglist...> {
// virtual ~NoMoreRecordedAction() override = default;
//
// virtual R invoke(const typename fakeit::production_arg<arglist>::type...) override {
// throw NoMoreRecordedActionException();
// }
virtual R invoke(const ArgumentsTuple<arglist...> &) override {
throw NoMoreRecordedActionException();
}
virtual bool isDone() override {
return false;
}
};
void append(Action<R, arglist...> *action) {
std::shared_ptr<Destructible> destructable{action};
_recordedActions.insert(_recordedActions.end() - 1, destructable);
}
void clear() {
_recordedActions.clear();
_usedActions.clear();
auto actionPtr = std::shared_ptr<Destructible> {new NoMoreRecordedAction()};
_recordedActions.push_back(actionPtr);
}
std::vector<std::shared_ptr<Destructible>> _recordedActions;
std::vector<std::shared_ptr<Destructible>> _usedActions;
};
}
|
83bba671f08ff194c1fbeade779bac4749c86743
|
fd5789f78ec7d921ba5eeb448c1a2e39a58eac5a
|
/taichi/program/ir_bank.h
|
22ebb25fb3693bd726f6790a37ceda9cf58d806f
|
[
"MIT"
] |
permissive
|
thisguy2020/taichi
|
5f2c720fac9769933b6fb697fdc11b15b2f5a7d9
|
75d5eccfe40091ba5a259cc2cc391e916e574954
|
refs/heads/master
| 2022-12-23T18:37:09.439277
| 2020-10-01T14:23:39
| 2020-10-01T14:23:39
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 957
|
h
|
ir_bank.h
|
#include "taichi/program/async_utils.h"
TLANG_NAMESPACE_BEGIN
class IRBank {
public:
uint64 get_hash(IRNode *ir);
void set_hash(IRNode *ir, uint64 hash);
bool insert(std::unique_ptr<IRNode> &&ir, uint64 hash);
void insert_to_trash_bin(std::unique_ptr<IRNode> &&ir);
IRNode *find(IRHandle ir_handle);
// Fuse handle_b into handle_a
IRHandle fuse(IRHandle handle_a, IRHandle handle_b, Kernel *kernel);
IRHandle demote_activation(IRHandle handle);
std::unordered_map<IRHandle, TaskMeta> meta_bank_;
std::unordered_map<IRHandle, TaskFusionMeta> fusion_meta_bank_;
private:
std::unordered_map<IRNode *, uint64> hash_bank_;
std::unordered_map<IRHandle, std::unique_ptr<IRNode>> ir_bank_;
std::vector<std::unique_ptr<IRNode>> trash_bin; // prevent IR from deleted
std::unordered_map<std::pair<IRHandle, IRHandle>, IRHandle> fuse_bank_;
std::unordered_map<IRHandle, IRHandle> demote_activation_bank_;
};
TLANG_NAMESPACE_END
|
5669bfca54cd2ddd5c627983937355f659fb9726
|
21508d3c2dd940797f97a350cb66e1e16ca42f29
|
/square/include/square/util.h
|
d0f3c88b442f7b1ec2d9e84da5d636e199961770
|
[
"MIT"
] |
permissive
|
mayant15/square
|
03a279f04b30665084b16affedf18c5270e51996
|
da6d492968fd8938887cbd6b9bdb5d1c295aff83
|
refs/heads/main
| 2023-08-29T05:20:15.200354
| 2021-10-25T18:37:40
| 2021-10-25T18:37:40
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 361
|
h
|
util.h
|
#pragma once
#include <string>
namespace sq
{
/*!
* @brief Set the viewport dimensions
*
* @param x Desired origin X
* @param y Desird origin Y
* @param width Desired viewport width
* @param height Desired viewport height
*/
void set_viewport(int x, int y, unsigned int width, unsigned int height);
} // namespace sq
|
36918f554297ec23fc47fc1e01483c535a4b4f0c
|
0ac059ac0027582d3f6ff57ec81cd56480d5b804
|
/Source/RainbowSeven_C/GameMode/LoginGameMode.cpp
|
1907c58569f894ea5b977516fdb9442f2ab89322
|
[] |
no_license
|
gitchg/RainbowSeven_C
|
b054f23dfcbef6309657f78ec23641c909c0d1fc
|
5570ae594292383ecd957a7efb9b754f3bea7c17
|
refs/heads/master
| 2023-07-10T16:55:50.820400
| 2020-04-28T02:53:51
| 2020-04-28T02:53:51
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,512
|
cpp
|
LoginGameMode.cpp
|
// Author : Kgho Github : https://github.com/kgho
#include "LoginGameMode.h"
#include "Engine/KBEngine.h"
#include "Scripts/ExCommon.h"
#include "Engine/KBEvent.h"
#include "Engine/KBEMain.h"
#include "UI/LoginWidget.h"
#include "KBEClient.h"
void ALoginGameMode::InstallEvent()
{
Super::InstallEvent();
//创建用户入口实体回调
KBENGINE_REGISTER_EVENT(KBEngine::KBEventTypes::onCreateAccountResult, OnCreateAccountResult);
//登陆失败回调
KBENGINE_REGISTER_EVENT(KBEngine::KBEventTypes::onLoginFailed, OnLoginFailed);
//版本匹配回调
KBENGINE_REGISTER_EVENT(KBEngine::KBEventTypes::onVersionNotMatch, OnVersionNotMatch);
//版本不匹配回调
KBENGINE_REGISTER_EVENT(KBEngine::KBEventTypes::onScriptVersionNotMatch, OnScriptVersionNotMatch);
//登陆baseapp失败回调
KBENGINE_REGISTER_EVENT(KBEngine::KBEventTypes::onLoginBaseappFailed, OnLoginBaseappFailed);
//登陆baseapp回调
KBENGINE_REGISTER_EVENT(KBEngine::KBEventTypes::onLoginBaseapp, OnLoginBaseapp);
//登陆成功回调, 生成 Account后在 __init__()时调用, 在这里跳转到选择角色场景
KBENGINE_REGISTER_EVENT("onLoginSuccessfully", OnLoginSuccessfully);
}
void ALoginGameMode::BeginPlay()
{
//每次进入到登录界面前先清理一次KBE,否则KBE插件缓存内容一直存在
KBEngine::KBEngineApp::getSingleton().reset();
Super::BeginPlay();
//创建UI
LoginWidget = CreateWidget<ULoginWidget>(GetWorld(), LoginWidgetClass);
LoginWidget->AddToViewport();
LoginWidget->LoginGameMode = this;
LoginWidget->InitWidget();
//遍历场景中的物体,找到KBEMain
for (TActorIterator<AKBEClient> ActorIt(GetWorld()); ActorIt; ++ActorIt)
{
KBEMain = (*ActorIt)->KBEMain;
}
}
void ALoginGameMode::EndPlay(const EEndPlayReason::Type EndPlayReason)
{
Super::EndPlay(EndPlayReason);
//注销该对象注册的所有事件
KBENGINE_DEREGISTER_ALL_EVENT();
}
void ALoginGameMode::OnCreateAccountResult(const UKBEventData* pEventData)
{
//转换为相应的参数结构体,然后打印信息
const UKBEventData_onCreateAccountResult* ServerData = Cast<UKBEventData_onCreateAccountResult>(pEventData);
DDH::Debug() << "OnCreateAccountResult : errorCode-->" << ServerData->errorCode << "; errorstr -->" << ServerData->errorStr << DDH::Endl();
}
void ALoginGameMode::OnLoginFailed(const UKBEventData* pEventData)
{
const UKBEventData_onLoginFailed* ServerData = Cast<UKBEventData_onLoginFailed>(pEventData);
DDH::Debug() << "OnLoginFailed : failedcode-->" << ServerData->failedcode << "; errorstr -->" << ServerData->errorStr << DDH::Endl();
}
void ALoginGameMode::OnVersionNotMatch(const UKBEventData* pEventData)
{
const UKBEventData_onVersionNotMatch* ServerData = Cast<UKBEventData_onVersionNotMatch>(pEventData);
DDH::Debug() << "OnVersionNotMatch : serverVersion-->" << ServerData->serverVersion << "; clientVersion -->" << ServerData->clientVersion << DDH::Endl();
LoginWidget->ShowErrorPanel();
}
void ALoginGameMode::OnScriptVersionNotMatch(const UKBEventData* pEventData)
{
const UKBEventData_onScriptVersionNotMatch* ServerData = Cast<UKBEventData_onScriptVersionNotMatch>(pEventData);
DDH::Debug() << "OnScriptVersionNotMatch : clientScriptVersion-->" << ServerData->clientScriptVersion << "; serverScriptVersion -->" << ServerData->serverScriptVersion << DDH::Endl();
LoginWidget->ShowErrorPanel();
}
void ALoginGameMode::OnLoginBaseappFailed(const UKBEventData* pEventData)
{
const UKBEventData_onLoginBaseappFailed* ServerData = Cast<UKBEventData_onLoginBaseappFailed>(pEventData);
DDH::Debug() << "OnLoginBaseappFailed : failedcode-->" << ServerData->failedcode << "; errorStr -->" << ServerData->errorStr << DDH::Endl();
}
void ALoginGameMode::OnLoginBaseapp(const UKBEventData* pEventData)
{
const UKBEventData_onLoginBaseapp* ServerData = Cast<UKBEventData_onLoginBaseapp>(pEventData);
DDH::Debug() << "OnLoginBaseapp : eventName-->" << ServerData->eventName << DDH::Endl();
}
void ALoginGameMode::OnLoginSuccessfully(const UKBEventData* pEventData)
{
const UKBEventData_onLoginSuccessfully* ServerData = Cast<UKBEventData_onLoginSuccessfully>(pEventData);
DDH::Debug() << "OnLoginSuccessfully : entity_uuid-->" << ServerData->entity_uuid
<< "; entity_id -->" << ServerData->entity_id
<< "; eventName -->" << ServerData->eventName
<< DDH::Endl();
//登录成功后跳转到菜单场景,在该场景可以解锁干员,创建对战,查看资料,设置等
UGameplayStatics::OpenLevel(GetWorld(), FName("MenuMap"));
}
|
596463cd754660157b1ed341f06836204a8fb09f
|
355ca7072c6a9208a7b0db8e8ae69035d7d6d40c
|
/appendix/dump_hid_report/main.cpp
|
1df4271258ccbf555092d4644083c4cf8c45d478
|
[
"Unlicense"
] |
permissive
|
guider/Karabiner-Elements
|
7c4139dd92614c2608ac3a576907033179a500e1
|
b3d6c3a29818b11ed113b1d3424d290777631667
|
refs/heads/master
| 2020-04-06T13:43:27.131747
| 2018-11-14T00:05:41
| 2018-11-14T00:05:41
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,927
|
cpp
|
main.cpp
|
#include "dispatcher_utility.hpp"
#include "hid_manager.hpp"
namespace {
class dump_hid_report final : public pqrs::dispatcher::extra::dispatcher_client {
public:
dump_hid_report(const dump_hid_report&) = delete;
dump_hid_report(void) : dispatcher_client() {
std::vector<std::pair<krbn::hid_usage_page, krbn::hid_usage>> targets({
std::make_pair(krbn::hid_usage_page::generic_desktop, krbn::hid_usage::gd_keyboard),
std::make_pair(krbn::hid_usage_page::generic_desktop, krbn::hid_usage::gd_mouse),
std::make_pair(krbn::hid_usage_page::generic_desktop, krbn::hid_usage::gd_pointer),
std::make_pair(krbn::hid_usage_page::leds, krbn::hid_usage::led_caps_lock),
});
hid_manager_ = std::make_unique<krbn::hid_manager>(targets);
hid_manager_->device_detected.connect([this](auto&& weak_hid) {
if (auto hid = weak_hid.lock()) {
hid->report_arrived.connect([this, weak_hid](auto&& type,
auto&& report_id,
auto&& report) {
if (auto hid = weak_hid.lock()) {
report_arrived(hid, type, report_id, report);
}
});
hid->async_enable_report_callback();
hid->async_open();
hid->async_schedule();
}
});
hid_manager_->async_start();
}
virtual ~dump_hid_report(void) {
detach_from_dispatcher([this] {
hid_manager_ = nullptr;
});
}
private:
void report_arrived(std::shared_ptr<krbn::human_interface_device> hid,
IOHIDReportType type,
uint32_t report_id,
std::shared_ptr<std::vector<uint8_t>> report) const {
// Logitech Unifying Receiver sends a lot of null report. We ignore them.
if (auto manufacturer = hid->find_manufacturer()) {
if (auto product = hid->find_product()) {
if (*manufacturer == "Logitech" && *product == "USB Receiver") {
if (report_id == 0) {
return;
}
}
}
}
krbn::logger::get_logger().info("report_length: {0}", report->size());
std::cout << " report_id: " << std::dec << report_id << std::endl;
for (CFIndex i = 0; i < report->size(); ++i) {
std::cout << " key[" << i << "]: 0x" << std::hex << static_cast<int>((*report)[i]) << std::dec << std::endl;
}
}
std::unique_ptr<krbn::hid_manager> hid_manager_;
};
} // namespace
int main(int argc, const char* argv[]) {
krbn::dispatcher_utility::initialize_dispatchers();
signal(SIGINT, [](int) {
CFRunLoopStop(CFRunLoopGetMain());
});
auto d = std::make_unique<dump_hid_report>();
// ------------------------------------------------------------
CFRunLoopRun();
// ------------------------------------------------------------
d = nullptr;
krbn::dispatcher_utility::terminate_dispatchers();
return 0;
}
|
e288129ed8515005f38d3e2e7799106026df1985
|
44119e98c4e8f79e69647defc5c2400104c887ba
|
/D3D11Engine/Engine.h
|
489f986f351fe8681073e833e074e0b43f1544a3
|
[] |
no_license
|
IcarusCoding/D3D11Engine
|
20fb598a83dfda5f4ddba0953387624380741209
|
c7a8f75ab8a7158e1d28c83e97eb9682878b084e
|
refs/heads/master
| 2023-06-03T14:49:03.052952
| 2021-06-28T00:53:18
| 2021-06-28T00:53:18
| 377,317,487
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 320
|
h
|
Engine.h
|
#pragma once
#include "Window.h"
#include "FPSCounter.h"
class Engine {
private:
Window* ptrWindow;
FPSCounter frameCounter;
void Tick() noexcept;
public:
Engine() noexcept;
~Engine() noexcept;
Window* Init(const wchar_t* className) noexcept;
DWORD Start() noexcept;
void AllocateConsole() noexcept;
};
|
d1f10749cabf6607a0fb70d224c8215bd08e4c9a
|
bc62fef73c32417ed4b71c193ab8b6ed712a73f1
|
/libnd4j/include/ConstMessages.cpp
|
f7bca1d1dfb3bfb872ad167c09c8b375262287ed
|
[
"Apache-2.0",
"MIT",
"BSD-3-Clause"
] |
permissive
|
deeplearning4j/deeplearning4j
|
0a1af00abc2fe7a843b50650b72c8200364b53bf
|
91131d0e1e2cf37002658764df29ae5c0e1f577b
|
refs/heads/master
| 2023-08-17T08:20:54.290807
| 2023-07-30T10:04:23
| 2023-07-30T10:04:23
| 14,734,876
| 13,626
| 4,793
|
Apache-2.0
| 2023-09-11T06:54:25
| 2013-11-27T02:03:28
|
Java
|
UTF-8
|
C++
| false
| false
| 5,452
|
cpp
|
ConstMessages.cpp
|
/* ******************************************************************************
*
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://www.apache.org/licenses/LICENSE-2.0.
*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
* 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.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
#include <ConstMessages.h>
namespace sd {
const char *UNIQUE_TRANSFORM_STRICT_PREFIX = "__transform__strict__";
const char *UNIQUE_SCALAROP_PREFIX= "__scalarop__";
const char *OP_VALIDATION_FAIL_MSG = "Op validation failed";
const char *HAVE_PEEPHOLE = "Having the Peephole connections";
const char *HAVE_SEQLENARR = "Having theSequence length array";
const char *MSG_CELL_CLIPPING = "Cell clipping";
const char *TYPECHECK_MSG = "Checking the Type requirments for the NDArrays";
const char *NO_MSG = "";
const char *EXPECTED_TRUE = "expected to be True";
const char *EXPECTED_FALSE = "expected to be False";
const char *EXPECTED_NOT_SUPPORTED = "not supported";
const char *EXPECTED_EQ_MSG = "expected to be equal to";
const char *EXPECTED_NE_MSG = "expected to be different than";
const char *EXPECTED_LT_MSG = "expected to be less than";
const char *EXPECTED_LE_MSG = "expected to be less than or equal";
const char *EXPECTED_GT_MSG = "expected to be greater than";
const char *EXPECTED_GE_MSG = "expected to be greater than or equal";
const char *EXPECTED_IN = "expected to be one of these";
const char *IS_EMPTY_MSG_INPUT = IS_EMPTY_MSG_INPUT_;
const char *IS_EMPTY_MSG_INPUT0 = IS_EMPTY_MSG_INPUT_ "#0";
const char *IS_EMPTY_MSG_INPUT1 = IS_EMPTY_MSG_INPUT_ "#1";
const char *IS_EMPTY_MSG_INPUT2 = IS_EMPTY_MSG_INPUT_ "#2";
const char *IS_EMPTY_MSG_INPUT3 = IS_EMPTY_MSG_INPUT_ "#3";
const char *RANK_MSG_INPUT = RANK_MSG_INPUT_;
const char *RANK_MSG_INPUT0 = RANK_MSG_INPUT_ "#0";
const char *RANK_MSG_INPUT1 = RANK_MSG_INPUT_ "#1";
const char *RANK_MSG_INPUT2 = RANK_MSG_INPUT_ "#2";
const char *RANK_MSG_INPUT3 = RANK_MSG_INPUT_ "#3";
const char *LENGTH_MSG_INPUT = LENGTH_MSG_INPUT_;
const char *LENGTH_MSG_INPUT0 = LENGTH_MSG_INPUT_ "#0";
const char *LENGTH_MSG_INPUT1 = LENGTH_MSG_INPUT_ "#1";
const char *LENGTH_MSG_INPUT2 = LENGTH_MSG_INPUT_ "#2";
const char *LENGTH_MSG_INPUT3 = LENGTH_MSG_INPUT_ "#3";
const char *SHAPE_MSG_INPUT = SHAPE_MSG_INPUT_;
const char *SHAPE_MSG_INPUT0 = SHAPE_MSG_INPUT_ "#0";
const char *SHAPE_MSG_INPUT1 = SHAPE_MSG_INPUT_ "#1";
const char *SHAPE_MSG_INPUT2 = SHAPE_MSG_INPUT_ "#2";
const char *SHAPE_MSG_INPUT3 = SHAPE_MSG_INPUT_ "#3";
const char *TYPE_MSG_INPUT = TYPE_MSG_INPUT_;
const char *TYPE_MSG_INPUT0 = TYPE_MSG_INPUT_ "#0";
const char *TYPE_MSG_INPUT1 = TYPE_MSG_INPUT_ "#1";
const char *TYPE_MSG_INPUT2 = TYPE_MSG_INPUT_ "#2";
const char *TYPE_MSG_INPUT3 = TYPE_MSG_INPUT_ "#3";
const char *EWS_MSG_INPUT = EWS_MSG_INPUT_;
const char *EWS_MSG_INPUT0 = EWS_MSG_INPUT_ "#0";
const char *EWS_MSG_INPUT1 = EWS_MSG_INPUT_ "#1";
const char *EWS_MSG_INPUT2 = EWS_MSG_INPUT_ "#2";
const char *EWS_MSG_INPUT3 = EWS_MSG_INPUT_ "#3";
const char *ORDERING_MSG_INPUT = ORDERING_MSG_INPUT_;
const char *ORDERING_MSG_INPUT0 = ORDERING_MSG_INPUT_ "#0";
const char *ORDERING_MSG_INPUT1 = ORDERING_MSG_INPUT_ "#1";
const char *ORDERING_MSG_INPUT2 = ORDERING_MSG_INPUT_ "#2";
const char *ORDERING_MSG_INPUT3 = ORDERING_MSG_INPUT_ "#3";
const char *RANK_MSG_OUTPUT = RANK_MSG_OUTPUT_;
const char *RANK_MSG_OUTPUT0 = RANK_MSG_OUTPUT_ "#0";
const char *RANK_MSG_OUTPUT1 = RANK_MSG_OUTPUT_ "#1";
const char *RANK_MSG_OUTPUT2 = RANK_MSG_OUTPUT_ "#2";
const char *IS_EMPTY_MSG_OUTPUT = IS_EMPTY_MSG_OUTPUT_;
const char *IS_EMPTY_MSG_OUTPUT0 = IS_EMPTY_MSG_OUTPUT_ "#0";
const char *IS_EMPTY_MSG_OUTPUT1 = IS_EMPTY_MSG_OUTPUT_ "#1";
const char *IS_EMPTY_MSG_OUTPUT2 = IS_EMPTY_MSG_OUTPUT_ "#2";
const char *TYPE_MSG_OUTPUT = TYPE_MSG_OUTPUT_;
const char *TYPE_MSG_OUTPUT0 = TYPE_MSG_OUTPUT_ "#0";
const char *TYPE_MSG_OUTPUT1 = TYPE_MSG_OUTPUT_ "#1";
const char *TYPE_MSG_OUTPUT2 = TYPE_MSG_OUTPUT_ "#2";
const char *EWS_MSG_OUTPUT = EWS_MSG_OUTPUT_;
const char *EWS_MSG_OUTPUT0 = EWS_MSG_OUTPUT_ "#0";
const char *EWS_MSG_OUTPUT1 = EWS_MSG_OUTPUT_ "#1";
const char *EWS_MSG_OUTPUT2 = EWS_MSG_OUTPUT_ "#2";
const char *ORDERING_MSG_OUTPUT = ORDERING_MSG_OUTPUT_;
const char *ORDERING_MSG_OUTPUT0 = ORDERING_MSG_OUTPUT_ "#0";
const char *ORDERING_MSG_OUTPUT1 = ORDERING_MSG_OUTPUT_ "#1";
const char *ORDERING_MSG_OUTPUT2 = ORDERING_MSG_OUTPUT_ "#2";
const char *SHAPE_MSG_OUTPUT = SHAPE_MSG_OUTPUT_;
const char *SHAPE_MSG_OUTPUT0 = SHAPE_MSG_OUTPUT_ "#0";
const char *SHAPE_MSG_OUTPUT1 = SHAPE_MSG_OUTPUT_ "#1";
const char *SHAPE_MSG_OUTPUT2 = SHAPE_MSG_OUTPUT_ "#2";
const char *IS_USE_ONEDNN_MSG = "isUseONEDNN should be enabled to use ONEDNN";
const char *ONEDNN_STREAM_NOT_SUPPORTED = "ONEDNN stream is not supported";
const char *REQUIREMENTS_MEETS_MSG = "meets the requirements";
const char *REQUIREMENTS_FAILS_MSG = "fails the requirements";
} // namespace sd
|
1af7a16e2c771ab1536f0b214000cabb2e027303
|
2a1f10ef11b1bc3326e5e7ba98d7a664901c3755
|
/app/script_host/src/quanta/app_script_host/types.hpp
|
dda3e0d229be185cf8255dd7658d5bf8e44dfc42
|
[
"MIT"
] |
permissive
|
komiga/quanta
|
bc57c21e9dc4a9307a14e2bebf229390ead134ad
|
28c186d2a74dd660baccd7981836f9ef46219bf1
|
refs/heads/master
| 2020-05-21T15:17:59.704742
| 2020-01-24T05:29:42
| 2020-01-24T05:29:42
| 51,727,484
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 459
|
hpp
|
types.hpp
|
#line 2 "quanta/app_script_host/types.hpp"
/**
@copyright MIT license; see @ref index or the accompanying LICENSE file.
@file
@brief app_script_host types.
@ingroup app_script_host_types
@defgroup app_script_host_types Types
@ingroup app_script_host
@details
*/
#pragma once
#include <quanta/app_script_host/config.hpp>
#include <quanta/core/types.hpp>
namespace quanta {
namespace app_script_host {
} // namespace app_script_host
} // namespace quanta
|
faafcbb61b10136dd780fb5b62347cd423f08a0c
|
0106751477cd91074c198abc4923613486548eb6
|
/vs/VsContext.hpp
|
e39764d54edbb1fbd5aa3213f541e36b7a70a80c
|
[] |
no_license
|
eriser/linAnil
|
2f65b8fcfb931b9ad35d0439db8199cc1643cce9
|
8a862d0f886f897446a8fb6f9bf1ee7dfdcadc3a
|
refs/heads/master
| 2020-05-29T12:31:42.952823
| 2015-08-19T08:59:46
| 2015-08-19T08:59:46
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 11,768
|
hpp
|
VsContext.hpp
|
#pragma once
//
// Created by manoyuria on 2015/7/11.
//
#ifndef LINANIL_VSCONTEXT_HPP
#define LINANIL_VSCONTEXT_HPP
#endif //LINANIL_VSCONTEXT_HPP
#include <stdio.h>
//#ifdef NANOVG_GLEW
#include <GL/glew.h>
//#endif
#include <GLFW/glfw3.h>
#include <iostream>
#include <thread>
#include "nanovg/nanovg.h"
#define NANOVG_GL3_IMPLEMENTATION
#include "nanovg/nanovg_gl.h"
#include <exception>
#include <vs/events/VsEvent.hpp>
#include <vs/events/KeyEvent.hpp>
#include <vs/events/MouseEvent.hpp>
#include "VsObj.hpp"
#define VG_CONTEXT VsContext::_().getContext()
#define VS_CONTEXT VsContext::_()
#define add_event_on_context(type, func) VS_CONTEXT.add_event(type,func);
#include "events/EventDispatcher.hpp"
#include "events/BaseEvent.hpp"
#include "Performance.hpp"
#define VS_WIDTH 1440
#define VS_HEIGHT 920
#define VS_DOUBLE_CLICK_DELAY 0.2 //double click 200 ms
#include "windows.h"
using namespace std;
template<typename T>
class S {
public:
static T &_() {
static T instance;
return instance;
}
};
struct pos {
int x;
int y;
};
void errorcb(int error, const char *desc) {
cout << "GLFW error " << error << ": " << desc << endl;
}
void mouseButton(GLFWwindow *window, int button, int action, int mods);
void cursorPos(GLFWwindow *window, double x, double y);
void key(GLFWwindow *window, int key, int scancode, int action, int mods);
void scrollevent(GLFWwindow *window, double x, double y) {
NVG_NOTUSED(window);
// uiSetScroll((int) x, (int) y);
}
void charEvent(GLFWwindow *window, unsigned int codepoint) ;
class VsContext : public EventDispatcher, public S<VsContext> {
public:
Performance *perfFps;
Performance *perfCpu;
// int screenWidth;
// int screenHeight;
HWND actWindow;
long normalStyle;
long noBorderStyle;
bool isMaximized = false;
int lastWidth;
int lastHeight;
void initVsContext() {
actWindow = GetActiveWindow();
long Style = GetWindowLong(actWindow, GWL_STYLE);
normalStyle = Style;
Style &= ~(0x00C00000L |
0x00C0000L); //this makes it still work when WS_MAXIMIZEBOX is actually already toggled off
// Style &= ~WS_CAPTION;
noBorderStyle = Style;
SetWindowLong(actWindow, GWL_STYLE, Style);
// long Style = GetWindowLong(actWindow, GWL_STYLE);
// Style &= ~WS_MAXIMIZEBOX; //this makes it still work when WS_MAXIMIZEBOX is actually already toggled off
// SetWindowLong(actWindow, GWL_STYLE, Style);
// GLFWmonitor *monitor = glfwGetPrimaryMonitor();
// const GLFWvidmode *mode = glfwGetVideoMode(monitor);
// screenWidth = mode->width;
// screenHeight = mode->height;
nvgContext = nvgCreateGL3(NVG_ANTIALIAS);
nvgCreateFont(nvgContext, "icons", "fonts/entypo.ttf");
nvgCreateFont(nvgContext, "sans", "fonts/Roboto-Regular.ttf");
nvgCreateFont(nvgContext, "sans-bold", "fonts/Roboto-Bold.ttf");
nvgCreateFont(nvgContext, "system", "oui/DejaVuSans.ttf");
nvgCreateImage(nvgContext, "oui/blender_icons16.png", 0);
perfFps = new Performance(nvgContext);
perfFps->setX(5);
perfFps->setY(5);
perfFps->initGraph(GRAPH_RENDER_FPS, "Frame Time");
// addChild(perfFps);
perfCpu = new Performance(nvgContext);
perfCpu->setX(perfFps->gX() + perfFps->width + 5);
perfCpu->setY(5);
perfCpu->initGraph(GRAPH_RENDER_MS, "CPU Time");
disEvent(VsEvent::INITED);
}
void run() {
if (!glfwInit()) {
printf("Failed to init GLFW.");
// return -1;
}
// glfwSetErrorCallback([this](int error, const char *desc) { this->errorcb(error, desc); });
glfwSetErrorCallback(errorcb);
//#ifndef _WIN32 // don't require this on win32, and works with more cards
// glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
// glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
// glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
// glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
//#endif
glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, 1);
//no title bar no border
// glfwWindowHint(GLFW_DECORATED, false);
_window = glfwCreateWindow(VS_WIDTH, VS_HEIGHT, "", nullptr, nullptr);
if (!_window) {
glfwTerminate();
// return -1;
}
glfwSetKeyCallback(_window, key);
glfwSetCharCallback(_window, charEvent);
glfwSetCursorPosCallback(_window, cursorPos);
glfwSetMouseButtonCallback(_window, mouseButton);
glfwSetScrollCallback(_window, scrollevent);
glfwMakeContextCurrent(_window);
#ifdef NANOVG_GLEW
glewExperimental = GL_TRUE;
if (glewInit() != GLEW_OK) {
cout << "Could not init glew." << endl;
// return -1;
}
// GLEW generates GL error because it calls glGetString(GL_EXTENSIONS), we'll consume it here.
glGetError();
#endif
////////////////////////vg
initVsContext();
//limit fps to monitor on=1 off=0
// glfwSwapInterval(0);
glfwSwapInterval(1);
glfwSetTime(0);
double c = 0.0;
int total = 0;
bool isPerf = true;
// if (isPerf) {
double prevt = 0, cpuTime = 0;
// }
while (!glfwWindowShouldClose(_window)) {
double mx, my;
int winWidth, winHeight;
int fbWidth, fbHeight;
float pxRatio;
double t, dt;
// if (isPerf) {
t = glfwGetTime();
_frameTime = dt = t - prevt;
prevt = t;
// }
glfwGetCursorPos(_window, &mx, &my);
glfwGetWindowSize(_window, &winWidth, &winHeight);
glfwGetFramebufferSize(_window, &fbWidth, &fbHeight);
// Calculate pixel ration for hi-dpi devices.
pxRatio = (float) fbWidth / (float) winWidth;
// Update and render
glViewport(0, 0, fbWidth, fbHeight);
glClearColor(0, 0, 0, 1);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
// double t = glfwGetTime();
nvgBeginFrame(nvgContext, winWidth, winHeight, pxRatio);
VS_CONTEXT.beginFrame();
//ui here
render(nvgContext, winWidth, winHeight);
perfFps->render();
perfCpu->render();
nvgEndFrame(nvgContext);
VS_CONTEXT.endFrame();
if (isPerf) {
cpuTime = glfwGetTime() - t;
perfFps->updateGraph(dt);
perfCpu->updateGraph(cpuTime);
}
glfwSwapBuffers(_window);
glfwPollEvents();
}
nvgDeleteGL3(nvgContext);
glfwTerminate();
}
NVGcontext *getContext() {
if (nvgContext)
return nvgContext;
else {
string e = "call init() first!";
cout << this << e << endl;
throw runtime_error(e.c_str());
}
}
void close() {
glfwSetWindowShouldClose(_window, GL_TRUE);
}
void minimize() {
glfwIconifyWindow(_window);
}
void maximize() {
if (isMaximized) {
SetWindowLong(actWindow, GWL_STYLE, noBorderStyle);
glfwSetWindowSize(_window, lastWidth, lastHeight);
}
else {
lastWidth = width;
lastHeight = height;
SetWindowLong(actWindow, GWL_STYLE, normalStyle);
ShowWindow(actWindow, SW_MAXIMIZE);
SetWindowLong(actWindow, GWL_STYLE, normalStyle & ~WS_CAPTION);
}
isMaximized = !isMaximized;
}
void moveWindow(int dx, int dy) {
RECT r;
GetWindowRect(actWindow, &r);
MoveWindow(actWindow, r.left + dx, r.top + dy, width, height, TRUE);
}
int buttons;
int mods;
int enabeld;
int action;
int renderIdx;
void beginFrame() {
// renderIdx = 0;
}
int width;
int height;
void render(NVGcontext *vg, int w, int h) {
if (this->width != w || this->height != h) {
this->width = w;
this->height = h;
disEvent(VsEvent::RESIZE);
}
disEvent(VsEvent::RENDER);
}
double getFrameTime() {
return _frameTime;
}
void endFrame() {
popUIEvent();
}
int _curCursor = 0;
map<int, GLFWcursor *> _mapCursor;
void setCursor(int v) {
if (_curCursor != v) {
_curCursor = v;
if (_mapCursor.find(v) == _mapCursor.end())
_mapCursor[v] = glfwCreateStandardCursor(v);
glfwSetCursor(_window, _mapCursor[v]);
}
}
void setCursorPos(int x, int y) {
glfwSetCursorPos(_window, x, y);
}
void hideCursor() {
glfwSetInputMode(_window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN);
}
void showCursor() {
glfwSetInputMode(_window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
}
void setMouseButton(int button, int mod, int act) {
buttons = button;
mods = mod;
action = act;
enabeld = 1;
if (button == GLFW_MOUSE_BUTTON_1) {
if (act == GLFW_PRESS) {
disEvent(MouseEvent::DOWN);
}
else if (act == GLFW_RELEASE) {
disEvent(MouseEvent::UP);
}
}
else if (button == GLFW_MOUSE_BUTTON_2) {
if (act == GLFW_PRESS)
disEvent(MouseEvent::RIGHT_DOWN);
else if (act == GLFW_RELEASE)
disEvent(MouseEvent::RIGHT_UP);
}
}
void setCursor(int x, int y) {
cursor.x = x;
cursor.y = y;
}
pos cursor;
void setKey(int key, int action, int mods) {
KeyEvent *keyEvent = new KeyEvent();
keyEvent->key = key;
keyEvent->isShift = mods & GLFW_MOD_SHIFT;
keyEvent->isAlt = mods & GLFW_MOD_ALT;
keyEvent->isCtrl = mods & GLFW_MOD_CONTROL;
if (action == GLFW_PRESS) {
keyEvent->type = KeyEvent::DOWN;
}
else if (action == GLFW_RELEASE) {
keyEvent->type = KeyEvent::UP;
}
disEvent(keyEvent);
// cout << typeid(this).name() << " key " << key << " mods " << mods << keyEvent << endl;
}
void setChar(char c) {
// KeyEvent *keyEvent = new KeyEvent;
// keyEvent->key
}
void popUIEvent() {
for (const auto &obs : _uiEvents) {
BaseEvent *event = &obs.second;
if (!event->isAccept) {
((EventDispatcher *) event->target)->disEvent(event);
event->isAccept = true;
}
}
enabeld = 0;
}
void pushUIEvent(BaseEvent event) {
_uiEvents[event.type] = event;
}
protected:
GLFWwindow *_window;
map<string, BaseEvent> _uiEvents;
NVGcontext *nvgContext = nullptr;
private:
double _frameTime;
};
void mouseButton(GLFWwindow *window, int button, int action, int mods) {
NVG_NOTUSED(window);
VsContext::_().setMouseButton(button, mods, action);
}
void cursorPos(GLFWwindow *window, double x, double y) {
NVG_NOTUSED(window);
VsContext::_().setCursor(x, y);
}
void key(GLFWwindow *window, int key, int scancode, int action, int mods) {
NVG_NOTUSED(scancode);
VsContext::_().setKey(key, action, mods);
// uiSetKey(key, mods, action);
}
void charEvent(GLFWwindow *window, unsigned int codepoint) {
NVG_NOTUSED(window);
char c = codepoint;
VsContext::_().setChar(codepoint);
cout << "charEvent" << c << endl;
}
|
d04f2cc49c4ecdf4e30d862190a0159119e07a6b
|
fd5e6ea643853dacc1ff5c6ed99d1d7cd26d50fa
|
/memory_system.cpp
|
dc12c87b61745521de43d085aba9aec95e0a1567
|
[] |
no_license
|
swelgan/membles
|
dec0a268364b1058f4b7af3110b6422d35b5a106
|
572e310562e080c40921658ec2639ba122faeefd
|
refs/heads/master
| 2020-05-18T06:00:43.784084
| 2014-06-26T05:19:03
| 2014-06-26T05:19:03
| 20,864,788
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,126
|
cpp
|
memory_system.cpp
|
/* Copyright (c) 2014, Jue Wang
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "memory_system.h"
namespace membles
{
/* ctor: Memory System
* The number of channels is 1 by default
*/
MemorySystem::MemorySystem()
: BaseObj(),
num_chan_(1),
chan_itlv_bit_(10)
{}
/* dtor: Memory System
* deallocate output stream if necesary
*/
MemorySystem::~MemorySystem()
{
if (log_) {
log_->close();
delete log_;
}
if (csv_) {
csv_->close();
delete csv_;
}
if (trc_) {
trc_->close();
delete trc_;
}
}
/*
* Initialize the memory system by specifying:
* the controller configuration including the number of channels
* an array of device configuration and channel capacity
* If the array size is less than channel count, then assuming a homogeneous
* channel seeting
*/
bool MemorySystem::init(const string &ctrl_filename,
const vector<string> &dev_filenames,
vector<uint64_t> sizes)
{
// TODO: just for test
trc_ = new ofstream;
trc_->open("test.trc", ios_base::out | ios_base::trunc);
sizes_ = sizes;
bool success = true;
// load controller configuration file
success &= ctrl_cfg_.ReadFile(ctrl_filename);
num_chan_ = ctrl_cfg_.num_chan;
chan_itlv_bit_ = ctrl_cfg_.chan_itlv_bit;
freq_ = ctrl_cfg_.ctrl_freq;
// load device configuration files
if (num_chan_ < dev_filenames.size()) {
ERROR("User provides " << dev_filenames.size() << " device "
"configurations in a " << num_chan_ << "-channel system");
return false;
}
if (sizes.size() != 1 && num_chan_ != sizes.size()) {
ERROR("User provides " << sizes.size() << " capacity settings "
"in a " << num_chan_ << "-channel system");
return false;
}
dev_cfgs_.resize(num_chan_);
// set verbosity
if (verbose_) {
for (auto &cfg : dev_cfgs_) cfg.set_verbose();
}
// load device configuration one by one
for (size_t i = 0; i < num_chan_; ++i) {
size_t index = i;
if (index >= dev_filenames.size()) index = dev_filenames.size() - 1;
success &= dev_cfgs_[i].ReadFile(dev_filenames[index]);
}
// set channel capacity
sizes_.resize(num_chan_);
for (size_t i = 0; i < num_chan_; ++i) {
if (sizes.size() == 1) {
sizes_[i] = sizes[0] / num_chan_;
} else {
sizes_[i] = sizes[i];
}
success &= dev_cfgs_[i].derive(sizes_[i], ctrl_cfg_);
}
// check if channel capacit can be correctly partitioned
if (sizes.size() == 1 && sizes_[0] * num_chan_ != sizes[0]) {
ERROR(sizes[0] << "MB cannot be evenly divided into a " << num_chan_
<< "-channel system");
return false;
}
// check if the entire initialization is successful
if (!success) {
ERROR("Fail to initialize the memory system.");
return false;
}
// create components
// create N channels depending on the input setting
channels_.resize(num_chan_);
for (size_t i = 0; i < num_chan_; ++i) {
if (verbose_) channels_[i].set_verbose();
success &= channels_[i].init(i, &ctrl_cfg_, &(dev_cfgs_[i]), log_,
csv_, trc_);
}
return success;
}
/*
* Simulate one cycle ahead
*/
void MemorySystem::step()
{
// TODO
cycle_++;
for (size_t i = 0; i < num_chan_; ++i) {
channels_[i].step();
}
}
/*
* Find which channel a transaciton belongs to
*/
uint32_t MemorySystem::FindChanId(Transaction *tx)
{
assert(tx);
if (num_chan_ == 1) return 0;
uint64_t mask = (1UL << num_chan_) - 1;
return (tx->addr() >> chan_itlv_bit_) & mask;
}
/*
* Add a transaction into the memory system
* Return false if the transaction queue cannot hold the incoming transaction
*/
bool MemorySystem::AddTx(Transaction *tx)
{
if (tx->len() > (1UL << chan_itlv_bit_)) {
ERROR("Found a transaction whose length is larger than channel "
"interleaving granularity");
return false;
}
uint32_t chan = FindChanId(tx);
return channels_[chan].AddTx(tx);
}
/*
* Print some statistics of the memory system
*/
void MemorySystem::stat()
{
// TODO
}
/*
* Override this function because we need to cascade the setting
*/
void MemorySystem::set_verbose()
{
BaseObj::set_verbose();
// set verbosity to controller configuration
// device configuration verbosity will be correctly set later
ctrl_cfg_.set_verbose();
// TODO
}
}
|
421dfee5c798ecab9ff15f3cd2e6c89af97d4876
|
f8303dca1b39028da22d58c4e9fd62f6f91a0cd0
|
/backend/c++/libs/ioc/test/container/ClassFactoryTests.cpp
|
0588f74a59383152a5c6865128977f5bd194f2cf
|
[] |
no_license
|
m-biermann/mabiphmo
|
92f8adccac8cd00e27efb1adddaac9e2060e60c9
|
740cb8bf50a82db82448ed174335699f31f9eb5d
|
refs/heads/master
| 2022-12-12T00:59:05.998336
| 2020-09-06T15:42:09
| 2020-09-06T15:42:09
| 291,800,601
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,075
|
cpp
|
ClassFactoryTests.cpp
|
//
// Created by max on 8/14/20.
//
#include <mabiphmo/ioc/Container.h>
#include <boost/test/unit_test.hpp>
#include "structs.h"
BOOST_AUTO_TEST_SUITE(container)
BOOST_AUTO_TEST_SUITE(class_factory)
BOOST_AUTO_TEST_CASE(registerAndGet)
{
mabiphmo::ioc::Container uut;
uut.RegisterClassFactory<A, std::tuple<unsigned>, std::tuple<>>();
std::shared_ptr<A> aInst3 = uut.GetInstance<A>((unsigned)3);
std::shared_ptr<A> aInst2 = uut.GetInstance<A>((unsigned)2);
BOOST_TEST(aInst3 != aInst2);
BOOST_TEST(aInst3->a == 3);
BOOST_TEST(aInst2->a == 2);
BOOST_TEST(aInst3 != uut.GetInstance<A>((unsigned)3));
BOOST_TEST(aInst2 != uut.GetInstance<A>((unsigned)2));
}
BOOST_AUTO_TEST_CASE(registerWithDependencyAndGet)
{
mabiphmo::ioc::Container uut;
uut.RegisterSingletonClassFactory<A>(3);
uut.RegisterClassFactory<B, std::tuple<unsigned>, std::tuple<A>>();
std::shared_ptr<B> bInst5 = uut.GetInstance<B>((unsigned)5);
std::shared_ptr<B> bInst6 = uut.GetInstance<B>((unsigned)6);
std::shared_ptr<A> aInst = uut.GetInstance<A>();
BOOST_TEST(bInst5 != bInst6);
BOOST_TEST(bInst5->b == 5);
BOOST_TEST(bInst6->b == 6);
BOOST_TEST(bInst5 != uut.GetInstance<B>((unsigned)5));
BOOST_TEST(bInst6 != uut.GetInstance<B>((unsigned)6));
BOOST_TEST(bInst6->a == aInst);
BOOST_TEST(bInst5->a == aInst);
BOOST_TEST(aInst->a == 3);
}
BOOST_AUTO_TEST_CASE(registerOnInterfaceAndGet)
{
mabiphmo::ioc::Container uut;
uut.RegisterClassFactoryOnInterface<IC, CImpl, std::tuple<unsigned>, std::tuple<>>();
std::shared_ptr<IC> cInst5 = uut.GetInstance<IC>((unsigned)5);
std::shared_ptr<IC> cInst6 = uut.GetInstance<IC>((unsigned)6);
BOOST_TEST(cInst5 != cInst6);
BOOST_TEST(cInst5->C() == 5);
BOOST_TEST(cInst6->C() == 6);
BOOST_TEST(cInst5 != uut.GetInstance<IC>((unsigned)5));
BOOST_TEST(cInst6 != uut.GetInstance<IC>((unsigned)6));
}
BOOST_AUTO_TEST_CASE(registerWithDependencyInjectionAndGet)
{
mabiphmo::ioc::Container uut;
uut.RegisterSingletonClassFactoryOnInterface<IC, CImpl>(10);
uut.RegisterSingletonClassFactory<A>(3);
uut.RegisterSingletonClassFactory<B, A>(5);
uut.RegisterClassFactory<D, std::tuple<unsigned>, std::tuple<B, IC>>();
std::shared_ptr<D> dInst2 = uut.GetInstance<D>((unsigned)2);
std::shared_ptr<D> dInst3 = uut.GetInstance<D>((unsigned)3);
std::shared_ptr<IC> cInst = uut.GetInstance<IC>();
std::shared_ptr<B> bInst = uut.GetInstance<B>();
std::shared_ptr<A> aInst = uut.GetInstance<A>();
BOOST_TEST(dInst2 != dInst3);
BOOST_TEST(dInst2->sum == 20);
BOOST_TEST(dInst3->sum == 21);
BOOST_TEST(dInst2->d == 2);
BOOST_TEST(dInst3->d == 3);
BOOST_TEST(dInst2 != uut.GetInstance<D>((unsigned)2));
BOOST_TEST(dInst3 != uut.GetInstance<D>((unsigned)3));
BOOST_TEST(dInst2->c == cInst);
BOOST_TEST(dInst3->c == cInst);
BOOST_TEST(cInst->C() == 10);
BOOST_TEST(dInst2->b == bInst);
BOOST_TEST(dInst3->b == bInst);
BOOST_TEST(bInst->b == 5);
BOOST_TEST(bInst->a == aInst);
BOOST_TEST(aInst->a == 3);
}
BOOST_AUTO_TEST_SUITE_END()
BOOST_AUTO_TEST_SUITE_END()
|
b7a73eea707dc2c847aaafd48695fbe2a7971ab1
|
772d932a0e5f6849227a38cf4b154fdc21741c6b
|
/CPP_Joc_Windows_Android/SH_Client_Win_Cpp_Cmake/App/src/graphics/geometry/data/bufferChangesTracker/GLBCTSingleRegion.cpp
|
bdc8992f8eee2d822f6801973ff12fd1855ab5c9
|
[] |
no_license
|
AdrianNostromo/CodeSamples
|
1a7b30fb6874f2059b7d03951dfe529f2464a3c0
|
a0307a4b896ba722dd520f49d74c0f08c0e0042c
|
refs/heads/main
| 2023-02-16T04:18:32.176006
| 2021-01-11T17:47:45
| 2021-01-11T17:47:45
| 328,739,437
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,592
|
cpp
|
GLBCTSingleRegion.cpp
|
#include "GLBCTSingleRegion.h"
#include <base/opengl/util/GLUtil.h>
#include <base/list/CompositesBuffer.h>
#include <base/opengl/IGL.h>
#include <base/math/Math.h>
using namespace graphics;
GLBCTSingleRegion::GLBCTSingleRegion(CompositesBuffer* buffer)
: super(buffer)
{
//void
}
void GLBCTSingleRegion::validate(GLenum glBindTarget) {
int invalidRangeLen = invalidEntriesRange.getLenX();
if (invalidRangeLen > 0) {
// Make sure to not update outside of the active buffer range if it shrunk.
GLUtil::gl->bufferSubData(
glBindTarget/*target*/,
invalidEntriesRange.min.x * buffer->stride()/*offset_in_bytes*/, Math::min(invalidRangeLen, buffer->count()) * buffer->stride()/*size_in_bytes*/,
buffer->getData()/*data*/
);
invalidEntriesRange.clear();
}
//asd_01;// a bug exists here, it seems like the remaping buffer is the proble.
//asd_01;_t;
GLUtil::gl->bufferSubData(
glBindTarget/*target*/,
0/*offset_in_bytes*/, buffer->count() * buffer->stride()/*size_in_bytes*/,
buffer->getData()/*data*/
);
}
void GLBCTSingleRegion::invalidateUsedRegion() {
// This class doesn't ignore the optional buffer empty region because this does only 1 update block.
/// The center_empty buffer region is not used with this update method.
invalidEntriesRange.unionOther(0/*xMin*/, 0 + buffer->count()/*xMax*/);
}
void GLBCTSingleRegion::invalidateRegion(int blockEntriesOffset, int blockEntriesCount) {
invalidEntriesRange.unionOther(blockEntriesOffset/*xMin*/, blockEntriesOffset + blockEntriesCount/*xMax*/);
}
GLBCTSingleRegion::~GLBCTSingleRegion() {
//void
}
|
7e6de58913359484929159bbc78b783ef55f67a2
|
8402b846cd8f86034d16d72809a1483c603a9019
|
/LOJ/6046.cpp
|
83bbb628eaee897c57bff7906e67ca7c78ccd442
|
[] |
no_license
|
syniox/Online_Judge_solutions
|
6f0f3b5603c5e621f72cb1c8952ffbcbb94e3ea6
|
c4265f23823e7f1c87141f5a7429b8e55e906ac6
|
refs/heads/master
| 2021-08-29T05:40:06.071468
| 2021-08-28T03:05:28
| 2021-08-28T03:05:28
| 136,417,266
| 2
| 3
| null | 2018-06-10T09:33:57
| 2018-06-07T03:31:17
|
C++
|
UTF-8
|
C++
| false
| false
| 2,713
|
cpp
|
6046.cpp
|
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cassert>
#include <algorithm>
//const int N=3e4+5;
//const int S=175;
const int N=1e5+5;
const int S=320;
int n,m,val[N],bel[N];
int b_que[S][S+5],b_len[S],b_dlt[N];
namespace utils{
template <class T> inline void apx(T &x,const T y){
x<y?x=y:0;
}
template <class T> inline void apn(T &x,const T y){
x>y?x=y:0;
}
inline int nxi(FILE *fd=stdin){
int x=0;
char c;
while(((c=fgetc(fd))>'9'||c<'0')&&c!='-');
const bool f=(c=='-')&&(c=fgetc(fd));
while(x=x*10-48+c,(c=fgetc(fd))>='0'&&c<='9');
return f?-x:x;
}
}
using namespace utils;
namespace G{
int cnt=1,fir[N],dfn[N],sz[N],dep[N];
struct edge{
int to,wi,nx;
}eg[N];
inline void add(const int a,const int b,const int v){
eg[++cnt]=(edge){b,v,fir[a]};
fir[a]=cnt;
}
void dfs(const int x){
static int cnd;
dfn[x]=++cnd;
sz[x]=1;
for(int i=fir[x]; i; i=eg[i].nx){
const int y=eg[i].to;
dep[y]=dep[x]+eg[i].wi;
dfs(y);
sz[x]+=sz[y];
}
}
}
int getsum(int *a,int len,int v){
//小于等于的个数
return std::upper_bound(a+1,a+len+1,v)-a-1;
}
void build(const int p){
int l=(p-1)*S+1,r=std::min(n,p*S);
int cnt=0;
int *que=b_que[p];
for(int i=l; i<=r; ++i){
que[++cnt]=val[i];
}
std::sort(que+1,que+cnt+1);
b_len[p]=cnt;
}
void add(const int l,const int r,const int v){
if(bel[l]==bel[r]){
for(int i=l; i<=r; ++i){
val[i]+=v;
}
build(bel[l]);
return;
}
for(int i=bel[l]+1; i<bel[r]; ++i){
b_dlt[i]+=v;
}
for(int i=l; bel[i]==bel[l]; ++i){
val[i]+=v;
}
for(int i=r; bel[i]==bel[r]; --i){
val[i]+=v;
}
build(bel[l]);
build(bel[r]);
}
int ask(const int x,const int y,const int k){
static int que[S<<1];
if(y-x+1<k) return -1;
int cnt=0;
if(bel[x]==bel[y]){
for(int i=x; i<=y; ++i){
que[++cnt]=val[i]+b_dlt[bel[i]];
}
}
else{
for(int i=x; bel[i]==bel[x]; ++i){
que[++cnt]=val[i]+b_dlt[bel[i]];
}
for(int i=y; bel[i]==bel[y]; --i){
que[++cnt]=val[i]+b_dlt[bel[i]];
}
}
std::sort(que+1,que+cnt+1);
int l=0,r=n*20,mid;
while(l!=r){
mid=(l+r)>>1;
int res=getsum(que,cnt,mid);
for(int i=bel[x]+1; i<bel[y]; ++i){
res+=getsum(b_que[i],b_len[i],mid-b_dlt[i]);
}
if(res>=k) r=mid;
else l=mid+1;
}
return l;
}
int main(){
n=nxi(),m=nxi();
nxi();
for(int i=2; i<=n; ++i){
int f=nxi(),v=nxi();
G::add(f,i,v);
}
G::dfs(1);
for(int i=1; i<=n; ++i){
bel[i]=(i-1)/S+1;
val[G::dfn[i]]=G::dep[i];
}
for(int i=1; i<=bel[n]; ++i){
build(i);
}
for(int i=1; i<=m; ++i){
const int op=nxi(),x=nxi(),y=nxi();
if(op==2){
add(G::dfn[x],G::dfn[x]+G::sz[x]-1,y);
}
else{
printf("%d\n",ask(G::dfn[x],G::dfn[x]+G::sz[x]-1,y));
}
}
return 0;
}
|
f582d825351b9fc0dfe2cc5a2564332748cc5a92
|
ef2ecfbd789fc409bdc02f7637a4dee4591bc699
|
/Projects/04/protocols/ipv6/include/ipv6/domain/ipv6.h
|
ca1910e1783301ee9fb7315da6c032db7a106d88
|
[] |
no_license
|
muff1nman/CSCI471
|
66a927f977eeb57408c79da2ddaef93503eb829d
|
1e530e6b16fc73b10c1dac5d7a1d46a2ecffa0e0
|
refs/heads/master
| 2021-01-23T12:11:35.447697
| 2013-12-07T11:49:40
| 2013-12-07T11:49:40
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,875
|
h
|
ipv6.h
|
/*
* ipv6.h
* Copyright (C) 2013 Andrew DeMaria (muff1nman) <ademaria@mines.edu>
*
* All Rights Reserved.
*/
#ifndef IPV6_H
#define IPV6_H
#include <bitset>
#include "networkmuncher/util/byte/byte.h"
#include "networkmuncher/util/byte/convert.h"
#include "networkmuncher/util/logging.h"
#include "networkmuncher/domain/network_layer_protocol.h"
struct Ipv6 : public Logging, public NetworkLayerProtocol {
public:
virtual int what_type() const { return PType::Network::IPV6; }
static const size_t EXPECTED_VERSION = 6;
/**
* Lengths for bitsets
*/
static const size_t VERSION_LENGTH = 4;
static const size_t TOS_LENGTH = 8;
static const size_t FLOW_LENGTH = 20;
static const size_t TOTAL_LENGTH_LENGTH = 16;
static const size_t NEXT_HEADER_LENGTH = 8;
static const size_t HOP_LIMIT_LENGTH = 8;
static const size_t ADDR_LENGTH = 128;
static const size_t ADDR_LENGTH_IN_BYTES = ADDR_LENGTH / BITS_PER_BYTE;
/**
* Types
*/
typedef std::bitset<VERSION_LENGTH> Version;
typedef std::bitset<TOS_LENGTH> Tos;
typedef std::bitset<FLOW_LENGTH> Flow;
typedef std::bitset<TOTAL_LENGTH_LENGTH> TotalLength;
typedef std::bitset<NEXT_HEADER_LENGTH> NextHeader;
typedef std::bitset<HOP_LIMIT_LENGTH> HopLimit;
typedef std::bitset<ADDR_LENGTH> Addr;
/**
* Ipv6 instance variables
*/
Version version;
Tos tos;
Flow flow;
TotalLength total_length;
NextHeader next_header;
HopLimit hop_limit;
Addr source_addr;
Addr dest_addr;
friend class Ipv6Builder;
std::string stringify_object() const {
std::stringstream object;
object << "Todo";
return object.str();
}
bool operator==( const Ipv6& other ) const {
return
version == other.version &&
tos == other.tos &&
flow == other.flow &&
total_length == other.total_length &&
next_header == other.next_header &&
hop_limit == other.hop_limit &&
source_addr == other.source_addr &&
dest_addr == other.dest_addr &&
true;
}
static inline std::string addr_from_data( const BytesContainer& data ) {
std::stringstream joined;
for( size_t i = 0; i < ADDR_LENGTH_IN_BYTES; ++i ) {
if( ! (i < data.size()) ) {
throw "Unexpected end of data while parsing ip";
}
joined << (size_t) data.at(i);
if( i != ADDR_LENGTH_IN_BYTES - 1 ) {
joined << ".";
}
}
return joined.str();
}
static inline std::string addr_from_data( const std::bitset<ADDR_LENGTH>& data ) {
return addr_from_data( convert_big_endian<ADDR_LENGTH_IN_BYTES>(data));
}
// TODO make protected
// protected:
Ipv6() {}
};
#endif /* !IPV6_H */
|
e7c62013903a41303918377e3ad7d1c64ee38337
|
18cc5605600f9fe69e0b994156259c606128ac8a
|
/src/listgame.cpp
|
19007855ce34829c8c950594e2e7bb889cc8c0f3
|
[] |
no_license
|
sam-hunt/open-kattis
|
2583ebdc61ec467c418c17f0fb7250fa99b2624f
|
f9c8ad5c27b709554c0328053210b661bde5fe16
|
refs/heads/master
| 2021-03-22T05:11:39.800389
| 2017-03-22T11:24:27
| 2017-03-22T11:24:27
| 73,696,194
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 624
|
cpp
|
listgame.cpp
|
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
unsigned long long X = 0;
scanf("%llu", &X);
unsigned int prime_factors = 0;
unsigned long long divisor = 3;
unsigned long long Xsqrt = ceil(sqrt(X));
while (!(X % 2))
{
X /= 2;
prime_factors++;
//printf("2 ");
}
while ((X>1) && !(!prime_factors && divisor > Xsqrt))
{
while (!(X % divisor))
{
X /= divisor;
//printf("%llu ", divisor);
prime_factors++;
}
divisor++;
divisor++;
}
if (!prime_factors)
prime_factors=1;
printf("%u\n", prime_factors);
return(0);
}
|
9ceb9cbfa0845e5b1c93b11a660d5da6a7d1ab48
|
95fdb141b16815d46f4549702fdaba91a44b0d5e
|
/contest/Topic 4/0316211-4-B.cpp
|
c705b9619d9ebb2e633b583c61aef0306088f643
|
[] |
no_license
|
leo0049l/Programming-contest
|
fb356fcb68294ff6cd95c63a8e25562cd1019943
|
71e2b2441fc80fbb554e64004d20a04a74b33bdf
|
refs/heads/master
| 2021-07-07T00:07:46.821471
| 2017-10-03T07:38:28
| 2017-10-03T07:38:28
| 105,625,690
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 642
|
cpp
|
0316211-4-B.cpp
|
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
int size;
cin>>size;
int ans;
int answer=-9999999;
int array[size][size];
int sum[size][size];
for(int i=0;i<size;i++)
{
for(int j=0;j<size;j++)
{
sum[i][j]=0;
scanf("%d",&array[i][j]);
if(i>0)
sum[i][j]+=(array[i][j]+sum[i-1][j]);
else
sum[i][j]=array[i][j];
}
}
for(int i=0;i<size;i++)
{
for(int j=i;j<size;j++)
{
ans=0;
for(int k=0;k<size;k++)
{
if(i<1)
ans+=sum[j][k];
else
ans+=(sum[j][k]-sum[i-1][k]);
if(ans>answer)
answer=ans;
if(ans<0)
ans=0;
}
}
}
cout<<answer<<endl;
return 0;
}
|
29e9b66cc276d90097d195d1433c48be02f0f378
|
86a6a4f978fdf44351390513814d4f6715faa2c8
|
/HMM/viterbi/viterbi/main.cpp
|
dd01b1c9087f034c12b91023a6b0f45cda428ad8
|
[] |
no_license
|
irismanchen/Chinese_parser
|
19d7e2fab18661a788e8ec7c7d8f57181bc37609
|
46ce0c90f2cbfda152204af6f4fcceb1eb9afc82
|
refs/heads/master
| 2021-01-10T10:20:48.340855
| 2016-03-22T14:00:16
| 2016-03-22T14:00:16
| 54,479,540
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 16,446
|
cpp
|
main.cpp
|
//
// main.cpp
// viterbi
//
// Created by 王曼晨 on 15/12/19.
// Copyright © 2015年 王曼晨. All rights reserved.
//
#include <iostream>
#include <fstream>
#include <sstream>
#include <map>
#include <vector>
#include <stack>
#include <iomanip>
using namespace std;
const int N = 4;
const int M = 4577;
class DB
{
private:
map<string,int> cchar_map; //汉字-编码映射
map<int,string> index_map; //编码-汉字映射
public:
DB();
DB(string file);
string getCchar(int id); //根据编码获得汉字
int getObservIndex(string cchar); //根据汉字获得编码
int getStateIndex(char state); //根据状态获得状态编号,B-0,M-1,E-2,S-3
vector<int> makeObservs(string line); //将输入的句子构造为发射符号序列
};
DB::DB(){}
DB::DB(string file){
ifstream fin(file.c_str());
if(!fin){
cout << "Open input file fail ! " << endl;
exit(-1);
}
string line = "";
string word = "";
string cchar = "";
int id = 0;
while(getline(fin, line)){
istringstream strstm(line);
strstm >> word;
cchar = word;
strstm >> word;
id = atoi(word.c_str()); //加入map
cchar_map[cchar] = id;
index_map[id] = cchar;
}
}
int DB::getStateIndex(char state){
switch(state){
case 'B' :
return 0;
break;
case 'M' :
return 1;
break;
case 'E' :
return 2;
break;
case 'S' :
return 3;
break;
default :
return -1;
break;
}
}
int DB::getObservIndex(string cchar){
map<string, int>::iterator iter = cchar_map.find(cchar);
if(iter != cchar_map.end()){
return iter -> second;
}else{
return -1;
}
}
string DB::getCchar(int id){
map<int, string>::iterator iter = index_map.find(id);
if(iter != index_map.end()){
return iter -> second;
}else{
return NULL;
}
}
vector<int> DB::makeObservs(string line){
vector<int> vec_observ; //输出符号的集合
string cchar = ""; //存放每个汉字
string word = ""; //存放一个单词
int num = 0; //单词的字数
int index = -1; //单词对应的编号
istringstream strstm(line);
while(strstm >> word){
if(word.size()%3 != 0){
cout << "单词不符合要求:" << word << endl;
continue;
}
num =(int)word.size()/3;
if(num == 0){
continue;
}
else{
for(int i = 0; i < num; i++){
cchar = word.substr(3*i, 3);
index = getObservIndex(cchar);
vec_observ.push_back(index);
//cout << "cchar = " << cchar << " index = " << index << endl;
}
}
}
return vec_observ;
}
class HMM
{
public:
int n; //状态数目
int m; //可能的观察符号数目
double Pi[N]; //初始状态概率
double A1[N][N]; //状态转移概率矩阵
double A2[N][N][N]; //状态转移概率矩阵
double B1[N][M]; //符号发射概率矩阵
double B2[N][N][M]; //符号发射概率矩阵
HMM();
HMM(string f_pi, string f_a1, string f_a2, string f_b1, string f_b2);
};
HMM::HMM(){}
HMM::HMM(string f_pi, string f_a1, string f_a2, string f_b1, string f_b2){
ifstream fin_1(f_pi.c_str());
ifstream fin_2(f_a1.c_str());
ifstream fin_3(f_a2.c_str());
ifstream fin_4(f_b1.c_str());
ifstream fin_5(f_b2.c_str());
if(!(fin_1 && fin_2 && fin_3 && fin_4 && fin_5)){
exit(-1);
}
n = N;
m = M;
string line = "";
string word = "";
getline(fin_1, line); //读取Pi
istringstream strstm_1(line);
for(int i = 0; i < N; i++){
strstm_1 >> word;
Pi[i] = atof(word.c_str());
//cout<<Pi[i]<<endl;
}
for(int i = 0; i < N; i++){ //读取A1
getline(fin_2, line);
istringstream strstm_2(line);
for(int j = 0; j < N; j++){
strstm_2 >> word;
A1[i][j] = atof(word.c_str());
}
}
for(int i = 0; i < N; i++){ //读取A2
for(int j = 0; j < N; j++){
getline(fin_3, line);
istringstream strstm_3(line);
for(int k = 0; k < N; k++){
strstm_3 >> word;
A2[i][j][k] = atof(word.c_str());
}
}
}
for(int i = 0; i < N; i++){ //读取B1
getline(fin_4, line);
istringstream strstm_4(line);
for(int j = 0; j < M; j++){
strstm_4 >> word;
B1[i][j] = atof(word.c_str());
}
}
for(int i = 0; i < N; i++){ //读取B2
for(int j = 0; j < N; j++){
getline(fin_5, line);
istringstream strstm_5(line);
for(int k = 0; k < M; k++){
strstm_5 >> word;
B2[i][j][k] = atof(word.c_str());
}
}
}
fin_1.close();
fin_2.close();
fin_3.close();
fin_4.close();
fin_5.close();
}
DB db("/Users/Iris/Desktop/viterbi/word2num.txt");
HMM hmm("/Users/Iris/Desktop/viterbi/Pi.txt","/Users/Iris/Desktop/viterbi/A1.txt","/Users/Iris/Desktop/viterbi/A2.txt","/Users/Iris/Desktop/viterbi/B1.txt","/Users/Iris/Desktop/viterbi/B2.txt");
string viterbiTwo(string str_in){
int row = (int)str_in.size() / 3; //计算输入句子中的汉字个数
//cout<<row<<endl;
string str_out = "";
if(row == 0){ //如果输入字符串为空,则直接返回空
return str_out;
}
if(row < 2){ //如果只有一个字的话,则直接输出即可
str_out = str_in + " ";
return str_out;
}
double **delta = new double *[row]; //分配矩阵空间
int **path = new int *[row];
for(int i = 0; i < row; i++){
delta[i] = new double[N]();
path[i] = new int[N]();
}
string cchar = ""; //存放汉字
int min_path = -1;
double val = 0.0;
double min_val = 0.0;
cchar = str_in.substr(0, 3); //取第一个字
int cchar_num = db.getObservIndex(cchar); //第一个字的编号
for(int i = 0; i < N; i++){ //初始化矩阵,给delta和path矩阵的第一行赋初值
delta[0][i] = hmm.Pi[i] + hmm.B1[i][cchar_num]; //之前取过负对数了
path[0][i] = -1;
}
for(int t = 1; t < row; t++){ //给delta和path的后续行赋值
cchar = str_in.substr(3*t, 3);
cchar_num = db.getObservIndex(cchar);
for(int j = 0; j < N; j++){ //遍历当前字每个隐藏状态
min_val = 100000.0;
min_path = -1;
for(int i = 0; i < N; i++){ //遍历上个字每个隐藏状态
val = delta[t-1][i] + hmm.A1[i][j]; //加隐藏状态转移函数
if(val < min_val){
min_val = val;
min_path = i;
}
}
delta[t][j] = min_val + hmm.B1[j][cchar_num];
path[t][j] = min_path;
}
}
min_val = 100000.0;
min_path = -1;
for(int i = 0; i < N; i++){ //找delta矩阵最后一行的最大值
if(delta[row-1][i] < min_val){
min_val = delta[row-1][i];
min_path = i;
}
}
stack<int> path_st;
path_st.push(min_path);
for(int i = row - 1; i > 0; i--){ //从min_path出发,回溯得到最可能的路径
min_path = path[i][min_path];
path_st.push(min_path);
}
for(int i = 0; i < row; i++){ //释放二维数组
delete []delta[i];
delete []path[i];
}
delete []delta;
delete []path;
int pos = 0;
int index = -1;
while(!path_st.empty()){
index = path_st.top();
path_st.pop();
str_out.insert(str_out.size(), str_in, pos, 3);
if(index == 2 || index == 3){ //状态为E或S
str_out.append(" ");
}
pos += 3;
}
return str_out;
}
string viterbiThree(string str_in){
int row = (int)str_in.size() / 3;
string str_out = "";
if(row == 0){
return str_out;
}
if(row < 2){
str_out = str_in + " ";
return str_out;
}
double ***delta = new double **[row];
int ***path = new int **[row];
for(int i = 0; i < row; i++){
delta[i] = new double *[N];
path[i] = new int *[N];
for(int j = 0; j < N; j++){
delta[i][j] = new double[N];
path[i][j] = new int[N];
for(int k = 0; k < N; k++){
delta[i][j][k] = 0.0;
path[i][j][k] = 0;
}
}
}
//初始化矩阵,给delta和path矩阵的第1个面赋初值
//初始状态需要两个面,第0面不赋值,只给第1个面赋值
string cchar_1 = str_in.substr(0, 3); //第1个字
string cchar_2 = str_in.substr(3, 3); //第2个字
int num_1 = db.getObservIndex(cchar_1); //第1个字的编号
int num_2 = db.getObservIndex(cchar_2); //第2个字的编号
for(int i = 0; i < N; i++){
for(int j = 0; j < N; j++){
delta[1][i][j] = hmm.Pi[i] + hmm.B1[i][num_1] +
hmm.A1[i][j] + hmm.B2[i][j][num_2]; //负对数
path[1][i][j] = -1;
}
}
string cchar_3 = ""; //存放汉字
int min_path = -1;
double val = 0.0;
double min_val = 0.0;
//给delta和path的后续面赋值(对数)
//第0、1面为初始面,后续面从2开始,到row-1为止
for(int t = 2; t < row; t++){
cchar_3 = str_in.substr(3*t, 3);
int num_3 = db.getObservIndex(cchar_3);
for(int j = 0; j < N; j++){
for(int k = 0; k < N; k++){
min_val = 100000.0;
min_path = -1;
for(int i = 0; i < N; i++){
val = delta[t-1][i][j] + hmm.A2[i][j][k];
if(val < min_val){
min_val = val;
min_path = i;
}
}
delta[t][j][k] = min_val + hmm.B2[j][k][num_3];
path[t][j][k] = min_path;
}
}
}
//找delta矩阵最后一个面的最大值,最后一个面为row-1
min_val = 100000.0;
int min_path_i = -1;
int min_path_j = -1;
for(int i = 0; i < N; i++){
for(int j = 0; j < N; j++){
if(delta[row-1][i][j] < min_val){
min_val = delta[row-1][i][j];
min_path_i = i;
min_path_j = j;
}
}
}
//从min_path_i和min_path_j出发,回溯得到最可能的路径
//回溯从row-1开始,到2为止
stack<int> path_st;
path_st.push(min_path_j);
path_st.push(min_path_i);
for(int t = row - 1; t > 1; t--){
int min_path_k = path[t][min_path_i][min_path_j];
path_st.push(min_path_k);
min_path_j = min_path_i;
min_path_i = min_path_k;
}
for(int i = 0; i < row; i++){ //释放三维数组
for(int j = 0; j < N; j++){
delete []delta[i][j];
delete []path[i][j];
}
delete []delta[i];
delete []path[i];
}
delete []delta;
delete []path;
int pos = 0; //根据标记好的状态序列分词
int index = -1;
while(!path_st.empty()){
index = path_st.top();
path_st.pop();
str_out.insert(str_out.size(), str_in, pos, 3);
if(index == 2 || index == 3){
str_out.append(" ");
}
pos += 3;
}
return str_out;
}
vector<int> getPos(string strline_right, string strline_in){ //计算切分标记的位置
int pos_1 = 0;
int pos_2 = -2;
int pos_3 = 0;
string word = "";
vector<int> vec;
int length = (int)strline_right.length(); //切分后的字符串
while(pos_2 < length){
pos_1 = pos_2; //前面的分词标记
pos_2 = (int)strline_right.find(" ", pos_1 + 2); //后面的分词标记
if(pos_2 > pos_1){
word = strline_right.substr(pos_1 + 2, pos_2 - pos_1 - 2); //将两个分词标记之间的单词取出
//cout<<word<<endl;
pos_3 = (int)strline_in.find(word, pos_3); //根据单词去输入序列中查出出现的位置
vec.push_back(pos_3); //将位置存入数组
//cout<<pos_3<<" ";
pos_3 = pos_3 + (int)word.size();
}
else{
break;
}
}
//cout<<endl;
return vec;
}
vector<int> getCount_2(string strline, vector<int> vec_right, vector<int> vec_out)
{ //vec_right 正确的分词标记位置集合,vec_out 函数切分得到的分词标记位置集合
vector<int> vec(4, 0); //存放计算结果
map<int, int> map_result;
for(int i = 0; i < vec_right.size(); i++){
map_result[vec_right[i]] += 1;
}
for(int i = 0; i < vec_out.size(); i++){
map_result[vec_out[i]] += 2;
}
map<int, int>::iterator p_pre, p_cur;
int count_value_1 = 0; //只在vec_right中
int count_value_2 = 0; //只在vec_out中
int count_value_3 = 0; //切分正确的数目
p_pre = map_result.begin();
p_cur = map_result.begin();
while(p_cur != map_result.end()){
while(p_cur != map_result.end() && p_cur -> second == 3){
p_pre = p_cur;
++count_value_3; //切分正确的数目
++p_cur; //迭代器后移
}
while(p_cur != map_result.end() && p_cur -> second != 3){
if(p_cur -> second == 1){
++count_value_1;
}
else if(p_cur -> second == 2){
++count_value_2;
}
++p_cur;
}
if(p_cur == map_result.end() && p_cur == (++p_pre)){
continue;
}
if(count_value_1 > 0 && count_value_2 == 0)
vec[1]+= count_value_1;
else if(count_value_1 == 0 && count_value_2 > 0)
vec[2] += count_value_2;
else if(count_value_1 > 0 && count_value_2 > 0)
vec[3] += count_value_2;
count_value_1 = 0;
count_value_2 = 0;
}
vec[0] += count_value_3;
return vec;
}
int main()
{
string strline_in,strline_right,strline_out_1;
ifstream fin2("/Users/Iris/Desktop/viterbi/test.txt");
ifstream fin3("/Users/Iris/Desktop/viterbi/test.answer.txt");
ofstream fout2("/Users/Iris/Desktop/viterbi/viterbitest2.txt");
ofstream fout3("/Users/Iris/Desktop/viterbi/viterbitest3.txt");
long count=0; //句子总数
long count_1 = 0; //隐马尔科夫模型(二阶)切分完全正确的句子总数
long count_out_1_all = 0; //隐马尔科夫模型切分总数
long count_right_all = 0; //准确的切分总数
long count_out_1_right_all = 0; //隐马尔科夫模型切分正确总数
while(getline(fin2,strline_in,'\n')) //没切的
{
//cout<<strline_in<<endl;
//cout<<strline_in.size()<<endl;
strline_out_1 = viterbiThree(strline_in);
fout3<<strline_out_1<<endl;
getline(fin3,strline_right); //切好的
//cout<<strline_right<<endl;
count++;
vector<int> vec_right = getPos(strline_right, strline_in);
vector<int> vec_out_1 = getPos(strline_out_1, strline_in);
if(vec_right == vec_out_1){
count_1++;
}
vector<int> vec_count_1 = getCount_2(strline_in, vec_right, vec_out_1);
int count_out_1_right = vec_count_1[0]; //切分正确的数量
int count_right = (int)vec_right.size(); //准确的切分数量
int count_out_1 = (int)vec_out_1.size(); //切分得到的数量
count_right_all += count_right;
count_out_1_all += count_out_1;
count_out_1_right_all += count_out_1_right;
}
double kk_1 = (double)count_out_1_right_all / count_out_1_all; //隐马尔科夫模型(二阶)准确率
double kk_2 = (double)count_out_1_right_all / count_right_all; //隐马尔科夫模型(二阶)召回率
double F1 = (double) 2.0*kk_1*kk_2/(kk_1+kk_2);
cout<< "隐马尔科夫模型(三阶)"<<endl;
cout<<"准确率:" << kk_1*100 << "%"<<endl;
cout<<"召回率:" << kk_2*100 << "%" << endl;
cout<<"F值:"<<F1<<endl;
return 0;
}
|
5dbd733edec50581b03a7af502fb96d49d4e388e
|
13a610314057a810a61e2a679dc88570f1214803
|
/src/LedPack/bassFilterShow.cpp
|
62669f1bb6d64e498a34c33e9a9b4417fd990443
|
[
"MIT"
] |
permissive
|
Robert1991/LedPack
|
9ecfcc8772deda72d768edd013855687b40d7fbf
|
df0737120f82b83d3eeda5ca23981af161dd3113
|
refs/heads/master
| 2022-12-13T17:14:54.402702
| 2020-09-27T14:06:28
| 2020-09-27T14:06:28
| 255,381,579
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 569
|
cpp
|
bassFilterShow.cpp
|
#include "bassfilterShow.h"
BassFilterShow::BassFilterShow(LedHeart *ledHeart, LowPassSampler *lowPassSampler, int lowPassFilterSamples = 25) {
this->ledHeart = ledHeart;
this->lowPassSampler = lowPassSampler;
this->lowPassFilterSamples = lowPassFilterSamples;
}
void BassFilterShow::executeIteration(int changeLightsThresHold) {
int lvl = lowPassSampler->read(lowPassFilterSamples);
float brightnessFactor = lvl / 1023.0;
if (lvl > changeLightsThresHold) {
ledHeart->turnOnRandomly(2);
}
ledHeart->toggleBrightness((brightnessFactor * 255));
}
|
64d6ed380d6c34e99868e6cde7c9c2c9d0230221
|
2160fd4cc5cb24bb8427ec78ef9b2d3a9549c2c5
|
/include/cyng/sys/filesystem.h
|
89e91fad7c3a686c993eabe2a9950d4bce99dc22
|
[
"MIT"
] |
permissive
|
solosTec/cyng
|
7e698487ef57f050fc2b3e287aa79463b2debc9f
|
a55fc9a7566254cb8e60a51b9884b40f19f866b9
|
refs/heads/master
| 2023-07-25T11:49:07.089159
| 2022-10-21T15:17:13
| 2022-10-21T15:17:13
| 115,027,279
| 0
| 2
|
MIT
| 2022-10-21T15:17:14
| 2017-12-21T16:46:54
|
C++
|
UTF-8
|
C++
| false
| false
| 415
|
h
|
filesystem.h
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2021 Sylko Olzscher
*
*/
#ifndef CYNG_SYS_FILESYSTEM_H
#define CYNG_SYS_FILESYSTEM_H
#include <filesystem>
#include <chrono>
namespace cyng {
namespace sys
{
/**
* To get the last write time is currently a mess with the STL.
* Waiting for C++20
*/
std::chrono::system_clock::time_point get_write_time(std::filesystem::path const& p);
}
}
#endif
|
a7963fc4ed1888b664f25af7c4dd5950855a3cfa
|
7c83c576b29c5b5d37124bc940eba482c97d6836
|
/projects/dump/rf95_router_server/rf95_router_server.ino
|
6dc869b628b239818cc6bc04eb75467f9b7d1703
|
[] |
no_license
|
royyandzakiy/LoRa-RHMesh
|
37a7f2153d0a91f41c7127ea46ec6f36b531bd07
|
5df9a9417af1acb4271237d86b30a2389c2f6d86
|
refs/heads/master
| 2023-07-31T10:24:47.655431
| 2023-07-17T16:42:24
| 2023-07-17T16:42:24
| 250,162,352
| 5
| 6
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,462
|
ino
|
rf95_router_server.ino
|
// rf95_router_client.pde
// -*- mode: C++ -*-
// Example sketch showing how to create a simple addressed, routed reliable messaging client
// with the RHRouter class.
// It is designed to work with the other examples rf95_router_server*
#include <RHRouter.h>
#include <RH_RF95.h>
#include <SPI.h>
// In this small artifical network of 4 nodes,
// messages are routed via intermediate nodes to their destination
// node. All nodes can act as routers
// CLIENT_ADDRESS <-> SERVER1_ADDRESS <-> SERVER2_ADDRESS<->SERVER3_ADDRESS
#define CLIENT_ADDRESS 1
#define SERVER1_ADDRESS 2
#define SERVER2_ADDRESS 3
#define SERVER3_ADDRESS 4
/*// Arduino
#define RFM95_CS 10
#define RFM95_RST 9
#define RFM95_INT 2 //*/
// ESP32
#define RFM95_CS 5
#define RFM95_RST 14
#define RFM95_INT 2 //*/
// Change to 434.0 or other frequency, must match RX's freq!
#define RF95_FREQ 915.0
// Singleton instance of the radio driver
RH_RF95 driver(RFM95_CS, RFM95_INT);
// Class to manage message delivery and receipt, using the driver declared above
RHRouter *manager;
int count = 0;
void setup()
{
Serial.begin(9600);
driver.setTxPower(23, false);
driver.setFrequency(RF95_FREQ);
driver.setCADTimeout(500);
manager = new RHRouter(driver, SERVER3_ADDRESS);
if (!manager->init())
Serial.println("init failed");
// Defaults after init are 434.0MHz, 0.05MHz AFC pull-in, modulation FSK_Rb2_4Fd36
// Manually define the routes for this network
// manager->addRouteTo(CLIENT_ADDRESS, CLIENT_ADDRESS);
manager->addRouteTo(CLIENT_ADDRESS, SERVER1_ADDRESS);
manager->addRouteTo(SERVER1_ADDRESS, SERVER1_ADDRESS);
// manager->addRouteTo(SERVER2_ADDRESS, SERVER2_ADDRESS);
// manager->addRouteTo(SERVER3_ADDRESS, SERVER2_ADDRESS);
Serial.println("Router Server " + (String) (SERVER3_ADDRESS-1) + ": Up and Running");
}
uint8_t data[] = "And hello back to you from server3";
// Dont put this on the stack:
uint8_t buf[RH_ROUTER_MAX_MESSAGE_LEN];
void loop()
{
uint8_t len = sizeof(buf);
uint8_t from;
if (manager->recvfromAck(buf, &len, &from))
{
Serial.print("got request from : 0x");
Serial.print(from, HEX);
Serial.print(": ");
Serial.println((char*)buf);
count++;
Serial.println("Count Recieved: " + (String) count + "/100");
// Send a reply back to the originator client
if (manager->sendtoWait(data, sizeof(data), from) != RH_ROUTER_ERROR_NONE)
Serial.println("sendtoWait failed");
}
}
|
b04de4843221151450b5331d73388503b4b2545c
|
a909df0ba2abf695df4a7d15350312d4c6463c48
|
/UVa/10446.cpp
|
257f00b2e265b42bc0623880e0085cebe4c68dca
|
[] |
no_license
|
SayaUrobuchi/uvachan
|
1dadd767a96bb02c7e9449c48e463847480e98ec
|
c213f5f3dcfc72376913a21f9abe72988a8127a1
|
refs/heads/master
| 2023-07-23T03:59:50.638063
| 2023-07-16T04:31:23
| 2023-07-16T04:31:23
| 94,064,326
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 523
|
cpp
|
10446.cpp
|
#include <stdio.h>
#include <string.h>
unsigned long long dp[61][61];
char chk[61][61];
unsigned long long trib(int n, int m)
{
int i;
if(n < 2)
{
return 1;
}
if(chk[n][m])
{
return dp[n][m];
}
dp[n][m] = chk[n][m] = 1;
for(i=1; i<=m; i++)
{
dp[n][m] += trib(n-i, m);
}
return dp[n][m];
}
int main()
{
int cas, n, m;
cas = 0;
while(scanf("%d%d", &n, &m) == 2)
{
if(n > 60 || m > 60)
{
break;
}
memset(chk, 0, sizeof(chk));
printf("Case %d: %llu\n", ++cas, trib(n, m));
}
return 0;
}
|
db4434dc41bd8cdd5c8aadb24abac994b221f055
|
4ffb20c0822d16cbaeafe65815a5d21cbfb747a0
|
/src/cpp/v7_cache_reuse/step.cpp
|
095c2c27e4f8d4f38ccf30811298d46bb6f89718
|
[
"MIT"
] |
permissive
|
WallyMirrors/parallel-rust-shortcut-comparison
|
dd2eaa4b715c0a5a6bcbf02971ea7f13e9cf92e0
|
d676483ef3f9e2fae6f975417bee7d7f5a3ea044
|
refs/heads/master
| 2023-03-19T13:31:03.500428
| 2020-03-23T15:04:09
| 2020-03-23T15:04:09
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,437
|
cpp
|
step.cpp
|
/*
* From http://ppc.cs.aalto.fi/ch2/v7/
*/
#include <algorithm>
#if !NO_MULTI_THREAD
#include <parallel/algorithm>
#endif
#include <vector>
#include <tuple>
#include "step.hpp"
#include "simd.hpp"
void step(float* r, const float* d_, int n) {
constexpr int cols_per_stripe = 500;
int na = (n + 8 - 1) / 8;
// Build a Z-order curve memory access pattern for vd and vt
std::vector<std::tuple<int,int,int>> rows(na*na);
#pragma omp parallel for
for (int ia = 0; ia < na; ++ia) {
for (int ja = 0; ja < na; ++ja) {
int ija = _pdep_u32(ia, 0x55555555) | _pdep_u32(ja, 0xAAAAAAAA);
rows[ia*na + ja] = std::make_tuple(ija, ia, ja);
}
}
#if !NO_MULTI_THREAD
__gnu_parallel::sort(rows.begin(), rows.end());
#else
std::sort(rows.begin(), rows.end());
#endif
// One stripe of rows and cols packed into float8_ts
float8_t* vd = float8_alloc(na*cols_per_stripe);
float8_t* vt = float8_alloc(na*cols_per_stripe);
// Partial results
float8_t* vr = float8_alloc(na*na*8);
for (int stripe = 0; stripe < n; stripe += cols_per_stripe) {
int stripe_end = std::min(n - stripe, cols_per_stripe);
// Load one row and column stripe from d
#pragma omp parallel for
for (int ja = 0; ja < na; ++ja) {
for (int id = 0; id < stripe_end; ++id) {
int t = cols_per_stripe * ja + id;
int i = stripe + id;
for (int jb = 0; jb < 8; ++jb) {
int j = ja * 8 + jb;
vd[t][jb] = j < n ? d_[n*j + i] : infty;
vt[t][jb] = j < n ? d_[n*i + j] : infty;
}
}
}
#pragma omp parallel for
for (int i = 0; i < na * na; ++i) {
// Get corresponding pair (x, y) for Z-order value ija
int ija, ia, ja;
std::tie(ija, ia, ja) = rows[i];
(void)ija;
// If we are not at column 0, then the partial results contain something useful, else the partial results are uninitialized
float8_t vv000 = stripe ? vr[8*i + 0] : f8infty;
float8_t vv001 = stripe ? vr[8*i + 1] : f8infty;
float8_t vv010 = stripe ? vr[8*i + 2] : f8infty;
float8_t vv011 = stripe ? vr[8*i + 3] : f8infty;
float8_t vv100 = stripe ? vr[8*i + 4] : f8infty;
float8_t vv101 = stripe ? vr[8*i + 5] : f8infty;
float8_t vv110 = stripe ? vr[8*i + 6] : f8infty;
float8_t vv111 = stripe ? vr[8*i + 7] : f8infty;
// Compute partial results for this column chunk
for (int k = 0; k < stripe_end; ++k) {
float8_t a000 = vd[cols_per_stripe*ia + k];
float8_t b000 = vt[cols_per_stripe*ja + k];
float8_t a100 = swap4(a000);
float8_t a010 = swap2(a000);
float8_t a110 = swap2(a100);
float8_t b001 = swap1(b000);
vv000 = min8(vv000, a000 + b000);
vv001 = min8(vv001, a000 + b001);
vv010 = min8(vv010, a010 + b000);
vv011 = min8(vv011, a010 + b001);
vv100 = min8(vv100, a100 + b000);
vv101 = min8(vv101, a100 + b001);
vv110 = min8(vv110, a110 + b000);
vv111 = min8(vv111, a110 + b001);
}
vr[8*i + 0] = vv000;
vr[8*i + 1] = vv001;
vr[8*i + 2] = vv010;
vr[8*i + 3] = vv011;
vr[8*i + 4] = vv100;
vr[8*i + 5] = vv101;
vr[8*i + 6] = vv110;
vr[8*i + 7] = vv111;
}
}
// Unpack final results from partial results
#pragma omp parallel for
for (int i = 0; i < na * na; ++i) {
int ija, ia, ja;
std::tie(ija, ia, ja) = rows[i];
(void)ija;
float8_t vv[8];
for (int kb = 0; kb < 8; ++kb) {
vv[kb] = vr[8*i + kb];
}
for (int kb = 1; kb < 8; kb += 2) {
vv[kb] = swap1(vv[kb]);
}
for (int jb = 0; jb < 8; ++jb) {
for (int ib = 0; ib < 8; ++ib) {
int i = ib + ia*8;
int j = jb + ja*8;
if (j < n && i < n) {
r[n*i + j] = vv[ib^jb][jb];
}
}
}
}
std::free(vd);
std::free(vt);
std::free(vr);
}
|
23326eb2a8c2576b36cb9c96250ac9351769e783
|
e511e2cc83b3050f95d0a7c66098e49bb730c1cc
|
/base/gfunc.cc
|
41443ce324ae21d988dda9ccab41e7325419a24d
|
[] |
no_license
|
masteranza/qprop
|
15b8ef400d0c9695beb73fed57b332dcb898cd0c
|
0bfa29fb18446d124e8a0e5376d497cd911d4d0e
|
refs/heads/master
| 2023-06-01T21:36:39.197024
| 2021-06-17T08:44:38
| 2021-06-17T08:44:38
| 331,671,250
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,242
|
cc
|
gfunc.cc
|
#include <gfunc.h>
void gfunc(wavefunction &psi_at_RI, wavefunction &d_psi_dr_at_RI,
double energy, wavefunction staticpot, fluid V_ee_0, double nuclear_charge, grid g, wavefunction wf, double R_surff)
{
long ell, i, m_index, m_limit, index, lmindex;
const long dimens = g.dimens();
const long rgridsize = g.ngps_x();
const double dr = g.delt_x();
const long ind_R = g.rindex(R_surff);
const cplxd two_over_3delta_r = (2. / 3. / dr, 0);
const cplxd one_over_12delta_r = (1. / 12. / dr, 0);
const cplxd j_eps(0.0, 0.0); // adds an effective window exp(-jeps t)
wavefunction psi(rgridsize);
wavefunction dir_psi(rgridsize);
wavefunction vec_pot(rgridsize);
wavefunction m2_wf(rgridsize);
wavefunction m2_dir_wf(rgridsize);
wavefunction a(rgridsize);
wavefunction b(rgridsize);
wavefunction c(rgridsize);
const double m2_b = -10.0 / 6.0;
const double d2_b = -2.0 / (dr * dr);
const double m2_a = -1.0 / 6.0;
const double d2_a = 1.0 / (dr * dr);
const double m2_c = m2_a;
const double d2_c = d2_a;
// *****Upper left corrections******
int modifiedcornerelements = 1;
const double d2_0 = -2.0 / (dr * dr) * (1.0 - (nuclear_charge * dr / (12.0 - 10.0 * nuclear_charge * dr)));
const double m2_0 = -2.0 * (1.0 + dr * dr / 12.0 * d2_0);
psi_at_RI.nullify();
d_psi_dr_at_RI.nullify();
for (ell = 0; ell < g.ngps_y(); ell++)
{
if (dimens == 34)
{
m_limit = 0;
}
else if (dimens == 44)
{
m_limit = ell;
}
else
{
cerr << "No such option implemented for qprop dim " << dimens << endl;
};
for (m_index = -m_limit; m_index <= m_limit; m_index++)
{
for (i = 0; i < rgridsize; i++)
{
index = g.index(i, ell, m_index, 0);
psi[i] = wf[index];
};
//Multiply M2 and wf;
m2_wf[0] = m2_b * psi[0] + m2_a * psi[1];
if ((ell == 0) && (modifiedcornerelements == 1))
m2_wf[0] = m2_0 * psi[0] + m2_a * psi[1];
for (i = 1; i < rgridsize - 1; i++)
m2_wf[i] = m2_c * psi[i - 1] +
m2_b * psi[i] + m2_a * psi[i + 1];
m2_wf[rgridsize - 1] = m2_c * psi[rgridsize - 2] + m2_b * psi[rgridsize - 1];
// Build up the first matrix
for (i = 0; i < rgridsize; i++)
{
index = g.index(i, ell, m_index, 0);
vec_pot[i] = staticpot[index] + V_ee_0[i] - energy - j_eps;
};
for (i = 0; i < rgridsize - 1; i++)
a[i] = d2_a + m2_a * vec_pot[i + 1];
for (i = 1; i < rgridsize; i++)
b[i] = d2_b + m2_b * vec_pot[i];
for (i = 1; i < rgridsize; i++)
c[i] = d2_c + m2_c * vec_pot[i - 1];
b[0] = d2_b + m2_b * vec_pot[0];
if ((ell == 0) && (modifiedcornerelements == 1))
b[0] = d2_0 + m2_0 * vec_pot[0];
// Solve the first matrix
psi.solve_du(a, b, c, m2_wf, rgridsize);
if (dimens == 34)
{
lmindex = ell;
}
else if (dimens == 44)
{
lmindex = ell * (ell + 1) + m_index;
}
else
{
cerr << "No such option implemented for qprop dim " << dimens << endl;
};
psi_at_RI[lmindex] = psi[ind_R];
for (i = 0; i < rgridsize; i++)
{
a[i] = 1. / 6.;
b[i] = 4. / 6.;
c[i] = 1. / 6.;
dir_psi[i] = (psi[i + 1] - psi[i - 1]) * 0.5 / dr;
};
double y = sqrt(3.0) - 2.;
dir_psi[0] = psi[1] * 0.5 / dr + psi[0] * 0.5 * y / dr;
dir_psi[rgridsize - 1] = -psi[rgridsize - 1] * 0.5 * y / dr - psi[rgridsize - 2] * 0.5 / dr;
b[0] = (4. + y) / 6.;
b[rgridsize - 1] = (4. + y) / 6.;
dir_psi.solve_du(a, b, c, dir_psi, rgridsize);
d_psi_dr_at_RI[lmindex] = dir_psi[ind_R];
};
};
};
|
0ffcdf11e30cc547a67bde12d39669eb56ebb692
|
6913518fb95063b60829bd2854619cfbee27a724
|
/Problem_Solving_Paradigms/Complete_Search/Iterative (One Loop, Linear Scan)/ecological_bin_packing.cpp
|
58e63f902aae847b6a65fd48b0bdd70d2089d7c8
|
[] |
no_license
|
sachinlomte2008/uva
|
44b75a2c64fbbca67350901b91fbcfa84c559615
|
bd0e28840b9cdc56ce346001e894c1d9bdd86864
|
refs/heads/master
| 2022-06-16T11:58:03.921025
| 2022-05-25T07:36:56
| 2022-05-25T07:36:56
| 97,311,004
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 810
|
cpp
|
ecological_bin_packing.cpp
|
//https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=640&page=show_problem&problem=38
#include <bits/stdc++.h>
using namespace std;
int main(){
int b1,g1,c1,b2,g2,c2,b3,g3,c3,a[6],min;
// while(scanf("%d%d%d%d%d%d%d%d%d",&b1,&g1,&c1,&b2,&g2,&c2,&b3,&g3,&c3)){
while(cin>>b1>>g1>>c1>>b2>>g2>>c2>>b3>>g3>>c3){
a[0]=b2+b3+g1+g2+c1+c3;
a[1]=b2+b3+g1+g3+c1+c2;
a[2]=b1+b3+g2+g3+c1+c2;
a[3]=b2+b1+g2+g3+c1+c3;
a[4]=b3+b1+g1+g2+c3+c2;
a[5]=b1+b2+g1+g3+c3+c2;
for(int i=0;i<6;i++){
if(i==0)min=a[0];
if(min>a[i])min=a[i];
}
if(min==a[0])cout<<"BCG ";
else if(min==a[1])cout<<"BGC ";
else if(min==a[2])cout<<"GBC ";
else if(min==a[3])cout<<"GCB ";
else if(min==a[4])cout<<"CBG ";
else if(min==a[5])cout<<"CGB ";
cout<<min<<endl;
}
return 0;
}
|
f0ec6e3dcf6311e3920b75c5977f5adbf441fb95
|
be2d2e1934c0ef07f8bd4e0f4aec3d5d5d109dd3
|
/src/fix_qbias.cpp
|
7a97f37ada9179c5d230cebb866f0c7f36a3932d
|
[
"MIT"
] |
permissive
|
luwei0917/GlpG_Nature_Communication
|
b4064b3feec8c99dbc28c97dac5267d598e34347
|
a7f4f8b526e633b158dc606050e8993d70734943
|
refs/heads/master
| 2020-04-01T02:42:27.788338
| 2018-10-12T18:29:17
| 2018-10-12T18:29:17
| 152,791,497
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 14,638
|
cpp
|
fix_qbias.cpp
|
/* ----------------------------------------------------------------------
Copyright (2010) Aram Davtyan and Garegin Papoian
Papoian's Group, University of Maryland at Collage Park
http://papoian.chem.umd.edu/
Last Update: 12/01/2010
------------------------------------------------------------------------- */
#include <math.h>
#include <string.h>
#include "fix_qbias.h"
#include "atom.h"
#include "atom_vec_awsemmd.h"
#include "timer.h"
#include "update.h"
#include "respa.h"
#include "error.h"
#include "output.h"
#include "group.h"
#include "domain.h"
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
using std::ifstream;
using namespace LAMMPS_NS;
using namespace FixConst;
/* ---------------------------------------------------------------------- */
inline void FixQBias::print_log(char *line)
{
if (screen) fprintf(screen, line);
if (logfile) fprintf(logfile, line);
}
FixQBias::FixQBias(LAMMPS *lmp, int narg, char **arg) :
Fix(lmp, narg, arg)
{
if (narg != 4) error->all(FLERR,"Illegal fix qbias command");
efile = fopen("energyQ.log", "w");
char eheader[] = "Step\tQBias\tVTotal\n";
fprintf(efile, "%s", eheader);
char force_file_name[] = "forcesQ.dat";
fout = fopen(force_file_name,"w");
scalar_flag = 1;
vector_flag = 1;
thermo_energy = 1;
size_vector = nEnergyTerms;
global_freq = 1;
extscalar = 1;
extvector = 1;
force_flag = 0;
n = (int)(group->count(igroup)+1e-12);
for (int i=0;i<nEnergyTerms;++i) energy[i] = 0.0;
allocated = false;
allocate();
qbias_flag = 0;
qbias_exp_flag = 0;
qobias_flag = 0;
qobias_exp_flag = 0;
epsilon = 1.0;
int i, j;
char varsection[30];
ifstream in(arg[3]);
if (!in) error->all(FLERR,"Coefficient file was not found!");
while (!in.eof()) {
in >> varsection;
if (strcmp(varsection, "[Epsilon]")==0) {
in >> epsilon;
} else if (strcmp(varsection, "[QBias]")==0) {
qbias_flag = 1;
print_log("QBias flag on\n");
in >> k_qbias;
in >> q0;
in >> l;
in >> sigma;
} else if (strcmp(varsection, "[QBias_Exp]")==0) {
qbias_exp_flag = 1;
print_log("QBias_Exp flag on\n");
in >> k_qbias;
in >> q0;
in >> l;
in >> sigma_exp;
} else if (strcmp(varsection, "[QOBias]")==0) {
qobias_flag = 1;
print_log("QOBias flag on\n");
in >> k_qbias;
in >> q0;
in >> l;
in >> sigma;
in >> cutoff;
} else if (strcmp(varsection, "[QOBias_Exp]")==0) {
qobias_exp_flag = 1;
print_log("QOBias_Exp flag on\n");
in >> k_qbias;
in >> q0;
in >> l;
in >> sigma_exp;
in >> cutoff;
}
varsection[0]='\0';
}
in.close();
print_log("\n");
ifstream in_rnative("rnative.dat");
if (!in_rnative) error->all(FLERR,"File rnative.dat can't be read");
for (i=0;i<n;++i)
for (j=0;j<n;++j)
in_rnative >> rN[i][j];
in_rnative.close();
// Minimal sequence separation
min_sep = 3;
if (qobias_flag || qobias_exp_flag) min_sep=4;
for (i=0;i<n;i++) sigma_sq[i] = Sigma(i)*Sigma(i);
x = atom->x;
f = atom->f;
image = atom->image;
prd[0] = domain->xprd;
prd[1] = domain->yprd;
prd[2] = domain->zprd;
half_prd[0] = prd[0]/2;
half_prd[1] = prd[1]/2;
half_prd[2] = prd[2]/2;
periodicity = domain->periodicity;
Step = 0;
sStep=0, eStep=0;
ifstream in_rs("record_steps");
in_rs >> sStep >> eStep;
in_rs.close();
}
/* ---------------------------------------------------------------------- */
FixQBias::~FixQBias()
{
if (allocated) {
for (int i=0;i<n;i++) {
delete [] r[i];
delete [] rN[i];
delete [] q[i];
delete [] xca[i];
}
delete [] r;
delete [] rN;
delete [] q;
delete [] alpha_carbons;
delete [] xca;
delete [] res_no;
delete [] res_info;
delete [] chain_no;
delete [] sigma_sq;
}
}
/* ---------------------------------------------------------------------- */
inline bool FixQBias::isFirst(int index)
{
if (res_no[index]==1) return true;
return false;
}
inline bool FixQBias::isLast(int index)
{
if (res_no[index]==n) return true;
return false;
}
int FixQBias::Tag(int index) {
if (index==-1) return -1;
return atom->tag[index];
}
inline void FixQBias::Construct_Computational_Arrays()
{
int *mask = atom->mask;
int nlocal = atom->nlocal;
int nall = atom->nlocal + atom->nghost;
int *mol_tag = atom->molecule;
int *res_tag = avec->residue;
int i, j, js;
// Creating index arrays for Alpha_Carbons
nn = 0;
int last = 0;
for (i = 0; i < n; ++i) {
int min = -1, jm = -1;
for (int j = 0; j < nall; ++j) {
if (i==0 && res_tag[j]<=0)
error->all(FLERR,"Residue index must be positive in fix qbias");
if ( (mask[j] & groupbit) && res_tag[j]>last ) {
if (res_tag[j]<min || min==-1) {
min = res_tag[j];
jm = j;
}
}
}
if (min==-1) break;
alpha_carbons[nn] = jm;
res_no[nn] = min;
last = min;
nn++;
}
int nMinNeighbours = 3;
int iLastLocal = -1;
int lastResNo = -1;
int lastResType = NONE;
int nlastType = 0;
// Checking sequance and marking residues
for (i = 0; i < nn; ++i) {
chain_no[i] = -1;
if (lastResNo!=-1 && lastResNo!=res_no[i]-1) {
if (lastResType==LOCAL && res_no[i]!=n)
error->all(FLERR,"Missing neighbor atoms in fix qbias (code: 001)");
if (lastResType==GHOST) {
if (iLastLocal!=-1 && i-nMinNeighbours<=iLastLocal)
error->all(FLERR,"Missing neighbor atoms in fix qbias (code: 002)");
}
iLastLocal = -1;
lastResNo = -1;
lastResType = NONE;
nlastType = 0;
}
if (alpha_carbons[i]!=-1) {
chain_no[i] = mol_tag[alpha_carbons[i]];
if (alpha_carbons[i]<nlocal) {
if ( lastResType==OFF || (lastResType==GHOST && nlastType<nMinNeighbours && nlastType!=res_no[i]-1) ) {
error->all(FLERR,"Missing neighbor atoms in fix qbias (code: 003)");
}
iLastLocal = i;
res_info[i] = LOCAL;
} else {
res_info[i] = GHOST;
}
} else res_info[i] = OFF;
if (lastResNo == res_no[i]) nlastType++; else nlastType = 0;
lastResNo = res_no[i];
lastResType = res_info[i];
}
if (lastResType==LOCAL && res_no[nn-1]!=n)
error->all(FLERR,"Missing neighbor atoms in fix qbias (code: 004)");
if (lastResType==GHOST) {
if (iLastLocal!=-1 && nn-nMinNeighbours<=iLastLocal)
error->all(FLERR,"Missing neighbor atoms in fix qbias (code: 005)");
}
}
void FixQBias::allocate()
{
r = new double*[n];
rN = new double*[n];
q = new double*[n];
sigma_sq = new double[n];
alpha_carbons = new int[n];
xca = new double*[n];
res_no = new int[n];
res_info = new int[n];
chain_no = new int[n];
for (int i = 0; i < n; ++i) {
r[i] = new double [n];
rN[i] = new double [n];
q[i] = new double [n];
xca[i] = new double [3];
}
allocated = true;
}
/* ---------------------------------------------------------------------- */
int FixQBias::setmask()
{
int mask = 0;
mask |= POST_FORCE;
mask |= THERMO_ENERGY;
mask |= POST_FORCE_RESPA;
mask |= MIN_POST_FORCE;
return mask;
}
/* ---------------------------------------------------------------------- */
void FixQBias::init()
{
avec = (AtomVecAWSEM *) atom->style_match("awsemmd");
if (!avec) error->all(FLERR,"Fix qbias requires atom style awsemmd");
if (strstr(update->integrate_style,"respa"))
nlevels_respa = ((Respa *) update->integrate)->nlevels;
}
/* ---------------------------------------------------------------------- */
void FixQBias::setup(int vflag)
{
if (strstr(update->integrate_style,"verlet"))
post_force(vflag);
else {
((Respa *) update->integrate)->copy_flevel_f(nlevels_respa-1);
post_force_respa(vflag,nlevels_respa-1,0);
((Respa *) update->integrate)->copy_f_flevel(nlevels_respa-1);
}
}
/* ---------------------------------------------------------------------- */
void FixQBias::min_setup(int vflag)
{
post_force(vflag);
}
/* ---------------------------------------------------------------------- */
inline double adotb(double *a, double *b)
{
return (a[0]*b[0] + a[1]*b[1] + a[2]*b[2]);
}
inline double cross(double *a, double *b, int index)
{
switch (index) {
case 0:
return a[1]*b[2] - a[2]*b[1];
case 1:
return a[2]*b[0] - a[0]*b[2];
case 2:
return a[0]*b[1] - a[1]*b[0];
}
return 0;
}
inline double atan2(double y, double x)
{
if (x==0) {
if (y>0) return M_PI_2;
else if (y<0) return -M_PI_2;
else return NULL;
} else {
return atan(y/x) + (x>0 ? 0 : (y>=0 ? M_PI : -M_PI) );
}
}
inline double FixQBias::PeriodicityCorrection(double d, int i)
{
if (!periodicity[i]) return d;
else return ( d > half_prd[i] ? d - prd[i] : (d < -half_prd[i] ? d + prd[i] : d) );
}
double FixQBias::Sigma(int sep)
{
if (qbias_exp_flag || qobias_exp_flag)
return pow(1+sep, sigma_exp);
return sigma;
}
void FixQBias::compute_qbias()
{
double qsum, a, dx[3], dr, dql1, dql;
double force, force1;
int i, j;
qsum = 0.0;
a = 0.0;
// a = 2.0/((n-2)*(n-3));
for (i=0;i<n;++i) {
for (j=i+min_sep;j<n;++j) {
if ( (qobias_flag || qobias_exp_flag) && rN[i][j]>=cutoff ) continue;
dx[0] = xca[i][0] - xca[j][0];
dx[1] = xca[i][1] - xca[j][1];
dx[2] = xca[i][2] - xca[j][2];
r[i][j] = sqrt(dx[0]*dx[0]+dx[1]*dx[1]+dx[2]*dx[2]);
dr = r[i][j] - rN[i][j];
q[i][j] = exp(-dr*dr/(2*sigma_sq[j-i]));
qsum += q[i][j];
a +=1.0;
}
}
qsum = qsum/a;
dql1 = pow(qsum-q0, l-1);
dql = dql1*(qsum-q0);
energy[ET_QBIAS] += 0.5*epsilon*k_qbias*dql;
force = epsilon*k_qbias*dql1*l/a;
for (i=0;i<n;++i) {
for (j=i+min_sep;j<n;++j) {
if ( (qobias_flag || qobias_exp_flag) && rN[i][j]>=cutoff ) continue;
dx[0] = xca[i][0] - xca[j][0];
dx[1] = xca[i][1] - xca[j][1];
dx[2] = xca[i][2] - xca[j][2];
dr = r[i][j] - rN[i][j];
force1 = force*q[i][j]*dr/r[i][j]/sigma_sq[j-i];
f[alpha_carbons[i]][0] -= -dx[0]*force1;
f[alpha_carbons[i]][1] -= -dx[1]*force1;
f[alpha_carbons[i]][2] -= -dx[2]*force1;
f[alpha_carbons[j]][0] -= dx[0]*force1;
f[alpha_carbons[j]][1] -= dx[1]*force1;
f[alpha_carbons[j]][2] -= dx[2]*force1;
}
}
}
void FixQBias::out_xyz_and_force(int coord)
{
// out.precision(12);
fprintf(fout, "%d\n", Step);
fprintf(fout, "%d%d\n", qbias_flag, qbias_exp_flag, qobias_flag, qobias_exp_flag);
fprintf(fout, "Number of atoms %d\n", n);
fprintf(fout, "Energy: %d\n\n", energy[ET_TOTAL]);
int index;
if (coord==1) {
fprintf(fout, "rca = {");
for (int i=0;i<nn;i++) {
index = alpha_carbons[i];
if (index!=-1) {
fprintf(fout, "{%.8f, %.8f, %.8f}", x[index][0], x[index][1], x[index][2]);
if (i!=nn-1) fprintf(fout, ",\n");
}
}
fprintf(fout, "};\n\n\n");
}
fprintf(fout, "fca = {");
for (int i=0;i<nn;i++) {
index = alpha_carbons[i];
if (index!=-1) {
fprintf(fout, "{%.8f, %.8f, %.8f}", f[index][0], f[index][1], f[index][2]);
if (i!=nn-1) fprintf(fout, ",\n");
}
}
fprintf(fout, "};\n\n\n\n");
}
void FixQBias::compute()
{
ntimestep = update->ntimestep;
Step++;
if(atom->nlocal==0) return;
Construct_Computational_Arrays();
x = atom->x;
f = atom->f;
image = atom->image;
int i, j, xbox, ybox, zbox;
int i_resno, j_resno;
for (int i=0;i<nEnergyTerms;++i) energy[i] = 0.0;
force_flag = 0;
for (i=0;i<nn;++i) {
// Calculating xca Ca atoms coordinates array
if ( (res_info[i]==LOCAL || res_info[i]==GHOST) ) {
if (domain->xperiodic) {
xbox = (image[alpha_carbons[i]] & 1023) - 512;
xca[i][0] = x[alpha_carbons[i]][0] + xbox*prd[0];
} else xca[i][0] = x[alpha_carbons[i]][0];
if (domain->yperiodic) {
ybox = (image[alpha_carbons[i]] >> 10 & 1023) - 512;
xca[i][1] = x[alpha_carbons[i]][1] + ybox*prd[1];
} else xca[i][1] = x[alpha_carbons[i]][1];
if (domain->zperiodic) {
zbox = (image[alpha_carbons[i]] >> 20) - 512;
xca[i][2] = x[alpha_carbons[i]][2] + zbox*prd[2];
} else xca[i][2] = x[alpha_carbons[i]][2];
}
}
double tmp, tmp2;
double tmp_time;
int me,nprocs;
MPI_Comm_rank(world,&me);
MPI_Comm_size(world,&nprocs);
if (Step>=sStep && Step<=eStep) {
fprintf(fout, "At Start %d:\n", nn);
out_xyz_and_force(1);
}
tmp = energy[ET_QBIAS];
if (qbias_flag || qbias_exp_flag || qobias_flag || qobias_exp_flag)
compute_qbias();
if ((qbias_flag || qbias_exp_flag || qobias_flag || qobias_exp_flag) && Step>=sStep && Step<=eStep) {
fprintf(fout, "Qbias %d:\n", nn);
fprintf(fout, "Qbias_Energy: %.12f\n", energy[ET_QBIAS]-tmp);
out_xyz_and_force();
}
if (Step>=sStep && Step<=eStep) {
fprintf(fout, "All:\n");
out_xyz_and_force(1);
fprintf(fout, "\n\n\n");
}
for (int i=1;i<nEnergyTerms;++i) energy[ET_TOTAL] += energy[i];
if (ntimestep%output->thermo_every==0) {
fprintf(efile, "%d ", ntimestep);
for (int i=1;i<nEnergyTerms;++i) fprintf(efile, "\t%.6f", energy[i]);
fprintf(efile, "\t%.6f\n", energy[ET_TOTAL]);
}
}
/* ---------------------------------------------------------------------- */
void FixQBias::post_force(int vflag)
{
compute();
}
/* ---------------------------------------------------------------------- */
void FixQBias::post_force_respa(int vflag, int ilevel, int iloop)
{
if (ilevel == nlevels_respa-1) post_force(vflag);
}
/* ---------------------------------------------------------------------- */
void FixQBias::min_post_force(int vflag)
{
post_force(vflag);
}
/* ----------------------------------------------------------------------
return total potential energy
------------------------------------------------------------------------- */
double FixQBias::compute_scalar()
{
// only sum across procs one time
if (force_flag == 0) {
MPI_Allreduce(energy,energy_all,nEnergyTerms,MPI_DOUBLE,MPI_SUM,world);
force_flag = 1;
}
return energy_all[ET_TOTAL];
}
/* ----------------------------------------------------------------------
return potential energies of terms computed in this fix
------------------------------------------------------------------------- */
double FixQBias::compute_vector(int nv)
{
// only sum across procs one time
if (force_flag == 0) {
MPI_Allreduce(energy,energy_all,nEnergyTerms,MPI_DOUBLE,MPI_SUM,world);
force_flag = 1;
}
return energy_all[nv+1];
}
|
afbe303bf8150ae2a8ac6a3bf5d260575e08c70b
|
4c48713719116ebe8c33ed0262aeaf770e8e6736
|
/Εργασία2/final/9378_9380_PartB/Player.h
|
24921ff98531abe0be88d77de2cef68432f5f7d5
|
[] |
no_license
|
Skapis9999/Object-oriented-programming-course
|
7da03f36ba7dee558a75e29ebeb394290b397a5b
|
0f347384d9c14ed93beacc8892d708b17b525942
|
refs/heads/main
| 2023-01-27T15:11:33.543539
| 2020-12-09T11:48:54
| 2020-12-09T11:48:54
| 319,938,493
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,695
|
h
|
Player.h
|
/* Μέρος Εργασίας των:
Ηλία Κωφοκώτσιου 9380 ikofokots@ece.auth.gr
Σκαπέτη Χρήστου 9378 skapetis@ece.auth.gr
*/
#ifndef PLAYER_H_INCLUDED
#define PLAYER_H_INCLUDED
#include <string>
using namespace std;
// Κλάση που καλύπτει τις ανάγκες των παικτών. Οι μεταβλητές της κλάσης αυτής είναι, κατά σειρά γραφής, το όνομα του παίκτη, το φύλο,
// η ηλικία, το επάγγελμα, η τεχνική κατάρτιση, η κούραση, η δημοφιλία, οι νίκες στους διαγωνισμούς καθώς και η ομάδα
class Player{
string name;
string gender;
unsigned int age;
string occupation;
float skill;
float fatigue;
float popularity;
unsigned int victories;
string team;
public:
// Δυο συναρτήσεις αρχικών συνθηκών, με και χωρίς παραμέτρους και η συνάρτηση τελικών συνθηκών της κλάσης
Player();
// Επειδή κάποια στοιχεία, όπως πχ η κούραση, έχουν πολύ συγκεκριμένες τιμές κατά την δημιουργία ενός παίκτη, η συνάρτηση αρχικών συνθηκών
// παίρνει ως ορίσματα μόνο το όνομα (n), το φύλο (g), την ηλικία (a), το επάγγελμα (o) και την ομάδα του παίκτη (t)
Player(string n, string g, unsigned int a, string o, string t);
~Player();
// Ακολουθούν όλες οι συναρτήσεις get/set για όλες τις μεταβλητές της κλάσης. Οι συναρτήσεις set παίρνουν ως όρισμα κάθε φορά την νέα τιμή
// της εκάστοτε μεταβλητής
string getName() {return name;};
void setName(string value) {name = value;};
string getGender() {return gender;};
void setGender(string value);
unsigned int getAge() {return age;};
void setAge (unsigned int value);
string getOccupation() {return occupation;};
void setOccupation(string value) {occupation = value;};
float getSkill() {return skill;};
void setSkill(float value);
float getFatigue() {return fatigue;};
void setFatigue(float value);
float getPopularity() {return popularity;};
void setPopularity(float value);
unsigned int getVictories() {return victories;};
void setVictories(unsigned int value);
string getTeam() {return team;};
void setTeam(string value);
// Μια συνάρτηση που εκτυπώνει όλα τα στοιχεία του παίκτη στην οθόνη
void printStats();
// Οι συναρτήσεις που περιγράφουν τις δυνατότητες του παίκτη, όπως αυτές αναγράφονται μέσα στο κείμενο της εκφώνησης. (βλ. Player.cpp)
void work();
void socialize();
void endOfWeekActivities();
void participateInCompetition(string type);
void receiveTrophy(string type);
};
#endif // PLAYER_H_INCLUDED
|
ce091d9a0654d1885769bb3afb2869fb401acd01
|
5cab06ca45252790696e2b263c28cd3af9b4dc81
|
/VersionInfoDlg.cpp
|
db7f3644e82e7d2845c1cc21e13259a79423115b
|
[] |
no_license
|
Gucchiy/PicStand2.00
|
d91d412949cef06566ea2a923aa66b279fa07659
|
a59b2bea0a0cef4c837c8e96522faf71bc3d4f11
|
refs/heads/master
| 2021-01-12T13:15:39.981694
| 2016-10-28T02:32:57
| 2016-10-28T02:32:57
| 72,166,683
| 0
| 0
| null | null | null | null |
SHIFT_JIS
|
C++
| false
| false
| 1,239
|
cpp
|
VersionInfoDlg.cpp
|
// VersionInfoDlg.cpp : インプリメンテーション ファイル
//
#include "stdafx.h"
#include "picstand.h"
#include "VersionInfoDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CVersionInfoDlg ダイアログ
CVersionInfoDlg::CVersionInfoDlg(CWnd* pParent /*=NULL*/)
: CDialog(CVersionInfoDlg::IDD, pParent)
{
//{{AFX_DATA_INIT(CVersionInfoDlg)
// メモ - ClassWizard はこの位置にマッピング用のマクロを追加または削除します。
//}}AFX_DATA_INIT
}
void CVersionInfoDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CVersionInfoDlg)
// メモ - ClassWizard はこの位置にマッピング用のマクロを追加または削除します。
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CVersionInfoDlg, CDialog)
//{{AFX_MSG_MAP(CVersionInfoDlg)
// メモ - ClassWizard はこの位置にマッピング用のマクロを追加または削除します。
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CVersionInfoDlg メッセージ ハンドラ
|
35467bb15b95141d9e8634235afe46924a22b753
|
587cdded2d93f1bae729ab1bb912378fc9b03cac
|
/fun_test.cpp
|
0381bfa19e82875cae1657dc2c67d02d82f3455c
|
[] |
no_license
|
ZychDev/Zak_Io_Project
|
d8460fcfd4dd09fcbe9d8d610a62b4e8a8e8af29
|
469d149bc395f05c1ab4edd8760052878e49628f
|
refs/heads/master
| 2023-05-09T00:24:49.288290
| 2021-01-27T19:02:56
| 2021-01-27T19:02:56
| 304,053,468
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,712
|
cpp
|
fun_test.cpp
|
#include<iostream>
#include<vector>
#include<map>
#include<list>
#include<string>
#include<gtest/gtest.h>
#include "search_func_nam.cpp"
#include "listing.cpp"
std::map<std::string, double> listing(std::string sciezka);
std::map<std::string, std::vector<std::string>> wyszukiwanie2(std::map<std::string, double> pliki);
bool te_same_wyniki(std::string sciezka2, std::map<std::string, double> x){
std::map<std::string, double> y=listing(sciezka2);
//std::map<std::string, std::vector<std::string>> y = wyszukiwanie2(sciezka2);
if(x == y){
return true;
}
else return false;
}
void wrong_path(std::string sciezka){
if(sciezka==" "){
std::cout<<"Wrong path"<<std::endl;
exit(-1);
}
}
TEST(szukanie_funkcji, czy_istnieje_funkcja){
std::map<std::string, double> x;
std::map<std::string, std::vector<std::string>> z = wyszukiwanie2(x);
z["EXPECT_EQ"];
z["FileExists"];
z["Graph"];
z["Save_File_Func"];
z["Save_File_n"];
z["Save_In_File_Files"];
z["Save_In_File_Func"];
z["Save_In_File_Namespac"];
z["TEST"];
z["czy"];
z["exec"];
z["fileExists"];
z["function_namespce_functions"];
z["listing"];
z["main"];
z["map_second_element_on_list_string"];
z["map_string_double_TO_string"];
z["pliki_fun"];
z["te_same_wyniki"];
z["wyszukiwanie"];
z["wyszukiwanie2"];
z["wyszukiwanie_name"];
z["wyszukiwanie_name_ciag"];
std::string sc = ".";
EXPECT_TRUE(te_same_wyniki(sc, z));
ASSERT_EXIT(wrong_path(" "), ::testing::ExitedWithCode(‑1), "Wrong path");
}
int main(int argc, char **argv){
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
f172ee8da99fb340f08e853c306a13b8f7feb629
|
7092fbff65f11dc2da7e6a0c1ea5e189eb6ad147
|
/readerswriters.cpp
|
90611d9bef80da636e44c88ee5034b7f7385aa28
|
[] |
no_license
|
singalkunal/sem4-OS
|
66339831e75fb190f37dd59196bcf7b0734c5094
|
840bd230d060e6ce181cc53c1b281d2b9f5d4c65
|
refs/heads/master
| 2022-09-15T12:40:25.642645
| 2020-05-31T21:47:31
| 2020-05-31T21:47:31
| 268,369,493
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,367
|
cpp
|
readerswriters.cpp
|
#include <iostream>
using namespace std;
#include<stdio.h>
#include<pthread.h>
#include<semaphore.h>
#include <unistd.h>
#include <time.h>
#include<cmath>
sem_t mutex, wrt;
int readcount;
int data;
void* reader(void*){
sem_wait(&mutex); //lock readcount
readcount++;
if(readcount == 1) //first reader (currently no reader is reading)
sem_wait(&wrt); //cs acquired by readers
sem_post(&mutex);
cout<<"Read data: "<<data<<endl;
sem_wait(&mutex);
readcount--;
if(readcount == 0)
sem_post(&wrt);
sem_post(&mutex);
sleep(2);
return NULL;
}
void* writer(void* arg){
int item;
item = (*(int*)arg);
sem_wait(&wrt);
//writing
data = item;
cout<<"Written: "<<data<<endl;
sem_post(&wrt);
sleep(2);
return NULL;
}
int main(){
//Initialization
sem_init(&mutex, 0, 1);
sem_init(&wrt, 0, 1);
readcount = 0;
pthread_t r1, r2, w1, w2;
int item = 10;
for(int i=0; i< 4; i++){
pthread_create(&w1, NULL, &writer, (void*)&item);
// pthread_create(&w2, NULL, &writer, (void*)&item);
pthread_create(&r1, NULL, &reader, NULL);
pthread_create(&r2, NULL, &reader, NULL);
pthread_join(w1, NULL);
// pthread_join(w2, NULL);
pthread_join(r1, NULL);
pthread_join(r2, NULL);
}
}
|
495948e3e2dcae69a5515f893b3eb7dd211949cd
|
5b9add05f5630207728aa9fa92df40d0f624188c
|
/Castleforce/Source/Castleforce/Castleforce.cpp
|
5863609db55eb5643f90bd480798e02c50d4a69d
|
[] |
no_license
|
rh27un/castleforce
|
ff6bdb2f3719bee2e3d23b8c12084fa0f1ef5ad2
|
a1f70316e3876bfe2812f720fff4969ce83a1f3f
|
refs/heads/master
| 2021-10-26T10:55:05.166505
| 2019-02-08T13:33:25
| 2019-02-08T13:33:25
| 168,685,731
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 212
|
cpp
|
Castleforce.cpp
|
// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved.
#include "Castleforce.h"
#include "Modules/ModuleManager.h"
IMPLEMENT_PRIMARY_GAME_MODULE(FDefaultGameModuleImpl, Castleforce, "Castleforce");
|
ed505df0c55f0fda1f9013303137b474ed547a36
|
f588635240479cb0411e1514e006dfccc2002d2e
|
/Classes/common/CommonMacros.hpp
|
420df8e052201117bd649f6a2631bf63ae82f07e
|
[] |
no_license
|
youssefmyh/ThreadPoolcommandObserver
|
fe9459063bf73d7b0e10f4fcb5a358cf5c6af004
|
0aaeafd4713d7a82811222e7595812bfe188cd14
|
refs/heads/master
| 2023-02-27T12:54:37.712225
| 2021-02-09T10:26:05
| 2021-02-09T10:26:05
| 253,470,981
| 3
| 2
| null | 2020-09-13T10:55:18
| 2020-04-06T10:58:53
|
C++
|
UTF-8
|
C++
| false
| false
| 1,004
|
hpp
|
CommonMacros.hpp
|
//
// CommonMacros.hpp
// myGame
//
// Created by Youssef Hanna on 9/17/19.
//
#ifndef CommonMacros_hpp
#define CommonMacros_hpp
#include <stdio.h>
/*
Create A Macro to generate a getter and setter
*/
#define CREATE_SYNTHESIS_RETAIN_GENERAL(varType, varName, funName,protecion) \
private: varType varName; \
protecion: void set##funName(varType varName) \
{ \
if(this->varName != varName){ \
this->varName = varName; \
} \
} \
protecion: varType get##funName () const { return this->varName;}
/*
Create A Macro to generate a getter and setter with different protections
*/
#define CREATE_SYNTHISIS_PRIVATE(varType, varName, funName) CREATE_SYNTHESIS_RETAIN_GENERAL(varType, varName, funName,private)
#define CREATE_SYNTHISIS_PUBLIC(varType, varName, funName) CREATE_SYNTHESIS_RETAIN_GENERAL(varType, varName, funName,public)
#define CREATE_SYNTHISIS_PROTECTED(varType, varName, funName) CREATE_SYNTHESIS_RETAIN_GENERAL(varType, varName, funName,protected)
#endif /* CommonMacros_hpp */
|
69abc19a95a17afc44d5487d255f8f7d76d6fd2d
|
843ff84bebaf929c1ac03c7e96c17b535c3952f8
|
/shader/simpleshadowshader.h
|
202afcc70659fc33ff258874d27eedb697e13b52
|
[
"MIT"
] |
permissive
|
navythenerd/raytracer
|
f65fbc24aa0ebdb52914b64febaa7ebd795e8bfc
|
8f26466d64e1d07aad5a1a63d04da425f38e151b
|
refs/heads/master
| 2023-06-20T04:48:51.607044
| 2017-10-04T22:02:22
| 2017-10-04T22:02:22
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 310
|
h
|
simpleshadowshader.h
|
#ifndef SIMPLESHADOWSHADER_H
#define SIMPLESHADOWSHADER_H
#include "shader/shader.h"
class SimpleShadowShader : public Shader {
public:
// Constructor
SimpleShadowShader(Color const& objectColor);
// Shader functions
virtual Color shade(Ray * ray) const;
private:
Color objectColor;
};
#endif
|
895f5d03c0bc4cfe9eb69f4d1e3e1d9825b112ff
|
07effd83737bf8a5576b6e57b85e2ad8d47017da
|
/include/libexample/libexample.h
|
a1a7160093f2fd6c8e48891b823ae911c1909faf
|
[
"MIT"
] |
permissive
|
kuntalghosh/cpp-basic-libs
|
e1a7cff3480dc8f7ca4472b30005c0f5360579d2
|
fbd0eef8fdc86dfab1f8b3d7d3e3fbb77e27388d
|
refs/heads/master
| 2022-06-06T22:11:15.026731
| 2020-04-29T09:17:41
| 2020-05-01T15:24:47
| 260,487,163
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 238
|
h
|
libexample.h
|
#pragma once
/* This is a simple library interface. */
namespace PROJECT_NAMESPACE {
template <typename T>
class MyClass {
T a;
public:
void initialize(T a_val) {
a = a_val;
}
T get_initialized_value() {
return a;
}
};
}
|
5b835e5121f66d12fc13ab9ed3bc9119b26b77b4
|
113854f799ea342b2b2986d40256c9164b5759b4
|
/E.设计模式/13.组合模式/C++/Component.h
|
f011fff88652f0a5eb0e95156905fd058ed12ee3
|
[
"Apache-2.0"
] |
permissive
|
isshe/coding-life
|
5710ad135bf91ab9c6caf2f29a91215f03bba120
|
f93ecaee587474446d51a0be6bce54176292fd97
|
refs/heads/master
| 2023-08-31T20:43:23.967162
| 2023-08-30T22:00:02
| 2023-08-30T22:00:02
| 147,092,799
| 8
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 159
|
h
|
Component.h
|
#ifndef _COMPONENT_H_
#define _COMPONENT_H_
class Component {
public:
virtual void add(Component *component) = 0;
virtual void print() = 0;
};
#endif
|
cc5ab686927266e73655ea2b6d7ef424a605e1e5
|
8247c3aaf5ea08ffd9be526988f9420bdba7bfb5
|
/1759_solveThecipher_again/1759_Solve_The_Cipher_functions.cpp
|
9bced90a92dc397d67f2e9792a074d3d347dd9be
|
[] |
no_license
|
BlueWhale1017/BAEKJOONALGORITHM
|
b26db1776efec5f02299d65ff5e3f1deed5318a9
|
0f2364057afae9bd620203e515727f052aec1492
|
refs/heads/master
| 2023-09-05T10:28:14.564338
| 2021-11-19T18:02:24
| 2021-11-19T18:02:24
| 290,677,328
| 0
| 0
| null | null | null | null |
UHC
|
C++
| false
| false
| 972
|
cpp
|
1759_Solve_The_Cipher_functions.cpp
|
#include "1759_Solve_The_Cipher.h"
void Input() {
cin >> L >> C; //C는 문자 종류의 개수, L은 단어의 총 길이.
for (int i = 0; i < C; i++) {
char x = 0;
cin >> x;
words.push_back(x);
check.push_back(1);
}
}
void Cipher() {
do {
string s = "";
for (int i = 0; i < C; i++) {
if (check[i] == 0) {
s = s + words[i];//처음에 sort로 정렬을 해 주었고, 그 이후로 next_permutation 함수로 작은 수부터 차례로 올라가기에 규칙을 만족함.
}
}
int mouem = 0;
int jauem = 0;
for (int i = 0; i < s.size(); i++) {
if (s[i] == 'a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'o' || s[i] == 'u') {//모음일경우.
mouem += 1;
}
else {
jauem += 1;
}
}
if (mouem < 1 || jauem < 2) {
continue;
}
cout << s << '\n';
} while (next_permutation(check.begin(), check.end()));//0과 1 밖에 없기에 순열이지만 조합처럼 작용.
}
|
2dd3e2ee912bbae2f5d353007a4bd5eb052d31f5
|
a212bf19c79c4b7f89cca9388cf6809b081f3ebc
|
/js_transcriptor.cpp
|
04d1a92207e5b0b24783e3d71cfd95486ef144e5
|
[] |
no_license
|
r0ller/alice
|
96df1358f2d9ed819c6b66a25348b4f07d186fc4
|
43896ee0893a37b68fcce12af9340c2cc9331d7b
|
refs/heads/master
| 2023-07-26T05:35:24.460082
| 2023-06-06T15:58:57
| 2023-06-06T15:58:57
| 1,894,416
| 8
| 1
| null | 2023-09-14T09:08:58
| 2011-06-14T13:33:31
|
C++
|
UTF-8
|
C++
| false
| false
| 4,834
|
cpp
|
js_transcriptor.cpp
|
#include "js_transcriptor.h"
js_transcriptor::js_transcriptor(const char *analyses):transcriptor(analyses){
}
js_transcriptor::~js_transcriptor(){
logger::singleton()==NULL?(void)0:logger::singleton()->log(3,"destructing js transcriptor");
}
std::string js_transcriptor::args_to_jsfun_arglist(std::vector<std::string>& arguments){
std::string arglist;
for(auto&& i:arguments){
arglist+=i+",";
}
if(arglist.empty()==false) arglist.pop_back();
return arglist;
}
std::string js_transcriptor::args_to_jsfun_pmlist(std::vector<std::string>& arguments){
std::string arglist;
for(auto&& i:arguments){
arglist+="'"+i+"',";
}
if(arglist.empty()==false) arglist.pop_back();
arglist="["+arglist+"]";
return arglist;
}
std::string js_transcriptor::transcribeDependencies(rapidjson::Value& morphology,rapidjson::Value& syntax,rapidjson::Value& dependencies,rapidjson::Value& functors,std::vector<std::string>& argList,bool first_call){
std::string script;
std::vector<std::string> arguments;
for(unsigned int i=0;i<dependencies.Size();++i){
rapidjson::Value& dependency=dependencies[i];
std::string functorID;
if(dependency.HasMember("functor id")==true){
functorID=dependency["functor id"].GetString();
}
if(functorID.empty()==true){
functorID=dependency["functor"].GetString();
}
std::string dependencyID=dependency["id"].GetString();
std::string functionName=functorID+"_"+dependencyID;
std::string argument=functionName+"_out";
argList.push_back(argument);
if(dependency.HasMember("dependencies")==true){
script+=transcribeDependencies(morphology,syntax,dependency["dependencies"],functors,arguments);
}
std::string morphologyArg;
if(dependency.HasMember("morpheme id")==true){
std::string morphemeID=dependency["morpheme id"].GetString();
for(unsigned int j=0;j<morphology.Size();++j){
rapidjson::Value& morphologyObj=morphology[j];
if(morphologyObj["morpheme id"].GetString()==morphemeID){
morphologyArg=value_to_string(morphologyObj);
find_replace(morphologyArg,"\"","\\\"");
break;
}
}
}
std::string morphologyVarName=functionName+"_morphology";
arguments.push_back(morphologyVarName);
std::string tags;
std::string tagsVarName;
if(dependency.HasMember("tags")==true){
for(auto& tag: dependency["tags"].GetObject()){
std::string tag_quoted="\""+std::string(tag.name.GetString())+"\":\""+std::string(tag.value.GetString())+"\",";
//quoting here is necessary for js
find_replace(tag_quoted,"\"","\\\"");
tags+=tag_quoted;
}
if(tags.empty()==false){
tags.pop_back();
tags="{"+tags+"}";
tagsVarName=functionName+"_tags";
arguments.push_back(tagsVarName);
}
}
std::string argStr=args_to_jsfun_arglist(arguments);
std::string parameterList=args_to_jsfun_pmlist(arguments);
std::string functorDef;
for(unsigned int j=0;j<functors.Size();++j){
rapidjson::Value& functor=functors[j];
if(functor["functor id"].GetString()==functorID){
functorDef=functor["definition"].GetString();
if(functorDef.empty()==false){
functorDef = "function " + functionName + "(functionName,parameterList," + argStr + "){" + functorDef + "};";
}
break;
}
}
if(functorDef.empty()==true){
//TODO:if functor has no definition but has dependencies, propagate the outgoing result of its dependencies to the parent.
//However, if there are more than one functor having no definition it'll be necessary to pass on which is the last
//functor that has a definition in order that the arguments are propagated to the right level.
script+=functionName+"_out="+"\""+morphologyArg+"\";";
}
else{
script+=morphologyVarName+"="+"\""+morphologyArg+"\";";
if(tags.empty()==false) script+=tagsVarName+"="+"\""+tags+"\";";
if(first_call==true){
script+=functorDef+"return "+functionName+"_out="+functionName+"('"+functionName+"',"+parameterList+","+argStr+");";
}
else{
script+=functorDef+functionName+"_out="+functionName+"('"+functionName+"',"+parameterList+","+argStr+");";
}
}
arguments.clear();
}
return script;
}
|
428fff910d004764cdd0375ae74dd791fc79b514
|
1e6726c14ac01a0f01cde2c714157a377c9393d1
|
/lidar-esp/src/controller/network/OscController.h
|
80f8b73eb6d33297f0c2c837920753f5fdf06bb7
|
[
"MIT"
] |
permissive
|
cansik/sweep-3d-lidar
|
b858aebd2fd10e92deee642cbaacb6bd1ffbb8c4
|
38434908c32a6835aae419e08f447fb090debc76
|
refs/heads/master
| 2021-07-17T07:14:55.373690
| 2018-11-04T22:25:36
| 2018-11-04T22:25:36
| 133,274,213
| 6
| 1
| null | 2018-08-15T11:45:48
| 2018-05-13T21:04:08
|
C#
|
UTF-8
|
C++
| false
| false
| 1,075
|
h
|
OscController.h
|
//
// Created by Florian on 27.11.17.
//
#ifndef SILVA_OSCCONTROLLER_H
#define SILVA_OSCCONTROLLER_H
#include <controller/BaseController.h>
#include <cstdint>
#include <IPAddress.h>
#include <OSCMessage.h>
#include <WiFiUdp.h>
// exclude min and max
#undef max
#undef min
#include <functional>
#define CHAR_BUFFER_SIZE 16
class OscController : public BaseController {
private:
typedef std::function<void(OSCMessage &msg)> OSCHandlerFunction;
const IPAddress broadcastIP = IPAddress(255, 255, 255, 255);
uint16_t inPort;
uint16_t outPort;
WiFiUDP Udp;
OSCHandlerFunction onMessageReceivedCallback;
void routeOSCMessage(OSCMessage &msg);
public:
OscController(uint16_t inPort, uint16_t outPort);
void setup() override;
void loop() override;
void sendMessage(OSCMessage &msg);
void onMessageReceived(OSCHandlerFunction handler);
void send(const char *route, const char *value);
void send(const char *route, int value);
void send(const char *route, float value);
};
#endif //SILVA_OSCCONTROLLER_H
|
f0bac64ed86da23ca0b46b05f0731ddf91340e65
|
51635c1a1135b979b47e4fc35fdf2b5421192d96
|
/lava/framework/core/graphicspipeline.cpp
|
5eb344feda2e4e4ee4780ee5e3c257a8f4eebb28
|
[
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
BalderOdinson/LavaVk
|
4b980166f44945e62b0f401d4da8e8ce94cf316a
|
f3241e1077bbfc8bbf14267d35e9c72272fceefa
|
refs/heads/master
| 2020-12-15T16:50:08.354426
| 2020-01-24T05:09:57
| 2020-01-24T05:09:57
| 235,183,993
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 8,400
|
cpp
|
graphicspipeline.cpp
|
//
// Created by dorian on 13. 12. 2019..
//
#include "graphicspipeline.h"
#include "options/pipelineoptions.h"
LavaVk::Core::GraphicsPipeline::GraphicsPipeline(LavaVk::InjectionContext &context) : Pipeline(context)
{
auto options = context.container.option<PipelineOptions>(context);
std::vector<ShaderModule::Module> shaderModules;
std::vector<vk::PipelineShaderStageCreateInfo> stageCreateInfos;
// Create specialization info from tracked state. This is shared by all shaders.
std::vector<uint8_t> data{};
std::vector<vk::SpecializationMapEntry> mapEntries{};
const auto specializationConstantState = options->state.getSpecializationConstantState().getSpecializationConstantState();
for (const auto &specializationConstant : specializationConstantState)
{
mapEntries.emplace_back(specializationConstant.first, static_cast<uint32_t >(data.size()),
specializationConstant.second.size());
data.insert(data.end(), specializationConstant.second.begin(), specializationConstant.second.end());
}
vk::SpecializationInfo specializationInfo{};
specializationInfo.mapEntryCount = static_cast<uint32_t>(mapEntries.size());
specializationInfo.pMapEntries = mapEntries.data();
specializationInfo.dataSize = data.size();
specializationInfo.pData = data.data();
for (auto &shaderModule : options->state.getPipelineLayout()->getStages())
{
vk::PipelineShaderStageCreateInfo stageCreateInfo{};
stageCreateInfo.stage = shaderModule->getStage();
stageCreateInfo.pName = shaderModule->getEntryPoint().c_str();
// Create the Vulkan handle
shaderModules.emplace_back(shaderModule->getModule());
stageCreateInfo.module = shaderModules.back().getHandle();
stageCreateInfo.pSpecializationInfo = &specializationInfo;
stageCreateInfos.push_back(stageCreateInfo);
}
vk::GraphicsPipelineCreateInfo createInfo{};
createInfo.stageCount = static_cast<uint32_t>(stageCreateInfos.size());
createInfo.pStages = stageCreateInfos.data();
vk::PipelineVertexInputStateCreateInfo vertexInputState{};
vertexInputState.pVertexAttributeDescriptions = options->state.getVertexInputState().attributes.data();
vertexInputState.vertexAttributeDescriptionCount = static_cast<uint32_t>(
options->state.getVertexInputState().attributes.size());
vertexInputState.pVertexBindingDescriptions = options->state.getVertexInputState().bindings.data();
vertexInputState.vertexBindingDescriptionCount = static_cast<uint32_t>(options->state.getVertexInputState().bindings.size());
vk::PipelineInputAssemblyStateCreateInfo inputAssemblyState{};
inputAssemblyState.topology = options->state.getInputAssemblyState().topology;
inputAssemblyState.primitiveRestartEnable = options->state.getInputAssemblyState().primitiveRestartEnable;
vk::PipelineViewportStateCreateInfo viewportState{};
viewportState.viewportCount = options->state.getViewportState().viewportCount;
viewportState.scissorCount = options->state.getViewportState().scissorCount;
vk::PipelineRasterizationStateCreateInfo rasterizationState{};
rasterizationState.depthClampEnable = options->state.getRasterizationState().depthClampEnable;
rasterizationState.rasterizerDiscardEnable = options->state.getRasterizationState().rasterizerDiscardEnable;
rasterizationState.polygonMode = options->state.getRasterizationState().polygonMode;
rasterizationState.cullMode = options->state.getRasterizationState().cullMode;
rasterizationState.frontFace = options->state.getRasterizationState().frontFace;
rasterizationState.depthBiasEnable = options->state.getRasterizationState().depthBiasEnable;
rasterizationState.depthBiasClamp = 1.0f;
rasterizationState.depthBiasSlopeFactor = 1.0f;
rasterizationState.lineWidth = 1.0f;
vk::PipelineMultisampleStateCreateInfo multisampleState{};
multisampleState.sampleShadingEnable = options->state.getMultisampleState().sampleShadingEnable;
multisampleState.rasterizationSamples = options->state.getMultisampleState().rasterizationSamples;
multisampleState.minSampleShading = options->state.getMultisampleState().minSampleShading;
multisampleState.alphaToCoverageEnable = options->state.getMultisampleState().alphaToCoverageEnable;
multisampleState.alphaToOneEnable = options->state.getMultisampleState().alphaToOneEnable;
if (options->state.getMultisampleState().sampleMask)
multisampleState.pSampleMask = &options->state.getMultisampleState().sampleMask;
vk::PipelineDepthStencilStateCreateInfo depthStencilState{};
depthStencilState.depthTestEnable = options->state.getDepthStencilState().depthTestEnable;
depthStencilState.depthWriteEnable = options->state.getDepthStencilState().depthWriteEnable;
depthStencilState.depthCompareOp = options->state.getDepthStencilState().depthCompareOp;
depthStencilState.depthBoundsTestEnable = options->state.getDepthStencilState().depthBoundsTestEnable;
depthStencilState.stencilTestEnable = options->state.getDepthStencilState().stencilTestEnable;
depthStencilState.front.failOp = options->state.getDepthStencilState().front.failOp;
depthStencilState.front.passOp = options->state.getDepthStencilState().front.passOp;
depthStencilState.front.depthFailOp = options->state.getDepthStencilState().front.depthFailOp;
depthStencilState.front.compareOp = options->state.getDepthStencilState().front.compareOp;
depthStencilState.front.compareMask = ~0U;
depthStencilState.front.writeMask = ~0U;
depthStencilState.front.reference = ~0U;
depthStencilState.back.failOp = options->state.getDepthStencilState().back.failOp;
depthStencilState.back.passOp = options->state.getDepthStencilState().back.passOp;
depthStencilState.back.depthFailOp = options->state.getDepthStencilState().back.depthFailOp;
depthStencilState.back.compareOp = options->state.getDepthStencilState().back.compareOp;
depthStencilState.back.compareMask = ~0U;
depthStencilState.back.writeMask = ~0U;
depthStencilState.back.reference = ~0U;
vk::PipelineColorBlendStateCreateInfo colorBlendState{};
colorBlendState.logicOpEnable = options->state.getColorBlendState().logicOpEnable;
colorBlendState.logicOp = options->state.getColorBlendState().logicOp;
colorBlendState.attachmentCount = static_cast<uint32_t>(options->state.getColorBlendState().attachments.size());
colorBlendState.pAttachments = reinterpret_cast<const vk::PipelineColorBlendAttachmentState *>(options->state.getColorBlendState().attachments.data());
colorBlendState.blendConstants[0] = 1.0f;
colorBlendState.blendConstants[1] = 1.0f;
colorBlendState.blendConstants[2] = 1.0f;
colorBlendState.blendConstants[3] = 1.0f;
std::array<vk::DynamicState, 9> dynamicStates{
vk::DynamicState::eViewport,
vk::DynamicState::eScissor,
vk::DynamicState::eLineWidth,
vk::DynamicState::eDepthBias,
vk::DynamicState::eBlendConstants,
vk::DynamicState::eDepthBounds,
vk::DynamicState::eStencilCompareMask,
vk::DynamicState::eStencilWriteMask,
vk::DynamicState::eStencilReference,
};
vk::PipelineDynamicStateCreateInfo dynamicState{};
dynamicState.pDynamicStates = dynamicStates.data();
dynamicState.dynamicStateCount = static_cast<uint32_t>(dynamicStates.size());
createInfo.pVertexInputState = &vertexInputState;
createInfo.pInputAssemblyState = &inputAssemblyState;
createInfo.pViewportState = &viewportState;
createInfo.pRasterizationState = &rasterizationState;
createInfo.pMultisampleState = &multisampleState;
createInfo.pDepthStencilState = &depthStencilState;
createInfo.pColorBlendState = &colorBlendState;
createInfo.pDynamicState = &dynamicState;
createInfo.layout = options->state.getPipelineLayout()->getHandle();
createInfo.renderPass = options->state.getRenderPass()->getHandle();
createInfo.subpass = options->state.getSubpassIndex();
handle = device->getHandle().createGraphicsPipeline(options->cache, createInfo);
state = options->state;
}
std::type_index LavaVk::Core::GraphicsPipeline::getType() const
{
return typeid(GraphicsPipeline);
}
|
5a80613d7e665054ced3929485d7b945a9f973bc
|
b94a823ad86403049f7e36897b3f6602446ecac6
|
/Algorithm/2020/weekly_vitaalgo/mon_04/0403_01.cpp
|
1c52f8083c1a4391c53539af9ef922cfb52c0567
|
[] |
no_license
|
sos0911/PS_Cpluslplus
|
2807880e82942e8ad1971fb8ce2bbd940845fb15
|
c4ba30ef5112f2fb4369183dc263aec560949f8e
|
refs/heads/master
| 2021-07-17T14:38:01.320237
| 2021-07-15T15:44:18
| 2021-07-15T15:44:18
| 240,442,891
| 1
| 0
| null | null | null | null |
UHC
|
C++
| false
| false
| 1,122
|
cpp
|
0403_01.cpp
|
// string을 쓰는 일반 문제풀이용 템플릿
#include <bits/stdc++.h>
using namespace std;
int main() {
cin.tie(NULL);
ios_base::sync_with_stdio(false);
string input;
cin >> input;
int len = input.size();
int n;
cin >> n;
// dp[i][j] : 길이가 i고 중심점이 j일때 이게 회문인가?
// 길이가 짝수, 홀수일때 구분
bool dp[1001][1001] = { false, };
// 길이 1,2 precal
for (int j = 0; j < len; j++)
dp[1][j] = true;
for (int i = 0; i < len - 1; i++)
if (input[i] == input[i + 1])
dp[2][i] = true;
for (int i = 3; i < len; i++) {
if (i % 2) {
for (int j = 0; j < len; j++) {
if (i - 2 >= 1 && dp[i - 2][j] && j - i / 2 >= 0 && j + i / 2 < len && input[j - i / 2] == input[j + i / 2]) {
dp[i][j] = true;
}
}
}
else {
for (int j = 0; j < len; j++) {
if (i - 2 >= 1 && dp[i - 2][j] && j - i / 2 + 1 >= 0 && j + i / 2 < len && input[j - i / 2 + 1] == input[j + i / 2]) {
dp[i][j] = true;
}
}
}
}
for (int i = 0; i < n; i++) {
int s, e;
cin >> s >> e;
s--; e--;
cout << dp[e - s + 1][(e + s) / 2] << '\n';
}
return 0;
}
|
ffc6c2e060834f88a6dfcfea0fb5a2163f860cfe
|
52d9fea5825f0f9211f85d7caecbe7ef151bdf78
|
/include/defence.h
|
a8efbc1c365f5f892060dacd9430e966cf10939a
|
[] |
no_license
|
Lapulatos/Intercept-Simulation
|
3b8857c6147d504b828807cc09d6454b14bcc335
|
ca03eb8c16708855328a4e08717e9f526662c3c4
|
refs/heads/master
| 2021-05-13T21:32:33.199403
| 2018-02-26T02:25:58
| 2018-02-26T02:25:58
| 116,464,867
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,463
|
h
|
defence.h
|
#ifndef DEFENCE_INCLUDED
#define DEFENCE_INCLUDED
#include "miliobj.h"
#include "target.h"
#include "bomber.h"
#include "missile.h"
namespace Simu
{
////////////////////////////////////
// 防守方的定义
////////////////////////////////////
// 前向声明导弹类
class Missile;
typedef std::shared_ptr<Simu::Missile> MissileHolder; // 自动释放实例资源
typedef std::vector<Simu::Missile*> MissileList; // 导弹指针表[提高程序运行效率]
typedef std::vector<Simu::MissileHolder> MissileHolderList; // 导弹实例表[存储具体实例]
// 前向声明军事目标
class Target;
typedef std::shared_ptr<Simu::Target> TargetHolder; // 自动释放实例资源
typedef std::vector<Simu::Target*> TargetList; // 守方指针列表[提高程序运行效率]
typedef std::vector<Simu::TargetHolder> TargetHolderList; // 守方实例列表
// 前向声明轰炸机
class Bomber;
typedef std::shared_ptr<Simu::Bomber> BomberHolder; // 自动释放实例资源
typedef std::vector<Simu::Bomber*> BomberList; // 轰炸机指针表[提高程序运行效率]
typedef std::vector<Simu::BomberHolder> BomberHolderList; // 轰炸机实例表[保存具体实例]
// 前向声明守方
class DefenceObject;
typedef std::shared_ptr<Simu::DefenceObject> DefenceObjectHolder; // 持有实例,自动释放实例资源
typedef std::vector<Simu::DefenceObject*> DefenceObjectList; // 守方实例指针表[提高程序运行效率]
typedef std::vector<Simu::DefenceObjectHolder> DefenceObjectHolderList; // 守方实例表[保存具体实例]
typedef enum DefenceStatus
{
DEFENCE_OBJECT_IDLE, // 空闲状态
DEFENCE_OBJECT_AWAIT_ORDER, // 待机发弹
DEFENCE_OBJECT_LAUNCH_MISSILE // 发射导弹
} DefenceStatus; // 定义防守方状态
class DefenceObject : public MilitaryObject, public MovingObject
{
public:
DefenceObject();
DefenceObject(const DefenceObject& defence);
DefenceObject(const unsigned number, const Simu::Position& pos, const unsigned missiles,
const catype radius, const DefenceStatus status,
const Simu::TargetList& tlist);
void SetObjectMissileNumber(const unsigned missiles);
void SetObjectActionRadius(const catype radius);
void SetObjectStatus(const DefenceStatus status);
void SetObjectTargetList(const Simu::TargetList& tlist);
void SetObjectBomberList(const Simu::BomberList& blist);
unsigned GetObjectMissileNumber() const;
catype GetObjectActionRadius() const;
DefenceStatus GetObjectStatus() const;
Simu::TargetList& GetObjectTargetList();
Simu::MissileHolderList& GetObjectMissileHolderList();
Simu::BomberList& GetObjectBomberList();
//
// 时间更新
void TimeUpdate();
// 状态记录
void StatusRecord();
// 状态更新
void ChangeStatusAwaitOrder();
void ChangeStatusLaunchMissile();
protected:
unsigned m_MissileNumber_; // 导弹数量
catype m_ActionRadius_; // 作战半径
DefenceStatus m_Status_; // 防守方状态
Simu::TargetList m_TargetList_; // 守护的军事目标列表
Simu::MissileHolderList m_MissileHolderList_; // 导弹列表
Simu::BomberList m_BomberList_; // 轰炸机列表
}; // class DefenceObject
} // namespace Simu
#endif // DEFENCE_INCLUDED
|
15e8e2b2627c9bd9e4f919be70442da108cf454a
|
9e009ec7d7e2cfc7e2ce264a2fd7689463bab017
|
/模板数组类.cpp
|
469596bdf583b46ae70b5f7c4b47de37b6fe52d9
|
[] |
no_license
|
yuu1031/nione
|
d90a8e474d520645a9655a8ae461b33a08e0be33
|
419be3fd6b15eb727a32cd5d6ca68f4cf8852873
|
refs/heads/master
| 2021-07-16T11:30:58.782833
| 2021-03-09T06:29:01
| 2021-03-09T06:29:01
| 240,189,100
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,661
|
cpp
|
模板数组类.cpp
|
#include <iostream>
#include <vector>
using namespace std;
template <typename T>
/*封装一个模板数组类Array,支持以下操作:
1. 构造函数Array(int n),将数组初始化为n个存储空间,建议使用vector;
2. 函数input(int n),使用插入运算符<<读取数据,最多读取n个元素,但不能超过数组存储空间的上限;
3. 重载下标运算符,返回数组的元素。*/
class Array
{
//请完成类的设计
public:
vector<T> arr;
Array(int n)
{
}
void input(int n)
// 使用插入运算符<<读取数据,最多读取n个元素,但不能超过数组存储空间的上限;
{
for(int i=0; i<n; i++)
{
T a;
cin>>a;
arr.push_back(a);
}
}
T& operator [](int n)
{
return arr[n];
}
};
class Fract
/*封装一个分数类Fract,用来处理分数功能和运算,能支持你的Array类使用。
1. 构造:传入两个参数n和m,表示n/m;分数在构造时立即转化成最简分数。
提示:分数化简有专门的算法,可自行调研
2. show()函数:分数输出为“a/b”或“-a/b”的形式,a、b都是无符号整数。若a为0或b为1,只输出符号和分子,不输出“/”和分母。
3. 在分数类上重载+=运算符,进行分数的加法运算。*/
{
//请完成类的设计
public:
Fract(){}
int n,m;
int gys(int n,int m)//最大公约数
{
while (m != 0)
{
int t = n% m;
n = m;
m = t;
}
int gyueshu = n;
return gyueshu;
}
Fract(int a,int b)
{
n=a/gys(a,b);
m=b/gys(a,b);
}
void show();
Fract operator +=(const Fract &a)//1/4+2/3=1*3+2*4/4*3
{
Fract b(a.n*m+a.m*n,a.m*m);
return *this=b;
}
friend istream &operator>>(istream &it,Fract &a)
{
it>>a.n>>a.m;
return it;
}
friend ostream &operator<<(ostream &it,Fract &a);
int fabs(int a)
{
if(a>0)
return a;
else return 0-a;
}
};
void Fract::show()
{
if(n==0||m==1)
{
cout<<n<<endl;
}
else
{
if(n*m<0)
cout<<"-"<<fabs(n)<<"/"<<fabs(m)<<endl;
else
cout<<n<<"/"<<m<<endl;
}
}
int main()
{
unsigned int n;
cin >> n;
Array<double> db(n);
db.input(n);
double dbsum(0.0);
for (unsigned int i = 0; i < n; i++)
dbsum += db[i];
cout << dbsum << endl;
cin >> n;
Array<Fract> fr(n);
fr.input(n);
Fract frsum(0, 1);
for ( unsigned int i = 0; i < n; i++)
frsum += fr[i];
frsum.show();
}
|
0da7a50ee108ca206c82e7eca782b75a09e97625
|
68a54c8ff6b3ecf041116576e323ffad80f2b24a
|
/MainWindow.cpp
|
a16ca975f9a2115b3009dfcdceb15189398405cd
|
[] |
no_license
|
8Observer8/OpenAndSaveJsonFileByDialog
|
3647fb11b8bc7ff0f95ed6a76c661ebd1c8edcee
|
e55990d502c3f29386c8e4e5ec607c9a0d9d0be7
|
refs/heads/master
| 2020-06-04T11:15:42.659471
| 2014-10-20T17:02:09
| 2014-10-20T17:02:09
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,418
|
cpp
|
MainWindow.cpp
|
#include <QString>
#include <QFileDialog>
#include <QJsonObject>
#include <QJsonDocument>
#include <QFile>
#include <QMessageBox>
#include <QByteArray>
#include <QDebug>
#include "MainWindow.h"
#include "ui_MainWindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_actionOpen_triggered()
{
QString fileName = QFileDialog::getOpenFileName(
this,
tr( "Open File" ),
QString(),
tr( "Json Files (*.json)" ) );
if ( fileName.isEmpty() ) {
return;
}
// Open the file
QFile file( fileName );
if ( !file.open( QIODevice::ReadOnly ) ) {
QMessageBox::critical(
this, tr( "Error" ),
tr( "Error: unable to open the file \"%1\"" ).arg( fileName ) );
return;
}
// Read the file
QByteArray data = file.readAll();
// Create Json document
QJsonDocument document;
document = document.fromJson( data );
// Get the text from the Json document
QString text = document.object()["Text"].toString();
ui->textEdit->setText( text );
}
void MainWindow::on_actionSave_triggered()
{
QString fileName = QFileDialog::getSaveFileName(
this,
tr( "Save File" ),
QString(),
tr( "Json Files (*.json)" ) );
if ( fileName.isEmpty() ) {
return;
}
// Get text
QString text = ui->textEdit->toPlainText();
// Create a Json object from the text
QJsonObject json;
json["Text"] = text;
// Create a Json document
QJsonDocument document;
document.setObject( json );
// Write the Json document to a file
// Open a file
QFile file( fileName );
if ( !file.open( QIODevice::WriteOnly ) ) {
QMessageBox::critical(
this, tr( "Error" ),
tr( "Error: unable to open the file \"%1\"" ).arg( fileName ) );
return;
}
// Write to the file
if ( !file.write( document.toJson() ) ) {
QMessageBox::critical(
this, tr( "Error" ),
tr( "Error: unable to write to the file \"%1\"" ).arg( fileName ) );
return;
}
}
void MainWindow::on_actionExit_triggered()
{
this->close();
}
|
581187ad102ba624e764ebd6b323b38d7dcb114d
|
90e9208bfab6c1b9a6095066f723123ee35284f6
|
/UI/UIOperationalControlPanel.cpp
|
d14f2f0bc06409d100ef4e5f8b8800975d1bacec
|
[] |
no_license
|
hvictor/Release
|
58cc832618fa777e87bbb8d79d5e8f6f4743910f
|
46655174cee9a357b7cc0b6b49ab51afd906d432
|
refs/heads/master
| 2020-12-12T07:00:36.358723
| 2016-08-08T06:17:10
| 2016-08-08T06:17:10
| 51,407,400
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 337
|
cpp
|
UIOperationalControlPanel.cpp
|
/*
* UIOperationalControlPanel.cpp
*
* Created on: Feb 13, 2016
* Author: sled
*/
#include "UIOperationalControlPanel.h"
UIOperationalControlPanel::UIOperationalControlPanel() {
// TODO Auto-generated constructor stub
}
UIOperationalControlPanel::~UIOperationalControlPanel() {
// TODO Auto-generated destructor stub
}
|
1754bd51d3a6c54aab033da0eb5aaeb1577e90e7
|
524efe3384ccba12f5849786e54de92740c4c0c2
|
/string.cpp
|
e1282e3bb306467e6b0f280d366d6a96f66ccf37
|
[] |
no_license
|
mismail85/IndexedTable
|
1de174b7cd9db4ab7df3497a06788c8c2f123a1e
|
f250b95b66f9133ae13214ec98059246c71d7942
|
refs/heads/master
| 2021-01-19T05:43:17.167082
| 2014-11-06T17:22:45
| 2014-11-06T17:22:45
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,018
|
cpp
|
string.cpp
|
#include "string.h"
#include <algorithm>
#include <functional>
#include <cctype>
#include <locale>
String::String()
{
}
String::String(string &str)
{
this->assign(str);
}
/**
* @brief split
* @param tokens
* @param text
* @param sep
* Splits an string (text)into tokens using a separator
*/
void String::split(vector<string> &tokens, char sep) {
int start = 0, end = 0;
while ((end = find(sep, start)) != string::npos) {
tokens.push_back( substr(start, end - start));
start = end + 1;
}
tokens.push_back( substr(start));
}
// trim from start
String& String::ltrim() {
erase( begin(), std::find_if( begin(), end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
return *this;
}
// trim from end
String& String::rtrim() {
erase(std::find_if( rbegin(), rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), end());
return *this;
}
// trim from both ends
String& String::trim() {
assign(rtrim());
assign(ltrim());
return *this;
}
|
7232cc08fdc083933db9476811dbbc44f603c70e
|
95b8ce7f08a5eb103fa74afd3cd32b53f9885db6
|
/types.cpp
|
2ebd5ed56170fed816e95eaab1badbcf08e19bae
|
[] |
no_license
|
guyKN/Chess
|
a10c42150be797341518f680b2a05fe579a0639f
|
af131736a37180b0dfa321950c243d227157203b
|
refs/heads/main
| 2023-01-31T15:30:52.503473
| 2020-12-13T20:41:43
| 2020-12-13T20:41:43
| 321,156,072
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,672
|
cpp
|
types.cpp
|
//#pragma clang diagnostic push
//
// Created by guykn on 12/7/2020.
//
#include <iostream>
#include "types.h"
# include <cassert>
using namespace Chess;
namespace Chess {
std::ostream &printBitboard(Bitboard bitboard, std::ostream &os) {
SquareMask squareMask = SQUARE_MASK_FIRST;
os << "\n";
for (Rank rank = RANK_FIRST; rank <= RANK_LAST; ++rank) {
for (File file = FILE_FIRST; file <= FILE_LAST; ++file) {
os << (squareMask & bitboard ? '1' : '.') << ' ';
squareMask <<= 1;
}
os << std::endl;
}
return os;
}
Rank rankOf(Square square) {
return static_cast<Rank>(square / 8);
}
inline constexpr File fileOf(Square square) {
return static_cast<File>(square % 8);
}
bool square_ok(Square square) {
return square >= SQ_FIRST && square <= SQ_LAST;
}
char toChar(Rank rank) {
if (rank >= RANK_FIRST && rank <= RANK_LAST) {
return RANK_NAMES[rank];
} else {
return '?';
}
}
Rank parseRank(char rankChar) {
for (Rank rank = RANK_FIRST; rank <= RANK_LAST; ++rank) {
if (toChar(rank) == rankChar) {
return rank;
}
}
return RANK_INVALID;
}
char toChar(File file) {
if (file >= FILE_FIRST && file <= FILE_LAST) {
return FILE_NAMES[file];
} else {
return '?';
}
}
File parseFile(char fileChar) {
for (File file = FILE_FIRST; file <= FILE_LAST; ++file) {
if (toupper(toChar(file)) == toupper(fileChar)) {
return file;
}
}
return FILE_INVALID;
}
Square parseSquare(std::string &str) {
str = removeSpaces(str);
if (str.length() != 2) {
return SQ_INVALID;
}
File file = parseFile(str[0]);
Rank rank = parseRank(str[1]);
if (rank_ok(rank) && file_ok(file)) {
return makeSquare(rank, file);
} else {
return SQ_INVALID;
}
}
std::string removeSpaces(std::string &input) {
input.erase(std::remove(input.begin(), input.end(), ' '), input.end());
input.erase(std::remove(input.begin(), input.end(), '\n'), input.end());
return input;
}
std::string toString(Square square) {
if (!square_ok(square)) {
return "INVALID";
}
std::string result = "";
result.push_back(toChar(fileOf(square)));
result.push_back(toChar(rankOf(square)));
return result;
}
}
|
112d328cccc9e1164ef9f5ee32125ad462564f5c
|
6ab9a3229719f457e4883f8b9c5f1d4c7b349362
|
/lib/geometry.cpp
|
ca8481d1909d2a48e1285fe00238dd6d491e9457
|
[] |
no_license
|
ajmarin/coding
|
77c91ee760b3af34db7c45c64f90b23f6f5def16
|
8af901372ade9d3d913f69b1532df36fc9461603
|
refs/heads/master
| 2022-01-26T09:54:38.068385
| 2022-01-09T11:26:30
| 2022-01-09T11:26:30
| 2,166,262
| 33
| 15
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,545
|
cpp
|
geometry.cpp
|
#include <cassert>
#include <cmath>
#include <cstdio>
template <class _T> bool cmp(_T a, _T b){ return (a > b) - (a < b); }
template <class _T>
struct point {
_T x, y;
point(_T _x = 0, _T _y = 0): x(_x), y(_y) {}
_T dot(const point p){ return x * p.x + y * p.y; }
_T cross(const point p){ return x * p.y - y * p.x; }
point operator-(point p){ return point(x - p.x, y - p.y); }
point operator+(point p){ return point(x + p.x, y + p.y); }
point operator/(_T div){ return point(x / div, y / div); }
point operator*(_T mul){ return point(x * mul, y * mul); }
double mod(){ return sqrt(x * x + y * y); }
// Clockwise rotation from *this to p in radians [-pi, pi]
double ang(point p){ return atan2(this -> cross(p), this -> dot(p)); }
bool operator<(point p) const { return x < p.x || (x == p.x && y < p.y); }
bool operator>(point p) const { return x > p.x || (x == p.x && y > p.y); }
bool operator==(point p) const { return cmp(x, p.x) + cmp(y, p.y) == 0; }
};
template <class _T>
_T cross(const point<_T>& O, const point<_T>& A, const point<_T>& B){
return (A - O) * (B - O);
}
template <class _T>
vector< point<_T> > convex_hull(vector< point<_T> >& P){
int n = P.size(), k = 0;
vector< point<_T> > r(2*n);
sort(P.begin(), P.end());
// Build lower hull
for(int i = 0; i < n; ++i){
while(k >= 2 && cross(r[k - 2], r[k - 1], P[i]) <= 0) --k;
r[k++] = P[i];
}
// Build upper hull
for(int i = n - 2, t = k + 1; i >= 0; --i){
while(k >= t && cross(r[k - 2], r[k - 1], P[i]) <= 0) --k;
r[k++] = P[i];
}
r.resize(k);
return r;
}
int main(void){
// Orthogonal vectors have dot product 0
assert(point<int>(1,0).dot(point<int>(0,1)) == 0);
assert(point<int>(2,-3).dot(point<int>(3,2)) == 0);
// Parallel vectors have cross product 0
assert(point<int>(1,1).cross(point<int>(3,3)) == 0);
// Simple operations + comparison tests
assert(point<int>(1,1) + point<int>(2,5) == point<int>(3,6));
assert(point<int>(5,2) - point<int>(2,5) == point<int>(3,-3));
assert(point<int>(5,5)/5 == point<int>(1,1));
assert(point<int>(2,3) * 7 == point<int>(14,21));
assert(point<int>(1,2) > point<int>(0,99));
assert(point<int>(1,3) > point<int>(1,2));
assert(point<int>(0,99) < point<int>(1,1));
assert(point<int>(0,1) < point<int>(0,3));
// Vector (1,0) rotated cw 90 degrees is vector (1,0)
assert(!cmp(point<int>(1,0).ang(point<int>(0,1)), acos(-1)/2.0));
// Vector (0,1) rotated ccw 90 degrees is vector (1,0)
assert(!cmp(point<int>(0,1).ang(point<int>(1,0)), -acos(-1)/2.0));
puts("TEST SUCCEEDED");
return 0;
}
|
7e48e0071d629c0c3fc4c2c81aef2923060ce5d9
|
4c25432a6d82aaebd82fd48e927317b15a6bf6ab
|
/data/dataset_2017/dataset_2017_8_formatted/jddantes/8294486_5681755159789568_jddantes.cpp
|
0443a75d77099e09cad3a59f30e404700548cc10
|
[] |
no_license
|
wzj1988tv/code-imitator
|
dca9fb7c2e7559007e5dbadbbc0d0f2deeb52933
|
07a461d43e5c440931b6519c8a3f62e771da2fc2
|
refs/heads/master
| 2020-12-09T05:33:21.473300
| 2020-01-09T15:29:24
| 2020-01-09T15:29:24
| 231,937,335
| 1
| 0
| null | 2020-01-05T15:28:38
| 2020-01-05T15:28:37
| null |
UTF-8
|
C++
| false
| false
| 1,637
|
cpp
|
8294486_5681755159789568_jddantes.cpp
|
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef tuple<int, int, ll> t3;
#define INF (1e200)
int N;
int input[100][100];
int input_spd[100];
int input_rem[100];
map<t3, double> memo;
double f(int index, int spd, ll rem) {
if (index == N - 1) {
return 0;
}
t3 state(index, spd, rem);
auto itr = memo.find(state);
if (itr != memo.end()) {
return itr->second;
}
double best_ret = INF;
if (rem - input[index][index + 1] >= 0) {
double this_horse = (double)input[index][index + 1] / (double)spd +
f(index + 1, spd, rem - input[index][index + 1]);
best_ret = min(best_ret, this_horse);
}
// Use this horse
if (input_rem[index] - input[index][index + 1] >= 0) {
double this_horse =
(double)input[index][index + 1] / (double)input_spd[index] +
f(index + 1, input_spd[index],
input_rem[index] - input[index][index + 1]);
best_ret = min(best_ret, this_horse);
}
memo[state] = best_ret;
return best_ret;
}
int main() {
int cases;
scanf("%d", &cases);
for (int e = 0; e < cases; e++) {
int Q;
scanf("%d %d", &N, &Q);
for (int i = 0; i < N; i++) {
scanf("%d %d", &input_rem[i], &input_spd[i]);
}
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
scanf("%d", &input[i][j]);
}
}
printf("Case #%d:", e + 1);
for (int q = 0; q < Q; q++) {
int src, dest;
scanf("%d %d", &src, &dest);
memo.clear();
double ans = f(0, input_spd[0], input_rem[0]);
printf(" %f", ans);
}
printf("\n");
}
return 0;
}
|
2d6883c7798dfbf1cda4148262528307ad63b95c
|
1d75146a66245dc046dc216bb602129208e00733
|
/closed/Intel/code/bert-99/pytorch-cpu/mlperf_plugins/csrc/i_softmax_tpp.cpp
|
ddaa14c4187946de778f1752f7812fa5162a111e
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
georgelyuan/inference_results_v1.1
|
febf287bd5967bf7f087355a81f06a2bd298cbfe
|
3196a5587887c39203ee3ac246fa5dbe789d9085
|
refs/heads/main
| 2023-08-16T08:49:45.274284
| 2021-09-23T20:57:17
| 2021-09-23T20:57:17
| 409,773,141
| 0
| 0
|
NOASSERTION
| 2021-09-23T23:36:37
| 2021-09-23T23:36:37
| null |
UTF-8
|
C++
| false
| false
| 22,521
|
cpp
|
i_softmax_tpp.cpp
|
#include <cstdint>
#include <immintrin.h>
#include "i_softmax_tpp.hpp"
#include "el_common_intrin.hpp"
namespace intel_mlperf {
static inline __m256 snd_order_poly_exp(
__m256 z, __m256 f, const float c[]) {
const auto c0 = _mm256_set1_ps(c[0]);
const auto c1 = _mm256_set1_ps(c[1]);
const auto c2 = _mm256_set1_ps(c[2]);
auto y = (f * c0 + c1) * f + c2;
auto exp = _mm256_scalef_ps(y, z);
return exp;
}
static inline __m512 snd_order_poly_exp(
__m512 z, __m512 f, const float c[]) {
const auto c0 = _mm512_set1_ps(c[0]);
const auto c1 = _mm512_set1_ps(c[1]);
const auto c2 = _mm512_set1_ps(c[2]);
auto y = (f * c0 + c1) * f + c2;
auto exp = _mm512_scalef_ps(y, z);
return exp;
}
static inline __m256 third_order_poly_exp(
__m256 z, __m256 f, const float c[]) {
const auto c0 = _mm256_set1_ps(c[0]);
const auto c1 = _mm256_set1_ps(c[1]);
const auto c2 = _mm256_set1_ps(c[2]);
const auto c3 = _mm256_set1_ps(c[3]);
auto y = ((f * c0 + c1) * f + c2) * f + c3;
auto exp = _mm256_scalef_ps(y, z);
return exp;
}
static inline __m512 third_order_poly_exp(
__m512 z, __m512 f, const float c[]) {
const auto c0 = _mm512_set1_ps(c[0]);
const auto c1 = _mm512_set1_ps(c[1]);
const auto c2 = _mm512_set1_ps(c[2]);
const auto c3 = _mm512_set1_ps(c[3]);
auto y = ((f * c0 + c1) * f + c2) * f + c3;
auto exp = _mm512_scalef_ps(y, z);
return exp;
}
// [0.5, 0.5)
static inline __m256 exp_ps_0_1(__m256 x) {
const auto log2e = _mm256_set1_ps(1.442695f);
const float _c [] = {0.240226507f, 0.452920674f, 0.713483036f};
auto x1 = x * log2e + _mm256_set1_ps(0.5f);
auto z = _mm256_floor_ps(x1);
auto f = x1 - z;
return snd_order_poly_exp(z, f, _c);
}
// [0.5, 0.5)
static inline __m512 exp_ps_0_1(__m512 x) {
const auto log2e = _mm512_set1_ps(1.442695f);
const float _c [] = {0.240226507f, 0.452920674f, 0.713483036f};
auto x1 = x * log2e + _mm512_set1_ps(0.5f);
auto z = _mm512_floor_ps(x1);
auto f = x1 - z;
return snd_order_poly_exp(z, f, _c);
}
static inline __m256 exp_ps_zero_one_third(__m256 x) {
const auto log2e = _mm256_set1_ps(1.442695f);
const auto half = _mm256_set1_ps(0.5f);
const float _c [] = {0.05550410866f, 0.15697034396f, 0.49454875509f, 0.70654502287f};
auto x1 = x * log2e + half;
auto z = _mm256_floor_ps(x1);
auto f = x1 - z;
return third_order_poly_exp(z, f, _c);
}
static inline __m512 exp_ps_zero_one_third(__m512 x) {
const auto log2e = _mm512_set1_ps(1.442695f);
const auto half = _mm512_set1_ps(0.5f);
const float _c [] = {0.05550410866f, 0.15697034396f, 0.49454875509f, 0.70654502287f};
auto x1 = x * log2e + half;
auto z = _mm512_floor_ps(x1);
auto f = x1 - z;
return third_order_poly_exp(z, f, _c);
}
// Smaller range [-ln2, 0)
static inline __m256 exp_ps_negln2_zero(__m256 x) {
const auto _log2e = _mm256_set1_ps(1.442695f);
const auto ln2 = _mm256_set1_ps(0.693147180f);
const float _c [] = {0.35815147f, 0.96963238f, 1.0f};
auto z = _mm256_ceil_ps(x * _log2e);
auto f = x - z * ln2;
return snd_order_poly_exp(z, f, _c);
}
static inline __m512 exp_ps_negln2_zero(__m512 x) {
const auto _log2e = _mm512_set1_ps(1.442695f);
const auto ln2 = _mm512_set1_ps(0.693147180f);
const float _c [] = {0.35815147f, 0.96963238f, 1.0f};
auto z = _mm512_ceil_ps(x * _log2e);
auto f = x - z * ln2;
return snd_order_poly_exp(z, f, _c);
}
static inline __m256 _mm256_max_reduce_ps(__m256 v) {
auto perm0 = _mm256_permute_ps(v, _MM_SHUFFLE(2,3,0,1));
auto m1 = _mm256_max_ps(v, perm0);
auto perm1 = _mm256_permute_ps(m1, _MM_SHUFFLE(1,0,3,2));
auto m2 = _mm256_max_ps(perm1, m1);
auto perm2 = _mm256_permute2f128_ps(m2, m2, 0x01);
auto m3 = _mm256_max_ps(perm2, m2);
return m3;
}
static inline float _mm256_reduce_max_ps(__m256 v) {
return _mm256_max_reduce_ps(v)[0];
}
static inline __m256 _mm256_add_reduce_ps(__m256 v) {
auto perm0 = _mm256_permute_ps(v, _MM_SHUFFLE(2,3,0,1));
auto m1 = v + perm0;
auto perm1 = _mm256_permute_ps(m1, _MM_SHUFFLE(1,0,3,2));
auto m2 = m1 + perm1;
auto perm2 = _mm256_permute2f128_ps(m2, m2, 0x01);
auto m3 = m2 + perm2;
return m3;
}
static inline float _mm256_reduce_add_ps(__m256 v) {
return _mm256_add_reduce_ps(v)[0];
}
static inline __m512 _mm512_max_reduce_ps(__m512 v) {
auto perm0 = _mm512_permute_ps(v, _MM_SHUFFLE(2,3,0,1));
auto m1 = _mm512_max_ps(v, perm0);
auto perm1 = _mm512_permute_ps(m1, _MM_SHUFFLE(1,0,3,2));
auto m2 = _mm512_max_ps(perm1, m1);
auto perm2 = _mm512_shuffle_f32x4(m2, m2, _MM_SHUFFLE(2,3,0,1));
auto m3 = _mm512_max_ps(perm2, m2);
auto perm3 = _mm512_shuffle_f32x4(m3, m3, _MM_SHUFFLE(1,0,3,2));
auto m4 = _mm512_max_ps(perm3, m3);
return m4;
}
static inline __m512 _mm512_add_reduce_ps(__m512 v) {
auto perm0 = _mm512_permute_ps(v, _MM_SHUFFLE(2,3,0,1));
auto m1 = v + perm0;
auto perm1 = _mm512_permute_ps(m1, _MM_SHUFFLE(1,0,3,2));
auto m2 = m1 + perm1;
auto perm2 = _mm512_shuffle_f32x4(m2, m2, _MM_SHUFFLE(2,3,0,1));
auto m3 = m2 + perm2;
auto perm3 = _mm512_shuffle_f32x4(m3, m3, _MM_SHUFFLE(1,0,3,2));
auto m4 = m3 + perm3;
return m4;
}
template <int vec_l>
inline float scale_add_and_max(
float *out, float scale, int32_t *in, float *att_mask, int64_t ld);
// Integer softmax reference, int32 in, int8 out
template <>
inline float scale_add_and_max<8>(
float *out, float scale, int32_t *in, float *att_mask, int64_t ld) {
auto pin = reinterpret_cast<int32_t (*)>(in);
auto pout = reinterpret_cast<float (*)>(out);
auto full = _mm256_set1_epi32(-5000);
auto full_ps = _mm256_set1_ps(-5000.0f);
int64_t d2 = 0;
auto vmax = _mm256_set1_ps(0.0f);
for (; d2 < (ld/8 * 8); d2 += 8) {
auto l = _mm256_lddqu_si256((__m256i *)&pin[d2]);
auto m = _mm256_loadu_ps(&att_mask[d2]);
auto f = _mm256_cvtepi32_ps(l) * _mm256_set1_ps(scale) + m;
vmax = _mm256_max_ps(f, vmax);
_mm256_storeu_ps(&pout[d2], f);
}
if (d2 < ld) {
int rem = ld - d2;
__mmask8 mask = (1<<rem) -1;
auto l = _mm256_mask_loadu_epi32(full, mask, &pin[d2]);
auto m = _mm256_mask_loadu_ps(full_ps, mask, &att_mask[d2]);
auto f = _mm256_cvtepi32_ps(l) * _mm256_set1_ps(scale) + m;
vmax = _mm256_max_ps(f, vmax);
_mm256_mask_storeu_ps(&pout[d2], mask, f);
}
return _mm256_reduce_max_ps(vmax);
}
template <>
inline float scale_add_and_max<16>(
float *out, float scale, int32_t *in, float *att_mask, int64_t ld) {
auto pin = reinterpret_cast<int32_t (*)>(in);
auto pout = reinterpret_cast<float (*)>(out);
auto full = _mm512_set1_epi32(-5000);
auto full_ps = _mm512_set1_ps(-5000.0f);
int64_t d2 = 0;
auto vmax = _mm512_set1_ps(0.0f);
for (; d2 < (ld/16 * 16); d2 += 16) {
auto l = _mm512_loadu_si512(&pin[d2]);
auto m = _mm512_loadu_ps(&att_mask[d2]);
auto f = _mm512_cvtepi32_ps(l) * _mm512_set1_ps(scale) + m;
vmax = _mm512_max_ps(f, vmax);
_mm512_storeu_ps(&pout[d2], f);
}
if (d2 < ld) {
int rem = ld - d2;
__mmask16 mask = (1<<rem) -1;
auto l = _mm512_mask_loadu_epi32(full, mask, &pin[d2]);
auto m = _mm512_mask_loadu_ps(full_ps, mask, &att_mask[d2]);
auto f = _mm512_cvtepi32_ps(l) * _mm512_set1_ps(scale) + m;
vmax = _mm512_max_ps(f, vmax);
_mm512_mask_storeu_ps(&pout[d2], mask, f);
}
return _mm512_reduce_max_ps(vmax);
}
template <int vec_l>
inline float subtract_and_exp_reduce(
float *out, float max, float *in, int64_t ld);
template <>
inline float subtract_and_exp_reduce<8>(
float *out, float max, float *in, int64_t ld) {
int64_t d2 = 0;
auto vsum = _mm256_setzero_ps();
auto full = _mm256_set1_ps(-5000.0f); // XXX: Denorm clear?
auto vmax = _mm256_set1_ps(max);
for (;d2 < (ld/8*8); d2 += 8) {
auto f = _mm256_loadu_ps(&in[d2]);
auto d = f - vmax;
auto e = exp_ps_0_1(d);
_mm256_storeu_ps(&out[d2], e);
vsum += e;
}
if (d2 < ld) {
int rem = ld - d2;
__mmask8 mask = (1<<rem) -1;
auto f = _mm256_mask_loadu_ps(full, mask, &in[d2]);
auto d = f - vmax;
auto e = exp_ps_0_1(d);
_mm256_mask_storeu_ps(&out[d2], mask, e);
vsum += e;
}
return _mm256_reduce_add_ps(vsum);
}
template <>
inline float subtract_and_exp_reduce<16>(
float *out, float max, float *in, int64_t ld) {
int64_t d2 = 0;
auto vsum = _mm512_setzero_ps();
auto full = _mm512_set1_ps(-5000.0f); // XXX: Denorm clear?
auto vmax = _mm512_set1_ps(max);
for (;d2 < (ld/16*16); d2 += 16) {
auto f = _mm512_loadu_ps(&in[d2]);
auto d = f - vmax;
auto e = exp_ps_0_1(d);
_mm512_storeu_ps(&out[d2], e);
vsum += e;
}
if (d2 < ld) {
int rem = ld - d2;
__mmask16 mask = (1<<rem) -1;
auto f = _mm512_mask_loadu_ps(full, mask, &in[d2]);
auto d = f - vmax;
auto e = exp_ps_0_1(d);
_mm512_mask_storeu_ps(&out[d2], mask, e);
vsum += e;
}
return _mm512_reduce_add_ps(vsum);
}
template <int vec_l>
static inline void scale_quant_out(
int8_t *out, float sum, float scale, float *in, int64_t ld);
template <>
inline void scale_quant_out<8>(
int8_t *out, float sum, float scale, float *in, int64_t ld) {
int64_t d2 = 0;
auto vsum = _mm256_set1_ps(sum);
auto s = _mm256_set1_ps(scale) / vsum;
auto full = _mm256_set1_ps(0.0);
for (; d2 < ld/8*8; d2 += 8) {
auto l = _mm256_loadu_ps(&in[d2]);
auto m = _mm256_round_ps(
l * s, _MM_FROUND_TO_NEAREST_INT |_MM_FROUND_NO_EXC);
auto i_4 = _mm256_cvtps_epi32(m);
_mm256_mask_cvtepi32_storeu_epi8(&out[d2], 0xff, i_4);
}
if (d2 < ld) {
int rem = ld - d2;
__mmask8 mask = (1<<rem) -1;
auto l = _mm256_mask_loadu_ps(full, mask, &in[d2]);
auto m = _mm256_round_ps(
l * s, _MM_FROUND_TO_NEAREST_INT |_MM_FROUND_NO_EXC);
auto i_4 = _mm256_cvtps_epi32(m);
_mm256_mask_cvtepi32_storeu_epi8(&out[d2], mask, i_4);
}
}
template <>
inline void scale_quant_out<16>(
int8_t *out, float sum, float scale, float *in, int64_t ld) {
int64_t d2 = 0;
auto vsum = _mm512_set1_ps(sum);
auto s = _mm512_set1_ps(scale) / vsum;
auto full = _mm512_setzero_ps();
for (; d2 < ld/16*16; d2 += 16) {
auto l = _mm512_loadu_ps(&in[d2]);
auto m = _mm512_mul_round_ps(
l, s, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC);
auto i_4 = _mm512_cvtps_epi32(m);
_mm512_mask_cvtepi32_storeu_epi8(&out[d2], 0xffff, i_4);
}
if (d2 < ld) {
int rem = ld - d2;
__mmask16 mask = (1<<rem) -1;
auto l = _mm512_mask_loadu_ps(full, mask, &in[d2]);
auto m = _mm512_mul_round_ps(
l, s, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC);
auto i_4 = _mm512_cvtps_epi32(m);
_mm512_mask_cvtepi32_storeu_epi8(&out[d2], mask, i_4);
}
}
template <int vec_length, int N>
struct i32_scale_softmax_scale_i8 {
inline static void run(
void *out, void *in, void *att_mask, float M, float oscale, int64_t ld);
};
template <int vec_length, int N>
struct i32_scale_attlen_softmax_scale_i8 {
inline static void run(
void *out, void *in, int32_t att_len, float M, float oscale, int64_t ld);
};
template <int N>
struct i32_scale_softmax_scale_i8<16, N> {
inline static void run(
void *out, void *in, float *att_mask, float M, float oscale, int64_t ld) {
auto pin = reinterpret_cast<int32_t (*)[ld]>(in);
auto ld_16 = (ld + 15) / 16 * 16;
// Scratch for max subtraction
alignas(64) float dout [N][ld_16];
auto zero = _mm512_setzero_epi32();
auto full_ps = _mm512_set1_ps(-5000.f);
auto vscale = _mm512_set1_ps(M);
__m512 vmax[N];
# pragma unroll N
for (int i = 0; i < N; ++i) {
vmax[i] = _mm512_setzero_ps();
}
int64_t d2;
for (d2 = 0; d2 < ld/16 * 16; d2 += 16) {
auto m = _mm512_loadu_ps(&att_mask[d2]);
# pragma unroll N
for (int i = 0; i < N; ++i) {
auto l = _mm512_loadu_si512(&pin[i][d2]);
auto f = _mm512_cvtepi32_ps(l) * vscale + m;
vmax[i] = _mm512_max_ps(f, vmax[i]);
_mm512_storeu_ps(&dout[i][d2], f);
}
}
if (d2 < ld) {
int rem = ld - d2;
__mmask16 mask = (1<<rem) -1;
auto m = _mm512_mask_loadu_ps(full_ps, mask, &att_mask[d2]);
# pragma unroll N
for (int i = 0; i < N; ++i) {
auto l = _mm512_mask_loadu_epi32(zero, mask, &pin[i][d2]);
auto f = _mm512_cvtepi32_ps(l) * vscale + m;
vmax[i] = _mm512_max_ps(f, vmax[i]);
_mm512_storeu_ps(&dout[i][d2], f);
}
}
__m512 vsum[N];
# pragma unroll N
for (int i = 0; i < N; ++ i) {
vmax[i] = _mm512_max_reduce_ps(vmax[i]);
vsum[i] = _mm512_setzero_ps();
}
for (d2 = 0; d2 < ld_16; d2 += 16) {
# pragma unroll N
for (int i = 0; i < N; ++ i) {
auto f = _mm512_loadu_ps(&dout[i][d2]);
auto d = f - vmax[i];
auto e = exp_ps_0_1(d);
_mm512_storeu_ps(&dout[i][d2], e);
vsum[i] += e;
}
}
auto voscale = _mm512_set1_ps(oscale);
# pragma unroll N
for (int i = 0; i < N; ++ i) {
#ifdef usercp
vsum[i] = voscale * _mm512_rcp14_ps(_mm512_add_reduce_ps(vsum[i]));
#else
vsum[i] = voscale / _mm512_add_reduce_ps(vsum[i]);
#endif
}
auto pout = reinterpret_cast<int8_t (*)[ld]>(out);
for (d2 = 0; d2 < ld/16 * 16; d2 += 16) {
# pragma unroll N
for (int i = 0; i < N; ++ i) {
auto l = _mm512_loadu_ps(&dout[i][d2]);
auto i_4 = _mm512_scale_minmax_i8_ps(l, vsum[i]);
_mm512_mask_cvtepi32_storeu_epi8(&pout[i][d2], 0xffff, i_4);
}
}
if (d2 < ld) {
int rem = ld -d2;
__mmask16 mask = (1<<rem) -1;
# pragma unroll N
for (int i = 0; i < N; ++ i) {
auto l = _mm512_loadu_ps(&dout[i][d2]);
auto i_4 = _mm512_scale_minmax_i8_ps(l, vsum[i]);
_mm512_mask_cvtepi32_storeu_epi8(&pout[i][d2], mask, i_4);
}
}
}
};
template <int N>
struct i32_scale_attlen_softmax_scale_i8<16, N> {
inline static void run(
void *out, void *in, int32_t att_len, float M, float oscale, int64_t ld) {
auto pin = reinterpret_cast<int32_t (*)[ld]>(in);
// assert(att_len <= ld);
auto att_l16 = (att_len + 15) / 16 * 16;
// Scratch for max subtraction
alignas(64) float dout [N][att_l16];
auto neg_large = _mm512_set1_epi32(-500000);
auto vscale = _mm512_set1_ps(M);
__m512 vmax[N];
# pragma unroll N
for (int i = 0; i < N; ++i) {
vmax[i] = _mm512_setzero_ps();
}
int d2;
for (d2 = 0; d2 < att_len / 16 * 16; d2 += 16) {
# pragma unroll N
for (int i = 0; i < N; ++i) {
auto l = _mm512_loadu_si512(&pin[i][d2]);
auto f = _mm512_cvtepi32_ps(l) * vscale;
vmax[i] = _mm512_max_ps(f, vmax[i]);
_mm512_storeu_ps(&dout[i][d2], f);
}
}
if (d2 < att_len) {
int rem = att_len - d2;
__mmask16 mask = (1<<rem) -1;
# pragma unroll N
for (int i = 0; i < N; ++i) {
auto l = _mm512_mask_loadu_epi32(neg_large, mask, &pin[i][d2]);
auto f = _mm512_cvtepi32_ps(l) * vscale;
vmax[i] = _mm512_max_ps(f, vmax[i]);
_mm512_storeu_ps(&dout[i][d2], f);
}
}
__m512 vsum[N];
# pragma unroll N
for (int i = 0; i < N; ++ i) {
vmax[i] = _mm512_max_reduce_ps(vmax[i]);
vsum[i] = _mm512_setzero_ps();
}
for (d2 = 0; d2 < att_l16; d2 += 16) {
# pragma unroll N
for (int i = 0; i < N; ++ i) {
auto f = _mm512_loadu_ps(&dout[i][d2]);
auto d = f - vmax[i];
auto e = exp_ps_0_1(d);
_mm512_storeu_ps(&dout[i][d2], e);
vsum[i] += e;
}
}
auto voscale = _mm512_set1_ps(oscale);
# pragma unroll N
for (int i = 0; i < N; ++ i) {
#ifdef usercp
vsum[i] = voscale * _mm512_rcp14_ps(_mm512_add_reduce_ps(vsum[i]));
#else
vsum[i] = voscale / _mm512_add_reduce_ps(vsum[i]);
#endif
}
auto pout = reinterpret_cast<int8_t (*)[ld]>(out);
auto zero = _mm512_setzero_ps();
for (d2 = 0; d2 < ld/16*16; d2 += 16) {
# pragma unroll N
for (int i = 0; i < N; ++ i) {
auto l = d2 < att_l16 ? _mm512_loadu_ps(&dout[i][d2])
: zero;
auto i_4 = _mm512_scale_minmax_i8_ps(l, vsum[i]);
_mm512_mask_cvtepi32_storeu_epi8(&pout[i][d2], 0xffff, i_4);
}
}
if (d2 < ld) {
int rem = ld -d2;
__mmask16 mask = (1<<rem) -1;
# pragma unroll N
for (int i = 0; i < N; ++ i) {
auto l = d2 < att_l16 ? _mm512_loadu_ps(&dout[i][d2])
: zero;
auto i_4 = _mm512_scale_minmax_i8_ps(l, vsum[i]);
_mm512_mask_cvtepi32_storeu_epi8(&pout[i][d2], mask, i_4);
}
}
}
};
static inline void f_i32_scale_softmax_scale_i8(
int8_t *out, int32_t *in, float *att_mask,
float M, float oscale, int64_t ld, int l) {
switch(l) {
case 1:
return i32_scale_softmax_scale_i8<16, 1>::run(out, in, att_mask,
M, oscale, ld);
case 2:
return i32_scale_softmax_scale_i8<16, 2>::run(out, in, att_mask,
M, oscale, ld);
case 3:
return i32_scale_softmax_scale_i8<16, 3>::run(out, in, att_mask,
M, oscale, ld);
case 4:
return i32_scale_softmax_scale_i8<16, 4>::run(out, in, att_mask,
M, oscale, ld);
case 5:
return i32_scale_softmax_scale_i8<16, 5>::run(out, in, att_mask,
M, oscale, ld);
case 6:
return i32_scale_softmax_scale_i8<16, 6>::run(out, in, att_mask,
M, oscale, ld);
case 7:
return i32_scale_softmax_scale_i8<16, 7>::run(out, in, att_mask,
M, oscale, ld);
case 8:
return i32_scale_softmax_scale_i8<16, 8>::run(out, in, att_mask,
M, oscale, ld);
case 9:
return i32_scale_softmax_scale_i8<16, 9>::run(out, in, att_mask,
M, oscale, ld);
case 10:
return i32_scale_softmax_scale_i8<16, 10>::run(out, in, att_mask,
M, oscale, ld);
case 11:
return i32_scale_softmax_scale_i8<16, 11>::run(out, in, att_mask,
M, oscale, ld);
case 12:
return i32_scale_softmax_scale_i8<16, 12>::run(out, in, att_mask,
M, oscale, ld);
case 13:
return i32_scale_softmax_scale_i8<16, 13>::run(out, in, att_mask,
M, oscale, ld);
case 14:
return i32_scale_softmax_scale_i8<16, 14>::run(out, in, att_mask,
M, oscale, ld);
case 15:
return i32_scale_softmax_scale_i8<16, 15>::run(out, in, att_mask,
M, oscale, ld);
case 16:
return i32_scale_softmax_scale_i8<16, 16>::run(out, in, att_mask,
M, oscale, ld);
}
auto l1 = l/2;
auto l2 = l - l1;
auto pin = reinterpret_cast<int32_t (*)[ld]>(in);
auto pout = reinterpret_cast<int8_t (*)[ld]>(out);
f_i32_scale_softmax_scale_i8(pout[0], pin[0], att_mask, M, oscale, ld, l1);
f_i32_scale_softmax_scale_i8(pout[l1], pin[l1], att_mask, M, oscale, ld, l2);
}
static inline void f_i32_scale_softmax_scale_i8(
int8_t *out, int32_t *in, int32_t att_len,
float M, float oscale, int64_t ld, int l) {
switch(l) {
case 1:
return i32_scale_attlen_softmax_scale_i8<16, 1>::run(out, in, att_len,
M, oscale, ld);
case 2:
return i32_scale_attlen_softmax_scale_i8<16, 2>::run(out, in, att_len,
M, oscale, ld);
case 3:
return i32_scale_attlen_softmax_scale_i8<16, 3>::run(out, in, att_len,
M, oscale, ld);
case 4:
return i32_scale_attlen_softmax_scale_i8<16, 4>::run(out, in, att_len,
M, oscale, ld);
case 5:
return i32_scale_attlen_softmax_scale_i8<16, 5>::run(out, in, att_len,
M, oscale, ld);
case 6:
return i32_scale_attlen_softmax_scale_i8<16, 6>::run(out, in, att_len,
M, oscale, ld);
case 7:
return i32_scale_attlen_softmax_scale_i8<16, 7>::run(out, in, att_len,
M, oscale, ld);
case 8:
return i32_scale_attlen_softmax_scale_i8<16, 8>::run(out, in, att_len,
M, oscale, ld);
case 9:
return i32_scale_attlen_softmax_scale_i8<16, 9>::run(out, in, att_len,
M, oscale, ld);
case 10:
return i32_scale_attlen_softmax_scale_i8<16, 10>::run(out, in, att_len,
M, oscale, ld);
case 11:
return i32_scale_attlen_softmax_scale_i8<16, 11>::run(out, in, att_len,
M, oscale, ld);
case 12:
return i32_scale_attlen_softmax_scale_i8<16, 12>::run(out, in, att_len,
M, oscale, ld);
case 13:
return i32_scale_attlen_softmax_scale_i8<16, 13>::run(out, in, att_len,
M, oscale, ld);
case 14:
return i32_scale_attlen_softmax_scale_i8<16, 14>::run(out, in, att_len,
M, oscale, ld);
case 15:
return i32_scale_attlen_softmax_scale_i8<16, 15>::run(out, in, att_len,
M, oscale, ld);
case 16:
return i32_scale_attlen_softmax_scale_i8<16, 16>::run(out, in, att_len,
M, oscale, ld);
}
auto l1 = l/2;
auto l2 = l - l1;
auto pin = reinterpret_cast<int32_t (*)[ld]>(in);
auto pout = reinterpret_cast<int8_t (*)[ld]>(out);
f_i32_scale_softmax_scale_i8(pout[0], pin[0], att_len, M, oscale, ld, l1);
f_i32_scale_softmax_scale_i8(pout[l1], pin[l1], att_len, M, oscale, ld, l2);
}
template <int vec_length>
void i_softmax_tpp<vec_length>::ref(
void *out, void *in, float *att_mask, float M, float oscale) {
# pragma omp parallel for collapse(2)
for (auto d0 = 0; d0 < dim0; ++ d0) {
for (auto d1 = 0; d1 < dim1; ++ d1) {
auto* p_att_mask = reinterpret_cast<float (*)[1 * 1 * dim3]>(att_mask);
auto* p_in = reinterpret_cast<int32_t (*)[dim1][dim2 * dim3]>(in);
auto* p_out = reinterpret_cast<int8_t (*)[dim1][dim2 * dim3]>(out);
f_i32_scale_softmax_scale_i8(
p_out[d0][d1], p_in[d0][d1], p_att_mask[d0], M, oscale, dim3, dim2);
}
}
}
// Accept attention mask as attention length
template <int vec_length>
void i_softmax_tpp<vec_length>::ref(
void *out, void *in, int32_t* att_lens, float M, float oscale) {
# pragma omp parallel for collapse(2)
for (auto d0 = 0; d0 < dim0; ++ d0) {
for (auto d1 = 0; d1 < dim1; ++ d1) {
auto* p_in = reinterpret_cast<int32_t (*)[dim1][dim2 * dim3]>(in);
auto* p_out = reinterpret_cast<int8_t (*)[dim1][dim2 * dim3]>(out);
f_i32_scale_softmax_scale_i8(
p_out[d0][d1], p_in[d0][d1], att_lens[d0], M, oscale, dim3, dim2);
}
}
}
template void i_softmax_tpp<8>::ref(void *, void *, float *, float, float);
template void i_softmax_tpp<16>::ref(void *, void *, float *, float, float);
template void i_softmax_tpp<8>::ref(void *, void *, int32_t *, float, float);
template void i_softmax_tpp<16>::ref(void *, void *, int32_t *, float, float);
}
|
8fc3ce719a5a4562a8d6bbf787628c23f7feaeec
|
69c9db81c9d4e8a491ce2051548263872dedbd1e
|
/SynchiveMonitor/SynchiveMonitor/WinTaskScheduler.cpp
|
e9da96d262ed91890ac9224b5f3c282da2725fcb
|
[] |
no_license
|
tonyhsu17/SynchiveMonitor
|
cffea581f8024785f0ec66249137e7a1b1bc5086
|
d018c8dda34879d1088f303e383831827f871ebc
|
refs/heads/master
| 2021-01-17T17:17:34.217846
| 2017-01-08T22:32:21
| 2017-01-08T22:32:21
| 61,244,685
| 1
| 0
| null | 2016-12-24T08:13:25
| 2016-06-15T22:15:02
|
C++
|
UTF-8
|
C++
| false
| false
| 2,115
|
cpp
|
WinTaskScheduler.cpp
|
#include "stdafx.h"
#include "WinTaskScheduler.h"
String^ WinTaskScheduler::createOnLogonTask()
{
if(checkVersion() > 0)
{
return "";
}
String^ filePath = kStoragePath + kFileName;
String^ args = "/create /tn " + kEventSchTskName + " /tr \"" + (filePath + " " + kStartAllKeyword) + "\" /sc onlogon /f";
return executeTaskSchCommandLine(args);
}
String^ WinTaskScheduler::executeTaskSchCommandLine(String^ args)
{
Process^ p = gcnew Process();
ProcessStartInfo^ ps = gcnew ProcessStartInfo("schtasks", args);
ps->RedirectStandardOutput = true;
ps->UseShellExecute = false;
p->StartInfo = ps;
p->Start();
StreamReader^ sc = p->StandardOutput;
return sc->ReadToEnd();
}
// get important information out of schtask output
/*
Folder:
HostName: XXX
TaskName: Synchive\FolderName
Next Run Time:
Status:
Logon Mode:
*/
Double WinTaskScheduler::checkVersion()
{
String^ args = "/query /fo list";
String^ str = executeTaskSchCommandLine(args);
StringReader^ r = gcnew StringReader(str);
String^ line;
array<wchar_t>^ filter = {' '};
while((line = r->ReadLine()) != nullptr)
{
if(line->Length == 0)
{
continue; // skip empty lines
}
array<String^>^ splitStr = line->Split(filter, 2);
// since system lists by folder, scan per folder
if(splitStr[0] == "Folder:" && splitStr[1]->Contains(kEventSchedulerFolder))
{
// while within folder read each line
while((line = r->ReadLine()) != nullptr && !line->StartsWith("Folder"))
{
splitStr = line->Split(filter, 2, StringSplitOptions::RemoveEmptyEntries);
if(splitStr->Length > 0 && splitStr[0] == "TaskName:")
{
array<String^>^ versionFilter = {"_v"};
array<String^>^ trimmed = splitStr[1]->Split(versionFilter, StringSplitOptions::RemoveEmptyEntries);
return Double::Parse(trimmed[1]);
}
}
}
}
return 0; // no task found
}
// Manually update task scheduler so other versions can be deleted
// Will always try to find latest version to run anyways
String ^ WinTaskScheduler::updateVersion()
{
throw gcnew System::NotImplementedException();
// TODO: insert return statement here
}
|
5fb69edb1f37813628607674e79a18209cd06e0b
|
7a00cb00c5bd71299a4507616b0251c0dc5a0c54
|
/Mrowka/Komorka.cpp
|
12a6802b5dd4481b0065f5ae215cc1f4a6b15476
|
[] |
no_license
|
Kacp3r3/JZO_Langton
|
0de6d8d25114c78940886e63f701d8d4c424bdb2
|
dd831883152935aa0a856988577ffb6d4672eea5
|
refs/heads/master
| 2020-05-30T05:23:56.997484
| 2019-05-31T08:37:13
| 2019-05-31T08:37:13
| 189,558,951
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 153
|
cpp
|
Komorka.cpp
|
#include "Komorka.h"
Komorka::Komorka()
{
}
Komorka::Komorka(size_t x, size_t y, Color cl)
{
_x = x;
_y = y;
c = cl;
}
Komorka::~Komorka()
{
}
|
6a728d371913934f57c2e6abf403c1afb57c73d7
|
42df5c6064fd34c85852a98e821d06b9f4bb61af
|
/BasicPlatformer/TitleScreen.cpp
|
98c712fb3d11ae1e76ecc14e98d3255938dfe9bf
|
[
"Unlicense",
"LicenseRef-scancode-public-domain"
] |
permissive
|
luksamuk/BasicPlatformer
|
a8761903526baeac21283349917060bf3f52b60d
|
a476e2fbe7d2ec016d377a647ea90cf27145cec4
|
refs/heads/master
| 2023-04-16T18:14:59.456126
| 2023-04-16T15:33:30
| 2023-04-16T15:33:30
| 57,168,827
| 3
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 8,409
|
cpp
|
TitleScreen.cpp
|
#include "TitleScreen.hpp"
#include "LevelSelectScreen.hpp"
#include "LevelScreen.hpp"
#include "OptionsScreen.hpp"
#include <OficinaFramework/InputSystem.hpp>
using namespace OficinaFramework;
TitleScreen::TitleScreen()
{
SetActive(true);
SetVisible(true);
}
void TitleScreen::Initialize()
{
m_fadetimer = 0;
m_whitefade = 1.0f;
m_fade = 0.0f;
ScreenSystem::Screen::Initialize();
}
void TitleScreen::LoadContent()
{
soundEmitter = new AudioSystem::AudioSource;
effectEmitter = new AudioSystem::AudioSource;
//bgmAudio = AudioSystem::AudioPool::LoadAudio("bgm/titlescreen", AudioSystem::OF_AUDIO_TYPE_OGG);
bgmAudio = AudioSystem::AudioPool::LoadAudio("bgm/titlescreen2", AudioSystem::OF_AUDIO_TYPE_OGG);
sfxNegate = AudioSystem::AudioPool::LoadAudio("sfx/11_wrongway", AudioSystem::OF_AUDIO_TYPE_OGG);
titleLogo = RenderingSystem::TexturePool::LoadTexture("background/titlescreen/title_alt");
titleLogo_black = RenderingSystem::TexturePool::LoadTexture("background/titlescreen/title_black_alt");
menuFont = new RenderingSystem::Font(RenderingSystem::TexturePool::LoadTexture("fonts/levelselect"),
vec2dw(8u), vec2b::One());
optionXPos = (RenderingSystem::GetResolution().toVec2().x / 2.0f) - (menuFont->MeasureString(menuOptions[0], 1.5f).x / 2.0f);
parallax.AppendPiece(new ParallaxPiece("background/titlescreen/parallax/layer0", 1.0f, 0.0f));
parallax.AppendPiece(new ParallaxPiece("background/titlescreen/parallax/layer1", 1.0f, 0.94f));
parallax.AppendPiece(new ParallaxPiece("background/titlescreen/parallax/layer2", 1.0f, 0.9f));
parallax.AppendPiece(new ParallaxPiece("background/titlescreen/parallax/layer3", 1.0f, 0.92f));
parallax.AppendPiece(new ParallaxPiece("background/titlescreen/parallax/layer4_0", 1.0f, 0.9f));
parallax.AppendPiece(new ParallaxPiece("background/titlescreen/parallax/layer4_1", 1.0f, 0.92f));
parallax.AppendPiece(new ParallaxPiece("background/titlescreen/parallax/layer5_3", 1.0f, 0.83f));
parallax.AppendPiece(new ParallaxPiece("background/titlescreen/parallax/layer5_0", 1.0f, 0.81f));
parallax.AppendPiece(new ParallaxPiece("background/titlescreen/parallax/layer5_1", 1.0f, 0.79f));
parallax.AppendPiece(new ParallaxPiece("background/titlescreen/parallax/layer5_2", 1.0f, 0.77f));
ScreenSystem::Screen::LoadContent();
}
void TitleScreen::UnloadContent()
{
delete menuFont;
RenderingSystem::TexturePool::DisposeTexture(titleLogo);
RenderingSystem::TexturePool::DisposeTexture(titleLogo_black);
parallax.UnloadContent();
soundEmitter->Stop();
effectEmitter->Stop();
AudioSystem::AudioPool::UnloadAudio(bgmAudio);
AudioSystem::AudioPool::UnloadAudio(sfxNegate);
delete soundEmitter;
delete effectEmitter;
ScreenSystem::Screen::UnloadContent();
}
void TitleScreen::Update()
{
RenderingSystem::SetCameraPosition(RenderingSystem::GetResolution().toVec2() / 2.0f);
// Debugger
if (InputSystem::PressedKey(SDL_SCANCODE_F1)
// Lstick + RB
|| (InputSystem::PressingButton(InputSystem::GamePadButton::LSTICK)
&& InputSystem::PressedButton(InputSystem::GamePadButton::RSHOULDER1)))
ScreenSystem::SetDebug(!ScreenSystem::IsDebugActive());
else if (InputSystem::PressedKey(SDL_SCANCODE_F2)
|| InputSystem::PressedButton(InputSystem::GamePadButton::LSHOULDER1))
ScreenSystem::Debug_ToggleMinimalist();
// Fullscreen toggle
else if (InputSystem::PressedKey(SDL_SCANCODE_F11))
ScreenSystem::SetFullScreen(!ScreenSystem::IsFullScreen());
// Fade out + transition
if (m_fade > 0.0f && m_fade < 1.0f)
m_fade += 0.1f;
else if (m_fade > 1.0f)
{
m_fade = 1.0f;
switch (m_selection)
{
case 0: // New Game
ScreenSystem::AddScreen(new LevelScreen(23u));
RemoveMe();
break;
case 1: // Level Select
ScreenSystem::AddScreen(new LevelSelectScreen);
RemoveMe();
break;
case 2: // Extra
break;
case 3: // Options
ScreenSystem::AddScreen(new OptionsScreen);
RemoveMe();
break;
case 4: // Quit
InputSystem::CallExitCommand();
break;
default: break;
}
}
// Option select logic
if (m_menuselection != m_selection)
{
// Option logic
if (m_menuselection < m_selection)
{
optionXPos -= menuSpeed;
if (optionXPos < -menuFont->MeasureString(menuOptions[m_menuselection], 1.5f).x)
{
m_menuselection = m_selection;
optionXPos = RenderingSystem::GetResolution().toVec2().x;
}
}
else if (m_menuselection > m_selection)
{
optionXPos += menuSpeed;
if (optionXPos > float(RenderingSystem::GetResolution().toVec2().x))
{
m_menuselection = m_selection;
optionXPos = -menuFont->MeasureString(menuOptions[m_menuselection], 1.5f).x;
}
}
}
else
{
// Change option
float optionSize = menuFont->MeasureString(menuOptions[m_menuselection], 1.5f).x;
float optionFinalPos = (RenderingSystem::GetResolution().toVec2().x / 2.0f) - (optionSize / 2.0f);
if (abs(optionXPos - optionFinalPos) < menuSpeed)
optionXPos = optionFinalPos;
if (optionXPos < optionFinalPos)
{
optionXPos += menuSpeed;
}
else if (optionXPos > optionFinalPos)
{
optionXPos -= menuSpeed;
}
else
{
if (InputSystem::GetLeftStick().x > 0.0f)
m_selection++;
else if (InputSystem::GetLeftStick().x < 0.0f)
m_selection--;
}
if (m_selection < 0) m_selection = 0;
if (m_selection > m_maxSelection) m_selection = m_maxSelection;
}
// White intro
if(!m_fadetimer) soundEmitter->Play(bgmAudio);
if (m_fadetimer < 42)
{
m_fadetimer++;
if (InputSystem::PressedButton(InputSystem::GamePadButton::START)
|| InputSystem::PressedButton(InputSystem::GamePadButton::A))
m_fadetimer = 42;
}
else if(m_fadetimer >= 42)
{
if (m_whitefade > 0.0f) m_whitefade -= 0.1f;
// Quit
if ((InputSystem::PressedButton(InputSystem::GamePadButton::START)
|| InputSystem::PressedButton(InputSystem::GamePadButton::A))
&& m_fade == 0.0f
&& (m_selection == m_menuselection))
{
// But only if valid
/*if( m_selection == 2 &&
(ScreenSystem::IsFullScreen()
|| RenderingSystem::GetViewportSize().y < 720u)) */
if(m_selection == 2) {
// NOTE: I am deliberately deactivating the Level Editor
// and will delete it pretty shortly. Found it better to
// break it into another project.
effectEmitter->Stop();
effectEmitter->Play(sfxNegate);
}
else m_fade = 0.1f;
}
}
// Parallax
parallax.Update();
}
void TitleScreen::Draw()
{
vec2 viewportPos = RenderingSystem::GetViewportPosition();
vec2 viewportSize = RenderingSystem::GetResolution().toVec2();
RenderingSystem::glClearColorM(m_fadetimer < 42 ? WHITE : BLACK);
// Logo management
RenderingSystem::Texture* currentLogo = m_fadetimer < 42 ? titleLogo_black : titleLogo;
float scale = m_fadetimer < 42 ? float(m_fadetimer) / 42.0f : 1.0f;
// Draw BG
if (m_fadetimer >= 42)
parallax.Draw();
// Draw white background
if (m_fadetimer >= 42 && m_whitefade > 0.0f)
{
glPushMatrix();
glTranslatef(viewportPos.x, viewportPos.y, 0.0f);
OficinaFramework::RenderingSystem::glColorM(WHITE, m_whitefade);
glBegin(GL_QUADS);
glVertex2f(0.0f, 0.0f);
glVertex2f(viewportSize.x, 0.0f);
glVertex2f(viewportSize.x, viewportSize.y);
glVertex2f(0.0f, viewportSize.y);
glEnd();
glPopMatrix();
}
// Draw logo
currentLogo->Draw(vec2(RenderingSystem::GetResolution().toVec2() / 2.0f) - vec2(currentLogo->GetSize().toVec2() * (scale / 2.0f)),
Color4::MaskToColor4(WHITE), scale);
// Draw text
if (m_fadetimer >= 42) {
// Option Select
vec2 optionPos = vec2(RenderingSystem::GetResolution().toVec2() / 2.0f);
optionPos.x = optionXPos;
//optionPos.x -= menuFont->MeasureString(menuOptions[m_menuselection], 1.5f).x / 2.0f;
optionPos.y += optionPos.y - 40.0f;
menuFont->DrawString(optionPos, menuOptions[m_menuselection], 1.5f);
// Disclaimer
std::string disclaimerString =
" v0.4.0\n"
"2016-2023 Lucas S. Vieira\n"
" Not Affiliated with SEGA";
menuFont->DrawString(viewportSize - menuFont->MeasureString(disclaimerString, 1.0f),
disclaimerString);
}
// Fade out
if (m_fade > 0.0f)
{
glPushMatrix();
glTranslatef(viewportPos.x, viewportPos.y, 0.0f);
OficinaFramework::RenderingSystem::glColorM(BLACK, m_fade > 1.0f ? 1.0f : m_fade);
glBegin(GL_QUADS);
glVertex2f(0.0f, 0.0f);
glVertex2f(viewportSize.x, 0.0f);
glVertex2f(viewportSize.x, viewportSize.y);
glVertex2f(0.0f, viewportSize.y);
glEnd();
glPopMatrix();
}
}
|
6804d7185027da2f1447f227f238b20330267118
|
8582495b78eaeb694c921e8453c07bfe6714838c
|
/HTTPServer/HTTPServer.cpp
|
ae3e366755a0bffb428aee849763c27fd4998b38
|
[] |
no_license
|
phamkhacquang/HTTPServer
|
2a842e1d6e0802dbd2023fba0188167e054c3f10
|
8ba1e01b441392262aed4411f11a49082ee8e598
|
refs/heads/master
| 2021-01-01T03:40:44.008848
| 2016-05-13T03:29:55
| 2016-05-13T03:29:55
| 58,187,368
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 13,115
|
cpp
|
HTTPServer.cpp
|
// Simple HTTP Server.cpp : Defines the entry point for the application.
//
#include "stdafx.h"
#include "HTTPServer.h"
#include <WinSock2.h>
#include <stdio.h>
#define MAX_LOADSTRING 100
#define MAX_WND 1024
#define MAX_SOCKET_NUM 2
#define WM_ACCEPT WM_USER + 1
#define WM_RECV WM_USER + 2
#define WM_SOCKET_CLOSE WM_USER + 3
// Global Variables:
HINSTANCE hInst; // current instance
WCHAR szTitle[MAX_LOADSTRING]; // The title bar text
WCHAR szWindowClass[MAX_LOADSTRING]; // the main window class name
HWND g_hwnd[MAX_WND]; //Danh sach cua so da tao
int g_count[MAX_WND]; //So socket cua moi cua so
int g_nWnd = 0; //So luong cua so da tao
// Forward declarations of functions included in this code module:
ATOM MyRegisterClass(HINSTANCE hInstance);
BOOL InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM);
int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPWSTR lpCmdLine,
_In_ int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
// TODO: Place code here.
// Initialize global strings
LoadStringW(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
LoadStringW(hInstance, IDC_HTTPSERVER, szWindowClass, MAX_LOADSTRING);
MyRegisterClass(hInstance);
// Perform application initialization:
if (!InitInstance(hInstance, nCmdShow))
{
return FALSE;
}
HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_HTTPSERVER));
MSG msg;
// Main message loop:
while (GetMessage(&msg, nullptr, 0, 0))
{
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return (int)msg.wParam;
}
//
// FUNCTION: MyRegisterClass()
//
// PURPOSE: Registers the window class.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
WNDCLASSEXW wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDC_HTTPSERVER));
wcex.hCursor = LoadCursor(nullptr, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wcex.lpszMenuName = MAKEINTRESOURCEW(IDC_HTTPSERVER);
wcex.lpszClassName = szWindowClass;
wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
return RegisterClassExW(&wcex);
}
//
// FUNCTION: InitInstance(HINSTANCE, int)
//
// PURPOSE: Saves instance handle and creates main window
//
// COMMENTS:
//
// In this function, we save the instance handle in a global variable and
// create and display the main program window.
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
hInst = hInstance; // Store instance handle in our global variable
HWND hWnd = CreateWindowW(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, nullptr, nullptr, hInstance, nullptr);
if (!hWnd)
{
return FALSE;
}
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
return TRUE;
}
//
// FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
// PURPOSE: Processes messages for the main window.
//
// WM_COMMAND - process the application menu
// WM_PAINT - Paint the main window
// WM_DESTROY - post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
WSADATA DATA;
SOCKET s = INVALID_SOCKET;
SOCKET c = INVALID_SOCKET;
SOCKADDR_IN saddr;
static SOCKADDR_IN caddr;
WIN32_FIND_DATAA FDATA;
int clen;
int i;
static bool sentFirst = true;
char* buffer = NULL;
char* clenstr = NULL;
char* html = NULL;
char* getstr = NULL;
char* folder = NULL;
char* httpstr = NULL;
char* fullpath = NULL;
switch (message)
{
case WM_RECV:
if (LOWORD(lParam) == FD_READ)
{
int portDownload = 10000;
buffer = (char*)calloc(1024, 1);
getstr = (char*)calloc(1024, 1);
folder = (char*)calloc(1024, 1);
httpstr = (char*)calloc(1024, 1);
fullpath = (char*)calloc(1024, 1);
recv((SOCKET)wParam, buffer, 1024, 0);
sscanf(buffer, "%s%s%s", getstr, folder, httpstr);
//Xoa ki tu / thua
if (folder[strlen(folder) - 1] == '/') {
folder[strlen(folder) - 1] = '\0';
}
if (strstr(folder, "%20")) {
char* tmp = folder;
folder = replaceStr(folder, "%20", " ");
free(tmp);
}
free(buffer);
if (strlen(folder + 1) > 0)
sprintf(fullpath, "C:\\%s\\*.*", folder + 1);
else
sprintf(fullpath, "%s", "C:\\*.*");
HANDLE hFind = FindFirstFileA(fullpath, &FDATA);
//Xet dieu kien co la fordel khong, neu la file thi gui file
if ((strcmp(FDATA.cFileName, ".") == 0) || (strlen(folder + 1) == 0)) {
html = (char*)calloc(32768, 1);
sprintf(html, "<h1 class =\"info\">%s</h1>", add_info(caddr));
sprintf(html + strlen(html), "<div class=\"filemanager\"><ul class = \"data animated\">");
sprintf(html + strlen(html), "%s", add_breadcrumbs(folder));
do
{
if (strcmp(FDATA.cFileName, ".") == 0) continue;//Bo qua file "."
if (strlen(folder + 1) == 0) {
if (FDATA.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
sprintf(html + strlen(html), "<li><a href=\"%s\">", getLink(FDATA.cFileName));
sprintf(html + strlen(html), "<span class=\"icon folder full\"></span>");
sprintf(html + strlen(html), "<span class=\"name\">%s</span>", FDATA.cFileName);
sprintf(html + strlen(html), "<span class=\"details\">%s</span>", getNumberOfFolderSubItem(folder, FDATA.cFileName));
sprintf(html + strlen(html), "</a></li>");
}
else {
sprintf(html + strlen(html), "<li><a href=\"%s\">", getLink(FDATA.cFileName));
sprintf(html + strlen(html), "<span class=\"icon file f - %s\">.%s</span>", getFilenameExt(FDATA.cFileName), getFilenameExt(FDATA.cFileName));
sprintf(html + strlen(html), "<span class=\"name\">%s</span>", FDATA.cFileName);
sprintf(html + strlen(html), "<span class=\"details\">%s</span>", getFileSizeString(FDATA.cFileName, folder));
sprintf(html + strlen(html), "</a></li>");
}
}
else {
if (FDATA.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
sprintf(html + strlen(html), "<li><a href=\"%s\/%s\">", getLink(folder + 1), FDATA.cFileName);
sprintf(html + strlen(html), "<span class=\"icon folder full\"></span>");
sprintf(html + strlen(html), "<span class=\"name\">%s</span>", FDATA.cFileName);
sprintf(html + strlen(html), "<span class=\"details\">%s</span>", getNumberOfFolderSubItem(folder, FDATA.cFileName));
sprintf(html + strlen(html), "</a></li>");
}
else {
sprintf(html + strlen(html), "<li><a href=\"%s\/%s\">", getLink(folder + 1), FDATA.cFileName);
sprintf(html + strlen(html), "<span class=\"icon file f-%s\">.%s</span>", getFilenameExt(FDATA.cFileName), getFilenameExt(FDATA.cFileName));
sprintf(html + strlen(html), "<span class=\"name\">%s</span>", FDATA.cFileName);
sprintf(html + strlen(html), "<span class=\"details\">%s</span>", getFileSizeString(FDATA.cFileName, folder));
sprintf(html + strlen(html), "</a></li>");
}
}
} while (FindNextFileA(hFind, &FDATA));
sprintf(html + strlen(html), "</ul></div>");
clenstr = (char*)calloc(1024, 1);
sprintf(clenstr, "Content - length: %d\n", strlen(html) + strlen(top) + strlen(bot));
send((SOCKET)wParam, "HTTP/1.1 200 OK\n", 16, 0);
send((SOCKET)wParam, clenstr, strlen(clenstr), 0);
send((SOCKET)wParam, "Content-Type: text/html\n\n", 25, 0);
send((SOCKET)wParam, top, strlen(top), 0);
send((SOCKET)wParam, html, strlen(html), 0);
send((SOCKET)wParam, bot, strlen(bot), 0);
}
else {
char* fileName = (char*)calloc(1024, 1);
sprintf(fileName, "C:%s", folder);
if (strcmp(getFilenameExt(fileName), "exe") == 0) {
char* run = (char*)calloc(1024, 1);
sprintf(run, "start %s", fileName);
system(run);
free(run);
html = (char*)calloc(32768, 1);
sprintf(html, "<h1 class =\"info\">%s</h1>", add_info(caddr));
sprintf(html + strlen(html), "<div class=\"filemanager\"><ul class = \"data animated\">");
sprintf(html + strlen(html), "%s", add_breadcrumbs(folder));
sprintf(html + strlen(html), "</ul></div>");
sprintf(html + strlen(html), "<h1 class =\"info\">Program is running</h1>");
clenstr = (char*)calloc(1024, 1);
sprintf(clenstr, "Content - length: %d\n", strlen(html) + strlen(top) + strlen(bot));
send((SOCKET)wParam, "HTTP/1.1 200 OK\n", 16, 0);
send((SOCKET)wParam, clenstr, strlen(clenstr), 0);
send((SOCKET)wParam, "Content-Type: text/html\n\n", 25, 0);
send((SOCKET)wParam, top, strlen(top), 0);
send((SOCKET)wParam, html, strlen(html), 0);
send((SOCKET)wParam, bot, strlen(bot), 0);
}
else {
if (sentFirst && ((strcmp(getFilenameExt(fileName), "jpg") == 0) ||
(strcmp(getFilenameExt(fileName), "png") == 0) ||
(strcmp(getFilenameExt(fileName), "bmp") == 0) ||
(strcmp(getFilenameExt(fileName), "gif") == 0))) {
html = (char*)calloc(32768, 1);
sprintf(html, "<h1 class =\"info\">%s</h1>", add_info(caddr));
sprintf(html + strlen(html), "<div class=\"filemanager\"><ul class = \"data animated\">");
sprintf(html + strlen(html), "%s", add_breadcrumbs(folder));
sprintf(html + strlen(html), "</ul></div>");
sprintf(html + strlen(html), "<img src=\"%s\" alt=\"Image\">", getLink(folder + 1));
clenstr = (char*)calloc(1024, 1);
sprintf(clenstr, "Content - length: %d\n", strlen(html) + strlen(top) + strlen(bot));
send((SOCKET)wParam, "HTTP/1.1 200 OK\n", 16, 0);
send((SOCKET)wParam, clenstr, strlen(clenstr), 0);
send((SOCKET)wParam, "Content-Type: text/html\n\n", 25, 0);
send((SOCKET)wParam, top, strlen(top), 0);
send((SOCKET)wParam, html, strlen(html), 0);
send((SOCKET)wParam, bot, strlen(bot), 0);
sentFirst = false;
}
else {
sendFile(fileName, (SOCKET)wParam);
sentFirst = true;
}
}
free(fileName);
}
free(getstr);
free(folder);
free(httpstr);
free(fullpath);
free(clenstr);
free(html);
}
else
{
for (i = 1; i < g_nWnd; i++)
{
if (g_hwnd[i] == hWnd)
break;
}
if (g_count[i] > 0)
g_count[i] -= 1;
}
closesocket((SOCKET)wParam);//Dong socket vi trinh duyet se load lien tuc
break;
case WM_ACCEPT:
clen = sizeof(caddr);
c = accept((SOCKET)wParam, (sockaddr*)&caddr, &clen);
if (g_nWnd == 1) //Moi co 1 cua so chinh
{
//Tao them cua so
HWND hWnd1 = CreateWindowW(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, nullptr, nullptr, hInst, nullptr);
if (hWnd1)
{
g_hwnd[g_nWnd] = hWnd1;
g_count[g_nWnd] = 0;
g_nWnd += 1;
ShowWindow(hWnd1, 0);
UpdateWindow(hWnd1);
}
}
for (i = 1; i < g_nWnd; i++)
{
if (g_count[i] < MAX_SOCKET_NUM)
{
WSAAsyncSelect(c, g_hwnd[i], WM_RECV, FD_READ | FD_CLOSE);
g_count[i] += 1;
//Cua so nay van con co the xu ly them socket
break;
}
}
if (i == g_nWnd) //Khong con cua so nao xu ly them duoc
{
//Tao them cua so
HWND hWnd1 = CreateWindowW(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, nullptr, nullptr, hInst, nullptr);
if (hWnd1)
{
WSAAsyncSelect(c, hWnd1, WM_RECV, FD_READ | FD_CLOSE);
g_hwnd[g_nWnd] = hWnd1;
g_count[g_nWnd] = 1;
g_nWnd += 1;
}
}
break;
case WM_CREATE:
if (g_nWnd == 0)
{
g_hwnd[g_nWnd] = hWnd;
g_count[g_nWnd] = 0;
g_nWnd += 1;
WSAStartup(MAKEWORD(2, 2), &DATA);
s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
saddr.sin_family = AF_INET;
saddr.sin_port = htons(PORT);
saddr.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
bind(s, (sockaddr*)&saddr, sizeof(saddr));
listen(s, 5);
WSAAsyncSelect(s, hWnd, WM_ACCEPT, FD_ACCEPT);
}
break;
case WM_COMMAND:
{
int wmId = LOWORD(wParam);
// Parse the menu selections:
switch (wmId)
{
case IDM_ABOUT:
DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
break;
case IDM_EXIT:
DestroyWindow(hWnd);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
}
break;
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hWnd, &ps);
// TODO: Add any drawing code that uses hdc here...
EndPaint(hWnd, &ps);
}
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
// Message handler for about box.
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam);
switch (message)
{
case WM_INITDIALOG:
return (INT_PTR)TRUE;
case WM_COMMAND:
if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
{
EndDialog(hDlg, LOWORD(wParam));
return (INT_PTR)TRUE;
}
break;
}
return (INT_PTR)FALSE;
}
|
9e4318eb9498c93a1f94de18818002eecf8d1ef6
|
84d98378511f59301f9693b7fe91ee8a4ac76283
|
/7. OOPS - 2/newFractionUse.cpp
|
f3c96e880c728da36f946015fc940701417d0031
|
[] |
no_license
|
SaquibAnwar/Cpp-playground
|
03358e9b7b7d27b8ee6b3c62c1d6ba2b5c01086e
|
523202204b5ed24e162fc51d871afd2cb45f034b
|
refs/heads/master
| 2021-06-23T12:51:41.844899
| 2021-02-05T07:20:19
| 2021-02-05T07:20:19
| 189,625,826
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 747
|
cpp
|
newFractionUse.cpp
|
#include<iostream>
#include "newFraction.cpp"
using namespace std;
int main(){
Fraction f1(10, 3);
Fraction f2(5, 2);
// Fraction f3 = f1.add(f2);
// f1.print();
// f2.print();
// f3.print();
// Fraction f4 = f2 + f3;
// Fraction f5 = f2 * f3;
// f4.print();
// f5.print();
// if(f1 == f2)
// cout << "Equal" << endl;
// else
// cout << "Not Equal" << endl;
// ++f1;
// f1.print();
// Fraction f6 = ++f1;
// f6.print();
// Fraction f3 = ++(++f1);
// f1.print();
// f3.print();
// Fraction f3 = f1++;
// f1.print();
// f3.print();
f1 += f2;
f1.print();
f2.print();
(f1 += f2) += f2;
f1.print();
f2.print();
}
|
bf138784acaa00874631c84efab8fd8c0093ed2d
|
a52f81bf16032336404e31dd68aa88ff664e6831
|
/Game/Object/Wall/WallSystem.hpp
|
7755a3cd422023fa242e399a9db28a1e10e8aeb1
|
[] |
no_license
|
lineCode/SpaceshipWarriorCombatED
|
651a525cedf586eb66c3db6543b07b8c9614c7a9
|
d52e394d781894b2abc63c77c51b844abe2aa53d
|
refs/heads/master
| 2023-03-18T07:39:58.366975
| 2020-11-02T21:13:07
| 2020-11-02T21:13:07
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 590
|
hpp
|
WallSystem.hpp
|
/*
** EPITECH PROJECT, 2019
** SpaceshipWarriorCombatED
** File description:
** WallSystem
*/
#ifndef WALLSYSTEM_HPP_
#define WALLSYSTEM_HPP_
#include <chrono>
#include <ctime>
#include "Wall.hpp"
class WallSystem : public ASystem {
public:
WallSystem();
~WallSystem();
void init();
void update(const std::chrono::time_point<std::chrono::system_clock>&);
void activate(bool, const std::chrono::time_point<std::chrono::system_clock>& now);
private:
std::unique_ptr<IObjet> _wall;
int _size;
};
#endif /* !WALLSYSTEM_HPP_ */
|
bab4b55bb8e192aa1a3fa2b52ad6de3cae048f5c
|
c30d4130c348a2bcf9ab6f847a03fd1d0fed78b4
|
/Codecube/90.cpp
|
50cfb31a2d1e7b1946a826beb40a4c0c09ef92e8
|
[] |
no_license
|
boyplus/competitive-programming
|
6278c5f9c93ce830b62aa16ed4877dc82f5dd538
|
88ead4fddb09ac2ca658ad291c0fc6e8679eedda
|
refs/heads/master
| 2022-11-07T05:31:34.004320
| 2020-06-28T16:09:58
| 2020-06-28T16:09:58
| 67,353,435
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,637
|
cpp
|
90.cpp
|
#include <stdio.h>
void print(int,int);
char str[100][100];
int table[100][100]={0};
int main()
{
int i,j,k,n,m,w,h;
scanf("%d %d",&w,&h);
for(i=0;i<h;i++)
{
scanf("%s",&str[i]);
}
for(i=0;i<h;i++)
{
for(j=0;j<w;j++)
{
if(str[i][j] == '.')
{
table[i][j] = 1;
}
else if(str[i][j]=='^')
{
table[i][j] = 2;
}
else if(str[i][j]=='<')
{
table[i][j] = 3;
}
else if(str[i][j]=='>')
{
table[i][j] = 4;
}
else if(str[i][j] == 'V')
{
table[i][j] = 5;
}
else if(str[i][j] == 'B')
{
table[i][j] = 6;
}
else
{
table[i][j] = -1;
}
}
}
//7 -> - from left or right
//8 -> - from up or down
//10 -> plus sign
for(i=0;i<h;i++)
{
for(j=0;j<w;j++)
{
if(table[i][j] == 2) //^
{
int temp_i = i-1;
while(temp_i>=0&&table[temp_i][j]!=-1)
{
if(table[temp_i][j]==1||table[temp_i][j]==8)
{
table[temp_i][j] = 8;
}
else if(table[temp_i][j]==7)
{
table[temp_i][j] = 10;
}
temp_i--;
}
}
else if(table[i][j] == 5)//V
{
int temp_i = i+1;
while(temp_i<h&&table[temp_i][j]!=-1)
{
if(table[temp_i][j] == 1||table[temp_i][j]==8)
{
table[temp_i][j] = 8;
}
else if(table[temp_i][j] == 7)
{
table[temp_i][j] = 10;
}
temp_i++;
}
}
}
}
for(i=0;i<h;i++)
{
for(j=0;j<w;j++)
{
printf("%2d",table[i][j]);
}
printf("\n");
}
printf("\n");
printf("\n");
print(w,h);
return 0;
}
void print(int w,int h)
{
for(int i=0;i<h;i++)
{
for(int j=0;j<w;j++)
{
printf("%c",str[i][j]);
}
printf("\n");
}
}
|
df860c9fb2581aaaf7c9712e77e5c586cacc21fb
|
73ed0329c341fbe3811b08e1bd36cd2c5b7b49e1
|
/Source/Render/RenderInterface.h
|
cdf3b62c160d5784015ac497614b682f1b3a60d8
|
[
"Unlicense"
] |
permissive
|
Crazykingjammy/bkbotz
|
6e6bb661c91c677aa7b438b09d49cfd52096ffa4
|
6cdaa4164ff02e40f2909982f6dacad161c7d6cf
|
refs/heads/master
| 2020-07-28T23:25:14.667811
| 2019-09-19T14:59:05
| 2019-09-19T14:59:05
| 209,576,581
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,933
|
h
|
RenderInterface.h
|
#ifndef __Render_Interface_h__
#define __Render_Interface_h__
#include "Render.h"
#include "../Object/Object.h"
#include "Lights/Lights.h"
#include "Camera/Camera.h"
#include "Camera/FreeCamera.h"
#include "../Object/2D/2d.h"
#include "../Object/Particles/Particle.h"
#define MAX_LIGHTS 4
class CRenderInterface
{
private:
// Instance
static CRenderInterface *pInstance;
//Default Constructor
CRenderInterface();
//Copy Constructor
CRenderInterface(const CRenderInterface&);
//Assignment Operator
CRenderInterface &operator = (const CRenderInterface&);
//Render system
CRender* m_RenderSystem;
public:
//List of objects.
vector<CBaseObject*> m_ObjectList;
//List of 2D Objects.
vector<CLabel*> m_Objects2D;
//List of particles
vector <CBaseParticleEmitter*> m_ParticleList;
//Lights
CLight Light[MAX_LIGHTS];
//Pointer to the Active Camera
CBaseCamera* m_ActiveCamera;
//Pointer to the world.
CWorld* m_World;
//gosh.. ill put a default camera..........gosh
CFreeCamera m_DefaultCamera_GOSH;
CWorld* m_DefaultWorld;
public:
static void DeleteInstance(void);
static CRenderInterface* GetInstance(void);
public:
//Public Interface.
//Initialize
void Initialize(HINSTANCE hInstance, int Width, int Height, bool Fullscreen, HWND hwnd);
//Update
void Update(float timeDelta);
//Shutdown
void Shutdown();
//Add an object to the list.
void AddObject(CBaseObject* object);
//Add a label on the screen.
void AddLabel(CLabel* label);
//Add a particle to the list.
void AddParticle(CBaseParticleEmitter* emitter);
//Load a model to memory
int LoadModel(char* filename);
//Load a texture to memory
int LoadTexture(char *filename);
//Set to the current active camera.
void SetActiveCamera(CBaseCamera* camera);
//Set the world
void SetWorld(LPCSTR worldmodel);
//Create the Scene
void CreateScene();
//Destroy the Scene;
void DestroyScene();
};
#endif
|
e87ec288c9abf99192360897950bd9e030fdfa2e
|
a5efeeba8379cb72abd5b12538292dd77b5b8a85
|
/include/SAX/helpers/XMLFilterImpl.hpp
|
b605b122d829db91a1b53658fd9857776636da3e
|
[] |
no_license
|
BenKeyFSI/arabica
|
4d48dc3509e8b718ac80cfdbfca81315922e6bec
|
0f0c4e85ec52ac66bf9acbb91bd91bbd72f7baab
|
refs/heads/master
| 2020-12-11T09:14:36.979061
| 2020-04-25T14:30:30
| 2020-04-25T14:30:30
| 55,283,591
| 0
| 0
| null | 2016-04-02T07:41:51
| 2016-04-02T07:41:51
| null |
UTF-8
|
C++
| false
| false
| 17,759
|
hpp
|
XMLFilterImpl.hpp
|
#ifndef ARABICA_XML_FILTER_IMPL_H
#define ARABICA_XML_FILTER_IMPL_H
// XMLFilterImpl.h
#include <SAX/ArabicaConfig.hpp>
#include <string>
#include <SAX/XMLFilter.hpp>
#include <SAX/helpers/DefaultHandler.hpp>
#include <SAX/SAXNotRecognizedException.hpp>
#include <Arabica/StringAdaptor.hpp>
namespace Arabica
{
namespace SAX
{
/**
* Base class for deriving an XML filter.
*
* <p>This class is designed to sit between an {@link XMLReader
* XMLReader} and the client application's event handlers. By default, it
* does nothing but pass requests up to the reader and events
* on to the handlers unmodified, but subclasses can override
* specific methods to modify the event stream or the configuration
* requests as they pass through.</p>
*
* @since SAX 2.0
* @author Jez Higgins,
* <a href="mailto:jez@jezuk.co.uk">jez@jezuk.co.uk</a>
* @version 2.0
* @see XMLFilter
* @see XMLReader
* @see EntityResolver
* @see DTDHandler
* @see ContentHandler
* @see ErrorHandler
*/
template<class string_type, class string_adaptor>
class XMLFilterImpl : public XMLFilter<string_type, string_adaptor>,
public EntityResolver<string_type, string_adaptor>,
public DTDHandler<string_type, string_adaptor>,
public ContentHandler<string_type, string_adaptor>,
public ErrorHandler<string_type, string_adaptor>,
public DeclHandler<string_type, string_adaptor>,
public LexicalHandler<string_type, string_adaptor>
{
public:
typedef XMLReaderInterface<string_type, string_adaptor> XMLReaderT;
typedef EntityResolver<string_type, string_adaptor> EntityResolverT;
typedef DTDHandler<string_type, string_adaptor> DTDHandlerT;
typedef ContentHandler<string_type, string_adaptor> ContentHandlerT;
typedef InputSource<string_type, string_adaptor> InputSourceT;
typedef Locator<string_type, string_adaptor> LocatorT;
typedef ErrorHandler<string_type, string_adaptor> ErrorHandlerT;
typedef DeclHandler<string_type, string_adaptor> DeclHandlerT;
typedef LexicalHandler<string_type, string_adaptor> LexicalHandlerT;
typedef typename ErrorHandler<string_type, string_adaptor>::SAXParseExceptionT SAXParseExceptionT;
typedef DefaultHandler<string_type, string_adaptor> DefaultHandlerT;
XMLFilterImpl() :
parent_(0)
{
setDefaults();
} // XMLFilterImpl
XMLFilterImpl(XMLReaderT& parent) :
parent_(&parent)
{
setDefaults();
} // XMLFilterImpl
virtual ~XMLFilterImpl() { }
/////////////////////////////////////////////////
// XMLFilter implementation
/**
* Set the parent reader.
*
* <p>This is the {@link XMLReader XMLReader} from which
* this filter will obtain its events and to which it will pass its
* configuration requests. The parent may itself be another filter.</p>
*
* <p>If there is no parent reader set, any attempt to parse
* or to set or get a feature or property will fail.</p>
*
* @param parent The parent XML reader.
* @see #getParent
*/
virtual void setParent(XMLReaderT& parent) { parent_ = &parent; }
/**
* Get the parent reader.
*
* @return The parent XML reader, or null if none is set.
* @see #setParent
*/
virtual XMLReaderT* getParent() const { return parent_; }
/////////////////////////////////////////////////
// XMLReader implementation
/**
* Set the state of a feature.
*
* <p>This will always fail if the parent is null.</p>
*
* @param name The feature name.
* @param value The requested feature value.
* @exception SAXNotRecognizedException When the
* XMLReader does not recognize the feature name.
* @exception SAXNotSupportedException When the
* XMLReader recognizes the feature name but
* cannot set the requested value.
* @see XMLReader#setFeature
*/
virtual void setFeature(const string_type& name, bool value)
{
if(!parent_)
{
string_type ex = string_adaptor::construct_from_utf8("Feature: ");
string_adaptor::append(ex, name);
throw SAXNotRecognizedException(string_adaptor::asStdString(ex));
} // if ...
parent_->setFeature(name, value);
} // setFeature
/**
* Look up the state of a feature.
*
* <p>This will always fail if the parent is null.</p>
*
* @param name The feature name.
* @return The current state of the feature.
* @exception SAXNotRecognizedException When the
* XMLReader does not recognize the feature name.
* @exception SAXNotSupportedException When the
* XMLReader recognizes the feature name but
* cannot determine its state at this time.
* @see XMLReader#getFeature
*/
virtual bool getFeature(const string_type& name) const
{
if(!parent_)
{
string_type ex = string_adaptor::construct_from_utf8("Feature: ");
string_adaptor::append(ex, name);
throw SAXNotRecognizedException(string_adaptor::asStdString(ex));
} // if ...
return parent_->getFeature(name);
} // setFeature
/**
* Set the entity resolver.
*
* @param resolver The new entity resolver.
* @see XMLReader#setEntityResolver
*/
virtual void setEntityResolver(EntityResolverT& resolver) { entityResolver_ = &resolver; }
/**
* Get the current entity resolver.
*
* @return The current entity resolver, or null if none was set.
* @see XMLReader#getEntityResolver
*/
virtual EntityResolverT* getEntityResolver() const { return entityResolver_ ; }
/**
* Set the DTD event handler.
*
* @param handler The new DTD handler.
* @see XMLReader#setDTDHandler
*/
virtual void setDTDHandler(DTDHandlerT& handler) { dtdHandler_ = &handler; }
/**
* Get the current DTD event handler.
*
* @return The current DTD handler, or null if none was set.
* @see XMLReader#getDTDHandler
*/
virtual DTDHandlerT* getDTDHandler() const { return dtdHandler_; }
/**
* Set the content event handler.
*
* @param handler The new content handler.
* @see XMLReader#setContentHandler
*/
virtual void setContentHandler(ContentHandlerT& handler) { contentHandler_ = &handler; }
/**
* Get the content event handler.
*
* @return The current content handler, or null if none was set.
* @see XMLReader#getContentHandler
*/
virtual ContentHandlerT* getContentHandler() const { return contentHandler_; }
/**
* Set the error event handler.
*
* @param handler The new error handler.
* @see XMLReader#setErrorHandler
*/
virtual void setErrorHandler(ErrorHandlerT& handler) { errorHandler_ = &handler; }
/**
* Get the current error event handler.
*
* @return The current error handler, or null if none was set.
* @see XMLReader#getErrorHandler
*/
virtual ErrorHandlerT* getErrorHandler() const { return errorHandler_; }
virtual void setDeclHandler(DeclHandlerT& handler) { declHandler_ = &handler; }
virtual DeclHandlerT* getDeclHandler() const { return declHandler_; }
virtual void setLexicalHandler(LexicalHandlerT& handler) { lexicalHandler_ = &handler; }
virtual LexicalHandlerT* getLexicalHandler() const { return lexicalHandler_; }
/**
* Parse a document.
*
* @param input The input source for the document entity.
* @see XMLReader#parse(InputSource)
*/
virtual void parse(InputSourceT& input)
{
setupParse();
parent_->parse(input);
} // parse
public:
//////////////////////////////////////////////////
// EntityResolver
/**
* Filter an external entity resolution.
*
* @param publicId The entity's public identifier, or an empty string.
* @param systemId The entity's system identifier.
* @return A new InputSource or a default-constructed
* <code>InputSourceT</code> for the default.
* @see EntityResolver#resolveEntity
*/
virtual InputSourceT resolveEntity(const string_type& publicId, const string_type& systemId)
{
if(entityResolver_)
return entityResolver_->resolveEntity(publicId, systemId);
return InputSourceT();
} // resolveEntity
//////////////////////////////////////////////////
// DTDHandler
/**
* Filter a notation declaration event.
*
* @param name The notation name.
* @param publicId The notation's public identifier, or an empty string.
* @param systemId The notation's system identifier, or an empty string.
* @see DTDHandler#notationDecl
*/
virtual void notationDecl(const string_type& name,
const string_type& publicId,
const string_type& systemId)
{
dtdHandler_->notationDecl(name, publicId, systemId);
} // notationDecl
/**
* Filter an unparsed entity declaration event.
*
* @param name The entity name.
* @param publicId The entity's public identifier, or an empty string.
* @param systemId The entity's system identifier, or an empty string.
* @param notationName The name of the associated notation.
* @see DTDHandler#unparsedEntityDecl
*/
virtual void unparsedEntityDecl(const string_type& name,
const string_type& publicId,
const string_type& systemId,
const string_type& notationName)
{
dtdHandler_->unparsedEntityDecl(name, publicId, systemId, notationName);
} // unparsedEntityDecl
//////////////////////////////////////////////////
// ContentHandler
/**
* Filter a new document locator event.
*
* @param locator The document locator.
* @see ContentHandler#setDocumentLocator
*/
virtual void setDocumentLocator(const LocatorT& locator)
{
contentHandler_->setDocumentLocator(locator);
} // setDocumentLocator
/**
* Filter a start document event.
*
* @see ContentHandler#startDocument
*/
virtual void startDocument()
{
contentHandler_->startDocument();
} // startDocument
/**
* Filter an end document event.
*
* @see ContentHandler#endDocument
*/
virtual void endDocument()
{
contentHandler_->endDocument();
} // endDocument
/**
* Filter a start Namespace prefix mapping event.
*
* @param prefix The Namespace prefix.
* @param uri The Namespace URI.
* @see ContentHandler#startPrefixMapping
*/
virtual void startPrefixMapping(const string_type& prefix, const string_type& uri)
{
contentHandler_->startPrefixMapping(prefix, uri);
} // startPrefixMapping
/**
* Filter an end Namespace prefix mapping event.
*
* @param prefix The Namespace prefix.
* @see ContentHandler#endPrefixMapping
*/
virtual void endPrefixMapping(const string_type& prefix)
{
contentHandler_->endPrefixMapping(prefix);
} // endPrefixMapping
/**
* Filter a start element event.
*
* @param namespaceURI The element's Namespace URI, or the empty string.
* @param localName The element's local name, or the empty string.
* @param qName The element's qualified (prefixed) name, or the empty
* string.
* @param atts The element's attributes.
* @see ContentHandler#startElement
*/
virtual void startElement(const string_type& namespaceURI, const string_type& localName,
const string_type& qName, const typename ContentHandlerT::AttributesT& atts)
{
contentHandler_->startElement(namespaceURI, localName, qName, atts);
} // startElement
/**
* Filter an end element event.
*
* @param namespaceURI The element's Namespace URI, or the empty string.
* @param localName The element's local name, or the empty string.
* @param qName The element's qualified (prefixed) name, or the empty
* string.
* @see ContentHandler#endElement
*/
virtual void endElement(const string_type& namespaceURI, const string_type& localName,
const string_type& qName)
{
contentHandler_->endElement(namespaceURI, localName, qName);
} // endElement
/**
* Filter a character data event.
*
* @param ch The characters.
* @see ContentHandler#characters
*/
virtual void characters(const string_type& ch)
{
contentHandler_->characters(ch);
} // characters
/**
* Filter an ignorable whitespace event.
*
* @param ch The whitespace
* @see ContentHandler#ignorableWhitespace
*/
virtual void ignorableWhitespace(const string_type& ch)
{
contentHandler_->ignorableWhitespace(ch);
} // ignorableWhitespace
/**
* Filter a processing instruction event.
*
* @param target The processing instruction target.
* @param data The text following the target.
* @see ContentHandler#processingInstruction
*/
virtual void processingInstruction(const string_type& target, const string_type& data)
{
contentHandler_->processingInstruction(target, data);
} // processingInstruction
/**
* Filter a skipped entity event.
*
* @param name The name of the skipped entity.
* @see ContentHandler#skippedEntity
*/
virtual void skippedEntity(const string_type& name)
{
contentHandler_->skippedEntity(name);
} // skippedEntity
//////////////////////////////////////////////////
// ErrorHandler
/**
* Filter a warning event.
*
* @param exception The warning as an exception.
* @see ErrorHandler#warning
*/
virtual void warning(const SAXParseExceptionT& exception)
{
errorHandler_->warning(exception);
} // warning
/**
* Filter an error event.
*
* @param exception The error as an exception.
* @see ErrorHandler#error
*/
virtual void error(const SAXParseExceptionT& exception)
{
errorHandler_->error(exception);
} // error
/**
* Filter a fatal error event.
*
* @param exception The error as an exception.
* @see ErrorHandler#fatalError
*/
virtual void fatalError(const SAXParseExceptionT& exception)
{
errorHandler_->fatalError(exception);
} // fatalError
////////////////////////////////////////////////////////////
// DeclHandler
/**
* Filter an element type declaration.
*/
virtual void elementDecl(const string_type& name, const string_type& model)
{
declHandler_->elementDecl(name, model);
} // elementDecl
/**
* Filter an attribute type declaration.
*/
virtual void attributeDecl(const string_type& elementName,
const string_type& attributeName,
const string_type& type,
const string_type& valueDefault,
const string_type& value)
{
declHandler_->attributeDecl(elementName, attributeName, type, valueDefault, value);
} // attributeDecl
/**
* Filter an internal entity declaration.
*/
virtual void internalEntityDecl(const string_type& name, const string_type& value)
{
declHandler_->internalEntityDecl(name, value);
} // internalEntityDecl
/**
* Filter a parsed external entity declaration.
*/
virtual void externalEntityDecl(const string_type& name,
const string_type& publicId,
const string_type& systemId)
{
declHandler_->externalEntityDecl(name, publicId, systemId);
} // externalEntityDecl
//////////////////////////////////////////////////////////
// LexicalHandler
/**
* Filter the start of DTD declarations, if any.
*/
virtual void startDTD(const string_type& name,
const string_type& publicId,
const string_type& systemId)
{
lexicalHandler_->startDTD(name, publicId, systemId);
} // startDTD
/**
* Filter the end of DTD declarations.
*/
virtual void endDTD()
{
lexicalHandler_->endDTD();
} // endDTD
/**
* Filter the beginning of some internal and external XML entities.
*/
virtual void startEntity(const string_type& name)
{
lexicalHandler_->startEntity(name);
} // startEntity
/**
* Filter the end of an entity.
*/
virtual void endEntity(const string_type& name)
{
lexicalHandler_->endEntity(name);
} // endEntity
/**
* Filter the start of a CDATA section.
*/
virtual void startCDATA()
{
lexicalHandler_->startCDATA();
} // startCDATA
/**
* Filter the end of a CDATA section.
*/
virtual void endCDATA()
{
lexicalHandler_->endCDATA();
} // endCDATA
/**
* Filter an XML comment anywhere in the document.
*/
virtual void comment(const string_type& text)
{
lexicalHandler_->comment(text);
} // comment
private:
void setDefaults()
{
setEntityResolver(defaultHandler_);
setDTDHandler(defaultHandler_);
setContentHandler(defaultHandler_);
setErrorHandler(defaultHandler_);
setDeclHandler(defaultHandler_);
setLexicalHandler(defaultHandler_);
} // setDefaults
void setupParse()
{
parent_->setEntityResolver(*this);
parent_->setDTDHandler(*this);
parent_->setContentHandler(*this);
parent_->setErrorHandler(*this);
parent_->setDeclHandler(*this);
parent_->setLexicalHandler(*this);
} // setupParse
XMLFilterImpl(const XMLFilterImpl&);
XMLFilterImpl& operator=(const XMLFilterImpl&); // no impl
bool operator==(const XMLFilterImpl&); // no impl
XMLReaderT* parent_;
EntityResolverT* entityResolver_;
DTDHandlerT* dtdHandler_;
ContentHandlerT* contentHandler_;
ErrorHandlerT* errorHandler_;
DeclHandlerT* declHandler_;
LexicalHandlerT* lexicalHandler_;
DefaultHandlerT defaultHandler_;
}; // class XMLFilter
} // namespace SAX
} // namespace Arabica
#endif
// end of file
|
f65ad94ddade53ff13b47cfc5742fad84e6ad3c0
|
99f0cd397d6a4b5c3a1d425a285c1ecc3d3e57a3
|
/sketch_nov01a.ino
|
be119743aa6b25887dc4d924197e784d2284ae36
|
[] |
no_license
|
VitalyNikonorov/Arduino-MPU6050
|
160c75774a2bafeef8168e5ec76a0948c3a3d1d2
|
c0fd139d2ab9d4c5c76e281d1e0b069322b6209e
|
refs/heads/master
| 2021-05-31T04:56:33.605774
| 2016-05-14T18:41:57
| 2016-05-14T18:41:57
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,848
|
ino
|
sketch_nov01a.ino
|
#include <SoftwareSerial.h>
int ledpin = 13; // LED connected to pin 48 (on-board LED)
#include "I2Cdev.h"
#include "MPU6050.h"
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
#include "Wire.h"
#endif
SoftwareSerial mySerial(0, 1); // RX, TX
char myChar;
MPU6050 accelgyro;
int incomingByte = 0;
int16_t ax, ay, az;
int16_t gx, gy, gz;
#define OUTPUT_READABLE_ACCELGYRO
#define LED_PIN 13
bool blinkState = false;
bool flag = false;
void setup()
{
pinMode(ledpin, OUTPUT); // pin 48 (on-board LED) as OUTPUT
Serial.begin(9600);
//mySerial.begin(38400);
mySerial.begin(9600);
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
Wire.begin();
#elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
Fastwire::setup(400, true);
#endif
accelgyro.initialize();accelgyro.initialize();
pinMode(LED_PIN, OUTPUT);pinMode(LED_PIN, OUTPUT);
mySerial.print("AT");
delay(1000);
}
void loop() // run over and over
{
if ( mySerial.available() ){
myChar = Serial.read();
if( myChar == 'b' ){
digitalWrite(ledpin, HIGH); // turn ON the LED
flag = true;
}
if (myChar == 'e') {
digitalWrite(ledpin, LOW); // otherwise turn it OFF
flag = false;
}
myChar = 0;
}
if (flag){
// read raw accel/gyro measurements from device
accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
#ifdef OUTPUT_READABLE_ACCELGYRO
// display tab-separated accel/gyro x/y/z values
Serial.print("a/g:\t");
Serial.print(ax); Serial.print("\t");
Serial.print(ay); Serial.print("\t");
Serial.print(az); Serial.print("\t");
Serial.print(gx); Serial.print("\t");
Serial.print(gy); Serial.print("\t");
Serial.println(gz);
#endif
}
}
|
b736fe6c8111c0199e7578c72d9d249014eebfba
|
cdeddf21e84922779350dc1ade310847f5511bee
|
/Cpp/NTP/Zadatak4/Fish.cpp
|
dd71d256f70868ead900312d04c9145d888b51c4
|
[] |
no_license
|
luciantin-old/RandomStf
|
15e92c4d59f374f2622304bf28ddf78e9a825a7d
|
cec7dc40dd97163272b5bc291af276a16b8f954a
|
refs/heads/master
| 2022-11-16T17:35:27.210640
| 2020-07-17T17:39:27
| 2020-07-17T17:39:27
| 240,583,873
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 212
|
cpp
|
Fish.cpp
|
#include "Fish.h"
bool Shark::IsDangerous(){ return isDangerous;}
bool WhiteCatFish::IsCatFish(){ return isCat & isFish;}
bool WhiteCatFish::IsCat(){ return isCat;}
bool WhiteCatFish::IsFish(){ return isFish;}
|
718cf3d7189f917295fe6e5ecbc3e7b27cb1e711
|
a3d6556180e74af7b555f8d47d3fea55b94bcbda
|
/chrome/browser/ui/startup/google_api_keys_infobar_delegate.cc
|
e677d475d354b37b83e08e63933432de5c16f814
|
[
"BSD-3-Clause"
] |
permissive
|
chromium/chromium
|
aaa9eda10115b50b0616d2f1aed5ef35d1d779d6
|
a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c
|
refs/heads/main
| 2023-08-24T00:35:12.585945
| 2023-08-23T22:01:11
| 2023-08-23T22:01:11
| 120,360,765
| 17,408
| 7,102
|
BSD-3-Clause
| 2023-09-10T23:44:27
| 2018-02-05T20:55:32
| null |
UTF-8
|
C++
| false
| false
| 1,540
|
cc
|
google_api_keys_infobar_delegate.cc
|
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/startup/google_api_keys_infobar_delegate.h"
#include <memory>
#include "chrome/browser/infobars/confirm_infobar_creator.h"
#include "chrome/grit/chromium_strings.h"
#include "components/infobars/content/content_infobar_manager.h"
#include "components/infobars/core/infobar.h"
#include "components/strings/grit/components_strings.h"
#include "google_apis/google_api_keys.h"
#include "ui/base/l10n/l10n_util.h"
// static
void GoogleApiKeysInfoBarDelegate::Create(
infobars::ContentInfoBarManager* infobar_manager) {
infobar_manager->AddInfoBar(
CreateConfirmInfoBar(std::unique_ptr<ConfirmInfoBarDelegate>(
new GoogleApiKeysInfoBarDelegate())));
}
GoogleApiKeysInfoBarDelegate::GoogleApiKeysInfoBarDelegate()
: ConfirmInfoBarDelegate() {
}
infobars::InfoBarDelegate::InfoBarIdentifier
GoogleApiKeysInfoBarDelegate::GetIdentifier() const {
return GOOGLE_API_KEYS_INFOBAR_DELEGATE;
}
std::u16string GoogleApiKeysInfoBarDelegate::GetLinkText() const {
return l10n_util::GetStringUTF16(IDS_LEARN_MORE);
}
GURL GoogleApiKeysInfoBarDelegate::GetLinkURL() const {
return GURL(google_apis::kAPIKeysDevelopersHowToURL);
}
std::u16string GoogleApiKeysInfoBarDelegate::GetMessageText() const {
return l10n_util::GetStringUTF16(IDS_MISSING_GOOGLE_API_KEYS);
}
int GoogleApiKeysInfoBarDelegate::GetButtons() const {
return BUTTON_NONE;
}
|
3decf38d8730080edc8e8342e880352201d06c9a
|
5ae79331e507854d00654a8242427eae0869d30a
|
/Test/test/tst_TestStatemachine.cpp
|
9efaf3cf5c969216498c7e1cccb69f93cd04e420
|
[] |
no_license
|
openspaceaarhus/immobilePay
|
42f49a1adc7f2194818884faac91b401ff6e215a
|
8dbc8f4a1d4c8129c675cebede8c12d3c0319a90
|
refs/heads/master
| 2022-12-17T21:00:37.462695
| 2017-04-15T15:32:33
| 2017-04-15T15:32:33
| 294,988,109
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,593
|
cpp
|
tst_TestStatemachine.cpp
|
#include <QString>
#include <QtTest>
#include <memory>
#include "StateMachine.h"
#include "UserDatabase.h"
class TestStatemachine : public QObject
{
Q_OBJECT
public:
TestStatemachine();
private:
std::unique_ptr< boost::sml::sm< OsaaMat::purchaseMachine > > machine;
UserDatabase db;
private Q_SLOTS:
void TestStatemacineStartsUpInIdle();
void TestInvalidUserPutsStateMachineInAddUser();
void TestRejectUserCreationPutsStateMachineInIdle();
void TestAcceptUserCreatesANewUser();
};
TestStatemachine::TestStatemachine()
:db()
{
machine = std::make_unique< boost::sml::sm< OsaaMat::purchaseMachine > >( db );
}
void TestStatemachine::TestStatemacineStartsUpInIdle()
{
using namespace boost::sml;
QVERIFY( machine->is( "Idle"_s ) );
}
void TestStatemachine::TestInvalidUserPutsStateMachineInAddUser()
{
using namespace boost::sml;
machine->process_event( OsaaMat::Login{ "00000000" } );
QVERIFY( machine->is( "NewUser"_s ) );
}
void TestStatemachine::TestRejectUserCreationPutsStateMachineInIdle()
{
using namespace boost::sml;
QVERIFY( machine->is( "NewUser"_s ) );
machine->process_event( OsaaMat::CancelUserCreation{} );
QVERIFY( machine->is( "Idle"_s ) );
}
void TestStatemachine::TestAcceptUserCreatesANewUser()
{
using namespace boost::sml;
machine->process_event( OsaaMat::Login{ "00000001" } );
QVERIFY( machine->is( "NewUser"_s ) );
machine->process_event( OsaaMat::AcceptUserCreation{} );
QVERIFY( machine->is( "Idle"_s ) );
QVERIFY( db.exists( "00000001" ) );
}
QTEST_APPLESS_MAIN(TestStatemachine)
#include "tst_TestStatemachine.moc"
|
728acd98f024bc0936f479144a30d71e7d175808
|
4cd434f48bf76da03503130cb3e9d8611a29a659
|
/iTrace/MeshBaker.h
|
4db36ae3e5aecaf5d9784452f152ac04495885b1
|
[
"MIT"
] |
permissive
|
Ruixel/iTrace
|
39d593856f89664d9c42e570369af146e2098713
|
07e31bb60acba03bc6523986233f16191c502682
|
refs/heads/master
| 2022-12-22T13:44:10.535266
| 2020-10-01T22:43:41
| 2020-10-01T22:43:41
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 446
|
h
|
MeshBaker.h
|
#pragma once
#include <assimp/cimport.h>
#include <assimp/mesh.h>
#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
#include "Core.h"
#include "CustomBlockModel.h"
namespace iTrace {
namespace Rendering {
namespace Chunk {
void ConvertToModel(const std::string& Directory, const std::string& ModelName);
void LoadModelData(CustomBlockModel& Model, const std::string& ModelName);
}
}
}
|
f26de678bf12ebb137281f7f80dde71dd7c4a09d
|
d366d7ad668b560e58ca63bf1d35b471b7cf6031
|
/libraries/Signalling/SignalController.cpp
|
dc0e98a39c41a2c8e1f6ab60c83389452a560ea3
|
[] |
no_license
|
chenbk85/arduino
|
2de76282e583bc75408bfe5649de6720b8606277
|
d39d0c0728d9529410ebbad54f306b5a9227935c
|
refs/heads/master
| 2021-01-17T17:13:56.679937
| 2014-02-15T22:28:39
| 2014-02-15T22:28:39
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,218
|
cpp
|
SignalController.cpp
|
#include "SignalController.h"
SignalController::SignalController() {
this->activePattern = NULL;
for(int i=0; i<10; i++)
this->signalPatterns[i]=NULL;
}
SignalPattern* SignalController::getPattern(int idx) {
if(idx<0 || idx>=10)
return NULL;
return this->signalPatterns[idx];
}
void SignalController::setPattern(int idx, SignalPattern *pattern) {
if(idx<0 || idx>=10)
return;
this->signalPatterns[idx] = pattern;
Serial.print(F("setPattern: "));
Serial.println(idx);
}
void SignalController::start(int idx) {
if(idx<0 || idx>=10)
return;
if(this->signalPatterns[idx] == NULL) {
Serial.println(F("startPattern: no signal pattern"));
return;
}
if(this->activePattern != NULL)
this->activePattern->stop();
this->activePattern = this->signalPatterns[idx];
this->activePattern->start();
// Serial.print(F("startPattern"));
}
void SignalController::stop() {
if(this->activePattern == NULL)
return;
this->activePattern->stop();
this->activePattern = NULL;
}
void SignalController::update() {
if(this->activePattern == NULL)
return;
this->activePattern->update();
/*
for(int i=0; i<10; i++) {
if(this->signalPatterns[i] != NULL)
this->signalPatterns[i]->update();
}
*/
}
|
f9f9e9a16bc1eaf5eb5339fb75090ded30a187b1
|
58a0ba5ee99ec7a0bba36748ba96a557eb798023
|
/GeeksForGeeks/Algorithms/6. Mathematical/22.program-to-efficiently-calculate-ex.cpp
|
f0da5e2cefc027c2d57003630d5c07da6c2913d9
|
[
"MIT"
] |
permissive
|
adityanjr/code-DS-ALGO
|
5bdd503fb5f70d459c8e9b8e58690f9da159dd53
|
1c104c33d2f56fe671d586b702528a559925f875
|
refs/heads/master
| 2022-10-22T21:22:09.640237
| 2022-10-18T15:38:46
| 2022-10-18T15:38:46
| 217,567,198
| 40
| 54
|
MIT
| 2022-10-18T15:38:47
| 2019-10-25T15:50:28
|
C++
|
UTF-8
|
C++
| false
| false
| 349
|
cpp
|
22.program-to-efficiently-calculate-ex.cpp
|
// http://www.geeksforgeeks.org/program-to-efficiently-calculate-ex
#include <iostream>
#include <cstdio>
using namespace std;
float exponential(int n, int x){
float res = 1.0;
for(int i=n-1; i>0; i--){
res = 1 + res*x/i;
}
return res;
}
int main(){
int n = 10;
float x = 1.0f;
printf("e^x = %f", exponential(n, x));
return 0;
}
|
516fe0088d44d758a23a87799ee6967f35aff786
|
4e22d261d7dcf5fe2731d77ba3cfb47c5568977c
|
/Source/Engine/TempestEngine/External/SceneEntityReference.cpp
|
867ce9e47d11819514d2ec6e6dc1ae4ddcc30d2c
|
[] |
no_license
|
SeraphinaMJ/Reformed
|
2d7424d6d38d1cfaf8d385fade474a27c02103a5
|
8563d35ab2b80ca403b3b57ad80db1173504cf55
|
refs/heads/master
| 2023-04-06T00:40:34.223840
| 2021-05-06T11:25:51
| 2021-05-06T11:25:51
| 364,884,928
| 0
| 0
| null | null | null | null |
WINDOWS-1252
|
C++
| false
| false
| 1,221
|
cpp
|
SceneEntityReference.cpp
|
/*!***************************************************************************************
\file SceneEntityReference.cpp
\author Aaron Damyen
\date 7/31/18
\copyright All content © 2018-2019 DigiPen (USA) Corporation, all rights reserved.
\par Project: Boomerang
\brief
*****************************************************************************************/
#include "SceneEntityReference.hpp"
sceneEntityReference::sceneEntityReference()
: m_type{entityType::None}, m_id{0}
{
}
sceneEntityReference::sceneEntityReference(entityType p_type, unsigned int p_id)
: m_type{p_type}, m_id{p_id}
{
}
bool sceneEntityReference::isValid() const
{
return m_type != entityType::None;
}
bool sceneEntityReference::isScene() const
{
return m_type == entityType::Scene;
}
bool sceneEntityReference::isSpace() const
{
return m_type == entityType::Space;
}
bool sceneEntityReference::isObject() const
{
return m_type == entityType::Object;
}
bool sceneEntityReference::isComponent() const
{
return m_type == entityType::Component;
}
sceneEntityReference::entityType sceneEntityReference::getType() const
{
return m_type;
}
unsigned int sceneEntityReference::getID() const
{
return m_id;
}
|
b71ad25330d7c905e2e8a747ce42dd9bc8393b21
|
264eddcd3cd05f86aa6317c2486af6d03efc44f8
|
/lab/test2/a1.cpp
|
b374c570ddd9e63940981a0743684ee54a0203c9
|
[] |
no_license
|
miapurva/OOAD
|
6a6c5be7106a8028cb686baab80dd6a38449fbfe
|
f8dfce390378684c1b4a97aa127529aebaa4e5dc
|
refs/heads/master
| 2021-05-07T17:31:12.495316
| 2017-10-29T14:24:57
| 2017-10-29T14:24:57
| 108,741,512
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,141
|
cpp
|
a1.cpp
|
#include <iostream>
#include <cstdlib>
using namespace std;
#define d 50
int abc(int x,int deno[],int no_of_deno)
{
int quot,rem[d],i,k,r=0,sum=0;
rem[0]={x};
//int res[x]={0};
//int l=0;
int res[x];
X:for(i=0;i<no_of_deno;i++)
{
for(int l=0;l<x;l++)
{
quot=x/deno[i];
if(quot<1)
continue;
else
sum=quot;
res[l++]=sum;
{
LOOP:while(r<d)
{
rem[r++]=rem[r]%deno[i];
if(rem[r++]==0)
goto X;
for(int j=i+1;j<no_of_deno;j++)
{
for(int l=0;l<x;l++)
{
k=rem[r++]/deno[j];
if(k<1)
continue;
else
sum=k;
sum=sum+res[l];
r++;
res[l]=-1;
sum=sum+res[l];
cout<<"\n result"<<res[l++]<<endl;
cout<<"\nSum:\t"<<sum<<"\n";
goto LOOP;
}
}
}
}
}
}
}
int main(void)
{
int no_of_deno,i,x,b;
cout<<"\n Enter value of x"<<endl;
cin>>x;
cout<<"\nEnter the no. of denominations"<<endl;
cin>>no_of_deno;
int deno[no_of_deno];
for(i=0;i<no_of_deno;i++)
{
cout<<"\nEnter the denomination\n";
cin>>deno[i];
}
b=abc(x,deno,no_of_deno);
return(0);
}
|
4425bc9883ac19a351b3704587d01cd92616f3f0
|
48d5d1af9fc728a1a83ac91e2d335df037b57d22
|
/modules/glfw/src/filewatcher.cpp
|
e003be749e7daad8dd1bc17b2c447cb67f67adad
|
[
"BSD-3-Clause",
"BSD-2-Clause"
] |
permissive
|
inviwo/inviwo
|
67601343919f3469c08beddd589df50153557a82
|
f268803cafb5cde2ce640daabbd3ed1ac2c66a87
|
refs/heads/master
| 2023-08-17T04:11:51.970989
| 2023-08-14T13:56:17
| 2023-08-14T13:56:17
| 108,262,622
| 402
| 129
|
BSD-2-Clause
| 2023-09-13T15:19:38
| 2017-10-25T11:47:56
|
C++
|
UTF-8
|
C++
| false
| false
| 12,252
|
cpp
|
filewatcher.cpp
|
/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2020-2023 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include <modules/glfw/filewatcher.h>
#include <inviwo/core/util/assertion.h> // for IVW_ASSERT
#include <inviwo/core/util/logcentral.h> // for LogCentral, LogWarn
#include <inviwo/core/util/stdextensions.h> // for erase_remove
#include <algorithm> // for find
#ifdef WIN32
#include <inviwo/core/common/inviwoapplication.h>
#include <inviwo/core/util/filesystem.h>
#include <inviwo/core/util/threadutil.h>
#include <inviwo/core/util/zip.h>
#include <inviwo/core/util/stringconversion.h>
#include <inviwo/core/util/fileobserver.h>
#include <Windows.h>
#include <array>
#include <mutex>
#include <atomic>
#include <chrono>
#endif
namespace inviwo {
#ifdef WIN32
class WatcherThread {
public:
enum class Action { Added, Removed, Modified };
WatcherThread(
std::function<void(const std::filesystem::path&, const std::filesystem::path&, Action)>
changeCallback)
: changeCallback_{std::move(changeCallback)} {}
~WatcherThread() {
stop_ = true;
thread_.join();
}
bool addObservation(const std::filesystem::path& path) {
std::scoped_lock lock{mutex_};
if (active_ + toAdd_.size() - toRemove_.size() + 1 < MAXIMUM_WAIT_OBJECTS) {
toAdd_.push_back(path);
return true;
} else {
return false;
}
}
void removeObservation(const std::filesystem::path& path) {
std::scoped_lock lock{mutex_};
toRemove_.push_back(path);
}
private:
void remove(const std::vector<std::filesystem::path>& toRemove) {
auto range = util::zip(handles_, observed_);
auto it = std::remove_if(range.begin(), range.end(), [&](auto&& elem) {
return std::find(toRemove.begin(), toRemove.end(), elem.second().first) !=
toRemove.end();
});
for (auto&& [handle, observed] : util::as_range(it, range.end())) {
FindCloseChangeNotification(handle);
observed.first.clear();
observed.second.clear();
--active_;
}
}
void add(const std::vector<std::filesystem::path>& toAdd) {
for (auto& path : toAdd) {
const auto handle = FindFirstChangeNotification(path.c_str(), TRUE, filter);
if (handle == INVALID_HANDLE_VALUE || handle == nullptr) {
LogError("FindFirstChangeNotification function failed.");
continue;
}
handles_[active_] = handle;
observed_[active_].first = path;
for (auto&& elem : std::filesystem::recursive_directory_iterator{path}) {
observed_[active_].second[elem] = std::filesystem::last_write_time(elem);
}
++active_;
}
}
void watch() {
while (!stop_) {
{
std::scoped_lock lock{mutex_};
if (!toRemove_.empty()) {
remove(toRemove_);
toRemove_.clear();
}
if (!toAdd_.empty()) {
add(toAdd_);
toAdd_.clear();
}
}
if (active_ == 0) {
std::this_thread::sleep_for(timeout_);
} else {
const auto status =
WaitForMultipleObjects(static_cast<DWORD>(active_), handles_.data(), FALSE,
static_cast<DWORD>(timeout_.count()));
if (status >= WAIT_OBJECT_0 && status < WAIT_OBJECT_0 + MAXIMUM_WAIT_OBJECTS) {
const auto& path = observed_[status - WAIT_OBJECT_0].first;
auto& files = observed_[status - WAIT_OBJECT_0].second;
const auto changedFiles = getChangedAndUpdateFiles(path, files);
for (auto&& [changedFile, action] : changedFiles) {
changeCallback_(path, changedFile, action);
}
const auto handle = handles_[status - WAIT_OBJECT_0];
FindNextChangeNotification(handle);
}
}
}
for (auto handle : util::as_range(handles_.begin(), handles_.begin() + active_)) {
FindCloseChangeNotification(handle);
}
}
// Update the time stamps on all files and return the changed ones.
std::vector<std::pair<std::filesystem::path, Action>> getChangedAndUpdateFiles(
const std::filesystem::path& path,
std::unordered_map<std::filesystem::path, std::filesystem::file_time_type>& files) {
std::vector<std::pair<std::filesystem::path, Action>> changed;
std::erase_if(files, [&](const auto& item) {
if (!std::filesystem::is_regular_file(item.first)) {
changed.emplace_back(item.first, Action::Removed);
return true;
} else {
return false;
}
});
for (auto&& elem : std::filesystem::recursive_directory_iterator{path}) {
auto it = files.find(elem);
if (it == files.end()) {
changed.emplace_back(elem, Action::Removed);
files[elem] = std::filesystem::last_write_time(elem);
} else {
auto newTime = std::filesystem::last_write_time(elem);
if (newTime > it->second) {
changed.emplace_back(elem, Action::Modified);
it->second = newTime;
}
}
}
return changed;
}
static constexpr DWORD filter =
FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | FILE_NOTIFY_CHANGE_LAST_WRITE;
std::array<HANDLE, MAXIMUM_WAIT_OBJECTS> handles_{};
std::array<
std::pair<std::filesystem::path,
std::unordered_map<std::filesystem::path, std::filesystem::file_time_type>>,
MAXIMUM_WAIT_OBJECTS>
observed_{};
std::atomic<size_t> active_ = 0;
std::function<void(const std::filesystem::path&, const std::filesystem::path&, Action)>
changeCallback_;
std::mutex mutex_;
std::vector<std::filesystem::path> toAdd_;
std::vector<std::filesystem::path> toRemove_;
std::atomic<bool> stop_{false};
std::chrono::milliseconds timeout_{1000};
std::thread thread_{[this]() {
util::setThreadDescription("Inviwo File Watcher Thread");
watch();
}};
};
FileWatcher::FileWatcher(InviwoApplication* app)
: app_{app}
, watcher_{std::make_unique<WatcherThread>([this](const std::filesystem::path& dir,
const std::filesystem::path& path,
WatcherThread::Action) {
auto notifyAboutChanges = [this, dir, path]() {
if (std::filesystem::is_regular_file(path)) {
// don't use iterators here, they might be invalidated.
const auto orgSize = fileObservers_.size();
for (size_t i = 0; i < orgSize && i < fileObservers_.size(); ++i) {
if (fileObservers_[i]->isObserved(path)) {
fileObservers_[i]->fileChanged(path);
}
}
}
if (std::filesystem::is_directory(dir)) {
// don't use iterators here, they might be invalidated.
const auto orgSize = fileObservers_.size();
for (size_t i = 0; i < orgSize && i < fileObservers_.size(); ++i) {
if (fileObservers_[i]->isObserved(dir)) {
fileObservers_[i]->fileChanged(dir);
}
}
}
};
if (app_) {
app_->dispatchFront(notifyAboutChanges);
} else {
notifyAboutChanges();
}
})} {}
FileWatcher::~FileWatcher() = default;
void FileWatcher::registerFileObserver(FileObserver* fileObserver) {
IVW_ASSERT(std::find(fileObservers_.cbegin(), fileObservers_.cend(), fileObserver) ==
fileObservers_.cend(),
"File observer already registered.");
fileObservers_.push_back(fileObserver);
}
void FileWatcher::unRegisterFileObserver(FileObserver* fileObserver) {
const auto it = std::find(fileObservers_.begin(), fileObservers_.end(), fileObserver);
if (it != fileObservers_.end()) {
fileObservers_.erase(it);
}
}
void FileWatcher::startFileObservation(const std::filesystem::path& fileName) {
const bool isDirectory = std::filesystem::is_directory(fileName);
const auto dir = isDirectory ? fileName : fileName.parent_path();
const auto it = observed_.find(dir);
if (it == observed_.end()) {
observed_[dir].insert(fileName);
if (!watcher_->addObservation(dir)) {
LogError("Can't watch more files");
}
} else {
it->second.insert(fileName);
}
}
void FileWatcher::stopFileObservation(const std::filesystem::path& fileName) {
auto observerit =
std::find_if(std::begin(fileObservers_), std::end(fileObservers_),
[fileName](const auto observer) { return observer->isObserved(fileName); });
// Make sure that no observer is observing the file
if (observerit == std::end(fileObservers_)) {
const bool isDirectory = std::filesystem::is_directory(fileName);
const auto dir = isDirectory ? fileName : fileName.parent_path();
const auto it = observed_.find(dir);
if (it != observed_.end()) {
it->second.erase(fileName);
if (it->second.empty()) {
watcher_->removeObservation(dir);
observed_.erase(it);
}
}
}
}
#else
class WatcherThread {
public:
WatcherThread() = default;
};
FileWatcher::FileWatcher(InviwoApplication* app) : app_{app} {
(void)app_;
LogWarn("FileObserver are currently not supported using GLFW on this platform");
}
FileWatcher::~FileWatcher() = default;
void FileWatcher::registerFileObserver(FileObserver* fileObserver) {
IVW_ASSERT(std::find(fileObservers_.cbegin(), fileObservers_.cend(), fileObserver) ==
fileObservers_.cend(),
"File observer already registered.");
fileObservers_.push_back(fileObserver);
}
void FileWatcher::unRegisterFileObserver(FileObserver* fileObserver) {
std::erase(fileObservers_, fileObserver);
}
void FileWatcher::stopFileObservation(const std::filesystem::path& fileName) {}
void FileWatcher::startFileObservation(const std::filesystem::path& fileName) {}
#endif
} // namespace inviwo
|
f0c0fb973741689998ccd22a560b5c6f74beccf5
|
b494c362dd9a3c2ea0629c4e9bb841c1bdd05b6e
|
/SDK/SCUM_BP_WeaponBullet_WoodenArrowMetalTip_functions.cpp
|
3823f7fbfb402ae3ef835d604950eb3efdc35964
|
[] |
no_license
|
a-ahmed/SCUM_SDK
|
6b55076b4aeb5973c4a1a3770c470fccce898100
|
cd5e5089507a638f130cc95a003e0000918a1ec7
|
refs/heads/master
| 2022-05-20T17:28:10.940288
| 2020-04-03T18:48:52
| 2020-04-03T18:48:52
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,328
|
cpp
|
SCUM_BP_WeaponBullet_WoodenArrowMetalTip_functions.cpp
|
// SCUM (Dumped by Hinnie) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "../SDK.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Functions
//---------------------------------------------------------------------------
// Function BP_WeaponBullet_WoodenArrowMetalTip.BP_WeaponBullet_WoodenArrowMetalTip_C.UserConstructionScript
// (Event, Public, BlueprintCallable, BlueprintEvent)
void ABP_WeaponBullet_WoodenArrowMetalTip_C::UserConstructionScript()
{
static auto fn = UObject::FindObject<UFunction>("Function BP_WeaponBullet_WoodenArrowMetalTip.BP_WeaponBullet_WoodenArrowMetalTip_C.UserConstructionScript");
ABP_WeaponBullet_WoodenArrowMetalTip_C_UserConstructionScript_Params fn_params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, &fn_params);
fn->FunctionFlags = flags;
}
// Function BP_WeaponBullet_WoodenArrowMetalTip.BP_WeaponBullet_WoodenArrowMetalTip_C.ReceiveBeginPlay
// (Event, Protected, BlueprintEvent)
void ABP_WeaponBullet_WoodenArrowMetalTip_C::ReceiveBeginPlay()
{
static auto fn = UObject::FindObject<UFunction>("Function BP_WeaponBullet_WoodenArrowMetalTip.BP_WeaponBullet_WoodenArrowMetalTip_C.ReceiveBeginPlay");
ABP_WeaponBullet_WoodenArrowMetalTip_C_ReceiveBeginPlay_Params fn_params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, &fn_params);
fn->FunctionFlags = flags;
}
// Function BP_WeaponBullet_WoodenArrowMetalTip.BP_WeaponBullet_WoodenArrowMetalTip_C.ExecuteUbergraph_BP_WeaponBullet_WoodenArrowMetalTip
// ()
// Parameters:
// int EntryPoint (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
void ABP_WeaponBullet_WoodenArrowMetalTip_C::ExecuteUbergraph_BP_WeaponBullet_WoodenArrowMetalTip(int EntryPoint)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_WeaponBullet_WoodenArrowMetalTip.BP_WeaponBullet_WoodenArrowMetalTip_C.ExecuteUbergraph_BP_WeaponBullet_WoodenArrowMetalTip");
ABP_WeaponBullet_WoodenArrowMetalTip_C_ExecuteUbergraph_BP_WeaponBullet_WoodenArrowMetalTip_Params fn_params;
fn_params.EntryPoint = EntryPoint;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, &fn_params);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
|
827f8601fb3aa9dd2f845481e8fd409a1b1bb6f6
|
4be8bf1a7ae35c094d7ce4d4eb355fd897a6b1a2
|
/passwordKalkulator_C++/lev2.h
|
9289b53547b84604fa489f7eb0c1a2e5866cad57
|
[] |
no_license
|
Perry15/passwordKalculator
|
56461f1033d460be545c2bfa099b0d9f2dd68ca1
|
ae6289100942592201be491231d6d660aa60db7a
|
refs/heads/master
| 2020-05-04T20:43:56.543856
| 2019-04-04T08:06:44
| 2019-04-04T08:06:44
| 179,449,231
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 562
|
h
|
lev2.h
|
#ifndef LEV2_H
#define LEV2_H
#include "password.h"
#include <iostream>
using namespace std;
class lev2 : public Password{
private:
const int lenMin;
QString description;
public:
lev2(QString p="00000000");
~lev2();
virtual QString combination1(const startingData &d1, const startingData &d2);
virtual QString combination2(const startingData &d1, const startingData &d2);
virtual QString combination3(const startingData &d1, const startingData &d2);
virtual QString getDescription() const;
};
#endif // LEV2_H
|
6627f151cb4212310fa4c755a8bfee3a6fe25650
|
d0b04ba4a1b1e95a5e205d33b9704791279ef157
|
/programs/bailey/bailey.ino
|
eaafd3d4d080409e269d9600d43c62a0b85fdfbe
|
[] |
no_license
|
bsswartz/hexbright
|
787d3a732e24eb01c6e0e05f6fc2a3064f81ab96
|
420ad478dc6bb56dcc1fbaba543d655627a31ea6
|
refs/heads/master
| 2021-01-17T23:25:21.057645
| 2013-08-22T23:47:57
| 2013-08-22T23:47:57
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,808
|
ino
|
bailey.ino
|
/*
Copyright (c) 2013, "Bailey Swartz" <bsswartz@gmail.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
#include <hexbright.h>
#include <Wire.h>
// Modes
#define MODE_OFF 0
#define MODE_RUNNING 1
static char mode = MODE_OFF;
static const int click = 350; // Maximum duration of a normal click (milliseconds)
hexbright hb;
void setup() {
// We just powered on! That means either we got plugged
// into USB, or the user is pressing the power button.
hb.init_hardware();
}
void loop() {
//Have the HexBright library handle the boring stuff!
hb.update();
if(!hb.printing_number()) {
hb.print_power();
}
// When a normal click is encountered, perform state transitions.
// This only happens once for a transition, only perform
// initialization tasks!!!
if(hb.button_just_released() && hb.button_pressed_time() < click) {
switch(mode){
// We are off, but someone wants light now... engage light at full power.
case MODE_OFF:
mode=MODE_RUNNING;
hb.set_light(CURRENT_LEVEL, MAX_LEVEL, 50);
break;
// A normal press when the light is on should always turn it off.
default:
mode=MODE_OFF;
hb.shutdown();
break;
}
}
// The button is beind held down, check if we are in a button long-hold condition.
if (hb.button_pressed()) {
if (hb.button_pressed_time() > click) {
// If the hold is from an off state, give the user some medium light.
if (mode != MODE_RUNNING) {
mode=MODE_RUNNING;
hb.set_light(CURRENT_LEVEL, 500, 50);
}
}
if (hb.button_pressed_time() > 2*click) {
// It has been longer, do angle adjust mode.
adjustLED();
}
}
}
int adjustLED() {
double angle = hb.difference_from_down(); // Between 0 (straight down) and 1 (straight up)
int intensity = (int)(angle * 2 * MAX_LEVEL); // Translate to light intensity range.
//Force intensity value to be within range. Truncating at MAX_LEVEL
//from the total range of 2 * MAX_LEVEL has the effect
//of creating full intensity at horizontal level and above.
intensity = (intensity > MAX_LEVEL) ? MAX_LEVEL : intensity;
intensity = (intensity <= 0) ? 1 : intensity;
mode=MODE_RUNNING;
hb.set_light(CURRENT_LEVEL, intensity, 100);
return intensity;
}
|
57e802203f31486981665a50a3d2886a1874654a
|
a15c6b9ad62e06e3c1a054c13d6109cc1f1f1039
|
/Student.h
|
dee0168e05b462a71905e71cc33b6295da1e673b
|
[] |
no_license
|
kholland57/CPSC350-Assignment4
|
82c5c12579d2171a81738d6695972237fc2d4128
|
38b34e9b3d42153d45566260cd090f56ec09bdc7
|
refs/heads/master
| 2022-04-21T17:30:28.599578
| 2020-04-24T03:23:21
| 2020-04-24T03:23:21
| 258,393,228
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 918
|
h
|
Student.h
|
/*
Kelsey Holland
002298547
kholland@chapman.edu
CPSC-350-02
Assignment 4
*/
//Libraries Included Here
#include <string>
#include <iostream>
using namespace std;
#ifndef STUDENT_H
#define STUDENT_H
class Student
{
public:
//Constructors
Student();
Student(int waitTime, int timeAtWindow, bool atWindow, int idnum);
Student(const Student& origStudent);
~Student();
//Accessors and Mutators
int getWaitTime();
void setWaitTime(int newTime);
void incWaitTime();
void setTimeAtWindow(int newTime);
int getTimeAtWindow();
void decTimeAtWindow();
void setAtWindow(bool isAtWindow);
bool getAtWindow();
//Assignment operator and cout overwritting
Student& operator=(const Student& origStudent);
friend std::ostream& operator<<(std::ostream& os, const Student& student);
private:
//Private Variables
int waitTime;
int timeAtWindow;
bool atWindow;
int idnum;
};
#endif
|
85f5401ccaba970330581ed3e9a96ee2b57025a3
|
6f86a2533e592fa02428521fc7dfb2ffdc9343d0
|
/examples/stiffened_panel/stiffened_panel.cpp
|
1bc044fbbac9b2dcb63fd842f4b1adf326da3685
|
[
"GPL-3.0-only",
"Apache-2.0"
] |
permissive
|
SourangshuGhosh/tacs
|
d3ff6d7b4a36d98ba35aae2b985fd721f7738775
|
1473eec093f3ac2c18ee9759865dc39a15b2e048
|
refs/heads/master
| 2022-11-19T05:33:02.127603
| 2020-07-22T13:08:44
| 2020-07-22T13:08:44
| 278,541,353
| 4
| 1
|
Apache-2.0
| 2020-07-21T07:08:02
| 2020-07-10T04:52:46
|
C++
|
UTF-8
|
C++
| false
| false
| 13,833
|
cpp
|
stiffened_panel.cpp
|
#include "TACSAssembler.h"
#include "TACSBuckling.h"
#include "TACSToFH5.h"
#include "TACSMeshLoader.h"
#include "MITCShell.h"
#include "isoFSDTStiffness.h"
#include "TACSPanelAnalysis.h"
/*
The TACSPanelAnalysis object cannot be used in complex mode because
the underlying implementation uses eigenvalue routines from LAPACK
that are not "complexified".
*/
#ifndef TACS_USE_COMPLEX
/*
Analyze a stiffened-panel model with a T-stiffener for some combined
loading. This uses the TACSPanelAnalysis code which forms a
finite-strip model of the panel for buckling analysis.
input:
skin: the constitutive object for the skin
base: the constitutive object for the base
stiffener: the constitutive object for the stiffener
theta: the skew angle
Nx: the axial load on the panel
Nxy: the shear load on the panel
use_lapack: use (or don't use) LAPACK routines for eigenvalue analysis
*/
void panel_test( FSDTStiffness *skin, FSDTStiffness *base,
FSDTStiffness *stiffener, TacsScalar theta,
TacsScalar Nx, TacsScalar Nxy, int use_lapack ){
// The number of elements/nodes in the finite-strip model
int nrepeat = 4; // repeat this many segments
int nnodes = 10*nrepeat+1;
int nseg = 10*nrepeat;
int nbeams = 0;
int nmodes = 12;
// The baked-in dimensions of the panel in [mm]
TacsScalar Lx = 450.0;
TacsScalar b = 110.0;
TacsScalar hs = 20.0;
TacsScalar wb = 35.0;
// Create the TACSPanaelAnalysis object
TACSPanelAnalysis *panel = new TACSPanelAnalysis(nnodes, nseg,
nbeams, nmodes, Lx,
theta);
panel->incref();
// Set the size of the Lanczos subspace for the eigenvalue solver
panel->setLanczosSubspaceSize(100);
// Allocate an array to store the nodal locations
TacsScalar *Xpts = new TacsScalar[2*nnodes];
memset(Xpts, 0, 2*nnodes*sizeof(TacsScalar));
// Set the initial segment
int seg = 0, node = 0;
// For each repeating geometry segment (which incorporates a
// stiffener) set the nodal locations from the geometry parameters
//
for ( int k = 0; k < nrepeat; k++ ){
// Set the nodal locations
Xpts[2*node] = b*k;
Xpts[2*(node+1)] = b*k + (1.0/6.0)*(b - wb);
Xpts[2*(node+2)] = b*k + (1.0/3.0)*(b - wb);
Xpts[2*(node+3)] = b*k + 0.5*(b - wb);
Xpts[2*(node+4)] = 0.5*b*(2*k + 1);
Xpts[2*(node+5)] = 0.5*b*(2*k + 1);
Xpts[2*(node+5)+1] = - hs/2.0;
Xpts[2*(node+6)] = 0.5*b*(2*k + 1);
Xpts[2*(node+6)+1] = - hs;
Xpts[2*(node+7)] = 0.5*b*(2*k + 1) + 0.5*wb;
Xpts[2*(node+8)] = 0.5*b*(2*k + 1) + 0.5*wb + (1.0/6.0)*(b - wb);
Xpts[2*(node+9)] = 0.5*b*(2*k + 1) + 0.5*wb + (1.0/3.0)*(b - wb);
Xpts[2*(node+10)] = 0.5*b*(2*k + 1) + 0.5*wb + 0.5*(b - wb);
// Set the connectivity and set the constitutive objects
panel->setSegment(seg, TACSPanelAnalysis::SKIN_SEGMENT,
skin, node, node+1);
panel->setSegment(seg+1, TACSPanelAnalysis::SKIN_SEGMENT,
skin, node+1, node+2);
panel->setSegment(seg+2, TACSPanelAnalysis::SKIN_SEGMENT,
skin, node+2, node+3);
panel->setSegment(seg+3, TACSPanelAnalysis::SKIN_SEGMENT,
base, node+3, node+4);
panel->setSegment(seg+4, TACSPanelAnalysis::STIFFENER_SEGMENT,
stiffener, node+4, node+5);
panel->setSegment(seg+5, TACSPanelAnalysis::STIFFENER_SEGMENT,
stiffener, node+5, node+6);
panel->setSegment(seg+6, TACSPanelAnalysis::SKIN_SEGMENT,
base, node+4, node+7);
panel->setSegment(seg+7, TACSPanelAnalysis::SKIN_SEGMENT,
skin, node+7, node+8);
panel->setSegment(seg+8, TACSPanelAnalysis::SKIN_SEGMENT,
skin, node+8, node+9);
panel->setSegment(seg+9, TACSPanelAnalysis::SKIN_SEGMENT,
skin, node+9, node+10);
node += 10;
seg += 10;
}
// Set the final node locations
Xpts[2*node] = b*nrepeat;
// Set the node locations into the panel object
panel->setPoints(Xpts, nnodes);
// Set which boundary conditions to use within the model
int bc = (4 | 8);
panel->setFirstNodeBC(0, bc);
panel->setLastNodeBC(nnodes-1, bc);
panel->initialize();
// Set the flag for whether to use LAPACK or not
panel->setUseLapackEigensolver(use_lapack);
// Compute all of the loads and record the time
int nloads = 15;
TacsScalar pos_loads[20], neg_loads[20];
double t0 = 0.0;
if (Nx == 0.0){
t0 = MPI_Wtime();
panel->computeBucklingLoads(Nx, Nxy,
pos_loads, nloads, "results/pos_");
panel->computeBucklingLoads(Nx, -Nxy,
neg_loads, nloads, "results/neg_");
t0 = MPI_Wtime() - t0;
for ( int k = 0; k < nloads; k++ ){
printf("pos_load[%2d] = %25.12f\n", k, pos_loads[k]);
}
for ( int k = 0; k < nloads; k++ ){
printf("neg_load[%2d] = %25.12f\n", k, neg_loads[k]);
}
}
else {
t0 = MPI_Wtime();
panel->computeBucklingLoads(Nx, Nxy,
pos_loads, nloads, "results/");
t0 = MPI_Wtime() - t0;
for ( int k = 0; k < nloads; k++ ){
printf("load[%2d] = %25.12f\n", k, pos_loads[k]);
}
}
printf("Solution time: %f\n", t0);
delete [] Xpts;
panel->decref();
}
#endif // TACS_USE_COMPLEX
/*
The following code compares the results of a full buckling
eigenvalue computation in TACS to the approximate calculations
performed using the TACSPanelAnalysis class. This calculation uses a
finite-strip method which restricts the type of panel geometries
that can be analyzed.
The useage of this script is the following:
./stiffened_panel [options]
where [options] consist of the following:
dh: the step length size
shear: use the input file for shear
lapack: use LAPACK routines for the TACSPanelAnalysis
Note:
1. You must generate a .bdf file first by using the other code in
this directory.
2. The results will be written to files in the ./results/ directory.
If no such directory exists, then no results will be written.
*/
int main( int argc, char *argv[] ){
MPI_Init(&argc, &argv);
// Depending on the arguments, load in a different
const char *bdf_file = "axial_stiffened_panel.bdf";
const char *shear_file = "shear_stiffened_panel.bdf";
// Interpret the input flags
double dh = 1e-6;
int shear_flag = 0;
int use_lapack = 0;
for ( int k = 0; k < argc; k++ ){
if (strcmp(argv[k], "shear") == 0){
bdf_file = shear_file;
shear_flag = 1;
}
if (strcmp(argv[k], "lapack") == 0){
use_lapack = 1;
}
if (sscanf(argv[k], "fd=%le", &dh) == 1){
if (dh > 0.1){
dh = 0.1;
}
printf("Using difference step size: %le\n", dh);
}
}
// Get processor rank
int rank = 0;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
// The thickness of the skin, base and stiffener
TacsScalar tskin = 1.0;
TacsScalar tbase = tskin;
TacsScalar tstiff = 1.2*tskin;
// The material properties used for the skin/base and stiffener
TacsScalar rho = 2750.0, E = 70.0e3, nu = 0.3;
TacsScalar kcorr = 5.0/6.0, yield_stress = 464e3;
TacsScalar G = 0.5*E/(1.0 + nu);
// Create the stiffness objects for the skin/base and stiffener
FSDTStiffness *stiff_skin =
new isoFSDTStiffness(rho, E, nu, kcorr,
yield_stress, tskin, 0);
FSDTStiffness *stiff_base =
new isoFSDTStiffness(rho, E, nu, kcorr,
yield_stress, tbase, 1);
FSDTStiffness *stiff_stiffener =
new isoFSDTStiffness(rho, E, nu, kcorr,
yield_stress, tstiff, 2);
// Set the number of design variables in the problem
int ndvs = 3;
// Allocate the elements associated with the skin/stiffener/base
TACSElement *skin = NULL, *base = NULL, *stiffener = NULL;
skin = new MITCShell<4>(stiff_skin, LINEAR, 0);
base = new MITCShell<4>(stiff_base, LINEAR, 1);
stiffener = new MITCShell<4>(stiff_stiffener, LINEAR, 2);
// Set the loading conditions which depends on whether or not a
// shear flag is used
TacsScalar Nx = -1.0, Nxy = 0.0;
if (shear_flag){
Nx = 0.0;
Nxy = 1.0;
}
// When using complex mode, we cannot use the tacs panel analysis
#ifndef TACS_USE_COMPLEX
TacsScalar theta = -15.0/180.0*M_PI;
if (rank == 0){
printf("theta = %8.1f\n", theta*180.0/M_PI);
panel_test(stiff_skin, stiff_base, stiff_stiffener, theta,
Nx, Nxy, use_lapack);
}
#endif // TACS_USE_COMPLEX
// Load in the .bdf file using the TACS mesh loader
TACSMeshLoader *mesh = new TACSMeshLoader(MPI_COMM_WORLD);
mesh->incref();
// Scan the file
mesh->scanBDFFile(bdf_file);
// Set the skin/base/stiffener elements
mesh->setElement(0, skin);
mesh->setElement(1, base);
mesh->setElement(2, stiffener);
// Create the TACSAssembler object
int vars_per_node = 6;
TACSAssembler *tacs = mesh->createTACS(vars_per_node);
tacs->incref();
// Output for visualization
int write_flag = (TACSElement::OUTPUT_NODES |
TACSElement::OUTPUT_DISPLACEMENTS |
TACSElement::OUTPUT_STRAINS |
TACSElement::OUTPUT_STRESSES |
TACSElement::OUTPUT_EXTRAS);
// Create a TACSToFH5 object
TACSToFH5 *f5 = new TACSToFH5(tacs, TACS_SHELL, write_flag);
f5->incref();
int lev_fill = 5000; // ILU(k) fill in
int fill = 8.0; // Expected number of non-zero entries
// These calls compute the symbolic factorization and allocate
// the space required for the preconditioners
FEMat *aux_mat = tacs->createFEMat();
PcScMat *pc = new PcScMat(aux_mat, lev_fill, fill, 1);
aux_mat->incref();
pc->incref();
// Now, set up the solver
int gmres_iters = 15;
int nrestart = 0; // Number of allowed restarts
int is_flexible = 0; // Is a flexible preconditioner?
GMRES *ksm = new GMRES(aux_mat, pc, gmres_iters, nrestart, is_flexible);
ksm->setTolerances(1e-12, 1e-30);
ksm->incref();
// Compute the linearized buckling mode
int max_lanczos = 50;
int neigvals = 4;
double eig_tol = 1e-8;
TacsScalar sigma = 0.15;
// Allocate matrices for the stiffness/geometric stiffness matrix
FEMat *kmat = tacs->createFEMat();
FEMat *gmat = tacs->createFEMat();
// Create a print object for writing output to the screen
int freq = 1;
KSMPrint *ksm_print = new KSMPrintStdout("KSM", rank, freq);
// Allocate the linear buckling analysis object
TACSLinearBuckling *linear_buckling
= new TACSLinearBuckling(tacs, sigma, gmat, kmat, aux_mat, ksm,
max_lanczos, neigvals, eig_tol);
linear_buckling->incref();
linear_buckling->solve(NULL, ksm_print);
f5->writeToFile("results/load_path.f5");
linear_buckling->checkEigenvector(0);
// Extract the eigenvalue
TacsScalar error = 0.0, eigvalue = 0.0;
eigvalue = linear_buckling->extractEigenvalue(0, &error);
// Compute the derivative of the eigenvalue
TacsScalar *fdvSens = new TacsScalar[ ndvs ];
linear_buckling->evalEigenDVSens(0, fdvSens, ndvs);
// Now, compute the FD approximation
TacsScalar *x = new TacsScalar[ ndvs ];
tacs->getDesignVars(x, ndvs);
// Compute the projected derivative. Set the direction such that it
// lies along the positive gradient component directions.
TacsScalar proj = 0.0;
for ( int i = 0; i < ndvs; i++ ){
proj += fabs(fdvSens[i]);
}
#ifdef TACS_USE_COMPLEX
// Use a complex-step perturbation
for ( int i = 0; i < ndvs; i++ ){
if (TacsRealPart(fdvSens[i]) > 0.0){
x[i] = x[i] + TacsScalar(0.0, dh);
}
else {
x[i] = x[i] - TacsScalar(0.0, dh);
}
}
#else
// Use finite-difference perturbation
for ( int i = 0; i < ndvs; i++ ){
if (fdvSens[i] > 0.0){
x[i] = x[i] + dh;
}
else {
x[i] = x[i] - dh;
}
}
#endif // TACS_USE_COMPLEX
// Set the new design variable values
tacs->setDesignVars(x, ndvs);
// Solve the buckling problem again
linear_buckling->solve(NULL, ksm_print);
TacsScalar eigvalue1 =
linear_buckling->extractEigenvalue(0, &error);
// Evaluate the finite-difference or complex-step approximation
#ifdef TACS_USE_COMPLEX
TacsScalar pfd = TacsImagPart(eigvalue1)/dh;
#else
TacsScalar pfd = (eigvalue1 - eigvalue)/dh;
#endif // TACS_USE_COMPLEX
// Write out the projected error
if (rank == 0){
printf("%15s %15s %15s %15s\n",
"<p, df/dx>", "FD", "Err", "Rel err");
printf("%15.8e %15.8e %15.8e %15.8e\n",
TacsRealPart(proj), TacsRealPart(pfd), TacsRealPart(proj - pfd),
TacsRealPart((proj - pfd)/proj));
}
delete [] fdvSens;
delete [] x;
// Write out the results to a file. Iterate through the eigenvectors
// and print out each one using the TACSToFH5 converter
TACSBVec *vec = tacs->createVec();
vec->incref();
for ( int k = 0; k < neigvals; k++ ){
TacsScalar error = 0.0, eigvalue = 0.0;
eigvalue = linear_buckling->extractEigenvector(k, vec, &error);
double Lx = 450.0;
double b = 110.0;
double hs = 20.0;
double wb = 35.0;
if (shear_flag){
TacsScalar Nxy_crit = G*((tskin*(b - wb) +
tbase*wb)/b)*(eigvalue/Lx);
if (rank == 0){
printf("TACS eigs[%2d]: %15.6f\n", k, TacsRealPart(Nxy_crit));
}
}
else {
TacsScalar Nx_crit = E*((tskin*(b - wb) +
tbase*wb + tstiff*hs)/b)*(eigvalue/Lx);
if (rank == 0){
printf("TACS eigs[%2d]: %15.6f\n", k, TacsRealPart(Nx_crit));
}
}
// Set the local variables
tacs->setVariables(vec);
char file_name[256];
sprintf(file_name, "results/tacs_buckling_mode%02d.f5", k);
f5->writeToFile(file_name);
}
linear_buckling->decref();
vec->decref();
mesh->decref();
ksm->decref();
pc->decref();
tacs->decref();
MPI_Finalize();
return (0);
}
|
eaca6afccc9c3cfe3f307050857e65733d457fbe
|
d0121b4428a3fdd06702225b8fe6d9c5971643e3
|
/DFS_Tarjan_TopologicalSort/DFS_Tarjan_TopologicalSort/Source.cpp
|
3a17b8a2cce277401cb3513873db58a85d893ee2
|
[] |
no_license
|
adrianbischin/Algoritmi_Fundamentali
|
c1069115973f7e8427768b18148ecc5f3d8736f0
|
b405671479a6629284fc63e0e2860c2ebaf0ebfa
|
refs/heads/main
| 2023-03-09T13:08:52.499213
| 2021-02-25T15:31:51
| 2021-02-25T15:31:51
| 341,998,497
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 8,033
|
cpp
|
Source.cpp
|
/*
ADRIAN BISCHIN
Group 30228
DFS: complexitatea algoritmului DFS este O(|V| + |E|). Tarjan -> O(|V| + |E|).
Topological sort -> O(|V| + |E|) -> este un DFS cu o stiva in plus.
*/
#include <iostream>
#include <queue>
#include <stack>
#include <iterator>
#include <algorithm>
#include "Profiler.h"
using namespace std;
Profiler profiler("Edges variations");
struct Graph;
struct List
{
Graph* graphNode;
List* next;
};
struct Graph
{
int key;
int color;//0=white, 1=gray, 2=black
List* adj;
int discoveryTime;
int finalTime;
Graph* parent;
};
List* Insert_First(List* list, Graph* key)
{
List* nn = (List*)calloc(1, sizeof(List));
if (nn == NULL)
{
cerr << "\nEroare la alocarea unui nod in lista !!";
exit(1);
}
nn->graphNode = key;
nn->next = list;
list = nn;
return list;
}
void Free_List(List* list)
{
while (list != NULL)
{
List* dn = list;
list = list->next;
free(dn);
}
}
Graph* Generate_Graph(int size, int edges, bool print, bool read)
{
Graph* graph = (Graph*)calloc(size, sizeof(Graph));
if (graph == NULL)
{
cerr << "\nEroare la alocarea grafului !!";
exit(1);
}
for (int i = 0; i < size; i++)
{
graph[i].key = i;
graph[i].color = 0;
graph[i].adj = NULL;
graph[i].discoveryTime = -1;
graph[i].finalTime = -1;
graph[i].parent = NULL;
}
int** adjacent_matrix = (int**)calloc(size, sizeof(int*));
if (adjacent_matrix == NULL)
{
cerr << "\nEroare la alocarea matricei de adiacenta !!";
exit(2);
}
for (int i = 0; i < size; i++)
{
*(adjacent_matrix + i) = (int*)calloc(size, sizeof(int));
if (*(adjacent_matrix + i) == NULL)
{
cerr << "\nEroare la alocarea matricei de adiacenta !!";
exit(2);
}
}
int count = 0, u, v;
if (print)
{
cout << "\nMuchiile grafului sunt:";
}
while (count < edges)
{
if (read)
{
cout << "\nMuchia " << count + 1 << ":\nbaza=";
cin >> u;
cout << "varf=";
cin >> v;
}
else
{
u = rand() % size;
do
{
v = rand() % size;
} while (v == u);
}
if (*(*(adjacent_matrix + u) + v) == 0)
{
count++;
*(*(adjacent_matrix + u) + v) = 1;
(graph + u)->adj = Insert_First((graph + u)->adj, graph + v);
if (print)
{
cout << " (" << u << ", " << v << ")";
}
}
}
for (int i = 0; i < size; i++)
{
free(adjacent_matrix[i]);
}
free(adjacent_matrix);
return graph;
}
void Free_Graph(Graph* graph, int size)
{
for (int i = 0; i < size; i++)
{
Free_List((graph + i)->adj);
}
free(graph);
}
void See_Graph(Graph* graph, int size)
{
cout << "\n\nNodurile grafului (key, finalTime):";
for (int i = 0; i < size; i++)
{
cout << "\n(" << graph[i].key << ", " << graph[i].finalTime << ")";
}
}
void Pretty_Print(Graph* graph, int size, Graph* root, int level)
{
cout << '\n';
for (int i = 1; i <= level; i++)
{
cout << " ";
}
cout << root->key;
for (int i = 0; i < size; i++)
{
if ((graph + i)->parent == root)
{
Pretty_Print(graph, size, graph + i, level + 1);
}
}
}
int myTime;
void DFS_Visit(Graph* graph, Graph* u, int functionParameter)
{
profiler.countOperation("DFS Complexity", functionParameter, 6);//apel = push stiva -> operation, terminare apel = pop stiva -> operation
//=> 4(de mai jos) + 2 = 6
myTime++;
u->discoveryTime = myTime;//operation
u->color = 1;//operation
for (List* v = u->adj; v != NULL; v = v->next)
{
profiler.countOperation("DFS Complexity", functionParameter, 1);
if (v->graphNode->color == 0)
{
profiler.countOperation("DFS Complexity", functionParameter, 1);
v->graphNode->parent = u;
DFS_Visit(graph, v->graphNode, functionParameter);
}
}
u->color = 2;//operation
myTime++;
u->finalTime = myTime;//operation
}
void DFS(Graph* graph, int size, bool print, int functionParameter)
{
myTime = 0;
List* coverageTrees = NULL;
for (int i = 0; i < size; i++)
{
if (graph[i].color == 0)
{
DFS_Visit(graph, graph + i, functionParameter);
if (print)
{
coverageTrees = Insert_First(coverageTrees, graph + i);
}
}
}
if (print)
{
List* p = coverageTrees;
while (coverageTrees)
{
List* dn = coverageTrees;
Pretty_Print(graph, size, coverageTrees->graphNode, 0);
coverageTrees = coverageTrees->next;
free(dn);
}
}
}
int Partition(Graph* graph, int left, int right)
{
int pivot_index = rand() % (right + 1 - left) + left;
swap(graph[pivot_index], graph[right]);
pivot_index = right;
int border = left; //border este indexul primului element din partea celor mai mari decat pivotul
for (int i = left; i < right; i++)
{
if (graph[i].finalTime < graph[pivot_index].finalTime)
{
swap(graph[border], graph[i]);
border++;
}
}
swap(graph[border], graph[right]); //dupa executarea acestui swap, border va fi indexul pivotului (asezat pe pozitia lui finala in sirul sortat)
return border;
}
void QuickSort(Graph* graph, int left, int right)
{
if (left < right)
{
int pivot_index = Partition(graph, left, right);
QuickSort(graph, left, pivot_index - 1);
QuickSort(graph, pivot_index + 1, right);
}
return;
}
void Topological_Sort(Graph* graph, int size, bool print, int functionParameter)
{
QuickSort(graph, 0, size - 1);
}
int globalIndex = 0;
void Strongly_Connected(Graph* graph, stack <int>* lifo, int* index, int* lowlink, bool* onstack, int v)
{
int w;
index[v] = globalIndex;
lowlink[v] = globalIndex;
globalIndex++;
lifo->push(v);
onstack[v] = true;
List* p = graph[v].adj;
while (p)
{
w = p->graphNode->key;
if (index[w] == -1)
{
Strongly_Connected(graph, lifo, index, lowlink, onstack, w);
lowlink[v] = min(lowlink[v], lowlink[w]);
}
else
{
if (onstack[w])
{
lowlink[v] = min(lowlink[v], index[w]);
}
}
p = p->next;
}
if (lowlink[v] == index[v])
{
cout << "\nComponenta tare conexa: ";
do
{
w = lifo->top();
lifo->pop();
onstack[w] = false;
cout << " " << w;
} while (w != v);
}
}
void Tarjan(Graph* graph, int size)
{
int* index = (int*)calloc(size, sizeof(int));
if (!index)
{
cerr << "\nEroare la alocarea vectorului index !!";
exit(4);
}
int* lowlink = (int*)calloc(size, sizeof(int));
if (!lowlink)
{
cerr << "\nEroare la alocarea vectorului lowlink !!";
exit(5);
}
bool* onstack = (bool*)calloc(size, sizeof(bool));
if (!onstack)
{
cerr << "\nEroare la alocarea vectorului onstack !!";
exit(6);
}
stack <int> lifo;
for (int i = 0; i < size; i++)
{
index[i] = -1;
lowlink[i] = -1;
onstack[i] = 0;
}
for (int i = 0; i < size; i++)
{
if (index[i] == -1)
{
Strongly_Connected(graph, &lifo, index, lowlink, onstack, i);
}
}
}
int main()
{
/*DFS DEMO
int size = 9, edges = 9;
Graph* graph = Generate_Graph(size, edges, 1, 1);
DFS(graph, size, 1, 0);
//*/
/*TOPOLOGICAL SORT DEMO
int size = 8, edges = 6;
Graph* graph = Generate_Graph(size, edges, true, false);
DFS(graph, size, 1, 0);
See_Graph(graph, size);
Topological_Sort(graph, size, 1, 0);
See_Graph(graph, size);
//*/
/*TARJAN ALGORITHM DEMO
int size = 6, edges = 10;
Graph* graph = Generate_Graph(size, edges, true, false);
Tarjan(graph, size);
//*/
//*ANALISYS
//EDGES VARIATION
cout << "\nedges";
int size = 100;
for (int edges = 1000; edges <= 4500; edges += 100)
{
cout << "\n" << edges;
Graph* graph = Generate_Graph(size, edges, false, false);
DFS(graph, size, 0, edges);
}
//VERTEX VARIATION
cout << "\nsize";
profiler.reset("Vertex variations");
int edges = 4500;
for (int size = 100; size <= 200; size += 10)
{
cout << "\n" << size;
Graph* graph = Generate_Graph(size, edges, false, false);
DFS(graph, size, 0, size);
}
profiler.showReport();
//*/
return 0;
}
|
9c9d8aec2f03b0f14e82e43a4b527ae8dead4360
|
5c668bf23f2ab23219eb2a4d60640f96fe788906
|
/src/options.h
|
a1cbc96b5ffc686e855ffc7b73e8058ad44a2baf
|
[] |
no_license
|
ctpo6/resmtp
|
d4a6b3087c3eacc29436a1362bbcdb27c2be09f4
|
f9b0e266cc54ba78273d8f8fe81bc5381a62fc91
|
refs/heads/master
| 2021-01-21T04:41:29.068841
| 2020-04-05T21:46:17
| 2020-04-05T21:46:17
| 46,131,482
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,305
|
h
|
options.h
|
#ifndef _OPTIONS_H_
#define _OPTIONS_H_
#include <sys/types.h>
#include <unistd.h>
#include <cstdint>
#include <iostream>
#include <set>
#include <string>
#include <vector>
#if 0
#include <boost/asio.hpp>
#else
#include "asio/asio.hpp"
#endif
#include "log.h"
namespace r = resmtp;
using std::string;
using std::vector;
// these types are needed for boost::program_options validation mechanism
struct uid_value {
uid_value() = default;
explicit uid_value(uid_t u) : uid(u) {}
operator uid_t () const { return uid; }
uid_t uid = 0;
};
struct gid_value {
gid_value() = default;
explicit gid_value(gid_t g) : gid(g) {}
operator gid_t () const { return gid; }
gid_t gid = 0;
};
struct log_value {
log_value() = default;
explicit log_value(r::log l) : log_(l) {}
operator r::log() const { return log_; }
operator int() const { return static_cast<int>(log_); }
r::log log_ = r::log::notice;
};
struct server_parameters {
static constexpr const char * def_config_file = "/etc/resmtp/resmtp.conf";
static constexpr const char * def_pid_file = "/var/run/resmtp/resmtp.pid";
// [proto://]host_name[:port][/url]
// [proto://]host_name[:port]
struct remote_point {
std::string m_proto;
std::string m_host_name;
unsigned int m_port;
std::string m_url;
};
// host_name[:weight]
struct backend_host {
backend_host(std::string s, uint32_t w) : host_name(s), weight(w) {}
std::string host_name;
uint32_t weight; // 0..100; 0 - off, 100 - max
};
// for debug: quit after specified number of sessions
unsigned n_quit_after_;
string config_file_ = def_config_file;
// don't daemonize
bool m_foreground;
// value of this variable is mapped to syslog priority
log_value log_level;
string m_pid_file;
// number of SMTP connections worker threads
uint32_t m_worker_count;
uid_value m_uid;
gid_value m_gid;
// plain SMTP listen point
// ex.: "0.0.0.0:25"
vector<string> m_listen_points;
vector<string> m_ssl_listen_points;
// monitoring listen point
// ex: "0.0.0.0:11311"
string mon_listen_point;
// max number of incoming connections
uint32_t m_connection_count_limit;
// max number of incoming connections per IP
uint32_t m_client_connection_count_limit;
bool m_use_local_relay;
remote_point m_local_relay_host;
vector<string> backend_hosts_str;
// initialized from backend_hosts_str
vector<backend_host> backend_hosts;
// all backend hosts have the same TCP port
uint16_t backend_port;
// spamhaus log file name
// can be empty
// ex.: /spool/logs/resmtp/spamhaus.log
// default: empty
string spamhaus_log_file;
// SMTP greeting string
string m_smtp_banner;
//
// DNS settings
//
// input from cfg
vector<string> dns_ip_str;
// actually used by the program
vector<asio::ip::address_v4> dns_ip;
// tarpitting delay
uint32_t m_tarpit_delay_seconds;
// 'White' IP addresses
vector<string> white_ip_str;
vector<asio::ip::address_v4> white_ip;
// DNSBL hosts
vector<string> dnsbl_hosts;
// DNSWL host
string dnswl_host;
// maximum number of recipients
uint32_t m_max_rcpt_count;
time_t frontend_cmd_timeout;
time_t frontend_data_timeout;
time_t backend_connect_timeout;
time_t backend_cmd_timeout;
time_t backend_data_timeout;
uint32_t m_message_size_limit;
// bool m_remove_headers;
// std::string m_remove_headers_list;
// boost::unordered_set<std::string> m_remove_headers_set;
// remove extra CRLF at the beginning of message DATA?
bool m_remove_extra_cr;
// config: number of allowed recipients
string m_ip_config_file;
bool m_use_tls;
string m_tls_cert_file;
string m_tls_key_file;
// max number of errors an SMTP client allowed to make
uint32_t m_hard_error_limit;
// return: false - program must correctly exit, true - proceed
// on error throws exception
bool parse_config(int argc, char* argv[]);
void init_dns_settings();
void init_white_ip_settings();
void init_backend_hosts_settings();
};
#endif
|
becb811ca2c1fc030b88a865f800e9793cffb0e9
|
311ec343422dea00ea543ef0b61921d605b3a11f
|
/RecipientsBook.h
|
33cd9c4554375913fd4d120aca18a6d8b3a92cb2
|
[] |
no_license
|
Khyho/Ksiazka_Adresowa_Obiektowo
|
48a6fe7bbeb4d6092f23a4026bb119e84a68ca35
|
b57eea3ccd744e733e8f10993d60a67e28a6bef9
|
refs/heads/master
| 2021-09-03T11:58:58.727610
| 2018-01-08T22:34:07
| 2018-01-08T22:34:07
| 115,660,858
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,336
|
h
|
RecipientsBook.h
|
#include <iostream>
#include <cstdlib>
#include "Recipient.h"
#include <windows.h>
#include <cstdio>
#include <fstream>
#include <vector>
#include <sstream>
#include <algorithm>
#include <iterator>
using namespace std;
class RecipientsBook :public Recipient{
string changeCase (string textToChange);
int specifyID (vector <Recipient> &addressBook, int userID);
void loadAllPeopleFromTheFile (vector <Recipient> &addressBook);
void savePeopleToAFile (Recipient person, vector <Recipient> &addressBook);
void savePeopleToTheFileByOverwritingTheFile (vector <Recipient> &addressBook, int userID);
void updateTheRecordInTheAddressBook (vector <Recipient> &addressBook, int idWybranegoAdresata, int choice);
void removal (vector <Recipient> &addressBook, int idUsuwanejOsoby, int userID);
public:
RecipientsBook (int , int , string , string, string, string, string);
void loadPeopleFromAFileForTheLoggedinUser (vector <Recipient> &addressBook, int userID);
void enteringNewRecipientsToTheAddressBook (vector <Recipient> &addressBook, int userID);
void searchByName (vector <Recipient> &addressBook);
void searchBySurname(vector <Recipient> &addressBook);
void viewAll (vector <Recipient> &addressBook);
void deletingRecord (vector <Recipient> &addressBook, int userID);
void editRecord (vector <Recipient> &addressBook, int userID);
};
|
0457801c223e5793b104e1fec400c4b4974d1a7e
|
6f3ca80c0bcf1ba68a4a76fe9e7890670c7cb9b9
|
/Od zera do gier kodera/Ch.4/4.SimpleCast/main.cpp
|
4a6b2317312f6452d561ee86fb1e1f1f647ad9c7
|
[] |
no_license
|
VKiNGpl/Cpp-projects
|
5977ce9696d7f859f6e7b220c45bb87864475295
|
3dbfeba1ec1c8fcf382a75d00cc6ba3311f690ae
|
refs/heads/master
| 2022-09-21T06:48:15.309868
| 2020-06-03T04:31:39
| 2020-06-03T04:31:39
| 197,949,676
| 0
| 0
| null | 2019-07-22T00:06:33
| 2019-07-20T15:38:14
|
C++
|
UTF-8
|
C++
| false
| false
| 372
|
cpp
|
main.cpp
|
#include <iostream>
int main()
{
for (int i = 32; i < 256; i +=4)
{
std::cout << "| " << (char) (i) << " == " << i << " | ";
std::cout << (char) (i + 1) << " == " << i + 1 << " | ";
std::cout << (char) (i + 2) << " == " << i + 2 << " | ";
std::cout << (char) (i + 3) << " == " << i + 3 << " | ";
std::cout << std::endl;
}
return 0;
}
|
f70356ebdc5ad3f32e14a9afa9b48f52256d2088
|
16e130599e881b7c1782ae822f3c52d88eac5892
|
/leetcode/maxStack/mySol2.cpp
|
19f168de726893316c6910578f1a37ee7b313329
|
[] |
no_license
|
knightzf/review
|
9b40221a908d8197a3288ba3774651aa31aef338
|
8c716b13b5bfba7eafc218f29e4f240700ae3707
|
refs/heads/master
| 2023-04-27T04:43:36.840289
| 2023-04-22T22:15:26
| 2023-04-22T22:15:26
| 10,069,788
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 932
|
cpp
|
mySol2.cpp
|
#include "header.h"
class MaxStack {
private:
map<int, vector<list<int>::iterator>> m;
list<int> l;
public:
/** initialize your data structure here. */
MaxStack() {
}
void push(int x) {
l.push_front(x);
m[x].push_back(l.begin());
}
int pop() {
int res = top();
auto iter = m.find(l.front());
if(iter->second.size() > 1) iter->second.pop_back();
else m.erase(iter);
l.pop_front();
return res;
}
int top() {
return l.front();
}
int peekMax() {
return m.rbegin()->first;
}
int popMax() {
int res = peekMax();
l.erase(m.rbegin()->second.back());
auto iter = m.find(res);
if(iter->second.size() > 1) iter->second.pop_back();
else m.erase(iter);
return res;
}
};
int main()
{
//Solution s;
}
|
5d23b26c482737d40cf807ef8dd2ab89cdd406de
|
39a582a9ec775f7f7b818651ed40c0c567b70f45
|
/utils/local_seq_generator.h
|
b74e347a2ad13c81d21a6c8a3ae74a4f9dcbc97c
|
[] |
no_license
|
sky-cfw/comm
|
2fe5427a2f90dc8f95209912d486963e98bd95f2
|
57f6cdf2c43ac5c1bf9c5e6a42a0771ba0e906ac
|
refs/heads/master
| 2022-05-29T10:24:27.278821
| 2022-05-28T16:13:11
| 2022-05-28T16:13:11
| 162,808,664
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,439
|
h
|
local_seq_generator.h
|
#include <sys/types.h>
#include <sys/shm.h>
#include <sys/ipc.h>
#include <errno.h>
#include <string.h>
#include <stdint.h>
#include <string>
class local_seq_generator
{
public:
local_seq_generator( const key_t &key ):
shm_key(key),
inited(false),
shmid(0),
pseq(NULL),
errmsg("")
{
if ( (shmid = shmget(shm_key, sizeof(unsigned int), (IPC_CREAT|0666))) == -1)
{
errmsg = "shmget (" + shm_key + std::string(") error:") + std::string( strerror(errno) );
return ;
}
//
if ( (pseq = (unsigned int *)shmat(shmid, NULL, 0)) == (unsigned int *)-1 )
{
errmsg = "shmat (" + shm_key + std::string(") error:") + std::string( strerror(errno) );
return ;
}
inited = true;
}
~local_seq_generator()
{
if ( pseq != (unsigned int *)-1
&& -1 == shmdt((void *)pseq) )
{
errmsg = "shmdt (" + shm_key + std::string(") error:") + std::string( strerror(errno) );
return ;
}
}
bool is_inited()
{
return inited;
}
//
unsigned int generator_seqno()
{
return __sync_fetch_and_add( pseq, 1 );
}
//
std::string get_last_errmsg()
{
return errmsg;
}
private:
key_t shm_key;
bool inited;
int shmid;
volatile unsigned int *pseq;
std::string errmsg;
};
|
e237d09df9c6d82bb4d17e4d77c3f689954a5800
|
aaf3139fbede85f779ef906866437133f6518fc4
|
/BZRFlag AI/StraightLineCommanderAI.cpp
|
4bc1b343364898d6e7521ca4846c3cdaa8b6a0e8
|
[] |
no_license
|
zygoth/BZRFlag-Project
|
1524de81c4820d9c8d89ce157feac7d128121852
|
59b6a051eeea77e9c458ae4eb5acf990d231322f
|
refs/heads/master
| 2021-01-10T20:29:27.579353
| 2013-06-17T16:08:31
| 2013-06-17T16:08:31
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 829
|
cpp
|
StraightLineCommanderAI.cpp
|
/*
* File: StraightLineCommanderAI.cpp
* Author: zygoth
*
* Created on June 3, 2013, 2:39 PM
*/
#include "StraightLineCommanderAI.h"
#include "StraightLineTankAI.h"
StraightLineCommanderAI::StraightLineCommanderAI(BZRC* connection) : CommanderAI(connection)
{
vector<tank_t> myTanks;
connection->get_mytanks(&myTanks);
for(int i = 0; i < myTanks.size(); i++)
{
tankAIs.push_back(new StraightLineTankAI(connection, i, myColor));
}
}
void StraightLineCommanderAI::controlTeam()
{
vector<tank_t> myTanks;
connection->get_mytanks(&myTanks);
for(int i = 0; i < tankAIs.size(); i++)
{
tankAIs[i]->controlTank();
}
}
StraightLineCommanderAI::~StraightLineCommanderAI()
{
for(int i = 0; i < tankAIs.size(); i++)
{
delete tankAIs[i];
}
}
|
dc4c3ea7a7792d15f02e17e6e73e07a69905f084
|
c9be9c963fbc6591453cdd7cdedee8742991a3b4
|
/disjoint_sets.hpp
|
d3dbad20e663202fc5f5ef773157fe1ed87fa8bc
|
[
"MIT"
] |
permissive
|
mzhong99/maze-generator
|
72215110aa4e67a3d271937b4f73f481487b2fa8
|
4a3cc13390b75eb0677b3aba0c6f30576e5d0aba
|
refs/heads/master
| 2020-04-13T06:26:07.782742
| 2019-01-29T14:34:13
| 2019-01-29T14:34:13
| 163,020,507
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 713
|
hpp
|
disjoint_sets.hpp
|
#ifndef _DISJOINT_SETS_HPP_
#define _DISJOINT_SETS_HPP_
#include <vector>
#include <cstdint>
#include "point.hpp"
class DisjointSets {
private:
uint32_t width, height;
size_t number_of_sets;
std::vector<std::vector<size_t>> sets;
void fill_sets();
public:
DisjointSets();
DisjointSets(uint32_t width, uint32_t height);
// add p2 to the set that has p1
void join(const Point& p1, const Point& p2);
bool is_joined(const Point& p1, const Point& p2) const;
size_t find(const Point& point) const;
std::vector<Point> elements(const size_t set_number) const;
uint32_t get_width() const;
uint32_t get_height() const;
};
#include "disjoint_sets.cpp"
#endif
|
b6e8f83dd565eb0d0df11b64fd2759828947d4ca
|
69654bd7c4910ebc2a7decdb5cd59d42f833c279
|
/engine/debug.cpp
|
c7eba620f57c012a350d97bed81f63fb308bd40a
|
[] |
no_license
|
jensheukers/Battle
|
459058d63b8ff6a50a381f30ca172b1af19f27b5
|
b927a7be3ae56b049bc902039e61a929bca162d3
|
refs/heads/master
| 2023-04-05T09:04:24.200775
| 2021-04-09T13:26:55
| 2021-04-09T13:26:55
| 345,944,494
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,118
|
cpp
|
debug.cpp
|
// Source file for debug class.
//
// Version: 19/9/2019
//
// Copyright (C) Jens Heukers - All Rights Reserved
// Unauthorized copying of this file, via any medium is strictly prohibited
// Proprietary and confidential
// Written by Jens Heukers, September 2019
#include "debug.h"
#include <functional>
#include "imgui.h"
#include "editor.h"
#include "input.h"
#include "luascript.h"
#include "graphics/font.h"
Debug* Debug::instance;
bool Debug::consoleActive = false;
Debug* Debug::GetInstance() {
if (!instance) {
instance = new Debug();
}
return instance;
}
void Debug::Log(std::string message) {
std::string logMessage = LOG_PREFIX + message;
std::cout << logMessage << std::endl;
//Push to logs
static int counter = 0;
static std::string lastLogMessage;
if (GetInstance()->logs.size() > 0 && lastLogMessage == logMessage) {
GetInstance()->logs[GetInstance()->logs.size() - 1] = std::to_string(counter) + " - " + logMessage;
counter++;
}
else {
GetInstance()->logs.push_back(logMessage);
lastLogMessage = logMessage;
counter = 0;
}
if (GetInstance()->logs.size() > MAX_AMOUNT_LOGS_SAVED) {
GetInstance()->logs.erase(GetInstance()->logs.begin());
}
}
void Debug::DrawLine(Vec2 a, Vec2 b, glm::vec3 color) {
Line line;
line.a = a;
line.b = b;
line.color = color;
GetInstance()->_lineDrawList.push_back(line);
}
void Debug::DrawCube(Vec2 a, Vec2 b, glm::vec3 color) {
Line line0; line0.a = a; line0.b = Vec2(b.x, a.y); line0.color = color; GetInstance()->_lineDrawList.push_back(line0);
Line line1; line1.a = Vec2(b.x, a.y); line1.b = b; line1.color = color; GetInstance()->_lineDrawList.push_back(line1);
Line line2; line2.a = b; line2.b = Vec2(a.x, b.y); line2.color = color; GetInstance()->_lineDrawList.push_back(line2);
Line line3; line3.a = Vec2(a.x, b.y); line3.b = a; line3.color = color; GetInstance()->_lineDrawList.push_back(line3);
}
void Debug::DrawText(std::string text, Vec2 position, float size, glm::vec3 color) {
static Font* font = FontLoader::LoadFont("fonts/consola.ttf");
DebugText debugText;
debugText.font = font;
debugText.text = text;
debugText.position = position;
debugText.size = size;
debugText.color = color;
GetInstance()->_textDrawList.push_back(debugText);
}
void Debug::ConstructConsole() {
//Handle events
ImGuiIO& io = ImGui::GetIO();
io.KeysDown[KEYCODE_BACKSPACE] = Input::GetKey(KEYCODE_BACKSPACE);
io.KeysDown[KEYCODE_ENTER] = Input::GetKeyDown(KEYCODE_ENTER);
io.KeysDown[KEYCODE_DOWN] = Input::GetKeyDown(KEYCODE_DOWN);
io.KeysDown[KEYCODE_UP] = Input::GetKeyDown(KEYCODE_UP);
io.KeysDown[KEYCODE_LEFT] = Input::GetKeyDown(KEYCODE_LEFT);
io.KeysDown[KEYCODE_RIGHT] = Input::GetKeyDown(KEYCODE_RIGHT);
ImGui::Begin("Console");
ImGui::SetWindowSize(ImVec2(512, 512));
ImGui::BeginChild("Logs", ImVec2(512, 450));
for (size_t i = 0; i < GetInstance()->logs.size(); i++){
ImGui::Text(GetInstance()->logs[i].c_str());
}
ImGui::EndChild();
static char buffer[128]; // Allocate buffer
ImGui::InputText("", buffer, sizeof(buffer));
std::function<void()> onExecute = [=](){
GetInstance()->logs.push_back(buffer);
//Run on lua
LuaScript::Run(buffer);
GetInstance()->commands.push_back(buffer);
//Clear buffer
for (size_t i = 0; i < 128; i++) {
buffer[i] = '\0';
}
};
if (ImGui::IsItemActive() && Input::GetKeyDown(KEYCODE_ENTER)) {
onExecute();
}
ImGui::SameLine();
if (ImGui::Button("Execute")) {
onExecute();
}
ImGui::SameLine();
if (ImGui::Button("Clear")) {
for (size_t i = 0; i < GetInstance()->logs.size(); i++) {
GetInstance()->logs.erase(GetInstance()->logs.begin() + i);
}
}
ImGui::SameLine();
if (ImGui::Button("Editor")) {
Editor::editorActive = true;
}
ImGui::End();
}
void Debug::Clear() {
for (size_t i = 0; i < GetInstance()->_lineDrawList.size(); i++) {
GetInstance()->_lineDrawList.erase(GetInstance()->_lineDrawList.begin() + i);
}
for (size_t i = 0; i < GetInstance()->_textDrawList.size(); i++) {
GetInstance()->_textDrawList.erase(GetInstance()->_textDrawList.begin() + i);
}
}
|
f736eb581b45125566a9407d02388bf20e0c62f8
|
be8c21ee854de4af539d04faa620722e6ec6f706
|
/DeferredRenderer/LightClass.hpp
|
2360836628b69b9d656f2632a3c66fd39b643ca1
|
[] |
no_license
|
Markyparky56/DeferredRenderer
|
449ebdaaf174c86608c5ca83691dd65b74e4af0d
|
9cef9616131ef217ea6d0a90ab135521fcc0c317
|
refs/heads/master
| 2021-01-23T03:43:48.703263
| 2017-04-04T21:42:17
| 2017-04-04T21:42:17
| 86,117,318
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 752
|
hpp
|
LightClass.hpp
|
#pragma once
#include <DirectXMath.h>
using namespace DirectX;
class LightClass
{
public:
LightClass();
~LightClass();
void SetAmbientColour(float red, float green, float blue, float alpha);
void SetDiffuseColour(float red, float green, float blue, float alpha);
void SetSpecularColour(float red, float green, float blue, float alpha);
void SetDirection(float x, float y, float z);
void SetSpecularPower(float p);
XMFLOAT4 GetAmbientColour();
XMFLOAT4 GetDiffuseColour();
XMFLOAT4 GetSpecularColour();
XMFLOAT3 GetDirection();
float GetSpecularPower();
private:
XMFLOAT4 ambientColour;
XMFLOAT4 diffuseColour;
XMFLOAT4 specularColour;
XMFLOAT3 direction;
float specularPower;
};
|
470b4aefa089504ea04abde3bc8770852216bd67
|
a413e224714c87b41d621a848d040a0ec53e5524
|
/scriptline.cpp
|
c316fbd8ddddac9fba3e9bdff41def810f24abae
|
[] |
no_license
|
Kaythay/RPG
|
c12a14618ccf2a3890b5600ae7ef2f65ad302953
|
b4cbc6b4f7bd701c0ac87f14587415c44c700948
|
refs/heads/master
| 2021-01-19T20:48:00.264516
| 2016-11-10T03:03:56
| 2016-11-10T03:07:59
| 71,415,552
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,810
|
cpp
|
scriptline.cpp
|
#include <iostream>
#include <string>
#include <QObject>
#include "scriptline.h"
//TODO: make exeption for whenever a file line is in the wrong format
Dialog::Dialog(std::string s) {
this->parse(s);
this->next = NULL;
}
/** Method takes the string from the constructor to parse for the speaker, words, and emotion. */
bool Dialog::parse(std::string s){
if ((s[0] == '/' && s[1] == '/')){
this->read = false;
} else {
this->read = true;
int ref = 0;
this->speaker = this->find(s, ref);
this->words = this->find(s, ref);
this->emotion = this->find(s, ref);
this->side = this->findSide(s, ref);
}
return true;
}
/** Returns the substring from the input string, starting from the 'ref' position
* and ending whenever a char equals the 'end' char or null */
std::string Dialog::find(std::string input, int &ref, char end){
std::string temp = "";
while ((input[ref] != end) && (input[ref] != '\0')){
temp.push_back(input[ref]);
ref++;
}
ref++;
return temp;
}
DialogConstants::sideOfScreen Dialog::findSide(std::string input, int &ref, char end){
std::string s = this->find(input, ref, end);
if (s.compare("LEFT")) {
return DialogConstants::LEFT;
} else {
//assume right for invalid inputs
return DialogConstants::RIGHT;
}
}
/** set the next property as a new Dialog */
bool Dialog::setNext(std::string s){
this->next = new Dialog(s);
return true;
}
bool Dialog::readable(){
return this->read;
}
Dialog * Dialog::getNext(){
return this->next;
}
std::string Dialog::getSpeaker(){
return this->speaker;
}
std::string Dialog::getWords(){
return this->words;
}
std::string Dialog::getEmotion(){
return this->emotion;
}
|
431f3a8e9a26dd10e649266908da0aa1fcb56c15
|
6bcdb9e8836cd60e972be865beb50fbfefdfa650
|
/libs/core/include/fcppt/container/bitfield/detail/make_range.hpp
|
e47ce93dd89f2ea528239277b7f32908a76bb150
|
[
"BSL-1.0"
] |
permissive
|
pmiddend/fcppt
|
4dbba03f7386c1e0d35c21aa0e88e96ed824957f
|
9f437acbb10258e6df6982a550213a05815eb2be
|
refs/heads/master
| 2020-09-22T08:54:49.438518
| 2019-11-30T14:14:04
| 2019-11-30T14:14:04
| 225,129,546
| 0
| 0
|
BSL-1.0
| 2019-12-01T08:31:12
| 2019-12-01T08:31:11
| null |
UTF-8
|
C++
| false
| false
| 1,163
|
hpp
|
make_range.hpp
|
// Copyright Carl Philipp Reh 2009 - 2018.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef FCPPT_CONTAINER_BITFIELD_DETAIL_MAKE_RANGE_HPP_INCLUDED
#define FCPPT_CONTAINER_BITFIELD_DETAIL_MAKE_RANGE_HPP_INCLUDED
#include <fcppt/int_range_impl.hpp>
#include <fcppt/make_int_range_count.hpp>
#include <fcppt/enum/make_range.hpp>
#include <fcppt/enum/range_impl.hpp>
#include <fcppt/config/external_begin.hpp>
#include <type_traits>
#include <fcppt/config/external_end.hpp>
namespace fcppt
{
namespace container
{
namespace bitfield
{
namespace detail
{
template<
typename Element,
typename Size
>
inline
std::enable_if_t<
std::is_enum<
Element
>::value,
fcppt::enum_::range<
Element
>
>
make_range()
{
return
fcppt::enum_::make_range<
Element
>();
}
template<
typename Element,
typename Size
>
inline
std::enable_if_t<
std::is_integral<
Element
>::value,
fcppt::int_range<
Element
>
>
make_range()
{
return
fcppt::make_int_range_count<
Element
>(
Size::value
);
}
}
}
}
}
#endif
|
634bbd5e7a00807c76879bfe3a7605648da3aa19
|
5acf17fcc1e19dbb6343fe21608269898a0217c4
|
/_Embedded/Arduino.ino
|
acf88cb3376342bc4d237ee15e14ae87d544b061
|
[] |
no_license
|
christopher-stewart15/ECSE3038_LAB_6
|
42c82266e3065a74bb1504dc509f8aab5d0c2366
|
3c13a9837377f699259f2a56e857dc209709466b
|
refs/heads/main
| 2023-04-05T12:48:14.294064
| 2021-04-03T05:47:05
| 2021-04-03T05:47:05
| 354,209,801
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,985
|
ino
|
Arduino.ino
|
#include <SoftwareSerial.h>
#define RX 10
#define TX 11
SoftwareSerial ESP01 (RX,TX); // RX | TX
String ssid = "138SL-Residents";
String password = "resident2020@138sl";
String host = "10.10.85.212";
String PORT = "5000";
String Command = "";
String post = "";
String body = "";
int id = 1;
int countTrueCommand;
int countTimeCommand;
boolean found = false;
void setup() {
randomSeed(analogRead(0));
Serial.begin(115200);
ESP01.begin(115200);
sendCommand("AT",5,"OK"); // check if connection is okay
sendCommand("AT+CWMODE=1",5,"OK"); // set client mode
sendCommand("AT+CWJAP=\""+ ssid +"\",\""+ password +"\"",20,"OK");
}
void loop() {
sendCommand("AT+CIPSTART=\"TCP\",\""+ host +"\"," + PORT,15,"OK");
body = "";
body = "{\"tank_id\":"+ String(id);
body+= ",\"water_level\":" +String(getWaterLevel());
body+= "}";
post="";
post = "POST /tank HTTP/1.1\r\nHost: ";
post += host;
post += "\r\nContent-Type: application/json\r\nContent-Length:";
post += body.length();
post += "\r\n\r\n";
post += body;
post += "\r\n";
Command = "AT+CIPSEND=";
Command+= String(post.length());
sendCommand(Command, 10, "OK");
sendCommand(post, 10,"OK");
sendCommand("AT+CIPCLOSE=0", 15, "OK");
delay(200);
}
void sendCommand(String command, int maxTime, char readReplay[]) {
Serial.print(countTrueCommand);
Serial.print(". at command => ");
Serial.print(command);
Serial.print(" ");
while(countTimeCommand < (maxTime*1))
{
ESP01.println(command);//at+cipsend
if(ESP01.find(readReplay))//ok
{
found = true;
break;
}
countTimeCommand++;
}
if(found == true)
{
Serial.println("Successful");
countTrueCommand++;
countTimeCommand = 0;
id ++;
}
if(found == false)
{
Serial.println("Unsuccessful");
countTrueCommand = 0;
countTimeCommand = 0;
}
found = false;
}
int getWaterLevel() {
return random(10, 200);
}
|
faae0f3e2d0f015c38cba01adb20977e7d87bfe8
|
93e8d75b94de07533c8bf716790acd0792a03f5e
|
/src/lfortran/pass/param_to_const.h
|
868637f22d4530eb6bd4e31bc5b6811a5e6f5fbe
|
[
"BSD-3-Clause"
] |
permissive
|
mfkiwl/lfortran
|
44ccedd36f146537a6740dcfc4b06259c29d811b
|
94bf06129614f418cbccbca71f1a07eafbb1d77b
|
refs/heads/master
| 2023-08-06T10:24:20.930448
| 2021-09-29T14:51:05
| 2021-09-29T14:51:05
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 278
|
h
|
param_to_const.h
|
#ifndef LFORTRAN_PASS_PARAM_TO_CONST_H
#define LFORTRAN_PASS_PARAM_TO_CONST_H
#include <lfortran/asr.h>
namespace LFortran {
void pass_replace_param_to_const(Allocator &al, ASR::TranslationUnit_t &unit);
} // namespace LFortran
#endif // LFORTRAN_PASS_PARAM_TO_CONST_H
|
eb6cd97b35581217fc42a8aada59a9d5d662799d
|
6c0ae2e7d7276618d4a0662315fca6541db72b55
|
/Day22.cpp
|
f61f8f2b45a5b61c4d03b30aad6f216b69c0fddb
|
[] |
no_license
|
SanchiChopra/NovemberLeetcodingChallenge
|
1568fd13d377b94a98e99c98ac2ef67f01cbd25c
|
ba3e102ef206cb56f14ac66402cd4a7be12d9bb6
|
refs/heads/main
| 2023-01-29T23:20:03.188648
| 2020-12-09T14:38:35
| 2020-12-09T14:38:35
| 309,166,050
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,609
|
cpp
|
Day22.cpp
|
/* QUESTION: International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows: "a" maps to ".-", "b" maps to "-...", "c" maps to "-.-.", and so on.
For convenience, the full table for the 26 letters of the English alphabet is given below:
[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
Now, given a list of words, each word can be written as a concatenation of the Morse code of each letter. For example, "cab" can be written as "-.-..--...", (which is the concatenation "-.-." + ".-" + "-..."). We'll call such a concatenation, the transformation of a word.
Return the number of different transformations among all words we have.
Example:
Input: words = ["gin", "zen", "gig", "msg"]
Output: 2
Explanation:
The transformation of each word is:
"gin" -> "--...-."
"zen" -> "--...-."
"gig" -> "--...--."
"msg" -> "--...--."
There are 2 different transformations, "--...-." and "--...--.".
*/
class Solution {
public:
int uniqueMorseRepresentations(vector<string>& words) {
string s[26] = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
set<string> ms;
for(int i=0;i<words.size();++i){
string tmp="";
for(int j=0;j<words[i].size();++j){
tmp+=s[words[i][j]-'a'];
}
ms.insert(tmp);
}
return ms.size();
}
};
|
6a0f6b11a5177575cc9023b760b53d10bab715f8
|
f8210f0073e0d05b4b2cb38ce080ef70d44bb5be
|
/Include/Common/twSceneManager.h
|
7513bf9362b34faf9adb09a3b8f70aa80e012106
|
[
"MIT"
] |
permissive
|
microqq/TwinkleGraphics
|
87c3255d17ca36fd5fb720f86ef1da9d75f075de
|
e3975dc6dad5b6b8d5db1d54e30e815072db162e
|
refs/heads/master
| 2022-10-03T11:32:46.527840
| 2020-08-17T02:26:36
| 2020-08-17T02:26:36
| 187,617,795
| 0
| 0
|
MIT
| 2020-07-03T03:14:56
| 2019-05-20T10:17:51
|
CMake
|
UTF-8
|
C++
| false
| false
| 1,205
|
h
|
twSceneManager.h
|
#ifndef TW_SCENEMANAGEMENT_H
#define TW_SCENEMANAGEMENT_H
#include "twCommon.h"
#include "twCamera.h"
#define MAX_SCENE_CAMERA_COUNT 128
namespace TwinkleGraphics
{
class Scene : public Object
{
public:
typedef std::shared_ptr<Scene> Ptr;
Scene();
virtual ~Scene();
virtual void Init();
virtual void Update(float32 delta_time);
virtual void Render();
void SetMainCamera(Camera::Ptr cam)
{
_maincamera = cam;
}
void AddCamera(Camera::Ptr cam)
{
if(cam == nullptr)
return;
_cameralists[++_validCameraCount] = cam;
}
void RemoveCamera(int32 index)
{
if(index < 0 || index >= MAX_SCENE_CAMERA_COUNT)
{
return;
}
_cameralists[index] = nullptr;
}
Camera::Ptr GetCamera(int32 index)
{
if(index < 0 || index >= MAX_SCENE_CAMERA_COUNT)
{
return nullptr;
}
return _cameralists[index];
}
void SortCamera() {}
protected:
Camera::Ptr _maincamera;
Camera::Ptr _cameralists[MAX_SCENE_CAMERA_COUNT];
ISceneNode _sceneroot;
int32 _validCameraCount;
};
} // namespace TwinkleGraphics
#endif
|
d7bf0fe435e662c5f89305708bd5852ba8b805c9
|
4d623ea7a585e58e4094c41dc212f60ba0aec5ea
|
/C_Dubious_Document.cpp
|
39bbe4c6bd8a4f784b670e7b7f78b510f38ee128
|
[] |
no_license
|
akshit-04/CPP-Codes
|
624aadeeec35bf608ef4e83f1020b7b54d992203
|
ede0766d65df0328f7544cadb3f8ff0431147386
|
refs/heads/main
| 2023-08-30T13:28:14.748412
| 2021-11-19T12:04:43
| 2021-11-19T12:04:43
| 429,779,083
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,216
|
cpp
|
C_Dubious_Document.cpp
|
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define For(i,n) for(int i=0;i<n;i++)
#define VI vector<int>
#define fast ios_base::sync_with_stdio(0); cin.tie(0)
const int MOD = 1000000007;
template< int mod >
struct ModInt {
int x;
ModInt() : x(0) {}
ModInt(int64_t y) : x(y >= 0 ? y % mod : (mod - (-y) % mod) % mod) {}
ModInt &operator+=(const ModInt &p) {
if((x += p.x) >= mod) x -= mod;
return *this;
}
ModInt &operator-=(const ModInt &p) {
if((x += mod - p.x) >= mod) x -= mod;
return *this;
}
ModInt &operator*=(const ModInt &p) {
x = (int) (1LL * x * p.x % mod);
return *this;
}
ModInt &operator/=(const ModInt &p) {
*this *= p.inverse();
return *this;
}
ModInt operator-() const { return ModInt(-x); }
ModInt operator+(const ModInt &p) const { return ModInt(*this) += p; }
ModInt operator-(const ModInt &p) const { return ModInt(*this) -= p; }
ModInt operator*(const ModInt &p) const { return ModInt(*this) *= p; }
ModInt operator/(const ModInt &p) const { return ModInt(*this) /= p; }
bool operator==(const ModInt &p) const { return x == p.x; }
bool operator!=(const ModInt &p) const { return x != p.x; }
ModInt inverse() const {
int a = x, b = mod, u = 1, v = 0, t;
while(b > 0) {
t = a / b;
swap(a -= t * b, b);
swap(u -= t * v, v);
}
return ModInt(u);
}
ModInt pow(int64_t n) const {
ModInt ret(1), mul(x);
while(n > 0) {
if(n & 1) ret *= mul;
mul *= mul;
n >>= 1;
}
return ret;
}
friend ostream &operator<<(ostream &os, const ModInt &p) {
return os << p.x;
}
friend istream &operator>>(istream &is, ModInt &a) {
int64_t t;
is >> t;
a = ModInt< mod >(t);
return (is);
}
static int get_mod() { return mod; }
};
using mint = ModInt< MOD >;
int main()
{
fast;
int n,m;
cin>>n>>m;
VI x(n),y(m);
For(i,n){
cin>>x[i];
}
For(i,m){
cin>>y[i];
}
sort(x.begin(),x.end());
sort(y.begin(),y.end());
mint xsum=0,ysum=0;
For(i,n-1)
xsum+=(ll)(x[i+1]-x[i])*(i+1)*(n-i-1);
For(i,m-1)
ysum+=(ll)(y[i+1]-y[i])*(i+1)*(m-i-1);
mint answer=xsum*ysum;
cout<<answer;
return 0;
}
|
8f5da5c54ec855c6e723078451d7931598829e5e
|
d09945668f19bb4bc17087c0cb8ccbab2b2dd688
|
/yuki/0001-1000/001-100/060.cpp
|
cec5c95a55466b4aec9f089006fdee8e72ef8ca1
|
[] |
no_license
|
kmjp/procon
|
27270f605f3ae5d80fbdb28708318a6557273a57
|
8083028ece4be1460150aa3f0e69bdb57e510b53
|
refs/heads/master
| 2023-09-04T11:01:09.452170
| 2023-09-03T15:25:21
| 2023-09-03T15:25:21
| 30,825,508
| 23
| 2
| null | 2023-08-18T14:02:07
| 2015-02-15T11:25:23
|
C++
|
UTF-8
|
C++
| false
| false
| 1,195
|
cpp
|
060.cpp
|
#include <bits/stdc++.h>
using namespace std;
typedef signed long long ll;
#undef _P
#define _P(...) (void)printf(__VA_ARGS__)
#define FOR(x,to) for(x=0;x<to;x++)
#define ITR(x,c) for(__typeof(c.begin()) x=c.begin();x!=c.end();x++)
#define ALL(a) (a.begin()),(a.end())
#define ZERO(a) memset(a,0,sizeof(a))
#define MINUS(a) memset(a,0xff,sizeof(a))
//-------------------------------------------------------
int N,K;
int X[100001],Y[100001],H[100001];
int AX[100001],AY[100001],W[100001],HH[100001],D[100001];
int DD[1505][1505];
int S[1505][1505];
void solve() {
int i,j,k,l,r,x,y; string s;
cin>>N>>K;
FOR(i,N) cin>>X[i]>>Y[i]>>H[i];
FOR(i,K) {
cin>>AX[i]>>AY[i]>>W[i]>>HH[i]>>D[i];
for(y=AY[i]+500;y<=AY[i]+500+HH[i];y++) DD[y][AX[i]+500]+=D[i],DD[y][AX[i]+500+W[i]+1]-=D[i];
}
FOR(y,1502) FOR(x,1502) S[y][x]=((x>0)?S[y][x-1]:0)+DD[y][x];
int tot=0;
FOR(i,N) tot+=max(0,H[i]-S[Y[i]+500][X[i]+500]);
cout<<tot<<endl;
}
int main(int argc,char** argv){
string s;int i;
if(argc==1) ios::sync_with_stdio(false);
FOR(i,argc-1) s+=argv[i+1],s+='\n';
FOR(i,s.size()) ungetc(s[s.size()-1-i],stdin);
solve(); return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.