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 109 | 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 48.5k ⌀ | 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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2e85659c8a6c118ebe7e4ed04bee70cd125b1ee6 | 5,729 | cpp | C++ | Software/Remote-Control/LCD/settings.cpp | Nils2332/Timelapsebuild | b52f6aef94047295e815dabe2a9db1f44e46d883 | [
"MIT"
] | null | null | null | Software/Remote-Control/LCD/settings.cpp | Nils2332/Timelapsebuild | b52f6aef94047295e815dabe2a9db1f44e46d883 | [
"MIT"
] | null | null | null | Software/Remote-Control/LCD/settings.cpp | Nils2332/Timelapsebuild | b52f6aef94047295e815dabe2a9db1f44e46d883 | [
"MIT"
] | null | null | null | /*
* settings.cpp
*
* Created on: 02.04.2019
* Author: Nils
*/
#include "settings.h"
#include "Gui.h"
#include "math.h"
#include "lvgl.h"
#include "joycon.h"
#include "App.h"
#include "System.h"
static lv_res_t fkt_Jaw_min(lv_obj_t *btn);
static lv_res_t fkt_Jaw_max(lv_obj_t *btn);
static lv_res_t fkt_Pitch_min(lv_obj_t *btn);
static lv_res_t fkt_Pitch_max(lv_obj_t *btn);
static lv_res_t fkt_Slide_min(lv_obj_t *btn);
static lv_res_t fkt_Slide_max(lv_obj_t *btn);
static lv_res_t fkt_Jaw_min(lv_obj_t *btn){
uint8_t data[6];
int32_t buffer = -11111*4; //125/0.01125
data[0] = 0;
data[0] |= 0<<4;
data[0] |= 2;
data[1] = buffer >> 24;
data[2] = buffer >> 16;
data[3] = buffer >> 8;
data[4] = buffer;
data[5] = 100;
System::sendcheck(data, 6);
return LV_RES_OK;
}
static lv_res_t fkt_Jaw_max(lv_obj_t *btn)
{
uint8_t data[6];
int32_t buffer = 11111*4; //125/0.01125
data[0] = 0;
data[0] |= 0<<4;
data[0] |= 2;
data[1] = buffer >> 24;
data[2] = buffer >> 16;
data[3] = buffer >> 8;
data[4] = buffer;
data[5] = 100;
System::sendcheck(data, 6);
return LV_RES_OK;
}
static lv_res_t fkt_Pitch_min(lv_obj_t *btn)
{
uint8_t data[6];
int32_t buffer = -8088*4; //92/0.01125
data[0] = 0;
data[0] |= 1<<4;
data[0] |= 2;
data[1] = buffer >> 24;
data[2] = buffer >> 16;
data[3] = buffer >> 8;
data[4] = buffer;
data[5] = 100;
System::sendcheck(data, 6);
return LV_RES_OK;
}
static lv_res_t fkt_Pitch_max(lv_obj_t *btn)
{
uint8_t data[6];
int32_t buffer = 8088*4; //92/0.01125
data[0] = 0;
data[0] |= 1<<4;
data[0] |= 2;
data[1] = buffer >> 24;
data[2] = buffer >> 16;
data[3] = buffer >> 8;
data[4] = buffer;
data[5] = 100;
System::sendcheck(data, 6);
return LV_RES_OK;
}
static lv_res_t fkt_Slide_min(lv_obj_t *btn)
{
uint8_t data[6];
int32_t buffer = 0;
data[0] = 0;
data[0] |= 2<<4;
data[0] |= 2;
data[1] = buffer >> 24;
data[2] = buffer >> 16;
data[3] = buffer >> 8;
data[4] = buffer;
data[5] = 100;
System::sendcheck(data, 6);
return LV_RES_OK;
}
static lv_res_t fkt_Slide_max(lv_obj_t *btn)
{
uint8_t data[6];
int32_t buffer = 50000*4;
data[0] = 0;
data[0] |= 2<<4;
data[0] |= 2;
data[1] = buffer >> 24;
data[2] = buffer >> 16;
data[3] = buffer >> 8;
data[4] = buffer;
data[5] = 100;
System::sendcheck(data, 6);
return LV_RES_OK;
}
void createSettings(lv_obj_t * parent)
{
uint8_t btn_height = 36;
/*Button Back*/
lv_obj_t *btn = lv_btn_create(parent, NULL);
lv_obj_set_size(btn, 150, btn_height);
lv_obj_align(btn, parent, LV_ALIGN_IN_TOP_LEFT, 5, 0);
lv_btn_set_action(btn, LV_BTN_ACTION_CLICK, fkt_return);
lv_obj_t *label = lv_label_create(btn, NULL);
lv_label_set_text(label, "Return");
/*Button Jaw min*/
lv_obj_t *btn_Jaw_min = lv_btn_create(parent, NULL);
lv_obj_set_size(btn_Jaw_min, 115, btn_height);
lv_obj_align(btn_Jaw_min, btn, LV_ALIGN_OUT_BOTTOM_LEFT, 0, 20);
lv_btn_set_action(btn_Jaw_min, LV_BTN_ACTION_CLICK, fkt_Jaw_min);
label = lv_label_create(btn_Jaw_min, NULL);
lv_label_set_text(label, "Jaw min");
/*Button Jaw max*/
lv_obj_t *btn_Jaw_max = lv_btn_create(parent, NULL);
lv_obj_set_size(btn_Jaw_max, 115, btn_height);
lv_obj_align(btn_Jaw_max, btn_Jaw_min, LV_ALIGN_OUT_RIGHT_MID, 0, 0);
lv_btn_set_action(btn_Jaw_max, LV_BTN_ACTION_CLICK, fkt_Jaw_max);
label = lv_label_create(btn_Jaw_max, NULL);
lv_label_set_text(label, "Jaw max");
/*Button Pitch min*/
lv_obj_t *btn_Pitch_min = lv_btn_create(parent, NULL);
lv_obj_set_size(btn_Pitch_min, 115, btn_height);
lv_obj_align(btn_Pitch_min, btn_Jaw_min, LV_ALIGN_OUT_BOTTOM_LEFT, 0, 0);
lv_btn_set_action(btn_Pitch_min, LV_BTN_ACTION_CLICK, fkt_Pitch_min);
label = lv_label_create(btn_Pitch_min, NULL);
lv_label_set_text(label, "Pitch min");
/*Button Pitch max*/
lv_obj_t *btn_Pitch_max = lv_btn_create(parent, NULL);
lv_obj_set_size(btn_Pitch_max, 115, btn_height);
lv_obj_align(btn_Pitch_max, btn_Pitch_min, LV_ALIGN_OUT_RIGHT_MID, 0, 0);
lv_btn_set_action(btn_Pitch_max, LV_BTN_ACTION_CLICK, fkt_Pitch_max);
label = lv_label_create(btn_Pitch_max, NULL);
lv_label_set_text(label, "Pitch max");
/*Button Slide min*/
lv_obj_t *btn_Slide_min = lv_btn_create(parent, NULL);
lv_obj_set_size(btn_Slide_min, 115, btn_height);
lv_obj_align(btn_Slide_min, btn_Pitch_min, LV_ALIGN_OUT_BOTTOM_LEFT, 0, 0);
lv_btn_set_action(btn_Slide_min, LV_BTN_ACTION_CLICK, fkt_Slide_min);
label = lv_label_create(btn_Slide_min, NULL);
lv_label_set_text(label, "Slide left");
/*Button Slide max*/
lv_obj_t *btn_Slide_max = lv_btn_create(parent, NULL);
lv_obj_set_size(btn_Slide_max, 115, btn_height);
lv_obj_align(btn_Slide_max, btn_Slide_min, LV_ALIGN_OUT_RIGHT_MID, 0, 0);
lv_btn_set_action(btn_Slide_max, LV_BTN_ACTION_CLICK, fkt_Slide_max);
label = lv_label_create(btn_Slide_max, NULL);
lv_label_set_text(label, "Slide right");
/*Button All min*/
lv_obj_t *btn_All_min = lv_btn_create(parent, NULL);
lv_obj_set_size(btn_All_min, 115, btn_height);
lv_obj_align(btn_All_min, btn_Slide_min, LV_ALIGN_OUT_BOTTOM_LEFT, 0, 20);
//TODO lv_btn_set_action(btn_All_min, LV_BTN_ACTION_CLICK, btn_returntomain);
label = lv_label_create(btn_All_min, NULL);
lv_label_set_text(label, "All left");
/*Button All max*/
lv_obj_t *btn_All_max = lv_btn_create(parent, NULL);
lv_obj_set_size(btn_All_max, 115, btn_height);
lv_obj_align(btn_All_max, btn_All_min, LV_ALIGN_OUT_RIGHT_MID, 0, 0);
//TODO lv_btn_set_action(btn_All_max, LV_BTN_ACTION_CLICK, btn_returntomain);
label = lv_label_create(btn_All_max, NULL);
lv_label_set_text(label, "All right");
}
| 26.896714 | 81 | 0.699948 | Nils2332 |
2e8717ba32c0ba0666497ed6a52f05b851ac8e46 | 1,997 | hh | C++ | include/premaidai_teleoperation/interactive_marker.hh | chikuta/premaidai_teleoperation | b2bae0e09d0c923a9aeb4ebea1b4c4e2cb85e2d4 | [
"MIT"
] | null | null | null | include/premaidai_teleoperation/interactive_marker.hh | chikuta/premaidai_teleoperation | b2bae0e09d0c923a9aeb4ebea1b4c4e2cb85e2d4 | [
"MIT"
] | null | null | null | include/premaidai_teleoperation/interactive_marker.hh | chikuta/premaidai_teleoperation | b2bae0e09d0c923a9aeb4ebea1b4c4e2cb85e2d4 | [
"MIT"
] | null | null | null | #ifndef _PREMAIDAI_INTERACTIVE_MARKER_HH_
#define _PREMAIDAI_INTERACTIVE_MARKER_HH_
#include <ros/ros.h>
#include <std_srvs/Empty.h>
#include <tf2_ros/transform_broadcaster.h>
#include <tf2_ros/transform_listener.h>
#include <interactive_markers/interactive_marker_server.h>
namespace premaidai_teleoperation
{
class InteractiveMarker
{
public:
explicit InteractiveMarker(const std::string& name);
virtual ~InteractiveMarker();
protected:
void timerCallback(const ros::TimerEvent& event);
void processFeedback(const visualization_msgs::InteractiveMarkerFeedbackConstPtr& feedback);
bool resetMarkerPose(std_srvs::Empty::Request& request, std_srvs::Empty::Response& response);
geometry_msgs::TransformStamped getInitialTransform(const std::string& base_link, const std::string& target_frame);
private:
// typedef
typedef std::shared_ptr<interactive_markers::InteractiveMarkerServer> InteractiveMarkerServerPtr;
InteractiveMarkerServerPtr server_; /** interactive marker server */
std::string name_; /** interactive marker server name */
std::string frame_id_; /** frame_id (default: /base_link) */
std::string base_link_; /** base_link name (default: /base_link) */
std::string initial_frame_; /** base_link name (default: /base_link) */
ros::NodeHandle nh_; /** ros private node handler */
ros::ServiceServer reset_marker_pos_srv_; /** reset marker position service */
ros::Timer tf_timer_; /** timer callback for tf (base_link_ -> frame_id_) */
tf2_ros::Buffer tf_buffer_; /** tf buffer */
tf2_ros::TransformListener listener_; /** tf listener */
tf2_ros::TransformBroadcaster broadcaster_; /** tf broadcaster */
geometry_msgs::TransformStamped initial_trans_;
geometry_msgs::Pose current_pose_;
};
};
#endif //_PREMAIDAI_INTERACTIVE_MARKER_HH_
| 42.489362 | 119 | 0.699549 | chikuta |
2e8cac60d5c21599a6e03391c8585c04fcaf87ea | 5,905 | cc | C++ | modules/intermodal/src/query_bounds.cc | dgcl/motis | 6b134f80aa3b6445f710418962f1fed9cffda3a0 | [
"MIT"
] | 2 | 2020-08-11T19:41:58.000Z | 2021-12-10T16:05:52.000Z | modules/intermodal/src/query_bounds.cc | dgcl/motis | 6b134f80aa3b6445f710418962f1fed9cffda3a0 | [
"MIT"
] | null | null | null | modules/intermodal/src/query_bounds.cc | dgcl/motis | 6b134f80aa3b6445f710418962f1fed9cffda3a0 | [
"MIT"
] | 1 | 2021-10-06T13:48:23.000Z | 2021-10-06T13:48:23.000Z | #include "motis/intermodal/query_bounds.h"
#include "utl/verify.h"
#include "motis/core/access/station_access.h"
#include "motis/module/context/motis_call.h"
#include "motis/module/message.h"
#include "motis/intermodal/error.h"
using namespace flatbuffers;
using namespace motis::routing;
using namespace motis::module;
namespace motis::intermodal {
inline std::time_t get_direct_start_time(Interval const* interval) {
return interval->begin() + (interval->end() - interval->begin()) / 2;
}
inline station const* get_station(schedule const& sched,
InputStation const* input_station) {
using guesser::StationGuesserResponse;
std::string station_id;
if (input_station->id()->Length() != 0) {
station_id = input_station->id()->str();
} else {
module::message_creator b;
b.create_and_finish(MsgContent_StationGuesserRequest,
guesser::CreateStationGuesserRequest(
b, 1, b.CreateString(input_station->name()->str()))
.Union(),
"/guesser");
auto const msg = motis_call(make_msg(b))->val();
auto const guesses = motis_content(StationGuesserResponse, msg)->guesses();
if (guesses->size() == 0) {
throw std::system_error(error::no_guess_for_station);
}
station_id = guesses->Get(0)->id()->str();
}
return motis::get_station(sched, station_id);
}
query_start parse_query_start(FlatBufferBuilder& fbb,
IntermodalRoutingRequest const* req,
schedule const& sched) {
auto start_station = CreateInputStation(fbb, fbb.CreateString(STATION_START),
fbb.CreateString(STATION_START));
switch (req->start_type()) {
case IntermodalStart_IntermodalOntripStart: {
auto const start =
reinterpret_cast<IntermodalOntripStart const*>(req->start());
return {
Start_OntripStationStart,
CreateOntripStationStart(fbb, start_station, start->departure_time())
.Union(),
{start->position()->lat(), start->position()->lng()},
start->departure_time(),
true};
}
case IntermodalStart_IntermodalPretripStart: {
auto const start =
reinterpret_cast<IntermodalPretripStart const*>(req->start());
return {Start_PretripStart,
CreatePretripStart(fbb, start_station, start->interval(),
start->min_connection_count(),
start->extend_interval_earlier(),
start->extend_interval_later())
.Union(),
{start->position()->lat(), start->position()->lng()},
get_direct_start_time(start->interval()),
true};
}
case IntermodalStart_OntripTrainStart: {
auto const start =
reinterpret_cast<OntripTrainStart const*>(req->start());
auto const station = get_station(sched, start->station());
return {Start_OntripTrainStart,
CreateOntripTrainStart(
fbb, motis_copy_table(TripId, fbb, start->trip()),
CreateInputStation(fbb, fbb.CreateString(station->eva_nr_),
fbb.CreateString("")),
start->arrival_time())
.Union(),
{station->lat(), station->lng()},
start->arrival_time(),
false};
}
case IntermodalStart_OntripStationStart: {
auto const start =
reinterpret_cast<OntripStationStart const*>(req->start());
auto const station = get_station(sched, start->station());
return {Start_OntripStationStart,
CreateOntripStationStart(
fbb,
CreateInputStation(fbb, fbb.CreateString(station->eva_nr_),
fbb.CreateString("")),
start->departure_time())
.Union(),
{station->lat(), station->lng()},
start->departure_time(),
false};
}
case IntermodalStart_PretripStart: {
auto const start = reinterpret_cast<PretripStart const*>(req->start());
auto const station = get_station(sched, start->station());
return {
Start_PretripStart,
CreatePretripStart(
fbb,
CreateInputStation(fbb, fbb.CreateString(station->eva_nr_),
fbb.CreateString("")),
start->interval(), start->min_connection_count(),
start->extend_interval_earlier(), start->extend_interval_later())
.Union(),
{station->lat(), station->lng()},
get_direct_start_time(start->interval()),
false};
}
default: throw utl::fail("invalid query start");
}
}
query_dest parse_query_dest(FlatBufferBuilder& fbb,
IntermodalRoutingRequest const* req,
schedule const& sched) {
switch (req->destination_type()) {
case IntermodalDestination_InputStation: {
auto const station = get_station(
sched, reinterpret_cast<InputStation const*>(req->destination()));
return query_dest{motis_copy_table(InputStation, fbb, req->destination()),
{station->lat(), station->lng()},
false};
}
case IntermodalDestination_InputPosition: {
auto pos = reinterpret_cast<InputPosition const*>(req->destination());
auto end_station = CreateInputStation(fbb, fbb.CreateString(STATION_END),
fbb.CreateString(STATION_END));
return {end_station, {pos->lat(), pos->lng()}, true};
}
default: throw utl::fail("invalid query dest");
}
}
} // namespace motis::intermodal
| 37.852564 | 80 | 0.584589 | dgcl |
2e8fda6cf4184d3935b4202492bdc60e23b818db | 2,033 | cpp | C++ | demos/sjtwo/esp8266/source/main.cpp | diarkia124/SJSU-Dev2 | 3385f034690d281c2720e17b0a6bdbe51a65113c | [
"Apache-2.0"
] | 1 | 2019-11-25T20:31:07.000Z | 2019-11-25T20:31:07.000Z | demos/sjtwo/esp8266/source/main.cpp | diarkia124/SJSU-Dev2 | 3385f034690d281c2720e17b0a6bdbe51a65113c | [
"Apache-2.0"
] | null | null | null | demos/sjtwo/esp8266/source/main.cpp | diarkia124/SJSU-Dev2 | 3385f034690d281c2720e17b0a6bdbe51a65113c | [
"Apache-2.0"
] | null | null | null | #include <cinttypes>
#include <cstdint>
#include <string_view>
#include "L1_Peripheral/lpc40xx/uart.hpp"
#include "L2_HAL/communication/esp8266.hpp"
#include "utility/log.hpp"
#include "utility/debug.hpp"
constexpr char kGetRequestExample[] =
"GET / HTTP/1.1\r\n"
"Host: www.example.com\r\n\r\n";
#define LOG_IF_NOT_SUCCESSFUL(expression) \
{ \
sjsu::Status log_no_success_status = (expression); \
if (log_no_success_status != sjsu::Status::kSuccess) \
{ \
LOG_WARNING("Expression Failed: %s", #expression); \
} \
}
int main()
{
LOG_INFO("ESP8266 Application Starting...");
sjsu::lpc40xx::Uart uart3(sjsu::lpc40xx::Uart::Port::kUart3);
sjsu::Esp8266 wifi(uart3);
LOG_INFO("Initializing Wifi...");
LOG_IF_NOT_SUCCESSFUL(wifi.Initialize());
while (true)
{
LOG_INFO("Attempting to connect...");
auto status = wifi.ConnectToAccessPoint("KAMMCE-PHONE", "roverteam");
if (status == sjsu::Status::kSuccess)
{
break;
}
LOG_INFO("Failed to connect... Retrying ...");
wifi.DisconnectFromAccessPoint();
}
LOG_INFO("Connected to Wifi");
for (int i = 0; i < 2; i++)
{
LOG_INFO("Connecting to server...");
LOG_IF_NOT_SUCCESSFUL(wifi.Connect(
sjsu::InternetSocket::Protocol::kTCP, "www.example.com", 80, 5s));
LOG_INFO("Send Write Request...");
LOG_IF_NOT_SUCCESSFUL(
wifi.Write(kGetRequestExample, sizeof(kGetRequestExample), 100ms));
LOG_INFO("Read Back Response...");
char response[1024 * 4] = {};
size_t read_back = wifi.Read(response, sizeof(response), 10s);
LOG_INFO("Hexdumping Response...");
sjsu::debug::Hexdump(response, read_back);
LOG_INFO("Direct Print...");
printf("%.*s\r", read_back, response);
wifi.Close();
sjsu::Delay(5s);
}
wifi.DisconnectFromAccessPoint();
return 0;
}
| 27.472973 | 75 | 0.597147 | diarkia124 |
2e99becc881b7f2b3104ef16f8e13011e63532dd | 1,308 | cpp | C++ | src/compiler/Type Checker/TypeString.cpp | dimashky/compiler | 0b772d16aec1a327698886b1f28f3abdfa60c1a1 | [
"MIT"
] | 5 | 2018-07-06T04:05:05.000Z | 2021-08-05T23:59:44.000Z | src/compiler/Type Checker/TypeString.cpp | maheralkassir/compiler | 0b772d16aec1a327698886b1f28f3abdfa60c1a1 | [
"MIT"
] | 4 | 2018-07-05T22:19:30.000Z | 2018-07-05T22:19:30.000Z | src/compiler/Type Checker/TypeString.cpp | maheralkassir/compiler | 0b772d16aec1a327698886b1f28f3abdfa60c1a1 | [
"MIT"
] | 3 | 2018-12-08T10:13:32.000Z | 2021-03-27T02:04:18.000Z | #include "all.h"
#include <iostream>
#include <string>
TypeString::TypeString() {
this->typeId = TYPE_STRING;
this->bytes = 255;
}
TypeString* TypeString::instance = nullptr;
TypeString* TypeString::getInstance() {
if (TypeString::instance == nullptr) {
TypeString::instance = new TypeString();
}
return TypeString::instance;
}
std::string TypeString::typeExpression() {
return "STRING";
}
TypeExpression* TypeString::operation(Operator op, TypeExpression* secondOperand) {
int equivelant = TYPE_STRING;
if (secondOperand != nullptr) {
equivelant = this->equivelantTo(secondOperand);
}
if (equivelant == TYPE_ERROR) {
return new TypeError(this->typeExpression() + " is not equivelant to " + secondOperand->typeExpression());
}
else {
switch (op)
{
case Plus:
return TypeString::getInstance();
break;
case eqeq:
return TypeBoolean::getInstance();
break;
case Equal:
return TypeString::getInstance();
break;
default:
return new TypeError(this->typeExpression() + " has no predefined " + OperatorName[op] + " operation");
break;
}
}
}
int TypeString::equivelantTo(TypeExpression* secondOperand, bool cast) {
if (secondOperand->getTypeId() == TYPE_STRING || secondOperand->getTypeId() == TYPE_CHAR)
return TYPE_STRING;
return TYPE_ERROR;
}
| 22.947368 | 108 | 0.704128 | dimashky |
2e9aa7cd74b7f8b00fa1da4ebcf03018f8fd3099 | 339 | cpp | C++ | duilib_test/EditTab.cpp | balloonwj/BalloonDuilib | 3fd8700d3b10075e2a9f62931c56bb394e893876 | [
"BSD-2-Clause",
"MIT"
] | 2 | 2018-11-23T00:57:12.000Z | 2019-03-26T05:52:41.000Z | duilib_test/EditTab.cpp | balloonwj/BalloonDuilib | 3fd8700d3b10075e2a9f62931c56bb394e893876 | [
"BSD-2-Clause",
"MIT"
] | null | null | null | duilib_test/EditTab.cpp | balloonwj/BalloonDuilib | 3fd8700d3b10075e2a9f62931c56bb394e893876 | [
"BSD-2-Clause",
"MIT"
] | 9 | 2019-05-13T17:36:45.000Z | 2022-03-22T12:46:33.000Z | #include "stdafx.h"
#include "EditTab.h"
CEditTab::CEditTab( CPaintManagerUI* ppm /*= NULL*/ )
{
CDialogBuilder builder;
CContainerUI* pbtnTab = static_cast<CContainerUI*>(builder.Create(_T("Edit.xml"), 0, NULL, ppm));
if( pbtnTab ) {
this->Add(pbtnTab);
}
else {
this->RemoveAll();
return;
}
}
CEditTab::~CEditTab(void)
{
}
| 16.95 | 98 | 0.666667 | balloonwj |
2e9c807a920155169b02111123b65f82b9dfc004 | 1,913 | hpp | C++ | modules/core/linalg/include/nt2/linalg/functions/scalar/mnormfro.hpp | psiha/nt2 | 5e829807f6b57b339ca1be918a6b60a2507c54d0 | [
"BSL-1.0"
] | 34 | 2017-05-19T18:10:17.000Z | 2022-01-04T02:18:13.000Z | modules/core/linalg/include/nt2/linalg/functions/scalar/mnormfro.hpp | psiha/nt2 | 5e829807f6b57b339ca1be918a6b60a2507c54d0 | [
"BSL-1.0"
] | null | null | null | modules/core/linalg/include/nt2/linalg/functions/scalar/mnormfro.hpp | psiha/nt2 | 5e829807f6b57b339ca1be918a6b60a2507c54d0 | [
"BSL-1.0"
] | 7 | 2017-12-02T12:59:17.000Z | 2021-07-31T12:46:14.000Z | //==============================================================================
// Copyright 2003 - 2012 LASMEA UMR 6602 CNRS/Univ. Clermont II
// Copyright 2009 - 2012 LRI UMR 8623 CNRS/Univ Paris Sud XI
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef NT2_LINALG_FUNCTIONS_SCALAR_MNORMFRO_HPP_INCLUDED
#define NT2_LINALG_FUNCTIONS_SCALAR_MNORMFRO_HPP_INCLUDED
#include <nt2/linalg/functions/mnormfro.hpp>
#include <nt2/include/functions/abs.hpp>
#include <nt2/include/functions/colon.hpp>
#include <nt2/include/functions/ismatrix.hpp>
#include <nt2/include/functions/norm2.hpp>
#include <nt2/core/container/dsl.hpp>
#include <nt2/core/container/colon/colon.hpp>
#include <nt2/linalg/options.hpp>
#include <nt2/sdk/meta/as_real.hpp>
#include <nt2/core/container/dsl/forward.hpp>
#include <boost/assert.hpp>
namespace nt2 { namespace ext
{
BOOST_DISPATCH_IMPLEMENT ( mnormfro_, tag::cpu_
, (A0)
, (scalar_<unspecified_<A0> >)
)
{
typedef typename meta::as_real<A0>::type result_type;
BOOST_FORCEINLINE result_type operator()(A0 const& a0) const
{
return nt2::abs(a0);
}
};
BOOST_DISPATCH_IMPLEMENT ( mnormfro_, tag::cpu_
, (A0)
, ((ast_<A0, nt2::container::domain>))
)
{
typedef typename A0::value_type type_t;
typedef typename meta::as_real<type_t>::type result_type;
NT2_FUNCTOR_CALL(1)
{
BOOST_ASSERT_MSG(nt2::ismatrix(a0), "a0 is not a matrix");
return norm2(a0(nt2::_));
}
};
} }
#endif
| 34.781818 | 80 | 0.568217 | psiha |
2ea1a62694467a11b46470d8cdc9c57bd29a6633 | 2,846 | cc | C++ | flens/blas/interface/blas/rot.cc | stip/FLENS | 80495fa97dda42a0acafc8f83fc9639ae36d2e10 | [
"BSD-3-Clause"
] | 98 | 2015-01-26T20:31:37.000Z | 2021-09-09T15:51:37.000Z | flens/blas/interface/blas/rot.cc | stip/FLENS | 80495fa97dda42a0acafc8f83fc9639ae36d2e10 | [
"BSD-3-Clause"
] | 16 | 2015-01-21T07:43:45.000Z | 2021-12-06T12:08:36.000Z | flens/blas/interface/blas/rot.cc | stip/FLENS | 80495fa97dda42a0acafc8f83fc9639ae36d2e10 | [
"BSD-3-Clause"
] | 31 | 2015-01-05T08:06:45.000Z | 2022-01-26T20:12:00.000Z | #include <flens/blas/interface/blas/config.h>
using namespace flens;
extern "C" {
void
BLAS(srot)(const INTEGER *N,
float *X,
const INTEGER *INCX,
float *Y,
const INTEGER *INCY,
const float *C,
const float *S)
{
# ifdef TEST_DIRECT_CBLAS
cblas_srot(*N, X, *INCX, Y, *INCY, *C, *S);
# else
using std::abs;
SDenseVectorView x(SArrayView(*N, X, abs(*INCX)), *INCX<0);
SDenseVectorView y(SArrayView(*N, Y, abs(*INCY)), *INCY<0);
blas::rot(x, y, *C, *S);
# endif
}
void
BLAS(drot)(const INTEGER *N,
double *X,
const INTEGER *INCX,
double *Y,
const INTEGER *INCY,
const double *C,
const double *S)
{
# ifdef TEST_DIRECT_CBLAS
cblas_drot(*N, X, *INCX, Y, *INCY, *C, *S);
# else
using std::abs;
DDenseVectorView x(DArrayView(*N, X, abs(*INCX)), *INCX<0);
DDenseVectorView y(DArrayView(*N, Y, abs(*INCY)), *INCY<0);
blas::rot(x, y, *C, *S);
# endif
}
void
BLAS(crot)(const INTEGER *N,
cfloat *X,
const INTEGER *INCX,
cfloat *Y,
const INTEGER *INCY,
const cfloat *C,
const cfloat *S)
{
using std::abs;
CDenseVectorView x(CArrayView(*N, X, abs(*INCX)), *INCX<0);
CDenseVectorView y(CArrayView(*N, Y, abs(*INCY)), *INCY<0);
blas::rot(x, y, *C, *S);
}
void
BLAS(zrot)(const INTEGER *N,
cdouble *X,
const INTEGER *INCX,
cdouble *Y,
const INTEGER *INCY,
const cdouble *C,
const cdouble *S)
{
using std::abs;
ZDenseVectorView x(ZArrayView(*N, X, abs(*INCX)), *INCX<0);
ZDenseVectorView y(ZArrayView(*N, Y, abs(*INCY)), *INCY<0);
blas::rot(x, y, *C, *S);
}
void
BLAS(csrot)(const INTEGER *N,
cfloat *X,
const INTEGER *INCX,
cfloat *Y,
const INTEGER *INCY,
const float *C,
const float *S)
{
std::cerr << "csrot not implemented" << std::endl;
ASSERT(0);
// FAKE USE
(void)N;
(void)X;
(void)INCX;
(void)Y;
(void)INCY;
(void)C;
(void)S;
}
void
BLAS(zdrot)(const INTEGER *N,
cdouble *X,
const INTEGER *INCX,
cdouble *Y,
const INTEGER *INCY,
const double *C,
const double *S)
{
std::cerr << "zdrot not implemented" << std::endl;
ASSERT(0);
// FAKE USE
(void)N;
(void)X;
(void)INCX;
(void)Y;
(void)INCY;
(void)C;
(void)S;
}
} // extern "C"
| 20.47482 | 68 | 0.471188 | stip |
2ea2226d328d4098b2aa6ca50bde3a070926d8ff | 2,515 | cc | C++ | src/server.cc | SiLeader/eidos | 5ec2b19c79f45d25936fae799f59ef7cf35f4580 | [
"Apache-2.0"
] | 2 | 2022-01-24T07:05:16.000Z | 2022-02-08T07:14:53.000Z | src/server.cc | SiLeader/eidos | 5ec2b19c79f45d25936fae799f59ef7cf35f4580 | [
"Apache-2.0"
] | null | null | null | src/server.cc | SiLeader/eidos | 5ec2b19c79f45d25936fae799f59ef7cf35f4580 | [
"Apache-2.0"
] | null | null | null | // Copyright 2021 SiLeader and Cerussite.
//
// 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 <boost/asio.hpp>
#include <boost/log/trivial.hpp>
#include <cstdint>
#include <string>
#include "context.hpp"
#include "request.hpp"
#include "storage/storage_base.hpp"
#include "tcp.hpp"
namespace {
/// request parameter read event handler
/// \param engine storage engine
/// \param context request context
/// \param params parameters
void OnParamsRead(const std::shared_ptr<eidos::storage::StorageEngineBase>& engine,
std::shared_ptr<eidos::RequestContext> context, const std::vector<std::vector<std::byte>>& params) {
auto res = context->response();
auto cmd = eidos::BytesToString(params.front());
// command name convert to uppercase
std::transform(std::begin(cmd), std::end(cmd), std::begin(cmd), ::toupper);
// repack command arguments
std::vector<std::vector<std::byte>> args(std::begin(params) + 1, std::end(params));
// call on request handler
eidos::OnRequest(engine, res, cmd, args, [context = std::move(context), engine](bool) {
// start to read next command
context->read([context, engine](const std::vector<std::vector<std::byte>>& params) {
OnParamsRead(engine, context, params);
});
});
}
} // namespace
namespace eidos {
void Serve(boost::asio::io_context& ioc, std::uint16_t port,
std::shared_ptr<eidos::storage::StorageEngineBase> engine) {
auto server =
std::make_shared<net::tcp::Server>(ioc, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port));
server->listen([server, engine = std::move(engine)](const std::shared_ptr<net::tcp::Socket>& socket) {
auto context = std::make_shared<RequestContext>(socket);
const auto callback = [context, engine](const std::vector<std::vector<std::byte>>& params) {
OnParamsRead(engine, context, params);
};
context->read(callback);
});
BOOST_LOG_TRIVIAL(info) << "listening on 0.0.0.0:" << port;
}
} // namespace eidos
| 35.422535 | 118 | 0.694632 | SiLeader |
2ea49c6074e1ff6cd59e672d45e6aac514b86928 | 397 | cpp | C++ | Leetcode0887.cpp | dezhonger/LeetCode | 70de054be5af3a0749dce0625fefd75e176e59f4 | [
"Apache-2.0"
] | 1 | 2020-06-28T06:29:05.000Z | 2020-06-28T06:29:05.000Z | Leetcode0887.cpp | dezhonger/LeetCode | 70de054be5af3a0749dce0625fefd75e176e59f4 | [
"Apache-2.0"
] | null | null | null | Leetcode0887.cpp | dezhonger/LeetCode | 70de054be5af3a0749dce0625fefd75e176e59f4 | [
"Apache-2.0"
] | null | null | null | int f[101][10001];
class Solution {
public:
int superEggDrop(int k, int n) {
//i个鸡蛋扔j次能确定的最大楼层
//f[i][j] = f[i - 1][j - 1] + 1 + f[i - 1][j];
for (int j = 1; j <= n; j++) {
for (int i = 1; i <= k; i++) {
f[i][j] = f[i - 1][j - 1] + 1 + f[i][j - 1];
}
if (f[k][j] >= n) return j;
}
return -1;
}
};
| 24.8125 | 60 | 0.345088 | dezhonger |
2eb5c8a863d254852370df75945d49cfa4631c3e | 42,923 | hpp | C++ | CmnCS/module/computationalgeometry2/inc/computationalgeometry2/MinimumVolumeBox3.hpp | Khoronus/CmnUniverse | 9cf9b4297f2fcb49330126aa1047b422144045e1 | [
"MIT"
] | null | null | null | CmnCS/module/computationalgeometry2/inc/computationalgeometry2/MinimumVolumeBox3.hpp | Khoronus/CmnUniverse | 9cf9b4297f2fcb49330126aa1047b422144045e1 | [
"MIT"
] | null | null | null | CmnCS/module/computationalgeometry2/inc/computationalgeometry2/MinimumVolumeBox3.hpp | Khoronus/CmnUniverse | 9cf9b4297f2fcb49330126aa1047b422144045e1 | [
"MIT"
] | null | null | null | // Geometric Tools LLC, Redmond WA 98052
// Copyright (c) 1998-2015
// Distributed under the Boost Software License, Version 1.0.
// http://www.boost.org/LICENSE_1_0.txt
// http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
// File Version: 1.0.10 (2015/03/10)
#pragma once
#include "GteOrientedBox.h"
#include "GteConvexHull3.h"
#include "GteMinimumAreaBox2.h"
#include "GteEdgeKey.h"
#include <thread>
#include <type_traits>
// Compute a minimum-volume oriented box containing the specified points. The
// algorithm is really about computing the minimum-volume box containing the
// convex hull of the points, so we must compute the convex hull or you must
// pass an already built hull to the code.
//
// The minimum-volume oriented box has a face coincident with a hull face
// or has three mutually orthogonal edges coincident with three hull edges
// that (of course) are mutually orthogonal.
// J.O'Rourke, "Finding minimal enclosing boxes",
// Internat. J. Comput. Inform. Sci., 14:183-199, 1985.
//
// NOTE: This algorithm guarantees a correct output only when ComputeType is
// an exact arithmetic type that supports division. In GTEngine, one such
// type is BSRational<UIntegerAP32> (arbitrary precision). Another such type
// is BSRational<UIntegerFP32<N>> (fixed precision), where N is chosen large
// enough for your input data sets. If you choose ComputeType to be 'float'
// or 'double', the output is not guaranteed to be correct.
//
// See GeometricTools/GTEngine/Samples/Geometrics/MinimumVolumeBox3 for an
// example of how to use the code.
namespace gte
{
template <typename InputType, typename ComputeType>
class MinimumVolumeBox3
{
public:
// The class is a functor to support computing the minimum-volume box of
// multiple data sets using the same class object. For multithreading
// in ProcessFaces, choose 'numThreads' subject to the constraints
// 1 <= numThreads <= std::thread::hardware_concurrency()
MinimumVolumeBox3(unsigned int numThreads = 1);
// The points are arbitrary, so we must compute the convex hull from
// them in order to compute the minimum-area box. The input parameters
// are necessary for using ConvexHull3.
OrientedBox3<InputType> operator()(int numPoints,
Vector3<InputType> const* points,
bool useRotatingCalipers =
!std::is_floating_point<ComputeType>::value);
// The points form a nondegenerate convex polyhedron. The indices input
// must be nonnull and specify the triangle faces.
OrientedBox3<InputType> operator()(int numPoints,
Vector3<InputType> const* points, int numIndices, int const* indices,
bool useRotatingCalipers =
!std::is_floating_point<ComputeType>::value);
// Member access.
inline int GetNumPoints() const;
inline Vector3<InputType> const* GetPoints() const;
inline std::vector<int> const& GetHull() const;
private:
struct Box
{
Vector3<ComputeType> P, U[3];
ComputeType sqrLenU[3], range[3][2], volume;
};
enum { EXT_B, EXT_R, EXT_T, EXT_L };
struct ExtrudeRectangle
{
Vector3<ComputeType> U[2];
std::array<int, 4> index;
ComputeType area;
};
// Compute the minimum-volume box relative to each hull face.
void ProcessFaces(ETManifoldMesh const& mesh);
// Compute the minimum-volume box for each triple of orthgonal hull edges.
void ProcessEdges(ETManifoldMesh const& mesh);
// Compute the minimum-volume box relative to a single hull face.
void ProcessFace(ETManifoldMesh::Triangle const* supportTri,
std::vector<Vector3<ComputeType>> const& normal,
std::map<ETManifoldMesh::Triangle const*, int> const& triNormalMap,
ETManifoldMesh::EMap const& emap, Box& localMinBox);
// The rotating calipers algorithm has a loop invariant that requires
// the convex polygon not to have collinear points. Any such points
// must be removed first. The code is also executed for the O(n^2)
// algorithm to reduce the number of process edges.
void RemoveCollinearPoints(Vector3<ComputeType> const& N,
std::vector<int>& polyline);
// This is the slow order O(n^2) search.
void ComputeBoxForFaceOrderNSqr(Vector3<ComputeType> const& N,
std::vector<int> const& polyline, Box& box);
// This is the rotating calipers version, which is O(n).
void ComputeBoxForFaceOrderN(Vector3<ComputeType> const& N,
std::vector<int> const& polyline, Box& box);
// Compute the new supporting box from the old supporting points in the
// rotating calipers algoriothm
void UpdateRectangle(int numPolyline, int const* polyline,
ExtrudeRectangle& rct);
// The rotating calipers algorithm requires computing a minimum angle
// formed by edges starting at supporting points of the current rectangle.
// We must compare Dot(D0/|D0|,E0/|E0|) > Dot(D1/|D1|,E1/|E1|) using exact
// arithmetic; thus, we may square each side and compare, but the signs of
// the dot products must be taken into account.
bool IsLarger(
Vector3<ComputeType> const& D0, Vector3<ComputeType> const& E0,
Vector3<ComputeType> const& D1, Vector3<ComputeType> const& E1);
// Convert the extruded box to the minimum-volume box of InputType. When
// the ComputeType is an exact rational type, the conversions are
// performed to avoid precision loss until necessary at the last step.
void ConvertTo(OrientedBox3<InputType>& itMinBox);
// The code is multithreaded, both for convex hull computation and
// computing minimum-volume extruded boxes for the hull faces. The
// default value is 1, which implies a single-threaded computation (on
// the main thread).
unsigned int mNumThreads;
// The input points to be bound.
int mNumPoints;
Vector3<InputType> const* mPoints;
// The ComputeType conversions of the input points. Only points of the
// convex hull (vertices of a convex polyhedron) are converted for
// performance when ComputeType is rational.
Vector3<ComputeType> const* mComputePoints;
// The indices into mPoints/mComputePoints for the convex hull vertices.
std::vector<int> mHull;
// The unique indices in mHull. This set allows us to compute only for
// the hull vertices and avoids redundant computations if the indices
// were to have repeated indices into mPoints/mComputePoints. This is
// a performance improvement for rational ComputeType.
std::set<int> mUniqueIndices;
// The caller can specify whether to use rotating calipers or the slower
// all-edge processing for computing an extruded bounding box.
bool mUseRotatingCalipers;
// Convenient values that occur regularly in the code. When using
// rational ComputeType, we construct these numbers only once.
ComputeType mZero, mOne, mNegOne, mHalf;
// The minimum-volume box computed internally using ComputeType
// arithmetic.
Box mMinBox;
};
//----------------------------------------------------------------------------
template <typename InputType, typename ComputeType>
MinimumVolumeBox3<InputType, ComputeType>::MinimumVolumeBox3(
unsigned int numThreads)
:
mNumThreads(numThreads),
mNumPoints(0),
mPoints(nullptr),
mComputePoints(nullptr),
mUseRotatingCalipers(true),
mZero(0),
mOne(1),
mNegOne(-1),
mHalf((InputType)0.5)
{
}
//----------------------------------------------------------------------------
template <typename InputType, typename ComputeType>
OrientedBox3<InputType> MinimumVolumeBox3<InputType, ComputeType>::operator()(
int numPoints, Vector3<InputType> const* points, bool useRotatingCalipers)
{
mNumPoints = numPoints;
mPoints = points;
mUseRotatingCalipers = useRotatingCalipers;
mHull.clear();
mUniqueIndices.clear();
// Get the convex hull of the points.
ConvexHull3<InputType, ComputeType> ch3;
ch3(mNumPoints, mPoints, (InputType)0);
int dimension = ch3.GetDimension();
OrientedBox3<InputType> itMinBox;
if (dimension == 0)
{
// The points are all effectively the same (using fuzzy epsilon).
itMinBox.center = mPoints[0];
itMinBox.axis[0] = Vector3<InputType>::Unit(0);
itMinBox.axis[1] = Vector3<InputType>::Unit(1);
itMinBox.axis[2] = Vector3<InputType>::Unit(2);
itMinBox.extent[0] = (InputType)0;
itMinBox.extent[1] = (InputType)0;
itMinBox.extent[2] = (InputType)0;
mHull.resize(1);
mHull[0] = 0;
return itMinBox;
}
if (dimension == 1)
{
// The points effectively lie on a line (using fuzzy epsilon).
// Determine the extreme t-values for the points represented as
// P = origin + t*direction. We know that 'origin' is an input
// vertex, so we can start both t-extremes at zero.
Line3<InputType> const& line = ch3.GetLine();
InputType tmin = (InputType)0, tmax = (InputType)0;
int imin = 0, imax = 0;
for (int i = 0; i < mNumPoints; ++i)
{
Vector3<InputType> diff = mPoints[i] - line.origin;
InputType t = Dot(diff, line.direction);
if (t > tmax)
{
tmax = t;
imax = i;
}
else if (t < tmin)
{
tmin = t;
imin = i;
}
}
itMinBox.center = line.origin +
((InputType)0.5)*(tmin + tmax) * line.direction;
itMinBox.extent[0] = ((InputType)0.5)*(tmax - tmin);
itMinBox.extent[1] = (InputType)0;
itMinBox.extent[2] = (InputType)0;
itMinBox.axis[0] = line.direction;
ComputeOrthogonalComplement(1, &itMinBox.axis[0]);
mHull.resize(2);
mHull[0] = imin;
mHull[1] = imax;
return itMinBox;
}
if (dimension == 2)
{
// The points effectively line on a plane (using fuzzy epsilon).
// Project the points onto the plane and compute the minimum-area
// bounding box of them.
Plane3<InputType> const& plane = ch3.GetPlane();
// Get a coordinate system relative to the plane of the points.
// Choose the origin to be any of the input points.
Vector3<InputType> origin = mPoints[0];
Vector3<InputType> basis[3];
basis[0] = plane.normal;
ComputeOrthogonalComplement(1, basis);
// Project the input points onto the plane.
std::vector<Vector2<InputType>> projection(mNumPoints);
for (int i = 0; i < mNumPoints; ++i)
{
Vector3<InputType> diff = mPoints[i] - origin;
projection[i][0] = Dot(basis[1], diff);
projection[i][1] = Dot(basis[2], diff);
}
// Compute the minimum area box in 2D.
MinimumAreaBox2<InputType, ComputeType> mab2;
OrientedBox2<InputType> rectangle = mab2(mNumPoints, &projection[0]);
// Lift the values into 3D.
itMinBox.center = origin + rectangle.center[0] * basis[1] +
rectangle.center[1] * basis[2];
itMinBox.axis[0] = rectangle.axis[0][0] * basis[1] +
rectangle.axis[0][1] * basis[2];
itMinBox.axis[1] = rectangle.axis[1][0] * basis[1] +
rectangle.axis[1][1] * basis[2];
itMinBox.axis[2] = basis[0];
itMinBox.extent[0] = rectangle.extent[0];
itMinBox.extent[1] = rectangle.extent[1];
itMinBox.extent[2] = (InputType)0;
mHull = mab2.GetHull();
return itMinBox;
}
// Get the set of unique indices of the hull. This is used to project
// hull vertices onto lines.
ETManifoldMesh const& mesh = ch3.GetHullMesh();
mHull.resize(3 * mesh.GetTriangles().size());
int h = 0;
for (auto const& element : mesh.GetTriangles())
{
for (int i = 0; i < 3; ++i, ++h)
{
int index = element.first.V[i];
mHull[h] = index;
mUniqueIndices.insert(index);
}
}
mComputePoints = ch3.GetQuery().GetVertices();
mMinBox.volume = mNegOne;
ProcessFaces(mesh);
ProcessEdges(mesh);
ConvertTo(itMinBox);
mComputePoints = nullptr;
return itMinBox;
}
//----------------------------------------------------------------------------
template <typename InputType, typename ComputeType>
OrientedBox3<InputType> MinimumVolumeBox3<InputType, ComputeType>::operator()(
int numPoints, Vector3<InputType> const* points, int numIndices,
int const* indices, bool useRotatingCalipers)
{
mNumPoints = numPoints;
mPoints = points;
mUseRotatingCalipers = useRotatingCalipers;
mUniqueIndices.clear();
// Build the mesh from the indices. The box construction uses the edge
// map of the mesh.
ETManifoldMesh mesh;
int numTriangles = numIndices / 3;
for (int t = 0; t < numTriangles; ++t)
{
int v0 = *indices++;
int v1 = *indices++;
int v2 = *indices++;
mesh.Insert(v0, v1, v2);
}
// Get the set of unique indices of the hull. This is used to project
// hull vertices onto lines.
mHull.resize(3 * mesh.GetTriangles().size());
int h = 0;
for (auto const& element : mesh.GetTriangles())
{
for (int i = 0; i < 3; ++i, ++h)
{
int index = element.first.V[i];
mHull[h] = index;
mUniqueIndices.insert(index);
}
}
// Create the ComputeType points to be used downstream.
std::vector<Vector3<ComputeType>> computePoints(mNumPoints);
for (auto i : mUniqueIndices)
{
for (int j = 0; j < 3; ++j)
{
computePoints[i][j] = (ComputeType)mPoints[i][j];
}
}
OrientedBox3<InputType> itMinBox;
mComputePoints = &computePoints[0];
mMinBox.volume = mNegOne;
ProcessFaces(mesh);
ProcessEdges(mesh);
ConvertTo(itMinBox);
mComputePoints = nullptr;
return itMinBox;
}
//----------------------------------------------------------------------------
template <typename InputType, typename ComputeType> inline
int MinimumVolumeBox3<InputType, ComputeType>::GetNumPoints() const
{
return mNumPoints;
}
//----------------------------------------------------------------------------
template <typename InputType, typename ComputeType> inline
Vector3<InputType> const*
MinimumVolumeBox3<InputType, ComputeType>::GetPoints() const
{
return mPoints;
}
//----------------------------------------------------------------------------
template <typename InputType, typename ComputeType> inline
std::vector<int> const& MinimumVolumeBox3<InputType, ComputeType>::GetHull()
const
{
return mHull;
}
//----------------------------------------------------------------------------
template <typename InputType, typename ComputeType>
void MinimumVolumeBox3<InputType, ComputeType>::ProcessFaces(
ETManifoldMesh const& mesh)
{
// Get the mesh data structures.
auto const& tmap = mesh.GetTriangles();
auto const& emap = mesh.GetEdges();
// Compute inner-pointing face normals for searching boxes supported by
// a face and an extreme vertex. The indirection in triNormalMap, using
// an integer index instead of the normal/sqrlength pair itself, avoids
// expensive copies when using exact arithmetic.
std::vector<Vector3<ComputeType>> normal(tmap.size());
std::map<ETManifoldMesh::Triangle const*, int> triNormalMap;
int index = 0;
for (auto const& element : tmap)
{
auto const* tri = element.second;
Vector3<ComputeType> const& v0 = mComputePoints[tri->V[0]];
Vector3<ComputeType> const& v1 = mComputePoints[tri->V[1]];
Vector3<ComputeType> const& v2 = mComputePoints[tri->V[2]];
Vector3<ComputeType> edge1 = v1 - v0;
Vector3<ComputeType> edge2 = v2 - v0;
normal[index] = Cross(edge2, edge1); // inner-pointing normal
triNormalMap[tri] = index++;
}
// Process the triangle faces. For each face, compute the polyline of
// edges that supports the bounding box with a face coincident to the
// triangle face. The projection of the polyline onto the plane of the
// triangle face is a convex polygon, so we can use the method of rotating
// calipers to compute its minimum-area box efficiently.
unsigned int numFaces = static_cast<unsigned int>(tmap.size());
if (mNumThreads > 1 && numFaces >= mNumThreads)
{
// Repackage the triangle pointers to support the partitioning of
// faces for multithreaded face processing.
std::vector<ETManifoldMesh::Triangle const*> triangles;
triangles.reserve(numFaces);
for (auto const& element : tmap)
{
triangles.push_back(element.second);
}
// Partition the data for multiple threads.
unsigned int numFacesPerThread = numFaces / mNumThreads;
std::vector<unsigned int> imin(mNumThreads), imax(mNumThreads);
std::vector<Box> localMinBox(mNumThreads);
for (unsigned int t = 0; t < mNumThreads; ++t)
{
imin[t] = t * numFacesPerThread;
imax[t] = imin[t] + numFacesPerThread - 1;
localMinBox[t].volume = mNegOne;
}
imax[mNumThreads - 1] = numFaces - 1;
// Execute the face processing in multiple threads.
std::vector<std::thread> process(mNumThreads);
for (unsigned int t = 0; t < mNumThreads; ++t)
{
process[t] = std::thread([this, t, &imin, &imax, &triangles,
&normal, &triNormalMap, &emap, &localMinBox]()
{
for (unsigned int i = imin[t]; i <= imax[t]; ++i)
{
auto const* supportTri = triangles[i];
ProcessFace(supportTri, normal, triNormalMap, emap,
localMinBox[t]);
}
});
}
// Wait for all threads to finish.
for (unsigned int t = 0; t < mNumThreads; ++t)
{
process[t].join();
// Update the minimum-volume box candidate.
if (mMinBox.volume == mNegOne
|| localMinBox[t].volume < mMinBox.volume)
{
mMinBox = localMinBox[t];
}
}
}
else
{
for (auto const& element : tmap)
{
auto const* supportTri = element.second;
ProcessFace(supportTri, normal, triNormalMap, emap, mMinBox);
}
}
}
//----------------------------------------------------------------------------
template <typename InputType, typename ComputeType>
void MinimumVolumeBox3<InputType, ComputeType>::ProcessEdges(
ETManifoldMesh const& mesh)
{
// The minimum-volume box can also be supported by three mutually
// orthogonal edges of the convex hull. For each triple of orthogonal
// edges, compute the minimum-volume box for that coordinate frame by
// projecting the points onto the axes of the frame. Use a hull vertex
// as the origin.
int index = mesh.GetTriangles().begin()->first.V[0];
Vector3<ComputeType> const& origin = mComputePoints[index];
Vector3<ComputeType> U[3];
std::array<ComputeType, 3> sqrLenU;
auto const& emap = mesh.GetEdges();
auto e2 = emap.begin(), end = emap.end();
for (/**/; e2 != end; ++e2)
{
U[2] =
mComputePoints[e2->first.V[1]] -
mComputePoints[e2->first.V[0]];
auto e1 = e2;
for (++e1; e1 != end; ++e1)
{
U[1] =
mComputePoints[e1->first.V[1]] -
mComputePoints[e1->first.V[0]];
if (Dot(U[1], U[2]) != mZero)
{
continue;
}
sqrLenU[1] = Dot(U[1], U[1]);
auto e0 = e1;
for (++e0; e0 != end; ++e0)
{
U[0] =
mComputePoints[e0->first.V[1]] -
mComputePoints[e0->first.V[0]];
sqrLenU[0] = Dot(U[0], U[0]);
if (Dot(U[0], U[1]) != mZero || Dot(U[0], U[2]) != mZero)
{
continue;
}
// The three edges are mutually orthogonal. To support exact
// rational arithmetic for volume computation, we replace U[2]
// by a parallel vector.
U[2] = Cross(U[0], U[1]);
sqrLenU[2] = sqrLenU[0] * sqrLenU[1];
// Project the vertices onto the lines containing the edges.
// Use vertex 0 as the origin.
std::array<ComputeType, 3> umin, umax;
for (int j = 0; j < 3; ++j)
{
umin[j] = mZero;
umax[j] = mZero;
}
for (auto i : mUniqueIndices)
{
Vector3<ComputeType> diff = mComputePoints[i] - origin;
for (int j = 0; j < 3; ++j)
{
ComputeType dot = Dot(diff, U[j]);
if (dot < umin[j])
{
umin[j] = dot;
}
else if (dot > umax[j])
{
umax[j] = dot;
}
}
}
ComputeType volume = (umax[0] - umin[0]) / sqrLenU[0];
volume *= (umax[1] - umin[1]) / sqrLenU[1];
volume *= (umax[2] - umin[2]);
// Update current minimum-volume box (if necessary).
if (volume < mMinBox.volume)
{
// The edge keys have unordered vertices, so it is
// possible that {U[0],U[1],U[2]} is a left-handed set.
// We need a right-handed set.
if (DotCross(U[0], U[1], U[2]) < mZero)
{
U[2] = -U[2];
}
mMinBox.P = origin;
for (int j = 0; j < 3; ++j)
{
mMinBox.U[j] = U[j];
mMinBox.sqrLenU[j] = sqrLenU[j];
for (int k = 0; k < 3; ++k)
{
mMinBox.range[k][0] = umin[k];
mMinBox.range[k][1] = umax[k];
}
}
mMinBox.volume = volume;
}
}
}
}
}
//----------------------------------------------------------------------------
template <typename InputType, typename ComputeType>
void MinimumVolumeBox3<InputType, ComputeType>::ProcessFace(
ETManifoldMesh::Triangle const* supportTri,
std::vector<Vector3<ComputeType>> const& normal,
std::map<ETManifoldMesh::Triangle const*, int> const& triNormalMap,
ETManifoldMesh::EMap const& emap, Box& localMinBox)
{
// Get the supporting triangle information.
Vector3<ComputeType> const& supportNormal =
normal[triNormalMap.find(supportTri)->second];
// Build the polyline of supporting edges. The pair (v,polyline[v])
// represents an edge directed appropriately (see next set of
// comments).
std::vector<int> polyline(mNumPoints);
int polylineStart = -1;
for (auto const& edgeElement : emap)
{
auto const& edge = *edgeElement.second;
auto const* tri0 = edge.T[0];
auto const* tri1 = edge.T[1];
auto const& normal0 = normal[triNormalMap.find(tri0)->second];
auto const& normal1 = normal[triNormalMap.find(tri1)->second];
ComputeType dot0 = Dot(supportNormal, normal0);
ComputeType dot1 = Dot(supportNormal, normal1);
ETManifoldMesh::Triangle const* tri = nullptr;
if (dot0 < mZero && dot1 >= mZero)
{
tri = tri0;
}
else if (dot1 < mZero && dot0 >= mZero)
{
tri = tri1;
}
if (tri)
{
// The edge supports the bounding box. Insert the edge in the
// list using clockwise order relative to tri. This will lead
// to a polyline whose projection onto the plane of the hull
// face is a convex polygon that is counterclockwise oriented.
for (int j0 = 2, j1 = 0; j1 < 3; j0 = j1++)
{
if (tri->V[j1] == edge.V[0])
{
if (tri->V[j0] == edge.V[1])
{
polyline[edge.V[1]] = edge.V[0];
}
else
{
polyline[edge.V[0]] = edge.V[1];
}
polylineStart = edge.V[0];
break;
}
}
}
}
// Rearrange the edges to form a closed polyline. For M vertices, each
// ComputeBoxFor*() function starts with the edge from closedPolyline[M-1]
// to closedPolyline[0].
std::vector<int> closedPolyline(mNumPoints);
int numClosedPolyline = 0;
int v = polylineStart;
for (auto& cp : closedPolyline)
{
cp = v;
++numClosedPolyline;
v = polyline[v];
if (v == polylineStart)
{
break;
}
}
closedPolyline.resize(numClosedPolyline);
// This avoids redundant face testing in the O(n^2) or O(n) algorithms
// and it simplifies the O(n) implementation.
RemoveCollinearPoints(supportNormal, closedPolyline);
// Compute the box coincident to the hull triangle that has minimum
// area on the face coincident with the triangle.
Box faceBox;
if (mUseRotatingCalipers)
{
ComputeBoxForFaceOrderN(supportNormal, closedPolyline, faceBox);
}
else
{
ComputeBoxForFaceOrderNSqr(supportNormal, closedPolyline, faceBox);
}
// Update the minimum-volume box candidate.
if (localMinBox.volume == mNegOne || faceBox.volume < localMinBox.volume)
{
localMinBox = faceBox;
}
}
//----------------------------------------------------------------------------
template <typename InputType, typename ComputeType>
void MinimumVolumeBox3<InputType, ComputeType>::RemoveCollinearPoints(
Vector3<ComputeType> const& N, std::vector<int>& polyline)
{
std::vector<int> tmpPolyline = polyline;
int const numPolyline = static_cast<int>(polyline.size());
int numNoncollinear = 0;
Vector3<ComputeType> ePrev =
mComputePoints[tmpPolyline[0]] - mComputePoints[tmpPolyline.back()];
for (int i0 = 0, i1 = 1; i0 < numPolyline; ++i0)
{
Vector3<ComputeType> eNext =
mComputePoints[tmpPolyline[i1]] - mComputePoints[tmpPolyline[i0]];
ComputeType tsp = DotCross(ePrev, eNext, N);
if (tsp != mZero)
{
polyline[numNoncollinear++] = tmpPolyline[i0];
}
ePrev = eNext;
if (++i1 == numPolyline)
{
i1 = 0;
}
}
polyline.resize(numNoncollinear);
}
//----------------------------------------------------------------------------
template <typename InputType, typename ComputeType>
void MinimumVolumeBox3<InputType, ComputeType>::ComputeBoxForFaceOrderNSqr(
Vector3<ComputeType> const& N, std::vector<int> const& polyline,
Box& box)
{
// This code processes the polyline terminator associated with a convex
// hull face of inner-pointing normal N. The polyline is usually not
// contained by a plane, and projecting the polyline to a convex polygon
// in a plane perpendicular to N introduces floating-point rounding
// errors. The minimum-area box for the projected polyline is computed
// indirectly to support exact rational arithmetic.
box.P = mComputePoints[polyline[0]];
box.U[2] = N;
box.sqrLenU[2] = Dot(N, N);
box.range[1][0] = mZero;
box.volume = mNegOne;
int const numPolyline = static_cast<int>(polyline.size());
for (int i0 = numPolyline - 1, i1 = 0; i1 < numPolyline; i0 = i1++)
{
// Create a coordinate system for the plane perpendicular to the face
// normal and containing a polyline vertex.
Vector3<ComputeType> const& P = mComputePoints[polyline[i0]];
Vector3<ComputeType> E =
mComputePoints[polyline[i1]] - mComputePoints[polyline[i0]];
Vector3<ComputeType> U1 = Cross(N, E);
Vector3<ComputeType> U0 = Cross(U1, N);
// Compute the smallest rectangle containing the projected polyline.
ComputeType min0 = mZero, max0 = mZero, max1 = mZero;
for (int j = 0; j < numPolyline; ++j)
{
Vector3<ComputeType> diff = mComputePoints[polyline[j]] - P;
ComputeType dot = Dot(U0, diff);
if (dot < min0)
{
min0 = dot;
}
else if (dot > max0)
{
max0 = dot;
}
dot = Dot(U1, diff);
if (dot > max1)
{
max1 = dot;
}
}
// The true area is Area(rectangle)*Length(N). After the smallest
// scaled-area rectangle is computed and returned, the box.volume is
// updated to be the actual squared volume of the box.
ComputeType sqrLenU1 = Dot(U1, U1);
ComputeType volume = (max0 - min0) * max1 / sqrLenU1;
if (box.volume == mNegOne || volume < box.volume)
{
box.P = P;
box.U[0] = U0;
box.U[1] = U1;
box.sqrLenU[0] = sqrLenU1 * box.sqrLenU[2];
box.sqrLenU[1] = sqrLenU1;
box.range[0][0] = min0;
box.range[0][1] = max0;
box.range[1][1] = max1;
box.volume = volume;
}
}
// Compute the range of points in the support-normal direction.
box.range[2][0] = mZero;
box.range[2][1] = mZero;
for (auto i : mUniqueIndices)
{
Vector3<ComputeType> diff = mComputePoints[i] - box.P;
ComputeType height = Dot(box.U[2], diff);
if (height < box.range[2][0])
{
box.range[2][0] = height;
}
else if (height > box.range[2][1])
{
box.range[2][1] = height;
}
}
// Compute the actual volume.
box.volume *= (box.range[2][1] - box.range[2][0]) / box.sqrLenU[2];
}
//----------------------------------------------------------------------------
template <typename InputType, typename ComputeType>
void MinimumVolumeBox3<InputType, ComputeType>::ComputeBoxForFaceOrderN(
Vector3<ComputeType> const& N, std::vector<int> const& polyline, Box& box)
{
// This code processes the polyline terminator associated with a convex
// hull face of inner-pointing normal N. The polyline is usually not
// contained by a plane, and projecting the polyline to a convex polygon
// in a plane perpendicular to N introduces floating-point rounding
// errors. The minimum-area box for the projected polyline is computed
// indirectly to support exact rational arithmetic.
// When the bounding box corresponding to a polyline edge is computed,
// we mark the edge as visited. If the edge is encountered later, the
// algorithm terminates.
int const numPolyline = static_cast<int>(polyline.size());
std::vector<bool> visited(numPolyline);
std::fill(visited.begin(), visited.end(), false);
// Start the minimum-area rectangle search with the edge from the last
// polyline vertex to the first. When updating the extremes, we want the
// bottom-most point on the left edge, the top-most point on the right
// edge, the left-most point on the top edge, and the right-most point
// on the bottom edge. The polygon edges starting at these points are
// then guaranteed not to coincide with a box edge except when an extreme
// point is shared by two box edges (at a corner).
ExtrudeRectangle minRct;
Vector3<ComputeType> E = mComputePoints[polyline[0]] -
mComputePoints[polyline[numPolyline - 1]];
minRct.U[1] = Cross(N, E);
minRct.U[0] = Cross(minRct.U[1], N);
UpdateRectangle(numPolyline, &polyline[0], minRct);
visited[minRct.index[EXT_B]] = true;
// Execute the rotating calipers algorithm.
ExtrudeRectangle rct = minRct;
for (;;)
{
// Determine the edge that forms the minimum angle with the current
// box edges. To support exact arithmetic in the algorithm, the box
// axes are not usually the same length. The dot product between
// consecutive edges cannot be computed with exact arithmetic, but
// a comparison between two dot products can be; see IsLarger(). This
// allows us to determine the maximum dot product (minimum angle)
// using exact arithmetic. The initial choice for Emax causes the
// first IsLarger(...) call to return true, so the bottom edge becomes
// the first candidate for minimum-angle edge.
int extreme = -1;
Vector3<ComputeType> Dmax = rct.U[0];
Vector3<ComputeType> Emax = -Dmax, Emaxperp{ mZero, mZero, mZero };
for (int i = 0; i < 4; ++i)
{
int k0 = rct.index[i], k1 = k0 + 1;
if (k1 == numPolyline)
{
k1 = 0;
}
// The box edges are ordered in i as U[0], U[1], -U[0], -U[1].
Vector3<ComputeType> D = ((i & 2) ? -rct.U[i & 1] : rct.U[i & 1]);
Vector3<ComputeType> E =
mComputePoints[polyline[k1]] - mComputePoints[polyline[k0]];
Vector3<ComputeType> Eperp = Cross(N, E);
E = Cross(Eperp, N);
if (IsLarger(D, E, Dmax, Emax))
{
Dmax = D;
Emax = E;
Emaxperp = Eperp;
extreme = i;
}
}
if (extreme == -1)
{
// The projected polyline is a rectangle, so the search is over.
break;
}
// Rotate the calipers and compute the bounding box.
rct.U[0] = Emax;
rct.U[1] = Emaxperp;
// The right endpoint of the edge forming smallest angle with its
// box edge becomes the new "bottom" extreme for the next pass.
int bottom = rct.index[extreme] + 1;
if (bottom == numPolyline)
{
bottom = 0;
}
if (visited[bottom])
{
// We have already processed this polyline edge, so the search
// is over.
break;
}
visited[bottom] = true;
// We need to update only a subset of the polyline. To share the code
// for UpdateRectangle, we need a level of indirection to recapture
// rct.index[] in {0..numPolyline-1}. The new bottom point is used to
// initialize several quantities in UpdateRectangle. The four old
// support points are included because a subset must support the new
// rectangle. However, if two or more support points have a 'next'
// edge that ties the minimum angle, we need to select the endpoint
// of that next edge as the new support point. Thus, we have a total
// of nine points to process.
std::array<int, 9> indexIndirect, supportPolyline;
indexIndirect[0] = bottom;
supportPolyline[0] = polyline[bottom];
for (int i = 0, j = 1; i < 4; ++i)
{
indexIndirect[j] = rct.index[i];
supportPolyline[j] = polyline[indexIndirect[j]];
++j;
indexIndirect[j] = rct.index[i] + 1;
if (indexIndirect[j] == numPolyline)
{
indexIndirect[j] = 0;
}
supportPolyline[j] = polyline[indexIndirect[j]];
++j;
}
UpdateRectangle(9, &supportPolyline[0], rct); // rct.index[] in {0..4}
rct.index[EXT_B] = bottom;
for (int i = 1; i < 4; ++i)
{
rct.index[i] = indexIndirect[rct.index[i]];
// rct.index[i] in {0..numPolyline-1}
}
if (rct.area < minRct.area)
{
minRct = rct;
}
}
// Store relevant box information for computing volume and converting to
// an InputType bounding box.
box.P = mComputePoints[polyline[minRct.index[EXT_B]]];
box.U[0] = minRct.U[0];
box.U[1] = minRct.U[1];
box.U[2] = N;
box.sqrLenU[0] = Dot(box.U[0], box.U[0]);
box.sqrLenU[1] = Dot(box.U[1], box.U[1]);
box.sqrLenU[2] = Dot(box.U[2], box.U[2]);
// Compute the range of points in the plane perpendicular to the support
// normal.
box.range[0][0] = Dot(box.U[0],
mComputePoints[polyline[minRct.index[EXT_L]]] - box.P);
box.range[0][1] = Dot(box.U[0],
mComputePoints[polyline[minRct.index[EXT_R]]] - box.P);
box.range[1][0] = mZero;
box.range[1][1] = Dot(box.U[1],
mComputePoints[polyline[minRct.index[EXT_T]]] - box.P);
// Compute the range of points in the support-normal direction.
box.range[2][0] = mZero;
box.range[2][1] = mZero;
for (auto i : mUniqueIndices)
{
Vector3<ComputeType> diff = mComputePoints[i] - box.P;
ComputeType height = Dot(box.U[2], diff);
if (height < box.range[2][0])
{
box.range[2][0] = height;
}
else if (height > box.range[2][1])
{
box.range[2][1] = height;
}
}
// Compute the actual volume.
box.volume =
(box.range[0][1] - box.range[0][0]) *
((box.range[1][1] - box.range[1][0]) / box.sqrLenU[1]) *
((box.range[2][1] - box.range[2][0]) / box.sqrLenU[2]);
}
//----------------------------------------------------------------------------
template <typename InputType, typename ComputeType>
void MinimumVolumeBox3<InputType, ComputeType>::UpdateRectangle(
int numPolyline, int const* polyline, ExtrudeRectangle& rct)
{
Vector3<ComputeType> const& origin = mComputePoints[polyline[0]];
rct.index = { 0, 0, 0, 0 };
Vector2<ComputeType> support[4];
support[EXT_B] = { mZero, mZero };
support[EXT_R] = { mZero, mZero };
support[EXT_T] = { mZero, mZero };
support[EXT_L] = { mZero, mZero };
for (int i = 0; i < numPolyline; ++i)
{
Vector3<ComputeType> diff = mComputePoints[polyline[i]] - origin;
Vector2<ComputeType> v = { Dot(rct.U[0], diff), Dot(rct.U[1], diff) };
if (v[1] < support[EXT_B][1] ||
(v[1] == support[EXT_B][1] && v[0] > support[EXT_B][0]))
{
// New bottom minimum OR same bottom minimum but closer to right.
rct.index[EXT_B] = i;
support[EXT_B] = v;
}
if (v[0] > support[EXT_R][0] ||
(v[0] == support[EXT_R][0] && v[1] > support[EXT_R][1]))
{
// New right maximum OR same right maximum but closer to top.
rct.index[EXT_R] = i;
support[EXT_R] = v;
}
if (v[1] > support[EXT_T][1] ||
(v[1] == support[EXT_T][1] && v[0] < support[EXT_T][0]))
{
// New top maximum OR same top maximum but closer to left.
rct.index[EXT_T] = i;
support[EXT_T] = v;
}
if (v[0] < support[EXT_L][0] ||
(v[0] == support[EXT_L][0] && v[1] < support[EXT_L][1]))
{
// New left minimum OR same left minimum but closer to bottom.
rct.index[EXT_L] = i;
support[EXT_L] = v;
}
}
rct.area =
(support[EXT_R][0] - support[EXT_L][0]) *
(support[EXT_T][1] - support[EXT_B][1]) /
Dot(rct.U[1], rct.U[1]);
}
//----------------------------------------------------------------------------
template <typename InputType, typename ComputeType>
bool MinimumVolumeBox3<InputType, ComputeType>::IsLarger(
Vector3<ComputeType> const& D0, Vector3<ComputeType> const& E0,
Vector3<ComputeType> const& D1, Vector3<ComputeType> const& E1)
{
ComputeType d0e0 = Dot(D0, E0);
ComputeType d1e1 = Dot(D1, E1);
ComputeType d0d0, e0e0, d1d1, e1e1, tmp0, tmp1;
if (d0e0 > mZero)
{
if (d1e1 <= mZero)
{
return true;
}
d0d0 = Dot(D0, D0);
e0e0 = Dot(E0, E0);
d1d1 = Dot(D1, D1);
e1e1 = Dot(E1, E1);
tmp0 = (d0e0 / d0d0) * (d0e0 / e0e0);
tmp1 = (d1e1 / d1d1) * (d1e1 / e1e1);
return tmp0 > tmp1;
}
if (d0e0 < mZero)
{
if (d1e1 >= mZero)
{
return false;
}
d0d0 = Dot(D0, D0);
e0e0 = Dot(E0, E0);
d1d1 = Dot(D1, D1);
e1e1 = Dot(E1, E1);
tmp0 = (d0e0 / d0d0) * (d0e0 / e0e0);
tmp1 = (d1e1 / d1d1) * (d1e1 / e1e1);
return tmp0 < tmp1;
}
return d1e1 < mZero;
}
//----------------------------------------------------------------------------
template <typename InputType, typename ComputeType>
void MinimumVolumeBox3<InputType, ComputeType>::ConvertTo(
OrientedBox3<InputType>& itMinBox)
{
Vector3<ComputeType> center = mMinBox.P;
for (int i = 0; i < 3; ++i)
{
ComputeType average =
mHalf * (mMinBox.range[i][0] + mMinBox.range[i][1]);
center += (average / mMinBox.sqrLenU[i]) * mMinBox.U[i];
}
for (int i = 0; i < 3; ++i)
{
itMinBox.center[i] = (InputType)center[i];
// Calculate the squared extent using ComputeType to avoid loss of
// precision before computing a squared root.
ComputeType sqrExtent =
mHalf * (mMinBox.range[i][1] - mMinBox.range[i][0]);
sqrExtent *= sqrExtent;
sqrExtent /= mMinBox.sqrLenU[i];
itMinBox.extent[i] = sqrt((InputType)sqrExtent);
// Before converting to floating-point, factor out the maximum
// component using ComputeType to generate rational numbers in a
// range that avoids loss of precision during the conversion and
// normalization.
Vector3<ComputeType> const& axis = mMinBox.U[i];
ComputeType cmax = std::max(std::abs(axis[0]), std::abs(axis[1]));
cmax = std::max(cmax, std::abs(axis[2]));
ComputeType invCMax = mOne / cmax;
for (int j = 0; j < 3; ++j)
{
itMinBox.axis[i][j] = (InputType)(axis[j] * invCMax);
}
Normalize(itMinBox.axis[i]);
}
}
//----------------------------------------------------------------------------
} // namespace computationalgeometry
} // namespace CmnMath
#endif /* CMNMATH_GEOMETRICPRIMITIVE_LINE2D_HPP__ */ | 37.066494 | 78 | 0.569578 | Khoronus |
2eb70835727b7adf472d827a3451e5970c096e81 | 2,090 | cpp | C++ | calibration/source/PECCalibration.cpp | pavlokleymonov/PEDeadReckoning | 0a8b60d90d02386d0d6a4ef8e0b0cd5fec012a20 | [
"BSD-2-Clause"
] | 2 | 2019-10-23T12:02:58.000Z | 2019-10-23T12:03:49.000Z | calibration/source/PECCalibration.cpp | pavlokleymonov/PEDeadReckoning | 0a8b60d90d02386d0d6a4ef8e0b0cd5fec012a20 | [
"BSD-2-Clause"
] | null | null | null | calibration/source/PECCalibration.cpp | pavlokleymonov/PEDeadReckoning | 0a8b60d90d02386d0d6a4ef8e0b0cd5fec012a20 | [
"BSD-2-Clause"
] | null | null | null | /**
* Position Engine provides dead reckoning engine to obtain position
* information based on fusion of different kind of sensors.
*
* Copyright 2017 Pavlo Kleymonov <pavlo.kleymonov@gmail.com>
*
* Distributed under the OSI-approved BSD License (the "License");
* see accompanying file LICENSE.txt for details.
*
* This software is distributed WITHOUT ANY WARRANTY; without even the
* implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the License for more information.
*/
#include "PECCalibration.h"
using namespace PE;
PE::CCalibration::CCalibration( CNormalisation* norm, TValue ratio, TValue threshold )
: mpNorm(norm)
, mRatio(ratio)
, mThreshold(threshold)
, mRefInstAcc(0.0)
, mRefInstCnt(0.0)
, mRawInstAcc(0.0)
, mRawInstCnt(0.0)
{
}
PE::CCalibration::~CCalibration()
{
}
void PE::CCalibration::AddReference(const SBasicSensor& ref)
{
if ( ref.IsValid() )
{
mRefInstAcc += ref.Value;
mRefInstCnt += 1.0;
DoCalibration();
}
}
void PE::CCalibration::AddSensor( const SBasicSensor& raw )
{
if ( raw.IsValid() )
{
mRawInstAcc += raw.Value;
mRawInstCnt += 1.0;
DoCalibration();
}
}
TValue PE::CCalibration::processValue(TValue& last, TValue& max, TValue& min, const TValue& value)
{
if ( MAX_VALUE == last )
{
max = value;
min = value;
}
else
{
if ( last < value )
{
max = value;
min = last;
}
else
{
max = last;
min = value;
}
}
last = value;
return (max - min);
}
void PE::CCalibration::clearInst()
{
mRefInstAcc = 0.0;
mRefInstCnt = 0.0;
mRawInstAcc = 0.0;
mRawInstCnt = 0.0;
}
bool PE::CCalibration::IsOverRatio()
{
if ( mRatio + mThreshold < mRawInstCnt / mRefInstCnt )
{
return true;
}
else if ( mRatio - mThreshold > mRawInstCnt / mRefInstCnt )
{
return true;
}
else
{
return false;
}
}
| 19 | 99 | 0.590431 | pavlokleymonov |
e483565e6180c0ebbf30c3798faaae258858e613 | 2,691 | cpp | C++ | src/OpenGL/entrypoints/GL3.0/gl_get_tex_parameter_i_iv.cpp | kbiElude/VKGL | fffabf412723a3612ba1c5bfeafe1da38062bd18 | [
"MIT"
] | 114 | 2018-08-05T16:26:53.000Z | 2021-12-30T07:28:35.000Z | src/OpenGL/entrypoints/GL3.0/gl_get_tex_parameter_i_iv.cpp | kbiElude/VKGL | fffabf412723a3612ba1c5bfeafe1da38062bd18 | [
"MIT"
] | 5 | 2018-08-18T21:16:58.000Z | 2018-11-22T21:50:48.000Z | src/OpenGL/entrypoints/GL3.0/gl_get_tex_parameter_i_iv.cpp | kbiElude/VKGL | fffabf412723a3612ba1c5bfeafe1da38062bd18 | [
"MIT"
] | 6 | 2018-08-05T22:32:28.000Z | 2021-10-04T15:39:53.000Z | /* VKGL (c) 2018 Dominik Witczak
*
* This code is licensed under MIT license (see LICENSE.txt for details)
*/
#include "OpenGL/entrypoints/GL3.0/gl_get_tex_parameter_i_iv.h"
#include "OpenGL/context.h"
#include "OpenGL/globals.h"
#include "OpenGL/utils_enum.h"
static bool validate(OpenGL::Context* in_context_ptr,
const GLenum& in_target,
const GLenum& in_pname,
GLint* out_params_ptr)
{
bool result = false;
// ..
result = true;
return result;
}
void VKGL_APIENTRY OpenGL::vkglGetTexParameterIiv(GLenum target,
GLenum pname,
GLint* params)
{
const auto& dispatch_table_ptr = OpenGL::g_dispatch_table_ptr;
VKGL_TRACE("glGetTexParameterIiv(target=[%s] pname=[%s] params=[%p])",
OpenGL::Utils::get_raw_string_for_gl_enum(target),
OpenGL::Utils::get_raw_string_for_gl_enum(pname),
params);
dispatch_table_ptr->pGLGetTexParameterIiv(dispatch_table_ptr->bound_context_ptr,
target,
pname,
params);
}
static void vkglGetTexParameterIiv_execute(OpenGL::Context* in_context_ptr,
const GLenum& in_target,
const GLenum& in_pname,
GLint* out_params_ptr)
{
const auto pname_vkgl = OpenGL::Utils::get_texture_property_for_gl_enum(in_pname);
const auto target_vkgl = OpenGL::Utils::get_texture_target_for_gl_enum (in_target);
in_context_ptr->get_texture_parameter(target_vkgl,
pname_vkgl,
OpenGL::GetSetArgumentType::Int,
out_params_ptr);
}
void OpenGL::vkglGetTexParameterIiv_with_validation(OpenGL::Context* in_context_ptr,
const GLenum& in_target,
const GLenum& in_pname,
GLint* out_params_ptr)
{
if (validate(in_context_ptr,
in_target,
in_pname,
out_params_ptr) )
{
vkglGetTexParameterIiv_execute(in_context_ptr,
in_target,
in_pname,
out_params_ptr);
}
}
| 38.442857 | 87 | 0.493497 | kbiElude |
e4838a972eefe8df7790cd9a6a495d8c754f3223 | 26,147 | hpp | C++ | library/ATF/CMainThread.hpp | lemkova/Yorozuya | f445d800078d9aba5de28f122cedfa03f26a38e4 | [
"MIT"
] | 29 | 2017-07-01T23:08:31.000Z | 2022-02-19T10:22:45.000Z | library/ATF/CMainThread.hpp | kotopes/Yorozuya | 605c97d3a627a8f6545cc09f2a1b0a8afdedd33a | [
"MIT"
] | 90 | 2017-10-18T21:24:51.000Z | 2019-06-06T02:30:33.000Z | library/ATF/CMainThread.hpp | kotopes/Yorozuya | 605c97d3a627a8f6545cc09f2a1b0a8afdedd33a | [
"MIT"
] | 44 | 2017-12-19T08:02:59.000Z | 2022-02-24T23:15:01.000Z | // This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually
#pragma once
#include <common/common.h>
#include <CBattleTournamentInfo.hpp>
#include <CCharacter.hpp>
#include <CCheckSum.hpp>
#include <CConnNumPHMgr.hpp>
#include <CFrameRate.hpp>
#include <CGameObject.hpp>
#include <CItemLootTable.hpp>
#include <CItemUpgradeTable.hpp>
#include <CLogFile.hpp>
#include <CMainThreadVtbl.hpp>
#include <CMapData.hpp>
#include <CMonsterSPGroupTable.hpp>
#include <CMsgProcess.hpp>
#include <CMyTimer.hpp>
#include <CNetIndexList.hpp>
#include <CNotifyNotifyRaceLeaderSownerUTaxrate.hpp>
#include <COreCuttingTable.hpp>
#include <CRFWorldDatabase.hpp>
#include <CRecordData.hpp>
#include <GuildCreateEventInfo.hpp>
#include <RFEventBase.hpp>
#include <TimeLimitMgr.hpp>
#include <_AIOC_A_MACRODATA.hpp>
#include <_AVATOR_DATA.hpp>
#include <_BUDDY_DB_BASE.hpp>
#include <_CLID.hpp>
#include <_CRYMSG_DB_BASE.hpp>
#include <_CUTTING_DB_BASE.hpp>
#include <_DB_QRY_SYN_DATA.hpp>
#include <_GLBID.hpp>
#include <_INVEN_DB_BASE.hpp>
#include <_ITEMCOMBINE_DB_BASE.hpp>
#include <_LINK_DB_BASE.hpp>
#include <_NOT_ARRANGED_AVATOR_DB.hpp>
#include <_PCBANG_FAVOR_ITEM_DB_BASE.hpp>
#include <_PCBANG_PLAY_TIME.hpp>
#include <_POTION_NEXT_USE_TIME_DB_BASE.hpp>
#include <_PVPPOINT_LIMIT_DB_BASE.hpp>
#include <_PVP_ORDER_VIEW_DB_BASE.hpp>
#include <_QUEST_DB_BASE.hpp>
#include <_REGED.hpp>
#include <_REGED_AVATOR_DB.hpp>
#include <_SFCONT_DB_BASE.hpp>
#include <_SRAND.hpp>
#include <_SUPPLEMENT_DB_BASE.hpp>
#include <_SYSTEMTIME.hpp>
#include <_TIMELIMITINFO_DB_BASE.hpp>
#include <_TRADE_DB_BASE.hpp>
#include <_TRUNK_DB_BASE.hpp>
#include <_UNIT_DB_BASE.hpp>
#include <_WAIT_ENTER_ACCOUNT.hpp>
#include <_db_cash_limited_sale.hpp>
#include <_db_golden_box_item.hpp>
#include <_economy_history_data.hpp>
#include <_mob_message.hpp>
#include <_object_id.hpp>
#include <_qry_case_gm_greetingmsg.hpp>
#include <_qry_case_guild_greetingmsg.hpp>
#include <_qry_case_guildroom_insert.hpp>
#include <_qry_case_guildroom_update.hpp>
#include <_qry_case_race_greetingmsg.hpp>
#include <_qry_case_sendwebracebosssms.hpp>
#include <_qry_case_update_guildmaster.hpp>
#include <_server_rate_realtime_load.hpp>
#include <_worlddb_economy_history_info_array.hpp>
#include <_worlddb_sf_delay_info.hpp>
#include <qry_case_cash_limsale.hpp>
#include <qry_case_select_golden_box_item.hpp>
START_ATF_NAMESPACE
#pragma pack(push, 8)
struct CMainThread
{
CMainThreadVtbl *vfptr;
_SRAND m_Rand;
_WAIT_ENTER_ACCOUNT m_WaitEnterAccount[2532];
CRFWorldDatabase *m_pWorldDB;
CFrameRate m_MainFrameRate;
CFrameRate m_DBFrameRate;
CMsgProcess m_GameMsg;
CConnNumPHMgr m_MgrConnNum;
CConnNumPHMgr m_HisMainFPS;
CConnNumPHMgr m_HisSendFPS;
CConnNumPHMgr m_HisDataFPS;
CMyTimer m_tmServerState;
bool m_bVerCheck;
CMyTimer m_tmEconomyState;
int m_tmDbUpdate;
_DB_QRY_SYN_DATA m_DBQrySynData[12660];
CNetIndexList m_listDQSData;
CNetIndexList m_listDQSDataComplete;
CNetIndexList m_listDQSDataEmpty;
CCheckSum m_CheckSum;
int m_nLimUserNum;
char m_szWorldName[33];
char m_wszWorldName[33];
char m_wszMainGreetingMsg[256];
char m_wszRaceGreetingMsg[3][256];
char m_wszGMName[17];
char m_wszBossName[3][17];
bool m_bAwayPartyConsumeItem;
char m_strAwayPartyItemCode[64];
bool m_bAwayPartyConsumeMoney;
unsigned int m_dwAwayPartyMoney;
char m_strAllRaceChatItemCode[64];
bool m_bAllRaceChatItemConsume;
bool m_bAllRaceChatMoneyConsume;
unsigned int m_dwAllRaceChatMoney;
char m_byWorldCode;
bool m_bWorldOpen;
bool m_bWorldService;
char m_szWorldDBName[64];
unsigned int m_dwMessengerIP;
unsigned int m_dwAccountIP;
unsigned int m_dwCheckAccountOldTick;
CMyTimer m_tmrCheckAvator;
CMyTimer m_tmrCheckLoop;
CMyTimer m_tmrAccountPing;
CMyTimer m_tmrStateMsgGotoWeb;
CMyTimer m_tmrCheckRadarDelay;
int m_bFreeServer;
bool m_bRuleThread;
bool m_bDQSThread;
CRecordData m_tblPlayer;
CRecordData m_tblMonster;
CRecordData m_tblNPC;
CRecordData m_tblAnimus;
CRecordData m_tblClass;
CRecordData m_tblExp;
CRecordData m_tblGrade;
CItemLootTable m_tblItemLoot;
COreCuttingTable m_tblOreCutting;
CRecordData m_tblItemMakeData;
CRecordData m_tblItemCombineData;
CRecordData m_tblItemExchangeData;
CItemUpgradeTable m_tblItemUpgrade;
CRecordData m_tblItemData[37];
CRecordData m_tblEffectData[4];
CRecordData m_tblUnitPart[6];
CRecordData m_tblUnitBullet;
CRecordData m_tblUnitFrame;
CRecordData m_tblEditData;
CRecordData m_MonsterBaseSPData;
CMonsterSPGroupTable m_MonsterSPGroupTable;
CLogFile m_logBillCheck;
CLogFile m_logSystemError;
CLogFile m_logLoadingError;
CLogFile m_logDungeon;
CLogFile m_logKillMon;
CLogFile m_logServerState;
CLogFile m_logDTrade;
CLogFile m_logGuild;
CLogFile m_logDQS;
CLogFile m_logRename;
CLogFile m_logAutoTrade;
CLogFile m_logEvent;
CLogFile m_logMove;
CLogFile m_logSave;
CLogFile m_logReturnGate;
CLogFile m_logHack;
CLogFile m_logPvP;
CLogFile m_logMonNum;
CMyTimer m_tmForceUserExit;
int m_nForceExitSocketIndexOffset;
bool m_bServerClosing;
bool m_bCheckOverTickCount;
int m_nSleepTerm;
int m_nSleepValue;
int m_nSleepIgnore;
bool m_bCheckSumActive;
char m_byWebAgentServerNetInx;
bool m_bConnectedWebAgentServer;
char m_byControllServerNetInx;
bool m_bConnectedControllServer;
int m_iOldDay;
bool m_bServiceKeyPass;
char m_byWorldType;
bool m_bReleaseServiceMode;
bool m_bExcuteService;
RFEventBase *m_pRFEvent_ClassRefine;
CNotifyNotifyRaceLeaderSownerUTaxrate m_kEtcNotifyInfo;
CBattleTournamentInfo m_BattleTournamentInfo;
GuildCreateEventInfo m_GuildCreateEventInfo;
_server_rate_realtime_load m_ServerRateLoad;
TimeLimitMgr *m_pTimeLimitMgr;
CMyTimer m_tmCheckForceClose;
unsigned int m_dwStartNPCQuestCnt[3];
_mob_message *m_MobMessage;
unsigned int m_dwServerResetToken;
unsigned int m_dwCheatSetPlayTime;
unsigned __int16 m_dwCheatSetScanerCnt;
unsigned __int16 m_dwCheatSetLevel;
public:
void AccountServerLogin();
void AddGuildBattleSchdule(struct _DB_QRY_SYN_DATA* pData);
void AddPassablePacket();
void Alive_Char_Complete(struct _DB_QRY_SYN_DATA* pData);
CMainThread();
void ctor_CMainThread();
bool CashDBInit(char* szIP, char* szDBName, char* szAccount, char* szPassword, unsigned int dwPort);
void CheckAccountLineState();
void CheckAvatorState();
void CheckConnNumLog();
void CheckDayChangedPvpPointClear();
bool CheckDefine();
void CheckForceClose();
void CheckRadarItemDelay();
void CheckServerRateINIFile();
void CheckServiceableTime();
void CompleteLoadGuildBattleTotalRecord(char byRet, char* pLoadData);
void CompleteUpdatePlayerVoteInfo(char* pData);
void CompleteUpdateServerToken(char* pData);
void CompleteUpdateSetLimitRun(char byRet, char* pData);
void CompleteUpdateVoteAvailable(char* pData);
void Complete_Select_RegeAvator_For_Lobby_Logout(char* pSheet);
void Complete_db_Update_Data_For_Post_Send(char* pSheet);
void Complete_db_Update_Data_For_Trade(char* pSheet);
void ContUserSaveJobCheck();
void Cont_UserSave_Complete(struct _DB_QRY_SYN_DATA* pData);
unsigned int CreateDataResetToken(struct _SYSTEMTIME* tm);
void CreateSelectCharacterLogTable(char byMonth);
void DQSCompleteProcess();
static void DQSThread(void* pv);
bool DataFileInit();
bool DatabaseInit(char* pszDBName, char* pszDBIP);
void Delete_Avator_Complete(struct _DB_QRY_SYN_DATA* pData);
void EndServer();
void ForceCloseUserInTiming();
struct CGameObject* GetChar(char* pszCharName);
struct CGameObject* GetCharW(char* wpszCharName);
struct CGameObject* GetObjectA(struct _object_id* pObjID);
struct CGameObject* GetObjectA(int kind, int id, int index);
struct CGameObject* GetObjectExpand(struct _object_id* pObjID, char* szCharName, uint16_t wSearchIndex);
void GetTommorrowStr(char* szTommorrow);
void InAtradTaxMoney(struct _DB_QRY_SYN_DATA* p);
void InGuildbattleCost(struct _DB_QRY_SYN_DATA* pData);
void InGuildbattleRewardMoney(struct _DB_QRY_SYN_DATA* pData);
bool Init();
void Insert_Avator_Complete(struct _DB_QRY_SYN_DATA* pData);
bool IsExcuteService();
bool IsReleaseServiceMode();
bool IsTestServer();
int LoadINI();
void LoadItemConsumeINI();
bool LoadLimitInfo();
bool LoadServerRateINIFile();
int LoadWorldInfoINI();
int LoadWorldSystemINI();
void Load_Content_Complete(char* pData);
void Load_PostStorage_Complete(char* pData);
void Load_ReturnPost_Complete(char* pData);
void Lobby_Account_Complete(struct _DB_QRY_SYN_DATA* pData);
void Logout_Account_Complete(struct _DB_QRY_SYN_DATA* pData);
void MakeSystemTower();
void ManageClientLimitRunRequest(char* pBuf);
bool NetworkInit();
bool ObjectInit();
void OnDQSRun();
void OnRun();
void OutDestGuildbattleCost(struct _DB_QRY_SYN_DATA* pData);
void OutSrcGuildbattleCost(struct _DB_QRY_SYN_DATA* pData);
void PingToAccount();
struct _DB_QRY_SYN_DATA* PushDQSData(unsigned int dwAccountSerial, struct _CLID* pidWorld, char byQryCase, char* pQryData, int nSize);
void PushResetServerToken();
bool Push_ChargeItem(unsigned int dwSerial, unsigned int dwK, unsigned int dwD, unsigned int dwU, char byType);
void QryCaseAddpvppoint(struct _DB_QRY_SYN_DATA* pData);
void Reged_Avator_Complete(struct _DB_QRY_SYN_DATA* pData);
void Release();
static void RuleThread(void* pv);
void Select_Avator_Complete(struct _DB_QRY_SYN_DATA* pData);
void SendWebRaceBossSMS(struct _DB_QRY_SYN_DATA* pData);
void SerivceForceSet(bool bService);
void SerivceSelfStart();
void SerivceSelfStop();
void ServerStateMsgGotoWebAgent();
bool SetGlobalDataName();
void SetServerRate();
void UpdateGuildBattleDrawRankInfo(struct _DB_QRY_SYN_DATA* pData);
void UpdateGuildBattleWinLoseRankInfo(struct _DB_QRY_SYN_DATA* pData);
void UpdateLoadGuildBattleRank(struct _DB_QRY_SYN_DATA* pData);
void UpdateReservedGuildBattleSchedule(struct _DB_QRY_SYN_DATA* pData);
bool ValidMacAddress();
bool _CheckGuildCheckSum(unsigned int dwSerial, char* wszGuildName, long double* dDalant, long double* dGold);
bool _CheckTotalSales();
bool _GameDataBaseInit();
char _db_Check_NpcData(unsigned int dwSerial, struct _AVATOR_DATA* pAvatorData);
char _db_GuildRoom_Insert(struct _qry_case_guildroom_insert* pSheet);
bool _db_GuildRoom_Update(struct _qry_case_guildroom_update* pSheet);
char _db_Load_Base(unsigned int dwSerial, struct _AVATOR_DATA* pCon);
void _db_Load_BattleTournamentInfo();
char _db_Load_Buddy(unsigned int dwSerial, struct _BUDDY_DB_BASE* pBuddy);
char _db_Load_Cash_LimSale(struct qry_case_cash_limsale* pDbLimitedSale);
char _db_Load_CryMsg(unsigned int dwSerial, struct _CRYMSG_DB_BASE* pBossCry);
char _db_Load_General(unsigned int dwSerial, char byRaceCode, struct _AVATOR_DATA* pCon);
char _db_Load_GoldBoxItem(struct qry_case_select_golden_box_item* pDbGoldenboxitem, int* pnDBSerial);
char _db_Load_Inven(unsigned int dwSerial, int nBagNum, struct _INVEN_DB_BASE* pCon);
char _db_Load_ItemCombineEx(unsigned int dwSerial, struct _ITEMCOMBINE_DB_BASE* pCombineEx);
char _db_Load_MacroData(unsigned int dwSerial, struct _AIOC_A_MACRODATA* pMacro);
char _db_Load_NpcQuest_History(unsigned int dwSerial, struct _QUEST_DB_BASE* pCon);
char _db_Load_OreCutting(unsigned int dwSerial, struct _CUTTING_DB_BASE* pDbCutting);
int _db_Load_PatriarchComm(char* pData);
char _db_Load_PcBangFavor(unsigned int dwSerial, struct _PCBANG_FAVOR_ITEM_DB_BASE* pDbPcBangFavor);
char _db_Load_PotionDelay(unsigned int dwSerial, struct _POTION_NEXT_USE_TIME_DB_BASE* pDbPotionDelay);
char _db_Load_PrimiumPlayTime(unsigned int dwAccSerial, struct _PCBANG_PLAY_TIME* kData);
char _db_Load_PvpOrderView(unsigned int dwSerial, struct _PVP_ORDER_VIEW_DB_BASE* kData);
char _db_Load_PvpPointLimitData(unsigned int dwSerial, struct _PVPPOINT_LIMIT_DB_BASE* kData);
char _db_Load_Quest(unsigned int dwSerial, struct _QUEST_DB_BASE* pCon);
char _db_Load_SFDelayData(unsigned int dwSerial, struct _worlddb_sf_delay_info* pDbSFDelayInfo);
char _db_Load_Start_NpcQuest_History(unsigned int dwSerial, char byRaceCode, struct _QUEST_DB_BASE* pCon);
char _db_Load_Supplement(unsigned int dwSerial, struct _SUPPLEMENT_DB_BASE* pDbSupplement);
char _db_Load_TimeLimitInfo(unsigned int dwAccSerial, struct _TIMELIMITINFO_DB_BASE* pDbTimeLimitInfo);
char _db_Load_Trade(char byRace, unsigned int dwSerial, struct _TRADE_DB_BASE* pTrade);
char _db_Load_Trunk(unsigned int dwSerial, unsigned int dwAccountSerial, char byRace, struct _TRUNK_DB_BASE* pTrunk);
char _db_Load_UI(unsigned int dwSerial, struct _LINK_DB_BASE* pLink, struct _SFCONT_DB_BASE* pSfcont);
char _db_Load_Unit(unsigned int dwSerial, struct _UNIT_DB_BASE* pCon);
char _db_Select_RegeAvator_For_Lobby_Logout(char* pSheet);
bool _db_Update_Base(unsigned int dwSerial, struct _AVATOR_DATA* pNewData, struct _AVATOR_DATA* pOldData, char* pSzQuery, bool bCheckLowHigh);
bool _db_Update_Buddy(unsigned int dwSerial, struct _AVATOR_DATA* pNewData, struct _AVATOR_DATA* pOldData, char* pwszQuery);
char _db_Update_Cash_LimSale(struct _db_cash_limited_sale* pNewData, struct _db_cash_limited_sale* pOldData);
bool _db_Update_CryMsg(unsigned int dwSerial, struct _AVATOR_DATA* pNewData, struct _AVATOR_DATA* pOldData, char* pwszQuery);
char _db_Update_Data_For_Post_Send(char* pSheet);
char _db_Update_Data_For_Trade(char* pSheet);
bool _db_Update_General(unsigned int dwSerial, struct _AVATOR_DATA* pNewData, struct _AVATOR_DATA* pOldData, char* pSzQuery, bool bCheckLowHigh);
char _db_Update_GoldBoxItem(int nDBSerial, struct _db_golden_box_item* pNewData, struct _db_golden_box_item* pOldData);
bool _db_Update_Inven(unsigned int dwSerial, struct _AVATOR_DATA* pNewData, struct _AVATOR_DATA* pOldData, char* pSzQuery);
bool _db_Update_ItemCombineEx(unsigned int dwSerial, struct _AVATOR_DATA* pNewData, struct _AVATOR_DATA* pOldData, char* pSzQuery);
bool _db_Update_MacroData(unsigned int dwSerial, struct _AIOC_A_MACRODATA* pMacro, struct _AIOC_A_MACRODATA* pOldMacro);
bool _db_Update_NpcData(unsigned int dwSerial, struct _AVATOR_DATA* pAvatorData, char* pSzNpcQuery);
bool _db_Update_NpcQuest_History(unsigned int dwSerial, struct _AVATOR_DATA* pNewData, struct _AVATOR_DATA* pOldData, char* pSzQuery);
bool _db_Update_OreCutting(unsigned int dwSerial, struct _AVATOR_DATA* pNewData, struct _AVATOR_DATA* pOldData, char* szOreCuttingQuery, int nSize);
bool _db_Update_PcBangFavor(unsigned int dwSerial, struct _AVATOR_DATA* pNewData, struct _AVATOR_DATA* pOldData, char* szPcBangFavorQuery, int nSize);
bool _db_Update_PotionDelay(unsigned int dwSerial, struct _AVATOR_DATA* pNewData, struct _AVATOR_DATA* pOldData, char* szPotionDelayQuery, int nSize);
bool _db_Update_PrimiumPlayTime(unsigned int dwAccSerial, struct _AVATOR_DATA* pNewData, struct _AVATOR_DATA* pOldData, char* szQuery, char* szError);
bool _db_Update_PvpOrderView(unsigned int dwSerial, struct _AVATOR_DATA* pNewData, struct _AVATOR_DATA* pOldData, char* szQuery, char* szError);
bool _db_Update_PvpPointLimit(unsigned int dwSerial, struct _AVATOR_DATA* pNewData, struct _AVATOR_DATA* pOldData, char* szQuery, char* szError);
bool _db_Update_Quest(unsigned int dwSerial, struct _AVATOR_DATA* pNewData, struct _AVATOR_DATA* pOldData, char* pSzQuery);
bool _db_Update_SFDelayData(unsigned int dwSerial, struct _AVATOR_DATA* pNewData);
char _db_Update_Set_Limit_Run();
bool _db_Update_Start_NpcQuest_History(unsigned int dwSerial, struct _AVATOR_DATA* pNewData, struct _AVATOR_DATA* pOldData);
bool _db_Update_Supplement(unsigned int dwSerial, struct _AVATOR_DATA* pNewData, struct _AVATOR_DATA* pOldData, char* szSupplementQuery, int nSize);
char _db_Update_TimeLimitInfo(unsigned int dwAccSerial, struct _AVATOR_DATA* pNewData, struct _AVATOR_DATA* pOldData, char* szTimeLimitInfoQuery, int nSize);
bool _db_Update_Trunk(unsigned int dwAccountSerial, struct _AVATOR_DATA* pNewData, struct _AVATOR_DATA* pOldData, char* pwszQuery);
bool _db_Update_Trunk_Extend(unsigned int dwAccountSerial, struct _AVATOR_DATA* pNewData, struct _AVATOR_DATA* pOldData, char* pwszQuery);
bool _db_Update_UI(unsigned int dwSerial, struct _AVATOR_DATA* pNewData, struct _AVATOR_DATA* pOldData, char* pSzQuery);
bool _db_Update_Unit(unsigned int dwSerial, struct _AVATOR_DATA* pNewData, struct _AVATOR_DATA* pOldData, char* pSzQuery);
void _db_complete_event_classrefine(uint16_t wSock, unsigned int dwAvatorSerial, char byRefinedCnt, unsigned int dwRefineDate);
void _db_complete_update_event_classrefine(uint16_t wSock, unsigned int dwAvatorSerial);
int _db_init_classrefine_count();
char _db_load_event_classrefine(unsigned int dwAvatorSerial, char* byRefinedCnt, unsigned int* dwRefineDate);
char _db_load_losebattlecount(unsigned int dwSerial, struct _AVATOR_DATA* pCon);
char _db_load_punishment(unsigned int dwSerial, struct _AVATOR_DATA* pCon);
char _db_load_raceboss(unsigned int dwSerial, struct _AVATOR_DATA* pCon);
char _db_update_event_classrefine(uint16_t wSock, unsigned int dwAvatorSerial, char byRefinedCnt, unsigned int dwRefineDate);
bool _db_update_inven_AMP(unsigned int dwAvatorSerial, struct _AVATOR_DATA* pNewData, struct _AVATOR_DATA* pOldData, char* pszQuery);
bool check_dbsyn_data_size();
bool check_item_code_index();
bool check_loaded_data();
char check_min_max_guild_money(unsigned int dwGuildSerial, long double* pdDalant, long double* pdGold);
char db_Add_PvpPoint(unsigned int dwSerial, unsigned int dwPoint, unsigned int dwCashBag);
char db_Delete_Avator(unsigned int dwSerial, char byRaceCode);
char db_GM_GreetingMsg(struct _qry_case_gm_greetingmsg* pSheet);
char db_GUILD_GreetingMsg(struct _qry_case_guild_greetingmsg* pSheet);
char db_Insert_Avator(unsigned int dwAccountSerial, char* pszAccount, struct _REGED_AVATOR_DB* pCharDB, unsigned int* pdwAvatorSerial);
char db_Insert_ChangeClass_AfterInitClass(unsigned int dwCharacSerial, char byType, char* szPrevClassCode, char* szNextClassCode, int nClassInitCnt, char byLastClassGrade, uint16_t dwYear, char byMonth, char byDay, char byHour, char byMin, char bySec);
char db_Insert_CharacSelect_Log(unsigned int dwAccountSerial, char* szAccount, unsigned int dwCharacSerial, char* pwszCharacName, uint16_t dwYear, char byMonth, char byDay, char byHour, char byMin, char bySec);
char db_Insert_Economy_History(unsigned int dwDate, struct _worlddb_economy_history_info_array::_worlddb_economy_history_info* pEconomyData);
char db_Insert_Item(unsigned int dwSerial, unsigned int dwItemCodeK, unsigned int dwItemCodeD, unsigned int dwItemCodeU, char byType);
char db_Insert_guild(unsigned int* dwSerial, char* pwszGuildName, char byRace, unsigned int* dwGuildSerial);
bool db_LoadGreetingMsg();
char db_Load_Avator(unsigned int dwSerial, unsigned int dwAccountSerial, struct _AVATOR_DATA* pData, bool* pbAddItem, unsigned int* pdwAddDalant, unsigned int* pdwAddGold, bool* pbTrunkAddItem, char* pbyTrunkOldSlot, long double* pdTrunkOldDalant, long double* pdTrunkOldGold, bool* pbCreateTrunkFree, bool* pbExtTrunkAddItem, char* pbyExtTrunkOldSlot, bool bAll, unsigned int* pdwCheckSum);
char db_Load_Content(char* pData);
char db_Load_PostStorage(char* pData);
char db_Load_ReturnPost(char* pData);
char db_Log_AvatorLevel(unsigned int dwTotalPlayMin, unsigned int dwSerial, char byLv);
char db_Log_UserNum(int nAveragePerHour, int nMaxPerHour);
char db_RACE_GreetingMsg(struct _qry_case_race_greetingmsg* pSheet);
char db_Reged_Avator(unsigned int dwAccountSerial, struct _REGED* pRegedList, struct _NOT_ARRANGED_AVATOR_DB* pArrangedList, char* pszIP);
char db_Select_Economy_History(struct _economy_history_data* pCurData, int* pnCurMgrValue, int* pnNextMgrValue, struct _economy_history_data* pHisData, int* pHistoryNum, unsigned int dwDate);
char db_Update_Avator(unsigned int dwSerial, struct _AVATOR_DATA* pNewData, struct _AVATOR_DATA* pOldData, bool bCheckLowHigh);
char db_Update_PostStorage(unsigned int dwAvatorSerial, struct _AVATOR_DATA* pNewData, struct _AVATOR_DATA* pOldData);
char db_Update_PvpInfo(unsigned int dwSerial, char byLevel, int16_t* pzClassHistory, long double dPvpPoint);
char db_buy_emblem(unsigned int dwGuildSerial, int nEmblemDalant, unsigned int dwEmblemBack, unsigned int dwEmblemMark, unsigned int dwSuggestorSerial, long double* dTotalDalant, long double* dTotalGold, char* byDate, char* pwszName, char* pbyProcRet);
char db_char_set_alive(unsigned int dwAccountSerial, char byCase, unsigned int dwSerial, char* pwszName, char bySlot, struct _REGED* pAliveAvator);
char db_disjoint_guild(unsigned int dwGuildSerial);
char db_input_guild_money(unsigned int dwPusherSerial, unsigned int dwGuildSerial, unsigned int dwAddDalant, unsigned int dwAddGold, long double* dTotalDalant, long double* dTotalGold, char* byDate, char* pwszName);
char db_input_guild_money_atradetax(unsigned int dwPusherSerial, unsigned int dwGuildSerial, unsigned int dwAddDalant, long double* dTotalDalant, long double* dTotalGold, char* byDate);
char db_output_guild_money(unsigned int dwPusherSerial, unsigned int dwGuildSerial, unsigned int dwSubDalant, unsigned int dwSubGold, long double* dTotalDalant, long double* dTotalGold, char* byDate, char* pwszName, char* pbyProcRet);
char db_sendwebracebosssms(struct _qry_case_sendwebracebosssms* pSheet);
char db_update_guildmaster(struct _qry_case_update_guildmaster* pSheet);
char db_update_guildmember_add(unsigned int dwAvatorSerial, unsigned int dwGuildSerial, char byGrade, int nMemberNum);
char db_update_guildmember_del(unsigned int dwAvatorSerial, unsigned int dwGuildSerial, int nMemberNum);
void gm_DisplayAll();
void gm_DisplaymodeChange();
void gm_DungeonLoad();
void gm_MainThreadControl();
void gm_MapChange(struct CMapData* pMap);
bool gm_MonsterInit(struct CCharacter* pExt);
void gm_ObjectSelect();
void gm_PreCloseAnn();
void gm_ServerClose();
void gm_UpdateMap();
void gm_UpdateObject();
void gm_UpdateServer();
void gm_UserExit();
void pc_AllUserGMNoticeInform(char* pwszMsg);
void pc_AllUserKickInform();
void pc_AllUserMsgInform(char* pwszMsg);
void pc_AlterWorldService(bool bSerivce);
void pc_CashDBInfoRecvResult(char* szIP, char* szDBName, char* szAccount, char* szPassword, unsigned int dwPort);
void pc_ChatLockCommand(struct _CLID* pidLocal, uint16_t wBlockTimeH);
void pc_EnterWorldResult(char byRetCode, struct _CLID* pidWorld);
void pc_ForceCloseCommand(struct _CLID* pidWorld, bool bDirectly, char byKickType, unsigned int dwPushIP);
void pc_OpenWorldFailureResult(char* szMsg);
void pc_OpenWorldSuccessResult(char byWorldCode, char* pszDBName, char* pszDBIP);
void pc_SetMainGreetingMsg(char* pwszGMName, char* pwszMsg);
void pc_SetRaceGreetingMsg(int racenum, char* pwszBossName, char* pwszMsg);
void pc_TaiwanBillingUserCertify(char* szAccount, char byCertify);
void pc_TransIPKeyInform(unsigned int dwAccountSerial, char* pszAccountID, char byUserDgr, char bySubDgr, unsigned int* pdwKey, struct _GLBID* pgidGlobal, unsigned int dwClientIP, bool bChatLock, int16_t iType, char* szCMS, struct _SYSTEMTIME* pstEndDate, int lRemainTime, char byUILock, char* szUILockPW, char byUILockFailCnt, char* szAccountPW, char byUILock_HintIndex, char* uszUILock_HintAnswer, char byUILockFindPassFailCount, bool bIsPcBang, int nTrans, bool bAgeLimit, unsigned int* pdwRequestMoveCharacterSerialList, unsigned int* pdwTournamentCharacterSerialList);
void pc_UILockInitResult(char* pMsg);
void pc_UILockUpdateResult(char* pMsg);
void pc_UserChatBlockResult(char byBlockResult, struct _CLID* pcidTarget, struct _CLID* pcidGM, int bLogin);
~CMainThread();
void dtor_CMainThread();
};
#pragma pack(pop)
static_assert(ATF::checkSize<CMainThread, 944222408>(), "CMainThread");
END_ATF_NAMESPACE
| 60.385681 | 581 | 0.752209 | lemkova |
e48534dd596495a1205132f60f02b8ac514233c8 | 916 | cc | C++ | CH16_TemplatesAndGenericProgramming/exercises/ex16_30_31.cc | iZhangHui/CppPrimer | e61f660c9b0155a2c13d64f104cbd3f641ea00c4 | [
"Unlicense"
] | 34 | 2016-09-23T06:22:35.000Z | 2021-12-09T14:01:14.000Z | CH16_TemplatesAndGenericProgramming/exercises/ex16_30_31.cc | zhangzheng0317/CppPrimer | 322ed3cb120fe0282fe75e147b7d13c2a966519c | [
"Unlicense"
] | null | null | null | CH16_TemplatesAndGenericProgramming/exercises/ex16_30_31.cc | zhangzheng0317/CppPrimer | 322ed3cb120fe0282fe75e147b7d13c2a966519c | [
"Unlicense"
] | 10 | 2018-05-14T01:35:18.000Z | 2021-06-14T02:44:53.000Z | #include <iostream>
#include <string>
#include "Blob.h"
int main(int argc, char const *argv[])
{
Blob<int> blob{1, 2, 3};
blob.push_back(4);
for (size_t i = 0; i != blob.size(); ++i) {
std::cout << blob[i] << " ";
}
std::cout << std::endl;
// int ret = blob.back();
int& ret = blob.back();
ret = 5;
for (size_t i = 0; i != blob.size(); ++i) {
std::cout << blob[i] << " ";
}
std::cout << std::endl;
Blob<std::string> b1; // empty Blob
std::cout << b1.size() << std::endl;
{ // new scope
Blob<std::string> b2 = {"a", "an", "the"};
b1 = b2; // b1 and b2 share the same elements
b2.push_back("about");
std::cout << b1.size() << " " << b2.size() << std::endl;
} // b2 is destroyed, but the elements it points to must not be destroyed
std::cout << b1.size() << std::endl;
for (size_t i = 0; i != b1.size(); ++i) {
std::cout << b1[i] << " ";
}
std::cout << std::endl;
return 0;
}
| 22.341463 | 74 | 0.537118 | iZhangHui |
e4853e6f0eed01a2abe8cf3f53e86a776843e761 | 179 | hpp | C++ | optionals/last_ship/XEH_PREP.hpp | kellerkompanie/kellerkompanie-mods | f15704710f77ba6c018c486d95cac4f7749d33b8 | [
"MIT"
] | 6 | 2018-05-05T22:28:57.000Z | 2019-07-06T08:46:51.000Z | optionals/last_ship/XEH_PREP.hpp | Schwaggot/kellerkompanie-mods | 7a389e49e3675866dbde1b317a44892926976e9d | [
"MIT"
] | 107 | 2018-04-11T19:42:27.000Z | 2019-09-13T19:05:31.000Z | optionals/last_ship/XEH_PREP.hpp | kellerkompanie/kellerkompanie-mods | f15704710f77ba6c018c486d95cac4f7749d33b8 | [
"MIT"
] | 3 | 2018-10-03T11:54:46.000Z | 2019-02-28T13:30:16.000Z | PREP(addVendingActions);
PREP(canRefillVendingMachine);
PREP(checkAmountLeft);
PREP(initTelephone);
PREP(initVendingMachine);
PREP(refillVendingMachine);
PREP(useVendingMachine);
| 22.375 | 30 | 0.843575 | kellerkompanie |
e486b760eae206c1a5ed3a7817f9167fef0063a3 | 4,006 | cpp | C++ | Day03/Day03.cpp | Zhoroaan/adventofcode2021 | 099b6ae8d58032045dfa4c2edc2d7b2f9f0fdab9 | [
"MIT"
] | null | null | null | Day03/Day03.cpp | Zhoroaan/adventofcode2021 | 099b6ae8d58032045dfa4c2edc2d7b2f9f0fdab9 | [
"MIT"
] | null | null | null | Day03/Day03.cpp | Zhoroaan/adventofcode2021 | 099b6ae8d58032045dfa4c2edc2d7b2f9f0fdab9 | [
"MIT"
] | null | null | null | #include <bitset>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include "../Lib/CommonLib.h"
const char* InputData = "TestInputData.txt";
//const char* InputData = "MyInput.txt";
int32_t CountSetInColumn(const std::vector<std::bitset<32>>& InRows, int InColumn)
{
uint32_t count = 0;
for (const auto& element : InRows)
{
if (element.test(InColumn))
count++;
}
return count;
}
int_fast32_t FindRatings(std::vector<std::bitset<32>> InRows, size_t InNumBits, bool InCheckOxygenRating)
{
for(int index = static_cast<int>(InNumBits) - 1; index >= 0; --index)
{
auto count = CountSetInColumn(InRows, index);
auto isSet = InCheckOxygenRating ? count * 2 > InRows.size() : count * 2 < InRows.size();
auto isEqual = count * 2 == InRows.size();
std::erase_if(InRows, [InCheckOxygenRating, isSet, isEqual, index](std::bitset<32> InLine) // check rating
{
if (isEqual)
return InLine.test(index) != InCheckOxygenRating;
return InLine.test(index) != isSet;
});
if (InRows.size() == 1)
{
return InRows[0].to_ulong();
}
int breakHere = 2;
}
std::cerr << "Did not find one match, found [" << InRows.size() << "] matches" << std::endl;
return 0;
}
int main(int argc, char* argv[])
{
Timer fullProgramTime("Full Program Time");
std::ifstream inputDataStream;
inputDataStream.open(InputData);
if (!inputDataStream.is_open())
{
std::cerr << "Incorrect path to input data" << std::endl;
return 1;
}
std::vector<uint_fast32_t> bitCount;
std::string buffer;
std::getline(inputDataStream, buffer);
uint_fast32_t inverseRelevance = 0;
std::vector<std::bitset<32>> rows;
uint32_t firstRow = 0;
for(int32_t charIndex = static_cast<int32_t>(buffer.size()) - 1; charIndex >= 0 ; charIndex--)
{
const auto currentBit = buffer[charIndex];
if (currentBit != '0' && currentBit != '1')
continue;
inverseRelevance |= 1 << bitCount.size();
const bool isSet = currentBit == '1';
if (isSet)
firstRow |= 1 << bitCount.size();
bitCount.insert(bitCount.begin(), isSet ? 1 : 0);
}
rows.push_back(firstRow); // First row
int_fast32_t rowCount = 0;
while (std::getline(inputDataStream, buffer))
{
rowCount += 1;
uint32_t currentRow = 0;
for(int32_t charIndex = static_cast<int32_t>(buffer.size()) - 1; charIndex >= 0 ; charIndex--)
{
if (buffer[charIndex] == '1')
{
bitCount[charIndex] += 1;
currentRow |= 1 << (buffer.size() - charIndex - 1);
}
}
rows.push_back(currentRow);
}
uint_fast32_t mostCommonColumns = 0;
uint_fast32_t equalColumns = 0;
const uint_fast32_t minCount = rowCount / 2 + 1;
for(auto bitIndex = 0; bitIndex < bitCount.size(); ++bitIndex)
{
if (bitCount[bitIndex] > minCount)
mostCommonColumns |= 1 << (bitCount.size() - bitIndex - 1);
else if (bitCount[bitIndex] == minCount)
equalColumns |= 1 << (bitCount.size() - bitIndex - 1);
}
std::bitset<32> y(mostCommonColumns);
std::cout << "Accumulator : " << y << std::endl;
std::cout << "Gamma : " << mostCommonColumns << std::endl;
const uint_fast32_t epsilon = (~mostCommonColumns & inverseRelevance);
std::cout << "Epsilon : " << epsilon << std::endl;
const int_fast32_t oxygenRating = FindRatings(rows, bitCount.size(), true);
const int_fast32_t co2ScrubberRating = FindRatings(rows, bitCount.size(), false);
std::cout << "Oxygen generation rating: " << oxygenRating << std::endl;
std::cout << "CO2 scrubbing rating: " << co2ScrubberRating << std::endl;
std::cout << "Answer : " << oxygenRating * co2ScrubberRating << std::endl;
return 0;
}
| 33.949153 | 114 | 0.594109 | Zhoroaan |
e4890b3a6dc165690f9ec27c21a78230dbec4662 | 8,487 | cpp | C++ | cpp-projects/exvr-designer/widgets/components/config_parameters/camera_target_pw.cpp | FlorianLance/exvr | 4d210780737479e9576c90e9c80391c958787f44 | [
"MIT"
] | null | null | null | cpp-projects/exvr-designer/widgets/components/config_parameters/camera_target_pw.cpp | FlorianLance/exvr | 4d210780737479e9576c90e9c80391c958787f44 | [
"MIT"
] | null | null | null | cpp-projects/exvr-designer/widgets/components/config_parameters/camera_target_pw.cpp | FlorianLance/exvr | 4d210780737479e9576c90e9c80391c958787f44 | [
"MIT"
] | null | null | null |
/***********************************************************************************
** exvr-designer **
** MIT License **
** Copyright (c) [2018] [Florian Lance][EPFL-LNCO] **
** Permission is hereby granted, free of charge, to any person obtaining a copy **
** of this software and associated documentation files (the "Software"), to deal **
** in the Software without restriction, including without limitation the rights **
** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell **
** copies of the Software, and to permit persons to whom the Software is **
** furnished to do so, subject to the following conditions: **
** **
** The above copyright notice and this permission notice shall be included in all **
** copies or substantial portions of the Software. **
** **
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR **
** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, **
** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE **
** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER **
** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, **
** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE **
** SOFTWARE. **
************************************************************************************/
#include "camera_target_pw.hpp"
// qt-utility
#include "ex_widgets/ex_float_spin_box_w.hpp"
#include "ex_widgets/ex_radio_button_w.hpp"
#include "ex_widgets/ex_vector3d_w.hpp"
#include "ex_widgets/ex_curve_w.hpp"
#include "ex_widgets/ex_line_edit_w.hpp"
using namespace tool::ex;
struct CameraTargetConfigParametersW::Impl{
// settings
ExFloatSpinBoxW duration{"duration"};
ExCheckBoxW sphericalInterpolation{"spherical_linear_interpolation"};
ExCheckBoxW pitch{"pitch"};
ExCheckBoxW yaw{"yaw"};
ExCheckBoxW roll{"roll"};
// # choice
QButtonGroup buttonGroup1;
ExRadioButtonW moveToTarget{"move_to_target"};
ExRadioButtonW moveBack{"move_back"};
ExRadioButtonW doNothing{"do_nothing"};
ExCheckBoxW teleport{"teleport"};
ExCheckBoxW doNotSaveTraj{"do_not_save_traj"};
QButtonGroup buttonGroup2;
ExRadioButtonW useNeutralCamera {"use_neutral"};
ExRadioButtonW useEyeCamera{"use_eye"};
// # move to target
ExLineEditW componentName{"target_component"};
QButtonGroup buttonGroup3;
ExRadioButtonW relatetiveToEye{"relative_to_eye"};
ExRadioButtonW absolute{"absolute"};
ExVector3dW targetPos{"target_pos"};
ExVector3dW targetRot{"target_rot"};
QButtonGroup buttonGroup4;
ExRadioButtonW usingTime{"use_time"};
ExRadioButtonW usingFactor{"use_factor"};
ExFloatSpinBoxW factorOffset{"factor_offset"};
ExFloatSpinBoxW factorFactor{"factor_factor"};
// curves
QTabWidget curves;
ExCurveW speedCurve{"speed_curve"};
};
CameraTargetConfigParametersW::CameraTargetConfigParametersW() : ConfigParametersW(), m_p(std::make_unique<Impl>()){
}
void CameraTargetConfigParametersW::insert_widgets(){
add_widget(ui::W::txt("<b>Action</b>"));
add_widget(ui::F::gen(ui::L::HB(), {m_p->moveToTarget(), m_p->moveBack(), m_p->doNothing()}, LStretch{true}, LMargins{false},QFrame::NoFrame));
add_widget(ui::F::gen(ui::L::HB(), {m_p->teleport(), m_p->doNotSaveTraj()}, LStretch{true}, LMargins{false},QFrame::NoFrame));
add_widget(ui::W::txt("<b>Camera</b>"));
add_widget(ui::F::gen(ui::L::HB(), {m_p->useNeutralCamera(), m_p->useEyeCamera()}, LStretch{true}, LMargins{false},QFrame::NoFrame));
add_widget(ui::F::gen(ui::L::HB(), {m_p->pitch(), m_p->yaw(), m_p->roll()},LStretch{true}, LMargins{false},QFrame::NoFrame));
add_widget(ui::W::txt("<b>Progress</b>"));
add_widget(ui::F::gen(ui::L::HB(), {m_p->usingTime(), ui::W::txt("Movement duration: "), m_p->duration()}, LStretch{true}, LMargins{false},QFrame::NoFrame));
add_widget(ui::F::gen(ui::L::HB(), {m_p->usingFactor(),
ui::W::txt("add: "), m_p->factorOffset(), ui::W::txt("multiply by: "), m_p->factorFactor()}, LStretch{true}, LMargins{false},QFrame::NoFrame));
add_widget(ui::W::txt("<b>Interpolation</b>"));
add_widget(ui::F::gen(ui::L::HB(), {m_p->sphericalInterpolation()}, LStretch{true}, LMargins{false},QFrame::NoFrame));
add_widget(ui::W::txt("<b>Target</b>"));
add_widget(ui::F::gen(ui::L::HB(), {ui::W::txt("Name of the component position to match: "), m_p->componentName()}, LStretch{false}, LMargins{false}));
add_widget(ui::F::gen(ui::L::VB(), {ui::W::txt("If name empty, use position and rotation below:"), m_p->targetPos(), m_p->targetRot()}, LStretch{false}, LMargins{false}));
add_widget(ui::F::gen(ui::L::HB(), {m_p->absolute(), m_p->relatetiveToEye()}, LStretch{true}, LMargins{false}));
add_widget(&m_p->curves);
m_p->curves.addTab(m_p->speedCurve(), "Factor curve");
}
void CameraTargetConfigParametersW::init_and_register_widgets(){
// settings
add_input_ui(m_p->duration.init_widget(MinV<qreal>{0}, V<qreal>{5.}, MaxV<qreal>{500.}, StepV<qreal>{0.1}, 2, true));
add_input_ui(m_p->sphericalInterpolation.init_widget("Use spherical linear interpolation ", true));
// axies
add_input_ui(m_p->pitch.init_widget("Use pitch", false));
add_input_ui(m_p->yaw.init_widget("Use yaw", true));
add_input_ui(m_p->roll.init_widget("use roll", false));
// actions
add_inputs_ui(
ExRadioButtonW::init_group_widgets(m_p->buttonGroup1,
{&m_p->moveToTarget, &m_p->moveBack, &m_p->doNothing},
{
"Move to target",
"Move back to previous target",
"Do nothing"
},
{true, false, false}
)
);
add_input_ui(m_p->teleport.init_widget("Teleport", false));
add_input_ui(m_p->doNotSaveTraj.init_widget("Do not save trajectory", false));
add_inputs_ui(
ExRadioButtonW::init_group_widgets(m_p->buttonGroup3,
{&m_p->relatetiveToEye, &m_p->absolute},
{
"Relative to eye",
"Absolute"
},
{false, true}
)
);
// cameras
add_inputs_ui(
ExRadioButtonW::init_group_widgets(m_p->buttonGroup2,
{&m_p->useNeutralCamera, &m_p->useEyeCamera},
{
"Use start neutral camera",
"Use eye camera"
},
{true, false}
)
);
// progress
add_inputs_ui(
ExRadioButtonW::init_group_widgets(m_p->buttonGroup4,
{&m_p->usingTime, &m_p->usingFactor},
{
"Use elapsed time",
"Use input factor [0-1]"
},
{true, false}
)
);
add_input_ui(m_p->factorOffset.init_widget(MinV<qreal>{-100}, V<qreal>{0.}, MaxV<qreal>{100.}, StepV<qreal>{0.1}, 2, true));
add_input_ui(m_p->factorFactor.init_widget(MinV<qreal>{0}, V<qreal>{1.}, MaxV<qreal>{100.}, StepV<qreal>{0.1}, 2, true));
// move to target
add_input_ui(m_p->componentName.init_widget(""));
DsbSettings s1 = {MinV<qreal>{-10000.}, V<qreal>{0.},MaxV<qreal>{10000.}, StepV<qreal>{0.1}, 3};
add_input_ui(m_p->targetPos.init_widget("Position: ", Vector3dSettings{s1,s1,s1}, true));
add_input_ui(m_p->targetRot.init_widget("Rotation: ", Vector3dSettings{s1,s1,s1}, true));
// curves
add_input_ui(m_p->speedCurve.init_widget("Factor speed curve"));
m_p->speedCurve.minX.w->setEnabled(false);
m_p->speedCurve.maxX.w->setEnabled(false);
m_p->speedCurve.minY.w->setEnabled(false);
m_p->speedCurve.maxY.w->setEnabled(false);
m_p->speedCurve.firstY.w->setMinimum(0.);
m_p->speedCurve.firstY.w->setMaximum(1.);
m_p->speedCurve.lastY.w->setMinimum(0.);
m_p->speedCurve.lastY.w->setMaximum(1.);
m_p->speedCurve.currentCurveId.w->setEnabled(false);
m_p->speedCurve.currentCurveId.w->setValue(0);
}
| 44.434555 | 175 | 0.609403 | FlorianLance |
e49423a473eb24293b0f9323adeb7b47175d9bd0 | 2,945 | cpp | C++ | test/test_Sort.cpp | chuyangliu/tastylib | 0f353938b18e39efdfce27be36ad511b3112af6b | [
"MIT"
] | 11 | 2019-06-12T03:11:05.000Z | 2021-08-13T16:04:31.000Z | test/test_Sort.cpp | chuyangliu/tastylib | 0f353938b18e39efdfce27be36ad511b3112af6b | [
"MIT"
] | null | null | null | test/test_Sort.cpp | chuyangliu/tastylib | 0f353938b18e39efdfce27be36ad511b3112af6b | [
"MIT"
] | 3 | 2019-12-05T20:56:48.000Z | 2021-07-25T20:44:57.000Z | #include "gtest/gtest.h"
#include "tastylib/Sort.h"
#include "tastylib/util/random.h"
#include <algorithm>
using tastylib::Random;
using tastylib::insertionSort;
using tastylib::selectionSort;
using tastylib::heapSort;
using tastylib::quickSort;
using tastylib::quickSelect;
TEST(SortTest, InsertionSort) {
Random *random = Random::getInstance();
const int n = 3000;
int arr1[n], arr2[n];
for (int i = 0; i < n; ++i) {
arr1[i] = arr2[i] = random->nextInt(1, 10000);
}
std::sort(arr1, arr1 + n, std::greater<int>());
insertionSort<int, std::greater<int>>(arr2, n);
EXPECT_TRUE(std::is_sorted(arr1, arr1 + n, std::greater<int>()));
EXPECT_TRUE(std::is_sorted(arr2, arr2 + n, std::greater<int>()));
for (int i = 0; i < n; ++i) {
EXPECT_EQ(arr1[i], arr2[i]);
}
}
TEST(SortTest, SelectionSort) {
Random *random = Random::getInstance();
const int n = 3000;
int arr1[n], arr2[n];
for (int i = 0; i < n; ++i) {
arr1[i] = arr2[i] = random->nextInt(1, 10000);
}
std::sort(arr1, arr1 + n, std::greater<int>());
selectionSort<int, std::greater<int>>(arr2, n);
EXPECT_TRUE(std::is_sorted(arr1, arr1 + n, std::greater<int>()));
EXPECT_TRUE(std::is_sorted(arr2, arr2 + n, std::greater<int>()));
for (int i = 0; i < n; ++i) {
EXPECT_EQ(arr1[i], arr2[i]);
}
}
TEST(SortTest, HeapSort) {
Random *random = Random::getInstance();
const int n = 3000;
int arr1[n], arr2[n];
for (int i = 0; i < n; ++i) {
arr1[i] = arr2[i] = random->nextInt(1, 10000);
}
std::sort(arr1, arr1 + n, std::greater<int>());
heapSort<int, std::greater<int>>(arr2, n);
EXPECT_TRUE(std::is_sorted(arr1, arr1 + n, std::greater<int>()));
EXPECT_TRUE(std::is_sorted(arr2, arr2 + n, std::greater<int>()));
for (int i = 0; i < n; ++i) {
EXPECT_EQ(arr1[i], arr2[i]);
}
}
TEST(SortTest, QuickSort) {
Random *random = Random::getInstance();
const int n = 3000;
int arr1[n], arr2[n];
for (int i = 0; i < n; ++i) {
arr1[i] = arr2[i] = random->nextInt(1, 10000);
}
std::sort(arr1, arr1 + n, std::greater<int>());
quickSort<int, std::greater<int>>(arr2, 0, n - 1);
EXPECT_TRUE(std::is_sorted(arr1, arr1 + n, std::greater<int>()));
EXPECT_TRUE(std::is_sorted(arr2, arr2 + n, std::greater<int>()));
for (int i = 0; i < n; ++i) {
EXPECT_EQ(arr1[i], arr2[i]);
}
}
TEST(SortTest, QuickSelect) {
Random *random = Random::getInstance();
const int n = 3000;
for (int i = 0; i < 5; ++i) {
int arr1[n], arr2[n];
for (int j = 0; j < n; ++j) {
arr1[j] = arr2[j] = random->nextInt(1, 10000);
}
unsigned k = random->nextInt(0, n - 1);
std::nth_element(arr1, arr1 + k, arr1 + n, std::greater<int>());
quickSelect<int, std::greater<int>>(arr2, 0, n - 1, k);
EXPECT_EQ(arr1[k], arr2[k]);
}
}
| 32.362637 | 72 | 0.564686 | chuyangliu |
e4945739f60d5a9a45751d2931cc6480aea1f38f | 1,154 | cc | C++ | 2018/santi/day_7.1.cc | bbglab/adventofcode | 65b6d8331d10f229b59232882d60024b08d69294 | [
"MIT"
] | null | null | null | 2018/santi/day_7.1.cc | bbglab/adventofcode | 65b6d8331d10f229b59232882d60024b08d69294 | [
"MIT"
] | null | null | null | 2018/santi/day_7.1.cc | bbglab/adventofcode | 65b6d8331d10f229b59232882d60024b08d69294 | [
"MIT"
] | 3 | 2016-12-02T09:20:42.000Z | 2021-12-01T13:31:07.000Z | #include <iostream>
#include <vector>
using namespace std;
struct work{
char id;
int prev;
vector<struct work *> next;
};
bool compare( struct work a, struct work b){
return a.id < b.id;
}
int main(){
string word;
char a, b;
vector<struct work> works = vector<struct work>('Z' - 'A' + 1);
for(int i = 0; i < works.size(); i++) works[i].id = '0';
while(cin >> word >> a >> word >> word >> word >> word >> word >> b >> word >> word){
if(word[5] != '.') cerr << "Error reading, last word: " << word << endl;
works[a - 'A'].id = a;
works[a - 'A'].next.push_back(&works[b - 'A']);
works[b - 'A'].id = b;
works[b - 'A'].prev++;
}
sort(works.begin(), works.end(), compare);
int current = 0;
while(works.size() > current){
if(works[current].id == '0'){
//works.erase(works.begin() + current);
current++;
}
else{
if(works[current].prev == 0){
cout << works[current].id;
for(int i = 0; i < works[current].next.size(); i++) works[current].next[i]->prev--;
works[current].id = '0';
current = 0;
}
else{
current++;
}
}
// cout << works.size() << " - " << current << endl;
}
cout << endl;
}
| 22.627451 | 87 | 0.548527 | bbglab |
e494de65fb3756ac707e9c54cc9904d391a1588d | 3,487 | cpp | C++ | src/OutputWindow.cpp | kmachnicki/houseOnFire | eac4aaf3ed6d8e3b8359f58737eeeb127105c058 | [
"MIT"
] | null | null | null | src/OutputWindow.cpp | kmachnicki/houseOnFire | eac4aaf3ed6d8e3b8359f58737eeeb127105c058 | [
"MIT"
] | null | null | null | src/OutputWindow.cpp | kmachnicki/houseOnFire | eac4aaf3ed6d8e3b8359f58737eeeb127105c058 | [
"MIT"
] | null | null | null | #include "OutputWindow.hpp"
#include "Firefighter.hpp"
#include "Arsonist.hpp"
OutputWindow::OutputWindow()
: m_screen(Coords(0,0))
{
initscr();
cbreak();
noecho();
start_color();
curs_set(FALSE);
init_pair(1, COLOR_WHITE, COLOR_YELLOW);
init_pair(2, COLOR_WHITE, COLOR_RED);
init_pair(3, COLOR_WHITE, COLOR_GREEN);
refresh();
getmaxyx(stdscr, m_screen.y, m_screen.x);
m_firefightersWindow.window = newwin(m_screen.y / 2, (m_screen.x / 3), 0, 0);
m_arsonistsWindow.window = newwin(m_screen.y / 2, (m_screen.x / 3), 0, (m_screen.x / 3));
m_houseWindow.window = newwin(m_screen.y / 2, (m_screen.x / 3), 0,
(m_screen.x / 3) + (m_screen.x / 3));
m_resourcesWindow.window = newwin(m_screen.y / 2, m_screen.x, m_screen.y / 2, 0);
mvwprintw(m_firefightersWindow.window, 0, 0, "Firefighters");
mvwprintw(m_arsonistsWindow.window, 0, 0, "Arsonists");
mvwprintw(m_houseWindow.window, 0, 0, "House");
mvwprintw(m_resourcesWindow.window, 0, 0, "Resources");
wrefresh(m_firefightersWindow.window);
wrefresh(m_arsonistsWindow.window);
wrefresh(m_houseWindow.window);
wrefresh(m_resourcesWindow.window);
}
OutputWindow::~OutputWindow()
{
endwin();
}
void OutputWindow::refreshFirefighters(unsigned id, std::string status)
{
std::unique_lock<std::mutex> lock(m_screenLock);
m_firefighters[id] = status;
std::string message;
unsigned i = 0;
for (auto it = m_firefighters.begin(); it != m_firefighters.end(); ++it, ++i)
{
message = "ID: " + std::to_string(it->first) + ": " + it->second;
move(i + 2, 0);
wclrtoeol(m_firefightersWindow.window);
refresh();
mvwprintw(m_firefightersWindow.window, i + 2, 0, message.c_str());
}
wrefresh(m_firefightersWindow.window);
}
void OutputWindow::refreshArsonists(unsigned id, std::string status)
{
std::unique_lock<std::mutex> lock(m_screenLock);
m_arsonists[id] = status;
std::string message;
unsigned i = 0;
for (auto it = m_arsonists.begin(); it != m_arsonists.end(); ++it, ++i)
{
message = "ID: " + std::to_string(it->first) + ": " + it->second;
move(i + 2, 0);
wclrtoeol(m_arsonistsWindow.window);
refresh();
mvwprintw(m_arsonistsWindow.window, i + 2, 0, message.c_str());
}
wrefresh(m_arsonistsWindow.window);
}
void OutputWindow::refreshResources(unsigned numOfHatchets, unsigned numOfFirehoses, unsigned numOfHelmets,
unsigned numOfMatches, unsigned numOfFuel)
{
std::unique_lock<std::mutex> lock(m_screenLock);
std::string message;
message = "Hatches: " + std::to_string(numOfHatchets) + " Firehoses: " + std::to_string(numOfFirehoses)
+ " Helmets: " + std::to_string(numOfHelmets) + " Matches: " + std::to_string(numOfMatches)
+ " Fuel: " + std::to_string(numOfFuel);
move(2, 0);
wclrtoeol(m_resourcesWindow.window);
refresh();
mvwprintw(m_resourcesWindow.window, 2, 0, message.c_str());
wrefresh(m_resourcesWindow.window);
}
void OutputWindow::refreshHouse(unsigned houseFireSize)
{
std::unique_lock<std::mutex> lock(m_screenLock);
std::string message;
message = "Destruction level: " + std::to_string(houseFireSize) + "%";
move(2, 0);
wclrtoeol(m_houseWindow.window);
refresh();
mvwprintw(m_houseWindow.window, 2, 0, message.c_str());
wrefresh(m_houseWindow.window);
}
| 34.524752 | 107 | 0.65357 | kmachnicki |
e499dbf5d66a39f8b17ecf75d0ac31ae93f96261 | 12,449 | cpp | C++ | libs/vm_modules/tests/unit/array_tests.cpp | devjsc/ledger-1 | 2aa68e05b9f9c10a9971fc8ddf4848695511af3c | [
"Apache-2.0"
] | null | null | null | libs/vm_modules/tests/unit/array_tests.cpp | devjsc/ledger-1 | 2aa68e05b9f9c10a9971fc8ddf4848695511af3c | [
"Apache-2.0"
] | null | null | null | libs/vm_modules/tests/unit/array_tests.cpp | devjsc/ledger-1 | 2aa68e05b9f9c10a9971fc8ddf4848695511af3c | [
"Apache-2.0"
] | null | null | null | //------------------------------------------------------------------------------
//
// Copyright 2018-2019 Fetch.AI Limited
//
// 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 "vm_test_toolkit.hpp"
namespace {
class ArrayTests : public ::testing::Test
{
public:
VmTestToolkit toolkit;
};
TEST_F(ArrayTests, count_returns_the_number_of_elements_in_the_array)
{
static char const *TEXT = R"(
function main()
print(Array<UInt32>(2).count());
print('-');
print(Array<Array<UInt32>>(5).count());
endfunction
)";
ASSERT_TRUE(toolkit.Compile(TEXT));
ASSERT_TRUE(toolkit.Run());
ASSERT_EQ(toolkit.stdout(), "2-5");
}
TEST_F(ArrayTests, count_returns_zero_if_the_array_is_empty)
{
static char const *TEXT = R"(
function main()
print(Array<UInt32>(0).count());
print('-');
print(Array<Array<UInt32>>(0).count());
endfunction
)";
ASSERT_TRUE(toolkit.Compile(TEXT));
ASSERT_TRUE(toolkit.Run());
ASSERT_EQ(toolkit.stdout(), "0-0");
}
TEST_F(ArrayTests, append_adds_one_element_at_the_end_of_the_array)
{
static char const *TEXT = R"(
function main()
var data = Array<UInt32>(2);
data[0] = 1u32;
data[1] = 2u32;
data.append(42u32);
print(data);
endfunction
)";
ASSERT_TRUE(toolkit.Compile(TEXT));
ASSERT_TRUE(toolkit.Run());
ASSERT_EQ(toolkit.stdout(), "[1, 2, 42]");
}
TEST_F(ArrayTests, append_is_statically_type_safe_with_numeric_arrays)
{
static char const *TEXT = R"(
function main()
var data = Array<UInt32>(1);
data.append(2u16);
endfunction
)";
ASSERT_FALSE(toolkit.Compile(TEXT));
}
TEST_F(ArrayTests, append_accepts_objects)
{
static char const *TEXT = R"(
function main()
var data = Array<Array<Int32>>(1);
print(data.count());
print('-');
data.append(Array<Int32>(1));
data.append(Array<Int32>(2));
print(data.count());
endfunction
)";
ASSERT_TRUE(toolkit.Compile(TEXT));
ASSERT_TRUE(toolkit.Run());
ASSERT_EQ(toolkit.stdout(), "1-3");
}
TEST_F(ArrayTests, append_is_statically_type_safe_with_object_arrays)
{
static char const *TEXT = R"(
function main()
var data = Array<Array<UInt32>>(1);
data[0] = Array<UInt32>(1);
data.append(Array<Int16>(1));
endfunction
)";
ASSERT_FALSE(toolkit.Compile(TEXT));
}
TEST_F(ArrayTests, popBack_removes_the_last_element_and_returns_it)
{
static char const *TEXT = R"(
function main()
var data = Array<Int32>(3);
data[0] = 10;
data[1] = 20;
data[2] = 30;
var popped = data.popBack();
print(popped);
print('-');
print(data);
endfunction
)";
ASSERT_TRUE(toolkit.Compile(TEXT));
ASSERT_TRUE(toolkit.Run());
ASSERT_EQ(toolkit.stdout(), "30-[10, 20]");
}
TEST_F(ArrayTests, popBack_works_with_arrays_of_objects)
{
static char const *TEXT = R"(
function main()
var data = Array<Array<Int32>>(3);
data[0] = Array<Int32>(1);
data[1] = Array<Int32>(1);
data[2] = Array<Int32>(1);
data[0][0]=10; data[1][0]=20; data[2][0]=30;
print(data.count());
print('-');
var popped = data.popBack();
print(data.count());
print('-');
print(popped);
print('-');
print(data[0]);
print('-');
print(data[1]);
endfunction
)";
ASSERT_TRUE(toolkit.Compile(TEXT));
ASSERT_TRUE(toolkit.Run());
ASSERT_EQ(toolkit.stdout(), "3-2-[30]-[10]-[20]");
}
TEST_F(ArrayTests, popBack_fails_if_array_is_empty)
{
static char const *TEXT = R"(
function main()
var data = Array<Int32>(0);
data.popBack();
endfunction
)";
ASSERT_TRUE(toolkit.Compile(TEXT));
ASSERT_FALSE(toolkit.Run());
}
TEST_F(ArrayTests,
when_passed_an_integer_N_popBack_removes_the_last_N_elements_and_returns_them_as_an_array)
{
static char const *TEXT = R"(
function main()
var data = Array<Int32>(3);
data[0] = 10;
data[1] = 20;
data[2] = 30;
var popped = data.popBack(2);
print(popped);
print('-');
print(data);
endfunction
)";
ASSERT_TRUE(toolkit.Compile(TEXT));
ASSERT_TRUE(toolkit.Run());
ASSERT_EQ(toolkit.stdout(), "[20, 30]-[10]");
}
TEST_F(ArrayTests, when_passed_an_integer_N_popBack_works_for_arrays_of_objects)
{
static char const *TEXT = R"(
function main()
var data = Array<Array<Int32>>(3);
data[0] = Array<Int32>(1);
data[1] = Array<Int32>(1);
data[2] = Array<Int32>(1);
data[0][0]=10; data[1][0]=20; data[2][0]=30;
print(data.count());
print('-');
var popped = data.popBack(2);
print(data.count());
print('-');
print(popped.count());
print('-');
print(popped[0]);
print('-');
print(popped[1]);
print('-');
print(data[0]);
endfunction
)";
ASSERT_TRUE(toolkit.Compile(TEXT));
ASSERT_TRUE(toolkit.Run());
ASSERT_EQ(toolkit.stdout(), "3-1-2-[20]-[30]-[10]");
}
TEST_F(ArrayTests, when_passed_zero_popBack_does_not_mutate_its_array_and_returns_an_empty_array)
{
static char const *TEXT = R"(
function main()
var data = Array<Int32>(3);
data[0] = 10;
data[1] = 20;
data[2] = 30;
var popped = data.popBack(0);
print(popped);
print('-');
print(data);
endfunction
)";
ASSERT_TRUE(toolkit.Compile(TEXT));
ASSERT_TRUE(toolkit.Run());
ASSERT_EQ(toolkit.stdout(), "[]-[10, 20, 30]");
}
TEST_F(ArrayTests, when_passed_a_negative_number_popBack_fails)
{
static char const *TEXT = R"(
function main()
var data = Array<Int32>(3);
data[0] = 10;
data[1] = 20;
data[2] = 30;
var popped = data.popBack(-3);
endfunction
)";
ASSERT_TRUE(toolkit.Compile(TEXT));
ASSERT_FALSE(toolkit.Run());
}
TEST_F(ArrayTests, popFront_removes_the_first_element_and_returns_it)
{
static char const *TEXT = R"(
function main()
var data = Array<Int32>(3);
data[0] = 10;
data[1] = 20;
data[2] = 30;
var popped = data.popFront();
print(popped);
print('-');
print(data);
endfunction
)";
ASSERT_TRUE(toolkit.Compile(TEXT));
ASSERT_TRUE(toolkit.Run());
ASSERT_EQ(toolkit.stdout(), "10-[20, 30]");
}
TEST_F(ArrayTests, popFront_works_with_arrays_of_objects)
{
static char const *TEXT = R"(
function main()
var data = Array<Array<Int32>>(3);
data[0] = Array<Int32>(1);
data[1] = Array<Int32>(1);
data[2] = Array<Int32>(1);
data[0][0] = 10; data[1][0] = 20; data[2][0] = 30;
print(data.count());
print('-');
var popped = data.popFront();
print(data.count());
print('-');
print(popped);
print('-');
print(data[0]);
print('-');
print(data[1]);
endfunction
)";
ASSERT_TRUE(toolkit.Compile(TEXT));
ASSERT_TRUE(toolkit.Run());
ASSERT_EQ(toolkit.stdout(), "3-2-[10]-[20]-[30]");
}
TEST_F(ArrayTests, popFront_fails_if_array_is_empty)
{
static char const *TEXT = R"(
function main()
var data = Array<Int32>(0);
data.popFront();
endfunction
)";
ASSERT_TRUE(toolkit.Compile(TEXT));
ASSERT_FALSE(toolkit.Run());
}
TEST_F(ArrayTests,
when_passed_an_integer_N_popFront_removes_the_last_N_elements_and_returns_them_as_an_array)
{
static char const *TEXT = R"(
function main()
var data = Array<Int32>(3);
data[0] = 10;
data[1] = 20;
data[2] = 30;
var popped = data.popFront(2);
print(popped);
print('-');
print(data);
endfunction
)";
ASSERT_TRUE(toolkit.Compile(TEXT));
ASSERT_TRUE(toolkit.Run());
ASSERT_EQ(toolkit.stdout(), "[10, 20]-[30]");
}
TEST_F(ArrayTests, when_passed_an_integer_N_popFront_works_for_arrays_of_objects)
{
static char const *TEXT = R"(
function main()
var data = Array<Array<Int32>>(3);
data[0] = Array<Int32>(1);
data[1] = Array<Int32>(1);
data[2] = Array<Int32>(1);
data[0][0]=10; data[1][0]=20; data[2][0]=30;
print(data.count());
print('-');
var popped = data.popFront(2);
print(data.count());
print('-');
print(popped.count());
print('-');
print(popped[0]);
print('-');
print(popped[1]);
print('-');
print(data[0]);
endfunction
)";
ASSERT_TRUE(toolkit.Compile(TEXT));
ASSERT_TRUE(toolkit.Run());
ASSERT_EQ(toolkit.stdout(), "3-1-2-[10]-[20]-[30]");
}
TEST_F(ArrayTests, when_passed_zero_popFront_does_not_mutate_its_array_and_returns_an_empty_array)
{
static char const *TEXT = R"(
function main()
var data = Array<Int32>(3);
data[0] = 10;
data[1] = 20;
data[2] = 30;
var popped = data.popFront(0);
print(popped);
print('-');
print(data);
endfunction
)";
ASSERT_TRUE(toolkit.Compile(TEXT));
ASSERT_TRUE(toolkit.Run());
ASSERT_EQ(toolkit.stdout(), "[]-[10, 20, 30]");
}
TEST_F(ArrayTests, when_passed_a_negative_number_popFront_fails)
{
static char const *TEXT = R"(
function main()
var data = Array<Int32>(3);
data[0] = 10;
data[1] = 20;
data[2] = 30;
var popped = data.popFront(-3);
endfunction
)";
ASSERT_TRUE(toolkit.Compile(TEXT));
ASSERT_FALSE(toolkit.Run());
}
TEST_F(ArrayTests, reverse_inverts_the_order_of_elements)
{
static char const *TEXT = R"(
function main()
var data = Array<Int32>(3);
data[0] = 10;
data[1] = 20;
data[2] = 30;
data.reverse();
print(data);
endfunction
)";
ASSERT_TRUE(toolkit.Compile(TEXT));
ASSERT_TRUE(toolkit.Run());
ASSERT_EQ(toolkit.stdout(), "[30, 20, 10]");
}
TEST_F(ArrayTests, reverse_of_an_empty_array_is_a_noop)
{
static char const *TEXT = R"(
function main()
var data = Array<Int32>(0);
data.reverse();
print(data);
endfunction
)";
ASSERT_TRUE(toolkit.Compile(TEXT));
ASSERT_TRUE(toolkit.Run());
ASSERT_EQ(toolkit.stdout(), "[]");
}
TEST_F(ArrayTests, extend_appends_the_elements_of_the_argument_array_in_order)
{
static char const *TEXT = R"(
function main()
var data1 = Array<Int32>(3);
data1[0] = 1;
data1[1] = 2;
data1[2] = 3;
var data2 = Array<Int32>(2);
data2[0] = 5;
data2[1] = 4;
data1.extend(data2);
print(data1);
endfunction
)";
ASSERT_TRUE(toolkit.Compile(TEXT));
ASSERT_TRUE(toolkit.Run());
ASSERT_EQ(toolkit.stdout(), "[1, 2, 3, 5, 4]");
}
TEST_F(ArrayTests, extend_called_with_an_empty_array_is_a_noop)
{
static char const *TEXT = R"(
function main()
var data1 = Array<Int32>(3);
data1[0] = 1;
data1[1] = 2;
data1[2] = 3;
var data2 = Array<Int32>(0);
data1.extend(data2);
print(data1);
endfunction
)";
ASSERT_TRUE(toolkit.Compile(TEXT));
ASSERT_TRUE(toolkit.Run());
ASSERT_EQ(toolkit.stdout(), "[1, 2, 3]");
}
TEST_F(ArrayTests, extend_fails_if_called_with_an_array_of_different_type)
{
static char const *TEXT = R"(
function main()
var data1 = Array<Int32>(1);
data1[0] = 1;
var data2 = Array<UInt64>(1);
data2[0] = 1;
data1.extend(data2);
print(data1);
endfunction
)";
ASSERT_FALSE(toolkit.Compile(TEXT));
}
TEST_F(ArrayTests, extend_does_not_mutate_its_argument)
{
static char const *TEXT = R"(
function main()
var data1 = Array<Int32>(2);
data1[0] = 10;
data1[1] = 20;
var data2 = Array<Int32>(3);
data2[0] = 50;
data2[1] = 40;
data2[2] = 30;
data1.extend(data2);
print(data2);
endfunction
)";
ASSERT_TRUE(toolkit.Compile(TEXT));
ASSERT_TRUE(toolkit.Run());
ASSERT_EQ(toolkit.stdout(), "[50, 40, 30]");
}
} // namespace
| 21.538062 | 98 | 0.601012 | devjsc |
e49b955c2dc3aa8a8c91eb256165625354e1102b | 4,159 | cpp | C++ | ibp_external__libtommatch_set01__bn_fast_s_mp_mul_high_digs.cpp | dmitry-lipetsk/libtommath-for-ibprovider--set01 | b7b8e7cf76bd0b2d265d0c31a99836a3b4bad882 | [
"WTFPL"
] | null | null | null | ibp_external__libtommatch_set01__bn_fast_s_mp_mul_high_digs.cpp | dmitry-lipetsk/libtommath-for-ibprovider--set01 | b7b8e7cf76bd0b2d265d0c31a99836a3b4bad882 | [
"WTFPL"
] | null | null | null | ibp_external__libtommatch_set01__bn_fast_s_mp_mul_high_digs.cpp | dmitry-lipetsk/libtommath-for-ibprovider--set01 | b7b8e7cf76bd0b2d265d0c31a99836a3b4bad882 | [
"WTFPL"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////
#include <_pch_.h>
#pragma hdrstop
#include "source/external/libtommath/set01/ibp_external__libtommatch_set01__tommath_private.h"
#include <structure/t_limits.h>
namespace ibp{namespace external{namespace libtommath{namespace set01{
////////////////////////////////////////////////////////////////////////////////
/* LibTomMath, multiple-precision integer library -- Tom St Denis
*
* LibTomMath is a library that provides multiple-precision
* integer arithmetic as well as number theoretic functionality.
*
* The library was designed directly after the MPI library by
* Michael Fromberger but has been written from scratch with
* additional optimizations in place.
*
* The library is free for all purposes without any express
* guarantee it works.
*
* Tom St Denis, tomstdenis@gmail.com, http://libtom.org
*/
/* this is a modified version of fast_s_mul_digs that only produces
* output digits *above* digs. See the comments for fast_s_mul_digs
* to see how it works.
*
* This is used in the Barrett reduction since for one of the multiplications
* only the higher digits were needed. This essentially halves the work.
*
* Based on Algorithm 14.12 on pp.595 of HAC.
*/
mp_err fast_s_mp_mul_high_digs(const mp_int* const a,
const mp_int* const b,
mp_int* const c,
mp_int_size_type const digs)
{
DEBUG_CODE(mp_debug__check_int__total(a);)
DEBUG_CODE(mp_debug__check_int__total(b);)
DEBUG_CODE(mp_debug__check_int__light(c);)
assert(a->used <= (MP_WARRAY/2));
assert(b->used <= (MP_WARRAY/2));
assert((digs == 0) || (digs > 0));
assert(digs <= a->used ||
digs <= b->used);
mp_err res;
if(mp_iszero(a) || mp_iszero(b))
{
mp_zero(c);
return MP_OKAY;
}//if
assert(a->used > 0);
assert(b->used > 0);
/* grow the destination as required */
const mp_int::size_type pa = (a->used + b->used);
if((res = mp_grow(c, pa)) != MP_OKAY)
return res;
/* number of output digits to produce */
assert(pa == (a->used + b->used));
mp_digit W[MP_WARRAY];
/* clear the carry */
mp_word _W = 0;
assert(digs <= pa);
for(mp_int::size_type ix = digs; ix != pa; ++ix)
{
assert(ix < pa);
assert(b->used > 0);
/* get offsets into the two bignums */
const mp_int::size_type ty = MIN(b->used - 1, ix);
assert((ty == 0) || (ty > 0));
assert(ty < b->used);
assert(ix >= ty);
const mp_int::size_type tx = (ix - ty);
assert((tx == 0) || (tx > 0));
if(tx < a->used)
{
/* setup temp aliases */
const mp_digit* tmpx = (a->dp + tx);
const mp_digit* tmpy = (b->dp + ty);
// this is the number of times the loop will iterrate, essentially its
// while (tx++ < a->used && ty-- >= 0) { ... }
const mp_int::size_type iy = MIN(a->used - tx, ty + 1);
assert(iy > 0);
/* execute loop */
for(const mp_digit* const _ex = (tmpx + iy); tmpx != _ex; ++tmpx, --tmpy)
{
assert(tmpx >= (a->dp));
assert(tmpx < (a->dp + a->used));
assert(tmpy >= (b->dp));
assert(tmpy < (b->dp + b->used));
const mp_word m = (static_cast<mp_word>(*tmpx) * static_cast<mp_word>(*tmpy));
assert(m < (structure::t_numeric_limits<mp_word>::max_value() - _W));
_W += m;
}//for
}//if(tx < a->used)
/* store term */
assert((ix == 0) || (ix > 0));
assert(ix < _DIM_(W));
W[ix] = ((mp_digit)_W) & MP_MASK;
/* make next carry */
_W = _W >> ((mp_word)MP_DIGIT_BIT);
}//for is
/* setup dest */
if(pa < c->used)
{
std::fill(c->dp + pa, c->dp + c->used, 0);
}//if
assert(digs <= pa);
for(mp_int::size_type ix = digs; ix != pa ; ++ix)
{
assert(ix < pa);
assert((ix == 0) || (ix > 0));
assert(ix < _DIM_(W));
/* now extract the previous digit [below the carry] */
assert(W[ix] <= MP_MASK);
c->dp[ix] = W[ix];
}//for ix
c->used = pa;
mp_clamp(c);
return MP_OKAY;
}//fast_s_mp_mul_high_digs
////////////////////////////////////////////////////////////////////////////////
}/*nms set01*/}/*nms libtommath*/}/*nms external*/}/*nms ibp*/
| 25.054217 | 94 | 0.577062 | dmitry-lipetsk |
e4a02f0ce3bd8d4eb4f89b9be5992b51654a7390 | 901 | cpp | C++ | M5Stack_MultiApp_Firmware/Apps/appCfgBrightness.cpp | botofancalin/M5Stack_MultiApp_Firmware | 05894d1d61cab7015d17109e9e31f24d11ba54e1 | [
"MIT"
] | 21 | 2018-04-07T21:10:54.000Z | 2020-06-08T18:10:05.000Z | M5Stack_MultiApp_Firmware/Apps/appCfgBrightness.cpp | botofancalin/M5Stack_MultiApp_Firmware | 05894d1d61cab7015d17109e9e31f24d11ba54e1 | [
"MIT"
] | 1 | 2018-04-25T07:38:22.000Z | 2018-04-25T07:38:22.000Z | M5Stack_MultiApp_Firmware/Apps/appCfgBrightness.cpp | botofancalin/M5Stack_MultiApp_Firmware | 05894d1d61cab7015d17109e9e31f24d11ba54e1 | [
"MIT"
] | 5 | 2018-04-01T14:43:20.000Z | 2020-05-15T10:13:34.000Z | #include "../apps.h"
void appCfgBrigthness()
{
byte tmp_brigth = byte(EEPROM.read(0));
byte tmp_lbrigth = 0;
MyMenu.drawAppMenu(F("DISPLAY BRIGHTNESS"), F("-"), F("OK"), F("+"));
while (M5.BtnB.wasPressed())
{
M5.update();
}
while (!M5.BtnB.wasPressed())
{
if (M5.BtnA.wasPressed() && tmp_brigth >= 16)
{
tmp_brigth = tmp_brigth - 16;
}
if (M5.BtnC.wasPressed() && tmp_brigth <= 239)
{
tmp_brigth = tmp_brigth + 16;
}
if (tmp_lbrigth != tmp_brigth)
{
tmp_lbrigth = tmp_brigth;
EEPROM.write(0, tmp_lbrigth);
EEPROM.commit();
M5.lcd.setBrightness(byte(EEPROM.read(0)));
MyMenu.windowClr();
M5.Lcd.drawNumber(byte(EEPROM.read(0)), 120, 90, 6);
}
M5.update();
}
MyMenu.show();
} | 25.027778 | 73 | 0.502775 | botofancalin |
e4a2a680843d3323f4b8f895886e0253e38c97bb | 339 | cpp | C++ | applications/TexturePainter/main.cpp | billhj/Etoile2015 | c9311fc2a901cd60b2aeead5462ca8d6f7c5aa3a | [
"Apache-2.0"
] | null | null | null | applications/TexturePainter/main.cpp | billhj/Etoile2015 | c9311fc2a901cd60b2aeead5462ca8d6f7c5aa3a | [
"Apache-2.0"
] | null | null | null | applications/TexturePainter/main.cpp | billhj/Etoile2015 | c9311fc2a901cd60b2aeead5462ca8d6f7c5aa3a | [
"Apache-2.0"
] | null | null | null | #include "TexturePainter.h"
#include <QtGui/QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QFile stylesheet("./styles/stylesheet.txt");
stylesheet.open(QFile::ReadOnly);
QString setSheet = QLatin1String(stylesheet.readAll());
a.setStyleSheet(setSheet);
TexturePainter w;
w.show();
return a.exec();
}
| 22.6 | 56 | 0.731563 | billhj |
e4a5a710402c5b46dd6f444f48194d7655726ac7 | 1,667 | cpp | C++ | RealFluid/src/App/Application/EventHandlers.cpp | cypherix93/cse328-project | 8239f7ddc7d104607649dd24670584b91be8e162 | [
"MIT"
] | null | null | null | RealFluid/src/App/Application/EventHandlers.cpp | cypherix93/cse328-project | 8239f7ddc7d104607649dd24670584b91be8e162 | [
"MIT"
] | null | null | null | RealFluid/src/App/Application/EventHandlers.cpp | cypherix93/cse328-project | 8239f7ddc7d104607649dd24670584b91be8e162 | [
"MIT"
] | null | null | null | #include "EventHandlers.h"
#include <Core/Physics/NavierStokesSolver/NavierStokesSolver.h>
/* Event Handlers*/
void InitHandler()
{
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_DEPTH_TEST);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_NORMALIZE);
glEnable(GL_POINT_SMOOTH);
glShadeModel(GL_SMOOTH);
CELL_GRID = new Grid{ 16, 16, 1 };
CELL_GRID_OPTIONS = new GridDrawOptions();
CELL_GRID_OPTIONS->CellDimensions = 40;
int windowWidth, windowHeight;
windowWidth = CELL_GRID->CellsX * CELL_GRID_OPTIONS->CellDimensions;
windowHeight = CELL_GRID->CellsY * CELL_GRID_OPTIONS->CellDimensions;
APPLICATION->GetWindowManager()->ResizeWindow(windowWidth, windowHeight);
glViewport(0, 0, windowWidth, windowHeight);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
// gluPerspective(45.0, (double)WINDOW_WIDTH / (double)WINDOW_HEIGHT, 1.0, 200.0);
gluOrtho2D(0, windowWidth, 0, windowHeight);
}
void DrawHandler()
{
ProcessGrid(CELL_GRID);
glClearColor(0.0f, 0.10f, 0.20f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
// glTranslatef(0.0f, 0.0f, -8.0f);
/*glRotatef(_angleX, 1.0f, 0.0f, 0.0f);
glRotatef(_angleY, 0.0f, 1.0f, 0.0f);*/
// glLineWidth(2.0f);
//options.DrawCellOutline = false;
DrawCellGrid(CELL_GRID, CELL_GRID_OPTIONS);
}
// Called when a keyboard key is pressed
void KeyboardButtonHandler(SDL_KeyboardEvent evt)
{
}
//Called when the mouse button is pressed
void MouseButtonHandler(SDL_MouseButtonEvent evt)
{
}
| 26.460317 | 89 | 0.710258 | cypherix93 |
e4acd3c0442de01e743af498da7efc818232acc5 | 1,224 | cpp | C++ | e-olymp/Transport-system.cpp | MaGnsio/CP-Problems | a7f518a20ba470f554b6d54a414b84043bf209c5 | [
"Unlicense"
] | 3 | 2020-11-01T06:31:30.000Z | 2022-02-21T20:37:51.000Z | e-olymp/Transport-system.cpp | MaGnsio/CP-Problems | a7f518a20ba470f554b6d54a414b84043bf209c5 | [
"Unlicense"
] | null | null | null | e-olymp/Transport-system.cpp | MaGnsio/CP-Problems | a7f518a20ba470f554b6d54a414b84043bf209c5 | [
"Unlicense"
] | 1 | 2021-05-05T18:56:31.000Z | 2021-05-05T18:56:31.000Z | /**
* author: MaGnsi0
* created: 09/06/2021 00:48:50
**/
#include <bits/stdc++.h>
using namespace std;
void bfs(vector<vector<int>>& adj, vector<int>& d, int& s) {
queue<int> q;
q.push(s);
d[s] = 0;
while (!q.empty()) {
int v = q.front();
q.pop();
for (auto& u : adj[v]) {
if (d[u] == -1) {
q.push(u);
d[u] = d[v] + 1;
}
}
}
}
int main() {
ios_base::sync_with_stdio (0); cin.tie (0); cout.tie (0);
int n, m, s, t, ans = 0;
cin >> n >> m >> s >> t;
set<pair<int, int>> edges;
vector<vector<int>> adj(n + 1);
for (int i = 0; i < m; ++i) {
int u, v;
cin >> u >> v;
adj[u].push_back(v);
adj[v].push_back(u);
edges.insert({min(u, v), max(u, v)});
}
vector<int> ds(n + 1, -1), dt(n + 1, -1);
bfs(adj, ds, s);
bfs(adj, dt, t);
for (int i = 1; i <= n; ++i) {
for (int j = i + 1; j <= n; ++j) {
if (edges.count({i, j})) {
continue;
}
if (ds[i] + 1 + dt[j] >= ds[t] && dt[i] + 1 + ds[j] >= ds[t]) {
ans++;
}
}
}
cout << ans;
}
| 23.538462 | 75 | 0.378268 | MaGnsio |
e4b4475eea2c48d572a8a8f0653bfaccc22538e9 | 1,534 | cpp | C++ | binarysearch.cpp | AKoudounis/refactored-journey | 81719c57104f14b141f0f7cd2aa805f9007ed79e | [
"MIT"
] | null | null | null | binarysearch.cpp | AKoudounis/refactored-journey | 81719c57104f14b141f0f7cd2aa805f9007ed79e | [
"MIT"
] | null | null | null | binarysearch.cpp | AKoudounis/refactored-journey | 81719c57104f14b141f0f7cd2aa805f9007ed79e | [
"MIT"
] | null | null | null | #include <iostream>
#include <stdlib.h>
#include <algorithm>
using namespace std;
template<class T>
int binarySearch(T* arr, T* left, T* right, T x)
{
int result = -1;
if (*left > *right){
return result;
}
T* mid = left + (right - left) / 2;
if (*mid==x){
return mid-arr;
}
if (x <* mid){
return binarySearch(arr, left, mid - 1, x);
}
else if (x > *mid){
return binarySearch(arr, mid + 1, right, x);
}
return result;
}
/* if (right >= left) {
int mid = left + (right - left) / 2;
if (arr[mid] == x) {
return mid;
}
//[,,,,,x,,,,,mid,,,,,,,,,]
if (arr[mid] > x) {
return binarySearch(arr, left, mid - 1, x);
}
//[,,,,,,,,,,,mid,,,,,x,,,]
return binarySearch(arr, mid + 1, right, x);
}
return -1;
*/
int main()
{
int size = 6;
int* arr = new int [size];
for (int i=0; i<size; i++) //random array values
{
arr[i]= {rand() %100};
}
sort(arr,arr+size); //array sorter
for (int i=0; i<size; i++) {
cout << arr[i] << ", ";
}
int x = 24;
int result = binarySearch(arr, arr, arr + size -1, x);
if (result == -1)
{
cout << " Number is not found in array search";
}
else
{
cout << " Number is found in position (starting from 0) " << result;
}
return 0;
}
| 18.481928 | 78 | 0.4309 | AKoudounis |
e4bae320dd28ebc1f4219ea1c1b09318a3b2e9f2 | 585 | cc | C++ | 0_leetcode/121_best-time-to-buy-and-sell-stock/maxProfit2.cc | amdfansheng/alogrithm | b2e1dd4094b766895dda8c8fc2cbb2e37e6aa22d | [
"MIT"
] | null | null | null | 0_leetcode/121_best-time-to-buy-and-sell-stock/maxProfit2.cc | amdfansheng/alogrithm | b2e1dd4094b766895dda8c8fc2cbb2e37e6aa22d | [
"MIT"
] | null | null | null | 0_leetcode/121_best-time-to-buy-and-sell-stock/maxProfit2.cc | amdfansheng/alogrithm | b2e1dd4094b766895dda8c8fc2cbb2e37e6aa22d | [
"MIT"
] | null | null | null | // 自己写的
// 超出时间限制 O(n^2)
#include <cstdio>
#include <climits>
#include <vector>
using namespace std;
class Solution {
public:
int maxProfit(vector<int>& prices)
{
int max{}, min{INT_MAX};
for (auto &&price : prices) {
if (price - min > max) max = price - min;
if (min > price) min = price;
}
return max;
}
};
int main()
{
//vector<int> v = {7,1,5,3,6,4};
//vector<int> v = {1,2,3,4,5};
//vector<int> v = {7,6,4,3,1};
vector<int> v = {2,4,1};
Solution s;
printf("%d\n", s.maxProfit(v));
}
| 17.727273 | 53 | 0.504274 | amdfansheng |
e4c05c71427a74d04d2776cbafedbb5af695d9a5 | 12,134 | cc | C++ | src/2d/mpi/tausch_exchanger.cc | cedar-framework/cedar | 9fb53ec221738b8dd16dfb31dc9a18d69fc2cc44 | [
"BSD-3-Clause"
] | 9 | 2018-03-07T19:15:27.000Z | 2019-02-22T20:10:23.000Z | src/2d/mpi/tausch_exchanger.cc | cedar-framework/cedar | 9fb53ec221738b8dd16dfb31dc9a18d69fc2cc44 | [
"BSD-3-Clause"
] | 5 | 2018-11-13T19:59:46.000Z | 2020-04-09T19:31:25.000Z | src/2d/mpi/tausch_exchanger.cc | cedar-framework/cedar | 9fb53ec221738b8dd16dfb31dc9a18d69fc2cc44 | [
"BSD-3-Clause"
] | 2 | 2018-07-20T01:06:48.000Z | 2019-11-25T12:15:16.000Z | #include <cedar/2d/mpi/tausch_exchanger.h>
extern "C" {
using namespace cedar;
void BMG2_SymStd_SETUP_Tausch(int nog, len_t *dimx, len_t *dimy,
len_t *dimxfine, len_t *dimyfine, int nproci, int nprocj);
}
namespace cedar { namespace cdr2 { namespace mpi {
line_pkg::line_pkg(grid_topo & topo):
datadist{{array<len_t, 2>(2, topo.nproc(0)),
array<len_t, 2>(2, topo.nproc(1))}}
{
}
void tausch_exchanger::setup(std::vector<topo_ptr> topos)
{
this->nlevels = topos.size();
dims[0] = aarray<int, len_t, 2>(topos[0]->nproc(0), nlevels);
dims[1] = aarray<int, len_t, 2>(topos[0]->nproc(1), nlevels);
line_data = std::make_unique<line_pkg>(*topos[0]);
coord[0] = topos[0]->coord(0);
coord[1] = topos[0]->coord(1);
init_gfunc(topos);
init_so(topos);
for (std::size_t lvl = 0; lvl < nlevels; lvl++) {
for (int dir = 0; dir < halo_dir::count; dir++) {
send_active[index(lvl,dir)] = true;
recv_active[index(lvl,dir)] = true;
}
if (not params->periodic[0]) {
if (topos[0]->coord(0) == 0) {
send_active[index(lvl, halo_dir::left)] = false;
recv_active[index(lvl, halo_dir::right)] = false;
}
if (topos[0]->coord(0) == topos[0]->nproc(0) - 1) {
send_active[index(lvl, halo_dir::right)] = false;
recv_active[index(lvl, halo_dir::left)] = false;
}
}
if (not params->periodic[1]) {
if (topos[0]->coord(1) == 0) {
send_active[index(lvl, halo_dir::down)] = false;
recv_active[index(lvl, halo_dir::up)] = false;
}
if (topos[0]->coord(1) == topos[0]->nproc(1) - 1) {
send_active[index(lvl, halo_dir::up)] = false;
recv_active[index(lvl, halo_dir::down)] = false;
}
}
}
init_dims(*topos[0]);
}
void tausch_exchanger::init_dims(grid_topo & topo)
{
auto & dimxfine = dimfine[0];
auto & dimyfine = dimfine[1];
if (topo.dimyfine.size() > 0) {
dimyfine = topo.dimyfine;
} else {
dimyfine.reserve(topo.nproc(1));
for (auto j : range(topo.nproc(1))) {
dimyfine[j] = topo.nlocal(1) - 2;
}
}
if (topo.dimxfine.size() > 0) {
dimxfine = topo.dimxfine;
} else {
dimxfine.reserve(topo.nproc(0));
for (auto i : range(topo.nproc(0))) {
dimxfine[i] = topo.nlocal(0) - 2;
}
}
BMG2_SymStd_SETUP_Tausch(topo.nlevel(),
dims[0].data(), dims[1].data(),
dimxfine.data(), dimyfine.data(),
topo.nproc(0), topo.nproc(1));
init_datadist();
}
void tausch_exchanger::init_datadist()
{
auto & dimxfine = dimfine[0];
auto & dimyfine = dimfine[1];
auto & xdatadist = line_data->datadist[0];
auto & ydatadist = line_data->datadist[1];
xdatadist(0, 0) = 2;
xdatadist(1, 0) = xdatadist(0, 0) + dimxfine[0] - 1;
for (auto i : range<len_t>(1, xdatadist.len(1))) {
xdatadist(0, i) = xdatadist(1, i-1) + 1;
xdatadist(1, i) = xdatadist(0, i) + dimxfine[i] - 1;
}
ydatadist(0, 0) = 2;
ydatadist(1, 0) = ydatadist(0, 0) + dimyfine[0] - 1;
for (auto j : range<len_t>(1, ydatadist.len(1))) {
ydatadist(0, j) = ydatadist(1, j-1) + 1;
ydatadist(1, j) = ydatadist(0, j) + dimyfine[j] - 1;
}
// This bound may not be correct!
line_data->linebuf.resize(std::max(dimxfine[0], dimyfine[0])*(8+1)*std::max(ydatadist.len(1), xdatadist.len(1)));
}
void tausch_exchanger::init_gfunc(std::vector<topo_ptr> & topos)
{
std::vector<std::vector<std::array<int, 4> > > remote_spec(halo_dir::count * nlevels);
std::vector<std::vector<std::array<int, 4> > > local_spec(halo_dir::count * nlevels);
std::vector<int> remote_remoteMpiRank(halo_dir::count * nlevels);
std::vector<int> local_remoteMpiRank(halo_dir::count * nlevels);
send_active.reserve(halo_dir::count * nlevels);
recv_active.reserve(halo_dir::count * nlevels);
int rank;
MPI_Comm_rank(topos[0]->comm, &rank);
for (std::size_t lvl = 0; lvl < nlevels; lvl++) {
set_level_spec(lvl, rank,
*topos[lvl],
remote_spec, local_spec,
remote_remoteMpiRank, local_remoteMpiRank);
}
int nbuf = 1;
tausch = std::make_unique<Tausch>(topos[0]->comm);
for (std::size_t i = 0; i < halo_dir::count * nlevels; i++) {
tausch->addSendHaloInfo(local_spec[i], sizeof(real_t), nbuf, local_remoteMpiRank[i]);
tausch->addRecvHaloInfo(remote_spec[i], sizeof(real_t), nbuf, remote_remoteMpiRank[i]);
}
}
void tausch_exchanger::init_so(std::vector<topo_ptr> & topos)
{
std::vector<std::vector<std::array<int, 4> > > remote_spec(halo_dir::count * nlevels);
std::vector<std::vector<std::array<int, 4> > > local_spec(halo_dir::count * nlevels);
std::vector<int> remote_remoteMpiRank(halo_dir::count * nlevels);
std::vector<int> local_remoteMpiRank(halo_dir::count * nlevels);
send_active.reserve(halo_dir::count * nlevels);
recv_active.reserve(halo_dir::count * nlevels);
int rank;
MPI_Comm_rank(topos[0]->comm, &rank);
for (std::size_t lvl = 0; lvl < nlevels; lvl++) {
set_level_spec_so(lvl, rank,
*topos[lvl],
remote_spec, local_spec,
remote_remoteMpiRank, local_remoteMpiRank);
}
int nbuf = stencil_ndirs<nine_pt>::value;
tausch_so = std::make_unique<Tausch>(topos[0]->comm);
for (std::size_t i = 0; i < halo_dir::count * nlevels; i++) {
tausch_so->addSendHaloInfo(local_spec[i], sizeof(real_t), nbuf, local_remoteMpiRank[i]);
tausch_so->addRecvHaloInfo(remote_spec[i], sizeof(real_t), nbuf, remote_remoteMpiRank[i]);
}
}
void tausch_exchanger::set_level_spec(int lvl, int rank,
grid_topo & topo,
std::vector<std::vector<std::array<int, 4> > > & remote_spec,
std::vector<std::vector<std::array<int, 4> > > & local_spec,
std::vector<int> & remote_remoteMpiRank,
std::vector<int> & local_remoteMpiRank)
{
const int nx = topo.nlocal(0);
const int ny = topo.nlocal(1);
// right
remote_spec[index(lvl,halo_dir::right)].push_back(std::array<int,4>{ 0, 1, ny, nx});
local_spec [index(lvl,halo_dir::right)].push_back(std::array<int,4>{nx-2, 1, ny, nx});
if(topo.coord(0) == 0)
remote_remoteMpiRank[index(lvl,halo_dir::right)] = rank + topo.nproc(0) - 1;
else
remote_remoteMpiRank[index(lvl,halo_dir::right)] = rank - 1;
if((rank + 1) % topo.nproc(0) == 0)
local_remoteMpiRank[index(lvl,halo_dir::right)] = rank - topo.nproc(0) + 1;
else
local_remoteMpiRank[index(lvl,halo_dir::right)] = rank + 1;
// left
remote_spec[index(lvl,halo_dir::left)].push_back(std::array<int,4>{nx-1, 1, ny, nx});
local_spec [index(lvl,halo_dir::left)].push_back(std::array<int,4>{ 1, 1, ny, nx});
remote_remoteMpiRank[index(lvl,halo_dir::left)] = local_remoteMpiRank[index(lvl,halo_dir::right)];
local_remoteMpiRank[index(lvl,halo_dir::left)] = remote_remoteMpiRank[index(lvl,halo_dir::right)];
// up
remote_spec[index(lvl,halo_dir::up)].push_back(std::array<int,4>{ 0, nx, 1, 1});
local_spec [index(lvl,halo_dir::up)].push_back(std::array<int,4>{(ny-2)*nx, nx, 1, 1});
if(topo.coord(1) == 0)
remote_remoteMpiRank[index(lvl,halo_dir::up)] = rank + topo.nproc(0)*topo.nproc(1) - topo.nproc(0);
else
remote_remoteMpiRank[index(lvl,halo_dir::up)] = rank - topo.nproc(0);
if(topo.coord(1) == (topo.nproc(1) - 1))
local_remoteMpiRank[index(lvl,halo_dir::up)] = rank - topo.nproc(0)*topo.nproc(1) + topo.nproc(0);
else
local_remoteMpiRank[index(lvl,halo_dir::up)] = rank + topo.nproc(0);
// down
remote_spec[index(lvl,halo_dir::down)].push_back(std::array<int,4>{(ny-1)*nx, nx, 1, 1});
local_spec [index(lvl,halo_dir::down)].push_back(std::array<int,4>{ nx, nx, 1, 1});
remote_remoteMpiRank[index(lvl,halo_dir::down)] = local_remoteMpiRank[index(lvl,halo_dir::up)];
local_remoteMpiRank[index(lvl,halo_dir::down)] = remote_remoteMpiRank[index(lvl,halo_dir::up)];
}
void tausch_exchanger::set_level_spec_so(int lvl, int rank,
grid_topo & topo,
std::vector<std::vector<std::array<int,4> > > & remote_spec,
std::vector<std::vector<std::array<int,4> > > & local_spec,
std::vector<int> & remote_remoteMpiRank,
std::vector<int> & local_remoteMpiRank)
{
const int nx = topo.nlocal(0)+1;
const int ny = topo.nlocal(1)+1;
// right
remote_spec[index(lvl,halo_dir::right)].push_back(std::array<int,4>{ 0, 1, ny-1, nx});
local_spec [index(lvl,halo_dir::right)].push_back(std::array<int,4>{nx-3, 1, ny-1, nx});
if(topo.coord(0) == 0)
remote_remoteMpiRank[index(lvl,halo_dir::right)] = rank + topo.nproc(0) - 1;
else
remote_remoteMpiRank[index(lvl,halo_dir::right)] = rank - 1;
if(((rank + 1) % topo.nproc(0) == 0))
local_remoteMpiRank[index(lvl,halo_dir::right)] = rank - topo.nproc(0) + 1;
else
local_remoteMpiRank[index(lvl,halo_dir::right)] = rank + 1;
// left
remote_spec[index(lvl,halo_dir::left)].push_back(std::array<int,4>{nx-2, 2, ny-1, nx});
local_spec [index(lvl,halo_dir::left)].push_back(std::array<int,4>{ 1, 2, ny-1, nx});
remote_remoteMpiRank[index(lvl,halo_dir::left)] = local_remoteMpiRank[index(lvl,halo_dir::right)];
local_remoteMpiRank[index(lvl,halo_dir::left)] = remote_remoteMpiRank[index(lvl,halo_dir::right)];
// up
remote_spec[index(lvl,halo_dir::up)].push_back(std::array<int,4>{ 0, nx-1, 1, 1});
local_spec [index(lvl,halo_dir::up)].push_back(std::array<int,4>{(ny-3)*nx, nx-1, 1, 1});
if(topo.coord(1) == 0)
remote_remoteMpiRank[index(lvl,halo_dir::up)] = rank + topo.nproc(0)*topo.nproc(1) - topo.nproc(0);
else
remote_remoteMpiRank[index(lvl,halo_dir::up)] = rank - topo.nproc(0);
if(topo.coord(1) == (topo.nproc(1) - 1))
local_remoteMpiRank[index(lvl,halo_dir::up)] = rank - topo.nproc(0)*topo.nproc(1) + topo.nproc(0);
else
local_remoteMpiRank[index(lvl,halo_dir::up)] = rank + topo.nproc(0);
// down
remote_spec[index(lvl,halo_dir::down)].push_back(std::array<int,4>{(ny-2)*nx, nx-1, 2, nx});
local_spec [index(lvl,halo_dir::down)].push_back(std::array<int,4>{ nx, nx-1, 2, nx});
remote_remoteMpiRank[index(lvl,halo_dir::down)] = local_remoteMpiRank[index(lvl,halo_dir::up)];
local_remoteMpiRank[index(lvl,halo_dir::down)] = remote_remoteMpiRank[index(lvl,halo_dir::up)];
}
void tausch_exchanger::exchange_func(int k, real_t * gf)
{
int lvl = nlevels - k;
for (int dir = 0; dir < halo_dir::count; dir++) {
if (send_active[index(lvl, dir)]) {
tausch->packSendBuffer(index(lvl,dir), 0, gf);
tausch->send(index(lvl,dir), index(lvl,dir));
}
if (recv_active[index(lvl, dir)]) {
tausch->recv(index(lvl,dir), index(lvl,dir));
tausch->unpackRecvBuffer(index(lvl,dir), 0, gf);
}
}
}
void tausch_exchanger::exchange_sten(int k, real_t * so)
{
int lvl = nlevels - k;
auto & dimx = leveldims(0);
auto & dimy = leveldims(1);
len_t II = dimx(coord[0], k-1) + 2;
len_t JJ = dimy(coord[1], k-1) + 2;
for (int dir = 0; dir < halo_dir::count; dir++) {
if (send_active[index(lvl, dir)]) {
for (int sdir = 0; sdir < stencil_ndirs<nine_pt>::value; sdir++) {
len_t offset = (JJ+1)*(II+1)*sdir;
tausch_so->packSendBuffer(index(lvl,dir), sdir, so + offset);
}
tausch_so->send(index(lvl,dir), index(lvl,dir));
}
if (recv_active[index(lvl, dir)]) {
tausch_so->recv(index(lvl,dir), index(lvl,dir));
for (int sdir = 0; sdir < stencil_ndirs<nine_pt>::value; sdir++) {
len_t offset = (JJ+1)*(II+1)*sdir;
tausch_so->unpackRecvBuffer(index(lvl,dir), sdir, so + offset);
}
}
}
}
void tausch_exchanger::run(mpi::grid_func & f, unsigned short dmask)
{
auto lvl = f.grid().level();
lvl = nlevels - lvl - 1;
for (int dir = 0; dir < halo_dir::count; dir++) {
if (send_active[index(lvl, dir)]) {
tausch->packSendBuffer(index(lvl,dir), 0, f.data());
tausch->send(index(lvl,dir), index(lvl,dir));
}
if (recv_active[index(lvl, dir)]) {
tausch->recv(index(lvl,dir), index(lvl,dir));
tausch->unpackRecvBuffer(index(lvl,dir), 0, f.data());
}
}
}
}}}
| 33.243836 | 114 | 0.633756 | cedar-framework |
e4c32af310ef2dbc0391b581081c12b8241aa751 | 3,513 | hpp | C++ | src/framework/qobj.hpp | awcross1/qiskit-aer | 72863e804ec3d07c0da2ebeb665a31db7a7e3010 | [
"Apache-2.0"
] | null | null | null | src/framework/qobj.hpp | awcross1/qiskit-aer | 72863e804ec3d07c0da2ebeb665a31db7a7e3010 | [
"Apache-2.0"
] | null | null | null | src/framework/qobj.hpp | awcross1/qiskit-aer | 72863e804ec3d07c0da2ebeb665a31db7a7e3010 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2018, IBM.
*
* This source code is licensed under the Apache License, Version 2.0 found in
* the LICENSE.txt file in the root directory of this source tree.
*/
#ifndef _aer_framework_qobj_hpp_
#define _aer_framework_qobj_hpp_
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>
#include "framework/circuit.hpp"
namespace AER {
//============================================================================
// Qobj data structure
//============================================================================
class Qobj {
public:
Qobj() = default;
virtual ~Qobj() = default;
// JSON deserialization constructor
inline Qobj(const json_t &js) {load_qobj_from_json(js);};
//----------------------------------------------------------------
// Data
//----------------------------------------------------------------
std::string id; // qobj identifier passed to result
std::string type = "QASM"; // currently we only support QASM
std::vector<Circuit> circuits; // List of circuits
json_t header; // (optional) passed through to result;
json_t config; // (optional) not currently used?
int_t seed = -1; // Seed for qobj (-1 for random)
//----------------------------------------------------------------
// Loading Functions
//----------------------------------------------------------------
void load_qobj_from_json(const json_t &js);
void load_qobj_from_file(const std::string file);
inline void load_qobj_from_string(const std::string &input);
};
inline void from_json(const json_t &js, Qobj &qobj) {qobj = Qobj(js);}
//============================================================================
// Implementation: Qobj methods
//============================================================================
void Qobj::load_qobj_from_file(const std::string file) {
json_t js = JSON::load(file);
load_qobj_from_json(js);
}
void Qobj::load_qobj_from_string(const std::string &input) {
json_t js = json_t::parse(input);
load_qobj_from_json(js);
}
void Qobj::load_qobj_from_json(const json_t &js) {
// Get qobj id
if (JSON::get_value(id, "qobj_id", js) == false) {
throw std::invalid_argument("Invalid qobj: no \"qobj_id\" field");
};
// Get header and config;
JSON::get_value(config, "config", js);
JSON::get_value(header, "header", js);
// Check for fixed seed
JSON::get_value(seed, "seed", config);
// Get type
JSON::get_value(type, "type", js);
if (type != "QASM") {
throw std::invalid_argument("Invalid qobj: currently only \"type\" = \"QASM\" is supported.");
};
// Get circuits
if (JSON::check_key("experiments", js) == false) {
throw std::invalid_argument("Invalid qobj: no \"experiments\" field.");
}
// Parse experiments
const json_t &circs = js["experiments"];
uint_t seed_shift = 0;
for (const auto &circ : circs) {
Circuit circuit(circ, config);
// override random seed with fixed seed if set
// We shift the seed for each successive experiment
// So that results aren't correlated between experiments
if (seed >= 0) {
circuit.set_seed(seed + seed_shift);
seed_shift += 2113; // Shift the seed
}
circuits.push_back(circuit);
}
}
//------------------------------------------------------------------------------
} // end namespace QISKIT
//------------------------------------------------------------------------------
#endif | 31.648649 | 98 | 0.522346 | awcross1 |
e4c3c28e1cf13b834c5d035ba15b95f2a13815eb | 4,525 | cpp | C++ | src/net/examples/sita_net_example_003/src/sita_net_example_003-main.cpp | SimpleTalkCpp/libsita | e0c13f16cebf799f0d57b8345d21de7407f59e2b | [
"MIT"
] | 2 | 2021-03-19T13:19:27.000Z | 2021-04-03T17:42:30.000Z | src/net/examples/sita_net_example_003/src/sita_net_example_003-main.cpp | SimpleTalkCpp/libsita | e0c13f16cebf799f0d57b8345d21de7407f59e2b | [
"MIT"
] | null | null | null | src/net/examples/sita_net_example_003/src/sita_net_example_003-main.cpp | SimpleTalkCpp/libsita | e0c13f16cebf799f0d57b8345d21de7407f59e2b | [
"MIT"
] | null | null | null | #include <sita_net_common.h>
#include <sita_imgui.h>
namespace sita {
enum class MyPacketCmd : NEPacketCmd {
Hello,
Test,
};
#define MyPacket_Define(T) \
virtual void onWrite(BinSerializer& se) { io(se); } \
virtual void onRead (BinDeserializer& se) { io(se); } \
public: \
MyPacket_##T() : MyPacket(Cmd::T) {} \
//-------
class MyPacket : public NEPacket {
public:
using Cmd = MyPacketCmd;
MyPacket(MyPacketCmd cmd) : NEPacket(enumInt(cmd)) {}
};
class MyPacket_Hello : public MyPacket {
MyPacket_Define(Hello)
public:
String_<32> msg;
template<class SE>
void io(SE& se) {
se << msg;
}
};
class MyPacket_Test : public MyPacket {
MyPacket_Define(Test)
public:
u32 seq = 0;
static const u32 kDataSize = 200;
Vector_<u32, kDataSize> data;
void initData(u32 seq_) {
seq = seq_;
data.resize(kDataSize);
for (u32 i = 0; i < kDataSize; i++) {
data[i] = i + seq;
}
}
bool validateData() {
if (data.size() != kDataSize) {
SITA_ASSERT(false);
return false;
}
for (u32 i = 0; i < kDataSize; i++) {
if (data[i] != i + seq) {
SITA_ASSERT(false);
return false;
}
}
return true;
}
template<class SE>
void io(SE& se) {
se << seq << data;
}
};
class MyNetEngine : public NetEngine {
public:
virtual void onAccept(NESocket* s) override {
// SITA_LOG("onAccept");
}
virtual void onConnect(NESocket* s) override {
// SITA_LOG("onConnect");
MyPacket_Hello pkt;
pkt.msg = "hello";
sendPacket(s, pkt);
}
virtual void onDisconnect(NESocket* s) override {
// SITA_LOG("onDisconnect");
}
virtual void onError(NESocket* s, const Error& err) override {
// SITA_LOG("onError");
}
virtual void onRecvPacket(NESocket* s, const NEPacketHeader& hdr, Span<u8> data) override {
using Cmd = MyPacketCmd;
auto cmd = static_cast<Cmd>(hdr.cmd);
#define RECV_PACKET_CASE(T) \
case Cmd::T: { \
MyPacket_##T pkt; \
pkt.readFromBuffer(data); \
_onRecvPacket(s, pkt); \
} break; \
//-----
switch (cmd) {
RECV_PACKET_CASE(Hello) \
RECV_PACKET_CASE(Test) \
}
#undef RECV_PACKET_CASE
}
void _onRecvPacket(NESocket* s, MyPacket_Hello& pkt) {
// SITA_LOG("MyPacket_Hello");
MyPacket_Test outPkt;
outPkt.initData(10);
sendPacket(s, outPkt);
}
void _onRecvPacket(NESocket* s, MyPacket_Test& pkt) {
// SITA_LOG("MyPacket_Test");
if (!pkt.validateData()) {
SITA_ASSERT(false);
}
pkt.initData(pkt.seq + 1);
sendPacket(s, pkt);
}
};
class MyApp : public ImGuiApp {
public:
int port = 30000;
char hostname[256] = "localhost";
int testConnCount = 1000;
bool isHost() const { return false; }
MyNetEngine _netEngine;
virtual void onInit() override {
setTitle("sita_net_example_003");
}
void updateUI() {
{
auto& rs = _netEngine.recvStatis();
auto& ss = _netEngine.recvStatis();
ImGui::Text("statistics:\n"
" recv %10llu kB/s, total %10llu kB\n"
" send %10llu kB/s, total %10llu kB\n"
, rs.lastSecond / 1024, rs.total / 1024
, ss.lastSecond / 1024, rs.total / 1024
);
}
ImGui::Spacing();
ImGui::InputText("Hostname", hostname, sizeof(hostname));
ImGui::InputInt("Port", &port);
{
ImGui::BeginGroup();
ImGui::LabelText("Listen Count", "%u", _netEngine.listenCount());
if (ImGui::Button("Listen")) {
try {
_netEngine.listen(hostname, port, testConnCount * 2);
} catch (...) {
SITA_LOG("error listen");
}
}
ImGui::SameLine();
if (ImGui::Button("Stop Listen")) {
_netEngine.stopListen();
}
ImGui::EndGroup();
}
ImGui::LabelText("Connected Count", "%u", _netEngine.connectedCount());
ImGui::InputInt("Test Connection Count", &testConnCount);
if (testConnCount < 1) testConnCount = 1;
if (ImGui::Button("Connect")) {
try {
for (int i = 0; i < testConnCount; i++) {
_netEngine.connect(hostname, static_cast<u16>(port));
}
} catch (...) {
SITA_LOG("error connect");
}
}
ImGui::SameLine();
if (ImGui::Button("Disconnect All")) {
_netEngine.disconnectAll();
}
}
virtual void onUpdate(float deltaTime) override {
_netEngine.update();
ImGui::Begin("UI");
updateUI();
ImGui::End();
}
};
} // namespace
int main()
{
srand(time(nullptr));
using namespace sita;
MyApp app;
app.run();
return 0;
} | 20.022124 | 93 | 0.601105 | SimpleTalkCpp |
e4c485ca8e332a8baddb257a0666d2ec19a0ae07 | 25,688 | cpp | C++ | gamgee/variant/variant_builder.cpp | audiohacked/gamgee | 772a095c5f0725c410e7c23e88f79d8b76e098a8 | [
"MIT"
] | 24 | 2015-01-20T16:15:46.000Z | 2019-09-16T07:53:54.000Z | gamgee/variant/variant_builder.cpp | audiohacked/gamgee | 772a095c5f0725c410e7c23e88f79d8b76e098a8 | [
"MIT"
] | 8 | 2015-01-30T07:27:00.000Z | 2017-07-11T21:37:17.000Z | gamgee/variant/variant_builder.cpp | audiohacked/gamgee | 772a095c5f0725c410e7c23e88f79d8b76e098a8 | [
"MIT"
] | 15 | 2015-01-11T05:28:26.000Z | 2022-01-18T08:47:10.000Z | #include "variant_builder.h"
#include "../missing.h"
#include <algorithm>
#include <stdexcept>
using namespace std;
namespace gamgee {
VariantBuilder::VariantBuilder(const VariantHeader& header) :
m_header { header.m_header }, // Important: take shared ownership of header rather than make a deep copy
m_contig {},
m_start_pos {},
m_stop_pos {},
m_qual {},
m_shared_region { header, true },
m_individual_region { header, true },
m_enable_validation { true }
{}
VariantBuilder& VariantBuilder::set_enable_validation(const bool enable_validation) {
m_enable_validation = enable_validation;
m_shared_region.set_enable_validation(enable_validation);
m_individual_region.set_enable_validation(enable_validation);
return *this;
}
/******************************************************************************
*
* Functions for setting core site-level fields
*
******************************************************************************/
VariantBuilder& VariantBuilder::set_chromosome(const uint32_t chromosome) {
m_contig.set(int32_t(chromosome));
return *this;
}
VariantBuilder& VariantBuilder::set_chromosome(const std::string& chromosome) {
// Note: we will validate the contig id (including checking for -1) at build time, if validation is turned on
m_contig.set(bcf_hdr_id2int(m_header.m_header.get(), BCF_DT_CTG, chromosome.c_str()));
return *this;
}
VariantBuilder& VariantBuilder::set_alignment_start(const uint32_t alignment_start) {
m_start_pos.set(alignment_start - 1);
return *this;
}
VariantBuilder& VariantBuilder::set_alignment_stop(const uint32_t alignment_stop) {
m_stop_pos.set(alignment_stop - 1);
return *this;
}
VariantBuilder& VariantBuilder::set_qual(const float qual) {
m_qual.set(qual);
return *this;
}
VariantBuilder& VariantBuilder::set_id(const std::string& id) {
m_shared_region.set_id(id);
return *this;
}
VariantBuilder& VariantBuilder::set_ref_allele(const std::string& ref_allele) {
m_shared_region.set_ref_allele(ref_allele);
return *this;
}
VariantBuilder& VariantBuilder::set_alt_allele(const std::string& alt_allele) {
m_shared_region.set_alt_allele(alt_allele);
return *this;
}
VariantBuilder& VariantBuilder::set_alt_alleles(const std::vector<std::string>& alt_alleles) {
m_shared_region.set_alt_alleles(alt_alleles);
return *this;
}
VariantBuilder& VariantBuilder::set_filters(const std::vector<std::string>& filters) {
m_shared_region.set_filters(filters);
return *this;
}
VariantBuilder& VariantBuilder::set_filters(const std::vector<int32_t>& filters) {
m_shared_region.set_filters(filters);
return *this;
}
/******************************************************************************
*
* Functions for removing core site-level fields
*
******************************************************************************/
VariantBuilder& VariantBuilder::remove_alignment_stop() {
m_stop_pos.clear();
return *this;
}
VariantBuilder& VariantBuilder::remove_qual() {
m_qual.clear();
return *this;
}
VariantBuilder& VariantBuilder::remove_id() {
m_shared_region.remove_id();
return *this;
}
VariantBuilder& VariantBuilder::remove_alt_alleles() {
m_shared_region.remove_alt_alleles();
return *this;
}
VariantBuilder& VariantBuilder::remove_filters() {
m_shared_region.remove_filters();
return *this;
}
/******************************************************************************
*
* Functions for setting shared/INFO fields
*
******************************************************************************/
VariantBuilder& VariantBuilder::set_integer_shared_field(const std::string& tag, const int32_t value) {
m_shared_region.set_info_field(tag, value, BCF_HT_INT, 1u);
return *this;
}
VariantBuilder& VariantBuilder::set_integer_shared_field(const std::string& tag, const std::vector<int32_t>& values) {
m_shared_region.set_info_field(tag, values, BCF_HT_INT, values.size());
return *this;
}
VariantBuilder& VariantBuilder::set_integer_shared_field(const uint32_t index, const int32_t value) {
m_shared_region.set_info_field(index, value, BCF_HT_INT, 1u);
return *this;
}
VariantBuilder& VariantBuilder::set_integer_shared_field(const uint32_t index, const std::vector<int32_t>& values) {
m_shared_region.set_info_field(index, values, BCF_HT_INT, values.size());
return *this;
}
VariantBuilder& VariantBuilder::set_float_shared_field(const std::string& tag, const float value) {
m_shared_region.set_info_field(tag, value, BCF_HT_REAL, 1u);
return *this;
}
VariantBuilder& VariantBuilder::set_float_shared_field(const std::string& tag, const std::vector<float>& values) {
m_shared_region.set_info_field(tag, values, BCF_HT_REAL, values.size());
return *this;
}
VariantBuilder& VariantBuilder::set_float_shared_field(const uint32_t index, const float value) {
m_shared_region.set_info_field(index, value, BCF_HT_REAL, 1u);
return *this;
}
VariantBuilder& VariantBuilder::set_float_shared_field(const uint32_t index, const std::vector<float>& values) {
m_shared_region.set_info_field(index, values, BCF_HT_REAL, values.size());
return *this;
}
VariantBuilder& VariantBuilder::set_string_shared_field(const std::string& tag, const std::string& value) {
m_shared_region.set_info_field(tag, value, BCF_HT_STR, value.length());
return *this;
}
VariantBuilder& VariantBuilder::set_string_shared_field(const uint32_t index, const std::string& value) {
m_shared_region.set_info_field(index, value, BCF_HT_STR, value.length());
return *this;
}
VariantBuilder& VariantBuilder::set_boolean_shared_field(const std::string& tag) {
m_shared_region.set_info_field(tag, true, BCF_HT_FLAG, 1u);
return *this;
}
VariantBuilder& VariantBuilder::set_boolean_shared_field(const uint32_t index) {
m_shared_region.set_info_field(index, true, BCF_HT_FLAG, 1u);
return *this;
}
/******************************************************************************
*
* Functions for removing shared/INFO fields
*
******************************************************************************/
VariantBuilder& VariantBuilder::remove_shared_field(const std::string& tag) {
m_shared_region.remove_info_field(tag);
return *this;
}
VariantBuilder& VariantBuilder::remove_shared_field(const uint32_t field_index) {
m_shared_region.remove_info_field(field_index);
return *this;
}
VariantBuilder& VariantBuilder::remove_shared_fields(const std::vector<std::string>& tags) {
for_each(tags.begin(), tags.end(), [this](const std::string& tag){ m_shared_region.remove_info_field(tag); });
return *this;
}
VariantBuilder& VariantBuilder::remove_shared_fields(const std::vector<uint32_t>& field_indices) {
for_each(field_indices.begin(), field_indices.end(), [this](const uint32_t field_index){ m_shared_region.remove_info_field(field_index); });
return *this;
}
/******************************************************************************
*
* Functions for setting individual/FORMAT fields in bulk
* (ie., setting all values for all samples at once)
*
******************************************************************************/
VariantBuilder& VariantBuilder::set_genotypes(const VariantBuilderMultiSampleVector<int32_t>& genotypes_for_all_samples) {
// Since the user has chosen to pass by lvalue, make a copy before encoding the genotypes
auto encoded_genotypes = genotypes_for_all_samples;
Genotype::encode_genotypes(encoded_genotypes);
// We've made a copy, so we can move the copy into the storage layer
m_individual_region.bulk_set_genotype_field(m_individual_region.gt_index(), move(encoded_genotypes.get_vector()));
return *this;
}
VariantBuilder& VariantBuilder::set_genotypes(VariantBuilderMultiSampleVector<int32_t>&& genotypes_for_all_samples) {
// Encode user's vector directly, since it's been moved in to us
Genotype::encode_genotypes(genotypes_for_all_samples);
m_individual_region.bulk_set_genotype_field(m_individual_region.gt_index(), move(genotypes_for_all_samples.get_vector()));
return *this;
}
VariantBuilder& VariantBuilder::set_genotypes(const std::vector<std::vector<int32_t>>& genotypes_for_all_samples) {
// Since the user has chosen to pass by lvalue, make a copy before encoding the genotypes
auto encoded_genotypes = genotypes_for_all_samples;
Genotype::encode_genotypes(encoded_genotypes);
// We've made a copy, so we can move the copy into the storage layer
m_individual_region.bulk_set_genotype_field(m_individual_region.gt_index(), move(encoded_genotypes));
return *this;
}
VariantBuilder& VariantBuilder::set_genotypes(std::vector<std::vector<int32_t>>&& genotypes_for_all_samples) {
// Encode user's vector directly, since it's been moved in to us
Genotype::encode_genotypes(genotypes_for_all_samples);
m_individual_region.bulk_set_genotype_field(m_individual_region.gt_index(), move(genotypes_for_all_samples));
return *this;
}
VariantBuilder& VariantBuilder::set_integer_individual_field(const std::string& tag, const VariantBuilderMultiSampleVector<int32_t>& values_for_all_samples) {
// Ensure that we have an lvalue reference to the values vector so that we make a copy further down the line
const auto& values_vector = values_for_all_samples.get_vector();
m_individual_region.bulk_set_integer_field(tag, values_vector);
return *this;
}
VariantBuilder& VariantBuilder::set_integer_individual_field(const std::string& tag, VariantBuilderMultiSampleVector<int32_t>&& values_for_all_samples) {
m_individual_region.bulk_set_integer_field(tag, move(values_for_all_samples.get_vector()));
return *this;
}
VariantBuilder& VariantBuilder::set_integer_individual_field(const std::string& tag, const std::vector<std::vector<int32_t>>& values_for_all_samples) {
m_individual_region.bulk_set_integer_field(tag, values_for_all_samples);
return *this;
}
VariantBuilder& VariantBuilder::set_integer_individual_field(const std::string& tag, std::vector<std::vector<int32_t>>&& values_for_all_samples) {
m_individual_region.bulk_set_integer_field(tag, move(values_for_all_samples));
return *this;
}
VariantBuilder& VariantBuilder::set_integer_individual_field(const uint32_t field_index, const VariantBuilderMultiSampleVector<int32_t>& values_for_all_samples) {
// Ensure that we have an lvalue reference to the values vector so that we make a copy further down the line
const auto& values_vector = values_for_all_samples.get_vector();
m_individual_region.bulk_set_integer_field(field_index, values_vector);
return *this;
}
VariantBuilder& VariantBuilder::set_integer_individual_field(const uint32_t field_index, VariantBuilderMultiSampleVector<int32_t>&& values_for_all_samples) {
m_individual_region.bulk_set_integer_field(field_index, move(values_for_all_samples.get_vector()));
return *this;
}
VariantBuilder& VariantBuilder::set_integer_individual_field(const uint32_t field_index, const std::vector<std::vector<int32_t>>& values_for_all_samples) {
m_individual_region.bulk_set_integer_field(field_index, values_for_all_samples);
return *this;
}
VariantBuilder& VariantBuilder::set_integer_individual_field(const uint32_t field_index, std::vector<std::vector<int32_t>>&& values_for_all_samples) {
m_individual_region.bulk_set_integer_field(field_index, move(values_for_all_samples));
return *this;
}
VariantBuilder& VariantBuilder::set_float_individual_field(const std::string& tag, const VariantBuilderMultiSampleVector<float>& values_for_all_samples) {
// Ensure that we have an lvalue reference to the values vector so that we make a copy further down the line
const auto& values_vector = values_for_all_samples.get_vector();
m_individual_region.bulk_set_float_field(tag, values_vector);
return *this;
}
VariantBuilder& VariantBuilder::set_float_individual_field(const std::string& tag, VariantBuilderMultiSampleVector<float>&& values_for_all_samples) {
m_individual_region.bulk_set_float_field(tag, move(values_for_all_samples.get_vector()));
return *this;
}
VariantBuilder& VariantBuilder::set_float_individual_field(const std::string& tag, const std::vector<std::vector<float>>& values_for_all_samples) {
m_individual_region.bulk_set_float_field(tag, values_for_all_samples);
return *this;
}
VariantBuilder& VariantBuilder::set_float_individual_field(const std::string& tag, std::vector<std::vector<float>>&& values_for_all_samples) {
m_individual_region.bulk_set_float_field(tag, move(values_for_all_samples));
return *this;
}
VariantBuilder& VariantBuilder::set_float_individual_field(const uint32_t field_index, const VariantBuilderMultiSampleVector<float>& values_for_all_samples) {
// Ensure that we have an lvalue reference to the values vector so that we make a copy further down the line
const auto& values_vector = values_for_all_samples.get_vector();
m_individual_region.bulk_set_float_field(field_index, values_vector);
return *this;
}
VariantBuilder& VariantBuilder::set_float_individual_field(const uint32_t field_index, VariantBuilderMultiSampleVector<float>&& values_for_all_samples) {
m_individual_region.bulk_set_float_field(field_index, move(values_for_all_samples.get_vector()));
return *this;
}
VariantBuilder& VariantBuilder::set_float_individual_field(const uint32_t field_index, const std::vector<std::vector<float>>& values_for_all_samples) {
m_individual_region.bulk_set_float_field(field_index, values_for_all_samples);
return *this;
}
VariantBuilder& VariantBuilder::set_float_individual_field(const uint32_t field_index, std::vector<std::vector<float>>&& values_for_all_samples) {
m_individual_region.bulk_set_float_field(field_index, move(values_for_all_samples));
return *this;
}
VariantBuilder& VariantBuilder::set_string_individual_field(const std::string& tag, const std::vector<std::string>& values_for_all_samples) {
m_individual_region.bulk_set_string_field(tag, values_for_all_samples);
return *this;
}
VariantBuilder& VariantBuilder::set_string_individual_field(const std::string& tag, std::vector<std::string>&& values_for_all_samples) {
m_individual_region.bulk_set_string_field(tag, move(values_for_all_samples));
return *this;
}
VariantBuilder& VariantBuilder::set_string_individual_field(const uint32_t field_index, const std::vector<std::string>& values_for_all_samples) {
m_individual_region.bulk_set_string_field(field_index, values_for_all_samples);
return *this;
}
VariantBuilder& VariantBuilder::set_string_individual_field(const uint32_t field_index, std::vector<std::string>&& values_for_all_samples) {
m_individual_region.bulk_set_string_field(field_index, move(values_for_all_samples));
return *this;
}
/******************************************************************************
*
* Functions for setting individual/FORMAT fields by sample
*
******************************************************************************/
VariantBuilder& VariantBuilder::set_genotype(const std::string& sample, const std::vector<int32_t>& genotype) {
// Since the user has passed by lvalue, make a copy before encoding
auto encoded_genotype = genotype;
Genotype::encode_genotype(encoded_genotype);
m_individual_region.set_genotype_field_by_sample(m_individual_region.gt_index(), sample, encoded_genotype.empty() ? nullptr : &(encoded_genotype[0]), encoded_genotype.size());
return *this;
}
VariantBuilder& VariantBuilder::set_genotype(const std::string& sample, std::vector<int32_t>&& genotype) {
// Encode user's vector directly, since it's been moved in to us
Genotype::encode_genotype(genotype);
m_individual_region.set_genotype_field_by_sample(m_individual_region.gt_index(), sample, genotype.empty() ? nullptr : &(genotype[0]), genotype.size());
return *this;
}
VariantBuilder& VariantBuilder::set_genotype(const uint32_t sample_index, const std::vector<int32_t>& genotype) {
// Since the user has passed by lvalue, make a copy before encoding
auto encoded_genotype = genotype;
Genotype::encode_genotype(encoded_genotype);
m_individual_region.set_genotype_field_by_sample(m_individual_region.gt_index(), sample_index, encoded_genotype.empty() ? nullptr : &(encoded_genotype[0]), encoded_genotype.size());
return *this;
}
VariantBuilder& VariantBuilder::set_genotype(const uint32_t sample_index, std::vector<int32_t>&& genotype) {
// Encode user's vector directly, since it's been moved in to us
Genotype::encode_genotype(genotype);
m_individual_region.set_genotype_field_by_sample(m_individual_region.gt_index(), sample_index, genotype.empty() ? nullptr : &(genotype[0]), genotype.size());
return *this;
}
VariantBuilder& VariantBuilder::set_integer_individual_field(const std::string& tag, const std::string& sample, const int32_t value) {
m_individual_region.set_integer_field_by_sample(tag, sample, &value, 1);
return *this;
}
VariantBuilder& VariantBuilder::set_integer_individual_field(const std::string& tag, const std::string& sample, const std::vector<int32_t>& values) {
m_individual_region.set_integer_field_by_sample(tag, sample, values.empty() ? nullptr : &(values[0]), values.size());
return *this;
}
VariantBuilder& VariantBuilder::set_integer_individual_field(const uint32_t field_index, const uint32_t sample_index, const int32_t value) {
m_individual_region.set_integer_field_by_sample(field_index, sample_index, &value, 1);
return *this;
}
VariantBuilder& VariantBuilder::set_integer_individual_field(const uint32_t field_index, const uint32_t sample_index, const std::vector<int32_t>& values) {
m_individual_region.set_integer_field_by_sample(field_index, sample_index, values.empty() ? nullptr : &(values[0]), values.size());
return *this;
}
VariantBuilder& VariantBuilder::set_float_individual_field(const std::string& tag, const std::string& sample, const float value) {
m_individual_region.set_float_field_by_sample(tag, sample, &value, 1);
return *this;
}
VariantBuilder& VariantBuilder::set_float_individual_field(const std::string& tag, const std::string& sample, const std::vector<float>& values) {
m_individual_region.set_float_field_by_sample(tag, sample, values.empty() ? nullptr : &(values[0]), values.size());
return *this;
};
VariantBuilder& VariantBuilder::set_float_individual_field(const uint32_t field_index, const uint32_t sample_index, const float value) {
m_individual_region.set_float_field_by_sample(field_index, sample_index, &value, 1);
return *this;
}
VariantBuilder& VariantBuilder::set_float_individual_field(const uint32_t field_index, const uint32_t sample_index, const std::vector<float>& values) {
m_individual_region.set_float_field_by_sample(field_index, sample_index, values.empty() ? nullptr : &(values[0]), values.size());
return *this;
}
VariantBuilder& VariantBuilder::set_string_individual_field(const std::string& tag, const std::string& sample, const std::string& value) {
m_individual_region.set_string_field_by_sample(tag, sample, value.empty() ? nullptr : value.c_str(), value.length());
return *this;
}
VariantBuilder& VariantBuilder::set_string_individual_field(const uint32_t field_index, const uint32_t sample_index, const std::string& value) {
m_individual_region.set_string_field_by_sample(field_index, sample_index, value.empty() ? nullptr : value.c_str(), value.length());
return *this;
}
/******************************************************************************
*
* Functions for removing individual/FORMAT fields
*
******************************************************************************/
VariantBuilder& VariantBuilder::remove_individual_field(const std::string& tag) {
m_individual_region.remove_individual_field(tag);
return *this;
}
VariantBuilder& VariantBuilder::remove_individual_field(const uint32_t field_index) {
m_individual_region.remove_individual_field(field_index);
return *this;
}
VariantBuilder& VariantBuilder::remove_individual_fields(const std::vector<std::string>& tags) {
for_each(tags.begin(), tags.end(), [this](const std::string& tag){ m_individual_region.remove_individual_field(tag); });
return *this;
}
VariantBuilder& VariantBuilder::remove_individual_fields(const std::vector<uint32_t>& field_indices) {
for_each(field_indices.begin(), field_indices.end(), [this](const uint32_t field_index){ m_individual_region.remove_individual_field(field_index); });
return *this;
}
/******************************************************************************
*
* Data preparation functions for working with individual fields
*
******************************************************************************/
VariantBuilderMultiSampleVector<int32_t> VariantBuilder::get_genotype_multi_sample_vector(const uint32_t num_samples, const uint32_t max_values_per_sample) const {
return VariantBuilderMultiSampleVector<int32_t>{num_samples, max_values_per_sample, -1, bcf_int32_vector_end};
}
VariantBuilderMultiSampleVector<int32_t> VariantBuilder::get_integer_multi_sample_vector(const uint32_t num_samples, const uint32_t max_values_per_sample) const {
return VariantBuilderMultiSampleVector<int32_t>{num_samples, max_values_per_sample, bcf_int32_missing, bcf_int32_vector_end};
}
VariantBuilderMultiSampleVector<float> VariantBuilder::get_float_multi_sample_vector(const uint32_t num_samples, const uint32_t max_values_per_sample) const {
auto float_missing = 0.0f; bcf_float_set_missing(float_missing);
auto float_vector_end = 0.0f; bcf_float_set_vector_end(float_vector_end);
return VariantBuilderMultiSampleVector<float>{num_samples, max_values_per_sample, float_missing, float_vector_end};
}
/******************************************************************************
*
* Builder operations: build() and clear()
*
******************************************************************************/
Variant VariantBuilder::build() const {
const auto new_variant_body = utils::make_shared_variant(bcf_init1());
// Always build from scratch for now, until support for building from a starting variant is added
build_from_scratch(new_variant_body);
if ( m_enable_validation ) {
post_build_validation(new_variant_body);
}
return Variant{m_header.m_header, new_variant_body};
}
VariantBuilder& VariantBuilder::clear() {
m_contig.clear();
m_start_pos.clear();
m_stop_pos.clear();
m_qual.clear();
m_shared_region.clear();
m_individual_region.clear();
return *this;
}
/******************************************************************************
*
* Private functionality
*
******************************************************************************/
void VariantBuilder::build_from_scratch(const std::shared_ptr<bcf1_t>& new_variant_body) const {
// Missing rid/pos are errors that will be caught in post-build validation (if validation is turned on)
new_variant_body->rid = m_contig.is_set() ? m_contig.field_value() : missing_values::int32;
new_variant_body->pos = m_start_pos.is_set() ? m_start_pos.field_value() : missing_values::int32;
if ( m_qual.is_set() ) {
new_variant_body->qual = m_qual.field_value();
}
else {
bcf_float_set_missing(new_variant_body->qual);
}
// Set rlen to the reference block size if alignment stop was set, otherwise set it to the ref allele length.
// If m_start_pos is not set, we'll get an error in the post-validation stage.
new_variant_body->rlen = m_stop_pos.is_set() ? (m_stop_pos.field_value() - m_start_pos.field_value() + 1) :
int32_t(m_shared_region.ref_allele_length());
new_variant_body->n_allele = 1 + m_shared_region.num_alt_alleles();
// Shared region (always encoded, since at a minimum the ref allele will be present)
new_variant_body->n_info = m_shared_region.num_present_info_fields();
auto shared_buffer = utils::initialize_htslib_buffer(m_shared_region.estimate_total_size());
m_shared_region.encode_into(&shared_buffer);
new_variant_body->shared = shared_buffer;
// Individual region (conditionally encoded)
new_variant_body->n_sample = m_header.n_samples();
new_variant_body->n_fmt = m_individual_region.num_present_fields();
if ( m_individual_region.num_present_fields() > 0 ) {
auto indiv_buffer = utils::initialize_htslib_buffer(m_individual_region.estimate_total_size());
m_individual_region.encode_into(&indiv_buffer);
new_variant_body->indiv = indiv_buffer;
}
else {
new_variant_body->indiv = {0, 0, 0};
}
}
void VariantBuilder::post_build_validation(const std::shared_ptr<bcf1_t>& new_variant_body) const {
// Note that we only do validation of core (non-data-region) fields here.
// The data region fields are validated in the VariantBuilderSharedRegion and
// VariantBuilderIndividualRegion/VariantBuilderIndividualField classes.
// Chromosome field must be present
if ( new_variant_body->rid == missing_values::int32 ) {
throw logic_error("Missing required chromosome field");
}
// Chromosome must be in header sequence dictionary
if ( new_variant_body->rid < 0 || new_variant_body->rid >= m_header.m_header->n[BCF_DT_CTG] || m_header.m_header->id[BCF_DT_CTG][new_variant_body->rid].key == nullptr ) {
throw invalid_argument(string{"Chromosome with index "} + to_string(new_variant_body->rid) + " not found in header sequence dictionary");
}
// Alignment start field must be present
if ( new_variant_body->pos == missing_values::int32 ) {
throw logic_error("Missing required alignment start field");
}
// rlen will be negative or 0 at this point if alignment stop was < alignment start
if ( new_variant_body->rlen <= 0 ) {
throw logic_error("Alignment stop must be >= alignment start");
}
}
}
| 42.389439 | 183 | 0.739372 | audiohacked |
e4c870018d54f71d477e97735d7189686c52fb46 | 800 | cpp | C++ | scugog_project/frontend_src/EndGameScreen.cpp | akinshonibare/Food-Fight-Game | cad246c5e29dab32c94d52ab97804575edd2233c | [
"MIT"
] | null | null | null | scugog_project/frontend_src/EndGameScreen.cpp | akinshonibare/Food-Fight-Game | cad246c5e29dab32c94d52ab97804575edd2233c | [
"MIT"
] | null | null | null | scugog_project/frontend_src/EndGameScreen.cpp | akinshonibare/Food-Fight-Game | cad246c5e29dab32c94d52ab97804575edd2233c | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "EndGameScreen.h"
int EndGameScreen::Show(sf::RenderWindow & renderWindow, int player_won)
{
//sf::Image image;
sf::Texture texture;
if (player_won == 0) {
if (texture.loadFromFile("../scugog_project/resources/images/player_one_wins.png") != true)
{
return -1;
}
}
else {
if (texture.loadFromFile("../scugog_project/resources/images/player_two_wins.png") != true)
{
return -1;
}
}
//texture.update(image);
sf::Sprite sprite(texture);
renderWindow.draw(sprite);
renderWindow.display();
sf::Event event;
while (true)
{
while (renderWindow.pollEvent(event))
{
if (event.type == sf::Event::EventType::Closed)
{
return -2;
}
else if (event.type == sf::Event::EventType::MouseButtonPressed) {
return 0;
}
}
}
}
| 18.604651 | 93 | 0.65625 | akinshonibare |
e4c8e9967610e7aa0758c54e24ea3c1220e982bf | 1,410 | cpp | C++ | examples/FeatureShowcase/features/step_definitions/TagSteps.cpp | meshell/cucumber-cpp | a41565d8fd7b87fd160e441602b398dc76f6d739 | [
"MIT"
] | 214 | 2015-01-09T05:09:50.000Z | 2022-03-25T05:51:23.000Z | examples/FeatureShowcase/features/step_definitions/TagSteps.cpp | meshell/cucumber-cpp | a41565d8fd7b87fd160e441602b398dc76f6d739 | [
"MIT"
] | 186 | 2015-01-06T15:52:03.000Z | 2022-03-07T21:16:01.000Z | examples/FeatureShowcase/features/step_definitions/TagSteps.cpp | meshell/cucumber-cpp | a41565d8fd7b87fd160e441602b398dc76f6d739 | [
"MIT"
] | 120 | 2015-01-06T15:40:54.000Z | 2022-03-22T17:56:29.000Z | #include <gtest/gtest.h>
#include <cucumber-cpp/autodetect.hpp>
#include <iostream>
using std::string;
using std::cout;
using std::endl;
BEFORE_ALL()
{
cout << "-------------------- (Before all scenarios)" << endl;
}
AFTER_ALL()
{
cout << "-------------------- (After all scenarios)" << endl;
}
BEFORE() {
cout << "-------------------- (Before any scenario)" << endl;
}
BEFORE("@foo,@bar","@baz") {
cout << "Before scenario (\"@foo,@baz\",\"@bar\")" << endl;
}
AROUND_STEP("@baz") {
cout << "Around step (\"@baz\") ...before" << endl;
step->call();
cout << "Around step (\"@baz\") ..after" << endl;
}
AFTER_STEP("@bar") {
cout << "After step (\"@bar\")" << endl;
}
AFTER("@foo") {
cout << "After scenario (\"@foo\")" << endl;
}
AFTER("@gherkin") {
cout << "After scenario (\"@gherkin\")" << endl;
}
/*
* CUKE_STEP_ is used just because the feature does not convey any
* business value. It should NEVER be used in real step definitions!
*/
CUKE_STEP_("^I'm running a step from a scenario not tagged$") {
cout << "Running step from scenario without tags" << endl;
EXPECT_TRUE(true); // To fix a problem at link time
}
CUKE_STEP_("^I'm running a step from a scenario tagged with (.*)$") {
REGEX_PARAM(string, tags);
cout << "Running step from scenario with tags: " << tags << endl;
EXPECT_TRUE(true); // To fix a problem at link time
}
| 22.741935 | 69 | 0.574468 | meshell |
e4caf51c0ab1d17d3e307e83a3f74cfedfd1c4ef | 932 | cpp | C++ | aws-cpp-sdk-sagemaker/source/model/Alarm.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-01-05T18:20:03.000Z | 2022-01-05T18:20:03.000Z | aws-cpp-sdk-sagemaker/source/model/Alarm.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-sagemaker/source/model/Alarm.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2022-03-23T15:17:18.000Z | 2022-03-23T15:17:18.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/sagemaker/model/Alarm.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace SageMaker
{
namespace Model
{
Alarm::Alarm() :
m_alarmNameHasBeenSet(false)
{
}
Alarm::Alarm(JsonView jsonValue) :
m_alarmNameHasBeenSet(false)
{
*this = jsonValue;
}
Alarm& Alarm::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("AlarmName"))
{
m_alarmName = jsonValue.GetString("AlarmName");
m_alarmNameHasBeenSet = true;
}
return *this;
}
JsonValue Alarm::Jsonize() const
{
JsonValue payload;
if(m_alarmNameHasBeenSet)
{
payload.WithString("AlarmName", m_alarmName);
}
return payload;
}
} // namespace Model
} // namespace SageMaker
} // namespace Aws
| 15.533333 | 69 | 0.703863 | perfectrecall |
e4cbcd1f69f4b00e194b33b4c2e1c5c893251641 | 708 | hpp | C++ | include/voxelio/macro.hpp | Eisenwave/voxel-io | d902568de2d4afda254e533a5ee9e4ad5fe7d2be | [
"MIT"
] | 12 | 2020-06-25T13:40:22.000Z | 2021-12-06T04:00:29.000Z | include/voxelio/macro.hpp | Eisenwave/voxel-io | d902568de2d4afda254e533a5ee9e4ad5fe7d2be | [
"MIT"
] | 2 | 2021-02-04T16:19:40.000Z | 2021-06-25T09:39:20.000Z | include/voxelio/macro.hpp | Eisenwave/voxel-io | d902568de2d4afda254e533a5ee9e4ad5fe7d2be | [
"MIT"
] | null | null | null | #ifndef VXIO_MACRO_HPP
#define VXIO_MACRO_HPP
#include "results.hpp"
#define VXIO_FORWARD_ERROR(expr) \
if (auto exprResult__ = expr; ::voxelio::isError(static_cast<::voxelio::ResultCode>(exprResult__))) { \
return exprResult__; \
}
#define VXIO_NO_EOF() \
if constexpr (::voxelio::build::DEBUG) \
VXIO_DEBUG_ASSERT(not this->stream.eof()); \
else if (this->stream.eof()) \
return ::voxelio::ReadResult::unexpectedEof(stream.position())
#endif // VXIO_MACRO_HPP
| 39.333333 | 107 | 0.487288 | Eisenwave |
e4cc16d81bd9b13a4d5fd21d54a3fca46968bd31 | 589 | cpp | C++ | examples/article_examples/hello_world_timer.cpp | jbandela/cppcomponents_libuv | 412fd05b32b7e01d4bd85e799d1e887537a4143a | [
"BSL-1.0"
] | 16 | 2015-04-09T06:27:45.000Z | 2021-11-21T15:43:38.000Z | examples/article_examples/hello_world_timer.cpp | jbandela/cppcomponents_libuv | 412fd05b32b7e01d4bd85e799d1e887537a4143a | [
"BSL-1.0"
] | 1 | 2015-07-30T00:08:59.000Z | 2015-07-30T00:08:59.000Z | examples/article_examples/hello_world_timer.cpp | jbandela/cppcomponents_libuv | 412fd05b32b7e01d4bd85e799d1e887537a4143a | [
"BSL-1.0"
] | 4 | 2015-02-26T20:01:16.000Z | 2021-11-11T05:25:10.000Z | #include <cppcomponents_libuv/cppcomponents_libuv.hpp>
using cppcomponents::Future;
int main(){
cppcomponents_libuv::Tty out{1,false};
Future<int> output_fut = out.Write("Hello world...");
output_fut.Then(
[&](Future<int> f){
cppcomponents_libuv::Timer::WaitFor(std::chrono::seconds{5}).Then([&](Future<int> f){
out.Write("See you later").Then([](Future<int> f){
cppcomponents_libuv::Uv::DefaultExecutor().MakeLoopExit();
});
});
}
);
cppcomponents_libuv::Uv::DefaultExecutor().Loop();
}
| 31 | 96 | 0.601019 | jbandela |
e4cfd11fccda7b927fdf0cafbf262445b37a573f | 2,815 | hpp | C++ | src/include/log_file_handler.hpp | violador/catalyst | 40d5c1dd04269a0764a9804711354a474bc43c15 | [
"Unlicense"
] | null | null | null | src/include/log_file_handler.hpp | violador/catalyst | 40d5c1dd04269a0764a9804711354a474bc43c15 | [
"Unlicense"
] | null | null | null | src/include/log_file_handler.hpp | violador/catalyst | 40d5c1dd04269a0764a9804711354a474bc43c15 | [
"Unlicense"
] | null | null | null | // ../src/include/log_file_handler.hpp ------------------------------------------------- //
//
// File author: Humberto Jr.
//
// Date: 09/2013
//
// Description: The log file handler defines the data struct of members that
// handles the usage of the log file. The overloaded << operat-
// or is also ready to operate in a variable of log file handl-
// er type such as an ofstream or fstream object. There are al-
// so member functions designed to write with all the format
// issues already built-in.
//
// References:
//
// ------------------------------------------------------------------------------------- //
#ifndef __LOG_FILE_HANDLER_HPP
#define __LOG_FILE_HANDLER_HPP
#include "globals.hpp"
#include "settings.hpp"
#include "global_settings.hpp"
#include "file_system.hpp"
#include "tools.hpp"
//
//
//
class log_file_handler
{
private:
//
// Declaring the data members:
file_system manager; // A pointer-object to link with any object of file_system type.
std::fstream log_file; // The internal fstream object to write the log file.
bool log_file_ready; // The fstream object creation state. True if created, false otherwise.
settings *config; // A pointer-object to link with any object of settings type.
time_t current_time;
struct tm *time_info;
char stamp[12];
//
// init_log_file(): To start the log file if it not exists yet.
void init_log_file();
//
//
void report_input_list();
//
// Including the inline/template/private member functions:
#include "log_file_handler__open.cpp"
#include "log_file_handler__close.cpp"
#include "log_file_handler__open_and_init.cpp"
#include "log_file_handler__report_bad_init.cpp"
//
public:
//
// Struct identifier:
static const int id = 12659;
//
// Declaring the class constructor:
log_file_handler();
//
// Declaring the class constructor:
log_file_handler(settings &runtime_setup);
//
// Declaring the class copy constructor:
log_file_handler(log_file_handler &given_log_file);
//
// Including the inline/template/public member functions:
#include "log_file_handler__write.cpp"
#include "log_file_handler__exists.cpp"
#include "log_file_handler__set_scientific_notation.cpp"
#include "log_file_handler__set_fixed.cpp"
#include "log_file_handler__set_width.cpp"
#include "log_file_handler__set_right.cpp"
#include "log_file_handler__set_left.cpp"
#include "log_file_handler__set_new_line.cpp"
#include "log_file_handler__fill_line_with.cpp"
#include "log_file_handler__write_title_bar.cpp"
#include "log_file_handler__timestamp.cpp"
#include "log_file_handler__bitwise_left_shift.cpp"
#include "log_file_handler__write_debug_msg.cpp"
#include "log_file_handler__set_config.cpp"
#include "log_file_handler__destructor.cpp"
//
};
#endif
| 32.732558 | 95 | 0.711901 | violador |
e4e157ac23bd111bbfbd8a9f74a737ae0948f6b2 | 603 | cpp | C++ | libnes/emu.cpp | am1ko/nes | 4c1addaa6331733ccde90a3d9a0eed74968e859e | [
"MIT"
] | null | null | null | libnes/emu.cpp | am1ko/nes | 4c1addaa6331733ccde90a3d9a0eed74968e859e | [
"MIT"
] | null | null | null | libnes/emu.cpp | am1ko/nes | 4c1addaa6331733ccde90a3d9a0eed74968e859e | [
"MIT"
] | null | null | null | #include "emu.h"
Emu::Emu(Cpu& cpu, Ppu& ppu) : cpu(cpu), ppu(ppu) {}
// ---------------------------------------------------------------------------------------------- //
void Emu::reset() {
cpu.reset();
ppu.reset();
}
// ---------------------------------------------------------------------------------------------- //
unsigned Emu::tick() {
unsigned const ret = cpu.tick();
for (unsigned i = 0U; i < ret*3U; i++) {
bool const irq = ppu.tick();
if (irq) {
cpu.set_interrupt_pending(CpuInterrupt::InterruptSource::NMI);
}
}
return ret;
}
| 25.125 | 100 | 0.356551 | am1ko |
e4e3ac596b384b17e121ba89e933db0f300d596a | 5,481 | hpp | C++ | mainwindow.hpp | NuarkNoir/toynote | ba7fdb8a8d93012123e4125dae1dcdb4cf2e9b51 | [
"Unlicense"
] | null | null | null | mainwindow.hpp | NuarkNoir/toynote | ba7fdb8a8d93012123e4125dae1dcdb4cf2e9b51 | [
"Unlicense"
] | null | null | null | mainwindow.hpp | NuarkNoir/toynote | ba7fdb8a8d93012123e4125dae1dcdb4cf2e9b51 | [
"Unlicense"
] | null | null | null | /*!
* \file
* \brief Заголовочный файл класса MainWindow.
* \author Кирилл Пушкарёв
* \date 2017
*/
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <memory> // unique_ptr
#include <QItemSelection>
#include <QMainWindow>
#include "notebook.hpp"
// Объявляем класс Ui::MainWindow, чтобы ниже можно было упоминать указатели на него,
// не включая определение класса. Этот класс создаётся автоматически из UI-файла.
// Данное объявление также было создано автоматически, когда Qt Creator
// добавлял в проект UI-файл и класс для него.
namespace Ui {
class MainWindow;
}
/*!
* \brief Класс главного окна программы.
*
* Отвечает за реализацию функций, специфичных для данной конкретной
* программы. За реализацию функций, общих для всех программ с графическим
* интерфейсом, отвечает класс QMainWindow из библиотеки Qt.
*
* MainWindow является производным классом от QMainWindow и может добавлять свои
* атрибуты и методы к тем, которые уже есть в QMainWindow.
*/
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
//! Конструктор с необязательным указанием родительского объекта \a parent.
explicit MainWindow(QWidget *parent = 0);
//! Деструктор MainWindow.
~MainWindow();
//! Событие закрытия приложения
void closeEvent(QCloseEvent *event);
/*
* В этом разделе перечисляются слоты — методы, которые могут получать и
* обрабатывать сигналы, например от активации пункта меню
*/
private slots:
//! Отображает окно с информацией о программе.
void displayAbout();
//! Создаёт новую записную книжку.
void newNotebook();
//! Сохраняет текущую записную книжку. Возвращает \c true в случае успеха.
bool saveNotebook();
//! Сохраняет текущую записную книжку в указанном пользователем файле. Возвращает \c true в случае успеха.
bool saveNotebookAs();
//! Открывает записную книжку вместо текущей. Возвращает \c true в случае успеха.
bool openNotebook();
//! Закрывает текущую записную книжку. Возвращает \c true в случае успеха.
bool closeNotebook();
//! Создаёт новую заметку в текущей записной книжке. Возвращает \c true в случае успеха.
bool newNote();
//! Удаляет выбранные заметки из текущей записной книжки.
void deleteNotes();
//! Обновляет интерфейс окна.
void updateUI();
//! Обновляет заголовок окна.
void refreshWindowTitle();
//! Закрывает приложение.
void on_actionExit_triggered();
//! Открывает еКурсы.
void on_actionVisit_eCourses_triggered();
//! Экспортирует заметки в текстовом формате.
void on_actionSave_As_Text_triggered();
//! Запускает диалог лотереи.
void on_actionLottery_triggered();
//! Запускает диалог редактирования заметки
void on_notesView_activated(const QModelIndex &index);
//! Запускает поиск текста заметки в интернете
void on_actionWeb_search_triggered();
// В этом разделе перечисляются сигналы, которые выдаёт данный класс
signals:
/*!
* \brief Сигнал об изменении имени открытого файла.
* \param name Новое имя файла записной книжки.
*
* Сигнализирует, что имени открытого файла записной книжки присвоено
* значение \a name.
*/
void notebookFileNameChanged(QString name);
//! Сигнализирует, что записная книжка готова к работе с пользователем (после создания или открытия).
void notebookReady();
//! Сигнализирует, что записная книжка успешно создана.
void notebookCreated();
/*!
* \brief Сигнализирует, что записная книжка успешно открыта.
* \param fileName Имя файла открытой записной книжки.
*/
void notebookOpened(QString fileName);
//! Сигнализирует, что записная книжка успешно сохранена.
void notebookSaved();
//! Сигнализирует, что записная книжка успешно закрыта.
void notebookClosed();
/*
* В этом разделе перечисляются закрытые члены класса, которые обеспечивают
* его работу и недоступны извне.
*/
private:
/*!
* \brief Сохраняет текущую записную книжку в файл.
* \param fileName Имя файла.
*/
void saveNotebookToFile(QString fileName);
//! Возвращает \c true, если в настоящий момент имеется открытая записная книжка.
bool isNotebookOpen() const;
//! Устанавливает имя файла текущей записной книжки равным \a name.
void setNotebookFileName(QString name = QString());
//! Возвращает имя файла текущей записной книжки.
QString notebookName() const;
//! Создаёт новую записную книжку.
void createNotebook();
//! Устанавливает указатель на текущую записную книжку равным \a notebook.
void setNotebook(Notebook *notebook);
//! Уничтожает объект текущей записной книжки.
void destroyNotebook();
/*!
* \brief Указатель на сгенерированный интерфейс.
*
* Указатель на объект UI-класса, сгенерированного на основе UI-файла
* mainwindow.ui.
*
* Через этот указатель можно обратиться к элементам главного окна,
* созданного в Qt Designer.
* \sa \ref faq_qt_designer_whatis
*/
Ui::MainWindow *mUi;
/*!
* \brief Указатель на текущую записную книжку.
* \note std::unique_ptr, в целом, ведёт себя как обычный указатель, но
* автоматически удаляет указуемый объект при присваивании другого значения
* или уничтожении самого unique_ptr.
*/
std::unique_ptr<Notebook> mNotebook;
//! Имя файла текущей записной книжки.
QString mNotebookFileName;
};
#endif // MAINWINDOW_H
| 35.823529 | 110 | 0.713009 | NuarkNoir |
e4e3ca9534d7b4cb05ba68061ff52a6a1551e45f | 4,314 | cpp | C++ | test/multi_type_vector/perf/test_main.cpp | kohei101/multidimalgorithm | c479747d204b8953933fdbec9a88650a75b822b7 | [
"MIT"
] | 3 | 2018-10-08T16:30:06.000Z | 2018-10-24T05:05:11.000Z | test/multi_type_vector/perf/test_main.cpp | kohei101/mdds | c479747d204b8953933fdbec9a88650a75b822b7 | [
"MIT"
] | null | null | null | test/multi_type_vector/perf/test_main.cpp | kohei101/mdds | c479747d204b8953933fdbec9a88650a75b822b7 | [
"MIT"
] | null | null | null | /*************************************************************************
*
* Copyright (c) 2011-2013 Kohei Yoshida
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
************************************************************************/
#include "test_global.hpp" // This must be the first header to be included.
#include <mdds/multi_type_vector.hpp>
#include <mdds/multi_type_vector_trait.hpp>
#include <cassert>
#include <sstream>
#include <vector>
#include <deque>
using namespace std;
using namespace mdds;
namespace {
typedef mdds::multi_type_vector<mdds::mtv::element_block_func> mtv_type;
void mtv_perf_test_block_position_lookup()
{
size_t n = 24000;
{
// Default insertion which always looks up the right element block
// from the position of the first block. As such, as the block size
// grows, so does the time it takes to search for the right block.
mtv_type db(n * 2);
double val1 = 1.1;
int val2 = 23;
stack_printer __stack_printer__("::mtv_perf_test_block_position_lookup::default insertion");
for (size_t i = 0; i < n; ++i)
{
size_t pos1 = i * 2, pos2 = i * 2 + 1;
db.set(pos1, val1);
db.set(pos2, val2);
}
}
{
// As a solution for this, we can use an iterator to specify the start
// position, which eliminates the above scalability problem nicely.
mtv_type db(n * 2);
mtv_type::iterator pos_hint = db.begin();
double val1 = 1.1;
int val2 = 23;
stack_printer __stack_printer__("::mtv_perf_test_block_position_lookup::insertion with position hint");
for (size_t i = 0; i < n; ++i)
{
size_t pos1 = i * 2, pos2 = i * 2 + 1;
pos_hint = db.set(pos_hint, pos1, val1);
pos_hint = db.set(pos_hint, pos2, val2);
}
}
}
void mtv_perf_test_insert_via_position_object()
{
size_t data_size = 80000;
mtv_type db(data_size);
{
stack_printer __stack_printer__("::mtv_perf_test_insert_via_position_object initialize mtv.");
mtv_type::iterator it = db.begin();
for (size_t i = 0, n = db.size() / 2; i < n; ++i)
{
it = db.set(it, i * 2, 1.1);
}
}
mtv_type db2 = db;
{
stack_printer __stack_printer__("::mtv_perf_test_insert_via_position_object insert with position hint.");
mtv_type::iterator it = db2.begin();
for (size_t i = 0, n = db2.size(); i < n; ++i)
{
it = db2.set(it, i, string("foo"));
}
}
db2 = db;
{
stack_printer __stack_printer__("::mtv_perf_test_insert_via_position_object insert via position object.");
mtv_type::position_type pos = db2.position(0);
for (; pos.first != db2.end(); pos = mtv_type::next_position(pos))
{
size_t log_pos = mtv_type::logical_position(pos);
pos.first = db2.set(pos.first, log_pos, string("foo"));
pos.second = log_pos - pos.first->position;
}
}
}
} // namespace
int main()
try
{
mtv_perf_test_block_position_lookup();
mtv_perf_test_insert_via_position_object();
return EXIT_SUCCESS;
}
catch (...)
{
return EXIT_FAILURE;
}
| 32.19403 | 114 | 0.623783 | kohei101 |
e4e44608ae31175b57a7dc94c830397e0c06dcba | 2,363 | cpp | C++ | src/widgets/SettingsDialog.cpp | picardb/QtRemote | 049610cb93d01eec21f923b2fa824f15318d07bc | [
"MIT"
] | null | null | null | src/widgets/SettingsDialog.cpp | picardb/QtRemote | 049610cb93d01eec21f923b2fa824f15318d07bc | [
"MIT"
] | null | null | null | src/widgets/SettingsDialog.cpp | picardb/QtRemote | 049610cb93d01eec21f923b2fa824f15318d07bc | [
"MIT"
] | null | null | null | /* This source file is distributed under the MIT license
* (see attached LICENSE.txt file for details)
*/
#include "SettingsDialog.h"
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QLabel>
#include <QFileDialog>
#include "globals.h"
/*
* SettingsDialog::SettingsDialog
*
* SettingsDialog constructor. Creates and lays out the children widgets.
*
* Parameters:
* - parent: pointer to the parent widget (optional)
* - f: window flags (optional)
*/
SettingsDialog::SettingsDialog(QWidget *parent, Qt::WindowFlags f)
: QDialog(parent, f)
{
/* Create layout */
QVBoxLayout *pMainLayout = new QVBoxLayout;
/* Create log directory edit */
QHBoxLayout *pLogLayout = new QHBoxLayout;
QLabel *pLogDirLabel = new QLabel("Log directory: ");
pLogLayout->addWidget(pLogDirLabel);
m_pLogDirEdit = new QLineEdit;
m_pLogDirEdit->setText(g_appSettings.value("LOG_DIR").toString());
pLogLayout->addWidget(m_pLogDirEdit);
m_pLogBrowseButton = new QPushButton("Browse");
connect(m_pLogBrowseButton, SIGNAL(clicked(bool)),
this, SLOT(onLogBrowseButtonClicked()));
pLogLayout->addWidget(m_pLogBrowseButton);
pMainLayout->addLayout(pLogLayout);
/* Create OK/Cancel buttons */
QHBoxLayout *pButtonsLayout = new QHBoxLayout;
m_pOkButton = new QPushButton("OK");
m_pOkButton->setDefault(true);
pButtonsLayout->addWidget(m_pOkButton, 0, Qt::AlignRight);
connect(m_pOkButton, SIGNAL(clicked(bool)),
this, SLOT(accept()));
m_pCancelButton = new QPushButton("Cancel");
pButtonsLayout->addWidget(m_pCancelButton, 0, Qt::AlignLeft);
connect(m_pCancelButton, SIGNAL(clicked(bool)),
this, SLOT(reject()));
pMainLayout->addLayout(pButtonsLayout);
/* Setup dialog */
setLayout(pMainLayout);
setWindowFlags(Qt::Dialog | Qt::MSWindowsFixedSizeDialogHint);
setWindowTitle("Settings");
}
/*
* SettingsDialog::onLogBrowseButtonClicked
*
* Slot called when the log directory "Browse" button is clicked.
*
* Parameters: none
*
* Return value: none
*/
void SettingsDialog::onLogBrowseButtonClicked() {
/* Create a file dialog */
QString newDir = QFileDialog::getExistingDirectory(this, "Select a results directory", m_pLogDirEdit->text());
if (newDir != "") {
m_pLogDirEdit->setText(newDir);
}
}
| 29.5375 | 114 | 0.700804 | picardb |
e4e7894cf82f25fc8b679efd1bb9d930c8517891 | 4,101 | cpp | C++ | bindings/python/src/LibraryCorePy/Types/Integer.cpp | cowlicks/library-core | 9a872ab7aa6bc4aba22734705b72dc22ea35ee77 | [
"Apache-2.0"
] | null | null | null | bindings/python/src/LibraryCorePy/Types/Integer.cpp | cowlicks/library-core | 9a872ab7aa6bc4aba22734705b72dc22ea35ee77 | [
"Apache-2.0"
] | null | null | null | bindings/python/src/LibraryCorePy/Types/Integer.cpp | cowlicks/library-core | 9a872ab7aa6bc4aba22734705b72dc22ea35ee77 | [
"Apache-2.0"
] | 1 | 2020-12-01T14:50:50.000Z | 2020-12-01T14:50:50.000Z | ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @project Library ▸ Core
/// @file LibraryCorePy/Types/Integer.cpp
/// @author Lucas Brémond <lucas@loftorbital.com>
/// @license Apache License 2.0
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include <Library/Core/Types/Integer.hpp>
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
inline void LibraryCorePy_Types_Integer ( )
{
using namespace boost::python ;
using library::core::types::Integer ;
using library::core::types::Real ;
using library::core::types::String ;
class_<Integer>("Integer", init<int>())
.def(int_(self))
.def(self == self)
.def(self != self)
.def(self < self)
.def(self <= self)
.def(self > self)
.def(self >= self)
.def(self + self)
.def(self += self)
.def(self - self)
.def(self -= self)
.def(self * self)
.def(self *= self)
.def(self / self)
.def(self /= self)
.def(self + int())
.def(self += int())
.def(self - int())
.def(self -= int())
.def(self * int())
.def(self *= int())
.def(self / int())
.def(self /= int())
.def(int() + self)
.def(int() - self)
.def(int() * self)
.def(int() / self)
.def("__str__", +[] (const library::core::types::Integer& anInteger) -> std::string { return anInteger.toString() ; })
.def("__repr__", +[] (const library::core::types::Integer& anInteger) -> std::string { return anInteger.toString() ; })
.def("isDefined", &Integer::isDefined)
.def("isZero", &Integer::isZero)
.def("isPositive", &Integer::isPositive)
.def("isNegative", &Integer::isNegative)
.def("isStrictlyPositive", &Integer::isStrictlyPositive)
.def("isStrictlyNegative", &Integer::isStrictlyNegative)
.def("isInfinity", &Integer::isInfinity)
.def("isPositiveInfinity", &Integer::isPositiveInfinity)
.def("isNegativeInfinity", &Integer::isNegativeInfinity)
.def("isFinite", &Integer::isFinite)
.def("isEven", &Integer::isEven)
.def("isOdd", &Integer::isOdd)
.def("getSign", &Integer::getSign)
.def("toString", &Integer::toString)
.def("Undefined", &Integer::Undefined).staticmethod("Undefined")
.def("Zero", &Integer::Zero).staticmethod("Zero")
.def("PositiveInfinity", &Integer::PositiveInfinity).staticmethod("PositiveInfinity")
.def("NegativeInfinity", &Integer::NegativeInfinity).staticmethod("NegativeInfinity")
.def("Int8", &Integer::Int8).staticmethod("Int8")
.def("Int16", &Integer::Int16).staticmethod("Int16")
.def("Int32", &Integer::Int32).staticmethod("Int32")
.def("Int64", &Integer::Int64).staticmethod("Int64")
.def("Uint8", &Integer::Uint8).staticmethod("Uint8")
.def("Uint16", &Integer::Uint16).staticmethod("Uint16")
.def("Uint32", &Integer::Uint32).staticmethod("Uint32")
.def("Uint64", &Integer::Uint64).staticmethod("Uint64")
.def("Index", &Integer::Index).staticmethod("Index")
.def("Size", &Integer::Size).staticmethod("Size")
.def("CanParse", static_cast<bool(*)(const String&)>(&Integer::CanParse)).staticmethod("CanParse")
.def("Parse", static_cast<Integer(*)(const String&)>(&Integer::Parse)).staticmethod("Parse")
;
implicitly_convertible<Integer, int>() ;
implicitly_convertible<int, Integer>() ;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
| 40.60396 | 160 | 0.486467 | cowlicks |
e4ea88aac26fcc1cbc391368d23aa4840ebd9abe | 109 | hh | C++ | build/x86/mem/protocol/RubyRequest.hh | billionshang/gem5 | 18cc4294f32315595f865d07d1f33434e92b06b2 | [
"BSD-3-Clause"
] | null | null | null | build/x86/mem/protocol/RubyRequest.hh | billionshang/gem5 | 18cc4294f32315595f865d07d1f33434e92b06b2 | [
"BSD-3-Clause"
] | null | null | null | build/x86/mem/protocol/RubyRequest.hh | billionshang/gem5 | 18cc4294f32315595f865d07d1f33434e92b06b2 | [
"BSD-3-Clause"
] | null | null | null | #include "/mnt/hgfs/ShareShen/gem5-origin-stable-2015-9-3/build/x86/mem/ruby/slicc_interface/RubyRequest.hh"
| 54.5 | 108 | 0.807339 | billionshang |
e4eda83af21b6ce02a47bda2b18e178204a81045 | 2,972 | cc | C++ | src/base/varint-encoding.cc | emptyland/nyaa | e2092a086869342b14de51c2afc1246500dbf47d | [
"BSD-2-Clause"
] | null | null | null | src/base/varint-encoding.cc | emptyland/nyaa | e2092a086869342b14de51c2afc1246500dbf47d | [
"BSD-2-Clause"
] | null | null | null | src/base/varint-encoding.cc | emptyland/nyaa | e2092a086869342b14de51c2afc1246500dbf47d | [
"BSD-2-Clause"
] | null | null | null | #include "base/varint-encoding.h"
namespace nyaa {
namespace base {
#define TEST_OR_SET(c) b = ((in & 0x7FU << (c * 7)) >> (c * 7))
#define FILL_AND_TEST_OR_SET(c) \
out[i++] = (b | 0x80); \
TEST_OR_SET(c)
/*static*/ size_t Varint32::Encode(void *buf, uint32_t in) {
size_t i = 0;
uint8_t b;
auto out = static_cast<uint8_t *>(buf);
if ((b = ((in & 0xFU << 28) >> 28)) != 0) // 29~32
goto bit_28_k5;
if ((TEST_OR_SET(3)) != 0) // 22~28
goto bit_21_k6;
if ((TEST_OR_SET(2)) != 0) // 15~21
goto bit_14_k7;
if ((TEST_OR_SET(1)) != 0) // 8~14
goto bit_07_k8;
TEST_OR_SET(0);
out[i++] = b;
return i;
bit_28_k5:
FILL_AND_TEST_OR_SET(3);
bit_21_k6:
FILL_AND_TEST_OR_SET(2);
bit_14_k7:
FILL_AND_TEST_OR_SET(1);
bit_07_k8:
FILL_AND_TEST_OR_SET(0);
out[i++] = b;
return i;
}
#undef FILL_AND_TEST_OR_SET
#undef TEST_OR_SET
#define TEST_OR_SET(c) b = ((in & 0x7fULL << (c * 7)) >> (c * 7))
#define FILL_AND_TEST_OR_SET(c) \
out[i++] = (b | 0x80); \
TEST_OR_SET(c)
/*static*/ size_t Varint64::Encode(void *buf, uint64_t in) {
size_t i = 0;
uint8_t b;
auto out = static_cast<uint8_t *>(buf);
// [+---+---+---+---]
if (in & 0xFFFE000000000000ULL) {
if ((b = ((in & 0x1ULL << 63) >> 63)) != 0) // 64
goto bit_63_k0;
if ((TEST_OR_SET(8)) != 0) // 58~63
goto bit_56_k1;
if ((TEST_OR_SET(7)) != 0) // 50~57
goto bit_49_k2;
}
// [-+---+---+---]
if (in & 0x1FFFFF0000000ULL) {
if ((TEST_OR_SET(6)) != 0) // 43~49
goto bit_42_k3;
if ((TEST_OR_SET(5)) != 0) // 36~42
goto bit_35_k4;
if ((TEST_OR_SET(4)) != 0) // 29~35
goto bit_28_k5;
}
// [---+---]
if (in & 0xFFFFF80ULL) {
if ((TEST_OR_SET(3)) != 0) // 22~28
goto bit_21_k6;
if ((TEST_OR_SET(2)) != 0) // 15~21
goto bit_14_k7;
if ((TEST_OR_SET(1)) != 0) // 8~14
goto bit_07_k8;
}
TEST_OR_SET(0);
out[i++] = b;
return i;
bit_63_k0:
FILL_AND_TEST_OR_SET(8);
bit_56_k1:
FILL_AND_TEST_OR_SET(7);
bit_49_k2:
FILL_AND_TEST_OR_SET(6);
bit_42_k3:
FILL_AND_TEST_OR_SET(5);
bit_35_k4:
FILL_AND_TEST_OR_SET(4);
bit_28_k5:
FILL_AND_TEST_OR_SET(3);
bit_21_k6:
FILL_AND_TEST_OR_SET(2);
bit_14_k7:
FILL_AND_TEST_OR_SET(1);
bit_07_k8:
FILL_AND_TEST_OR_SET(0);
out[i++] = b;
return i;
}
#undef FILL_AND_TEST_OR_SET
#undef TEST_OR_SET
/*static*/ uint64_t Varint64::Decode(const void *buf, size_t *len) {
size_t i = 0;
uint8_t b;
uint64_t out = 0;
auto in = static_cast<const uint8_t *>(buf);
while ((b = in[i++]) >= 0x80) {
out |= (b & 0x7f);
out <<= 7;
}
out |= b; // last 7bit
*len = i;
return out;
}
} // namespace base
} // namespace nyaa
| 23.967742 | 68 | 0.53432 | emptyland |
e4f083a8855ae7c69d4e8e357a5d31b735235454 | 290 | cc | C++ | src/NOP.cc | domahony/6502Emulator | dbc1088998966ce4d59b9a38e5fe08dfcb1bfcf9 | [
"MIT"
] | null | null | null | src/NOP.cc | domahony/6502Emulator | dbc1088998966ce4d59b9a38e5fe08dfcb1bfcf9 | [
"MIT"
] | 1 | 2015-02-04T01:30:10.000Z | 2015-02-04T01:30:10.000Z | src/NOP.cc | domahony/6502Emulator | dbc1088998966ce4d59b9a38e5fe08dfcb1bfcf9 | [
"MIT"
] | null | null | null | /*
* NOP.cc
*
* Created on: Feb 16, 2015
* Author: domahony
*/
#include "NOP.h"
#include "CPU.h"
using domahony::emu::CPU;
void
initNOP(std::function<int (domahony::emu::CPU&)> *fn)
{
/*
* NOP
*/
// implied
fn[0xea] = [](CPU& cpu) {
cpu.NOP();
return 2;
};
}
| 9.666667 | 53 | 0.531034 | domahony |
e4f0b2741b7e892fefa56b36bfad4a92a1a7e51d | 7,184 | cpp | C++ | dlls/Game/scene/inPlay/GameOver.cpp | Mynsu/sirtet_SFML | ad1b64597868959d96d27fcb73fd272f41b21e16 | [
"MIT"
] | null | null | null | dlls/Game/scene/inPlay/GameOver.cpp | Mynsu/sirtet_SFML | ad1b64597868959d96d27fcb73fd272f41b21e16 | [
"MIT"
] | null | null | null | dlls/Game/scene/inPlay/GameOver.cpp | Mynsu/sirtet_SFML | ad1b64597868959d96d27fcb73fd272f41b21e16 | [
"MIT"
] | null | null | null | #include "../../pch.h"
#include "GameOver.h"
#include "../../ServiceLocatorMirror.h"
bool scene::inPlay::GameOver::IsInstantiated = false;
scene::inPlay::GameOver::GameOver( const sf::RenderWindow& window,
sf::Drawable& shapeOrSprite,
std::unique_ptr<::scene::inPlay::IScene>& overlappedScene )
: mTargetAlpha( 0x7f ), mFade( 0xff ), mFrameCountToMainMenu( 0 ), mBackgroundRGB( 0x29cdb500 ), // Cyan
mBackgroundRect_( (sf::RectangleShape&)shapeOrSprite )
{
ASSERT_TRUE( false == IsInstantiated );
overlappedScene.reset( );
auto& vault = gService()->vault();
const auto it = vault.find(HK_FORE_FPS);
ASSERT_TRUE( vault.end() != it );
mFPS_ = (uint16_t)it->second;
loadResources( window );
if ( false == gService()->sound().playBGM(mSoundPaths[(int)SoundIndex::BGM]) )
{
gService()->console().printFailure(FailureLevel::WARNING,
"File Not Found: "+mSoundPaths[(int)SoundIndex::BGM] );
}
IsInstantiated = true;
}
scene::inPlay::GameOver::~GameOver()
{
IsInstantiated = false;
}
void scene::inPlay::GameOver::loadResources( const sf::RenderWindow& window )
{
sf::Vector2f imageSize( 512.f, 256.f );
std::string imagePath( "Images/GameOver.png" );
mSoundPaths[(int)SoundIndex::BGM] = "Sounds/gameOver.wav";
lua_State* lua = luaL_newstate();
const std::string scriptPath( "Scripts/GameOver.lua" );
if ( true == luaL_dofile(lua, scriptPath.data()) )
{
gService()->console().printFailure( FailureLevel::FATAL,
"File Not Found: "+scriptPath );
}
else
{
luaL_openlibs( lua );
const int TOP_IDX = -1;
std::string varName( "Background" );
lua_getglobal( lua, varName.data() );
int type = lua_type(lua, TOP_IDX);
if ( LUA_TNUMBER == type )
{
mBackgroundRGB = (uint32_t)lua_tointeger(lua, TOP_IDX);
}
else if ( LUA_TNIL == type )
{
gService()->console().printScriptError( ExceptionType::VARIABLE_NOT_FOUND,
varName, scriptPath );
}
else
{
gService()->console().printScriptError( ExceptionType::TYPE_CHECK,
varName, scriptPath );
}
lua_pop( lua, 1 );
varName = "TargetAlpha";
lua_getglobal(lua, varName.data() );
type = lua_type(lua, TOP_IDX);
if ( LUA_TNUMBER == type )
{
mTargetAlpha = (uint8_t)lua_tointeger(lua, TOP_IDX);
}
else if ( LUA_TNIL == type )
{
gService()->console().printScriptError( ExceptionType::VARIABLE_NOT_FOUND,
varName, scriptPath );
}
else
{
gService()->console().printScriptError( ExceptionType::TYPE_CHECK,
varName, scriptPath );
}
lua_pop( lua, 1 );
std::string tableName( "Image" );
lua_getglobal( lua, tableName.data() );
if ( false == lua_istable(lua, TOP_IDX) )
{
gService()->console().printScriptError( ExceptionType::TYPE_CHECK, tableName, scriptPath );
}
else
{
std::string field( "path" );
lua_pushstring( lua, field.data() );
lua_gettable( lua, 1 );
type = lua_type(lua, TOP_IDX);
if ( LUA_TSTRING == type )
{
imagePath = lua_tostring(lua, TOP_IDX);
}
else if ( LUA_TNIL == type )
{
gService()->console().printScriptError( ExceptionType::VARIABLE_NOT_FOUND,
tableName+':'+field, scriptPath );
}
else
{
gService()->console().printScriptError( ExceptionType::TYPE_CHECK,
tableName+':'+field, scriptPath );
}
lua_pop( lua, 1 );
field = "width";
lua_pushstring( lua, field.data() );
lua_gettable( lua, 1 );
type = lua_type(lua, TOP_IDX);
if ( LUA_TNUMBER == type )
{
const float temp = (float)lua_tonumber(lua, TOP_IDX);
if ( 0 > temp )
{
gService()->console().printScriptError( ExceptionType::RANGE_CHECK,
tableName+':'+field, scriptPath );
}
else
{
imageSize.x = temp;
}
}
else if ( LUA_TNIL == type )
{
gService()->console().printScriptError( ExceptionType::VARIABLE_NOT_FOUND,
tableName+':'+field, scriptPath );
}
else
{
gService()->console().printScriptError( ExceptionType::TYPE_CHECK,
tableName+':'+field, scriptPath );
}
lua_pop( lua, 1 );
field = "height";
lua_pushstring( lua, field.data() );
lua_gettable( lua, 1 );
type = lua_type(lua, TOP_IDX);
if ( LUA_TNUMBER == type )
{
const float temp = (float)lua_tonumber(lua, TOP_IDX);
if ( 0 > temp )
{
gService()->console().printScriptError( ExceptionType::RANGE_CHECK,
tableName+':'+field, scriptPath );
}
else
{
imageSize.y = temp;
}
}
else if ( LUA_TNIL == type )
{
gService()->console().printScriptError( ExceptionType::VARIABLE_NOT_FOUND,
tableName+':'+field, scriptPath );
}
else
{
gService()->console().printScriptError( ExceptionType::TYPE_CHECK,
tableName+':'+field, scriptPath );
}
lua_pop( lua, 1 );
}
lua_pop( lua, 1 );
tableName = "Sound";
lua_getglobal( lua, tableName.data() );
if ( false == lua_istable(lua, TOP_IDX) )
{
gService()->console().printScriptError( ExceptionType::TYPE_CHECK, tableName, scriptPath );
}
else
{
std::string innerTableName( "BGM" );
lua_pushstring( lua, innerTableName.data() );
lua_gettable( lua, 1 );
if ( false == lua_istable(lua, TOP_IDX) )
{
gService()->console().printScriptError( ExceptionType::TYPE_CHECK,
tableName+':'+innerTableName, scriptPath );
}
else
{
std::string field( "path" );
lua_pushstring( lua, field.data() );
lua_gettable( lua, 2 );
int type = lua_type(lua, TOP_IDX);
if ( LUA_TSTRING == type )
{
mSoundPaths[(int)SoundIndex::BGM] = lua_tostring(lua, TOP_IDX);
}
else if ( LUA_TNIL == type )
{
gService()->console().printScriptError( ExceptionType::VARIABLE_NOT_FOUND,
tableName+':'+field, scriptPath );
}
else
{
gService()->console().printScriptError( ExceptionType::TYPE_CHECK,
tableName+':'+field, scriptPath );
}
lua_pop( lua, 1 );
}
lua_pop( lua, 1 );
}
lua_pop( lua, 1 );
}
lua_close( lua );
if ( false == mTexture.loadFromFile(imagePath) )
{
gService()->console().printFailure( FailureLevel::WARNING,
"File Not Found: "+imagePath );
}
mSprite.setTexture( mTexture );
mSprite.setTextureRect( sf::IntRect(sf::Vector2i(0, 0), sf::Vector2i(imageSize)) );
mSprite.setOrigin( imageSize*0.5f );
mSprite.setPosition( sf::Vector2f(window.getSize())*0.5f );
}
::scene::inPlay::ID scene::inPlay::GameOver::update( std::vector<sf::Event>& )
{
::scene::inPlay::ID retVal = ::scene::inPlay::ID::AS_IS;
// When mFade reaches the target,
if ( mFade <= mTargetAlpha )
{
// Frame counting starts.
++mFrameCountToMainMenu;
// 3 seconds after,
if ( 3*mFPS_ == mFrameCountToMainMenu )
{
retVal = ::scene::inPlay::ID::EXIT;
}
}
return retVal;
}
void scene::inPlay::GameOver::draw( sf::RenderWindow& window )
{
if ( mTargetAlpha < mFade )
{
mFade -= 2u;
mBackgroundRect_.setFillColor( sf::Color(mBackgroundRGB | mFade) );
window.draw( mBackgroundRect_ );
}
else
{
window.draw( mBackgroundRect_ );
window.draw( mSprite );
}
}
| 26.80597 | 105 | 0.627366 | Mynsu |
e4f471d665ee67e7cf16ce85c6e80bf57482736e | 3,748 | hpp | C++ | include/af/autograd/Functions.hpp | syurkevi/arrayfire-ml | fde97a5bf157936c8d904d0c857c6cb3275ee527 | [
"BSD-3-Clause"
] | 106 | 2015-07-29T14:41:22.000Z | 2021-12-03T23:46:17.000Z | include/af/autograd/Functions.hpp | syurkevi/arrayfire-ml | fde97a5bf157936c8d904d0c857c6cb3275ee527 | [
"BSD-3-Clause"
] | 30 | 2015-08-05T00:27:17.000Z | 2022-03-25T10:24:30.000Z | include/af/autograd/Functions.hpp | arrayfire/arrayfire-ml | fde97a5bf157936c8d904d0c857c6cb3275ee527 | [
"BSD-3-Clause"
] | 19 | 2015-07-29T15:18:05.000Z | 2021-10-05T05:36:31.000Z | /*******************************************************
* Copyright (c) 2017, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#pragma once
#include <arrayfire.h>
#include <vector>
namespace af {
namespace autograd {
class Variable;
Variable operator +(const Variable &lhs, const Variable &rhs);
Variable operator *(const Variable &lhs, const Variable &rhs);
Variable operator -(const Variable &lhs, const Variable &rhs);
Variable operator /(const Variable &lhs, const Variable &rhs);
Variable operator >(const Variable &lhs, const Variable &rhs);
Variable operator <(const Variable &lhs, const Variable &rhs);
Variable operator >=(const Variable &lhs, const Variable &rhs);
Variable operator <=(const Variable &lhs, const Variable &rhs);
Variable operator +(const double &lhs, const Variable &rhs);
Variable operator *(const double &lhs, const Variable &rhs);
Variable operator -(const double &lhs, const Variable &rhs);
Variable operator /(const double &lhs, const Variable &rhs);
Variable operator >(const double &lhs, const Variable &rhs);
Variable operator <(const double &lhs, const Variable &rhs);
Variable operator >=(const double &lhs, const Variable &rhs);
Variable operator <=(const double &lhs, const Variable &rhs);
Variable operator +(const Variable &lhs, const double &rhs);
Variable operator *(const Variable &lhs, const double &rhs);
Variable operator -(const Variable &lhs, const double &rhs);
Variable operator /(const Variable &lhs, const double &rhs);
Variable operator >(const Variable &lhs, const double &rhs);
Variable operator <(const Variable &lhs, const double &rhs);
Variable operator >=(const Variable &lhs, const double &rhs);
Variable operator <=(const Variable &lhs, const double &rhs);
Variable operator !(const Variable &input);
Variable negate(const Variable &input);
Variable reciprocal(const Variable &input);
Variable exp(const Variable &input);
Variable log(const Variable &input);
Variable sin(const Variable &input);
Variable cos(const Variable &input);
Variable tanh(const Variable &input);
Variable sigmoid(const Variable &input);
Variable max(const Variable &lhs, const Variable &rhs);
Variable max(const Variable &lhs, const double &rhs);
Variable max(const double &lhs, const Variable &rhs);
Variable min(const Variable &lhs, const Variable &rhs);
Variable min(const Variable &lhs, const double &rhs);
Variable min(const double &lhs, const Variable &rhs);
Variable transpose(const Variable &input);
Variable tileAs(const Variable &input, const Variable &reference);
Variable sumAs(const Variable &input, const Variable &reference);
Variable tile(const Variable &input, const std::vector<int> &repeats);
Variable sum(const Variable &input, const std::vector<int> &axes);
Variable mean(const Variable &input, const std::vector<int> &axes);
Variable matmul(const Variable &lhs, const Variable &rhs);
Variable matmulTN(const Variable &lhs, const Variable &rhs);
Variable matmulNT(const Variable &lhs, const Variable &rhs);
Variable abs(const Variable &input);
Variable flat(const Variable &input);
Variable moddims(const Variable &input, const dim4 &dims);
}
}
| 44.619048 | 78 | 0.64968 | syurkevi |
e4f95ba54616ff3737c0cb522dc637384bf1eff8 | 1,958 | cpp | C++ | transport/message_compressor_metrics.cpp | RedBeard0531/mongo_utils | 402c2023df7d67609ce9da8e405bf13cdd270e20 | [
"Apache-2.0"
] | 1 | 2018-03-14T21:48:43.000Z | 2018-03-14T21:48:43.000Z | transport/message_compressor_metrics.cpp | RedBeard0531/mongo_utils | 402c2023df7d67609ce9da8e405bf13cdd270e20 | [
"Apache-2.0"
] | null | null | null | transport/message_compressor_metrics.cpp | RedBeard0531/mongo_utils | 402c2023df7d67609ce9da8e405bf13cdd270e20 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (C) 2016 MongoDB Inc.
*
* 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 "mongo/platform/basic.h"
#include "mongo/bson/bsonobjbuilder.h"
#include "mongo/transport/message_compressor_registry.h"
namespace mongo {
namespace {
const auto kBytesIn = "bytesIn"_sd;
const auto kBytesOut = "bytesOut"_sd;
} // namespace
void appendMessageCompressionStats(BSONObjBuilder* b) {
auto& registry = MessageCompressorRegistry::get();
const auto& names = registry.getCompressorNames();
if (names.empty()) {
return;
}
BSONObjBuilder compressionSection(b->subobjStart("compression"));
for (auto&& name : names) {
auto&& compressor = registry.getCompressor(name);
BSONObjBuilder base(compressionSection.subobjStart(name));
BSONObjBuilder compressorSection(base.subobjStart("compressor"));
compressorSection << kBytesIn << compressor->getCompressorBytesIn() << kBytesOut
<< compressor->getCompressorBytesOut();
compressorSection.doneFast();
BSONObjBuilder decompressorSection(base.subobjStart("decompressor"));
decompressorSection << kBytesIn << compressor->getDecompressorBytesIn() << kBytesOut
<< compressor->getDecompressorBytesOut();
decompressorSection.doneFast();
base.doneFast();
}
compressionSection.doneFast();
}
} // namespace mongo
| 35.6 | 92 | 0.693054 | RedBeard0531 |
e4faa34de907099cb390ecccfe0c00b750eafb45 | 1,079 | cpp | C++ | src/gp_map/network_maps/bool_to_bool_net_map.cpp | jamesbut/NeuroEvo | 96a2e952e93c280e6018a7f55b2c66264cd47206 | [
"MIT"
] | 8 | 2019-07-23T13:05:35.000Z | 2020-07-09T03:42:27.000Z | src/gp_map/network_maps/bool_to_bool_net_map.cpp | jamesbut/NeuroEvo | 96a2e952e93c280e6018a7f55b2c66264cd47206 | [
"MIT"
] | null | null | null | src/gp_map/network_maps/bool_to_bool_net_map.cpp | jamesbut/NeuroEvo | 96a2e952e93c280e6018a7f55b2c66264cd47206 | [
"MIT"
] | null | null | null | #include <gp_map/network_maps/bool_to_bool_net_map.h>
#include <phenotype/vector_phenotype.h>
namespace NeuroEvo {
BoolToBoolNetMap::BoolToBoolNetMap(NetworkBuilder& net_builder,
VectorPhenotypeSpec* pheno_spec) :
NetworkMap<bool, bool>(net_builder, pheno_spec) {}
Phenotype<bool>* BoolToBoolNetMap::map(Genotype<bool>& genotype)
{
//Push genotype through decoder
const std::vector<double> double_genotype(genotype.genes().begin(), genotype.genes().end());
const std::vector<double> decoder_output = _decoder->activate(double_genotype);
//Cast output back to bools
std::vector<bool> traits(decoder_output.size());
for(std::size_t i = 0; i < decoder_output.size(); i++)
{
if(decoder_output[i] < 0.5)
traits[i] = false;
else
traits[i] = true;
}
//Only returns vector phenotypes for now
return new VectorPhenotype<bool>(traits);
}
BoolToBoolNetMap* BoolToBoolNetMap::clone_impl() const
{
return new BoolToBoolNetMap(*this);
}
} // namespace NeuroEvo
| 29.162162 | 96 | 0.677479 | jamesbut |
e4fd0627c44066b5635690a94d268c554f640c1a | 386 | cpp | C++ | sword_to_offer/Solution_10.cpp | fingthinking/nowcoder | 9a88a431cd682369a5b19eb4f1055480ccb3a81d | [
"Apache-2.0"
] | null | null | null | sword_to_offer/Solution_10.cpp | fingthinking/nowcoder | 9a88a431cd682369a5b19eb4f1055480ccb3a81d | [
"Apache-2.0"
] | null | null | null | sword_to_offer/Solution_10.cpp | fingthinking/nowcoder | 9a88a431cd682369a5b19eb4f1055480ccb3a81d | [
"Apache-2.0"
] | null | null | null | class Solution {
public:
int rectCover(int number) {
// 依然是斐波那契数列数列
// f(n) = f(n-1)+f(n-2); 最后一个横着放,或竖着放;横着放,则其他的就是f(n-1),竖着放,则其他的是f(n-2)
if(number <=0){
return 0;
}
int before = 0, after = 1;
while (number-- >= 0) {
before += after;
after = before-after;
}
return before;
}
}; | 24.125 | 78 | 0.455959 | fingthinking |
e4ffeb9f67795a3b8f4ee0071a9ccb92f5191c55 | 475 | cpp | C++ | ejercicio3.cpp | fienbeh1/portfolio | 2f25112c73b9304cbd6e45bb0fbfa21e97e4e26f | [
"Unlicense"
] | null | null | null | ejercicio3.cpp | fienbeh1/portfolio | 2f25112c73b9304cbd6e45bb0fbfa21e97e4e26f | [
"Unlicense"
] | null | null | null | ejercicio3.cpp | fienbeh1/portfolio | 2f25112c73b9304cbd6e45bb0fbfa21e97e4e26f | [
"Unlicense"
] | null | null | null | #include <stdio.h>
#include <conio.h>
#include "iostream"
using namespace std;
int main()
{
string nom;
string carrera;
int edad;
cout << "Bienvenido"<< endl;
cout << "Ingrese el Nombre: "; cin >> nom;
cout << "Carrera: "; cin >> carrera;
cout << "Ingrese Edad: "; cin >> edad;
cout <<"el nombre es:"<<nom<<endl;
cout <<"La carrera es :"<<carrera<<endl;
cout <<"la edad es :"<<edad<<endl;
return 0;
}
| 17.592593 | 47 | 0.534737 | fienbeh1 |
07e75c50215e633c7dc870e7ff3702f5a8a744c1 | 1,962 | hpp | C++ | lib/openZia/openZia/Packet.hpp | NicolasKeita/Apache-like | e8e866ab164547dda4353dc6fbc8219e32846082 | [
"MIT"
] | 1 | 2020-01-13T22:50:40.000Z | 2020-01-13T22:50:40.000Z | lib/openZia/openZia/Packet.hpp | NicolasKeita/My_Apache | e8e866ab164547dda4353dc6fbc8219e32846082 | [
"MIT"
] | null | null | null | lib/openZia/openZia/Packet.hpp | NicolasKeita/My_Apache | e8e866ab164547dda4353dc6fbc8219e32846082 | [
"MIT"
] | null | null | null | /*
** EPITECH PROJECT, 2020
** CPP_zia_2019
** File description:
** NetworkPacket
*/
#pragma once
#include "ByteArray.hpp"
#include "Endpoint.hpp"
namespace oZ { class Packet; }
class oZ::Packet
{
public:
/**
* @brief Construct a new Packet object
*/
Packet(void) = default;
/**
* @brief Construct a new Packet object using byteArray and an endpoint
*/
Packet(ByteArray &&byteArray, const Endpoint endpoint, const FileDescriptor fd = -1)
: _byteArray(std::move(byteArray)), _endpoint(endpoint), _fd(fd) {}
/**
* @brief Destroy the Packet object
*/
~Packet(void) = default;
/**
* @brief Get the ByteArray of the context
*/
[[nodiscard]] ByteArray &getByteArray(void) noexcept { return _byteArray; }
/**
* @brief Get the ByteArray of the context (constant)
*/
[[nodiscard]] const ByteArray getByteArray(void) const noexcept { return _byteArray; }
/**
* @brief Get the current context's endpoint
*/
[[nodiscard]] Endpoint getEndpoint(void) const noexcept { return _endpoint; }
/**
* @brief Set the Endpoint target
*/
void setEndpoint(const Endpoint endpoint) noexcept { _endpoint = endpoint; }
/**
* @brief Get the context's file descriptor
*/
[[nodiscard]] FileDescriptor getFileDescriptor(void) const noexcept { return _fd; }
/**
* @brief Set the context's file descriptor
*/
void setFileDescriptor(const FileDescriptor fd) noexcept { _fd = fd; }
/**
* @brief Check the usage of encryption port (used for HTTPS)
*/
[[nodiscard]] bool hasEncryption(void) const noexcept { return _useEncryption; }
/**
* @brief Set the encryption state
*/
void setEncryption(const bool value) noexcept { _useEncryption = value; }
private:
ByteArray _byteArray {};
Endpoint _endpoint {};
FileDescriptor _fd { -1 };
bool _useEncryption = false;
}; | 24.835443 | 90 | 0.637615 | NicolasKeita |
07f14abbc1d5cc983e4d97576aa3aec091307aa9 | 6,967 | cpp | C++ | base/src/GameSparksRT/Proto/Packet.cpp | djdron/gamesparks-cpp-base | 00b8af5dc2b58b7954cfa5d99c5ea7ded7115af8 | [
"Apache-2.0"
] | 7 | 2019-07-11T02:05:32.000Z | 2020-11-01T18:57:51.000Z | base/src/GameSparksRT/Proto/Packet.cpp | djdron/gamesparks-cpp-base | 00b8af5dc2b58b7954cfa5d99c5ea7ded7115af8 | [
"Apache-2.0"
] | 3 | 2019-02-26T15:59:03.000Z | 2019-06-04T10:46:07.000Z | base/src/GameSparksRT/Proto/Packet.cpp | djdron/gamesparks-cpp-base | 00b8af5dc2b58b7954cfa5d99c5ea7ded7115af8 | [
"Apache-2.0"
] | 6 | 2020-05-18T08:44:47.000Z | 2022-02-26T12:18:17.000Z | #include "../../System/IO/MemoryStream.hpp"
#include "./Packet.hpp"
#include "ProtocolParser.hpp"
#include "../Commands/Requests/RTRequest.hpp"
#include "ProtocolBufferException.hpp"
#include "../../System/IO/EndOfStreamException.hpp"
namespace GameSparks { namespace RT { namespace Proto {
System::Failable<void> Packet::Serialize(System::IO::Stream& stream, const Packet& instance)
{
// Key for field: 1, Varint
GS_CALL_OR_THROW(stream.WriteByte(8));
GS_CALL_OR_THROW(::GameSparks::RT::Proto::ProtocolParser::WriteZInt32(stream, instance.OpCode));
if (instance.SequenceNumber.HasValue())
{
// Key for field: 2, Varint
GS_CALL_OR_THROW(stream.WriteByte(16));
GS_CALL_OR_THROW(::GameSparks::RT::Proto::ProtocolParser::WriteUInt64(stream,(uint64_t) instance.SequenceNumber.Value()));
}
if (instance.RequestId.HasValue())
{
// Key for field: 3, Varint
GS_CALL_OR_THROW(stream.WriteByte(24));
GS_CALL_OR_THROW(::GameSparks::RT::Proto::ProtocolParser::WriteUInt64(stream,(uint64_t) instance.RequestId.Value()));
}
if (!instance.TargetPlayers.empty())
{
for (const auto& i4 : instance.TargetPlayers)
{
// Key for field: 4, Varint
GS_CALL_OR_THROW(stream.WriteByte(32));
GS_CALL_OR_THROW(::GameSparks::RT::Proto::ProtocolParser::WriteUInt64(stream,(uint64_t)i4));
}
}
if (instance.Sender.HasValue())
{
// Key for field: 5, Varint
GS_CALL_OR_THROW(stream.WriteByte(40));
GS_CALL_OR_THROW(::GameSparks::RT::Proto::ProtocolParser::WriteUInt64(stream,(uint64_t) instance.Sender.Value()));
}
if (instance.Reliable.HasValue())
{
// Key for field: 6, Varint
GS_CALL_OR_THROW(stream.WriteByte(48));
GS_CALL_OR_THROW(::GameSparks::RT::Proto::ProtocolParser::WriteBool(stream, instance.Reliable.Value()));
}
//if(true/*instance.Data*/)
{
GS_CALL_OR_THROW(stream.WriteByte(114));
GS_CALL_OR_THROW(RTData::WriteRTData(stream, instance.Data));
}
GS_CALL_OR_THROW(instance.WritePayload(stream));
return {};
}
System::Failable<int> Packet::SerializeLengthDelimited(System::IO::Stream &stream, const Packet &instance)
{
System::IO::MemoryStream ms;// = PooledObjects.MemoryStreamPool.Pop ();
GS_CALL_OR_THROW(Serialize(ms, instance));
const auto& data = ms.GetBuffer();
//int64_t pos = ms.Position();
GS_CALL_OR_THROW(GameSparks::RT::Proto::ProtocolParser::WriteUInt32(stream, (unsigned int)ms.Position()));
GS_CALL_OR_THROW(stream.Write(data, 0, (int)ms.Position()));
return ms.Position();
}
System::Failable<void> Packet::WritePayload(System::IO::Stream &stream) const
{
if (Request != nullptr) {
// Key for field: 15, LengthDelimited
System::IO::MemoryStream ms;// = PooledObjects.MemoryStreamPool.Pop();
GS_CALL_OR_THROW(Request->Serialize (ms));
auto written = ms.GetBuffer();
if (ms.Position() > 0) {
GS_CALL_OR_THROW(stream.WriteByte (122));
GS_CALL_OR_THROW(::GameSparks::RT::Proto::ProtocolParser::WriteBytes (stream, written, (int)ms.Position()));
}
} else {
if (!Payload.empty())
{
// Key for field: 15, LengthDelimited
GS_CALL_OR_THROW(stream.WriteByte(122));
GS_CALL_OR_THROW(::GameSparks::RT::Proto::ProtocolParser::WriteBytes(stream, Payload));
}
}
return {};
}
System::Failable<void> Packet::DeserializeLengthDelimited(System::IO::Stream &stream, System::IO::BinaryReader &br, Packet& instance)
{
GS_ASSIGN_OR_THROW(limit_, ::GameSparks::RT::Proto::ProtocolParser::ReadUInt32(stream));
int limit = static_cast<int>(limit_);
limit += stream.Position();
for (;;)
{
if (stream.Position() >= limit)
{
if (stream.Position() == limit)
break;
else
return GameSparks::RT::Proto::ProtocolBufferException("Read past max limit");
}
GS_ASSIGN_OR_THROW(keyByte, stream.ReadByte());
if (keyByte == -1)
GS_THROW(System::IO::EndOfStreamException("EndOfStreamException"));
// Optimized reading of known fields with field ID < 16
switch (keyByte)
{
// Field 1 Varint
case 8:
{
GS_ASSIGN_OR_THROW(tmp, ::GameSparks::RT::Proto::ProtocolParser::ReadZInt32 (stream));
instance.OpCode = tmp;
continue;
// Field 2 Varint
}
case 16:
{
GS_ASSIGN_OR_THROW(tmp, ::GameSparks::RT::Proto::ProtocolParser::ReadUInt64(stream));
instance.SequenceNumber = (int)tmp;
continue;
}
// Field 3 Varint
case 24:
{
GS_ASSIGN_OR_THROW(tmp, ::GameSparks::RT::Proto::ProtocolParser::ReadUInt64(stream));
instance.RequestId = (int)tmp;
continue;
}
// Field 5 Varint
case 40:
{
GS_ASSIGN_OR_THROW(tmp, ::GameSparks::RT::Proto::ProtocolParser::ReadUInt64(stream));
instance.Sender = (int)tmp;
continue;
}
// Field 6 Varint
case 48:
{
GS_ASSIGN_OR_THROW(tmp, ::GameSparks::RT::Proto::ProtocolParser::ReadBool(stream));
instance.Reliable = tmp;
continue;
}
// Field 7 Varint
case 114:
{
/*if (instance.Data == nullptr)
instance.Data = RTData.ReadRTData(stream, br, instance.Data);
else*/
GS_CALL_OR_THROW(RTData::ReadRTData(stream, br, instance.Data));
continue;
}
// Field 15 LengthDelimited
case 122:
{
// note: ReadPayload always return null. the payload is stored in a MemoryStream withing a CustomCommand
GS_CALL_OR_THROW(instance.ReadPayload(stream));
instance.Payload = {};
continue;
}
}
GS_ASSIGN_OR_THROW(key, ::GameSparks::RT::Proto::ProtocolParser::ReadKey((unsigned char)keyByte, stream));
// Reading field ID > 16 and unknown field ID/wire type combinations
switch (key.Field)
{
case 0:
GS_THROW(GameSparks::RT::Proto::ProtocolBufferException("Invalid field id: 0, something went wrong in the stream"));
default:
GS_CALL_OR_THROW(::GameSparks::RT::Proto::ProtocolParser::SkipKey(stream, key));
break;
}
}
assert(instance.OpCode != gsstl::numeric_limits<int>::lowest());
return {};
}
}}} /* namespace GameSparks.RT.Proto */
| 36.668421 | 133 | 0.590211 | djdron |
07f84009250626525431410b771e25f940ae3a66 | 308 | hpp | C++ | include/hg_enzine/events/Event.hpp | HadesD/HGEnzine | 722b22c1ac2a192c04cbf5729335d3ef7f50b5b0 | [
"MIT"
] | null | null | null | include/hg_enzine/events/Event.hpp | HadesD/HGEnzine | 722b22c1ac2a192c04cbf5729335d3ef7f50b5b0 | [
"MIT"
] | null | null | null | include/hg_enzine/events/Event.hpp | HadesD/HGEnzine | 722b22c1ac2a192c04cbf5729335d3ef7f50b5b0 | [
"MIT"
] | null | null | null | #ifndef __HGENZINE_EVENTS_EVENT_HPP__
#define __HGENZINE_EVENTS_EVENT_HPP__
#include "hg_enzine/core/BeginPreprocessors.hpp"
#include <functional>
namespace HGEnzine::events
{
class HGENZINE_API Event
{
public:
virtual ~Event();
public:
virtual void update() = 0;
};
}
#endif
| 14 | 48 | 0.714286 | HadesD |
07fcd84a1594d8c35c570e30a2e464460cfa6a1c | 5,392 | cpp | C++ | vkconfig_core/layer_setting_value.cpp | johnzupin/VulkanTools | 4a4d824b43984d29902f7c8246aab99f0909151d | [
"Apache-2.0"
] | null | null | null | vkconfig_core/layer_setting_value.cpp | johnzupin/VulkanTools | 4a4d824b43984d29902f7c8246aab99f0909151d | [
"Apache-2.0"
] | null | null | null | vkconfig_core/layer_setting_value.cpp | johnzupin/VulkanTools | 4a4d824b43984d29902f7c8246aab99f0909151d | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2020 Valve Corporation
* Copyright (c) 2020 LunarG, Inc.
*
* 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.
*
* Authors:
* - Christophe Riccio <christophe@lunarg.com>
*/
#include "layer_setting_value.h"
#include "util.h"
#include "path.h"
#include <QJsonArray>
#include <QString>
#include <cassert>
SettingValue::SettingValue(const char* key, const QVariant& value) : setting_key(key) { setting_value.push_back(value); }
SettingValue::SettingValue(const char* key, const std::vector<QVariant>& value) : setting_key(key), setting_value(value) {}
const char* SettingValue::Key() const { return setting_key.c_str(); }
bool SettingValue::Empty() const { return this->setting_value.empty(); }
std::size_t SettingValue::Size() const { return this->setting_value.size(); }
bool SettingValue::Load(const char* key, const SettingType type, const QJsonObject& json_object) {
assert(key != nullptr);
assert(!json_object.isEmpty());
setting_key = key;
const QJsonValue& json_value = json_object.value(key);
assert(json_value != QJsonValue::Undefined);
switch (type) {
case SETTING_VUID_FILTER:
case SETTING_INCLUSIVE_LIST: {
assert(json_value.isArray());
const QJsonArray& json_array = json_value.toArray();
for (int i = 0, n = json_array.size(); i < n; ++i) {
setting_value.push_back(QVariant(json_array[i].toString()));
}
break;
}
case SETTING_EXCLUSIVE_LIST:
case SETTING_STRING:
case SETTING_LOAD_FILE:
case SETTING_SAVE_FOLDER: {
assert(json_value.isString());
setting_value.push_back(QVariant(json_value.toString()));
break;
}
case SETTING_SAVE_FILE: {
assert(json_value.isString());
const QString& value = json_value.toString();
const QString path(ReplacePathBuiltInVariables(ValidatePath(value.toStdString())).c_str());
setting_value.push_back(path);
break;
}
case SETTING_BOOL_NUMERIC:
case SETTING_INT: {
assert(!json_value.isArray());
setting_value.push_back(QVariant(json_value.toInt()));
break;
}
case SETTING_RANGE_INT: {
assert(json_value.isArray());
const QJsonArray& json_array = json_value.toArray();
assert(json_array.size() == 2);
for (int i = 0, n = 2; i < n; ++i) {
setting_value.push_back(QVariant(json_array[i].toInt()));
}
break;
}
case SETTING_BOOL: {
assert(json_value.isBool());
setting_value.push_back(QVariant(json_value.toBool()));
break;
}
default: {
assert(0);
return false;
}
}
return true;
}
bool SettingValue::Save(const char* key, const SettingType type, QJsonObject& json_object) const {
assert(key != nullptr);
switch (type) {
case SETTING_VUID_FILTER:
case SETTING_INCLUSIVE_LIST: {
QJsonArray json_array;
for (std::size_t i = 0, n = this->setting_value.size(); i < n; ++i) {
json_array.append(this->setting_value[i].toString());
}
json_object.insert(key, json_array);
break;
}
case SETTING_EXCLUSIVE_LIST:
case SETTING_STRING:
case SETTING_LOAD_FILE:
case SETTING_SAVE_FILE:
case SETTING_SAVE_FOLDER: {
assert(this->setting_value.size() == 1);
json_object.insert(key, this->setting_value[0].toString());
break;
}
case SETTING_BOOL_NUMERIC:
case SETTING_INT: {
assert(this->setting_value.size() == 1);
json_object.insert(key, this->setting_value[0].toInt());
break;
}
case SETTING_RANGE_INT: {
assert(this->setting_value.size() == 2);
QJsonArray json_array;
for (std::size_t i = 0, n = this->setting_value.size(); i < n; ++i) {
json_array.append(this->setting_value[i].toInt());
}
json_object.insert(key, json_array);
break;
}
case SETTING_BOOL: {
assert(this->setting_value.size() == 1);
json_object.insert(key, this->setting_value[0].toBool());
break;
}
default: {
assert(0);
break;
}
}
return true;
}
bool operator==(const SettingValue& l, const SettingValue& r) {
if (l.Size() != r.Size()) return false;
for (std::size_t i = 0, n = l.Size(); i < n; ++i) {
if (l[i] != r[i]) return false;
}
return true;
}
bool operator!=(const SettingValue& l, const SettingValue& r) { return !(l == r); }
| 32.678788 | 123 | 0.594955 | johnzupin |
07fdd91bae99dfdb428f4842587a3f1c570e0b4c | 3,027 | cpp | C++ | camera.cpp | dodopod/raycast | 31d1d508c7a6fd86f184fc43079bfaaf9d5a28c1 | [
"MIT"
] | null | null | null | camera.cpp | dodopod/raycast | 31d1d508c7a6fd86f184fc43079bfaaf9d5a28c1 | [
"MIT"
] | null | null | null | camera.cpp | dodopod/raycast | 31d1d508c7a6fd86f184fc43079bfaaf9d5a28c1 | [
"MIT"
] | null | null | null | #include "camera.hpp"
Camera::Camera(Map* map, const Vec2& position, const Vec2& direction,
double fov, double nearDistance, double drawDistance) :
map(map),
position(position),
nearDistance(nearDistance),
drawDistance(drawDistance)
{
zUnit = direction;
zUnit.normalize();
xUnit = direction;
xUnit.rotate(-M_PI/2);
xUnit.normalize();
viewRadius = nearDistance * sin(fov/2);
}
void Camera::moveX(double dx)
{
position += dx * xUnit;
}
void Camera::moveZ(double dz)
{
position += dz * zUnit;
}
void Camera::rotate(double angle)
{
xUnit.rotate(angle);
zUnit.rotate(angle);
}
void Camera::render(SDL_Surface* surface) const
{
// fill in the background
SDL_FillRect(surface, NULL, SDL_MapRGB(surface->format,
SKY_COLOR.r,
SKY_COLOR.g,
SKY_COLOR.b));
// walls reach equally above and below horizon
const int HORIZON = surface->h / 2; // horizon in center of screen
const int WALL_HEIGHT = surface->h; // walls touch top and bottom of screen at z=1
// For each column of the image
for (int x = 0; x < surface->w; x++)
{
// Cast a ray
Ray ray = Ray(position, findColumn(x, surface->w) - position);
Vec2 intersection = map->cast(ray, drawDistance);
// If the ray intersects a wall, draw it
if (!map->passable(intersection))
{
// find visible height of wall
double z = dot(intersection - position, zUnit);
SDL_Rect column =
{
x, // x
HORIZON - (WALL_HEIGHT/2) / z, // y
1, // width
WALL_HEIGHT / z // height
};
// add fog so we can't see walls clip out of existence
int shade = 255 * z / drawDistance;
SDL_Color shaded = WALL_COLOR;
shaded.r = shaded.r > shade ? shaded.r - shade : 0;
shaded.g = shaded.g > shade ? shaded.g - shade : 0;
shaded.b = shaded.b > shade ? shaded.b - shade : 0;
// draw wall
column.x = x;
SDL_FillRect(surface, &column, SDL_MapRGB(surface->format,
shaded.r,
shaded.g,
shaded.b));
}
}
}
// TODO function to convert camera to world coords
Vec2 Camera::findColumn(int x, int w) const
{
// Origin to center of image
Vec2 center = position + nearDistance * zUnit;
// Center point to pixel
Vec2 cameraX = ((2 * (double)x / w) - 1) * viewRadius * xUnit;
return center + cameraX;
}
| 29.970297 | 86 | 0.487281 | dodopod |
5804098fd6441cdb267cc812bec43ca5690816b6 | 714 | cpp | C++ | 02/roh/1543.cpp | Dcom-KHU/2021-Winter-Algorithm-Study | ea32826abe7d8245ee9d3dc8d0161f7ba018a02f | [
"MIT"
] | 2 | 2021-01-09T10:05:21.000Z | 2021-01-10T06:14:03.000Z | 02/roh/1543.cpp | Dcom-KHU/2021-Winter-Algorithm-Study | ea32826abe7d8245ee9d3dc8d0161f7ba018a02f | [
"MIT"
] | null | null | null | 02/roh/1543.cpp | Dcom-KHU/2021-Winter-Algorithm-Study | ea32826abe7d8245ee9d3dc8d0161f7ba018a02f | [
"MIT"
] | 1 | 2021-02-03T13:09:09.000Z | 2021-02-03T13:09:09.000Z | #include <iostream>
#include <string>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
string a,b;
getline(cin,a);
getline(cin,b);
int cnt = 0;
//아래 if문안넣어서 제출 10번함 띠용..
if(a.size() >= b.size())
for(int shift = 0; shift <= a.size() - b.size(); shift++){
for(int walker = 0 ; walker <= b.size(); walker++){
//마지막 인덱스 그 뒤에 도달시 성공
if(walker == b.size()){
cnt++;
shift += b.size()-1;
break;
}
//index out of range 방지.. 필요한가?
if(shift+walker >= a.size())
break;
//둘이 다를경우 break
if(b[walker] != a[shift+walker]){
break;
}
}
}
cout<<cnt;
return 0;
} | 19.297297 | 60 | 0.511204 | Dcom-KHU |
580dcb92371e2fd8cc738ad861a46b5c872287d7 | 18,749 | cpp | C++ | mobilican_demos/pick_and_place/src/point_head_action.cpp | robotican/mobilican_robots | faf97fa1dbb05db8068eaede65b572e1e0ba2273 | [
"BSD-2-Clause"
] | 1 | 2020-05-01T19:39:51.000Z | 2020-05-01T19:39:51.000Z | mobilican_demos/pick_and_place/src/point_head_action.cpp | robotican/mobilican_robots | faf97fa1dbb05db8068eaede65b572e1e0ba2273 | [
"BSD-2-Clause"
] | 1 | 2019-01-21T11:00:54.000Z | 2019-01-28T08:21:30.000Z | mobilican_demos/pick_and_place/src/point_head_action.cpp | robotican/mobilican_robots | faf97fa1dbb05db8068eaede65b572e1e0ba2273 | [
"BSD-2-Clause"
] | 2 | 2019-01-22T12:13:19.000Z | 2019-01-30T10:07:21.000Z | /*******************************************************************************
* Copyright (c) 2018, RoboTICan, LTD.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of RoboTICan 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.
*******************************************************************************/
/* Author: Elchay Rauper*/
#include <ros/ros.h>
#include <vector>
#include <boost/scoped_ptr.hpp>
#include <boost/thread/condition.hpp>
#include <actionlib/server/action_server.h>
#include <geometry_msgs/PoseStamped.h>
#include <geometry_msgs/PointStamped.h>
#include <geometry_msgs/Twist.h>
#include <kdl/chainfksolver.hpp>
#include <kdl/chain.hpp>
#include <kdl/chainjnttojacsolver.hpp>
#include <kdl/frames.hpp>
#include "kdl/chainfksolverpos_recursive.hpp"
#include "kdl_parser/kdl_parser.hpp"
#include "tf_conversions/tf_kdl.h"
#include <message_filters/subscriber.h>
#include <tf/message_filter.h>
#include <tf/transform_datatypes.h>
#include <tf/transform_listener.h>
#include <sensor_msgs/JointState.h>
#include <std_msgs/Float32MultiArray.h>
#include <std_msgs/Int32.h>
#include <urdf/model.h>
#include <trajectory_msgs/JointTrajectory.h>
#include <mobilican_msgs/PointHeadAction.h>
#include <mobilican_msgs/QueryTrajectoryState.h>
#include <mobilican_msgs/JointTrajectoryControllerState.h>
void printVector3(const char * label, tf::Vector3 v)
{
printf("%s % 7.3f % 7.3f % 7.3f\n", label, v.x(), v.y(), v.z() );
}
class ControlHead
{
private:
typedef actionlib::ActionServer<mobilican_msgs::PointHeadAction> PHAS;
typedef PHAS::GoalHandle GoalHandle;
std::string node_name_;
std::string action_name_;
std::string root_;
std::string tip_;
std::string pan_link_;
std::string default_pointing_frame_;
std::string pointing_frame_;
tf::Vector3 pointing_axis_;
std::vector< std::string> joint_names_;
ros::NodeHandle nh_, pnh_;
ros::Publisher pub_controller_command_;
ros::Subscriber sub_controller_state_;
ros::Subscriber command_sub_;
ros::ServiceClient cli_query_traj_;
ros::Timer watchdog_timer_;
PHAS action_server_;
bool has_active_goal_;
GoalHandle active_goal_;
tf::Stamped<tf::Point> target_in_pan_;
std::string pan_parent_;
double success_angle_threshold_;
geometry_msgs::PointStamped target_;
KDL::Tree tree_;
KDL::Chain chain_;
tf::Point target_in_root_;
boost::scoped_ptr<KDL::ChainFkSolverPos> pose_solver_;
boost::scoped_ptr<KDL::ChainJntToJacSolver> jac_solver_;
tf::TransformListener tfl_;
urdf::Model urdf_model_;
public:
ControlHead(const ros::NodeHandle &node) :
node_name_(ros::this_node::getName())
, action_name_("point_head_action")
, nh_(node)
, pnh_("~")
, action_server_(nh_, action_name_.c_str(),
boost::bind(&ControlHead::goalCB, this, _1),
boost::bind(&ControlHead::cancelCB, this, _1), false)
, has_active_goal_(false)
{
pnh_.param("pan_link", pan_link_, std::string("head_pan_link"));
pnh_.param("default_pointing_frame", default_pointing_frame_, std::string("head_tilt_link"));
pnh_.param("success_angle_threshold", success_angle_threshold_, 0.1);
if(pan_link_[0] == '/') pan_link_.erase(0, 1);
if(default_pointing_frame_[0] == '/') default_pointing_frame_.erase(0, 1);
// Connects to the controller
pub_controller_command_ =
nh_.advertise<trajectory_msgs::JointTrajectory>("command", 2);
sub_controller_state_ =
nh_.subscribe("state", 1, &ControlHead::controllerStateCB, this);
cli_query_traj_ =
nh_.serviceClient<mobilican_msgs::QueryTrajectoryState>("/pan_tilt_trajectory_controller/query_state");
// Should only ever happen on first call... move to constructor?
if(tree_.getNrOfJoints() == 0)
{
std::string robot_desc_string;
nh_.param("/robot_description", robot_desc_string, std::string());
ROS_DEBUG("Reading tree from robot_description...");
if (!kdl_parser::treeFromString(robot_desc_string, tree_)){
ROS_ERROR("Failed to construct kdl tree");
exit(-1);
}
if (!urdf_model_.initString(robot_desc_string)){
ROS_ERROR("Failed to parse urdf string for urdf::Model.");
exit(-2);
}
}
ROS_DEBUG("Tree has %d joints and %d segments.", tree_.getNrOfJoints(), tree_.getNrOfSegments());
action_server_.start();
watchdog_timer_ = nh_.createTimer(ros::Duration(1.0), &ControlHead::watchdog, this);
}
void goalCB(GoalHandle gh)
{
// Before we do anything, we need to know that name of the pan_link's parent, which we will treat as the root.
if (root_.empty())
{
for (int i = 0; i < 10; ++i)
{
try {
tfl_.getParent(pan_link_, ros::Time(), root_);
break;
}
catch (const tf::TransformException &ex) {}
ros::Duration(0.5).sleep();
}
if (root_.empty())
{
ROS_ERROR("Could not get parent of %s in the TF tree", pan_link_.c_str());
gh.setRejected();
return;
}
}
if(root_[0] == '/') root_.erase(0, 1);
ROS_DEBUG("Got point head goal!");
// Process pointing frame and axis
const geometry_msgs::PointStamped &target = gh.getGoal()->target;
pointing_frame_ = gh.getGoal()->pointing_frame;
if(pointing_frame_.length() == 0)
{
ROS_WARN("Pointing frame not specified, using %s [1, 0, 0] by default.", default_pointing_frame_.c_str());
pointing_frame_ = default_pointing_frame_;
pointing_axis_ = tf::Vector3(1.0, 0.0, 0.0);
}
else
{
if(pointing_frame_[0] == '/') pointing_frame_.erase(0, 1);
bool ret1 = false;
try
{
std::string error_msg;
ret1 = tfl_.waitForTransform(pan_link_, pointing_frame_, target.header.stamp,
ros::Duration(5.0), ros::Duration(0.01), &error_msg);
tf::vector3MsgToTF(gh.getGoal()->pointing_axis, pointing_axis_);
if(pointing_axis_.length() < 0.1)
{
size_t found = pointing_frame_.find("optical_frame");
if (found != std::string::npos)
{
ROS_WARN("Pointing axis appears to be zero-length. Using [0, 0, 1] as default for an optical frame.");
pointing_axis_ = tf::Vector3(0, 0, 1);
}
else
{
ROS_WARN("Pointing axis appears to be zero-length. Using [1, 0, 0] as default for a non-optical frame.");
pointing_axis_ = tf::Vector3(1, 0, 0);
}
}
else
{
pointing_axis_.normalize();
}
}
catch(const tf::TransformException &ex)
{
ROS_ERROR("Transform failure (%d): %s", ret1, ex.what());
gh.setRejected();
return;
}
}
//Put the target point in the root frame (usually torso_lift_link).
bool ret1 = false;
try
{
std::string error_msg;
ret1 = tfl_.waitForTransform(root_.c_str(), target.header.frame_id, target.header.stamp,
ros::Duration(5.0), ros::Duration(0.01), &error_msg);
geometry_msgs::PointStamped target_in_root_msg;
tfl_.transformPoint(root_.c_str(), target, target_in_root_msg );
tf::pointMsgToTF(target_in_root_msg.point, target_in_root_);
}
catch(const tf::TransformException &ex)
{
ROS_ERROR("Transform failure (%d): %s", ret1, ex.what());
gh.setRejected();
return;
}
if( tip_.compare(pointing_frame_) != 0 )
{
bool success = tree_.getChain(root_.c_str(), pointing_frame_.c_str(), chain_);
if( !success )
{
ROS_ERROR("Couldn't create chain from %s to %s.", root_.c_str(), pointing_frame_.c_str());
gh.setRejected();
return;
}
tip_ = pointing_frame_;
pose_solver_.reset(new KDL::ChainFkSolverPos_recursive(chain_));
jac_solver_.reset(new KDL::ChainJntToJacSolver(chain_));
joint_names_.resize(chain_.getNrOfJoints());
}
unsigned int joints = chain_.getNrOfJoints();
// int segments = chain_.getNrOfSegments();
// ROS_INFO("Parsed urdf from %s to %s and found %d joints and %d segments.", root_.c_str(), pointing_frame_.c_str(), joints, segments);
// for(int i = 0; i < segments; i++)
// {
// KDL::Segment segment = chain_.getSegment(i);
// ROS_INFO("Segment %d, %s: joint %s type %s",
// i, segment.getName().c_str(), segment.getJoint().getName().c_str(), segment.getJoint().getTypeName().c_str() );
// }
KDL::JntArray jnt_pos(joints), jnt_eff(joints);
KDL::Jacobian jacobian(joints);
mobilican_msgs::QueryTrajectoryState traj_state;
traj_state.request.time = ros::Time::now() + ros::Duration(0.01);
if (!cli_query_traj_.call(traj_state))
{
ROS_ERROR("Service call to query controller trajectory failed.");
gh.setRejected();
return;
}
if(traj_state.response.name.size() != joints)
{
ROS_ERROR("Number of joints mismatch: urdf chain vs. trajectory controller state.");
gh.setRejected();
return;
}
std::vector<urdf::JointLimits> limits_(joints);
// Get initial joint positions and joint limits.
for(unsigned int i = 0; i < joints; i++)
{
joint_names_[i] = traj_state.response.name[i];
limits_[i] = *(urdf_model_.joints_[joint_names_[i].c_str()]->limits);
ROS_DEBUG("Joint %d %s: %f, limits: %f %f", i, traj_state.response.name[i].c_str(), traj_state.response.position[i], limits_[i].lower, limits_[i].upper);
//jnt_pos(i) = traj_state.response.position[i];
jnt_pos(i) = 0;
}
int count = 0;
int limit_flips = 0;
float correction_angle = 2*M_PI;
float correction_delta = 2*M_PI;
while( ros::ok() && fabs(correction_delta) > 0.001)
{
//get the pose and jacobian for the current joint positions
KDL::Frame pose;
pose_solver_->JntToCart(jnt_pos, pose);
jac_solver_->JntToJac(jnt_pos, jacobian);
tf::Transform frame_in_root;
tf::poseKDLToTF(pose, frame_in_root);
tf::Vector3 axis_in_frame = pointing_axis_.normalized();
tf::Vector3 target_from_frame = (target_in_root_ - frame_in_root.getOrigin()).normalized();
tf::Vector3 current_in_frame = frame_in_root.getBasis().inverse()*target_from_frame;
float prev_correction = correction_angle;
correction_angle = current_in_frame.angle(axis_in_frame);
correction_delta = correction_angle - prev_correction;
ROS_DEBUG("At step %d, joint poses are %.4f and %.4f, angle error is %f", count, jnt_pos(0), jnt_pos(1), correction_angle);
if(correction_angle < 0.5*success_angle_threshold_) break;
tf::Vector3 correction_axis = frame_in_root.getBasis()*(axis_in_frame.cross(current_in_frame).normalized());
//printVector3("correction_axis in root:", correction_axis);
tf::Transform correction_tf(tf::Quaternion(correction_axis, 0.5*correction_angle), tf::Vector3(0,0,0));
KDL::Frame correction_kdl;
tf::transformTFToKDL(correction_tf, correction_kdl);
// We apply a "wrench" proportional to the desired correction
KDL::Frame identity_kdl;
KDL::Twist twist = diff(correction_kdl, identity_kdl);
KDL::Wrench wrench_desi;
for (unsigned int i=0; i<6; i++)
wrench_desi(i) = -1.0*twist(i);
// Converts the "wrench" into "joint corrections" with a jacbobian-transpose
for (unsigned int i = 0; i < joints; i++)
{
jnt_eff(i) = 0;
for (unsigned int j=0; j<6; j++)
jnt_eff(i) += (jacobian(j,i) * wrench_desi(j));
jnt_pos(i) += jnt_eff(i);
}
// account for pan_link joint limit in back.
// if(jnt_pos(0) < limits_[0].lower && limit_flips++ == 0){ jnt_pos(0) += 1.5*M_PI; }
// if(jnt_pos(0) > limits_[0].upper && limit_flips++ == 0){ jnt_pos(0) -= 1.5*M_PI; }
for (unsigned int i = 0; i < joints; i++)
{
jnt_pos(i) = std::max(limits_[i].lower, jnt_pos(i));
jnt_pos(i) = std::min(limits_[i].upper, jnt_pos(i));
}
// jnt_pos(1) = std::max(limits_[1].lower, jnt_pos(1));
// jnt_pos(1) = std::min(limits_[1].upper, jnt_pos(1));
count++;
if(limit_flips > 1){
ROS_ERROR("Goal is out of joint limits, trying to point there anyway... \n");
break;
}
}
ROS_DEBUG("Iterative solver took %d steps", count);
std::vector<double> q_goal(joints);
for(unsigned int i = 0; i < joints; i++)
{
jnt_pos(i) = std::max(limits_[i].lower, jnt_pos(i));
jnt_pos(i) = std::min(limits_[i].upper, jnt_pos(i));
q_goal[i] = jnt_pos(i);
ROS_DEBUG("Joint %d %s: %f", i, joint_names_[i].c_str(), jnt_pos(i));
}
if (has_active_goal_)
{
active_goal_.setCanceled();
has_active_goal_ = false;
}
gh.setAccepted();
active_goal_ = gh;
has_active_goal_ = true;
// Computes the duration of the movement.
ros::Duration min_duration(0.1);
if (gh.getGoal()->min_duration > min_duration)
min_duration = gh.getGoal()->min_duration;
// Determines if we need to increase the duration of the movement in order to enforce a maximum velocity.
if (gh.getGoal()->max_velocity > 0)
{
// Very approximate velocity limiting.
double dist = sqrt(pow(q_goal[0] - traj_state.response.position[0], 2) +
pow(q_goal[1] - traj_state.response.position[1], 2));
ros::Duration limit_from_velocity(dist / gh.getGoal()->max_velocity);
if (limit_from_velocity > min_duration)
min_duration = limit_from_velocity;
}
// Computes the command to send to the trajectory controller.
trajectory_msgs::JointTrajectory traj;
traj.header.stamp = traj_state.request.time;
traj.joint_names.push_back(traj_state.response.name[0]);
traj.joint_names.push_back(traj_state.response.name[1]);
traj.points.resize(1);
// traj.points[0].positions = traj_state.response.position;
//traj.points[0].velocities = traj_state.response.velocity;
//traj.points[0].time_from_start = ros::Duration(0.0);
traj.points[0].positions = q_goal;
traj.points[0].velocities.push_back(0);
traj.points[0].velocities.push_back(0);
traj.points[0].time_from_start = ros::Duration(min_duration);
pub_controller_command_.publish(traj);
}
void watchdog(const ros::TimerEvent &e)
{
ros::Time now = ros::Time::now();
// Aborts the active goal if the controller does not appear to be active.
if (has_active_goal_)
{
bool should_abort = false;
if (!last_controller_state_)
{
should_abort = true;
ROS_WARN("Aborting goal because we have never heard a controller state message.");
}
else if ((now - last_controller_state_->header.stamp) > ros::Duration(5.0))
{
should_abort = true;
ROS_WARN("Aborting goal because we haven't heard from the controller in %.3lf seconds",
(now - last_controller_state_->header.stamp).toSec());
}
if (should_abort)
{
// Stops the controller.
trajectory_msgs::JointTrajectory empty;
empty.joint_names = joint_names_;
pub_controller_command_.publish(empty);
// Marks the current goal as aborted.
active_goal_.setAborted();
has_active_goal_ = false;
}
}
}
void cancelCB(GoalHandle gh)
{
if (active_goal_ == gh)
{
// Stops the controller.
trajectory_msgs::JointTrajectory empty;
empty.joint_names = joint_names_;
pub_controller_command_.publish(empty);
// Marks the current goal as canceled.
active_goal_.setCanceled();
has_active_goal_ = false;
}
}
mobilican_msgs::JointTrajectoryControllerStateConstPtr last_controller_state_;
void controllerStateCB(const mobilican_msgs::JointTrajectoryControllerStateConstPtr &msg)
{
last_controller_state_ = msg;
ros::Time now = ros::Time::now();
if (!has_active_goal_)
return;
//! \todo Support frames that are not the pan link itself
try
{
KDL::JntArray jnt_pos(msg->joint_names.size());
for(unsigned int i = 0; i < msg->joint_names.size(); i++)
jnt_pos(i) = msg->actual.positions[i];
KDL::Frame pose;
pose_solver_->JntToCart(jnt_pos, pose);
tf::Transform frame_in_root;
tf::poseKDLToTF(pose, frame_in_root);
tf::Vector3 axis_in_frame = pointing_axis_.normalized();
tf::Vector3 target_from_frame = target_in_root_ - frame_in_root.getOrigin();
target_from_frame.normalize();
tf::Vector3 current_in_frame = frame_in_root.getBasis().inverse()*target_from_frame;
mobilican_msgs::PointHeadFeedback feedback;
feedback.pointing_angle_error = current_in_frame.angle(axis_in_frame);
active_goal_.publishFeedback(feedback);
if (feedback.pointing_angle_error < success_angle_threshold_)
{
active_goal_.setSucceeded();
has_active_goal_ = false;
}
}
catch(const tf::TransformException &ex)
{
ROS_ERROR("Could not transform: %s", ex.what());
}
}
};
int main(int argc, char** argv)
{
ros::init(argc, argv, "point_head_action");
ros::NodeHandle node;
ControlHead ch(node);
ros::spin();
return 0;
}
| 34.592251 | 159 | 0.655288 | robotican |
580fcfad0f567543f742f09b4cb8e48b0f1bb72b | 300 | hpp | C++ | src/up/task_pool.hpp | snailbaron/up | 586e9514d914010dcd62a2144ef82a9018db5abf | [
"MIT"
] | null | null | null | src/up/task_pool.hpp | snailbaron/up | 586e9514d914010dcd62a2144ef82a9018db5abf | [
"MIT"
] | null | null | null | src/up/task_pool.hpp | snailbaron/up | 586e9514d914010dcd62a2144ef82a9018db5abf | [
"MIT"
] | null | null | null | #pragma once
#include <functional>
#include <vector>
enum class TaskState {
Running,
Success,
Fail,
};
class TaskPool {
public:
void add(std::function<TaskState(double)>&& task);
void update(double delta);
private:
std::vector<std::function<TaskState(double)>> _tasks;
};
| 15 | 57 | 0.67 | snailbaron |
581286790fb436c431b95e5dd6123efd0fb7205f | 3,679 | cpp | C++ | Sandbox/Scenes/SceneModelViewer.cpp | adriengivry/Lumos | beab295c25639e2320be9f1b6f0c0e49a2412d5a | [
"MIT"
] | null | null | null | Sandbox/Scenes/SceneModelViewer.cpp | adriengivry/Lumos | beab295c25639e2320be9f1b6f0c0e49a2412d5a | [
"MIT"
] | null | null | null | Sandbox/Scenes/SceneModelViewer.cpp | adriengivry/Lumos | beab295c25639e2320be9f1b6f0c0e49a2412d5a | [
"MIT"
] | 1 | 2020-04-17T13:40:49.000Z | 2020-04-17T13:40:49.000Z | #include "SceneModelViewer.h"
using namespace Lumos;
using namespace Maths;
SceneModelViewer::SceneModelViewer(const std::string& SceneName)
: Scene(SceneName)
{
}
SceneModelViewer::~SceneModelViewer()
{
}
void SceneModelViewer::OnInit()
{
Scene::OnInit();
LoadModels();
m_pCamera = new EditorCamera(-20.0f, 330.0f, Maths::Vector3(-2.5f, 1.3f, 3.8f), 45.0f, 0.1f, 1000.0f, (float) m_ScreenWidth / (float) m_ScreenHeight);
auto audioSystem = Application::Instance()->GetSystem<AudioManager>();
if (audioSystem)
Application::Instance()->GetSystem<AudioManager>()->SetListener(m_pCamera);
String environmentFiles[11] =
{
"/Textures/cubemap/CubeMap0.tga",
"/Textures/cubemap/CubeMap1.tga",
"/Textures/cubemap/CubeMap2.tga",
"/Textures/cubemap/CubeMap3.tga",
"/Textures/cubemap/CubeMap4.tga",
"/Textures/cubemap/CubeMap5.tga",
"/Textures/cubemap/CubeMap6.tga",
"/Textures/cubemap/CubeMap7.tga",
"/Textures/cubemap/CubeMap8.tga",
"/Textures/cubemap/CubeMap9.tga",
"/Textures/cubemap/CubeMap10.tga"
};
m_EnvironmentMap = Graphics::TextureCube::CreateFromVCross(environmentFiles, 11);
auto lightEntity = m_Registry.create();
m_Registry.assign<Graphics::Light>(lightEntity, Maths::Vector3(26.0f, 22.0f, 48.5f), Maths::Vector4(1.0f), 1.3f);
m_Registry.assign<Maths::Transform>(lightEntity,Matrix4::Translation(Maths::Vector3(26.0f, 22.0f, 48.5f)) * Maths::Quaternion::LookAt(Maths::Vector3(26.0f, 22.0f, 48.5f), Maths::Vector3::ZERO).RotationMatrix4());
m_Registry.assign<NameComponent>(lightEntity, "Directional Light");
auto cameraEntity = m_Registry.create();
m_Registry.assign<CameraComponent>(cameraEntity, m_pCamera);
m_Registry.assign<NameComponent>(cameraEntity, "Camera");
auto deferredRenderer = new Graphics::DeferredRenderer(m_ScreenWidth, m_ScreenHeight);
auto skyboxRenderer = new Graphics::SkyboxRenderer(m_ScreenWidth, m_ScreenHeight, m_EnvironmentMap);
deferredRenderer->SetRenderToGBufferTexture(true);
skyboxRenderer->SetRenderToGBufferTexture(true);
auto deferredLayer = new Layer3D(deferredRenderer, "Deferred");
auto skyBoxLayer = new Layer3D(skyboxRenderer, "Skybox");
Application::Instance()->PushLayer(deferredLayer);
Application::Instance()->PushLayer(skyBoxLayer);
Application::Instance()->GetRenderManager()->SetSkyBoxTexture(m_EnvironmentMap);
#ifndef LUMOS_PLATFORM_IOS
auto shadowRenderer = new Graphics::ShadowRenderer();
shadowRenderer->SetLightEntity(lightEntity);
auto shadowLayer = new Layer3D(shadowRenderer);
Application::Instance()->GetRenderManager()->SetShadowRenderer(shadowRenderer);
Application::Instance()->PushLayer(shadowLayer);
#endif
m_SceneBoundingRadius = 20.0f;
}
void SceneModelViewer::OnUpdate(TimeStep* timeStep)
{
Scene::OnUpdate(timeStep);
}
void SceneModelViewer::OnCleanupScene()
{
if (m_CurrentScene)
{
SAFE_DELETE(m_pCamera)
SAFE_DELETE(m_EnvironmentMap);
}
Scene::OnCleanupScene();
}
void SceneModelViewer::LoadModels()
{
std::vector<String> ExampleModelPaths
{
"/Meshes/DamagedHelmet/glTF/DamagedHelmet.gltf",
"/Meshes/Scene/scene.gltf",
"/Meshes/Spyro/ArtisansHub.obj",
"/Meshes/Cube/Cube.gltf",
"/Meshes/KhronosExamples/MetalRoughSpheres/glTF/MetalRoughSpheres.gltf",
"/Meshes/KhronosExamples/EnvironmentTest/glTF/EnvironmentTest.gltf",
"/Meshes/Sponza/sponza.gltf",
"/Meshes/capsule.glb"
};
auto TestObject = ModelLoader::LoadModel(ExampleModelPaths[0], m_Registry);
m_Registry.get_or_assign<Maths::Transform>(TestObject, Maths::Matrix4::Scale(Maths::Vector3(1.0f, 1.0f, 1.0f)));
}
void SceneModelViewer::OnImGui()
{
}
| 31.991304 | 216 | 0.742593 | adriengivry |
58140229249902d21d2a42726d33256d52e16e20 | 6,235 | cc | C++ | dp/CoinsWaySameValueSamePapper.cc | raining888/leetcode | e9e8ac51d49e0c5f1450a6b76ba9777b89f7e25b | [
"MIT"
] | null | null | null | dp/CoinsWaySameValueSamePapper.cc | raining888/leetcode | e9e8ac51d49e0c5f1450a6b76ba9777b89f7e25b | [
"MIT"
] | null | null | null | dp/CoinsWaySameValueSamePapper.cc | raining888/leetcode | e9e8ac51d49e0c5f1450a6b76ba9777b89f7e25b | [
"MIT"
] | null | null | null | #include <iostream>
#include <unordered_map>
#include <stdbool.h>
#include <random>
#include <memory.h>
using namespace std;
class CoinsWaySameValueSamePapper
{
public:
class Info
{
public:
int* coins; // coins[i]不同的面值
int* zhangs; // zhangs[i]面值的张数
int length; // 去重后的数组长度
Info(int* c, int* z, int len)
{
coins = c;
zhangs = z;
length = len;
}
};
// 去重
static Info getInfo(int* arr, int len)
{
unordered_map<int, int> counts;
for (int i = 0; i < len; i++)
{
if (counts.find(arr[i]) == counts.end())
{
counts[arr[i]] = 1;
}
else
{
counts[arr[i]]++;
}
}
int N = counts.size();
int* coins = (int*)malloc(sizeof(int) * N);
memset(coins, 0, sizeof(int) * N);
int* zhangs = (int*)malloc(sizeof(int) * N);
memset(zhangs, 0, sizeof(int) * N);
int index = 0;
for (auto cur : counts)
{
coins[index] = cur.first;
zhangs[index++] = cur.second;
}
return Info(coins, zhangs, N);
}
static int coinsWay(int* arr, int len, int aim)
{
if (arr == nullptr || len == 0 || aim < 0)
{
return 0;
}
Info info = getInfo(arr, len);
return process(info.coins, info.zhangs, info.length, 0, aim);
}
// coins 面值数组,正数且去重
// zhangs 每种面值对应的张数
static int process(int* coins, int* zhangs, int len, int index, int rest)
{
if (index == len)
{
return rest == 0 ? 1 : 0;
}
int ways = 0;
for (int zhang = 0; zhang * coins[index] <= rest && zhang <= zhangs[index]; zhang++)
{
ways += process(coins, zhangs, len, index + 1, rest - (zhang * coins[index]));
}
return ways;
}
static int dp1(int* arr, int len, int aim)
{
if (arr == nullptr || len == 0 || aim < 0)
{
return 0;
}
Info info = getInfo(arr, len);
int* coins = info.coins;
int* zhangs = info.zhangs;
int N = info.length;
int** dp = mallocArray(N + 1, aim + 1);
dp[N][0] = 1;
for (int index = N - 1; index >= 0; index--)
{
for (int rest = 0; rest <= aim; rest++)
{
int ways = 0;
for (int zhang = 0; zhang * coins[index] <= rest && zhang <= zhangs[index]; zhang++)
{
ways += dp[index + 1][rest - (zhang * coins[index])];
}
dp[index][rest] = ways;
}
}
int ans = dp[0][aim];
freeArray(dp, N + 1);
return ans;
}
static int dp2(int* arr, int len, int aim)
{
if (arr == nullptr || len == 0 || aim < 0)
{
return 0;
}
Info info = getInfo(arr, len);
int* coins = info.coins;
int* zhangs = info.zhangs;
int N = info.length;
int** dp = mallocArray(N + 1, aim + 1);
dp[N][0] = 1;
for (int index = N - 1; index >= 0; index--)
{
for (int rest = 0; rest <= aim; rest++)
{
dp[index][rest] = dp[index + 1][rest]; // 当前index不使用
// 当前index不计数量的使用,斜率优化
if (rest - coins[index] >= 0)
{
dp[index][rest] += dp[index][rest - coins[index]];
}
// 减去数量超出zhangs[index]的方案
if (rest - coins[index] * (zhangs[index] + 1) >= 0)
{
// 仔细想一想这里为什么减去 index + 1 而不是 index ?
// 从←看,不计数量使用:
// index+1行 | d | c | b | a
// index行 | a+b+c+d | a+b+c | a+b | a
// 从←看,记数量使用,减去index项:
// index+1行 | d | c | b | a
// index行 | a+b+c+d - (a) - (a + b)| a+b+c - (a) | a+b | a
// 会发现减了n次a,(n-1)次b,(n-2)次c,...
// 从←看,记数量使用,减去index+1项:
// index+1行 | d | c | b | a
// index行 | a+b+c+d - (a) - (b)| a+b+c - (a) | a+b | a
// 会发现减了1次a,1次b,1次c,...
// 并且可以发现减法是从左边一步步累减过来的
dp[index][rest] -= dp[index + 1][rest - coins[index] * (zhangs[index] + 1)];
}
}
}
return dp[0][aim];
}
// for test
static int** mallocArray(int row, int column)
{
int** arr = (int**)malloc(sizeof(int*) * row);
for(int i = 0; i < row; i++)
{
arr[i] = (int*)malloc(sizeof(int) * column);
memset(arr[i], 0, sizeof(int) * column);
}
return arr;
}
static void freeArray(int** arr, int row)
{
for(int i = 0; i < row; i++)
{
free(arr[i]);
}
free(arr);
}
// 为了测试
static int* randomArray(int maxLen, int maxValue, int* len)
{
*len = getRandom(0, maxLen);
int* arr = (int*)malloc(sizeof(int) * (*len));
for (int i = 0; i < *len; i++)
{
arr[i] = getRandom(1, maxValue);
}
return arr;
}
static int getRandom(int min, int max)
{
random_device seed; // 硬件生成随机数种子
ranlux48 engine(seed()); // 利用种子生成随机数引
uniform_int_distribution<> distrib(min, max); // 设置随机数范围,并为均匀分布
int res = distrib(engine); // 随机数
return res;
}
// 为了测试
static void printArray(int* arr, int len)
{
for (int i = 0; i < len; i++)
{
cout << arr[i] << " ";
}
cout << endl;
}
// 为了测试
static void test()
{
int maxLen = 10;
int maxValue = 20;
int testTime = 10000;
int len = 0;
cout << "测试开始" <<endl;
for (int i = 0; i < testTime; i++)
{
int* arr = randomArray(maxLen, maxValue, &len);
int aim = getRandom(0, maxValue);
int ans1 = coinsWay(arr, len, aim);
int ans2 = dp1(arr, len, aim);
int ans3 = dp2(arr, len, aim);
if (ans1 != ans2 || ans1 != ans3)
{
cout << "Oops!" <<endl;
printArray(arr, len);
cout << aim <<endl;
cout << ans1 <<endl;
cout << ans2 <<endl;
cout << ans3 <<endl;
break;
}
}
cout << "测试结束" <<endl;
}
};
int main()
{
CoinsWaySameValueSamePapper::test();
return 0;
}
| 25.553279 | 94 | 0.451002 | raining888 |
581a707426fc893d330b340dd9005937ff7b1d96 | 5,591 | cc | C++ | lib/core/builder/ninja/syntax.cc | poacpm/cpm | 1e004120990d952ec8f20cdc72e58b57fba9e333 | [
"Apache-2.0"
] | null | null | null | lib/core/builder/ninja/syntax.cc | poacpm/cpm | 1e004120990d952ec8f20cdc72e58b57fba9e333 | [
"Apache-2.0"
] | null | null | null | lib/core/builder/ninja/syntax.cc | poacpm/cpm | 1e004120990d952ec8f20cdc72e58b57fba9e333 | [
"Apache-2.0"
] | null | null | null | // external
#include <boost/regex.hpp>
// internal
#include "poac/core/builder/ninja/syntax.hpp"
#include "poac/util/pretty.hpp"
namespace poac::core::builder::ninja::syntax {
/// Expand a string containing $vars as Ninja would.
///
/// Note: doesn't handle the full Ninja variable syntax, but it's enough
/// to make configure.py's use of it work.
String
expand(const String& text, const Variables& vars, const Variables& local_vars) {
const auto exp = [&](const boost::smatch& m) {
const String var = m[1].str();
if (var == "$") {
return "$"s;
}
return local_vars.contains(var) ? local_vars.at(var)
: vars.contains(var) ? vars.at(var)
: ""s;
};
return boost::regex_replace(text, boost::regex("\\$(\\$|\\w*)"), exp);
}
/// ref: https://stackoverflow.com/a/46379136
String
operator*(const String& s, usize n) {
String result;
result.reserve(s.size() * n);
for (usize i = 0; i < n; ++i) {
result += s;
}
return result;
}
/// Returns the number of '$' characters right in front of s[i].
usize
Writer::count_dollars_before_index(StringRef s, usize i) const {
usize dollar_count = 0;
usize dollar_index = i - 1;
while (dollar_index > 0 && s[dollar_index] == '$') {
dollar_count += 1;
dollar_index -= 1;
}
return dollar_count;
}
/// Write 'text' word-wrapped at self.width characters.
void
Writer::_line(String text, usize indent) {
String leading_space = String(" ") * indent;
while (leading_space.length() + text.length() > width) {
// The text is too wide; wrap if possible.
// Find the rightmost space that would obey our width constraint and
// that's not an escaped space.
std::int32_t available_space =
width - leading_space.length() - 2; // " $".length() == 2
std::int32_t space = available_space;
do {
space = text.rfind(' ', space);
} while (!(space < 0 || count_dollars_before_index(text, space) % 2 == 0));
if (space < 0) {
// No such space; just use the first unescaped space we can find.
space = available_space - 1;
do {
space = text.find(' ', space + 1);
} while (!(space < 0 || count_dollars_before_index(text, space) % 2 == 0)
);
}
if (space < 0) {
// Give up on breaking.
break;
}
output << leading_space + text.substr(0, space) + " $\n";
text = text.substr(space + 1);
// Subsequent lines are continuations, so indent them.
leading_space = String(" ") * (indent + 2);
}
output << leading_space + text + '\n';
}
void
Writer::comment(const String& text) {
for (const String& line : util::pretty::textwrap(text, width - 2)) {
output << "# " + line + '\n';
}
}
void
Writer::variable(StringRef key, StringRef value, usize indent) {
if (value.empty()) {
return;
}
_line(format("{} = {}", key, value), indent);
}
void
Writer::rule(StringRef name, StringRef command, const RuleSet& rule_set) {
_line(format("rule {}", name));
variable("command", command, 1);
if (rule_set.description.has_value()) {
variable("description", rule_set.description.value(), 1);
}
if (rule_set.depfile.has_value()) {
variable("depfile", rule_set.depfile.value(), 1);
}
if (rule_set.generator) {
variable("generator", "1", 1);
}
if (rule_set.pool.has_value()) {
variable("pool", rule_set.pool.value(), 1);
}
if (rule_set.restat) {
variable("restat", "1", 1);
}
if (rule_set.rspfile.has_value()) {
variable("rspfile", rule_set.rspfile.value(), 1);
}
if (rule_set.rspfile_content.has_value()) {
variable("rspfile_content", rule_set.rspfile_content.value(), 1);
}
if (rule_set.deps.has_value()) {
variable("deps", rule_set.deps.value(), 1);
}
}
Vec<String>
Writer::build(
const Vec<String>& outputs, StringRef rule, const BuildSet& build_set
) {
Vec<String> out_outputs;
for (const String& o : outputs) {
out_outputs.emplace_back(escape_path(o).string());
}
Vec<String> all_inputs;
if (build_set.inputs.has_value()) {
for (const String& i : build_set.inputs.value()) {
all_inputs.emplace_back(escape_path(i).string());
}
}
if (build_set.implicit.has_value()) {
Vec<String> implicit;
for (const Path& i : build_set.implicit.value()) {
implicit.emplace_back(escape_path(i).string());
}
all_inputs.emplace_back("|");
boost::push_back(all_inputs, implicit);
}
if (build_set.order_only.has_value()) {
Vec<String> order_only;
for (const Path& o : build_set.order_only.value()) {
order_only.emplace_back(escape_path(o).string());
}
all_inputs.emplace_back("||");
boost::push_back(all_inputs, order_only);
}
if (build_set.implicit_outputs.has_value()) {
Vec<String> implicit_outputs;
for (const Path& i : build_set.implicit_outputs.value()) {
implicit_outputs.emplace_back(escape_path(i).string());
}
out_outputs.emplace_back("|");
boost::push_back(out_outputs, implicit_outputs);
}
_line(format(
"build {}: {} {}", boost::algorithm::join(out_outputs, " "), rule,
boost::algorithm::join(all_inputs, " ")
));
if (build_set.pool.has_value()) {
_line(format(" pool = {}", build_set.pool.value()));
}
if (build_set.dyndep.has_value()) {
_line(format(" dyndep = {}", build_set.dyndep.value()));
}
if (build_set.variables.has_value()) {
for (const auto& [key, val] : build_set.variables.value()) {
variable(key, val, 1);
}
}
return outputs;
}
} // namespace poac::core::builder::ninja::syntax
| 28.237374 | 80 | 0.62547 | poacpm |
5820f7cd77c89c0c427627b244697a53750946e6 | 8,544 | hpp | C++ | include/ldgr/logger.hpp | akalsi87/ldgr | 490392d7e3a0de3cb6240f4bcf12bce80ed5135f | [
"Zlib"
] | null | null | null | include/ldgr/logger.hpp | akalsi87/ldgr | 490392d7e3a0de3cb6240f4bcf12bce80ed5135f | [
"Zlib"
] | null | null | null | include/ldgr/logger.hpp | akalsi87/ldgr | 490392d7e3a0de3cb6240f4bcf12bce80ed5135f | [
"Zlib"
] | null | null | null | //! @file logger.hpp
//! @brief Logger
/*
* zlib License
*
* (C) 2020 Aaditya Kalsi
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#ifndef INCLUDED_LDGR_LOGGER_HPP
#define INCLUDED_LDGR_LOGGER_HPP
#include <ldgr/logentry.hpp>
#include <ldgr/logsink.hpp>
#include <fmt/ostream.h>
#include <algorithm>
#include <atomic>
#include <string>
#include <unordered_map>
namespace ldgr {
class logger {
friend class log_registry;
std::atomic<log_severity> d_level_;
std::shared_ptr<pooled_log_buffer_factory> d_factory_;
std::vector<std::shared_ptr<log_sink>> d_sinks_;
std::string d_name_;
std::mutex d_sinks_mutex_;
logger(std::string name,
std::shared_ptr<log_sink> sink,
std::shared_ptr<pooled_log_buffer_factory> factory) noexcept
: d_level_(log_severity::info)
, d_factory_(std::move(factory))
, d_sinks_(1, std::move(sink))
, d_name_(std::move(name))
, d_sinks_mutex_()
{
}
public:
logger(const logger&) = delete;
logger& operator=(const logger&) = delete;
fmt::string_view name() const noexcept
{
return fmt::string_view{d_name_.c_str(), d_name_.size()};
}
log_severity level() const noexcept
{
return d_level_.load(std::memory_order_acquire);
}
void add_sink(std::shared_ptr<log_sink> sink)
{
const std::lock_guard<std::mutex> guard{d_sinks_mutex_};
for (const auto& s : d_sinks_) {
if (s == sink) {
return;
}
}
d_sinks_.push_back(sink);
}
void remove_sink(std::shared_ptr<log_sink> sink)
{
const std::lock_guard<std::mutex> guard{d_sinks_mutex_};
d_sinks_.erase(std::remove(d_sinks_.begin(), d_sinks_.end(), sink));
}
bool should_log(log_severity lvl) const noexcept
{
return lvl >= level();
}
void set_level(log_severity lvl) noexcept
{
d_level_.store(lvl, std::memory_order_release);
}
void log(const log_entry& entry)
{
auto cp = log_entry_util::copy_log_entry(entry, true, *d_factory_);
const std::lock_guard<std::mutex> guard{d_sinks_mutex_};
for (const auto& s : d_sinks_) {
s->log(cp);
}
}
};
class log_registry {
struct hasher {
std::size_t operator()(const fmt::string_view& x) const noexcept
{
std::size_t h{0};
for (auto c : x) {
h = (h << 4u) + h + c;
}
return h;
}
};
static log_registry& instance();
std::shared_ptr<log_sink> d_default_sink_{log_sink_factory::stderr_sink()};
std::shared_ptr<pooled_log_buffer_factory> d_factory_{
pooled_log_buffer_factory::create()};
std::unordered_map<fmt::string_view, std::shared_ptr<logger>, hasher>
d_loggers_{std::make_pair(
fmt::string_view{"ROOT", 4},
std::shared_ptr<logger>{
new logger{"ROOT", d_default_sink_, d_factory_}})};
std::mutex d_logger_mutex_{};
public:
static logger& get(fmt::string_view logger_name)
{
auto& s = instance();
const std::lock_guard<std::mutex> guard{s.d_logger_mutex_};
auto it = s.d_loggers_.find(logger_name);
if (it != s.d_loggers_.end()) {
return *it->second;
}
auto l = std::shared_ptr<logger>(
new logger{std::string{logger_name.data(), logger_name.size()},
s.d_default_sink_,
s.d_factory_});
s.d_loggers_[l->name()] = l;
return *l;
}
};
namespace dtl {
template <class T>
struct format_checker {
enum { value = false };
};
template <class... ARGS>
constexpr bool check_formatters()
{
constexpr bool values[] = {
fmt::has_formatter<ARGS, fmt::format_context>::value...};
for (auto x : values) {
if (!x) {
return false;
}
}
return true;
}
template <class... ARGS>
struct format_checker<std::tuple<ARGS...>> {
enum { value = check_formatters<ARGS...>() };
};
template <class... ARGS>
auto derive_types(ARGS&&...) -> format_checker<std::tuple<ARGS...>>
{
return {};
};
} // namespace dtl
} // namespace ldgr
#define LDGR__STR2(x) #x
#define LDGR__STR(x) LDGR__STR2(x)
#define LDGR__LOG_IMPL(lvl, cat, fmtstr, ...) \
do { \
auto& l = ::ldgr::log_registry::get(cat); \
if (!l.should_log(::ldgr::log_severity::lvl)) { \
break; \
} \
::ldgr::log_buffer_t buff; \
using compile_time_format = \
decltype(::ldgr::dtl::derive_types(__VA_ARGS__)); \
if constexpr (compile_time_format::value) { \
::fmt::format_to(::std::back_inserter(buff), \
FMT_COMPILE(fmtstr), \
##__VA_ARGS__); \
} \
else { \
::fmt::format_to( \
::std::back_inserter(buff), fmtstr, ##__VA_ARGS__); \
} \
::ldgr::log_entry entry{ \
::ldgr::log_severity::lvl, \
::ldgr::fmtutil::to_view(cat), \
::ldgr::fmtutil::to_view(__FILE__), \
::ldgr::fmtutil::to_view(LDGR__STR(__LINE__)), \
::std::chrono::system_clock::now(), \
::ldgr::fmtutil::to_view(buff)}; \
l.log(entry); \
} while (0)
#define LDGR_CAT_TRACE(cat, fmtstr, ...) \
LDGR__LOG_IMPL(trace, cat, fmtstr, ##__VA_ARGS__)
#define LDGR_CAT_DEBUG(cat, fmtstr, ...) \
LDGR__LOG_IMPL(debug, cat, fmtstr, ##__VA_ARGS__)
#define LDGR_CAT_INFO(cat, fmtstr, ...) \
LDGR__LOG_IMPL(info, cat, fmtstr, ##__VA_ARGS__)
#define LDGR_CAT_WARN(cat, fmtstr, ...) \
LDGR__LOG_IMPL(warn, cat, fmtstr, ##__VA_ARGS__)
#define LDGR_CAT_ERROR(cat, fmtstr, ...) \
LDGR__LOG_IMPL(error, cat, fmtstr, ##__VA_ARGS__)
#define LDGR_CAT_FATAL(cat, fmtstr, ...) \
LDGR__LOG_IMPL(fatal, cat, fmtstr, ##__VA_ARGS__)
#define LDGR_TRACE(fmtstr, ...) LDGR_CAT_TRACE("ROOT", fmtstr, ##__VA_ARGS__)
#define LDGR_DEBUG(fmtstr, ...) LDGR_CAT_DEBUG("ROOT", fmtstr, ##__VA_ARGS__)
#define LDGR_INFO(fmtstr, ...) LDGR_CAT_INFO("ROOT", fmtstr, ##__VA_ARGS__)
#define LDGR_WARN(fmtstr, ...) LDGR_CAT_WARN("ROOT", fmtstr, ##__VA_ARGS__)
#define LDGR_ERROR(fmtstr, ...) LDGR_CAT_ERROR("ROOT", fmtstr, ##__VA_ARGS__)
#define LDGR_FATAL(fmtstr, ...) LDGR_CAT_FATAL("ROOT", fmtstr, ##__VA_ARGS__)
#endif /*INCLUDED_LDGR_LOGGER_HPP*/
| 34.039841 | 79 | 0.525866 | akalsi87 |
582362dae1216080f8d7b442b9fe59fae721d4e7 | 1,427 | cpp | C++ | src/animation/animation.cpp | krait-games/hyperion-engine | 5c52085658630fbf0992f794ecfcb25325b80b1c | [
"MIT"
] | 21 | 2022-01-23T15:20:59.000Z | 2022-03-31T22:10:14.000Z | src/animation/animation.cpp | krait-games/hyperion-engine | 5c52085658630fbf0992f794ecfcb25325b80b1c | [
"MIT"
] | 2 | 2022-01-30T22:24:58.000Z | 2022-03-28T02:37:07.000Z | src/animation/animation.cpp | krait-games/hyperion-engine | 5c52085658630fbf0992f794ecfcb25325b80b1c | [
"MIT"
] | 2 | 2022-02-10T13:55:26.000Z | 2022-03-31T22:10:16.000Z | #include "animation.h"
#include "../math/math_util.h"
namespace hyperion {
Animation::Animation(const std::string &name)
: name(name)
{
}
Animation::Animation(const Animation &other)
: name(name),
tracks(other.tracks)
{
}
const std::string &Animation::GetName() const
{
return name;
}
void Animation::SetName(const std::string &str)
{
name = str;
}
float Animation::GetLength() const
{
if (tracks.empty()) {
return 0.0;
} else {
return tracks.back().GetLength();
}
}
void Animation::AddTrack(const AnimationTrack &track)
{
tracks.push_back(track);
}
AnimationTrack &Animation::GetTrack(size_t index)
{
return tracks.at(index);
}
const AnimationTrack &Animation::GetTrack(size_t index) const
{
return tracks.at(index);
}
size_t Animation::NumTracks() const
{
return tracks.size();
}
void Animation::Apply(float time)
{
for (auto &&track : tracks) {
track.GetBone()->ClearPose();
track.GetBone()->ApplyPose(track.GetPoseAt(time));
}
}
void Animation::ApplyBlended(float time, float blend)
{
for (auto &&track : tracks) {
if (blend <= 0.001f) {
track.GetBone()->ClearPose();
}
auto frame = track.GetPoseAt(time);
auto blended = track.GetBone()->GetCurrentPose().Blend(frame,
MathUtil::Clamp(blend, 0.0f, 1.0f));
track.GetBone()->ApplyPose(blended);
}
}
}
| 18.532468 | 70 | 0.627891 | krait-games |
58266bb50af9f4d41e04bae91df5ab9607cefda7 | 1,515 | hpp | C++ | src/mlpack/core/tree/space_split/midpoint_space_split.hpp | RMaron/mlpack | a179a2708d9555ab7ee4b1e90e0c290092edad2e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 675 | 2019-02-07T01:23:19.000Z | 2022-03-28T05:45:10.000Z | src/mlpack/core/tree/space_split/midpoint_space_split.hpp | RMaron/mlpack | a179a2708d9555ab7ee4b1e90e0c290092edad2e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 843 | 2019-01-25T01:06:46.000Z | 2022-03-16T11:15:53.000Z | src/mlpack/core/tree/space_split/midpoint_space_split.hpp | RMaron/mlpack | a179a2708d9555ab7ee4b1e90e0c290092edad2e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 83 | 2019-02-20T06:18:46.000Z | 2022-03-20T09:36:09.000Z | /**
* @file midpoing_space_split.hpp
* @author Marcos Pividori
*
* Definition of MidpointSpaceSplit, to create a splitting hyperplane
* considering the midpoint of the values in a certain projection.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#ifndef MLPACK_CORE_TREE_SPILL_TREE_MIDPOINT_SPACE_SPLIT_HPP
#define MLPACK_CORE_TREE_SPILL_TREE_MIDPOINT_SPACE_SPLIT_HPP
#include <mlpack/prereqs.hpp>
#include "hyperplane.hpp"
namespace mlpack {
namespace tree {
template<typename MetricType, typename MatType>
class MidpointSpaceSplit
{
public:
/**
* Create a splitting hyperplane considering the midpoint of the values in a
* certain projection.
*
* @param bound The bound used for this node.
* @param data The dataset used by the tree.
* @param points Vector of indexes of points to be considered.
* @param hyp Resulting splitting hyperplane.
* @return Flag to determine if split is possible.
*/
template<typename HyperplaneType>
static bool SplitSpace(
const typename HyperplaneType::BoundType& bound,
const MatType& data,
const arma::Col<size_t>& points,
HyperplaneType& hyp);
};
} // namespace tree
} // namespace mlpack
// Include implementation.
#include "midpoint_space_split_impl.hpp"
#endif
| 29.705882 | 78 | 0.747855 | RMaron |
582a73f9ef3f01d3937dc0f1e9d724d3c752c5d3 | 4,889 | cpp | C++ | docs/template_plugin/tests/functional/op_reference/sigmoid.cpp | ivkalgin/openvino | 81685c8d212135dd9980da86a18db41fbf6d250a | [
"Apache-2.0"
] | null | null | null | docs/template_plugin/tests/functional/op_reference/sigmoid.cpp | ivkalgin/openvino | 81685c8d212135dd9980da86a18db41fbf6d250a | [
"Apache-2.0"
] | 18 | 2022-01-21T08:42:58.000Z | 2022-03-28T13:21:31.000Z | docs/template_plugin/tests/functional/op_reference/sigmoid.cpp | ematroso/openvino | 403339f8f470c90dee6f6d94ed58644b2787f66b | [
"Apache-2.0"
] | null | null | null | // Copyright (C) 2018-2022 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include <gtest/gtest.h>
#include "openvino/op/sigmoid.hpp"
#include "base_reference_test.hpp"
using namespace reference_tests;
using namespace ov;
namespace {
struct SigmoidParams {
template <class IT>
SigmoidParams(const ov::PartialShape& shape, const ov::element::Type& iType, const std::vector<IT>& iValues, const std::vector<IT>& oValues)
: pshape(shape),
inType(iType),
outType(iType),
inputData(CreateTensor(iType, iValues)),
refData(CreateTensor(iType, oValues)) {}
ov::PartialShape pshape;
ov::element::Type inType;
ov::element::Type outType;
ov::runtime::Tensor inputData;
ov::runtime::Tensor refData;
};
class ReferenceSigmoidLayerTest : public testing::TestWithParam<SigmoidParams>, public CommonReferenceTest {
public:
void SetUp() override {
auto params = GetParam();
function = CreateFunction(params.pshape, params.inType, params.outType);
inputData = {params.inputData};
refOutData = {params.refData};
}
static std::string getTestCaseName(const testing::TestParamInfo<SigmoidParams>& obj) {
auto param = obj.param;
std::ostringstream result;
result << "shape=" << param.pshape << "_";
result << "iType=" << param.inType << "_";
result << "oType=" << param.outType;
return result.str();
}
private:
static std::shared_ptr<Model> CreateFunction(const PartialShape& input_shape, const element::Type& input_type,
const element::Type& Sigmoidected_output_type) {
const auto in = std::make_shared<op::v0::Parameter>(input_type, input_shape);
const auto Sigmoid = std::make_shared<op::v0::Sigmoid>(in);
return std::make_shared<ov::Model>(NodeVector {Sigmoid}, ParameterVector {in});
}
};
TEST_P(ReferenceSigmoidLayerTest, CompareWithRefs) {
Exec();
}
template <element::Type_t IN_ET>
std::vector<SigmoidParams> generateSigmoidFloatParams() {
using T = typename element_type_traits<IN_ET>::value_type;
float x1 = 1.0f;
float x2 = 4.0f;
float sigma1 = 1.0f / (1.0f + std::exp(-x1));
float sigma2 = 1.0f / (1.0f + std::exp(-x2));
std::vector<SigmoidParams> sigmoidParams {
SigmoidParams(ov::PartialShape {1, 1, 2, 2},
IN_ET,
std::vector<T>{x1, x2, x1, x2},
std::vector<T>{sigma1, sigma2, sigma1, sigma2}),
SigmoidParams(ov::PartialShape {1, 1, 4},
IN_ET,
std::vector<T>{x1, x2, x1, x2},
std::vector<T>{sigma1, sigma2, sigma1, sigma2})
};
return sigmoidParams;
}
template <element::Type_t IN_ET>
std::vector<SigmoidParams> generateSigmoidIntParams() {
using T = typename element_type_traits<IN_ET>::value_type;
std::vector<SigmoidParams> sigmoidParams {
SigmoidParams(ov::PartialShape {1, 1, 2, 2},
IN_ET,
std::vector<T>{1, 4, -1, -4},
std::vector<T>{1, 1, 0, 0}),
SigmoidParams(ov::PartialShape {1, 1, 4},
IN_ET,
std::vector<T>{1, 4, -1, -4},
std::vector<T>{1, 1, 0, 0})
};
return sigmoidParams;
}
template <element::Type_t IN_ET>
std::vector<SigmoidParams> generateSigmoidUintParams() {
using T = typename element_type_traits<IN_ET>::value_type;
std::vector<SigmoidParams> sigmoidParams {
SigmoidParams(ov::PartialShape {1, 1, 2, 2},
IN_ET,
std::vector<T>{1, 4, 1, 4},
std::vector<T>{1, 1, 1, 1}),
SigmoidParams(ov::PartialShape {1, 1, 4},
IN_ET,
std::vector<T>{1, 4, 1, 4},
std::vector<T>{1, 1, 1, 1})
};
return sigmoidParams;
}
std::vector<SigmoidParams> generateSigmoidCombinedParams() {
const std::vector<std::vector<SigmoidParams>> sigmoidTypeParams {
generateSigmoidFloatParams<element::Type_t::f32>(),
generateSigmoidFloatParams<element::Type_t::f16>(),
generateSigmoidIntParams<element::Type_t::i64>(),
generateSigmoidIntParams<element::Type_t::i32>(),
generateSigmoidUintParams<element::Type_t::u64>(),
generateSigmoidUintParams<element::Type_t::u32>()
};
std::vector<SigmoidParams> combinedParams;
for (const auto& params : sigmoidTypeParams) {
combinedParams.insert(combinedParams.end(), params.begin(), params.end());
}
return combinedParams;
}
INSTANTIATE_TEST_SUITE_P(smoke_Sigmoid_With_Hardcoded_Refs, ReferenceSigmoidLayerTest,
testing::ValuesIn(generateSigmoidCombinedParams()), ReferenceSigmoidLayerTest::getTestCaseName);
} // namespace
| 35.427536 | 144 | 0.617304 | ivkalgin |
582d0e4755402a4e2c221813857d1277ef1f8094 | 3,800 | cpp | C++ | src/lib/factory_manager.cpp | sj0897/my-ARIAC-competition-2021 | fbaa26430d5c37444464a3c04d44d80cf11c5ef1 | [
"BSD-3-Clause"
] | null | null | null | src/lib/factory_manager.cpp | sj0897/my-ARIAC-competition-2021 | fbaa26430d5c37444464a3c04d44d80cf11c5ef1 | [
"BSD-3-Clause"
] | null | null | null | src/lib/factory_manager.cpp | sj0897/my-ARIAC-competition-2021 | fbaa26430d5c37444464a3c04d44d80cf11c5ef1 | [
"BSD-3-Clause"
] | null | null | null | #include "factory_manager.h"
#include <string>
#include <std_srvs/Trigger.h>
#include <nist_gear/KittingShipment.h>
#include <nist_gear/AssemblyShipment.h>
FactoryManager::FactoryManager(ros::NodeHandle* nodehandle):
m_nh{*nodehandle},
m_orders{nodehandle}
{
// Subscribers
m_busy_subscriber = m_nh.subscribe("/worker/busy", 50, &FactoryManager::busy_callback, this);
// Publishers
m_kitting_publisher = m_nh.advertise<nist_gear::KittingShipment>("/factory_manager/kitting_task", 10);
m_assembly_publisher = m_nh.advertise<nist_gear::AssemblyShipment>("/factory_manager/assembly_task", 10);
// Services
m_get_competition_time_service = m_nh.advertiseService("/factory_manager/get_competition_time", &FactoryManager::get_competition_time, this);
// All workers are free at start
for (auto& worker: m_workers) {
m_busy_state[worker] = false;
}
}
void FactoryManager::run_competition()
{
this->start_competition();
m_start_time = ros::Time::now();
while (ros::ok()) {
if (m_orders.get_order()) {
this->plan();
}
}
this->end_competition();
}
void FactoryManager::busy_callback(const ariac_group1::Busy& msg){
m_busy_state[msg.id] = msg.state;
}
void FactoryManager::start_competition()
{
std::string service_name = "/ariac/start_competition";
static auto client = m_nh.serviceClient<std_srvs::Trigger>(service_name);
if (!client.exists()) {
ROS_INFO("Waiting for the competition to be ready...");
client.waitForExistence();
ROS_INFO("Competition is now ready.");
}
std_srvs::Trigger srv;
if (client.call(srv)) {
ROS_INFO("%s", srv.response.message.c_str());
}
else {
ROS_ERROR("Failed to call %s", service_name.c_str());
}
}
void FactoryManager::end_competition()
{
std::string service_name = "/ariac/end_competition";
static auto client = m_nh.serviceClient<std_srvs::Trigger>(service_name);
if (!client.exists()) {
ROS_INFO("Waiting for the competition to be ready...");
client.waitForExistence();
ROS_INFO("Competition is now ready.");
}
std_srvs::Trigger srv;
if (client.call(srv)) {
ROS_INFO("%s", srv.response.message.c_str());
}
else {
ROS_ERROR("Failed to call %s", service_name.c_str());
}
}
void FactoryManager::plan()
{
// Lock to prevent adding new orders when assigning tasks
const std::lock_guard<std::mutex> lock(*m_mutex_ptr);
for (auto& order_id: m_orders.get_new_orders_id()) {
// Check if parts valid in order
// auto valid = this->check_order(order_id);
auto& order = m_orders.orders_record[order_id]->order;
for (auto &shipment: order->kitting_shipments) {
this->assign_kitting_task(shipment);
}
for (auto &shipment: order->assembly_shipments) {
this->assign_assembly_task(shipment);
}
}
m_orders.clear_new_orders_id();
}
void FactoryManager::assign_kitting_task(nist_gear::KittingShipment& shipment)
{
nist_gear::KittingShipment msg;
msg = shipment;
m_kitting_publisher.publish(msg);
}
void FactoryManager::assign_assembly_task(nist_gear::AssemblyShipment& shipment){
nist_gear::AssemblyShipment msg;
msg = shipment;
m_assembly_publisher.publish(msg);
}
bool FactoryManager::get_competition_time(ariac_group1::GetCompetitionTime::Request &req,
ariac_group1::GetCompetitionTime::Response &res)
{
auto competition_time = ros::Time::now() - m_start_time;
res.competition_time = competition_time.toSec();
return true;
}
bool FactoryManager::work_done()
{
for (const auto& worker_busy_state: m_busy_state) {
if (worker_busy_state.second) {
ROS_INFO("Waiting for worker: %s", worker_busy_state.first.c_str());
return false;
}
}
return true;
}
| 24.516129 | 144 | 0.697895 | sj0897 |
583e2c1a990b26c999fb50cafcc3f738de619d45 | 1,148 | cpp | C++ | src/UdpServer.cpp | anloro/modular_slam | fbcb125f57e7875051ca0f600e882c87d72b1bdb | [
"MIT"
] | 1 | 2021-09-05T10:58:01.000Z | 2021-09-05T10:58:01.000Z | src/UdpServer.cpp | anloro/modular_slam | fbcb125f57e7875051ca0f600e882c87d72b1bdb | [
"MIT"
] | null | null | null | src/UdpServer.cpp | anloro/modular_slam | fbcb125f57e7875051ca0f600e882c87d72b1bdb | [
"MIT"
] | 1 | 2021-09-05T10:58:04.000Z | 2021-09-05T10:58:04.000Z | // Server side implementation of UDP client-server model
#include "UdpClientServer.h"
using namespace anloro;
anloro::UdpServer::UdpServer()
{
// Create the UDP socket
// SOCK_STREAM for TCP / SOCK_DGRAM for UDP
if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
perror("cannot create socket\n");
}
// Bind the socket to any valid IP address and a specific port
memset((char *)&myaddr, 0, sizeof(myaddr));
myaddr.sin_family = AF_INET;
myaddr.sin_addr.s_addr = htonl(INADDR_ANY);
myaddr.sin_port = htons(port);
if (bind(fd, (struct sockaddr *)&myaddr, sizeof(myaddr)) < 0) {
perror("bind failed");
}
// Allocate the buffer
// buffer = calloc(1, sizeof(struct MsgUdp));
}
int anloro::UdpServer::Receive(void * buffer)
{
int recvlen;
recvlen = recvfrom(fd, buffer, sizeof(MsgUdp), 0, (struct sockaddr *)&remaddr, &addrlen);
return recvlen;
}
int anloro::UdpServer::Send(MsgUdp msg)
{
if (sendto(fd, (char*)&msg, sizeof(MsgUdp), 0, (struct sockaddr *)&remaddr, slen)==-1){
perror("sendto");
return -1;
}
return 0;
}
| 24.956522 | 93 | 0.623693 | anloro |
58455840aca91f9510459442d3ede8058ebbb07a | 238 | cpp | C++ | solutions/717.1-bit-and-2-bit-characters.249179424.ac.cpp | satu0king/Leetcode-Solutions | 2edff60d76c2898d912197044f6284efeeb34119 | [
"MIT"
] | 78 | 2020-10-22T11:31:53.000Z | 2022-02-22T13:27:49.000Z | solutions/717.1-bit-and-2-bit-characters.249179424.ac.cpp | satu0king/Leetcode-Solutions | 2edff60d76c2898d912197044f6284efeeb34119 | [
"MIT"
] | null | null | null | solutions/717.1-bit-and-2-bit-characters.249179424.ac.cpp | satu0king/Leetcode-Solutions | 2edff60d76c2898d912197044f6284efeeb34119 | [
"MIT"
] | 26 | 2020-10-23T15:10:44.000Z | 2021-11-07T16:13:50.000Z | class Solution {
public:
bool isOneBitCharacter(vector<int> &bits) {
for (int i = 0; i < bits.size(); i++) {
if (i == bits.size() - 1)
return true;
if (bits[i] == 1)
i++;
}
return false;
}
};
| 15.866667 | 45 | 0.47479 | satu0king |
5847bf7b722c0a98d5b24db66f5c59ce67b592ff | 3,141 | hpp | C++ | src/mesh/mesh.hpp | guhanfeng/HSF | d2f091e990bb5a18473db0443872e37de6b6a83f | [
"Apache-2.0"
] | null | null | null | src/mesh/mesh.hpp | guhanfeng/HSF | d2f091e990bb5a18473db0443872e37de6b6a83f | [
"Apache-2.0"
] | null | null | null | src/mesh/mesh.hpp | guhanfeng/HSF | d2f091e990bb5a18473db0443872e37de6b6a83f | [
"Apache-2.0"
] | null | null | null | /**
* @file: mesh.hpp
* @author: Liu Hongbin
* @brief:
* @date: 2019-09-24 09:25:44
* @last Modified by: lenovo
* @last Modified time: 2019-11-28 10:27:09
*/
#ifndef MESH_HPP
#define MESH_HPP
#include "utilities.hpp"
#include "section.hpp"
#include "topology.hpp"
#include "nodes.hpp"
namespace HSF
{
/**
* @brief Mesh
*/
class Mesh
{
private:
Topology topo_; ///< topology
Nodes nodes_; ///< Coordinates of Nodes
Nodes ownNodes_; ///< Coordinates of nodes owned by this process
Table<label, label> coordMap_; ///< map between the absolute index and the local index
Array<Section> secs_; ///< section information for CGNS file
label meshType_; ///< the type of mesh: boundary or inner mesh
label nodeNum_; /// count of nodes
label eleNum_; /// count of elements
/**
* @brief read mesh file with CGNS format
*/
void readCGNSFile(const char* filePtr);
/**
* @brief read mesh file with CGNS format, parallel version
*/
void readCGNSFilePar(const char* filePtr);
/**
* @brief write mesh file with CGNS format, parallel version
*/
void writeCGNSFilePar(const char* filePtr);
/**
* @brief initialize mesh file with CGNS format, parallel version
*/
void initCGNSFilePar(const char* filePtr);
public:
/**
* @brief default constructor
*/
Mesh()
{
this->meshType_ = Inner;
};
/**
* @brief deconstructor
*/
virtual ~Mesh(){};
/**
* @brief read mesh and construct topology
*/
void readMesh(const char* filePtr)
{
readCGNSFilePar(filePtr);
topo_.constructTopology(this->secs_);
};
/**
* @brief initialize mesh and construct topology
*/
void initMesh(const char* filePtr)
{
// writeCGNSFile(filePtr);
initCGNSFilePar(filePtr);
// topo_ = new Topology(this->secs_);
};
/**
* @brief write mesh and construct topology
*/
void writeMesh(const char* filePtr)
{
// writeCGNSFile(filePtr);
writeCGNSFilePar(filePtr);
// topo_ = new Topology(this->secs_);
};
/**
* @brief get class Topology
*/
Topology& getTopology() {return this->topo_;};
/**
* @brief get coordinates of Nodes without load balance
*/
Nodes& getNodes() {return this->nodes_;};
/**
* @brief get coordinates of nodes owned by this process
*/
Nodes& getOwnNodes() {return this->ownNodes_;};
/**
* @brief get the collections of section in CGNS file
*/
Array<Section>& getSections() {return this->secs_; };
/**
* @brief set the load balance result to topology
* @param[in] cell2Node the topology between elements and nodes
* @param[in] cellType the elements type
*/
void setLoadBalancerResult(ArrayArray<label>& cell2Node,
Array<label> cellType)
{
this->topo_.setCell2Node(cell2Node);
this->topo_.setCellType(cellType);
};
void setMeshType(label meshType) {this->meshType_ = meshType;};
/**
* @brief translate the element type to string
*/
char* typeToString(ElementType_t eleType);
/**
* @brief fetch the coordinates of nodes owned by this process
*/
void fetchNodes(char* filePtr);
/**
* @brief get the map between the absolute index and the local index
*/
Table<label, label>& getCoordMap() {return this->coordMap_;};
};
} // end namespace HSF
#endif | 21.080537 | 87 | 0.687361 | guhanfeng |
5847ce0346d8abf2c2692c30cefd0d4219c5731e | 3,905 | hpp | C++ | include/integratorxx/quadratures/muraknowles.hpp | evaleev/IntegratorXX | 70339ca2d8f753e477dffb64788913c1bc12b519 | [
"BSD-3-Clause"
] | null | null | null | include/integratorxx/quadratures/muraknowles.hpp | evaleev/IntegratorXX | 70339ca2d8f753e477dffb64788913c1bc12b519 | [
"BSD-3-Clause"
] | null | null | null | include/integratorxx/quadratures/muraknowles.hpp | evaleev/IntegratorXX | 70339ca2d8f753e477dffb64788913c1bc12b519 | [
"BSD-3-Clause"
] | 3 | 2019-05-09T21:02:21.000Z | 2021-03-04T21:34:35.000Z | #pragma once
#include <integratorxx/quadrature.hpp>
#include <integratorxx/quadratures/uniform.hpp>
namespace IntegratorXX {
/**
* @brief Implementation of the Mura-Knowles radial quadrature.
*
* Generates a quadrature on the bounds (0, inf). Suitable for integrands
* which tend to zero as their argument tends to 0 and inf. Tailored for
* radial integrands, i.e. r^2 * f(r), with lim_{r->inf} f(r) = 0.
*
* Reference:
* J. Chem. Phys. 104, 9848 (1996);
* DOI: https://doi.org/10.1063/1.471749
*
* @tparam PointType Type describing the quadrature points
* @tparam WeightType Type describing the quadrature weights
*/
template <typename PointType, typename WeightType>
class MuraKnowles :
public Quadrature<MuraKnowles<PointType,WeightType>> {
using base_type = Quadrature<MuraKnowles<PointType,WeightType>>;
public:
using point_type = typename base_type::point_type;
using weight_type = typename base_type::weight_type;
using point_container = typename base_type::point_container;
using weight_container = typename base_type::weight_container;
/**
* @brief Construct the Mura-Knowles radial quadrature
*
* @param[in] npts Number of quadrature points to generate
* @param[in] R Radial scaling factor. Table for suggested
* values is given in the original reference.
*/
MuraKnowles(size_t npts, weight_type R = 1.): base_type( npts, R ) { }
MuraKnowles( const MuraKnowles& ) = default;
MuraKnowles( MuraKnowles&& ) noexcept = default;
};
/**
* @brief Quadrature traits for the Mura-Knowles quadrature
*
* @tparam PointType Type describing the quadrature points
* @tparam WeightType Type describing the quadrature weights
*/
template <typename PointType, typename WeightType>
struct quadrature_traits<
MuraKnowles<PointType,WeightType>,
std::enable_if_t<
std::is_floating_point_v<PointType> and
std::is_floating_point_v<WeightType>
>
> {
using point_type = PointType;
using weight_type = WeightType;
using point_container = std::vector< point_type >;
using weight_container = std::vector< weight_type >;
/**
* @brief Generator for the Mura-Knowles quadrature
*
* @param[in] npts Number of quadrature points to generate
* @param[in] R Radial scaling factor. Table for suggested
* values is given in the original reference.
*
* @returns Tuple of quadrature points and weights
*/
inline static std::tuple<point_container,weight_container>
generate( size_t npts, weight_type R ) {
point_container points( npts );
weight_container weights( npts );
using base_quad_traits =
quadrature_traits<UniformTrapezoid<PointType,WeightType>>;
/*
* Generate uniform trapezoid points on [0,1]
* ux(j) = j/(m-1)
* uw(j) = 1/(m-1)
* m = npts + 2, j in [0, npts+2)
*/
auto [ux, uw] = base_quad_traits::generate( npts+2, 0., 1. );
/*
* Perform Mura and Knowles transformation
*
* Original reference:
* J. Chem. Phys. 104, 9848 (1996);
* DOI: https://doi.org/10.1063/1.471749
*
* Closed form for points / weights obtained from:
* Journal of Computational Chemistry, 24: 732–740, 2003
* DOI: https://doi.org/10.1002/jcc.10211
*
* x(i) = ux(i+1)
* r(i) = - log(1 - x(i)^3)
* w(i) = uw(i+1) * 3 * x(i)^2 / ( 1 - x(i)^3 )
* i in [0, npts)
*
* XXX: i+1 offset on trapezoid points ignores enpoints of trapezoid
* quadrature (f(r) = 0 with r in {0,inf})
*/
for( size_t i = 0; i < npts; ++i ) {
const auto xi = ux[i+1];
const auto one_m_xi3 = 1. - xi*xi*xi;
points[i] = -R * std::log( one_m_xi3 );
weights[i] = R * uw[i+1] * 3 * xi * xi / one_m_xi3;
}
return std::make_tuple( points, weights );
}
};
}
| 28.713235 | 74 | 0.646607 | evaleev |
58488fe57a8099381d7b96f43d0bc199ebea1358 | 769 | cpp | C++ | date-triad/main.cpp | Sanlovty/lab-date-triad | 9b0232192049e0affdebc1c4ed15358a33a19eac | [
"Apache-2.0"
] | null | null | null | date-triad/main.cpp | Sanlovty/lab-date-triad | 9b0232192049e0affdebc1c4ed15358a33a19eac | [
"Apache-2.0"
] | null | null | null | date-triad/main.cpp | Sanlovty/lab-date-triad | 9b0232192049e0affdebc1c4ed15358a33a19eac | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include "Date.h"
using namespace std;
int main()
{
try
{
Date date(10, 15, 2001);
cout << "Initial date: " << date.toString();
date.increaseDateByN(10);
cout << endl << "Date after 10 days: " << date.toString();
date.increaseFirst();
cout << endl << "Date after applying method increaseFirst(): " << date.toString();
date.increaseSecond();
cout << endl << "Date after applying method increaseSecond(): " << date.toString();
date.increaseThird();
cout << endl << "Date after applying method increaseThird(): " << date.toString();
date.increaseTuple();
cout << endl << "Date after applying method increaseTuple(): " << date.toString();
}
catch (const exception& ex)
{
cout << "Error: " << ex.what();
}
return 0;
}
| 25.633333 | 85 | 0.637191 | Sanlovty |
5849b58566a16cebca8d63cb9124c2f21ce3ce65 | 6,131 | cpp | C++ | test/queue_bridge.cpp | uos/hatsdf_slam | f30f69c0f6b9286cd4fa51ca17f0e2d423ca4682 | [
"BSD-3-Clause"
] | 5 | 2021-05-21T07:52:50.000Z | 2022-02-09T04:26:31.000Z | test/queue_bridge.cpp | uos/hatsdf_slam | f30f69c0f6b9286cd4fa51ca17f0e2d423ca4682 | [
"BSD-3-Clause"
] | null | null | null | test/queue_bridge.cpp | uos/hatsdf_slam | f30f69c0f6b9286cd4fa51ca17f0e2d423ca4682 | [
"BSD-3-Clause"
] | 1 | 2022-02-09T04:26:33.000Z | 2022-02-09T04:26:33.000Z | /**
* @file queue_bridge.cpp
* @author Marcel Flottmann
* @date 2020-10-6
*/
#include "catch2_config.h"
#include <comm/receiver.h>
#include <msg/stamped.h>
#include <msg/point_cloud.h>
#include <comm/buffered_receiver.h>
#include <comm/queue_bridge.h>
#include <iostream>
using namespace fastsense::comm;
using namespace fastsense::msg;
using namespace fastsense::util;
using namespace std::chrono_literals;
#define SLEEP(x) std::this_thread::sleep_for(x)
TEST_CASE("QueueBridge", "[communication_queue_bridge]")
{
std::cout << "Testing 'QueueBridge'" << std::endl;
int value_received = 0;
int value_to_send = 42;
bool received = false;
bool sending = true;
auto in = std::make_shared<ConcurrentRingBuffer<int>>(16);
auto out = std::make_shared<ConcurrentRingBuffer<int>>(16);
QueueBridge<int, true> bridge{in, out, 5234};
std::thread receive_thread{[&]()
{
Receiver<int> receiver{"127.0.0.1", 5234, 20ms};
while (!received)
{
if (receiver.receive(value_received))
{
received = true;
}
}
}};
std::thread send_thread{[&]()
{
while (sending)
{
in->push(value_to_send);
SLEEP(100ms);
}
}};
bridge.start();
while (!received)
{
std::this_thread::yield();
}
bridge.stop();
sending = false;
receive_thread.join();
send_thread.join();
REQUIRE(value_to_send == value_received);
REQUIRE(out->size() != 0);
}
TEST_CASE("QueueBridge shared_ptr", "[communication_queue_bridge]")
{
std::cout << "Testing 'QueueBridge shared_ptr'" << std::endl;
int value_received = 0;
int value_to_send = 42;
bool received = false;
bool sending = true;
auto in = std::make_shared<ConcurrentRingBuffer<std::shared_ptr<int>>>(16);
auto out = std::make_shared<ConcurrentRingBuffer<std::shared_ptr<int>>>(16);
QueueBridge<std::shared_ptr<int>, true> bridge{in, out, 4234};
std::thread receive_thread{[&]()
{
Receiver<int> receiver{"127.0.0.1", 4234, 20ms};
while (!received)
{
if (receiver.receive(value_received))
{
received = true;
}
}
}};
std::thread send_thread{[&]()
{
while (sending)
{
in->push(std::make_shared<int>(value_to_send));
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}};
bridge.start();
while (!received)
{
std::this_thread::yield();
}
bridge.stop();
sending = false;
receive_thread.join();
send_thread.join();
REQUIRE(value_to_send == value_received);
REQUIRE(out->size() != 0);
}
TEST_CASE("QueueBridge Stamped<Imu>", "[communication_queue_bridge]")
{
std::cout << "Testing 'QueueBridge Stamped<Imu>'" << std::endl;
Imu imu{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
auto ts_sent = HighResTime::now();
ImuStamped value_to_send{std::move(imu), ts_sent};
ImuStamped value_received;
bool received = false;
bool sending = true;
auto in = std::make_shared<ConcurrentRingBuffer<ImuStamped>>(16);
auto out = std::make_shared<ConcurrentRingBuffer<ImuStamped>>(16);
QueueBridge<ImuStamped, true> bridge{in, out, 3234};
std::thread receive_thread{[&]()
{
Receiver<ImuStamped> receiver{"127.0.0.1", 3234, 20ms};
while (!received)
{
if (receiver.receive(value_received))
{
received = true;
}
}
}};
std::thread send_thread{[&]()
{
while (sending)
{
in->push(value_to_send);
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}};
bridge.start();
while (!received)
{
std::this_thread::yield();
}
bridge.stop();
sending = false;
receive_thread.join();
send_thread.join();
const auto& [ imu_received, ts ] = value_received;
REQUIRE(imu_received.acc.x() == 1);
REQUIRE(imu_received.acc.y() == 2);
REQUIRE(imu_received.acc.z() == 3);
REQUIRE(imu_received.ang.x() == 4);
REQUIRE(imu_received.ang.y() == 5);
REQUIRE(imu_received.ang.z() == 6);
REQUIRE(imu_received.mag.x() == 7);
REQUIRE(imu_received.mag.y() == 8);
REQUIRE(imu_received.mag.z() == 9);
REQUIRE(ts == ts_sent);
REQUIRE(out->size() != 0);
}
TEST_CASE("QueueBridge Stamped<PointCloud>", "[communication_queue_bridge]")
{
std::cout << "Testing 'QueueBridge Stamped<PointCloud>'" << std::endl;
Imu imu{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
auto ts_sent = HighResTime::now();
PointCloud pc_to_send;
pc_to_send.rings_ = 2;
pc_to_send.points_.push_back({1, 2, 3});
pc_to_send.points_.push_back({2, 3, 4});
pc_to_send.points_.push_back({3, 4, 5});
Stamped<PointCloud> pcl_sent{std::move(pc_to_send), ts_sent};
Stamped<PointCloud> pcl_received;
bool received = false;
bool sending = true;
auto in = std::make_shared<ConcurrentRingBuffer<Stamped<PointCloud>>>(16);
auto out = std::make_shared<ConcurrentRingBuffer<Stamped<PointCloud>>>(16);
QueueBridge<Stamped<PointCloud>, true> bridge{in, out, 2234};
std::thread receive_thread{[&]()
{
Receiver<Stamped<PointCloud>> receiver{"127.0.0.1", 2234, 20ms};
while (!received)
{
if (receiver.receive(pcl_received))
{
received = true;
}
}
}};
std::thread send_thread{[&]()
{
while (sending)
{
in->push(pcl_sent);
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}};
bridge.start();
while (!received)
{
std::this_thread::yield();
}
bridge.stop();
sending = false;
receive_thread.join();
send_thread.join();
const auto& [ pcl_data, ts ] = pcl_received;
REQUIRE(pcl_data.points_ == pcl_sent.data_.points_);
REQUIRE(ts == ts_sent);
REQUIRE(out->size() != 0);
} | 25.127049 | 80 | 0.585549 | uos |
5850c3de7cfeeeef067a1000d1bd3f86a682913f | 1,147 | cpp | C++ | src/parser/Parser.cpp | SebastianBogado/7559-tp-concu-2014-1c | 8aab30db8b9a7d9c10e5f6b1980207ee89b6bad1 | [
"MIT"
] | null | null | null | src/parser/Parser.cpp | SebastianBogado/7559-tp-concu-2014-1c | 8aab30db8b9a7d9c10e5f6b1980207ee89b6bad1 | [
"MIT"
] | null | null | null | src/parser/Parser.cpp | SebastianBogado/7559-tp-concu-2014-1c | 8aab30db8b9a7d9c10e5f6b1980207ee89b6bad1 | [
"MIT"
] | null | null | null | #include "parser/Parser.h"
#include <iostream>
#include <cassert>
#include <unistd.h>
#include <stdlib.h>
#include <getopt.h>
Parser::Parser() : _debug(default_debug), _ready(true), _surtidores(default_surtidores), _empleados(default_empleados) {
}
void Parser::printUsage() const {
std::cout << "Uso: ./estacion [-d] [-e] <empleados> [-s] <surtidores>\n";
std::cout << "\t-d: debug mode\n";
std::cout << "\t-e: cantidad de empleados\n";
std::cout << "\t-s: cantidad de surtidores\n";
}
bool Parser::parse(int argc, char* argv[]) {
int option;
while ((option = getopt(argc, argv, "de:s:")) != -1) {
switch (option) {
case 'd':
_debug = true;
break;
case 'e':
_empleados = atoi(optarg);
break;
case 's':
_surtidores = atoi(optarg);
break;
case '?':
_ready = false;
return false;
default:
_ready = false;
return false;
}
}
_ready = true;
return true;
}
int Parser::cantSurtidores() const {
assert(_ready);
return _surtidores;
}
int Parser::cantEmpleados() const {
assert(_ready);
return _empleados;
}
bool Parser::debugMode() const {
assert(_ready);
return _debug;
} | 19.775862 | 120 | 0.634699 | SebastianBogado |
5855830bd1a7e4f5b08e7fd41e595a5ff66b3d37 | 912 | cpp | C++ | tests/core/IntegrationTest.cpp | dkozyr/brainfuck | dd6cae16e78ab2afcbd12d70bf399d6559a1f92f | [
"MIT"
] | 1 | 2022-02-01T09:57:29.000Z | 2022-02-01T09:57:29.000Z | tests/core/IntegrationTest.cpp | dkozyr/brainfuck | dd6cae16e78ab2afcbd12d70bf399d6559a1f92f | [
"MIT"
] | null | null | null | tests/core/IntegrationTest.cpp | dkozyr/brainfuck | dd6cae16e78ab2afcbd12d70bf399d6559a1f92f | [
"MIT"
] | null | null | null | #include "Compiler.h"
#include <gtest/gtest.h>
TEST(Integration, HelloWorld) {
Compiler bf(std::string{EXAMPLES_PATH} + "/hello.bf");
bf.Execute();
bf.ExecuteOptimized();
}
TEST(Integration, Bench1) {
Compiler bf(std::string{EXAMPLES_PATH} + "/bench-1.bf");
bf.Execute();
bf.ExecuteOptimized();
std::cout << std::endl;
// DebugScript(bf.GetProgram());
}
TEST(Integration, Bench2) {
Compiler bf(std::string{EXAMPLES_PATH} + "/bench-2.bf");
bf.Execute();
bf.ExecuteOptimized();
}
TEST(Integration, MandelbrotTiny) {
Compiler bf(std::string{EXAMPLES_PATH} + "/mandelbrot-tiny.bf");
bf.ExecuteOptimized();
}
TEST(Integration, DISABLED_pi) {
Compiler bf(std::string{EXAMPLES_PATH} + "/pi-digits.bf");
bf.ExecuteOptimized();
}
TEST(Integration, DISABLED_e) {
Compiler bf(std::string{EXAMPLES_PATH} + "/e.bf");
bf.ExecuteOptimized(1'000'000);
}
| 24 | 68 | 0.662281 | dkozyr |
5855fef4e8b04780212d3f0d8704f88527ea70e2 | 631 | hpp | C++ | include/awl/backends/windows/wndclass.hpp | freundlich/libawl | 0d51f388a6b662373058cb51a24ef25ed826fa0f | [
"BSL-1.0"
] | null | null | null | include/awl/backends/windows/wndclass.hpp | freundlich/libawl | 0d51f388a6b662373058cb51a24ef25ed826fa0f | [
"BSL-1.0"
] | null | null | null | include/awl/backends/windows/wndclass.hpp | freundlich/libawl | 0d51f388a6b662373058cb51a24ef25ed826fa0f | [
"BSL-1.0"
] | null | null | null | #ifndef AWL_BACKENDS_WINDOWS_WNDCLASS_HPP_INCLUDED
#define AWL_BACKENDS_WINDOWS_WNDCLASS_HPP_INCLUDED
#include <awl/backends/windows/windows.hpp>
#include <awl/backends/windows/wndclass_fwd.hpp>
#include <awl/detail/symbol.hpp>
#include <fcppt/noncopyable.hpp>
#include <fcppt/string.hpp>
namespace awl
{
namespace backends
{
namespace windows
{
class wndclass
{
FCPPT_NONCOPYABLE(wndclass);
public:
AWL_DETAIL_SYMBOL
wndclass(fcppt::string const &class_name, WNDPROC);
AWL_DETAIL_SYMBOL
~wndclass();
AWL_DETAIL_SYMBOL
fcppt::string const &name() const;
private:
fcppt::string class_name_;
};
}
}
}
#endif
| 15.775 | 53 | 0.77813 | freundlich |
58567d983af56e3a411066ea32da58ec0a87c356 | 380 | hpp | C++ | include/Variable.hpp | andremmvgabriel/boolean_circuit_generator | 21a36e04072b4ce388b22992d3ca35643b967fc9 | [
"MIT"
] | 1 | 2021-09-03T14:03:28.000Z | 2021-09-03T14:03:28.000Z | include/Variable.hpp | andremmvgabriel/boolean_circuit_generator | 21a36e04072b4ce388b22992d3ca35643b967fc9 | [
"MIT"
] | null | null | null | include/Variable.hpp | andremmvgabriel/boolean_circuit_generator | 21a36e04072b4ce388b22992d3ca35643b967fc9 | [
"MIT"
] | null | null | null | #pragma once
#include <stdint.h>
#include <vector>
#include <Wire.hpp>
namespace gabe
{
namespace circuits
{
class Variable
{
public:
std::vector<Wire> wires;
uint8_t number_wires;
public:
Variable();
Variable(uint8_t n_bits);
virtual ~Variable();
};
}
}
| 14.615385 | 37 | 0.492105 | andremmvgabriel |
5856a7e58f4e14787f3910cd09f3ecabd992b495 | 2,352 | hpp | C++ | far/common/keep_alive.hpp | lidacity/FarManager | 4ff6edbd53b6652d3ab1d9ae86f66873be850209 | [
"BSD-3-Clause"
] | 1 | 2019-11-15T10:13:04.000Z | 2019-11-15T10:13:04.000Z | far/common/keep_alive.hpp | fcccode/FarManager | 5df65d2ea1fc1dca27acd439313b5347d4c9afdd | [
"BSD-3-Clause"
] | 1 | 2021-01-21T13:57:07.000Z | 2021-01-21T13:57:07.000Z | far/common/keep_alive.hpp | fcccode/FarManager | 5df65d2ea1fc1dca27acd439313b5347d4c9afdd | [
"BSD-3-Clause"
] | null | null | null | #ifndef KEEP_ALIVE_HPP_9C3E665F_56D5_4A21_9950_F1F8F6BFC7A3
#define KEEP_ALIVE_HPP_9C3E665F_56D5_4A21_9950_F1F8F6BFC7A3
#pragma once
/*
keep_alive.hpp
*/
/*
Copyright © 2018 Far Group
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
*/
//----------------------------------------------------------------------------
template<typename arg_type>
using keep_alive_type =
std::enable_if_t<std::is_reference_v<arg_type>,
std::conditional_t<
std::is_rvalue_reference_v<arg_type>,
std::remove_reference_t<arg_type>,
arg_type
>
>;
template<typename type>
class [[nodiscard]] keep_alive
{
public:
explicit keep_alive(type&& Value):
m_Value(FWD(Value))
{}
[[nodiscard]]
operator const type&() const { return m_Value; }
[[nodiscard]]
auto operator&() const { return &m_Value; }
[[nodiscard]]
auto& get() const { return m_Value; }
private:
type m_Value;
};
template<typename type>
keep_alive(type&& Value) -> keep_alive<keep_alive_type<decltype(Value)>>;
#endif // KEEP_ALIVE_HPP_9C3E665F_56D5_4A21_9950_F1F8F6BFC7A3
| 32.666667 | 78 | 0.758929 | lidacity |
5856cc332134f67cd2873a77599d9df4cbd74c5e | 529 | hpp | C++ | include/Interpreter.hpp | Electrux/alacrity-lang | 2931533c0f393cf2d2500ac0848da452fbc19295 | [
"BSD-3-Clause"
] | 15 | 2019-03-21T14:37:17.000Z | 2021-11-14T20:35:46.000Z | include/Interpreter.hpp | Electrux/alacrity-lang | 2931533c0f393cf2d2500ac0848da452fbc19295 | [
"BSD-3-Clause"
] | null | null | null | include/Interpreter.hpp | Electrux/alacrity-lang | 2931533c0f393cf2d2500ac0848da452fbc19295 | [
"BSD-3-Clause"
] | 5 | 2019-02-02T10:18:04.000Z | 2021-05-06T16:34:04.000Z | /*
Copyright (c) 2019, Electrux
All rights reserved.
Using the BSD 3-Clause license for the project,
main LICENSE file resides in project's root directory.
Please read that file and understand the license terms
before using or altering the project.
*/
#ifndef INTERPRETER_HPP
#define INTERPRETER_HPP
#include "Parser.hpp"
namespace Interpreter
{
int Interpret( const Parser::ParseTree & ps, const std::string & file_path,
const int depth = 0, const bool internal_display_enabled = true );
}
#endif // INTERPRETER_HPP | 24.045455 | 75 | 0.765595 | Electrux |
58573f1335b4829382b546f26d700970695a75c1 | 439 | cpp | C++ | Libraries/Libc/_init.cpp | vpachkov/MacaronOS | e2572761f0d73a435d5660eb88d4dc96c944a349 | [
"MIT"
] | 21 | 2021-08-22T19:06:54.000Z | 2022-03-31T12:44:30.000Z | Libraries/Libc/_init.cpp | Plunkerusr/WisteriaOS | 14f853cb8fdd6b958dd94ab24e5f19ac0268a4f6 | [
"MIT"
] | 1 | 2021-09-01T22:55:59.000Z | 2021-09-08T20:52:09.000Z | Libraries/Libc/_init.cpp | Plunkerusr/WisteriaOS | 14f853cb8fdd6b958dd94ab24e5f19ac0268a4f6 | [
"MIT"
] | null | null | null | #include <Macaronlib/Common.hpp>
extern "C" {
extern void _init();
void _init()
{
extern void (*__init_array_start[])(int, char**, char**) __attribute__((visibility("hidden")));
extern void (*__init_array_end[])(int, char**, char**) __attribute__((visibility("hidden")));
const size_t size = __init_array_end - __init_array_start;
for (size_t i = 0; i < size; i++) {
(*__init_array_start[i])(0, 0, 0);
}
}
} | 25.823529 | 99 | 0.635535 | vpachkov |
585931ff9957e4fb029299be48f167e1e318211c | 3,060 | cpp | C++ | codeforces/archived/B_Putting_Bricks_in_the_Wall.cpp | st3v3nmw/competitive-programming | 581d36c1c128e0e3ee3a0b52628e932ab43821d4 | [
"MIT"
] | null | null | null | codeforces/archived/B_Putting_Bricks_in_the_Wall.cpp | st3v3nmw/competitive-programming | 581d36c1c128e0e3ee3a0b52628e932ab43821d4 | [
"MIT"
] | null | null | null | codeforces/archived/B_Putting_Bricks_in_the_Wall.cpp | st3v3nmw/competitive-programming | 581d36c1c128e0e3ee3a0b52628e932ab43821d4 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
#define eol "\n"
#define _(x) #x << "=" << to_str(x) << ", "
#define debug(x) { ostringstream stream; stream << x; string s = stream.str(); cout << s.substr(0, s.length() - 2) << eol; }
string to_string(basic_string<char>& x) { return "\"" + x + "\""; }
string to_string(char x) { string r = ""; r += x; return "\'" + r + "\'";}
string to_string(bool x) { return x ? "true" : "false"; }
template <typename T> string to_str(T x) { return to_string(x); }
template <typename T1, typename T2> string to_str(pair<T1, T2> x) { return "(" + to_str(x.first) + ", " + to_str(x.second) + ")"; }
template <typename T> string to_str(vector<T> x) { string r = "{"; for (auto t : x) r += to_str(t) + ", "; return r.substr(0, r.length() - 2) + "}"; }
template <typename T1, typename T2> string to_str(map<T1, T2> x) { string r = "{"; for (auto t : x) r += to_str(t.first) + ": " + to_str(t.second) + ", "; return r.substr(0, r.length() - 2) + "}"; }
#define ll long long
#define ull unsigned ll
const ull MOD = 1e9 + 7;
int path_count(vector<string> v, int n, char check, int r, int c) {
v[0][0] = check;
v[n - 1][n - 1] = check;
v[r][c] = (v[r][c] == '0' ? '1' : '0');
vector<vector<int>> t(n, vector<int>(n, 0));
t[0][0] = 1;
for (int i = 1; i < n; i++) {
if (v[i][0] == check)
t[i][0] = t[i - 1][0];
}
for (int j = 1; j < n; j++) {
if (v[0][j] == check)
t[0][j] = t[0][j - 1];
}
for (int i = 1; i < n; i++) {
for (int j = 1; j < n; j++) {
if (v[i][j] == check)
t[i][j] = t[i - 1][j] + t[i][j - 1];
}
}
return t[n - 1][n - 1];
}
int main() {
ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
int g;
cin >> g;
for (int t = 0; t < g; t++) {
int n;
cin >> n;
vector<string> v(n), v2;
for (int i = 0; i < n; i++)
cin >> v[i];
vector<pair<int, int>> ans;
int paths = path_count(v, n, '0', 0, 0) + path_count(v, n, '1', 0, 0);
if (paths == 0) {
cout << 0 << eol;
continue;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if ((i == 0 && j == 0) || (i == n - 1 && j == n - 1))
continue;
int c0 = path_count(v, n, '0', i, j);
int c1 = path_count(v, n, '1', i, j);
if (c0 + c1 == 0) {
ans.push_back({i + 1, j + 1});
goto end;
} else if (paths > c0 + c1) {
ans.push_back({i + 1, j + 1});
paths = c0 + c1;
}
}
}
end:
cout << ans.size() << eol;
for (auto e : ans) {
cout << e.first << " " << e.second << eol;
v[e.first][e.second] = (v[e.first][e.second] == '0' ? '1' : '0');
}
// for (auto e : v)
// cout << e << eol;
// cout << eol;
}
} | 36.86747 | 198 | 0.418301 | st3v3nmw |
5859f9acabe99c710454e61e68802858b64fe00b | 3,296 | cpp | C++ | weatherclass.cpp | Alvee93/PhotoAnnotator | 9b330b35b59883f98eb54b3d85e858071626cbff | [
"Unlicense"
] | null | null | null | weatherclass.cpp | Alvee93/PhotoAnnotator | 9b330b35b59883f98eb54b3d85e858071626cbff | [
"Unlicense"
] | null | null | null | weatherclass.cpp | Alvee93/PhotoAnnotator | 9b330b35b59883f98eb54b3d85e858071626cbff | [
"Unlicense"
] | null | null | null | #include "weatherclass.h"
#include <QApplication>
QString api_key = "_api_key_";
WeatherClass::WeatherClass(QObject *parent) : QObject(parent)
{
}
QString WeatherClass::getWeather(double map_lat, double map_long, string p_date)
{
// This string will contain weather info
QString weather_qStr;
// Parsing date info
string convDate = convertDate(p_date);
string convDate_start = convDate.substr(0, 13);
string convDate_end = convDate.substr(13, 13);
QLoggingCategory::setFilterRules("qt.network.ssl.w arning=false");
// Create custom temporary event loop on stack
QEventLoop eventLoop_weather;
// "quit()" the event-loop, when the network request "finished()"
QNetworkAccessManager mgr_weather;
QObject::connect(&mgr_weather, SIGNAL(finished(QNetworkReply*)), &eventLoop_weather, SLOT(quit()));
// The HTTP request
QNetworkRequest req( QUrl( QString("https://api.weatherbit.io/v1.0/history/hourly?"
"lat=" + QString::number(map_lat) + "&lon=" + QString::number(map_long) +
"&start_date=" + QString::fromStdString(convDate_start) +
"&end_date=" + QString::fromStdString(convDate_end) +
"&key=" + api_key)));
QNetworkReply *reply_weather = mgr_weather.get(req);
// Blocks stack until "finished()" has been called
eventLoop_weather.exec();
if (reply_weather->error() == QNetworkReply::NoError) {
QByteArray jsonData_weather = reply_weather->readAll();
QJsonDocument document_weather = QJsonDocument::fromJson(jsonData_weather);
QJsonObject object_weather = document_weather.object();
QJsonValue value_weather = object_weather.value("data");
if(!value_weather.isNull() || value_weather != ""){
if(!value_weather.toArray().isEmpty()){
QJsonArray array_weather = value_weather.toArray();
QJsonObject object_weather2 = array_weather[0].toObject();
QJsonObject object_weather3 = object_weather2.value("weather").toObject();
weather_qStr = object_weather3.value("description").toString();
}
else {
weather_qStr = "Sorry, too early date found on image for forecasting.";
}
}
else {
weather_qStr = "Sorry, too early date found on image for forecasting.";
}
}
else {
//failure
qDebug() << "weather data fetch failure = " <<reply_weather->errorString();
weather_qStr = "N/A";
}
delete reply_weather;
return weather_qStr;
}
string WeatherClass::convertDate(string org_date)
{
string token_year, token_month, token_day, token_hour;
token_year = org_date.substr(0, 4);
token_month = org_date.substr(5, 2);
token_day = org_date.substr(8, 2);
token_hour = org_date.substr(11, 2);
string mod_date_start = token_year + "-" + token_month + "-" + token_day + ":" + token_hour;
int hour_int = stoi(token_hour);
hour_int++;
string mod_date_end = token_year + "-" + token_month + "-" + token_day + ":" + to_string(hour_int);
string mod_date = mod_date_start + mod_date_end;
return mod_date;
}
| 33.632653 | 112 | 0.635012 | Alvee93 |
5861a7b82f8784c5a5852244033e2a3c2d6f4c01 | 2,066 | cpp | C++ | IlluminoEngine/src/Illumino/Renderer/SceneRenderer.cpp | MohitSethi99/IlluminoEngine | c24efc384d538caa1b635770bfba6666cc5448a8 | [
"Apache-2.0"
] | null | null | null | IlluminoEngine/src/Illumino/Renderer/SceneRenderer.cpp | MohitSethi99/IlluminoEngine | c24efc384d538caa1b635770bfba6666cc5448a8 | [
"Apache-2.0"
] | null | null | null | IlluminoEngine/src/Illumino/Renderer/SceneRenderer.cpp | MohitSethi99/IlluminoEngine | c24efc384d538caa1b635770bfba6666cc5448a8 | [
"Apache-2.0"
] | null | null | null | #include "ipch.h"
#include "SceneRenderer.h"
#include <glm/glm.hpp>
#include <glm/gtx/transform.hpp>
#include "RenderCommand.h"
#include "Shader.h"
namespace IlluminoEngine
{
static Ref<Shader> s_Shader;
static glm::mat4 s_Projection;
std::vector<MeshData> SceneRenderer::s_Meshes;
void SceneRenderer::Init()
{
OPTICK_EVENT();
s_Shader = Shader::Create("Assets/Shaders/TestShader.hlsl",
{
{"POSITION", ShaderDataType::Float3},
{"TEXCOORD", ShaderDataType::Float2}
});
}
void SceneRenderer::Shutdown()
{
OPTICK_EVENT();
}
void SceneRenderer::BeginScene()
{
OPTICK_EVENT();
// TODO: setup camera, lights, etc data
s_Projection = glm::perspective(glm::radians(45.0f), 1920.0f / 1080.0f, 0.001f, 1000.0f);
}
void SceneRenderer::EndScene()
{
OPTICK_EVENT();
RenderPass();
}
void SceneRenderer::SubmitMesh(const Ref<MeshBuffer>& mesh, glm::mat4& transform)
{
OPTICK_EVENT();
MeshData meshData =
{
transform,
mesh
};
s_Meshes.push_back(meshData);
}
void SceneRenderer::RenderPass()
{
OPTICK_EVENT();
RenderCommand::ClearColor({ 0.042f, 0.042f, 0.042f, 1.0f });
if (s_Meshes.empty())
return;
s_Shader->Bind();
struct CB
{
glm::mat4 u_MVP;
glm::vec4 u_Color = { 1.0f, 0.0f, 0.0f, 1.0f };
};
const size_t alignedSize = ALIGN(256, sizeof(CB));
const uint32_t meshCount = s_Meshes.size();
uint64_t gpuHandle = s_Shader->CreateBuffer("Properties", alignedSize * meshCount);
size_t bufferSize = alignedSize * meshCount;
char* buffer = new char[bufferSize];
for (size_t i = 0; i < meshCount; ++i)
{
auto& meshData = s_Meshes[i];
CB cb;
cb.u_MVP = s_Projection * meshData.Transform;
memcpy(buffer + alignedSize * i, &cb, sizeof(CB));
}
s_Shader->UploadBuffer("Properties", buffer, bufferSize, 0);
delete[] buffer;
for (size_t i = 0; i < s_Meshes.size(); ++i)
{
auto& meshData = s_Meshes[i];
meshData.Mesh->Bind();
RenderCommand::DrawIndexed(meshData.Mesh, gpuHandle + alignedSize * i);
}
s_Meshes.clear();
}
}
| 19.12963 | 91 | 0.662149 | MohitSethi99 |
58623d1d6a408e522769ff0a1cacdb667f233c64 | 1,452 | cpp | C++ | gfg_DP/fibo.cpp | kbhartiya/C-Problems | 2dd0e74b44bb4678a55afcb58ed1292efa237efa | [
"Apache-2.0"
] | 1 | 2019-01-05T13:16:21.000Z | 2019-01-05T13:16:21.000Z | gfg_DP/fibo.cpp | kbhartiya/C-Problems | 2dd0e74b44bb4678a55afcb58ed1292efa237efa | [
"Apache-2.0"
] | null | null | null | gfg_DP/fibo.cpp | kbhartiya/C-Problems | 2dd0e74b44bb4678a55afcb58ed1292efa237efa | [
"Apache-2.0"
] | null | null | null | #include<bits/stdc++.h>
//#include<chrono>
using namespace std;
//using namespace std::chrono;
# define MAX 102334155
long long res[MAX+1]={-1};
long long recursive(long long n)
{
if(n==1) return 1;
if(n==0) return 0;
return recursive(n-1) + recursive(n-2);
}
long long bott_up(long long n)
{
int fib[n+1];
fib[0] = 0;
fib[1] = 1;
for(int i=2;i<=n;i++)
fib[i] = fib[i-1] + fib[i-2];
return fib[n];
}
long long top_down(long long n)
{
if(res[n]==-1)
{
if(n<=1)
res[n] = n;
else
{
res[n] = top_down(n-1) + top_down(n-2);
}
}
return res[n];
}
int main()
{
int n = 102334155;
//double start = chrono::high_resolution_clock::now();
cout<<"Recursive: "<<recursive(n)<<endl;
//double stop = chrono::high_resolution_clock::now();
//double duration = chrono::duration_cast<microseconds>(stop - start);
//cout<<"Time Taken: "<<duration.count()<<endl;
//double start = chrono::high_resolution_clock::now();
cout<<"Bottom up: "<<bott_up(n)<<endl;
//double stop = chrono::high_resolution_clock::now();
//double duration = chrono::duration_cast<microseconds>(stop - start);
//cout<<"Time Taken: "<<duration.count()<<endl;
//double start = chrono::high_resolution_clock::now();
cout<<"Top down: "<<top_down(n)<<endl;
//double stop = chrono::high_resolution_clock::now();
//double duration = chrono::duration_cast<microseconds>(stop - start);
//cout<<"Time Taken: "<<duration.count()<<endl;
return 0;
}
| 23.419355 | 71 | 0.641873 | kbhartiya |
58627161bf53585d8433038adc01695bbccc28b8 | 1,994 | hpp | C++ | Components/8530/z8530.hpp | ajacocks/CLK | 5f39938a192f976f51f54e4bbaf6d5cded03d48d | [
"MIT"
] | null | null | null | Components/8530/z8530.hpp | ajacocks/CLK | 5f39938a192f976f51f54e4bbaf6d5cded03d48d | [
"MIT"
] | null | null | null | Components/8530/z8530.hpp | ajacocks/CLK | 5f39938a192f976f51f54e4bbaf6d5cded03d48d | [
"MIT"
] | null | null | null | //
// z8530.hpp
// Clock Signal
//
// Created by Thomas Harte on 07/06/2019.
// Copyright © 2019 Thomas Harte. All rights reserved.
//
#ifndef z8530_hpp
#define z8530_hpp
#include <cstdint>
namespace Zilog {
namespace SCC {
/*!
Models the Zilog 8530 SCC, a serial adaptor.
*/
class z8530 {
public:
/*
**Interface for emulated machine.**
Notes on addressing below:
There's no inherent ordering of the two 'address' lines,
A/B and C/D, but the methods below assume:
A/B = A0
C/D = A1
*/
std::uint8_t read(int address);
void write(int address, std::uint8_t value);
void reset();
bool get_interrupt_line() const;
struct Delegate {
virtual void did_change_interrupt_status(z8530 *, bool new_status) = 0;
};
void set_delegate(Delegate *delegate) {
delegate_ = delegate;
}
/*
**Interface for serial port input.**
*/
void set_dcd(int port, bool level);
private:
class Channel {
public:
uint8_t read(bool data, uint8_t pointer);
void write(bool data, uint8_t pointer, uint8_t value);
void set_dcd(bool level);
bool get_interrupt_line() const;
private:
uint8_t data_ = 0xff;
enum class Parity {
Even, Odd, Off
} parity_ = Parity::Off;
enum class StopBits {
Synchronous, OneBit, OneAndAHalfBits, TwoBits
} stop_bits_ = StopBits::Synchronous;
enum class Sync {
Monosync, Bisync, SDLC, External
} sync_mode_ = Sync::Monosync;
int clock_rate_multiplier_ = 1;
uint8_t interrupt_mask_ = 0; // i.e. Write Register 0x1.
uint8_t external_interrupt_mask_ = 0; // i.e. Write Register 0xf.
bool external_status_interrupt_ = false;
uint8_t external_interrupt_status_ = 0;
bool dcd_ = false;
} channels_[2];
uint8_t pointer_ = 0;
uint8_t interrupt_vector_ = 0;
uint8_t master_interrupt_control_ = 0;
bool previous_interrupt_line_ = false;
void update_delegate();
Delegate *delegate_ = nullptr;
};
}
}
#endif /* z8530_hpp */
| 19.94 | 74 | 0.673521 | ajacocks |
5863cd5477845084d895724ee922c756b8c99aaa | 3,097 | cpp | C++ | src/homework/06_tic_tac_toe/tic_tac_toe_3.cpp | acc-cosc-1337-fall-2021/acc-cosc-1337-fall-2021-hopeAtACC | 52e495ed939dafc78293a4ea280ac7dcd3c24c25 | [
"MIT"
] | null | null | null | src/homework/06_tic_tac_toe/tic_tac_toe_3.cpp | acc-cosc-1337-fall-2021/acc-cosc-1337-fall-2021-hopeAtACC | 52e495ed939dafc78293a4ea280ac7dcd3c24c25 | [
"MIT"
] | null | null | null | src/homework/06_tic_tac_toe/tic_tac_toe_3.cpp | acc-cosc-1337-fall-2021/acc-cosc-1337-fall-2021-hopeAtACC | 52e495ed939dafc78293a4ea280ac7dcd3c24c25 | [
"MIT"
] | null | null | null | #include "tic_tac_toe_3.h"
using std::string; using std::vector; using std::ostream; using std::istream; using std::endl; using std::cout;
bool Tic_tac_toe_3::check_column_win()
{
for (int i = 0; i<= 8; i++)
{
if (pegs[0] == "X" && pegs[3] == "X" && pegs[6] == "X")
{
return true;
}
else if (pegs[1] == "X" && pegs[4] == "X" && pegs[7] == "X")
{
return true;
}
else if (pegs[2] == "X" && pegs[5] == "X" && pegs[8] == "X")
{
return true;
}
else if (pegs[0] == "O" && pegs[3] == "O" && pegs[6] == "O")
{
return true;
}
else if (pegs[1] == "O" && pegs[4] == "O" && pegs[7] == "O")
{
return true;
}
else if (pegs[2] == "O" && pegs[5] == "O" && pegs[8] == "O")
{
return true;
}
}
return false;
}
bool Tic_tac_toe_3::check_row_win()
{
for (int i = 0; i<= 8; i++)
{
if (pegs[0] == "X" && pegs[1] == "X" && pegs[2] == "X")
{
return true;
}
else if (pegs[3] == "X" && pegs[4] == "X" && pegs[5] == "X")
{
return true;
}
else if (pegs[6] == "X" && pegs[7] == "X" && pegs[8] == "X")
{
return true;
}
else if (pegs[0] == "O" && pegs[1] == "O" && pegs[2] == "O")
{
return true;
}
else if (pegs[3] == "O" && pegs[4] == "O" && pegs[5] == "O")
{
return true;
}
else if (pegs[6] == "O" && pegs[7] == "O" && pegs[8] == "O")
{
return true;
}
}
return false;
}
bool Tic_tac_toe_3::check_diagonal_win()
{
for (int i = 0; i<= 8; i++)
{
if (pegs[0] == "X" && pegs[4] == "X" && pegs[8] == "X")
{
return true;
}
else if (pegs[6] == "X" && pegs[4] == "X" && pegs[2] == "X")
{
return true;
}
else if (pegs[0] == "O" && pegs[4] == "O" && pegs[8] == "O")
{
return true;
}
else if (pegs[6] == "O" && pegs[4] == "O" && pegs[2] == "O")
{
return true;
}
}
return false;
}
/*
ostream& operator<<(ostream& out, const unique_ptr<Tic_tac_toe>& game) {
string board;
for (int i = 0; i <= 8; i += 3) {
board += game->pegs[i] + "|" + game->pegs[i+1] + "|" + game->pegs[i+2] + "\n";
}
out << endl << board << endl;
return out;
};
istream& operator>>(istream& in, const unique_ptr<Tic_tac_toe>& game) {
int position;
do {
cout << "Choose a board position from 1 - 9: ";
in >> position;
} while (position > 9 || position < 1);//keep asking user question if they don't provide an integer from 1-9
while (game->pegs[position - 1] != " ") {
cout << "That position has already been chosen. Please pick a new one: ";
in >> position;
}
game->mark_board(position);
return in;
};
*/
| 24.007752 | 111 | 0.399096 | acc-cosc-1337-fall-2021 |
5863d5374103c52890b7726cb33d3eaf776fcf1b | 18,267 | cpp | C++ | cli/main.cpp | svp-dev/mgsim | 0abd708f3c48723fc233f6c53f3e638129d070fa | [
"MIT"
] | 7 | 2016-03-01T13:16:59.000Z | 2021-08-20T07:41:43.000Z | cli/main.cpp | svp-dev/mgsim | 0abd708f3c48723fc233f6c53f3e638129d070fa | [
"MIT"
] | null | null | null | cli/main.cpp | svp-dev/mgsim | 0abd708f3c48723fc233f6c53f3e638129d070fa | [
"MIT"
] | 5 | 2015-04-20T14:29:38.000Z | 2018-12-29T11:09:17.000Z | #ifdef HAVE_CONFIG_H
#include <sys_config.h>
#endif
#include "simreadline.h"
#include "commands.h"
#include <arch/MGSystem.h>
#include <sim/config.h>
#include <sim/configparser.h>
#include <sim/readfile.h>
#include <sim/rusage.h>
#include <sim/sampling.h>
#include <sim/monitor.h>
#include <sstream>
#include <iostream>
#include <fstream>
#include <limits>
#include <memory>
#include <cstdlib>
#include <sys/param.h>
#include <unistd.h>
#include <argp.h>
using namespace Simulator;
using namespace std;
struct ProgramConfig
{
unsigned int m_areaTech;
string m_configFile;
bool m_enableMonitor;
bool m_interactive;
bool m_terminate;
bool m_dumpconf;
bool m_dumpcache;
bool m_quiet;
bool m_dumpvars;
vector<string> m_printvars;
bool m_earlyquit;
ConfigMap m_overrides;
vector<string> m_extradevs;
vector<string> m_regs;
bool m_dumptopo;
string m_topofile;
bool m_dumpnodeprops;
bool m_dumpedgeprops;
vector<string> m_argv;
ProgramConfig()
: m_areaTech(0),
m_configFile(MGSIM_CONFIG_PATH),
m_enableMonitor(false),
m_interactive(false),
m_terminate(false),
m_dumpconf(false),
m_dumpcache(false),
m_quiet(false),
m_dumpvars(false),
m_printvars(),
m_earlyquit(false),
m_overrides(),
m_extradevs(),
m_regs(),
m_dumptopo(false),
m_topofile(),
m_dumpnodeprops(true),
m_dumpedgeprops(true),
m_argv()
{
const char *v = getenv("MGSIM_BASE_CONFIG");
if (v != nullptr)
{
// A base file in the environment variable
// will override the default.
m_configFile = v;
}
}
};
extern "C"
{
const char *argp_program_version =
"mgsim " PACKAGE_VERSION "\n"
"Copyright (C) 2008-2015 the MGSim project.\n"
"\n"
"Written by Mike Lankamp. Maintained by the MGSim project.";
const char *argp_program_bug_address =
PACKAGE_BUGREPORT;
}
static const char *mgsim_doc =
"This program runs micro-architecture simulation models."
"\v" /* separates top and bottom part of --help generated by argp. */
"The first non-option argument is treated as a file to load as "
"a bootable ROM. All non-option arguments are also stored as strings "
"in a data ROM. For more advanced code/data arrangements, use "
"configuration options to set up ROM devices and memory ranges."
"\n\n"
"If argument -c is not specified, the base configuration file "
"is taken from environment variable MGSIM_BASE_CONFIG if set, "
"otherwise from " MGSIM_CONFIG_PATH "."
"\n\n"
"For more information, see mgsimdoc(1).";
static const struct argp_option mgsim_options[] =
{
{ "interactive", 'i', 0, 0, "Start the simulator in interactive mode.", 0 },
{ 0, 'R', "NUM VALUE", 0, "Store the integer VALUE in the specified register of the initial thread.", 1 },
{ 0, 'F', "NUM VALUE", 0, "Store the float VALUE in the specified FP register of the initial thread.", 1 },
{ 0, 'L', "NUM FILE", 0, "Create an ActiveROM component with the contents of FILE and store the address in the specified register of the initial thread.", 1 },
{ "config", 'c', "FILE", 0, "Read default configuration from FILE. "
"The contents of this file are considered after all overrides (-o/-I).", 2 },
{ "dump-configuration", 'd', 0, 0, "Dump configuration to standard error prior to program startup.", 2 },
{ "dump-config-cache", 10, 0, 0, "Dump configuration cache to standard error prior to program startup.", 2 },
{ "override", 'o', "NAME=VAL", 0, "Add override option NAME with value VAL. Can be specified multiple times.", 2 },
{ "include", 'I', "FILE", 0, "Read extra override options from FILE. Can be specified multiple times.", 2 },
{ "do-nothing", 'n', 0, 0, "Exit before the program starts, but after the system is configured.", 3 },
{ "quiet", 'q', 0, 0, "Do not print simulation statistics after execution.", 3 },
{ "terminate", 't', 0, 0, "Terminate the simulator upon an exception, instead of dropping to the interactive prompt.", 3 },
#ifdef ENABLE_CACTI
{ "area", 'a', "VAL", 0, "Dump area information prior to program startup using CACTI. Assume technology is VAL nanometers.", 4 },
#endif
{ "list-mvars", 'l', 0, 0, "Dump list of monitor variables prior to program startup.", 5 },
{ "print-final-mvars", 'p', "PATTERN", 0, "Print the value of all monitoring variables matching PATTERN. Can be specified multiple times.", 5 },
{ "dump-topology", 'T', "FILE", 0, "Dump the grid topology to FILE prior to program startup.", 6 },
{ "no-node-properties", 11, 0, 0, "Do not print component properties in the topology dump.", 6 },
{ "no-edge-properties", 12, 0, 0, "Do not print link properties in the topology output.", 6 },
{ "monitor", 'm', 0, 0, "Enable asynchronous simulation monitoring (configure with -o MonitorSampleVariables).", 7 },
{ "symtable", 's', "FILE", OPTION_HIDDEN, "(obsolete; symbols are now read automatically from ELF)", 8 },
{ 0, 0, 0, 0, 0, 0 }
};
static error_t mgsim_parse_opt(int key, char *arg, struct argp_state *state)
{
struct ProgramConfig &config = *(struct ProgramConfig*)state->input;
switch (key)
{
case 'a':
{
char* endptr;
unsigned int tech = strtoul(arg, &endptr, 0);
if (*endptr != '\0') {
throw runtime_error("Error: unable to parse technology size");
} else if (tech < 1) {
throw runtime_error("Error: technology size must be >= 1 nm");
} else {
config.m_areaTech = tech;
}
}
break;
case 'c': config.m_configFile = arg; break;
case 'i': config.m_interactive = true; break;
case 't': config.m_terminate = true; break;
case 'q': config.m_quiet = true; break;
case 's': cerr << "# Warning: ignoring obsolete flag '-s'" << endl; break;
case 'd': config.m_dumpconf = true; break;
case 10 : config.m_dumpcache = true; break;
case 'm': config.m_enableMonitor = true; break;
case 'l': config.m_dumpvars = true; break;
case 'p': config.m_printvars.push_back(arg); break;
case 'T': config.m_dumptopo = true; config.m_topofile = arg; break;
case 11 : config.m_dumpnodeprops = false; break;
case 12 : config.m_dumpedgeprops = false; break;
case 'n': config.m_earlyquit = true; break;
case 'o':
{
string sarg = arg;
string::size_type eq = sarg.find_first_of("=");
if (eq == string::npos) {
throw runtime_error("Error: malformed configuration override syntax: " + sarg);
}
string name = sarg.substr(0, eq);
config.m_overrides.append(name, sarg.substr(eq + 1));
}
break;
case 'I':
{
ConfigParser parser(config.m_overrides);
try {
parser(read_file(arg));
} catch (runtime_error& e) {
throw runtime_error("Error reading include file: " + string(arg) + "\n" + e.what());
}
}
break;
case 'L':
{
string regnum(arg);
if (state->next == state->argc) {
throw runtime_error("Error: -L" + regnum + " expected filename");
}
string filename(state->argv[state->next++]);
string devname = "rom_file" + regnum;
config.m_extradevs.push_back(devname);
string cfgprefix = devname + ":";
config.m_overrides.append(cfgprefix + "Type", "AROM");
config.m_overrides.append(cfgprefix + "ROMContentSource", "RAW");
config.m_overrides.append(cfgprefix + "ROMFileName", filename);
config.m_regs.push_back("R" + regnum + "=B" + devname);
}
break;
case 'R': case 'F':
{
string regnum;
regnum += (char)key;
regnum += arg;
if (state->next == state->argc) {
throw runtime_error("Error: -" + regnum + ": expected register value");
}
config.m_regs.push_back(regnum + "=" + state->argv[state->next++]);
}
break;
case ARGP_KEY_ARG: /* extra arguments */
{
config.m_argv.push_back(arg);
}
break;
case ARGP_KEY_NO_ARGS:
argp_usage (state);
break;
default:
return ARGP_ERR_UNKNOWN;
}
return 0;
}
static struct argp argp = {
mgsim_options /* options */,
mgsim_parse_opt /* parser */,
NULL /* args_doc */,
mgsim_doc /* doc */,
NULL /* children */,
NULL /* help filter */,
NULL /* argp domain */
};
static
void PrintFinalVariables(const Kernel& kernel, const ProgramConfig& cfg)
{
if (!cfg.m_printvars.empty())
{
cout << "### begin end-of-simulation variables" << endl;
for (auto& i : cfg.m_printvars)
kernel.GetVariableRegistry().RenderVariables(cout, i, false);
cout << "### end end-of-simulation variables" << endl;
}
}
static
void AtEnd(const MGSystem& sys, const ProgramConfig& cfg)
{
if (!cfg.m_quiet)
{
clog << "### begin end-of-simulation statistics" << endl;
sys.PrintAllStatistics(clog);
clog << "### end end-of-simulation statistics" << endl;
}
PrintFinalVariables(*sys.GetKernel(), cfg);
}
static
void MemoryExhausted()
{
ResourceUsage ru(true);
cerr << "MGSim: cannot allocate memory for C++ object (std::bad_alloc)." << endl
<< dec
<< "### error statistics" << endl
<< ru.GetUserTime() << "\t# total real time in user mode (us)" << endl
<< ru.GetSystemTime() << "\t# total real time in system mode (us)" << endl
<< ru.GetMaxResidentSize() << "\t# maximum resident set size (Kibytes)" << endl
<< "### end error statistics" << endl;
std::abort();
}
int main(int argc, char** argv)
{
std::set_new_handler(MemoryExhausted);
ProgramConfig flags;
UNIQUE_PTR<Config> config;
UNIQUE_PTR<MGSystem> sys;
UNIQUE_PTR<Monitor> mo;
////
// Early initialization.
// Argument parsing, no simulation yet.
try
{
// Parse command line arguments
argp_parse(&argp, argc, argv, 0, 0, &flags);
}
catch (const exception& e)
{
PrintException(NULL, cerr, e);
return 1;
}
if (flags.m_interactive)
{
// Interactive mode: print name & version first
clog << argp_program_version << endl
<< endl;
// Then print also command name & arguments
clog << "Command line:";
for (int i = 0; i < argc; ++i)
clog << ' ' << argv[i];
char buf[MAXPATHLEN];
getcwd(buf, MAXPATHLEN);
clog << endl << "Current working directory: " << buf << endl;
}
// Convert the remaining m_regs to an override
if (!flags.m_regs.empty())
{
ostringstream s;
for (size_t i = 0; i < flags.m_regs.size(); ++i)
{
if (i)
s << ',';
s << flags.m_regs[i];
}
flags.m_overrides.append("CmdLineRegs", s.str());
}
// Convert the extra devices created with -L to an override
if (!flags.m_extradevs.empty())
{
string n;
for (size_t i = 0; i < flags.m_extradevs.size(); ++i)
{
if (i > 0)
n += ',';
n += flags.m_extradevs[i];
}
flags.m_overrides.append("CmdLineFileDevs", n);
}
if (flags.m_quiet)
{
// Silence the ROM loads.
flags.m_overrides.append("*.ROMVerboseLoad", "false");
}
////
// Load the simulation configuration.
// Process -c, group with overrides and argv.
try
{
// Read configuration from file
ConfigMap base_config;
ConfigParser parser(base_config);
try {
parser(read_file(flags.m_configFile));
} catch (runtime_error& e) {
throw runtime_error("Error reading configuration file: " + flags.m_configFile + "\n" + e.what());
}
config.reset(new Config(base_config, flags.m_overrides, flags.m_argv));
}
catch (const exception& e)
{
PrintException(NULL, cerr, e);
return 1;
}
////
// Initialize the random seed.
// We place it in the configuration, so that dumpConfiguration below
// can print it too (for reproducability).
try
{
(void)config->getValue<string>("RandomSeed");
}
catch (const exception& e)
{
// Not in configuration(yet)
char s[20];
snprintf(s, 20, "%u", (unsigned)time(NULL));
config->GetOverrides().append("RandomSeed", s);
}
{
unsigned seed = config->getValue<unsigned>("RandomSeed");
clog << "### random seed: " << seed << endl;
srand(seed);
}
if (flags.m_dumpconf)
{
// Printing the configuration if requested. We need to
// do/check this early, in case constructing the system
// (below) fails.
clog << "### simulator version: " PACKAGE_VERSION << endl;
config->dumpConfiguration(clog, flags.m_configFile);
}
////
// Construct the simulator.
// This instantiates all the components, in the initial (stopped) state.
// It also populates the "config" object with a cache of all
// values effectively looked up by the instantiated components.
try
{
// Create the system
sys.reset(new MGSystem(*config, !flags.m_interactive));
}
catch (const exception& e)
{
PrintException(NULL, cerr, e);
return 1;
}
if (flags.m_dumpcache)
{
// Dump the configuration cache if requested.
config->dumpConfigurationCache(clog);
}
if (flags.m_dumpvars)
{
// Dump the list of monitoring variables if requested.
clog << "### begin monitor variables" << endl;
sys->GetKernel()->GetVariableRegistry().ListVariables(clog);
clog << "### end monitor variables" << endl;
}
if (flags.m_areaTech > 0)
{
// Dump the area estimation information if requested.
clog << "### begin area information" << endl;
#ifdef ENABLE_CACTI
sys->DumpArea(cout, flags.m_areaTech);
#else
clog << "# Warning: CACTI not enabled; reconfigure with --enable-cacti" << endl;
#endif
clog << "### end area information" << endl;
}
if (flags.m_dumptopo)
{
// Dump the component topology diagram if requested.
ofstream of(flags.m_topofile.c_str(), ios::out);
config->dumpComponentGraph(of, flags.m_dumpnodeprops, flags.m_dumpedgeprops);
of.close();
}
if (flags.m_earlyquit)
// At this point the simulation is ready and we have dumped
// everything requested. If the user requested to not do anything,
// we can just stop here.
return 0;
// Otherwise, the simulation should start.
////
// Start the simulation.
// First construct the monitor thread, if enabled.
string mo_mdfile = config->getValueOrDefault<string>("MonitorMetadataFile", "mgtrace.md");
string mo_tfile = config->getValueOrDefault<string>("MonitorTraceFile", "mgtrace.out");
mo.reset(new Monitor(*sys, flags.m_enableMonitor,
mo_mdfile, flags.m_earlyquit ? "" : mo_tfile, !flags.m_interactive));
// Simulation proper.
// Rules:
// - if interactive, then do not automatically start the simulation.
// - if interactive at start, always remain interactive.
// - if not interactive at start and the simulation stops abnormally, then become interactive unless -t is specified.
// - upon becoming interative because of an exception, print the exception.
// - always print statistics at termination if not quiet.
// - always print final variables at termination.
bool interactive = flags.m_interactive;
try
{
if (!interactive)
{
// Non-interactive: automatically start and run until simulation terminates.
try
{
mo->start();
StepSystem(*sys, INFINITE_CYCLES);
mo->stop();
}
catch (const exception& e)
{
mo->stop();
if (flags.m_terminate)
{
// Re-throw to terminate.
throw;
}
// else
// Print the exception and become interactive.
PrintException(sys.get(), cerr, e);
interactive = true;
}
}
if (interactive)
{
// Command loop
cout << endl;
CommandLineReader clr;
cli_context ctx = { clr, *sys, *mo };
while (HandleCommandLine(ctx) == false)
/* just loop */;
}
}
catch (const exception& e)
{
const ProgramTerminationException *ex = dynamic_cast<const ProgramTerminationException*>(&e);
if (!flags.m_quiet || ex == NULL)
// Print exception.
PrintException(sys.get(), cerr, e);
// Print statistics & final variables.
AtEnd(*sys, flags);
sys.reset(nullptr);
if (ex != NULL)
{
// The program is telling us how to terminate. Do it.
if (ex->TerminateWithAbort())
abort();
else
return ex->GetExitCode();
}
else
// No more information, simply terminate with error.
return 1;
}
// Print statistics & final variables.
AtEnd(*sys, flags);
sys.reset(nullptr);
return 0;
}
| 32.503559 | 163 | 0.573384 | svp-dev |
586be7c392c580a6d34c2613e9365e021c6fcc7b | 3,035 | hpp | C++ | beaker/value.hpp | thehexia/beaker2 | ca6c563c51be4a08d78e4eda007967bc4ae812a2 | [
"Apache-2.0"
] | null | null | null | beaker/value.hpp | thehexia/beaker2 | ca6c563c51be4a08d78e4eda007967bc4ae812a2 | [
"Apache-2.0"
] | null | null | null | beaker/value.hpp | thehexia/beaker2 | ca6c563c51be4a08d78e4eda007967bc4ae812a2 | [
"Apache-2.0"
] | null | null | null | // Copyright (c) 2015 Andrew Sutton
// All rights reserved
#ifndef BEAKER_VALUE_HPP
#define BEAKER_VALUE_HPP
// The value module represents compile-time or
// interpreted values.
//
// TODO: Make a visitor for values.
#include "prelude.hpp"
struct Value;
enum Value_kind
{
error_value,
integer_value,
function_value,
reference_value,
};
using Integer_value = int;
using Function_value = Function_decl const*;
using Reference_value = Value*;
union Value_rep
{
Value_rep() = default;
Value_rep(Integer_value z) : int_(z) { }
Value_rep(Function_value f) : fn_(f) { }
Value_rep(Reference_value r) : ref_(r) { }
Integer_value int_;
Function_value fn_;
Reference_value ref_;
};
// Represents a compile time value.
struct Value
{
Value()
: k(error_value), r()
{ }
Value(Integer_value n)
: k(integer_value), r(n)
{ }
Value(Function_value f)
: k(function_value), r(f)
{ }
Value(Value* v);
Value_kind kind() const { return k; }
inline bool is_integer() const;
inline bool is_function() const;
inline bool is_reference() const;
Integer_value get_integer() const;
Function_value get_function() const;
Reference_value get_reference() const;
Value_kind k;
Value_rep r;
};
// Construct a value reference. Not that reference
// chains are not permitted. That is, v shall not
// be a reference.
inline
Value::Value(Value* v)
: k(reference_value), r(v)
{
assert(!v->is_reference());
}
// Returns true if the value is an integer or
// a reference to an integer.
inline bool
Value::is_integer() const
{
if (k == integer_value)
return true;
if (k == reference_value && r.ref_->k == integer_value)
return true;
return false;
}
// Returns true if the value is a function or a
// reference to a function.
inline bool
Value::is_function() const
{
if (k == function_value)
return true;
if (k == reference_value && r.ref_->k == function_value)
return true;
return false;
}
// Returns true if k is a reference.
inline bool
Value::is_reference() const
{
return k == reference_value;
}
// Retrieve the integer value. If the value is
// a reference to an integer, then return the
// dereferenced value.
inline Integer_value
Value::get_integer() const
{
if (k == reference_value)
return r.ref_->get_integer();
assert(k == integer_value);
return r.int_;
}
// Retrieve a function value. If the value is
// a reference to a function, then return the
// dereferenced value.
inline Function_value
Value::get_function() const
{
if (k == reference_value)
return r.ref_->get_function();
assert(k == function_value);
return r.fn_;
}
// Get the reference value. Note that this
// does not "unwind" the references since
// references to references are not permitted.
inline Reference_value
Value::get_reference() const
{
assert(k == reference_value);
return r.ref_;
}
// A sequence of values.
using Value_seq = std::vector<Value>;
// Streaming
std::ostream& operator<<(std::ostream& os, Value const&);
#endif
| 18.065476 | 58 | 0.695222 | thehexia |
5878daeeba6873f8bb34bb4ba1ce0ba70faf2643 | 6,483 | hpp | C++ | include/autotune/continuous_parameter.hpp | DavidPfander-UniStuttgart/AutoTuneTMP | f5fb836778b04c2ab0fbcc4d36c466e577e96e65 | [
"BSD-3-Clause"
] | 5 | 2019-11-06T15:02:41.000Z | 2022-01-14T20:25:50.000Z | include/autotune/continuous_parameter.hpp | DavidPfander-UniStuttgart/AutoTuneTMP | f5fb836778b04c2ab0fbcc4d36c466e577e96e65 | [
"BSD-3-Clause"
] | 3 | 2018-01-25T21:25:22.000Z | 2022-03-14T17:35:27.000Z | include/autotune/continuous_parameter.hpp | DavidPfander-UniStuttgart/AutoTuneTMP | f5fb836778b04c2ab0fbcc4d36c466e577e96e65 | [
"BSD-3-Clause"
] | 1 | 2020-07-15T11:05:43.000Z | 2020-07-15T11:05:43.000Z | #pragma once
#include "autotune_exception.hpp"
#include "util.hpp"
#include <cmath>
#include <functional>
#include <iomanip>
namespace autotune {
class stepable_continuous_parameter {
protected:
std::string name;
double initial;
double current;
double step;
bool multiply;
// std::function<double(double, double)> next_functional;
// std::function<double(double, double)> prev_functional;
public:
stepable_continuous_parameter(const std::string &name, double initial,
double step, bool multiply = false)
: name(name), initial(initial), current(initial), step(step),
multiply(multiply) {
if (multiply) {
initial = initial / step; // step is factor for multiply
current = initial;
}
}
const std::string &get_name() const { return this->name; }
const std::string get_value() const {
if (multiply) {
return detail::truncate_trailing_zeros(current * step);
} else {
return detail::truncate_trailing_zeros(current);
}
}
double get_raw_value() const {
if (multiply) {
return current * step;
} else {
return current;
}
}
void set_initial() {
// TODO: should be extended, so that an initial guess can be supplied
if (multiply) {
current = initial / step;
} else {
current = initial;
}
}
bool next() {
if (multiply) {
current += 1;
} else {
current += step;
}
return true;
}
bool prev() {
if (multiply) {
current -= 1;
} else {
current -= step;
}
return true;
}
void to_nearest_valid(double factor) {
if (!multiply) {
current = autotune::detail::round_to_nearest(current, factor);
} else {
current =
autotune::detail::round_to_nearest(current * step, factor) / step;
}
}
double get_step() { return step; }
};
class countable_continuous_parameter : public stepable_continuous_parameter {
private:
double min;
double max;
size_t value_range;
public:
countable_continuous_parameter(const std::string &name, double initial,
double step, double min, double max,
bool multiply = false)
: stepable_continuous_parameter(name, initial, step, multiply), min(min),
max(max), value_range(1) {
set_min();
while (next()) {
value_range += 1;
}
set_initial();
}
bool next() {
if (multiply) {
if ((current + 1.0) * step > max) {
return false;
}
} else {
if (current + step > max) {
return false;
}
}
return stepable_continuous_parameter::next();
}
bool prev() {
if (multiply) {
if ((current - 1.0) * step < min) {
return false;
}
} else {
if (current - step < min) {
return false;
}
}
return stepable_continuous_parameter::prev();
}
void set_min() {
if (multiply) {
this->current = min / step;
} else {
this->current = min;
}
}
void set_max() {
if (multiply) {
this->current = max / step;
} else {
this->current = max;
}
}
double get_min() const { return min; }
double get_max() const { return max; }
size_t count_values() const { return value_range; }
void set_random_value() {
size_t num_values = count_values();
auto random_gen = detail::make_uniform_int_generator(0ul, num_values - 1ul);
size_t value_index = random_gen();
set_min();
for (size_t i = 0; i < value_index; i += 1) {
next();
}
}
void set_value_unsafe(const std::string &v) {
if (multiply) {
current = std::stod(v) / step;
} else {
current = std::stod(v);
}
}
void to_nearest_valid(double factor) {
if (!multiply) {
current =
autotune::detail::round_to_nearest_bounded(current, factor, min, max);
} else {
current = autotune::detail::round_to_nearest_bounded(current * step,
factor, min, max) /
step;
}
}
void to_nearest_valid_nonzero(double factor) {
if (!multiply) {
current = autotune::detail::round_to_nearest_nonzero(current, factor);
} else {
current =
autotune::detail::round_to_nearest_nonzero(current * step, factor) /
step;
}
}
};
class limited_continuous_parameter {
private:
std::string name;
double initial;
double current;
double min;
double max;
bool integer_parameter;
public:
limited_continuous_parameter(const std::string &name, double initial,
double min, double max,
bool integer_parameter = false)
: name(name), initial(initial), current(initial), min(min), max(max),
integer_parameter(integer_parameter) {}
const std::string &get_name() const { return this->name; }
const std::string get_value() const {
return detail::truncate_trailing_zeros(current);
}
double get_raw_value() const { return current; }
void set_min() { current = min; }
void set_max() { current = max; }
double get_min() const { return min; }
double get_max() const { return max; }
void set_initial() {
// TODO: should be extended, so that an initial guess can be supplied
current = initial;
}
bool set_value(double new_value) {
if (new_value < min || new_value > max) {
return false;
}
if (integer_parameter && (new_value != std::trunc(new_value))) {
return false;
}
current = new_value;
return true;
}
bool is_integer_parameter() const { return integer_parameter; }
void set_random_value() {
if (this->is_integer_parameter()) {
// randomize index
std::uniform_int_distribution<size_t> distribution(
static_cast<size_t>(min), static_cast<size_t>(max));
std::random_device rd;
std::default_random_engine generator(rd());
current = distribution(generator);
} else {
std::uniform_real_distribution<double> distribution(min, max);
std::random_device rd;
std::default_random_engine generator(rd());
current = distribution(generator);
}
}
void set_value_unsafe(const std::string &v) { current = std::stod(v); }
void to_nearest_valid(double factor) {
current =
autotune::detail::round_to_nearest_bounded(current, factor, min, max);
}
};
} // namespace autotune
| 23.834559 | 80 | 0.603424 | DavidPfander-UniStuttgart |
587a791edcedde92a23e91c10620ac6b6ef4c407 | 12,134 | cpp | C++ | src/nescore/apu_tnd.cpp | BenWenger/Schpune | 723e0bae8cac846c2bcbc9c1fb4f4a9fd1191a23 | [
"MIT"
] | 2 | 2018-11-11T03:49:47.000Z | 2019-05-22T09:34:20.000Z | src/nescore/apu_tnd.cpp | BenWenger/Schpune | 723e0bae8cac846c2bcbc9c1fb4f4a9fd1191a23 | [
"MIT"
] | null | null | null | src/nescore/apu_tnd.cpp | BenWenger/Schpune | 723e0bae8cac846c2bcbc9c1fb4f4a9fd1191a23 | [
"MIT"
] | null | null | null |
#include "apu_tnd.h"
#include "cpubus.h"
#include "resetinfo.h"
#include "dmaunit.h"
#include "eventmanager.h"
#include "apu.h"
#include <algorithm>
namespace schcore
{
const u16 Apu_Tnd::noiseFreqLut[2][0x10] = {
{ 4, 8, 16, 32, 64, 96, 128, 160, 202, 254, 380, 508, 762, 1016, 2034, 4068 }, // NTSC
{ 4, 8, 14, 30, 60, 88, 118, 148, 188, 236, 354, 472, 708, 944, 1890, 3778 } // PAL
};
const int Apu_Tnd::dmcFreqLut[2][0x10] = {
{ 428, 380, 340, 320, 286, 254, 226, 214, 190, 160, 142, 128, 106, 84, 72, 54 }, // NTSC
{ 398, 354, 316, 298, 276, 236, 210, 198, 176, 148, 132, 118, 98, 78, 66, 50 } // PAL
};
void Apu_Tnd::makeSilent()
{
tri.length.writeEnable(0);
nse.length.writeEnable(0);
dmcpu.len = dmcaud.len = 0;
}
void Apu_Tnd::writeMain(u16 a, u8 v)
{
switch(a)
{
//////////////////////////////////
// Tri
case 0x4008:
tri.linear.writeLoad(v);
tri.length.writeHalt(v & 0x80);
break;
case 0x400A:
tri.freqTimer = (tri.freqTimer & 0x0700) | v;
break;
case 0x400B:
tri.freqTimer = (tri.freqTimer & 0x00FF) | ((v & 0x07) << 8);
tri.length.writeLoad(v);
tri.linear.writeHigh();
break;
//////////////////////////////////
// Noise
case 0x400C:
nse.length.writeHalt(v & 0x20);
nse.decay.write(v);
break;
case 0x400E:
nse.shiftMode = (v & 0x80) ? 9 : 14;
nse.freqTimer = noiseFreqLut[region][v & 0x0F];
break;
case 0x400F:
nse.length.writeLoad(v);
nse.decay.writeHigh();
break;
//////////////////////////////////
// DMC
case 0x4010:
dmcIrqEnabled = (v & 0x80) != 0;
if(!dmcIrqEnabled && dmcIrqPending)
{
dmcIrqPending = false;
cpuBus->acknowledgeIrq(dmcIrqBit);
}
dmcLoop = (v & 0x40) != 0;
dmcFreqTimer = dmcFreqLut[region][v & 0x0F];
predictNextEvent(); // time of next fetch may have changed, predict next event
break;
case 0x4011:
dmcOut = v & 0x7F;
break;
case 0x4012:
dmcAddrLoad = 0xC000 | (v << 6);
break;
case 0x4013:
dmcLenLoad = (v << 4) + 1;
break;
}
}
void Apu_Tnd::write4015(u8 v)
{
tri.length.writeEnable(v & 0x04);
nse.length.writeEnable(v & 0x08);
if(dmcIrqPending)
{
dmcIrqPending = false;
cpuBus->acknowledgeIrq( dmcIrqBit );
}
if(v & 0x10)
{
if(!dmcpu.len)
{
// start a new clip
// if dmcaud is completely silent, sync with dmcpu
tryToSyncDmc();
startDmcClip(dmcpu);
startDmcClip(dmcaud);
doDmcFetch(dmcpu,true);
doDmcFetch(dmcaud,false);
predictNextEvent(); // length became nonzero, predict next event
}
}
else
{
dmcpu.len = dmcaud.len = 0;
}
}
inline void Apu_Tnd::tryToSyncDmc()
{
// only sync if the dmcaud is totally silent
if(dmcaud.audible) return;
if(dmcPeekSampleBuffer.willBeAudible()) return;
if(dmcaud.len) return;
// OK to sync!
dmcaud.freqCounter = dmcpu.freqCounter;
dmcaud.bitsRemaining = dmcpu.bitsRemaining;
}
inline void Apu_Tnd::startDmcClip(DmcData& dat)
{
dat.len = dmcLenLoad;
dat.addr = dmcAddrLoad;
}
inline void Apu_Tnd::doDmcFetch(DmcData& dat, bool isdmcpu)
{
if(!dat.len) return;
dat.supplier->triggerFetch( dat.addr );
dat.addr = (dat.addr + 1) | 0x8000;
if(!--dat.len)
{
if(dmcLoop)
startDmcClip(dat);
else if(isdmcpu && dmcIrqEnabled)
{
dmcIrqPending = true;
cpuBus->triggerIrq(dmcIrqBit);
}
}
}
void Apu_Tnd::read4015(u8& v)
{
if(tri.length.isAudible()) v |= 0x04;
if(nse.length.isAudible()) v |= 0x08;
if(dmcpu.len) v |= 0x10;
if(dmcIrqPending) v |= 0x80;
}
void Apu_Tnd::reset(const ResetInfo& info)
{
if(info.hardReset)
{
channelHardReset();
region = (info.region.apuTables == RegionInfo::ApuTables::pal);
tri.length.hardReset();
tri.linear.hardReset();
tri.freqCounter = tri.freqTimer = 0x07FF;
tri.triStep = 0;
nse.decay.hardReset();
nse.length.hardReset();
nse.freqTimer = nse.freqTimer = noiseFreqLut[region][0x0F];
nse.shiftMode = 14;
nse.shifter = 1;
dmcPeekSampleBuffer.reset(info);
cpuBus = info.cpuBus;
eventManager = info.eventManager;
apuHost = info.apu;
dmcOut = 0;
dmcFreqTimer = dmcFreqLut[region][0];
dmcAddrLoad = 0xC000;
dmcLenLoad = 0x0FF1;
dmcIrqPending = false;
dmcIrqEnabled = false;
dmcIrqBit = cpuBus->createIrqCode("DMC");
dmcLoop = false;
dmcpu .supplier = info.dmaUnit;
dmcaud.supplier = &dmcPeekSampleBuffer;
dmcpu.freqCounter = dmcaud.freqCounter = dmcFreqTimer;
dmcpu.addr = dmcaud.addr = dmcAddrLoad;
dmcpu.len = dmcaud.len = 0;
dmcpu.outputUnit = dmcaud.outputUnit = 0;
dmcpu.bitsRemaining = dmcaud.bitsRemaining = 8;
dmcpu.audible = dmcaud.audible = false;
}
else
{
tri.length.writeEnable(0);
nse.length.writeEnable(0);
dmcpu.len = 0;
dmcaud.len = 0;
// flush audible DMC buffers
dmcaud.audible = false;
u8 t;
bool b;
dmcaud.supplier->getFetchedByte(t,b);
}
}
void Apu_Tnd::clockSeqHalf()
{
tri.length.clock();
nse.length.clock();
}
void Apu_Tnd::clockSeqQuarter()
{
tri.linear.clock();
nse.decay.clock();
}
timestamp_t Apu_Tnd::clocksToNextUpdate()
{
timestamp_t out = Time::Never;
if(tri.length.isAudible() && tri.linear.isAudible()) out = std::min( out, tri.freqCounter );
if(nse.length.isAudible() && nse.decay.getOutput()) out = std::min( out, nse.freqCounter );
if(dmcaud.audible || dmcPeekSampleBuffer.willBeAudible()) out = std::min( out, dmcaud.freqCounter );
return out;
}
int Apu_Tnd::doTicks(timestamp_t ticks, bool doaudio, bool docpu)
{
if(docpu) runDmc(dmcpu, ticks, true);
if(!doaudio) return 0;
int out;
////////////////////////
// triangle
tri.freqCounter -= ticks;
while(tri.freqCounter <= 0)
{
tri.freqCounter += tri.freqTimer + 1;
if(tri.length.isAudible() && tri.linear.isAudible())
tri.triStep = (tri.triStep + 1) & 0x1F;
}
if(tri.triStep & 0x10) out = tri.triStep ^ 0x1F;
else out = tri.triStep;
////////////////////////
// noise
nse.freqCounter -= ticks;
while(nse.freqCounter <= 0)
{
nse.freqCounter += nse.freqTimer;
nse.shifter |= 0x8000 & ( (nse.shifter << 15) ^ (nse.shifter << nse.shiftMode) );
nse.shifter >>= 1;
}
if(nse.length.isAudible() && !(nse.shifter & 0x0001))
out |= nse.decay.getOutput() << 4;
////////////////////////
// DMC
runDmc(dmcaud, ticks, false);
out |= dmcOut << 8;
return out;
}
void Apu_Tnd::runDmc(DmcData& dat, timestamp_t ticks, bool isdmcpu)
{
dat.freqCounter -= ticks;
while(dat.freqCounter <= 0)
{
dat.freqCounter += dmcFreqTimer;
--dat.bitsRemaining;
if(!isdmcpu && dat.audible)
{
if(dat.outputUnit & 0x01) { if(dmcOut < 0x7E) dmcOut += 2; }
else { if(dmcOut > 1) dmcOut -= 2; }
}
dat.outputUnit >>= 1;
if(!dat.bitsRemaining)
{
dat.bitsRemaining = 8;
dat.supplier->getFetchedByte( dat.outputUnit, dat.audible );
doDmcFetch( dat, isdmcpu );
if(isdmcpu)
predictNextEvent();
}
}
}
void Apu_Tnd::predictNextEvent()
{
//////////////////////////////////////////
// DMC has 2 noteworthy events: DMA cycle stealing, and DMC IRQ
//
// fortunately, the IRQ is performed at the same time as the cycle stealing (it happens when the last
// sample byte is fetched), therefore we only need to report the cycle stealing event.
// cycle stealing will happen only if the dmcpu has a nonzero length
if(!dmcpu.len) return;
// next stolen cycle will happen when all remaining bits get shifted out
timestamp_t ticks = dmcpu.freqCounter;
if(dmcpu.bitsRemaining > 1)
ticks += dmcFreqTimer * (dmcpu.bitsRemaining-1);
// scale that up to an actual timestamp
ticks *= apuHost->getClockBase();
ticks += apuHost->curCyc();
eventManager->addEvent( ticks, EventType::evt_apu );
}
void Apu_Tnd::recalcOutputLevels(const AudioSettings& settings, ChannelId chanid, std::vector<float> (&levels)[2])
{
levels[0].resize(0x8000);
levels[1].resize(0x8000);
/*
159.79
tnd_out = -------------------------------------------------------------
1
----------------------------------------------------- + 100
(triangle / 8227) + (noise / 12241) + (dmc / 22638)
*/
float mvol = static_cast<float>( settings.masterVol * baseNativeOutputLevel );
auto tri = getVolMultipliers( settings, ChannelId::triangle );
auto nse = getVolMultipliers( settings, ChannelId::noise );
auto dmc = getVolMultipliers( settings, ChannelId::dmc );
float t;
for(int i = 0; i < 0x8000; ++i)
{
// L
t = (i & 0x000F) * tri.first / 8227;
t += ((i & 0x00F0) >> 4) * nse.first / 12241;
t += ( i >> 8 ) * dmc.first / 22638;
if(t != 0)
{
t = 1 / t;
t += 100;
t = 159.79f / t;
t *= mvol;
}
levels[0][i] = t;
// R
t = (i & 0x000F) * tri.second / 8227;
t += ((i & 0x00F0) >> 4) * nse.second / 12241;
t += ( i >> 8 ) * dmc.second / 22638;
if(t != 0)
{
t = 1 / t;
t += 100;
t = 159.79f / t;
t *= mvol;
}
levels[1][i] = t;
}
}
} | 30.796954 | 118 | 0.449563 | BenWenger |
587add24c3c19686ff638d4ae70d2d9abab23d44 | 3,735 | cpp | C++ | source/main.cpp | suVrik/aabbox_benchmark | f83a838c9342a0fc684d4bb978f6c1b76a6c487f | [
"MIT"
] | null | null | null | source/main.cpp | suVrik/aabbox_benchmark | f83a838c9342a0fc684d4bb978f6c1b76a6c487f | [
"MIT"
] | null | null | null | source/main.cpp | suVrik/aabbox_benchmark | f83a838c9342a0fc684d4bb978f6c1b76a6c487f | [
"MIT"
] | null | null | null | #include "shared.h"
#include <chrono>
#include <cstdlib>
#include <iomanip>
#include <iostream>
constexpr size_t TEST_COUNT = 10000000;
int main(int argc, char* argv[]) {
//
// Generate data.
//
float4 float3_data[8192];
aabbox aabbox_data[4096];
for (float4& value : float3_data) {
value.x = static_cast<float>(rand()) / RAND_MAX;
value.y = static_cast<float>(rand()) / RAND_MAX;
value.z = static_cast<float>(rand()) / RAND_MAX;
}
for (aabbox& value : aabbox_data) {
#ifdef USE_MINMAX
value.min.x = static_cast<float>(rand()) / RAND_MAX;
value.min.y = static_cast<float>(rand()) / RAND_MAX;
value.min.z = static_cast<float>(rand()) / RAND_MAX;
value.max.x = static_cast<float>(rand()) / RAND_MAX;
value.max.y = static_cast<float>(rand()) / RAND_MAX;
value.max.z = static_cast<float>(rand()) / RAND_MAX;
#else
value.center.x = static_cast<float>(rand()) / RAND_MAX;
value.center.y = static_cast<float>(rand()) / RAND_MAX;
value.center.z = static_cast<float>(rand()) / RAND_MAX;
value.extent.x = static_cast<float>(rand()) / RAND_MAX;
value.extent.y = static_cast<float>(rand()) / RAND_MAX;
value.extent.z = static_cast<float>(rand()) / RAND_MAX;
#endif
}
//
// operator+(float4)
//
auto t1 = std::chrono::high_resolution_clock::now();
for (size_t i = 0; i < TEST_COUNT; i++) {
size_t float3_idx = i & 8191;
size_t aabbox_idx = i & 4095;
aabbox result = aabbox_data[aabbox_idx] + float3_data[float3_idx];
consume_result(result);
}
auto t2 = std::chrono::high_resolution_clock::now();
//
// operator+(aabbox)
//
auto t3 = std::chrono::high_resolution_clock::now();
for (size_t i = 0, j = 1337; i < TEST_COUNT; i++, j++) {
size_t aabbox_lhs_idx = i & 4095;
size_t aabbox_rhs_idx = j & 4095;
aabbox result = aabbox_data[aabbox_lhs_idx] + aabbox_data[aabbox_rhs_idx];
consume_result(result);
}
auto t4 = std::chrono::high_resolution_clock::now();
//
// intersect(float4)
//
auto t5 = std::chrono::high_resolution_clock::now();
for (size_t i = 0; i < TEST_COUNT; i++) {
size_t float3_idx = i & 8191;
size_t aabbox_idx = i & 4095;
bool result = intersect(float3_data[float3_idx], aabbox_data[aabbox_idx]);
consume_result(result);
}
auto t6 = std::chrono::high_resolution_clock::now();
//
// intersect(aabbox)
//
auto t7 = std::chrono::high_resolution_clock::now();
for (size_t i = 0, j = 1337; i < TEST_COUNT; i++, j++) {
size_t aabbox_lhs_idx = i & 4095;
size_t aabbox_rhs_idx = j & 4095;
bool result = intersect(aabbox_data[aabbox_lhs_idx], aabbox_data[aabbox_rhs_idx]);
consume_result(result);
}
auto t8 = std::chrono::high_resolution_clock::now();
//
// Print results.
//
long long t12 = std::chrono::duration_cast<std::chrono::nanoseconds>(t2 - t1).count();
long long t34 = std::chrono::duration_cast<std::chrono::nanoseconds>(t4 - t3).count();
long long t56 = std::chrono::duration_cast<std::chrono::nanoseconds>(t6 - t5).count();
long long t78 = std::chrono::duration_cast<std::chrono::nanoseconds>(t8 - t7).count();
std::cout << "operator+(float4): " << std::setw(10) << t12 << "ns" << std::endl;
std::cout << "operator+(aabbox): " << std::setw(10) << t34 << "ns" << std::endl;
std::cout << "intersect(float4): " << std::setw(10) << t56 << "ns" << std::endl;
std::cout << "intersect(aabbox): " << std::setw(10) << t78 << "ns" << std::endl;
return 0;
}
| 29.642857 | 90 | 0.599197 | suVrik |
587fbc1bf055b7d1476cfc9b6a5ba6a03173d7dd | 11,857 | hpp | C++ | statistics.hpp | 25077667/statistics_BM_NSYSU | 2c6c462727d9bf4bcff5844e785fd165a82c5a2d | [
"MIT"
] | null | null | null | statistics.hpp | 25077667/statistics_BM_NSYSU | 2c6c462727d9bf4bcff5844e785fd165a82c5a2d | [
"MIT"
] | null | null | null | statistics.hpp | 25077667/statistics_BM_NSYSU | 2c6c462727d9bf4bcff5844e785fd165a82c5a2d | [
"MIT"
] | null | null | null | #include <boost/math/distributions/normal.hpp>
#include <boost/math/distributions/students_t.hpp>
#include <cmath>
#include <fstream>
#include <iostream>
#include <map>
#include <utility>
#include <vector>
// this header for all except for ch8
// MIT LICENSE
#ifndef STATISTICS_HPP
#define STATISTICS_HPP
using namespace std;
#define yes true
#define no false
double genPValue(double z_value, bool isTwoTail = false, bool tailInvertSign = false) {
// need to add two tail test!
// add bool isTwotail = false
// this is the conjugate function of genZValue
boost::math::normal Ndistribution(0, 1);
auto P = boost::math::cdf(boost::math::complement(Ndistribution, fabs(z_value)));
if (isTwoTail && tailInvertSign)
throw "error range";
if (tailInvertSign)
P = 1 - P;
if (isTwoTail)
P *= 2;
return P;
}
double genPValue(double degree, double t_value, bool isTwoTail = false, bool tailInvertSign = false) {
// this is the conjugate function of genTValue
// @degree: the degree of freedom
boost::math::students_t Tdistribution(degree);
auto P = boost::math::cdf(boost::math::complement(Tdistribution, fabs(t_value)));
if (isTwoTail && tailInvertSign)
throw "error range";
if (tailInvertSign)
P = 1 - P;
if (isTwoTail)
P *= 2;
return P;
}
double genZValue(double subscript, bool isSingleTail) {
/*
* @subscript: the score below the "z", which means the cumulative distribution function of the area.
* if subscript is negative meaning it is left tail, possitive otherwise
* @isSingleTail: is only sigle tail of the reject area
* return the z-score which lookup from the z-table
*/
boost::math::normal Ndistribution(0, 1);
if (!isSingleTail)
subscript /= 2;
auto Z = boost::math::quantile(boost::math::complement(Ndistribution, fabs(subscript)));
if (subscript < 0)
Z = -Z;
return Z;
}
double genTValue(int degree, double upperTailArea) {
boost::math::students_t Tdistribution(degree);
auto T = boost::math::quantile(boost::math::complement(Tdistribution, upperTailArea));
return T;
}
template <typename Iteratable>
double genMean(Iteratable& _dataSet) {
double sum = 0;
for (auto i : _dataSet)
sum += i;
return sum / _dataSet.size();
}
template <typename Iteratable>
double genSampleStandardDeviation(Iteratable& _dataSet, double sampleMean, double size) {
double sxx = 0;
for (auto i : _dataSet)
sxx += (i - sampleMean) * (i - sampleMean);
return sqrt(1 / (size - 1) * sxx);
}
double genPercentageStandardDeviation(double p, int sampleSize) {
return sqrt(p * (1 - p) / sampleSize);
}
int twoPopulationDegreeFreedom(double ssd1, double ssd2, int n1, int n2) {
auto sampleVariation1 = (ssd1 * ssd1 / n1);
auto sampleVariation2 = (ssd2 * ssd2 / n2);
return (sampleVariation1 + sampleVariation2) * (sampleVariation1 + sampleVariation2) /
(sampleVariation1 * sampleVariation1 / (n1 - 1) + sampleVariation2 * sampleVariation2 / (n2 - 1));
}
template <typename Iteratable>
int twoPopulationDegreeFreedom(Iteratable& _dataSet1, Iteratable& _dataSet2) {
auto ssd1 = genSampleStandardDeviation(_dataSet1, genMean(_dataSet1), _dataSet1.size());
auto ssd2 = genSampleStandardDeviation(_dataSet2, genMean(_dataSet2), _dataSet2.size());
return twoPopulationDegreeFreedom(ssd1, ssd2, _dataSet1.size(), _dataSet2.size());
}
double errorRadius(vector<double>& _dataSet, int degree, int sampleSize, double upperTailArea) {
double mean = genMean(_dataSet);
double ssd = genSampleStandardDeviation(_dataSet, mean, sampleSize);
return ssd / sqrt(sampleSize) * genTValue(degree, upperTailArea);
}
double errorRadius(vector<double>& _dataSet, double upperTailArea = 0.025) {
/*
* giving data set and the upper tail area of Student-T distribution
* return the error radius
* for too lazy to only input data set
*/
int sampleSize = _dataSet.size();
return errorRadius(_dataSet, sampleSize - 1, sampleSize, upperTailArea);
}
double errorRadius(double knownSigma, double alpha, int sampleSize, bool isSingleTail = false, bool isSample = false) {
/*
* @knownSigma: the population sigma, which over sqrt(n)
* giving alpha return the error radius for known Sigma of Z distribution
* return the error radius
*/
if (isSample) {
if (!isSingleTail)
alpha /= 2;
return knownSigma / sqrt(sampleSize) * genTValue(sampleSize - 1, alpha);
}
return knownSigma / sqrt(sampleSize) * genZValue(alpha, isSingleTail);
}
pair<double, double> genConfidenceInterval(double theta, double errorRadius, int tailOrient = 0) {
/*
* @theta: the sample variable
* @errorRadius: a radius of error, which might greater than 1,
* means the standardDeviation times (z or t) over sqrt(n)
* @tailOrient: if (tailOrient > 0) will reject right tail
* else if (tailOrient < 0) will reject left tail
* else will reject two tail
*/
if (tailOrient > 0)
return make_pair(-numeric_limits<double>::infinity(), theta + errorRadius);
else if (tailOrient < 0)
return make_pair(theta - errorRadius, numeric_limits<double>::infinity());
else
return make_pair(theta - errorRadius, theta + errorRadius);
}
vector<pair<double, double>> invertInterval(pair<double, double> originInterval) {
if (originInterval.first == -numeric_limits<double>::infinity())
return {make_pair(originInterval.second, numeric_limits<double>::infinity())};
else if (originInterval.second == numeric_limits<double>::infinity())
return {make_pair(-numeric_limits<double>::infinity(), originInterval.first)};
else
return {make_pair(-numeric_limits<double>::infinity(), originInterval.first),
make_pair(originInterval.second, numeric_limits<double>::infinity())};
}
pair<double, double> standardlizeInterval(pair<double, double> originInterval, double mu, double standardDeviation) {
/**
* @originInterval: the interval need to be standardlized
* @mu: the mean
* @standardDeviation: the standard deviation of mu
*/
return make_pair((originInterval.first - mu) / standardDeviation, (originInterval.second - mu) / standardDeviation);
}
double intervalProbability(pair<double, double> standardlizedInterval) {
/*
* this will return the probability with z distribution in some interval
* @standardlizedInterval: the standardlized interval which want to get the probability
*/
double leftTail = genPValue(standardlizedInterval.first, false, false),
rightTail = genPValue(standardlizedInterval.second, false, false);
return 1 - leftTail - rightTail;
}
template <typename T, typename S>
ostream& operator<<(ostream& os, const pair<T, S>& v) {
pair<char, char> boundSign('[', ']');
if (v.first == -numeric_limits<double>::infinity())
boundSign.first = '(';
if (v.second == numeric_limits<double>::infinity())
boundSign.second = ')';
os << boundSign.first << v.first << ", " << v.second << boundSign.second;
return os;
}
namespace needingSampleSize {
int p(double alpha, double p = 0.5, double marginError = 0.95) {
/*
* @p: the p bar of sample proportions, which might be iid Ber(P) (Bernoulli distribution)
* @marginError: the margin error of confidence interval
*/
double q = 1 - p, z = genZValue(alpha, false);
auto sampleSize = p * q * z * z / marginError / marginError;
return ceil(sampleSize);
}
int x_bar(double alpha, double knownTheta, double marginError) {
/*
* @knownTheta: the sigma which is the population standard deviation
* @marginError: the margin error of confidence interval
*/
double z = genZValue(alpha, false);
auto sampleSize = z * z * knownTheta * knownTheta / marginError / marginError;
return ceil(sampleSize);
}
int hypothesis(double mu_0, double mu_a, double za, double zb, double sigma) {
return ceil(pow((za + zb) * sigma / (mu_0 - mu_a), 2));
}
} // namespace needingSampleSize
double testStatistic(double x_bar, double mu_0, double sd, int sampleSize, bool isSample = false) {
/**
* @x_bar: sampleMean
* @sd: standard deviation
* @mu_0: the null hypotheses
* @sampleSize: the sample size which want to againest the H0
* @isSample: Are we not know the population @sd?
* if(false): we don't know the population standard deviation
*/
if (isSample)
sampleSize -= 1;
return (x_bar - mu_0) / (sd / sqrt(sampleSize));
}
template <class T>
string readSingleLineCSV(vector<T>& _dataSet, string fileName) {
/* will return the file's title
* read only single line csv file
* @_dataSet: a container you want to storge at
* @fileName: fileName
*/
ifstream inFile(fileName, ios::in);
if (inFile.fail()) {
cerr << "Open file failed" << endl;
return "";
}
string title;
T rawdata;
getline(inFile, title);
while (inFile >> rawdata)
_dataSet.push_back(rawdata);
inFile.close();
return title;
}
template <class T>
string readSingleLineCSV(map<T, int>& proportionDataSet, string fileName) {
/*
* only for reading proportion Data
* will return the file's title
* read only single line csv file
* @proportionDataSet: a container you want to storge at
* @fileName: fileName
*/
ifstream inFile(fileName, ios::in);
if (inFile.fail()) {
cerr << "Open file failed" << endl;
return "";
}
string title;
T rawData;
getline(inFile, title);
while (getline(inFile, rawData)) {
auto isInMap = proportionDataSet.find(rawData);
if (isInMap != proportionDataSet.end())
proportionDataSet.at(isInMap->first)++;
else
proportionDataSet.insert(pair<T, int>(rawData, 1));
}
inFile.close();
return title;
}
string readMultiLineCSV(map<string, map<string, int>>& proportionDataSet, string fileName) {
// @proportionDataSet: {title, {data, freq}}
// return file name
ifstream inFile(fileName, ios::in);
if (inFile.fail()) {
cerr << "Open file failed" << endl;
return "";
}
string titles, singleLine;
vector<string> titlesContainer;
getline(inFile, titles);
for (auto index = titles.find(','); index != string::npos; index = titles.find(',')) {
string firstSubstring(titles.substr(0, index));
titlesContainer.push_back(firstSubstring);
titles.erase(0, firstSubstring.length() + 1);
}
titlesContainer.push_back(titles); //push last title
while (getline(inFile, singleLine)) {
for (auto i : titlesContainer) {
auto index = singleLine.find(',');
string tmp;
if (index != string::npos)
tmp = singleLine.substr(0, index);
else
tmp = singleLine; //the last element
if (tmp.length()) {
auto isTitleInTable = proportionDataSet.find(i);
if (isTitleInTable != proportionDataSet.end()) {
auto isInMap = isTitleInTable->second.find(tmp);
if (isInMap != isTitleInTable->second.end())
isTitleInTable->second.at(isInMap->first)++;
else
isTitleInTable->second.insert(make_pair(tmp, 1));
} else {
auto inMap = make_pair(tmp, 1);
proportionDataSet[i].insert(inMap);
}
}
singleLine.erase(0, tmp.length() + 1);
}
}
inFile.close();
return fileName;
}
#endif
| 36.595679 | 120 | 0.651177 | 25077667 |
5885ce345983b2acb00db0411fa4b6344d94d5b2 | 3,865 | hpp | C++ | cpp/euler003/Primesieve.hpp | marvins/ProjectEuler | 55a377bb9702067bac6908c1316c578498402668 | [
"MIT"
] | null | null | null | cpp/euler003/Primesieve.hpp | marvins/ProjectEuler | 55a377bb9702067bac6908c1316c578498402668 | [
"MIT"
] | null | null | null | cpp/euler003/Primesieve.hpp | marvins/ProjectEuler | 55a377bb9702067bac6908c1316c578498402668 | [
"MIT"
] | 1 | 2020-12-16T09:25:19.000Z | 2020-12-16T09:25:19.000Z | #ifndef __PRIME_SIEVE_H__
#define __PRIME_SIEVE_H__
// C++ Standard Libraries
#include <cinttypes>
#include <iostream>
#include <cmath>
#include <vector>
#include <sstream>
#include <string>
using namespace std;
/**
* @class Prime Sieve Class
*
* Implements a basic prime sieve
*/
class Primes{
public:
/**
* Constructor
*/
Primes( int64_t const& maxval,
bool const& debug = false)
: MAX(maxval)
{
// MAX value
long int root = static_cast<long int>(ceil(sqrt(static_cast<double>(MAX))));
m_pos = 1;
if(debug)cout << "Starting Library Construction" << endl;
// Iterate over data
m_data.begin();
for(long int i=0;i<MAX;i++){
m_data.push_back(true);
}
// Set 0 to false
m_data[0]=false;
for(long int i=1;i<=root;i++)
{
if(m_data[i-1]){
for( long int j = i*2; j <= MAX; j+= i){
m_data[j-1] = false;
// Print the debugging data
if(debug){
cout << status(i,root);
}
}
}
}
// Print the debugging flag
if(debug) cout << endl;
}
/**
* Start Processing Prime Numbers
*/
void prime_start(){
m_pos = 2;
}
/**
* Get the next prime.
*
* @param[out] end Check if the value is the last prime number.
*/
int64_t prime_next(bool& end )
{
// If the position is below the array size
if( m_pos < (int)m_data.size() )
{
while(!is_prime(m_pos) && (m_pos!=-1)){
m_pos++;
if( m_pos > MAX ){
end=true;
return 0;
}
}
m_pos++;
if((m_pos-1) > (int)m_data.size() || (m_pos == -1))
{
end = true;
return 0;
}
else
{
end = false;
return m_pos-1;
}
}
end = true;
return 0;
}
/**
* @brief Check if a number is prime.
*
* @param[in] number Number to test.
*
* @return True if the number is prime, false otherwise.
*/
bool is_prime(const long int& number ) const
{
if(number > 0 && number < MAX)
{
return m_data[number-1];
}
return false;
}
private:
/**
* Get the status
*/
std::string status( int64_t const& x,
int64_t const& y ) const
{
// Output stream buffer
std::ostringstream buff;
// Compute a z value
double z = x/(double)y;
// Create output
string output = " Building Library [";
// Iterate over output
for(int i=0;i<40;i++){
if((i/40.0)<(z))
output += '*';
else
output += ' ';
}
output += "] ";
buff << ((x/(double)y)*100);
output += buff.str();
output += "% \r";
return output;
}
// Data Array
vector<bool> m_data;
// Max Value
const int64_t MAX;
// Position
int64_t m_pos;
};
#endif
| 22.602339 | 88 | 0.381371 | marvins |
5888eae2237ee496343ad00fe64f487ec39abe45 | 1,457 | cpp | C++ | src/Pic.cpp | NiwakaDev/X86_EMULATOR_2 | 2e725e0eaa543048ce9a20bd223bcdcde2df7a73 | [
"MIT"
] | 16 | 2021-11-19T22:26:22.000Z | 2022-02-16T12:38:50.000Z | src/Pic.cpp | NiwakaDev/X86_EMULATOR_2 | 2e725e0eaa543048ce9a20bd223bcdcde2df7a73 | [
"MIT"
] | 1 | 2022-02-19T04:56:47.000Z | 2022-02-19T10:00:58.000Z | src/Pic.cpp | NiwakaDev/X86_EMULATOR_2 | 2e725e0eaa543048ce9a20bd223bcdcde2df7a73 | [
"MIT"
] | null | null | null | #include "Pic.h"
#include <format>
#include "IoDevice.h"
using namespace std;
Pic::Pic(IoDevice** io_devices) {
if (io_devices == NULL) {
throw runtime_error("io_devices is NULL at Pic::Pic");
}
this->obj = make_unique<Object>();
for (int i = 0; i < 16; i++) {
this->irq_list[i] = false;
}
this->io_devices = io_devices;
}
Pic::~Pic() {}
void Pic::Out8(const uint16_t addr, const uint8_t data) {
switch (addr) {
case PIC1_ICW1:
case PIC0_ICW1:
break;
case PIC0_IMR:
for (int i = 0; i < 8; i++) {
this->irq_list[i] = !((data & (1 << i)) == (1 << i));
}
break;
case PIC1_IMR:
for (int i = 8; i < 16; i++) {
this->irq_list[i] =
!(((((unsigned int)data) << 8) & (1 << i)) == (1 << i));
}
break;
default:
throw runtime_error(this->obj->Format(
"Not implemented: io_addr=0x%04X at Pic::Out8", addr));
}
}
uint8_t Pic::In8(const uint16_t addr) {
switch (addr) {
default:
throw runtime_error(
this->obj->Format("Not implemented: io_addr=%04X at Pic::In8", addr));
}
}
bool Pic::HasIrq() {
for (int i = 0; i < 16; i++) {
if (this->io_devices[i] == NULL) {
continue;
}
if (!this->irq_list[i]) {
continue;
}
// TODO : 入出力デバイスが割り込み番号を知っていない実装に変更
if ((this->now_irq_num = this->io_devices[i]->IsEmpty()) == -1) {
continue;
}
return true;
}
return false;
} | 22.765625 | 80 | 0.539465 | NiwakaDev |
588f5de16d7dacf8c21f1a364bb9b7f54d6304c4 | 906 | cc | C++ | leet_code/Iterator_for_Combination/solve.cc | ldy121/algorithm | 7939cb4c15e2bc655219c934f00c2bb74ddb4eec | [
"Apache-2.0"
] | 1 | 2020-04-11T22:04:23.000Z | 2020-04-11T22:04:23.000Z | leet_code/Iterator_for_Combination/solve.cc | ldy121/algorithm | 7939cb4c15e2bc655219c934f00c2bb74ddb4eec | [
"Apache-2.0"
] | null | null | null | leet_code/Iterator_for_Combination/solve.cc | ldy121/algorithm | 7939cb4c15e2bc655219c934f00c2bb74ddb4eec | [
"Apache-2.0"
] | null | null | null | class CombinationIterator {
private :
list<string> m_list;
list<string>::iterator m_iter;
void generate(string& characters, string str, int idx, int n) {
if (n == 0) {
m_list.push_back(str);
} else if ((n > 0) && (idx < characters.length())) {
generate(characters, str + characters[idx], idx + 1, n - 1);
generate(characters, str, idx + 1, n);
}
}
public:
CombinationIterator(string characters, int combinationLength) {
string str;
generate(characters, str, 0, combinationLength);
m_iter = m_list.begin();
}
string next() {
string ret = *m_iter;
++m_iter;
return ret;
}
bool hasNext() {
return (m_iter != m_list.end());
}
};
/**
* Your CombinationIterator object will be instantiated and called as such:
* CombinationIterator* obj = new CombinationIterator(characters, combinationLength);
* string param_1 = obj->next();
* bool param_2 = obj->hasNext();
*/
| 23.230769 | 85 | 0.66777 | ldy121 |
588f88a4b57ef2b4f86f673d4bd7ec668ccedb95 | 5,339 | cpp | C++ | test/decode.cpp | cdglove/boost.radix | 39626a1a76eb33ce9bd43b3957f1a39678943a30 | [
"BSL-1.0"
] | 1 | 2018-01-11T20:27:16.000Z | 2018-01-11T20:27:16.000Z | test/decode.cpp | cdglove/boost.radix | 39626a1a76eb33ce9bd43b3957f1a39678943a30 | [
"BSL-1.0"
] | null | null | null | test/decode.cpp | cdglove/boost.radix | 39626a1a76eb33ce9bd43b3957f1a39678943a30 | [
"BSL-1.0"
] | null | null | null | //
// test/decode.cpp
//
// Copyright (c) Chris Glover, 2017-2018
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#define BOOST_TEST_MODULE TestDecode
#include <boost/test/unit_test.hpp>
#include <boost/radix/basic_codec.hpp>
#include <boost/radix/decode.hpp>
#include <boost/radix/static_obitstream_lsb.hpp>
#include <boost/range/algorithm/equal.hpp>
#include <vector>
#include "common.hpp"
// -----------------------------------------------------------------------------
//
template <std::size_t Bits>
class msb_codec
: public boost::radix::basic_codec<
boost::radix::bits::to_alphabet_size<Bits>::value> {
public:
msb_codec()
: boost::radix::basic_codec<
boost::radix::bits::to_alphabet_size<Bits>::value>(
generate_alphabet(Bits)) {
}
};
template <std::size_t Bits>
boost::radix::static_obitstream_msb<Bits> get_segment_packer(
msb_codec<Bits> const&) {
return boost::radix::static_obitstream_msb<Bits>();
}
template <std::size_t Bits>
bool is_invalid_whitespace_character(
msb_codec<Bits> const& codec, char_type c) {
return false;
}
// -----------------------------------------------------------------------------
//
template <std::size_t Bits>
class lsb_codec
: public boost::radix::basic_codec<
boost::radix::bits::to_alphabet_size<Bits>::value> {
public:
lsb_codec()
: boost::radix::basic_codec<
boost::radix::bits::to_alphabet_size<Bits>::value>(
generate_alphabet(Bits)) {
}
};
template <std::size_t Bits>
boost::radix::static_obitstream_lsb<Bits> get_segment_packer(
lsb_codec<Bits> const&) {
return boost::radix::static_obitstream_lsb<Bits>();
}
template <std::size_t Bits, typename ErrorHandler>
boost::radix::decode_validation::op validate_character(
lsb_codec<Bits> const& codec, char_type c, ErrorHandler& errh) {
return boost::radix::decode_validation::op_consume;
}
// -----------------------------------------------------------------------------
//
template <std::size_t Bits, typename DataGenerator, typename Decoder>
void test_decode(DataGenerator data_generator, Decoder decoder) {
std::vector<char_type> alphabet = generate_alphabet(Bits);
std::vector<bits_type> data = data_generator(Bits);
std::vector<bits_type> result;
boost::radix::decode(
alphabet.begin(), alphabet.end(), std::back_inserter(result), decoder);
BOOST_TEST(boost::equal(data, result, is_equal_unsigned()));
}
template <std::size_t Bits>
void test_decode_msb() {
test_decode<Bits>(generate_all_permutations_msb, msb_codec<Bits>());
}
template <std::size_t Bits>
void test_decode_lsb() {
test_decode<Bits>(generate_all_permutations_lsb, lsb_codec<Bits>());
}
template <std::size_t Bits, typename DataGenerator, typename Encoder>
void test_decoder(DataGenerator data_generator, Encoder codec) {
std::vector<char_type> alphabet = generate_alphabet(Bits);
std::vector<bits_type> data = data_generator(Bits);
std::vector<bits_type> result;
result.resize(boost::radix::decoded_size(data.size(), codec));
boost::radix::decoder<Encoder, bits_type*> decoder =
boost::radix::make_decoder(codec, result.data());
decoder.append(alphabet.begin(), alphabet.end());
decoder.resolve();
result.resize(decoder.bytes_written());
BOOST_TEST(boost::equal(data, result, is_equal_unsigned()));
}
// -----------------------------------------------------------------------------
//
BOOST_AUTO_TEST_CASE(decode_one_bit_msb) {
test_decode_msb<1>();
}
BOOST_AUTO_TEST_CASE(decode_two_bit_msb) {
test_decode_msb<2>();
}
BOOST_AUTO_TEST_CASE(decode_three_bit_msb) {
test_decode_msb<3>();
}
BOOST_AUTO_TEST_CASE(decode_four_bit_msb) {
test_decode_msb<4>();
}
BOOST_AUTO_TEST_CASE(decode_five_bit_msb) {
test_decode_msb<5>();
}
BOOST_AUTO_TEST_CASE(decode_six_bit_msb) {
test_decode_msb<6>();
}
BOOST_AUTO_TEST_CASE(decode_seven_bit_msb) {
test_decode_msb<7>();
}
BOOST_AUTO_TEST_CASE(decode_one_bit_lsb) {
test_decode_lsb<1>();
}
BOOST_AUTO_TEST_CASE(decode_two_bit_lsb) {
test_decode_lsb<2>();
}
BOOST_AUTO_TEST_CASE(decode_three_bit_lsb) {
test_decode_lsb<3>();
}
BOOST_AUTO_TEST_CASE(decode_four_bit_lsb) {
test_decode_lsb<4>();
}
BOOST_AUTO_TEST_CASE(decode_five_bit_lsb) {
test_decode_lsb<5>();
}
BOOST_AUTO_TEST_CASE(decode_six_bit_lsb) {
test_decode_lsb<6>();
}
BOOST_AUTO_TEST_CASE(decode_seven_bit_lsb) {
test_decode_lsb<7>();
}
BOOST_AUTO_TEST_CASE(decoder_one_bit_msb) {
test_decoder<1>(generate_all_permutations_msb, msb_codec<1>());
}
BOOST_AUTO_TEST_CASE(decoder_two_bit_msb) {
test_decoder<2>(generate_all_permutations_msb, msb_codec<2>());
}
BOOST_AUTO_TEST_CASE(decoder_three_bit_msb) {
test_decoder<3>(generate_all_permutations_msb, msb_codec<3>());
}
BOOST_AUTO_TEST_CASE(decoder_four_bit_msb) {
test_decoder<4>(generate_all_permutations_msb, msb_codec<4>());
}
BOOST_AUTO_TEST_CASE(decoder_five_bit_msb) {
test_decoder<5>(generate_all_permutations_msb, msb_codec<5>());
}
BOOST_AUTO_TEST_CASE(decoder_six_bit_msb) {
test_decoder<6>(generate_all_permutations_msb, msb_codec<6>());
}
BOOST_AUTO_TEST_CASE(decoder_seven_bit_msb) {
test_decoder<7>(generate_all_permutations_msb, msb_codec<7>());
}
| 27.379487 | 80 | 0.701255 | cdglove |
5895b01774a3b95dcf02a56bcf363bf6e704c4f3 | 5,486 | cpp | C++ | lang/steve/Cli.cpp | flowgrammable/steve-legacy | 5e7cbc16280c199732d26a2cb0703422695abe16 | [
"Apache-2.0"
] | 1 | 2017-07-30T04:18:56.000Z | 2017-07-30T04:18:56.000Z | lang/steve/Cli.cpp | flowgrammable/steve-legacy | 5e7cbc16280c199732d26a2cb0703422695abe16 | [
"Apache-2.0"
] | null | null | null | lang/steve/Cli.cpp | flowgrammable/steve-legacy | 5e7cbc16280c199732d26a2cb0703422695abe16 | [
"Apache-2.0"
] | null | null | null |
#include <steve/Cli.hpp>
#include <steve/Config.hpp>
#include <steve/Ast.hpp>
#include <steve/Error.hpp>
#include <steve/Extract.hpp>
#include <steve/Module.hpp>
#include <steve/String.hpp>
#include <cctype>
#include <cstring>
#include <algorithm>
#include <iostream>
namespace steve {
namespace cli {
namespace {
// Returns true if the character c starts an option.
inline bool
is_option(char c) { return c == '-'; }
bool
parse_long_arg(Parser& p, const char* arg) {
int n = std::strlen(arg);
const char* end = arg + n;
// Is there an '=' in the option name?
const char* eq = std::find(arg, end, '=');
// Get the name from the argument.
std::string name;
if (eq == end)
name = arg;
else
name = std::string(arg, eq);
// FIXME: Parse the value of the parameter.
// Find the corresponding parameter.
if (p.parms.find(name) != p.parms.end()) {
p.args[name] = Value(true);
} else {
std::cerr << format("error: unrecognized option '{}'", name) << '\n';
return false;
}
return true;
}
bool
parse_short_arg(Parser& p, const char* arg) {
std::cout << format("error: unrecognized option '{}'", arg) << '\n';
return false;
}
bool
parse_arg(Parser& p, const char* arg) {
if (std::isalnum(arg[1]))
return parse_short_arg(p, arg + 1);
else if (is_option(arg[1]))
return parse_long_arg(p, arg + 2);
else
std::cerr << format("error: unrecognized option '{}'", arg) << '\n';
return false;
}
} // namespace
int
Parser::operator()(int first, int argc, char** argv) {
bool err = false;
char* arg = argv[first];
while (first != argc and is_option(*arg)) {
if (not parse_arg(*this, arg))
err = true;
++first;
arg = argv[first];
}
return err ? -1 : first;
}
int
Parser::operator()(int argc, char** argv) {
return operator()(1, argc, argv);
}
// -------------------------------------------------------------------------- //
// Help command
bool
Help_command::operator()(const Command_map& cmds) {
std::cout << "steve [steve-arguments] <command> [command-arguments] [command-inputs]\n";
std::cout << '\n';
// TODO: Print the list of global steve arguments.
// Print the list of registered commands.
// TODO: Also print a brief descriptions of those commands.
std::cout << "Commands\n";
for (const auto& x : cmds)
std::cout << " " << x.first << '\n';
return true;
}
bool
Help_command::operator()(int arg, int argc, char** argv) {
if (arg == argc) {
std::cerr << "error: missing help topic\n";
return false;
}
std::cout << "help on '" << argv[arg] << "'\n";
return true;
}
// -------------------------------------------------------------------------- //
// Version command
//
// TODO: Abstract the version, copyright, and author data into a
// facility that can be compiled at build time.
//
// TOOD: Version information should be set by configuration, not
// in code.
bool
Version_command::operator()(int arg, int argc, char** argv) {
if (arg != argc) {
std::cerr << "error: too many arguments\n";
return false;
}
std::cout << "Steve Programming Language v0.1\n";
std::cout << "Copyright (c) 2013-2015 Flowgrammable.org\n";
return true;
}
// -------------------------------------------------------------------------- //
// Extract command
//
// The extract command applies a function (an extractor) to a
// qualified-id that designates a declaration. For example:
//
// steve extract doc std.net.ofp.uint
//
// Will extract the associated documentation for the uint function
// in that module.
// TODO: Use command line parameters to provide options for the
// extractor.
bool
Extract_command::operator()(int arg, int argc, char** argv) {
// FIXME: This is totally broken. Also, use the help command to
// print the actual help for this extractor.
if (arg + 2 >= argc) {
error() << "too few arguments";
error() << "usage: steve extract <extractor> <id>";
}
std::string what = argv[arg++];
std::string from = argv[arg++];
// Load the name.
Expr* e = load_name(from);
if (not e) {
error() << format("no matching declaration for '{}'", from);
return false;
}
// if (Extractor* e = get_extractor(extractor))
// (*e)(mod);
// else
// error() << format("no extractor named '{}'", extractor);
return true;
}
// -------------------------------------------------------------------------- //
// Test command
//
// TODO: Support a number of test modes that emit diagnosable
// text for the following activities
//
// - lexical analysis -- print the list of tokens
// - syntactic analysis -- print the parse tree
// - semantic analysis -- print the elaborated AST
// - other?
//
// TODO: Maybe rename this to 'dump' command... or define several?
//
// TODO: Allow multiple inputs? Maybe, but we need to fork() to
// do that. Otherwise, we end up building a single input module.
bool
Test_command::operator()(int arg, int argc, char** argv) {
Diagnostics diags;
Diagnostics_guard dg = diags;
// Parse arguments, saving input files to the configuration.
if (arg == argc) {
error(no_location) << "no input files\n";
return false;
}
if (argc - arg != 1) {
error(no_location) << "too many input files\n";
}
// Parse the input files.
Module* mod = load_file(argv[arg]);
if (mod) {
for (Decl* d : *mod->decls())
std::cout << debug(d) << '\n';
}
return mod ? true : false;
}
} // namespace cli
} // namespace steve
| 24.711712 | 90 | 0.595516 | flowgrammable |
5895e8e4df264498717bb31cea0001f602950c9f | 1,227 | cpp | C++ | lib/Seeed_Arduino_TFlidar/src/TFLidar.cpp | sei-kiu/Wio-Terminal-Grove-TF-Mini-LiDAR | f1a3090d0ad4de7c8ac4bccf765a5266d998a81a | [
"MIT"
] | null | null | null | lib/Seeed_Arduino_TFlidar/src/TFLidar.cpp | sei-kiu/Wio-Terminal-Grove-TF-Mini-LiDAR | f1a3090d0ad4de7c8ac4bccf765a5266d998a81a | [
"MIT"
] | null | null | null | lib/Seeed_Arduino_TFlidar/src/TFLidar.cpp | sei-kiu/Wio-Terminal-Grove-TF-Mini-LiDAR | f1a3090d0ad4de7c8ac4bccf765a5266d998a81a | [
"MIT"
] | 2 | 2021-05-31T21:57:02.000Z | 2022-03-29T22:38:19.000Z | #include "TFLidar.h"
TFLidar::TFLidar(TFBase *TF_Lidar){
_TF_Lidar = TF_Lidar;
}
void TFLidar::begin(SoftwareSerial *TFSerial,uint32_t baud_rate){
_TF_Lidar->begin(TFSerial,baud_rate);
}
void TFLidar::begin(HardwareSerial *TFSerial,uint32_t baud_rate){
_TF_Lidar->begin(TFSerial,baud_rate);
}
uint16_t TFLidar::get_distance(){
return _TF_Lidar->get_distance();
}
uint16_t TFLidar::get_strength(){
return _TF_Lidar->get_strength();
}
uint8_t TFLidar::get_chip_temperature(){
return _TF_Lidar->get_chip_temperature();
}
bool TFLidar::get_frame_data(){
return _TF_Lidar->get_frame_data();
}
uint16_t TFLidar::get_version(int buff[]){
return _TF_Lidar->get_version(buff);
}
bool TFLidar::set_frame_rate(samplerate_mode mode){
return _TF_Lidar->set_frame_rate(mode);
}
bool TFLidar::set_output_status(bool status){
return _TF_Lidar->set_output_status(status);
}
bool TFLidar::reset_device(){
return _TF_Lidar->reset_device();
}
bool TFLidar::factory_reset(void){
return _TF_Lidar->factory_reset();
}
bool TFLidar::save_config(void){
return _TF_Lidar->save_config();
}
bool TFLidar::set_baud_rate(uint32_t baud_rate){
return _TF_Lidar->set_baud_rate(baud_rate);
}
| 21.526316 | 65 | 0.745721 | sei-kiu |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.