hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
bf8716a5087dc89d0c954d4bb6a14a8d88330e76
1,097
cpp
C++
hikyuu_cpp/hikyuu/realtime/receive.cpp
scanfyu/hikyuu
55265de4d8d4773391f2dcd1211acec9fe901f53
[ "MIT" ]
null
null
null
hikyuu_cpp/hikyuu/realtime/receive.cpp
scanfyu/hikyuu
55265de4d8d4773391f2dcd1211acec9fe901f53
[ "MIT" ]
null
null
null
hikyuu_cpp/hikyuu/realtime/receive.cpp
scanfyu/hikyuu
55265de4d8d4773391f2dcd1211acec9fe901f53
[ "MIT" ]
null
null
null
/* * Copyright(C) 2020 hikyuu.org * * Create on: 2020-12-16 * Author: fasiondog */ #include <nng/nng.h> #include <nng/protocol/pubsub0/sub.h> #include "../flatbuffers/spot_generated.h" #include "receive.h" namespace hku { void receive_data() {} void HKU_API start_receive() { string url{"ipc:///tmp/hikyuu_real_pub.ipc"}; nng_socket sock; int rv = 0; HKU_CHECK((rv = nng_sub0_open(&sock)) == 0, "Can't open nng sub0! {}", nng_strerror(rv)); HKU_CHECK((rv = nng_socket_set_string(sock, NNG_OPT_SUB_SUBSCRIBE, "")) == 0, "Failed set nng socket option! {}", nng_strerror(rv)); HKU_CHECK((rv = nng_dial(sock, url.c_str(), nullptr, 0) == 0), "Faied nng_dial! {}", nng_strerror(rv)); // while (true) { for (int i = 0; i < 3; i++) { char* buf = NULL; size_t length = 0; HKU_INFO("{}", i); HKU_CHECK(rv = nng_recv(sock, &buf, &length, NNG_FLAG_ALLOC) == 0, "Failed nng_recv! {}", nng_strerror(rv)); nng_free(buf, length); } nng_close(sock); } } // namespace hku
28.128205
97
0.584321
scanfyu
bf8d72ff9d55999e90a336cc096140cd230f9887
8,436
cpp
C++
logic/ShenGuan.cpp
chntujia/CodfiyAsteriatedGrailClient
5e148f2f31783fcf4ecb6b46d94245a8d2f9a8f6
[ "MIT" ]
23
2016-01-14T01:44:18.000Z
2021-11-07T05:36:21.000Z
logic/ShenGuan.cpp
chntujia/CodfiyAsteriatedGrailClient
5e148f2f31783fcf4ecb6b46d94245a8d2f9a8f6
[ "MIT" ]
null
null
null
logic/ShenGuan.cpp
chntujia/CodfiyAsteriatedGrailClient
5e148f2f31783fcf4ecb6b46d94245a8d2f9a8f6
[ "MIT" ]
8
2016-01-11T06:28:06.000Z
2020-05-17T11:03:53.000Z
#include "ShenGuan.h" enum CAUSE{ SHEN_SHENG_QI_SHI = 1501, SHEN_SHENG_QI_FU = 1502, SHUI_ZHI_SHEN_LI = 1503, SHENG_SHI_SHOU_HU = 1504, SHEN_SHENG_QI_YUE = 1505, SHEN_SHENG_LING_YU = 1506, SHUI_ZHI_SHEN_LI_GIVE = 1531, SHUI_ZHI_SHEN_LI_CROSS = 1532, SHEN_SHENG_QI_YUE_1 = 1551, SHEN_SHENG_QI_YUE_2 = 1552, SHEN_SHENG_LING_YU_1 = 1561, SHEN_SHENG_LING_YU_2 = 1562 }; ShenGuan::ShenGuan() { makeConnection(); setMyRole(this); Button *shenShengQiFu, *shuiZhiShenLi, *shenShengLingYu; shenShengQiFu = new Button(3,QStringLiteral("神圣祈福")); buttonArea->addButton(shenShengQiFu); connect(shenShengQiFu,SIGNAL(buttonSelected(int)),this,SLOT(ShenShengQiFu())); shuiZhiShenLi = new Button(4,QStringLiteral("水之神力")); buttonArea->addButton(shuiZhiShenLi); connect(shuiZhiShenLi,SIGNAL(buttonSelected(int)),this,SLOT(ShuiZhiShenLi1())); shenShengLingYu = new Button(5,QStringLiteral("神圣领域")); buttonArea->addButton(shenShengLingYu); connect(shenShengLingYu,SIGNAL(buttonSelected(int)),this,SLOT(ShenShengLingYu1())); } void ShenGuan::normal() { Role::normal(); Player* myself=dataInterface->getMyself(); SafeList<Card*> handcards=dataInterface->getHandCards(); int qiFu = 0; for(int i=0; i<handcards.size();i++) { if(handcards[i]->getType() == QStringLiteral("magic")) qiFu++; } if(qiFu>1) buttonArea->enable(3); if(handArea->checkElement("water")) buttonArea->enable(4); if(myself->getEnergy()>0) buttonArea->enable(5); unactionalCheck(); } void ShenGuan::ShenShengQiFu() { state = SHEN_SHENG_QI_FU; handArea->reset(); playerArea->reset(); tipArea->reset(); handArea->setQuota(2); decisionArea->enable(1); decisionArea->disable(0); handArea->enableMagic(); } void ShenGuan::ShuiZhiShenLi1() { state = SHUI_ZHI_SHEN_LI; handArea->reset(); playerArea->reset(); tipArea->reset(); playerArea->setQuota(1); handArea->setQuota(1); decisionArea->enable(1); decisionArea->disable(0); handArea->enableElement("water"); } void ShenGuan::ShuiZhiShenLi2() { state = SHUI_ZHI_SHEN_LI_GIVE; handArea->reset(); playerArea->reset(); tipArea->reset(); tipArea->setMsg(QStringLiteral("请给目标角色一张牌")); handArea->setQuota(1); decisionArea->enable(1); decisionArea->disable(0); handArea->enableAll(); } void ShenGuan::ShenShengQiYue1() { state = SHEN_SHENG_QI_YUE_1; gui->reset(); tipArea->setMsg(QStringLiteral("是否发动神圣契约")); SafeList<Card*> handcards=dataInterface->getHandCards(); bool flag=true; if(handcards.size()==1 && handcards.at(0)->getType()=="light" && dataInterface->getMyself()->getEnergy()==1) flag=false; if(flag) decisionArea->enable(0); decisionArea->enable(1); } void ShenGuan::ShenShengQiYue2() { state = SHEN_SHENG_QI_YUE_2; Player* myself=dataInterface->getMyself(); handArea->reset(); playerArea->reset(); tipArea->reset(); int cross = myself->getCrossNum(); if (cross>4) cross = 4; for(;cross>0;cross--) tipArea->addBoxItem(QString::number(cross)); tipArea->setMsg(QStringLiteral("请选择要转移的治疗数目")); tipArea->showBox(); playerArea->setQuota(1); playerArea->enableMate(); decisionArea->enable(1); decisionArea->disable(0); } void ShenGuan::ShenShengLingYu1() { state = SHEN_SHENG_LING_YU_1; handArea->reset(); playerArea->reset(); tipArea->reset(); decisionArea->enable(1); decisionArea->enable(0); tipArea->setMsg(QStringLiteral("请先选择一项:")); if(dataInterface->getMyself()->getCrossNum()>0) tipArea->addBoxItem(QStringLiteral("1.(移除1治疗)对目标角色造成2点法术伤害")); tipArea->addBoxItem(QStringLiteral("2.增加2治疗,目标队友增加1治疗")); tipArea->showBox(); } void ShenGuan::ShenShengLingYu2() { state = SHEN_SHENG_LING_YU_2; handArea->reset(); playerArea->reset(); tipArea->reset(); playerArea->setQuota(1); SafeList<Card*> handcards=dataInterface->getHandCards(); if(handcards.size()>1) handArea->setQuota(2); else if(handcards.size()==1) handArea->setQuota(1); else { if(lingYu==1) playerArea->enableAll(); else playerArea->enableMate(); } handArea->enableAll(); decisionArea->enable(1); decisionArea->disable(0); } void ShenGuan::cardAnalyse() { Role::cardAnalyse(); switch (state) { case SHEN_SHENG_QI_FU: decisionArea->enable(0); break; case SHUI_ZHI_SHEN_LI: playerArea->enableMate(); break; case SHUI_ZHI_SHEN_LI_GIVE: decisionArea->enable(0); break; case SHEN_SHENG_LING_YU_2: if(lingYu==1) playerArea->enableAll(); else playerArea->enableMate(); break; } } void ShenGuan::onOkClicked() { Role::onOkClicked(); SafeList<Card*> selectedCards; SafeList<Player*>selectedPlayers; selectedCards=handArea->getSelectedCards(); selectedPlayers=playerArea->getSelectedPlayers(); network::Action* action; network::Respond* respond; try{ switch(state) { case SHEN_SHENG_QI_FU: action = newAction(ACTION_MAGIC_SKILL, SHEN_SHENG_QI_FU); foreach(Card*ptr,selectedCards){ action->add_card_ids(ptr->getID()); } emit sendCommand(network::MSG_ACTION, action); gui->reset(); break; case SHUI_ZHI_SHEN_LI: action = newAction(ACTION_MAGIC_SKILL, SHUI_ZHI_SHEN_LI); action->add_card_ids(selectedCards[0]->getID()); action->add_dst_ids(selectedPlayers[0]->getID()); emit sendCommand(network::MSG_ACTION, action); gui->reset(); break; case SHUI_ZHI_SHEN_LI_GIVE: respond = newRespond(SHUI_ZHI_SHEN_LI_GIVE); respond->add_card_ids(selectedCards[0]->getID()); emit sendCommand(network::MSG_RESPOND, respond); gui->reset(); break; case SHEN_SHENG_QI_YUE_1: ShenShengQiYue2(); break; case SHEN_SHENG_QI_YUE_2: respond = newRespond(SHEN_SHENG_QI_YUE); respond->add_dst_ids(selectedPlayers[0]->getID()); respond->add_args(tipArea->getBoxCurrentText().toInt()); start = true; emit sendCommand(network::MSG_RESPOND, respond); gui->reset(); break; case SHEN_SHENG_LING_YU_1: if(tipArea->getBoxCurrentText()[0]=='1') lingYu = 1; else lingYu = 2; ShenShengLingYu2(); break; case SHEN_SHENG_LING_YU_2: action = newAction(ACTION_MAGIC_SKILL, SHEN_SHENG_LING_YU); action->add_args(lingYu); action->add_dst_ids(selectedPlayers[0]->getID()); foreach(Card*ptr,selectedCards){ action->add_card_ids(ptr->getID()); } emit sendCommand(network::MSG_ACTION, action); gui->reset(); break; } }catch(int error){ logic->onError(error); } } void ShenGuan::onCancelClicked() { Role::onCancelClicked(); QString command; network::Respond* respond; switch(state) { case SHEN_SHENG_QI_FU: case SHUI_ZHI_SHEN_LI: case SHEN_SHENG_LING_YU_1: case SHEN_SHENG_LING_YU_2: normal(); break; case SHEN_SHENG_QI_YUE_1: respond = newRespond(SHEN_SHENG_QI_YUE); respond->add_args(0); emit sendCommand(network::MSG_RESPOND, respond); gui->reset(); break; case SHEN_SHENG_QI_YUE_2: respond = newRespond(SHEN_SHENG_QI_YUE); respond->add_args(0); emit sendCommand(network::MSG_RESPOND, respond); gui->reset(); break; } } void ShenGuan::askForSkill(network::Command* cmd) { switch (cmd->respond_id()) { case SHUI_ZHI_SHEN_LI_GIVE: ShuiZhiShenLi2(); break; case SHEN_SHENG_QI_YUE: ShenShengQiYue1(); break; default: Role::askForSkill(cmd); } }
26.3625
113
0.61119
chntujia
bf8ef47648deb21ca90f6d4ad65b623d1f7c002e
8,952
cpp
C++
src/fsnorm.cpp
melmi/aban2
b17e318a82ef9003893ac818465807aecd8757fc
[ "MIT" ]
1
2017-10-15T07:20:16.000Z
2017-10-15T07:20:16.000Z
src/fsnorm.cpp
melmi/aban2
b17e318a82ef9003893ac818465807aecd8757fc
[ "MIT" ]
null
null
null
src/fsnorm.cpp
melmi/aban2
b17e318a82ef9003893ac818465807aecd8757fc
[ "MIT" ]
null
null
null
#include "vof.h" #include <cmath> #include <memory> #include "gradient.h" #include "volreconst.h" namespace aban2 { fsnorm::fsnorm(aban2::domain_t *_d): d(_d) { } fsnorm::~fsnorm() { } fsnorm::neighbs_t fsnorm::get_nighb_vals(size_t i, size_t j, size_t k) { neighbs_t result; size_t no; for (int ii = 0; ii < 3; ++ii) for (int jj = 0; jj < 3; ++jj) #ifdef THREE_D for (int kk = 0; kk < 3; ++kk) if (d->exists_and_inside(i, j, k, ii - 1, jj - 1, kk - 1, no)) result[ii][jj][kk] = d->vof[no]; else result[ii][jj][kk] = -1; #else if (d->is_inside(i, j, k, ii - 1, jj - 1, k, no)) result[ii][jj][0] = result[ii][jj][1] = result[ii][jj][2] = d->vof[no]; else result[ii][jj][0] = result[ii][jj][1] = result[ii][jj][2] = -1; #endif return result; } double fsnorm::col_sum(double delta, double v1, double v2, double v3) { if (v1 < -0.5 || v2 < -0.5 || v3 < -0.5)return -1; return delta * (v1 + v2 + v3); } double fsnorm::dir_sign(double v1, double v2, double v3) { if (v1 > -epsilon && v3 > -epsilon) return (v3 - v1) / (std::abs(v3 - v1) + epsilon); if (v1 > -epsilon && v2 > -epsilon) return (v2 - v1) / (std::abs(v2 - v1) + epsilon); if (v3 > -epsilon && v2 > -epsilon) return (v3 - v2) / (std::abs(v3 - v2) + epsilon); return 0; } double fsnorm::get_column_grad(double p, double f, double b, double delta) { if (f < -0.5) return (p - b) / delta; if (b < -0.5) return (f - p) / delta; double gf = (f - p) / delta; double gb = (p - b) / delta; // return std::abs(gb) > std::abs(gf) ? gb : gf; // Zalski // return 0.5 * (gf + bf); // CC double yf = p + 1.5 * delta * gb; double yb = p - 1.5 * delta * gf; bool cf = 0 <= yf && yf <= 3 * delta; bool cb = 0 <= yb && yb <= 3 * delta; if (cf && !cb) return gf; if (cb && !cf) return gb; return 0.5 * (gf + gb); } bool fsnorm::create_column_candidate(vector &v, size_t dir, double sign, molecule_t molecule) { if (molecule.p < -0.5 || std::abs(sign) < 0.5 || (molecule.f1 < -0.5 && molecule.b1 < -0.5) || (molecule.f2 < -0.5 && molecule.b2 < -0.5)) return false; size_t dir1 = (dir + 1) % 3, dir2 = (dir + 2) % 3; v.cmpnt[dir] = sign; v.cmpnt[dir1] = get_column_grad(molecule.p, molecule.f1, molecule.b1, d->delta); v.cmpnt[dir2] = get_column_grad(molecule.p, molecule.f2, molecule.b2, d->delta); return true; } void fsnorm::create_column_candidates(const neighbs_t &n, vector *candidates, bool *ok) { double center[3], dir1f[3], dir1b[3], dir2f[3], dir2b[3], sign[3]; sign[0] = dir_sign(n[0][1][1], n[1][1][1], n[2][1][1]); sign[1] = dir_sign(n[1][0][1], n[1][1][1], n[1][2][1]); sign[2] = dir_sign(n[1][1][0], n[1][1][1], n[1][1][2]); center[0] = col_sum(d->delta, n[0][1][1], n[1][1][1], n[2][1][1]); center[1] = col_sum(d->delta, n[1][0][1], n[1][1][1], n[1][2][1]); center[2] = col_sum(d->delta, n[1][1][0], n[1][1][1], n[1][1][2]); dir1f[0] = col_sum(d->delta, n[0][2][1], n[1][2][1], n[2][2][1]); dir1f[1] = col_sum(d->delta, n[1][0][2], n[1][1][2], n[1][2][2]); dir1f[2] = col_sum(d->delta, n[2][1][0], n[2][1][1], n[2][1][2]); dir1b[0] = col_sum(d->delta, n[0][0][1], n[1][0][1], n[2][0][1]); dir1b[1] = col_sum(d->delta, n[1][0][0], n[1][1][0], n[1][2][0]); dir1b[2] = col_sum(d->delta, n[0][1][0], n[0][1][1], n[0][1][2]); dir2f[0] = col_sum(d->delta, n[0][1][2], n[1][1][2], n[2][1][2]); dir2f[1] = col_sum(d->delta, n[2][0][1], n[2][1][1], n[2][2][1]); dir2f[2] = col_sum(d->delta, n[1][2][0], n[1][2][1], n[1][2][2]); dir2b[0] = col_sum(d->delta, n[0][1][0], n[1][1][0], n[2][1][0]); dir2b[1] = col_sum(d->delta, n[0][0][1], n[0][1][1], n[0][2][1]); dir2b[2] = col_sum(d->delta, n[1][0][0], n[1][0][1], n[1][0][2]); for (size_t i = 0; i < 3; ++i) ok[i] = create_column_candidate(candidates[i], i, sign[i], {center[i], dir1f[i], dir1b[i], dir2f[i], dir2b[i]}); } bool fsnorm::create_young_candidate(const neighbs_t &n, vector &candidate) { for (int ii = 0; ii < 3; ++ii) for (int jj = 0; jj < 3; ++jj) for (int kk = 0; kk < 3; ++kk) if (n[ii][jj][kk] < -0.5)return false; candidate.x = ( (1.0 * (n[2][0][0] + n[2][0][2] + n[2][2][0] + n[2][2][2]) + 2.0 * (n[2][1][0] + n[2][1][2] + n[2][0][1] + n[2][2][1]) + 4.0 * (n[2][1][1])) - (1.0 * (n[0][0][0] + n[0][0][2] + n[0][2][0] + n[0][2][2]) + 2.0 * (n[0][1][0] + n[0][1][2] + n[0][0][1] + n[0][2][1]) + 4.0 * (n[0][1][1])) ) / 2. / d->delta; candidate.y = ( (1.0 * (n[0][2][0] + n[0][2][2] + n[2][2][0] + n[2][2][2]) + 2.0 * (n[1][2][0] + n[1][2][2] + n[0][2][1] + n[2][2][1]) + 4.0 * (n[1][2][1])) - (1.0 * (n[0][0][0] + n[0][0][2] + n[2][0][0] + n[2][0][2]) + 2.0 * (n[1][0][0] + n[1][0][2] + n[0][0][1] + n[2][0][1]) + 4.0 * (n[1][0][1])) ) / 2. / d->delta; candidate.z = ( (1.0 * (n[0][0][2] + n[0][2][2] + n[2][0][2] + n[2][2][2]) + 2.0 * (n[1][0][2] + n[1][2][2] + n[0][1][2] + n[2][1][2]) + 4.0 * (n[1][1][2])) - (1.0 * (n[0][0][0] + n[0][2][0] + n[2][0][0] + n[2][2][0]) + 2.0 * (n[1][0][0] + n[1][2][0] + n[0][1][0] + n[2][1][0]) + 4.0 * (n[1][1][0])) ) / 2. / d->delta; return true; } void fsnorm::relax_center_val(int i, int j, int k, neighbs_t &n) { if (n[i][j][k] < -0.5)n[i][j][k] = n[1][1][1]; } void fsnorm::relax_edge_val(int i, int j, int k, neighbs_t &n) { if (n[i][j][k] >= -0.5)return; int i1 = i, i2 = i, j1 = j, j2 = j, k1 = k, k2 = k; if (i == 1) { j1 = (j + 1) % 3; k2 = (k + 1) % 3; } if (j == 1) { i1 = (i + 1) % 3; k2 = (k + 1) % 3; } if (k == 1) { i1 = (i + 1) % 3; j2 = (j + 1) % 3; } n[i][j][k] = 0.5 * (n[i1][j1][k1] + n[i2][j2][k2]); } void fsnorm::relax_corner_val(int i, int j, int k, neighbs_t &n) { if (n[i][j][k] >= -0.5)return; int ii = (i + 1) % 3; int jj = (j + 1) % 3; int kk = (k + 1) % 3; n[i][j][k] = (n[ii][j][k] + n[i][jj][k] + n[i][j][kk]) / 3.0; } void fsnorm::relax_neighb_vals(neighbs_t &n) { relax_center_val(0, 1, 1, n); relax_center_val(2, 1, 1, n); relax_center_val(1, 0, 1, n); relax_center_val(1, 2, 1, n); relax_center_val(1, 1, 0, n); relax_center_val(1, 1, 2, n); relax_edge_val(1, 0, 0, n); relax_edge_val(1, 0, 2, n); relax_edge_val(1, 2, 0, n); relax_edge_val(1, 2, 2, n); relax_edge_val(0, 1, 0, n); relax_edge_val(0, 1, 2, n); relax_edge_val(2, 1, 0, n); relax_edge_val(2, 1, 2, n); relax_edge_val(0, 0, 1, n); relax_edge_val(0, 2, 1, n); relax_edge_val(2, 0, 1, n); relax_edge_val(2, 2, 1, n); relax_corner_val(0, 0, 0, n); relax_corner_val(0, 0, 2, n); relax_corner_val(0, 2, 0, n); relax_corner_val(0, 2, 2, n); relax_corner_val(2, 0, 0, n); relax_corner_val(2, 0, 2, n); relax_corner_val(2, 2, 0, n); relax_corner_val(2, 2, 2, n); } inline vector taxicab_normalized(const vector &v) { double size = std::abs(v.x) + std::abs(v.y) + std::abs(v.z); return v * (1.0 / size); } vector fsnorm::get_normal(size_t i, size_t j, size_t k, size_t no) { vector y; // young's normal vector // bool y_ok; // young's normal ok vector c[3]; // column normal vector bool c_ok[3]; vector *final; auto neighb_vals = get_nighb_vals(i, j, k); create_column_candidates(neighb_vals, c, c_ok); // y_ok = create_young_candidate(neighb_vals, y); if (c_ok[0] || c_ok[1] || c_ok[2]) { double m0[] {0, 0, 0}; int selected_dir = -1; for (size_t i = 0; i < 3; ++i) if (c_ok[i]) { m0[i] = std::abs(taxicab_normalized(c[i]).cmpnt[i]); if (selected_dir == -1 || m0[i] > m0[selected_dir])selected_dir = i; } // if (y_ok) // if (std::abs(taxicab_normalized(y).cmpnt[selected_dir]) < m0[selected_dir]) // final = &y; // else // final = c + selected_dir; // else final = c + selected_dir; } // else if (y_ok) // Young helper // final = &y; else { relax_neighb_vals(neighb_vals); create_young_candidate(neighb_vals, y); final = &y; } final->normalize(); return *final; } }
31.191638
120
0.457887
melmi
bf906dbb10eab49b7ab0ae63c332a1601f86f4f6
2,192
cpp
C++
breadth-first-search/542-01-matrix.cpp
gromitsun/algorithm
5aea12139c1b98221650063b91c0d38b965047e5
[ "MIT" ]
null
null
null
breadth-first-search/542-01-matrix.cpp
gromitsun/algorithm
5aea12139c1b98221650063b91c0d38b965047e5
[ "MIT" ]
null
null
null
breadth-first-search/542-01-matrix.cpp
gromitsun/algorithm
5aea12139c1b98221650063b91c0d38b965047e5
[ "MIT" ]
null
null
null
ass Solution { public: vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) { if (matrix.empty()) return matrix; if (matrix[0].empty()) return matrix; // queue for BFS queue<int> rows; queue<int> cols; // sizes int n = matrix.size(); int m = matrix[0].size(); // initialize queue with indices of 0's for (int i=0; i<matrix.size(); i++) { for (int j=0; j<matrix[i].size(); j++) { if (matrix[i][j] == 0) { rows.push(i); cols.push(j); } else { matrix[i][j] = -1; } } } // BFS while (!rows.empty()) { int i = rows.front(); int j = cols.front(); rows.pop(); cols.pop(); // check elements on nsew if (i > 0) { if (matrix[i-1][j] < 0) { matrix[i-1][j] = matrix[i][j] + 1; rows.push(i-1); cols.push(j); } } if (j > 0) { if (matrix[i][j-1] < 0) { matrix[i][j-1] = matrix[i][j] + 1; rows.push(i); cols.push(j-1); } } if (i < n - 1) { if (matrix[i+1][j] < 0) { matrix[i+1][j] = matrix[i][j] + 1; rows.push(i+1); cols.push(j); } } if (j < m - 1) { if (matrix[i][j+1] < 0) { matrix[i][j+1] = matrix[i][j] + 1; rows.push(i); cols.push(j+1); } } } return matrix; } };
23.826087
67
0.273723
gromitsun
bf91298e40c612d400b59a1ba3345244171e365e
1,293
hh
C++
code/language/family_prolog/language_prolog.hh
jmpcosta/loc
0efc9aadd4cc08a6c5c6841f494862b35f4533be
[ "MIT" ]
null
null
null
code/language/family_prolog/language_prolog.hh
jmpcosta/loc
0efc9aadd4cc08a6c5c6841f494862b35f4533be
[ "MIT" ]
null
null
null
code/language/family_prolog/language_prolog.hh
jmpcosta/loc
0efc9aadd4cc08a6c5c6841f494862b35f4533be
[ "MIT" ]
null
null
null
// ***************************************************************************************** // // File description: // // Author: Joao Costa // Purpose: Provide the definitions/declarations for a programming language // // ***************************************************************************************** #ifndef LOC_LANGUAGE_PROLOG_HH_ #define LOC_LANGUAGE_PROLOG_HH_ // ***************************************************************************************** // // Section: Import headers // // ***************************************************************************************** // Import C++ system headers #include <string> // Import application headers #include "loc_defs.hh" #include "trace_macros.hh" #include "language/family_prolog/language_family_prolog.hh" // ***************************************************************************************** // // Section: Function declaration // // ***************************************************************************************** /// @brief Class responsible for implementing a C language class language_prolog : public language_family_prolog { public: /// @brief Class constructor language_prolog ( void ); private: TRACE_CLASSNAME_DECLARATION }; #endif // LOC_LANGUAGE_PROLOG_HH_
23.944444
92
0.422274
jmpcosta
bf920eb264af20bd39516fb40da5ccaf9094ca7c
128
cpp
C++
tensorflow-yolo-ios/dependencies/eigen/doc/snippets/MatrixBase_template_int_int_bottomLeftCorner_int_int.cpp
initialz/tensorflow-yolo-face-ios
ba74cf39168d0128e91318e65a1b88ce4d65a167
[ "MIT" ]
27
2017-06-07T19:07:32.000Z
2020-10-15T10:09:12.000Z
tensorflow-yolo-ios/dependencies/eigen/doc/snippets/MatrixBase_template_int_int_bottomLeftCorner_int_int.cpp
initialz/tensorflow-yolo-face-ios
ba74cf39168d0128e91318e65a1b88ce4d65a167
[ "MIT" ]
3
2017-08-25T17:39:46.000Z
2017-11-18T03:40:55.000Z
tensorflow-yolo-ios/dependencies/eigen/doc/snippets/MatrixBase_template_int_int_bottomLeftCorner_int_int.cpp
initialz/tensorflow-yolo-face-ios
ba74cf39168d0128e91318e65a1b88ce4d65a167
[ "MIT" ]
10
2017-06-16T18:04:45.000Z
2018-07-05T17:33:01.000Z
version https://git-lfs.github.com/spec/v1 oid sha256:ccbb36f2c90e75f1642d971bedefd05aa14d5ad26bf65ff7021499ec23df1725 size 301
32
75
0.882813
initialz
bf94113e47a2461e70721233023c3fc1f496de7a
18,118
cpp
C++
unit_tests/src/test_re_serialization.cpp
aghsmith/irods
31d48a47a4942df688da94b30aa8a5b5210261bb
[ "BSD-3-Clause" ]
1
2022-03-08T13:00:56.000Z
2022-03-08T13:00:56.000Z
unit_tests/src/test_re_serialization.cpp
selroc/irods
d232c7f3e0154cacc3a115aa50e366a98617b126
[ "BSD-3-Clause" ]
null
null
null
unit_tests/src/test_re_serialization.cpp
selroc/irods
d232c7f3e0154cacc3a115aa50e366a98617b126
[ "BSD-3-Clause" ]
null
null
null
#include <catch2/catch.hpp> #include "irods_error_enum_matcher.hpp" #include "irods/irods_exception.hpp" #include "irods/irods_re_serialization.hpp" #include "irods/lifetime_manager.hpp" #include "irods/key_value_proxy.hpp" #include <map> #include <string> #include <string_view> namespace res = irods::re_serialization; const std::string null_out = "null_value"; TEST_CASE("serialize_bytesBuf_ptr", "[pointer][serialization]") { bytesBuf_t* bbuf{}; bbuf = static_cast<bytesBuf_t*>(std::malloc(sizeof(bytesBuf_t))); std::memset(bbuf, 0, sizeof(bytesBuf_t)); auto lm = irods::experimental::lifetime_manager{*bbuf}; SECTION("nullptr") { auto out = res::serialized_parameter_t{{},{}}; const auto e = res::serialize_parameter(static_cast<bytesBuf_t*>(nullptr), out); CHECK(e.status()); CHECK(null_out == out.at(null_out)); } SECTION("empty") { auto out = res::serialized_parameter_t{{},{}}; const auto e = res::serialize_parameter(bbuf, out); CHECK(e.status()); CHECK(std::to_string(0) == out.at("len")); CHECK(std::string{} == out.at("buf")); } SECTION("basic_string") { const std::string cs = "wheeeee"; const int len = cs.size() + 1; bbuf->len = len; bbuf->buf = static_cast<void*>(std::malloc(len)); std::memset(bbuf->buf, 0, sizeof(len)); std::memcpy(bbuf->buf, cs.data(), len); auto out = res::serialized_parameter_t{{},{}}; const auto e = res::serialize_parameter(bbuf, out); CHECK(e.status()); CHECK(std::to_string(len) == out.at("len")); CHECK(cs + "\\x00" == out.at("buf")); } } TEST_CASE("serialize_openedDataObjInp_ptr", "[pointer][serialization]") { openedDataObjInp_t* odoi{}; odoi = static_cast<openedDataObjInp_t*>(std::malloc(sizeof(openedDataObjInp_t))); std::memset(odoi, 0, sizeof(openedDataObjInp_t)); auto lm = irods::experimental::lifetime_manager{*odoi}; SECTION("nullptr") { auto out = res::serialized_parameter_t{{},{}}; const auto e = res::serialize_parameter(static_cast<openedDataObjInp_t*>(nullptr), out); CHECK(e.status()); CHECK(null_out == out.at(null_out)); } SECTION("empty") { auto out = res::serialized_parameter_t{{},{}}; const auto e = res::serialize_parameter(odoi, out); CHECK(e.status()); CHECK(std::to_string(0) == out.at("l1descInx")); CHECK(std::to_string(0) == out.at("len")); CHECK(std::to_string(0) == out.at("whence")); CHECK(std::to_string(0) == out.at("oprType")); CHECK(std::to_string(0) == out.at("offset")); CHECK(std::to_string(0) == out.at("bytesWritten")); CHECK(std::string("nullptr") == out.at("keyValPair_t")); } SECTION("basic_struct") { odoi->l1descInx = 3; odoi->len = 42; odoi->whence = -1; odoi->oprType = PUT_OPR; odoi->offset = 20; odoi->bytesWritten = 9; auto cond_input = irods::experimental::make_key_value_proxy(odoi->condInput); cond_input["key"] = "value"; auto out = res::serialized_parameter_t{{},{}}; const auto e = res::serialize_parameter(odoi, out); CHECK(e.status()); CHECK(std::to_string(odoi->l1descInx) == out.at("l1descInx")); CHECK(std::to_string(odoi->len) == out.at("len")); CHECK(std::to_string(odoi->whence) == out.at("whence")); CHECK(std::to_string(odoi->oprType) == out.at("oprType")); CHECK(std::to_string(odoi->offset) == out.at("offset")); CHECK(std::to_string(odoi->bytesWritten) == out.at("bytesWritten")); CHECK(cond_input.at("key").value() == out.at("key")); } } TEST_CASE("serialize_rsComm_ptr", "[pointer][serialization]") { RsComm* rscp{}; rscp = static_cast<RsComm*>(std::malloc(sizeof(RsComm))); std::memset(rscp, 0, sizeof(RsComm)); auto lm = irods::experimental::lifetime_manager{*rscp}; SECTION("nullptr") { auto out = res::serialized_parameter_t{{},{}}; const auto e = res::serialize_parameter(static_cast<RsComm*>(nullptr), out); CHECK(e.status()); CHECK("nullptr" == out.at("rsComm_ptr")); } SECTION("empty") { auto out = res::serialized_parameter_t{{},{}}; const auto e = res::serialize_parameter(rscp, out); CHECK(e.status()); CHECK_THROWS(out.at("auth_scheme")); CHECK(out.at("client_addr") == rscp->clientAddr); const auto& pu = rscp->proxyUser; CHECK(out.at("proxy_user_name") == pu.userName); CHECK(out.at("proxy_rods_zone") == pu.rodsZone); CHECK(out.at("proxy_user_type") == pu.userType); CHECK(out.at("proxy_sys_uid") == std::to_string(pu.sysUid)); const auto& puai = pu.authInfo; CHECK(out.at("proxy_auth_info_auth_scheme") == puai.authScheme); CHECK(out.at("proxy_auth_info_auth_flag") == std::to_string(puai.authFlag)); CHECK(out.at("proxy_auth_info_flag") == std::to_string(puai.flag)); CHECK(out.at("proxy_auth_info_ppid") == std::to_string(puai.ppid)); CHECK(out.at("proxy_auth_info_host") == puai.host); CHECK(out.at("proxy_auth_info_auth_str") == puai.authStr); const auto& puuoi = pu.userOtherInfo; CHECK(out.at("proxy_user_other_info_user_info") == puuoi.userInfo); CHECK(out.at("proxy_user_other_info_user_comments") == puuoi.userComments); CHECK(out.at("proxy_user_other_info_user_create") == puuoi.userCreate); CHECK(out.at("proxy_user_other_info_user_modify") == puuoi.userModify); const auto& cu = rscp->clientUser; CHECK(out.at("user_user_name") == cu.userName); CHECK(out.at("user_rods_zone") == cu.rodsZone); CHECK(out.at("user_user_type") == cu.userType); CHECK(out.at("user_sys_uid") == std::to_string(cu.sysUid)); const auto& cuai = cu.authInfo; CHECK(out.at("user_auth_info_auth_scheme") == cuai.authScheme); CHECK(out.at("user_auth_info_auth_flag") == std::to_string(cuai.authFlag)); CHECK(out.at("user_auth_info_flag") == std::to_string(cuai.flag)); CHECK(out.at("user_auth_info_ppid") == std::to_string(cuai.ppid)); CHECK(out.at("user_auth_info_host") == cuai.host); CHECK(out.at("user_auth_info_auth_str") == cuai.authStr); const auto& cuuoi = cu.userOtherInfo; CHECK(out.at("user_user_other_info_user_info") == cuuoi.userInfo); CHECK(out.at("user_user_other_info_user_comments") == cuuoi.userComments); CHECK(out.at("user_user_other_info_user_create") == cuuoi.userCreate); CHECK(out.at("user_user_other_info_user_modify") == cuuoi.userModify); CHECK(out.at("socket") == std::to_string(rscp->sock)); CHECK(out.at("connect_count") == std::to_string(rscp->connectCnt)); CHECK(out.at("status") == std::to_string(rscp->status)); CHECK(out.at("api_index") == std::to_string(rscp->apiInx)); CHECK(out.at("option") == rscp->option); } SECTION("basic_struct") { const std::string as = "myauthscheme"; std::strncpy(rscp->clientAddr, "127.0.0.1", sizeof(rscp->clientAddr)); rscp->auth_scheme = const_cast<char*>(as.data()); auto& pu = rscp->proxyUser; std::strncpy(pu.userName, "rods", sizeof(pu.userName)); std::strncpy(pu.rodsZone, "tempZone", sizeof(pu.rodsZone)); std::strncpy(pu.userType, "rodsadmin", sizeof(pu.userType)); pu.sysUid = 999; auto& puai = pu.authInfo; std::strncpy(puai.authScheme, "myauthscheme", sizeof(puai.authScheme)); puai.authFlag = 1; puai.flag = 2; puai.ppid = 3; std::strncpy(puai.host, "here.example.org", sizeof(puai.host)); std::strncpy(puai.authStr, "myauthstr", sizeof(puai.authStr)); auto& puuoi = pu.userOtherInfo; std::strncpy(puuoi.userInfo, "userinfo", sizeof(puuoi.userInfo)); std::strncpy(puuoi.userComments, "jimbo", sizeof(puuoi.userComments)); std::strncpy(puuoi.userCreate, "123456789", sizeof(puuoi.userCreate)); std::strncpy(puuoi.userModify, "987654321", sizeof(puuoi.userModify)); auto& cu = rscp->clientUser; std::strncpy(cu.userName, "alice", sizeof(cu.userName)); std::strncpy(cu.rodsZone, "otherZone", sizeof(cu.rodsZone)); std::strncpy(cu.userType, "rodsuser", sizeof(cu.userType)); cu.sysUid = 111; auto& cuai = cu.authInfo; std::strncpy(cuai.authScheme, "authschemezzz", sizeof(cuai.authScheme)); cuai.authFlag = 4; cuai.flag = 5; cuai.ppid = 6; std::strncpy(cuai.host, "other.example.org", sizeof(cuai.host)); std::strncpy(cuai.authStr, "anotherauthstr", sizeof(cuai.authStr)); auto& cuuoi = cu.userOtherInfo; std::strncpy(cuuoi.userInfo, "aaaaaaaa", sizeof(cuuoi.userInfo)); std::strncpy(cuuoi.userComments, "kimbo", sizeof(cuuoi.userComments)); std::strncpy(cuuoi.userCreate, "987654321", sizeof(cuuoi.userCreate)); std::strncpy(cuuoi.userModify, "123456789", sizeof(cuuoi.userModify)); rscp->sock = 3; rscp->connectCnt = 1; rscp->status = -808000; rscp->apiInx = 701; std::strncpy(rscp->option, "option", sizeof(rscp->option)); auto out = res::serialized_parameter_t{{},{}}; const auto e = res::serialize_parameter(rscp, out); CHECK(e.status()); CHECK(out.at("client_addr") == rscp->clientAddr); CHECK(out.at("auth_scheme") == as); CHECK(out.at("proxy_user_name") == pu.userName); CHECK(out.at("proxy_rods_zone") == pu.rodsZone); CHECK(out.at("proxy_user_type") == pu.userType); CHECK(out.at("proxy_sys_uid") == std::to_string(pu.sysUid)); CHECK(out.at("proxy_auth_info_auth_scheme") == puai.authScheme); CHECK(out.at("proxy_auth_info_auth_flag") == std::to_string(puai.authFlag)); CHECK(out.at("proxy_auth_info_flag") == std::to_string(puai.flag)); CHECK(out.at("proxy_auth_info_ppid") == std::to_string(puai.ppid)); CHECK(out.at("proxy_auth_info_host") == puai.host); CHECK(out.at("proxy_auth_info_auth_str") == puai.authStr); CHECK(out.at("proxy_user_other_info_user_info") == puuoi.userInfo); CHECK(out.at("proxy_user_other_info_user_comments") == puuoi.userComments); CHECK(out.at("proxy_user_other_info_user_create") == puuoi.userCreate); CHECK(out.at("proxy_user_other_info_user_modify") == puuoi.userModify); CHECK(out.at("user_user_name") == cu.userName); CHECK(out.at("user_rods_zone") == cu.rodsZone); CHECK(out.at("user_user_type") == cu.userType); CHECK(out.at("user_sys_uid") == std::to_string(cu.sysUid)); CHECK(out.at("user_auth_info_auth_scheme") == cuai.authScheme); CHECK(out.at("user_auth_info_auth_flag") == std::to_string(cuai.authFlag)); CHECK(out.at("user_auth_info_flag") == std::to_string(cuai.flag)); CHECK(out.at("user_auth_info_ppid") == std::to_string(cuai.ppid)); CHECK(out.at("user_auth_info_host") == cuai.host); CHECK(out.at("user_auth_info_auth_str") == cuai.authStr); CHECK(out.at("user_user_other_info_user_info") == cuuoi.userInfo); CHECK(out.at("user_user_other_info_user_comments") == cuuoi.userComments); CHECK(out.at("user_user_other_info_user_create") == cuuoi.userCreate); CHECK(out.at("user_user_other_info_user_modify") == cuuoi.userModify); CHECK(out.at("socket") == std::to_string(rscp->sock)); CHECK(out.at("connect_count") == std::to_string(rscp->connectCnt)); CHECK(out.at("status") == std::to_string(rscp->status)); CHECK(out.at("api_index") == std::to_string(rscp->apiInx)); CHECK(out.at("option") == rscp->option); } } TEST_CASE("serialize_dataObjInfo_ptr", "[pointer][serialization]") { SECTION("nullptr") { res::serialized_parameter_t out; const auto e = res::serialize_parameter(static_cast<DataObjInfo*>(nullptr), out); CHECK(e.status()); CHECK(out.size() == 1); CHECK(out.at("dataObjInfo_ptr") == "nullptr"); } SECTION("empty and basic_struct") { std::map<std::string_view, DataObjInfo> test_data{ {"empty", {}}, {"non_empty", { .objPath = "objPath", .rescName = "rescName", .rescHier = "rescHier", .dataType = "dataType", .dataSize = 100, .chksum = "chksum", .version = "version", .filePath = "filePath", .dataOwnerName = "dataOwnerName", .dataOwnerZone = "dataOwnerZone", .replNum = 200, .replStatus = 300, .statusString = "statusString", .dataId = 400, .collId = 500, .dataMapId = 600, .flags = 700, .dataComments = "dataComments", .dataMode = "dataMode", .dataExpiry = "dataExpiry", .dataCreate = "dataCreate", .dataModify = "dataModify", .dataAccess = "dataAccess", .dataAccessInx = 800, .writeFlag = 900, .destRescName = "destRescName", .backupRescName = "backupRescName", .subPath = "subPath", .specColl = nullptr, .regUid = 1000, .otherFlags = 1100, .condInput = {}, .in_pdmo = "in_pdmo", .next = nullptr, .rescId = 1200 }} }; for (auto&& [section_name, doi] : test_data) { DYNAMIC_SECTION(section_name) { res::serialized_parameter_t out; const auto e = res::serialize_parameter(&doi, out); CHECK(e.status()); CHECK(out.at("logical_path") == doi.objPath); CHECK(out.at("resc_name") == doi.rescName); CHECK(out.at("resc_hier") == doi.rescHier); CHECK(out.at("data_type") == doi.dataType); CHECK(out.at("data_size") == std::to_string(doi.dataSize)); CHECK(out.at("checksum") == doi.chksum); CHECK(out.at("version") == doi.version); CHECK(out.at("physical_path") == doi.filePath); CHECK(out.at("data_owner_name") == doi.dataOwnerName); CHECK(out.at("data_owner_zone") == doi.dataOwnerZone); CHECK(out.at("replica_number") == std::to_string(doi.replNum)); CHECK(out.at("replica_status") == std::to_string(doi.replStatus)); CHECK(out.at("status_string") == doi.statusString); CHECK(out.at("data_id") == std::to_string(doi.dataId)); CHECK(out.at("coll_id") == std::to_string(doi.collId)); CHECK(out.at("data_map_id") == std::to_string(doi.dataMapId)); CHECK(out.at("flags") == std::to_string(doi.flags)); CHECK(out.at("data_comments") == doi.dataComments); CHECK(out.at("data_mode") == doi.dataMode); CHECK(out.at("data_expiry") == doi.dataExpiry); CHECK(out.at("data_create") == doi.dataCreate); CHECK(out.at("data_modify") == doi.dataModify); CHECK(out.at("data_access") == doi.dataAccess); CHECK(out.at("data_access_index") == std::to_string(doi.dataAccessInx)); CHECK(out.at("write_flag") == std::to_string(doi.writeFlag)); CHECK(out.at("dest_resc_name") == doi.destRescName); CHECK(out.at("backup_resc_name") == doi.backupRescName); CHECK(out.at("sub_path") == doi.subPath); CHECK(nullptr == doi.specColl); CHECK(out.at("reg_uid") == std::to_string(doi.regUid)); CHECK(out.at("other_flags") == std::to_string(doi.otherFlags)); CHECK(out.at("keyValPair_t") == "nullptr"); CHECK(out.at("in_pdmo") == doi.in_pdmo); CHECK(nullptr == doi.next); CHECK(out.at("resc_id") == std::to_string(doi.rescId)); } } } }
45.408521
98
0.538967
aghsmith
bf9750c0c8cbfd0d30800c2894844c5ebcaa1eca
6,723
cc
C++
src/ufo/rttovcpp/ObsRadianceRTTOVCPPTLAD.cc
NOAA-EMC/ufo
3bf1407731b79eab16ceff64129552577d9cfcd0
[ "Apache-2.0" ]
null
null
null
src/ufo/rttovcpp/ObsRadianceRTTOVCPPTLAD.cc
NOAA-EMC/ufo
3bf1407731b79eab16ceff64129552577d9cfcd0
[ "Apache-2.0" ]
10
2020-12-10T22:57:51.000Z
2020-12-17T15:57:04.000Z
src/ufo/rttovcpp/ObsRadianceRTTOVCPPTLAD.cc
NOAA-EMC/ufo
3bf1407731b79eab16ceff64129552577d9cfcd0
[ "Apache-2.0" ]
3
2020-12-10T18:38:22.000Z
2020-12-11T01:36:37.000Z
/* * (C) Copyright 2017-2021 UCAR * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. */ #include <ostream> #include <string> #include <vector> #include "ioda/ObsSpace.h" #include "ioda/ObsVector.h" #include "oops/base/Variables.h" #include "oops/util/IntSetParser.h" #include "oops/util/Logger.h" #include "oops/util/missingValues.h" #include "ufo/GeoVaLs.h" #include "ufo/ObsDiagnostics.h" #include "ufo/rttovcpp/ObsRadianceRTTOVCPPTLAD.h" #include "ufo/rttovcpp/rttovcpp_interface.h" namespace ufo { // ----------------------------------------------------------------------------- static LinearObsOperatorMaker<ObsRadianceRTTOVCPPTLAD> makerRTTOVCPPTL_("RTTOVCPP"); // ----------------------------------------------------------------------------- ObsRadianceRTTOVCPPTLAD::ObsRadianceRTTOVCPPTLAD(const ioda::ObsSpace & odb, const Parameters_ & parameters) : LinearObsOperatorBase(odb), varin_() { // Increment fields to be requested from getvalues and stored in geovals const std::vector<std::string> vv{ "air_temperature", "specific_humidity" }; for (size_t jvar = 0; jvar < vv.size(); ++jvar) { varin_.push_back(vv[jvar]); // set private data member varin_ } // get channels from observations const oops::Variables & observed = odb.obsvariables(); channels_ = observed.channels(); // set private data member channels_ // get optical depth coef file name from yaml const std::string CoefPath = parameters.CoefPath; const std::string SensorID = parameters.SensorID; CoefFileName = CoefPath + "rtcoef_" + SensorID + ".dat"; oops::Log::trace() << "ObsRadianceRTTOVCPPTLAD created." << std::endl; } // ----------------------------------------------------------------------------- ObsRadianceRTTOVCPPTLAD::~ObsRadianceRTTOVCPPTLAD() { oops::Log::trace() << "ObsRadianceRTTOVCPPTLAD destructed" << std::endl; } // ----------------------------------------------------------------------------- void ObsRadianceRTTOVCPPTLAD::setTrajectory(const GeoVaLs & geovals, ObsDiagnostics &) { // ufo::rttovcpp_interface(geovals, obsspace(), aRttov_, CoefFileName, channels_, nlevels, skip_profile); oops::Log::trace() << "ObsRadianceRTTOVCPPTLAD::setTrajectory done" << std::endl; } // ----------------------------------------------------------------------------- void ObsRadianceRTTOVCPPTLAD::simulateObsTL(const GeoVaLs & dx, ioda::ObsVector & dy) const { // std::size_t nprofiles = dy.nlocs(); std::size_t nchannels = aRttov_.getNchannels(); std::vector<double> tmpvar2d(nprofiles, 0.0); // one single level field std::vector<std::vector<double>> dT; // [nlevels][nprofiles] std::vector<std::vector<double>> dQ; // [nlevels][nprofiles] // Retrieve temperature increment in K for (std::size_t i = 0; i < nlevels; ++i) { dx.getAtLevel(tmpvar2d, "air_temperature", i); // get one level T dT.push_back(tmpvar2d); // push one level T into 3D T } // Retrieve specific humidity increment in kg/kg for (std::size_t i = 0; i < nlevels; ++i) { dx.getAtLevel(tmpvar2d, "specific_humidity", i); // get one level Q dQ.push_back(tmpvar2d); // push one level Q into 3D Q } //------------------------------------------- ASSERT(dx.nlocs() == dy.nlocs()); ASSERT(nchannels == dy.nvars()); dy.zero(); std::vector <double> var_k(nlevels, 0.0); for (size_t p = 0; p < nprofiles; p++) { if (skip_profile[p]) continue; for (size_t c = 0; c < nchannels; c++) { var_k = aRttov_.getTK(p, c); // T Jacobian for a single profile/channel for (size_t l = 0; l < nlevels; l++) dy[p*nchannels+c] += var_k[l]*dT[l][p]; var_k = aRttov_.getItemK(rttov::Q, p, c); // Q Jacobian for (size_t l = 0; l < nlevels; l++) dy[p*nchannels+c] += var_k[l]*dQ[l][p]; } } oops::Log::trace() << "ObsRadianceRTTOVCPPTLAD::simulateObsTL done" << std::endl; } // ----------------------------------------------------------------------------- void ObsRadianceRTTOVCPPTLAD::simulateObsAD(GeoVaLs & dx, const ioda::ObsVector & dy) const { // std::size_t nprofiles = dy.nlocs(); std::size_t nchannels = aRttov_.getNchannels(); std::vector<double> tmpvar2d(nprofiles, 0.0); // one single level field std::vector<std::vector<double>> dT; // [nlevels][nprofiles] std::vector<std::vector<double>> dQ; // [nlevels][nprofiles] // Retrieve temperature increment in K for (std::size_t i = 0; i < nlevels; ++i) { dx.getAtLevel(tmpvar2d, "air_temperature", i); // get one level T dT.push_back(tmpvar2d); // push one level T into 3D T } // Retrieve specific humidity increment in kg/kg for (std::size_t i = 0; i < nlevels; ++i) { dx.getAtLevel(tmpvar2d, "specific_humidity", i); // get one level Q dQ.push_back(tmpvar2d); // push one level Q into 3D Q } //------------------------------------------- ASSERT(dx.nlocs() == dy.nlocs()); double missing = util::missingValue(missing); std::vector <double> var_k(nlevels, 0.0); for (size_t p = 0; p < nprofiles; p++) { if (skip_profile[p]) continue; for (size_t c = 0; c < nchannels; c++) { var_k = aRttov_.getTK(p, c); // T Jacobian, nlevels for (size_t l = 0; l < nlevels; ++l) { if (dy[p*nchannels+c] != missing) { dT[l][p] += dy[p*nchannels+c] * var_k[l]; } } var_k = aRttov_.getItemK(rttov::Q, p, c); // Q Jacobian, nlevels for (size_t l = 0; l < nlevels; l++) { if (dy[p*nchannels+c] != missing) { dQ[l][p] += dy[p*nchannels+c] * var_k[l]; } } } } // Put temperature increment in kg/kg for (std::size_t l = 0; l < nlevels; ++l) { for (size_t p = 0; p < nprofiles; p++) { tmpvar2d[p] = dT[l][p]; } dx.putAtLevel(tmpvar2d, "air_temperature", l); // put one level T } // Put specific humidity increment in kg/kg for (std::size_t l = 0; l < nlevels; ++l) { for (size_t p = 0; p < nprofiles; p++) { tmpvar2d[p] = dQ[l][p]; } dx.putAtLevel(tmpvar2d, "specific_humidity", l); // put one level Q } oops::Log::trace() << "ObsRadianceRTTOVCPPTLAD::simulateObsAD done" << std::endl; } // ----------------------------------------------------------------------------- void ObsRadianceRTTOVCPPTLAD::print(std::ostream & os) const { os << "ObsRadianceRTTOVCPPTLAD::print not implemented" << std::endl; } // ----------------------------------------------------------------------------- } // namespace ufo
34.30102
93
0.564926
NOAA-EMC
bf992618c15b414844100ec7522af7048ab0ce02
1,024
hpp
C++
include/boost/simd/function/definition/shuffle.hpp
yaeldarmon/boost.simd
561316cc54bdc6353ca78f3b6d7e9120acd11144
[ "BSL-1.0" ]
null
null
null
include/boost/simd/function/definition/shuffle.hpp
yaeldarmon/boost.simd
561316cc54bdc6353ca78f3b6d7e9120acd11144
[ "BSL-1.0" ]
null
null
null
include/boost/simd/function/definition/shuffle.hpp
yaeldarmon/boost.simd
561316cc54bdc6353ca78f3b6d7e9120acd11144
[ "BSL-1.0" ]
null
null
null
//================================================================================================== /*! @file @copyright 2016 NumScale SAS @copyright 2016 J.T.Lapreste Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ //================================================================================================== #ifndef BOOST_SIMD_FUNCTION_DEFINITION_SHUFFLE_HPP_INCLUDED #define BOOST_SIMD_FUNCTION_DEFINITION_SHUFFLE_HPP_INCLUDED #include <boost/simd/config.hpp> #include <boost/dispatch/function/make_callable.hpp> #include <boost/dispatch/hierarchy/functions.hpp> #include <boost/simd/detail/dispatch.hpp> namespace boost { namespace simd { namespace tag { BOOST_DISPATCH_MAKE_TAG(ext, shuffle_, boost::dispatch::elementwise_<shuffle_>); } namespace ext { BOOST_DISPATCH_FUNCTION_DECLARATION(tag, shuffle_); } BOOST_DISPATCH_CALLABLE_DEFINITION(tag::shuffle_,shuffle); } } #endif
26.947368
100
0.624023
yaeldarmon
bcce7e14c2292faff64de0cbe006700351469bcc
2,101
cpp
C++
src/SynchronizationPoint.cpp
omi-lab/tp_task_queue
e7b4e61cc87ad2ff3954782fb96d5e988c9fbc3f
[ "MIT" ]
null
null
null
src/SynchronizationPoint.cpp
omi-lab/tp_task_queue
e7b4e61cc87ad2ff3954782fb96d5e988c9fbc3f
[ "MIT" ]
null
null
null
src/SynchronizationPoint.cpp
omi-lab/tp_task_queue
e7b4e61cc87ad2ff3954782fb96d5e988c9fbc3f
[ "MIT" ]
2
2018-08-30T10:00:25.000Z
2021-05-05T08:39:06.000Z
#include "tp_task_queue/SynchronizationPoint.h" #include "tp_task_queue/Task.h" #include "tp_utils/MutexUtils.h" namespace tp_task_queue { //################################################################################################## struct SynchronizationPoint::Private { TP_REF_COUNT_OBJECTS("tp_task_queue::SynchronizationPoint::Private"); TP_NONCOPYABLE(Private); Private() = default; std::vector<Task*> tasks; TPMutex mutex{TPM}; TPWaitCondition waitCondition; }; //################################################################################################## SynchronizationPoint::SynchronizationPoint(): d(new Private()) { } //################################################################################################## SynchronizationPoint::~SynchronizationPoint() { join(); delete d; } //################################################################################################## void SynchronizationPoint::join() { TP_MUTEX_LOCKER(d->mutex); while(!d->tasks.empty()) d->waitCondition.wait(TPMc d->mutex); } //################################################################################################## void SynchronizationPoint::addTask(Task* task, size_t maxActive) { task->setSynchronizationPoint(this); TP_MUTEX_LOCKER(d->mutex); while(d->tasks.size()>=maxActive) d->waitCondition.wait(TPMc d->mutex); d->tasks.push_back(task); } //################################################################################################## void SynchronizationPoint::cancelTasks() { TP_MUTEX_LOCKER(d->mutex); for(auto task : d->tasks) task->cancelTask(); } //################################################################################################## size_t SynchronizationPoint::activeTasks() { TP_MUTEX_LOCKER(d->mutex); return d->tasks.size(); } //################################################################################################## void SynchronizationPoint::removeTask(Task* task) { TP_MUTEX_LOCKER(d->mutex); tpRemoveOne(d->tasks, task); d->waitCondition.wakeAll(); } }
27.285714
100
0.447882
omi-lab
bccfd61828612b69f482e7a3c46f2248bdab8811
713
hpp
C++
include/SFRL/Direction.hpp
marukrap/SFRL
a241e09dae33eb6099b1ccb1eb1c741e0af589f0
[ "MIT" ]
4
2018-06-19T08:43:04.000Z
2021-03-15T08:37:57.000Z
include/SFRL/Direction.hpp
marukrap/SFRL
a241e09dae33eb6099b1ccb1eb1c741e0af589f0
[ "MIT" ]
null
null
null
include/SFRL/Direction.hpp
marukrap/SFRL
a241e09dae33eb6099b1ccb1eb1c741e0af589f0
[ "MIT" ]
null
null
null
#pragma once #include <SFML/System/Vector2.hpp> #include <array> namespace rl { class Direction : public sf::Vector2i { public: using sf::Vector2i::Vector2; Direction operator-() const; Direction left45() const; Direction right45() const; Direction left90() const; Direction right90() const; public: static const Direction None; static const Direction N; static const Direction NE; static const Direction E; static const Direction SE; static const Direction S; static const Direction SW; static const Direction W; static const Direction NW; static const std::array<Direction, 8> All; static const std::array<Direction, 4> Cardinal; static const std::array<Direction, 4> Diagonal; }; }
17.825
48
0.743338
marukrap
bcd410c7242d42133211bac47bb3e7e5c9876b32
5,966
cxx
C++
SimVascular-master/Code/Source/sv2/Segmentation/sv2_LevelSetVelocityImage.cxx
mccsssk2/SimVascularPM3_March2020
3cce6cc7be66545bea5dc3915a2db50a3892bf04
[ "BSD-3-Clause" ]
null
null
null
SimVascular-master/Code/Source/sv2/Segmentation/sv2_LevelSetVelocityImage.cxx
mccsssk2/SimVascularPM3_March2020
3cce6cc7be66545bea5dc3915a2db50a3892bf04
[ "BSD-3-Clause" ]
null
null
null
SimVascular-master/Code/Source/sv2/Segmentation/sv2_LevelSetVelocityImage.cxx
mccsssk2/SimVascularPM3_March2020
3cce6cc7be66545bea5dc3915a2db50a3892bf04
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) Stanford University, The Regents of the University of * California, and others. * * All Rights Reserved. * * See Copyright-SimVascular.txt for additional details. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * 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 "SimVascular.h" #include "sv2_LevelSetVelocityImage.h" #include "sv2_LevelSet.h" // ------ // cvLevelSetVelocityImage // ------ cvLevelSetVelocityImage::cvLevelSetVelocityImage() { image_ = NULL; } // ------- // ~cvLevelSetVelocityImage // ------- cvLevelSetVelocityImage::~cvLevelSetVelocityImage() { ClearImage(); } // -------- // SetImage // -------- int cvLevelSetVelocityImage::SetImage( Image_T *i, int closed ) { if ( image_ != NULL ) { return SV_ERROR; } else if ( i == NULL ) { return SV_ERROR; } else { image_ = i; ComputeImageGrad( image_ ); SetImageClosed( image_, closed ); PostSetImageAction(); return SV_OK; } } // -------- // SetImage // -------- int cvLevelSetVelocityImage::SetImage( char *filebase, int fileNumRange[], int imgDims[], double pixDims[], int closed ) { Image_T *tmp = NULL; tmp = ReadImage( filebase, fileNumRange, "-short", imgDims, pixDims ); if ( tmp == NULL ) { return SV_ERROR; } if ( image_ ) { ClearImage(); } image_ = tmp; ComputeImageGrad( image_ ); SetImageClosed( image_, closed ); PostSetImageAction(); return SV_OK; } // -------- // SetImage // -------- // Being able to set image directly with a pre-existing array of data // allows us to interface to other systems that work with imaging data // (e.g. vtk). CreateImage COPIES the given data array, which means // the copy passed in to this method still belongs to the caller. int cvLevelSetVelocityImage::SetImage( short *imgData, int numData, int imgDims[], double pixDims[], double origin[], int closed ) { Image_T *tmp = NULL; tmp = CreateImage( imgData, numData, "-short", imgDims, pixDims ); if ( tmp == NULL ) { return SV_ERROR; } SetLowerLeft( tmp, origin ); if ( image_ ) { ClearImage(); } image_ = tmp; ComputeImageGrad( image_ ); SetImageClosed( image_, closed ); PostSetImageAction(); return SV_OK; } // -------- // SetImage // -------- int cvLevelSetVelocityImage::SetImage( double *imgData, int numData, int imgDims[], double pixDims[], double origin[], int closed ) { Image_T *tmp = NULL; tmp = CreateImage( imgData, numData, "-double", imgDims, pixDims ); if ( tmp == NULL ) { return SV_ERROR; } SetLowerLeft( tmp, origin ); if ( image_ ) { ClearImage(); } image_ = tmp; ComputeImageGrad( image_ ); SetImageClosed( image_, closed ); PostSetImageAction(); return SV_OK; } // -------- // SetImage // -------- int cvLevelSetVelocityImage::SetImage( float *imgData, int numData, int imgDims[], double pixDims[], double origin[], int closed ) { Image_T *tmp = NULL; tmp = CreateImage( (void*)imgData, numData, "-float", imgDims, pixDims ); if ( tmp == NULL ) { return SV_ERROR; } SetLowerLeft( tmp, origin ); if ( image_ ) { ClearImage(); } image_ = tmp; ComputeImageGrad( image_ ); SetImageClosed( image_, closed ); PostSetImageAction(); return SV_OK; } // -------- // GetImage // -------- int cvLevelSetVelocityImage::GetImage( Image_T **i ) { if ( image_ == NULL ) { return SV_ERROR; } else { *i = image_; return SV_OK; } } // --------------- // GetMagGradRange // --------------- int cvLevelSetVelocityImage::GetMagGradRange( double rng[] ) { if ( image_ == NULL ) { return SV_ERROR; } else { Img_GetMagGradRange( image_, rng ); return SV_OK; } } // ----------------- // GetXYMagGradRange // ----------------- int cvLevelSetVelocityImage::GetXYMagGradRange( double rng[] ) { if ( image_ == NULL ) { return SV_ERROR; } else { Img_GetXYMagGradRange( image_, rng ); return SV_OK; } } // ---------------- // GetZMagGradRange // ---------------- int cvLevelSetVelocityImage::GetZMagGradRange( double rng[] ) { if ( image_ == NULL ) { return SV_ERROR; } else { Img_GetZMagGradRange( image_, rng ); return SV_OK; } } // ----------------- // GetIntensityRange // ----------------- int cvLevelSetVelocityImage::GetIntensityRange( double rng[] ) { if ( image_ == NULL ) { return SV_ERROR; } else { Img_GetIntensityRange( image_, rng ); return SV_OK; } } // ---------- // ClearImage // ---------- int cvLevelSetVelocityImage::ClearImage() { if ( image_ != NULL ) { Image_Delete( image_ ); } image_ = NULL; return SV_OK; }
22.261194
89
0.643144
mccsssk2
bcd570392a18bf0acdd15273f3a9f1d4aa4eec15
1,396
cpp
C++
CSES/Tree Algorithms/Tree Diameter.cpp
s166harth/CC
b6c0fe58f03633fe2787a567a16909f1b2966e7b
[ "MIT" ]
406
2020-05-28T13:35:08.000Z
2022-03-31T17:23:26.000Z
CSES/Tree Algorithms/Tree Diameter.cpp
shakeeb-droids/CC
2f49fcb52d748804aee9fc7f26abb3150bec69e5
[ "MIT" ]
3
2021-01-01T17:50:34.000Z
2021-10-02T10:02:27.000Z
CSES/Tree Algorithms/Tree Diameter.cpp
shakeeb-droids/CC
2f49fcb52d748804aee9fc7f26abb3150bec69e5
[ "MIT" ]
108
2020-07-21T13:02:33.000Z
2022-03-28T22:46:49.000Z
/** 🍪 thew6rst 🍪 11.02.2021 20:15:33 **/ #ifdef W #include "k_II.h" #else #include <bits/stdc++.h> using namespace std; #endif #define pb emplace_back #define all(x) x.begin(), x.end() #define sz(x) static_cast<int32_t>(x.size()) template<class T> class Y { T f; public: template<class U> explicit Y(U&& f): f(forward<U>(f)) {} template<class... Args> decltype(auto) operator()(Args&&... args) { return f(ref(*this), forward<Args>(args)...); } }; template<class T> Y(T) -> Y<T>; const int64_t DESPACITO = 2e18; const int INF = 2e9, MOD = 1e9+7; const int N = 2e5 + 5; int main() { cin.tie(nullptr)->sync_with_stdio(false); int i, n; cin >> n; vector<vector<int>> g(n); for(i = 0; i < n-1; i++) { int u, v; cin >> u >> v; u--, v--; g[u].pb(v); g[v].pb(u); } auto bfs = [&] (int root) { queue<int> q; q.push(root); vector<int> d(n, -1); d[root] = 0; while(!q.empty()) { auto cur = q.front(); q.pop(); for(auto nxt : g[cur]) { if(d[nxt] == -1) { d[nxt] = d[cur] + 1; q.push(nxt); } } } auto it = max_element(all(d)); return make_pair(it-d.begin(), *it); }; cout << bfs(bfs(0).first).second; } // ~W
25.851852
72
0.465616
s166harth
bcde1e1fe21ce2194c1eaef09273b97749633db7
64
cpp
C++
test/wiztk/base/sigcxx/subject.cpp
wiztk/framework
179baf8a24406b19d3f4ea28e8405358b21f8446
[ "Apache-2.0" ]
37
2017-11-22T14:15:33.000Z
2021-11-25T20:39:39.000Z
test/unit/core-sigcxx/subject.cpp
zhanggyb/skland
055d91a6830b95d248d407c37a8a2fa20b148efd
[ "Apache-2.0" ]
3
2018-03-01T12:44:22.000Z
2021-01-04T23:14:41.000Z
test/wiztk/base/sigcxx/subject.cpp
wiztk/framework
179baf8a24406b19d3f4ea28e8405358b21f8446
[ "Apache-2.0" ]
10
2017-11-25T19:09:11.000Z
2020-12-02T02:05:47.000Z
// // Created by zhanggyb on 17-9-7. // #include "subject.hpp"
10.666667
33
0.625
wiztk
bcdf098c2e1237d63a0036cb40009668e10ec93f
3,616
cpp
C++
src/ndnSIM/model/cs/content-store-with-stats.cpp
NDNLink/NDN-Chord
cfabf8f56eea2c4ba47052ce145a939ebdc21e57
[ "MIT" ]
1
2021-09-07T04:12:15.000Z
2021-09-07T04:12:15.000Z
src/ndnSIM/model/cs/content-store-with-stats.cpp
NDNLink/NDN-Chord
cfabf8f56eea2c4ba47052ce145a939ebdc21e57
[ "MIT" ]
null
null
null
src/ndnSIM/model/cs/content-store-with-stats.cpp
NDNLink/NDN-Chord
cfabf8f56eea2c4ba47052ce145a939ebdc21e57
[ "MIT" ]
1
2020-07-15T06:21:03.000Z
2020-07-15T06:21:03.000Z
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /** * Copyright (c) 2011-2015 Regents of the University of California. * * This file is part of ndnSIM. See AUTHORS for complete list of ndnSIM authors and * contributors. * * ndnSIM is free software: you can redistribute it and/or modify it under the terms * of the GNU General Public License as published by the Free Software Foundation, * either version 3 of the License, or (at your option) any later version. * * ndnSIM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * ndnSIM, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>. **/ #include "content-store-with-stats.hpp" #include "../../utils/trie/random-policy.hpp" #include "../../utils/trie/lru-policy.hpp" #include "../../utils/trie/fifo-policy.hpp" #include "../../utils/trie/lfu-policy.hpp" #define NS_OBJECT_ENSURE_REGISTERED_TEMPL(type, templ) \ static struct X##type##templ##RegistrationClass { \ X##type##templ##RegistrationClass() \ { \ ns3::TypeId tid = type<templ>::GetTypeId(); \ tid.GetParent(); \ } \ } x_##type##templ##RegistrationVariable namespace ns3 { namespace ndn { using namespace ndnSIM; namespace cs { // explicit instantiation and registering /** * @brief ContentStore with stats and LRU cache replacement policy **/ template class ContentStoreWithStats<lru_policy_traits>; /** * @brief ContentStore with stats and random cache replacement policy **/ template class ContentStoreWithStats<random_policy_traits>; /** * @brief ContentStore with stats and FIFO cache replacement policy **/ template class ContentStoreWithStats<fifo_policy_traits>; /** * @brief ContentStore with stats and Least Frequently Used (LFU) cache replacement policy **/ template class ContentStoreWithStats<lfu_policy_traits>; NS_OBJECT_ENSURE_REGISTERED_TEMPL(ContentStoreWithStats, lru_policy_traits); NS_OBJECT_ENSURE_REGISTERED_TEMPL(ContentStoreWithStats, random_policy_traits); NS_OBJECT_ENSURE_REGISTERED_TEMPL(ContentStoreWithStats, fifo_policy_traits); NS_OBJECT_ENSURE_REGISTERED_TEMPL(ContentStoreWithStats, lfu_policy_traits); #ifdef DOXYGEN // /** // * \brief Content Store with stats implementing LRU cache replacement policy // */ class Stats::Lru : public ContentStoreWithStats<lru_policy_traits> { }; /** * \brief Content Store with stats implementing FIFO cache replacement policy */ class Stats::Fifo : public ContentStoreWithStats<fifo_policy_traits> { }; /** * \brief Content Store with stats implementing Random cache replacement policy */ class Stats::Random : public ContentStoreWithStats<random_policy_traits> { }; /** * \brief Content Store with stats implementing Least Frequently Used cache replacement policy */ class Stats::Lfu : public ContentStoreWithStats<lfu_policy_traits> { }; #endif } // namespace cs } // namespace ndn } // namespace ns3
36.16
100
0.655697
NDNLink
bce860a715f430c2d98ccef0ee18be5e34d29288
958
cpp
C++
EasyCppTest/OTP.cpp
Thalhammer/EasyCpp
6b9886fecf0aa363eaf03741426fd3462306c211
[ "MIT" ]
3
2018-02-06T05:12:41.000Z
2020-05-12T20:57:32.000Z
EasyCppTest/OTP.cpp
Thalhammer/EasyCpp
6b9886fecf0aa363eaf03741426fd3462306c211
[ "MIT" ]
41
2016-07-11T12:19:10.000Z
2017-08-08T07:43:12.000Z
EasyCppTest/OTP.cpp
Thalhammer/EasyCpp
6b9886fecf0aa363eaf03741426fd3462306c211
[ "MIT" ]
2
2019-08-02T10:24:36.000Z
2020-09-11T01:45:12.000Z
#include <gtest/gtest.h> #include <Hash/HOTP.h> #include <Hash/TOTP.h> #include <HexEncoding.h> using namespace EasyCpp; using namespace EasyCpp::Hash; namespace EasyCppTest { TEST(OTP, HOTP) { std::string secret = "3132333435363738393031323334353637383930"; auto hotp = HOTP(HexEncoding::decode(secret)); std::string token6 = hotp.generate(0, 6); std::string token8 = hotp.generate(0, 8); ASSERT_EQ(std::string("755224"), token6); ASSERT_EQ(std::string("84755224"), token8); token6 = hotp.generate(1, 6); token8 = hotp.generate(1, 8); ASSERT_EQ(std::string("287082"), token6); ASSERT_EQ(std::string("94287082"), token8); } TEST(OTP, TOTP) { std::string secret = "3132333435363738393031323334353637383930"; auto totp = TOTP(HexEncoding::decode(secret)); std::vector<std::string> keys; for (int i = -5; i < 6; i++) keys.push_back(totp.generate(i)); // Set a break point here and check using your TOTP device ! } }
25.210526
66
0.692067
Thalhammer
bce8b12b2f99b609f0bbb11fe76914c570a3201b
9,707
cpp
C++
multiview/contrib/fast-bilateral-space_stereo-master/src/bilateral_grid_simplified.cpp
prcvlabs/multiview
1a03e14855292967ffb0c0ec7fff855c5abbc9d2
[ "Apache-2.0" ]
5
2021-09-03T23:12:08.000Z
2022-03-04T21:43:32.000Z
multiview/contrib/fast-bilateral-space_stereo-master/src/bilateral_grid_simplified.cpp
prcvlabs/multiview
1a03e14855292967ffb0c0ec7fff855c5abbc9d2
[ "Apache-2.0" ]
3
2021-09-08T02:57:46.000Z
2022-02-26T05:33:02.000Z
multiview/contrib/fast-bilateral-space_stereo-master/src/bilateral_grid_simplified.cpp
prcvlabs/multiview
1a03e14855292967ffb0c0ec7fff855c5abbc9d2
[ "Apache-2.0" ]
2
2021-09-26T03:14:40.000Z
2022-01-26T06:42:52.000Z
/* Copyright 2017 Toon Van den Zegel. All Rights Reserved. */ /* */ /* This file is part of fast_bilateral_space_stereo. */ /* */ /* fast_bilateral_space_stereo is free software : */ /* you can redistribute it and / or modify */ /* it under the terms of the GNU General Public License as published by */ /* the Free Software Foundation, either version 3 of the License, or */ /* (at your option) any later version. */ /* */ /* fast_bilateral_space_stereo is distributed in the hope that it will be useful, */ /* but WITHOUT ANY WARRANTY; without even the implied warranty of */ /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the */ /* GNU General Public License for more details. */ /* */ /* You should have received a copy of the GNU General Public License */ /* along with fast_bilateral_space_stereo. */ /* If not, see <http://www.gnu.org/licenses/>. */ #include "bilateral_grid_simplified.h" bilateral_grid_simplified::bilateral_grid_simplified() : nb_vertices(0), nb_reference_pixels(0), reference_width(0), reference_height(0) { } void bilateral_grid_simplified::init(const cv::Mat reference_bgr, const int sigma_spatial, const int sigma_luma, const int sigma_chroma) { // let's work in yuv space cv::Mat reference_yuv; cv::cvtColor(reference_bgr, reference_yuv, CV_BGR2YUV); std::chrono::steady_clock::time_point begin_grid_construction = std::chrono::steady_clock::now(); const int w = reference_yuv.cols; const int h = reference_yuv.rows; reference_width = w; reference_height = h; nb_reference_pixels = w * h; int max_coord[5]; max_coord[0] = w / sigma_spatial; max_coord[1] = h / sigma_spatial; max_coord[2] = 255 / sigma_luma; max_coord[3] = 255 / sigma_chroma; max_coord[4] = 255 / sigma_chroma; // with this hash function we can convert each 5 dimensional coordinate to 1 unique number std::int64_t hash_vec[5]; for (int i = 0; i < 5; ++i) hash_vec[i] = static_cast<std::int64_t>(std::pow(255, i)); std::unordered_map<std::int64_t /* hash */, int /* vert id */> hashed_coords; hashed_coords.reserve(w*h); const unsigned char* pref = (const unsigned char*)reference_yuv.data; int vert_idx = 0; int pix_idx = 0; typedef Eigen::Triplet<float> T; std::vector<T> tripletList; tripletList.reserve(w * h); // loop through each pixel of the image for (int y = 0; y < h; ++y) { for (int x = 0; x < w; ++x) { std::int64_t coord[5]; coord[0] = x / sigma_spatial; coord[1] = y / sigma_spatial; coord[2] = pref[0] / sigma_luma; coord[3] = pref[1] / sigma_chroma; coord[4] = pref[2] / sigma_chroma; // convert the coordinate to a hash value std::int64_t hash_coord = 0; for (int i = 0; i < 5; ++i) hash_coord += coord[i] * hash_vec[i]; // pixels whom are alike will have the same hash value. // We only want to keep a unique list of hash values, therefore make sure we only insert // unique hash values. auto it = hashed_coords.find(hash_coord); if (it == hashed_coords.end()) { hashed_coords.insert(std::pair<std::int64_t, int>(hash_coord, vert_idx)); tripletList.push_back(T(vert_idx, pix_idx, 1.0f)); ++vert_idx; } else { tripletList.push_back(T(it->second, pix_idx, 1.0f)); } pref += 3; // skip 3 bytes (y u v) ++pix_idx; } } // construct our splat and splice matrices mat_splat = Eigen::SparseMatrix<float, Eigen::RowMajor>(hashed_coords.size(), tripletList.size()); mat_splat.setFromTriplets(tripletList.begin(), tripletList.end()); mat_slice = mat_splat.transpose(); nb_vertices = static_cast<std::int32_t>(hashed_coords.size()); std::chrono::steady_clock::time_point end_grid_construction = std::chrono::steady_clock::now(); std::cout << "grid construction:" << std::chrono::duration_cast<std::chrono::milliseconds>(end_grid_construction - begin_grid_construction).count() << "ms" << std::endl; std::chrono::steady_clock::time_point begin_blur_construction = std::chrono::steady_clock::now(); // Blur matrices Eigen::SparseMatrix<float, Eigen::RowMajor> mat_b_left(hashed_coords.size(), hashed_coords.size()); Eigen::SparseMatrix<float, Eigen::RowMajor> mat_b_right(hashed_coords.size(), hashed_coords.size()); mat_blur = Eigen::SparseMatrix<float, Eigen::RowMajor>(hashed_coords.size(), hashed_coords.size()); for (int i = 0; i < 5; ++i) { std::int64_t offset_hash_coord = -1 * hash_vec[i]; tripletList.clear(); for (auto it = hashed_coords.begin(); it != hashed_coords.end(); ++it) { std::int64_t neighb_coord = it->first + offset_hash_coord; auto it_neighb = hashed_coords.find(neighb_coord); if (it_neighb != hashed_coords.end()) { tripletList.push_back(T(it->second, it_neighb->second, 1.0f)); } } mat_b_left.setZero(); mat_b_left.setFromTriplets(tripletList.begin(), tripletList.end()); offset_hash_coord = 1 * hash_vec[i]; tripletList.clear(); for (auto it = hashed_coords.begin(); it != hashed_coords.end(); ++it) { std::int64_t neighb_coord = it->first + offset_hash_coord; auto it_neighb = hashed_coords.find(neighb_coord); if (it_neighb != hashed_coords.end()) { tripletList.push_back(T(it->second, it_neighb->second, 1.0f)); } } mat_b_right.setZero(); mat_b_right.setFromTriplets(tripletList.begin(), tripletList.end()); mat_blur += mat_b_left; mat_blur += mat_b_right; } std::chrono::steady_clock::time_point end_blur_construction = std::chrono::steady_clock::now(); std::cout << "blur construction: " << std::chrono::duration_cast<std::chrono::milliseconds>(end_blur_construction - begin_blur_construction).count() << "ms" << std::endl; mat_slice.finalize(); mat_splat.finalize(); mat_blur.finalize(); // normalization matrix (the splat matrix is not normalized) Eigen::MatrixXf mat_ones(w*h, 1); mat_ones.setOnes(); Eigen::MatrixXf mat_ones_splatted = mat_splat * mat_ones; mat_normalizer = mat_slice * mat_ones_splatted; } Eigen::MatrixXf bilateral_grid_simplified::blur(Eigen::MatrixXf& in) const { return mat_blur * in + (in *(5.0f * 2.0f)); } Eigen::SparseMatrix<float, Eigen::RowMajor> bilateral_grid_simplified::blur(const Eigen::SparseMatrix<float, Eigen::RowMajor>& in) const { Eigen::SparseMatrix<float, Eigen::RowMajor> a = (in *(5.0f * 2.0f)); Eigen::SparseMatrix<float, Eigen::RowMajor> b = mat_blur * in; return b + a; } cv::Mat bilateral_grid_simplified::filter(cv::Mat input_image) { assert(input_image.type() == CV_32FC1); std::chrono::steady_clock::time_point start_blur = std::chrono::steady_clock::now(); // splat & blur & slice Eigen::Map<Eigen::MatrixXf> eig_input_image(reinterpret_cast<float*>(input_image.data), input_image.cols * input_image.rows, 1); Eigen::MatrixXf mat_splatted = mat_splat * eig_input_image; Eigen::MatrixXf mat_splatted_and_blurred = blur(mat_splatted); Eigen::MatrixXf mat_blurred = mat_slice * mat_splatted_and_blurred; // normalize Eigen::MatrixXf mat_blurred_result = mat_blurred.cwiseQuotient(mat_normalizer); // convert to opencv cv::Mat cv_blurred_result(input_image.rows, input_image.cols, CV_32FC1); memcpy(cv_blurred_result.data, mat_blurred_result.data(), input_image.rows * input_image.cols * sizeof(float)); std::chrono::steady_clock::time_point end_blur = std::chrono::steady_clock::now(); std::cout << "blur: " << std::chrono::duration_cast<std::chrono::milliseconds>(end_blur - start_blur).count() << "ms" << std::endl; return cv_blurred_result; } cv::Mat bilateral_grid_simplified::splat_slice(cv::Mat input_image) { assert(input_image.type() == CV_32FC1); // splat & slice Eigen::Map<Eigen::MatrixXf> eig_input_image(reinterpret_cast<float*>(input_image.data), input_image.cols * input_image.rows, 1); Eigen::MatrixXf mat_splatted = mat_splat * eig_input_image; Eigen::MatrixXf mat_sliced = mat_slice * mat_splatted; // normalize Eigen::MatrixXf result = mat_sliced.cwiseQuotient(mat_normalizer); cv::Mat cv_result(input_image.rows, input_image.cols, CV_32FC1); memcpy(cv_result.data, result.data(), input_image.rows * input_image.cols * 4); return cv_result; } //void serialize(std::string directory) //{ // //Serialize(directory + "\\mat_splat.dat", mat_splat); // //Serialize(directory + "\\mat_slice.dat", mat_slice); // //Serialize(directory + "\\mat_blur.dat", mat_blur); //} // //void deserialize(std::string directory) //{ // /* std::chrono::steady_clock::time_point begin_deserialize = std::chrono::steady_clock::now(); // // Deserialize(directory + "\\mat_splat.dat", mat_splat); // Deserialize(directory + "\\mat_slice.dat", mat_slice); // Deserialize(directory + "\\mat_blur.dat", mat_blur); // nb_vertices = static_cast<int>(mat_splat.outerSize()); // // std::chrono::steady_clock::time_point end_deserialize = std::chrono::steady_clock::now(); // std::cout << "bilateral_grid::deserialize: " << std::chrono::duration_cast<std::chrono::milliseconds>(end_deserialize - begin_deserialize).count() << "ms" << std::endl; // */ //}
38.519841
171
0.657361
prcvlabs
bcedc443bbec46ce3220483cef3732cf95b74e68
1,533
hpp
C++
include/codegen/include/OVR/OpenVR/VRTextureDepthInfo_t.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/OVR/OpenVR/VRTextureDepthInfo_t.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/OVR/OpenVR/VRTextureDepthInfo_t.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:05 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes // Including type: System.ValueType #include "System/ValueType.hpp" // Including type: System.IntPtr #include "System/IntPtr.hpp" // Including type: OVR.OpenVR.HmdMatrix44_t #include "OVR/OpenVR/HmdMatrix44_t.hpp" // Including type: OVR.OpenVR.HmdVector2_t #include "OVR/OpenVR/HmdVector2_t.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Completed forward declares // Type namespace: OVR.OpenVR namespace OVR::OpenVR { // Autogenerated type: OVR.OpenVR.VRTextureDepthInfo_t struct VRTextureDepthInfo_t : public System::ValueType { public: // public System.IntPtr handle // Offset: 0x0 System::IntPtr handle; // public OVR.OpenVR.HmdMatrix44_t mProjection // Offset: 0x8 OVR::OpenVR::HmdMatrix44_t mProjection; // public OVR.OpenVR.HmdVector2_t vRange // Offset: 0x48 OVR::OpenVR::HmdVector2_t vRange; // Creating value type constructor for type: VRTextureDepthInfo_t VRTextureDepthInfo_t(System::IntPtr handle_ = {}, OVR::OpenVR::HmdMatrix44_t mProjection_ = {}, OVR::OpenVR::HmdVector2_t vRange_ = {}) : handle{handle_}, mProjection{mProjection_}, vRange{vRange_} {} }; // OVR.OpenVR.VRTextureDepthInfo_t } DEFINE_IL2CPP_ARG_TYPE(OVR::OpenVR::VRTextureDepthInfo_t, "OVR.OpenVR", "VRTextureDepthInfo_t"); #pragma pack(pop)
39.307692
204
0.70972
Futuremappermydud
bcef795865b64ed8f4a5e4332ed5a48021129fd7
2,016
cpp
C++
src/entities/bretoniafighter.cpp
P-Sc/Pirateers
440e477d33bbbcd79d291700c369f74fd0a6cc7d
[ "MIT" ]
null
null
null
src/entities/bretoniafighter.cpp
P-Sc/Pirateers
440e477d33bbbcd79d291700c369f74fd0a6cc7d
[ "MIT" ]
null
null
null
src/entities/bretoniafighter.cpp
P-Sc/Pirateers
440e477d33bbbcd79d291700c369f74fd0a6cc7d
[ "MIT" ]
null
null
null
#include "bretoniafighter.h" #include "ship/shipsystem.h" #include "gamelogic/aisystem.h" BretoniaFighter::BretoniaFighter(ShipSystem& shipSystem, AISystem& aiSystem, ShipSettings shipSettings, float multiplier) : EnemyShip(shipSystem, aiSystem) { EnergySettings energySettings; energySettings.maxEnergy = 350; energySettings.regenPerSecond = 70; ShieldSettings shieldSettings; shieldSettings.maxHull = 400; shieldSettings.maxShield = 200; shieldSettings.regenPerSecond = 100; shieldSettings.maxRegenPause = 2; shipSettings.energySettings = energySettings; shipSettings.shieldSettings = shieldSettings; shipSettings.shipname = "BretoniaFighter"; shipSettings.explosionDelay = 1; shipSettings.weapons.push_back(Weapon("plasma", b2Vec2(0, 1))); shipSettings.weapons.back().damageMultiplier = 0.4f; shipSettings.weapons.back().rateOfFireMultiplier = 1.5f * (0.5f + (rand() % 10) / 10.f); shipSettings.weapons.back().scatterMultiplier = 0.5f; shipSettings.weapons.push_back(Weapon("plasma", b2Vec2(1, 0))); shipSettings.weapons.back().damageMultiplier = 0.4f; shipSettings.weapons.back().rateOfFireMultiplier = 1.5f * (0.5f + (rand() % 10) / 10.f); shipSettings.weapons.back().scatterMultiplier = 0.5f; shipSettings.weapons.push_back(Weapon("plasma", b2Vec2(-1, 0))); shipSettings.weapons.back().damageMultiplier = 0.4f; shipSettings.weapons.back().rateOfFireMultiplier = 1.5f * (0.5f + (rand() % 10) / 10.f); shipSettings.weapons.back().scatterMultiplier = 0.5f; //shipSettings.weapons.back().velocityMultiplier = 0.2f; shipSettings.rewardCount = 2; shipSettings.engineEffectSettings.offset.Set(0, -3); shipSettings.engineEffectSettings.size = 4; this->shipSettings = shipSettings; aiSettings.type = AISettings::fighter; aiSettings.weaponRange = 160; aiSettings.combatRadius = 10 + rand() % 20; aiSettings.sightRange = 300; create(multiplier); }
43.826087
103
0.713294
P-Sc
bcf3136b0161d63fcd188ddbac92dcb85a6f7e33
520
cpp
C++
tree/src/diameter.cpp
fumiphys/programming_contest
b9466e646045e1c64571af2a1e64813908e70841
[ "MIT" ]
7
2019-04-30T14:25:40.000Z
2020-12-19T17:38:11.000Z
tree/src/diameter.cpp
fumiphys/programming_contest
b9466e646045e1c64571af2a1e64813908e70841
[ "MIT" ]
46
2018-09-19T16:42:09.000Z
2020-05-07T09:05:08.000Z
tree/src/diameter.cpp
fumiphys/programming_contest
b9466e646045e1c64571af2a1e64813908e70841
[ "MIT" ]
null
null
null
/* * Library for Diameter */ #include <iostream> #include <cassert> #include "../diameter.hpp" using namespace std; int main(int argc, char const* argv[]) { cout << "-- test for diameter start --" << endl; Tree<int> t(6); t.adde(0, 1, 1); t.adde(0, 4, 1); t.adde(1, 2, 1); t.adde(1, 3, 1); t.adde(4, 5, 1); t.adde(1, 0, 1); t.adde(4, 0, 1); t.adde(2, 1, 1); t.adde(3, 1, 1); t.adde(5, 4, 1); assert(t.diameter() == 4); cout << "-- test for diameter end: Success --" << endl; return 0; }
19.259259
57
0.542308
fumiphys
bcf621d0d6f4d422359da11384b422b14a90c990
135,341
cpp
C++
retired/scalycpp/Parser.cpp
rschleitzer/scaly
7537cdf44f7a63ad1a560975017ee1c897c73787
[ "MIT" ]
4
2019-09-08T15:20:11.000Z
2021-06-07T11:27:36.000Z
retired/scalycpp/Parser.cpp
rschleitzer/scaly
7537cdf44f7a63ad1a560975017ee1c897c73787
[ "MIT" ]
null
null
null
retired/scalycpp/Parser.cpp
rschleitzer/scaly
7537cdf44f7a63ad1a560975017ee1c897c73787
[ "MIT" ]
1
2017-07-20T21:12:33.000Z
2017-07-20T21:12:33.000Z
#include "scalycpp.h" using namespace scaly; namespace scalycpp { Parser::Parser(string* theFileName, string* text) { lexer = new(_getPage()->allocateExclusivePage()) Lexer(text); fileName = theFileName; classKeyword = new(_getPage()) string("class"); functionKeyword = new(_getPage()) string("function"); ifKeyword = new(_getPage()) string("if"); elseKeyword = new(_getPage()) string("else"); switchKeyword = new(_getPage()) string("switch"); caseKeyword = new(_getPage()) string("case"); defaultKeyword = new(_getPage()) string("default"); catchKeyword = new(_getPage()) string("catch"); forKeyword = new(_getPage()) string("for"); inKeyword = new(_getPage()) string("in"); whileKeyword = new(_getPage()) string("while"); doKeyword = new(_getPage()) string("do"); returnKeyword = new(_getPage()) string("return"); throwKeyword = new(_getPage()) string("throw"); breakKeyword = new(_getPage()) string("break"); throwsKeyword = new(_getPage()) string("throws"); staticKeyword = new(_getPage()) string("static"); letKeyword = new(_getPage()) string("let"); mutableKeyword = new(_getPage()) string("mutable"); isKeyword = new(_getPage()) string("is"); asKeyword = new(_getPage()) string("as"); constructorKeyword = new(_getPage()) string("constructor"); enumKeyword = new(_getPage()) string("enum"); thisKeyword = new(_getPage()) string("this"); nullKeyword = new(_getPage()) string("null"); newKeyword = new(_getPage()) string("new"); extendsKeyword = new(_getPage()) string("extends"); equal = new(_getPage()) string("="); comma = new(_getPage()) string(","); leftParen = new(_getPage()) string("("); rightParen = new(_getPage()) string(")"); leftCurly = new(_getPage()) string("{"); rightCurly = new(_getPage()) string("}"); leftBracket = new(_getPage()) string("["); rightBracket = new(_getPage()) string("]"); colon = new(_getPage()) string(":"); dot = new(_getPage()) string("."); underscore = new(_getPage()) string("_"); circumflex = new(_getPage()) string("^"); dollar = new(_getPage()) string("$"); at = new(_getPage()) string("@"); hash = new(_getPage()) string("#"); ampersand = new(_getPage()) string("&"); } _Result<Module, ParserError> Parser::parseModule(_Page* _rp, _Page* _ep) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); _Array<Statement>* statements = parseStatementList(_rp); if (statements != nullptr) { if (!isAtEnd()) { _Region _region; _Page* _p = _region.get(); Position* errorPos = lexer->getPreviousPosition(_p); return _Result<Module, ParserError>(new(_ep) ParserError(new(_ep) _ParserError_syntax(errorPos->line, errorPos->column))); } } Position* end = lexer->getPosition(_p); Module* ret = new(_rp) Module(statements, new(_rp) Position(start), new(_rp) Position(end)); if (statements != nullptr) { Statement* item = nullptr; size_t _statements_length = statements->length(); for (size_t _i = 0; _i < _statements_length; _i++) { item = *(*statements)[_i]; item->parent = ret; } } return ret; } _Array<Statement>* Parser::parseStatementList(_Page* _rp) { _Region _region; _Page* _p = _region.get(); _Array<Statement>* ret = nullptr; while (true) { Statement* node = parseStatement(_rp); if (node == nullptr) break; if (ret == nullptr) ret = new(_p) _Array<Statement>(); ret->push(node); } return ret ? new(_rp) _Array<Statement>(ret) : nullptr; } Statement* Parser::parseStatement(_Page* _rp) { { Declaration* node = parseDeclaration(_rp); if (node != nullptr) return node; } { Expression* node = parseExpression(_rp); if (node != nullptr) return node; } return nullptr; } Declaration* Parser::parseDeclaration(_Page* _rp) { { ConstantDeclaration* node = parseConstantDeclaration(_rp); if (node != nullptr) return node; } { MutableDeclaration* node = parseMutableDeclaration(_rp); if (node != nullptr) return node; } { FunctionDeclaration* node = parseFunctionDeclaration(_rp); if (node != nullptr) return node; } { EnumDeclaration* node = parseEnumDeclaration(_rp); if (node != nullptr) return node; } { ClassDeclaration* node = parseClassDeclaration(_rp); if (node != nullptr) return node; } { ConstructorDeclaration* node = parseConstructorDeclaration(_rp); if (node != nullptr) return node; } return nullptr; } ConstantDeclaration* Parser::parseConstantDeclaration(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); bool successLet1 = lexer->parseKeyword(letKeyword); if (successLet1) lexer->advance(); else return nullptr; BindingInitializer* initializer = parseBindingInitializer(_rp); if (initializer == nullptr) return nullptr; Position* end = lexer->getPosition(_p); ConstantDeclaration* ret = new(_rp) ConstantDeclaration(initializer, new(_rp) Position(start), new(_rp) Position(end)); initializer->parent = ret; return ret; } MutableDeclaration* Parser::parseMutableDeclaration(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); bool successMutable1 = lexer->parseKeyword(mutableKeyword); if (successMutable1) lexer->advance(); else return nullptr; BindingInitializer* initializer = parseBindingInitializer(_rp); if (initializer == nullptr) return nullptr; Position* end = lexer->getPosition(_p); MutableDeclaration* ret = new(_rp) MutableDeclaration(initializer, new(_rp) Position(start), new(_rp) Position(end)); initializer->parent = ret; return ret; } BindingInitializer* Parser::parseBindingInitializer(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); IdentifierInitializer* initializer = parseIdentifierInitializer(_rp); if (initializer == nullptr) return nullptr; _Array<AdditionalInitializer>* additionalInitializers = parseAdditionalInitializerList(_rp); Position* end = lexer->getPosition(_p); BindingInitializer* ret = new(_rp) BindingInitializer(initializer, additionalInitializers, new(_rp) Position(start), new(_rp) Position(end)); initializer->parent = ret; if (additionalInitializers != nullptr) { AdditionalInitializer* item = nullptr; size_t _additionalInitializers_length = additionalInitializers->length(); for (size_t _i = 0; _i < _additionalInitializers_length; _i++) { item = *(*additionalInitializers)[_i]; item->parent = ret; } } return ret; } _Array<IdentifierInitializer>* Parser::parseIdentifierInitializerList(_Page* _rp) { _Region _region; _Page* _p = _region.get(); _Array<IdentifierInitializer>* ret = nullptr; while (true) { IdentifierInitializer* node = parseIdentifierInitializer(_rp); if (node == nullptr) break; if (ret == nullptr) ret = new(_p) _Array<IdentifierInitializer>(); ret->push(node); } return ret ? new(_rp) _Array<IdentifierInitializer>(ret) : nullptr; } IdentifierInitializer* Parser::parseIdentifierInitializer(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); IdentifierPattern* pattern = parseIdentifierPattern(_rp); if (pattern == nullptr) return nullptr; Initializer* initializer = parseInitializer(_rp); Position* end = lexer->getPosition(_p); IdentifierInitializer* ret = new(_rp) IdentifierInitializer(pattern, initializer, new(_rp) Position(start), new(_rp) Position(end)); pattern->parent = ret; if (initializer != nullptr) initializer->parent = ret; return ret; } Initializer* Parser::parseInitializer(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); bool successEqual1 = lexer->parsePunctuation(equal); if (successEqual1) lexer->advance(); else return nullptr; Expression* expression = parseExpression(_rp); if (expression == nullptr) return nullptr; Position* end = lexer->getPosition(_p); Initializer* ret = new(_rp) Initializer(expression, new(_rp) Position(start), new(_rp) Position(end)); expression->parent = ret; return ret; } _Array<AdditionalInitializer>* Parser::parseAdditionalInitializerList(_Page* _rp) { _Region _region; _Page* _p = _region.get(); _Array<AdditionalInitializer>* ret = nullptr; while (true) { AdditionalInitializer* node = parseAdditionalInitializer(_rp); if (node == nullptr) break; if (ret == nullptr) ret = new(_p) _Array<AdditionalInitializer>(); ret->push(node); } return ret ? new(_rp) _Array<AdditionalInitializer>(ret) : nullptr; } AdditionalInitializer* Parser::parseAdditionalInitializer(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); bool successComma1 = lexer->parsePunctuation(comma); if (successComma1) lexer->advance(); else return nullptr; IdentifierInitializer* pattern = parseIdentifierInitializer(_rp); if (pattern == nullptr) return nullptr; Position* end = lexer->getPosition(_p); AdditionalInitializer* ret = new(_rp) AdditionalInitializer(pattern, new(_rp) Position(start), new(_rp) Position(end)); pattern->parent = ret; return ret; } Pattern* Parser::parsePattern(_Page* _rp) { { WildcardPattern* node = parseWildcardPattern(_rp); if (node != nullptr) return node; } { IdentifierPattern* node = parseIdentifierPattern(_rp); if (node != nullptr) return node; } { TuplePattern* node = parseTuplePattern(_rp); if (node != nullptr) return node; } { ExpressionPattern* node = parseExpressionPattern(_rp); if (node != nullptr) return node; } return nullptr; } IdentifierPattern* Parser::parseIdentifierPattern(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); string* identifier = lexer->parseIdentifier(_rp); if ((identifier != nullptr) && isIdentifier(identifier)) lexer->advance(); else return nullptr; TypeAnnotation* annotationForType = parseTypeAnnotation(_rp); Position* end = lexer->getPosition(_p); IdentifierPattern* ret = new(_rp) IdentifierPattern(identifier, annotationForType, new(_rp) Position(start), new(_rp) Position(end)); if (annotationForType != nullptr) annotationForType->parent = ret; return ret; } TypeAnnotation* Parser::parseTypeAnnotation(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); bool successColon1 = lexer->parsePunctuation(colon); if (successColon1) lexer->advance(); else return nullptr; Type* annotationForType = parseType(_rp); if (annotationForType == nullptr) return nullptr; Position* end = lexer->getPosition(_p); TypeAnnotation* ret = new(_rp) TypeAnnotation(annotationForType, new(_rp) Position(start), new(_rp) Position(end)); annotationForType->parent = ret; return ret; } Type* Parser::parseType(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); string* name = lexer->parseIdentifier(_rp); if ((name != nullptr) && isIdentifier(name)) lexer->advance(); else return nullptr; _Array<TypePostfix>* postfixes = parseTypePostfixList(_rp); LifeTime* lifeTime = parseLifeTime(_rp); Position* end = lexer->getPosition(_p); Type* ret = new(_rp) Type(name, postfixes, lifeTime, new(_rp) Position(start), new(_rp) Position(end)); if (postfixes != nullptr) { TypePostfix* item = nullptr; size_t _postfixes_length = postfixes->length(); for (size_t _i = 0; _i < _postfixes_length; _i++) { item = *(*postfixes)[_i]; item->parent = ret; } } if (lifeTime != nullptr) lifeTime->parent = ret; return ret; } _Array<TypePostfix>* Parser::parseTypePostfixList(_Page* _rp) { _Region _region; _Page* _p = _region.get(); _Array<TypePostfix>* ret = nullptr; while (true) { TypePostfix* node = parseTypePostfix(_rp); if (node == nullptr) break; if (ret == nullptr) ret = new(_p) _Array<TypePostfix>(); ret->push(node); } return ret ? new(_rp) _Array<TypePostfix>(ret) : nullptr; } TypePostfix* Parser::parseTypePostfix(_Page* _rp) { { IndexedType* node = parseIndexedType(_rp); if (node != nullptr) return node; } { Pointer* node = parsePointer(_rp); if (node != nullptr) return node; } return nullptr; } IndexedType* Parser::parseIndexedType(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); bool successLeftBracket1 = lexer->parsePunctuation(leftBracket); if (successLeftBracket1) lexer->advance(); else return nullptr; Type* key = parseType(_rp); bool successRightBracket3 = lexer->parsePunctuation(rightBracket); if (successRightBracket3) lexer->advance(); else return nullptr; Position* end = lexer->getPosition(_p); IndexedType* ret = new(_rp) IndexedType(key, new(_rp) Position(start), new(_rp) Position(end)); if (key != nullptr) key->parent = ret; return ret; } Pointer* Parser::parsePointer(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); bool successCircumflex1 = lexer->parsePunctuation(circumflex); if (successCircumflex1) lexer->advance(); else return nullptr; Position* end = lexer->getPosition(_p); Pointer* ret = new(_rp) Pointer(new(_rp) Position(start), new(_rp) Position(end)); return ret; } LifeTime* Parser::parseLifeTime(_Page* _rp) { { Root* node = parseRoot(_rp); if (node != nullptr) return node; } { Local* node = parseLocal(_rp); if (node != nullptr) return node; } { Reference* node = parseReference(_rp); if (node != nullptr) return node; } { Thrown* node = parseThrown(_rp); if (node != nullptr) return node; } return nullptr; } Root* Parser::parseRoot(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); bool successDollar1 = lexer->parsePunctuation(dollar); if (successDollar1) lexer->advance(); else return nullptr; Position* end = lexer->getPosition(_p); Root* ret = new(_rp) Root(new(_rp) Position(start), new(_rp) Position(end)); return ret; } Local* Parser::parseLocal(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); bool successAt1 = lexer->parsePunctuation(at); if (successAt1) lexer->advance(); else return nullptr; string* location = lexer->parseIdentifier(_rp); if ((location != nullptr) && isIdentifier(location)) lexer->advance(); else return nullptr; Position* end = lexer->getPosition(_p); Local* ret = new(_rp) Local(location, new(_rp) Position(start), new(_rp) Position(end)); return ret; } Reference* Parser::parseReference(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); bool successAmpersand1 = lexer->parsePunctuation(ampersand); if (successAmpersand1) lexer->advance(); else return nullptr; Literal* age = lexer->parseLiteral(_rp); if (age != nullptr) lexer->advance(); Position* end = lexer->getPosition(_p); Reference* ret = new(_rp) Reference(age, new(_rp) Position(start), new(_rp) Position(end)); return ret; } Thrown* Parser::parseThrown(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); bool successHash1 = lexer->parsePunctuation(hash); if (successHash1) lexer->advance(); else return nullptr; Position* end = lexer->getPosition(_p); Thrown* ret = new(_rp) Thrown(new(_rp) Position(start), new(_rp) Position(end)); return ret; } FunctionDeclaration* Parser::parseFunctionDeclaration(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); _Array<Modifier>* modifiers = parseModifierList(_rp); bool successFunction2 = lexer->parseKeyword(functionKeyword); if (successFunction2) lexer->advance(); else return nullptr; string* name = lexer->parseIdentifier(_rp); if ((name != nullptr) && isIdentifier(name)) lexer->advance(); else return nullptr; FunctionSignature* signature = parseFunctionSignature(_rp); if (signature == nullptr) return nullptr; Expression* body = parseExpression(_rp); Position* end = lexer->getPosition(_p); FunctionDeclaration* ret = new(_rp) FunctionDeclaration(modifiers, name, signature, body, new(_rp) Position(start), new(_rp) Position(end)); if (modifiers != nullptr) { Modifier* item = nullptr; size_t _modifiers_length = modifiers->length(); for (size_t _i = 0; _i < _modifiers_length; _i++) { item = *(*modifiers)[_i]; item->parent = ret; } } signature->parent = ret; if (body != nullptr) body->parent = ret; return ret; } _Array<Modifier>* Parser::parseModifierList(_Page* _rp) { _Region _region; _Page* _p = _region.get(); _Array<Modifier>* ret = nullptr; while (true) { Modifier* node = parseModifier(_rp); if (node == nullptr) break; if (ret == nullptr) ret = new(_p) _Array<Modifier>(); ret->push(node); } return ret ? new(_rp) _Array<Modifier>(ret) : nullptr; } Modifier* Parser::parseModifier(_Page* _rp) { { StaticWord* node = parseStaticWord(_rp); if (node != nullptr) return node; } return nullptr; } StaticWord* Parser::parseStaticWord(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); bool successStatic1 = lexer->parseKeyword(staticKeyword); if (successStatic1) lexer->advance(); else return nullptr; Position* end = lexer->getPosition(_p); StaticWord* ret = new(_rp) StaticWord(new(_rp) Position(start), new(_rp) Position(end)); return ret; } FunctionSignature* Parser::parseFunctionSignature(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); ParameterClause* parameterClause = parseParameterClause(_rp); if (parameterClause == nullptr) return nullptr; FunctionResult* result = parseFunctionResult(_rp); ThrowsClause* throwsClause = parseThrowsClause(_rp); Position* end = lexer->getPosition(_p); FunctionSignature* ret = new(_rp) FunctionSignature(parameterClause, result, throwsClause, new(_rp) Position(start), new(_rp) Position(end)); parameterClause->parent = ret; if (result != nullptr) result->parent = ret; if (throwsClause != nullptr) throwsClause->parent = ret; return ret; } _Array<ParameterClause>* Parser::parseParameterClauseList(_Page* _rp) { _Region _region; _Page* _p = _region.get(); _Array<ParameterClause>* ret = nullptr; while (true) { ParameterClause* node = parseParameterClause(_rp); if (node == nullptr) break; if (ret == nullptr) ret = new(_p) _Array<ParameterClause>(); ret->push(node); } return ret ? new(_rp) _Array<ParameterClause>(ret) : nullptr; } ParameterClause* Parser::parseParameterClause(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); bool successLeftParen1 = lexer->parsePunctuation(leftParen); if (successLeftParen1) lexer->advance(); else return nullptr; _Array<Parameter>* parameters = parseParameterList(_rp); bool successRightParen3 = lexer->parsePunctuation(rightParen); if (successRightParen3) lexer->advance(); else return nullptr; Position* end = lexer->getPosition(_p); ParameterClause* ret = new(_rp) ParameterClause(parameters, new(_rp) Position(start), new(_rp) Position(end)); if (parameters != nullptr) { Parameter* item = nullptr; size_t _parameters_length = parameters->length(); for (size_t _i = 0; _i < _parameters_length; _i++) { item = *(*parameters)[_i]; item->parent = ret; } } return ret; } _Array<Parameter>* Parser::parseParameterList(_Page* _rp) { _Region _region; _Page* _p = _region.get(); _Array<Parameter>* ret = nullptr; while (true) { Parameter* node = parseParameter(_rp); if (node == nullptr) break; if (ret == nullptr) ret = new(_p) _Array<Parameter>(); ret->push(node); } return ret ? new(_rp) _Array<Parameter>(ret) : nullptr; } Parameter* Parser::parseParameter(_Page* _rp) { { ConstParameter* node = parseConstParameter(_rp); if (node != nullptr) return node; } { VarParameter* node = parseVarParameter(_rp); if (node != nullptr) return node; } return nullptr; } ConstParameter* Parser::parseConstParameter(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); bool successLet1 = lexer->parseKeyword(letKeyword); if (successLet1) lexer->advance(); string* name = lexer->parseIdentifier(_rp); if ((name != nullptr) && isIdentifier(name)) lexer->advance(); else return nullptr; bool successColon3 = lexer->parsePunctuation(colon); if (successColon3) lexer->advance(); else return nullptr; Type* parameterType = parseType(_rp); if (parameterType == nullptr) return nullptr; bool successComma5 = lexer->parsePunctuation(comma); if (successComma5) lexer->advance(); Position* end = lexer->getPosition(_p); ConstParameter* ret = new(_rp) ConstParameter(name, parameterType, new(_rp) Position(start), new(_rp) Position(end)); parameterType->parent = ret; return ret; } VarParameter* Parser::parseVarParameter(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); bool successMutable1 = lexer->parseKeyword(mutableKeyword); if (successMutable1) lexer->advance(); else return nullptr; string* name = lexer->parseIdentifier(_rp); if ((name != nullptr) && isIdentifier(name)) lexer->advance(); else return nullptr; bool successColon3 = lexer->parsePunctuation(colon); if (successColon3) lexer->advance(); else return nullptr; Type* parameterType = parseType(_rp); if (parameterType == nullptr) return nullptr; bool successComma5 = lexer->parsePunctuation(comma); if (successComma5) lexer->advance(); Position* end = lexer->getPosition(_p); VarParameter* ret = new(_rp) VarParameter(name, parameterType, new(_rp) Position(start), new(_rp) Position(end)); parameterType->parent = ret; return ret; } FunctionResult* Parser::parseFunctionResult(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); bool successColon1 = lexer->parsePunctuation(colon); if (successColon1) lexer->advance(); else return nullptr; Type* resultType = parseType(_rp); if (resultType == nullptr) return nullptr; Position* end = lexer->getPosition(_p); FunctionResult* ret = new(_rp) FunctionResult(resultType, new(_rp) Position(start), new(_rp) Position(end)); resultType->parent = ret; return ret; } ThrowsClause* Parser::parseThrowsClause(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); bool successThrows1 = lexer->parseKeyword(throwsKeyword); if (successThrows1) lexer->advance(); else return nullptr; Type* throwsType = parseType(_rp); if (throwsType == nullptr) return nullptr; Position* end = lexer->getPosition(_p); ThrowsClause* ret = new(_rp) ThrowsClause(throwsType, new(_rp) Position(start), new(_rp) Position(end)); throwsType->parent = ret; return ret; } EnumDeclaration* Parser::parseEnumDeclaration(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); bool successEnum1 = lexer->parseKeyword(enumKeyword); if (successEnum1) lexer->advance(); else return nullptr; string* name = lexer->parseIdentifier(_rp); if ((name != nullptr) && isIdentifier(name)) lexer->advance(); else return nullptr; bool successLeftCurly3 = lexer->parsePunctuation(leftCurly); if (successLeftCurly3) lexer->advance(); else return nullptr; _Array<EnumMember>* members = parseEnumMemberList(_rp); bool successRightCurly5 = lexer->parsePunctuation(rightCurly); if (successRightCurly5) lexer->advance(); else return nullptr; Position* end = lexer->getPosition(_p); EnumDeclaration* ret = new(_rp) EnumDeclaration(name, members, new(_rp) Position(start), new(_rp) Position(end)); if (members != nullptr) { EnumMember* item = nullptr; size_t _members_length = members->length(); for (size_t _i = 0; _i < _members_length; _i++) { item = *(*members)[_i]; item->parent = ret; } } return ret; } _Array<EnumMember>* Parser::parseEnumMemberList(_Page* _rp) { _Region _region; _Page* _p = _region.get(); _Array<EnumMember>* ret = nullptr; while (true) { EnumMember* node = parseEnumMember(_rp); if (node == nullptr) break; if (ret == nullptr) ret = new(_p) _Array<EnumMember>(); ret->push(node); } return ret ? new(_rp) _Array<EnumMember>(ret) : nullptr; } EnumMember* Parser::parseEnumMember(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); bool successCase1 = lexer->parseKeyword(caseKeyword); if (successCase1) lexer->advance(); else return nullptr; EnumCase* enumCase = parseEnumCase(_rp); if (enumCase == nullptr) return nullptr; _Array<AdditionalCase>* additionalCases = parseAdditionalCaseList(_rp); ParameterClause* parameterClause = parseParameterClause(_rp); Position* end = lexer->getPosition(_p); EnumMember* ret = new(_rp) EnumMember(enumCase, additionalCases, parameterClause, new(_rp) Position(start), new(_rp) Position(end)); enumCase->parent = ret; if (additionalCases != nullptr) { AdditionalCase* item = nullptr; size_t _additionalCases_length = additionalCases->length(); for (size_t _i = 0; _i < _additionalCases_length; _i++) { item = *(*additionalCases)[_i]; item->parent = ret; } } if (parameterClause != nullptr) parameterClause->parent = ret; return ret; } EnumCase* Parser::parseEnumCase(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); string* name = lexer->parseIdentifier(_rp); if ((name != nullptr) && isIdentifier(name)) lexer->advance(); else return nullptr; Position* end = lexer->getPosition(_p); EnumCase* ret = new(_rp) EnumCase(name, new(_rp) Position(start), new(_rp) Position(end)); return ret; } _Array<AdditionalCase>* Parser::parseAdditionalCaseList(_Page* _rp) { _Region _region; _Page* _p = _region.get(); _Array<AdditionalCase>* ret = nullptr; while (true) { AdditionalCase* node = parseAdditionalCase(_rp); if (node == nullptr) break; if (ret == nullptr) ret = new(_p) _Array<AdditionalCase>(); ret->push(node); } return ret ? new(_rp) _Array<AdditionalCase>(ret) : nullptr; } AdditionalCase* Parser::parseAdditionalCase(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); bool successComma1 = lexer->parsePunctuation(comma); if (successComma1) lexer->advance(); else return nullptr; EnumCase* enumCase = parseEnumCase(_rp); if (enumCase == nullptr) return nullptr; Position* end = lexer->getPosition(_p); AdditionalCase* ret = new(_rp) AdditionalCase(enumCase, new(_rp) Position(start), new(_rp) Position(end)); enumCase->parent = ret; return ret; } ClassDeclaration* Parser::parseClassDeclaration(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); bool successClass1 = lexer->parseKeyword(classKeyword); if (successClass1) lexer->advance(); else return nullptr; string* name = lexer->parseIdentifier(_rp); if ((name != nullptr) && isIdentifier(name)) lexer->advance(); else return nullptr; TypeInheritanceClause* typeInheritanceClause = parseTypeInheritanceClause(_rp); ClassBody* body = parseClassBody(_rp); Position* end = lexer->getPosition(_p); ClassDeclaration* ret = new(_rp) ClassDeclaration(name, typeInheritanceClause, body, new(_rp) Position(start), new(_rp) Position(end)); if (typeInheritanceClause != nullptr) typeInheritanceClause->parent = ret; if (body != nullptr) body->parent = ret; return ret; } TypeInheritanceClause* Parser::parseTypeInheritanceClause(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); bool successExtends1 = lexer->parseKeyword(extendsKeyword); if (successExtends1) lexer->advance(); else return nullptr; _Array<Inheritance>* inheritances = parseInheritanceList(_rp); Position* end = lexer->getPosition(_p); TypeInheritanceClause* ret = new(_rp) TypeInheritanceClause(inheritances, new(_rp) Position(start), new(_rp) Position(end)); if (inheritances != nullptr) { Inheritance* item = nullptr; size_t _inheritances_length = inheritances->length(); for (size_t _i = 0; _i < _inheritances_length; _i++) { item = *(*inheritances)[_i]; item->parent = ret; } } return ret; } _Array<Inheritance>* Parser::parseInheritanceList(_Page* _rp) { _Region _region; _Page* _p = _region.get(); _Array<Inheritance>* ret = nullptr; while (true) { Inheritance* node = parseInheritance(_rp); if (node == nullptr) break; if (ret == nullptr) ret = new(_p) _Array<Inheritance>(); ret->push(node); } return ret ? new(_rp) _Array<Inheritance>(ret) : nullptr; } Inheritance* Parser::parseInheritance(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); Type* type = parseType(_rp); if (type == nullptr) return nullptr; bool successComma2 = lexer->parsePunctuation(comma); if (successComma2) lexer->advance(); Position* end = lexer->getPosition(_p); Inheritance* ret = new(_rp) Inheritance(type, new(_rp) Position(start), new(_rp) Position(end)); type->parent = ret; return ret; } ClassBody* Parser::parseClassBody(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); bool successLeftCurly1 = lexer->parsePunctuation(leftCurly); if (successLeftCurly1) lexer->advance(); else return nullptr; _Array<ClassMember>* members = parseClassMemberList(_rp); bool successRightCurly3 = lexer->parsePunctuation(rightCurly); if (successRightCurly3) lexer->advance(); else return nullptr; Position* end = lexer->getPosition(_p); ClassBody* ret = new(_rp) ClassBody(members, new(_rp) Position(start), new(_rp) Position(end)); if (members != nullptr) { ClassMember* item = nullptr; size_t _members_length = members->length(); for (size_t _i = 0; _i < _members_length; _i++) { item = *(*members)[_i]; item->parent = ret; } } return ret; } _Array<ClassMember>* Parser::parseClassMemberList(_Page* _rp) { _Region _region; _Page* _p = _region.get(); _Array<ClassMember>* ret = nullptr; while (true) { ClassMember* node = parseClassMember(_rp); if (node == nullptr) break; if (ret == nullptr) ret = new(_p) _Array<ClassMember>(); ret->push(node); } return ret ? new(_rp) _Array<ClassMember>(ret) : nullptr; } ClassMember* Parser::parseClassMember(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); Declaration* declaration = parseDeclaration(_rp); if (declaration == nullptr) return nullptr; Position* end = lexer->getPosition(_p); ClassMember* ret = new(_rp) ClassMember(declaration, new(_rp) Position(start), new(_rp) Position(end)); declaration->parent = ret; return ret; } ConstructorDeclaration* Parser::parseConstructorDeclaration(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); bool successConstructor1 = lexer->parseKeyword(constructorKeyword); if (successConstructor1) lexer->advance(); else return nullptr; ParameterClause* parameterClause = parseParameterClause(_rp); if (parameterClause == nullptr) return nullptr; Expression* body = parseExpression(_rp); if (body == nullptr) return nullptr; Position* end = lexer->getPosition(_p); ConstructorDeclaration* ret = new(_rp) ConstructorDeclaration(parameterClause, body, new(_rp) Position(start), new(_rp) Position(end)); parameterClause->parent = ret; body->parent = ret; return ret; } Expression* Parser::parseExpression(_Page* _rp) { { CodeBlock* node = parseCodeBlock(_rp); if (node != nullptr) return node; } { SimpleExpression* node = parseSimpleExpression(_rp); if (node != nullptr) return node; } return nullptr; } CodeBlock* Parser::parseCodeBlock(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); bool successLeftCurly1 = lexer->parsePunctuation(leftCurly); if (successLeftCurly1) lexer->advance(); else return nullptr; _Array<Statement>* statements = parseStatementList(_rp); bool successRightCurly3 = lexer->parsePunctuation(rightCurly); if (successRightCurly3) lexer->advance(); else return nullptr; Position* end = lexer->getPosition(_p); CodeBlock* ret = new(_rp) CodeBlock(statements, new(_rp) Position(start), new(_rp) Position(end)); if (statements != nullptr) { Statement* item = nullptr; size_t _statements_length = statements->length(); for (size_t _i = 0; _i < _statements_length; _i++) { item = *(*statements)[_i]; item->parent = ret; } } return ret; } SimpleExpression* Parser::parseSimpleExpression(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); PrefixExpression* prefixExpression = parsePrefixExpression(_rp); if (prefixExpression == nullptr) return nullptr; _Array<BinaryExpression>* binaryExpressions = parseBinaryExpressionList(_rp); Position* end = lexer->getPosition(_p); SimpleExpression* ret = new(_rp) SimpleExpression(prefixExpression, binaryExpressions, new(_rp) Position(start), new(_rp) Position(end)); prefixExpression->parent = ret; if (binaryExpressions != nullptr) { BinaryExpression* item = nullptr; size_t _binaryExpressions_length = binaryExpressions->length(); for (size_t _i = 0; _i < _binaryExpressions_length; _i++) { item = *(*binaryExpressions)[_i]; item->parent = ret; } } return ret; } PrefixExpression* Parser::parsePrefixExpression(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); string* prefixOperator = lexer->parsePrefixOperator(_rp); if (prefixOperator != nullptr) lexer->advance(); PostfixExpression* expression = parsePostfixExpression(_rp); if (expression == nullptr) return nullptr; Position* end = lexer->getPosition(_p); PrefixExpression* ret = new(_rp) PrefixExpression(prefixOperator, expression, new(_rp) Position(start), new(_rp) Position(end)); expression->parent = ret; return ret; } PostfixExpression* Parser::parsePostfixExpression(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); PrimaryExpression* primaryExpression = parsePrimaryExpression(_rp); if (primaryExpression == nullptr) return nullptr; _Array<Postfix>* postfixes = parsePostfixList(_rp); Position* end = lexer->getPosition(_p); PostfixExpression* ret = new(_rp) PostfixExpression(primaryExpression, postfixes, new(_rp) Position(start), new(_rp) Position(end)); primaryExpression->parent = ret; if (postfixes != nullptr) { Postfix* item = nullptr; size_t _postfixes_length = postfixes->length(); for (size_t _i = 0; _i < _postfixes_length; _i++) { item = *(*postfixes)[_i]; item->parent = ret; } } return ret; } PrimaryExpression* Parser::parsePrimaryExpression(_Page* _rp) { { IdentifierExpression* node = parseIdentifierExpression(_rp); if (node != nullptr) return node; } { LiteralExpression* node = parseLiteralExpression(_rp); if (node != nullptr) return node; } { IfExpression* node = parseIfExpression(_rp); if (node != nullptr) return node; } { SwitchExpression* node = parseSwitchExpression(_rp); if (node != nullptr) return node; } { ForExpression* node = parseForExpression(_rp); if (node != nullptr) return node; } { WhileExpression* node = parseWhileExpression(_rp); if (node != nullptr) return node; } { DoExpression* node = parseDoExpression(_rp); if (node != nullptr) return node; } { ParenthesizedExpression* node = parseParenthesizedExpression(_rp); if (node != nullptr) return node; } { ReturnExpression* node = parseReturnExpression(_rp); if (node != nullptr) return node; } { ThrowExpression* node = parseThrowExpression(_rp); if (node != nullptr) return node; } { BreakExpression* node = parseBreakExpression(_rp); if (node != nullptr) return node; } { ConstructorCall* node = parseConstructorCall(_rp); if (node != nullptr) return node; } { ThisExpression* node = parseThisExpression(_rp); if (node != nullptr) return node; } { NullExpression* node = parseNullExpression(_rp); if (node != nullptr) return node; } return nullptr; } IdentifierExpression* Parser::parseIdentifierExpression(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); string* name = lexer->parseIdentifier(_rp); if ((name != nullptr) && isIdentifier(name)) lexer->advance(); else return nullptr; Position* end = lexer->getPosition(_p); IdentifierExpression* ret = new(_rp) IdentifierExpression(name, new(_rp) Position(start), new(_rp) Position(end)); return ret; } LiteralExpression* Parser::parseLiteralExpression(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); Literal* literal = lexer->parseLiteral(_rp); if (literal != nullptr) lexer->advance(); else return nullptr; Position* end = lexer->getPosition(_p); LiteralExpression* ret = new(_rp) LiteralExpression(literal, new(_rp) Position(start), new(_rp) Position(end)); return ret; } IfExpression* Parser::parseIfExpression(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); bool successIf1 = lexer->parseKeyword(ifKeyword); if (successIf1) lexer->advance(); else return nullptr; Expression* condition = parseExpression(_rp); if (condition == nullptr) return nullptr; Expression* consequent = parseExpression(_rp); if (consequent == nullptr) return nullptr; ElseClause* elseClause = parseElseClause(_rp); Position* end = lexer->getPosition(_p); IfExpression* ret = new(_rp) IfExpression(condition, consequent, elseClause, new(_rp) Position(start), new(_rp) Position(end)); condition->parent = ret; consequent->parent = ret; if (elseClause != nullptr) elseClause->parent = ret; return ret; } ElseClause* Parser::parseElseClause(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); bool successElse1 = lexer->parseKeyword(elseKeyword); if (successElse1) lexer->advance(); else return nullptr; Expression* alternative = parseExpression(_rp); if (alternative == nullptr) return nullptr; Position* end = lexer->getPosition(_p); ElseClause* ret = new(_rp) ElseClause(alternative, new(_rp) Position(start), new(_rp) Position(end)); alternative->parent = ret; return ret; } SwitchExpression* Parser::parseSwitchExpression(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); bool successSwitch1 = lexer->parseKeyword(switchKeyword); if (successSwitch1) lexer->advance(); else return nullptr; Expression* expression = parseExpression(_rp); if (expression == nullptr) return nullptr; SwitchBody* body = parseSwitchBody(_rp); if (body == nullptr) return nullptr; Position* end = lexer->getPosition(_p); SwitchExpression* ret = new(_rp) SwitchExpression(expression, body, new(_rp) Position(start), new(_rp) Position(end)); expression->parent = ret; body->parent = ret; return ret; } SwitchBody* Parser::parseSwitchBody(_Page* _rp) { { CurliedSwitchBody* node = parseCurliedSwitchBody(_rp); if (node != nullptr) return node; } { NakedSwitchBody* node = parseNakedSwitchBody(_rp); if (node != nullptr) return node; } return nullptr; } CurliedSwitchBody* Parser::parseCurliedSwitchBody(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); bool successLeftCurly1 = lexer->parsePunctuation(leftCurly); if (successLeftCurly1) lexer->advance(); else return nullptr; _Array<SwitchCase>* cases = parseSwitchCaseList(_rp); bool successRightCurly3 = lexer->parsePunctuation(rightCurly); if (successRightCurly3) lexer->advance(); else return nullptr; Position* end = lexer->getPosition(_p); CurliedSwitchBody* ret = new(_rp) CurliedSwitchBody(cases, new(_rp) Position(start), new(_rp) Position(end)); if (cases != nullptr) { SwitchCase* item = nullptr; size_t _cases_length = cases->length(); for (size_t _i = 0; _i < _cases_length; _i++) { item = *(*cases)[_i]; item->parent = ret; } } return ret; } NakedSwitchBody* Parser::parseNakedSwitchBody(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); _Array<SwitchCase>* cases = parseSwitchCaseList(_rp); Position* end = lexer->getPosition(_p); NakedSwitchBody* ret = new(_rp) NakedSwitchBody(cases, new(_rp) Position(start), new(_rp) Position(end)); if (cases != nullptr) { SwitchCase* item = nullptr; size_t _cases_length = cases->length(); for (size_t _i = 0; _i < _cases_length; _i++) { item = *(*cases)[_i]; item->parent = ret; } } return ret; } _Array<SwitchCase>* Parser::parseSwitchCaseList(_Page* _rp) { _Region _region; _Page* _p = _region.get(); _Array<SwitchCase>* ret = nullptr; while (true) { SwitchCase* node = parseSwitchCase(_rp); if (node == nullptr) break; if (ret == nullptr) ret = new(_p) _Array<SwitchCase>(); ret->push(node); } return ret ? new(_rp) _Array<SwitchCase>(ret) : nullptr; } SwitchCase* Parser::parseSwitchCase(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); CaseLabel* label = parseCaseLabel(_rp); if (label == nullptr) return nullptr; CaseContent* content = parseCaseContent(_rp); if (content == nullptr) return nullptr; Position* end = lexer->getPosition(_p); SwitchCase* ret = new(_rp) SwitchCase(label, content, new(_rp) Position(start), new(_rp) Position(end)); label->parent = ret; content->parent = ret; return ret; } CaseLabel* Parser::parseCaseLabel(_Page* _rp) { { ItemCaseLabel* node = parseItemCaseLabel(_rp); if (node != nullptr) return node; } { DefaultCaseLabel* node = parseDefaultCaseLabel(_rp); if (node != nullptr) return node; } return nullptr; } ItemCaseLabel* Parser::parseItemCaseLabel(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); bool successCase1 = lexer->parseKeyword(caseKeyword); if (successCase1) lexer->advance(); else return nullptr; Pattern* pattern = parsePattern(_rp); if (pattern == nullptr) return nullptr; _Array<CaseItem>* additionalPatterns = parseCaseItemList(_rp); bool successColon4 = lexer->parsePunctuation(colon); if (successColon4) lexer->advance(); else return nullptr; Position* end = lexer->getPosition(_p); ItemCaseLabel* ret = new(_rp) ItemCaseLabel(pattern, additionalPatterns, new(_rp) Position(start), new(_rp) Position(end)); pattern->parent = ret; if (additionalPatterns != nullptr) { CaseItem* item = nullptr; size_t _additionalPatterns_length = additionalPatterns->length(); for (size_t _i = 0; _i < _additionalPatterns_length; _i++) { item = *(*additionalPatterns)[_i]; item->parent = ret; } } return ret; } DefaultCaseLabel* Parser::parseDefaultCaseLabel(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); bool successDefault1 = lexer->parseKeyword(defaultKeyword); if (successDefault1) lexer->advance(); else return nullptr; bool successColon2 = lexer->parsePunctuation(colon); if (successColon2) lexer->advance(); else return nullptr; Position* end = lexer->getPosition(_p); DefaultCaseLabel* ret = new(_rp) DefaultCaseLabel(new(_rp) Position(start), new(_rp) Position(end)); return ret; } _Array<CaseItem>* Parser::parseCaseItemList(_Page* _rp) { _Region _region; _Page* _p = _region.get(); _Array<CaseItem>* ret = nullptr; while (true) { CaseItem* node = parseCaseItem(_rp); if (node == nullptr) break; if (ret == nullptr) ret = new(_p) _Array<CaseItem>(); ret->push(node); } return ret ? new(_rp) _Array<CaseItem>(ret) : nullptr; } CaseItem* Parser::parseCaseItem(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); bool successComma1 = lexer->parsePunctuation(comma); if (successComma1) lexer->advance(); else return nullptr; Pattern* pattern = parsePattern(_rp); if (pattern == nullptr) return nullptr; Position* end = lexer->getPosition(_p); CaseItem* ret = new(_rp) CaseItem(pattern, new(_rp) Position(start), new(_rp) Position(end)); pattern->parent = ret; return ret; } CaseContent* Parser::parseCaseContent(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); _Array<Statement>* statements = parseStatementList(_rp); Position* end = lexer->getPosition(_p); CaseContent* ret = new(_rp) CaseContent(statements, new(_rp) Position(start), new(_rp) Position(end)); if (statements != nullptr) { Statement* item = nullptr; size_t _statements_length = statements->length(); for (size_t _i = 0; _i < _statements_length; _i++) { item = *(*statements)[_i]; item->parent = ret; } } return ret; } ForExpression* Parser::parseForExpression(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); bool successFor1 = lexer->parseKeyword(forKeyword); if (successFor1) lexer->advance(); else return nullptr; IdentifierPattern* pattern = parseIdentifierPattern(_rp); if (pattern == nullptr) return nullptr; bool successIn3 = lexer->parseKeyword(inKeyword); if (successIn3) lexer->advance(); else return nullptr; Expression* expression = parseExpression(_rp); if (expression == nullptr) return nullptr; Expression* code = parseExpression(_rp); if (code == nullptr) return nullptr; Position* end = lexer->getPosition(_p); ForExpression* ret = new(_rp) ForExpression(pattern, expression, code, new(_rp) Position(start), new(_rp) Position(end)); pattern->parent = ret; expression->parent = ret; code->parent = ret; return ret; } WhileExpression* Parser::parseWhileExpression(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); bool successWhile1 = lexer->parseKeyword(whileKeyword); if (successWhile1) lexer->advance(); else return nullptr; Expression* condition = parseExpression(_rp); if (condition == nullptr) return nullptr; Expression* code = parseExpression(_rp); if (code == nullptr) return nullptr; Position* end = lexer->getPosition(_p); WhileExpression* ret = new(_rp) WhileExpression(condition, code, new(_rp) Position(start), new(_rp) Position(end)); condition->parent = ret; code->parent = ret; return ret; } DoExpression* Parser::parseDoExpression(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); bool successDo1 = lexer->parseKeyword(doKeyword); if (successDo1) lexer->advance(); else return nullptr; Expression* code = parseExpression(_rp); if (code == nullptr) return nullptr; bool successWhile3 = lexer->parseKeyword(whileKeyword); if (successWhile3) lexer->advance(); else return nullptr; Expression* condition = parseExpression(_rp); if (condition == nullptr) return nullptr; Position* end = lexer->getPosition(_p); DoExpression* ret = new(_rp) DoExpression(code, condition, new(_rp) Position(start), new(_rp) Position(end)); code->parent = ret; condition->parent = ret; return ret; } ParenthesizedExpression* Parser::parseParenthesizedExpression(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); bool successLeftParen1 = lexer->parsePunctuation(leftParen); if (successLeftParen1) lexer->advance(); else return nullptr; _Array<ExpressionElement>* expressionElements = parseExpressionElementList(_rp); bool successRightParen3 = lexer->parsePunctuation(rightParen); if (successRightParen3) lexer->advance(); else return nullptr; Position* end = lexer->getPosition(_p); ParenthesizedExpression* ret = new(_rp) ParenthesizedExpression(expressionElements, new(_rp) Position(start), new(_rp) Position(end)); if (expressionElements != nullptr) { ExpressionElement* item = nullptr; size_t _expressionElements_length = expressionElements->length(); for (size_t _i = 0; _i < _expressionElements_length; _i++) { item = *(*expressionElements)[_i]; item->parent = ret; } } return ret; } _Array<ExpressionElement>* Parser::parseExpressionElementList(_Page* _rp) { _Region _region; _Page* _p = _region.get(); _Array<ExpressionElement>* ret = nullptr; while (true) { ExpressionElement* node = parseExpressionElement(_rp); if (node == nullptr) break; if (ret == nullptr) ret = new(_p) _Array<ExpressionElement>(); ret->push(node); } return ret ? new(_rp) _Array<ExpressionElement>(ret) : nullptr; } ExpressionElement* Parser::parseExpressionElement(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); Expression* expression = parseExpression(_rp); if (expression == nullptr) return nullptr; bool successComma2 = lexer->parsePunctuation(comma); if (successComma2) lexer->advance(); Position* end = lexer->getPosition(_p); ExpressionElement* ret = new(_rp) ExpressionElement(expression, new(_rp) Position(start), new(_rp) Position(end)); expression->parent = ret; return ret; } ReturnExpression* Parser::parseReturnExpression(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); bool successReturn1 = lexer->parseKeyword(returnKeyword); if (successReturn1) lexer->advance(); else return nullptr; ParenthesizedExpression* expression = parseParenthesizedExpression(_rp); Position* end = lexer->getPosition(_p); ReturnExpression* ret = new(_rp) ReturnExpression(expression, new(_rp) Position(start), new(_rp) Position(end)); if (expression != nullptr) expression->parent = ret; return ret; } ThrowExpression* Parser::parseThrowExpression(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); bool successThrow1 = lexer->parseKeyword(throwKeyword); if (successThrow1) lexer->advance(); else return nullptr; IdentifierExpression* error = parseIdentifierExpression(_rp); if (error == nullptr) return nullptr; ParenthesizedExpression* arguments = parseParenthesizedExpression(_rp); Position* end = lexer->getPosition(_p); ThrowExpression* ret = new(_rp) ThrowExpression(error, arguments, new(_rp) Position(start), new(_rp) Position(end)); error->parent = ret; if (arguments != nullptr) arguments->parent = ret; return ret; } BreakExpression* Parser::parseBreakExpression(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); bool successBreak1 = lexer->parseKeyword(breakKeyword); if (successBreak1) lexer->advance(); else return nullptr; ParenthesizedExpression* expression = parseParenthesizedExpression(_rp); Position* end = lexer->getPosition(_p); BreakExpression* ret = new(_rp) BreakExpression(expression, new(_rp) Position(start), new(_rp) Position(end)); if (expression != nullptr) expression->parent = ret; return ret; } ConstructorCall* Parser::parseConstructorCall(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); bool successNew1 = lexer->parseKeyword(newKeyword); if (successNew1) lexer->advance(); else return nullptr; Type* typeToConstruct = parseType(_rp); if (typeToConstruct == nullptr) return nullptr; ParenthesizedExpression* arguments = parseParenthesizedExpression(_rp); if (arguments == nullptr) return nullptr; _Array<CatchClause>* catchClauses = parseCatchClauseList(_rp); Position* end = lexer->getPosition(_p); ConstructorCall* ret = new(_rp) ConstructorCall(typeToConstruct, arguments, catchClauses, new(_rp) Position(start), new(_rp) Position(end)); typeToConstruct->parent = ret; arguments->parent = ret; if (catchClauses != nullptr) { CatchClause* item = nullptr; size_t _catchClauses_length = catchClauses->length(); for (size_t _i = 0; _i < _catchClauses_length; _i++) { item = *(*catchClauses)[_i]; item->parent = ret; } } return ret; } ThisExpression* Parser::parseThisExpression(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); bool successThis1 = lexer->parseKeyword(thisKeyword); if (successThis1) lexer->advance(); else return nullptr; Position* end = lexer->getPosition(_p); ThisExpression* ret = new(_rp) ThisExpression(new(_rp) Position(start), new(_rp) Position(end)); return ret; } NullExpression* Parser::parseNullExpression(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); bool successNull1 = lexer->parseKeyword(nullKeyword); if (successNull1) lexer->advance(); else return nullptr; Position* end = lexer->getPosition(_p); NullExpression* ret = new(_rp) NullExpression(new(_rp) Position(start), new(_rp) Position(end)); return ret; } _Array<Postfix>* Parser::parsePostfixList(_Page* _rp) { _Region _region; _Page* _p = _region.get(); _Array<Postfix>* ret = nullptr; while (true) { Postfix* node = parsePostfix(_rp); if (node == nullptr) break; if (ret == nullptr) ret = new(_p) _Array<Postfix>(); ret->push(node); } return ret ? new(_rp) _Array<Postfix>(ret) : nullptr; } Postfix* Parser::parsePostfix(_Page* _rp) { { OperatorPostfix* node = parseOperatorPostfix(_rp); if (node != nullptr) return node; } { FunctionCall* node = parseFunctionCall(_rp); if (node != nullptr) return node; } { MemberExpression* node = parseMemberExpression(_rp); if (node != nullptr) return node; } { Subscript* node = parseSubscript(_rp); if (node != nullptr) return node; } return nullptr; } OperatorPostfix* Parser::parseOperatorPostfix(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); string* postfixOperator = lexer->parsePostfixOperator(_rp); if (postfixOperator != nullptr) lexer->advance(); else return nullptr; Position* end = lexer->getPosition(_p); OperatorPostfix* ret = new(_rp) OperatorPostfix(postfixOperator, new(_rp) Position(start), new(_rp) Position(end)); return ret; } FunctionCall* Parser::parseFunctionCall(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); ParenthesizedExpression* arguments = parseParenthesizedExpression(_rp); if (arguments == nullptr) return nullptr; _Array<CatchClause>* catchClauses = parseCatchClauseList(_rp); Position* end = lexer->getPosition(_p); FunctionCall* ret = new(_rp) FunctionCall(arguments, catchClauses, new(_rp) Position(start), new(_rp) Position(end)); arguments->parent = ret; if (catchClauses != nullptr) { CatchClause* item = nullptr; size_t _catchClauses_length = catchClauses->length(); for (size_t _i = 0; _i < _catchClauses_length; _i++) { item = *(*catchClauses)[_i]; item->parent = ret; } } return ret; } _Array<CatchClause>* Parser::parseCatchClauseList(_Page* _rp) { _Region _region; _Page* _p = _region.get(); _Array<CatchClause>* ret = nullptr; while (true) { CatchClause* node = parseCatchClause(_rp); if (node == nullptr) break; if (ret == nullptr) ret = new(_p) _Array<CatchClause>(); ret->push(node); } return ret ? new(_rp) _Array<CatchClause>(ret) : nullptr; } CatchClause* Parser::parseCatchClause(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); bool successCatch1 = lexer->parseKeyword(catchKeyword); if (successCatch1) lexer->advance(); else return nullptr; CatchPattern* catchPattern = parseCatchPattern(_rp); if (catchPattern == nullptr) return nullptr; TuplePattern* bindingPattern = parseTuplePattern(_rp); Expression* expression = parseExpression(_rp); if (expression == nullptr) return nullptr; Position* end = lexer->getPosition(_p); CatchClause* ret = new(_rp) CatchClause(catchPattern, bindingPattern, expression, new(_rp) Position(start), new(_rp) Position(end)); catchPattern->parent = ret; if (bindingPattern != nullptr) bindingPattern->parent = ret; expression->parent = ret; return ret; } CatchPattern* Parser::parseCatchPattern(_Page* _rp) { { WildCardCatchPattern* node = parseWildCardCatchPattern(_rp); if (node != nullptr) return node; } { IdentifierCatchPattern* node = parseIdentifierCatchPattern(_rp); if (node != nullptr) return node; } return nullptr; } WildCardCatchPattern* Parser::parseWildCardCatchPattern(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); WildcardPattern* pattern = parseWildcardPattern(_rp); if (pattern == nullptr) return nullptr; Position* end = lexer->getPosition(_p); WildCardCatchPattern* ret = new(_rp) WildCardCatchPattern(pattern, new(_rp) Position(start), new(_rp) Position(end)); pattern->parent = ret; return ret; } IdentifierCatchPattern* Parser::parseIdentifierCatchPattern(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); string* name = lexer->parseIdentifier(_rp); if ((name != nullptr) && isIdentifier(name)) lexer->advance(); else return nullptr; MemberExpression* member = parseMemberExpression(_rp); Position* end = lexer->getPosition(_p); IdentifierCatchPattern* ret = new(_rp) IdentifierCatchPattern(name, member, new(_rp) Position(start), new(_rp) Position(end)); if (member != nullptr) member->parent = ret; return ret; } WildcardPattern* Parser::parseWildcardPattern(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); bool successUnderscore1 = lexer->parsePunctuation(underscore); if (successUnderscore1) lexer->advance(); else return nullptr; Position* end = lexer->getPosition(_p); WildcardPattern* ret = new(_rp) WildcardPattern(new(_rp) Position(start), new(_rp) Position(end)); return ret; } TuplePattern* Parser::parseTuplePattern(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); bool successLeftParen1 = lexer->parsePunctuation(leftParen); if (successLeftParen1) lexer->advance(); else return nullptr; _Array<TuplePatternElement>* elements = parseTuplePatternElementList(_rp); bool successRightParen3 = lexer->parsePunctuation(rightParen); if (successRightParen3) lexer->advance(); else return nullptr; Position* end = lexer->getPosition(_p); TuplePattern* ret = new(_rp) TuplePattern(elements, new(_rp) Position(start), new(_rp) Position(end)); if (elements != nullptr) { TuplePatternElement* item = nullptr; size_t _elements_length = elements->length(); for (size_t _i = 0; _i < _elements_length; _i++) { item = *(*elements)[_i]; item->parent = ret; } } return ret; } _Array<TuplePatternElement>* Parser::parseTuplePatternElementList(_Page* _rp) { _Region _region; _Page* _p = _region.get(); _Array<TuplePatternElement>* ret = nullptr; while (true) { TuplePatternElement* node = parseTuplePatternElement(_rp); if (node == nullptr) break; if (ret == nullptr) ret = new(_p) _Array<TuplePatternElement>(); ret->push(node); } return ret ? new(_rp) _Array<TuplePatternElement>(ret) : nullptr; } TuplePatternElement* Parser::parseTuplePatternElement(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); Pattern* pattern = parsePattern(_rp); if (pattern == nullptr) return nullptr; bool successComma2 = lexer->parsePunctuation(comma); if (successComma2) lexer->advance(); Position* end = lexer->getPosition(_p); TuplePatternElement* ret = new(_rp) TuplePatternElement(pattern, new(_rp) Position(start), new(_rp) Position(end)); pattern->parent = ret; return ret; } ExpressionPattern* Parser::parseExpressionPattern(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); Expression* expression = parseExpression(_rp); if (expression == nullptr) return nullptr; Position* end = lexer->getPosition(_p); ExpressionPattern* ret = new(_rp) ExpressionPattern(expression, new(_rp) Position(start), new(_rp) Position(end)); expression->parent = ret; return ret; } MemberExpression* Parser::parseMemberExpression(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); bool successDot1 = lexer->parsePunctuation(dot); if (successDot1) lexer->advance(); else return nullptr; string* member = lexer->parseIdentifier(_rp); if ((member != nullptr) && isIdentifier(member)) lexer->advance(); else return nullptr; Position* end = lexer->getPosition(_p); MemberExpression* ret = new(_rp) MemberExpression(member, new(_rp) Position(start), new(_rp) Position(end)); return ret; } Subscript* Parser::parseSubscript(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); bool successLeftBracket1 = lexer->parsePunctuation(leftBracket); if (successLeftBracket1) lexer->advance(); else return nullptr; _Array<ExpressionElement>* expressions = parseExpressionElementList(_rp); bool successRightBracket3 = lexer->parsePunctuation(rightBracket); if (successRightBracket3) lexer->advance(); else return nullptr; Position* end = lexer->getPosition(_p); Subscript* ret = new(_rp) Subscript(expressions, new(_rp) Position(start), new(_rp) Position(end)); if (expressions != nullptr) { ExpressionElement* item = nullptr; size_t _expressions_length = expressions->length(); for (size_t _i = 0; _i < _expressions_length; _i++) { item = *(*expressions)[_i]; item->parent = ret; } } return ret; } _Array<BinaryExpression>* Parser::parseBinaryExpressionList(_Page* _rp) { _Region _region; _Page* _p = _region.get(); _Array<BinaryExpression>* ret = nullptr; while (true) { BinaryExpression* node = parseBinaryExpression(_rp); if (node == nullptr) break; if (ret == nullptr) ret = new(_p) _Array<BinaryExpression>(); ret->push(node); } return ret ? new(_rp) _Array<BinaryExpression>(ret) : nullptr; } BinaryExpression* Parser::parseBinaryExpression(_Page* _rp) { { BinaryOperation* node = parseBinaryOperation(_rp); if (node != nullptr) return node; } { Assignment* node = parseAssignment(_rp); if (node != nullptr) return node; } { TypeQuery* node = parseTypeQuery(_rp); if (node != nullptr) return node; } { TypeCast* node = parseTypeCast(_rp); if (node != nullptr) return node; } return nullptr; } BinaryOperation* Parser::parseBinaryOperation(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); string* binaryOperator = lexer->parseBinaryOperator(_rp); if (binaryOperator != nullptr) lexer->advance(); else return nullptr; PrefixExpression* expression = parsePrefixExpression(_rp); if (expression == nullptr) return nullptr; Position* end = lexer->getPosition(_p); BinaryOperation* ret = new(_rp) BinaryOperation(binaryOperator, expression, new(_rp) Position(start), new(_rp) Position(end)); expression->parent = ret; return ret; } Assignment* Parser::parseAssignment(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); bool successEqual1 = lexer->parsePunctuation(equal); if (successEqual1) lexer->advance(); else return nullptr; Expression* expression = parseExpression(_rp); if (expression == nullptr) return nullptr; Position* end = lexer->getPosition(_p); Assignment* ret = new(_rp) Assignment(expression, new(_rp) Position(start), new(_rp) Position(end)); expression->parent = ret; return ret; } TypeQuery* Parser::parseTypeQuery(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); bool successIs1 = lexer->parseKeyword(isKeyword); if (successIs1) lexer->advance(); else return nullptr; Type* objectType = parseType(_rp); if (objectType == nullptr) return nullptr; Position* end = lexer->getPosition(_p); TypeQuery* ret = new(_rp) TypeQuery(objectType, new(_rp) Position(start), new(_rp) Position(end)); objectType->parent = ret; return ret; } TypeCast* Parser::parseTypeCast(_Page* _rp) { _Region _region; _Page* _p = _region.get(); Position* start = lexer->getPreviousPosition(_p); bool successAs1 = lexer->parseKeyword(asKeyword); if (successAs1) lexer->advance(); else return nullptr; Type* objectType = parseType(_rp); if (objectType == nullptr) return nullptr; Position* end = lexer->getPosition(_p); TypeCast* ret = new(_rp) TypeCast(objectType, new(_rp) Position(start), new(_rp) Position(end)); objectType->parent = ret; return ret; } bool Parser::isAtEnd() { return lexer->isAtEnd(); } bool Parser::isIdentifier(string* id) { if (id->equals(classKeyword)) return false; if (id->equals(functionKeyword)) return false; if (id->equals(ifKeyword)) return false; if (id->equals(elseKeyword)) return false; if (id->equals(switchKeyword)) return false; if (id->equals(caseKeyword)) return false; if (id->equals(defaultKeyword)) return false; if (id->equals(catchKeyword)) return false; if (id->equals(forKeyword)) return false; if (id->equals(inKeyword)) return false; if (id->equals(whileKeyword)) return false; if (id->equals(doKeyword)) return false; if (id->equals(returnKeyword)) return false; if (id->equals(throwKeyword)) return false; if (id->equals(breakKeyword)) return false; if (id->equals(throwsKeyword)) return false; if (id->equals(staticKeyword)) return false; if (id->equals(letKeyword)) return false; if (id->equals(mutableKeyword)) return false; if (id->equals(isKeyword)) return false; if (id->equals(asKeyword)) return false; if (id->equals(constructorKeyword)) return false; if (id->equals(enumKeyword)) return false; if (id->equals(thisKeyword)) return false; if (id->equals(nullKeyword)) return false; if (id->equals(newKeyword)) return false; if (id->equals(extendsKeyword)) return false; return true; } bool Visitor::openProgram(Program* program) { return true; } void Visitor::closeProgram(Program* program) { } bool Visitor::openModule(Module* module) { return true; } void Visitor::closeModule(Module* module) { } bool Visitor::openConstantDeclaration(ConstantDeclaration* constantDeclaration) { return true; } void Visitor::closeConstantDeclaration(ConstantDeclaration* constantDeclaration) { } bool Visitor::openMutableDeclaration(MutableDeclaration* mutableDeclaration) { return true; } void Visitor::closeMutableDeclaration(MutableDeclaration* mutableDeclaration) { } bool Visitor::openBindingInitializer(BindingInitializer* bindingInitializer) { return true; } void Visitor::closeBindingInitializer(BindingInitializer* bindingInitializer) { } bool Visitor::openIdentifierInitializer(IdentifierInitializer* identifierInitializer) { return true; } void Visitor::closeIdentifierInitializer(IdentifierInitializer* identifierInitializer) { } bool Visitor::openInitializer(Initializer* initializer) { return true; } void Visitor::closeInitializer(Initializer* initializer) { } bool Visitor::openAdditionalInitializer(AdditionalInitializer* additionalInitializer) { return true; } void Visitor::closeAdditionalInitializer(AdditionalInitializer* additionalInitializer) { } bool Visitor::openIdentifierPattern(IdentifierPattern* identifierPattern) { return true; } void Visitor::closeIdentifierPattern(IdentifierPattern* identifierPattern) { } bool Visitor::openTypeAnnotation(TypeAnnotation* typeAnnotation) { return true; } void Visitor::closeTypeAnnotation(TypeAnnotation* typeAnnotation) { } bool Visitor::openType(Type* type) { return true; } void Visitor::closeType(Type* type) { } bool Visitor::openIndexedType(IndexedType* indexedType) { return true; } void Visitor::closeIndexedType(IndexedType* indexedType) { } void Visitor::visitPointer(Pointer* pointer) { } void Visitor::visitRoot(Root* root) { } void Visitor::visitLocal(Local* local) { } void Visitor::visitReference(Reference* reference) { } void Visitor::visitThrown(Thrown* thrown) { } bool Visitor::openFunctionDeclaration(FunctionDeclaration* functionDeclaration) { return true; } void Visitor::closeFunctionDeclaration(FunctionDeclaration* functionDeclaration) { } void Visitor::visitStaticWord(StaticWord* staticWord) { } bool Visitor::openFunctionSignature(FunctionSignature* functionSignature) { return true; } void Visitor::closeFunctionSignature(FunctionSignature* functionSignature) { } bool Visitor::openParameterClause(ParameterClause* parameterClause) { return true; } void Visitor::closeParameterClause(ParameterClause* parameterClause) { } bool Visitor::openConstParameter(ConstParameter* constParameter) { return true; } void Visitor::closeConstParameter(ConstParameter* constParameter) { } bool Visitor::openVarParameter(VarParameter* varParameter) { return true; } void Visitor::closeVarParameter(VarParameter* varParameter) { } bool Visitor::openFunctionResult(FunctionResult* functionResult) { return true; } void Visitor::closeFunctionResult(FunctionResult* functionResult) { } bool Visitor::openThrowsClause(ThrowsClause* throwsClause) { return true; } void Visitor::closeThrowsClause(ThrowsClause* throwsClause) { } bool Visitor::openEnumDeclaration(EnumDeclaration* enumDeclaration) { return true; } void Visitor::closeEnumDeclaration(EnumDeclaration* enumDeclaration) { } bool Visitor::openEnumMember(EnumMember* enumMember) { return true; } void Visitor::closeEnumMember(EnumMember* enumMember) { } void Visitor::visitEnumCase(EnumCase* enumCase) { } bool Visitor::openAdditionalCase(AdditionalCase* additionalCase) { return true; } void Visitor::closeAdditionalCase(AdditionalCase* additionalCase) { } bool Visitor::openClassDeclaration(ClassDeclaration* classDeclaration) { return true; } void Visitor::closeClassDeclaration(ClassDeclaration* classDeclaration) { } bool Visitor::openTypeInheritanceClause(TypeInheritanceClause* typeInheritanceClause) { return true; } void Visitor::closeTypeInheritanceClause(TypeInheritanceClause* typeInheritanceClause) { } bool Visitor::openInheritance(Inheritance* inheritance) { return true; } void Visitor::closeInheritance(Inheritance* inheritance) { } bool Visitor::openClassBody(ClassBody* classBody) { return true; } void Visitor::closeClassBody(ClassBody* classBody) { } bool Visitor::openClassMember(ClassMember* classMember) { return true; } void Visitor::closeClassMember(ClassMember* classMember) { } bool Visitor::openConstructorDeclaration(ConstructorDeclaration* constructorDeclaration) { return true; } void Visitor::closeConstructorDeclaration(ConstructorDeclaration* constructorDeclaration) { } bool Visitor::openCodeBlock(CodeBlock* codeBlock) { return true; } void Visitor::closeCodeBlock(CodeBlock* codeBlock) { } bool Visitor::openSimpleExpression(SimpleExpression* simpleExpression) { return true; } void Visitor::closeSimpleExpression(SimpleExpression* simpleExpression) { } bool Visitor::openPrefixExpression(PrefixExpression* prefixExpression) { return true; } void Visitor::closePrefixExpression(PrefixExpression* prefixExpression) { } bool Visitor::openPostfixExpression(PostfixExpression* postfixExpression) { return true; } void Visitor::closePostfixExpression(PostfixExpression* postfixExpression) { } void Visitor::visitIdentifierExpression(IdentifierExpression* identifierExpression) { } void Visitor::visitLiteralExpression(LiteralExpression* literalExpression) { } bool Visitor::openIfExpression(IfExpression* ifExpression) { return true; } void Visitor::closeIfExpression(IfExpression* ifExpression) { } bool Visitor::openElseClause(ElseClause* elseClause) { return true; } void Visitor::closeElseClause(ElseClause* elseClause) { } bool Visitor::openSwitchExpression(SwitchExpression* switchExpression) { return true; } void Visitor::closeSwitchExpression(SwitchExpression* switchExpression) { } bool Visitor::openCurliedSwitchBody(CurliedSwitchBody* curliedSwitchBody) { return true; } void Visitor::closeCurliedSwitchBody(CurliedSwitchBody* curliedSwitchBody) { } bool Visitor::openNakedSwitchBody(NakedSwitchBody* nakedSwitchBody) { return true; } void Visitor::closeNakedSwitchBody(NakedSwitchBody* nakedSwitchBody) { } bool Visitor::openSwitchCase(SwitchCase* switchCase) { return true; } void Visitor::closeSwitchCase(SwitchCase* switchCase) { } bool Visitor::openItemCaseLabel(ItemCaseLabel* itemCaseLabel) { return true; } void Visitor::closeItemCaseLabel(ItemCaseLabel* itemCaseLabel) { } void Visitor::visitDefaultCaseLabel(DefaultCaseLabel* defaultCaseLabel) { } bool Visitor::openCaseItem(CaseItem* caseItem) { return true; } void Visitor::closeCaseItem(CaseItem* caseItem) { } bool Visitor::openCaseContent(CaseContent* caseContent) { return true; } void Visitor::closeCaseContent(CaseContent* caseContent) { } bool Visitor::openForExpression(ForExpression* forExpression) { return true; } void Visitor::closeForExpression(ForExpression* forExpression) { } bool Visitor::openWhileExpression(WhileExpression* whileExpression) { return true; } void Visitor::closeWhileExpression(WhileExpression* whileExpression) { } bool Visitor::openDoExpression(DoExpression* doExpression) { return true; } void Visitor::closeDoExpression(DoExpression* doExpression) { } bool Visitor::openParenthesizedExpression(ParenthesizedExpression* parenthesizedExpression) { return true; } void Visitor::closeParenthesizedExpression(ParenthesizedExpression* parenthesizedExpression) { } bool Visitor::openExpressionElement(ExpressionElement* expressionElement) { return true; } void Visitor::closeExpressionElement(ExpressionElement* expressionElement) { } bool Visitor::openReturnExpression(ReturnExpression* returnExpression) { return true; } void Visitor::closeReturnExpression(ReturnExpression* returnExpression) { } bool Visitor::openThrowExpression(ThrowExpression* throwExpression) { return true; } void Visitor::closeThrowExpression(ThrowExpression* throwExpression) { } bool Visitor::openBreakExpression(BreakExpression* breakExpression) { return true; } void Visitor::closeBreakExpression(BreakExpression* breakExpression) { } bool Visitor::openConstructorCall(ConstructorCall* constructorCall) { return true; } void Visitor::closeConstructorCall(ConstructorCall* constructorCall) { } void Visitor::visitThisExpression(ThisExpression* thisExpression) { } void Visitor::visitNullExpression(NullExpression* nullExpression) { } void Visitor::visitOperatorPostfix(OperatorPostfix* operatorPostfix) { } bool Visitor::openFunctionCall(FunctionCall* functionCall) { return true; } void Visitor::closeFunctionCall(FunctionCall* functionCall) { } bool Visitor::openCatchClause(CatchClause* catchClause) { return true; } void Visitor::closeCatchClause(CatchClause* catchClause) { } bool Visitor::openWildCardCatchPattern(WildCardCatchPattern* wildCardCatchPattern) { return true; } void Visitor::closeWildCardCatchPattern(WildCardCatchPattern* wildCardCatchPattern) { } bool Visitor::openIdentifierCatchPattern(IdentifierCatchPattern* identifierCatchPattern) { return true; } void Visitor::closeIdentifierCatchPattern(IdentifierCatchPattern* identifierCatchPattern) { } void Visitor::visitWildcardPattern(WildcardPattern* wildcardPattern) { } bool Visitor::openTuplePattern(TuplePattern* tuplePattern) { return true; } void Visitor::closeTuplePattern(TuplePattern* tuplePattern) { } bool Visitor::openTuplePatternElement(TuplePatternElement* tuplePatternElement) { return true; } void Visitor::closeTuplePatternElement(TuplePatternElement* tuplePatternElement) { } bool Visitor::openExpressionPattern(ExpressionPattern* expressionPattern) { return true; } void Visitor::closeExpressionPattern(ExpressionPattern* expressionPattern) { } void Visitor::visitMemberExpression(MemberExpression* memberExpression) { } bool Visitor::openSubscript(Subscript* subscript) { return true; } void Visitor::closeSubscript(Subscript* subscript) { } bool Visitor::openBinaryOperation(BinaryOperation* binaryOperation) { return true; } void Visitor::closeBinaryOperation(BinaryOperation* binaryOperation) { } bool Visitor::openAssignment(Assignment* assignment) { return true; } void Visitor::closeAssignment(Assignment* assignment) { } bool Visitor::openTypeQuery(TypeQuery* typeQuery) { return true; } void Visitor::closeTypeQuery(TypeQuery* typeQuery) { } bool Visitor::openTypeCast(TypeCast* typeCast) { return true; } void Visitor::closeTypeCast(TypeCast* typeCast) { } bool Visitor::_isCommonVisitor() { return (false); } bool Visitor::_isCppVisitor() { return (false); } bool Visitor::_isHeaderVisitor() { return (false); } bool Visitor::_isSourceVisitor() { return (false); } bool Visitor::_isModelVisitor() { return (false); } bool SyntaxNode::_isProgram() { return (false); } bool SyntaxNode::_isModule() { return (false); } bool SyntaxNode::_isStatement() { return (false); } bool SyntaxNode::_isDeclaration() { return (false); } bool SyntaxNode::_isConstantDeclaration() { return (false); } bool SyntaxNode::_isMutableDeclaration() { return (false); } bool SyntaxNode::_isFunctionDeclaration() { return (false); } bool SyntaxNode::_isEnumDeclaration() { return (false); } bool SyntaxNode::_isClassDeclaration() { return (false); } bool SyntaxNode::_isConstructorDeclaration() { return (false); } bool SyntaxNode::_isExpression() { return (false); } bool SyntaxNode::_isCodeBlock() { return (false); } bool SyntaxNode::_isSimpleExpression() { return (false); } bool SyntaxNode::_isBindingInitializer() { return (false); } bool SyntaxNode::_isIdentifierInitializer() { return (false); } bool SyntaxNode::_isInitializer() { return (false); } bool SyntaxNode::_isAdditionalInitializer() { return (false); } bool SyntaxNode::_isPattern() { return (false); } bool SyntaxNode::_isIdentifierPattern() { return (false); } bool SyntaxNode::_isWildcardPattern() { return (false); } bool SyntaxNode::_isTuplePattern() { return (false); } bool SyntaxNode::_isExpressionPattern() { return (false); } bool SyntaxNode::_isTypeAnnotation() { return (false); } bool SyntaxNode::_isType() { return (false); } bool SyntaxNode::_isTypePostfix() { return (false); } bool SyntaxNode::_isIndexedType() { return (false); } bool SyntaxNode::_isPointer() { return (false); } bool SyntaxNode::_isLifeTime() { return (false); } bool SyntaxNode::_isRoot() { return (false); } bool SyntaxNode::_isLocal() { return (false); } bool SyntaxNode::_isReference() { return (false); } bool SyntaxNode::_isThrown() { return (false); } bool SyntaxNode::_isModifier() { return (false); } bool SyntaxNode::_isStaticWord() { return (false); } bool SyntaxNode::_isFunctionSignature() { return (false); } bool SyntaxNode::_isParameterClause() { return (false); } bool SyntaxNode::_isParameter() { return (false); } bool SyntaxNode::_isConstParameter() { return (false); } bool SyntaxNode::_isVarParameter() { return (false); } bool SyntaxNode::_isFunctionResult() { return (false); } bool SyntaxNode::_isThrowsClause() { return (false); } bool SyntaxNode::_isEnumMember() { return (false); } bool SyntaxNode::_isEnumCase() { return (false); } bool SyntaxNode::_isAdditionalCase() { return (false); } bool SyntaxNode::_isTypeInheritanceClause() { return (false); } bool SyntaxNode::_isInheritance() { return (false); } bool SyntaxNode::_isClassBody() { return (false); } bool SyntaxNode::_isClassMember() { return (false); } bool SyntaxNode::_isPrefixExpression() { return (false); } bool SyntaxNode::_isPostfixExpression() { return (false); } bool SyntaxNode::_isPrimaryExpression() { return (false); } bool SyntaxNode::_isIdentifierExpression() { return (false); } bool SyntaxNode::_isLiteralExpression() { return (false); } bool SyntaxNode::_isIfExpression() { return (false); } bool SyntaxNode::_isSwitchExpression() { return (false); } bool SyntaxNode::_isForExpression() { return (false); } bool SyntaxNode::_isWhileExpression() { return (false); } bool SyntaxNode::_isDoExpression() { return (false); } bool SyntaxNode::_isParenthesizedExpression() { return (false); } bool SyntaxNode::_isReturnExpression() { return (false); } bool SyntaxNode::_isThrowExpression() { return (false); } bool SyntaxNode::_isBreakExpression() { return (false); } bool SyntaxNode::_isConstructorCall() { return (false); } bool SyntaxNode::_isThisExpression() { return (false); } bool SyntaxNode::_isNullExpression() { return (false); } bool SyntaxNode::_isElseClause() { return (false); } bool SyntaxNode::_isSwitchBody() { return (false); } bool SyntaxNode::_isCurliedSwitchBody() { return (false); } bool SyntaxNode::_isNakedSwitchBody() { return (false); } bool SyntaxNode::_isSwitchCase() { return (false); } bool SyntaxNode::_isCaseLabel() { return (false); } bool SyntaxNode::_isItemCaseLabel() { return (false); } bool SyntaxNode::_isDefaultCaseLabel() { return (false); } bool SyntaxNode::_isCaseItem() { return (false); } bool SyntaxNode::_isCaseContent() { return (false); } bool SyntaxNode::_isExpressionElement() { return (false); } bool SyntaxNode::_isPostfix() { return (false); } bool SyntaxNode::_isOperatorPostfix() { return (false); } bool SyntaxNode::_isFunctionCall() { return (false); } bool SyntaxNode::_isMemberExpression() { return (false); } bool SyntaxNode::_isSubscript() { return (false); } bool SyntaxNode::_isCatchClause() { return (false); } bool SyntaxNode::_isCatchPattern() { return (false); } bool SyntaxNode::_isWildCardCatchPattern() { return (false); } bool SyntaxNode::_isIdentifierCatchPattern() { return (false); } bool SyntaxNode::_isTuplePatternElement() { return (false); } bool SyntaxNode::_isBinaryExpression() { return (false); } bool SyntaxNode::_isBinaryOperation() { return (false); } bool SyntaxNode::_isAssignment() { return (false); } bool SyntaxNode::_isTypeQuery() { return (false); } bool SyntaxNode::_isTypeCast() { return (false); } Program::Program(string* name, _Array<Module>* modules) { start = new(_getPage()) Position(0, 0); end = new(_getPage()) Position(0, 0); this->name = name; this->modules = modules; this->parent = nullptr; } void Program::accept(Visitor* visitor) { if (!visitor->openProgram(this)) return; if (modules != nullptr) { Module* node = nullptr; size_t _modules_length = modules->length(); for (size_t _i = 0; _i < _modules_length; _i++) { node = *(*modules)[_i]; node->accept(visitor); } } visitor->closeProgram(this); } bool Program::_isProgram() { return (true); } Module::Module(_Array<Statement>* statements, Position* start, Position* end) { this->start = start; this->end = end; this->statements = statements; } void Module::accept(Visitor* visitor) { if (!visitor->openModule(this)) return; if (statements != nullptr) { Statement* node = nullptr; size_t _statements_length = statements->length(); for (size_t _i = 0; _i < _statements_length; _i++) { node = *(*statements)[_i]; node->accept(visitor); } } visitor->closeModule(this); } bool Module::_isModule() { return (true); } void Statement::accept(Visitor* visitor) { } bool Statement::_isStatement() { return (true); } bool Statement::_isDeclaration() { return (false); } bool Statement::_isConstantDeclaration() { return (false); } bool Statement::_isMutableDeclaration() { return (false); } bool Statement::_isFunctionDeclaration() { return (false); } bool Statement::_isEnumDeclaration() { return (false); } bool Statement::_isClassDeclaration() { return (false); } bool Statement::_isConstructorDeclaration() { return (false); } bool Statement::_isExpression() { return (false); } bool Statement::_isCodeBlock() { return (false); } bool Statement::_isSimpleExpression() { return (false); } void Declaration::accept(Visitor* visitor) { } bool Declaration::_isDeclaration() { return (true); } bool Declaration::_isConstantDeclaration() { return (false); } bool Declaration::_isMutableDeclaration() { return (false); } bool Declaration::_isFunctionDeclaration() { return (false); } bool Declaration::_isEnumDeclaration() { return (false); } bool Declaration::_isClassDeclaration() { return (false); } bool Declaration::_isConstructorDeclaration() { return (false); } ConstantDeclaration::ConstantDeclaration(BindingInitializer* initializer, Position* start, Position* end) { this->start = start; this->end = end; this->initializer = initializer; } void ConstantDeclaration::accept(Visitor* visitor) { if (!visitor->openConstantDeclaration(this)) return; initializer->accept(visitor); visitor->closeConstantDeclaration(this); } bool ConstantDeclaration::_isConstantDeclaration() { return (true); } MutableDeclaration::MutableDeclaration(BindingInitializer* initializer, Position* start, Position* end) { this->start = start; this->end = end; this->initializer = initializer; } void MutableDeclaration::accept(Visitor* visitor) { if (!visitor->openMutableDeclaration(this)) return; initializer->accept(visitor); visitor->closeMutableDeclaration(this); } bool MutableDeclaration::_isMutableDeclaration() { return (true); } BindingInitializer::BindingInitializer(IdentifierInitializer* initializer, _Array<AdditionalInitializer>* additionalInitializers, Position* start, Position* end) { this->start = start; this->end = end; this->initializer = initializer; this->additionalInitializers = additionalInitializers; } void BindingInitializer::accept(Visitor* visitor) { if (!visitor->openBindingInitializer(this)) return; initializer->accept(visitor); if (additionalInitializers != nullptr) { AdditionalInitializer* node = nullptr; size_t _additionalInitializers_length = additionalInitializers->length(); for (size_t _i = 0; _i < _additionalInitializers_length; _i++) { node = *(*additionalInitializers)[_i]; node->accept(visitor); } } visitor->closeBindingInitializer(this); } bool BindingInitializer::_isBindingInitializer() { return (true); } IdentifierInitializer::IdentifierInitializer(IdentifierPattern* pattern, Initializer* initializer, Position* start, Position* end) { this->start = start; this->end = end; this->pattern = pattern; this->initializer = initializer; } void IdentifierInitializer::accept(Visitor* visitor) { if (!visitor->openIdentifierInitializer(this)) return; pattern->accept(visitor); if (initializer != nullptr) initializer->accept(visitor); visitor->closeIdentifierInitializer(this); } bool IdentifierInitializer::_isIdentifierInitializer() { return (true); } Initializer::Initializer(Expression* expression, Position* start, Position* end) { this->start = start; this->end = end; this->expression = expression; } void Initializer::accept(Visitor* visitor) { if (!visitor->openInitializer(this)) return; expression->accept(visitor); visitor->closeInitializer(this); } bool Initializer::_isInitializer() { return (true); } AdditionalInitializer::AdditionalInitializer(IdentifierInitializer* pattern, Position* start, Position* end) { this->start = start; this->end = end; this->pattern = pattern; } void AdditionalInitializer::accept(Visitor* visitor) { if (!visitor->openAdditionalInitializer(this)) return; pattern->accept(visitor); visitor->closeAdditionalInitializer(this); } bool AdditionalInitializer::_isAdditionalInitializer() { return (true); } void Pattern::accept(Visitor* visitor) { } bool Pattern::_isPattern() { return (true); } bool Pattern::_isIdentifierPattern() { return (false); } bool Pattern::_isWildcardPattern() { return (false); } bool Pattern::_isTuplePattern() { return (false); } bool Pattern::_isExpressionPattern() { return (false); } IdentifierPattern::IdentifierPattern(string* identifier, TypeAnnotation* annotationForType, Position* start, Position* end) { this->start = start; this->end = end; this->identifier = identifier; this->annotationForType = annotationForType; } void IdentifierPattern::accept(Visitor* visitor) { if (!visitor->openIdentifierPattern(this)) return; if (annotationForType != nullptr) annotationForType->accept(visitor); visitor->closeIdentifierPattern(this); } bool IdentifierPattern::_isIdentifierPattern() { return (true); } TypeAnnotation::TypeAnnotation(Type* annotationForType, Position* start, Position* end) { this->start = start; this->end = end; this->annotationForType = annotationForType; } void TypeAnnotation::accept(Visitor* visitor) { if (!visitor->openTypeAnnotation(this)) return; annotationForType->accept(visitor); visitor->closeTypeAnnotation(this); } bool TypeAnnotation::_isTypeAnnotation() { return (true); } Type::Type(string* name, _Array<TypePostfix>* postfixes, LifeTime* lifeTime, Position* start, Position* end) { this->start = start; this->end = end; this->name = name; this->postfixes = postfixes; this->lifeTime = lifeTime; } void Type::accept(Visitor* visitor) { if (!visitor->openType(this)) return; if (postfixes != nullptr) { TypePostfix* node = nullptr; size_t _postfixes_length = postfixes->length(); for (size_t _i = 0; _i < _postfixes_length; _i++) { node = *(*postfixes)[_i]; node->accept(visitor); } } if (lifeTime != nullptr) lifeTime->accept(visitor); visitor->closeType(this); } bool Type::_isType() { return (true); } void TypePostfix::accept(Visitor* visitor) { } bool TypePostfix::_isTypePostfix() { return (true); } bool TypePostfix::_isIndexedType() { return (false); } bool TypePostfix::_isPointer() { return (false); } IndexedType::IndexedType(Type* key, Position* start, Position* end) { this->start = start; this->end = end; this->key = key; } void IndexedType::accept(Visitor* visitor) { if (!visitor->openIndexedType(this)) return; if (key != nullptr) key->accept(visitor); visitor->closeIndexedType(this); } bool IndexedType::_isIndexedType() { return (true); } Pointer::Pointer(Position* start, Position* end) { this->start = start; this->end = end; } void Pointer::accept(Visitor* visitor) { visitor->visitPointer(this); } bool Pointer::_isPointer() { return (true); } void LifeTime::accept(Visitor* visitor) { } bool LifeTime::_isLifeTime() { return (true); } bool LifeTime::_isRoot() { return (false); } bool LifeTime::_isLocal() { return (false); } bool LifeTime::_isReference() { return (false); } bool LifeTime::_isThrown() { return (false); } Root::Root(Position* start, Position* end) { this->start = start; this->end = end; } void Root::accept(Visitor* visitor) { visitor->visitRoot(this); } bool Root::_isRoot() { return (true); } Local::Local(string* location, Position* start, Position* end) { this->start = start; this->end = end; this->location = location; } void Local::accept(Visitor* visitor) { visitor->visitLocal(this); } bool Local::_isLocal() { return (true); } Reference::Reference(Literal* age, Position* start, Position* end) { this->start = start; this->end = end; this->age = age; } void Reference::accept(Visitor* visitor) { visitor->visitReference(this); } bool Reference::_isReference() { return (true); } Thrown::Thrown(Position* start, Position* end) { this->start = start; this->end = end; } void Thrown::accept(Visitor* visitor) { visitor->visitThrown(this); } bool Thrown::_isThrown() { return (true); } FunctionDeclaration::FunctionDeclaration(_Array<Modifier>* modifiers, string* name, FunctionSignature* signature, Expression* body, Position* start, Position* end) { this->start = start; this->end = end; this->modifiers = modifiers; this->name = name; this->signature = signature; this->body = body; } void FunctionDeclaration::accept(Visitor* visitor) { if (!visitor->openFunctionDeclaration(this)) return; if (modifiers != nullptr) { Modifier* node = nullptr; size_t _modifiers_length = modifiers->length(); for (size_t _i = 0; _i < _modifiers_length; _i++) { node = *(*modifiers)[_i]; node->accept(visitor); } } signature->accept(visitor); if (body != nullptr) body->accept(visitor); visitor->closeFunctionDeclaration(this); } bool FunctionDeclaration::_isFunctionDeclaration() { return (true); } void Modifier::accept(Visitor* visitor) { } bool Modifier::_isModifier() { return (true); } bool Modifier::_isStaticWord() { return (false); } StaticWord::StaticWord(Position* start, Position* end) { this->start = start; this->end = end; } void StaticWord::accept(Visitor* visitor) { visitor->visitStaticWord(this); } bool StaticWord::_isStaticWord() { return (true); } FunctionSignature::FunctionSignature(ParameterClause* parameterClause, FunctionResult* result, ThrowsClause* throwsClause, Position* start, Position* end) { this->start = start; this->end = end; this->parameterClause = parameterClause; this->result = result; this->throwsClause = throwsClause; } void FunctionSignature::accept(Visitor* visitor) { if (!visitor->openFunctionSignature(this)) return; parameterClause->accept(visitor); if (result != nullptr) result->accept(visitor); if (throwsClause != nullptr) throwsClause->accept(visitor); visitor->closeFunctionSignature(this); } bool FunctionSignature::_isFunctionSignature() { return (true); } ParameterClause::ParameterClause(_Array<Parameter>* parameters, Position* start, Position* end) { this->start = start; this->end = end; this->parameters = parameters; } void ParameterClause::accept(Visitor* visitor) { if (!visitor->openParameterClause(this)) return; if (parameters != nullptr) { Parameter* node = nullptr; size_t _parameters_length = parameters->length(); for (size_t _i = 0; _i < _parameters_length; _i++) { node = *(*parameters)[_i]; node->accept(visitor); } } visitor->closeParameterClause(this); } bool ParameterClause::_isParameterClause() { return (true); } void Parameter::accept(Visitor* visitor) { } bool Parameter::_isParameter() { return (true); } bool Parameter::_isConstParameter() { return (false); } bool Parameter::_isVarParameter() { return (false); } ConstParameter::ConstParameter(string* name, Type* parameterType, Position* start, Position* end) { this->start = start; this->end = end; this->name = name; this->parameterType = parameterType; } void ConstParameter::accept(Visitor* visitor) { if (!visitor->openConstParameter(this)) return; parameterType->accept(visitor); visitor->closeConstParameter(this); } bool ConstParameter::_isConstParameter() { return (true); } VarParameter::VarParameter(string* name, Type* parameterType, Position* start, Position* end) { this->start = start; this->end = end; this->name = name; this->parameterType = parameterType; } void VarParameter::accept(Visitor* visitor) { if (!visitor->openVarParameter(this)) return; parameterType->accept(visitor); visitor->closeVarParameter(this); } bool VarParameter::_isVarParameter() { return (true); } FunctionResult::FunctionResult(Type* resultType, Position* start, Position* end) { this->start = start; this->end = end; this->resultType = resultType; } void FunctionResult::accept(Visitor* visitor) { if (!visitor->openFunctionResult(this)) return; resultType->accept(visitor); visitor->closeFunctionResult(this); } bool FunctionResult::_isFunctionResult() { return (true); } ThrowsClause::ThrowsClause(Type* throwsType, Position* start, Position* end) { this->start = start; this->end = end; this->throwsType = throwsType; } void ThrowsClause::accept(Visitor* visitor) { if (!visitor->openThrowsClause(this)) return; throwsType->accept(visitor); visitor->closeThrowsClause(this); } bool ThrowsClause::_isThrowsClause() { return (true); } EnumDeclaration::EnumDeclaration(string* name, _Array<EnumMember>* members, Position* start, Position* end) { this->start = start; this->end = end; this->name = name; this->members = members; } void EnumDeclaration::accept(Visitor* visitor) { if (!visitor->openEnumDeclaration(this)) return; if (members != nullptr) { EnumMember* node = nullptr; size_t _members_length = members->length(); for (size_t _i = 0; _i < _members_length; _i++) { node = *(*members)[_i]; node->accept(visitor); } } visitor->closeEnumDeclaration(this); } bool EnumDeclaration::_isEnumDeclaration() { return (true); } EnumMember::EnumMember(EnumCase* enumCase, _Array<AdditionalCase>* additionalCases, ParameterClause* parameterClause, Position* start, Position* end) { this->start = start; this->end = end; this->enumCase = enumCase; this->additionalCases = additionalCases; this->parameterClause = parameterClause; } void EnumMember::accept(Visitor* visitor) { if (!visitor->openEnumMember(this)) return; enumCase->accept(visitor); if (additionalCases != nullptr) { AdditionalCase* node = nullptr; size_t _additionalCases_length = additionalCases->length(); for (size_t _i = 0; _i < _additionalCases_length; _i++) { node = *(*additionalCases)[_i]; node->accept(visitor); } } if (parameterClause != nullptr) parameterClause->accept(visitor); visitor->closeEnumMember(this); } bool EnumMember::_isEnumMember() { return (true); } EnumCase::EnumCase(string* name, Position* start, Position* end) { this->start = start; this->end = end; this->name = name; } void EnumCase::accept(Visitor* visitor) { visitor->visitEnumCase(this); } bool EnumCase::_isEnumCase() { return (true); } AdditionalCase::AdditionalCase(EnumCase* enumCase, Position* start, Position* end) { this->start = start; this->end = end; this->enumCase = enumCase; } void AdditionalCase::accept(Visitor* visitor) { if (!visitor->openAdditionalCase(this)) return; enumCase->accept(visitor); visitor->closeAdditionalCase(this); } bool AdditionalCase::_isAdditionalCase() { return (true); } ClassDeclaration::ClassDeclaration(string* name, TypeInheritanceClause* typeInheritanceClause, ClassBody* body, Position* start, Position* end) { this->start = start; this->end = end; this->name = name; this->typeInheritanceClause = typeInheritanceClause; this->body = body; } void ClassDeclaration::accept(Visitor* visitor) { if (!visitor->openClassDeclaration(this)) return; if (typeInheritanceClause != nullptr) typeInheritanceClause->accept(visitor); if (body != nullptr) body->accept(visitor); visitor->closeClassDeclaration(this); } bool ClassDeclaration::_isClassDeclaration() { return (true); } TypeInheritanceClause::TypeInheritanceClause(_Array<Inheritance>* inheritances, Position* start, Position* end) { this->start = start; this->end = end; this->inheritances = inheritances; } void TypeInheritanceClause::accept(Visitor* visitor) { if (!visitor->openTypeInheritanceClause(this)) return; if (inheritances != nullptr) { Inheritance* node = nullptr; size_t _inheritances_length = inheritances->length(); for (size_t _i = 0; _i < _inheritances_length; _i++) { node = *(*inheritances)[_i]; node->accept(visitor); } } visitor->closeTypeInheritanceClause(this); } bool TypeInheritanceClause::_isTypeInheritanceClause() { return (true); } Inheritance::Inheritance(Type* type, Position* start, Position* end) { this->start = start; this->end = end; this->type = type; } void Inheritance::accept(Visitor* visitor) { if (!visitor->openInheritance(this)) return; type->accept(visitor); visitor->closeInheritance(this); } bool Inheritance::_isInheritance() { return (true); } ClassBody::ClassBody(_Array<ClassMember>* members, Position* start, Position* end) { this->start = start; this->end = end; this->members = members; } void ClassBody::accept(Visitor* visitor) { if (!visitor->openClassBody(this)) return; if (members != nullptr) { ClassMember* node = nullptr; size_t _members_length = members->length(); for (size_t _i = 0; _i < _members_length; _i++) { node = *(*members)[_i]; node->accept(visitor); } } visitor->closeClassBody(this); } bool ClassBody::_isClassBody() { return (true); } ClassMember::ClassMember(Declaration* declaration, Position* start, Position* end) { this->start = start; this->end = end; this->declaration = declaration; } void ClassMember::accept(Visitor* visitor) { if (!visitor->openClassMember(this)) return; declaration->accept(visitor); visitor->closeClassMember(this); } bool ClassMember::_isClassMember() { return (true); } ConstructorDeclaration::ConstructorDeclaration(ParameterClause* parameterClause, Expression* body, Position* start, Position* end) { this->start = start; this->end = end; this->parameterClause = parameterClause; this->body = body; } void ConstructorDeclaration::accept(Visitor* visitor) { if (!visitor->openConstructorDeclaration(this)) return; parameterClause->accept(visitor); body->accept(visitor); visitor->closeConstructorDeclaration(this); } bool ConstructorDeclaration::_isConstructorDeclaration() { return (true); } void Expression::accept(Visitor* visitor) { } bool Expression::_isExpression() { return (true); } bool Expression::_isCodeBlock() { return (false); } bool Expression::_isSimpleExpression() { return (false); } CodeBlock::CodeBlock(_Array<Statement>* statements, Position* start, Position* end) { this->start = start; this->end = end; this->statements = statements; } void CodeBlock::accept(Visitor* visitor) { if (!visitor->openCodeBlock(this)) return; if (statements != nullptr) { Statement* node = nullptr; size_t _statements_length = statements->length(); for (size_t _i = 0; _i < _statements_length; _i++) { node = *(*statements)[_i]; node->accept(visitor); } } visitor->closeCodeBlock(this); } bool CodeBlock::_isCodeBlock() { return (true); } SimpleExpression::SimpleExpression(PrefixExpression* prefixExpression, _Array<BinaryExpression>* binaryExpressions, Position* start, Position* end) { this->start = start; this->end = end; this->prefixExpression = prefixExpression; this->binaryExpressions = binaryExpressions; } void SimpleExpression::accept(Visitor* visitor) { if (!visitor->openSimpleExpression(this)) return; prefixExpression->accept(visitor); if (binaryExpressions != nullptr) { BinaryExpression* node = nullptr; size_t _binaryExpressions_length = binaryExpressions->length(); for (size_t _i = 0; _i < _binaryExpressions_length; _i++) { node = *(*binaryExpressions)[_i]; node->accept(visitor); } } visitor->closeSimpleExpression(this); } bool SimpleExpression::_isSimpleExpression() { return (true); } PrefixExpression::PrefixExpression(string* prefixOperator, PostfixExpression* expression, Position* start, Position* end) { this->start = start; this->end = end; this->prefixOperator = prefixOperator; this->expression = expression; } void PrefixExpression::accept(Visitor* visitor) { if (!visitor->openPrefixExpression(this)) return; expression->accept(visitor); visitor->closePrefixExpression(this); } bool PrefixExpression::_isPrefixExpression() { return (true); } PostfixExpression::PostfixExpression(PrimaryExpression* primaryExpression, _Array<Postfix>* postfixes, Position* start, Position* end) { this->start = start; this->end = end; this->primaryExpression = primaryExpression; this->postfixes = postfixes; } void PostfixExpression::accept(Visitor* visitor) { if (!visitor->openPostfixExpression(this)) return; primaryExpression->accept(visitor); if (postfixes != nullptr) { Postfix* node = nullptr; size_t _postfixes_length = postfixes->length(); for (size_t _i = 0; _i < _postfixes_length; _i++) { node = *(*postfixes)[_i]; node->accept(visitor); } } visitor->closePostfixExpression(this); } bool PostfixExpression::_isPostfixExpression() { return (true); } void PrimaryExpression::accept(Visitor* visitor) { } bool PrimaryExpression::_isPrimaryExpression() { return (true); } bool PrimaryExpression::_isIdentifierExpression() { return (false); } bool PrimaryExpression::_isLiteralExpression() { return (false); } bool PrimaryExpression::_isIfExpression() { return (false); } bool PrimaryExpression::_isSwitchExpression() { return (false); } bool PrimaryExpression::_isForExpression() { return (false); } bool PrimaryExpression::_isWhileExpression() { return (false); } bool PrimaryExpression::_isDoExpression() { return (false); } bool PrimaryExpression::_isParenthesizedExpression() { return (false); } bool PrimaryExpression::_isReturnExpression() { return (false); } bool PrimaryExpression::_isThrowExpression() { return (false); } bool PrimaryExpression::_isBreakExpression() { return (false); } bool PrimaryExpression::_isConstructorCall() { return (false); } bool PrimaryExpression::_isThisExpression() { return (false); } bool PrimaryExpression::_isNullExpression() { return (false); } IdentifierExpression::IdentifierExpression(string* name, Position* start, Position* end) { this->start = start; this->end = end; this->name = name; } void IdentifierExpression::accept(Visitor* visitor) { visitor->visitIdentifierExpression(this); } bool IdentifierExpression::_isIdentifierExpression() { return (true); } LiteralExpression::LiteralExpression(Literal* literal, Position* start, Position* end) { this->start = start; this->end = end; this->literal = literal; } void LiteralExpression::accept(Visitor* visitor) { visitor->visitLiteralExpression(this); } bool LiteralExpression::_isLiteralExpression() { return (true); } IfExpression::IfExpression(Expression* condition, Expression* consequent, ElseClause* elseClause, Position* start, Position* end) { this->start = start; this->end = end; this->condition = condition; this->consequent = consequent; this->elseClause = elseClause; } void IfExpression::accept(Visitor* visitor) { if (!visitor->openIfExpression(this)) return; condition->accept(visitor); consequent->accept(visitor); if (elseClause != nullptr) elseClause->accept(visitor); visitor->closeIfExpression(this); } bool IfExpression::_isIfExpression() { return (true); } ElseClause::ElseClause(Expression* alternative, Position* start, Position* end) { this->start = start; this->end = end; this->alternative = alternative; } void ElseClause::accept(Visitor* visitor) { if (!visitor->openElseClause(this)) return; alternative->accept(visitor); visitor->closeElseClause(this); } bool ElseClause::_isElseClause() { return (true); } SwitchExpression::SwitchExpression(Expression* expression, SwitchBody* body, Position* start, Position* end) { this->start = start; this->end = end; this->expression = expression; this->body = body; } void SwitchExpression::accept(Visitor* visitor) { if (!visitor->openSwitchExpression(this)) return; expression->accept(visitor); body->accept(visitor); visitor->closeSwitchExpression(this); } bool SwitchExpression::_isSwitchExpression() { return (true); } void SwitchBody::accept(Visitor* visitor) { } bool SwitchBody::_isSwitchBody() { return (true); } bool SwitchBody::_isCurliedSwitchBody() { return (false); } bool SwitchBody::_isNakedSwitchBody() { return (false); } CurliedSwitchBody::CurliedSwitchBody(_Array<SwitchCase>* cases, Position* start, Position* end) { this->start = start; this->end = end; this->cases = cases; } void CurliedSwitchBody::accept(Visitor* visitor) { if (!visitor->openCurliedSwitchBody(this)) return; if (cases != nullptr) { SwitchCase* node = nullptr; size_t _cases_length = cases->length(); for (size_t _i = 0; _i < _cases_length; _i++) { node = *(*cases)[_i]; node->accept(visitor); } } visitor->closeCurliedSwitchBody(this); } bool CurliedSwitchBody::_isCurliedSwitchBody() { return (true); } NakedSwitchBody::NakedSwitchBody(_Array<SwitchCase>* cases, Position* start, Position* end) { this->start = start; this->end = end; this->cases = cases; } void NakedSwitchBody::accept(Visitor* visitor) { if (!visitor->openNakedSwitchBody(this)) return; if (cases != nullptr) { SwitchCase* node = nullptr; size_t _cases_length = cases->length(); for (size_t _i = 0; _i < _cases_length; _i++) { node = *(*cases)[_i]; node->accept(visitor); } } visitor->closeNakedSwitchBody(this); } bool NakedSwitchBody::_isNakedSwitchBody() { return (true); } SwitchCase::SwitchCase(CaseLabel* label, CaseContent* content, Position* start, Position* end) { this->start = start; this->end = end; this->label = label; this->content = content; } void SwitchCase::accept(Visitor* visitor) { if (!visitor->openSwitchCase(this)) return; label->accept(visitor); content->accept(visitor); visitor->closeSwitchCase(this); } bool SwitchCase::_isSwitchCase() { return (true); } void CaseLabel::accept(Visitor* visitor) { } bool CaseLabel::_isCaseLabel() { return (true); } bool CaseLabel::_isItemCaseLabel() { return (false); } bool CaseLabel::_isDefaultCaseLabel() { return (false); } ItemCaseLabel::ItemCaseLabel(Pattern* pattern, _Array<CaseItem>* additionalPatterns, Position* start, Position* end) { this->start = start; this->end = end; this->pattern = pattern; this->additionalPatterns = additionalPatterns; } void ItemCaseLabel::accept(Visitor* visitor) { if (!visitor->openItemCaseLabel(this)) return; pattern->accept(visitor); if (additionalPatterns != nullptr) { CaseItem* node = nullptr; size_t _additionalPatterns_length = additionalPatterns->length(); for (size_t _i = 0; _i < _additionalPatterns_length; _i++) { node = *(*additionalPatterns)[_i]; node->accept(visitor); } } visitor->closeItemCaseLabel(this); } bool ItemCaseLabel::_isItemCaseLabel() { return (true); } DefaultCaseLabel::DefaultCaseLabel(Position* start, Position* end) { this->start = start; this->end = end; } void DefaultCaseLabel::accept(Visitor* visitor) { visitor->visitDefaultCaseLabel(this); } bool DefaultCaseLabel::_isDefaultCaseLabel() { return (true); } CaseItem::CaseItem(Pattern* pattern, Position* start, Position* end) { this->start = start; this->end = end; this->pattern = pattern; } void CaseItem::accept(Visitor* visitor) { if (!visitor->openCaseItem(this)) return; pattern->accept(visitor); visitor->closeCaseItem(this); } bool CaseItem::_isCaseItem() { return (true); } CaseContent::CaseContent(_Array<Statement>* statements, Position* start, Position* end) { this->start = start; this->end = end; this->statements = statements; } void CaseContent::accept(Visitor* visitor) { if (!visitor->openCaseContent(this)) return; if (statements != nullptr) { Statement* node = nullptr; size_t _statements_length = statements->length(); for (size_t _i = 0; _i < _statements_length; _i++) { node = *(*statements)[_i]; node->accept(visitor); } } visitor->closeCaseContent(this); } bool CaseContent::_isCaseContent() { return (true); } ForExpression::ForExpression(IdentifierPattern* pattern, Expression* expression, Expression* code, Position* start, Position* end) { this->start = start; this->end = end; this->pattern = pattern; this->expression = expression; this->code = code; } void ForExpression::accept(Visitor* visitor) { if (!visitor->openForExpression(this)) return; pattern->accept(visitor); expression->accept(visitor); code->accept(visitor); visitor->closeForExpression(this); } bool ForExpression::_isForExpression() { return (true); } WhileExpression::WhileExpression(Expression* condition, Expression* code, Position* start, Position* end) { this->start = start; this->end = end; this->condition = condition; this->code = code; } void WhileExpression::accept(Visitor* visitor) { if (!visitor->openWhileExpression(this)) return; condition->accept(visitor); code->accept(visitor); visitor->closeWhileExpression(this); } bool WhileExpression::_isWhileExpression() { return (true); } DoExpression::DoExpression(Expression* code, Expression* condition, Position* start, Position* end) { this->start = start; this->end = end; this->code = code; this->condition = condition; } void DoExpression::accept(Visitor* visitor) { if (!visitor->openDoExpression(this)) return; code->accept(visitor); condition->accept(visitor); visitor->closeDoExpression(this); } bool DoExpression::_isDoExpression() { return (true); } ParenthesizedExpression::ParenthesizedExpression(_Array<ExpressionElement>* expressionElements, Position* start, Position* end) { this->start = start; this->end = end; this->expressionElements = expressionElements; } void ParenthesizedExpression::accept(Visitor* visitor) { if (!visitor->openParenthesizedExpression(this)) return; if (expressionElements != nullptr) { ExpressionElement* node = nullptr; size_t _expressionElements_length = expressionElements->length(); for (size_t _i = 0; _i < _expressionElements_length; _i++) { node = *(*expressionElements)[_i]; node->accept(visitor); } } visitor->closeParenthesizedExpression(this); } bool ParenthesizedExpression::_isParenthesizedExpression() { return (true); } ExpressionElement::ExpressionElement(Expression* expression, Position* start, Position* end) { this->start = start; this->end = end; this->expression = expression; } void ExpressionElement::accept(Visitor* visitor) { if (!visitor->openExpressionElement(this)) return; expression->accept(visitor); visitor->closeExpressionElement(this); } bool ExpressionElement::_isExpressionElement() { return (true); } ReturnExpression::ReturnExpression(ParenthesizedExpression* expression, Position* start, Position* end) { this->start = start; this->end = end; this->expression = expression; } void ReturnExpression::accept(Visitor* visitor) { if (!visitor->openReturnExpression(this)) return; if (expression != nullptr) expression->accept(visitor); visitor->closeReturnExpression(this); } bool ReturnExpression::_isReturnExpression() { return (true); } ThrowExpression::ThrowExpression(IdentifierExpression* error, ParenthesizedExpression* arguments, Position* start, Position* end) { this->start = start; this->end = end; this->error = error; this->arguments = arguments; } void ThrowExpression::accept(Visitor* visitor) { if (!visitor->openThrowExpression(this)) return; error->accept(visitor); if (arguments != nullptr) arguments->accept(visitor); visitor->closeThrowExpression(this); } bool ThrowExpression::_isThrowExpression() { return (true); } BreakExpression::BreakExpression(ParenthesizedExpression* expression, Position* start, Position* end) { this->start = start; this->end = end; this->expression = expression; } void BreakExpression::accept(Visitor* visitor) { if (!visitor->openBreakExpression(this)) return; if (expression != nullptr) expression->accept(visitor); visitor->closeBreakExpression(this); } bool BreakExpression::_isBreakExpression() { return (true); } ConstructorCall::ConstructorCall(Type* typeToConstruct, ParenthesizedExpression* arguments, _Array<CatchClause>* catchClauses, Position* start, Position* end) { this->start = start; this->end = end; this->typeToConstruct = typeToConstruct; this->arguments = arguments; this->catchClauses = catchClauses; } void ConstructorCall::accept(Visitor* visitor) { if (!visitor->openConstructorCall(this)) return; typeToConstruct->accept(visitor); arguments->accept(visitor); if (catchClauses != nullptr) { CatchClause* node = nullptr; size_t _catchClauses_length = catchClauses->length(); for (size_t _i = 0; _i < _catchClauses_length; _i++) { node = *(*catchClauses)[_i]; node->accept(visitor); } } visitor->closeConstructorCall(this); } bool ConstructorCall::_isConstructorCall() { return (true); } ThisExpression::ThisExpression(Position* start, Position* end) { this->start = start; this->end = end; } void ThisExpression::accept(Visitor* visitor) { visitor->visitThisExpression(this); } bool ThisExpression::_isThisExpression() { return (true); } NullExpression::NullExpression(Position* start, Position* end) { this->start = start; this->end = end; } void NullExpression::accept(Visitor* visitor) { visitor->visitNullExpression(this); } bool NullExpression::_isNullExpression() { return (true); } void Postfix::accept(Visitor* visitor) { } bool Postfix::_isPostfix() { return (true); } bool Postfix::_isOperatorPostfix() { return (false); } bool Postfix::_isFunctionCall() { return (false); } bool Postfix::_isMemberExpression() { return (false); } bool Postfix::_isSubscript() { return (false); } OperatorPostfix::OperatorPostfix(string* postfixOperator, Position* start, Position* end) { this->start = start; this->end = end; this->postfixOperator = postfixOperator; } void OperatorPostfix::accept(Visitor* visitor) { visitor->visitOperatorPostfix(this); } bool OperatorPostfix::_isOperatorPostfix() { return (true); } FunctionCall::FunctionCall(ParenthesizedExpression* arguments, _Array<CatchClause>* catchClauses, Position* start, Position* end) { this->start = start; this->end = end; this->arguments = arguments; this->catchClauses = catchClauses; } void FunctionCall::accept(Visitor* visitor) { if (!visitor->openFunctionCall(this)) return; arguments->accept(visitor); if (catchClauses != nullptr) { CatchClause* node = nullptr; size_t _catchClauses_length = catchClauses->length(); for (size_t _i = 0; _i < _catchClauses_length; _i++) { node = *(*catchClauses)[_i]; node->accept(visitor); } } visitor->closeFunctionCall(this); } bool FunctionCall::_isFunctionCall() { return (true); } CatchClause::CatchClause(CatchPattern* catchPattern, TuplePattern* bindingPattern, Expression* expression, Position* start, Position* end) { this->start = start; this->end = end; this->catchPattern = catchPattern; this->bindingPattern = bindingPattern; this->expression = expression; } void CatchClause::accept(Visitor* visitor) { if (!visitor->openCatchClause(this)) return; catchPattern->accept(visitor); if (bindingPattern != nullptr) bindingPattern->accept(visitor); expression->accept(visitor); visitor->closeCatchClause(this); } bool CatchClause::_isCatchClause() { return (true); } void CatchPattern::accept(Visitor* visitor) { } bool CatchPattern::_isCatchPattern() { return (true); } bool CatchPattern::_isWildCardCatchPattern() { return (false); } bool CatchPattern::_isIdentifierCatchPattern() { return (false); } WildCardCatchPattern::WildCardCatchPattern(WildcardPattern* pattern, Position* start, Position* end) { this->start = start; this->end = end; this->pattern = pattern; } void WildCardCatchPattern::accept(Visitor* visitor) { if (!visitor->openWildCardCatchPattern(this)) return; pattern->accept(visitor); visitor->closeWildCardCatchPattern(this); } bool WildCardCatchPattern::_isWildCardCatchPattern() { return (true); } IdentifierCatchPattern::IdentifierCatchPattern(string* name, MemberExpression* member, Position* start, Position* end) { this->start = start; this->end = end; this->name = name; this->member = member; } void IdentifierCatchPattern::accept(Visitor* visitor) { if (!visitor->openIdentifierCatchPattern(this)) return; if (member != nullptr) member->accept(visitor); visitor->closeIdentifierCatchPattern(this); } bool IdentifierCatchPattern::_isIdentifierCatchPattern() { return (true); } WildcardPattern::WildcardPattern(Position* start, Position* end) { this->start = start; this->end = end; } void WildcardPattern::accept(Visitor* visitor) { visitor->visitWildcardPattern(this); } bool WildcardPattern::_isWildcardPattern() { return (true); } TuplePattern::TuplePattern(_Array<TuplePatternElement>* elements, Position* start, Position* end) { this->start = start; this->end = end; this->elements = elements; } void TuplePattern::accept(Visitor* visitor) { if (!visitor->openTuplePattern(this)) return; if (elements != nullptr) { TuplePatternElement* node = nullptr; size_t _elements_length = elements->length(); for (size_t _i = 0; _i < _elements_length; _i++) { node = *(*elements)[_i]; node->accept(visitor); } } visitor->closeTuplePattern(this); } bool TuplePattern::_isTuplePattern() { return (true); } TuplePatternElement::TuplePatternElement(Pattern* pattern, Position* start, Position* end) { this->start = start; this->end = end; this->pattern = pattern; } void TuplePatternElement::accept(Visitor* visitor) { if (!visitor->openTuplePatternElement(this)) return; pattern->accept(visitor); visitor->closeTuplePatternElement(this); } bool TuplePatternElement::_isTuplePatternElement() { return (true); } ExpressionPattern::ExpressionPattern(Expression* expression, Position* start, Position* end) { this->start = start; this->end = end; this->expression = expression; } void ExpressionPattern::accept(Visitor* visitor) { if (!visitor->openExpressionPattern(this)) return; expression->accept(visitor); visitor->closeExpressionPattern(this); } bool ExpressionPattern::_isExpressionPattern() { return (true); } MemberExpression::MemberExpression(string* member, Position* start, Position* end) { this->start = start; this->end = end; this->member = member; } void MemberExpression::accept(Visitor* visitor) { visitor->visitMemberExpression(this); } bool MemberExpression::_isMemberExpression() { return (true); } Subscript::Subscript(_Array<ExpressionElement>* expressions, Position* start, Position* end) { this->start = start; this->end = end; this->expressions = expressions; } void Subscript::accept(Visitor* visitor) { if (!visitor->openSubscript(this)) return; if (expressions != nullptr) { ExpressionElement* node = nullptr; size_t _expressions_length = expressions->length(); for (size_t _i = 0; _i < _expressions_length; _i++) { node = *(*expressions)[_i]; node->accept(visitor); } } visitor->closeSubscript(this); } bool Subscript::_isSubscript() { return (true); } void BinaryExpression::accept(Visitor* visitor) { } bool BinaryExpression::_isBinaryExpression() { return (true); } bool BinaryExpression::_isBinaryOperation() { return (false); } bool BinaryExpression::_isAssignment() { return (false); } bool BinaryExpression::_isTypeQuery() { return (false); } bool BinaryExpression::_isTypeCast() { return (false); } BinaryOperation::BinaryOperation(string* binaryOperator, PrefixExpression* expression, Position* start, Position* end) { this->start = start; this->end = end; this->binaryOperator = binaryOperator; this->expression = expression; } void BinaryOperation::accept(Visitor* visitor) { if (!visitor->openBinaryOperation(this)) return; expression->accept(visitor); visitor->closeBinaryOperation(this); } bool BinaryOperation::_isBinaryOperation() { return (true); } Assignment::Assignment(Expression* expression, Position* start, Position* end) { this->start = start; this->end = end; this->expression = expression; } void Assignment::accept(Visitor* visitor) { if (!visitor->openAssignment(this)) return; expression->accept(visitor); visitor->closeAssignment(this); } bool Assignment::_isAssignment() { return (true); } TypeQuery::TypeQuery(Type* objectType, Position* start, Position* end) { this->start = start; this->end = end; this->objectType = objectType; } void TypeQuery::accept(Visitor* visitor) { if (!visitor->openTypeQuery(this)) return; objectType->accept(visitor); visitor->closeTypeQuery(this); } bool TypeQuery::_isTypeQuery() { return (true); } TypeCast::TypeCast(Type* objectType, Position* start, Position* end) { this->start = start; this->end = end; this->objectType = objectType; } void TypeCast::accept(Visitor* visitor) { if (!visitor->openTypeCast(this)) return; objectType->accept(visitor); visitor->closeTypeCast(this); } bool TypeCast::_isTypeCast() { return (true); } }
32.003074
165
0.671171
rschleitzer
bcf693b12b384c6c0d63a3b581b0840c2c6f7db5
854
cpp
C++
problems/189.Rotate_Array/AC_pointer_n_1space.cpp
subramp-prep/leetcode
d125201d9021ab9b1eea5e5393c2db4edd84e740
[ "Unlicense" ]
null
null
null
problems/189.Rotate_Array/AC_pointer_n_1space.cpp
subramp-prep/leetcode
d125201d9021ab9b1eea5e5393c2db4edd84e740
[ "Unlicense" ]
null
null
null
problems/189.Rotate_Array/AC_pointer_n_1space.cpp
subramp-prep/leetcode
d125201d9021ab9b1eea5e5393c2db4edd84e740
[ "Unlicense" ]
null
null
null
/* * Author: illuz <iilluzen[at]gmail.com> * File: AC_pointer_n_1space.cpp * Create Date: 2015-04-01 11:14:48 * Descripton: O(1) space */ #include <bits/stdc++.h> using namespace std; const int N = 0; class Solution { private: void reverse_array(int nums[], int a, int b) { while (a < b) { swap(nums[a], nums[b]); ++a; --b; } } public: void rotate(int nums[], int n, int k) { if (n == 0 || k % n == 0) return; k = k % n; reverse_array(nums, 0, n - k - 1); reverse_array(nums, n - k, n - 1); reverse_array(nums, 0, n - 1); } }; int main() { int num[] = {1, 2, 3, 4, 5}; Solution s; s.rotate(num, 5, 3); for (int i = 0; i < 5; ++i) cout << num[i] << ' '; cout << endl; return 0; }
19.409091
50
0.4637
subramp-prep
bcfb26f1b23ecdb6fb1d8ca72d4cf914751b0995
8,418
cpp
C++
code/wxWidgets/src/mac/classic/dirmac.cpp
Bloodknight/NeuTorsion
a5890e9ca145a8c1b6bec7b70047a43d9b1c29ea
[ "MIT" ]
38
2016-02-20T02:46:28.000Z
2021-11-17T11:39:57.000Z
code/wxWidgets/src/mac/classic/dirmac.cpp
Dwarf-King/TorsionEditor
e6887d1661ebaf4ccbf1d09f2690e2bf805fbb50
[ "MIT" ]
17
2016-02-20T02:19:55.000Z
2021-02-08T15:15:17.000Z
code/wxWidgets/src/mac/classic/dirmac.cpp
Dwarf-King/TorsionEditor
e6887d1661ebaf4ccbf1d09f2690e2bf805fbb50
[ "MIT" ]
46
2016-02-20T02:47:33.000Z
2021-01-31T15:46:05.000Z
///////////////////////////////////////////////////////////////////////////// // Name: msw/dir.cpp // Purpose: wxDir implementation for Mac // Author: Stefan Csomor // Modified by: // Created: 08.12.99 // RCS-ID: $Id: dirmac.cpp,v 1.4 2005/04/05 16:10:06 ABX Exp $ // Copyright: (c) 1999 Stefan Csomor <csomor@advanced.ch> // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// // ============================================================================ // declarations // ============================================================================ // ---------------------------------------------------------------------------- // headers // ---------------------------------------------------------------------------- #ifdef __GNUG__ #pragma implementation "dir.h" #endif // For compilers that support precompilation, includes "wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #ifndef WX_PRECOMP #include "wx/intl.h" #include "wx/log.h" #endif // PCH #include "wx/dir.h" #include "wx/filefn.h" // for wxDirExists() #ifndef __DARWIN__ #include <windows.h> #endif #include "wx/mac/private.h" #ifdef __DARWIN__ # include "MoreFilesX.h" #else # include "MoreFiles.h" # include "MoreFilesExtras.h" #endif // ---------------------------------------------------------------------------- // constants // ---------------------------------------------------------------------------- #ifndef MAX_PATH #define MAX_PATH 260 // from VC++ headers #endif // ---------------------------------------------------------------------------- // macros // ---------------------------------------------------------------------------- #define M_DIR ((wxDirData *)m_data) // ---------------------------------------------------------------------------- // private classes // ---------------------------------------------------------------------------- // this class stores everything we need to enumerate the files class wxDirData { public: wxDirData(const wxString& dirname); ~wxDirData(); void SetFileSpec(const wxString& filespec) { m_filespec = filespec; } void SetFlags(int flags) { m_flags = flags; } bool Read(wxString *filename); // reads the next void Rewind() ; const wxString& GetName() const { return m_dirname; } bool Ok() const { return m_ok; } private: CInfoPBRec m_CPB ; wxInt16 m_index ; long m_dirId ; Str255 m_name ; Boolean m_isDir ; wxString m_dirname; wxString m_filespec; int m_flags; bool m_ok; }; // ============================================================================ // implementation // ============================================================================ // ---------------------------------------------------------------------------- // wxDirData // ---------------------------------------------------------------------------- wxDirData::wxDirData(const wxString& dirname) : m_dirname(dirname) { m_ok = false; OSErr err; // throw away the trailing slashes size_t n = m_dirname.length(); wxCHECK_RET( n, _T("empty dir name in wxDir") ); while ( n > 0 && wxIsPathSeparator(m_dirname[--n]) ) ; m_dirname.Truncate(n + 1); #ifdef __DARWIN__ FSRef theRef; // get the FSRef associated with the POSIX path err = FSPathMakeRef((const UInt8 *) m_dirname.c_str(), &theRef, NULL); FSGetVRefNum(&theRef, &(m_CPB.hFileInfo.ioVRefNum)); err = FSGetNodeID( &theRef , &m_dirId , &m_isDir ) ; #else FSSpec fsspec ; wxMacFilename2FSSpec( m_dirname , &fsspec ) ; m_CPB.hFileInfo.ioVRefNum = fsspec.vRefNum ; err = FSpGetDirectoryID( &fsspec , &m_dirId , &m_isDir ) ; #endif //wxASSERT_MSG( (err == noErr) || (err == nsvErr) , wxT("Error accessing directory " + m_dirname)) ; if ( (err == noErr) || (err == nsvErr)) m_ok = true; else wxLogError(wxString(wxT("Error accessing directory ")) + m_dirname); m_CPB.hFileInfo.ioNamePtr = m_name ; m_index = 0 ; } wxDirData::~wxDirData() { } void wxDirData::Rewind() { m_index = 0 ; } bool wxDirData::Read(wxString *filename) { if ( !m_isDir ) return false ; wxString result; short err = noErr ; while ( err == noErr ) { m_index++ ; m_CPB.dirInfo.ioFDirIndex = m_index; m_CPB.dirInfo.ioDrDirID = m_dirId; /* we need to do this every time */ err = PBGetCatInfoSync((CInfoPBPtr)&m_CPB); if ( err != noErr ) break ; // its hidden but we don't want it if ( ( m_CPB.hFileInfo.ioFlFndrInfo.fdFlags & kIsInvisible ) && !(m_flags & wxDIR_HIDDEN) ) continue ; #ifdef __DARWIN__ // under X, names that start with '.' are hidden if ( ( m_name[1] == '.' ) && !(m_flags & wxDIR_HIDDEN) ) continue; #endif #if TARGET_CARBON // under X thats the way the mounting points look like if ( ( m_CPB.dirInfo.ioDrDirID == 0 ) && ( m_flags & wxDIR_DIRS) ) break ; #endif // we have a directory if ( ( m_CPB.dirInfo.ioFlAttrib & ioDirMask) != 0 && (m_flags & wxDIR_DIRS) ) break ; // its a file but we don't want it if ( ( m_CPB.dirInfo.ioFlAttrib & ioDirMask) == 0 && !(m_flags & wxDIR_FILES ) ) continue ; wxString file = wxMacMakeStringFromPascal( m_name ) ; if ( m_filespec.empty() || m_filespec == wxT("*.*") || m_filespec == wxT("*") ) { } else if ( m_filespec.Length() > 1 && m_filespec.Left(1) == wxT("*") ) { if ( file.Right( m_filespec.Length() - 1 ).Upper() != m_filespec.Mid(1).Upper() ) { continue ; } } else if ( m_filespec.Length() > 1 && m_filespec.Right(1) == wxT("*") ) { if ( file.Left( m_filespec.Length() - 1 ).Upper() != m_filespec.Left( m_filespec.Length() - 1 ).Upper() ) { continue ; } } else if ( file.Upper() != m_filespec.Upper() ) { continue ; } break ; } if ( err != noErr ) { return false ; } *filename = wxMacMakeStringFromPascal( m_name ) ; return true; } // ---------------------------------------------------------------------------- // wxDir helpers // ---------------------------------------------------------------------------- /* static */ bool wxDir::Exists(const wxString& dir) { return wxDirExists(dir); } // ---------------------------------------------------------------------------- // wxDir construction/destruction // ---------------------------------------------------------------------------- wxDir::wxDir(const wxString& dirname) { m_data = NULL; (void)Open(dirname); } bool wxDir::Open(const wxString& dirname) { delete M_DIR; m_data = new wxDirData(dirname); if (m_data->Ok()) return true; else { delete m_data; m_data = NULL; return false; } } bool wxDir::IsOpened() const { return m_data != NULL; } wxString wxDir::GetName() const { wxString name; if ( m_data ) { name = M_DIR->GetName(); if ( !name.empty() && (name.Last() == _T('/')) ) { // chop off the last (back)slash name.Truncate(name.length() - 1); } } return name; } wxDir::~wxDir() { if (M_DIR != NULL) { delete M_DIR; m_data = NULL; } } // ---------------------------------------------------------------------------- // wxDir enumerating // ---------------------------------------------------------------------------- bool wxDir::GetFirst(wxString *filename, const wxString& filespec, int flags) const { wxCHECK_MSG( IsOpened(), false, _T("must wxDir::Open() first") ); M_DIR->Rewind(); M_DIR->SetFileSpec(filespec); M_DIR->SetFlags(flags); return GetNext(filename); } bool wxDir::GetNext(wxString *filename) const { wxCHECK_MSG( IsOpened(), false, _T("must wxDir::Open() first") ); wxCHECK_MSG( filename, false, _T("bad pointer in wxDir::GetNext()") ); return M_DIR->Read(filename); }
26.06192
117
0.456284
Bloodknight
bcfc03d92db5f9264d543bfdd870552a562d320c
279
cpp
C++
OJ/judge.u-aizu.ac.jp/Introduction to Programming II/ITP2_5_A_SortingPairs.cpp
webturing/CPlusPlus
6b9c671b0c9a7c0d24d937610bf54e9aec9a5a1f
[ "AFL-2.0" ]
14
2018-06-21T14:41:26.000Z
2021-12-19T14:43:51.000Z
OJ/judge.u-aizu.ac.jp/Introduction to Programming II/ITP2_5_A_SortingPairs.cpp
webturing/CPlusPlus
6b9c671b0c9a7c0d24d937610bf54e9aec9a5a1f
[ "AFL-2.0" ]
null
null
null
OJ/judge.u-aizu.ac.jp/Introduction to Programming II/ITP2_5_A_SortingPairs.cpp
webturing/CPlusPlus
6b9c671b0c9a7c0d24d937610bf54e9aec9a5a1f
[ "AFL-2.0" ]
2
2020-04-20T11:16:53.000Z
2021-01-02T15:58:35.000Z
#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; vector<pair<int, int>> v(n); for (int i = 0; i < n; i++) cin >> v[i].first >> v[i].second; sort(v.begin(), v.end()); for (auto p : v) cout << p.first << " " << p.second << endl; return 0; }
25.363636
63
0.523297
webturing
bcfc661585e36f6c8151eb01e629a4dc593374e6
1,755
cpp
C++
src/main/algorithms/cpp/dynamic-programming/minimum_path_sum_64/solution.cpp
algorithmlover2016/leet_code
2eecc7971194c8a755e67719d8f66c636694e7e9
[ "Apache-2.0" ]
null
null
null
src/main/algorithms/cpp/dynamic-programming/minimum_path_sum_64/solution.cpp
algorithmlover2016/leet_code
2eecc7971194c8a755e67719d8f66c636694e7e9
[ "Apache-2.0" ]
null
null
null
src/main/algorithms/cpp/dynamic-programming/minimum_path_sum_64/solution.cpp
algorithmlover2016/leet_code
2eecc7971194c8a755e67719d8f66c636694e7e9
[ "Apache-2.0" ]
null
null
null
#include "../../head.h" class Solution { public: int minPathSum(std::vector<std::vector<int>> const & grid) { int rowSize = grid.size(); if (0 == rowSize) { return 0; } int colSize = grid[0].size(); if (0 == colSize) { return 0; } std::vector<std::vector<int> > dpSum(rowSize, std::vector<int>(colSize, 0)); for (int row = 0; row < grid.size(); row++) { for (int col = 0; col < grid[row].size(); col++) { int upRow = row - 1; int minNum = INT_MAX; if (upRow >= 0) { minNum = std::min(minNum, dpSum[upRow][col]); } int leftCol = col - 1; if (leftCol >= 0) { minNum = std::min(minNum, dpSum[row][leftCol]); } if (INT_MAX == minNum) { minNum = 0; } dpSum[row][col] = minNum + grid[row][col]; // std::cout << "dp: " << dpSum[row][col] << "\n"; } } return dpSum[rowSize - 1][colSize - 1]; } }; class Solution { public: int minPathSum(std::vector<std::vector<int>> const & grid) { int n = grid.size(), m = grid[0].size(); std::vector<std::vector<int>> v(n, std::vector<int>(m, INT_MAX)); v[0][0] = grid[0][0]; for (int i = 0; i < n; i++) { for(int j = 0;j < m; j++) { if(i >= 1) v[i][j] = std::min(v[i][j], v[i - 1][j] + grid[i][j]); if(j >= 1) v[i][j] = std::min(v[i][j], v[i][j - 1] + grid[i][j]); } } return v[n - 1][m - 1]; } };
31.339286
84
0.393732
algorithmlover2016
bcfe1439f23512fc8d91bbe91c3438e7af167dfb
264
cpp
C++
Thermostaten/src/Thermostat.cpp
oerpli/ComputationalPhysics
5081c46c01d078fe7b86601919a3447294304d8d
[ "Apache-2.0" ]
null
null
null
Thermostaten/src/Thermostat.cpp
oerpli/ComputationalPhysics
5081c46c01d078fe7b86601919a3447294304d8d
[ "Apache-2.0" ]
null
null
null
Thermostaten/src/Thermostat.cpp
oerpli/ComputationalPhysics
5081c46c01d078fe7b86601919a3447294304d8d
[ "Apache-2.0" ]
null
null
null
#include "Thermostat.h" #include "Polymer.h" Thermostat::Thermostat(Polymer &poly, double delta_time) : m_poly(poly) { dtime(delta_time); } double Thermostat::dtime() const { return m_dtime; } void Thermostat::dtime(double new_dtime) { m_dtime = new_dtime; }
18.857143
73
0.734848
oerpli
4c01be17a7ee931aab224362627f5ded43f4288c
2,047
hpp
C++
include/HoudiniEngineUnity/HEU_TestHelpers_RequireClass_1.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
include/HoudiniEngineUnity/HEU_TestHelpers_RequireClass_1.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
include/HoudiniEngineUnity/HEU_TestHelpers_RequireClass_1.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: HoudiniEngineUnity.HEU_TestHelpers #include "HoudiniEngineUnity/HEU_TestHelpers.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE_GENERIC_CLASS(::HoudiniEngineUnity::HEU_TestHelpers::RequireClass_1, "HoudiniEngineUnity", "HEU_TestHelpers/RequireClass`1"); // Type namespace: HoudiniEngineUnity namespace HoudiniEngineUnity { // WARNING Size may be invalid! // Autogenerated type: HoudiniEngineUnity.HEU_TestHelpers/HoudiniEngineUnity.RequireClass`1 // [TokenAttribute] Offset: FFFFFFFF template<typename T> class HEU_TestHelpers::RequireClass_1 : public ::Il2CppObject { public: // public System.Void .ctor() // Offset: 0xFFFFFFFFFFFFFFFF // Implemented from: System.Object // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static HEU_TestHelpers::RequireClass_1<T>* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("::HoudiniEngineUnity::HEU_TestHelpers::RequireClass_1::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<HEU_TestHelpers::RequireClass_1<T>*, creationType>())); } }; // HoudiniEngineUnity.HEU_TestHelpers/HoudiniEngineUnity.RequireClass`1 // Could not write size check! Type: HoudiniEngineUnity.HEU_TestHelpers/HoudiniEngineUnity.RequireClass`1 is generic, or has no fields that are valid for size checks! } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
53.868421
168
0.753786
RedBrumbler
4c05bd2e801efe4d94d466660e3639a588d0b640
528
cpp
C++
application/source/geometry_node.cpp
luigielbambino/CG_Lab_Titz120003Alvarez119446
e494b9d7695dcee5d1e466a3b8bbef1f13cb96bc
[ "MIT" ]
null
null
null
application/source/geometry_node.cpp
luigielbambino/CG_Lab_Titz120003Alvarez119446
e494b9d7695dcee5d1e466a3b8bbef1f13cb96bc
[ "MIT" ]
null
null
null
application/source/geometry_node.cpp
luigielbambino/CG_Lab_Titz120003Alvarez119446
e494b9d7695dcee5d1e466a3b8bbef1f13cb96bc
[ "MIT" ]
null
null
null
// Geometry Node function definitions #include "node.hpp" #include "window_handler.hpp" #include "utils.hpp" #include <glbinding/gl/gl.h> // use gl definitions from glbinding using namespace gl; #define GLFW_INCLUDE_NONE #include <GLFW/glfw3.h> #include <iostream> //Geometry Node constructor GeometryNode::GeometryNode(){ //geometry = newgeometry; } // getters and setters definitios model GeometryNode::getGeometry(){ return geometry; } void GeometryNode::setGeometry(model newgeometry){ geometry = newgeometry; }
19.555556
50
0.761364
luigielbambino
4c07d9c899552b022ad3629f2b0f776769c1fa46
2,277
cpp
C++
test/error.cpp
madmongo1/url
e7c9b0c860abd5fba3b7a20c3b29552a326de7b5
[ "BSL-1.0" ]
null
null
null
test/error.cpp
madmongo1/url
e7c9b0c860abd5fba3b7a20c3b29552a326de7b5
[ "BSL-1.0" ]
null
null
null
test/error.cpp
madmongo1/url
e7c9b0c860abd5fba3b7a20c3b29552a326de7b5
[ "BSL-1.0" ]
null
null
null
// // Copyright (c) 2019 Vinnie Falco (vinnie.falco@gmail.com) // // 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) // // Official repository: https://github.com/CPPAlliance/url // // Test that header file is self-contained. #include <boost/url/error.hpp> #include "test_suite.hpp" #include <memory> namespace boost { namespace urls { class error_test { public: void check(error e) { auto const ec = make_error_code(e); BOOST_TEST(ec.category().name() != nullptr); BOOST_TEST(! ec.message().empty()); BOOST_TEST(ec.category().default_error_condition( static_cast<int>(e)).category() == ec.category()); } void check(condition c, error e) { { auto const ec = make_error_code(e); BOOST_TEST(ec.category().name() != nullptr); BOOST_TEST(! ec.message().empty()); BOOST_TEST(ec == c); } { auto ec = make_error_condition(c); BOOST_TEST(ec.category().name() != nullptr); BOOST_TEST(! ec.message().empty()); BOOST_TEST(ec == c); } } void run() { check(condition::parse_error, error::no_match); check(condition::parse_error, error::syntax); check(condition::parse_error, error::invalid); check(condition::parse_error, error::missing_scheme); check(condition::parse_error, error::bad_scheme_start_char); check(condition::parse_error, error::bad_scheme_char); check(condition::parse_error, error::bad_username_char); check(condition::parse_error, error::bad_userinfo_char); check(condition::parse_error, error::bad_port_char); check(condition::parse_error, error::port_overflow); check(condition::parse_error, error::missing_hostname); check(condition::parse_error, error::missing_port); check(condition::parse_error, error::bad_pct_encoding_digit); check(condition::parse_error, error::incomplete_pct_encoding); check(condition::parse_error, error::illegal_reserved_char); } }; TEST_SUITE(error_test, "boost.url.error"); } // urls } // boost
30.36
79
0.639877
madmongo1
4c0a4a878fea72ad83ca002391f785bed505d4e9
6,635
cc
C++
src/student_dataSK.cc
rmolin88/corba
b23fe31e084b0946211ee8df6346f9042f4f5bac
[ "MIT" ]
null
null
null
src/student_dataSK.cc
rmolin88/corba
b23fe31e084b0946211ee8df6346f9042f4f5bac
[ "MIT" ]
null
null
null
src/student_dataSK.cc
rmolin88/corba
b23fe31e084b0946211ee8df6346f9042f4f5bac
[ "MIT" ]
1
2020-04-29T23:43:55.000Z
2020-04-29T23:43:55.000Z
// This file is generated by omniidl (C++ backend)- omniORB_4_2. Do not edit. #include "student_data.hh" #include <omniORB4/IOP_S.h> #include <omniORB4/IOP_C.h> #include <omniORB4/callDescriptor.h> #include <omniORB4/callHandle.h> #include <omniORB4/objTracker.h> OMNI_USING_NAMESPACE(omni) static const char* _0RL_library_version = omniORB_4_2; StudentInfo_ptr StudentInfo_Helper::_nil() { return ::StudentInfo::_nil(); } ::CORBA::Boolean StudentInfo_Helper::is_nil(::StudentInfo_ptr p) { return ::CORBA::is_nil(p); } void StudentInfo_Helper::release(::StudentInfo_ptr p) { ::CORBA::release(p); } void StudentInfo_Helper::marshalObjRef(::StudentInfo_ptr obj, cdrStream& s) { ::StudentInfo::_marshalObjRef(obj, s); } StudentInfo_ptr StudentInfo_Helper::unmarshalObjRef(cdrStream& s) { return ::StudentInfo::_unmarshalObjRef(s); } void StudentInfo_Helper::duplicate(::StudentInfo_ptr obj) { if (obj && !obj->_NP_is_nil()) omni::duplicateObjRef(obj); } StudentInfo_ptr StudentInfo::_duplicate(::StudentInfo_ptr obj) { if (obj && !obj->_NP_is_nil()) omni::duplicateObjRef(obj); return obj; } StudentInfo_ptr StudentInfo::_narrow(::CORBA::Object_ptr obj) { if (!obj || obj->_NP_is_nil() || obj->_NP_is_pseudo()) return _nil(); _ptr_type e = (_ptr_type) obj->_PR_getobj()->_realNarrow(_PD_repoId); return e ? e : _nil(); } StudentInfo_ptr StudentInfo::_unchecked_narrow(::CORBA::Object_ptr obj) { if (!obj || obj->_NP_is_nil() || obj->_NP_is_pseudo()) return _nil(); _ptr_type e = (_ptr_type) obj->_PR_getobj()->_uncheckedNarrow(_PD_repoId); return e ? e : _nil(); } StudentInfo_ptr StudentInfo::_nil() { #ifdef OMNI_UNLOADABLE_STUBS static _objref_StudentInfo _the_nil_obj; return &_the_nil_obj; #else static _objref_StudentInfo* _the_nil_ptr = 0; if (!_the_nil_ptr) { omni::nilRefLock().lock(); if (!_the_nil_ptr) { _the_nil_ptr = new _objref_StudentInfo; registerNilCorbaObject(_the_nil_ptr); } omni::nilRefLock().unlock(); } return _the_nil_ptr; #endif } const char* StudentInfo::_PD_repoId = "IDL:StudentInfo:1.0"; _objref_StudentInfo::~_objref_StudentInfo() { } _objref_StudentInfo::_objref_StudentInfo(omniIOR* ior, omniIdentity* id) : omniObjRef(::StudentInfo::_PD_repoId, ior, id, 1) { _PR_setobj(this); } void* _objref_StudentInfo::_ptrToObjRef(const char* id) { if (id == ::StudentInfo::_PD_repoId) return (::StudentInfo_ptr) this; if (id == ::CORBA::Object::_PD_repoId) return (::CORBA::Object_ptr) this; if (omni::strMatch(id, ::StudentInfo::_PD_repoId)) return (::StudentInfo_ptr) this; if (omni::strMatch(id, ::CORBA::Object::_PD_repoId)) return (::CORBA::Object_ptr) this; return 0; } // // Code for StudentInfo::SetStudentData // Proxy call descriptor class. Mangled signature: // _clong class _0RL_cd_80d5c52d0a7a1b14_00000000 : public omniCallDescriptor { public: inline _0RL_cd_80d5c52d0a7a1b14_00000000(LocalCallFn lcfn, const char* op_, size_t oplen, _CORBA_Boolean upcall=0) : omniCallDescriptor(lcfn, op_, oplen, 0, _user_exns, 0, upcall) { } void unmarshalReturnedValues(cdrStream&); void marshalReturnedValues(cdrStream&); static const char* const _user_exns[]; ::CORBA::Long result; }; void _0RL_cd_80d5c52d0a7a1b14_00000000::marshalReturnedValues(cdrStream& _n) { result >>= _n; } void _0RL_cd_80d5c52d0a7a1b14_00000000::unmarshalReturnedValues(cdrStream& _n) { (::CORBA::Long&)result <<= _n; } const char* const _0RL_cd_80d5c52d0a7a1b14_00000000::_user_exns[] = { 0 }; // Local call call-back function. static void _0RL_lcfn_80d5c52d0a7a1b14_10000000(omniCallDescriptor* cd, omniServant* svnt) { _0RL_cd_80d5c52d0a7a1b14_00000000* tcd = (_0RL_cd_80d5c52d0a7a1b14_00000000*)cd; _impl_StudentInfo* impl = (_impl_StudentInfo*) svnt->_ptrToInterface(StudentInfo::_PD_repoId); tcd->result = impl->SetStudentData(); } ::CORBA::Long _objref_StudentInfo::SetStudentData() { _0RL_cd_80d5c52d0a7a1b14_00000000 _call_desc(_0RL_lcfn_80d5c52d0a7a1b14_10000000, "SetStudentData", 15); _invoke(_call_desc); return _call_desc.result; } // // Code for StudentInfo::GetStudentData // Proxy call descriptor class. Mangled signature: // void class _0RL_cd_80d5c52d0a7a1b14_20000000 : public omniCallDescriptor { public: inline _0RL_cd_80d5c52d0a7a1b14_20000000(LocalCallFn lcfn, const char* op_, size_t oplen, _CORBA_Boolean upcall=0) : omniCallDescriptor(lcfn, op_, oplen, 0, _user_exns, 0, upcall) { } static const char* const _user_exns[]; }; const char* const _0RL_cd_80d5c52d0a7a1b14_20000000::_user_exns[] = { 0 }; // Local call call-back function. static void _0RL_lcfn_80d5c52d0a7a1b14_30000000(omniCallDescriptor*, omniServant* svnt) { _impl_StudentInfo* impl = (_impl_StudentInfo*) svnt->_ptrToInterface(StudentInfo::_PD_repoId); impl->GetStudentData(); } void _objref_StudentInfo::GetStudentData() { _0RL_cd_80d5c52d0a7a1b14_20000000 _call_desc(_0RL_lcfn_80d5c52d0a7a1b14_30000000, "GetStudentData", 15); _invoke(_call_desc); } _pof_StudentInfo::~_pof_StudentInfo() {} omniObjRef* _pof_StudentInfo::newObjRef(omniIOR* ior, omniIdentity* id) { return new ::_objref_StudentInfo(ior, id); } ::CORBA::Boolean _pof_StudentInfo::is_a(const char* id) const { if (omni::ptrStrMatch(id, ::StudentInfo::_PD_repoId)) return 1; return 0; } const _pof_StudentInfo _the_pof_StudentInfo; _impl_StudentInfo::~_impl_StudentInfo() {} ::CORBA::Boolean _impl_StudentInfo::_dispatch(omniCallHandle& _handle) { const char* op = _handle.operation_name(); if (omni::strMatch(op, "SetStudentData")) { _0RL_cd_80d5c52d0a7a1b14_00000000 _call_desc(_0RL_lcfn_80d5c52d0a7a1b14_10000000, "SetStudentData", 15, 1); _handle.upcall(this,_call_desc); return 1; } if (omni::strMatch(op, "GetStudentData")) { _0RL_cd_80d5c52d0a7a1b14_20000000 _call_desc(_0RL_lcfn_80d5c52d0a7a1b14_30000000, "GetStudentData", 15, 1); _handle.upcall(this,_call_desc); return 1; } return 0; } void* _impl_StudentInfo::_ptrToInterface(const char* id) { if (id == ::StudentInfo::_PD_repoId) return (::_impl_StudentInfo*) this; if (id == ::CORBA::Object::_PD_repoId) return (void*) 1; if (omni::strMatch(id, ::StudentInfo::_PD_repoId)) return (::_impl_StudentInfo*) this; if (omni::strMatch(id, ::CORBA::Object::_PD_repoId)) return (void*) 1; return 0; } const char* _impl_StudentInfo::_mostDerivedRepoId() { return ::StudentInfo::_PD_repoId; } POA_StudentInfo::~POA_StudentInfo() {}
21.542208
116
0.728711
rmolin88
4c0a90c979631b093d1f0d7897b5cd069e096071
22,287
cpp
C++
archive/olddraw/PdfDraw/PdfDraw.cpp
dreamsxin/ultimatepp
41d295d999f9ff1339b34b43c99ce279b9b3991c
[ "BSD-2-Clause" ]
2
2016-04-07T07:54:26.000Z
2020-04-14T12:37:34.000Z
archive/olddraw/PdfDraw/PdfDraw.cpp
dreamsxin/ultimatepp
41d295d999f9ff1339b34b43c99ce279b9b3991c
[ "BSD-2-Clause" ]
null
null
null
archive/olddraw/PdfDraw/PdfDraw.cpp
dreamsxin/ultimatepp
41d295d999f9ff1339b34b43c99ce279b9b3991c
[ "BSD-2-Clause" ]
null
null
null
#include "PdfDraw.h" NAMESPACE_UPP #define LDUMP(x) // DUMP(x) #define LLOG(x) // LOG(x) #define PDF_COMPRESS #define USE_TTF void PdfDraw::Init(int pagecx, int pagecy, int _margin) { Clear(); margin = _margin; pgsz.cx = pagecx; pgsz.cy = pagecy; pageMMs = iscale(pgsz, 254, 6000); inchPixels = Size(600, 600); pagePixels = pgsz; pgsz += margin; sheetPixels = pgsz; pageOffset = Point(0, 0); pixels = false; actual_offset = Point(0, 0); actual_clip = Rect(pgsz); } void PdfDraw::Clear() { out.Clear(); page.Clear(); offset.Clear(); out << "%PDF-1.3\n"; out << "%\xf1\xf2\xf3\xf4\n\n"; } int PdfDraw::BeginObj() { offset.Add(out.GetLength()); out << offset.GetCount() << " 0 obj\n"; return offset.GetCount(); } void PdfDraw::EndObj() { out << "endobj\n\n"; } void PdfDraw::PutRect(const Rect& rc) { page << Pt(rc.left) << ' ' << Pt(pgsz.cy - rc.bottom) << ' ' << Pt(rc.Width()) << ' ' << Pt(rc.Height()) << " re\n"; } int PdfDraw::PutStream(const String& data, const String& keys) { #ifdef PDF_COMPRESS String c = ZCompress(data); if(c.GetLength() < data.GetLength()) { BeginObj(); out << "<< " << keys << "/Length " << c.GetLength() << " " << "/Length1 " << data.GetLength() << " " << "/Filter /FlateDecode " << " >>\n" << "stream\r\n" << c << "\r\nendstream\n"; EndObj(); return offset.GetCount(); } #endif BeginObj(); out << "<< " << keys << " /Length " << data.GetLength() << " /Length1 "<< data.GetLength() << " >>\n" << "stream\r\n" << data << "\r\nendstream\n"; EndObj(); return offset.GetCount(); } void PdfDraw::PutrgColor(Color rg) { if(IsNull(rgcolor) || rg != rgcolor) page << PdfColor(rgcolor = rg) << " rg\n"; } void PdfDraw::PutRGColor(Color RG) { if(IsNull(RGcolor) || RG != RGcolor) page << PdfColor(RGcolor = RG) << " RG\n"; } void PdfDraw::PutLineWidth(int lw) { lw = max(Nvl(lw, 0), 5); if(linewidth != lw) page << Pt(linewidth = lw) << " w\n"; } void PdfDraw::StartPage() { offstack.Clear(); clipstack.Clear(); actual_offset = Point(0, 0); actual_clip = Rect(pgsz); rgcolor = RGcolor = Null; fontid = -1; textht = Null; linewidth = -1; if(margin) OffsetOp(Point(margin, margin)); } void PdfDraw::EndPage() { if(margin) EndOp(); ASSERT(offstack.IsEmpty()); PutStream(page); page.Clear(); } void PdfDraw::BeginOp() { offstack.Add(actual_offset); clipstack.Add(actual_clip); page << "q\n"; } void PdfDraw::EndOp() { fontid = -1; textht = Null; rgcolor = RGcolor = Null; linewidth = -1; page << "Q\n"; if(offstack.GetCount()) { actual_offset = offstack.Pop(); actual_clip = clipstack.Pop(); } else { NEVER(); } } void PdfDraw::OffsetOp(Point p) { offstack.Add(actual_offset); clipstack.Add(actual_clip); page << "q\n"; if(p.x || p.y) { page << "1 0 0 1 " << Pt(p.x) << ' ' << Pt(-p.y) << " cm\n"; actual_offset += p; actual_clip -= p; } } bool PdfDraw::ClipOp(const Rect& r) { offstack.Add(actual_offset); clipstack.Add(actual_clip); page << "q "; PutRect(r); page << "W* n\n"; actual_clip &= r; return !actual_clip.IsEmpty(); } bool PdfDraw::ClipoffOp(const Rect& r) { offstack.Add(actual_offset); clipstack.Add(actual_clip); actual_offset += r.TopLeft(); actual_clip &= r; page << "q "; PutRect(actual_clip); actual_clip -= r.TopLeft(); page << "W* n\n"; if(r.left || r.top) page << "1 0 0 1 " << Pt(r.left) << ' ' << Pt(-r.top) << " cm\n"; return !actual_clip.IsEmpty(); } bool PdfDraw::ExcludeClipOp(const Rect& r) { if(r.left <= actual_clip.left && r.right >= actual_clip.right) { if(r.top <= actual_clip.top) actual_clip.top = max(actual_clip.top, r.bottom); if(r.bottom >= actual_clip.bottom) actual_clip.bottom = min(actual_clip.bottom, r.top); } if(r.top <= actual_clip.top && r.bottom >= actual_clip.bottom) { if(r.left <= actual_clip.left) actual_clip.left = max(actual_clip.left, r.right); if(r.right >= actual_clip.right) actual_clip.right = min(actual_clip.right, r.left); } PutRect(actual_clip); PutRect(r & actual_clip); page << "W* n\n"; return !actual_clip.IsEmpty(); } bool PdfDraw::IntersectClipOp(const Rect& r) { PutRect(r); page << "W* n\n"; actual_clip &= r; return !actual_clip.IsEmpty(); } Rect PdfDraw::GetClipOp() const { return actual_clip; } bool PdfDraw::IsPaintingOp(const Rect&) const { return true; } PdfDraw::CharPos PdfDraw::GetCharPos(Font fnt, wchar chr) { fnt.Underline(false); VectorMap<wchar, CharPos>& fc = fontchars.GetAdd(fnt); int q = fc.Find(chr); if(q >= 0) return fc[q]; CharPos& p = fc.Add(chr); q = pdffont.FindLast(fnt); if(q < 0 || pdffont[q].GetCount() > 250) { p.fi = pdffont.GetCount(); p.ci = 0; pdffont.Add(fnt).Add(chr); } else { p.fi = q; p.ci = pdffont[q].GetCount(); pdffont[q].Add(chr); } return p; } void PdfDraw::FlushText(int dx, int fi, int height, const String& txt) { if(fi < 0) return; if(dx) page << Pt(dx) << " 0 Td "; PutFontHeight(fi, height); page << "<" << txt << "> Tj\n"; } String PdfDraw::PdfColor(Color c) { return NFormat("%3nf %3nf %3nf", c.GetR() / 255.0, c.GetG() / 255.0, c.GetB() / 255.0); } void PdfDraw::PutFontHeight(int fi, double ht) { if(fi != fontid || IsNull(textht) || ht != textht) page << "/F" << ((fontid = fi) + 1) << ' ' << Pt(textht = ht) << " Tf\n"; } PdfDraw::OutlineInfo PdfDraw::GetOutlineInfo(Font fnt) { fnt.Height(0); int q = outline_info.Find(fnt); if(q >= 0) return outline_info[q]; OutlineInfo of; of.sitalic = of.ttf = false; #ifdef USE_TTF #ifdef PLATFORM_WIN32 ScreenDraw info; info.SetFont(fnt().Underline(false)); TEXTMETRIC tm; GetTextMetrics(info.GetHandle(), &tm); if(tm.tmPitchAndFamily & TMPF_TRUETYPE) { of.ttf = true; int c = GetOutlineTextMetrics(info.GetHandle(), 0, NULL); if(c > 0) { Buffer<byte> h(c); OUTLINETEXTMETRIC *otm = (OUTLINETEXTMETRIC *)~h; GetOutlineTextMetrics(info.GetHandle(), c, otm); of.sitalic = otm->otmItalicAngle == 0 && fnt.IsItalic(); } } #endif #ifdef PLATFORM_X11 FontInfo fi = fnt.Info(); String fn = fi.GetFileName(); String ext = ToLower(GetFileExt(fn)); if(ext == ".ttf" || ext == ".otf") { String data = LoadFile(fn); TTFReader ttf; if(ttf.Open(data, false, true)) { of.ttf = true; of.sitalic = ttf.post.italicAngle == 0 && fnt.IsItalic(); } } #endif #endif outline_info.Add(fnt, of); return of; } void PdfDraw::DrawTextOp(int x, int y, int angle, const wchar *s, Font fnt, Color ink, int n, const int *dx) { if(!n) return; if(fnt.GetHeight() == 0) fnt.Height(100); FontInfo ff = fnt.Info(); #ifdef PLATFORM_WIN32 int fh = ff.GetHeight() - ff.GetInternal();//TODO #endif #ifdef PLATFORM_X11 int fh = fnt.GetHeight(); #endif OutlineInfo of = GetOutlineInfo(fnt); if(of.ttf) fnt.Height(0); String txt; PutrgColor(ink); PutRGColor(ink); page << "BT "; double sina = 0, cosa = 1; int posx = 0; if(angle || dx || (of.sitalic && !fnt.IsItalic())) { M22 m; if(of.sitalic) m.c = 0.165; if(angle) { Draw::SinCos(angle, sina, cosa); m.Mul(cosa, sina, -sina, cosa); } int fi = -1; bool straight = (fabs(m.a - 1) <= 1e-8 && fabs(m.b) <= 1e-8 && fabs(m.c) <= 1e-8 && fabs(m.d - 1) <= 1e-8); Pointf prev(0, 0); for(int i = 0; i < n; i++) { Pointf next(Pt(x + posx * cosa + fround(ff.GetAscent() * sina)), Pt(pgsz.cy - (y - posx * sina) - fround(ff.GetAscent() * cosa))); CharPos fp = GetCharPos(fnt, s[i]); if(fi != fp.fi) { fi = fp.fi; PutFontHeight(fi, fh); } if(straight) page << (next.x - prev.x) << ' ' << (next.y - prev.y) << " Td"; else page << m.a << ' ' << m.b << ' ' << m.c << ' ' << m.d << ' ' << next.x << ' ' << next.y << " Tm"; page << " <" << FormatIntHex(fp.ci, 2); while(i + 1 < n) { int cw = ff[s[i]]; if(dx && dx[i] != cw) break; posx += cw; CharPos np = GetCharPos(fnt, s[i + 1]); if(np.fi != fp.fi) break; page << FormatIntHex(np.ci, 2); i++; } page << "> Tj\n"; posx += dx ? dx[i] : ff[s[i]]; prev = next; } } else { page << Pt(x) << " " << Pt(pgsz.cy - y - ff.GetAscent()) << " Td\n"; int fi = -1; int ppos = 0; int np = 0; for(int i = 0; i < n; i++) { CharPos fp = GetCharPos(fnt, s[i]); if(fp.fi != fi) { FlushText(np, fi, fnt.GetHeight(), txt); txt.Clear(); np = posx - ppos; ppos = posx; fi = fp.fi; } txt.Cat(Sprintf("%02.2X", fp.ci)); posx += ff[s[i]]; } FlushText(np, fi, fh, txt); } page << "ET\n"; if(fnt.IsUnderline()) { int w = ff.GetAscent() / 15; int dy = ff.GetAscent() + max((ff.GetDescent() - w) / 2, ff.GetAscent() / 10); DrawLine(fround(x + sina * dy), fround(y + cosa * dy), fround(x + cosa * posx + sina * dy), fround(y + cosa * dy - sina * posx), w, ink); } } Image RenderGlyph(int cx, int x, Font font, int chr, int py, int pcy) { ImageDraw iw(cx, pcy); iw.DrawRect(0, 0, cx, pcy, White); iw.DrawText(x, -py, WString(chr, 1), font, Black); return iw; } PdfDraw::RGlyph PdfDraw::RasterGlyph(Font fnt, int chr) { RGlyph rg; FontInfo fi = fnt.Info(); rg.x = 0; rg.sz.cx = fi[chr]; rg.sz.cy = fi.GetHeight(); int l = fi.GetLeftSpace(chr); if(l < 0) { rg.x = -l; rg.sz.cx -= l; } int r = fi.GetRightSpace(chr); if(r < 0) rg.sz.cx -= r; RasterFormat fmt; fmt.Set1mf(); int linebytes = fmt.GetByteCount(rg.sz.cx); Buffer<byte> ob(linebytes); int y = 0; while(y < rg.sz.cy) { int ccy = min(16, rg.sz.cy - y); Image m = RenderGlyph(rg.sz.cx, rg.x, fnt, chr, y, ccy); for(int i = 0; i < m.GetHeight(); i++) { fmt.Write(ob, m[i], rg.sz.cx, NULL); rg.data.Cat((const char *)~ob, linebytes); } y += ccy; } return rg; } void PdfDraw::DrawRectOp(int x, int y, int cx, int cy, Color color) { if(IsNull(color) || cx <= 0 || cy <= 0) return; PutrgColor(color); PutRGColor(color); PutRect(RectC(x, y, cx, cy)); page << "f\n"; } void PdfDraw::DrawLineOp(int x1, int y1, int x2, int y2, int width, Color color) { if(!IsNull(width)) { PutRGColor(color); PutLineWidth(width); page << " 1 J " << Pt(x1) << ' ' << Pt(pgsz.cy - y1) << " m " << Pt(x2) << ' ' << Pt(pgsz.cy - y2) << " l S\n"; } } void PdfDraw::DrawImageOp(int x, int y, int cx, int cy, const Image& _img, const Rect& src, Color c) { Image img = _img; if(!IsNull(c)) img = SetColorKeepAlpha(img, c); image.Add(img); imagerect.Add(src); page << "q " << Pt(cx) << " 0 0 " << Pt(cy) << ' ' << Pt(x) << ' ' << Pt(pgsz.cy - y - cy) << " cm /Image" << image.GetCount() << " Do Q\n"; } void PdfDraw::DrawPolyPolylineOp(const Point *vertices, int vertex_count, const int *counts, int count_count, int width, Color color, Color doxor) { if(IsNull(color) || IsNull(width)) return; PutRGColor(color); PutLineWidth(width); while(--count_count >= 0) { int part = *counts++; page << Pt(vertices->x) << ' ' << Pt(pgsz.cy - vertices->y) << " m\n"; vertices++; for(; --part > 0; vertices++) page << Pt(vertices->x) << ' ' << Pt(pgsz.cy - vertices->y) << " l\n"; page << "S\n"; } } void PdfDraw::DrawEllipseOp(const Rect& r, Color color, int pen, Color outline) { bool fill = !IsNull(color), stroke = !IsNull(outline) && !IsNull(pen); if(fill) PutrgColor(color); if(stroke) { PutRGColor(outline); PutLineWidth(pen); } if(!fill && !stroke) return; char closeop = (stroke && fill ? 'B' : fill ? 'f' : 'S'); int sizelim = r.Width() | r.Height(); int bits = 1; while(bits < 20 && sizelim > (1 << bits)) bits++; int parts = 3 + max(((bits * (bits - 6)) >> 3) | 1, 1); double k = 2 * M_PI / 3 / parts; Pointf center(Pt((r.left + r.right) / 2.0), Pt(pgsz.cy - ((r.top + r.bottom) / 2.0))); Pointf size(Pt(r.Width() / 2.0), Pt(r.Height() / 2.0)); for(int partid = 0; partid < parts; partid++) { double phi1 = (partid + 0) * (2 * M_PI / parts); double phi2 = (partid + 1) * (2 * M_PI / parts); double s1 = sin(phi1), c1 = cos(phi1), s2 = sin(phi2), c2 = cos(phi2); Pointf A = center + Pointf(c1, s1) * size; Pointf D = center + Pointf(c2, s2) * size; Pointf dA = Pointf(-s1, c1) * size; Pointf dD = Pointf(-s2, c2) * size; Pointf B = A + k * dA; Pointf C = D - k * dD; if(!partid) page << FormatDoubleFix(A.x, 2) << ' ' << FormatDoubleFix(A.y, 2) << " m\n"; page << FormatDoubleFix(B.x, 2) << ' ' << FormatDoubleFix(B.y, 2) << ' ' << FormatDoubleFix(C.x, 2) << ' ' << FormatDoubleFix(C.y, 2) << ' ' << FormatDoubleFix(D.x, 2) << ' ' << FormatDoubleFix(D.y, 2) << " c\n"; } page << closeop << '\n'; } void PdfDraw::DrawArcOp(const Rect& rc, Point start, Point end, int width, Color color) { //TODO!! NEVER(); } void PdfDraw::DrawPolyPolyPolygonOp(const Point *vertices, int vertex_count, const int *subpolygon_counts, int subpolygon_count_count, const int *disjunct_polygon_counts, int disjunct_polygon_count_count, Color color, int width, Color outline, uint64 pattern, Color doxor) { bool fill = !IsNull(color), stroke = !IsNull(outline) && !IsNull(width); if(fill) PutrgColor(color); if(stroke) { PutRGColor(outline); PutLineWidth(width); } if(!fill && !stroke) return; const char *closeop = (fill & stroke ? "B*" : fill ? "f*" : "S"); while(--disjunct_polygon_count_count >= 0) { int disj = *disjunct_polygon_counts++; while(disj > 0) { int sub = *subpolygon_counts++; disj -= sub; page << Pt(vertices->x) << ' ' << Pt(pgsz.cy - vertices->y) << " m\n"; vertices++; for(; --sub > 0; vertices++) page << Pt(vertices->x) << ' ' << Pt(pgsz.cy - vertices->y) << " l\n"; page << "h\n"; } page << closeop << '\n'; } } String PdfDraw::Finish() { if(!IsNull(page)) PutStream(page); int pagecount = offset.GetCount(); Vector<int> imageobj; for(int i = 0; i < image.GetCount(); i++) { Size sz = image[i].GetSize(); Rect sr = sz & imagerect[i]; String data; const Image& m = image[i]; int mask = -1; int smask = -1; if(m.GetKind() == IMAGE_MASK) { for(int y = sr.top; y < sr.bottom; y++) { const RGBA *p = m[y] + sr.left; const RGBA *e = m[y] + sr.right; while(p < e) { int bit = 0x80; byte b = 0; while(bit && p < e) { if(p->a != 255) b |= bit; bit >>= 1; p++; } data.Cat(b); } } mask = PutStream(data, String().Cat() << "/Type /XObject /Subtype /Image /Width " << sr.Width() << " /Height " << sr.Height() << " /BitsPerComponent 1 /ImageMask true /Decode [0 1]"); } if(m.GetKind() == IMAGE_ALPHA) { for(int y = sr.top; y < sr.bottom; y++) { const RGBA *p = m[y] + sr.left; const RGBA *e = m[y] + sr.right; while(p < e) data.Cat((p++)->a); } smask = PutStream(data, String().Cat() << "/Type /XObject /Subtype /Image /Width " << sr.Width() << " /Height " << sr.Height() << " /BitsPerComponent 8 /ColorSpace /DeviceGray /Decode [0 1]"); } data.Clear(); for(int y = sr.top; y < sr.bottom; y++) { const RGBA *p = m[y] + sr.left; const RGBA *e = m[y] + sr.right; while(p < e) { data.Cat(p->r); data.Cat(p->g); data.Cat(p->b); p++; } } String imgobj; imgobj << "/Type /XObject /Subtype /Image /Width " << sr.Width() << " /Height " << sr.Height() << " /BitsPerComponent 8 /ColorSpace /DeviceRGB"; if(mask >= 0) imgobj << " /Mask " << mask << " 0 R"; if(smask >= 0) imgobj << " /SMask " << smask << " 0 R"; imageobj << PutStream(data, imgobj); } /* Vector<int> rgobj; Vector<Size> rgsz; Vector<int> rgx; for(int i = 0; i < pdffont.GetCount(); i++) { Font fnt = pdffont.GetKey(i); if(fnt.GetHeight()) { for(int c = 0; c < pdffont[i].GetCount(); c++) { RGlyph rg = RasterGlyph(fnt, pdffont[i][c]); int ii = rgobj.GetCount(); rgobj << PutStream(rg.data, String().Cat() << "/Type /XObject /Subtype /Image " << " /Width " << rg.sz.cx << " /Height " << rg.sz.cy << " /BitsPerComponent 1 /ImageMask true /Decode [0 1]"); rgsz.Add(rg.sz); rgx.Add(rg.x); } } } */ Vector<int> fontobj; for(int i = 0; i < pdffont.GetCount(); i++) { Font fnt = pdffont.GetKey(i); const Vector<wchar>& cs = pdffont[i]; String cmap; cmap << "/CIDInit /ProcSet findresource begin\n" "12 dict begin\n" "begincmap\n" "/CIDSystemInfo\n" "<< /Registry (Adobe)\n" "/Ordering (UCS)\n" "/Supplement 0\n" ">> def\n" "/CMapName /UCS" << i << " def\n" "/CMapType 2 def\n" "1 begincodespacerange\n" "<00> <" << FormatIntHex(cs.GetCount() - 1, 2) << ">\n" "endcodespacerange\n" "1 beginbfrange\n" "<00> <" << FormatIntHex(cs.GetCount() - 1, 2) << ">\n" "[\n"; for(int c = 0; c < cs.GetCount(); c++) cmap << '<' << FormatIntHex(cs[c], 4) << ">\n"; cmap << "]\n" "endbfrange\n" "endcmap\n" "CMapName currentdict /CMap defineresource pop\n" "end\n" "end\n"; int cmapi = PutStream(cmap); if(fnt.GetHeight()) { FontInfo fi = fnt.Info(); int t3ch = offset.GetCount() + 1; int fa = fi.GetHeight() - fi.GetInternal(); String res; for(int c = 0; c < cs.GetCount(); c++) { RGlyph rg = RasterGlyph(fnt, pdffont[i][c]); String proc; proc << 1000 * fi[cs[c]] / fa << " 0 0 " << -1000 * fi.GetDescent() / fa << ' ' << 1000 * (rg.sz.cx + rg.x) / fa << ' ' << 1000 * rg.sz.cy / fa << " d1\nq " << 1000 * rg.sz.cx / fa << " 0 0 " << 1000 * rg.sz.cy / fa << " " << -1000 * rg.x / fa << " " << -1000 * fi.GetDescent() / fa << " cm BI /W " << rg.sz.cx << " /H " << rg.sz.cy << " /BPC 1 /IM true /D [0 1] ID\n" << rg.data << "\nEI Q" ; PutStream(proc); } int charprocs = BeginObj(); out << "<<"; for(int c = 0; c < cs.GetCount(); c++) out << " /Rgch" << c << ' ' << t3ch + c<< " 0 R"; out << " >>\n"; EndObj(); int encoding = BeginObj(); out << "<< /Type /Encoding /Differences [0"; for(int c = 0; c < cs.GetCount(); c++) out << " /Rgch" << c; out << "] >>\n"; EndObj(); fontobj.Add() = BeginObj(); out << "<< /Name /F" << i + 1 << " /Type /Font\n" "/Subtype /Type3\n" "/FontBBox [0 0 0 0]\n" "/FontMatrix [0.001 0 0 0.001 0 0]\n" "/CharProcs " << charprocs << " 0 R\n" "/Encoding " << encoding << " 0 R\n" "/FirstChar 0\n" "/LastChar " << cs.GetCount() - 1 << "\n" "/Widths ["; for(int i = 0; i < cs.GetCount(); i++) out << ' ' << 1000 * fi[cs[i]] / fa; out << "]\n"; out << "/Resources << /ProcSet [ /PDF /Text /ImageB ] >>\n" << "/FirstChar 0 /LastChar " << cs.GetCount() - 1 <<" /ToUnicode " << cmapi << " 0 R\n>>\n"; EndObj(); } else { #ifdef PLATFORM_POSIX FontInfo fi = pdffont.GetKey(i).Info(); String fontbuffer = LoadFile(fi.GetFileName()); #endif #ifdef PLATFORM_WIN32 ScreenDraw sd; sd.SetFont(pdffont.GetKey(i)); int size = GetFontData(sd.GetHandle(), 0, 0, NULL, 0); if(size == GDI_ERROR) { LLOG("PdfDraw::Finish: GDI_ERROR on font " << pdffont.GetKey(i)); return Null; } StringBuffer fontbuffer(size); GetFontData(sd.GetHandle(), 0, 0, fontbuffer, size); #endif TTFReader ttf; if(!ttf.Open(fontbuffer)) return Null; String name = FormatIntAlpha(i + 1, true); name.Cat('A', 6 - name.GetLength()); name << '+' << ttf.ps_name; int fonti = PutStream(ttf.Subset(cs)); BeginObj(); int ascent = ttf.hhea.ascent * 1000 / ttf.head.unitsPerEm; int descent = ttf.hhea.descent * 1000 / ttf.head.unitsPerEm; out << "<< /Type /FontDescriptor\n" "/FontName /" << name << "\n" "/Flags 4\n" "/FontBBox [ -1000 " << descent << " 3000 " << ascent << " ]\n" //????? "/ItalicAngle " << ttf.post.italicAngle / 65536.0 << "\n" "/Ascent " << ascent << "\n" "/Descent " << -descent << "\n" "/CapHeight " << ttf.hhea.ascent * 1000 / ttf.head.unitsPerEm << "\n" "/StemV 80\n" "/FontFile2 " << fonti << " 0 R\n" << ">>\n"; EndObj(); fontobj.Add() = BeginObj(); out << "<< /Type /Font\n" "/Subtype /TrueType\n" "/BaseFont /" << name << "\n" "/FirstChar 0\n" "/LastChar " << cs.GetCount() - 1 << "\n" "/Widths [ "; for(int i = 0; i < cs.GetCount(); i++) out << ttf.GetAdvanceWidth(cs[i]) * 1000 / ttf.head.unitsPerEm << ' '; out << "]\n" "/FontDescriptor " << fonti + 1 << " 0 R\n" "/ToUnicode " << cmapi << " 0 R\n" << ">>\n"; EndObj(); } } int pages = BeginObj(); out << "<< /Type /Pages\n" << "/Kids ["; for(int i = 0; i < pagecount; i++) out << i + pages + 1 << " 0 R "; out << "]\n" << "/Count " << pagecount << "\n" << "/Resources << /ProcSet [ /PDF /Text /ImageB /ImageC ]\n"; if(pdffont.GetCount()) { out << "/Font << "; for(int i = 0; i < pdffont.GetCount(); i++) out << "/F" << i + 1 << ' ' << fontobj[i] << " 0 R "; out << ">>\n"; } if(!imageobj.IsEmpty()) { out << "/XObject << "; for(int i = 0; i < imageobj.GetCount(); i++) out << "/Image" << i + 1 << ' ' << imageobj[i] << " 0 R "; out << ">>\n"; } out << ">> >>\n"; EndObj(); for(int i = 0; i < pagecount; i++) { BeginObj(); out << "<< /Type /Page\n" << "/Parent " << pages << " 0 R\n" << "/MediaBox [0 0 " << Pt(pgsz.cx) << ' ' << Pt(pgsz.cy) << "]\n" << "/Contents " << i + 1 << " 0 R\n" << ">>\n"; EndObj(); } int outlines = BeginObj(); out << "<< /Type /Outlines\n" "/Count 0\n" ">>\n"; EndObj(); int catalog = BeginObj(); out << "<< /Type /Catalog\n" << "/Outlines " << outlines << " 0 R\n" << "/Pages " << pages << " 0 R\n" << ">>\n"; EndObj(); int startxref = out.GetCount(); out << "xref\n" << "0 " << offset.GetCount() + 1 << "\n"; out << "0000000000 65535 f\r\n"; for(int i = 0; i < offset.GetCount(); i++) out << Sprintf("%010d 00000 n\r\n", offset[i]); out << "\n" << "trailer\n" << "<< /Size " << offset.GetCount() + 1 << "\n" << "/Root " << catalog << " 0 R\n" << ">>\n" << "startxref\r\n" << startxref << "\r\n" << "%%EOF\r\n"; return out; } END_UPP_NAMESPACE
25.885017
109
0.546642
dreamsxin
4c0ca970261e746930efb887b363d742f6ed5d0b
42
hpp
C++
src/boost_mpl_map_aux__at_impl.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_mpl_map_aux__at_impl.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_mpl_map_aux__at_impl.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/mpl/map/aux_/at_impl.hpp>
21
41
0.761905
miathedev
4c0d35249900a138833faf652e5648fcf36d3b67
914
cpp
C++
runtime/layout-builtins.cpp
creativemindplus/skybison
d1740e08d8de85a0a56b650675717da67de171a0
[ "CNRI-Python-GPL-Compatible" ]
278
2021-08-31T00:46:51.000Z
2022-02-13T19:43:28.000Z
runtime/layout-builtins.cpp
creativemindplus/skybison
d1740e08d8de85a0a56b650675717da67de171a0
[ "CNRI-Python-GPL-Compatible" ]
9
2021-11-05T22:28:43.000Z
2021-11-23T08:39:04.000Z
runtime/layout-builtins.cpp
tekknolagi/skybison
bea8fc2af0a70e7203b4c19f36c14a745512a335
[ "CNRI-Python-GPL-Compatible" ]
12
2021-08-31T07:49:54.000Z
2021-10-08T01:09:01.000Z
// Copyright (c) Facebook, Inc. and its affiliates. (http://www.facebook.com) #include "layout-builtins.h" #include "builtins.h" #include "type-builtins.h" namespace py { static const BuiltinAttribute kLayoutAttributes[] = { {ID(_layout__described_type), RawLayout::kDescribedTypeOffset}, {ID(_layout__in_object_attributes), RawLayout::kInObjectAttributesOffset}, {ID(_layout__overflow_attributes), RawLayout::kOverflowAttributesOffset}, {ID(_layout__additions), RawLayout::kAdditionsOffset}, {ID(_layout__deletions), RawLayout::kDeletionsOffset}, {ID(_layout__num_in_object_attributes), RawLayout::kNumInObjectAttributesOffset}, }; void initializeLayoutType(Thread* thread) { addBuiltinType(thread, ID(layout), LayoutId::kLayout, /*superclass_id=*/LayoutId::kObject, kLayoutAttributes, Layout::kSize, /*basetype=*/false); } } // namespace py
35.153846
78
0.73523
creativemindplus
4c0f1384b6ce732404099c631cdd6015b8de3650
4,777
cpp
C++
src/stormcast/PrayersOfTheStormhosts.cpp
rweyrauch/AoSSimulator
d2bfbbe0fab904cc543f1a01e62e0b82cf67c27b
[ "MIT" ]
5
2019-02-01T01:41:19.000Z
2021-06-17T02:16:13.000Z
src/stormcast/PrayersOfTheStormhosts.cpp
rweyrauch/AoSSimulator
d2bfbbe0fab904cc543f1a01e62e0b82cf67c27b
[ "MIT" ]
2
2020-01-14T16:57:42.000Z
2021-04-01T00:53:18.000Z
src/stormcast/PrayersOfTheStormhosts.cpp
rweyrauch/AoSSimulator
d2bfbbe0fab904cc543f1a01e62e0b82cf67c27b
[ "MIT" ]
1
2019-03-02T20:03:51.000Z
2019-03-02T20:03:51.000Z
/* * Warhammer Age of Sigmar battle simulator. * * Copyright (C) 2019 by Rick Weyrauch - rpweyrauch@gmail.com * * This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT) */ #include <stormcast/PrayersOfTheStormhosts.h> #include "StormcastEternalsPrivate.h" namespace StormcastEternals { class DivineLight : public Prayer { public: explicit DivineLight(Unit *priest); protected: bool apply(int prayingRoll, Unit *target) override; bool apply(int prayingRoll, double x, double y) override { return false; } }; DivineLight::DivineLight(Unit *priest) : Prayer(priest, "Divine Light", 3, 18) { m_allowedTargets = Abilities::Target::Any; m_effect = Abilities::EffectType::Buff; } bool DivineLight::apply(int prayingRoll, Unit *target) { if (target == nullptr) return false; const Duration duration = {GamePhase::Hero, m_round + 1, m_priest->owningPlayer()}; if (m_priest->isFriendly(target)) { target->buffReroll(Attribute::Target_To_Hit_Melee, Rerolls::Sixes, duration); target->buffReroll(Attribute::Target_To_Hit_Missile, Rerolls::Sixes, duration); } else { target->buffReroll(Attribute::Target_To_Hit_Melee, Rerolls::Ones, duration); target->buffReroll(Attribute::Target_To_Hit_Missile, Rerolls::Ones, duration); } return true; } class BlessWeapons : public Prayer { public: explicit BlessWeapons(Unit *priest) : Prayer(priest, "Bless Weapons", 4, 18) { m_allowedTargets = Abilities::Target::SelfAndFriendly; m_effect = Abilities::EffectType::Buff; } protected: bool apply(int prayingRoll, Unit *target) override { if (target == nullptr) return false; const Duration duration = {GamePhase::Hero, m_round + 1, m_priest->owningPlayer()}; target->buffAbility(Ability::Extra_Hit_On_Value, 6, duration); return true; } bool apply(int prayingRoll, double x, double y) override { return false; } }; class BolsterFaith : public Prayer { public: explicit BolsterFaith(Unit *priest) : Prayer(priest, "Bolster Faith", 3, 9) { m_allowedTargets = Abilities::Target::Friendly; m_effect = Abilities::EffectType::Buff; } protected: bool apply(int prayingRoll, Unit *target) override { if (target == nullptr) return false; const Duration duration = {GamePhase::Hero, m_round + 1, m_priest->owningPlayer()}; target->buffAbility(Ability::Ignore_Battleshock, true, duration); return true; } bool apply(int prayingRoll, double x, double y) override { return false; } }; std::string ToString(PrayersOfTheStormhost which) { return std::string(magic_enum::enum_name(which)); } bool FromString(const std::string &enumString, PrayersOfTheStormhost &outPrayer) { auto prayer = magic_enum::enum_cast<PrayersOfTheStormhost>(enumString); if (prayer.has_value()) outPrayer = prayer.value(); return prayer.has_value(); } Prayer *CreateDivineLight(Unit *priest) { return new DivineLight(priest); } Prayer *CreateBlessWeapons(Unit *priest) { return new BlessWeapons(priest); } Prayer *CreateBolsterFaith(Unit *priest) { return new BolsterFaith(priest); } Prayer *CreateAbjuration(Unit *priest) { // TODO: Abjuration return nullptr; } Prayer *CreateGodKingsAspect(Unit *priest) { // TODO: God Kings Aspect return nullptr; } Prayer *CreateTranslocation(Unit *priest) { // TODO: Translocation return nullptr; } Prayer *CreatePrayerOfTheStormhost(PrayersOfTheStormhost which, Unit *priest) { switch (which) { case PrayersOfTheStormhost::Divine_Light: return CreateDivineLight(priest); case PrayersOfTheStormhost::Bless_Weapons: return CreateBlessWeapons(priest); case PrayersOfTheStormhost::Bolster_Faith: return CreateBolsterFaith(priest); case PrayersOfTheStormhost::Abjuration: return CreateAbjuration(priest); case PrayersOfTheStormhost::God_Kings_Aspect: return CreateGodKingsAspect(priest); case PrayersOfTheStormhost::Translocation: return CreateTranslocation(priest); default: return nullptr; } } } //namespace StormcastEternals
31.846667
95
0.624241
rweyrauch
4c0f49126be8045054e8bbb5fbc2b341af61d729
13,082
cpp
C++
VST3 SDK/vstgui4/vstgui/lib/controls/csegmentbutton.cpp
jagilley/MrsWatson
dd00b6a3740cce4bf7c10d3342d4742c7d1b4836
[ "BSD-2-Clause" ]
2
2019-06-14T10:20:30.000Z
2020-02-19T17:53:42.000Z
VST3 SDK/vstgui4/vstgui/lib/controls/csegmentbutton.cpp
jagilley/MrsWatson
dd00b6a3740cce4bf7c10d3342d4742c7d1b4836
[ "BSD-2-Clause" ]
null
null
null
VST3 SDK/vstgui4/vstgui/lib/controls/csegmentbutton.cpp
jagilley/MrsWatson
dd00b6a3740cce4bf7c10d3342d4742c7d1b4836
[ "BSD-2-Clause" ]
1
2021-03-16T13:02:17.000Z
2021-03-16T13:02:17.000Z
//----------------------------------------------------------------------------- // VST Plug-Ins SDK // VSTGUI: Graphical User Interface Framework not only for VST plugins // // Version 4.3 // //----------------------------------------------------------------------------- // VSTGUI LICENSE // (c) 2015, Steinberg Media Technologies, All Rights Reserved //----------------------------------------------------------------------------- // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * 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. // * Neither the name of the Steinberg Media Technologies nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // 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 "csegmentbutton.h" #include "../cdrawcontext.h" #include "../cframe.h" #include "../cgraphicspath.h" #include <algorithm> namespace VSTGUI { typedef std::numeric_limits<uint32_t> UInt32Limit; uint32_t CSegmentButton::kPushBack = UInt32Limit::max (); //----------------------------------------------------------------------------- CSegmentButton::CSegmentButton (const CRect& size, IControlListener* listener, int32_t tag) : CControl (size, listener, tag) , textColor (kBlackCColor) , textColorHighlighted (kWhiteCColor) , frameColor (kBlackCColor) , textAlignment (kCenterText) , textMargin (0) , font (kNormalFont) , roundRadius (5) , frameWidth (1) , style (kHorizontal) , textTruncateMode (CDrawMethods::kTextTruncateNone) { setWantsFocus (true); } //----------------------------------------------------------------------------- void CSegmentButton::addSegment (Segment segment, uint32_t index) { if (index == kPushBack && segments.size () < kPushBack) segments.push_back (segment); else if (index < segments.size ()) { Segments::iterator it = segments.begin (); std::advance (it, index); segments.insert (it, segment); } updateSegmentSizes (); } //----------------------------------------------------------------------------- void CSegmentButton::removeSegment (uint32_t index) { if (index < segments.size ()) { Segments::iterator it = segments.begin (); std::advance (it, index); segments.erase (it); } updateSegmentSizes (); } //----------------------------------------------------------------------------- void CSegmentButton::removeAllSegments () { segments.clear (); invalid (); } //----------------------------------------------------------------------------- void CSegmentButton::setSelectedSegment (uint32_t index) { setValueNormalized (static_cast<float> (index) / static_cast<float> (segments.size () - 1)); invalid (); } //----------------------------------------------------------------------------- uint32_t CSegmentButton::getSelectedSegment () const { return getSegmentIndex (getValueNormalized ()); } //----------------------------------------------------------------------------- void CSegmentButton::setStyle (Style newStyle) { if (style != newStyle) { style = newStyle; updateSegmentSizes (); invalid (); } } //----------------------------------------------------------------------------- void CSegmentButton::setTextTruncateMode (CDrawMethods::TextTruncateMode mode) { if (textTruncateMode != mode) { textTruncateMode = mode; invalid (); } } //----------------------------------------------------------------------------- void CSegmentButton::setGradient (CGradient* newGradient) { if (gradient != newGradient) { gradient = newGradient; invalid (); } } //----------------------------------------------------------------------------- void CSegmentButton::setGradientHighlighted (CGradient* newGradient) { if (gradientHighlighted != newGradient) { gradientHighlighted = newGradient; invalid (); } } //----------------------------------------------------------------------------- void CSegmentButton::setRoundRadius (CCoord newRoundRadius) { if (roundRadius != newRoundRadius) { roundRadius = newRoundRadius; invalid (); } } //----------------------------------------------------------------------------- void CSegmentButton::setFont (CFontRef newFont) { if (font != newFont) { font = newFont; invalid (); } } //----------------------------------------------------------------------------- void CSegmentButton::setTextAlignment (CHoriTxtAlign newAlignment) { if (textAlignment != newAlignment) { textAlignment = newAlignment; invalid (); } } //----------------------------------------------------------------------------- void CSegmentButton::setTextMargin (CCoord newMargin) { if (textMargin != newMargin) { textMargin = newMargin; invalid (); } } //----------------------------------------------------------------------------- void CSegmentButton::setTextColor (CColor newColor) { if (textColor != newColor) { textColor = newColor; invalid (); } } //----------------------------------------------------------------------------- void CSegmentButton::setTextColorHighlighted (CColor newColor) { if (textColorHighlighted != newColor) { textColorHighlighted = newColor; invalid (); } } //----------------------------------------------------------------------------- void CSegmentButton::setFrameColor (CColor newColor) { if (frameColor != newColor) { frameColor = newColor; invalid (); } } //----------------------------------------------------------------------------- void CSegmentButton::setFrameWidth (CCoord newWidth) { if (frameWidth != newWidth) { frameWidth = newWidth; invalid (); } } //----------------------------------------------------------------------------- bool CSegmentButton::attached (CView *parent) { if (CControl::attached (parent)) { updateSegmentSizes (); return true; } return false; } //----------------------------------------------------------------------------- void CSegmentButton::setViewSize (const CRect& rect, bool invalid) { CControl::setViewSize (rect, invalid); updateSegmentSizes (); } //----------------------------------------------------------------------------- CMouseEventResult CSegmentButton::onMouseDown (CPoint& where, const CButtonState& buttons) { if (buttons.isLeftButton ()) { float newValue = 0; float valueOffset = 1.f / (segments.size () - 1); uint32_t currentIndex = getSegmentIndex (getValueNormalized ()); for (Segments::const_iterator it = segments.begin (), end = segments.end (); it != end; ++it, newValue += valueOffset) { if ((*it).rect.pointInside (where)) { uint32_t newIndex = getSegmentIndex (newValue); if (newIndex != currentIndex) { beginEdit (); setSelectedSegment (newIndex); valueChanged (); endEdit (); invalid (); } break; } } } return kMouseDownEventHandledButDontNeedMovedOrUpEvents; } //----------------------------------------------------------------------------- int32_t CSegmentButton::onKeyDown (VstKeyCode& keyCode) { int32_t result = -1; if (keyCode.modifier == 0 && keyCode.character == 0) { uint32_t newIndex = getSegmentIndex (getValueNormalized ()); uint32_t oldIndex = newIndex; switch (keyCode.virt) { case VKEY_LEFT: { if (style == kHorizontal && newIndex > 0) newIndex--; result = 1; break; } case VKEY_RIGHT: { if (style == kHorizontal && newIndex < segments.size () - 1) newIndex++; result = 1; break; } case VKEY_UP: { if (style == kVertical && newIndex > 0) newIndex--; result = 1; break; } case VKEY_DOWN: { if (style == kVertical && newIndex < segments.size () - 1) newIndex++; result = 1; break; } } if (newIndex != oldIndex) { beginEdit (); setSelectedSegment (newIndex); valueChanged (); endEdit (); invalid (); } } return result; } //----------------------------------------------------------------------------- void CSegmentButton::draw (CDrawContext* pContext) { CView::draw (pContext); } //----------------------------------------------------------------------------- void CSegmentButton::drawRect (CDrawContext* pContext, const CRect& dirtyRect) { bool isHorizontal = style == kHorizontal; SharedPointer<CGraphicsPath> path; if (gradient || gradientHighlighted || (getFrameWidth () > 0. && getFrameColor ().alpha != 0)) { CRect r (getViewSize ()); r.inset (getFrameWidth () / 2., getFrameWidth () / 2.); path = owned (pContext->createGraphicsPath ()); path->addRoundRect (r, getRoundRadius ()); } pContext->setDrawMode (kAntiAliasing); bool drawLines = getFrameWidth () > 0. && getFrameColor ().alpha != 0; if (drawLines) { pContext->setLineStyle (kLineSolid); pContext->setLineWidth (getFrameWidth ()); pContext->setFrameColor (getFrameColor ()); } if (gradient) { pContext->fillLinearGradient (path, *gradient, getViewSize ().getTopLeft (), getViewSize ().getBottomLeft ()); } uint32_t selectedIndex = getSelectedSegment (); for (uint32_t index = 0; index < segments.size (); ++index) { Segment& segment = segments[index]; if (!dirtyRect.rectOverlap (segment.rect)) continue; CRect oldClip; pContext->getClipRect (oldClip); CRect clipRect (segment.rect); clipRect.bound (oldClip); pContext->setClipRect (clipRect); bool selected = selectedIndex == index; if (selected && gradientHighlighted) pContext->fillLinearGradient (path, *gradientHighlighted, segment.rect.getTopLeft (), segment.rect.getBottomLeft ()); if (selected && segment.backgroundHighlighted) segment.backgroundHighlighted->draw (pContext, segment.rect); else if (segment.background) segment.background->draw (pContext, segment.rect); CDrawMethods::drawIconAndText (pContext, selected ? segment.iconHighlighted : segment.icon, segment.iconPosition, textAlignment, textMargin, segment.rect, segment.name, font, selected ? textColorHighlighted : textColor, textTruncateMode); pContext->setClipRect (oldClip); if (drawLines && index > 0 && index < segments.size ()) { path->beginSubpath (segment.rect.getTopLeft ()); path->addLine (isHorizontal ? segment.rect.getBottomLeft () : segment.rect.getTopRight ()); } } if (drawLines) pContext->drawGraphicsPath (path, CDrawContext::kPathStroked); setDirty (false); } //----------------------------------------------------------------------------- uint32_t CSegmentButton::getSegmentIndex (float value) const { if (value < 0.f || value > 1.f) return kPushBack; return static_cast<uint32_t> (static_cast<float> (segments.size () - 1) * value); } //----------------------------------------------------------------------------- void CSegmentButton::updateSegmentSizes () { if (isAttached () && !segments.empty ()) { if (style == kHorizontal) { CCoord width = getWidth () / segments.size (); CRect r (getViewSize ()); r.setWidth (width); for (Segments::iterator it = segments.begin (), end = segments.end (); it != end; ++it) { (*it).rect = r; r.offset (width, 0); } } else { CCoord height = getHeight () / segments.size (); CRect r (getViewSize ()); r.setHeight (height); for (Segments::iterator it = segments.begin (), end = segments.end (); it != end; ++it) { (*it).rect = r; r.offset (0, height); } } } } //----------------------------------------------------------------------------- bool CSegmentButton::drawFocusOnTop () { return false; } //----------------------------------------------------------------------------- bool CSegmentButton::getFocusPath (CGraphicsPath& outPath) { CRect r (getViewSize ()); r.inset (getFrameWidth () / 2., getFrameWidth () / 2.); outPath.addRoundRect (r, getRoundRadius ()); CCoord focusWidth = getFrame ()->getFocusWidth (); r.extend (focusWidth, focusWidth); outPath.addRoundRect (r, getRoundRadius ()); return true; } } // namespace
29.397753
240
0.561764
jagilley
4c167a98f982f4c381e95bf4a1ecf121b323b20c
26,089
cpp
C++
build/source/rotatelogsw.cpp
g-stefan/vendor-httpd
14c434fc0932dd888a620442016c7a52cfe34e14
[ "MIT", "Apache-2.0", "Unlicense" ]
null
null
null
build/source/rotatelogsw.cpp
g-stefan/vendor-httpd
14c434fc0932dd888a620442016c7a52cfe34e14
[ "MIT", "Apache-2.0", "Unlicense" ]
null
null
null
build/source/rotatelogsw.cpp
g-stefan/vendor-httpd
14c434fc0932dd888a620442016c7a52cfe34e14
[ "MIT", "Apache-2.0", "Unlicense" ]
null
null
null
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr.h" #include "apr_lib.h" #include "apr_strings.h" #include "apr_errno.h" #include "apr_file_io.h" #include "apr_file_info.h" #include "apr_general.h" #include "apr_time.h" #include "apr_getopt.h" #include "apr_thread_proc.h" #include "apr_signal.h" #if APR_FILES_AS_SOCKETS #include "apr_poll.h" #endif #if APR_HAVE_STDLIB_H #include <stdlib.h> #endif #define APR_WANT_STRFUNC #include "apr_want.h" #define BUFSIZE 65536 #define ROTATE_NONE 0 #define ROTATE_NEW 1 #define ROTATE_TIME 2 #define ROTATE_SIZE 3 #define ROTATE_FORCE 4 static const char *const ROTATE_REASONS[] = { "None", "Open a new file", "Time interval expired", "Maximum size reached", "Forced rotation", NULL }; typedef struct rotate_config rotate_config_t; struct rotate_config { unsigned int sRotation; int tRotation; int utc_offset; int use_localtime; int use_strftime; int force_open; int verbose; int echo; char *szLogRoot; int truncate; const char *linkfile; const char *postrotate_prog; #if APR_FILES_AS_SOCKETS int create_empty; #endif int num_files; int create_path; }; typedef struct rotate_status rotate_status_t; /* "adjusted_time_t" is used to store Unix time (seconds since epoch) * which has been adjusted for some timezone fudge factor. It should * be used for storing the return values from get_now(). A typedef is * used since this type is similar to time_t, but different. */ typedef long adjusted_time_t; /* Structure to contain relevant logfile state: fd, pool and * filename. */ struct logfile { apr_pool_t *pool; apr_file_t *fd; char name[APR_PATH_MAX]; }; struct rotate_status { struct logfile current; /* current logfile. */ apr_pool_t *pool; /* top-level pool */ int rotateReason; adjusted_time_t tLogEnd; int nMessCount; int fileNum; }; static rotate_config_t config; static rotate_status_t status; static void usage(const char *argv0, const char *reason) { if (reason) { fprintf(stderr, "%s\n", reason); } fprintf(stderr, #if APR_FILES_AS_SOCKETS "Usage: %s [-v] [-l] [-L linkname] [-p prog] [-f] [-D] [-t] [-e] [-c] [-n number] <logfile> " #else "Usage: %s [-v] [-l] [-L linkname] [-p prog] [-f] [-D] [-t] [-e] [-n number] <logfile> " #endif "{<rotation time in seconds>|<rotation size>(B|K|M|G)} " "[offset minutes from UTC]\n\n", argv0); #ifdef OS2 fprintf(stderr, "Add this:\n\nTransferLog \"|%s.exe /some/where 86400\"\n\n", argv0); #else fprintf(stderr, "Add this:\n\nTransferLog \"|%s /some/where 86400\"\n\n", argv0); fprintf(stderr, "or \n\nTransferLog \"|%s /some/where 5M\"\n\n", argv0); #endif fprintf(stderr, "to httpd.conf. By default, the generated name will be\n" "<logfile>.nnnn where nnnn is the system time at which the log\n" "nominally starts (N.B. if using a rotation time, the time will\n" "always be a multiple of the rotation time, so you can synchronize\n" "cron scripts with it). If <logfile> contains strftime conversion\n" "specifications, those will be used instead. At the end of each\n" "rotation time or when the file size is reached a new log is\n" "started.\n" "\n" "Options:\n" " -v Verbose operation. Messages are written to stderr.\n" " -l Base rotation on local time instead of UTC.\n" " -L path Create hard link from current log to specified path.\n" " -p prog Run specified program after opening a new log file. See below.\n" " -f Force opening of log on program start.\n" " -D Create parent directories of log file.\n" " -t Truncate logfile instead of rotating, tail friendly.\n" " -e Echo log to stdout for further processing.\n" #if APR_FILES_AS_SOCKETS " -c Create log even if it is empty.\n" #endif " -n num Rotate file by adding suffixes '.1', '.2', ..., '.num'.\n" "\n" "The program for '-p' is invoked as \"[prog] <curfile> [<prevfile>]\"\n" "where <curfile> is the filename of the newly opened logfile, and\n" "<prevfile>, if given, is the filename of the previously used logfile.\n" "\n"); exit(1); } /* This function returns the current Unix time (time_t) adjusted for * any configured or derived local time offset. The offset applied is * returned via *offset. */ static adjusted_time_t get_now(rotate_config_t *config, apr_int32_t *offset) { apr_time_t tNow = apr_time_now(); apr_int32_t utc_offset; if (config->use_localtime) { /* Check for our UTC offset before using it, since it might * change if there's a switch between standard and daylight * savings time. */ apr_time_exp_t lt; apr_time_exp_lt(&lt, tNow); utc_offset = lt.tm_gmtoff; } else { utc_offset = config->utc_offset; } if (offset) *offset = utc_offset; return apr_time_sec(tNow) + utc_offset; } /* * Close a file and destroy the associated pool. */ static void close_logfile(rotate_config_t *config, struct logfile *logfile) { if (config->verbose) { fprintf(stderr, "Closing file %s\n", logfile->name); } apr_file_close(logfile->fd); apr_pool_destroy(logfile->pool); } /* * Dump the configuration parsing result to STDERR. */ static void dumpConfig (rotate_config_t *config) { fprintf(stderr, "Rotation time interval: %12d\n", config->tRotation); fprintf(stderr, "Rotation size interval: %12d\n", config->sRotation); fprintf(stderr, "Rotation time UTC offset: %12d\n", config->utc_offset); fprintf(stderr, "Rotation based on localtime: %12s\n", config->use_localtime ? "yes" : "no"); fprintf(stderr, "Rotation file date pattern: %12s\n", config->use_strftime ? "yes" : "no"); fprintf(stderr, "Rotation file forced open: %12s\n", config->force_open ? "yes" : "no"); fprintf(stderr, "Create parent directories: %12s\n", config->create_path ? "yes" : "no"); fprintf(stderr, "Rotation verbose: %12s\n", config->verbose ? "yes" : "no"); #if APR_FILES_AS_SOCKETS fprintf(stderr, "Rotation create empty logs: %12s\n", config->create_empty ? "yes" : "no"); #endif fprintf(stderr, "Rotation file name: %21s\n", config->szLogRoot); fprintf(stderr, "Post-rotation prog: %21s\n", config->postrotate_prog ? config->postrotate_prog : "not used"); } /* * Check whether we need to rotate. * Possible reasons are: * - No log file open (ROTATE_NEW) * - User forces us to rotate (ROTATE_FORCE) * - Our log file size is already bigger than the * allowed maximum (ROTATE_SIZE) * - The next log time interval expired (ROTATE_TIME) * * When size and time constraints are both given, * it suffices that one of them is fulfilled. */ static void checkRotate(rotate_config_t *config, rotate_status_t *status) { if (status->current.fd == NULL) { status->rotateReason = ROTATE_NEW; } else if (config->sRotation) { apr_finfo_t finfo; apr_off_t current_size = -1; if (apr_file_info_get(&finfo, APR_FINFO_SIZE, status->current.fd) == APR_SUCCESS) { current_size = finfo.size; } if (current_size > config->sRotation) { status->rotateReason = ROTATE_SIZE; } else if (config->tRotation) { if (get_now(config, NULL) >= status->tLogEnd) { status->rotateReason = ROTATE_TIME; } } } else if (config->tRotation) { if (get_now(config, NULL) >= status->tLogEnd) { status->rotateReason = ROTATE_TIME; } } else { fprintf(stderr, "No rotation time or size specified\n"); exit(2); } if (status->rotateReason != ROTATE_NONE && config->verbose) { fprintf(stderr, "File rotation needed, reason: %s\n", ROTATE_REASONS[status->rotateReason]); } } /* * Handle post-rotate processing. */ static void post_rotate(apr_pool_t *pool, struct logfile *newlog, rotate_config_t *config, rotate_status_t *status) { apr_status_t rv; char error[120]; apr_procattr_t *pattr; const char *argv[4]; apr_proc_t proc; /* Handle link file, if configured. */ if (config->linkfile) { apr_file_remove(config->linkfile, newlog->pool); if (config->verbose) { fprintf(stderr, "Linking %s to %s\n", newlog->name, config->linkfile); } rv = apr_file_link(newlog->name, config->linkfile); if (rv != APR_SUCCESS) { apr_strerror(rv, error, sizeof error); fprintf(stderr, "Error linking file %s to %s (%s)\n", newlog->name, config->linkfile, error); exit(2); } } if (!config->postrotate_prog) { /* Nothing more to do. */ return; } /* Collect any zombies from a previous run, but don't wait. */ while (apr_proc_wait_all_procs(&proc, NULL, NULL, APR_NOWAIT, pool) == APR_CHILD_DONE) /* noop */; if ((rv = apr_procattr_create(&pattr, pool)) != APR_SUCCESS) { fprintf(stderr, "post_rotate: apr_procattr_create failed for '%s': %s\n", config->postrotate_prog, apr_strerror(rv, error, sizeof(error))); return; } rv = apr_procattr_error_check_set(pattr, 1); if (rv == APR_SUCCESS) rv = apr_procattr_cmdtype_set(pattr, APR_PROGRAM_ENV); if (rv != APR_SUCCESS) { fprintf(stderr, "post_rotate: could not set up process attributes for '%s': %s\n", config->postrotate_prog, apr_strerror(rv, error, sizeof(error))); return; } argv[0] = config->postrotate_prog; argv[1] = newlog->name; if (status->current.fd) { argv[2] = status->current.name; argv[3] = NULL; } else { argv[2] = NULL; } if (config->verbose) fprintf(stderr, "Calling post-rotate program: %s\n", argv[0]); rv = apr_proc_create(&proc, argv[0], argv, NULL, pattr, pool); if (rv != APR_SUCCESS) { fprintf(stderr, "Could not spawn post-rotate process '%s': %s\n", config->postrotate_prog, apr_strerror(rv, error, sizeof(error))); return; } } /* After a error, truncate the current file and write out an error * message, which must be contained in message. The process is * terminated on failure. */ static void truncate_and_write_error(rotate_status_t *status, const char *message) { apr_size_t buflen = strlen(message); if (apr_file_trunc(status->current.fd, 0) != APR_SUCCESS) { fprintf(stderr, "Error truncating the file %s\n", status->current.name); exit(2); } if (apr_file_write_full(status->current.fd, message, buflen, NULL) != APR_SUCCESS) { fprintf(stderr, "Error writing error (%s) to the file %s\n", message, status->current.name); exit(2); } } /* * Open a new log file, and if successful * also close the old one. * * The timestamp for the calculation of the file * name of the new log file will be the actual millisecond * timestamp, except when a regular rotation based on a time * interval is configured and the previous interval * is over. Then the timestamp is the starting time * of the actual interval. */ static void doRotate(rotate_config_t *config, rotate_status_t *status) { apr_int32_t offset; adjusted_time_t now, tLogStart; apr_status_t rv; struct logfile newlog; int thisLogNum = -1; /* Retrieve local-time-adjusted-Unix-time. */ now = get_now(config, &offset); status->rotateReason = ROTATE_NONE; if (config->tRotation) { adjusted_time_t tLogEnd; tLogStart = (now / config->tRotation) * config->tRotation; tLogEnd = tLogStart + config->tRotation; /* * Check if rotation was forced and the last rotation * interval is not yet over. Use the value of now instead * of the time interval boundary for the file name then. */ if (tLogStart < status->tLogEnd) { tLogStart = now; } status->tLogEnd = tLogEnd; } else { tLogStart = now; } if (config->use_strftime) { apr_time_t tNow = apr_time_from_sec(tLogStart); apr_time_exp_t e; apr_size_t rs; /* Explode the local-time-adjusted-Unix-time into a struct tm, * first *reversing* local-time-adjustment applied by * get_now() if we are using localtime. */ if (config->use_localtime) apr_time_exp_lt(&e, tNow - apr_time_from_sec(offset)); else apr_time_exp_gmt(&e, tNow); apr_strftime(newlog.name, &rs, sizeof(newlog.name), config->szLogRoot, &e); } else { if (config->truncate) { apr_snprintf(newlog.name, sizeof(newlog.name), "%s", config->szLogRoot); } else if (config->num_files > 0) { if (status->fileNum == -1 || status->fileNum == (config->num_files - 1)) { thisLogNum = 0; apr_snprintf(newlog.name, sizeof(newlog.name), "%s", config->szLogRoot); } else { thisLogNum = status->fileNum + 1; apr_snprintf(newlog.name, sizeof(newlog.name), "%s.%d", config->szLogRoot, thisLogNum); } } else { apr_snprintf(newlog.name, sizeof(newlog.name), "%s.%010ld", config->szLogRoot, tLogStart); } } apr_pool_create(&newlog.pool, status->pool); if (config->create_path) { char *ptr = strrchr(newlog.name, '/'); if (ptr && ptr > newlog.name) { char *path = apr_pstrmemdup(newlog.pool, newlog.name, ptr - newlog.name); if (config->verbose) { fprintf(stderr, "Creating directory tree %s\n", path); } rv = apr_dir_make_recursive(path, APR_FPROT_OS_DEFAULT, newlog.pool); if (rv != APR_SUCCESS) { char error[120]; apr_strerror(rv, error, sizeof error); fprintf(stderr, "Could not create directory '%s' (%s)\n", path, error); exit(2); } } } if (config->verbose) { fprintf(stderr, "Opening file %s\n", newlog.name); } rv = apr_file_open(&newlog.fd, newlog.name, APR_WRITE | APR_CREATE | APR_APPEND | (config->truncate || (config->num_files > 0 && status->current.fd) ? APR_TRUNCATE : 0), APR_OS_DEFAULT, newlog.pool); if (rv == APR_SUCCESS) { /* Handle post-rotate processing. */ post_rotate(newlog.pool, &newlog, config, status); status->fileNum = thisLogNum; /* Close out old (previously 'current') logfile, if any. */ if (status->current.fd) { close_logfile(config, &status->current); } /* New log file is now 'current'. */ status->current = newlog; } else { char *error = apr_psprintf(newlog.pool, "%pm", &rv); char *message; /* Uh-oh. Failed to open the new log file. Try to clear * the previous log file, note the lost log entries, * and keep on truckin'. */ if (status->current.fd == NULL) { fprintf(stderr, "Could not open log file '%s' (%s)\n", newlog.name, error); exit(2); } /* Try to keep this error message constant length * in case it occurs several times. */ message = apr_psprintf(newlog.pool, "Resetting log file due to error opening " "new log file, %10d messages lost: %-25.25s\n", status->nMessCount, error); truncate_and_write_error(status, message); /* Throw away new state; it isn't going to be used. */ apr_pool_destroy(newlog.pool); } status->nMessCount = 0; } /* * Get a size or time param from a string. * Parameter 'last' indicates, whether the * argument is the last commadnline argument. * UTC offset is only allowed as a last argument * in order to make is distinguishable from the * rotation interval time. */ static const char *get_time_or_size(rotate_config_t *config, const char *arg, int last) { const char *ptr = NULL; /* Byte multiplier */ unsigned int mult = 1; if ((ptr = strchr(arg, 'B')) != NULL) { /* Found KB size */ mult = 1; } else if ((ptr = strchr(arg, 'K')) != NULL) { /* Found KB size */ mult = 1024; } else if ((ptr = strchr(arg, 'M')) != NULL) { /* Found MB size */ mult = 1024 * 1024; } else if ((ptr = strchr(arg, 'G')) != NULL) { /* Found GB size */ mult = 1024 * 1024 * 1024; } if (ptr) { /* rotation based on file size */ if (config->sRotation > 0) { return "Rotation size parameter allowed only once"; } if (*(ptr+1) == '\0') { config->sRotation = atoi(arg) * mult; } if (config->sRotation == 0) { return "Invalid rotation size parameter"; } } else if ((config->sRotation > 0 || config->tRotation > 0) && last) { /* rotation based on elapsed time */ if (config->use_localtime) { return "UTC offset parameter is not valid with -l"; } config->utc_offset = atoi(arg) * 60; } else { /* rotation based on elapsed time */ if (config->tRotation > 0) { return "Rotation time parameter allowed only once"; } config->tRotation = atoi(arg); if (config->tRotation <= 0) { return "Invalid rotation time parameter"; } } return NULL; } // // 2019.07.03 - modified by Grigore Stefan <g_stefan@yahoo.com> // int applicationMain (int argc, const char * const argv[]) { char buf[BUFSIZE]; apr_size_t nRead, nWrite; apr_file_t *f_stdin; apr_file_t *f_stdout; apr_getopt_t *opt; apr_status_t rv; char c; const char *opt_arg; const char *err = NULL; #if APR_FILES_AS_SOCKETS apr_pollfd_t pollfd = { 0 }; apr_status_t pollret = APR_SUCCESS; long polltimeout; #endif apr_app_initialize(&argc, &argv, NULL); atexit(apr_terminate); memset(&config, 0, sizeof config); memset(&status, 0, sizeof status); status.rotateReason = ROTATE_NONE; apr_pool_create(&status.pool, NULL); apr_getopt_init(&opt, status.pool, argc, argv); #if APR_FILES_AS_SOCKETS while ((rv = apr_getopt(opt, "lL:p:fDtvecn:", &c, &opt_arg)) == APR_SUCCESS) { #else while ((rv = apr_getopt(opt, "lL:p:fDtven:", &c, &opt_arg)) == APR_SUCCESS) { #endif switch (c) { case 'l': config.use_localtime = 1; break; case 'L': config.linkfile = opt_arg; break; case 'p': config.postrotate_prog = opt_arg; #ifdef SIGCHLD /* Prevent creation of zombies (on modern Unix systems). */ apr_signal(SIGCHLD, SIG_IGN); #endif break; case 'f': config.force_open = 1; break; case 'D': config.create_path = 1; break; case 't': config.truncate = 1; break; case 'v': config.verbose = 1; break; case 'e': config.echo = 1; break; #if APR_FILES_AS_SOCKETS case 'c': config.create_empty = 1; break; #endif case 'n': config.num_files = atoi(opt_arg); status.fileNum = -1; break; } } if (rv != APR_EOF) { usage(argv[0], NULL /* specific error message already issued */ ); } /* * After the initial flags we need 2 to 4 arguments, * the file name, either the rotation interval time or size * or both of them, and optionally the UTC offset. */ if ((argc - opt->ind < 2) || (argc - opt->ind > 4) ) { usage(argv[0], "Incorrect number of arguments"); } rv = apr_filepath_merge(&config.szLogRoot, "", argv[opt->ind++], APR_FILEPATH_TRUENAME, status.pool); if (rv != APR_SUCCESS && rv != APR_EPATHWILD) { usage(argv[0], "Invalid filename given"); } /* Read in the remaining flags, namely time, size and UTC offset. */ for(; opt->ind < argc; opt->ind++) { if ((err = get_time_or_size(&config, argv[opt->ind], opt->ind < argc - 1 ? 0 : 1)) != NULL) { usage(argv[0], err); } } config.use_strftime = (strchr(config.szLogRoot, '%') != NULL); if (config.use_strftime && config.num_files > 0) { fprintf(stderr, "Cannot use -n with %% in filename\n"); exit(1); } if (status.fileNum == -1 && config.num_files < 1) { fprintf(stderr, "Invalid -n argument\n"); exit(1); } if (apr_file_open_stdin(&f_stdin, status.pool) != APR_SUCCESS) { fprintf(stderr, "Unable to open stdin\n"); exit(1); } if (apr_file_open_stdout(&f_stdout, status.pool) != APR_SUCCESS) { fprintf(stderr, "Unable to open stdout\n"); exit(1); } /* * Write out result of config parsing if verbose is set. */ if (config.verbose) { dumpConfig(&config); } #if APR_FILES_AS_SOCKETS if (config.create_empty && config.tRotation) { pollfd.p = status.pool; pollfd.desc_type = APR_POLL_FILE; pollfd.reqevents = APR_POLLIN; pollfd.desc.f = f_stdin; } #endif /* * Immediately open the logfile as we start, if we were forced * to do so via '-f'. */ if (config.force_open) { doRotate(&config, &status); } for (;;) { nRead = sizeof(buf); #if APR_FILES_AS_SOCKETS if (config.create_empty && config.tRotation) { polltimeout = status.tLogEnd ? status.tLogEnd - get_now(&config, NULL) : config.tRotation; if (polltimeout <= 0) { pollret = APR_TIMEUP; } else { pollret = apr_poll(&pollfd, 1, &pollret, apr_time_from_sec(polltimeout)); } } if (pollret == APR_SUCCESS) { rv = apr_file_read(f_stdin, buf, &nRead); if (APR_STATUS_IS_EOF(rv)) { break; } else if (rv != APR_SUCCESS) { exit(3); } } else if (pollret == APR_TIMEUP) { *buf = 0; nRead = 0; } else { fprintf(stderr, "Unable to poll stdin\n"); exit(5); } #else /* APR_FILES_AS_SOCKETS */ rv = apr_file_read(f_stdin, buf, &nRead); if (APR_STATUS_IS_EOF(rv)) { break; } else if (rv != APR_SUCCESS) { exit(3); } #endif /* APR_FILES_AS_SOCKETS */ checkRotate(&config, &status); if (status.rotateReason != ROTATE_NONE) { doRotate(&config, &status); } nWrite = nRead; rv = apr_file_write_full(status.current.fd, buf, nWrite, &nWrite); if (nWrite != nRead) { apr_off_t cur_offset; apr_pool_t *pool; char *error; cur_offset = 0; if (apr_file_seek(status.current.fd, APR_CUR, &cur_offset) != APR_SUCCESS) { cur_offset = -1; } status.nMessCount++; apr_pool_create(&pool, status.pool); error = apr_psprintf(pool, "Error %d writing to log file at offset %" APR_OFF_T_FMT ". %10d messages lost (%pm)\n", rv, cur_offset, status.nMessCount, &rv); truncate_and_write_error(&status, error); apr_pool_destroy(pool); } else { status.nMessCount++; } if (config.echo) { if (apr_file_write_full(f_stdout, buf, nRead, &nWrite)) { fprintf(stderr, "Unable to write to stdout\n"); exit(4); } } } return 0; /* reached only at stdin EOF. */ } // // 2019.07.03 - modified by Grigore Stefan <g_stefan@yahoo.com> // - suport subsytem windows [no console window] // #include "xyo.hpp" int __stdcall WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR cmdLine,int cmdShow) { char exeName[MAX_PATH]; int cmdN; char** cmdS; int retV; GetModuleFileName(nullptr,exeName,MAX_PATH); XYO::Shell::mainArgsSet(exeName,GetCommandLineA(),cmdN,cmdS); retV=applicationMain(cmdN,cmdS); XYO::Shell::mainArgsDelete(cmdN,cmdS); return retV; }
32.288366
114
0.584423
g-stefan
4c1714d40ec701830907793939149d0f492a9e12
6,015
cpp
C++
arm9/source/level.cpp
RocketRobz/Konotsu-Gunner-DS
7e8f3d6594c4a02ab431662008f10614a3b6987e
[ "MIT" ]
1
2020-02-26T14:39:43.000Z
2020-02-26T14:39:43.000Z
arm9/source/level.cpp
RocketRobz/Konotsu-Gunner-DS
7e8f3d6594c4a02ab431662008f10614a3b6987e
[ "MIT" ]
null
null
null
arm9/source/level.cpp
RocketRobz/Konotsu-Gunner-DS
7e8f3d6594c4a02ab431662008f10614a3b6987e
[ "MIT" ]
1
2020-03-04T18:44:02.000Z
2020-03-04T18:44:02.000Z
#include <nds.h> #include "gl2d.h" #include "graphics/fontHandler.h" #include "graphics/graphics.h" #include "tonccpy.h" #include "sound.h" #include "player.h" #include "bottomImage.h" #include "spr_aimbutton.h" #include "tiles.h" #include "tilenum.h" #define bgTile 11 #define grayBlockTile 17 extern bool wideScreen; extern bool fadeType; static bool inited = false; int mapHsize = 32; int mapVsize = 24; int cameraXpos = 0; int cameraYpos = 0; u8 mapData[32*27] = {7}; extern int playerX[2], playerY[2]; static int tileTexID; glImage tileImage[(128 / 16) * (128 / 16)]; void levelGraphicLoad(void) { tileTexID = glLoadTileSet(tileImage, // pointer to glImage array 16, // sprite width 16, // sprite height 128, // bitmap width 128, // bitmap height GL_RGB256, // texture type for glTexImage2D() in videoGL.h TEXTURE_SIZE_128, // sizeX for glTexImage2D() in videoGL.h TEXTURE_SIZE_128, // sizeY for glTexImage2D() in videoGL.h GL_TEXTURE_WRAP_S | GL_TEXTURE_WRAP_T | TEXGEN_OFF | GL_TEXTURE_COLOR0_TRANSPARENT, // param for glTexImage2D() in videoGL.h 256, // Length of the palette to use (16 colors) (u16*) tilesPal, // Load our 16 color tiles palette (u8*) tilesBitmap // image data generated by GRIT ); } bool isSolidTile(u8 tile) { switch (tile) { case 4: case 5: case 6: case 7: case 8: case 13: case 16: case 17: case 20: case 21: case 24: case 25: case 28: case 29: case 33: case 34: case 35: case 36: case 37: case 40: case 41: case 42: case 43: case 44: case 45: return true; default: break; } return false; } void loadLevel(const char* filename) { mapHsize = -1; mapVsize = -1; toncset(mapData, 0, sizeof(mapData)); off_t klvFileSize = 0; FILE* klvFile = fopen(filename, "rb"); fseek(klvFile, 0, SEEK_END); klvFileSize = ftell(klvFile); // Get source file's size fseek(klvFile, 0, SEEK_SET); if (klvFileSize == 0) { return; } u8* orgMapData = new u8[klvFileSize]; fread(orgMapData, 1, klvFileSize, klvFile); fclose(klvFile); bool mapHsizeSet = false; bool processTile = false; int generatedPlayerX = -16; int i1 = -1; // Position in generated map int i2 = -1; // Position in kglf file while (1) { if (orgMapData[i2] == 'E' && orgMapData[i2+1] == 'N' && orgMapData[i2+2] == 'D') { break; } else if ((orgMapData[i2] == 0x0D && orgMapData[i2+1] == 0x0A) || (orgMapData[i2] == 0x0A)) { if (orgMapData[i2] == 0x0D && orgMapData[i2+1] == 0x0A) { i2++; } mapVsize++; generatedPlayerX = -16; mapHsizeSet = true; } else { i1++; processTile = true; } generatedPlayerX += 16; i2++; if (!mapHsizeSet) { mapHsize++; } if (orgMapData[i2] == '1' || orgMapData[i2] == '2') { setPlayerPosition((orgMapData[i2] == '2' ? 1 : 0), generatedPlayerX, (mapVsize*16)-16); } else if (processTile) { for (int i3 = 0; i3 < (int)sizeof(textTiles); i3++) { if (textTiles[i3] == orgMapData[i2]) { mapData[i1] = i3; break; } } processTile = false; } } delete[] orgMapData; } void levelMode(void) { if (!inited) { loadLevel("nitro:/klv/level.klv"); playerGraphicLoad(); decompress(bottomImageBitmap, bgGetGfxPtr(bg3), LZ77Vram); bgSetScroll(bg3, 0, 0); bgScroll(bg3, 0, 0); oamClear(&oamSub, 0, 2); gfxSub = oamAllocateGfx(&oamSub, SpriteSize_32x64, SpriteColorFormat_16Color); tonccpy(gfxSub, spr_aimbuttonTiles, spr_aimbuttonTilesLen); for (int i = 0; i < 16; i++) { SPRITE_PALETTE_SUB[i] = spr_aimbuttonPal[i]; } oamSet(&oamSub, 0, 80, 48, 0, 0, SpriteSize_32x32, SpriteColorFormat_16Color, gfxSub+(32*8), -1, false, false, false, false, false ); oamSet(&oamSub, 1, 112, 48, 0, 0, SpriteSize_32x32, SpriteColorFormat_16Color, gfxSub, -1, false, false, false, false, false ); oamSet(&oamSub, 2, 144, 48, 0, 0, SpriteSize_32x32, SpriteColorFormat_16Color, gfxSub+(32*8), -1, false, false, true, false, false ); oamSet(&oamSub, 3, 80, 80, 0, 0, SpriteSize_32x32, SpriteColorFormat_16Color, gfxSub+(64*8), -1, false, false, false, false, false ); oamSet(&oamSub, 4, 144, 80, 0, 0, SpriteSize_32x32, SpriteColorFormat_16Color, gfxSub+(64*8), -1, false, false, true, false, false ); oamSet(&oamSub, 5, 80, 112, 0, 0, SpriteSize_32x32, SpriteColorFormat_16Color, gfxSub+(32*8), -1, false, false, false, true, false ); oamSet(&oamSub, 6, 144, 112, 0, 0, SpriteSize_32x32, SpriteColorFormat_16Color, gfxSub+(32*8), -1, false, false, true, true, false ); fadeType = true; snd().loadStream("nitro:/music/tense.wav", true); snd().beginStream(); inited = true; } scanKeys(); int pressed = keysDown(); int held = keysHeld(); playerLoop(pressed, held); } void levelGraphicDisplay(void) { glBoxFilled(0, 0, (wideScreen ? 308 : 256), 192, RGB15(85/8, 85/8, 255/8)); /*for (int x = 0; x < 256; x += 16) { for (int y = 0; y < 192; y += 16) { glSprite(x, y, GL_FLIP_NONE, &tileImage[bgTile]); } }*/ //if (mapHsize>16 && playerX>(256/2)) { cameraXpos = playerX[0]-((wideScreen ? 308 : 256)/2); /* if (cameraXpos > (mapHsize*16)-256) { cameraXpos = (mapHsize*16)-256; } } else { cameraXpos = 0; }*/ //if (mapVsize>12 && playerY>192/2) { cameraYpos = playerY[0]-(192/2); /* if (cameraYpos > (mapVsize*16)-192) { cameraYpos = (mapVsize*16)-192; } } else { cameraYpos = 0; }*/ for (int x = 0; x < mapHsize; x++) { for (int y = 0; y < mapVsize; y++) { if (mapData[(y*mapHsize)+x] != 0) { glSprite((x*16)-cameraXpos, (y*16)-cameraYpos, GL_FLIP_NONE, &tileImage[mapData[(y*mapHsize)+x]]); } } } renderPlayer(); }
18.974763
131
0.599501
RocketRobz
4c17c434f60635a03bdd688a2d0ea179d13ab46e
4,824
cc
C++
google/cloud/pubsublite/internal/default_routing_policy_test.cc
GoogleCloudPlatform/google-cloud-cpp
c4fc35de9e15f95b1dbf585f1c96de5dba609e2b
[ "Apache-2.0" ]
80
2017-11-24T00:19:45.000Z
2019-01-25T10:24:33.000Z
google/cloud/pubsublite/internal/default_routing_policy_test.cc
GoogleCloudPlatform/google-cloud-cpp
c4fc35de9e15f95b1dbf585f1c96de5dba609e2b
[ "Apache-2.0" ]
1,579
2017-11-24T01:01:21.000Z
2019-01-28T23:41:21.000Z
google/cloud/pubsublite/internal/default_routing_policy_test.cc
GoogleCloudPlatform/google-cloud-cpp
c4fc35de9e15f95b1dbf585f1c96de5dba609e2b
[ "Apache-2.0" ]
51
2017-11-24T00:56:11.000Z
2019-01-18T20:35:02.000Z
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "google/cloud/pubsublite/internal/default_routing_policy.h" #include <gmock/gmock.h> #include <array> #include <unordered_map> namespace google { namespace cloud { namespace pubsublite_internal { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN using google::cloud::pubsublite_internal::DefaultRoutingPolicy; TEST(DefaultRoutingPolicyTest, RouteWithKey) { // same list of test values as in other client libraries DefaultRoutingPolicy rp; std::unordered_map<std::string, std::uint64_t> mods = { {"oaisdhfoiahsd", 18}, {"P(#*YNPOIUDF", 9}, {"LCIUNDFPOASIUN", 8}, {";odsfiupoius", 9}, {"OPISUDfpoiu", 2}, {"dokjwO:IDf", 21}, {"%^&*", 19}, {"XXXXXXXXX", 15}, {"dpcollins", 28}, {"#()&$IJHLOIURF", 2}, {"dfasiduyf", 6}, {"983u2poer", 3}, {"8888888", 6}, {"OPUIPOUYPOIOPUIOIPUOUIPJOP", 2}, {"x", 16}}; for (auto const& kv : mods) { EXPECT_EQ(rp.Route(kv.first, 29), kv.second); } } TEST(DefaultRoutingPolicyTest, RouteWithoutKey) { unsigned int num_partitions = 29; DefaultRoutingPolicy rp; std::uint32_t initial_partition = rp.Route(num_partitions); for (unsigned int i = 0; i < num_partitions; ++i) { std::uint32_t next_partition = rp.Route(num_partitions); EXPECT_EQ((initial_partition + 1) % num_partitions, next_partition % num_partitions); initial_partition = next_partition; } } // expected values obtained from Python3 REPL TEST(TestGetMod, MaxValue) { std::array<std::uint8_t, 32> arr{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}; EXPECT_EQ(GetMod(arr, 2), 1); EXPECT_EQ(GetMod(arr, 18), 15); EXPECT_EQ(GetMod(arr, 100), 35); EXPECT_EQ(GetMod(arr, 10023), 5397); EXPECT_EQ(GetMod(arr, UINT8_MAX), 0); EXPECT_EQ(GetMod(arr, UINT32_MAX - 1), 255); } TEST(TestGetMod, OneLessThanMaxValue) { std::array<std::uint8_t, 32> arr{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254}; EXPECT_EQ(GetMod(arr, 2), 0); EXPECT_EQ(GetMod(arr, 18), 14); EXPECT_EQ(GetMod(arr, 100), 34); EXPECT_EQ(GetMod(arr, 10023), 5396); EXPECT_EQ(GetMod(arr, UINT8_MAX), 254); EXPECT_EQ(GetMod(arr, UINT32_MAX - 1), 254); } TEST(TestGetMod, Zeros) { std::array<std::uint8_t, 32> arr{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; EXPECT_EQ(GetMod(arr, 2), 0); EXPECT_EQ(GetMod(arr, 18), 0); EXPECT_EQ(GetMod(arr, 100), 0); EXPECT_EQ(GetMod(arr, 10023), 0); EXPECT_EQ(GetMod(arr, UINT8_MAX), 0); EXPECT_EQ(GetMod(arr, UINT32_MAX - 1), 0); } TEST(TestGetMod, ArbitraryValue) { std::array<std::uint8_t, 32> arr{255, 255, 255, 255, 255, 255, 2, 255, 5, 79, 255, 255, 255, 255, 80, 255, 255, 255, 8, 255, 255, 4, 255, 255, 78, 255, 255, 100, 255, 255, 255, 254}; EXPECT_EQ(GetMod(arr, 10), 0); EXPECT_EQ(GetMod(arr, 109), 4); EXPECT_EQ(GetMod(arr, 10023), 3346); EXPECT_EQ(GetMod(arr, 109000), 60390); EXPECT_EQ(GetMod(arr, UINT8_MAX), 100); EXPECT_EQ(GetMod(arr, UINT32_MAX - 1), 1136793478); } TEST(TestGetMod, ArbitraryValue1) { std::array<std::uint8_t, 32> arr{0, 48, 0, 0, 60, 0, 0, 56, 0, 99, 0, 0, 0, 0, 0, 90, 231, 0, 89, 0, 27, 80, 0, 0, 0, 254, 0, 0, 0, 0, 23, 0}; EXPECT_EQ(GetMod(arr, 109001), 68945); EXPECT_EQ(GetMod(arr, 102301), 93535); EXPECT_EQ(GetMod(arr, 23), 13); EXPECT_EQ(GetMod(arr, UINT8_MAX), 37); EXPECT_EQ(GetMod(arr, UINT32_MAX - 1), 3416191692); } GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace pubsublite_internal } // namespace cloud } // namespace google
37.107692
77
0.597015
GoogleCloudPlatform
4c18f3b90f58b5b8a27f20b89750db369bce7152
851
cpp
C++
search/base/text_index/mem.cpp
AddisMap/omim
3e7e4ed7b24f12a7d6cabf4d83b968523f150f1b
[ "Apache-2.0" ]
null
null
null
search/base/text_index/mem.cpp
AddisMap/omim
3e7e4ed7b24f12a7d6cabf4d83b968523f150f1b
[ "Apache-2.0" ]
null
null
null
search/base/text_index/mem.cpp
AddisMap/omim
3e7e4ed7b24f12a7d6cabf4d83b968523f150f1b
[ "Apache-2.0" ]
null
null
null
#include "search/base/text_index/mem.hpp" #include "base/stl_helpers.hpp" using namespace std; namespace search { namespace base { void MemTextIndex::AddPosting(Token const & token, Posting const & posting) { m_postingsByToken[token].emplace_back(posting); } void MemTextIndex::SortPostings() { for (auto & entry : m_postingsByToken) { // A posting may occur several times in a document, // so we remove duplicates for the docid index. // If the count is needed for ranking it may be stored // separately. my::SortUnique(entry.second); } } void MemTextIndex::BuildDictionary() { vector<Token> tokens; tokens.reserve(m_postingsByToken.size()); for (auto const & entry : m_postingsByToken) tokens.emplace_back(entry.first); m_dictionary.SetTokens(move(tokens)); } } // namespace base } // namespace search
22.394737
75
0.720329
AddisMap
4c18fb902051a325612095e40494106613a076fa
32
cc
C++
src/mesytec-mvlc/mvlc_usb_interface.cc
ExternalRepositories/mesytec-mvlc
be62792fb951a7938a9121424a38bd020572b327
[ "BSL-1.0" ]
null
null
null
src/mesytec-mvlc/mvlc_usb_interface.cc
ExternalRepositories/mesytec-mvlc
be62792fb951a7938a9121424a38bd020572b327
[ "BSL-1.0" ]
3
2021-07-15T10:10:19.000Z
2021-08-05T13:47:36.000Z
src/mesytec-mvlc/mvlc_usb_interface.cc
ExternalRepositories/mesytec-mvlc
be62792fb951a7938a9121424a38bd020572b327
[ "BSL-1.0" ]
5
2020-09-22T10:21:25.000Z
2022-02-17T15:06:14.000Z
#include "mvlc_usb_interface.h"
16
31
0.8125
ExternalRepositories
4c1abc47ce27fd4ac8805bda0b50bfb8b2b3a6bc
665
cpp
C++
Miracle/src/Miracle/MiracleAppBuilder.cpp
McFlyboy/Miracle
03a41bb8e24ecf2dfc18b5e3aee964640ec9a593
[ "MIT" ]
null
null
null
Miracle/src/Miracle/MiracleAppBuilder.cpp
McFlyboy/Miracle
03a41bb8e24ecf2dfc18b5e3aee964640ec9a593
[ "MIT" ]
3
2021-12-10T23:19:29.000Z
2022-03-27T05:04:14.000Z
Miracle/src/Miracle/MiracleAppBuilder.cpp
McFlyboy/Miracle
03a41bb8e24ecf2dfc18b5e3aee964640ec9a593
[ "MIT" ]
null
null
null
#include <Miracle/components/Miracle/MiracleAppBuilder.hpp> namespace Miracle { MiracleAppBuilder& MiracleAppBuilder::configureWindow(std::function<void (View::WindowProps&)> configurer) { configurer(m_windowProps); return *this; } MiracleAppBuilder& MiracleAppBuilder::setStartScript(std::function<void ()> startScript) { m_startScript = startScript; return *this; } MiracleAppBuilder& MiracleAppBuilder::setUpdateScript(std::function<void ()> updateScript) { m_updateScript = updateScript; return *this; } MiracleApp MiracleAppBuilder::build() const { return MiracleApp( m_windowProps, m_startScript, m_updateScript ); } }
22.166667
109
0.754887
McFlyboy
4c1d25a633f36fe9440429bf80fa36acfb840bca
1,039
cc
C++
src/mvp/Frontend/mvpdumpjob.cc
NeoGeographyToolkit/MultipleViewPipeline
c2ad4ebb7555a1157616389466c7075e0c61292a
[ "Apache-2.0" ]
10
2015-05-13T22:52:47.000Z
2022-03-10T12:09:44.000Z
src/mvp/Frontend/mvpdumpjob.cc
NeoGeographyToolkit/MultipleViewPipeline
c2ad4ebb7555a1157616389466c7075e0c61292a
[ "Apache-2.0" ]
null
null
null
src/mvp/Frontend/mvpdumpjob.cc
NeoGeographyToolkit/MultipleViewPipeline
c2ad4ebb7555a1157616389466c7075e0c61292a
[ "Apache-2.0" ]
15
2015-01-07T02:11:03.000Z
2021-11-12T18:35:20.000Z
#include <iostream> #include <mvp/Config.h> #if MVP_ENABLE_OCTAVE_SUPPORT #include <mvp/Octave/Main.h> #endif #include <mvp/Pipeline/Session.h> #include <mvp/Pipeline/Job.h> #include <mvp/Core/Settings.h> #include <boost/foreach.hpp> #include <boost/lexical_cast.hpp> using namespace std; using namespace mvp; int main(int argc, char *argv[]) { if (argc != 5) { cout << "Usage: mvpdumpjob jobfile col row level" << endl; return 1; } pipeline::SessionDesc session_desc; core::load_settings(&session_desc, argv[1]); pipeline::Session session(session_desc); int col = boost::lexical_cast<int>(argv[2]); int row = boost::lexical_cast<int>(argv[3]); int level = boost::lexical_cast<int>(argv[4]); pipeline::Job job(session.job(col, row, level)); job.save_job_file(); #if MVP_ENABLE_OCTAVE_SUPPORT octave::start_octave_interpreter(LOADTESTENV_M); // TODO: instead //octave::start_octave_interpreter(); job.save_job_file_octave(); octave::stop_octave_interpreter(); #endif return 0; }
19.980769
62
0.708373
NeoGeographyToolkit
4c1ea65b0d605de48f120bd0a345a2196b0fce32
11,295
cc
C++
sync/test/fake_server/fake_server.cc
iplo/Chain
8bc8943d66285d5258fffc41bed7c840516c4422
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
231
2015-01-08T09:04:44.000Z
2021-12-30T03:03:10.000Z
sync/test/fake_server/fake_server.cc
JasonEric/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2017-02-14T21:55:58.000Z
2017-02-14T21:55:58.000Z
sync/test/fake_server/fake_server.cc
JasonEric/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
268
2015-01-21T05:53:28.000Z
2022-03-25T22:09:01.000Z
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "sync/test/fake_server/fake_server.h" #include <limits> #include <string> #include <vector> #include "base/basictypes.h" #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "base/strings/string_number_conversions.h" #include "net/base/net_errors.h" #include "net/http/http_status_code.h" #include "sync/internal_api/public/base/model_type.h" #include "sync/protocol/sync.pb.h" using std::string; // The parent tag for childen of the root node. static const char kRootParentTag[] = "0"; // The default birthday value. static const char kDefaultBirthday[] = "1234567890"; // The default keystore key. static const char kDefaultKeystoreKey[] = "1111111111111111"; // A dummy value to use for the position_in_parent field of SyncEntity. static const int64 kDummyBookmarkPositionInParent = 1337; namespace syncer { namespace { // A filter used during GetUpdates calls to determine what information to // send back to the client. There is a 1:1 correspondence between any given // GetUpdates call and an UpdateSieve instance. class UpdateSieve { public: ~UpdateSieve() { } // Factory method for creating an UpdateSieve. static scoped_ptr<UpdateSieve> Create( const sync_pb::GetUpdatesMessage& get_updates_message); // Sets the progress markers in |get_updates_response| given the progress // markers from the original GetUpdatesMessage and |new_version| (the latest // version in the entries sent back). void UpdateProgressMarkers( int64 new_version, sync_pb::GetUpdatesResponse* get_updates_response) const { ModelTypeToVersionMap::const_iterator it; for (it = request_from_version_.begin(); it != request_from_version_.end(); ++it) { sync_pb::DataTypeProgressMarker* new_marker = get_updates_response->add_new_progress_marker(); new_marker->set_data_type_id( GetSpecificsFieldNumberFromModelType(it->first)); int64 version = std::max(new_version, it->second); new_marker->set_token(base::Int64ToString(version)); } } // Determines whether the server should send |entity| to the client based // on its type and version. bool ClientWantsItem(const sync_pb::SyncEntity& entity) const { ModelTypeToVersionMap::const_iterator it = request_from_version_.find(GetModelType(entity)); return it == request_from_version_.end() ? false : it->second < entity.version(); } // Returns the mininum version seen across all types. int64 GetMinVersion() const { return min_version_; } // Returns the data type IDs of types being synced for the first time. std::vector<ModelType> GetFirstTimeTypes() const { std::vector<ModelType> types; ModelTypeToVersionMap::const_iterator it; for (it = request_from_version_.begin(); it != request_from_version_.end(); ++it) { if (it->second == 0) types.push_back(it->first); } return types; } private: typedef std::map<ModelType, int64> ModelTypeToVersionMap; // Creates an UpdateSieve. UpdateSieve(const ModelTypeToVersionMap request_from_version, const int64 min_version) : request_from_version_(request_from_version), min_version_(min_version) { } // Maps data type IDs to the latest version seen for that type. const ModelTypeToVersionMap request_from_version_; // The minimum version seen among all data types. const int min_version_; }; scoped_ptr<UpdateSieve> UpdateSieve::Create( const sync_pb::GetUpdatesMessage& get_updates_message) { DCHECK_GT(get_updates_message.from_progress_marker_size(), 0); UpdateSieve::ModelTypeToVersionMap request_from_version; int64 min_version = std::numeric_limits<int64>::max(); for (int i = 0; i < get_updates_message.from_progress_marker_size(); i++) { sync_pb::DataTypeProgressMarker marker = get_updates_message.from_progress_marker(i); int64 version = 0; // Let the version remain zero if there is no token or an empty token (the // first request for this type). if (marker.has_token() && !marker.token().empty()) { bool parsed = base::StringToInt64(marker.token(), &version); DCHECK(parsed); } ModelType model_type = GetModelTypeFromSpecificsFieldNumber( marker.data_type_id()); request_from_version[model_type] = version; if (version < min_version) min_version = version; } return scoped_ptr<UpdateSieve>( new UpdateSieve(request_from_version, min_version)); } } // namespace FakeServer::FakeServer() : version_(0), birthday_(kDefaultBirthday) { keystore_keys_.push_back(kDefaultKeystoreKey); } FakeServer::~FakeServer() { } void FakeServer::CreateDefaultPermanentItems( const std::vector<ModelType>& first_time_types) { for (std::vector<ModelType>::const_iterator it = first_time_types.begin(); it != first_time_types.end(); ++it) { if (!ModelTypeSet::All().Has(*it)) { NOTREACHED() << "An unexpected ModelType was encountered."; } ModelType model_type = *it; CreateSyncEntity(model_type, ModelTypeToRootTag(model_type), ModelTypeToString(model_type), kRootParentTag); if (model_type == BOOKMARKS) { CreateSyncEntity(BOOKMARKS, "bookmark_bar", "Bookmark Bar", ModelTypeToRootTag(BOOKMARKS)); CreateSyncEntity(BOOKMARKS, "other_bookmarks", "Other Bookmarks", ModelTypeToRootTag(BOOKMARKS)); } } // TODO(pvalenzuela): Create the mobile bookmarks folder when the fake server // is used by mobile tests. } void FakeServer::CreateSyncEntity(ModelType model_type, const std::string& id, const std::string& name, const std::string& parent_tag) { DCHECK(!id.empty()); DCHECK(!name.empty()); DCHECK(!parent_tag.empty()); sync_pb::SyncEntity entity; entity.set_id_string(id); entity.set_non_unique_name(name); entity.set_name(name); entity.set_server_defined_unique_tag(id); entity.set_folder(true); entity.set_deleted(false); entity.set_parent_id_string(parent_tag); if (parent_tag != kRootParentTag && model_type == BOOKMARKS) { // Use a dummy value here. entity.set_position_in_parent(kDummyBookmarkPositionInParent); } sync_pb::EntitySpecifics* specifics = entity.mutable_specifics(); AddDefaultFieldValue(model_type, specifics); SaveEntity(&entity); } void FakeServer::SaveEntity(sync_pb::SyncEntity* entity) { version_++; entity->set_version(version_); entity->set_sync_timestamp(version_); sync_pb::SyncEntity original_entity = entities_[entity->id_string()]; entity->set_originator_cache_guid(original_entity.originator_cache_guid()); entity->set_originator_client_item_id( original_entity.originator_client_item_id()); entities_[entity->id_string()] = *entity; } int FakeServer::HandleCommand(const string& request, int* response_code, string* response) { sync_pb::ClientToServerMessage message; bool parsed = message.ParseFromString(request); DCHECK(parsed); sync_pb::ClientToServerResponse response_proto; switch (message.message_contents()) { case sync_pb::ClientToServerMessage::GET_UPDATES: response_proto = HandleGetUpdatesRequest(message); break; case sync_pb::ClientToServerMessage::COMMIT: response_proto = HandleCommitRequest(message); break; default: return net::ERR_NOT_IMPLEMENTED; } *response_code = net::HTTP_OK; *response = response_proto.SerializeAsString(); return 0; } bool SyncEntityVersionComparator(const sync_pb::SyncEntity& first, const sync_pb::SyncEntity& second) { return first.version() < second.version(); } sync_pb::ClientToServerResponse FakeServer::HandleGetUpdatesRequest( const sync_pb::ClientToServerMessage& message) { sync_pb::ClientToServerResponse response; response.set_error_code(sync_pb::SyncEnums::SUCCESS); response.set_store_birthday(birthday_); sync_pb::GetUpdatesResponse* get_updates_response = response.mutable_get_updates(); // TODO(pvalenzuela): Implement batching instead of sending all information // at once. get_updates_response->set_changes_remaining(0); scoped_ptr<UpdateSieve> sieve = UpdateSieve::Create(message.get_updates()); CreateDefaultPermanentItems(sieve->GetFirstTimeTypes()); int64 min_version = sieve->GetMinVersion(); bool send_encryption_keys_based_on_nigori = false; int64 max_response_version = 0; for (EntityMap::iterator it = entities_.begin(); it != entities_.end(); ++it) { sync_pb::SyncEntity entity = it->second; if (entity.version() > min_version && sieve->ClientWantsItem(entity)) { sync_pb::SyncEntity* response_entity = get_updates_response->add_entries(); response_entity->CopyFrom(entity); max_response_version = std::max(max_response_version, response_entity->version()); if (response_entity->name() == ModelTypeToString(NIGORI)) { send_encryption_keys_based_on_nigori = response_entity->specifics().nigori().passphrase_type() == sync_pb::NigoriSpecifics::KEYSTORE_PASSPHRASE; } } } if (send_encryption_keys_based_on_nigori || message.get_updates().need_encryption_key()) { for (std::vector<std::string>::iterator it = keystore_keys_.begin(); it != keystore_keys_.end(); ++it) { get_updates_response->add_encryption_keys(*it); } } sieve->UpdateProgressMarkers(max_response_version, get_updates_response); return response; } sync_pb::SyncEntity FakeServer::CommitEntity(const sync_pb::SyncEntity& entity, string guid) { // TODO(pvalenzuela): Implement this. Right now this method cheats and // doesn't actually commit. return entity; } sync_pb::ClientToServerResponse FakeServer::HandleCommitRequest( const sync_pb::ClientToServerMessage& message) { sync_pb::ClientToServerResponse response; response.set_error_code(sync_pb::SyncEnums::SUCCESS); response.set_store_birthday(birthday_); sync_pb::CommitMessage commit = message.commit(); string guid = commit.cache_guid(); sync_pb::CommitResponse* commit_response = response.mutable_commit(); ::google::protobuf::RepeatedPtrField<sync_pb::SyncEntity>::const_iterator it; for (it = commit.entries().begin(); it != commit.entries().end(); ++it) { sync_pb::CommitResponse_EntryResponse* entry_response = commit_response->add_entryresponse(); sync_pb::SyncEntity server_entity = CommitEntity(*it, guid); entry_response->set_id_string(server_entity.id_string()); entry_response->set_response_type(sync_pb::CommitResponse::SUCCESS); entry_response->set_version(it->version() + 1); } return response; } } // namespace syncer
33.616071
79
0.702966
iplo
4c23f6b804630fac96234cd58e52ca421e1a7e19
15,015
cpp
C++
drape_frontend/traffic_generator.cpp
ruilin/RLMap
e16b52f77d165e719b3af20b097f227959e8e374
[ "Apache-2.0" ]
2
2019-01-24T15:36:20.000Z
2019-12-26T10:03:48.000Z
drape_frontend/traffic_generator.cpp
ruilin/RLMap
e16b52f77d165e719b3af20b097f227959e8e374
[ "Apache-2.0" ]
1
2018-03-07T15:05:23.000Z
2018-03-07T15:05:23.000Z
drape_frontend/traffic_generator.cpp
ruilin/RLMap
e16b52f77d165e719b3af20b097f227959e8e374
[ "Apache-2.0" ]
1
2019-08-09T21:31:29.000Z
2019-08-09T21:31:29.000Z
#include "drape_frontend/traffic_generator.hpp" #include "drape_frontend/line_shape_helper.hpp" #include "drape_frontend/map_shape.hpp" #include "drape_frontend/shader_def.hpp" #include "drape_frontend/shape_view_params.hpp" #include "drape_frontend/tile_utils.hpp" #include "drape_frontend/traffic_renderer.hpp" #include "drape_frontend/visual_params.hpp" #include "drape/attribute_provider.hpp" #include "drape/glsl_func.hpp" #include "drape/texture_manager.hpp" #include "indexer/map_style_reader.hpp" #include "base/logging.hpp" #include "std/algorithm.hpp" #include <functional> using namespace std::placeholders; namespace df { namespace { // Values of the following arrays are based on traffic-arrow texture. static array<float, static_cast<size_t>(traffic::SpeedGroup::Count)> kCoordVOffsets = {{ 0.75f, // G0 0.75f, // G1 0.75f, // G2 0.5f, // G3 0.25f, // G4 0.25f, // G5 0.75f, // TempBlock 0.0f, // Unknown }}; static array<float, static_cast<size_t>(traffic::SpeedGroup::Count)> kMinCoordU = {{ 0.15f, // G0 0.15f, // G1 0.15f, // G2 0.33f, // G3 0.5f, // G4 0.0f, // G5 0.15f, // TempBlock 0.0f, // Unknown }}; dp::BindingInfo const & GetTrafficStaticBindingInfo() { static unique_ptr<dp::BindingInfo> s_info; if (s_info == nullptr) { dp::BindingFiller<TrafficStaticVertex> filler(3); filler.FillDecl<TrafficStaticVertex::TPosition>("a_position"); filler.FillDecl<TrafficStaticVertex::TNormal>("a_normal"); filler.FillDecl<TrafficStaticVertex::TTexCoord>("a_colorTexCoord"); s_info.reset(new dp::BindingInfo(filler.m_info)); } return *s_info; } dp::BindingInfo const & GetTrafficLineStaticBindingInfo() { static unique_ptr<dp::BindingInfo> s_info; if (s_info == nullptr) { dp::BindingFiller<TrafficLineStaticVertex> filler(2); filler.FillDecl<TrafficLineStaticVertex::TPosition>("a_position"); filler.FillDecl<TrafficLineStaticVertex::TTexCoord>("a_colorTexCoord"); s_info.reset(new dp::BindingInfo(filler.m_info)); } return *s_info; } void SubmitStaticVertex(glsl::vec3 const & pivot, glsl::vec2 const & normal, float side, float offsetFromStart, glsl::vec4 const & texCoord, vector<TrafficStaticVertex> & staticGeom) { staticGeom.emplace_back(pivot, TrafficStaticVertex::TNormal(normal, side, offsetFromStart), texCoord); } void GenerateCapTriangles(glsl::vec3 const & pivot, vector<glsl::vec2> const & normals, dp::TextureManager::ColorRegion const & colorRegion, vector<TrafficStaticVertex> & staticGeometry) { float const kEps = 1e-5; glsl::vec4 const uv = glsl::vec4(glsl::ToVec2(colorRegion.GetTexRect().Center()), 0.0f, 0.0f); size_t const trianglesCount = normals.size() / 3; for (size_t j = 0; j < trianglesCount; j++) { SubmitStaticVertex(pivot, normals[3 * j], glsl::length(normals[3 * j]) < kEps ? 0.0f : 1.0f, 0.0f, uv, staticGeometry); SubmitStaticVertex(pivot, normals[3 * j + 1], glsl::length(normals[3 * j + 1]) < kEps ? 0.0f : 1.0f, 0.0f, uv, staticGeometry); SubmitStaticVertex(pivot, normals[3 * j + 2], glsl::length(normals[3 * j + 2]) < kEps ? 0.0f : 1.0f, 0.0f, uv, staticGeometry); } } } // namespace bool TrafficGenerator::m_simplifiedColorScheme = true; void TrafficGenerator::Init() { int constexpr kBatchersCount = 3; int constexpr kBatchSize = 65000; m_batchersPool = make_unique_dp<BatchersPool<TrafficBatcherKey, TrafficBatcherKeyComparator>>( kBatchersCount, bind(&TrafficGenerator::FlushGeometry, this, _1, _2, _3), kBatchSize, kBatchSize); m_providerLines.InitStream(0 /* stream index */, GetTrafficLineStaticBindingInfo(), nullptr); m_providerTriangles.InitStream(0 /* stream index */, GetTrafficStaticBindingInfo(), nullptr); } void TrafficGenerator::ClearGLDependentResources() { InvalidateTexturesCache(); m_batchersPool.reset(); } void TrafficGenerator::FlushSegmentsGeometry(TileKey const & tileKey, TrafficSegmentsGeometry const & geom, ref_ptr<dp::TextureManager> textures) { FillColorsCache(textures); ASSERT(m_colorsCacheValid, ()); auto const texture = m_colorsCache[static_cast<size_t>(traffic::SpeedGroup::G0)].GetTexture(); dp::GLState state(gpu::TRAFFIC_PROGRAM, dp::GLState::GeometryLayer); state.SetColorTexture(texture); state.SetMaskTexture(textures->GetTrafficArrowTexture()); dp::GLState lineState(gpu::TRAFFIC_LINE_PROGRAM, dp::GLState::GeometryLayer); lineState.SetColorTexture(texture); lineState.SetDrawAsLine(true); static vector<RoadClass> const kRoadClasses = {RoadClass::Class0, RoadClass::Class1, RoadClass::Class2}; static float const kDepths[] = {2.0f, 1.0f, 0.0f}; static vector<int> const kGenerateCapsZoomLevel = {14, 14, 16}; for (auto geomIt = geom.begin(); geomIt != geom.end(); ++geomIt) { auto coloringIt = m_coloring.find(geomIt->first); if (coloringIt != m_coloring.end()) { for (auto const & roadClass : kRoadClasses) m_batchersPool->ReserveBatcher(TrafficBatcherKey(geomIt->first, tileKey, roadClass)); auto & coloring = coloringIt->second; for (size_t i = 0; i < geomIt->second.size(); i++) { traffic::TrafficInfo::RoadSegmentId const & sid = geomIt->second[i].first; auto segmentColoringIt = coloring.find(sid); if (segmentColoringIt != coloring.end()) { // We do not generate geometry for unknown segments. if (segmentColoringIt->second == traffic::SpeedGroup::Unknown) continue; TrafficSegmentGeometry const & g = geomIt->second[i].second; ref_ptr<dp::Batcher> batcher = m_batchersPool->GetBatcher(TrafficBatcherKey(geomIt->first, tileKey, g.m_roadClass)); float const depth = kDepths[static_cast<size_t>(g.m_roadClass)]; ASSERT(m_colorsCacheValid, ()); dp::TextureManager::ColorRegion const & colorRegion = m_colorsCache[static_cast<size_t>(segmentColoringIt->second)]; float const vOffset = kCoordVOffsets[static_cast<size_t>(segmentColoringIt->second)]; float const minU = kMinCoordU[static_cast<size_t>(segmentColoringIt->second)]; int width = 0; if (TrafficRenderer::CanBeRendereredAsLine(g.m_roadClass, tileKey.m_zoomLevel, width)) { vector<TrafficLineStaticVertex> staticGeometry; GenerateLineSegment(colorRegion, g.m_polyline, tileKey.GetGlobalRect().Center(), depth, staticGeometry); if (staticGeometry.empty()) continue; m_providerLines.Reset(static_cast<uint32_t>(staticGeometry.size())); m_providerLines.UpdateStream(0 /* stream index */, make_ref(staticGeometry.data())); dp::GLState curLineState = lineState; curLineState.SetLineWidth(width); batcher->InsertLineStrip(curLineState, make_ref(&m_providerLines)); } else { vector<TrafficStaticVertex> staticGeometry; bool const generateCaps = (tileKey.m_zoomLevel > kGenerateCapsZoomLevel[static_cast<uint32_t>(g.m_roadClass)]); GenerateSegment(colorRegion, g.m_polyline, tileKey.GetGlobalRect().Center(), generateCaps, depth, vOffset, minU, staticGeometry); if (staticGeometry.empty()) continue; m_providerTriangles.Reset(static_cast<uint32_t>(staticGeometry.size())); m_providerTriangles.UpdateStream(0 /* stream index */, make_ref(staticGeometry.data())); batcher->InsertTriangleList(state, make_ref(&m_providerTriangles)); } } } for (auto const & roadClass : kRoadClasses) m_batchersPool->ReleaseBatcher(TrafficBatcherKey(geomIt->first, tileKey, roadClass)); } } GLFunctions::glFlush(); } void TrafficGenerator::UpdateColoring(TrafficSegmentsColoring const & coloring) { for (auto const & p : coloring) m_coloring[p.first] = p.second; } void TrafficGenerator::ClearCache() { InvalidateTexturesCache(); m_coloring.clear(); } void TrafficGenerator::ClearCache(MwmSet::MwmId const & mwmId) { m_coloring.erase(mwmId); } void TrafficGenerator::InvalidateTexturesCache() { m_colorsCacheValid = false; } void TrafficGenerator::FlushGeometry(TrafficBatcherKey const & key, dp::GLState const & state, drape_ptr<dp::RenderBucket> && buffer) { TrafficRenderData renderData(state); renderData.m_bucket = move(buffer); renderData.m_mwmId = key.m_mwmId; renderData.m_tileKey = key.m_tileKey; renderData.m_roadClass = key.m_roadClass; m_flushRenderDataFn(move(renderData)); } void TrafficGenerator::GenerateSegment(dp::TextureManager::ColorRegion const & colorRegion, m2::PolylineD const & polyline, m2::PointD const & tileCenter, bool generateCaps, float depth, float vOffset, float minU, vector<TrafficStaticVertex> & staticGeometry) { vector<m2::PointD> const & path = polyline.GetPoints(); ASSERT_GREATER(path.size(), 1, ()); size_t const kAverageSize = path.size() * 4; size_t const kAverageCapSize = 12; staticGeometry.reserve(staticGeometry.size() + kAverageSize + kAverageCapSize * 2); // Build geometry. glsl::vec2 firstPoint, firstTangent, firstLeftNormal, firstRightNormal; glsl::vec2 lastPoint, lastTangent, lastLeftNormal, lastRightNormal; bool firstFilled = false; glsl::vec4 const uvStart = glsl::vec4(glsl::ToVec2(colorRegion.GetTexRect().Center()), vOffset, 1.0f); glsl::vec4 const uvEnd = glsl::vec4(uvStart.x, uvStart.y, uvStart.z, minU); for (size_t i = 1; i < path.size(); ++i) { if (path[i].EqualDxDy(path[i - 1], 1.0E-5)) continue; glsl::vec2 const p1 = glsl::ToVec2(MapShape::ConvertToLocal(path[i - 1], tileCenter, kShapeCoordScalar)); glsl::vec2 const p2 = glsl::ToVec2(MapShape::ConvertToLocal(path[i], tileCenter, kShapeCoordScalar)); glsl::vec2 tangent, leftNormal, rightNormal; CalculateTangentAndNormals(p1, p2, tangent, leftNormal, rightNormal); // Fill first and last point, tangent and normals. if (!firstFilled) { firstPoint = p1; firstTangent = tangent; firstLeftNormal = leftNormal; firstRightNormal = rightNormal; firstFilled = true; } lastTangent = tangent; lastLeftNormal = leftNormal; lastRightNormal = rightNormal; lastPoint = p2; float const maskSize = static_cast<float>((path[i] - path[i - 1]).Length()); glsl::vec3 const startPivot = glsl::vec3(p1, depth); glsl::vec3 const endPivot = glsl::vec3(p2, depth); SubmitStaticVertex(startPivot, rightNormal, -1.0f, 0.0f, uvStart, staticGeometry); SubmitStaticVertex(startPivot, leftNormal, 1.0f, 0.0f, uvStart, staticGeometry); SubmitStaticVertex(endPivot, rightNormal, -1.0f, maskSize, uvEnd, staticGeometry); SubmitStaticVertex(endPivot, rightNormal, -1.0f, maskSize, uvEnd, staticGeometry); SubmitStaticVertex(startPivot, leftNormal, 1.0f, 0.0f, uvStart, staticGeometry); SubmitStaticVertex(endPivot, leftNormal, 1.0f, maskSize, uvEnd, staticGeometry); } // Generate caps. if (generateCaps && firstFilled) { int const kSegmentsCount = 4; vector<glsl::vec2> normals; normals.reserve(kAverageCapSize); GenerateCapNormals(dp::RoundCap, firstLeftNormal, firstRightNormal, -firstTangent, 1.0f, true /* isStart */, normals, kSegmentsCount); GenerateCapTriangles(glsl::vec3(firstPoint, depth), normals, colorRegion, staticGeometry); normals.clear(); GenerateCapNormals(dp::RoundCap, lastLeftNormal, lastRightNormal, lastTangent, 1.0f, false /* isStart */, normals, kSegmentsCount); GenerateCapTriangles(glsl::vec3(lastPoint, depth), normals, colorRegion, staticGeometry); } } void TrafficGenerator::GenerateLineSegment(dp::TextureManager::ColorRegion const & colorRegion, m2::PolylineD const & polyline, m2::PointD const & tileCenter, float depth, vector<TrafficLineStaticVertex> & staticGeometry) { vector<m2::PointD> const & path = polyline.GetPoints(); ASSERT_GREATER(path.size(), 1, ()); size_t const kAverageSize = path.size(); staticGeometry.reserve(staticGeometry.size() + kAverageSize); // Build geometry. glsl::vec2 const uv = glsl::ToVec2(colorRegion.GetTexRect().Center()); for (size_t i = 0; i < path.size(); ++i) { glsl::vec2 const p = glsl::ToVec2(MapShape::ConvertToLocal(path[i], tileCenter, kShapeCoordScalar)); staticGeometry.emplace_back(glsl::vec3(p, depth), uv); } } // static void TrafficGenerator::SetSimplifiedColorSchemeEnabled(bool enabled) { m_simplifiedColorScheme = enabled; } // static traffic::SpeedGroup TrafficGenerator::CheckColorsSimplification(traffic::SpeedGroup speedGroup) { // In simplified color scheme we reduce amount of speed groups visually. if (m_simplifiedColorScheme && speedGroup == traffic::SpeedGroup::G4) return traffic::SpeedGroup::G3; return speedGroup; } // static df::ColorConstant TrafficGenerator::GetColorBySpeedGroup(traffic::SpeedGroup speedGroup, bool route) { size_t constexpr kSpeedGroupsCount = static_cast<size_t>(traffic::SpeedGroup::Count); static array<df::ColorConstant, kSpeedGroupsCount> const kColorMap {{ "TrafficG0", "TrafficG1", "TrafficG2", "TrafficG3", "TrafficG4", "TrafficG5", "TrafficTempBlock", "TrafficUnknown", }}; static array<df::ColorConstant, kSpeedGroupsCount> const kColorMapRoute {{ "RouteTrafficG0", "RouteTrafficG1", "RouteTrafficG2", "RouteTrafficG3", "TrafficG4", "TrafficG5", "TrafficTempBlock", "TrafficUnknown", }}; size_t const index = static_cast<size_t>(CheckColorsSimplification(speedGroup)); ASSERT_LESS(index, kSpeedGroupsCount, ()); return route ? kColorMapRoute[index] : kColorMap[index]; } void TrafficGenerator::FillColorsCache(ref_ptr<dp::TextureManager> textures) { size_t constexpr kSpeedGroupsCount = static_cast<size_t>(traffic::SpeedGroup::Count); if (!m_colorsCacheValid) { for (size_t i = 0; i < kSpeedGroupsCount; i++) { dp::TextureManager::ColorRegion colorRegion; auto const colorConstant = GetColorBySpeedGroup(static_cast<traffic::SpeedGroup>(i), false /* route */); textures->GetColorRegion(df::GetColorConstant(colorConstant), colorRegion); m_colorsCache[i] = colorRegion; } m_colorsCacheValid = true; } } } // namespace df
36.801471
110
0.678788
ruilin
4c2500db72cf536f5754aceeb1c412e75ade4455
1,412
cpp
C++
aoj/1195/main.cpp
acm-icpc-training/acm-icpc-training
a4ee0f81a89cfe95b94c3de8521a11d61290bba3
[ "MIT" ]
null
null
null
aoj/1195/main.cpp
acm-icpc-training/acm-icpc-training
a4ee0f81a89cfe95b94c3de8521a11d61290bba3
[ "MIT" ]
null
null
null
aoj/1195/main.cpp
acm-icpc-training/acm-icpc-training
a4ee0f81a89cfe95b94c3de8521a11d61290bba3
[ "MIT" ]
null
null
null
#include <algorithm> #include <unordered_set> #include <iostream> #include <string> #include <vector> using namespace std; bool ProcessCase() { string encoded; cin >> encoded; if (encoded == "#") return false; unordered_set<string> curr_set; curr_set.insert(encoded); unordered_set<string> next_set; for (int step = 24; step >= 0; step--) { char after = 'a' + step; char before = 'a' + step + 1; for (const string& curr : curr_set) { bool end = false; for (int i = 0; i < curr.size(); i++) { if (curr[i] == before) { end = true; break; } if (curr[i] == after) { string next = curr; next[i] = before; next_set.insert(next); } } if (!end) { next_set.insert(curr); } } curr_set.swap(next_set); next_set.clear(); } vector<string> answers; answers.assign(curr_set.begin(), curr_set.end()); sort(answers.begin(), answers.end()); cout << answers.size() << endl; if (answers.size() <= 10) { for (int i = 0; i < answers.size(); ++i) { cout << answers[i] << endl; } } else { for (int i = 0; i < 5; i++) { cout << answers[i] << endl; } for (int i = answers.size() - 5; i < answers.size(); ++i) { cout << answers[i] << endl; } } return true; } int main() { while (ProcessCase()) {} return 0; }
21.074627
63
0.525496
acm-icpc-training
4c2710bc5685a5c748ce3c4505b334a480be6ce6
1,128
cpp
C++
src/Engine.cpp
nsierra-/DotEngine
07d0d9bc6cf5238d9e94e6f538298b89d51832e5
[ "MIT" ]
null
null
null
src/Engine.cpp
nsierra-/DotEngine
07d0d9bc6cf5238d9e94e6f538298b89d51832e5
[ "MIT" ]
null
null
null
src/Engine.cpp
nsierra-/DotEngine
07d0d9bc6cf5238d9e94e6f538298b89d51832e5
[ "MIT" ]
null
null
null
#include "Engine.hpp" #include "Logger.hpp" namespace Dot { Engine::Engine() : _running(true), _window(sf::VideoMode(800, 600), "DotEngine") { } void Engine::handleEvents(void) { Logger::debug("Engine - handleEvents()"); _retrieveEvents(); _statesManager.handleEvents(this); } void Engine::update(void) { Logger::debug("Engine - update()"); _statesManager.update(this); } void Engine::draw(void) { Logger::debug("Engine - draw()"); _statesManager.draw(this); } void Engine::_retrieveEvents(void) { sf::Event * tmp = new sf::Event; _events.clear(); while (_window.pollEvent(*tmp)) { if (tmp->type == sf::Event::Closed) { _running = false; delete tmp; return ; } _events.push_back(std::unique_ptr<sf::Event>(tmp)); tmp = new sf::Event; } delete tmp; } void Engine::loop(void) { while (_running) { handleEvents(); update(); draw(); } } void Engine::pushState(AGameState * state) { _statesManager.pushState(state); } void Engine::popState(void) { _statesManager.popState(); } bool Engine::isRunning() const { return _running; } }
17.353846
80
0.640071
nsierra-
4c276fd69fe70021e55ab4059c738da69f267136
2,521
cpp
C++
test_json.cpp
6502/jsoncpp
934481de03c373ee5299b8f880e0179a9d3a0030
[ "MIT" ]
2
2016-10-25T09:31:08.000Z
2018-11-10T07:42:29.000Z
test_json.cpp
6502/jsoncpp
934481de03c373ee5299b8f880e0179a9d3a0030
[ "MIT" ]
null
null
null
test_json.cpp
6502/jsoncpp
934481de03c373ee5299b8f880e0179a9d3a0030
[ "MIT" ]
null
null
null
#include "json.h" using JSON::Value; int main() { Value v; v["x"][2]["y"] = "Test"; v["a"] = false; v["b"] = 3.141592654; Value& vv = v["c"]; vv[0] = 42; vv[2] = "Foo"; vv[4]["x"] = 10; vv[4]["y"] = 20; std::vector< std::vector<int> > vvi(2); vvi[0].push_back(1); vvi[0].push_back(2); vvi[0].push_back(3); vvi[1].push_back(4); vvi[1].push_back(5); vvi[1].push_back(6); v["c"][5] = vvi; std::vector< std::vector<int> > vvi_b = v["c"][5]; v["c"][6] = vvi_b; v["c"][6][0][0] = std::string(v["c"][2]) + "\n"; std::string s = JSON::json(v); printf("%s\n", s.c_str()); const char *p = s.c_str(); Value v2 = JSON::parse(p); printf("%s\n", JSON::json(v2).c_str()); Value& path = v["path"]; for (int i=0; i<1000; i++) { path[i]["x"] = 10.0 / (i+1); path[i]["y"] = 20.0 / (i+1); } { clock_t start = clock(); for (int i=0; i<1000; i++) { v["path2"] = v["path"]; } clock_t stop = clock(); printf("Assignment = %0.3fms\n", double(stop-start) / CLOCKS_PER_SEC); } { clock_t start = clock(); for (int i=0; i<1000; i++) { std::string s = JSON::json(v["path"]); } clock_t stop = clock(); printf("obj -> JSON = %0.3fms\n", double(stop-start) / CLOCKS_PER_SEC); } { std::string s = JSON::json(v["path"]); clock_t start = clock(); for (int i=0; i<1000; i++) { const char *p = s.c_str(); v["path"] = JSON::parse(p); } clock_t stop = clock(); printf("JSON -> obj = %0.3fms\n", double(stop-start) / CLOCKS_PER_SEC); printf("data = %i bytes\n", int(s.size())); } { clock_t start = clock(); for (int i=0; i<1000; i++) { std::vector<unsigned char> buf; JSON::save(v["path"], buf); } clock_t stop = clock(); printf("obj -> buf = %0.3fms\n", double(stop-start) / CLOCKS_PER_SEC); } { clock_t start = clock(); std::vector<unsigned char> buf; JSON::save(v["path"], buf); for (int i=0; i<1000; i++) { Value x; const unsigned char *p = &buf[0]; JSON::load(x, p); } clock_t stop = clock(); printf("buf -> obj = %0.3fms\n", double(stop-start) / CLOCKS_PER_SEC); printf("data = %i bytes\n", int(buf.size())); } return 0; }
25.72449
79
0.455375
6502
4c295f55b985099b580bdbc8686857ddc049022b
189
cpp
C++
258-add-digits/258-add-digits.cpp
ComputerScientist-01/SDE-Sheet
e0ebd6e6a21ed07ce0a1ae123f552e7a4da3ac3a
[ "MIT" ]
null
null
null
258-add-digits/258-add-digits.cpp
ComputerScientist-01/SDE-Sheet
e0ebd6e6a21ed07ce0a1ae123f552e7a4da3ac3a
[ "MIT" ]
null
null
null
258-add-digits/258-add-digits.cpp
ComputerScientist-01/SDE-Sheet
e0ebd6e6a21ed07ce0a1ae123f552e7a4da3ac3a
[ "MIT" ]
null
null
null
class Solution { public: int addDigits(int num) { // we use the property of 9 if(num == 0) return 0; if(num % 9 == 0 ) return 9; return (num%9); } };
21
35
0.492063
ComputerScientist-01
4c296640cc8de970340275d0c02e70352695760f
1,276
cpp
C++
kickstart/2019/round c/circuit_board.cpp
Surya-06/My-Solutions
58f7c7f1a0a3a28f25eff22d03a09cb2fbcf7806
[ "MIT" ]
null
null
null
kickstart/2019/round c/circuit_board.cpp
Surya-06/My-Solutions
58f7c7f1a0a3a28f25eff22d03a09cb2fbcf7806
[ "MIT" ]
null
null
null
kickstart/2019/round c/circuit_board.cpp
Surya-06/My-Solutions
58f7c7f1a0a3a28f25eff22d03a09cb2fbcf7806
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; typedef long long int llint; llint calc(void) { llint r, c, req; cin >> r >> c >> req; vector<vector<llint>> grid(r, vector<llint>(c)); for (llint i = 0; i < r; i++) for (llint j = 0; j < c; j++) cin >> grid[i][j]; llint min_value = -1, max_value = -1; for (llint i = 0; i < r; i++) for (llint j = 0; j < c; j++) { llint count = 1; min_value = grid[i][j], max_value = grid[i][j]; for (llint k = j + 1; k < c; k++) { min_value = min(min_value, grid[i][k]), max_value = max(max_value, grid[i][k]); if (max_value - min_value <= req) count += 1; else break; } grid[i][j] = count; } llint answer = -1; for (llint j = 0; j < c; j++) for (llint i = 0; i < r; i++) { llint min_value = grid[i][j]; answer = max(answer, min_value); for (llint k = i + 1; k < r; k++) { min_value = min(min_value, grid[k][j]); answer = max(answer, min_value * (k - i + 1)); } } return answer; } int main() { llint t; cin >> t; for (llint i = 1; i <= t; i++) { llint answer = calc(); cout << "Case #" << i << ": " << answer; if (i < t) cout << endl; } return 0; }
25.019608
54
0.474922
Surya-06
4c29f12f57e0613478b5209d1726665f0c5f6e85
2,651
cpp
C++
KRIGInputWidget.cpp
jonathanyxchen/quoFEM-UQPy
0cbbe2935ea3bc337fca8e8894c44825d7d36b32
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
KRIGInputWidget.cpp
jonathanyxchen/quoFEM-UQPy
0cbbe2935ea3bc337fca8e8894c44825d7d36b32
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
KRIGInputWidget.cpp
jonathanyxchen/quoFEM-UQPy
0cbbe2935ea3bc337fca8e8894c44825d7d36b32
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
#include <KRIGInputWidget.h> #include <QLineEdit> #include <QVBoxLayout> #include <QLabel> #include <QValidator> #include <QJsonObject> KRIGInputWidget::KRIGInputWidget(QWidget *parent) : UQ_MethodInputWidget(parent) { auto layout = new QGridLayout(); // create layout label and entry for # samples numSamples = new QLineEdit(); numSamples->setText(tr("500")); numSamples->setValidator(new QIntValidator); numSamples->setToolTip("Specify the number of samples"); layout->addWidget(new QLabel("# Samples"), 0, 0); layout->addWidget(numSamples, 0, 1); // create label and entry for seed to layout // srand(time(NULL)); // int randomNumber = rand() % 1000 + 1; // randomSeed = new QLineEdit(); // randomSeed->setText(QString::number(randomNumber)); // randomSeed->setValidator(new QIntValidator); // randomSeed->setToolTip("Set the seed"); // layout->addWidget(new QLabel("Seed"), 1, 0); // layout->addWidget(randomSeed, 1, 1); QLineEdit * weightsErrors = new QLineEdit(); layout->addWidget(new QLabel("weights-errors"), 1, 0); layout->addWidget(weightsErrors, 1, 1); QLineEdit * weightsDistribution = new QLineEdit(); layout->addWidget(new QLabel("weights-distribution"), 2, 0); layout->addWidget(weightsDistribution, 2, 1); QLineEdit * weightsMoments = new QLineEdit(); layout->addWidget(new QLabel("weights-moments"), 3, 0); layout->addWidget(weightsMoments, 3, 1); QLineEdit * weightsCorrelation = new QLineEdit(); layout->addWidget(new QLabel("weights-correlation"), 4, 0); layout->addWidget(weightsCorrelation, 4, 1); QLineEdit * properties = new QLineEdit(); layout->addWidget(new QLabel("properties"), 5, 0); layout->addWidget(properties, 5, 1); layout->setRowStretch(2, 1); layout->setColumnStretch(2, 1); this->setLayout(layout); } KRIGInputWidget::~KRIGInputWidget() { } bool KRIGInputWidget::outputToJSON(QJsonObject &jsonObj){ bool result = true; jsonObj["samples"]=numSamples->text().toInt(); jsonObj["seed"]=randomSeed->text().toDouble(); return result; } bool KRIGInputWidget::inputFromJSON(QJsonObject &jsonObject){ bool result = false; if (jsonObject.contains("samples") && jsonObject.contains("seed")) { int samples=jsonObject["samples"].toInt(); double seed=jsonObject["seed"].toDouble(); numSamples->setText(QString::number(samples)); randomSeed->setText(QString::number(seed)); result = true; } return result; } void KRIGInputWidget::clear(void) { } int KRIGInputWidget::getNumberTasks() { return numSamples->text().toInt(); }
25.490385
70
0.685025
jonathanyxchen
4c2d5e5e00ca4b86193b4e1d7f83654af69f1384
3,199
cpp
C++
thirdparty/boost_1_71_0/libs/test/doc/examples/runtime-configuration_4.run-fail.cpp
anonymouscode1/djxperf
b6073a761753aa7a6247f2618977ca3a2633e78a
[ "MIT" ]
155
2015-01-19T11:00:04.000Z
2022-03-17T03:08:16.000Z
3rdparty/boost_1_73_0/libs/test/doc/examples/runtime-configuration_4.run-fail.cpp
qingkouwei/mediaones
cec475e1bfd5807b5351cc7e38d244ac5298ca16
[ "MIT" ]
266
2015-01-05T02:03:25.000Z
2022-03-25T12:22:12.000Z
3rdparty/boost_1_73_0/libs/test/doc/examples/runtime-configuration_4.run-fail.cpp
qingkouwei/mediaones
cec475e1bfd5807b5351cc7e38d244ac5298ca16
[ "MIT" ]
185
2015-01-03T18:09:54.000Z
2022-01-31T18:07:05.000Z
// Copyright (c) 2019 Raffi Enficiaud // 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) // See http://www.boost.org/libs/test for the library home page. //[example_code #define BOOST_TEST_MODULE runtime_configuration4 #include <boost/test/included/unit_test.hpp> #include <boost/test/data/test_case.hpp> #include <iostream> #include <functional> #include <sstream> #include <fstream> // this dataset loads a file that contains a list of strings // this list is used to create a dataset test case. class file_dataset { private: std::string m_filename; std::size_t m_line_start; std::size_t m_line_end; public: enum { arity = 2 }; public: file_dataset(std::size_t line_start = 0, std::size_t line_end = std::size_t(-1)) : m_line_start(line_start) , m_line_end(line_end) { int argc = boost::unit_test::framework::master_test_suite().argc; char** argv = boost::unit_test::framework::master_test_suite().argv; if(argc != 3) throw std::logic_error("Incorrect number of arguments"); if(std::string(argv[1]) != "--test-file") throw std::logic_error("First argument != '--test-file'"); if(!(m_line_start < std::size_t(-1))) throw std::logic_error("Incorrect line start/end"); m_filename = argv[2]; std::ifstream file(m_filename); if(!file.is_open()) throw std::logic_error("Cannot open the file '" + m_filename + "'"); std::size_t nb_lines = std::count_if( std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>(), [](char c){ return c == '\n';}); m_line_end = (std::min)(nb_lines, m_line_end); if(!(m_line_start <= m_line_end)) throw std::logic_error("Incorrect line start/end"); } struct iterator { iterator(std::string const& filename, std::size_t line_start) : file(filename, std::ios::binary) { if(!file.is_open()) throw std::runtime_error("Cannot open the file"); for(std::size_t i = 0; i < line_start; i++) { getline(file, m_current_line); } } auto operator*() const -> std::tuple<float, float> { float a, b; std::istringstream istr(m_current_line); istr >> a >> b; return std::tuple<float, float>(a, b); } void operator++() { getline(file, m_current_line); } private: std::ifstream file; std::string m_current_line; }; // size of the DS boost::unit_test::data::size_t size() const { return m_line_end - m_line_start; } // iterator over the lines of the file iterator begin() const { return iterator(m_filename, m_line_start); } }; namespace boost { namespace unit_test { namespace data { namespace monomorphic { template <> struct is_dataset<file_dataset> : boost::mpl::true_ {}; } }}} BOOST_DATA_TEST_CASE(command_line_test_file, boost::unit_test::data::make_delayed<file_dataset>( 3, 10 ), input, expected) { BOOST_TEST(input <= expected); } //]
28.81982
84
0.629884
anonymouscode1
4c2e2b46ae909c69019d6a7028002f03b7417a0e
1,932
cpp
C++
src/wm_objects/Objects.cpp
fmrico/WaterMellon
5d61914d9597118735e933e6d61a7e7872d83f5a
[ "BSD-3-Clause" ]
1
2017-02-23T02:05:57.000Z
2017-02-23T02:05:57.000Z
src/wm_objects/Objects.cpp
fmrico/WaterMellon
5d61914d9597118735e933e6d61a7e7872d83f5a
[ "BSD-3-Clause" ]
null
null
null
src/wm_objects/Objects.cpp
fmrico/WaterMellon
5d61914d9597118735e933e6d61a7e7872d83f5a
[ "BSD-3-Clause" ]
null
null
null
/* * Objects.cpp * * Created on: 11/10/2015 * Author: paco */ #include "wm_objects/Objects.h" #include <fstream> #include <streambuf> #include <string> namespace wm_objects { Objects::Objects() :objects_() { } Objects::~Objects() { } void Objects::readFile(std::string filename) { if(filename!="") { std::ifstream t(filename.c_str()); std::stringstream buffer; buffer << t.rdbuf(); Json::Value root; // will contains the root value after parsing. Json::Reader reader; bool parsingSuccessful = reader.parse( buffer.str(), root ); if ( !parsingSuccessful ) { // report to the user the failure and their objects in the document. std::cerr << "Failed to parse configuration\n" << reader.getFormattedErrorMessages(); return; } Json::Value objects = root["objects"]; if(objects.isArray()) { for(int i=0; i< objects.size(); i++) { if(objects[i].isMember("name") && objects[i].isMember("filename")) { Json::Value name = objects[i]["name"]; Json::Value filename = objects[i]["filename"]; objects_[name.asString()] = filename.asString(); } } } } } void Objects::printObjects() { std::map<std::string, std::string>::iterator it; for(it=objects_.begin(); it!=objects_.end();++it) std::cout<<"["<<it->first<<"] (" <<it->second<<")"<<std::endl; } std::string Objects::getFilename(const std::string& obj_id) { std::map<std::string, std::string>::iterator it = objects_.find(obj_id); if(it != objects_.end()) return it->second; else { ROS_ERROR("Object [%s] does not exist", objects_[obj_id].c_str()); return ""; } } std::list<std::string> Objects::getAvailableObjects() { std::list<std::string> object_list; std::map<std::string, std::string>::iterator it; for(it=objects_.begin(); it!=objects_.end();++it) object_list.push_back(it->first); return object_list; } } /* namespace wm_navigation */
17.724771
74
0.635093
fmrico
4c2e5c096d5deddf10ce1cb14fc8826ed0c5e871
579
cpp
C++
src/env.cpp
ibradypod/bradypod
cd3b0bc156d7fccb1b8efb2b02163dca46c366d7
[ "BSD-3-Clause" ]
3
2018-03-05T15:29:42.000Z
2018-03-07T01:54:11.000Z
src/env.cpp
ibradypod/bradypod
cd3b0bc156d7fccb1b8efb2b02163dca46c366d7
[ "BSD-3-Clause" ]
null
null
null
src/env.cpp
ibradypod/bradypod
cd3b0bc156d7fccb1b8efb2b02163dca46c366d7
[ "BSD-3-Clause" ]
null
null
null
#include "env.h" #include <QCoreApplication> #include <QString> #include <QVariantMap> #include <QProcessEnvironment> static Env* env_instance = NULL; Env* Env::instance() { if (NULL == env_instance) { env_instance = new Env(); } return env_instance; } Env::Env() : QObject(QCoreApplication::instance()) { const QProcessEnvironment& env = QProcessEnvironment::systemEnvironment(); foreach(const QString & key, env.keys()) { m_map[key] = env.value(key); } } // public: QVariantMap Env::asVariantMap() const { return m_map; }
17.029412
78
0.658031
ibradypod
4c32df3f96185150890e6b58f2b995ed6470d32e
463
cpp
C++
Questions Level-Wise/Medium/count-nice-pairs-in-an-array.cpp
PrakharPipersania/LeetCode-Solutions
ea74534bbdcf1ca3ea4d88a1081582e0e15f50c7
[ "MIT" ]
2
2021-03-05T22:32:23.000Z
2021-03-05T22:32:29.000Z
Questions Level-Wise/Medium/count-nice-pairs-in-an-array.cpp
PrakharPipersania/LeetCode-Solutions
ea74534bbdcf1ca3ea4d88a1081582e0e15f50c7
[ "MIT" ]
null
null
null
Questions Level-Wise/Medium/count-nice-pairs-in-an-array.cpp
PrakharPipersania/LeetCode-Solutions
ea74534bbdcf1ca3ea4d88a1081582e0e15f50c7
[ "MIT" ]
null
null
null
class Solution { public: int rev(int num) { int t=0; while(num>0) t=(t*10)+(num%10),num/=10; return t; } int countNicePairs(vector<int>& nums) { int c=0; unordered_map<int,int> x; for(int i=0;i<nums.size();i++) x[nums[i]-rev(nums[i])]++; for(auto e: x) c=(c+((((long)e.second*(long)(e.second-1))/2)%1000000007))%1000000007; return c; } };
23.15
82
0.464363
PrakharPipersania
4c3370c1c627b7857e4423d1aeaf009ac6d23811
2,219
cpp
C++
projects/acommandline/test/repeated_test.cpp
agnesoft/adev-alt
3df0329939e3048bbf5db252efb5f74de9c0f061
[ "Apache-2.0" ]
null
null
null
projects/acommandline/test/repeated_test.cpp
agnesoft/adev-alt
3df0329939e3048bbf5db252efb5f74de9c0f061
[ "Apache-2.0" ]
136
2020-03-29T11:15:38.000Z
2020-10-14T06:21:23.000Z
projects/acommandline/test/repeated_test.cpp
agnesoft/adev-alt
3df0329939e3048bbf5db252efb5f74de9c0f061
[ "Apache-2.0" ]
1
2020-08-04T09:56:53.000Z
2020-08-04T09:56:53.000Z
import atest; import acommandline; using ::atest::expect; using ::atest::suite; using ::atest::test; static const auto S = suite("repeated", [] { // NOLINT(cert-err58-cpp) test("single named", [] { std::stringstream stream; ::acommandline::CommandLine commandLine{stream}; std::vector<std::string> values; commandLine.option().long_name("name1").description("").bind_to(&values); expect(commandLine.parse(2, std::array<const char *, 2>{"./app", "--name1=val"}.data())).to_be(true); expect(values).to_be(std::vector<std::string>{"val"}); }); test("named", [] { std::stringstream stream; ::acommandline::CommandLine commandLine{stream}; std::vector<double> values; static constexpr int argc = 7; commandLine.option().long_name("value").short_name('v').description("").bind_to(&values); expect(commandLine.parse(argc, std::array<const char *, argc>{"./app", "-v", "33.3", "--value=51.61234", "-v=9.999", "-v", "19.19"}.data())).to_be(true); expect(values).to_be(std::vector{33.3, 51.61234, 9.999, 19.19}); // NOLINT(cppcoreguidelines-avoid-magic-numbers,readability-magic-numbers) }); test("single positional", [] { std::stringstream stream; ::acommandline::CommandLine commandLine{stream}; std::vector<std::int64_t> values; commandLine.option().positional().description("").bind_to(&values); expect(commandLine.parse(2, std::array<const char *, 2>{"./app", "1350"}.data())).to_be(true); expect(values).to_be(std::vector<std::int64_t>{1350}); // NOLINT(cppcoreguidelines-avoid-magic-numbers,readability-magic-numbers) }); test("positional", [] { std::stringstream stream; ::acommandline::CommandLine commandLine{stream}; std::vector<std::string> values; commandLine.option().positional().default_value(std::vector<std::string>{"input"}).description("").bind_to(&values); expect(commandLine.parse(4, std::array<const char *, 4>{"./app", "input1", "input2", "input3"}.data())).to_be(true); expect(values).to_be(std::vector<std::string>{"input1", "input2", "input3"}); }); });
38.929825
161
0.626408
agnesoft
4c33c36926beaa4f6ea1988c79e0984e52a259b9
3,616
hpp
C++
source/Math.hpp
Amaranese/mario-bros-cplusplus
b5aefffbd3650cfa0ff5e846f43748efde8666c5
[ "Unlicense" ]
1
2021-08-15T00:37:29.000Z
2021-08-15T00:37:29.000Z
source/Math.hpp
Amaranese/mario-bros-cplusplus
b5aefffbd3650cfa0ff5e846f43748efde8666c5
[ "Unlicense" ]
null
null
null
source/Math.hpp
Amaranese/mario-bros-cplusplus
b5aefffbd3650cfa0ff5e846f43748efde8666c5
[ "Unlicense" ]
null
null
null
/** * @file * @brief defines math stuff. */ #ifndef MATH_HPP #define MATH_HPP #include <cmath> #include "Vector2.hpp" #include "Vector3.hpp" //Constants static const double PI = 4.0 * std::atan(1.0); /** Pi. */ //Non-Templated funcitons /** * This performs a modulus that has the appearance of a sawtooth wave for all numbers. * @todo this needs a better name. */ int saw(int a, int b); //Templated functions /** * Clamp a value to a range. * * @param min the minimum value. * @param max the maxmimum value. */ template <typename T> T clamp(T value, T min, T max) { if( value < min ) { return min; } if( value > max ) { return max; } return value; } /** * Clamp a value to a domain, wrapping around when the range is exceeded. * * @param value the value to clamp. * @param domain the maximum value that the value can have before being * modified. */ template <typename T> void clampDomain(T& value, unsigned domain) { //Adjust for negative values by sticking them in a sawtooth function //and by adding the fractional part back in value = (T)saw((int)std::floor(value), domain) + (value - std::floor(value)); } /** * Calculate the cross product of two vectors. * * @param u the first vector. * @param v the second vector. * @return the cross product. */ template <typename T> Vector3<T> cross( const Vector3<T>& u, const Vector3<T>& v ) { Vector3<T> t; t.x = (u.y * v.z) - (u.z * v.y); t.y = (u.z * v.x) - (u.x * v.z); t.z = (u.x * v.y) - (u.y * v.x); return t; } /** * Calculate the dot product of two vectors. * * @param u the first vector. * @param v the second vector. * @return the dot product. */ template <typename T> T dot( const Vector2<T>& u, const Vector2<T>& v ) { return (u.x * v.x) + (u.y * v.y); } /** * Calculate the dot product of two vectors. * * @param u the first vector. * @param v the second vector. * @return the dot product. */ template <typename T> T dot( const Vector3<T>& u, const Vector3<T>& v ) { return (u.x * v.x) + (u.y * v.y) + (u.z * v.z); } /** * This smooths out a value from 0 to 1 in the same range as a curve. * * @param x the value. * @return the faded value. */ template <typename T> T fade(T x) { // 6x^15 - 15x^4 + 10x^3 return x * x * x * (x * (x * 6.0 - 15.0) + 10.0); } /** * Fast floor to integer. */ template <typename T> int fastFloor( T x ) { int i = (int)x; // truncate return i - (i > x); // convert to floor for negatives } /** * Get the fractional part of a floating-point number. * * @param value the value. * @return the fractional part of the value. */ template <typename T> T fraction( T value ) { double dummy; return modf(value, &dummy); } /** * Perform linear interpolation between two values. * * @param a the lower value. * @param b the upper value. * @param x the weight between the two values in the range [0, 1]. * @return the interpolated value. */ template <typename T> T lerp(T a, T b, T x) { return a * (1.0 - x) + b * x; } /** * Convert a value in the range [-1, 1] to one in the range [0, 1]. * * @param n the value. * @return the converted value. */ template <typename T> T normalizePositive(T n) { return (n + 1.0) / 2.0; } /** * Convert a value in the range [0, 1] to one in the range [-1, 1]. * * @param n the value. * @return the converted value. */ template <typename T> T normalizeReal(T n) { return (n * 2.0) - 1.0; } /** * Get the sign of a number. * * @param n the value. * @return the sign of the number as -1 or 1. */ template <typename T> T sign(T n) { if( n < 0 ) { return -1; } return 1; } #endif // MATH_HPP
18.54359
85
0.621405
Amaranese
4c3984bc3005960c087f0b4d701a9d4caba60fda
1,057
cc
C++
cpp/leetcode/451.sort-characters-by-frequency.cc
liubang/laboratory
747f239a123cd0c2e5eeba893b9a4d1536555b1e
[ "MIT" ]
3
2021-03-03T13:18:23.000Z
2022-02-09T07:49:24.000Z
cpp/leetcode/451.sort-characters-by-frequency.cc
liubang/laboratory
747f239a123cd0c2e5eeba893b9a4d1536555b1e
[ "MIT" ]
null
null
null
cpp/leetcode/451.sort-characters-by-frequency.cc
liubang/laboratory
747f239a123cd0c2e5eeba893b9a4d1536555b1e
[ "MIT" ]
1
2021-03-29T15:21:42.000Z
2021-03-29T15:21:42.000Z
#include <gtest/gtest.h> #include <algorithm> #include <string> #include <unordered_map> namespace { class Solution { public: std::string frequencySort(const std::string& s) { std::unordered_map<char, int> charcount; for (auto& ch : s) { charcount[ch]++; } std::vector<std::pair<char, int>> v(charcount.begin(), charcount.end()); std::sort(v.begin(), v.end(), [](const auto& lhs, const auto& rhs) { return lhs.second > rhs.second; }); std::string ret; for (auto& p : v) { ret.append(p.second, p.first); } return ret; } }; } // namespace TEST(Leetcode, sort_characters_by_frequency) { Solution s; { std::string input = "tree"; auto ret = s.frequencySort(input); EXPECT_TRUE(ret == "eetr" || ret == "eert"); } { std::string input = "cccaaa"; auto ret = s.frequencySort(input); EXPECT_TRUE(ret == "cccaaa" || ret == "aaaccc"); } { std::string input = "Aabb"; auto ret = s.frequencySort(input); EXPECT_TRUE(ret == "bbaA" || ret == "bbAa"); } }
22.978261
76
0.589404
liubang
4c3be975324d4c979442a56019d9e3ddc8edb0c8
567
cpp
C++
src/cells/src/lib/logic/effect/buff/Slow.cpp
SimonPiCarter/GameEngine
10d366bd37d202a5a22eb504b2a2dd9a49669dc8
[ "Apache-2.0" ]
null
null
null
src/cells/src/lib/logic/effect/buff/Slow.cpp
SimonPiCarter/GameEngine
10d366bd37d202a5a22eb504b2a2dd9a49669dc8
[ "Apache-2.0" ]
15
2021-05-18T14:16:03.000Z
2021-06-17T19:36:32.000Z
src/cells/src/lib/logic/effect/buff/Slow.cpp
SimonPiCarter/GameEngine
10d366bd37d202a5a22eb504b2a2dd9a49669dc8
[ "Apache-2.0" ]
null
null
null
#include "Slow.h" #include <cassert> #include "logic/entity/MobEntity.h" Slow::Slow(MobEntity * target_p, std::string id_p, double spawntime_p, double duration_p, double slow_p, unsigned long maxStack_p) : BuffTimer(target_p, id_p, spawntime_p, duration_p, maxStack_p) , _slow(slow_p) { assert(_slow > 1e-5); assert(_slow < 1.-1e-5); } void Slow::applyBuff() { _mobTarget->setSpeed(_mobTarget->getSpeed() * (1.-std::min(0.99,(_slow*_stack)))); } void Slow::revertBuff() { _mobTarget->setSpeed(_mobTarget->getSpeed() * (1.-std::min(0.99,(_slow*_stack)))); }
24.652174
130
0.705467
SimonPiCarter
4c3e7de4cc2769551a5a667eac89c1b621ae1049
11,672
cpp
C++
src/unit_tests/parallel/utest_PAR_bodyauxref.cpp
andrewseidl/chrono
ec3d1689fa4d1ca40ef6d9ffdd2f509c0dc2cecd
[ "BSD-3-Clause" ]
null
null
null
src/unit_tests/parallel/utest_PAR_bodyauxref.cpp
andrewseidl/chrono
ec3d1689fa4d1ca40ef6d9ffdd2f509c0dc2cecd
[ "BSD-3-Clause" ]
null
null
null
src/unit_tests/parallel/utest_PAR_bodyauxref.cpp
andrewseidl/chrono
ec3d1689fa4d1ca40ef6d9ffdd2f509c0dc2cecd
[ "BSD-3-Clause" ]
null
null
null
// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All right reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Radu Serban // ============================================================================= // // Test for ChBodyAuxRef (body defined with respect to a non-centroidal frame), // using two identical pendulums, modeled as a ChBody and as a ChBodyAuxRef, // respectively. // // The two pendulums have length 2 and are pinned to ground through revolute // joints with the rotation axis along the global Y axis. The absolute locations // of the revolute joints are at (0, 1, 0) and (0, -1, 0), respectively. // // The ChBody pendulum is defined with respect to a centroidal frame (as assumed // by ChBody) located at the geometric center of the pendulum, with the X axis // along the length of the pendulum. // The ChBodyAuxRef pendulum is defined with respect to a local frame, parallel // to its centroidal frame but located at the pin location. In other words, the // center of mass of the pendulum is at (1, 0, 0), relative to the body frame. // // The two pendulums move under the action of gravity, acting along the negative // global Z direction. // // ============================================================================= #include "chrono_parallel/physics/ChSystemParallel.h" #include "chrono/ChConfig.h" #include "chrono/utils/ChUtilsCreators.h" #include "chrono/utils/ChUtilsInputOutput.h" #ifdef CHRONO_OPENGL #include "chrono_opengl/ChOpenGLWindow.h" #endif using namespace chrono; using namespace chrono::collision; // Function declarations. bool VerifySolution(double time, std::shared_ptr<ChBody> pend_1, std::shared_ptr<ChBodyAuxRef> pend_2); // ----------------------------------------------------------------------------- // Main driver function for running the simulation and validating the results. // ----------------------------------------------------------------------------- int main(int argc, char* argv[]) { // No animation by default (i.e. when no program arguments) bool animate = (argc > 1); // Settings //--------- int threads = 1; bool thread_tuning = false; double time_end = 5; double time_step = 1e-3; double tolerance = 1e-5; int max_iteration_bilateral = 100; int max_iteration_normal = 0; int max_iteration_sliding = 100; int max_iteration_spinning = 0; bool clamp_bilaterals = false; double bilateral_clamp_speed = 1000; double contact_recovery_speed = 1; // Create the mechanical system // ---------------------------- ChSystemParallelDVI* system = new ChSystemParallelDVI(); system->Set_G_acc(ChVector<>(0, 0, -9.81)); // Set number of threads. CHOMPfunctions::SetNumThreads(threads); system->GetSettings()->max_threads = threads; system->GetSettings()->perform_thread_tuning = thread_tuning; // Edit system settings system->GetSettings()->solver.tolerance = tolerance; system->GetSettings()->solver.max_iteration_bilateral = max_iteration_bilateral; system->GetSettings()->solver.clamp_bilaterals = clamp_bilaterals; system->GetSettings()->solver.bilateral_clamp_speed = bilateral_clamp_speed; system->GetSettings()->solver.solver_mode = SolverMode::SLIDING; system->GetSettings()->solver.max_iteration_normal = max_iteration_normal; system->GetSettings()->solver.max_iteration_sliding = max_iteration_sliding; system->GetSettings()->solver.max_iteration_spinning = max_iteration_spinning; system->ChangeSolverType(SolverType::APGD); // Define a couple of rotations for later use ChQuaternion<> y2x; ChQuaternion<> z2y; y2x.Q_from_AngZ(-CH_C_PI / 2); z2y.Q_from_AngX(-CH_C_PI / 2); // Create the ground body // ---------------------- auto ground = std::make_shared<ChBody>(std::make_shared<ChCollisionModelParallel>()); ground->SetBodyFixed(true); system->AddBody(ground); // Attach a visualization asset representing the Y axis. auto box = std::make_shared<ChBoxShape>(); box->GetBoxGeometry().Size = ChVector<>(0.02, 3, 0.02); ground->AddAsset(box); // Create a pendulum modeled using ChBody // -------------------------------------- auto pend_1 = std::make_shared<ChBody>(std::make_shared<ChCollisionModelParallel>()); system->AddBody(pend_1); pend_1->SetIdentifier(1); pend_1->SetBodyFixed(false); pend_1->SetCollide(false); pend_1->SetMass(1); pend_1->SetInertiaXX(ChVector<>(0.2, 1, 1)); // Attach a visualization asset. Note that the cylinder is defined with // respect to the centroidal reference frame (which is the body reference // frame for a ChBody). auto cyl_1 = std::make_shared<ChCylinderShape>(); cyl_1->GetCylinderGeometry().p1 = ChVector<>(0, -1, 0); cyl_1->GetCylinderGeometry().p2 = ChVector<>(0, 1, 0); cyl_1->GetCylinderGeometry().rad = 0.2; cyl_1->Pos = ChVector<>(0, 0, 0); cyl_1->Rot = y2x; pend_1->AddAsset(cyl_1); auto col_1 = std::make_shared<ChColorAsset>(); col_1->SetColor(ChColor(0.6f, 0, 0)); pend_1->AddAsset(col_1); // Specify the initial position of the pendulum (horizontal, pointing towards // positive X). In this case, we set the absolute position of its center of // mass. pend_1->SetPos(ChVector<>(1, 1, 0)); // Create a revolute joint to connect pendulum to ground. We specify the link // coordinate frame in the absolute frame. auto rev_1 = std::make_shared<ChLinkLockRevolute>(); rev_1->Initialize(ground, pend_1, ChCoordsys<>(ChVector<>(0, 1, 0), z2y)); system->AddLink(rev_1); // Create a pendulum modeled using ChBodyAuxRef // -------------------------------------------- auto pend_2 = std::make_shared<ChBodyAuxRef>(std::make_shared<ChCollisionModelParallel>()); system->Add(pend_2); pend_2->SetIdentifier(2); pend_2->SetBodyFixed(false); pend_2->SetCollide(false); pend_2->SetMass(1); pend_2->SetInertiaXX(ChVector<>(0.2, 1, 1)); // NOTE: the inertia tensor must still be expressed in the centroidal frame! // Attach a visualization asset. Note that now the cylinder is defined with // respect to the body reference frame. auto cyl_2 = std::make_shared<ChCylinderShape>(); cyl_2->GetCylinderGeometry().p1 = ChVector<>(0, -1, 0); cyl_2->GetCylinderGeometry().p2 = ChVector<>(0, 1, 0); cyl_2->GetCylinderGeometry().rad = 0.2; cyl_2->Pos = ChVector<>(1, 0, 0); cyl_2->Rot = y2x; pend_2->AddAsset(cyl_2); auto col_2 = std::make_shared<ChColorAsset>(); col_2->SetColor(ChColor(0, 0, 0.6f)); pend_2->AddAsset(col_2); // In this case, we must specify the centroidal frame, relative to the body // reference frame. pend_2->SetFrame_COG_to_REF(ChFrame<>(ChVector<>(1, 0, 0), ChQuaternion<>(1, 0, 0, 0))); // Specify the initial position of the pendulum (horizontal, pointing towards // positive X). Here, we want to specify the position of the body reference // frame (relative to the absolute frame). Recall that the body reference // frame is located at the pin. pend_2->SetFrame_REF_to_abs(ChFrame<>(ChVector<>(0, -1, 0))); // Create a revolute joint to connect pendulum to ground. We specify the link // coordinate frame in the absolute frame. auto rev_2 = std::make_shared<ChLinkLockRevolute>(); rev_2->Initialize(ground, pend_2, ChCoordsys<>(ChVector<>(0, -1, 0), z2y)); system->AddLink(rev_2); // Perform the simulation // ---------------------- bool passed = true; double time = 0; if (animate) { #ifdef CHRONO_OPENGL opengl::ChOpenGLWindow& gl_window = opengl::ChOpenGLWindow::getInstance(); gl_window.Initialize(1280, 720, "BodyAuxRef", system); gl_window.SetCamera(ChVector<>(6, -6, 1), ChVector<>(0, 0, 0), ChVector<>(0, 0, 1)); gl_window.SetRenderMode(opengl::WIREFRAME); gl_window.StartDrawLoop(time_step); #else std::cout << "OpenGL support not available. Cannot animate mechanism." << std::endl; return false; #endif } else { while (time < time_end) { system->DoStepDynamics(time_step); time += time_step; if (!VerifySolution(time, pend_1, pend_2)) passed = false; } } std::cout << (passed ? "PASSED" : "FAILED") << std::endl << std::endl; // Return 0 if all tests passed and 1 otherwise return !passed; } // ----------------------------------------------------------------------------- // Verify simulation results against analytical solution at the specified time. // ----------------------------------------------------------------------------- bool VerifySolution(double time, // current time std::shared_ptr<ChBody> pend_1, // handle to ChBody pendulum std::shared_ptr<ChBodyAuxRef> pend_2) // handle to ChBodyAuxRef pendulum { // Tolerances double pos_tol = 1e-6; double vel_tol = 1e-6; double acc_tol = 1e-5; double quat_tol = 1e-6; double avel_tol = 1e-6; double aacc_tol = 1e-5; // Position and orientation of the COGs ChVector<> pos_1 = pend_1->GetPos(); ChVector<> pos_2 = pend_2->GetPos(); ChQuaternion<> quat_1 = pend_1->GetRot(); ChQuaternion<> quat_2 = pend_2->GetRot(); if (std::abs(pos_1.x() - pos_2.x()) > pos_tol) { std::cout << " at t = " << time << " pos_1.x - pos_2.x = " << pos_1.x() - pos_2.x() << std::endl; return false; } if (std::abs(pos_1.z() - pos_2.z()) > pos_tol) { std::cout << " at t = " << time << " pos_1.z - pos_2.z = " << pos_1.z() - pos_2.z() << std::endl; return false; } ChQuaternion<> quat_delta = quat_1 - quat_2; if (quat_delta.Length() > quat_tol) { std::cout << " at t = " << time << " quat_1 - quat_2 = " << quat_delta.e0() << " " << quat_delta.e1() << " " << quat_delta.e2() << " " << quat_delta.e3() << std::endl; return false; } // Linear and angular velocities of the COGs (expressed in global frame) ChVector<> vel_1 = pend_1->GetPos_dt(); ChVector<> vel_2 = pend_2->GetPos_dt(); ChVector<> avel_1 = pend_1->GetWvel_par(); ChVector<> avel_2 = pend_2->GetWvel_par(); ChVector<> vel_delta = vel_1 - vel_2; if (vel_delta.Length() > vel_tol) { std::cout << " at t = " << time << " vel_1 - vel_2 = " << vel_delta.x() << " " << vel_delta.y() << " " << vel_delta.z() << std::endl; return false; } ChVector<> avel_delta = avel_1 - avel_2; if (avel_delta.Length() > avel_tol) { std::cout << " at t = " << time << " avel_1 - avel_2 = " << avel_delta.x() << " " << avel_delta.y() << " " << avel_delta.z() << std::endl; return false; } // Linear and angular accelerations of the COGs (expressed in global frame) ChVector<> acc_1 = pend_1->GetPos_dtdt(); ChVector<> acc_2 = pend_2->GetPos_dtdt(); ChVector<> aacc_1 = pend_1->GetWacc_par(); ChVector<> aacc_2 = pend_2->GetWacc_par(); ChVector<> acc_delta = acc_1 - acc_2; if (acc_delta.Length() > acc_tol) { std::cout << " at t = " << time << " acc_1 - acc_2 = " << acc_delta.x() << " " << acc_delta.y() << " " << acc_delta.z() << std::endl; return false; } ChVector<> aacc_delta = aacc_1 - aacc_2; if (aacc_delta.Length() > aacc_tol) { std::cout << " at t = " << time << " aacc_1 - aacc_2 = " << aacc_delta.x() << " " << aacc_delta.y() << " " << aacc_delta.z() << std::endl; return false; } return true; }
37.651613
118
0.625942
andrewseidl
4c410d1d29d3a9598e009809b2aca084df0c1b48
893
cpp
C++
Problem Solving/Data Structures/Linked Lists/Find Merge Point of Two Lists/find merge point of two lists.cpp
IsaacAsante/hackerrank
76c430b341ce1e2ab427eda57508eb309d3b215b
[ "MIT" ]
108
2021-03-29T05:04:16.000Z
2022-03-19T15:11:52.000Z
Problem Solving/Data Structures/Linked Lists/Find Merge Point of Two Lists/find merge point of two lists.cpp
IsaacAsante/hackerrank
76c430b341ce1e2ab427eda57508eb309d3b215b
[ "MIT" ]
null
null
null
Problem Solving/Data Structures/Linked Lists/Find Merge Point of Two Lists/find merge point of two lists.cpp
IsaacAsante/hackerrank
76c430b341ce1e2ab427eda57508eb309d3b215b
[ "MIT" ]
32
2021-03-30T03:56:54.000Z
2022-03-27T14:41:32.000Z
/* Author: Isaac Asante * HackerRank URL for this exercise: https://www.hackerrank.com/challenges/find-the-merge-point-of-two-joined-linked-lists/problem * Original video explanation: https://www.youtube.com/watch?v=PUMCc5GPn1Q * Last verified on: March 28, 2021 */ /* IMPORTANT: * This code is meant to be used as a solution on HackerRank (link above). * It is not meant to be executed as a standalone program. */ // Complete the findMergeNode function below. int findMergeNode(SinglyLinkedListNode* head1, SinglyLinkedListNode* head2) { SinglyLinkedListNode* first = head1; SinglyLinkedListNode* second = head2; while (first != second) { first = first->next; second = second->next; // Restart when necessary if (!first) first = head1; if (!second) second = head2; } return first->data; // first and second are the same }
34.346154
130
0.693169
IsaacAsante
4c417224f883b73130aba6d98bc4b1db7c73d838
4,501
hpp
C++
src/read_set.hpp
dcjones/isolator
24bafc0a102dce213bfc2b5b9744136ceadaba03
[ "MIT" ]
33
2015-07-13T03:00:01.000Z
2021-03-20T08:49:07.000Z
src/read_set.hpp
dcjones/isolator
24bafc0a102dce213bfc2b5b9744136ceadaba03
[ "MIT" ]
9
2016-11-29T00:04:30.000Z
2020-02-10T17:46:01.000Z
src/read_set.hpp
dcjones/isolator
24bafc0a102dce213bfc2b5b9744136ceadaba03
[ "MIT" ]
6
2015-09-10T15:49:34.000Z
2017-03-09T05:14:06.000Z
#ifndef ISOLATOR_READ_SET_HPP #define ISOLATOR_READ_SET_HPP #include <boost/iterator/iterator_facade.hpp> #include <boost/unordered_map.hpp> #include <vector> #include "common.hpp" #include "hat-trie/hat-trie.h" #include "samtools/sam.h" #include "samtools/samtools_extra.h" #include "transcripts.hpp" /* A representation of an aligned sequence. */ struct Alignment { Alignment(); Alignment(const Alignment& other); Alignment(const bam1_t* other); ~Alignment(); bool operator == (const bam1_t* b) const; bool operator != (const bam1_t* b) const; bool operator == (const Alignment& other) const; bool operator < (const Alignment& other) const; pos_t start; pos_t end; bool paired; uint16_t cigar_len; uint32_t* cigar; uint8_t strand; uint16_t alnnum; float misaligned_pr; }; struct AlignmentPtrCmp { bool operator () (const Alignment* a, const Alignment* b) const { return *a < *b; } }; /* A single cigar operation. */ struct Cigar { uint8_t op; pos_t start; pos_t end; }; /* Iterate through cigar operations in an alignment.. */ class CigarIterator : public boost::iterator_facade<CigarIterator, const Cigar, boost::forward_traversal_tag> { public: CigarIterator(); CigarIterator(const Alignment&); private: friend class boost::iterator_core_access; void increment(); bool equal(const CigarIterator& other) const; const Cigar& dereference() const; const Alignment* owner; size_t i; Cigar c; }; /* A read with some number of alignments. */ struct AlignedRead { AlignedRead(); ~AlignedRead(); bool operator < (const AlignedRead& other) const; pos_t start, end; bool paired; std::vector<Alignment*> mate1; std::vector<Alignment*> mate2; }; /* A pair of alignments. (One for each mate.) */ struct AlignmentPair { AlignmentPair(); AlignmentPair(const AlignmentPair& other); bool operator == (const AlignmentPair& other) const; bool operator < (const AlignmentPair& other) const; bool valid_frag() const; /* Fragment length, assuming the read-pair originated from the given * transcript. * * Returns 0 if the pair lacks a mate so that so not no estimate can be * made. * * Return <0 if the pair is incompatible with the trascript. */ pos_t frag_len(const Transcript& t) const; /* The fragment length of a paired-end read, ignoring the effects of * splicing. */ pos_t naive_frag_len() const; /* Orientation of the read. */ strand_t strand() const; const Alignment* mate1; const Alignment* mate2; // Return the amount of soft-clipping on the ends of the fragment std::pair<pos_t, pos_t> flanks_soft_clipping() const; }; /* Iterate of the cartesian product of mate alignment. */ class AlignedReadIterator : public boost::iterator_facade<AlignedReadIterator, const AlignmentPair, boost::forward_traversal_tag> { public: AlignedReadIterator(); AlignedReadIterator(const AlignedRead&); ~AlignedReadIterator(); private: friend class boost::iterator_core_access; void increment(); bool equal(const AlignedReadIterator& other) const; bool finished() const; const AlignmentPair& dereference() const; const AlignedRead* r; size_t i, j; AlignmentPair p; }; /* A container for a set of reads indexed by id. */ class ReadSet { public: ReadSet(); ~ReadSet(); /* Add an alignment to the read set. */ void add_alignment(long idx, const bam1_t* b); /* Make the set empty. Free memory. */ void clear(); size_t size() const; /* Map aligned reads to number of occurances. */ struct UniqueReadCountsCmp { bool operator () (AlignedRead* const& a, AlignedRead* const& b) const { return *a < *b; } }; typedef std::map<AlignedRead*, unsigned int, UniqueReadCountsCmp> UniqueReadCounts; /* Make a unique read count from the read set. */ void make_unique_read_counts(UniqueReadCounts& counts); boost::unordered_map<long, AlignedRead*> rs; }; #endif
23.321244
81
0.623639
dcjones
4c41fb73ad192e0954d76cd272202e5fde06a400
13,084
cc
C++
SmartDiet_Backend/matlab/SensorFusion/BSR/grouping/source/gpb_src/matlab/recognition/mex_shapeme_db.cc
mdepak/mobile_computing
0ac1250b86c35cbe4eef7186f4efcdbfeabfb244
[ "MIT" ]
3
2018-11-05T05:01:21.000Z
2021-01-14T20:36:09.000Z
SmartDiet_Backend/matlab/SensorFusion/BSR/grouping/source/gpb_src/matlab/recognition/mex_shapeme_db.cc
mdepak/mobile_computing
0ac1250b86c35cbe4eef7186f4efcdbfeabfb244
[ "MIT" ]
null
null
null
SmartDiet_Backend/matlab/SensorFusion/BSR/grouping/source/gpb_src/matlab/recognition/mex_shapeme_db.cc
mdepak/mobile_computing
0ac1250b86c35cbe4eef7186f4efcdbfeabfb244
[ "MIT" ]
null
null
null
/* * Database of geometric blur features. */ #include <iostream> #include "collections/array_list.hh" #include "collections/list.hh" #include "collections/pointers/auto_collection.hh" #include "lang/array.hh" #include "lang/exceptions/exception.hh" #include "lang/pointers/auto_ptr.hh" #include "lang/pointers/safe_ptr.hh" #include "math/math.hh" #include "math/matrices/matrix.hh" #include "vision/features/geometric_blur.hh" #include "vision/recognition/classifiers/unigram_classifier.hh" #include "vision/recognition/classifiers/bigram_classifier.hh" #include "vision/recognition/databases/category_db.hh" #include "vision/recognition/models/category.hh" #include "vision/recognition/models/exemplar.hh" #include "vision/recognition/models/ids/category_id.hh" #include "vision/recognition/models/ids/exemplar_id.hh" #include "vision/recognition/models/ids/feature_id.hh" #include "mlearning/clustering/clusterers/covering/matrix_clusterer.hh" #include <cstring> #include <mex.h> using collections::array_list; using collections::list; using collections::pointers::auto_collection; using lang::array; using lang::exceptions::exception; using lang::pointers::auto_ptr; using lang::pointers::safe_ptr; using math::matrices::matrix; using vision::features::geometric_blur; using vision::recognition::classifiers::unigram_classifier; using vision::recognition::classifiers::bigram_classifier; using vision::recognition::databases::category_db; using vision::recognition::models::category; using vision::recognition::models::exemplar; using vision::recognition::models::ids::category_id; using mlearning::clustering::clusterers::covering::matrix_clusterer; /********************************** * Matlab array conversion routines. **********************************/ /* * Get a string from an mxArray. */ char *mexGetString(const mxArray *arr) { char *string; int buflen; buflen = (mxGetM(arr) * mxGetN(arr) * sizeof(mxChar)) + 1; string = new char[buflen]; mxGetString(arr, string, buflen); return string; } /* * Create a single element Matlab double matrix. */ mxArray* mxCreateDoubleScalar (double value) { mxArray* pa = mxCreateDoubleMatrix(1, 1, mxREAL); *mxGetPr(pa) = value; return pa; } /* * Convert an mxArray to a double array. */ double** toDouble(const mxArray *a) { int mrows = mxGetM(a); int ncols = mxGetN(a); double *arr = mxGetPr(a); double *v = new double[(mrows * ncols)]; double **data = new double*[mrows]; int r, c; for (r = 0; r < mrows; r++) { data[r] = v; v += ncols; } /* copy the data */ for (r = 0; r < mrows; r++) { for (c = 0; c < ncols; c++) { data[r][c] = arr[(c*mrows) + r]; } } return data; } /* * Convert an mxArray to an array<double>. */ array<double> toArrayDouble(const mxArray* a) { int mrows = mxGetM(a); int ncols = mxGetN(a); double *arr = mxGetPr(a); unsigned long size = static_cast<unsigned long>(mrows*ncols); array<double> data(size); for (unsigned long n = 0; n < size; n++) data[n] = arr[n]; return data; } /* * Convert an array<double> to an mxArray. */ mxArray* toMxArray(const array<double>& a) { mxArray *arr = mxCreateDoubleMatrix( 1, static_cast<int>(a.size()), mxREAL ); double *data = mxGetPr(arr); for (unsigned long n = 0; n < a.size(); n++) data[n] = a[n]; return arr; } /* * Convert a list of array<double>'s to a multi-dimensional mxArray. */ mxArray* toMxArray(const list< array<double> >& lst) { int mrows = static_cast<int>(lst.size()); int ncols = ((mrows > 0) ? (lst.head().size()) : 0); mxArray* arr = mxCreateDoubleMatrix(mrows, ncols, mxREAL); double* data = mxGetPr(arr); int r = 0; for (list< array<double> >::iterator_t i(lst); i.has_next(); ) { array<double>& a = i.next(); for (int c = 0; c < ncols; c++) { data[(c*mrows) + r] = a[c]; } r++; } return arr; } /* * Convert a double array back to an mxArray. */ mxArray* toMxArray(double **data, int mrows, int ncols) { mxArray *a = mxCreateDoubleMatrix(mrows, ncols, mxREAL); double *arr = mxGetPr(a); /* copy the data */ int r, c; for (r = 0; r < mrows; r++) { for (c = 0; c < ncols; c++) { arr[(c*mrows) + r] = data[r][c]; } } return a; } /* * Delete a double array. */ void deleteDouble(double **data) { delete [] (data[0]); delete [] data; } /* * Print an array. */ void print(const array<double> a) { for (unsigned long n = 0; n < a.size(); n++) std::cout << a[n] << " "; } /******************************************************************/ /* * Database. */ static array_list<category> c_list; /* pending category list */ /* * Shapeme vocabulary. */ static array_list< matrix<> > s_gb_list; /* gb features to cluster */ static auto_collection< matrix<>, array_list< matrix<> > > s_centroids; /* shapeme centroids */ /* * Shapeme frequency counts. */ matrix<> count_C_s; /* count_C_s(C,s) = # times shapeme s occurs in category C */ matrix<> count_C; /* count_C(C) = total # shapeme occurances in category C */ /* * Utility function - get id of nearest cluster center. */ unsigned long find_cluster( const matrix<>& m, const array_list< matrix<> >& centroids) { unsigned long min_id = 0; matrix<> diff = centroids[0] - m; double min_dist = dot(diff, diff); for (unsigned long n = 1; n < centroids.size(); n++) { matrix<> curr_diff = centroids[n] - m; double curr_dist = dot(curr_diff, curr_diff); if (curr_dist < min_dist) { min_id = n; min_dist = curr_dist; } } return min_id; } /* * Matlab interface - extract unigram features from an mxArray. * Input: * * mx_features - (feature vector length) x n_features * matrix of geometric blur descriptors * * mx_x_pos - vector of length n_features * x-coordinate for each feature * * mx_y_pos - vector of length n_features * y-coordinate for each feature * * Output: exemplar containing features. */ auto_ptr<exemplar> matlab_extract_features( const mxArray* mx_features, const mxArray* mx_x_pos, const mxArray* mx_y_pos) { /* extract features */ array<double> feature_data = toArrayDouble(mx_features); array<double> x_pos = toArrayDouble(mx_x_pos); array<double> y_pos = toArrayDouble(mx_y_pos); unsigned long fvec_len = static_cast<unsigned long>(mxGetM(mx_features)); unsigned long n_features = static_cast<unsigned long>(mxGetN(mx_features)); auto_collection<geometric_blur> features(new list<geometric_blur>()); for (unsigned long n = 0; n < n_features; n++) { array<double> fvec = feature_data.subarray( n*fvec_len, (n+1)*fvec_len - 1 ); matrix<> m_fvec(fvec.size(), 1); for (unsigned long i = 0; i < fvec.size(); i++) m_fvec[i] = fvec[i]; auto_ptr<geometric_blur> gb( new geometric_blur(x_pos[n], y_pos[n], 0, 1, m_fvec) ); features->add(*gb); gb.release(); } return auto_ptr<exemplar>(new exemplar(features)); } /* * Matlab interface - add exemplar to database. */ void matlab_add_exemplar_to_db( auto_ptr<exemplar> e, /* exemplar */ const mxArray* mx_c_id) /* category id */ { unsigned long n_categories = c_list.size(); unsigned long c_id = static_cast<unsigned long>(*mxGetPr(mx_c_id)); for (unsigned long n = n_categories; n < (c_id+1); n++) { auto_ptr<category> c(new category()); c_list.add(*c); c.release(); } c_list[c_id].add_exemplar(e); } /* * Matlab interface - add exemplar to vocabulary. */ void matlab_add_exemplar_to_vocab(auto_ptr<exemplar> e) { const array_list<geometric_blur>& gb_list = e->gb_features(); for (unsigned long n = 0; n < gb_list.size(); n++) { const matrix<>& f = gb_list[n].descriptor(); s_gb_list.add(*(new matrix<>(f))); } } /* * Matlab interface - build database. */ void matlab_build_db(const mxArray* mx_r) { /* compute shapeme vocabulary by clustering */ std::cout << "clustering into shapemes...\n"; double r = static_cast<double>(*mxGetPr(mx_r)); matrix_clusterer<> cover_clust(r); cover_clust.cluster(s_gb_list, s_centroids); unsigned long K = s_centroids->size(); std::cout << K << " shapemes computed\n"; /* compute shapeme frequency counts for each category */ std::cout << "computing category shapeme frequency counts...\n"; unsigned long n_categories = c_list.size(); count_C_s = matrix<>::ones(n_categories, K); count_C = matrix<>::zeros(n_categories, 1); count_C.fill(static_cast<double>(K)); for (unsigned long n = 0; n < n_categories; n++) { std::cout << "\ncategory " << n << "\n"; const category& c = c_list[n]; const array_list<exemplar>& e_list = c.exemplars(); for (unsigned long n_e = 0; n_e < e_list.size(); n_e++) { const exemplar& e = e_list[n_e]; const array_list<geometric_blur>& gb_list = e.gb_features(); for (unsigned long n_f = 0; n_f < gb_list.size(); n_f++) { const matrix<>& f = gb_list[n_f].descriptor(); unsigned long s_id = find_cluster(f, *s_centroids); count_C_s(n,s_id)++; count_C[n]++; } } } } /* * Matlab interface - perform query. * * mx_features - (feature vector length) x n_features * matrix of geometric blur descriptors * * mx_x_pos - vector of length n_features * x-coordinate for each feature * * mx_y_pos - vector of length n_features * y-coordinate for each feature * * Return: * * mx_results - vector of categories ids (one for each classifier run) */ void matlab_query_db( const mxArray* mx_features, const mxArray* mx_x_pos, const mxArray* mx_y_pos, mxArray*& mx_results) { /* create query exemplar */ auto_ptr<exemplar> e = matlab_extract_features( mx_features, mx_x_pos, mx_y_pos ); /* compute shapemes in exemplar by vector quantization */ const array_list<geometric_blur>& gb_list = e->gb_features(); unsigned long n_features = gb_list.size(); array<unsigned long> f_ids(n_features); for (unsigned long n = 0; n < n_features; n++) { const matrix<>& f = gb_list[n].descriptor(); f_ids[n] = find_cluster(f, *s_centroids); } /* naive bayes classifier */ unsigned long n_categories = count_C_s.size(0); array<double> category_probs(n_categories); /* compute log probability for each category */ for (unsigned long n = 0; n < n_categories; n++) { double p = 0; for (unsigned long n_f = 0; n_f < n_features; n_f++) p += math::log(count_C_s(n, f_ids[n_f])/(count_C[n])); category_probs[n] = p; } /* find category with highest log probability */ unsigned long c_id = 0; double c_prob = category_probs[0]; for (unsigned long n = 1; n < n_categories; n++) { if (category_probs[n] > c_prob) { c_id = n; c_prob = category_probs[n]; } } /* report results (category id) */ array<double> results(1); results[0] = c_id; mx_results = toMxArray(results); } /* * Matlab interface. */ void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { /* get function to call */ char* fun_name = mexGetString(prhs[0]); try { /* branch to appropriate function */ if (strcmp(fun_name, "add_exemplar_to_db") == 0) { /* add an exemplar to the database */ const mxArray* mx_features = prhs[1]; const mxArray* mx_x_pos = prhs[2]; const mxArray* mx_y_pos = prhs[3]; const mxArray* mx_c_id = prhs[4]; auto_ptr<exemplar> e = matlab_extract_features( mx_features, mx_x_pos, mx_y_pos ); matlab_add_exemplar_to_db(e, mx_c_id); } else if (strcmp(fun_name, "add_exemplar_to_vocab") == 0) { const mxArray* mx_features = prhs[1]; const mxArray* mx_x_pos = prhs[2]; const mxArray* mx_y_pos = prhs[3]; auto_ptr<exemplar> e = matlab_extract_features( mx_features, mx_x_pos, mx_y_pos ); matlab_add_exemplar_to_vocab(e); } else if (strcmp(fun_name, "build_db") == 0) { const mxArray* mx_r = prhs[1]; matlab_build_db(mx_r); } else if (strcmp(fun_name, "query_db") == 0) { /* run query */ const mxArray* mx_features = prhs[1]; const mxArray* mx_x_pos = prhs[2]; const mxArray* mx_y_pos = prhs[3]; matlab_query_db( mx_features, mx_x_pos, mx_y_pos, plhs[0] ); } else { std::cout << "Invalid command.\n"; } } catch (exception& e) { std::cout << e << "\n"; } delete [] fun_name; }
30.078161
106
0.61686
mdepak
4c436c434537e6a9b906a1a0c48187e7b294f98f
20,984
cpp
C++
src/main.cpp
MarkZH/Genetic_Chess
1e07cf0b3bbe87936820844edb322a3fd85f8155
[ "MIT" ]
9
2019-08-01T14:42:38.000Z
2021-09-03T17:49:37.000Z
src/main.cpp
MarkZH/Genetic_Chess
1e07cf0b3bbe87936820844edb322a3fd85f8155
[ "MIT" ]
107
2016-05-22T14:28:08.000Z
2022-03-31T08:27:27.000Z
src/main.cpp
MarkZH/Genetic_Chess
1e07cf0b3bbe87936820844edb322a3fd85f8155
[ "MIT" ]
3
2017-12-13T04:15:42.000Z
2021-07-17T20:59:00.000Z
#include <iostream> #include <memory> #include <fstream> #include <cctype> #include <algorithm> #include <string> #include <stdexcept> #include <utility> #include "Game/Game.h" #include "Game/Board.h" #include "Game/Clock.h" #include "Game/Game_Result.h" #include "Moves/Move.h" #include "Players/Minimax_AI.h" #include "Players/Iterative_Deepening_AI.h" #include "Players/Random_AI.h" #include "Genes/Gene_Pool.h" #include "Utility/Exceptions.h" #include "Utility/String.h" #include "Testing.h" //! \file namespace { //! \brief Print the command-line options for this program. void print_help(); //! \brief Confirm that all moves in a PGN game record are legal moves. //! //! \param file_name The name of the file with the PGN game records. All games will be examined. bool confirm_game_record(const std::string& file_name); //! \brief Starts a single game according to command line options. //! //! \param argc The number of command line options (same as for main(int argc, char *argv[])). //! \param argv The command line options (same as for main(int argc, char *argv[])). void start_game(int argc, char* argv[]); //! \brief Reads a genome file and rewrites it in the latest style. //! //! \param file_name The name of the file to update. //! \exception Genetic_AI_Creation_Error or derivative if the genome file is invalid. void update_genome_file(const std::string& file_name); //! \brief Throws std::invalid_argument if assertion fails //! //! \param condition A condition that must be true to continue. //! \param failure_message A message to display if the assertion fails. void argument_assert(bool condition, const std::string& failure_message); } //! \brief The starting point for the whole program. //! //! \param argc The number of command-line arguments. //! \param argv The command-line arguments. See print_help() (or run the program //! with no arguments) for a listing of all the options. //! \returns EXIT_SUCCESS or EXIT_FAILURE. int main(int argc, char *argv[]) { if(argc <= 1) { print_help(); return EXIT_SUCCESS; } try { const std::string option = argv[1]; if(option == "-gene-pool") { argument_assert(argc > 2, "Specify a configuration file to run a gene pool."); gene_pool(argv[2]); } else if(option == "-confirm") { argument_assert(argc > 2, "Provide a file containing a game to confirm has all legal moves."); return confirm_game_record(argv[2]) ? EXIT_SUCCESS : EXIT_FAILURE; } else if(option == "-test") { return run_tests() ? EXIT_SUCCESS : EXIT_FAILURE; } else if(option == "-speed") { run_speed_tests(); } else if(option == "-perft") { return run_perft_tests() ? EXIT_SUCCESS : EXIT_FAILURE; } else if(option == "-update") { argument_assert(argc > 2, "Provide a file containing Genetic AI data."); update_genome_file(argv[2]); } else { start_game(argc, argv); } } catch(const std::exception& e) { std::cerr << "\nERROR: " << e.what() << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } namespace { void print_help() { std::cout << "\n\nGenetic Chess\n" << "=============\n\n" << "Standalone functions (only first is run if multiple are specified):\n\n" << "\t-gene-pool [file name]\n" << "\t\tStart a run of a gene pool with parameters set in the given\n\t\tfile name.\n\n" << "\t-confirm [filename]\n" << "\t\tCheck a file containing PGN game records for any illegal moves\n\t\tor mismarked checks or checkmates.\n\n" << "\t-test\n" << "\t\tRun tests to ensure various parts of the program function\n\t\tcorrectly.\n\n" << "\t-speed\n" << "\t\tRun a speed test for gene scoring and boad move submission.\n\n" << "\t-perft\n" << "\t\tRun a legal move generation test.\n\n" << "\t-update [filename]\n" << "\t\tIf genetic_chess has changed how genomes are written, use\n\t\tthis option to update the file to the latest format.\n\n" << "The following options start a game with various players. If two players are\nspecified, the first plays white and the second black. If only one player is\nspecified, the program will wait for a CECP/xboard or UCI command from a GUI\nto start playing.\n\n" << "\t-genetic-minimax [filename [number]]\n" << "\t\tSelect a minimaxing genetic AI player for a game. Optional file name\n\t\tand ID number to load an AI from a file.\n\n" << "\t-genetic-iterative [filename [number]]\n" << "\t\tSelect an iteratively deepening minimax genetic AI player for the game.\n\t\tOptional file name and ID number to\n\t\tload an AI from a file.\n\n" << "\t-random\n" << "\t\tSelect a player that makes random moves for a game.\n\n" << "Other game options:\n\n" << "\t-time [number]\n" << "\t\tSpecify the time (in seconds) each player has to play the game\n\t\tor to make a set number of moves (see -reset_moves option).\n\n" << "\t-reset-moves [number]\n" << "\t\tSpecify the number of moves a player must make within the time\n\t\tlimit. The clock adds the initial time every time this\n\t\tnumber of moves is made.\n\n" << "\t-increment-time [number]\n" << "\t\tSpecify seconds to add to time after each move.\n\n" << "\t-board [FEN string]\n" << "\t\tSpecify the starting board state using FEN notation. The entire\n\t\tstring should be quoted.\n\n" << "\t-event [name]\n" << "\t\tAn optional name for the game to be played. This name will be\n\t\twritten to the PGN game record.\n\n" << "\t-location [name]\n" << "\t\tAn optional location for the game to be played. This will be\n\t\twritten to the PGN game record.\n\n" << "\t-game-file [file name]\n" << "\t\tSpecify the name of the file where the game record should be\n\t\twritten. If none, record is printed to stdout.\n\n" << "All game options in this section can be overriden by GUI commands except\n-short-post, -event, -location, and -game-file.\n\n"; } bool confirm_game_record(const std::string& file_name) { auto input = std::ifstream(file_name); if( ! input) { throw std::runtime_error("Could not open file " + file_name + " for reading."); } auto line_number = 0; auto last_move_line_number = 0; auto expected_winner = Winner_Color::NONE; auto expect_checkmate = true; auto expect_fifty_move_draw = false; auto expect_threefold_draw = false; auto in_game = false; Board board; Game_Result result; for(std::string line; std::getline(input, line);) { ++line_number; line = String::remove_pgn_comments(line); if(line.empty()) { continue; } // Start header of new game if(in_game && String::starts_with(line, "[")) { if(expect_fifty_move_draw != String::contains(result.ending_reason(), "50")) { std::cerr << "Header indicates 50-move draw, but last move did not trigger rule (line: " << last_move_line_number << ")." << std::endl; return false; } if(expect_threefold_draw != String::contains(result.ending_reason(), "fold")) { std::cerr << "Header indicates threefold draw, but last move did not trigger rule (line: " << last_move_line_number << ")." << std::endl; return false; } expected_winner = Winner_Color::NONE; expect_checkmate = true; expect_fifty_move_draw = false; expect_threefold_draw = false; in_game = false; board = Board(); result = {}; } if(String::starts_with(line, "[Result")) { if(String::contains(line, "1-0")) { expected_winner = Winner_Color::WHITE; } else if(String::contains(line, "0-1")) { expected_winner = Winner_Color::BLACK; } else if(String::contains(line, "1/2-1/2")) { expect_checkmate = false; } else if(String::contains(line, '*')) { expect_checkmate = false; } else { std::cerr << "Malformed Result: " << line << " (line: " << line_number << ")" << std::endl; return false; } } else if(String::starts_with(line, "[Termination")) { expect_checkmate = false; if(String::contains(line, "fold")) { expect_threefold_draw = true; } else if(String::contains(line, "50")) { expect_fifty_move_draw = true; } } else if(String::starts_with(line, "[FEN")) { board = Board(String::split(line, "\"").at(1)); } else if(String::starts_with(line, "[")) { continue; } else // Line contains game moves { in_game = true; std::string move_number; for(const auto& move : String::split(line)) { if(move.back() == '.') { move_number = move + ' '; continue; } if(board.whose_turn() == Piece_Color::BLACK) { move_number += "... "; } if((move == "1/2-1/2" && expected_winner != Winner_Color::NONE) || (move == "1-0" && expected_winner != Winner_Color::WHITE) || (move == "0-1" && expected_winner != Winner_Color::BLACK) || (move == "*" && expected_winner != Winner_Color::NONE)) { std::cerr << "Final result mark (" << move << ") does not match game result. (line: " << line_number << ")" << std::endl; return false; } if(move == "1/2-1/2" || move == "1-0" || move == "0-1" || move == "*") { continue; } try { const auto move_checkmates = move.back() == '#'; const auto move_checks = move_checkmates || move.back() == '+'; const auto& move_to_play = board.interpret_move(move); last_move_line_number = line_number; if(String::contains(move, 'x')) // check that move captures { if( ! std::as_const(board).piece_on_square(move_to_play.end()) && ! move_to_play.is_en_passant()) { std::cerr << "Move: " << move_number << move << " indicates capture but does not capture. (line: " << line_number << ")" << std::endl; return false; } } result = board.play_move(move_to_play); if(move_checks) { if( ! board.king_is_in_check()) { std::cerr << "Move (" << move_number << move << ") indicates check but does not check. (line: " << line_number << ")" << std::endl; return false; } } else { if(board.king_is_in_check()) { std::cerr << "Move (" << move_number << move << ") indicates no check but does check. (line: " << line_number << ")" << std::endl; return false; } } if(move_checkmates) { if(result.winner() != static_cast<Winner_Color>(opposite(board.whose_turn()))) { std::cerr << "Move (" << move_number << move << ") indicates checkmate, but move does not checkmate. (line: " << line_number << ")" << std::endl; return false; } if( ! expect_checkmate) { std::cerr << "Game ends in checkmate, but this is not indicated in headers. (line: " << line_number << ")" << std::endl; return false; } } else { if(result.winner() != Winner_Color::NONE) { std::cerr << "Move (" << move_number << move << ") does not indicate checkmate, but move does checkmate. (line: " << line_number << ")" << std::endl; return false; } } } catch(const Illegal_Move& error) { std::cerr << "Move (" << move_number << move << ") is illegal: " << error.what() << ". (line: " << line_number << ")" << std::endl; std::cerr << "Legal moves: "; for(const auto legal_move : board.legal_moves()) { std::cerr << legal_move->algebraic(board) << " "; } std::cerr << std::endl; std::cerr << board.fen() << std::endl; return false; } } } } return true; } void start_game(int argc, char* argv[]) { // Use pointers since each player could be Genetic, Random, etc. std::unique_ptr<Player> white; std::unique_ptr<Player> black; std::unique_ptr<Player> latest; Clock::seconds game_time{}; size_t moves_per_reset = 0; Clock::seconds increment_time{}; Board board; std::string game_file_name; std::string event_name; std::string location; auto thinking_output = Thinking_Output_Type::NO_THINKING; for(int i = 1; i < argc; ++i) { const std::string opt = argv[i]; if(opt == "-random") { latest = std::make_unique<Random_AI>(); } else if(opt == "-genetic-minimax") { argument_assert(i + 1 < argc, "Genome file needed for Genetic AI player"); std::string filename = argv[++i]; try { const auto id = i + 1 < argc ? argv[i + 1] : std::string{}; latest = std::make_unique<Minimax_AI>(filename, String::to_number<int>(id)); ++i; } catch(const std::invalid_argument&) // Could not convert id to an int. { latest = std::make_unique<Minimax_AI>(filename, find_last_id(filename)); } } else if(opt == "-genetic-iterative") { argument_assert(i + 1 < argc, "Genome file needed for Genetic AI player"); std::string filename = argv[++i]; try { const auto id = i + 1 < argc ? argv[i + 1] : std::string{}; latest = std::make_unique<Iterative_Deepening_AI>(filename, String::to_number<int>(id)); ++i; } catch(const std::invalid_argument&) // Could not convert id to an int. { latest = std::make_unique<Iterative_Deepening_AI>(filename, find_last_id(filename)); } } else if(opt == "-time" && i + 1 < argc) { game_time = String::to_duration<Clock::seconds>(argv[++i]); } else if(opt == "-reset-moves" && i + 1 < argc) { moves_per_reset = String::to_number<size_t>(argv[++i]); } else if(opt == "-increment-time" && i + 1 < argc) { increment_time = String::to_duration<Clock::seconds>(argv[++i]); } else if(opt == "-board" && i + 1 < argc) { board = Board(argv[++i]); } else if(opt == "-game-file" && i + 1 < argc) { game_file_name = argv[++i]; } else if(opt == "-event" && i + 1 < argc) { event_name = argv[++i]; } else if(opt == "-location" && i + 1 < argc) { location = argv[++i]; } else if(opt == "-xboard") { thinking_output = Thinking_Output_Type::CECP; } else if(opt == "-uci") { thinking_output = Thinking_Output_Type::UCI; } else { throw std::invalid_argument("Invalid or incomplete game option: " + opt); } if(latest) { if( ! white) { white = std::move(latest); } else if( ! black) { black = std::move(latest); } else { throw std::invalid_argument("More than two players specified."); } } } if( ! white) { throw std::invalid_argument("At least one player must be specified."); } if( ! black) { play_game_with_outsider(*white, event_name, location, game_file_name); } else { board.set_thinking_mode(thinking_output); play_game(board, Clock(game_time, moves_per_reset, increment_time, Time_Reset_Method::ADDITION, board.whose_turn()), *white, *black, event_name, location, game_file_name); } } void update_genome_file(const std::string& file_name) { auto input = std::ifstream(file_name); std::vector<int> id_list; for(std::string line; std::getline(input, line);) { if(String::starts_with(line, "ID:")) { id_list.push_back(String::to_number<int>(String::split(line, ":", 1).back())); } } input = std::ifstream(file_name); const auto output_file_name = String::add_to_file_name(file_name, "-updated"); auto output = std::ofstream(output_file_name); std::cout << "Writing to: " << output_file_name << std::endl; for(auto id : id_list) { try { Genetic_AI(input, id).print(output); } catch(const Genetic_AI_Creation_Error& e) { std::cerr << e.what() << '\n'; } } } void argument_assert(const bool condition, const std::string& failure_message) { if( ! condition) { throw std::invalid_argument(failure_message); } } }
39.22243
275
0.468643
MarkZH
4c477a5cf79b4be9d463acfb54ce565b4d909723
959
cc
C++
tests/proto_worker.cc
acs-network/MCC
808e8f27a5a875331f2d54b99c83d4720f2c9bb9
[ "BSD-3-Clause" ]
5
2022-03-04T06:57:43.000Z
2022-03-30T08:45:42.000Z
tests/proto_worker.cc
acs-network/MCC
808e8f27a5a875331f2d54b99c83d4720f2c9bb9
[ "BSD-3-Clause" ]
null
null
null
tests/proto_worker.cc
acs-network/MCC
808e8f27a5a875331f2d54b99c83d4720f2c9bb9
[ "BSD-3-Clause" ]
2
2022-03-04T07:19:13.000Z
2022-03-04T07:23:58.000Z
#include "proto/mcc.pb.h" #include "application.h" #include "reactor.h" #include "tcp_server.h" using namespace infgen; namespace bpo = boost::program_options; int main(int argc, char* argv[]) { application app; app.add_options() ("client-id,n", bpo::value<unsigned>()->default_value(0), "client id"); app.run(argc, argv, [&app]() { // worker node auto &config = app.configuration(); auto id = config["client-id"].as<unsigned>(); ipv4_addr addr("10.30.10.233", 2222); pin_this_thread(1); auto conn = engine().connect(make_ipv4_address(addr)); conn->when_ready([&](const connptr& conn) { report r; r.set_client_id(id); report::notice* n = r.mutable_note(); n->set_online(true); std::string packet; if (!r.SerializeToString(&packet)) { app_logger.error("serialize message failed"); exit(-1); } conn->send_packet(packet); }); engine().run(); }); }
27.4
75
0.618352
acs-network
4c47ffd057e8d17bf3da03f0f9e399a9055e9775
229
cpp
C++
native_libs/src/ValueHolder.cpp
mwu-tow/Dataframes
fd82802fe9b490cee9ac7be9aee0f5cc2e1fba28
[ "MIT" ]
4
2019-05-09T17:25:29.000Z
2019-10-30T21:22:14.000Z
native_libs/src/ValueHolder.cpp
mwu-tow/Dataframes
fd82802fe9b490cee9ac7be9aee0f5cc2e1fba28
[ "MIT" ]
94
2018-07-09T19:02:56.000Z
2019-03-29T13:30:39.000Z
native_libs/src/ValueHolder.cpp
mwu-tow/Dataframes
fd82802fe9b490cee9ac7be9aee0f5cc2e1fba28
[ "MIT" ]
3
2019-05-16T21:05:39.000Z
2020-06-19T14:36:33.000Z
#include "ValueHolder.h" #include <utility> const char * ValueHolder::store(std::string s) { buffer = std::move(s); return buffer.c_str(); } void ValueHolder::clear() { buffer.clear(); buffer.shrink_to_fit(); }
15.266667
46
0.650655
mwu-tow
4c4ef384bb0ab01432660c8f155c5409c543a8f3
1,631
cpp
C++
src/Crypt.cpp
thomaseolsen/SpaceMonopoly
96eb22111f3584b972e71b3880ee91314d9fd0cd
[ "MIT" ]
null
null
null
src/Crypt.cpp
thomaseolsen/SpaceMonopoly
96eb22111f3584b972e71b3880ee91314d9fd0cd
[ "MIT" ]
null
null
null
src/Crypt.cpp
thomaseolsen/SpaceMonopoly
96eb22111f3584b972e71b3880ee91314d9fd0cd
[ "MIT" ]
null
null
null
//--------------------------------------------------------------------------- #include <vcl\vcl.h> #pragma hdrstop #include "crypt.h" //--------------------------------------------------------------------------- /***************************************************************************** * crypt -- encrypt and decrypt functions used to encrypt and decrypt arrays * * of characters using arrays of characters! * * * * Author: David Vivash * * Created: 6-Jul-1998 * *****************************************************************************/ //----------------------------------------------- void encrypt(unsigned char *buffer, unsigned char *passbuf,int size1, int size2) { int j=0; /* Counter for passbuf */ for (int i=0; i<(size1); ++i) { //if((buffer[i] += passbuf[j])>255) buffer[i] -= 256; if ((256-passbuf[j])<=buffer[i]) buffer[i]-=(256-passbuf[j]); else buffer[i]+=passbuf[j]; //buffer[i] += passbuf[j]; ++j; if (j==size2) j=0; } } //------------------------------------------ void decrypt(unsigned char *buffer, unsigned char *passbuf,int size1, int size2) { int j=0; for (int i=0; i<(size1); ++i) { //if((buffer[i] -= passbuf[j])<0) buffer[i] += 256; if (buffer[i]>passbuf[j]) buffer[i] -= passbuf[j]; else buffer[i]+=(256-passbuf[j]); //buffer[i] -= passbuf[j]; ++j; if (j==size2) j=0; } } //---------------
33.979167
81
0.351318
thomaseolsen
4c4fd3c0aadb17f20ae5d2d8e8872be84f963c8c
2,664
hxx
C++
code/rtkRayEllipsoidIntersectionImageFilter.hxx
ldqcarbon/RTK
88df8ed953805aca3c5a73c22cb940164e7cc296
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
code/rtkRayEllipsoidIntersectionImageFilter.hxx
ldqcarbon/RTK
88df8ed953805aca3c5a73c22cb940164e7cc296
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
code/rtkRayEllipsoidIntersectionImageFilter.hxx
ldqcarbon/RTK
88df8ed953805aca3c5a73c22cb940164e7cc296
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
/*========================================================================= * * Copyright RTK Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * 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. * *=========================================================================*/ #ifndef __rtkRayEllipsoidIntersectionImageFilter_hxx #define __rtkRayEllipsoidIntersectionImageFilter_hxx #include <itkImageRegionConstIterator.h> #include <itkImageRegionIteratorWithIndex.h> #include "rtkHomogeneousMatrix.h" namespace rtk { template <class TInputImage, class TOutputImage> RayEllipsoidIntersectionImageFilter<TInputImage, TOutputImage> ::RayEllipsoidIntersectionImageFilter():m_EQPFunctor( EQPFunctionType::New() ) { m_Axis.Fill(0.); m_Center.Fill(0.); m_Angle = 0.; m_Figure = "Ellipsoid"; } template <class TInputImage, class TOutputImage> void RayEllipsoidIntersectionImageFilter<TInputImage, TOutputImage>::BeforeThreadedGenerateData() { Superclass::BeforeThreadedGenerateData(); typename EQPFunctionType::VectorType semiprincipalaxis; typename EQPFunctionType::VectorType center; semiprincipalaxis[0] = m_Axis[0]; semiprincipalaxis[1] = m_Axis[1]; semiprincipalaxis[2] = m_Axis[2]; center[0] = m_Center[0]; center[1] = m_Center[1]; center[2] = m_Center[2]; //Set type of Figure m_EQPFunctor->SetFigure(m_Figure); //Translate from regular expression to quadric m_EQPFunctor->Translate(semiprincipalaxis); //Applies rotation and translation if necessary m_EQPFunctor->Rotate(m_Angle, center); //Setting parameters in order to compute the projections this->GetRQIFunctor()->SetA( m_EQPFunctor->GetA() ); this->GetRQIFunctor()->SetB( m_EQPFunctor->GetB() ); this->GetRQIFunctor()->SetC( m_EQPFunctor->GetC() ); this->GetRQIFunctor()->SetD( m_EQPFunctor->GetD() ); this->GetRQIFunctor()->SetE( m_EQPFunctor->GetE() ); this->GetRQIFunctor()->SetF( m_EQPFunctor->GetF() ); this->GetRQIFunctor()->SetG( m_EQPFunctor->GetG() ); this->GetRQIFunctor()->SetH( m_EQPFunctor->GetH() ); this->GetRQIFunctor()->SetI( m_EQPFunctor->GetI() ); this->GetRQIFunctor()->SetJ( m_EQPFunctor->GetJ() ); } }// end namespace rtk #endif
35.52
97
0.703453
ldqcarbon
4c55579d1744ae667b09286e5ebb8381f368ce04
970
cpp
C++
src/Paddle.cpp
ItsSeaJay/lily-tin
0fa9a225e9a3496aa925137355afe243d2c88dce
[ "MIT" ]
4
2018-07-03T20:23:41.000Z
2021-05-19T04:01:29.000Z
src/Paddle.cpp
ItsSeaJay/lily-tin
0fa9a225e9a3496aa925137355afe243d2c88dce
[ "MIT" ]
null
null
null
src/Paddle.cpp
ItsSeaJay/lily-tin
0fa9a225e9a3496aa925137355afe243d2c88dce
[ "MIT" ]
1
2018-07-01T19:49:44.000Z
2018-07-01T19:49:44.000Z
#include "Paddle.h" LilyTin::Paddle::Paddle() { } LilyTin::Paddle::~Paddle() { } void LilyTin::Paddle::start() { mTexture.loadFromFile("../res/png/paddleRed.png"); mSprite.setTexture(mTexture); } void LilyTin::Paddle::update(float deltaTime) { bool left = sf::Keyboard::isKeyPressed(sf::Keyboard::Left) || sf::Keyboard::isKeyPressed(sf::Keyboard::A); bool right = sf::Keyboard::isKeyPressed(sf::Keyboard::Right) || sf::Keyboard::isKeyPressed(sf::Keyboard::D); if (left) { mVelocity = sf::Vector2f(-1.0f, 0.0f); } else if (right) { mVelocity = sf::Vector2f(1.0f, 0.0f); } else { mVelocity = sf::Vector2f(0.0f, 0.0f); } mBoundingBox = mSprite.getGlobalBounds(); mTransform.move(mVelocity * mSpeed * deltaTime); } void LilyTin::Paddle::collision() { std::cout << "Paddle Collision!"; } void LilyTin::Paddle::draw(sf::RenderWindow& window) { window.draw(mSprite); mSprite.setPosition(mTransform.getPosition()); }
18.301887
64
0.662887
ItsSeaJay
4c570b3d079bc038581b4359cbf08f4267f96251
7,901
cpp
C++
src/native/Utils.cpp
sx-aurora-test/rv
5d546958b155d7349b20a8cbbeff1b4c65589fd7
[ "Apache-2.0" ]
2
2020-09-04T07:19:24.000Z
2020-10-08T11:36:58.000Z
src/native/Utils.cpp
sx-aurora-test/rv
5d546958b155d7349b20a8cbbeff1b4c65589fd7
[ "Apache-2.0" ]
null
null
null
src/native/Utils.cpp
sx-aurora-test/rv
5d546958b155d7349b20a8cbbeff1b4c65589fd7
[ "Apache-2.0" ]
1
2022-01-25T07:01:35.000Z
2022-01-25T07:01:35.000Z
//===- Utils.cpp -----------------------------===// // // The Region Vectorizer // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // // @author montada #include <llvm/IR/DerivedTypes.h> #include <llvm/IR/Constants.h> #include <utils/rvTools.h> #include "Utils.h" #include "NatBuilder.h" using namespace llvm; using namespace rv; Type *getVectorType(Type *type, unsigned width) { if (type->isVoidTy()) return type; else return FixedVectorType::get(type, width); } Value *createContiguousVector(unsigned width, Type *type, int start, int stride) { std::vector<Constant*> constants(width, nullptr); for (unsigned i = 0; i < width; ++i) { unsigned int val = i*stride + start; Constant *constant = type->isFloatingPointTy() ? ConstantFP::get(type, val) : ConstantInt::get(type, val); constants[i] = constant; } return ConstantVector::get(constants); } llvm::Value *getConstantVector(unsigned width, Type *type, unsigned value) { Constant *constant = type->isFloatingPointTy() ? ConstantFP::get(type, value) : ConstantInt::get(type, value); return getConstantVector(width, constant); } llvm::Value *getConstantVector(unsigned width, Constant *constant) { std::vector<Constant *> constants; constants.reserve(width); for (unsigned i = 0; i < width; ++i) { constants.push_back(constant); } return ConstantVector::get(constants); } Value *getConstantVectorPadded(unsigned width, Type *type, std::vector<unsigned> &values, bool padWithZero) { std::vector<Constant *> constants(width, nullptr); unsigned i = 0; for (; i < values.size(); ++i) { Constant *constant = type->isFloatingPointTy() ? ConstantFP::get(type, values[i]) : ConstantInt::get(type, values[i]); constants[i] = constant; } Constant *zeroConst = type->isFloatingPointTy() ? ConstantFP::get(type, 0) : ConstantInt::get(type, 0); Constant *padding = padWithZero ? zeroConst : UndefValue::get(type); for (; i < width; ++i) { constants[i] = padding; } return ConstantVector::get(constants); } Value *getPointerOperand(Instruction *instr) { LoadInst *load = dyn_cast<LoadInst>(instr); StoreInst *store = dyn_cast<StoreInst>(instr); if (load) return load->getPointerOperand(); else if (store) return store->getPointerOperand(); else return nullptr; } Value *getBasePointer(Value *addr) { GetElementPtrInst *gep = dyn_cast<GetElementPtrInst>(addr); BitCastInst *bc = dyn_cast<BitCastInst>(addr); if (gep) return getBasePointer(gep->getPointerOperand()); if (bc) return getBasePointer(bc->getOperand(0)); return addr; } BasicBlock *createCascadeBlocks(Function *insertInto, unsigned vectorWidth, std::vector<BasicBlock *> &condBlocks, std::vector<BasicBlock *> &maskedBlocks) { BasicBlock *cond, *mask; for (unsigned lane = 0; lane < vectorWidth; ++lane) { cond = BasicBlock::Create(insertInto->getContext(), "cascade_cond_" + std::to_string(lane), insertInto); mask = BasicBlock::Create(insertInto->getContext(), "cascade_masked_" + std::to_string(lane), insertInto); condBlocks.push_back(cond); maskedBlocks.push_back(mask); } return BasicBlock::Create(insertInto->getContext(), "cascade_end", insertInto); } bool isSupportedOperation(Instruction *const inst) { // binary operations (normal & bitwise), load / stores, conversion operations, returns, and other operations // exception: calls with vector or struct return type are not supported CallInst *call = dyn_cast<CallInst>(inst); if (call) { Type *retType = call->getFunctionType()->getReturnType(); if (retType->isStructTy() || retType->isVectorTy()) return false; } return inst->isUnaryOp() || inst->isBinaryOp() || isa<LoadInst>(inst) || isa<StoreInst>(inst) || inst->isCast() || isa<ReturnInst>(inst) || (!isa<ExtractElementInst>(inst) && !isa<ExtractValueInst>(inst) && !isa<InsertElementInst>(inst) && !isa<InsertValueInst>(inst) && !isa<ShuffleVectorInst>(inst) && (inst->getOpcode() >= Instruction::OtherOpsBegin && inst->getOpcode() <= Instruction::OtherOpsEnd)); } bool isHomogeneousStruct(StructType *const type, DataLayout &layout) { assert(type->getStructNumElements() > 0 && "emptry struct!"); Type *prevElTy = nullptr; for (Type *elTy : type->elements()) { if (!elTy->isStructTy() && !(elTy->isIntegerTy() || elTy->isFloatingPointTy())) return false; else if (elTy->isStructTy() && !isHomogeneousStruct(cast<StructType>(elTy), layout)) return false; if (prevElTy && layout.getTypeStoreSize(prevElTy) != layout.getTypeStoreSize(elTy)) return false; prevElTy = elTy; } return true; } StructType *isStructAccess(Value *const address) { assert(address->getType()->isPointerTy() && "not a pointer"); if (isa<BitCastInst>(address)) return isStructAccess(cast<BitCastInst>(address)->getOperand(0)); Type *type; if (isa<GetElementPtrInst>(address)) type = cast<GetElementPtrInst>(address)->getSourceElementType(); else type = address->getType(); return containsStruct(type); } StructType *containsStruct(Type *const type) { if (type->isStructTy()) return cast<StructType>(type); if (type->isPointerTy()) return containsStruct(cast<PointerType>(type)->getPointerElementType()); else return nullptr; } unsigned getNumLeafElements(Type *const type, Type *const leafType, DataLayout &layout) { return (unsigned) (layout.getTypeStoreSize(type) / layout.getTypeStoreSize(leafType)); #if 0 std::deque<std::pair<Type *const, unsigned>> queue; queue.push_back(std::pair<Type *const, unsigned>(type, 0)); unsigned nodes = 0; unsigned lastDistance = 0; bool lastTrip = false; while (!queue.empty()) { Type *const ty = queue.front().first; unsigned distance = queue.front().second; queue.pop_front(); if (distance == lastDistance) ++nodes; else if (!lastTrip) { nodes = 1; lastDistance = distance; } else break; if (ty->getNumContainedTypes() == 0) lastTrip = true; if (!lastTrip) for (unsigned i = 0; i < ty->getNumContainedTypes(); ++i) { Type *const elTy = ty->getContainedType(i); queue.push_back(std::pair<Type *const, unsigned>(elTy, distance + 1)); } } return nodes; #endif } unsigned getStructOffset(GetElementPtrInst *const gep) { Type *srcPtrType = gep->getSourceElementType(); std::vector<Value *> indices; for (unsigned i = 0; i < gep->getNumIndices(); ++i) { Value *idx = gep->getOperand(i + 1); indices.push_back(idx); Type *indexedType = GetElementPtrInst::getIndexedType(srcPtrType, indices); if (indexedType->isStructTy()) { unsigned structOffset = 0; for (++i; i < gep->getNumIndices(); ++i) { idx = gep->getOperand(i + 1); assert(isa<ConstantInt>(idx) && "element access with non-constant!"); unsigned idxValue = (unsigned) cast<ConstantInt>(idx)->getLimitedValue(); structOffset += idxValue; } return structOffset; } } return 0; } void setInsertionToDomBlockEnd(IRBuilder<> &builder, std::vector<llvm::BasicBlock *> &blocks) { BasicBlock *domBlock = nullptr; for (BasicBlock *block : blocks) { if (block->getName().count("cascade_masked")) continue; domBlock = block; if (block->empty()) break; if (!block->getTerminator()) break; } assert(domBlock && "no block found!"); Instruction *term; if ((term = domBlock->getTerminator())) builder.SetInsertPoint(term); else builder.SetInsertPoint(domBlock); }
32.24898
141
0.654727
sx-aurora-test
4c59fe702fd49d18898f89598a63ac96541d1ac3
13,407
cpp
C++
tests/sm/test_btree_basic.cpp
lslersch/zero
ab779235f3c3bf58d6a3aa9d2a0a5296578ee498
[ "Spencer-94" ]
27
2015-04-21T08:52:37.000Z
2022-03-18T03:38:58.000Z
tests/sm/test_btree_basic.cpp
lslersch/zero
ab779235f3c3bf58d6a3aa9d2a0a5296578ee498
[ "Spencer-94" ]
24
2015-07-04T10:45:41.000Z
2018-05-03T08:52:36.000Z
tests/sm/test_btree_basic.cpp
lslersch/zero
ab779235f3c3bf58d6a3aa9d2a0a5296578ee498
[ "Spencer-94" ]
15
2015-03-31T09:57:10.000Z
2021-06-09T13:44:58.000Z
#include "btree_test_env.h" #include "gtest/gtest.h" #include "sm_vas.h" #include "btree.h" #include "btcursor.h" btree_test_env *test_env; /** * Unit test for basic Insert/Select/Delete features of BTree. */ w_rc_t insert_simple(ss_m* ssm, test_volume_t *test_volume) { StoreID stid; PageID root_pid; W_DO(x_btree_create_index(ssm, test_volume, stid, root_pid)); W_DO(test_env->begin_xct()); W_DO(test_env->btree_insert(stid, "a1", "data1")); W_DO(test_env->btree_insert(stid, "aa2", "data2")); W_DO(test_env->btree_insert(stid, "aaaa3", "data3")); W_DO(test_env->commit_xct()); x_btree_scan_result s; W_DO(test_env->btree_scan(stid, s)); EXPECT_EQ (3, s.rownum); EXPECT_EQ (std::string("a1"), s.minkey); EXPECT_EQ (std::string("aaaa3"), s.maxkey); return RCOK; } TEST (BtreeBasicTest, InsertSimple) { test_env->empty_logdata_dir(); EXPECT_EQ(test_env->runBtreeTest(insert_simple), 0); } TEST (BtreeBasicTest, InsertSimpleLock) { test_env->empty_logdata_dir(); EXPECT_EQ(test_env->runBtreeTest(insert_simple, true), 0); } w_rc_t insert_toolong_fail(ss_m* ssm, test_volume_t *test_volume) { StoreID stid; PageID root_pid; W_DO(x_btree_create_index(ssm, test_volume, stid, root_pid)); W_DO(test_env->begin_xct()); W_DO(test_env->btree_insert (stid, "a1", "data1lkjdflgjldfjgkldfjg1")); W_DO(test_env->btree_insert (stid, "ab2", "data1lkjdflgjldfjgkldfjg2")); W_DO(test_env->btree_insert (stid, "abc3", "data1lkjdflgjldfjgkldfjg3")); W_DO(test_env->btree_insert (stid, "abcd4", "data1lkjdflgjldfjgkldfjg4")); // this one is fine. though the key is longer than the definition, we actually don't care the schema. W_DO(test_env->btree_insert (stid, "abcde5", "data1lkjdflgjldfjgkldfjg5")); // should fail here because one page can't hold this record char long_data[SM_PAGESIZE + 1] = ""; memset (long_data, 'a', SM_PAGESIZE); long_data[SM_PAGESIZE] = '\0'; cout << "We should see too-long error here:" << endl; w_rc_t rc = test_env->btree_insert (stid, "abcdef6", long_data); EXPECT_EQ (rc.err_num(), (w_error_codes) eRECWONTFIT); if (rc.err_num() == eRECWONTFIT) { cout << "yep, we did. the following message is NOT an error." << endl; } else { cerr << "wtf" << endl; } W_DO(test_env->commit_xct()); x_btree_scan_result s; W_DO(test_env->btree_scan(stid, s)); EXPECT_EQ (5, s.rownum); EXPECT_EQ (std::string("a1"), s.minkey); EXPECT_EQ (std::string("abcde5"), s.maxkey); return rc; } TEST (BtreeBasicTest, InsertTooLongfail) { test_env->empty_logdata_dir(); EXPECT_NE(test_env->runBtreeTest(insert_toolong_fail), 0); } TEST (BtreeBasicTest, InsertTooLongfailLock) { test_env->empty_logdata_dir(); EXPECT_NE(test_env->runBtreeTest(insert_toolong_fail, true), 0); } w_rc_t insert_dup_fail(ss_m* ssm, test_volume_t *test_volume) { StoreID stid; PageID root_pid; W_DO(x_btree_create_index(ssm, test_volume, stid, root_pid)); W_DO(test_env->begin_xct()); W_DO(test_env->btree_insert (stid, "key005", "data5")); W_DO(test_env->btree_insert (stid, "key004", "data4")); W_DO(test_env->btree_insert (stid, "key006", "data6")); // should fail here cout << "We should see a duplicate error here:" << endl; w_rc_t rc = test_env->btree_insert (stid, "key006", "data7"); EXPECT_EQ (rc.err_num(), (w_error_codes) eDUPLICATE); if (rc.err_num() == eDUPLICATE) { cout << "yep, we did. the following message is NOT an error." << endl; } else { cerr << "wtf: no duplicate?" << endl; } W_DO(test_env->commit_xct()); x_btree_scan_result s; W_DO(test_env->btree_scan(stid, s)); EXPECT_EQ (3, s.rownum); EXPECT_EQ (std::string("key004"), s.minkey); EXPECT_EQ (std::string("key006"), s.maxkey); return rc; } TEST (BtreeBasicTest, InsertDupFail) { test_env->empty_logdata_dir(); EXPECT_NE(test_env->runBtreeTest(insert_dup_fail), 0); } TEST (BtreeBasicTest, InsertDupFailLock) { test_env->empty_logdata_dir(); EXPECT_NE(test_env->runBtreeTest(insert_dup_fail, true), 0); } w_rc_t insert_remove(ss_m* ssm, test_volume_t *test_volume) { StoreID stid; PageID root_pid; W_DO(x_btree_create_index(ssm, test_volume, stid, root_pid)); W_DO(test_env->begin_xct()); W_DO(test_env->btree_insert (stid, "key005", "data5")); W_DO(test_env->btree_insert (stid, "key004", "data4")); W_DO(test_env->btree_insert (stid, "key006", "data6")); W_DO(test_env->btree_remove (stid, "key006")); W_DO(test_env->btree_insert (stid, "key006", "data7")); W_DO(test_env->commit_xct()); x_btree_scan_result s; W_DO(test_env->btree_scan(stid, s)); EXPECT_EQ (3, s.rownum); EXPECT_EQ (std::string("key004"), s.minkey); EXPECT_EQ (std::string("key006"), s.maxkey); return RCOK; } TEST (BtreeBasicTest, InsertRemove) { test_env->empty_logdata_dir(); EXPECT_EQ(test_env->runBtreeTest(insert_remove), 0); } TEST (BtreeBasicTest, InsertRemoveLock) { test_env->empty_logdata_dir(); EXPECT_EQ(test_env->runBtreeTest(insert_remove, true), 0); } w_rc_t insert_remove_fail(ss_m* ssm, test_volume_t *test_volume) { StoreID stid; PageID root_pid; W_DO(x_btree_create_index(ssm, test_volume, stid, root_pid)); W_DO(test_env->begin_xct()); W_DO(test_env->btree_insert (stid, "key005", "data5")); W_DO(test_env->btree_insert (stid, "key004", "data4")); W_DO(test_env->btree_insert (stid, "key006", "data6")); // should fail here cout << "We should see a NOTFOUND error here:" << endl; w_rc_t rc = test_env->btree_remove (stid, "key003"); EXPECT_EQ (rc.err_num(), eNOTFOUND); if (rc.err_num() == eNOTFOUND) { cout << "yep, we did. the following message is NOT an error." << endl; } else { cerr << "wtf?" << endl; } W_DO(test_env->commit_xct()); x_btree_scan_result s; W_DO(test_env->btree_scan(stid, s)); EXPECT_EQ (3, s.rownum); EXPECT_EQ (std::string("key004"), s.minkey); EXPECT_EQ (std::string("key006"), s.maxkey); return rc; } TEST (BtreeBasicTest, InsertRemoveFail) { test_env->empty_logdata_dir(); EXPECT_NE(test_env->runBtreeTest(insert_remove_fail), 0); } TEST (BtreeBasicTest, InsertRemoveFailLock) { test_env->empty_logdata_dir(); EXPECT_NE(test_env->runBtreeTest(insert_remove_fail, true), 0); } w_rc_t insert_remove_fail_repeat(ss_m* ssm, test_volume_t *test_volume) { StoreID stid; PageID root_pid; W_DO(x_btree_create_index(ssm, test_volume, stid, root_pid)); W_DO(test_env->begin_xct()); W_DO(test_env->btree_insert (stid, "key005", "data5")); W_DO(test_env->btree_insert (stid, "key004", "data4")); W_DO(test_env->btree_insert (stid, "key006", "data6")); W_DO(test_env->btree_remove (stid, "key005")); // should fail here cout << "We should see a NOTFOUND error here:" << endl; w_rc_t rc = test_env->btree_remove (stid, "key005"); EXPECT_EQ (rc.err_num(), (w_error_codes) eNOTFOUND); if (rc.err_num() == eNOTFOUND) { cout << "yep, we did. the following message is NOT an error." << endl; } else { cerr << "wtf?" << endl; } W_DO(test_env->commit_xct()); x_btree_scan_result s; W_DO(test_env->btree_scan(stid, s)); EXPECT_EQ (2, s.rownum); EXPECT_EQ (std::string("key004"), s.minkey); EXPECT_EQ (std::string("key006"), s.maxkey); return rc; } TEST (BtreeBasicTest, InsertRemoveFailRepeat) { test_env->empty_logdata_dir(); EXPECT_NE(test_env->runBtreeTest(insert_remove_fail_repeat), 0); } TEST (BtreeBasicTest, InsertRemoveFailRepeatLock) { test_env->empty_logdata_dir(); EXPECT_NE(test_env->runBtreeTest(insert_remove_fail_repeat, true), 0); } w_rc_t insert_update(ss_m* ssm, test_volume_t *test_volume) { StoreID stid; PageID root_pid; W_DO(x_btree_create_index(ssm, test_volume, stid, root_pid)); W_DO(test_env->begin_xct()); W_DO(test_env->btree_insert (stid, "key005", "data5")); W_DO(test_env->btree_insert (stid, "key004", "data4")); W_DO(test_env->btree_insert (stid, "key006", "data6")); W_DO(test_env->btree_update (stid, "key006", "data7")); W_DO(test_env->commit_xct()); x_btree_scan_result s; W_DO(test_env->btree_scan(stid, s)); EXPECT_EQ (3, s.rownum); EXPECT_EQ (std::string("key004"), s.minkey); EXPECT_EQ (std::string("key006"), s.maxkey); W_DO(x_btree_verify(ssm, stid)); W_DO(test_env->begin_xct()); std::string data; test_env->btree_lookup(stid, "key006", data); EXPECT_EQ (std::string("data7"), data); W_DO(test_env->btree_update (stid, "key006", "d")); test_env->btree_lookup(stid, "key006", data); EXPECT_EQ (std::string("d"), data); W_DO(test_env->btree_update (stid, "key006", "dksjdfljslkdfjskldjf")); test_env->btree_lookup(stid, "key006", data); EXPECT_EQ (std::string("dksjdfljslkdfjskldjf"), data); W_DO(test_env->commit_xct()); W_DO(x_btree_verify(ssm, stid)); return RCOK; } TEST (BtreeBasicTest, InsertUpdate) { test_env->empty_logdata_dir(); EXPECT_EQ(test_env->runBtreeTest(insert_update), 0); } TEST (BtreeBasicTest, InsertUpdateLock) { test_env->empty_logdata_dir(); EXPECT_EQ(test_env->runBtreeTest(insert_update, true), 0); } w_rc_t insert_overwrite(ss_m* ssm, test_volume_t *test_volume) { StoreID stid; PageID root_pid; W_DO(x_btree_create_index(ssm, test_volume, stid, root_pid)); W_DO(test_env->begin_xct()); W_DO(test_env->btree_insert (stid, "key005", "data5")); W_DO(test_env->btree_insert (stid, "key004", "data4")); W_DO(test_env->btree_insert (stid, "key006", "data6")); W_DO(test_env->btree_overwrite (stid, "key006", "b", 2)); W_DO(test_env->commit_xct()); x_btree_scan_result s; W_DO(test_env->btree_scan(stid, s)); EXPECT_EQ (3, s.rownum); EXPECT_EQ (std::string("key004"), s.minkey); EXPECT_EQ (std::string("key006"), s.maxkey); W_DO(x_btree_verify(ssm, stid)); std::string data; test_env->btree_lookup_and_commit(stid, "key006", data); EXPECT_EQ (std::string("daba6"), data); return RCOK; } TEST (BtreeBasicTest, InsertOverwrite) { test_env->empty_logdata_dir(); EXPECT_EQ(test_env->runBtreeTest(insert_overwrite), 0); } TEST (BtreeBasicTest, InsertOverwriteLock) { test_env->empty_logdata_dir(); EXPECT_EQ(test_env->runBtreeTest(insert_overwrite, true), 0); } w_rc_t insert_overwrite_fail(ss_m* ssm, test_volume_t *test_volume) { StoreID stid; PageID root_pid; W_DO(x_btree_create_index(ssm, test_volume, stid, root_pid)); W_DO(test_env->begin_xct()); W_DO(test_env->btree_insert (stid, "key005", "data5")); W_DO(test_env->btree_insert (stid, "key004", "data4")); W_DO(test_env->btree_insert (stid, "key006", "data6")); W_DO(test_env->btree_overwrite (stid, "key006", "b", 4)); rc_t rc1 = test_env->btree_overwrite (stid, "key006", "b", 5); EXPECT_EQ (eRECWONTFIT, rc1.err_num()); rc_t rc2 = test_env->btree_overwrite (stid, "key006", "b", 6); EXPECT_EQ (eRECWONTFIT, rc2.err_num()); W_DO(test_env->commit_xct()); return RCOK; } TEST (BtreeBasicTest, InsertOverwriteFail) { test_env->empty_logdata_dir(); EXPECT_EQ(test_env->runBtreeTest(insert_overwrite_fail), 0); } TEST (BtreeBasicTest, InsertOverwriteFailLock) { test_env->empty_logdata_dir(); EXPECT_EQ(test_env->runBtreeTest(insert_overwrite_fail, true), 0); } w_rc_t insert_many(ss_m* ssm, test_volume_t *test_volume) { StoreID stid; PageID root_pid; W_DO(x_btree_create_index(ssm, test_volume, stid, root_pid)); W_DO(ssm->begin_xct()); test_env->set_xct_query_lock(); w_keystr_t key; vec_t data; char keystr[6] = ""; char datastr[50] = ""; memset(keystr, '\0', 6); memset(datastr, '\0', 50); keystr[0] = 'k'; keystr[1] = 'e'; keystr[2] = 'y'; datastr[0] = 'd'; datastr[1] = 'a'; datastr[2] = 't'; cout << "Inserting 200 records into BTree..." << endl; for (int i = 0; i < 200; ++i) { datastr[3] = keystr[3] = ('0' + ((i / 100) % 10)); datastr[4] = keystr[4] = ('0' + ((i / 10) % 10)); datastr[5] = keystr[5] = ('0' + ((i / 1) % 10)); for (int j = 6; j < 50; ++j) { ++datastr[j]; if (datastr[j] > '9') datastr[j] = '0'; } key.construct_regularkey(keystr, 6); data.set(datastr, 50); W_DO(ssm->create_assoc(stid, key, data)); } W_DO(ssm->commit_xct()); cout << "Inserted." << endl; x_btree_scan_result s; W_DO(x_btree_scan(ssm, stid, s, test_env->get_use_locks())); EXPECT_EQ (200, s.rownum); EXPECT_EQ (std::string("key000"), s.minkey); EXPECT_EQ (std::string("key199"), s.maxkey); return RCOK; } TEST (BtreeBasicTest, InsertMany) { test_env->empty_logdata_dir(); EXPECT_EQ(test_env->runBtreeTest(insert_many), 0); } TEST (BtreeBasicTest, InsertManyLock) { test_env->empty_logdata_dir(); EXPECT_EQ(test_env->runBtreeTest(insert_many, true), 0); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); test_env = new btree_test_env(); ::testing::AddGlobalTestEnvironment(test_env); return RUN_ALL_TESTS(); }
33.68593
105
0.664877
lslersch
4c5a359188817fdbd8c0198157ea1cd50b3434d3
3,005
cpp
C++
code_reading/oceanbase-master/src/observer/virtual_table/ob_virtual_sql_monitor_statname.cpp
wangcy6/weekly_read
3a8837ee9cd957787ee1785e4066dd623e02e13a
[ "Apache-2.0" ]
null
null
null
code_reading/oceanbase-master/src/observer/virtual_table/ob_virtual_sql_monitor_statname.cpp
wangcy6/weekly_read
3a8837ee9cd957787ee1785e4066dd623e02e13a
[ "Apache-2.0" ]
null
null
null
code_reading/oceanbase-master/src/observer/virtual_table/ob_virtual_sql_monitor_statname.cpp
wangcy6/weekly_read
3a8837ee9cd957787ee1785e4066dd623e02e13a
[ "Apache-2.0" ]
1
2020-10-18T12:59:31.000Z
2020-10-18T12:59:31.000Z
/** * Copyright (c) 2021 OceanBase * OceanBase CE is licensed under Mulan PubL v2. * You can use this software according to the terms and conditions of the Mulan PubL v2. * You may obtain a copy of Mulan PubL v2 at: * http://license.coscl.org.cn/MulanPubL-2.0 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PubL v2 for more details. */ #include "observer/virtual_table/ob_virtual_sql_monitor_statname.h" #include "share/diagnosis/ob_sql_monitor_statname.h" using namespace oceanbase::observer; using namespace oceanbase::common; using namespace oceanbase::sql; ObVirtualSqlMonitorStatname::ObVirtualSqlMonitorStatname() : ObVirtualTableScannerIterator(), stat_iter_(1) {} ObVirtualSqlMonitorStatname::~ObVirtualSqlMonitorStatname() { reset(); } void ObVirtualSqlMonitorStatname::reset() { ObVirtualTableScannerIterator::reset(); stat_iter_ = 1; // skip MONITOR_STATNAME_BEGIN for (int64_t i = 0; i < OB_ROW_MAX_COLUMNS_COUNT; i++) { cells_[i].reset(); } } int ObVirtualSqlMonitorStatname::inner_get_next_row(ObNewRow*& row) { int ret = OB_SUCCESS; if (OB_UNLIKELY(NULL == allocator_)) { ret = OB_NOT_INIT; SERVER_LOG(WARN, "allocator is NULL", K(ret)); } else { const int64_t col_count = output_column_ids_.count(); cur_row_.cells_ = cells_; cur_row_.count_ = reserved_column_cnt_; if (stat_iter_ >= ObSqlMonitorStatIds::MONITOR_STATNAME_END) { ret = OB_ITER_END; } if (OB_SUCC(ret)) { uint64_t cell_idx = 0; for (int64_t i = 0; OB_SUCC(ret) && i < col_count; ++i) { uint64_t col_id = output_column_ids_.at(i); switch (col_id) { case ID: { cells_[cell_idx].set_int(stat_iter_); break; } case GROUP_ID: { cells_[cell_idx].set_int(0); break; } case NAME: { cells_[cell_idx].set_varchar(OB_MONITOR_STATS[stat_iter_].name_); cells_[cell_idx].set_collation_type(ObCharset::get_default_collation(ObCharset::get_default_charset())); break; } case DESCRIPTION: { cells_[cell_idx].set_varchar(OB_MONITOR_STATS[stat_iter_].description_); cells_[cell_idx].set_collation_type(ObCharset::get_default_collation(ObCharset::get_default_charset())); break; } default: { ret = OB_ERR_UNEXPECTED; SERVER_LOG(WARN, "invalid column id", K(ret), K(cell_idx), K(output_column_ids_), K(col_id)); break; } } if (OB_SUCC(ret)) { cell_idx++; } } } if (OB_SUCC(ret)) { stat_iter_++; row = &cur_row_; if (ObSqlMonitorStatIds::MONITOR_STATNAME_END == stat_iter_) { stat_iter_++; } } } return ret; }
30.979381
116
0.648586
wangcy6
4c5a826ebefb81e6e0062c3ce90b8057aaba4c06
37,943
cpp
C++
SPOUTSDK/SpoutGL/SpoutControls.cpp
initialfx/Spout2
0f88e631d5328d5e5aedef287a7f8f3076b99be3
[ "BSD-2-Clause" ]
null
null
null
SPOUTSDK/SpoutGL/SpoutControls.cpp
initialfx/Spout2
0f88e631d5328d5e5aedef287a7f8f3076b99be3
[ "BSD-2-Clause" ]
null
null
null
SPOUTSDK/SpoutGL/SpoutControls.cpp
initialfx/Spout2
0f88e631d5328d5e5aedef287a7f8f3076b99be3
[ "BSD-2-Clause" ]
null
null
null
// // SpoutControls // // Allows an application to control a Spout sender // // ==================================================================================== // Revisions : // // 21.06.15 - project start // 08.07.15 - project Version 1 // 16.07.15 - changed CheckControls to return the control index that was changed // int SpoutControls::CheckControls(vector<control> &controls) // 17.07.15 - introduced two versions of CheckControls // introduced Lesser GPL licence // 22.07.15 - included CreateControl // - removed clear control file path from the registry // so that it remains for controllers to find the last sender started // 27.07.15 - Added "OpenSpoutController" // 18.08.15 - Cleanup for 1.002 release // 24.09.15 - re-ordering in cleanup // 24.12.15 - added executable path to registry "ControlPath" // 30.12.15 - restored CopyControlFile // - Moved GetControls public // 13.01.16 - Changed OpenSpoutController to look for executable host path // as well as SpoutControls installation path. // 15.01.16 - Added fixed "NoClose" argument for opening SpoutController from an application // so that the Close button is hidden. // 17.01.16 - Added commandline argument to the OpenController function // "NoClose" is now a key word // - CloseControls - look for the SpoutController window and close it // 18.01.16 - added getcwd to OpenSpoutController // - cleanup on exit confirmed for Processing // - Instead of closecontrols, close the controller in CleanUp if it has been opened // 26.01.16 - added default empty string for OpenSpoutController - then needs SpoutControls installation // 27.01.16 - brought SpoutController.exe topmost before close to prevent freeze if hidden // 19.02.16 - fixed command line for OpenSpoutController // 08.05.16 - fixed OpenSpoutController function to detect SpoutController.exe // 11.05.16 - 1.007 // 02.09.16 - safety checks for mailslot handle. Code cleanup. // 17.01.17 - 1.008 release for Spout 2.006 - no code changes // 27.01.17 - Changes to OpenSpoutController to find a SpoutControls installation // 02.06.17 - Registry functions called from SpoutUtils // 13.12.17 - OpenControls - returns false if no controls - no registry write // 28.12.17 - Added GetFileControls // 04.12.18 - corrected return value for GetFileControls // 03.01.19 - Changed to revised registry functions in SpoutUtils // 28.04.19 - Rebuild VS2017 - 2.007 - /MT // 27.12.20 - Remove from Spout SDK and use for Processing library // Rebuild Win32/x64 - /MT : VS2017 - 2.007 // // // ==================================================================================== // // Copyright (C) 2015-2021. Lynn Jarvis, Leading Edge. Pty. Ltd. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You will receive a copy of the GNU Lesser General Public License along // with this program. If not, see http://www.gnu.org/licenses/. // #include "SpoutControls.h" SpoutControls::SpoutControls() { m_sharedMemoryName = ""; // Memory map name sring m_hSharedMemory = NULL; // Memory map handle m_pBuffer = NULL; // Shared memory pointer m_hAccessMutex = NULL; // Map access mutex m_hSlot = NULL; // Handle to the mailslot m_dwSize = 0; // Size of the memory map } //--------------------------------------------------------- SpoutControls::~SpoutControls() { Cleanup(); } // ====================================================================== // Public // ====================================================================== // ===================================================================== // // CONTROLLER // // ===================================================================== // //--------------------------------------------------------- // Find a control map name in the registry // This will only exist if the sender has created it and is running // It is erased when the sender closes. bool SpoutControls::FindControls(std::string &mapname) { char path[MAX_PATH]; // Find the if controller map name exists the registry if(ReadPathFromRegistry(HKEY_CURRENT_USER, "Software\\Leading Edge\\Spout", "ControlMap", path) ) { if(path[0] > 0) { mapname = path; return true; } } return false; } //--------------------------------------------------------- // Create a controls memory map, existence mutex and access mutex // and fill the memory map with the control vector bool SpoutControls::CreateControls(std::string mapname, std::vector<control> controls) { std::string mutexName; std::string sharedMemoryName; // Create a mutex to control the write / read mutexName = mapname; mutexName += "ControlsAccess"; mutexName += "_mutex"; m_hAccessMutex = CreateMutexA(NULL, true, mutexName.c_str()); // initial ownership if (!m_hAccessMutex) { printf("CreateControls : Mutex creation failed\n"); return false; } // Create a memory map that will contain the updated control information m_sharedMemoryName = mapname; // Global shared memory name used throughout sharedMemoryName = mapname; sharedMemoryName += "Controls"; sharedMemoryName += "_map"; // Calculate the size required for the memory map // First 4 bytes on the first line are the size of the control array // Next the information for each control // Type DWORD (4 bytes) Name (16 bytes) Data (256 bytes) - total 276 bytes per control // Total : 276 + size *(276) m_dwSize = 276 + (DWORD)(controls.size()*276); // Create or open the shared memory map m_hSharedMemory = CreateFileMappingA(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, m_dwSize, (LPCSTR)sharedMemoryName.c_str()); if (m_hSharedMemory == NULL || m_hSharedMemory == INVALID_HANDLE_VALUE) { printf("CreateControls : error occured while creating file mapping object : %d\n", GetLastError() ); CloseHandle(m_hAccessMutex); return false; } // Map a view to get a pointer to write to m_pBuffer = (LPTSTR)MapViewOfFile(m_hSharedMemory, FILE_MAP_ALL_ACCESS, 0, 0, m_dwSize); if (m_pBuffer == NULL) { printf("CreateControls : error occured while mapping view of the file : %d\n", GetLastError() ); CloseHandle(m_hSharedMemory); CloseHandle(m_hAccessMutex); return false; } WriteControls(m_pBuffer, controls); UnmapViewOfFile(m_pBuffer); // End of creation so unlock the access mutex // If the reader tries to access the memory there will be nothing in it ReleaseMutex(m_hAccessMutex); return true; } //--------------------------------------------------------- // Set the changed controls to the memory map and inform the sender bool SpoutControls::SetControls(std::vector<control> controls) { if(UpdateControls(controls)) { // Inform the sender that new control data is ready WriteMail(m_sharedMemoryName, "Ready"); return true; } return false; } //--------------------------------------------------------- // Find a control map and update it with the controls bool SpoutControls::UpdateControls(std::vector<control> controls) { std::string mutexName; std::string memoryMapName; // local name of the shared memory HANDLE hMemory = NULL; // local handle to shared memory LPTSTR pBuf = NULL; // local shared memory pointer HANDLE hAccessMutex = NULL; DWORD dwWaitResult; DWORD dwMapSize = 0; char *buf = NULL; char temp[256]; // // Controller writes to the memory map to update control data // // Check the access mutex mutexName = m_sharedMemoryName; // mapname; mutexName += "ControlsAccess"; mutexName += "_mutex"; hAccessMutex = OpenMutexA(MUTEX_ALL_ACCESS, 0, mutexName.c_str()); if(!hAccessMutex) { printf("UpdateControls - access mutex does not exist\n"); CloseHandle(hAccessMutex); return false; } dwWaitResult = WaitForSingleObject(m_hAccessMutex, 67); if (dwWaitResult != WAIT_OBJECT_0) { // reader is accessing it CloseHandle(hAccessMutex); return false; } // The mutex is now locked so that the reader does not read while writing // The memory map name is defined by the global mapname memoryMapName = m_sharedMemoryName; // local name; memoryMapName += "Controls"; memoryMapName += "_map"; // ==================================== // At this stage the map size is not known, but it's size // is the first 4 bytes of the map, so read that first to get the size hMemory = CreateFileMappingA ( INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, 4, (LPCSTR)memoryMapName.c_str()); if (hMemory == NULL || hMemory == INVALID_HANDLE_VALUE) { printf("UpdateControls : Error occured while opening file mapping object : %d\n", GetLastError() ); CloseHandle(hAccessMutex); return false; } pBuf = (LPTSTR)MapViewOfFile(hMemory, FILE_MAP_ALL_ACCESS, 0, 0, 4); // only 4 bytes to read if (pBuf == NULL || pBuf[0] == 0) { printf("UpdateControls : Error 1 occured while mapping view of the file : %d\n", GetLastError() ); if(pBuf) UnmapViewOfFile(pBuf); CloseHandle(hMemory); CloseHandle(hAccessMutex); return false; } // Retrieve the map size - the first 4 bytes buf = (char *)pBuf; // moveable pointer for(int i = 0; i<4; i++) temp[i] = *buf++; temp[4] = 0; dwMapSize = (DWORD)atoi(temp); // Now close the map and re-open it with the known size UnmapViewOfFile(pBuf); CloseHandle(hMemory); // First check that the map size is correct for the control vector passed // First 4 bytes on the first line are the size of the control array // Next the information for each control // Type DWORD (4 bytes) Name (16 bytes) Data (256 bytes) - total 276 bytes per control // Total : 276 + size *(276) if(dwMapSize != (276 + (DWORD)(controls.size()*276)) ) { CloseHandle(hAccessMutex); return false; } // Now open the full map and write the control data to it hMemory = CreateFileMappingA ( INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, dwMapSize, (LPCSTR)memoryMapName.c_str()); if (hMemory == NULL || hMemory == INVALID_HANDLE_VALUE) { CloseHandle(hAccessMutex); return false; } pBuf = (LPTSTR)MapViewOfFile(hMemory, FILE_MAP_ALL_ACCESS, 0, 0, dwMapSize); if (pBuf == NULL) { printf("UpdateControls : Error 2 occured while mapping view of the file : %d\n", GetLastError() ); CloseHandle(hMemory); CloseHandle(hAccessMutex); return false; } // // Write the controls to the memory map // WriteControls(pBuf, controls); UnmapViewOfFile(pBuf); // Finished with the buffer CloseHandle(hMemory); // Closes the memory map ReleaseMutex(hAccessMutex); // Unlock the access mutex so that the reader can read from the memory map CloseHandle(hAccessMutex);// Close the local handle return true; } //--------------------------------------------------------- // Get controls from an existing map bool SpoutControls::GetControls(std::vector<control> &controls) { std::string mutexName; std::string memoryMapName; // local name of the shared memory HANDLE hMemory = NULL; // local handle to shared memory LPTSTR pBuf = NULL; // local shared memory pointer HANDLE hAccessMutex = NULL; DWORD dwWaitResult; DWORD dwMapSize = 0; // int nControls = 0; // int ControlType = 0; // float ControlValue = 0; // Float value of a control std::string ControlText; // Text data of a control char *buf = NULL; char temp[256]; // // Reader reads the memory map to retrieve control data // // Check the access mutex mutexName = m_sharedMemoryName; // mapname; mutexName += "ControlsAccess"; mutexName += "_mutex"; hAccessMutex = OpenMutexA(MUTEX_ALL_ACCESS, 0, mutexName.c_str()); if(!hAccessMutex) { printf("GetControls : No access mutex\n"); CloseHandle(hAccessMutex); return false; } dwWaitResult = WaitForSingleObject(hAccessMutex, 67); if (dwWaitResult != WAIT_OBJECT_0) { // writer is accessing it CloseHandle(hAccessMutex); return false; } // The mutex is now locked so that the writer does not write while reading // The memory map name is defined by the global mapname memoryMapName = m_sharedMemoryName; memoryMapName += "Controls"; memoryMapName += "_map"; // ==================================== // At this stage the map size is not known, but it's size is the // first 4 bytes of the map so read that first to get the size hMemory = CreateFileMappingA ( INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, 4, (LPCSTR)memoryMapName.c_str()); if (hMemory == NULL || hMemory == INVALID_HANDLE_VALUE) { printf("GetControls - Error occured opening file mapping object : %d\n", GetLastError() ); ReleaseMutex(hAccessMutex); CloseHandle(hAccessMutex); return false; } pBuf = (LPTSTR)MapViewOfFile(hMemory, FILE_MAP_ALL_ACCESS, 0, 0, 4); // only 4 bytes to read // Did the mapping fail or is there nothing in the map if (pBuf == NULL || pBuf[0] == 0) { printf("GetControls - Error 1 occured while mapping view of the file : %d\n", GetLastError() ); if(pBuf) UnmapViewOfFile(pBuf); CloseHandle(hMemory); ReleaseMutex(hAccessMutex); CloseHandle(hAccessMutex); return false; } // Retrieve the map size - the first 4 bytes buf = (char *)pBuf; // moveable pointer for(int i = 0; i<4; i++) temp[i] = *buf++; temp[4] = 0; dwMapSize = (DWORD)atoi(temp); // Now close the map and re-open it with the known size UnmapViewOfFile(pBuf); CloseHandle(hMemory); hMemory = CreateFileMappingA ( INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, dwMapSize, (LPCSTR)memoryMapName.c_str()); if (hMemory == NULL || hMemory == INVALID_HANDLE_VALUE) { printf("GetControls - CreateFileMapping failed\n"); ReleaseMutex(hAccessMutex); CloseHandle(hAccessMutex); return false; } pBuf = (LPTSTR)MapViewOfFile(hMemory, FILE_MAP_ALL_ACCESS, 0, 0, dwMapSize); if (pBuf == NULL) { printf("GetControls - Error 2 occured while mapping view of the file : %d\n", GetLastError() ); CloseHandle(hMemory); ReleaseMutex(hAccessMutex); CloseHandle(hAccessMutex); return false; } // // Get the controls from the memory map // ReadControls(pBuf, controls); // Finished with the buffer UnmapViewOfFile(pBuf); // Reader closes the memory map CloseHandle(hMemory); // Unlock the access mutex so that the writer can write to the memory map ReleaseMutex(hAccessMutex); // Close the local mutex handle // All handles must be closed before the writer finally closes with the creation handle CloseHandle(hAccessMutex); return true; } //--------------------------------------------------------- // OpenControls // A sender creates the controls and then calls OpenControls with a control name // so that the controller can set up a memory map ans share data with the sender as it changes the controls // The sender provides the map name, creates the mailslot and writes the map name to the registry bool SpoutControls::OpenControls(std::string mapname) { char Path[MAX_PATH]; HRESULT hr; Path[0] = 0; // 13.12.17 - return if no controls // TODO remove size check below // printf("SpoutControls::OpenControls(%s) - controls size = %d\n", mapname.c_str(), filecontrols.size()); if (filecontrols.size() == 0) { // printf("No controls\n"); return false; } // Set the global map name m_sharedMemoryName = mapname; // Create the mailslot // m_hSlot is intitialized to NULL in constructor CreateMail(m_sharedMemoryName, m_hSlot); // printf("Created mailslot handle [%x]\n", m_hSlot); // Write the executable path to the registry GetModuleFileNameA(NULL, Path, sizeof(Path)); // printf("ControlPath(%s)\n", Path); if (WritePathToRegistry(HKEY_CURRENT_USER, "Software\\Leading Edge\\Spout", "ControlPath", Path)) { // printf("registry write OK\n"); } // Write the name path to the registry to identify the memory map strcpy_s(Path, MAX_PATH, m_sharedMemoryName.c_str()); PathStripPathA(Path); PathRemoveExtensionA(Path); // printf("ControlMap(%s)\n", Path); if (WritePathToRegistry(HKEY_CURRENT_USER, "Software\\Leading Edge\\Spout", "ControlMap", Path)) { // printf("registry write 2 OK\n"); } // If the user has created controls, find the programdata or executable path and write the control file m_ControlFilePath[0] = 0; if(filecontrols.size() > 0) { // Find or create the Spout programdata folder // Look for "ProgramData" if it exists hr = SHGetFolderPathA(NULL, CSIDL_COMMON_APPDATA, NULL, 0, Path); if (SUCCEEDED(hr)) { sprintf_s(m_ControlFilePath, MAX_PATH, "%s\\Spout", Path); CreateDirectoryA((LPCSTR)m_ControlFilePath, NULL); // Will create if it does not exist // RemoveDirectoryA((LPCSTR)SpoutPath); strcat_s(m_ControlFilePath, MAX_PATH, "\\"); strcat_s(m_ControlFilePath, mapname.c_str()); strcat_s(m_ControlFilePath, ".txt"); // The control file name } // If that failed use the executable path if(!m_ControlFilePath[0]) { GetModuleFileNameA(NULL, Path, sizeof(Path)); PathRemoveFileSpecA(Path); strcat_s(Path, MAX_PATH, "\\"); strcat_s(Path, mapname.c_str()); strcat_s(Path, ".txt"); // The control file name strcpy_s(m_ControlFilePath, MAX_PATH, Path); } CreateControlFile(m_ControlFilePath); // Write the control file path to the registry // printf("writing control file [%s]\n", m_ControlFilePath); WritePathToRegistry(HKEY_CURRENT_USER, "Software\\Leading Edge\\Spout", "ControlFile", m_ControlFilePath); return true; } return false; } //--------------------------------------------------------- bool SpoutControls::CloseControls() { // Release all handles etc Cleanup(); return true; } //--------------------------------------------------------- // Open the SpoutController executable to allow controls to be changed // Requires SpoutController.exe to be in the path passed // or in the folder of a host executable // or a SpoutControls installation bool SpoutControls::OpenSpoutController(std::string CommandLine) { char Path[MAX_PATH]; char InstallPath[MAX_PATH]; // HRESULT hr; Path[0] = 0; InstallPath[0] = 0; // Look for the SpoutControls installation path in the registry // This contains the full path including "SpoutController.exe" if(ReadPathFromRegistry(HKEY_CURRENT_USER, "Software\\Leading Edge\\SpoutControls", "InstallPath", InstallPath)) { strcpy_s(Path, MAX_PATH, InstallPath); } else if(!CommandLine.empty()) { // A path been passed - add the executable name strcpy_s(Path, MAX_PATH, CommandLine.c_str()); strcat_s(Path, MAX_PATH, "\\SpoutController.exe"); } else { // No path can be found return false; } if(PathFileExistsA(Path) ) { // Launch SpoutController SHELLEXECUTEINFOA ShExecInfo; ZeroMemory(&ShExecInfo, sizeof(ShExecInfo)); ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO); ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS; ShExecInfo.hwnd = NULL; ShExecInfo.lpVerb = NULL; ShExecInfo.lpFile = (LPCSTR)Path; // If opening the controller from an application, give it an argument // "NoClose" to remove the Close button // WinSpoutController is now changed to show/hide or exit on Escape key if(!CommandLine.empty() && CommandLine.c_str()[0] != 0) { if(InstallPath[0] == 0) { // No SpoutContols installation, so use the path passed ShExecInfo.lpParameters = (LPCSTR)CommandLine.c_str(); // ""; } else { // SpoutContols installation as well as a command line, so use "NOCLOSE" strcpy_s(InstallPath, MAX_PATH, "NOCLOSE"); ShExecInfo.lpParameters = InstallPath; } } else { ShExecInfo.lpParameters = ""; } ShExecInfo.lpDirectory = NULL; ShExecInfo.nShow = SW_SHOW; ShExecInfo.hInstApp = NULL; ShellExecuteExA(&ShExecInfo); Sleep(125); // alow time to open return true; } return false; } //--------------------------------------------------------- // Check the mailslot and return all controls bool SpoutControls::CheckControls(std::vector<control> &controls) { // if intialized already, check for a message from the controller if(CheckMail(m_sharedMemoryName, m_hSlot)) { // Get the new controls GetControls(controls); return true; } return false; } // ====================================================================== // Sender functions to create a control file // ====================================================================== bool SpoutControls::CreateControl(std::string name, std::string type) { return CreateFileControl(name, type, 0.0f, 1.0f, 1.0, ""); } bool SpoutControls::CreateControl(std::string name, std::string type, float value) { return CreateFileControl(name, type, 0.0f, value, value, ""); // Min. max, default } bool SpoutControls::CreateControl(std::string name, std::string type, std::string text) { return CreateFileControl(name, type, 0.0f, 1.0f, 1.0, text); } bool SpoutControls::CreateControl(std::string name, std::string type, float minimum, float maximum, float value) { return CreateFileControl(name, type, minimum, maximum, value, ""); } //--------------------------------------------------------- // Used by the controller to find the control file path // and find the control map name in the registry bool SpoutControls::FindControlFile(std::string &filepath) { char path[MAX_PATH]; // Find if the controller map file name exists the registry if(ReadPathFromRegistry(HKEY_CURRENT_USER, "Software\\Leading Edge\\Spout", "ControlFile", path) ) { if(path[0] > 0) { // 24.08.15 - add existence check if(_access(path, 0) == -1) // Mode 0 - existence check return false; // File found filepath = path; return true; } } return false; } //--------------------------------------------------------- // Used by a multiple controlled senders to copy the control // file from ProgramData to the local dll directory bool SpoutControls::CopyControlFile (std::string &filepath, std::string &destpath) { // copy from source to destination if(CopyFileA((LPCSTR)filepath.c_str(), (LPCSTR)destpath.c_str(), false)) { return true; } return false; } bool SpoutControls::GetFileControls(std::vector<filecontrol> &controls) { if (filecontrols.size() > 0) { controls.clear(); for (unsigned int i = 0; i < filecontrols.size(); i++) { controls.push_back(filecontrols.at(i)); } return true; } return false; } // ====================================================================== // Private // ====================================================================== //--------------------------------------------------------- // Create a file control and add to the sender's filecontrol vector bool SpoutControls::CreateFileControl(std::string name, std::string type, float minimum, float maximum, float value, std::string text) { filecontrol fc; if(name.empty() || type.empty()) { return false; } fc.name = name; fc.desc = type; fc.min = minimum; fc.max = maximum; fc.def = value; fc.value = value; fc.text = text.c_str(); if(type == "bool") fc.fftype = 0; // checkbox if(type == "event") fc.fftype = 1; // button if(type == "float") fc.fftype = 10; // float slider if(type == "text") fc.fftype = 100; // text filecontrols.push_back(fc); return true; } //--------------------------------------------------------- // Create a JSON control file from the filecontrols vector bool SpoutControls::CreateControlFile(const char *filepath) { std::string linestring; char path[MAX_PATH]; char temp[256]; if(!filepath[0] || filecontrols.empty()) return false; strcpy_s(path, MAX_PATH, filepath); // // Write the contents of the parameter list // // Example // /*{ "CREDIT": "by Lynn Jarvis - spout.zeal.co", "DESCRIPTION": "SpoutControls", "CATEGORIES": [ "Parameter adjustment" ], "INPUTS": [ { "NAME": "User text", "TYPE": "text", "DEFAULT": 0 }, { "NAME": "Rotate", "TYPE": "bool", "DEFAULT": 1 }, { "NAME": "Speed", "TYPE": "float", "MIN": 0.0, "MAX": 4.0, "DEFAULT": 0.5 }, ] }*/ // Create the file std::ofstream sourceFile(path); // Source file created OK ? if(sourceFile.is_open()) { // Create the JSON header linestring = "/*{\n"; sourceFile.write(linestring.c_str(), linestring.length()); sprintf_s(temp, 256, " \"CREDIT\": \"SpoutControls - spout.zeal.co\",\n"); sourceFile.write(temp, strlen(temp)); PathStripPathA(path); PathRemoveExtensionA(path); sprintf_s(temp, 256, " \"DESCRIPTION\": \"%s\",\n", path); sourceFile.write(temp, strlen(temp)); sprintf_s(temp, 256, " \"CATEGORIES\": [\n"); sourceFile.write(temp, strlen(temp)); sprintf_s(temp, 256, " \"Parameter adjustment\"\n"); sourceFile.write(temp, strlen(temp)); sprintf_s(temp, 256, " ],\n"); sourceFile.write(temp, strlen(temp)); sprintf_s(temp, 256, " \"INPUTS\": [\n"); sourceFile.write(temp, strlen(temp)); // Write the control data here // Example // { // "NAME": "Speed", // "TYPE": "float", // "MIN": 0.0, // "MAX": 4.0, // "DEFAULT": 0.5 // }, for(unsigned int i = 0; i < filecontrols.size(); i++) { sprintf_s(temp, 256, " {\n"); sourceFile.write(temp, strlen(temp)); sprintf_s(temp, 256, " \"NAME\": \"%s\",\n", filecontrols.at(i).name.c_str()); sourceFile.write(temp, strlen(temp)); sprintf_s(temp, 256, " \"TYPE\": \"%s\",\n", filecontrols.at(i).desc.c_str()); sourceFile.write(temp, strlen(temp)); if(filecontrols.at(i).desc != "text") { sprintf_s(temp, 256, " \"MIN\": %.2f,\n", filecontrols.at(i).min); sourceFile.write(temp, strlen(temp)); sprintf_s(temp, 256, " \"MAX\": %.2f,\n", filecontrols.at(i).max); sourceFile.write(temp, strlen(temp)); sprintf_s(temp, 256, " \"DEFAULT\": %.2f\n", filecontrols.at(i).def); sourceFile.write(temp, strlen(temp)); } else { sprintf_s(temp, 256, " \"TEXT\": \"%s\"\n", filecontrols.at(i).text.c_str()); sourceFile.write(temp, strlen(temp)); } sprintf_s(temp, 256, " },\n"); sourceFile.write(temp, strlen(temp)); } sprintf_s(temp, 256, " ],\n"); sourceFile.write(temp, strlen(temp)); sprintf_s(temp, 256, "}*/\n"); sourceFile.write(temp, strlen(temp)); sourceFile.close(); // printf("Control file created\n[%s]\n", filepath); } else { sprintf_s(temp, 256, "Control file not created\n[%s]", path); MessageBoxA(NULL, temp, "Info", MB_OK); // MessageBoxA(NULL, "File not created", "Info", MB_OK); } return true; } //--------------------------------------------------------- // Write control map with updated values bool SpoutControls::WriteControls(void *pBuffer, std::vector<control> controls) { // // Write the control data to shared memory // The writer knows the memory map size to open it (m_dwSize) // float fValue = 0; char desc[256]; char *buffer = NULL; // the buffer to store in shared memory char *buf = NULL; // pointer within the buffer int i, j; buffer = (char *)malloc(m_dwSize*sizeof(unsigned char)); if(!buffer) return false; // Clear the buffer to zero so that there is a null for each data line ZeroMemory(buffer, m_dwSize*sizeof(unsigned char)); buf = buffer; // pointer within the buffer // The first 4 bytes of the first line is the memory map size so the reader knows how big it is // printf("Writing the memory map size (%d)\n", m_dwSize); sprintf_s(desc, 256, "%4d", m_dwSize); for(i = 0 ; i< 4; i++) *buf++ = desc[i]; // The next 4 bytes contains the number of controls ZeroMemory(desc, 256); sprintf_s(desc, 256, "%4d", (DWORD)controls.size()); for(i = 0 ; i< 4; i++) *buf++ = desc[i]; // Move on 268 bytes to the start of the controls (each memory map line is 276 bytes) buf += 268; // Next the controls and their data // Name (16 bytes) Type (4 bytes) Data (256 bytes) - total 276 bytes per control for(i = 0; i < (int)controls.size(); i++) { // Control name - 16 bytes ZeroMemory(desc, 256); if(controls.at(i).name.c_str()[0]) sprintf_s(desc, 256, "%s", controls.at(i).name.c_str()); for(j = 0 ; j<16; j++) *buf++ = desc[j]; // Control type - 4 bytes ZeroMemory(desc, 256); sprintf_s(desc, 256, "%4d", (DWORD)controls.at(i).type); for(j = 0 ; j<4; j++) *buf++ = desc[j]; // Control data - 256 bytes ZeroMemory(desc, 256); if(controls.at(i).type == 100) { // Text data if(controls.at(i).text[0]) { sprintf_s(desc, 256, "%s", controls.at(i).text.c_str()); } } else { fValue = controls.at(i).value; sprintf_s(desc, 256, "%f", fValue); // float data } // copy it with 256 length for(j = 0 ; j<256; j++) *buf++ = desc[j]; } // end all controls // Now transfer to shared memory which will be the same size memcpy( (void *)pBuffer, (void *)buffer, m_dwSize ); free((void *)buffer); return true; } //--------------------------------------------------------- // Read controls from the memory map bool SpoutControls::ReadControls(void *pBuffer, std::vector<control> &controls) { char *buf = NULL; char temp[256]; int i, j, nControls; control control; // // Get the controls // buf = (char *)pBuffer; // moveable pointer buf += 4; // The first 4 bytes of the first line is the memory map size, so skip that // the next 4 bytes contains the number of controls for(i = 0; i<4; i++) temp[i] = *buf++; temp[4] = 0; nControls = atoi(temp); // Move on 268 bytes to the control data (each line is 276 bytes) buf += 268; // Clear the controls vector controls.clear(); // Fill it again (use previously found size) for(i = 0; i<nControls; i++) { control.name.clear(); control.text.clear(); control.value = 0; control.type = 0; // First 16 bytes are the control name ZeroMemory(temp, 256); for(j = 0; j<16; j++) temp[j] = *buf++; temp[16] = 0; if(temp[0]) control.name = temp; // Control type ZeroMemory(temp, 256); for(j = 0; j<4; j++) temp[j] = *buf++; temp[4] = 0; control.type = atoi(temp); // Next 256 bytes on the same line are allocated to the float or string data ZeroMemory(temp, 256); for(j = 0; j<256; j++) temp[j] = *buf++; if(control.type == 100) { // text data if(temp[0]) { control.text = temp; } } else { // float data control.value = (float)atof(temp); } controls.push_back(control); } // Done all controls return true; } //--------------------------------------------------------- // Sender creates the mailslot bool SpoutControls::CreateMail(std::string SlotName, HANDLE &hSlot) { HANDLE hslot = NULL; std::string slotstring; // printf("SpoutControls::CreateMail\n"); // Already exists ? if (hSlot != NULL) { // printf("SpoutControls::CreateMail - hSlot exists\n"); return true; } /* // LJ DEBUG - check with CreateFile // An error occurs if a mailslot with the specified name already exists. // If CreateFile is called to access a non-existent mailslot, the ERROR_FILE_NOT_FOUND error code will be set // If the function succeeds, the return value is an open handle to // the specified file, device, named pipe, or mail slot. // If the function fails, the return value is INVALID_HANDLE_VALUE. // To get extended error information, call HANDLE hFile; hFile = CreateFileA(slotstring.c_str(), GENERIC_WRITE, FILE_SHARE_READ, (LPSECURITY_ATTRIBUTES)NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, (HANDLE)NULL); // DWORD dwError = GetLastError(); if (hFile != INVALID_HANDLE_VALUE) { // The system found the file specified printf("SpoutControls::CreateMail - CreateFileA already exists\n"); CloseHandle(hFile); return true; } printf("SpoutControls::CreateMail - CreateFileA returned %x\n", hFile); CloseHandle(hFile); */ slotstring = "\\\\.\\mailslot\\"; slotstring += SlotName; hslot = CreateMailslotA(slotstring.c_str(), 0, // no maximum message size 0, // Time-out for operations - set to zero - was originally 2msec (LPSECURITY_ATTRIBUTES) NULL); // default security if (hslot == INVALID_HANDLE_VALUE) { // (-1) // Want no delay here // DWORD dwError = GetLastError(); // printf("CreateMailslot (%s) failed with %d\n", SlotName.c_str(), dwError); // Now should not happen if (GetLastError() == ERROR_ALREADY_EXISTS) { // printf("CreateMailslot (%s) already exists (%x)(%x)\n", SlotName.c_str(), (unsigned int)hSlot, (unsigned int)m_hSlot); return true; } return false; } hSlot = hslot; // printf("Created mailslot handle [%x]\n", hSlot); return true; } //--------------------------------------------------------- // Controller writes to the mailslot bool SpoutControls::WriteMail(std::string SlotName, std::string SlotMessage) { std::string slotstring; HANDLE hFile; BOOL fResult; DWORD dwWritten; slotstring = "\\\\.\\mailslot\\"; slotstring += SlotName; hFile = CreateFileA(slotstring.c_str(), GENERIC_WRITE, FILE_SHARE_READ, (LPSECURITY_ATTRIBUTES)NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, (HANDLE)NULL); if (hFile == INVALID_HANDLE_VALUE) { // The system cannot find the file specified // printf("CreateFile failed with %d.\n", GetLastError()); return false; } fResult = WriteFile(hFile, SlotMessage.c_str(), (DWORD) (strlen(SlotMessage.c_str())+1)*sizeof(TCHAR), &dwWritten, (LPOVERLAPPED)NULL); if (!fResult) { // printf("WriteFile failed with error (%d)\n", GetLastError()); CloseHandle(hFile); return false; } CloseHandle(hFile); return true; } //--------------------------------------------------------- // Sender checks the mailslot for messages bool SpoutControls::CheckMail(std::string SlotName, HANDLE hSlot) { if(hSlot == NULL) return false; std::string slotmessage; // Not used but could return the message return ReadMail(SlotName, hSlot, slotmessage); } //--------------------------------------------------------- // Sender reads the mailslot to determine whether // a message is ready and clears pending messages bool SpoutControls::ReadMail(std::string SlotName, HANDLE hSlot, std::string &SlotMessage) { DWORD cbMessage, cMessage, cbRead; BOOL fResult; LPTSTR lpszBuffer; char achID[80]; DWORD cAllMessages; HANDLE hEvent; OVERLAPPED ov; if(hSlot == NULL) return false; cbMessage = cMessage = cbRead = 0; hEvent = CreateEvent(NULL, false, false, TEXT("SpoutControlsSlotEvent")); if( NULL == hEvent ) { return false; } ov.Offset = 0; ov.OffsetHigh = 0; ov.hEvent = hEvent; fResult = GetMailslotInfo( hSlot, // mailslot handle (LPDWORD) NULL, // no maximum message size &cbMessage, // size of next message &cMessage, // number of messages (LPDWORD)NULL); // no read time-out. TODO : 1/2 frame timeout ? if (!fResult) { // printf("GetMailslotInfo failed with %d.\n", GetLastError()); CloseHandle(hEvent); return false; } if (cbMessage == MAILSLOT_NO_MESSAGE) { CloseHandle(hEvent); return false; } cAllMessages = cMessage; while (cMessage != 0) { // retrieve all messages // Allocate memory for the message. // TODO - clean up lpszBuffer = (LPTSTR) GlobalAlloc(GPTR, lstrlen((LPTSTR)achID)*sizeof(TCHAR) + cbMessage); if( NULL == lpszBuffer ) return false; lpszBuffer[0] = '\0'; fResult = ReadFile( hSlot, lpszBuffer, cbMessage, &cbRead, &ov); if (!fResult) { // printf("ReadFile failed with %d.\n", GetLastError()); GlobalFree((HGLOBAL) lpszBuffer); CloseHandle(hEvent); return false; } fResult = GetMailslotInfo( hSlot, // mailslot handle (LPDWORD) NULL, // no maximum message size &cbMessage, // size of next message &cMessage, // number of messages (LPDWORD) NULL); // no read time-out if (!fResult) { // printf("GetMailslotInfo failed (%d)\n", GetLastError()); GlobalFree((HGLOBAL) lpszBuffer); CloseHandle(hEvent); return false; } // We only return the last message here but it could be extended to a vector of strings SlotMessage = (LPSTR)lpszBuffer; GlobalFree((HGLOBAL) lpszBuffer); } // end all messages CloseHandle(hEvent); return true; } //--------------------------------------------------------- void SpoutControls::CloseMap() { if(m_pBuffer) UnmapViewOfFile(m_pBuffer); if(m_hSharedMemory) CloseHandle(m_hSharedMemory); if(m_hAccessMutex) CloseHandle(m_hAccessMutex); m_pBuffer = NULL; m_hSharedMemory = NULL; m_hAccessMutex = NULL; } //--------------------------------------------------------- bool SpoutControls::Cleanup() { // Cleanup for this class // Release the filecontrols vector created by a sender if(filecontrols.size() > 0) { filecontrols.clear(); } // Release all objects if(m_pBuffer) UnmapViewOfFile(m_pBuffer); if(m_hSharedMemory) CloseHandle(m_hSharedMemory); if(m_hAccessMutex) CloseHandle(m_hAccessMutex); m_pBuffer = NULL; m_hSharedMemory = NULL; m_hAccessMutex = NULL; if(m_hSlot) { // printf("Closing mailslot handle\n"); // For a sender, clear the map name from the registry RemovePathFromRegistry(HKEY_CURRENT_USER, "Software\\Leading Edge\\Spout", "ControlMap"); CloseHandle(m_hSlot); m_hSlot = NULL; } // Close the controller if it has been opened HWND hwnd = FindWindowA(NULL, (LPCSTR)"Spout Controller"); if(hwnd) { // ShowWindow(hwnd, SW_SHOWNORMAL); // causes a freeze if the window is hidden SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_ASYNCWINDOWPOS | SWP_SHOWWINDOW | SWP_NOSIZE | SWP_NOMOVE); SendMessageA(hwnd, WM_SYSCOMMAND, SC_CLOSE, 0); } return true; }
29.970774
134
0.647155
initialfx
4c5abf814ba2ac2274c92395df2b592cff646d16
3,170
cpp
C++
FileZillaFTP/source/AdminInterface.cpp
JyothsnaMididoddi26/xampp
8f34d7fa7c2e6cc37fe4ece5e6886dc4e5c0757b
[ "Apache-2.0" ]
1
2017-01-31T08:49:16.000Z
2017-01-31T08:49:16.000Z
FileZillaFTP/source/AdminInterface.cpp
JyothsnaMididoddi26/xampp
8f34d7fa7c2e6cc37fe4ece5e6886dc4e5c0757b
[ "Apache-2.0" ]
2
2020-07-17T00:13:41.000Z
2021-05-08T17:01:54.000Z
FileZillaFTP/source/AdminInterface.cpp
JyothsnaMididoddi26/xampp
8f34d7fa7c2e6cc37fe4ece5e6886dc4e5c0757b
[ "Apache-2.0" ]
null
null
null
// FileZilla Server - a Windows ftp server // Copyright (C) 2002-2004 - Tim Kosse <tim.kosse@gmx.de> // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // AdminInterface.cpp: Implementierung der Klasse CAdminInterface. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "AdminInterface.h" #include "AdminSocket.h" #include "Server.h" ////////////////////////////////////////////////////////////////////// // Konstruktion/Destruktion ////////////////////////////////////////////////////////////////////// CAdminInterface::CAdminInterface(CServer *pServer) { ASSERT(pServer); m_pServer = pServer; } CAdminInterface::~CAdminInterface() { for (std::list<CAdminSocket *>::iterator iter = m_AdminSocketList.begin(); iter != m_AdminSocketList.end(); iter++) delete *iter; } BOOL CAdminInterface::Add(CAdminSocket *pAdminSocket) { if (pAdminSocket->Init()) { m_AdminSocketList.push_back(pAdminSocket); return TRUE; } return FALSE; } BOOL CAdminInterface::SendCommand(int nType, int nID, const void *pData, int nDataLength) { ASSERT((!nDataLength && !pData) || (pData && nDataLength)); std::list<CAdminSocket *> deleteList; std::list<CAdminSocket *>::iterator iter; for (iter = m_AdminSocketList.begin(); iter != m_AdminSocketList.end(); iter++) if (!(*iter)->SendCommand(nType, nID, pData, nDataLength)) { deleteList.push_back(*iter); } for (iter = deleteList.begin(); iter != deleteList.end(); iter++) VERIFY(Remove(*iter)); return TRUE; } BOOL CAdminInterface::Remove(CAdminSocket *pAdminSocket) { for (std::list<CAdminSocket *>::iterator iter = m_AdminSocketList.begin(); iter != m_AdminSocketList.end(); iter++) if (*iter == pAdminSocket) { delete *iter; m_AdminSocketList.erase(iter); return TRUE; } return FALSE; } BOOL CAdminInterface::ProcessCommand(CAdminSocket *pAdminSocket, int nID, void *pData, int nDataLength) { m_pServer->ProcessCommand(pAdminSocket, nID, reinterpret_cast<unsigned char *>(pData), nDataLength); return TRUE; } void CAdminInterface::CheckForTimeout() { std::list<CAdminSocket *> deleteList; std::list<CAdminSocket *>::iterator iter; for (iter=m_AdminSocketList.begin(); iter!=m_AdminSocketList.end(); iter++) if ((*iter)->CheckForTimeout()) deleteList.push_back(*iter); for (iter=deleteList.begin(); iter!=deleteList.end(); iter++) VERIFY(Remove(*iter)); }
31.7
117
0.655205
JyothsnaMididoddi26
4c5b7b47c52278a64e3e8ca486aef44db48f8b04
4,007
cc
C++
Source/BladeDevice/source/window/android/AndroidWindowMessagePump.cc
OscarGame/blade
6987708cb011813eb38e5c262c7a83888635f002
[ "MIT" ]
146
2018-12-03T08:08:17.000Z
2022-03-21T06:04:06.000Z
Source/BladeDevice/source/window/android/AndroidWindowMessagePump.cc
huangx916/blade
3fa398f4d32215bbc7e292d61e38bb92aad1ee1c
[ "MIT" ]
1
2019-01-18T03:35:49.000Z
2019-01-18T03:36:08.000Z
Source/BladeDevice/source/window/android/AndroidWindowMessagePump.cc
huangx916/blade
3fa398f4d32215bbc7e292d61e38bb92aad1ee1c
[ "MIT" ]
31
2018-12-03T10:32:43.000Z
2021-10-04T06:31:44.000Z
/******************************************************************** created: 2013/12/28 filename: AndroidWindowMessagePump.cc author: Crazii purpose: *********************************************************************/ #include <BladePCH.h> #if BLADE_PLATFORM == BLADE_PLATFORM_ANDROID #include <unistd.h> #include <window/android/AndroidWindowMessagePump.h> namespace Blade { ////////////////////////////////////////////////////////////////////////// AndroidMessagePump::AndroidMessagePump() { } ////////////////////////////////////////////////////////////////////////// AndroidMessagePump::~AndroidMessagePump() { } /************************************************************************/ /* IWindowMessagePump interface */ /************************************************************************/ ////////////////////////////////////////////////////////////////////////// void AndroidMessagePump::processMessage() { std::for_each(mMessageListeners.begin(),mMessageListeners.end(), std::mem_fun(&IMessageListener::preProcessMessages) ); int ident; int events; struct android_poll_source* source; while((ident=::ALooper_pollAll(0, NULL, &events, (void**)&source)) >= 0) { if(source != NULL) { android_app* app = source->app; if( source->id == LOOPER_ID_MAIN ) { //process main cmd source->cmd = AndroidMessagePump::androidThreadMessage(app); source->preprocess(app, source); std::for_each(mMessageListeners.begin(),mMessageListeners.end(), std::bind2nd( std::mem_fun(&IMessageListener::preProcessMessage), source) ); source->process(app, source); std::for_each(mMessageListeners.begin(),mMessageListeners.end(), std::bind2nd( std::mem_fun(&IMessageListener::postProcessMessage), source) ); source->postprocess(app, source); } else if( source->id == LOOPER_ID_INPUT ) { //process input event while(::AInputQueue_getEvent(app->inputQueue, &(source->event) ) >= 0) { LOGV("New input event: type=%d\n", AInputEvent_getType(source->event)); if( ::AInputQueue_preDispatchEvent(app->inputQueue, source->event) ) continue; source->preprocess(app, source); std::for_each(mMessageListeners.begin(),mMessageListeners.end(), std::bind2nd( std::mem_fun(&IMessageListener::preProcessMessage), source) ); source->process(app, source); std::for_each(mMessageListeners.begin(),mMessageListeners.end(), std::bind2nd( std::mem_fun(&IMessageListener::postProcessMessage), source) ); source->postprocess(app, source); ::AInputQueue_finishEvent(app->inputQueue, source->event, 1); } } } } std::for_each(mMessageListeners.begin(),mMessageListeners.end(), std::mem_fun(&IMessageListener::postProcessMessages) ); } ////////////////////////////////////////////////////////////////////////// bool AndroidMessagePump::addMessageListener(IMessageListener* listener) { if( listener != NULL ) return mMessageListeners.insert(listener).second; else return false; } ////////////////////////////////////////////////////////////////////////// bool AndroidMessagePump::removeMessageListener(IMessageListener* listener) { if( listener != NULL ) return mMessageListeners.erase(listener) == 1; else return false; } /************************************************************************/ /* */ /************************************************************************/ ////////////////////////////////////////////////////////////////////////// int8_t AndroidMessagePump::androidThreadMessage(struct android_app* android_app) { int8_t cmd; if ( ::read(android_app->msgread, &cmd, sizeof(cmd)) == sizeof(cmd) ) return cmd; else LOGE("No data on command pipe!"); return -1; } }//namespace Blade #endif//BLADE_PLATFORM
32.314516
122
0.516346
OscarGame
4c5e1dd5125b037fd99e48ed261d3a595fff2d14
3,461
cc
C++
src/tir/transforms/convert_blocks_to_opaque.cc
Exhorder6/tvm
7e3f068373937c0ae08d58f67b84030a027db1c9
[ "Zlib", "Unlicense", "Apache-2.0", "BSD-2-Clause", "MIT", "ECL-2.0" ]
90
2019-01-26T00:38:49.000Z
2022-03-11T23:12:34.000Z
src/tir/transforms/convert_blocks_to_opaque.cc
Exhorder6/tvm
7e3f068373937c0ae08d58f67b84030a027db1c9
[ "Zlib", "Unlicense", "Apache-2.0", "BSD-2-Clause", "MIT", "ECL-2.0" ]
91
2019-02-27T00:17:01.000Z
2022-02-21T18:08:21.000Z
src/tir/transforms/convert_blocks_to_opaque.cc
Exhorder6/tvm
7e3f068373937c0ae08d58f67b84030a027db1c9
[ "Zlib", "Unlicense", "Apache-2.0", "BSD-2-Clause", "MIT", "ECL-2.0" ]
41
2019-01-28T14:37:03.000Z
2022-03-31T03:58:57.000Z
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * \file convert_block_to_opaque.cc * \brief Convert the blocks to opaque blocks which do not have block vars. */ #include <tvm/tir/stmt_functor.h> #include <tvm/tir/transform.h> namespace tvm { namespace tir { /*! * \brief Substitute expr via BlockRealize value bindings and convert each block into opaque * blocks. */ class OpaqueBlockConverter : public StmtExprMutator { public: static Stmt Substitute(const PrimFunc& f) { OpaqueBlockConverter substituter; return substituter.VisitStmt(f->body); } private: OpaqueBlockConverter() = default; PrimExpr VisitExpr_(const VarNode* var) final { auto it = var_substitutes_.find(var); if (it != var_substitutes_.end()) { return it->second; } return GetRef<Var>(var); } Stmt VisitStmt_(const BlockNode* block) final { ICHECK(!block->init.defined()) << "Block Init part is not allowed in pass ConvertBlocksToOpaque"; Block new_block = Downcast<Block>(StmtExprMutator::VisitStmt_(block)); if (!new_block->iter_vars.empty()) { new_block.CopyOnWrite()->iter_vars.clear(); } return std::move(new_block); } Stmt VisitStmt_(const BlockRealizeNode* realize) final { const auto* block_op = realize->block.get(); ICHECK(!block_op->init.defined()); // Step 1. Update "block vars => binding values" for substitution. ICHECK_EQ(block_op->iter_vars.size(), realize->iter_values.size()); for (int i = 0, n = block_op->iter_vars.size(); i < n; ++i) { IterVar block_var = block_op->iter_vars[i]; PrimExpr v = this->VisitExpr(realize->iter_values[i]); var_substitutes_.emplace(block_var->var.get(), v); } // Step 2. Visit recursively. BlockRealize new_realize = Downcast<BlockRealize>(StmtExprMutator::VisitStmt_(realize)); if (!new_realize->iter_values.empty()) { new_realize.CopyOnWrite()->iter_values.clear(); } return std::move(new_realize); } /*! \brief The map from block vars to thier binding values. */ std::unordered_map<const VarNode*, PrimExpr> var_substitutes_; }; PrimFunc ConvertBlocksToOpaque(PrimFunc f) { PrimFuncNode* fptr = f.CopyOnWrite(); fptr->body = OpaqueBlockConverter::Substitute(f); return f; } namespace transform { Pass ConvertBlocksToOpaque() { auto pass_func = [=](PrimFunc f, IRModule m, PassContext ctx) { return ConvertBlocksToOpaque(std::move(f)); }; return CreatePrimFuncPass(pass_func, 0, "tir.ConvertBlocksToOpaque", {}); } TVM_REGISTER_GLOBAL("tir.transform.ConvertBlocksToOpaque").set_body_typed(ConvertBlocksToOpaque); } // namespace transform } // namespace tir } // namespace tvm
32.961905
97
0.710488
Exhorder6
4c5e5f51389a8c2095a2b892a7b337852237bbc8
869
cpp
C++
Baekjoon/10799_stack.cpp
r4k0nb4k0n/Programming-Challenges
3d734902a7503f9dc49c97fe6e69e7541cd73e56
[ "MIT" ]
2
2019-05-24T08:58:26.000Z
2022-01-09T00:46:42.000Z
Baekjoon/10799_stack.cpp
r4k0nb4k0n/Programming-Challenges
3d734902a7503f9dc49c97fe6e69e7541cd73e56
[ "MIT" ]
null
null
null
Baekjoon/10799_stack.cpp
r4k0nb4k0n/Programming-Challenges
3d734902a7503f9dc49c97fe6e69e7541cd73e56
[ "MIT" ]
null
null
null
#include <iostream> #include <utility> // pair #include <string> #include <stack> #include <vector> using namespace std; int main() { vector<pair<int, int> > Bar; vector<int> Razer; stack<int> start_point; string input; int length, Bar_cnt = 0, Razer_cnt = 0, cnt = 0; cin >> input; length = input.length(); for (int i = 0; i < length; i++) { if (input[i] == '(') { if (input[i + 1] == ')') { Razer.push_back(i); Razer_cnt++; i = i + 1; } else // '(' start_point.push(i); } else // ')' { Bar.push_back(make_pair(start_point.top(), i)); Bar_cnt++; start_point.pop(); } } for (int i = 0; i < Bar_cnt; i++) { int inbound = 0; for (int j = 0; j < Razer_cnt; j++) { if (Bar[i].first <= Razer[j] && Razer[j] <= Bar[i].second) inbound++; } cnt = cnt + inbound + 1; } cout << cnt; return 0; }
16.711538
61
0.540852
r4k0nb4k0n
4c5f08ba5759a8c633e2c29c73f944038e1e4e86
13,012
cc
C++
Modules/Transformation/src/irtkPartialBSplineFreeFormTransformationSV.cc
kevin-keraudren/IRTK
ce329b7f58270b6c34665dcfe9a6e941649f3b94
[ "Apache-2.0" ]
3
2018-10-04T19:32:36.000Z
2021-09-02T07:37:30.000Z
Modules/Transformation/src/irtkPartialBSplineFreeFormTransformationSV.cc
kevin-keraudren/IRTK
ce329b7f58270b6c34665dcfe9a6e941649f3b94
[ "Apache-2.0" ]
null
null
null
Modules/Transformation/src/irtkPartialBSplineFreeFormTransformationSV.cc
kevin-keraudren/IRTK
ce329b7f58270b6c34665dcfe9a6e941649f3b94
[ "Apache-2.0" ]
4
2016-03-17T02:55:00.000Z
2018-02-03T05:40:05.000Z
/* The Image Registration Toolkit (IRTK) * * Copyright 2008-2015 Imperial College London * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <irtkTransformation.h> // ============================================================================= // Construction/Destruction // ============================================================================= // ----------------------------------------------------------------------------- irtkPartialBSplineFreeFormTransformationSV ::irtkPartialBSplineFreeFormTransformationSV(irtkBSplineFreeFormTransformationSV *t, double f) : _Transformation(t), _Fraction (f) { } // ----------------------------------------------------------------------------- irtkPartialBSplineFreeFormTransformationSV ::~irtkPartialBSplineFreeFormTransformationSV() { } // ============================================================================= // Transformation parameters // ============================================================================= // ----------------------------------------------------------------------------- bool irtkPartialBSplineFreeFormTransformationSV::CopyFrom(const irtkTransformation *t) { const irtkPartialBSplineFreeFormTransformationSV *part = NULL; if ((part = dynamic_cast<const irtkPartialBSplineFreeFormTransformationSV *>(t))) { return _Transformation->CopyFrom(part->Transformation()); } else { return _Transformation->CopyFrom(t); } } // ----------------------------------------------------------------------------- int irtkPartialBSplineFreeFormTransformationSV::NumberOfDOFs() const { return _Transformation->NumberOfDOFs(); } // ----------------------------------------------------------------------------- void irtkPartialBSplineFreeFormTransformationSV::Put(int dof, double x) { _Transformation->Put(dof, x); } // ----------------------------------------------------------------------------- double irtkPartialBSplineFreeFormTransformationSV::Get(int dof) const { return _Transformation->Get(dof); } // ----------------------------------------------------------------------------- void irtkPartialBSplineFreeFormTransformationSV::Put(const DOFValue *x) { _Transformation->Put(x); } // ----------------------------------------------------------------------------- void irtkPartialBSplineFreeFormTransformationSV::Add(const DOFValue *dx) { _Transformation->Add(dx); } // ----------------------------------------------------------------------------- double irtkPartialBSplineFreeFormTransformationSV::Update(const DOFValue *dx) { return _Transformation->Update(dx); } // ----------------------------------------------------------------------------- void irtkPartialBSplineFreeFormTransformationSV::Get(DOFValue *x) const { _Transformation->Get(x); } // ----------------------------------------------------------------------------- void irtkPartialBSplineFreeFormTransformationSV::PutStatus(int dof, DOFStatus s) { _Transformation->PutStatus(dof, s); } // ----------------------------------------------------------------------------- DOFStatus irtkPartialBSplineFreeFormTransformationSV::GetStatus(int dof) const { return _Transformation->GetStatus(dof); } // ----------------------------------------------------------------------------- bool irtkPartialBSplineFreeFormTransformationSV::HasSameDOFsAs(const irtkTransformation *t) const { return HaveSameDOFs(_Transformation, t); } // ----------------------------------------------------------------------------- bool irtkPartialBSplineFreeFormTransformationSV::IsIdentity() const { return (_Fraction == .0) || _Transformation->IsIdentity(); } // ============================================================================= // Parameters (non-DoFs) // ============================================================================= // ----------------------------------------------------------------------------- bool irtkPartialBSplineFreeFormTransformationSV::Set(const char *param, const char *value) { return _Transformation->Set(param, value); } // ----------------------------------------------------------------------------- irtkParameterList irtkPartialBSplineFreeFormTransformationSV::Parameter() const { return _Transformation->Parameter(); } // ============================================================================= // Point transformation // ============================================================================= // ----------------------------------------------------------------------------- bool irtkPartialBSplineFreeFormTransformationSV::RequiresCachingOfDisplacements() const { return _Transformation->RequiresCachingOfDisplacements(); } // ----------------------------------------------------------------------------- inline double irtkPartialBSplineFreeFormTransformationSV::UpperIntegrationLimit(double t, double t0) const { return _Fraction * _Transformation->UpperIntegrationLimit(t, t0); } // ----------------------------------------------------------------------------- void irtkPartialBSplineFreeFormTransformationSV::GlobalTransform(double &x, double &y, double &z, double t, double t0) const { _Transformation->GlobalTransform(x, y, z, t, t0); } // ----------------------------------------------------------------------------- void irtkPartialBSplineFreeFormTransformationSV::LocalTransform(double &x, double &y, double &z, double t, double t0) const { const double T = UpperIntegrationLimit(t, t0); if (T) _Transformation->LocalTransform(x, y, z, T, .0); } // ----------------------------------------------------------------------------- void irtkPartialBSplineFreeFormTransformationSV::Transform(double &x, double &y, double &z, double t, double t0) const { const double T = UpperIntegrationLimit(t, t0); if (T) _Transformation->Transform(x, y, z, T, .0); } // ----------------------------------------------------------------------------- void irtkPartialBSplineFreeFormTransformationSV::GlobalInverse(double &x, double &y, double &z, double t, double t0) const { _Transformation->GlobalInverse(x, y, z, t, t0); } // ----------------------------------------------------------------------------- bool irtkPartialBSplineFreeFormTransformationSV::LocalInverse(double &x, double &y, double &z, double t, double t0) const { const double T = UpperIntegrationLimit(t, t0); if (T) _Transformation->LocalInverse(x, y, z, T, .0); return true; } // ----------------------------------------------------------------------------- bool irtkPartialBSplineFreeFormTransformationSV::Inverse(double &x, double &y, double &z, double t, double t0) const { const double T = UpperIntegrationLimit(t, t0); if (T) _Transformation->Inverse(x, y, z, T, .0); return true; } // --------------------------------------------------------------------------- void irtkPartialBSplineFreeFormTransformationSV::Displacement(irtkGenericImage<double> &disp, double t, double t0, const irtkWorldCoordsImage *wc) const { const double T = UpperIntegrationLimit(t, t0); if (T) _Transformation->Displacement(disp, T, .0, wc); } // --------------------------------------------------------------------------- void irtkPartialBSplineFreeFormTransformationSV::Displacement(irtkGenericImage<float> &disp, double t, double t0, const irtkWorldCoordsImage *wc) const { const double T = UpperIntegrationLimit(t, t0); if (T) _Transformation->Displacement(disp, T, .0, wc); } // --------------------------------------------------------------------------- int irtkPartialBSplineFreeFormTransformationSV::InverseDisplacement(irtkGenericImage<double> &disp, double t, double t0, const irtkWorldCoordsImage *wc) const { const double T = UpperIntegrationLimit(t, t0); if (T) _Transformation->InverseDisplacement(disp, T, .0, wc); return 0; } // --------------------------------------------------------------------------- int irtkPartialBSplineFreeFormTransformationSV::InverseDisplacement(irtkGenericImage<float> &disp, double t, double t0, const irtkWorldCoordsImage *wc) const { const double T = UpperIntegrationLimit(t, t0); if (T) _Transformation->InverseDisplacement(disp, T, .0, wc); return 0; } // ============================================================================= // Derivatives // ============================================================================= // ----------------------------------------------------------------------------- void irtkPartialBSplineFreeFormTransformationSV::GlobalJacobian(irtkMatrix &jac, double x, double y, double z, double t, double t0) const { _Transformation->GlobalJacobian(jac, x, y, z, t, t0); } // ----------------------------------------------------------------------------- void irtkPartialBSplineFreeFormTransformationSV::LocalJacobian(irtkMatrix &jac, double x, double y, double z, double t, double t0) const { const double T = UpperIntegrationLimit(t, t0); if (T) _Transformation->LocalJacobian(jac, x, y, z, T, .0); } // ----------------------------------------------------------------------------- void irtkPartialBSplineFreeFormTransformationSV::Jacobian(irtkMatrix &jac, double x, double y, double z, double t, double t0) const { const double T = UpperIntegrationLimit(t, t0); if (T) _Transformation->Jacobian(jac, x, y, z, T, .0); } // ----------------------------------------------------------------------------- void irtkPartialBSplineFreeFormTransformationSV::GlobalHessian(irtkMatrix h[3], double x, double y, double z, double t, double t0) const { _Transformation->GlobalHessian(h, x, y, z, t, t0); } // ----------------------------------------------------------------------------- void irtkPartialBSplineFreeFormTransformationSV::LocalHessian(irtkMatrix h[3], double x, double y, double z, double t, double t0) const { const double T = UpperIntegrationLimit(t, t0); if (T) _Transformation->LocalHessian(h, x, y, z, T, .0); } // ----------------------------------------------------------------------------- void irtkPartialBSplineFreeFormTransformationSV::Hessian(irtkMatrix h[3], double x, double y, double z, double t, double t0) const { const double T = UpperIntegrationLimit(t, t0); if (T) _Transformation->Hessian(h, x, y, z, T, .0); } // ----------------------------------------------------------------------------- void irtkPartialBSplineFreeFormTransformationSV::JacobianDOFs(double jac[3], int dof, double x, double y, double z, double t, double t0) const { const double T = UpperIntegrationLimit(t, t0); if (T) _Transformation->JacobianDOFs(jac, dof, x, y, z, T, .0); } // ----------------------------------------------------------------------------- void irtkPartialBSplineFreeFormTransformationSV ::ParametricGradient(const irtkGenericImage<double> *in, double *out, const irtkWorldCoordsImage *i2w, const irtkWorldCoordsImage *wc, double t0, double w) const { const double T = UpperIntegrationLimit(in->GetTOrigin(), t0); if (T) _Transformation->ParametricGradient(in, out, i2w, wc, T, .0, w); } // ----------------------------------------------------------------------------- void irtkPartialBSplineFreeFormTransformationSV ::ParametricGradient(const irtkGenericImage<double> **in, int n, double *out, const irtkWorldCoordsImage *i2w, const irtkWorldCoordsImage *wc, const double *t0, double w) const { double t, T; for (int i = 0; i < n; ++i) { t = in[i]->GetTOrigin(); T = UpperIntegrationLimit(t, t0 ? t0[i] : t); if (T) _Transformation->ParametricGradient(in[i], out, i2w, wc, T, .0, w); } } // ============================================================================= // I/O // ============================================================================= // ----------------------------------------------------------------------------- void irtkPartialBSplineFreeFormTransformationSV::Print(irtkIndent indent) const { cout << indent << "Partial B-spline SV FFD" << endl; _Transformation->Print(indent+1); cout << indent << "Fraction of transformation applied: " << _Fraction << endl; } // ----------------------------------------------------------------------------- irtkCifstream &irtkPartialBSplineFreeFormTransformationSV::Read(irtkCifstream &from) { return _Transformation->Read(from); } // ----------------------------------------------------------------------------- irtkCofstream &irtkPartialBSplineFreeFormTransformationSV::Write(irtkCofstream &to) const { return _Transformation->Write(to); }
40.409938
158
0.511912
kevin-keraudren
4c625bb757e4347781c1514f86b956ca78e563e1
295
cpp
C++
atcoder/abc135/a.cpp
yuik46/competition_programming_code
0c47db99ce7fb9bcf6e3b0dbfb8c84d9cfa165fd
[ "MIT" ]
null
null
null
atcoder/abc135/a.cpp
yuik46/competition_programming_code
0c47db99ce7fb9bcf6e3b0dbfb8c84d9cfa165fd
[ "MIT" ]
null
null
null
atcoder/abc135/a.cpp
yuik46/competition_programming_code
0c47db99ce7fb9bcf6e3b0dbfb8c84d9cfa165fd
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main(){ int A; int B; cin >> A >> B; if(A % 2 != B % 2){ cout << "IMPOSSIBLE" << endl; //条件を満たす整数が存在しなければ、代わりにIMPOSSIBLEと出力 } else { cout << (A + B) / 2 << endl; //A + B して2で割った数字を出力 } }
17.352941
44
0.471186
yuik46
4c64128d35359e3e2bc9ef4b29a43e59c171f064
92,562
hpp
C++
include/voxelio/3rd_party/lodepng.hpp
Eisenwave/voxel-io
d902568de2d4afda254e533a5ee9e4ad5fe7d2be
[ "MIT" ]
12
2020-06-25T13:40:22.000Z
2021-12-06T04:00:29.000Z
include/voxelio/3rd_party/lodepng.hpp
Eisenwave/voxel-io
d902568de2d4afda254e533a5ee9e4ad5fe7d2be
[ "MIT" ]
2
2021-02-04T16:19:40.000Z
2021-06-25T09:39:20.000Z
include/voxelio/3rd_party/lodepng.hpp
Eisenwave/voxel-io
d902568de2d4afda254e533a5ee9e4ad5fe7d2be
[ "MIT" ]
null
null
null
/* LodePNG version 20200306 Copyright (c) 2005-2020 Lode Vandevenne This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef VXIO_LODEPNG_HPP #define VXIO_LODEPNG_HPP #include <cstddef> #include "lodepngfwd.hpp" extern const char* LODEPNG_VERSION_STRING; // VOXELIO MODIFICATIONS =============================================================================================== #define LODEPNG_NO_COMPILE_DECODER #define LODEPNG_NO_COMPILE_DISK #define LODEPNG_NO_COMPILE_ANCILLARY_CHUNKS // ===================================================================================================================== /* The following #defines are used to create code sections. They can be disabled to disable code sections, which can give faster compile time and smaller binary. The "NO_COMPILE" defines are designed to be used to pass as defines to the compiler command to disable them without modifying this header, e.g. -DLODEPNG_NO_COMPILE_ZLIB for gcc. In addition to those below, you can also define LODEPNG_NO_COMPILE_CRC to allow implementing a custom lodepng_crc32. */ /*deflate & zlib. If disabled, you must specify alternative zlib functions in the custom_zlib field of the compress and decompress settings*/ #ifndef LODEPNG_NO_COMPILE_ZLIB #define LODEPNG_COMPILE_ZLIB #endif /*png encoder and png decoder*/ #ifndef LODEPNG_NO_COMPILE_PNG #define LODEPNG_COMPILE_PNG #endif /*deflate&zlib decoder and png decoder*/ #ifndef LODEPNG_NO_COMPILE_DECODER #define LODEPNG_COMPILE_DECODER #endif /*deflate&zlib encoder and png encoder*/ #ifndef LODEPNG_NO_COMPILE_ENCODER #define LODEPNG_COMPILE_ENCODER #endif /*the optional built in harddisk file loading and saving functions*/ #ifndef LODEPNG_NO_COMPILE_DISK #define LODEPNG_COMPILE_DISK #endif /*support for chunks other than IHDR, IDAT, PLTE, tRNS, IEND: ancillary and unknown chunks*/ #ifndef LODEPNG_NO_COMPILE_ANCILLARY_CHUNKS #define LODEPNG_COMPILE_ANCILLARY_CHUNKS #endif /*ability to convert error numerical codes to English text string*/ #ifndef LODEPNG_NO_COMPILE_ERROR_TEXT #define LODEPNG_COMPILE_ERROR_TEXT #endif /*Compile the default allocators (C's free, malloc and realloc). If you disable this, you can define the functions lodepng_free, lodepng_malloc and lodepng_realloc in your source files with custom allocators.*/ #ifndef LODEPNG_NO_COMPILE_ALLOCATORS #define LODEPNG_COMPILE_ALLOCATORS #endif /*compile the C++ version (you can disable the C++ wrapper here even when compiling for C++)*/ #ifdef __cplusplus #ifndef LODEPNG_NO_COMPILE_CPP #define LODEPNG_COMPILE_CPP #endif #endif #ifdef LODEPNG_COMPILE_CPP #include <vector> #include <string> #endif /*LODEPNG_COMPILE_CPP*/ #ifdef LODEPNG_COMPILE_PNG #ifdef LODEPNG_COMPILE_DECODER /* Converts PNG data in memory to raw pixel data. out: Output parameter. Pointer to buffer that will contain the raw pixel data. After decoding, its size is w * h * (bytes per pixel) bytes larger than initially. Bytes per pixel depends on colortype and bitdepth. Must be freed after usage with free(*out). Note: for 16-bit per channel colors, uses big endian format like PNG does. w: Output parameter. Pointer to width of pixel data. h: Output parameter. Pointer to height of pixel data. in: Memory buffer with the PNG file. insize: size of the in buffer. colortype: the desired color type for the raw output image. See explanation on PNG color types. bitdepth: the desired bit depth for the raw output image. See explanation on PNG color types. Return value: LodePNG error code (0 means no error). */ unsigned lodepng_decode_memory(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in, size_t insize, LodePNGColorType colortype, unsigned bitdepth); /*Same as lodepng_decode_memory, but always decodes to 32-bit RGBA raw image*/ unsigned lodepng_decode32(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in, size_t insize); /*Same as lodepng_decode_memory, but always decodes to 24-bit RGB raw image*/ unsigned lodepng_decode24(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in, size_t insize); #ifdef LODEPNG_COMPILE_DISK /* Load PNG from disk, from file with given name. Same as the other decode functions, but instead takes a filename as input. */ unsigned lodepng_decode_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename, LodePNGColorType colortype, unsigned bitdepth); /*Same as lodepng_decode_file, but always decodes to 32-bit RGBA raw image.*/ unsigned lodepng_decode32_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename); /*Same as lodepng_decode_file, but always decodes to 24-bit RGB raw image.*/ unsigned lodepng_decode24_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename); #endif /*LODEPNG_COMPILE_DISK*/ #endif /*LODEPNG_COMPILE_DECODER*/ #ifdef LODEPNG_COMPILE_ENCODER /* Converts raw pixel data into a PNG image in memory. The colortype and bitdepth of the output PNG image cannot be chosen, they are automatically determined by the colortype, bitdepth and content of the input pixel data. Note: for 16-bit per channel colors, needs big endian format like PNG does. out: Output parameter. Pointer to buffer that will contain the PNG image data. Must be freed after usage with free(*out). outsize: Output parameter. Pointer to the size in bytes of the out buffer. image: The raw pixel data to encode. The size of this buffer should be w * h * (bytes per pixel), bytes per pixel depends on colortype and bitdepth. w: width of the raw pixel data in pixels. h: height of the raw pixel data in pixels. colortype: the color type of the raw input image. See explanation on PNG color types. bitdepth: the bit depth of the raw input image. See explanation on PNG color types. Return value: LodePNG error code (0 means no error). */ unsigned lodepng_encode_memory(unsigned char** out, size_t* outsize, const unsigned char* image, unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth); /*Same as lodepng_encode_memory, but always encodes from 32-bit RGBA raw image.*/ unsigned lodepng_encode32(unsigned char** out, size_t* outsize, const unsigned char* image, unsigned w, unsigned h); /*Same as lodepng_encode_memory, but always encodes from 24-bit RGB raw image.*/ unsigned lodepng_encode24(unsigned char** out, size_t* outsize, const unsigned char* image, unsigned w, unsigned h); #ifdef LODEPNG_COMPILE_DISK /* Converts raw pixel data into a PNG file on disk. Same as the other encode functions, but instead takes a filename as output. NOTE: This overwrites existing files without warning! */ unsigned lodepng_encode_file(const char* filename, const unsigned char* image, unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth); /*Same as lodepng_encode_file, but always encodes from 32-bit RGBA raw image.*/ unsigned lodepng_encode32_file(const char* filename, const unsigned char* image, unsigned w, unsigned h); /*Same as lodepng_encode_file, but always encodes from 24-bit RGB raw image.*/ unsigned lodepng_encode24_file(const char* filename, const unsigned char* image, unsigned w, unsigned h); #endif /*LODEPNG_COMPILE_DISK*/ #endif /*LODEPNG_COMPILE_ENCODER*/ #ifdef LODEPNG_COMPILE_CPP namespace lodepng { #ifdef LODEPNG_COMPILE_DECODER /*Same as lodepng_decode_memory, but decodes to an std::vector. The colortype is the format to output the pixels to. Default is RGBA 8-bit per channel.*/ unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h, const unsigned char* in, size_t insize, LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h, const std::vector<unsigned char>& in, LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); #ifdef LODEPNG_COMPILE_DISK /* Converts PNG file from disk to raw pixel data in memory. Same as the other decode functions, but instead takes a filename as input. */ unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h, const std::string& filename, LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); #endif /* LODEPNG_COMPILE_DISK */ #endif /* LODEPNG_COMPILE_DECODER */ #ifdef LODEPNG_COMPILE_ENCODER /*Same as lodepng_encode_memory, but encodes to an std::vector. colortype is that of the raw input data. The output PNG color type will be auto chosen.*/ unsigned encode(voxelio::OutputStream& out, const voxelio::u8* in, unsigned w, unsigned h, LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); #ifdef LODEPNG_COMPILE_DISK /* Converts 32-bit RGBA raw pixel data into a PNG file on disk. Same as the other encode functions, but instead takes a filename as output. NOTE: This overwrites existing files without warning! */ unsigned encode(const std::string& filename, const unsigned char* in, unsigned w, unsigned h, LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); unsigned encode(const std::string& filename, const std::vector<unsigned char>& in, unsigned w, unsigned h, LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); #endif /* LODEPNG_COMPILE_DISK */ #endif /* LODEPNG_COMPILE_ENCODER */ } /* namespace lodepng */ #endif /*LODEPNG_COMPILE_CPP*/ #endif /*LODEPNG_COMPILE_PNG*/ #ifdef LODEPNG_COMPILE_ERROR_TEXT /*Returns an English description of the numerical error code.*/ const char* lodepng_error_text(unsigned code); #endif /*LODEPNG_COMPILE_ERROR_TEXT*/ #ifdef LODEPNG_COMPILE_DECODER /*Settings for zlib decompression*/ typedef struct LodePNGDecompressSettings LodePNGDecompressSettings; struct LodePNGDecompressSettings { /* Check LodePNGDecoderSettings for more ignorable errors such as ignore_crc */ unsigned ignore_adler32; /*if 1, continue and don't give an error message if the Adler32 checksum is corrupted*/ unsigned ignore_nlen; /*ignore complement of len checksum in uncompressed blocks*/ /*use custom zlib decoder instead of built in one (default: null)*/ unsigned (*custom_zlib)(unsigned char**, size_t*, const unsigned char*, size_t, const LodePNGDecompressSettings*); /*use custom deflate decoder instead of built in one (default: null) if custom_zlib is not null, custom_inflate is ignored (the zlib format uses deflate)*/ unsigned (*custom_inflate)(unsigned char**, size_t*, const unsigned char*, size_t, const LodePNGDecompressSettings*); const void* custom_context; /*optional custom settings for custom functions*/ }; extern const LodePNGDecompressSettings lodepng_default_decompress_settings; void lodepng_decompress_settings_init(LodePNGDecompressSettings* settings); #endif /*LODEPNG_COMPILE_DECODER*/ #ifdef LODEPNG_COMPILE_ENCODER /* Settings for zlib compression. Tweaking these settings tweaks the balance between speed and compression ratio. */ typedef struct LodePNGCompressSettings LodePNGCompressSettings; struct LodePNGCompressSettings /*deflate = compress*/ { /*LZ77 related settings*/ unsigned btype; /*the block type for LZ (0, 1, 2 or 3, see zlib standard). Should be 2 for proper compression.*/ unsigned use_lz77; /*whether or not to use LZ77. Should be 1 for proper compression.*/ unsigned windowsize; /*must be a power of two <= 32768. higher compresses more but is slower. Default value: 2048.*/ unsigned minmatch; /*minimum lz77 length. 3 is normally best, 6 can be better for some PNGs. Default: 0*/ unsigned nicematch; /*stop searching if >= this length found. Set to 258 for best compression. Default: 128*/ unsigned lazymatching; /*use lazy matching: better compression but a bit slower. Default: true*/ /*use custom zlib encoder instead of built in one (default: null)*/ unsigned (*custom_zlib)(unsigned char**, size_t*, const unsigned char*, size_t, const LodePNGCompressSettings*); /*use custom deflate encoder instead of built in one (default: null) if custom_zlib is used, custom_deflate is ignored since only the built in zlib function will call custom_deflate*/ unsigned (*custom_deflate)(unsigned char**, size_t*, const unsigned char*, size_t, const LodePNGCompressSettings*); const void* custom_context; /*optional custom settings for custom functions*/ }; extern const LodePNGCompressSettings lodepng_default_compress_settings; void lodepng_compress_settings_init(LodePNGCompressSettings* settings); #endif /*LODEPNG_COMPILE_ENCODER*/ #ifdef LODEPNG_COMPILE_PNG /* Color mode of an image. Contains all information required to decode the pixel bits to RGBA colors. This information is the same as used in the PNG file format, and is used both for PNG and raw image data in LodePNG. */ typedef struct LodePNGColorMode { /*header (IHDR)*/ LodePNGColorType colortype; /*color type, see PNG standard or documentation further in this header file*/ unsigned bitdepth; /*bits per sample, see PNG standard or documentation further in this header file*/ /* palette (PLTE and tRNS) Dynamically allocated with the colors of the palette, including alpha. This field may not be allocated directly, use lodepng_color_mode_init first, then lodepng_palette_add per color to correctly initialize it (to ensure size of exactly 1024 bytes). The alpha channels must be set as well, set them to 255 for opaque images. When decoding, by default you can ignore this palette, since LodePNG already fills the palette colors in the pixels of the raw RGBA output. The palette is only supported for color type 3. */ unsigned char* palette; /*palette in RGBARGBA... order. Must be either 0, or when allocated must have 1024 bytes*/ size_t palettesize; /*palette size in number of colors (amount of used bytes is 4 * palettesize)*/ /* transparent color key (tRNS) This color uses the same bit depth as the bitdepth value in this struct, which can be 1-bit to 16-bit. For grayscale PNGs, r, g and b will all 3 be set to the same. When decoding, by default you can ignore this information, since LodePNG sets pixels with this key to transparent already in the raw RGBA output. The color key is only supported for color types 0 and 2. */ unsigned key_defined; /*is a transparent color key given? 0 = false, 1 = true*/ unsigned key_r; /*red/grayscale component of color key*/ unsigned key_g; /*green component of color key*/ unsigned key_b; /*blue component of color key*/ } LodePNGColorMode; /*init, cleanup and copy functions to use with this struct*/ void lodepng_color_mode_init(LodePNGColorMode* info); void lodepng_color_mode_cleanup(LodePNGColorMode* info); /*return value is error code (0 means no error)*/ unsigned lodepng_color_mode_copy(LodePNGColorMode* dest, const LodePNGColorMode* source); /* Makes a temporary LodePNGColorMode that does not need cleanup (no palette) */ LodePNGColorMode lodepng_color_mode_make(LodePNGColorType colortype, unsigned bitdepth); void lodepng_palette_clear(LodePNGColorMode* info); /*add 1 color to the palette*/ unsigned lodepng_palette_add(LodePNGColorMode* info, unsigned char r, unsigned char g, unsigned char b, unsigned char a); /*get the total amount of bits per pixel, based on colortype and bitdepth in the struct*/ unsigned lodepng_get_bpp(const LodePNGColorMode* info); /*get the amount of color channels used, based on colortype in the struct. If a palette is used, it counts as 1 channel.*/ unsigned lodepng_get_channels(const LodePNGColorMode* info); /*is it a grayscale type? (only colortype 0 or 4)*/ unsigned lodepng_is_greyscale_type(const LodePNGColorMode* info); /*has it got an alpha channel? (only colortype 2 or 6)*/ unsigned lodepng_is_alpha_type(const LodePNGColorMode* info); /*has it got a palette? (only colortype 3)*/ unsigned lodepng_is_palette_type(const LodePNGColorMode* info); /*only returns true if there is a palette and there is a value in the palette with alpha < 255. Loops through the palette to check this.*/ unsigned lodepng_has_palette_alpha(const LodePNGColorMode* info); /* Check if the given color info indicates the possibility of having non-opaque pixels in the PNG image. Returns true if the image can have translucent or invisible pixels (it still be opaque if it doesn't use such pixels). Returns false if the image can only have opaque pixels. In detail, it returns true only if it's a color type with alpha, or has a palette with non-opaque values, or if "key_defined" is true. */ unsigned lodepng_can_have_alpha(const LodePNGColorMode* info); /*Returns the byte size of a raw image buffer with given width, height and color mode*/ size_t lodepng_get_raw_size(unsigned w, unsigned h, const LodePNGColorMode* color); #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS /*The information of a Time chunk in PNG.*/ typedef struct LodePNGTime { unsigned year; /*2 bytes used (0-65535)*/ unsigned month; /*1-12*/ unsigned day; /*1-31*/ unsigned hour; /*0-23*/ unsigned minute; /*0-59*/ unsigned second; /*0-60 (to allow for leap seconds)*/ } LodePNGTime; #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ /*Information about the PNG image, except pixels, width and height.*/ typedef struct LodePNGInfo { /*header (IHDR), palette (PLTE) and transparency (tRNS) chunks*/ unsigned compression_method;/*compression method of the original file. Always 0.*/ unsigned filter_method; /*filter method of the original file*/ unsigned interlace_method; /*interlace method of the original file: 0=none, 1=Adam7*/ LodePNGColorMode color; /*color type and bits, palette and transparency of the PNG file*/ #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS /* Suggested background color chunk (bKGD) This uses the same color mode and bit depth as the PNG (except no alpha channel), with values truncated to the bit depth in the unsigned integer. For grayscale and palette PNGs, the value is stored in background_r. The values in background_g and background_b are then unused. So when decoding, you may get these in a different color mode than the one you requested for the raw pixels. When encoding with auto_convert, you must use the color model defined in info_png.color for these values. The encoder normally ignores info_png.color when auto_convert is on, but will use it to interpret these values (and convert copies of them to its chosen color model). When encoding, avoid setting this to an expensive color, such as a non-gray value when the image is gray, or the compression will be worse since it will be forced to write the PNG with a more expensive color mode (when auto_convert is on). The decoder does not use this background color to edit the color of pixels. This is a completely optional metadata feature. */ unsigned background_defined; /*is a suggested background color given?*/ unsigned background_r; /*red/gray/palette component of suggested background color*/ unsigned background_g; /*green component of suggested background color*/ unsigned background_b; /*blue component of suggested background color*/ /* non-international text chunks (tEXt and zTXt) The char** arrays each contain num strings. The actual messages are in text_strings, while text_keys are keywords that give a short description what the actual text represents, e.g. Title, Author, Description, or anything else. All the string fields below including keys, names and language tags are null terminated. The PNG specification uses null characters for the keys, names and tags, and forbids null characters to appear in the main text which is why we can use null termination everywhere here. A keyword is minimum 1 character and maximum 79 characters long. It's discouraged to use a single line length longer than 79 characters for texts. Don't allocate these text buffers yourself. Use the init/cleanup functions correctly and use lodepng_add_text and lodepng_clear_text. */ size_t text_num; /*the amount of texts in these char** buffers (there may be more texts in itext)*/ char** text_keys; /*the keyword of a text chunk (e.g. "Comment")*/ char** text_strings; /*the actual text*/ /* international text chunks (iTXt) Similar to the non-international text chunks, but with additional strings "langtags" and "transkeys". */ size_t itext_num; /*the amount of international texts in this PNG*/ char** itext_keys; /*the English keyword of the text chunk (e.g. "Comment")*/ char** itext_langtags; /*language tag for this text's language, ISO/IEC 646 string, e.g. ISO 639 language tag*/ char** itext_transkeys; /*keyword translated to the international language - UTF-8 string*/ char** itext_strings; /*the actual international text - UTF-8 string*/ /*time chunk (tIME)*/ unsigned time_defined; /*set to 1 to make the encoder generate a tIME chunk*/ LodePNGTime time; /*phys chunk (pHYs)*/ unsigned phys_defined; /*if 0, there is no pHYs chunk and the values below are undefined, if 1 else there is one*/ unsigned phys_x; /*pixels per unit in x direction*/ unsigned phys_y; /*pixels per unit in y direction*/ unsigned phys_unit; /*may be 0 (unknown unit) or 1 (metre)*/ /* Color profile related chunks: gAMA, cHRM, sRGB, iCPP LodePNG does not apply any color conversions on pixels in the encoder or decoder and does not interpret these color profile values. It merely passes on the information. If you wish to use color profiles and convert colors, please use these values with a color management library. See the PNG, ICC and sRGB specifications for more information about the meaning of these values. */ /* gAMA chunk: optional, overridden by sRGB or iCCP if those are present. */ unsigned gama_defined; /* Whether a gAMA chunk is present (0 = not present, 1 = present). */ unsigned gama_gamma; /* Gamma exponent times 100000 */ /* cHRM chunk: optional, overridden by sRGB or iCCP if those are present. */ unsigned chrm_defined; /* Whether a cHRM chunk is present (0 = not present, 1 = present). */ unsigned chrm_white_x; /* White Point x times 100000 */ unsigned chrm_white_y; /* White Point y times 100000 */ unsigned chrm_red_x; /* Red x times 100000 */ unsigned chrm_red_y; /* Red y times 100000 */ unsigned chrm_green_x; /* Green x times 100000 */ unsigned chrm_green_y; /* Green y times 100000 */ unsigned chrm_blue_x; /* Blue x times 100000 */ unsigned chrm_blue_y; /* Blue y times 100000 */ /* sRGB chunk: optional. May not appear at the same time as iCCP. If gAMA is also present gAMA must contain value 45455. If cHRM is also present cHRM must contain respectively 31270,32900,64000,33000,30000,60000,15000,6000. */ unsigned srgb_defined; /* Whether an sRGB chunk is present (0 = not present, 1 = present). */ unsigned srgb_intent; /* Rendering intent: 0=perceptual, 1=rel. colorimetric, 2=saturation, 3=abs. colorimetric */ /* iCCP chunk: optional. May not appear at the same time as sRGB. LodePNG does not parse or use the ICC profile (except its color space header field for an edge case), a separate library to handle the ICC data (not included in LodePNG) format is needed to use it for color management and conversions. For encoding, if iCCP is present, gAMA and cHRM are recommended to be added as well with values that match the ICC profile as closely as possible, if you wish to do this you should provide the correct values for gAMA and cHRM and enable their '_defined' flags since LodePNG will not automatically compute them from the ICC profile. For encoding, the ICC profile is required by the PNG specification to be an "RGB" profile for non-gray PNG color types and a "GRAY" profile for gray PNG color types. If you disable auto_convert, you must ensure the ICC profile type matches your requested color type, else the encoder gives an error. If auto_convert is enabled (the default), and the ICC profile is not a good match for the pixel data, this will result in an encoder error if the pixel data has non-gray pixels for a GRAY profile, or a silent less-optimal compression of the pixel data if the pixels could be encoded as grayscale but the ICC profile is RGB. To avoid this do not set an ICC profile in the image unless there is a good reason for it, and when doing so make sure you compute it carefully to avoid the above problems. */ unsigned iccp_defined; /* Whether an iCCP chunk is present (0 = not present, 1 = present). */ char* iccp_name; /* Null terminated string with profile name, 1-79 bytes */ /* The ICC profile in iccp_profile_size bytes. Don't allocate this buffer yourself. Use the init/cleanup functions correctly and use lodepng_set_icc and lodepng_clear_icc. */ unsigned char* iccp_profile; unsigned iccp_profile_size; /* The size of iccp_profile in bytes */ /* End of color profile related chunks */ /* unknown chunks: chunks not known by LodePNG, passed on byte for byte. There are 3 buffers, one for each position in the PNG where unknown chunks can appear. Each buffer contains all unknown chunks for that position consecutively. The 3 positions are: 0: between IHDR and PLTE, 1: between PLTE and IDAT, 2: between IDAT and IEND. For encoding, do not store critical chunks or known chunks that are enabled with a "_defined" flag above in here, since the encoder will blindly follow this and could then encode an invalid PNG file (such as one with two IHDR chunks or the disallowed combination of sRGB with iCCP). But do use this if you wish to store an ancillary chunk that is not supported by LodePNG (such as sPLT or hIST), or any non-standard PNG chunk. Do not allocate or traverse this data yourself. Use the chunk traversing functions declared later, such as lodepng_chunk_next and lodepng_chunk_append, to read/write this struct. */ unsigned char* unknown_chunks_data[3]; size_t unknown_chunks_size[3]; /*size in bytes of the unknown chunks, given for protection*/ #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ } LodePNGInfo; /*init, cleanup and copy functions to use with this struct*/ void lodepng_info_init(LodePNGInfo* info); void lodepng_info_cleanup(LodePNGInfo* info); /*return value is error code (0 means no error)*/ unsigned lodepng_info_copy(LodePNGInfo* dest, const LodePNGInfo* source); #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS unsigned lodepng_add_text(LodePNGInfo* info, const char* key, const char* str); /*push back both texts at once*/ void lodepng_clear_text(LodePNGInfo* info); /*use this to clear the texts again after you filled them in*/ unsigned lodepng_add_itext(LodePNGInfo* info, const char* key, const char* langtag, const char* transkey, const char* str); /*push back the 4 texts of 1 chunk at once*/ void lodepng_clear_itext(LodePNGInfo* info); /*use this to clear the itexts again after you filled them in*/ /*replaces if exists*/ unsigned lodepng_set_icc(LodePNGInfo* info, const char* name, const unsigned char* profile, unsigned profile_size); void lodepng_clear_icc(LodePNGInfo* info); /*use this to clear the texts again after you filled them in*/ #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ /* Converts raw buffer from one color type to another color type, based on LodePNGColorMode structs to describe the input and output color type. See the reference manual at the end of this header file to see which color conversions are supported. return value = LodePNG error code (0 if all went ok, an error if the conversion isn't supported) The out buffer must have size (w * h * bpp + 7) / 8, where bpp is the bits per pixel of the output color type (lodepng_get_bpp). For < 8 bpp images, there should not be padding bits at the end of scanlines. For 16-bit per channel colors, uses big endian format like PNG does. Return value is LodePNG error code */ unsigned lodepng_convert(unsigned char* out, const unsigned char* in, const LodePNGColorMode* mode_out, const LodePNGColorMode* mode_in, unsigned w, unsigned h); #ifdef LODEPNG_COMPILE_DECODER /* Settings for the decoder. This contains settings for the PNG and the Zlib decoder, but not the Info settings from the Info structs. */ typedef struct LodePNGDecoderSettings { LodePNGDecompressSettings zlibsettings; /*in here is the setting to ignore Adler32 checksums*/ /* Check LodePNGDecompressSettings for more ignorable errors such as ignore_adler32 */ unsigned ignore_crc; /*ignore CRC checksums*/ unsigned ignore_critical; /*ignore unknown critical chunks*/ unsigned ignore_end; /*ignore issues at end of file if possible (missing IEND chunk, too large chunk, ...)*/ /* TODO: make a system involving warnings with levels and a strict mode instead. Other potentially recoverable errors: srgb rendering intent value, size of content of ancillary chunks, more than 79 characters for some strings, placement/combination rules for ancillary chunks, crc of unknown chunks, allowed characters in string keys, etc... */ unsigned color_convert; /*whether to convert the PNG to the color type you want. Default: yes*/ #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS unsigned read_text_chunks; /*if false but remember_unknown_chunks is true, they're stored in the unknown chunks*/ /*store all bytes from unknown chunks in the LodePNGInfo (off by default, useful for a png editor)*/ unsigned remember_unknown_chunks; #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ } LodePNGDecoderSettings; void lodepng_decoder_settings_init(LodePNGDecoderSettings* settings); #endif /*LODEPNG_COMPILE_DECODER*/ #ifdef LODEPNG_COMPILE_ENCODER /*automatically use color type with less bits per pixel if losslessly possible. Default: AUTO*/ typedef enum LodePNGFilterStrategy { /*every filter at zero*/ LFS_ZERO = 0, /*every filter at 1, 2, 3 or 4 (paeth), unlike LFS_ZERO not a good choice, but for testing*/ LFS_ONE = 1, LFS_TWO = 2, LFS_THREE = 3, LFS_FOUR = 4, /*Use filter that gives minimum sum, as described in the official PNG filter heuristic.*/ LFS_MINSUM, /*Use the filter type that gives smallest Shannon entropy for this scanline. Depending on the image, this is better or worse than minsum.*/ LFS_ENTROPY, /* Brute-force-search PNG filters by compressing each filter for each scanline. Experimental, very slow, and only rarely gives better compression than MINSUM. */ LFS_BRUTE_FORCE, /*use predefined_filters buffer: you specify the filter type for each scanline*/ LFS_PREDEFINED } LodePNGFilterStrategy; /*Gives characteristics about the integer RGBA colors of the image (count, alpha channel usage, bit depth, ...), which helps decide which color model to use for encoding. Used internally by default if "auto_convert" is enabled. Public because it's useful for custom algorithms.*/ typedef struct LodePNGColorStats { unsigned colored; /*not grayscale*/ unsigned key; /*image is not opaque and color key is possible instead of full alpha*/ unsigned short key_r; /*key values, always as 16-bit, in 8-bit case the byte is duplicated, e.g. 65535 means 255*/ unsigned short key_g; unsigned short key_b; unsigned alpha; /*image is not opaque and alpha channel or alpha palette required*/ unsigned numcolors; /*amount of colors, up to 257. Not valid if bits == 16 or allow_palette is disabled.*/ unsigned char palette[1024]; /*Remembers up to the first 256 RGBA colors, in no particular order, only valid when numcolors is valid*/ unsigned bits; /*bits per channel (not for palette). 1,2 or 4 for grayscale only. 16 if 16-bit per channel required.*/ size_t numpixels; /*user settings for computing/using the stats*/ unsigned allow_palette; /*default 1. if 0, disallow choosing palette colortype in auto_choose_color, and don't count numcolors*/ unsigned allow_greyscale; /*default 1. if 0, choose RGB or RGBA even if the image only has gray colors*/ } LodePNGColorStats; void lodepng_color_stats_init(LodePNGColorStats* stats); /*Get a LodePNGColorStats of the image. The stats must already have been inited. Returns error code (e.g. alloc fail) or 0 if ok.*/ unsigned lodepng_compute_color_stats(LodePNGColorStats* stats, const unsigned char* image, unsigned w, unsigned h, const LodePNGColorMode* mode_in); /*Settings for the encoder.*/ typedef struct LodePNGEncoderSettings { LodePNGCompressSettings zlibsettings; /*settings for the zlib encoder, such as window size, ...*/ unsigned auto_convert; /*automatically choose output PNG color type. Default: true*/ /*If true, follows the official PNG heuristic: if the PNG uses a palette or lower than 8 bit depth, set all filters to zero. Otherwise use the filter_strategy. Note that to completely follow the official PNG heuristic, filter_palette_zero must be true and filter_strategy must be LFS_MINSUM*/ unsigned filter_palette_zero; /*Which filter strategy to use when not using zeroes due to filter_palette_zero. Set filter_palette_zero to 0 to ensure always using your chosen strategy. Default: LFS_MINSUM*/ LodePNGFilterStrategy filter_strategy; /*used if filter_strategy is LFS_PREDEFINED. In that case, this must point to a buffer with the same length as the amount of scanlines in the image, and each value must <= 5. You have to cleanup this buffer, LodePNG will never free it. Don't forget that filter_palette_zero must be set to 0 to ensure this is also used on palette or low bitdepth images.*/ const unsigned char* predefined_filters; /*force creating a PLTE chunk if colortype is 2 or 6 (= a suggested palette). If colortype is 3, PLTE is _always_ created.*/ unsigned force_palette; #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS /*add LodePNG identifier and version as a text chunk, for debugging*/ unsigned add_id; /*encode text chunks as zTXt chunks instead of tEXt chunks, and use compression in iTXt chunks*/ unsigned text_compression; #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ } LodePNGEncoderSettings; void lodepng_encoder_settings_init(LodePNGEncoderSettings* settings); #endif /*LODEPNG_COMPILE_ENCODER*/ #if defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER) /*The settings, state and information for extended encoding and decoding.*/ typedef struct LodePNGState { #ifdef LODEPNG_COMPILE_DECODER LodePNGDecoderSettings decoder; /*the decoding settings*/ #endif /*LODEPNG_COMPILE_DECODER*/ #ifdef LODEPNG_COMPILE_ENCODER LodePNGEncoderSettings encoder; /*the encoding settings*/ #endif /*LODEPNG_COMPILE_ENCODER*/ LodePNGColorMode info_raw; /*specifies the format in which you would like to get the raw pixel buffer*/ LodePNGInfo info_png; /*info of the PNG image obtained after decoding*/ unsigned error; } LodePNGState; /*init, cleanup and copy functions to use with this struct*/ void lodepng_state_init(LodePNGState* state); void lodepng_state_cleanup(LodePNGState* state); void lodepng_state_copy(LodePNGState* dest, const LodePNGState* source); #endif /* defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER) */ #ifdef LODEPNG_COMPILE_DECODER /* Same as lodepng_decode_memory, but uses a LodePNGState to allow custom settings and getting much more information about the PNG image and color mode. */ unsigned lodepng_decode(unsigned char** out, unsigned* w, unsigned* h, LodePNGState* state, const unsigned char* in, size_t insize); /* Read the PNG header, but not the actual data. This returns only the information that is in the IHDR chunk of the PNG, such as width, height and color type. The information is placed in the info_png field of the LodePNGState. */ unsigned lodepng_inspect(unsigned* w, unsigned* h, LodePNGState* state, const unsigned char* in, size_t insize); #endif /*LODEPNG_COMPILE_DECODER*/ /* Reads one metadata chunk (other than IHDR) of the PNG file and outputs what it read in the state. Returns error code on failure. Use lodepng_inspect first with a new state, then e.g. lodepng_chunk_find_const to find the desired chunk type, and if non null use lodepng_inspect_chunk (with chunk_pointer - start_of_file as pos). Supports most metadata chunks from the PNG standard (gAMA, bKGD, tEXt, ...). Ignores unsupported, unknown, non-metadata or IHDR chunks (without error). Requirements: &in[pos] must point to start of a chunk, must use regular lodepng_inspect first since format of most other chunks depends on IHDR, and if there is a PLTE chunk, that one must be inspected before tRNS or bKGD. */ unsigned lodepng_inspect_chunk(LodePNGState* state, size_t pos, const unsigned char* in, size_t insize); #ifdef LODEPNG_COMPILE_ENCODER /*This function allocates the out buffer with standard malloc and stores the size in *outsize.*/ unsigned lodepng_encode(unsigned char** out, size_t* outsize, const unsigned char* image, unsigned w, unsigned h, LodePNGState* state); #endif /*LODEPNG_COMPILE_ENCODER*/ /* The lodepng_chunk functions are normally not needed, except to traverse the unknown chunks stored in the LodePNGInfo struct, or add new ones to it. It also allows traversing the chunks of an encoded PNG file yourself. The chunk pointer always points to the beginning of the chunk itself, that is the first byte of the 4 length bytes. In the PNG file format, chunks have the following format: -4 bytes length: length of the data of the chunk in bytes (chunk itself is 12 bytes longer) -4 bytes chunk type (ASCII a-z,A-Z only, see below) -length bytes of data (may be 0 bytes if length was 0) -4 bytes of CRC, computed on chunk name + data The first chunk starts at the 8th byte of the PNG file, the entire rest of the file exists out of concatenated chunks with the above format. PNG standard chunk ASCII naming conventions: -First byte: uppercase = critical, lowercase = ancillary -Second byte: uppercase = public, lowercase = private -Third byte: must be uppercase -Fourth byte: uppercase = unsafe to copy, lowercase = safe to copy */ /* Gets the length of the data of the chunk. Total chunk length has 12 bytes more. There must be at least 4 bytes to read from. If the result value is too large, it may be corrupt data. */ unsigned lodepng_chunk_length(const unsigned char* chunk); /*puts the 4-byte type in null terminated string*/ void lodepng_chunk_type(char type[5], const unsigned char* chunk); /*check if the type is the given type*/ unsigned char lodepng_chunk_type_equals(const unsigned char* chunk, const char* type); /*0: it's one of the critical chunk types, 1: it's an ancillary chunk (see PNG standard)*/ unsigned char lodepng_chunk_ancillary(const unsigned char* chunk); /*0: public, 1: private (see PNG standard)*/ unsigned char lodepng_chunk_private(const unsigned char* chunk); /*0: the chunk is unsafe to copy, 1: the chunk is safe to copy (see PNG standard)*/ unsigned char lodepng_chunk_safetocopy(const unsigned char* chunk); /*get pointer to the data of the chunk, where the input points to the header of the chunk*/ unsigned char* lodepng_chunk_data(unsigned char* chunk); const unsigned char* lodepng_chunk_data_const(const unsigned char* chunk); /*returns 0 if the crc is correct, 1 if it's incorrect (0 for OK as usual!)*/ unsigned lodepng_chunk_check_crc(const unsigned char* chunk); /*generates the correct CRC from the data and puts it in the last 4 bytes of the chunk*/ void lodepng_chunk_generate_crc(unsigned char* chunk); /* Iterate to next chunks, allows iterating through all chunks of the PNG file. Input must be at the beginning of a chunk (result of a previous lodepng_chunk_next call, or the 8th byte of a PNG file which always has the first chunk), or alternatively may point to the first byte of the PNG file (which is not a chunk but the magic header, the function will then skip over it and return the first real chunk). Will output pointer to the start of the next chunk, or at or beyond end of the file if there is no more chunk after this or possibly if the chunk is corrupt. Start this process at the 8th byte of the PNG file. In a non-corrupt PNG file, the last chunk should have name "IEND". */ unsigned char* lodepng_chunk_next(unsigned char* chunk, unsigned char* end); const unsigned char* lodepng_chunk_next_const(const unsigned char* chunk, const unsigned char* end); /*Finds the first chunk with the given type in the range [chunk, end), or returns NULL if not found.*/ unsigned char* lodepng_chunk_find(unsigned char* chunk, unsigned char* end, const char type[5]); const unsigned char* lodepng_chunk_find_const(const unsigned char* chunk, const unsigned char* end, const char type[5]); /* Appends chunk to the data in out. The given chunk should already have its chunk header. The out variable and outsize are updated to reflect the new reallocated buffer. Returns error code (0 if it went ok) */ unsigned lodepng_chunk_append(unsigned char** out, size_t* outsize, const unsigned char* chunk); /* Appends new chunk to out. The chunk to append is given by giving its length, type and data separately. The type is a 4-letter string. The out variable and outsize are updated to reflect the new reallocated buffer. Returne error code (0 if it went ok) */ unsigned lodepng_chunk_create(unsigned char** out, size_t* outsize, unsigned length, const char* type, const unsigned char* data); /*Calculate CRC32 of buffer*/ unsigned lodepng_crc32(const unsigned char* buf, size_t len); #endif /*LODEPNG_COMPILE_PNG*/ #ifdef LODEPNG_COMPILE_ZLIB /* This zlib part can be used independently to zlib compress and decompress a buffer. It cannot be used to create gzip files however, and it only supports the part of zlib that is required for PNG, it does not support dictionaries. */ #ifdef LODEPNG_COMPILE_DECODER /*Inflate a buffer. Inflate is the decompression step of deflate. Out buffer must be freed after use.*/ unsigned lodepng_inflate(unsigned char** out, size_t* outsize, const unsigned char* in, size_t insize, const LodePNGDecompressSettings* settings); /* Decompresses Zlib data. Reallocates the out buffer and appends the data. The data must be according to the zlib specification. Either, *out must be NULL and *outsize must be 0, or, *out must be a valid buffer and *outsize its size in bytes. out must be freed by user after usage. */ unsigned lodepng_zlib_decompress(unsigned char** out, size_t* outsize, const unsigned char* in, size_t insize, const LodePNGDecompressSettings* settings); #endif /*LODEPNG_COMPILE_DECODER*/ #ifdef LODEPNG_COMPILE_ENCODER /* Compresses data with Zlib. Reallocates the out buffer and appends the data. Zlib adds a small header and trailer around the deflate data. The data is output in the format of the zlib specification. Either, *out must be NULL and *outsize must be 0, or, *out must be a valid buffer and *outsize its size in bytes. out must be freed by user after usage. */ unsigned lodepng_zlib_compress(unsigned char** out, size_t* outsize, const unsigned char* in, size_t insize, const LodePNGCompressSettings* settings); /* Find length-limited Huffman code for given frequencies. This function is in the public interface only for tests, it's used internally by lodepng_deflate. */ unsigned lodepng_huffman_code_lengths(unsigned* lengths, const unsigned* frequencies, size_t numcodes, unsigned maxbitlen); /*Compress a buffer with deflate. See RFC 1951. Out buffer must be freed after use.*/ unsigned lodepng_deflate(unsigned char** out, size_t* outsize, const unsigned char* in, size_t insize, const LodePNGCompressSettings* settings); #endif /*LODEPNG_COMPILE_ENCODER*/ #endif /*LODEPNG_COMPILE_ZLIB*/ #ifdef LODEPNG_COMPILE_DISK /* Load a file from disk into buffer. The function allocates the out buffer, and after usage you should free it. out: output parameter, contains pointer to loaded buffer. outsize: output parameter, size of the allocated out buffer filename: the path to the file to load return value: error code (0 means ok) */ unsigned lodepng_load_file(unsigned char** out, size_t* outsize, const char* filename); /* Save a file from buffer to disk. Warning, if it exists, this function overwrites the file without warning! buffer: the buffer to write buffersize: size of the buffer to write filename: the path to the file to save to return value: error code (0 means ok) */ unsigned lodepng_save_file(const unsigned char* buffer, size_t buffersize, const char* filename); #endif /*LODEPNG_COMPILE_DISK*/ #ifdef LODEPNG_COMPILE_CPP /* The LodePNG C++ wrapper uses std::vectors instead of manually allocated memory buffers. */ namespace lodepng { #ifdef LODEPNG_COMPILE_PNG class State : public LodePNGState { public: State(); State(const State& other); ~State(); State& operator=(const State& other); }; #ifdef LODEPNG_COMPILE_DECODER /* Same as other lodepng::decode, but using a State for more settings and information. */ unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h, State& state, const unsigned char* in, size_t insize); unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h, State& state, const std::vector<unsigned char>& in); #endif /*LODEPNG_COMPILE_DECODER*/ #ifdef LODEPNG_COMPILE_DISK /* Load a file from disk into an std::vector. return value: error code (0 means ok) */ unsigned load_file(std::vector<unsigned char>& buffer, const std::string& filename); /* Save the binary data in an std::vector to a file on disk. The file is overwritten without warning. */ unsigned save_file(const std::vector<unsigned char>& buffer, const std::string& filename); #endif /* LODEPNG_COMPILE_DISK */ #endif /* LODEPNG_COMPILE_PNG */ #ifdef LODEPNG_COMPILE_ZLIB #ifdef LODEPNG_COMPILE_DECODER /* Zlib-decompress an unsigned char buffer */ unsigned decompress(std::vector<unsigned char>& out, const unsigned char* in, size_t insize, const LodePNGDecompressSettings& settings = lodepng_default_decompress_settings); /* Zlib-decompress an std::vector */ unsigned decompress(std::vector<unsigned char>& out, const std::vector<unsigned char>& in, const LodePNGDecompressSettings& settings = lodepng_default_decompress_settings); #endif /* LODEPNG_COMPILE_DECODER */ #ifdef LODEPNG_COMPILE_ENCODER /* Zlib-compress an unsigned char buffer */ unsigned compress(std::vector<unsigned char>& out, const unsigned char* in, size_t insize, const LodePNGCompressSettings& settings = lodepng_default_compress_settings); /* Zlib-compress an std::vector */ unsigned compress(std::vector<unsigned char>& out, const std::vector<unsigned char>& in, const LodePNGCompressSettings& settings = lodepng_default_compress_settings); #endif /* LODEPNG_COMPILE_ENCODER */ #endif /* LODEPNG_COMPILE_ZLIB */ } /* namespace lodepng */ #endif /*LODEPNG_COMPILE_CPP*/ /* TODO: [.] test if there are no memory leaks or security exploits - done a lot but needs to be checked often [.] check compatibility with various compilers - done but needs to be redone for every newer version [X] converting color to 16-bit per channel types [X] support color profile chunk types (but never let them touch RGB values by default) [ ] support all public PNG chunk types (almost done except sBIT, sPLT and hIST) [ ] make sure encoder generates no chunks with size > (2^31)-1 [ ] partial decoding (stream processing) [X] let the "isFullyOpaque" function check color keys and transparent palettes too [X] better name for the variables "codes", "codesD", "codelengthcodes", "clcl" and "lldl" [ ] allow treating some errors like warnings, when image is recoverable (e.g. 69, 57, 58) [ ] make warnings like: oob palette, checksum fail, data after iend, wrong/unknown crit chunk, no null terminator in text, ... [ ] error messages with line numbers (and version) [ ] errors in state instead of as return code? [ ] new errors/warnings like suspiciously big decompressed ztxt or iccp chunk [ ] let the C++ wrapper catch exceptions coming from the standard library and return LodePNG error codes [ ] allow user to provide custom color conversion functions, e.g. for premultiplied alpha, padding bits or not, ... [ ] allow user to give data (void*) to custom allocator [X] provide alternatives for C library functions not present on some platforms (memcpy, ...) */ #endif // VXIO_LODEPNG_HPP /* LodePNG Documentation --------------------- 0. table of contents -------------------- 1. about 1.1. supported features 1.2. features not supported 2. C and C++ version 3. security 4. decoding 5. encoding 6. color conversions 6.1. PNG color types 6.2. color conversions 6.3. padding bits 6.4. A note about 16-bits per channel and endianness 7. error values 8. chunks and PNG editing 9. compiler support 10. examples 10.1. decoder C++ example 10.2. decoder C example 11. state settings reference 12. changes 13. contact information 1. about -------- PNG is a file format to store raster images losslessly with good compression, supporting different color types and alpha channel. LodePNG is a PNG codec according to the Portable Network Graphics (PNG) Specification (Second Edition) - W3C Recommendation 10 November 2003. The specifications used are: *) Portable Network Graphics (PNG) Specification (Second Edition): http://www.w3.org/TR/2003/REC-PNG-20031110 *) RFC 1950 ZLIB Compressed Data Format version 3.3: http://www.gzip.org/zlib/rfc-zlib.html *) RFC 1951 DEFLATE Compressed Data Format Specification ver 1.3: http://www.gzip.org/zlib/rfc-deflate.html The most recent version of LodePNG can currently be found at http://lodev.org/lodepng/ LodePNG works both in C (ISO C90) and C++, with a C++ wrapper that adds extra functionality. LodePNG exists out of two files: -lodepng.h: the header file for both C and C++ -lodepng.c(pp): give it the name lodepng.c or lodepng.cpp (or .cc) depending on your usage If you want to start using LodePNG right away without reading this doc, get the examples from the LodePNG website to see how to use it in code, or check the smaller examples in chapter 13 here. LodePNG is simple but only supports the basic requirements. To achieve simplicity, the following design choices were made: There are no dependencies on any external library. There are functions to decode and encode a PNG with a single function call, and extended versions of these functions taking a LodePNGState struct allowing to specify or get more information. By default the colors of the raw image are always RGB or RGBA, no matter what color type the PNG file uses. To read and write files, there are simple functions to convert the files to/from buffers in memory. This all makes LodePNG suitable for loading textures in games, demos and small programs, ... It's less suitable for full fledged image editors, loading PNGs over network (it requires all the image data to be available before decoding can begin), life-critical systems, ... 1.1. supported features ----------------------- The following features are supported by the decoder: *) decoding of PNGs with any color type, bit depth and interlace mode, to a 24- or 32-bit color raw image, or the same color type as the PNG *) encoding of PNGs, from any raw image to 24- or 32-bit color, or the same color type as the raw image *) Adam7 interlace and deinterlace for any color type *) loading the image from harddisk or decoding it from a buffer from other sources than harddisk *) support for alpha channels, including RGBA color model, translucent palettes and color keying *) zlib decompression (inflate) *) zlib compression (deflate) *) CRC32 and ADLER32 checksums *) colorimetric color profile conversions: currently experimentally available in lodepng_util.cpp only, plus alternatively ability to pass on chroma/gamma/ICC profile information to other color management system. *) handling of unknown chunks, allowing making a PNG editor that stores custom and unknown chunks. *) the following chunks are supported by both encoder and decoder: IHDR: header information PLTE: color palette IDAT: pixel data IEND: the final chunk tRNS: transparency for palettized images tEXt: textual information zTXt: compressed textual information iTXt: international textual information bKGD: suggested background color pHYs: physical dimensions tIME: modification time cHRM: RGB chromaticities gAMA: RGB gamma correction iCCP: ICC color profile sRGB: rendering intent 1.2. features not supported --------------------------- The following features are _not_ supported: *) some features needed to make a conformant PNG-Editor might be still missing. *) partial loading/stream processing. All data must be available and is processed in one call. *) The following public chunks are not (yet) supported but treated as unknown chunks by LodePNG: sBIT hIST sPLT 2. C and C++ version -------------------- The C version uses buffers allocated with alloc that you need to free() yourself. You need to use init and cleanup functions for each struct whenever using a struct from the C version to avoid exploits and memory leaks. The C++ version has extra functions with std::vectors in the interface and the lodepng::State class which is a LodePNGState with constructor and destructor. These files work without modification for both C and C++ compilers because all the additional C++ code is in "#ifdef __cplusplus" blocks that make C-compilers ignore it, and the C code is made to compile both with strict ISO C90 and C++. To use the C++ version, you need to rename the source file to lodepng.cpp (instead of lodepng.c), and compile it with a C++ compiler. To use the C version, you need to rename the source file to lodepng.c (instead of lodepng.cpp), and compile it with a C compiler. 3. Security ----------- Even if carefully designed, it's always possible that LodePNG contains possible exploits. If you discover one, please let me know, and it will be fixed. When using LodePNG, care has to be taken with the C version of LodePNG, as well as the C-style structs when working with C++. The following conventions are used for all C-style structs: -if a struct has a corresponding init function, always call the init function when making a new one -if a struct has a corresponding cleanup function, call it before the struct disappears to avoid memory leaks -if a struct has a corresponding copy function, use the copy function instead of "=". The destination must also be inited already. 4. Decoding ----------- Decoding converts a PNG compressed image to a raw pixel buffer. Most documentation on using the decoder is at its declarations in the header above. For C, simple decoding can be done with functions such as lodepng_decode32, and more advanced decoding can be done with the struct LodePNGState and lodepng_decode. For C++, all decoding can be done with the various lodepng::decode functions, and lodepng::State can be used for advanced features. When using the LodePNGState, it uses the following fields for decoding: *) LodePNGInfo info_png: it stores extra information about the PNG (the input) in here *) LodePNGColorMode info_raw: here you can say what color mode of the raw image (the output) you want to get *) LodePNGDecoderSettings decoder: you can specify a few extra settings for the decoder to use LodePNGInfo info_png -------------------- After decoding, this contains extra information of the PNG image, except the actual pixels, width and height because these are already gotten directly from the decoder functions. It contains for example the original color type of the PNG image, text comments, suggested background color, etc... More details about the LodePNGInfo struct are at its declaration documentation. LodePNGColorMode info_raw ------------------------- When decoding, here you can specify which color type you want the resulting raw image to be. If this is different from the colortype of the PNG, then the decoder will automatically convert the result. This conversion always works, except if you want it to convert a color PNG to grayscale or to a palette with missing colors. By default, 32-bit color is used for the result. LodePNGDecoderSettings decoder ------------------------------ The settings can be used to ignore the errors created by invalid CRC and Adler32 chunks, and to disable the decoding of tEXt chunks. There's also a setting color_convert, true by default. If false, no conversion is done, the resulting data will be as it was in the PNG (after decompression) and you'll have to puzzle the colors of the pixels together yourself using the color type information in the LodePNGInfo. 5. Encoding ----------- Encoding converts a raw pixel buffer to a PNG compressed image. Most documentation on using the encoder is at its declarations in the header above. For C, simple encoding can be done with functions such as lodepng_encode32, and more advanced decoding can be done with the struct LodePNGState and lodepng_encode. For C++, all encoding can be done with the various lodepng::encode functions, and lodepng::State can be used for advanced features. Like the decoder, the encoder can also give errors. However it gives less errors since the encoder input is trusted, the decoder input (a PNG image that could be forged by anyone) is not trusted. When using the LodePNGState, it uses the following fields for encoding: *) LodePNGInfo info_png: here you specify how you want the PNG (the output) to be. *) LodePNGColorMode info_raw: here you say what color type of the raw image (the input) has *) LodePNGEncoderSettings encoder: you can specify a few settings for the encoder to use LodePNGInfo info_png -------------------- When encoding, you use this the opposite way as when decoding: for encoding, you fill in the values you want the PNG to have before encoding. By default it's not needed to specify a color type for the PNG since it's automatically chosen, but it's possible to choose it yourself given the right settings. The encoder will not always exactly match the LodePNGInfo struct you give, it tries as close as possible. Some things are ignored by the encoder. The encoder uses, for example, the following settings from it when applicable: colortype and bitdepth, text chunks, time chunk, the color key, the palette, the background color, the interlace method, unknown chunks, ... When encoding to a PNG with colortype 3, the encoder will generate a PLTE chunk. If the palette contains any colors for which the alpha channel is not 255 (so there are translucent colors in the palette), it'll add a tRNS chunk. LodePNGColorMode info_raw ------------------------- You specify the color type of the raw image that you give to the input here, including a possible transparent color key and palette you happen to be using in your raw image data. By default, 32-bit color is assumed, meaning your input has to be in RGBA format with 4 bytes (unsigned chars) per pixel. LodePNGEncoderSettings encoder ------------------------------ The following settings are supported (some are in sub-structs): *) auto_convert: when this option is enabled, the encoder will automatically choose the smallest possible color mode (including color key) that can encode the colors of all pixels without information loss. *) btype: the block type for LZ77. 0 = uncompressed, 1 = fixed huffman tree, 2 = dynamic huffman tree (best compression). Should be 2 for proper compression. *) use_lz77: whether or not to use LZ77 for compressed block types. Should be true for proper compression. *) windowsize: the window size used by the LZ77 encoder (1 - 32768). Has value 2048 by default, but can be set to 32768 for better, but slow, compression. *) force_palette: if colortype is 2 or 6, you can make the encoder write a PLTE chunk if force_palette is true. This can used as suggested palette to convert to by viewers that don't support more than 256 colors (if those still exist) *) add_id: add text chunk "Encoder: LodePNG <version>" to the image. *) text_compression: default 1. If 1, it'll store texts as zTXt instead of tEXt chunks. zTXt chunks use zlib compression on the text. This gives a smaller result on large texts but a larger result on small texts (such as a single program name). It's all tEXt or all zTXt though, there's no separate setting per text yet. 6. color conversions -------------------- An important thing to note about LodePNG, is that the color type of the PNG, and the color type of the raw image, are completely independent. By default, when you decode a PNG, you get the result as a raw image in the color type you want, no matter whether the PNG was encoded with a palette, grayscale or RGBA color. And if you encode an image, by default LodePNG will automatically choose the PNG color type that gives good compression based on the values of colors and amount of colors in the image. It can be configured to let you control it instead as well, though. To be able to do this, LodePNG does conversions from one color mode to another. It can convert from almost any color type to any other color type, except the following conversions: RGB to grayscale is not supported, and converting to a palette when the palette doesn't have a required color is not supported. This is not supported on purpose: this is information loss which requires a color reduction algorithm that is beyond the scope of a PNG encoder (yes, RGB to gray is easy, but there are multiple ways if you want to give some channels more weight). By default, when decoding, you get the raw image in 32-bit RGBA or 24-bit RGB color, no matter what color type the PNG has. And by default when encoding, LodePNG automatically picks the best color model for the output PNG, and expects the input image to be 32-bit RGBA or 24-bit RGB. So, unless you want to control the color format of the images yourself, you can skip this chapter. 6.1. PNG color types -------------------- A PNG image can have many color types, ranging from 1-bit color to 64-bit color, as well as palettized color modes. After the zlib decompression and unfiltering in the PNG image is done, the raw pixel data will have that color type and thus a certain amount of bits per pixel. If you want the output raw image after decoding to have another color type, a conversion is done by LodePNG. The PNG specification gives the following color types: 0: grayscale, bit depths 1, 2, 4, 8, 16 2: RGB, bit depths 8 and 16 3: palette, bit depths 1, 2, 4 and 8 4: grayscale with alpha, bit depths 8 and 16 6: RGBA, bit depths 8 and 16 Bit depth is the amount of bits per pixel per color channel. So the total amount of bits per pixel is: amount of channels * bitdepth. 6.2. color conversions ---------------------- As explained in the sections about the encoder and decoder, you can specify color types and bit depths in info_png and info_raw to change the default behaviour. If, when decoding, you want the raw image to be something else than the default, you need to set the color type and bit depth you want in the LodePNGColorMode, or the parameters colortype and bitdepth of the simple decoding function. If, when encoding, you use another color type than the default in the raw input image, you need to specify its color type and bit depth in the LodePNGColorMode of the raw image, or use the parameters colortype and bitdepth of the simple encoding function. If, when encoding, you don't want LodePNG to choose the output PNG color type but control it yourself, you need to set auto_convert in the encoder settings to false, and specify the color type you want in the LodePNGInfo of the encoder (including palette: it can generate a palette if auto_convert is true, otherwise not). If the input and output color type differ (whether user chosen or auto chosen), LodePNG will do a color conversion, which follows the rules below, and may sometimes result in an error. To avoid some confusion: -the decoder converts from PNG to raw image -the encoder converts from raw image to PNG -the colortype and bitdepth in LodePNGColorMode info_raw, are those of the raw image -the colortype and bitdepth in the color field of LodePNGInfo info_png, are those of the PNG -when encoding, the color type in LodePNGInfo is ignored if auto_convert is enabled, it is automatically generated instead -when decoding, the color type in LodePNGInfo is set by the decoder to that of the original PNG image, but it can be ignored since the raw image has the color type you requested instead -if the color type of the LodePNGColorMode and PNG image aren't the same, a conversion between the color types is done if the color types are supported. If it is not supported, an error is returned. If the types are the same, no conversion is done. -even though some conversions aren't supported, LodePNG supports loading PNGs from any colortype and saving PNGs to any colortype, sometimes it just requires preparing the raw image correctly before encoding. -both encoder and decoder use the same color converter. The function lodepng_convert does the color conversion. It is available in the interface but normally isn't needed since the encoder and decoder already call it. Non supported color conversions: -color to grayscale when non-gray pixels are present: no error is thrown, but the result will look ugly because only the red channel is taken (it assumes all three channels are the same in this case so ignores green and blue). The reason no error is given is to allow converting from three-channel grayscale images to one-channel even if there are numerical imprecisions. -anything to palette when the palette does not have an exact match for a from-color in it: in this case an error is thrown Supported color conversions: -anything to 8-bit RGB, 8-bit RGBA, 16-bit RGB, 16-bit RGBA -any gray or gray+alpha, to gray or gray+alpha -anything to a palette, as long as the palette has the requested colors in it -removing alpha channel -higher to smaller bitdepth, and vice versa If you want no color conversion to be done (e.g. for speed or control): -In the encoder, you can make it save a PNG with any color type by giving the raw color mode and LodePNGInfo the same color mode, and setting auto_convert to false. -In the decoder, you can make it store the pixel data in the same color type as the PNG has, by setting the color_convert setting to false. Settings in info_raw are then ignored. 6.3. padding bits ----------------- In the PNG file format, if a less than 8-bit per pixel color type is used and the scanlines have a bit amount that isn't a multiple of 8, then padding bits are used so that each scanline starts at a fresh byte. But that is NOT true for the LodePNG raw input and output. The raw input image you give to the encoder, and the raw output image you get from the decoder will NOT have these padding bits, e.g. in the case of a 1-bit image with a width of 7 pixels, the first pixel of the second scanline will the 8th bit of the first byte, not the first bit of a new byte. 6.4. A note about 16-bits per channel and endianness ---------------------------------------------------- LodePNG uses unsigned char arrays for 16-bit per channel colors too, just like for any other color format. The 16-bit values are stored in big endian (most significant byte first) in these arrays. This is the opposite order of the little endian used by x86 CPU's. LodePNG always uses big endian because the PNG file format does so internally. Conversions to other formats than PNG uses internally are not supported by LodePNG on purpose, there are myriads of formats, including endianness of 16-bit colors, the order in which you store R, G, B and A, and so on. Supporting and converting to/from all that is outside the scope of LodePNG. This may mean that, depending on your use case, you may want to convert the big endian output of LodePNG to little endian with a for loop. This is certainly not always needed, many applications and libraries support big endian 16-bit colors anyway, but it means you cannot simply cast the unsigned char* buffer to an unsigned short* buffer on x86 CPUs. 7. error values --------------- All functions in LodePNG that return an error code, return 0 if everything went OK, or a non-zero code if there was an error. The meaning of the LodePNG error values can be retrieved with the function lodepng_error_text: given the numerical error code, it returns a description of the error in English as a string. Check the implementation of lodepng_error_text to see the meaning of each code. 8. chunks and PNG editing ------------------------- If you want to add extra chunks to a PNG you encode, or use LodePNG for a PNG editor that should follow the rules about handling of unknown chunks, or if your program is able to read other types of chunks than the ones handled by LodePNG, then that's possible with the chunk functions of LodePNG. A PNG chunk has the following layout: 4 bytes length 4 bytes type name length bytes data 4 bytes CRC 8.1. iterating through chunks ----------------------------- If you have a buffer containing the PNG image data, then the first chunk (the IHDR chunk) starts at byte number 8 of that buffer. The first 8 bytes are the signature of the PNG and are not part of a chunk. But if you start at byte 8 then you have a chunk, and can check the following things of it. NOTE: none of these functions check for memory buffer boundaries. To avoid exploits, always make sure the buffer contains all the data of the chunks. When using lodepng_chunk_next, make sure the returned value is within the allocated memory. unsigned lodepng_chunk_length(const unsigned char* chunk): Get the length of the chunk's data. The total chunk length is this length + 12. void lodepng_chunk_type(char type[5], const unsigned char* chunk): unsigned char lodepng_chunk_type_equals(const unsigned char* chunk, const char* type): Get the type of the chunk or compare if it's a certain type unsigned char lodepng_chunk_critical(const unsigned char* chunk): unsigned char lodepng_chunk_private(const unsigned char* chunk): unsigned char lodepng_chunk_safetocopy(const unsigned char* chunk): Check if the chunk is critical in the PNG standard (only IHDR, PLTE, IDAT and IEND are). Check if the chunk is private (public chunks are part of the standard, private ones not). Check if the chunk is safe to copy. If it's not, then, when modifying data in a critical chunk, unsafe to copy chunks of the old image may NOT be saved in the new one if your program doesn't handle that type of unknown chunk. unsigned char* lodepng_chunk_data(unsigned char* chunk): const unsigned char* lodepng_chunk_data_const(const unsigned char* chunk): Get a pointer to the start of the data of the chunk. unsigned lodepng_chunk_check_crc(const unsigned char* chunk): void lodepng_chunk_generate_crc(unsigned char* chunk): Check if the crc is correct or generate a correct one. unsigned char* lodepng_chunk_next(unsigned char* chunk): const unsigned char* lodepng_chunk_next_const(const unsigned char* chunk): Iterate to the next chunk. This works if you have a buffer with consecutive chunks. Note that these functions do no boundary checking of the allocated data whatsoever, so make sure there is enough data available in the buffer to be able to go to the next chunk. unsigned lodepng_chunk_append(unsigned char** out, size_t* outsize, const unsigned char* chunk): unsigned lodepng_chunk_create(unsigned char** out, size_t* outsize, unsigned length, const char* type, const unsigned char* data): These functions are used to create new chunks that are appended to the data in *out that has length *outsize. The append function appends an existing chunk to the new data. The create function creates a new chunk with the given parameters and appends it. Type is the 4-letter name of the chunk. 8.2. chunks in info_png ----------------------- The LodePNGInfo struct contains fields with the unknown chunk in it. It has 3 buffers (each with size) to contain 3 types of unknown chunks: the ones that come before the PLTE chunk, the ones that come between the PLTE and the IDAT chunks, and the ones that come after the IDAT chunks. It's necessary to make the distinction between these 3 cases because the PNG standard forces to keep the ordering of unknown chunks compared to the critical chunks, but does not force any other ordering rules. info_png.unknown_chunks_data[0] is the chunks before PLTE info_png.unknown_chunks_data[1] is the chunks after PLTE, before IDAT info_png.unknown_chunks_data[2] is the chunks after IDAT The chunks in these 3 buffers can be iterated through and read by using the same way described in the previous subchapter. When using the decoder to decode a PNG, you can make it store all unknown chunks if you set the option settings.remember_unknown_chunks to 1. By default, this option is off (0). The encoder will always encode unknown chunks that are stored in the info_png. If you need it to add a particular chunk that isn't known by LodePNG, you can use lodepng_chunk_append or lodepng_chunk_create to the chunk data in info_png.unknown_chunks_data[x]. Chunks that are known by LodePNG should not be added in that way. E.g. to make LodePNG add a bKGD chunk, set background_defined to true and add the correct parameters there instead. 9. compiler support ------------------- No libraries other than the current standard C library are needed to compile LodePNG. For the C++ version, only the standard C++ library is needed on top. Add the files lodepng.c(pp) and lodepng.h to your project, include lodepng.h where needed, and your program can read/write PNG files. It is compatible with C90 and up, and C++03 and up. If performance is important, use optimization when compiling! For both the encoder and decoder, this makes a large difference. Make sure that LodePNG is compiled with the same compiler of the same version and with the same settings as the rest of the program, or the interfaces with std::vectors and std::strings in C++ can be incompatible. CHAR_BITS must be 8 or higher, because LodePNG uses unsigned chars for octets. *) gcc and g++ LodePNG is developed in gcc so this compiler is natively supported. It gives no warnings with compiler options "-Wall -Wextra -pedantic -ansi", with gcc and g++ version 4.7.1 on Linux, 32-bit and 64-bit. *) Clang Fully supported and warning-free. *) Mingw The Mingw compiler (a port of gcc for Windows) should be fully supported by LodePNG. *) Visual Studio and Visual C++ Express Edition LodePNG should be warning-free with warning level W4. Two warnings were disabled with pragmas though: warning 4244 about implicit conversions, and warning 4996 where it wants to use a non-standard function fopen_s instead of the standard C fopen. Visual Studio may want "stdafx.h" files to be included in each source file and give an error "unexpected end of file while looking for precompiled header". This is not standard C++ and will not be added to the stock LodePNG. You can disable it for lodepng.cpp only by right clicking it, Properties, C/C++, Precompiled Headers, and set it to Not Using Precompiled Headers there. NOTE: Modern versions of VS should be fully supported, but old versions, e.g. VS6, are not guaranteed to work. *) Compilers on Macintosh LodePNG has been reported to work both with gcc and LLVM for Macintosh, both for C and C++. *) Other Compilers If you encounter problems on any compilers, feel free to let me know and I may try to fix it if the compiler is modern and standards compliant. 10. examples ------------ This decoder example shows the most basic usage of LodePNG. More complex examples can be found on the LodePNG website. 10.1. decoder C++ example ------------------------- #include "lodepng.h" #include <iostream> int main(int argc, char *argv[]) { const char* filename = argc > 1 ? argv[1] : "test.png"; //load and decode std::vector<unsigned char> image; unsigned width, height; unsigned error = lodepng::decode(image, width, height, filename); //if there's an error, display it if(error) std::cout << "decoder error " << error << ": " << lodepng_error_text(error) << std::endl; //the pixels are now in the vector "image", 4 bytes per pixel, ordered RGBARGBA..., use it as texture, draw it, ... } 10.2. decoder C example ----------------------- #include "lodepng.h" int main(int argc, char *argv[]) { unsigned error; unsigned char* image; size_t width, height; const char* filename = argc > 1 ? argv[1] : "test.png"; error = lodepng_decode32_file(&image, &width, &height, filename); if(error) printf("decoder error %u: %s\n", error, lodepng_error_text(error)); / * use image here * / free(image); return 0; } 11. state settings reference ---------------------------- A quick reference of some settings to set on the LodePNGState For decoding: state.decoder.zlibsettings.ignore_adler32: ignore ADLER32 checksums state.decoder.zlibsettings.custom_...: use custom inflate function state.decoder.ignore_crc: ignore CRC checksums state.decoder.ignore_critical: ignore unknown critical chunks state.decoder.ignore_end: ignore missing IEND chunk. May fail if this corruption causes other errors state.decoder.color_convert: convert internal PNG color to chosen one state.decoder.read_text_chunks: whether to read in text metadata chunks state.decoder.remember_unknown_chunks: whether to read in unknown chunks state.info_raw.colortype: desired color type for decoded image state.info_raw.bitdepth: desired bit depth for decoded image state.info_raw....: more color settings, see struct LodePNGColorMode state.info_png....: no settings for decoder but ouput, see struct LodePNGInfo For encoding: state.encoder.zlibsettings.btype: disable compression by setting it to 0 state.encoder.zlibsettings.use_lz77: use LZ77 in compression state.encoder.zlibsettings.windowsize: tweak LZ77 windowsize state.encoder.zlibsettings.minmatch: tweak min LZ77 length to match state.encoder.zlibsettings.nicematch: tweak LZ77 match where to stop searching state.encoder.zlibsettings.lazymatching: try one more LZ77 matching state.encoder.zlibsettings.custom_...: use custom deflate function state.encoder.auto_convert: choose optimal PNG color type, if 0 uses info_png state.encoder.filter_palette_zero: PNG filter strategy for palette state.encoder.filter_strategy: PNG filter strategy to encode with state.encoder.force_palette: add palette even if not encoding to one state.encoder.add_id: add LodePNG identifier and version as a text chunk state.encoder.text_compression: use compressed text chunks for metadata state.info_raw.colortype: color type of raw input image you provide state.info_raw.bitdepth: bit depth of raw input image you provide state.info_raw: more color settings, see struct LodePNGColorMode state.info_png.color.colortype: desired color type if auto_convert is false state.info_png.color.bitdepth: desired bit depth if auto_convert is false state.info_png.color....: more color settings, see struct LodePNGColorMode state.info_png....: more PNG related settings, see struct LodePNGInfo 12. changes ----------- The version number of LodePNG is the date of the change given in the format yyyymmdd. Some changes aren't backwards compatible. Those are indicated with a (!) symbol. Not all changes are listed here, the commit history in github lists more: https://github.com/lvandeve/lodepng *) 06 mar 2020: simplified some of the dynamic memory allocations. *) 12 jan 2020: (!) added 'end' argument to lodepng_chunk_next to allow correct overflow checks. *) 14 aug 2019: around 25% faster decoding thanks to huffman lookup tables. *) 15 jun 2019: (!) auto_choose_color API changed (for bugfix: don't use palette if gray ICC profile) and non-ICC LodePNGColorProfile renamed to LodePNGColorStats. *) 30 dec 2018: code style changes only: removed newlines before opening braces. *) 10 sep 2018: added way to inspect metadata chunks without full decoding. *) 19 aug 2018: (!) fixed color mode bKGD is encoded with and made it use palette index in case of palette. *) 10 aug 2018: (!) added support for gAMA, cHRM, sRGB and iCCP chunks. This change is backwards compatible unless you relied on unknown_chunks for those. *) 11 jun 2018: less restrictive check for pixel size integer overflow *) 14 jan 2018: allow optionally ignoring a few more recoverable errors *) 17 sep 2017: fix memory leak for some encoder input error cases *) 27 nov 2016: grey+alpha auto color model detection bugfix *) 18 apr 2016: Changed qsort to custom stable sort (for platforms w/o qsort). *) 09 apr 2016: Fixed colorkey usage detection, and better file loading (within the limits of pure C90). *) 08 dec 2015: Made load_file function return error if file can't be opened. *) 24 okt 2015: Bugfix with decoding to palette output. *) 18 apr 2015: Boundary PM instead of just package-merge for faster encoding. *) 24 aug 2014: Moved to github *) 23 aug 2014: Reduced needless memory usage of decoder. *) 28 jun 2014: Removed fix_png setting, always support palette OOB for simplicity. Made ColorProfile public. *) 09 jun 2014: Faster encoder by fixing hash bug and more zeros optimization. *) 22 dec 2013: Power of two windowsize required for optimization. *) 15 apr 2013: Fixed bug with LAC_ALPHA and color key. *) 25 mar 2013: Added an optional feature to ignore some PNG errors (fix_png). *) 11 mar 2013: (!) Bugfix with custom free. Changed from "my" to "lodepng_" prefix for the custom allocators and made it possible with a new #define to use custom ones in your project without needing to change lodepng's code. *) 28 jan 2013: Bugfix with color key. *) 27 okt 2012: Tweaks in text chunk keyword length error handling. *) 8 okt 2012: (!) Added new filter strategy (entropy) and new auto color mode. (no palette). Better deflate tree encoding. New compression tweak settings. Faster color conversions while decoding. Some internal cleanups. *) 23 sep 2012: Reduced warnings in Visual Studio a little bit. *) 1 sep 2012: (!) Removed #define's for giving custom (de)compression functions and made it work with function pointers instead. *) 23 jun 2012: Added more filter strategies. Made it easier to use custom alloc and free functions and toggle #defines from compiler flags. Small fixes. *) 6 may 2012: (!) Made plugging in custom zlib/deflate functions more flexible. *) 22 apr 2012: (!) Made interface more consistent, renaming a lot. Removed redundant C++ codec classes. Reduced amount of structs. Everything changed, but it is cleaner now imho and functionality remains the same. Also fixed several bugs and shrunk the implementation code. Made new samples. *) 6 nov 2011: (!) By default, the encoder now automatically chooses the best PNG color model and bit depth, based on the amount and type of colors of the raw image. For this, autoLeaveOutAlphaChannel replaced by auto_choose_color. *) 9 okt 2011: simpler hash chain implementation for the encoder. *) 8 sep 2011: lz77 encoder lazy matching instead of greedy matching. *) 23 aug 2011: tweaked the zlib compression parameters after benchmarking. A bug with the PNG filtertype heuristic was fixed, so that it chooses much better ones (it's quite significant). A setting to do an experimental, slow, brute force search for PNG filter types is added. *) 17 aug 2011: (!) changed some C zlib related function names. *) 16 aug 2011: made the code less wide (max 120 characters per line). *) 17 apr 2011: code cleanup. Bugfixes. Convert low to 16-bit per sample colors. *) 21 feb 2011: fixed compiling for C90. Fixed compiling with sections disabled. *) 11 dec 2010: encoding is made faster, based on suggestion by Peter Eastman to optimize long sequences of zeros. *) 13 nov 2010: added LodePNG_InfoColor_hasPaletteAlpha and LodePNG_InfoColor_canHaveAlpha functions for convenience. *) 7 nov 2010: added LodePNG_error_text function to get error code description. *) 30 okt 2010: made decoding slightly faster *) 26 okt 2010: (!) changed some C function and struct names (more consistent). Reorganized the documentation and the declaration order in the header. *) 08 aug 2010: only changed some comments and external samples. *) 05 jul 2010: fixed bug thanks to warnings in the new gcc version. *) 14 mar 2010: fixed bug where too much memory was allocated for char buffers. *) 02 sep 2008: fixed bug where it could create empty tree that linux apps could read by ignoring the problem but windows apps couldn't. *) 06 jun 2008: added more error checks for out of memory cases. *) 26 apr 2008: added a few more checks here and there to ensure more safety. *) 06 mar 2008: crash with encoding of strings fixed *) 02 feb 2008: support for international text chunks added (iTXt) *) 23 jan 2008: small cleanups, and #defines to divide code in sections *) 20 jan 2008: support for unknown chunks allowing using LodePNG for an editor. *) 18 jan 2008: support for tIME and pHYs chunks added to encoder and decoder. *) 17 jan 2008: ability to encode and decode compressed zTXt chunks added Also various fixes, such as in the deflate and the padding bits code. *) 13 jan 2008: Added ability to encode Adam7-interlaced images. Improved filtering code of encoder. *) 07 jan 2008: (!) changed LodePNG to use ISO C90 instead of C++. A C++ wrapper around this provides an interface almost identical to before. Having LodePNG be pure ISO C90 makes it more portable. The C and C++ code are together in these files but it works both for C and C++ compilers. *) 29 dec 2007: (!) changed most integer types to unsigned int + other tweaks *) 30 aug 2007: bug fixed which makes this Borland C++ compatible *) 09 aug 2007: some VS2005 warnings removed again *) 21 jul 2007: deflate code placed in new namespace separate from zlib code *) 08 jun 2007: fixed bug with 2- and 4-bit color, and small interlaced images *) 04 jun 2007: improved support for Visual Studio 2005: crash with accessing invalid std::vector element [0] fixed, and level 3 and 4 warnings removed *) 02 jun 2007: made the encoder add a tag with version by default *) 27 may 2007: zlib and png code separated (but still in the same file), simple encoder/decoder functions added for more simple usage cases *) 19 may 2007: minor fixes, some code cleaning, new error added (error 69), moved some examples from here to lodepng_examples.cpp *) 12 may 2007: palette decoding bug fixed *) 24 apr 2007: changed the license from BSD to the zlib license *) 11 mar 2007: very simple addition: ability to encode bKGD chunks. *) 04 mar 2007: (!) tEXt chunk related fixes, and support for encoding palettized PNG images. Plus little interface change with palette and texts. *) 03 mar 2007: Made it encode dynamic Huffman shorter with repeat codes. Fixed a bug where the end code of a block had length 0 in the Huffman tree. *) 26 feb 2007: Huffman compression with dynamic trees (BTYPE 2) now implemented and supported by the encoder, resulting in smaller PNGs at the output. *) 27 jan 2007: Made the Adler-32 test faster so that a timewaste is gone. *) 24 jan 2007: gave encoder an error interface. Added color conversion from any greyscale type to 8-bit greyscale with or without alpha. *) 21 jan 2007: (!) Totally changed the interface. It allows more color types to convert to and is more uniform. See the manual for how it works now. *) 07 jan 2007: Some cleanup & fixes, and a few changes over the last days: encode/decode custom tEXt chunks, separate classes for zlib & deflate, and at last made the decoder give errors for incorrect Adler32 or Crc. *) 01 jan 2007: Fixed bug with encoding PNGs with less than 8 bits per channel. *) 29 dec 2006: Added support for encoding images without alpha channel, and cleaned out code as well as making certain parts faster. *) 28 dec 2006: Added "Settings" to the encoder. *) 26 dec 2006: The encoder now does LZ77 encoding and produces much smaller files now. Removed some code duplication in the decoder. Fixed little bug in an example. *) 09 dec 2006: (!) Placed output parameters of public functions as first parameter. Fixed a bug of the decoder with 16-bit per color. *) 15 okt 2006: Changed documentation structure *) 09 okt 2006: Encoder class added. It encodes a valid PNG image from the given image buffer, however for now it's not compressed. *) 08 sep 2006: (!) Changed to interface with a Decoder class *) 30 jul 2006: (!) LodePNG_InfoPng , width and height are now retrieved in different way. Renamed decodePNG to decodePNGGeneric. *) 29 jul 2006: (!) Changed the interface: image info is now returned as a struct of type LodePNG::LodePNG_Info, instead of a vector, which was a bit clumsy. *) 28 jul 2006: Cleaned the code and added new error checks. Corrected terminology "deflate" into "inflate". *) 23 jun 2006: Added SDL example in the documentation in the header, this example allows easy debugging by displaying the PNG and its transparency. *) 22 jun 2006: (!) Changed way to obtain error value. Added loadFile function for convenience. Made decodePNG32 faster. *) 21 jun 2006: (!) Changed type of info vector to unsigned. Changed position of palette in info vector. Fixed an important bug that happened on PNGs with an uncompressed block. *) 16 jun 2006: Internally changed unsigned into unsigned where needed, and performed some optimizations. *) 07 jun 2006: (!) Renamed functions to decodePNG and placed them in LodePNG namespace. Changed the order of the parameters. Rewrote the documentation in the header. Renamed files to lodepng.cpp and lodepng.h *) 22 apr 2006: Optimized and improved some code *) 07 sep 2005: (!) Changed to std::vector interface *) 12 aug 2005: Initial release (C++, decoder only) 13. contact information ----------------------- Feel free to contact me with suggestions, problems, comments, ... concerning LodePNG. If you encounter a PNG image that doesn't work properly with this decoder, feel free to send it and I'll use it to find and fix the problem. My email address is (puzzle the account and domain together with an @ symbol): Domain: gmail dot com. Account: lode dot vandevenne. Copyright (c) 2005-2020 Lode Vandevenne */
48.084156
136
0.75276
Eisenwave
4c64e7e41edd0448714ab80a001590deabd9bfc8
21,132
cpp
C++
sundog_engine/various/palmos/palm_functions.cpp
Sound-Linux-More/sunvox
7376fbe9f9bca92be1e17aefaac2e68b558d8357
[ "BSD-3-Clause" ]
100
2016-01-15T02:43:07.000Z
2022-03-16T14:02:38.000Z
sundog_engine/various/palmos/palm_functions.cpp
Sound-Linux-More/sunvox
7376fbe9f9bca92be1e17aefaac2e68b558d8357
[ "BSD-3-Clause" ]
2
2018-01-10T18:21:37.000Z
2021-12-05T01:48:08.000Z
sundog_engine/various/palmos/palm_functions.cpp
Sound-Linux-More/sunvox
7376fbe9f9bca92be1e17aefaac2e68b558d8357
[ "BSD-3-Clause" ]
17
2016-05-16T19:48:19.000Z
2022-03-23T10:59:42.000Z
#include <PalmOS.h> #include "VFSMgr.h" #include "PceNativeCall.h" #include "palm_functions.h" // local definition of the emulation state structure void *g_form_handler; long *g_new_screen_size; EmulStateType *emulStatePtr; Call68KFuncType *call68KFuncPtr; unsigned char args_stack[ 4 * 32 ]; unsigned char args_ptr = 0; // ================= // PalmOS functions: // ================= Char *StrCat( Char *dst, const Char *src ) { CALL P4(dst) P4(src) return (Char*)TRAPP(sysTrapStrCat) } UInt16 StrLen( const Char *src ) { CALL P4(src) return (UInt16)TRAP(sysTrapStrLen) } Int16 StrCompare( const Char *s1, const Char *s2 ) { CALL P4(s1) P4(s2) return (UInt16)TRAP(sysTrapStrCompare) } Err MemSemaphoreReserve( Boolean writeAccess ) { CALL P1(writeAccess) return (Err)TRAP(sysTrapMemSemaphoreReserve) } Err MemSemaphoreRelease( Boolean writeAccess ) { CALL P1(writeAccess) return (Err)TRAP(sysTrapMemSemaphoreRelease) } UInt16 MemHeapID( UInt16 cardNo, UInt16 heapIndex ) { CALL P2(cardNo) P2(heapIndex) return (UInt16)TRAP(sysTrapMemHeapID) } Err MemMove( void *dstP, const void *sP, Int32 numBytes ) { CALL P4(dstP) P4(sP) P4(numBytes) return (Err)TRAP(sysTrapMemMove) } Err MemSet( void *dstP, Int32 numBytes, UInt8 value ) { CALL P4(dstP) P4(numBytes) P1(value) return (Err)TRAP(sysTrapMemSet) } Int16 MemCmp ( const void* s1, const void* s2, Int32 numBytes ) { CALL P4(s1) P4(s2) P4(numBytes) return (Int16)TRAP(sysTrapMemCmp) } Err MemChunkFree( MemPtr chunkDataP ) { CALL P4(chunkDataP) return (Err)TRAP(sysTrapMemChunkFree) } MemPtr MemChunkNew( UInt16 heapID, UInt32 size, UInt16 attr ) { CALL P2(heapID) P4(size) P2(attr) return (MemPtr)TRAPP(sysTrapMemChunkNew) } MemHandle MemHandleNew( UInt32 size ) { CALL P4(size) return (MemHandle)TRAPP(sysTrapMemHandleNew) } Err MemHandleFree( MemHandle h ) { CALL P4(h) return (Err)TRAP(sysTrapMemHandleFree) } UInt16 MemHandleLockCount( MemHandle h ) { CALL P4(h) return (UInt16)TRAP(sysTrapMemHandleLockCount) } MemPtr MemHandleLock( MemHandle h ) { CALL P4(h) return (MemPtr)TRAPP(sysTrapMemHandleLock) } Err MemHandleUnlock( MemHandle h ) { CALL P4(h) return (Err)TRAP(sysTrapMemHandleUnlock) } UInt32 MemHandleSize( MemHandle h ) { CALL P4(h) return (UInt32)TRAP(sysTrapMemHandleSize) } MemPtr MemPtrNew( UInt32 size ) { CALL P4(size) return (MemPtr)TRAPP(sysTrapMemPtrNew) } UInt16 MemPtrHeapID( MemPtr p ) { CALL P4(p) return (UInt16)TRAP(sysTrapMemPtrHeapID) } // ================= // VFS : // ================= Err VFSVolumeEnumerate( UInt16 *volRefNumP, UInt32 *volIteratorP ) { *volIteratorP = BSwap32( *volIteratorP ); // <-> CALL P4(volRefNumP) P4(volIteratorP) emulStatePtr->regData[2] = vfsTrapVolumeEnumerate; Err retval = (Err)TRAP(0xA348 & (0x00000FFF)) if( volIteratorP ) *volIteratorP = BSwap32( *volIteratorP ); // <-> if( volRefNumP ) *volRefNumP = BSwap16( *volRefNumP ); // <- return retval; } Err VFSFileOpen( UInt16 volRefNum, const Char *pathNameP,UInt16 openMode, FileRef *fileRefP ) { CALL P2(volRefNum) P4(pathNameP) P2(openMode) P4(fileRefP) emulStatePtr->regData[2] = vfsTrapFileOpen; Err retval = (Err)TRAP(0xA348 & (0x00000FFF)) if( fileRefP ) *fileRefP = (FileRef)BSwap32( *fileRefP ); // <- return retval; } Err VFSFileClose( FileRef fileRef ) { CALL P4(fileRef) emulStatePtr->regData[2] = vfsTrapFileClose; return (Err)TRAP(0xA348 & (0x00000FFF)) } Err VFSFileCreate( UInt16 volRefNum, const Char *pathNameP ) { CALL P2(volRefNum) P4(pathNameP) emulStatePtr->regData[2] = vfsTrapFileCreate; return (Err)TRAP(0xA348 & (0x00000FFF)) } Err VFSFileReadData( FileRef fileRef, UInt32 numBytes, void *bufBaseP, UInt32 offset, UInt32 *numBytesReadP ) { CALL P4(fileRef) P4(numBytes) P4(bufBaseP) P4(offset) P4(numBytesReadP) emulStatePtr->regData[2] = vfsTrapFileReadData; Err retval = (Err)TRAP(0xA348 & (0x00000FFF)) if( numBytesReadP ) *numBytesReadP = BSwap32( *numBytesReadP ); // <- return retval; } Err VFSFileRead( FileRef fileRef, UInt32 numBytes, void *bufP, UInt32 *numBytesReadP ) { CALL P4(fileRef) P4(numBytes) P4(bufP) P4(numBytesReadP) emulStatePtr->regData[2] = vfsTrapFileRead; Err retval = (Err)TRAP(0xA348 & (0x00000FFF)) if( numBytesReadP ) *numBytesReadP = BSwap32( *numBytesReadP ); // <- return retval; } Err VFSFileWrite( FileRef fileRef, UInt32 numBytes, const void *dataP, UInt32 *numBytesWrittenP ) { CALL P4(fileRef) P4(numBytes) P4(dataP) P4(numBytesWrittenP) emulStatePtr->regData[2] = vfsTrapFileWrite; Err retval = (Err)TRAP(0xA348 & (0x00000FFF)) if( numBytesWrittenP ) *numBytesWrittenP = BSwap32( *numBytesWrittenP ); // <- return retval; } Err VFSFileDelete( UInt16 volRefNum, const Char *pathNameP ) { CALL P2(volRefNum) P4(pathNameP) emulStatePtr->regData[2] = vfsTrapFileDelete; return (Err)TRAP(0xA348 & (0x00000FFF)) } Err VFSFileRename( UInt16 volRefNum, const Char *pathNameP, const Char *newNameP ) { CALL P2(volRefNum) P4(pathNameP) P4(newNameP) emulStatePtr->regData[2] = vfsTrapFileRename; return (Err)TRAP(0xA348 & (0x00000FFF)) } Err VFSFileSeek( FileRef fileRef, FileOrigin origin, Int32 offset ) { CALL P4(fileRef) P2(origin) P4(offset) emulStatePtr->regData[2] = vfsTrapFileSeek; return (Err)TRAP(0xA348 & (0x00000FFF)) } Err VFSFileEOF( FileRef fileRef ) { CALL P4(fileRef) emulStatePtr->regData[2] = vfsTrapFileEOF; return (Err)TRAP(0xA348 & (0x00000FFF)) } Err VFSFileTell( FileRef fileRef, UInt32 *filePosP ) { CALL P4(fileRef) P4(filePosP) emulStatePtr->regData[2] = vfsTrapFileTell; Err retval = (Err)TRAP(0xA348 & (0x00000FFF)) if( filePosP ) *filePosP = BSwap32( *filePosP ); // <- return retval; } Err VFSFileSize( FileRef fileRef, UInt32 *fileSizeP ) { CALL P4(fileRef) P4(fileSizeP) emulStatePtr->regData[2] = vfsTrapFileSize; Err retval = (Err)TRAP(0xA348 & (0x00000FFF)) if( fileSizeP ) *fileSizeP = BSwap32( *fileSizeP ); // <- return retval; } Err VFSDirEntryEnumerate( FileRef dirRef, UInt32 *dirEntryIteratorP, FileInfoType *infoP ) { *dirEntryIteratorP = BSwap32( *dirEntryIteratorP ); // <-> infoP->attributes = BSwap32( infoP->attributes ); // <-> infoP->nameP = (Char*)BSwap32( infoP->nameP ); // <-> infoP->nameBufLen = BSwap16( infoP->nameBufLen ); // <-> CALL P4(dirRef) P4(dirEntryIteratorP) P4(infoP) emulStatePtr->regData[2] = vfsTrapDirEntryEnumerate; Err retval = (Err)TRAP(0xA348 & (0x00000FFF)) *dirEntryIteratorP = BSwap32( *dirEntryIteratorP ); // <-> infoP->attributes = BSwap32( infoP->attributes ); // <-> infoP->nameP = (Char*)BSwap32( infoP->nameP ); // <-> infoP->nameBufLen = BSwap16( infoP->nameBufLen ); // <-> return retval; } // ================= // DATABASES : // ================= Err DmDatabaseInfo( UInt16 cardNo, LocalID dbID, Char *nameP, UInt16 *attributesP, UInt16 *versionP, UInt32 *crDateP, UInt32 * modDateP, UInt32 *bckUpDateP, UInt32 * modNumP, LocalID *appInfoIDP, LocalID *sortInfoIDP, UInt32 *typeP, UInt32 *creatorP ) { CALL P2(cardNo) P4(dbID) P4(nameP) P4(attributesP) P4(versionP) P4(crDateP) P4(modDateP) P4(bckUpDateP) P4(modNumP) P4(appInfoIDP) P4(sortInfoIDP) P4(typeP) P4(creatorP) Err retval = (Err)TRAP(sysTrapDmDatabaseInfo) if( attributesP ) *attributesP = BSwap16( *attributesP ); if( versionP ) *versionP = BSwap16( *versionP ); if( crDateP ) *crDateP = BSwap32( *crDateP ); if( modNumP ) *modNumP = BSwap32( *modNumP ); if( appInfoIDP ) *appInfoIDP = (LocalID)BSwap32( *appInfoIDP ); if( sortInfoIDP ) *sortInfoIDP = (LocalID)BSwap32( *sortInfoIDP ); if( typeP ) *typeP = BSwap32( *typeP ); if( creatorP ) *creatorP = BSwap32( *creatorP ); return retval; } MemHandle DmGetResource( DmResType type, DmResID resID ) { CALL P4(type) P2(resID) return (MemHandle)TRAPP(sysTrapDmGetResource) } Err DmRecordInfo( DmOpenRef dbP, UInt16 index, UInt16 *attrP, UInt32 *uniqueIDP, LocalID *chunkIDP ) { CALL P4(dbP) P2(index) P4(attrP) P4(uniqueIDP) P4(chunkIDP) Err retval = (Err)TRAP(sysTrapDmRecordInfo) if( attrP ) *attrP = BSwap16( *attrP ); // <- if( uniqueIDP ) *uniqueIDP = BSwap32( *uniqueIDP ); // <- if( chunkIDP ) *chunkIDP = (LocalID)BSwap32( *chunkIDP ); // <- return retval; } DmOpenRef DmOpenDatabase( UInt16 cardNo, LocalID dbID, UInt16 mode ) { CALL P2(cardNo) P4(dbID) P2(mode) return (DmOpenRef)TRAPP(sysTrapDmOpenDatabase) } Err DmCreateDatabase( UInt16 cardNo, const Char *nameP, UInt32 creator, UInt32 type, Boolean resDB ) { CALL P2(cardNo) P4(nameP) P4(creator) P4(type) P1(resDB) return (Err)TRAP(sysTrapDmCreateDatabase) } Err DmDeleteDatabase( UInt16 cardNo, LocalID dbID ) { CALL P2(cardNo) P4(dbID) return (Err)TRAP(sysTrapDmDeleteDatabase) } LocalID DmFindDatabase( UInt16 cardNo, const Char *nameP ) { CALL P2(cardNo) P4(nameP) return (LocalID)TRAP(sysTrapDmFindDatabase) } Err DmGetNextDatabaseByTypeCreator( Boolean newSearch, DmSearchStatePtr stateInfoP, UInt32 type, UInt32 creator, Boolean onlyLatestVers, UInt16 *cardNoP, LocalID *dbIDP ) { CALL P1(newSearch) P4(stateInfoP) P4(type) P4(creator) P1(onlyLatestVers) P4(cardNoP) P4(dbIDP) Err retval = (Err)TRAP(sysTrapDmGetNextDatabaseByTypeCreator) if( cardNoP ) *cardNoP = BSwap16( *cardNoP ); // <- if( dbIDP ) *dbIDP = (LocalID)BSwap32( *dbIDP ); // <- return retval; } Err DmCloseDatabase( DmOpenRef dbP ) { CALL P4(dbP) return (Err)TRAP(sysTrapDmCloseDatabase) } UInt16 DmNumRecords( DmOpenRef dbP ) { CALL P4(dbP) return (UInt16)TRAP(sysTrapDmNumRecords) } MemHandle DmNewRecord( DmOpenRef dbP, UInt16 *atP, UInt32 size ) { *atP = BSwap16( *atP ); // <-> CALL P4(dbP) P4(atP) P4(size) MemHandle retval = (MemHandle)TRAPP(sysTrapDmNewRecord) *atP = BSwap16( *atP ); // <-> return retval; } MemHandle DmGetRecord( DmOpenRef dbP, UInt16 index ) { CALL P4(dbP) P2(index) return (MemHandle)TRAPP(sysTrapDmGetRecord) } MemHandle DmResizeRecord( DmOpenRef dbP, UInt16 index, UInt32 newSize ) { CALL P4(dbP) P2(index) P4(newSize) return (MemHandle)TRAPP(sysTrapDmResizeRecord) } Err DmReleaseRecord( DmOpenRef dbP, UInt16 index, Boolean dirty ) { CALL P4(dbP) P2(index) P1(dirty) return (Err)TRAP(sysTrapDmReleaseRecord) } Err DmWrite( void *recordP, UInt32 offset, const void *srcP, UInt32 bytes ) { CALL P4(recordP) P4(offset) P4(srcP) P4(bytes) return (Err)TRAP(sysTrapDmWrite) } Err DmWriteCheck( void *recordP, UInt32 offset, UInt32 bytes ) { CALL P4(recordP) P4(offset) P4(bytes) return (Err)TRAP(sysTrapDmWriteCheck) } // ================= // SOUND : // ================= Err SndStreamCreate( SndStreamRef *channel, SndStreamMode mode, UInt32 samplerate, SndSampleType type, SndStreamWidth width, SndStreamBufferCallback func, void *userdata, UInt32 buffsize, Boolean armNative ) { CALL P4(channel) P1(mode) P4(samplerate) P2(type) P1(width) P4(func) P4(userdata) P4(buffsize) P1(armNative) Err retval = (Err)TRAP(sysTrapSndStreamCreate) *channel = (SndStreamRef)BSwap32( *channel ); // <- return retval; } Err SndStreamDelete( SndStreamRef channel ) { CALL P4(channel) return (Err)TRAP(sysTrapSndStreamDelete) } Err SndStreamStart( SndStreamRef channel ) { CALL P4(channel) return (Err)TRAP(sysTrapSndStreamStart) } Err SndStreamPause( SndStreamRef channel, Boolean pause ) { CALL P4(channel) P1(pause) return (Err)TRAP(sysTrapSndStreamPause) } Err SndStreamStop( SndStreamRef channel ) { CALL P4(channel) return (Err)TRAP(sysTrapSndStreamStop) } Err SndStreamSetVolume( SndStreamRef channel, Int32 volume ) { CALL P4(channel) P4(volume) return (Err)TRAP(sysTrapSndStreamSetVolume) } // WINDOWS : void WinDrawChars( const Char *chars, Int16 len, Coord x, Coord y ) { CALL P4(chars) P2(len) P2(x) P2(y) TRAP(sysTrapWinDrawChars) } WinHandle WinGetDisplayWindow( void ) { CALL return (WinHandle)TRAPP(sysTrapWinGetDisplayWindow) } BitmapType *WinGetBitmap( WinHandle winHandle ) { CALL P4(winHandle) return (BitmapType*)TRAPP(sysTrapWinGetBitmap); } void WinGetBounds( WinHandle winH, RectangleType *rP ) { CALL P4(winH) P4(rP) TRAP(sysTrapWinGetBounds) rP->topLeft.x = BSwap16( rP->topLeft.x ); // <- rP->topLeft.y = BSwap16( rP->topLeft.y ); // <- rP->extent.x = BSwap16( rP->extent.x ); // <- rP->extent.y = BSwap16( rP->extent.y ); // <- } void WinSetBounds( WinHandle winHandle, const RectangleType *rP ) { RectangleType *r = (RectangleType*)rP; r->topLeft.x = BSwap16( r->topLeft.x ); // -> r->topLeft.y = BSwap16( r->topLeft.y ); // -> r->extent.x = BSwap16( r->extent.x ); // -> r->extent.y = BSwap16( r->extent.y ); // -> CALL P4(winHandle) P4(rP) TRAP(sysTrapWinSetBounds) } void WinSetClip( const RectangleType *rP ) { RectangleType *r = (RectangleType*)rP; r->topLeft.x = BSwap16( r->topLeft.x ); // -> r->topLeft.y = BSwap16( r->topLeft.y ); // -> r->extent.x = BSwap16( r->extent.x ); // -> r->extent.y = BSwap16( r->extent.y ); // -> CALL P4(rP) TRAP(sysTrapWinSetClip) } void WinDrawRectangle( const RectangleType *rP, UInt16 cornerDiam ) { RectangleType *r = (RectangleType*)rP; r->topLeft.x = BSwap16( r->topLeft.x ); // -> r->topLeft.y = BSwap16( r->topLeft.y ); // -> r->extent.x = BSwap16( r->extent.x ); // -> r->extent.y = BSwap16( r->extent.y ); // -> CALL P4(rP) P2(cornerDiam) TRAP(sysTrapWinDrawRectangle) } void WinDrawLine( Coord x1, Coord y1, Coord x2, Coord y2 ) { CALL P2(x1) P2(y1) P2(x2) P2(y2) TRAP(sysTrapWinDrawLine) } void WinDrawPixel( Coord x, Coord y ) { CALL P2(x) P2(y) TRAP(sysTrapWinDrawPixel) } Err WinGetPixelRGB( Coord x, Coord y, RGBColorType *rgbP ) { CALL P2(x) P2(y) P4(rgbP) TRAP(sysTrapWinGetPixelRGB) } void WinSetForeColorRGB( const RGBColorType *newRgbP, RGBColorType *prevRgbP ) { CALL P4(newRgbP) P4(prevRgbP) TRAP(sysTrapWinSetForeColorRGB) } UInt16 WinSetCoordinateSystem( UInt16 coordSys ) { CALL P2(coordSys) emulStatePtr->regData[2] = HDSelectorWinSetCoordinateSystem; #ifdef sysTrapSysHighDensitySelector return (UInt16)TRAP(sysTrapSysHighDensitySelector & (0x00000FFF)) #else return (UInt16)TRAP(sysTrapHighDensityDispatch & (0x00000FFF)) #endif } #define WinSetWindowBounds(winH, rP) (WinSetBounds((winH), (rP))) Err WinScreenGetAttribute( WinScreenAttrType selector, UInt32* attrP ) { CALL P1(selector) P4(attrP) emulStatePtr->regData[2] = HDSelectorWinScreenGetAttribute; Err retval; #ifdef sysTrapSysHighDensitySelector retval = (Err)TRAP(sysTrapSysHighDensitySelector & (0x00000FFF)) #else retval = (Err)TRAP(sysTrapHighDensityDispatch & (0x00000FFF)) #endif *attrP = BSwap32( *attrP ); // <- return retval; } Err WinScreenMode( WinScreenModeOperation operation, UInt32 *widthP, UInt32 *heightP, UInt32 *depthP, Boolean *enableColorP ) { *widthP = BSwap32( *widthP ); // <-> *heightP = BSwap32( *heightP ); // <-> *depthP = BSwap32( *depthP ); // <-> CALL P1(operation) P4(widthP) P4(heightP) P4(depthP) P4(enableColorP) Err retval = (Err)TRAP(sysTrapWinScreenMode) *widthP = BSwap32( *widthP ); // <-> *heightP = BSwap32( *heightP ); // <-> *depthP = BSwap32( *depthP ); // <-> return retval; } UInt8 *WinScreenLock( WinLockInitType initMode ) { CALL P1(initMode) return (UInt8*)TRAPP(sysTrapWinScreenLock); } void WinScreenUnlock( void ) { CALL TRAP(sysTrapWinScreenUnlock); } Err WinPalette( UInt8 operation, Int16 startIndex, UInt16 paletteEntries, RGBColorType *tableP ) { CALL P1(operation) P2(startIndex) P2(paletteEntries) P4(tableP) return (Err)TRAP(sysTrapWinPalette) } void WinDrawBitmap( BitmapPtr bitmapP, Coord x, Coord y ) { CALL P4(bitmapP) P2(x) P2(y) TRAP(sysTrapWinDrawBitmap) } // ================= // FORMS : // ================= WinHandle FrmGetWindowHandle( const FormType *formP ) { CALL P4(formP) return (WinHandle)TRAPP(sysTrapFrmGetWindowHandle) } FormType *FrmGetActiveForm( void ) { CALL return (FormType*)TRAPP(sysTrapFrmGetActiveForm) } void FrmDrawForm( FormType *formP ) { CALL P4(formP) TRAP(sysTrapFrmDrawForm) } void FrmEraseForm( FormType *formP ) { CALL P4(formP) TRAP(sysTrapFrmEraseForm) } void FrmDeleteForm( FormType *formP ) { CALL P4(formP) TRAP(sysTrapFrmDeleteForm) } FormType *FrmInitForm( UInt16 rscID ) { CALL P2(rscID) return (FormType*)TRAPP(sysTrapFrmInitForm) } void FrmSetActiveForm( FormType *formP ) { CALL P4(formP) TRAP(sysTrapFrmSetActiveForm) } void FrmSetEventHandler( FormType *formP, FormEventHandlerType *handler ) { CALL P4(formP) P4(handler) TRAP(sysTrapFrmSetEventHandler) } void FrmGotoForm( UInt16 formId ) { CALL P2(formId) TRAP(sysTrapFrmGotoForm) } void FrmGetFormBounds( const FormType *formP, RectangleType *rP ) { CALL P4(formP) P4(rP) TRAP(sysTrapFrmGetFormBounds) rP->topLeft.x = BSwap16( rP->topLeft.x ); // -> rP->topLeft.y = BSwap16( rP->topLeft.y ); // -> rP->extent.x = BSwap16( rP->extent.x ); // -> rP->extent.y = BSwap16( rP->extent.y ); // -> } void FrmCloseAllForms( void ) { CALL TRAP(sysTrapFrmCloseAllForms) } // Events are in m68 format! You need convert it for using on the ARM Boolean FrmDispatchEvent( EventType *eventP ) { CALL P4(eventP) return (Boolean)TRAP(sysTrapFrmDispatchEvent) } FormType *FrmGetFormPtr( UInt16 formId ) { CALL P2(formId) return (FormType*)TRAPP(sysTrapFrmGetFormPtr) } // ================= // FEATURES : // ================= Err FtrGet( UInt32 creator, UInt16 featureNum, UInt32 *valueP ) { CALL P4(creator) P2(featureNum) P4(valueP) Err retval = (Err)TRAP(sysTrapFtrGet) *valueP = BSwap32( *valueP ); // <- return retval; } // ================= // EVENTS : // ================= void EvtGetEvent( EventType *event, Int32 timeout ) { CALL P4(event) P4(timeout) TRAP(sysTrapEvtGetEvent) } Boolean MenuHandleEvent( MenuBarType *menuP, EventType *event, UInt16 *error ) { CALL P4(menuP) P4(event) P4(error) Boolean retval = (Boolean)TRAP(sysTrapMenuHandleEvent) *error = BSwap16( *error ); // <- return retval; } Boolean SysHandleEvent( EventPtr eventP ) { CALL P4(eventP) return (Boolean)TRAP(sysTrapSysHandleEvent) } // ================= // BITMAPS : // ================= BitmapType* BmpCreate( Coord width, Coord height, UInt8 depth, ColorTableType * colortableP, UInt16 * error ) { CALL P2(width) P2(height) P1(depth) P4(colortableP) P4(error) BitmapType* retval = (BitmapType*)TRAPP(sysTrapBmpCreate) *error = BSwap16( *error ); // <- return retval; } void* BmpGetBits( BitmapType * bitmapP ) { CALL P4(bitmapP) return (void*)TRAPP(sysTrapBmpGetBits) } BitmapTypeV3* BmpCreateBitmapV3( const BitmapType* bitmapP, UInt16 density, const void* bitsP, const ColorTableType* colorTableP ) { CALL P4(bitmapP) P2(density) P4(bitsP) P4(colorTableP) emulStatePtr->regData[2] = HDSelectorBmpCreateBitmapV3; #ifdef sysTrapSysHighDensitySelector return (BitmapTypeV3*)TRAPP(sysTrapSysHighDensitySelector) #else return (BitmapTypeV3*)TRAPP(sysTrapHighDensityDispatch) #endif } Err BmpDelete( BitmapType * bitmapP ) { CALL P4(bitmapP) return (Err)TRAP(sysTrapBmpDelete) } // ================= // TIME : // ================= void TimSecondsToDateTime( UInt32 seconds, DateTimeType *dateTimeP ) { CALL P4(seconds) P4(dateTimeP) TRAP(sysTrapTimSecondsToDateTime) if( dateTimeP ) { dateTimeP->second = BSwap16( dateTimeP->second ); // <- dateTimeP->minute = BSwap16( dateTimeP->minute ); // <- dateTimeP->hour = BSwap16( dateTimeP->hour ); // <- dateTimeP->day = BSwap16( dateTimeP->day ); // <- dateTimeP->month = BSwap16( dateTimeP->month ); // <- dateTimeP->year = BSwap16( dateTimeP->year ); // <- dateTimeP->weekDay = BSwap16( dateTimeP->weekDay );// <- } } UInt16 SysTicksPerSecond( void ) { CALL return (UInt16)TRAP(sysTrapSysTicksPerSecond) } UInt32 TimGetTicks( void ) { CALL return (UInt32)TRAP(sysTrapTimGetTicks) } UInt32 TimGetSeconds( void ) { CALL return (UInt32)TRAP(sysTrapTimGetSeconds) } // ================= // SYSTEM : // ================= unsigned long KeyCurrentState( void ) { CALL return (unsigned long)TRAP(sysTrapKeyCurrentState) } UInt16 SysSetAutoOffTime( UInt16 seconds ) { CALL P2(seconds) return (UInt16)TRAP(sysTrapSysSetAutoOffTime) } Int16 SysRandom( Int32 newSeed ) { CALL P4(newSeed) return (UInt16)TRAP(sysTrapSysRandom) }
26.349127
130
0.675989
Sound-Linux-More
4c66f3691c04f078b9c0457c9bb158bfd22867d2
27,034
cpp
C++
MWCNNLayerImpl.cpp
henryjimenez/DL-matlab
de77f6d5387a4feb43dd175100006138bbea755f
[ "BSD-2-Clause" ]
null
null
null
MWCNNLayerImpl.cpp
henryjimenez/DL-matlab
de77f6d5387a4feb43dd175100006138bbea755f
[ "BSD-2-Clause" ]
null
null
null
MWCNNLayerImpl.cpp
henryjimenez/DL-matlab
de77f6d5387a4feb43dd175100006138bbea755f
[ "BSD-2-Clause" ]
null
null
null
#include "MWCNNLayerImpl.hpp" #include "MWTargetNetworkImpl.hpp" #include "cnn_api.hpp" #include <cassert> #include <cstring> #include <stdio.h> #if MW_LAYERS_TAP extern void mw_interm_tap(arm_compute::Tensor& armTensor, int size, int count); extern int tap_count; #endif MWCNNLayerImpl::MWCNNLayerImpl(MWCNNLayer* layer, MWTargetNetworkImpl* ntwk_impl) : cnEykmOGhLuyKuadExWe(layer) , fylVqSnTjNbHDtlPhzaj(ntwk_impl) { } void MWCNNLayerImpl::allocateOutputData(int i) { MWTensor* opTensor = getLayer()->getOutputTensor(i); if (opTensor->getopBufIndex() < 0) { getarmTensor(i)->allocator()->allocate(); } else { #if defined(USE_18_11_LIBRARY) || defined(USE_19_02_LIBRARY) getarmTensor(i)->allocator()->import_memory(fylVqSnTjNbHDtlPhzaj->memBuffer[opTensor->getopBufIndex()],fylVqSnTjNbHDtlPhzaj->maxBufSize *sizeof(float)); #elif defined(USE_19_05_LIBRARY) getarmTensor(i)->allocator()->import_memory(fylVqSnTjNbHDtlPhzaj->memBuffer[opTensor->getopBufIndex()]); #else getarmTensor(i)->allocator()->import_memory(arm_compute::Memory(fylVqSnTjNbHDtlPhzaj->memBuffer[opTensor->getopBufIndex()])); #endif } opTensor->setData((float*)getarmTensor(i)->buffer()); } void MWCNNLayerImpl::deallocateOutputData(int i) { if (cnEykmOGhLuyKuadExWe->getOutputTensor()->getopBufIndex() < 0) { getarmTensor(i)->allocator()->free(); } } std::string MWCNNLayerImpl::getLinuxPath(const char* fileName) { std::string fileS(fileName); std::string key ("\\"); std::size_t found = 0; while(found != std::string::npos){ found = fileS.rfind(key); if (found!=std::string::npos) fileS.replace (found,key.length(),"/"); } return fileS; } arm_compute::Tensor* MWCNNLayerImpl::getprevLayerarmTensor(MWTensor* ipTensor) { int index = ipTensor->getSourcePortIndex(); if (ipTensor->getOwner()->getImpl() == NULL) { return ipTensor->getOwner()->getInputTensor()->getOwner()->getImpl()->getarmTensor(index); } else { if (ipTensor->getOwner()->getImpl()->getarmTensor() == nullptr) { return ipTensor->getOwner()->getInputTensor()->getOwner()->getImpl()->getarmTensor( index); } else { return ipTensor->getOwner()->getImpl()->getarmTensor(index); } } } std::shared_ptr<arm_compute::Tensor> MWCNNLayerImpl::getARMTensorsharedPtr(MWTensor* ipTensor) { int index = ipTensor->getSourcePortIndex(); if (ipTensor->getOwner()->getImpl() == NULL) { return ipTensor->getOwner()->getInputTensor()->getOwner()->getImpl()->armTensor[index]; } else { if (ipTensor->getOwner()->getImpl()->getarmTensor() == nullptr) { return ipTensor->getOwner()->getInputTensor()->getOwner()->getImpl()->armTensor[index]; } else { return ipTensor->getOwner()->getImpl()->armTensor[index]; } } } arm_compute::Tensor* MWCNNLayerImpl::getarmTensor(int index) { if (armTensor.size() >= 1) { return armTensor[index].get(); } else { return nullptr; } } void MWCNNLayerImpl::setarmTensor(std::shared_ptr<arm_compute::Tensor> tensor, int index) { armTensor[index] = tensor; } MWInputLayerImpl::MWInputLayerImpl(MWCNNLayer* layer, MWTargetNetworkImpl* ntwk_impl, int TfsmDFpPPOscKZifVzSQ, int wJyXsrUCMgxdIKVIJSyx, int QhTesEEIHwhNmHSeYbRR, int zRhMJbzYfMHEzDwdpDGW, const char* avg_file_name) : MWCNNLayerImpl(layer, ntwk_impl) , bYBVtTnVUuGDUlaTmmHp(zRhMJbzYfMHEzDwdpDGW) { setarmTensor(std::make_shared<arm_compute::Tensor>()); if( bYBVtTnVUuGDUlaTmmHp ) { loadAvg(avg_file_name, TfsmDFpPPOscKZifVzSQ * wJyXsrUCMgxdIKVIJSyx, QhTesEEIHwhNmHSeYbRR); } } MWInputLayerImpl::~MWInputLayerImpl() { } void MWInputLayerImpl::propagateSize(){ MWInputLayer* inpLayer = static_cast<MWInputLayer*>(getLayer()); MWTensor* ipTensor = inpLayer->getInputTensor(0); getarmTensor()->allocator()->init( arm_compute::TensorInfo(arm_compute::TensorShape((long unsigned int)ipTensor->getWidth(), (long unsigned int)ipTensor->getHeight(), (long unsigned int)ipTensor->getChannels(), (long unsigned int)ipTensor->getBatchSize()), 1, arm_compute::DataType::F32)); } void MWInputLayerImpl::loadAvg(const char* THfVbcZJtANcLKxEriuV, int channelSize, int numChannels) { std::string fileString = getLinuxPath(THfVbcZJtANcLKxEriuV); FILE* TbrNrGxaFFHrzKUcfHNZ = MWCNNLayer::openBinaryFile(fileString.c_str()); if (TbrNrGxaFFHrzKUcfHNZ == NULL) { std::cerr<<"Unable to open Input Average file"<<std::endl; } int gNROjwaqhxDPvBWUCUcQ = channelSize * numChannels; JLDBTuxkNCsKfaFIEVHB = new std::vector<float>; JLDBTuxkNCsKfaFIEVHB->reserve(gNROjwaqhxDPvBWUCUcQ); if(bYBVtTnVUuGDUlaTmmHp==1){ call_fread(JLDBTuxkNCsKfaFIEVHB->data(), sizeof(float), gNROjwaqhxDPvBWUCUcQ, TbrNrGxaFFHrzKUcfHNZ, THfVbcZJtANcLKxEriuV); } else{ int channelOffset=0; std::vector<float> ONvcEjLBnVNUdjMKOAwF(numChannels); call_fread(ONvcEjLBnVNUdjMKOAwF.data(), sizeof(float), numChannels, TbrNrGxaFFHrzKUcfHNZ, THfVbcZJtANcLKxEriuV); for(int i=0;i<numChannels;i++){ std::fill_n(JLDBTuxkNCsKfaFIEVHB->begin()+channelOffset, channelSize, ONvcEjLBnVNUdjMKOAwF[i]); channelOffset = channelOffset+channelSize; } } fclose(TbrNrGxaFFHrzKUcfHNZ); return; } void MWInputLayerImpl::allocateOutputData(int i) { MWCNNLayerImpl::allocateOutputData(i); MWTensor* ipTensor = getLayer()->getInputTensor(0); MWTensor* opTensor = getLayer()->getOutputTensor(0); m_inputImage = (float*)malloc(ipTensor->getBatchSize() * ipTensor->getChannels() * ipTensor->getHeight() * ipTensor->getWidth() * sizeof(float)); if ((getarmTensor(i)->info()->total_size() / 4) == (opTensor->getBatchSize() * opTensor->getChannels() * opTensor->getHeight() * opTensor->getWidth())) { opTensor->setData((float*)getarmTensor(i)->buffer()); } else { opTensor->setData(m_inputImage); } opTensor->setData(getData<float>()); } void MWInputLayerImpl::predict() { float* inp = m_inputImage; int i, btch; MWInputLayer* inpLayer = static_cast<MWInputLayer*>(getLayer()); MWTensor* opTensor = inpLayer->getOutputTensor(0); float* out = m_inputImage; if ((getarmTensor()->info()->total_size() / 4) == (opTensor->getBatchSize() * opTensor->getChannels() * opTensor->getHeight() * opTensor->getWidth())) { inp = (float*)getarmTensor()->buffer(); out = (float*)getarmTensor()->buffer(); } else { inp = m_inputImage; out = m_inputImage; } if (bYBVtTnVUuGDUlaTmmHp) { for (btch = 0; btch < opTensor->getBatchSize(); btch++) { #pragma omp parallel for for (i = 0; i < opTensor->getChannels() * opTensor->getHeight() * opTensor->getWidth(); i++) { out[i] = inp[i] - (*JLDBTuxkNCsKfaFIEVHB)[i]; } inp += opTensor->getChannels() * opTensor->getHeight() * opTensor->getWidth(); out += opTensor->getChannels() * opTensor->getHeight() * opTensor->getWidth(); } } if ((getarmTensor()->info()->total_size() / 4) != (opTensor->getBatchSize() * opTensor->getChannels() * opTensor->getHeight() * opTensor->getWidth())) { MWACLUtils::fillBufferToTensor(m_inputImage, *getarmTensor()); } #if MW_INPUT_TAP mw_interm_tap(*getarmTensor(), opTensor->getNumElements(), tap_count++); #endif return; } void MWInputLayerImpl::cleanup() { if (bYBVtTnVUuGDUlaTmmHp) { if (JLDBTuxkNCsKfaFIEVHB) { delete JLDBTuxkNCsKfaFIEVHB; } } return; } void MWInputLayerImpl::deallocate() { free(m_inputImage); m_inputImage = NULL; return; } MWReLULayerImpl::MWReLULayerImpl(MWCNNLayer* layer, MWTargetNetworkImpl* ntwk_impl, int inPlace) : MWCNNLayerImpl(layer, ntwk_impl) , MW_Mangled_inPlace(inPlace) { if(MW_Mangled_inPlace){ MWTensor* ipTensor = getLayer()->getInputTensor(); setarmTensor(getARMTensorsharedPtr(ipTensor)); }else{ setarmTensor(std::make_shared<arm_compute::Tensor>()); } } MWReLULayerImpl::~MWReLULayerImpl() { } void MWReLULayerImpl::propagateSize() { MWReLULayer* reluLayer = static_cast<MWReLULayer*>(getLayer()); MWTensor* ipTensor = reluLayer->getInputTensor(); MWTensor* opTensor = reluLayer->getOutputTensor(); m_actLayer = std::unique_ptr<arm_compute::NEActivationLayer>(new arm_compute::NEActivationLayer); arm_compute::Tensor* prevLayerarmTensor = getprevLayerarmTensor(ipTensor); if(!MW_Mangled_inPlace){ bool doesPrevLayerHas2DArmTensor = prevLayerarmTensor->info()->num_dimensions() <= 2 && ipTensor->getHeight() == 1 && ipTensor->getWidth()==1; if (doesPrevLayerHas2DArmTensor) { getarmTensor()->allocator()->init(arm_compute::TensorInfo( arm_compute::TensorShape((long unsigned int)opTensor->getChannels(), (long unsigned int)(opTensor->getSequenceLength()*opTensor->getBatchSize())), 1, arm_compute::DataType::F32)); } else { getarmTensor()->allocator()->init( arm_compute::TensorInfo(arm_compute::TensorShape((long unsigned int)ipTensor->getWidth(), (long unsigned int)ipTensor->getHeight(), (long unsigned int)opTensor->getChannels(), (long unsigned int)(opTensor->getSequenceLength()*opTensor->getBatchSize())), 1, arm_compute::DataType::F32)); } } m_actLayer->configure(prevLayerarmTensor, getarmTensor(), arm_compute::ActivationLayerInfo(arm_compute::ActivationLayerInfo::ActivationFunction::RELU)); return; } void MWReLULayerImpl::allocateOutputData(int i){ assert(i==0); MWTensor* opTensor = getLayer()->getOutputTensor(i); if(MW_Mangled_inPlace){ MWTensor* ipTensor = getLayer()->getInputTensor(); opTensor->setData((float*)getprevLayerarmTensor(ipTensor)->buffer()); }else{ getarmTensor(i)->allocator()->allocate(); opTensor->setData((float*)getarmTensor(i)->buffer()); } } void MWReLULayerImpl::deallocateOutputData(int i){ if(!MW_Mangled_inPlace) getarmTensor(i)->allocator()->free(); } void MWReLULayerImpl::predict() { MWReLULayer* reluLayer = static_cast<MWReLULayer*>(getLayer()); MWTensor* opTensor = reluLayer->getOutputTensor(); m_actLayer->run(); #if MW_RELU_TAP mw_interm_tap(*getarmTensor(), opTensor->getNumElements(), tap_count++); #endif return; } MWNormLayerImpl::MWNormLayerImpl(MWCNNLayer* layer, MWTargetNetworkImpl* ntwk_impl, unsigned JABfZsGuaCAmcRcqOYEO, double AuqaQHxmPQSyYRemQvyX, double BHuHNDGoRwGRouCxeMbw, double CDJtexcMbXMWAmnNZsNf) : MWCNNLayerImpl(layer, ntwk_impl) , AuqaQHxmPQSyYRemQvyX(AuqaQHxmPQSyYRemQvyX) , BHuHNDGoRwGRouCxeMbw(BHuHNDGoRwGRouCxeMbw) , CDJtexcMbXMWAmnNZsNf(CDJtexcMbXMWAmnNZsNf) , JABfZsGuaCAmcRcqOYEO(JABfZsGuaCAmcRcqOYEO) { setarmTensor(std::make_shared<arm_compute::Tensor>()); } MWNormLayerImpl::~MWNormLayerImpl() { } void MWNormLayerImpl::propagateSize() { MWNormLayer* normLayer = static_cast<MWNormLayer*>(getLayer()); MWTensor* ipTensor = normLayer->getInputTensor(); m_normLayer = std::unique_ptr<arm_compute::NENormalizationLayer>(new arm_compute::NENormalizationLayer); arm_compute::Tensor* prevLayerarmTensor = getprevLayerarmTensor(ipTensor); m_isIpArmTensorReshaped = prevLayerarmTensor->info()->num_dimensions() <= 2 && ipTensor->getHeight() == 1 && ipTensor->getWidth()==1; if(m_isIpArmTensorReshaped){ m_layerInputArmTensor = std::make_shared<arm_compute::Tensor>(); m_layerInputArmTensor->allocator()->init( arm_compute::TensorInfo(arm_compute::TensorShape((long unsigned int)ipTensor->getWidth(), (long unsigned int)ipTensor->getHeight(), (long unsigned int)ipTensor->getChannels(), (long unsigned int)ipTensor->getBatchSize()), 1, arm_compute::DataType::F32)); m_reshapeKernel = std::unique_ptr<arm_compute::NEReshapeLayer>(new arm_compute::NEReshapeLayer); m_reshapeKernel->configure(prevLayerarmTensor, m_layerInputArmTensor.get()); } else{ m_layerInputArmTensor = getARMTensorsharedPtr(ipTensor); } getarmTensor()->allocator()->init( arm_compute::TensorInfo(arm_compute::TensorShape((long unsigned int)ipTensor->getWidth(), (long unsigned int)ipTensor->getHeight(), (long unsigned int)ipTensor->getChannels(), (long unsigned int)ipTensor->getBatchSize()), 1, arm_compute::DataType::F32)); m_normLayer->configure(m_layerInputArmTensor.get(), getarmTensor(), arm_compute::NormalizationLayerInfo(arm_compute::NormType::CROSS_MAP, JABfZsGuaCAmcRcqOYEO, AuqaQHxmPQSyYRemQvyX, BHuHNDGoRwGRouCxeMbw, CDJtexcMbXMWAmnNZsNf)); return; } void MWNormLayerImpl::allocate(){ if(m_isIpArmTensorReshaped){ m_layerInputArmTensor->allocator()->allocate(); } return; } void MWNormLayerImpl::predict() { MWNormLayer* normLayer = static_cast<MWNormLayer*>(getLayer()); MWTensor* opTensor = normLayer->getOutputTensor(); if(m_isIpArmTensorReshaped){ m_reshapeKernel->run(); } m_normLayer->run(); #if MW_NORM_TAP mw_interm_tap(*getarmTensor(), opTensor->getNumElements(), tap_count++); #endif return; } MWMaxPoolingLayerImpl::MWMaxPoolingLayerImpl(MWCNNLayer* layer, MWTargetNetworkImpl* ntwk_impl, int GZGFVDrXwFLJleoTDywO, int GbdgxISzcqHOpzQEBrvP, int IIiwAtyrOtLzLWAUlTey, int IpFhwalnAlrMvcuyQpQD, int FeVcBgtQmTLtmnNcJGMY, int FLuSVNoPhAFKtLUchSvv, int GFggoMvRWucDMqzlWzCl, int GLovsOhUpzOJhKgXUAJY, bool JsZenQeBPMhwsyEhVHiD, int hKyfKjPACkOBDvLdESxH) : MWCNNLayerImpl(layer, ntwk_impl) , GZGFVDrXwFLJleoTDywO(GZGFVDrXwFLJleoTDywO) , GbdgxISzcqHOpzQEBrvP(GbdgxISzcqHOpzQEBrvP) , FeVcBgtQmTLtmnNcJGMY(FeVcBgtQmTLtmnNcJGMY) , FLuSVNoPhAFKtLUchSvv(FLuSVNoPhAFKtLUchSvv) , GFggoMvRWucDMqzlWzCl(GFggoMvRWucDMqzlWzCl) , GLovsOhUpzOJhKgXUAJY(GLovsOhUpzOJhKgXUAJY) , IIiwAtyrOtLzLWAUlTey(IIiwAtyrOtLzLWAUlTey) , IpFhwalnAlrMvcuyQpQD(IpFhwalnAlrMvcuyQpQD){ assert(hKyfKjPACkOBDvLdESxH == 1); assert(!JsZenQeBPMhwsyEhVHiD); setarmTensor(std::make_shared<arm_compute::Tensor>()); } MWMaxPoolingLayerImpl::~MWMaxPoolingLayerImpl() { } float* MWMaxPoolingLayerImpl::getIndexData() { assert(false); } void MWMaxPoolingLayerImpl::propagateSize() { MWMaxPoolingLayer* maxPoolLayer = static_cast<MWMaxPoolingLayer*>(getLayer()); MWTensor* ipTensor = maxPoolLayer->getInputTensor(); MWTensor* opTensor = maxPoolLayer->getOutputTensor(); m_maxPoolLayer = std::unique_ptr<arm_compute::NEPoolingLayer>(new arm_compute::NEPoolingLayer); arm_compute::Tensor* prevLayerarmTensor = getprevLayerarmTensor(ipTensor); if ((GZGFVDrXwFLJleoTDywO == -1) && (GbdgxISzcqHOpzQEBrvP == -1)) { GZGFVDrXwFLJleoTDywO = ipTensor->getHeight(); GbdgxISzcqHOpzQEBrvP = ipTensor->getWidth(); } getarmTensor()->allocator()->init(arm_compute::TensorInfo(arm_compute::TensorShape((long unsigned int)opTensor->getWidth(), (long unsigned int)opTensor->getHeight(), (long unsigned int)opTensor->getChannels(), (long unsigned int)opTensor->getBatchSize()), 1, arm_compute::DataType::F32)); m_maxPoolLayer->configure( prevLayerarmTensor, getarmTensor(), arm_compute::PoolingLayerInfo( arm_compute::PoolingType::MAX, GZGFVDrXwFLJleoTDywO, arm_compute::PadStrideInfo(IpFhwalnAlrMvcuyQpQD, IIiwAtyrOtLzLWAUlTey, GFggoMvRWucDMqzlWzCl, GLovsOhUpzOJhKgXUAJY, FeVcBgtQmTLtmnNcJGMY, FLuSVNoPhAFKtLUchSvv, arm_compute::DimensionRoundingType::FLOOR))); return; } void MWMaxPoolingLayerImpl::predict() { MWMaxPoolingLayer* maxPoolLayer = static_cast<MWMaxPoolingLayer*>(getLayer()); MWTensor* opTensor = maxPoolLayer->getOutputTensor(); m_maxPoolLayer->run(); #if MW_POOL_TAP mw_interm_tap(*getarmTensor(), opTensor->getNumElements(), tap_count++); #endif return; } MWFCLayerImpl::MWFCLayerImpl(MWCNNLayer* layer, MWTargetNetworkImpl* ntwk_impl, int m_NumInputFeatures, int m_NumOutputFeatures, const char* m_weights_file, const char* m_bias_file) : MWCNNLayerImpl(layer, ntwk_impl) { MWTensor* opTensor = getLayer()->getOutputTensor(); setarmTensor(std::make_shared<arm_compute::Tensor>()); int gNROjwaqhxDPvBWUCUcQ = m_NumInputFeatures * m_NumOutputFeatures; wJyXsrUCMgxdIKVIJSyx = CREATE_BUFFER(gNROjwaqhxDPvBWUCUcQ); OiVqrkNdXioJhALWMMvm = CREATE_BUFFER(m_NumOutputFeatures); m_fcLayerWgtTensor.allocator()->init( arm_compute::TensorInfo(arm_compute::TensorShape((long unsigned int)(m_NumInputFeatures), (long unsigned int)(m_NumOutputFeatures)), 1, arm_compute::DataType::F32)); m_fcLayerBiasTensor.allocator()->init( arm_compute::TensorInfo(arm_compute::TensorShape((long unsigned int)(m_NumOutputFeatures)), 1, arm_compute::DataType::F32)); loadWeights(m_weights_file, gNROjwaqhxDPvBWUCUcQ); loadBias(m_bias_file, m_NumOutputFeatures); } MWFCLayerImpl::~MWFCLayerImpl() { } void MWFCLayerImpl::propagateSize(){ MWFCLayer* fcLayer = static_cast<MWFCLayer*>(getLayer()); MWTensor* ipTensor = fcLayer->getInputTensor(); MWTensor* opTensor = fcLayer->getOutputTensor(); m_fcLayer = std::unique_ptr<arm_compute::NEFullyConnectedLayer>(new arm_compute::NEFullyConnectedLayer); arm_compute::Tensor* prevLayerarmTensor = getprevLayerarmTensor(ipTensor); getarmTensor()->allocator()->init(arm_compute::TensorInfo( arm_compute::TensorShape((long unsigned int)(opTensor->getWidth()* opTensor->getHeight()*opTensor->getChannels()), (long unsigned int)(opTensor->getBatchSize()* opTensor->getSequenceLength())), 1, arm_compute::DataType::F32)); m_fcLayer->configure(prevLayerarmTensor, &m_fcLayerWgtTensor, &m_fcLayerBiasTensor, getarmTensor()); prepareWeights(); return; } void MWFCLayerImpl::allocate(){ MWFCLayer* fcLayer = static_cast<MWFCLayer*>(getLayer()); MWTensor* ipTensor = fcLayer->getInputTensor(); MWTensor* opTensor = fcLayer->getOutputTensor(); int CufLFODQDXTAPyRqYodN = ipTensor->getChannels(); int DRzwhbNPpftRRIXXfHzd = opTensor->getChannels(); MWACLUtils::allocateAndFillTensor(m_fcLayerWgtTensor, wJyXsrUCMgxdIKVIJSyx, CufLFODQDXTAPyRqYodN * DRzwhbNPpftRRIXXfHzd, isWgtsPadded); MWACLUtils::allocateAndFillTensor(m_fcLayerBiasTensor, OiVqrkNdXioJhALWMMvm, DRzwhbNPpftRRIXXfHzd, isBiasPadded); return; } void MWFCLayerImpl::loadWeights(const char* THfVbcZJtANcLKxEriuV, int gNROjwaqhxDPvBWUCUcQ) { float* wMySyzzledUmSLTWhuYH = GET_BUFFER(wJyXsrUCMgxdIKVIJSyx); std::string fileString = getLinuxPath(THfVbcZJtANcLKxEriuV); FILE* TbrNrGxaFFHrzKUcfHNZ = MWCNNLayer::openBinaryFile(fileString.c_str()); call_fread(wMySyzzledUmSLTWhuYH, sizeof(float), gNROjwaqhxDPvBWUCUcQ, TbrNrGxaFFHrzKUcfHNZ, THfVbcZJtANcLKxEriuV); fclose(TbrNrGxaFFHrzKUcfHNZ); } void MWFCLayerImpl::prepareWeights(){ float* wvufwFZlsnpjbxmTBVYE = GET_BUFFER(wJyXsrUCMgxdIKVIJSyx); MWFCLayer* fcLayer = static_cast<MWFCLayer*>(getLayer()); MWTensor* ipTensor = fcLayer->getInputTensor(); MWTensor* opTensor = fcLayer->getOutputTensor(); int CufLFODQDXTAPyRqYodN = ipTensor->getChannels() * ipTensor->getWidth() * ipTensor->getHeight(); int DRzwhbNPpftRRIXXfHzd = opTensor->getChannels(); int gNROjwaqhxDPvBWUCUcQ = CufLFODQDXTAPyRqYodN * DRzwhbNPpftRRIXXfHzd; if (ipTensor->getHeight() != 1 && ipTensor->getWidth() != 1) { float* wMySyzzledUmSLTWhuYH = (float*)malloc(sizeof(float) * ipTensor->getHeight() * ipTensor->getWidth()); for (int k = 0; k < gNROjwaqhxDPvBWUCUcQ / ipTensor->getHeight() / ipTensor->getWidth(); k++) { for (int i = 0; i < ipTensor->getHeight() * ipTensor->getWidth(); i++) wMySyzzledUmSLTWhuYH[i] = wvufwFZlsnpjbxmTBVYE[k * ipTensor->getHeight() * ipTensor->getWidth() + i]; for (int j = 0; j < ipTensor->getHeight(); j++) for (int i = 0; i < ipTensor->getWidth(); i++) wvufwFZlsnpjbxmTBVYE[k * ipTensor->getHeight() * ipTensor->getWidth() + j * ipTensor->getWidth() + i] = wMySyzzledUmSLTWhuYH[j + i * ipTensor->getHeight()]; } free(wMySyzzledUmSLTWhuYH); } return; } void MWFCLayerImpl::loadBias(const char* THfVbcZJtANcLKxEriuV, int DRzwhbNPpftRRIXXfHzd) { float* OzygUJRIZYnGLzSjgahB = GET_BUFFER(OiVqrkNdXioJhALWMMvm); std::string fileString = getLinuxPath(THfVbcZJtANcLKxEriuV); FILE* TbrNrGxaFFHrzKUcfHNZ = MWCNNLayer::openBinaryFile(fileString.c_str()); call_fread(OzygUJRIZYnGLzSjgahB, sizeof(float), DRzwhbNPpftRRIXXfHzd, TbrNrGxaFFHrzKUcfHNZ, THfVbcZJtANcLKxEriuV); fclose(TbrNrGxaFFHrzKUcfHNZ); return; } void MWFCLayerImpl::predict() { m_fcLayer->run(); #if MW_FC_TAP MWFCLayer* fcLayer = static_cast<MWFCLayer*>(getLayer()); MWTensor* opTensor = fcLayer->getOutputTensor(); mw_interm_tap(*getarmTensor(), opTensor->getNumElements(), tap_count++); #endif return; } void MWFCLayerImpl::deallocate() { if (isWgtsPadded){ m_fcLayerWgtTensor.allocator()->free(); isWgtsPadded = false; } if (isBiasPadded){ m_fcLayerBiasTensor.allocator()->free(); isWgtsPadded = false; } return; } void MWFCLayerImpl::cleanup() { FREE_BUFFER_MEMORY(wJyXsrUCMgxdIKVIJSyx); FREE_BUFFER_MEMORY(OiVqrkNdXioJhALWMMvm); return; } MWSoftmaxLayerImpl::MWSoftmaxLayerImpl(MWCNNLayer* layer, MWTargetNetworkImpl* ntwk_impl) : MWCNNLayerImpl(layer, ntwk_impl) , m_doesChannelwiseSoftmax(false) { setarmTensor(std::make_shared<arm_compute::Tensor>()); } MWSoftmaxLayerImpl::~MWSoftmaxLayerImpl() { } void MWSoftmaxLayerImpl::propagateSize() { MWSoftmaxLayer* sfmxLayer = static_cast<MWSoftmaxLayer*>(getLayer()); MWTensor* ipTensor = sfmxLayer->getInputTensor(); MWTensor* opTensor = sfmxLayer->getOutputTensor(); m_softmaxLayer = std::unique_ptr<arm_compute::NESoftmaxLayer>(new arm_compute::NESoftmaxLayer); arm_compute::Tensor* prevLayerarmTensor = getprevLayerarmTensor(ipTensor); bool doesPrevLayerHas2DArmTensor = prevLayerarmTensor->info()->num_dimensions() <= 2 && ipTensor->getHeight() == 1 && ipTensor->getWidth()==1; if (doesPrevLayerHas2DArmTensor) { getarmTensor()->allocator()->init(arm_compute::TensorInfo( arm_compute::TensorShape((long unsigned int)opTensor->getChannels(), (long unsigned int)(opTensor->getBatchSize()*opTensor->getSequenceLength())), 1, arm_compute::DataType::F32)); } else { m_doesChannelwiseSoftmax = true; getarmTensor()->allocator()->init(arm_compute::TensorInfo( arm_compute::TensorShape((long unsigned int)opTensor->getWidth(), (long unsigned int)opTensor->getHeight(), (long unsigned int)opTensor->getChannels(), (long unsigned int)(opTensor->getBatchSize()*opTensor->getSequenceLength())), 1, arm_compute::DataType::F32)); } if (!m_doesChannelwiseSoftmax) { m_softmaxLayer->configure(prevLayerarmTensor, getarmTensor()); } else { permuteToNHWC = std::unique_ptr<arm_compute::NEPermute>(new arm_compute::NEPermute); permuteToNCHW = std::unique_ptr<arm_compute::NEPermute>(new arm_compute::NEPermute); arm_compute::PermutationVector nhwcPermuteDims(2, 0, 1), nchwPermuteDims(1, 2, 0); inputNHWCArmTensor.allocator()->init(arm_compute::TensorInfo( arm_compute::TensorShape((long unsigned int)ipTensor->getChannels(), (long unsigned int)ipTensor->getWidth(), (long unsigned int)ipTensor->getHeight(), 1), 1, arm_compute::DataType::F32)); permuteToNHWC->configure(prevLayerarmTensor, &inputNHWCArmTensor, nhwcPermuteDims); tmpSfmaxNHWCArmTensor.allocator()->init(arm_compute::TensorInfo( arm_compute::TensorShape((long unsigned int)ipTensor->getChannels(), (long unsigned int)ipTensor->getWidth(), (long unsigned int)ipTensor->getHeight(), 1), 1, arm_compute::DataType::F32)); m_softmaxLayer->configure(&inputNHWCArmTensor, &tmpSfmaxNHWCArmTensor); permuteToNCHW->configure(&tmpSfmaxNHWCArmTensor, getarmTensor(), nchwPermuteDims); } return; } void MWSoftmaxLayerImpl::allocate() { if (m_doesChannelwiseSoftmax) { inputNHWCArmTensor.allocator()->allocate(); tmpSfmaxNHWCArmTensor.allocator()->allocate(); } return; } void MWSoftmaxLayerImpl::predict() { MWSoftmaxLayer* sfmxLayer = static_cast<MWSoftmaxLayer*>(getLayer()); MWTensor* opTensor = sfmxLayer->getOutputTensor(); if (!m_doesChannelwiseSoftmax) { m_softmaxLayer->run(); } else { permuteToNHWC->run(); m_softmaxLayer->run(); permuteToNCHW->run(); } #if MW_SFMX_TAP mw_interm_tap(*getarmTensor(), opTensor->getNumElements(), tap_count++); #endif return; } void MWSoftmaxLayerImpl::deallocate() { if (m_doesChannelwiseSoftmax) { inputNHWCArmTensor.allocator()->free(); tmpSfmaxNHWCArmTensor.allocator()->free(); } return; } MWAvgPoolingLayerImpl::MWAvgPoolingLayerImpl(MWCNNLayer* layer, MWTargetNetworkImpl* ntwk_impl, int GZGFVDrXwFLJleoTDywO, int GbdgxISzcqHOpzQEBrvP, int IIiwAtyrOtLzLWAUlTey, int IpFhwalnAlrMvcuyQpQD, int FwLnexHgxHRquTKmNpoa, int EvebzoroiuKkIxwjkGnD, int FpguQZSermqZCMRiUfML, int FshVHIJMRAhtQirYPlZd) : MWCNNLayerImpl(layer, ntwk_impl) , GZGFVDrXwFLJleoTDywO(GZGFVDrXwFLJleoTDywO) , GbdgxISzcqHOpzQEBrvP(GbdgxISzcqHOpzQEBrvP) , IIiwAtyrOtLzLWAUlTey(IIiwAtyrOtLzLWAUlTey) , IpFhwalnAlrMvcuyQpQD(IpFhwalnAlrMvcuyQpQD) , FeVcBgtQmTLtmnNcJGMY(FwLnexHgxHRquTKmNpoa) , FLuSVNoPhAFKtLUchSvv(EvebzoroiuKkIxwjkGnD) , GFggoMvRWucDMqzlWzCl(FpguQZSermqZCMRiUfML) , GLovsOhUpzOJhKgXUAJY(FshVHIJMRAhtQirYPlZd) { setarmTensor(std::make_shared<arm_compute::Tensor>()); } MWAvgPoolingLayerImpl::~MWAvgPoolingLayerImpl() { } void MWAvgPoolingLayerImpl::propagateSize() { MWAvgPoolingLayer* avgpoolLayer = static_cast<MWAvgPoolingLayer*>(getLayer()); MWTensor* opTensor = avgpoolLayer->getOutputTensor(); MWTensor* ipTensor = avgpoolLayer->getInputTensor(); m_avgPoolLayer = std::unique_ptr<arm_compute::NEPoolingLayer>(new arm_compute::NEPoolingLayer); if ((GZGFVDrXwFLJleoTDywO == -1) && (GbdgxISzcqHOpzQEBrvP == -1)) { GZGFVDrXwFLJleoTDywO = ipTensor->getHeight(); GbdgxISzcqHOpzQEBrvP = ipTensor->getWidth(); } arm_compute::Tensor* prevLayerarmTensor = getprevLayerarmTensor(ipTensor); getarmTensor()->allocator()->init(arm_compute::TensorInfo(arm_compute::TensorShape((long unsigned int)opTensor->getWidth(), (long unsigned int)opTensor->getHeight(), (long unsigned int)opTensor->getChannels(), (long unsigned int)opTensor->getBatchSize()), 1, arm_compute::DataType::F32)); m_avgPoolLayer->configure( prevLayerarmTensor, getarmTensor(), arm_compute::PoolingLayerInfo( arm_compute::PoolingType::AVG, GZGFVDrXwFLJleoTDywO, arm_compute::PadStrideInfo(IpFhwalnAlrMvcuyQpQD, IIiwAtyrOtLzLWAUlTey, GFggoMvRWucDMqzlWzCl, GLovsOhUpzOJhKgXUAJY, FeVcBgtQmTLtmnNcJGMY, FLuSVNoPhAFKtLUchSvv, arm_compute::DimensionRoundingType::FLOOR))); return ; } void MWAvgPoolingLayerImpl::predict() { m_avgPoolLayer->run(); #if MW_AVG_POOL_TAP MWAvgPoolingLayer* avgpoolLayer = static_cast<MWAvgPoolingLayer*>(getLayer()); MWTensor* opTensor = avgpoolLayer->getOutputTensor(); mw_interm_tap(*getarmTensor(), opTensor->getNumElements(), tap_count++); #endif return; } MWOutputLayerImpl::MWOutputLayerImpl(MWCNNLayer* layer, MWTargetNetworkImpl* ntwk_impl) : MWCNNLayerImpl(layer, ntwk_impl) { } MWOutputLayerImpl::~MWOutputLayerImpl() { } void MWOutputLayerImpl::propagateSize() { MWOutputLayer* opLayer = static_cast<MWOutputLayer*>(getLayer()); MWTensor* ipTensor = opLayer->getInputTensor(0); MWTensor* opTensor = opLayer->getOutputTensor(0); m_outputArmTensor = getprevLayerarmTensor(ipTensor); } void MWOutputLayerImpl::allocateOutputData(int i) { assert(i == 0); MWOutputLayer* opLayer = static_cast<MWOutputLayer*>(getLayer()); MWTensor* opTensor = opLayer->getOutputTensor(0); m_outputData = (float*)malloc(opTensor->getNumElements() * sizeof(float)); opTensor->setData(m_outputData); if ((m_outputArmTensor->info()->total_size() / 4) == opTensor->getNumElements()) { opTensor->setData((float*)m_outputArmTensor->buffer()); } opTensor->setData(getData<float>()); } void MWOutputLayerImpl::predict() { MWOutputLayer* opLayer = static_cast<MWOutputLayer*>(getLayer()); MWTensor* opTensor = opLayer->getOutputTensor(0); if ((m_outputArmTensor->info()->total_size() / 4) != opTensor->getNumElements()) { MWACLUtils::fillTensorToBuffer(opTensor->getData<float>(), *m_outputArmTensor); } return; } void MWOutputLayerImpl::deallocateOutputData(int i) { if(m_outputData){ free(m_outputData); m_outputData = NULL; } return; }
64.520286
136
0.774506
henryjimenez
4c6955b5aba9ffd250f77ff17df3d1d3592309fe
2,837
cc
C++
chrome/chrome_cleaner/parsers/target/sandbox_setup.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
575
2015-06-18T23:58:20.000Z
2022-03-23T09:32:39.000Z
chrome/chrome_cleaner/parsers/target/sandbox_setup.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
chrome/chrome_cleaner/parsers/target/sandbox_setup.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
52
2015-07-14T10:40:50.000Z
2022-03-15T01:11:49.000Z
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/chrome_cleaner/parsers/target/sandbox_setup.h" #include <utility> #include "base/run_loop.h" #include "base/task/single_thread_task_executor.h" #include "chrome/chrome_cleaner/ipc/mojo_sandbox_hooks.h" #include "chrome/chrome_cleaner/ipc/mojo_task_runner.h" #include "chrome/chrome_cleaner/mojom/parser_interface.mojom.h" #include "chrome/chrome_cleaner/os/early_exit.h" #include "chrome/chrome_cleaner/parsers/target/parser_impl.h" #include "components/chrome_cleaner/public/constants/result_codes.h" #include "mojo/public/cpp/bindings/pending_receiver.h" namespace chrome_cleaner { namespace { class ParserSandboxTargetHooks : public MojoSandboxTargetHooks { public: explicit ParserSandboxTargetHooks(MojoTaskRunner* mojo_task_runner) : mojo_task_runner_(mojo_task_runner) {} ~ParserSandboxTargetHooks() override { // Delete the mojo objects on the IPC thread. mojo_task_runner_->PostTask( FROM_HERE, base::BindOnce( [](std::unique_ptr<ParserImpl> parser_impl) { parser_impl.reset(); }, std::move(parser_impl_))); } // SandboxTargetHooks ResultCode TargetDroppedPrivileges( const base::CommandLine& command_line) override { mojo::PendingReceiver<mojom::Parser> receiver( ExtractSandboxMessagePipe(command_line)); // This loop will run forever. Once the communication channel with the // broker process is broken, mojo error handler will abort this process. base::RunLoop run_loop; mojo_task_runner_->PostTask( FROM_HERE, base::BindOnce(&ParserSandboxTargetHooks::CreateParserImpl, base::Unretained(this), std::move(receiver))); run_loop.Run(); return RESULT_CODE_SUCCESS; } private: void CreateParserImpl(mojo::PendingReceiver<mojom::Parser> receiver) { parser_impl_ = std::make_unique<ParserImpl>(std::move(receiver), base::BindOnce(&EarlyExit, 1)); } MojoTaskRunner* mojo_task_runner_; base::SingleThreadTaskExecutor main_thread_task_executor_; std::unique_ptr<ParserImpl> parser_impl_; DISALLOW_COPY_AND_ASSIGN(ParserSandboxTargetHooks); }; } // namespace ResultCode RunParserSandboxTarget(const base::CommandLine& command_line, sandbox::TargetServices* target_services) { scoped_refptr<MojoTaskRunner> mojo_task_runner = MojoTaskRunner::Create(); ParserSandboxTargetHooks target_hooks(mojo_task_runner.get()); return RunSandboxTarget(command_line, target_services, &target_hooks); } } // namespace chrome_cleaner
36.371795
80
0.720127
sarang-apps
4c6b8ca41338111eb30b19cf2f22b586572688df
592
hpp
C++
src/state.hpp
ebassi/node-clutter
760b8f5704a216dcd633658051c0778151b21391
[ "MIT" ]
1
2017-08-31T00:58:33.000Z
2017-08-31T00:58:33.000Z
src/state.hpp
ebassi/node-clutter
760b8f5704a216dcd633658051c0778151b21391
[ "MIT" ]
null
null
null
src/state.hpp
ebassi/node-clutter
760b8f5704a216dcd633658051c0778151b21391
[ "MIT" ]
null
null
null
#ifndef NODE_CLUTTER_STATE_H_ #define NODE_CLUTTER_STATE_H_ #include <clutter/clutter.h> #include <v8.h> #include <node.h> namespace clutter { class State : public node::ObjectWrap { public: static void Initialize(v8::Handle<v8::Object> target); static void PrototypeMethodsInit(v8::Handle<v8::FunctionTemplate> constructor_template); ClutterState *_state; protected: State(); static v8::Handle<v8::Value> New(const v8::Arguments& args); static v8::Handle<v8::Value> Set(const v8::Arguments& args); static v8::Handle<v8::Value> SetState(const v8::Arguments& args); }; } #endif
21.142857
89
0.746622
ebassi
4c6baa5c68411296b4cc7a6cc74c1d9d6e6a8dd5
163
hpp
C++
kernel/keyboard.hpp
mox692/mos
211b36dade615cfd43d3bb077703b82b638eec10
[ "Apache-2.0" ]
null
null
null
kernel/keyboard.hpp
mox692/mos
211b36dade615cfd43d3bb077703b82b638eec10
[ "Apache-2.0" ]
null
null
null
kernel/keyboard.hpp
mox692/mos
211b36dade615cfd43d3bb077703b82b638eec10
[ "Apache-2.0" ]
null
null
null
/** * @file keyboard.hpp * * キーボード制御プログラム. */ #pragma once #include <deque> #include "message.hpp" void InitializeKeyboard(std::deque<Message>& msg_queue);
12.538462
56
0.687117
mox692
4c6ce52e3b9443de9c0b7bd2c929337c06fd5fb9
11,495
cpp
C++
src/RcppExports.cpp
peekxc/clustertree
3c7cb80945067fd980a9f07a16dba7f8b1ad5907
[ "MIT" ]
6
2018-05-19T20:31:56.000Z
2021-11-28T09:10:33.000Z
src/RcppExports.cpp
peekxc/clustertree
3c7cb80945067fd980a9f07a16dba7f8b1ad5907
[ "MIT" ]
1
2018-05-19T20:31:44.000Z
2018-06-02T16:21:25.000Z
src/RcppExports.cpp
peekxc/clustertree
3c7cb80945067fd980a9f07a16dba7f8b1ad5907
[ "MIT" ]
1
2020-05-18T01:54:17.000Z
2020-05-18T01:54:17.000Z
// Generated by using Rcpp::compileAttributes() -> do not edit by hand // Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 #include <Rcpp.h> using namespace Rcpp; // normalizeIndices IntegerMatrix normalizeIndices(const IntegerMatrix& mst); RcppExport SEXP _clustertree_normalizeIndices(SEXP mstSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< const IntegerMatrix& >::type mst(mstSEXP); rcpp_result_gen = Rcpp::wrap(normalizeIndices(mst)); return rcpp_result_gen; END_RCPP } // mstToCC IntegerVector mstToCC(const IntegerMatrix& mst, const NumericVector& dist); RcppExport SEXP _clustertree_mstToCC(SEXP mstSEXP, SEXP distSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< const IntegerMatrix& >::type mst(mstSEXP); Rcpp::traits::input_parameter< const NumericVector& >::type dist(distSEXP); rcpp_result_gen = Rcpp::wrap(mstToCC(mst, dist)); return rcpp_result_gen; END_RCPP } // mstToHclust List mstToHclust(const IntegerMatrix& mst_, const NumericVector& dist); RcppExport SEXP _clustertree_mstToHclust(SEXP mst_SEXP, SEXP distSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< const IntegerMatrix& >::type mst_(mst_SEXP); Rcpp::traits::input_parameter< const NumericVector& >::type dist(distSEXP); rcpp_result_gen = Rcpp::wrap(mstToHclust(mst_, dist)); return rcpp_result_gen; END_RCPP } // hclustMergeOrder List hclustMergeOrder(const NumericMatrix& mst, const IntegerVector& o); RcppExport SEXP _clustertree_hclustMergeOrder(SEXP mstSEXP, SEXP oSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< const NumericMatrix& >::type mst(mstSEXP); Rcpp::traits::input_parameter< const IntegerVector& >::type o(oSEXP); rcpp_result_gen = Rcpp::wrap(hclustMergeOrder(mst, o)); return rcpp_result_gen; END_RCPP } // knn_dist NumericVector knn_dist(const NumericVector& dist_x, const int k); RcppExport SEXP _clustertree_knn_dist(SEXP dist_xSEXP, SEXP kSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< const NumericVector& >::type dist_x(dist_xSEXP); Rcpp::traits::input_parameter< const int >::type k(kSEXP); rcpp_result_gen = Rcpp::wrap(knn_dist(dist_x, k)); return rcpp_result_gen; END_RCPP } // knn_dist2 NumericVector knn_dist2(const NumericVector& dist_x, const int k); RcppExport SEXP _clustertree_knn_dist2(SEXP dist_xSEXP, SEXP kSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< const NumericVector& >::type dist_x(dist_xSEXP); Rcpp::traits::input_parameter< const int >::type k(kSEXP); rcpp_result_gen = Rcpp::wrap(knn_dist2(dist_x, k)); return rcpp_result_gen; END_RCPP } // chooseMetric_int SEXP chooseMetric_int(std::string metric_name, List config); RcppExport SEXP _clustertree_chooseMetric_int(SEXP metric_nameSEXP, SEXP configSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< std::string >::type metric_name(metric_nameSEXP); Rcpp::traits::input_parameter< List >::type config(configSEXP); rcpp_result_gen = Rcpp::wrap(chooseMetric_int(metric_name, config)); return rcpp_result_gen; END_RCPP } // primsCtree NumericMatrix primsCtree(const NumericVector r, const NumericVector r_k, const int n, const double alpha, const int type); RcppExport SEXP _clustertree_primsCtree(SEXP rSEXP, SEXP r_kSEXP, SEXP nSEXP, SEXP alphaSEXP, SEXP typeSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< const NumericVector >::type r(rSEXP); Rcpp::traits::input_parameter< const NumericVector >::type r_k(r_kSEXP); Rcpp::traits::input_parameter< const int >::type n(nSEXP); Rcpp::traits::input_parameter< const double >::type alpha(alphaSEXP); Rcpp::traits::input_parameter< const int >::type type(typeSEXP); rcpp_result_gen = Rcpp::wrap(primsCtree(r, r_k, n, alpha, type)); return rcpp_result_gen; END_RCPP } // naive_clustertree NumericMatrix naive_clustertree(const NumericVector& dist_x, const NumericVector& r_k, const int k, const double alpha, const int type); RcppExport SEXP _clustertree_naive_clustertree(SEXP dist_xSEXP, SEXP r_kSEXP, SEXP kSEXP, SEXP alphaSEXP, SEXP typeSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< const NumericVector& >::type dist_x(dist_xSEXP); Rcpp::traits::input_parameter< const NumericVector& >::type r_k(r_kSEXP); Rcpp::traits::input_parameter< const int >::type k(kSEXP); Rcpp::traits::input_parameter< const double >::type alpha(alphaSEXP); Rcpp::traits::input_parameter< const int >::type type(typeSEXP); rcpp_result_gen = Rcpp::wrap(naive_clustertree(dist_x, r_k, k, alpha, type)); return rcpp_result_gen; END_RCPP } // kd_knn List kd_knn(NumericMatrix query_x, SEXP tree_ptr, int k, bool priority); RcppExport SEXP _clustertree_kd_knn(SEXP query_xSEXP, SEXP tree_ptrSEXP, SEXP kSEXP, SEXP prioritySEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< NumericMatrix >::type query_x(query_xSEXP); Rcpp::traits::input_parameter< SEXP >::type tree_ptr(tree_ptrSEXP); Rcpp::traits::input_parameter< int >::type k(kSEXP); Rcpp::traits::input_parameter< bool >::type priority(prioritySEXP); rcpp_result_gen = Rcpp::wrap(kd_knn(query_x, tree_ptr, k, priority)); return rcpp_result_gen; END_RCPP } // kdtree List kdtree(NumericMatrix x, const int bkt_size); RcppExport SEXP _clustertree_kdtree(SEXP xSEXP, SEXP bkt_sizeSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< NumericMatrix >::type x(xSEXP); Rcpp::traits::input_parameter< const int >::type bkt_size(bkt_sizeSEXP); rcpp_result_gen = Rcpp::wrap(kdtree(x, bkt_size)); return rcpp_result_gen; END_RCPP } // kNN_int List kNN_int(const NumericMatrix& x, int k, int type, int bucketSize, int splitRule, double approx, NumericMatrix& r_x); RcppExport SEXP _clustertree_kNN_int(SEXP xSEXP, SEXP kSEXP, SEXP typeSEXP, SEXP bucketSizeSEXP, SEXP splitRuleSEXP, SEXP approxSEXP, SEXP r_xSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< const NumericMatrix& >::type x(xSEXP); Rcpp::traits::input_parameter< int >::type k(kSEXP); Rcpp::traits::input_parameter< int >::type type(typeSEXP); Rcpp::traits::input_parameter< int >::type bucketSize(bucketSizeSEXP); Rcpp::traits::input_parameter< int >::type splitRule(splitRuleSEXP); Rcpp::traits::input_parameter< double >::type approx(approxSEXP); Rcpp::traits::input_parameter< NumericMatrix& >::type r_x(r_xSEXP); rcpp_result_gen = Rcpp::wrap(kNN_int(x, k, type, bucketSize, splitRule, approx, r_x)); return rcpp_result_gen; END_RCPP } // mergeHeight NumericVector mergeHeight(List hcl); RcppExport SEXP _clustertree_mergeHeight(SEXP hclSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< List >::type hcl(hclSEXP); rcpp_result_gen = Rcpp::wrap(mergeHeight(hcl)); return rcpp_result_gen; END_RCPP } // kruskalsMST NumericMatrix kruskalsMST(const NumericVector dist_x); RcppExport SEXP _clustertree_kruskalsMST(SEXP dist_xSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< const NumericVector >::type dist_x(dist_xSEXP); rcpp_result_gen = Rcpp::wrap(kruskalsMST(dist_x)); return rcpp_result_gen; END_RCPP } // primsMST NumericMatrix primsMST(const NumericVector dist_x); RcppExport SEXP _clustertree_primsMST(SEXP dist_xSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< const NumericVector >::type dist_x(dist_xSEXP); rcpp_result_gen = Rcpp::wrap(primsMST(dist_x)); return rcpp_result_gen; END_RCPP } // cut_simplified_hclust IntegerVector cut_simplified_hclust(List hcl, IntegerVector cl_in, const int big_n); RcppExport SEXP _clustertree_cut_simplified_hclust(SEXP hclSEXP, SEXP cl_inSEXP, SEXP big_nSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< List >::type hcl(hclSEXP); Rcpp::traits::input_parameter< IntegerVector >::type cl_in(cl_inSEXP); Rcpp::traits::input_parameter< const int >::type big_n(big_nSEXP); rcpp_result_gen = Rcpp::wrap(cut_simplified_hclust(hcl, cl_in, big_n)); return rcpp_result_gen; END_RCPP } // simplified_hclust List simplified_hclust(List hcl, const int min_sz); RcppExport SEXP _clustertree_simplified_hclust(SEXP hclSEXP, SEXP min_szSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< List >::type hcl(hclSEXP); Rcpp::traits::input_parameter< const int >::type min_sz(min_szSEXP); rcpp_result_gen = Rcpp::wrap(simplified_hclust(hcl, min_sz)); return rcpp_result_gen; END_RCPP } // vol_nSphere double vol_nSphere(const int n, const double R); RcppExport SEXP _clustertree_vol_nSphere(SEXP nSEXP, SEXP RSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< const int >::type n(nSEXP); Rcpp::traits::input_parameter< const double >::type R(RSEXP); rcpp_result_gen = Rcpp::wrap(vol_nSphere(n, R)); return rcpp_result_gen; END_RCPP } static const R_CallMethodDef CallEntries[] = { {"_clustertree_normalizeIndices", (DL_FUNC) &_clustertree_normalizeIndices, 1}, {"_clustertree_mstToCC", (DL_FUNC) &_clustertree_mstToCC, 2}, {"_clustertree_mstToHclust", (DL_FUNC) &_clustertree_mstToHclust, 2}, {"_clustertree_hclustMergeOrder", (DL_FUNC) &_clustertree_hclustMergeOrder, 2}, {"_clustertree_knn_dist", (DL_FUNC) &_clustertree_knn_dist, 2}, {"_clustertree_knn_dist2", (DL_FUNC) &_clustertree_knn_dist2, 2}, {"_clustertree_chooseMetric_int", (DL_FUNC) &_clustertree_chooseMetric_int, 2}, {"_clustertree_primsCtree", (DL_FUNC) &_clustertree_primsCtree, 5}, {"_clustertree_naive_clustertree", (DL_FUNC) &_clustertree_naive_clustertree, 5}, {"_clustertree_kd_knn", (DL_FUNC) &_clustertree_kd_knn, 4}, {"_clustertree_kdtree", (DL_FUNC) &_clustertree_kdtree, 2}, {"_clustertree_kNN_int", (DL_FUNC) &_clustertree_kNN_int, 7}, {"_clustertree_mergeHeight", (DL_FUNC) &_clustertree_mergeHeight, 1}, {"_clustertree_kruskalsMST", (DL_FUNC) &_clustertree_kruskalsMST, 1}, {"_clustertree_primsMST", (DL_FUNC) &_clustertree_primsMST, 1}, {"_clustertree_cut_simplified_hclust", (DL_FUNC) &_clustertree_cut_simplified_hclust, 3}, {"_clustertree_simplified_hclust", (DL_FUNC) &_clustertree_simplified_hclust, 2}, {"_clustertree_vol_nSphere", (DL_FUNC) &_clustertree_vol_nSphere, 2}, {NULL, NULL, 0} }; RcppExport void R_init_clustertree(DllInfo *dll) { R_registerRoutines(dll, NULL, CallEntries, NULL, NULL); R_useDynamicSymbols(dll, FALSE); }
44.042146
149
0.762331
peekxc
4c6e81dbf53824b66fe0a3f5b00c2e88a212be88
688
cpp
C++
ejercicios clase/ejercicioGasolina(random).cpp
Trx21-5672/IMEC-8A-5672
ff4f0f4bcd61425a9eccba7be1fb646849360d45
[ "MIT" ]
null
null
null
ejercicios clase/ejercicioGasolina(random).cpp
Trx21-5672/IMEC-8A-5672
ff4f0f4bcd61425a9eccba7be1fb646849360d45
[ "MIT" ]
1
2020-04-05T03:13:08.000Z
2020-04-05T03:13:08.000Z
ejercicios clase/ejercicioGasolina(random).cpp
Trx21-5672/IMEC-8A-5672
ff4f0f4bcd61425a9eccba7be1fb646849360d45
[ "MIT" ]
null
null
null
#include <iostream> //random seed #include <cstdlib> #include <ctime> using namespace std; const int x1=12; const int x2=10; const int precio=19; int costo_final=0; int m = 0; int main(){ srand(time(NULL)); int lim_inf = 50; int lim_sup = 150; for (int i=0;i<2000;i++) { int velocidad = lim_inf + rand()%(lim_sup + 1 - lim_inf); m++; if (velocidad>100) costo_final=costo_final+(x1*precio); else costo_final=costo_final+(x2*precio); cout<<"el costo del combustible en el minuto "<<m<<" es "<<costo_final<<endl; } cout<<"el costo final del combustible es "<<costo_final<<endl; return 0; }
22.933333
85
0.597384
Trx21-5672
4c70e5bc85e0fe18a5d6562d8f6026087655db81
23,209
cpp
C++
DemoApps/Window/VulkanTriangle/source/VulkanTriangle.cpp
alexvonduar/gtec-demo-framework
6f8a7e429d0e15242ba64eb4cb41bfc2dd7dc749
[ "MIT", "BSD-3-Clause" ]
null
null
null
DemoApps/Window/VulkanTriangle/source/VulkanTriangle.cpp
alexvonduar/gtec-demo-framework
6f8a7e429d0e15242ba64eb4cb41bfc2dd7dc749
[ "MIT", "BSD-3-Clause" ]
null
null
null
DemoApps/Window/VulkanTriangle/source/VulkanTriangle.cpp
alexvonduar/gtec-demo-framework
6f8a7e429d0e15242ba64eb4cb41bfc2dd7dc749
[ "MIT", "BSD-3-Clause" ]
null
null
null
/** * The MIT License (MIT) * * Copyright (c) since 2014 Norbert Nopper * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ // Based on a sample by Norbert Nopper from VKTS Examples (VKTS_Sample02) // Recreated as a DemoFramework freestyle window sample by Freescale (2016) #include <FslBase/Log/Log3Fmt.hpp> #include <FslBase/Exceptions.hpp> #include <FslDemoHost/Base/Service/WindowHost/IWindowHostInfo.hpp> #include <FslNativeWindow/Vulkan/IVulkanNativeWindow.hpp> #include <FslUtil/Vulkan1_0/TypeConverter.hpp> #include <FslUtil/Vulkan1_0/Exceptions.hpp> #include <FslUtil/Vulkan1_0/SurfaceFormatInfo.hpp> #include <FslUtil/Vulkan1_0/Util/MemoryTypeUtil.hpp> #include <FslUtil/Vulkan1_0/Util/SwapchainKHRUtil.hpp> #include <RapidVulkan/Check.hpp> #include "VulkanTriangle.hpp" #include <vulkan/vulkan.h> #include <array> #include <cstring> namespace Fsl { namespace { const std::size_t VKTS_NUMBER_BUFFERS = 2; const auto VKTS_VERTEX_SHADER_NAME = "vertex_only_ndc.vert.spv"; const auto VKTS_FRAGMENT_SHADER_NAME = "red.frag.spv"; } VulkanTriangle::VulkanTriangle(const DemoAppConfig& config) : VulkanWindowDemoApp(config) { FSLLOG3_INFO("VulkanTriangle app creating"); m_commandPool.Reset(m_device.Get(), 0, m_deviceQueue.QueueFamilyIndex); BuildVertexBuffer(); BuildShader(); BuildPipelineLayout(); BuildResources(); m_imageAcquiredSemaphore.Reset(m_device.Get(), 0); m_renderingCompleteSemaphore.Reset(m_device.Get(), 0); FSLLOG3_INFO("VulkanTriangle app created"); } VulkanTriangle::~VulkanTriangle() { try { // Wait for everything to be idle before we try to free it FSLLOG3_INFO("VulkanTriangle app destroying"); } catch (const std::exception& ex) { // We log and swallow it since destructor's are not allowed to throw FSLLOG3_ERROR("Exception during destruction: {}", ex.what()); } } void VulkanTriangle::Update(const DemoTime& /*demoTime*/) { } void VulkanTriangle::Draw(const DemoTime& /*demoTime*/) { VkResult result = VK_SUCCESS; // FIX: hasCurrentExtentChanged missing, is this important? // if (surface->hasCurrentExtentChanged(physicalDevice->getPhysicalDevice())) //{ // const auto& currentExtent = surface->getCurrentExtent(physicalDevice->getPhysicalDevice(), VK_FALSE); // if (currentExtent.width == 0 || currentExtent.height == 0) // { // return VK_TRUE; // } // result = VK_ERROR_OUT_OF_DATE_KHR; //} //// uint32_t currentBuffer = 0; if (result == VK_SUCCESS) { result = vkAcquireNextImageKHR(m_device.Get(), m_swapchain.Get(), UINT64_MAX, m_imageAcquiredSemaphore.Get(), VK_NULL_HANDLE, &currentBuffer); } if (!(result == VK_SUCCESS || result == VK_SUBOPTIMAL_KHR)) { if (result == VK_ERROR_OUT_OF_DATE_KHR) { // TODO: support 'soft restart' FSLLOG3_INFO("Restaring app due to VK_ERROR_OUT_OF_DATE_KHR"); GetDemoAppControl()->RequestAppRestart(); return; } throw std::runtime_error("Could not acquire next image."); } const VkSemaphore waitSemaphores = m_imageAcquiredSemaphore.Get(); const VkSemaphore signalSemaphores = m_renderingCompleteSemaphore.Get(); const VkPipelineStageFlags waitDstStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; VkSubmitInfo submitInfo{}; submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; submitInfo.waitSemaphoreCount = 1; submitInfo.pWaitSemaphores = &waitSemaphores; submitInfo.pWaitDstStageMask = &waitDstStageMask; submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = m_cmdBuffer[currentBuffer].GetPointer(); submitInfo.signalSemaphoreCount = 1; submitInfo.pSignalSemaphores = &signalSemaphores; m_deviceQueue.Submit(1, &submitInfo, VK_NULL_HANDLE); result = m_swapchain.TryQueuePresent(m_deviceQueue.Queue, 1, &signalSemaphores, &currentBuffer, nullptr); if (result == VK_SUCCESS || result == VK_SUBOPTIMAL_KHR) { m_deviceQueue.WaitIdle(); } else { if (result == VK_ERROR_OUT_OF_DATE_KHR) { // TODO: support 'soft restart' FSLLOG3_INFO("Restaring app due to VK_ERROR_OUT_OF_DATE_KHR"); GetDemoAppControl()->RequestAppRestart(); return; } throw std::runtime_error("Could not present queue"); } } void VulkanTriangle::BuildVertexBuffer() { // Window clip origin is upper left. // NOLINTNEXTLINE(modernize-avoid-c-arrays) static const float vertices[3 * 4] = {-0.5f, 0.5f, 0.0f, 1.0f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, -0.5f, 0.0f, 1.0f}; VkBufferCreateInfo bufferCreateInfo{}; bufferCreateInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; bufferCreateInfo.flags = 0; bufferCreateInfo.size = sizeof(vertices); bufferCreateInfo.usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT; bufferCreateInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; bufferCreateInfo.queueFamilyIndexCount = 0; bufferCreateInfo.pQueueFamilyIndices = nullptr; m_vertexBuffer.Reset(m_device.Get(), bufferCreateInfo); VkMemoryRequirements memoryRequirements = m_vertexBuffer.GetBufferMemoryRequirements(); VkPhysicalDeviceMemoryProperties physicalDeviceMemoryProperties = m_physicalDevice.MemoryProperties; const auto memoryTypeIndex = Vulkan::MemoryTypeUtil::GetMemoryTypeIndex(physicalDeviceMemoryProperties, memoryRequirements.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT); m_deviceMemoryVertexBuffer.Reset(m_device.Get(), memoryRequirements.size, memoryTypeIndex); void* mappedData = nullptr; // TODO: (Improvement) Use a scoped map memory command since it would be exception safe RAPIDVULKAN_CHECK(vkMapMemory(m_deviceMemoryVertexBuffer.GetDevice(), m_deviceMemoryVertexBuffer.Get(), 0, sizeof(vertices), 0, &mappedData)); { std::memcpy(mappedData, vertices, sizeof(vertices)); if ((physicalDeviceMemoryProperties.memoryTypes[memoryTypeIndex].propertyFlags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) == 0u) { VkMappedMemoryRange mappedMemoryRange{}; mappedMemoryRange.sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE; mappedMemoryRange.memory = m_deviceMemoryVertexBuffer.Get(); mappedMemoryRange.offset = 0; mappedMemoryRange.size = sizeof(vertices); RAPIDVULKAN_CHECK(vkFlushMappedMemoryRanges(m_deviceMemoryVertexBuffer.GetDevice(), 1, &mappedMemoryRange)); } } vkUnmapMemory(m_deviceMemoryVertexBuffer.GetDevice(), m_deviceMemoryVertexBuffer.Get()); RAPIDVULKAN_CHECK(vkBindBufferMemory(m_device.Get(), m_vertexBuffer.Get(), m_deviceMemoryVertexBuffer.Get(), 0)); } void VulkanTriangle::BuildShader() { const auto vertexShaderBinary = GetContentManager()->ReadBytes(VKTS_VERTEX_SHADER_NAME); const auto fragmentShaderBinary = GetContentManager()->ReadBytes(VKTS_FRAGMENT_SHADER_NAME); m_vertexShaderModule.Reset(m_device.Get(), 0, vertexShaderBinary.size(), reinterpret_cast<const uint32_t*>(vertexShaderBinary.data())); m_fragmentShaderModule.Reset(m_device.Get(), 0, fragmentShaderBinary.size(), reinterpret_cast<const uint32_t*>(fragmentShaderBinary.data())); } void VulkanTriangle::BuildPipelineLayout() { m_pipelineLayout.Reset(m_device.Get(), 0, 0, nullptr, 0, nullptr); } void VulkanTriangle::BuildResources() { auto fallbackExtent = TypeConverter::UncheckedTo<VkExtent2D>(GetScreenExtent()); m_swapchain = Vulkan::SwapchainKHRUtil::CreateSwapchain( m_physicalDevice.Device, m_device.Get(), 0, m_surface, VKTS_NUMBER_BUFFERS, 1, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, VK_SHARING_MODE_EXCLUSIVE, 0, nullptr, VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR, VK_TRUE, m_swapchain.Get(), fallbackExtent, Vulkan::SurfaceFormatInfo()); uint32_t swapchainImagesCount = m_swapchain.GetImageCount(); if (swapchainImagesCount == 0) { throw std::runtime_error("We need at least one image in the swapchain"); } m_swapchainImageView.clear(); m_framebuffer.clear(); m_cmdBuffer.clear(); m_swapchainImageView.resize(swapchainImagesCount); m_framebuffer.resize(swapchainImagesCount); m_cmdBuffer.resize(swapchainImagesCount); BuildRenderPass(); BuildPipeline(); for (uint32_t i = 0; i < swapchainImagesCount; ++i) { BuildSwapchainImageView(i); BuildFramebuffer(i); BuildCmdBuffer(i); } } void VulkanTriangle::BuildRenderPass() { VkAttachmentDescription attachmentDescription{}; attachmentDescription.flags = 0; attachmentDescription.format = m_swapchain.GetImageFormat(); attachmentDescription.samples = VK_SAMPLE_COUNT_1_BIT; attachmentDescription.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; attachmentDescription.storeOp = VK_ATTACHMENT_STORE_OP_STORE; attachmentDescription.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; attachmentDescription.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; attachmentDescription.initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; attachmentDescription.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; VkAttachmentReference colorAttachmentReference{}; colorAttachmentReference.attachment = 0; colorAttachmentReference.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; VkSubpassDescription subpassDescription{}; subpassDescription.flags = 0; subpassDescription.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; subpassDescription.inputAttachmentCount = 0; subpassDescription.pInputAttachments = nullptr; subpassDescription.colorAttachmentCount = 1; subpassDescription.pColorAttachments = &colorAttachmentReference; subpassDescription.pResolveAttachments = nullptr; subpassDescription.pDepthStencilAttachment = nullptr; subpassDescription.preserveAttachmentCount = 0; subpassDescription.pPreserveAttachments = nullptr; m_renderPass.Reset(m_device.Get(), 0, 1, &attachmentDescription, 1, &subpassDescription, 0, nullptr); } void VulkanTriangle::BuildPipeline() { std::array<VkPipelineShaderStageCreateInfo, 2> pipelineShaderStageCreateInfo{}; pipelineShaderStageCreateInfo[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; pipelineShaderStageCreateInfo[0].flags = 0; pipelineShaderStageCreateInfo[0].stage = VK_SHADER_STAGE_VERTEX_BIT; pipelineShaderStageCreateInfo[0].module = m_vertexShaderModule.Get(); pipelineShaderStageCreateInfo[0].pName = "main"; pipelineShaderStageCreateInfo[0].pSpecializationInfo = nullptr; pipelineShaderStageCreateInfo[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; pipelineShaderStageCreateInfo[1].flags = 0; pipelineShaderStageCreateInfo[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT; pipelineShaderStageCreateInfo[1].module = m_fragmentShaderModule.Get(); pipelineShaderStageCreateInfo[1].pName = "main"; pipelineShaderStageCreateInfo[1].pSpecializationInfo = nullptr; VkVertexInputBindingDescription vertexInputBindingDescription{}; vertexInputBindingDescription.binding = 0; vertexInputBindingDescription.stride = 4 * sizeof(float); vertexInputBindingDescription.inputRate = VK_VERTEX_INPUT_RATE_VERTEX; VkVertexInputAttributeDescription vertexInputAttributeDescription{}; vertexInputAttributeDescription.location = 0; vertexInputAttributeDescription.binding = 0; vertexInputAttributeDescription.format = VK_FORMAT_R32G32B32A32_SFLOAT; vertexInputAttributeDescription.offset = 0; VkPipelineVertexInputStateCreateInfo pipelineVertexInputCreateInfo{}; pipelineVertexInputCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; pipelineVertexInputCreateInfo.flags = 0; pipelineVertexInputCreateInfo.vertexBindingDescriptionCount = 1; pipelineVertexInputCreateInfo.pVertexBindingDescriptions = &vertexInputBindingDescription; pipelineVertexInputCreateInfo.vertexAttributeDescriptionCount = 1; pipelineVertexInputCreateInfo.pVertexAttributeDescriptions = &vertexInputAttributeDescription; VkPipelineInputAssemblyStateCreateInfo pipelineInputAssemblyStateCreateInfo{}; pipelineInputAssemblyStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; pipelineInputAssemblyStateCreateInfo.flags = 0; pipelineInputAssemblyStateCreateInfo.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; pipelineInputAssemblyStateCreateInfo.primitiveRestartEnable = VK_FALSE; VkViewport viewport{}; viewport.x = 0.0f; viewport.y = 0.0f; viewport.width = static_cast<float>(m_swapchain.GetImageExtent().width); viewport.height = static_cast<float>(m_swapchain.GetImageExtent().height); viewport.minDepth = 0.0f; viewport.maxDepth = 1.0f; VkRect2D scissor{}; scissor.offset.x = 0; scissor.offset.y = 0; scissor.extent = m_swapchain.GetImageExtent(); VkPipelineViewportStateCreateInfo pipelineViewportStateCreateInfo{}; pipelineViewportStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; pipelineViewportStateCreateInfo.flags = 0; pipelineViewportStateCreateInfo.viewportCount = 1; pipelineViewportStateCreateInfo.pViewports = &viewport; pipelineViewportStateCreateInfo.scissorCount = 1; pipelineViewportStateCreateInfo.pScissors = &scissor; VkPipelineRasterizationStateCreateInfo pipelineRasterizationStateCreateInfo{}; pipelineRasterizationStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; pipelineRasterizationStateCreateInfo.flags = 0; pipelineRasterizationStateCreateInfo.depthClampEnable = VK_FALSE; pipelineRasterizationStateCreateInfo.rasterizerDiscardEnable = VK_FALSE; pipelineRasterizationStateCreateInfo.polygonMode = VK_POLYGON_MODE_FILL; pipelineRasterizationStateCreateInfo.cullMode = VK_CULL_MODE_NONE; pipelineRasterizationStateCreateInfo.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE; pipelineRasterizationStateCreateInfo.depthBiasEnable = VK_FALSE; pipelineRasterizationStateCreateInfo.depthBiasConstantFactor = 0.0f; pipelineRasterizationStateCreateInfo.depthBiasClamp = 0.0f; pipelineRasterizationStateCreateInfo.depthBiasSlopeFactor = 0.0f; pipelineRasterizationStateCreateInfo.lineWidth = 1.0f; VkPipelineMultisampleStateCreateInfo pipelineMultisampleStateCreateInfo{}; pipelineMultisampleStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; pipelineMultisampleStateCreateInfo.flags = 0; pipelineMultisampleStateCreateInfo.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; pipelineMultisampleStateCreateInfo.sampleShadingEnable = VK_FALSE; pipelineMultisampleStateCreateInfo.minSampleShading = 0.0f; pipelineMultisampleStateCreateInfo.pSampleMask = nullptr; pipelineMultisampleStateCreateInfo.alphaToCoverageEnable = VK_FALSE; pipelineMultisampleStateCreateInfo.alphaToOneEnable = VK_FALSE; VkPipelineColorBlendAttachmentState pipelineColorBlendAttachmentState{}; pipelineColorBlendAttachmentState.blendEnable = VK_FALSE; pipelineColorBlendAttachmentState.srcColorBlendFactor = VK_BLEND_FACTOR_ZERO; pipelineColorBlendAttachmentState.dstColorBlendFactor = VK_BLEND_FACTOR_ZERO; pipelineColorBlendAttachmentState.colorBlendOp = VK_BLEND_OP_ADD; pipelineColorBlendAttachmentState.srcAlphaBlendFactor = VK_BLEND_FACTOR_ZERO; pipelineColorBlendAttachmentState.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO; pipelineColorBlendAttachmentState.alphaBlendOp = VK_BLEND_OP_ADD; pipelineColorBlendAttachmentState.colorWriteMask = 0xf; VkPipelineColorBlendStateCreateInfo pipelineColorBlendStateCreateInfo{}; pipelineColorBlendStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; pipelineColorBlendStateCreateInfo.flags = 0; pipelineColorBlendStateCreateInfo.logicOpEnable = VK_FALSE; pipelineColorBlendStateCreateInfo.logicOp = VK_LOGIC_OP_COPY; pipelineColorBlendStateCreateInfo.attachmentCount = 1; pipelineColorBlendStateCreateInfo.pAttachments = &pipelineColorBlendAttachmentState; pipelineColorBlendStateCreateInfo.blendConstants[0] = 0.0f; pipelineColorBlendStateCreateInfo.blendConstants[1] = 0.0f; pipelineColorBlendStateCreateInfo.blendConstants[2] = 0.0f; pipelineColorBlendStateCreateInfo.blendConstants[3] = 0.0f; std::array<VkDynamicState, 2> dynamicState = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; VkPipelineDynamicStateCreateInfo pipelineDynamicStateCreateInfo{}; pipelineDynamicStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO; pipelineDynamicStateCreateInfo.flags = 0; pipelineDynamicStateCreateInfo.dynamicStateCount = static_cast<uint32_t>(dynamicState.size()); pipelineDynamicStateCreateInfo.pDynamicStates = dynamicState.data(); VkGraphicsPipelineCreateInfo graphicsPipelineCreateInfo{}; graphicsPipelineCreateInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; graphicsPipelineCreateInfo.flags = 0; graphicsPipelineCreateInfo.stageCount = static_cast<uint32_t>(pipelineShaderStageCreateInfo.size()); graphicsPipelineCreateInfo.pStages = pipelineShaderStageCreateInfo.data(); graphicsPipelineCreateInfo.pVertexInputState = &pipelineVertexInputCreateInfo; graphicsPipelineCreateInfo.pInputAssemblyState = &pipelineInputAssemblyStateCreateInfo; graphicsPipelineCreateInfo.pTessellationState = nullptr; graphicsPipelineCreateInfo.pViewportState = &pipelineViewportStateCreateInfo; graphicsPipelineCreateInfo.pRasterizationState = &pipelineRasterizationStateCreateInfo; graphicsPipelineCreateInfo.pMultisampleState = &pipelineMultisampleStateCreateInfo; graphicsPipelineCreateInfo.pDepthStencilState = nullptr; graphicsPipelineCreateInfo.pColorBlendState = &pipelineColorBlendStateCreateInfo; graphicsPipelineCreateInfo.pDynamicState = &pipelineDynamicStateCreateInfo; graphicsPipelineCreateInfo.layout = m_pipelineLayout.Get(); graphicsPipelineCreateInfo.renderPass = m_renderPass.Get(); graphicsPipelineCreateInfo.subpass = 0; graphicsPipelineCreateInfo.basePipelineHandle = VK_NULL_HANDLE; graphicsPipelineCreateInfo.basePipelineIndex = 0; m_pipeline.Reset(m_device.Get(), VK_NULL_HANDLE, graphicsPipelineCreateInfo); } void VulkanTriangle::BuildSwapchainImageView(const uint32_t bufferIndex) { VkComponentMapping componentMapping = {VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_G, VK_COMPONENT_SWIZZLE_B, VK_COMPONENT_SWIZZLE_A}; VkImageSubresourceRange imageSubresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; m_swapchainImageView[bufferIndex].Reset(m_device.Get(), 0, m_swapchain[bufferIndex], VK_IMAGE_VIEW_TYPE_2D, m_swapchain.GetImageFormat(), componentMapping, imageSubresourceRange); } void VulkanTriangle::BuildFramebuffer(const uint32_t bufferIndex) { VkImageView imageView = m_swapchainImageView[bufferIndex].Get(); m_framebuffer[bufferIndex].Reset(m_device.Get(), 0, m_renderPass.Get(), 1, &imageView, m_swapchain.GetImageExtent().width, m_swapchain.GetImageExtent().height, 1); } void VulkanTriangle::BuildCmdBuffer(const uint32_t bufferIndex) { m_cmdBuffer[bufferIndex].Reset(m_device.Get(), m_commandPool.Get(), VK_COMMAND_BUFFER_LEVEL_PRIMARY); m_cmdBuffer[bufferIndex].Begin(0, VK_NULL_HANDLE, 0, VK_NULL_HANDLE, VK_FALSE, 0, 0); { m_swapchain.CmdPipelineBarrier(m_cmdBuffer[bufferIndex].Get(), VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, bufferIndex); std::array<VkClearValue, 1> clearValues{}; clearValues[0].color = {{0.0f, 0.0f, 1.0f, 1.0f}}; VkRenderPassBeginInfo renderPassBeginInfo{}; renderPassBeginInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; renderPassBeginInfo.renderPass = m_renderPass.Get(); renderPassBeginInfo.framebuffer = m_framebuffer[bufferIndex].Get(); renderPassBeginInfo.renderArea.offset.x = 0; renderPassBeginInfo.renderArea.offset.y = 0; renderPassBeginInfo.renderArea.extent = m_swapchain.GetImageExtent(); renderPassBeginInfo.clearValueCount = static_cast<uint32_t>(clearValues.size()); renderPassBeginInfo.pClearValues = clearValues.data(); m_cmdBuffer[bufferIndex].CmdBeginRenderPass(&renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE); { vkCmdBindPipeline(m_cmdBuffer[bufferIndex].Get(), VK_PIPELINE_BIND_POINT_GRAPHICS, m_pipeline.Get()); VkViewport viewport{}; viewport.x = 0.0f; viewport.y = 0.0f; viewport.width = static_cast<float>(m_swapchain.GetImageExtent().width); viewport.height = static_cast<float>(m_swapchain.GetImageExtent().height); viewport.minDepth = 0.0f; viewport.maxDepth = 1.0f; vkCmdSetViewport(m_cmdBuffer[bufferIndex].Get(), 0, 1, &viewport); VkRect2D scissor{}; scissor.offset.x = 0; scissor.offset.y = 0; scissor.extent = m_swapchain.GetImageExtent(); vkCmdSetScissor(m_cmdBuffer[bufferIndex].Get(), 0, 1, &scissor); std::array<VkDeviceSize, 1> offsets = {0}; VkBuffer vertexBuffer = m_vertexBuffer.Get(); vkCmdBindVertexBuffers(m_cmdBuffer[bufferIndex].Get(), 0, static_cast<uint32_t>(offsets.size()), &vertexBuffer, offsets.data()); vkCmdDraw(m_cmdBuffer[bufferIndex].Get(), 3, 1, 0, 0); } m_cmdBuffer[bufferIndex].CmdEndRenderPass(); m_swapchain.CmdPipelineBarrier(m_cmdBuffer[bufferIndex].Get(), VK_ACCESS_MEMORY_READ_BIT, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, bufferIndex); } m_cmdBuffer[bufferIndex].End(); } }
45.507843
148
0.771726
alexvonduar
4c73421a95332d31f572c343c9e36e226c2eddbe
267
cc
C++
L1Trigger/DemonstratorTools/src/LinkId.cc
PKUfudawei/cmssw
8fbb5ce74398269c8a32956d7c7943766770c093
[ "Apache-2.0" ]
2
2018-06-01T05:18:55.000Z
2021-04-08T21:44:06.000Z
L1Trigger/DemonstratorTools/src/LinkId.cc
PKUfudawei/cmssw
8fbb5ce74398269c8a32956d7c7943766770c093
[ "Apache-2.0" ]
26
2018-10-30T12:47:58.000Z
2022-03-29T08:39:00.000Z
L1Trigger/DemonstratorTools/src/LinkId.cc
PKUfudawei/cmssw
8fbb5ce74398269c8a32956d7c7943766770c093
[ "Apache-2.0" ]
1
2021-11-30T16:16:05.000Z
2021-11-30T16:16:05.000Z
#include "L1Trigger/DemonstratorTools/interface/LinkId.h" namespace l1t::demo { bool operator<(const LinkId& x, const LinkId& y) { int c = x.interface.compare(y.interface); return c == 0 ? (x.channel < y.channel) : (c < 0); } } // namespace l1t::demo
24.272727
57
0.651685
PKUfudawei
dbc8a8d1ebce122a4794f37b992e534ddb1cd498
4,370
hh
C++
servicesim_competition/src/Checkpoint.hh
raymondchaneee/servicesim
9e1c827aa0022d3f3c188be7d2ccf1ed20391d09
[ "Apache-2.0" ]
6
2020-05-03T01:27:45.000Z
2021-12-14T06:36:48.000Z
servicesim_competition/src/Checkpoint.hh
raymondchaneee/servicesim
9e1c827aa0022d3f3c188be7d2ccf1ed20391d09
[ "Apache-2.0" ]
1
2021-04-19T14:24:26.000Z
2021-04-19T14:24:26.000Z
servicesim_competition/src/Checkpoint.hh
raymondchaneee/servicesim
9e1c827aa0022d3f3c188be7d2ccf1ed20391d09
[ "Apache-2.0" ]
6
2020-06-15T14:34:18.000Z
2021-09-28T19:50:17.000Z
/* * Copyright (C) 2018 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef SERVICESIM_CHECKPOINT_HH_ #define SERVICESIM_CHECKPOINT_HH_ #include <sdf/sdf.hh> #include <ignition/math/Pose3.hh> #include <ignition/msgs/boolean.pb.h> #include <ignition/transport/Node.hh> #include <gazebo/common/Time.hh> namespace servicesim { class Checkpoint { /// \brief Constructor /// \param[in] _sdf SDF element with configuration for this checkpoint. public: Checkpoint(const sdf::ElementPtr &_sdf); /// \brief Default destructor public: virtual ~Checkpoint() = default; /// \brief Check whether checkpoint has been completed. /// Any publishers or subscribers should be created the first time this is /// called, and cleaned up once it returns true. /// \return True if completed. public: virtual bool Check() = 0; /// \brief Check whether to pause this checkpoint and return to the /// previous one. /// \return True if it should pause. public: bool Paused() const; /// \brief Check whether the checkpoint has started at least once /// \return True if it has started. public: bool Started() const; /// \brief Call this the first time the checkpoint is checked. public: void Start(); /// \brief Get the current score for this checkpoint. /// \return Score public: virtual double Score() const; /// \brief Get the checkpoint's name /// \return Checkpoint's name public: std::string Name() const; /// \brief Pause the checkpoint, ending the current interval. Only works if /// canPause is true. protected: void Pause(); /// \brief Set if this checkpoint is done. It also registers the time when /// it was done. /// \param[in] _done True if done protected: void SetDone(const bool _done); /// \brief Get whether this checkpoint is done /// \return True if done. protected: bool Done() const; /// \brief The total penalty for this checkpoint protected: double penalty{0.0}; /// \brief The weight for this checkpoint's time when scoring. protected: double weightTime{0.0}; /// \brief The checkpoint's name protected: std::string name; /// \brief True if it's possible to restart the checkpoint. protected: bool canPause{false}; /// \brief Vector of sim time intervals when the checkpoint was /// running. The first time is the beginning of the interval, the /// second is the end private: std::vector<std::pair<gazebo::common::Time, gazebo::common::Time>> intervals; /// \brief True when checkpoint is complete. private: bool done{false}; /// \brief True when checkpoint is paused. private: bool paused{false}; }; /// \brief A checkpoint tied to a gazebo::ContainPlugin. class ContainCheckpoint : public Checkpoint { /// \brief Constructor /// \param[in] _sdf SDF element for this checkpoint. public: ContainCheckpoint(const sdf::ElementPtr &_sdf); /// \brief Check whether the contain checkpoint has been completed. /// \return True if completed. protected: bool Check() override; /// \brief Callback when messages are received from the ContainPlugin. /// \param[in] _msg True if contains. private: void OnContain(const ignition::msgs::Boolean &_msg); /// \brief Callabck for enable service /// \param[in] _rep Response /// \param[in] _result Result private: void EnableCallback(const ignition::msgs::Boolean &_rep, const bool _result); /// \brief Ignition transport node for communication. protected: ignition::transport::Node ignNode; /// \brief Namespace for transport protected: std::string ns; /// \brief True if enabled private: bool enabled{false}; }; } #endif
32.61194
79
0.680092
raymondchaneee
dbc8cab1f94ce579405de1bcc93c6ba27638dd17
30,636
cc
C++
third_party/blink/renderer/core/inspector/inspector_emulation_agent.cc
Yannic/chromium
ab32e8aacb08c9fce0dc4bf09eec456ba46e3710
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
76
2020-09-02T03:05:41.000Z
2022-03-30T04:40:55.000Z
third_party/blink/renderer/core/inspector/inspector_emulation_agent.cc
blueboxd/chromium-legacy
07223bc94bd97499909c9ed3c3f5769d718fe2e0
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
45
2020-09-02T03:21:37.000Z
2022-03-31T22:19:45.000Z
third_party/blink/renderer/core/inspector/inspector_emulation_agent.cc
Yannic/chromium
ab32e8aacb08c9fce0dc4bf09eec456ba46e3710
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
8
2020-07-22T18:49:18.000Z
2022-02-08T10:27:16.000Z
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/core/inspector/inspector_emulation_agent.h" #include "third_party/blink/public/common/input/web_touch_event.h" #include "third_party/blink/public/platform/platform.h" #include "third_party/blink/renderer/core/css/vision_deficiency.h" #include "third_party/blink/renderer/core/exported/web_view_impl.h" #include "third_party/blink/renderer/core/frame/local_frame_view.h" #include "third_party/blink/renderer/core/frame/settings.h" #include "third_party/blink/renderer/core/frame/web_local_frame_impl.h" #include "third_party/blink/renderer/core/inspector/dev_tools_emulator.h" #include "third_party/blink/renderer/core/inspector/locale_controller.h" #include "third_party/blink/renderer/core/inspector/protocol/DOM.h" #include "third_party/blink/renderer/core/loader/document_loader.h" #include "third_party/blink/renderer/core/page/focus_controller.h" #include "third_party/blink/renderer/core/page/page.h" #include "third_party/blink/renderer/platform/geometry/double_rect.h" #include "third_party/blink/renderer/platform/graphics/color.h" #include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h" #include "third_party/blink/renderer/platform/loader/fetch/loader_freeze_mode.h" #include "third_party/blink/renderer/platform/loader/fetch/resource.h" #include "third_party/blink/renderer/platform/loader/fetch/resource_request.h" #include "third_party/blink/renderer/platform/loader/fetch/url_loader/request_conversion.h" #include "third_party/blink/renderer/platform/network/network_utils.h" #include "third_party/blink/renderer/platform/scheduler/public/thread.h" #include "third_party/blink/renderer/platform/scheduler/public/thread_cpu_throttler.h" namespace blink { using protocol::Maybe; using protocol::Response; InspectorEmulationAgent::InspectorEmulationAgent( WebLocalFrameImpl* web_local_frame_impl) : web_local_frame_(web_local_frame_impl), default_background_color_override_rgba_(&agent_state_, /*default_value=*/{}), script_execution_disabled_(&agent_state_, /*default_value=*/false), scrollbars_hidden_(&agent_state_, /*default_value=*/false), document_cookie_disabled_(&agent_state_, /*default_value=*/false), touch_event_emulation_enabled_(&agent_state_, /*default_value=*/false), max_touch_points_(&agent_state_, /*default_value=*/1), emulated_media_(&agent_state_, /*default_value=*/WTF::String()), emulated_media_features_(&agent_state_, /*default_value=*/WTF::String()), emulated_vision_deficiency_(&agent_state_, /*default_value=*/WTF::String()), navigator_platform_override_(&agent_state_, /*default_value=*/WTF::String()), user_agent_override_(&agent_state_, /*default_value=*/WTF::String()), serialized_ua_metadata_override_( &agent_state_, /*default_value=*/std::vector<uint8_t>()), accept_language_override_(&agent_state_, /*default_value=*/WTF::String()), locale_override_(&agent_state_, /*default_value=*/WTF::String()), virtual_time_budget_(&agent_state_, /*default_value*/ 0.0), initial_virtual_time_(&agent_state_, /*default_value=*/0.0), virtual_time_policy_(&agent_state_, /*default_value=*/WTF::String()), virtual_time_task_starvation_count_(&agent_state_, /*default_value=*/0), wait_for_navigation_(&agent_state_, /*default_value=*/false), emulate_focus_(&agent_state_, /*default_value=*/false), emulate_auto_dark_mode_(&agent_state_, /*default_value=*/false), auto_dark_mode_override_(&agent_state_, /*default_value=*/false), timezone_id_override_(&agent_state_, /*default_value=*/WTF::String()), disabled_image_types_(&agent_state_, /*default_value=*/false) {} InspectorEmulationAgent::~InspectorEmulationAgent() = default; WebViewImpl* InspectorEmulationAgent::GetWebViewImpl() { return web_local_frame_ ? web_local_frame_->ViewImpl() : nullptr; } void InspectorEmulationAgent::Restore() { // Since serialized_ua_metadata_override_ can't directly be converted back // to appropriate protocol message, we initially pass null and decode it // directly. std::vector<uint8_t> save_serialized_ua_metadata_override = serialized_ua_metadata_override_.Get(); setUserAgentOverride( user_agent_override_.Get(), accept_language_override_.Get(), navigator_platform_override_.Get(), protocol::Maybe<protocol::Emulation::UserAgentMetadata>()); ua_metadata_override_ = blink::UserAgentMetadata::Demarshal(std::string( reinterpret_cast<char*>(save_serialized_ua_metadata_override.data()), save_serialized_ua_metadata_override.size())); serialized_ua_metadata_override_.Set(save_serialized_ua_metadata_override); if (!locale_override_.Get().IsEmpty()) setLocaleOverride(locale_override_.Get()); if (!web_local_frame_) return; // Following code only runs for pages. if (script_execution_disabled_.Get()) GetWebViewImpl()->GetDevToolsEmulator()->SetScriptExecutionDisabled(true); if (scrollbars_hidden_.Get()) GetWebViewImpl()->GetDevToolsEmulator()->SetScrollbarsHidden(true); if (document_cookie_disabled_.Get()) GetWebViewImpl()->GetDevToolsEmulator()->SetDocumentCookieDisabled(true); setTouchEmulationEnabled(touch_event_emulation_enabled_.Get(), max_touch_points_.Get()); auto features = std::make_unique<protocol::Array<protocol::Emulation::MediaFeature>>(); for (auto const& name : emulated_media_features_.Keys()) { auto const& value = emulated_media_features_.Get(name); features->push_back(protocol::Emulation::MediaFeature::create() .setName(name) .setValue(value) .build()); } setEmulatedMedia(emulated_media_.Get(), std::move(features)); if (!emulated_vision_deficiency_.Get().IsNull()) setEmulatedVisionDeficiency(emulated_vision_deficiency_.Get()); auto status_or_rgba = protocol::DOM::RGBA::ReadFrom( default_background_color_override_rgba_.Get()); if (status_or_rgba.ok()) setDefaultBackgroundColorOverride(std::move(status_or_rgba).value()); setFocusEmulationEnabled(emulate_focus_.Get()); if (emulate_auto_dark_mode_.Get()) setAutoDarkModeOverride(auto_dark_mode_override_.Get()); if (!timezone_id_override_.Get().IsNull()) setTimezoneOverride(timezone_id_override_.Get()); if (virtual_time_policy_.Get().IsNull()) return; // Preserve wait for navigation in all modes. bool wait_for_navigation = wait_for_navigation_.Get(); // Reinstate the stored policy. double virtual_time_ticks_base_ms; // For Pause, do not pass budget or starvation count. if (virtual_time_policy_.Get() == protocol::Emulation::VirtualTimePolicyEnum::Pause) { setVirtualTimePolicy(protocol::Emulation::VirtualTimePolicyEnum::Pause, Maybe<double>(), Maybe<int>(), wait_for_navigation, initial_virtual_time_.Get(), &virtual_time_ticks_base_ms); return; } // Calculate remaining budget for the advancing modes. double budget_remaining = virtual_time_budget_.Get(); DCHECK_GE(budget_remaining, 0); setVirtualTimePolicy(virtual_time_policy_.Get(), budget_remaining, virtual_time_task_starvation_count_.Get(), wait_for_navigation, initial_virtual_time_.Get(), &virtual_time_ticks_base_ms); } Response InspectorEmulationAgent::disable() { if (enabled_) { instrumenting_agents_->RemoveInspectorEmulationAgent(this); enabled_ = false; } setUserAgentOverride( String(), protocol::Maybe<String>(), protocol::Maybe<String>(), protocol::Maybe<protocol::Emulation::UserAgentMetadata>()); if (!locale_override_.Get().IsEmpty()) setLocaleOverride(String()); if (!web_local_frame_) return Response::Success(); setScriptExecutionDisabled(false); setScrollbarsHidden(false); setDocumentCookieDisabled(false); setTouchEmulationEnabled(false, Maybe<int>()); // Clear emulated media features. Note that the current approach // doesn't work well in cases where two clients have the same set of // features overridden to the same value by two different clients // (e.g. if we allowed two different front-ends with the same // settings to attach to the same page). TODO: support this use case. setEmulatedMedia(String(), {}); if (!emulated_vision_deficiency_.Get().IsNull()) setEmulatedVisionDeficiency(String("none")); setCPUThrottlingRate(1); setFocusEmulationEnabled(false); if (emulate_auto_dark_mode_.Get()) { setAutoDarkModeOverride(Maybe<bool>()); } setDefaultBackgroundColorOverride(Maybe<protocol::DOM::RGBA>()); disabled_image_types_.Clear(); return Response::Success(); } Response InspectorEmulationAgent::resetPageScaleFactor() { Response response = AssertPage(); if (!response.IsSuccess()) return response; GetWebViewImpl()->ResetScaleStateImmediately(); return response; } Response InspectorEmulationAgent::setPageScaleFactor(double page_scale_factor) { Response response = AssertPage(); if (!response.IsSuccess()) return response; GetWebViewImpl()->SetPageScaleFactor(static_cast<float>(page_scale_factor)); return response; } Response InspectorEmulationAgent::setScriptExecutionDisabled(bool value) { Response response = AssertPage(); if (!response.IsSuccess()) return response; if (script_execution_disabled_.Get() == value) return response; script_execution_disabled_.Set(value); GetWebViewImpl()->GetDevToolsEmulator()->SetScriptExecutionDisabled(value); return response; } Response InspectorEmulationAgent::setScrollbarsHidden(bool hidden) { Response response = AssertPage(); if (!response.IsSuccess()) return response; if (scrollbars_hidden_.Get() == hidden) return response; scrollbars_hidden_.Set(hidden); GetWebViewImpl()->GetDevToolsEmulator()->SetScrollbarsHidden(hidden); return response; } Response InspectorEmulationAgent::setDocumentCookieDisabled(bool disabled) { Response response = AssertPage(); if (!response.IsSuccess()) return response; if (document_cookie_disabled_.Get() == disabled) return response; document_cookie_disabled_.Set(disabled); GetWebViewImpl()->GetDevToolsEmulator()->SetDocumentCookieDisabled(disabled); return response; } Response InspectorEmulationAgent::setTouchEmulationEnabled( bool enabled, protocol::Maybe<int> max_touch_points) { Response response = AssertPage(); if (!response.IsSuccess()) return response; int max_points = max_touch_points.fromMaybe(1); if (max_points < 1 || max_points > WebTouchEvent::kTouchesLengthCap) { String msg = "Touch points must be between 1 and " + String::Number(static_cast<uint16_t>(WebTouchEvent::kTouchesLengthCap)); return Response::InvalidParams(msg.Utf8()); } touch_event_emulation_enabled_.Set(enabled); max_touch_points_.Set(max_points); GetWebViewImpl()->GetDevToolsEmulator()->SetTouchEventEmulationEnabled( enabled, max_points); return response; } Response InspectorEmulationAgent::setEmulatedMedia( Maybe<String> media, Maybe<protocol::Array<protocol::Emulation::MediaFeature>> features) { Response response = AssertPage(); if (!response.IsSuccess()) return response; if (media.isJust()) { auto mediaValue = media.takeJust(); emulated_media_.Set(mediaValue); GetWebViewImpl()->GetPage()->GetSettings().SetMediaTypeOverride(mediaValue); } else { emulated_media_.Set(""); GetWebViewImpl()->GetPage()->GetSettings().SetMediaTypeOverride(""); } for (const WTF::String& feature : emulated_media_features_.Keys()) { GetWebViewImpl()->GetPage()->SetMediaFeatureOverride(AtomicString(feature), ""); } emulated_media_features_.Clear(); if (features.isJust()) { auto featuresValue = features.takeJust(); for (auto const& mediaFeature : *featuresValue.get()) { auto const& name = mediaFeature->getName(); auto const& value = mediaFeature->getValue(); emulated_media_features_.Set(name, value); GetWebViewImpl()->GetPage()->SetMediaFeatureOverride(AtomicString(name), value); } } return response; } Response InspectorEmulationAgent::setEmulatedVisionDeficiency( const String& type) { Response response = AssertPage(); if (!response.IsSuccess()) return response; VisionDeficiency vision_deficiency; namespace TypeEnum = protocol::Emulation::SetEmulatedVisionDeficiency::TypeEnum; if (type == TypeEnum::None) vision_deficiency = VisionDeficiency::kNoVisionDeficiency; else if (type == TypeEnum::Achromatopsia) vision_deficiency = VisionDeficiency::kAchromatopsia; else if (type == TypeEnum::BlurredVision) vision_deficiency = VisionDeficiency::kBlurredVision; else if (type == TypeEnum::Deuteranopia) vision_deficiency = VisionDeficiency::kDeuteranopia; else if (type == TypeEnum::Protanopia) vision_deficiency = VisionDeficiency::kProtanopia; else if (type == TypeEnum::Tritanopia) vision_deficiency = VisionDeficiency::kTritanopia; else return Response::InvalidParams("Unknown vision deficiency type"); emulated_vision_deficiency_.Set(type); GetWebViewImpl()->GetPage()->SetVisionDeficiency(vision_deficiency); return response; } Response InspectorEmulationAgent::setCPUThrottlingRate(double rate) { Response response = AssertPage(); if (!response.IsSuccess()) return response; scheduler::ThreadCPUThrottler::GetInstance()->SetThrottlingRate(rate); return response; } Response InspectorEmulationAgent::setFocusEmulationEnabled(bool enabled) { Response response = AssertPage(); if (!response.IsSuccess()) return response; emulate_focus_.Set(enabled); GetWebViewImpl()->GetPage()->GetFocusController().SetFocusEmulationEnabled( enabled); return response; } Response InspectorEmulationAgent::setAutoDarkModeOverride(Maybe<bool> enabled) { Response response = AssertPage(); if (!response.IsSuccess()) return response; if (enabled.isJust()) { emulate_auto_dark_mode_.Set(true); auto_dark_mode_override_.Set(enabled.fromJust()); GetWebViewImpl()->GetDevToolsEmulator()->SetAutoDarkModeOverride( enabled.fromJust()); } else { emulate_auto_dark_mode_.Set(false); GetWebViewImpl()->GetDevToolsEmulator()->ResetAutoDarkModeOverride(); } return response; } Response InspectorEmulationAgent::setVirtualTimePolicy( const String& policy, Maybe<double> virtual_time_budget_ms, protocol::Maybe<int> max_virtual_time_task_starvation_count, protocol::Maybe<bool> wait_for_navigation, protocol::Maybe<double> initial_virtual_time, double* virtual_time_ticks_base_ms) { Response response = AssertPage(); if (!response.IsSuccess()) return response; virtual_time_policy_.Set(policy); PendingVirtualTimePolicy new_policy; new_policy.policy = PageScheduler::VirtualTimePolicy::kPause; if (protocol::Emulation::VirtualTimePolicyEnum::Advance == policy) { new_policy.policy = PageScheduler::VirtualTimePolicy::kAdvance; } else if (protocol::Emulation::VirtualTimePolicyEnum:: PauseIfNetworkFetchesPending == policy) { new_policy.policy = PageScheduler::VirtualTimePolicy::kDeterministicLoading; } if (new_policy.policy == PageScheduler::VirtualTimePolicy::kPause && virtual_time_budget_ms.isJust()) { LOG(ERROR) << "Can only specify virtual time budget for non-Pause policy"; return Response::InvalidParams( "Can only specify budget for non-Pause policy"); } if (new_policy.policy == PageScheduler::VirtualTimePolicy::kPause && max_virtual_time_task_starvation_count.isJust()) { LOG(ERROR) << "Can only specify virtual time starvation for non-Pause policy"; return Response::InvalidParams( "Can only specify starvation count for non-Pause policy"); } if (virtual_time_budget_ms.isJust()) { new_policy.virtual_time_budget_ms = virtual_time_budget_ms.fromJust(); virtual_time_budget_.Set(*new_policy.virtual_time_budget_ms); } else { virtual_time_budget_.Clear(); } if (max_virtual_time_task_starvation_count.isJust()) { new_policy.max_virtual_time_task_starvation_count = max_virtual_time_task_starvation_count.fromJust(); virtual_time_task_starvation_count_.Set( *new_policy.max_virtual_time_task_starvation_count); } else { virtual_time_task_starvation_count_.Clear(); } InnerEnable(); // This needs to happen before we apply virtual time. if (initial_virtual_time.isJust()) { initial_virtual_time_.Set(initial_virtual_time.fromJust()); web_local_frame_->View()->Scheduler()->SetInitialVirtualTime( base::Time::FromDoubleT(initial_virtual_time.fromJust())); } if (wait_for_navigation.fromMaybe(false)) { wait_for_navigation_.Set(true); pending_virtual_time_policy_ = std::move(new_policy); } else { ApplyVirtualTimePolicy(new_policy); } if (virtual_time_base_ticks_.is_null()) { *virtual_time_ticks_base_ms = 0; } else { *virtual_time_ticks_base_ms = (virtual_time_base_ticks_ - base::TimeTicks()).InMillisecondsF(); } return response; } void InspectorEmulationAgent::ApplyVirtualTimePolicy( const PendingVirtualTimePolicy& new_policy) { DCHECK(web_local_frame_); web_local_frame_->View()->Scheduler()->SetVirtualTimePolicy( new_policy.policy); virtual_time_base_ticks_ = web_local_frame_->View()->Scheduler()->EnableVirtualTime(); if (new_policy.virtual_time_budget_ms) { TRACE_EVENT_NESTABLE_ASYNC_BEGIN1("renderer.scheduler", "VirtualTimeBudget", TRACE_ID_LOCAL(this), "budget", *new_policy.virtual_time_budget_ms); base::TimeDelta budget_amount = base::Milliseconds(*new_policy.virtual_time_budget_ms); web_local_frame_->View()->Scheduler()->GrantVirtualTimeBudget( budget_amount, WTF::Bind(&InspectorEmulationAgent::VirtualTimeBudgetExpired, WrapWeakPersistent(this))); for (DocumentLoader* loader : pending_document_loaders_) loader->SetDefersLoading(LoaderFreezeMode::kNone); pending_document_loaders_.clear(); } if (new_policy.max_virtual_time_task_starvation_count) { web_local_frame_->View()->Scheduler()->SetMaxVirtualTimeTaskStarvationCount( *new_policy.max_virtual_time_task_starvation_count); } } void InspectorEmulationAgent::FrameStartedLoading(LocalFrame*) { if (pending_virtual_time_policy_) { wait_for_navigation_.Set(false); ApplyVirtualTimePolicy(*pending_virtual_time_policy_); pending_virtual_time_policy_ = absl::nullopt; } } AtomicString InspectorEmulationAgent::OverrideAcceptImageHeader( const HashSet<String>* disabled_image_types) { String header(ImageAcceptHeader()); for (String type : *disabled_image_types) { // The header string is expected to be like // `image/jxl,image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8` // and is expected to be always ending with `image/*,*/*;q=xxx`, therefore, // to remove a type we replace `image/x,` with empty string. Only webp, avif // and jxl types can be disabled. header.Replace(String(type + ","), ""); } return AtomicString(header); } void InspectorEmulationAgent::PrepareRequest(DocumentLoader* loader, ResourceRequest& request, ResourceLoaderOptions& options, ResourceType resource_type) { if (!accept_language_override_.Get().IsEmpty() && request.HttpHeaderField("Accept-Language").IsEmpty()) { request.SetHttpHeaderField( "Accept-Language", AtomicString(network_utils::GenerateAcceptLanguageHeader( accept_language_override_.Get()))); } if (resource_type != ResourceType::kImage || disabled_image_types_.IsEmpty()) return; if (!options.unsupported_image_mime_types) { options.unsupported_image_mime_types = base::MakeRefCounted<base::RefCountedData<HashSet<String>>>(); } for (String type : disabled_image_types_.Keys()) { options.unsupported_image_mime_types->data.insert(type); } request.SetHTTPAccept( OverrideAcceptImageHeader(&options.unsupported_image_mime_types->data)); // Bypassing caching to prevent the use of the previously loaded and cached // images. request.SetCacheMode(mojom::blink::FetchCacheMode::kBypassCache); } Response InspectorEmulationAgent::setNavigatorOverrides( const String& platform) { Response response = AssertPage(); if (!response.IsSuccess()) return response; navigator_platform_override_.Set(platform); GetWebViewImpl()->GetPage()->GetSettings().SetNavigatorPlatformOverride( platform); return response; } void InspectorEmulationAgent::VirtualTimeBudgetExpired() { TRACE_EVENT_NESTABLE_ASYNC_END0("renderer.scheduler", "VirtualTimeBudget", TRACE_ID_LOCAL(this)); WebView* view = web_local_frame_->View(); if (!view) return; view->Scheduler()->SetVirtualTimePolicy( PageScheduler::VirtualTimePolicy::kPause); virtual_time_policy_.Set(protocol::Emulation::VirtualTimePolicyEnum::Pause); // We could have been detached while VT was still running. // TODO(caseq): should we rather force-pause the time upon Disable()? if (auto* frontend = GetFrontend()) frontend->virtualTimeBudgetExpired(); } Response InspectorEmulationAgent::setDefaultBackgroundColorOverride( Maybe<protocol::DOM::RGBA> color) { Response response = AssertPage(); if (!response.IsSuccess()) return response; if (!color.isJust()) { // Clear the override and state. GetWebViewImpl()->SetBaseBackgroundColorOverrideForInspector(absl::nullopt); default_background_color_override_rgba_.Clear(); return Response::Success(); } blink::protocol::DOM::RGBA* rgba = color.fromJust(); default_background_color_override_rgba_.Set(rgba->Serialize()); // Clamping of values is done by Color() constructor. int alpha = static_cast<int>(lroundf(255.0f * rgba->getA(1.0f))); GetWebViewImpl()->SetBaseBackgroundColorOverrideForInspector( Color(rgba->getR(), rgba->getG(), rgba->getB(), alpha).Rgb()); return Response::Success(); } Response InspectorEmulationAgent::setDeviceMetricsOverride( int width, int height, double device_scale_factor, bool mobile, Maybe<double> scale, Maybe<int> screen_width, Maybe<int> screen_height, Maybe<int> position_x, Maybe<int> position_y, Maybe<bool> dont_set_visible_size, Maybe<protocol::Emulation::ScreenOrientation>, Maybe<protocol::Page::Viewport>, Maybe<protocol::Emulation::DisplayFeature>) { // We don't have to do anything other than reply to the client, as the // emulation parameters should have already been updated by the handling of // blink::mojom::FrameWidget::EnableDeviceEmulation. return AssertPage(); } Response InspectorEmulationAgent::clearDeviceMetricsOverride() { // We don't have to do anything other than reply to the client, as the // emulation parameters should have already been cleared by the handling of // blink::mojom::FrameWidget::DisableDeviceEmulation. return AssertPage(); } Response InspectorEmulationAgent::setUserAgentOverride( const String& user_agent, protocol::Maybe<String> accept_language, protocol::Maybe<String> platform, protocol::Maybe<protocol::Emulation::UserAgentMetadata> ua_metadata_override) { if (!user_agent.IsEmpty() || accept_language.isJust() || platform.isJust()) InnerEnable(); user_agent_override_.Set(user_agent); accept_language_override_.Set(accept_language.fromMaybe(String())); navigator_platform_override_.Set(platform.fromMaybe(String())); if (web_local_frame_) { GetWebViewImpl()->GetPage()->GetSettings().SetNavigatorPlatformOverride( navigator_platform_override_.Get()); } if (ua_metadata_override.isJust()) { blink::UserAgentMetadata default_ua_metadata = Platform::Current()->UserAgentMetadata(); if (user_agent.IsEmpty()) { ua_metadata_override_ = absl::nullopt; serialized_ua_metadata_override_.Set(std::vector<uint8_t>()); return Response::InvalidParams( "Can't specify UserAgentMetadata but no UA string"); } std::unique_ptr<protocol::Emulation::UserAgentMetadata> ua_metadata = ua_metadata_override.takeJust(); ua_metadata_override_.emplace(); if (ua_metadata->hasBrands()) { for (const auto& bv : *ua_metadata->getBrands(nullptr)) { blink::UserAgentBrandVersion out_bv; out_bv.brand = bv->getBrand().Ascii(); out_bv.major_version = bv->getVersion().Ascii(); ua_metadata_override_->brand_version_list.push_back(std::move(out_bv)); } } else { ua_metadata_override_->brand_version_list = std::move(default_ua_metadata.brand_version_list); } if (ua_metadata->hasFullVersion()) { ua_metadata_override_->full_version = ua_metadata->getFullVersion("").Ascii(); } else { ua_metadata_override_->full_version = std::move(default_ua_metadata.full_version); } ua_metadata_override_->platform = ua_metadata->getPlatform().Ascii(); ua_metadata_override_->platform_version = ua_metadata->getPlatformVersion().Ascii(); ua_metadata_override_->architecture = ua_metadata->getArchitecture().Ascii(); ua_metadata_override_->model = ua_metadata->getModel().Ascii(); ua_metadata_override_->mobile = ua_metadata->getMobile(); } else { ua_metadata_override_ = absl::nullopt; } std::string marshalled = blink::UserAgentMetadata::Marshal(ua_metadata_override_) .value_or(std::string()); std::vector<uint8_t> marshalled_as_bytes; marshalled_as_bytes.insert(marshalled_as_bytes.end(), marshalled.begin(), marshalled.end()); serialized_ua_metadata_override_.Set(std::move(marshalled_as_bytes)); return Response::Success(); } Response InspectorEmulationAgent::setLocaleOverride( protocol::Maybe<String> maybe_locale) { // Only allow resetting overrides set by the same agent. if (locale_override_.Get().IsEmpty() && LocaleController::instance().has_locale_override()) { return Response::ServerError( "Another locale override is already in effect"); } String locale = maybe_locale.fromMaybe(String()); String error = LocaleController::instance().SetLocaleOverride(locale); if (!error.IsEmpty()) return Response::ServerError(error.Utf8()); locale_override_.Set(locale); return Response::Success(); } Response InspectorEmulationAgent::setTimezoneOverride( const String& timezone_id) { if (timezone_id.IsEmpty()) { timezone_override_.reset(); } else { if (timezone_override_) { timezone_override_->change(timezone_id); } else { timezone_override_ = TimeZoneController::SetTimeZoneOverride(timezone_id); } if (!timezone_override_) { return TimeZoneController::HasTimeZoneOverride() ? Response::ServerError( "Timezone override is already in effect") : Response::InvalidParams("Invalid timezone id"); } } timezone_id_override_.Set(timezone_id); return Response::Success(); } void InspectorEmulationAgent::GetDisabledImageTypes(HashSet<String>* result) { if (disabled_image_types_.IsEmpty()) return; for (String type : disabled_image_types_.Keys()) result->insert(type); } void InspectorEmulationAgent::WillCommitLoad(LocalFrame*, DocumentLoader* loader) { if (virtual_time_policy_.Get() != protocol::Emulation::VirtualTimePolicyEnum::Pause) { return; } loader->SetDefersLoading(LoaderFreezeMode::kStrict); pending_document_loaders_.push_back(loader); } void InspectorEmulationAgent::ApplyAcceptLanguageOverride(String* accept_lang) { if (!accept_language_override_.Get().IsEmpty()) *accept_lang = accept_language_override_.Get(); } void InspectorEmulationAgent::ApplyUserAgentOverride(String* user_agent) { if (!user_agent_override_.Get().IsEmpty()) *user_agent = user_agent_override_.Get(); } void InspectorEmulationAgent::ApplyUserAgentMetadataOverride( absl::optional<blink::UserAgentMetadata>* ua_metadata) { // This applies when UA override is set. if (!user_agent_override_.Get().IsEmpty()) { *ua_metadata = ua_metadata_override_; } } void InspectorEmulationAgent::InnerEnable() { if (enabled_) return; enabled_ = true; instrumenting_agents_->AddInspectorEmulationAgent(this); } Response InspectorEmulationAgent::AssertPage() { if (!web_local_frame_) { LOG(ERROR) << "Can only enable virtual time for pages, not workers"; return Response::InvalidParams( "Can only enable virtual time for pages, not workers"); } return Response::Success(); } void InspectorEmulationAgent::Trace(Visitor* visitor) const { visitor->Trace(web_local_frame_); visitor->Trace(pending_document_loaders_); InspectorBaseAgent::Trace(visitor); } protocol::Response InspectorEmulationAgent::setDisabledImageTypes( std::unique_ptr<protocol::Array<protocol::Emulation::DisabledImageType>> disabled_types) { if (disabled_types->size() > 0 && !enabled_) InnerEnable(); disabled_image_types_.Clear(); String prefix = "image/"; namespace DisabledImageTypeEnum = protocol::Emulation::DisabledImageTypeEnum; for (protocol::Emulation::DisabledImageType type : *disabled_types) { if (DisabledImageTypeEnum::Avif == type || DisabledImageTypeEnum::Jxl == type || DisabledImageTypeEnum::Webp == type) { disabled_image_types_.Set(prefix + type, true); continue; } disabled_image_types_.Clear(); return Response::InvalidParams("Invalid image type"); } return Response::Success(); } } // namespace blink
39.530323
91
0.725976
Yannic
dbc93a863223f8f7bc6c03c727913d42e7c556ab
5,174
cc
C++
tensorflow/core/ops/string_ops.cc
breandan/tensorflow
7509bad95200e1baed4eb488dbeaaa2c505a2824
[ "Apache-2.0" ]
4
2016-09-26T08:55:23.000Z
2019-05-06T15:26:03.000Z
tensorflow/core/ops/string_ops.cc
breandan/tensorflow
7509bad95200e1baed4eb488dbeaaa2c505a2824
[ "Apache-2.0" ]
null
null
null
tensorflow/core/ops/string_ops.cc
breandan/tensorflow
7509bad95200e1baed4eb488dbeaaa2c505a2824
[ "Apache-2.0" ]
8
2017-04-17T23:39:12.000Z
2019-05-11T14:06:31.000Z
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/framework/op.h" namespace tensorflow { REGISTER_OP("StringToHashBucketFast") .Input("input: string") .Output("output: int64") .Attr("num_buckets: int >= 1") .Doc(R"doc( Converts each string in the input Tensor to its hash mod by a number of buckets. The hash function is deterministic on the content of the string within the process and will never change. However, it is not suitable for cryptography. This function may be used when CPU time is scarce and inputs are trusted or unimportant. There is a risk of adversaries constructing inputs that all hash to the same bucket. To prevent this problem, use a strong hash function with `tf.string_to_hash_bucket_strong`. input: The strings to assign a hash bucket. num_buckets: The number of buckets. output: A Tensor of the same shape as the input `string_tensor`. )doc"); REGISTER_OP("StringToHashBucketStrong") .Input("input: string") .Output("output: int64") .Attr("num_buckets: int >= 1") .Attr("key: list(int)") .Doc(R"doc( Converts each string in the input Tensor to its hash mod by a number of buckets. The hash function is deterministic on the content of the string within the process. The hash function is a keyed hash function, where attribute `key` defines the key of the hash function. `key` is an array of 2 elements. A strong hash is important when inputs may be malicious, e.g. URLs with additional components. Adversaries could try to make their inputs hash to the same bucket for a denial-of-service attack or to skew the results. A strong hash prevents this by making it dificult, if not infeasible, to compute inputs that hash to the same bucket. This comes at a cost of roughly 4x higher compute time than tf.string_to_hash_bucket_fast. input: The strings to assign a hash bucket. num_buckets: The number of buckets. key: The key for the keyed hash function passed as a list of two uint64 elements. output: A Tensor of the same shape as the input `string_tensor`. )doc"); REGISTER_OP("StringToHashBucket") .Input("string_tensor: string") .Output("output: int64") .Attr("num_buckets: int >= 1") .Deprecated(10, "Use `tf.string_to_hash_bucket_fast()` or " "`tf.string_to_hash_bucket_strong()`") .Doc(R"doc( Converts each string in the input Tensor to its hash mod by a number of buckets. The hash function is deterministic on the content of the string within the process. Note that the hash function may change from time to time. num_buckets: The number of buckets. output: A Tensor of the same shape as the input `string_tensor`. )doc"); REGISTER_OP("ReduceJoin") .Input("inputs: string") .Input("reduction_indices: int32") .Attr("keep_dims: bool = false") .Attr("separator: string = ''") .Output("output: string") .Doc(R"doc( Joins a string Tensor across the given dimensions. Computes the string join across dimensions in the given string Tensor of shape `[d_0, d_1, ..., d_n-1]`. Returns a new Tensor created by joining the input strings with the given separator (default: empty string). Negative indices are counted backwards from the end, with `-1` being equivalent to `n - 1`. Passing an empty `reduction_indices` joins all strings in linear index order and outputs a scalar string. For example: ``` # tensor `a` is [["a", "b"], ["c", "d"]] tf.reduce_join(a, 0) ==> ["ac", "bd"] tf.reduce_join(a, 1) ==> ["ab", "cd"] tf.reduce_join(a, -2) = tf.reduce_join(a, 0) ==> ["ac", "bd"] tf.reduce_join(a, -1) = tf.reduce_join(a, 1) ==> ["ab", "cd"] tf.reduce_join(a, 0, keep_dims=True) ==> [["ac", "bd"]] tf.reduce_join(a, 1, keep_dims=True) ==> [["ab"], ["cd"]] tf.reduce_join(a, 0, separator=".") ==> ["a.c", "b.d"] tf.reduce_join(a, [0, 1]) ==> ["acbd"] tf.reduce_join(a, [1, 0]) ==> ["abcd"] tf.reduce_join(a, []) ==> ["abcd"] ``` inputs: The input to be joined. All reduced indices must have non-zero size. reduction_indices: The dimensions to reduce over. Dimensions are reduced in the order specified. If `reduction_indices` has higher rank than `1`, it is flattened. Omitting `reduction_indices` is equivalent to passing `[n-1, n-2, ..., 0]`. Negative indices from `-n` to `-1` are supported. keep_dims: If `True`, retain reduced dimensions with length `1`. separator: The separator to use when joining. output: Has shape equal to that of the input with reduced dimensions removed or set to `1` depending on `keep_dims`. )doc"); } // namespace tensorflow
40.108527
80
0.711055
breandan
dbca7033d2e551b6d754c8f530d7918631ff8de9
160
cpp
C++
chapter12/ex12_16.cpp
chaomi1998/CppPrimer_5th
9ecad51c21e5f57f2d682d9941812e1d51cc8a43
[ "MIT" ]
null
null
null
chapter12/ex12_16.cpp
chaomi1998/CppPrimer_5th
9ecad51c21e5f57f2d682d9941812e1d51cc8a43
[ "MIT" ]
null
null
null
chapter12/ex12_16.cpp
chaomi1998/CppPrimer_5th
9ecad51c21e5f57f2d682d9941812e1d51cc8a43
[ "MIT" ]
null
null
null
#include <memory> using std::unique_ptr; int main() { unique_ptr<int> p1(new int(42)); unique_ptr<int> p2(p1); unique_ptr<int> p3; p3 = p1; }
13.333333
36
0.60625
chaomi1998
dbcce76b57459545909d7286af87a7354ce06de1
1,334
cpp
C++
windows/appcompat/shims/general/cuasappfix.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
windows/appcompat/shims/general/cuasappfix.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
windows/appcompat/shims/general/cuasappfix.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*++ Copyright (c) 2002 Microsoft Corporation Module Name: CUASAppHack.cpp Abstract: This shim communicates with CUAS to pass AppHack information down to msctf.dll. Notes: This is a general purpose shim, but must be customized via the command line. History: 05/10/2002 yutakas Created --*/ #include "precomp.h" IMPLEMENT_SHIM_BEGIN(CUASAppFix) #include "ShimHookMacro.h" APIHOOK_ENUM_BEGIN APIHOOK_ENUM_END typedef HRESULT (*PFNCUASAPPFIX)(LPCSTR lpCommandLine); VOID CUASAppFix(LPCSTR lpCommandLine) { if (!lpCommandLine) { LOGN(eDbgLevelError, "CUASAppFix requires a command line"); return; } PFNCUASAPPFIX pfn; HMODULE hMod = LoadLibrary(TEXT("msctf.dll")); if (hMod) { pfn = (PFNCUASAPPFIX) GetProcAddress(hMod, "TF_CUASAppFix"); if (pfn) { LOGN(eDbgLevelInfo, "Running CUASAppFix with %S", lpCommandLine); pfn(lpCommandLine); } } } BOOL NOTIFY_FUNCTION( DWORD fdwReason ) { if (fdwReason == SHIM_STATIC_DLLS_INITIALIZED) { CUASAppFix(COMMAND_LINE); } return TRUE; } /*++ Register hooked functions --*/ HOOK_BEGIN CALL_NOTIFY_FUNCTION HOOK_END IMPLEMENT_SHIM_END
17.102564
78
0.625187
npocmaka
dbd17702a329c4b83b51779eb2f79b9026e168d6
888
cpp
C++
leetcode/188.best-time-to-buy-and-sell-stock-iv.cpp
vkashkumar/Competitive-Programming
c457e745208c0ca3e45b1ffce254a21504533f51
[ "MIT" ]
2
2019-01-30T12:45:18.000Z
2021-05-06T19:02:51.000Z
leetcode/188.best-time-to-buy-and-sell-stock-iv.cpp
vkashkumar/Competitive-Programming
c457e745208c0ca3e45b1ffce254a21504533f51
[ "MIT" ]
null
null
null
leetcode/188.best-time-to-buy-and-sell-stock-iv.cpp
vkashkumar/Competitive-Programming
c457e745208c0ca3e45b1ffce254a21504533f51
[ "MIT" ]
3
2020-10-02T15:42:04.000Z
2022-03-27T15:14:16.000Z
/* * @lc app=leetcode id=188 lang=cpp * * [188] Best Time to Buy and Sell Stock IV */ // @lc code=start class Solution { public: int maxProfit(int K, vector<int>& prices) { int n = prices.size(); if(K>=n/2) { int ans = 0; for(int i=1;i<n;i++) { if(prices[i] > prices[i-1]) { ans += prices[i]-prices[i-1]; } } return ans; } int dp[1001][1001] = {0}; for(int k=1;k<=K;k++) { for(int i=1;i<n;i++) { int ans = 0; for(int j=0;j<i;j++) { if(prices[i] > prices[j]) ans = max(ans,prices[i]-prices[j] + dp[k-1][j]); } dp[k][i] = max(ans, dp[k][i-1]); } } return dp[K][n-1]; } }; // @lc code=end
24
72
0.371622
vkashkumar
dbd288c489b8ebacce0bcf45509ae152c6810840
1,069
cpp
C++
CR696/a.cpp
JackBai0914/Competitive-Programming-Codebase
a1cabf0fa5072b07a7da25d66bf455eb45b0b7e9
[ "MIT" ]
null
null
null
CR696/a.cpp
JackBai0914/Competitive-Programming-Codebase
a1cabf0fa5072b07a7da25d66bf455eb45b0b7e9
[ "MIT" ]
null
null
null
CR696/a.cpp
JackBai0914/Competitive-Programming-Codebase
a1cabf0fa5072b07a7da25d66bf455eb45b0b7e9
[ "MIT" ]
null
null
null
/* * * * * * * * * * * * * * * * * * * * * @author: Xingjian Bai * @date: 2021-01-19 14:33:26 * @description: * * * @notes: * g++ -fsanitize=address -ftrapv * * * * * * * * * * * * * * * * * */ #include <bits/stdc++.h> #define F first #define S second #define MP make_pair #define TIME (double)clock()/CLOCKS_PER_SEC using namespace std; typedef long long ll; typedef long double ld; typedef pair <int, int> pii; const int mod = 1000000007; const ll oo = 1e18; const ld eps = 1e-8; #define debug(x) cerr << "(debug mod) " << #x << " = " << x << endl string b; int main() { ios::sync_with_stdio(false); int t; cin >> t; while (t --) { int n; cin >> n; cin >> b; int lst = -1; for (int i = 0; i <b.size(); i ++) { if (b[i] == '0') { if (lst == 1) cout << '0', lst = 0; else cout << '1', lst = 1; } if (b[i] == '1') { if (lst == 2) cout << '0', lst = 1; else cout << '1', lst = 2; } } cout << endl; } return 0; }
21.38
67
0.451824
JackBai0914
dbd3c52399555f17ba2073c20f5e7efad2b0d56d
381
hpp
C++
src/include/ooyw/safecolor.hpp
creikey/ooyw
702bb42ed2e4f30f89eb54c9167772aaab7c1795
[ "MIT" ]
null
null
null
src/include/ooyw/safecolor.hpp
creikey/ooyw
702bb42ed2e4f30f89eb54c9167772aaab7c1795
[ "MIT" ]
null
null
null
src/include/ooyw/safecolor.hpp
creikey/ooyw
702bb42ed2e4f30f89eb54c9167772aaab7c1795
[ "MIT" ]
null
null
null
#ifndef HPP_SAFECOLOR #define HPP_SAFECOLOR #include <allegro5/allegro.h> namespace ooyw { class SafeColor { public: SafeColor() : r(0), g(0), b(0){}; SafeColor(double inr, double ing, double inb) : r(inr), g(ing), b(inb){}; ALLEGRO_COLOR al_c() { return al_map_rgb(this->r, this->g, this->b); }; private: double r; double g; double b; }; } #endif // HPP_SAFECOLOR
18.142857
75
0.658793
creikey
dbd49e09d75fd3aac825c667db5e1c9733c493d2
18,530
cpp
C++
argos3/src/plugins/robots/generic/simulator/camera_default_sensor.cpp
yiftachn/krembot_sim_fork
d3d1b050f9fff4c96bded298eadde5a9ca4dab6b
[ "MIT" ]
211
2015-01-27T20:16:40.000Z
2022-02-25T03:11:13.000Z
argos3/src/plugins/robots/generic/simulator/camera_default_sensor.cpp
yiftachn/krembot_sim_fork
d3d1b050f9fff4c96bded298eadde5a9ca4dab6b
[ "MIT" ]
154
2015-02-09T20:32:38.000Z
2022-03-30T21:35:24.000Z
argos3/src/plugins/robots/generic/simulator/camera_default_sensor.cpp
yiftachn/krembot_sim_fork
d3d1b050f9fff4c96bded298eadde5a9ca4dab6b
[ "MIT" ]
128
2015-02-09T10:21:49.000Z
2022-03-31T22:24:51.000Z
/** * @file <argos3/plugins/robots/generic/simulator/camera_default_sensor.cpp> * * @author Michael Allwright - <allsey87@gmail.com> */ #include "camera_default_sensor.h" #include <argos3/core/simulator/simulator.h> #include <argos3/core/simulator/entity/composable_entity.h> #include <argos3/plugins/robots/generic/simulator/camera_sensor_algorithm.h> namespace argos { /****************************************/ /****************************************/ CCameraDefaultSensor::CCameraDefaultSensor() : m_bShowFrustum(false), m_pcEmbodiedEntity(nullptr), m_pcControllableEntity(nullptr) {} /****************************************/ /****************************************/ void CCameraDefaultSensor::SetRobot(CComposableEntity& c_entity) { /* Get the embodied and controllable entities */ m_pcEmbodiedEntity = &(c_entity.GetComponent<CEmbodiedEntity>("body")); m_pcControllableEntity = &(c_entity.GetComponent<CControllableEntity>("controller")); } /****************************************/ /****************************************/ void CCameraDefaultSensor::Init(TConfigurationNode& t_tree) { try { /* Parent class init */ CCI_CameraSensor::Init(t_tree); /* Show the frustums */ GetNodeAttributeOrDefault(t_tree, "show_frustum", m_bShowFrustum, m_bShowFrustum); /* For each camera */ TConfigurationNodeIterator itCamera("camera"); for(itCamera = itCamera.begin(&t_tree); itCamera != itCamera.end(); ++itCamera) { /* Get camera indentifier */ std::string strId; GetNodeAttribute(*itCamera, "id", strId); /* Parse and look up the anchor */ std::string strAnchorId; GetNodeAttribute(*itCamera, "anchor", strAnchorId); SAnchor& sAnchor = m_pcEmbodiedEntity->GetAnchor(strAnchorId); /* parse the offset */ CVector3 cOffsetPosition; CQuaternion cOffsetOrientation; GetNodeAttribute(*itCamera, "position", cOffsetPosition); GetNodeAttribute(*itCamera, "orientation", cOffsetOrientation); CTransformationMatrix3 cOffset(cOffsetOrientation, cOffsetPosition); /* parse the range */ CRange<Real> cRange; GetNodeAttribute(*itCamera, "range", cRange); /* create the projection matrix */ CSquareMatrix<3> cProjectionMatrix; cProjectionMatrix.SetIdentityMatrix(); /* set the focal length */ CVector2 cFocalLength; GetNodeAttribute(*itCamera, "focal_length", cFocalLength); cProjectionMatrix(0,0) = cFocalLength.GetX(); // Fx cProjectionMatrix(1,1) = cFocalLength.GetY(); // Fy /* set the principal point */ CVector2 cPrincipalPoint; GetNodeAttribute(*itCamera, "principal_point", cPrincipalPoint); cProjectionMatrix(0,2) = cPrincipalPoint.GetX(); // Px cProjectionMatrix(1,2) = cPrincipalPoint.GetY(); // Py /* set the distortion parameters */ /* CMatrix<1,5> cDistortionParameters; std::string strDistortionParameters; Real pfDistortionParameters[3]; GetNodeAttribute(*itCamera, "distortion_parameters", strDistortionParameters); ParseValues<Real>(strDistortionParameters, 3, pfDistortionParameters, ','); cDistortionParameters(0,0) = pfDistortionParameters[0]; // K1 cDistortionParameters(0,1) = pfDistortionParameters[1]; // K2 cDistortionParameters(0,4) = pfDistortionParameters[2]; // K3 */ /* parse the resolution */ CVector2 cResolution; GetNodeAttribute(*itCamera, "resolution", cResolution); /* create and initialise the algorithms */ std::vector<CCameraSensorSimulatedAlgorithm*> vecSimulatedAlgorithms; std::vector<CCI_CameraSensorAlgorithm*> vecAlgorithms; TConfigurationNodeIterator itAlgorithm; for(itAlgorithm = itAlgorithm.begin(&(*itCamera)); itAlgorithm != itAlgorithm.end(); ++itAlgorithm) { /* create the algorithm */ CCameraSensorSimulatedAlgorithm* pcAlgorithm = CFactory<CCameraSensorSimulatedAlgorithm>::New(itAlgorithm->Value()); /* check that algorithm inherits from a control interface */ auto* pcCIAlgorithm = dynamic_cast<CCI_CameraSensorAlgorithm*>(pcAlgorithm); if(pcCIAlgorithm == nullptr) { THROW_ARGOSEXCEPTION("Algorithm \"" << itAlgorithm->Value() << "\" does not inherit from CCI_CameraSensorAlgorithm"); } /* initialize the algorithm's control interface */ pcCIAlgorithm->Init(*itAlgorithm); /* store pointers to the algorithms */ vecSimulatedAlgorithms.push_back(pcAlgorithm); vecAlgorithms.push_back(pcCIAlgorithm); } /* create the simulated sensor */ m_vecSensors.emplace_back(sAnchor, cOffset, cRange, cProjectionMatrix, cResolution, vecSimulatedAlgorithms); /* create the sensor's control interface */ m_vecInterfaces.emplace_back(strId, vecAlgorithms); } } catch(CARGoSException& ex) { THROW_ARGOSEXCEPTION_NESTED("Error initializing camera sensor", ex); } /* sensor is disabled by default */ Disable(); } /****************************************/ /****************************************/ void CCameraDefaultSensor::Update() { /* sensor is disabled--nothing to do */ if (IsDisabled()) { return; } /* vector of controller rays */ std::vector<std::pair<bool, CRay3> >& vecCheckedRays = m_pcControllableEntity->GetCheckedRays(); /* sensor parameters */ CTransformationMatrix3 cWorldToAnchorTransform; CTransformationMatrix3 cWorldToCameraTransform; CTransformationMatrix3 cCameraToWorldTransform; CVector3 cCameraLocation, cLookAt, cUp; CVector3 cX, cY, cZ; CVector3 cNearCenter, cNearTopLeft, cNearTopRight, cNearBottomLeft, cNearBottomRight; CVector3 cFarCenter, cFarTopLeft, cFarTopRight, cFarBottomLeft, cFarBottomRight; std::array<CPlane, 6> arrFrustumPlanes; CVector3 cBoundingBoxMinCorner, cBoundingBoxMaxCorner; CVector3 cBoundingBoxPosition, cBoundingBoxHalfExtents; /* for each camera sensor */ for(SSensor& s_sensor : m_vecSensors) { /* calculate transform matrices */ cWorldToAnchorTransform.SetFromComponents(s_sensor.Anchor.Orientation, s_sensor.Anchor.Position); cWorldToCameraTransform = cWorldToAnchorTransform * s_sensor.Offset; cCameraToWorldTransform = cWorldToCameraTransform.GetInverse(); /* calculate camera direction vectors */ cCameraLocation = cWorldToCameraTransform.GetTranslationVector(); cLookAt = cWorldToCameraTransform * CVector3::Z; cUp = CVector3(0,-1,0); // -Y cUp.Rotate(cWorldToCameraTransform.GetRotationMatrix()); /* calculate direction vectors */ cZ = cCameraLocation - cLookAt; cZ.Normalize(); cX = cUp; cX.CrossProduct(cZ); cX.Normalize(); cY = cZ; cY.CrossProduct(cX); /* calculate frustum coordinates */ cNearCenter = cCameraLocation - cZ * s_sensor.Range.GetMin(); cFarCenter = cCameraLocation - cZ * s_sensor.Range.GetMax(); cNearTopLeft = cNearCenter + (cY * s_sensor.NearPlaneHeight) - (cX * s_sensor.NearPlaneWidth); cNearTopRight = cNearCenter + (cY * s_sensor.NearPlaneHeight) + (cX * s_sensor.NearPlaneWidth); cNearBottomLeft = cNearCenter - (cY * s_sensor.NearPlaneHeight) - (cX * s_sensor.NearPlaneWidth); cNearBottomRight = cNearCenter - (cY * s_sensor.NearPlaneHeight) + (cX * s_sensor.NearPlaneWidth); cFarTopLeft = cFarCenter + (cY * s_sensor.FarPlaneHeight) - (cX * s_sensor.FarPlaneWidth); cFarTopRight = cFarCenter + (cY * s_sensor.FarPlaneHeight) + (cX * s_sensor.FarPlaneWidth); cFarBottomLeft = cFarCenter - (cY * s_sensor.FarPlaneHeight) - (cX * s_sensor.FarPlaneWidth); cFarBottomRight = cFarCenter - (cY * s_sensor.FarPlaneHeight) + (cX * s_sensor.FarPlaneWidth); /* show frustum if enabled by adding outline to the checked rays vector */ if(m_bShowFrustum) { vecCheckedRays.emplace_back(false, CRay3(cNearTopLeft, cNearTopRight)); vecCheckedRays.emplace_back(false, CRay3(cNearTopRight, cNearBottomRight)); vecCheckedRays.emplace_back(false, CRay3(cNearBottomRight, cNearBottomLeft)); vecCheckedRays.emplace_back(false, CRay3(cNearBottomLeft, cNearTopLeft)); vecCheckedRays.emplace_back(false, CRay3(cFarTopLeft, cFarTopRight)); vecCheckedRays.emplace_back(false, CRay3(cFarTopRight, cFarBottomRight)); vecCheckedRays.emplace_back(false, CRay3(cFarBottomRight, cFarBottomLeft)); vecCheckedRays.emplace_back(false, CRay3(cFarBottomLeft, cFarTopLeft)); vecCheckedRays.emplace_back(false, CRay3(cNearTopLeft, cFarTopLeft)); vecCheckedRays.emplace_back(false, CRay3(cNearTopRight, cFarTopRight)); vecCheckedRays.emplace_back(false, CRay3(cNearBottomRight, cFarBottomRight)); vecCheckedRays.emplace_back(false, CRay3(cNearBottomLeft, cFarBottomLeft)); } //std::cerr << cFarBottomRight.GetZ() << "\t" << cFarBottomLeft.GetZ() << std::endl; TODO /* generate a bounding box for the frustum */ cBoundingBoxMinCorner = cNearCenter; cBoundingBoxMaxCorner = cNearCenter; for(const CVector3& c_point : { cNearTopLeft, cNearTopRight, cNearBottomLeft, cNearBottomRight, cFarTopLeft, cFarTopRight, cFarBottomLeft, cFarBottomRight }) { if(c_point.GetX() > cBoundingBoxMaxCorner.GetX()) { cBoundingBoxMaxCorner.SetX(c_point.GetX()); } if(c_point.GetX() < cBoundingBoxMinCorner.GetX()) { cBoundingBoxMinCorner.SetX(c_point.GetX()); } if(c_point.GetY() > cBoundingBoxMaxCorner.GetY()) { cBoundingBoxMaxCorner.SetY(c_point.GetY()); } if(c_point.GetY() < cBoundingBoxMinCorner.GetY()) { cBoundingBoxMinCorner.SetY(c_point.GetY()); } if(c_point.GetZ() > cBoundingBoxMaxCorner.GetZ()) { cBoundingBoxMaxCorner.SetZ(c_point.GetZ()); } if(c_point.GetZ() < cBoundingBoxMinCorner.GetZ()) { cBoundingBoxMinCorner.SetZ(c_point.GetZ()); } } cBoundingBoxMaxCorner *= 0.5; cBoundingBoxMinCorner *= 0.5; cBoundingBoxPosition = (cBoundingBoxMaxCorner + cBoundingBoxMinCorner); cBoundingBoxHalfExtents = (cBoundingBoxMaxCorner - cBoundingBoxMinCorner); /* generate frustum planes */ arrFrustumPlanes[0].SetFromThreePoints(cNearTopRight, cNearTopLeft, cFarTopLeft); arrFrustumPlanes[1].SetFromThreePoints(cNearBottomLeft, cNearBottomRight, cFarBottomRight); arrFrustumPlanes[2].SetFromThreePoints(cNearTopLeft, cNearBottomLeft, cFarBottomLeft); arrFrustumPlanes[3].SetFromThreePoints(cNearBottomRight, cNearTopRight, cFarBottomRight); arrFrustumPlanes[4].SetFromThreePoints(cNearTopLeft, cNearTopRight, cNearBottomRight); arrFrustumPlanes[5].SetFromThreePoints(cFarTopRight, cFarTopLeft, cFarBottomLeft); /* execute each algorithm */ for(CCameraSensorSimulatedAlgorithm* pc_algorithm : s_sensor.Algorithms) { pc_algorithm->Update(s_sensor.ProjectionMatrix, arrFrustumPlanes, cCameraToWorldTransform, cCameraLocation, cBoundingBoxPosition, cBoundingBoxHalfExtents); /* transfer any rays to the controllable entity for rendering */ vecCheckedRays.insert(std::end(vecCheckedRays), std::begin(pc_algorithm->GetCheckedRays()), std::end(pc_algorithm->GetCheckedRays())); } } } /****************************************/ /****************************************/ REGISTER_SENSOR(CCameraDefaultSensor, "cameras", "default", "Michael Allwright [allsey87@gmail.com]", "1.0", "A generic multi-camera sensor capable of running various algorithms", "The generic multi-camera sensor can be attached to any composable entity in\n" "ARGoS that contains an embodied entity with at least one anchor. The sensor\n" "can be initialized with a number of cameras each running different algorithms\n" "for detecting different objects in the simulation. The sensor is designed so\n" "that algorithms can project a feature in the simulation on to the virtual\n" "sensor and store its 2D pixel coordinates as a reading. The implementation\n" "of algorithms that behave differently, however, is also possible.\n\n" "This sensor is disabled by default, and must be enabled before it can be\n" "used.\n\n" "REQUIRED XML CONFIGURATION\n\n" " <controllers>\n" " ...\n" " <my_controller ...>\n" " ...\n" " <sensors>\n" " ...\n" " <cameras implementation=\"default\"/>\n" " ...\n" " </sensors>\n" " ...\n" " </my_controller>\n" " ...\n" " </controllers>\n\n" "OPTIONAL XML CONFIGURATION\n\n" "It is possible to draw the frustum of each camera sensor in the OpenGL\n" "visualization. This can be useful for sensor debugging but also to understand\n" "what's wrong in your controller. To turn this functionality on, add the\n" "attribute \"show_frustum\" as follows:\n\n" " <controllers>\n" " ...\n" " <my_controller ...>\n" " ...\n" " <sensors>\n" " ...\n" " <cameras implementation=\"default\" show_frustum=\"true\"/>\n" " ...\n" " </sensors>\n" " ...\n" " </my_controller>\n" " ...\n" " </controllers>\n\n" "To add a camera to the plugin, create a camera node as shown in the following\n" "example. A camera is defined by its range (how close and how far the camera\n" "can see), its anchor and its position and orientation offsets from that\n" "that anchor, its focal length and principal point (which define the\n" "projection matrix), and its resolution.\n\n" " <controllers>\n" " ...\n" " <my_controller ...>\n" " ...\n" " <sensors>\n" " ...\n" " <cameras implementation=\"default\" show_frustum=\"true\">\n" " <camera id=\"camera0\" range=\"0.025:0.25\" anchor=\"origin\"\n" " position=\"0.1,0,0.1\" orientation=\"90,-90,0\"\n" " focal_length=\"800,800\" principal_point=\"320,240\"\n" " resolution=\"640,480\"/>\n" " </cameras>\n" " ...\n" " </sensors>\n" " ...\n" " </my_controller>\n" " ...\n" " </controllers>\n\n" "To run an algorithm on the camera sensor, simply add the algorithm as a node\n" "under the camera node. At the time of writing, three algorithms are available\n" "by default: led_detector, directional_led_detector, and tag_detector. Each of\n" "algorithms requires a medium attribute that specifies the medium where the\n" "target entities are indexed. By setting the show_rays attribute to true, you\n" "can see whether or not a target was partially occluded by another object in\n" "the simulation. For example:\n\n" " <controllers>\n" " ...\n" " <my_controller ...>\n" " ...\n" " <sensors>\n" " ...\n" " <cameras implementation=\"default\" show_frustum=\"true\">\n" " <camera id=\"camera0\" range=\"0.025:0.25\" anchor=\"origin\"\n" " position=\"0.1,0,0.1\" orientation=\"90,-90,0\"\n" " focal_length=\"800,800\" principal_point=\"320,240\"\n" " resolution=\"640,480\">\n" " <led_detector medium=\"leds\" show_rays=\"true\"/>\n" " </camera>\n" " </cameras>\n" " ...\n" " </sensors>\n" " ...\n" " </my_controller>\n" " ...\n" " </controllers>\n", "Usable"); }
51.759777
107
0.554128
yiftachn
dbd4bac249440c2fb749f49563a123b468e79220
572
cpp
C++
tests/test.cpp
Darioshka/lab_03
24d79f98900451ccd336d9c9b930d6c4d3d7f0dd
[ "MIT" ]
null
null
null
tests/test.cpp
Darioshka/lab_03
24d79f98900451ccd336d9c9b930d6c4d3d7f0dd
[ "MIT" ]
null
null
null
tests/test.cpp
Darioshka/lab_03
24d79f98900451ccd336d9c9b930d6c4d3d7f0dd
[ "MIT" ]
null
null
null
// Copyright 2018 Your Name <your_email> #include <gtest/gtest.h> #include "header.hpp" TEST(Example, EmptyTest) { int*a = new int; a[0] = 42; int*b = new int; b[0] = 20; SharedPtr<int> link1(a); SharedPtr<int> link2(link1); SharedPtr<int> link3(b); EXPECT_EQ(static_cast<int>(link1.get()[0]), 42); EXPECT_EQ(static_cast<int>(link2.get()[0]), 42); link1.swap(link3); EXPECT_EQ(static_cast<int>(link1.get()[0]), 20); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
24.869565
52
0.624126
Darioshka
dbd83e5512cfabf81133a23131ebb9a96e15fba9
2,922
cpp
C++
Projects/Skylicht/Components/Source/ParticleSystem/Particles/Zones/CPolyLine.cpp
tsukoyumi/skylicht-engine
3b88d9718e87e552152633ef60e3f889869b71de
[ "MIT" ]
310
2019-11-25T04:14:11.000Z
2022-03-31T23:39:19.000Z
Projects/Skylicht/Components/Source/ParticleSystem/Particles/Zones/CPolyLine.cpp
tsukoyumi/skylicht-engine
3b88d9718e87e552152633ef60e3f889869b71de
[ "MIT" ]
79
2019-11-17T07:51:02.000Z
2022-03-22T08:49:41.000Z
Projects/Skylicht/Components/Source/ParticleSystem/Particles/Zones/CPolyLine.cpp
tsukoyumi/skylicht-engine
3b88d9718e87e552152633ef60e3f889869b71de
[ "MIT" ]
24
2020-05-10T09:37:55.000Z
2022-03-05T13:19:31.000Z
/* !@ MIT License Copyright (c) 2020 Skylicht Technology CO., LTD Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This file is part of the "Skylicht Engine". https://github.com/skylicht-lab/skylicht-engine !# */ #include "pch.h" #include "CPolyLine.h" #include "ParticleSystem/Particles/CParticle.h" #include "ParticleSystem/Particles/CGroup.h" namespace Skylicht { namespace Particle { CPolyLine::CPolyLine(const core::array<core::vector3df>& point) : CZone(PolyLine), m_length(0.0f), m_normal(0.0f, 1.0f, 0.0f) { setLine(point); } CPolyLine::~CPolyLine() { } void CPolyLine::setLine(const core::array<core::vector3df>& point) { if (point.size() < 2) return; m_point = point; m_segments.set_used(0); m_ratios.set_used(0); m_length = 0.0f; for (u32 i = 0, n = (u32)point.size(); i < n - 1; i++) { float d = point[i].getDistanceFrom(point[i + 1]); m_length = m_length + d; m_segments.push_back(d); } float d = 0.0f; for (u32 i = 0, n = (u32)m_segments.size(); i < n; i++) { d = d + m_segments[i]; m_ratios.push_back(d / m_length); } } void CPolyLine::generatePosition(CParticle& particle, bool full, CGroup* group) { float ratio = random(0.0f, 1.0f); int segmentId = 0; float length = 0.0f; float l = 0.0f; for (u32 i = 0, n = (u32)m_segments.size(); i < n; i++) { segmentId = i; if (ratio < m_ratios[i]) { l = (m_ratios[i] - ratio) * m_length; break; } } const core::vector3df& p1 = m_point[segmentId]; const core::vector3df& p2 = m_point[segmentId + 1]; core::vector3df pos = group->getTransformPosition(p1); core::vector3df direction = group->getTransformPosition(p2) - pos; direction.normalize(); particle.Position = pos + direction * l; } core::vector3df CPolyLine::computeNormal(const core::vector3df& point, CGroup* group) { return m_normal; } } }
27.055556
141
0.688227
tsukoyumi
dbd86ef518460542975a29739d90d9e910c2b75e
524
cc
C++
chromium/components/web_view/client_initiated_frame_connection.cc
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
null
null
null
chromium/components/web_view/client_initiated_frame_connection.cc
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
null
null
null
chromium/components/web_view/client_initiated_frame_connection.cc
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/web_view/client_initiated_frame_connection.h" #include <utility> namespace web_view { ClientInitiatedFrameConnection::ClientInitiatedFrameConnection( mojom::FrameClientPtr frame_client) : frame_client_(std::move(frame_client)) {} ClientInitiatedFrameConnection::~ClientInitiatedFrameConnection() {} } // namespace web_view
29.111111
73
0.791985
wedataintelligence