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
b5cd5ed893535932712ac661a6939930b707839c
12,034
cc
C++
xarm_api/src/xarm_core/instruction/uxbus_cmd.cc
stevewen/xarm_ros
93770d50faf83be627ad16c268c7477ba72187c5
[ "BSD-3-Clause" ]
null
null
null
xarm_api/src/xarm_core/instruction/uxbus_cmd.cc
stevewen/xarm_ros
93770d50faf83be627ad16c268c7477ba72187c5
[ "BSD-3-Clause" ]
null
null
null
xarm_api/src/xarm_core/instruction/uxbus_cmd.cc
stevewen/xarm_ros
93770d50faf83be627ad16c268c7477ba72187c5
[ "BSD-3-Clause" ]
null
null
null
/* Copyright 2017 UFACTORY Inc. All Rights Reserved. * * Software License Agreement (BSD License) * * Author: Jimy Zhang <jimy92@163.com> ============================================================================*/ #include "xarm/instruction/uxbus_cmd.h" #include "xarm/instruction/servo3_config.h" #include "xarm/instruction/uxbus_cmd_config.h" UxbusCmd::UxbusCmd(void) {} UxbusCmd::~UxbusCmd(void) {} int UxbusCmd::check_xbus_prot(u8 *data, u8 funcode) { return -11; } int UxbusCmd::send_pend(u8 funcode, int num, int timeout, u8 *rx_data) { return -11; } int UxbusCmd::send_xbus(u8 funcode, u8 *txdata, int num) { return -11; } void UxbusCmd::close(void) {} int UxbusCmd::set_nu8(u8 funcode, u8 *datas, int num) { int ret = send_xbus(funcode, datas, num); if (ret != 0) return UXBUS_STATE::ERR_NOTTCP; ret = send_pend(funcode, 0, UXBUS_CONF::SET_TIMEOUT, NULL); return ret; } int UxbusCmd::get_nu8(u8 funcode, u8 num, u8 *rx_data) { int ret = send_xbus(funcode, 0, 0); if (ret != 0) return UXBUS_STATE::ERR_NOTTCP; ret = send_pend(funcode, num, UXBUS_CONF::GET_TIMEOUT, rx_data); return ret; } int UxbusCmd::get_nu16(u8 funcode, u8 num, u16 *rx_data) { u8 datas[num * 2]; int ret = send_xbus(funcode, 0, 0); if (ret != 0) return UXBUS_STATE::ERR_NOTTCP; ret = send_pend(funcode, num * 2, UXBUS_CONF::GET_TIMEOUT, datas); for (int i = 0; i < num; i++) rx_data[i] = bin8_to_16(&datas[i * 2]); return ret; } int UxbusCmd::set_nfp32(u8 funcode, fp32 *datas, u8 num) { u8 hexdata[num * 4] = {0}; nfp32_to_hex(datas, hexdata, num); int ret = send_xbus(funcode, hexdata, num * 4); if (0 != ret) return UXBUS_STATE::ERR_NOTTCP; ret = send_pend(funcode, 0, UXBUS_CONF::SET_TIMEOUT, NULL); return ret; } int UxbusCmd::get_nfp32(u8 funcode, u8 num, fp32 *rx_data) { u8 datas[num * 4] = {0}; int ret = send_xbus(funcode, 0, 0); if (0 != ret) return UXBUS_STATE::ERR_NOTTCP; ret = send_pend(funcode, num * 4, UXBUS_CONF::GET_TIMEOUT, datas); hex_to_nfp32(datas, rx_data, num); return ret; } int UxbusCmd::swop_nfp32(u8 funcode, fp32 tx_datas[], u8 txn, fp32 *rx_data, u8 rxn) { u8 hexdata[128] = {0}; nfp32_to_hex(tx_datas, hexdata, txn); int ret = send_xbus(funcode, hexdata, txn * 4); if (0 != ret) return UXBUS_STATE::ERR_NOTTCP; ret = send_pend(funcode, rxn * 4, UXBUS_CONF::GET_TIMEOUT, hexdata); hex_to_nfp32(hexdata, rx_data, rxn); return ret; } int UxbusCmd::is_nfp32(u8 funcode, fp32 datas[], u8 txn, int *value) { u8 hexdata[txn * 4] = {0}; nfp32_to_hex(datas, hexdata, txn); int ret = send_xbus(funcode, hexdata, txn * 4); if (0 != ret) return UXBUS_STATE::ERR_NOTTCP; ret = send_pend(funcode, 1, UXBUS_CONF::GET_TIMEOUT, hexdata); *value = hexdata[0]; return ret; } int UxbusCmd::get_version(u8 rx_data[40]) { return get_nu8(UXBUS_RG::GET_VERSION, 40, rx_data); } int UxbusCmd::motion_en(u8 id, u8 value) { u8 txdata[2]; txdata[0] = id; txdata[1] = value; int ret = set_nu8(UXBUS_RG::MOTION_EN, txdata, 2); return ret; } int UxbusCmd::set_state(u8 value) { u8 txdata[1]; txdata[0] = value; int ret = set_nu8(UXBUS_RG::SET_STATE, txdata, 1); return ret; } int UxbusCmd::get_state(u8 *rx_data) { int ret = get_nu8(UXBUS_RG::GET_STATE, 1, rx_data); return ret; } int UxbusCmd::get_cmdnum(u16 *rx_data) { int ret = get_nu16(UXBUS_RG::GET_CMDNUM, 1, rx_data); return ret; } int UxbusCmd::get_errcode(u8 *rx_data) { int ret = get_nu8(UXBUS_RG::GET_ERROR, 2, rx_data); return ret; } int UxbusCmd::clean_err(void) { u8 txdata[1]; txdata[0] = 0; int ret = set_nu8(UXBUS_RG::CLEAN_ERR, txdata, 0); return ret; } int UxbusCmd::clean_war(void) { u8 txdata[1]; txdata[0] = 0; int ret = set_nu8(UXBUS_RG::CLEAN_WAR, txdata, 0); return ret; } int UxbusCmd::set_brake(u8 axis, u8 en) { u8 txdata[2] = {0}; txdata[0] = axis; txdata[1] = en; int ret = set_nu8(UXBUS_RG::SET_BRAKE, txdata, 2); return ret; } int UxbusCmd::set_mode(u8 value) { u8 txdata[1]; txdata[0] = value; int ret = set_nu8(UXBUS_RG::SET_MODE, txdata, 1); return ret; } int UxbusCmd::move_line(fp32 mvpose[6], fp32 mvvelo, fp32 mvacc, fp32 mvtime) { int i; fp32 txdata[9] = {0}; for (i = 0; i < 6; i++) txdata[i] = mvpose[i]; txdata[6] = mvvelo; txdata[7] = mvacc; txdata[8] = mvtime; int ret = set_nfp32(UXBUS_RG::MOVE_LINE, txdata, 9); return ret; } int UxbusCmd::move_lineb(fp32 mvpose[6], fp32 mvvelo, fp32 mvacc, fp32 mvtime, fp32 mvradii) { int i; fp32 txdata[10] = {0}; for (i = 0; i < 6; i++) txdata[i] = mvpose[i]; txdata[6] = mvvelo; txdata[7] = mvacc; txdata[8] = mvtime; txdata[9] = mvradii; int ret = set_nfp32(UXBUS_RG::MOVE_LINEB, txdata, 10); return ret; } int UxbusCmd::move_joint(fp32 mvjoint[7], fp32 mvvelo, fp32 mvacc, fp32 mvtime) { int i; fp32 txdata[10] = {0}; for (i = 0; i < 7; i++) txdata[i] = mvjoint[i]; txdata[7] = mvvelo; txdata[8] = mvacc; txdata[9] = mvtime; int ret = set_nfp32(UXBUS_RG::MOVE_JOINT, txdata, 10); return ret; } int UxbusCmd::move_gohome(fp32 mvvelo, fp32 mvacc, fp32 mvtime) { fp32 txdata[3] = {0}; txdata[0] = mvvelo; txdata[1] = mvacc; txdata[2] = mvtime; int ret = set_nfp32(UXBUS_RG::MOVE_HOME, txdata, 3); return ret; } int UxbusCmd::move_servoj(fp32 mvjoint[7], fp32 mvvelo, fp32 mvacc, fp32 mvtime) { int i; fp32 txdata[10] = {0}; for (i = 0; i < 7; i++) txdata[i] = mvjoint[i]; txdata[7] = mvvelo; txdata[8] = mvacc; txdata[9] = mvtime; int ret = set_nfp32(UXBUS_RG::MOVE_SERVOJ, txdata, 10); return ret; } int UxbusCmd::sleep_instruction(fp32 sltime) { fp32 txdata[1] = {0}; txdata[0] = sltime; int ret = set_nfp32(UXBUS_RG::SLEEP_INSTT, txdata, 1); return ret; } int UxbusCmd::set_tcp_jerk(fp32 jerk) { fp32 txdata[1] = {0}; txdata[0] = jerk; int ret = set_nfp32(UXBUS_RG::SET_TCP_JERK, txdata, 1); return ret; } int UxbusCmd::set_tcp_maxacc(fp32 maxacc) { fp32 txdata[1] = {0}; txdata[0] = maxacc; int ret = set_nfp32(UXBUS_RG::SET_TCP_MAXACC, txdata, 1); return ret; } int UxbusCmd::set_joint_jerk(fp32 jerk) { fp32 txdata[1] = {0}; txdata[0] = jerk; int ret = set_nfp32(UXBUS_RG::SET_JOINT_JERK, txdata, 1); return ret; } int UxbusCmd::set_joint_maxacc(fp32 maxacc) { fp32 txdata[1] = {0}; txdata[0] = maxacc; int ret = set_nfp32(UXBUS_RG::SET_JOINT_MAXACC, txdata, 1); return ret; } int UxbusCmd::set_tcp_offset(fp32 pose_offset[6]) { return set_nfp32(UXBUS_RG::SET_TCP_OFFSET, pose_offset, 6); } int UxbusCmd::clean_conf() { return set_nu8(UXBUS_RG::CLEAN_CONF, 0, 0); } int UxbusCmd::save_conf() { return set_nu8(UXBUS_RG::SAVE_CONF, 0, 0); } int UxbusCmd::get_tcp_pose(fp32 pose[6]) { return get_nfp32(UXBUS_RG::GET_TCP_POSE, 6, pose); } int UxbusCmd::get_joint_pose(fp32 angles[7]) { return get_nfp32(UXBUS_RG::GET_JOINT_POS, 7, angles); } int UxbusCmd::get_ik(fp32 pose[6], fp32 angles[7]) { return swop_nfp32(UXBUS_RG::GET_IK, pose, 6, angles, 7); } int UxbusCmd::get_fk(fp32 angles[7], fp32 pose[6]) { return swop_nfp32(UXBUS_RG::GET_FK, angles, 7, pose, 6); } int UxbusCmd::is_joint_limit(fp32 joint[7], int *value) { return is_nfp32(UXBUS_RG::IS_JOINT_LIMIT, joint, 7, value); } int UxbusCmd::is_tcp_limit(fp32 pose[6], int *value) { return is_nfp32(UXBUS_RG::IS_TCP_LIMIT, pose, 6, value); } int UxbusCmd::gripper_addr_w16(u8 id, u16 addr, fp32 value) { u8 txdata[7]; txdata[0] = id; bin16_to_8(addr, &txdata[1]); fp32_to_hex(value, &txdata[3]); int ret = send_xbus(UXBUS_RG::GRIPP_W16B, txdata, 7); if (0 != ret) return UXBUS_STATE::ERR_NOTTCP; ret = send_pend(UXBUS_RG::GRIPP_W16B, 0, UXBUS_CONF::GET_TIMEOUT, NULL); return ret; } int UxbusCmd::gripper_addr_r16(u8 id, u16 addr, fp32 *value) { u8 txdata[3], rx_data[4]; txdata[0] = id; bin16_to_8(addr, &txdata[1]); int ret = send_xbus(UXBUS_RG::GRIPP_R16B, txdata, 3); if (0 != ret) return UXBUS_STATE::ERR_NOTTCP; ret = send_pend(UXBUS_RG::GRIPP_R16B, 4, UXBUS_CONF::GET_TIMEOUT, rx_data); *value = bin8_to_16(rx_data); return ret; } int UxbusCmd::gripper_addr_w32(u8 id, u16 addr, fp32 value) { u8 txdata[7]; txdata[0] = id; bin16_to_8(addr, &txdata[1]); fp32_to_hex(value, &txdata[3]); int ret = send_xbus(UXBUS_RG::GRIPP_W32B, txdata, 7); if (0 != ret) return UXBUS_STATE::ERR_NOTTCP; ret = send_pend(UXBUS_RG::GRIPP_W32B, 0, UXBUS_CONF::GET_TIMEOUT, NULL); return ret; } int UxbusCmd::gripper_addr_r32(u8 id, u16 addr, fp32 *value) { u8 txdata[3], rx_data[4]; txdata[0] = id; bin16_to_8(addr, &txdata[1]); int ret = send_xbus(UXBUS_RG::GRIPP_R32B, txdata, 3); if (0 != ret) return UXBUS_STATE::ERR_NOTTCP; ret = send_pend(UXBUS_RG::GRIPP_R32B, 4, UXBUS_CONF::GET_TIMEOUT, rx_data); *value = bin8_to_32(rx_data); return ret; } int UxbusCmd::gripper_set_en(u16 value) { return gripper_addr_w16(UXBUS_CONF::GRIPPER_ID, SERVO3_RG::CON_EN, value); } int UxbusCmd::gripper_set_mode(u16 value) { return gripper_addr_w16(UXBUS_CONF::GRIPPER_ID, SERVO3_RG::CON_MODE, value); } int UxbusCmd::gripper_set_zero() { return gripper_addr_w16(UXBUS_CONF::GRIPPER_ID, SERVO3_RG::MT_ZERO, 1); } int UxbusCmd::gripper_get_pos(fp32 *pulse) { return gripper_addr_r32(UXBUS_CONF::GRIPPER_ID, SERVO3_RG::CURR_POS, pulse); } int UxbusCmd::gripper_set_pos(fp32 pulse) { return gripper_addr_w32(UXBUS_CONF::GRIPPER_ID, SERVO3_RG::TAGET_POS, pulse); } int UxbusCmd::gripper_set_posspd(fp32 speed) { return gripper_addr_w16(UXBUS_CONF::GRIPPER_ID, SERVO3_RG::POS_SPD, speed); } int UxbusCmd::gripper_get_errcode(u8 rx_data[2]) { return get_nu8(UXBUS_RG::GPGET_ERR, 2, rx_data); } int UxbusCmd::gripper_clean_err() { return gripper_addr_w16(UXBUS_CONF::GRIPPER_ID, SERVO3_RG::RESET_ERR, 1); } int UxbusCmd::servo_set_zero(u8 id) { u8 txdata[1]; txdata[0] = id; int ret = set_nu8(UXBUS_RG::SERVO_ZERO, txdata, 1); return ret; } int UxbusCmd::servo_get_dbmsg(u8 rx_data[16]) { int ret = get_nu8(UXBUS_RG::SERVO_DBMSG, 16, rx_data); return ret; } int UxbusCmd::servo_addr_w16(u8 id, u16 addr, fp32 value) { u8 txdata[7]; txdata[0] = id; bin16_to_8(addr, &txdata[1]); fp32_to_hex(value, &txdata[3]); int ret = send_xbus(UXBUS_RG::SERVO_W16B, txdata, 7); if (0 != ret) return UXBUS_STATE::ERR_NOTTCP; ret = send_pend(UXBUS_RG::SERVO_W16B, 0, UXBUS_CONF::GET_TIMEOUT, NULL); return ret; } int UxbusCmd::servo_addr_r16(u8 id, u16 addr, fp32 *value) { u8 txdata[3], rx_data[4]; txdata[0] = id; bin16_to_8(addr, &txdata[1]); int ret = send_xbus(UXBUS_RG::SERVO_R16B, txdata, 3); if (0 != ret) return UXBUS_STATE::ERR_NOTTCP; ret = send_pend(UXBUS_RG::SERVO_R16B, 4, UXBUS_CONF::GET_TIMEOUT, rx_data); *value = bin8_to_16(rx_data); return ret; } int UxbusCmd::servo_addr_w32(u8 id, u16 addr, fp32 value) { u8 txdata[7]; txdata[0] = id; bin16_to_8(addr, &txdata[1]); fp32_to_hex(value, &txdata[3]); int ret = send_xbus(UXBUS_RG::SERVO_W32B, txdata, 7); if (0 != ret) return UXBUS_STATE::ERR_NOTTCP; ret = send_pend(UXBUS_RG::SERVO_W32B, 0, UXBUS_CONF::GET_TIMEOUT, NULL); return ret; } int UxbusCmd::servo_addr_r32(u8 id, u16 addr, fp32 *value) { u8 txdata[3], rx_data[4]; txdata[0] = id; bin16_to_8(addr, &txdata[1]); int ret = send_xbus(UXBUS_RG::SERVO_R32B, txdata, 3); if (0 != ret) return UXBUS_STATE::ERR_NOTTCP; ret = send_pend(UXBUS_RG::SERVO_R32B, 4, UXBUS_CONF::GET_TIMEOUT, rx_data); *value = bin8_to_32(rx_data); return ret; }
28.248826
80
0.650241
stevewen
b5cd79a05b721e64c5f9a08ccd37f1c95e5f6e76
3,585
cc
C++
crypto/uuid.cc
stablecc/scclib
cedcb3b37a814d3a393e128db7aa9753f518cbaf
[ "BSD-3-Clause" ]
null
null
null
crypto/uuid.cc
stablecc/scclib
cedcb3b37a814d3a393e128db7aa9753f518cbaf
[ "BSD-3-Clause" ]
10
2022-02-27T18:52:11.000Z
2022-03-21T14:11:35.000Z
crypto/uuid.cc
stablecc/scclib
cedcb3b37a814d3a393e128db7aa9753f518cbaf
[ "BSD-3-Clause" ]
null
null
null
/* BSD 3-Clause License Copyright (c) 2022, Stable Cloud Computing, Inc. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder 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 HOLDER 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 <crypto/uuid.h> #include <ctype.h> #include <algorithm> #include <vector> #include <string> #include <sstream> #include <crypto/random.h> #include <encode/hex.h> using namespace scc::crypto; using scc::encode::Hex; std::ostream& operator <<(std::ostream& os, const Uuid& u) { return os.write(u.val().c_str(), u.val().size()); } void scc::crypto::PrintTo(const Uuid& u, std::ostream* os) { *os << u; } const std::string Uuid::zero = "00000000-0000-0000-0000-000000000000"; void Uuid::assign(const std::string& s) { std::stringstream str(s); std::string tok; std::vector<std::string> v; while (std::getline(str, tok, '-')) { v.push_back(tok); } if (v.size() != 5) { m_uuid = zero; return; } if (v[0].size() != 8) { m_uuid = zero; return; } if (v[1].size() != 4) { m_uuid = zero; return; } if (v[2].size() != 4) { m_uuid = zero; return; } if (v[3].size() != 4) { m_uuid = zero; return; } if (v[4].size() != 12) { m_uuid = zero; return; } for (auto& x : v) { for (auto b : x) { if ( ((b<'0')||(b>'9')) && ((b<'a')||(b>'f')) && ((b<'A')||(b>'F')) ) { m_uuid = zero; return; } } } // NOTE: does not check for binary requirements m_uuid = s; std::for_each(m_uuid.begin(), m_uuid.end(), [](char& c) { c = tolower(c); }); } std::string Uuid::generate() { std::vector<char> u(16); RandomEngine::rand_bytes(&u[0], 16); // set most significant bits of time_hi_and_version (octet 6) to 0100 (version) u[6] &= 0x4f; u[6] |= 0x40; // set most significant bits of clock_seq_hi_and_reserved (octet 8) to 01 u[8] &= 0x7f; u[8] |= 0x40; // emit hex HxHxHxHx-HxHx-HxHx-HxHx-HxHxHxHxHxHx std::stringstream uuid; typedef std::vector<char> CharVec; uuid << Hex::bin_to_hex(CharVec(&u[0], &u[4])); uuid << "-"; uuid << Hex::bin_to_hex(CharVec(&u[4], &u[6])); uuid << "-"; uuid << Hex::bin_to_hex(CharVec(&u[6], &u[8])); uuid << "-"; uuid << Hex::bin_to_hex(CharVec(&u[8], &u[10])); uuid << "-"; uuid << Hex::bin_to_hex(CharVec(&u[10], &u[16])); m_uuid = uuid.str(); return m_uuid; }
28.228346
80
0.67894
stablecc
b5cda330eefe38e66510d1bc15d4e51a916d1222
543
hpp
C++
liboh/include/oh/ProxyLightObject.hpp
princeofcode/sirikata
41d33a574934aea2d8a30ce3514509b7a4ec182e
[ "BSD-3-Clause" ]
1
2016-05-09T07:55:37.000Z
2016-05-09T07:55:37.000Z
liboh/include/oh/ProxyLightObject.hpp
princeofcode/sirikata
41d33a574934aea2d8a30ce3514509b7a4ec182e
[ "BSD-3-Clause" ]
null
null
null
liboh/include/oh/ProxyLightObject.hpp
princeofcode/sirikata
41d33a574934aea2d8a30ce3514509b7a4ec182e
[ "BSD-3-Clause" ]
null
null
null
#ifndef _SIRIKATA_PROXY_LIGHT_OBJECT_HPP_ #define _SIRIKATA_PROXY_LIGHT_OBJECT_HPP_ #include "LightListener.hpp" #include "ProxyPositionObject.hpp" namespace Sirikata { /** * This class represents a ProxyObject that holds a LightInfo */ class SIRIKATA_OH_EXPORT ProxyLightObject : public MarkovianProvider1<LightListenerPtr,LightInfo>, public ProxyPositionObject { public: ProxyLightObject():MarkovianProvider1<LightListenerPtr,LightInfo>(LightInfo()){} void update(const LightInfo &li) { notify(li); } }; } #endif
27.15
84
0.779006
princeofcode
b5cdb76ac53f7881584cc514459e4a5c2d0db674
3,520
cpp
C++
ThreadTaxi.cpp
MapleStoryGameHack/Deprecated-RwBox-Plus
df927665c316b43791c4b72e2ac8a00789d05877
[ "MIT" ]
1
2021-07-11T13:01:57.000Z
2021-07-11T13:01:57.000Z
ThreadTaxi.cpp
MapleStoryGameHack/Deprecated-RwBox-Plus
df927665c316b43791c4b72e2ac8a00789d05877
[ "MIT" ]
null
null
null
ThreadTaxi.cpp
MapleStoryGameHack/Deprecated-RwBox-Plus
df927665c316b43791c4b72e2ac8a00789d05877
[ "MIT" ]
null
null
null
//--------------------------------------------------------------------------- #pragma hdrstop #include "Map.h"; #include "ThreadTaxi.h" #include "Pointer.h" #include "Function.h" #include "WindowHook.h" //--------------------------------------------------------------------------- TThreadTaxi* ThreadTaxi ; __fastcall TThreadTaxi::TThreadTaxi(bool CreateSuspended ,long sMap,long eMap , MLPROC proc) : TThread(CreateSuspended) { this->proc = proc; isRunning = true; this->sMap = sMap; this->eMap = eMap; } void __fastcall TThreadTaxi::Start() { } void __fastcall TThreadTaxi::TaxiGo(long sMap , long eMap) { this->sMap = sMap; this->eMap = eMap; status = TaxiStart; } TThreadTaxi::TaxiStatus TThreadTaxi::GetTaxiStatus() { return this->status; } void __fastcall TThreadTaxi::TaxiControl( long* & tmp) { long cmap = ReadPointer(MapBase,MapIDOffset); long hp; POINT pt; if( (*tmp) == sMap) // FirstTime { GetTeleportPoint(*tmp,*(tmp+1),pt); proc(1,*tmp,*(tmp+1)); TeleXY(true,pt.x,pt.y-5); tmp++; GetTeleportPoint(*tmp,*(tmp+1),pt); SetXY(true,pt.x,pt.y); Sleep(200); SendKey(hWndMS, VK_UP); while( *(DWORD*)PeopleBase != 0 && this->isRunning) { SetXY(true,pt.x,pt.y); SendKey(hWndMS, VK_UP); Sleep(100); } if(! this->isRunning) return; while( *(DWORD*)PeopleBase == 0 && this->isRunning) Sleep(100); if(! this->isRunning) return; if(*tmp != eMap) tmp++; Sleep(500); } else { GetTeleportPoint(*tmp,*(tmp+1),pt); proc(1,*tmp,*(tmp+1)); SetXY(true,pt.x,pt.y); Sleep(200); while( *(DWORD*)PeopleBase == 0 && this->isRunning) Sleep(100); if( cmap != *(tmp-1)) { delete tmp; sMap = cmap; tmp = SearchMapPath(sMap, eMap); Sleep(100); return; } SendKey(hWndMS, VK_UP); SetXY(true,pt.x,pt.y); Sleep(200); while( *(DWORD*)PeopleBase != 0 && this->isRunning) { SetXY(true,pt.x,pt.y); SendKey(hWndMS, VK_UP); Sleep(100); } if(! this->isRunning) return; while( *(DWORD*)PeopleBase == 0 && this->isRunning) Sleep(100); if(! this->isRunning) return; if(*tmp != eMap) tmp++; Sleep(500); } } void __fastcall TThreadTaxi::Execute() { proc(0,0,0); long *path = SearchMapPath(sMap, eMap); long *tmp = path; POINT pt; String name; status = TaxiStart; if( *tmp != eMap ) { while( *tmp != eMap && (status != TaxiStop && status != TaxiError ) && this->isRunning) { TaxiControl(tmp); } long cmap = ReadPointer(MapBase,MapIDOffset); if( *tmp == eMap && cmap != eMap ) { Sleep(700); SendKey(hWndMS, VK_UP); while( *(DWORD*)PeopleBase != 0 && this->isRunning) Sleep(100); while( *(DWORD*)PeopleBase == 0 && this->isRunning) Sleep(100); } } long cmap = ReadPointer(MapBase,MapIDOffset); if( cmap != eMap){ proc(-2,0,0); } Terminate(); } void __fastcall TThreadTaxi::Terminate() { proc(-1,0,0); this->isRunning = false; } void __fastcall TThreadTaxi::SetXY( bool s , int x, int y) { WritePointer(SystemBase,SpawnSwitchOffset,s); WritePointer(SystemBase,SpawnXOffset,x); WritePointer(SystemBase,SpawnYOffset,y); } void __fastcall TThreadTaxi::TeleXY( bool s , int x, int y) { WritePointer(PeopleBase,PeopleTeleX,x); WritePointer(PeopleBase,PeopleTeleY,y); WritePointer(PeopleBase,PeopleTeleSW,s); } #pragma package(smart_init)
21.728395
93
0.578977
MapleStoryGameHack
b5ce5589a216c73c7dcfc97d020e48d119c9b4cc
622
cc
C++
codeforces/1130/b.cc
Ashindustry007/competitive-programming
2eabd3975c029d235abb7854569593d334acae2f
[ "WTFPL" ]
506
2018-08-22T10:30:38.000Z
2022-03-31T10:01:49.000Z
codeforces/1130/b.cc
Ashindustry007/competitive-programming
2eabd3975c029d235abb7854569593d334acae2f
[ "WTFPL" ]
13
2019-08-07T18:31:18.000Z
2020-12-15T21:54:41.000Z
codeforces/1130/b.cc
Ashindustry007/competitive-programming
2eabd3975c029d235abb7854569593d334acae2f
[ "WTFPL" ]
234
2018-08-06T17:11:41.000Z
2022-03-26T10:56:42.000Z
// https://codeforces.com/contest/1130/problem/B #include<bits/stdc++.h> using namespace std; using ll=long long; using vi=vector<ll>; using vvi=vector<vi>; int main(){ ios::sync_with_stdio(0); cin.tie(0); ll n; cin>>n; vvi a(n); for(ll i=0;i<2*n;i++){ ll x; cin>>x; x--; a[x].push_back(i); } ll x=0,y=0; ll k=0; for(ll i=0;i<n;i++){ ll p1=a[i][0]; ll p2=a[i][1]; if(llabs(p1-x)+llabs(p2-y)<=llabs(p2-x)+llabs(p1-y)){ k+=llabs(p1-x)+llabs(p2-y); x=p1; y=p2; }else{ k+=llabs(p1-y)+llabs(p2-x); x=p2; y=p1; } } cout<<k<<endl; }
17.277778
57
0.512862
Ashindustry007
b5cefd2065c6c3cf7aaff7828bf4683581136abb
1,172
cpp
C++
OpenCV/facedetect.cpp
AmarOk1412/Scripts-CDSB
87a356ab32af231787b0831286053c2b5fef7abf
[ "WTFPL" ]
null
null
null
OpenCV/facedetect.cpp
AmarOk1412/Scripts-CDSB
87a356ab32af231787b0831286053c2b5fef7abf
[ "WTFPL" ]
null
null
null
OpenCV/facedetect.cpp
AmarOk1412/Scripts-CDSB
87a356ab32af231787b0831286053c2b5fef7abf
[ "WTFPL" ]
null
null
null
#include <opencv2/objdetect/objdetect.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <iostream> #include <stdio.h> #define ESC 27 using namespace std; using namespace cv; int main(int argc, const char** argv) { CascadeClassifier face_cascade; face_cascade.load("haarcascade_frontalface_alt.xml"); VideoCapture captureDevice; captureDevice.open(0); Mat captureFrame; Mat grayscaleFrame; namedWindow("RORI_EYE", 1); bool stop = false; while(!stop) { captureDevice >> captureFrame; cvtColor(captureFrame, grayscaleFrame, CV_BGR2GRAY); equalizeHist(grayscaleFrame, grayscaleFrame); std::vector<Rect> faces; //Find Faces face_cascade.detectMultiScale(grayscaleFrame, faces, 1.1, 3, CV_HAAR_FIND_BIGGEST_OBJECT|CV_HAAR_SCALE_IMAGE, Size(30,30)); for(int i = 0; i < faces.size(); i++) { Point pt1(faces[i].x + faces[i].width, faces[i].y + faces[i].height); Point pt2(faces[i].x, faces[i].y); rectangle(captureFrame, pt1, pt2, cvScalar(10, 30, 255, 0), 1, 8, 0); } imshow("RORI_EYE", captureFrame); int key = waitKey(10); if(key == ESC) stop = true; } return 0; }
20.206897
125
0.703925
AmarOk1412
b5d02d9f1cc28410f04a505d24a5922ca36f8690
3,339
cpp
C++
code_reading/oceanbase-master/deps/oblib/unittest/lib/container/test_ring_buffer.cpp
wangcy6/weekly_read
3a8837ee9cd957787ee1785e4066dd623e02e13a
[ "Apache-2.0" ]
null
null
null
code_reading/oceanbase-master/deps/oblib/unittest/lib/container/test_ring_buffer.cpp
wangcy6/weekly_read
3a8837ee9cd957787ee1785e4066dd623e02e13a
[ "Apache-2.0" ]
null
null
null
code_reading/oceanbase-master/deps/oblib/unittest/lib/container/test_ring_buffer.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 <gtest/gtest.h> #include "lib/container/ob_ring_array.h" #include "lib/allocator/ob_concurrent_fifo_allocator.h" #include "lib/stat/ob_diagnose_info.h" #include "lib/thread/thread_pool.h" using namespace oceanbase::common; using obsys::CThread; using oceanbase::lib::ThreadPool; class TestRingBuffer : public ::testing::Test, public ThreadPool { public: struct RBData { RBData() : valid_(0), val_(0) {} RBData(int64_t val) : valid_(1), val_(val) {} ~RBData() {} int64_t valid_; int64_t val_; int read_from(RBData* that) { int err = 0; if (that->valid_ == 0) { err = -ENOENT; } else { *this = *that; } return err; } int write_to(RBData* that) { int err = 0; if (valid_ == 0) { err = -EINVAL; // error("RBData invalid"); } else { *that = *this; } return err; } }; typedef ObRingArray<RBData> RingArray; TestRingBuffer() : seq_(0) { set_thread_count(8); allocator_.init(4 * 1024 * 1024, 4 * 1024 * 1024, OB_MALLOC_NORMAL_BLOCK_SIZE); assert(0 == rbuffer_.init(0, &allocator_)); limit_ = atoll(getenv("limit") ?: "1000000"); } virtual ~TestRingBuffer() {} virtual void SetUp() {} virtual void TearDown() {} void do_stress() { start(); int64_t last_seq = ATOMIC_LOAD(&seq_); while (ATOMIC_LOAD(&seq_) < limit_) { sleep(1); int64_t cur_seq = ATOMIC_LOAD(&seq_); LIB_LOG(INFO, "ring_buffer", "tps", cur_seq - last_seq); last_seq = cur_seq; } wait(); } int64_t get_seq() { return ATOMIC_FAA(&seq_, 1); } int insert(int64_t seq) { int err = 0; RBData data(seq); if (0 != (err = rbuffer_.set(seq, data))) { // error("rbuffer.set fail: seq=%ld err=%d", seq, err); } return err; } int del(int64_t seq) { return rbuffer_.truncate(seq); } int mix() { int err = 0; int64_t stable_size = 1000000; int64_t seq = 0; while ((seq = get_seq()) < limit_) { if (0 != (err = insert(seq))) { // error("insert fail: err=%d seq=%ld", err, seq); } if (seq > stable_size && (0 != (err = del(seq - stable_size)))) { // error("del fail: err=%d seq=%ld", err, seq - stable_size); } } return err; } void run1() final { mix(); } private: int64_t seq_ CACHE_ALIGNED; int64_t limit_; RingArray rbuffer_; ObConcurrentFIFOAllocator allocator_; }; // end of class Consumer TEST_F(TestRingBuffer, stress) { do_stress(); } int main(int argc, char* argv[]) { oceanbase::common::ObLogger::get_logger().set_log_level("debug"); testing::InitGoogleTest(&argc, argv); // testing::FLAGS_gtest_filter = "DO_NOT_RUN"; return RUN_ALL_TESTS(); }
24.021583
88
0.609763
wangcy6
b5d09e10d87dd250f44f3d9d73afb41ca07c0cb9
1,028
hpp
C++
Keys.hpp
dnasdw/ctrcdnfetch
f3a4dcfd5f6e615635e1acea8746cd67e5e83643
[ "MIT" ]
1
2020-10-26T17:13:32.000Z
2020-10-26T17:13:32.000Z
Keys.hpp
dnasdw/ctrcdnfetch
f3a4dcfd5f6e615635e1acea8746cd67e5e83643
[ "MIT" ]
null
null
null
Keys.hpp
dnasdw/ctrcdnfetch
f3a4dcfd5f6e615635e1acea8746cd67e5e83643
[ "MIT" ]
null
null
null
#ifndef __KEYS_HPP__ #define __KEYS_HPP__ #include "types.h" namespace NintendoData { namespace KeyUtils { namespace Storage { enum KeyType { KeyX, KeyY, KeyNormal }; void ReloadStorage(); const u8* GetKey(int keyslot, KeyType type = KeyX, bool retail = true); const u8* GetKeyX(int keyslot, bool retail = true) {return GetKey(keyslot, KeyX, retail);} const u8* GetKeyY(int keyslot, bool retail = true) {return GetKey(keyslot, KeyY, retail);} const u8* GetKeyNormal(int keyslot, bool retail = true) {return GetKey(keyslot, KeyNormal, retail);} } bool Scrambler(u8* outnormal, const u8* KeyX, const u8* KeyY); bool Scrambler(u8* outnormal, int keyslotX, const u8* keyY, bool retail = true) { return Scrambler(outnormal, Storage::GetKeyX(keyslotX, retail), keyY); } bool Scrambler(u8* outnormal, const u8* keyX, int keyslotY, bool retail = true) { return Scrambler(outnormal, keyX, Storage::GetKeyY(keyslotY, retail)); } void SeedKeyY(u8* keyY, const u8* seed); } } #endif
35.448276
103
0.703307
dnasdw
b5d1b131006a5d8e01b001fb277f2fd11aaf7080
1,411
cpp
C++
tests/module/object_test.cpp
mambaru/wfc
170bf87302487c0cedc40b47c84447a765894774
[ "MIT" ]
1
2018-10-18T10:15:53.000Z
2018-10-18T10:15:53.000Z
tests/module/object_test.cpp
mambaru/wfc
170bf87302487c0cedc40b47c84447a765894774
[ "MIT" ]
7
2019-12-04T23:36:03.000Z
2021-04-21T12:37:07.000Z
tests/module/object_test.cpp
mambaru/wfc
170bf87302487c0cedc40b47c84447a765894774
[ "MIT" ]
null
null
null
#define IOW_DISABLE_LOG #include <iow/logger.hpp> #include <wfc/domain_object.hpp> #include <wfc/module/instance.hpp> #include <wfc/module/singleton.hpp> #include <wfc/module/multiton.hpp> #include <fas/utility/ignore_args.hpp> struct itest: public wfc::iinterface { ~itest(){} }; struct options { int test = 33; }; struct options_json { JSON_NAME(test) typedef wfc::json::object< options, fas::type_list_n< wfc::json::member<n_test, options, int, &options::test> >::type > type; typedef typename type::serializer serializer; typedef typename type::member_list member_list; typedef typename type::target target; }; class test: public ::wfc::domain_object<itest, options> { }; JSON_NAME2(name_test, "test") class test_singleton : public ::wfc::singleton< name_test, ::wfc::instance<test>, options_json > {}; class test_multiton : public ::wfc::multiton< name_test, ::wfc::instance<test>, options_json > {}; template<typename T> int test_gen() { T t; t.create(nullptr); std::cout << "[" << t.interface_name() << "]" << std::endl; std::string genstr = t.generate(""); std::cout << genstr << std::endl; t.configure(genstr, nullptr); if (t.name()!="test") return 1; return 0; } int main() { options opt; opt.test=0; fas::ignore_arg(opt); int res = test_gen<test_singleton>(); res += test_gen<test_multiton>(); return res; }
18.565789
77
0.669029
mambaru
b5d417695dc6a5ef7d643a1cf3c2f9178f0f0f48
18,707
cpp
C++
gearoenix/render/graph/tree/gx-rnd-gr-tr-pbr.cpp
Hossein-Noroozpour/gearoenix
c8fa8b8946c03c013dad568d6d7a97d81097c051
[ "BSD-Source-Code" ]
35
2018-01-07T02:34:38.000Z
2022-02-09T05:19:03.000Z
gearoenix/render/graph/tree/gx-rnd-gr-tr-pbr.cpp
Hossein-Noroozpour/gearoenix
c8fa8b8946c03c013dad568d6d7a97d81097c051
[ "BSD-Source-Code" ]
111
2017-09-20T09:12:36.000Z
2020-12-27T12:52:03.000Z
gearoenix/render/graph/tree/gx-rnd-gr-tr-pbr.cpp
Hossein-Noroozpour/gearoenix
c8fa8b8946c03c013dad568d6d7a97d81097c051
[ "BSD-Source-Code" ]
5
2020-02-11T11:17:37.000Z
2021-01-08T17:55:43.000Z
#include "gx-rnd-gr-tr-pbr.hpp" #include "../../../core/asset/gx-cr-asset-manager.hpp" #include "../../../core/sync/gx-cr-sync-kernel-workers.hpp" #include "../../../physics/gx-phs-engine.hpp" #include "../../../system/gx-sys-application.hpp" #include "../../camera/gx-rnd-cmr-perspective.hpp" #include "../../engine/gx-rnd-eng-engine.hpp" #include "../../light/gx-rnd-lt-cascade-info.hpp" #include "../../light/gx-rnd-lt-directional.hpp" #include "../../reflection/gx-rnd-rfl-runtime.hpp" #include "../../scene/gx-rnd-scn-manager.hpp" #include "../../skybox/gx-rnd-sky-cube.hpp" #include "../../skybox/gx-rnd-sky-equirectangular.hpp" #include "../../texture/gx-rnd-txt-target.hpp" #include "../node/gx-rnd-gr-nd-forward-pbr.hpp" #include "../node/gx-rnd-gr-nd-irradiance-convoluter.hpp" #include "../node/gx-rnd-gr-nd-mipmap-generator.hpp" #include "../node/gx-rnd-gr-nd-radiance-convoluter.hpp" #include "../node/gx-rnd-gr-nd-shadow-mapper.hpp" #include "../node/gx-rnd-gr-nd-skybox-cube.hpp" #include "../node/gx-rnd-gr-nd-skybox-equirectangular.hpp" #include "../node/gx-rnd-gr-nd-unlit.hpp" #define GX_START_TASKS \ unsigned int task_number = 0; \ const unsigned int kernels_count = e->get_kernels()->get_threads_count(); #define GX_DO_TASK(expr) \ { \ if (task_number == kernel_index) { \ expr; \ } \ task_number = (task_number + 1) % kernels_count; \ } void gearoenix::render::graph::tree::Pbr::CameraData::clear() noexcept { skyboxes.clear(); opaques.forward_pbr = nullptr; opaques.unlit = nullptr; transparencies.clear(); } void gearoenix::render::graph::tree::Pbr::update_camera( const scene::Scene* const scn, camera::Camera* const cam, graph::tree::Pbr::CameraData& camera_nodes) noexcept { camera_nodes.clear(); update_skyboxes(scn, cam, camera_nodes); update_opaque(cam->get_seen_static_opaque_meshes(), scn, cam, camera_nodes); update_opaque(cam->get_seen_dynamic_opaque_meshes(), scn, cam, camera_nodes); update_transparent(cam->get_seen_transparent_meshes(), scn, cam, camera_nodes); for (auto& c : cam->get_cascades()) { cascades.push_back(&c); } } void gearoenix::render::graph::tree::Pbr::update_skyboxes(const scene::Scene* const scn, const camera::Camera* const cam, CameraData& camera_nodes) noexcept { node::SkyboxCube* previous_cube = nullptr; node::SkyboxEquirectangular* previous_equirectangular = nullptr; for (const auto& id_skybox : scn->get_skyboxs()) { const auto* const sky = id_skybox.second.get(); if (!sky->get_enabled()) continue; switch (sky->get_skybox_type()) { case skybox::Type::Equirectangular: previous_cube = nullptr; if (previous_equirectangular == nullptr) { previous_equirectangular = skybox_equirectangular.get_next([this] { auto* const n = new node::SkyboxEquirectangular("pbr-sky-equ", e, GX_DEFAULT_IGNORED_END_CALLER); n->set_render_target(e->get_main_render_target().get()); return n; }); camera_nodes.skyboxes[sky->get_layer()].push_back(previous_equirectangular); } previous_equirectangular->update(); previous_equirectangular->set_camera(cam); previous_equirectangular->add_sky(reinterpret_cast<const skybox::Equirectangular*>(sky)); break; case skybox::Type::Cube: previous_equirectangular = nullptr; if (previous_cube == nullptr) { previous_cube = skybox_cube.get_next([this] { auto* const n = new node::SkyboxCube("pbr-sky-cube", e, GX_DEFAULT_IGNORED_END_CALLER); n->set_render_target(e->get_main_render_target().get()); return n; }); camera_nodes.skyboxes[sky->get_layer()].push_back(previous_cube); } previous_cube->update(); previous_cube->set_camera(cam); previous_cube->add_sky(reinterpret_cast<const skybox::Cube*>(sky)); break; default: GX_UNEXPECTED } } } void gearoenix::render::graph::tree::Pbr::update_runtime_reflection(const scene::Scene* const scn) noexcept { const auto& runtime_reflections = scn->get_runtime_reflections(); for (const auto& id_rtr : runtime_reflections) { auto* const rtr = id_rtr.second.get(); if (!rtr->get_enabled()) continue; switch (rtr->get_state()) { case reflection::Runtime::State::EnvironmentCubeRender: { if (rtr->get_state_environment_face() == 0) { runtime_reflections_data.emplace(rtr, RuntimeReflectionData(rtr->get_radiance_convoluters()[0].size())); } auto& rtr_nodes = runtime_reflections_data.find(rtr)->second; const auto& cam = rtr->get_cameras()[rtr->get_state_environment_face()]; auto& rtr_face_nodes = rtr_nodes.faces[rtr->get_state_environment_face()]; rtr_face_nodes.cam = cam.get(); update_camera(scn, rtr_face_nodes.cam, rtr_face_nodes.camera_data); break; } case reflection::Runtime::State::EnvironmentCubeMipMap: { auto& rtr_nodes = runtime_reflections_data.find(rtr)->second; rtr_nodes.environment_mipmap_generator = rtr->get_environment_mipmap_generator().get(); rtr_nodes.environment_mipmap_generator->update(); rtr_nodes.irradiance_mipmap_generator = rtr->get_irradiance_mipmap_generator().get(); rtr_nodes.irradiance_mipmap_generator->update(); break; } case reflection::Runtime::State::IrradianceFace: { const auto fi = rtr->get_state_irradiance_face(); auto& irradiance = runtime_reflections_data.find(rtr)->second.faces[fi].irradiance; irradiance = rtr->get_irradiance_convoluters()[fi].get(); irradiance->update(); break; } case reflection::Runtime::State::IrradianceMipMap: { auto& rtr_nodes = runtime_reflections_data.find(rtr)->second; rtr_nodes.irradiance_mipmap_generator = rtr->get_irradiance_mipmap_generator().get(); rtr_nodes.irradiance_mipmap_generator->update(); break; } case reflection::Runtime::State::RadianceFaceLevel: { auto& rtr_nodes = runtime_reflections_data.find(rtr)->second; const auto& radiances = rtr->get_radiance_convoluters(); const auto fi = rtr->get_state_radiance_face(); auto& rtr_face_nodes = rtr_nodes.faces[fi]; const auto& face_radiances = radiances[fi]; const auto li = rtr->get_state_radiance_level(); auto* const radiance = face_radiances[li].get(); rtr_face_nodes.radiances[li] = radiance; radiance->update(); break; } default: return; } } } void gearoenix::render::graph::tree::Pbr::update_opaque( const std::vector<std::tuple<double, material::Type, model::Model*, model::Mesh*>>& seen_meshes, const scene::Scene* const scn, const camera::Camera* const cam, CameraData& camera_nodes) noexcept { node::ForwardPbr* fwd = camera_nodes.opaques.forward_pbr; if (fwd == nullptr) { fwd = forward_pbr.get_next([this] { return new node::ForwardPbr("pbr-fwd-pbr", e, GX_DEFAULT_IGNORED_END_CALLER); }); fwd->update(); fwd->set_scene(scn); fwd->set_camera(cam); const auto& cs = cam->get_cascades(); for (auto& cascade : cs) { fwd->add_cascade(&cascade); } camera_nodes.opaques.forward_pbr = fwd; } node::Unlit* unl = camera_nodes.opaques.unlit; if (unl == nullptr) { unl = unlit.get_next([this] { return new node::Unlit("pbr-tree-unlit", e, GX_DEFAULT_IGNORED_END_CALLER); }); unl->update(); unl->set_camera(cam); camera_nodes.opaques.unlit = unl; } for (const auto& [dis, material_id, model_ptr, mesh_ptr] : seen_meshes) { switch (material_id) { case material::Type::Pbr: { fwd->add_mesh(std::make_pair(model_ptr, mesh_ptr)); break; } case material::Type::Unlit: { unl->add_mesh(std::make_pair(model_ptr, mesh_ptr)); break; } default: GX_UNEXPECTED } } } void gearoenix::render::graph::tree::Pbr::update_transparent( const std::vector<std::tuple<double, material::Type, model::Model*, model::Mesh*>>& seen_meshes, const scene::Scene* scn, const camera::Camera* cam, CameraData& camera_nodes) noexcept { const auto& cs = cam->get_cascades(); node::ForwardPbr* fwd = nullptr; node::Unlit* unl = nullptr; for (const auto& [dis, mat_type, mdl, msh] : seen_meshes) { switch (mat_type) { case material::Type::Pbr: { unl = nullptr; if (fwd == nullptr) { fwd = forward_pbr.get_next([this] { auto* const n = new node::ForwardPbr( "pbr-tree-pbr", e, core::sync::EndCaller<core::sync::EndCallerIgnore>([] {})); n->set_render_target(e->get_main_render_target().get()); return n; }); camera_nodes.transparencies.push_back(fwd); fwd->update(); fwd->set_scene(scn); fwd->set_camera(cam); for (auto& c : cs) { fwd->add_cascade(&c); } } fwd->add_mesh({ mdl, msh }); break; } case material::Type::Unlit: { fwd = nullptr; if (unl == nullptr) { unl = unlit.get_next([this] { auto* const n = new node::Unlit( "pbr-tree-unlit", e, core::sync::EndCaller<core::sync::EndCallerIgnore>([] {})); n->set_render_target(e->get_main_render_target().get()); return n; }); camera_nodes.transparencies.push_back(unl); unl->update(); unl->set_camera(cam); } unl->add_mesh({ mdl, msh }); break; } default: GX_UNEXPECTED } (void)dis; } } void gearoenix::render::graph::tree::Pbr::record_runtime_reflection( const scene::Scene* const scn, unsigned int& task_number, const unsigned int kernel_index, const unsigned int kernels_count) noexcept { const auto& runtime_reflections = scn->get_runtime_reflections(); for (const auto& id_rtr : runtime_reflections) { auto* const rtr = id_rtr.second.get(); if (!rtr->get_enabled()) continue; auto id_rtr_data = runtime_reflections_data.find(rtr); if (runtime_reflections_data.end() == id_rtr_data) continue; auto& runtime_reflection = id_rtr_data->second; switch (rtr->get_state()) { case reflection::Runtime::State::EnvironmentCubeRender: { const auto& face = runtime_reflection.faces[rtr->get_state_environment_face()]; for (const auto& skies : face.camera_data.skyboxes) { for (auto* const sky : skies.second) { GX_DO_TASK(sky->record_continuously(kernel_index)) } } const auto& opaques = face.camera_data.opaques; if (opaques.forward_pbr != nullptr) opaques.forward_pbr->record(kernel_index); if (opaques.unlit != nullptr) opaques.unlit->record(kernel_index); for (auto* const node : face.camera_data.transparencies) { GX_DO_TASK(node->record_continuously(kernel_index)) } break; } case reflection::Runtime::State::EnvironmentCubeMipMap: { GX_DO_TASK(runtime_reflection.environment_mipmap_generator->record_continuously(kernel_index)) break; } case reflection::Runtime::State::IrradianceFace: { GX_DO_TASK(runtime_reflection.faces[rtr->get_state_irradiance_face()].irradiance->record_continuously(kernel_index)) break; } case reflection::Runtime::State::IrradianceMipMap: { GX_DO_TASK(runtime_reflection.irradiance_mipmap_generator->record_continuously(kernel_index)) break; } case reflection::Runtime::State::RadianceFaceLevel: { GX_DO_TASK(runtime_reflection.faces[rtr->get_state_radiance_face()].radiances[rtr->get_state_radiance_level()]->record_continuously(kernel_index)) break; } default: return; } } } void gearoenix::render::graph::tree::Pbr::submit_camera_data(const CameraData& camera_data) const noexcept { for (const auto& skies : camera_data.skyboxes) for (auto* const sky : skies.second) sky->submit(); const auto& opaques = camera_data.opaques; if (opaques.forward_pbr != nullptr) opaques.forward_pbr->submit(); if (opaques.unlit != nullptr) opaques.unlit->submit(); for (auto* const node : camera_data.transparencies) node->submit(); } void gearoenix::render::graph::tree::Pbr::submit_runtime_reflections(const scene::Scene* const scn) noexcept { const auto& runtime_reflections = scn->get_runtime_reflections(); for (const auto& id_rtr : runtime_reflections) { auto* const rtr = id_rtr.second.get(); if (!rtr->get_enabled()) continue; auto id_rtr_data = runtime_reflections_data.find(rtr); if (runtime_reflections_data.end() != id_rtr_data) { auto& runtime_reflection = id_rtr_data->second; switch (rtr->get_state()) { case reflection::Runtime::State::EnvironmentCubeRender: submit_camera_data(runtime_reflection.faces[rtr->get_state_environment_face()].camera_data); break; case reflection::Runtime::State::EnvironmentCubeMipMap: runtime_reflection.environment_mipmap_generator->submit(); break; case reflection::Runtime::State::IrradianceFace: runtime_reflection.faces[rtr->get_state_irradiance_face()].irradiance->submit(); break; case reflection::Runtime::State::IrradianceMipMap: runtime_reflection.irradiance_mipmap_generator->submit(); break; case reflection::Runtime::State::RadianceFaceLevel: { auto* const radiance_node = runtime_reflection.faces[rtr->get_state_radiance_face()].radiances[rtr->get_state_radiance_level()]; if (nullptr != radiance_node) radiance_node->submit(); break; } default: break; } } rtr->update_state(); } } gearoenix::render::graph::tree::Pbr::Pbr(engine::Engine* const e, const core::sync::EndCaller<core::sync::EndCallerIgnore>&) noexcept : Tree(e) , in_weak_hardware(engine::Type::OpenGLES2 == e->get_engine_type()) { } gearoenix::render::graph::tree::Pbr::~Pbr() noexcept { GXLOGD("Pbr render tree deleted.") } void gearoenix::render::graph::tree::Pbr::update() noexcept { forward_pbr.refresh(); skybox_cube.refresh(); skybox_equirectangular.refresh(); unlit.refresh(); nodes.clear(); cascades.clear(); const auto& priorities_scenes = e->get_physics_engine()->get_sorted_scenes(); for (const auto& priority_scenes : priorities_scenes) { const double scene_priority = priority_scenes.first; auto& scene_priority_nodes = nodes[scene_priority]; const scene::Scene* const scn = priority_scenes.second.get(); auto& scene_nodes = scene_priority_nodes[scn]; update_runtime_reflection(scn); const auto& cameras = scn->get_cameras(); for (const auto& id_camera : cameras) { auto* const cam = id_camera.second.get(); const double camera_priority = cam->get_layer(); auto& camera_priority_nodes = scene_nodes.cameras[camera_priority]; CameraData& camera_nodes = camera_priority_nodes[cam]; update_camera(scn, cam, camera_nodes); } } } void gearoenix::render::graph::tree::Pbr::record(const unsigned int kernel_index) noexcept { GX_START_TASKS for (auto* const cas : cascades) { cas->record(kernel_index); } for (const auto& priority_scenes : nodes) { for ([[maybe_unused]] const auto& [scn, scene_data] : priority_scenes.second) { record_runtime_reflection(scn, task_number, kernel_index, kernels_count); for (const auto& priority_cameras : scene_data.cameras) { for (const auto& cam_camera_nodes : priority_cameras.second) { const CameraData& camera_nodes = cam_camera_nodes.second; for (const auto& skies : camera_nodes.skyboxes) for (auto* const sky : skies.second) GX_DO_TASK(sky->record_continuously(kernel_index)) const auto& opaques = camera_nodes.opaques; if (opaques.forward_pbr != nullptr) opaques.forward_pbr->record(kernel_index); if (opaques.unlit != nullptr) opaques.unlit->record(kernel_index); for (auto* const node : camera_nodes.transparencies) GX_DO_TASK(node->record_continuously(kernel_index)) } } } } } void gearoenix::render::graph::tree::Pbr::submit() noexcept { for (auto* cas : cascades) { cas->submit(); } for (auto& priority_scenes : nodes) { for (const auto& [scn, scene_data] : priority_scenes.second) { submit_runtime_reflections(scn); for ([[maybe_unused]] const auto& [priority, cameras] : scene_data.cameras) { for ([[maybe_unused]] const auto& [cam, camera_data] : cameras) { submit_camera_data(camera_data); } } } } }
41.943946
158
0.600043
Hossein-Noroozpour
b5dcb140de4475a08dd5ba6bbdd81b4c578931b4
4,639
cc
C++
ui/ozone/platform/dri/crtc_controller.cc
hefen1/chromium
52f0b6830e000ca7c5e9aa19488af85be792cc88
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
ui/ozone/platform/dri/crtc_controller.cc
hefen1/chromium
52f0b6830e000ca7c5e9aa19488af85be792cc88
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
ui/ozone/platform/dri/crtc_controller.cc
hefen1/chromium
52f0b6830e000ca7c5e9aa19488af85be792cc88
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2020-04-04T13:34:56.000Z
2020-11-04T07:17:52.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 "ui/ozone/platform/dri/crtc_controller.h" #include "base/logging.h" #include "base/time/time.h" #include "ui/ozone/platform/dri/dri_wrapper.h" #include "ui/ozone/platform/dri/page_flip_observer.h" #include "ui/ozone/platform/dri/scanout_buffer.h" namespace ui { CrtcController::CrtcController(const scoped_refptr<DriWrapper>& drm, uint32_t crtc, uint32_t connector) : drm_(drm), crtc_(crtc), connector_(connector), saved_crtc_(drm->GetCrtc(crtc)), is_disabled_(true), page_flip_pending_(false), time_of_last_flip_(0) { } CrtcController::~CrtcController() { if (!is_disabled_) { drm_->SetCrtc(saved_crtc_.get(), std::vector<uint32_t>(1, connector_)); UnsetCursor(); } } bool CrtcController::Modeset(const OverlayPlane& plane, drmModeModeInfo mode) { if (!drm_->SetCrtc(crtc_, plane.buffer->GetFramebufferId(), std::vector<uint32_t>(1, connector_), &mode)) { LOG(ERROR) << "Failed to modeset: error='" << strerror(errno) << "' crtc=" << crtc_ << " connector=" << connector_ << " framebuffer_id=" << plane.buffer->GetFramebufferId() << " mode=" << mode.hdisplay << "x" << mode.vdisplay << "@" << mode.vrefresh; return false; } mode_ = mode; pending_planes_.clear(); is_disabled_ = false; // drmModeSetCrtc has an immediate effect, so we can assume that the current // planes have been updated. However if a page flip is still pending, set the // pending planes to the same values so that the callback keeps the correct // state. current_planes_ = std::vector<OverlayPlane>(1, plane); if (page_flip_pending_) pending_planes_ = current_planes_; return true; } bool CrtcController::Disable() { if (is_disabled_) return true; is_disabled_ = true; return drm_->DisableCrtc(crtc_); } bool CrtcController::SchedulePageFlip(HardwareDisplayPlaneList* plane_list, const OverlayPlaneList& overlays) { DCHECK(!page_flip_pending_); DCHECK(!is_disabled_); const OverlayPlane* primary = OverlayPlane::GetPrimaryPlane(overlays); if (!primary) { LOG(ERROR) << "No primary plane to display on crtc " << crtc_; FOR_EACH_OBSERVER(PageFlipObserver, observers_, OnPageFlipEvent()); return true; } DCHECK(primary->buffer.get()); if (primary->buffer->GetSize() != gfx::Size(mode_.hdisplay, mode_.vdisplay)) { LOG(WARNING) << "Trying to pageflip a buffer with the wrong size. Expected " << mode_.hdisplay << "x" << mode_.vdisplay << " got " << primary->buffer->GetSize().ToString() << " for" << " crtc=" << crtc_ << " connector=" << connector_; FOR_EACH_OBSERVER(PageFlipObserver, observers_, OnPageFlipEvent()); return true; } if (!drm_->plane_manager()->AssignOverlayPlanes(plane_list, overlays, crtc_, this)) { LOG(ERROR) << "Failed to assign overlay planes for crtc " << crtc_; return false; } page_flip_pending_ = true; pending_planes_ = overlays; return true; } void CrtcController::PageFlipFailed() { pending_planes_.clear(); page_flip_pending_ = false; } void CrtcController::OnPageFlipEvent(unsigned int frame, unsigned int seconds, unsigned int useconds) { page_flip_pending_ = false; time_of_last_flip_ = static_cast<uint64_t>(seconds) * base::Time::kMicrosecondsPerSecond + useconds; current_planes_.clear(); current_planes_.swap(pending_planes_); FOR_EACH_OBSERVER(PageFlipObserver, observers_, OnPageFlipEvent()); } bool CrtcController::SetCursor(const scoped_refptr<ScanoutBuffer>& buffer) { DCHECK(!is_disabled_); cursor_buffer_ = buffer; return drm_->SetCursor(crtc_, buffer->GetHandle(), buffer->GetSize()); } bool CrtcController::UnsetCursor() { bool state = drm_->SetCursor(crtc_, 0, gfx::Size()); cursor_buffer_ = NULL; return state; } bool CrtcController::MoveCursor(const gfx::Point& location) { DCHECK(!is_disabled_); return drm_->MoveCursor(crtc_, location); } void CrtcController::AddObserver(PageFlipObserver* observer) { observers_.AddObserver(observer); } void CrtcController::RemoveObserver(PageFlipObserver* observer) { observers_.RemoveObserver(observer); } } // namespace ui
31.773973
80
0.661781
hefen1
b5df3f87c0836fa18ab4d58b828505a316c0c16c
2,670
cpp
C++
vcc/src/fence.cpp
sjfricke/vulkan-cpp-library
82314d765013ce96e23186594259eebaf3127072
[ "Apache-2.0" ]
276
2016-04-04T20:47:47.000Z
2022-02-01T21:48:42.000Z
vcc/src/fence.cpp
sjfricke/vulkan-cpp-library
82314d765013ce96e23186594259eebaf3127072
[ "Apache-2.0" ]
2
2017-03-23T20:33:23.000Z
2017-05-17T21:03:16.000Z
vcc/src/fence.cpp
sjfricke/vulkan-cpp-library
82314d765013ce96e23186594259eebaf3127072
[ "Apache-2.0" ]
42
2016-04-07T21:00:53.000Z
2021-09-05T09:17:03.000Z
/* * Copyright 2016 Google Inc. 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 <vcc/fence.h> namespace vcc { namespace fence { fence_type create(const type::supplier<const device::device_type> &device, VkFenceCreateFlags flags) { VkFenceCreateInfo create = {VK_STRUCTURE_TYPE_FENCE_CREATE_INFO, NULL}; create.flags = flags; VkFence fence; VKCHECK(vkCreateFence(internal::get_instance(*device), &create, NULL, &fence)); return fence_type(fence, device); } VkResult wait(const device::device_type &device, const std::vector<std::reference_wrapper<const fence_type>> &fences, bool wait_all, uint64_t timeout) { std::vector<VkFence> converted_fences; converted_fences.reserve(fences.size()); for (const fence_type &fence : fences) { converted_fences.push_back(internal::get_instance(fence)); } VkResult result = vkWaitForFences(internal::get_instance(device), (uint32_t)fences.size(), converted_fences.data(), !!wait_all, timeout); if (result != VK_TIMEOUT && result != VK_SUCCESS) { VKCHECK(result); } return result; } VkResult wait(const device::device_type &device, const std::vector<std::reference_wrapper<const fence_type>> &fences, bool wait_all, std::chrono::nanoseconds timeout) { return wait(device, fences, wait_all, timeout.count()); } VkResult wait(const device::device_type &device, const std::vector<std::reference_wrapper<const fence_type>> &fences, bool wait_all) { return wait(device, fences, wait_all, UINT64_MAX); } void reset(const device::device_type &device, const std::vector<std::reference_wrapper<const fence_type>> &fences) { std::vector<VkFence> converted_fences; converted_fences.reserve(fences.size()); for (const fence_type &fence : fences) { converted_fences.push_back(internal::get_instance(fence)); } std::vector<std::unique_lock<std::mutex>> locks; locks.reserve(fences.size()); for (const fence_type &fence : fences) { locks.emplace_back(internal::get_mutex(fence), std::defer_lock); } util::lock(locks); VKCHECK(vkResetFences(internal::get_instance(device), uint32_t(fences.size()), converted_fences.data())); } } // namespace fence } // namespace vcc
34.675325
87
0.753933
sjfricke
b5e06ebbf8a12bc929daf4a1551f54864f3ecc8a
1,230
cpp
C++
Longest Subarray of 1's After Deleting One Element.cpp
PoojaRani24/Leetcode_Monthly_Challenge
9ad56cb332b33bf8ce1c4ef5e64f92a1599e598b
[ "MIT" ]
null
null
null
Longest Subarray of 1's After Deleting One Element.cpp
PoojaRani24/Leetcode_Monthly_Challenge
9ad56cb332b33bf8ce1c4ef5e64f92a1599e598b
[ "MIT" ]
null
null
null
Longest Subarray of 1's After Deleting One Element.cpp
PoojaRani24/Leetcode_Monthly_Challenge
9ad56cb332b33bf8ce1c4ef5e64f92a1599e598b
[ "MIT" ]
null
null
null
class Solution { public: int longestSubarray(vector<int>& nums) { vector<pair<int,int>>v; int count=0; for(int i=0;i<nums.size();){ if(nums[i]==0) i++; else{ int start=i; int c=0; while(i<nums.size() && nums[i]==1) { i++; c++; } v.push_back({start,i-1}); if(c>count) count=c; } } for(int i=0;i<v.size();i++) cout<<v[i].first<<" "<<v[i].second<<endl; if(v.size()==0) return 0; else if(v.size()==1){ if(v[0].second-v[0].first+1==nums.size()) return nums.size()-1; else return v[0].second-v[0].first+1; } else{ for(int i=0;i<v.size()-1;i++){ if(v[i+1].first-v[i].second>2)continue; else { if(v[i+1].second-v[i].first>count) count=v[i+1].second-v[i].first; } } return count; } //return 0; } };
26.73913
55
0.339837
PoojaRani24
b5e3847310e58f59993c42ded3f4625891223f52
1,062
cpp
C++
CsPlugin/Source/CsEditor/Public/DetailCustomizations/EnumStruct/Team/ECsTeamCustomization.cpp
closedsum/core
c3cae44a177b9684585043a275130f9c7b67fef0
[ "Unlicense" ]
2
2019-03-17T10:43:53.000Z
2021-04-20T21:24:19.000Z
CsPlugin/Source/CsEditor/Public/DetailCustomizations/EnumStruct/Team/ECsTeamCustomization.cpp
closedsum/core
c3cae44a177b9684585043a275130f9c7b67fef0
[ "Unlicense" ]
null
null
null
CsPlugin/Source/CsEditor/Public/DetailCustomizations/EnumStruct/Team/ECsTeamCustomization.cpp
closedsum/core
c3cae44a177b9684585043a275130f9c7b67fef0
[ "Unlicense" ]
null
null
null
// Copyright 2017-2021 Closed Sum Games, LLC. All Rights Reserved. #include "DetailCustomizations/EnumStruct/Team/ECsTeamCustomization.h" // Types #include "Team/CsTypes_Team.h" #define LOCTEXT_NAMESPACE "ECsTeamCustomization" #define EnumMapType EMCsTeam #define EnumType FECsTeam FECsTeamCustomization::FECsTeamCustomization() : Super() { Init<EnumMapType, EnumType>(); } TSharedRef<IPropertyTypeCustomization> FECsTeamCustomization::MakeInstance() { return MakeShareable(new FECsTeamCustomization); } void FECsTeamCustomization::SetPropertyHandles(TSharedRef<IPropertyHandle> StructPropertyHandle) { SetPropertyHandles_Internal<EnumType>(StructPropertyHandle); } void FECsTeamCustomization::SetEnumWithDisplayName(const FString& DisplayName) { SetEnumWithDisplayName_Internal<EnumMapType, EnumType>(DisplayName); } void FECsTeamCustomization::GetDisplayNamePropertyValue(FString& OutDisplayName) const { GetDisplayNamePropertyValue_Internal<EnumMapType, EnumType>(OutDisplayName); } #undef EnumMapType #undef EnumType #undef LOCTEXT_NAMESPACE
25.285714
96
0.834275
closedsum
b5e4860f8b8f0f766cdf780d3f4708b774d987ed
3,264
hpp
C++
include/Pomdog/Graphics/DepthStencilDescription.hpp
bis83/pomdog
133a9262958d539ae6d93664e6cb2207b5b6c7ff
[ "MIT" ]
null
null
null
include/Pomdog/Graphics/DepthStencilDescription.hpp
bis83/pomdog
133a9262958d539ae6d93664e6cb2207b5b6c7ff
[ "MIT" ]
null
null
null
include/Pomdog/Graphics/DepthStencilDescription.hpp
bis83/pomdog
133a9262958d539ae6d93664e6cb2207b5b6c7ff
[ "MIT" ]
null
null
null
// Copyright (c) 2013-2015 mogemimi. // Distributed under the MIT license. See LICENSE.md file for details. #ifndef POMDOG_DEPTHSTENCILDESCRIPTION_E14C5D77_HPP #define POMDOG_DEPTHSTENCILDESCRIPTION_E14C5D77_HPP #include "ComparisonFunction.hpp" #include "DepthStencilOperation.hpp" #include "Pomdog/Basic/Export.hpp" #include <cstdint> #include <limits> namespace Pomdog { struct POMDOG_EXPORT DepthStencilDescription { DepthStencilOperation ClockwiseFace; DepthStencilOperation CounterClockwiseFace; std::int32_t ReferenceStencil; std::uint32_t StencilMask; std::uint32_t StencilWriteMask; ComparisonFunction DepthBufferFunction; bool DepthBufferEnable; bool DepthBufferWriteEnable; bool StencilEnable; static DepthStencilDescription CreateDefault() { return CreateReadWriteDepth(); } static DepthStencilDescription CreateReadWriteDepth() { DepthStencilDescription desc; desc.DepthBufferEnable = true; desc.DepthBufferWriteEnable = true; desc.StencilEnable = false; desc.DepthBufferFunction = ComparisonFunction::LessEqual; desc.ReferenceStencil = 0; desc.StencilMask = std::numeric_limits<std::uint32_t>::max(); desc.StencilWriteMask = std::numeric_limits<std::uint32_t>::max(); DepthStencilOperation defaultOperation = { StencilOperation::Keep, StencilOperation::Keep, StencilOperation::Keep, ComparisonFunction::Always }; desc.ClockwiseFace = defaultOperation; desc.CounterClockwiseFace = defaultOperation; return desc; } static DepthStencilDescription CreateReadOnlyDepth() { DepthStencilDescription desc; desc.DepthBufferEnable = true; desc.DepthBufferWriteEnable = false; desc.StencilEnable = false; desc.DepthBufferFunction = ComparisonFunction::LessEqual; desc.ReferenceStencil = 0; desc.StencilMask = std::numeric_limits<std::uint32_t>::max(); desc.StencilWriteMask = std::numeric_limits<std::uint32_t>::max(); DepthStencilOperation defaultOperation = { StencilOperation::Keep, StencilOperation::Keep, StencilOperation::Keep, ComparisonFunction::Always }; desc.ClockwiseFace = defaultOperation; desc.CounterClockwiseFace = defaultOperation; return desc; } static DepthStencilDescription CreateNone() { DepthStencilDescription desc; desc.DepthBufferEnable = false; desc.DepthBufferWriteEnable = false; desc.StencilEnable = false; desc.DepthBufferFunction = ComparisonFunction::LessEqual; desc.ReferenceStencil = 0; desc.StencilMask = std::numeric_limits<std::uint32_t>::max(); desc.StencilWriteMask = std::numeric_limits<std::uint32_t>::max(); DepthStencilOperation defaultOperation = { StencilOperation::Keep, StencilOperation::Keep, StencilOperation::Keep, ComparisonFunction::Always }; desc.ClockwiseFace = defaultOperation; desc.CounterClockwiseFace = defaultOperation; return desc; } }; } // namespace Pomdog #endif // POMDOG_DEPTHSTENCILDESCRIPTION_E14C5D77_HPP
35.478261
74
0.704044
bis83
b5ece2947cc73f1bb321c8c8e02d09bc2888ca5f
1,916
cpp
C++
src/SolarChargeSystem/lib/SerialReceiver/SerialReceiver.cpp
jack96013/Solar-Charge-System
e64c5fece5bff9b7a7f1c7d9b92235ed9e391812
[ "MIT" ]
null
null
null
src/SolarChargeSystem/lib/SerialReceiver/SerialReceiver.cpp
jack96013/Solar-Charge-System
e64c5fece5bff9b7a7f1c7d9b92235ed9e391812
[ "MIT" ]
null
null
null
src/SolarChargeSystem/lib/SerialReceiver/SerialReceiver.cpp
jack96013/Solar-Charge-System
e64c5fece5bff9b7a7f1c7d9b92235ed9e391812
[ "MIT" ]
null
null
null
#include "SerialReceiver.h" SerialReceiver::SerialReceiver() { } void SerialReceiver::begin(Stream& serial,uint16_t bufferLength) { this->serial = &serial; receiveBufferLength = bufferLength; receiveBuffer.reserve(bufferLength + 1); //serial.println("Ready !"); } void SerialReceiver::run() { serialCheck(); } void SerialReceiver::serialCheck() { bool receiveFinishFlag = false; while (serial->available()) { // 一個字節一個字節地讀,下一句是讀到的放入字符串數組中組成一個完成的數據包 char incomingByte = serial->read(); // 緩衝區已滿 if (receiveBuffer.length() >= receiveBufferLength) { receiveBuffer = ""; } receiveBuffer += (char)incomingByte; // 將字元一個個串接 if (incomingByte == SM_ENDMARK) { receiveFinishFlag = true; break; } } if (receiveFinishFlag) { if (receiveBuffer.length() > 0) { // remove /r /n removeLineEnding(receiveBuffer); #ifdef SM_DEBUG serial->println(receiveBuffer); #endif onReceiveCallbackInvoke(); } receiveBuffer = ""; } } // Remove Line Ending void SerialReceiver::removeLineEnding(String &str) { // Remove \n \r if (str.endsWith("\n")) str.remove(str.length() - 1); ; if (str.endsWith("\r")) str.remove(str.length() - 1); } void SerialReceiver::onReceiveCallbackInvoke() { if (onReceiveCallback != nullptr) onReceiveCallback(onReceiveCallbackArg,receiveBuffer); } void SerialReceiver::setOnReceiveCallback(OnReceiveCallback callback,void* arg) { this->onReceiveCallback = callback; this->onReceiveCallbackArg = arg; } void SerialReceiver::clearBuffer() { receiveBuffer = ""; serial->flush(); } String* SerialReceiver::getBuffer() { return &receiveBuffer; }
20.602151
79
0.600731
jack96013
b5eec152c2d814fe6deada75cf753da496deb74c
362
cpp
C++
Source/MarchingCubes/MarchingCubesGameModeBase.cpp
Styvak/Marching-Cubes-UE4
2ef8266f0a63294fbd1789724281b4d87e9b8daa
[ "MIT" ]
2
2020-04-19T12:07:33.000Z
2020-05-15T21:17:48.000Z
Source/MarchingCubes/MarchingCubesGameModeBase.cpp
Styvak/Marching-Cubes-UE4
2ef8266f0a63294fbd1789724281b4d87e9b8daa
[ "MIT" ]
null
null
null
Source/MarchingCubes/MarchingCubesGameModeBase.cpp
Styvak/Marching-Cubes-UE4
2ef8266f0a63294fbd1789724281b4d87e9b8daa
[ "MIT" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #include "MarchingCubesGameModeBase.h" #include "BlockManager.h" void AMarchingCubesGameModeBase::InitGame(const FString& MapName, const FString& Options, FString& ErrorMessage) { Super::InitGame(MapName, Options, ErrorMessage); BlockManager::GetInstance()->RegisterBlocks(); }
30.166667
112
0.792818
Styvak
b5f031cd0c6b4408ae9cc3709dfb9e10e6935c84
2,228
hpp
C++
combinator/aggregate.hpp
kindone/proptest
174981600571b75bbd9ed69f56453c9994d2878c
[ "MIT" ]
null
null
null
combinator/aggregate.hpp
kindone/proptest
174981600571b75bbd9ed69f56453c9994d2878c
[ "MIT" ]
null
null
null
combinator/aggregate.hpp
kindone/proptest
174981600571b75bbd9ed69f56453c9994d2878c
[ "MIT" ]
null
null
null
#pragma once #include "../Shrinkable.hpp" #include "../Random.hpp" #include "../GenBase.hpp" #include "../util/function_traits.hpp" #include "../util/std.hpp" #include "../generator/integral.hpp" /** * @file aggregate.hpp * @brief Generator combinator for aggregating sequencially generated values into a value with a generator generator */ namespace proptest { namespace util { template <typename T> Generator<T> aggregateImpl(GenFunction<T> gen1, function<GenFunction<T>(T&)> gen2gen, size_t minSize, size_t maxSize) { auto gen1Ptr = util::make_shared<decltype(gen1)>(gen1); auto gen2genPtr = util::make_shared<function<GenFunction<T>(const T&)>>( [gen2gen](const T& t) { return gen2gen(const_cast<T&>(t)); }); return interval<uint64_t>(minSize, maxSize).flatMap<T>([gen1Ptr, gen2genPtr](uint64_t& size) { return Generator<T>([gen1Ptr, gen2genPtr, size](Random& rand) { Shrinkable<T> shr = (*gen1Ptr)(rand); for (size_t i = 0; i < size; i++) shr = (*gen2genPtr)(shr.get())(rand); return shr; }); }); } } // namespace util /** * @ingroup Combinators * @brief Generator combinator for aggregating a value of type T from a generator generator * @tparam GEN1 Generator type of (Random&) -> Shrinkable<T> * @tparam GEN2GEN (T&) -> ((Random&) -> Shrinkable<T>) (Generator for T) * @param gen1 base generator for type T * @param gen2gen function that returns a generator for type T based on previously generated value of the same type * @param minSize minimum size of the aggregate steps * @param maxSize maximum size of the aggregate steps * @return last generated value of T throughout the aggregation */ template <typename GEN1, typename GEN2GEN> decltype(auto) aggregate(GEN1&& gen1, GEN2GEN&& gen2gen, size_t minSize, size_t maxSize) { using T = typename invoke_result_t<GEN1, Random&>::type; // get the T from shrinkable<T>(Random&) using RetType = invoke_result_t<GEN2GEN, T&>; // GEN2GEN's return type GenFunction<T> funcGen1 = gen1; function<RetType(T&)> funcGen2Gen = gen2gen; return util::aggregateImpl<T>(funcGen1, funcGen2Gen, minSize, maxSize); } } // namespace proptest
37.762712
117
0.686266
kindone
b5f3921e8c1e683e8363151dbf1fc343f6525cc2
502
cpp
C++
src/nimbro/motion/gait_engines/feed_gait/src/kinematics/feed_kinematics_base.cpp
ssr-yuki/humanoid_op_ros
e8be8c445ead8c0d470c7998fdc28446ca9eb47a
[ "BSD-3-Clause" ]
45
2015-11-04T01:29:12.000Z
2022-02-11T05:37:42.000Z
src/nimbro/motion/gait_engines/feed_gait/src/kinematics/feed_kinematics_base.cpp
ssr-yuki/humanoid_op_ros
e8be8c445ead8c0d470c7998fdc28446ca9eb47a
[ "BSD-3-Clause" ]
1
2016-08-10T04:00:32.000Z
2016-08-10T12:59:36.000Z
src/nimbro/motion/gait_engines/feed_gait/src/kinematics/feed_kinematics_base.cpp
ssr-yuki/humanoid_op_ros
e8be8c445ead8c0d470c7998fdc28446ca9eb47a
[ "BSD-3-Clause" ]
20
2016-03-05T14:28:45.000Z
2021-01-30T00:50:47.000Z
// Feedback gait kinematics base class // Author: Philipp Allgeuer <pallgeuer@ais.uni-bonn.de> // Includes #include <feed_gait/kinematics/feed_kinematics_base.h> // Namespaces using namespace feed_gait; // // FeedKinematicsBase class // // Gait halt pose function: PoseCommand void FeedKinematicsBase::getHaltPose(PoseCommand& haltPose) const { // Calculate the required halt pose getHaltPose(haltPose.pos); getHaltPoseEffort(haltPose.effort); getHaltPoseSuppCoeff(haltPose.suppCoeff); } // EOF
22.818182
65
0.782869
ssr-yuki
b5f41904025ba35fbe68d8a502804c774be8181a
191
hpp
C++
src/AudioLib/EffectType.hpp
CircuitMess/JayD-Library
f90bbb72224681a972cd2b535f80925a3319e631
[ "MIT" ]
2
2021-08-19T17:23:46.000Z
2021-10-10T17:11:04.000Z
src/AudioLib/EffectType.hpp
CircuitMess/JayD-Library
f90bbb72224681a972cd2b535f80925a3319e631
[ "MIT" ]
null
null
null
src/AudioLib/EffectType.hpp
CircuitMess/JayD-Library
f90bbb72224681a972cd2b535f80925a3319e631
[ "MIT" ]
1
2021-11-21T16:02:06.000Z
2021-11-21T16:02:06.000Z
#ifndef JAYD_LIBRARY_EFFECTTYPE_HPP #define JAYD_LIBRARY_EFFECTTYPE_HPP enum EffectType { NONE, SPEED, LOWPASS, HIGHPASS, REVERB, BITCRUSHER, COUNT }; #endif //JAYD_LIBRARY_EFFECTTYPE_HPP
21.222222
58
0.82199
CircuitMess
b5f4e469e002fba53bf7f9bdfcccb3e86bcabefa
2,552
cpp
C++
uva/uva1588/main.cpp
oklen/my-soluation
56d6c32f0a328332b090f9d633365b75605f4616
[ "MIT" ]
null
null
null
uva/uva1588/main.cpp
oklen/my-soluation
56d6c32f0a328332b090f9d633365b75605f4616
[ "MIT" ]
null
null
null
uva/uva1588/main.cpp
oklen/my-soluation
56d6c32f0a328332b090f9d633365b75605f4616
[ "MIT" ]
null
null
null
#include <iostream> #include <cstring> using namespace std; constexpr int intsize = sizeof(int); int fillstr(char *ar) { int count = 0; char cache = getchar(); if(cache == EOF) exit(0); while(cache!='\n') { ar[count++] = cache; cache = getchar(); } return count; } int fillstrb(char *ar) { int count = 0; char cache = getchar(); if(cache == EOF) exit(0); while(cache!='\n') { if(cache=='1') ar[count++] = '2'; else ar[count++] = '1'; cache = getchar(); } return count; } int mycmp(char *a,char *b,int le) { int i =0; while (i<le) { if(*(a+i) == '2' && *(b+i) == '2') return 1; i++; } return 0; } int main() { char at[100]; char ag[100]; char *aa = at; char *ab = ag; int count = 0,aal,abl; memset(aa,0,100*sizeof(char)); memset(ab,0,100*sizeof(char)); while(!cin.eof()) { abl = fillstr(ab); aal = fillstr(aa); if(abl < aal) { char* cache = ab; ab = aa; aa = cache; int c = abl; abl = aal; aal = c; } int shift = 0,comparesize,apos; int min = abl+aal; while(++shift < aal+abl) { if(shift<aal) { comparesize = shift; apos = aal - shift; } else if (shift >abl) { comparesize = aal - shift + abl; apos = 0; } else { comparesize = aal; apos = 0; } // cout << shift <<"Compare:" // <<strndup(aa+apos,comparesize) << ":" << strndup(ab+(shift>aal?shift-aal:0),comparesize) // << endl; if(mycmp(aa+apos,ab+(shift>aal?shift-aal:0),comparesize) == 0) { if(shift < aal && min > abl+aal-shift) { min = abl+aal-shift; // cout << "1 cae" << endl; } else if(shift > abl && min > shift) { min = shift; // cout << "2 cae" << endl; } else if(shift <= abl && shift>=aal) { min = abl; // cout << "min" << endl; } } } cout << min << endl; } }
22
107
0.375
oklen
b5f511168de95fe0d248f4b44369abfff29e0a25
18,603
cpp
C++
globfit/src/RelationGraph.cpp
frozar/RAPter
8f1f9a37e4ac12fa08a26d18f58d3b335f797200
[ "Apache-2.0" ]
27
2017-09-21T19:52:28.000Z
2022-03-09T13:47:02.000Z
globfit/src/RelationGraph.cpp
frozar/RAPter
8f1f9a37e4ac12fa08a26d18f58d3b335f797200
[ "Apache-2.0" ]
12
2017-07-26T15:00:32.000Z
2021-12-03T03:08:15.000Z
globfit/src/RelationGraph.cpp
frozar/RAPter
8f1f9a37e4ac12fa08a26d18f58d3b335f797200
[ "Apache-2.0" ]
11
2017-03-24T16:56:08.000Z
2020-11-21T13:18:33.000Z
#include <boost/graph/breadth_first_search.hpp> #include <boost/graph/biconnected_components.hpp> #include <boost/graph/connected_components.hpp> #include "Primitive.h" #include "GlobFit.h" #include "RelationGraph.h" class PathDetectedException { public: protected: private: }; class path_recorder:public default_bfs_visitor { public: path_recorder(std::vector<GraphVertex>& vecPredecessor, GraphVertex startVertex, GraphVertex endVertex) :_vecPredecessor(vecPredecessor), _startVertex(startVertex), _endVertex(endVertex) {} template < typename Vertex, typename Graph > void initialize_vertex(Vertex u, const Graph & g) const { _vecPredecessor[u] = u; } template < typename Edge, typename Graph > void tree_edge(Edge e, const Graph & g) const { GraphVertex v = target(e, g); if (v == _startVertex) { return; } _vecPredecessor[v] = source(e, g); if (v == _endVertex) { throw PathDetectedException(); } } protected: private: std::vector<GraphVertex>& _vecPredecessor; GraphVertex _startVertex; GraphVertex _endVertex; }; static void removeIsolatedEdges(Graph& g) { bool bEdgeRemoved; do { bEdgeRemoved = false; for (GraphVertex i = 0, iEnd = num_vertices(g); i < iEnd; ++ i) { if (out_degree(i, g) == 1) { std::pair<GraphOutEdgeItr, GraphOutEdgeItr> edgeItr = out_edges(i, g); GraphVertex v = target(*(edgeItr.first), g); if (out_degree(v, g) != 1) { clear_vertex(i, g); bEdgeRemoved = true; } } } } while (bEdgeRemoved); } static void detectArticulationPoints(std::vector<RelationEdge>& vecRelationEdge, Graph& g) { PRINT_MESSAGE("Start...") for (size_t i = 0, iEnd = vecRelationEdge.size(); i < iEnd; ++ i) { RelationEdge& relationEdge = vecRelationEdge[i]; GraphVertex u = relationEdge.getSource().getIdx(); GraphVertex v = relationEdge.getTarget().getIdx(); add_edge(u, v, EdgeProp(relationEdge.getType(), relationEdge.getScore()), g); } removeIsolatedEdges(g); std::vector<GraphVertex> vecArticulationPoint; articulation_points(g, std::back_inserter(vecArticulationPoint)); while (!vecArticulationPoint.empty()) { GraphVertex nWeakestPoint = 0; double nMinWeight = std::numeric_limits<double>::max(); for (GraphVertex i = 0; i < vecArticulationPoint.size(); ++ i) { double nWeight = 0; std::pair<GraphOutEdgeItr, GraphOutEdgeItr> edgeItr = out_edges(vecArticulationPoint[i], g); for (GraphOutEdgeItr it = edgeItr.first; it != edgeItr.second; it ++) { nWeight += g[*it].score; } if (nWeight < nMinWeight) { nMinWeight = nWeight; nWeakestPoint = vecArticulationPoint[i]; } } std::map<GraphVertex, EdgeProp> mapVertex2Edge; std::pair<GraphOutEdgeItr, GraphOutEdgeItr> edgeItr = out_edges(nWeakestPoint, g); for (GraphOutEdgeItr it = edgeItr.first; it != edgeItr.second; it ++) { mapVertex2Edge[target(*it, g)] = g[*it]; } clear_vertex(nWeakestPoint, g); std::vector<GraphVertex> component(num_vertices(g)); size_t nComponentNum = connected_components(g, &component[0]); std::vector<double> vecWeight(nComponentNum, 0.0); std::vector<int> vecCount(nComponentNum, 0); for (std::map<GraphVertex, EdgeProp>::iterator it = mapVertex2Edge.begin(); it != mapVertex2Edge.end(); it ++) { vecWeight[component[it->first]] += it->second.score; vecCount[component[it->first]] ++; } for (size_t i = 0; i < nComponentNum; ++ i) { if (vecCount[i] != 0) { vecWeight[i] /= vecCount[i]; } } size_t nStrongestComponent = std::distance(vecWeight.begin(), std::max_element(vecWeight.begin(), vecWeight.end())); for (std::map<GraphVertex, EdgeProp>::iterator it = mapVertex2Edge.begin(); it != mapVertex2Edge.end(); it ++) { GraphVertex v = it->first; if (component[v] == nStrongestComponent) { add_edge(nWeakestPoint, v, mapVertex2Edge[v], g); } } removeIsolatedEdges(g); vecArticulationPoint.clear(); articulation_points(g, std::back_inserter(vecArticulationPoint)); } PRINT_MESSAGE("End...") return; } static void filterEdgesToArticulationPoints(std::vector<RelationEdge>& vecRelationEdge, Graph& g) { std::vector<RelationEdge> vecRemainingEdge; for (size_t i = 0, iEnd = vecRelationEdge.size(); i < iEnd; ++ i) { RelationEdge& relationEdge = vecRelationEdge[i]; GraphVertex u = relationEdge.getSource().getIdx(); GraphVertex v = relationEdge.getTarget().getIdx(); if (edge(u, v, g).second) { vecRemainingEdge.push_back(relationEdge); } } vecRelationEdge = vecRemainingEdge; return; } void biconnectDecompose(std::vector<RelationEdge>& vecRelationEdge, Graph& g) { PRINT_MESSAGE("Start...") detectArticulationPoints(vecRelationEdge, g); filterEdgesToArticulationPoints(vecRelationEdge, g); return; } static void filterTransitConstraint(std::vector<RelationEdge>& vecRelationEdge, RelationEdge::RelationEdgeType rt, Graph& g) { std::vector<RelationEdge> vecRemainingEdge; for (size_t i = 0, iEnd = vecRelationEdge.size(); i < iEnd; ++ i) { RelationEdge& relationEdge = vecRelationEdge[i]; const GraphVertex &u = relationEdge.getSource().getIdx(); const GraphVertex &v = relationEdge.getTarget().getIdx(); if (relationEdge.getType() == rt) { if (g[u].getParent() == g[v].getParent()) { continue; } } vecRemainingEdge.push_back(relationEdge); } vecRelationEdge = vecRemainingEdge; std::sort(vecRelationEdge.begin(), vecRelationEdge.end()); return; } static void collectTransitConstraint(std::vector<RelationEdge>& vecRelationEdge, RelationEdge::RelationEdgeType rt, Graph& g) { for (GraphVertex i = 0, iEnd = num_vertices(g); i < iEnd; ++ i) { if (g[i].getParent() != i) { const RelationVertex& targetVertex = g[g[i].getParent()]; const RelationVertex& sourceVertex = g[i]; vecRelationEdge.push_back(RelationEdge(rt, sourceVertex, targetVertex)); } } return; } static void filterOrientationConstraint(std::vector<RelationEdge>& vecRelationEdge, Graph& g) { PRINT_MESSAGE(__LINE__) filterTransitConstraint(vecRelationEdge, RelationEdge::RET_PARALLEL, g); PRINT_MESSAGE(__LINE__) std::vector<RelationEdge> vecRemainingEdge; vecRemainingEdge.reserve(vecRelationEdge.size()); for (size_t i = 0, iEnd = vecRelationEdge.size(); i < iEnd; ++ i) { const RelationEdge& relationEdge = vecRelationEdge[i]; const GraphVertex &u = relationEdge.getSource().getIdx(); const GraphVertex &v = relationEdge.getTarget().getIdx(); if (! ( relationEdge.getType() == RelationEdge::RET_ORTHOGONAL) || ! ( edge(g[u].getParent(), g[v].getParent(), g).second ) ) vecRemainingEdge.push_back(relationEdge); } PRINT_MESSAGE(__LINE__) vecRelationEdge = vecRemainingEdge; PRINT_MESSAGE(__LINE__) std::sort(vecRelationEdge.begin(), vecRelationEdge.end()); PRINT_MESSAGE(__LINE__) return; } static void collectOrientationConstraint(std::vector<RelationEdge>& vecRelationEdge, Graph& g) { collectTransitConstraint(vecRelationEdge, RelationEdge::RET_PARALLEL, g); std::pair<GraphEdgeItr, GraphEdgeItr> edgeItr = edges(g); for (GraphEdgeItr it = edgeItr.first; it != edgeItr.second; it ++) { GraphVertex u = source(*it, g); GraphVertex v = target(*it, g); const RelationVertex& sourceVertex = g[u]; const RelationVertex& targetVertex = g[v]; vecRelationEdge.push_back(RelationEdge(RelationEdge::RET_ORTHOGONAL, sourceVertex, targetVertex)); } return; } static bool findBridge(GraphVertex u, GraphVertex v, const Graph& g, GraphVertex &bridge) { std::set<GraphVertex> setBridge; std::pair<GraphOutEdgeItr, GraphOutEdgeItr> edgeItr = out_edges(u, g); for (GraphOutEdgeItr it = edgeItr.first; it != edgeItr.second; it ++) { setBridge.insert(target(*it, g)); } edgeItr = out_edges(v, g); for (GraphOutEdgeItr it = edgeItr.first; it != edgeItr.second; it ++) { bridge = target(*it, g); if (setBridge.find(bridge) != setBridge.end()) { return true; } } return false; } static std::pair<GraphVertex, GraphVertex> findParalell(const std::vector<GraphVertex>& vecLoop, const std::vector<Primitive*>& vecPrimitive, bool bForce, double angleThreshold) { std::pair<GraphVertex, GraphVertex> para; double nMinAngle = std::numeric_limits<double>::max(); int nLoopSize = vecLoop.size(); for (int i = 0; i < nLoopSize; ++ i) { Vector sNormal; if (!vecPrimitive[vecLoop[i]]->getNormal(sNormal)) { continue; } for (int j = i + 2; j < nLoopSize; ++ j) { if (i == 0 && j == nLoopSize-1) { continue; } Vector tNormal; if (!vecPrimitive[vecLoop[j]]->getNormal(tNormal)) { continue; } double nAngle = std::acos(std::abs(sNormal*tNormal)); if (nAngle < nMinAngle) { nMinAngle = nAngle; para.first = vecLoop[i]; para.second = vecLoop[j]; } } } if (!bForce && nMinAngle > angleThreshold) { return std::pair<GraphVertex, GraphVertex>(0, 0); } return para; } static bool willProduceLoop(std::vector<GraphVertex>& vecPredecessor, GraphVertex v, GraphVertex u, Graph& g) { path_recorder pathRecorder(vecPredecessor, v, u); try { breadth_first_search(g, v, visitor(pathRecorder)); // no path, so after we add edge(u, v), there will be no loop return false; } catch (PathDetectedException& e) { // there is a path between u and v, and we added edge(u, v), so there will be loop // and edge(u,v) is redundant return true; } } static void addParaEdge(GraphVertex u, GraphVertex v, const std::vector<Primitive*>& vecPrimitive, std::vector<GraphVertex>& vecPredecessor, double angleThreshold, Graph& g); static void addOrthEdge(GraphVertex u, GraphVertex v, const std::vector<Primitive*>& vecPrimitive, std::vector<GraphVertex>& vecPredecessor, double angleThreshold, Graph& g) { u = g[u].getParent(); v = g[v].getParent(); // check if edge exists if (edge(u, v, g).second) { return; } if (!willProduceLoop(vecPredecessor, v, u, g)) { add_edge(u, v, EdgeProp(RelationEdge::RET_ORTHOGONAL), g); } else { add_edge(u, v, EdgeProp(RelationEdge::RET_ORTHOGONAL), g); // there is a path between u and v, and we added edge(u, v), so there will be loop std::vector<GraphVertex> vecLoop; GraphVertex current = u; vecLoop.push_back(current); while (vecPredecessor[current] != current) { current = vecPredecessor[current]; vecLoop.push_back(current); } int nLoopSize = vecLoop.size(); if (nLoopSize == 3) { GraphVertex opposite2 = 0; GraphVertex opposite0 = 0; bool bShare01 = findBridge(vecLoop[0], vecLoop[1], g, opposite2); bool bShare12 = findBridge(vecLoop[1], vecLoop[2], g, opposite0); if (bShare01) { addParaEdge(opposite2, vecLoop[2], vecPrimitive, vecPredecessor, angleThreshold, g); } if (bShare12) { addParaEdge(opposite0, vecLoop[0], vecPrimitive, vecPredecessor, angleThreshold, g); } } else { std::pair<GraphVertex, GraphVertex> para = findParalell(vecLoop, vecPrimitive, (nLoopSize == 4), angleThreshold); if (para.first != para.second) { addParaEdge(para.first, para.second, vecPrimitive, vecPredecessor, angleThreshold, g); } } } return; } static void addParaEdge(GraphVertex u, GraphVertex v, const std::vector<Primitive*>& vecPrimitive, std::vector<GraphVertex>& vecPredecessor, double angleThreshold, Graph& g) { u = g[u].getParent(); v = g[v].getParent(); if (u == v) { return; } if (degree(u, g) != 0) { std::swap(u, v); } // path compression GraphVertex nVertexNum = num_vertices(g); std::vector<GraphVertex> vecStar; for (GraphVertex i = 0; i < nVertexNum; ++ i) { if (g[i].getParent() == u) { g[i].setParent(v); vecStar.push_back(i); } } for (std::vector<GraphVertex>::iterator it = vecStar.begin(); it != vecStar.end(); it ++) { GraphVertex i = *it; std::vector<GraphVertex> vecBridge; std::pair<GraphOutEdgeItr, GraphOutEdgeItr> edgeItr = out_edges(i, g); for (GraphOutEdgeItr it = edgeItr.first; it != edgeItr.second; it ++) { vecBridge.push_back(target(*it, g)); } int nBridgeNum = vecBridge.size(); for (int j = 0; j < nBridgeNum; ++ j) { remove_edge(i, vecBridge[j], g); } for (int j = 0; j < nBridgeNum; ++ j) { addOrthEdge(vecBridge[j], v, vecPrimitive, vecPredecessor, angleThreshold, g); } } return; } void reduceParaOrthEdges(const std::vector<Primitive*>& vecPrimitive, double angleThreshold, std::vector<RelationEdge>& vecRelationEdge, Graph& g) { PRINT_MESSAGE("Start...") filterOrientationConstraint(vecRelationEdge, g); PRINT_MESSAGE("Check relation edges...") if (vecRelationEdge.size() == 0) { collectOrientationConstraint(vecRelationEdge, g); return; } PRINT_MESSAGE("Start reduction...") while (!vecRelationEdge.empty()) { RelationEdge& relationEdge = vecRelationEdge.back(); vecRelationEdge.pop_back(); GraphVertex u = relationEdge.getSource().getIdx(); GraphVertex v = relationEdge.getTarget().getIdx(); std::vector<GraphVertex> vecPredecessor(vecPrimitive.size()); if (relationEdge.getType() == RelationEdge::RET_PARALLEL) { addParaEdge(u, v, vecPrimitive, vecPredecessor, angleThreshold, g); } else if (relationEdge.getType() == RelationEdge::RET_ORTHOGONAL) { addOrthEdge(u, v, vecPrimitive, vecPredecessor, angleThreshold, g); } PRINT_MESSAGE("FilterOrientation constraints... \n") //std::cout << vecRelationEdge.size() << " remaining" << std::endl; filterOrientationConstraint(vecRelationEdge, g); } PRINT_MESSAGE("Collect orientations...") collectOrientationConstraint(vecRelationEdge, g); return; } void reduceTransitEdges(const std::vector<Primitive*>& vecPrimitive, std::vector<RelationEdge>& vecRelationEdge, RelationEdge::RelationEdgeType relationType, Graph& g) { std::sort(vecRelationEdge.begin(), vecRelationEdge.end()); std::map<GraphVertex, RelationVertex> mapVertex; for (size_t i = 0, iEnd = vecRelationEdge.size(); i < iEnd; ++ i) { GraphVertex u = vecRelationEdge[i].getTarget().getIdx(); GraphVertex v = vecRelationEdge[i].getSource().getIdx(); mapVertex[u] = vecRelationEdge[i].getTarget(); mapVertex[v] = vecRelationEdge[i].getSource(); add_edge(u, v, EdgeProp(relationType), g); } std::vector<GraphVertex> component(num_vertices(g)); size_t numComponent = connected_components(g, &component[0]); std::map<size_t, std::vector<size_t> > mapComponent; for (size_t i = 0, iEnd = component.size(); i < iEnd; ++ i) { mapComponent[component[i]].push_back(i); } vecRelationEdge.clear(); for (std::map<size_t, std::vector<size_t> >::const_iterator it = mapComponent.begin(); it != mapComponent.end(); ++ it) { const std::vector<size_t>& vecComponent = it->second; if (vecComponent.size() < 2) { continue; } GraphVertex u = vecComponent[0]; for (size_t i = 1, iEnd = vecComponent.size(); i < iEnd; ++ i) { GraphVertex v = vecComponent[i]; RelationEdge relationEdge(relationType, mapVertex[v], mapVertex[u], 1.0); GlobFit::computeEdgeScore(relationEdge, vecPrimitive); vecRelationEdge.push_back(relationEdge); } } std::sort(vecRelationEdge.begin(), vecRelationEdge.end()); if (vecRelationEdge.size() == 0) { return; } if (vecRelationEdge[0].getType() != RelationEdge::RET_EQUAL_ANGLE && vecRelationEdge[0].getType() != RelationEdge::RET_EQUAL_LENGTH) { return; } g.clear(); for (size_t i = 0, iEnd = vecPrimitive.size(); i < iEnd; ++ i) { RelationVertex relationVertex(i, vecPrimitive[i]->getIdx()); relationVertex.setParent(i); add_vertex(relationVertex, g); } std::vector<RelationEdge> vecRemainingEdge; std::vector<GraphVertex> vecPredecessor(vecPrimitive.size()); for (size_t i = 0, iEnd = vecRelationEdge.size(); i < iEnd; ++ i) { const RelationVertex& source = vecRelationEdge[i].getSource(); const RelationVertex& target = vecRelationEdge[i].getTarget(); bool sourceProduceLoop = willProduceLoop(vecPredecessor, source.getPrimitiveIdx1(), source.getPrimitiveIdx2(), g); bool targetProduceLoop = willProduceLoop(vecPredecessor, target.getPrimitiveIdx1(), target.getPrimitiveIdx2(), g); // this is too strong for avoiding conflicts, some compatible cases may be removed // TODO: deduce the right rules for edges with 4 primitives involved if (sourceProduceLoop || targetProduceLoop) { continue; } add_edge(source.getPrimitiveIdx1(), source.getPrimitiveIdx2(), g); add_edge(target.getPrimitiveIdx1(), target.getPrimitiveIdx2(), g); vecRemainingEdge.push_back(vecRelationEdge[i]); } vecRelationEdge = vecRemainingEdge; return; }
34.968045
178
0.622319
frozar
b5f5162e7ba888302af6f4ecf48dc048e8c80be4
648
cpp
C++
HSAHRBNUOJ/P27xx/P2711.cpp
HeRaNO/OI-ICPC-Codes
4a4639cd3e347b472520065ca6ab8caadde6906d
[ "MIT" ]
18
2019-01-01T13:16:59.000Z
2022-02-28T04:51:50.000Z
HSAHRBNUOJ/P27xx/P2711.cpp
HeRaNO/OI-ICPC-Codes
4a4639cd3e347b472520065ca6ab8caadde6906d
[ "MIT" ]
null
null
null
HSAHRBNUOJ/P27xx/P2711.cpp
HeRaNO/OI-ICPC-Codes
4a4639cd3e347b472520065ca6ab8caadde6906d
[ "MIT" ]
5
2019-09-13T08:48:17.000Z
2022-02-19T06:59:03.000Z
#include <cstdio> #define MAXN 110 using namespace std; struct point { int x; int y; }; point a[MAXN]; int n, ans; bool judge(int p, int q, int r) { if (a[p].x == a[q].x && a[q].x == a[r].x) return false; if (a[p].y == a[q].y && a[q].y == a[r].y) return false; if ((a[r].y - a[q].y) * (a[q].x - a[p].x) == (a[r].x - a[q].x) * (a[q].y - a[p].y)) return false; return true; } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) scanf("%d %d", &a[i].x, &a[i].y); for (int i = 1; i <= n; i++) for (int j = i + 1; j <= n; j++) for (int k = j + 1; k <= n; k++) if (judge(i, j, k)) ans++; printf("%d\n", ans); return 0; }
19.058824
98
0.464506
HeRaNO
b5f673fb80ce02ef3b53323ff159b7c8e8907e38
1,197
cpp
C++
Records.cpp
pmwasson/LightCycle
42e9b7e0fe0e17ee231f43577b222288306be238
[ "MIT" ]
2
2019-12-07T19:37:31.000Z
2020-03-18T13:33:46.000Z
Records.cpp
pmwasson/LightCycle
42e9b7e0fe0e17ee231f43577b222288306be238
[ "MIT" ]
null
null
null
Records.cpp
pmwasson/LightCycle
42e9b7e0fe0e17ee231f43577b222288306be238
[ "MIT" ]
1
2020-06-30T15:46:03.000Z
2020-06-30T15:46:03.000Z
#include "Records.h" void Records::validate() { if (checksum != calcChecksum()) { edgeRaceMinutes = 99; edgeRaceSeconds = 0; edgeRaceSeed = 0xFADED; crazyCourierScore = 0; crazyCourierSeed = 0xDECAF; checksum = calcChecksum(); } } bool Records::setER(uint32_t seed, uint8_t minutes, uint8_t seconds) { if ((minutes < edgeRaceMinutes) || ((minutes == edgeRaceMinutes) && (seconds < edgeRaceSeconds))) { edgeRaceMinutes = minutes; edgeRaceSeconds = seconds; edgeRaceSeed = seed; checksum = calcChecksum(); return true; } else { return false; } } bool Records::setCC(uint32_t seed, uint16_t score) { if (score > crazyCourierScore) { crazyCourierScore = score; crazyCourierSeed = seed; checksum = calcChecksum(); return true; } else { return false; } } uint8_t Records::calcChecksum() { return 0x58 ^ edgeRaceMinutes ^ edgeRaceSeconds ^ edgeRaceSeed ^ (edgeRaceSeed >> 8) ^ (edgeRaceSeed >> 16) ^ crazyCourierScore ^ (crazyCourierScore >> 8) ^ crazyCourierSeed ^ (crazyCourierSeed >> 8) ^ (crazyCourierSeed >> 16); }
23.019231
101
0.619048
pmwasson
b5fd38e38aba66f3e4f63ed577a561d4dfae7516
3,079
cpp
C++
redis-cli/command.cpp
mobile-pos/amp
efe4eb4fda1e6f1ad2ee6113c3bf0a9a61068763
[ "MIT" ]
6
2020-09-12T08:16:46.000Z
2020-11-19T04:05:35.000Z
redis-cli/command.cpp
mobile-pos/amp
efe4eb4fda1e6f1ad2ee6113c3bf0a9a61068763
[ "MIT" ]
null
null
null
redis-cli/command.cpp
mobile-pos/amp
efe4eb4fda1e6f1ad2ee6113c3bf0a9a61068763
[ "MIT" ]
2
2020-12-11T02:27:56.000Z
2021-11-18T02:15:01.000Z
#include "command.h" using namespace Redis; Command::Command(QString commandName, QObject *parent) : QObject(parent), commandName(commandName) { arguments << commandName; } void Command::addArgument(QVariant argument) { arguments << argument; } void Command::addArgumentStrings(QStringList arguments) { foreach (QString argument, arguments) { addArgument(argument); } } QString Command::getCommandName() { return arguments[0].toString(); } QVariantList Command::getArguments() { return arguments; } Command* Command::HKEYS(QString key) { Command *command = new Command("HKEYS"); command->addArgument(key); return command; } Command *Command::Auth(QString auth) { Command *command = new Command("AUTH"); command->addArgument(auth); return command; } Command *Command::HGETALL(QString key) { Command *command = new Command("HGETALL"); command->addArgument(key); return command; } Command *Command::HGET(QString key, QString field) { Command *command = new Command("HGET"); command->addArgument(key); command->addArgument(field); return command; } Command *Command::HSET(QString key, QString field, QString value) { Command *command = new Command("HSET"); command->addArgument(key); command->addArgument(field); command->addArgument(value); return command; } Command *Command::HDEL(QString key, QString field) { Command *command = new Command("HDEL"); command->addArgument(key); command->addArgument(field); return command; } Command *Command::SET(QString key, QString value) { Command *command = new Command("SET"); command->addArgument(key); command->addArgument(value); return command; } Command *Command::GET(QString key) { Command *command = new Command("GET"); command->addArgument(key); return command; } Command *Command::DEL(QStringList keys) { Command *command = new Command("DEL"); command->addArgumentStrings(keys); return command; } Command *Command::EXPIRE(QString key, int seconds) { Command *command = new Command("EXPIRE"); command->addArgument(key); command->addArgument(seconds); return command; } Command *Command::KEYS(QString pattern) { Command *command = new Command("KEYS"); command->addArgument(pattern); return command; } Command *Command::LPUSH(QString key, QStringList values) { Command *command = new Command("LPUSH"); command->addArgument(key); command->addArgumentStrings(values); return command; } Command *Command::RPOP(QString key) { Command *command = new Command("RPOP"); command->addArgument(key); return command; } Command *Command::SUBSCRIBE(QStringList channels) { Command *command = new Command("SUBSCRIBE"); command->addArgumentStrings(channels); return command; } Command* Command::PUBLISH(QString channel, QString value) { Command *command = new Command("PUBLISH"); command->addArgument(channel); command->addArgument(value); return command; }
18.889571
73
0.683664
mobile-pos
b5fd899d46cd2044378731b452add96fc5a8fee3
9,183
cpp
C++
bundle/calamares/src/calamares/DebugWindow.cpp
ehalferty/garchinstall
29185f13a53d6bef0983349f29856a349e753d0a
[ "BSD-2-Clause" ]
null
null
null
bundle/calamares/src/calamares/DebugWindow.cpp
ehalferty/garchinstall
29185f13a53d6bef0983349f29856a349e753d0a
[ "BSD-2-Clause" ]
null
null
null
bundle/calamares/src/calamares/DebugWindow.cpp
ehalferty/garchinstall
29185f13a53d6bef0983349f29856a349e753d0a
[ "BSD-2-Clause" ]
null
null
null
/* === This file is part of Calamares - <https://calamares.io> === * * SPDX-FileCopyrightText: 2015-2016 Teo Mrnjavac <teo@kde.org> * SPDX-FileCopyrightText: 2019 Adriaan de Groot <groot@kde.org> * SPDX-License-Identifier: GPL-3.0-or-later * * Calamares is Free Software: see the License-Identifier above. * */ #include "DebugWindow.h" #include "ui_DebugWindow.h" #include "Branding.h" #include "GlobalStorage.h" #include "Job.h" #include "JobQueue.h" #include "Settings.h" #include "VariantModel.h" #include "modulesystem/Module.h" #include "modulesystem/ModuleManager.h" #include "utils/Logger.h" #include "utils/Paste.h" #include "utils/Retranslator.h" #ifdef WITH_PYTHONQT #include "ViewManager.h" #include "viewpages/PythonQtViewStep.h" #include <gui/PythonQtScriptingConsole.h> #endif #include <QSplitter> #include <QStringListModel> #include <QTreeView> #include <QWidget> /** * @brief crash makes Calamares crash immediately. */ static void crash() { volatile int* a = nullptr; *a = 1; } /// @brief Print out the widget tree (names) in indented form. static void dumpWidgetTree( QDebug& deb, const QWidget* widget, int depth ) { if ( !widget ) { return; } deb << Logger::Continuation; for ( int i = 0; i < depth; ++i ) { deb << ' '; } deb << widget->metaObject()->className() << widget->objectName(); for ( const auto* w : widget->findChildren< QWidget* >( QString(), Qt::FindDirectChildrenOnly ) ) { dumpWidgetTree( deb, w, depth + 1 ); } } namespace Calamares { DebugWindow::DebugWindow() : QWidget( nullptr ) , m_ui( new Ui::DebugWindow ) , m_globals( JobQueue::instance()->globalStorage()->data() ) , m_globals_model( std::make_unique< VariantModel >( &m_globals ) ) , m_module_model( std::make_unique< VariantModel >( &m_module ) ) { GlobalStorage* gs = JobQueue::instance()->globalStorage(); m_ui->setupUi( this ); m_ui->globalStorageView->setModel( m_globals_model.get() ); m_ui->globalStorageView->expandAll(); // Do above when the GS changes, too connect( gs, &GlobalStorage::changed, this, [=] { m_globals = JobQueue::instance()->globalStorage()->data(); m_globals_model->reload(); m_ui->globalStorageView->expandAll(); } ); // JobQueue page m_ui->jobQueueText->setReadOnly( true ); connect( JobQueue::instance(), &JobQueue::queueChanged, this, [this]( const QStringList& jobs ) { m_ui->jobQueueText->setText( jobs.join( '\n' ) ); } ); // Modules page QStringList modulesKeys; for ( const auto& m : ModuleManager::instance()->loadedInstanceKeys() ) { modulesKeys << m.toString(); } QStringListModel* modulesModel = new QStringListModel( modulesKeys ); m_ui->modulesListView->setModel( modulesModel ); m_ui->modulesListView->setSelectionMode( QAbstractItemView::SingleSelection ); m_ui->moduleConfigView->setModel( m_module_model.get() ); #ifdef WITH_PYTHONQT QPushButton* pythonConsoleButton = new QPushButton; pythonConsoleButton->setText( "Attach Python console" ); m_ui->modulesVerticalLayout->insertWidget( 1, pythonConsoleButton ); pythonConsoleButton->hide(); QObject::connect( pythonConsoleButton, &QPushButton::clicked, this, [this, moduleConfigModel] { QString moduleName = m_ui->modulesListView->currentIndex().data().toString(); Module* module = ModuleManager::instance()->moduleInstance( moduleName ); if ( module->interface() != Module::Interface::PythonQt || module->type() != Module::Type::View ) return; for ( ViewStep* step : ViewManager::instance()->viewSteps() ) { if ( step->moduleInstanceKey() == module->instanceKey() ) { PythonQtViewStep* pqvs = qobject_cast< PythonQtViewStep* >( step ); if ( pqvs ) { QWidget* consoleWindow = new QWidget; QWidget* console = pqvs->createScriptingConsole(); console->setParent( consoleWindow ); QVBoxLayout* layout = new QVBoxLayout; consoleWindow->setLayout( layout ); layout->addWidget( console ); QHBoxLayout* bottomLayout = new QHBoxLayout; layout->addLayout( bottomLayout ); QLabel* bottomLabel = new QLabel( consoleWindow ); bottomLayout->addWidget( bottomLabel ); QString line = QString( "Module: <font color=\"#008000\"><code>%1</code></font><br/>" "Python class: <font color=\"#008000\"><code>%2</code></font>" ) .arg( module->instanceKey() ) .arg( console->property( "classname" ).toString() ); bottomLabel->setText( line ); QPushButton* closeButton = new QPushButton( consoleWindow ); closeButton->setText( "&Close" ); QObject::connect( closeButton, &QPushButton::clicked, [consoleWindow] { consoleWindow->close(); } ); bottomLayout->addWidget( closeButton ); bottomLabel->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Preferred ); consoleWindow->setParent( this ); consoleWindow->setWindowFlags( Qt::Window ); consoleWindow->setWindowTitle( "Calamares Python console" ); consoleWindow->setAttribute( Qt::WA_DeleteOnClose, true ); consoleWindow->showNormal(); break; } } } } ); #endif connect( m_ui->modulesListView->selectionModel(), &QItemSelectionModel::selectionChanged, this, [this #ifdef WITH_PYTHONQT , pythonConsoleButton #endif ] { QString moduleName = m_ui->modulesListView->currentIndex().data().toString(); Module* module = ModuleManager::instance()->moduleInstance( ModuleSystem::InstanceKey::fromString( moduleName ) ); if ( module ) { m_module = module->configurationMap(); m_module_model->reload(); m_ui->moduleConfigView->expandAll(); m_ui->moduleTypeLabel->setText( module->typeString() ); m_ui->moduleInterfaceLabel->setText( module->interfaceString() ); #ifdef WITH_PYTHONQT pythonConsoleButton->setVisible( module->interface() == Module::Interface::PythonQt && module->type() == Module::Type::View ); #endif } } ); // Tools page connect( m_ui->crashButton, &QPushButton::clicked, this, [] { ::crash(); } ); connect( m_ui->reloadStylesheetButton, &QPushButton::clicked, []() { for ( auto* w : qApp->topLevelWidgets() ) { // Needs to match what's set in CalamaresWindow if ( w->objectName() == QStringLiteral( "mainApp" ) ) { w->setStyleSheet( Calamares::Branding::instance()->stylesheet() ); } } } ); connect( m_ui->widgetTreeButton, &QPushButton::clicked, []() { for ( auto* w : qApp->topLevelWidgets() ) { Logger::CDebug deb; dumpWidgetTree( deb, w, 0 ); } } ); // Send Log button only if it would be useful m_ui->sendLogButton->setVisible( CalamaresUtils::Paste::isEnabled() ); connect( m_ui->sendLogButton, &QPushButton::clicked, [this]() { CalamaresUtils::Paste::doLogUploadUI( this ); } ); CALAMARES_RETRANSLATE( m_ui->retranslateUi( this ); setWindowTitle( tr( "Debug information" ) ); ); } void DebugWindow::closeEvent( QCloseEvent* e ) { Q_UNUSED( e ) emit closed(); } DebugWindowManager::DebugWindowManager( QObject* parent ) : QObject( parent ) { } bool DebugWindowManager::enabled() const { const auto* s = Settings::instance(); return ( Logger::logLevel() >= Logger::LOGVERBOSE ) || ( s ? s->debugMode() : false ); } void DebugWindowManager::show( bool visible ) { if ( !enabled() ) { visible = false; } if ( m_visible == visible ) { return; } if ( visible ) { m_debugWindow = new Calamares::DebugWindow(); m_debugWindow->show(); connect( m_debugWindow.data(), &Calamares::DebugWindow::closed, this, [=]() { m_debugWindow->deleteLater(); m_visible = false; emit visibleChanged( false ); } ); m_visible = true; emit visibleChanged( true ); } else { if ( m_debugWindow ) { m_debugWindow->deleteLater(); } m_visible = false; emit visibleChanged( false ); } } void DebugWindowManager::toggle() { show( !m_visible ); } } // namespace Calamares
31.665517
120
0.582054
ehalferty
bd0403e8ed23cf7df3d81530bfdbea5c6b1f7840
1,564
cpp
C++
tools/deps/MachoParser/src/MachoTools.cpp
streamwater/HookZz
b09b89ea520c442142bf93b32c1a92b082715d59
[ "Apache-2.0" ]
4
2019-04-23T14:44:50.000Z
2020-11-05T06:52:37.000Z
tools/deps/MachoParser/src/MachoTools.cpp
streamwater/HookZz
b09b89ea520c442142bf93b32c1a92b082715d59
[ "Apache-2.0" ]
null
null
null
tools/deps/MachoParser/src/MachoTools.cpp
streamwater/HookZz
b09b89ea520c442142bf93b32c1a92b082715d59
[ "Apache-2.0" ]
4
2019-04-23T08:26:33.000Z
2021-09-21T07:45:19.000Z
// Copyright 2017 jmpews // // 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 "MachoTools.h" #ifdef __cplusplus extern "C" { #endif #include "zzdeps/common/LEB128.h" #include "zzdeps/common/debugbreak.h" #include "zzdeps/darwin/memory-utils-darwin.h" #ifdef __cplusplus } #endif #include "parsers/ObjcRuntime.h" #include "zz.h" void PrintClassInfo(objc_class_info_t *objc_class_info) { if (!objc_class_info) return; Xinfo("Class Name: %s, Address: %p", objc_class_info->class_name, (zpointer)objc_class_info->class_vmaddr); objc_method_infos_t *objc_method_infos; objc_method_infos = &(objc_class_info->objc_method_infos); std::vector<objc_method_info_t *>::iterator iter; objc_method_info_t *objc_method_info; for (iter = objc_method_infos->begin(); iter != objc_method_infos->end(); iter++) { objc_method_info = (*iter); Xinfo("- %s, %p", objc_method_info->method_name, (zpointer)objc_method_info->method_vmaddr); } }
30.666667
78
0.698849
streamwater
bd0508eac89c0ad4ebc1d8293f06bfcef10623e2
3,546
cpp
C++
dynamic_programming_tsp_solution/main.cpp
adw1n/TSP
a98ac96593023d1e782e60ff3e562b54caa7cc88
[ "WTFPL" ]
null
null
null
dynamic_programming_tsp_solution/main.cpp
adw1n/TSP
a98ac96593023d1e782e60ff3e562b54caa7cc88
[ "WTFPL" ]
1
2015-01-03T03:36:36.000Z
2015-01-03T03:37:21.000Z
dynamic_programming_tsp_solution/main.cpp
adw1n/TSP
a98ac96593023d1e782e60ff3e562b54caa7cc88
[ "WTFPL" ]
null
null
null
//DP O(n^2 * 2^n) solution for tsp problem #include <cstdio> #include <iostream> #include <algorithm> #include <string> #include <vector> #include <cstring> #include <set> #include <numeric> #include <utility> #include <map> #include <cmath> #include <functional> #include <chrono> using namespace std; using namespace chrono; typedef vector<int> VI; typedef long long LL; #define FOR(x, b, e) for(int x = b; x <= (e); ++x) #define FORD(x, b, e) for(int x = b; x >= (e); --x) #define REP(x, n) for(int x = 0; x < (n); ++x) #define VAR(v, n) __typeof(n) v = (n) #define ALL(c) (c).begin(), (c).end() #define SIZE(x) ((int)(x).size()) #define FOREACH(i, c) for(VAR(i, (c).begin()); i != (c).end(); ++i) #define PB push_back #define ST first #define ND second #define MP make_pair const int max_num_of_vertices=24; LL graph[max_num_of_vertices][max_num_of_vertices];//graph[i][j] - cost of edge from i to j const LL INF=1000000000; const int source=0;//home vertex LL num_of_vertices; VI hamilton_walk; LL tab[1<<max_num_of_vertices][max_num_of_vertices]; //bitmask - set of visited vertices, end - the last vertex to visit LL solve(int bitmask,int end){ if(tab[bitmask][end]!=-1) return tab[bitmask][end]; tab[bitmask][end]=INF; REP(vertex,num_of_vertices) if(vertex!=end and bitmask & (1<<vertex)) tab[bitmask][end]=min(tab[bitmask][end], solve(bitmask xor (1<<end), vertex )+graph[vertex][end]); return tab[bitmask][end]; } //implemented http://codeforces.com/blog/entry/337 1) bool find_hamilton_walk(int bitmask,int end,LL cost){ if(cost==0) { hamilton_walk.PB(end); return true; } bool found=false; hamilton_walk.PB(end); REP(vertex,num_of_vertices){ if((cost==tab[bitmask xor (1<<end)][vertex]+graph[vertex][end] and end!=vertex)) if(find(ALL(hamilton_walk),vertex)==hamilton_walk.end() or SIZE(hamilton_walk)==num_of_vertices) { found=find_hamilton_walk(bitmask xor (1<<end), vertex, cost-graph[vertex][end]); if(found) break; } } if(!found) hamilton_walk.pop_back(); return found; } bool find_best_hamilton_cycle(int bitmask,int end,LL cost){ bool found=find_hamilton_walk(bitmask, end, cost); hamilton_walk=vector<int>(hamilton_walk.rbegin(),hamilton_walk.rend()); return found; } int main (int argc, char * const argv[]) { if(!freopen(argc>=2 ? argv[1] :"../../tests/8cities_symmetric.txt", "r", stdin)) cout<<"Input file not found."<<endl; ios_base::sync_with_stdio(0); time_point<system_clock> start,end; start=system_clock::now(); memset(tab, -1, sizeof(tab)); cin>>num_of_vertices; if(num_of_vertices> max_num_of_vertices) { cout<<"too large number of vertices! "; return 0; } LL cost; REP(row,num_of_vertices) REP(column, num_of_vertices) { cin>>cost; if(cost<=0) cost=INF; graph[row][column]=cost; } REP(vertex,num_of_vertices) tab[1<<vertex][vertex]=graph[source][vertex],tab[source][vertex]=0; LL min_cost=solve( (1<<num_of_vertices) -1 ,source); find_best_hamilton_cycle((1<<num_of_vertices) -1 ,source, min_cost); end=system_clock::now(); duration<double> elapsed_time=end-start; if(min_cost>=INF) cout<<"NO HAMILTON CYCLE!"<<endl; else{ cout<<"min cost "<<min_cost<<endl; FOREACH(it,hamilton_walk) cout<<*it<<" "; cout<<endl<<"Computed in: "<<elapsed_time.count()<<" seconds."<<endl; } return 0; }
31.660714
118
0.648336
adw1n
bd0594d47c0c5ad4f3923d2845466807efb29609
707
cpp
C++
2nd/378_kth_smallest_element_in_a_sorted_matrix.cpp
buptlxb/leetcode
b641419de040801c4f54618d7ee26edcf10ee53c
[ "BSD-3-Clause" ]
null
null
null
2nd/378_kth_smallest_element_in_a_sorted_matrix.cpp
buptlxb/leetcode
b641419de040801c4f54618d7ee26edcf10ee53c
[ "BSD-3-Clause" ]
null
null
null
2nd/378_kth_smallest_element_in_a_sorted_matrix.cpp
buptlxb/leetcode
b641419de040801c4f54618d7ee26edcf10ee53c
[ "BSD-3-Clause" ]
null
null
null
#include <iostream> #include <algorithm> using namespace std; class Solution { public: int kthSmallest(vector<vector<int>>& matrix, int k) { if (matrix.empty()) return 0; int left = matrix[0][0], right = matrix.back().back(); while (left < right) { int cnt = 0; int mid = left + (right - left) / 2; for (int i = 0; i < matrix.size(); ++i) cnt += distance( matrix[i].begin(), upper_bound(matrix[i].begin(), matrix[i].end(), mid)); if (cnt < k) left = mid + 1; else right = mid; } return left; } }; int main(void) { return 0; }
23.566667
106
0.472419
buptlxb
bd05fc8012747354593e61af4b0c9f4bc1f9267a
1,044
cpp
C++
test/compare/test_compare_uint64.cpp
VeloPayments/v-portable-runtime
0810b249f78b04c9003db47782eb6a5bbb95f028
[ "MIT" ]
null
null
null
test/compare/test_compare_uint64.cpp
VeloPayments/v-portable-runtime
0810b249f78b04c9003db47782eb6a5bbb95f028
[ "MIT" ]
null
null
null
test/compare/test_compare_uint64.cpp
VeloPayments/v-portable-runtime
0810b249f78b04c9003db47782eb6a5bbb95f028
[ "MIT" ]
1
2020-07-03T18:18:24.000Z
2020-07-03T18:18:24.000Z
/** * \file test_compare_uint64.cpp * * Unit tests for compare_uint64. * * \copyright 2017 Velo-Payments, Inc. All rights reserved. */ #include <gtest/gtest.h> #include <vpr/compare.h> /** * Test that comparing two uint64_t values that are equal results in 0. */ TEST(compare_uint64, equality) { const uint64_t X = 17; const uint64_t Y = 17; EXPECT_EQ(0, memcmp(&X, &Y, sizeof(uint64_t))); EXPECT_EQ(0, compare_uint64(&X, &Y, sizeof(uint64_t))); } /** * Test that X > Y results in a return value that is greater than zero. */ TEST(compare_uint64, greater_than) { const uint64_t X = 17; const uint64_t Y = 14; EXPECT_LT(0, memcmp(&X, &Y, sizeof(uint64_t))); EXPECT_LT(0, compare_uint64(&X, &Y, sizeof(uint64_t))); } /** * Test that X < Y results in a return value that is less than zero. */ TEST(compare_uint64, less_than) { const uint64_t X = 17; const uint64_t Y = 19; EXPECT_GT(0, memcmp(&X, &Y, sizeof(uint64_t))); EXPECT_GT(0, compare_uint64(&X, &Y, sizeof(uint64_t))); }
22.212766
71
0.65613
VeloPayments
bd07027f10655ddf7e7644cece5a940dd0649e0d
7,191
cpp
C++
ShaderGLLib/Material.cpp
EPAC-Saxon/advance-obj-JulienBaumgartner
884aaf5a960f4f9575b0e9028b3234eacbfbb75b
[ "MIT" ]
null
null
null
ShaderGLLib/Material.cpp
EPAC-Saxon/advance-obj-JulienBaumgartner
884aaf5a960f4f9575b0e9028b3234eacbfbb75b
[ "MIT" ]
null
null
null
ShaderGLLib/Material.cpp
EPAC-Saxon/advance-obj-JulienBaumgartner
884aaf5a960f4f9575b0e9028b3234eacbfbb75b
[ "MIT" ]
null
null
null
#include "Material.h" #include <iterator> #include <fstream> #include <sstream> namespace sgl { std::map<std::string, std::shared_ptr<Material>> LoadMaterialsFromMtl(std::string file) { std::map<std::string, std::shared_ptr<Material>> materials; std::ifstream ifs; ifs.open(file, std::ifstream::in); if (!ifs.is_open()) { throw std::runtime_error("Couldn't open file: " + file); } std::shared_ptr<Material> material; std::string name; while (!ifs.eof()) { std::string line = ""; if (!std::getline(ifs, line)) break; if (line.empty()) continue; std::istringstream iss(line); std::string dump; if (!(iss >> dump)) { throw std::runtime_error( "Error parsing file: " + file + " no token found."); } if (dump == "newmtl") { if (material != nullptr) { materials[name] = material; } if (!(iss >> name)) { throw std::runtime_error( "Error parsing file : " + file + " no name found in newmtl."); } material = std::make_shared<Material>(name); } else if (dump == "map_Ka") { std::string path; if (!(iss >> path)) { throw std::runtime_error( "Error parsing file : " + file + " no path found in map_Ka."); } material->SetAmbientTexture(std::make_shared<Texture>(path)); } else if (dump == "map_Kd") { std::string path; if (!(iss >> path)) { throw std::runtime_error( "Error parsing file : " + file + " no path found in map_Kd."); } material->SetDiffuseTexture(std::make_shared<Texture>(path)); } else if (dump == "map_norm") { std::string path; if (!(iss >> path)) { throw std::runtime_error( "Error parsing file : " + file + " no path found in map_norm."); } material->SetNormalTexture(std::make_shared<Texture>(path)); } else if (dump == "map_Pm") { std::string path; if (!(iss >> path)) { throw std::runtime_error( "Error parsing file : " + file + " no path found in map_Pm."); } material->SetMetallicTexture(std::make_shared<Texture>(path)); } else if (dump == "map_Pr") { std::string path; if (!(iss >> path)) { throw std::runtime_error( "Error parsing file : " + file + " no path found in map_Pr."); } material->SetRoughnessTexture(std::make_shared<Texture>(path)); } else if (dump == "d") { float alpha; if (!(iss >> alpha)) { throw std::runtime_error( "Error parsing file : " + file + " no value found in d."); } material->SetAlpha(alpha); } else if (dump == "illum") { float illum; if (!(iss >> illum)) { throw std::runtime_error( "Error parsing file : " + file + " no value found in illum."); } material->SetIllum(illum); } else if (dump == "Ka") { float v[3]; if (!(iss >> v[0])) { throw std::runtime_error( "Error parsing file : " + file + " no r found in Ka."); } if (!(iss >> v[1])) { throw std::runtime_error( "Error parsing file : " + file + " no g found in Ka."); } if (!(iss >> v[2])) { throw std::runtime_error( "Error parsing file : " + file + " no b found in Ka."); } material->CreateAmbientTexture(v); } else if (dump == "Kd") { float v[3]; if (!(iss >> v[0])) { throw std::runtime_error( "Error parsing file : " + file + " no r found in Kd."); } if (!(iss >> v[1])) { throw std::runtime_error( "Error parsing file : " + file + " no g found in Kd."); } if (!(iss >> v[2])) { throw std::runtime_error( "Error parsing file : " + file + " no b found in Kd."); } material->CreateDiffuseTexture(v); } else if (dump == "norm") { float v[3]; if (!(iss >> v[0])) { throw std::runtime_error( "Error parsing file : " + file + " no r found in norm."); } if (!(iss >> v[1])) { throw std::runtime_error( "Error parsing file : " + file + " no g found in norm."); } if (!(iss >> v[2])) { throw std::runtime_error( "Error parsing file : " + file + " no b found in norm."); } material->CreateNormalTexture(v); } else if (dump == "Pm") { float v; if (!(iss >> v)) { throw std::runtime_error( "Error parsing file : " + file + " no value found in Pm."); } material->CreateMetallicTexture(&v); } else if (dump == "Pr") { float v; if (!(iss >> v)) { throw std::runtime_error( "Error parsing file : " + file + " no value found in Pr."); } material->CreateRoughnessTexture(&v); } } materials[name] = material; return materials; } Material::Material(std::string name) : name_(name) { } void Material::SetAmbientTexture(std::shared_ptr<Texture> texture) { ambient_texture_ = texture; } void Material::SetDiffuseTexture(std::shared_ptr<Texture> texture) { diffuse_texture_ = texture; } void Material::SetNormalTexture(std::shared_ptr<Texture> texture) { normal_texture_ = texture; } void Material::SetMetallicTexture(std::shared_ptr<Texture> texture) { metallic_texture_ = texture; } void Material::SetRoughnessTexture(std::shared_ptr<Texture> texture) { roughness_texture_ = texture; } void Material::SetAlpha(float alpha) { alpha_ = alpha; } void Material::SetIllum(float illum) { illum_ = illum; } void Material::CreateAmbientTexture(void* data) { ambient_texture_ = std::make_shared<Texture>(std::pair(1,1), data, PixelElementSize::FLOAT, PixelStructure::RGB); } void Material::CreateDiffuseTexture(void* data) { diffuse_texture_ = std::make_shared<Texture>(std::pair(1, 1), data, PixelElementSize::FLOAT, PixelStructure::RGB); } void Material::CreateNormalTexture(void* data) { normal_texture_ = std::make_shared<Texture>(std::pair(1, 1), data, PixelElementSize::FLOAT, PixelStructure::RGB); } void Material::CreateMetallicTexture(void* data) { metallic_texture_ = std::make_shared<Texture>(std::pair(1, 1), data, PixelElementSize::FLOAT, PixelStructure::GREY); } void Material::CreateRoughnessTexture(void* data) { roughness_texture_ = std::make_shared<Texture>(std::pair(1, 1), data, PixelElementSize::FLOAT, PixelStructure::GREY); } void Material::AddTextures(TextureManager& texture_manager) { texture_manager.AddTexture(name_ + "Ambient", ambient_texture_); texture_manager.AddTexture(name_ + "Diffuse", diffuse_texture_); texture_manager.AddTexture(name_ + "Normal", normal_texture_); texture_manager.AddTexture(name_ + "Metallic", metallic_texture_); texture_manager.AddTexture(name_ + "Roughness", roughness_texture_); } std::vector<std::string> Material::GetTexturesName() { std::vector<std::string> names; names.push_back(name_ + "Ambient"); names.push_back(name_ + "Diffuse"); names.push_back(name_ + "Normal"); names.push_back(name_ + "Metallic"); names.push_back(name_ + "Roughness"); return names; } }
22.54232
119
0.590738
EPAC-Saxon
bd07c25d6feec31f895d37fbd5aa4cc862c65811
1,578
cpp
C++
ModernOpenGLUdemy/main.cpp
killerasus/ModernOpenGL
3bde26a468e945282cd0f8366939bd6c2730ab05
[ "MIT" ]
2
2019-10-16T00:05:57.000Z
2019-10-16T00:17:25.000Z
ModernOpenGLUdemy/main.cpp
killerasus/ModernOpenGL
3bde26a468e945282cd0f8366939bd6c2730ab05
[ "MIT" ]
null
null
null
ModernOpenGLUdemy/main.cpp
killerasus/ModernOpenGL
3bde26a468e945282cd0f8366939bd6c2730ab05
[ "MIT" ]
null
null
null
#include <iostream> #include <GL/glew.h> #include <GLFW/glfw3.h> const GLint WIDTH = 800, HEIGHT = 600; int main() { if (!glfwInit()) { std::cout << "GLFW initialization failed!" << std::endl; glfwTerminate(); return 1; } // Setup GLFW window properties // OpenGL version glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); // Core profile - No backwards compatibility glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // Allow forward compatibility glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); GLFWwindow* mainWindow = glfwCreateWindow(WIDTH, HEIGHT, "Test Window", nullptr, nullptr); if (mainWindow == nullptr) { std::cout << "GLFW window creation failed!" << std::endl; glfwTerminate(); return 1; } // Get buffer size information int bufferWidth = -1, bufferHeight = -1; glfwGetFramebufferSize(mainWindow, &bufferWidth, &bufferHeight); // Set context for GLEW to use glfwMakeContextCurrent(mainWindow); // Allow modern extension features glewExperimental = GL_TRUE; if (glewInit() != GLEW_OK) { std::cout << "GLEW initialization failed!" << std::endl; glfwDestroyWindow(mainWindow); glfwTerminate(); return 1; } // Setup viewport size glViewport(0, 0, bufferWidth, bufferHeight); // Loop until window closed while (!glfwWindowShouldClose(mainWindow)) { // Get and handle user input events glfwPollEvents(); // Clear window glClearColor(1.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); glfwSwapBuffers(mainWindow); } return 0; }
22.542857
91
0.720532
killerasus
bd0c7f26e20517c38fe3a380aa92afbc081f20d4
4,847
cpp
C++
src/api/API.cpp
myxor/ceema
e0a9f299fd488da38a9a1492502017995d59e183
[ "Apache-2.0" ]
19
2018-08-31T12:52:13.000Z
2021-08-11T18:05:42.000Z
src/api/API.cpp
myxor/ceema
e0a9f299fd488da38a9a1492502017995d59e183
[ "Apache-2.0" ]
4
2019-02-01T09:12:56.000Z
2022-01-14T21:36:17.000Z
src/api/API.cpp
myxor/ceema
e0a9f299fd488da38a9a1492502017995d59e183
[ "Apache-2.0" ]
5
2021-03-28T18:06:21.000Z
2022-01-13T17:46:12.000Z
/** * Copyright 2017 Harold Bruintjes * * 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 "API.h" #include "logging/logging.h" namespace ceema { API::API(HttpManager& manager) : m_manager(manager) { m_manager.set_cert(api_cert); } future<byte_vector> API::get(std::string const &url) { auto& client = m_manager.getFreeClient(); return client.get(url); } future<void> API::get(std::string const &url, IHttpTransfer* transfer) { auto& client = m_manager.getFreeClient(); return client.get(url, transfer); } future<byte_vector> API::post(std::string const &url, byte_vector const& data) { auto& client = m_manager.getFreeClient(); return client.post(url, data); } void API::postFile(std::string url, IHttpTransfer* transfer, std::string const& filename) { auto& client = m_manager.getFreeClient(); client.postFile(url, transfer, filename); } future<byte_vector> API::postFile(std::string url, byte_vector const& data, std::string const& filename) { auto& client = m_manager.getFreeClient(); return client.postFile(url, data, filename); } future<json> API::jsonGet(std::string const& url) { auto& client = m_manager.getFreeClient(); auto request_fut = client.get(url); auto json_fut = request_fut.next([](future<byte_vector> fut) { byte_vector data = fut.get(); return checkJSONResult(json::parse(data.begin(), data.end())); }); return json_fut; } future<json> API::jsonPost(std::string const& url, json request) { auto& client = m_manager.getFreeClient(); std::string jsonString = request.dump(); LOG_DBG("Submitting API request: " << request); auto request_fut = client.post(url, byte_vector(jsonString.begin(), jsonString.end())); auto json_fut = request_fut.next([](future<byte_vector> fut) { byte_vector data = fut.get(); return checkJSONResult(json::parse(data.begin(), data.end())); }); return json_fut; } json API::checkJSONResult(json data) { LOG_DBG("Got JSON data for API: " << data); if (data.count("success") && !data["success"].get<bool>()) { throw std::runtime_error(data["error"].get<std::string>().c_str()); } return data; } const char* API::api_cert = "-----BEGIN CERTIFICATE-----\n" "MIIEYTCCA0mgAwIBAgIJAM1DR/DBRFpQMA0GCSqGSIb3DQEBBQUAMH0xCzAJBgNV\n" "BAYTAkNIMQswCQYDVQQIEwJaSDEPMA0GA1UEBxMGWnVyaWNoMRAwDgYDVQQKEwdU\n" "aHJlZW1hMQswCQYDVQQLEwJDQTETMBEGA1UEAxMKVGhyZWVtYSBDQTEcMBoGCSqG\n" "SIb3DQEJARYNY2FAdGhyZWVtYS5jaDAeFw0xMjExMTMxMTU4NThaFw0zMjExMDgx\n" "MTU4NThaMH0xCzAJBgNVBAYTAkNIMQswCQYDVQQIEwJaSDEPMA0GA1UEBxMGWnVy\n" "aWNoMRAwDgYDVQQKEwdUaHJlZW1hMQswCQYDVQQLEwJDQTETMBEGA1UEAxMKVGhy\n" "ZWVtYSBDQTEcMBoGCSqGSIb3DQEJARYNY2FAdGhyZWVtYS5jaDCCASIwDQYJKoZI\n" "hvcNAQEBBQADggEPADCCAQoCggEBAK8GdoT7IpNC3Dz7IUGYW9pOBwx+9EnDZrkN\n" "VD8l3KfBHjGTdi9gQ6Nh+mQ9/yQ8254T2big9p0hcn8kjgEQgJWHpNhYnOhy3i0j\n" "cmlzb1MF/deFjJVtuMP3tqTwiMavpweoa20lGDn/CLZodu0Ra8oL78b6FVztNkWg\n" "PdiWClMk0JPPMlfLEiK8hfHE+6mRVXmi12itK1semmwyHKdj9fG4X9+rQ2sKuLfe\n" "jx7uFxnAF+GivCuCo8xfOesLw72vx+W7mmdYshg/lXOcqvszQQ/LmFEVQYxNaeeV\n" "nPSAs+ht8vUPW4sX9IkXKVgBJd1R1isUpoF6dKlUexmvLxEyf5cCAwEAAaOB4zCB\n" "4DAdBgNVHQ4EFgQUw6LaC7+J62rKdaTA37kAYYUbrkgwgbAGA1UdIwSBqDCBpYAU\n" "w6LaC7+J62rKdaTA37kAYYUbrkihgYGkfzB9MQswCQYDVQQGEwJDSDELMAkGA1UE\n" "CBMCWkgxDzANBgNVBAcTBlp1cmljaDEQMA4GA1UEChMHVGhyZWVtYTELMAkGA1UE\n" "CxMCQ0ExEzARBgNVBAMTClRocmVlbWEgQ0ExHDAaBgkqhkiG9w0BCQEWDWNhQHRo\n" "cmVlbWEuY2iCCQDNQ0fwwURaUDAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBBQUA\n" "A4IBAQARHMyIHBDFul+hvjACt6r0EAHYwR9GQSghIQsfHt8cyVczmEnJH9hrvh9Q\n" "Vivm7mrfveihmNXAn4WlGwQ+ACuVtTLxw8ErbST7IMAOx9npHf/kngnZ4nSwURF9\n" "rCEyHq179pNXpOzZ257E5r0avMNNXXDwulw03iBE21ebd00pG11GVq/I26s+8Bjn\n" "DKRPquKrSO4/luEDvL4ngiQjZp32S9Z1K9sVOzqtQ7I9zzeUADm3aVa/Bpaw4iMR\n" "1SI7o9aJYiRi1gxYP2BUA1IFqr8NzyfGD7tRHdq7bZOxXAluv81dcbz0SBX8SgV1\n" "4HEKc6xMANnYs/aYKjvmP0VpOvRU\n" "-----END CERTIFICATE-----"; }
42.147826
110
0.706416
myxor
bd0e127ea93ad4b923f4790be65c14f7046fd2d5
4,668
cpp
C++
Visual Mercutio/zModelBP/PSS_RiskNewFileDlg.cpp
Jeanmilost/Visual-Mercutio
f079730005b6ce93d5e184bb7c0893ccced3e3ab
[ "MIT" ]
1
2022-01-31T06:24:24.000Z
2022-01-31T06:24:24.000Z
Visual Mercutio/zModelBP/PSS_RiskNewFileDlg.cpp
Jeanmilost/Visual-Mercutio
f079730005b6ce93d5e184bb7c0893ccced3e3ab
[ "MIT" ]
2
2021-04-11T15:50:42.000Z
2021-06-05T08:23:04.000Z
Visual Mercutio/zModelBP/PSS_RiskNewFileDlg.cpp
Jeanmilost/Visual-Mercutio
f079730005b6ce93d5e184bb7c0893ccced3e3ab
[ "MIT" ]
2
2021-01-08T00:55:18.000Z
2022-01-31T06:24:18.000Z
/**************************************************************************** * ==> PSS_RiskNewFileDlg --------------------------------------------------* **************************************************************************** * Description : Provides a create a new risk file dialog box * * Developer : Processsoft * ****************************************************************************/ #include "stdafx.h" #include "PSS_RiskNewFileDlg.h" // processsoft #include "zMediator\PSS_Application.h" #include "zBaseLib\PSS_File.h" #include "zBaseLib\PSS_TextFile.h" #include "zBaseLib\PSS_MsgBox.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif //--------------------------------------------------------------------------- // Message map //--------------------------------------------------------------------------- BEGIN_MESSAGE_MAP(PSS_RiskNewFileDlg, CDialog) //{{AFX_MSG_MAP(PSS_RiskNewFileDlg) ON_BN_CLICKED(IDC_DIRECTORY_SELECT, OnBnClickedDirectorySelect) ON_EN_CHANGE(IDC_FILENAME, OnEnChangeFileName) ON_EN_CHANGE(IDC_DIRECTORY, OnEnChangeDirectory) ON_BN_CLICKED(IDOK, OnBnClickedOk) //}}AFX_MSG_MAP END_MESSAGE_MAP() //--------------------------------------------------------------------------- // PSS_RiskNewFileDlg //--------------------------------------------------------------------------- PSS_RiskNewFileDlg::PSS_RiskNewFileDlg(const CString& extension, CWnd* pParent) : CDialog(PSS_RiskNewFileDlg::IDD, pParent), m_Extension(extension) {} //--------------------------------------------------------------------------- PSS_RiskNewFileDlg::~PSS_RiskNewFileDlg() {} //--------------------------------------------------------------------------- CString PSS_RiskNewFileDlg::GetDirectory() { return m_Directory; } //--------------------------------------------------------------------------- CString PSS_RiskNewFileDlg::GetFileName() { return m_FileName; } //--------------------------------------------------------------------------- void PSS_RiskNewFileDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(PSS_RiskNewFileDlg) DDX_Text (pDX, IDC_FILENAME, m_FileName); DDX_Text (pDX, IDC_DIRECTORY, m_Directory); DDX_Control(pDX, IDC_FILENAME, m_FileName_Ctrl); DDX_Control(pDX, IDC_DIRECTORY, m_Directory_Ctrl); DDX_Control(pDX, IDOK, m_OK_Ctrl); //}}AFX_DATA_MAP } //--------------------------------------------------------------------------- BOOL PSS_RiskNewFileDlg::OnInitDialog() { CDialog::OnInitDialog(); PSS_Application* pApplication = PSS_Application::Instance(); if (pApplication) { PSS_MainForm* pMainForm = pApplication->GetMainForm(); if (pMainForm) { m_Directory = pMainForm->GetApplicationDir() + g_RiskDirectory; m_Directory_Ctrl.SetWindowText(m_Directory); } } m_OK_Ctrl.EnableWindow(FALSE); return TRUE; } //--------------------------------------------------------------------------- void PSS_RiskNewFileDlg::OnBnClickedDirectorySelect() { CSHFileInfo fileInfo; fileInfo.m_strTitle = _T(m_Directory); if (fileInfo.BrowseForFolder(GetParent()) == IDOK) { m_Directory = fileInfo.m_strPath; m_Directory_Ctrl.SetWindowText(m_Directory); } } //--------------------------------------------------------------------------- void PSS_RiskNewFileDlg::OnEnChangeFileName() { m_FileName_Ctrl.GetWindowText(m_FileName); CheckUserEntry(); } //--------------------------------------------------------------------------- void PSS_RiskNewFileDlg::OnEnChangeDirectory() { m_Directory_Ctrl.GetWindowText(m_Directory); CheckUserEntry(); } //--------------------------------------------------------------------------- void PSS_RiskNewFileDlg::OnBnClickedOk() { PSS_File file; if (!file.Exist(m_Directory)) { PSS_MsgBox mBox; mBox.Show(IDS_BAD_DIRECTORY, MB_OK); return; } if (file.Exist(m_Directory + _T("\\") + m_FileName + m_Extension)) { PSS_MsgBox mBox; mBox.Show(IDS_RISK_FILE_ALREADY_EXIST, MB_OK); return; } OnOK(); } //--------------------------------------------------------------------------- void PSS_RiskNewFileDlg::CheckUserEntry() { if (!m_FileName.IsEmpty() && !m_Directory.IsEmpty()) m_OK_Ctrl.EnableWindow(TRUE); else m_OK_Ctrl.EnableWindow(FALSE); } //---------------------------------------------------------------------------
32.643357
81
0.477721
Jeanmilost
bd135eb20b929718d7642e8d65a5bd52e3093f55
438
cpp
C++
src/generate_ua_nodeset2.cpp
Jokymon/TinyModelCompiler
dd0251cd8c1915e5615f43348c03f4176d9e90af
[ "MIT" ]
1
2020-01-03T16:18:47.000Z
2020-01-03T16:18:47.000Z
src/generate_ua_nodeset2.cpp
Jokymon/TinyModelCompiler
dd0251cd8c1915e5615f43348c03f4176d9e90af
[ "MIT" ]
null
null
null
src/generate_ua_nodeset2.cpp
Jokymon/TinyModelCompiler
dd0251cd8c1915e5615f43348c03f4176d9e90af
[ "MIT" ]
1
2020-01-30T20:54:12.000Z
2020-01-30T20:54:12.000Z
#include "ua_nodeset2_generator.h" #include <CLI/CLI.hpp> #include <iostream> #include <string> int main(int argc, char **argv) { CLI::App app; std::string docname; app.add_option("docname", docname, "Path to the Opc.Ua.NodeSet2.xml input file") ->required(); CLI11_PARSE(app, argc, argv); ua_nodeset2_generator ns2gen; ns2gen.load_nodeset(docname); ns2gen.write_nodeset2_sources(); return 0; }
19.043478
84
0.680365
Jokymon
bd14c36f8c89d0bc09bbf909b0862b8d22e91b02
1,980
cpp
C++
src/vega/pathname.cpp
project-eutopia/vega
c7b536c5e949094a908fa8f378729dbffc657f4a
[ "MIT" ]
18
2018-01-23T12:28:13.000Z
2022-02-13T12:23:21.000Z
src/vega/pathname.cpp
project-eutopia/vega
c7b536c5e949094a908fa8f378729dbffc657f4a
[ "MIT" ]
2
2018-11-29T01:51:25.000Z
2022-03-22T14:14:22.000Z
src/vega/pathname.cpp
project-eutopia/vega
c7b536c5e949094a908fa8f378729dbffc657f4a
[ "MIT" ]
6
2019-02-01T09:54:44.000Z
2022-01-09T22:13:54.000Z
#include "vega/pathname.h" namespace vega { Pathname::Pathname() noexcept : full_name_(), last_slash_(std::string::npos), last_dot_(std::string::npos) {} Pathname::Pathname(const std::string& full_name) noexcept : full_name_(full_name), last_slash_(std::string::npos), last_dot_(std::string::npos) { precompute(); } Pathname::Pathname(const char* s) noexcept : full_name_(s), last_slash_(std::string::npos), last_dot_(std::string::npos) { precompute(); } void Pathname::precompute() { last_slash_ = full_name_.rfind('/'); last_dot_ = full_name_.rfind('.'); if (last_dot_ != std::string::npos) { if (last_slash_ == std::string::npos) { // If no folder in front, then leading dot is not preceding file name extension if (last_dot_ == 0) last_dot_ = std::string::npos; } else { if (last_slash_ + 1 >= last_dot_) last_dot_ = std::string::npos; } } } const std::string& Pathname::full_name() const { return full_name_; } Pathname::operator std::string() const { return full_name_; } std::string Pathname::extension() const { return last_dot_ == std::string::npos ? "" : full_name_.substr(last_dot_ + 1); } std::string Pathname::base_name() const { size_t start = last_slash_ == std::string::npos ? 0 : last_slash_ + 1; if (last_dot_ == std::string::npos) { return full_name_.substr(start); } else { return full_name_.substr(start, last_dot_-start); } } std::string Pathname::folder() const { return last_slash_ == std::string::npos ? "./" : full_name_.substr(0, last_slash_ + 1); } std::istream& operator>>(std::istream& is, Pathname& pathname) { is >> pathname.full_name_; pathname.precompute(); return is; } const Pathname operator+(const Pathname& lhs, const Pathname& rhs) { return Pathname(lhs.full_name() + rhs.full_name()); } }
26.052632
91
0.621717
project-eutopia
bd1545f163aa78bc26da6765ece2afb2198c552e
652
hpp
C++
src/Dispatcher.hpp
tblyons/goon
fd5fbdda14fe1b4869e365c7cebec2bcb7de06e3
[ "Unlicense" ]
1
2022-02-11T21:25:53.000Z
2022-02-11T21:25:53.000Z
apps/Goon/src/Dispatcher.hpp
tybl/tybl
cc74416d3d982177d46b89c0ca44f3a8e1cf00d6
[ "Unlicense" ]
15
2021-08-21T13:41:29.000Z
2022-03-08T14:13:43.000Z
apps/Goon/src/Dispatcher.hpp
tybl/tybl
cc74416d3d982177d46b89c0ca44f3a8e1cf00d6
[ "Unlicense" ]
null
null
null
// License: The Unlicense (https://unlicense.org) #ifndef GOON_DISPATCHER_HPP #define GOON_DISPATCHER_HPP #include <SDL2/SDL.h> #include <functional> #include <vector> struct Dispatcher { Dispatcher(void); bool KeepRunning(void) const; void ProcessEvents(void); void AddKeyboardListener(std::function<void(SDL_Keycode)> func); void AddWindowListener(std::function<void(SDL_WindowEvent)> func); private: void OptOutEvents(void); private: std::vector<std::function<void(SDL_Keycode)>> mKeyboardListeners; std::vector<std::function<void(SDL_WindowEvent)>> mWindowListeners; bool mKeepRunning; }; #endif // GOON_DISPATCHER_HPP
28.347826
70
0.760736
tblyons
bd168b5563576a730d42a2d3e9d2c92f433af997
1,246
hpp
C++
include/interpolation/appoximate.hpp
mnrn/game-memo
8ed939b8ccc77ba9266beddd6214a5c0c5cc03c2
[ "Apache-2.0" ]
null
null
null
include/interpolation/appoximate.hpp
mnrn/game-memo
8ed939b8ccc77ba9266beddd6214a5c0c5cc03c2
[ "Apache-2.0" ]
null
null
null
include/interpolation/appoximate.hpp
mnrn/game-memo
8ed939b8ccc77ba9266beddd6214a5c0c5cc03c2
[ "Apache-2.0" ]
null
null
null
/** * @brief 近似していきます。近似アルゴリズムとは関係ありません。 * @date 2018/12/24 */ #ifndef APPROXIMATE_HPP #define APPROXIMATE_HPP // ******************************************************************************** // Include files // ******************************************************************************** #include <climits> #include <cstdint> #include <type_traits> // ******************************************************************************** // Macros // ******************************************************************************** #define APPROXIMATE_BEGIN namespace approximate { #define APPROXIMATE_END } APPROXIMATE_BEGIN // ******************************************************************************** // Functions // ******************************************************************************** /** * @brief 値をsrcからdstへ近似していきます。 * @tparam Float 浮動少数点数型 * @param src 始点 * @param dst 終点 * @param speed 近似速度 * @return 近似後の値 */ template <typename Float> constexpr Float approx(Float src, Float dst, Float speed) { static_assert(std::is_floating_point_v<Float>, "only make sence for floating point types."); return src + (dst - src) * speed; } APPROXIMATE_END #endif // end of APPROXIMATE_HPP
25.958333
83
0.422151
mnrn
bd18b866b9459091ef5ec62a3e6f9a2319c38bf5
1,127
cc
C++
src/02_management/12_move.cc
chanchann/lighao
5c06c4dfcf93b9dd59522971f9c939af128b9378
[ "MIT" ]
1
2021-01-18T02:37:03.000Z
2021-01-18T02:37:03.000Z
src/02_management/12_move.cc
chanchann/Thread
5c06c4dfcf93b9dd59522971f9c939af128b9378
[ "MIT" ]
null
null
null
src/02_management/12_move.cc
chanchann/Thread
5c06c4dfcf93b9dd59522971f9c939af128b9378
[ "MIT" ]
null
null
null
/* 下面实现一个为std::thread添加了析构行为的joining_thread TODO */ #include <iostream> #include <thread> class A { std::thread t; public: A() noexcept = default; template<typename T, typename... Ts> explicit A(T&& f, Ts&&... args) : t(std::forward<T>(f), std::forward<Ts>(args)...) {} explicit A(std::thread x) noexcept : t(std::move(x)) {} A(A&& rhs) noexcept : t(std::move(rhs.t)) {} A& operator=(A&& rhs) noexcept { if (joinable()) join(); t = std::move(rhs.t); return *this; } A& operator=(std::thread rhs) noexcept { if (joinable()) join(); t = std::move(rhs); return *this; } ~A() noexcept { if (joinable()) join(); } void swap(A&& rhs) noexcept { t.swap(rhs.t); } std::thread::id get_id() const noexcept { return t.get_id(); } bool joinable() const noexcept { return t.joinable(); } void join() { t.join(); } void detach() { t.detach(); } std::thread& as_thread() noexcept { return t; } const std::thread& as_thread() const noexcept { return t; } };
22.54
66
0.535936
chanchann
bd1939be39508ed63c7723040f71afabc12c94c6
7,116
hpp
C++
engine/alice/application.hpp
stereoboy/isaac_sdk_20191213
73c863254e626c8d498870189fbfb20be4e10fb3
[ "FSFAP" ]
1
2020-04-14T13:55:16.000Z
2020-04-14T13:55:16.000Z
engine/alice/application.hpp
stereoboy/isaac_sdk_20191213
73c863254e626c8d498870189fbfb20be4e10fb3
[ "FSFAP" ]
4
2020-09-25T22:34:29.000Z
2022-02-09T23:45:12.000Z
engine/alice/application.hpp
stereoboy/isaac_sdk_20191213
73c863254e626c8d498870189fbfb20be4e10fb3
[ "FSFAP" ]
1
2020-07-02T11:51:17.000Z
2020-07-02T11:51:17.000Z
/* Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited. */ #pragma once #include <atomic> #include <memory> #include <string> #include <tuple> #include <utility> #include <vector> #include "engine/alice/node.hpp" #include "engine/gems/serialization/json.hpp" #include "engine/gems/uuid/uuid.hpp" namespace isaac { namespace alice { class ApplicationJsonLoader; class Backend; // The basis of an Isaac application. An application normally contains many nodes which work // together to create complex behaviors. A node in turn contains multiple components which define // its functionality. Components can be configured via parameters, exchange data via messages, and // much more. // // Applications can be created as specified in a JSON object. They can also be built interactively // at runtime, however not all features are yet supported for this use case. // // If you want to create an application which parses basic parameters via the command line you // can use the //engine/alice/tools:parse_command_line. This is kept as a separate library to not // pollute the default compile object with static variable from gflags. // // The API of this class is still under development and should considered to be experimental. class Application { public: // Creates a new application Application(const ApplicationJsonLoader& loader); // Creates a new application with a random name Application(const std::vector<std::string> module_paths = {}, const std::string& asset_path = ""); // Creates a new application as specified in the given JSON object. Application(const nlohmann::json& json, const std::vector<std::string> module_paths = {}, const std::string& asset_path = ""); ~Application(); // A name for the app which stays the same over time const std::string& name() const { return name_; } // A unique identifier which is different for every running application const Uuid& uuid() const { return uuid_; } // Loads more configuration and nodes from a JSON file void loadFromFile(const std::string& json_file); // Loads more configuration and nodes from a JSON text string void loadFromText(const std::string& json_text); // Loads more configuration and nodes from a JSON object void load(const nlohmann::json& json); // Creates a new node with the given name Node* createNode(const std::string& name); Node* createMessageNode(const std::string& name); // Destroys the node with the given name and all its components void destroyNode(const std::string& name); // Finds a node by name. This function will return nullptr if no node with this name exists. Node* findNodeByName(const std::string& name) const; // Gets a node by name. This function will assert if no node with this name exists. Node* getNodeByName(const std::string& name) const; // Find all nodes which have a component of the given type template <typename T> std::vector<Node*> findNodesWithComponent() const { std::vector<Node*> result; for (Node* node : nodes()) { if (node->hasComponent<T>()) { result.push_back(node); } } return result; } // Find all components of the given type. This function is quite slow. template <typename T> std::vector<T*> findComponents() const { std::vector<T*> result; for (Node* node : nodes()) { const auto components = node->getComponents<T>(); result.insert(result.end(), components.begin(), components.end()); } return result; } // Finds a unique component of the given type. Returns null if none or multiple components of this // type where found. This function is quite slow. template <typename T> T* findComponent() const { T* pointer = nullptr; for (Node* node : nodes()) { if (T* component = node->getComponentOrNull<T>()) { if (pointer != nullptr) { return nullptr; } pointer = component; } } return pointer; } // @deprecated: Use `getNodeComponentOrNull` instead. // Find a component by name and type. `link` is given as "node_name/component_name" template <typename T> T* findComponentByName(const std::string& link) const { return dynamic_cast<T*>(findComponentByName(link)); } // Find a component by name. `link` is given as "node_name/component_name" Component* findComponentByName(const std::string& link) const; // Gets the component of given type in the node of given name. Asserts in case the node // does not exists, or if there are none or multiple components of the given type in the node. template <typename T> T* getNodeComponent(const std::string& node_name) const { return getNodeByName(node_name)->getComponent<T>(); } // Gets the component of given type in the node of given name. nullptr is returned in case the // node does not exist, or if there are none or multiple components of the given type in the node. template <typename T> T* getNodeComponentOrNull(const std::string& node_name) const { const Node* node = findNodeByName(node_name); if (node == nullptr) return nullptr; return node->getComponentOrNull<T>(); } // For a channel 'nodename/compname/tag', return the component and tag string std::tuple<Component*, std::string> getComponentAndTag(const std::string& channel); // Starts the app, waits for the given duration, then stops the app void startWaitStop(double duration); // Starts the app, waits for Ctrl+C, then stops the app void startWaitStop(); // Interrupts the application and stops it void interrupt(); // Starts the app void start(); // Srops the app void stop(); Backend* backend() const { return backend_.get(); } // Gets absolute filename for relative asset filename. Identity in case of absolute filename. std::string getAssetPath(const std::string& path = "") const; private: friend class Node; friend class Backend; // Gets all nodes std::vector<Node*> nodes() const; // Creates a new application from the given JSON object. void createApplication(const ApplicationJsonLoader& loader); // Creates more configuration and graph void createMore(const ApplicationJsonLoader& loader); std::string name_; Uuid uuid_; std::unique_ptr<Backend> backend_; std::atomic<bool> is_running_; // Filename to write out the application json std::string application_backup_; // Cache the application json while the app is loading to write out to file later nlohmann::json app_json_; // Filename to write out the configuration std::string config_backup_; // Filename to write out the performance report std::string performance_report_out_; // Base path to search assets for std::string asset_path_; }; } // namespace alice } // namespace isaac
36.870466
100
0.723159
stereoboy
bd1da0dfad056a510f059f4a7642bff52a7cf4e3
3,240
cpp
C++
tc 160+/MagicBoxes.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
3
2015-05-25T06:24:37.000Z
2016-09-10T07:58:00.000Z
tc 160+/MagicBoxes.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
null
null
null
tc 160+/MagicBoxes.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
5
2015-05-25T06:24:40.000Z
2021-08-19T19:22:29.000Z
#include <algorithm> #include <cassert> #include <cstdio> #include <iostream> #include <sstream> #include <string> #include <vector> #include <cstring> using namespace std; /* NE RADI */ bool canMake[31][31][1<<15]; bool done[31][31][1<<15]; bool go(int x, int y, int mask) { assert(x>=0 && y>=0); if (mask == 0) return true; if (x > y) swap(x, y); if (done[x][y][mask]) return canMake[x][y][mask]; done[x][y][mask] = true; for (int i=15; i>0; --i) if (mask & (1<<(i-1))) { if (i > x) return (canMake[x][y][mask] = false); int left = (mask ^ (1<<(i-1))); if (left == 0) return canMake[x][y][mask] = true; for (int m1=0; m1<left; m1=(((~left | m1)+1)&left)) { int m2 = left^m1; assert((m1|m2) == left); assert((m1&m2) == 0); if (go(x-i, y, m1) && go(i, y-i, m2) || go(x-i, i, m1) && go(x, y-i, m2)) return (canMake[x][y][mask] = true); } if (go(x-i, y, left) || go(x-i, i, left)) return (canMake[x][y][mask] = true); break; } for (int i=1; i<16; ++i) if (mask & (1<<(i-1))) { int left = (mask ^ (1<<(i-1))); if (left == 0) return canMake[x][y][mask] = true; for (int m1=0; m1<left; m1=(((~left | m1)+1)&left)) { int m2 = left^m1; assert((m1|m2) == left); assert((m1&m2) == 0); if (go(x-i, y, m1) && go(i, y-i, m2) || go(x-i, i, m1) && go(x, y-i, m2)) return (canMake[x][y][mask] = true); } if (go(x-i, y, left) || go(x-i, i, left)) return (canMake[x][y][mask] = true); break; } return (canMake[x][y][mask] = false); } class MagicBoxes { public: int biggest(int x, int y) { memset(done, 0, sizeof done); for (int i=15; i>1; --i) if (go(x, y, (1<<i)-1)) return i; return 1; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { int Arg0 = 1; int Arg1 = 1; int Arg2 = 1; verify_case(0, Arg2, biggest(Arg0, Arg1)); } void test_case_1() { int Arg0 = 2; int Arg1 = 2; int Arg2 = 1; verify_case(1, Arg2, biggest(Arg0, Arg1)); } void test_case_2() { int Arg0 = 10; int Arg1 = 10; int Arg2 = 5; verify_case(2, Arg2, biggest(Arg0, Arg1)); } void test_case_3() { int Arg0 = 26; int Arg1 = 26; int Arg2 = 11; verify_case(3, Arg2, biggest(Arg0, Arg1)); } // END CUT HERE }; // BEGIN CUT HERE int main() { MagicBoxes ___test; ___test.run_test(3); } // END CUT HERE
27.931034
309
0.517901
ibudiselic
bd226bd072be31791ea4537446d0236960feab71
421
cpp
C++
Level-1/9. Recursion on the way up/Print_Permutations.cpp
anubhvshrma18/PepCoding
1d5ebd43e768ad923bf007c8dd584e217df1f017
[ "Apache-2.0" ]
22
2021-06-02T04:25:55.000Z
2022-01-30T06:25:07.000Z
Level-1/9. Recursion on the way up/Print_Permutations.cpp
amitdubey6261/PepCoding
1d5ebd43e768ad923bf007c8dd584e217df1f017
[ "Apache-2.0" ]
2
2021-10-17T19:26:10.000Z
2022-01-14T18:18:12.000Z
Level-1/9. Recursion on the way up/Print_Permutations.cpp
amitdubey6261/PepCoding
1d5ebd43e768ad923bf007c8dd584e217df1f017
[ "Apache-2.0" ]
8
2021-07-21T09:55:15.000Z
2022-01-31T10:32:51.000Z
#include <iostream> using namespace std; void printPermutations(string str, string asf){ // write your code here if(str.length()==0){ cout << asf << endl; } for(int i=0;i<str.length();i++){ swap(str[0],str[i]); string y=""; y+=str[0]; printPermutations(str.substr(1),asf+y); } } int main(){ string str; cin>>str; printPermutations(str,""); }
18.304348
47
0.539192
anubhvshrma18
bd2bc1ea4e7c4ac7babe7112e769ae65f6f92ed4
2,308
cpp
C++
core/utils/src/TimeTracker.cpp
nicsor/BreadCrumbs
9ee5111d87d7a71b0a3910c14c4751eb3f1635ab
[ "MIT" ]
null
null
null
core/utils/src/TimeTracker.cpp
nicsor/BreadCrumbs
9ee5111d87d7a71b0a3910c14c4751eb3f1635ab
[ "MIT" ]
null
null
null
core/utils/src/TimeTracker.cpp
nicsor/BreadCrumbs
9ee5111d87d7a71b0a3910c14c4751eb3f1635ab
[ "MIT" ]
null
null
null
/** * @file TimeTracker.cpp * * @author Nicolae Natea * Contact: nicu@natea.ro */ #include <cstdint> #include <map> #include <mutex> #include <core/util/TimeTracker.hpp> namespace core { namespace util { namespace { struct TimeInfo { uint64_t times_called; ///< Keep track of number of times a particular method was called. uint64_t total_time; ///< Keep track of total execution time for a particular method. }; /** Global map to keep track of method execution */ std::map<std::string, TimeInfo> tracked_time_info; /** Synchronization mutex for updating time */ std::mutex tracked_time_mutex; } TimeTracker::TimeTracker(const std::string &id) : m_id(id) { m_start = std::chrono::steady_clock::now(); } TimeTracker::~TimeTracker() { auto durationUs = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::steady_clock::now() - m_start).count(); std::lock_guard<std::mutex> lock(tracked_time_mutex); auto item = tracked_time_info.find(m_id); if (item == tracked_time_info.end()) { tracked_time_info.insert({m_id, {1, (uint64_t)durationUs}}); } else { item->second.total_time += durationUs; ++item->second.times_called; } } void clearStatistics() { std::lock_guard<std::mutex> lock(tracked_time_mutex); tracked_time_info.clear(); } std::string getTimingStatistics() { std::string response; response.reserve(16 * 1024); for (auto &el : tracked_time_info) { auto &stats = el.second; response.append(el.first); response.append(": "); response.append(std::to_string(stats.total_time)); response.append("us, "); response.append(std::to_string(stats.times_called)); response.append(" times, "); response.append(std::to_string((double) stats.total_time / stats.times_called)); response.append("us average\n"); } return response; } } }
31.616438
137
0.557192
nicsor
bd2c0645a6e63bf2ac8123eac1c868a4125ee907
22,274
cpp
C++
src/level/lightingcalculator.cpp
alexeyden/whack
2bff3beb0afb8c5aaba996b2838d2f0b9797039c
[ "WTFPL" ]
null
null
null
src/level/lightingcalculator.cpp
alexeyden/whack
2bff3beb0afb8c5aaba996b2838d2f0b9797039c
[ "WTFPL" ]
null
null
null
src/level/lightingcalculator.cpp
alexeyden/whack
2bff3beb0afb8c5aaba996b2838d2f0b9797039c
[ "WTFPL" ]
null
null
null
#include "lightingcalculator.h" #include "entityvisualinfoextractor.h" #include "level.h" #include "util/math.h" #include "util/rect.h" void LightingCalculator::calculate() { preparePass(); calculatePass(); averagePass(); spritesPass(); } void LightingCalculator::preparePass() { for(unsigned i = 0; i < _level->sizeX(); i++) { for(unsigned j = 0; j < _level->sizeY(); j++) { auto& block = _level->block(i, j); memcpy(block.lightingTint.floor, ambientRGB, sizeof(uint32_t) * 3); memcpy(block.lightingTint.ceiling, ambientRGB, sizeof(uint32_t) * 3); memcpy(block.lightingTint.north_bot, ambientRGB, sizeof(uint32_t) * 3); memcpy(block.lightingTint.south_bot, ambientRGB, sizeof(uint32_t) * 3); memcpy(block.lightingTint.east_bot, ambientRGB, sizeof(uint32_t) * 3); memcpy(block.lightingTint.west_bot, ambientRGB, sizeof(uint32_t) * 3); memcpy(block.lightingTint.north_top, ambientRGB, sizeof(uint32_t) * 3); memcpy(block.lightingTint.south_top, ambientRGB, sizeof(uint32_t) * 3); memcpy(block.lightingTint.east_top, ambientRGB, sizeof(uint32_t) * 3); memcpy(block.lightingTint.west_top, ambientRGB, sizeof(uint32_t) * 3); } } for(VisualEntity* e : _level->entities()) { memcpy(e->lighting_tint, ambientRGB, sizeof(uint32_t) * 3); } } void LightingCalculator::calculatePass() { for(const auto& light : _level->lights()) { for(unsigned i = 0; i < _level->sizeX(); i++) { for(unsigned j = 0; j < _level->sizeY(); j++) { auto& block = _level->block(i, j); calcLight(light, block, i, j); } } } } void LightingCalculator::calcLight(const Light& light, Block& block, uint32_t x, uint32_t y) { EntityVisualInfoExtractor extr; vec3 light_p(light.x, light.y, light.z); Rect<float> rect_block(x, y, x + 1, y + 1); vec3 p = vec3(x + 0.5f, y + 0.5f, block.standHeightVisual() + 0.01f); if(hitsLight(light_p, p)) { bool has_entity = false; for(const auto& e : _level->entitiesAt(x, y)) { const auto& aabb = e->collisionAABB(); bool near_ground = fabs(e->z() - block.standHeightVisual()) < 1.0f; bool intersects = Rect<float>(aabb.x0, aabb.y0, aabb.x1, aabb.y1).intersects(rect_block); if(near_ground && intersects && extr.extract(e).type == EntityFactory::ET_DECOR) { has_entity = true; break; } } if(!has_entity) lightAdd(block.lightingTint.floor, light, (light_p - p).length()); } uint32_t (*sides_bot[4])[3] = { &block.lightingTint.north_bot, &block.lightingTint.south_bot, &block.lightingTint.west_bot, &block.lightingTint.east_bot }; uint32_t (*sides_top[4])[3] = { &block.lightingTint.north_top, &block.lightingTint.south_top, &block.lightingTint.west_top, &block.lightingTint.east_top }; vec3 points[4] = { vec3(x + 0.5f, y + 1.05f, 0), vec3(x + 0.5f, y - 0.05f, 0), vec3(x - 0.05f, y + 0.5f, 0), vec3(x + 1.05f, y + 0.5f, 0) }; for(int i = 0; i < 4; i++) { for(float j = 0.0f; j <= 20; j += 0.5f) { vec3 p = points[i]; p.z = std::min(block.standHeightVisual() * j / 20.0f, block.standHeightVisual() - 0.05f); if(hitsLight(light_p, p)) { lightAdd(*(sides_bot[i]), light, (light_p - p).length()); break; } } } if(block.notchHeight > 0) { p = vec3(x + 0.5f, y + 0.5f, block.notchHeight + block.notch - 0.05f); if(hitsLight(light_p, p)) { lightAdd(block.lightingTint.ceiling, light, (light_p - p).length()); } for(int i = 0; i < 4; i++) { for(float j = 0.0f; j <= 20.0f; j += 0.5f) { vec3 p = points[i]; p.z = std::max(std::min( block.notch + block.notchHeight + (block.height - (block.notch + block.notchHeight))*j / 20.0f, block.height - 0.5f ), block.notch + block.notchHeight + 0.05f); if(hitsLight(light_p, p)) { lightAdd(*(sides_top[i]), light, (light_p - p).length()); break; } } } } } bool LightingCalculator::hitsLight(const vec3& light, const vec3& point) { // EntityVisualInfoExtractor extr; vec3 ray = (light - point).normalize(); _caster.stop_target = light; const auto& result = _caster.cast(point, ray); if(result.block != nullptr) return false; /* if(result.entity != nullptr && extr.extract(result.entity).type == EntityFactory::ET_DECOR) { float t; return !rayAABBIntersect3D(point.x, point.y, point.z, ray.x, ray.y, ray.z, result.entity->collisionAABB(), &t); } */ return true; } void LightingCalculator::lightAdd(uint32_t (&color)[3], const Light& light, float distance) { if(light.type == LT_SUN) { color[0] = std::min<uint32_t>(uint32_t(color[0]) + light.red, 0xff); color[1] = std::min<uint32_t>(uint32_t(color[1]) + light.green, 0xff); color[2] = std::min<uint32_t>(uint32_t(color[2]) + light.blue, 0xff); } else { float k = std::max<float>(-distance * 1.0f/light.intensity + 1.0f, 0.0f); if(k > 0) { color[0] = std::min<uint32_t>(uint32_t(color[0] + light.red * k), 0xffu); color[1] = std::min<uint32_t>(uint32_t(color[1] + light.green * k), 0xffu); color[2] = std::min<uint32_t>(uint32_t(color[2] + light.blue * k), 0xffu); } } } void LightingCalculator::averagePass() { averageFloor(); //averageFloor(); averageNorthSouth(); averageEastWest(); } void LightingCalculator::averageFloor() { struct ColorU32 { uint32_t red; uint32_t green; uint32_t blue; }; ColorU32* temp = new ColorU32[_level->sizeX() * _level->sizeY()]; for(unsigned i = 0; i < _level->sizeX(); i++) { for(unsigned j = 0; j < _level->sizeY(); j++) { auto& block = _level->block(i, j); uint32_t tint[3]; tint[0] = block.lightingTint.floor[0]; tint[1] = block.lightingTint.floor[1]; tint[2] = block.lightingTint.floor[2]; unsigned average_n = 1; if(i > 0 && _level->block(i - 1, j).standHeight() == block.standHeight()) { tint[0] += _level->block(i - 1, j).lightingTint.floor[0]; tint[1] += _level->block(i - 1, j).lightingTint.floor[1]; tint[2] += _level->block(i - 1, j).lightingTint.floor[2]; average_n += 1; } if(j > 0 && _level->block(i, j-1).standHeight() == block.standHeight()) { tint[0] += _level->block(i, j-1).lightingTint.floor[0]; tint[1] += _level->block(i, j-1).lightingTint.floor[1]; tint[2] += _level->block(i, j-1).lightingTint.floor[2]; average_n += 1; } if(i < _level->sizeX()-1 && _level->block(i + 1, j).standHeight() == block.standHeight()) { tint[0] += _level->block(i + 1, j).lightingTint.floor[0]; tint[1] += _level->block(i + 1, j).lightingTint.floor[1]; tint[2] += _level->block(i + 1, j).lightingTint.floor[2]; average_n += 1; } if(j < _level->sizeY()-1 && _level->block(i, j+1).standHeight() == block.standHeight()) { tint[0] += _level->block(i, j+1).lightingTint.floor[0]; tint[1] += _level->block(i, j+1).lightingTint.floor[1]; tint[2] += _level->block(i, j+1).lightingTint.floor[2]; average_n += 1; } if(i > 0 && j > 0 && _level->block(i - 1, j-1).standHeight() == block.standHeight()) { tint[0] += _level->block(i - 1, j-1).lightingTint.floor[0]; tint[1] += _level->block(i - 1, j-1).lightingTint.floor[1]; tint[2] += _level->block(i - 1, j-1).lightingTint.floor[2]; average_n += 1; } if(i > 0 && j < _level->sizeY()-1 && _level->block(i - 1, j+1).standHeight() == block.standHeight()) { tint[0] += _level->block(i - 1, j+1).lightingTint.floor[0]; tint[1] += _level->block(i - 1, j+1).lightingTint.floor[1]; tint[2] += _level->block(i - 1, j+1).lightingTint.floor[2]; average_n += 1; } if(i < _level->sizeX()-1 && j > 0 && _level->block(i + 1, j-1).standHeight() == block.standHeight()) { tint[0] += _level->block(i + 1, j-1).lightingTint.floor[0]; tint[1] += _level->block(i + 1, j-1).lightingTint.floor[1]; tint[2] += _level->block(i + 1, j-1).lightingTint.floor[2]; average_n += 1; } if(i < _level->sizeX()-1 && j < _level->sizeY()-1 && _level->block(i + 1, j+1).standHeight() == block.standHeight()) { tint[0] += _level->block(i + 1, j+1).lightingTint.floor[0]; tint[1] += _level->block(i + 1, j+1).lightingTint.floor[1]; tint[2] += _level->block(i + 1, j+1).lightingTint.floor[2]; average_n += 1; } tint[0] = tint[0]/average_n; tint[1] = tint[1]/average_n; tint[2] = tint[2]/average_n; temp[i + j * _level->sizeX()] = ColorU32 { uint8_t(tint[0]), uint8_t(tint[1]), uint8_t(tint[2]) }; } } for(uint32_t i = 0; i < _level->sizeX(); i++) { for(uint32_t j = 0; j < _level->sizeY(); j++) { Block& block = _level->block(i, j); const ColorU32& color = temp[i + _level->sizeX() * j]; block.lightingTint.floor[0] = color.red; block.lightingTint.floor[1] = color.green; block.lightingTint.floor[2] = color.blue; } } delete [] temp; } void LightingCalculator::averageEastWest() { for(unsigned i = 0; i < _level->sizeX(); i++) { for(unsigned j = 0; j < _level->sizeY(); j++) { auto& block = _level->block(i, j); uint32_t tint_north_bot[3]; uint32_t tint_south_bot[3]; uint32_t tint_north_top[3]; uint32_t tint_south_top[3]; tint_north_bot[0] = block.lightingTint.north_bot[0]; tint_north_bot[1] = block.lightingTint.north_bot[1]; tint_north_bot[2] = block.lightingTint.north_bot[2]; tint_south_bot[0] = block.lightingTint.south_bot[0]; tint_south_bot[1] = block.lightingTint.south_bot[1]; tint_south_bot[2] = block.lightingTint.south_bot[2]; tint_north_top[0] = block.lightingTint.north_top[0]; tint_north_top[1] = block.lightingTint.north_top[1]; tint_north_top[2] = block.lightingTint.north_top[2]; tint_south_top[0] = block.lightingTint.south_top[0]; tint_south_top[1] = block.lightingTint.south_top[1]; tint_south_top[2] = block.lightingTint.south_top[2]; uint8_t average_n[4] = {1, 1, 1, 1}; const float height_diff = 3.0f; if(i > 0 && isBlockBottomVisible(i - 1, j, DIR_N) && fabs(_level->block(i - 1, j).height - block.height) < height_diff) { tint_north_bot[0] += _level->block(i - 1, j).lightingTint.north_bot[0]; tint_north_bot[1] += _level->block(i - 1, j).lightingTint.north_bot[1]; tint_north_bot[2] += _level->block(i - 1, j).lightingTint.north_bot[2]; average_n[0] += 1; } if(i > 0 && isBlockBottomVisible(i - 1, j, DIR_S) && fabs(_level->block(i - 1, j).height - block.height) < height_diff) { tint_south_bot[0] += _level->block(i - 1, j).lightingTint.south_bot[0]; tint_south_bot[1] += _level->block(i - 1, j).lightingTint.south_bot[1]; tint_south_bot[2] += _level->block(i - 1, j).lightingTint.south_bot[2]; average_n[1] += 1; } if(i < _level->sizeX()-1 && isBlockBottomVisible(i + 1, j, DIR_N) && fabs(_level->block(i + 1, j).height - block.height) < height_diff) { tint_north_bot[0] += _level->block(i + 1, j).lightingTint.north_bot[0]; tint_north_bot[1] += _level->block(i + 1, j).lightingTint.north_bot[1]; tint_north_bot[2] += _level->block(i + 1, j).lightingTint.north_bot[2]; average_n[0] += 1; } if(i < _level->sizeX()-1 && isBlockBottomVisible(i + 1, j, DIR_S) && fabs(_level->block(i + 1, j).height - block.height) < height_diff) { tint_south_bot[0] += _level->block(i + 1, j).lightingTint.south_bot[0]; tint_south_bot[1] += _level->block(i + 1, j).lightingTint.south_bot[1]; tint_south_bot[2] += _level->block(i + 1, j).lightingTint.south_bot[2]; average_n[1] += 1; } if(i > 0 && isBlockTopVisible(i - 1, j, DIR_N) && fabs(_level->block(i - 1, j).height - block.height) < height_diff) { const auto& b = _level->block(i - 1, j); const auto color_north = b.hasTop() ? b.lightingTint.north_top : b.lightingTint.north_bot; tint_north_top[0] += color_north[0]; tint_north_top[1] += color_north[1]; tint_north_top[2] += color_north[2]; average_n[2] += 1; } if(i > 0 && isBlockTopVisible(i - 1, j, DIR_S) && fabs(_level->block(i - 1, j).height - block.height) < height_diff) { const auto& b = _level->block(i - 1, j); const auto color_south = b.hasTop() ? b.lightingTint.south_top : b.lightingTint.south_bot; tint_south_top[0] += color_south[0]; tint_south_top[1] += color_south[1]; tint_south_top[2] += color_south[2]; average_n[3] += 1; } if(i < _level->sizeX()-1 && isBlockTopVisible(i + 1, j, DIR_N) && fabs(_level->block(i + 1, j).height - block.height) < height_diff) { const auto& b = _level->block(i + 1, j); const auto color_north = b.hasTop() ? b.lightingTint.north_top : b.lightingTint.north_bot; tint_north_top[0] += color_north[0]; tint_north_top[1] += color_north[1]; tint_north_top[2] += color_north[2]; average_n[2] += 1; } if(i < _level->sizeX()-1 && isBlockTopVisible(i + 1, j, DIR_S) && fabs(_level->block(i + 1, j).height - block.height) < height_diff) { const auto& b = _level->block(i + 1, j); const auto color_south = b.hasTop() ? b.lightingTint.south_top : b.lightingTint.south_bot; tint_south_top[0] += color_south[0]; tint_south_top[1] += color_south[1]; tint_south_top[2] += color_south[2]; average_n[3] += 1; } tint_north_bot[0] = tint_north_bot[0]/average_n[0]; tint_north_bot[1] = tint_north_bot[1]/average_n[0]; tint_north_bot[2] = tint_north_bot[2]/average_n[0]; tint_south_bot[0] = tint_south_bot[0]/average_n[1]; tint_south_bot[1] = tint_south_bot[1]/average_n[1]; tint_south_bot[2] = tint_south_bot[2]/average_n[1]; tint_north_top[0] = tint_north_top[0]/average_n[2]; tint_north_top[1] = tint_north_top[1]/average_n[2]; tint_north_top[2] = tint_north_top[2]/average_n[2]; tint_south_top[0] = tint_south_top[0]/average_n[3]; tint_south_top[1] = tint_south_top[1]/average_n[3]; tint_south_top[2] = tint_south_top[2]/average_n[3]; block.lightingTint.north_bot[0] = tint_north_bot[0]; block.lightingTint.north_bot[1] = tint_north_bot[1]; block.lightingTint.north_bot[2] = tint_north_bot[2]; block.lightingTint.south_bot[0] = tint_south_bot[0]; block.lightingTint.south_bot[1] = tint_south_bot[1]; block.lightingTint.south_bot[2] = tint_south_bot[2]; block.lightingTint.north_top[0] = tint_north_top[0]; block.lightingTint.north_top[1] = tint_north_top[1]; block.lightingTint.north_top[2] = tint_north_top[2]; block.lightingTint.south_top[0] = tint_south_top[0]; block.lightingTint.south_top[1] = tint_south_top[1]; block.lightingTint.south_top[2] = tint_south_top[2]; } } } bool LightingCalculator::isBlockBottomVisible(uint32_t x, uint32_t y, Dir dir) const { const Block& block = _level->block(x, y); bool vis_x0 = x > 0 && _level->block(x - 1, y).standHeightVisual() < block.standHeightVisual(); bool vis_x1 = x < _level->sizeX() - 1 && _level->block(x + 1, y).standHeightVisual() < block.standHeightVisual(); bool vis_y0 = y > 0 && _level->block(x, y - 1).standHeightVisual() < block.standHeightVisual(); bool vis_y1 = y < _level->sizeY() - 1 && _level->block(x, y + 1).standHeightVisual() < block.standHeightVisual(); return (dir == DIR_W && vis_x0) || (dir == DIR_E && vis_x1) || (dir == DIR_S && vis_y0) || (dir == DIR_N && vis_y1); } bool LightingCalculator::isBlockTopVisible(uint32_t x, uint32_t y, Dir dir) const { const Block& block = _level->block(x, y); if(!block.hasTop()) return isBlockBottomVisible(x, y, dir); auto side_visible = [&block](const Block& b) { if(!b.hasTop() && b.height > block.height) return false; if(b.hasTop() && b.notch + b.notchHeight < block.notch + block.notchHeight && b.height > block.height) return false; if(b.hasTop() && b.notch > block.height) return false; return true; }; bool vis_x0 = x > 0 && side_visible(_level->block(x - 1, y)); bool vis_x1 = x < _level->sizeX() - 1 && side_visible(_level->block(x + 1, y)); bool vis_y0 = y > 0 && side_visible(_level->block(x, y - 1)); bool vis_y1 = y < _level->sizeY() - 1 && side_visible(_level->block(x, y + 1)); return (dir == DIR_W && vis_x0) || (dir == DIR_E && vis_x1) || (dir == DIR_S && vis_y0) || (dir == DIR_N && vis_y1); } void LightingCalculator::averageNorthSouth() { for(size_t i = 0; i < _level->sizeX(); i++) { for(size_t j = 0; j < _level->sizeY(); j++) { auto& block = _level->block(i, j); uint32_t tint_west_bot[3]; uint32_t tint_east_bot[3]; uint32_t tint_west_top[3]; uint32_t tint_east_top[3]; tint_west_bot[0] = block.lightingTint.west_bot[0]; tint_west_bot[1] = block.lightingTint.west_bot[1]; tint_west_bot[2] = block.lightingTint.west_bot[2]; tint_east_bot[0] = block.lightingTint.east_bot[0]; tint_east_bot[1] = block.lightingTint.east_bot[1]; tint_east_bot[2] = block.lightingTint.east_bot[2]; tint_west_top[0] = block.lightingTint.west_top[0]; tint_west_top[1] = block.lightingTint.west_top[1]; tint_west_top[2] = block.lightingTint.west_top[2]; tint_east_top[0] = block.lightingTint.east_top[0]; tint_east_top[1] = block.lightingTint.east_top[1]; tint_east_top[2] = block.lightingTint.east_top[2]; uint8_t average_n[4] = {1, 1, 1, 1}; const float height_diff = 3.0f; if(j > 0 && isBlockBottomVisible(i, j - 1, DIR_W) && fabs(_level->block(i, j - 1).height - block.height) < height_diff) { tint_west_bot[0] += _level->block(i, j - 1).lightingTint.west_bot[0]; tint_west_bot[1] += _level->block(i, j - 1).lightingTint.west_bot[1]; tint_west_bot[2] += _level->block(i, j - 1).lightingTint.west_bot[2]; average_n[0] += 1; } if(j > 0 && isBlockBottomVisible(i, j - 1, DIR_E) && fabs(_level->block(i, j - 1).height - block.height) < height_diff) { tint_east_bot[0] += _level->block(i, j - 1).lightingTint.east_bot[0]; tint_east_bot[1] += _level->block(i, j - 1).lightingTint.east_bot[1]; tint_east_bot[2] += _level->block(i, j - 1).lightingTint.east_bot[2]; average_n[1] += 1; } if(j < _level->sizeX()-1 && isBlockBottomVisible(i, j + 1, DIR_W) && fabs(_level->block(i, j + 1).height - block.height) < height_diff) { tint_west_bot[0] += _level->block(i, j + 1).lightingTint.west_bot[0]; tint_west_bot[1] += _level->block(i, j + 1).lightingTint.west_bot[1]; tint_west_bot[2] += _level->block(i, j + 1).lightingTint.west_bot[2]; average_n[0] += 1; } if(j < _level->sizeX()-1 && isBlockBottomVisible(i, j + 1, DIR_E) && fabs(_level->block(i, j + 1).height - block.height) < height_diff) { tint_east_bot[0] += _level->block(i, j + 1).lightingTint.east_bot[0]; tint_east_bot[1] += _level->block(i, j + 1).lightingTint.east_bot[1]; tint_east_bot[2] += _level->block(i, j + 1).lightingTint.east_bot[2]; average_n[1] += 1; } if(j > 0 && isBlockTopVisible(i, j - 1, DIR_W) && fabs(_level->block(i, j - 1).height - block.height) < height_diff) { const auto& b = _level->block(i, j - 1); const auto color_west = b.hasTop() ? b.lightingTint.west_top : b.lightingTint.west_bot; tint_west_top[0] += color_west[0]; tint_west_top[1] += color_west[1]; tint_west_top[2] += color_west[2]; average_n[2] += 1; } if(j > 0 && isBlockTopVisible(i, j - 1, DIR_E) && fabs(_level->block(i, j - 1).height - block.height) < height_diff) { const auto& b = _level->block(i, j - 1); const auto color_east = b.hasTop() ? b.lightingTint.east_top : b.lightingTint.east_bot; tint_east_top[0] += color_east[0]; tint_east_top[1] += color_east[1]; tint_east_top[2] += color_east[2]; average_n[3] += 1; } if(j < _level->sizeX()-1 && isBlockTopVisible(i, j + 1, DIR_W) && fabs(_level->block(i, j + 1).height - block.height) < height_diff) { const auto& b = _level->block(i, j + 1); const auto color_west = b.hasTop() ? b.lightingTint.west_top : b.lightingTint.west_bot; tint_west_top[0] += color_west[0]; tint_west_top[1] += color_west[1]; tint_west_top[2] += color_west[2]; average_n[2] += 1; } if(j < _level->sizeX()-1 && isBlockTopVisible(i, j + 1, DIR_E) && fabs(_level->block(i, j + 1).height - block.height) < height_diff) { const auto& b = _level->block(i, j + 1); const auto color_east = b.hasTop() ? b.lightingTint.east_top : b.lightingTint.east_bot; tint_east_top[0] += color_east[0]; tint_east_top[1] += color_east[1]; tint_east_top[2] += color_east[2]; average_n[3] += 1; } tint_west_bot[0] = tint_west_bot[0]/average_n[0]; tint_west_bot[1] = tint_west_bot[1]/average_n[0]; tint_west_bot[2] = tint_west_bot[2]/average_n[0]; tint_east_bot[0] = tint_east_bot[0]/average_n[1]; tint_east_bot[1] = tint_east_bot[1]/average_n[1]; tint_east_bot[2] = tint_east_bot[2]/average_n[1]; tint_west_top[0] = tint_west_top[0]/average_n[2]; tint_west_top[1] = tint_west_top[1]/average_n[2]; tint_west_top[2] = tint_west_top[2]/average_n[2]; tint_east_top[0] = tint_east_top[0]/average_n[3]; tint_east_top[1] = tint_east_top[1]/average_n[3]; tint_east_top[2] = tint_east_top[2]/average_n[3]; block.lightingTint.west_bot[0] = tint_west_bot[0]; block.lightingTint.west_bot[1] = tint_west_bot[1]; block.lightingTint.west_bot[2] = tint_west_bot[2]; block.lightingTint.east_bot[0] = tint_east_bot[0]; block.lightingTint.east_bot[1] = tint_east_bot[1]; block.lightingTint.east_bot[2] = tint_east_bot[2]; block.lightingTint.west_top[0] = tint_west_top[0]; block.lightingTint.west_top[1] = tint_west_top[1]; block.lightingTint.west_top[2] = tint_west_top[2]; block.lightingTint.east_top[0] = tint_east_top[0]; block.lightingTint.east_top[1] = tint_east_top[1]; block.lightingTint.east_top[2] = tint_east_top[2]; } } } void LightingCalculator::spritesPass() { for(const auto& light : _level->lights()) { for(VisualEntity* e : _level->entities()) { if(e->lighting_static) { auto lp = vec3(light.x, light.y, light.z); auto ep = vec3(e->x(), e->y(), e->z() + e->visualHeight() / 2.0f); if(hitsLight(lp, ep)) { lightAdd(e->lighting_tint, light, (lp - ep).length()); } } } } }
35.355556
121
0.633923
alexeyden
bd2f24769b4675ea5eb988c7616f917e027b2783
8,612
hpp
C++
cc/include/bounding_eccentricities.hpp
parthmittal/graph-algorithms
10ebeead1b3fc1ad52f9f69a5bf42d90c5604508
[ "MIT" ]
null
null
null
cc/include/bounding_eccentricities.hpp
parthmittal/graph-algorithms
10ebeead1b3fc1ad52f9f69a5bf42d90c5604508
[ "MIT" ]
null
null
null
cc/include/bounding_eccentricities.hpp
parthmittal/graph-algorithms
10ebeead1b3fc1ad52f9f69a5bf42d90c5604508
[ "MIT" ]
null
null
null
#include <algorithm> #include <iostream> #include <iterator> #include <queue> #include <vector> #include <graph.hpp> #include <optparser.hpp> #ifndef __BOUNDING_ECCENTRICITY_HPP__ #define __BOUNDING_ECCENTRICITY_HPP__ namespace our { using namespace std; /* * An iterative bfs implementation that returns the distance vector from the * source. * Here graph_type can take up naive graph type and CRS type. */ template <typename graph_type> vector<int> ECCENTRICITY(const graph_type &G, int source, int N) { const int inf = 1e9; std::vector<int> dist(N, inf); std::vector<int> visited(N, false); dist[source] = 0; visited[source] = true; std::queue<int> q; // cerr << "Starting BFS from node : " << source << endl; q.push(source); while (!q.empty()) { int u = q.front(); q.pop(); for (auto &v : G[u]) { if (!visited[v]) { visited[v] = true; dist[v] = dist[u] + 1; q.push(v); } } } for (int i = 0; i < N; i++) { if (dist[i] >= inf) { dist[i] = -1; } } return dist; } /* * Function to prune the degree 1 nodes and create links to nodes that have * similar eccentricity * Returns the vector pruned where pruned[i] takes the following values: * -1 : if this node as well as its neighbours are not pruned * -2 : if the neighbours of this node are pruned * >= 0 : index of the node which is similar to this node */ template <typename graph_type> vector<int> pruning(const graph_type &G, int N, int &count) { std::vector<int> pruned(N, -1); count = 0; for (int i = 0; i < N; i++) { if (!G.in_LWCC(i)) continue; int degree = G[i].size(); int prunee = -1; for (int j = 0; j < degree; j++) { auto it = G[i].begin(); std::advance(it, j); int v = *it; // if degree of v is 1 and its neighbours haven't been pruned. if (G[v].size() == 1 && pruned[v] == -1) { if (prunee == -1) { prunee = v; // prune all but this one } else { pruned[v] = v; count++; pruned[prunee] = -2; // when the neighbours of prunee are pruned } } } } std::cerr << std::endl << "Number of nodes pruned: " << count << std::endl << std::endl; return pruned; } template <typename graph_type> int select_from(int STRATEGY, const vector<int> &is_candidate, const graph_type &G, const vector<int> &lower, const vector<int> &upper, const vector<int> &d, bool &high, int N) { int to_return; if (STRATEGY == 1) // select the node with largest upper - lower difference, // break ties with degree { int max_range = 0; for (int i = 0; i < N; i++) { if (is_candidate[i]) { int diff = upper[i] - lower[i]; if (diff > max_range) { to_return = i; max_range = diff; } else if (diff == max_range && G[i].size() > G[to_return].size()) { to_return = i; } } } } else if (STRATEGY == 2) // select node alternatively between max lower // bound and min upperbound, break ties with degree { int min_lower_bound = N, max_upper_bound = 0; for (int i = 0; i < N; i++) { if (is_candidate[i]) { min_lower_bound = std::min(min_lower_bound, lower[i]); max_upper_bound = std::max(max_upper_bound, upper[i]); } } // cerr << "MIN ECCENTRICITY LOWER BOUND " << min_lower_bound << endl; // cerr << "MAX ECCENTRICITY UPPER BOUND " << max_upper_bound << endl; int min_lower_node = -1, max_upper_node = -1; for (int i = 0; i < N; i++) { if (is_candidate[i]) { if (lower[i] == min_lower_bound && (min_lower_node == -1 || G[i].size() > G[min_lower_node].size())) { // cerr << endl << "Updating min_lower_node to " << i << // endl; min_lower_node = i; } // cerr << upper[i] << " "; if (upper[i] == max_upper_bound && (max_upper_node == -1 || G[i].size() > G[max_upper_node].size())) { // cerr << "Updating max_upper_node to " << i << endl; max_upper_node = i; } } } if (high) { high = false; to_return = min_lower_node; } else { high = true; to_return = max_upper_node; } } else if (STRATEGY == 3) // select node with the farthest distance from the // current node, break ties with degree { to_return = std::distance(d.begin(), std::max_element(d.begin(), d.end())); } // cerr << "NEXT NODE FOR BFS " << to_return << endl; return to_return; } template <typename graph_type> vector<int> bounding_eccentricities(const graph_type &G, int N, int STRATEGY, OptParser &parser) { int PRUNE = parser.checkIncluded("to_prune"); int prune_count = 0; std::vector<int> pruned; if (PRUNE) { pruned = pruning(G, N, prune_count); } int candidates = G.size_LWCC() - prune_count, current = -1; std::vector<int> is_candidate(N, true); std::vector<int> eccentricity(N, 0), ecc_lower(N, 0), ecc_upper(N, N); std::vector<int> d; bool high = true; int number_of_iterations = 0; while (candidates > 0) { // cout << "Number of candidates left " << candidates << endl; if (current == -1) // choose the node with max degree in the first iteration { current = 0; for (int i = 0; i < N; i++) { if (pruned[i] >= 0 || !G.in_LWCC(i)) { is_candidate[i] = false; ecc_lower[i] = N + 1; ecc_upper[i] = -1; continue; } if (G[i].size() > G[current].size()) { current = i; } } } else { current = select_from(STRATEGY, is_candidate, G, ecc_lower, ecc_upper, d, high, N); } // run a bfs fron the selected node d = ECCENTRICITY(G, current, N); // calculate eccentricity of current node eccentricity[current] = *std::max_element(d.begin(), d.end()); is_candidate[current] = false; candidates--; // update lower and upper bounds to connected nodes for (int i = 0; i < N; i++) { if (pruned[i] >= 0 || !G.in_LWCC(i) || d[i] == -1) continue; ecc_lower[i] = std::max( ecc_lower[i], std::max(eccentricity[current] - d[i], d[i])); ecc_upper[i] = std::min(ecc_upper[i], eccentricity[current] + d[i]); } // update candidate set for (int i = 0; i < N; i++) { if (!is_candidate[i] || !G.in_LWCC(i) || pruned[i] >= 0) continue; if (ecc_lower[i] == ecc_upper[i]) { is_candidate[i] = false; eccentricity[i] = ecc_lower[i]; ecc_lower[i] = N + 1; ecc_upper[i] = -1; candidates--; } } number_of_iterations++; #ifdef DEBUG std::cerr << "---------------------------------------------------------" << std::endl; std::cerr << "Performed BFS on " << current << std::endl; std::cerr << "ECCENTRICITY = " << eccentricity[current] << std::endl; std::cerr << "---------------------------------------------------------" << std::endl; #endif } if (PRUNE) { for (int i = 0; i < N; i++) { if (!G.in_LWCC(i)) continue; if (pruned[i] >= 0) eccentricity[i] = eccentricity[pruned[i]]; } } std::cerr << "Number of iterations performed : " << number_of_iterations << endl; return eccentricity; } } // namespace our #endif
32.996169
80
0.474686
parthmittal
bd31b969c8a8f046cb9da623d66a153f98ef167b
3,385
cpp
C++
test/test_kernelarg.cpp
rise-lang/yacx
da81fe8f814151b1c2024617f0bc9891f210cd84
[ "MIT" ]
5
2019-12-16T15:32:05.000Z
2021-05-21T18:36:37.000Z
test/test_kernelarg.cpp
rise-lang/yacx
da81fe8f814151b1c2024617f0bc9891f210cd84
[ "MIT" ]
98
2019-12-07T15:28:18.000Z
2021-03-02T14:20:48.000Z
test/test_kernelarg.cpp
rise-lang/yacx
da81fe8f814151b1c2024617f0bc9891f210cd84
[ "MIT" ]
6
2019-12-08T13:20:57.000Z
2021-05-16T11:21:14.000Z
#include "test_compare.hpp" #include "yacx/Headers.hpp" #include "yacx/KernelArgs.hpp" #include "yacx/Source.hpp" #include <catch2/catch.hpp> #include <iostream> using yacx::KernelArg, yacx::Source, yacx::Headers; CATCH_REGISTER_ENUM(compare, compare::CORRECT, compare::CHECK_COMPARE_WRONG, compare::A_COMPARE_WRONG, compare::X_COMPARE_WRONG, compare::Y_COMPARE_WRONG, compare::OUT_COMPARE_WRONG) TEST_CASE("KernelArg can be constructed", "[yacx::KernelArg]") { int a{5}; compare check{CORRECT}; int *hX = new int[5]{1, 2, 3, 4, 5}; int *hY = new int[5]{6, 7, 8, 9, 10}; int *hOut = new int[5]{11, 12, 13, 14, 15}; size_t bufferSize = 5 * sizeof(int); std::vector<KernelArg> args; args.emplace_back(KernelArg(&a)); args.emplace_back(KernelArg{hX, bufferSize}); args.emplace_back(KernelArg{hY, bufferSize}); args.emplace_back(KernelArg{hOut, bufferSize, true}); args.emplace_back(KernelArg{&check, sizeof(compare), true}); SECTION("KernelArg can be downloaded") { REQUIRE(a == 5); REQUIRE(hX[0] == 1); REQUIRE(hY[0] == 6); REQUIRE(hOut[0] == 11); Source source{"#include \"test_compare.hpp\"\n" "extern \"C\"\n" "__global__ void download(int a, int *x, int *y, int " "*out, compare *check) {\n" " a = 6;\n" " x[0] = 2;\n" " y[0] = 7;\n" " out[0] = 12;\n" "}", Headers{"test_compare.hpp"}}; dim3 grid(1); dim3 block(1); source.program("download").compile().configure(grid, block).launch(args); REQUIRE(a == 5); REQUIRE(hX[0] == 1); REQUIRE(hY[0] == 6); REQUIRE(hOut[0] == 12); } SECTION("KernelArg can be uploaded") { REQUIRE(hX[0] == 1); REQUIRE(hY[0] == 6); REQUIRE(hOut[0] == 11); Source source{"#include \"test_compare.hpp\"\n" "extern \"C\"\n" "__global__ void compare(int a, int *x, int *y, int " "*out, compare *check) {\n" " int dA = 5.1;\n" " int dX[5] = {1, 2, 3, 4, 5};\n" " int dY[5] = {6, 7, 8, 9, 10};\n" " int dOut[5] = {11, 12, 13, 14, 15};\n" " if(*check != CORRECT) {\n" " *check = CHECK_COMPARE_WRONG;\n" " } else if (dA != a) {\n" " *check = A_COMPARE_WRONG;\n" " } else {\n" " for (int i = 0; i < 5; ++i) {\n" " if(dX[i] != x[i]) {\n" " *check = X_COMPARE_WRONG;\n" " break;\n" " } else if(dY[i] != y[i]) {\n" " *check = Y_COMPARE_WRONG;\n" " break;\n" " } else if(dOut[i] != out[i]) {\n" " *check = OUT_COMPARE_WRONG;\n" " break;\n" " }\n" " }\n" " }\n" "}", Headers{"test_compare.hpp"}}; dim3 grid(1); dim3 block(1); source.program("compare").compile().configure(grid, block).launch(args); REQUIRE(check == CORRECT); } delete[] hX; delete[] hY; delete[] hOut; }
34.540816
77
0.467061
rise-lang
bd320c78da022b4ae14dfbb6afff43b64024c678
6,369
hxx
C++
ds/adsi/ldap/globals.hxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
ds/adsi/ldap/globals.hxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
ds/adsi/ldap/globals.hxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//--------------------------------------------------------------------------- // // Microsoft Windows // Copyright (C) Microsoft Corporation, 1992 - 1995 // // File: globals.hxx // // Contents: // // History: //---------------------------------------------------------------------------- extern TCHAR *szProviderName; extern TCHAR *szLDAPNamespaceName; extern TCHAR *szGCNamespaceName; // // List of interface properties for Generic Objects // extern INTF_PROP_DATA IntfPropsGeneric[]; extern INTF_PROP_DATA IntfPropsSchema[]; extern INTF_PROP_DATA IntfPropsConnection[]; extern INTF_PROP_DATA IntfPropsCursor[]; extern INTF_PROP_DATA IntfPropsQuery[]; HMODULE LoadLibraryHelper( LPTSTR pszFileName ); // // Helper routine to split relative url to class and RDN. // HRESULT UrlToClassAndDn( IN IUmiURL *pUrl, OUT LPWSTR *ppszDN, OUT LPWSTR *ppszClass ); // // Helper routine to conver the url to the ldap path. // HRESULT UrlToLDAPPath( IN IUmiURL *pURL, OUT LPWSTR *ppszLDAPPath, OPTIONAL OUT LPWSTR *ppszDn = NULL, OPTIONAL OUT LPWSTR *ppszServer = NULL ); // // Helper routine to convert ADsPath to url text in umi format. // HRESULT ADsPathToUmiURL( IN LPWSTR ADsPath, OUT LPWSTR *ppszUrlTxt ); // // Converts the given hr to the umi hr. // HRESULT MapHrToUmiError( IN HRESULT hr ); // // These routine are exported by the router (activeds.dll) and convert // binary format security descriptors to IADsSecurityDescriptor and // IADsSecurityDescriptor to binary format. // #ifdef __cplusplus extern "C" #else extern #endif HRESULT ConvertSecDescriptorToVariant( LPWSTR pszServerName, CCredentials& Credentials, PSECURITY_DESCRIPTOR pSecurityDescriptor, VARIANT * pVarSec, BOOL fNTDS ); #ifdef __cplusplus extern "C" #else extern #endif HRESULT ConvertSecurityDescriptorToSecDes( LPWSTR pszServerName, CCredentials& Credentials, IADsSecurityDescriptor FAR * pSecDes, PSECURITY_DESCRIPTOR * ppSecurityDescriptor, PDWORD pdwSDLength, BOOL fNTDSType ); #ifdef __cplusplus extern "C" #else extern #endif HRESULT ConvertTrusteeToSid( LPWSTR pszServerName, CCredentials& Credentials, BSTR bstrTrustee, PSID * ppSid, PDWORD pdwSidSize, BOOL fNTDSType ); // // The remaining definitions are support routines to enable // dynamic loading of libraries. // extern CRITICAL_SECTION g_csLoadLibsCritSect; #define ENTER_LOADLIBS_CRITSECT() EnterCriticalSection(&g_csLoadLibsCritSect) #define LEAVE_LOADLIBS_CRITSECT() LeaveCriticalSection(&g_csLoadLibsCritSect) extern HANDLE g_hDllSecur32; extern HANDLE g_hDllNtdsapi; #define DSUNQUOTERDN_API "DsUnquoteRdnValueW" #define DSCRACK_NAMES_API "DsCrackNamesW" #define DSBIND_API "DsBindW" #define DSUNBIND_API "DsUnBindW" #define DSMAKEPASSWD_CRED_API "DsMakePasswordCredentialsW" #define DSFREEPASSWD_CRED_API "DsFreePasswordCredentials" #define DSBINDWITHCRED_API "DsBindWithCredW" #define DSFREENAME_RESULT_API "DsFreeNameResultW" #define QUERYCONTEXT_ATTR_API "QueryContextAttributesW" // // DsUnquoteRdnValue definition // typedef DWORD (*PF_DsUnquoteRdnValueW) ( IN DWORD cQuotedRdnValueLength, IN LPCWSTR psQuotedRdnValue, IN OUT DWORD *pcUnquotedRdnValueLength, OUT LPWSTR psUnquotedRdnValue ); DWORD DsUnquoteRdnValueWrapper( IN DWORD cQuotedRdnValueLength, IN LPCWSTR psQuotedRdnValue, IN OUT DWORD *pcUnquotedRdnValueLength, OUT LPTCH psUnquotedRdnValue ); // // DsMakePasswordCredentialsW // typedef DWORD (*PF_DsMakePasswordCredentialsW) ( LPCWSTR User, LPCWSTR Domain, LPCWSTR Password, RPC_AUTH_IDENTITY_HANDLE *pAuthIdentity ); DWORD DsMakePasswordCredentialsWrapper( LPCWSTR User, LPCWSTR Domain, LPCWSTR Password, RPC_AUTH_IDENTITY_HANDLE *pAuthIdentity ); // // DsFreePasswordCredentials definition // typedef DWORD (*PF_DsFreePasswordCredentials) ( RPC_AUTH_IDENTITY_HANDLE AuthIdentity ); DWORD DsFreePasswordCredentialsWrapper( RPC_AUTH_IDENTITY_HANDLE AuthIdentity ); // // DsBindW // typedef DWORD (*PF_DsBindW) ( LPCWSTR DomainControllerName, LPCWSTR DnsDomainName, HANDLE *phDS ); DWORD DsBindWrapper( LPCWSTR DomainControllerName, LPCWSTR DnsDomainName, HANDLE *phDS ); // // DsUnbindW // typedef DWORD (*PF_DsUnbindW) ( HANDLE *phDS ); DWORD DsUnBindWrapper( HANDLE *phDS ); // // DsCrackNamesW // typedef DWORD(*PF_DsCrackNamesW) ( HANDLE hDS, DS_NAME_FLAGS flags, DS_NAME_FORMAT formatOffered, DS_NAME_FORMAT formatDesired, DWORD cNames, const LPCWSTR *rpNames, PDS_NAME_RESULTW *ppResult ); DWORD DsCrackNamesWrapper( HANDLE hDS, DS_NAME_FLAGS flags, DS_NAME_FORMAT formatOffered, DS_NAME_FORMAT formatDesired, DWORD cNames, const LPCWSTR *rpNames, PDS_NAME_RESULTW *ppResult ); // // DsBindWithCredW. // typedef DWORD (*PF_DsBindWithCredW) ( LPCWSTR DomainControllerName, LPCWSTR DnsDomainName, RPC_AUTH_IDENTITY_HANDLE AuthIdentity, HANDLE *phDS ); DWORD DsBindWithCredWrapper( LPCWSTR DomainControllerName, LPCWSTR DnsDomainName, RPC_AUTH_IDENTITY_HANDLE AuthIdentity, HANDLE *phDS ); // // DsFreeNameResultW // typedef DWORD (*PF_DsFreeNameResultW) ( DS_NAME_RESULTW *pResult ); DWORD DsFreeNameResultWrapper( DS_NAME_RESULTW *pResult ); // // QueryContextAttributes // typedef DWORD (*PF_QueryContextAttributes) ( PCtxtHandle phContext, unsigned long ulAttribute, void SEC_FAR * pBuffer ); DWORD QueryContextAttributesWrapper( PCtxtHandle phContext, unsigned long ulAttribute, void SEC_FAR * pBuffer );
22.99278
79
0.651908
npocmaka
bd332dd50289923aa99b1205d1b715bf2588c36c
5,424
cpp
C++
TAO/tests/Bug_1535_Regression/bug_1535_regression.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
36
2015-01-10T07:27:33.000Z
2022-03-07T03:32:08.000Z
TAO/tests/Bug_1535_Regression/bug_1535_regression.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
2
2018-08-13T07:30:51.000Z
2019-02-25T03:04:31.000Z
TAO/tests/Bug_1535_Regression/bug_1535_regression.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
38
2015-01-08T14:12:06.000Z
2022-01-19T08:33:00.000Z
// $Id: bug_1535_regression.cpp 92387 2010-10-28 07:46:18Z johnnyw $ #include "Test.h" #include "tao/Utils/ORB_Destroyer.h" #include "tao/Utils/RIR_Narrow.h" #include "tao/Utils/PolicyList_Destroyer.h" PortableServer::POA_ptr create_persistent_POA (PortableServer::POA_ptr parent, char const * name) { TAO::Utils::PolicyList_Destroyer plist (3); plist.length(3); plist[0] = parent->create_lifespan_policy (PortableServer::PERSISTENT); plist[1] = parent->create_id_assignment_policy (PortableServer::USER_ID); plist[2] = parent->create_implicit_activation_policy ( PortableServer::NO_IMPLICIT_ACTIVATION); PortableServer::POAManager_var mgr = parent->the_POAManager (); return parent->create_POA (name, mgr.in(), plist); } void test_create_object_before_servant_reactivation ( CORBA::ORB_ptr orb, PortableServer::POA_ptr root_poa) { // Create a persistent POA and then create a reference in it... PortableServer::POA_var persistent_poa = create_persistent_POA(root_poa, "T1"); PortableServer::ObjectId_var oid = PortableServer::string_to_ObjectId ("TestServant"); char const * id = _tc_Test->id (); CORBA::Object_var object = persistent_poa->create_reference_with_id ( oid.in (), id); if (CORBA::is_nil (object.in ())) { ACE_ERROR ((LM_ERROR, "(%P|%t) nil reference in create_reference_with_id\n")); return; } CORBA::String_var ior = orb->object_to_string (object.in ()); // Now destroy the POA... persistent_poa->destroy (true, true); // Now create the POA again... persistent_poa = create_persistent_POA (root_poa, "T1"); // And try to create the object again... object = orb->string_to_object (ior.in ()); if(CORBA::is_nil (object.in ())) { ACE_ERROR ((LM_ERROR, "(%P|%t) nil reference in string_to_object (servant reactivation)\n")); return; } persistent_poa->destroy (true, true); } void test_create_object_before_POA_reactivation( CORBA::ORB_ptr orb, PortableServer::POA_ptr root_poa) { // Create a persistent POA and then create a reference in it... PortableServer::POA_var persistent_poa = create_persistent_POA (root_poa, "T2"); PortableServer::ObjectId_var oid = PortableServer::string_to_ObjectId ("TestServant"); char const * id = _tc_Test->id (); CORBA::Object_var object = persistent_poa->create_reference_with_id (oid.in (), id); if (CORBA::is_nil (object.in ())) { ACE_DEBUG ((LM_DEBUG, "(%P|%t) nil reference in create_reference_with_id\n")); return; } CORBA::String_var ior = orb->object_to_string (object.in ()); // Now destroy the POA... persistent_poa->destroy (true, true); // And try to create the object again... object = orb->string_to_object (ior.in ()); if (CORBA::is_nil (object.in ())) { ACE_DEBUG ((LM_DEBUG, "(%P|%t) nil reference in string_to_object (POA reactivation)\n")); return; } persistent_poa->destroy (true, true); } void test_no_implicit_activation ( PortableServer::POA_ptr root_poa) { // Create a persistent POA and then create a reference in it... PortableServer::POA_var persistent_poa = create_persistent_POA (root_poa, "T3"); Hello myhello (persistent_poa.in ()); bool succeed = false; try { // Implicit activation should fail Test_var myservant = myhello._this (); } catch (const PortableServer::POA::WrongPolicy& ) { succeed = true; } catch (const PortableServer::POA::ServantNotActive& ) { // This is now the case when looking at the corba spec, raised // an issue 10522 about this succeed = true; } catch (const CORBA::Exception&) { } if (!succeed) { ACE_ERROR ((LM_ERROR, "(%t) ERROR, Implicit activation failed with invalid exception\n")); } // Now destroy the POA... persistent_poa->destroy (true, true); } int ACE_TMAIN(int argc, ACE_TCHAR *argv[]) { try { CORBA::ORB_var orb = CORBA::ORB_init (argc, argv); TAO::Utils::ORB_Destroyer orb_destroyer (orb.in()); PortableServer::POA_var root_poa = TAO::Utils::RIR_Narrow<PortableServer::POA>::narrow (orb.in (), "RootPOA"); PortableServer::POAManager_var poa_manager = root_poa->the_POAManager (); poa_manager->activate (); test_create_object_before_POA_reactivation (orb.in(), root_poa.in ()); test_create_object_before_servant_reactivation (orb.in (), root_poa.in ()); test_no_implicit_activation (root_poa.in ()); } catch (const CORBA::Exception& ex) { ex._tao_print_exception ("Caught a CORBA exception\n"); return 1; } catch (...) { return 1; } return 0; }
24.542986
89
0.588127
cflowe
bd36c9ba7242d8535dfaadecbaea76c9db574ee4
320
cpp
C++
test/t_0011.cpp
rayloyal/leetcode
79ded19bbb9f2d294b609f30bd3cbfe2cf8311a9
[ "MIT" ]
1
2022-03-02T14:19:55.000Z
2022-03-02T14:19:55.000Z
test/t_0011.cpp
rayloyal/leetcode
79ded19bbb9f2d294b609f30bd3cbfe2cf8311a9
[ "MIT" ]
null
null
null
test/t_0011.cpp
rayloyal/leetcode
79ded19bbb9f2d294b609f30bd3cbfe2cf8311a9
[ "MIT" ]
null
null
null
#include "q_0011.h" #include "gtest/gtest.h" using namespace std; using ::testing::Test; TEST(Q0011, EXAMPLE){ Solution solution; vector<int> height1 = {1, 8, 6, 2, 5, 4, 8, 3, 7}; ASSERT_EQ(solution.maxArea(height1), 49); vector<int> height2 = {1, 1}; ASSERT_EQ(solution.maxArea(height2), 1); }
20
54
0.640625
rayloyal
bd371762adb95fd0bdec8328c6e81eff72b7e664
547
cpp
C++
60 Must Solve List/Unique Email Addresses.cpp
Tiger-Team-01/DSA-A-Z-Practice
e08284ffdb1409c08158dd4e90dc75dc3a3c5b18
[ "MIT" ]
14
2021-08-22T18:21:14.000Z
2022-03-08T12:04:23.000Z
60 Must Solve List/Unique Email Addresses.cpp
Tiger-Team-01/DSA-A-Z-Practice
e08284ffdb1409c08158dd4e90dc75dc3a3c5b18
[ "MIT" ]
1
2021-10-17T18:47:17.000Z
2021-10-17T18:47:17.000Z
60 Must Solve List/Unique Email Addresses.cpp
Tiger-Team-01/DSA-A-Z-Practice
e08284ffdb1409c08158dd4e90dc75dc3a3c5b18
[ "MIT" ]
5
2021-09-01T08:21:12.000Z
2022-03-09T12:13:39.000Z
// Hari class Solution { public: string ruler(string email){ string cleanMail; for(char c: email){ if(c == '+' || c == '@') break; if(c == '.') continue; cleanMail += c; } cleanMail += email.substr(email.find('@')); return cleanMail; } int numUniqueEmails(vector<string>& emails) { unordered_set<string> emailSet; for(auto &it: emails){ emailSet.insert(ruler(it)); } return emailSet.size(); } };
21.88
51
0.482633
Tiger-Team-01
bd38582b1dbd9cb4342900ad66bbde0535bb73ad
3,060
cpp
C++
lib/project_euler/0001-0050/Problem17.cpp
wtmitchell/project_euler
b0fd328af41901aa53f757f1dd84f44f71d7be44
[ "MIT" ]
2
2016-04-03T08:44:15.000Z
2018-10-05T02:12:19.000Z
lib/project_euler/0001-0050/Problem17.cpp
wtmitchell/challenge_problems
b0fd328af41901aa53f757f1dd84f44f71d7be44
[ "MIT" ]
null
null
null
lib/project_euler/0001-0050/Problem17.cpp
wtmitchell/challenge_problems
b0fd328af41901aa53f757f1dd84f44f71d7be44
[ "MIT" ]
null
null
null
//===-- project_euler/Problem17.cpp -----------------------------*- C++ -*-===// // // ProjectEuler.net solutions by Will Mitchell // // This file is distributed under the MIT License. See LICENSE for details. // //===----------------------------------------------------------------------===// /// /// \class project_euler::Problem17 /// \brief Number letter counts /// /// Question /// -------- /// If the numbers 1 to 5 are written out in words: one, two, three, four, five, /// then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total. /// /// If all the numbers from 1 to 1000 (one thousand) inclusive were written out /// in words, how many letters would be used? /// /// NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and /// forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 /// letters. The use of "and" when writing out numbers is in compliance with /// British usage. /// /// Analysis /// -------- /// Observe that for this case, we have a lot of redundancies. For instance, /// one, two, ... ninety-nine will occur 10 total times. The word "and" will /// occur 99 times per group of one hundred above 100, for a total of 99*8 times /// Then "one hundred" occurs 100 times, "two hundred" occurs 100 times etc. //===----------------------------------------------------------------------===// #include "Problem17.h" #include <sstream> using std::stringstream; #include <string> using std::string; #include "number/Miscellaneous.h" using number::toEnglishString; using number::toEnglishStringUnder1000; string project_euler::Problem17::answer() { if (!solved) solve(); stringstream ss; ss << "The number of letters used to write 1 to 1000 with British usage is " << count; return ss.str(); } std::string project_euler::Problem17::description() const { return "Problem 17: Number letter counts"; } void project_euler::Problem17::solve() { count = bruteForce3(); solved = true; } unsigned long project_euler::Problem17::bruteForce(const unsigned long limit) const { unsigned long letters = 0; for (auto i = 1ul; i <= limit; ++i) letters += toEnglishString<unsigned long, false, true>(i).length(); return letters; } unsigned long project_euler::Problem17::bruteForce2() const { unsigned long letters = 0; for (auto i = 1u; i <= 999; ++i) letters += toEnglishStringUnder1000<false, true>(i).length(); letters += string("onethousand").length(); return letters; } unsigned long project_euler::Problem17::bruteForce3() const { unsigned long letters = 0; // one, two, ... ninety-nine occur ten times total for (auto i = 1u; i <= 99; ++i) letters += toEnglishStringUnder1000<false>(i).length(); letters *= 10; // All the "and" from British grammar letters += 3 * 99 * 9; // All the "one hundred", "two hundred", etc for (auto i = 1u; i <= 9; ++i) letters += 100 * toEnglishStringUnder1000<false>(i * 100).length(); // Finally one thousand is an odd-ball letters += string("onethousand").length(); return letters; }
29.708738
80
0.63268
wtmitchell
bd399cd1cda1969d2bd5786d2646317b001d54a8
1,247
cpp
C++
011/demo.cpp
jiejieTop/c-plus-plus
2f5832333eb2521e08aea430e65f003cdf4611a5
[ "Apache-2.0" ]
null
null
null
011/demo.cpp
jiejieTop/c-plus-plus
2f5832333eb2521e08aea430e65f003cdf4611a5
[ "Apache-2.0" ]
null
null
null
011/demo.cpp
jiejieTop/c-plus-plus
2f5832333eb2521e08aea430e65f003cdf4611a5
[ "Apache-2.0" ]
null
null
null
/* * @Author: jiejie * @Github: https://github.com/jiejieTop * @Date: 2020-03-21 15:55:37 * @LastEditTime: 2020-04-01 00:45:32 * @Description: the code belongs to jiejie, please keep the author information and source code according to the license. */ #include <string> #include <cstring> #include <iostream> #include <vector> class class_a { private: /* data */ int width, high; public: class_a(int _w, int _h); ~class_a(); void print_info(void); }; class class_b { private: /* data */ int number; class_a test_a; public: class_b(int _b, int _w, int _h); ~class_b(); void print_info(void); }; class_a::class_a(int _w, int _h):width(_w),high(_h) { }; class_a::~class_a() { }; class_b::class_b(int _b, int _w, int _h):number(_b), test_a(_w, _h) { }; class_b::~class_b() { }; void class_a::print_info(void) { std::cout << "class_a::width = " << this->width << std::endl; std::cout << "class_a::high = " << this->high << std::endl; } void class_b::print_info(void) { std::cout << "class_b::number = " << this->number << std::endl; this->test_a.print_info(); } int main(void) { using namespace std; class_b r2(20, 13, 14); r2.print_info(); return 0; }
15.78481
121
0.615076
jiejieTop
bd3b3ec24327e465114d49a5114bac5b1750a4ba
985
cc
C++
chrome/browser/supervised_user/supervised_user_test_util.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
chrome/browser/supervised_user/supervised_user_test_util.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
chrome/browser/supervised_user/supervised_user_test_util.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2020 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/browser/supervised_user/supervised_user_test_util.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/pref_names.h" #include "components/prefs/pref_service.h" namespace supervised_user_test_util { void AddCustodians(Profile* profile) { DCHECK(profile->IsChild()); PrefService* prefs = profile->GetPrefs(); prefs->SetString(prefs::kSupervisedUserCustodianEmail, "test_parent_0@google.com"); prefs->SetString(prefs::kSupervisedUserCustodianObfuscatedGaiaId, "239029320"); prefs->SetString(prefs::kSupervisedUserSecondCustodianEmail, "test_parent_1@google.com"); prefs->SetString(prefs::kSupervisedUserSecondCustodianObfuscatedGaiaId, "85948533"); } } // namespace supervised_user_test_util
35.178571
73
0.735025
chromium
bd3fef6937348f5e42026b3f068ee912e83bceb5
1,006
cpp
C++
test/bubblesort.cpp
SherlockZhang3/MyCppTest
393b91270e1485a8e7ff78bd11d9b91c7af3a872
[ "Apache-2.0" ]
null
null
null
test/bubblesort.cpp
SherlockZhang3/MyCppTest
393b91270e1485a8e7ff78bd11d9b91c7af3a872
[ "Apache-2.0" ]
null
null
null
test/bubblesort.cpp
SherlockZhang3/MyCppTest
393b91270e1485a8e7ff78bd11d9b91c7af3a872
[ "Apache-2.0" ]
null
null
null
/*================================================================ * Copyright (c) 2022年 SherlockZhang. All rights reserved. * * 文件名称:bubblesort.cpp * 创 建 者:SherlockZhang * 邮 箱:SherlockZhang@aliyun.com * 创建日期:2021年02月23日 * 描 述:冒泡排序,其实应该说是反冒泡排序,把最大的数沉到后方。 * #pragma once ================================================================*/ #include <iostream> #include "printarr.h" using namespace std; void BubbleSort(int sort[]) { int k = 0; for (int j = 9; j >= 0; j--) //第一轮,bsort[9]是最大的,接下来找第二大的放到bsort[8]里 { for (int i = 0; i < j; i++) //两两比较,把最大的数放到最后 { if (sort[i] > sort[i + 1]) { k = sort[i]; sort[i] = sort[i + 1]; sort[i + 1] = k; } } } } int main() { int sort_array[10] = {2, 4, 1, 5, 0, 8, 6, 9, 3, 7}; PrintArr(sort_array, "冒泡排序前数组sort_array为:"); BubbleSort(sort_array); PrintArr(sort_array, "冒泡排序后数组sort_array为:"); return 0; }
24.536585
71
0.457256
SherlockZhang3
bd40e6b8cac0dac07eac0b6e7ff9f1a6db88d8dd
621
cc
C++
adlik_serving/runtime/tensorflow/model/plan_model_loader.cc
yuanliya/Adlik
602074b44064002fc0bb054e17a989a5bcf22e92
[ "Apache-2.0" ]
548
2019-09-27T07:37:47.000Z
2022-03-31T05:12:38.000Z
adlik_serving/runtime/tensorflow/model/plan_model_loader.cc
yespon/Adlik
c890eea7b9d0983905dd38c380839bda1a2d8237
[ "Apache-2.0" ]
533
2019-09-27T06:30:41.000Z
2022-03-29T07:34:08.000Z
adlik_serving/runtime/tensorflow/model/plan_model_loader.cc
yespon/Adlik
c890eea7b9d0983905dd38c380839bda1a2d8237
[ "Apache-2.0" ]
54
2019-10-10T02:19:31.000Z
2021-12-28T03:37:45.000Z
// Copyright 2019 ZTE corporation. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 #include "adlik_serving/runtime/tensorflow/model/plan_model_loader.h" #include "adlik_serving/runtime/tensorflow/model/plan_model_factory.h" namespace tensorflow { cub::Status PlanModelLoader::loadBare() { if (auto model = ROLE(PlanModelFactory).create()) { bundle.reset(model); return cub::Success; } return cub::Failure; } cub::Status PlanModelLoader::unloadBare() { bundle.reset(); return cub::Success; } cub::AnyPtr PlanModelLoader::model() { return {bundle.get()}; } } // namespace tensorflow
22.178571
70
0.731079
yuanliya
bd434a766d281b10a06c7695d9803c9dffb2bddb
589
cpp
C++
C++/M02_Fundamentals/L04_StringsAndStreams/Exercises/Solutions/P05_InvalidInput.cpp
todorkrastev/softuni-software-engineering
cfc0b5eaeb82951ff4d4668332ec3a31c59a5f84
[ "MIT" ]
null
null
null
C++/M02_Fundamentals/L04_StringsAndStreams/Exercises/Solutions/P05_InvalidInput.cpp
todorkrastev/softuni-software-engineering
cfc0b5eaeb82951ff4d4668332ec3a31c59a5f84
[ "MIT" ]
null
null
null
C++/M02_Fundamentals/L04_StringsAndStreams/Exercises/Solutions/P05_InvalidInput.cpp
todorkrastev/softuni-software-engineering
cfc0b5eaeb82951ff4d4668332ec3a31c59a5f84
[ "MIT" ]
1
2022-02-23T13:03:14.000Z
2022-02-23T13:03:14.000Z
#include <iostream> #include <sstream> #include <string> using namespace std; int main() { string inp; getline(cin, inp); istringstream input(inp); string current; ostringstream streamLetters; int sum = 0; while (input >> current) { char c = current[0]; if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) { streamLetters << current << " "; } else { int n = stoi(current); sum += n; } } cout << sum << endl; cout << streamLetters.str() << endl; return 0; }
16.361111
63
0.475382
todorkrastev
bd49a473ba04607edf42d8ee0c3a946a6b35e102
2,740
cpp
C++
learncpp/ej6c6.cpp
ignaciop/c-varios
c8ef033485efd19a01fbc43658be36473eb1d08d
[ "MIT" ]
null
null
null
learncpp/ej6c6.cpp
ignaciop/c-varios
c8ef033485efd19a01fbc43658be36473eb1d08d
[ "MIT" ]
null
null
null
learncpp/ej6c6.cpp
ignaciop/c-varios
c8ef033485efd19a01fbc43658be36473eb1d08d
[ "MIT" ]
null
null
null
#include <iostream> #include <array> #include <ctime> #include <cstdlib> enum CardSuit { SUIT_CLUB, SUIT_DIAMOND, SUIT_HEART, SUIT_SPADE, MAX_SUITS }; enum CardRank { RANK_2, RANK_3, RANK_4, RANK_5, RANK_6, RANK_7, RANK_8, RANK_9, RANK_10, RANK_JACK, RANK_QUEEN, RANK_KING, RANK_ACE, MAX_RANKS }; struct Card { CardSuit suit; CardRank rank; }; void printCard(const Card &card) { switch (card.rank) { case RANK_2: std::cout << '2'; break; case RANK_3: std::cout << '3'; break; case RANK_4: std::cout << '4'; break; case RANK_5: std::cout << '5'; break; case RANK_6: std::cout << '6'; break; case RANK_7: std::cout << '7'; break; case RANK_8: std::cout << '8'; break; case RANK_9: std::cout << '9'; break; case RANK_10: std::cout << 'T'; break; case RANK_JACK: std::cout << 'J'; break; case RANK_QUEEN: std::cout << 'Q'; break; case RANK_KING: std::cout << 'K'; break; case RANK_ACE: std::cout << 'A'; break; case MAX_RANKS: std::cout << ' '; break; } switch (card.suit) { case SUIT_CLUB: std::cout << 'C'; break; case SUIT_DIAMOND: std::cout << 'D'; break; case SUIT_HEART: std::cout << 'H'; break; case SUIT_SPADE: std::cout << 'S'; break; case MAX_SUITS: std::cout << ' '; break; } } void printDeck(const std::array<Card, 52> &deck) { for (const auto &card : deck) { printCard(card); std::cout << ' '; } std::cout << '\n'; } void swapCard(Card &a, Card &b) { Card temp = a; a = b; b = temp; } int getRandomNumber(int min, int max) { static const double fraction = 1.0 / (static_cast<double>(RAND_MAX) + 1.0); return static_cast<int>(rand()*fraction*(max - min + 1) + min); } void shuffleDeck(std::array<Card, 52> &deck) { for (int index = 0; index < 52; ++index) { int swapIndex = getRandomNumber(0, 51); swapCard(deck[index], deck[swapIndex]); } } int getCardValue(Card &card) { switch (card.rank) { case RANK_2: return 2; break; case RANK_3: return 3; break; case RANK_4: return 4; break; case RANK_5: return 5; break; case RANK_6: return 6; break; case RANK_7: return 7; break; case RANK_8: return 8; break; case RANK_9: return 9; break; case RANK_10: return 10; break; case RANK_JACK: return 10; break; case RANK_QUEEN: return 10; break; case RANK_KING: return 10; break; case RANK_ACE: return 11; break; case MAX_RANKS: return 0; break; } return 0; } int main() { std::array<Card, 52> deck; int card = 0; for (int suit = 0; suit < MAX_SUITS; ++suit) { for (int rank = 0; rank < MAX_RANKS; ++rank) { deck[card].suit = static_cast<CardSuit>(suit); deck[card].rank = static_cast<CardRank>(rank); ++card; } } printDeck(deck); shuffleDeck(deck); printDeck(deck); return 0; }
20.916031
76
0.633212
ignaciop
bd4d6a5048b2e6cb1a39b74982989d8c1ebe87cc
1,812
cc
C++
benchmark/unordered_map_benchmark.cc
uazo/goma-client
1cffeb7978539ac2fee02257ca0a95a05b4c6cc0
[ "BSD-3-Clause" ]
4
2018-12-26T10:54:24.000Z
2022-03-31T21:19:47.000Z
benchmark/unordered_map_benchmark.cc
uazo/goma-client
1cffeb7978539ac2fee02257ca0a95a05b4c6cc0
[ "BSD-3-Clause" ]
null
null
null
benchmark/unordered_map_benchmark.cc
uazo/goma-client
1cffeb7978539ac2fee02257ca0a95a05b4c6cc0
[ "BSD-3-Clause" ]
1
2021-05-31T13:27:25.000Z
2021-05-31T13:27:25.000Z
// Copyright 2018 The Goma 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 <random> #include <unordered_map> #include "absl/container/flat_hash_map.h" #include "benchmark/benchmark.h" namespace devtools_goma { template <class M> void BM_HashMap(benchmark::State& state) { for (auto _ : state) { (void)_; M m; for (int i = 0; i < state.range(0); ++i) { m[i] = i; } } state.SetItemsProcessed(state.iterations()); } BENCHMARK_TEMPLATE(BM_HashMap, std::unordered_map<int, int>) ->RangeMultiplier(4) ->Range(1, 65536); BENCHMARK_TEMPLATE(BM_HashMap, absl::flat_hash_map<int, int>) ->RangeMultiplier(4) ->Range(1, 65536); template <class M> void BM_HashMapReserve(benchmark::State& state) { for (auto _ : state) { (void)_; M m; m.reserve(state.range(0)); for (int i = 0; i < state.range(0); ++i) { m[i] = i; } } state.SetItemsProcessed(state.iterations()); } BENCHMARK_TEMPLATE(BM_HashMapReserve, std::unordered_map<int, int>) ->RangeMultiplier(4) ->Range(1, 65536); BENCHMARK_TEMPLATE(BM_HashMapReserve, absl::flat_hash_map<int, int>) ->RangeMultiplier(4) ->Range(1, 65536); template <class M> void BM_HashMapRandom(benchmark::State& state) { std::mt19937 mt; for (auto _ : state) { (void)_; M m; for (int i = 0; i < state.range(0); ++i) { m[mt()] = i; } } state.SetItemsProcessed(state.iterations()); } BENCHMARK_TEMPLATE(BM_HashMapRandom, std::unordered_map<int, int>) ->RangeMultiplier(4) ->Range(1, 65536); BENCHMARK_TEMPLATE(BM_HashMapRandom, absl::flat_hash_map<int, int>) ->RangeMultiplier(4) ->Range(1, 65536); } // namespace devtools_goma BENCHMARK_MAIN();
22.37037
73
0.657837
uazo
bd4f382bb6fb76eb87a50d0974245357ea70e6ec
23,775
cpp
C++
ExploringScaleSymmetry/Chapter6/automata2D/Evolver.cpp
TGlad/ExploringScaleSymmetry
25b2dae0279a0ac26f6bae2277d3b76a1cda8b04
[ "MIT" ]
null
null
null
ExploringScaleSymmetry/Chapter6/automata2D/Evolver.cpp
TGlad/ExploringScaleSymmetry
25b2dae0279a0ac26f6bae2277d3b76a1cda8b04
[ "MIT" ]
null
null
null
ExploringScaleSymmetry/Chapter6/automata2D/Evolver.cpp
TGlad/ExploringScaleSymmetry
25b2dae0279a0ac26f6bae2277d3b76a1cda8b04
[ "MIT" ]
null
null
null
// Thomas Lowe, 2020. // Defines the evolution of the automaton. Typically a fixed function of the neighbouring cells. #include "evolver.h" #include "Image.h" #include <string.h> #include <algorithm> using namespace std; Evolver::Evolver(int depth) { this->depth = depth; bitmaps = new Image*[depth+1]; bitmapDuals = new Image*[depth+1]; for (int size = 2, i=1; i<=depth; size *= 2, i++) { bitmaps[i] = new Image(size+2, size+2); // store each pixel bitmaps[i]->clear(); bitmapDuals[i] = new Image(size+2, size+2); // store each pixel bitmapDuals[i]->clear(); } type = 1; reset(); } void Evolver::checkSiblings() { if (type == 10) // temporal coherence { int count = 0; for (int i = 0; i < 89; i++) count += siblingMasks[i] ? 1 : 0; if (count >= 45) { for (int i = 0; i < 89; i++) siblingMasks[i] = !siblingMasks[i]; count = 89 - count; } } } void Evolver::reset() { frame = 0; // type 3 for (int i = 0; i<1<<9; i++) siblingMasks[i] = random(-1.0, 1.0)>0; checkSiblings(); for (int i = 0; i<1<<4; i++) parentMasks[i] = random(-1.0, 1.0)>0; for (int i = 0; i<1<<4; i++) childMasks[i] = random(-1.0, 1.0)>0; for (int i = 0; i<32; i++) totalMasks[i] = random(-1.0, 1.0) > 0 ? 1 : 0; // type 6 for (int i = 0; i<6; i++) for (int j = 0; j<3; j++) for (int k = 0; k<3; k++) { parentsAdd[i][j][k] = random(-1.0, 1.0) > 0 ? 1 : 0; parentsRemove[i][j][k] = random(-1.0, 1.0) > 0 ? 1 : 0; } // type 7 for (int i = 0; i<1<<7; i++) octagonalMasks[i] = random(-1.0, 1.0)>0; randomise(); } bool Evolver::load(const char* fileName, int type) { this->type = type; ifstream fp(fileName, ios::in | ios::binary); if (!fp.is_open()) { printf("Cannot find file: %s\n", fileName); return false; } read(fp); fp.close(); return true; } void Evolver::randomiseMasks(const Evolver& master, float percentVariation) { type = master.type; float threshold = 1.0f - 2.0f*0.01f*percentVariation; for (int i = 0; i<1<<9; i++) { siblingMasks[i] = master.siblingMasks[i]; if (random(-1.0, 1.0) > threshold) siblingMasks[i] = !siblingMasks[i]; } checkSiblings(); for (int i = 0; i<1<<4; i++) { parentMasks[i] = master.parentMasks[i]; if (random(-1.0, 1.0) > threshold) parentMasks[i] = !parentMasks[i]; } for (int i = 0; i<1<<4; i++) { childMasks[i] = master.childMasks[i]; if (random(-1.0, 1.0) > threshold) childMasks[i] = !childMasks[i]; } frame = 0; for (int i = 0; i<32; i++) { totalMasks[i] = master.totalMasks[i]; if (random(-1.0, 1.0) > threshold) totalMasks[i] = 1-totalMasks[i]; } for (int i = 0; i<6; i++) for (int j = 0; j<3; j++) for (int k = 0; k<3; k++) { parentsAdd[i][j][k] = master.parentsAdd[i][j][k]; parentsRemove[i][j][k] = master.parentsRemove[i][j][k]; if (random(-1.0, 1.0) > threshold) parentsAdd[i][j][k] = !parentsAdd[i][j][k]; if (random(-1.0, 1.0) > threshold) parentsRemove[i][j][k] = !parentsRemove[i][j][k]; } for (int i = 0; i<1<<7; i++) { octagonalMasks[i] = master.octagonalMasks[i]; if (random(-1.0, 1.0) > threshold) octagonalMasks[i] = !octagonalMasks[i]; } } void Evolver::randomise(bool *starts) { // initialise the bitmaps to some random image: // This is a recursive process, generating the data procedurally as we go deeper in detail level. for (int level = 2; level<=depth; level++) { int size = 1<<level; if (level == 2 && starts) { int c = 0; for (int i = 0; i<size; i++) for (int j = 0; j<size; j++) bitmaps[level]->setPixel(i, j, starts[c++] ? 128 : 0); continue; } for (int i = 0; i<size; i++) for (int j = 0; j<size; j++) bitmaps[level]->setPixel(i, j, random(-1.0, 1.0) > (type == 7 ? 0.0f : 0.5f) ? 128 : 0); } } void Evolver::read(ifstream &fp) { switch(type) { case(1): for (int i = 0; i<16; i++) fp.read((char *)&totalMasks[i], sizeof(int)); break; case(2): for (int i = 0; i<17; i++) fp.read((char *)&totalMasks[i], sizeof(int)); break; case(3): for (int i = 0; i<1<<9; i++) fp.read((char *)&siblingMasks[i], sizeof(bool)); for (int i = 0; i<1<<4; i++) fp.read((char *)&parentMasks[i], sizeof(bool)); for (int i = 0; i<1<<4; i++) fp.read((char *)&childMasks[i], sizeof(bool)); break; case(4): for (int i = 0; i<33; i++) fp.read((char *)&totalMasks[i], sizeof(int)); break; case(5): for (int i = 0; i<164; i++) fp.read((char *)&siblingMasks[i], sizeof(int)); break; case(6): for (int i = 0; i<6; i++) for (int j = 0; j<3; j++) for (int k = 0; k<3; k++) { fp.read((char *)&parentsAdd[i][j][k], sizeof(bool)); fp.read((char *)&parentsRemove[i][j][k], sizeof(bool)); } break; case(7): for (int i = 0; i<1<<6; i++) fp.read((char *)&octagonalMasks[i], sizeof(bool)); break; case(8) : for (int i = 0; i<1 << 7; i++) fp.read((char *)&octagonalMasks[i], sizeof(bool)); break; case(9) : for (int i = 0; i<1 << 4; i++) fp.read((char *)&parentMasks[i], sizeof(bool)); break; case(10) : for (int i = 0; i<89; i++) fp.read((char *)&siblingMasks[i], sizeof(bool)); break; case(11) : for (int i = 0; i<100; i++) fp.read((char *)&siblingMasks[i], sizeof(bool)); break; default: return; } frame = 0; } void Evolver::write(ofstream &fp) { switch(type) { case(1): for (int i = 0; i<16; i++) fp.write((char *)&totalMasks[i], sizeof(int)); break; case(2): for (int i = 0; i<17; i++) fp.write((char *)&totalMasks[i], sizeof(int)); break; case(3): for (int i = 0; i<1<<9; i++) fp.write((char *)&siblingMasks[i], sizeof(bool)); for (int i = 0; i<1<<4; i++) fp.write((char *)&parentMasks[i], sizeof(bool)); for (int i = 0; i<1<<4; i++) fp.write((char *)&childMasks[i], sizeof(bool)); break; case(4): for (int i = 0; i<33; i++) fp.write((char *)&totalMasks[i], sizeof(int)); break; case(5): for (int i = 0; i<164; i++) fp.write((char *)&siblingMasks[i], sizeof(int)); break; case(6): for (int i = 0; i<6; i++) for (int j = 0; j<3; j++) for (int k = 0; k<3; k++) { fp.write((char *)&parentsAdd[i][j][k], sizeof(bool)); fp.write((char *)&parentsRemove[i][j][k], sizeof(bool)); } break; case(7): for (int i = 0; i<1<<6; i++) fp.write((char *)&octagonalMasks[i], sizeof(bool)); break; case(8) : for (int i = 0; i<1 << 7; i++) fp.write((char *)&octagonalMasks[i], sizeof(bool)); break; case(9) : for (int i = 0; i<1 << 4; i++) fp.write((char *)&parentMasks[i], sizeof(bool)); break; case(10) : for (int i = 0; i<89; i++) fp.write((char *)&siblingMasks[i], sizeof(bool)); break; case(11) : for (int i = 0; i<100; i++) fp.write((char *)&siblingMasks[i], sizeof(bool)); break; default: break; } } void Evolver::set(const Evolver& evolver) { type = evolver.type; for (int i = 0; i<1<<9; i++) siblingMasks[i] = evolver.siblingMasks[i]; for (int i = 0; i<1<<4; i++) parentMasks[i] = evolver.parentMasks[i]; for (int i = 0; i<1<<4; i++) childMasks[i] = evolver.childMasks[i]; frame = 0; for (int i = 0; i<32; i++) totalMasks[i] = evolver.totalMasks[i]; for (int i = 0; i<6; i++) for (int j = 0; j<3; j++) for (int k = 0; k<3; k++) { parentsAdd[i][j][k] = evolver.parentsAdd[i][j][k]; parentsRemove[i][j][k] = evolver.parentsRemove[i][j][k]; } for (int i = 0; i<1<<7; i++) octagonalMasks[i] = evolver.octagonalMasks[i]; } void Evolver::draw() { bitmaps[depth]->generateTexture(); bitmaps[depth]->draw(); } void Evolver::drawMask() { if (type == 9) { int level = 8; bitmapDuals[level]->generateTexture(); bitmapDuals[level]->draw(); } } bool Evolver::getNewValue(int level, int X, int Y) { int dirX = X%2 ? 1 : -1; int dirY = Y%2 ? 1 : -1; int xx = X-dirX; int pattern1 = 0; int pattern2 = 0; for (int x = 0; x<3; x++) { int yy = Y-dirY; for (int y = 0; y<3; y++) { if (bitmaps[level]->isSet(xx, yy)) { pattern1 += 1<<(x+3*y); pattern2 += 1<<(y+3*x); } yy += dirY; } xx += dirX; } if (!siblingMasks[min(pattern1, pattern2)]) return false; xx = X/2; pattern1 = 0; pattern2 = 0; if (level > 0) { for (int x = 0; x<2; x++) { int yy = Y/2; for (int y = 0; y<2; y++) { if (bitmaps[level-1]->isSet(xx, yy)) { pattern1 += 1<<(x+2*y); pattern2 += 1<<(y+2*x); } yy += dirY; } xx += dirX; } } if (parentMasks[min(pattern1, pattern2)]) // the min ensures we remain symettric return true; pattern1 = 0; pattern2 = 0; xx = X*2 + 1 - X%2; if (level+1 <= depth) { for (int x = 0; x<2; x++) { int yy = Y*2 + 1 - Y%2; for (int y = 0; y<2; y++) { if (bitmaps[level+1]->isSet(xx, yy)) { pattern1 += 1<<(x+2*y); pattern2 += 1<<(y+2*x); } yy += dirY; } xx += dirX; } } if (childMasks[min(pattern1, pattern2)]) return true; return false; } bool Evolver::checkAddRemove(int level, int X, int Y, bool addRemove[6][3][3], int i, bool flip) { int dirX = X%2 ? 1 : -1; int dirY = Y%2 ? 1 : -1; int xx = X/2 - dirX; for (int x = 0; x<3; x++, xx += dirX) { int yy = Y/2 - dirY; for (int y = 0; y<3; y++, yy += dirY) { if (x==1 && y==1) continue; // if ((addRemove == parentsRemove && x==2 && y==2) || (addRemove == parentsAdd && x==0 && y==0)) // continue; bool mask = flip ? addRemove[i][y][x] : addRemove[i][x][y]; if (bitmaps[level-1]->isSet(xx, yy) != mask) return false; } } return true; } bool Evolver::getNewValueParentsOnly(int level, int X, int Y) { ASSERT(level > 0); if (bitmaps[level - 1]->isSet(X / 2, Y / 2)) // then prepare to remove { for (int i = 0; i<6; i++) if (checkAddRemove(level, X, Y, parentsRemove, i, false) || checkAddRemove(level, X, Y, parentsRemove, i, true)) return false; return true; } else { for (int i = 0; i<6; i++) if (checkAddRemove(level, X, Y, parentsAdd, i, false) || checkAddRemove(level, X, Y, parentsAdd, i, true)) return true; return false; } } bool Evolver::getNewValue4Parents(int level, int X, int Y) { ASSERT(level > 0); int dirX = X % 2 ? 1 : -1; int dirY = Y % 2 ? 1 : -1; int xx = X / 2; int pattern1 = 0; int pattern2 = 0; if (level > 0) { for (int x = 0; x<2; x++) { int yy = Y / 2; for (int y = 0; y<2; y++) { if (bitmaps[level - 1]->isSet(xx, yy)) { pattern1 += 1 << (x + 2 * y); pattern2 += 1 << (y + 2 * x); } yy += dirY; } xx += dirX; } } return parentMasks[min(pattern1, pattern2)]; // the min ensures we remain symettric } bool Evolver::getNewValueParentsOctagonal2(Image* image, int X, int Y, bool flip, bool extended, int level) { int pattern1 = 0; int pattern2 = 0; int pattern3 = 0; int pattern4 = 0; for (int i = 0; i<3; i++) { for (int j = 0; j<2; j++) { int I; int J; if (!flip) { I = X + i; J = Y + j; } else { I = X + j; J = Y + i; } if (image->isSet(I, J)) { pattern1 += 1<<(i + 3*j); pattern2 += 1<<((2-i) + 3*j); pattern3 += 1<<(i + 3*(1-j)); pattern4 += 1<<((2-i) + 3*(1-j)); } } } if (extended) { int i = 1; for (int j = -1; j<=2; j+=3) { int I; int J; if (!flip) { I = X + i; J = Y + j; } else { I = X + j; J = Y + i; } I = clamped(I, 0, 1<<level); J = clamped(J, 0, 1<<level); if (image->isSet(I, J)) { pattern1 += j==-1 ? 64 : 128; pattern2 += j==-1 ? 64 : 128; pattern3 += j==-1 ? 128 : 64; pattern4 += j==-1 ? 128 : 64; } } int minPattern = min(pattern1, min(pattern2, min(pattern3, pattern4))); if (minPattern <= 127) return octagonalMasks[minPattern]; else return !octagonalMasks[255 - minPattern]; } return octagonalMasks[min(pattern1, min(pattern2, min(pattern3, pattern4)))]; } bool Evolver::getNewValue2(int level, int X, int Y) { int dirX = X % 2 ? 1 : -1; int dirY = Y % 2 ? 1 : -1; int xx = X - dirX; // First, num neighbours int pattern1 = 0; int pattern2 = 0; int numNeighbours = 0; bool centreSet = false; for (int x = 0; x<3; x++) { int yy = Y - dirY; for (int y = 0; y<3; y++) { if (bitmaps[level]->isSet(xx, yy)) { if (x == 1 && y == 1) centreSet = true; else numNeighbours++; } yy += dirY; } xx += dirX; } xx = X / 2; bool hasParent = level > 0 ? bitmaps[level - 1]->isSet(X / 2, Y / 2) : 0; int numChildren = 0; xx = X * 2 + 1 - X % 2; if (level + 1 <= depth) { for (int x = 0; x<2; x++) { int yy = Y * 2 + 1 - Y % 2; for (int y = 0; y<2; y++) { if (bitmaps[level + 1]->isSet(xx, yy)) numChildren++; yy += dirY; } xx += dirX; } } return siblingMasks[((numNeighbours + numChildren * 8) * 2 + (int)hasParent) * 2 + (int)centreSet]; } bool getVal(int numChildren, int numParents, int numNeighbours, bool centreSet, bool *siblingMasks) { int coherence = 1; // even if (numNeighbours > 8 - coherence) return true; if (numNeighbours < coherence) return false; if (numParents == 1 && numChildren > 4 - coherence) return true; if (numParents == 0 && numChildren < coherence) return false; int index = numNeighbours + numChildren * 9 + numParents * 45; if (!centreSet) return siblingMasks[index]; else return !siblingMasks[89 - index]; } bool getVal4(int numChildren, int numParents, int numNeighbours, bool centreSet, bool *siblingMasks) { int coherence = 1; // even if (numNeighbours > 8 - coherence) return true; if (numNeighbours < coherence) return false; if (numParents > 4-coherence && numChildren > 4 - coherence) return true; if (numParents < coherence && numChildren < coherence) return false; int index = numNeighbours + numChildren * 9 + numParents * 45; if (!centreSet) return siblingMasks[index]; else return !siblingMasks[224 - index]; } bool Evolver::getNewValueAllSymmetries(int level, int X, int Y) { int dirX = X % 2 ? 1 : -1; int dirY = Y % 2 ? 1 : -1; int xx = X - dirX; // First, num neighbours int numNeighbours = 0; bool centreSet = false; for (int x = 0; x<3; x++) { int yy = Y - dirY; for (int y = 0; y<3; y++) { if (bitmaps[level]->isSet(xx, yy, centreSet)) { if (x == 1 && y == 1) centreSet = true; else numNeighbours++; } yy += dirY; } xx += dirX; } xx = X / 2; bool hasParent = level > 0 ? bitmaps[level - 1]->isSet(X / 2, Y / 2) : centreSet; #define ONE_PARENT #if defined ONE_PARENT int numParents = hasParent ? 1 : 0; #else int numParents = 0; if (level > 0) { for (int x = 0; x<2; x++) { int yy = Y / 2; for (int y = 0; y<2; y++) { if (bitmaps[level - 1]->isSet(xx, yy)) numParents++; yy += dirY; } xx += dirX; } } #endif int numChildren = 0; xx = X * 2 + 1 - X % 2; if (level + 1 <= depth) { for (int x = 0; x < 2; x++) { int yy = Y * 2 + 1 - Y % 2; for (int y = 0; y < 2; y++) { if (bitmaps[level + 1]->isSet(xx, yy)) numChildren++; yy += dirY; } xx += dirX; } } else numChildren = centreSet ? 4 : 0; // or 3, 1 bool answer = getVal(numChildren, numParents, numNeighbours, centreSet, siblingMasks); /* bool answer2 = !getVal(4-numChildren, 1-numParents, 8-numNeighbours, !centreSet, siblingMasks); if (answer != answer2) { std::cout << "didn't work" << std::endl; }*/ return answer; } bool Evolver::getNewValueChapter6(int level, int X, int Y) { int dirX = X % 2 ? 1 : -1; int dirY = Y % 2 ? 1 : -1; int xx = X - dirX; // First, num neighbours int numNeighbours = 0; bool centreSet = false; for (int x = 0; x<3; x++) { int yy = Y - dirY; for (int y = 0; y<3; y++) { if (bitmaps[level]->isSet(xx, yy, centreSet)) { if (x == 1 && y == 1) centreSet = true; else numNeighbours++; } yy += dirY; } xx += dirX; } xx = X / 2; int numParents = 0; if (level > 0) { for (int x = 0; x < 2; x++) { int yy = Y / 2; for (int y = 0; y < 2; y++) { if (bitmaps[level - 1]->isSet(xx, yy)) numParents++; yy += dirY; } xx += dirX; } } else numParents = centreSet ? 4 : 0; int numChildren = 0; xx = X * 2 + 1 - X % 2; if (level + 1 <= depth) { for (int x = 0; x < 2; x++) { int yy = Y * 2 + 1 - Y % 2; for (int y = 0; y < 2; y++) { if (bitmaps[level + 1]->isSet(xx, yy)) numChildren++; yy += dirY; } xx += dirX; } } else numChildren = centreSet ? 4 : 0; int total = (numChildren + numParents)*9 + numNeighbours; int maxx = max(numParents, numChildren); int minx = min(numParents, numChildren); if (minx >= 3) return true; if (maxx <= 1) return false; if (numNeighbours > 6) return true; if (numNeighbours < 2) return false; if (!centreSet) return siblingMasks[total]; else return !siblingMasks[80 - total]; } bool Evolver::getNewValueSimple(int level, int X, int Y) { int dirX = X%2 ? 1 : -1; int dirY = Y%2 ? 1 : -1; int xx = X-dirX; // First, num neighbours int pattern1 = 0; int pattern2 = 0; int numNeighbours = 0; bool centreSet = false; for (int x = 0; x<3; x++) { int yy = Y-dirY; for (int y = 0; y<3; y++) { if (bitmaps[level]->isSet(xx, yy)) { if (type != 2 && x==1 && y==1) centreSet = true; else numNeighbours++; } yy += dirY; } xx += dirX; } xx = X/2; if (level > 0) { for (int x = 0; x<2; x++) { int yy = Y/2; for (int y = 0; y<2; y++) { if (bitmaps[level-1]->isSet(xx, yy)) numNeighbours++; yy += dirY; } xx += dirX; } } xx = X*2 + 1 - X%2; if (level+1 <= depth) { for (int x = 0; x<2; x++) { int yy = Y*2 + 1 - Y%2; for (int y = 0; y<2; y++) { if (bitmaps[level+1]->isSet(xx, yy)) numNeighbours++; yy += dirY; } xx += dirX; } } if (type == 4) return totalMasks[centreSet ? numNeighbours : numNeighbours + 16]!=0; else return totalMasks[numNeighbours]!=0; } void Evolver::update() { // This performs the covolution frame++; if (type == 6) { if (frame == 1) { for (int level = 3; level <= depth; level++) { int size = 1 << level; for (int i = 0; i<size; i++) { for (int j = 0; j<size; j++) { int& pixel = bitmaps[level]->pixel(i, j); pixel = getNewValueParentsOnly(level, i, j) ? 192 : 0; } } } } return; } if (type == 9) { if (frame == 1) { for (int level = 3; level <= depth; level++) { int size = 1 << level; for (int i = 0; i<size; i++) { for (int j = 0; j<size; j++) { int& pixel = bitmaps[level]->pixel(i, j); pixel = getNewValue4Parents(level, i, j) ? 192 : 0; } } } for (int i = 0; i < 256; i++) { for (int j = 0; j < 256; j++) { bitmapDuals[8]->setPixel(i, j, bitmaps[2]->isSet(i / 64, j / 64) ? 128 : 0); } } } return; } if (type == 7 || type == 8) { if (frame == 1) { bool extended = frame==8; for (int level = 3; level<=depth; level++) { Image* mapFrom = bitmaps[level-1]; Image* mapTo = bitmapDuals[level]; int size = 1<<level; for (int i = 0; i<size/2; i++) { for (int j = 0; j<size/2 + 1; j++) { int toX = i + j; int toY = size/2 - 1 + j-i; int& pixel = mapTo->pixel(toX, toY); pixel = getNewValueParentsOctagonal2(mapFrom, i-1, j-1, false, extended, level-1) ? 192 : 0; } } for (int i = 0; i<size/2 + 1; i++) { for (int j = 0; j<size/2; j++) { int toX = i + j; int toY = size/2 + j-i; int& pixel = mapTo->pixel(toX, toY); pixel = getNewValueParentsOctagonal2(mapFrom, i-1, j-1, true, extended, level-1) ? 192 : 0; } } mapFrom = mapTo; mapTo = bitmaps[level]; for (int i = 0; i<size; i++) { for (int j = 0; j<size; j++) { int& pixel = mapTo->pixel(i, j); int fromX = -1 + (1 + i+j)/2; int fromY = -1 + (size + j-i)/2; pixel = getNewValueParentsOctagonal2(mapFrom, fromX, fromY, ((i+j)%2)==1, extended, level) ? 192 : 0; } } } } return; } // I need to get the timing algorithm right here... int currentLevel = -1; for (int i = 0; i<depth && currentLevel==-1; i++) if ((1<<i) & frame) currentLevel = i; // should go 0,1,0,2,0,1,0,3,... currentLevel = depth - currentLevel; // so most common is the highest detail. if (currentLevel == 1) { currentLevel = depth; frame = 1; } ASSERT(currentLevel <= depth && currentLevel > 1); int size = 1<<currentLevel; if (type < 3 || type == 4) { for (int i = 0; i<size; i++) { for (int j = 0; j<size; j++) { int& pixel = bitmaps[currentLevel]->pixel(i, j); adjustPixel(pixel, getNewValueSimple(currentLevel, i, j)); } } } else if (type == 3) { for (int i = 0; i<size; i++) { for (int j = 0; j<size; j++) { int& pixel = bitmaps[currentLevel]->pixel(i, j); adjustPixel(pixel, getNewValue(currentLevel, i, j)); } } } else if (type == 5) { for (int i = 0; i<size; i++) { for (int j = 0; j<size; j++) { int& pixel = bitmaps[currentLevel]->pixel(i, j); adjustPixel(pixel, getNewValue2(currentLevel, i, j)); } } } else if (type == 10) { for (int i = 0; i<size; i++) { for (int j = 0; j<size; j++) { int& pixel = bitmaps[currentLevel]->pixel(i, j); adjustPixel(pixel, getNewValueAllSymmetries(currentLevel, i, j)); } } } else if (type == 11) { for (int i = 0; i<size; i++) { for (int j = 0; j<size; j++) { int& pixel = bitmaps[currentLevel]->pixel(i, j); adjustPixel(pixel, getNewValueChapter6(currentLevel, i, j)); } } } for (int i = 0; i<size; i++) for (int j = 0; j<size; j++) bitmaps[currentLevel]->pixel(i, j) >>= 1; }
23.400591
118
0.492492
TGlad
bd53af54ccd266c823556b38c6bb37d8d0bf6290
23,001
cpp
C++
ros/src/Mobile_Platform.cpp
norlab-ulaval/navtechradar
4d3ccd2558e79142d656a6c12cd826d9397b0f2d
[ "MIT" ]
2
2020-11-18T17:48:40.000Z
2021-01-12T14:15:17.000Z
ros/src/Mobile_Platform.cpp
norlab-ulaval/navtechradar
4d3ccd2558e79142d656a6c12cd826d9397b0f2d
[ "MIT" ]
null
null
null
ros/src/Mobile_Platform.cpp
norlab-ulaval/navtechradar
4d3ccd2558e79142d656a6c12cd826d9397b0f2d
[ "MIT" ]
1
2022-03-22T16:09:51.000Z
2022-03-22T16:09:51.000Z
/* Copyright 2016 Navtech Radar Limited This file is part of iasdk which is released under The MIT License (MIT). See file LICENSE.txt in project root or go to https://opensource.org/licenses/MIT for full license details. */ /* Node Description: Example Application: Moving Platform Data Processor + Visualizer This app will subscribe to the raw data and give a user-configurable way to process this data. Functionality can be switched on/off using the dynamic reconfigure rqt plugin. Functionality available: Thresholded pointcloud of raw data Image topic using object detection algorithms Grid lines */ #define AZIMUTH_AVERAGING false #include "radarclient.h" #include "nav_ross/nav_msg.h" #include <iostream> #include <string> #include <vector> #include <math.h> #include <cstdint> #include <functional> #include <chrono> #include <thread> #include <cmath> #include <ros/ros.h> #include <std_msgs/String.h> #include <dynamic_reconfigure/server.h> #include <dynamic_paramConfig.h> #include <std_msgs/String.h> #include <visualization_msgs/Marker.h> #include <visualization_msgs/MarkerArray.h> #include <pcl/point_cloud.h> #include <pcl_ros/point_cloud.h> #include <pcl/point_types.h> #include <pcl_conversions/pcl_conversions.h> #include <sensor_msgs/PointCloud2.h> #include <sensor_msgs/point_cloud2_iterator.h> #include <cv_bridge/cv_bridge.h> #include <image_transport/image_transport.h> #include <opencv2/opencv.hpp> #include <opencv2/imgcodecs.hpp> #include <opencv2/highgui.hpp> #include <opencv2/imgproc.hpp> #include <opencv2/opencv.hpp> #include <opencv2/highgui/highgui.hpp> #include <sensor_msgs/LaserScan.h> #ifdef _WIN32 #include <winsock2.h> #pragma comment(lib, "Ws2_32.lib") #pragma comment(lib, "Rpcrt4.lib") #pragma comment(lib, "Iphlpapi.lib") #endif using namespace Navtech; using namespace cv; using namespace std; // DYNAMICALLY CONFIGURABLE PARAMETERS (on the parameter server) uint16_t threshold_value = 62; uint16_t dilation_value = 2; //Default Image Slider value uint16_t gaussian_value = 5; //Default Dilation filter size uint16_t maxangle = 35; uint16_t pcl_threshold_value=60; uint16_t grid_stepSize = 10; uint16_t grid_stepSize_m; uint16_t grid_width; uint16_t grid_height; uint8_t colormap = 10; uint16_t level_above_average=19; uint16_t adaptive_size=2; bool boundingboxes2 = false; bool pointcloud = false; bool LaserScan2 = false; bool MinAreaRect = false; bool radarimage=false; bool radarimageprocessing =false; bool grid = true; bool adaptive_threshold=false; bool longtermaverage = false; bool ThreeDScanApp; static bool Configuration_NOT_Set = 1; double grid_opacity = 0.5; // End of configurable Parameters uint16_t azimuths = 400; bool initialisedaverage; float range_res; float sin_values [405]={}; float cos_values [405]={}; float Phi = 0; float last_Phi=0; pcl::PointCloud<pcl::PointXYZI>::Ptr threeDPCL(new pcl::PointCloud<pcl::PointXYZI>); image_transport::Publisher CartesianPublisher; image_transport::Publisher FilteredPublisher; image_transport::Publisher BoxesPublisher; ros::Publisher LaserScanPublisher2; ros::Publisher PointcloudPublisher; ros::Publisher PointcloudPublisher3d; ros::Publisher MarkerPub; cv::Mat Long_Term_Average; // struct TimerROS // { // std::chrono::time_point<std::chrono::steady_clock>start,end; // std::chrono::duration<float>duration; // TimerROS() // { // start = std::chrono::high_resolution_clock::now(); // } // ~TimerROS() // { // end= std::chrono::high_resolution_clock::now(); // duration=end-start; // float ms = duration.count()*1000.0f; // std::cout<<"Timer took "<<ms<<"ms"<<endl; // } // }; void InitialiseParameters(float &range_res,uint16_t &azimuths) { if((ros::param::has("configuration_range_res")) && (ros::param::has("configuration_azimuths"))){ ros::param::getCached("configuration_range_res",range_res); int az_tmp; ros::param::get("/configuration_azimuths",az_tmp); azimuths = az_tmp; std::cout<<"\nRange Resolution Set from Parameter Server: "<<range_res<<"m\n"; std::cout<<"Number of Azimuths Set from Parameter Server: "<<az_tmp<<"\n"; for (int i=0;i<azimuths;i++){ float theta=(float)i*2*M_PI/azimuths; sin_values[i]=sin(theta); cos_values[i]=cos(theta); } for (int i=az_tmp;i<azimuths+5;i++){ float theta=(float)(i-azimuths)*2*M_PI/azimuths; sin_values[i]=sin(theta); cos_values[i]=cos(theta); } } else{ std::cout<<"\nConfiguration Settings not loaded from ros::param server..\nIf doing data playback, set parameters in server manually using ROS param CLI.\nParameters required are: configuration_range_res and configuration_azimuths\nExiting..."; } } void PublishPointcloud(cv_bridge::CvImagePtr &cv_polar_image, uint16_t &pcl_threshold_value, uint16_t &maxangle, float &range_res) { float theta; cv::Mat navigation_image = (cv_polar_image->image - (double)pcl_threshold_value) * 255.0 / (255.0 - pcl_threshold_value); pcl::PointCloud<pcl::PointXYZI>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZI>); for (int bearing = 0; bearing < cv_polar_image->image.rows; bearing++) { theta = ((float)(bearing) / cv_polar_image->image.rows) * 2 * M_PI; for (size_t ind =1; ind < cv_polar_image->image.cols; ind++) { pcl::PointXYZI p; if ((theta < maxangle * M_PI / 180) || (theta > 2 * M_PI - maxangle * M_PI / 180)) { //The coordinate of the point is taken from the depth map //Y and Z taken negative to immediately visualize the cloud in the right way p.x = range_res * ind * cos(theta); p.y = range_res * ind * sin(theta); //Coloring the point with the corrispondent point in the rectified image p.intensity = navigation_image.at<uchar>(bearing, ind); p.z = 0;//((float)p.intensity / 64);//0; // Uncomment to make height of pixel proportional to Radar cross sectional area ((float)p.intensity / 32); } //Insert point in the cloud, cutting the points that are too distant if (cv_polar_image->image.at<uchar>(bearing, ind) > pcl_threshold_value) cloud->points.push_back(p); } } cloud->width = (int)cloud->points.size(); cloud->height = 1; cloud->header.frame_id = "navtech"; pcl_conversions::toPCL(cv_polar_image->header.stamp,cloud->header.stamp);//pcl_conversions::toPCL(cv_polar_image->header.stamp,cloud->header.stamp); PointcloudPublisher.publish(cloud); } void PublishLaserScan2(cv::Mat &new_im2,float range_resolution, uint16_t range_bins, uint16_t ScanAzimuths, int radarbins,cv_bridge::CvImagePtr &cv_polar_image) { sensor_msgs::LaserScan scan2; scan2.angle_increment = 2 * M_PI / (float)ScanAzimuths; scan2.time_increment = 1 / ((float)4 * (float)ScanAzimuths); scan2.scan_time = 1 / (float)4; scan2.range_min = 0.0; scan2.range_max = 500.0; //Set MaxRange of Scan scan2.ranges.resize(ScanAzimuths); std::cout<<"\nrange_bins, radar_bins: "<<range_bins<<", "<<radarbins; for (int i = 0; i <ScanAzimuths; i++) //all azimuths { for (int j = 30; j < range_bins; j++) //bin ranges { if (j == range_bins - 2) { scan2.ranges[i] = (float)j * range_resolution*(float)range_bins/(float)radarbins; break; } if (new_im2.at<uchar>(i, j) == 0) //if no edge is at this location, carry on searching along azimuth { } else //else, an edge is there - assign edge value { scan2.ranges[i] = (float)j * range_resolution*(float)range_bins / (float)radarbins; break; } } } scan2.header.stamp=cv_polar_image->header.stamp;//cv_polar_image->header.stamp; scan2.header.frame_id = "navtech"; LaserScanPublisher2.publish(scan2); } // void PublishProcessedImage(cv_bridge::CvImagePtr &Input_cv_image){ // cv::Mat radar_image_polar_copy ; // Input_cv_image->image.copyTo(radar_image_polar_copy); // cv::Mat maskmat(Input_cv_image->image.size(),CV_8UC1); // uint16_t cartesian_rows = Input_cv_image->image.cols; // uint16_t cartesian_cols = Input_cv_image->image.cols; // cv::Mat radar_image_cart = cv::Mat::zeros(cartesian_rows, cartesian_cols, CV_8UC1); // cv::Point2f center((float)cartesian_cols / 2, (float)cartesian_rows / 2); // double maxRadius = min(center.y, center.x); // int flags = cv::INTER_LINEAR + cv::WARP_FILL_OUTLIERS; // if(radarimageprocessing){ // cv::GaussianBlur(radar_image_polar_copy, radar_image_polar_copy, cvSize(gaussian_value * 2 + 1, gaussian_value * 2 + 1), 0); // cv::Mat processed_im; // cv::threshold(radar_image_polar_copy, radar_image_polar_copy, threshold_value, 255, CV_THRESH_TOZERO); // cv::Canny(radar_image_polar_copy, radar_image_polar_copy, 50, 100); // cv::dilate(radar_image_polar_copy, radar_image_polar_copy, cv::getStructuringElement(cv::MORPH_RECT, cvSize(dilation_value + 1, dilation_value + 1))); // std::vector<std::vector<cv::Point>> contours; // cv::findContours(radar_image_polar_copy, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE); //Save only outer contours // cv::drawContours(maskmat, contours, -1, 255, -1); // cv::warpPolar(maskmat, radar_image_cart, radar_image_cart.size(), center, maxRadius, flags + cv::WARP_INVERSE_MAP); // } // else{ // cv::warpPolar(radar_image_polar_copy, radar_image_cart, radar_image_cart.size(), center, maxRadius, flags + cv::WARP_INVERSE_MAP); // } // cv::rotate(radar_image_cart, radar_image_cart, cv::ROTATE_90_COUNTERCLOCKWISE); // cv::bitwise_not(radar_image_cart,radar_image_cart); // cv::Mat radar_image_color; // cv::applyColorMap(radar_image_cart, radar_image_color, colormap); // if (grid){ // cv::Mat radar_grid; // grid_width = radar_image_color.size().width; // grid_height = radar_image_color.size().height; // radar_image_color.copyTo(radar_grid); // int start_point_y = (grid_height / 2) % grid_stepSize_m; // int start_point_x = (grid_width / 2) % grid_stepSize_m; // for (int i = start_point_y; i < grid_height; i += grid_stepSize_m) // cv::line(radar_grid, Point(0, i), Point(grid_width, i), cv::Scalar(255, 255, 255)); // for (int i = start_point_x; i < grid_width; i += grid_stepSize_m) // cv::line(radar_grid, Point(i, 0), Point(i, grid_height), cv::Scalar(255, 255, 255)); // addWeighted(radar_image_color, grid_opacity, radar_grid, 1 - grid_opacity, 0.0, radar_image_color); // } // sensor_msgs::ImagePtr CartesianMsg = cv_bridge::CvImage(Input_cv_image->header, "rgb8", radar_image_color).toImageMsg(); // CartesianPublisher.publish(CartesianMsg); // } void FindEdges2(cv_bridge::CvImagePtr &inputImage,uint16_t &gaussian_value, cv::Mat &OutputMatImage, uint16_t &threshold_value, uint16_t &dilation_value,uint16_t maxangle) { cv::Mat radar_image_rcs; inputImage->image.copyTo(radar_image_rcs); if(adaptive_threshold){ cv::adaptiveThreshold(OutputMatImage,OutputMatImage,255,ADAPTIVE_THRESH_MEAN_C,THRESH_BINARY,adaptive_size*2+1,-(double)level_above_average); } cv::GaussianBlur(inputImage->image, inputImage->image, cvSize(gaussian_value * 2 + 1, gaussian_value * 2 + 1), 0); if(AZIMUTH_AVERAGING){ cv::Mat mean; cv::reduce(inputImage->image,mean,0,CV_REDUCE_AVG,CV_8UC1); inputImage->image.copyTo(OutputMatImage); for(int i=0;i<inputImage->image.rows;i++) { cv::Mat temp_im; cv::threshold(inputImage->image.row(i), inputImage->image.row(i), (int)mean.at<uchar>(0,i)+threshold_value, 255, CV_THRESH_TOZERO); inputImage->image.row(i).copyTo(OutputMatImage.row(i)); } } else { cv::threshold(inputImage->image, OutputMatImage, threshold_value, 255, CV_THRESH_TOZERO); } cv::vconcat(OutputMatImage,OutputMatImage.rowRange(0,5),OutputMatImage); uint16_t deltaRow = inputImage->image.rows/2 - std::round(((float)maxangle/360.0)*(inputImage->image.rows)); OutputMatImage.rowRange(inputImage->image.rows/2 - deltaRow,inputImage->image.rows/2 +deltaRow).setTo(0); cv::Canny(OutputMatImage, OutputMatImage, 50, 100); } void PublishBoundingBoxes(cv_bridge::CvImagePtr &cv_polar_image,cv::Mat &EdgesMat){ cv::dilate(EdgesMat, EdgesMat, cv::getStructuringElement(cv::MORPH_RECT, cvSize(dilation_value + 1, dilation_value + 1))); std::vector<std::vector<cv::Point>> contours; cv::findContours(EdgesMat, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE); //Save only outer contours visualization_msgs::MarkerArray Marker_Array; Marker_Array.markers.resize(contours.size()); cv::Mat radar_image_rcs; cv_polar_image->image.copyTo(radar_image_rcs); //Draw Box Contours Round Features if (MinAreaRect) { geometry_msgs::Point p; p.z=0; for (unsigned int i = 0; i < contours.size(); i++) { Marker_Array.markers[i].header.frame_id = "navtech"; Marker_Array.markers[i].header.stamp = cv_polar_image->header.stamp;//cv_polar_image->header.stamp; Marker_Array.markers[i].action = visualization_msgs::Marker::ADD; Marker_Array.markers[i].type = visualization_msgs::Marker::LINE_STRIP; Marker_Array.markers[i].pose.orientation.w = 1.0; Marker_Array.markers[i].id = i; Marker_Array.markers[i].scale.x = .3; Marker_Array.markers[i].color.b = 0;//1.0; Marker_Array.markers[i].color.a = 1.0; Marker_Array.markers[i].lifetime=ros::Duration(.25); Mat maskmat(radar_image_rcs.size(),CV_8UC1); double minVal; double maxVal; Scalar mean; cv::Point p1,p2; drawContours(maskmat, contours, i, 255, -1); cv::minMaxLoc(radar_image_rcs, &minVal, &maxVal, &p1,&p2, maskmat); mean = cv::mean(radar_image_rcs, maskmat); if(mean[0]>127){mean[0]=127;} Marker_Array.markers[i].color.r = (127+mean[0])/255; Marker_Array.markers[i].color.g = (127-mean[0])/255; cv::RotatedRect rect = cv::minAreaRect(contours[i]); cv::Point2f points[4]; rect.points(points); p.z=1; for (unsigned int j = 0; j<4; j++) { p.y=points[j].x*sin(points[j].y*2*M_PI/(float)azimuths)*range_res; p.x=points[j].x*cos(points[j].y*2*M_PI/(float)azimuths)*range_res; Marker_Array.markers[i].points.push_back(p); } p.y=points[0].x*sin(points[0].y*2*M_PI/(float)azimuths)*range_res; p.x=points[0].x*cos(points[0].y*2*M_PI/(float)azimuths)*range_res; Marker_Array.markers[i].points.push_back(p); Marker_Array.markers.push_back(Marker_Array.markers[i]); } } else{ for (unsigned int i = 0; i < contours.size(); i++) { Marker_Array.markers[i].header.frame_id = "navtech"; Marker_Array.markers[i].header.stamp = cv_polar_image->header.stamp; Marker_Array.markers[i].action = visualization_msgs::Marker::ADD; Marker_Array.markers[i].pose.orientation.w = 1.0; Marker_Array.markers[i].id = i; Marker_Array.markers[i].type = visualization_msgs::Marker::LINE_LIST; Marker_Array.markers[i].scale.x = .2; Marker_Array.markers[i].scale.z = 1,0; Marker_Array.markers[i].color.b = 0;//1.0; Marker_Array.markers[i].color.a = 1.0; Marker_Array.markers[i].lifetime=ros::Duration(.25); std::vector<cv::Point> boundingContour; geometry_msgs::Point p; p.z=0; cv::Mat maskmat(radar_image_rcs.size(),CV_8UC1); double minVal; double maxVal; Scalar mean; cv::Point p1,p2; drawContours(maskmat, contours, i, 255, -1); cv::minMaxLoc(radar_image_rcs, &minVal, &maxVal, &p1,&p2, maskmat); mean = cv::mean(radar_image_rcs, maskmat); if(mean[0]>127){mean[0]=127;} if(mean[0]<50){mean[0]=50;} Marker_Array.markers[i].color.r = (mean[0]-50)/(127-50); Marker_Array.markers[i].color.g = 1.0-(mean[0]-50)/(127-50); for (int k=0;k<10;k++) { for (unsigned int j = 0; j<contours[i].size(); ++j) { p.y=(contours[i][j].x*sin_values[contours[i][j].y])*range_res; p.x=(contours[i][j].x*cos_values[contours[i][j].y])*range_res; Marker_Array.markers[i].points.push_back(p); if(j+1<contours[i].size()) { p.y=(contours[i][j+1].x*sin_values[contours[i][j+1].y])*range_res; p.x=(contours[i][j+1].x*cos_values[contours[i][j+1].y])*range_res; } else { p.y=(contours[i][0].x*sin_values[contours[i][0].y])*range_res; p.x=(contours[i][0].x*cos_values[contours[i][0].y])*range_res; } Marker_Array.markers[i].points.push_back(p); } p.z=p.z+.2; } Marker_Array.markers.push_back(Marker_Array.markers[i]); } } MarkerPub.publish(Marker_Array); } void createThreeDPointCloud(cv::Mat &edgesMatInput,float range_resolution, uint16_t range_bins,uint16_t scanAzimuths,cv_bridge::CvImagePtr &cv_polar_image,uint16_t &maxangle){ last_Phi=Phi; for (int i = 0; i <scanAzimuths; i++) //all azimuths { float theta = 2*M_PI* i/scanAzimuths; pcl::PointXYZI p; for (int j = 30; j < range_bins; j++) //bin ranges { if (edgesMatInput.at<uchar>(i, j) == 0) //if no edge is at this location, carry on searching along azimuth { } else //else, an edge is there - assign edge value { if ((theta < maxangle * M_PI / 180) || (theta > 2 * M_PI - maxangle * M_PI / 180)){ p.x =(float)j * range_resolution* cos(theta); p.y = (float)j * range_resolution* sin(theta) * cos(Phi*M_PI/180); p.z = (float)j * range_resolution* sin(theta) * sin(Phi*M_PI/180); //Coloring the point with the corrispondent point in the rectified image if (p.z>18){ p.intensity=255;} if (p.z<-2){ p.intensity=0;} p.intensity = (int)((p.z+2)*255)/20; threeDPCL->points.push_back(p); } break; } } } } void ParamCallback(nav_ross::dynamic_paramConfig &config, uint32_t level){ Phi = config.Phi; ThreeDScanApp = config.ThreeDScanApp; threshold_value = config.threshold_value; dilation_value = config.dilation_value; gaussian_value = config.gaussian_value; pcl_threshold_value = config.pcl_threshold_value; maxangle = config.maxangle; colormap = config.colormap; boundingboxes2 = config.boundingboxes2; MinAreaRect = config.MinAreaRect; longtermaverage = config.longtermaverage; LaserScan2 = config.LaserScan2_Map; pointcloud = config.pointcloud; radarimage=config.radarimage; radarimageprocessing=config.radarimageprocessing; grid = config.grid; adaptive_threshold=config.adaptive_threshold; level_above_average=config.level_above_average; adaptive_size=config.adaptive_size; if (grid == true){ grid_stepSize = config.grid_stepSize; grid_stepSize_m = grid_stepSize / (range_res * 2); grid_opacity = config.grid_opacity; } } void ChatterCallback(const sensor_msgs::ImageConstPtr &radar_image_polar) { // TimerROS ProcessingTime; cv_bridge::CvImagePtr cv_polar_image; cv_polar_image = cv_bridge::toCvCopy(radar_image_polar, sensor_msgs::image_encodings::MONO8); cv_polar_image->header.stamp=radar_image_polar->header.stamp; uint16_t bins = cv_polar_image->image.rows; //uint16_t azimuths = cv_polar_image->image.cols; rotate(cv_polar_image->image, cv_polar_image->image, cv::ROTATE_90_COUNTERCLOCKWISE); cv::normalize(cv_polar_image->image, cv_polar_image->image, 0, 255, NORM_MINMAX, CV_8UC1); cv::Mat edges_Mat; if (pointcloud == true){ PublishPointcloud(cv_polar_image,pcl_threshold_value,maxangle,range_res); } // if(radarimage){ // //if(initialisedaverage){ // // cv_polar_image->image = Long_Term_Average;} // PublishProcessedImage(cv_polar_image); // } if(longtermaverage){ if(initialisedaverage){ Long_Term_Average = .9*Long_Term_Average + .1*cv_polar_image->image; cv_polar_image->image = cv_polar_image->image-Long_Term_Average; } else{ Long_Term_Average = cv_polar_image->image; initialisedaverage=true; } } else{initialisedaverage=false;} if(boundingboxes2 || LaserScan2 || ThreeDScanApp){ FindEdges2(cv_polar_image,gaussian_value,edges_Mat,threshold_value,dilation_value,maxangle); } if (boundingboxes2 == true){ PublishBoundingBoxes(cv_polar_image,edges_Mat); } if (LaserScan2 == true){ PublishLaserScan2(edges_Mat, range_res, edges_Mat.cols, edges_Mat.rows, bins,cv_polar_image); } if(boundingboxes2 || LaserScan2){ sensor_msgs::ImagePtr FilteredMsg = cv_bridge::CvImage(cv_polar_image->header, "mono8", edges_Mat).toImageMsg(); FilteredPublisher.publish(FilteredMsg); } if(ThreeDScanApp){ if(Phi != last_Phi){ createThreeDPointCloud(edges_Mat,range_res,edges_Mat.cols,edges_Mat.rows,cv_polar_image,maxangle); } threeDPCL->width = (int)threeDPCL->points.size(); threeDPCL->height = 1; threeDPCL->header.frame_id = "navtech"; pcl_conversions::toPCL(cv_polar_image->header.stamp,threeDPCL->header.stamp);//pcl_conversions::toPCL(cv_polar_image->header.stamp,cloud->header.stamp); PointcloudPublisher3d.publish(threeDPCL); } } int main(int argc, char **argv) { ros::init(argc, argv, "Mapper_V2"); ROS_INFO("initialized = true"); ros::NodeHandle n; ros::NodeHandle n1; InitialiseParameters(range_res,azimuths); ros::Subscriber sub2; sub2 = n.subscribe("talker1/Navtech/Polar", 10, ChatterCallback); ROS_INFO("subscribed = true"); image_transport::ImageTransport it(n1); CartesianPublisher = it.advertise("Navtech/Cartesian1", 10); FilteredPublisher = it.advertise("Navtech/Filtered", 10); LaserScanPublisher2 = n1.advertise<sensor_msgs::LaserScan>("Navtech/scan3", 1); PointcloudPublisher = n1.advertise<sensor_msgs::PointCloud2>("Navtech/FilteredPointcloud", 1); PointcloudPublisher3d = n1.advertise<sensor_msgs::PointCloud2>("Navtech/3dPCL", 1); MarkerPub = n1.advertise<visualization_msgs::MarkerArray>("visualization_markers",100); dynamic_reconfigure::Server<nav_ross::dynamic_paramConfig> srv; dynamic_reconfigure::Server<nav_ross::dynamic_paramConfig>::CallbackType f; f = boost::bind(&ParamCallback, _1, _2); srv.setCallback(f); ros::spin(); ROS_INFO("spinning = true"); return 0; }
39.656897
245
0.677449
norlab-ulaval
bd5506aa474c31782c9b4bad560841be06bf25d2
52
cpp
C++
TRAVELLING SALESMAN PROBLEM/stdafx.cpp
Emperor86/racheal-folusho
b1ed0dbc71e7f696ade23c8042d17718ebd2fb2f
[ "MIT" ]
null
null
null
TRAVELLING SALESMAN PROBLEM/stdafx.cpp
Emperor86/racheal-folusho
b1ed0dbc71e7f696ade23c8042d17718ebd2fb2f
[ "MIT" ]
null
null
null
TRAVELLING SALESMAN PROBLEM/stdafx.cpp
Emperor86/racheal-folusho
b1ed0dbc71e7f696ade23c8042d17718ebd2fb2f
[ "MIT" ]
null
null
null
////For precompiled headers #include "stdafx.h"
13
28
0.673077
Emperor86
bd5561a3c355f33ea27f417e351e0457091c9bf9
2,047
cpp
C++
luogu/codes/P4783.cpp
Tony031218/OI
562f5f45d0448f4eab77643b99b825405a123d92
[ "MIT" ]
1
2021-02-22T03:39:24.000Z
2021-02-22T03:39:24.000Z
luogu/codes/P4783.cpp
Tony031218/OI
562f5f45d0448f4eab77643b99b825405a123d92
[ "MIT" ]
null
null
null
luogu/codes/P4783.cpp
Tony031218/OI
562f5f45d0448f4eab77643b99b825405a123d92
[ "MIT" ]
null
null
null
/************************************************************* * > File Name : P4783.cpp * > Author : Tony * > Created Time : 2019/05/18 00:14:50 **************************************************************/ #include <bits/stdc++.h> using namespace std; typedef long long LL; const LL mod = 1e9 + 7; const int maxn = 410; long long a[maxn][maxn]; int n, is[maxn], js[maxn]; void exgcd(LL a, LL b, LL& d, LL& x, LL& y) { if (!b) { d = a; x = 1; y = 0; } else { exgcd(b, a % b, d, y, x); y -= x * (a / b); } } LL inv(LL a, LL n) { LL d, x, y; exgcd(a, n, d, x, y); return d == 1 ? (x + n) % n : -1; } void inv() { for (int k = 1; k <= n; ++k) { for (int i = k; i <= n; ++i) { for (int j = k; j <= n; ++j) { if (a[i][j]) { is[k] = i; js[k] = j; break; } } } for (int i = 1; i <= n; ++i) swap(a[k][i], a[is[k]][i]); for (int i = 1; i <= n; ++i) swap(a[i][k], a[i][js[k]]); if (!a[k][k]) { printf("No Solution\n"); exit(0); } a[k][k] = inv(a[k][k], mod); for (int j = 1; j <= n; ++j) if (j != k) (a[k][j] *= a[k][k]) %= mod; for (int i = 1; i <= n; ++i) if (i != k) for (int j = 1; j <= n; ++j) if (j != k) (a[i][j] += mod - a[i][k] * a[k][j] % mod) %= mod; for (int i = 1; i <= n; ++i) if (i != k) a[i][k] = (mod - a[i][k] * a[k][k] % mod) % mod; } for (int k = n; k; --k) { for (int i = 1; i <= n; ++i) swap(a[js[k]][i], a[k][i]); for (int i = 1; i <= n; ++i) swap(a[i][is[k]], a[i][k]); } } int main() { scanf("%d", &n); for (int i = 1; i <= n; ++i) { for (int j = 1; j <= n; ++j) { scanf("%lld", &a[i][j]); } } inv(); for (int i = 1; i <= n; ++i) { for (int j = 1; j <= n; ++j) { printf("%lld ", a[i][j]); } printf("\n"); } return 0; }
28.041096
78
0.31998
Tony031218
32e80c663cdd87684b96a42b9d99fb19fdf8e349
1,628
hpp
C++
mod/wrd/frame/thread.hpp
kniz/World
13b0c8c7fdc6280efcb2135dc3902754a34e6d06
[ "MIT" ]
1
2019-02-02T07:07:32.000Z
2019-02-02T07:07:32.000Z
mod/wrd/frame/thread.hpp
kniz/World
13b0c8c7fdc6280efcb2135dc3902754a34e6d06
[ "MIT" ]
25
2016-09-23T16:36:19.000Z
2019-02-12T14:14:32.000Z
mod/wrd/frame/thread.hpp
kniz/World
13b0c8c7fdc6280efcb2135dc3902754a34e6d06
[ "MIT" ]
null
null
null
#pragma once #include "../builtin/container/mgd/tarr.hpp" #include "../builtin/container/native/tnmap.hpp" #include "frame.hpp" namespace wrd { class slotLoader; typedef tnarr<frame> frames; class _wout thread : public node { WRD(CLASS(thread, node), FRIEND_VERIFY(defAssignExpr, isDefinable), FRIEND_VERIFY(defVarExpr, defineVariable)) friend class baseObj; // for frames. friend class mgdFunc; // for frames. friend class blockExpr; // for frames. friend class defVarExpr; // for frames friend class defAssignExpr; friend class assignExpr; friend class verifier; friend class returnExpr; friend class runExpr; friend class func; // for frames. private: thread(); thread(const node& root); public: const frames& getFrames() const WRD_UNCONST_FUNC(_getFrames()) const frame& getNowFrame() const WRD_UNCONST_FUNC(_getNowFrame()) static thread& get(); static const instancer& getInstancer(); // node: nbicontainer& subs() override; wbool canRun(const ucontainable& args) const override; str run(const ucontainable& args) override; void rel() override; /// @return slot instances loaded by internal system. /// you can cast these to 'slot' types. const nmap& getSlots() const; protected: frames& _getFrames(); frame& _getNowFrame(); private: static thread** _get(); private: frames _frames; str _root; }; }
25.4375
73
0.613022
kniz
32e83204e9a70e8224dd58e8583c3ed4be2e4923
5,823
cc
C++
log/checkpoint_sender.cc
QiumingLu/dawn
58ebdb0d5389f6e3244c91aa09f20a7a47ee8042
[ "BSD-3-Clause" ]
13
2016-12-02T17:00:39.000Z
2020-11-24T08:24:43.000Z
log/checkpoint_sender.cc
QiumingLu/dawn
58ebdb0d5389f6e3244c91aa09f20a7a47ee8042
[ "BSD-3-Clause" ]
1
2018-06-12T05:18:57.000Z
2018-06-12T09:31:05.000Z
log/checkpoint_sender.cc
QiumingLu/dawn
58ebdb0d5389f6e3244c91aa09f20a7a47ee8042
[ "BSD-3-Clause" ]
2
2018-02-01T04:17:38.000Z
2020-04-26T10:21:06.000Z
// Copyright (c) 2016 Mirants Lu. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "log/checkpoint_sender.h" #include <vector> #include "log/checkpoint_manager.h" #include "paxos/config.h" #include "skywalker/file.h" #include "skywalker/logging.h" namespace skywalker { CheckpointSender::CheckpointSender(Config* config, CheckpointManager* manager) : config_(config), manager_(manager), receiver_node_id_(0), sequence_id_(0), ack_sequence_id_(0), flag_(true) {} CheckpointSender::~CheckpointSender() {} bool CheckpointSender::SendCheckpoint(uint64_t node_id) { receiver_node_id_ = node_id; sequence_id_ = 0; ack_sequence_id_ = 0; flag_ = true; bool res = config_->GetCheckpoint()->LockCheckpoint(config_->GetGroupId()); if (res) { uint64_t instance_id = manager_->GetCheckpointInstanceId(); BeginToSend(instance_id); res = SendCheckpointFiles(instance_id); if (res) { EndToSend(instance_id); } else { LOG_ERROR("Group %u - send checkpoint failed.", config_->GetGroupId()); } config_->GetCheckpoint()->UnLockCheckpoint(config_->GetGroupId()); } else { LOG_WARN("Group %u - lock checkpoint failed.", config_->GetGroupId()); } return res; } void CheckpointSender::BeginToSend(uint64_t instance_id) { Content content; content.set_type(CHECKPOINT_MESSAGE); content.set_group_id(config_->GetGroupId()); CheckpointMessage* begin = content.mutable_checkpoint_msg(); begin->set_type(CHECKPOINT_BEGIN); begin->set_node_id(config_->GetNodeId()); begin->set_instance_id(instance_id); begin->set_sequence_id(sequence_id_++); config_->GetMessager()->SendMessage(receiver_node_id_, content); } bool CheckpointSender::SendCheckpointFiles(uint64_t instance_id) { bool res = true; std::string dir; std::vector<std::string> files; const std::vector<StateMachine*>& machines = config_->GetStateMachines(); for (auto& machine : machines) { files.clear(); res = config_->GetCheckpoint()->GetCheckpoint( config_->GetGroupId(), machine->machine_id(), &dir, &files); if (!res) { LOG_ERROR("Group %u - get checkpoint failed, the machine_id=%d.", config_->GetGroupId(), machine->machine_id()); return res; } if (dir.empty() || files.empty()) { continue; } if (dir[dir.size() - 1] != '/') { dir += '/'; } for (auto& file : files) { res = SendFile(instance_id, machine->machine_id(), dir, file); if (!res) { LOG_ERROR("Group %u - send file failed, the file=%s%s.", config_->GetGroupId(), dir.c_str(), file.c_str()); break; } } } return res; } bool CheckpointSender::SendFile(uint64_t instance_id, int machine_id, const std::string& dir, const std::string& file) { std::string fname = dir + file; SequentialFile* seq_file; Status s = FileManager::Instance()->NewSequentialFile(fname, &seq_file); if (!s.ok()) { LOG_ERROR("Group %u - %s", config_->GetGroupId(), s.ToString().c_str()); return false; } bool res = true; size_t offset = 0; Content content; content.set_type(CHECKPOINT_MESSAGE); content.set_group_id(config_->GetGroupId()); CheckpointMessage* msg = content.mutable_checkpoint_msg(); msg->set_type(CHECKPOINT_FILE); msg->set_node_id(config_->GetNodeId()); msg->set_instance_id(instance_id); msg->set_machine_id(machine_id); msg->set_file(file); while (res) { Slice fragmenet; s = seq_file->Read(kBufferSize, &fragmenet, buffer_); if (!s.ok()) { res = false; LOG_ERROR("Group %u - %s", config_->GetGroupId(), s.ToString().c_str()); break; } if (fragmenet.empty()) { break; } offset += fragmenet.size(); msg->set_sequence_id(sequence_id_++); msg->set_offset(offset); msg->set_data(fragmenet.data(), fragmenet.size()); config_->GetMessager()->SendMessage(receiver_node_id_, content); res = CheckReceive(); } delete seq_file; return res; } void CheckpointSender::EndToSend(uint64_t instance_id) { Content content; content.set_type(CHECKPOINT_MESSAGE); content.set_group_id(config_->GetGroupId()); CheckpointMessage* end = content.mutable_checkpoint_msg(); end->set_type(CHECKPOINT_END); end->set_node_id(config_->GetNodeId()); end->set_instance_id(instance_id); end->set_sequence_id(sequence_id_); config_->GetMessager()->SendMessage(receiver_node_id_, content); } void CheckpointSender::OnComfirmReceive(const CheckpointMessage& msg) { std::unique_lock<std::mutex> lock(mutex_); if (msg.node_id() == receiver_node_id_ && msg.sequence_id() == ack_sequence_id_) { ++ack_sequence_id_; flag_ = msg.flag(); cond_.notify_one(); } else { LOG_WARN( "Group %u - receive a confirm message, " "which node_id = %llu, sequence_id=%d, " "but my sender_node_id_=%llu, ack_sequence_id_=%d.", config_->GetGroupId(), (unsigned long long)msg.node_id(), msg.sequence_id(), (unsigned long long)receiver_node_id_, ack_sequence_id_); } } bool CheckpointSender::CheckReceive() { bool res = true; std::unique_lock<std::mutex> lock(mutex_); while (flag_ && (sequence_id_ > ack_sequence_id_ + 16)) { std::cv_status cs = cond_.wait_for(lock, std::chrono::microseconds(10 * 1000 * 1000)); if (cs == std::cv_status::timeout) { LOG_ERROR("Group %u - receive comfirm message timeout!", config_->GetGroupId()); break; } } if (!flag_) { LOG_ERROR("Group %u - error happen.", config_->GetGroupId()); res = false; } return res; } } // namespace skywalker
30.170984
78
0.660484
QiumingLu
32eb7af8480ec3cf7a6c4bbbd4a80d38ebd6377c
39,341
cpp
C++
src/script/lua_api/l_mapgen.cpp
crazyBaboon/MathWorlds
dd35e88e207a26be8632999ad09eeef81820343d
[ "CC-BY-4.0" ]
1
2018-03-01T13:03:01.000Z
2018-03-01T13:03:01.000Z
src/script/lua_api/l_mapgen.cpp
crazyBaboon/MathWorlds
dd35e88e207a26be8632999ad09eeef81820343d
[ "CC-BY-4.0" ]
null
null
null
src/script/lua_api/l_mapgen.cpp
crazyBaboon/MathWorlds
dd35e88e207a26be8632999ad09eeef81820343d
[ "CC-BY-4.0" ]
null
null
null
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> 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 2.1 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 should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "lua_api/l_mapgen.h" #include "lua_api/l_internal.h" #include "lua_api/l_vmanip.h" #include "common/c_converter.h" #include "common/c_content.h" #include "cpp_api/s_security.h" #include "util/serialize.h" #include "server.h" #include "environment.h" #include "emerge.h" #include "mg_biome.h" #include "mg_ore.h" #include "mg_decoration.h" #include "mg_schematic.h" #include "mapgen_v5.h" #include "mapgen_v7.h" #include "filesys.h" #include "settings.h" #include "log.h" struct EnumString ModApiMapgen::es_BiomeTerrainType[] = { {BIOMETYPE_NORMAL, "normal"}, {BIOMETYPE_LIQUID, "liquid"}, {BIOMETYPE_NETHER, "nether"}, {BIOMETYPE_AETHER, "aether"}, {BIOMETYPE_FLAT, "flat"}, {0, NULL}, }; struct EnumString ModApiMapgen::es_DecorationType[] = { {DECO_SIMPLE, "simple"}, {DECO_SCHEMATIC, "schematic"}, {DECO_LSYSTEM, "lsystem"}, {0, NULL}, }; struct EnumString ModApiMapgen::es_MapgenObject[] = { {MGOBJ_VMANIP, "voxelmanip"}, {MGOBJ_HEIGHTMAP, "heightmap"}, {MGOBJ_BIOMEMAP, "biomemap"}, {MGOBJ_HEATMAP, "heatmap"}, {MGOBJ_HUMIDMAP, "humiditymap"}, {MGOBJ_GENNOTIFY, "gennotify"}, {0, NULL}, }; struct EnumString ModApiMapgen::es_OreType[] = { {ORE_SCATTER, "scatter"}, {ORE_SHEET, "sheet"}, {ORE_PUFF, "puff"}, {ORE_BLOB, "blob"}, {ORE_VEIN, "vein"}, {0, NULL}, }; struct EnumString ModApiMapgen::es_Rotation[] = { {ROTATE_0, "0"}, {ROTATE_90, "90"}, {ROTATE_180, "180"}, {ROTATE_270, "270"}, {ROTATE_RAND, "random"}, {0, NULL}, }; struct EnumString ModApiMapgen::es_SchematicFormatType[] = { {SCHEM_FMT_HANDLE, "handle"}, {SCHEM_FMT_MTS, "mts"}, {SCHEM_FMT_LUA, "lua"}, {0, NULL}, }; ObjDef *get_objdef(lua_State *L, int index, ObjDefManager *objmgr); Biome *get_or_load_biome(lua_State *L, int index, BiomeManager *biomemgr); Biome *read_biome_def(lua_State *L, int index, INodeDefManager *ndef); size_t get_biome_list(lua_State *L, int index, BiomeManager *biomemgr, UNORDERED_SET<u8> *biome_id_list); Schematic *get_or_load_schematic(lua_State *L, int index, SchematicManager *schemmgr, StringMap *replace_names); Schematic *load_schematic(lua_State *L, int index, INodeDefManager *ndef, StringMap *replace_names); Schematic *load_schematic_from_def(lua_State *L, int index, INodeDefManager *ndef, StringMap *replace_names); bool read_schematic_def(lua_State *L, int index, Schematic *schem, std::vector<std::string> *names); bool read_deco_simple(lua_State *L, DecoSimple *deco); bool read_deco_schematic(lua_State *L, SchematicManager *schemmgr, DecoSchematic *deco); /////////////////////////////////////////////////////////////////////////////// ObjDef *get_objdef(lua_State *L, int index, ObjDefManager *objmgr) { if (index < 0) index = lua_gettop(L) + 1 + index; // If a number, assume this is a handle to an object def if (lua_isnumber(L, index)) return objmgr->get(lua_tointeger(L, index)); // If a string, assume a name is given instead if (lua_isstring(L, index)) return objmgr->getByName(lua_tostring(L, index)); return NULL; } /////////////////////////////////////////////////////////////////////////////// Schematic *get_or_load_schematic(lua_State *L, int index, SchematicManager *schemmgr, StringMap *replace_names) { if (index < 0) index = lua_gettop(L) + 1 + index; Schematic *schem = (Schematic *)get_objdef(L, index, schemmgr); if (schem) return schem; schem = load_schematic(L, index, schemmgr->getNodeDef(), replace_names); if (!schem) return NULL; if (schemmgr->add(schem) == OBJDEF_INVALID_HANDLE) { delete schem; return NULL; } return schem; } Schematic *load_schematic(lua_State *L, int index, INodeDefManager *ndef, StringMap *replace_names) { if (index < 0) index = lua_gettop(L) + 1 + index; Schematic *schem = NULL; if (lua_istable(L, index)) { schem = load_schematic_from_def(L, index, ndef, replace_names); if (!schem) { delete schem; return NULL; } } else if (lua_isnumber(L, index)) { return NULL; } else if (lua_isstring(L, index)) { schem = SchematicManager::create(SCHEMATIC_NORMAL); std::string filepath = lua_tostring(L, index); if (!fs::IsPathAbsolute(filepath)) filepath = ModApiBase::getCurrentModPath(L) + DIR_DELIM + filepath; if (!schem->loadSchematicFromFile(filepath, ndef, replace_names)) { delete schem; return NULL; } } return schem; } Schematic *load_schematic_from_def(lua_State *L, int index, INodeDefManager *ndef, StringMap *replace_names) { Schematic *schem = SchematicManager::create(SCHEMATIC_NORMAL); if (!read_schematic_def(L, index, schem, &schem->m_nodenames)) { delete schem; return NULL; } size_t num_nodes = schem->m_nodenames.size(); schem->m_nnlistsizes.push_back(num_nodes); if (replace_names) { for (size_t i = 0; i != num_nodes; i++) { StringMap::iterator it = replace_names->find(schem->m_nodenames[i]); if (it != replace_names->end()) schem->m_nodenames[i] = it->second; } } if (ndef) ndef->pendNodeResolve(schem); return schem; } bool read_schematic_def(lua_State *L, int index, Schematic *schem, std::vector<std::string> *names) { if (!lua_istable(L, index)) return false; //// Get schematic size lua_getfield(L, index, "size"); v3s16 size = check_v3s16(L, -1); lua_pop(L, 1); schem->size = size; //// Get schematic data lua_getfield(L, index, "data"); luaL_checktype(L, -1, LUA_TTABLE); u32 numnodes = size.X * size.Y * size.Z; schem->schemdata = new MapNode[numnodes]; size_t names_base = names->size(); UNORDERED_MAP<std::string, content_t> name_id_map; u32 i = 0; for (lua_pushnil(L); lua_next(L, -2); i++, lua_pop(L, 1)) { if (i >= numnodes) continue; //// Read name std::string name; if (!getstringfield(L, -1, "name", name)) throw LuaError("Schematic data definition with missing name field"); //// Read param1/prob u8 param1; if (!getintfield(L, -1, "param1", param1) && !getintfield(L, -1, "prob", param1)) param1 = MTSCHEM_PROB_ALWAYS_OLD; //// Read param2 u8 param2 = getintfield_default(L, -1, "param2", 0); //// Find or add new nodename-to-ID mapping UNORDERED_MAP<std::string, content_t>::iterator it = name_id_map.find(name); content_t name_index; if (it != name_id_map.end()) { name_index = it->second; } else { name_index = names->size() - names_base; name_id_map[name] = name_index; names->push_back(name); } //// Perform probability/force_place fixup on param1 param1 >>= 1; if (getboolfield_default(L, -1, "force_place", false)) param1 |= MTSCHEM_FORCE_PLACE; //// Actually set the node in the schematic schem->schemdata[i] = MapNode(name_index, param1, param2); } if (i != numnodes) { errorstream << "read_schematic_def: incorrect number of " "nodes provided in raw schematic data (got " << i << ", expected " << numnodes << ")." << std::endl; return false; } //// Get Y-slice probability values (if present) schem->slice_probs = new u8[size.Y]; for (i = 0; i != (u32) size.Y; i++) schem->slice_probs[i] = MTSCHEM_PROB_ALWAYS; lua_getfield(L, index, "yslice_prob"); if (lua_istable(L, -1)) { for (lua_pushnil(L); lua_next(L, -2); lua_pop(L, 1)) { u16 ypos; if (!getintfield(L, -1, "ypos", ypos) || (ypos >= size.Y) || !getintfield(L, -1, "prob", schem->slice_probs[ypos])) continue; schem->slice_probs[ypos] >>= 1; } } return true; } void read_schematic_replacements(lua_State *L, int index, StringMap *replace_names) { if (index < 0) index = lua_gettop(L) + 1 + index; lua_pushnil(L); while (lua_next(L, index)) { std::string replace_from; std::string replace_to; if (lua_istable(L, -1)) { // Old {{"x", "y"}, ...} format lua_rawgeti(L, -1, 1); if (!lua_isstring(L, -1)) throw LuaError("schematics: replace_from field is not a string"); replace_from = lua_tostring(L, -1); lua_pop(L, 1); lua_rawgeti(L, -1, 2); if (!lua_isstring(L, -1)) throw LuaError("schematics: replace_to field is not a string"); replace_to = lua_tostring(L, -1); lua_pop(L, 1); } else { // New {x = "y", ...} format if (!lua_isstring(L, -2)) throw LuaError("schematics: replace_from field is not a string"); replace_from = lua_tostring(L, -2); if (!lua_isstring(L, -1)) throw LuaError("schematics: replace_to field is not a string"); replace_to = lua_tostring(L, -1); } replace_names->insert(std::make_pair(replace_from, replace_to)); lua_pop(L, 1); } } /////////////////////////////////////////////////////////////////////////////// Biome *get_or_load_biome(lua_State *L, int index, BiomeManager *biomemgr) { if (index < 0) index = lua_gettop(L) + 1 + index; Biome *biome = (Biome *)get_objdef(L, index, biomemgr); if (biome) return biome; biome = read_biome_def(L, index, biomemgr->getNodeDef()); if (!biome) return NULL; if (biomemgr->add(biome) == OBJDEF_INVALID_HANDLE) { delete biome; return NULL; } return biome; } Biome *read_biome_def(lua_State *L, int index, INodeDefManager *ndef) { if (!lua_istable(L, index)) return NULL; BiomeType biometype = (BiomeType)getenumfield(L, index, "type", ModApiMapgen::es_BiomeTerrainType, BIOMETYPE_NORMAL); Biome *b = BiomeManager::create(biometype); b->name = getstringfield_default(L, index, "name", ""); b->depth_top = getintfield_default(L, index, "depth_top", 0); b->depth_filler = getintfield_default(L, index, "depth_filler", -31000); b->depth_water_top = getintfield_default(L, index, "depth_water_top", 0); b->depth_riverbed = getintfield_default(L, index, "depth_riverbed", 0); b->y_min = getintfield_default(L, index, "y_min", -31000); b->y_max = getintfield_default(L, index, "y_max", 31000); b->heat_point = getfloatfield_default(L, index, "heat_point", 0.f); b->humidity_point = getfloatfield_default(L, index, "humidity_point", 0.f); b->flags = 0; //reserved std::vector<std::string> &nn = b->m_nodenames; nn.push_back(getstringfield_default(L, index, "node_top", "")); nn.push_back(getstringfield_default(L, index, "node_filler", "")); nn.push_back(getstringfield_default(L, index, "node_stone", "")); nn.push_back(getstringfield_default(L, index, "node_water_top", "")); nn.push_back(getstringfield_default(L, index, "node_water", "")); nn.push_back(getstringfield_default(L, index, "node_river_water", "")); nn.push_back(getstringfield_default(L, index, "node_riverbed", "")); nn.push_back(getstringfield_default(L, index, "node_dust", "")); ndef->pendNodeResolve(b); return b; } size_t get_biome_list(lua_State *L, int index, BiomeManager *biomemgr, UNORDERED_SET<u8> *biome_id_list) { if (index < 0) index = lua_gettop(L) + 1 + index; if (lua_isnil(L, index)) return 0; bool is_single = true; if (lua_istable(L, index)) { lua_getfield(L, index, "name"); is_single = !lua_isnil(L, -1); lua_pop(L, 1); } if (is_single) { Biome *biome = get_or_load_biome(L, index, biomemgr); if (!biome) { infostream << "get_biome_list: failed to get biome '" << (lua_isstring(L, index) ? lua_tostring(L, index) : "") << "'." << std::endl; return 1; } biome_id_list->insert(biome->index); return 0; } // returns number of failed resolutions size_t fail_count = 0; size_t count = 0; for (lua_pushnil(L); lua_next(L, index); lua_pop(L, 1)) { count++; Biome *biome = get_or_load_biome(L, -1, biomemgr); if (!biome) { fail_count++; infostream << "get_biome_list: failed to get biome '" << (lua_isstring(L, -1) ? lua_tostring(L, -1) : "") << "'" << std::endl; continue; } biome_id_list->insert(biome->index); } return fail_count; } /////////////////////////////////////////////////////////////////////////////// // get_biome_id(biomename) // returns the biome id used in biomemap int ModApiMapgen::l_get_biome_id(lua_State *L) { NO_MAP_LOCK_REQUIRED; const char *biome_str = lua_tostring(L, 1); if (!biome_str) return 0; BiomeManager *bmgr = getServer(L)->getEmergeManager()->biomemgr; if (!bmgr) return 0; Biome *biome = (Biome *)bmgr->getByName(biome_str); if (!biome || biome->index == OBJDEF_INVALID_INDEX) return 0; lua_pushinteger(L, biome->index); return 1; } // get_mapgen_object(objectname) // returns the requested object used during map generation int ModApiMapgen::l_get_mapgen_object(lua_State *L) { NO_MAP_LOCK_REQUIRED; const char *mgobjstr = lua_tostring(L, 1); int mgobjint; if (!string_to_enum(es_MapgenObject, mgobjint, mgobjstr ? mgobjstr : "")) return 0; enum MapgenObject mgobj = (MapgenObject)mgobjint; EmergeManager *emerge = getServer(L)->getEmergeManager(); Mapgen *mg = emerge->getCurrentMapgen(); if (!mg) throw LuaError("Must only be called in a mapgen thread!"); size_t maplen = mg->csize.X * mg->csize.Z; switch (mgobj) { case MGOBJ_VMANIP: { MMVManip *vm = mg->vm; // VoxelManip object LuaVoxelManip *o = new LuaVoxelManip(vm, true); *(void **)(lua_newuserdata(L, sizeof(void *))) = o; luaL_getmetatable(L, "VoxelManip"); lua_setmetatable(L, -2); // emerged min pos push_v3s16(L, vm->m_area.MinEdge); // emerged max pos push_v3s16(L, vm->m_area.MaxEdge); return 3; } case MGOBJ_HEIGHTMAP: { if (!mg->heightmap) return 0; lua_newtable(L); for (size_t i = 0; i != maplen; i++) { lua_pushinteger(L, mg->heightmap[i]); lua_rawseti(L, -2, i + 1); } return 1; } case MGOBJ_BIOMEMAP: { if (!mg->biomegen) return 0; lua_newtable(L); for (size_t i = 0; i != maplen; i++) { lua_pushinteger(L, mg->biomegen->biomemap[i]); lua_rawseti(L, -2, i + 1); } return 1; } case MGOBJ_HEATMAP: { if (!mg->biomegen || mg->biomegen->getType() != BIOMEGEN_ORIGINAL) return 0; BiomeGenOriginal *bg = (BiomeGenOriginal *)mg->biomegen; lua_newtable(L); for (size_t i = 0; i != maplen; i++) { lua_pushnumber(L, bg->heatmap[i]); lua_rawseti(L, -2, i + 1); } return 1; } case MGOBJ_HUMIDMAP: { if (!mg->biomegen || mg->biomegen->getType() != BIOMEGEN_ORIGINAL) return 0; BiomeGenOriginal *bg = (BiomeGenOriginal *)mg->biomegen; lua_newtable(L); for (size_t i = 0; i != maplen; i++) { lua_pushnumber(L, bg->humidmap[i]); lua_rawseti(L, -2, i + 1); } return 1; } case MGOBJ_GENNOTIFY: { std::map<std::string, std::vector<v3s16> >event_map; std::map<std::string, std::vector<v3s16> >::iterator it; mg->gennotify.getEvents(event_map); lua_newtable(L); for (it = event_map.begin(); it != event_map.end(); ++it) { lua_newtable(L); for (size_t j = 0; j != it->second.size(); j++) { push_v3s16(L, it->second[j]); lua_rawseti(L, -2, j + 1); } lua_setfield(L, -2, it->first.c_str()); } return 1; } } return 0; } int ModApiMapgen::l_get_mapgen_params(lua_State *L) { NO_MAP_LOCK_REQUIRED; log_deprecated(L, "get_mapgen_params is deprecated; " "use get_mapgen_setting instead"); std::string value; MapSettingsManager *settingsmgr = getServer(L)->getEmergeManager()->map_settings_mgr; lua_newtable(L); settingsmgr->getMapSetting("mg_name", &value); lua_pushstring(L, value.c_str()); lua_setfield(L, -2, "mgname"); settingsmgr->getMapSetting("seed", &value); std::istringstream ss(value); u64 seed; ss >> seed; lua_pushinteger(L, seed); lua_setfield(L, -2, "seed"); settingsmgr->getMapSetting("water_level", &value); lua_pushinteger(L, stoi(value, -32768, 32767)); lua_setfield(L, -2, "water_level"); settingsmgr->getMapSetting("chunksize", &value); lua_pushinteger(L, stoi(value, -32768, 32767)); lua_setfield(L, -2, "chunksize"); settingsmgr->getMapSetting("mg_flags", &value); lua_pushstring(L, value.c_str()); lua_setfield(L, -2, "flags"); return 1; } // set_mapgen_params(params) // set mapgen parameters int ModApiMapgen::l_set_mapgen_params(lua_State *L) { NO_MAP_LOCK_REQUIRED; log_deprecated(L, "set_mapgen_params is deprecated; " "use set_mapgen_setting instead"); if (!lua_istable(L, 1)) return 0; MapSettingsManager *settingsmgr = getServer(L)->getEmergeManager()->map_settings_mgr; lua_getfield(L, 1, "mgname"); if (lua_isstring(L, -1)) settingsmgr->setMapSetting("mg_name", lua_tostring(L, -1), true); lua_getfield(L, 1, "seed"); if (lua_isnumber(L, -1)) settingsmgr->setMapSetting("seed", lua_tostring(L, -1), true); lua_getfield(L, 1, "water_level"); if (lua_isnumber(L, -1)) settingsmgr->setMapSetting("water_level", lua_tostring(L, -1), true); lua_getfield(L, 1, "chunksize"); if (lua_isnumber(L, -1)) settingsmgr->setMapSetting("chunksize", lua_tostring(L, -1), true); warn_if_field_exists(L, 1, "flagmask", "Deprecated: flags field now includes unset flags."); lua_getfield(L, 1, "flags"); if (lua_isstring(L, -1)) settingsmgr->setMapSetting("mg_flags", lua_tostring(L, -1), true); return 0; } // get_mapgen_setting(name) int ModApiMapgen::l_get_mapgen_setting(lua_State *L) { NO_MAP_LOCK_REQUIRED; std::string value; MapSettingsManager *settingsmgr = getServer(L)->getEmergeManager()->map_settings_mgr; const char *name = luaL_checkstring(L, 1); if (!settingsmgr->getMapSetting(name, &value)) return 0; lua_pushstring(L, value.c_str()); return 1; } // get_mapgen_setting_noiseparams(name) int ModApiMapgen::l_get_mapgen_setting_noiseparams(lua_State *L) { NO_MAP_LOCK_REQUIRED; NoiseParams np; MapSettingsManager *settingsmgr = getServer(L)->getEmergeManager()->map_settings_mgr; const char *name = luaL_checkstring(L, 1); if (!settingsmgr->getMapSettingNoiseParams(name, &np)) return 0; push_noiseparams(L, &np); return 1; } // set_mapgen_setting(name, value, override_meta) // set mapgen config values int ModApiMapgen::l_set_mapgen_setting(lua_State *L) { NO_MAP_LOCK_REQUIRED; MapSettingsManager *settingsmgr = getServer(L)->getEmergeManager()->map_settings_mgr; const char *name = luaL_checkstring(L, 1); const char *value = luaL_checkstring(L, 2); bool override_meta = lua_isboolean(L, 3) ? lua_toboolean(L, 3) : false; if (!settingsmgr->setMapSetting(name, value, override_meta)) { errorstream << "set_mapgen_setting: cannot set '" << name << "' after initialization" << std::endl; } return 0; } // set_mapgen_setting_noiseparams(name, noiseparams, set_default) // set mapgen config values for noise parameters int ModApiMapgen::l_set_mapgen_setting_noiseparams(lua_State *L) { NO_MAP_LOCK_REQUIRED; MapSettingsManager *settingsmgr = getServer(L)->getEmergeManager()->map_settings_mgr; const char *name = luaL_checkstring(L, 1); NoiseParams np; if (!read_noiseparams(L, 2, &np)) { errorstream << "set_mapgen_setting_noiseparams: cannot set '" << name << "'; invalid noiseparams table" << std::endl; return 0; } bool override_meta = lua_isboolean(L, 3) ? lua_toboolean(L, 3) : false; if (!settingsmgr->setMapSettingNoiseParams(name, &np, override_meta)) { errorstream << "set_mapgen_setting_noiseparams: cannot set '" << name << "' after initialization" << std::endl; } return 0; } // set_noiseparams(name, noiseparams, set_default) // set global config values for noise parameters int ModApiMapgen::l_set_noiseparams(lua_State *L) { NO_MAP_LOCK_REQUIRED; const char *name = luaL_checkstring(L, 1); NoiseParams np; if (!read_noiseparams(L, 2, &np)) { errorstream << "set_noiseparams: cannot set '" << name << "'; invalid noiseparams table" << std::endl; return 0; } bool set_default = lua_isboolean(L, 3) ? lua_toboolean(L, 3) : true; g_settings->setNoiseParams(name, np, set_default); return 0; } // get_noiseparams(name) int ModApiMapgen::l_get_noiseparams(lua_State *L) { NO_MAP_LOCK_REQUIRED; std::string name = luaL_checkstring(L, 1); NoiseParams np; if (!g_settings->getNoiseParams(name, np)) return 0; push_noiseparams(L, &np); return 1; } // set_gen_notify(flags, {deco_id_table}) int ModApiMapgen::l_set_gen_notify(lua_State *L) { NO_MAP_LOCK_REQUIRED; u32 flags = 0, flagmask = 0; EmergeManager *emerge = getServer(L)->getEmergeManager(); if (read_flags(L, 1, flagdesc_gennotify, &flags, &flagmask)) { emerge->gen_notify_on &= ~flagmask; emerge->gen_notify_on |= flags; } if (lua_istable(L, 2)) { lua_pushnil(L); while (lua_next(L, 2)) { if (lua_isnumber(L, -1)) emerge->gen_notify_on_deco_ids.insert((u32)lua_tonumber(L, -1)); lua_pop(L, 1); } } return 0; } // get_gen_notify() int ModApiMapgen::l_get_gen_notify(lua_State *L) { NO_MAP_LOCK_REQUIRED; EmergeManager *emerge = getServer(L)->getEmergeManager(); push_flags_string(L, flagdesc_gennotify, emerge->gen_notify_on, emerge->gen_notify_on); lua_newtable(L); int i = 1; for (std::set<u32>::iterator it = emerge->gen_notify_on_deco_ids.begin(); it != emerge->gen_notify_on_deco_ids.end(); ++it) { lua_pushnumber(L, *it); lua_rawseti(L, -2, i); i++; } return 2; } // register_biome({lots of stuff}) int ModApiMapgen::l_register_biome(lua_State *L) { NO_MAP_LOCK_REQUIRED; int index = 1; luaL_checktype(L, index, LUA_TTABLE); INodeDefManager *ndef = getServer(L)->getNodeDefManager(); BiomeManager *bmgr = getServer(L)->getEmergeManager()->biomemgr; Biome *biome = read_biome_def(L, index, ndef); if (!biome) return 0; ObjDefHandle handle = bmgr->add(biome); if (handle == OBJDEF_INVALID_HANDLE) { delete biome; return 0; } lua_pushinteger(L, handle); return 1; } // register_decoration({lots of stuff}) int ModApiMapgen::l_register_decoration(lua_State *L) { NO_MAP_LOCK_REQUIRED; int index = 1; luaL_checktype(L, index, LUA_TTABLE); INodeDefManager *ndef = getServer(L)->getNodeDefManager(); DecorationManager *decomgr = getServer(L)->getEmergeManager()->decomgr; BiomeManager *biomemgr = getServer(L)->getEmergeManager()->biomemgr; SchematicManager *schemmgr = getServer(L)->getEmergeManager()->schemmgr; enum DecorationType decotype = (DecorationType)getenumfield(L, index, "deco_type", es_DecorationType, -1); Decoration *deco = decomgr->create(decotype); if (!deco) { errorstream << "register_decoration: decoration placement type " << decotype << " not implemented" << std::endl; return 0; } deco->name = getstringfield_default(L, index, "name", ""); deco->fill_ratio = getfloatfield_default(L, index, "fill_ratio", 0.02); deco->y_min = getintfield_default(L, index, "y_min", -31000); deco->y_max = getintfield_default(L, index, "y_max", 31000); deco->nspawnby = getintfield_default(L, index, "num_spawn_by", -1); deco->sidelen = getintfield_default(L, index, "sidelen", 8); if (deco->sidelen <= 0) { errorstream << "register_decoration: sidelen must be " "greater than 0" << std::endl; delete deco; return 0; } //// Get node name(s) to place decoration on size_t nread = getstringlistfield(L, index, "place_on", &deco->m_nodenames); deco->m_nnlistsizes.push_back(nread); //// Get decoration flags getflagsfield(L, index, "flags", flagdesc_deco, &deco->flags, NULL); //// Get NoiseParams to define how decoration is placed lua_getfield(L, index, "noise_params"); if (read_noiseparams(L, -1, &deco->np)) deco->flags |= DECO_USE_NOISE; lua_pop(L, 1); //// Get biomes associated with this decoration (if any) lua_getfield(L, index, "biomes"); if (get_biome_list(L, -1, biomemgr, &deco->biomes)) infostream << "register_decoration: couldn't get all biomes " << std::endl; lua_pop(L, 1); //// Get node name(s) to 'spawn by' size_t nnames = getstringlistfield(L, index, "spawn_by", &deco->m_nodenames); deco->m_nnlistsizes.push_back(nnames); if (nnames == 0 && deco->nspawnby != -1) { errorstream << "register_decoration: no spawn_by nodes defined," " but num_spawn_by specified" << std::endl; } //// Handle decoration type-specific parameters bool success = false; switch (decotype) { case DECO_SIMPLE: success = read_deco_simple(L, (DecoSimple *)deco); break; case DECO_SCHEMATIC: success = read_deco_schematic(L, schemmgr, (DecoSchematic *)deco); break; case DECO_LSYSTEM: break; } if (!success) { delete deco; return 0; } ndef->pendNodeResolve(deco); ObjDefHandle handle = decomgr->add(deco); if (handle == OBJDEF_INVALID_HANDLE) { delete deco; return 0; } lua_pushinteger(L, handle); return 1; } bool read_deco_simple(lua_State *L, DecoSimple *deco) { int index = 1; int param2; deco->deco_height = getintfield_default(L, index, "height", 1); deco->deco_height_max = getintfield_default(L, index, "height_max", 0); if (deco->deco_height <= 0) { errorstream << "register_decoration: simple decoration height" " must be greater than 0" << std::endl; return false; } size_t nnames = getstringlistfield(L, index, "decoration", &deco->m_nodenames); deco->m_nnlistsizes.push_back(nnames); if (nnames == 0) { errorstream << "register_decoration: no decoration nodes " "defined" << std::endl; return false; } param2 = getintfield_default(L, index, "param2", 0); if ((param2 < 0) || (param2 > 255)) { errorstream << "register_decoration: param2 out of bounds (0-255)" << std::endl; return false; } deco->deco_param2 = (u8)param2; return true; } bool read_deco_schematic(lua_State *L, SchematicManager *schemmgr, DecoSchematic *deco) { int index = 1; deco->rotation = (Rotation)getenumfield(L, index, "rotation", ModApiMapgen::es_Rotation, ROTATE_0); StringMap replace_names; lua_getfield(L, index, "replacements"); if (lua_istable(L, -1)) read_schematic_replacements(L, -1, &replace_names); lua_pop(L, 1); lua_getfield(L, index, "schematic"); Schematic *schem = get_or_load_schematic(L, -1, schemmgr, &replace_names); lua_pop(L, 1); deco->schematic = schem; return schem != NULL; } // register_ore({lots of stuff}) int ModApiMapgen::l_register_ore(lua_State *L) { NO_MAP_LOCK_REQUIRED; int index = 1; luaL_checktype(L, index, LUA_TTABLE); INodeDefManager *ndef = getServer(L)->getNodeDefManager(); BiomeManager *bmgr = getServer(L)->getEmergeManager()->biomemgr; OreManager *oremgr = getServer(L)->getEmergeManager()->oremgr; enum OreType oretype = (OreType)getenumfield(L, index, "ore_type", es_OreType, ORE_SCATTER); Ore *ore = oremgr->create(oretype); if (!ore) { errorstream << "register_ore: ore_type " << oretype << " not implemented\n"; return 0; } ore->name = getstringfield_default(L, index, "name", ""); ore->ore_param2 = (u8)getintfield_default(L, index, "ore_param2", 0); ore->clust_scarcity = getintfield_default(L, index, "clust_scarcity", 1); ore->clust_num_ores = getintfield_default(L, index, "clust_num_ores", 1); ore->clust_size = getintfield_default(L, index, "clust_size", 0); ore->noise = NULL; ore->flags = 0; //// Get noise_threshold warn_if_field_exists(L, index, "noise_threshhold", "Deprecated: new name is \"noise_threshold\"."); float nthresh; if (!getfloatfield(L, index, "noise_threshold", nthresh) && !getfloatfield(L, index, "noise_threshhold", nthresh)) nthresh = 0; ore->nthresh = nthresh; //// Get y_min/y_max warn_if_field_exists(L, index, "height_min", "Deprecated: new name is \"y_min\"."); warn_if_field_exists(L, index, "height_max", "Deprecated: new name is \"y_max\"."); int ymin, ymax; if (!getintfield(L, index, "y_min", ymin) && !getintfield(L, index, "height_min", ymin)) ymin = -31000; if (!getintfield(L, index, "y_max", ymax) && !getintfield(L, index, "height_max", ymax)) ymax = 31000; ore->y_min = ymin; ore->y_max = ymax; if (ore->clust_scarcity <= 0 || ore->clust_num_ores <= 0) { errorstream << "register_ore: clust_scarcity and clust_num_ores" "must be greater than 0" << std::endl; delete ore; return 0; } //// Get flags getflagsfield(L, index, "flags", flagdesc_ore, &ore->flags, NULL); //// Get biomes associated with this decoration (if any) lua_getfield(L, index, "biomes"); if (get_biome_list(L, -1, bmgr, &ore->biomes)) infostream << "register_ore: couldn't get all biomes " << std::endl; lua_pop(L, 1); //// Get noise parameters if needed lua_getfield(L, index, "noise_params"); if (read_noiseparams(L, -1, &ore->np)) { ore->flags |= OREFLAG_USE_NOISE; } else if (ore->NEEDS_NOISE) { errorstream << "register_ore: specified ore type requires valid " "noise parameters" << std::endl; delete ore; return 0; } lua_pop(L, 1); //// Get type-specific parameters switch (oretype) { case ORE_SHEET: { OreSheet *oresheet = (OreSheet *)ore; oresheet->column_height_min = getintfield_default(L, index, "column_height_min", 1); oresheet->column_height_max = getintfield_default(L, index, "column_height_max", ore->clust_size); oresheet->column_midpoint_factor = getfloatfield_default(L, index, "column_midpoint_factor", 0.5f); break; } case ORE_PUFF: { OrePuff *orepuff = (OrePuff *)ore; lua_getfield(L, index, "np_puff_top"); read_noiseparams(L, -1, &orepuff->np_puff_top); lua_pop(L, 1); lua_getfield(L, index, "np_puff_bottom"); read_noiseparams(L, -1, &orepuff->np_puff_bottom); lua_pop(L, 1); break; } case ORE_VEIN: { OreVein *orevein = (OreVein *)ore; orevein->random_factor = getfloatfield_default(L, index, "random_factor", 1.f); break; } default: break; } ObjDefHandle handle = oremgr->add(ore); if (handle == OBJDEF_INVALID_HANDLE) { delete ore; return 0; } ore->m_nodenames.push_back(getstringfield_default(L, index, "ore", "")); size_t nnames = getstringlistfield(L, index, "wherein", &ore->m_nodenames); ore->m_nnlistsizes.push_back(nnames); ndef->pendNodeResolve(ore); lua_pushinteger(L, handle); return 1; } // register_schematic({schematic}, replacements={}) int ModApiMapgen::l_register_schematic(lua_State *L) { NO_MAP_LOCK_REQUIRED; SchematicManager *schemmgr = getServer(L)->getEmergeManager()->schemmgr; StringMap replace_names; if (lua_istable(L, 2)) read_schematic_replacements(L, 2, &replace_names); Schematic *schem = load_schematic(L, 1, schemmgr->getNodeDef(), &replace_names); if (!schem) return 0; ObjDefHandle handle = schemmgr->add(schem); if (handle == OBJDEF_INVALID_HANDLE) { delete schem; return 0; } lua_pushinteger(L, handle); return 1; } // clear_registered_biomes() int ModApiMapgen::l_clear_registered_biomes(lua_State *L) { NO_MAP_LOCK_REQUIRED; BiomeManager *bmgr = getServer(L)->getEmergeManager()->biomemgr; bmgr->clear(); return 0; } // clear_registered_decorations() int ModApiMapgen::l_clear_registered_decorations(lua_State *L) { NO_MAP_LOCK_REQUIRED; DecorationManager *dmgr = getServer(L)->getEmergeManager()->decomgr; dmgr->clear(); return 0; } // clear_registered_ores() int ModApiMapgen::l_clear_registered_ores(lua_State *L) { NO_MAP_LOCK_REQUIRED; OreManager *omgr = getServer(L)->getEmergeManager()->oremgr; omgr->clear(); return 0; } // clear_registered_schematics() int ModApiMapgen::l_clear_registered_schematics(lua_State *L) { NO_MAP_LOCK_REQUIRED; SchematicManager *smgr = getServer(L)->getEmergeManager()->schemmgr; smgr->clear(); return 0; } // generate_ores(vm, p1, p2, [ore_id]) int ModApiMapgen::l_generate_ores(lua_State *L) { NO_MAP_LOCK_REQUIRED; EmergeManager *emerge = getServer(L)->getEmergeManager(); Mapgen mg; mg.seed = emerge->mgparams->seed; mg.vm = LuaVoxelManip::checkobject(L, 1)->vm; mg.ndef = getServer(L)->getNodeDefManager(); v3s16 pmin = lua_istable(L, 2) ? check_v3s16(L, 2) : mg.vm->m_area.MinEdge + v3s16(1,1,1) * MAP_BLOCKSIZE; v3s16 pmax = lua_istable(L, 3) ? check_v3s16(L, 3) : mg.vm->m_area.MaxEdge - v3s16(1,1,1) * MAP_BLOCKSIZE; sortBoxVerticies(pmin, pmax); u32 blockseed = Mapgen::getBlockSeed(pmin, mg.seed); emerge->oremgr->placeAllOres(&mg, blockseed, pmin, pmax); return 0; } // generate_decorations(vm, p1, p2, [deco_id]) int ModApiMapgen::l_generate_decorations(lua_State *L) { NO_MAP_LOCK_REQUIRED; EmergeManager *emerge = getServer(L)->getEmergeManager(); Mapgen mg; mg.seed = emerge->mgparams->seed; mg.vm = LuaVoxelManip::checkobject(L, 1)->vm; mg.ndef = getServer(L)->getNodeDefManager(); v3s16 pmin = lua_istable(L, 2) ? check_v3s16(L, 2) : mg.vm->m_area.MinEdge + v3s16(1,1,1) * MAP_BLOCKSIZE; v3s16 pmax = lua_istable(L, 3) ? check_v3s16(L, 3) : mg.vm->m_area.MaxEdge - v3s16(1,1,1) * MAP_BLOCKSIZE; sortBoxVerticies(pmin, pmax); u32 blockseed = Mapgen::getBlockSeed(pmin, mg.seed); emerge->decomgr->placeAllDecos(&mg, blockseed, pmin, pmax); return 0; } // create_schematic(p1, p2, probability_list, filename, y_slice_prob_list) int ModApiMapgen::l_create_schematic(lua_State *L) { MAP_LOCK_REQUIRED; INodeDefManager *ndef = getServer(L)->getNodeDefManager(); const char *filename = luaL_checkstring(L, 4); CHECK_SECURE_PATH(L, filename, true); Map *map = &(getEnv(L)->getMap()); Schematic schem; v3s16 p1 = check_v3s16(L, 1); v3s16 p2 = check_v3s16(L, 2); sortBoxVerticies(p1, p2); std::vector<std::pair<v3s16, u8> > prob_list; if (lua_istable(L, 3)) { lua_pushnil(L); while (lua_next(L, 3)) { if (lua_istable(L, -1)) { lua_getfield(L, -1, "pos"); v3s16 pos = check_v3s16(L, -1); lua_pop(L, 1); u8 prob = getintfield_default(L, -1, "prob", MTSCHEM_PROB_ALWAYS); prob_list.push_back(std::make_pair(pos, prob)); } lua_pop(L, 1); } } std::vector<std::pair<s16, u8> > slice_prob_list; if (lua_istable(L, 5)) { lua_pushnil(L); while (lua_next(L, 5)) { if (lua_istable(L, -1)) { s16 ypos = getintfield_default(L, -1, "ypos", 0); u8 prob = getintfield_default(L, -1, "prob", MTSCHEM_PROB_ALWAYS); slice_prob_list.push_back(std::make_pair(ypos, prob)); } lua_pop(L, 1); } } if (!schem.getSchematicFromMap(map, p1, p2)) { errorstream << "create_schematic: failed to get schematic " "from map" << std::endl; return 0; } schem.applyProbabilities(p1, &prob_list, &slice_prob_list); schem.saveSchematicToFile(filename, ndef); actionstream << "create_schematic: saved schematic file '" << filename << "'." << std::endl; lua_pushboolean(L, true); return 1; } // place_schematic(p, schematic, rotation, replacement) int ModApiMapgen::l_place_schematic(lua_State *L) { MAP_LOCK_REQUIRED; GET_ENV_PTR; ServerMap *map = &(env->getServerMap()); SchematicManager *schemmgr = getServer(L)->getEmergeManager()->schemmgr; //// Read position v3s16 p = check_v3s16(L, 1); //// Read rotation int rot = ROTATE_0; const char *enumstr = lua_tostring(L, 3); if (enumstr) string_to_enum(es_Rotation, rot, std::string(enumstr)); //// Read force placement bool force_placement = true; if (lua_isboolean(L, 5)) force_placement = lua_toboolean(L, 5); //// Read node replacements StringMap replace_names; if (lua_istable(L, 4)) read_schematic_replacements(L, 4, &replace_names); //// Read schematic Schematic *schem = get_or_load_schematic(L, 2, schemmgr, &replace_names); if (!schem) { errorstream << "place_schematic: failed to get schematic" << std::endl; return 0; } schem->placeOnMap(map, p, 0, (Rotation)rot, force_placement); lua_pushboolean(L, true); return 1; } int ModApiMapgen::l_place_schematic_on_vmanip(lua_State *L) { NO_MAP_LOCK_REQUIRED; SchematicManager *schemmgr = getServer(L)->getEmergeManager()->schemmgr; //// Read VoxelManip object MMVManip *vm = LuaVoxelManip::checkobject(L, 1)->vm; //// Read position v3s16 p = check_v3s16(L, 2); //// Read rotation int rot = ROTATE_0; const char *enumstr = lua_tostring(L, 4); if (enumstr) string_to_enum(es_Rotation, rot, std::string(enumstr)); //// Read force placement bool force_placement = true; if (lua_isboolean(L, 6)) force_placement = lua_toboolean(L, 6); //// Read node replacements StringMap replace_names; if (lua_istable(L, 5)) read_schematic_replacements(L, 5, &replace_names); //// Read schematic Schematic *schem = get_or_load_schematic(L, 3, schemmgr, &replace_names); if (!schem) { errorstream << "place_schematic: failed to get schematic" << std::endl; return 0; } bool schematic_did_fit = schem->placeOnVManip( vm, p, 0, (Rotation)rot, force_placement); lua_pushboolean(L, schematic_did_fit); return 1; } // serialize_schematic(schematic, format, options={...}) int ModApiMapgen::l_serialize_schematic(lua_State *L) { NO_MAP_LOCK_REQUIRED; SchematicManager *schemmgr = getServer(L)->getEmergeManager()->schemmgr; //// Read options bool use_comments = getboolfield_default(L, 3, "lua_use_comments", false); u32 indent_spaces = getintfield_default(L, 3, "lua_num_indent_spaces", 0); //// Get schematic bool was_loaded = false; Schematic *schem = (Schematic *)get_objdef(L, 1, schemmgr); if (!schem) { schem = load_schematic(L, 1, NULL, NULL); was_loaded = true; } if (!schem) { errorstream << "serialize_schematic: failed to get schematic" << std::endl; return 0; } //// Read format of definition to save as int schem_format = SCHEM_FMT_MTS; const char *enumstr = lua_tostring(L, 2); if (enumstr) string_to_enum(es_SchematicFormatType, schem_format, std::string(enumstr)); //// Serialize to binary string std::ostringstream os(std::ios_base::binary); switch (schem_format) { case SCHEM_FMT_MTS: schem->serializeToMts(&os, schem->m_nodenames); break; case SCHEM_FMT_LUA: schem->serializeToLua(&os, schem->m_nodenames, use_comments, indent_spaces); break; default: return 0; } if (was_loaded) delete schem; std::string ser = os.str(); lua_pushlstring(L, ser.c_str(), ser.length()); return 1; } void ModApiMapgen::Initialize(lua_State *L, int top) { API_FCT(get_biome_id); API_FCT(get_mapgen_object); API_FCT(get_mapgen_params); API_FCT(set_mapgen_params); API_FCT(get_mapgen_setting); API_FCT(set_mapgen_setting); API_FCT(get_mapgen_setting_noiseparams); API_FCT(set_mapgen_setting_noiseparams); API_FCT(set_noiseparams); API_FCT(get_noiseparams); API_FCT(set_gen_notify); API_FCT(get_gen_notify); API_FCT(register_biome); API_FCT(register_decoration); API_FCT(register_ore); API_FCT(register_schematic); API_FCT(clear_registered_biomes); API_FCT(clear_registered_decorations); API_FCT(clear_registered_ores); API_FCT(clear_registered_schematics); API_FCT(generate_ores); API_FCT(generate_decorations); API_FCT(create_schematic); API_FCT(place_schematic); API_FCT(place_schematic_on_vmanip); API_FCT(serialize_schematic); }
25.679504
88
0.689281
crazyBaboon
32f001602699f6595c27fc1572306c97c5a2d0b0
2,577
cc
C++
edas/src/model/ListConfigCentersResult.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
edas/src/model/ListConfigCentersResult.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
edas/src/model/ListConfigCentersResult.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
69
2018-01-22T09:45:52.000Z
2022-03-28T07:58:38.000Z
/* * Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/edas/model/ListConfigCentersResult.h> #include <json/json.h> using namespace AlibabaCloud::Edas; using namespace AlibabaCloud::Edas::Model; ListConfigCentersResult::ListConfigCentersResult() : ServiceResult() {} ListConfigCentersResult::ListConfigCentersResult(const std::string &payload) : ServiceResult() { parse(payload); } ListConfigCentersResult::~ListConfigCentersResult() {} void ListConfigCentersResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); auto allConfigCentersListNode = value["ConfigCentersList"]["ListConfigCenters"]; for (auto valueConfigCentersListListConfigCenters : allConfigCentersListNode) { ListConfigCenters configCentersListObject; if(!valueConfigCentersListListConfigCenters["AppName"].isNull()) configCentersListObject.appName = valueConfigCentersListListConfigCenters["AppName"].asString(); if(!valueConfigCentersListListConfigCenters["DataId"].isNull()) configCentersListObject.dataId = valueConfigCentersListListConfigCenters["DataId"].asString(); if(!valueConfigCentersListListConfigCenters["Group"].isNull()) configCentersListObject.group = valueConfigCentersListListConfigCenters["Group"].asString(); if(!valueConfigCentersListListConfigCenters["Id"].isNull()) configCentersListObject.id = valueConfigCentersListListConfigCenters["Id"].asString(); configCentersList_.push_back(configCentersListObject); } if(!value["Code"].isNull()) code_ = std::stoi(value["Code"].asString()); if(!value["Message"].isNull()) message_ = value["Message"].asString(); } std::string ListConfigCentersResult::getMessage()const { return message_; } std::vector<ListConfigCentersResult::ListConfigCenters> ListConfigCentersResult::getConfigCentersList()const { return configCentersList_; } int ListConfigCentersResult::getCode()const { return code_; }
33.038462
108
0.780753
aliyun
32f11db0729e90e6d3b0383560439ac40545ae4a
957
cpp
C++
GFG/All_Code/1.cpp
jnvshubham7/CPP_Programming
a17c4a42209556495302ca305b7c3026df064041
[ "Apache-2.0" ]
1
2021-12-22T12:37:36.000Z
2021-12-22T12:37:36.000Z
GFG/All_Code/1.cpp
jnvshubham7/CPP_Programming
a17c4a42209556495302ca305b7c3026df064041
[ "Apache-2.0" ]
null
null
null
GFG/All_Code/1.cpp
jnvshubham7/CPP_Programming
a17c4a42209556495302ca305b7c3026df064041
[ "Apache-2.0" ]
null
null
null
class Solution { public: // create isupper() function bool isupper(char c) { return c >= 'A' && c <= 'Z'; } string arrangeString(string str) { int sum=0; //store all capital letters in a vector and all integer in different vector vector<char> capital; vector<int> integer; for(int i=0;i<str.length();i++) { if(isupper(str[i])) { capital.push_back(str[i]); } else { integer.push_back(str[i]-'0'); } } sort(capital.begin(),capital.end()); //sum of all integer for(int i=0;i<integer.size();i++) { sum=sum+integer[i]; } //return all capital letters follwed by sum of all integer string ans=""; for(int i=0;i<capital.size();i++) { ans=ans+capital[i]; } ans=ans+to_string(sum); return ans; } };
17.4
83
0.486938
jnvshubham7
32f5107af06c7dc0199c24de35bda54ec13df7f6
1,238
cpp
C++
src/easy/calculate-distance/solutions/c++/solution.cpp
rdtsc/codeeval-solutions
d5c06baf89125e9e9f4b163ee57e5a8f7e73e717
[ "MIT" ]
null
null
null
src/easy/calculate-distance/solutions/c++/solution.cpp
rdtsc/codeeval-solutions
d5c06baf89125e9e9f4b163ee57e5a8f7e73e717
[ "MIT" ]
null
null
null
src/easy/calculate-distance/solutions/c++/solution.cpp
rdtsc/codeeval-solutions
d5c06baf89125e9e9f4b163ee57e5a8f7e73e717
[ "MIT" ]
null
null
null
#include <cassert> #include <cmath> #include <fstream> #include <iostream> #include <limits> template<typename T> struct Point2d { using value_type = T; Point2d() : x(), y() {} friend std::istream& operator>>(std::istream& inputStream, Point2d& point) { static constexpr auto ignoreLimit = std::numeric_limits<std::streamsize>::max(); inputStream.ignore(ignoreLimit, '('); inputStream >> point.x; inputStream.ignore(ignoreLimit, ','); inputStream >> point.y; return inputStream; } T x, y; }; int main(const int argc, const char* const argv[]) { // Getting away with no error checking throughout because CodeEval makes some // strong guarantees about our runtime environment. No need to pay when we're // being benchmarked. Don't forget to define NDEBUG prior to submitting! assert(argc >= 2 && "Expecting at least one command-line argument."); std::ifstream inputStream(argv[1]); assert(inputStream && "Failed to open input stream."); for(Point2d<int> a, b; inputStream >> a >> b;) { // Distance formula. const unsigned distance = ::sqrt(::pow(b.x - a.x, 2) + ::pow(b.y - a.y, 2)); std::cout << distance << '\n'; } }
24.76
79
0.636511
rdtsc
fd002ae81f34a991282284bee5286b60508ad213
1,164
cpp
C++
tests/Test_json11.cpp
mattparks/Serial
327cbd7a8446434975de5466e53966e6f362532e
[ "MIT" ]
2
2020-01-02T15:02:07.000Z
2020-06-28T19:45:53.000Z
tests/Test_json11.cpp
mattparks/Serial
327cbd7a8446434975de5466e53966e6f362532e
[ "MIT" ]
null
null
null
tests/Test_json11.cpp
mattparks/Serial
327cbd7a8446434975de5466e53966e6f362532e
[ "MIT" ]
null
null
null
#include <fstream> #include <gtest/gtest.h> #include <json11/json11.hpp> #include "MemoryData.hpp" static class Json11Data { public: json11::Json canada; json11::Json catalog; json11::Json twitter; } json11Data; TEST(json11, parseInMemory) { std::string err; json11Data.canada = json11::Json::parse(MemoryData::canadaString, err); json11Data.catalog = json11::Json::parse(MemoryData::catalogString, err); json11Data.twitter = json11::Json::parse(MemoryData::twitterString, err); } TEST(json11, stringify) { std::string canadaString = json11Data.canada.dump(); std::string catalogString = json11Data.catalog.dump(); std::string twitterString = json11Data.twitter.dump(); } TEST(json11, writeToFiles) { std::ofstream canadaStream("Tests/canada.json11.json", std::ios_base::binary | std::ios_base::out); canadaStream << json11Data.canada.dump(); std::ofstream catalogStream("Tests/citm_catalog.json11.json", std::ios_base::binary | std::ios_base::out); catalogStream << json11Data.catalog.dump(); std::ofstream twitterStream("Tests/twitter.json11.json", std::ios_base::binary | std::ios_base::out); twitterStream << json11Data.twitter.dump(); }
32.333333
107
0.747423
mattparks
fd01b6c6ca2b1d23ffc199101def58cccd4d36bc
2,792
cpp
C++
Contrib-Intel/RSD-PSME-RMM/common/agent-framework/src/module/model/psu.cpp
opencomputeproject/Rack-Manager
e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a
[ "MIT" ]
5
2019-11-11T07:57:26.000Z
2022-03-28T08:26:53.000Z
Contrib-Intel/RSD-PSME-RMM/common/agent-framework/src/module/model/psu.cpp
opencomputeproject/Rack-Manager
e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a
[ "MIT" ]
3
2019-09-05T21:47:07.000Z
2019-09-17T18:10:45.000Z
Contrib-Intel/RSD-PSME-RMM/common/agent-framework/src/module/model/psu.cpp
opencomputeproject/Rack-Manager
e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a
[ "MIT" ]
11
2019-07-20T00:16:32.000Z
2022-01-11T14:17:48.000Z
/*! * @copyright * Copyright (c) 2015-2019 Intel Corporation * * @copyright * 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 * * @copyright * http://www.apache.org/licenses/LICENSE-2.0 * * @copyright * 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 "agent-framework/module/model/psu.hpp" #include "agent-framework/module/constants/rmm.hpp" using namespace agent_framework::model; using namespace agent_framework::model::utils; const enums::Component Psu::component = enums::Component::PSU; const enums::CollectionName Psu::collection_name = enums::CollectionName::Psus; Psu::Psu(const std::string& parent_uuid, enums::Component parent_type) : Resource{parent_uuid, parent_type} {} Psu::~Psu() {} json::Json Psu::to_json() const { json::Json result = json::Json(); result[literals::Psu::STATUS] = get_status().to_json(); result[literals::Psu::FRU_INFO] = get_fru_info().to_json(); result[literals::Psu::POWER_SUPPLY_TYPE] = get_power_supply_type(); result[literals::Psu::LINE_INPUT_VOLTAGE_TYPE] = get_line_input_voltage_type(); result[literals::Psu::LINE_INPUT_VOLTAGE_VOLTS] = get_line_input_voltage_volts(); result[literals::Psu::FIRMWARE_VERSION] = get_firmware_version(); result[literals::Psu::LAST_POWER_OUTPUT_WATTS] = get_last_power_output_watts(); result[literals::Psu::POWER_CAPACITY_WATTS] = get_power_capacity_watts(); result[literals::Psu::INDICATOR_LED] = get_indicator_led(); result[literals::Psu::OEM] = get_oem().to_json(); return result; } Psu Psu::from_json(const json::Json& json) { Psu psu; psu.set_status(attribute::Status::from_json(json[literals::Psu::STATUS])); psu.set_fru_info(attribute::FruInfo::from_json(json[literals::Psu::FRU_INFO])); psu.set_power_supply_type(json[literals::Psu::POWER_SUPPLY_TYPE]); psu.set_line_input_voltage_type(json[literals::Psu::LINE_INPUT_VOLTAGE_TYPE]); psu.set_line_input_voltage_volts(json[literals::Psu::LINE_INPUT_VOLTAGE_VOLTS]); psu.set_firmware_version(json[literals::Psu::FIRMWARE_VERSION]); psu.set_power_capacity_watts(json[literals::Psu::POWER_CAPACITY_WATTS]); psu.set_last_power_output_watts(json[literals::Psu::LAST_POWER_OUTPUT_WATTS]); psu.set_indicator_led(json[literals::Psu::INDICATOR_LED]); psu.set_oem(attribute::Oem::from_json(json[literals::Psu::OEM])); return psu; }
38.777778
85
0.745344
opencomputeproject
fd06776d3caabb93ba92481f1953dc2aaa8115e0
7,724
cpp
C++
net/homenet/config/dll/hncstrs.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
net/homenet/config/dll/hncstrs.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
net/homenet/config/dll/hncstrs.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//+--------------------------------------------------------------------------- // // Microsoft Windows // Copyright (C) Microsoft Corporation, 1997 - 2000 // // File: H N C S T R S . C P P // // Contents: Constant string definitions // // Notes: // // Author: jonburs 21 June 2000 // //---------------------------------------------------------------------------- #include "pch.h" #pragma hdrstop const OLECHAR c_wszNamespace[] = L"\\\\.\\Root\\Microsoft\\HomeNet"; const OLECHAR c_wszWQL[] = L"WQL"; const OLECHAR c_wszStar[] = L"*"; const OLECHAR c_wszHnetConnection[] = L"HNet_Connection"; const OLECHAR c_wszHnetProperties[] = L"HNet_ConnectionProperties"; const OLECHAR c_wszHnetApplicationProtocol[] = L"HNet_ApplicationProtocol"; const OLECHAR c_wszHnetPortMappingProtocol[] = L"HNet_PortMappingProtocol"; const OLECHAR c_wszHnetConnectionPortMapping[] = L"HNet_ConnectionPortMapping2"; const OLECHAR c_wszHnetFWLoggingSettings[] = L"HNet_FirewallLoggingSettings"; const OLECHAR c_wszHnetIcsSettings[] = L"HNet_IcsSettings"; const OLECHAR c_wszHnetResponseRange[] = L"HNet_ResponseRange"; const OLECHAR c_wszPath[] = L"Path"; const OLECHAR c_wszMaxFileSize[] = L"MaxFileSize"; const OLECHAR c_wszLogDroppedPackets[] = L"LogDroppedPackets"; const OLECHAR c_wszLogConnections[] = L"LogConnections"; const OLECHAR c_wszDhcpEnabled[] = L"DhcpEnabled"; const OLECHAR c_wszDnsEnabled[] = L"DnsEnabled"; const OLECHAR c_wszName[] = L"Name"; const OLECHAR c_wszDeviceName[] = L"DeviceName"; const OLECHAR c_wszEnabled[] = L"Enabled"; const OLECHAR c_wszBuiltIn[] = L"BuiltIn"; const OLECHAR c_wszOutgoingIPProtocol[] = L"OutgoingIPProtocol"; const OLECHAR c_wszOutgoingPort[] = L"OutgoingPort"; const OLECHAR c_wszResponseCount[] = L"ResponseCount"; const OLECHAR c_wszResponseArray[] = L"ResponseArray"; const OLECHAR c_wszIPProtocol[] = L"IPProtocol"; const OLECHAR c_wszStartPort[] = L"StartPort"; const OLECHAR c_wszEndPort[] = L"EndPort"; const OLECHAR c_wszPort[] = L"Port"; const OLECHAR c_wszId[] = L"Id"; const OLECHAR c_wszConnection[] = L"Connection"; const OLECHAR c_wszProtocol[] = L"Protocol"; const OLECHAR c_wszTargetName[] = L"TargetName"; const OLECHAR c_wszTargetIPAddress[] = L"TargetIPAddress"; const OLECHAR c_wszTargetPort[] = L"TargetPort"; const OLECHAR c_wszNameActive[] = L"NameActive"; const OLECHAR c_wszIsLanConnection[] = L"IsLanConnection"; const OLECHAR c_wszIsFirewalled[] = L"IsFirewalled"; const OLECHAR c_wszIsIcsPublic[] = L"IsIcsPublic"; const OLECHAR c_wszIsIcsPrivate[] = L"IsIcsPrivate"; const OLECHAR c_wszIsBridgeMember[] = L"IsBridgeMember"; const OLECHAR c_wszIsBridge[] = L"IsBridge"; const OLECHAR c_wszPhonebookPath[] = L"PhonebookPath"; const OLECHAR c_wszGuid[] = L"Guid"; const OLECHAR c_wszHnetFwIcmpSettings[] = L"HNet_FwIcmpSettings"; const OLECHAR c_wszAllowOutboundDestinationUnreachable[] = L"AllowOutboundDestinationUnreachable"; const OLECHAR c_wszAllowOutboundSourceQuench[] = L"AllowOutboundSourceQuench"; const OLECHAR c_wszAllowRedirect[] = L"AllowRedirect"; const OLECHAR c_wszAllowInboundEchoRequest[] = L"AllowInboundEchoRequest"; const OLECHAR c_wszAllowInboundRouterRequest[] = L"AllowInboundRouterRequest"; const OLECHAR c_wszAllowOutboundTimeExceeded[] = L"AllowOutboundTimeExceeded"; const OLECHAR c_wszAllowOutboundParameterProblem[] = L"AllowOutboundParameterProblem"; const OLECHAR c_wszAllowInboundTimestampRequest[] = L"AllowInboundTimestampRequest"; const OLECHAR c_wszAllowInboundMaskRequest[] = L"AllowInboundMaskRequest"; const OLECHAR c_wszDefault[] = L"Default"; const OLECHAR c_wszDefaultIcmpSettingsPath[] = L"HNet_FwIcmpSettings.Name=\"Default\""; const OLECHAR c_wszHnetConnectionIcmpSetting[] = L"HNet_ConnectionIcmpSetting"; const OLECHAR c_wszIcmpSettings[] = L"IcmpSettings"; const OLECHAR c_wszHnetBridgeMember[] = L"HNet_BridgeMember"; const OLECHAR c_wszBridge[] = L"Bridge"; const OLECHAR c_wszMember[] = L"Member"; const OLECHAR c_wszSelect[] = L"SELECT"; const OLECHAR c_wszFrom[] = L"FROM"; const OLECHAR c_wszWhere[] = L"WHERE"; const OLECHAR c_wsz__Path[] = L"__Relpath"; const OLECHAR c_wszReferencesOf[] = L"REFERENCES OF {"; const OLECHAR c_wszWhereResultClass[] = L"} WHERE ResultClass = "; const OLECHAR c_wszAssociatorsOf[] = L"ASSOCIATORS OF {"; const OLECHAR c_wszWhereAssocClass[] = L"} WHERE AssocClass = "; const OLECHAR c_wszPortMappingProtocolQueryFormat[] = L"Port = %u AND IPProtocol = %u"; const OLECHAR c_wszApplicationProtocolQueryFormat[] = L"OutgoingPort = %u AND OutgoingIPProtocol = %u"; const OLECHAR c_wszConnectionPropertiesPathFormat[] = L"HNet_ConnectionProperties.Connection=\"HNet_Connection.Guid=\\\"%s\\\"\""; const OLECHAR c_wszBackupIpConfiguration[] = L"HNet_BackupIpConfiguration"; const OLECHAR c_wszEnableDHCP[] = L"EnableDHCP"; const OLECHAR c_wszInterfaces[] = L"Interfaces"; const OLECHAR c_wszIPAddress[] = L"IPAddress"; const OLECHAR c_wszSubnetMask[] = L"SubnetMask"; const OLECHAR c_wszDefaultGateway[] = L"DefaultGateway"; const OLECHAR c_wszTcpipParametersKey[] = L"\\Registry\\Machine\\System\\CurrentControlSet\\Services\\Tcpip" L"\\Parameters"; const OLECHAR c_wszZeroIpAddress[] = L"0.0.0.0"; const OLECHAR c_wszSharedAccess[] = L"SharedAccess"; const OLECHAR c_wszDevice[] = L"\\Device\\"; const OLECHAR c_wszServiceCheckQuery[] = L"SELECT * FROM HNet_ConnectionProperties WHERE IsFirewalled != FALSE" L" or IsIcsPublic != FALSE or IsIcsPrivate != FALSE"; const OLECHAR c_wszHnetConnectionAutoconfig[] = L"HNet_ConnectionAutoconfig"; // ICS Upgrade named event (has to be the same name in net\config\shell\netsetup\icsupgrd.h) const OLECHAR c_wszIcsUpgradeEventName[] = L"IcsUpgradeEventName_"; // // Commonly used string lengths. Generating these at compile time // saves us a large number of wcslen calls. On debug builds, these // values are compared with the output of wcslen, and an assertion is // raised if the values do not match. // #define STRING_LENGTH(pwz) \ (sizeof((pwz)) / sizeof((pwz)[0]) - 1) const ULONG c_cchSelect = STRING_LENGTH(c_wszSelect); const ULONG c_cchFrom = STRING_LENGTH(c_wszFrom); const ULONG c_cchWhere = STRING_LENGTH(c_wszWhere); const ULONG c_cchReferencesOf = STRING_LENGTH(c_wszReferencesOf); const ULONG c_cchWhereResultClass = STRING_LENGTH(c_wszWhereResultClass); const ULONG c_cchAssociatorsOf = STRING_LENGTH(c_wszAssociatorsOf); const ULONG c_cchWhereAssocClass = STRING_LENGTH(c_wszWhereAssocClass); const ULONG c_cchConnection = STRING_LENGTH(c_wszConnection); const ULONG c_cchConnectionPropertiesPathFormat = STRING_LENGTH(c_wszConnectionPropertiesPathFormat); // // Bindings-related strings // const WCHAR c_wszSBridgeMPID[] = L"ms_bridgemp"; const WCHAR c_wszSBridgeSID[] = L"ms_bridge"; const WCHAR *c_pwszBridgeBindExceptions[] = { L"ms_ndisuio", // Need NDISUIO for wireless adapters; want the wireless UI // even when the adapter is bridged. NULL }; // // String constants used for IsRrasConfigured. // const WCHAR c_wszRrasConfigurationPath[] = L"SYSTEM\\CurrentControlSet\\Services\\RemoteAccess"; const WCHAR c_wszRrasConfigurationValue[] = L"ConfigurationFlags"; // // Strings that are used in WinBom homenet install // const TCHAR c_szEnableFirewall[] = _T("EnableFirewall"); const TCHAR c_szYes[] = _T("Yes"); const TCHAR c_szNo[] = _T("No");
44.906977
131
0.72333
npocmaka
fd07203282a5ae22b4030a053f9cb7a812387b64
1,776
cpp
C++
Lab 1/Ch_02-SourceCode/first_last_lab1A.cpp
candr002/CS150
8270f60769fc8a9c18e5c5c46879b63663ba2117
[ "Unlicense" ]
null
null
null
Lab 1/Ch_02-SourceCode/first_last_lab1A.cpp
candr002/CS150
8270f60769fc8a9c18e5c5c46879b63663ba2117
[ "Unlicense" ]
null
null
null
Lab 1/Ch_02-SourceCode/first_last_lab1A.cpp
candr002/CS150
8270f60769fc8a9c18e5c5c46879b63663ba2117
[ "Unlicense" ]
null
null
null
/* ************************************************************* Programmer: your name goes here file: first_last_lab1A.cpp change this TA Name: ( put the name of your lab TA here ) TA Email: (find out your TAs email, and put it here) Given the length and width of a rectangle, this C++ program computes and outputs the perimeter and area of the rectangle. Modify this program to produce the required output as explained in the comments below. You will submit this program as part of your solution for lab 1. //********************************************************** */ #include <iostream> using namespace std; int main() { ///(1) Required "programmer info code" ///(2) declared. initialize these variables to zero! double length; double width; double area; double perimeter; cout << "\nProgram to compute and output the perimeter and " << "area of a rectangle.\n\n\n"; ///(3) ask the user for the length, using a cout statement ///(4) store input in variable, using a cin statement ///(5) do the same two steps for width. ///(7)calculations - all you need to do is UN-comment these two lines //perimeter = 2 * (length + width); //area = length * width; ///(8) output results cout << " Length = " << length << endl; cout << " Width = " << width << endl; cout << " Perimeter = " << perimeter << endl; cout << " Area = " << area << endl; cout<<"\n\n"; // comment out this line, and see what happens cout <<endl<<endl; // now comment out this one,.. what happens? ///(9) exit program return 0; }//========================end of main======================
30.101695
74
0.543356
candr002
fd0a0c8bc0a0a65f09217ac5ff7ebbd688911cd1
685
cpp
C++
engine/src/resources/text.cpp
gguedesaz/thunder
41fbd8393dc6974ae26e1d77d5f2f8f252e14b5c
[ "Apache-2.0" ]
null
null
null
engine/src/resources/text.cpp
gguedesaz/thunder
41fbd8393dc6974ae26e1d77d5f2f8f252e14b5c
[ "Apache-2.0" ]
null
null
null
engine/src/resources/text.cpp
gguedesaz/thunder
41fbd8393dc6974ae26e1d77d5f2f8f252e14b5c
[ "Apache-2.0" ]
null
null
null
#include "resources/text.h" #include <variant.h> #define DATA "Data" #include <log.h> class TextPrivate { public: ByteArray m_Data; }; Text::Text() : p_ptr(new TextPrivate) { } Text::~Text() { delete p_ptr; } void Text::loadUserData(const VariantMap &data) { auto it = data.find(DATA); if(it != data.end()) { p_ptr->m_Data = (*it).second.toByteArray(); } } char *Text::data() const { return reinterpret_cast<char *>(&p_ptr->m_Data[0]); } uint32_t Text::size() const { return p_ptr->m_Data.size(); } void Text::setSize(uint32_t size) { p_ptr->m_Data.resize(size); } string Text::text() { return string(data(), size()); }
15.222222
55
0.614599
gguedesaz
fd0a1148a9c5147f96bb3d20de84c538c1c85fb2
1,752
cpp
C++
src/tf.cpp
JeroenBongers96/suii_3d_vision_ros
82197531f44d58d2579cd2563757581aae91d021
[ "BSD-3-Clause" ]
null
null
null
src/tf.cpp
JeroenBongers96/suii_3d_vision_ros
82197531f44d58d2579cd2563757581aae91d021
[ "BSD-3-Clause" ]
null
null
null
src/tf.cpp
JeroenBongers96/suii_3d_vision_ros
82197531f44d58d2579cd2563757581aae91d021
[ "BSD-3-Clause" ]
1
2020-01-01T22:29:24.000Z
2020-01-01T22:29:24.000Z
#include "tf.h" Transformation::Transformation() { std::cout << "TRANSFORMATION CREATED" << std::endl; std::cout << "##############################" << std::endl; } tf_struct_data Transformation::getTf(pcl::PointCloud<pcl::PointXYZ>::Ptr cloud) { //Calculate the TF from a given PCD pcl::MomentOfInertiaEstimation <pcl::PointXYZ> feature_extractor; feature_extractor.setInputCloud (cloud); feature_extractor.compute (); std::vector <float> moment_of_inertia; std::vector <float> eccentricity; Eigen::Matrix3f rotational_matrix_OBB; float major_value, middle_value, minor_value; Eigen::Vector3f major_vector, middle_vector, minor_vector; Eigen::Vector3f mass_center; feature_extractor.getMomentOfInertia (moment_of_inertia); feature_extractor.getEigenValues (major_value, middle_value, minor_value); feature_extractor.getEigenVectors (major_vector, middle_vector, minor_vector); feature_extractor.getMassCenter (mass_center); int scale = 8; pcl::PointXYZ center (mass_center (0), mass_center (1), mass_center (2)); pcl::PointXYZ x_axis ((major_vector (0) / scale) + mass_center (0), (major_vector (1) / scale) + mass_center (1), (major_vector (2) / scale) + mass_center (2)); pcl::PointXYZ y_axis ((middle_vector (0) / scale) + mass_center (0), (middle_vector (1) / scale) + mass_center (1), (middle_vector (2) / scale) + mass_center (2)); pcl::PointXYZ z_axis ((minor_vector (0) / scale) + mass_center (0), (minor_vector (1) / scale) + mass_center (1), (minor_vector (2) / scale) + mass_center (2)); tf_tf_data.center = center; tf_tf_data.x_axis = x_axis; tf_tf_data.y_axis = y_axis; tf_tf_data.z_axis = z_axis; return(tf_tf_data); }
39.818182
167
0.693493
JeroenBongers96
fd0c7f939264a99f958c88c75bf0b80b09fa9fe0
869
cpp
C++
01_Programming_Basics/01_Programming_Basics_with_C++/12_Nested_Loops_Lab/08_cookie_factory.cpp
Knightwalker/Knowledgebase
00c6dea5e52c0d2b0fe0dc3b7b5c298d445f0161
[ "MIT" ]
null
null
null
01_Programming_Basics/01_Programming_Basics_with_C++/12_Nested_Loops_Lab/08_cookie_factory.cpp
Knightwalker/Knowledgebase
00c6dea5e52c0d2b0fe0dc3b7b5c298d445f0161
[ "MIT" ]
null
null
null
01_Programming_Basics/01_Programming_Basics_with_C++/12_Nested_Loops_Lab/08_cookie_factory.cpp
Knightwalker/Knowledgebase
00c6dea5e52c0d2b0fe0dc3b7b5c298d445f0161
[ "MIT" ]
null
null
null
#include <iostream> #include <string> using namespace std; int main() { int n = 0; cin >> n; cin.ignore(); for(int i = 0; i < n; i++) { bool flour = false; bool eggs = false; bool sugar = false; while(true) { string products = ""; getline(cin, products); if(products == "flour") { flour = true; } else if(products == "eggs") { eggs = true; } else if(products == "sugar") { sugar = true; } else if(products == "Bake!") { if(flour == true && eggs == true && sugar == true) { cout << "Baking batch number " << i + 1 << "..." << endl; break; } else { cout << "The batter should contain flour, eggs and sugar!" << endl; continue; } } } } return 0; }
18.104167
77
0.443038
Knightwalker
fd0e6c8493a55abd25ac5a8c7fcc1dd5b46ff55b
4,017
cpp
C++
src/Cpp/networks_lib/bimap_str_int.cpp
PathwayAnalysisPlatform/ProteoformNetworks
3d31e5b3cb4abc45e6419fa982c08b3dc5c2624e
[ "Apache-2.0" ]
1
2019-08-16T12:40:14.000Z
2019-08-16T12:40:14.000Z
src/Cpp/networks_lib/bimap_str_int.cpp
LuisFranciscoHS/ProteoformNetworks
a6baa87fe6f76905f6d58a2f7cb66aad5d8d56c5
[ "Apache-2.0" ]
9
2019-08-16T07:33:33.000Z
2022-03-04T22:20:02.000Z
src/Cpp/networks_lib/bimap_str_int.cpp
LuisFranciscoHS/ProteoformNetworks
a6baa87fe6f76905f6d58a2f7cb66aad5d8d56c5
[ "Apache-2.0" ]
1
2022-02-21T17:42:48.000Z
2022-02-21T17:42:48.000Z
#include "bimap_str_int.hpp" Bimap_str_int::Bimap_str_int() { } std::string rtrim(std::string &s) { if (s.length() > 0) { auto it = s.end() - 1; while (isspace(*it)) { s.erase(it); it = s.end() - 1; } } return s; } vs convert_uss_to_vs(const uss &a_set) { vs result; result.assign(a_set.begin(), a_set.end()); return result; } // Create from list, without header, list comes already sorted, there is only one column in the file. Bimap_str_int::Bimap_str_int(std::string_view file_elements) { std::cout << "Reading vertices...\n"; std::ifstream f; f.open(file_elements.data()); if (!f.is_open()) { std::string message = "Cannot open vertices file at "; std::string function = __FUNCTION__; throw std::runtime_error(message + function); } std::string element; int i = 0; while (f >> element) { // std::cout << "Adding element: " << element << std::endl; itos.push_back(element); stoi[element] = i; i++; } std::cout << "Complete.\n\n"; } // Creates a bimap of string to int and viceversa. // The int index assigned to each string corresponds to the lexicographic order. // Creates a bimap of the elements in the selected column. // Column index starts counting at 0 // The columns of the file must be separated by a tab ('\t') Bimap_str_int::Bimap_str_int(std::string_view file_elements, bool has_header, int column_index, int total_num_columns) : itos{createIntToStr(file_elements, has_header, column_index, total_num_columns)}, stoi{createStrToInt(itos)} { } umsi createStrToInt(const vs &index_to_entities) { umsi entities_to_index; for (auto I = 0u; I < index_to_entities.size(); I++) { entities_to_index.emplace(index_to_entities[I], I); } return entities_to_index; } // Creates the bimap from a vector of elements // Removes the duplicate elements in the vector // Sorts the elements to assign the indexes Bimap_str_int::Bimap_str_int(const vs &index_to_entities) { std::set<std::string> s(index_to_entities.begin(), index_to_entities.end()); vs sortedAndUniqueVector(s.begin(), s.end()); itos = sortedAndUniqueVector; stoi = createStrToInt(sortedAndUniqueVector); } int Bimap_str_int::index(const std::string &key) const { if(stoi.find(key) == stoi.end()) { // std::cerr << "Key not found: " << key << std::endl; return -1; } return stoi.at(key); } // The input file has one identifier per row in the selected column. // The index of the selected column starts counting at 0. vs createIntToStr(std::string_view path_file, bool has_header, int selected_column, int total_num_columns) { std::ifstream map_file(path_file.data()); std::string entity, leftover; uss temp_set; vs index_to_entities; int current_column; if (!map_file.is_open()) { std::string message = "Could not open file "; message += path_file; message += " at "; message += __FUNCTION__; throw std::runtime_error(message); } if (selected_column >= total_num_columns || selected_column < 0) { throw std::runtime_error("Invalid column index"); } if (has_header) { getline(map_file, leftover); // Skip header line } current_column = 0; while (map_file.peek() != EOF) { while (current_column != selected_column) { std::getline(map_file, leftover, '\t'); current_column++; } if (selected_column == total_num_columns - 1) { std::getline(map_file, entity, '\n'); } else { std::getline(map_file, entity, '\t'); std::getline(map_file, leftover, '\n'); } temp_set.insert(rtrim(entity)); current_column = 0; } index_to_entities = convert_uss_to_vs(temp_set); sort(index_to_entities.begin(), index_to_entities.end()); return index_to_entities; }
30.431818
120
0.636794
PathwayAnalysisPlatform
fd0f022e398ad675bde99872b460846a60c7006d
229
cpp
C++
module/timer.cpp
Matej-Chmel/hnsw-mch
fee8f4c0e06269dfa4dd1b62e9b0d4408f494d03
[ "MIT" ]
null
null
null
module/timer.cpp
Matej-Chmel/hnsw-mch
fee8f4c0e06269dfa4dd1b62e9b0d4408f494d03
[ "MIT" ]
null
null
null
module/timer.cpp
Matej-Chmel/hnsw-mch
fee8f4c0e06269dfa4dd1b62e9b0d4408f494d03
[ "MIT" ]
null
null
null
#include "timer.h" namespace mch { Timer::Timer() {} void Timer::start() { this->_start = system_clock::now(); } ll Timer::stop() { return duration_cast<milliseconds>(system_clock::now() - this->_start).count(); } }
14.3125
81
0.637555
Matej-Chmel
fd11af26a355261c9fa59c2fa1a80e32ba376a7c
886
cpp
C++
src/main.cpp
LuisHsu/Assignment_4
1735738d3d523d9c3a007d9fb471f121071e75fe
[ "BSD-3-Clause" ]
null
null
null
src/main.cpp
LuisHsu/Assignment_4
1735738d3d523d9c3a007d9fb471f121071e75fe
[ "BSD-3-Clause" ]
null
null
null
src/main.cpp
LuisHsu/Assignment_4
1735738d3d523d9c3a007d9fb471f121071e75fe
[ "BSD-3-Clause" ]
null
null
null
/** * Copyright 2020 Luis Hsu. All rights reserved. * Use of this source code is governed by a BSD-style * license that can be found in the LICENSE file. */ #include <exception> #include <iostream> #include <unistd.h> #include <termios.h> #include <SpiningCube.hpp> int main(int argc, char const *argv[]){ struct termios term; tcgetattr(STDIN_FILENO, &term); { struct termios rawterm = term; cfmakeraw(&rawterm); rawterm.c_oflag |= OPOST; rawterm.c_lflag |= ISIG; tcsetattr(STDIN_FILENO, TCSANOW, &rawterm); } try{ SpiningCube app; app.exec(); }catch(std::exception& err){ std::cerr << err.what() << std::endl; tcflush(STDIN_FILENO, TCIFLUSH); tcsetattr(STDIN_FILENO, TCSANOW, &term); return -1; } tcflush(STDIN_FILENO, TCIFLUSH); tcsetattr(STDIN_FILENO, TCSANOW, &term); return 0; }
23.945946
53
0.646727
LuisHsu
fd121f8e6cc0bc74c3e6252f16e0f94bff96cdaa
591
hpp
C++
src/frontend/internal/patch_args.hpp
BastianBlokland/novus
3b984c36855aa84d6746c14ff7e294ab7d9c1575
[ "MIT" ]
14
2020-04-14T17:00:56.000Z
2021-08-30T08:29:26.000Z
src/frontend/internal/patch_args.hpp
BastianBlokland/novus
3b984c36855aa84d6746c14ff7e294ab7d9c1575
[ "MIT" ]
27
2020-12-27T16:00:44.000Z
2021-08-01T13:12:14.000Z
src/frontend/internal/patch_args.hpp
BastianBlokland/novus
3b984c36855aa84d6746c14ff7e294ab7d9c1575
[ "MIT" ]
1
2020-05-29T18:33:37.000Z
2020-05-29T18:33:37.000Z
#pragma once #include "frontend/diag.hpp" #include "frontend/source_table.hpp" #include "prog/program.hpp" #include <functional> namespace frontend::internal { using PatchDiagReportFunc = std::function<void(Diag)>; /* Patches all call expressions in the program to include any information that was not available * when the call expression was initialally created. One example of this are the optional argument * initializers. */ auto patchCallArgs( const prog::Program& prog, const SourceTable& srcTable, PatchDiagReportFunc reportDiag) -> void; } // namespace frontend::internal
31.105263
100
0.774958
BastianBlokland
fd15d303beaf57426353061df12517d496968fa8
1,569
cpp
C++
codeforces/A - Number of Apartments/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
1
2022-02-11T16:55:36.000Z
2022-02-11T16:55:36.000Z
codeforces/A - Number of Apartments/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
codeforces/A - Number of Apartments/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
/**************************************************************************************** * @author: kzvd4729# created: Mar/24/2021 19:41 * solution_verdict: Accepted language: GNU C++17 (64) * run_time: 31 ms memory_used: 0 KB * problem: https://codeforces.com/contest/1430/problem/A ****************************************************************************************/ #include<iostream> #include<vector> #include<cstring> #include<map> #include<bitset> #include<assert.h> #include<algorithm> #include<iomanip> #include<cmath> #include<set> #include<queue> #include<sstream> #include<unordered_map> #include<unordered_set> #include<chrono> #include<stack> #include<deque> #include<random> #define long long long using namespace std; mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); const int N=1000,inf=1e9,mod=998244353; int a[N+2],b[N+2],c[N+2]; int main() { ios_base::sync_with_stdio(0);cin.tie(0); memset(a,-1,sizeof a); for(int i=0;i<=1000;i++) { if(i*3>1000)break; for(int j=0;j<=1000;j++) { if(i*3+j*5>1000)break; for(int k=0;k<=1000;k++) { int id=i*3+j*5+k*7; if(id>1000)break; a[id]=i,b[id]=j,c[id]=k; } } } int t;cin>>t; while(t--) { int x;cin>>x; if(a[x]==-1)cout<<-1<<endl; else cout<<a[x]<<" "<<b[x]<<" "<<c[x]<<endl; } return 0; }
28.017857
111
0.472275
kzvd4729
fd1a6891a77eab53fe831499466f91e5161229d8
6,258
cpp
C++
src/WebinariaEditor/TimelineControl/OverlayControl.cpp
mkmpvtltd1/Webinaria
41d86467800adb48e77ab49b92891fae2a99bb77
[ "MIT" ]
5
2015-03-31T15:51:22.000Z
2022-03-10T07:01:56.000Z
src/WebinariaEditor/TimelineControl/OverlayControl.cpp
mkmpvtltd1/Webinaria
41d86467800adb48e77ab49b92891fae2a99bb77
[ "MIT" ]
null
null
null
src/WebinariaEditor/TimelineControl/OverlayControl.cpp
mkmpvtltd1/Webinaria
41d86467800adb48e77ab49b92891fae2a99bb77
[ "MIT" ]
null
null
null
#include "StdAfx.h" #include "OverlayControl.h" #include "OverlayElement.h" #include "utils.h" OverlayControl::OverlayControl() : activeOverlay(0) , hitTestAnchor(ohtNone) { memset(&clickAnchor, 0, sizeof(clickAnchor)); } OverlayControl::~OverlayControl() { } Overlay* OverlayControl::GetActiveOverlay() const { return activeOverlay; } void OverlayControl::SetActiveOverlay(Overlay *overlay) { activeOverlay = overlay; } void OverlayControl::ResetCursor() { UpdateCursor(ohtNone); } void OverlayControl::UpdateCursor(OverlayHitTest hitTest) { HCURSOR cursor; switch (hitTest) { case ohtNone: cursor = LoadCursor(0, IDC_ARROW); break; case ohtInside: cursor = LoadCursor(0, IDC_SIZEALL); break; case ohtLeftBorder: case ohtRightBorder: cursor = LoadCursor(0, IDC_SIZEWE); break; case ohtTopBorder: case ohtBottomBorder: cursor = LoadCursor(0, IDC_SIZENS); break; case ohtTopLeftCorner: case ohtBottomRightCorner: cursor = LoadCursor(0, IDC_SIZENWSE); break; case ohtTopRightCorner: case ohtBottomLeftCorner: cursor = LoadCursor(0, IDC_SIZENESW); break; default: cursor = LoadCursor(0, IDC_ARROW); break; } SetCursor(cursor); } void OverlayControl::ActivateElement(HWND hwnd, OverlayElement *element) { if (ActiveOverlay->ActiveElement != element) { ActiveOverlay->ActiveElement = element; RepaintAll(hwnd); // Repaint window, if selection changed (block activated or selection cleared). ActiveOverlayElementChanged(); } } void OverlayControl::RepaintAll(HWND hwnd) { InvalidateRect(hwnd, 0, FALSE); } void OverlayControl::Paint(HWND hwnd, HDC dc) { if (!ActiveOverlay) return; RECT rect; GetClientRect(hwnd, &rect); ActiveOverlay->Paint(dc, &rect); } void OverlayControl::MouseDown(HWND hwnd, WPARAM wParam, LPARAM lParam) { if (!ActiveOverlay) return; // Left or right button clicked -- select the element under cursor. RECT clipRect, clientRect; GetWindowRect(hwnd, &clipRect); GetClientRect(hwnd, &clientRect); // Save original mouse position. GetCursorPosition(hwnd, &clickAnchor); // Element could be activated only if no element active AND user doesn't click // within the active element. if (!ActiveOverlay->ActiveElement || !ActiveOverlay->HitTestElement(ActiveOverlay->ActiveElement, &clientRect, &clickAnchor, &hitTestAnchor)) { // Find overlay element under cursor. OverlayElement *element = ActiveOverlay->FindElementFromPoint(&clientRect, &clickAnchor, &hitTestAnchor); ActivateElement(hwnd, element); } if (!ActiveOverlay->ActiveElement) { ResetCursor(); } if (0 != (wParam & MK_LBUTTON)) { if (ActiveOverlay->ActiveElement) { ActiveOverlay->ActiveElement->GetRect(&clientRect, &elementRectAnchor); // Show that we're about to drag the object. UpdateCursor(hitTestAnchor); // Capture the mouse. SetCapture(hwnd); ClipCursor(&clipRect); } return; } if (0 != (wParam & MK_RBUTTON)) { // Show popup menu. POINT pt; GetCursorPos(&pt); __raise RightMouseButtonClicked(ActiveOverlay->ActiveElement, &pt); return; } } void OverlayControl::MouseUp(HWND hwnd, WPARAM wParam, LPARAM lParam) { if (!ActiveOverlay) return; // Release mouse. ClipCursor(0); ReleaseCapture(); ResetCursor(); } void OverlayControl::MouseMove(HWND hwnd, WPARAM wParam, LPARAM lParam) { if (!ActiveOverlay || !ActiveOverlay->ActiveElement) { ResetCursor(); return; } RECT clientRect; GetClientRect(hwnd, &clientRect); POINT pt; GetCursorPosition(hwnd, &pt); if (0 != (wParam & MK_LBUTTON)) { RECT elementRect; memmove(&elementRect, &elementRectAnchor, sizeof(elementRect)); int dx = pt.x - clickAnchor.x, dy = pt.y - clickAnchor.y; bool updateAnchors = false; // Move/drag element. if (0 != (hitTestAnchor & ohtLeftBorder)) { if (ohtInside != hitTestAnchor && dx > 0 && RectWidth(elementRect) - dx < OverlayElement::MinimalSize) dx = RectWidth(elementRect) - OverlayElement::MinimalSize; elementRect.left += dx; } if (0 != (hitTestAnchor & ohtRightBorder)) { if (ohtInside != hitTestAnchor && dx < 0 && RectWidth(elementRect) + dx < OverlayElement::MinimalSize) dx = OverlayElement::MinimalSize - RectWidth(elementRect); elementRect.right += dx; } if (0 != (hitTestAnchor & ohtTopBorder)) { if (ohtInside != hitTestAnchor && dy > 0 && RectHeight(elementRect) - dy < OverlayElement::MinimalSize) dy = RectHeight(elementRect) - OverlayElement::MinimalSize; elementRect.top += dy; } if (0 != (hitTestAnchor & ohtBottomBorder)) { if (ohtInside != hitTestAnchor && dy < 0 && RectHeight(elementRect) + dy < OverlayElement::MinimalSize) dy = OverlayElement::MinimalSize - RectHeight(elementRect); elementRect.bottom += dy; } // Check for sanity. if (elementRect.left < clientRect.left) { updateAnchors = true; OffsetRect(&elementRect, clientRect.left - elementRect.left, 0); } if (elementRect.right > clientRect.right) { updateAnchors = true; OffsetRect(&elementRect, clientRect.right - elementRect.right, 0); } if (elementRect.top < clientRect.top) { updateAnchors = true; OffsetRect(&elementRect, 0, clientRect.top - elementRect.top); } if (elementRect.bottom > clientRect.bottom) { updateAnchors = true; OffsetRect(&elementRect, 0, clientRect.bottom - elementRect.bottom); } if (updateAnchors) { memmove(&clickAnchor, &pt, sizeof(clickAnchor)); memmove(&elementRectAnchor, &elementRect, sizeof(elementRectAnchor)); } // Update element coordinates. ActiveOverlay->ActiveElement->SetRect(&clientRect, &elementRect); // Drag object under cursor. RepaintAll(hwnd); } else { // No mouse keys pressed -- change cursor accordingly to what's // visible on the screen. OverlayHitTest hitTest = ohtNone; OverlayElement *element = ActiveOverlay->ActiveElement; if (ActiveOverlay->ActiveElement && !ActiveOverlay->HitTestElement(ActiveOverlay->ActiveElement, &clientRect, &pt, &hitTest)) { element = ActiveOverlay->FindElementFromPoint(&clientRect, &pt, &hitTest); } if (0 != element && element == ActiveOverlay->ActiveElement && ohtInside != hitTest) UpdateCursor(hitTest); else ResetCursor(); } }
23.007353
107
0.71109
mkmpvtltd1
fd1c2497840d64b8bc73e62fdaa9815b1ca59956
6,430
hpp
C++
src/server/piece/Piece.hpp
LB--/ChessPlusPlus
70b389f0c3f4a5299ed4a2292bed22383ff95ed0
[ "Apache-1.1" ]
1
2021-07-11T18:04:34.000Z
2021-07-11T18:04:34.000Z
src/server/piece/Piece.hpp
LB--/ChessPlusPlus
70b389f0c3f4a5299ed4a2292bed22383ff95ed0
[ "Apache-1.1" ]
null
null
null
src/server/piece/Piece.hpp
LB--/ChessPlusPlus
70b389f0c3f4a5299ed4a2292bed22383ff95ed0
[ "Apache-1.1" ]
2
2017-10-02T23:25:35.000Z
2019-09-08T10:03:34.000Z
#ifndef chesspp_server_piece_Piece_HeaderPlusPlus #define chesspp_server_piece_Piece_HeaderPlusPlus #include "server/config/BoardConfig.hpp" #include <memory> #include <set> #include <typeinfo> #include <iosfwd> namespace chesspp { namespace server { namespace board { class Board; } namespace piece { /** * \brief * A chess piece. */ class Piece { friend class ::chesspp::server::board::Board; public: using Position_t = config::BoardConfig::Position_t; using Suit_t = config::BoardConfig::SuitClass_t; using Class_t = config::BoardConfig::PieceClass_t; /** * \brief * The chesspp::board::Board in which the Piece exists. */ board::Board &board; private: Position_t p; Suit_t s; Class_t c; std::size_t m = 0; public: /** * \brief * The position of this piece. */ Position_t const &pos = p; /** * \brief * The display suit of this piece (e.g. Black or White). */ Suit_t const &suit = s; /** * \brief * The display class of this piece (e.g. Pawn, Rook, etc). * * \note * This cannot be used to determine what kind of piece this is, as this value is * only for display purposes and may not match the actual type. */ Class_t const &pclass = c; /** * \brief * The number of moves this piece has made. */ std::size_t const &moves = m; /** * \brief * Construct onto a board at the given position with the given suit and class. * * \param b The chesspp::board::Board on which this piece is to live, must outlive * this instance. * \param pos The initial position of this piece. * \param s The display suit of the piece. * \param pc The display class of the piece. */ Piece(board::Board &b, Position_t const &pos, Suit_t const &s, Class_t const &pc); virtual ~Piece() = default; /** * \brief * Update movement information. * * \note * Should not be overridden or shadowed by deriving classes. */ void makeTrajectory() { addCapturable(pos); calcTrajectory(); } protected: /** * \brief * Called by `makeTrajectory()` to calculate movement information. * * Implementations should call `addTrajectory()`, `addCapturing()`, and * `addCapturable()`, as well as their `remove` counterparts if necessary. By * default, `addCapturable()` is called with the current position of the piece * before this member function is called. */ virtual void calcTrajectory() = 0; /** * \brief * Mark a position as a valid position to move to without capturing. * * \param tile The position to mark. */ void addTrajectory(Position_t const &tile); /** * \brief * Unmark a position as a valid position to move to without capturing. * * \param tile The position to unmark. */ void removeTrajectory(Position_t const &tile); /** * \brief * Mark a position as a valid position to move to when capturing. * * \param tile The position to mark. */ void addCapturing(Position_t const &tile); /** * \brief * Unmark a position as a valid position to move to when capturing. * * \param tile The position to unmark. */ void removeCapturing(Position_t const &tile); /** * \brief * Mark a position as a valid position to capture this piece from. * * \param tile The position to mark. */ void addCapturable(Position_t const &tile); /** * \brief * Unmark a position as a valid position to capture this piece from. * * \param tile The position to mark. */ void removeCapturable(Position_t const &tile); private: /** * \brief * Called when another piece moves on the same board. * * \param m The position of the piece that moved. */ virtual void tick(Position_t const &m) { } /** * \brief * The chesspp::board::Board calls this to change the position of the piece. * * \param to The new position of the piece. */ void move(Position_t const &to) { Position_t from = pos; p = to; moveUpdate(from, to); ++m; } /** * \brief * Called after this piece has moved. * * \note * The value of `moves` is not updated until after this member function returns. * * \param from The old position of the piece. * \param to The current position of the piece. */ virtual void moveUpdate(Position_t const &from, Position_t const &to) { } public: /** * \brief * Outputs a basic human-readable description of this piece to an output stream. * * \param os The stream to which to describe this piece. * \param p The piece to describe. */ friend std::ostream &operator<<(std::ostream &os, Piece const &p); }; } }} #endif
31.519608
94
0.473872
LB--
fd1f55dd9bc4b4175c4acc40a89ed26b1f343964
187
hpp
C++
pythran/pythonic/include/numpy/add/accumulate.hpp
davidbrochart/pythran
24b6c8650fe99791a4091cbdc2c24686e86aa67c
[ "BSD-3-Clause" ]
1,647
2015-01-13T01:45:38.000Z
2022-03-28T01:23:41.000Z
pythran/pythonic/include/numpy/add/accumulate.hpp
davidbrochart/pythran
24b6c8650fe99791a4091cbdc2c24686e86aa67c
[ "BSD-3-Clause" ]
1,116
2015-01-01T09:52:05.000Z
2022-03-18T21:06:40.000Z
pythran/pythonic/include/numpy/add/accumulate.hpp
davidbrochart/pythran
24b6c8650fe99791a4091cbdc2c24686e86aa67c
[ "BSD-3-Clause" ]
180
2015-02-12T02:47:28.000Z
2022-03-14T10:28:18.000Z
#ifndef PYTHONIC_INCLUDE_NUMPY_ADD_ACCUMULATE_HPP #define PYTHONIC_INCLUDE_NUMPY_ADD_ACCUMULATE_HPP #define UFUNC_NAME add #include "pythonic/include/numpy/ufunc_accumulate.hpp" #endif
23.375
54
0.877005
davidbrochart
fd23938cbc9e14eab4be2683bbcd009f4bf8c631
15,242
cpp
C++
prototype/src/asf_meta/meta_ut1_table.cpp
glshort/MapReady
c9065400a64c87be46418ab32e3a251ca2f55fd5
[ "BSD-3-Clause" ]
3
2017-12-31T05:33:28.000Z
2021-07-28T01:51:22.000Z
prototype/src/asf_meta/meta_ut1_table.cpp
glshort/MapReady
c9065400a64c87be46418ab32e3a251ca2f55fd5
[ "BSD-3-Clause" ]
null
null
null
prototype/src/asf_meta/meta_ut1_table.cpp
glshort/MapReady
c9065400a64c87be46418ab32e3a251ca2f55fd5
[ "BSD-3-Clause" ]
7
2017-04-26T18:18:33.000Z
2020-05-15T08:01:09.000Z
/* Table prepared by script process_epoc.sh eopc01.1900-2006 on Tue Jun 20 10:53:11 AKDT 2006 Format: <UTC year> <TAI-UTC> <UT1-TAI> (DUT source) */ { 1972.00, 10, -10.04749},/*IERS*/ { 1972.10, 10, -10.16419},/*IERS*/ { 1972.20, 10, -10.28450},/*IERS*/ { 1972.30, 10, -10.41373},/*IERS*/ { 1972.40, 10, -10.54006},/*IERS*/ { 1972.50, 11, -10.64084},/*IERS*/ { 1972.60, 11, -10.73373},/*IERS*/ { 1972.70, 11, -10.83149},/*IERS*/ { 1972.80, 11, -10.94923},/*IERS*/ { 1972.90, 11, -11.06709},/*IERS*/ { 1973.00, 12, -11.18856},/*IERS*/ { 1973.10, 12, -11.30265},/*IERS*/ { 1973.20, 12, -11.42686},/*IERS*/ { 1973.30, 12, -11.55778},/*IERS*/ { 1973.40, 12, -11.67471},/*IERS*/ { 1973.50, 12, -11.77400},/*IERS*/ { 1973.60, 12, -11.86491},/*IERS*/ { 1973.70, 12, -11.96185},/*IERS*/ { 1973.80, 12, -12.07210},/*IERS*/ { 1973.90, 12, -12.19501},/*IERS*/ { 1974.00, 13, -12.29977},/*IERS*/ { 1974.10, 13, -12.39364},/*IERS*/ { 1974.20, 13, -12.50162},/*IERS*/ { 1974.30, 13, -12.61288},/*IERS*/ { 1974.40, 13, -12.72934},/*IERS*/ { 1974.50, 13, -12.81714},/*IERS*/ { 1974.60, 13, -12.88905},/*IERS*/ { 1974.70, 13, -12.97471},/*IERS*/ { 1974.80, 13, -13.08026},/*IERS*/ { 1974.90, 13, -13.19056},/*IERS*/ { 1975.00, 14, -13.29168},/*IERS*/ { 1975.10, 14, -13.39445},/*IERS*/ { 1975.20, 14, -13.49861},/*IERS*/ { 1975.30, 14, -13.61121},/*IERS*/ { 1975.40, 14, -13.71758},/*IERS*/ { 1975.50, 14, -13.80278},/*IERS*/ { 1975.60, 14, -13.86928},/*IERS*/ { 1975.70, 14, -13.95555},/*IERS*/ { 1975.80, 14, -14.05870},/*IERS*/ { 1975.90, 14, -14.17115},/*IERS*/ { 1976.00, 15, -14.27485},/*IERS*/ { 1976.10, 15, -14.37858},/*IERS*/ { 1976.20, 15, -14.48529},/*IERS*/ { 1976.30, 15, -14.60920},/*IERS*/ { 1976.40, 15, -14.72609},/*IERS*/ { 1976.50, 15, -14.81439},/*IERS*/ { 1976.60, 15, -14.90276},/*IERS*/ { 1976.70, 15, -14.99438},/*IERS*/ { 1976.80, 15, -15.11295},/*IERS*/ { 1976.90, 15, -15.22922},/*IERS*/ { 1977.00, 16, -15.33429},/*IERS*/ { 1977.10, 16, -15.43486},/*IERS*/ { 1977.20, 16, -15.53991},/*IERS*/ { 1977.30, 16, -15.65816},/*IERS*/ { 1977.40, 16, -15.76907},/*IERS*/ { 1977.50, 16, -15.85318},/*IERS*/ { 1977.60, 16, -15.92317},/*IERS*/ { 1977.70, 16, -16.00853},/*IERS*/ { 1977.80, 16, -16.11962},/*IERS*/ { 1977.90, 16, -16.23631},/*IERS*/ { 1978.00, 17, -16.35048},/*IERS*/ { 1978.10, 17, -16.46424},/*IERS*/ { 1978.20, 17, -16.59385},/*IERS*/ { 1978.30, 17, -16.71645},/*IERS*/ { 1978.40, 17, -16.83222},/*IERS*/ { 1978.50, 17, -16.92002},/*IERS*/ { 1978.60, 17, -16.98716},/*IERS*/ { 1978.70, 17, -17.07543},/*IERS*/ { 1978.80, 17, -17.18262},/*IERS*/ { 1978.90, 17, -17.29274},/*IERS*/ { 1979.00, 18, -17.40095},/*IERS*/ { 1979.10, 18, -17.51263},/*IERS*/ { 1979.20, 18, -17.61610},/*IERS*/ { 1979.30, 18, -17.73014},/*IERS*/ { 1979.40, 18, -17.84034},/*IERS*/ { 1979.50, 18, -17.92136},/*IERS*/ { 1979.60, 18, -17.99174},/*IERS*/ { 1979.70, 18, -18.07234},/*IERS*/ { 1979.80, 18, -18.16697},/*IERS*/ { 1979.90, 18, -18.26064},/*IERS*/ { 1980.00, 19, -18.35506},/*IERS*/ { 1980.10, 19, -18.44519},/*IERS*/ { 1980.20, 19, -18.53334},/*IERS*/ { 1980.30, 19, -18.63331},/*IERS*/ { 1980.40, 19, -18.72368},/*IERS*/ { 1980.50, 19, -18.79364},/*IERS*/ { 1980.60, 19, -18.85472},/*IERS*/ { 1980.70, 19, -18.92492},/*IERS*/ { 1980.80, 19, -19.01279},/*IERS*/ { 1980.90, 19, -19.10786},/*IERS*/ { 1981.00, 19, -19.19533},/*IERS*/ { 1981.10, 19, -19.27770},/*IERS*/ { 1981.20, 19, -19.37273},/*IERS*/ { 1981.30, 19, -19.46855},/*IERS*/ { 1981.40, 19, -19.55874},/*IERS*/ { 1981.50, 20, -19.63015},/*IERS*/ { 1981.60, 20, -19.68015},/*IERS*/ { 1981.70, 20, -19.73470},/*IERS*/ { 1981.80, 20, -19.81950},/*IERS*/ { 1981.90, 20, -19.90425},/*IERS*/ { 1982.00, 20, -19.98157},/*IERS*/ { 1982.10, 20, -20.05764},/*IERS*/ { 1982.20, 20, -20.14294},/*IERS*/ { 1982.30, 20, -20.23245},/*IERS*/ { 1982.40, 20, -20.32120},/*IERS*/ { 1982.50, 21, -20.39269},/*IERS*/ { 1982.60, 21, -20.44047},/*IERS*/ { 1982.70, 21, -20.51094},/*IERS*/ { 1982.80, 21, -20.59604},/*IERS*/ { 1982.90, 21, -20.67953},/*IERS*/ { 1983.00, 21, -20.77233},/*IERS*/ { 1983.10, 21, -20.87840},/*IERS*/ { 1983.20, 21, -20.98260},/*IERS*/ { 1983.30, 21, -21.08940},/*IERS*/ { 1983.40, 21, -21.18155},/*IERS*/ { 1983.50, 22, -21.25242},/*IERS*/ { 1983.60, 22, -21.30479},/*IERS*/ { 1983.70, 22, -21.37015},/*IERS*/ { 1983.80, 22, -21.44164},/*IERS*/ { 1983.90, 22, -21.52831},/*IERS*/ { 1984.00, 22, -21.60454},/*IERS*/ { 1984.10, 22, -21.66061},/*IERS*/ { 1984.20, 22, -21.72310},/*IERS*/ { 1984.30, 22, -21.79878},/*IERS*/ { 1984.40, 22, -21.86186},/*IERS*/ { 1984.50, 22, -21.90229},/*IERS*/ { 1984.60, 22, -21.93164},/*IERS*/ { 1984.70, 22, -21.97718},/*IERS*/ { 1984.80, 22, -22.03639},/*IERS*/ { 1984.90, 22, -22.10288},/*IERS*/ { 1985.00, 22, -22.15755},/*IERS*/ { 1985.10, 22, -22.21164},/*IERS*/ { 1985.20, 22, -22.27369},/*IERS*/ { 1985.30, 22, -22.34299},/*IERS*/ { 1985.40, 22, -22.40256},/*IERS*/ { 1985.50, 23, -22.45214},/*IERS*/ { 1985.60, 23, -22.47489},/*IERS*/ { 1985.70, 23, -22.50517},/*IERS*/ { 1985.80, 23, -22.56613},/*IERS*/ { 1985.90, 23, -22.63315},/*IERS*/ { 1986.00, 23, -22.68677},/*IERS*/ { 1986.10, 23, -22.74045},/*IERS*/ { 1986.20, 23, -22.79309},/*IERS*/ { 1986.30, 23, -22.84464},/*IERS*/ { 1986.40, 23, -22.90151},/*IERS*/ { 1986.50, 23, -22.93016},/*IERS*/ { 1986.60, 23, -22.95058},/*IERS*/ { 1986.70, 23, -22.98209},/*IERS*/ { 1986.80, 23, -23.03895},/*IERS*/ { 1986.90, 23, -23.08991},/*IERS*/ { 1987.00, 23, -23.13808},/*IERS*/ { 1987.10, 23, -23.18654},/*IERS*/ { 1987.20, 23, -23.24637},/*IERS*/ { 1987.30, 23, -23.30866},/*IERS*/ { 1987.40, 23, -23.36392},/*IERS*/ { 1987.50, 23, -23.39857},/*IERS*/ { 1987.60, 23, -23.41932},/*IERS*/ { 1987.70, 23, -23.45848},/*IERS*/ { 1987.80, 23, -23.51296},/*IERS*/ { 1987.90, 23, -23.57487},/*IERS*/ { 1988.00, 24, -23.63580},/*IERS*/ { 1988.10, 24, -23.68559},/*IERS*/ { 1988.20, 24, -23.75280},/*IERS*/ { 1988.30, 24, -23.82072},/*IERS*/ { 1988.40, 24, -23.87745},/*IERS*/ { 1988.50, 24, -23.91014},/*IERS*/ { 1988.60, 24, -23.93105},/*IERS*/ { 1988.70, 24, -23.95515},/*IERS*/ { 1988.80, 24, -24.00189},/*IERS*/ { 1988.90, 24, -24.06531},/*IERS*/ { 1989.00, 24, -24.11503},/*IERS*/ { 1989.10, 24, -24.16144},/*IERS*/ { 1989.20, 24, -24.21817},/*IERS*/ { 1989.30, 24, -24.27613},/*IERS*/ { 1989.40, 24, -24.33885},/*IERS*/ { 1989.50, 24, -24.38600},/*IERS*/ { 1989.60, 24, -24.42140},/*IERS*/ { 1989.70, 24, -24.46111},/*IERS*/ { 1989.80, 24, -24.52280},/*IERS*/ { 1989.90, 24, -24.60148},/*IERS*/ { 1990.00, 25, -24.67052},/*IERS*/ { 1990.10, 25, -24.73857},/*IERS*/ { 1990.20, 25, -24.82081},/*IERS*/ { 1990.30, 25, -24.90511},/*IERS*/ { 1990.40, 25, -24.97988},/*IERS*/ { 1990.50, 25, -25.04038},/*IERS*/ { 1990.60, 25, -25.08310},/*IERS*/ { 1990.70, 25, -25.14583},/*IERS*/ { 1990.80, 25, -25.22266},/*IERS*/ { 1990.90, 25, -25.30233},/*IERS*/ { 1991.00, 26, -25.38103},/*IERS*/ { 1991.10, 26, -25.46249},/*IERS*/ { 1991.20, 26, -25.54368},/*IERS*/ { 1991.30, 26, -25.63048},/*IERS*/ { 1991.40, 26, -25.71474},/*IERS*/ { 1991.50, 26, -25.77556},/*IERS*/ { 1991.60, 26, -25.82080},/*IERS*/ { 1991.70, 26, -25.88546},/*IERS*/ { 1991.80, 26, -25.95804},/*IERS*/ { 1991.90, 26, -26.03975},/*IERS*/ { 1992.00, 26, -26.12531},/*IERS*/ { 1992.10, 26, -26.21336},/*IERS*/ { 1992.20, 26, -26.30379},/*IERS*/ { 1992.30, 26, -26.41029},/*IERS*/ { 1992.40, 26, -26.49599},/*IERS*/ { 1992.50, 27, -26.55791},/*IERS*/ { 1992.60, 27, -26.61077},/*IERS*/ { 1992.70, 27, -26.67686},/*IERS*/ { 1992.80, 27, -26.75412},/*IERS*/ { 1992.90, 27, -26.84612},/*IERS*/ { 1993.00, 27, -26.93602},/*IERS*/ { 1993.10, 27, -27.02831},/*IERS*/ { 1993.20, 27, -27.12756},/*IERS*/ { 1993.30, 27, -27.22865},/*IERS*/ { 1993.40, 27, -27.32495},/*IERS*/ { 1993.50, 28, -27.40242},/*IERS*/ { 1993.60, 28, -27.46253},/*IERS*/ { 1993.70, 28, -27.53203},/*IERS*/ { 1993.80, 28, -27.62255},/*IERS*/ { 1993.90, 28, -27.71486},/*IERS*/ { 1994.00, 28, -27.79932},/*IERS*/ { 1994.10, 28, -27.88382},/*IERS*/ { 1994.20, 28, -27.97527},/*IERS*/ { 1994.30, 28, -28.06622},/*IERS*/ { 1994.40, 28, -28.15865},/*IERS*/ { 1994.50, 29, -28.21844},/*IERS*/ { 1994.60, 29, -28.26859},/*IERS*/ { 1994.70, 29, -28.33348},/*IERS*/ { 1994.80, 29, -28.42066},/*IERS*/ { 1994.90, 29, -28.50642},/*IERS*/ { 1995.00, 29, -28.60090},/*IERS*/ { 1995.10, 29, -28.69718},/*IERS*/ { 1995.20, 29, -28.79435},/*IERS*/ { 1995.30, 29, -28.89725},/*IERS*/ { 1995.40, 29, -28.99328},/*IERS*/ { 1995.50, 29, -29.06358},/*IERS*/ { 1995.60, 29, -29.11361},/*IERS*/ { 1995.70, 29, -29.18038},/*IERS*/ { 1995.80, 29, -29.26329},/*IERS*/ { 1995.90, 29, -29.35337},/*IERS*/ { 1996.00, 30, -29.44481},/*IERS*/ { 1996.10, 30, -29.51008},/*IERS*/ { 1996.20, 30, -29.59074},/*IERS*/ { 1996.30, 30, -29.67417},/*IERS*/ { 1996.40, 30, -29.75456},/*IERS*/ { 1996.50, 30, -29.81371},/*IERS*/ { 1996.60, 30, -29.85922},/*IERS*/ { 1996.70, 30, -29.90147},/*IERS*/ { 1996.80, 30, -29.97022},/*IERS*/ { 1996.90, 30, -30.04416},/*IERS*/ { 1997.00, 30, -30.10965},/*IERS*/ { 1997.10, 30, -30.17309},/*IERS*/ { 1997.20, 30, -30.24820},/*IERS*/ { 1997.30, 30, -30.33871},/*IERS*/ { 1997.40, 30, -30.41623},/*IERS*/ { 1997.50, 31, -30.47382},/*IERS*/ { 1997.60, 31, -30.51875},/*IERS*/ { 1997.70, 31, -30.57240},/*IERS*/ { 1997.80, 31, -30.64863},/*IERS*/ { 1997.90, 31, -30.72153},/*IERS*/ { 1998.00, 31, -30.78121},/*IERS*/ { 1998.10, 31, -30.84997},/*IERS*/ { 1998.20, 31, -30.92540},/*IERS*/ { 1998.30, 31, -30.99751},/*IERS*/ { 1998.40, 31, -31.06848},/*IERS*/ { 1998.50, 31, -31.10114},/*IERS*/ { 1998.60, 31, -31.11460},/*IERS*/ { 1998.70, 31, -31.14183},/*IERS*/ { 1998.80, 31, -31.18624},/*IERS*/ { 1998.90, 31, -31.24017},/*IERS*/ { 1999.00, 32, -31.28314},/*IERS*/ { 1999.10, 32, -31.32083},/*IERS*/ { 1999.20, 32, -31.36002},/*IERS*/ { 1999.30, 32, -31.41203},/*IERS*/ { 1999.40, 32, -31.45641},/*IERS*/ { 1999.50, 32, -31.48014},/*IERS*/ { 1999.60, 32, -31.49444},/*IERS*/ { 1999.70, 32, -31.51801},/*IERS*/ { 1999.80, 32, -31.54939},/*IERS*/ { 1999.90, 32, -31.60251},/*IERS*/ { 2000.00, 32, -31.64452},/*IERS*/ { 2000.10, 32, -31.67494},/*IERS*/ { 2000.20, 32, -31.71001},/*IERS*/ { 2000.30, 32, -31.74474},/*IERS*/ { 2000.40, 32, -31.78012},/*IERS*/ { 2000.50, 32, -31.79592},/*IERS*/ { 2000.60, 32, -31.80120},/*IERS*/ { 2000.70, 32, -31.81286},/*IERS*/ { 2000.80, 32, -31.84000},/*IERS*/ { 2000.90, 32, -31.87947},/*IERS*/ { 2001.00, 32, -31.90630},/*IERS*/ { 2001.10, 32, -31.92371},/*IERS*/ { 2001.20, 32, -31.96111},/*IERS*/ { 2001.30, 32, -31.99033},/*IERS*/ { 2001.40, 32, -32.02290},/*IERS*/ { 2001.50, 32, -32.02782},/*IERS*/ { 2001.60, 32, -32.02061},/*IERS*/ { 2001.70, 32, -32.03042},/*IERS*/ { 2001.80, 32, -32.05585},/*IERS*/ { 2001.90, 32, -32.08686},/*IERS*/ { 2002.00, 32, -32.11544},/*IERS*/ { 2002.10, 32, -32.14173},/*IERS*/ { 2002.20, 32, -32.17393},/*IERS*/ { 2002.30, 32, -32.20071},/*IERS*/ { 2002.40, 32, -32.23035},/*IERS*/ { 2002.50, 32, -32.22962},/*IERS*/ { 2002.60, 32, -32.22404},/*IERS*/ { 2002.70, 32, -32.23033},/*IERS*/ { 2002.80, 32, -32.24297},/*IERS*/ { 2002.90, 32, -32.26122},/*IERS*/ { 2003.00, 32, -32.28924},/*IERS*/ { 2003.10, 32, -32.30788},/*IERS*/ { 2003.20, 32, -32.32854},/*IERS*/ { 2003.30, 32, -32.35880},/*IERS*/ { 2003.40, 32, -32.37457},/*IERS*/ { 2003.50, 32, -32.36613},/*IERS*/ { 2003.60, 32, -32.35380},/*IERS*/ { 2003.70, 32, -32.35299},/*IERS*/ { 2003.80, 32, -32.36284},/*IERS*/ { 2003.90, 32, -32.38076},/*IERS*/ { 2004.00, 32, -32.38958},/*IERS*/ { 2004.10, 32, -32.40412},/*IERS*/ { 2004.20, 32, -32.42257},/*IERS*/ { 2004.30, 32, -32.45126},/*IERS*/ { 2004.40, 32, -32.46832},/*IERS*/ { 2004.50, 32, -32.46861},/*IERS*/ { 2004.60, 32, -32.45463},/*IERS*/ { 2004.70, 32, -32.45006},/*IERS*/ { 2004.80, 32, -32.46423},/*IERS*/ { 2004.90, 32, -32.48719},/*IERS*/ { 2005.00, 32, -32.50336},/*IERS*/ { 2005.10, 32, -32.52311},/*IERS*/ { 2005.20, 32, -32.56365},/*IERS*/ { 2005.30, 32, -32.58598},/*IERS*/ { 2005.40, 32, -32.61477},/*IERS*/ { 2005.50, 32, -32.61517},/*IERS*/ { 2005.60, 32, -32.60093},/*IERS*/ { 2005.70, 32, -32.60041},/*IERS*/ { 2005.80, 32, -32.61887},/*IERS*/ { 2005.90, 32, -32.64200},/*IERS*/ { 2006.00, 33, -32.66113},/*IERS*/ { 2006.10, 33, -32.68219},/*IERS*/ { 2006.20, 33, -32.71340},/*IERS*/ { 2006.30, 33, -32.74972},/*IERS*/ { 2006.40, 33, -32.81039},/*pred*/ { 2006.50, 33, -32.81648},/*pred*/ { 2006.60, 33, -32.80854},/*pred*/ { 2006.70, 33, -32.80703},/*pred*/ { 2006.80, 33, -32.82483},/*pred*/ { 2006.90, 33, -32.85479},/*pred*/ { 2007.00, 33, -32.88236},/*pred*/ { 2007.10, 33, -32.90476},/*pred*/ { 2007.20, 33, -32.93106},/*pred*/ { 2007.30, 33, -32.96344},/*pred*/ { 2007.40, 33, -32.98924},/*pred*/ { 2007.50, 33, -32.99547},/*pred*/ { 2007.60, 33, -32.98757},/*pred*/ { 2007.70, 33, -32.98595},/*pred*/ { 2007.80, 33, -33.00362},/*pred*/ { 2007.90, 33, -33.03355},/*pred*/ { 2008.00, 33, -33.06117},/*pred*/ { 2008.10, 33, -33.08358},/*pred*/ { 2008.20, 33, -33.10983},/*pred*/ { 2008.30, 33, -33.14220},/*pred*/ { 2008.40, 33, -33.16810},/*pred*/ { 2008.50, 33, -33.17446},/*pred*/ { 2008.60, 33, -33.16659},/*pred*/ { 2008.70, 33, -33.16486},/*pred*/ { 2008.80, 33, -33.18242},/*pred*/ { 2008.90, 33, -33.21232},/*pred*/ { 2009.00, 33, -33.23998},/*pred*/ { 2009.10, 33, -33.26302},/*pred*/ { 2009.20, 33, -33.28943},/*pred*/ { 2009.30, 33, -33.32183},/*pred*/ { 2009.40, 33, -33.34742},/*pred*/ { 2009.50, 33, -33.35336},/*pred*/ { 2009.60, 33, -33.34539},/*pred*/ { 2009.70, 33, -33.34399},/*pred*/ { 2009.80, 33, -33.36194},/*pred*/ { 2009.90, 33, -33.39192},/*pred*/ { 2010.00, 33, -33.41945},/*pred*/ { 2010.10, 33, -33.44184},/*pred*/ { 2010.20, 33, -33.46820},/*pred*/ { 2010.30, 33, -33.50059},/*pred*/ { 2010.40, 33, -33.52627},/*pred*/ { 2010.50, 33, -33.53235},/*pred*/ { 2010.60, 33, -33.52441},/*pred*/ { 2010.70, 33, -33.52291},/*pred*/ { 2010.80, 33, -33.54073},/*pred*/ { 2010.90, 33, -33.57069},/*pred*/ { 2011.00, 33, -33.59826},/*pred*/ { 2011.10, 33, -33.62066},/*pred*/ { 2011.20, 33, -33.64696},/*pred*/ { 2011.30, 33, -33.67935},/*pred*/ { 2011.40, 33, -33.70513},/*pred*/ { 2011.50, 33, -33.71134},/*pred*/ { 2011.60, 33, -33.70343},/*pred*/ { 2011.70, 33, -33.70183},/*pred*/ { 2011.80, 33, -33.71952},/*pred*/ { 2011.90, 33, -33.74945},/*pred*/ { 2012.00, 33, -33.77707},/*pred*/ { 2012.10, 33, -33.79948},/*pred*/ { 2012.20, 33, -33.82573},/*pred*/ { 2012.30, 33, -33.85810},/*pred*/ { 2012.40, 33, -33.88399},/*pred*/ { 2012.50, 33, -33.89034},/*pred*/ { 2012.60, 33, -33.88246},/*pred*/ { 2012.70, 33, -33.88075},/*pred*/ { 2012.80, 33, -33.89832},/*pred*/ { 2012.90, 33, -33.92822},/*pred*/ { 2013.00, 33, -33.95587},/*pred*/ { 2013.10, 33, -33.97892},/*pred*/ { 2013.20, 33, -34.00533},/*pred*/ { 2013.30, 33, -34.03773},/*pred*/ { 2013.40, 33, -34.06331},/*pred*/ { 2013.50, 33, -34.06923},/*pred*/ { 2013.60, 33, -34.06125},/*pred*/ { 2013.70, 33, -34.05987},/*pred*/ { 2013.80, 33, -34.07783},/*pred*/ { 2013.90, 33, -34.10782},/*pred*/ { 2014.00, 33, -34.13534},/*pred*/ { 2014.10, 33, -34.15774},/*pred*/ { 2014.20, 33, -34.18410},/*pred*/ { 2014.30, 33, -34.21649},/*pred*/ { 2014.40, 33, -34.24216},/*pred*/ { 2014.50, 33, -34.24822},/*pred*/ { 2014.60, 33, -34.24028},/*pred*/ { 2014.70, 33, -34.23879},/*pred*/ { 2014.80, 33, -34.25663},/*pred*/ { 2014.90, 33, -34.28659},/*pred*/ { 2015.00, 33, -34.31415},/*pred*/
34.719818
45
0.544286
glshort
fd27823da30cf2c99148fc361d2ed35542f6ab40
2,130
cpp
C++
src/util/string_util.cpp
luist18/feup-aeda-proj1
c9d500f3fbc24d36fed85a706926872094c2bf0b
[ "MIT" ]
null
null
null
src/util/string_util.cpp
luist18/feup-aeda-proj1
c9d500f3fbc24d36fed85a706926872094c2bf0b
[ "MIT" ]
null
null
null
src/util/string_util.cpp
luist18/feup-aeda-proj1
c9d500f3fbc24d36fed85a706926872094c2bf0b
[ "MIT" ]
1
2020-04-03T17:10:34.000Z
2020-04-03T17:10:34.000Z
#include <vector> #include <string> #include <sstream> #include <iomanip> #include <random> #include <algorithm> #include "string_util.h" std::vector<std::string> string_util::split(const std::string &string, const std::string &delimiter) { std::string aux = string; std::string token; size_t pos = 0; std::vector<std::string> res; while ((pos = aux.find(delimiter)) != std::string::npos) { token = aux.substr(0, pos); res.push_back(token); aux.erase(0, pos + delimiter.length()); } res.push_back(aux); return res; } std::string string_util::random_password(int length) { std::random_device rd; std::mt19937 mt(rd()); const char characters[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; std::stringstream password_stream; std::uniform_real_distribution<double> dist(0.0, (double) sizeof(characters) - .01); for (int i = 0; i < length; i++) { password_stream << characters[(int) dist(mt)]; } return password_stream.str(); } bool string_util::is_number(const std::string &string) { return !string.empty() && std::find_if(string.begin(), string.end(), [](char c) { return !std::isdigit(c); }) == string.end(); } std::string string_util::trim(const std::string &string) { auto it_b = string.begin(); for (; *it_b == ' '; it_b++); auto it_e = string.end() - 1; for (; *it_e == ' '; it_e--); int size = it_e + 1 - it_b; return string.substr(it_b - string.begin(), size < 0 ? 0 : size); } std::string string_util::pad_number(int number, int n) { std::string res = std::to_string(number); while (res.length() < n) res = "0" + res; return res; } std::string string_util::capitalize(std::string string) { string[0] = toupper(string[0]); for (int i = 1; i < string.size(); i++) string[i] = tolower(string[i]); return string; } std::string string_util::removeCarriageReturn(std::string string) { if (!string.empty() && string.back() == '\r') string.erase(string.size() - 1); return string; }
27.662338
114
0.615023
luist18
fd2e91aee0cd8b477dfab122b7ad308982499973
3,178
cpp
C++
gueepo2D/engine/core/renderer/Renderer.cpp
guilhermepo2/gueepo2D
deb03ff39c871710c07d36c366b53b34dbfebf08
[ "MIT" ]
1
2022-02-03T19:24:47.000Z
2022-02-03T19:24:47.000Z
gueepo2D/engine/core/renderer/Renderer.cpp
guilhermepo2/gueepo2D
deb03ff39c871710c07d36c366b53b34dbfebf08
[ "MIT" ]
4
2021-10-30T19:03:07.000Z
2022-02-10T01:06:02.000Z
gueepo2D/engine/core/renderer/Renderer.cpp
guilhermepo2/gueepo2D
deb03ff39c871710c07d36c366b53b34dbfebf08
[ "MIT" ]
1
2021-10-01T03:08:21.000Z
2021-10-01T03:08:21.000Z
#include "gueepo2Dpch.h" #include "Renderer.h" #include "core/Containers/string.h" #include "core/filesystem/Filesystem.h" #include "core/renderer/OrtographicCamera.h" #include "core/Renderer/RendererAPI.h" #include "core/Renderer/Shader.h" #include "core/Renderer/SpriteBatcher.h" // Specific Renderer APIs #include "platform/OpenGL/OpenGLRendererAPI.h" namespace gueepo { static RendererAPI* s_RendererAPI = nullptr; static ShaderLibrary shaderLibrary; SpriteBatcher* Renderer::s_spriteBatcher = nullptr; SpriteBatcher* Renderer::s_uiBatcher; static RendererAPI* InitRendererAPI() { switch (RendererAPI::GetAPI()) { case RendererAPI::API::None: LOG_ERROR("RENDERER API 'NONE' NOT IMPLEMENTED!"); break; case RendererAPI::API::OpenGL: return new OpenGLRendererAPI(); break; case RendererAPI::API::DirectX: case RendererAPI::API::Vulkan: case RendererAPI::API::Metal: LOG_ERROR("RENDERER API NOT IMPLEMENTED!"); break; } return nullptr; } // ======================================================================== // ======================================================================== void Renderer::Initialize() { s_RendererAPI = InitRendererAPI(); s_spriteBatcher = new SpriteBatcher(); s_uiBatcher = new SpriteBatcher(); if (s_RendererAPI == nullptr) { LOG_ERROR("Error initializing Renderer API"); return; } // #todo: well, ideally we should have a default assets folder or some way that we know this is not going to break, lmao. // I think it makes sense that the renderer itself handles the shaders, not the batches... LOG_INFO("Verifying shaders folder..."); bool bShaderPathExists = gueepo::filesystem::DirectoryExists("./assets/shaders"); if (bShaderPathExists) { shaderLibrary.Load("sprite shader", "./assets/shaders/sprite.vertex", "./assets/shaders/sprite.fragment"); shaderLibrary.Load("font shader", "./assets/shaders/font.vertex", "./assets/shaders/font.fragment"); } else { LOG_ERROR("couldn't find path assets/shaders"); LOG_ERROR("there might be issues with the renderer!"); return; } s_spriteBatcher->Initialize(s_RendererAPI, shaderLibrary.Get("sprite shader")); s_uiBatcher->Initialize(s_RendererAPI, shaderLibrary.Get("font shader")); } void Renderer::Shutdown() { s_spriteBatcher->Shutdown(); s_uiBatcher->Shutdown(); delete s_spriteBatcher; delete s_uiBatcher; } void Renderer::Begin(const OrtographicCamera& camera) { s_RendererAPI->SetClearColor( camera.GetBackGroundColor().rgba[0], camera.GetBackGroundColor().rgba[1], camera.GetBackGroundColor().rgba[2], camera.GetBackGroundColor().rgba[3] ); s_RendererAPI->Clear(); s_spriteBatcher->Begin(camera); s_uiBatcher->Begin(camera); } void Renderer::End() { s_spriteBatcher->End(); s_uiBatcher->End(); } /* void Renderer::Submit(VertexArray* vertexArray, Shader* shader) { shader->Bind(); shader->SetMat4("u_ViewProjection", s_RenderData.ViewProjection); vertexArray->Bind(); s_RendererAPI->DrawIndexed(vertexArray); } */ void Renderer::SetUnpackAlignment(int value) { s_RendererAPI->SetUnpackAlignment(value); } }
27.877193
123
0.69163
guilhermepo2
fd3064ad9e0677815b06b9eb961cf0c0376d285c
295
hh
C++
events/NewPlayerEvent.hh
deb0ch/R-Type
8bb37cd5ec318efb97119afb87d4996f6bb7644e
[ "WTFPL" ]
5
2016-03-15T20:14:10.000Z
2020-10-30T23:56:24.000Z
events/NewPlayerEvent.hh
deb0ch/R-Type
8bb37cd5ec318efb97119afb87d4996f6bb7644e
[ "WTFPL" ]
3
2018-12-19T19:12:44.000Z
2020-04-02T13:07:00.000Z
events/NewPlayerEvent.hh
deb0ch/R-Type
8bb37cd5ec318efb97119afb87d4996f6bb7644e
[ "WTFPL" ]
2
2016-04-11T19:29:28.000Z
2021-11-26T20:53:22.000Z
#ifndef NEWPLAYEREVENT_H_ # define NEWPLAYEREVENT_H_ # include "AEvent.hh" class NewPlayerEvent : public AEvent { public: NewPlayerEvent(unsigned int hash); virtual ~NewPlayerEvent(); unsigned int getRemoteId() const; protected: unsigned int _hash; }; #endif /* !NEWPLAYEREVENT_H_ */
17.352941
36
0.752542
deb0ch
fd327d1641017eb8fd91a66d05ede5f755759d7a
10,510
cpp
C++
frenet_planner_ros/src/frenetROS_obst.cpp
anime-sh/frenet-gym
2f8f4aa5a3de8c0e63aee81b0891ea0cf16bc305
[ "MIT" ]
1
2021-12-10T11:40:12.000Z
2021-12-10T11:40:12.000Z
frenet_planner_ros/src/frenetROS_obst.cpp
anime-sh/frenet-gym
2f8f4aa5a3de8c0e63aee81b0891ea0cf16bc305
[ "MIT" ]
1
2021-05-29T09:12:19.000Z
2021-05-29T09:12:19.000Z
frenet_planner_ros/src/frenetROS_obst.cpp
anime-sh/frenet-gym
2f8f4aa5a3de8c0e63aee81b0891ea0cf16bc305
[ "MIT" ]
1
2020-09-17T14:30:44.000Z
2020-09-17T14:30:44.000Z
#include "../include/frenet_optimal_trajectory.hpp" #include <ros/ros.h> #include <geometry_msgs/Twist.h> #include <nav_msgs/Path.h> #include <tf/transform_datatypes.h> #include <utility> #include <ros/console.h> #include <std_msgs/String.h> #include <std_msgs/Float64.h> #include <thread> #include <chrono> namespace plt = matplotlibcpp; std_msgs::String path_id; vecD FrenetPath::get_x() { return x; } vecD FrenetPath::get_y() { return y; } vecD FrenetPath::get_d() { return d; } vecD FrenetPath::get_c() { return c; } vecD FrenetPath::get_s_d() { return s_d; } vecD FrenetPath::get_s() { return s; } vecD FrenetPath::get_d_d() { return d_d; } vecD FrenetPath::get_d_dd() { return d_dd; } vecD FrenetPath::get_yaw() { return yaw; } double FrenetPath::get_cf() { return cf; } void path_id_callback(const std_msgs::String msg) { path_id = msg; got_path = true; } void action_callback(const geometry_msgs::Twist::ConstPtr& msg) { twist = *msg; no_action = false; } void odom_callback(const nav_msgs::Odometry::ConstPtr& msg) { odom = *msg; //ROS_INFO("Odom Received"); } void global_callback(const nav_msgs::Path::ConstPtr& msg) { path = *msg; } double calc_dis(double x1, double y1, double x2, double y2) { return sqrt(pow((x1 - x2), 2) + pow((y1 - y2), 2)); } void find_nearest_in_global_path(vecD global_x, vecD global_y, double &min_x, double &min_y, double &min_dis, int &min_id, int flag, FrenetPath path) { double bot_x, bot_y; if(flag==0) { bot_x = odom.pose.pose.position.x; bot_y = odom.pose.pose.position.y; } else { bot_x = path.get_x()[1]; bot_y = path.get_y()[1]; } min_dis = FLT_MAX; for(int i = 0; i < global_x.size(); i++) { double dis = calc_dis(global_x[i], global_y[i], bot_x, bot_y); if(dis < min_dis) { min_dis = dis; min_x = global_x[i]; min_y = global_y[i]; min_id = i; } } } double calc_s(double ptx, double pty, vecD global_x, vecD global_y) { double s = 0; if(global_x[0] == ptx && global_y[0] == pty) return s; for(int i = 1; i < global_x.size(); i++) { double dis = calc_dis(global_x[i], global_y[i], global_x[i - 1], global_y[i - 1]); s = s + dis; if(global_x[i] == ptx && global_y[i] == pty) break; } return s; } double get_bot_yaw() { geometry_msgs::Pose p = odom.pose.pose; tf::Quaternion q(p.orientation.x, p.orientation.y, p.orientation.z, p.orientation.w); tf::Matrix3x3 m(q); double roll, pitch, yaw; m.getRPY(roll, pitch, yaw); return yaw; } vecD global_path_yaw(Spline2D csp, vecD gx, vecD gy) { vecD yaw; vecD t = csp.calc_s(gx, gy); for(int i = 0; i < t.size(); i++) { yaw.push_back(csp.calc_yaw(t[i])); } return yaw; } void initial_conditions_path(Spline2D csp, vecD global_x, vecD global_y, vecD ryaw, double &s0, double &c_speed, double &c_d, double &c_d_d, double &c_d_dd, double &bot_yaw, FrenetPath path) { // Approach 1 vecD k= path.get_c(); vecD d = path.get_d(); vecD s_d = path.get_s_d(); vecD d_d = path.get_d_d(); vecD d_dd = path.get_d_dd(); vecD s= path.get_s(); s0= s[1]; c_speed = s_d[1]; c_d = d[1]; c_d_d= d_d[1]; c_d_dd= 0; bot_yaw = get_bot_yaw(); } void initial_conditions_new(Spline2D csp, vecD global_x, vecD global_y, vecD ryaw, double &s0, double &c_speed, double &c_d, double &c_d_d, double &c_d_dd, double bot_yaw) { FrenetPath path; double vx = odom.twist.twist.linear.x; double vy = odom.twist.twist.linear.y; double v = sqrt(vx*vx + vy*vy); double min_x, min_y; int min_id; // getting d find_nearest_in_global_path(global_x, global_y, min_x, min_y, c_d, min_id, 0, path); // deciding the sign for d pair<double, double> vec1, vec2; vec1.first = odom.pose.pose.position.x - global_x[min_id]; vec1.second = odom.pose.pose.position.y - global_y[min_id]; vec2.first = global_x[min_id] - global_x[min_id + 1]; vec2.second = global_y[min_id] - global_y[min_id + 1]; double curl2D = vec1.first*vec2.second - vec2.first*vec1.second; if(curl2D < 0) c_d *= -1; s0 = calc_s(min_x, min_y, global_x, global_y); bot_yaw = get_bot_yaw(); vecD theta = global_path_yaw(csp, global_x, global_y); double g_path_yaw = theta[min_id]; double delta_theta = bot_yaw - g_path_yaw; c_d_d = v*sin(delta_theta);//Equation 5 double k_r = csp.calc_curvature(s0); c_speed = v*cos(delta_theta) / (1 - k_r*c_d); //s_dot (Equation 7) c_d_dd = 0; // For the time being. Need to be updated } void publishPath(nav_msgs::Path &path_msg, FrenetPath path, vecD rk, vecD ryaw, double &c_speed, double &c_d, double &c_d_d) { vecD x_vec = path.get_x(); vecD y_vec = path.get_y(); for(int i = 0; i < path.get_x().size(); i++) { geometry_msgs::PoseStamped loc; loc.pose.position.x = x_vec[i]; loc.pose.position.y = y_vec[i]; double delta_theta = atan(c_d_d / ((1 - rk[i]*c_d)*c_speed)); double yaw = delta_theta + ryaw[i]; tf::Quaternion q = tf::createQuaternionFromRPY(0, 0, yaw); // roll , pitch = 0 q.normalize(); quaternionTFToMsg(q, loc.pose.orientation); path_msg.poses.push_back(loc); } } int main(int argc, char **argv) { ros::init(argc, argv, "frenet_planner"); ros::NodeHandle n; ros::Publisher frenet_path = n.advertise<nav_msgs::Path>("/frenet_path", 1); ros::Publisher target_vel = n.advertise<geometry_msgs::Twist>("/cmd_vel", 10); //Publish velocity ros::Publisher cost_fp = n.advertise<std_msgs::Float64>("/cost_fp", 10); //cost publish ros::Subscriber global_sub = n.subscribe("/global_path", 100, global_callback); ros::Subscriber odom_sub = n.subscribe("/carla/ego_vehicle/odometry", 10, odom_callback); //different subscriber ros::Subscriber action_sub = n.subscribe("/action", 1000, action_callback); ros::Subscriber path_id_sub = n.subscribe("/path_id", 1000, path_id_callback); ROS_INFO("Getting params"); // get params n.getParam("/frenet_planner/path/max_speed", MAX_SPEED); n.getParam("/frenet_planner/path/max_accel", MAX_ACCEL); n.getParam("/frenet_planner/path/max_curvature", MAX_CURVATURE); n.getParam("/frenet_planner/path/max_road_width", MAX_ROAD_WIDTH); n.getParam("/frenet_planner/path/d_road_w", D_ROAD_W); n.getParam("/frenet_planner/path/dt", DT); n.getParam("/frenet_planner/path/maxt", MAXT); n.getParam("/frenet_planner/path/mint", MINT); n.getParam("/frenet_planner/path/target_speed", TARGET_SPEED); n.getParam("/frenet_planner/path/d_t_s", D_T_S); n.getParam("/frenet_planner/path/n_s_sample", N_S_SAMPLE); n.getParam("/frenet_planner/path/robot_radius", ROBOT_RADIUS); n.getParam("/frenet_planner/path/max_lat_vel", MAX_LAT_VEL); n.getParam("/frenet_planner/path/min_lat_vel", MIN_LAT_VEL); n.getParam("/frenet_planner/path/d_d_ns", D_D_NS); n.getParam("/frenet_planner/path/max_shift_d", MAX_SHIFT_D); n.getParam("/frenet_planner/cost/kj", KJ); n.getParam("/frenet_planner/cost/kt", KT); n.getParam("/frenet_planner/cost/kd", KD); n.getParam("/frenet_planner/cost/kd_v", KD_V); n.getParam("/frenet_planner/cost/klon", KLON); n.getParam("/frenet_planner/cost/klat", KLAT); vecD rx, ry, ryaw, rk; double ds = 0.1; //ds represents the step size for cubic_spline double bot_yaw; while(!got_path) { cout<<"No message received in path_id. Waiting for connection."<<endl<<flush; this_thread::sleep_for(chrono::seconds(1)); ros::spinOnce(); } //Global path is made using the waypoints cout<<"Path_id : "<<path_id.data<<endl; string id_path = path_id.data; n.getParam("/frenet_planner/waypoints/W_X_" + id_path, W_X); n.getParam("/frenet_planner/waypoints/W_Y_" + id_path, W_Y); cout<<"Got new waypoints."<<endl; Spline2D csp = calc_spline_course(W_X, W_Y, rx, ry, ryaw, rk, ds); cout<<"Updated global path."<<endl; got_path = false; FrenetPath path; FrenetPath lp; double s0, c_d, c_d_d, c_d_dd, c_speed ; int ctr=0; while(ros::ok()) { if(got_path) { while(path_id.data == "") { cout<<"No message received in path_id. Waiting for connection."<<endl<<flush; this_thread::sleep_for(chrono::seconds(1)); ros::spinOnce(); } cout<<"Path_id : "<<path_id.data<<endl; string id_path = path_id.data; n.getParam("/frenet_planner/waypoints/W_X_" + id_path, W_X); n.getParam("/frenet_planner/waypoints/W_Y_" + id_path, W_Y); cout<<"Got new waypoints."<<endl; csp = calc_spline_course(W_X, W_Y, rx, ry, ryaw, rk, ds); cout<<"Updated global path."<<endl; got_path = false; } //Specifing initial conditions for the frenet planner using odometry if(ctr%10 == 0 or path.get_c().size() == 0) { cout << "initial NEW STARTS"<< endl; initial_conditions_new(csp, rx, ry, ryaw, s0, c_speed, c_d, c_d_d, c_d_dd, bot_yaw); } else { cout << "initial PATH STARTS"<< endl; initial_conditions_path(csp, rx, ry, ryaw, s0, c_speed, c_d, c_d_d, c_d_dd, bot_yaw, path); } while(no_action) { cout<<"Action message not received."<<endl<<flush; this_thread::sleep_for(chrono::seconds(1)); ros::spinOnce(); } cout<<"Before calling frenet_optimal_planning: Action : \n"<<twist.linear.x<<"\n"<<twist.linear.y<<"\n"<<twist.linear.z<<"\n"<<twist.angular.x<<endl; path = frenet_optimal_planning(csp, s0, c_speed, c_d, c_d_d, c_d_dd, lp, bot_yaw); cout<<"After calling frenet_optimal_planning"<<endl; lp = path; nav_msgs::Path path_msg; nav_msgs::Path global_path_msg; // paths are published in map frame path_msg.header.frame_id = "map"; global_path_msg.header.frame_id = "map"; //Global path pushed into the message for(int i = 0; i < rx.size(); i++) { geometry_msgs::PoseStamped loc; loc.pose.position.x = rx[i]; loc.pose.position.y = ry[i]; global_path_msg.poses.push_back(loc); } if(false) { plt::ion(); plt::show(); plt::plot(lp.get_x(), lp.get_y()); plt::pause(0.001); plt::plot(rx,ry); plt::pause(0.001); } //Required tranformations on the Frenet path are made and pushed into message publishPath(path_msg, path, rk, ryaw, c_d, c_speed, c_d_d); //Next velocity along the path double bot_v = sqrt(pow(1 - rk[1]*c_d, 2)*pow(c_speed, 2) + pow(c_d_d, 2)); geometry_msgs::Twist vel; vel.linear.x = bot_v; vel.linear.y = 0; vel.linear.z = 0; std_msgs::Float64 cost; cost.data = path.get_cf(); cost_fp.publish(cost); frenet_path.publish(path_msg); //global_path.publish(global_path_msg); target_vel.publish(vel); printf("VEL. PUBLISHED = %lf \n", vel.linear.x); ctr++; ros::spinOnce(); } }
26.811224
190
0.677545
anime-sh
fd36ce26d4be3904e2ad166a033ca00fa1f33f78
2,812
hpp
C++
waterbox/ares64/ares/nall/emulation/21fx.hpp
Fortranm/BizHawk
8cb0ffb6f8964cc339bbe1784838918fb0aa7e27
[ "MIT" ]
153
2020-07-25T17:55:29.000Z
2021-10-01T23:45:01.000Z
waterbox/ares64/ares/nall/emulation/21fx.hpp
Fortranm/BizHawk
8cb0ffb6f8964cc339bbe1784838918fb0aa7e27
[ "MIT" ]
296
2021-10-16T18:00:18.000Z
2022-03-31T12:09:00.000Z
waterbox/ares64/ares/nall/emulation/21fx.hpp
Fortranm/BizHawk
8cb0ffb6f8964cc339bbe1784838918fb0aa7e27
[ "MIT" ]
44
2020-07-25T08:51:55.000Z
2021-09-25T16:09:01.000Z
#pragma once #include <nall/nall.hpp> #include <nall/serial.hpp> using namespace nall; struct FX { auto open(Arguments& arguments) -> bool; auto close() -> void; auto readable() -> bool; auto read() -> u8; auto writable() -> bool; auto write(u8 data) -> void; auto read(u32 offset, u32 length) -> vector<u8>; auto write(u32 offset, const void* buffer, u32 length) -> void; auto write(u32 offset, const vector<u8>& buffer) -> void { write(offset, buffer.data(), buffer.size()); } auto execute(u32 offset) -> void; auto read(u32 offset) -> u8; auto write(u32 offset, u8 data) -> void; serial device; }; inline auto FX::open(Arguments& arguments) -> bool { //device name override support string name; arguments.take("--device", name); if(!device.open(name)) { print("[21fx] error: unable to open hardware device\n"); return false; } //flush the device (to clear floating inputs) while(true) { while(readable()) read(); auto iplrom = read(0x2184, 122); auto sha256 = Hash::SHA256(iplrom).digest(); if(sha256 == "41b79712a4a2d16d39894ae1b38cde5c41dad22eadc560df631d39f13df1e4b9") break; } return true; } inline auto FX::close() -> void { device.close(); } inline auto FX::readable() -> bool { return device.readable(); } //1000ns delay avoids burning CPU core at 100%; does not slow down max transfer rate at all inline auto FX::read() -> u8 { while(!readable()) usleep(1000); u8 buffer[1] = {0}; device.read(buffer, 1); return buffer[0]; } inline auto FX::writable() -> bool { return device.writable(); } inline auto FX::write(u8 data) -> void { while(!writable()) usleep(1000); u8 buffer[1] = {data}; device.write(buffer, 1); } // inline auto FX::read(u32 offset, u32 length) -> vector<u8> { write(0x21); write(0x66); write(0x78); write(offset >> 16); write(offset >> 8); write(offset >> 0); write(0x01); write(length >> 8); write(length >> 0); write(0x00); vector<u8> buffer; while(length--) buffer.append(read()); return buffer; } inline auto FX::write(u32 offset, const void* data, u32 length) -> void { write(0x21); write(0x66); write(0x78); write(offset >> 16); write(offset >> 8); write(offset >> 0); write(0x01); write(length >> 8); write(length >> 0); write(0x01); auto buffer = (u8*)data; for(auto n : range(length)) write(buffer[n]); write(0x00); } inline auto FX::execute(u32 offset) -> void { write(0x21); write(0x66); write(0x78); write(offset >> 16); write(offset >> 8); write(offset >> 0); write(0x00); } // inline auto FX::read(u32 offset) -> u8 { auto buffer = read(offset, 1); return buffer[0]; } inline auto FX::write(u32 offset, u8 data) -> void { vector<u8> buffer = {data}; write(offset, buffer); }
21.79845
107
0.63478
Fortranm
fd370b1916e9f70f78daaa6e4b16f876ff71acab
836
cpp
C++
console/src/boost_1_78_0/libs/hana/test/issues/github_460.cpp
vany152/FilesHash
39f282807b7f1abc56dac389e8259ee3bb557a8d
[ "MIT" ]
1,260
2015-10-19T20:49:55.000Z
2022-03-30T03:17:05.000Z
console/src/boost_1_78_0/libs/hana/test/issues/github_460.cpp
vany152/FilesHash
39f282807b7f1abc56dac389e8259ee3bb557a8d
[ "MIT" ]
310
2015-10-20T12:42:04.000Z
2022-03-31T17:19:53.000Z
Libs/boost_1_76_0/libs/hana/test/issues/github_460.cpp
Antd23rus/S2DE
47cc7151c2934cd8f0399a9856c1e54894571553
[ "MIT" ]
218
2015-11-02T06:46:17.000Z
2022-02-07T05:25:54.000Z
// Copyright Jason Rice 2020 // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) #include <boost/hana/define_struct.hpp> #include <boost/hana/equal.hpp> #include <boost/hana/members.hpp> #include <boost/hana/not_equal.hpp> namespace hana = boost::hana; struct SomeStruct { BOOST_HANA_DEFINE_STRUCT(SomeStruct, (int, x)); constexpr bool operator==(SomeStruct const& other) { return hana::equal(hana::members(*this), hana::members(other)); } constexpr bool operator!=(SomeStruct const& other) { return hana::not_equal(hana::members(*this), hana::members(other)); } }; int main() { static_assert(SomeStruct{5} == SomeStruct{5}, ""); static_assert(hana::equal(SomeStruct{5}, SomeStruct{5}), ""); }
29.857143
81
0.696172
vany152
fd3a945300df5ca2ac17b3e959d996cfd02d0c10
1,403
cpp
C++
LivestreamEx/SubProcessorDanmuDouyu.cpp
cnSchwarzer/LivestreamExtract
14aabf3c5bb728941c62e3871b9aa1f55d0390a5
[ "MIT" ]
8
2021-04-01T00:36:34.000Z
2021-06-13T15:58:17.000Z
LivestreamEx/SubProcessorDanmuDouyu.cpp
cnSchwarzer/LivestreamExtract
14aabf3c5bb728941c62e3871b9aa1f55d0390a5
[ "MIT" ]
null
null
null
LivestreamEx/SubProcessorDanmuDouyu.cpp
cnSchwarzer/LivestreamExtract
14aabf3c5bb728941c62e3871b9aa1f55d0390a5
[ "MIT" ]
2
2021-04-16T04:00:34.000Z
2021-08-30T03:06:47.000Z
#include "SubProcessorDanmuDouyu.h" #include <filesystem> #include <fstream> #include "../common.h" void SubProcessorDanmuDouyu::initialize(LivestreamDanmuDouyu* dm) { dm->onChatMessage([=](ChatMessage* msg) { danmu(reinterpret_cast<ChatMessageDouyu*>(msg)); }); } void SubProcessorDanmuDouyu::danmu(ChatMessageDouyu* msg) { if (!working) return; json::object_t m = json::object_t(); m["username"] = msg->username; m["content"] = msg->content; m["color"] = static_cast<int>(msg->color); m["level"] = msg->level; m["timestamp"] = msg->time; danmuJson.push_back(m); danmuCount++; //Backup every 50 danmu if (danmuCount % 50 == 0) { std::ofstream danmu(danmuFilePath); danmu << danmuJson.dump(4, ' ', false, nlohmann::detail::error_handler_t::ignore); danmu.close(); } } void SubProcessorDanmuDouyu::onSerialize(json& root) { root["danmu_file"] = std::filesystem::absolute(danmuFilePath).string(); } void SubProcessorDanmuDouyu::start(time_t timestamp) { danmuFilePath = outputFolder + "/output_danmu/" + std::to_string(timestamp) + ".json"; std::filesystem::create_directories(outputFolder + "/output_danmu"); working = true; } void SubProcessorDanmuDouyu::stop() { std::ofstream danmu(danmuFilePath); danmu << danmuJson.dump(4, ' ', false, nlohmann::detail::error_handler_t::ignore); danmu.close(); danmuCount = 0; danmuJson.clear(); working = false; }
23
87
0.703493
cnSchwarzer
fd3c63cfa74d73ef827df6b19f1dae409a9b6502
15,480
cpp
C++
uwsim_resources/uwsim_osgworks/src/osgwTools/TangentSpaceGeneratorDouble.cpp
epsilonorion/usv_lsa_sim_copy
d189f172dc1d265b7688c7dc8375a65ac4a9c048
[ "Apache-2.0" ]
1
2020-11-30T09:55:33.000Z
2020-11-30T09:55:33.000Z
uwsim_resources/uwsim_osgworks/src/osgwTools/TangentSpaceGeneratorDouble.cpp
epsilonorion/usv_lsa_sim_copy
d189f172dc1d265b7688c7dc8375a65ac4a9c048
[ "Apache-2.0" ]
null
null
null
uwsim_resources/uwsim_osgworks/src/osgwTools/TangentSpaceGeneratorDouble.cpp
epsilonorion/usv_lsa_sim_copy
d189f172dc1d265b7688c7dc8375a65ac4a9c048
[ "Apache-2.0" ]
2
2020-11-21T19:50:54.000Z
2020-12-27T09:35:29.000Z
/*************** <auto-copyright.pl BEGIN do not edit this line> ************** * * osgWorks is (C) Copyright 2009-2012 by Kenneth Mark Bryden * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1 as published by the Free Software Foundation. * * This library 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 * Library General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * *************** <auto-copyright.pl END do not edit this line> ***************/ // This code was taken from OSG v2.8.5 and modified to use double precision. #include <osgwTools/TangentSpaceGeneratorDouble.h> #include <osgwTools/Version.h> #include <osg/Notify> #include <osg/io_utils> namespace osgwTools { TangentSpaceGeneratorDouble::TangentSpaceGeneratorDouble() : osg::Referenced(), T_(new osg::Vec4Array), B_(new osg::Vec4Array), N_(new osg::Vec4Array) { } TangentSpaceGeneratorDouble::TangentSpaceGeneratorDouble(const TangentSpaceGeneratorDouble &copy, const osg::CopyOp &copyop) : osg::Referenced(copy), T_(static_cast<osg::Vec4Array *>(copyop(copy.T_.get()))), B_(static_cast<osg::Vec4Array *>(copyop(copy.B_.get()))), N_(static_cast<osg::Vec4Array *>(copyop(copy.N_.get()))) { } void TangentSpaceGeneratorDouble::generate(osg::Geometry *geo, int normal_map_tex_unit) { #if( OSGWORKS_OSG_VERSION < 30108 ) // check to see if vertex attributes indices exists, if so expand them to remove them // This was removed from OSG 3.1.8 upwards if (geo->suitableForOptimization()) { // removing coord indices so we don't have to deal with them in the binormal code. osg::notify(osg::INFO)<<"TangentSpaceGeneratorDouble::generate(Geometry*,int): Removing attribute indices"<<std::endl; geo->copyToAndOptimize(*geo); } #endif const osg::Array *vx = geo->getVertexArray(); const osg::Array *nx = geo->getNormalArray(); const osg::Array *tx = geo->getTexCoordArray(normal_map_tex_unit); if (!vx || !tx) return; unsigned int vertex_count = vx->getNumElements(); if (geo->getVertexIndices() == NULL) { T_->assign(vertex_count, osg::Vec4()); B_->assign(vertex_count, osg::Vec4()); N_->assign(vertex_count, osg::Vec4()); } else { unsigned int index_count = geo->getVertexIndices()->getNumElements(); T_->assign(index_count, osg::Vec4()); B_->assign(index_count, osg::Vec4()); N_->assign(index_count, osg::Vec4()); indices_ = new osg::UIntArray(); unsigned int i; for (i=0;i<index_count;i++) { indices_->push_back(i); } } unsigned int i; // VC6 doesn't like for-scoped variables for (unsigned int pri=0; pri<geo->getNumPrimitiveSets(); ++pri) { osg::PrimitiveSet *pset = geo->getPrimitiveSet(pri); unsigned int N = pset->getNumIndices(); switch (pset->getMode()) { case osg::PrimitiveSet::TRIANGLES: for (i=0; i<N; i+=3) { compute(pset, vx, nx, tx, i, i+1, i+2); } break; case osg::PrimitiveSet::QUADS: for (i=0; i<N; i+=4) { compute(pset, vx, nx, tx, i, i+1, i+2); compute(pset, vx, nx, tx, i+2, i+3, i); } break; case osg::PrimitiveSet::TRIANGLE_STRIP: if (pset->getType() == osg::PrimitiveSet::DrawArrayLengthsPrimitiveType) { osg::DrawArrayLengths *dal = static_cast<osg::DrawArrayLengths *>(pset); unsigned int j = 0; for (osg::DrawArrayLengths::const_iterator pi=dal->begin(); pi!=dal->end(); ++pi) { unsigned int iN = static_cast<unsigned int>(*pi-2); for (i=0; i<iN; ++i, ++j) { if ((i%2) == 0) { compute(pset, vx, nx, tx, j, j+1, j+2); } else { compute(pset, vx, nx, tx, j+1, j, j+2); } } j += 2; } } else { for (i=0; i<N-2; ++i) { if ((i%2) == 0) { compute(pset, vx, nx, tx, i, i+1, i+2); } else { compute(pset, vx, nx, tx, i+1, i, i+2); } } } break; case osg::PrimitiveSet::TRIANGLE_FAN: if (pset->getType() == osg::PrimitiveSet::DrawArrayLengthsPrimitiveType) { osg::DrawArrayLengths *dal = static_cast<osg::DrawArrayLengths *>(pset); unsigned int j = 0; for (osg::DrawArrayLengths::const_iterator pi=dal->begin(); pi!=dal->end(); ++pi) { unsigned int iN = static_cast<unsigned int>(*pi-2); for (i=0; i<iN; ++i) { compute(pset, vx, nx, tx, 0, j+1, j+2); } j += 2; } } else { for (i=0; i<N-2; ++i) { compute(pset, vx, nx, tx, 0, i+1, i+2); } } break; case osg::PrimitiveSet::POINTS: case osg::PrimitiveSet::LINES: case osg::PrimitiveSet::LINE_STRIP: case osg::PrimitiveSet::LINE_LOOP: break; default: osg::notify(osg::WARN) << "Warning: TangentSpaceGeneratorDouble: unknown primitive mode " << pset->getMode() << "\n"; } } // normalize basis vectors and force the normal vector to match // the triangle normal's direction unsigned int attrib_count = vx->getNumElements(); if (geo->getVertexIndices() != NULL) { attrib_count = geo->getVertexIndices()->getNumElements(); } for (i=0; i<attrib_count; ++i) { osg::Vec4 &vT = (*T_)[i]; osg::Vec4 &vB = (*B_)[i]; osg::Vec4 &vN = (*N_)[i]; osg::Vec3d txN = osg::Vec3d(vT.x(), vT.y(), vT.z()) ^ osg::Vec3d(vB.x(), vB.y(), vB.z()); if (txN * osg::Vec3d(vN.x(), vN.y(), vN.z()) >= 0) { vN = osg::Vec4(txN, 0); } else { vN = osg::Vec4(-txN, 0); } vT.normalize(); vB.normalize(); vN.normalize(); } /* TO-DO: if indexed, compress the attributes to have only one * version of each (different indices for each one?) */ } void TangentSpaceGeneratorDouble::compute(osg::PrimitiveSet *pset, const osg::Array* vx, const osg::Array* nx, const osg::Array* tx, int iA, int iB, int iC) { iA = pset->index(iA); iB = pset->index(iB); iC = pset->index(iC); osg::Vec3d P1; osg::Vec3d P2; osg::Vec3d P3; int i; // VC6 doesn't like for-scoped variables switch (vx->getType()) { case osg::Array::Vec2ArrayType: for (i=0; i<2; ++i) { P1.ptr()[i] = static_cast<const osg::Vec2Array&>(*vx)[iA].ptr()[i]; P2.ptr()[i] = static_cast<const osg::Vec2Array&>(*vx)[iB].ptr()[i]; P3.ptr()[i] = static_cast<const osg::Vec2Array&>(*vx)[iC].ptr()[i]; } break; case osg::Array::Vec3ArrayType: P1 = static_cast<const osg::Vec3Array&>(*vx)[iA]; P2 = static_cast<const osg::Vec3Array&>(*vx)[iB]; P3 = static_cast<const osg::Vec3Array&>(*vx)[iC]; break; case osg::Array::Vec4ArrayType: for (i=0; i<3; ++i) { P1.ptr()[i] = static_cast<const osg::Vec4Array&>(*vx)[iA].ptr()[i]; P2.ptr()[i] = static_cast<const osg::Vec4Array&>(*vx)[iB].ptr()[i]; P3.ptr()[i] = static_cast<const osg::Vec4Array&>(*vx)[iC].ptr()[i]; } break; default: osg::notify(osg::WARN) << "Warning: TangentSpaceGeneratorDouble: vertex array must be Vec2Array, Vec3Array or Vec4Array" << std::endl; } osg::Vec3d N1; osg::Vec3d N2; osg::Vec3d N3; if(nx) { switch (nx->getType()) { case osg::Array::Vec2ArrayType: for (i=0; i<2; ++i) { N1.ptr()[i] = static_cast<const osg::Vec2Array&>(*nx)[iA].ptr()[i]; N2.ptr()[i] = static_cast<const osg::Vec2Array&>(*nx)[iB].ptr()[i]; N3.ptr()[i] = static_cast<const osg::Vec2Array&>(*nx)[iC].ptr()[i]; } break; case osg::Array::Vec3ArrayType: N1 = static_cast<const osg::Vec3Array&>(*nx)[iA]; N2 = static_cast<const osg::Vec3Array&>(*nx)[iB]; N3 = static_cast<const osg::Vec3Array&>(*nx)[iC]; break; case osg::Array::Vec4ArrayType: for (i=0; i<3; ++i) { N1.ptr()[i] = static_cast<const osg::Vec4Array&>(*nx)[iA].ptr()[i]; N2.ptr()[i] = static_cast<const osg::Vec4Array&>(*nx)[iB].ptr()[i]; N3.ptr()[i] = static_cast<const osg::Vec4Array&>(*nx)[iC].ptr()[i]; } break; default: osg::notify(osg::WARN) << "Warning: TangentSpaceGeneratorDouble: normal array must be Vec2Array, Vec3Array or Vec4Array" << std::endl; } } osg::Vec2d uv1; osg::Vec2d uv2; osg::Vec2d uv3; switch (tx->getType()) { case osg::Array::Vec2ArrayType: uv1 = static_cast<const osg::Vec2Array&>(*tx)[iA]; uv2 = static_cast<const osg::Vec2Array&>(*tx)[iB]; uv3 = static_cast<const osg::Vec2Array&>(*tx)[iC]; break; case osg::Array::Vec3ArrayType: for (i=0; i<2; ++i) { uv1.ptr()[i] = static_cast<const osg::Vec3Array&>(*tx)[iA].ptr()[i]; uv2.ptr()[i] = static_cast<const osg::Vec3Array&>(*tx)[iB].ptr()[i]; uv3.ptr()[i] = static_cast<const osg::Vec3Array&>(*tx)[iC].ptr()[i]; } break; case osg::Array::Vec4ArrayType: for (i=0; i<2; ++i) { uv1.ptr()[i] = static_cast<const osg::Vec4Array&>(*tx)[iA].ptr()[i]; uv2.ptr()[i] = static_cast<const osg::Vec4Array&>(*tx)[iB].ptr()[i]; uv3.ptr()[i] = static_cast<const osg::Vec4Array&>(*tx)[iC].ptr()[i]; } break; default: osg::notify(osg::WARN) << "Warning: TangentSpaceGeneratorDouble: texture coord array must be Vec2Array, Vec3Array or Vec4Array" << std::endl; } if(nx){ osg::Vec3d V, T1, T2, T3, B1, B2, B3; V = osg::Vec3d(P2.x() - P1.x(), uv2.x() - uv1.x(), uv2.y() - uv1.y()) ^ osg::Vec3d(P3.x() - P1.x(), uv3.x() - uv1.x(), uv3.y() - uv1.y()); if (V.x() != 0) { V.normalize(); T1.x() += -V.y() / V.x(); B1.x() += -V.z() / V.x(); T2.x() += -V.y() / V.x(); B2.x() += -V.z() / V.x(); T3.x() += -V.y() / V.x(); B3.x() += -V.z() / V.x(); } V = osg::Vec3d(P2.y() - P1.y(), uv2.x() - uv1.x(), uv2.y() - uv1.y()) ^ osg::Vec3d(P3.y() - P1.y(), uv3.x() - uv1.x(), uv3.y() - uv1.y()); if (V.x() != 0) { V.normalize(); T1.y() += -V.y() / V.x(); B1.y() += -V.z() / V.x(); T2.y() += -V.y() / V.x(); B2.y() += -V.z() / V.x(); T3.y() += -V.y() / V.x(); B3.y() += -V.z() / V.x(); } V = osg::Vec3d(P2.z() - P1.z(), uv2.x() - uv1.x(), uv2.y() - uv1.y()) ^ osg::Vec3d(P3.z() - P1.z(), uv3.x() - uv1.x(), uv3.y() - uv1.y()); if (V.x() != 0) { V.normalize(); T1.z() += -V.y() / V.x(); B1.z() += -V.z() / V.x(); T2.z() += -V.y() / V.x(); B2.z() += -V.z() / V.x(); T3.z() += -V.y() / V.x(); B3.z() += -V.z() / V.x(); } if( (T1.length() == 0) && (B1.length() == 0) && (T2.length() == 0) && (B2.length() == 0) && (T3.length() == 0) && (B3.length() == 0) ) { osg::notify( osg::WARN ) << "Bad tangent space." << std::endl; osg::notify( osg::WARN ) << " iA " << iA << " uv1 " << uv1 << std::endl; osg::notify( osg::WARN ) << " iB " << iB << " uv2 " << uv2 << std::endl; osg::notify( osg::WARN ) << " iC " << iC << " uv3 " << uv3 << std::endl; } osg::Vec3d tempvec; tempvec = N1 ^ T1; (*T_)[iA] = osg::Vec4(tempvec ^ N1, 0); tempvec = B1 ^ N1; (*B_)[iA] = osg::Vec4(N1 ^ tempvec, 0); tempvec = N2 ^ T2; (*T_)[iB] = osg::Vec4(tempvec ^ N2, 0); tempvec = B2 ^ N2; (*B_)[iB] = osg::Vec4(N2 ^ tempvec, 0); tempvec = N3 ^ T3; (*T_)[iC] = osg::Vec4(tempvec ^ N3, 0); tempvec = B3 ^ N3; (*B_)[iC] = osg::Vec4(N3 ^ tempvec, 0); (*N_)[iA] += osg::Vec4(N1, 0); (*N_)[iB] += osg::Vec4(N2, 0); (*N_)[iC] += osg::Vec4(N3, 0); } else{ osg::Vec3d face_normal = (P2 - P1) ^ (P3 - P1); osg::Vec3d V; V = osg::Vec3d(P2.x() - P1.x(), uv2.x() - uv1.x(), uv2.y() - uv1.y()) ^ osg::Vec3d(P3.x() - P1.x(), uv3.x() - uv1.x(), uv3.y() - uv1.y()); if (V.x() != 0) { V.normalize(); (*T_)[iA].x() += -V.y() / V.x(); (*B_)[iA].x() += -V.z() / V.x(); (*T_)[iB].x() += -V.y() / V.x(); (*B_)[iB].x() += -V.z() / V.x(); (*T_)[iC].x() += -V.y() / V.x(); (*B_)[iC].x() += -V.z() / V.x(); } V = osg::Vec3d(P2.y() - P1.y(), uv2.x() - uv1.x(), uv2.y() - uv1.y()) ^ osg::Vec3d(P3.y() - P1.y(), uv3.x() - uv1.x(), uv3.y() - uv1.y()); if (V.x() != 0) { V.normalize(); (*T_)[iA].y() += -V.y() / V.x(); (*B_)[iA].y() += -V.z() / V.x(); (*T_)[iB].y() += -V.y() / V.x(); (*B_)[iB].y() += -V.z() / V.x(); (*T_)[iC].y() += -V.y() / V.x(); (*B_)[iC].y() += -V.z() / V.x(); } V = osg::Vec3d(P2.z() - P1.z(), uv2.x() - uv1.x(), uv2.y() - uv1.y()) ^ osg::Vec3d(P3.z() - P1.z(), uv3.x() - uv1.x(), uv3.y() - uv1.y()); if (V.x() != 0) { V.normalize(); (*T_)[iA].z() += -V.y() / V.x(); (*B_)[iA].z() += -V.z() / V.x(); (*T_)[iB].z() += -V.y() / V.x(); (*B_)[iB].z() += -V.z() / V.x(); (*T_)[iC].z() += -V.y() / V.x(); (*B_)[iC].z() += -V.z() / V.x(); } (*N_)[iA] += osg::Vec4(face_normal, 0); (*N_)[iB] += osg::Vec4(face_normal, 0); (*N_)[iC] += osg::Vec4(face_normal, 0); } } // osgwTools }
37.033493
149
0.461693
epsilonorion
fd3d0a66668762df21be8791e950c82c515166d9
2,120
hpp
C++
Engine/Source/Core/Testing.hpp
AhsanSarwar45/Qombat-OLD
0247441cf4927733ef0786c6df9a087461b0260b
[ "Apache-2.0" ]
null
null
null
Engine/Source/Core/Testing.hpp
AhsanSarwar45/Qombat-OLD
0247441cf4927733ef0786c6df9a087461b0260b
[ "Apache-2.0" ]
null
null
null
Engine/Source/Core/Testing.hpp
AhsanSarwar45/Qombat-OLD
0247441cf4927733ef0786c6df9a087461b0260b
[ "Apache-2.0" ]
null
null
null
// #pragma once // #include "Core/Core.hpp" // #include "Core/Configuration/ConfigManager.hpp" // #include "Core/Memory/PoolAllocator.hpp" // #include "Core/Memory/StackAllocator.hpp" // #include "Utility/Hashing.hpp" // #include <Core/Configuration/Configuration.hpp> // namespace QMBT // { // class MemoryLogger // { // public: // static void Init() // { // CONFIG_GROUP("TestGroup", // CONFIG_INT(s_VerbosityLevel, "Verbosity Level", "Sets the Verbosity Level", 0, 3)) // } // //inline static std::shared_ptr<spdlog::logger>& Get() { return s_Logger; } // //inline static std::shared_ptr<spdlog::logger> s_Logger; // inline static int s_VerbosityLevel = 5; // inline static int s_Pattern = 3; // }; // struct TestingPools // { // char a = 'g'; // double b = 5; // int c; // }; // void TestHash() // { // StringHash hash = StringHash("Arhedzejtgfxryeuhtrjytdkytkytjtfxjtrfrdjtyk"); // StringHash hash1 = StringHash("Arhedzejtgfxryeuhtrjytdkytkytjtfxjtrfrdjtyj"); // StringHash hash2 = StringHash("Arhedzejtgfxryeuhtrjytdkytkytjtfxjtrfrdjtyk"); // LOG_CORE_INFO("test hash = {0}", hash); // LOG_CORE_INFO("test hash1 = {0}", hash1); // LOG_CORE_INFO("test hash2 = {0}", hash2); // } // void TestMemory() // { // // StackAllocator allocator = StackAllocator("Stack Allocator"); // // TestingPools* objects[10]; // // for (int i = 0; i < 8; ++i) // // { // // objects[i] = allocator.Allocate<TestingPools>(); // // objects[i]->a = 'a' + i; // // objects[i]->b = i; // // } // // for (int i = 0; i < 8; ++i) // // { // // LOG_CORE_INFO("Info {0}, {1}, {2}", objects[i]->a, objects[i]->b, objects[i]->c); // // } // // for (int i = 7; i >= 0; --i) // // { // // allocator.Deallocate<TestingPools>(objects[i]); // // } // } // void Test() // { // LOG_CORE_INFO("Initial Val: {0}", MemoryLogger::s_VerbosityLevel); // MemoryLogger::Init(); // ConfigManager::SetConfigInt("TestGroup", "Verbosity Level", 345); // LOG_CORE_INFO("Initial Val: {0}", MemoryLogger::s_VerbosityLevel); // } // } // namespace QMBT
27.179487
92
0.602358
AhsanSarwar45
fd402f55cf0e7f00c97c9edff1c1f848eed9ad4e
17,006
cpp
C++
test/test.cpp
erichschroeter/circular_buffer
b161e9043b8996ef00c38afe43a6cffe8dfaaffe
[ "MIT" ]
2
2015-03-17T09:53:42.000Z
2020-05-15T07:28:37.000Z
test/test.cpp
erichschroeter/circular_buffer
b161e9043b8996ef00c38afe43a6cffe8dfaaffe
[ "MIT" ]
null
null
null
test/test.cpp
erichschroeter/circular_buffer
b161e9043b8996ef00c38afe43a6cffe8dfaaffe
[ "MIT" ]
null
null
null
#define CATCH_CONFIG_MAIN #include "catch.hpp" #include <circular_buffer.h> #ifdef _WIN32 #define snprintf _snprintf_s #define sprintf sprintf_s #define strcat strcat_s #endif static int get_seed() { /* If user set CB_SEED env var, use it. Otherwise use default. */ char *env = getenv("CB_SEED"); if (env == NULL) { WARN("CB_SEED environment variable not set. Set via 'export CB_SEED=$RANDOM'."); return 1; } else { return atoi(env); } } static struct circular_buffer* random_buffer(int max) { struct circular_buffer *buffer; int bufferSize; srand(get_seed()); /* Random buffer size. */ bufferSize = rand() % max; buffer = cb_create(bufferSize); REQUIRE(buffer != 0); return buffer; } static struct circular_buffer* incrementing_buffer(int size) { int i; char data[size]; struct circular_buffer *buffer = cb_create(size); REQUIRE(buffer != 0); /* populate test data with incrementing numbers */ for (i = 0; i < sizeof(data); i++) data[i] = i; cb_write(buffer, data, sizeof(data)); return buffer; } TEST_CASE("Circular buffer full function", "[full][utility]") { struct circular_buffer *incrementing, *empty; incrementing = incrementing_buffer(10); empty = cb_create(20); REQUIRE(cb_full(incrementing) == 1); REQUIRE(cb_full(empty) == 0); } TEST_CASE("Circular buffer empty function", "[empty][utility]") { struct circular_buffer *incrementing, *empty; incrementing = incrementing_buffer(10); empty = cb_create(20); REQUIRE(cb_empty(incrementing) == 0); REQUIRE(cb_empty(empty) == 1); } TEST_CASE("Circular buffer starts at function", "[utility]") { const unsigned int SIZE = 10, READ_SIZE = 5; char buffer[SIZE]; struct circular_buffer *incrementing, *empty; incrementing = incrementing_buffer(SIZE); /* Verify the data starts at the beginning of a full buffer. */ REQUIRE(cb_starts_at(incrementing) == incrementing->buffer); cb_read(incrementing, buffer, READ_SIZE); /* Verify the data starts at the correct offset from the beginning of the buffer. */ REQUIRE(cb_starts_at(incrementing) == incrementing->buffer + READ_SIZE); empty = cb_create(20); /* Verify the data starts at the beginning of an empty buffer. */ REQUIRE(cb_starts_at(empty) == empty->buffer); cb_read(empty, buffer, READ_SIZE); /* Verify the data start position has not changed after reading an empty buffer. */ REQUIRE(cb_starts_at(empty) == empty->buffer); } TEST_CASE("Circular buffer ends at function", "[utility]") { char testdata[] = "test data"; const unsigned int SIZE = sizeof(testdata); char buffer[SIZE]; struct circular_buffer *full, *empty; full = incrementing_buffer(SIZE); /* Verify the data ends at the end of a full buffer. */ REQUIRE(cb_ends_at(full) == full->buffer + full->length); /* Make some room to write some more. */ cb_read(full, buffer, SIZE); /* Verify the data end position has not changed from reading. */ REQUIRE(cb_ends_at(full) == full->buffer + full->length); cb_write(full, testdata, SIZE); /* * Verify the data ends at the correct offset from the beginning of the buffer. * Since this was a full buffer we need to take into account the head wrapping. The * -1 exists because the actual size of the buffer is length + 1. */ REQUIRE(cb_ends_at(full) == (full->buffer + SIZE - 1)); /* Create an empty buffer big enough to fit the test data. */ empty = cb_create(SIZE + 1); /* Verify the data ends at the beginning of an empty buffer. */ REQUIRE(cb_starts_at(empty) == empty->buffer); cb_read(empty, buffer, SIZE); /* Verify the data end position has not changed after reading an empty buffer. */ REQUIRE(cb_starts_at(empty) == empty->buffer); cb_write(empty, testdata, SIZE); /* * Verify the data ends at the correct offset from the beginning of the buffer. * We don't have to take into account the -1 since we haven't wrapped this buffer. */ REQUIRE(cb_ends_at(empty) == empty->buffer + SIZE); } TEST_CASE("Circular buffer available data function", "[utility]") { const unsigned int SIZE = 10, READ_SIZE = 5; char buffer[SIZE]; struct circular_buffer *incrementing, *empty; incrementing = incrementing_buffer(SIZE); empty = cb_create(20); /* Verify a full buffer has the correct amount of data. */ REQUIRE(cb_available_data(incrementing) == SIZE); cb_read(incrementing, buffer, READ_SIZE); /* Verify the buffer has reduced the available data by the amount read. */ REQUIRE(cb_available_data(incrementing) == SIZE - READ_SIZE); /* Verify an empty buffer has no data available. */ REQUIRE(cb_available_data(empty) == 0); cb_read(empty, buffer, READ_SIZE); /* Verify that no data is still available. */ REQUIRE(cb_available_data(empty) == 0); } TEST_CASE("Circular buffer available space function", "[utility]") { const unsigned int SIZE = 10, READ_SIZE = 5, WRITE_SIZE = 5; char buffer[SIZE], data[SIZE]; struct circular_buffer *incrementing, *empty; int i; incrementing = incrementing_buffer(SIZE); empty = cb_create(SIZE); for (i = 0; i < sizeof(data); i++) data[i] = i; /* Verify there is no space available in a full buffer. */ REQUIRE(cb_available_space(incrementing) == 0); cb_read(incrementing, buffer, READ_SIZE); /* Verify the space available is the amount just read of a full buffer. */ REQUIRE(cb_available_space(incrementing) == READ_SIZE); /* Verify the space available is the size of an empty buffer. */ REQUIRE(cb_available_space(empty) == SIZE); cb_read(empty, buffer, READ_SIZE); /* Verify that reading doesn't affect the space available of an empty buffer. */ REQUIRE(cb_available_space(empty) == SIZE); cb_write(empty, data, WRITE_SIZE); /* Verify the space available is reduced by the amount written. */ REQUIRE(cb_available_space(empty) == SIZE - WRITE_SIZE); } TEST_CASE("Circular buffer clear function", "[utility]") { const unsigned int FULL_SIZE = 10, EMPTY_SIZE = 20; struct circular_buffer *full, *empty; full = incrementing_buffer(FULL_SIZE); empty = cb_create(EMPTY_SIZE); cb_clear(full); REQUIRE(cb_available_data(full) == 0); REQUIRE(cb_available_space(full) == FULL_SIZE); REQUIRE(cb_full(full) == 0); REQUIRE(cb_empty(full) == 1); cb_clear(empty); REQUIRE(cb_available_data(empty) == 0); REQUIRE(cb_available_space(empty) == EMPTY_SIZE); REQUIRE(cb_full(empty) == 0); REQUIRE(cb_empty(empty) == 1); } TEST_CASE("Circular buffer read single", "[read]") { const unsigned int SIZE = 10; char data; struct circular_buffer *incrementing; int i, ret; incrementing = incrementing_buffer(SIZE); REQUIRE(cb_available_data(incrementing) == incrementing->length); ret = cb_read_single(incrementing, &data); REQUIRE(ret == 1); REQUIRE(cb_available_space(incrementing) == 1); REQUIRE(data == 0); ret = cb_read_single(incrementing, &data); REQUIRE(data == 1); } TEST_CASE("Circular buffer read all", "[read]") { const unsigned int SIZE = 10; char buffer[SIZE]; struct circular_buffer *incrementing; int i, ret; incrementing = incrementing_buffer(SIZE); REQUIRE(cb_available_data(incrementing) == incrementing->length); ret = cb_read(incrementing, buffer, sizeof(buffer)); REQUIRE(ret == sizeof(buffer)); REQUIRE(cb_available_data(incrementing) == 0); for (i = 0; i < sizeof(buffer); i++) { if (buffer[i] != i) { FAIL("Data read from incrementing is incorrect."); break; } } } TEST_CASE("Circular buffer read none", "[read]") { const unsigned int SIZE = 10; char buffer[SIZE]; struct circular_buffer *incrementing, *empty; int ret; incrementing = incrementing_buffer(SIZE); empty = cb_create(20); REQUIRE(cb_available_data(incrementing) == incrementing->length); ret = cb_read(incrementing, buffer, 0); REQUIRE(ret == 0); REQUIRE(cb_available_data(incrementing) == incrementing->length); REQUIRE(cb_available_data(empty) == 0); ret = cb_read(empty, buffer, 0); REQUIRE(ret == 0); REQUIRE(cb_available_data(empty) == 0); } TEST_CASE("Circular buffer read too much", "[read]") { const unsigned int SIZE = 10; char buffer[SIZE + 1]; struct circular_buffer *incrementing, *empty; int ret; incrementing = incrementing_buffer(SIZE); empty = cb_create(20); /* * circular_buffer_read should only return up to the amount of available data. This * means it should return at most the amount specified, but could be less if the amount * specified was more than was available. */ REQUIRE(cb_available_data(incrementing) == incrementing->length); ret = cb_read(incrementing, buffer, sizeof(buffer)); REQUIRE(ret == SIZE); REQUIRE(cb_available_data(incrementing) == 0); REQUIRE(cb_available_data(empty) == 0); ret = cb_read(empty, buffer, 1); REQUIRE(ret == 0); REQUIRE(cb_available_data(empty) == 0); } TEST_CASE("Circular buffer write all", "[write]") { const unsigned int SIZE = 10; char data[SIZE]; struct circular_buffer *empty; int i, ret; empty = cb_create(SIZE); /* populate test data with incrementing numbers */ for (i = 0; i < sizeof(data); i++) data[i] = i; REQUIRE(cb_available_data(empty) == 0); ret = cb_write(empty, data, SIZE); REQUIRE(ret == SIZE); REQUIRE(cb_available_data(empty) == SIZE); for (i = 0; i < empty->length; i++) { if (empty->buffer[i] != i) { FAIL("Data written to empty buffer is incorrect."); break; } } } TEST_CASE("Circular buffer write none", "[write]") { const unsigned int SIZE = 10; struct circular_buffer *empty; int ret; char data[10]; empty = cb_create(SIZE); ret = cb_write(empty, data, 0); REQUIRE(ret == 0); REQUIRE(cb_available_data(empty) == 0); REQUIRE(cb_available_space(empty) == SIZE); } TEST_CASE("Circular buffer write too much", "[write]") { const unsigned int SIZE = 10; char data[SIZE + 1]; struct circular_buffer *empty; int i, ret; empty = cb_create(SIZE); /* populate test data with incrementing numbers */ for (i = 0; i < sizeof(data); i++) data[i] = i; REQUIRE(cb_available_data(empty) == 0); ret = cb_write(empty, data, sizeof(data)); REQUIRE(ret == -1); REQUIRE(cb_available_data(empty) == 0); for (i = 0; i < empty->length; i++) { if (empty->buffer[i] != 0) { FAIL("The buffer was modified when it shouldn't have been."); break; } } } TEST_CASE("Circular buffer head wraps", "[read][write]") { const unsigned int SIZE = 10, READ_SIZE = 5, WRITE_SIZE = 5; char data[SIZE]; struct circular_buffer *incrementing; int i, ret; incrementing = incrementing_buffer(SIZE); for (i = 0; i < sizeof(data); i++) data[i] = i; /* Attempt to write to a full buffer and expect nothing to change. */ REQUIRE(incrementing->head == incrementing->length); REQUIRE(incrementing->tail == 0); ret = cb_write(incrementing, data, WRITE_SIZE); REQUIRE(ret == -1); REQUIRE(incrementing->head == incrementing->length); REQUIRE(incrementing->tail == 0); /* Now read some. */ ret = cb_read(incrementing, data, READ_SIZE); REQUIRE(ret == READ_SIZE); REQUIRE(incrementing->head == incrementing->length); REQUIRE(incrementing->tail == READ_SIZE); /* Now write and verify head has wrapped. */ ret = cb_write(incrementing, data, WRITE_SIZE); REQUIRE(ret == WRITE_SIZE); /* head should be 1 less than WRITE_SIZE since the actual buffer is length + 1. */ REQUIRE(incrementing->head == WRITE_SIZE - 1); REQUIRE(incrementing->tail == READ_SIZE); } TEST_CASE("Circular buffer tail wraps", "[read][write]") { const unsigned int SIZE = 10, READ_SIZE = 4, WRITE_SIZE = 5; char data[SIZE]; struct circular_buffer *incrementing; int i, ret; incrementing = incrementing_buffer(SIZE); for (i = 0; i < sizeof(data); i++) data[i] = i; /* Attempt to write to a full buffer and expect nothing to change. */ REQUIRE(incrementing->head == incrementing->length); REQUIRE(incrementing->tail == 0); ret = cb_write(incrementing, data, WRITE_SIZE); REQUIRE(ret == -1); REQUIRE(incrementing->head == incrementing->length); REQUIRE(incrementing->tail == 0); /* Now read all data. */ ret = cb_read(incrementing, data, incrementing->length); REQUIRE(ret == incrementing->length); REQUIRE(incrementing->head == incrementing->length); REQUIRE(incrementing->tail == incrementing->length); /* Now fill the buffer up again. */ ret = cb_write(incrementing, data, WRITE_SIZE); REQUIRE(ret == WRITE_SIZE); /* head should be 1 less than WRITE_SIZE since the actual buffer is length + 1. */ REQUIRE(incrementing->head == WRITE_SIZE - 1); REQUIRE(incrementing->tail == incrementing->length); /* Now read and verify tail has wrapped. */ ret = cb_read(incrementing, data, READ_SIZE); REQUIRE(ret == READ_SIZE); REQUIRE(incrementing->head == WRITE_SIZE - 1); REQUIRE(incrementing->tail == READ_SIZE - 1); } TEST_CASE("Circular buffer validate data", "[read][write]") { char data[] = "this is a test", validate[sizeof(data)]; struct circular_buffer *buffer; int i, ret; buffer = cb_create(sizeof(data)); /* Write the test data to the buffer and validate it is actually loaded. */ ret = cb_write(buffer, data, sizeof(data)); REQUIRE(ret == sizeof(data)); for (i = 0; i < sizeof(data); i++) { if (buffer->buffer[i] != data[i]) { FAIL("Data written to buffer is not valid."); break; } } /* Read the test data and validate that it was actually copied. */ ret = cb_read(buffer, validate, sizeof(validate)); REQUIRE(ret == sizeof(validate)); for (i = 0; i < sizeof(validate); i++) { if (validate[i] != data[i]) { FAIL("Data read from buffer is not valid."); break; } } } TEST_CASE("Circular buffer wrapping boundary", "[read][write]") { char data[] = {1,2,3,4}, data2[] = {5,6}, validate[sizeof(data)]; struct circular_buffer *buffer; int i, ret; buffer = cb_create(sizeof(data)); /* Write the test data to the buffer and validate it is actually loaded. */ ret = cb_write(buffer, data, sizeof(data)); REQUIRE(ret == sizeof(data)); for (i = 0; i < sizeof(data); i++) { if (buffer->buffer[i] != data[i]) { FAIL("Data written to buffer is not valid."); break; } } /* * At this point the buffer is full. Now we need to create the condition * where tail is located at the very last position before wrapping and * then read the buffer. */ ret = cb_read(buffer, validate, 4); REQUIRE(ret == 4); ret = cb_write(buffer, data2, 2); REQUIRE(ret == 2); /* Verify that a read that wraps has valid data. */ ret = cb_read(buffer, validate, 2); REQUIRE(ret == 2); for (i = 0; i < 2; i++) { if (validate[i] != data2[i]) { FAIL("Data read from buffer is not valid."); break; } } } static volatile int _running = 0; static void* cb_write_thread(void *circular_buffer) { int i = 0, ret; struct circular_buffer *buffer = (struct circular_buffer*) circular_buffer; char data[4]; while (_running) { data[0] = (i >> 24) & 0xff; data[1] = (i >> 16) & 0xff; data[2] = (i >> 8) & 0xff; data[3] = i & 0xff; retry: ret = cb_write(buffer, data, 4); /* * In case we stop the thread from outside, we don't want to get * stuck in an infinite loop. So, check that we are still running. */ if (ret < 0 && _running) { usleep(10); goto retry; } i++; } return 0; } TEST_CASE("Circular buffer multithreading", "[read][write][multithread]") { int i, ret, value; struct circular_buffer *buffer; pthread_t thread; const unsigned int VERIFY_NUM = 100000; char data[4]; buffer = cb_create(12); REQUIRE(buffer != 0); _running = 1; ret = pthread_create(&thread, NULL, &cb_write_thread, buffer); REQUIRE(ret == 0); /* * We are testing that each value we read from the buffer is incremented * by one. This will verify that there is no jumping around or overwriting * in the buffer when reading/writing in multithreaded environment. */ for (i = 0; i < VERIFY_NUM; i++) { retry: ret = cb_read(buffer, data, 4); /* In case the write thread hasn't kept up keep trying to read. */ if (ret < 1) { goto retry; } value = ((data[0] << 24) & 0xff000000) | ((data[1] << 16) & 0xff0000) | ((data[2] << 8) & 0xff00) | (data[3] & 0xff); if (value != i) { _running = 0; FAIL("Multithreaded data is not syncronized."); break; } } pthread_cancel(thread); cb_destroy(buffer); } TEST_CASE("Random buffer size and rounds", "[read][write][random]") { #define MAX_BUFFER 4096 /* Keep it reasonable, otherwise this test takes a long time. */ #define MAX_ROUNDS 100 struct circular_buffer *buffer; int i, ret, rounds; srand(get_seed()); /* Random number of bytes read from buffer. */ rounds = rand() % MAX_ROUNDS; buffer = random_buffer(MAX_BUFFER); INFO("Testing buffer size (" << buffer->length << " for " << rounds << " rounds."); i = 0; while (rounds > 0) { char write[] = { i }, read[1]; /* Write the int value to the buffer. This is garbage data. */ ret = cb_write(buffer, write, 1); REQUIRE(ret == 1); /* Verify what was read is what was written. */ ret = cb_read(buffer, read, 1); REQUIRE(read[0] == write[0]); if (i >= buffer->length) { rounds--; i = 0; } i++; } /* There should be no remaining data. */ REQUIRE(cb_available_data(buffer) == 0); }
28.155629
88
0.688639
erichschroeter
fd415f40366e15530e9acc482cf037f4fda479d6
351
cpp
C++
demos/stdio/carrots/carrots.cpp
rambasnet/CPP-Fundamentals
bc2fa9fddac95ffaca56d3251842f35c52eb76b8
[ "MIT" ]
6
2021-03-12T10:02:23.000Z
2022-01-11T12:27:41.000Z
demos/stdio/carrots/carrots.cpp
rambasnet/CPPFundamentals
d0dabf1969b2a084b15e8c0bbba3f70045b263f5
[ "MIT" ]
1
2021-03-13T18:07:37.000Z
2021-05-12T09:09:17.000Z
demos/stdio/carrots/carrots.cpp
rambasnet/CPPFundamentals
d0dabf1969b2a084b15e8c0bbba3f70045b263f5
[ "MIT" ]
10
2021-03-12T10:02:33.000Z
2022-03-07T23:20:39.000Z
/* Kattis problem - https://open.kattis.com/problems/carrots Solving for Carrots Algorithm steps: - read only the first line (two numbers) - output the second number */ #include <iostream> #include <cstdio> // printf using namespace std; int main() { int N, P; cin >> N >> P; //cout << P << endl; printf("%d\n", P); return 0; }
16.714286
57
0.62963
rambasnet
fd42376fcd48f86a650efbef3d27f2221688aa60
882
cpp
C++
src/Przeszkoda_Prost.cpp
broszczakmateusz/Dron-poprawione
a7a3efc370e2ddf6110fd8e3672296cf32775dc2
[ "MIT" ]
null
null
null
src/Przeszkoda_Prost.cpp
broszczakmateusz/Dron-poprawione
a7a3efc370e2ddf6110fd8e3672296cf32775dc2
[ "MIT" ]
null
null
null
src/Przeszkoda_Prost.cpp
broszczakmateusz/Dron-poprawione
a7a3efc370e2ddf6110fd8e3672296cf32775dc2
[ "MIT" ]
null
null
null
// // Created by mati on 07.06.2020. // #include "Przeszkoda_Prost.h" Przeszkoda_Prost::Przeszkoda_Prost(std::shared_ptr<drawNS::Draw3DAPI> ptrApi, const SWektor<double,ROZMIAR> &sr) : Prostopadloscian(ptrApi, sr) { for (int i = 0; i<8; i++) { Wierzcholki[i] = Wierzcholki[i] /2; } SWektor<double,ROZMIAR> tmp; tmp = srodek - Wierzcholki[0]; r_przeszkoda = tmp.dlugosc(); } void Przeszkoda_Prost::Rysuj() { Prostopadloscian::Rysuj(); api->change_shape_color(id,"green"); api->redraw(); } bool Przeszkoda_Prost::czy_kolizja(const Dron_interfejs &D)const { double suma_r = r_przeszkoda + D.get_r(); SWektor<double,ROZMIAR> tmp; tmp = srodek - D.get_srodek(); if ( tmp.dlugosc() < suma_r) { std::cout<< "Nastapila kolizja z przeszkoada! Wstrzymano ruch."; return true; } else return false; }
26.727273
112
0.646259
broszczakmateusz
fd42e1fb90e15220993a425ab67d649d58b8b1e0
2,842
cpp
C++
Programiranje Test 2 - Fuzija (spajanje) 2 niza u jedan/main.cpp
owlCoder/C_Plus_Plus_Projects
d2c70411c9322c89a8d6158a144e161abce65735
[ "MIT" ]
null
null
null
Programiranje Test 2 - Fuzija (spajanje) 2 niza u jedan/main.cpp
owlCoder/C_Plus_Plus_Projects
d2c70411c9322c89a8d6158a144e161abce65735
[ "MIT" ]
null
null
null
Programiranje Test 2 - Fuzija (spajanje) 2 niza u jedan/main.cpp
owlCoder/C_Plus_Plus_Projects
d2c70411c9322c89a8d6158a144e161abce65735
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; #include "FUZIJA.hpp" #include "PRAVOUGAONIK.hpp" #include "TACKA.hpp" int main() { int na, nb, nc, i; { cout << "\n---------------------- <int> ----------------------\n"; cout << endl << "Unos dimenzije za prvi niz: "; cin >> na; int* a = new int [na]; cout << "Unos elemenata prvog niza: "; for (i = 0; i < na; i++) cin >> a[i]; cout << endl << "\nUnos dimenzije za drugi niz: "; cin >> nb; int* b = new int [nb]; cout << "Unos elemenata drugog niza: "; for (i = 0; i < nb; i++) cin >> b[i]; int* c; fuzija <int> (a, na, b, nb, c, nc); cout << endl << "Fuzija: \n"; for (i = 0; i < nc; i++) cout << " " << c[i]; delete [] a; delete [] b; delete [] c; cout << "\n---------------------- <int> ----------------------\n"; } { cout << "\n\n\n\n---------------------- <Tacka> --------------------\n"; cout << endl << "Unos dimenzije za prvi niz: "; cin >> na; Tacka* a = new Tacka [na]; cout << "Unos elemenata prvog niza: "; for (i = 0; i < na; i++) cin >> a[i]; cout << endl << "\nUnos dimenzije za drugi niz: "; cin >> nb; Tacka* b = new Tacka [nb]; cout << "Unos elemenata drugog niza: "; for (i = 0; i < nb; i++) cin >> b[i]; Tacka* c; fuzija <Tacka> (a, na, b, nb, c, nc); cout << endl << "Fuzija: \n"; for (i = 0; i < nc; i++) cout << " " << c[i]; delete [] a; delete [] b; delete [] c; cout << "\n---------------------- <Tacka> ---------------------\n"; } { cout << "\n\n\n\n----------------- <Pravougaonik> -----------------\n"; cout << endl << "Unos dimenzije za prvi niz: "; cin >> na; Pravougaonik* a = new Pravougaonik [na]; cout << "Unos elemenata prvog niza: "; for (i = 0; i < na; i++) cin >> a[i]; cout << endl << "\nUnos dimenzije za drugi niz: "; cin >> nb; Pravougaonik* b = new Pravougaonik [nb]; cout << "Unos elemenata drugog niza: "; for (i = 0; i < nb; i++) cin >> b[i]; Pravougaonik* c; fuzija <Pravougaonik> (a, na, b, nb, c, nc); cout << endl << "Fuzija: \n"; for (i = 0; i < nc; i++) cout << " " << c[i]; delete [] a; delete [] b; delete [] c; cout << "\n------------------- <Pravougaonik> -----------------\n"; } return 0; }
23.882353
81
0.354328
owlCoder
fd47f756c6468c0c78a994564c8a0efa229d2268
1,721
cpp
C++
gpmp2/obstacle/tests/testSelfCollision.cpp
Cryptum169/gpmp2
f361baac4917b9a4d1220411e9c69dc9f96f4277
[ "BSD-3-Clause" ]
null
null
null
gpmp2/obstacle/tests/testSelfCollision.cpp
Cryptum169/gpmp2
f361baac4917b9a4d1220411e9c69dc9f96f4277
[ "BSD-3-Clause" ]
null
null
null
gpmp2/obstacle/tests/testSelfCollision.cpp
Cryptum169/gpmp2
f361baac4917b9a4d1220411e9c69dc9f96f4277
[ "BSD-3-Clause" ]
null
null
null
/** * @file testSelfCollisionArm.cpp * @author Mustafa Mukadam **/ #include <CppUnitLite/TestHarness.h> #include <gtsam/base/Matrix.h> #include <gtsam/base/Testable.h> #include <gtsam/base/numericalDerivative.h> #include <gpmp2/obstacle/SelfCollisionArm.h> #include <iostream> #include <cmath> using namespace std; using namespace gtsam; using namespace gpmp2; /* ************************************************************************** */ TEST(SelfCollisionArm, error) { // 3 link arm Vector3 a(1, 1, 1), alpha(0, 0, 0), d(0, 0, 0); Arm abs_arm(3, a, alpha, d); BodySphereVector body_spheres; body_spheres.push_back(BodySphere(0, 0.1, Point3(-0.5, 0, 0))); body_spheres.push_back(BodySphere(1, 0.1, Point3(-0.5, 0, 0))); body_spheres.push_back(BodySphere(1, 0.1, Point3(0, 0, 0))); body_spheres.push_back(BodySphere(2, 0.1, Point3(0, 0, 0))); ArmModel arm(abs_arm, body_spheres); Matrix data(2, 4); // sphere A id, sphere B id, epsilon, sigma data << 0, 1, 2.0, 0.1, 2, 3, 5.0, 0.1; SelfCollisionArm factor = SelfCollisionArm(0, arm, data); Vector actual, expect; Matrix H_exp, H_act; Vector3 q; q = Vector3(0.0, M_PI/2.0, 0.0); actual = factor.evaluateError(q, H_act); expect = (Vector(2) << 1.4928932188134527, 4.2).finished(); H_exp = numericalDerivative11(std::function<Vector2(const Vector3&)>( boost::bind(&SelfCollisionArm::evaluateError, factor, _1, boost::none)), q, 1e-6); EXPECT(assert_equal(expect, actual, 1e-6)); EXPECT(assert_equal(H_exp, H_act, 1e-6)); } /* ************************************************************************** */ /* main function */ int main() { TestResult tr; return TestRegistry::runAllTests(tr); }
28.213115
86
0.617083
Cryptum169
fd4ea416767b84ab190e43866def0e8565f86d59
2,159
cpp
C++
src/dataEntry.cpp
fborsani/water-usage-manager
74bacca63f255837054247cd26bad90c5e2ce31f
[ "MIT" ]
null
null
null
src/dataEntry.cpp
fborsani/water-usage-manager
74bacca63f255837054247cd26bad90c5e2ce31f
[ "MIT" ]
null
null
null
src/dataEntry.cpp
fborsani/water-usage-manager
74bacca63f255837054247cd26bad90c5e2ce31f
[ "MIT" ]
1
2019-11-16T20:15:48.000Z
2019-11-16T20:15:48.000Z
#include "dataEntry.h" dataEntry::dataEntry(QString date, QString cons, QString user):date(date),cons(cons),user(user){} dataEntry::dataEntry(std::string stdDate, std::string stdCons, std::string stdUser): date(date.fromStdString(stdDate)), cons(cons.fromStdString(stdUser)), user(user.fromStdString(stdCons)){} dataEntry::dataEntry(){} QString dataEntry::getDate() const{return date;} QDateTime dataEntry::getDateTime() const{return QDateTime::fromString(date,DATE_TIME_FORMAT);} QString dataEntry::getUser() const{return user;} QString dataEntry::getCons() const{return cons;} double dataEntry::getConsDouble() const{return cons.toDouble();} size_t dataEntry::sizeOf() const{return sizeof(date)+sizeof(user)+sizeof(cons);} bool dataEntry::compare(dataEntry lt, dataEntry rt){return lt.getDateTime() < rt.getDateTime();} void dataEntry::calcDelta(dataEntry* prevRead){ if(prevRead==NULL) this->delta = this->getConsDouble(); else this->delta = this->getConsDouble()-prevRead->getConsDouble(); } double dataEntry::getDelta(){return delta;} bool dataEntry::operator ==(dataEntry& c){return this->getDate()==c.getDate();} bool dataEntry::operator !=(dataEntry& c){return !(*this==c);} bool dataEntry::operator >(dataEntry& c){return this->getDateTime()>c.getDateTime();} bool dataEntry::operator <(dataEntry& c){return this->getDateTime()<c.getDateTime();} bool dataEntry::operator >=(dataEntry& c){return this->getDateTime()>=c.getDateTime();} bool dataEntry::operator <=(dataEntry& c){return this->getDateTime()<=c.getDateTime();} bool dataEntry::operator ==(const dataEntry& c) const{return this->getDate()==c.getDate();} bool dataEntry::operator !=(const dataEntry& c) const{return !(*this==c);} bool dataEntry::operator >(const dataEntry& c) const{return this->getDateTime()>c.getDateTime();} bool dataEntry::operator <(const dataEntry& c) const{return this->getDateTime()<c.getDateTime();} bool dataEntry::operator >=(const dataEntry& c) const{return this->getDateTime()>=c.getDateTime();} bool dataEntry::operator <=(const dataEntry& c) const{return this->getDateTime()<=c.getDateTime();}
55.358974
100
0.728115
fborsani
fd57a84e742671ace2a25b648a9028b9f8e41bee
966
cpp
C++
library/source/operations_tests/pretty_print_tester.cpp
spiretrading/darcel
a9c32989ad9c1571edaa41c7c3a86b276b782c0d
[ "MIT" ]
null
null
null
library/source/operations_tests/pretty_print_tester.cpp
spiretrading/darcel
a9c32989ad9c1571edaa41c7c3a86b276b782c0d
[ "MIT" ]
null
null
null
library/source/operations_tests/pretty_print_tester.cpp
spiretrading/darcel
a9c32989ad9c1571edaa41c7c3a86b276b782c0d
[ "MIT" ]
1
2020-04-17T13:25:25.000Z
2020-04-17T13:25:25.000Z
#include <sstream> #include <catch.hpp> #include "darcel/operations/pretty_print.hpp" #include "darcel/syntax/literal_expression.hpp" using namespace darcel; using namespace std; TEST_CASE("test_pretty_print_let", "[pretty_print]") { SECTION("Int literal") { std::stringstream ss; auto l = std::make_unique<LiteralExpression>(Location::global(), Literal("123", IntegerDataType::get_instance())); pretty_print(*l, ss); REQUIRE(ss.str() == "123"); } SECTION("Bool literal") { std::stringstream ss; auto l = std::make_unique<LiteralExpression>(Location::global(), Literal("true", BoolDataType::get_instance())); pretty_print(*l, ss); REQUIRE(ss.str() == "true"); } SECTION("String literal") { std::stringstream ss; auto l = std::make_unique<LiteralExpression>(Location::global(), Literal("hello", TextDataType::get_instance())); pretty_print(*l, ss); REQUIRE(ss.str() == "\"hello\""); } }
30.1875
68
0.665631
spiretrading