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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6efa0b7caa5c3485087e445ab01d9180aff7e1b5 | 21,293 | cc | C++ | src/video_encoder.cc | AugmentariumLab/foveated-360-video | bd5cb585712cc67b20da1264430c33c8bc68cf49 | [
"MIT"
] | 3 | 2021-03-30T15:46:36.000Z | 2021-11-26T03:20:15.000Z | src/video_encoder.cc | AugmentariumLab/foveated-360-video | bd5cb585712cc67b20da1264430c33c8bc68cf49 | [
"MIT"
] | null | null | null | src/video_encoder.cc | AugmentariumLab/foveated-360-video | bd5cb585712cc67b20da1264430c33c8bc68cf49 | [
"MIT"
] | 2 | 2021-03-30T15:46:40.000Z | 2021-12-19T09:53:38.000Z | #include "video_encoder.h"
VideoEncoder::VideoEncoder(AVCodecContext *s_video_codec_ctx) {
using namespace std;
int ret = 0;
std::array<char, 256> errstr;
hw_frame = av_frame_alloc();
hw_device_ctx = NULL;
out_format_ctx = NULL;
audio_codec = NULL;
audio_codec_ctx = NULL;
if ((ret = av_hwdevice_ctx_create(&hw_device_ctx, AV_HWDEVICE_TYPE_CUDA, NULL,
NULL, 0)) < 0) {
cerr << "[VideoEncoder::VideoEncoder] Failed to create hw context" << endl;
av_make_error_string(errstr.data(), errstr.size(), ret);
cerr << "Ret: " << ret << "," << errstr.data() << endl;
return;
}
if (!(video_codec = avcodec_find_encoder_by_name("h264_nvenc"))) {
cerr << "[VideoEncoder::VideoEncoder] Failed to find h264_nvenc encoder"
<< endl;
return;
}
video_codec_ctx = avcodec_alloc_context3(video_codec);
video_codec_ctx->bit_rate = std::pow(10, 8);
// std::cerr << "Max bitrate " << video_codec_ctx->bit_rate << std::endl;
video_codec_ctx->width = s_video_codec_ctx->width;
video_codec_ctx->height = s_video_codec_ctx->height;
std::cerr << "Encoded resolution " << s_video_codec_ctx->width << ", "
<< s_video_codec_ctx->height << std::endl;
video_codec_ctx->codec_type = AVMEDIA_TYPE_VIDEO;
video_codec_ctx->time_base = s_video_codec_ctx->time_base;
input_timebase = s_video_codec_ctx->time_base;
video_codec_ctx->framerate = s_video_codec_ctx->framerate;
video_codec_ctx->pix_fmt = AV_PIX_FMT_CUDA;
video_codec_ctx->profile = FF_PROFILE_H264_MAIN;
video_codec_ctx->max_b_frames = 0;
video_codec_ctx->delay = 0;
ret = av_opt_set(video_codec_ctx->priv_data, "cq", "25", 0);
if (ret != 0) {
std::cerr << "Failed to set cq in priv data" << std::endl;
}
if ((ret = SetHWFrameCtx(video_codec_ctx, hw_device_ctx)) < 0) {
cerr << "[VideoEncoder::VideoEncoder] Failed to set hwframe context."
<< endl;
return;
}
AVDictionary *opts = NULL;
av_dict_set(&opts, "preset", "fast", 0);
if (avcodec_open2(video_codec_ctx, video_codec, &opts) < 0) {
cerr << "[VideoEncoder::VideoEncoder] Failed to open H264 codec" << endl;
return;
}
if ((ret = av_hwframe_get_buffer(video_codec_ctx->hw_frames_ctx, hw_frame,
0)) < 0) {
cerr << "[VideoEncoder::VideoEncoder] Av_hwframe_get_buffer failed" << endl;
return;
}
NvencContext *nv = (NvencContext *)video_codec_ctx->priv_data;
// auto r = nv->output_surface_ready_queue;
// auto p = nv->output_surface_queue;
// std::cerr << "Ready "
// << (uint32_t)(r->wndx - r->rndx) / sizeof(NvencSurface *)
// << std::endl;
// std::cerr << "Pending "
// << (uint32_t)(p->wndx - p->rndx) / sizeof(NvencSurface *)
// << std::endl;
// std::cerr << "rc_lookahead " << nv->rc_lookahead << std::endl;
// std::cerr << "nb_surfaces " << nv->nb_surfaces << std::endl;
nv->async_depth = 1;
}
VideoEncoder::VideoEncoder(AVCodecContext *s_video_codec_ctx,
AVCodecContext *s_audio_codec_ctx,
std::string filename) {
using namespace std;
int ret = 0;
hw_frame = av_frame_alloc();
hw_device_ctx = NULL;
this->output_filename = filename;
if ((ret = avformat_alloc_output_context2(
&out_format_ctx, NULL, NULL, this->output_filename.c_str())) < 0) {
cerr << "[VideoEncoder::VideoEncoder] avformat_alloc_output_context2 failed"
<< endl;
return;
}
if ((ret = avio_open(&out_format_ctx->pb, this->output_filename.c_str(),
AVIO_FLAG_WRITE)) < 0) {
cerr << "[VideoEncoder::VideoEncoder] AVIO Open failed" << endl;
return;
}
if ((ret = av_hwdevice_ctx_create(&hw_device_ctx, AV_HWDEVICE_TYPE_CUDA, NULL,
NULL, 0)) < 0) {
cerr << "[VideoEncoder::VideoEncoder] Failed to create hw context" << endl;
return;
}
if (!(video_codec = avcodec_find_encoder_by_name("h264_nvenc"))) {
cerr << "[VideoEncoder::VideoEncoder] Failed to find h264_nvenc encoder"
<< endl;
return;
}
video_codec_ctx = avcodec_alloc_context3(video_codec);
video_codec_ctx->bit_rate = std::pow(10, 8);
video_codec_ctx->width = s_video_codec_ctx->width;
video_codec_ctx->height = s_video_codec_ctx->height;
// video_codec_ctx->codec_type = AVMEDIA_TYPE_VIDEO;
video_codec_ctx->time_base = s_video_codec_ctx->time_base;
input_timebase = s_video_codec_ctx->time_base;
video_codec_ctx->framerate = s_video_codec_ctx->framerate;
video_codec_ctx->pix_fmt = AV_PIX_FMT_CUDA;
video_codec_ctx->profile = FF_PROFILE_H264_MAIN;
video_codec_ctx->max_b_frames = 0;
video_codec_ctx->delay = 0;
ret = av_opt_set(video_codec_ctx->priv_data, "cq", "25", 0);
if ((ret = SetHWFrameCtx(video_codec_ctx, hw_device_ctx)) < 0) {
cerr << "[VideoEncoder::VideoEncoder] Failed to set hwframe context."
<< endl;
return;
}
AVDictionary *opts = NULL;
av_dict_set(&opts, "preset", "fast", 0);
if (avcodec_open2(video_codec_ctx, video_codec, &opts) < 0) {
cerr << "[VideoEncoder::VideoEncoder] Failed to open H264 codec" << endl;
return;
}
if (!(out_video_stream = avformat_new_stream(out_format_ctx, video_codec))) {
cerr << "[VideoEncoder::VideoEncoder] Failed to allocate output stream"
<< endl;
}
out_video_stream->time_base = video_codec_ctx->time_base;
out_video_stream->r_frame_rate = video_codec_ctx->framerate;
if ((ret = avcodec_parameters_from_context(out_video_stream->codecpar,
video_codec_ctx)) < 0) {
cerr << "[VideoEncoder::VideoEncoder] Failed to copy parameters to context"
<< endl;
return;
}
if (s_audio_codec_ctx) {
out_audio_stream = avformat_new_stream(out_format_ctx, NULL);
audio_codec = avcodec_find_encoder(s_audio_codec_ctx->codec_id);
if (!audio_codec) {
std::cerr << __func__ << " Audio encoder not found" << std::endl;
return;
}
audio_codec_ctx = avcodec_alloc_context3(audio_codec);
if (!audio_codec_ctx) {
std::cerr << __func__ << "Failed to allocate the encoder context\n"
<< std::endl;
return;
}
/* In this example, we transcode to same properties (picture size,
* sample rate etc.). These properties can be changed for output
* streams easily using filters */
audio_codec_ctx->sample_rate = s_audio_codec_ctx->sample_rate;
audio_codec_ctx->channel_layout = s_audio_codec_ctx->channel_layout;
audio_codec_ctx->channels =
av_get_channel_layout_nb_channels(s_audio_codec_ctx->channel_layout);
/* take first format from list of supported formats */
audio_codec_ctx->sample_fmt = audio_codec->sample_fmts[0];
audio_codec_ctx->time_base = {1, audio_codec_ctx->sample_rate};
if (out_format_ctx->oformat->flags & AVFMT_GLOBALHEADER)
audio_codec_ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
/* Third parameter can be used to pass settings to encoder */
ret = avcodec_open2(audio_codec_ctx, audio_codec, NULL);
if (ret < 0) {
std::cerr << __func__ << "Cannot open video encoder for audio stream"
<< std::endl;
return;
}
ret = avcodec_parameters_from_context(out_audio_stream->codecpar,
audio_codec_ctx);
if (ret < 0) {
std::cerr << __func__
<< "Failed to copy encoder parameters to audio stream"
<< std::endl;
return;
}
out_audio_stream->time_base = audio_codec_ctx->time_base;
} else {
audio_codec_ctx = NULL;
out_audio_stream = NULL;
}
if ((ret = av_hwframe_get_buffer(video_codec_ctx->hw_frames_ctx, hw_frame,
0)) < 0) {
cerr << "[VideoEncoder::VideoEncoder] Av_hwframe_get_buffer failed" << endl;
return;
}
if ((ret = avformat_write_header(out_format_ctx, NULL)) < 0) {
cerr << "[VideoEncoder::VideoEncoder] Failed to copy parameters to context"
<< endl;
return;
}
}
VideoEncoder::VideoEncoder(AVCodecContext *s_video_codec_ctx,
AVCodecContext *s_audio_codec_ctx,
std::string filename, int bitrate) {
using namespace std;
int ret = 0;
hw_frame = av_frame_alloc();
hw_device_ctx = NULL;
this->output_filename = filename;
if ((ret = avformat_alloc_output_context2(
&out_format_ctx, NULL, NULL, this->output_filename.c_str())) < 0) {
cerr << "[VideoEncoder::VideoEncoder] avformat_alloc_output_context2 failed"
<< endl;
return;
}
if ((ret = avio_open(&out_format_ctx->pb, this->output_filename.c_str(),
AVIO_FLAG_WRITE)) < 0) {
cerr << "[VideoEncoder::VideoEncoder] AVIO Open failed" << endl;
return;
}
if ((ret = av_hwdevice_ctx_create(&hw_device_ctx, AV_HWDEVICE_TYPE_CUDA, NULL,
NULL, 0)) < 0) {
cerr << "[VideoEncoder::VideoEncoder] Failed to create hw context" << endl;
return;
}
if (!(video_codec = avcodec_find_encoder_by_name("h264_nvenc"))) {
cerr << "[VideoEncoder::VideoEncoder] Failed to find h264_nvenc encoder"
<< endl;
return;
}
video_codec_ctx = avcodec_alloc_context3(video_codec);
video_codec_ctx->width = s_video_codec_ctx->width;
video_codec_ctx->height = s_video_codec_ctx->height;
// video_codec_ctx->codec_type = AVMEDIA_TYPE_VIDEO;
video_codec_ctx->time_base = s_video_codec_ctx->time_base;
input_timebase = s_video_codec_ctx->time_base;
video_codec_ctx->framerate = s_video_codec_ctx->framerate;
video_codec_ctx->pix_fmt = AV_PIX_FMT_CUDA;
video_codec_ctx->profile = FF_PROFILE_H264_MAIN;
video_codec_ctx->max_b_frames = 0;
video_codec_ctx->delay = 0;
if (bitrate > 0) {
video_codec_ctx->bit_rate = bitrate;
} else {
video_codec_ctx->bit_rate = std::pow(10, 8);
ret = av_opt_set(video_codec_ctx->priv_data, "cq", "25", 0);
}
if ((ret = SetHWFrameCtx(video_codec_ctx, hw_device_ctx)) < 0) {
cerr << "[VideoEncoder::VideoEncoder] Failed to set hwframe context."
<< endl;
return;
}
AVDictionary *opts = NULL;
av_dict_set(&opts, "preset", "fast", 0);
if (avcodec_open2(video_codec_ctx, video_codec, &opts) < 0) {
cerr << "[VideoEncoder::VideoEncoder] Failed to open H264 codec" << endl;
return;
}
if (!(out_video_stream = avformat_new_stream(out_format_ctx, video_codec))) {
cerr << "[VideoEncoder::VideoEncoder] Failed to allocate output stream"
<< endl;
}
out_video_stream->time_base = video_codec_ctx->time_base;
out_video_stream->r_frame_rate = video_codec_ctx->framerate;
if ((ret = avcodec_parameters_from_context(out_video_stream->codecpar,
video_codec_ctx)) < 0) {
cerr << "[VideoEncoder::VideoEncoder] Failed to copy parameters to context"
<< endl;
return;
}
if (s_audio_codec_ctx) {
out_audio_stream = avformat_new_stream(out_format_ctx, NULL);
audio_codec = avcodec_find_encoder(s_audio_codec_ctx->codec_id);
if (!audio_codec) {
std::cerr << __func__ << " Audio encoder not found" << std::endl;
return;
}
audio_codec_ctx = avcodec_alloc_context3(audio_codec);
if (!audio_codec_ctx) {
std::cerr << __func__ << "Failed to allocate the encoder context\n"
<< std::endl;
return;
}
/* In this example, we transcode to same properties (picture size,
* sample rate etc.). These properties can be changed for output
* streams easily using filters */
audio_codec_ctx->sample_rate = s_audio_codec_ctx->sample_rate;
audio_codec_ctx->channel_layout = s_audio_codec_ctx->channel_layout;
audio_codec_ctx->channels =
av_get_channel_layout_nb_channels(s_audio_codec_ctx->channel_layout);
/* take first format from list of supported formats */
audio_codec_ctx->sample_fmt = audio_codec->sample_fmts[0];
audio_codec_ctx->time_base = {1, audio_codec_ctx->sample_rate};
if (out_format_ctx->oformat->flags & AVFMT_GLOBALHEADER)
audio_codec_ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
/* Third parameter can be used to pass settings to encoder */
ret = avcodec_open2(audio_codec_ctx, audio_codec, NULL);
if (ret < 0) {
std::cerr << __func__ << "Cannot open video encoder for audio stream"
<< std::endl;
return;
}
ret = avcodec_parameters_from_context(out_audio_stream->codecpar,
audio_codec_ctx);
if (ret < 0) {
std::cerr << __func__
<< "Failed to copy encoder parameters to audio stream"
<< std::endl;
return;
}
out_audio_stream->time_base = audio_codec_ctx->time_base;
} else {
audio_codec_ctx = NULL;
out_audio_stream = NULL;
}
if ((ret = av_hwframe_get_buffer(video_codec_ctx->hw_frames_ctx, hw_frame,
0)) < 0) {
cerr << "[VideoEncoder::VideoEncoder] Av_hwframe_get_buffer failed" << endl;
return;
}
if ((ret = avformat_write_header(out_format_ctx, NULL)) < 0) {
cerr << "[VideoEncoder::VideoEncoder] Failed to copy parameters to context"
<< endl;
return;
}
}
VideoEncoder::~VideoEncoder() {
if (hw_frame != NULL) {
av_frame_free(&hw_frame);
}
if (video_codec_ctx != NULL) {
avcodec_close(video_codec_ctx);
avcodec_free_context(&video_codec_ctx);
}
av_buffer_unref(&hw_device_ctx);
if (out_format_ctx != NULL) {
WriteTrailerAndCloseFile();
}
}
int VideoEncoder::EncodeFrame(AVPacket *out_packet, AVFrame *source_frame) {
int ret = 0;
std::array<char, 256> err_buf;
if (source_frame == NULL) {
// std::cerr << __func__ << " Source frame is null" << std::endl;
avcodec_send_frame(video_codec_ctx, NULL);
ret = avcodec_receive_packet(video_codec_ctx, out_packet);
if (ret == 0 && !pts_queue.empty()) {
PtsDts pts = pts_queue.front();
pts_queue.pop();
out_packet->pts = pts.pts;
out_packet->dts = pts.dts;
}
return ret;
}
AVFrame *yuv_frame = source_frame;
if (!hw_frame->hw_frames_ctx) {
std::cerr << "[VideoEncoder::EncodeFrame] Error no memory" << std::endl;
goto Error;
}
if (yuv_frame->format != AV_PIX_FMT_YUV420P) {
yuv_frame = av_frame_alloc();
yuv_frame->width = source_frame->width;
yuv_frame->height = source_frame->height;
yuv_frame->format = AV_PIX_FMT_YUV420P;
yuv_frame->pts = source_frame->pts;
yuv_frame->pkt_dts = source_frame->pkt_dts;
av_frame_get_buffer(yuv_frame, 0);
SwsContext *to_yuv =
sws_getContext(source_frame->width, source_frame->height,
(AVPixelFormat)source_frame->format, source_frame->width,
source_frame->height, AV_PIX_FMT_YUV420P, SWS_BILINEAR,
NULL, NULL, NULL);
sws_scale(to_yuv, source_frame->data, source_frame->linesize, 0,
source_frame->height, yuv_frame->data, yuv_frame->linesize);
sws_freeContext(to_yuv);
}
if ((ret = av_hwframe_transfer_data(hw_frame, yuv_frame, 0)) < 0) {
av_make_error_string(err_buf.data(), 256, ret);
std::cerr
<< "[VideoEncoder::EncodeFrame] Error transfering frame from software "
"to hardware; "
<< ret << "; " << err_buf.data() << std::endl;
if (source_frame != NULL) {
AVPixelFormat *format;
const char *pix_fmt_name =
av_get_pix_fmt_name((AVPixelFormat)source_frame->format);
std::cout << "[VideoEncoder::EncodeFrame] Received format "
<< pix_fmt_name << ", " << source_frame->format << std::endl;
} else {
std::cerr << "[VideoEncoder::EncodeFrame] Source frame was null"
<< std::endl;
}
goto Error;
}
av_init_packet(out_packet);
out_packet->data = NULL;
out_packet->size = 0;
pts_queue.emplace(yuv_frame->pts, yuv_frame->pkt_dts);
if ((ret = avcodec_send_frame(video_codec_ctx, hw_frame)) < 0) {
std::cerr << "[VideoEncoder::EncodeFrame] Error in send frame" << std::endl;
goto Error;
}
if (yuv_frame != source_frame) {
av_frame_free(&yuv_frame);
}
ret = avcodec_receive_packet(video_codec_ctx, out_packet);
if (ret == 0 && !pts_queue.empty()) {
PtsDts pts = pts_queue.front();
pts_queue.pop();
out_packet->pts = pts.pts;
out_packet->dts = pts.dts;
}
return ret;
Error:
return -1;
}
int VideoEncoder::EncodeFrameToFile(AVFrame *source_frame) {
using namespace std;
if (out_format_ctx == NULL) {
cerr << "[VideoEncoder::EncodeFrameToFile] No file opened" << endl;
return -1;
}
int ret = 0;
char err_buf[256];
AVPacket packet;
av_init_packet(&packet);
packet.data = NULL;
packet.size = 0;
ret = EncodeFrame(&packet, source_frame);
if (source_frame == NULL) {
while (ret == 0) {
packet.stream_index = 0;
av_packet_rescale_ts(&packet, input_timebase,
out_video_stream->time_base);
ret = av_interleaved_write_frame(out_format_ctx, &packet);
if (ret < 0) {
cerr
<< "[VideoEncoder::EncodeFrameToFile] Error writing to output file."
<< endl;
return -1;
}
av_packet_unref(&packet);
ret = GetPacket(&packet);
}
return 0;
}
if (ret == 0) {
packet.stream_index = 0;
av_packet_rescale_ts(&packet, input_timebase, out_video_stream->time_base);
ret = av_interleaved_write_frame(out_format_ctx, &packet);
if (ret < 0) {
cerr << "[VideoEncoder::EncodeFrameToFile] Error writing to output file."
<< endl;
return -1;
}
}
return 0;
}
int VideoEncoder::EncodeFrameToFile(AVFrame *source_frame,
AVPacketSideData side_data) {
using namespace std;
if (out_format_ctx == NULL) {
cerr << "[VideoEncoder::EncodeFrameToFile] No file opened" << endl;
return -1;
}
int ret = 0;
char err_buf[256];
AVPacket packet;
av_init_packet(&packet);
packet.data = NULL;
packet.size = 0;
ret = EncodeFrame(&packet, source_frame);
if (ret == 0) {
packet.stream_index = 0;
av_packet_rescale_ts(&packet, input_timebase, out_video_stream->time_base);
cout << "Adding side data to packet: " << side_data.size << endl;
ret = av_packet_add_side_data(&packet, side_data.type, side_data.data,
side_data.size);
if (ret != 0) {
av_make_error_string(err_buf, 256, ret);
cout << "Add side data error " << err_buf << endl;
}
cout << "Side_data_size: " << packet.side_data->size << endl;
ret = av_interleaved_write_frame(out_format_ctx, &packet);
if (ret < 0) {
cerr << "[VideoEncoder::EncodeFrameToFile] Error writing to output file."
<< endl;
return -1;
}
}
return 0;
}
int VideoEncoder::GetPacket(AVPacket *out_packet) {
using namespace std;
int ret = -1;
av_init_packet(out_packet);
out_packet->data = NULL;
out_packet->size = 0;
ret = avcodec_receive_packet(video_codec_ctx, out_packet);
// ret = video_codec_ctx->codec->receive_packet(video_codec_ctx, out_packet);
if (ret == 0 && !pts_queue.empty()) {
PtsDts pts = pts_queue.front();
pts_queue.pop();
out_packet->pts = pts.pts;
out_packet->dts = pts.dts;
}
return ret;
}
int VideoEncoder::SetHWFrameCtx(AVCodecContext *ctx,
AVBufferRef *hw_device_ctx) {
using namespace std;
AVBufferRef *hw_frames_ref;
AVHWFramesContext *frames_ctx = NULL;
int err = 0;
if (!(hw_frames_ref = av_hwframe_ctx_alloc(hw_device_ctx))) {
fprintf(stderr,
"[VideoEncoder::SetHWFrameCtx] Failed to create hw "
"frame context.\n");
return -1;
}
frames_ctx = (AVHWFramesContext *)(hw_frames_ref->data);
frames_ctx->format = AV_PIX_FMT_CUDA;
frames_ctx->sw_format = AV_PIX_FMT_YUV420P;
frames_ctx->width = ctx->width;
frames_ctx->height = ctx->height;
frames_ctx->initial_pool_size = 20;
if ((err = av_hwframe_ctx_init(hw_frames_ref)) < 0) {
cerr << "[VideoEncoder::SetHWFrameCtx] Failed to initialize hw frame "
"context."
<< endl;
av_buffer_unref(&hw_frames_ref);
return err;
}
ctx->hw_frames_ctx = av_buffer_ref(hw_frames_ref);
if (!ctx->hw_frames_ctx) err = AVERROR(ENOMEM);
// av_buffer_unref(&hw_frames_ref);
return err;
}
void VideoEncoder::WriteTrailerAndCloseFile() {
using namespace std;
if (out_format_ctx == NULL) {
cerr << "[VideoEncoder::EncodeFrameToFile] No file opened" << endl;
}
av_write_trailer(out_format_ctx);
avformat_close_input(&out_format_ctx);
}
void VideoEncoder::PrintSupportedPixelFormats() {
using namespace std;
AVPixelFormat *formats;
cout << "Supported Formats: ";
av_hwframe_transfer_get_formats(
hw_frame->hw_frames_ctx, AV_HWFRAME_TRANSFER_DIRECTION_TO, &formats, 0);
for (int i = 0; i < 99 && formats[i] != AV_PIX_FMT_NONE; i++) {
const char *pix_fmt_name = av_get_pix_fmt_name(formats[i]);
cout << pix_fmt_name;
if (formats[i + 1] != AV_PIX_FMT_NONE) {
cout << ", ";
}
}
cout << endl;
free(formats);
}
| 35.967905 | 80 | 0.651388 | AugmentariumLab |
3e01e78f73b43fad156ad659d8806a25f17646b6 | 7,208 | hpp | C++ | client/ui/UIBase.hpp | LoneDev6/MikuMikuOnline_wss-mod | de05011d5b7f0d5492640743c79ae005a832109a | [
"BSD-3-Clause"
] | 6 | 2015-01-03T08:18:16.000Z | 2022-01-22T00:01:23.000Z | client/ui/UIBase.hpp | LoneDev6/MikuMikuOnline_wss-mod | de05011d5b7f0d5492640743c79ae005a832109a | [
"BSD-3-Clause"
] | 1 | 2021-10-03T19:07:56.000Z | 2021-10-03T19:07:56.000Z | client/ui/UIBase.hpp | LoneDev6/MikuMikuOnline_wss-mod | de05011d5b7f0d5492640743c79ae005a832109a | [
"BSD-3-Clause"
] | 1 | 2021-10-03T19:29:40.000Z | 2021-10-03T19:29:40.000Z | //
// UIBase.hpp
//
#pragma once
#include "UISuper.hpp"
#include <v8.h>
#include "../InputManager.hpp"
#include <functional>
using namespace v8;
class ScriptEnvironment;
typedef std::weak_ptr<ScriptEnvironment> ScriptEnvironmentWeakPtr;
class UIBase;
class Input;
typedef std::shared_ptr<UIBase> UIBasePtr;
typedef std::weak_ptr<UIBase> UIBaseWeakPtr;
typedef std::function<void(UIBase*)> CallbackFuncWithThisPointer;
class UIBase : public UISuper {
public:
UIBase();
virtual ~UIBase();
virtual void ProcessInput(InputManager* input);
virtual void Update();
virtual void Draw();
virtual void AsyncUpdate(); // 毎ループ実行する必要のない処理
/* function */
static Handle<Value> Function_addChild(const Arguments& args);
static Handle<Value> Function_removeChild(const Arguments& args);
static Handle<Value> Function_parent(const Arguments& args);
/* property */
static Handle<Value> Property_visible(Local<String> property, const AccessorInfo &info);
static void Property_set_visible(Local<String> property, Local<Value> value, const AccessorInfo& info);
static Handle<Value> Property_width(Local<String> property, const AccessorInfo &info);
static void Property_set_width(Local<String> property, Local<Value> value, const AccessorInfo& info);
static Handle<Value> Property_height(Local<String> property, const AccessorInfo &info);
static void Property_set_height(Local<String> property, Local<Value> value, const AccessorInfo& info);
static Handle<Value> Property_top(Local<String> property, const AccessorInfo &info);
static void Property_set_top(Local<String> property, Local<Value> value, const AccessorInfo& info);
static Handle<Value> Property_left(Local<String> property, const AccessorInfo &info);
static void Property_set_left(Local<String> property, Local<Value> value, const AccessorInfo& info);
static Handle<Value> Property_right(Local<String> property, const AccessorInfo &info);
static void Property_set_right(Local<String> property, Local<Value> value, const AccessorInfo& info);
static Handle<Value> Property_bottom(Local<String> property, const AccessorInfo &info);
static void Property_set_bottom(Local<String> property, Local<Value> value, const AccessorInfo& info);
static Handle<Value> Property_docking(Local<String> property, const AccessorInfo &info);
static void Property_set_docking(Local<String> property, Local<Value> value, const AccessorInfo& info);
/* event */
static Handle<Value> Property_on_click(Local<String> property, const AccessorInfo &info);
static void Property_set_on_click(Local<String> property, Local<Value> value, const AccessorInfo& info);
Handle<Object> parent() const;
void set_parent(const Handle<Object>& parent);
UIBasePtr parent_c() const;
void set_parent_c(const UIBasePtr &parent_c);
Input* input_adpator() const;
void set_input_adaptor(Input * adaptor);
size_t children_size() const;
template<class T>
static void SetObjectTemplate(const std::string& classname,
Handle<ObjectTemplate>* object);
template<class F>
static void SetFunction(Handle<ObjectTemplate>* object, const std::string& name, F func);
template<class G, class S>
static void SetProperty(Handle<ObjectTemplate>* object, const std::string& name, G getter, S setter);
template<class T>
static void SetConstant(Handle<ObjectTemplate>* object, const std::string& name, T value);
public:
static void DefineInstanceTemplate(Handle<ObjectTemplate>* object);
protected:
virtual void UpdatePosition();
void ProcessInputChildren(InputManager* input);
void UpdateChildren();
void DrawChildren();
void AsyncUpdateChildren();
virtual void UpdateBaseImage();
void GetParam(const Handle<Object>& object, const std::string& name, int* value);
void GetParam(const Handle<Object>& object, const std::string& name, bool* value);
void GetParam(const Handle<Object>& object, const std::string& name, std::string* value);
void Focus();
public:
/* Property */
template<class F>
void set_on_click_function_(F function);
template<class F>
void set_on_hover_function_(F function);
template<class F>
void set_on_out_function_(F function);
protected:
Persistent<Object> parent_;
std::vector<Persistent<Object>> children_;
Persistent<Function> on_click_;
CallbackFuncWithThisPointer on_click_function_;
CallbackFuncWithThisPointer on_hover_function_;
CallbackFuncWithThisPointer on_out_function_;
bool hover_flag_;
/*C++からクラスを伝達するためのメンバ*/
UIBasePtr parent_c_;
Input* input_adaptor_;
};
//inline void Destruct(Persistent<Value> handle, void* parameter) {
inline void Destruct(Isolate* isolate,Persistent<Value> handle, void* parameter) {
auto instance = static_cast<UIBasePtr*>(parameter);
delete instance;
handle.Dispose();
}
template<class T>
Handle<Value> Construct(const Arguments& args) {
UIBasePtr* instance = new UIBasePtr(new T());
Local<v8::Object> thisObject = args.This();
assert(thisObject->InternalFieldCount() > 0);
thisObject->SetInternalField(0, External::New(instance));
Persistent<v8::Object> holder = Persistent<v8::Object>::New(thisObject);
// holder.MakeWeak(instance, Destruct);
holder.MakeWeak(Isolate::GetCurrent(),instance, Destruct); // ※ V8のバージョンを上げるために変更
return thisObject;
}
template<class T>
void UIBase::SetObjectTemplate(const std::string& classname,
Handle<ObjectTemplate>* object)
{
auto func = FunctionTemplate::New(Construct<T>);
func->SetClassName(String::New(classname.c_str()));
auto instance_template = func->InstanceTemplate();
instance_template->SetInternalFieldCount(1);
T::DefineInstanceTemplate(&instance_template);
(*object)->Set(String::New(("_" + classname).c_str()), func,
PropertyAttribute(ReadOnly));
}
template<class F>
void UIBase::SetFunction(Handle<ObjectTemplate>* object, const std::string& name, F func)
{
Handle<ObjectTemplate>& instance_template = *object;
instance_template->Set(String::New(name.c_str()), FunctionTemplate::New(func));
}
template<class G, class S>
void UIBase::SetProperty(Handle<ObjectTemplate>* object, const std::string& name, G getter, S setter)
{
Handle<ObjectTemplate>& instance_template = *object;
instance_template->SetAccessor(String::New(name.c_str()), getter, setter);
}
template<class T>
void UIBase::SetConstant(Handle<ObjectTemplate>* object, const std::string& name, T value)
{
Handle<ObjectTemplate>& instance_template = *object;
instance_template->Set(String::New(name.c_str()), value);
}
template<class F>
void UIBase::set_on_click_function_(F function)
{
on_click_function_ = function;
}
template<class F>
void UIBase::set_on_hover_function_(F function)
{
on_hover_function_ = function;
}
template<class F>
void UIBase::set_on_out_function_(F function)
{
on_out_function_ = function;
} | 35.683168 | 112 | 0.720172 | LoneDev6 |
3e02918fea0f5319730bcb9858404f2221358db1 | 2,959 | cpp | C++ | tests/unit/watchtower/error_cache_test.cpp | EnrikoChavez/opencbdc-tx | 3f4ebe9fa8296542158ff505b47fd8f277e313dd | [
"MIT"
] | 652 | 2022-02-03T19:31:04.000Z | 2022-03-31T17:45:29.000Z | tests/unit/watchtower/error_cache_test.cpp | EnrikoChavez/opencbdc-tx | 3f4ebe9fa8296542158ff505b47fd8f277e313dd | [
"MIT"
] | 50 | 2022-02-03T23:16:36.000Z | 2022-03-31T19:50:19.000Z | tests/unit/watchtower/error_cache_test.cpp | EnrikoChavez/opencbdc-tx | 3f4ebe9fa8296542158ff505b47fd8f277e313dd | [
"MIT"
] | 116 | 2022-02-03T19:57:26.000Z | 2022-03-20T17:23:47.000Z | // Copyright (c) 2021 MIT Digital Currency Initiative,
// Federal Reserve Bank of Boston
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "uhs/atomizer/watchtower/error_cache.hpp"
#include "uhs/atomizer/watchtower/tx_error_messages.hpp"
#include <gtest/gtest.h>
class error_cache_test : public ::testing::Test {
protected:
void SetUp() override {
std::vector<cbdc::watchtower::tx_error> errs{
{cbdc::watchtower::tx_error{
{'t', 'x', 'a'},
cbdc::watchtower::tx_error_inputs_dne{
{{'u', 'h', 's', 'a'}, {'u', 'h', 's', 'b'}}}},
cbdc::watchtower::tx_error{
{'t', 'x', 'b'},
cbdc::watchtower::tx_error_stxo_range{}},
cbdc::watchtower::tx_error{{'t', 'x', 'c'},
cbdc::watchtower::tx_error_sync{}},
cbdc::watchtower::tx_error{
{'t', 'x', 'd'},
cbdc::watchtower::tx_error_inputs_spent{
{{'u', 'h', 's', 'c'}, {'u', 'h', 's', 'd'}}}}}};
m_ec.push_errors(std::move(errs));
}
cbdc::watchtower::error_cache m_ec{4};
};
TEST_F(error_cache_test, no_errors) {
ASSERT_FALSE(m_ec.check_tx_id({'Z'}).has_value());
ASSERT_FALSE(m_ec.check_uhs_id({'Z'}).has_value());
}
TEST_F(error_cache_test, add_k_plus_1) {
ASSERT_TRUE(m_ec.check_tx_id({'t', 'x', 'a'}).has_value());
ASSERT_TRUE(m_ec.check_uhs_id({'u', 'h', 's', 'a'}).has_value());
ASSERT_TRUE(m_ec.check_uhs_id({'u', 'h', 's', 'b'}).has_value());
ASSERT_TRUE(m_ec.check_tx_id({'t', 'x', 'b'}).has_value());
ASSERT_TRUE(m_ec.check_tx_id({'t', 'x', 'c'}).has_value());
ASSERT_TRUE(m_ec.check_tx_id({'t', 'x', 'd'}).has_value());
ASSERT_TRUE(m_ec.check_uhs_id({'u', 'h', 's', 'c'}).has_value());
ASSERT_TRUE(m_ec.check_uhs_id({'u', 'h', 's', 'd'}).has_value());
m_ec.push_errors({cbdc::watchtower::tx_error{
{'t', 'x', 'e'},
cbdc::watchtower::tx_error_inputs_spent{
{{'u', 'h', 's', 'e'}, {'u', 'h', 's', 'f'}}}}});
ASSERT_TRUE(m_ec.check_tx_id({'t', 'x', 'e'}).has_value());
ASSERT_TRUE(m_ec.check_uhs_id({'u', 'h', 's', 'e'}).has_value());
ASSERT_TRUE(m_ec.check_uhs_id({'u', 'h', 's', 'f'}).has_value());
ASSERT_TRUE(m_ec.check_tx_id({'t', 'x', 'b'}).has_value());
ASSERT_TRUE(m_ec.check_tx_id({'t', 'x', 'c'}).has_value());
ASSERT_TRUE(m_ec.check_tx_id({'t', 'x', 'd'}).has_value());
ASSERT_TRUE(m_ec.check_uhs_id({'u', 'h', 's', 'c'}).has_value());
ASSERT_TRUE(m_ec.check_uhs_id({'u', 'h', 's', 'd'}).has_value());
ASSERT_FALSE(m_ec.check_tx_id({'t', 'x', 'a'}).has_value());
ASSERT_FALSE(m_ec.check_uhs_id({'u', 'h', 's', 'a'}).has_value());
ASSERT_FALSE(m_ec.check_uhs_id({'u', 'h', 's', 'b'}).has_value());
}
| 44.164179 | 75 | 0.558297 | EnrikoChavez |
3e068924620de9486e0a8e14f90b29bf809b5b26 | 1,428 | hpp | C++ | Utility/VLTree/HydraGame/a_Body.hpp | p-adic/cpp | 9404a08f26c55a19c53ab0a11edb70f3ed6a8e3c | [
"MIT"
] | 2 | 2020-09-13T07:31:22.000Z | 2022-03-26T08:37:32.000Z | Utility/VLTree/HydraGame/a_Body.hpp | p-adic/cpp | 9404a08f26c55a19c53ab0a11edb70f3ed6a8e3c | [
"MIT"
] | null | null | null | Utility/VLTree/HydraGame/a_Body.hpp | p-adic/cpp | 9404a08f26c55a19c53ab0a11edb70f3ed6a8e3c | [
"MIT"
] | null | null | null | // c:/Users/user/Documents/Programming/Utility/VLTree/HydraGame/a_Body.hpp
#pragma once
#include "../a_Body.hpp"
template <typename T>
void CutHydra( VLSubTree<T>& t , const uint& n )
{
if( t.IsLeaf() ){
ERR_CALL;
}
VLSubTree<T> t0 = t.RightMostSubTree();
if( t0.IsLeaf() ){
t.pop_back();
} else {
VLSubTree<T> t1 = t0.RightMostSubTree();
if( t1.IsLeaf() ){
t0.pop_back();
for( uint i = 0 ; i < n ; i++ ){
t.push_back( t0 );
}
} else {
CutHydra( t0 , n );
}
}
return;
}
template <typename T>
uint KillHydra( VLTree<T>& t , uint& n , const uint& incr )
{
string s = to_string( t );
s += "[n]";
cout << s << endl;
while( KillHydra_Body( t , n ) ){
cout << "[" << n << "]" << endl;
n += incr;
}
return n;
}
template <typename T>
void KillHydra( VLTree<T>& t )
{
string s = to_string( t );
s += "[n]";
cout << s << endl;
uint n = 0;
cout << "n = ";
cin >> n;
while( KillHydra_Body( t , n ) && n != 691){
cout << "[" << n << "][n]" << endl;
cout << "n = ";
cin >> n;
}
return;
}
template <typename T>
bool KillHydra_Body( VLTree<T>& t , const uint& n )
{
if( t.IsLeaf() ){
return false;
}
CutHydra( t , n );
cout << to_string( t );
return true;
}
| 12.981818 | 75 | 0.465686 | p-adic |
3e0ea51a9742e9ee27272a85e2e2eaeedde464ed | 1,791 | hpp | C++ | galaxy/src/galaxy/input/Mouse.hpp | reworks/rework | 90508252c9a4c77e45a38e7ce63cfd99f533f42b | [
"Apache-2.0"
] | 6 | 2018-07-21T20:37:01.000Z | 2018-10-31T01:49:35.000Z | galaxy/src/galaxy/input/Mouse.hpp | reworks/rework | 90508252c9a4c77e45a38e7ce63cfd99f533f42b | [
"Apache-2.0"
] | null | null | null | galaxy/src/galaxy/input/Mouse.hpp | reworks/rework | 90508252c9a4c77e45a38e7ce63cfd99f533f42b | [
"Apache-2.0"
] | null | null | null | ///
/// Mouse.hpp
/// galaxy
///
/// Refer to LICENSE.txt for more details.
///
#ifndef GALAXY_INPUT_MOUSE_HPP_
#define GALAXY_INPUT_MOUSE_HPP_
#include <glm/vec2.hpp>
#include "galaxy/input/InputDevice.hpp"
namespace galaxy
{
namespace input
{
///
/// Physical mouse device and state management.
///
class Mouse final : public InputDevice
{
friend class core::Window;
public:
///
/// \brief Enum class representing mouse buttons.
///
/// Values used are based off of GLFW.
///
enum class Buttons : int
{
UNKNOWN = -1,
BTN_1 = 0,
BTN_2 = 1,
BTN_3 = 2,
BTN_4 = 3,
BTN_5 = 4,
BTN_6 = 5,
BTN_7 = 6,
BTN_8 = 7,
BTN_LAST = BTN_8,
BTN_LEFT = BTN_1,
BTN_RIGHT = BTN_2,
BTN_MIDDLE = BTN_3
};
///
/// Destructor.
///
virtual ~Mouse() noexcept = default;
///
/// \brief Enable sticky mouse.
///
/// The pollable state of a nouse button will remain pressed until the state of that button is polled.
///
void enable_sticky_mouse() noexcept;
///
/// Disable sticky mouse.
///
void disable_sticky_mouse() noexcept;
///
/// Get last recorded mouse position.
///
/// \return XY vector position of cursor.
///
[[nodiscard]] glm::dvec2 get_pos() noexcept;
private:
///
/// Constructor.
///
Mouse() noexcept;
///
/// Move constructor.
///
Mouse(Mouse&&) = delete;
///
/// Move assignment operator.
///
Mouse& operator=(Mouse&&) = delete;
///
/// Copy constructor.
///
Mouse(const Mouse&) = delete;
///
/// Copy assignment operator.
///
Mouse& operator=(const Mouse&) = delete;
};
} // namespace input
} // namespace galaxy
#endif | 17.558824 | 105 | 0.564489 | reworks |
3e0f99001035521eca0535e341d247d24db03c45 | 7,115 | hpp | C++ | third_party/misc/def/def/defrCallBacks.hpp | jesec/livehd | 1a82dbea1d86dbd1511de588609de320aa4ef6ed | [
"BSD-3-Clause"
] | 115 | 2019-09-28T13:39:41.000Z | 2022-03-24T11:08:53.000Z | third_party/misc/def/def/defrCallBacks.hpp | jesec/livehd | 1a82dbea1d86dbd1511de588609de320aa4ef6ed | [
"BSD-3-Clause"
] | 120 | 2018-05-16T23:11:09.000Z | 2019-09-25T18:52:49.000Z | third_party/misc/def/def/defrCallBacks.hpp | jesec/livehd | 1a82dbea1d86dbd1511de588609de320aa4ef6ed | [
"BSD-3-Clause"
] | 44 | 2019-09-28T07:53:21.000Z | 2022-02-13T23:21:12.000Z | // *****************************************************************************
// *****************************************************************************
// Copyright 2013, Cadence Design Systems
//
// This file is part of the Cadence LEF/DEF Open Source
// Distribution, Product Version 5.8.
//
// 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.
//
// For updates, support, or to become part of the LEF/DEF Community,
// check www.openeda.org for details.
//
// $Author: dell $
// $Revision: #1 $
// $Date: 2017/06/06 $
// $State: $
// *****************************************************************************
// *****************************************************************************
#ifndef DEFRCALLBACKS_H
#define DEFRCALLBACKS_H 1
#include "defiKRDefs.hpp"
#include "defrReader.hpp"
BEGIN_LEFDEF_PARSER_NAMESPACE
class defrCallbacks {
public:
defrCallbacks();
void SetUnusedCallbacks(defrVoidCbkFnType f);
defrStringCbkFnType DesignCbk;
defrStringCbkFnType TechnologyCbk;
defrVoidCbkFnType DesignEndCbk;
defrPropCbkFnType PropCbk;
defrVoidCbkFnType PropDefEndCbk;
defrVoidCbkFnType PropDefStartCbk;
defrStringCbkFnType ArrayNameCbk;
defrStringCbkFnType FloorPlanNameCbk;
defrDoubleCbkFnType UnitsCbk;
defrStringCbkFnType DividerCbk;
defrStringCbkFnType BusBitCbk;
defrSiteCbkFnType SiteCbk;
defrSiteCbkFnType CanplaceCbk;
defrSiteCbkFnType CannotOccupyCbk;
defrIntegerCbkFnType ComponentStartCbk;
defrVoidCbkFnType ComponentEndCbk;
defrComponentCbkFnType ComponentCbk;
defrComponentMaskShiftLayerCbkFnType ComponentMaskShiftLayerCbk;
defrIntegerCbkFnType NetStartCbk;
defrVoidCbkFnType NetEndCbk;
defrNetCbkFnType NetCbk;
defrStringCbkFnType NetNameCbk;
defrStringCbkFnType NetSubnetNameCbk;
defrStringCbkFnType NetNonDefaultRuleCbk;
defrNetCbkFnType NetPartialPathCbk;
defrPathCbkFnType PathCbk;
defrDoubleCbkFnType VersionCbk;
defrStringCbkFnType VersionStrCbk;
defrStringCbkFnType PinExtCbk;
defrStringCbkFnType ComponentExtCbk;
defrStringCbkFnType ViaExtCbk;
defrStringCbkFnType NetConnectionExtCbk;
defrStringCbkFnType NetExtCbk;
defrStringCbkFnType GroupExtCbk;
defrStringCbkFnType ScanChainExtCbk;
defrStringCbkFnType IoTimingsExtCbk;
defrStringCbkFnType PartitionsExtCbk;
defrStringCbkFnType HistoryCbk;
defrBoxCbkFnType DieAreaCbk;
defrPinCapCbkFnType PinCapCbk;
defrPinCbkFnType PinCbk;
defrIntegerCbkFnType StartPinsCbk;
defrVoidCbkFnType PinEndCbk;
defrIntegerCbkFnType DefaultCapCbk;
defrRowCbkFnType RowCbk;
defrTrackCbkFnType TrackCbk;
defrGcellGridCbkFnType GcellGridCbk;
defrIntegerCbkFnType ViaStartCbk;
defrVoidCbkFnType ViaEndCbk;
defrViaCbkFnType ViaCbk;
defrIntegerCbkFnType RegionStartCbk;
defrVoidCbkFnType RegionEndCbk;
defrRegionCbkFnType RegionCbk;
defrIntegerCbkFnType SNetStartCbk;
defrVoidCbkFnType SNetEndCbk;
defrNetCbkFnType SNetCbk;
defrNetCbkFnType SNetPartialPathCbk;
defrNetCbkFnType SNetWireCbk;
defrIntegerCbkFnType GroupsStartCbk;
defrVoidCbkFnType GroupsEndCbk;
defrStringCbkFnType GroupNameCbk;
defrStringCbkFnType GroupMemberCbk;
defrGroupCbkFnType GroupCbk;
defrIntegerCbkFnType AssertionsStartCbk;
defrVoidCbkFnType AssertionsEndCbk;
defrAssertionCbkFnType AssertionCbk;
defrIntegerCbkFnType ConstraintsStartCbk;
defrVoidCbkFnType ConstraintsEndCbk;
defrAssertionCbkFnType ConstraintCbk;
defrIntegerCbkFnType ScanchainsStartCbk;
defrVoidCbkFnType ScanchainsEndCbk;
defrScanchainCbkFnType ScanchainCbk;
defrIntegerCbkFnType IOTimingsStartCbk;
defrVoidCbkFnType IOTimingsEndCbk;
defrIOTimingCbkFnType IOTimingCbk;
defrIntegerCbkFnType FPCStartCbk;
defrVoidCbkFnType FPCEndCbk;
defrFPCCbkFnType FPCCbk;
defrIntegerCbkFnType TimingDisablesStartCbk;
defrVoidCbkFnType TimingDisablesEndCbk;
defrTimingDisableCbkFnType TimingDisableCbk;
defrIntegerCbkFnType PartitionsStartCbk;
defrVoidCbkFnType PartitionsEndCbk;
defrPartitionCbkFnType PartitionCbk;
defrIntegerCbkFnType PinPropStartCbk;
defrVoidCbkFnType PinPropEndCbk;
defrPinPropCbkFnType PinPropCbk;
defrIntegerCbkFnType CaseSensitiveCbk;
defrIntegerCbkFnType BlockageStartCbk;
defrVoidCbkFnType BlockageEndCbk;
defrBlockageCbkFnType BlockageCbk;
defrIntegerCbkFnType SlotStartCbk;
defrVoidCbkFnType SlotEndCbk;
defrSlotCbkFnType SlotCbk;
defrIntegerCbkFnType FillStartCbk;
defrVoidCbkFnType FillEndCbk;
defrFillCbkFnType FillCbk;
defrIntegerCbkFnType NonDefaultStartCbk;
defrVoidCbkFnType NonDefaultEndCbk;
defrNonDefaultCbkFnType NonDefaultCbk;
defrIntegerCbkFnType StylesStartCbk;
defrVoidCbkFnType StylesEndCbk;
defrStylesCbkFnType StylesCbk;
defrStringCbkFnType ExtensionCbk;
};
END_LEFDEF_PARSER_NAMESPACE
USE_LEFDEF_PARSER_NAMESPACE
#endif
| 45.903226 | 80 | 0.581588 | jesec |
3e14095a07a869c7851dcaece44d3a89081e1964 | 7,634 | cpp | C++ | Umbrella-Engine/Graphics/SDLWindow.cpp | jfla-fan/JFla-Engine | dcbdcdff815fd1729bed35ec556b850cc94f6553 | [
"MIT"
] | null | null | null | Umbrella-Engine/Graphics/SDLWindow.cpp | jfla-fan/JFla-Engine | dcbdcdff815fd1729bed35ec556b850cc94f6553 | [
"MIT"
] | null | null | null | Umbrella-Engine/Graphics/SDLWindow.cpp | jfla-fan/JFla-Engine | dcbdcdff815fd1729bed35ec556b850cc94f6553 | [
"MIT"
] | null | null | null | #include <OpenImageIO/imageio.h>
#include "../Image/ImageLoader.h"
#include "../Image/ImageUtils.h"
#include "SDLWindow.h"
#include <array>
#include <vector>
namespace J::Graphics
{
JSDLWindow::JSDLWindow(const SWindowCreateOptions& InOptions)
: options(InOptions), bIsOpened(false), window(nullptr, [](WindowHandle* window) {})
{
OnCreate(InOptions);
}
JSDLWindow::~JSDLWindow()
{
OnDestroy();
}
// examples of simple shaders
const std::string& VertexShader = R"(
#version 450 core
in vec3 inPosition;
in vec3 inColor;
in vec2 inTexCoords;
out vec3 outColor;
out vec2 outTexCoords;
void main()
{
gl_Position = vec4(inPosition, 1.0);
outColor = inColor;
outTexCoords = inTexCoords;
}
)";
const std::string& FragmentShader = R"(
#version 450 core
in vec3 outColor;
in vec2 outTexCoords;
uniform sampler2D sampler1;
uniform sampler2D sampler2;
void main()
{
gl_FragColor = max(texture(sampler1, outTexCoords), texture(sampler2, outTexCoords));
//gl_FragColor = texture(sampler1, outTexCoords);
//gl_FragColor = texture(sampler2, outTexCoords);
}
)";
//static std::map<Utils::ERawImageFormat, EGLDataType> ImageFormatToGLDataTypeTable =
//{
// { }
//}
void JSDLWindow::OnCreate(const SWindowCreateOptions& InOptions)
{
window = Scope<WindowHandle, DestroyWindowCallback>
(
SDL_CreateWindow
(
options.title.c_str(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
options.width, options.height, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE
),
[](WindowHandle* handle) { SDL_DestroyWindow(handle); }
);
// #todo set time when the window was created.
context = GraphicsContext::Create(window.get());
bIsOpened = true;
glViewport(0, 0, options.width, options.height);
const Math::LinearColor& yellow = Math::LinearColor::Yellow;
// rectangle
RECT_VAO = MakeRef<OpenGLVertexArray>();
// rectangle coordinates and color
// position // color
Vertices[0] = { Vector3 {0.5f, 0.5f, 0.f}, Vector3 {1.0f, 0.0f, 0.0f} };
Vertices[1] = { Vector3 {-0.5f, 0.5f, 0.f}, Vector3 {0.0f, 1.0f, 0.0f} };
Vertices[2] = { Vector3 {-0.5f, -0.5f, 0.f}, Vector3 {0.0f, 0.0f, 1.0f} };
Vertices[3] = { Vector3 {0.5f, -0.5f, 0.f}, Vector3 { yellow.R(), yellow.G(), yellow.B() } };
const std::string ImagePath = "C:/Users/ДНС/Documents/Projects/VisualStudioProjects/GameEngine/Resources/Images/sleepy-cat.jpg";
const std::string DendyImagePath = "C:/Users/ДНС/Documents/Projects/VisualStudioProjects/GameEngine/Resources/Images/dendy.png";
const std::string SaveImagePath = "C:/Users/ДНС/Documents/Projects/VisualStudioProjects/GameEngine/Resources/Images/flipped-sleepy-cat.jpg";
Utils::ImagePtr image = Utils::ImageLoader::Load(ImagePath, true);
if (!image)
{
std::cout << std::format("Could not load {} image.\n", ImagePath);
std::exit(EXIT_FAILURE);
}
image->PrintImageMetaData(std::cout);
Utils::ImagePtr dendyImage = Utils::ImageLoader::Load(DendyImagePath, true);
if (!dendyImage)
{
std::cout << std::format("Could not load {} image.\n", DendyImagePath);
std::exit(EXIT_FAILURE);
}
dendyImage->PrintImageMetaData(std::cout);
//glGenTextures(1, &TextureID);
//glGenTextures(1, &texture2);
//glActiveTexture(GL_TEXTURE0);
//glBindTexture(GL_TEXTURE_2D, TextureID);
//glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, dendyImage->GetWidth(), dendyImage->GetHeight(), 0, GL_RGB, GL_UNSIGNED_BYTE, dendyImage->RawData());
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
////glTextureParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, color);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_NEAREST);
//glGenerateMipmap(GL_TEXTURE_2D);
////glBindTexture(GL_TEXTURE_2D, 0);
//glActiveTexture(GL_TEXTURE0 + 1);
//glBindTexture(GL_TEXTURE_2D, texture2);
//glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, image->GetWidth(), image->GetHeight(), 0, GL_RGB8, GL_UNSIGNED_BYTE, image->RawData());
//
//float color[] = { 1.0f, 0.0f, 0.0f, 1.0f };
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
////glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, color);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_NEAREST);
//glGenerateMipmap(GL_TEXTURE_2D);
RECT_TEXTURE1 = MakeRef<OpenGLTexture>();
RECT_TEXTURE2 = MakeRef<OpenGLTexture>();
if (!RECT_TEXTURE1->Load(*image))
{
std::cout << "Failed to load texture\n";
std::exit(1);
}
if (!RECT_TEXTURE2->Load(*dendyImage))
{
std::cout << "Failed to load texture\n";
std::exit(1);
}
image.reset();
dendyImage.reset();
RECT_VBO = OpenGLVertexBuffer::Create(
new float[]
{
// position // color // uv - texture coordinates
0.5f, 0.5f, 0.f, 1.0f, 0.0f, 0.0f, /* red */ 1.0f, 1.0f,
-0.5f, 0.5f, 0.f, 0.0f, 1.0f, 0.0f, /* green */ 0.0f, 1.0f,
-0.5f, -0.5f, 0.f, 0.0f, 0.0f, 1.0f, /* blue */ 0.0f, 0.0f,
0.5f, -0.5f, 0.f, yellow.R(), yellow.G(), yellow.B(), 1.0f, 0.0f,
},
8 * 4
);
// index buffer
RECT_IBO = OpenGLIndexBuffer::Create(
new uint32[]
{
0, 1, 2,
3, 0, 2
},
6,
GpuApi::EBufferAccessBits::ALL
);
RECT_VAO->AddVertexLayout(RECT_VBO,
std::array
{
SVertexAttribute::GetAttribute<Vector3>(),
SVertexAttribute::GetAttribute<Vector3>(),
SVertexAttribute::GetAttribute<Vector2>()
}
);
// disable color attribute
// this should result in a black square (square without color) [to enable add true to every attribute in constructor]
RECT_VAO->RemoveVertexLayout(
std::array
{
SVertexAttribute::GetAttribute<Vector3>(),
SVertexAttribute::GetAttribute<Vector3>(),
}
);
// Dealing with shaders
SHADER = MakeRef<OpenGLShader>();
SHADER->LoadFromString(VertexShader, FragmentShader);
/*glUniform1i(glGetUniformLocation(SHADER->GetHandle(), "samp"), 0);
glUniform1i(glGetUniformLocation(SHADER->GetHandle(), "cat"), 1);*/
GraphicsContext::BindShader(*SHADER);
RECT_TEXTURE1->Bind(0);
RECT_TEXTURE2->Bind(1);
SHADER->SetUniform("sampler1", 0);
SHADER->SetUniform("sampler2", 1);
//SHADER->SetUniform("sampler2", 1);
}
void JSDLWindow::OnUpdate()
{
SDL_Event e;
while (SDL_PollEvent(&e))
{
// dispatch every event using event dispatcher.
// all the callbacks should be invoked in application class
// using event dispatcher
if (e.type == SDL_QUIT)
{
std::cout << "quit";
this->Close();
std::exit(0);
}
}
}
void JSDLWindow::OnRender()
{
/*GraphicsContext::ClearColor(Math::LinearColor::Blue);
GraphicsContext::Clear();*/
const float color[] = { 0.2f, 0.5f, 0.7f, 1.0f };
glClearBufferfv(GL_COLOR, 0, color);
// draw something with OpenGL here
RECT_VAO->Bind();
//glDrawArrays(GL_POINTS, 0, 3);
GraphicsContext::DrawElements(EGLPrimitiveType::TRIANGLES, *RECT_IBO); // instead of graphics context here will be used renderer
GraphicsContext::SwapBuffers(window.get());
}
void JSDLWindow::OnDestroy()
{
this->Close();
}
void JSDLWindow::Close()
{
if (bIsOpened)
{
std::cout << "Releasing resource\n";
window.reset();
bIsOpened = false;
}
}
}
| 26.233677 | 144 | 0.680639 | jfla-fan |
3e192b7bc7c7109250b95f60e59ff653a775bbc6 | 367 | cxx | C++ | Algorithms/Strings/beautiful-binary-string.cxx | will-crawford/HackerRank | 74965480ee6a51603eb320e5982b0943fdaf1302 | [
"MIT"
] | null | null | null | Algorithms/Strings/beautiful-binary-string.cxx | will-crawford/HackerRank | 74965480ee6a51603eb320e5982b0943fdaf1302 | [
"MIT"
] | null | null | null | Algorithms/Strings/beautiful-binary-string.cxx | will-crawford/HackerRank | 74965480ee6a51603eb320e5982b0943fdaf1302 | [
"MIT"
] | null | null | null | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int n; cin >> n; string s, needle = "010"; cin >> s; int changes = 0;
for ( string::size_type p = 0, q = string::npos; ( p = s.find ( needle, p ) ) != q; p += 3, ++changes )
;
cout << changes << endl;
return 0;
}
| 22.9375 | 107 | 0.566757 | will-crawford |
3e1bdee67edb08fffcaa80562d57b36e7a17f7ca | 6,580 | inl | C++ | include/ffsm2/detail/structure/composite.inl | linuxxiaolei/FFSM2 | d432e2ea361d81c69638a931ad821e7a7e47e748 | [
"MIT"
] | 1 | 2021-01-28T14:54:32.000Z | 2021-01-28T14:54:32.000Z | include/ffsm2/detail/structure/composite.inl | linuxxiaolei/FFSM2 | d432e2ea361d81c69638a931ad821e7a7e47e748 | [
"MIT"
] | null | null | null | include/ffsm2/detail/structure/composite.inl | linuxxiaolei/FFSM2 | d432e2ea361d81c69638a931ad821e7a7e47e748 | [
"MIT"
] | null | null | null | namespace ffsm2 {
namespace detail {
////////////////////////////////////////////////////////////////////////////////
template <typename TA, typename TH, typename... TS>
bool
C_<TA, TH, TS...>::deepForwardEntryGuard(GuardControl& control) noexcept {
FFSM2_ASSERT(control._registry.active != INVALID_SHORT);
const Short requested = control._registry.requested;
FFSM2_ASSERT(requested != INVALID_SHORT);
return _subStates.wideEntryGuard(control, requested);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
template <typename TA, typename TH, typename... TS>
bool
C_<TA, TH, TS...>::deepEntryGuard(GuardControl& control) noexcept {
const Short requested = control._registry.requested;
FFSM2_ASSERT(requested != INVALID_SHORT);
return _headState.deepEntryGuard(control) ||
_subStates.wideEntryGuard(control, requested);
}
//------------------------------------------------------------------------------
template <typename TA, typename TH, typename... TS>
void
C_<TA, TH, TS...>::deepConstruct(PlanControl& control) noexcept {
Short& active = control._registry.active;
Short& requested = control._registry.requested;
FFSM2_ASSERT(active == INVALID_SHORT);
FFSM2_ASSERT(requested != INVALID_SHORT);
active = requested;
requested = INVALID_SHORT;
_headState.deepConstruct(control);
_subStates.wideConstruct(control, active);
}
//------------------------------------------------------------------------------
template <typename TA, typename TH, typename... TS>
void
C_<TA, TH, TS...>::deepEnter(PlanControl& control) noexcept {
const Short active = control._registry.active;
FFSM2_ASSERT(active != INVALID_SHORT);
FFSM2_ASSERT(control._registry.requested == INVALID_SHORT);
_headState.deepEnter(control);
_subStates.wideEnter(control, active);
}
//------------------------------------------------------------------------------
template <typename TA, typename TH, typename... TS>
void
C_<TA, TH, TS...>::deepUpdate(FullControl& control) noexcept {
const Short active = control._registry.active;
FFSM2_ASSERT(active != INVALID_SHORT);
FFSM2_ASSERT(control._registry.requested == INVALID_SHORT);
if (_headState.deepUpdate(control)) {
ControlLock lock{control};
_subStates.wideUpdate(control, active);
} else {
FFSM2_IF_PLANS(const Status subStatus =)
_subStates.wideUpdate(control, active);
#ifdef FFSM2_ENABLE_PLANS
if (subStatus && control._planData.planExists)
control.updatePlan(_headState, subStatus);
#endif
}
}
//------------------------------------------------------------------------------
template <typename TA, typename TH, typename... TS>
template <typename TEvent>
void
C_<TA, TH, TS...>::deepReact(FullControl& control,
const TEvent& event) noexcept
{
const Short active = control._registry.active;
FFSM2_ASSERT(active != INVALID_SHORT);
FFSM2_ASSERT(control._registry.requested == INVALID_SHORT);
if (_headState.deepReact(control, event)) {
ControlLock lock{control};
_subStates.wideReact(control, event, active);
} else {
FFSM2_IF_PLANS(const Status subStatus =)
_subStates.wideReact(control, event, active);
#ifdef FFSM2_ENABLE_PLANS
if (subStatus && control._planData.planExists)
control.updatePlan(_headState, subStatus);
#endif
}
}
//------------------------------------------------------------------------------
template <typename TA, typename TH, typename... TS>
bool
C_<TA, TH, TS...>::deepForwardExitGuard(GuardControl& control) noexcept {
FFSM2_ASSERT(control._registry.requested != INVALID_SHORT);
const Short active = control._registry.active;
FFSM2_ASSERT(active != INVALID_SHORT);
return _subStates.wideExitGuard(control, active);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
template <typename TA, typename TH, typename... TS>
bool
C_<TA, TH, TS...>::deepExitGuard(GuardControl& control) noexcept {
const Short active = control._registry.active;
FFSM2_ASSERT(active != INVALID_SHORT);
FFSM2_ASSERT(control._registry.requested != INVALID_SHORT);
return _headState.deepExitGuard(control) ||
_subStates.wideExitGuard(control, active);
}
//------------------------------------------------------------------------------
template <typename TA, typename TH, typename... TS>
void
C_<TA, TH, TS...>::deepExit(PlanControl& control) noexcept {
const Short active = control._registry.active;
FFSM2_ASSERT(active != INVALID_SHORT);
_subStates.wideExit(control, active);
_headState.deepExit(control);
}
//------------------------------------------------------------------------------
template <typename TA, typename TH, typename... TS>
void
C_<TA, TH, TS...>::deepDestruct(PlanControl& control) noexcept {
Short& active = control._registry.active;
FFSM2_ASSERT(active != INVALID_SHORT);
_subStates.wideDestruct(control, active);
_headState.deepDestruct(control);
active = INVALID_SHORT;
#ifdef FFSM2_ENABLE_PLANS
auto plan = control.plan();
plan.clear();
#endif
}
//------------------------------------------------------------------------------
// COMMON
template <typename TA, typename TH, typename... TS>
void
C_<TA, TH, TS...>::deepChangeToRequested(PlanControl& control) noexcept {
Short& active = control._registry.active;
Short& requested = control._registry.requested;
FFSM2_ASSERT(active != INVALID_SHORT);
FFSM2_ASSERT(requested != INVALID_SHORT);
if (requested != active) {
_subStates.wideExit (control, active);
_subStates.wideDestruct (control, active);
active = requested;
requested = INVALID_SHORT;
_subStates.wideConstruct(control, active);
_subStates.wideEnter (control, active);
} else {
requested = INVALID_SHORT;
// reconstruction done in S_::reenter()
_subStates.wideReenter (control, active);
}
}
//------------------------------------------------------------------------------
#ifdef FFSM2_ENABLE_SERIALIZATION
template <typename TA, typename TH, typename... TS>
void
C_<TA, TH, TS...>::deepSaveActive(const Registry& registry,
WriteStream& stream) const noexcept
{
stream.template write<WIDTH_BITS>(registry.active);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
template <typename TA, typename TH, typename... TS>
void
C_<TA, TH, TS...>::deepLoadRequested(Registry& registry,
ReadStream& stream) const noexcept
{
registry.requested = stream.template read<WIDTH_BITS>();
FFSM2_ASSERT(registry.requested < WIDTH);
}
#endif
// COMMON
////////////////////////////////////////////////////////////////////////////////
}
}
| 28.362069 | 80 | 0.615957 | linuxxiaolei |
3e1d42cb90f570ba2f60d5ee941351edb677e1c7 | 1,093 | cpp | C++ | Source/Engine/Ultra/Renderer/Framebuffer.cpp | larioteo/ultra | 48910110caae485ef518a0e972ab7271f5e5b430 | [
"MIT"
] | null | null | null | Source/Engine/Ultra/Renderer/Framebuffer.cpp | larioteo/ultra | 48910110caae485ef518a0e972ab7271f5e5b430 | [
"MIT"
] | null | null | null | Source/Engine/Ultra/Renderer/Framebuffer.cpp | larioteo/ultra | 48910110caae485ef518a0e972ab7271f5e5b430 | [
"MIT"
] | null | null | null | #include "FrameBuffer.h"
#include "Ultra/Platform/OpenGL/GLFramebuffer.h"
#include "Ultra/Platform/Vulkan/VKFramebuffer.h"
#include "Renderer.h"
namespace Ultra {
Reference<Framebuffer> Framebuffer::Create(const FramebufferProperties &properties) {
switch (Context::API) {
case GraphicsAPI::Null: { return nullptr; }
case GraphicsAPI::OpenGL: { return CreateReference<GLFramebuffer>(properties); }
case GraphicsAPI::Vulkan: { return CreateReference<VKFramebuffer>(properties); }
default: { break; }
}
AppLogCritical("[Engine::Renderer::Framebuffer] ", "The current graphics API doesn't support Framebuffers!");
return nullptr;
}
FramebufferPool::FramebufferPool(uint32_t maxBuffers) {
static FramebufferPool *instance = this;
Instance = instance;
}
FramebufferPool::~FramebufferPool() {}
void FramebufferPool::Add(const Reference<Framebuffer> &framebuffer) {
Pool.push_back(framebuffer);
}
weak_ptr<Framebuffer> FramebufferPool::Allocate() {
// ToDo: Push back to Pool
return weak_ptr<Framebuffer>();
}
}
| 29.540541 | 113 | 0.717292 | larioteo |
4a3f10ec880bcfce0979584c6d23b68a9347c114 | 1,369 | cc | C++ | tests/api/mpi/comm/ctxalloc.cc | jpkenny/sst-macro | bcc1f43034281885104962586d8b104df84b58bd | [
"BSD-Source-Code"
] | 20 | 2017-01-26T09:28:23.000Z | 2022-01-17T11:31:55.000Z | tests/api/mpi/comm/ctxalloc.cc | jpkenny/sst-macro | bcc1f43034281885104962586d8b104df84b58bd | [
"BSD-Source-Code"
] | 542 | 2016-03-29T22:50:58.000Z | 2022-03-22T20:14:08.000Z | tests/api/mpi/comm/ctxalloc.cc | jpkenny/sst-macro | bcc1f43034281885104962586d8b104df84b58bd | [
"BSD-Source-Code"
] | 36 | 2016-03-10T21:33:54.000Z | 2021-12-01T07:44:12.000Z | /*
*
* (C) 2003 by Argonne National Laboratory.
* See COPYRIGHT in top-level directory.
*/
#include <sstmac/replacements/mpi/mpi.h>
#include <stdio.h>
#include "mpitest.h"
namespace ctxalloc {
/**
* This program tests the allocation (and deallocation) of contexts.
*
*/
int ctxalloc( int argc, char **argv )
{
int errs = 0;
int i, j, err;
MPI_Comm newcomm1, newcomm2[200];
MTest_Init( &argc, &argv );
/** Get a separate communicator to duplicate */
MPI_Comm_dup( MPI_COMM_WORLD, &newcomm1 );
MPI_Errhandler_set( newcomm1, MPI_ERRORS_RETURN );
/** Allocate many communicators in batches, then free them */
for (i=0; i<1000; i++) {
for (j=0; j<200; j++) {
err = MPI_Comm_dup( newcomm1, &newcomm2[j] );
if (err) {
errs++;
if (errs < 10) {
fprintf( stderr, "Failed to duplicate communicator for (%d,%d)\n", i, j );
MTestPrintError( err );
}
}
}
for (j=0; j<200; j++) {
err = MPI_Comm_free( &newcomm2[j] );
if (err) {
errs++;
if (errs < 10) {
fprintf( stderr, "Failed to free %d,%d\n", i, j );
MTestPrintError( err );
}
}
}
}
err = MPI_Comm_free( &newcomm1 );
if (err) {
errs++;
fprintf( stderr, "Failed to free newcomm1\n" );
MTestPrintError( err );
}
MTest_Finalize( errs );
MPI_Finalize();
return 0;
}
}
| 20.432836 | 80 | 0.583638 | jpkenny |
4a421482460913dfde21e0ed245bf59855dc508c | 105 | cpp | C++ | chapter-10/10.23.cpp | zero4drift/Cpp-Primer-5th-Exercises | d3d0f0d228e8c2c5a3b3fe1fd03ce34e0894e93f | [
"MIT"
] | null | null | null | chapter-10/10.23.cpp | zero4drift/Cpp-Primer-5th-Exercises | d3d0f0d228e8c2c5a3b3fe1fd03ce34e0894e93f | [
"MIT"
] | null | null | null | chapter-10/10.23.cpp | zero4drift/Cpp-Primer-5th-Exercises | d3d0f0d228e8c2c5a3b3fe1fd03ce34e0894e93f | [
"MIT"
] | null | null | null | // bind requires an argument as callable and the rest arguments responded to given callable's arguments.
| 52.5 | 104 | 0.809524 | zero4drift |
4a4ad52a38af8707af30b515a584c5f18f47927e | 1,524 | cpp | C++ | Binary_search/Search_in_Row_wise_And_Column_wise_Sorted_Array.cpp | shitesh2607/dsa | 2293eb090c0a0334a9903b83aa881b5201ec26e4 | [
"MIT"
] | 1 | 2021-11-27T06:57:22.000Z | 2021-11-27T06:57:22.000Z | Binary_search/Search_in_Row_wise_And_Column_wise_Sorted_Array.cpp | shitesh2607/dsa | 2293eb090c0a0334a9903b83aa881b5201ec26e4 | [
"MIT"
] | null | null | null | Binary_search/Search_in_Row_wise_And_Column_wise_Sorted_Array.cpp | shitesh2607/dsa | 2293eb090c0a0334a9903b83aa881b5201ec26e4 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
// Actualy both problem are exactly same.
// leetcode: 240. Search a 2D Matrix =: https://leetcode.com/problems/search-a-2d-matrix/
class soluion{
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
if(!matrix.size()) return false;
int n = matrix.size();
int m = matrix[0].size();
int low = 0;
int high = (n*m) - 1;
while(low<=high){
int mid = (low +(high - low) / 2);
if(matrix[mid/m][mid % m] == target){
return true;
}
if(matrix[mid/m][mid%m] < target){
low = mid +1;
}else{
high = mid -1;
}
}
return false;
}
};
// leetcode: 240. Search a 2D Matrix II =: https://leetcode.com/problems/search-a-2d-matrix-ii/discuss/1598490/240-search-a-2d-matrix-ii-c-solution-time-complexity-omn-binary-search
class solution{
public:
bool searchMatrix(vector<vector<int>> matrix, int target) {
int row = matrix.size();
int col = matrix[0].size();
int i = 0;
int j = col-1;
while((i>=0 && i<=row-1) && (j<=col-1 && j>=0)){
if(matrix[i][j]==target){
return true;
}else if(matrix[i][j]>target){
j--;
}else if(matrix[i][j]<target){
i++;
}
}
return false;
}
}; | 31.75 | 181 | 0.476378 | shitesh2607 |
4a4c6efe25064ed287e3a63e36a936a8b425b865 | 4,130 | cpp | C++ | test/barebone_sounds.cpp | Sgw32/UltiSID | 319edaa63f25c76b6c2675a2cb87d7992724b2d9 | [
"MIT"
] | 9 | 2021-04-30T09:06:13.000Z | 2022-03-31T04:52:07.000Z | test/barebone_sounds.cpp | Sgw32/UltiSID | 319edaa63f25c76b6c2675a2cb87d7992724b2d9 | [
"MIT"
] | null | null | null | test/barebone_sounds.cpp | Sgw32/UltiSID | 319edaa63f25c76b6c2675a2cb87d7992724b2d9 | [
"MIT"
] | 4 | 2021-04-30T16:37:09.000Z | 2022-03-01T23:11:26.000Z | #include "barebone_sounds.h"
extern uint8_t period;
extern uint8_t multiplier;
extern uint8_t DEFAULT_SONG;
extern const uint8_t magic_number;
void error_sound_SD() {
//reset_SID();
OSC_1_HiLo = 0xffff; // just having fun with globals here :-)
MASTER_VOLUME = 0x0f;
ADSR_Attack_1 = 0x09;
ADSR_Decay_1 = 0x07;
ADSR_Sustain_1 = 0x06;
ADSR_Release_1 = 0x0b;
PW_HiLo_voice_1 = 0x400;
//sawtooth_bit_voice_1=1;
triangle_bit_voice_1 = 1;
pulse_bit_voice_1 = 1;
Gate_bit_1 = 1;
delay(480);
OSC_1_HiLo = 0xf000;
Gate_bit_1 = 0;
delay(4000);
}
inline void error_sound_ROOT() {
//reset_SID();
OSC_1_HiLo = 0x1000;
MASTER_VOLUME = 0x0f;
ADSR_Attack_1 = 0x09;
ADSR_Decay_1 = 0x07;
ADSR_Sustain_1 = 0x06;
ADSR_Release_1 = 0x0b;
PW_HiLo_voice_1 = 0x400;
//sawtooth_bit_voice_1=1;
triangle_bit_voice_1 = 1;
pulse_bit_voice_1 = 1;
Gate_bit_1 = 1;
delay(480);
OSC_1_HiLo = 0x0800;
Gate_bit_1 = 0;
delay(1000);
}
inline void error_open_file() {
//reset_SID();
OSC_1_HiLo = 0xc000;
MASTER_VOLUME = 0x0f;
ADSR_Attack_1 = 0x00;
ADSR_Decay_1 = 0x00;
ADSR_Sustain_1 = 0x0f;
ADSR_Release_1 = 0x05;
PW_HiLo_voice_1 = 0x400;
//sawtooth_bit_voice_1=1;
// triangle_bit_voice_1 = 1;
//pulse_bit_voice_1 = 1;
noise_bit_voice_1;
Gate_bit_1 = 1;
delay(480);
OSC_1_HiLo = 0xc800;
Gate_bit_1 = 0;
delay(480);
}
inline void error_open_folder () {
//reset_SID();
OSC_1_HiLo = 0x2000;
MASTER_VOLUME = 0x0f;
ADSR_Attack_1 = 0x09;
ADSR_Decay_1 = 0x07;
ADSR_Sustain_1 = 0x06;
ADSR_Release_1 = 0x0b;
PW_HiLo_voice_1 = 0x400;
//sawtooth_bit_voice_1=1;
triangle_bit_voice_1 = 1;
pulse_bit_voice_1 = 1;
Gate_bit_1 = 1;
delay(480);
OSC_1_HiLo = 0x1000;
Gate_bit_1 = 0;
delay(1000);
}
inline void error_open_sid () {
//reset_SID();
OSC_1_HiLo = 0x4000;
MASTER_VOLUME = 0x0f;
ADSR_Attack_1 = 0x0b;
ADSR_Decay_1 = 0x08;
ADSR_Sustain_1 = 0x06;
ADSR_Release_1 = 0x0b;
PW_HiLo_voice_1 = 0x400;
//sawtooth_bit_voice_1=1;
triangle_bit_voice_1 = 1;
pulse_bit_voice_1 = 1;
Gate_bit_1 = 1;
delay(1500);
OSC_1_HiLo = 0x3f00;
Gate_bit_1 = 0;
Gate_bit_2 = 0;
Gate_bit_3 = 0;
for (int oscup = 0; oscup > 4000; oscup++) {
OSC_1_HiLo = oscup;
delay(1);
}
}
inline void error_PSID_V2_RAM_OVERFLOW () {
//reset_SID();
OSC_1_HiLo = 0x4000; // barebone sound
MASTER_VOLUME = 0x0f;
ADSR_Attack_1 = 0x0b;
ADSR_Decay_1 = 0x08;
ADSR_Sustain_1 = 0x06;
ADSR_Release_1 = 0x0b;
PW_HiLo_voice_1 = 0x400;
//sawtooth_bit_voice_1=1;
triangle_bit_voice_1 = 1;
pulse_bit_voice_1 = 1;
Gate_bit_1 = 1;
delay(1500);
OSC_1_HiLo = 0x3f00;
Gate_bit_1 = 0;
Gate_bit_2 = 0;
Gate_bit_3 = 0;
for (int oscdown = 4000; oscdown > 0; oscdown = oscdown - 2) {
OSC_1_HiLo = oscdown;
delay(1);
}
}
inline void reset_SID() {
OSC_1_HiLo = 0;
PW_HiLo_voice_1 = 0;
noise_bit_voice_1 = 0;
pulse_bit_voice_1 = 0;
sawtooth_bit_voice_1 = 0;
triangle_bit_voice_1 = 0;
test_bit_voice_1 = 0;
ring_bit_voice_1 = 0;
SYNC_bit_voice_1 = 0;
Gate_bit_1 = 0;
ADSR_Attack_1 = 0;
ADSR_Decay_1 = 0;
ADSR_Sustain_1 = 0;
ADSR_Release_1 = 0;
OSC_2_HiLo = 0;
PW_HiLo_voice_2 = 0;
noise_bit_voice_2 = 0;
pulse_bit_voice_2 = 0;
sawtooth_bit_voice_2 = 0;
triangle_bit_voice_2 = 0;
test_bit_voice_2 = 0;
ring_bit_voice_2 = 0;
SYNC_bit_voice_2 = 0;
Gate_bit_2 = 0;
ADSR_Attack_2 = 0;
ADSR_Decay_2 = 0;
ADSR_Sustain_2 = 0;
ADSR_Release_2 = 0;
OSC_3_HiLo = 0;
PW_HiLo_voice_3 = 0;
noise_bit_voice_3 = 0;
pulse_bit_voice_3 = 0;
sawtooth_bit_voice_3 = 0;
triangle_bit_voice_3 = 0;
test_bit_voice_3 = 0;
ring_bit_voice_3 = 0;
SYNC_bit_voice_3 = 0;
Gate_bit_3 = 0;
ADSR_Attack_3 = 0;
ADSR_Decay_3 = 0;
ADSR_Sustain_3 = 0;
ADSR_Release_3 = 0;
FILTER_HiLo = 0;
FILTER_Resonance = 0;
FILTER_Enable_1 = 0;
FILTER_Enable_2 = 0;
FILTER_Enable_3 = 0;
FILTER_Enable_EXT = 0;
FILTER_Enable_switch = 0;
OFF3 = 0;
FILTER_HP = 0;
FILTER_BP = 0;
FILTER_LP = 0;
MASTER_VOLUME = 0;
} | 19.57346 | 64 | 0.678692 | Sgw32 |
4a5155a016ba64c8b36cb336a94595bd16e03096 | 682 | cpp | C++ | nd-coursework/books/cpp/C++ConcurrencyInAction/Chapter02/Listing2_05/Listing2_05.cpp | crdrisko/nd-grad | f1765e4f24d7a4b1b3a76c64eb8d88bcca0eaa44 | [
"MIT"
] | 1 | 2020-09-26T12:38:55.000Z | 2020-09-26T12:38:55.000Z | nd-coursework/books/cpp/C++ConcurrencyInAction/Chapter02/Listing2_05/Listing2_05.cpp | crdrisko/nd-research | f1765e4f24d7a4b1b3a76c64eb8d88bcca0eaa44 | [
"MIT"
] | null | null | null | nd-coursework/books/cpp/C++ConcurrencyInAction/Chapter02/Listing2_05/Listing2_05.cpp | crdrisko/nd-research | f1765e4f24d7a4b1b3a76c64eb8d88bcca0eaa44 | [
"MIT"
] | null | null | null | // Copyright (c) 2019 by Anthony Williams. All rights reserved.
// Licensed under the Boost Software License. See the LICENSE file in the project root for more information.
//
// Name: Listing2_05.cpp
// Author: crdrisko
// Date: 12/26/2020-07:57:22
// Description: Returning a std::thread from a function
#include <thread>
void some_function() {}
void some_other_function(int) {}
std::thread f()
{
void some_function();
return std::thread(some_function);
}
std::thread g()
{
void some_other_function(int);
std::thread t(some_other_function, 42);
return t;
}
int main()
{
std::thread t1 = f();
t1.join();
std::thread t2 = g();
t2.join();
}
| 19.485714 | 108 | 0.668622 | crdrisko |
4a53db9992c70d155a8361999b3aff87e1f88831 | 369 | cpp | C++ | AtCoder/tkppc3/b/main.cpp | H-Tatsuhiro/Com_Pro-Cpp | fd79f7821a76b11f4a6f83bbb26a034db577a877 | [
"MIT"
] | null | null | null | AtCoder/tkppc3/b/main.cpp | H-Tatsuhiro/Com_Pro-Cpp | fd79f7821a76b11f4a6f83bbb26a034db577a877 | [
"MIT"
] | 1 | 2021-10-19T08:47:23.000Z | 2022-03-07T05:23:56.000Z | AtCoder/tkppc3/b/main.cpp | H-Tatsuhiro/Com_Pro-Cpp | fd79f7821a76b11f4a6f83bbb26a034db577a877 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cmath>
#include <algorithm>
#include <vector>
#include <boost/multiprecision/cpp_int.hpp>
using namespace boost::multiprecision;
using namespace std;
int main() {
cpp_int n; cin >> n;
if (n % 6 == 0) cout << "yES" << endl;
else cout << "nO" << endl;
if (n % 11 == 0) cout << "yES" << endl;
else cout << "nO" << endl;
}
| 24.6 | 43 | 0.601626 | H-Tatsuhiro |
4a54dee2701eec0c1dbb49eac4ee1bc5a1bd6ff9 | 1,452 | cpp | C++ | tests/buffer_complex_test.cpp | Tommoa/Snippets | ceaa29b1486615abdbab0e6a7ad152353d3a3ccc | [
"MIT"
] | 1 | 2017-06-07T06:52:16.000Z | 2017-06-07T06:52:16.000Z | tests/buffer_complex_test.cpp | Tommoa/Snippets | ceaa29b1486615abdbab0e6a7ad152353d3a3ccc | [
"MIT"
] | null | null | null | tests/buffer_complex_test.cpp | Tommoa/Snippets | ceaa29b1486615abdbab0e6a7ad152353d3a3ccc | [
"MIT"
] | null | null | null | #include "../buffer/buffer_complex.hpp"
#include <fstream>
#include <iostream>
using namespace Snippets;
int main() {
std::cout << std::endl << "Start of complex buffer test" << std::endl;
std::cout << std::endl;
std::cout << "size of buffer: " << sizeof(buffer_complex) << std::endl
<< std::endl;
Snippets::buffer_complex complex_buffer =
Snippets::buffer_complex(); // Will use malloc, has no special traits.
std::cout << "Assigned new complex buffer with malloc" << std::endl;
int* test_int_1 = (int*)complex_buffer.allocate(sizeof(int));
long* test_long_1 = (long*)complex_buffer.allocate(sizeof(long));
std::cout << "Allocated a new int and a new long on the buffer"
<< std::endl;
*test_int_1 = rand();
*test_long_1 = rand();
std::cout << "\ttest_int_1: " << *test_int_1 << std::endl;
std::cout << "\ttestlong_1: " << *test_long_1 << std::endl;
std::cout << std::endl;
std::ofstream out("buffer_complex_test");
complex_buffer.save(out);
out.close();
std::cout << "Saved buffer to file" << std::endl;
std::ifstream in("buffer_complex_test");
buffer_complex cb = buffer_complex();
cb.load(in);
in.close();
std::cout << "Read buffer to new buffer 'cb'" << std::endl;
std::cout << std::endl;
std::cout << "Attempting to read back the int and the long" << std::endl;
test_int_1 = (int*)cb.offset(0);
test_long_1 = (long*)cb.offset(4);
std::cout << *test_int_1 << std::endl << *test_long_1 << std::endl;
}
| 32.266667 | 74 | 0.661157 | Tommoa |
4a5522ef04b83812ad9dd47013eb11d1ff99f629 | 8,037 | cpp | C++ | Controller/CPU-related/AMD/Griffin/UsageGetterAndControllerBase.cpp | st-gb/CPUinfoAndControl | 5e93d4a195b4692d147bb05cfef534e38d7f8b64 | [
"MIT"
] | null | null | null | Controller/CPU-related/AMD/Griffin/UsageGetterAndControllerBase.cpp | st-gb/CPUinfoAndControl | 5e93d4a195b4692d147bb05cfef534e38d7f8b64 | [
"MIT"
] | null | null | null | Controller/CPU-related/AMD/Griffin/UsageGetterAndControllerBase.cpp | st-gb/CPUinfoAndControl | 5e93d4a195b4692d147bb05cfef534e38d7f8b64 | [
"MIT"
] | 1 | 2021-07-16T21:01:26.000Z | 2021-07-16T21:01:26.000Z | /* Do not remove this header/ copyright information.
*
* Copyright © Trilobyte Software Engineering GmbH, Berlin, Germany 2010-2011.
* You are allowed to modify and use the source code from
* Trilobyte Software Engineering GmbH, Berlin, Germany for free if you are not
* making profit with it or its adaption. Else you may contact Trilobyte SE.
*/
/*
* UsageGetterAndControllerBase.cpp
*
* Created on: 09.04.2010
* Author: Stefan
*/
#include <Controller/AMD/Griffin/UsageGetterAndControllerBase.hpp>
#include <Controller/AMD/Griffin/AMD_family17.h>
#include <Controller/I_CPUaccess.hpp>
#include <preprocessor_helper_macros.h> //BITMASK_FOR_LOWMOST_8BIT
namespace Griffin
{
UsageGetterAndControllerBase::UsageGetterAndControllerBase() {
// TODO Auto-generated constructor stub
}
UsageGetterAndControllerBase::~UsageGetterAndControllerBase() {
// TODO Auto-generated destructor stub
}
//this method is for this purpose:
//AMD BIOS and Kernel Dev Guide:
//"To accurately start counting with the write that enables the counter,
//disable the counter when changing the event and then enable the counter
//with a second MSR write."
void UsageGetterAndControllerBase::AccuratelyStartPerformanceCounting(
DWORD dwAffinityBitMask ,
BYTE byPerformanceCounterNumber ,
WORD wEventSelect ,
bool bInvertCounterMask
)
{
//Disables the performance counter for accurately start performance
//counting.
PrepareForNextPerformanceCounting(
dwAffinityBitMask , byPerformanceCounterNumber) ;
PerformanceEventSelectRegisterWrite(
dwAffinityBitMask ,
byPerformanceCounterNumber ,
//wEventSelect
//0x0C1 ,
wEventSelect ,
// 0x076 ,
//byCounterMask: 00h: The corresponding PERF_CTR[3:0] register is incremented by the number of events
//occurring in a clock cycle. Maximum number of events in one cycle is 3.
0,
bInvertCounterMask ,
//0,
//bEnablePerformanceCounter
1,
//bEnableAPICinterrupt
0,
//bEdgeDetect
0,
//bOSmode
//0
true
,
//bUserMode
true
,
//byEventQualification
0
) ;
}
BYTE UsageGetterAndControllerBase::GetNumberOfCPUCores()
{
BYTE byCoreNumber = 0 ;
DWORD dwEAX;
DWORD dwEBX;
DWORD dwECX;
DWORD dwEDX;
DEBUG_COUTN("UsageGetterAndControllerBase::GetNumberOfCPUCores()");
if( //CpuidEx(
mp_cpuaccess->CpuidEx(
//AMD: "CPUID Fn8000_0008 Address Size And Physical Core Count Information"
0x80000008,
&dwEAX,
&dwEBX,
&dwECX,
&dwEDX,
1
)
)
{
byCoreNumber = ( dwECX & BITMASK_FOR_LOWMOST_7BIT )
//"ECX 7:0 NC: number of physical cores - 1.
//The number of cores in the processor is NC+1 (e.g., if
//NC=0, then there is one core).
//See also section 2.9.2 [Number of Cores and Core Number]."
+ 1 ;
//DEBUG("Number of CPU cores: %u\n", (WORD) byCoreNumber );
DEBUG_COUTN("UsageGetterAndControllerBase::GetNumberOfCPUCores() "
"Number of CPU cores according to CPUID: " << (WORD) byCoreNumber );
}
else
{
DEBUG_COUTN("UsageGetterAndControllerBase::GetNumberOfCPUCores() "
"mp_cpuaccess->CpuidEx failed" );
}
return byCoreNumber ;
}
void UsageGetterAndControllerBase::PerformanceEventSelectRegisterWrite(
DWORD dwAffinityBitMask ,
//Griffin has 4 "Performance Event Select Register" from
// MSR 0xC001_0000_00 to MSRC001_00_03 for
// 4 "Performance Event Counter Registers" from
// MSR 0xC001_0004 to 0xC001_0007
// that store the 48 bit counter value
BYTE byPerformanceEventSelectRegisterNumber ,
WORD wEventSelect ,
BYTE byCounterMask ,
bool bInvertCounterMask ,
bool bEnablePerformanceCounter,
bool bEnableAPICinterrupt,
bool bEdgeDetect,
bool bOSmode,
bool bUserMode,
BYTE byEventQualification
)
{
if( bInvertCounterMask == true )
//When Inv = 1, the corresponding PERF_CTR[3:0] register is incremented by 1, if the
//number of events occurring in a clock cycle is less than CntMask value.
//Less than 1 = 0 -> so if Clocks not halted and 0 times "not halted": ->"halted"
byCounterMask = 1 ;
//see AMD Family 11h Processor BKDG, paragraph
//"MSRC001_00[03:00] Performance Event Select Register (PERF_CTL[3:0])"
//bits:
//31:24 CntMask: counter mask. Read-write. Controls the number of events
//counted per clock cycle.
//00h The corresponding PERF_CTR[3:0] register is incremented by the number of events
//occurring in a clock cycle. Maximum number of events in one cycle is 3.
//01h-03h When Inv = 0, the corresponding PERF_CTR[3:0] register is incremented by 1, if the
//number of events occurring in a clock cycle is greater than or equal to the CntMask value.
//When Inv = 1, the corresponding PERF_CTR[3:0] register is incremented by 1, if the
//number of events occurring in a clock cycle is less than CntMask value.
//04h-FFh Reserved.
//23 | Inv: invert counter mask. Read-write. See CntMask.
DWORD dwLow = 0 |
( byCounterMask << 24 ) |
( bInvertCounterMask << 23 ) |
( bEnablePerformanceCounter << 22 ) |
( bEnableAPICinterrupt << 20 ) |
( bEdgeDetect << 18 ) |
( bOSmode << 17 ) |
( bUserMode << 16 ) |
( byEventQualification << 8 ) |
( wEventSelect & BITMASK_FOR_LOWMOST_8BIT )
;
#ifdef _EMULATE_TURION_X2_ULTRA_ZM82
#else
mp_cpuaccess->WrmsrEx(
PERF_CTL_0 + byPerformanceEventSelectRegisterNumber ,
dwLow ,
wEventSelect >> 8 ,
//1=core 0
//1
dwAffinityBitMask
) ;
#endif //_EMULATE_TURION_X2_ULTRA_ZM82
}
void UsageGetterAndControllerBase::PrepareForNextPerformanceCounting(
DWORD dwAffinityBitMask
, BYTE byPerformanceEventSelectRegisterNumber
)
{
PerformanceEventSelectRegisterWrite(
dwAffinityBitMask ,
//byPerformanceCounterNumber ,
byPerformanceEventSelectRegisterNumber ,
//wEventSelect ,
0x0C1 ,
// 0x076 ,
// 0x076 ,
//byCounterMask: 00h: The corresponding PERF_CTR[3:0] register is incremented by the number of events
//occurring in a clock cycle. Maximum number of events in one cycle is 3.
//0,
//"When Inv = 0, the corresponding PERF_CTR[3:0] register is
//incremented by 1, if the number of events occurring in a clock
//cycle is greater than or equal to the CntMask"
1 ,
//bInvertCounterMask
0,
//bEnablePerformanceCounter
0,
//bEnableAPICinterrupt
0,
//bEdgeDetect
0,
//bOSmode[...]1=Events are only counted when CPL=0.
//(CPL=Current Privilege Level?) http://en.wikipedia.org/wiki/Current_privilege_level
1,
//bUserMode
1,
//byEventQualification
0
) ;
}
//inline
bool UsageGetterAndControllerBase::ReadPerformanceEventCounterRegister(
BYTE byPerformanceEventCounterNumber ,
ULONGLONG & r_ull ,
DWORD_PTR dwAffinityMask // Thread Affinity Mask
)
{
DWORD dwLow , dwHigh ;
bool bRet =
//TODO better use ReadPMC? : AMD Family 11h Processor BKDG :
//"The RDPMC instruction is not serializing, and it can be executed
//out-of-order with respect to other instructions around it.
//Even when bound by serializing instructions, the system environment at
//the time the instruction is executed can cause events to be counted
//before the counter value is loaded into EDX:EAX."
RdmsrEx(
PERFORMANCE_EVENT_COUNTER_0_REGISTER + byPerformanceEventCounterNumber ,
//PERFORMANCE_EVENT_COUNTER_1_REGISTER ,
dwLow,
dwHigh,
//1=core 0
dwAffinityMask
) ;
//RdpmcEx seemed to cause a blue screen (maybe because of wrong param values)
//mp_cpuaccess->RdpmcEx(
// PERFORMANCE_EVENT_COUNTER_0_REGISTER + byPerformanceEventCounterNumber ,
// //PERFORMANCE_EVENT_COUNTER_1_REGISTER ,
// & dwLow,
// & dwHigh,
// //1=core 0
// dwAffinityMask
// ) ;
r_ull = dwHigh ;
r_ull <<= 32 ;
r_ull |= dwLow ;
return bRet ;
}
} //end namespace
| 31.641732 | 105 | 0.696155 | st-gb |
4a5cca250efd7d3ea01d9a6edd88e75b2fc21058 | 13,636 | cpp | C++ | master/core/third/cxxtools/src/convert.cpp | importlib/klib | a59837857689d0e60d3df6d2ebd12c3160efa794 | [
"MIT"
] | 4 | 2017-12-04T08:22:48.000Z | 2019-10-26T21:44:59.000Z | master/core/third/cxxtools/src/convert.cpp | isuhao/klib | a59837857689d0e60d3df6d2ebd12c3160efa794 | [
"MIT"
] | null | null | null | master/core/third/cxxtools/src/convert.cpp | isuhao/klib | a59837857689d0e60d3df6d2ebd12c3160efa794 | [
"MIT"
] | 4 | 2017-12-19T11:13:56.000Z | 2018-02-23T08:44:03.000Z | /*
* Copyright (C) 2011 Tommi Maekitalo
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* As a special exception, you may use this file as part of a free
* software library without restriction. Specifically, if other files
* instantiate templates or use macros or inline functions from this
* file, or you compile this file and link it with other files to
* produce an executable, this file does not by itself cause the
* resulting executable to be covered by the GNU General Public
* License. This exception does not however invalidate any other
* reasons why the executable file might be covered by the GNU Library
* General Public License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <cxxtools/convert.h>
#include <iomanip>
#include <limits>
#include <cctype>
namespace cxxtools
{
template <typename IterT>
void _skipws(IterT& it, IterT end)
{
while (it != end && isspace(*it))
++it;
}
template<typename T>
class nullterm_array_iterator : public std::iterator<std::input_iterator_tag, T>
{
public:
nullterm_array_iterator()
: _ptr(0)
{ }
explicit nullterm_array_iterator(const T* ptr)
: _ptr(ptr)
{
if(*_ptr == '\0')
_ptr = 0;
}
nullterm_array_iterator<T>& operator=(const nullterm_array_iterator<T>& it)
{
_ptr = it._ptr;
return *this;
}
bool operator==(const nullterm_array_iterator<T>& it) const
{
return _ptr == it._ptr;
}
bool operator!=(const nullterm_array_iterator<T>& it) const
{
return _ptr != it._ptr;
}
const T& operator*() const
{
return *_ptr;
}
nullterm_array_iterator<T>& operator++()
{
if(*++_ptr == '\0')
_ptr = 0;
return *this;
}
nullterm_array_iterator<T> operator++(int)
{
if(*++_ptr == '\0')
_ptr = 0;
return *this;
}
private:
const T* _ptr;
};
template <typename T>
void convertInt(T& n, const String& str, const char* typeto)
{
bool ok = false;
String::const_iterator r = getInt( str.begin(), str.end(), ok, n, DecimalFormat<Char>() );
if (ok)
_skipws(r, str.end());
if( r != str.end() || ! ok )
ConversionError::doThrow(typeto, "String", str.narrow().c_str());
}
template <typename T>
void convertInt(T& n, const std::string& str, const char* typeto)
{
bool ok = false;
std::string::const_iterator r = getInt( str.begin(), str.end(), ok, n );
if (ok)
_skipws(r, str.end());
if( r != str.end() || ! ok )
ConversionError::doThrow(typeto, "string", str.c_str());
}
template <typename T>
void convertInt(T& n, const char* str, const char* typeto)
{
bool ok = false;
nullterm_array_iterator<char> it(str);
nullterm_array_iterator<char> end;
it = getInt( it, end, ok, n );
if (ok)
_skipws(it, end);
if( it != end || ! ok )
ConversionError::doThrow(typeto, "char*");
}
template <typename T>
void convertFloat(T& n, const String& str, const char* typeto)
{
bool ok = false;
String::const_iterator r = getFloat(str.begin(), str.end(), ok, n, FloatFormat<Char>() );
if (ok)
_skipws(r, str.end());
if(r != str.end() || ! ok)
ConversionError::doThrow(typeto, "String", str.narrow().c_str());
}
template <typename T>
void convertFloat(T& n, const std::string& str, const char* typeto)
{
bool ok = false;
std::string::const_iterator r = getFloat(str.begin(), str.end(), ok, n);
if (ok)
_skipws(r, str.end());
if(r != str.end() || ! ok)
ConversionError::doThrow(typeto, "string", str.c_str());
}
template <typename T>
void convertFloat(T& n, const char* str, const char* typeto)
{
bool ok = false;
nullterm_array_iterator<char> it(str);
nullterm_array_iterator<char> end;
it = getFloat( it, end, ok, n );
if (ok)
_skipws(it, end);
if( it != end || ! ok )
ConversionError::doThrow(typeto, "char*", str);
}
//
// Conversions to cxxtools::String
//
void convert(String& s, const std::string& value)
{
s = String::widen(value);
}
void convert(String& str, bool value)
{
static const wchar_t* trueValue = L"true";
static const wchar_t* falseValue = L"false";
str = value ? trueValue : falseValue;
}
void convert(String& str, char value)
{
str = String(1, Char(value));
}
void convert(String& str, wchar_t value)
{
str = String(1, Char(value));
}
void convert(String& str, Char value)
{
str = String(1, value);
}
void convert(String& str, unsigned char value)
{
str.clear();
putInt(std::back_inserter(str), value);
}
void convert(String& str, signed char value)
{
str.clear();
putInt(std::back_inserter(str), value);
}
void convert(String& str, short value)
{
str.clear();
putInt(std::back_inserter(str), value);
}
void convert(String& str, unsigned short value)
{
str.clear();
putInt(std::back_inserter(str), value);
}
void convert(String& str, int value)
{
str.clear();
putInt(std::back_inserter(str), value);
}
void convert(String& str, unsigned int value)
{
str.clear();
putInt(std::back_inserter(str), value);
}
void convert(String& str, long value)
{
str.clear();
putInt(std::back_inserter(str), value);
}
void convert(String& str, unsigned long value)
{
str.clear();
putInt(std::back_inserter(str), value);
}
void convert(String& str, float value)
{
str.clear();
putFloat(std::back_inserter(str), value);
}
void convert(String& str, double value)
{
str.clear();
putFloat(std::back_inserter(str), value);
}
void convert(String& str, long double value)
{
str.clear();
putFloat(std::back_inserter(str), value);
}
//
// Conversions from cxxtools::String
//
void convert(bool& n, const String& str)
{
if (str == L"true" || str == L"1")
n = true;
else if (str == L"false" || str == L"0")
n = false;
else
ConversionError::doThrow("bool", "String", str.narrow().c_str());
}
void convert(char& c, const String& str)
{
if ( str.empty() )
ConversionError::doThrow("char", "String");
c = str[0].narrow();
}
void convert(wchar_t& c, const String& str)
{
if ( str.empty() )
ConversionError::doThrow("wchar_t", "String");
c = str[0].toWchar();
}
void convert(Char& c, const String& str)
{
if ( str.empty() )
ConversionError::doThrow("char", "Char");
c = str[0];
}
void convert(unsigned char& n, const String& str)
{
convertInt(n, str, "unsigned char");
}
void convert(signed char& n, const String& str)
{
convertInt(n, str, "signed char");
}
void convert(short& n, const String& str)
{
convertInt(n, str, "short");
}
void convert(unsigned short& n, const String& str)
{
convertInt(n, str, "unsigned short");
}
void convert(int& n, const String& str)
{
convertInt(n, str, "int");
}
void convert(unsigned int& n, const String& str)
{
convertInt(n, str, "unsigned int");
}
void convert(long& n, const String& str)
{
convertInt(n, str, "long");
}
void convert(unsigned long& n, const String& str)
{
convertInt(n, str, "unsigned long");
}
#ifdef HAVE_LONG_LONG
void convert(long long& n, const String& str)
{
convertInt(n, str, "long long");
}
#endif
#ifdef HAVE_UNSIGNED_LONG_LONG
void convert(unsigned long long& n, const String& str)
{
convertInt(n, str, "unsigned long long");
}
#endif
void convert(float& n, const String& str)
{
convertFloat(n, str, "float");
}
void convert(double& n, const String& str)
{
convertFloat(n, str, "double");
}
void convert(long double& n, const String& str)
{
convertFloat(n, str, "long double");
}
//
// Conversions to std::string
//
void convert(std::string& s, const String& str)
{
s = str.narrow();
}
void convert(std::string& str, bool value)
{
static const char* trueValue = "true";
static const char* falseValue = "false";
str = value ? trueValue : falseValue;
}
void convert(std::string& str, char value)
{
str.clear();
str += value;
}
void convert(std::string& str, signed char value)
{
str.clear();
putInt(std::back_inserter(str), value);
}
void convert(std::string& str, unsigned char value)
{
str.clear();
putInt(std::back_inserter(str), value);
}
void convert(std::string& str, short value)
{
str.clear();
putInt(std::back_inserter(str), value);
}
void convert(std::string& str, unsigned short value)
{
str.clear();
putInt(std::back_inserter(str), value);
}
void convert(std::string& str, int value)
{
str.clear();
putInt(std::back_inserter(str), value);
}
void convert(std::string& str, unsigned int value)
{
str.clear();
putInt(std::back_inserter(str), value);
}
void convert(std::string& str, long value)
{
str.clear();
putInt(std::back_inserter(str), value);
}
void convert(std::string& str, unsigned long value)
{
str.clear();
putInt(std::back_inserter(str), value);
}
void convert(std::string& str, float value)
{
str.clear();
putFloat(std::back_inserter(str), value);
}
void convert(std::string& str, double value)
{
str.clear();
putFloat(std::back_inserter(str), value);
}
void convert(std::string& str, long double value)
{
str.clear();
putFloat(std::back_inserter(str), value);
}
//
// Conversions from std::string
//
void convert(bool& n, const std::string& str)
{
if (str == "true" || str == "1")
n = true;
else if (str == "false" || str == "0")
n = false;
else
ConversionError::doThrow("bool", "string", str.c_str());
}
void convert(char& c, const std::string& str)
{
if ( str.empty() )
ConversionError::doThrow("char", "string");
int n = str[0];
c = n;
}
void convert(signed char& n, const std::string& str)
{
convertInt(n, str, "signed char");
}
void convert(unsigned char& n, const std::string& str)
{
convertInt(n, str, "unsigned char");
}
void convert(short& n, const std::string& str)
{
convertInt(n, str, "short");
}
void convert(unsigned short& n, const std::string& str)
{
convertInt(n, str, "unsigned short");
}
void convert(int& n, const std::string& str)
{
convertInt(n, str, "int");
}
void convert(unsigned int& n, const std::string& str)
{
convertInt(n, str, "unsigned int");
}
void convert(long& n, const std::string& str)
{
convertInt(n, str, "long");
}
void convert(unsigned long& n, const std::string& str)
{
convertInt(n, str, "unsigned long");
}
#ifdef HAVE_LONG_LONG
void convert(long long& n, const std::string& str)
{
convertInt(n, str, "long long");
}
#endif
#ifdef HAVE_UNSIGNED_LONG_LONG
void convert(unsigned long long& n, const std::string& str)
{
convertInt(n, str, "unsigned long long");
}
#endif
void convert(float& n, const std::string& str)
{
convertFloat(n, str, "float");
}
void convert(double& n, const std::string& str)
{
convertFloat(n, str, "double");
}
void convert(long double& n, const std::string& str)
{
convertFloat(n, str, "long double");
}
//
// Conversions from const char*
//
void convert(bool& n, const char* str)
{
if (std::strcmp(str, "true") == 0 || std::strcmp(str, "1") == 0)
n = true;
else if (std::strcmp(str, "false") || std::strcmp(str, "0"))
n = false;
else
ConversionError::doThrow("bool", "char*", str);
}
void convert(char& c, const char* str)
{
if ( *str == '\0' )
ConversionError::doThrow("char", "char*");
c = str[0];
}
void convert(signed char& n, const char* str)
{
convertInt(n, str, "signed char");
}
void convert(unsigned char& n, const char* str)
{
convertInt(n, str, "unsigned char");
}
void convert(short& n, const char* str)
{
convertInt(n, str, "short");
}
void convert(unsigned short& n, const char* str)
{
convertInt(n, str, "unsigned short");
}
void convert(int& n, const char* str)
{
convertInt(n, str, "int");
}
void convert(unsigned int& n, const char* str)
{
convertInt(n, str, "unsigned int");
}
void convert(long& n, const char* str)
{
convertInt(n, str, "long");
}
void convert(unsigned long& n, const char* str)
{
convertInt(n, str, "unsigned long");
}
#ifdef HAVE_LONG_LONG
void convert(long long& n, const char* str)
{
convertInt(n, str, "long long");
}
#endif
#ifdef HAVE_UNSIGNED_LONG_LONG
void convert(unsigned long long& n, const char* str)
{
convertInt(n, str, "unsigned long long");
}
#endif
void convert(float& n, const char* str)
{
convertFloat(n, str, "float");
}
void convert(double& n, const char* str)
{
convertFloat(n, str, "double");
}
void convert(long double& n, const char* str)
{
convertFloat(n, str, "long double");
}
}
| 18.730769 | 94 | 0.62115 | importlib |
4a5d29f3944111cf1b6b85339919d58fcb13a027 | 11,724 | cpp | C++ | ble-cpp/src/mc/MetropolisSampler.cpp | harsh-agarwal/blelocpp | eaba46c6239981c7b8e69bef2ab33bb08ecb15b4 | [
"MIT"
] | 8 | 2016-06-13T20:47:18.000Z | 2021-12-22T17:29:32.000Z | ble-cpp/src/mc/MetropolisSampler.cpp | harsh-agarwal/blelocpp | eaba46c6239981c7b8e69bef2ab33bb08ecb15b4 | [
"MIT"
] | 11 | 2016-03-14T07:00:04.000Z | 2019-05-07T18:20:15.000Z | ble-cpp/src/mc/MetropolisSampler.cpp | harsh-agarwal/blelocpp | eaba46c6239981c7b8e69bef2ab33bb08ecb15b4 | [
"MIT"
] | 11 | 2016-02-03T07:41:00.000Z | 2019-09-11T10:03:48.000Z | /*******************************************************************************
* Copyright (c) 2014-2016 IBM Corporation and others
*
* 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 "MetropolisSampler.hpp"
namespace loc{
// Implementation
template <class Tstate, class Tinput>
void MetropolisSampler<Tstate, Tinput>::input(const Tinput& input){
mInput = input;
initialize();
}
template <class Tstate, class Tinput>
void MetropolisSampler<Tstate, Tinput>::observationModel(std::shared_ptr<ObservationModel<Tstate, Tinput>> obsModel){
mObsModel = obsModel;
}
template <class Tstate, class Tinput>
void MetropolisSampler<Tstate, Tinput>::statusInitializer(std::shared_ptr<StatusInitializerImpl> statusInitializer){
mStatusInitializer = statusInitializer;
}
template <class Tstate, class Tinput>
State MetropolisSampler<Tstate, Tinput>::findInitialMaxLikelihoodState(){
Locations locations;
if (mParams.initType == INIT_WITH_SAMPLE_LOCATIONS) {
locations = mStatusInitializer->extractLocationsCloseToBeacons(mInput, mParams.radius2D);
} else if (mParams.initType == INIT_WITH_BEACON_LOCATIONS){
locations = mStatusInitializer->generateLocationsCloseToBeaconsWithPerturbation(mInput, mParams.radius2D);
}
if(locations.size()==0){
BOOST_THROW_EXCEPTION(LocException("No location close to beacons was found in sampler."));
}
locations = Location::filterLocationsOnFlatFloor(locations); // Remove locations with an unusual z value.
locations = mStatusInitializer->extractMovableLocations(locations);
if(locations.size()==0){
std::cerr << "All locations were removed at filtering step in sampler. Not filtered locations are used." << std::endl;
if (mParams.initType == INIT_WITH_SAMPLE_LOCATIONS) {
locations = mStatusInitializer->extractLocationsCloseToBeacons(mInput, mParams.radius2D);
} else if (mParams.initType == INIT_WITH_BEACON_LOCATIONS){
locations = mStatusInitializer->generateLocationsCloseToBeaconsWithPerturbation(mInput, mParams.radius2D);
}
}
auto states = mStatusInitializer->initializeStatesFromLocations(locations);
std::vector<double> logLLs = mObsModel->computeLogLikelihood(states, mInput);
auto iterMax = std::max_element(logLLs.begin(), logLLs.end());
size_t index = std::distance(logLLs.begin(), iterMax);
Tstate locMaxLL = states.at(index);
if(isVerbose){
std::cout << "findInitialMaxLikelihoodState: states.size=" << states.size() << "max state=" << locMaxLL << std::endl;
}
return locMaxLL;
}
template <class Tstate, class Tinput>
void MetropolisSampler<Tstate, Tinput>::initialize(){
clear();
currentState = findInitialMaxLikelihoodState();
std::vector<Tstate> ss = {currentState};
currentLogLL = mObsModel->computeLogLikelihood(ss, mInput).at(0);
}
template <class Tstate, class Tinput>
void MetropolisSampler<Tstate, Tinput>::prepare(){
startBurnIn();
}
template <class Tstate, class Tinput>
void MetropolisSampler<Tstate, Tinput>::startBurnIn(int burnIn){
for(int i=0; i<burnIn; i++){
sample();
}
isBurnInFinished = true;
}
template <class Tstate, class Tinput>
void MetropolisSampler<Tstate, Tinput>::startBurnIn(){
startBurnIn(mParams.burnIn);
}
template <class Tstate, class Tinput>
std::vector<Tstate> MetropolisSampler<Tstate, Tinput>::getAllStates() const{
return allStates;
}
template <class Tstate, class Tinput>
std::vector<double> MetropolisSampler<Tstate, Tinput>::getAllLogLLs() const{
return allLogLLs;
}
template <class Tstate, class Tinput>
bool MetropolisSampler<Tstate, Tinput>::sample(){
return sample(true, true);
}
// This function returns the result whether a proposed sample was accepted or not.
template <class Tstate, class Tinput>
bool MetropolisSampler<Tstate, Tinput>::sample(bool transitLoc, bool transitRssiBias){
Tstate stateNew = transitState(currentState, transitLoc, transitRssiBias);
std::vector<Tstate> ss = {stateNew};
double logLLNew = mObsModel->computeLogLikelihood(ss, mInput).at(0);
double r = std::exp(logLLNew-currentLogLL); // p(xnew)/p(x) = exp(log(p(xnew))-log(p(xpre)))
bool isAccepted = false;
if(randGen.nextDouble() < r){
currentState = stateNew;
currentLogLL = logLLNew;
isAccepted = true;
}
// Save current state
allStates.push_back(Tstate(currentState));
allLogLLs.push_back(currentLogLL);
return isAccepted;
}
template <class Tstate, class Tinput>
std::vector<Tstate> MetropolisSampler<Tstate, Tinput>::sampling(int n){
return sampling(n, mParams.withOrdering);
/*
std::vector<Tstate> sampledStates;
int count = 0;
int countAccepted = 0;
for(int i=1; ;i++){
bool isAccepted = sample();
count++;
if(isAccepted){
countAccepted++;
}
if(i%mParams.interval==0){
sampledStates.push_back(Tstate(currentState));
}
if(sampledStates.size()>=n){
break;
}
}
std::cout << "M-H acceptance rate = " << (double)countAccepted / (double) count << " (" << countAccepted << "/" << count << ")" << std::endl;
return sampledStates;
*/
}
template <class Tstate, class Tinput>
std::vector<Tstate> MetropolisSampler<Tstate, Tinput>::sampling(int n, bool withOrderging){
if(! isBurnInFinished){
this->startBurnIn();
}
std::vector<Tstate> sampledStates;
int count = 0;
int countAccepted = 0;
for(int i=1; ;i++){
if(n==0){
break;
}
bool isAccepted = sample();
count++;
if(isAccepted){
countAccepted++;
}
if(i%mParams.interval==0){
sampledStates.push_back(Tstate(currentState));
}
if(sampledStates.size()>=n){
break;
}
}
if(isVerbose){
std::cout << "M-H acceptance rate = " << (double)countAccepted / (double) count << " (" << countAccepted << "/" << count << ")" << std::endl;
}
if(! withOrderging){
return sampledStates;
}else{
sampledStates = std::vector<State>();
std::vector<int> indices(allStates.size());
// create indices = {1,2,3,...,n};
std::iota(indices.begin(), indices.end(), 0);
std::sort(indices.begin(), indices.end(),[&](int a, int b){
return allLogLLs.at(a) < allLogLLs.at(b);
});
double logLLMemo = std::numeric_limits<double>::lowest();
for(int i=0; ;i++){
//std::cout << "indices.size() = " << indices.size() << std::endl;
int index = indices.at(indices.size()-1-i);
double logLL = allLogLLs.at(index);
// if(logLLMemo!=logLL)
{
logLLMemo = logLL;
sampledStates.push_back(allStates.at(index));
//std::cout << "state=" << allStates.at(index) << ", logLL=" << logLLMemo << std::endl;
}
if(sampledStates.size()>=n){
break;
}
}
}
return sampledStates;
}
template <class Tstate, class Tinput>
std::vector<Tstate> MetropolisSampler<Tstate, Tinput>::sampling(int n, const Location &location){
Locations locs = {location};
auto states = mStatusInitializer->initializeStatesFromLocations(locs);
std::vector<Tstate> ss = {states};
currentState = ss.at(0);
currentLogLL = mObsModel->computeLogLikelihood(ss, mInput).at(0);
std::vector<Tstate> sampledStates;
int count = 0;
int countAccepted = 0;
for(int i=1; ;i++){
if(n==0){
break;
}
bool isAccepted = sample(false, true);
count++;
if(isAccepted){
countAccepted++;
}
if(i%mParams.interval==0){
sampledStates.push_back(Tstate(currentState));
}
if(sampledStates.size()>=n){
break;
}
}
std::cout << "M-H acceptance rate = " << (double)countAccepted / (double) count << " (" << countAccepted << "/" << count << ")" << std::endl;
return sampledStates;
}
template <class Tstate, class Tinput>
State MetropolisSampler<Tstate, Tinput>::transitState(Tstate state) {
return transitState(state, true, true);
}
template <class Tstate, class Tinput>
State MetropolisSampler<Tstate, Tinput>::transitState(Tstate state, bool transitLoc, bool transitRssiBias){
// update variables that affect mainly likelihood
Tstate stateNew(state);
if (transitLoc) {
auto locNew = mStatusInitializer->perturbLocation(stateNew);
stateNew.x(locNew.x());
stateNew.y(locNew.y());
}
if (transitRssiBias) {
stateNew = mStatusInitializer->perturbRssiBias(stateNew);
}
return stateNew;
}
template <class Tstate, class Tinput>
void MetropolisSampler<Tstate, Tinput>::clear(){
allStates.clear();
allLogLLs.clear();
}
template <class Tstate, class Tinput>
void MetropolisSampler<Tstate, Tinput>::print() const{
double averageLogLL = std::accumulate(allLogLLs.begin(), allLogLLs.end(), 0.0)/(allLogLLs.size());
std::cout << "allStates.size()=" << allStates.size()
<< ",allLogLLs.size()=" << allLogLLs.size()
<< ",averageLogLL=" << averageLogLL << std::endl;
}
// explicit instantiation
template class MetropolisSampler<State, Beacons>;
}
| 38.313725 | 153 | 0.58376 | harsh-agarwal |
4a5e7f3d0eb904ca51a0068b09804230a450577c | 9,643 | hpp | C++ | src/sutil/CRegisteredCallbacks.hpp | samirmenon/sUtil | 6b75697cddf18bc309ceea571f9f687045883183 | [
"Unlicense",
"MIT"
] | 3 | 2015-04-26T03:51:13.000Z | 2019-04-09T03:33:17.000Z | src/sutil/CRegisteredCallbacks.hpp | samirmenon/sUtil | 6b75697cddf18bc309ceea571f9f687045883183 | [
"Unlicense",
"MIT"
] | 2 | 2015-03-31T22:36:33.000Z | 2016-01-25T23:31:52.000Z | src/sutil/CRegisteredCallbacks.hpp | samirmenon/sUtil | 6b75697cddf18bc309ceea571f9f687045883183 | [
"Unlicense",
"MIT"
] | null | null | null | /* This file is part of sUtil, a random collection of utilities.
See the Readme.txt file in the root folder for licensing information.
*/
/* \file CRegisteredCallbacks.hpp
*
* Created on: Sep 13, 2011
*
* Copyright (C) 2011, Samir Menon <[email protected]>
*/
#ifndef CREGISTEREDCALLBACKS_HPP_
#define CREGISTEREDCALLBACKS_HPP_
#include <sutil/CSingleton.hpp>
#include <sutil/CMappedList.hpp>
#include <vector>
#ifdef DEBUG
#include <iostream>
#endif
namespace sutil
{
// These are forward declarations. Read the class comments for details.
template <typename Idx> class CCallbackSuperBase;
template <typename Idx, typename ArgumentTuple, typename Data> class CCallbackBase;
template <typename Idx> class CRegisteredCallbacks;
/** Use this namespace to create and call callback
* functions
*
* Example usage:
*
* // 1. Defining a callback function class
*
* // NOTE: You can also use typename Data to
* // customize different objects of this class and then
* // register them.
* class CCallbackFunc : public
* sutil::CCallbackBase<std::string, std::vector<std::string> >
* {
* typedef sutil::CCallbackBase<std::string, std::vector<std::string> > base;
* public:
* virtual void call(std::vector<std::string>& args)
* {//Do something with the argument
* std::vector<std::string>::iterator it,ite;
* for(it = args.begin(), ite = args.end(); it!=ite; ++it)
* { std::cout<<"\nPassed arg : "<<*it; }
*
* //And/or copy the result into it
* std::string x;
* std::cin>>x;
* args.push_back(x);
* }
*
* virtual base* createObject()
* { return dynamic_cast<base*>(new CCallbackFunc()); }
* };
*
* //2. Register the function
* std::string name("BoboFunc");
* std::vector<std::string> args;
*
* flag = sutil::callbacks::add<CCallbackFunc,
* std::string, std::vector<std::string> >(name);
*
* //3. Call the function
* sutil::callbacks::call<std::string,std::vector<std::string> >(callback_name,args);
*/
namespace callbacks
{
/** This function returns an indexed callback (if the
* callback has already been registered with the singleton) */
template<typename Idx, typename ArgumentTuple, typename Data=bool >
bool call(const Idx& arg_callback_name, ArgumentTuple& args)
{
CCallbackSuperBase<Idx>** mapped_callback =
CRegisteredCallbacks<Idx>::getCallbacks()->at(arg_callback_name);
if(0 == mapped_callback) { return false; } //Function not found.
CCallbackBase<Idx, ArgumentTuple, Data>* callback =
dynamic_cast<CCallbackBase<Idx, ArgumentTuple, Data>*>(*mapped_callback);
if(NULL == callback)
{ return false; }
callback->call(args); //The actual function call
return true; //Everything worked out
}
/** Why do we allow specifying Data?
* Ans: Well a class might automatically and uniquely
* initialize the Data in the constructor */
template< typename CallbackClass, typename Idx,
typename ArgumentTuple, typename Data=bool >
bool add(const Idx& arg_callback_name)
{
CallbackClass f;
return f.sutil::CCallbackBase<Idx, ArgumentTuple, Data>::
registerCallback(arg_callback_name);
}
template< typename CallbackClass, typename Idx,
typename ArgumentTuple, typename Data>
bool add(const Idx& arg_callback_name, Data* arg_data)
{
CallbackClass f;
return f.sutil::CCallbackBase<Idx, ArgumentTuple, Data>::
registerCallback(arg_callback_name, arg_data);
}
/** Return a list of the registered callbacks (a vector of indices) */
template<typename Idx>
bool list(std::vector<Idx>& idxlist)
{ typedef CMappedPointerList<Idx,CCallbackSuperBase<Idx>,true> map;
map* m = CRegisteredCallbacks<Idx>::getCallbacks();
if(NULL == m) { return false; }
typename map::iterator it,ite;
idxlist.clear();
for(it = m->begin(), ite = m->end();it!=ite;++it)
{ idxlist.push_back(!it); }//Add the index to the vector
return true;
}
}
/** This class implements a callback factory singleton. In plain English,
* it is a one-of-a-kind class that can give you an function based on
* its name.
*
* NOTE: The singleton manages its memory and deletes all the pointers. */
template <typename Idx>
class CRegisteredCallbacks : private CSingleton<CMappedPointerList<Idx,CCallbackSuperBase<Idx>,true> >
{
//A typedef for easy use;
typedef CSingleton<CMappedPointerList<Idx,CCallbackSuperBase<Idx>,true> > singleton;
//So that the base class can call the register function
friend class CCallbackSuperBase<Idx>;
public:
/** Checks whether this callback has been registered with the factory */
static bool callbackRegistered(const Idx& arg_callback_name)
{
CCallbackSuperBase<Idx>** mapped_callback = singleton::getData()->at(arg_callback_name);
if(0 == mapped_callback) { return false; }
return true;
}
/** Deletes the singleton object and creates a new one
* in its stead */
static bool resetCallbacks()
{ return singleton::resetData(); }
/** Used to access the callback list */
static CMappedPointerList<Idx,CCallbackSuperBase<Idx>,true>* getCallbacks()
{ return singleton::getData(); }
private:
/** This function registers new dynamic callbacks with the factory.
* You can get objects of this callback by calling the
* createObjectForCallback function */
static bool registerCallback(const Idx& arg_callback_name,
CCallbackSuperBase<Idx>* arg_callback_object)
{
if(callbackRegistered(arg_callback_name))
{
#ifdef DEBUG
std::cerr<<"\nCRegisteredCallbacks::registerCallback() Warning :"
<<" The passed callback is already registered.";
#endif
return false;
}
// Creates an object that points to the passed callback object
CCallbackSuperBase<Idx>** t = singleton::getData()->
create(arg_callback_name,arg_callback_object);
if(0 == t)
{
#ifdef DEBUG
std::cerr<<"\nCRegisteredCallbacks::registerCallback() Error :"
<<" Failed to create callback in the callback mapped list.";
#endif
return false;
}
return true;
}
/** Private for the singleton */
CRegisteredCallbacks();
/** Private for the singleton */
CRegisteredCallbacks(const CRegisteredCallbacks&);
/** Private for the singleton */
CRegisteredCallbacks& operator= (const CRegisteredCallbacks&);
};
/** *********************************************************
* To support indexed querying for dynamic object allocation:
* Subclass CCallbackSuperBase and implement the createObject()
* function to return an object of the wanted callback.
* ********************************************************* */
template <typename Idx>
class CCallbackSuperBase
{
public:
/** Default Destructor : Does nothing */
virtual ~CCallbackSuperBase(){}
protected:
/** The constructor may only be called by a subclass */
CCallbackSuperBase(){}
/** To allow the callback registry to create objects for itself */
virtual bool registerCallbackSuper(
const Idx &arg_callback_name,
CCallbackSuperBase* arg_obj)
{
return CRegisteredCallbacks<Idx>::
registerCallback(arg_callback_name,arg_obj);
}
private:
/** Must name a callback while creating an object */
CCallbackSuperBase(const CCallbackSuperBase&);
/** Must name a callback while creating an object */
CCallbackSuperBase& operator= (const CCallbackSuperBase&);
};
/** *********************************************************
* This enables supporting dynamic typing for arbitrary
* index and object callbacks.
* ********************************************************* */
template <typename Idx, typename ArgumentTuple, typename Data=bool>
class CCallbackBase : public CCallbackSuperBase<Idx>
{
public:
/** A subclass must implement this function.
* You can choose to add a "return type" into
* the ArgumentTuple and get data from the function. */
virtual void call(ArgumentTuple& args) = 0;
/** A subclass must implement this function */
virtual CCallbackBase<Idx, ArgumentTuple, Data>* createObject()=0;
virtual bool registerCallback(
const Idx& arg_callback_name,
Data* arg_data = 0)
{
bool flag;
flag = CRegisteredCallbacks<Idx>::callbackRegistered(arg_callback_name);
if(flag)//Callback already registered. Do nothing and return false.
{ return false; }
else
{
//Duplicate this object and register the new one with the singleton
CCallbackBase<Idx,ArgumentTuple,Data>* obj = createObject();
//Set up data for this function object
if(0 != arg_data)
{ obj->data_ = arg_data; }
flag = CCallbackSuperBase<Idx>::registerCallbackSuper(
arg_callback_name,
dynamic_cast<CCallbackSuperBase<Idx>*>(obj) );
if(!flag)
{ delete obj; return false; }
}
return true;
}
/** Default Destructor : Does nothing */
virtual ~CCallbackBase(){}
protected:
/** Only a subclass may create an object of this type */
CCallbackBase() : data_(NULL){}
Data* data_;
private:
CCallbackBase(const CCallbackBase&);
CCallbackBase& operator= (const CCallbackBase&);
};
}
#endif /* CREGISTEREDCALLBACKS_HPP_ */
| 32.911263 | 104 | 0.649176 | samirmenon |
4a64925586459e57961c312fddfbaef60a543db5 | 4,835 | cpp | C++ | cpp_files/caffe_jni.cpp | malreddysid/sudoku_android | 2018aea4fbf11ccc739aeed8a22c97b6e0319fdc | [
"MIT"
] | 2 | 2016-08-10T12:05:05.000Z | 2016-08-10T12:10:14.000Z | cpp_files/caffe_jni.cpp | malreddysid/sudoku_android | 2018aea4fbf11ccc739aeed8a22c97b6e0319fdc | [
"MIT"
] | null | null | null | cpp_files/caffe_jni.cpp | malreddysid/sudoku_android | 2018aea4fbf11ccc739aeed8a22c97b6e0319fdc | [
"MIT"
] | null | null | null | #include <string.h>
#include <jni.h>
#include <android/log.h>
#include <string>
#include <vector>
#ifdef USE_EIGEN
#include <omp.h>
#else
#include <cblas.h>
#endif
#include "caffe/caffe.hpp"
#include "caffe_mobile.hpp"
#ifdef __cplusplus
extern "C" {
#endif
using std::string;
using std::vector;
using caffe::CaffeMobile;
int getTimeSec() {
struct timespec now;
clock_gettime(CLOCK_MONOTONIC, &now);
return (int)now.tv_sec;
}
string jstring2string(JNIEnv *env, jstring jstr) {
const char *cstr = env->GetStringUTFChars(jstr, 0);
string str(cstr);
env->ReleaseStringUTFChars(jstr, cstr);
return str;
}
JNIEXPORT void JNICALL
Java_com_sh1r0_caffe_1android_1lib_CaffeMobile_setNumThreads(JNIEnv *env,
jobject thiz,
jint numThreads) {
int num_threads = numThreads;
#ifdef USE_EIGEN
omp_set_num_threads(num_threads);
#else
openblas_set_num_threads(num_threads);
#endif
}
JNIEXPORT void JNICALL Java_com_sh1r0_caffe_1android_1lib_CaffeMobile_enableLog(
JNIEnv *env, jobject thiz, jboolean enabled) {}
JNIEXPORT jint JNICALL Java_com_sh1r0_caffe_1android_1lib_CaffeMobile_loadModel(
JNIEnv *env, jobject thiz, jstring modelPath, jstring weightsPath) {
CaffeMobile::Get(jstring2string(env, modelPath),
jstring2string(env, weightsPath));
return 0;
}
JNIEXPORT void JNICALL
Java_com_sh1r0_caffe_1android_1lib_CaffeMobile_setMeanWithMeanFile(
JNIEnv *env, jobject thiz, jstring meanFile) {
CaffeMobile *caffe_mobile = CaffeMobile::Get();
caffe_mobile->SetMean(jstring2string(env, meanFile));
}
JNIEXPORT void JNICALL
Java_com_sh1r0_caffe_1android_1lib_CaffeMobile_setMeanWithMeanValues(
JNIEnv *env, jobject thiz, jfloatArray meanValues) {
CaffeMobile *caffe_mobile = CaffeMobile::Get();
int num_channels = env->GetArrayLength(meanValues);
jfloat *ptr = env->GetFloatArrayElements(meanValues, 0);
vector<float> mean_values(ptr, ptr + num_channels);
caffe_mobile->SetMean(mean_values);
}
JNIEXPORT void JNICALL Java_com_sh1r0_caffe_1android_1lib_CaffeMobile_setScale(
JNIEnv *env, jobject thiz, jfloat scale) {
CaffeMobile *caffe_mobile = CaffeMobile::Get();
caffe_mobile->SetScale(scale);
}
JNIEXPORT jfloatArray JNICALL
Java_com_sh1r0_caffe_1android_1lib_CaffeMobile_getConfidenceScore(
JNIEnv *env, jobject thiz, jstring imgPath) {
CaffeMobile *caffe_mobile = CaffeMobile::Get();
vector<float> conf_score =
caffe_mobile->GetConfidenceScore(jstring2string(env, imgPath));
jfloatArray result;
result = env->NewFloatArray(conf_score.size());
if (result == NULL) {
return NULL; /* out of memory error thrown */
}
// move from the temp structure to the java structure
env->SetFloatArrayRegion(result, 0, conf_score.size(), &conf_score[0]);
return result;
}
JNIEXPORT jintArray JNICALL
Java_com_sh1r0_caffe_1android_1lib_CaffeMobile_predictImage(JNIEnv *env,
jobject thiz,
jstring imgPath,
jint k) {
CaffeMobile *caffe_mobile = CaffeMobile::Get();
vector<int> top_k =
caffe_mobile->PredictTopK(jstring2string(env, imgPath), k);
jintArray result;
result = env->NewIntArray(k);
if (result == NULL) {
return NULL; /* out of memory error thrown */
}
// move from the temp structure to the java structure
env->SetIntArrayRegion(result, 0, k, &top_k[0]);
return result;
}
JNIEXPORT jobjectArray JNICALL
Java_com_sh1r0_caffe_1android_1lib_CaffeMobile_extractFeatures(
JNIEnv *env, jobject thiz, jstring imgPath, jstring blobNames) {
CaffeMobile *caffe_mobile = CaffeMobile::Get();
vector<vector<float>> features = caffe_mobile->ExtractFeatures(
jstring2string(env, imgPath), jstring2string(env, blobNames));
jobjectArray array2D =
env->NewObjectArray(features.size(), env->FindClass("[F"), NULL);
for (size_t i = 0; i < features.size(); ++i) {
jfloatArray array1D = env->NewFloatArray(features[i].size());
if (array1D == NULL) {
return NULL; /* out of memory error thrown */
}
// move from the temp structure to the java structure
env->SetFloatArrayRegion(array1D, 0, features[i].size(), &features[i][0]);
env->SetObjectArrayElement(array2D, i, array1D);
}
return array2D;
}
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) {
JNIEnv *env = NULL;
jint result = -1;
if (vm->GetEnv((void **)&env, JNI_VERSION_1_6) != JNI_OK) {
LOG(FATAL) << "GetEnv failed!";
return result;
}
FLAGS_redirecttologcat = true;
FLAGS_android_logcat_tag = "caffe_jni";
return JNI_VERSION_1_6;
}
#ifdef __cplusplus
}
#endif
| 30.796178 | 80 | 0.696174 | malreddysid |
4a6e85f157a7c7f9ee4d3a3ae7de86cb7102000f | 1,221 | hpp | C++ | boost/network/protocol/http/message/wrappers/anchor.hpp | antoinelefloch/cpp-netlib | 5eb9b5550a10d06f064ee9883c7d942d3426f31b | [
"BSL-1.0"
] | 3 | 2015-02-10T22:08:08.000Z | 2021-11-13T20:59:25.000Z | include/boost/network/protocol/http/message/wrappers/anchor.hpp | waTeim/boost | eb3850fae8c037d632244cf15cf6905197d64d39 | [
"BSL-1.0"
] | 1 | 2018-08-10T04:47:12.000Z | 2018-08-10T13:54:57.000Z | include/boost/network/protocol/http/message/wrappers/anchor.hpp | waTeim/boost | eb3850fae8c037d632244cf15cf6905197d64d39 | [
"BSL-1.0"
] | 5 | 2017-12-28T12:42:25.000Z | 2021-07-01T07:41:53.000Z | #ifndef BOOST_NETWORK_PROTOCOL_HTTP_MESSAGE_WRAPPERS_ANCHOR_HPP_20100618
#define BOOST_NETWORK_PROTOCOL_HTTP_MESSAGE_WRAPPERS_ANCHOR_HPP_20100618
// Copyright 2010 (c) Dean Michael Berris.
// Copyright 2010 (c) Sinefunc, Inc.
// 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)
namespace boost { namespace network { namespace http {
template <class Tag>
struct basic_request;
namespace impl {
template <class Tag>
struct anchor_wrapper {
basic_request<Tag> const & message_;
anchor_wrapper(basic_request<Tag> const & message)
: message_(message) {}
typedef typename basic_request<Tag>::string_type string_type;
operator string_type() {
return message_.anchor();
}
};
}
template <class Tag> inline
impl::anchor_wrapper<Tag>
anchor(basic_request<Tag> const & request) {
return impl::anchor_wrapper<Tag>(request);
}
} // namespace http
} // namespace network
} // nmaespace boost
#endif // BOOST_NETWORK_PROTOCOL_HTTP_MESSAGE_WRAPPERS_ANCHOR_HPP_20100618
| 29.780488 | 74 | 0.689599 | antoinelefloch |
4a6f0ef95381bfd42ad02c0f8cc864fa7f262cc2 | 1,279 | cpp | C++ | Problems/ej/it-e/main.cpp | grand87/timus | 8edcae276ab74b68fff18da3722460f492534a8a | [
"MIT"
] | null | null | null | Problems/ej/it-e/main.cpp | grand87/timus | 8edcae276ab74b68fff18da3722460f492534a8a | [
"MIT"
] | 1 | 2019-05-09T19:17:00.000Z | 2019-05-09T19:17:00.000Z | Problems/ej/it-e/main.cpp | grand87/timus | 8edcae276ab74b68fff18da3722460f492534a8a | [
"MIT"
] | null | null | null | #include<iostream>
#include<algorithm>
using namespace std;
int net[1000][1000];
bool visited[1000] = {false};
int getFirstUnvistedNode(bool* nodes, int size) {
for (int i = 0; i < size; i++)
if (!nodes[i])
return i;
return size;
}
int dfs(int nodeIndex, int net[1000][1000], bool* visited, int nodesCount) {
int vistis = 0;
if (!visited[nodeIndex]) {
vistis++;
visited[nodeIndex] = true;
for (int i = 0; i < nodesCount; i++) {
if (net[nodeIndex][i]) {
vistis += dfs(i, net, visited, nodesCount);
}
}
}
return vistis;
}
int main()
{
//#ifndef ONLINE_JUDGE
// freopen("input.txt", "rt", stdin);
//#endif
int friends;
cin >> friends;
for (int i = 0; i < friends; i++)
for (int j = 0; j < friends; j++)
cin >> net[i][j];
int nodesVisited = 0;
int nodeIndex = getFirstUnvistedNode(visited, friends);
int paths = 1;
while (nodesVisited < friends && nodeIndex < friends) {
nodesVisited += dfs(nodeIndex, net, visited, friends);
if (nodesVisited < friends) {
paths++;
nodeIndex = getFirstUnvistedNode(visited, friends);
}
}
cout << paths;
return 0;
} | 22.839286 | 76 | 0.545739 | grand87 |
4a79db6c722db364b380ae93722af5eff778d9bd | 7,921 | hpp | C++ | lib/soc/stm32l011xx/mcu.hpp | JayKickliter/CML | d21061a3abc013a8386798280b9595e9d4a2978c | [
"MIT"
] | null | null | null | lib/soc/stm32l011xx/mcu.hpp | JayKickliter/CML | d21061a3abc013a8386798280b9595e9d4a2978c | [
"MIT"
] | null | null | null | lib/soc/stm32l011xx/mcu.hpp | JayKickliter/CML | d21061a3abc013a8386798280b9595e9d4a2978c | [
"MIT"
] | null | null | null | #pragma once
/*
Name: mcu.hpp
Copyright(c) 2019 Mateusz Semegen
This code is licensed under MIT license (see LICENSE file for details)
*/
//std
#include <cstdint>
//externals
#include <stm32l0xx.h>
//cml
#include <cml/bit.hpp>
#include <cml/frequency.hpp>
namespace soc {
namespace stm32l011xx {
struct mcu
{
enum class Clock : uint32_t
{
msi = RCC_CR_MSION,
hsi = RCC_CR_HSION,
pll = RCC_CR_PLLON,
lsi
};
enum class Sysclk_source : uint32_t
{
msi = RCC_CFGR_SW_MSI,
hsi = RCC_CFGR_SW_HSI,
pll = RCC_CFGR_SW_PLL
};
enum class Msi_frequency : uint32_t
{
_65536_Hz = 0,
_131072_Hz = 1,
_262144_Hz = 2,
_524288_Hz = 3,
_1048_kHz = 4,
_2097_kHz = 5,
_4194_kHz = 6
};
enum class Hsi_frequency : uint32_t
{
_16_MHz
};
enum class Lsi_frequency : uint32_t
{
_37_kHz
};
enum class Flash_latency : uint32_t
{
_0 = 0,
_1 = FLASH_ACR_LATENCY,
unknown
};
enum class Voltage_scaling : uint32_t
{
_1 = PWR_CR_VOS_0,
_2 = PWR_CR_VOS_1,
_3 = PWR_CR_VOS_0 | PWR_CR_VOS_1,
unknown
};
enum class Reset_source : uint32_t
{
illegal_low_power = RCC_CSR_LPWRRSTF,
window_watchdog = RCC_CSR_WWDGRSTF,
independent_window_watchdog = RCC_CSR_IWDGRSTF,
software = RCC_CSR_SFTRSTF,
por_bdr = RCC_CSR_PORRSTF,
pin = RCC_CSR_PINRSTF,
option_byte_loader = RCC_CSR_OBLRSTF
};
struct Pll_config
{
enum class Source : uint32_t
{
hsi = RCC_CFGR_PLLSRC_HSI
};
enum class Multiplier
{
_3 = RCC_CFGR_PLLMUL3,
_4 = RCC_CFGR_PLLMUL4,
_6 = RCC_CFGR_PLLMUL6,
_8 = RCC_CFGR_PLLMUL8,
_12 = RCC_CFGR_PLLMUL12,
_16 = RCC_CFGR_PLLMUL16,
_24 = RCC_CFGR_PLLMUL24,
_32 = RCC_CFGR_PLLMUL32,
_48 = RCC_CFGR_PLLMUL48,
unknown
};
enum class Divider
{
_2 = RCC_CFGR_PLLDIV2,
_3 = RCC_CFGR_PLLDIV3,
_4 = RCC_CFGR_PLLDIV4,
unknown
};
Source source;
bool hsidiv_enabled = false;
Multiplier multiplier = Multiplier::unknown;
Divider divider = Divider::unknown;
};
struct Device_id
{
const uint8_t serial_number[12] = { 0 };
const uint32_t type = 0;
};
struct Sysclk_frequency_change_callback
{
using Function = void(*)(void* a_p_user_data);
Function function = nullptr;
void* p_user_data = nullptr;
};
struct Bus_prescalers
{
enum class AHB
{
_1,
_2,
_4,
_8,
_16,
_64,
_128,
_256,
unknown
};
enum class APB1
{
_1,
_2,
_4,
_8,
_16,
unknown
};
enum class APB2
{
_1,
_2,
_4,
_8,
_16,
unknown
};
AHB ahb = AHB::unknown;
APB1 apb1 = APB1::unknown;
APB2 apb2 = APB2::unknown;
};
public:
static void enable_msi_clock(Msi_frequency a_freq);
static void enable_hsi_clock(Hsi_frequency a_freq);
static void enable_lsi_clock(Lsi_frequency a_freq);
static void disable_msi_clock();
static void disable_hsi_clock();
static void disable_lsi_clock();
static void enable_pll(const Pll_config& a_pll_config);
static void disable_pll();
static void set_sysclk(Sysclk_source a_source, const Bus_prescalers& a_prescalers);
static void reset();
static void halt();
static void register_pre_sysclk_frequency_change_callback(const Sysclk_frequency_change_callback& a_callback);
static void register_post_sysclk_frequency_change_callback(const Sysclk_frequency_change_callback& a_callback);
static Bus_prescalers get_bus_prescalers();
static Pll_config get_pll_config();
static void enable_syscfg()
{
cml::set_flag(&(RCC->APB2ENR), RCC_APB2ENR_SYSCFGEN);
}
static void disable_syscfg()
{
cml::clear_flag(&(RCC->APB2ENR), RCC_APB2ENR_SYSCFGEN);
}
static bool is_syscfg_enabled()
{
return cml::is_flag(RCC->APB2ENR, RCC_APB2ENR_SYSCFGEN);
}
static Device_id get_device_id()
{
const uint8_t* p_id_location = reinterpret_cast<uint8_t*>(UID_BASE);
return { { p_id_location[0], p_id_location[1], p_id_location[2], p_id_location[3],
p_id_location[4], p_id_location[5], p_id_location[6], p_id_location[7],
p_id_location[8], p_id_location[9], p_id_location[10], p_id_location[11] },
DBGMCU->IDCODE
};
}
static Sysclk_source get_sysclk_source()
{
return static_cast<Sysclk_source>(cml::get_flag(RCC->CFGR, RCC_CFGR_SWS) >> RCC_CFGR_SWS_Pos);
}
static uint32_t get_sysclk_frequency_hz()
{
return SystemCoreClock;
}
static constexpr cml::frequency get_hsi_frequency_hz()
{
return cml::MHz(16u);
}
static constexpr cml::frequency get_lsi_frequency_hz()
{
return cml::kHz(37u);
}
static bool is_clock_enabled(Clock a_clock)
{
switch (a_clock)
{
case Clock::msi:
case Clock::hsi:
case Clock::pll:
{
return cml::is_flag(RCC->CR, static_cast<uint32_t>(a_clock));
}
break;
case Clock::lsi:
{
return cml::is_flag(RCC->CSR, RCC_CSR_LSION);
}
break;
}
return false;
}
static Voltage_scaling get_voltage_scaling()
{
return static_cast<Voltage_scaling>(cml::get_flag(PWR->CR, PWR_CR_VOS));
}
static Flash_latency get_flash_latency()
{
return static_cast<Flash_latency>(cml::get_flag(FLASH->ACR, FLASH_ACR_LATENCY));
}
static Reset_source get_reset_source()
{
uint32_t flag = cml::get_flag(RCC->CSR, 0xFB000000u);
if (flag == 0x0u)
{
flag = RCC_CSR_PINRSTF;
}
cml::set_flag(&(RCC->CSR), RCC_CSR_RMVF);
return static_cast<Reset_source>(flag);
}
private:
mcu() = delete;
mcu(const mcu&) = delete;
mcu(mcu&&) = delete;
~mcu() = default;
mcu& operator = (const mcu&) = delete;
mcu& operator = (mcu&&) = delete;
static Flash_latency select_flash_latency(uint32_t a_syclk_freq, Voltage_scaling a_voltage_scaling);
static Voltage_scaling select_voltage_scaling(Sysclk_source a_source, uint32_t a_sysclk_freq);
static void set_flash_latency(Flash_latency a_latency);
static void set_voltage_scaling(Voltage_scaling a_scaling);
static void set_sysclk_source(Sysclk_source a_sysclk_source);
static void set_bus_prescalers(const Bus_prescalers& a_prescalers);
static void increase_sysclk_frequency(Sysclk_source a_source,
cml::frequency a_frequency_hz,
const Bus_prescalers& a_prescalers);
static void decrease_sysclk_frequency(Sysclk_source a_source,
cml::frequency a_frequency_hz,
const Bus_prescalers& a_prescalers);
static uint32_t calculate_frequency_from_pll_configuration();
};
} // namespace stm32l011xx
} // namespace soc | 24.447531 | 115 | 0.573539 | JayKickliter |
4a79f5b0472a0acd03b9b8c3cae5ed72a228f525 | 1,741 | cpp | C++ | src/channel_utility.cpp | tangzhenquan/libatbus | a842439ffc6b9c05a94e79f52bf3b1a5c57da0a2 | [
"BSL-1.0",
"MIT"
] | 49 | 2015-03-10T06:41:17.000Z | 2021-03-16T05:10:34.000Z | src/channel_utility.cpp | tangzhenquan/libatbus | a842439ffc6b9c05a94e79f52bf3b1a5c57da0a2 | [
"BSL-1.0",
"MIT"
] | 1 | 2017-04-22T15:22:16.000Z | 2019-01-08T04:58:23.000Z | src/channel_utility.cpp | tangzhenquan/libatbus | a842439ffc6b9c05a94e79f52bf3b1a5c57da0a2 | [
"BSL-1.0",
"MIT"
] | 20 | 2015-11-03T08:48:41.000Z | 2021-03-16T05:10:37.000Z | /**
* @brief 所有channel文件的模式均为 c + channel<br />
* 使用c的模式是为了简单、结构清晰并且避免异常<br />
* 附带c++的部分是为了避免命名空间污染并且c++的跨平台适配更加简单
*/
#include <cstdio>
#include "common/string_oprs.h"
#include "detail/libatbus_channel_export.h"
namespace atbus {
namespace channel {
bool make_address(const char *in, channel_address_t &addr) {
addr.address = in;
// 获取协议
size_t scheme_end = addr.address.find_first_of("://");
if (addr.address.npos == scheme_end) {
return false;
}
addr.scheme = addr.address.substr(0, scheme_end);
size_t port_end = addr.address.find_last_of(":");
addr.port = 0;
if (addr.address.npos != port_end && port_end >= scheme_end + 3) {
UTIL_STRFUNC_SSCANF(addr.address.c_str() + port_end + 1, "%d", &addr.port);
}
// 截取域名
addr.host = addr.address.substr(scheme_end + 3, (port_end == addr.address.npos) ? port_end : port_end - scheme_end - 3);
return true;
}
void make_address(const char *scheme, const char *host, int port, channel_address_t &addr) {
addr.scheme = scheme;
addr.host = host;
addr.port = port;
addr.address.reserve(addr.scheme.size() + addr.host.size() + 4 + 8);
addr.address = addr.scheme + "://" + addr.host;
if (port > 0) {
char port_str[16] = {0};
UTIL_STRFUNC_SNPRINTF(port_str, sizeof(port_str), "%d", port);
addr.address += ":";
addr.address += &port_str[0];
}
}
}
}
| 32.849057 | 133 | 0.517519 | tangzhenquan |
4a7d2f0f81da0a1387ae06aa8e8f17b5710c0306 | 1,835 | cpp | C++ | contracts/wawaka/common/StateReference.cpp | marcelamelara/private-data-objects | be6841715865d4733b6555f416c56dde8839849e | [
"Apache-2.0"
] | null | null | null | contracts/wawaka/common/StateReference.cpp | marcelamelara/private-data-objects | be6841715865d4733b6555f416c56dde8839849e | [
"Apache-2.0"
] | null | null | null | contracts/wawaka/common/StateReference.cpp | marcelamelara/private-data-objects | be6841715865d4733b6555f416c56dde8839849e | [
"Apache-2.0"
] | null | null | null | /* Copyright 2019 Intel Corporation
*
* 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 "StateReference.h"
// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
// Class: ww::value::StateReference
// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
// -----------------------------------------------------------------
bool ww::value::StateReference::deserialize(const ww::value::Object& reference)
{
if (! reference.validate_schema(STATE_REFERENCE_SCHEMA))
return false;
contract_id_ = reference.get_string("contract_id");
state_hash_ = reference.get_string("state_hash");
return true;
}
// -----------------------------------------------------------------
bool ww::value::StateReference::serialize(ww::value::Value& serialized_reference) const
{
ww::value::Structure reference(STATE_REFERENCE_SCHEMA);
if (! reference.set_string("contract_id", contract_id_.c_str()))
return false;
if (! reference.set_string("state_hash", state_hash_.c_str()))
return false;
serialized_reference.set(reference);
return true;
}
// -----------------------------------------------------------------
bool ww::value::StateReference::add_to_response(Response& rsp) const
{
return rsp.add_dependency(contract_id_, state_hash_);
}
| 35.980392 | 87 | 0.666485 | marcelamelara |
4a7e596a5d27f1c9928fb8c3adaa3be1b853d2ab | 2,258 | cpp | C++ | src/util/generic.cpp | nabijaczleweli/pb-cpp | ccf28ba3dd7a3ec7898bc155f6b14755cc79a8f3 | [
"MIT"
] | 9 | 2018-01-11T10:41:25.000Z | 2020-01-14T06:49:56.000Z | src/util/generic.cpp | nabijaczleweli/pb-cpp | ccf28ba3dd7a3ec7898bc155f6b14755cc79a8f3 | [
"MIT"
] | 1 | 2018-06-29T22:03:53.000Z | 2018-06-30T00:04:19.000Z | src/util/generic.cpp | nabijaczleweli/pb-cpp | ccf28ba3dd7a3ec7898bc155f6b14755cc79a8f3 | [
"MIT"
] | null | null | null | // The MIT License (MIT)
// Copyright (c) 2017 nabijaczleweli
// 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 "../../include/pb-cpp/util.hpp"
#include <cmath>
std::ostream & pb::util::operator<<(std::ostream & out, human_readable hr) {
static const auto ln_kib = std::log(1024.);
static const char * suffixes[] = {"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"};
if(hr.size == 0)
out << "0 B";
else {
const auto exp = std::min(std::max(static_cast<std::size_t>(std::log(static_cast<double>(hr.size)) / ln_kib), static_cast<std::size_t>(0)),
sizeof(suffixes) / sizeof(*suffixes));
const auto val = static_cast<double>(hr.size) / std::pow(2., exp * 10);
if(exp > 0)
out << std::round(val * 10.) / 10. << ' ' << suffixes[static_cast<std::size_t>(exp)];
else
out << std::round(val) << ' ' << suffixes[0];
}
return out;
}
pb::util::human_readable pb::util::make_human_readable(std::size_t size) {
return {size};
}
pb::util::cursor_up_mover pb::util::move_cursor_up(std::size_t by) {
return {by};
}
pb::util::cursor_hide::cursor_hide(bool a) : actually(a) {
if(actually)
hide();
}
pb::util::cursor_hide::~cursor_hide() {
if(actually)
restore();
}
| 34.738462 | 141 | 0.687777 | nabijaczleweli |
4a7fe3eb7b966c5b6159f9bfc90663d9a73e9f2f | 214 | cpp | C++ | .history/src/log_20200716172848.cpp | zoedsy/LibManage | 590311fb035d11daa209301f9ce76f53ccae7643 | [
"MIT"
] | 1 | 2021-03-16T05:22:46.000Z | 2021-03-16T05:22:46.000Z | .history/src/log_20200716172848.cpp | zoedsy/LibManage | 590311fb035d11daa209301f9ce76f53ccae7643 | [
"MIT"
] | null | null | null | .history/src/log_20200716172848.cpp | zoedsy/LibManage | 590311fb035d11daa209301f9ce76f53ccae7643 | [
"MIT"
] | null | null | null | /*
* @Author: your name
* @Date: 2020-07-16 17:28:47
* @LastEditTime: 2020-07-16 17:28:48
* @LastEditors: Please set LastEditors
* @Description: In User Settings Edit
* @FilePath: \LibManage\src\log.cpp
*/
| 23.777778 | 39 | 0.672897 | zoedsy |
4a821fb67de99b4fe87185440310b4838847a6b5 | 10,005 | hpp | C++ | benchmark/bm_conv.hpp | matazure/mtensor | 4289284b201cb09ed1dfc49f44d6738751affd63 | [
"MIT"
] | 82 | 2020-04-11T09:33:36.000Z | 2022-03-23T03:47:25.000Z | benchmark/bm_conv.hpp | Lexxos/mtensor | feb120923dad3fb4ae3b31dd09931622a63c3d06 | [
"MIT"
] | 28 | 2017-04-26T17:12:35.000Z | 2019-04-08T04:05:24.000Z | benchmark/bm_conv.hpp | Lexxos/mtensor | feb120923dad3fb4ae3b31dd09931622a63c3d06 | [
"MIT"
] | 22 | 2017-01-10T14:57:29.000Z | 2019-12-17T08:55:59.000Z | #pragma once
#include "bm_config.hpp"
namespace _tmp {
#ifndef MATAZURE_CUDA
using matazure::for_index;
using matazure::tensor;
#else
using matazure::cuda::for_index;
using matazure::cuda::tensor;
#endif
}
template <typename tensor_type>
inline void bm_tensor2f_general_roll_conv(benchmark::State& state) {
const static int_t rank = tensor_type::rank;
typedef typename tensor_type::value_type value_type;
pointi<rank> shape;
fill(shape, state.range(0));
pointi<rank> kernel_shape;
fill(kernel_shape, 3);
tensor_type kernel(kernel_shape);
auto kernel_radius = kernel_shape / 2;
tensor_type ts_dst(shape);
tensor_type ts_src_pad(shape + kernel.shape() - 1);
auto ts_src_view = view::slice(ts_src_pad, kernel_radius, shape);
while (state.KeepRunning()) {
_tmp::for_index(ts_dst.shape(), MLAMBDA(pointi<rank> idx) {
auto re = zero<value_type>::value();
for_index(zero<pointi<rank>>::value(), kernel_shape, [&](pointi<rank> neigbor_idx) {
re += kernel(neigbor_idx) * ts_src_view(idx + neigbor_idx - kernel_radius);
});
ts_dst(idx) = re;
});
benchmark::DoNotOptimize(ts_dst.data());
}
state.SetBytesProcessed(state.iterations() * static_cast<size_t>(ts_src_pad.size()) *
sizeof(ts_dst[0]));
state.SetItemsProcessed(state.iterations() * static_cast<size_t>(ts_dst.size()) *
kernel.size() * 2);
}
template <typename tensor_type>
inline void bm_tensor2f_general_unroll_conv(benchmark::State& state) {
const static int_t rank = tensor_type::rank;
typedef typename tensor_type::value_type value_type;
pointi<rank> shape;
fill(shape, state.range(0));
pointi<rank> kernel_shape;
fill(kernel_shape, 3);
tensor_type kernel(kernel_shape);
auto kernel_radius = kernel_shape / 2;
tensor_type ts_dst(shape);
tensor_type ts_src_pad(shape + kernel.shape() - 1);
auto ts_src_view = view::slice(ts_src_pad, kernel_radius, shape);
while (state.KeepRunning()) {
_tmp::for_index(ts_dst.shape(), MLAMBDA(pointi<rank> idx) {
// clang-format off
auto re = zero<value_type>::value();
re += kernel(pointi<2>{0, 0}) * ts_src_view(idx + pointi<2>{-1, -1});
re += kernel(pointi<2>{1, 0}) * ts_src_view(idx + pointi<2>{ 0, -1});
re += kernel(pointi<2>{2, 0}) * ts_src_view(idx + pointi<2>{ 1, -1});
re += kernel(pointi<2>{0, 1}) * ts_src_view(idx + pointi<2>{-1, 0});
re += kernel(pointi<2>{1, 1}) * ts_src_view(idx + pointi<2>{ 0, 0});
re += kernel(pointi<2>{2, 1}) * ts_src_view(idx + pointi<2>{ 1, 0});
re += kernel(pointi<2>{0, 2}) * ts_src_view(idx + pointi<2>{-1, 1});
re += kernel(pointi<2>{1, 2}) * ts_src_view(idx + pointi<2>{ 0, 1});
re += kernel(pointi<2>{2, 2}) * ts_src_view(idx + pointi<2>{ 1, 1});
ts_dst(idx) = re;
// clang-format on
});
benchmark::DoNotOptimize(ts_dst.data());
}
state.SetBytesProcessed(state.iterations() * static_cast<size_t>(ts_src_pad.size()) *
sizeof(ts_dst[0]));
state.SetItemsProcessed(state.iterations() * static_cast<size_t>(ts_dst.size()) *
kernel.size() * 2);
}
template <typename tensor_type>
inline void bm_tensor2f_padding_layout_general_unroll_conv(benchmark::State& state) {
const static int_t rank = tensor_type::rank;
typedef typename tensor_type::value_type value_type;
pointi<rank> shape;
fill(shape, state.range(0));
pointi<rank> kernel_shape;
fill(kernel_shape, 3);
tensor_type kernel(kernel_shape);
auto kernel_radius = kernel_shape / 2;
tensor_type ts_dst(shape);
_tmp::tensor<value_type, rank, padding_layout<rank>> ts_src(shape, kernel_radius,
kernel_radius);
while (state.KeepRunning()) {
_tmp::for_index(ts_dst.shape(), MLAMBDA(pointi<rank> idx) {
// clang-format off
auto re = zero<value_type>::value();
re += kernel(pointi<2>{0, 0}) * ts_src(idx + pointi<2>{-1, -1});
re += kernel(pointi<2>{1, 0}) * ts_src(idx + pointi<2>{ 0, -1});
re += kernel(pointi<2>{2, 0}) * ts_src(idx + pointi<2>{ 1, -1});
re += kernel(pointi<2>{0, 1}) * ts_src(idx + pointi<2>{-1, 0});
re += kernel(pointi<2>{1, 1}) * ts_src(idx + pointi<2>{ 0, 0});
re += kernel(pointi<2>{2, 1}) * ts_src(idx + pointi<2>{ 1, 0});
re += kernel(pointi<2>{0, 2}) * ts_src(idx + pointi<2>{-1, 1});
re += kernel(pointi<2>{1, 2}) * ts_src(idx + pointi<2>{ 0, 1});
re += kernel(pointi<2>{2, 2}) * ts_src(idx + pointi<2>{ 1, 1});
ts_dst(idx) = re;
// clang-format on
});
benchmark::DoNotOptimize(ts_dst.data());
}
state.SetBytesProcessed(state.iterations() * static_cast<size_t>(ts_src.size()) *
sizeof(ts_dst[0]));
state.SetItemsProcessed(state.iterations() * static_cast<size_t>(ts_dst.size()) *
kernel.size() * 2);
}
template <typename tensor_type>
inline void bm_tensor2_view_conv_local_tensor3x3(benchmark::State& state) {
const static int_t rank = tensor_type::rank;
typedef typename tensor_type::value_type value_type;
pointi<rank> shape;
fill(shape, state.range(0));
local_tensor<value_type, dim<3, 3>> kernel;
tensor_type ts_src_pad(shape + kernel.shape() - 1);
auto ts_src_view = view::slice(ts_src_pad, kernel.shape() / 2, shape);
tensor_type ts_dst(shape);
while (state.KeepRunning()) {
copy(view::conv(ts_src_view, kernel), ts_dst);
benchmark::DoNotOptimize(ts_dst.data());
}
state.SetBytesProcessed(state.iterations() * static_cast<size_t>(ts_src_pad.size()) *
sizeof(ts_src_view[0]));
state.SetItemsProcessed(state.iterations() * static_cast<size_t>(ts_dst.size()) *
kernel.size() * 2);
}
template <typename tensor_type>
inline void bm_tensor_view_conv_tensor3x3(benchmark::State& state) {
const static int_t rank = tensor_type::rank;
typedef typename tensor_type::value_type value_type;
pointi<rank> shape;
fill(shape, state.range(0));
pointi<rank> kernel_shape;
fill(kernel_shape, 3);
tensor_type kernel(kernel_shape);
tensor_type ts_src_pad(shape + kernel.shape() - 1);
auto ts_src_view = view::slice(ts_src_pad, kernel.shape() / 2, shape);
tensor_type ts_dst(shape);
while (state.KeepRunning()) {
copy(view::conv(ts_src_view, kernel), ts_dst);
benchmark::DoNotOptimize(ts_dst.data());
}
state.SetBytesProcessed(state.iterations() * static_cast<size_t>(ts_src_pad.size()) *
sizeof(ts_src_view[0]));
state.SetItemsProcessed(state.iterations() * static_cast<size_t>(ts_dst.size()) *
kernel.size() * 2);
}
template <typename tensor_type>
inline void bm_tensor2_view_conv_neighbors_weights3x3(benchmark::State& state) {
const static int_t rank = tensor_type::rank;
typedef typename tensor_type::value_type value_type;
pointi<rank> shape;
fill(shape, state.range(0));
tensor<tuple<pointi<rank>, value_type>, 1> neightbors_weights(9);
neightbors_weights[0] = make_tuple(pointi<rank>{-1, -1}, value_type{1});
neightbors_weights[0] = make_tuple(pointi<rank>{-1, -0}, value_type{1});
neightbors_weights[0] = make_tuple(pointi<rank>{-1, +1}, value_type{1});
neightbors_weights[0] = make_tuple(pointi<rank>{-0, -1}, value_type{1});
neightbors_weights[0] = make_tuple(pointi<rank>{-0, -0}, value_type{1});
neightbors_weights[0] = make_tuple(pointi<rank>{-0, +1}, value_type{1});
neightbors_weights[0] = make_tuple(pointi<rank>{+1, -1}, value_type{1});
neightbors_weights[0] = make_tuple(pointi<rank>{+1, -0}, value_type{1});
neightbors_weights[0] = make_tuple(pointi<rank>{+1, +1}, value_type{1});
pointi<2> padding = {1, 1};
tensor_type ts_src_pad(shape + 2 * padding);
auto ts_src_view = view::slice(ts_src_pad, padding, shape);
tensor_type ts_dst(shape);
while (state.KeepRunning()) {
copy(view::conv(ts_src_view, neightbors_weights), ts_dst);
benchmark::DoNotOptimize(ts_dst.data());
}
state.SetBytesProcessed(state.iterations() * static_cast<size_t>(ts_src_pad.size()) *
sizeof(ts_src_view[0]));
state.SetItemsProcessed(state.iterations() * static_cast<size_t>(ts_dst.size()) *
neightbors_weights.size() * 2);
}
template <typename tensor_type>
inline void bm_tensor2_view_conv_stride2_relu6_local_tensor3x3(benchmark::State& state) {
const static int_t rank = tensor_type::rank;
typedef typename tensor_type::value_type value_type;
pointi<rank> shape;
fill(shape, state.range(0));
local_tensor<value_type, dim<3, 3>> kernel;
tensor_type ts_src_pad(shape + kernel.shape() - 1);
auto ts_src_view = view::slice(ts_src_pad, kernel.shape() / 2, shape);
tensor_type ts_dst(shape / 2);
while (state.KeepRunning()) {
auto ts_conv_view = view::conv(ts_src_view, kernel);
auto ts_conv_stride_view = view::stride(ts_conv_view, pointi<2>{2, 2});
auto ts_conv_stride_relu6_view =
view::map(ts_conv_stride_view, [] MATAZURE_GENERAL(value_type v) { return v; });
copy(ts_conv_stride_view, ts_dst);
benchmark::DoNotOptimize(ts_dst.data());
}
state.SetBytesProcessed(state.iterations() * static_cast<size_t>(ts_src_pad.size()) *
sizeof(ts_src_view[0]));
state.SetItemsProcessed(state.iterations() * static_cast<size_t>(ts_dst.size()) *
kernel.size() * 2);
}
| 41.004098 | 96 | 0.625487 | matazure |
4a822b402279cba9624e983f628f28602c057281 | 776 | hpp | C++ | include/RED4ext/Types/generated/game/ui/AccessPointMiniGameStatus.hpp | Cyberpunk-Extended-Development-Team/RED4ext.SDK | 2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae | [
"MIT"
] | 1 | 2021-02-01T23:07:50.000Z | 2021-02-01T23:07:50.000Z | include/RED4ext/Types/generated/game/ui/AccessPointMiniGameStatus.hpp | Cyberpunk-Extended-Development-Team/RED4ext.SDK | 2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae | [
"MIT"
] | null | null | null | include/RED4ext/Types/generated/game/ui/AccessPointMiniGameStatus.hpp | Cyberpunk-Extended-Development-Team/RED4ext.SDK | 2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae | [
"MIT"
] | null | null | null | #pragma once
// This file is generated from the Game's Reflection data
#include <cstdint>
#include <RED4ext/Common.hpp>
#include <RED4ext/REDhash.hpp>
#include <RED4ext/Types/generated/game/ui/HackingMinigameState.hpp>
#include <RED4ext/Types/generated/red/Event.hpp>
namespace RED4ext
{
namespace game::ui {
struct AccessPointMiniGameStatus : red::Event
{
static constexpr const char* NAME = "gameuiAccessPointMiniGameStatus";
static constexpr const char* ALIAS = "AccessPointMiniGameStatus";
game::ui::HackingMinigameState minigameState; // 40
uint8_t unk44[0x48 - 0x44]; // 44
};
RED4EXT_ASSERT_SIZE(AccessPointMiniGameStatus, 0x48);
} // namespace game::ui
using AccessPointMiniGameStatus = game::ui::AccessPointMiniGameStatus;
} // namespace RED4ext
| 29.846154 | 74 | 0.770619 | Cyberpunk-Extended-Development-Team |
4a8246c58975a1961c4e550db4be876bfd9ea2b7 | 1,009 | cpp | C++ | tests/regression/ConnectedButIndepIters/test.cpp | SusanTan/noelle | 33c9e10a20bc59590c13bf29fb661fc406a9e687 | [
"MIT"
] | 43 | 2020-09-04T15:21:40.000Z | 2022-03-23T03:53:02.000Z | tests/regression/ConnectedButIndepIters/test.cpp | SusanTan/noelle | 33c9e10a20bc59590c13bf29fb661fc406a9e687 | [
"MIT"
] | 15 | 2020-09-17T18:06:15.000Z | 2022-01-24T17:14:36.000Z | tests/regression/ConnectedButIndepIters/test.cpp | SusanTan/noelle | 33c9e10a20bc59590c13bf29fb661fc406a9e687 | [
"MIT"
] | 23 | 2020-09-04T15:50:09.000Z | 2022-03-25T13:38:25.000Z | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
long long int computePowerSeries (long long int *a, long long int iters){
long long int s =0;
long long int t =0;
long long int u =0;
long long int v =0;
for (auto i=0; i < iters; ++i){
s += a[i];
for (long long int j=0; j < iters / 10; ++j){
t += a[j];
}
u -= t;
for (long long int j=0; j < iters / 10; ++j){
u += a[j];
}
v -= u;
for (long long int j=0; j < iters / 10; ++j){
v += a[j];
}
}
long long int x = s + t + u + v;
return x;
}
int main (int argc, char *argv[]){
/*
* Check the inputs.
*/
if (argc < 2){
fprintf(stderr, "USAGE: %s LOOP_ITERATIONS\n", argv[0]);
return -1;
}
auto iterations = atoll(argv[1]);
long long int *array = (long long int *) malloc(sizeof(long long int) * iterations);
for (auto i=0; i < iterations; i++){
array[i] = i;
}
auto s = computePowerSeries(array, iterations);
printf("%lld\n", s);
return 0;
}
| 19.784314 | 86 | 0.531219 | SusanTan |
4a88056dc75fcc250ddeaff290464f9d7946f921 | 2,606 | cpp | C++ | apps/unit_tests/test_fft_correctness_2.cpp | lzhang714/SIRIUS-develop | c07eefe995c417fb4247e8ddaf138784189523be | [
"BSD-2-Clause"
] | 1 | 2021-01-22T20:02:42.000Z | 2021-01-22T20:02:42.000Z | apps/unit_tests/test_fft_correctness_2.cpp | lzhang714/SIRIUS-develop | c07eefe995c417fb4247e8ddaf138784189523be | [
"BSD-2-Clause"
] | null | null | null | apps/unit_tests/test_fft_correctness_2.cpp | lzhang714/SIRIUS-develop | c07eefe995c417fb4247e8ddaf138784189523be | [
"BSD-2-Clause"
] | null | null | null | #include <sirius.h>
/* test FFT: tranfrom random function to real space, transfrom back and compare with the original function */
using namespace sirius;
int test_fft_complex(cmd_args& args, device_t fft_pu__)
{
double cutoff = args.value<double>("cutoff", 40);
matrix3d<double> M = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}};
auto fft_grid = get_min_fft_grid(cutoff, M);
auto spl_z = split_fft_z(fft_grid[2], Communicator::world());
Gvec gvec(M, cutoff, Communicator::world(), false);
Gvec_partition gvp(gvec, Communicator::world(), Communicator::self());
spfft::Grid spfft_grid(fft_grid[0], fft_grid[1], fft_grid[2], gvp.zcol_count_fft(), spl_z.local_size(),
SPFFT_PU_HOST, -1, Communicator::world().mpi_comm(), SPFFT_EXCH_DEFAULT);
const auto fft_type = gvec.reduced() ? SPFFT_TRANS_R2C : SPFFT_TRANS_C2C;
auto gv = gvp.get_gvec();
spfft::Transform spfft(spfft_grid.create_transform(SPFFT_PU_HOST, fft_type, fft_grid[0], fft_grid[1], fft_grid[2],
spl_z.local_size(), gvp.gvec_count_fft(), SPFFT_INDEX_TRIPLETS,
gv.at(memory_t::host)));
mdarray<double_complex, 1> f(gvp.gvec_count_fft());
for (int ig = 0; ig < gvp.gvec_count_fft(); ig++) {
f[ig] = utils::random<double_complex>();
}
mdarray<double_complex, 1> g(gvp.gvec_count_fft());
spfft.backward(reinterpret_cast<double const*>(&f[0]), spfft.processing_unit());
spfft.forward(spfft.processing_unit(), reinterpret_cast<double*>(&g[0]), SPFFT_FULL_SCALING);
double diff{0};
for (int ig = 0; ig < gvp.gvec_count_fft(); ig++) {
diff += std::pow(std::abs(f[ig] - g[ig]), 2);
}
Communicator::world().allreduce(&diff, 1);
diff = std::sqrt(diff / gvec.num_gvec());
if (diff > 1e-10) {
return 1;
} else {
return 0;
}
}
int run_test(cmd_args& args)
{
int result = test_fft_complex(args, device_t::CPU);
#ifdef __GPU
result += test_fft_complex(args, device_t::GPU);
#endif
return result;
}
int main(int argn, char **argv)
{
cmd_args args;
args.register_key("--cutoff=", "{double} cutoff radius in G-space");
args.parse_args(argn, argv);
if (args.exist("help")) {
printf("Usage: %s [options]\n", argv[0]);
args.print_help();
return 0;
}
sirius::initialize(true);
printf("running %-30s : ", argv[0]);
int result = run_test(args);
if (result) {
printf("\x1b[31m" "Failed" "\x1b[0m" "\n");
} else {
printf("\x1b[32m" "OK" "\x1b[0m" "\n");
}
sirius::finalize();
return result;
}
| 29.954023 | 118 | 0.625096 | lzhang714 |
4a8d78519d0a45746d6dc0bec068d0db8febe0db | 2,665 | cpp | C++ | course_project/ruledsurfacebycardinalspline.cpp | Dukend/Computer-graphics | b8a575f3e56e49399d2be1c62ebb96e85236971f | [
"MIT"
] | null | null | null | course_project/ruledsurfacebycardinalspline.cpp | Dukend/Computer-graphics | b8a575f3e56e49399d2be1c62ebb96e85236971f | [
"MIT"
] | null | null | null | course_project/ruledsurfacebycardinalspline.cpp | Dukend/Computer-graphics | b8a575f3e56e49399d2be1c62ebb96e85236971f | [
"MIT"
] | null | null | null | #include "ruledsurfacebycardinalspline.h"
RuledSurfaceByCardinalSpline::RuledSurfaceByCardinalSpline()
{
QObject::connect(&fLine, SIGNAL(splineChanged()), this, SLOT(acceptChanges()));
QObject::connect(&sLine, SIGNAL(splineChanged()), this, SLOT(acceptChanges()));
setFrameColor(Qt::black);
setMaterialColor(Qt::blue);
}
void RuledSurfaceByCardinalSpline::setPrecision(float p){
if(precision != p){
precision = p;
emit surfaceChanged();
}
}
float RuledSurfaceByCardinalSpline::getPrecision(){
return precision;
}
void RuledSurfaceByCardinalSpline::paint(){
if(fLine.isValid() && sLine.isValid()){
fLine.calculate();
sLine.calculate();
if(fLine.getSegments().size() > sLine.getSegments().size()){
paintLine(fLine, bufferFLinePoints, precision);
paintLine(sLine, bufferSLinePoints, precision * (float)fLine.getSegments().size()/(float)sLine.getSegments().size());
} else{
paintLine(fLine, bufferFLinePoints, precision * (float)sLine.getSegments().size()/(float)fLine.getSegments().size());
paintLine(sLine, bufferSLinePoints, precision);
}
while(bufferFLinePoints.size() < bufferSLinePoints.size())
bufferFLinePoints.push_back(fLine.getSegments().back().calculatePoint(1));
while(bufferFLinePoints.size() > bufferSLinePoints.size())
bufferSLinePoints.push_back(sLine.getSegments().back().calculatePoint(1));
for(int i = 0;i<bufferFLinePoints.size()-1;++i){
/*
addPolygon(bufferFLinePoints[i], bufferFLinePoints[i+1], bufferSLinePoints[i]);
addPolygon(bufferFLinePoints[i+1], bufferSLinePoints[i+1], bufferSLinePoints[i]);
*/
addPolygon(bufferFLinePoints[i], bufferSLinePoints[i],bufferFLinePoints[i+1]);
addPolygon(bufferFLinePoints[i+1],bufferSLinePoints[i], bufferSLinePoints[i+1]);
}
}
}
void RuledSurfaceByCardinalSpline::acceptChanges(){
emit surfaceChanged();
}
void RuledSurfaceByCardinalSpline::paintLine(CardinalSplineClass& line, QVector<QVector3D>& buffer, float pres){
buffer.clear();
auto& segments = line.getSegments();
float step = 1/pres;
QVector3D p;
for(int i = 0;i<segments.size(); ++i){
for(float s = 0; s < 1; s+= step){
p = segments[i].calculatePoint(s);
buffer.push_back(p);
}
}
p = segments.back().calculatePoint(1);
buffer.push_back(p);
}
void RuledSurfaceByCardinalSpline::recievePrecision(int p){
setPrecision(p);
}
| 38.071429 | 130 | 0.644653 | Dukend |
4a8f7d80227ed94b1e7fb6fff07021344469f7b3 | 432 | hpp | C++ | addons/external_intercom/ACEActions.hpp | severgun/task-force-arma-3-radio | 1379327a6ff71948dae692ca7a43876c9031e90e | [
"RSA-MD"
] | null | null | null | addons/external_intercom/ACEActions.hpp | severgun/task-force-arma-3-radio | 1379327a6ff71948dae692ca7a43876c9031e90e | [
"RSA-MD"
] | null | null | null | addons/external_intercom/ACEActions.hpp | severgun/task-force-arma-3-radio | 1379327a6ff71948dae692ca7a43876c9031e90e | [
"RSA-MD"
] | null | null | null | #define ADD_PLAYER_SELF_ACTIONS \
class ACE_SelfActions { \
class TFAR_Radio { \
condition = QUOTE((([] call TFAR_fnc_haveSWRadio) || {([] call TFAR_fnc_haveLRRadio) || !isNil {_player getVariable 'TFAR_ExternalIntercomVehicle'}})); \
insertChildren = QUOTE(([_player] call tfar_core_fnc_getOwnRadiosChildren) + (call TFAR_external_intercom_fnc_addWirelessIntercomMenu)); \
statement = " "; \
}; \
}
| 48 | 161 | 0.703704 | severgun |
4a918c4b2908814fd4957711da9745ba73fe4e0a | 6,196 | cc | C++ | Graphs/OpenGL/GL_FBO.cc | TrevorShelton/cplot | 8bf40e94519cc4fd69b2e0677d3a3dcf8695245a | [
"MIT"
] | 32 | 2017-11-27T03:04:44.000Z | 2022-01-21T17:03:40.000Z | Graphs/OpenGL/GL_FBO.cc | TrevorShelton/cplot | 8bf40e94519cc4fd69b2e0677d3a3dcf8695245a | [
"MIT"
] | 30 | 2017-11-10T09:47:16.000Z | 2018-11-21T22:36:47.000Z | Graphs/OpenGL/GL_FBO.cc | TrevorShelton/cplot | 8bf40e94519cc4fd69b2e0677d3a3dcf8695245a | [
"MIT"
] | 20 | 2018-01-05T17:15:11.000Z | 2021-07-30T14:11:01.000Z | #include "GL_FBO.h"
#include <cassert>
#ifdef TXDEBUG
#define DEBUG_TEXTURES(x) std::cerr << x << std::endl
#else
#define DEBUG_TEXTURES(x)
#endif
bool GL_FBO::init(GL_Context context, unsigned w_, unsigned h_, int bpp, bool depth_buffer)
{
assert(context);
GL_CHECK;
bool ok = (w_ > 0 && h_ > 0);
if (ok && !fbo)
{
glGenFramebuffers(1, &fbo);
if (!fbo) ok = false;
DEBUG_TEXTURES("Allocating FBO: " << fbo);
}
if (w > 0 && h > 0)
{
if (depth && (!ok || !depth_buffer || w != w_ || h != h_))
{
DEBUG_TEXTURES("Releasing FBO depth (" << w << " x " << h << ")");
context.delete_texture(depth);
depth = 0;
}
if (texture && (!ok || w != w_ || h != h_))
{
DEBUG_TEXTURES("Releasing FBO texture (" << w << " x " << h << ")");
context.delete_texture(texture);
texture = 0;
w = h = 0;
}
}
assert(texture || !depth); // if texture was released, depth buffer was too
if (ok && !texture)
{
glGenTextures(1, &texture);
if (!texture) ok = false;
DEBUG_TEXTURES("Allocating FBO texture id: " << texture);
}
if (ok && depth_buffer && !depth)
{
glGenTextures(1, &depth);
if (!depth) ok = false;
DEBUG_TEXTURES("Allocating FBO depth id: " << depth);
}
GL_CHECK;
if (ok && (w != w_ || h != h_))
{
assert(w == 0 && h == 0);
w = w_;
h = h_;
DEBUG_TEXTURES("Allocating FBO texture data (" << w << " x " << h << ")");
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glBindTexture(GL_TEXTURE_2D, texture);
switch (bpp)
{
case 8: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, w, h, 0, GL_BGRA, GL_UNSIGNED_BYTE, NULL); break;
case 16: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F_ARB, w, h, 0, GL_BGRA, GL_HALF_FLOAT_ARB, NULL); break;
//case 16: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16, w, h, 0, GL_BGRA, GL_UNSIGNED_SHORT, NULL); break;
case 32: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F_ARB, w, h, 0, GL_BGRA, GL_FLOAT, NULL); break;
default: assert(false); ok = false; break;
}
if (ok)
{
glBindTexture (GL_TEXTURE_2D, texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, 0);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (status != GL_FRAMEBUFFER_COMPLETE)
{
ok = false;
DEBUG_TEXTURES("Failed with code " << status);
}
}
if (ok && depth_buffer)
{
DEBUG_TEXTURES("Allocating FBO depth data (" << w << " x " << h << ")");
GL_CHECK;
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glBindTexture(GL_TEXTURE_2D, depth);
glTexImage2D (GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT32, w, h, 0, GL_DEPTH_COMPONENT, GL_FLOAT, 0);
GL_CHECK;
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
GL_CHECK;
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depth, 0);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
GL_CHECK;
GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (status != GL_FRAMEBUFFER_COMPLETE)
{
ok = false;
DEBUG_TEXTURES("Failed with code " << status);
}
}
}
GL_CHECK;
if (!ok)
{
if (fbo)
{
DEBUG_TEXTURES("Releasing FBO: " << fbo);
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glDeleteFramebuffers(1, &fbo);
fbo = 0;
}
if (depth)
{
DEBUG_TEXTURES("Releasing FBO depth data (" << w << " x " << h << ")");
context.delete_texture(depth);
depth = 0;
}
if (texture)
{
DEBUG_TEXTURES("Releasing FBO texture data (" << w << " x " << h << ")");
context.delete_texture(texture);
texture = 0;
w = h = 0;
}
}
GL_CHECK;
return ok || (w_ == 0 || h_ == 0);
}
void GL_FBO::bind() const
{
assert(fbo);
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
glDrawBuffer(GL_COLOR_ATTACHMENT0);
}
void GL_FBO::draw(bool blend, float factor) const
{
assert(fbo && texture);
if (!fbo || !texture){ assert(false); return; }
glMatrixMode(GL_TEXTURE); glLoadIdentity();
glMatrixMode(GL_MODELVIEW); glLoadIdentity();
glMatrixMode(GL_PROJECTION); glLoadIdentity();
glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0);
glDisable(GL_DEPTH_TEST);
if (blend)
{
glEnable(GL_BLEND);
if (factor < 1.0f-1e-8)
{
glBlendColor(0.0f, 0.0f, 0.0f, factor);
glBlendFunc(GL_CONSTANT_ALPHA, GL_ONE);
}
else
{
glBlendFunc(GL_ONE, GL_ONE);
}
}
else if (factor < 1.0f-1e-8)
{
glEnable(GL_BLEND);
glBlendColor(0.0f, 0.0f, 0.0f, factor);
glBlendFunc(GL_CONSTANT_ALPHA, GL_ZERO);
glBlendFunc(GL_ZERO, GL_CONSTANT_ALPHA);
}
else
{
glDisable(GL_BLEND);
}
glDisable(GL_LIGHTING);
glActiveTexture(GL_TEXTURE0);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texture);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 0.0f); glVertex3f(0.0f, 0.0f, 0.0f);
glTexCoord2f(1.0f, 0.0f); glVertex3f(1.0f, 0.0f, 0.0f);
glTexCoord2f(1.0f, 1.0f); glVertex3f(1.0f, 1.0f, 0.0f);
glTexCoord2f(0.0f, 1.0f); glVertex3f(0.0f, 1.0f, 0.0f);
glEnd();
glDisable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, 0);
}
void GL_FBO::acc_load(const GL_FBO &other, float factor)
{
if (factor < 1.0f-1e-8)
{
bind();
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT);
acc_add(other, factor);
}
else
{
bind();
glBindTexture(GL_TEXTURE_2D, texture);
other.bind();
glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, w, h);
glBindTexture(GL_TEXTURE_2D, 0);
}
}
void GL_FBO::acc_add(const GL_FBO &other, float factor)
{
bind();
other.draw(true, factor);
other.bind();
}
| 25.924686 | 109 | 0.668173 | TrevorShelton |
4a93a40e263c5ac6e1428f34e9552bb928963986 | 1,083 | cpp | C++ | BOJ_solve/16602.cpp | python-programmer1512/Code_of_gunwookim | e72e6724fb9ee6ccf2e1064583956fa954ba0282 | [
"MIT"
] | 4 | 2021-01-27T11:51:30.000Z | 2021-01-30T17:02:55.000Z | BOJ_solve/16602.cpp | python-programmer1512/Code_of_gunwookim | e72e6724fb9ee6ccf2e1064583956fa954ba0282 | [
"MIT"
] | null | null | null | BOJ_solve/16602.cpp | python-programmer1512/Code_of_gunwookim | e72e6724fb9ee6ccf2e1064583956fa954ba0282 | [
"MIT"
] | 5 | 2021-01-27T11:46:12.000Z | 2021-05-06T05:37:47.000Z | #include <bits/stdc++.h>
#define x first
#define y second
#define pb push_back
#define all(v) v.begin(),v.end()
#pragma gcc optimize("O3")
#pragma gcc optimize("Ofast")
#pragma gcc optimize("unroll-loops")
using namespace std;
const int INF = 1e9;
const int TMX = 1 << 18;
const long long llINF = 5e18;
const long long mod = 1e9+7;
const long long hmod1 = 1e9+409;
const long long hmod2 = 1e9+433;
const long long base = 257;
typedef long long ll;
typedef long double ld;
typedef pair <int,int> pi;
typedef pair <ll,ll> pl;
typedef vector <int> vec;
typedef vector <pi> vecpi;
typedef long long ll;
int n,ti,ans,t[400005],ind[400005];
vec v[400005];
int main() {
ios_base::sync_with_stdio(false), cin.tie(0);
cin >> n;
for(int i = 1;i <= n;i++) {
int x,y; cin >> t[i] >> x;
for(;x--;) cin >> y, v[i].pb(y), ind[y]++;
}
priority_queue <pi> q;
for(int i = 1;i <= n;i++) {
if(!ind[i]) q.push({-t[i],i});
}
while(!q.empty()) {
pi x = q.top(); q.pop();
ans = max(ans,n-ti-1-x.x), ti++;
for(int i : v[x.y]) {
if(!--ind[i]) q.push({-t[i],i});
}
}
cout << ans;
} | 23.543478 | 46 | 0.611265 | python-programmer1512 |
4a94280f6546dd03a58e1186bf9d6c5b4990ddc5 | 782 | cpp | C++ | PAT_LevelA/1036_Boys_vs_Girls.cpp | MarkIlV/PAT_Answers | 89eacf085069dc03b684d431f51715c491dbb984 | [
"MIT"
] | null | null | null | PAT_LevelA/1036_Boys_vs_Girls.cpp | MarkIlV/PAT_Answers | 89eacf085069dc03b684d431f51715c491dbb984 | [
"MIT"
] | null | null | null | PAT_LevelA/1036_Boys_vs_Girls.cpp | MarkIlV/PAT_Answers | 89eacf085069dc03b684d431f51715c491dbb984 | [
"MIT"
] | null | null | null | #include "cstdio"
struct Stu{
char name[11];
char sex;
char id[11];
int grade;
}male,female,tmp;
int main() {
int n;
male.grade = 101;
female.grade = -1;
if (scanf("%d",&n)==1);
for (int i = 0; i < n; ++i) {
if (scanf("%s %c %s %d",tmp.name,&tmp.sex,tmp.id,&tmp.grade)==1);
if (tmp.sex=='M' && (tmp.grade < male.grade)) male = tmp;
if (tmp.sex=='F' && (tmp.grade > female.grade)) female = tmp;
}
if (female.grade == -1) printf("Absent\n");
else printf("%s %s\n",female.name,female.id);
if (male.grade == 101) printf("Absent\n");
else printf("%s %s\n",male.name,male.id);
if(female.grade == -1 || male.grade == 101) printf("NA");
else printf("%d",female.grade-male.grade);
return 0;
} | 24.4375 | 73 | 0.531969 | MarkIlV |
4a946ecb9d43117814d1c8b8c18b6fc8b861d0aa | 875 | cpp | C++ | CPP/ex_2.7.9_multidem.cpp | w1ld/StepikExercies | 3efe07819a0456aa3846587b2a23bad9dd9710db | [
"MIT"
] | 4 | 2019-05-11T17:26:24.000Z | 2022-01-30T17:48:25.000Z | CPP/ex_2.7.9_multidem.cpp | w1ld/StepikExercises | 3efe07819a0456aa3846587b2a23bad9dd9710db | [
"MIT"
] | null | null | null | CPP/ex_2.7.9_multidem.cpp | w1ld/StepikExercises | 3efe07819a0456aa3846587b2a23bad9dd9710db | [
"MIT"
] | 4 | 2019-01-24T22:15:21.000Z | 2020-12-21T10:23:52.000Z | #include <iostream>
using namespace std;
int ** transpose(const int * const * m, unsigned rows, unsigned cols)
{
int ** mt = new int * [cols];
mt[0] = new int[cols * rows];
for(unsigned i = 1; i != cols; i++) {
mt[i] = mt[i - 1] + rows;
}
for(unsigned i = 0; i < rows; i++) {
for(unsigned j = 0; j < cols; j++) {
mt[j][i] = m[i][j];
}
}
return mt;
}
int main() {
const unsigned rows = 3;
const unsigned cols = 2;
int ** m = new int * [rows];
m[0] = new int[cols * rows];
for(unsigned i = 1; i != rows; i++) {
m[i] = m[i - 1] + cols;
}
m[0][0] = 1;
m[0][1] = 2;
m[1][0] = 3;
m[1][1] = 4;
m[2][0] = 5;
m[2][1] = 6;
int ** mt = transpose((int**)m, rows, cols);
for(unsigned i = 0; i < cols; i++) {
for(unsigned j = 0; j < rows; j++) {
cout << mt[i][j] << ' ';
}
cout << endl;
}
}
| 19.886364 | 70 | 0.459429 | w1ld |
4a9e53065f732e1ee8912b7cb0a5ed331289cc55 | 129 | cpp | C++ | tensorflow-yolo-ios/dependencies/eigen/unsupported/test/BVH.cpp | initialz/tensorflow-yolo-face-ios | ba74cf39168d0128e91318e65a1b88ce4d65a167 | [
"MIT"
] | 27 | 2017-06-07T19:07:32.000Z | 2020-10-15T10:09:12.000Z | tensorflow-yolo-ios/dependencies/eigen/unsupported/test/BVH.cpp | initialz/tensorflow-yolo-face-ios | ba74cf39168d0128e91318e65a1b88ce4d65a167 | [
"MIT"
] | 3 | 2017-08-25T17:39:46.000Z | 2017-11-18T03:40:55.000Z | tensorflow-yolo-ios/dependencies/eigen/unsupported/test/BVH.cpp | initialz/tensorflow-yolo-face-ios | ba74cf39168d0128e91318e65a1b88ce4d65a167 | [
"MIT"
] | 10 | 2017-06-16T18:04:45.000Z | 2018-07-05T17:33:01.000Z | version https://git-lfs.github.com/spec/v1
oid sha256:ccc4d628c6edaf86b7ac04d255d639790b9c39147a94e8d7950eba698898b910
size 7182
| 32.25 | 75 | 0.883721 | initialz |
4aa05e4d234e239b2a9a32382fee6d7dd4e33fcf | 1,047 | cpp | C++ | Back Tracking/gen-ip.cpp | richidubey/AwesomeDataStructuresAndAlgorithms | 356a43272c5898a4aa7b87bab8a02aa08cb81cd4 | [
"MIT"
] | 3 | 2018-11-15T07:59:13.000Z | 2021-07-20T02:06:28.000Z | Back Tracking/gen-ip.cpp | richidubey/AwesomeDataStructuresAndAlgorithms | 356a43272c5898a4aa7b87bab8a02aa08cb81cd4 | [
"MIT"
] | null | null | null | Back Tracking/gen-ip.cpp | richidubey/AwesomeDataStructuresAndAlgorithms | 356a43272c5898a4aa7b87bab8a02aa08cb81cd4 | [
"MIT"
] | 3 | 2018-11-15T06:39:53.000Z | 2021-07-20T02:09:18.000Z | set <string> sans;
void genip(string s,int dots,int mark,string ans)
{
if(mark==s.size()&&dots==3)
{
int c=0,m=0;
if(ans[ans.size()-1]=='.')
return;
for(int j=ans.size()-1;j>=0;j--)
{
if(ans[j]=='.')
{
// cout<<c<<endl;
c=0;
m=0;
}
else
{
c+=pow(10,m)*(ans[j]-'0');
m++;
}
if(ans[j]=='0'&&j!=0&&ans[j-1]=='.'&&j!=ans.size()-1&&ans[j+1]!='.')
return;
if(c>255)
return;
}
sans.insert(ans);
//cout<<ans<<endl;
return;
}
for(int i=mark;i<s.size();i++)
{
ans.push_back(s[i]);
genip(s,dots,i+1,ans);
if(dots<3)
{
ans.push_back('.');
genip(s,dots+1,i+1,ans);
ans.pop_back();
}
}
}
vector<string> genIp(string s)
{
sans.clear();
string ans="";
vector<string>ret;
if(s.size()<4||s.size()>12)
return ret;
genip(s,0,0,ans);
//Your code here
for(set<string>::iterator it=sans.begin();it!=sans.end();it++)
ret.push_back(*it);
return ret;
}
| 12.925926 | 71 | 0.464183 | richidubey |
4aa8f23ecf8e261d28d9cef01e41991beb451f26 | 565 | cpp | C++ | source/bounded/detail/arithmetic/left_shift.cpp | davidstone/bounded-integer | d4f9a88a12174ca8382af60b00c5affd19aa8632 | [
"BSL-1.0"
] | 44 | 2020-10-03T21:37:52.000Z | 2022-03-26T10:08:46.000Z | source/bounded/detail/arithmetic/left_shift.cpp | davidstone/bounded-integer | d4f9a88a12174ca8382af60b00c5affd19aa8632 | [
"BSL-1.0"
] | 1 | 2021-01-01T23:22:39.000Z | 2021-01-01T23:22:39.000Z | source/bounded/detail/arithmetic/left_shift.cpp | davidstone/bounded-integer | d4f9a88a12174ca8382af60b00c5affd19aa8632 | [
"BSL-1.0"
] | null | null | null | // Copyright David Stone 2017.
// 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)
#include <bounded/detail/arithmetic/left_shift.hpp>
#include <bounded/detail/class.hpp>
#include "../../homogeneous_equals.hpp"
namespace {
static_assert(homogeneous_equals(
bounded::integer<0, 2>(bounded::constant<1>) << bounded::integer<0, 60>(bounded::constant<3>),
bounded::integer<0, bounded::normalize<(2LL << 60LL)>>(bounded::constant<(1 << 3)>)
));
} // namespace
| 31.388889 | 95 | 0.723894 | davidstone |
4aa9ac69b8425c90eab363e74e1ef03e0533a6c8 | 255 | cpp | C++ | example/main.cpp | pqrs-org/cpp-osx-kext_return | a640bd791ea316baa2b6114fa7976460f7c80e21 | [
"BSL-1.0"
] | 1 | 2019-08-16T03:30:09.000Z | 2019-08-16T03:30:09.000Z | example/main.cpp | pqrs-org/cpp-osx-kext_return | a640bd791ea316baa2b6114fa7976460f7c80e21 | [
"BSL-1.0"
] | null | null | null | example/main.cpp | pqrs-org/cpp-osx-kext_return | a640bd791ea316baa2b6114fa7976460f7c80e21 | [
"BSL-1.0"
] | null | null | null | #include <pqrs/osx/os_kext_return.hpp>
int main(void) {
{
pqrs::osx::os_kext_return r(kOSKextReturnSystemPolicy);
std::cout << r << std::endl;
}
{
pqrs::osx::os_kext_return r(54321);
std::cout << r << std::endl;
}
return 0;
}
| 15.9375 | 59 | 0.6 | pqrs-org |
4ab9ca28ba453ee2f6a5e6f4a41dc49c5233eb49 | 6,805 | cc | C++ | ChiModules/LinearBoltzmannSolver/lbs_compute_balance.cc | zachhardy/chi-tech | 18fb6cb691962a90820e2ef4fcb05473f4a6bdd6 | [
"MIT"
] | 7 | 2019-09-10T12:16:08.000Z | 2021-05-06T16:01:59.000Z | ChiModules/LinearBoltzmannSolver/lbs_compute_balance.cc | zachhardy/chi-tech | 18fb6cb691962a90820e2ef4fcb05473f4a6bdd6 | [
"MIT"
] | 72 | 2019-09-04T15:00:25.000Z | 2021-12-02T20:47:29.000Z | ChiModules/LinearBoltzmannSolver/lbs_compute_balance.cc | Naktakala/chi-tech | df5f517d5aff1d167db50ccbcf4229ac0cb668c4 | [
"MIT"
] | 41 | 2019-09-02T15:33:31.000Z | 2022-02-10T13:26:49.000Z | #include "lbs_linear_boltzmann_solver.h"
#include "ChiMath/SpatialDiscretization/FiniteElement/PiecewiseLinear/pwl.h"
#include "chi_log.h"
extern ChiLog& chi_log;
#include <iomanip>
//###################################################################
/**Zeroes all the outflow data-structures required to compute
* balance.*/
void LinearBoltzmann::Solver::ZeroOutflowBalanceVars(LBSGroupset& groupset)
{
for (auto& cell_transport_view : cell_transport_views)
for (auto& group : groupset.groups)
cell_transport_view.ZeroOutflow(group.id);
}
//###################################################################
/**Compute balance.*/
void LinearBoltzmann::Solver::ComputeBalance()
{
MPI_Barrier(MPI_COMM_WORLD);
chi_log.Log() << "\n********** Computing balance\n";
auto pwld =
std::dynamic_pointer_cast<SpatialDiscretization_PWLD>(discretization);
if (not pwld) throw std::logic_error("Trouble getting PWLD-SDM in " +
std::string(__FUNCTION__));
SpatialDiscretization_PWLD& grid_fe_view = *pwld;
//======================================== Get material source
// This is done using the SetSource routine
// because it allows a lot of flexibility.
auto mat_src = phi_old_local;
mat_src.assign(mat_src.size(),0.0);
for (auto& groupset : groupsets)
{
q_moments_local.assign(q_moments_local.size(), 0.0);
SetSource(groupset, q_moments_local,
APPLY_MATERIAL_SOURCE | APPLY_AGS_FISSION_SOURCE |
APPLY_WGS_FISSION_SOURCE);
ScopedCopySTLvectors(groupset, q_moments_local, mat_src);
}
//======================================== Initialize diffusion params
// for xs
// This populates sigma_a
for (auto& xs : material_xs)
if (not xs->diffusion_initialized)
xs->ComputeDiffusionParameters();
//======================================== Compute absorption, material-source
// and in-flow
size_t num_groups=groups.size();
double local_out_flow = 0.0;
double local_in_flow = 0.0;
double local_absorption = 0.0;
double local_production = 0.0;
for (const auto& cell : grid->local_cells)
{
const auto& transport_view = cell_transport_views[cell.local_id];
const auto& fe_intgrl_values = grid_fe_view.GetUnitIntegrals(cell);
const size_t num_nodes = transport_view.NumNodes();
const auto& IntV_shapeI = fe_intgrl_values.GetIntV_shapeI();
const auto& IntS_shapeI = fe_intgrl_values.GetIntS_shapeI();
//====================================== Inflow
// This is essentially an integration over
// all faces, all angles, and all groups.
// Only the cosines that are negative are
// added to the integral.
for (int f=0; f<cell.faces.size(); ++f)
{
const auto& face = cell.faces[f];
for (const auto& groupset : groupsets)
{
for (int n = 0; n < groupset.quadrature->omegas.size(); ++n)
{
const auto &omega = groupset.quadrature->omegas[n];
const double wt = groupset.quadrature->weights[n];
const double mu = omega.Dot(face.normal);
if (mu < 0.0 and (not face.has_neighbor)) //mu<0 and bndry
{
const auto &bndry = sweep_boundaries[face.neighbor_id];
for (int fi = 0; fi < face.vertex_ids.size(); ++fi)
{
const int i = fe_intgrl_values.FaceDofMapping(f, fi);
const auto &IntFi_shapeI = IntS_shapeI[f][i];
for (const auto &group : groupset.groups)
{
const int g = group.id;
const double psi = bndry->boundary_flux[g];
local_in_flow -= mu * wt * psi * IntFi_shapeI;
}//for g
}//for fi
}//if bndry
}//for n
}//for groupset
}//for f
//====================================== Outflow
//The group-wise outflow was determined
//during a solve so here we just
//consolidate it.
for (int g=0; g<num_groups; ++g)
local_out_flow += transport_view.GetOutflow(g);
//====================================== Absorption and Src
//Isotropic flux based absorption and source
auto& xs = *material_xs[transport_view.XSMapping()];
for (int i=0; i<num_nodes; ++i)
for (int g=0; g<num_groups; ++g)
{
size_t imap = transport_view.MapDOF(i,0,g);
double phi_0g = phi_old_local[imap];
double q_0g = mat_src[imap];
local_absorption += xs.sigma_a[g] * phi_0g * IntV_shapeI[i];
local_production += q_0g * IntV_shapeI[i];
}//for g
}//for cell
//======================================== Consolidate local balances
double local_balance = local_production + local_in_flow
- local_absorption - local_out_flow;
double local_gain = local_production + local_in_flow;
std::vector<double> local_balance_table = {local_absorption,
local_production,
local_in_flow,
local_out_flow,
local_balance,
local_gain};
size_t table_size = local_balance_table.size();
std::vector<double> globl_balance_table(table_size,0.0);
MPI_Allreduce(local_balance_table.data(), //sendbuf
globl_balance_table.data(), //recvbuf
table_size,MPI_DOUBLE, //count + datatype
MPI_SUM, //operation
MPI_COMM_WORLD); //communicator
double globl_absorption = globl_balance_table.at(0);
double globl_production = globl_balance_table.at(1);
double globl_in_flow = globl_balance_table.at(2);
double globl_out_flow = globl_balance_table.at(3);
double globl_balance = globl_balance_table.at(4);
double globl_gain = globl_balance_table.at(5);
chi_log.Log() << "Balance table:\n"
<< std::setprecision(5) << std::scientific
<< " Absorption rate = " << globl_absorption << "\n"
<< " Production rate = " << globl_production << "\n"
<< " In-flow rate = " << globl_in_flow << "\n"
<< " Out-flow rate = " << globl_out_flow << "\n"
<< " Integrated scalar flux = " << globl_gain << "\n"
<< " Net Gain/Loss = " << globl_balance << "\n"
<< " Net Gain/Loss normalized = " << globl_balance/globl_gain << "\n";
chi_log.Log() << "\n********** Done computing balance\n";
MPI_Barrier(MPI_COMM_WORLD);
} | 40.029412 | 80 | 0.554739 | zachhardy |
4ab9cd7af36551920e7b49b6d693287ea8eb133e | 5,328 | cpp | C++ | src/AnimationSystem.cpp | SimonWallner/kocmoc-demo | a4f769b5ed7592ce50a18ab93c603d4371fbd291 | [
"MIT",
"Unlicense"
] | 12 | 2015-01-21T07:02:23.000Z | 2021-11-15T19:47:53.000Z | src/AnimationSystem.cpp | SimonWallner/kocmoc-demo | a4f769b5ed7592ce50a18ab93c603d4371fbd291 | [
"MIT",
"Unlicense"
] | null | null | null | src/AnimationSystem.cpp | SimonWallner/kocmoc-demo | a4f769b5ed7592ce50a18ab93c603d4371fbd291 | [
"MIT",
"Unlicense"
] | 3 | 2017-03-04T08:50:46.000Z | 2020-10-23T14:27:04.000Z | #include "AnimationSystem.hpp"
#include "Property.hpp"
#include "utility.hpp"
#include <fstream>
#include <gtx/spline.hpp>
using namespace kocmoc;
AnimationSystem::AnimationSystem(void)
{
fullPath = (std::string)util::Property("scriptsRootFolder") + (std::string)util::Property("animationFileName");
}
AnimationSystem::~AnimationSystem(void)
{
}
AnimationSystem& AnimationSystem::getInstance()
{
static AnimationSystem instance;
return instance;
}
bool AnimationSystem::isspacesonly(const string& line)
{
for (unsigned int i = 0; i < line.length(); ++i)
{
if (!isspace(line[i]))
return false;
}
return true;
}
void AnimationSystem::getnextline(std::istream& is, std::string& line)
{
while (!is.eof())
{
getline(is, line);
if (!isspacesonly(line))
return;
}
}
bool AnimationSystem::parseAnimationFile()
{
std::ifstream file(fullPath.c_str());
if (!file)
{
cout << "failed to load file: " << fullPath << endl;
return false;
}
try
{
string line = "";
string key, value;
while(!file.eof())
{
getnextline(file, line);
const char* cString = line.c_str();
// skip comment lines
if (cString[0] == '#' || cString[0] == '!')
continue;
std::vector<std::string > tokens;
util::tokenize(line, tokens, "\t");
if (tokens.size() == 3)
{
std::string name = tokens[1];
float time, offset, scalar;
if (tokens[0].c_str()[0] == '+')
{
sscanf(tokens[0].c_str(), "%f", &offset);
time = scalarLastKeyTime[name] + offset;
}
else
sscanf(tokens[0].c_str(), "%f", &time);
sscanf(tokens[2].c_str(), "%f", &scalar);
scalarMap[name].push_back(ScalarPair(time, scalar));
scalarLastKeyTime[name] = time;
}
else if (tokens.size() == 5)
{
std::string name = tokens[1];
float time, offset, v0, v1, v2;
if (tokens[0].c_str()[0] == '+')
{
sscanf(tokens[0].c_str(), "%f", &offset);
time = vecLastKeyTime[name] + offset;
}
else
sscanf(tokens[0].c_str(), "%f", &time);
sscanf(tokens[2].c_str(), "%f", &v0);
sscanf(tokens[3].c_str(), "%f", &v1);
sscanf(tokens[4].c_str(), "%f", &v2);
vecMap[name].push_back(VecPair(time, vec3(v0, v1, v2)));
vecLastKeyTime[name] = time;
}
else
std::cout << "failed to parse line: '" << line << "'" << std::endl;
}
} catch (...) {
file.close();
return false;
}
//cout << "parsing successful!" << endl;
file.close();
return true;
}
float AnimationSystem::getScalar(double time, std::string name)
{
// get list
ScalarValues values = scalarMap[name];
if (values.size() == 0)
return 0.0f;
if (values.size() == 1)
return values[0].second;
// binary search
unsigned int lowerIndex = binarySearch(values, time, 0, values.size());
// interpolate
if (lowerIndex == values.size() - 1)
return values[lowerIndex].second;
else
{
float timeA = values[lowerIndex].first;
float valueA = values[lowerIndex].second;
float timeB = values[lowerIndex + 1].first;
float valueB = values[lowerIndex + 1].second;
if (time < timeA)
return valueA;
if (time > timeB)
return valueB;
// we are right in the middle
float t = (timeB - time) / (timeB - timeA);
return t * valueA + (1 - t) * valueB;
}
}
vec3 AnimationSystem::getVec3(double time, std::string name)
{
// get list
VecValues values = vecMap[name];
if (values.size() == 0) // default value for 0 values
return vec3(0.0f);
if (values.size() == 1) // constant interpolation for a single value
return values[0].second;
// binary search
unsigned int lowerIndex = binarySearch(values, time, 0, values.size());
// interpolate
// time is left or right of all samples
if ((lowerIndex == 0 && time < values[lowerIndex].first) || lowerIndex == values.size() - 1)
{
return values[lowerIndex].second; // constant interpolation
}
// only one sample is left or right of time
else // if (lowerIndex == 0 || lowerIndex == values.size() - 2) // linearily interpolate
{
float timeA = values[lowerIndex].first;
vec3 valueA = values[lowerIndex].second;
float timeB = values[lowerIndex + 1].first;
vec3 valueB = values[lowerIndex + 1].second;
float t = (timeB - time) / (timeB - timeA);
return valueA * t + valueB * (1 - t);
}
// NOTE: going back to only linear interpolation
//else // enougth samples on both sides
//{
// // A--B-(time)-C--D
// vec3 valueA = values[lowerIndex -1].second;
// vec3 valueB = values[lowerIndex].second;
// vec3 valueC = values[lowerIndex + 1].second;
// vec3 valueD = values[lowerIndex + 2].second;
// float timeB = values[lowerIndex].first;
// float timeC = values[lowerIndex + 1].first;
//
// float t = (time - timeB) / (timeC - timeB);
// vec3 result = glm::gtx::spline::catmullRom(valueA, valueB, valueC, valueD, t);
// return result;
//}
}
template <class T> unsigned int AnimationSystem::binarySearch(T values, float needle, unsigned int lower, unsigned int upper)
{
if (upper - lower <= 1)
return lower;
unsigned int middle = lower + (upper - lower)/2;
if (needle < values[middle].first) // branch left
return binarySearch(values, needle, lower, middle);
else // branch right
return binarySearch(values, needle, middle, upper);
}
void AnimationSystem::reload()
{
scalarMap.clear();
vecMap.clear();
parseAnimationFile();
} | 22.481013 | 125 | 0.636637 | SimonWallner |
38595c4df2496111b0c7d8796862dd51dbc6c958 | 7,109 | hh | C++ | src/kt84/graphics/phong_tessellation.hh | honoriocassiano/skbar | e2a8fca752f5a2f9d9a32f19cbe1f9032a0e1ac4 | [
"MIT"
] | null | null | null | src/kt84/graphics/phong_tessellation.hh | honoriocassiano/skbar | e2a8fca752f5a2f9d9a32f19cbe1f9032a0e1ac4 | [
"MIT"
] | 5 | 2020-09-01T12:16:28.000Z | 2020-09-01T12:21:41.000Z | src/kt84/graphics/phong_tessellation.hh | honoriocassiano/skbar | e2a8fca752f5a2f9d9a32f19cbe1f9032a0e1ac4 | [
"MIT"
] | null | null | null | #pragma once
#include <GL/glew.h>
#include <vector>
#include <tuple>
#include <Eigen/Core>
#include "../geometry/PointNormal.hh"
namespace kt84 {
namespace phong_tessellation {
enum struct Mode {
TRIANGLES = 0,
LINES,
TRIANGLE_FAN,
LINE_LOOP,
LINE_STRIP
};
inline int& subdiv() {
static int subdiv = 3;
return subdiv;
}
inline double& weight() {
static double weight = 0.7;
return weight;
}
namespace internal {
inline Mode& mode() {
static Mode mode = Mode::TRIANGLES;
return mode;
}
inline bool& enabled() {
static bool enabled = true;
return enabled;
}
inline std::vector<std::tuple<bool, int, double>>& config_stack() {
static std::vector<std::tuple<bool, int, double>> config_stack;
return config_stack;
}
inline std::vector<PointNormal>& pointnormals() {
static std::vector<PointNormal> pointnormals;
return pointnormals;
}
inline PointNormal project(const PointNormal& p, const PointNormal& q) {
PointNormal result;
result.head(3) = q.head(3) - (q - p).head(3).dot(p.tail(3)) * p.tail(3);
result.tail(3) = p.tail(3);
return result;
}
inline PointNormal interpolate(const Eigen::Vector3d& baryCoord, const PointNormal& pn0, const PointNormal& pn1, const PointNormal& pn2) {
PointNormal result = baryCoord[0] * pn0 + baryCoord[1] * pn1 + baryCoord[2] * pn2;
pn_normalize(result);
return result;
}
inline PointNormal interpolate(double u, const PointNormal& pn0, const PointNormal& pn1) {
PointNormal result = (1 - u) * pn0 + u * pn1;
pn_normalize(result);
return result;
}
inline void draw_triangle_sub(int i, int j, const PointNormal& pn0, const PointNormal& pn1, const PointNormal& pn2) {
Eigen::Vector3d baryCoord;
baryCoord[1] = i / static_cast<double>(subdiv());
baryCoord[2] = j / static_cast<double>(subdiv());
baryCoord[0] = 1.0 - baryCoord[1] - baryCoord[2];
PointNormal p = interpolate(baryCoord, pn0, pn1, pn2);
PointNormal q0 = project(pn0, p);
PointNormal q1 = project(pn1, p);
PointNormal q2 = project(pn2, p);
PointNormal q = interpolate(baryCoord, q0, q1, q2);
PointNormal r = (1.0 - weight()) * p + weight() * q;
pn_normalize(r);
glNormal3dv(&r[3]);
glVertex3dv(&r[0]);
}
inline void draw_line_sub(int i, const PointNormal& pn0, const PointNormal& pn1) {
double u = i / static_cast<double>(subdiv());
PointNormal p = interpolate(u, pn0, pn1);
PointNormal q0 = project(pn0, p);
PointNormal q1 = project(pn1, p);
PointNormal q = interpolate(u, q0, q1);
PointNormal r = (1.0 - weight()) * p + weight() * q;
pn_normalize(r);
glNormal3dv(&r[3]);
glVertex3dv(&r[0]);
}
}
inline void begin(Mode mode_) { internal::mode() = mode_; }
inline void vertex(const PointNormal& pn) { internal::pointnormals().push_back(pn); }
inline void vertex(const Eigen::Vector3d& point, const Eigen::Vector3d& normal) {
PointNormal pn;
pn << point, normal;
vertex(pn);
}
inline void enable () { internal::enabled() = true; }
inline void disable() { internal::enabled() = false; }
// config stack
inline void push_config() {
internal::config_stack().push_back(std::make_tuple(internal::enabled(), subdiv(), weight()));
}
inline void pop_config () {
std::tie(internal::enabled(), subdiv(), weight()) = internal::config_stack().back();
internal::config_stack().pop_back();
}
inline void draw_triangle(const PointNormal& pn0, const PointNormal& pn1, const PointNormal& pn2) {
glBegin(GL_TRIANGLES);
if (internal::enabled()) {
for (int i = 0; i < subdiv(); ++i) {
for (int j = 0; j < subdiv() - 1 - i; ++j) {
internal::draw_triangle_sub(i , j , pn0, pn1, pn2);
internal::draw_triangle_sub(i + 1, j , pn0, pn1, pn2);
internal::draw_triangle_sub(i , j + 1, pn0, pn1, pn2);
internal::draw_triangle_sub(i , j + 1, pn0, pn1, pn2);
internal::draw_triangle_sub(i + 1, j , pn0, pn1, pn2);
internal::draw_triangle_sub(i + 1, j + 1, pn0, pn1, pn2);
}
internal::draw_triangle_sub(i , subdiv() - i, pn0, pn1, pn2);
internal::draw_triangle_sub(i , subdiv() - 1 - i, pn0, pn1, pn2);
internal::draw_triangle_sub(i + 1, subdiv() - 1 - i, pn0, pn1, pn2);
}
} else {
glNormal3dv(&pn0[3]); glVertex3dv(&pn0[0]);
glNormal3dv(&pn1[3]); glVertex3dv(&pn1[0]);
glNormal3dv(&pn2[3]); glVertex3dv(&pn2[0]);
}
glEnd();
}
inline void draw_line(const PointNormal& pn0, const PointNormal& pn1) {
glBegin(GL_LINE_STRIP);
if (internal::enabled()) {
for (int i = 0; i < subdiv(); ++i) {
internal::draw_line_sub(i , pn0, pn1);
internal::draw_line_sub(i + 1, pn0, pn1);
}
} else {
glNormal3dv(&pn0[3]); glVertex3dv(&pn0[0]);
glNormal3dv(&pn1[3]); glVertex3dv(&pn1[0]);
}
glEnd();
}
inline void end() {
auto& mode = internal::mode();
auto& pointnormals = internal::pointnormals();
auto n = pointnormals.size();
if (mode == Mode::TRIANGLES) {
if (n < 3) return;
size_t m = n / 3;
for (size_t i = 0; i < m; ++i)
draw_triangle(pointnormals[3 * i], pointnormals[3 * i + 1], pointnormals[3 * i + 2]);
} else if (mode == Mode::LINES) {
if (n < 2) return;
size_t m = n / 2;
for (size_t i = 0; i < m; ++i)
draw_line(pointnormals[2 * i], pointnormals[2 * i + 1]);
} else if (mode == Mode::TRIANGLE_FAN) {
if (n < 3) return;
for (size_t i = 1; i < n - 1; ++i)
draw_triangle(pointnormals[0], pointnormals[i], pointnormals[i + 1]);
} else if (mode == Mode::LINE_LOOP) {
if (n < 2) return;
for (size_t i = 0; i < n; ++i)
draw_line(pointnormals[i], pointnormals[(i + 1) % n]);
} else if (mode == Mode::LINE_STRIP) {
if (n < 2) return;
for (size_t i = 0; i < n - 1; ++i)
draw_line(pointnormals[i], pointnormals[i + 1]);
}
pointnormals .clear();
}
};
}
| 37.81383 | 146 | 0.517654 | honoriocassiano |
385c5629f0871645f8db23744cfeb2928c20aa6b | 52,957 | cpp | C++ | lumino/LuminoCore/src/Math/Matrix.cpp | GameDevery/Lumino | abce2ddca4b7678b04dbfd0ae5348e196c3c9379 | [
"MIT"
] | 113 | 2020-03-05T01:27:59.000Z | 2022-03-28T13:20:51.000Z | lumino/LuminoCore/src/Math/Matrix.cpp | GameDevery/Lumino | abce2ddca4b7678b04dbfd0ae5348e196c3c9379 | [
"MIT"
] | 35 | 2016-04-18T06:14:08.000Z | 2020-02-09T15:51:58.000Z | lumino/LuminoCore/src/Math/Matrix.cpp | GameDevery/Lumino | abce2ddca4b7678b04dbfd0ae5348e196c3c9379 | [
"MIT"
] | 12 | 2020-12-21T12:03:59.000Z | 2021-12-15T02:07:49.000Z |
#include <math.h>
#include <assert.h>
#include <string.h>
#include <LuminoCore/Math/Math.hpp>
#include <LuminoCore/Math/Vector3.hpp>
#include <LuminoCore/Math/Vector4.hpp>
#include <LuminoCore/Math/Quaternion.hpp>
#include <LuminoCore/Math/AttitudeTransform.hpp>
#include <LuminoCore/Math/Plane.hpp>
#include <LuminoCore/Math/Matrix.hpp>
#include "Asm.h"
//#define USE_D3DX9MATH
#ifdef USE_D3DX9MATH
#include <d3dx9math.h>
#pragma comment(lib, "d3dx9.lib")
#endif
namespace ln {
//==============================================================================
// Matrix
const Matrix Matrix::Identity = Matrix();
Matrix::Matrix()
{
m[0][0] = m[1][1] = m[2][2] = m[3][3] = 1.0f;
m[0][1] = m[0][2] = m[0][3] = 0.0f;
m[1][0] = m[1][2] = m[1][3] = 0.0f;
m[2][0] = m[2][1] = m[2][3] = 0.0f;
m[3][0] = m[3][1] = m[3][2] = 0.0f;
}
Matrix::Matrix(
float m11,
float m12,
float m13,
float m14,
float m21,
float m22,
float m23,
float m24,
float m31,
float m32,
float m33,
float m34,
float m41,
float m42,
float m43,
float m44)
{
m[0][0] = m11;
m[0][1] = m12;
m[0][2] = m13;
m[0][3] = m14;
m[1][0] = m21;
m[1][1] = m22;
m[1][2] = m23;
m[1][3] = m24;
m[2][0] = m31;
m[2][1] = m32;
m[2][2] = m33;
m[2][3] = m34;
m[3][0] = m41;
m[3][1] = m42;
m[3][2] = m43;
m[3][3] = m44;
}
Matrix::Matrix(const Vector4& row1, const Vector4& row2, const Vector4& row3, const Vector4& row4)
{
*((Vector4*)this->m[0]) = row1;
*((Vector4*)this->m[1]) = row2;
*((Vector4*)this->m[2]) = row3;
*((Vector4*)this->m[3]) = row4;
}
//Matrix::Matrix(const Quaternion& q)
//{
// float xx = q.X * q.X;
// float yy = q.Y * q.Y;
// float zz = q.Z * q.Z;
// float xy = q.X * q.Y;
// float zw = q.Z * q.W;
// float zx = q.Z * q.X;
// float yw = q.Y * q.W;
// float yz = q.Y * q.Z;
// float xw = q.X * q.W;
// M11 = 1.0f - (2.0f * (yy + zz));
// M12 = 2.0f * (xy + zw);
// M13 = 2.0f * (zx - yw);
// M14 = 0.0f;
// M21 = 2.0f * (xy - zw);
// M22 = 1.0f - (2.0f * (zz + xx));
// M23 = 2.0f * (yz + xw);
// M24 = 0.0f;
// M31 = 2.0f * (zx + yw);
// M32 = 2.0f * (yz - xw);
// M33 = 1.0f - (2.0f * (yy + xx));
// M34 = 0.0f;
// M41 = 0.0f;
// M42 = 0.0f;
// M43 = 0.0f;
// M44 = 1.0f;
//}
Matrix::Matrix(const AttitudeTransform& transform)
{
m[0][0] = m[1][1] = m[2][2] = m[3][3] = 1.0f;
m[0][1] = m[0][2] = m[0][3] = 0.0f;
m[1][0] = m[1][2] = m[1][3] = 0.0f;
m[2][0] = m[2][1] = m[2][3] = 0.0f;
m[3][0] = m[3][1] = m[3][2] = 0.0f;
scale(transform.scale);
rotateQuaternion(transform.rotation);
translate(transform.translation);
}
void Matrix::set(
float m11,
float m12,
float m13,
float m14,
float m21,
float m22,
float m23,
float m24,
float m31,
float m32,
float m33,
float m34,
float m41,
float m42,
float m43,
float m44)
{
m[0][0] = m11;
m[0][1] = m12;
m[0][2] = m13;
m[0][3] = m14;
m[1][0] = m21;
m[1][1] = m22;
m[1][2] = m23;
m[1][3] = m24;
m[2][0] = m31;
m[2][1] = m32;
m[2][2] = m33;
m[2][3] = m34;
m[3][0] = m41;
m[3][1] = m42;
m[3][2] = m43;
m[3][3] = m44;
}
bool Matrix::isIdentity() const
{
return (memcmp(this, &Matrix::Identity, sizeof(Matrix)) == 0);
}
void Matrix::translate(float x, float y, float z)
{
m[3][0] += x;
m[3][1] += y;
m[3][2] += z;
}
void Matrix::translate(const Vector3& vec)
{
m[3][0] += vec.x;
m[3][1] += vec.y;
m[3][2] += vec.z;
}
void Matrix::rotateX(float r)
{
float c, s;
Asm::sincos(r, &s, &c);
/* 普通の行列計算
m[0][0], m[0][1], m[0][2], m[0][3] 1, 0, 0, 0
m[1][0], m[1][1], m[1][2], m[1][3] 0, c,-s, 0
m[2][0], m[2][1], m[2][2], m[2][3] * 0, s, c, 0
m[3][0], m[3][1], m[3][2], m[3][3] 0, 0, 0, 1
*/
/* 計算イメージ
m[0][0] = m[0][0] * 1 + m[0][1] * 0 + m[0][2] * 0 + m[0][3] * 0;
m[0][1] = m[0][0] * 0 + m[0][1] * c + m[0][2] * s + m[0][3] * 0;
m[0][2] = m[0][0] * 0 + m[0][1] *-s + m[0][2] * c + m[0][3] * 0;
m[0][3] = m[0][0] * 0 + m[0][1] * 0 + m[0][2] * 0 + m[0][3] * 1;
m[1][0] = m[1][0] * 1 + m[1][1] * 0 + m[1][2] * 0 + m[1][3] * 0;
m[1][1] = m[1][0] * 0 + m[1][1] * c + m[1][2] * s + m[1][3] * 0;
m[1][2] = m[1][0] * 0 + m[1][1] *-s + m[1][2] * c + m[1][3] * 0;
m[1][3] = m[1][0] * 0 + m[1][1] * 0 + m[1][2] * 0 + m[1][3] * 1;
m[2][0] = m[2][0] * 1 + m[2][1] * 0 + m[2][2] * 0 + m[2][3] * 0;
m[2][1] = m[2][0] * 0 + m[2][1] * c + m[2][2] * s + m[2][3] * 0;
m[2][2] = m[2][0] * 0 + m[2][1] *-s + m[2][2] * c + m[2][3] * 0;
m[2][3] = m[2][0] * 0 + m[2][1] * 0 + m[2][2] * 0 + m[2][3] * 1;
m[3][0] = m[3][0] * 1 + m[3][1] * 0 + m[3][2] * 0 + m[3][3] * 0;
m[3][1] = m[3][0] * 0 + m[3][1] * c + m[3][2] * s + m[3][3] * 0;
m[3][2] = m[3][0] * 0 + m[3][1] *-s + m[3][2] * c + m[3][3] * 0;
m[3][3] = m[3][0] * 0 + m[3][1] * 0 + m[3][2] * 0 + m[3][3] * 1;
*/
/* 正しく計算できるようにしたもの
lfloat mx0 = m[0][0];
lfloat mx1 = m[0][1];
lfloat mx2 = m[0][2];
m[0][0] = mx0 * 1 + mx1 * 0 + mx2 * 0 + m[0][3] * 0;
m[0][1] = mx0 * 0 + mx1 * c + mx2 * s + m[0][3] * 0;
m[0][2] = mx0 * 0 + mx1 *-s + mx2 * c + m[0][3] * 0;
m[0][3] = mx0 * 0 + mx1 * 0 + mx2 * 0 + m[0][3] * 1;
mx0 = m[1][0];
mx1 = m[1][1];
mx2 = m[1][2];
m[1][0] = mx0 * 1 + mx1 * 0 + mx2 * 0 + m[1][3] * 0;
m[1][1] = mx0 * 0 + mx1 * c + mx2 * s + m[1][3] * 0;
m[1][2] = mx0 * 0 + mx1 *-s + mx2 * c + m[1][3] * 0;
m[1][3] = mx0 * 0 + mx1 * 0 + mx2 * 0 + m[1][3] * 1;
mx0 = m[2][0];
mx1 = m[2][1];
mx2 = m[2][2];
m[2][0] = mx0 * 1 + mx1 * 0 + mx2 * 0 + m[2][3] * 0;
m[2][1] = mx0 * 0 + mx1 * c + mx2 * s + m[2][3] * 0;
m[2][2] = mx0 * 0 + mx1 *-s + mx2 * c + m[2][3] * 0;
m[2][3] = mx0 * 0 + mx1 * 0 + mx2 * 0 + m[2][3] * 1;
mx0 = m[3][0];
mx1 = m[3][1];
mx2 = m[3][2];
m[3][0] = mx0 * 1 + mx1 * 0 + mx2 * 0 + m[3][3] * 0;
m[3][1] = mx0 * 0 + mx1 * c + mx2 * s + m[3][3] * 0;
m[3][2] = mx0 * 0 + mx1 *-s + mx2 * c + m[3][3] * 0;
m[3][3] = mx0 * 0 + mx1 * 0 + mx2 * 0 + m[3][3] * 1;
*/
/* 単純に * 0 とかの無駄なところを切る
lfloat mx0 = m[0][0];
lfloat mx1 = m[0][1];
lfloat mx2 = m[0][2];
m[0][0] = mx0;
m[0][1] = mx1 * c + mx2 * s;
m[0][2] = mx1 *-s + mx2 * c;
m[0][3] = m[0][3];
mx0 = m[1][0];
mx1 = m[1][1];
mx2 = m[1][2];
m[1][0] = mx0;
m[1][1] = mx1 * c + mx2 * s;
m[1][2] = mx1 *-s + mx2 * c;
m[1][3] = m[1][3];
mx0 = m[2][0];
mx1 = m[2][1];
mx2 = m[2][2];
m[2][0] = mx0;
m[2][1] = mx1 * c + mx2 * s;
m[2][2] = mx1 *-s + mx2 * c;
m[2][3] = m[2][3];
mx0 = m[3][0];
mx1 = m[3][1];
mx2 = m[3][2];
m[3][0] = mx0;
m[3][1] = mx1 * c + mx2 * s;
m[3][2] = mx1 *-s + mx2 * c;
m[3][3] = m[3][3];
*/
// 自分自身を代入しているところを切る
float mx1 = m[0][1];
m[0][1] = mx1 * c + m[0][2] * -s;
m[0][2] = mx1 * s + m[0][2] * c;
mx1 = m[1][1];
m[1][1] = mx1 * c + m[1][2] * -s;
m[1][2] = mx1 * s + m[1][2] * c;
mx1 = m[2][1];
m[2][1] = mx1 * c + m[2][2] * -s;
m[2][2] = mx1 * s + m[2][2] * c;
mx1 = m[3][1];
m[3][1] = mx1 * c + m[3][2] * -s;
m[3][2] = mx1 * s + m[3][2] * c;
/* OpenGL
lnFloat mx1 = m[0][1];
m[0][1] = mx1 * c + m[0][2] * s;
m[0][2] = mx1 *-s + m[0][2] * c;
mx1 = m[1][1];
m[1][1] = mx1 * c + m[1][2] * s;
m[1][2] = mx1 *-s + m[1][2] * c;
mx1 = m[2][1];
m[2][1] = mx1 * c + m[2][2] * s;
m[2][2] = mx1 *-s + m[2][2] * c;
mx1 = m[3][1];
m[3][1] = mx1 * c + m[3][2] * s;
m[3][2] = mx1 *-s + m[3][2] * c;
*/
}
void Matrix::rotateY(float r)
{
float c, s;
Asm::sincos(r, &s, &c);
/* 普通の行列計算
m[0][0], m[0][1], m[0][2], m[0][3] c, 0, s, 0
m[1][0], m[1][1], m[1][2], m[1][3] 0, 1, 0, 0
m[2][0], m[2][1], m[2][2], m[2][3] * -s, 0, c, 0
m[3][0], m[3][1], m[3][2], m[3][3] 0, 0, 0, 1
*/
/* 計算イメージ
m[0][0] = m[0][0] * c + m[0][1] * 0 + m[0][2] *-s + m[0][3] * 0;
m[0][1] = m[0][0] * 0 + m[0][1] * 1 + m[0][2] * 0 + m[0][3] * 0;
m[0][2] = m[0][0] * s + m[0][1] * 0 + m[0][2] * c + m[0][3] * 0;
m[0][3] = m[0][0] * 0 + m[0][1] * 0 + m[0][2] * 0 + m[0][3] * 1;
m[1][0] = m[1][0] * c + m[1][1] * 0 + m[1][2] *-s + m[1][3] * 0;
m[1][1] = m[1][0] * 0 + m[1][1] * 1 + m[1][2] * 0 + m[1][3] * 0;
m[1][2] = m[1][0] * s + m[1][1] * 0 + m[1][2] * c + m[1][3] * 0;
m[1][3] = m[1][0] * 0 + m[1][1] * 0 + m[1][2] * 0 + m[1][3] * 1;
m[2][0] = m[2][0] * c + m[2][1] * 0 + m[2][2] *-s + m[2][3] * 0;
m[2][1] = m[2][0] * 0 + m[2][1] * 1 + m[2][2] * 0 + m[2][3] * 0;
m[2][2] = m[2][0] * s + m[2][1] * 0 + m[2][2] * c + m[2][3] * 0;
m[2][3] = m[2][0] * 0 + m[2][1] * 0 + m[2][2] * 0 + m[2][3] * 1;
m[3][0] = m[3][0] * c + m[3][1] * 0 + m[3][2] *-s + m[3][3] * 0;
m[3][1] = m[3][0] * 0 + m[3][1] * 1 + m[3][2] * 0 + m[3][3] * 0;
m[3][2] = m[3][0] * s + m[3][1] * 0 + m[3][2] * c + m[3][3] * 0;
m[3][3] = m[3][0] * 0 + m[3][1] * 0 + m[3][2] * 0 + m[3][3] * 1;
*/
/* 正しく計算できるようにしたもの
lfloat mx0 = m[0][0];
lfloat mx1 = m[0][1];
lfloat mx2 = m[0][2];
m[0][0] = mx0 * c + mx1 * 0 + mx2 *-s + m[0][3] * 0;
m[0][1] = mx0 * 0 + mx1 * 1 + mx2 * 0 + m[0][3] * 0;
m[0][2] = mx0 * s + mx1 * 0 + mx2 * c + m[0][3] * 0;
m[0][3] = mx0 * 0 + mx1 * 0 + mx2 * 0 + m[0][3] * 1;
mx0 = m[1][0];
mx1 = m[1][1];
mx2 = m[1][2];
m[1][0] = mx0 * c + mx1 * 0 + mx2 *-s + m[1][3] * 0;
m[1][1] = mx0 * 0 + mx1 * 1 + mx2 * 0 + m[1][3] * 0;
m[1][2] = mx0 * s + mx1 * 0 + mx2 * c + m[1][3] * 0;
m[1][3] = mx0 * 0 + mx1 * 0 + mx2 * 0 + m[1][3] * 1;
mx0 = m[2][0];
mx1 = m[2][1];
mx2 = m[2][2];
m[2][0] = mx0 * c + mx1 * 0 + mx2 *-s + m[2][3] * 0;
m[2][1] = mx0 * 0 + mx1 * 1 + mx2 * 0 + m[2][3] * 0;
m[2][2] = mx0 * s + mx1 * 0 + mx2 * c + m[2][3] * 0;
m[2][3] = mx0 * 0 + mx1 * 0 + mx2 * 0 + m[2][3] * 1;
mx0 = m[3][0];
mx1 = m[3][1];
mx2 = m[3][2];
m[3][0] = mx0 * c + mx1 * 0 + mx2 *-s + m[3][3] * 0;
m[3][1] = mx0 * 0 + mx1 * 1 + mx2 * 0 + m[3][3] * 0;
m[3][2] = mx0 * s + mx1 * 0 + mx2 * c + m[3][3] * 0;
m[3][3] = mx0 * 0 + mx1 * 0 + mx2 * 0 + m[3][3] * 1;
*/
/* 単純に * 0 とかの無駄なところを切る
lfloat mx0 = m[0][0];
lfloat mx1 = m[0][1];
lfloat mx2 = m[0][2];
m[0][0] = mx0 * c + mx2 *-s;
m[0][1] = mx1;
m[0][2] = mx0 * s + mx2 * c;
m[0][3] = m[0][3];
mx0 = m[1][0];
mx1 = m[1][1];
mx2 = m[1][2];
m[1][0] = mx0 * c + mx2 *-s;
m[1][1] = mx1;
m[1][2] = mx0 * s + mx2 * c;
m[1][3] = m[1][3];
mx0 = m[2][0];
mx1 = m[2][1];
mx2 = m[2][2];
m[2][0] = mx0 * c + mx2 *-s;
m[2][1] = mx1;
m[2][2] = mx0 * s + mx2 * c;
m[2][3] = mx3;
mx0 = m[3][0];
mx1 = m[3][1];
mx2 = m[3][2];
m[3][0] = mx0 * c + mx2 *-s;
m[3][1] = mx1;
m[3][2] = mx0 * s + mx2 * c;
m[3][3] = m[3][3];
*/
// 自分自身を代入しているところを切る
float mx0 = m[0][0];
m[0][0] = mx0 * c + m[0][2] * s;
m[0][2] = mx0 * -s + m[0][2] * c;
mx0 = m[1][0];
m[1][0] = mx0 * c + m[1][2] * s;
m[1][2] = mx0 * -s + m[1][2] * c;
mx0 = m[2][0];
m[2][0] = mx0 * c + m[2][2] * s;
m[2][2] = mx0 * -s + m[2][2] * c;
mx0 = m[3][0];
m[3][0] = mx0 * c + m[3][2] * s;
m[3][2] = mx0 * -s + m[3][2] * c;
/* OpenGL
lnFloat mx0 = m[0][0];
m[0][0] = mx0 * c + m[0][2] *-s;
m[0][2] = mx0 * s + m[0][2] * c;
mx0 = m[1][0];
m[1][0] = mx0 * c + m[1][2] *-s;
m[1][2] = mx0 * s + m[1][2] * c;
mx0 = m[2][0];
m[2][0] = mx0 * c + m[2][2] *-s;
m[2][2] = mx0 * s + m[2][2] * c;
mx0 = m[3][0];
m[3][0] = mx0 * c + m[3][2] *-s;
m[3][2] = mx0 * s + m[3][2] * c;
*/
}
void Matrix::rotateZ(float r)
{
float c, s;
Asm::sincos(r, &s, &c);
/* 基本の計算イメージ
m[0][0] = m[0][0] * c + m[0][1] * s + m[0][2] * 0 + m[0][3] * 0;
m[0][1] = m[0][0] *-s + m[0][1] * c + m[0][2] * 0 + m[0][3] * 0;
m[0][2] = m[0][0] * 0 + m[0][1] * 0 + m[0][2] * 1 + m[0][3] * 0;
m[0][3] = m[0][0] * 0 + m[0][1] * 0 + m[0][2] * 0 + m[0][3] * 1;
m[1][0] = m[1][0] * c + m[1][1] * s + m[1][2] * 0 + m[1][3] * 0;
m[1][1] = m[1][0] *-s + m[1][1] * c + m[1][2] * 0 + m[1][3] * 0;
m[1][2] = m[1][0] * 0 + m[1][1] * 0 + m[1][2] * 1 + m[1][3] * 0;
m[1][3] = m[1][0] * 0 + m[1][1] * 0 + m[1][2] * 0 + m[1][3] * 1;
m[2][0] = m[2][0] * c + m[2][1] * s + m[2][2] * 0 + m[2][3] * 0;
m[2][1] = m[2][0] *-s + m[2][1] * c + m[2][2] * 0 + m[2][3] * 0;
m[2][2] = m[2][0] * 0 + m[2][1] * 0 + m[2][2] * 1 + m[2][3] * 0;
m[2][3] = m[2][0] * 0 + m[2][1] * 0 + m[2][2] * 0 + m[2][3] * 1;
m[3][0] = m[3][0] * c + m[3][1] * s + m[3][2] * 0 + m[3][3] * 0;
m[3][1] = m[3][0] *-s + m[3][1] * c + m[3][2] * 0 + m[3][3] * 0;
m[3][2] = m[3][0] * 0 + m[3][1] * 0 + m[3][2] * 1 + m[3][3] * 0;
m[3][3] = m[3][0] * 0 + m[3][1] * 0 + m[3][2] * 0 + m[3][3] * 1;
*/
/* 正しく計算できるようにしたもの
lfloat mx0 = m[0][0];
lfloat mx1 = m[0][1];
lfloat mx2 = m[0][2];
m[0][0] = mx0 * c + mx1 * s + mx2 * 0 + m[0][3] * 0;
m[0][1] = mx0 *-s + mx1 * c + mx2 * 0 + m[0][3] * 0;
m[0][2] = mx0 * 0 + mx1 * 0 + mx2 * 1 + m[0][3] * 0;
m[0][3] = mx0 * 0 + mx1 * 0 + mx2 * 0 + m[0][3] * 1;
mx0 = m[1][0];
mx1 = m[1][1];
mx2 = m[1][2];
m[1][0] = mx0 * c + mx1 * s + mx2 * 0 + m[1][3] * 0;
m[1][1] = mx0 *-s + mx1 * c + mx2 * 0 + m[1][3] * 0;
m[1][2] = mx0 * 0 + mx1 * 0 + mx2 * 1 + m[1][3] * 0;
m[1][3] = mx0 * 0 + mx1 * 0 + mx2 * 0 + m[1][3] * 1;
mx0 = m[2][0];
mx1 = m[2][1];
mx2 = m[2][2];
m[2][0] = mx0 * c + mx1 * s + mx2 * 0 + m[2][3] * 0;
m[2][1] = mx0 *-s + mx1 * c + mx2 * 0 + m[2][3] * 0;
m[2][2] = mx0 * 0 + mx1 * 0 + mx2 * 1 + m[2][3] * 0;
m[2][3] = mx0 * 0 + mx1 * 0 + mx2 * 0 + m[2][3] * 1;
mx0 = m[3][0];
mx1 = m[3][1];
mx2 = m[3][2];
m[3][0] = mx0 * c + mx1 * s + mx2 * 0 + m[3][3] * 0;
m[3][1] = mx0 *-s + mx1 * c + mx2 * 0 + m[3][3] * 0;
m[3][2] = mx0 * 0 + mx1 * 0 + mx2 * 1 + m[3][3] * 0;
m[3][3] = mx0 * 0 + mx1 * 0 + mx2 * 0 + m[3][3] * 1;
*/
/* 単純に * 0 とかの無駄なところを切る
lfloat mx0 = m[0][0];
lfloat mx1 = m[0][1];
lfloat mx2 = m[0][2];
m[0][0] = mx0 * c + mx1 * s;
m[0][1] = mx0 *-s + mx1 * c;
m[0][2] = mx2;
m[0][3] = m[0][3];
mx0 = m[1][0];
mx1 = m[1][1];
mx2 = m[1][2];
m[1][0] = mx0 * c + mx1 * s;
m[1][1] = mx0 *-s + mx1 * c;
m[1][2] = mx2;
m[1][3] = m[1][3];
mx0 = m[2][0];
mx1 = m[2][1];
mx2 = m[2][2];
m[2][0] = mx0 * c + mx1 * s;
m[2][1] = mx0 *-s + mx1 * c;
m[2][2] = mx2;
m[2][3] = m[2][3];
mx0 = m[3][0];
mx1 = m[3][1];
mx2 = m[3][2];
m[3][0] = mx0 * c + mx1 * s;
m[3][1] = mx0 *-s + mx1 * c;
m[3][2] = mx2;
m[3][3] = m[3][3];
*/
// 自分自身を代入しているところを切る
float mx0 = m[0][0];
m[0][0] = mx0 * c + m[0][1] * -s;
m[0][1] = mx0 * s + m[0][1] * c;
mx0 = m[1][0];
m[1][0] = mx0 * c + m[1][1] * -s;
m[1][1] = mx0 * s + m[1][1] * c;
mx0 = m[2][0];
m[2][0] = mx0 * c + m[2][1] * -s;
m[2][1] = mx0 * s + m[2][1] * c;
mx0 = m[3][0];
m[3][0] = mx0 * c + m[3][1] * -s;
m[3][1] = mx0 * s + m[3][1] * c;
// OpenGL
/*
lnFloat mx0 = m[0][0];
m[0][0] = mx0 * c + m[0][1] * s;
m[0][1] = mx0 *-s + m[0][1] * c;
mx0 = m[1][0];
m[1][0] = mx0 * c + m[1][1] * s;
m[1][1] = mx0 *-s + m[1][1] * c;
mx0 = m[2][0];
m[2][0] = mx0 * c + m[2][1] * s;
m[2][1] = mx0 *-s + m[2][1] * c;
mx0 = m[3][0];
m[3][0] = mx0 * c + m[3][1] * s;
m[3][1] = mx0 *-s + m[3][1] * c;
*/
}
void Matrix::rotateEulerAngles(float x, float y, float z, RotationOrder order)
{
rotateEulerAngles(Vector3(x, y, z), order);
}
void Matrix::rotateEulerAngles(const Vector3& angles, RotationOrder order)
{
switch (order) {
case RotationOrder::XYZ:
rotateX(angles.x);
rotateY(angles.y);
rotateZ(angles.z);
break;
case RotationOrder::YZX:
rotateY(angles.y);
rotateZ(angles.z);
rotateX(angles.x);
break;
case RotationOrder::ZXY:
rotateZ(angles.z);
rotateX(angles.x);
rotateY(angles.y);
break; // RotationYawPitchRoll
default:
assert(0);
break;
}
}
void Matrix::rotateAxis(const Vector3& axis_, float r)
{
Vector3 axis = axis_;
if (axis.lengthSquared() != 1.0f) {
axis.mutatingNormalize();
}
float s, c;
Asm::sincos(r, &s, &c);
float mc = 1.0f - c;
/* 計算イメージ
_00 = ( axis_.x * axis_.x ) * mc + c;
_01 = ( axis_.x * axis_.y ) * mc + ( axis_.z * s );
_02 = ( axis_.x * axis_.z ) * mc - ( axis_.y * s );
_03 = 0;
_10 = ( axis_.x * axis_.y ) * mc - ( axis_.z * s );
_11 = ( axis_.y * axis_.y ) * mc + c;
_12 = ( axis_.y * axis_.z ) * mc + ( axis_.x * s );
_13 = 0;
_20 = ( axis_.x * axis_.z ) * mc + ( axis_.y * s );
_21 = ( axis_.y * axis_.z ) * mc - ( axis_.x * s );
_22 = ( axis_.z * axis_.z ) * mc + c;
_23 = 0;
_30 = _31 = _32 = 0;
_33 = 1;
m[0][0] = m[0][0] * _00 + m[0][1] * _10 + m[0][2] * _20 + m[0][3] * _30;
m[0][1] = m[0][0] * _01 + m[0][1] * _11 + m[0][2] * _21 + m[0][3] * _31;
m[0][2] = m[0][0] * _02 + m[0][1] * _12 + m[0][2] * _22 + m[0][3] * _32;
m[0][3] = m[0][0] * _03 + m[0][1] * _13 + m[0][2] * _23 + m[0][3] * _33;
m[1][0] = m[1][0] * _00 + m[1][1] * _10 + m[1][2] * _20 + m[1][3] * _30;
m[1][1] = m[1][0] * _01 + m[1][1] * _11 + m[1][2] * _21 + m[1][3] * _31;
m[1][2] = m[1][0] * _02 + m[1][1] * _12 + m[1][2] * _22 + m[1][3] * _32;
m[1][3] = m[1][0] * _03 + m[1][1] * _13 + m[1][2] * _23 + m[1][3] * _33;
m[2][0] = m[2][0] * _00 + m[2][1] * _10 + m[2][2] * _20 + m[2][3] * _30;
m[2][1] = m[2][0] * _01 + m[2][1] * _11 + m[2][2] * _21 + m[2][3] * _31;
m[2][2] = m[2][0] * _02 + m[2][1] * _12 + m[2][2] * _22 + m[2][3] * _32;
m[2][3] = m[2][0] * _03 + m[2][1] * _13 + m[2][2] * _23 + m[2][3] * _33;
m[3][0] = m[3][0] * _00 + m[3][1] * _10 + m[3][2] * _20 + m[3][3] * _30;
m[3][1] = m[3][0] * _01 + m[3][1] * _11 + m[3][2] * _21 + m[3][3] * _31;
m[3][2] = m[3][0] * _02 + m[3][1] * _12 + m[3][2] * _22 + m[3][3] * _32;
m[3][3] = m[3][0] * _03 + m[3][1] * _13 + m[3][2] * _23 + m[3][3] * _33;
*/
/* 正しく計算できるようにしたもの
lfloat mx0 = m[0][0];
lfloat mx1 = m[0][1];
lfloat mx2 = m[0][2];
m[0][0] = mx0 * _00 + mx1 * _10 + mx2 * _20 + m[0][3] * _30;
m[0][1] = mx0 * _01 + mx1 * _11 + mx2 * _21 + m[0][3] * _31;
m[0][2] = mx0 * _02 + mx1 * _12 + mx2 * _22 + m[0][3] * _32;
m[0][3] = mx0 * _03 + mx1 * _13 + mx2 * _23 + m[0][3] * _33;
mx0 = m[1][0];
mx1 = m[1][1];
mx2 = m[1][2];
m[1][0] = mx0 * _00 + mx1 * _10 + mx2 * _20 + m[1][3] * _30;
m[1][1] = mx0 * _01 + mx1 * _11 + mx2 * _21 + m[1][3] * _31;
m[1][2] = mx0 * _02 + mx1 * _12 + mx2 * _22 + m[1][3] * _32;
m[1][3] = mx0 * _03 + mx1 * _13 + mx2 * _23 + m[1][3] * _33;
mx0 = m[2][0];
mx1 = m[2][1];
mx2 = m[2][2];
m[2][0] = mx0 * _00 + mx1 * _10 + mx2 * _20 + m[2][3] * _30;
m[2][1] = mx0 * _01 + mx1 * _11 + mx2 * _21 + m[2][3] * _31;
m[2][2] = mx0 * _02 + mx1 * _12 + mx2 * _22 + m[2][3] * _32;
m[2][3] = mx0 * _03 + mx1 * _13 + mx2 * _23 + m[2][3] * _33;
mx0 = m[3][0];
mx1 = m[3][1];
mx2 = m[3][2];
m[3][0] = mx0 * _00 + mx1 * _10 + mx2 * _20 + m[3][3] * _30;
m[3][1] = mx0 * _01 + mx1 * _11 + mx2 * _21 + m[3][3] * _31;
m[3][2] = mx0 * _02 + mx1 * _12 + mx2 * _22 + m[3][3] * _32;
m[3][3] = mx0 * _03 + mx1 * _13 + mx2 * _23 + m[3][3] * _33;
*/
/* 0 を乗算してるところと、*1 で自分自身代入しているところを切る
lfloat mx0 = m[0][0];
lfloat mx1 = m[0][1];
lfloat mx2 = m[0][2];
m[0][0] = mx0 * _00 + mx1 * _10 + mx2 * _20;
m[0][1] = mx0 * _01 + mx1 * _11 + mx2 * _21;
m[0][2] = mx0 * _02 + mx1 * _12 + mx2 * _22;
mx0 = m[1][0];
mx1 = m[1][1];
mx2 = m[1][2];
m[1][0] = mx0 * _00 + mx1 * _10 + mx2 * _20;
m[1][1] = mx0 * _01 + mx1 * _11 + mx2 * _21;
m[1][2] = mx0 * _02 + mx1 * _12 + mx2 * _22;
mx0 = m[2][0];
mx1 = m[2][1];
mx2 = m[2][2];
m[2][0] = mx0 * _00 + mx1 * _10 + mx2 * _20;
m[2][1] = mx0 * _01 + mx1 * _11 + mx2 * _21;
m[2][2] = mx0 * _02 + mx1 * _12 + mx2 * _22;
mx0 = m[3][0];
mx1 = m[3][1];
mx2 = m[3][2];
m[3][0] = mx0 * _00 + mx1 * _10 + mx2 * _20;
m[3][1] = mx0 * _01 + mx1 * _11 + mx2 * _21;
m[3][2] = mx0 * _02 + mx1 * _12 + mx2 * _22;
*/
// ※古いコードのなので変数名が 0 スタートになっている点に注意
float _00 = (axis.x * axis.x) * mc + c;
float _01 = (axis.x * axis.y) * mc + (axis.z * s);
float _02 = (axis.x * axis.z) * mc - (axis.y * s);
float _10 = (axis.x * axis.y) * mc - (axis.z * s);
float _11 = (axis.y * axis.y) * mc + c;
float _12 = (axis.y * axis.z) * mc + (axis.x * s);
float _20 = (axis.x * axis.z) * mc + (axis.y * s);
float _21 = (axis.y * axis.z) * mc - (axis.x * s);
float _22 = (axis.z * axis.z) * mc + c;
float mx0 = m[0][0];
float mx1 = m[0][1];
m[0][0] = mx0 * _00 + mx1 * _10 + m[0][2] * _20;
m[0][1] = mx0 * _01 + mx1 * _11 + m[0][2] * _21;
m[0][2] = mx0 * _02 + mx1 * _12 + m[0][2] * _22;
mx0 = m[1][0];
mx1 = m[1][1];
m[1][0] = mx0 * _00 + mx1 * _10 + m[1][2] * _20;
m[1][1] = mx0 * _01 + mx1 * _11 + m[1][2] * _21;
m[1][2] = mx0 * _02 + mx1 * _12 + m[1][2] * _22;
mx0 = m[2][0];
mx1 = m[2][1];
m[2][0] = mx0 * _00 + mx1 * _10 + m[2][2] * _20;
m[2][1] = mx0 * _01 + mx1 * _11 + m[2][2] * _21;
m[2][2] = mx0 * _02 + mx1 * _12 + m[2][2] * _22;
mx0 = m[3][0];
mx1 = m[3][1];
m[3][0] = mx0 * _00 + mx1 * _10 + m[3][2] * _20;
m[3][1] = mx0 * _01 + mx1 * _11 + m[3][2] * _21;
m[3][2] = mx0 * _02 + mx1 * _12 + m[3][2] * _22;
}
void Matrix::rotateQuaternion(const Quaternion& q)
{
float xx = q.x * q.x;
float yy = q.y * q.y;
float zz = q.z * q.z;
float xy = q.x * q.y;
float zw = q.z * q.w;
float zx = q.z * q.x;
float yw = q.y * q.w;
float yz = q.y * q.z;
float xw = q.x * q.w;
// ※古いコードのなので変数名が 0 スタートになっている点に注意
float _00 = 1.0f - (2.0f * (yy + zz));
float _01 = 2.0f * (xy + zw);
float _02 = 2.0f * (zx - yw);
float _10 = 2.0f * (xy - zw);
float _11 = 1.0f - (2.0f * (zz + xx));
float _12 = 2.0f * (yz + xw);
float _20 = 2.0f * (zx + yw);
float _21 = 2.0f * (yz - xw);
float _22 = 1.0f - (2.0f * (yy + xx));
float mx0 = m[0][0];
float mx1 = m[0][1];
m[0][0] = mx0 * _00 + mx1 * _10 + m[0][2] * _20;
m[0][1] = mx0 * _01 + mx1 * _11 + m[0][2] * _21;
m[0][2] = mx0 * _02 + mx1 * _12 + m[0][2] * _22;
mx0 = m[1][0];
mx1 = m[1][1];
m[1][0] = mx0 * _00 + mx1 * _10 + m[1][2] * _20;
m[1][1] = mx0 * _01 + mx1 * _11 + m[1][2] * _21;
m[1][2] = mx0 * _02 + mx1 * _12 + m[1][2] * _22;
mx0 = m[2][0];
mx1 = m[2][1];
m[2][0] = mx0 * _00 + mx1 * _10 + m[2][2] * _20;
m[2][1] = mx0 * _01 + mx1 * _11 + m[2][2] * _21;
m[2][2] = mx0 * _02 + mx1 * _12 + m[2][2] * _22;
mx0 = m[3][0];
mx1 = m[3][1];
m[3][0] = mx0 * _00 + mx1 * _10 + m[3][2] * _20;
m[3][1] = mx0 * _01 + mx1 * _11 + m[3][2] * _21;
m[3][2] = mx0 * _02 + mx1 * _12 + m[3][2] * _22;
}
void Matrix::scale(float x, float y, float z)
{
m[0][0] *= x;
m[0][1] *= y;
m[0][2] *= z;
m[1][0] *= x;
m[1][1] *= y;
m[1][2] *= z;
m[2][0] *= x;
m[2][1] *= y;
m[2][2] *= z;
m[3][0] *= x;
m[3][1] *= y;
m[3][2] *= z;
}
void Matrix::scale(const Vector3& vec)
{
scale(vec.x, vec.y, vec.z);
}
void Matrix::scale(float xyz)
{
scale(xyz, xyz, xyz);
}
void Matrix::inverse()
{
(*this) = Matrix::makeInverse(*this);
}
void Matrix::transpose()
{
(*this) = Matrix::makeTranspose(*this);
}
void Matrix::decompose(Vector3* scale, Quaternion* rot, Vector3* trans) const
{
Matrix scaleMat;
Matrix rotMat;
Matrix transMat;
decomposeMatrices(&scaleMat, &rotMat, &transMat);
if (scale) {
scale->set(scaleMat.m[0][0], scaleMat.m[1][1], scaleMat.m[2][2]);
}
if (rot) {
*rot = Quaternion::makeFromRotationMatrix(rotMat);
}
if (trans) {
trans->set(transMat.m[3][0], transMat.m[3][1], transMat.m[3][2]);
}
}
void Matrix::decomposeMatrices(Matrix* scale, Matrix* rot, Matrix* trans) const
{
if (trans) {
*trans = Matrix::makeTranslation(position());
}
Vector3 sc(
sqrtf(m[0][0] * m[0][0] + m[0][1] * m[0][1] + m[0][2] * m[0][2]),
sqrtf(m[1][0] * m[1][0] + m[1][1] * m[1][1] + m[1][2] * m[1][2]),
sqrtf(m[2][0] * m[2][0] + m[2][1] * m[2][1] + m[2][2] * m[2][2]));
if (scale) {
*scale = Matrix::makeScaling(sc);
}
if (rot) {
*rot = Identity;
rot->m[0][0] = (sc.x != 0.0f) ? m[0][0] / sc.x : 0.0f;
rot->m[0][1] = (sc.x != 0.0f) ? m[0][1] / sc.x : 0.0f;
rot->m[0][2] = (sc.x != 0.0f) ? m[0][2] / sc.x : 0.0f;
rot->m[0][3] = 0.0f;
rot->m[1][0] = (sc.y != 0.0f) ? m[1][0] / sc.y : 0.0f;
rot->m[1][1] = (sc.y != 0.0f) ? m[1][1] / sc.y : 0.0f;
rot->m[1][2] = (sc.y != 0.0f) ? m[1][2] / sc.y : 0.0f;
rot->m[1][3] = 0.0f;
rot->m[2][0] = (sc.z != 0.0f) ? m[2][0] / sc.z : 0.0f;
rot->m[2][1] = (sc.z != 0.0f) ? m[2][1] / sc.z : 0.0f;
rot->m[2][2] = (sc.z != 0.0f) ? m[2][2] / sc.z : 0.0f;
rot->m[2][3] = 0.0f;
rot->m[3][0] = 0.0f;
rot->m[3][1] = 0.0f;
rot->m[3][2] = 0.0f;
rot->m[3][3] = 1.0f;
}
}
#if 0
void Matrix::decompose(Vector3* scale, Matrix* rot, Vector3* trans)
{
if (trans)
{
trans->Set(m[3][0], m[3][1], m[3][2]);
}
Vector3 sc(
sqrtf(m[0][0] * m[0][0] + m[0][1] * m[0][1] + m[0][2] * m[0][2]),
sqrtf(m[1][0] * m[1][0] + m[1][1] * m[1][1] + m[1][2] * m[1][2]),
sqrtf(m[2][0] * m[2][0] + m[2][1] * m[2][1] + m[2][2] * m[2][2]));
if (scale)
{
*scale = sc;
}
if (rot)
{
rot->m[0][0] = (sc.X != 0.0f) ? m[0][0] / sc.X : 0.0f;
rot->m[0][1] = (sc.X != 0.0f) ? m[0][1] / sc.X : 0.0f;
rot->m[0][2] = (sc.X != 0.0f) ? m[0][2] / sc.X : 0.0f;
rot->m[0][3] = 0.0f;
rot->m[1][0] = (sc.Y != 0.0f) ? m[1][0] / sc.Y : 0.0f;
rot->m[1][1] = (sc.Y != 0.0f) ? m[1][1] / sc.Y : 0.0f;
rot->m[1][2] = (sc.Y != 0.0f) ? m[1][2] / sc.Y : 0.0f;
rot->m[1][3] = 0.0f;
rot->m[2][0] = (sc.Z != 0.0f) ? m[2][0] / sc.Z : 0.0f;
rot->m[2][1] = (sc.Z != 0.0f) ? m[2][1] / sc.Z : 0.0f;
rot->m[2][2] = (sc.Z != 0.0f) ? m[2][2] / sc.Z : 0.0f;
rot->m[2][3] = 0.0f;
rot->m[3][0] = 0.0f;
rot->m[3][1] = 0.0f;
rot->m[3][2] = 0.0f;
rot->m[3][3] = 1.0f;
}
}
void Matrix::decompose(Vector3* scale, Quaternion* rot, Vector3* trans) const
{
if (rot)
{
Matrix rotMat;
decompose(scale, &rotMat, trans);
*rot =
}
else
{
decompose(scale, NULL, trans);
}
}
#endif
static bool EulerAnglesXYZ(const Matrix& mat, float* xRot, float* yRot, float* zRot)
{
static const float Threshold = 0.0001f;
if (mat.m[0][2] > 1.0f - Threshold || mat.m[0][2] < -1.0f + Threshold) // ジンバルロック判定
{
*xRot = 0.0f;
*yRot = (mat.m[0][2] < 0 ? Math::PIDiv2 : -Math::PIDiv2);
*zRot = -atan2f(-mat.m[1][0], mat.m[1][1]);
return false;
}
*yRot = -asinf(mat.m[0][2]);
*xRot = asinf(mat.m[1][2] / cosf(*yRot));
if (Math::isNaN(*xRot)) // ジンバルロック判定
{
*xRot = 0.0f;
*yRot = (mat.m[0][2] < 0 ? Math::PIDiv2 : -Math::PIDiv2);
*zRot = -atan2f(-mat.m[1][0], mat.m[1][1]);
return false;
}
if (mat.m[2][2] < 0.0f) {
*xRot = Math::PI - (*xRot);
}
*zRot = atan2f(mat.m[0][1], mat.m[0][0]);
return true;
}
static bool EulerAnglesYZX(const Matrix& mat, float* xRot, float* yRot, float* zRot)
{
static const float Threshold = 0.0001f;
if (mat.m[1][0] > 1.0f - Threshold || mat.m[1][0] < -1.0f + Threshold) // ジンバルロック判定
{
*xRot = -atan2f(-mat.m[2][1], mat.m[2][2]);
*yRot = 0.0f;
*zRot = (mat.m[1][0] < 0 ? Math::PIDiv2 : -Math::PIDiv2);
return false;
}
*zRot = -asinf(mat.m[1][0]);
*yRot = asinf(mat.m[2][0] / cosf(*zRot));
if (Math::isNaN(*yRot)) // ジンバルロック判定
{
*xRot = -atan2f(-mat.m[2][1], mat.m[2][2]);
*yRot = 0.0f;
*zRot = (mat.m[1][0] < 0 ? Math::PIDiv2 : -Math::PIDiv2);
return false;
}
if (mat.m[0][0] < 0.0f) {
*yRot = Math::PI - (*yRot);
}
*xRot = atan2f(mat.m[1][2], mat.m[1][1]);
return true;
}
static bool EulerAnglesZXY(const Matrix& mat, float* xRot, float* yRot, float* zRot)
{
static const float Threshold = 0.0001f;
//if (locked) { *locked = true; } // 最初にジンバルロック発生状態にしておく
if (mat.m[2][1] > 1.0f - Threshold || mat.m[2][1] < -1.0f + Threshold) // ジンバルロック判定
{
*xRot = (mat.m[2][1] < 0 ? Math::PIDiv2 : -Math::PIDiv2);
*yRot = (float)atan2f(-mat.m[0][2], mat.m[0][0]);
*zRot = 0.0f;
return false;
}
*xRot = -(float)asinf(mat.m[2][1]);
*zRot = (float)asinf(mat.m[0][1] / cosf(*xRot));
if (Math::isNaN(*zRot)) // ジンバルロック判定
{
*xRot = (mat.m[2][1] < 0 ? Math::PIDiv2 : -Math::PIDiv2);
*yRot = (float)atan2f(-mat.m[0][2], mat.m[0][0]);
*zRot = 0.0f;
return false;
}
if (mat.m[1][1] < 0.0f) {
*zRot = Math::PI - (*zRot);
}
*yRot = (float)atan2f(mat.m[2][0], mat.m[2][2]);
//if (locked) { *locked = false; } // ジンバルロックは発生しなかった
//return Vector3(xRot, yRot, zRot);
return true;
}
Vector3 Matrix::toEulerAngles(RotationOrder order, bool* locked_) const
{
bool locked;
float xRot, yRot, zRot;
switch (order) {
case RotationOrder::XYZ:
locked = !EulerAnglesXYZ(*this, &xRot, &yRot, &zRot);
break;
//case RotationOrder_XZY: break;
//case RotationOrder_YXZ: break;
case RotationOrder::YZX:
locked = !EulerAnglesYZX(*this, &xRot, &yRot, &zRot);
break;
case RotationOrder::ZXY:
locked = !EulerAnglesZXY(*this, &xRot, &yRot, &zRot); // RotationYawPitchRoll
break;
//case RotationOrder_ZYX: break;
default:
assert(0);
return Vector3();
}
if (locked_ != NULL) {
*locked_ = locked;
}
return Vector3(xRot, yRot, zRot);
}
Matrix Matrix::getRotationMatrix() const
{
return Matrix(
m[0][0], m[0][1], m[0][2], 0.0f, m[1][0], m[1][1], m[1][2], 0.0f, m[2][0], m[2][1], m[2][2], 0.0f, 0.0f, 0.0f, 0.0f, 1.0f);
}
bool Matrix::isNaNOrInf() const
{
return Math::isNaNOrInf(m[0][0]) || Math::isNaNOrInf(m[0][1]) || Math::isNaNOrInf(m[0][2]) || Math::isNaNOrInf(m[0][3]) ||
Math::isNaNOrInf(m[1][0]) || Math::isNaNOrInf(m[1][1]) || Math::isNaNOrInf(m[1][2]) || Math::isNaNOrInf(m[1][3]) ||
Math::isNaNOrInf(m[2][0]) || Math::isNaNOrInf(m[2][1]) || Math::isNaNOrInf(m[2][2]) || Math::isNaNOrInf(m[2][3]) ||
Math::isNaNOrInf(m[3][0]) || Math::isNaNOrInf(m[3][1]) || Math::isNaNOrInf(m[3][2]) || Math::isNaNOrInf(m[3][3]);
}
String Matrix::toString() const
{
const std::size_t BufferLength = 4096;
char text[BufferLength];
StringHelper::vsprintf2(
text, BufferLength, "Matrix((%f, %f, %f, %f), (%f, %f, %f, %f), (%f, %f, %f, %f), (%f, %f, %f, %f))",
m[0][0], m[0][1], m[0][2], m[0][3],
m[1][0], m[1][1], m[1][2], m[1][3],
m[2][0], m[2][1], m[2][2], m[2][3],
m[3][0], m[3][1], m[3][2], m[3][3]);
return String::fromCString(text);
}
const float& Matrix::operator()(int row, int column) const
{
LN_CHECK(0 <= row && row <= 3);
LN_CHECK(0 <= column && column <= 3);
return m[row][column];
}
float & Matrix::operator()(int row, int column)
{
LN_CHECK(0 <= row && row <= 3);
LN_CHECK(0 <= column && column <= 3);
return m[row][column];
}
// static
Matrix Matrix::multiply(const Matrix& mat1, const Matrix& mat2)
{
Matrix out;
out.m[0][0] = mat1.m[0][0] * mat2.m[0][0] + mat1.m[0][1] * mat2.m[1][0] + mat1.m[0][2] * mat2.m[2][0] + mat1.m[0][3] * mat2.m[3][0];
out.m[0][1] = mat1.m[0][0] * mat2.m[0][1] + mat1.m[0][1] * mat2.m[1][1] + mat1.m[0][2] * mat2.m[2][1] + mat1.m[0][3] * mat2.m[3][1];
out.m[0][2] = mat1.m[0][0] * mat2.m[0][2] + mat1.m[0][1] * mat2.m[1][2] + mat1.m[0][2] * mat2.m[2][2] + mat1.m[0][3] * mat2.m[3][2];
out.m[0][3] = mat1.m[0][0] * mat2.m[0][3] + mat1.m[0][1] * mat2.m[1][3] + mat1.m[0][2] * mat2.m[2][3] + mat1.m[0][3] * mat2.m[3][3];
out.m[1][0] = mat1.m[1][0] * mat2.m[0][0] + mat1.m[1][1] * mat2.m[1][0] + mat1.m[1][2] * mat2.m[2][0] + mat1.m[1][3] * mat2.m[3][0];
out.m[1][1] = mat1.m[1][0] * mat2.m[0][1] + mat1.m[1][1] * mat2.m[1][1] + mat1.m[1][2] * mat2.m[2][1] + mat1.m[1][3] * mat2.m[3][1];
out.m[1][2] = mat1.m[1][0] * mat2.m[0][2] + mat1.m[1][1] * mat2.m[1][2] + mat1.m[1][2] * mat2.m[2][2] + mat1.m[1][3] * mat2.m[3][2];
out.m[1][3] = mat1.m[1][0] * mat2.m[0][3] + mat1.m[1][1] * mat2.m[1][3] + mat1.m[1][2] * mat2.m[2][3] + mat1.m[1][3] * mat2.m[3][3];
out.m[2][0] = mat1.m[2][0] * mat2.m[0][0] + mat1.m[2][1] * mat2.m[1][0] + mat1.m[2][2] * mat2.m[2][0] + mat1.m[2][3] * mat2.m[3][0];
out.m[2][1] = mat1.m[2][0] * mat2.m[0][1] + mat1.m[2][1] * mat2.m[1][1] + mat1.m[2][2] * mat2.m[2][1] + mat1.m[2][3] * mat2.m[3][1];
out.m[2][2] = mat1.m[2][0] * mat2.m[0][2] + mat1.m[2][1] * mat2.m[1][2] + mat1.m[2][2] * mat2.m[2][2] + mat1.m[2][3] * mat2.m[3][2];
out.m[2][3] = mat1.m[2][0] * mat2.m[0][3] + mat1.m[2][1] * mat2.m[1][3] + mat1.m[2][2] * mat2.m[2][3] + mat1.m[2][3] * mat2.m[3][3];
out.m[3][0] = mat1.m[3][0] * mat2.m[0][0] + mat1.m[3][1] * mat2.m[1][0] + mat1.m[3][2] * mat2.m[2][0] + mat1.m[3][3] * mat2.m[3][0];
out.m[3][1] = mat1.m[3][0] * mat2.m[0][1] + mat1.m[3][1] * mat2.m[1][1] + mat1.m[3][2] * mat2.m[2][1] + mat1.m[3][3] * mat2.m[3][1];
out.m[3][2] = mat1.m[3][0] * mat2.m[0][2] + mat1.m[3][1] * mat2.m[1][2] + mat1.m[3][2] * mat2.m[2][2] + mat1.m[3][3] * mat2.m[3][2];
out.m[3][3] = mat1.m[3][0] * mat2.m[0][3] + mat1.m[3][1] * mat2.m[1][3] + mat1.m[3][2] * mat2.m[2][3] + mat1.m[3][3] * mat2.m[3][3];
return out;
}
// static
Matrix Matrix::makeTranslation(float x, float y, float z)
{
return Matrix(
1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, x, y, z, 1.0f);
}
// static
Matrix Matrix::makeTranslation(const Vector3& vec)
{
return Matrix(
1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, vec.x, vec.y, vec.z, 1.0f);
}
// static
Matrix Matrix::makeRotationX(float r)
{
float c, s;
Asm::sincos(r, &s, &c);
return Matrix(
1.0f, 0.0f, 0.0f, 0.0f,
0.0f, c, s, 0.0f,
0.0f,-s, c, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f);
}
// static
Matrix Matrix::makeRotationY(float r)
{
float c, s;
Asm::sincos(r, &s, &c);
return Matrix(
c, 0.0f, -s, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, s, 0.0f, c, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f);
}
// static
Matrix Matrix::makeRotationZ(float r)
{
float c, s;
Asm::sincos(r, &s, &c);
return Matrix(
c, s, 0.0f, 0.0f,
-s, c, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f);
}
// static
Matrix Matrix::makeRotationAxis(const Vector3& axis_, float r)
{
Vector3 axis = axis_;
if (axis.lengthSquared() != 1.0f) {
axis.mutatingNormalize();
}
float s, c;
Asm::sincos(r, &s, &c);
float mc = 1.0f - c;
return Matrix(
(axis.x * axis.x) * mc + c, (axis.x * axis.y) * mc + (axis.z * s), (axis.x * axis.z) * mc - (axis.y * s), 0.0f, (axis.x * axis.y) * mc - (axis.z * s), (axis.y * axis.y) * mc + c, (axis.y * axis.z) * mc + (axis.x * s), 0.0f, (axis.x * axis.z) * mc + (axis.y * s), (axis.y * axis.z) * mc - (axis.x * s), (axis.z * axis.z) * mc + c, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f);
}
// static
Matrix Matrix::makeRotationQuaternion(const Quaternion& qua)
{
float xx = qua.x * qua.x;
float yy = qua.y * qua.y;
float zz = qua.z * qua.z;
float xy = qua.x * qua.y;
float zw = qua.z * qua.w;
float zx = qua.z * qua.x;
float yw = qua.y * qua.w;
float yz = qua.y * qua.z;
float xw = qua.x * qua.w;
return Matrix(
1.0f - (2.0f * (yy + zz)), 2.0f * (xy + zw), 2.0f * (zx - yw), 0.0f, 2.0f * (xy - zw), 1.0f - (2.0f * (zz + xx)), 2.0f * (yz + xw), 0.0f, 2.0f * (zx + yw), 2.0f * (yz - xw), 1.0f - (2.0f * (yy + xx)), 0.0f, 0.0f, 0.0f, 0.0f, 1.0f);
}
// static
Matrix Matrix::makeRotationEulerAngles(const Vector3& angles, RotationOrder order)
{
Matrix m;
switch (order) {
case RotationOrder::XYZ:
m.rotateX(angles.x);
m.rotateY(angles.y);
m.rotateZ(angles.z);
break;
//case RotationOrder_XZY:
// m.rotateX(angles.X); m.rotateZ(angles.Z); m.rotateY(angles.Y); break;
//case RotationOrder_YXZ:
// m.rotateY(angles.Y); m.rotateX(angles.X); m.rotateZ(angles.Z); break;
case RotationOrder::YZX:
m.rotateY(angles.y);
m.rotateZ(angles.z);
m.rotateX(angles.x);
break;
case RotationOrder::ZXY:
m.rotateZ(angles.z);
m.rotateX(angles.x);
m.rotateY(angles.y);
break; // RotationYawPitchRoll
//case RotationOrder_ZYX:
// m.rotateZ(angles.Z); m.rotateY(angles.Y); m.rotateX(angles.X); break;
default:
assert(0);
return m;
}
return m;
}
// static
Matrix Matrix::makeRotationEulerAngles(float x, float y, float z, RotationOrder order)
{
Matrix m;
switch (order) {
case RotationOrder::XYZ:
m.rotateX(x);
m.rotateY(y);
m.rotateZ(z);
break;
case RotationOrder::YZX:
m.rotateY(y);
m.rotateZ(z);
m.rotateX(y);
break;
case RotationOrder::ZXY:
m.rotateZ(z);
m.rotateX(x);
m.rotateY(y);
break; // RotationYawPitchRoll
default:
assert(0);
return m;
}
return m;
}
// static
Matrix Matrix::makeRotationYawPitchRoll(float yaw, float pitch, float roll)
{
Quaternion q = Quaternion::makeFromYawPitchRoll(yaw, pitch, roll);
return Matrix::makeRotationQuaternion(q);
}
// static
Matrix Matrix::makeScaling(float x, float y, float z)
{
return Matrix(
x, 0.0f, 0.0f, 0.0f, 0.0f, y, 0.0f, 0.0f, 0.0f, 0.0f, z, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f);
}
// static
Matrix Matrix::makeScaling(const Vector3& vec)
{
return Matrix(
vec.x, 0.0f, 0.0f, 0.0f, 0.0f, vec.y, 0.0f, 0.0f, 0.0f, 0.0f, vec.z, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f);
}
// static
Matrix Matrix::makeScaling(float xyz)
{
return Matrix(
xyz, 0.0f, 0.0f, 0.0f, 0.0f, xyz, 0.0f, 0.0f, 0.0f, 0.0f, xyz, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f);
}
// static
Matrix Matrix::makeInverse(const Matrix& mat)
{
#if 1 // 速度は D3DXMatrixInverse の 2~3倍 (100000 回で 3000us。コンストラクタとかが足引っ張ってそうな気がする…)
float coef00 = mat.m[2][2] * mat.m[3][3] - mat.m[3][2] * mat.m[2][3];
float coef02 = mat.m[1][2] * mat.m[3][3] - mat.m[3][2] * mat.m[1][3];
float coef03 = mat.m[1][2] * mat.m[2][3] - mat.m[2][2] * mat.m[1][3];
float coef04 = mat.m[2][1] * mat.m[3][3] - mat.m[3][1] * mat.m[2][3];
float coef06 = mat.m[1][1] * mat.m[3][3] - mat.m[3][1] * mat.m[1][3];
float coef07 = mat.m[1][1] * mat.m[2][3] - mat.m[2][1] * mat.m[1][3];
float coef08 = mat.m[2][1] * mat.m[3][2] - mat.m[3][1] * mat.m[2][2];
float coef10 = mat.m[1][1] * mat.m[3][2] - mat.m[3][1] * mat.m[1][2];
float coef11 = mat.m[1][1] * mat.m[2][2] - mat.m[2][1] * mat.m[1][2];
float coef12 = mat.m[2][0] * mat.m[3][3] - mat.m[3][0] * mat.m[2][3];
float coef14 = mat.m[1][0] * mat.m[3][3] - mat.m[3][0] * mat.m[1][3];
float coef15 = mat.m[1][0] * mat.m[2][3] - mat.m[2][0] * mat.m[1][3];
float coef16 = mat.m[2][0] * mat.m[3][2] - mat.m[3][0] * mat.m[2][2];
float coef18 = mat.m[1][0] * mat.m[3][2] - mat.m[3][0] * mat.m[1][2];
float coef19 = mat.m[1][0] * mat.m[2][2] - mat.m[2][0] * mat.m[1][2];
float coef20 = mat.m[2][0] * mat.m[3][1] - mat.m[3][0] * mat.m[2][1];
float coef22 = mat.m[1][0] * mat.m[3][1] - mat.m[3][0] * mat.m[1][1];
float coef23 = mat.m[1][0] * mat.m[2][1] - mat.m[2][0] * mat.m[1][1];
Vector4 fac0(coef00, coef00, coef02, coef03);
Vector4 fac1(coef04, coef04, coef06, coef07);
Vector4 fac2(coef08, coef08, coef10, coef11);
Vector4 fac3(coef12, coef12, coef14, coef15);
Vector4 fac4(coef16, coef16, coef18, coef19);
Vector4 fac5(coef20, coef20, coef22, coef23);
Vector4 vec0(mat.m[1][0], mat.m[0][0], mat.m[0][0], mat.m[0][0]);
Vector4 vec1(mat.m[1][1], mat.m[0][1], mat.m[0][1], mat.m[0][1]);
Vector4 vec2(mat.m[1][2], mat.m[0][2], mat.m[0][2], mat.m[0][2]);
Vector4 vec3(mat.m[1][3], mat.m[0][3], mat.m[0][3], mat.m[0][3]);
Vector4 inv0(vec1 * fac0 - vec2 * fac1 + vec3 * fac2);
Vector4 inv1(vec0 * fac0 - vec2 * fac3 + vec3 * fac4);
Vector4 inv2(vec0 * fac1 - vec1 * fac3 + vec3 * fac5);
Vector4 inv3(vec0 * fac2 - vec1 * fac4 + vec2 * fac5);
Vector4 signA(+1, -1, +1, -1);
Vector4 signB(-1, +1, -1, +1);
Matrix inverse(inv0 * signA, inv1 * signB, inv2 * signA, inv3 * signB);
Vector4 dot0(mat.m[0][0] * inverse.m[0][0], mat.m[0][1] * inverse.m[1][0], mat.m[0][2] * inverse.m[2][0], mat.m[0][3] * inverse.m[3][0]);
float dot1 = (dot0.x + dot0.y) + (dot0.z + dot0.w);
if (dot1 == 0.0) {
// 計算できない。D3D に合わせて、単位行列で返す
return Identity;
}
float oneOverDeterminant = 1.0f / dot1;
return inverse * oneOverDeterminant;
#endif
#if 0 // 速度は D3DXMatrixInverse の 10倍
int i, j;
float buf;
Matrix tm(mat_);
identity(out_);
// 掃き出し法
for (i = 0; i < 4; ++i)
{
//if (tm.m[ i ][ i ] != 0)
buf = 1.0f / tm.m[i][i]; // 0除算の可能性がある
//else
// buf = 0.0;
for (j = 0; j < 4; ++j)
{
tm.m[i][j] *= buf;
out_->m[i][j] *= buf;
}
for (j = 0; j < 4; ++j)
{
if (i != j)
{
buf = tm.m[j][i];
for (int k = 0; k < 4; ++k)
{
tm.m[j][k] -= tm.m[i][k] * buf;
out_->m[j][k] -= out_->m[i][k] * buf;
}
}
}
}
#endif
#ifdef USE_D3DX9MATH
Matrix out;
D3DXMatrixInverse((D3DXMATRIX*)&out, NULL, (D3DXMATRIX*)&mat);
return out;
#endif
#if 0
// http://www.cg.info.hiroshima-cu.ac.jp/~miyazaki/knowledge/tech23.html
float m0011 = mat_.m[0][0] * mat_.m[1][1];
float m0012 = mat_.m[0][0] * mat_.m[1][2];
float m0021 = mat_.m[0][0] * mat_.m[2][1];
float m0022 = mat_.m[0][0] * mat_.m[2][2];
float m0110 = mat_.m[0][1] * mat_.m[1][0];
float m0112 = mat_.m[0][1] * mat_.m[1][2];
float m0120 = mat_.m[0][1] * mat_.m[2][0];
float m0122 = mat_.m[0][1] * mat_.m[2][2];
float m0210 = mat_.m[0][2] * mat_.m[1][0];
float m0211 = mat_.m[0][2] * mat_.m[1][1];
float m0220 = mat_.m[0][2] * mat_.m[2][0];
float m0221 = mat_.m[0][2] * mat_.m[2][1];
float m1021 = mat_.m[1][0] * mat_.m[2][1];
float m1022 = mat_.m[1][0] * mat_.m[2][2];
float m1120 = mat_.m[1][1] * mat_.m[2][0];
float m1122 = mat_.m[1][1] * mat_.m[2][2];
float m1220 = mat_.m[1][2] * mat_.m[2][0];
float m1221 = mat_.m[1][2] * mat_.m[2][1];
float m1122_m1221 = m1122 - m1221;
float m1220_m1022 = m1220 - m1022;
float m1021_m1120 = m1021 - m1120;
float delta = mat_.m[0][0] * (m1122_m1221)+mat_.m[0][1] * (m1220_m1022)+mat_.m[0][2] * (m1021_m1120);
float rcpDelta = 1.f / delta;
Matrix mat;
mat.m[0][0] = (m1122_m1221)* rcpDelta;
mat.m[1][0] = (m1220_m1022)* rcpDelta;
mat.m[2][0] = (m1021_m1120)* rcpDelta;
mat.m[0][1] = (m0221 - m0122) * rcpDelta;
mat.m[1][1] = (m0022 - m0220) * rcpDelta;
mat.m[2][1] = (m0120 - m0021) * rcpDelta;
mat.m[0][2] = (m0112 - m0211) * rcpDelta;
mat.m[1][2] = (m0210 - m0012) * rcpDelta;
mat.m[2][2] = (m0011 - m0110) * rcpDelta;
float t03 = mat_.m[0][3];
float t13 = mat_.m[1][3];
mat.m[0][3] = -(mat.m[0][0] * t03 + mat.m[0][1] * t13 + mat.m[0][2] * mat_.m[2][3]);
mat.m[1][3] = -(mat.m[1][0] * t03 + mat.m[1][1] * t13 + mat.m[1][2] * mat_.m[2][3]);
mat.m[2][3] = -(mat.m[2][0] * t03 + mat.m[2][1] * t13 + mat.m[2][2] * mat_.m[2][3]);
return mat;
#endif
}
// static
Matrix Matrix::makeTranspose(const Matrix& mat)
{
return Matrix(
mat.m[0][0], mat.m[1][0], mat.m[2][0], mat.m[3][0], mat.m[0][1], mat.m[1][1], mat.m[2][1], mat.m[3][1], mat.m[0][2], mat.m[1][2], mat.m[2][2], mat.m[3][2], mat.m[0][3], mat.m[1][3], mat.m[2][3], mat.m[3][3]);
}
// static
Matrix Matrix::makeReflection(const Plane& plane_)
{
Plane plane = Plane::normalize(plane_);
float x = plane.normal.x;
float y = plane.normal.y;
float z = plane.normal.z;
float x2 = -2.0f * x;
float y2 = -2.0f * y;
float z2 = -2.0f * z;
return Matrix(
(x2 * x) + 1.0f, y2 * x, z2 * x, 0.0f, x2 * y, (y2 * y) + 1.0f, z2 * y, 0.0f, x2 * z, y2 * z, (z2 * z) + 1.0f, 0.0f, x2 * plane.distance, y2 * plane.distance, z2 * plane.distance, 1.0f);
}
// static
Matrix Matrix::makeLookAtLH(const Vector3& position, const Vector3& lookAt, const Vector3& up)
{
Vector3 xaxis, yaxis, zaxis;
// 注視点からカメラ位置までのベクトルをZ軸とする
zaxis = lookAt;
zaxis -= position;
zaxis.mutatingNormalize();
// Z軸と上方向のベクトルの外積をとるとX軸が分かる
xaxis = Vector3::cross(up, zaxis);
xaxis.mutatingNormalize();
// 2つの軸がわかったので、その2つの外積は残りの軸(Y軸)になる
yaxis = Vector3::cross(zaxis, xaxis);
return Matrix(
xaxis.x, yaxis.x, zaxis.x, 0.0f,
xaxis.y, yaxis.y, zaxis.y, 0.0f,
xaxis.z, yaxis.z, zaxis.z, 0.0f,
-(xaxis.x * position.x + xaxis.y * position.y + xaxis.z * position.z),
-(yaxis.x * position.x + yaxis.y * position.y + yaxis.z * position.z),
-(zaxis.x * position.x + zaxis.y * position.y + zaxis.z * position.z),
1.0f);
}
// static
Matrix Matrix::makeLookAtRH(const Vector3& position, const Vector3& lookAt, const Vector3& up)
{
Vector3 xaxis, yaxis, zaxis;
// 注視点からカメラ位置までのベクトルをZ軸とする
zaxis = position;
zaxis -= lookAt;
zaxis.mutatingNormalize();
// Z軸と上方向のベクトルの外積をとるとX軸が分かる
xaxis = Vector3::cross(up, zaxis);
xaxis.mutatingNormalize();
// 2つの軸がわかったので、その2つの外積は残りの軸(Y軸)になる
yaxis = Vector3::cross(zaxis, xaxis);
return Matrix(
xaxis.x, yaxis.x, zaxis.x, 0.0f,
xaxis.y, yaxis.y, zaxis.y, 0.0f,
xaxis.z, yaxis.z, zaxis.z, 0.0f,
-(xaxis.x * position.x + xaxis.y * position.y + xaxis.z * position.z),
-(yaxis.x * position.x + yaxis.y * position.y + yaxis.z * position.z),
-(zaxis.x * position.x + zaxis.y * position.y + zaxis.z * position.z),
1.0f);
}
// static
Matrix Matrix::makePerspectiveFovLH(float fovY, float aspect, float nearZ, float farZ)
{
float h = 1.f / tanf(fovY * 0.5f); // cot(fovY/2)
return Matrix(
h / aspect, 0.0f, 0.0f, 0.0f,
0.0f, h, 0.0f, 0.0f,
0.0f, 0.0f, farZ / (farZ - nearZ), 1.0f,
0.0f, 0.0f, (-nearZ * farZ) / (farZ - nearZ), 0.0f);
}
// static
Matrix Matrix::makePerspectiveFovRH(float fovY, float aspect, float nearZ, float farZ)
{
float h = 1.f / tanf(fovY * 0.5f); // cot(fovY/2)
return Matrix(
h / aspect, 0.0f, 0.0f, 0.0f,
0.0f, h, 0.0f, 0.0f,
0.0f, 0.0f, farZ / (nearZ - farZ), -1.0f,
0.0f, 0.0f, (nearZ * farZ) / (nearZ - farZ), 0.0f);
}
// static
Matrix Matrix::makeOrthoLH(float width, float height, float nearZ, float farZ)
{
return Matrix(
2.0f / width, 0.0f, 0.0f, 0.0f,
0.0f, 2.0f / height, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f / (farZ - nearZ),
0.0f, 0.0f, 0.0f, -nearZ / (nearZ - farZ), 1.0f);
}
// static
Matrix Matrix::makeOrthoRH(float width, float height, float nearZ, float farZ)
{
return Matrix(
2.0f / width, 0.0f, 0.0f, 0.0f,
0.0f, 2.0f / height, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f / (nearZ - farZ), 0.0f,
0.0f, 0.0f, nearZ / (nearZ - farZ), 1.0f);
}
// static
Matrix Matrix::makePerspective2DLH(float width, float height, float nearZ, float farZ)
{
return Matrix(
2.0f / width, 0.0f, 0.0f, 0.0f,
0.0f, -2.0f / height, 0.0f, 0.0f,
0.0f, 0.0f, -1.0f / (farZ - nearZ), 0.0f,
-1.0f, 1.0f, -nearZ / (nearZ - farZ) + 1.0f, 1.0f);
}
// static
Matrix Matrix::makePerspective2DRH(float width, float height, float nearZ, float farZ)
{
return Matrix(
-2.0f / width,0.0f, 0.0f, 0.0f,
0.0f, -2.0f / height, 0.0f, 0.0f,
0.0f, 0.0f, -1.0f / (nearZ - farZ), 0.0f,
-1.0f, 1.0f, nearZ / (nearZ - farZ)/* + 1.0f*/, 1.0f);
}
// static
Matrix Matrix::makeAffineTransformation(const Vector3& scaling, const Vector3& rotationCenter, const Quaternion& rotation, const Vector3& translation)
{
Matrix m = Matrix::makeScaling(scaling);
m.translate(-rotationCenter);
m.rotateQuaternion(rotation);
m.translate(rotationCenter);
m.translate(translation);
return m;
}
Matrix Matrix::extractRotation(const Matrix& mat)
{
Matrix result;
auto& d = result.m;
const auto& s = mat.m;
float scaleX = 1.0f / Vector3(s[0][0], s[1][0], s[2][0]).length();
float scaleY = 1.0f / Vector3(s[0][1], s[1][1], s[2][1]).length();
float scaleZ = 1.0f / Vector3(s[0][2], s[1][2], s[2][2]).length();
d[0][0] = s[0][0] * scaleX;
d[1][0] = s[1][0] * scaleX;
d[2][0] = s[2][0] * scaleX;
d[0][1] = s[0][1] * scaleY;
d[1][1] = s[1][1] * scaleY;
d[2][1] = s[2][1] * scaleY;
d[0][2] = s[0][2] * scaleZ;
d[1][2] = s[1][2] * scaleZ;
d[2][2] = s[2][2] * scaleZ;
return result;
}
// Note: inverse(lookAtLH) と同じ結果 (誤差はあるけど)
Matrix Matrix::makeAffineLookAtLH(const Vector3& eye, const Vector3& target, const Vector3& up)
{
if (target == eye) return Matrix::Identity;
// left-hand coord
Vector3 f = Vector3::normalize(target - eye);
Vector3 s = Vector3::cross(up, f);
if (Vector3::nearEqual(s, Vector3::Zero))
{
if (Math::nearEqual(std::abs(up.z), 1.0f)) {
f.x += 0.0001f;
}
else {
f.z += 0.0001f;
}
f.mutatingNormalize();
s = Vector3::cross(up, f);
}
s.mutatingNormalize();
Vector3 u = Vector3::cross(f, s);
return Matrix(
s.x, s.y, s.z, 0.0f,
u.x, u.y, u.z, 0.0f,
f.x, f.y, f.z, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f);
}
Matrix& Matrix::operator*=(const Matrix& matrix)
{
float mx0 = m[0][0];
float mx1 = m[0][1];
float mx2 = m[0][2];
m[0][0] = mx0 * matrix.m[0][0] + mx1 * matrix.m[1][0] + mx2 * matrix.m[2][0] + m[0][3] * matrix.m[3][0];
m[0][1] = mx0 * matrix.m[0][1] + mx1 * matrix.m[1][1] + mx2 * matrix.m[2][1] + m[0][3] * matrix.m[3][1];
m[0][2] = mx0 * matrix.m[0][2] + mx1 * matrix.m[1][2] + mx2 * matrix.m[2][2] + m[0][3] * matrix.m[3][2];
m[0][3] = mx0 * matrix.m[0][3] + mx1 * matrix.m[1][3] + mx2 * matrix.m[2][3] + m[0][3] * matrix.m[3][3];
mx0 = m[1][0];
mx1 = m[1][1];
mx2 = m[1][2];
m[1][0] = mx0 * matrix.m[0][0] + mx1 * matrix.m[1][0] + mx2 * matrix.m[2][0] + m[1][3] * matrix.m[3][0];
m[1][1] = mx0 * matrix.m[0][1] + mx1 * matrix.m[1][1] + mx2 * matrix.m[2][1] + m[1][3] * matrix.m[3][1];
m[1][2] = mx0 * matrix.m[0][2] + mx1 * matrix.m[1][2] + mx2 * matrix.m[2][2] + m[1][3] * matrix.m[3][2];
m[1][3] = mx0 * matrix.m[0][3] + mx1 * matrix.m[1][3] + mx2 * matrix.m[2][3] + m[1][3] * matrix.m[3][3];
mx0 = m[2][0];
mx1 = m[2][1];
mx2 = m[2][2];
m[2][0] = mx0 * matrix.m[0][0] + mx1 * matrix.m[1][0] + mx2 * matrix.m[2][0] + m[2][3] * matrix.m[3][0];
m[2][1] = mx0 * matrix.m[0][1] + mx1 * matrix.m[1][1] + mx2 * matrix.m[2][1] + m[2][3] * matrix.m[3][1];
m[2][2] = mx0 * matrix.m[0][2] + mx1 * matrix.m[1][2] + mx2 * matrix.m[2][2] + m[2][3] * matrix.m[3][2];
m[2][3] = mx0 * matrix.m[0][3] + mx1 * matrix.m[1][3] + mx2 * matrix.m[2][3] + m[2][3] * matrix.m[3][3];
mx0 = m[3][0];
mx1 = m[3][1];
mx2 = m[3][2];
m[3][0] = mx0 * matrix.m[0][0] + mx1 * matrix.m[1][0] + mx2 * matrix.m[2][0] + m[3][3] * matrix.m[3][0];
m[3][1] = mx0 * matrix.m[0][1] + mx1 * matrix.m[1][1] + mx2 * matrix.m[2][1] + m[3][3] * matrix.m[3][1];
m[3][2] = mx0 * matrix.m[0][2] + mx1 * matrix.m[1][2] + mx2 * matrix.m[2][2] + m[3][3] * matrix.m[3][2];
m[3][3] = mx0 * matrix.m[0][3] + mx1 * matrix.m[1][3] + mx2 * matrix.m[2][3] + m[3][3] * matrix.m[3][3];
return (*this);
}
Matrix operator*(const Matrix& mat1, const Matrix& mat2)
{
return Matrix::multiply(mat1, mat2);
}
Matrix operator*(const Matrix& mat1, float v)
{
return Matrix(
mat1.m[0][0] * v, mat1.m[0][1] * v, mat1.m[0][2] * v, mat1.m[0][3] * v, mat1.m[1][0] * v, mat1.m[1][1] * v, mat1.m[1][2] * v, mat1.m[1][3] * v, mat1.m[2][0] * v, mat1.m[2][1] * v, mat1.m[2][2] * v, mat1.m[2][3] * v, mat1.m[3][0] * v, mat1.m[3][1] * v, mat1.m[3][2] * v, mat1.m[3][3] * v);
}
static bool equals(const Matrix& value1, const Matrix& value2)
{
return (
value1.m11 == value2.m11 && value1.m12 == value2.m12 && value1.m13 == value2.m13 && value1.m14 == value2.m14 &&
value1.m21 == value2.m21 && value1.m22 == value2.m22 && value1.m23 == value2.m23 && value1.m24 == value2.m24 &&
value1.m31 == value2.m31 && value1.m32 == value2.m32 && value1.m33 == value2.m33 && value1.m34 == value2.m34 &&
value1.m41 == value2.m41 && value1.m42 == value2.m42 && value1.m43 == value2.m43 && value1.m44 == value2.m44);
}
bool Matrix::operator==(const Matrix& mat) const
{
return equals(*this, mat);
}
bool Matrix::operator!=(const Matrix& mat) const
{
return !equals(*this, mat);
}
} // namespace ln
| 30.575635 | 368 | 0.465548 | GameDevery |
3862f1bf18c94812188ef2a7aabf38130014edd7 | 9,408 | cc | C++ | test/test_psend_precv.cc | mpi-advance/Exhanced-MPL-tiny- | 9585fdc337a69c207a7c771d850b5ad7542666fa | [
"BSD-3-Clause"
] | 2 | 2021-10-13T03:55:48.000Z | 2022-01-28T15:33:54.000Z | test/test_psend_precv.cc | mpi-advance/mpl-subset | 9585fdc337a69c207a7c771d850b5ad7542666fa | [
"BSD-3-Clause"
] | null | null | null | test/test_psend_precv.cc | mpi-advance/mpl-subset | 9585fdc337a69c207a7c771d850b5ad7542666fa | [
"BSD-3-Clause"
] | null | null | null | #define BOOST_TEST_MODULE psend_precv
#include <boost/test/included/unit_test.hpp>
#include <limits>
#include <cstddef>
#include <complex>
#include <mpl/mpl.hpp>
template<typename T>
bool psend_precv_test(const T &data) {
const mpl::communicator &comm_world = mpl::environment::comm_world();
if (comm_world.size() < 2)
return false;
if (comm_world.rank() == 0) {
auto r{comm_world.send_init(data, 1)};
r.start();
r.wait();
}
if (comm_world.rank() == 1) {
T data_r;
auto r{comm_world.recv_init(data_r, 0)};
r.start();
while (not r.test().first) {
}
return data_r == data;
}
return true;
}
template<typename T>
bool pbsend_precv_test(const T &data) {
const mpl::communicator &comm_world = mpl::environment::comm_world();
if (comm_world.size() < 2)
return false;
if (comm_world.rank() == 0) {
const int size{comm_world.bsend_size<T>()};
mpl::bsend_buffer<> buff(size);
auto r{comm_world.bsend_init(data, 1)};
r.start();
r.wait();
}
if (comm_world.rank() == 1) {
T data_r;
auto r{comm_world.recv_init(data_r, 0)};
r.start();
while (not r.test().first) {
}
return data_r == data;
}
return true;
}
template<typename T>
bool pssend_precv_test(const T &data) {
const mpl::communicator &comm_world = mpl::environment::comm_world();
if (comm_world.size() < 2)
return false;
if (comm_world.rank() == 0) {
auto r{comm_world.ssend_init(data, 1)};
r.start();
r.wait();
}
if (comm_world.rank() == 1) {
T data_r;
auto r{comm_world.recv_init(data_r, 0)};
r.start();
while (not r.test().first) {
}
return data_r == data;
}
return true;
}
template<typename T>
bool prsend_precv_test(const T &data) {
const mpl::communicator &comm_world = mpl::environment::comm_world();
if (comm_world.size() < 2)
return false;
if (comm_world.rank() == 0) {
comm_world.barrier();
auto r{comm_world.rsend_init(data, 1)};
r.start();
r.wait();
} else if (comm_world.rank() == 1) {
T data_r;
auto r{comm_world.recv_init(data_r, 0)};
r.start();
comm_world.barrier();
while (not r.test().first) {
}
return data_r == data;
} else
comm_world.barrier();
return true;
}
BOOST_AUTO_TEST_CASE(psend_precv) {
// integer types
BOOST_TEST(psend_precv_test(std::byte(77)));
BOOST_TEST(psend_precv_test(std::numeric_limits<char>::max() - 1));
BOOST_TEST(psend_precv_test(std::numeric_limits<signed char>::max() - 1));
BOOST_TEST(psend_precv_test(std::numeric_limits<unsigned char>::max() - 1));
BOOST_TEST(psend_precv_test(std::numeric_limits<signed short>::max() - 1));
BOOST_TEST(psend_precv_test(std::numeric_limits<unsigned short>::max() - 1));
BOOST_TEST(psend_precv_test(std::numeric_limits<signed int>::max() - 1));
BOOST_TEST(psend_precv_test(std::numeric_limits<unsigned int>::max() - 1));
BOOST_TEST(psend_precv_test(std::numeric_limits<signed long>::max() - 1));
BOOST_TEST(psend_precv_test(std::numeric_limits<unsigned long>::max() - 1));
BOOST_TEST(psend_precv_test(std::numeric_limits<signed long long>::max() - 1));
BOOST_TEST(psend_precv_test(std::numeric_limits<unsigned long long>::max() - 1));
// character types
BOOST_TEST(psend_precv_test(static_cast<wchar_t>('A')));
BOOST_TEST(psend_precv_test(static_cast<char16_t>('A')));
BOOST_TEST(psend_precv_test(static_cast<char32_t>('A')));
// floating point number types
BOOST_TEST(psend_precv_test(static_cast<float>(3.14)));
BOOST_TEST(psend_precv_test(static_cast<double>(3.14)));
BOOST_TEST(psend_precv_test(static_cast<long double>(3.14)));
BOOST_TEST(psend_precv_test(std::complex<float>(3.14, 2.72)));
BOOST_TEST(psend_precv_test(std::complex<double>(3.14, 2.72)));
BOOST_TEST(psend_precv_test(std::complex<long double>(3.14, 2.72)));
// logical type
BOOST_TEST(psend_precv_test(true));
// enums
enum class my_enum : int { val = std::numeric_limits<int>::max() - 1 };
BOOST_TEST(psend_precv_test(my_enum::val));
}
BOOST_AUTO_TEST_CASE(pbsend_precv) {
// integer types
BOOST_TEST(pbsend_precv_test(std::byte(77)));
BOOST_TEST(pbsend_precv_test(std::numeric_limits<char>::max() - 1));
BOOST_TEST(pbsend_precv_test(std::numeric_limits<signed char>::max() - 1));
BOOST_TEST(pbsend_precv_test(std::numeric_limits<unsigned char>::max() - 1));
BOOST_TEST(pbsend_precv_test(std::numeric_limits<signed short>::max() - 1));
BOOST_TEST(pbsend_precv_test(std::numeric_limits<unsigned short>::max() - 1));
BOOST_TEST(pbsend_precv_test(std::numeric_limits<signed int>::max() - 1));
BOOST_TEST(pbsend_precv_test(std::numeric_limits<unsigned int>::max() - 1));
BOOST_TEST(pbsend_precv_test(std::numeric_limits<signed long>::max() - 1));
BOOST_TEST(pbsend_precv_test(std::numeric_limits<unsigned long>::max() - 1));
BOOST_TEST(pbsend_precv_test(std::numeric_limits<signed long long>::max() - 1));
BOOST_TEST(pbsend_precv_test(std::numeric_limits<unsigned long long>::max() - 1));
// character types
BOOST_TEST(pbsend_precv_test(static_cast<wchar_t>('A')));
BOOST_TEST(pbsend_precv_test(static_cast<char16_t>('A')));
BOOST_TEST(pbsend_precv_test(static_cast<char32_t>('A')));
// floating point number types
BOOST_TEST(pbsend_precv_test(static_cast<float>(3.14)));
BOOST_TEST(pbsend_precv_test(static_cast<double>(3.14)));
BOOST_TEST(pbsend_precv_test(static_cast<long double>(3.14)));
BOOST_TEST(pbsend_precv_test(std::complex<float>(3.14, 2.72)));
BOOST_TEST(pbsend_precv_test(std::complex<double>(3.14, 2.72)));
BOOST_TEST(pbsend_precv_test(std::complex<long double>(3.14, 2.72)));
// logical type
BOOST_TEST(pbsend_precv_test(true));
// enums
enum class my_enum : int { val = std::numeric_limits<int>::max() - 1 };
BOOST_TEST(pbsend_precv_test(my_enum::val));
}
BOOST_AUTO_TEST_CASE(pssend_precv) {
// integer types
BOOST_TEST(pssend_precv_test(std::byte(77)));
BOOST_TEST(pssend_precv_test(std::numeric_limits<char>::max() - 1));
BOOST_TEST(pssend_precv_test(std::numeric_limits<signed char>::max() - 1));
BOOST_TEST(pssend_precv_test(std::numeric_limits<unsigned char>::max() - 1));
BOOST_TEST(pssend_precv_test(std::numeric_limits<signed short>::max() - 1));
BOOST_TEST(pssend_precv_test(std::numeric_limits<unsigned short>::max() - 1));
BOOST_TEST(pssend_precv_test(std::numeric_limits<signed int>::max() - 1));
BOOST_TEST(pssend_precv_test(std::numeric_limits<unsigned int>::max() - 1));
BOOST_TEST(pssend_precv_test(std::numeric_limits<signed long>::max() - 1));
BOOST_TEST(pssend_precv_test(std::numeric_limits<unsigned long>::max() - 1));
BOOST_TEST(pssend_precv_test(std::numeric_limits<signed long long>::max() - 1));
BOOST_TEST(pssend_precv_test(std::numeric_limits<unsigned long long>::max() - 1));
// character types
BOOST_TEST(pssend_precv_test(static_cast<wchar_t>('A')));
BOOST_TEST(pssend_precv_test(static_cast<char16_t>('A')));
BOOST_TEST(pssend_precv_test(static_cast<char32_t>('A')));
// floating point number types
BOOST_TEST(pssend_precv_test(static_cast<float>(3.14)));
BOOST_TEST(pssend_precv_test(static_cast<double>(3.14)));
BOOST_TEST(pssend_precv_test(static_cast<long double>(3.14)));
BOOST_TEST(pssend_precv_test(std::complex<float>(3.14, 2.72)));
BOOST_TEST(pssend_precv_test(std::complex<double>(3.14, 2.72)));
BOOST_TEST(pssend_precv_test(std::complex<long double>(3.14, 2.72)));
// logical type
BOOST_TEST(pssend_precv_test(true));
// enums
enum class my_enum : int { val = std::numeric_limits<int>::max() - 1 };
BOOST_TEST(pssend_precv_test(my_enum::val));
}
BOOST_AUTO_TEST_CASE(prsend_precv) {
// integer types
BOOST_TEST(prsend_precv_test(std::byte(77)));
BOOST_TEST(prsend_precv_test(std::numeric_limits<char>::max() - 1));
BOOST_TEST(prsend_precv_test(std::numeric_limits<signed char>::max() - 1));
BOOST_TEST(prsend_precv_test(std::numeric_limits<unsigned char>::max() - 1));
BOOST_TEST(prsend_precv_test(std::numeric_limits<signed short>::max() - 1));
BOOST_TEST(prsend_precv_test(std::numeric_limits<unsigned short>::max() - 1));
BOOST_TEST(prsend_precv_test(std::numeric_limits<signed int>::max() - 1));
BOOST_TEST(prsend_precv_test(std::numeric_limits<unsigned int>::max() - 1));
BOOST_TEST(prsend_precv_test(std::numeric_limits<signed long>::max() - 1));
BOOST_TEST(prsend_precv_test(std::numeric_limits<unsigned long>::max() - 1));
BOOST_TEST(prsend_precv_test(std::numeric_limits<signed long long>::max() - 1));
BOOST_TEST(prsend_precv_test(std::numeric_limits<unsigned long long>::max() - 1));
// character types
BOOST_TEST(prsend_precv_test(static_cast<wchar_t>('A')));
BOOST_TEST(prsend_precv_test(static_cast<char16_t>('A')));
BOOST_TEST(prsend_precv_test(static_cast<char32_t>('A')));
// floating point number types
BOOST_TEST(prsend_precv_test(static_cast<float>(3.14)));
BOOST_TEST(prsend_precv_test(static_cast<double>(3.14)));
BOOST_TEST(prsend_precv_test(static_cast<long double>(3.14)));
BOOST_TEST(prsend_precv_test(std::complex<float>(3.14, 2.72)));
BOOST_TEST(prsend_precv_test(std::complex<double>(3.14, 2.72)));
BOOST_TEST(prsend_precv_test(std::complex<long double>(3.14, 2.72)));
// logical type
BOOST_TEST(prsend_precv_test(true));
// enums
enum class my_enum : int { val = std::numeric_limits<int>::max() - 1 };
BOOST_TEST(prsend_precv_test(my_enum::val));
}
| 41.813333 | 84 | 0.713861 | mpi-advance |
386658bfe8227e7876d887bdf5eec76f45a745ca | 742 | cc | C++ | src/lingx/core/path.cc | chrisxjzhu/lingx | 703d3b1b71b96ee87a8db0fdb37c786da0e299dd | [
"MIT"
] | null | null | null | src/lingx/core/path.cc | chrisxjzhu/lingx | 703d3b1b71b96ee87a8db0fdb37c786da0e299dd | [
"MIT"
] | null | null | null | src/lingx/core/path.cc | chrisxjzhu/lingx | 703d3b1b71b96ee87a8db0fdb37c786da0e299dd | [
"MIT"
] | 1 | 2021-05-21T10:04:07.000Z | 2021-05-21T10:04:07.000Z | #include <lingx/core/path.h>
namespace lnx {
Path Path::parent_path() const
{
std::string path = path_;
size_t pos = path_.rfind(Separator);
if (pos == std::string::npos)
return Path("");
while (pos != 0 && path_[pos] == Separator)
--pos;
return Path(path_.substr(0, pos + 1));
}
void Path::Tail_separator(std::string& path)
{
if (!path.empty() && path.back() != Separator)
path += Separator;
}
std::string Path::Get_full_name(const std::string& prefix,
const std::string& name)
{
if (name.c_str()[0] == Separator)
return name;
std::string fullname = prefix;
Tail_separator(fullname);
fullname += name;
return fullname;
}
}
| 19.025641 | 58 | 0.576819 | chrisxjzhu |
38685c15ac073f376d10a12e9c1ded8f7eaf85dd | 1,395 | cpp | C++ | backtracking/knight_tour.cpp | kashyap99saksham/Code | 96658d0920eb79c007701d2a3cc9dbf453d78f96 | [
"MIT"
] | 16 | 2020-06-02T19:22:45.000Z | 2022-02-05T10:35:28.000Z | backtracking/knight_tour.cpp | codezoned/Code | de91ffc7ef06812a31464fb40358e2436734574c | [
"MIT"
] | null | null | null | backtracking/knight_tour.cpp | codezoned/Code | de91ffc7ef06812a31464fb40358e2436734574c | [
"MIT"
] | 2 | 2020-08-27T17:40:06.000Z | 2022-02-05T10:33:52.000Z | #include <bits/stdc++.h>
using namespace std;
#define N 8
int isSafe(int x, int y, int sol[N][N]){
return (x >= 0 && x < N && y >= 0 && y < N && sol[x][y] == -1);
}
void printSolution(int sol[N][N]){
for(int x = 0; x < N; x++){
for (int y = 0; y < N; y++)
cout<<sol[x][y]<<" ";
cout<< endl;
}
}
int solveKT(int x, int y, int movei,int sol[N][N], int xMove[N],int yMove[N]){
int k, next_x, next_y;
if (movei == N*N)
return 1;
// Try all next moves from the current coordinate x, y
for (k = 0; k < 8; k++)
{
next_x = x + xMove[k];
next_y = y + yMove[k];
if (isSafe(next_x, next_y, sol)){
sol[next_x][next_y] = movei;
if (solveKT(next_x, next_y,movei + 1, sol,xMove, yMove) == 1)
return 1;
else sol[next_x][next_y] = -1; // backtrack
}
}
return 0;
}
int main(){
int sol[N][N];
memset(sol, -1, sizeof(sol));
// xMove[] and yMove[] define next move of Knight
// xMove[] is for next value of x coordinate
// yMove[] is for next value of y coordinate */
int xMove[8] = { 2, 1, -1, -2, -2, -1, 1, 2 };
int yMove[8] = { 1, 2, 2, 1, -1, -2, -2, -1 };
// Since the Knight is initially at the first block
sol[0][0] = 0;
// Start from 0,0 and explore all tours using solveKT
if (solveKT(0, 0, 1, sol, xMove, yMove) == 0){ // <x, y, move number, output, xmoves, ymoves>
cout << "Solution does not exist";
}
else printSolution(sol);
}
| 22.5 | 95 | 0.566308 | kashyap99saksham |
386e5c3806e7291df6367a1e3b47f4353e6aa0e2 | 408 | cpp | C++ | cpp/src/dp/util/error.cpp | robotalks/think | a734a6496b796e4e4435cc9214e6ede9847dc3c3 | [
"MIT"
] | null | null | null | cpp/src/dp/util/error.cpp | robotalks/think | a734a6496b796e4e4435cc9214e6ede9847dc3c3 | [
"MIT"
] | null | null | null | cpp/src/dp/util/error.cpp | robotalks/think | a734a6496b796e4e4435cc9214e6ede9847dc3c3 | [
"MIT"
] | null | null | null | #include <unistd.h>
#include <errno.h>
#include <cstring>
#include "dp/util/error.h"
namespace dp {
using namespace std;
string _error_msg_at(const char* fn, int line, const string& prefix) {
char loc[32], buf[32];
sprintf(loc, ":%d: ", line);
sprintf(buf, ": (%d) ", errno);
return string(fn) + string(loc) + prefix + string(buf) + string(strerror(errno));
}
}
| 25.5 | 89 | 0.598039 | robotalks |
386f282e2d117fda6f6fa0f7193db7d3459fe6c8 | 13,700 | cpp | C++ | Source/Core/GL/GLExtensions.cpp | nathanlink169/3D-Shaders-Test | 2493fb71664d75100fbb4a80ac70f657a189593d | [
"MIT"
] | null | null | null | Source/Core/GL/GLExtensions.cpp | nathanlink169/3D-Shaders-Test | 2493fb71664d75100fbb4a80ac70f657a189593d | [
"MIT"
] | null | null | null | Source/Core/GL/GLExtensions.cpp | nathanlink169/3D-Shaders-Test | 2493fb71664d75100fbb4a80ac70f657a189593d | [
"MIT"
] | null | null | null | #include "CommonHeader.h"
#pragma warning(push)
#pragma warning(disable:4191) // unsafe conversion from 'type of expression' to 'type required'
PFNGLUNIFORM1FPROC glUniform1f = 0;
PFNGLUNIFORM2FPROC glUniform2f = 0;
PFNGLUNIFORM3FPROC glUniform3f = 0;
PFNGLUNIFORM4FPROC glUniform4f = 0;
PFNGLUNIFORM1IPROC glUniform1i = 0;
PFNGLUNIFORM2IPROC glUniform2i = 0;
PFNGLUNIFORM3IPROC glUniform3i = 0;
PFNGLUNIFORM4IPROC glUniform4i = 0;
PFNGLUNIFORM1FVPROC glUniform1fv = 0;
PFNGLUNIFORM2FVPROC glUniform2fv = 0;
PFNGLUNIFORM3FVPROC glUniform3fv = 0;
PFNGLUNIFORM4FVPROC glUniform4fv = 0;
PFNGLUNIFORM1IVPROC glUniform1iv = 0;
PFNGLUNIFORM2IVPROC glUniform2iv = 0;
PFNGLUNIFORM3IVPROC glUniform3iv = 0;
PFNGLUNIFORM4IVPROC glUniform4iv = 0;
PFNGLUNIFORMMATRIX4FVPROC glUniformMatrix4fv = 0;
PFNGLVERTEXATTRIB1FPROC glVertexAttrib1f = 0;
PFNGLVERTEXATTRIB2FPROC glVertexAttrib2f = 0;
PFNGLVERTEXATTRIB3FPROC glVertexAttrib3f = 0;
PFNGLVERTEXATTRIB4FPROC glVertexAttrib4f = 0;
PFNGLVERTEXATTRIB1FVPROC glVertexAttrib1fv = 0;
PFNGLVERTEXATTRIB2FVPROC glVertexAttrib2fv = 0;
PFNGLVERTEXATTRIB3FVPROC glVertexAttrib3fv = 0;
PFNGLVERTEXATTRIB4FVPROC glVertexAttrib4fv = 0;
PFNGLENABLEVERTEXATTRIBARRAYPROC glEnableVertexAttribArray = 0;
PFNGLBINDATTRIBLOCATIONPROC glBindAttribLocation = 0;
PFNGLDISABLEVERTEXATTRIBARRAYPROC glDisableVertexAttribArray = 0;
PFNGLVERTEXATTRIBPOINTERPROC glVertexAttribPointer = 0;
PFNGLCREATESHADERPROC glCreateShader = 0;
PFNGLSHADERSOURCEPROC glShaderSource = 0;
PFNGLCOMPILESHADERPROC glCompileShader = 0;
PFNGLCREATEPROGRAMPROC glCreateProgram = 0;
PFNGLATTACHSHADERPROC glAttachShader = 0;
PFNGLLINKPROGRAMPROC glLinkProgram = 0;
PFNGLDETACHSHADERPROC glDetachShader = 0;
PFNGLDELETEPROGRAMPROC glDeleteProgram = 0;
PFNGLDELETESHADERPROC glDeleteShader = 0;
PFNGLUSEPROGRAMPROC glUseProgram = 0;
PFNGLGETATTRIBLOCATIONPROC glGetAttribLocation = 0;
PFNGLGETPROGRAMINFOLOGPROC glGetProgramInfoLog = 0;
PFNGLGETPROGRAMIVPROC glGetProgramiv = 0;
PFNGLGETSHADERINFOLOGPROC glGetShaderInfoLog = 0;
PFNGLGETSHADERSOURCEPROC glGetShaderSource = 0;
PFNGLGETSHADERIVPROC glGetShaderiv = 0;
PFNGLGETUNIFORMLOCATIONPROC glGetUniformLocation = 0;
PFNGLACTIVETEXTUREPROC glActiveTexture = 0;
PFNGLGENBUFFERSPROC glGenBuffers = 0;
PFNGLBINDBUFFERPROC glBindBuffer = 0;
PFNGLBUFFERDATAPROC glBufferData = 0;
PFNGLBUFFERSUBDATAPROC glBufferSubData = 0;
PFNGLDELETEBUFFERSPROC glDeleteBuffers = 0;
PFNGLBLENDFUNCSEPARATEPROC glBlendFuncSeparate = 0;
PFNGLBLENDCOLORPROC glBlendColor = 0;
PFNGLDELETEFRAMEBUFFERSPROC glDeleteFramebuffers = 0;
PFNGLGENFRAMEBUFFERSPROC glGenFramebuffers = 0;
PFNGLBINDFRAMEBUFFERPROC glBindFramebuffer = 0;
PFNGLFRAMEBUFFERTEXTURE2DPROC glFramebufferTexture2D = 0;
PFNGLCHECKFRAMEBUFFERSTATUSPROC glCheckFramebufferStatus = 0;
PFNGLGENRENDERBUFFERSPROC glGenRenderbuffers = 0;
PFNGLBINDRENDERBUFFERPROC glBindRenderbuffer = 0;
PFNGLFRAMEBUFFERRENDERBUFFERPROC glFramebufferRenderbuffer = 0;
PFNGLRENDERBUFFERSTORAGEPROC glRenderbufferStorage = 0;
PFNGLDELETERENDERBUFFERSPROC glDeleteRenderbuffers = 0;
PFNGLGENVERTEXARRAYSPROC glGenVertexArrays = 0;
PFNGLDELETEVERTEXARRAYSPROC glDeleteVertexArrays = 0;
PFNGLBINDVERTEXARRAYPROC glBindVertexArray = 0;
PFNGLGENERATEMIPMAPPROC glGenerateMipmap = 0;
void OpenGL_InitExtensions()
{
glUniform1i = (PFNGLUNIFORM1IPROC) wglGetProcAddress( "glUniform1i" );
glUniform2i = (PFNGLUNIFORM2IPROC) wglGetProcAddress( "glUniform2i" );
glUniform3i = (PFNGLUNIFORM3IPROC) wglGetProcAddress( "glUniform3i" );
glUniform4i = (PFNGLUNIFORM4IPROC) wglGetProcAddress( "glUniform4i" );
glUniform1iv = (PFNGLUNIFORM1IVPROC) wglGetProcAddress( "glUniform1iv" );
glUniform2iv = (PFNGLUNIFORM2IVPROC) wglGetProcAddress( "glUniform2iv" );
glUniform3iv = (PFNGLUNIFORM3IVPROC) wglGetProcAddress( "glUniform3iv" );
glUniform4iv = (PFNGLUNIFORM4IVPROC) wglGetProcAddress( "glUniform4iv" );
glUniform1f = (PFNGLUNIFORM1FPROC) wglGetProcAddress( "glUniform1f" );
glUniform2f = (PFNGLUNIFORM2FPROC) wglGetProcAddress( "glUniform2f" );
glUniform3f = (PFNGLUNIFORM3FPROC) wglGetProcAddress( "glUniform3f" );
glUniform4f = (PFNGLUNIFORM4FPROC) wglGetProcAddress( "glUniform4f" );
glUniform1fv = (PFNGLUNIFORM1FVPROC) wglGetProcAddress( "glUniform1fv" );
glUniform2fv = (PFNGLUNIFORM2FVPROC) wglGetProcAddress( "glUniform2fv" );
glUniform3fv = (PFNGLUNIFORM3FVPROC) wglGetProcAddress( "glUniform3fv" );
glUniform4fv = (PFNGLUNIFORM4FVPROC) wglGetProcAddress( "glUniform4fv" );
glUniformMatrix4fv = (PFNGLUNIFORMMATRIX4FVPROC) wglGetProcAddress( "glUniformMatrix4fv" );
glVertexAttrib1f = (PFNGLVERTEXATTRIB1FPROC) wglGetProcAddress( "glVertexAttrib1f" );
glVertexAttrib2f = (PFNGLVERTEXATTRIB2FPROC) wglGetProcAddress( "glVertexAttrib2f" );
glVertexAttrib3f = (PFNGLVERTEXATTRIB3FPROC) wglGetProcAddress( "glVertexAttrib3f" );
glVertexAttrib4f = (PFNGLVERTEXATTRIB4FPROC) wglGetProcAddress( "glVertexAttrib4f" );
glVertexAttrib1fv = (PFNGLVERTEXATTRIB1FVPROC) wglGetProcAddress( "glVertexAttrib1fv" );
glVertexAttrib2fv = (PFNGLVERTEXATTRIB2FVPROC) wglGetProcAddress( "glVertexAttrib2fv" );
glVertexAttrib3fv = (PFNGLVERTEXATTRIB3FVPROC) wglGetProcAddress( "glVertexAttrib3fv" );
glVertexAttrib4fv = (PFNGLVERTEXATTRIB4FVPROC) wglGetProcAddress( "glVertexAttrib4fv" );
glEnableVertexAttribArray = (PFNGLENABLEVERTEXATTRIBARRAYPROC) wglGetProcAddress( "glEnableVertexAttribArray" );
glBindAttribLocation = (PFNGLBINDATTRIBLOCATIONPROC) wglGetProcAddress( "glBindAttribLocation" );
glDisableVertexAttribArray = (PFNGLDISABLEVERTEXATTRIBARRAYPROC) wglGetProcAddress( "glDisableVertexAttribArray" );
glVertexAttribPointer = (PFNGLVERTEXATTRIBPOINTERPROC) wglGetProcAddress( "glVertexAttribPointer" );
glCreateShader = (PFNGLCREATESHADERPROC) wglGetProcAddress( "glCreateShader" );
glShaderSource = (PFNGLSHADERSOURCEPROC) wglGetProcAddress( "glShaderSource" );
glCompileShader = (PFNGLCOMPILESHADERPROC) wglGetProcAddress( "glCompileShader" );
glCreateProgram = (PFNGLCREATEPROGRAMPROC) wglGetProcAddress( "glCreateProgram" );
glAttachShader = (PFNGLATTACHSHADERPROC) wglGetProcAddress( "glAttachShader" );
glLinkProgram = (PFNGLLINKPROGRAMPROC) wglGetProcAddress( "glLinkProgram" );
glDetachShader = (PFNGLDETACHSHADERPROC) wglGetProcAddress( "glDetachShader" );
glDeleteShader = (PFNGLDELETESHADERPROC) wglGetProcAddress( "glDeleteShader" );
glDeleteProgram = (PFNGLDELETEPROGRAMPROC) wglGetProcAddress( "glDeleteProgram" );
glUseProgram = (PFNGLUSEPROGRAMPROC) wglGetProcAddress( "glUseProgram" );
glGetAttribLocation = (PFNGLGETATTRIBLOCATIONPROC) wglGetProcAddress( "glGetAttribLocation" );
glGetProgramInfoLog = (PFNGLGETPROGRAMINFOLOGPROC) wglGetProcAddress( "glGetProgramInfoLog" );
glGetProgramiv = (PFNGLGETPROGRAMIVPROC) wglGetProcAddress( "glGetProgramiv" );
glGetShaderInfoLog = (PFNGLGETSHADERINFOLOGPROC) wglGetProcAddress( "glGetShaderInfoLog" );
glGetShaderSource = (PFNGLGETSHADERSOURCEPROC) wglGetProcAddress( "glShaderSource" );
glGetShaderiv = (PFNGLGETSHADERIVPROC) wglGetProcAddress( "glGetShaderiv" );
glGetUniformLocation = (PFNGLGETUNIFORMLOCATIONPROC) wglGetProcAddress( "glGetUniformLocation" );
glActiveTexture = (PFNGLACTIVETEXTUREPROC) wglGetProcAddress( "glActiveTexture" );
glGenBuffers = (PFNGLGENBUFFERSPROC) wglGetProcAddress( "glGenBuffers" );
glBindBuffer = (PFNGLBINDBUFFERPROC) wglGetProcAddress( "glBindBuffer" );
glBufferData = (PFNGLBUFFERDATAPROC) wglGetProcAddress( "glBufferData" );
glBufferSubData = (PFNGLBUFFERSUBDATAPROC) wglGetProcAddress( "glBufferSubData" );
glDeleteBuffers = (PFNGLDELETEBUFFERSPROC) wglGetProcAddress( "glDeleteBuffers" );
glBlendFuncSeparate = (PFNGLBLENDFUNCSEPARATEPROC) wglGetProcAddress( "glBlendFuncSeparate" );
glBlendColor = (PFNGLBLENDCOLORPROC) wglGetProcAddress( "glBlendColor" );
glDeleteFramebuffers = (PFNGLDELETEFRAMEBUFFERSPROC) wglGetProcAddress( "glDeleteFramebuffers" );
if( glDeleteFramebuffers == 0 )
glDeleteFramebuffers = (PFNGLDELETEFRAMEBUFFERSPROC) wglGetProcAddress( "glDeleteFramebuffersEXT" );
glGenFramebuffers = (PFNGLGENFRAMEBUFFERSPROC) wglGetProcAddress( "glGenFramebuffers" );
if( glGenFramebuffers == 0 )
glGenFramebuffers = (PFNGLGENFRAMEBUFFERSPROC) wglGetProcAddress( "glGenFramebuffersEXT" );
glBindFramebuffer = (PFNGLBINDFRAMEBUFFERPROC) wglGetProcAddress( "glBindFramebuffer" );
if( glBindFramebuffer == 0 )
glBindFramebuffer = (PFNGLBINDFRAMEBUFFERPROC) wglGetProcAddress( "glBindFramebufferEXT" );
glFramebufferTexture2D = (PFNGLFRAMEBUFFERTEXTURE2DPROC) wglGetProcAddress( "glFramebufferTexture2D" );
if( glFramebufferTexture2D == 0 )
glFramebufferTexture2D = (PFNGLFRAMEBUFFERTEXTURE2DPROC) wglGetProcAddress( "glFramebufferTexture2DEXT" );
glCheckFramebufferStatus = (PFNGLCHECKFRAMEBUFFERSTATUSPROC) wglGetProcAddress( "glCheckFramebufferStatus" );
if( glCheckFramebufferStatus == 0 )
glCheckFramebufferStatus = (PFNGLCHECKFRAMEBUFFERSTATUSPROC) wglGetProcAddress( "glCheckFramebufferStatusEXT" );
glGenRenderbuffers = (PFNGLGENRENDERBUFFERSPROC) wglGetProcAddress( "glGenRenderbuffers" );
if( glGenRenderbuffers == 0 )
glGenRenderbuffers = (PFNGLGENRENDERBUFFERSPROC) wglGetProcAddress( "glGenRenderbuffersEXT" );
glBindRenderbuffer = (PFNGLBINDRENDERBUFFERPROC) wglGetProcAddress( "glBindRenderbuffer" );
if( glBindRenderbuffer == 0 )
glBindRenderbuffer = (PFNGLBINDRENDERBUFFERPROC) wglGetProcAddress( "glBindRenderbufferEXT" );
glFramebufferRenderbuffer = (PFNGLFRAMEBUFFERRENDERBUFFERPROC) wglGetProcAddress( "glFramebufferRenderbuffer" );
if( glFramebufferRenderbuffer == 0 )
glFramebufferRenderbuffer = (PFNGLFRAMEBUFFERRENDERBUFFERPROC) wglGetProcAddress( "glFramebufferRenderbufferEXT" );
glRenderbufferStorage = (PFNGLRENDERBUFFERSTORAGEPROC) wglGetProcAddress( "glRenderbufferStorage" );
if( glRenderbufferStorage == 0 )
glRenderbufferStorage = (PFNGLRENDERBUFFERSTORAGEPROC) wglGetProcAddress( "glRenderbufferStorageEXT" );
glDeleteRenderbuffers = (PFNGLDELETERENDERBUFFERSPROC) wglGetProcAddress( "glDeleteRenderbuffers" );
if( glDeleteRenderbuffers == 0 )
glDeleteRenderbuffers = (PFNGLDELETERENDERBUFFERSPROC) wglGetProcAddress( "glDeleteRenderbuffersEXT" );
glGenVertexArrays = (PFNGLGENVERTEXARRAYSPROC) wglGetProcAddress( "glGenVertexArrays" );
glDeleteVertexArrays = (PFNGLDELETEVERTEXARRAYSPROC) wglGetProcAddress( "glDeleteVertexArrays" );
glBindVertexArray = (PFNGLBINDVERTEXARRAYPROC) wglGetProcAddress( "glBindVertexArray" );
glGenerateMipmap = (PFNGLGENERATEMIPMAPPROC) wglGetProcAddress( "glGenerateMipmap" );
}
#pragma warning(pop)
| 69.543147 | 128 | 0.641752 | nathanlink169 |
386fbb5ebfeb5c64fc380fef5c0fd62cf9cc7afe | 2,520 | cc | C++ | DomainSymbolicPlanner/smartsoft/src-gen/DomainSymbolicPlanner/CommSymbolicPlannerRequestACE.cc | canonical-robots/DomainModelsRepositories | 68b9286d84837e5feb7b200833b158ab9c2922a4 | [
"BSD-3-Clause"
] | null | null | null | DomainSymbolicPlanner/smartsoft/src-gen/DomainSymbolicPlanner/CommSymbolicPlannerRequestACE.cc | canonical-robots/DomainModelsRepositories | 68b9286d84837e5feb7b200833b158ab9c2922a4 | [
"BSD-3-Clause"
] | 2 | 2020-08-20T14:49:47.000Z | 2020-10-07T16:10:07.000Z | DomainSymbolicPlanner/smartsoft/src-gen/DomainSymbolicPlanner/CommSymbolicPlannerRequestACE.cc | canonical-robots/DomainModelsRepositories | 68b9286d84837e5feb7b200833b158ab9c2922a4 | [
"BSD-3-Clause"
] | 8 | 2018-06-25T08:41:28.000Z | 2020-08-13T10:39:30.000Z | //--------------------------------------------------------------------------
// Code generated by the SmartSoft MDSD Toolchain
// The SmartSoft Toolchain has been developed by:
//
// Service Robotics Research Center
// University of Applied Sciences Ulm
// Prittwitzstr. 10
// 89075 Ulm (Germany)
//
// Information about the SmartSoft MDSD Toolchain is available at:
// www.servicerobotik-ulm.de
//
// Please do not modify this file. It will be re-generated
// running the code generator.
//--------------------------------------------------------------------------
#include "DomainSymbolicPlanner/CommSymbolicPlannerRequestACE.hh"
#include <ace/SString.h>
// serialization operator for element CommSymbolicPlannerRequest
ACE_CDR::Boolean operator<<(ACE_OutputCDR &cdr, const DomainSymbolicPlannerIDL::CommSymbolicPlannerRequest &data)
{
ACE_CDR::Boolean good_bit = true;
// serialize list-element plannertype
good_bit = good_bit && cdr << ACE_CString(data.plannertype.c_str());
// serialize list-element domaindescription
good_bit = good_bit && cdr << ACE_CString(data.domaindescription.c_str());
// serialize list-element factdescription
good_bit = good_bit && cdr << ACE_CString(data.factdescription.c_str());
return good_bit;
}
// de-serialization operator for element CommSymbolicPlannerRequest
ACE_CDR::Boolean operator>>(ACE_InputCDR &cdr, DomainSymbolicPlannerIDL::CommSymbolicPlannerRequest &data)
{
ACE_CDR::Boolean good_bit = true;
// deserialize string-type element plannertype
ACE_CString data_plannertype_str;
good_bit = good_bit && cdr >> data_plannertype_str;
data.plannertype = data_plannertype_str.c_str();
// deserialize string-type element domaindescription
ACE_CString data_domaindescription_str;
good_bit = good_bit && cdr >> data_domaindescription_str;
data.domaindescription = data_domaindescription_str.c_str();
// deserialize string-type element factdescription
ACE_CString data_factdescription_str;
good_bit = good_bit && cdr >> data_factdescription_str;
data.factdescription = data_factdescription_str.c_str();
return good_bit;
}
// serialization operator for CommunicationObject CommSymbolicPlannerRequest
ACE_CDR::Boolean operator<<(ACE_OutputCDR &cdr, const DomainSymbolicPlanner::CommSymbolicPlannerRequest &obj)
{
return cdr << obj.get();
}
// de-serialization operator for CommunicationObject CommSymbolicPlannerRequest
ACE_CDR::Boolean operator>>(ACE_InputCDR &cdr, DomainSymbolicPlanner::CommSymbolicPlannerRequest &obj)
{
return cdr >> obj.set();
}
| 39.375 | 113 | 0.746429 | canonical-robots |
3873f9366bb3c16c9822e7719cbbe25903449864 | 14,817 | cpp | C++ | OpenCLExample/DeviceQuery.cpp | zwakrim/mastethesis | c687e2389dbb81f50066aef881076161aa3079b9 | [
"MIT"
] | null | null | null | OpenCLExample/DeviceQuery.cpp | zwakrim/mastethesis | c687e2389dbb81f50066aef881076161aa3079b9 | [
"MIT"
] | null | null | null | OpenCLExample/DeviceQuery.cpp | zwakrim/mastethesis | c687e2389dbb81f50066aef881076161aa3079b9 | [
"MIT"
] | null | null | null | #include <exception>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#define __CL_ENABLE_EXCEPTIONS
#include <CL/cl.hpp>
const bool DEBUG = false;
using namespace std;
const char *readableStatus(cl_int status);
void showPlatformAndDeviceInfo(const cl::Platform& platform, int platform_id, const cl::Device& device, int device_id)
{
std::string platformName, platformVendor, platformProfile, platformVersion, platformExtensions;
platform.getInfo(CL_PLATFORM_NAME, &platformName);
platform.getInfo(CL_PLATFORM_VENDOR, &platformVendor);
platform.getInfo(CL_PLATFORM_PROFILE, &platformProfile);
platform.getInfo(CL_PLATFORM_VERSION, &platformVersion);
platform.getInfo(CL_PLATFORM_EXTENSIONS, &platformExtensions);
std::cout << "Platform " << platform_id << std::endl;
std::cout << " Name: " << platformName << std::endl;
std::cout << " Vendor: " << platformVendor << std::endl;
std::cout << " Profile: " << platformProfile << std::endl;
std::cout << " Version: " << platformVersion << std::endl;
std::cout << std::endl;
std::string deviceName, openCLCVersion, openCLExtensions;
size_t image2dMaxHeight, image2dMaxWidth;
size_t image3dMaxDepth, image3dMaxHeight, image3dMaxWidth;
size_t maxWorkGroupSize, timerResolution;
cl_ulong maxSize, localMemSize;
cl_uint nativeVectorWidthFloat, clockFrequency;
device.getInfo<std::string>(CL_DEVICE_NAME, &deviceName);
device.getInfo<std::string>(CL_DEVICE_OPENCL_C_VERSION, &openCLCVersion);
device.getInfo<std::string>(CL_DEVICE_EXTENSIONS, &openCLExtensions);
device.getInfo<cl_ulong>(CL_DEVICE_MAX_MEM_ALLOC_SIZE, &maxSize);
//device.getInfo<size_t>(CL_DEVICE_IMAGE2D_MAX_HEIGHT, &image2dMaxHeight);
//device.getInfo<size_t>(CL_DEVICE_IMAGE2D_MAX_WIDTH, &image2dMaxWidth);
//device.getInfo<size_t>(CL_DEVICE_IMAGE3D_MAX_DEPTH, &image3dMaxDepth);
//device.getInfo<size_t>(CL_DEVICE_IMAGE3D_MAX_HEIGHT, &image3dMaxHeight);
//device.getInfo<size_t>(CL_DEVICE_IMAGE3D_MAX_WIDTH, &image3dMaxWidth);
device.getInfo<cl_ulong>(CL_DEVICE_LOCAL_MEM_SIZE, &localMemSize);
device.getInfo<size_t>(CL_DEVICE_MAX_WORK_GROUP_SIZE, &maxWorkGroupSize);
device.getInfo<cl_uint>(CL_DEVICE_NATIVE_VECTOR_WIDTH_FLOAT, &nativeVectorWidthFloat);
device.getInfo<size_t>(CL_DEVICE_PROFILING_TIMER_RESOLUTION, &timerResolution);
device.getInfo<cl_uint>(CL_DEVICE_MAX_CLOCK_FREQUENCY, &clockFrequency);
std::cout << " Device " << device_id << std::endl;
std::cout << " Name : " << deviceName << std::endl;
std::cout << " OpenCL C Version : " << openCLCVersion << std::endl;
//std::cout << " 2D Image limits : "
// << image2dMaxHeight << "x" << image2dMaxWidth << std::endl;
//std::cout << " 3D Image limits : "
// << image3dMaxDepth << "x" << image3dMaxHeight << "x"
// << image2dMaxWidth << std::endl;
std::cout << " Maximum buffer size [MB]: "
<< maxSize/(1024*1024) << std::endl;
std::cout << " Local memory size [KB] : "
<< localMemSize/1024 << std::endl;
std::cout << " Maximum workgroup size : " << maxWorkGroupSize << std::endl;
std::cout << " Native vector width : " << nativeVectorWidthFloat << std::endl;
std::cout << " Timer resolution : " << timerResolution << std::endl;
std::cout << " Clock frequency : " << clockFrequency << std::endl;
std::cout << std::endl;
}
void showDevice(const cl::Device& device, int i)
{
std::string deviceName, openCLCVersion, openCLExtensions;
size_t image2dMaxHeight, image2dMaxWidth;
size_t image3dMaxDepth, image3dMaxHeight, image3dMaxWidth;
size_t maxWorkGroupSize, timerResolution;
cl_ulong maxSize, localMemSize;
cl_uint nbrComputeUnits, nativeVectorWidthFloat, clockFrequency;
device.getInfo<std::string>(CL_DEVICE_NAME, &deviceName);
device.getInfo<cl_uint>(CL_DEVICE_MAX_COMPUTE_UNITS, &nbrComputeUnits);
device.getInfo<std::string>(CL_DEVICE_OPENCL_C_VERSION, &openCLCVersion);
device.getInfo<std::string>(CL_DEVICE_EXTENSIONS, &openCLExtensions);
device.getInfo<cl_ulong>(CL_DEVICE_MAX_MEM_ALLOC_SIZE, &maxSize);
device.getInfo<size_t>(CL_DEVICE_IMAGE2D_MAX_HEIGHT, &image2dMaxHeight);
device.getInfo<size_t>(CL_DEVICE_IMAGE2D_MAX_WIDTH, &image2dMaxWidth);
device.getInfo<size_t>(CL_DEVICE_IMAGE3D_MAX_DEPTH, &image3dMaxDepth);
device.getInfo<size_t>(CL_DEVICE_IMAGE3D_MAX_HEIGHT, &image3dMaxHeight);
device.getInfo<size_t>(CL_DEVICE_IMAGE3D_MAX_WIDTH, &image3dMaxWidth);
device.getInfo<cl_ulong>(CL_DEVICE_LOCAL_MEM_SIZE, &localMemSize);
device.getInfo<size_t>(CL_DEVICE_MAX_WORK_GROUP_SIZE, &maxWorkGroupSize);
device.getInfo<cl_uint>(CL_DEVICE_NATIVE_VECTOR_WIDTH_FLOAT, &nativeVectorWidthFloat);
device.getInfo<size_t>(CL_DEVICE_PROFILING_TIMER_RESOLUTION, &timerResolution);
device.getInfo<cl_uint>(CL_DEVICE_MAX_CLOCK_FREQUENCY, &clockFrequency);
std::cout << " Device: " << i << std::endl;
std::cout << " Name : " << deviceName << std::endl;
std::cout << " OpenCL C Version : " << openCLCVersion << std::endl;
std::cout << " #Compute Units (cores) : " << nbrComputeUnits << std::endl;
std::cout << " Native vector width : " << nativeVectorWidthFloat << std::endl;
std::cout << " 2D Image limits : " << image2dMaxHeight << "x" << image2dMaxWidth << std::endl;
std::cout << " 3D Image limits : " << image3dMaxDepth << "x" << image3dMaxHeight << "x" << image2dMaxWidth << std::endl;
std::cout << " Maximum buffer size [MB]: " << maxSize / (1024 * 1024) << std::endl;
std::cout << " Local memory size [KB] : " << localMemSize / 1024 << std::endl;
std::cout << " Maximum workgroup size : " << maxWorkGroupSize << std::endl;
std::cout << " Timer resolution : " << timerResolution << std::endl;
std::cout << " Clock frequency : " << clockFrequency << std::endl;
std::cout << std::endl;
}
void showPlatform(const cl::Platform& platform, int i)
{
std::string platformName, platformVendor, platformProfile, platformVersion, platformExtensions;
platform.getInfo(CL_PLATFORM_NAME, &platformName);
platform.getInfo(CL_PLATFORM_VENDOR, &platformVendor);
platform.getInfo(CL_PLATFORM_PROFILE, &platformProfile);
platform.getInfo(CL_PLATFORM_VERSION, &platformVersion);
platform.getInfo(CL_PLATFORM_EXTENSIONS, &platformExtensions);
std::cout << "Platform " << i << std::endl;
std::cout << " Name: " << platformName << std::endl;
std::cout << " Vendor: " << platformVendor << std::endl;
std::cout << " Profile: " << platformProfile << std::endl;
std::cout << " Version: " << platformVersion << std::endl;
std::cout << std::endl;
std::vector<cl::Device> devices;
platform.getDevices(CL_DEVICE_TYPE_ALL, &devices);
for (int i = 0; i < devices.size(); ++i) {
showDevice(devices[i], i);
}
}
void showAllOpenCLDevices()
{
try {
std::vector<cl::Platform> platforms;
std::vector<cl::Device> devices;
cl::Platform::get(&platforms);
for (int i = 0; i < platforms.size(); ++i) {
showPlatform(platforms[i], i);
}
}
catch (cl::Error &e) {
std::cerr << e.what() << ":" << readableStatus(e.err());
return;
}
catch (std::exception& e) {
std::cerr << e.what();
return;
}
catch (...) {
std::cerr << "Unforeseen error";
return;
}
//cout << endl << "Press ENTER to close window...";
//char c = cin.get();
}
void showAllGPUs() {
try {
std::vector<cl::Platform> platforms;
std::vector<cl::Device> devices;
cl::Platform::get(&platforms);
for (int i = 0; i < platforms.size(); ++i) {
cl::Platform platform = platforms[i];
std::string platformName, platformVendor;
platform.getInfo(CL_PLATFORM_NAME, &platformName);
platform.getInfo(CL_PLATFORM_VENDOR, &platformVendor);
std::vector<cl::Device> devices;
platform.getDevices(CL_DEVICE_TYPE_GPU, &devices);
for (int j = 0; j < devices.size(); ++j) {
cl::Device device = devices[j];
std::string deviceName, openCLCVersion, openCLExtensions;
size_t maxWorkGroupSize, timerResolution;
cl_ulong maxSize, localMemSize;
cl_uint nativeVectorWidthFloat, clockFrequency, nbrComputeUnits;
device.getInfo<std::string>(CL_DEVICE_NAME, &deviceName);
device.getInfo<std::string>(CL_DEVICE_OPENCL_C_VERSION, &openCLCVersion);
device.getInfo<std::string>(CL_DEVICE_EXTENSIONS, &openCLExtensions);
device.getInfo<cl_ulong>(CL_DEVICE_MAX_MEM_ALLOC_SIZE, &maxSize);
device.getInfo<cl_uint>(CL_DEVICE_MAX_COMPUTE_UNITS, &nbrComputeUnits);
device.getInfo<size_t>(CL_DEVICE_MAX_WORK_GROUP_SIZE, &maxWorkGroupSize);
device.getInfo<cl_uint>(CL_DEVICE_NATIVE_VECTOR_WIDTH_FLOAT, &nativeVectorWidthFloat);
device.getInfo<size_t>(CL_DEVICE_PROFILING_TIMER_RESOLUTION, &timerResolution);
device.getInfo<cl_uint>(CL_DEVICE_MAX_CLOCK_FREQUENCY, &clockFrequency);
std::cout << " - " << deviceName << " on " << platformName<<": " << nbrComputeUnits <<" cores " << clockFrequency <<
"MHz " << " vector width="<< nativeVectorWidthFloat <<std::endl;
//std::cout << " OpenCL C Version :" << openCLCVersion << std::endl;
//std::cout << " Maximum workgroup size :" << maxWorkGroupSize << std::endl;
//std::cout << " Native vector width :" << nativeVectorWidthFloat << std::endl;
//std::cout << " Timer resolution :" << timerResolution << std::endl;
//std::cout << " Clock frequency :" << clockFrequency << std::endl;
//std::cout << std::endl;
}
}
}
catch (cl::Error &e) {
std::cerr << e.what() << ":" << readableStatus(e.err());
return;
}
catch (std::exception& e) {
std::cerr << e.what();
return;
}
catch (...) {
std::cerr << "Unforeseen error";
return;
}
}
int numberPlatforms() {
std::vector<cl::Platform> platforms;
cl::Platform::get(&platforms);
return platforms.size();
}
int numberDevices(int platformID) {
std::vector<cl::Platform> platforms;
std::vector<cl::Device> devices;
cl::Platform::get(&platforms);
if (platformID >= platforms.size() || platformID < 0)
return 0;
platforms[platformID].getDevices(CL_DEVICE_TYPE_ALL, &devices);
return devices.size();
}
string deviceName(int platformID, int deviceID) {
std::vector<cl::Platform> platforms;
std::vector<cl::Device> devices;
cl::Platform::get(&platforms);
if (platformID >= platforms.size() || platformID < 0)
return string("");
platforms[platformID].getDevices(CL_DEVICE_TYPE_ALL, &devices);
if (deviceID >= devices.size() || deviceID < 0)
return string("");
cl::Device device = devices[deviceID];
std::string deviceName;
device.getInfo<std::string>(CL_DEVICE_NAME, &deviceName);
return deviceName;
}
const char *readableStatus(cl_int status)
{
switch (status) {
case CL_SUCCESS:
return "CL_SUCCESS";
case CL_DEVICE_NOT_FOUND:
return "CL_DEVICE_NOT_FOUND";
case CL_DEVICE_NOT_AVAILABLE:
return "CL_DEVICE_NOT_AVAILABLE";
case CL_COMPILER_NOT_AVAILABLE:
return "CL_COMPILER_NOT_AVAILABLE";
case CL_MEM_OBJECT_ALLOCATION_FAILURE:
return "CL_COMPILER_NOT_AVAILABLE";
case CL_OUT_OF_RESOURCES:
return "CL_OUT_OF_RESOURCES";
case CL_OUT_OF_HOST_MEMORY:
return "CL_OUT_OF_HOST_MEMORY";
case CL_PROFILING_INFO_NOT_AVAILABLE:
return "CL_PROFILING_INFO_NOT_AVAILABLE";
case CL_MEM_COPY_OVERLAP:
return "CL_MEM_COPY_OVERLAP";
case CL_IMAGE_FORMAT_MISMATCH:
return "CL_IMAGE_FORMAT_MISMATCH";
case CL_IMAGE_FORMAT_NOT_SUPPORTED:
return "CL_IMAGE_FORMAT_NOT_SUPPORTED";
case CL_BUILD_PROGRAM_FAILURE:
return "CL_BUILD_PROGRAM_FAILURE";
case CL_MAP_FAILURE:
return "CL_MAP_FAILURE";
#ifndef CL_VERSION_1_0
case CL_MISALIGNED_SUB_BUFFER_OFFSET:
return "CL_MISALIGNED_SUB_BUFFER_OFFSET";
case CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST:
return "CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST";
#endif
case CL_INVALID_VALUE:
return "CL_INVALID_VALUE";
case CL_INVALID_DEVICE_TYPE:
return "CL_INVALID_DEVICE_TYPE";
case CL_INVALID_PLATFORM:
return "CL_INVALID_PLATFORM";
case CL_INVALID_DEVICE:
return "CL_INVALID_DEVICE";
case CL_INVALID_CONTEXT:
return "CL_INVALID_CONTEXT";
case CL_INVALID_QUEUE_PROPERTIES:
return "CL_INVALID_QUEUE_PROPERTIES";
case CL_INVALID_COMMAND_QUEUE:
return "CL_INVALID_COMMAND_QUEUE";
case CL_INVALID_HOST_PTR:
return "CL_INVALID_HOST_PTR";
case CL_INVALID_MEM_OBJECT:
return "CL_INVALID_MEM_OBJECT";
case CL_INVALID_IMAGE_FORMAT_DESCRIPTOR:
return "CL_INVALID_IMAGE_FORMAT_DESCRIPTOR";
case CL_INVALID_IMAGE_SIZE:
return "CL_INVALID_IMAGE_SIZE";
case CL_INVALID_SAMPLER:
return "CL_INVALID_SAMPLER";
case CL_INVALID_BINARY:
return "CL_INVALID_BINARY";
case CL_INVALID_BUILD_OPTIONS:
return "CL_INVALID_BUILD_OPTIONS";
case CL_INVALID_PROGRAM:
return "CL_INVALID_PROGRAM";
case CL_INVALID_PROGRAM_EXECUTABLE:
return "CL_INVALID_PROGRAM_EXECUTABLE";
case CL_INVALID_KERNEL_NAME:
return "CL_INVALID_KERNEL_NAME";
case CL_INVALID_KERNEL_DEFINITION:
return "CL_INVALID_KERNEL_DEFINITION";
case CL_INVALID_KERNEL:
return "CL_INVALID_KERNEL";
case CL_INVALID_ARG_INDEX:
return "CL_INVALID_ARG_INDEX";
case CL_INVALID_ARG_VALUE:
return "CL_INVALID_ARG_VALUE";
case CL_INVALID_ARG_SIZE:
return "CL_INVALID_ARG_SIZE";
case CL_INVALID_KERNEL_ARGS:
return "CL_INVALID_KERNEL_ARGS";
case CL_INVALID_WORK_DIMENSION:
return "CL_INVALID_WORK_DIMENSION";
case CL_INVALID_WORK_GROUP_SIZE:
return "CL_INVALID_WORK_GROUP_SIZE";
case CL_INVALID_WORK_ITEM_SIZE:
return "CL_INVALID_WORK_ITEM_SIZE";
case CL_INVALID_GLOBAL_OFFSET:
return "CL_INVALID_GLOBAL_OFFSET";
case CL_INVALID_EVENT_WAIT_LIST:
return "CL_INVALID_EVENT_WAIT_LIST";
case CL_INVALID_EVENT:
return "CL_INVALID_EVENT";
case CL_INVALID_OPERATION:
return "CL_INVALID_OPERATION";
case CL_INVALID_GL_OBJECT:
return "CL_INVALID_GL_OBJECT";
case CL_INVALID_BUFFER_SIZE:
return "CL_INVALID_BUFFER_SIZE";
case CL_INVALID_MIP_LEVEL:
return "CL_INVALID_MIP_LEVEL";
case CL_INVALID_GLOBAL_WORK_SIZE:
return "CL_INVALID_GLOBAL_WORK_SIZE";
#ifndef CL_VERSION_1_0
case CL_INVALID_PROPERTY:
return "CL_INVALID_PROPERTY";
#endif
default:
return "CL_UNKNOWN_CODE";
}
}
| 40.373297 | 137 | 0.694878 | zwakrim |
38754964ae7b296390a58f638cfbae82335574bf | 957 | cc | C++ | modificacion/src/complejos.cc | ULL-ESIT-IB-2020-2021/ib-practica12-oop-gtests-exercism-Saul-Sosa-Diaz | f1b8daf92fc55061d8bf73858653d3b336420b03 | [
"MIT"
] | null | null | null | modificacion/src/complejos.cc | ULL-ESIT-IB-2020-2021/ib-practica12-oop-gtests-exercism-Saul-Sosa-Diaz | f1b8daf92fc55061d8bf73858653d3b336420b03 | [
"MIT"
] | null | null | null | modificacion/src/complejos.cc | ULL-ESIT-IB-2020-2021/ib-practica12-oop-gtests-exercism-Saul-Sosa-Diaz | f1b8daf92fc55061d8bf73858653d3b336420b03 | [
"MIT"
] | null | null | null | /**
* Universidad de La Laguna
* Escuela Superior de Ingeniería y Tecnología
* Grado en Ingeniería Informática
* Informática Básica
*
* @author Saúl Sosa
* @date 3.enero.2021
* @brief Calculadora elemental de números complejos
*/
#include "complejo.h"
int main(int argc, char* argv[]){
Usage(argc, argv);//Modo de uso del programa
Complejo complejo1(1,4);
Complejo complejo2(4,-7);
Complejo complejo3 = complejo1 - 7.9;
Complejo complejo4 = complejo1 + 7.9;
std::cout << complejo1 << " - " << complejo2 << " = " << complejo1 - complejo2 << std::endl;
std::cout << complejo1 << " - 7.9 = ";
print(complejo3);
std::cout << std::endl;
std::cout << complejo1 << " + 7.9 = ";
print(complejo4);
std::cout << std::endl;
std::cout << complejo1 << " + " << complejo2 << " = " << complejo1 + complejo2 << std::endl;
std::cout << complejo1 << " * " << complejo2 << " = " << complejo1 * complejo2 << std::endl;
return 0;
} | 29 | 94 | 0.615465 | ULL-ESIT-IB-2020-2021 |
3876b4ce2d04a36444d5a0d33c88120f9f0b064f | 297 | cpp | C++ | sandbox/t_GVectorsGen1.cpp | f-fathurrahman/ffr-pspw-dft-c | 5e673e33385eb467d99fcd992b350614c2709740 | [
"MIT"
] | 1 | 2018-05-17T09:01:12.000Z | 2018-05-17T09:01:12.000Z | sandbox/t_GVectorsGen1.cpp | f-fathurrahman/ffr-pspw-dft-c | 5e673e33385eb467d99fcd992b350614c2709740 | [
"MIT"
] | null | null | null | sandbox/t_GVectorsGen1.cpp | f-fathurrahman/ffr-pspw-dft-c | 5e673e33385eb467d99fcd992b350614c2709740 | [
"MIT"
] | null | null | null | #include "../common_pspw_cuda.h"
void GVectorsGen1();
int main(int argc, char **argv)
{
NR1 = 20; NR2 = 20; NR3 = 20;
GCUT = 88.855355;
B1[0] = 1.0; B1[1] = 0.0; B1[2] = 0.0;
B2[0] = 0.0; B2[1] = 1.0; B2[2] = 0.0;
B3[0] = 0.0; B3[1] = 0.0; B3[2] = 1.0;
GVectorsGen1();
return 0;
}
| 16.5 | 39 | 0.515152 | f-fathurrahman |
38795cb08411dd8cba123633fe41d9210f15ea4a | 7,783 | cpp | C++ | libs/opengl/src/CGeneralizedEllipsoidTemplate.cpp | feroze/mrpt-shivang | 95bf524c5e10ed2e622bd199f1b0597951b45370 | [
"BSD-3-Clause"
] | 2 | 2017-03-25T18:09:17.000Z | 2017-05-22T08:14:48.000Z | libs/opengl/src/CGeneralizedEllipsoidTemplate.cpp | feroze/mrpt-shivang | 95bf524c5e10ed2e622bd199f1b0597951b45370 | [
"BSD-3-Clause"
] | null | null | null | libs/opengl/src/CGeneralizedEllipsoidTemplate.cpp | feroze/mrpt-shivang | 95bf524c5e10ed2e622bd199f1b0597951b45370 | [
"BSD-3-Clause"
] | 1 | 2018-07-29T09:40:46.000Z | 2018-07-29T09:40:46.000Z | /* +---------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| http://www.mrpt.org/ |
| |
| Copyright (c) 2005-2017, Individual contributors, see AUTHORS file |
| See: http://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See details in http://www.mrpt.org/License |
+---------------------------------------------------------------------------+ */
#include "opengl-precomp.h" // Precompiled header
#include <mrpt/opengl/CGeneralizedEllipsoidTemplate.h>
#include <mrpt/opengl/gl_utils.h>
#include "opengl_internals.h"
using namespace mrpt;
using namespace mrpt::opengl;
using namespace mrpt::utils;
using namespace mrpt::math;
using namespace std;
/*---------------------------------------------------------------
Render: 2D implementation
---------------------------------------------------------------*/
namespace mrpt {
namespace opengl {
namespace detail {
template <>
void renderGeneralizedEllipsoidTemplate<2>(
const std::vector<mrpt::math::CMatrixFixedNumeric<float,2,1> > & pts,
const float lineWidth,
const uint32_t slices,
const uint32_t stacks)
{
#if MRPT_HAS_OPENGL_GLUT
glEnable(GL_BLEND); gl_utils::checkOpenGLError();
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); gl_utils::checkOpenGLError();
glLineWidth(lineWidth); gl_utils::checkOpenGLError();
glDisable(GL_LIGHTING); // Disable lights when drawing lines
glBegin( GL_LINE_LOOP );
const size_t N = pts.size();
for (size_t i=0;i<N;i++)
glVertex2f( pts[i][0], pts[i][1] );
glEnd();
glEnable(GL_LIGHTING);
glDisable(GL_BLEND);
#else
MRPT_UNUSED_PARAM(pts); MRPT_UNUSED_PARAM(lineWidth); MRPT_UNUSED_PARAM(slices); MRPT_UNUSED_PARAM(stacks);
#endif
}
/*---------------------------------------------------------------
Render: 3D implementation
---------------------------------------------------------------*/
template <>
void renderGeneralizedEllipsoidTemplate<3>(
const std::vector<mrpt::math::CMatrixFixedNumeric<float,3,1> > & pts,
const float lineWidth,
const uint32_t slices,
const uint32_t stacks
)
{
#if MRPT_HAS_OPENGL_GLUT
glEnable(GL_BLEND); gl_utils::checkOpenGLError();
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); gl_utils::checkOpenGLError();
glLineWidth(lineWidth); gl_utils::checkOpenGLError();
glDisable(GL_LIGHTING); // Disable lights when drawing lines
// Points in the ellipsoid:
// * "#slices" slices, with "#stacks" points each, but for the two ends
// * 1 point at each end slice
// #total points = stacks*(slices-2) + 2
ASSERT_EQUAL_((slices-2)*stacks+2, pts.size())
const size_t idx_1st_slice = 1;
// 1st slice: triangle fan (if it were solid)
// ----------------------------
glBegin( GL_LINES );
for (size_t i=0;i<stacks;i++)
{
glVertex3fv(&pts[0][0]);
glVertex3fv(&pts[idx_1st_slice+i][0]);
}
glEnd();
// Middle slices: triangle strip (if it were solid)
// ----------------------------
for (size_t s=0;s<slices-3;s++)
{
size_t idx_this_slice = idx_1st_slice + stacks*s;
size_t idx_next_slice = idx_this_slice + stacks;
for (size_t i=0;i<stacks;i++)
{
const size_t ii = (i==(stacks-1) ? 0 : i+1); // next i with wrapping
glBegin( GL_LINE_STRIP );
glVertex3fv(&pts[idx_this_slice+i][0]);
glVertex3fv(&pts[idx_next_slice+ii][0]);
glVertex3fv(&pts[idx_next_slice+i][0]);
glVertex3fv(&pts[idx_this_slice+i][0]);
glVertex3fv(&pts[idx_this_slice+ii][0]);
glVertex3fv(&pts[idx_next_slice+ii][0]);
glEnd();
}
}
// Last slice: triangle fan (if it were solid)
// ----------------------------
const size_t idx_last_pt = pts.size()-1;
const size_t idx_last_slice = idx_1st_slice + (slices-3)*stacks;
glBegin( GL_LINES );
for (size_t i=0;i<stacks;i++)
{
glVertex3fv(&pts[idx_last_pt][0]);
glVertex3fv(&pts[idx_last_slice+i][0]);
}
glEnd();
//glBegin( GL_POINTS );
//const size_t N = pts.size();
//for (size_t i=0;i<N;i++)
// glVertex3f( pts[i][0], pts[i][1], pts[i][2] );
//glEnd();
glDisable(GL_BLEND);
glEnable(GL_LIGHTING);
#else
MRPT_UNUSED_PARAM(pts); MRPT_UNUSED_PARAM(lineWidth); MRPT_UNUSED_PARAM(slices); MRPT_UNUSED_PARAM(stacks);
#endif
}
/*---------------------------------------------------------------
generalizedEllipsoidPoints: 2D
---------------------------------------------------------------*/
template <>
void OPENGL_IMPEXP generalizedEllipsoidPoints<2>(
const mrpt::math::CMatrixFixedNumeric<double,2,2> & U,
const mrpt::math::CMatrixFixedNumeric<double,2,1> & mean,
std::vector<mrpt::math::CMatrixFixedNumeric<float,2,1> > &out_params_pts,
const uint32_t numSegments,
const uint32_t numSegments_unused)
{
MRPT_UNUSED_PARAM(numSegments_unused);
out_params_pts.clear();
out_params_pts.reserve(numSegments);
const double Aa = 2*M_PI/numSegments;
for (double ang=0;ang<2*M_PI;ang+=Aa)
{
const double ccos = cos(ang);
const double ssin = sin(ang);
out_params_pts.resize(out_params_pts.size()+1);
Eigen::Matrix<float,2,1> &pt = out_params_pts.back();
pt[0] = mean[0] + ccos * U.get_unsafe(0,0) + ssin * U.get_unsafe(0,1);
pt[1] = mean[1] + ccos * U.get_unsafe(1,0) + ssin * U.get_unsafe(1,1);
}
}
inline
void aux_add3DpointWithEigenVectors(
const double x,
const double y,
const double z,
std::vector<mrpt::math::CMatrixFixedNumeric<float,3,1> > & pts,
const mrpt::math::CMatrixFixedNumeric<double,3,3> & M,
const mrpt::math::CMatrixFixedNumeric<double,3,1> & mean)
{
pts.resize(pts.size()+1);
mrpt::math::CMatrixFixedNumeric<float,3,1> &pt= pts.back();
pt[0] = mean[0] + x * M.get_unsafe(0,0) + y * M.get_unsafe(0,1) + z * M.get_unsafe(0,2);
pt[1] = mean[1] + x * M.get_unsafe(1,0) + y * M.get_unsafe(1,1) + z * M.get_unsafe(1,2);
pt[2] = mean[2] + x * M.get_unsafe(2,0) + y * M.get_unsafe(2,1) + z * M.get_unsafe(2,2);
}
/*---------------------------------------------------------------
generalizedEllipsoidPoints: 3D
---------------------------------------------------------------*/
template <>
void OPENGL_IMPEXP generalizedEllipsoidPoints<3>(
const mrpt::math::CMatrixFixedNumeric<double,3,3> & U,
const mrpt::math::CMatrixFixedNumeric<double,3,1> & mean,
std::vector<mrpt::math::CMatrixFixedNumeric<float,3,1> > & pts,
const uint32_t slices,
const uint32_t stacks)
{
MRPT_START
ASSERT_ABOVEEQ_(slices,3)
ASSERT_ABOVEEQ_(stacks,3)
// sin/cos cache --------
// Slices: [0,pi]
std::vector<double> slice_cos(slices),slice_sin(slices);
for (uint32_t i = 0; i < slices; i++)
{
double angle = M_PI * i / double(slices-1);
slice_sin[i] = sin(angle);
slice_cos[i] = cos(angle);
}
// Stacks: [0,2*pi]
std::vector<double> stack_sin(stacks),stack_cos(stacks);
for (uint32_t i = 0; i < stacks; i++)
{
double angle = 2*M_PI * i / double(stacks);
stack_sin[i] = sin(angle);
stack_cos[i] = cos(angle);
}
// Points in the ellipsoid:
// * "#slices" slices, with "#stacks" points each, but for the two ends
// * 1 point at each end slice
// #total points = stacks*(slices-2) + 2
pts.clear();
pts.reserve((slices-2)*stacks+2);
for (uint32_t i=0;i<slices;i++)
{
if (i==0)
aux_add3DpointWithEigenVectors(1,0,0, pts,U,mean);
else if (i==(slices-1))
aux_add3DpointWithEigenVectors(-1,0,0, pts,U,mean);
else
{
const double x = slice_cos[i];
const double R = slice_sin[i];
for (uint32_t j=0;j<stacks;j++)
{
const double y = R*stack_cos[j];
const double z = R*stack_sin[j];
aux_add3DpointWithEigenVectors(x,y,z, pts,U,mean);
}
}
}
MRPT_END
}
}}} // end namespaces
| 30.884921 | 108 | 0.602724 | feroze |
387a4cac9693d42172ca2c7f43343f335500188c | 3,342 | cpp | C++ | Code/Lib/golSerialSharedGame.cpp | carlosparaciari/ParallelGameOfLife | 98b0251446adca123b7f2469073c5322c81b3824 | [
"BSD-3-Clause"
] | 1 | 2021-02-01T13:10:08.000Z | 2021-02-01T13:10:08.000Z | Code/Lib/golSerialSharedGame.cpp | carlosparaciari/ParallelGameOfLife | 98b0251446adca123b7f2469073c5322c81b3824 | [
"BSD-3-Clause"
] | null | null | null | Code/Lib/golSerialSharedGame.cpp | carlosparaciari/ParallelGameOfLife | 98b0251446adca123b7f2469073c5322c81b3824 | [
"BSD-3-Clause"
] | null | null | null | /*=============================================================================
GameOfLife: Let us mix together the Game of Life and parallel programming.
Copyright (c) University College London (UCL). All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.
See LICENSE.txt in the top level directory for details.
=============================================================================*/
#include "golSerialSharedGame.h"
namespace gol {
/// The class constructor.
SerialSharedGame::SerialSharedGame(game_parameters game_settings) {
m_game_settings = game_settings;
}
/// Method to evolve a frame by one time step.
void SerialSharedGame::evolve(frame & current_frame) {
if ( current_frame.empty() ) {
std::string message = std::string("The frame is empty.");
throw std::runtime_error(message);
}
bool notsame_x_size = current_frame.size() != m_game_settings.number_x_cells;
bool notsame_y_size = current_frame[0].size() != m_game_settings.number_y_cells;
if ( notsame_x_size || notsame_y_size ) {
std::string message = std::string("The frame size is not correct.");
throw std::runtime_error(message);
}
frame next_frame(m_game_settings.number_x_cells, std::vector<gol::cell>(m_game_settings.number_y_cells, gol::dead));
int number_alive_cells;
#pragma omp parallel private(number_alive_cells), shared(next_frame)
{
#pragma omp for collapse(2)
for ( int i = 0 ; i < m_game_settings.number_x_cells ; ++i ) {
for ( int j = 0 ; j < m_game_settings.number_y_cells ; ++j ) {
number_alive_cells = count_alive_neighbours(i, j, current_frame);
next_frame[i][j] = change_state_cell(number_alive_cells, current_frame[i][j]);
}
}
}
current_frame = next_frame;
}
/// Method to count the alive cells in the neighbourhood of a given cell.
int SerialSharedGame::count_alive_neighbours(int x_coord, int y_coord, frame & current_frame) {
int number_alive_cells = 0;
bool alive_centre = current_frame[x_coord][y_coord] == alive;
if ( alive_centre )
number_alive_cells += -1;
int delta = 1;
for ( int i = x_coord - delta ; i <= x_coord + delta ; ++i ) {
for ( int j = y_coord - delta ; j <= y_coord + delta ; ++j ) {
bool bad_coord = (i < 0) ||
(j < 0) ||
(i >= m_game_settings.number_x_cells) ||
(j >= m_game_settings.number_y_cells);
if ( !bad_coord ) {
bool alive_cell = current_frame[i][j] == alive;
if ( alive_cell )
number_alive_cells += 1;
}
}
}
return number_alive_cells;
}
/// Method to change the state of a cell depending on the number of closeby alive cells.
cell SerialSharedGame::change_state_cell(int alive_neighbours, cell current_state) {
if ( current_state == alive) {
if ( alive_neighbours < 2 )
return dead;
if ( (alive_neighbours == 2) || (alive_neighbours == 3) )
return alive;
if ( alive_neighbours > 3 )
return dead;
}
if ( current_state == dead) {
if ( alive_neighbours == 3 )
return alive;
else
return dead;
}
}
} // end namespace
| 30.66055 | 119 | 0.61939 | carlosparaciari |
387a9903da14d6a0119ccaf26e2d63c2435d054b | 405 | cc | C++ | src/runner.cc | dkozinski/uvgRTP | c74d6a75a7c226cec919ab2639d13f6a770d069c | [
"BSD-2-Clause"
] | null | null | null | src/runner.cc | dkozinski/uvgRTP | c74d6a75a7c226cec919ab2639d13f6a770d069c | [
"BSD-2-Clause"
] | null | null | null | src/runner.cc | dkozinski/uvgRTP | c74d6a75a7c226cec919ab2639d13f6a770d069c | [
"BSD-2-Clause"
] | null | null | null | #include "runner.hh"
uvg_rtp::runner::runner():
active_(false), runner_(nullptr)
{
}
uvg_rtp::runner::~runner()
{
active_ = false;
if (runner_)
delete runner_;
}
rtp_error_t uvg_rtp::runner::start()
{
active_ = true;
return RTP_OK;
}
rtp_error_t uvg_rtp::runner::stop()
{
active_ = false;
return RTP_OK;
}
bool uvg_rtp::runner::active()
{
return active_;
}
| 11.911765 | 36 | 0.624691 | dkozinski |
387abae9c3f8e233b5629d4945a89830d4880884 | 1,388 | cpp | C++ | shadows-of-the-knight/main_codingame.cpp | dubzzz/property-based-testing-cpp | 418c0e952cdb50633bd43e73faa545e52cc1af63 | [
"MIT"
] | 11 | 2018-03-14T17:12:10.000Z | 2021-12-12T04:15:53.000Z | shadows-of-the-knight/main_codingame.cpp | dubzzz/property-based-testing-cpp | 418c0e952cdb50633bd43e73faa545e52cc1af63 | [
"MIT"
] | null | null | null | shadows-of-the-knight/main_codingame.cpp | dubzzz/property-based-testing-cpp | 418c0e952cdb50633bd43e73faa545e52cc1af63 | [
"MIT"
] | 3 | 2019-06-19T16:45:19.000Z | 2021-07-13T10:22:16.000Z | #include <cstddef>
#include <iostream>
#include <string>
class Space
{
const std::size_t m_dim_x, m_dim_y;
std::size_t m_current_x, m_current_y;
std::string m_hint;
public:
Space(
std::size_t dim_x, std::size_t dim_y,
std::size_t current_x, std::size_t current_y)
: m_dim_x(dim_x)
, m_dim_y(dim_y)
, m_current_x(current_x)
, m_current_y(current_y)
, m_hint()
{
std::cin >> m_hint;
std::cin.ignore();
}
std::size_t dimension_x() const { return m_dim_x; }
std::size_t dimension_y() const { return m_dim_y; }
std::size_t previous_x() const { return m_current_x; }
std::size_t previous_y() const { return m_current_y; }
std::string const& hint() const { return m_hint; }
void move(std::size_t x, std::size_t y)
{
std::cout << x << " " << y << std::endl;
m_current_x = x;
m_current_y = y;
std::cin >> m_hint;
std::cin.ignore();
}
bool solved() const
{
return m_hint.empty();
}
};
/* COPY PASTE the code of "implem.inl.hpp"
HERE */
int main()
{
std::size_t W, H;
std::cin >> W >> H;
std::cin.ignore();
std::size_t N;
std::cin >> N;
std::cin.ignore();
std::size_t X0, Y0;
std::cin >> X0 >> Y0;
std::cin.ignore();
Space sp {W, H, X0, Y0};
locate_in_space(sp, N);
}
| 20.115942 | 56 | 0.561239 | dubzzz |
387b842d71f1e9ad201cbe78cc367cbd79d90234 | 9,579 | cpp | C++ | silkrpc/core/storage_walker.cpp | torquem-ch/silkrpc | 38441b1852345aae846071e36fc1a4745968caeb | [
"Apache-2.0"
] | 9 | 2021-03-08T13:26:46.000Z | 2022-02-25T23:23:16.000Z | silkrpc/core/storage_walker.cpp | torquem-ch/silkrpc | 38441b1852345aae846071e36fc1a4745968caeb | [
"Apache-2.0"
] | 151 | 2020-11-22T15:42:58.000Z | 2022-03-31T20:12:18.000Z | silkrpc/core/storage_walker.cpp | torquem-ch/silkrpc | 38441b1852345aae846071e36fc1a4745968caeb | [
"Apache-2.0"
] | 5 | 2021-03-15T11:01:34.000Z | 2022-03-12T15:45:00.000Z | /*
Copyright 2020 The Silkrpc Authors
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 "storage_walker.hpp"
#include <sstream>
#include <boost/endian/conversion.hpp>
#include <silkworm/core/silkworm/common/endian.hpp>
#include <silkworm/node/silkworm/db/bitmap.hpp>
#include <silkworm/node/silkworm/db/util.hpp>
#include <silkrpc/common/log.hpp>
#include <silkrpc/core/rawdb/chain.hpp>
#include <silkrpc/core/state_reader.hpp>
#include <silkrpc/ethdb/cursor.hpp>
#include <silkrpc/ethdb/tables.hpp>
#include <silkrpc/ethdb/transaction_database.hpp>
#include <silkrpc/json/types.hpp>
namespace silkrpc {
silkworm::Bytes make_key(const evmc::address& address, const evmc::bytes32& location) {
silkworm::Bytes res(silkworm::kAddressLength + silkworm::kHashLength, '\0');
std::memcpy(&res[0], address.bytes, silkworm::kAddressLength);
std::memcpy(&res[silkworm::kAddressLength], location.bytes, silkworm::kHashLength);
return res;
}
silkworm::Bytes make_key(const evmc::address& address, uint64_t incarnation, const evmc::bytes32& location) {
silkworm::Bytes res(silkworm::kAddressLength + silkworm::kHashLength + 8, '\0');
std::memcpy(&res[0], address.bytes, silkworm::kAddressLength);
boost::endian::store_big_u64(&res[silkworm::kAddressLength], incarnation);
std::memcpy(&res[silkworm::kAddressLength + 8], location.bytes, silkworm::kHashLength);
return res;
}
asio::awaitable<silkrpc::ethdb::SplittedKeyValue> next(silkrpc::ethdb::SplitCursor& cursor, uint64_t number) {
auto kv = co_await cursor.next();
if (kv.key2.empty()) {
co_return kv;
}
uint64_t block = silkworm::endian::load_big_u64(kv.key3.data());
SILKRPC_TRACE << "Curson on StorageHistory NEXT"
<< " addr 0x" << silkworm::to_hex(kv.key1)
<< " loc " << silkworm::to_hex(kv.key2)
<< " tsEnc " << silkworm::to_hex(kv.key3)
<< " v " << silkworm::to_hex(kv.value)
<< "\n";
while (block < number) {
kv = co_await cursor.next();
if (kv.key2.empty()) {
break;
}
block = silkworm::endian::load_big_u64(kv.key3.data());
SILKRPC_TRACE << "Curson on StorageHistory NEXT"
<< " addr 0x" << silkworm::to_hex(kv.key1)
<< " loc " << silkworm::to_hex(kv.key2)
<< " tsEnc " << silkworm::to_hex(kv.key3)
<< " v " << silkworm::to_hex(kv.value)
<< "\n";
}
co_return kv;
}
asio::awaitable<void> StorageWalker::walk_of_storages(uint64_t block_number, const evmc::address& start_address,
const evmc::bytes32& location_hash, uint64_t incarnation, Collector& collector) {
auto ps_cursor = co_await transaction_.cursor(db::table::kPlainState);
auto ps_key{make_key(start_address, incarnation, location_hash)};
silkrpc::ethdb::SplitCursor ps_split_cursor{*ps_cursor,
ps_key,
8 * (silkworm::kAddressLength + 8),
silkworm::kAddressLength,
silkworm::kAddressLength + 8,
silkworm::kAddressLength + 8 + silkworm::kHashLength};
SILKRPC_TRACE << "Curson on PlainState"
<< " ps_key 0x" << silkworm::to_hex(ps_key)
<< " key len " << ps_key.length()
<< " match_bits " << 8 * (silkworm::kAddressLength + 8)
<< " length1 " << silkworm::kAddressLength
<< " length2 " << 8
<< "\n";
auto sh_key{make_key(start_address, location_hash)};
auto sh_cursor = co_await transaction_.cursor(db::table::kStorageHistory);
silkrpc::ethdb::SplitCursor sh_split_cursor{*sh_cursor,
sh_key,
8 * silkworm::kAddressLength,
silkworm::kAddressLength,
silkworm::kAddressLength,
silkworm::kAddressLength + silkworm::kHashLength};
SILKRPC_TRACE << "Curson on StorageHistory"
<< " sh_key 0x" << silkworm::to_hex(sh_key)
<< " key len " << sh_key.length()
<< " match_bits " << 8 * silkworm::kAddressLength
<< " length1 " << silkworm::kAddressLength
<< " length2 " << 8
<< "\n";
auto ps_skv = co_await ps_split_cursor.seek();
SILKRPC_TRACE << "Curson on PlainState SEEK"
<< " addr 0x" << silkworm::to_hex(ps_skv.key1)
<< " loc " << silkworm::to_hex(ps_skv.key2)
<< " kk " << silkworm::to_hex(ps_skv.key3)
<< " v " << silkworm::to_hex(ps_skv.value)
<< "\n";
auto sh_skv = co_await sh_split_cursor.seek();
uint64_t block = silkworm::endian::load_big_u64(sh_skv.key3.data());
SILKRPC_TRACE << "Curson on StorageHistory SEEK"
<< " addr 0x" << silkworm::to_hex(sh_skv.key1)
<< " loc " << silkworm::to_hex(sh_skv.key2)
<< " tsEnc " << silkworm::to_hex(sh_skv.key3)
<< " v " << silkworm::to_hex(sh_skv.value)
<< "\n";
auto cs_cursor = co_await transaction_.cursor_dup_sort(db::table::kPlainStorageChangeSet);
if (block < block_number) {
sh_skv = co_await next(sh_split_cursor, block_number);
}
auto count = 0;
auto go_on = true;
while (go_on && count < 10) {
count++;
if (ps_skv.key1.empty() && sh_skv.key1.empty()) {
SILKRPC_TRACE << "Both keys1 are empty: break loop\n";
break;
}
auto cmp = ps_skv.key1.compare(sh_skv.key1);
SILKRPC_TRACE << "ITERATE ** KeyCmp: addr 0x" << silkworm::to_hex(ps_skv.key1)
<< " hAddr 0x" << silkworm::to_hex(sh_skv.key1)
<< " cmp " << cmp
<< "\n";
if (cmp == 0) {
if (ps_skv.key2.empty() && sh_skv.key2.empty()) {
SILKRPC_TRACE << "Both keys2 are empty: break loop\n";
break;
}
auto cmp = ps_skv.key2.compare(sh_skv.key2);
SILKRPC_TRACE << "ITERATE ** KeyCmp: loc 0x" << silkworm::to_hex(ps_skv.key2)
<< " hLoc 0x" << silkworm::to_hex(sh_skv.key2)
<< " cmp " << cmp
<< "\n";
}
if (cmp < 0) {
auto address = silkworm::to_address(ps_skv.key1);
go_on = collector(address, ps_skv.key2, ps_skv.value);
SILKRPC_TRACE << "ITERATE ** COLLECTOR CALLED: address 0x" << silkworm::to_hex(address)
<< " loc 0x" << silkworm::to_hex(ps_skv.key2)
<< " data 0x" << silkworm::to_hex(ps_skv.value)
<< " go_on " << go_on
<< "\n";
} else {
SILKRPC_TRACE << "ITERATE ** built roaring64 from " << silkworm::to_hex(sh_skv.value) << "\n";
const auto bitmap = silkworm::db::bitmap::read(sh_skv.value);
std::optional<silkworm::Account> result;
if (bitmap.contains(block_number)) {
auto dup_key{silkworm::db::storage_change_key(block_number, start_address, incarnation)};
SILKRPC_TRACE << "Curson on StorageHistory"
<< " dup_key 0x" << silkworm::to_hex(dup_key)
<< " key len " << dup_key.length()
<< " hLoc " << silkworm::to_hex(sh_skv.key2)
<< "\n";
auto data = co_await cs_cursor->seek_both(dup_key, sh_skv.key2);
SILKRPC_TRACE << "Curson on StorageHistory"
<< " found data 0x" << silkworm::to_hex(data)
<< "\n";
data = data.substr(silkworm::kHashLength);
if (data.length() > 0) { // Skip deleted entries
auto address = silkworm::to_address(ps_skv.key1);
go_on = collector(address, ps_skv.key2, data);
SILKRPC_TRACE << "ITERATE ** COLLECTOR CALLED: address 0x" << silkworm::to_hex(address)
<< " loc 0x" << silkworm::to_hex(sh_skv.key2)
<< " data 0x" << silkworm::to_hex(data)
<< " go_on " << go_on
<< "\n";
}
} else if (cmp == 0) {
auto address = silkworm::to_address(ps_skv.key1);
go_on = collector(address, ps_skv.key2, ps_skv.value);
SILKRPC_TRACE << "ITERATE ** COLLECTOR CALLED: address 0x" << silkworm::to_hex(address)
<< " loc 0x" << silkworm::to_hex(ps_skv.key2)
<< " data 0x" << silkworm::to_hex(ps_skv.value)
<< " go_on " << go_on
<< "\n";
}
}
if (go_on) {
if (cmp <= 0) {
ps_skv = co_await ps_split_cursor.next();
SILKRPC_TRACE << "Curson on PlainState NEXT"
<< " addr 0x" << silkworm::to_hex(ps_skv.key1)
<< " loc " << silkworm::to_hex(ps_skv.key2)
<< " kk " << silkworm::to_hex(ps_skv.key3)
<< " v " << silkworm::to_hex(ps_skv.value)
<< "\n";
}
if (cmp >= 0) {
sh_skv = co_await next(sh_split_cursor, block_number);
}
}
}
co_return;
}
} // namespace silkrpc
| 40.935897 | 112 | 0.573233 | torquem-ch |
387f24f11bd3321cba759133bb1cf5b63ed1d26b | 1,945 | cpp | C++ | Heap/06 HeapifyFunctionFasterMethodtoCreateHeap.cpp | GajuuKool/DSA_CPP | c63b64783238680fcb97f908298c7378f9109063 | [
"MIT"
] | 9 | 2020-09-30T17:57:18.000Z | 2021-11-14T18:27:49.000Z | Heap/06 HeapifyFunctionFasterMethodtoCreateHeap.cpp | GajuuKool/DSA_CPP | c63b64783238680fcb97f908298c7378f9109063 | [
"MIT"
] | 1 | 2020-10-06T11:15:20.000Z | 2021-01-02T11:35:57.000Z | Heap/06 HeapifyFunctionFasterMethodtoCreateHeap.cpp | GajuuKool/DSA_CPP | c63b64783238680fcb97f908298c7378f9109063 | [
"MIT"
] | 13 | 2020-09-30T17:56:50.000Z | 2022-03-15T11:07:08.000Z | #include <iostream>
using namespace std;
void swap(int A[], int i, int j){
int temp = A[i];
A[i] = A[j];
A[j] = temp;
}
int Delete(int A[], int n){
int x = A[0]; // Max element
A[0] = A[n-1];
int i = 0;
int j = 2 * i + 1;
while (j < n-1){
// Compare left and right children
if (A[j] < A[j+1]){
j = j+1;
}
// Compare parent and largest child
if (A[i] < A[j]){
swap(A, i, j);
i = j;
j = 2 * i + 1;
} else {
break;
}
}
return x;
}
void Heapify(int A[], int n){
// # of leaf elements: (n+1)/2, index of last leaf element's parent = (n/2)-1
for (int i=(n/2)-1; i>=0; i--){
int j = 2 * i + 1; // Left child for current i
while(j < n-1){
// Compare left and right children of current i
if (A[j] < A[j+1]){
j = j+1;
}
// Compare parent and largest child
if (A[i] < A[j]){
swap(A, i, j);
i = j;
j = 2 * i + 1;
} else {
break;
}
}
}
}
template <class T>
void Print(T& vec, int n, string s){
cout << s << ": [" << flush;
for (int i=0; i<n; i++){
cout << vec[i] << flush;
if (i < n-1){
cout << ", " << flush;
}
}
cout << "]" << endl;
}
int main() {
int A[] = {5, 10, 30, 20, 35, 40, 15};
Print(A, sizeof(A)/sizeof(A[0]), "A");
Heapify(A, sizeof(A)/sizeof(A[0]));
Print(A, sizeof(A)/sizeof(A[0]), "Heapified A");
cout << endl;
int B[] = {5, 10, 30, 20};
Print(B, sizeof(B)/sizeof(B[0]), "B");
Heapify(B, sizeof(B)/sizeof(B[0]));
Print(B, sizeof(B)/sizeof(B[0]), "Heapified B");
return 0;
} | 22.102273 | 82 | 0.382519 | GajuuKool |
38814d3e6fa1fed332afb5b4d0a555dca6af6b20 | 520 | cpp | C++ | sem1/hw6/hw6.1/hw6.1/main.cpp | Daria-Donina/Homework | 8853fb65c7a0ad62556a49d12908098af9caf7ed | [
"Apache-2.0"
] | 1 | 2018-11-29T11:12:51.000Z | 2018-11-29T11:12:51.000Z | sem1/hw6/hw6.1/hw6.1/main.cpp | Daria-Donina/Homework | 8853fb65c7a0ad62556a49d12908098af9caf7ed | [
"Apache-2.0"
] | null | null | null | sem1/hw6/hw6.1/hw6.1/main.cpp | Daria-Donina/Homework | 8853fb65c7a0ad62556a49d12908098af9caf7ed | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <string>
#include "stack.h"
#include "resultCounting.h"
#include "test.h"
using namespace std;
int main()
{
if (test())
{
cout << "Tests passed" << endl;
}
else
{
cout << "Tests failed" << endl;
}
Stack *stack = createStack();
cout << "Enter postfix expression: ";
string expression = "";
getline(cin, expression);
int expressionResult = result(stack, expression);
cout << "The result of the expression is: " << expressionResult << endl;
deleteStack(stack);
return 0;
}
| 17.931034 | 73 | 0.659615 | Daria-Donina |
3885337c7a198cf05f1321f6c5c9e94031e80a53 | 422 | cpp | C++ | src/lib/parser/ParserParamInstr.cpp | WasmVM/wass | e35962e1637a1445ab8ad97e5a06ee4d59b49fd7 | [
"BSD-3-Clause"
] | null | null | null | src/lib/parser/ParserParamInstr.cpp | WasmVM/wass | e35962e1637a1445ab8ad97e5a06ee4d59b49fd7 | [
"BSD-3-Clause"
] | null | null | null | src/lib/parser/ParserParamInstr.cpp | WasmVM/wass | e35962e1637a1445ab8ad97e5a06ee4d59b49fd7 | [
"BSD-3-Clause"
] | null | null | null | #include <parser/ParserParamInstr.hpp>
#include <Util.hpp>
#include <structure/BaseInstr.hpp>
ParserParamInstr::ParserParamInstr(ParserContext& context){
if(Util::matchString(context.cursor, context.end, "select")){
context.cursor += 6;
emplace<SelectInstr>(SelectInstr());
}else if(Util::matchString(context.cursor, context.end, "drop")){
context.cursor += 4;
emplace<DropInstr>(DropInstr());
}
}
| 28.133333 | 67 | 0.71564 | WasmVM |
388b7b699bba660dd4b5b1eb9027048e978008b5 | 3,764 | cpp | C++ | Extensions/GlyphKinect2/Kinect2SkeletonActor.cpp | zgpxgame/hieroglyph3 | bb1c59d82a69062bb76431b691fbcb381930768a | [
"MIT"
] | 25 | 2017-08-05T07:29:00.000Z | 2022-02-02T06:28:27.000Z | Extensions/GlyphKinect2/Kinect2SkeletonActor.cpp | zgpxgame/hieroglyph3 | bb1c59d82a69062bb76431b691fbcb381930768a | [
"MIT"
] | null | null | null | Extensions/GlyphKinect2/Kinect2SkeletonActor.cpp | zgpxgame/hieroglyph3 | bb1c59d82a69062bb76431b691fbcb381930768a | [
"MIT"
] | 9 | 2018-07-14T08:40:29.000Z | 2021-03-19T08:51:30.000Z | //--------------------------------------------------------------------------------
// This file is a portion of the Hieroglyph 3 Rendering Engine. It is distributed
// under the MIT License, available in the root of this distribution and
// at the following URL:
//
// http://www.opensource.org/licenses/mit-license.php
//
// Copyright (c) Jason Zink
//--------------------------------------------------------------------------------
//--------------------------------------------------------------------------------
#include "GlyphKinect2/Kinect2SkeletonActor.h"
//--------------------------------------------------------------------------------
using namespace Glyph3;
//--------------------------------------------------------------------------------
Kinect2SkeletonActor::Kinect2SkeletonActor()
{
}
//--------------------------------------------------------------------------------
Kinect2SkeletonActor::~Kinect2SkeletonActor()
{
}
//--------------------------------------------------------------------------------
void Kinect2SkeletonActor::UpdateSkeleton( const Kinect2Skeleton& body )
{
ResetGeometry();
SetColor( Vector4f( 1.0f, 1.0f, 0.0f, 0.0f ) );
for ( int joint = 0; joint < 25; ++joint ) {
DrawSphere( body.jointPositions[joint], 0.03f );
}
SetColor( Vector4f( 0.0f, 1.0f, 0.0f, 0.0f ) );
// Head to hips
DrawLinkage( body, Kinect2JointType::Head, Kinect2JointType::Neck);
DrawLinkage( body, Kinect2JointType::Neck, Kinect2JointType::SpineShoulder);
DrawLinkage( body, Kinect2JointType::SpineShoulder, Kinect2JointType::SpineMid);
DrawLinkage( body, Kinect2JointType::SpineMid, Kinect2JointType::SpineBase);
// Left arm
DrawLinkage( body, Kinect2JointType::SpineShoulder, Kinect2JointType::ShoulderLeft );
DrawLinkage( body, Kinect2JointType::ShoulderLeft, Kinect2JointType::ElbowLeft );
DrawLinkage( body, Kinect2JointType::ElbowLeft, Kinect2JointType::WristLeft );
DrawLinkage( body, Kinect2JointType::WristLeft, Kinect2JointType::HandLeft );
DrawLinkage( body, Kinect2JointType::HandLeft, Kinect2JointType::HandTipLeft );
DrawLinkage( body, Kinect2JointType::HandLeft, Kinect2JointType::ThumbLeft );
// Right arm
DrawLinkage( body, Kinect2JointType::SpineShoulder, Kinect2JointType::ShoulderRight );
DrawLinkage( body, Kinect2JointType::ShoulderRight, Kinect2JointType::ElbowRight );
DrawLinkage( body, Kinect2JointType::ElbowRight, Kinect2JointType::WristRight );
DrawLinkage( body, Kinect2JointType::WristRight, Kinect2JointType::HandRight );
DrawLinkage( body, Kinect2JointType::HandRight, Kinect2JointType::HandTipRight );
DrawLinkage( body, Kinect2JointType::HandRight, Kinect2JointType::ThumbRight );
// Left leg
DrawLinkage( body, Kinect2JointType::SpineBase, Kinect2JointType::HipLeft );
DrawLinkage( body, Kinect2JointType::HipLeft, Kinect2JointType::KneeLeft );
DrawLinkage( body, Kinect2JointType::KneeLeft, Kinect2JointType::AnkleLeft );
DrawLinkage( body, Kinect2JointType::AnkleLeft, Kinect2JointType::FootLeft );
// Right leg
DrawLinkage( body, Kinect2JointType::SpineBase, Kinect2JointType::HipRight );
DrawLinkage( body, Kinect2JointType::HipRight, Kinect2JointType::KneeRight );
DrawLinkage( body, Kinect2JointType::KneeRight, Kinect2JointType::AnkleRight );
DrawLinkage( body, Kinect2JointType::AnkleRight, Kinect2JointType::FootRight );
}
//--------------------------------------------------------------------------------
void Kinect2SkeletonActor::DrawLinkage( const Kinect2Skeleton& body, Kinect2JointType i1, Kinect2JointType i2 )
{
Vector3f p1, p2;
p1 = body.jointPositions[static_cast<int>(i1)];
p2 = body.jointPositions[static_cast<int>(i2)];
DrawCylinder( p1, p2, 0.015f, 0.015f );
}
//-------------------------------------------------------------------------------- | 47.64557 | 112 | 0.623804 | zgpxgame |
388c6d66c74c568fb14315b1f8a71f347fa27056 | 2,645 | hh | C++ | include/ignition/sensors/BrownDistortionModel.hh | david-alejo/ign-sensors | 13308478b6f88c99a3685181439ab51ed7ed63f6 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | include/ignition/sensors/BrownDistortionModel.hh | david-alejo/ign-sensors | 13308478b6f88c99a3685181439ab51ed7ed63f6 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | include/ignition/sensors/BrownDistortionModel.hh | david-alejo/ign-sensors | 13308478b6f88c99a3685181439ab51ed7ed63f6 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2022 Open Source Robotics Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef IGNITION_SENSORS_BROWNDISTORTIONMODEL_HH_
#define IGNITION_SENSORS_BROWNDISTORTIONMODEL_HH_
#include <sdf/sdf.hh>
#include "ignition/sensors/Distortion.hh"
#include "ignition/sensors/Export.hh"
#include "ignition/sensors/config.hh"
#include "ignition/utils/ImplPtr.hh"
namespace ignition
{
namespace sensors
{
// Inline bracket to help doxygen filtering.
inline namespace IGNITION_SENSORS_VERSION_NAMESPACE {
//
// Forward declarations
class BrownDistortionModelPrivate;
/** \class BrownDistortionModel BrownDistortionModel.hh \
ignition/sensors/BrownDistortionModel.hh
**/
/// \brief Brown Distortion Model class
class IGNITION_SENSORS_VISIBLE BrownDistortionModel : public Distortion
{
/// \brief Constructor.
public: BrownDistortionModel();
/// \brief Destructor.
public: virtual ~BrownDistortionModel();
// Documentation inherited.
public: virtual void Load(const sdf::Camera &_sdf) override;
/// \brief Get the radial distortion coefficient k1.
/// \return Distortion coefficient k1.
public: double K1() const;
/// \brief Get the radial distortion coefficient k2.
/// \return Distortion coefficient k2.
public: double K2() const;
/// \brief Get the radial distortion coefficient k3.
/// \return Distortion coefficient k3.
public: double K3() const;
/// \brief Get the tangential distortion coefficient p1.
/// \return Distortion coefficient p1.
public: double P1() const;
/// \brief Get the tangential distortion coefficient p2.
/// \return Distortion coefficient p2.
public: double P2() const;
/// \brief Get the distortion center.
/// \return Distortion center.
public: math::Vector2d Center() const;
/// Documentation inherited
public: virtual void Print(std::ostream &_out) const override;
/// \brief Private data pointer.
IGN_UTILS_IMPL_PTR(dataPtr)
};
}
}
}
#endif
| 30.056818 | 75 | 0.697921 | david-alejo |
388e8620647ac8baecffe6a25f64b80296a6dc33 | 1,604 | cpp | C++ | assignments/a5/main.cpp | elipwns/Data-Structures | 6c9d6da1254aefd31dfed5edad5987a70c4423a9 | [
"MIT"
] | null | null | null | assignments/a5/main.cpp | elipwns/Data-Structures | 6c9d6da1254aefd31dfed5edad5987a70c4423a9 | [
"MIT"
] | null | null | null | assignments/a5/main.cpp | elipwns/Data-Structures | 6c9d6da1254aefd31dfed5edad5987a70c4423a9 | [
"MIT"
] | null | null | null | /***********************************************************
* Author: eli kloft
* Lab Number: a5
* Filename: a5.cpp
* Date Created: 4/23/13
* Modifications:
*
* Overview:
* a wrapper around the double linked list class in the form of
* an iterator.
*
* Input:
*
*
* Output:
* tests the various funcitons
************************************************************/
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#include <iostream>
using std::cout;
#include "AbstractIterator.h"
#include "doublelinkedlist.h"
#include "ListIterator.h"
#include "node.h"
#include "BackwardsIterator.h"
#include "ForwardIterator.h"
int main()
{
_CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
DoubleLinkedList<int> * list = new DoubleLinkedList<int>();
for(int i = 0; i < 8; ++i)
{
list->Append(i);
}
cout <<"Testing forwards\n";
ForwardIterator<int> forward(*list);
while(!forward.IsDone())
{
cout << forward.GetCurrent() << "\n";
forward.MoveNext();
}
cout << forward.GetCurrent() << "\n";
cout << "testing reset\n";
forward.Reset();
cout << forward.GetCurrent() << "\n";
cout << "\n" << "Testing Backwards\n";
BackwardsIterator<int> back(*list);
while(!back.IsDone())
{
cout << back.GetCurrent() << "\n";
back.MoveNext();
}
cout << back.GetCurrent() << "\n";
cout <<"testing reset\n";
back.Reset();
cout << back.GetCurrent() << "\n";
cout << "testing copy and op=" << "\n";
ForwardIterator<int> copyForward(forward);
cout << copyForward.GetCurrent() << " " << forward.GetCurrent() << "\n";
system("Pause");
delete list;
return 0;
} | 22.277778 | 73 | 0.604115 | elipwns |
389193fd20eeddfa2f8d9e99338ae3d1b6913402 | 3,463 | cpp | C++ | DNP3Test/TestVtoLoopbackIntegration.cpp | rajive/dnp3 | f5d8dbcec2085eaeb980e66d07df19b7bb9c20aa | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | DNP3Test/TestVtoLoopbackIntegration.cpp | rajive/dnp3 | f5d8dbcec2085eaeb980e66d07df19b7bb9c20aa | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | DNP3Test/TestVtoLoopbackIntegration.cpp | rajive/dnp3 | f5d8dbcec2085eaeb980e66d07df19b7bb9c20aa | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2019-03-31T15:27:05.000Z | 2019-09-17T16:12:53.000Z | /*
* Licensed to Green Energy Corp (www.greenenergycorp.com) under one or more
* contributor license agreements. See the NOTICE file distributed with this
* work for additional information regarding copyright ownership. Green Enery
* Corp licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
#include <boost/test/unit_test.hpp>
#include <APL/PhysLoopback.h>
#include <APL/RandomizedBuffer.h>
#include <APLTestTools/MockPhysicalLayerMonitor.h>
#include "VtoIntegrationTestBase.h"
using namespace apl;
using namespace apl::dnp;
class VtoLoopbackTestStack : public VtoIntegrationTestBase
{
public:
VtoLoopbackTestStack(
bool clientOnSlave = true,
bool aImmediateOutput = false,
bool aLogToFile = false,
FilterLevel level = LEV_INFO,
boost::uint16_t port = MACRO_PORT_VALUE) :
VtoIntegrationTestBase(clientOnSlave, aImmediateOutput, aLogToFile, level, port),
loopback(mLog.GetLogger(level, "loopback"), &vtoServer, &timerSource),
local(mLog.GetLogger(level, "mock-client-connection"), &vtoClient, &timerSource, 500) {
}
virtual ~VtoLoopbackTestStack() {
local.Shutdown();
loopback.Shutdown();
}
bool WaitForLocalState(PhysicalLayerState aState, millis_t aTimeout = 30000) {
return testObj.ProceedUntil(boost::bind(&MockPhysicalLayerMonitor::NextStateIs, &local, aState), aTimeout);
}
bool WaitForExpectedDataToBeReceived(millis_t aTimeout = 30000) {
return testObj.ProceedUntil(boost::bind(&MockPhysicalLayerMonitor::AllExpectedDataHasBeenReceived, &local), aTimeout);
}
PhysLoopback loopback;
MockPhysicalLayerMonitor local;
};
BOOST_AUTO_TEST_SUITE(VtoLoopbackIntegrationSuite)
void TestLargeDataLoopback(VtoLoopbackTestStack& arTest, size_t aSizeInBytes)
{
// start everything
arTest.loopback.Start();
arTest.local.Start();
BOOST_REQUIRE(arTest.WaitForLocalState(PLS_OPEN));
// test that a large set of data flowing one way works
CopyableBuffer data(aSizeInBytes);
for(size_t i = 0; i < data.Size(); ++i) data[i] = static_cast<boost::uint8_t>(i % (0xAA));
arTest.local.ExpectData(data);
arTest.local.WriteData(data);
BOOST_REQUIRE(arTest.WaitForExpectedDataToBeReceived(60000));
// this will cause an exception if we receive any more data beyond what we wrote
arTest.testObj.ProceedForTime(1000);
}
#define MACRO_BUFFER_SIZE 1<<20 // 1 << 20 == 1MB, 1<<24 == 16MB
BOOST_AUTO_TEST_CASE(LargeDataLoopbackMasterWritesSlaveEchoes)
{
VtoLoopbackTestStack stack(true, false);
stack.tcpPipe.client.SetCorruptionProbability(0.005);
stack.tcpPipe.server.SetCorruptionProbability(0.005);
TestLargeDataLoopback(stack, MACRO_BUFFER_SIZE);
}
BOOST_AUTO_TEST_CASE(LargeDataLoopbackSlaveWritesMasterEchoes)
{
VtoLoopbackTestStack stack(false, false);
stack.tcpPipe.client.SetCorruptionProbability(0.005);
stack.tcpPipe.server.SetCorruptionProbability(0.005);
TestLargeDataLoopback(stack, MACRO_BUFFER_SIZE);
}
BOOST_AUTO_TEST_SUITE_END()
/* vim: set ts=4 sw=4: */
| 32.980952 | 120 | 0.775628 | rajive |
3898a81e317b195c4634e9ccd30ba4faf4928c02 | 2,429 | hpp | C++ | windows/include/boost/spirit/home/karma/nonterminal/meta_grammar.hpp | jaredhoberock/gotham | e3551cc355646530574d086d7cc2b82e41e8f798 | [
"Apache-2.0"
] | 6 | 2015-12-29T07:21:01.000Z | 2020-05-29T10:47:38.000Z | windows/include/boost/spirit/home/karma/nonterminal/meta_grammar.hpp | jaredhoberock/gotham | e3551cc355646530574d086d7cc2b82e41e8f798 | [
"Apache-2.0"
] | null | null | null | windows/include/boost/spirit/home/karma/nonterminal/meta_grammar.hpp | jaredhoberock/gotham | e3551cc355646530574d086d7cc2b82e41e8f798 | [
"Apache-2.0"
] | null | null | null | // Copyright (c) 2001-2008 Hartmut Kaiser
// Copyright (c) 2001-2007 Joel de Guzman
//
// 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)
#if !defined(BOOST_SPIRIT_KARMA_META_GRAMMAR_MAR_05_2007_0436PM)
#define BOOST_SPIRIT_KARMA_META_GRAMMAR_MAR_05_2007_0436PM
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
#pragma once // MS compatible compilers support #pragma once
#endif
#include <boost/spirit/home/support/nonterminal/nonterminal.hpp>
#include <boost/spirit/home/karma/nonterminal/nonterminal.hpp>
#include <boost/spirit/home/karma/domain.hpp>
#include <boost/spirit/home/support/meta_grammar.hpp>
#include <boost/utility/enable_if.hpp>
namespace boost { namespace spirit { namespace karma
{
///////////////////////////////////////////////////////////////////////////
// forwards
///////////////////////////////////////////////////////////////////////////
struct nonterminal_director;
template <typename Expr, typename Enable>
struct is_valid_expr;
template <typename Expr, typename Enable>
struct expr_transform;
///////////////////////////////////////////////////////////////////////////
// nonterminal meta-grammar
///////////////////////////////////////////////////////////////////////////
struct nonterminal_meta_grammar
: meta_grammar::terminal_rule<
karma::domain,
nonterminal_holder<proto::_, proto::_>,
nonterminal_director
>
{
};
///////////////////////////////////////////////////////////////////////////
// These specializations non-intrusively hook into the Karma meta-grammar.
// (see karma/meta_grammar.hpp)
///////////////////////////////////////////////////////////////////////////
template <typename Expr>
struct is_valid_expr<
Expr,
typename enable_if<
proto::matches<Expr, nonterminal_meta_grammar>
>::type
>
: mpl::true_
{
};
template <typename Expr>
struct expr_transform<
Expr,
typename enable_if<
proto::matches<Expr, nonterminal_meta_grammar>
>::type
>
: mpl::identity<nonterminal_meta_grammar>
{
};
}}}
#endif
| 33.273973 | 82 | 0.517085 | jaredhoberock |
389edfecf3adce37290f756b3fde829598f7c082 | 1,222 | cpp | C++ | src/Cancel.11/OutpThrd.cpp | jimbeveridge/multithreading | b092dde13968f91dfb9b86e3d7e760a50f799a96 | [
"MIT"
] | 2 | 2021-11-23T10:43:45.000Z | 2022-01-03T14:51:32.000Z | src/Cancel.11/OutpThrd.cpp | jimbeveridge/multithreading | b092dde13968f91dfb9b86e3d7e760a50f799a96 | [
"MIT"
] | null | null | null | src/Cancel.11/OutpThrd.cpp | jimbeveridge/multithreading | b092dde13968f91dfb9b86e3d7e760a50f799a96 | [
"MIT"
] | 1 | 2020-10-28T15:11:55.000Z | 2020-10-28T15:11:55.000Z | /*
* OutpThrd.cpp
*
* Sample code for "Multithreading Applications in Win32"
* This is from Chapter 11. This sample is discussed in
* the text, but there is no associated listing.
*
* Launch a dialog in another thread using both
* MFC and Win32. Demonstrate the related problems.
*/
#include "stdafx.h"
#include "Cancel.h"
#include "OutpThrd.h"
#include "OutDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
/////////////////////////////////////////////////////////////////////////////
// COutputCancelDlgThread
IMPLEMENT_DYNCREATE(COutputCancelDlgThread, CWinThread)
COutputCancelDlgThread::COutputCancelDlgThread()
{
}
COutputCancelDlgThread::~COutputCancelDlgThread()
{
}
BOOL COutputCancelDlgThread::InitInstance()
{
m_pDlg->Go();
return TRUE;
}
int COutputCancelDlgThread::ExitInstance()
{
// TODO: perform any per-thread cleanup here
return CWinThread::ExitInstance();
}
BEGIN_MESSAGE_MAP(COutputCancelDlgThread, CWinThread)
//{{AFX_MSG_MAP(COutputCancelDlgThread)
// NOTE - the ClassWizard will add and remove mapping macros here.
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// COutputCancelDlgThread message handlers
| 22.218182 | 77 | 0.667758 | jimbeveridge |
389f714370be975472e2f654a71ef11cd3a31abf | 399 | hpp | C++ | library/ATF/$2E938192DD5FA5274C06DCBFB060397F.hpp | lemkova/Yorozuya | f445d800078d9aba5de28f122cedfa03f26a38e4 | [
"MIT"
] | 29 | 2017-07-01T23:08:31.000Z | 2022-02-19T10:22:45.000Z | library/ATF/$2E938192DD5FA5274C06DCBFB060397F.hpp | kotopes/Yorozuya | 605c97d3a627a8f6545cc09f2a1b0a8afdedd33a | [
"MIT"
] | 90 | 2017-10-18T21:24:51.000Z | 2019-06-06T02:30:33.000Z | library/ATF/$2E938192DD5FA5274C06DCBFB060397F.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 <__GENERIC_BINDING_INFO.hpp>
START_ATF_NAMESPACE
union $2E938192DD5FA5274C06DCBFB060397F
{
void **pAutoHandle;
void **pPrimitiveHandle;
__GENERIC_BINDING_INFO *pGenericBindingInfo;
};
END_ATF_NAMESPACE
| 24.9375 | 108 | 0.741855 | lemkova |
38a14db8c58a9b74ebff7e08eb548894d3ea62aa | 655 | hpp | C++ | headers/Helpers.hpp | DetlevCM/chemical-kinetics-solver | 7010fd6c72c29a0d912ad0c353ff13a5b643cc04 | [
"MIT"
] | 3 | 2015-07-03T20:14:00.000Z | 2021-02-02T13:45:31.000Z | headers/Helpers.hpp | DetlevCM/chemical-kinetics-solver | 7010fd6c72c29a0d912ad0c353ff13a5b643cc04 | [
"MIT"
] | null | null | null | headers/Helpers.hpp | DetlevCM/chemical-kinetics-solver | 7010fd6c72c29a0d912ad0c353ff13a5b643cc04 | [
"MIT"
] | 4 | 2017-11-09T19:49:18.000Z | 2020-08-04T18:29:28.000Z | /*
* Helpers.h
*
* Created on: 14 May 2016
* Author: DetlevCM
*/
#ifndef HEADERS_HELPERS_HPP_
#define HEADERS_HELPERS_HPP_
string Strip_Single_Line_Comments(
string input ,
vector<string> tokens
);
vector< string > Tokenise_String_To_String(
string input,
string tokens
);
void Tokenise_String_To_String_Append(
vector< string >& data ,
string input, string tokens
);
vector< double > Tokenise_String_To_Double(
string input,
string tokens
);
bool Line_Not_Comment_Or_Empty(
string InputLine
);
bool Test_If_Word_Found(
string string_to_search,
string search_term
);
#endif /* HEADERS_HELPERS_HPP_ */
| 15.595238 | 43 | 0.729771 | DetlevCM |
38a4d815f10abe02d871cd6aa75742802053f007 | 613 | cpp | C++ | Baekjoon/4435.cpp | Twinparadox/AlgorithmProblem | 0190d17555306600cfd439ad5d02a77e663c9a4e | [
"MIT"
] | null | null | null | Baekjoon/4435.cpp | Twinparadox/AlgorithmProblem | 0190d17555306600cfd439ad5d02a77e663c9a4e | [
"MIT"
] | null | null | null | Baekjoon/4435.cpp | Twinparadox/AlgorithmProblem | 0190d17555306600cfd439ad5d02a77e663c9a4e | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int main(void)
{
int t, g, s, gan[6] = { 1,2,3,3,4,10 }, sa[7] = { 1,2, 2,2,3,5,10 }, ganScore, saScore;
cin >> t;
for (int i = 1; i <= t; i++)
{
ganScore = saScore = 0;
for (int i = 0; i < 6; i++)
{
cin >> g;
ganScore += gan[i] * g;
}
for (int i = 0; i < 7; i++)
{
cin >> s;
saScore += sa[i] * s;
}
cout << "Battle " << i << ": ";
if (ganScore > saScore)
cout << "Good triumphs over Evil\n";
else if (ganScore == saScore)
cout << "No victor on this battle field\n";
else
cout << "Evil eradicates all trace of Good\n";
}
}
| 20.433333 | 88 | 0.508972 | Twinparadox |
38a853c44610e67fd150d156764179bd78e6e502 | 5,874 | cpp | C++ | UMLEditor/UMLLabelPropertyDialog.cpp | pmachapman/Tulip | 54f7bc3e8d5bb452ed8de6e6622e23d5e9be650a | [
"Unlicense"
] | null | null | null | UMLEditor/UMLLabelPropertyDialog.cpp | pmachapman/Tulip | 54f7bc3e8d5bb452ed8de6e6622e23d5e9be650a | [
"Unlicense"
] | 33 | 2018-09-14T21:58:20.000Z | 2022-01-12T21:39:22.000Z | UMLEditor/UMLLabelPropertyDialog.cpp | pmachapman/Tulip | 54f7bc3e8d5bb452ed8de6e6622e23d5e9be650a | [
"Unlicense"
] | null | null | null | /* ==========================================================================
Class : CUMLLabelPropertyDialog
Author : Johan Rosengren, Abstrakt Mekanik AB
Date : 2004-04-29
Purpose : "CUMLLabelPropertyDialog" is a dialog box wrapper derived
from "CDiagramPropertyDlg", used by "CUMLEntity"-
derived objects to edit the object title attribute.
Description : Class-Wizard created class.
Usage : In the "CUMLEntity"-derived class, add a member of
the "CUMLLabelPropertyDialog"-derived class, and call
"SetPropertyDialog" in the constructor.
The dialog template with the resource id
"IDD_UML_DIALOG_PROPERTY_LABEL" must be added to the project.
========================================================================*/
#include "stdafx.h"
#include "UMLLabelPropertyDialog.h"
#include "UMLEntityLabel.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CUMLLabelPropertyDialog dialog
CUMLLabelPropertyDialog::CUMLLabelPropertyDialog(CWnd* pParent /*=NULL*/)
: CDiagramPropertyDlg(CUMLLabelPropertyDialog::IDD, pParent)
/* ============================================================
Function : CUMLLabelPropertyDialog::CUMLLabelPropertyDialog
Description : Constructor
Access : Public
Return : void
Parameters : CWnd* pParent - Dialog parent
Usage :
============================================================*/
{
//{{AFX_DATA_INIT(CUMLLabelPropertyDialog)
m_text = _T("");
//}}AFX_DATA_INIT
m_pointsize = 12;
m_bold = FALSE;
m_italic = FALSE;
m_underline = FALSE;
}
CUMLLabelPropertyDialog::~CUMLLabelPropertyDialog()
/* ============================================================
Function : CUMLLabelPropertyDialog::~CUMLLabelPropertyDialog
Description : Destructor
Access : Public
Return : void
Parameters : none
Usage :
============================================================*/
{
}
void CUMLLabelPropertyDialog::DoDataExchange(CDataExchange* pDX)
/* ============================================================
Function : CUMLLabelPropertyDialog::DoDataExchange
Description : MFC data exchange handler.
Access : Protected
Return : void
Parameters : CDataExchange* pDX - Pointer to exchange object
Usage : Called from MFC to exchange and validate
dialog data.
============================================================*/
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CUMLLabelPropertyDialog)
DDX_Text(pDX, IDC_EDIT_TEXT, m_text);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CUMLLabelPropertyDialog, CDialog)
//{{AFX_MSG_MAP(CUMLLabelPropertyDialog)
ON_BN_CLICKED(IDC_BUTTON_FONT, OnButtonFont)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CUMLLabelPropertyDialog message handlers
void CUMLLabelPropertyDialog::OnOK()
/* ============================================================
Function : CUMLLabelPropertyDialog::OnOK
Description : Called when the Apply-key is pressed.
Access : Protected
Return : void
Parameters : none
Usage : Called from MFC. Updates the attached object
and hides the modeless dialog.
============================================================*/
{
CUMLEntityLabel* uml = static_cast<CUMLEntityLabel*>(GetEntity());
UpdateData();
uml->SetTitle(m_text);
uml->SetFont(m_font);
uml->SetBold(m_bold);
uml->SetItalic(m_italic);
uml->SetUnderline(m_underline);
uml->SetPointsize(m_pointsize);
Redraw();
ShowWindow(SW_HIDE);
GetRedrawWnd()->SetFocus();
}
void CUMLLabelPropertyDialog::OnCancel()
/* ============================================================
Function : CUMLLabelPropertyDialog::OnCancel
Description : Called when the ESC-key is pressed.
Access : Protected
Return : void
Parameters : none
Usage : Called from MFC. Overridden to close the
dialog.
============================================================*/
{
CDialog::OnCancel();
GetRedrawWnd()->SetFocus();
}
/////////////////////////////////////////////////////////////////////////////
// CUMLLabelPropertyDialog overrides
void CUMLLabelPropertyDialog::SetValues()
/* ============================================================
Function : CUMLLabelPropertyDialog::SetValues
Description : Set the values in the dialog from the
attached object.
Access : Public
Return : void
Parameters : none
Usage : Will be called by the framework and the
attached object to initialize the dialog.
The editbox is filled with the contents of
the object title attribute.
============================================================*/
{
CUMLEntityLabel* uml = static_cast<CUMLEntityLabel*>(GetEntity());
m_text = uml->GetTitle();
m_font = uml->GetFont();
m_pointsize = uml->GetPointsize();
m_bold = uml->GetBold();
m_italic = uml->GetItalic();
m_underline = uml->GetUnderline();
}
void CUMLLabelPropertyDialog::OnButtonFont()
/* ============================================================
Function : CUMLLabelPropertyDialog::OnButtonFont
Description : Handler for the dialog button Font
Access : Protected
Return : void
Parameters : none
Usage : Called from MFC.
============================================================*/
{
CFont font;
CUMLEntityLabel* uml = static_cast<CUMLEntityLabel*>(GetEntity());
font.CreatePointFont(m_pointsize * 10, uml->GetFont());
LOGFONT lf;
font.GetLogFont(&lf);
lf.lfItalic = (BYTE)m_italic;
lf.lfUnderline = (BYTE)m_underline;
if (m_bold)
lf.lfWeight = FW_BOLD;
CFontDialog dlg(&lf);
if (dlg.DoModal() == IDOK)
{
m_font = dlg.GetFaceName();
m_pointsize = dlg.GetSize() / 10;
m_bold = dlg.IsBold();
m_italic = dlg.IsItalic();
m_underline = dlg.IsUnderline();
}
}
| 25.876652 | 77 | 0.575928 | pmachapman |
38b2d9be5f12e42bd1ad20e6df8165438fe6068b | 1,308 | hpp | C++ | Source/Gui/DictionaryPanel.hpp | alvinahmadov/Dixter | 6f98f1e84192e1e43eee409bdee6b3dac75d6443 | [
"MIT"
] | 4 | 2018-12-06T01:20:50.000Z | 2019-08-04T10:19:23.000Z | Source/Gui/DictionaryPanel.hpp | alvinahmadov/Dixter | 6f98f1e84192e1e43eee409bdee6b3dac75d6443 | [
"MIT"
] | null | null | null | Source/Gui/DictionaryPanel.hpp | alvinahmadov/Dixter | 6f98f1e84192e1e43eee409bdee6b3dac75d6443 | [
"MIT"
] | null | null | null | /**
* Copyright (C) 2015-2019
* Author Alvin Ahmadov <[email protected]>
*
* This file is part of Dixter Project
* License-Identifier: MIT License
* See README.md for more information.
*/
#pragma once
#include "Gui/Panel.hpp"
#include "Gui/OptionBox.hpp"
class QMutex;
namespace Dixter
{
enum class EWidgetID;
template<
typename T,
typename ID
>
class TGroup;
namespace Gui
{
class TDictionaryPanel : public APanel
{
Q_OBJECT
private:
using WidgetGroup = TGroup<QWidget, EWidgetID>;
using GridGroup = TGroup<QLayout, EWidgetID>;
public:
explicit TDictionaryPanel(QWidget* parent, int width = -1, int height = -1,
const QString& name = QString());
virtual ~TDictionaryPanel() override;
void show(bool show = true);
TOptionBoxPtr
getOptionBox(EWidgetID widgetID);
QWidget* getWidget(EWidgetID id);
protected:
void init() override;
void connectEvents() override;
void setValues();
void onCopyButton(void);
void onClearButton(void);
void onLanguageChange(void);
protected slots:
void onSearch() noexcept;
private:
bool m_isLanguageSet;
GridGroup* m_grids;
WidgetGroup* m_widgets;
};
} // namespace Gui
} // namespace Dixter | 17.917808 | 78 | 0.66208 | alvinahmadov |
38b3726773f8ecbccf841798e0925e4d1a1dc220 | 519 | hpp | C++ | include/Micron/Prim.hpp | khuldraeseth/micron | e3f55c69a5546c4bba2b306775b8271880677640 | [
"Unlicense"
] | null | null | null | include/Micron/Prim.hpp | khuldraeseth/micron | e3f55c69a5546c4bba2b306775b8271880677640 | [
"Unlicense"
] | null | null | null | include/Micron/Prim.hpp | khuldraeseth/micron | e3f55c69a5546c4bba2b306775b8271880677640 | [
"Unlicense"
] | null | null | null | #pragma once
#include <functional>
#include <utility>
#include <Data/Either.hpp>
#include <Data/String.hpp>
#include <Micron/Error.hpp>
template <typename A>
struct Micron {
using Fn = std::function<std::pair<String,Either<Error,A>>(String)>;
Fn fn {};
};
auto const runMicron = [](auto ma, auto s) {
return ma.fn(s).second;
};
template <typename T> struct UnMicron {};
template <typename T> struct UnMicron<Micron<T>> { using type = T; };
template <typename T> using UnMicronT = UnMicron<T>::type;
| 19.961538 | 72 | 0.680154 | khuldraeseth |
38b682f70b633abba3eba5436fe16bb46d62e197 | 2,473 | cpp | C++ | buildinfo.cpp | FrostDragon/JenkinsPlugin | a3179a188ef4b5d4bd57adec5a765d485faa7ac4 | [
"MIT"
] | 2 | 2020-06-25T21:58:45.000Z | 2021-01-07T11:20:37.000Z | buildinfo.cpp | FrostDragon/JenkinsPlugin | a3179a188ef4b5d4bd57adec5a765d485faa7ac4 | [
"MIT"
] | 4 | 2016-05-25T09:35:47.000Z | 2016-06-20T00:20:32.000Z | buildinfo.cpp | FrostDragon/JenkinsPlugin | a3179a188ef4b5d4bd57adec5a765d485faa7ac4 | [
"MIT"
] | 1 | 2020-06-25T20:49:38.000Z | 2020-06-25T20:49:38.000Z | #include "buildinfo.h"
#include "jenkinspluginconstants.h"
using namespace JenkinsCI::Internal;
QString BuildInfo::url() const { return _url; }
void BuildInfo::setUrl(const QString &url) { _url = url; }
int BuildInfo::number() const { return _number; }
void BuildInfo::setNumber(int number) { _number = number; }
QDateTime BuildInfo::timestamp() const { return _timestamp; }
void BuildInfo::setTimestamp(const QDateTime ×tamp) { _timestamp = timestamp; }
void BuildInfo::setTimestamp(const qint64 timestamp)
{
_timestamp = QDateTime::fromMSecsSinceEpoch(timestamp);
}
BuildInfo::Result BuildInfo::result() const { return _result; }
QString BuildInfo::getResultIcon() const
{
switch (_result)
{
case Result::Success:
return QLatin1String(JenkinsCI::Constants::SUCCESS_ICON);
case Result::Failure:
return QLatin1String(JenkinsCI::Constants::FAIL_ICON);
case Result::Unstable:
return QLatin1String(JenkinsCI::Constants::UNSTABLE_ICON);
case Result::NotBuilt:
case Result::Aborted:
case Result::Unknown:
return QLatin1String(JenkinsCI::Constants::NOT_BUILT_ICON);
}
return QLatin1String(JenkinsCI::Constants::NOT_BUILT_ICON);
}
void BuildInfo::setResult(const Result &result) { _result = result; }
void BuildInfo::setResult(const QString &result)
{
if (result == QStringLiteral("SUCCESS"))
_result = Result::Success;
else if (result == QStringLiteral("ABORTED"))
_result = Result::Aborted;
else if (result == QStringLiteral("FAILURE"))
_result = Result::Failure;
else if (result == QStringLiteral("NOT_BUILT"))
_result = Result::NotBuilt;
else if (result == QStringLiteral("UNSTABLE"))
_result = Result::Unstable;
else
_result = Result::Unknown;
}
QString BuildInfo::displayName() const { return _displayName; }
void BuildInfo::setDisplayName(const QString &displayName) { _displayName = displayName; }
QString BuildInfo::fullDisplayName() const { return _fullDisplayName; }
void BuildInfo::setFullDisplayName(const QString &fullDisplayName)
{
_fullDisplayName = fullDisplayName;
}
QString BuildInfo::description() const { return _description; }
void BuildInfo::setDescription(const QString &description) { _description = description; }
int BuildInfo::duration() const { return _duration; }
void BuildInfo::setDuration(int duration) { _duration = duration; }
| 30.9125 | 90 | 0.708856 | FrostDragon |
38b9048b9d15c7584d4a2209bada86d74b7c2e22 | 1,834 | cpp | C++ | src/checker.cpp | ammarfaizi2/ProxyScraper | 3a303f70d283833c96b3dd6c9b52c322865b946f | [
"MIT"
] | 3 | 2018-10-14T17:27:49.000Z | 2018-10-19T22:39:54.000Z | src/checker.cpp | cppid/ProxyScraper | 3a303f70d283833c96b3dd6c9b52c322865b946f | [
"MIT"
] | null | null | null | src/checker.cpp | cppid/ProxyScraper | 3a303f70d283833c96b3dd6c9b52c322865b946f | [
"MIT"
] | 1 | 2018-10-15T07:15:52.000Z | 2018-10-15T07:15:52.000Z |
#include <sys/file.h>
#include <sys/wait.h>
#include <unistd.h>
#include "lib/TeaCurl.h"
#include "lib/TeaPCRE.h"
int check(int argc, char *argv[]) {
int worker_limit = 5;
for (int i = 0; i < 2; ++i)
{
int pid = fork();
if (pid == 0) {
char *filename = (char*)malloc(64);
sprintf(argv[0], "checkerd_run --file=uncheck_%d.tmp --worker-limit=%d", i, worker_limit);
sprintf(filename, "uncheck_%d.tmp", i);
FILE *handle = fopen(filename, "r");
flock(fileno(handle), LOCK_SH);
char *buff = (char*)malloc(8);
char *ip = (char*)malloc(64);
char *port = (char*)malloc(32);
char *country = (char*)malloc(256);
int gotIp = 0;
int workers = 0;
while (!feof(handle)) {
size_t rbt = fread(buff, 1, sizeof(char), handle);
if (rbt) {
buff[1] = '\0';
if (buff[0] != '|' && (!gotIp)) {
strcat(ip, buff);
} else if (buff[0] == '|' && (!gotIp)) {
gotIp = 1;
} else if (buff[0] == '|' && gotIp) {
while(rbt) {
rbt = fread(buff, 1, sizeof(char), handle);
buff[1] = '\0';
if (buff[0] == '\n') break;
if (buff[0] == ' ') buff[0] = '_';
strcat(country, buff);
}
int chPid = fork();
workers++;
if (chPid == 0) {
sprintf(argv[0], "checker_worker --ip=%s --port=%s", ip, port);
printf("%s:%s %s\n", ip, port, country);
sleep(10);
exit(0);
}
if (workers == worker_limit)
{
wait(NULL);
workers = 0;
}
gotIp = 0;
delete ip;
delete port;
delete country;
ip = (char*)malloc(64);
port = (char*)malloc(32);
country = (char*)malloc(256);
} else {
strcat(port, buff);
}
}
}
flock(fileno(handle), LOCK_UN);
fclose(handle);
exit(0);
}
}
wait(NULL);
return 0;
}
| 21.833333 | 93 | 0.502181 | ammarfaizi2 |
38ba50287c2408a1e00f6095ad3194f217dd4ac7 | 1,054 | cpp | C++ | Project/ModuleRNG.cpp | albertllopart/GTi-Engine-Reborn | 87d3137866488075f534e50a9480180d1f6354c0 | [
"MIT"
] | 1 | 2020-03-19T18:07:32.000Z | 2020-03-19T18:07:32.000Z | Project/ModuleRNG.cpp | albertllopart/GTi-Engine-Reborn | 87d3137866488075f534e50a9480180d1f6354c0 | [
"MIT"
] | null | null | null | Project/ModuleRNG.cpp | albertllopart/GTi-Engine-Reborn | 87d3137866488075f534e50a9480180d1f6354c0 | [
"MIT"
] | null | null | null | #include "Globals.h"
#include "Application.h"
#include "ModuleRNG.h"
#include "parson/parson.h"
#include "Glew/include/glew.h"
#include <list>
ModuleRNG::ModuleRNG(Application* app, bool start_enabled) : Module(app, start_enabled)
{
name = "Rng";
}
// Destructor
ModuleRNG::~ModuleRNG()
{}
// Called before render is available
bool ModuleRNG::Init(JSON_Object* node)
{
LOG("Loading RNG");
App->imgui->AddConsoleLog("Loading RNG");
bool ret = true;
return ret;
}
bool ModuleRNG::Start()
{
pcg32_srandom_r(&seed, NULL, (intptr_t)&seed);
return true;
}
// Called before quitting
bool ModuleRNG::CleanUp()
{
LOG("Freeing RNG");
App->imgui->AddConsoleLog("Freeing RNG");
return true;
}
update_status ModuleRNG::Update(float dt)
{
return UPDATE_CONTINUE;
}
float ModuleRNG::RandomFloat()
{
return ldexp(pcg32_random_r(&floatseed), -32);
}
uint32_t ModuleRNG::RandomInt(int min, int max)
{
uint bound = max - min + 1;
return pcg32_boundedrand_r(&intbound, bound);
}
uint32_t ModuleRNG::Random32()
{
return pcg32_random_r(&seed);
}
| 15.969697 | 87 | 0.712524 | albertllopart |
38bbab352f6e8387485c5f0c5ce286419199909b | 4,460 | cpp | C++ | source/game/GLSLProgram.cpp | WarzesProject/2dgame | 7c398505bd02f9c519f2968bceb3ba87ac26a6a5 | [
"MIT"
] | null | null | null | source/game/GLSLProgram.cpp | WarzesProject/2dgame | 7c398505bd02f9c519f2968bceb3ba87ac26a6a5 | [
"MIT"
] | null | null | null | source/game/GLSLProgram.cpp | WarzesProject/2dgame | 7c398505bd02f9c519f2968bceb3ba87ac26a6a5 | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "GLSLProgram.h"
#include "IOManager.h"
//-----------------------------------------------------------------------------
void GLSLProgram::CompileShadersFromFile(std::string_view vertexShaderFilePath, std::string_view fragmentShaderFilePath)
{
std::string vertexSource;
std::string fragSource;
IOManager::ReadFileToBuffer(vertexShaderFilePath, vertexSource);
IOManager::ReadFileToBuffer(fragmentShaderFilePath, fragSource);
CompileShadersFromSource(vertexSource, fragSource);
}
//-----------------------------------------------------------------------------
void GLSLProgram::CompileShadersFromSource(std::string_view vertexSource, std::string_view fragmentSource)
{
m_programID = glCreateProgram();
m_vertexShaderID = glCreateShader(GL_VERTEX_SHADER);
if ( m_vertexShaderID == 0 )
Throw("Vertex shader failed to be created!");
m_fragmentShaderID = glCreateShader(GL_FRAGMENT_SHADER);
if ( m_fragmentShaderID == 0 )
Throw("Fragment shader failed to be created!");
compileShaders(vertexSource.data(), "Vertex shader", m_vertexShaderID);
compileShaders(fragmentSource.data(), "Fragment shader", m_fragmentShaderID);
}
//-----------------------------------------------------------------------------
void GLSLProgram::LinkShaders()
{
//Attach our shaders to our program
glAttachShader(m_programID, m_vertexShaderID);
glAttachShader(m_programID, m_fragmentShaderID);
//Link our program
glLinkProgram(m_programID);
//Note the different functions here: glGetProgram* instead of glGetShader*.
GLint isLinked = 0;
glGetProgramiv(m_programID, GL_LINK_STATUS, (int *)&isLinked);
if ( isLinked == GL_FALSE )
{
GLint maxLength = 0;
glGetProgramiv(m_programID, GL_INFO_LOG_LENGTH, &maxLength);
//The maxLength includes the NULL character
std::vector<GLchar> errorLog(maxLength);
glGetProgramInfoLog(m_programID, maxLength, &maxLength, &errorLog[0]);
//We don't need the program anymore.
glDeleteProgram(m_programID);
//Don't leak shaders either.
glDeleteShader(m_vertexShaderID);
glDeleteShader(m_fragmentShaderID);
Throw(&(errorLog[0]) + std::string("\nShader failed to link!"));
}
//Always detach shaders after a successful link.
glDetachShader(m_programID, m_vertexShaderID);
glDetachShader(m_programID, m_fragmentShaderID);
glDeleteShader(m_vertexShaderID);
glDeleteShader(m_fragmentShaderID);
}
//-----------------------------------------------------------------------------
void GLSLProgram::AddAttribute(std::string_view attributeName)
{
glBindAttribLocation(m_programID, m_numAttributtes++, attributeName.data());
}
//-----------------------------------------------------------------------------
GLint GLSLProgram::GetUniformLocation(std::string_view uniformName)
{
GLint location = glGetUniformLocation(m_programID, uniformName.data());
if ( location == GL_INVALID_INDEX )
Throw("Uniform " + std::string(uniformName.data()) + " not found in shader!");
return location;
}
//-----------------------------------------------------------------------------
void GLSLProgram::Use()
{
glUseProgram(m_programID);
for ( int i = 0; i < m_numAttributtes; i++ )
glEnableVertexAttribArray(i);
}
//-----------------------------------------------------------------------------
void GLSLProgram::Unuse()
{
glUseProgram(0);
for ( int i = 0; i < m_numAttributtes; i++ )
glDisableVertexAttribArray(i);
}
//-----------------------------------------------------------------------------
void GLSLProgram::Dispose()
{
if ( m_programID )
glDeleteProgram(m_programID);
m_numAttributtes = 0;
}
//-----------------------------------------------------------------------------
void GLSLProgram::compileShaders(const char* source, std::string_view name, const GLuint &id)
{
glShaderSource(id, 1, &source, nullptr);
glCompileShader(id);
GLint isCompiled = 0;
glGetShaderiv(id, GL_COMPILE_STATUS, &isCompiled);
if ( isCompiled == GL_FALSE )
{
GLint maxLength = 0;
glGetShaderiv(id, GL_INFO_LOG_LENGTH, &maxLength);
// The maxLength includes the NULL character
std::vector<GLchar> errorLog(maxLength);
glGetShaderInfoLog(id, maxLength, &maxLength, &errorLog[0]);
// Provide the infolog in whatever manor you deem best.
// Exit with failure.
glDeleteShader(id); // Don't leak the shader.
Throw(&(errorLog[0]) + std::string("Shader ") + name.data() + " failed to compile!");
}
}
//----------------------------------------------------------------------------- | 34.573643 | 120 | 0.62287 | WarzesProject |
38bbc9c37252aee9a3cf06244c691dac181b6fcd | 53,444 | cpp | C++ | source/DSES/ExecutionControl.cpp | jiajlin/TrickHLA | ae704b97049579e997593ae6d8dd016010b8fa1e | [
"NASA-1.3"
] | null | null | null | source/DSES/ExecutionControl.cpp | jiajlin/TrickHLA | ae704b97049579e997593ae6d8dd016010b8fa1e | [
"NASA-1.3"
] | null | null | null | source/DSES/ExecutionControl.cpp | jiajlin/TrickHLA | ae704b97049579e997593ae6d8dd016010b8fa1e | [
"NASA-1.3"
] | null | null | null | /*!
@file DSES/ExecutionControl.cpp
@ingroup DSES
@brief This class provides and abstract base class as the base implementation
for managing mode transitions.
@copyright Copyright 2019 United States Government as represented by the
Administrator of the National Aeronautics and Space Administration.
No copyright is claimed in the United States under Title 17, U.S. Code.
All Other Rights Reserved.
\par<b>Responsible Organization</b>
Simulation and Graphics Branch, Mail Code ER7\n
Software, Robotics & Simulation Division\n
NASA, Johnson Space Center\n
2101 NASA Parkway, Houston, TX 77058
@tldh
@trick_link_dependency{../TrickHLA/DebugHandler.cpp}
@trick_link_dependency{../TrickHLA/SyncPntListBase.cpp}
@trick_link_dependency{../TrickHLA/SleepTimeout.cpp}
@trick_link_dependency{ExecutionControl.cpp}
@revs_title
@revs_begin
@rev_entry{Edwin Z. Crues, NASA ER7, TrickHLA, Jan 2019, --, DSES support and testing.}
@rev_entry{Edwin Z. Crues, NASA ER7, TrickHLA, June 2019, --, Version 3 rewrite.}
@revs_end
*/
// System include files.
#include <iomanip>
#include <math.h>
// Trick includes.
#include "trick/Executive.hh"
#include "trick/exec_proto.hh"
#include "trick/message_proto.h"
// HLA include files.
// TrickHLA include files.
#include "TrickHLA/DebugHandler.hh"
#include "TrickHLA/Federate.hh"
#include "TrickHLA/Int64Interval.hh"
#include "TrickHLA/Manager.hh"
#include "TrickHLA/SleepTimeout.hh"
#include "TrickHLA/StringUtilities.hh"
#include "TrickHLA/Types.hh"
#include "TrickHLA/Utilities.hh"
// DSES include files.
#include "DSES/ExecutionConfiguration.hh"
#include "DSES/ExecutionControl.hh"
// IMSim file level declarations.
namespace DSES
{
// ExecutionControl type string.
const std::string ExecutionControl::type = "DSES";
// The DSES Multiphase initialization HLA synchronization-points.
static const std::wstring SIM_CONFIG_SYNC_POINT = L"sim_config";
static const std::wstring INITIALIZE_SYNC_POINT = L"initialize";
static const std::wstring STARTUP_SYNC_POINT = L"startup";
} // namespace DSES
using namespace std;
using namespace RTI1516_NAMESPACE;
using namespace TrickHLA;
using namespace DSES;
/*!
* @job_class{initialization}
*/
ExecutionControl::ExecutionControl()
: time_padding( 5.0 ),
mode_transition_requested( false ),
pending_mtr( DSES::MTR_UNINITIALIZED ),
requested_execution_control_mode( EXECUTION_CONTROL_UNINITIALIZED ),
current_execution_control_mode( EXECUTION_CONTROL_UNINITIALIZED ),
next_mode_scenario_time( -std::numeric_limits< double >::max() ),
next_mode_cte_time( -std::numeric_limits< double >::max() ),
simulation_freeze_time( 0.0 ),
scenario_freeze_time( 0.0 ),
late_joiner( false ),
late_joiner_determined( false ),
federate( NULL )
{
return;
}
/*!
* @job_class{shutdown}
*/
ExecutionControl::~ExecutionControl()
{
clear_mode_values();
}
/*!
@details This routine will set a lot of the data in the TrickHLA::Federate that
is required for this execution control scheme. This should greatly simplify
input files and reduce input file setting errors.
@job_class{initialization}
*/
void ExecutionControl::initialize()
{
if ( DebugHandler::show( DEBUG_LEVEL_2_TRACE, DEBUG_SOURCE_EXECUTION_CONTROL ) ) {
ostringstream msg;
msg << "DSES::ExecutionControl::initialize():" << __LINE__
<< " Initialization-Scheme:'" << get_type()
<< "'" << THLA_ENDL;
send_hs( stdout, (char *)msg.str().c_str() );
}
// Set the reference to the TrickHLA::Federate.
this->federate = &fed;
// Initialize the ExecutionControl so that it knows about the manager.
this->execution_configuration->initialize( this->get_manager() );
// There are things that must me set for the DSES initialization.
this->use_preset_master = true;
// If this is the Master federate, then it must support Time
// Management and be both Time Regulating and Time Constrained.
if ( this->is_master() ) {
federate->time_management = true;
federate->time_regulating = true;
federate->time_constrained = true;
// The software frame is set from the ExCO Least Common Time Step.
// For the Master federate the Trick simulation software frame must
// match the Least Common Time Step (LCTS).
double software_frame_time = Int64Interval::to_seconds( least_common_time_step );
exec_set_software_frame( software_frame_time );
}
// Add the Mode Transition Request synchronization points.
this->add_sync_pnt( L"mtr_run" );
this->add_sync_pnt( L"mtr_freeze" );
this->add_sync_pnt( L"mtr_shutdown" );
// Make sure we initialize the base class.
TrickHLA::ExecutionControlBase::initialize();
// Must use a preset master.
if ( !this->is_master_preset() ) {
ostringstream errmsg;
errmsg << "DSES::ExecutionControl::initialize(): WARNING:" << __LINE__
<< " Only a preset master is supported. Make sure to set"
<< " 'THLA.federate.use_preset_master = true' in your input file."
<< " Setting use_preset_master to true!"
<< THLA_ENDL;
send_hs( stdout, (char *)errmsg.str().c_str() );
this->use_preset_master = true;
}
if ( DebugHandler::show( DEBUG_LEVEL_2_TRACE, DEBUG_SOURCE_EXECUTION_CONTROL ) ) {
if ( this->is_master() ) {
send_hs( stdout, "DSES::ExecutionControl::initialize():%d\n I AM THE PRESET MASTER%c",
__LINE__, THLA_NEWLINE );
} else {
send_hs( stdout, "DSES::ExecutionControl::initialize():%d\n I AM NOT THE PRESET MASTER%c",
__LINE__, THLA_NEWLINE );
}
}
// Call the DSES ExecutionControl pre-multi-phase initialization processes.
pre_multi_phase_init_processes();
}
/*!
@details This routine implements the DSES Join Federation Process described
in section 7.2 and figure 7-3.
@job_class{initialization}
*/
void ExecutionControl::join_federation_process()
{
// The base class implementation is good enough for now.
TrickHLA::ExecutionControlBase::join_federation_process();
}
/*!
@details This routine implements the DSES pre multi-phase initialization process.
@job_class{initialization}
*/
void ExecutionControl::pre_multi_phase_init_processes()
{
if ( DebugHandler::show( DEBUG_LEVEL_2_TRACE, DEBUG_SOURCE_EXECUTION_CONTROL ) ) {
send_hs( stdout, "DSES::ExecutionControl::pre_multi_phase_init_processes():%d%c",
__LINE__, THLA_NEWLINE );
}
// Reset the sim-config required flag to make it required.
execution_configuration->mark_required();
// Reset the sim-config preferred-order for attributes to Receive-Order.
execution_configuration->reset_preferred_order();
// Reset the ownership flags and the attribute configuration flags for
// the simulation configuration object.
execution_configuration->reset_ownership_states();
// Setup all the Trick Ref-Attributes for the user specified objects,
// attributes, interactions and parameters.
get_manager()->setup_all_ref_attributes();
// Add the DSES multiphase initialization sync-points now that the
// Simulation-Configuration has been initialized in the call to
// the setup_all_ref_attributes() function. We do this here so
// that we can handle the RTI callbacks that use them.
this->add_multiphase_init_sync_points();
// Create the RTI Ambassador and connect.
federate->create_RTI_ambassador_and_connect();
// Destroy the federation if it was orphaned from a previous simulation
// run that did not shutdown cleanly.
federate->destroy_orphaned_federation();
// Create and then join the federation.
federate->create_and_join_federation();
// Don't forget to enable asynchronous delivery of messages.
federate->enable_async_delivery();
// Determine if this federate is the Master.
determine_federation_master();
// Setup all the RTI handles for the objects, attributes and interaction
// parameters.
get_manager()->setup_all_RTI_handles();
// Call publish_and_subscribe AFTER we've initialized the manager,
// federate, and FedAmb.
get_manager()->publish_and_subscribe();
// Reserve the RTI object instance names with the RTI, but only for
// the objects that are locally owned.
get_manager()->reserve_object_names_with_RTI();
// Waits on the reservation of the RTI object instance names for the
// locally owned objects. Calling this function will block until all
// the object instances names for the locally owned objects have been
// reserved.
get_manager()->wait_on_reservation_of_object_names();
// Creates an RTI object instance and registers it with the RTI, but
// only for the objects that are locally owned.
get_manager()->register_objects_with_RTI();
// Setup the preferred order for all object attributes and interactions.
get_manager()->setup_preferred_order_with_RTI();
// Waits on the registration of all the required RTI object instances with
// the RTI. Calling this function will block until all the required object
// instances in the Federation have been registered.
get_manager()->wait_on_registration_of_required_objects();
// Initialize the MOM interface handles.
federate->initialize_MOM_handles();
// Perform the next few steps if we are the Master federate.
if ( this->is_master() ) {
// Make sure all required federates have joined the federation.
(void)federate->wait_for_required_federates_to_join();
// Register the Multi-phase initialization sync-points.
this->register_all_sync_pnts( *federate->get_RTI_ambassador() );
}
// Wait for the "sim_config", "initialize", and "startup" sync-points
// to be registered.
this->wait_for_all_announcements( federate );
// Achieve the "sim_config" sync-point and wait for the federation
// to be synchronized on it.
federate->achieve_and_wait_for_synchronization( DSES::SIM_CONFIG_SYNC_POINT );
if ( this->is_master() ) {
// Send the "Simulation Configuration".
this->send_execution_configuration();
} else {
// Wait for the "Simulation Configuration" object attribute reflection.
this->receive_execution_configuration();
}
// Achieve the "initialize" sync-point and wait for the federation
// to be synchronized on it.
federate->achieve_and_wait_for_synchronization( DSES::INITIALIZE_SYNC_POINT );
}
/*!
@details This routine implements the DSES post multi-phase initialization process.
@job_class{initialization}
*/
void ExecutionControl::post_multi_phase_init_process()
{
// Setup HLA time management.
federate->setup_time_management();
// Achieve the "startup" sync-point and wait for the federation
// to be synchronized on it.
federate->achieve_and_wait_for_synchronization( DSES::STARTUP_SYNC_POINT );
}
/*!
* @job_class{shutdown}
*/
void ExecutionControl::shutdown()
{
return;
}
/*!
* @job_class{initialization}
*/
void ExecutionControl::setup_object_RTI_handles()
{
return;
}
/*!
* @job_class{initialization}
*/
void ExecutionControl::setup_interaction_RTI_handles()
{
return;
}
/*!
* @job_class{initialization}
*/
void ExecutionControl::add_multiphase_init_sync_points()
{
// Call the base class method to add user defined multi-phase
// initialization synchronization points.
ExecutionControlBase::add_multiphase_init_sync_points();
// Register initialization synchronization points used for startup regulation.
this->add_sync_pnt( DSES::STARTUP_SYNC_POINT );
this->add_sync_pnt( DSES::INITIALIZE_SYNC_POINT );
this->add_sync_pnt( DSES::SIM_CONFIG_SYNC_POINT );
}
void ExecutionControl::announce_sync_point(
RTI1516_NAMESPACE::RTIambassador &rti_ambassador,
wstring const & label,
RTI1516_USERDATA const & user_supplied_tag )
{
if ( this->contains( label ) ) {
// Mark init sync-point as announced.
if ( this->mark_announced( label ) ) {
if ( DebugHandler::show( DEBUG_LEVEL_2_TRACE, DEBUG_SOURCE_EXECUTION_CONTROL ) ) {
send_hs( stdout, "DSES::ExecutionControl::announce_sync_point():%d DSES Multiphase Init Sync-Point:'%ls'%c",
__LINE__, label.c_str(), THLA_NEWLINE );
}
}
} // By default, mark an unrecognized synchronization point as achieved.
else {
if ( DebugHandler::DebugHandler::show( DEBUG_LEVEL_2_TRACE, DEBUG_SOURCE_EXECUTION_CONTROL ) ) {
send_hs( stdout, "DSES::ExecutionControl::announce_sync_point():%d Unrecognized synchronization point:'%ls', which will be achieved.%c",
__LINE__, label.c_str(), THLA_NEWLINE );
}
// Unknown synchronization point so achieve it but don't wait for the
// federation to by synchronized on it.
this->achieve_sync_pnt( rti_ambassador, label );
}
}
/*!
* @job_class{initialization}
*/
void ExecutionControl::achieve_all_multiphase_init_sync_pnts(
RTI1516_NAMESPACE::RTIambassador &rti_ambassador )
{
// Iterate through this ExecutionControl's synchronization point list.
vector< SyncPnt * >::const_iterator i;
for ( i = sync_point_list.begin(); i != sync_point_list.end(); ++i ) {
SyncPnt *sp = ( *i );
// Achieve a synchronization point if it is not already achieved and is
// not one of the predefined ExecutionControl synchronization points.
if ( ( sp != NULL ) && sp->exists() && !sp->is_achieved()
&& ( sp->label.compare( DSES::STARTUP_SYNC_POINT ) != 0 )
&& ( sp->label.compare( DSES::INITIALIZE_SYNC_POINT ) != 0 )
&& ( sp->label.compare( DSES::SIM_CONFIG_SYNC_POINT ) != 0 ) ) {
// Achieve the synchronization point.
rti_ambassador.synchronizationPointAchieved( sp->label );
}
}
}
/*!
* @job_class{initialization}
*/
void ExecutionControl::wait_for_all_multiphase_init_sync_pnts()
{
// Iterate through this ExecutionControl's synchronization point list.
vector< SyncPnt * >::const_iterator i;
for ( i = sync_point_list.begin(); i != sync_point_list.end(); ++i ) {
SyncPnt *sp = ( *i );
// Wait for a synchronization point if it is not already achieved and is
// not one of the predefined ExecutionControl synchronization points.
if ( ( sp != NULL ) && sp->exists() && !sp->is_achieved()
&& ( sp->label.compare( DSES::STARTUP_SYNC_POINT ) != 0 )
&& ( sp->label.compare( DSES::INITIALIZE_SYNC_POINT ) != 0 )
&& ( sp->label.compare( DSES::SIM_CONFIG_SYNC_POINT ) != 0 ) ) {
SleepTimeout sleep_timer;
// Wait for the federation to synchronized on the sync-point.
while ( !sp->is_achieved() ) {
// Always check to see is a shutdown was received.
federate->check_for_shutdown_with_termination();
// Pause and release the processor for short sleep value.
(void)sleep_timer.sleep();
// Periodically check to make sure the federate is still part of
// the federation exectuion.
if ( !sp->is_achieved() && sleep_timer.timeout() ) {
sleep_timer.reset();
if ( !federate->is_execution_member() ) {
ostringstream errmsg;
errmsg << "DSES::ExecutionControl::wait_for_all_multiphase_init_sync_pnts:" << __LINE__
<< " ERROR: Unexpectedly the Federate is no longer an execution"
<< " member. This means we are either not connected to the"
<< " RTI or we are no longer joined to the federation"
<< " execution because someone forced our resignation at"
<< " the Central RTI Component (CRC) level!"
<< THLA_ENDL;
send_hs( stderr, (char *)errmsg.str().c_str() );
exec_terminate( __FILE__, (char *)errmsg.str().c_str() );
}
}
}
}
}
}
void ExecutionControl::publish()
{
return;
}
void ExecutionControl::unpublish()
{
return;
}
void ExecutionControl::subscribe()
{
return;
}
void ExecutionControl::unsubscribe()
{
return;
}
/*!
@job_class{initialization}
*/
bool ExecutionControlBase::object_instance_name_reservation_failed(
std::wstring const &obj_instance_name )
{
wstring ws_sim_config_name;
StringUtilities::to_wstring( ws_sim_config_name, execution_configuration->get_name() );
// For multiphase initialization version 1, we handle the SimConfig
// instance name reservation failure to help determine the master.
if ( obj_instance_name == ws_sim_config_name ) {
// We are NOT the Master federate since we failed to reserve the
// "SimConfig" name and only if the master was not preset.
if ( !this->is_master_preset() ) {
this->set_master( false );
}
// We failed to register the "SimConfig" name which means that another
// federate has already registered it.
execution_configuration->set_name_registered();
if ( DebugHandler::show( DEBUG_LEVEL_2_TRACE, DEBUG_SOURCE_EXECUTION_CONTROL ) ) {
send_hs( stdout, "DSES::ExecutionControl::object_instance_name_reservation_failed():%d Name:'%ls'%c",
__LINE__, obj_instance_name.c_str(), THLA_NEWLINE );
}
// Return 'true' since we found a match.
return ( true );
}
// Return 'false' since we did not find a match.
return ( false );
}
/*!
* @job_class{initialization}
*/
void ExecutionControl::determine_federation_master()
{
if ( DebugHandler::show( DEBUG_LEVEL_2_TRACE, DEBUG_SOURCE_EXECUTION_CONTROL ) ) {
send_hs( stdout, "DSES::ExecutionControl::determine_federation_master():%d%c",
__LINE__, THLA_NEWLINE );
}
// If we are not supposed to use a preset master, then reserve the SimConfig
// name so that we can determine the master. Also, if we are supposed to use
// a preset master and we are that master then go ahead and register the
// SimConfig name.
if ( !this->is_master_preset() || this->is_master() ) {
// Reserve "SimConfig" object instance name as a way of determining
// who the master federate is.
execution_configuration->reserve_object_name_with_RTI();
// Wait for success or failure for the "SimConfig" name reservation.
execution_configuration->wait_on_object_name_reservation();
}
// Setup the execution configuration object now that we know if we are the
// "Master" federate or not.
execution_configuration->set_master( this->is_master() );
if ( DebugHandler::show( DEBUG_LEVEL_2_TRACE, DEBUG_SOURCE_EXECUTION_CONTROL ) ) {
if ( this->is_master() ) {
send_hs( stdout, "DSES::ExecutionControl::determine_federation_master():%d\n I AM THE MASTER%c",
__LINE__, THLA_NEWLINE );
} else {
send_hs( stdout, "DSES::ExecutionControl::determine_federation_master():%d\n I AM NOT THE MASTER%c",
__LINE__, THLA_NEWLINE );
}
}
}
bool ExecutionControl::set_pending_mtr(
MTREnum mtr_value )
{
if ( this->is_mtr_valid( mtr_value ) ) {
this->pending_mtr = mtr_value;
}
return false;
}
bool ExecutionControl::is_mtr_valid(
MTREnum mtr_value )
{
ExecutionConfiguration *ExCO = get_execution_configuration();
switch ( mtr_value ) {
case MTR_GOTO_RUN: {
return ( ( ExCO->current_execution_mode == EXECUTION_MODE_INITIALIZING ) || ( ExCO->current_execution_mode == EXECUTION_MODE_FREEZE ) );
}
case MTR_GOTO_FREEZE: {
return ( ( ExCO->current_execution_mode == EXECUTION_MODE_INITIALIZING ) || ( ExCO->current_execution_mode == EXECUTION_MODE_RUNNING ) );
}
case MTR_GOTO_SHUTDOWN: {
return ( ExCO->current_execution_mode != EXECUTION_MODE_SHUTDOWN );
}
default: {
return false;
}
}
return false;
}
void ExecutionControl::set_mode_request_from_mtr(
MTREnum mtr_value )
{
switch ( mtr_value ) {
case MTR_UNINITIALIZED:
this->pending_mtr = MTR_UNINITIALIZED;
set_next_execution_control_mode( EXECUTION_CONTROL_UNINITIALIZED );
break;
case MTR_INITIALIZING:
this->pending_mtr = MTR_INITIALIZING;
set_next_execution_control_mode( EXECUTION_CONTROL_INITIALIZING );
break;
case MTR_GOTO_RUN:
this->pending_mtr = MTR_GOTO_RUN;
set_next_execution_control_mode( EXECUTION_CONTROL_RUNNING );
break;
case MTR_GOTO_FREEZE:
this->pending_mtr = MTR_GOTO_FREEZE;
set_next_execution_control_mode( EXECUTION_CONTROL_FREEZE );
break;
case MTR_GOTO_SHUTDOWN:
this->pending_mtr = MTR_GOTO_SHUTDOWN;
set_next_execution_control_mode( EXECUTION_CONTROL_SHUTDOWN );
break;
default:
this->pending_mtr = MTR_UNINITIALIZED;
break;
}
}
void ExecutionControl::set_next_execution_control_mode(
TrickHLA::ExecutionControlEnum exec_control )
{
// Reference the DSES Execution Configuration Object (ExCO)
ExecutionConfiguration *ExCO = get_execution_configuration();
// This should only be called by the Master federate.
if ( !this->is_master() ) {
ostringstream errmsg;
errmsg << "DSES::ExecutionControl::set_next_execution_mode():" << __LINE__
<< " ERROR: This should only be called by the Master federate!" << THLA_ENDL;
send_hs( stderr, (char *)errmsg.str().c_str() );
exec_terminate( __FILE__, (char *)errmsg.str().c_str() );
return;
}
switch ( exec_control ) {
case EXECUTION_CONTROL_UNINITIALIZED:
// Set the next execution mode.
this->requested_execution_control_mode = EXECUTION_CONTROL_UNINITIALIZED;
ExCO->set_next_execution_mode( EXECUTION_MODE_UNINITIALIZED );
// Set the next mode times.
this->next_mode_scenario_time = this->get_scenario_time(); // Immediate
ExCO->set_next_mode_scenario_time( this->get_scenario_time() ); // Immediate
ExCO->set_next_mode_cte_time( this->get_cte_time() ); // Immediate
break;
case EXECUTION_CONTROL_INITIALIZING:
// Set the next execution mode.
this->requested_execution_control_mode = EXECUTION_CONTROL_INITIALIZING;
ExCO->set_next_execution_mode( EXECUTION_MODE_INITIALIZING );
// Set the next mode times.
ExCO->set_scenario_time_epoch( this->get_scenario_time() ); // Now.
this->next_mode_scenario_time = this->get_scenario_time(); // Immediate
ExCO->set_next_mode_scenario_time( this->get_scenario_time() ); // Immediate
ExCO->set_next_mode_cte_time( this->get_cte_time() ); // Immediate
break;
case EXECUTION_CONTROL_RUNNING:
// Set the next execution mode.
this->requested_execution_control_mode = EXECUTION_CONTROL_RUNNING;
ExCO->set_next_execution_mode( EXECUTION_MODE_RUNNING );
// Set the next mode times.
this->next_mode_scenario_time = this->get_scenario_time(); // Immediate
ExCO->set_next_mode_scenario_time( this->next_mode_scenario_time ); // immediate
ExCO->set_next_mode_cte_time( this->get_cte_time() );
if ( ExCO->get_next_mode_cte_time() > -std::numeric_limits< double >::max() ) {
ExCO->set_next_mode_cte_time( ExCO->get_next_mode_cte_time() + this->time_padding ); // Some time in the future.
}
break;
case EXECUTION_CONTROL_FREEZE:
// Set the next execution mode.
this->requested_execution_control_mode = EXECUTION_CONTROL_FREEZE;
ExCO->set_next_execution_mode( EXECUTION_MODE_FREEZE );
// Set the next mode times.
this->next_mode_scenario_time = this->get_scenario_time() + this->time_padding; // Some time in the future.
ExCO->set_next_mode_scenario_time( this->next_mode_scenario_time );
ExCO->set_next_mode_cte_time( this->get_cte_time() );
if ( ExCO->get_next_mode_cte_time() > -std::numeric_limits< double >::max() ) {
ExCO->set_next_mode_cte_time( ExCO->get_next_mode_cte_time() + this->time_padding ); // Some time in the future.
}
// Set the ExecutionControl freeze times.
this->scenario_freeze_time = this->next_mode_scenario_time;
this->simulation_freeze_time = this->scenario_timeline->compute_simulation_time( this->next_mode_scenario_time );
break;
case EXECUTION_CONTROL_SHUTDOWN:
// Set the next execution mode.
this->requested_execution_control_mode = EXECUTION_CONTROL_SHUTDOWN;
ExCO->set_next_execution_mode( EXECUTION_MODE_SHUTDOWN );
// Set the next mode times.
this->next_mode_scenario_time = this->get_scenario_time(); // Immediate.
ExCO->set_next_mode_scenario_time( this->next_mode_scenario_time ); // Immediate.
ExCO->set_next_mode_cte_time( this->get_cte_time() ); // Immediate
break;
default:
this->requested_execution_control_mode = EXECUTION_CONTROL_UNINITIALIZED;
if ( DebugHandler::show( DEBUG_LEVEL_1_TRACE, DEBUG_SOURCE_EXECUTION_CONTROL ) ) {
ostringstream errmsg;
errmsg << "DSES::ExecutionControl::set_next_execution_mode():"
<< __LINE__ << " WARNING: Unknown execution mode value: " << exec_control
<< THLA_ENDL;
send_hs( stdout, (char *)errmsg.str().c_str() );
}
break;
}
}
bool ExecutionControl::check_mode_transition_request()
{
// Just return if false mode change has been requested.
if ( !this->is_mode_transition_requested() ) {
return false;
}
// Only the Master federate receives and processes Mode Transition Requests.
if ( !this->is_master() ) {
ostringstream errmsg;
errmsg << "DSES::ExecutionControl::check_mode_transition_request():"
<< __LINE__ << " WARNING: Received Mode Transition Request and not Master: "
<< mtr_enum_to_string( this->pending_mtr )
<< THLA_ENDL;
send_hs( stdout, (char *)errmsg.str().c_str() );
return false;
}
// First check to see if this is a valid MTR.
if ( !( is_mtr_valid( this->pending_mtr ) ) ) {
ostringstream errmsg;
errmsg << "DSES::ExecutionControl::check_mode_transition_request():"
<< __LINE__ << " WARNING: Invalid Mode Transition Request: "
<< mtr_enum_to_string( this->pending_mtr )
<< THLA_ENDL;
send_hs( stdout, (char *)errmsg.str().c_str() );
return false;
}
return true;
}
bool ExecutionControl::process_mode_transition_request()
{
// Just return is no mode change has been requested.
if ( !this->check_mode_transition_request() ) {
return false;
} else {
// Since this is a valid MTR, set the next mode from the MTR.
this->set_mode_request_from_mtr( this->pending_mtr );
}
// Reference the DSES Execution Configuration Object (ExCO)
ExecutionConfiguration *ExCO = this->get_execution_configuration();
// Print diagnostic message if appropriate.
if ( DebugHandler::show( DEBUG_LEVEL_4_TRACE, DEBUG_SOURCE_EXECUTION_CONTROL ) ) {
cout << "=============================================================" << endl
<< "ExecutionControl::process_mode_transition_request()" << endl
<< "\t current_scenario_time: " << setprecision( 18 ) << this->scenario_timeline->get_time() << endl
<< "\t scenario_time_epoch: " << setprecision( 18 ) << this->scenario_timeline->get_epoch() << endl
<< "\t scenario_time_epoch(ExCO): " << setprecision( 18 ) << ExCO->scenario_time_epoch << endl
<< "\t scenario_time_sim_offset: " << setprecision( 18 ) << this->scenario_timeline->get_sim_offset() << endl
<< "\t Current HLA grant time: " << federate->get_granted_time() << endl
<< "\t Current HLA request time: " << federate->get_requested_time() << endl
<< "\t current_sim_time: " << setprecision( 18 ) << this->sim_timeline->get_time() << endl
<< "\t simulation_time_epoch: " << setprecision( 18 ) << this->sim_timeline->get_epoch() << endl;
if ( this->does_cte_timeline_exist() ) {
cout << "\t current_CTE_time: " << setprecision( 18 ) << this->cte_timeline->get_time() << endl
<< "\t CTE_time_epoch: " << setprecision( 18 ) << this->cte_timeline->get_epoch() << endl;
}
cout << "\t next_mode_scenario_time: " << setprecision( 18 ) << ExCO->next_mode_scenario_time << endl
<< "\t next_mode_cte_time: " << setprecision( 18 ) << ExCO->next_mode_cte_time << endl
<< "\t scenario_freeze_time: " << setprecision( 18 ) << this->scenario_freeze_time << endl
<< "\t simulation_freeze_time: " << setprecision( 18 ) << this->simulation_freeze_time << endl
<< "=============================================================" << endl;
}
// Check Mode Transition Request.
switch ( this->pending_mtr ) {
case MTR_GOTO_RUN:
// Clear the mode change request flag.
this->clear_mode_transition_requested();
// Transition to run can only happen from initialization or freeze.
// We don't really need to do anything if we're in initialization.
if ( this->current_execution_control_mode == EXECUTION_CONTROL_FREEZE ) {
// Tell Trick to exit freeze and go to run.
the_exec->run();
// The run transition logic will be triggered when exiting Freeze.
// This is done in the TrickHLA::Federate::exit_freeze() routine
// called when exiting Freeze.
}
return true;
break;
case MTR_GOTO_FREEZE:
// Clear the mode change request flag.
this->clear_mode_transition_requested();
// Transition to freeze can only happen from initialization or run.
// We don't really need to do anything if we're in initialization.
if ( this->current_execution_control_mode == EXECUTION_CONTROL_RUNNING ) {
// Send out the updated ExCO.
ExCO->send_init_data();
// Announce the pending freeze.
this->freeze_mode_announce();
// Tell Trick to go into freeze at the appointed time.
the_exec->freeze( this->simulation_freeze_time );
// The freeze transition logic will be done just before entering
// Freeze. This is done in the TrickHLA::Federate::freeze_init()
// routine called when entering Freeze.
}
return true;
break;
case MTR_GOTO_SHUTDOWN:
// Announce the shutdown.
this->shutdown_mode_announce();
// Tell Trick to shutdown sometime in the future.
// The DSES ExecutionControl shutdown transition will be made from
// the TrickHLA::Federate::shutdown() job.
the_exec->stop( the_exec->get_sim_time() + this->time_padding );
return true;
break;
default:
break;
}
return false;
}
/*!
* \par<b>Assumptions and Limitations:</b>
* - Called from the ExCO unpack routine.
*
* @job_class{scheduled}
*/
bool ExecutionControl::process_execution_control_updates()
{
bool mode_change = false;
ostringstream errmsg;
// Reference the DSES Execution Configuration Object (ExCO)
ExecutionConfiguration *ExCO = get_execution_configuration();
// Check if there are pending changes from the ExCO.
if ( ExCO->update_pending() ) {
// Clear the ExCO update pending flag and continue.
ExCO->clear_update_pending();
} else {
// There are no pending changes from the ExCO.
// Return that no mode changes occurred.
return false;
}
// The Master federate should never have to process ExCO updates.
if ( this->is_master() ) {
errmsg << "DSES::ExecutionControl::process_execution_control_updates():"
<< __LINE__ << " WARNING: Master receive an ExCO update: "
<< execution_control_enum_to_string( this->requested_execution_control_mode )
<< THLA_ENDL;
send_hs( stdout, (char *)errmsg.str().c_str() );
// Return that no mode changes occurred.
return false;
}
// Translate the native ExCO mode values into ExecutionModeEnum.
ExecutionModeEnum exco_cem = execution_mode_int16_to_enum( ExCO->current_execution_mode );
ExecutionModeEnum exco_nem = execution_mode_int16_to_enum( ExCO->next_execution_mode );
// Check for consistency between ExecutionControl and ExCO.
if ( exco_cem != this->current_execution_control_mode ) {
errmsg << "DSES::ExecutionControl::process_execution_control_updates():"
<< __LINE__ << " WARNING: Current execution mode mismatch between ExecutionControl ("
<< execution_control_enum_to_string( this->current_execution_control_mode )
<< ") and the ExCO current execution mode ("
<< execution_mode_enum_to_string( exco_cem )
<< ")!"
<< THLA_ENDL;
send_hs( stdout, (char *)errmsg.str().c_str() );
}
// Check for change in execution mode.
if ( exco_nem != exco_cem ) {
mode_change = true;
if ( exco_nem == EXECUTION_MODE_SHUTDOWN ) {
this->requested_execution_control_mode = EXECUTION_CONTROL_SHUTDOWN;
} else if ( exco_nem == EXECUTION_MODE_RUNNING ) {
this->requested_execution_control_mode = EXECUTION_CONTROL_RUNNING;
} else if ( exco_nem == EXECUTION_MODE_FREEZE ) {
this->requested_execution_control_mode = EXECUTION_CONTROL_FREEZE;
this->scenario_freeze_time = ExCO->next_mode_scenario_time;
this->simulation_freeze_time = this->scenario_timeline->compute_simulation_time( this->scenario_freeze_time );
} else {
errmsg << "DSES::ExecutionControl::process_execution_control_updates():"
<< __LINE__ << " WARNING: Invalid ExCO next execution mode: "
<< execution_mode_enum_to_string( exco_nem ) << "!"
<< THLA_ENDL;
send_hs( stdout, (char *)errmsg.str().c_str() );
// Return that no mode changes occurred.
return false;
}
}
// Check for CTE mode time update.
if ( ExCO->next_mode_cte_time != this->next_mode_cte_time ) {
this->next_mode_cte_time = ExCO->next_mode_cte_time;
}
// Check for mode changes.
if ( !mode_change ) {
// Return that no mode changes occurred.
return false;
}
// Process the mode change.
switch ( this->current_execution_control_mode ) {
case EXECUTION_CONTROL_UNINITIALIZED:
// Check for SHUTDOWN.
if ( this->requested_execution_control_mode == EXECUTION_CONTROL_SHUTDOWN ) {
// Mark the current execution mode as SHUTDOWN.
this->current_execution_control_mode = EXECUTION_CONTROL_SHUTDOWN;
ExCO->current_execution_mode = EXECUTION_MODE_SHUTDOWN;
// Tell the TrickHLA::Federate to shutdown.
// The DSES ExecutionControl shutdown transition will be made from
// the TrickHLA::Federate::shutdown() job.
the_exec->stop();
} else {
errmsg << "DSES::ExecutionControl::process_execution_control_updates():"
<< __LINE__ << " WARNING: Execution mode mismatch between current mode ("
<< execution_control_enum_to_string( this->current_execution_control_mode )
<< ") and the requested execution mode ("
<< execution_control_enum_to_string( this->requested_execution_control_mode )
<< ")!"
<< THLA_ENDL;
send_hs( stdout, (char *)errmsg.str().c_str() );
// Return that no mode changes occurred.
return false;
}
// Return that a mode change occurred.
return true;
break;
case EXECUTION_CONTROL_INITIALIZING:
// Check for SHUTDOWN.
if ( this->requested_execution_control_mode == EXECUTION_CONTROL_SHUTDOWN ) {
// Mark the current execution mode as SHUTDOWN.
this->current_execution_control_mode = EXECUTION_CONTROL_SHUTDOWN;
ExCO->current_execution_mode = EXECUTION_MODE_SHUTDOWN;
// Tell the TrickHLA::Federate to shutdown.
// The DSES ExecutionControl shutdown transition will be made from
// the TrickHLA::Federate::shutdown() job.
the_exec->stop();
} else if ( this->requested_execution_control_mode == EXECUTION_CONTROL_RUNNING ) {
// Tell Trick to go to in Run at startup.
the_exec->set_freeze_command( false );
// This is an early joining federate in initialization.
// So, proceed to the run mode transition.
this->run_mode_transition();
} else if ( this->requested_execution_control_mode == EXECUTION_CONTROL_FREEZE ) {
// Announce the pending freeze.
this->freeze_mode_announce();
// Tell Trick to go into freeze at startup.
//the_exec->freeze();
// Tell Trick to go into freeze at startup.
the_exec->set_freeze_command( true );
// The freeze transition logic will be done just before entering
// Freeze. This is done in the TrickHLA::Federate::freeze_init()
// routine called when entering Freeze.
} else if ( this->requested_execution_control_mode == EXECUTION_CONTROL_INITIALIZING ) {
// There's really nothing to do here.
} else {
errmsg << "DSES::ExecutionControl::process_execution_control_updates():"
<< __LINE__ << " WARNING: Execution mode mismatch between current mode ("
<< execution_control_enum_to_string( this->current_execution_control_mode )
<< ") and the requested execution mode ("
<< execution_control_enum_to_string( this->requested_execution_control_mode )
<< ")!"
<< THLA_ENDL;
send_hs( stdout, (char *)errmsg.str().c_str() );
// Return that no mode changes occurred.
return false;
}
// Return that a mode change occurred.
return true;
break;
case EXECUTION_CONTROL_RUNNING:
// Check for SHUTDOWN.
if ( this->requested_execution_control_mode == EXECUTION_CONTROL_SHUTDOWN ) {
// Print out a diagnostic warning message.
errmsg << "DSES::ExecutionControl::process_execution_control_updates():"
<< __LINE__ << " WARNING: Execution mode mismatch between current mode ("
<< execution_control_enum_to_string( this->current_execution_control_mode )
<< ") and the requested execution mode ("
<< execution_control_enum_to_string( this->requested_execution_control_mode )
<< ")!"
<< THLA_ENDL;
send_hs( stdout, (char *)errmsg.str().c_str() );
// Mark the current execution mode as SHUTDOWN.
this->current_execution_control_mode = EXECUTION_CONTROL_SHUTDOWN;
ExCO->current_execution_mode = EXECUTION_MODE_SHUTDOWN;
// Tell the TrickHLA::Federate to shutdown.
// The DSES ExecutionControl shutdown transition will be made from
// the TrickHLA::Federate::shutdown() job.
the_exec->stop();
} else if ( this->requested_execution_control_mode == EXECUTION_CONTROL_FREEZE ) {
// Print diagnostic message if appropriate.
if ( DebugHandler::show( DEBUG_LEVEL_4_TRACE, DEBUG_SOURCE_EXECUTION_CONTROL ) ) {
cout << "DSES::ExecutionControl::process_execution_control_updates()" << endl
<< "\t current_scenario_time: " << setprecision( 18 ) << this->scenario_timeline->get_time() << endl
<< "\t scenario_time_epoch: " << setprecision( 18 ) << this->scenario_timeline->get_epoch() << endl
<< "\t scenario_time_epoch(ExCO): " << setprecision( 18 ) << ExCO->scenario_time_epoch << endl
<< "\t scenario_time_sim_offset: " << setprecision( 18 ) << this->scenario_timeline->get_sim_offset() << endl
<< "\t current_sim_time: " << setprecision( 18 ) << this->sim_timeline->get_time() << endl
<< "\t simulation_time_epoch: " << setprecision( 18 ) << this->sim_timeline->get_epoch() << endl;
if ( this->does_cte_timeline_exist() ) {
cout << "\t current_CTE_time: " << setprecision( 18 ) << this->cte_timeline->get_time() << endl
<< "\t CTE_time_epoch: " << setprecision( 18 ) << this->cte_timeline->get_epoch() << endl;
}
cout << "\t next_mode_scenario_time: " << setprecision( 18 ) << ExCO->next_mode_scenario_time << endl
<< "\t next_mode_cte_time: " << setprecision( 18 ) << ExCO->next_mode_cte_time << endl
<< "\t scenario_freeze_time: " << setprecision( 18 ) << this->scenario_freeze_time << endl
<< "\t simulation_freeze_time: " << setprecision( 18 ) << this->simulation_freeze_time << endl
<< "=============================================================" << endl;
}
// Announce the pending freeze.
this->freeze_mode_announce();
// Tell Trick to go into freeze at the appointed time.
the_exec->freeze( this->simulation_freeze_time );
// The freeze transition logic will be done just before entering
// Freeze. This is done in the TrickHLA::Federate::freeze_init()
// routine called when entering Freeze.
} else {
errmsg << "DSES::ExecutionControl::process_execution_control_updates():"
<< __LINE__ << " WARNING: Execution mode mismatch between current mode ("
<< execution_control_enum_to_string( this->current_execution_control_mode )
<< ") and the requested execution mode ("
<< execution_control_enum_to_string( this->requested_execution_control_mode )
<< ")!"
<< THLA_ENDL;
send_hs( stdout, (char *)errmsg.str().c_str() );
// Return that no mode changes occurred.
return false;
}
// Return that a mode change occurred.
return true;
break;
case EXECUTION_CONTROL_FREEZE:
// Check for SHUTDOWN.
if ( this->requested_execution_control_mode == EXECUTION_CONTROL_SHUTDOWN ) {
// Mark the current execution mode as SHUTDOWN.
this->current_execution_control_mode = EXECUTION_CONTROL_SHUTDOWN;
ExCO->current_execution_mode = EXECUTION_MODE_SHUTDOWN;
// Shutdown the federate now.
exec_get_exec_cpp()->stop();
} else if ( this->requested_execution_control_mode == EXECUTION_CONTROL_RUNNING ) {
// Tell Trick to exit freeze and go to run.
the_exec->run();
// The run transition logic will be done just when exiting
// Freeze. This is done in the TrickHLA::Federate::exit_freeze()
// routine called when entering Freeze.
// this->run_mode_transition();
} else {
errmsg << "DSES::ExecutionControl::process_execution_control_updates():"
<< __LINE__ << " WARNING: Execution mode mismatch between current mode ("
<< execution_control_enum_to_string( this->current_execution_control_mode )
<< ") and the requested execution mode ("
<< execution_control_enum_to_string( this->requested_execution_control_mode )
<< ")!"
<< THLA_ENDL;
send_hs( stdout, (char *)errmsg.str().c_str() );
// Return that no mode changes occurred.
return false;
}
// Return that a mode change occurred.
return true;
break;
case EXECUTION_CONTROL_SHUTDOWN:
// Once in SHUTDOWN, we cannot do anything else.
errmsg << "DSES::ExecutionControl::process_execution_control_updates():"
<< __LINE__ << " WARNING: Shutting down but received mode transition: "
<< execution_control_enum_to_string( this->requested_execution_control_mode )
<< THLA_ENDL;
send_hs( stdout, (char *)errmsg.str().c_str() );
// Return that no mode changes occurred.
return false;
break;
default:
break;
}
// Return that no mode changes occurred.
return false;
}
bool ExecutionControl::run_mode_transition()
{
RTIambassador * RTI_amb = federate->get_RTI_ambassador();
ExecutionConfiguration *ExCO = get_execution_configuration();
SyncPnt * sync_pnt = NULL;
// Register the 'mtr_run' sync-point.
if ( this->is_master() ) {
sync_pnt = this->register_sync_pnt( *RTI_amb, L"mtr_run" );
} else {
sync_pnt = this->get_sync_pnt( L"mtr_run" );
}
// Make sure that we have a valid sync-point.
if ( sync_pnt == (TrickHLA::SyncPnt *)NULL ) {
ostringstream errmsg;
errmsg << "DSES::ExecutionControl::run_mode_transition():" << __LINE__
<< " ERROR: The 'mtr_run' sync-point was not found!" << THLA_ENDL;
send_hs( stderr, (char *)errmsg.str().c_str() );
exec_terminate( __FILE__, (char *)errmsg.str().c_str() );
} else {
// Wait for 'mtr_run' sync-point announce.
sync_pnt->wait_for_announce( federate );
// Achieve the 'mtr-run' sync-point.
sync_pnt->achieve_sync_point( *RTI_amb );
// Wait for 'mtr_run' sync-point synchronization.
sync_pnt->wait_for_synchronization( federate );
// Set the current execution mode to running.
this->current_execution_control_mode = EXECUTION_CONTROL_RUNNING;
ExCO->set_current_execution_mode( EXECUTION_MODE_RUNNING );
// Check for CTE.
if ( this->does_cte_timeline_exist() ) {
double go_to_run_time;
// The Master federate updates the ExCO with the CTE got-to-run time.
if ( this->is_master() ) {
go_to_run_time = ExCO->get_next_mode_cte_time();
ExCO->send_init_data();
} // Other federates wait on the ExCO update with the CTE go-to-run time.
else {
// Wait for the ExCO update with the CTE time.
ExCO->wait_on_update();
// Process the just received ExCO update.
this->process_execution_control_updates();
// Set the CTE time to go to run.
go_to_run_time = ExCO->get_next_mode_cte_time();
}
// Wait for the CTE go-to-run time.
double diff;
while ( this->get_cte_time() < go_to_run_time ) {
// Check for shutdown.
federate->check_for_shutdown_with_termination();
diff = go_to_run_time - this->get_cte_time();
if ( fmod( diff, 1.0 ) == 0.0 ) {
if ( DebugHandler::show( DEBUG_LEVEL_2_TRACE, DEBUG_SOURCE_EXECUTION_CONTROL ) ) {
send_hs( stdout, "DSES::ExecutionControl::run_mode_transition():%d Going to run in %G seconds.%c",
__LINE__, diff, THLA_NEWLINE );
}
}
}
// Print debug message if appropriate.
if ( DebugHandler::show( DEBUG_LEVEL_2_TRACE, DEBUG_SOURCE_EXECUTION_CONTROL ) ) {
double curr_cte_time = this->get_cte_time();
diff = curr_cte_time - go_to_run_time;
send_hs( stdout, "DSES::ExecutionControl::run_mode_transition():%d \n Going to run at CTE time %.18G seconds. \n Current CTE time %.18G seconds. \n Difference: %.9lf seconds.%c",
__LINE__, go_to_run_time, curr_cte_time, diff, THLA_NEWLINE );
}
}
}
return true;
}
void ExecutionControl::freeze_mode_announce()
{
// Register the 'mtr_freeze' sync-point.
if ( this->is_master() ) {
this->register_sync_pnt( *( federate->get_RTI_ambassador() ), L"mtr_freeze" );
}
}
bool ExecutionControl::freeze_mode_transition()
{
RTIambassador * RTI_amb = federate->get_RTI_ambassador();
ExecutionConfiguration *ExCO = get_execution_configuration();
TrickHLA::SyncPnt * sync_pnt = NULL;
// Get the 'mtr_freeze' sync-point.
sync_pnt = this->get_sync_pnt( L"mtr_freeze" );
// Make sure that we have a valid sync-point.
if ( sync_pnt == (TrickHLA::SyncPnt *)NULL ) {
ostringstream errmsg;
errmsg << "DSES::ExecutionControl::freeze_mode_transition():" << __LINE__
<< " ERROR: The 'mtr_freeze' sync-point was not found!" << THLA_ENDL;
send_hs( stderr, (char *)errmsg.str().c_str() );
exec_terminate( __FILE__, (char *)errmsg.str().c_str() );
} else {
// Wait for 'mtr_freeze' sync-point announce.
sync_pnt->wait_for_announce( federate );
// Achieve the 'mtr_freeze' sync-point.
sync_pnt->achieve_sync_point( *RTI_amb );
// Wait for 'mtr_freeze' sync-point synchronization.
sync_pnt->wait_for_synchronization( federate );
// Set the current execution mode to freeze.
this->current_execution_control_mode = EXECUTION_CONTROL_FREEZE;
ExCO->set_current_execution_mode( EXECUTION_MODE_FREEZE );
}
return false;
}
bool ExecutionControl::check_freeze_exit()
{
// Check if this is a Master federate.
if ( this->is_master() ) {
// Process and Mode Transition Requests.
process_mode_transition_request();
// Handle requests for ExCO updates.
if ( this->execution_configuration->is_attribute_update_requested() ) {
this->execution_configuration->send_requested_data();
}
// Check for Trick shutdown command.
if ( the_exec->get_exec_command() == ExitCmd ) {
// Tell the TrickHLA::Federate to shutdown.
// The DSES ExecutionControl shutdown transition will be made from
// the TrickHLA::Federate::shutdown() job.
this->federate->shutdown();
}
} else {
// Check to see if there was an ExCO update.
this->execution_configuration->receive_init_data();
// Process the ExCO update.
this->process_execution_control_updates();
// Check for shutdown.
if ( this->current_execution_control_mode == EXECUTION_CONTROL_SHUTDOWN ) {
// Tell the TrickHLA::Federate to shutdown.
// The DSES Mode Manager shutdown transition will be made from
// the TrickHLA::Federate::shutdown() job.
this->federate->shutdown();
}
}
return ( true );
}
void ExecutionControl::shutdown_mode_announce()
{
// Only the Master federate will ever announce a shutdown.
if ( !this->is_master() ) {
return;
}
// If the current execution mode is uninitialized then we haven't gotten
// far enough in the initialization process to shut anything down.
if ( this->current_execution_control_mode == EXECUTION_CONTROL_UNINITIALIZED ) {
return;
}
// Set the next execution mode to shutdown.
this->set_next_execution_control_mode( EXECUTION_CONTROL_SHUTDOWN );
// Send out the updated ExCO.
this->get_execution_configuration()->send_init_data();
// Clear the mode change request flag.
this->clear_mode_transition_requested();
}
/*!
* @job_class{shutdown}
*/
void ExecutionControl::shutdown_mode_transition()
{
// Only the Master federate has any DSES tasks for shutdown.
if ( !this->is_master() ) {
return;
}
// If the current execution mode is uninitialized then we haven't gotten
// far enough in the initialization process to shut anything down.
if ( this->current_execution_control_mode == EXECUTION_CONTROL_UNINITIALIZED ) {
return;
}
// Register the 'mtr_shutdown' sync-point.
this->register_sync_pnt( *( federate->get_RTI_ambassador() ), L"mtr_shutdown" );
}
ExecutionConfiguration *ExecutionControl::get_execution_configuration()
{
ExecutionConfiguration *ExCO;
ExCO = dynamic_cast< ExecutionConfiguration * >( this->get_execution_configuration() );
if ( ExCO == NULL ) {
ostringstream errmsg;
errmsg << "DSES::ExecutionControl::epoch_and_root_frame_discovery_process():" << __LINE__
<< " ERROR: Execution Configureation is not an DSES ExCO." << THLA_ENDL;
send_hs( stderr, (char *)errmsg.str().c_str() );
exec_terminate( __FILE__, (char *)errmsg.str().c_str() );
}
return ( this->get_execution_configuration() );
}
| 37.930447 | 193 | 0.648978 | jiajlin |
38be358d6928ad7412aa0b3f2fcfa99543558716 | 3,388 | cpp | C++ | solutions/hackerrank/hour_rank/hr26/q3/ProblemC.cpp | bluedawnstar/algorithm_library | 4c7f64ec61fc2ba059b64ad7ba20fcb5b838ced6 | [
"Unlicense"
] | 40 | 2017-11-26T05:29:18.000Z | 2020-11-13T00:29:26.000Z | solutions/hackerrank/hour_rank/hr26/q3/ProblemC.cpp | bluedawnstar/algorithm_library | 4c7f64ec61fc2ba059b64ad7ba20fcb5b838ced6 | [
"Unlicense"
] | 101 | 2019-02-09T06:06:09.000Z | 2021-12-25T16:55:37.000Z | solutions/hackerrank/hour_rank/hr26/q3/ProblemC.cpp | bluedawnstar/algorithm_library | 4c7f64ec61fc2ba059b64ad7ba20fcb5b838ced6 | [
"Unlicense"
] | 6 | 2017-01-03T14:17:58.000Z | 2021-01-22T10:37:04.000Z | #include <memory.h>
#include <ctime>
#include <cstdio>
#include <cstdlib>
#include <climits>
#include <cctype>
#include <cstring>
#include <climits>
#include <cmath>
#include <vector>
#include <string>
#include <memory>
#include <numeric>
#include <limits>
#include <functional>
#include <tuple>
#include <set>
#include <map>
#include <bitset>
#include <stack>
#include <queue>
#include <unordered_set>
#include <unordered_map>
#include <algorithm>
#include <iostream>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
template <typename T>
struct DPConvexHullTrickMin {
struct Line {
T m, b; // f(x) = m * x + b
template <typename U>
inline T get(U x) const {
return m * x + b;
}
};
deque<Line> lines;
// when Xs of queries (not insert) are ascending, x[j] <= x[j + 1]
// PRECONDITION: m[k] >= m[k + 1]
void insert(T m, T b) {
Line l{ m, b };
while (lines.size() > 1 && ccw(lines[lines.size() - 2], lines[lines.size() - 1], l))
lines.pop_back();
lines.push_back(l);
}
// when Xs of queries (not insert) are descending, x[j] >= x[j + 1]
// PRECONDITION: m[k] <= m[k + 1]
void insertReverse(T m, T b) {
Line l{ m, b };
while (lines.size() > 1 && cw(lines[lines.size() - 2], lines[lines.size() - 1], l))
lines.pop_back();
lines.push_back(l);
}
template <typename U>
T query(U x) {
if (lines.empty())
return 0;
while (lines.size() > 1 && lines[0].get(x) >= lines[1].get(x))
lines.pop_front();
return lines[0].get(x);
}
private:
static T area(const Line& a, const Line& b, const Line& c) {
T ax = (b.m - a.m);
T bx = (c.b - a.b);
T ay = (c.m - a.m);
T by = (b.b - a.b);
return ax * bx - ay * by;
}
static bool ccw(const Line& a, const Line& b, const Line& c) {
return area(a, b, c) >= 0;
}
static bool cw(const Line& a, const Line& b, const Line& c) {
return area(a, b, c) <= 0;
}
};
vector<ll> A;
vector<ll> S;
vector<ll> SS;
ll dfs(int L, int R) {
if (L >= R)
return LLONG_MIN;
else if (L + 1 == R)
return 2ll * A[L] * A[R];
int mid = L + (R - L) / 2;
vector<int> idxL(mid - L + 1);
iota(idxL.begin(), idxL.end(), L);
sort(idxL.begin(), idxL.end(), [](int l, int r) {
return S[l] > S[r];
});
vector<int> idxR(R - mid);
iota(idxR.begin(), idxR.end(), mid + 2);
sort(idxR.begin(), idxR.end(), [](int l, int r) {
return S[l] < S[r];
});
DPConvexHullTrickMin<ll> cht;
for (int i : idxL)
cht.insert(2ll * S[i], -(S[i] * S[i] + SS[i]));
ll ans = 0;
for (int i : idxR) {
ans = max(ans, (S[i] * S[i] - SS[i]) - cht.query(S[i]));
}
ans = max(ans, dfs(L, mid));
ans = max(ans, dfs(mid + 1, R));
return ans;
}
int main(void) {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int N;
cin >> N;
A.resize(N);
for (int i = 0; i < N; i++) {
cin >> A[i];
}
S.resize(N + 1);
SS.resize(N + 1);
for (int i = 0; i < N; i++) {
S[i + 1] = S[i] + A[i];
SS[i + 1] = SS[i] + A[i] * A[i];
}
cout << dfs(0, N - 1) / 2 << endl;
return 0;
}
| 21.443038 | 92 | 0.50059 | bluedawnstar |
38c8bc38965a627cc6e62aa970ee44cfe1233a13 | 1,554 | cpp | C++ | atcoder/abc/abc112/c.cpp | yu3mars/proconVSCodeGcc | fcf36165bb14fb6f555664355e05dd08d12e426b | [
"MIT"
] | null | null | null | atcoder/abc/abc112/c.cpp | yu3mars/proconVSCodeGcc | fcf36165bb14fb6f555664355e05dd08d12e426b | [
"MIT"
] | null | null | null | atcoder/abc/abc112/c.cpp | yu3mars/proconVSCodeGcc | fcf36165bb14fb6f555664355e05dd08d12e426b | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using pii = pair<int, int>;
#define REP(i,n) for(int i=0, i##_len=(n); i<i##_len; ++i)
#define all(x) (x).begin(),(x).end()
#define m0(x) memset(x,0,sizeof(x))
int dx4[4] = {1,0,-1,0}, dy4[4] = {0,1,0,-1};
int main()
{
int n,ansx,ansy,ansh=-1;
cin>>n;
vector<int> x(n),y(n),h(n);
int xx,yy,hh;
for(int i = 0; i < n; i++)
{
cin>>x[i]>>y[i]>>h[i];
if(h[i]>0)
{
xx=x[i];
yy=y[i];
hh=h[i];
}
}
for(int tmpx = 0; tmpx < 101; tmpx++)
{
for(int tmpy = 0; tmpy < 101; tmpy++)
{
bool ok=true;
bool kakutei =false;
int tmph = hh + abs(tmpx-xx)+abs(tmpy-yy);
for(int info = 0; info < n; info++)
{
int diff= abs(tmpx-x[info])+abs(tmpy-y[info]);
if(tmph!=diff+h[info])
{
if(h[info]==0 && diff>tmph)
{
continue;
}
else
{
ok=false;
break;
}
}
}
if(ok)
{
ansx=tmpx;
ansy=tmpy;
ansh=tmph;
break;
}
}
if(ansh>0)break;
}
cout<<ansx<<" "<<ansy<<" "<<ansh<<endl;
return 0;
} | 22.2 | 62 | 0.348777 | yu3mars |
38ccda3f9728c41d4a8831bf3404a7f05bc3d9f1 | 628 | cpp | C++ | USACO Bronze/US Open 2016 Contest/diamond.cpp | Alecs-Li/Competitive-Programming | 39941ff8e2c8994abbae8c96a1ed0a04b10058b8 | [
"MIT"
] | 1 | 2021-07-06T02:14:03.000Z | 2021-07-06T02:14:03.000Z | USACO Bronze/US Open 2016 Contest/diamond.cpp | Alex01890-creator/competitive-programming | 39941ff8e2c8994abbae8c96a1ed0a04b10058b8 | [
"MIT"
] | null | null | null | USACO Bronze/US Open 2016 Contest/diamond.cpp | Alex01890-creator/competitive-programming | 39941ff8e2c8994abbae8c96a1ed0a04b10058b8 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#include <iostream>
using namespace std;
int main() {
freopen("diamond.in", "r", stdin);
freopen("diamond.out", "w", stdout);
int n, k; cin >> n >> k;
int arr[n], ans = 0, count = 0;
for(int a=0; a<n; a++){
cin >> arr[a];
}
for(int a=0; a<n; a++){
for(int b=0; b<n; b++){
if(arr[b] >= arr[a] && arr[b] <= arr[a] + k ){
count += 1;
}
}
ans = max(count, ans);
count = 0;
for(int b=0; b<n; b++){
if(arr[b] >= arr[a] - k && arr[b] <= arr[a]){
count += 1;
}
}
ans = max(count, ans);
count = 0;
}
cout << ans;
}
| 19.625 | 52 | 0.43949 | Alecs-Li |
38d33995e5eae06285c45bde3e171a2edf327d09 | 1,196 | cpp | C++ | LeetCodeCPP/304. Range Sum Query 2D - Immutable/main.cpp | 18600130137/leetcode | fd2dc72c0b85da50269732f0fcf91326c4787d3a | [
"Apache-2.0"
] | 1 | 2019-03-29T03:33:56.000Z | 2019-03-29T03:33:56.000Z | LeetCodeCPP/304. Range Sum Query 2D - Immutable/main.cpp | 18600130137/leetcode | fd2dc72c0b85da50269732f0fcf91326c4787d3a | [
"Apache-2.0"
] | null | null | null | LeetCodeCPP/304. Range Sum Query 2D - Immutable/main.cpp | 18600130137/leetcode | fd2dc72c0b85da50269732f0fcf91326c4787d3a | [
"Apache-2.0"
] | null | null | null | //
// main.cpp
// 304. Range Sum Query 2D - Immutable
//
// Created by admin on 2019/7/12.
// Copyright © 2019年 liu. All rights reserved.
//
#include <iostream>
#include <vector>
using namespace std;
class NumMatrix {
private:
vector<vector<int>> mc; //matrixCumulative
int m=0,n=0;
int a(int i,int j){
return i>=0&&j>=0?mc[i][j]:0;
}
public:
NumMatrix(vector<vector<int>>& matrix) {
mc =matrix;
m=mc.size();
if(m==0){
return;
}
n=mc[0].size();
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
mc[i][j]+=a(i-1,j)+a(i,j-1)-a(i-1,j-1);
}
}
}
int sumRegion(int row1, int col1, int row2, int col2) {
if(m==0 || n==0){
return -1;
}
return mc[row2][col2]-a(row2,col1-1)-a(row1-1,col2)+a(row1-1,col1-1);
}
};
int main(int argc, const char * argv[]) {
vector<vector<int>> input={{3,0,1,4,2},{5,6,3,2,1},{1,2,0,1,5},{4,1,0,1,7},{1,0,3,0,5}};
NumMatrix* obj = new NumMatrix(input);
int ret=obj->sumRegion(1, 2, 2, 4);
cout<<"The ret is:"<<ret<<endl;
return 0;
}
| 22.566038 | 92 | 0.485786 | 18600130137 |
38d9b46b19f37afdf68b7db37be568fff6db41b1 | 685 | cpp | C++ | chapter21/Combat.cpp | UncleCShark/CppIn24HoursWithCmake | 7d1f30906fed2c7d144e5495ad42a3a9a59d2dce | [
"MIT"
] | null | null | null | chapter21/Combat.cpp | UncleCShark/CppIn24HoursWithCmake | 7d1f30906fed2c7d144e5495ad42a3a9a59d2dce | [
"MIT"
] | null | null | null | chapter21/Combat.cpp | UncleCShark/CppIn24HoursWithCmake | 7d1f30906fed2c7d144e5495ad42a3a9a59d2dce | [
"MIT"
] | null | null | null | #include <iostream>
int main()
{
// define character values
int strength;
double accuracy;
int dexterity;
// define constants
const double maximum = 50;
// get user input
std::cout << "\nEnter strength (1-100): ";
std::cin >> strength;
std::cout << "\nEnter accuracy (1-50): ";
std::cin >> accuracy;
std::cout << "\nEnter dexterity (1-50): ";
std::cin >> dexterity;
// calculate character combat stats
double attack = strength * (accuracy / maximum);
double damage = strength * (dexterity / maximum);
std::cout << "\nAttack rating: " << attack << "\n";
std::cout << "Damage rating: " << damage << "\n";
}
| 22.096774 | 55 | 0.579562 | UncleCShark |
38d9c8ddee49603d3cc4d513aaf65cdd972a171c | 3,039 | cpp | C++ | luogu/1442.cpp | swwind/code | 25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0 | [
"WTFPL"
] | 3 | 2017-09-17T09:12:50.000Z | 2018-04-06T01:18:17.000Z | luogu/1442.cpp | swwind/code | 25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0 | [
"WTFPL"
] | null | null | null | luogu/1442.cpp | swwind/code | 25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0 | [
"WTFPL"
] | null | null | null | #include <bits/stdc++.h>
#define N 100020
#define ll long long
using namespace std;
inline int read(){
int x=0,f=1;char ch=getchar();
while(ch>'9'||ch<'0')ch=='-'&&(f=0)||(ch=getchar());
while(ch<='9'&&ch>='0')x=(x<<3)+(x<<1)+ch-'0',ch=getchar();
return f?x:-x;
}
struct node {
int h, l, r;
friend bool operator < (const node &a, const node &b) {
return a.h < b.h;
}
}a[N];
int tg[N<<3], vl[N<<3];
void push_down(int x) {
if (tg[x]) {
vl[x << 1] = tg[x];
vl[x<<1|1] = tg[x];
tg[x << 1] = tg[x];
tg[x<<1|1] = tg[x];
tg[x] = 0;
}
}
void update(int x, int l, int r, int L, int R, int v) {
if (l > r) return;
if (l == L && r == R) {
tg[x] = vl[x] = v;
return;
}
push_down(x);
int m = (L + R) >> 1;
if (r <= m) update(x << 1, l, r, L, m, v);
else if (l > m) update(x<<1|1, l, r, m + 1, R, v);
else update(x << 1, l, m, L, m, v), update(x<<1|1, m + 1, r, m + 1, R, v);
}
int ask(int x, int k, int L, int R) {
if (L == R)
return vl[x];
push_down(x);
int m = (L + R) >> 1;
if (k <= m) return ask(x << 1, k, L, m);
else return ask(x<<1|1, k, m + 1, R);
}
long long b[N<<1], cnt;
int gl[N], gr[N];
long long fl[N], fr[N];
int main(int argc, char const *argv[]) {
int n = read(), m = read();
int stx = read(), sty = read();
b[++cnt] = stx;
for (int i = 1; i <= n; i++) {
a[i].h = read();
if (a[i].h > sty) {
read(); read();
i --, n --;
continue;
}
b[++cnt] = a[i].l = read();
b[++cnt] = a[i].r = read();
}
sort(a + 1, a + n + 1);
sort(b + 1, b + cnt + 1);
cnt = unique(b + 1, b + cnt + 1) - b - 1;
for (int i = 1; i <= n; i++) {
a[i].l = lower_bound(b + 1, b + cnt + 1, a[i].l) - b;
a[i].r = lower_bound(b + 1, b + cnt + 1, a[i].r) - b;
gl[i] = ask(1, a[i].l, 1, cnt);
gr[i] = ask(1, a[i].r, 1, cnt);
update(1, a[i].l + 1, a[i].r - 1, 1, cnt, i);
}
stx = lower_bound(b + 1, b + cnt + 1, stx) - b;
// for (int i = 1; i <= n; i++)
// cout << gl[i] << " " << gr[i] << endl;
// cout << endl;
long long ans = 1ll << 60;
memset(fl, 63, sizeof fl);
memset(fr, 63, sizeof fr);
int st = ask(1, stx, 1, cnt);
fl[st] = sty - a[st].h + b[stx] - b[a[st].l];
fr[st] = sty - a[st].h + b[a[st].r] - b[stx];
for (int i = st; i; i--) {
if (a[i].h - a[gl[i]].h <= m) { // 如果该平台的左端点能掉下去
fl[gl[i]] = min(fl[gl[i]], fl[i] + a[i].h - a[gl[i]].h + b[a[i].l] - b[a[gl[i]].l]);
fr[gl[i]] = min(fr[gl[i]], fl[i] + a[i].h - a[gl[i]].h + b[a[gl[i]].r] - b[a[i].l]);
if (!gl[i])
ans = min(ans, fl[i] + a[i].h);
}
if (a[i].h - a[gr[i]].h <= m) { // 如果该平台的右端点能掉下去
fl[gr[i]] = min(fl[gr[i]], fr[i] + a[i].h - a[gr[i]].h + b[a[i].r] - b[a[gr[i]].l]);
fr[gr[i]] = min(fr[gr[i]], fr[i] + a[i].h - a[gr[i]].h + b[a[gr[i]].r] - b[a[i].r]);
if (!gr[i])
ans = min(ans, fr[i] + a[i].h);
}
}
// for (int i = 1; i <= st; i++)
// cout << fl[i] << " " << fr[i] << endl;
cout << ans << endl;
return 0;
}
// 15418021011393200024 | 29.504854 | 90 | 0.431392 | swwind |
38e388a25247776082543f1004409f1775132f11 | 32,398 | cpp | C++ | Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32756G_EVAL/Demonstrations/TouchGFX/Gui/generated/images/src/Graphs/half_circle_toggle_button_inactive.cpp | ramkumarkoppu/NUCLEO-F767ZI-ESW | 85e129d71ee8eccbd0b94b5e07e75b6b91679ee8 | [
"MIT"
] | null | null | null | Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32756G_EVAL/Demonstrations/TouchGFX/Gui/generated/images/src/Graphs/half_circle_toggle_button_inactive.cpp | ramkumarkoppu/NUCLEO-F767ZI-ESW | 85e129d71ee8eccbd0b94b5e07e75b6b91679ee8 | [
"MIT"
] | null | null | null | Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32756G_EVAL/Demonstrations/TouchGFX/Gui/generated/images/src/Graphs/half_circle_toggle_button_inactive.cpp | ramkumarkoppu/NUCLEO-F767ZI-ESW | 85e129d71ee8eccbd0b94b5e07e75b6b91679ee8 | [
"MIT"
] | null | null | null | // Generated by imageconverter. Please, do not edit!
#include <touchgfx/hal/Config.hpp>
LOCATION_EXTFLASH_PRAGMA
KEEP extern const unsigned char _half_circle_toggle_button_inactive[] LOCATION_EXTFLASH_ATTRIBUTE = { // 55x58 RGB565 pixels.
0x9a,0xce,0x35,0xa5,0x56,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,
0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,
0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,
0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x35,0xa5,0x9a,0xce,
0x35,0xa5,0xb7,0xb5,0x18,0xbe,0x19,0xc6,0x19,0xc6,0x19,0xc6,0x19,0xc6,0x19,0xc6,0x19,0xc6,
0x19,0xc6,0x19,0xc6,0x19,0xc6,0x19,0xc6,0x19,0xc6,0x19,0xc6,0x19,0xc6,0x19,0xc6,0x19,0xc6,0x19,0xc6,0x19,0xc6,0x19,0xc6,0x19,0xc6,0x19,0xc6,0x19,0xc6,0x19,0xc6,
0x19,0xc6,0x19,0xc6,0x19,0xc6,0x19,0xc6,0x19,0xc6,0x19,0xc6,0x19,0xc6,0x19,0xc6,0x19,0xc6,0x19,0xc6,0x19,0xc6,0x19,0xc6,0x19,0xc6,0x19,0xc6,0x19,0xc6,0x19,0xc6,
0x19,0xc6,0x19,0xc6,0x19,0xc6,0x19,0xc6,0x19,0xc6,0x19,0xc6,0x19,0xc6,0x19,0xc6,0x19,0xc6,0x19,0xc6,0x19,0xc6,0x19,0xc6,0xb7,0xb5,0x35,0xa5,
0x56,0xad,0x18,0xbe,
0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,
0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,
0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,
0x7a,0xce,0x7a,0xce,0x7a,0xce,0x18,0xbe,0x76,0xad,
0x76,0xad,0x19,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,
0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,
0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xc6,
0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x19,0xbe,0x76,0xad,
0x76,0xad,0x19,0xc6,0x7a,0xce,0x5a,0xce,
0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,
0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,
0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,
0x7a,0xce,0x18,0xc6,0x76,0xad,
0x76,0xad,0x18,0xbe,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xce,
0x7a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xce,
0x7a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xce,
0x7a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x19,0xbe,0x76,0xad,
0x76,0xad,0x19,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,
0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x5a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x5a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x5a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x5a,0xce,
0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x5a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x5a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x5a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x5a,0xc6,
0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x5a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x5a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x5a,0xc6,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x18,0xbe,
0x76,0xad,
0x76,0xad,0x19,0xc6,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,
0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,
0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,
0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x19,0xc6,0x76,0xad,
0x76,0xad,0x19,0xbe,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,
0x5a,0xc6,0x7a,0xce,0x5a,0xce,0x5a,0xce,0x7a,0xc6,0x7a,0xce,0x5a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xc6,0x5a,0xce,0x5a,0xce,0x7a,0xc6,0x7a,0xce,0x5a,0xce,0x5a,0xce,
0x7a,0xc6,0x7a,0xce,0x5a,0xce,0x5a,0xc6,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x5a,0xce,0x7a,0xc6,0x7a,0xce,0x5a,0xce,0x5a,0xc6,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x5a,0xc6,
0x7a,0xce,0x7a,0xce,0x5a,0xc6,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x5a,0xc6,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x19,0xbe,0x76,0xad,
0x76,0xad,
0x18,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x5a,0xce,
0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,
0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,
0x5a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x18,0xbe,0x76,0xad,
0x76,0xad,0x19,0xc6,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xc6,0x7a,0xce,0x5a,0xce,
0x7a,0xc6,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x5a,0xce,0x7a,0xce,
0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,
0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x19,0xc6,0x76,0xad,
0x76,0xad,0x19,0xbe,0x7a,0xce,
0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xc6,0x5a,0xce,0x7a,0xce,
0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xc6,0x5a,0xce,0x7a,0xce,0x5a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xc6,
0x5a,0xce,0x7a,0xce,0x5a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xc6,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xc6,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,
0x7a,0xce,0x7a,0xce,0x18,0xbe,0x76,0xad,
0x76,0xad,0x19,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,
0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xc6,
0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xc6,0x7a,0xce,
0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xc6,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x19,0xbe,0x76,0xad,
0x76,0xad,0x18,0xc6,0x7a,0xce,0x7a,0xce,0x5a,0xce,
0x7a,0xce,0x7a,0xce,0x5a,0xc6,0x7a,0xce,0x7a,0xce,0x5a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xc6,
0x7a,0xce,0x7a,0xce,0x5a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xc6,0x7a,0xce,
0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,
0x19,0xc6,0x76,0xad,
0x76,0xad,0x19,0xbe,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xce,
0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xce,0x5a,0xce,
0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,
0x5a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x18,0xbe,0x76,0xad,
0x76,0xad,0x19,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x5a,0xce,0x7a,0xce,
0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,
0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,
0x7a,0xc6,0x5a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x19,0xbe,0x76,0xad,
0x76,0xad,0x19,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xc6,0x7a,0xce,0x7a,0xce,0x5a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xc6,
0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xc6,0x7a,0xce,0x5a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x5a,0xce,0x7a,0xce,
0x7a,0xc6,0x5a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,
0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x18,0xc6,0x76,0xad,
0x76,0xad,0x18,0xbe,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,
0x5a,0xce,0x7a,0xce,0x5a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x5a,0xce,
0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,
0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x19,0xbe,0x76,0xad,
0x76,0xad,0x19,0xc6,
0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,
0x5a,0xce,0x7a,0xce,0x5a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,
0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x5a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,
0x5a,0xce,0x7a,0xce,0x7a,0xce,0x19,0xc6,0x76,0xad,
0x76,0xad,0x19,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,
0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,
0x7a,0xce,0x7a,0xce,0x5a,0xc6,0x7a,0xce,0x5a,0xce,0x5a,0xc6,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,
0x7a,0xc6,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x18,0xc6,0x76,0xad,
0x76,0xad,0x19,0xbe,0x7a,0xce,0x7a,0xce,
0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xc6,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,
0x5a,0xce,0x7a,0xc6,0x7a,0xce,0x5a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,
0x7a,0xce,0x5a,0xc6,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,
0x5a,0xce,0x19,0xbe,0x76,0xad,
0x76,0xad,0x18,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xc6,
0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xc6,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xc6,0x18,0xbe,0xd7,0xb5,0x97,0xad,0xd7,0xb5,0x5a,0xce,
0xd7,0xb5,0x97,0xad,0xd7,0xb5,0x18,0xc6,0x5a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,
0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x19,0xbe,0x76,0xad,
0x76,0xad,0x19,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,
0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x5a,0xce,0x7a,0xce,
0xf8,0xbd,0x96,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0xd7,0xbd,0x7a,0xce,0xd7,0xb5,0x76,0xad,0x76,0xad,0x76,0xad,0x96,0xad,0xf8,0xbd,0x7a,0xce,0x7a,0xce,0x7a,0xce,
0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x18,0xc6,
0x76,0xad,
0x76,0xad,0x19,0xbe,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,
0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x39,0xc6,0xb7,0xb5,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0xd8,0xbd,0x7a,0xce,0xd8,0xbd,0x76,0xad,
0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0xb7,0xb5,0x39,0xc6,0x5a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,
0x7a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xc6,0x7a,0xce,0x7a,0xce,0x19,0xbe,0x76,0xad,
0x76,0xad,0x19,0xc6,0x7a,0xce,0x7a,0xce,0x5a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,
0x5a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x5a,0xce,0x7a,0xc6,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x39,0xc6,0x96,0xad,0x76,0xad,0x76,0xad,0x76,0xad,
0x96,0xad,0x76,0xad,0x76,0xad,0xd8,0xbd,0x7a,0xce,0xd7,0xb5,0x76,0xad,0x76,0xad,0x96,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x96,0xad,0x39,0xc6,0x5a,0xce,0x7a,0xce,
0x7a,0xce,0x7a,0xc6,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x18,0xbe,0x76,0xad,
0x76,0xad,
0x18,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,
0x7a,0xce,0x39,0xc6,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x96,0xad,0x76,0xad,0x76,0xad,0xd8,0xbd,0x7a,0xce,0xd8,0xb5,0x76,0xad,0x76,0xad,0x76,0xad,
0x96,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x96,0xad,0x39,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,
0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x19,0xc6,0x76,0xad,
0x76,0xad,0x19,0xbe,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,
0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x59,0xc6,0x96,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x96,0xad,0x76,0xad,0x76,0xad,0x76,0xad,
0x97,0xb5,0xf8,0xbd,0x7a,0xce,0xf8,0xbd,0x97,0xb5,0x76,0xad,0x76,0xad,0x77,0xad,0x96,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x97,0xad,0x5a,0xce,0x7a,0xce,0x5a,0xce,
0x7a,0xce,0x7a,0xc6,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x5a,0xc6,0x7a,0xce,0x5a,0xce,0x7a,0xc6,0x7a,0xce,0x19,0xc6,0x76,0xad,
0x76,0xad,0x19,0xc6,0x7a,0xce,
0x7a,0xce,0x5a,0xc6,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x5a,0xc6,0x7a,0xce,0x7a,0xce,0x5a,0xce,0xd7,0xb5,0x76,0xad,
0x76,0xad,0x76,0xad,0x96,0xad,0x76,0xad,0x76,0xad,0xb7,0xb5,0x39,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x39,0xc6,0xb7,0xb5,0x76,0xad,0x76,0xb5,
0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0xd7,0xb5,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,
0x5a,0xce,0x7a,0xce,0x18,0xbe,0x76,0xad,
0x76,0xad,0x19,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,
0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x39,0xc6,0x76,0xad,0x76,0xad,0x76,0xad,0x96,0xad,0x77,0xad,0x76,0xad,0xf9,0xc5,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,
0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0xf8,0xbd,0x96,0xad,0x77,0xad,0x96,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x39,0xc6,0x7a,0xce,0x5a,0xce,0x7a,0xce,
0x5a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x19,0xbe,0x76,0xad,
0x76,0xad,0x18,0xbe,0x7a,0xce,0x7a,0xce,0x5a,0xce,
0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xc6,0x7a,0xce,0xb7,0xb5,0x76,0xad,0x76,0xad,0x96,0xad,0x76,0xad,
0x76,0xad,0x19,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x19,0xbe,0x76,0xad,0x76,0xb5,
0x96,0xad,0x76,0xad,0x76,0xad,0xd7,0xb5,0x7a,0xce,0x5a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xc6,0x5a,0xce,0x5a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,
0x18,0xc6,0x76,0xad,
0x76,0xad,0x19,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x5a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xc6,0x5a,0xce,0x7a,0xce,0x7a,0xc6,0x5a,0xce,0x7a,0xce,
0x7a,0xce,0x5a,0xc6,0x76,0xad,0x76,0xad,0x76,0xad,0x77,0xad,0x76,0xad,0xd7,0xbd,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,
0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0xd7,0xbd,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,
0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x19,0xbe,0x76,0xad,
0x76,0xad,0x19,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,
0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x18,0xbe,0x76,0xad,0x76,0xad,0x96,0xad,0x76,0xad,0x97,0xb5,0x5a,0xc6,0x7a,0xce,
0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xc6,0x76,0xad,0x76,0xad,0x97,0xad,
0x76,0xad,0x76,0xad,0x18,0xbe,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x19,0xbe,0x76,0xad,
0x76,0xad,0x19,0xbe,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xc6,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0xd7,0xb5,
0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0xd7,0xb5,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xc6,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,
0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0xb7,0xb5,0x76,0xad,0x96,0xb5,0x76,0xad,0x76,0xad,0xd8,0xb5,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xc6,0x7a,0xce,0x5a,0xce,
0x5a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x18,0xc6,0x76,0xad,
0x76,0xad,0x18,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xc6,0x5a,0xce,
0x7a,0xce,0x7a,0xc6,0x5a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x97,0xb5,0x76,0xad,0x96,0xad,0x76,0xad,0x76,0xad,0x19,0xc6,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,
0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x19,0xbe,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,
0xb7,0xb5,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x19,0xbe,0x76,0xad,
0x76,0xad,0x19,0xc6,
0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x96,0xad,0x76,0xad,0x77,0xad,
0x76,0xad,0x76,0xad,0x39,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,
0x7a,0xce,0x7a,0xce,0x39,0xc6,0x76,0xad,0x77,0xad,0x96,0xad,0x76,0xad,0x76,0xad,0x7a,0xce,0x5a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,
0x5a,0xce,0x7a,0xce,0x7a,0xce,0x19,0xbe,0x76,0xad,
0x76,0xad,0x19,0xbe,0x7a,0xce,0x7a,0xce,0x5a,0xc6,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xce,0x5a,0xce,0x7a,0xce,
0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xc6,0x5a,0xce,0x5a,0xce,
0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,
0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x18,0xc6,0x76,0xad,
0x76,0xad,0x19,0xc6,0x7a,0xce,0x7a,0xce,
0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x5a,0xc6,0x7a,0xce,0x7a,0xce,0x5a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,
0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,
0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,
0x7a,0xce,0x19,0xbe,0x76,0xad,
0x76,0xad,0x18,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,
0x7a,0xce,0x5a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,
0x5a,0xc6,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xc6,0x5a,0xce,0x7a,0xce,0x5a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,
0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xc6,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x19,0xc6,0x76,0xad,
0x76,0xad,0x19,0xbe,0x7a,0xce,0x7a,0xce,0x5a,0xc6,0x7a,0xce,
0x5a,0xce,0x5a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,
0x7a,0xce,0x7a,0xc6,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,
0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x18,0xbe,
0x76,0xad,
0x76,0xad,0x19,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xc6,0x5a,0xce,0x7a,0xce,0x7a,0xc6,
0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,
0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x5a,0xce,
0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x19,0xbe,0x76,0xad,
0x76,0xad,0x19,0xc6,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,
0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xc6,0x5a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,
0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xc6,0x5a,0xce,0x7a,0xce,0x7a,0xc6,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xc6,0x7a,0xce,0x7a,0xce,0x5a,0xc6,0x7a,0xce,
0x5a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x5a,0xce,0x7a,0xce,0x19,0xc6,0x76,0xad,
0x76,0xad,
0x18,0xbe,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,
0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xc6,0x7a,0xce,0x7a,0xce,0x5a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,
0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,
0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x18,0xbe,0x76,0xad,
0x76,0xad,0x19,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xce,0x5a,0xce,0x7a,0xce,
0x7a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xc6,0x7a,0xce,0x7a,0xce,0x5a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,
0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xc6,0x7a,0xce,0x7a,0xce,
0x7a,0xc6,0x7a,0xce,0x5a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x19,0xbe,0x76,0xad,
0x76,0xad,0x19,0xc6,0x7a,0xce,
0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,
0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x5a,0xc6,0x7a,0xce,
0x7a,0xce,0x5a,0xc6,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xc6,0x7a,0xce,0x5a,0xce,
0x7a,0xce,0x7a,0xce,0x19,0xc6,0x76,0xad,
0x76,0xad,0x19,0xbe,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xc6,0x7a,0xce,0x5a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xc6,
0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xc6,0x5a,0xce,0x7a,0xce,0x5a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,
0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xc6,
0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x5a,0xce,0x7a,0xce,0x18,0xbe,0x76,0xad,
0x76,0xad,0x18,0xc6,0x7a,0xce,0x7a,0xce,0x5a,0xce,
0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x5a,0xce,0x7a,0xce,0x7a,0xc6,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,
0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xc6,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,
0x7a,0xc6,0x5a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xc6,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,
0x19,0xbe,0x76,0xad,
0x76,0xad,0x19,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xc6,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,
0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,
0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,
0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x19,0xc6,0x76,0xad,
0x76,0xad,0x19,0xbe,0x7a,0xce,0x7a,0xce,0x5a,0xc6,0x7a,0xce,0x5a,0xce,
0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xc6,0x5a,0xce,
0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xc6,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,
0x7a,0xce,0x5a,0xce,0x7a,0xc6,0x7a,0xce,0x5a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xc6,0x7a,0xce,0x7a,0xce,0x5a,0xc6,0x7a,0xce,0x18,0xc6,0x76,0xad,
0x76,0xad,0x19,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x5a,0xce,
0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,
0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x5a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,
0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x19,0xbe,0x76,0xad,
0x76,0xad,0x18,0xc6,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,
0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,
0x7a,0xce,0x7a,0xc6,0x5a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,
0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x19,0xbe,0x76,0xad,
0x76,0xad,0x19,0xbe,
0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x5a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,
0x7a,0xce,0x7a,0xc6,0x5a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,
0x7a,0xce,0x7a,0xc6,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x5a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xc6,
0x7a,0xce,0x7a,0xce,0x7a,0xce,0x18,0xc6,0x76,0xad,
0x76,0xad,0x19,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,
0x5a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x5a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,
0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,
0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x19,0xbe,0x76,0xad,
0x76,0xad,0x18,0xc6,0x7a,0xce,0x7a,0xce,
0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,
0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x5a,0xce,0x7a,0xce,0x7a,0xc6,0x5a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x5a,0xce,0x7a,0xce,
0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,
0x7a,0xce,0x19,0xbe,0x76,0xad,
0x76,0xad,0xf8,0xbd,0x5a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x5a,0xce,0x7a,0xce,0x7a,0xc6,0x5a,0xce,
0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,
0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x5a,0xc6,0x7a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x5a,0xce,0x5a,0xce,0x7a,0xc6,0x7a,0xce,
0x7a,0xce,0x5a,0xce,0x7a,0xce,0x7a,0xce,0x7a,0xc6,0x5a,0xce,0x7a,0xce,0x7a,0xce,0xf8,0xbd,0x76,0xad,
0x35,0xa5,0xb7,0xb5,0x18,0xbe,0x19,0xc6,0x19,0xbe,0x18,0xbe,
0x19,0xc6,0x19,0xbe,0x18,0xbe,0x19,0xc6,0x19,0xbe,0x18,0xbe,0x19,0xbe,0x19,0xbe,0x18,0xbe,0x19,0xbe,0x19,0xbe,0x18,0xc6,0x19,0xbe,0x19,0xbe,0x19,0xc6,0x19,0xbe,
0x19,0xbe,0x19,0xbe,0x19,0xbe,0x19,0xbe,0x19,0xbe,0x19,0xbe,0x19,0xbe,0x19,0xbe,0x19,0xc6,0x19,0xbe,0x19,0xbe,0x19,0xbe,0x19,0xc6,0x19,0xbe,0x19,0xbe,0x19,0xc6,
0x19,0xbe,0x19,0xbe,0x19,0xc6,0x19,0xbe,0x19,0xbe,0x19,0xc6,0x19,0xbe,0x19,0xbe,0x19,0xc6,0x19,0xbe,0x19,0xbe,0x19,0xc6,0x19,0xbe,0x18,0xbe,0x19,0xc6,0xb7,0xb5,
0x35,0xa5,
0x5a,0xce,0x35,0xa5,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,
0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,
0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,
0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x76,0xad,0x35,0xa5,0x59,0xce,
0x1c,0xdf,0x1c,0xe7,0x1c,0xdf,0x1c,0xe7,0x1c,0xe7,0x1c,0xe7,0x1c,0xdf,0x1c,0xe7,
0x1c,0xe7,0x1c,0xe7,0x1c,0xe7,0x1c,0xe7,0x1c,0xe7,0x1c,0xe7,0x1c,0xe7,0x1c,0xe7,0x1c,0xe7,0x1c,0xe7,0x1c,0xe7,0x1c,0xe7,0x1c,0xdf,0x1c,0xe7,0x1c,0xe7,0x1c,0xe7,
0x1c,0xe7,0x1c,0xe7,0x1c,0xe7,0x1c,0xe7,0x1c,0xe7,0x1c,0xe7,0x1c,0xe7,0x1c,0xe7,0x1c,0xe7,0x1c,0xe7,0x1c,0xdf,0x1c,0xe7,0x1c,0xe7,0x1c,0xe7,0x1c,0xe7,0x1c,0xdf,
0x1c,0xe7,0x1c,0xe7,0x1c,0xe7,0x1c,0xe7,0x1c,0xe7,0x1c,0xdf,0x1c,0xe7,0x1c,0xe7,0x1c,0xe7,0x1c,0xdf,0x1c,0xe7,0x1c,0xe7,0x1d,0xdf,0x1c,0xe7,0x1c,0xdf,
0x1c,0xdf,
0x1d,0xe7,0x1c,0xdf,0x1c,0xdf,0x1d,0xe7,0x1d,0xdf,0x1c,0xdf,0x1c,0xe7,0x1d,0xdf,0x1d,0xdf,0x1c,0xdf,0x1c,0xe7,0x1d,0xdf,0x1d,0xdf,0x1c,0xe7,0x1c,0xdf,0x1d,0xdf,
0x1c,0xdf,0x1d,0xe7,0x1c,0xdf,0x1d,0xdf,0x1c,0xe7,0x1c,0xdf,0x1c,0xdf,0x1d,0xe7,0x1c,0xdf,0x1d,0xdf,0x1c,0xe7,0x1d,0xdf,0x1c,0xdf,0x1c,0xdf,0x1d,0xdf,0x1c,0xdf,
0x1c,0xe7,0x1d,0xdf,0x1d,0xdf,0x1c,0xe7,0x1d,0xdf,0x1c,0xdf,0x1d,0xe7,0x1d,0xdf,0x1c,0xdf,0x1d,0xdf,0x1c,0xe7,0x1c,0xdf,0x1c,0xdf,0x1d,0xe7,0x1c,0xdf,0x1c,0xdf,
0x1d,0xe7,0x1c,0xdf,0x1d,0xdf,0x1c,0xe7,0x1d,0xdf,0x1c,0xe7
};
| 123.186312 | 160 | 0.793784 | ramkumarkoppu |
38e50fec5d804c5f4a47ca0a69557151fd881378 | 68 | hpp | C++ | include/containers/span.hpp | SakuraEngine/Sakura.Runtime | 5a397fb2b1285326c4216f522fe10e347bd566f7 | [
"MIT"
] | 29 | 2021-11-19T11:28:22.000Z | 2022-03-29T00:26:51.000Z | include/containers/span.hpp | SakuraEngine/Sakura.Runtime | 5a397fb2b1285326c4216f522fe10e347bd566f7 | [
"MIT"
] | null | null | null | include/containers/span.hpp | SakuraEngine/Sakura.Runtime | 5a397fb2b1285326c4216f522fe10e347bd566f7 | [
"MIT"
] | 1 | 2022-03-05T08:14:40.000Z | 2022-03-05T08:14:40.000Z | #pragma once
#include <gsl/span>
namespace skr
{
using gsl::span;
} | 9.714286 | 19 | 0.705882 | SakuraEngine |
38e5b5850623304281363d81c433db97cc398052 | 2,224 | cpp | C++ | test/openpower-pels/pel_rules_test.cpp | Alpana07/phosphor-logging | 1be39849bd974c2f7df7fa932edcd7f71a2c6d59 | [
"Apache-2.0"
] | 14 | 2021-11-04T07:47:37.000Z | 2022-03-21T10:10:30.000Z | test/openpower-pels/pel_rules_test.cpp | Alpana07/phosphor-logging | 1be39849bd974c2f7df7fa932edcd7f71a2c6d59 | [
"Apache-2.0"
] | 26 | 2017-02-02T08:20:10.000Z | 2021-11-16T18:28:44.000Z | test/openpower-pels/pel_rules_test.cpp | Alpana07/phosphor-logging | 1be39849bd974c2f7df7fa932edcd7f71a2c6d59 | [
"Apache-2.0"
] | 28 | 2016-07-20T16:46:54.000Z | 2022-03-16T11:20:03.000Z | #include "extensions/openpower-pels/pel_rules.hpp"
#include <gtest/gtest.h>
using namespace openpower::pels;
struct CheckParams
{
// pel_rules::check() inputs
uint16_t actionFlags;
uint8_t eventType;
uint8_t severity;
// pel_rules::check() expected outputs
uint16_t expectedActionFlags;
uint8_t expectedEventType;
};
const uint8_t sevInfo = 0x00;
const uint8_t sevRecovered = 0x10;
const uint8_t sevPredictive = 0x20;
const uint8_t sevUnrecov = 0x40;
const uint8_t sevCrit = 0x50;
const uint8_t sevDiagnostic = 0x60;
const uint8_t sevSymptom = 0x70;
const uint8_t typeNA = 0x00;
const uint8_t typeMisc = 0x01;
const uint8_t typeTracing = 0x02;
const uint8_t typeDumpNotif = 0x08;
TEST(PELRulesTest, TestCheckRules)
{
// Impossible to cover all combinations, but
// do some interesting ones.
std::vector<CheckParams> testParams{
// Informational errors w/ empty action flags
// and different event types.
{0, typeNA, sevInfo, 0x6000, typeMisc},
{0, typeMisc, sevInfo, 0x6000, typeMisc},
{0, typeTracing, sevInfo, 0x6000, typeTracing},
{0, typeDumpNotif, sevInfo, 0x2000, typeDumpNotif},
// Informational errors with wrong action flags
{0x8900, typeNA, sevInfo, 0x6000, typeMisc},
// Informational errors with extra valid action flags
{0x00C0, typeMisc, sevInfo, 0x60C0, typeMisc},
// Informational - don't report
{0x1000, typeMisc, sevInfo, 0x5000, typeMisc},
// Recovered will report as hidden
{0, typeNA, sevRecovered, 0x6000, typeNA},
// The 5 error severities will have:
// service action, report, call home
{0, typeNA, sevPredictive, 0xA800, typeNA},
{0, typeNA, sevUnrecov, 0xA800, typeNA},
{0, typeNA, sevCrit, 0xA800, typeNA},
{0, typeNA, sevDiagnostic, 0xA800, typeNA},
{0, typeNA, sevSymptom, 0xA800, typeNA}};
for (const auto& entry : testParams)
{
auto [actionFlags, type] = pel_rules::check(
entry.actionFlags, entry.eventType, entry.severity);
EXPECT_EQ(actionFlags, entry.expectedActionFlags);
EXPECT_EQ(type, entry.expectedEventType);
}
}
| 30.465753 | 64 | 0.674011 | Alpana07 |
38e7aed3d3d330732e07aaf5c614bca861a61139 | 6,000 | hpp | C++ | sparta/python/sparta_support/PythonInterpreter.hpp | knute-sifive/map | fb25626830a56ad68ab896bcd01929023ff31c48 | [
"MIT"
] | null | null | null | sparta/python/sparta_support/PythonInterpreter.hpp | knute-sifive/map | fb25626830a56ad68ab896bcd01929023ff31c48 | [
"MIT"
] | null | null | null | sparta/python/sparta_support/PythonInterpreter.hpp | knute-sifive/map | fb25626830a56ad68ab896bcd01929023ff31c48 | [
"MIT"
] | null | null | null | // <PythonInterpreter.h> -*- C++ -*-
/*!
* \file PythonInterpreter.h
* \brief Instantiates python interpreter instance
*/
#ifndef __SPARTA_PYTHONINTERPRETER_H__
#define __SPARTA_PYTHONINTERPRETER_H__
#include "sparta/sparta.hpp" // For macro definitions
#include "simdb_fwd.hpp"
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#ifndef __USE_GNU
#define __USE_GNU
#endif
#include <signal.h>
#include <string>
#include <memory>
#include <Python.h>
namespace sparta {
class RootTreeNode;
namespace app {
class Simulation;
class SimulationConfiguration;
class ReportConfiguration;
}
namespace control {
class TemporaryRunControl;
}
namespace statistics {
class StatisticsArchives;
class StatisticsStreams;
}
namespace async {
class AsynchronousTaskEval;
}
namespace python {
/*!
* \brief Stack-based GIL lock
*/
class LocalGIL {
PyGILState_STATE gstate_;
public:
LocalGIL() :
gstate_(PyGILState_Ensure())
{}
~LocalGIL() {
PyGILState_Release(gstate_);
}
};
/*!
* \brief Wraps pyhton initialization into a class
*
* \warning Python can only be initlized once per process. Multiple interpreters
* can be created. This initializeds Python and creates interpreters. Do not
* instantiate if Python is initialized already.)
*
* \note May be able to instantiate this multiple times per process as long as
* lifestpans do not overlap but this is untested and no known use exists at
* this point
*/
class PythonInterpreter {
std::unique_ptr<char[]> progname_;
std::unique_ptr<char[]> homedir_;
struct sigaction sigint_act_; //!< signal action
struct sigaction sigint_next_; //!< Next handler in chain (replaced by this class)
/*!
* \brief Run control interface currently being used
* \todo Support multiple RC interfaces
*/
control::TemporaryRunControl* run_controller_ = nullptr;
public:
/*!
* \brief Helper to statically track that one intpreter instance exists at a time
*
* Sets flag when created and clears flag when destructed. Instantiated through a member
* of interpreter so that it will always be cleanly destructed (setting flag to false)
* when the interpreter class is destroyed no matter where the owning class fails
*
* This is necessary to help ensure that one instance of this class exist at a time so that
* signal handlers can be properly mainained
*/
class SingleInstanceForce {
static PythonInterpreter* curinstance_;
public:
SingleInstanceForce(PythonInterpreter* inst) {
sparta_assert(curinstance_ == nullptr,
"Attempted to create a new Python interpreter instance while another was still alive.");
curinstance_ = inst;
}
~SingleInstanceForce() {
curinstance_ = nullptr;
}
static PythonInterpreter* getCurInstance() { return curinstance_; }
};
PythonInterpreter(const std::string& progname,
const std::string& homedir,
int argc,
char** argv);
~PythonInterpreter();
//! ========================================================================
//! Global State
//! @{
std::string getExecPrefix() const;
std::string getPythonFullPath() const;
std::string getPath() const;
std::string getVersion() const;
std::string getPlatform() const;
std::string getCompiler() const;
void publishSimulationConfiguration(app::SimulationConfiguration * sim_config);
void publishReportConfiguration(app::ReportConfiguration * report_config);
void publishStatisticsArchives(statistics::StatisticsArchives * archives);
void publishStatisticsStreams(statistics::StatisticsStreams * streams);
void publishSimulationDatabase(simdb::ObjectManager * sim_db);
void publishDatabaseController(simdb::AsyncTaskEval * db_queue);
void publishSimulator(app::Simulation * sim);
void publishTree(RootTreeNode * n);
void publishRunController(control::TemporaryRunControl* rc);
void removePublishedObject(const void * obj_this_ptr);
/*!
* \brief Temporary interactive REPL loop
* \post Updates exit code with simulation result. Should not allow Python or C++ exceptions
* to bubble out of this function except for framework errors (C++ exceptions only)
* \see getExitCode
*/
void interact();
/*!
* \brief Handle a SIGINT signal
*/
void handleSIGINT(siginfo_t * info, void * ucontext);
/*!
* \brief Exit the shell and return control from interact
*/
void asyncExit(int exit_code);
/*!
* \brief IPython hook callback handler before each prompt display
*/
void IPyPrePrompt(PyObject* embed_shell);
/*!
* \brief IPython hook callback handler once IPython shell is initialized
*/
void IPyShellInitialized();
/*!
* \brief Return the exit code set by asyncExit (0 not asyncExit not called)
*/
int getExitCode() const { return exit_code_; }
private:
SingleInstanceForce sif_;
std::unique_ptr<PyObject, void (*)(PyObject*)> ipython_inst_;
int exit_code_ = 0;
//! Mapping from void* (published object's this pointer) to the
//! Python variable name it was published to.
std::unordered_map<const void*, std::string> published_obj_names_;
};
} // namespace python
} // namespace sparta
#endif // #ifndef __SPARTA_PYTHONINTERPRETER_H__
| 28.169014 | 116 | 0.625333 | knute-sifive |
38e7c9a39b18084efa26053ed9d8f55acf0fb4d2 | 4,123 | cc | C++ | src/invadermanager.cc | CS126SP20/space-invaders | 42b3021f04b41821c6fc203c6de74352f9c2afa5 | [
"MIT"
] | null | null | null | src/invadermanager.cc | CS126SP20/space-invaders | 42b3021f04b41821c6fc203c6de74352f9c2afa5 | [
"MIT"
] | null | null | null | src/invadermanager.cc | CS126SP20/space-invaders | 42b3021f04b41821c6fc203c6de74352f9c2afa5 | [
"MIT"
] | 1 | 2021-01-09T23:47:18.000Z | 2021-01-09T23:47:18.000Z | // Copyright (c) 2020 Saurav Raghavendra. All rights reserved.
#include "spaceinvaders/invadermanager.h"
namespace spaceinvaders {
using cinder::app::getWindowHeight;
using cinder::app::getWindowWidth;
namespace {
const int kMaxInvaders = 55;
}
InvaderManager::InvaderManager()
: step_gap_(std::chrono::seconds(static_cast<long>(0.5f))),
invader_renderer_(0, 25, Invader::kWidth, 25 + Invader::kHeight,
"invader.png"),
step_timer_(true),
alive_invaders_(0) {
const int gap = 10;
for (int y = 0; y < 5; y++) {
for (int x = 0; x < 11; x++) {
float invader_x = static_cast<float>(x) * Invader::kWidth +
static_cast<float>(gap * x * 3) + Invader::kWidth;
float invader_y = static_cast<float>(y) * Invader::kHeight +
static_cast<float>(gap * y) + Invader::kHeight * 4;
invaders_.emplace_back(cinder::vec2{invader_x, invader_y});
}
}
}
void InvaderManager::TryStepInvaders() {
if (step_timer_.getSeconds() > step_gap_.count()) {
invader_renderer_.NextFrame();
bool MoveDown = false;
float step = is_moving_left ? -0.8f : 0.8f;
if (move_down_) {
step *= -1;
}
for (auto &invader : invaders_) {
if (!invader.IsAlive()) {
continue;
}
invader.Move(step, 0.0f);
if (move_down_) {
invader.Move(0, Invader::kHeight / 2.0f);
} else if (!MoveDown) {
MoveDown = TestInvaderPosition(invader);
}
}
if (move_down_) {
is_moving_left = !is_moving_left;
}
move_down_ = MoveDown;
step_timer_.start();
}
}
void InvaderManager::DrawInvaders() {
for (auto &invader : invaders_) {
if (!invader.IsAlive()) {
continue;
}
invader_renderer_.RenderEntity(invader.GetPosition());
}
}
auto InvaderManager::TryCollideWithProjectiles(
std::vector<Projectile> &projectiles) -> CollisionResult {
CollisionResult result;
std::vector<cinder::vec2> collisionPoints;
for (auto &projectile : projectiles) {
for (auto &invader : invaders_) {
if (!invader.IsAlive() || !projectile.IsActive()) {
continue;
}
if (projectile.TryCollideWith(invader)) {
alive_invaders_--;
if (alive_invaders_ == 0) {
has_all_invaders_been_added_ = false;
}
result.second.emplace_back(invader.GetPosition());
result.first += 20;
UpdateStepDelay();
}
}
}
return result;
}
auto InvaderManager::GetRandomLowestInvaderPoint(cinder::Rand &random)
-> cinder::vec2 {
if (alive_invaders_ == 0) {
return {-1, -1};
}
while (true) {
auto invader_column = random.nextInt(0, 10);
for (int y = 4; y >= 0; y--) {
int index = y * 11 + invader_column;
auto &invader = invaders_.at(index);
if (invader.IsAlive()) {
return {invader.GetPosition().x + Invader::kWidth / 2,
invader.GetPosition().y + Invader::kHeight + 5};
}
}
}
}
void InvaderManager::InitAddInvader() {
static cinder::Timer delay(true);
if (delay.getSeconds() > 0.02) {
invaders_.at(init_y_ * 11 + init_x_).MakeAlive();
alive_invaders_++;
init_x_++;
if (init_x_ == 11) {
init_x_ = 0;
init_y_--;
}
delay.start();
}
if (alive_invaders_ == kMaxInvaders) {
has_all_invaders_been_added_ = true;
init_x_ = 0;
init_y_ = 4;
UpdateStepDelay();
}
}
auto InvaderManager::AreInvadersAlive() const -> bool {
return has_all_invaders_been_added_;
}
void InvaderManager::UpdateStepDelay() {
step_gap_ = std::chrono::seconds(
static_cast<int32_t>(static_cast<float>(alive_invaders_) / 90.0f));
}
auto InvaderManager::TestInvaderPosition(const Invader &invader) -> bool {
if (invader.GetPosition().y > static_cast<float>(getWindowHeight()) - 75) {
is_game_over_ = true;
}
return (invader.GetPosition().x < 15 && is_moving_left) ||
(invader.GetPosition().x + Invader::kWidth >
static_cast<float>(getWindowWidth()) - 15 &&
!is_moving_left);
}
} // namespace spaceinvaders
| 26.6 | 77 | 0.616299 | CS126SP20 |
38f66d481e09853a71bacb11618578718dce8692 | 4,046 | cpp | C++ | example/flappy_world.cpp | linussjo/linussjo_engine | 6a5db383633ffb99a2e83666e74fe7159d7b0c53 | [
"MIT"
] | null | null | null | example/flappy_world.cpp | linussjo/linussjo_engine | 6a5db383633ffb99a2e83666e74fe7159d7b0c53 | [
"MIT"
] | 4 | 2020-02-20T20:16:21.000Z | 2020-07-06T16:36:26.000Z | example/flappy_world.cpp | linussjo/linussjo_engine | 6a5db383633ffb99a2e83666e74fe7159d7b0c53 | [
"MIT"
] | null | null | null | //
// flappy_world.cpp
// linussjo_engine
//
// Created by Linus Sjöström on 2019-09-30.
// Copyright © 2019 Linus Sjöström. All rights reserved.
//
#include "flappy_world.hpp"
flappy_world::flappy_world(const std::shared_ptr<engine::graphic::graphic_engine> &ge, unsigned int w, unsigned int h) : world(ge, w, h){}
void flappy_world::first_prepare()
{
this->right = std::make_shared<engine::graphic::shape::texture>(engine::math::point2d{0,0}, std::string(IMG_RESOURCE+"/8-bit_Andreas.png"), 3);
this->left = std::make_shared<engine::graphic::shape::texture>(engine::math::point2d{0,0}, std::string(IMG_RESOURCE+"/8-bit_AndreasLeft.png"), 3);
auto po = std::make_shared<engine::physic::physical_object>(this->right);
this->left->is_visible = false;
po->pos = engine::math::vector2d{200,350};
po->velocity.x = 0;
po->is_affected_by_gravity = true;
po->width = 36;
po->height = 50;
this->character = po;
this->character->insert_shape(this->left);
this->append_po_object(po);
}
void flappy_world::create_obstacles()
{
auto re3 = std::make_shared<engine::graphic::shape::rectangle>(engine::math::point2d{0,0}, 50,2500);
auto po3 = std::make_shared<engine::physic::physical_object>(re3);
po3->height = 50;
po3->width = 2500;
po3->pos = engine::math::vector2d{100,600};
po3->is_affected_by_gravity = false;
po3->is_static = true;
this->append_po_object(po3);
auto re4 = std::make_shared<engine::graphic::shape::rectangle>(engine::math::point2d{0,0}, 75,200);
auto po4 = std::make_shared<engine::physic::physical_object>(re4);
po4->height = 75;
po4->width = 200;
po4->pos = engine::math::vector2d{400,450};
po4->is_affected_by_gravity = false;
po4->is_static = true;
this->append_po_object(po4);
auto re5 = std::make_shared<engine::graphic::shape::rectangle>(engine::math::point2d{0,0}, 200, 50);
auto po5 = std::make_shared<engine::physic::physical_object>(re5);
po5->height = 200;
po5->width = 50;
po5->pos = engine::math::vector2d{949,300};
po5->is_affected_by_gravity = false;
po5->is_static = true;
this->append_po_object(po5);
}
void flappy_world::prepare()
{
this->character->pos = engine::math::vector2d{500,350};
this->get_graphic_engine()->prepare_draw_for_focus(this->last_pos.x - this->character->pos.x, this->last_pos.y - this->character->pos.y);
this->character->velocity = engine::math::vector2f{0,0};
this->create_obstacles();
this->last_pos = this->character->pos;
}
void flappy_world::on_iteration()
{
this->get_graphic_engine()->prepare_draw_for_focus(this->last_pos.x - this->character->pos.x, this->last_pos.y - this->character->pos.y);
}
void flappy_world::on_key_input(GLFWwindow* window, int key, int scancode, int action, int mods)
{
if (key == GLFW_KEY_SPACE && action == GLFW_PRESS && this->character->is_grounded)
{
this->character->velocity.y = -400;
this->character->is_grounded = false;
}
if (key == GLFW_KEY_LEFT && action == GLFW_PRESS)
{
this->character->velocity.x = -300;
this->left->is_visible = true;
this->right->is_visible = false;
}
if (key == GLFW_KEY_RIGHT && action == GLFW_PRESS)
{
this->character->velocity.x = 300;
this->left->is_visible = false;
this->right->is_visible = true;
}
if (key == GLFW_KEY_UP && action == GLFW_PRESS)
{
this->character->velocity.y = -400;
}
if (key == GLFW_KEY_DOWN && action == GLFW_PRESS)
{
this->character->velocity.y = 300;
}
if ((key == GLFW_KEY_ESCAPE || key == GLFW_KEY_Q) && action == GLFW_PRESS)
{
this->continue_run = false;
}
if((key == GLFW_KEY_LEFT || key == GLFW_KEY_RIGHT) && action == GLFW_RELEASE)
{
this->character->velocity.x = 0;
}
if((key == GLFW_KEY_UP || key == GLFW_KEY_DOWN) && action == GLFW_RELEASE)
{
this->character->velocity.y = 0;
}
}
| 34 | 150 | 0.642116 | linussjo |
38f78352a606e9a9500733f7a5dee45abd5f97c7 | 5,958 | cpp | C++ | modules/tracktion_engine/playback/graph/tracktion_ModifierNode.cpp | jbloit/tracktion_engine | b3fa7d6a3a404f64ae419abdf9c801d672cffb16 | [
"MIT",
"Unlicense"
] | 734 | 2018-11-16T09:39:40.000Z | 2022-03-30T16:56:14.000Z | modules/tracktion_engine/playback/graph/tracktion_ModifierNode.cpp | jbloit/tracktion_engine | b3fa7d6a3a404f64ae419abdf9c801d672cffb16 | [
"MIT",
"Unlicense"
] | 100 | 2018-11-16T18:04:08.000Z | 2022-03-31T17:47:53.000Z | modules/tracktion_engine/playback/graph/tracktion_ModifierNode.cpp | jbloit/tracktion_engine | b3fa7d6a3a404f64ae419abdf9c801d672cffb16 | [
"MIT",
"Unlicense"
] | 123 | 2018-11-16T15:51:50.000Z | 2022-03-29T12:21:27.000Z | /*
,--. ,--. ,--. ,--.
,-' '-.,--.--.,--,--.,---.| |,-.,-' '-.`--' ,---. ,--,--, Copyright 2018
'-. .-'| .--' ,-. | .--'| /'-. .-',--.| .-. || \ Tracktion Software
| | | | \ '-' \ `--.| \ \ | | | |' '-' '| || | Corporation
`---' `--' `--`--'`---'`--'`--' `---' `--' `---' `--''--' www.tracktion.com
Tracktion Engine uses a GPL/commercial licence - see LICENCE.md for details.
*/
#pragma once
namespace tracktion_engine
{
ModifierNode::ModifierNode (std::unique_ptr<Node> inputNode,
tracktion_engine::Modifier::Ptr modifierToProcess,
double sampleRateToUse, int blockSizeToUse,
const TrackMuteState* trackMuteStateToUse,
tracktion_graph::PlayHeadState& playHeadStateToUse, bool rendering)
: input (std::move (inputNode)),
modifier (std::move (modifierToProcess)),
trackMuteState (trackMuteStateToUse),
playHeadState (&playHeadStateToUse),
isRendering (rendering)
{
jassert (input != nullptr);
jassert (modifier != nullptr);
initialiseModifier (sampleRateToUse, blockSizeToUse);
}
ModifierNode::ModifierNode (std::unique_ptr<Node> inputNode,
tracktion_engine::Modifier::Ptr modifierToProcess,
double sampleRateToUse, int blockSizeToUse,
std::shared_ptr<InputProvider> contextProvider)
: input (std::move (inputNode)),
modifier (std::move (modifierToProcess)),
audioRenderContextProvider (std::move (contextProvider))
{
jassert (input != nullptr);
jassert (modifier != nullptr);
initialiseModifier (sampleRateToUse, blockSizeToUse);
}
ModifierNode::~ModifierNode()
{
if (isInitialised && ! modifier->baseClassNeedsInitialising())
modifier->baseClassDeinitialise();
}
//==============================================================================
tracktion_graph::NodeProperties ModifierNode::getNodeProperties()
{
auto props = input->getNodeProperties();
props.numberOfChannels = juce::jmax (props.numberOfChannels, modifier->getAudioInputNames().size());
props.hasAudio = props.hasAudio || modifier->getAudioInputNames().size() > 0;
props.hasMidi = props.hasMidi || modifier->getMidiInputNames().size() > 0;
props.nodeID = (size_t) modifier->itemID.getRawID();
return props;
}
void ModifierNode::prepareToPlay (const tracktion_graph::PlaybackInitialisationInfo& info)
{
juce::ignoreUnused (info);
jassert (sampleRate == info.sampleRate);
auto props = getNodeProperties();
if (props.latencyNumSamples > 0)
automationAdjustmentTime = -tracktion_graph::sampleToTime (props.latencyNumSamples, sampleRate);
}
void ModifierNode::process (ProcessContext& pc)
{
auto inputBuffers = input->getProcessedOutput();
auto& inputAudioBlock = inputBuffers.audio;
auto& outputBuffers = pc.buffers;
auto& outputAudioBlock = outputBuffers.audio;
// Copy the inputs to the outputs, then process using the
// output buffers as that will be the correct size
if (auto numInputChannelsToCopy = std::min (inputAudioBlock.getNumChannels(),
outputAudioBlock.getNumChannels()))
{
jassert (inputAudioBlock.getNumFrames() == outputAudioBlock.getNumFrames());
copy (outputAudioBlock.getFirstChannels (numInputChannelsToCopy),
inputAudioBlock.getFirstChannels (numInputChannelsToCopy));
}
// Setup audio buffers
auto outputAudioBuffer = tracktion_graph::toAudioBuffer (outputAudioBlock);
// Then MIDI buffers
midiMessageArray.copyFrom (inputBuffers.midi);
bool shouldProcess = getBoolParamValue (*modifier->enabledParam);
if (playHeadState != nullptr && playHeadState->didPlayheadJump())
midiMessageArray.isAllNotesOff = true;
if (trackMuteState != nullptr)
{
if (! trackMuteState->shouldTrackContentsBeProcessed())
{
shouldProcess = shouldProcess && trackMuteState->shouldTrackBeAudible();
if (trackMuteState->wasJustMuted())
midiMessageArray.isAllNotesOff = true;
}
}
// Process the plugin
if (shouldProcess)
modifier->baseClassApplyToBuffer (getPluginRenderContext (pc.referenceSampleRange.getStart(), outputAudioBuffer));
// Then copy the buffers to the outputs
outputBuffers.midi.copyFrom (midiMessageArray);
}
//==============================================================================
void ModifierNode::initialiseModifier (double sampleRateToUse, int blockSizeToUse)
{
sampleRate = sampleRateToUse;
modifier->baseClassInitialise (sampleRate, blockSizeToUse);
isInitialised = true;
}
PluginRenderContext ModifierNode::getPluginRenderContext (int64_t referenceSamplePosition, juce::AudioBuffer<float>& destBuffer)
{
if (audioRenderContextProvider != nullptr)
{
tracktion_engine::PluginRenderContext rc (audioRenderContextProvider->getContext());
rc.destBuffer = &destBuffer;
rc.bufferStartSample = 0;
rc.bufferNumSamples = destBuffer.getNumSamples();
rc.bufferForMidiMessages = &midiMessageArray;
rc.midiBufferOffset = 0.0;
return rc;
}
jassert (playHeadState != nullptr);
auto& playHead = playHeadState->playHead;
return { &destBuffer,
juce::AudioChannelSet::canonicalChannelSet (destBuffer.getNumChannels()),
0, destBuffer.getNumSamples(),
&midiMessageArray, 0.0,
tracktion_graph::sampleToTime (playHead.referenceSamplePositionToTimelinePosition (referenceSamplePosition), sampleRate) + automationAdjustmentTime,
playHead.isPlaying(), playHead.isUserDragging(), isRendering, false };
}
}
| 37.949045 | 161 | 0.631252 | jbloit |
38fabda2e73e66e49bb6f3093e22e2076bf78337 | 7,556 | cpp | C++ | src/UdpUserSocketImpl.cpp | geraldselvino/GNSNet | 8d3b022186a1a3163a6466169f092b22390e8cae | [
"MIT"
] | null | null | null | src/UdpUserSocketImpl.cpp | geraldselvino/GNSNet | 8d3b022186a1a3163a6466169f092b22390e8cae | [
"MIT"
] | null | null | null | src/UdpUserSocketImpl.cpp | geraldselvino/GNSNet | 8d3b022186a1a3163a6466169f092b22390e8cae | [
"MIT"
] | null | null | null | #include "UdpUserSocket.h"
#include "UdpUserSocketImpl.h"
#include "ScopeLock.h"
/**
* Definition of the Handle class(UdpUserSocket)
*/
GNSNet::UdpUserSocket::UdpUserSocket()
: pImplUdpUserSocket(gcnew UdpUserSocketImpl())
{
}
GNSNet::UdpUserSocket::~UdpUserSocket()
{
delete pImplUdpUserSocket;
}
bool GNSNet::UdpUserSocket::CreateSocket(int PortNo)
{
return pImplUdpUserSocket->CreateSocket(PortNo);
}
bool GNSNet::UdpUserSocket::CreateSocket(int PortNo, String^ const% HostName)
{
return pImplUdpUserSocket->CreateSocket(PortNo, HostName);
}
bool GNSNet::UdpUserSocket::ShutDown()
{
return pImplUdpUserSocket->ShutDown();
}
bool GNSNet::UdpUserSocket::Send(String^ const% SendData)
{
return pImplUdpUserSocket->Send(SendData);
}
bool GNSNet::UdpUserSocket::Send(String^ const% SendData, String^ const% HostName, int PortNo)
{
return pImplUdpUserSocket->Send(SendData, HostName, PortNo);
}
bool GNSNet::UdpUserSocket::Send(String^ const% SendData, int Count)
{
return pImplUdpUserSocket->Send(SendData, Count);
}
bool GNSNet::UdpUserSocket::Recv(String^% pData)
{
return pImplUdpUserSocket->Recv(pData);
}
bool GNSNet::UdpUserSocket::DiscoverClientName()
{
return pImplUdpUserSocket->DiscoverClientName();
}
bool GNSNet::UdpUserSocket::GetClientName(String^% HostName, String^% PortNo)
{
return pImplUdpUserSocket->GetClientName(HostName, PortNo);
}
int GNSNet::UdpUserSocket::LastError()
{
return pImplUdpUserSocket->LastError();
}
bool GNSNet::UdpUserSocket::IsEnableSocket()
{
return pImplUdpUserSocket->IsEnableSocket();
}
/**
* Definition of the Body class(UdpUserSocketImpl)
*/
GNSNet::UdpUserSocketImpl::UdpUserSocketImpl()
: Socket(System::Net::Sockets::AddressFamily::InterNetwork,
System::Net::Sockets::SocketType::Dgram,
System::Net::Sockets::ProtocolType::Udp),
m_DataLen(0),
m_RecvBuf(gcnew array<Byte>(UDPRECVBUF_SIZE)),
m_SockStatus(false),
m_HostName(""),
m_Port(""),
m_nLastError(0)
{
}
GNSNet::UdpUserSocketImpl::~UdpUserSocketImpl()
{
}
bool GNSNet::UdpUserSocketImpl::CreateSocket(int PortNo)
{
return CreateSocket(PortNo, "");
}
bool GNSNet::UdpUserSocketImpl::CreateSocket(int PortNo, String^ const% HostName)
{
bool ret = true;
if(HostName == ""){
m_Kind = SERVER;
}
else{
m_Kind = CLIENT;
}
try{
if(m_Kind == SERVER){
IPEndPoint^ anyEndPoint = gcnew IPEndPoint(IPAddress::Any, PortNo);
Socket::Bind(anyEndPoint);
remoteEP = dynamic_cast<EndPoint^>(anyEndPoint);
}
else{
IPEndPoint^ serverEndPoint = gcnew IPEndPoint(IPAddress::Parse(HostName), PortNo);
remoteEP = dynamic_cast<EndPoint^>(serverEndPoint);
}
m_SockStatus = true;
SetClientName(HostName, PortNo.ToString());
}
catch(SocketException^ e){
m_nLastError = e->ErrorCode;
ret = false;
}
return ret;
}
bool GNSNet::UdpUserSocketImpl::ShutDown()
{
bool ret = true;
try{
if(IsEnableSocket()){
Socket::Shutdown(SocketShutdown::Both);
m_SockStatus = false;
}
SetClientName("", "");
Socket::Close();
}
catch(SocketException^ e){
m_nLastError = e->ErrorCode;
ret = false;
}
Thread::Sleep(100);
return ret;
}
bool GNSNet::UdpUserSocketImpl::Send(String^ const% SendData)
{
bool ret = true;
if(!IsEnableSocket()){
return false;
}
try{
array<Byte>^ t_Data;
Encoding^ l_encode = Encoding::GetEncoding("utf-32");
t_Data = l_encode->GetBytes(SendData);
Socket::SendTo(t_Data, remoteEP);
}
catch(SocketException^ e){
ret = false;
m_nLastError = e->ErrorCode;
}
return ret;
}
bool GNSNet::UdpUserSocketImpl::Send(String^ const% SendData, String^ const% HostName, int PortNo)
{
bool ret = true;
if(!IsEnableSocket()){
return false;
}
try{
IPEndPoint^ toEndpoint = gcnew IPEndPoint(IPAddress::Parse(HostName), PortNo);
array<Byte>^ t_Data;
Encoding^ l_encode = Encoding::GetEncoding("utf-32");
t_Data = l_encode->GetBytes(SendData);
Socket::SendTo(t_Data, toEndpoint);
}
catch(SocketException^ e){
ret = false;
m_nLastError = e->ErrorCode;
}
return ret;
}
bool GNSNet::UdpUserSocketImpl::Send(String^ const% SendData, int Count)
{
bool ret = true;
if(!IsEnableSocket()){
return false;
}
try{
array<Byte>^ t_Data;
Encoding^ l_encode = Encoding::GetEncoding("utf-32");
t_Data = l_encode->GetBytes(SendData);
Socket::SendTo(t_Data, Count, SocketFlags::None, remoteEP);
}
catch(SocketException^ e){
ret = false;
m_nLastError = e->ErrorCode;
}
return ret;
}
bool GNSNet::UdpUserSocketImpl::Recv(String^% pData)
{
ScopeLock l_Lock(m_RecvBuf);
bool ret = true;
pData = "";
if(!IsEnableSocket()){
return false;
}
int RecvCount = m_DataLen;
while(true){
if(GetRecord(pData, m_DataLen)){
break;
}
RecvCount = UDPRECVBUF_SIZE;
try{
m_DataLen = Socket::ReceiveFrom(m_RecvBuf, RecvCount, SocketFlags::None, remoteEP);
}
catch(SocketException^ e){
m_nLastError = e->ErrorCode;
if(m_nLastError != 10040){
m_DataLen = 0;
ret = false;
break;
}
else{
m_DataLen = RecvCount;
ret = true;
}
}
catch(InvalidOperationException^){
if(!Socket::IsBound){
m_DataLen = 0;
ret = true;
}
else{
m_DataLen = 0;
ret = false;
break;
}
}
}
return ret;
}
bool GNSNet::UdpUserSocketImpl::GetRecord(String^% pRecord, int RecvCount)
{
int RecvDataLen;
bool ret = false;
RecvDataLen = RecvCount;
if(RecvDataLen > 0){
Encoding^ l_encode = Encoding::GetEncoding("utf-32");
pRecord = l_encode->GetString(m_RecvBuf, 0, RecvCount);
delete m_RecvBuf;
m_RecvBuf = gcnew array<Byte>(UDPRECVBUF_SIZE);
m_DataLen = 0;
ret = true;
}
return ret;
}
bool GNSNet::UdpUserSocketImpl::DiscoverClientName()
{
String^ HostName;
String^ PortNo;
bool ret = true;
try{
IPEndPoint^ pRemoteEndPoint = dynamic_cast<IPEndPoint^>(remoteEP);
HostName = pRemoteEndPoint->Address->ToString();
PortNo = String::Format("{0:0000}",pRemoteEndPoint->Port.ToString());
}
catch(SocketException^ e){
HostName = "";
PortNo = "";
m_nLastError = e->ErrorCode;
ret = false;
}
SetClientName(HostName, PortNo);
return ret;
}
bool GNSNet::UdpUserSocketImpl::GetClientName(String^% HostName, String^% PortNo)
{
{
ScopeLock l_Lock(m_HostName);
HostName = m_HostName;
}
{
ScopeLock l_Lock(m_Port);
PortNo = m_Port;
}
return true;
}
bool GNSNet::UdpUserSocketImpl::SetClientName(String^ const% HostName, String^ const% PortNo)
{
{
ScopeLock l_Lock(m_HostName);
m_HostName = HostName;
}
{
ScopeLock l_Lock(m_Port);
m_Port = PortNo;
}
return true;
} | 22.158358 | 98 | 0.606935 | geraldselvino |
38fbf7654002c87ba777bd68cc15190b32a4b815 | 1,183 | cpp | C++ | core/main.cpp | 7-6-6/niggahack | 1f4f42a9fd1c89126c7d865f70eaa336ab1f6135 | [
"MIT"
] | null | null | null | core/main.cpp | 7-6-6/niggahack | 1f4f42a9fd1c89126c7d865f70eaa336ab1f6135 | [
"MIT"
] | null | null | null | core/main.cpp | 7-6-6/niggahack | 1f4f42a9fd1c89126c7d865f70eaa336ab1f6135 | [
"MIT"
] | null | null | null | #include "../dependencies/common_includes.hpp"
#include "features/misc/misc.hpp"
#include "menu/config/config.hpp"
#include "features/misc/events.hpp"
#include "features/skinchanger/parser.hpp"
unsigned long __stdcall initial_thread(void* reserved) {
while (!GetModuleHandleA("serverbrowser.dll"))
Sleep(200);
try {
interfaces::initialize();
hooks::initialize();
render.setup_fonts();
utilities::material_setup();
config_system.run("nigga hack");
events.setup();
kit_parser.setup();
}
catch (const std::runtime_error & error) {
MessageBoxA(NULL, error.what(), "nigga hack", MB_OK | MB_ICONERROR);
FreeLibraryAndExitThread(reinterpret_cast<HMODULE>(reserved), 0);
return 0ul;
}
while (!GetAsyncKeyState(VK_END))
std::this_thread::sleep_for(std::chrono::milliseconds(50));
hooks::shutdown();
std::this_thread::sleep_for(std::chrono::milliseconds(100));
FreeLibraryAndExitThread(reinterpret_cast<HMODULE>(reserved), 0);
return 0ul;
}
bool __stdcall DllMain(void* instance, unsigned long reason_to_call, void* reserved) {
if (reason_to_call == DLL_PROCESS_ATTACH) {
CreateThread(0, 0, initial_thread, instance, 0, 0);
}
return true;
} | 24.142857 | 86 | 0.734573 | 7-6-6 |
38ff7b8dc0ecf519a013dfe3ee8a0e2b2f4b6383 | 3,521 | cpp | C++ | IfcPlusPlus/src/ifcpp/IFC4/lib/IfcParameterizedProfileDef.cpp | AlexVlk/ifcplusplus | 2f8cd5457312282b8d90b261dbf8fb66e1c84057 | [
"MIT"
] | 426 | 2015-04-12T10:00:46.000Z | 2022-03-29T11:03:02.000Z | IfcPlusPlus/src/ifcpp/IFC4/lib/IfcParameterizedProfileDef.cpp | AlexVlk/ifcplusplus | 2f8cd5457312282b8d90b261dbf8fb66e1c84057 | [
"MIT"
] | 124 | 2015-05-15T05:51:00.000Z | 2022-02-09T15:25:12.000Z | IfcPlusPlus/src/ifcpp/IFC4/lib/IfcParameterizedProfileDef.cpp | AlexVlk/ifcplusplus | 2f8cd5457312282b8d90b261dbf8fb66e1c84057 | [
"MIT"
] | 214 | 2015-05-06T07:30:37.000Z | 2022-03-26T16:14:04.000Z | /* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */
#include <sstream>
#include <limits>
#include "ifcpp/model/AttributeObject.h"
#include "ifcpp/model/BuildingException.h"
#include "ifcpp/model/BuildingGuid.h"
#include "ifcpp/reader/ReaderUtil.h"
#include "ifcpp/writer/WriterUtil.h"
#include "ifcpp/IFC4/include/IfcAxis2Placement2D.h"
#include "ifcpp/IFC4/include/IfcExternalReferenceRelationship.h"
#include "ifcpp/IFC4/include/IfcLabel.h"
#include "ifcpp/IFC4/include/IfcParameterizedProfileDef.h"
#include "ifcpp/IFC4/include/IfcProfileProperties.h"
#include "ifcpp/IFC4/include/IfcProfileTypeEnum.h"
// ENTITY IfcParameterizedProfileDef
IfcParameterizedProfileDef::IfcParameterizedProfileDef( int id ) { m_entity_id = id; }
shared_ptr<BuildingObject> IfcParameterizedProfileDef::getDeepCopy( BuildingCopyOptions& options )
{
shared_ptr<IfcParameterizedProfileDef> copy_self( new IfcParameterizedProfileDef() );
if( m_ProfileType ) { copy_self->m_ProfileType = dynamic_pointer_cast<IfcProfileTypeEnum>( m_ProfileType->getDeepCopy(options) ); }
if( m_ProfileName ) { copy_self->m_ProfileName = dynamic_pointer_cast<IfcLabel>( m_ProfileName->getDeepCopy(options) ); }
if( m_Position ) { copy_self->m_Position = dynamic_pointer_cast<IfcAxis2Placement2D>( m_Position->getDeepCopy(options) ); }
return copy_self;
}
void IfcParameterizedProfileDef::getStepLine( std::stringstream& stream ) const
{
stream << "#" << m_entity_id << "= IFCPARAMETERIZEDPROFILEDEF" << "(";
if( m_ProfileType ) { m_ProfileType->getStepParameter( stream ); } else { stream << "$"; }
stream << ",";
if( m_ProfileName ) { m_ProfileName->getStepParameter( stream ); } else { stream << "$"; }
stream << ",";
if( m_Position ) { stream << "#" << m_Position->m_entity_id; } else { stream << "$"; }
stream << ");";
}
void IfcParameterizedProfileDef::getStepParameter( std::stringstream& stream, bool /*is_select_type*/ ) const { stream << "#" << m_entity_id; }
const std::wstring IfcParameterizedProfileDef::toString() const { return L"IfcParameterizedProfileDef"; }
void IfcParameterizedProfileDef::readStepArguments( const std::vector<std::wstring>& args, const std::map<int,shared_ptr<BuildingEntity> >& map )
{
const size_t num_args = args.size();
if( num_args != 3 ){ std::stringstream err; err << "Wrong parameter count for entity IfcParameterizedProfileDef, expecting 3, having " << num_args << ". Entity ID: " << m_entity_id << std::endl; throw BuildingException( err.str().c_str() ); }
m_ProfileType = IfcProfileTypeEnum::createObjectFromSTEP( args[0], map );
m_ProfileName = IfcLabel::createObjectFromSTEP( args[1], map );
readEntityReference( args[2], m_Position, map );
}
void IfcParameterizedProfileDef::getAttributes( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes ) const
{
IfcProfileDef::getAttributes( vec_attributes );
vec_attributes.emplace_back( std::make_pair( "Position", m_Position ) );
}
void IfcParameterizedProfileDef::getAttributesInverse( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes_inverse ) const
{
IfcProfileDef::getAttributesInverse( vec_attributes_inverse );
}
void IfcParameterizedProfileDef::setInverseCounterparts( shared_ptr<BuildingEntity> ptr_self_entity )
{
IfcProfileDef::setInverseCounterparts( ptr_self_entity );
}
void IfcParameterizedProfileDef::unlinkFromInverseCounterparts()
{
IfcProfileDef::unlinkFromInverseCounterparts();
}
| 55.015625 | 244 | 0.755183 | AlexVlk |
ac014641e10e2c843aa70fa79171b5705b8df544 | 5,366 | cc | C++ | physics/neutron/models/src/NeutronNudyFissionModel.cc | Geant-RnD/geant | ffff95e23547531f3254ada2857c062a31f33e8f | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2016-10-16T14:37:42.000Z | 2018-04-05T15:49:09.000Z | physics/neutron/models/src/NeutronNudyFissionModel.cc | Geant-RnD/geant | ffff95e23547531f3254ada2857c062a31f33e8f | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | physics/neutron/models/src/NeutronNudyFissionModel.cc | Geant-RnD/geant | ffff95e23547531f3254ada2857c062a31f33e8f | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | //
#include "Geant/NeutronNudyFissionModel.h"
#include "Geant/PhysicalConstants.h"
// for Vector_t
#include "Geant/Types.h"
#include "Geant/PhysicsData.h"
#include "Geant/Isotope.h"
#include "Geant/LightTrack.h"
#include "Geant/PhysicsData.h"
#include <iostream>
#include "Geant/math_wrappers.h"
// this should be replaced by some VecMath classes
#include "base/Lorentz.h"
#include "base/Vector3D.h"
namespace geantphysics {
NeutronNudyFissionModel::NeutronNudyFissionModel(const std::string &modelname) : HadronicFinalStateModel()
{
this->SetType(HadronicModelType::kNeutronNudy);
this->SetName(modelname);
std::vector<int> projVec;
projVec.push_back(1);
projVec.push_back(3);
projVec.push_back(10);
projVec.push_back(11);
projVec.push_back(12);
projVec.push_back(13);
projVec.push_back(14);
projVec.push_back(15);
projVec.push_back(16);
projVec.push_back(17);
char *path = std::getenv("GEANT_PHYSICS_DATA");
if (!path) {
std::cerr << "****** ERROR in NeutronNudyXsec() \n"
<< " GEANT_PHYSICS_DATA is not defined! Set the GEANT_PHYSICS_DATA\n"
<< " environmental variable to the location of Geant data directory\n"
<< " It should be .root file processed from ENDF data using EndfToPointRoot\n"
<< " executable. For more details see EndfToRoot in \n"
<< " physics/neutron/nudy/EndfToRoot/README\n"
<< " root file name format is n-Z_A.root!\n"
<< std::endl;
exit(1);
}
std::string tmp = path;
filename = tmp + "/neutron/nudy/n-";
this->SetProjectileCodeVec(projVec);
}
NeutronNudyFissionModel::~NeutronNudyFissionModel() {}
void NeutronNudyFissionModel::Initialize()
{
HadronicFinalStateModel::Initialize(); //
}
int NeutronNudyFissionModel::SampleFinalState(LightTrack &track, Isotope *targetisotope, geant::TaskData *td)
{
using vecgeom::LorentzRotation;
using vecgeom::LorentzVector;
using vecgeom::Vector3D;
int numSecondaries = 0;
double Ek = track.GetKinE();
// check if kinetic energy is below fLowEnergyUsageLimit and do nothing if yes;
// check if kinetic energy is above fHighEnergyUsageLimit andd o nothing if yes
if (Ek < GetLowEnergyUsageLimit() || Ek > GetHighEnergyUsageLimit()) {
return numSecondaries;
}
/*
std::cout << "NeutronNudyFissionModel: "
<< track.GetGVcode()
<< " Ekin(MeV) = " << Ek/geant::units::MeV
<< " scattered off Z= " << targetisotope->GetZ()
<< " N= " << targetisotope->GetN()
<< std::endl;
*/
int Z = targetisotope->GetZ();
int A = targetisotope->GetN();
std::string z = std::to_string(Z);
std::string a = std::to_string(A);
std::string tmp = filename + z + "_" + a + ".root";
// int particlePDG = Particle::GetParticleByInternalCode(particleCode)->GetPDGCode();
fRENDF = tmp.c_str();
int elemId = Z * 1000 + A;
recopoint.GetData(elemId, fRENDF);
// projectile mass
double mass1 = track.GetMass();
// target mass
// double mass2 = targetisotope->GetIsoMass();
// momentum in lab frame
double plab = std::sqrt(Ek * (Ek + 2 * mass1));
double nut = recopoint.GetNuTotal(elemId, Ek / geant::units::eV);
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
std::default_random_engine generator(seed);
std::poisson_distribution<int> distribution(nut);
int number = distribution(generator);
while (number == 0) {
number = distribution(generator);
}
numSecondaries = number;
for (int i = 0; i != number; ++i) {
double cosLab = recopoint.GetCos4(elemId, 2, Ek / geant::units::eV);
if (cosLab == -99) {
cosLab = 2 * td->fRndm->uniform() - 1;
}
double sinLab = 0;
// problem in sampling
if (cosLab > 1.0 || cosLab < -1.0) {
std::cout << "GVNeutronNudyFission WARNING (1 - cost)= " << 1 - cosLab << " after Fission of "
<< track.GetGVcode() << " p(GeV/c)= " << plab / geant::units::GeV
<< " on an ion Z= " << targetisotope->GetZ() << " N= " << targetisotope->GetN() << std::endl;
cosLab = 1.0;
sinLab = 0.0;
// normal situation
} else {
sinLab = std::sqrt((1.0 - cosLab) * (1.0 + cosLab));
}
double phi = geant::units::kTwoPi * td->fRndm->uniform();
double sinphi, cosphi;
Math::SinCos(phi, sinphi, cosphi);
double nDirX = sinLab * cosphi;
double nDirY = sinLab * sinphi;
double nDirZ = cosLab;
// rotate in the origional particle frame : This need to be checked: Harphool
// energy of the neutron from the ENDF distributions
double energy = recopoint.GetEnergy5(elemId, 18, Ek / geant::units::eV) * geant::units::eV;
// killing primary track after fission
track.SetTrackStatus(LTrackStatus::kKill);
track.SetKinE(0.0);
auto &secondarySoA = td->fPhysicsData->InsertSecondary();
// Add neutron
// int idx = secondarySoA.InsertTrack();
secondarySoA.SetDirX(nDirX);
secondarySoA.SetDirY(nDirY);
secondarySoA.SetDirZ(nDirZ);
secondarySoA.SetKinE(energy);
secondarySoA.SetGVcode(track.GetGVcode());
secondarySoA.SetMass(track.GetMass());
secondarySoA.SetTrackIndex(track.GetTrackIndex()); // parent Track index
}
return numSecondaries;
}
} // namespace geantphysics
| 33.962025 | 109 | 0.647782 | Geant-RnD |
ac03eb4a9a1a7a7d0847a8788296833f6c931ce3 | 58 | hpp | C++ | src/boost_fusion_include_adapt_assoc_adt_named.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 10 | 2018-03-17T00:58:42.000Z | 2021-07-06T02:48:49.000Z | src/boost_fusion_include_adapt_assoc_adt_named.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 2 | 2021-03-26T15:17:35.000Z | 2021-05-20T23:55:08.000Z | src/boost_fusion_include_adapt_assoc_adt_named.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 4 | 2019-05-28T21:06:37.000Z | 2021-07-06T03:06:52.000Z | #include <boost/fusion/include/adapt_assoc_adt_named.hpp>
| 29 | 57 | 0.844828 | miathedev |
f19bd8ffaa302bbcfb87123bcb193e816495ceb4 | 5,765 | hpp | C++ | transmission_interface_extensions/include/transmission_interface_extensions/posveleff_joint_interface_provider.hpp | smilerobotics/ros_control_extensions | 1eee21217708dcee80aa3d91b2c6415c1f4feffa | [
"MIT"
] | null | null | null | transmission_interface_extensions/include/transmission_interface_extensions/posveleff_joint_interface_provider.hpp | smilerobotics/ros_control_extensions | 1eee21217708dcee80aa3d91b2c6415c1f4feffa | [
"MIT"
] | null | null | null | transmission_interface_extensions/include/transmission_interface_extensions/posveleff_joint_interface_provider.hpp | smilerobotics/ros_control_extensions | 1eee21217708dcee80aa3d91b2c6415c1f4feffa | [
"MIT"
] | 1 | 2021-10-14T06:37:36.000Z | 2021-10-14T06:37:36.000Z | #ifndef TRANSMISSION_INTERFACE_EXTENSIONS_POSVELEFF_JOINT_INTERFACE_PROVIDER_HPP
#define TRANSMISSION_INTERFACE_EXTENSIONS_POSVELEFF_JOINT_INTERFACE_PROVIDER_HPP
#include <string>
#include <vector>
#include <hardware_interface/robot_hw.h>
#include <hardware_interface_extensions/posveleff_command_interface.hpp>
#include <transmission_interface/transmission_info.h>
// for RequisiteProvider, JointInterfaces, RawJointDataMap, JointData
#include <transmission_interface/transmission_interface_loader.h>
#include <transmission_interface_extensions/common_namespaces.hpp>
#include <transmission_interface_extensions/posvel_joint_interface_provider.hpp>
#include <boost/foreach.hpp>
namespace transmission_interface_extensions {
class PosVelEffJointInterfaceProvider : public PosVelJointInterfaceProvider {
public:
PosVelEffJointInterfaceProvider() {}
virtual ~PosVelEffJointInterfaceProvider() {}
virtual bool updateJointInterfaces(const ti::TransmissionInfo &trans_info, hi::RobotHW *robot_hw,
ti::JointInterfaces &jnt_ifaces,
ti::RawJointDataMap &raw_jnt_data_map) {
// register state interface & handles if never
if (!JointStateInterfaceProvider::updateJointInterfaces(trans_info, robot_hw, jnt_ifaces,
raw_jnt_data_map)) {
return false;
}
// register posveleff interface if never
if (!robot_hw->get< hie::PosVelEffJointInterface >()) {
robot_hw->registerInterface(&getPosVelEffJointInterface());
}
hie::PosVelEffJointInterface &iface(*robot_hw->get< hie::PosVelEffJointInterface >());
// register posveleff handle to the posvel interface if never
BOOST_FOREACH (const ti::JointInfo &jnt_info, trans_info.joints_) {
if (!hasResource(jnt_info.name_, iface)) {
ti::RawJointData &raw_jnt_data(raw_jnt_data_map[jnt_info.name_]);
iface.registerHandle(hie::PosVelEffJointHandle(
jnt_ifaces.joint_state_interface.getHandle(jnt_info.name_), &raw_jnt_data.position_cmd,
&raw_jnt_data.velocity_cmd, &raw_jnt_data.effort_cmd));
}
}
return true;
}
protected:
virtual bool getJointCommandData(const ti::TransmissionInfo &trans_info,
const ti::RawJointDataMap &raw_jnt_data_map,
ti::JointData &jnt_cmd_data) {
// get position & velocity commands
if (!PosVelJointInterfaceProvider::getJointCommandData(trans_info, raw_jnt_data_map,
jnt_cmd_data)) {
return false;
}
// allocate destination effort command data
const std::size_t dim(trans_info.joints_.size());
jnt_cmd_data.effort.resize(dim);
// map source to destination effort command data
for (std::size_t i = 0; i < dim; ++i) {
// find source data
const ti::RawJointDataMap::const_iterator raw_jnt_data(
raw_jnt_data_map.find(trans_info.joints_[i].name_));
if (raw_jnt_data == raw_jnt_data_map.end()) {
return false;
}
// map data
jnt_cmd_data.effort[i] = const_cast< double * >(&raw_jnt_data->second.effort_cmd);
}
return true;
}
virtual bool getActuatorCommandData(const ti::TransmissionInfo &trans_info, hi::RobotHW *robot_hw,
ti::ActuatorData &act_cmd_data) {
// get position & velocity commands
if (!PosVelJointInterfaceProvider::getActuatorCommandData(trans_info, robot_hw, act_cmd_data)) {
return false;
}
// find source effort command data
std::vector< hi::ActuatorHandle > act_eff_handles;
if (!getActuatorHandles< hi::EffortActuatorInterface >(trans_info.actuators_, robot_hw,
act_eff_handles)) {
return false;
}
// allocate destination actuator command data
const std::size_t dim(trans_info.actuators_.size());
act_cmd_data.effort.resize(dim);
// map source to destination actuator command data
for (std::size_t i = 0; i < dim; ++i) {
act_cmd_data.effort[i] = const_cast< double * >(act_eff_handles[i].getCommandPtr());
}
return true;
}
virtual bool registerTransmission(ti::TransmissionLoaderData &loader_data,
ti::RequisiteProvider::TransmissionHandleData &handle_data) {
// register state, position & velocity transmissions
if (!PosVelJointInterfaceProvider::registerTransmission(loader_data, handle_data)) {
return false;
}
// quick access to the transmission manager
ti::RobotTransmissions &trans_man(*loader_data.robot_transmissions);
// register effort command transmission interface if never
if (!trans_man.get< ti::JointToActuatorEffortInterface >()) {
trans_man.registerInterface(&loader_data.transmission_interfaces.jnt_to_act_eff_cmd);
}
ti::JointToActuatorEffortInterface &iface(
*trans_man.get< ti::JointToActuatorEffortInterface >());
// register effort command transmission handle if never
if (!hasResource(handle_data.name, iface)) {
iface.registerHandle(
ti::JointToActuatorEffortHandle(handle_data.name, handle_data.transmission.get(),
handle_data.act_cmd_data, handle_data.jnt_cmd_data));
}
return true;
}
private:
// return the joint interface. it must be in the static memory space
// to allow access from outside of this plugin.
static hie::PosVelEffJointInterface &getPosVelEffJointInterface() {
static hie::PosVelEffJointInterface interface;
return interface;
}
};
} // namespace transmission_interface_extensions
#endif | 39.486301 | 100 | 0.69072 | smilerobotics |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.