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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5e48b3deeca191dff86aa7d36cc8c5f2ab15b218
| 1,967
|
hpp
|
C++
|
src/viewer/tile_provider.hpp
|
malasiot/maplite
|
1edeec673110cdd5fa904ff2ff88289b6c3ec324
|
[
"MIT"
] | 12
|
2017-05-11T21:44:57.000Z
|
2021-12-30T08:35:56.000Z
|
src/viewer/tile_provider.hpp
|
malasiot/mftools
|
1edeec673110cdd5fa904ff2ff88289b6c3ec324
|
[
"MIT"
] | 8
|
2016-10-27T10:10:05.000Z
|
2019-12-07T21:27:02.000Z
|
src/viewer/tile_provider.hpp
|
malasiot/mftools
|
1edeec673110cdd5fa904ff2ff88289b6c3ec324
|
[
"MIT"
] | 5
|
2017-10-17T08:18:58.000Z
|
2021-11-12T11:44:23.000Z
|
#ifndef __TILE_PROVIDER_H__
#define __TILE_PROVIDER_H__
#include <QPixmap>
#include <QPixmapCache>
#include "geometry.hpp"
class TileProvider: public QObject
{
Q_OBJECT
public:
TileProvider(const QByteArray &id, unsigned int tileSize):
tile_size_(tileSize), id_(id), async_(false), start_zoom_(-1), has_start_position_(false) {}
virtual QImage getTile(int x, int y, int z) = 0 ;
QByteArray id() const { return id_ ; }
void setName(const QString &name) {
name_ = name ;
}
QString name() const { return name_ ; }
QString attribution() const { return attribution_ ; }
QString description() const { return description_ ; }
unsigned int tileSize() const { return tile_size_ ; }
bool isAsync() const { return async_ ; }
void coordsFromTileKey(const QByteArray &key, int &x, int &y, int &z) ;
void setDescription(const QString &desc) { description_ = desc ; }
void setAttribution(const QString &attr) { attribution_ = attr ; }
void setZoomRange(int minZ, int maxZ) { min_zoom_ = minZ ; max_zoom_ = maxZ ; }
int getStartZoom() const { return start_zoom_ ; }
QPointF getStartPosition() const { return start_position_ ; }
bool hasStartPosition() const { return has_start_position_ ; }
void setStartZoom(int z) { start_zoom_ = z ; }
void setStartPosition(const LatLon ¢er) {
start_position_ = QPointF(center.lat_, center.lon_) ;
has_start_position_ = true ;
}
virtual QByteArray key() const { return id_ ; }
virtual QByteArray tileKey(int x, int y, int z) const ;
virtual time_t creationTime() const { return 0 ; }
protected:
unsigned int tile_size_, min_zoom_, max_zoom_ ;
QString name_ ;
QByteArray id_ ;
QString attribution_, description_ ;
bool async_ ;
QPointF start_position_ ;
int start_zoom_ ;
bool has_start_position_ ;
Q_SIGNALS:
void tileReady(QByteArray, QImage) ;
} ;
#endif
| 28.926471
| 100
| 0.68124
|
malasiot
|
5e4de08ccf4c1ed4e615d55ce4b84e736ec89ffa
| 10,624
|
cpp
|
C++
|
remodet_repository_wdh_part/hp_demo_bak.cpp
|
UrwLee/Remo_experience
|
a59d5b9d6d009524672e415c77d056bc9dd88c72
|
[
"MIT"
] | null | null | null |
remodet_repository_wdh_part/hp_demo_bak.cpp
|
UrwLee/Remo_experience
|
a59d5b9d6d009524672e415c77d056bc9dd88c72
|
[
"MIT"
] | null | null | null |
remodet_repository_wdh_part/hp_demo_bak.cpp
|
UrwLee/Remo_experience
|
a59d5b9d6d009524672e415c77d056bc9dd88c72
|
[
"MIT"
] | null | null | null |
// if not use OPENCV, note it.
#include <opencv2/opencv.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
// if not use, note it.
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <map>
// Google log & flags
#include "gflags/gflags.h"
#include "glog/logging.h"
// caffe
#include "caffe/proto/caffe.pb.h"
#include "caffe/caffe.hpp"
// remo, note the useless classes.
#include "caffe/remo/remo_front_visualizer.hpp"
#include "caffe/remo/net_wrap.hpp"
#include "caffe/remo/frame_reader.hpp"
#include "caffe/remo/data_frame.hpp"
#include "caffe/remo/basic.hpp"
#include "caffe/remo/res_frame.hpp"
#include "caffe/remo/visualizer.hpp"
#include "caffe/mask/bbox_func.hpp"
#include "caffe/tracker/basic.hpp"
#include <boost/foreach.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include "caffe/det/detwrap.hpp"
#include "caffe/hp/hp_net.hpp"
using namespace std;
using namespace caffe;
using std::string;
using std::vector;
namespace bfs = boost::filesystem;
// 获取FaceBoxes: 3
void getFaceBoxes(const vector<LabeledBBox<float> >& rois, vector<BoundingBox<float> >* face_boxes) {
face_boxes->clear();
for (int i = 0; i < rois.size(); ++i) {
if (rois[i].cid != 3) continue;
face_boxes->push_back(rois[i].bbox);
}
}
// 获取HeadBoxes: 2
void getHeadBoxes(const vector<LabeledBBox<float> >& rois, vector<BoundingBox<float> >* head_boxes) {
head_boxes->clear();
for (int i = 0; i < rois.size(); ++i) {
if (rois[i].cid != 2) continue;
head_boxes->push_back(rois[i].bbox);
}
}
// 获取HandBoxes: 1
void getHandBoxes(const vector<LabeledBBox<float> >& rois, vector<BoundingBox<float> >* hand_boxes) {
hand_boxes->clear();
for (int i = 0; i < rois.size(); ++i) {
if (rois[i].cid != 1) continue;
hand_boxes->push_back(rois[i].bbox);
}
}
// 滤出HandBoxes:
// 将与Head/Face交叠的HandBoxes全部删除
void filterHandBoxes(vector<BoundingBox<float> >& hand_boxes,
const vector<BoundingBox<float> >& head_boxes,
const vector<BoundingBox<float> >& face_boxes) {
for (vector<BoundingBox<float> >::iterator it = hand_boxes.begin(); it!= hand_boxes.end();) {
bool cov = false;
// HEAD
for (int i = 0; i < head_boxes.size(); ++i) {
if (it->compute_coverage(head_boxes[i]) > 0.2) {
cov = true;
break;
}
}
// FACE
if (! cov) {
for (int i = 0; i < face_boxes.size(); ++i) {
if (it->compute_coverage(face_boxes[i]) > 0.1) {
cov = true;
break;
}
}
}
// 结论
if (cov) { // 删除之
it = hand_boxes.erase(it);
} else {
++it;
}
}
}
vector<bool> filterHandBoxesbyDistance(const vector<BoundingBox<float> >& head_boxes, const vector<BoundingBox<float> >& hand_boxes) {
vector<bool> matrix(hand_boxes.size() * head_boxes.size(), false);
vector<bool> chosen(hand_boxes.size(), false); // 未匹配过
// 距离判断
for (int i = 0; i < hand_boxes.size(); ++i) {
for (int j = 0; j < head_boxes.size(); ++j) {
float dx = hand_boxes[i].get_center_x() - head_boxes[j].get_center_x();
float dy = hand_boxes[i].get_center_y() - head_boxes[j].get_center_y();
float dis = dx * dx + dy * dy;
float size = head_boxes[j].compute_area();
matrix[i * head_boxes.size() + j] = (dis < size * 5) ? true : false;
}
}
// 择一判断
for (int j = 0; j < head_boxes.size(); ++j) {
// 选择最大的一个
int max_id = -1;
float max_area = 0;
for (int i = 0; i < hand_boxes.size(); ++i) { // 遍历所有hands
if (chosen[i]) continue; // 已经匹配过,pass
if (matrix[i * head_boxes.size() + j]) { // 匹配
const float area = hand_boxes[i].compute_area();
if (area > max_area) {
max_area = area;
max_id = i;
}
}
}
// 匹配的hand面积必须要大于head面积的一半以上
const float coeff = max_area / head_boxes[j].compute_area();
if (max_id >= 0 && coeff > 0.2) {
chosen[max_id] = true; // 匹配成功!
}
}
// 匹配成功的有效
return chosen;
}
int main(int nargc, char** args) {
// ################################ NETWORK ################################
// network input
int resized_width = 512;
int resized_height = 288;
const std::string network_proto = "/home/ethan/ForZhangM/Release20180314/Release20180314_Merged_profo2.5/Base_BD_PD_HD.prototxt";
const std::string network_model = "/home/ethan/ForZhangM/Release20180314/Release20180314_Merged_profo2.5/ResPoseDetTrackRelease_merge.caffemodel";
// GPU
int gpu_id = 0;
bool mode = true; // use GPU
// features
const std::string proposals = "det_out";
// display Size
int max_dis_size = 1280;
// active labels
vector<int> active_label;
// active_label.push_back(0);
active_label.push_back(1);
active_label.push_back(2);
// active_label.push_back(3);
// ################################ DATA ####################################
// CAMERA
const bool use_camera = true; // 0
const int cam_width = 1280;
const int cam_height = 720;
// ################################ MAIN LOOP ################################
// det_warpper
caffe::DetWrapper<float> det_wrapper(network_proto,network_model,mode,gpu_id,proposals,max_dis_size);
// HP
const string hp_network = "/home/ethan/Models/Results/HPNet/CNN_Base_V0-I96-FL/Proto/test_copy.prototxt";
// const string hp_network = "/home/ethan/Models/Results/HPNet/test.prototxt";
const string hp_model = "/home/ethan/Models/Results/HPNet/CNN_Base_V0-I96-FL/Models/CNN_Base_V0-I96-FL-ROT-20K_iter_100000.caffemodel";
// const string hp_model = "/home/ethan/Models/Results/HPNet/CNN_Base_I96-FLRTScaleAug1.5-2.0R8_V1Split1_1A_iter_100000.caffemodel";
caffe::HPNetWrapper hp_wrapper(hp_network, hp_model);
// CAMERA
if (use_camera) {
cv::VideoCapture cap;
if (!cap.open(0)) {
LOG(FATAL) << "Failed to open webcam: " << 0;
}
cap.set(CV_CAP_PROP_FRAME_WIDTH, cam_width);
cap.set(CV_CAP_PROP_FRAME_HEIGHT, cam_height);
int ex = static_cast<int>(cap.get(CV_CAP_PROP_FOURCC));
cv::VideoWriter outputVideo;
outputVideo.open("outvideo_hp_CNN_Base_I96-FLRTScaleAug1.5-2.0R8_V1Split1_1A.avi", ex, cap.get(CV_CAP_PROP_FPS), cv::Size(cam_width,cam_height), true);
cv::Mat cv_img;
cap >> cv_img;
int count = 0;
CHECK(cv_img.data) << "Could not load image.";
while (1) {
++count;
cv::Mat image;
cap >> image;
caffe::DataFrame<float> data_frame(count, image, resized_width, resized_height);
// 获取hand_detector的结果
vector<LabeledBBox<float> > rois;
det_wrapper.get_rois(data_frame, &rois);
vector<BoundingBox<float> > head_boxes;
vector<BoundingBox<float> > face_boxes;
vector<BoundingBox<float> > hand_boxes;
getHeadBoxes(rois, &head_boxes);
getFaceBoxes(rois, &face_boxes);
getHandBoxes(rois, &hand_boxes);
filterHandBoxes(hand_boxes, head_boxes, face_boxes);
/**
* 进一步滤除,每个Head最多允许一个HandBox
* (1) 滤除距离:头的max(w,h)的两倍距离,超过这个距离的全部忽略
* (2) 如果保留多个,则只选择其中面积最大的一个进行分析
*/
vector<bool> active_hands = filterHandBoxesbyDistance(head_boxes, hand_boxes);
// 绘制Head
for (int i = 0; i < head_boxes.size(); ++i) {
BoundingBox<float>& roi = head_boxes[i];
float x1 = roi.get_center_x() - 1 * roi.get_width() / 2;
float y1 = roi.get_center_y() - 1 * roi.get_height() / 2;
float x2 = roi.get_center_x() + 1 * roi.get_width() / 2;
float y2 = roi.get_center_y() + 1 * roi.get_height() / 2;
x1 = (x1 < 0) ? 0 : (x1 > 1 ? 1 : x1);
y1 = (y1 < 0) ? 0 : (y1 > 1 ? 1 : y1);
x2 = (x2 < 0) ? 0 : (x2 > 1 ? 1 : x2);
y2 = (y2 < 0) ? 0 : (y2 > 1 ? 1 : y2);
x1 *= image.cols;
x2 *= image.cols;
y1 *= image.rows;
y2 *= image.rows;
const cv::Point point1(x1, y1);
const cv::Point point2(x2, y2);
cv::rectangle(image, point1, point2, cv::Scalar(255,0,0), 3);
}
// 绘制Face
// for (int i = 0; i < face_boxes.size(); ++i) {
// BoundingBox<float>& roi = face_boxes[i];
// float x1 = roi.get_center_x() - 1 * roi.get_width() / 2;
// float y1 = roi.get_center_y() - 1 * roi.get_height() / 2;
// float x2 = roi.get_center_x() + 1 * roi.get_width() / 2;
// float y2 = roi.get_center_y() + 1 * roi.get_height() / 2;
// x1 = (x1 < 0) ? 0 : (x1 > 1 ? 1 : x1);
// y1 = (y1 < 0) ? 0 : (y1 > 1 ? 1 : y1);
// x2 = (x2 < 0) ? 0 : (x2 > 1 ? 1 : x2);
// y2 = (y2 < 0) ? 0 : (y2 > 1 ? 1 : y2);
// x1 *= image.cols;
// x2 *= image.cols;
// y1 *= image.rows;
// y2 *= image.rows;
// const cv::Point point1(x1, y1);
// const cv::Point point2(x2, y2);
// cv::rectangle(image, point1, point2, cv::Scalar(0,255,0), 3);
// }
// 绘制minihand网络的结果
for (int i = 0; i < hand_boxes.size(); ++i) {
BoundingBox<float>& roi = hand_boxes[i];
float x1 = roi.get_center_x() - 1 * roi.get_width() / 2;
float y1 = roi.get_center_y() - 1 * roi.get_height() / 2;
float x2 = roi.get_center_x() + 1 * roi.get_width() / 2;
float y2 = roi.get_center_y() + 1 * roi.get_height() / 2;
x1 = (x1 < 0) ? 0 : (x1 > 1 ? 1 : x1);
y1 = (y1 < 0) ? 0 : (y1 > 1 ? 1 : y1);
x2 = (x2 < 0) ? 0 : (x2 > 1 ? 1 : x2);
y2 = (y2 < 0) ? 0 : (y2 > 1 ? 1 : y2);
x1 *= image.cols;
x2 *= image.cols;
y1 *= image.rows;
y2 *= image.rows;
const cv::Point point1(x1, y1);
const cv::Point point2(x2, y2);
const int r = active_hands[i] ? 0 : 255;
const int g = active_hands[i] ? 255 : 0;
/**
* 获取手势
*/
if (active_hands[i]) {
float score;
int label = hp_wrapper.hpmode(image, hand_boxes[i], &score);
char tmp_str[256];
snprintf(tmp_str, 256, "%d", label);
cv::putText(image, tmp_str, cv::Point(x1, y1),
cv::FONT_HERSHEY_SIMPLEX, 3, cv::Scalar(0,0,255), 5);
}
cv::rectangle(image, point1, point2, cv::Scalar(0,g,r), 3);
}
outputVideo << image;
cv::namedWindow("RemoDet", cv::WINDOW_AUTOSIZE);
cv::imshow( "RemoDet", image);
cv::waitKey(1);
}
}
LOG(INFO) << "Finished.";
return 0;
}
| 36.634483
| 156
| 0.577654
|
UrwLee
|
5e4eeb30aab610c15d659219b4b2639ae6bf94b8
| 2,162
|
hh
|
C++
|
psdaq/psdaq/eb/Batch.hh
|
ZhenghengLi/lcls2
|
94e75c6536954a58c8937595dcac295163aa1cdf
|
[
"BSD-3-Clause-LBNL"
] | 16
|
2017-11-09T17:10:56.000Z
|
2022-03-09T23:03:10.000Z
|
psdaq/psdaq/eb/Batch.hh
|
ZhenghengLi/lcls2
|
94e75c6536954a58c8937595dcac295163aa1cdf
|
[
"BSD-3-Clause-LBNL"
] | 6
|
2017-12-12T19:30:05.000Z
|
2020-07-09T00:28:33.000Z
|
psdaq/psdaq/eb/Batch.hh
|
ZhenghengLi/lcls2
|
94e75c6536954a58c8937595dcac295163aa1cdf
|
[
"BSD-3-Clause-LBNL"
] | 25
|
2017-09-18T20:02:43.000Z
|
2022-03-27T22:27:42.000Z
|
#ifndef Pds_Eb_Batch_hh
#define Pds_Eb_Batch_hh
#include "eb.hh"
#include "psdaq/service/EbDgram.hh"
#include <cstdint> // For uint64_t
#include <cstddef> // for size_t
namespace Pds {
namespace Eb {
class Batch
{
public:
Batch();
public:
static uint64_t index(uint64_t pid);
public:
int initialize(size_t bufSize);
Pds::EbDgram* allocate(); // Allocate buffer in batch
Batch* initialize(void* region, uint64_t pid);
size_t extent() const; // Current extent
uint64_t id() const; // Batch start pulse ID
unsigned index() const; // Batch's index
const void* buffer() const; // Pointer to batch in RDMA space
void dump() const;
private:
void* _buffer; // Pointer to RDMA space for this Batch
size_t _bufSize; // Size of entries
uint64_t _id; // Id of Batch, in case it remains empty
unsigned _extent; // Current extent (unsigned is large enough)
};
};
};
inline
uint64_t Pds::Eb::Batch::index(uint64_t pid)
{
return pid & (MAX_LATENCY - 1);
}
inline
unsigned Pds::Eb::Batch::index() const
{
return index(_id);
}
inline
uint64_t Pds::Eb::Batch::id() const
{
return _id; // Full PID, not BatchNum
}
inline
const void* Pds::Eb::Batch::buffer() const
{
return _buffer;
}
inline
size_t Pds::Eb::Batch::extent() const
{
return _extent;
}
inline
Pds::Eb::Batch* Pds::Eb::Batch::initialize(void* region, uint64_t pid)
{
_id = pid; // Full PID, not BatchNum
_buffer = static_cast<char*>(region) + index(pid) * _bufSize;
_extent = 0;
//_buffer = region; // Revisit: For dense batch allocation idea
return this;
}
inline
Pds::EbDgram* Pds::Eb::Batch::allocate()
{
char* buf = static_cast<char*>(_buffer) + _extent;
_extent += _bufSize;
//if (_extent > (MAX_LATENCY - BATCH_DURATION) * _bufSize) _extent = 0; // Revisit
return reinterpret_cast<Pds::EbDgram*>(buf);
}
#endif
| 23.758242
| 85
| 0.584181
|
ZhenghengLi
|
5e5016ca697c7845540ba25711dcfef827df438b
| 1,221
|
cpp
|
C++
|
src/EnemyWandering.cpp
|
anqin-gh/minimaze
|
cfa3df279c75d5fe95a2e69af4569a3981a6f274
|
[
"MIT"
] | null | null | null |
src/EnemyWandering.cpp
|
anqin-gh/minimaze
|
cfa3df279c75d5fe95a2e69af4569a3981a6f274
|
[
"MIT"
] | null | null | null |
src/EnemyWandering.cpp
|
anqin-gh/minimaze
|
cfa3df279c75d5fe95a2e69af4569a3981a6f274
|
[
"MIT"
] | null | null | null |
#include <algorithm>
#include <random>
#include <EnemyWandering.h>
#include <Renderer.h>
#include <RendManager.h>
namespace minimaze {
EnemyWandering::EnemyWandering()
: m_rend_manager{&RendManager::get_instance()}
{
init();
}
void EnemyWandering::init() {
std::default_random_engine generator;
std::uniform_int_distribution<int8_t> distribution(1, 10);
m_dirs[0] = { 0, 1, distribution(generator)};
m_dirs[1] = { 0, -1, distribution(generator)};
m_dirs[2] = { 1, 0, distribution(generator)};
m_dirs[3] = {-1, 0, distribution(generator)};
std::random_shuffle(m_dirs.begin(), m_dirs.end());
m_di = 0;
m_step = 0;
}
int8_t EnemyWandering::steps_left_in_current_direction() const {
return m_dirs[m_di].steps - m_step;
}
void EnemyWandering::move_one_step_in_current_direction() {
const MoveDir& move = m_dirs[m_di];
set_next_movement(move.dx, move.dy);
++m_step;
}
void EnemyWandering::change_direction() {
++m_di;
if (m_di < 3) init();
}
void EnemyWandering::update() {
if (!steps_left_in_current_direction()) {
change_direction();
}
move_one_step_in_current_direction();
}
void EnemyWandering::draw() const {
m_rend_manager->renderer().draw_enemy_wandering(m_x, m_y);
}
} // minimaze
| 21.421053
| 64
| 0.719902
|
anqin-gh
|
5e5710941b5bfedbc3bd03b2c065a90f96c0d2cd
| 16,820
|
cpp
|
C++
|
Modules/ExampleModule/src/smartrefinement.cpp
|
pv6/smart-refinement-tool
|
1221a0a22ec0fc868cf922267fd0af73697025ea
|
[
"BSD-3-Clause"
] | null | null | null |
Modules/ExampleModule/src/smartrefinement.cpp
|
pv6/smart-refinement-tool
|
1221a0a22ec0fc868cf922267fd0af73697025ea
|
[
"BSD-3-Clause"
] | null | null | null |
Modules/ExampleModule/src/smartrefinement.cpp
|
pv6/smart-refinement-tool
|
1221a0a22ec0fc868cf922267fd0af73697025ea
|
[
"BSD-3-Clause"
] | null | null | null |
#include <smartrefinement.hpp>
#include <queue>
#include <iostream>
#include <vvt/algorithms/generallsm.hpp>
#include <vvt/algorithms/chanveselsm.hpp>
namespace vvt {
namespace accessory {
SmartRefinement::SmartRefinement(viewer::base *viewer) :
PropagationAccessory(viewer),
smartBrush_(new SmartBrushLevelSetImpl()),
lsm_(1, 1)
{
smartBrush_->connect([this](VoxelPosition p) {
markVoxel(p);
smartBrushMarkedVoxels_.push_back(p);
},
[this](VoxelPosition p) {
return getVoxelIntensity(p);
},
[this]() { return getSliceMinX(); },
[this]() { return getSliceMaxX(); },
[this]() { return getSliceMinY(); },
[this]() { return getSliceMaxY(); }
);
smartBrush_->changeRadius(smartBrush_->getRadius() / 2);
smartBrush_->startSelection();
result_ = std::make_unique<Matrix2D<bool>>(1, 1);
}
void SmartRefinement::exposeUseCaseCommands(vvt::engine *engine)
{
engine->registerCommand(getUseCaseName() + "_setSensitivity", this, &SmartRefinement::changeSensitivity, args_in("sensitivity"));
engine->registerCommand(getUseCaseName() + "_setBorderPenalty", this, &SmartRefinement::changeBorderPenalty, args_in("sensitivity"));
engine->registerCommand(getUseCaseName() + "_setSmoothness", this, &SmartRefinement::changeSmoothness, args_in("sensitivity"));
engine->registerCommand(getUseCaseName() + "_setBrushRadius", this, &SmartRefinement::changeBrushRadius, args_in("radius"));
engine->registerCommand(getUseCaseName() + "_startNewAnnotation", this, &SmartRefinement::startNewAnnotation);
engine->registerCommand(getUseCaseName() + "_saveDist", this, &SmartRefinement::saveDist, args_in("fileName"));
engine->registerCommand(getUseCaseName() + "_saveMask", this, &SmartRefinement::saveMask, args_in("fileName"));
engine->registerCommand(getUseCaseName() + "_savePhi", this, &SmartRefinement::savePhi, args_in("fileName"));
engine->registerCommand(getUseCaseName() + "_clearMask", this, &SmartRefinement::onClearMask);
}
void SmartRefinement::clearState() {
clicks_.clear();
smartBrushMarkedVoxels_.clear();
}
void SmartRefinement::onClearMask() {
clearState();
}
void SmartRefinement::startNewAnnotation()
{
convertTemporaryPatchToPrimary(); // save the latest patch
clearState();
}
std::string SmartRefinement::getUseCaseName()
{
return "SmartRefinement";
}
void SmartRefinement::changeSensitivity(double sens) {
sensitivity_ = sens;
lsm_.setSensitivity(sens);
}
void SmartRefinement::changeSmoothness(double sens) {
lsm_.setR2Mu(1 - sens);
}
void SmartRefinement::changeBrushRadius(int radius) {
smartBrush_->changeRadius(radius);
}
void SmartRefinement::changeBorderPenalty(double sens)
{
lsm_.setDF2SS(1 - sens);
} // End of 'SmartRefinement::changeSSCoef' function
void SmartRefinement::updateClicksBBox(BBox3D &bbox, const int padding)
{
int minX = getSliceMaxX(),
maxX = getSliceMinX(),
minY = getSliceMaxY(),
maxY = getSliceMinY();
int z = clicks_[0][2];
for (auto &p : clicks_) {
int x = p[0];
int y = p[1];
minX = std::min(minX, x);
minY = std::min(minY, y);
maxX = std::max(maxX, x);
maxY = std::max(maxY, y);
}
//if (minY > maxY) {
// minY = getSliceMinY();
// maxY = getSliceMaxY();
//}
bbox = {
VoxelPosition({
std::max(minX - padding, getSliceMinX()),
std::max(minY - padding, getSliceMinY()),
z
}),
VoxelPosition({
std::min(maxX + padding, getSliceMaxX()),
std::min(maxY + padding, getSliceMaxY()),
z
})
};
} // end of 'SmartRefinement::updateClicksBBox' function
void SmartRefinement::wholeShabang()
{
if (clicks_.size() >= 3) {
BBox3D bbox;
std::cout << "I am here now\n";
const int padding = smartBrush_->getRadius(); // 3;
/*
if (!updateSliceBBox(bbox, voxelPos[2], padding)) {
std::cout << "Can't find at least one marked voxel" << std::endl;
return;
}
*/
// find bbox using clicks_
updateClicksBBox(bbox, padding);
bbox_ = bbox;
bbox_[0][0] -= 1;
bbox_[0][1] += 1;
bbox_[1][0] -= 1;
bbox_[1][1] += 1;
/*seedPoints_.clear();
for (auto &seed : clicks_) {
seedPoints_.push_back(seed);
}*/
seedPoints_ = clicks_;
refine(bbox);
time_t tmp;
timer_ = time(&tmp) - timer_;
}
} // end of 'SmartRefinement::wholeShabang' function
void SmartRefinement::OnNewLabel2D(std::array<int, 3> &voxelPos)
{
// seedPoints_.push_back(voxelPos);
time(&timer_);
std::cout << "I am here, clicks size = " << clicks_.size() << std::endl;
clicks_.push_back(voxelPos);
drawSmartBrush(voxelPos);
wholeShabang();
}
void SmartRefinement::drawSmartBrush(std::array<int, 3> &voxelPos) {
// startNewLabeling(); // PATCH_TYPE_TEMP);
startNewLabeling(PATCH_TYPE_TEMP);
setPrimaryLabel();
for (auto &p : clicks_) {
smartBrush_->draw(p, smartBrush_->getRadius());
}
// smartBrush_->draw(voxelPos, smartBrush_->getRadius());
endNewLabeling();
}
void SmartRefinement::complementMask(Matrix2D<bool> &mask) {
struct Vec {
Vec() : x(0), y(0) {}
Vec(const Vec &vec) : x(vec.x), y(vec.y) {}
Vec(const int _x, const int _y) : x(_x), y(_y) {}
Vec operator-(const Vec& rhs) {
return Vec(x - rhs.x, y - rhs.y);
}
Vec cross() {
return Vec(-y, x);
}
int operator*(const Vec& rhs) {
return x * rhs.x + y * rhs.y;
}
int x;
int y;
};
std::vector<Vec> rectPoints;
// Add border points
/*
for (int y = 0; y < mask.sizeY; y++) {
for (int x = 0; x < mask.sizeX; x++) {
if (mask.get(x, y) && !mask.get(x - 1, y) && !mask.get(x - 1, y - 1) && !mask.get(x, y - 1)) {
rectPoints.push_back(Vec(x, y));
}
}
}
*/
for (auto &p : seedPoints_) {
rectPoints.push_back(Vec(p[0], p[1]));
}
if (rectPoints.size() <= 1) {
return;
}
// Sort points by x coordinate
std::sort(rectPoints.begin(), rectPoints.end(), [](auto a, auto b) {
if (a.x == b.x)
return a.y < b.y;
return a.x < b.x;
});
Vec normal = (rectPoints.back() - rectPoints.front()).cross();
Vec left = rectPoints.front();
std::vector<Vec> poly;
// Copy points placed below the first->last line
auto beg = std::copy_if(rectPoints.begin(), rectPoints.end(), std::back_inserter(poly), [&normal, &left](auto p) {
return normal * (left - p) >= 0;
});
// Copy points placed above first->last line
std::copy_if(rectPoints.rbegin(), rectPoints.rend(), beg, [&normal, &left](auto p) {
return normal * (left - p) < 0;
});
// Even-odd rule for polygon rasterization
std::function<bool(Vec&)> isPointInPath = [&poly](Vec& p) -> bool
{
size_t num = poly.size();
size_t end = num - 1;
bool res = false;
for (size_t i = 0; i < num; i++)
{
// p.y is between i and end points
bool c1 = (poly[i].y > p.y) != (poly[end].y > p.y);
Vec diff = poly[end] - poly[i];
if (c1 &&
((poly[i].x * diff.y + diff.x * (p - poly[i]).y > p.x * diff.y) == (diff.y > 0)))
{
res = !res;
}
end = i;
}
return res;
};
// Rasterize polygon
for (int y = 0; y < mask.sizeY; y++) {
for (int x = 0; x < mask.sizeX; x++) {
mask.set(x, y, mask.get(x, y) || isPointInPath(Vec(x, y)));
}
}
}
void SmartRefinement::refine(BBox3D &bbox)
{
startNewLabeling(PATCH_TYPE_TEMP);
setPrimaryLabel();
// transform seed points
for (VoxelPosition &seedPoint : seedPoints_)
seedPoint =
{
seedPoint[0] - bbox[0][0],
seedPoint[1] - bbox[0][1]
};
const int height = bbox[1][1] - bbox[0][1],
width = bbox[1][0] - bbox[0][0];
const int z = bbox[0][2];
Matrix2D<bool> mask(width, height);
Matrix2D<bool> trustedMask(width, height);
// load mask
for (int y = 0; y <= height; y++)
for (int x = 0; x <= width; x++)
{
mask.set(
x,
y,
isLabeled(x + bbox[0][0], y + bbox[0][1], z)
);
trustedMask.set(
x,
y,
isLabeled(x + bbox[0][0], y + bbox[0][1], z)
);
}
for (const auto& p : smartBrushMarkedVoxels_)
{
const int x = p[0] - bbox[0][0];
const int y = p[1] - bbox[0][1];
if (x < 0 || y < 0 || x > width || y > height)
continue;
mask.set(x, y, true);
trustedMask.set(x, y, true);
}
complementMask(mask);
Matrix2D<bool> result(width, height);
Matrix2D<double> sliceImage(width, height);
NormalizationParameters initialSliceNorm;
NormalizeImage(bbox, sliceImage, initialSliceNorm);
initLSM(sliceImage, mask);
refineSlice(sliceImage, mask, trustedMask, result);
mask.fill(false);
removeLeaks(mask, result);
result_ = std::make_unique<Matrix2D<bool>>(mask);
markMask(bbox[0], mask);
// markMask(bbox[0], result);
endNewLabeling();
//flushMarkedVoxels();
}
void SmartRefinement::initLSM(const Matrix2D<double> &sliceImage, const Matrix2D<bool> &mask)
{
} // End of 'SmartRefinement::initLSM' function
void SmartRefinement::refineSlice(const Matrix2D<double> &sliceImage,
const Matrix2D<bool> &mask,
const Matrix2D<bool> &trustedMask,
Matrix2D<bool> &result)
{
/*Matrix2D<double> densityField(sliceImage.sizeX, sliceImage.sizeY);
const double threshold = calcThreshold(sliceImage, mask);
const double eps = calcEps(sliceImage, threshold, mask);
initDensityField(sliceImage, eps, threshold, densityField);
GeneralLevelSet lsm_ = GeneralLevelSet(sliceImage.sizeX, sliceImage.sizeY);
lsm_.setAlpha(0.75);
lsm_.setIterationsDivider(1);
std::cout << "threshold: " << threshold << std::endl;
std::cout << "eps: " << eps << std::endl;
lsm_.run(densityField, mask, result);*/
lsm_.resize(sliceImage.sizeX, sliceImage.sizeY);
// lsm_.setTheta(50);
// lsm_.setEuclIncrease(10);
std::cout << "I am being refined over here" << std::endl;
//lsm_.setLambda(std::exp(sensitivity_ * 10.0));
//lsm_.setEuclIncrease(std::exp(sensitivity_ * 2.0));
lsm_.setInputSlice(sliceImage);
lsm_.setMaxIterations(100);
// If mask is passed instead of trustedMask, then area between clicks will be filled
lsm_.run(sliceImage, trustedMask, result, [&trustedMask, &mask, this]() -> double {
return lsm_.calculateC(trustedMask);
//return c;
//double c1 = lsm_.calculateC(trustedMask);
//double c2 = lsm_.calculateC(mask);
//const double alpha = sensitivity_;
//return c1 * alpha + c2 * (1 - alpha);
});
}
double SmartRefinement::calcEps(const Matrix2D<double> &sliceImage, const double threshold, const Matrix2D<bool> &mask)
{
NormalizedIntensityHistogram<255> hist;
double max = std::numeric_limits<double>::min();
for (int y = 0; y < sliceImage.sizeY; y++) {
for (int x = 0; x < sliceImage.sizeX; x++) {
if (mask.get(x, y)) {
const double dist = fabs(sliceImage.get(x, y) - threshold);
hist.add(dist);
max = std::max(max, dist);
}
}
}
hist.normalize();
std::cout << "quantile: " << hist.quantile(0.85) << std::endl;
std::cout << "max: " << max << std::endl;
return hist.quantile(0.85);
}
double SmartRefinement::calcThreshold(const Matrix2D<double> &sliceImage, const Matrix2D<bool> &mask)
{
std::vector<double> intensities;
for (int y = 0; y < sliceImage.sizeY; y++) {
for (int x = 0; x < sliceImage.sizeX; x++) {
if (mask.get(x, y)) {
intensities.push_back(sliceImage.get(x, y));
}
}
}
const auto median_it = intensities.begin() + intensities.size() / 2;
std::nth_element(intensities.begin(), median_it, intensities.end());
if (&(*median_it) == nullptr)
return -1;
double median = *median_it;
return median;
} // End of '' function
void SmartRefinement::initDensityField(const Matrix2D<double> &sliceImage, const double eps, const double thresh, Matrix2D<double> &dField)
{
for (int y = 0; y < dField.sizeY; y++) {
for (int x = 0; x < dField.sizeX; x++) {
double value = sliceImage.get(x, y);
const double density = eps - fabs(value - thresh);
dField.set(x, y, density);
}
}
} // End of 'SmartRefinement::initDensityField' function
void SmartRefinement::saveDist(const std::string &fileName)
{
printf("save distance\n");
saveImage(fileName, *lsm_.dist_);
} // End of 'SmartRefinement::saveDist' function
void SmartRefinement::saveMask(const std::string &fileName)
{
printf("save mask\n");
saveImage(fileName, *result_);
startNewAnnotation();
} // End of 'SmartRefinement::saveMask' function
void SmartRefinement::savePhi(const std::string &fileName)
{
printf("save phi\n");
saveImage(fileName, *lsm_.phi_);
} // End of 'SmartRefinement::savePhi' function
} // end of 'accessory' namespace
} // end of 'vvt' namespace
| 37.968397
| 147
| 0.481391
|
pv6
|
5e59824552fc0d88437aa54cf513d0704cf47ee2
| 3,100
|
hpp
|
C++
|
src/stan/math/rev/core.hpp
|
alashworth/stan-monorepo
|
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
|
[
"BSD-3-Clause"
] | 1
|
2019-09-06T15:53:17.000Z
|
2019-09-06T15:53:17.000Z
|
src/stan/math/rev/core.hpp
|
alashworth/stan-monorepo
|
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
|
[
"BSD-3-Clause"
] | 8
|
2019-01-17T18:51:16.000Z
|
2019-01-17T18:51:39.000Z
|
src/stan/math/rev/core.hpp
|
alashworth/stan-monorepo
|
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
|
[
"BSD-3-Clause"
] | null | null | null |
#ifndef STAN_MATH_REV_CORE_HPP
#define STAN_MATH_REV_CORE_HPP
#include <stan/math/rev/core/autodiffstackstorage.hpp>
#include <stan/math/rev/core/build_vari_array.hpp>
#include <stan/math/rev/core/chainable_alloc.hpp>
#include <stan/math/rev/core/chainablestack.hpp>
#include <stan/math/rev/core/init_chainablestack.hpp>
#include <stan/math/rev/core/ddv_vari.hpp>
#include <stan/math/rev/core/dv_vari.hpp>
#include <stan/math/rev/core/dvd_vari.hpp>
#include <stan/math/rev/core/dvv_vari.hpp>
#include <stan/math/rev/core/empty_nested.hpp>
#include <stan/math/rev/core/gevv_vvv_vari.hpp>
#include <stan/math/rev/core/grad.hpp>
#include <stan/math/rev/core/matrix_vari.hpp>
#include <stan/math/rev/core/nested_size.hpp>
#include <stan/math/rev/core/operator_addition.hpp>
#include <stan/math/rev/core/operator_divide_equal.hpp>
#include <stan/math/rev/core/operator_division.hpp>
#include <stan/math/rev/core/operator_equal.hpp>
#include <stan/math/rev/core/operator_greater_than.hpp>
#include <stan/math/rev/core/operator_greater_than_or_equal.hpp>
#include <stan/math/rev/core/operator_less_than.hpp>
#include <stan/math/rev/core/operator_less_than_or_equal.hpp>
#include <stan/math/rev/core/operator_logical_and.hpp>
#include <stan/math/rev/core/operator_logical_or.hpp>
#include <stan/math/rev/core/operator_minus_equal.hpp>
#include <stan/math/rev/core/operator_multiplication.hpp>
#include <stan/math/rev/core/operator_multiply_equal.hpp>
#include <stan/math/rev/core/operator_not_equal.hpp>
#include <stan/math/rev/core/operator_plus_equal.hpp>
#include <stan/math/rev/core/operator_subtraction.hpp>
#include <stan/math/rev/core/operator_unary_decrement.hpp>
#include <stan/math/rev/core/operator_unary_increment.hpp>
#include <stan/math/rev/core/operator_unary_negative.hpp>
#include <stan/math/rev/core/operator_unary_not.hpp>
#include <stan/math/rev/core/operator_unary_plus.hpp>
#include <stan/math/rev/core/precomp_v_vari.hpp>
#include <stan/math/rev/core/precomp_vv_vari.hpp>
#include <stan/math/rev/core/precomp_vvv_vari.hpp>
#include <stan/math/rev/core/precomputed_gradients.hpp>
#include <stan/math/rev/core/print_stack.hpp>
#include <stan/math/rev/core/recover_memory.hpp>
#include <stan/math/rev/core/recover_memory_nested.hpp>
#include <stan/math/rev/core/set_zero_all_adjoints.hpp>
#include <stan/math/rev/core/set_zero_all_adjoints_nested.hpp>
#include <stan/math/rev/core/start_nested.hpp>
#include <stan/math/rev/core/std_isinf.hpp>
#include <stan/math/rev/core/std_isnan.hpp>
#include <stan/math/rev/core/std_numeric_limits.hpp>
#include <stan/math/rev/core/stored_gradient_vari.hpp>
#include <stan/math/rev/core/v_vari.hpp>
#include <stan/math/rev/core/var.hpp>
#include <stan/math/rev/core/vari.hpp>
#include <stan/math/rev/core/vd_vari.hpp>
#include <stan/math/rev/core/vdd_vari.hpp>
#include <stan/math/rev/core/vdv_vari.hpp>
#include <stan/math/rev/core/vector_vari.hpp>
#include <stan/math/rev/core/vv_vari.hpp>
#include <stan/math/rev/core/vvd_vari.hpp>
#include <stan/math/rev/core/vvv_vari.hpp>
#endif
| 47.692308
| 65
| 0.785806
|
alashworth
|
5e683509ed69e27ce1bc582e62270e503fe47f28
| 592
|
hpp
|
C++
|
include/rive/nested_animation.hpp
|
rive-app/rive-cpp
|
2cc9cc92868d468ca75f8b5fcc40ad1ec33d27b1
|
[
"MIT"
] | 139
|
2020-08-17T20:10:24.000Z
|
2022-03-28T12:22:44.000Z
|
include/rive/nested_animation.hpp
|
rive-app/rive-cpp
|
2cc9cc92868d468ca75f8b5fcc40ad1ec33d27b1
|
[
"MIT"
] | 89
|
2020-08-28T16:41:01.000Z
|
2022-03-28T19:10:49.000Z
|
include/rive/nested_animation.hpp
|
rive-app/rive-cpp
|
2cc9cc92868d468ca75f8b5fcc40ad1ec33d27b1
|
[
"MIT"
] | 19
|
2020-10-19T00:54:40.000Z
|
2022-02-28T05:34:17.000Z
|
#ifndef _RIVE_NESTED_ANIMATION_HPP_
#define _RIVE_NESTED_ANIMATION_HPP_
#include "rive/generated/nested_animation_base.hpp"
#include <stdio.h>
namespace rive
{
class NestedAnimation : public NestedAnimationBase
{
public:
StatusCode onAddedDirty(CoreContext* context) override;
// Advance animations and apply them to the artboard.
virtual void advance(float elapsedSeconds, Artboard* artboard) = 0;
// Initialize the animation (make instances as necessary) from the
// source artboard.
virtual void initializeAnimation(Artboard* artboard) = 0;
};
} // namespace rive
#endif
| 28.190476
| 69
| 0.782095
|
rive-app
|
5e6e42425dcad7b83032aa5639e9bd1c2b6eb83e
| 2,268
|
cpp
|
C++
|
world/seasons/source/SeasonFactory.cpp
|
prolog/shadow-of-the-wyrm
|
a1312c3e9bb74473f73c4e7639e8bd537f10b488
|
[
"MIT"
] | 60
|
2019-08-21T04:08:41.000Z
|
2022-03-10T13:48:04.000Z
|
world/seasons/source/SeasonFactory.cpp
|
prolog/shadow-of-the-wyrm
|
a1312c3e9bb74473f73c4e7639e8bd537f10b488
|
[
"MIT"
] | 3
|
2021-03-18T15:11:14.000Z
|
2021-10-20T12:13:07.000Z
|
world/seasons/source/SeasonFactory.cpp
|
prolog/shadow-of-the-wyrm
|
a1312c3e9bb74473f73c4e7639e8bd537f10b488
|
[
"MIT"
] | 8
|
2019-11-16T06:29:05.000Z
|
2022-01-23T17:33:43.000Z
|
#include "SeasonFactory.hpp"
#include "Spring.hpp"
#include "Summer.hpp"
#include "Autumn.hpp"
#include "Winter.hpp"
using namespace std;
SeasonSerializationMap SeasonFactory::season_map;
SeasonFactory::SeasonFactory()
{
}
SeasonFactory::~SeasonFactory()
{
}
ISeasonPtr SeasonFactory::create_season(const Season season)
{
ISeasonPtr new_season;
switch(season)
{
case Season::SEASON_SPRING:
new_season = std::make_unique<Spring>();
break;
case Season::SEASON_SUMMER:
new_season = std::make_unique<Summer>();
break;
case Season::SEASON_AUTUMN:
new_season = std::make_unique<Autumn>();
break;
case Season::SEASON_WINTER:
default:
new_season = std::make_unique<Winter>();
break;
}
return new_season;
}
ISeasonPtr SeasonFactory::create_season(const ClassIdentifier ci)
{
ISeasonPtr season;
if (season_map.empty())
{
initialize_season_map();
}
SeasonSerializationMap::iterator s_it = season_map.find(ci);
if (s_it != season_map.end())
{
season = ISeasonPtr(s_it->second->clone());
}
return season;
}
ISeasonPtr SeasonFactory::create_season(const uint month_of_year)
{
ISeasonPtr season;
set<Season> seasons = {Season::SEASON_SPRING, Season::SEASON_SUMMER, Season::SEASON_AUTUMN, Season::SEASON_WINTER};
for (Season cur_season_enum : seasons)
{
ISeasonPtr cur_season = create_season(cur_season_enum);
set<Months> months = cur_season->get_months_in_season();
if (months.find(static_cast<Months>(month_of_year)) != months.end())
{
season = ISeasonPtr(cur_season->clone());
break;
}
}
return season;
}
void SeasonFactory::initialize_season_map()
{
season_map.clear();
ISeasonPtr spring = std::make_unique<Spring>();
ISeasonPtr summer = std::make_unique<Summer>();
ISeasonPtr autumn = std::make_unique<Autumn>();
ISeasonPtr winter = std::make_unique<Winter>();
season_map.insert(make_pair(ClassIdentifier::CLASS_ID_SPRING, std::move(spring)));
season_map.insert(make_pair(ClassIdentifier::CLASS_ID_SUMMER, std::move(summer)));
season_map.insert(make_pair(ClassIdentifier::CLASS_ID_AUTUMN, std::move(autumn)));
season_map.insert(make_pair(ClassIdentifier::CLASS_ID_WINTER, std::move(winter)));
}
| 23.873684
| 117
| 0.715608
|
prolog
|
5e703cdd9ca2cb7d95d7f6c206ba3cfc36a709ea
| 5,736
|
hpp
|
C++
|
game/quest/PC.hpp
|
miguelmig/LibM2
|
dad7591a885a421842851905dc2bc8bbd648ca20
|
[
"BSD-3-Clause"
] | null | null | null |
game/quest/PC.hpp
|
miguelmig/LibM2
|
dad7591a885a421842851905dc2bc8bbd648ca20
|
[
"BSD-3-Clause"
] | null | null | null |
game/quest/PC.hpp
|
miguelmig/LibM2
|
dad7591a885a421842851905dc2bc8bbd648ca20
|
[
"BSD-3-Clause"
] | 1
|
2021-11-14T10:51:30.000Z
|
2021-11-14T10:51:30.000Z
|
/* This file belongs to the LibM2 library (http://github.com/imermcmaps/LibM2)
* Copyright (c) 2013, iMer (www.imer.cc)
* All rights reserved.
* Licensed under the BSD 3-clause license (http://opensource.org/licenses/BSD-3-Clause)
*/
#ifndef __LIBM2_GAME_QUEST_HPP
#define __LIBM2_GAME_QUEST_HPP
#include "../stdInclude.hpp"
#include "../CHARACTER.hpp"
#include "RewardData.hpp"
#include "QuestState.hpp"
namespace libm2 {
namespace quest {
class PC {
public:
class TQuestStateChangeInfo {
DWORD quest_idx;
int prev_state;
int next_state;
public:
TQuestStateChangeInfo(DWORD, int, int);
};
private:
std::vector<quest::PC::TQuestStateChangeInfo, std::allocator<quest::PC::TQuestStateChangeInfo> > m_QuestStateChange;
std::vector<quest::RewardData, std::allocator<quest::RewardData> > m_vRewardData;
bool m_bIsGivenReward;
bool m_bShouldSendDone;
DWORD m_dwID;
std::map<unsigned int, quest::QuestState, std::less<unsigned int>, std::allocator<std::pair<unsigned int const, quest::QuestState> > > m_QuestInfo;
quest::QuestState *m_RunningQuestState;
std::string m_stCurQuest;
std::map<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, int, std::less<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::pair<std::basic_string<char, std::char_traits<char>, std::allocator<char> > const, int> > > m_FlagMap;
std::map<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, int, std::less<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::pair<std::basic_string<char, std::char_traits<char>, std::allocator<char> > const, int> > > m_FlagSaveMap;
std::map<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, boost::intrusive_ptr<event>, std::less<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::pair<std::basic_string<char, std::char_traits<char>, std::allocator<char> > const, boost::intrusive_ptr<event> > > > m_TimerMap;
int m_iSendToClient;
bool m_bLoaded;
int m_iLastState;
DWORD m_dwWaitConfirmFromPID;
bool m_bConfirmWait;
public:
PC(void);
~PC();
void Destroy(void);
void SetID(DWORD);
DWORD GetID(void);
bool HasQuest(const std::string &);
quest::QuestState & GetQuest(const std::string &);
std::_Rb_tree_iterator<std::pair<unsigned int const, quest::QuestState> > quest_begin(void);
std::_Rb_tree_iterator<std::pair<unsigned int const, quest::QuestState> > quest_end(void);
std::_Rb_tree_iterator<std::pair<unsigned int const, quest::QuestState> > quest_find(DWORD);
bool IsRunning(void);
void EndRunning(void);
void CancelRunning(void);
quest::QuestState * GetRunningQuestState(void);
void SetQuest(const std::string &, quest::QuestState &);
void SetCurrentQuestStateName(const std::string &);
void SetQuestState(const std::string &,
const std::string &);
void SetQuestState(const std::string &, int);
void SetQuestState(const char *, const char *);
void ClearQuest(const std::string &);
private:
void AddQuestStateChange(const std::string &, int, int);
void DoQuestStateChange(void);
public:
void SetFlag(const std::string &, int, bool);
int GetFlag(const std::string &);
bool DeleteFlag(const std::string &);
const std::string & GetCurrentQuestName(void) const;
int GetCurrentQuestIndex(void);
void RemoveTimer(const std::string &);
void RemoveTimerNotCancel(const std::string &);
void AddTimer(const std::string &, LPEVENT);
void ClearTimer(void);
void SetCurrentQuestStartFlag(void);
void SetCurrentQuestDoneFlag(void);
void SetQuestTitle(const std::string &,
const std::string &);
void SetCurrentQuestTitle(const std::string &);
void SetCurrentQuestClockName(const std::string &);
void SetCurrentQuestClockValue(int);
void SetCurrentQuestCounterName(const std::string &);
void SetCurrentQuestCounterValue(int);
void SetCurrentQuestIconFile(const std::string &);
bool IsLoaded(void) const;
void SetLoaded(void);
void Build(void);
void Save(void);
bool HasReward(void);
void Reward(LPCHARACTER);
void GiveItem(const std::string &, DWORD, int);
void GiveExp(const std::string &, DWORD);
void SetSendDoneFlag(void);
bool GetAndResetDoneFlag(void);
void SendFlagList(LPCHARACTER);
void SetConfirmWait(DWORD);
void ClearConfirmWait(void);
bool IsConfirmWait(void) const;
bool IsConfirmWait(DWORD) const;
private:
void SetSendFlag(int);
void ClearSendFlag(void);
void SaveFlag(const std::string &, int);
void ClearCurrentQuestBeginFlag(void);
void SetCurrentQuestBeginFlag(void);
int GetCurrentQuestBeginFlag(void);
void SendQuestInfoPakcet(void);
};
}
}
#endif // __LIBM2_GAME_QUEST_HPP
| 49.025641
| 354
| 0.614017
|
miguelmig
|
5e73977de01edda429bf31620ef17ccf67aad6d5
| 3,568
|
cpp
|
C++
|
day18a.cpp
|
Fossegrimen/advent-of-code
|
d9323346c167435fe461214e9eae990a1940c78e
|
[
"MIT"
] | null | null | null |
day18a.cpp
|
Fossegrimen/advent-of-code
|
d9323346c167435fe461214e9eae990a1940c78e
|
[
"MIT"
] | null | null | null |
day18a.cpp
|
Fossegrimen/advent-of-code
|
d9323346c167435fe461214e9eae990a1940c78e
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <queue>
#include <sstream>
#include <stack>
#include <string>
#include <vector>
typedef std::queue<char> OutputQueue;
typedef std::stack<char> OperatorStack;
typedef std::vector<char> TokenList;
void shuntingYardAlgorithm(const TokenList& tokens, OutputQueue& outputQueue);
uint64_t evalReversePolishNotation(OutputQueue& outputQueue);
int main()
{
uint64_t sum = 0;
std::string line;
while (std::getline(std::cin, line))
{
TokenList tokens;
std::stringstream _line(line);
char token;
while (_line >> token)
{
tokens.push_back(token);
}
OutputQueue outputQueue;
shuntingYardAlgorithm(tokens, outputQueue);
sum += evalReversePolishNotation(outputQueue);
}
std::cout << sum << std::endl;
return 0;
}
void shuntingYardAlgorithm(const TokenList& tokens, OutputQueue& outputQueue)
{
OperatorStack operatorStack;
for (char token : tokens)
{
switch (token)
{
case '+':
{
while (!operatorStack.empty() &&
(operatorStack.top() == '+' || operatorStack.top() == '*') &&
operatorStack.top() != '(')
{
outputQueue.push(operatorStack.top());
operatorStack.pop();
}
operatorStack.push('+');
break;
}
case '*':
{
while (!operatorStack.empty() &&
(operatorStack.top() == '+' || operatorStack.top() == '*') &&
operatorStack.top() != '(')
{
outputQueue.push(operatorStack.top());
operatorStack.pop();
}
operatorStack.push('*');
break;
}
case ')':
{
while (operatorStack.top() != '(')
{
outputQueue.push(operatorStack.top());
operatorStack.pop();
}
if (operatorStack.empty())
{
exit(1);
}
operatorStack.pop();
break;
}
case '(':
{
operatorStack.push('(');
break;
}
default:
{
outputQueue.push(token);
break;
}
}
}
while (!operatorStack.empty())
{
outputQueue.push(operatorStack.top());
operatorStack.pop();
}
}
uint64_t evalReversePolishNotation(OutputQueue& outputQueue)
{
std::stack<uint64_t> outputStack;
while (!outputQueue.empty())
{
const char token = outputQueue.front();
outputQueue.pop();
if (token != '+' && token != '*')
{
outputStack.push(token - '0');
}
else
{
const uint64_t a = outputStack.top();
outputStack.pop();
const uint64_t b = outputStack.top();
outputStack.pop();
switch (token)
{
case '+':
{
outputStack.push(a + b);
break;
}
case '*':
{
outputStack.push(a * b);
break;
}
}
}
}
return outputStack.top();
}
| 23.629139
| 84
| 0.43778
|
Fossegrimen
|
5e76666312e198d4bca69ff7c21fe85b79cf3922
| 2,169
|
cpp
|
C++
|
problems/codeforces/1520/f-guess-the-kth-zero/code.cpp
|
brunodccarvalho/competitive
|
4177c439174fbe749293b9da3445ce7303bd23c2
|
[
"MIT"
] | 7
|
2020-10-15T22:37:10.000Z
|
2022-02-26T17:23:49.000Z
|
problems/codeforces/1520/f-guess-the-kth-zero/code.cpp
|
brunodccarvalho/competitive
|
4177c439174fbe749293b9da3445ce7303bd23c2
|
[
"MIT"
] | null | null | null |
problems/codeforces/1520/f-guess-the-kth-zero/code.cpp
|
brunodccarvalho/competitive
|
4177c439174fbe749293b9da3445ce7303bd23c2
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
#define long int64_t
#define DV(a) (" [" #a "=" + to_string(a) + "]")
// *****
struct fenwick {
int N;
vector<int> tree;
explicit fenwick(int N = 0) : N(N), tree(N + 1, 0) {}
int sum(int i) {
int sum = 0;
while (i > 0) {
sum += tree[i];
i -= i & -i;
}
return sum;
}
void add(int i, int n) {
assert(i > 0);
while (i <= N) {
tree[i] += n;
i += i & -i;
}
}
int lower_bound(int n) {
int i = 0;
int bits = CHAR_BIT * sizeof(int) - __builtin_clz(N << 1);
for (int j = 1 << bits; j; j >>= 1) {
if (i + j <= N && tree[i + j] < n) {
n -= tree[i + j];
i += j;
}
}
return i + 1;
}
};
#define MAXN 200'010
#define MAX_QUERIES 60'000
int N, Q, queries_count = 0;
int know[MAXN]; // how many ones initially in [1..n].
fenwick added;
// how many ones in positions [1..r]
int QUERY(int r) {
queries_count++;
assert(queries_count <= MAX_QUERIES);
string s = "? 1 " + to_string(r);
cout << s << endl;
int ones;
cin >> ones;
return ones;
}
// how many ones in positions [1..r]
int maybe_query(int r) {
if (know[r] < 0) {
int ones = QUERY(r);
know[r] = ones - added.sum(r);
}
return know[r] + added.sum(r);
}
auto solve() {
cin >> N >> Q;
added = fenwick(N + 1);
memset(know, 0xff, sizeof(know)); // -1
know[0] = 0;
while (Q--) {
int k;
cin >> k;
int L = 0, R = N + 1;
while (L + 1 < R) {
int M = (L + R) / 2;
int ones = maybe_query(M);
int zeros = M - ones;
if (zeros >= k) {
R = M;
} else {
L = M;
}
}
assert(R <= N);
string s = "! " + to_string(R);
cout << s << endl;
added.add(R, 1);
}
}
// *****
int main() {
ios::sync_with_stdio(false);
solve();
cerr << "Queries: " << queries_count << endl;
return 0;
}
| 19.718182
| 66
| 0.420009
|
brunodccarvalho
|
5e7f18c28fca97ab25b2e639734e788486d458d9
| 1,530
|
inl
|
C++
|
Core/DianYing/Include/Dy/Meta/Information/Inline/DMetaMetarialInstanceTmp.inl
|
liliilli/DianYing
|
6e19f67e5d932e346a0ce63a648bed1a04ef618e
|
[
"MIT"
] | 4
|
2019-03-17T19:46:54.000Z
|
2019-12-09T20:11:01.000Z
|
Core/DianYing/Include/Dy/Meta/Information/Inline/DMetaMetarialInstanceTmp.inl
|
liliilli/DianYing
|
6e19f67e5d932e346a0ce63a648bed1a04ef618e
|
[
"MIT"
] | null | null | null |
Core/DianYing/Include/Dy/Meta/Information/Inline/DMetaMetarialInstanceTmp.inl
|
liliilli/DianYing
|
6e19f67e5d932e346a0ce63a648bed1a04ef618e
|
[
"MIT"
] | null | null | null |
#ifndef GUARD_DY_META_INFORMATION_INLINE_DMETAMETARIALINSTANCETMP_INL
#define GUARD_DY_META_INFORMATION_INLINE_DMETAMETARIALINSTANCETMP_INL
///
/// MIT License
/// Copyright (c) 2018-2019 Jongmin Yun
///
/// 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 <Dy/Core/Resource/Type/Uniform/TUniformValue.h>
#include <Dy/Helper/System/Assertion.h>
namespace dy
{
template <EUniformVariableType TType>
void PDyMaterialInstanceMetaInfo::InsertValue(
PDyMaterialInstanceMetaInfo& ioMaterialInfo,
const std::string& iSpecifier,
const typename MDY_PRIVATE(UniformBinder)<TType>::ValueType& iValue)
{
const auto it = ioMaterialInfo.mUniformValues.find(iSpecifier);
MDY_ASSERT_MSG_FORCE(
it == ioMaterialInfo.mUniformValues.end(),
"Initial uniform value's string must not be duplicated with others."
);
// In case of success.
auto [_, __] = ioMaterialInfo.mUniformValues.try_emplace
(
iSpecifier,
std::make_unique<TUniformValue<TType>>(-1, iValue)
);
}
} /// ::dy namespace
#endif /// GUARD_DY_META_INFORMATION_INLINE_DMETAMETARIALINSTANCETMP_INL
| 34.772727
| 81
| 0.769281
|
liliilli
|
5e8033d6a5e8dbc6b5461d779d6109848849d550
| 15,005
|
cpp
|
C++
|
libs/yap/example/autodiff_library/BinaryOPNode.cpp
|
Talustus/boost_src
|
ffe074de008f6e8c46ae1f431399cf932164287f
|
[
"BSL-1.0"
] | 32
|
2019-02-27T06:57:07.000Z
|
2021-08-29T10:56:19.000Z
|
third_party/boost/libs/yap/example/autodiff_library/BinaryOPNode.cpp
|
avplayer/cxxrpc
|
7049b4079fac78b3828e68f787d04d699ce52f6d
|
[
"BSL-1.0"
] | 1
|
2019-03-04T11:21:00.000Z
|
2019-05-24T01:36:31.000Z
|
third_party/boost/libs/yap/example/autodiff_library/BinaryOPNode.cpp
|
avplayer/cxxrpc
|
7049b4079fac78b3828e68f787d04d699ce52f6d
|
[
"BSL-1.0"
] | 5
|
2019-08-20T13:45:04.000Z
|
2022-03-01T18:23:49.000Z
|
/*
* BinaryOPNode.cpp
*
* Created on: 6 Nov 2013
* Author: s0965328
*/
#include "auto_diff_types.h"
#include "BinaryOPNode.h"
#include "PNode.h"
#include "Stack.h"
#include "Tape.h"
#include "EdgeSet.h"
#include "Node.h"
#include "VNode.h"
#include "OPNode.h"
#include "ActNode.h"
#include "EdgeSet.h"
namespace AutoDiff {
BinaryOPNode::BinaryOPNode(OPCODE op_, Node* left_, Node* right_):OPNode(op_,left_),right(right_)
{
}
OPNode* BinaryOPNode::createBinaryOpNode(OPCODE op, Node* left, Node* right)
{
assert(left!=NULL && right!=NULL);
OPNode* node = NULL;
node = new BinaryOPNode(op,left,right);
return node;
}
BinaryOPNode::~BinaryOPNode() {
if(right->getType()!=VNode_Type)
{
delete right;
right = NULL;
}
}
void BinaryOPNode::inorder_visit(int level,ostream& oss){
if(left!=NULL){
left->inorder_visit(level+1,oss);
}
oss<<this->toString(level)<<endl;
if(right!=NULL){
right->inorder_visit(level+1,oss);
}
}
void BinaryOPNode::collect_vnodes(boost::unordered_set<Node*>& nodes,unsigned int& total){
total++;
if (left != NULL) {
left->collect_vnodes(nodes,total);
}
if (right != NULL) {
right->collect_vnodes(nodes,total);
}
}
void BinaryOPNode::eval_function()
{
assert(left!=NULL && right!=NULL);
left->eval_function();
right->eval_function();
this->calc_eval_function();
}
void BinaryOPNode::calc_eval_function()
{
double x = NaN_Double;
double rx = SV->pop_back();
double lx = SV->pop_back();
switch (op)
{
case OP_PLUS:
x = lx + rx;
break;
case OP_MINUS:
x = lx - rx;
break;
case OP_TIMES:
x = lx * rx;
break;
case OP_DIVID:
x = lx / rx;
break;
case OP_POW:
x = pow(lx,rx);
break;
default:
cerr<<"op["<<op<<"] not yet implemented!!"<<endl;
assert(false);
break;
}
SV->push_back(x);
}
//1. visiting left if not NULL
//2. then, visiting right if not NULL
//3. calculating the immediate derivative hu and hv
void BinaryOPNode::grad_reverse_0()
{
assert(left!=NULL && right != NULL);
this->adj = 0;
left->grad_reverse_0();
right->grad_reverse_0();
this->calc_grad_reverse_0();
}
//right left - right most traversal
void BinaryOPNode::grad_reverse_1()
{
assert(right!=NULL && left!=NULL);
double r_adj = SD->pop_back()*this->adj;
right->update_adj(r_adj);
double l_adj = SD->pop_back()*this->adj;
left->update_adj(l_adj);
right->grad_reverse_1();
left->grad_reverse_1();
}
void BinaryOPNode::calc_grad_reverse_0()
{
assert(left!=NULL && right != NULL);
double l_dh = NaN_Double;
double r_dh = NaN_Double;
double rx = SV->pop_back();
double lx = SV->pop_back();
double x = NaN_Double;
switch (op)
{
case OP_PLUS:
x = lx + rx;
l_dh = 1;
r_dh = 1;
break;
case OP_MINUS:
x = lx - rx;
l_dh = 1;
r_dh = -1;
break;
case OP_TIMES:
x = lx * rx;
l_dh = rx;
r_dh = lx;
break;
case OP_DIVID:
x = lx / rx;
l_dh = 1 / rx;
r_dh = -(lx) / pow(rx, 2);
break;
case OP_POW:
if(right->getType()==PNode_Type){
x = pow(lx,rx);
l_dh = rx*pow(lx,(rx-1));
r_dh = 0;
}
else{
assert(lx>0.0); //otherwise log(lx) is not defined in read number
x = pow(lx,rx);
l_dh = rx*pow(lx,(rx-1));
r_dh = pow(lx,rx)*log(lx); //this is for x1^x2 when x1=0 cause r_dh become +inf, however d(0^x2)/d(x2) = 0
}
break;
default:
cerr<<"error op not impl"<<endl;
break;
}
SV->push_back(x);
SD->push_back(l_dh);
SD->push_back(r_dh);
}
void BinaryOPNode::hess_reverse_0_init_n_in_arcs()
{
this->left->hess_reverse_0_init_n_in_arcs();
this->right->hess_reverse_0_init_n_in_arcs();
this->Node::hess_reverse_0_init_n_in_arcs();
}
void BinaryOPNode::hess_reverse_1_clear_index()
{
this->left->hess_reverse_1_clear_index();
this->right->hess_reverse_1_clear_index();
this->Node::hess_reverse_1_clear_index();
}
unsigned int BinaryOPNode::hess_reverse_0()
{
assert(this->left!=NULL && right!=NULL);
if(index==0)
{
unsigned int lindex=0, rindex=0;
lindex = left->hess_reverse_0();
rindex = right->hess_reverse_0();
assert(lindex!=0 && rindex !=0);
II->set(lindex);
II->set(rindex);
double rx,rx_bar,rw,rw_bar;
double lx,lx_bar,lw,lw_bar;
double x,x_bar,w,w_bar;
double r_dh, l_dh;
right->hess_reverse_0_get_values(rindex,rx,rx_bar,rw,rw_bar);
left->hess_reverse_0_get_values(lindex,lx,lx_bar,lw,lw_bar);
switch(op)
{
case OP_PLUS:
// cout<<"lindex="<<lindex<<"\trindex="<<rindex<<"\tI="<<I<<endl;
x = lx + rx;
// cout<<lx<<"\t+"<<rx<<"\t="<<x<<"\t\t"<<toString(0)<<endl;
x_bar = 0;
l_dh = 1;
r_dh = 1;
w = lw * l_dh + rw * r_dh;
// cout<<lw<<"\t+"<<rw<<"\t="<<w<<"\t\t"<<toString(0)<<endl;
w_bar = 0;
break;
case OP_MINUS:
x = lx - rx;
x_bar = 0;
l_dh = 1;
r_dh = -1;
w = lw * l_dh + rw * r_dh;
w_bar = 0;
break;
case OP_TIMES:
x = lx * rx;
x_bar = 0;
l_dh = rx;
r_dh = lx;
w = lw * l_dh + rw * r_dh;
w_bar = 0;
break;
case OP_DIVID:
x = lx / rx;
x_bar = 0;
l_dh = 1/rx;
r_dh = -lx/pow(rx,2);
w = lw * l_dh + rw * r_dh;
w_bar = 0;
break;
case OP_POW:
if(right->getType()==PNode_Type)
{
x = pow(lx,rx);
x_bar = 0;
l_dh = rx*pow(lx,(rx-1));
r_dh = 0;
w = lw * l_dh + rw * r_dh;
w_bar = 0;
}
else
{
assert(lx>0.0); //otherwise log(lx) undefined in real number
x = pow(lx,rx);
x_bar = 0;
l_dh = rx*pow(lx,(rx-1));
r_dh = pow(lx,rx)*log(lx); //log(lx) cause -inf when lx=0;
w = lw * l_dh + rw * r_dh;
w_bar = 0;
}
break;
default:
cerr<<"op["<<op<<"] not yet implemented!"<<endl;
assert(false);
break;
}
TT->set(x);
TT->set(x_bar);
TT->set(w);
TT->set(w_bar);
TT->set(l_dh);
TT->set(r_dh);
assert(TT->index == TT->index);
index = TT->index;
}
return index;
}
void BinaryOPNode::hess_reverse_0_get_values(unsigned int i,double& x, double& x_bar, double& w, double& w_bar)
{
--i; // skip the r_dh (ie, dh/du)
--i; // skip the l_dh (ie. dh/dv)
w_bar = TT->get(--i);
w = TT->get(--i);
x_bar = TT->get(--i);
x = TT->get(--i);
}
void BinaryOPNode::hess_reverse_1(unsigned int i)
{
n_in_arcs--;
if(n_in_arcs==0)
{
assert(right!=NULL && left!=NULL);
unsigned int rindex = II->get(--(II->index));
unsigned int lindex = II->get(--(II->index));
// cout<<"ri["<<rindex<<"]\tli["<<lindex<<"]\t"<<this->toString(0)<<endl;
double r_dh = TT->get(--i);
double l_dh = TT->get(--i);
double w_bar = TT->get(--i);
--i; //skip w
double x_bar = TT->get(--i);
--i; //skip x
double lw_bar=0,rw_bar=0;
double lw=0,lx=0; left->hess_reverse_1_get_xw(lindex,lw,lx);
double rw=0,rx=0; right->hess_reverse_1_get_xw(rindex,rw,rx);
switch(op)
{
case OP_PLUS:
assert(l_dh==1);
assert(r_dh==1);
lw_bar += w_bar*l_dh;
rw_bar += w_bar*r_dh;
break;
case OP_MINUS:
assert(l_dh==1);
assert(r_dh==-1);
lw_bar += w_bar*l_dh;
rw_bar += w_bar*r_dh;
break;
case OP_TIMES:
assert(rx == l_dh);
assert(lx == r_dh);
lw_bar += w_bar*rx;
lw_bar += x_bar*lw*0 + x_bar*rw*1;
rw_bar += w_bar*lx;
rw_bar += x_bar*lw*1 + x_bar*rw*0;
break;
case OP_DIVID:
lw_bar += w_bar*l_dh;
lw_bar += x_bar*lw*0 + x_bar*rw*-1/(pow(rx,2));
rw_bar += w_bar*r_dh;
rw_bar += x_bar*lw*-1/pow(rx,2) + x_bar*rw*2*lx/pow(rx,3);
break;
case OP_POW:
if(right->getType()==PNode_Type){
lw_bar += w_bar*l_dh;
lw_bar += x_bar*lw*pow(lx,rx-2)*rx*(rx-1) + 0;
rw_bar += w_bar*r_dh; assert(r_dh==0.0);
rw_bar += 0;
}
else{
assert(lx>0.0); //otherwise log(lx) is not define in Real
lw_bar += w_bar*l_dh;
lw_bar += x_bar*lw*pow(lx,rx-2)*rx*(rx-1) + x_bar*rw*pow(lx,rx-1)*(rx*log(lx)+1); //cause log(lx)=-inf when
rw_bar += w_bar*r_dh;
rw_bar += x_bar*lw*pow(lx,rx-1)*(rx*log(lx)+1) + x_bar*rw*pow(lx,rx)*pow(log(lx),2);
}
break;
default:
cerr<<"op["<<op<<"] not yet implemented !"<<endl;
assert(false);
break;
}
double rx_bar = x_bar*r_dh;
double lx_bar = x_bar*l_dh;
right->update_x_bar(rindex,rx_bar);
left->update_x_bar(lindex,lx_bar);
right->update_w_bar(rindex,rw_bar);
left->update_w_bar(lindex,lw_bar);
this->right->hess_reverse_1(rindex);
this->left->hess_reverse_1(lindex);
}
}
void BinaryOPNode::hess_reverse_1_init_x_bar(unsigned int i)
{
TT->at(i-5) = 1;
}
void BinaryOPNode::update_x_bar(unsigned int i ,double v)
{
TT->at(i-5) += v;
}
void BinaryOPNode::update_w_bar(unsigned int i ,double v)
{
TT->at(i-3) += v;
}
void BinaryOPNode::hess_reverse_1_get_xw(unsigned int i,double& w,double& x)
{
w = TT->get(i-4);
x = TT->get(i-6);
}
void BinaryOPNode::hess_reverse_get_x(unsigned int i,double& x)
{
x = TT->get(i-6);
}
void BinaryOPNode::nonlinearEdges(EdgeSet& edges)
{
for(list<Edge>::iterator it=edges.edges.begin();it!=edges.edges.end();)
{
Edge e = *it;
if(e.a==this || e.b == this){
if(e.a == this && e.b == this)
{
Edge e1(left,left);
Edge e2(right,right);
Edge e3(left,right);
edges.insertEdge(e1);
edges.insertEdge(e2);
edges.insertEdge(e3);
}
else
{
Node* o = e.a==this? e.b: e.a;
Edge e1(left,o);
Edge e2(right,o);
edges.insertEdge(e1);
edges.insertEdge(e2);
}
it = edges.edges.erase(it);
}
else
{
it++;
}
}
Edge e1(left,right);
Edge e2(left,left);
Edge e3(right,right);
switch(op)
{
case OP_PLUS:
case OP_MINUS:
//do nothing for linear operator
break;
case OP_TIMES:
edges.insertEdge(e1);
break;
case OP_DIVID:
edges.insertEdge(e1);
edges.insertEdge(e3);
break;
case OP_POW:
edges.insertEdge(e1);
edges.insertEdge(e2);
edges.insertEdge(e3);
break;
default:
cerr<<"op["<<op<<"] not yet implmented !"<<endl;
assert(false);
break;
}
left->nonlinearEdges(edges);
right->nonlinearEdges(edges);
}
#if FORWARD_ENABLED
void BinaryOPNode::hess_forward(unsigned int len, double** ret_vec)
{
double* lvec = NULL;
double* rvec = NULL;
if(left!=NULL){
left->hess_forward(len,&lvec);
}
if(right!=NULL){
right->hess_forward(len,&rvec);
}
*ret_vec = new double[len];
hess_forward_calc0(len,lvec,rvec,*ret_vec);
//delete lvec, rvec
delete[] lvec;
delete[] rvec;
}
void BinaryOPNode::hess_forward_calc0(unsigned int& len, double* lvec, double* rvec, double* ret_vec)
{
double hu = NaN_Double, hv= NaN_Double;
double lval = NaN_Double, rval = NaN_Double;
double val = NaN_Double;
unsigned int index = 0;
switch (op)
{
case OP_PLUS:
rval = SV->pop_back();
lval = SV->pop_back();
val = lval + rval;
SV->push_back(val);
//calculate the first order derivatives
for(unsigned int i=0;i<AutoDiff::num_var;++i)
{
ret_vec[i] = lvec[i]+rvec[i];
}
//calculate the second order
index = AutoDiff::num_var;
for(unsigned int i=0;i<AutoDiff::num_var;++i)
{
for(unsigned int j=i;j<AutoDiff::num_var;++j){
ret_vec[index] = lvec[index] + 0 + rvec[index] + 0;
++index;
}
}
assert(index==len);
break;
case OP_MINUS:
rval = SV->pop_back();
lval = SV->pop_back();
val = lval + rval;
SV->push_back(val);
//calculate the first order derivatives
for(unsigned int i=0;i<AutoDiff::num_var;++i)
{
ret_vec[i] = lvec[i] - rvec[i];
}
//calculate the second order
index = AutoDiff::num_var;
for(unsigned int i=0;i<AutoDiff::num_var;++i)
{
for(unsigned int j=i;j<AutoDiff::num_var;++j){
ret_vec[index] = lvec[index] + 0 - rvec[index] + 0;
++index;
}
}
assert(index==len);
break;
case OP_TIMES:
rval = SV->pop_back();
lval = SV->pop_back();
val = lval * rval;
SV->push_back(val);
hu = rval;
hv = lval;
//calculate the first order derivatives
for(unsigned int i =0;i<AutoDiff::num_var;++i)
{
ret_vec[i] = hu*lvec[i] + hv*rvec[i];
}
//calculate the second order
index = AutoDiff::num_var;
for(unsigned int i=0;i<AutoDiff::num_var;++i)
{
for(unsigned int j=i;j<AutoDiff::num_var;++j)
{
ret_vec[index] = hu * lvec[index] + lvec[i] * rvec[j]+hv * rvec[index] + rvec[i] * lvec[j];
++index;
}
}
assert(index==len);
break;
case OP_POW:
rval = SV->pop_back();
lval = SV->pop_back();
val = pow(lval,rval);
SV->push_back(val);
if(left->getType()==PNode_Type && right->getType()==PNode_Type)
{
std::fill_n(ret_vec,len,0);
}
else
{
hu = rval*pow(lval,(rval-1));
hv = pow(lval,rval)*log(lval);
if(left->getType()==PNode_Type)
{
double coeff = pow(log(lval),2)*pow(lval,rval);
//calculate the first order derivatives
for(unsigned int i =0;i<AutoDiff::num_var;++i)
{
ret_vec[i] = hu*lvec[i] + hv*rvec[i];
}
//calculate the second order
index = AutoDiff::num_var;
for(unsigned int i=0;i<AutoDiff::num_var;++i)
{
for(unsigned int j=i;j<AutoDiff::num_var;++j)
{
ret_vec[index] = 0 + 0 + hv * rvec[index] + rvec[i] * coeff * rvec[j];
++index;
}
}
}
else if(right->getType()==PNode_Type)
{
double coeff = rval*(rval-1)*pow(lval,rval-2);
//calculate the first order derivatives
for(unsigned int i =0;i<AutoDiff::num_var;++i)
{
ret_vec[i] = hu*lvec[i] + hv*rvec[i];
}
//calculate the second order
index = AutoDiff::num_var;
for(unsigned int i=0;i<AutoDiff::num_var;++i)
{
for(unsigned int j=i;j<AutoDiff::num_var;++j)
{
ret_vec[index] = hu*lvec[index] + lvec[i] * coeff * lvec[j] + 0 + 0;
++index;
}
}
}
else
{
assert(false);
}
}
assert(index==len);
break;
case OP_SIN: //TODO should move to UnaryOPNode.cpp?
assert(left!=NULL&&right==NULL);
lval = SV->pop_back();
val = sin(lval);
SV->push_back(val);
hu = cos(lval);
double coeff;
coeff = -val; //=sin(left->val); -- and avoid cross initialisation
//calculate the first order derivatives
for(unsigned int i =0;i<AutoDiff::num_var;++i)
{
ret_vec[i] = hu*lvec[i] + 0;
}
//calculate the second order
index = AutoDiff::num_var;
for(unsigned int i=0;i<AutoDiff::num_var;++i)
{
for(unsigned int j=i;j<AutoDiff::num_var;++j)
{
ret_vec[index] = hu*lvec[index] + lvec[i] * coeff * lvec[j] + 0 + 0;
++index;
}
}
assert(index==len);
break;
default:
cerr<<"op["<<op<<"] not yet implemented!";
break;
}
}
#endif
string BinaryOPNode::toString(int level){
ostringstream oss;
string s(level,'\t');
oss<<s<<"[BinaryOPNode]("<<op<<")";
return oss.str();
}
} /* namespace AutoDiff */
| 23.013804
| 113
| 0.588937
|
Talustus
|
5e82025e8dadf298a606cd33e4afd6e015564838
| 962
|
cpp
|
C++
|
ITP1/ITP1_7D.cpp
|
taki-d/AizuOnlineJudgeAnswer
|
9ab2a6db91d9ea703081703b66ee5aaeb8ec0c31
|
[
"MIT"
] | 2
|
2017-05-02T06:46:31.000Z
|
2017-06-18T21:59:05.000Z
|
ITP1/ITP1_7D.cpp
|
taki-d/AizuOnlineJudgeAnswer
|
9ab2a6db91d9ea703081703b66ee5aaeb8ec0c31
|
[
"MIT"
] | null | null | null |
ITP1/ITP1_7D.cpp
|
taki-d/AizuOnlineJudgeAnswer
|
9ab2a6db91d9ea703081703b66ee5aaeb8ec0c31
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int a,b,c;
cin >> a >> b >> c;
vector<vector<int>> A(a,vector<int>(b,0));
vector<vector<int>> B(b,vector<int>(c,0));
for (int d = 0; d < a; ++d) {
for (int e = 0; e < b; ++e) {
cin >> A.at(d).at(e);
}
}
for (int f = 0; f < b; ++f) {
for (int g = 0; g < c; ++g) {
cin >> B.at(f).at(g);
}
}
vector<vector<int>> Result(a,vector<int>(c,0));
for (int i = 0; i < a; ++i) {
for (int k = 0; k < b; ++k) {
for (int j = 0; j < c; ++j) {
Result.at(i).at(j) += A.at(i).at(k) * B.at(k).at(j);
}
}
}
for (int l = 0; l < a; ++l) {
for (int m = 0; m < c; ++m) {
cout << Result.at(l).at(m);
if(m != c -1){
cout << " ";
}
}
cout << endl;
}
return 0;
}
| 18.862745
| 68
| 0.351351
|
taki-d
|
5e88c33719a8b3c623d5ae9d2b5b3a96e8ed9d82
| 90
|
hpp
|
C++
|
2SST/2LW/files.hpp
|
AVAtarMod/University
|
3c784a1e109b7a6f6ea495278ec3dc126258625a
|
[
"BSD-3-Clause"
] | 1
|
2021-07-31T06:55:08.000Z
|
2021-07-31T06:55:08.000Z
|
2SST/2LW/files.hpp
|
AVAtarMod/University-C
|
e516aac99eabbcbe14d897239f08acf6c8e146af
|
[
"BSD-3-Clause"
] | 1
|
2020-11-25T12:00:11.000Z
|
2021-01-13T08:51:52.000Z
|
2SST/2LW/files.hpp
|
AVAtarMod/University-C
|
e516aac99eabbcbe14d897239f08acf6c8e146af
|
[
"BSD-3-Clause"
] | null | null | null |
#ifndef FILES
#define FILES
#include <fstream>
bool isFileExist(const char *file);
#endif
| 15
| 35
| 0.766667
|
AVAtarMod
|
5e88c9cd294c0c9ca7fd2c0eb85bfc85a43eea8d
| 4,251
|
cpp
|
C++
|
sjf_p.cpp
|
tanujsinghal24/Lab_codes-COC3930-
|
3f36835b16897304c6b5d00ead1219d76f6b58df
|
[
"MIT"
] | 1
|
2021-08-02T08:35:32.000Z
|
2021-08-02T08:35:32.000Z
|
sjf_p.cpp
|
tanujsinghal24/Lab_codes-COC3930-
|
3f36835b16897304c6b5d00ead1219d76f6b58df
|
[
"MIT"
] | null | null | null |
sjf_p.cpp
|
tanujsinghal24/Lab_codes-COC3930-
|
3f36835b16897304c6b5d00ead1219d76f6b58df
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
class System_p {
public:
int process_num ,burst_time,arrival_t;
};
int n;
int wait_time[1000], turn_around_t[1000], total_wt = 0,total_tat = 0;
void print_process(System_p pt[],int i,int curr_t){
cout << "Process num Burst time Arrival time Current time\n";
cout << " " << pt[i].process_num << "\t\t"<< pt[i].burst_time << "\t\t"<< pt[i].arrival_t << "\t\t"<< curr_t << endl<<endl;
}
void fcfs(System_p p[]){
System_p ptemp[n];
int current_time=0;float avg_wt=0,avg_tat=0,st[n],ft[n];
for(int i=0;i<n;i++)
ptemp[i]=p[i];
for(int i=0;i<n;i++){
for(int j=0;j<n-i-1;j++){
if(ptemp[j+1].arrival_t<ptemp[j].arrival_t){
System_p temp = ptemp[j];
ptemp[j]=ptemp[j+1];
ptemp[j+1]=temp;
}
}
}
current_time=ptemp[0].arrival_t;
st[0]=current_time;
for(int i=0;i<n;i++){
int curr_p=i;
if(i<n-1)
st[i]=current_time;
print_process(ptemp,curr_p,current_time);
wait_time[i]= current_time - ptemp[curr_p].arrival_t;
if (wait_time[curr_p] < 0)
wait_time[curr_p] = 0;
avg_wt+=wait_time[i];
turn_around_t[i]=ptemp[curr_p].burst_time + wait_time[i];
avg_tat+=turn_around_t[i];
current_time+=ptemp[curr_p].burst_time;
ft[i]=current_time;
}
cout<<"\n\nGantt Chart: "<<ptemp[0].arrival_t<<" ";
for (int i = 0; i < n; i++){
if(0)
cout << " P" << ptemp[i].process_num << "\t"<< ptemp[i].arrival_t+turn_around_t[i];
else
cout << " P" << ptemp[i].process_num << "\t"<< ft[i];
}
cout<<"\n\n\n";
cout<<"FCFS Final Process Table:"<<endl;
cout << "Process num Burst time Arrival time Waiting time Turn around time\n";
for (int i = 0; i < n; i++)
cout << " " << ptemp[i].process_num << "\t\t"<< ptemp[i].burst_time << "\t\t"<< ptemp[i].arrival_t << "\t\t " << wait_time[i] << "\t\t " << turn_around_t[i] << endl;
avg_wt/=n;
avg_tat/=n;
cout << "\nAverage waiting time = "<< avg_wt<<"\nAverage turn around time = "<< avg_tat<<endl;
cout<<"\n\n\n\n";
}
void sjf_preemtive(System_p p[])
{
int temp[n];
float avg_wt,avg_tat;
for (int i = 0; i < n; i++)
temp[i] = p[i].burst_time;
int num_p = 0, current_time = 0, curr_min = 1000000,curr_p = 0, finish_time,f=0;
while (num_p != n) {
for (int j = 0; j < n; j++) {
if ((p[j].arrival_t <= current_time) )
if((temp[j] < curr_min) && (temp[j] > 0)) {
curr_min = temp[j];
curr_p = j;
f = 1;
}
}
if (f == 0) {
current_time++;
continue;
}
print_process(p,curr_p,current_time);
current_time++;
temp[curr_p]--;
curr_min = temp[curr_p];
if (temp[curr_p] == 0) {
num_p++;
f = 0;
wait_time[curr_p] = current_time - p[curr_p].arrival_t - p[curr_p].burst_time;
if (wait_time[curr_p] < 0)
wait_time[curr_p] = 0;
}
if (curr_min == 0)
curr_min = 1000000;
}
for (int i = 0; i < n; i++)
turn_around_t[i] = p[i].burst_time + wait_time[i];
cout<<"\n\nSJF PREEMTIVE Final Process Table:"<<endl;
cout << "Process num Burst time Arrival time Waiting time Turn around time\n";
for (int i = 0; i < n; i++) {
avg_wt += wait_time[i];
avg_tat += turn_around_t[i];
}
for (int i = 0; i < n; i++)
cout << " " << p[i].process_num << "\t\t"<< p[i].burst_time << "\t\t"<< p[i].arrival_t << "\t\t " << wait_time[i] << "\t\t " << turn_around_t[i] << endl;
avg_wt/=n;
avg_tat/=n;
cout << "\nAverage waiting time = "<< avg_wt<<"\nAverage turn around time = "<< avg_tat<<endl;
cout<<"\n\n\n\n";
}
int main()
{
cout<<"Enter number of processes:";
cin>>n;
System_p p[n];
for(int i=0;i<n;i++){
cout<<"Enter arrival and burst time of process "<<i+1<<" :";
p[i].process_num=i+1;
cin>>p[i].arrival_t>>p[i].burst_time;
}
fcfs(p);
// int t=1;
// cout<<"Enter Scheduling algorithm to be used(1.SJF PREEMTIVE 2.FCFS):";
// cin>>t;
// if(t==1)
// sjf_preemtive(p);
// else if(t==2)
// fcfs(p);
return 0;
}
| 32.204545
| 168
| 0.537521
|
tanujsinghal24
|
5e8b22afdc251b65480a82d20249eeabcd099f99
| 4,103
|
cpp
|
C++
|
src/mpc-base.cpp
|
PepMS/eagle-mpc
|
522b4af6f31dcdec72c9c461ace28bb774aa4057
|
[
"BSD-3-Clause"
] | 10
|
2021-07-14T10:50:20.000Z
|
2022-03-14T06:27:13.000Z
|
src/mpc-base.cpp
|
PepMS/multicopter-mpc
|
522b4af6f31dcdec72c9c461ace28bb774aa4057
|
[
"BSD-3-Clause"
] | 29
|
2020-06-04T08:38:52.000Z
|
2020-09-25T10:26:25.000Z
|
src/mpc-base.cpp
|
PepMS/eagle-mpc
|
522b4af6f31dcdec72c9c461ace28bb774aa4057
|
[
"BSD-3-Clause"
] | 2
|
2021-11-02T02:14:45.000Z
|
2022-01-10T11:32:59.000Z
|
#include "eagle_mpc/mpc-base.hpp"
namespace eagle_mpc
{
MpcAbstract::MpcAbstract(const std::string& yaml_path)
{
eagle_mpc::ParserYaml parser(yaml_path);
params_server_ = boost::make_shared<ParamsServer>(parser.get_params());
initializeRobotObjects();
loadParams();
int_models_.reserve(params_.knots);
dif_models_.reserve(params_.knots);
cost_factory_ = boost::make_shared<CostModelFactory>();
}
void MpcAbstract::initializeRobotObjects()
{
std::string prefix_robot = "robot/";
robot_model_path_ = getUrdfPath(params_server_->getParam<std::string>(prefix_robot + "urdf"));
pinocchio::Model model;
pinocchio::urdf::buildModel(robot_model_path_, pinocchio::JointModelFreeFlyer(), model);
robot_model_ = boost::make_shared<pinocchio::Model>(model);
platform_params_ = boost::make_shared<MultiCopterBaseParams>();
platform_params_->autoSetup(prefix_robot + "platform/", params_server_, robot_model_);
robot_state_ = boost::make_shared<crocoddyl::StateMultibody>(robot_model_);
actuation_ = boost::make_shared<crocoddyl::ActuationModelMultiCopterBase>(robot_state_, platform_params_->tau_f_);
squash_ = boost::make_shared<crocoddyl::SquashingModelSmoothSat>(platform_params_->u_lb, platform_params_->u_ub,
actuation_->get_nu());
actuation_squash_ =
boost::make_shared<crocoddyl::ActuationSquashingModel>(actuation_, squash_, actuation_->get_nu());
}
void MpcAbstract::loadParams()
{
std::string prefix_controller = "mpc_controller/";
std::string integration_method = params_server_->getParam<std::string>(prefix_controller + "integration_method");
params_.integrator_type = IntegratedActionModelTypes_map.at(integration_method);
params_.knots = params_server_->getParam<int>(prefix_controller + "knots");
params_.iters = params_server_->getParam<int>(prefix_controller + "iters");
params_.dt = params_server_->getParam<int>(prefix_controller + "dt");
std::string solver = params_server_->getParam<std::string>(prefix_controller + "solver");
params_.solver_type = SolverTypes_map.at(solver);
try {
params_.callback = params_server_->getParam<bool>(prefix_controller + "callback");
} catch (const std::exception& e) {
EMPC_DEBUG(e.what(), " Set to false.");
params_.callback = false;
}
}
const boost::shared_ptr<pinocchio::Model>& MpcAbstract::get_robot_model() const { return robot_model_; }
const std::string& MpcAbstract::get_robot_model_path() const { return robot_model_path_; }
const boost::shared_ptr<MultiCopterBaseParams>& MpcAbstract::get_platform_params() const { return platform_params_; }
const boost::shared_ptr<crocoddyl::StateMultibody>& MpcAbstract::get_robot_state() const { return robot_state_; }
const boost::shared_ptr<crocoddyl::ActuationModelMultiCopterBase>& MpcAbstract::get_actuation() const
{
return actuation_;
}
const boost::shared_ptr<crocoddyl::SquashingModelSmoothSat>& MpcAbstract::get_squash() const { return squash_; }
const boost::shared_ptr<crocoddyl::ActuationSquashingModel>& MpcAbstract::get_actuation_squash() const
{
return actuation_squash_;
}
const std::vector<boost::shared_ptr<crocoddyl::DifferentialActionModelAbstract>>& MpcAbstract::get_dif_models() const
{
return dif_models_;
}
const std::vector<boost::shared_ptr<crocoddyl::ActionModelAbstract>>& MpcAbstract::get_int_models() const
{
return int_models_;
}
const boost::shared_ptr<crocoddyl::ShootingProblem>& MpcAbstract::get_problem() const { return problem_; }
const boost::shared_ptr<crocoddyl::SolverDDP>& MpcAbstract::get_solver() const { return solver_; }
const std::size_t& MpcAbstract::get_dt() const { return params_.dt; }
const std::size_t& MpcAbstract::get_knots() const { return params_.knots; }
const std::size_t& MpcAbstract::get_iters() const { return params_.iters; }
const SolverTypes& MpcAbstract::get_solver_type() const { return params_.solver_type; }
} // namespace eagle_mpc
| 46.101124
| 119
| 0.737022
|
PepMS
|
5e8ccbbf856ee66c4c6afbe3f21b273f792e6fbc
| 1,749
|
cpp
|
C++
|
Editor/Source/Controls/ToolbarView.cpp
|
Claudio-Marchini/Lumen
|
41183d71f0fe6dfe9964617b127b40b26339c822
|
[
"MIT"
] | null | null | null |
Editor/Source/Controls/ToolbarView.cpp
|
Claudio-Marchini/Lumen
|
41183d71f0fe6dfe9964617b127b40b26339c822
|
[
"MIT"
] | null | null | null |
Editor/Source/Controls/ToolbarView.cpp
|
Claudio-Marchini/Lumen
|
41183d71f0fe6dfe9964617b127b40b26339c822
|
[
"MIT"
] | null | null | null |
#include "ToolbarView.h"
#include "../EditorApplication.h"
#include <imgui/imgui.h>
void ToolbarView::Render()
{
if (ImGui::BeginMainMenuBar())
{
if (ImGui::BeginMenu("Project"))
{
if (ImGui::MenuItem("Create"))
{
mFileOpen = true;
}
ImGui::MenuItem("Open");
if (ImGui::MenuItem("Save"))
{
EditorApp::Get()->Save();
}
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Actions"))
{
const b8 scenePlaying{ EditorApp::Get()->GetIsPlaying() };
if (ImGui::MenuItem(scenePlaying ? "Stop" : "Play"))
{
static const char* tempFile{ "$Temp$.lumen" };
EditorApp::Get()->SetPlaying(!scenePlaying);
auto& project{ EditorApp::Get()->GetProject() };
Lumen::Utils::Serializer serializer{ &project };
scenePlaying ? serializer.Load(project.Path / tempFile) : serializer.Save(project.Path / tempFile);
if (scenePlaying)
{
EditorApp::Get()->GetSceneView().mSelectedEntity = nullptr;
std::filesystem::remove(project.Path / tempFile);
}
else
{
EditorApp::Get()->GetScriptManager().Start(EditorApp::Get()->GetScene());
}
}
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Settings"))
{
ImGui::EndMenu();
}
ImGui::EndMainMenuBar();
}
CreateDialog();
}
void ToolbarView::CreateDialog()
{
if (mFileOpen)
{
ImGui::OpenPopup("Select a location");
mFileOpen = false;
if (!std::filesystem::exists(mFileExplorer.GetCurrentPath()))
{
mFileExplorer.SetCurrentPath("C:\\");
}
}
if (ImGui::BeginPopupModal("Select a location"))
{
mFileExplorer.Draw();
if (ImGui::Button("Create"))
ImGui::CloseCurrentPopup();
ImGui::SameLine();
if (ImGui::Button("Cancel"))
ImGui::CloseCurrentPopup();
ImGui::EndPopup();
}
}
| 20.576471
| 103
| 0.626072
|
Claudio-Marchini
|
5e906bde120ef8c06b7312812947a1ed610dcf97
| 609
|
cpp
|
C++
|
Leetcode/May-Challenge/remove-kdigits.cpp
|
shashankkmciv18/dsa
|
6feba269292d95d36e84f1adb910fe2ed5467f71
|
[
"MIT"
] | 54
|
2020-07-31T14:50:23.000Z
|
2022-03-14T11:03:02.000Z
|
Leetcode/May-Challenge/remove-kdigits.cpp
|
SahilMund/dsa
|
a94151b953b399ea56ff50cf30dfe96100e8b9a7
|
[
"MIT"
] | null | null | null |
Leetcode/May-Challenge/remove-kdigits.cpp
|
SahilMund/dsa
|
a94151b953b399ea56ff50cf30dfe96100e8b9a7
|
[
"MIT"
] | 30
|
2020-08-15T17:39:02.000Z
|
2022-03-10T06:50:18.000Z
|
class Solution {
public:
string removeKdigits(string num, int k) {
int n = num.size();
if( n<= k ) {
return "0";
}
while(k) {
int i = 0;
// for finding the peaks.
while(i+1<n && num[i+1]>=num[i]) i++;
num.erase(i,1);
k--;
}
// for deleting cases for 0 0 2 0 0 or 0 0 0 0 0
int j = 0;
while( j < n && num[j] == '0' ) j++;
num = num.substr(j);
return num=="" ? "0" : num;
}
};
| 20.3
| 58
| 0.338259
|
shashankkmciv18
|
5e993460efef73c852f0c0da59d4ff81ccfb98e3
| 182
|
cpp
|
C++
|
regression/esbmc-cpp/qt/QVector/vector_capacity_bug/main.cpp
|
shmarovfedor/esbmc
|
3226a3d68b009d44b9535a993ac0f25e1a1fbedd
|
[
"BSD-3-Clause"
] | 143
|
2015-06-22T12:30:01.000Z
|
2022-03-21T08:41:17.000Z
|
regression/esbmc-cpp/qt/QVector/vector_capacity_bug/main.cpp
|
shmarovfedor/esbmc
|
3226a3d68b009d44b9535a993ac0f25e1a1fbedd
|
[
"BSD-3-Clause"
] | 542
|
2017-06-02T13:46:26.000Z
|
2022-03-31T16:35:17.000Z
|
regression/esbmc-cpp/qt/QVector/vector_capacity_bug/main.cpp
|
shmarovfedor/esbmc
|
3226a3d68b009d44b9535a993ac0f25e1a1fbedd
|
[
"BSD-3-Clause"
] | 81
|
2015-10-21T22:21:59.000Z
|
2022-03-24T14:07:55.000Z
|
#include <QVector>
#include <cassert>
int main ()
{
QVector<int> myQVector;
myQVector << 1 << 4 << 6 << 8 << 10 << 12;
assert( !(myQVector.capacity() > 0) );
return 0;
}
| 13
| 44
| 0.56044
|
shmarovfedor
|
5e99fc1ad3513b3b4399c14fccbfcc41d5f07bc7
| 749
|
hpp
|
C++
|
cmdstan/stan/lib/stan_math/test/unit/math/torsten/expect_near_matrix_eq.hpp
|
csetraynor/Torsten
|
55b59b8068e2a539346f566ec698c755a9e3536c
|
[
"BSD-3-Clause"
] | null | null | null |
cmdstan/stan/lib/stan_math/test/unit/math/torsten/expect_near_matrix_eq.hpp
|
csetraynor/Torsten
|
55b59b8068e2a539346f566ec698c755a9e3536c
|
[
"BSD-3-Clause"
] | null | null | null |
cmdstan/stan/lib/stan_math/test/unit/math/torsten/expect_near_matrix_eq.hpp
|
csetraynor/Torsten
|
55b59b8068e2a539346f566ec698c755a9e3536c
|
[
"BSD-3-Clause"
] | null | null | null |
#ifndef TEST_MATH_MATRIX_EXPECT_NEAR_MATRIX_EQ_HPP
#define TEST_MATH_MATRIX_EXPECT_NEAR_MATRIX_EQ_HPP
#include <gtest/gtest.h>
void expect_near_matrix_eq(const
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>& a,
const
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>& b,
const double& rel_err,
const double& abs_err = 1e-15) {
EXPECT_EQ(a.rows(), b.rows());
EXPECT_EQ(a.cols(), b.cols());
double err;
for (int i = 0; i < a.rows(); ++i)
for (int j = 0; j < a.cols(); ++j) {
err = std::max(std::abs(rel_err * a(i, j)), abs_err);
EXPECT_NEAR(a(i, j), b(i, j), err);
}
}
#endif
| 32.565217
| 84
| 0.543391
|
csetraynor
|
5ea16254bd340594b68996760722d1463f05ff33
| 647
|
cpp
|
C++
|
src/bits_of_matcha/tensor/iterations/flatiteration.cpp
|
patztablook22/matcha-core
|
c6c595e82a6f2ff42342f28ed856be37a2b2ab5c
|
[
"MIT"
] | null | null | null |
src/bits_of_matcha/tensor/iterations/flatiteration.cpp
|
patztablook22/matcha-core
|
c6c595e82a6f2ff42342f28ed856be37a2b2ab5c
|
[
"MIT"
] | null | null | null |
src/bits_of_matcha/tensor/iterations/flatiteration.cpp
|
patztablook22/matcha-core
|
c6c595e82a6f2ff42342f28ed856be37a2b2ab5c
|
[
"MIT"
] | 1
|
2022-01-09T12:07:04.000Z
|
2022-01-09T12:07:04.000Z
|
#include "bits_of_matcha/tensor/iterations/flatiteration.h"
#include "bits_of_matcha/tensor/iterators/flatiterator.h"
#include "bits_of_matcha/tensor/tensor.h"
namespace matcha {
template <class T, class Access>
FlatIteration<T, Access>::FlatIteration(Access& tensor)
: tensor_(tensor)
{}
template <class T, class Access>
FlatIterator<T> FlatIteration<T, Access>::begin() {
return FlatIterator<T>(
reinterpret_cast<T*>(&tensor_.buffer_[0])
);
}
template <class T, class Access>
FlatIterator<T> FlatIteration<T, Access>::end() {
return FlatIterator(
reinterpret_cast<T*>(&tensor_.buffer_[0] + tensor_.buffer_.bytes())
);
}
}
| 23.962963
| 71
| 0.735703
|
patztablook22
|
5ea3878acb0a6799a1327973d36d59e0acf096d6
| 5,787
|
cpp
|
C++
|
src/Script/gameObjs/majorGos/bushs/Bush.cpp
|
turesnake/tprPixelGames
|
6b5471a072a1a8b423834ab04ff03e64df215d5e
|
[
"BSD-3-Clause"
] | 591
|
2020-03-12T05:10:33.000Z
|
2022-03-30T13:41:59.000Z
|
src/Script/gameObjs/majorGos/bushs/Bush.cpp
|
turesnake/tprPixelGames
|
6b5471a072a1a8b423834ab04ff03e64df215d5e
|
[
"BSD-3-Clause"
] | 4
|
2020-04-06T01:55:06.000Z
|
2020-05-02T04:28:04.000Z
|
src/Script/gameObjs/majorGos/bushs/Bush.cpp
|
turesnake/tprPixelGames
|
6b5471a072a1a8b423834ab04ff03e64df215d5e
|
[
"BSD-3-Clause"
] | 112
|
2020-04-05T23:55:36.000Z
|
2022-03-17T11:58:02.000Z
|
/*
* ======================= Bush.cpp ==========================
* -- tpr --
* CREATE -- 2019.10.09
* MODIFY --
* ----------------------------------------------------------
*/
#include "pch.h"
#include "Script/gameObjs/majorGos/bushs/Bush.h"
//-------------------- Engine --------------------//
#include "animSubspeciesId.h"
#include "dyParams.h"
#include "esrc_gameSeed.h"
//-------------------- Script --------------------//
#include "Script/components/windAnim/WindAnim.h"
using namespace std::placeholders;
namespace gameObjs {//------------- namespace gameObjs ----------------
namespace bush_inn {//----------- namespace: bush_inn ----------------//
std::vector<AnimActionEName> windAnimActionEName_pool {};
//----- flags -----//
bool isFstCalled {true};
//===== funcs =====//
void init()noexcept;
}//-------------- namespace: bush_inn end ----------------//
class Bush_PvtBinary{
public:
Bush_PvtBinary():
windAnimUPtr( std::make_unique<component::WindAnim>() )
{}
// Exist but forbidden to call
Bush_PvtBinary( const Bush_PvtBinary & ){ tprAssert(0); }
Bush_PvtBinary &operator=( const Bush_PvtBinary & );
//------- vals -------//
int tmp {0};
std::unique_ptr<component::WindAnim> windAnimUPtr {};
};
Bush_PvtBinary &Bush_PvtBinary::operator=( const Bush_PvtBinary & ){
tprAssert(0);
return *this; // never reach
}
void Bush::init(GameObj &goRef_, const DyParam &dyParams_ ){
//-- simple way ...
if( bush_inn::isFstCalled ){
bush_inn::isFstCalled = false;
bush_inn::init();
}
//================ go.pvtBinary =================//
auto *pvtBp = goRef_.init_pvtBinary<Bush_PvtBinary>();
//================ dyParams =================//
size_t typeHash = dyParams_.get_typeHash();
tprAssert( typeHash == typeid(DyParams_GoDataForCreate).hash_code() );
const DyParams_GoDataForCreate *bpParamPtr = dyParams_.get_binaryPtr<DyParams_GoDataForCreate>();
const GoDataForCreate *goDataPtr = bpParamPtr->goDataPtr;
//----- must before creat_new_goMesh() !!! -----//
goRef_.actionDirection.reset( goDataPtr->get_direction() );
goRef_.brokenLvl.reset( goDataPtr->get_brokenLvl() );
goRef_.set_colliDataFromJsonPtr( goDataPtr->get_colliDataFromJsonPtr() );
//================ animFrameSet/animFrameIdxHandle/ goMesh =================//
// 有些 bush 只有一个 gomesh,有些则是 复数个
// 一律按 复数个来处理
for( const auto &sptrRef : goDataPtr->get_goMeshs_autoInit() ){
const GoDataForCreate::GoMeshBase &gmRef = *sptrRef;
auto &goMeshRef = goRef_.goMeshSet.creat_new_goMesh(
gmRef.get_goMeshName(),
gmRef.get_subspeciesId(),
gmRef.get_animActionEName(),
gmRef.get_renderLayerType(),
gmRef.get_shaderType(), // pic shader
gmRef.get_dposOff(), //- pposoff
gmRef.get_zOff(), //- zOff
1151, // uweight tmp
gmRef.get_isVisible() //- isVisible
);
// 先收集 所有参与 风吹动画的 gomesh 数据
pvtBp->windAnimUPtr->insert_goMesh( &goMeshRef, gmRef.get_windDelayIdx() );
}
//----- component: windAnim -----//
// 正式 init
pvtBp->windAnimUPtr->init( &bush_inn::windAnimActionEName_pool );
//================ bind callback funcs =================//
//-- 故意将 首参数this 绑定到 保留类实例 dog_a 身上
goRef_.RenderUpdate = std::bind( &Bush::OnRenderUpdate, _1 );
goRef_.LogicUpdate = std::bind( &Bush::OnLogicUpdate, _1 );
//-------- actionSwitch ---------//
goRef_.actionSwitch.bind_func( std::bind( &Bush::OnActionSwitch, _1, _2 ) );
goRef_.actionSwitch.signUp( ActionSwitchType::Idle );
//================ go self vals =================//
}
void Bush::OnRenderUpdate( GameObj &goRef_ ){
//=====================================//
// ptr rebind
//-------------------------------------//
auto *pvtBp = goRef_.get_pvtBinaryPtr<Bush_PvtBinary>();
//=====================================//
// windClock
//-------------------------------------//
// goMeshRef.bind_animAction() 已经在 update 内被自动调用了
// 这不是一个好实现
// 在未来,可能要被转移到 其他地方
// ...
pvtBp->windAnimUPtr->update();
//=====================================//
// 将 确认要渲染的 goMeshs,添加到 renderPool
//-------------------------------------//
goRef_.goMeshSet.render_all_goMeshs_without_callback();
}
void Bush::bind( GameObj &goRef_ ){ /* do nothing... */ }
void Bush::rebind( GameObj &goRef_ ){ /* do nothing... */ }
void Bush::OnLogicUpdate( GameObj &goRef_ ){ /* do nothing... */ }
void Bush::OnActionSwitch( GameObj &goRef_, ActionSwitchType type_ ){ /* do nothing... */ }
namespace bush_inn {//----------- namespace: bush_inn ----------------//
void init()noexcept{
std::default_random_engine randEngine;
randEngine.seed( get_new_seed() );
//=== windAnimActionName pool ===//
windAnimActionEName_pool.reserve(20);
windAnimActionEName_pool.insert( windAnimActionEName_pool.end(), 15, AnimActionEName::Wind );
windAnimActionEName_pool.insert( windAnimActionEName_pool.end(), 1, AnimActionEName::Idle );
std::shuffle( windAnimActionEName_pool.begin(), windAnimActionEName_pool.end(), randEngine );
}
}//-------------- namespace: bush_inn end ----------------//
}//------------- namespace gameObjs: end ----------------
| 31.796703
| 101
| 0.51633
|
turesnake
|
5ea8820da0106fd47dbe8c8727502233e2c7aca2
| 379
|
hpp
|
C++
|
include/ce2/modules/ae/detail/ae_defines.hpp
|
chokomancarr/chokoengine2
|
2825f2b95d24689f4731b096c8be39cc9a0f759a
|
[
"Apache-2.0"
] | null | null | null |
include/ce2/modules/ae/detail/ae_defines.hpp
|
chokomancarr/chokoengine2
|
2825f2b95d24689f4731b096c8be39cc9a0f759a
|
[
"Apache-2.0"
] | null | null | null |
include/ce2/modules/ae/detail/ae_defines.hpp
|
chokomancarr/chokoengine2
|
2825f2b95d24689f4731b096c8be39cc9a0f759a
|
[
"Apache-2.0"
] | null | null | null |
#pragma once
#include "chokoengine.hpp"
#define CE_MOD_AE_NS ModuleAE
#define CE_BEGIN_MOD_AE_NAMESPACE\
CE_BEGIN_NAMESPACE\
namespace CE_MOD_AE_NS {
#define CE_END_MOD_AE_NAMESPACE }\
CE_END_NAMESPACE
#if PLATFORM_WIN
#ifdef BUILD_MODULE_AE
#define CE_AE_EXPORT __declspec(dllexport)
#else
#define CE_AE_EXPORT __declspec(dllimport)
#endif
#else
#define CE_EXPORT
#endif
| 17.227273
| 42
| 0.825858
|
chokomancarr
|
5eac58620adb30b5a225f27e47cf7ed807f85462
| 4,869
|
cc
|
C++
|
src/PingService.cc
|
taschik/ramcloud
|
6ef2e1cd61111995881d54bda6f9296b4777b928
|
[
"0BSD"
] | 1
|
2016-01-18T12:41:28.000Z
|
2016-01-18T12:41:28.000Z
|
src/PingService.cc
|
taschik/ramcloud
|
6ef2e1cd61111995881d54bda6f9296b4777b928
|
[
"0BSD"
] | null | null | null |
src/PingService.cc
|
taschik/ramcloud
|
6ef2e1cd61111995881d54bda6f9296b4777b928
|
[
"0BSD"
] | null | null | null |
/* Copyright (c) 2011-2012 Stanford University
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "Common.h"
#include "CycleCounter.h"
#include "Cycles.h"
#include "RawMetrics.h"
#include "ShortMacros.h"
#include "PingClient.h"
#include "PingService.h"
#include "ServerList.h"
namespace RAMCloud {
/**
* Construct a PingService.
*
* \param context
* Overall information about the RAMCloud server. The caller is assumed
* to have associated a serverList with this context; if not, this service
* will not return a valid ServerList version in response to pings.
*/
PingService::PingService(Context* context)
: context(context)
, ignoreKill(false)
{
}
/**
* Top-level service method to handle the GET_METRICS request.
*
* \copydetails Service::ping
*/
void
PingService::getMetrics(const WireFormat::GetMetrics::Request* reqHdr,
WireFormat::GetMetrics::Response* respHdr,
Rpc* rpc)
{
string serialized;
metrics->serialize(serialized);
respHdr->messageLength = downCast<uint32_t>(serialized.length());
memcpy(new(rpc->replyPayload, APPEND) uint8_t[respHdr->messageLength],
serialized.c_str(), respHdr->messageLength);
}
/**
* Top-level service method to handle the PING request.
*
* \copydetails Service::ping
*/
void
PingService::ping(const WireFormat::Ping::Request* reqHdr,
WireFormat::Ping::Response* respHdr,
Rpc* rpc)
{
uint64_t ticks = 0;
CycleCounter<> counter(&ticks);
string callerId = ServerId(reqHdr->callerId).toString();
ServerId serverId(reqHdr->callerId);
if (serverId.isValid()) {
// Careful, turning this into a real log message causes spurious
// ping timeouts.
TEST_LOG("Received ping request from server %s",
serverId.toString().c_str());
if (!context->serverList->isUp(serverId)) {
respHdr->common.status = STATUS_CALLER_NOT_IN_CLUSTER;
}
}
counter.stop();
double ms = Cycles::toSeconds(ticks) * 1000;
if (ms > 10) {
LOG(WARNING, "Slow responding to ping request from server %s; "
"took %.2f ms", callerId.c_str(), ms);
}
}
/**
* Top-level service method to handle the PROXY_PING request.
*
* \copydetails Service::ping
*/
void
PingService::proxyPing(const WireFormat::ProxyPing::Request* reqHdr,
WireFormat::ProxyPing::Response* respHdr,
Rpc* rpc)
{
uint64_t start = Cycles::rdtsc();
PingRpc pingRpc(context, ServerId(reqHdr->serverId));
respHdr->replyNanoseconds = ~0UL;
if (pingRpc.wait(reqHdr->timeoutNanoseconds)) {
respHdr->replyNanoseconds = Cycles::toNanoseconds(
Cycles::rdtsc() - start);
}
}
/**
* For debugging and testing this function tells the server to kill itself.
* There will be no response to the RPC for this message, and the process
* will exit with status code 0.
*
* TODO(Rumble): Should be only for debugging and performance testing.
*/
void
PingService::kill(const WireFormat::Kill::Request* reqHdr,
WireFormat::Kill::Response* respHdr,
Rpc* rpc)
{
LOG(ERROR, "Server remotely told to kill itself.");
if (!ignoreKill)
exit(0);
}
/**
* Dispatch an RPC to the right handler based on its opcode.
*/
void
PingService::dispatch(WireFormat::Opcode opcode, Rpc* rpc)
{
switch (opcode) {
case WireFormat::GetMetrics::opcode:
callHandler<WireFormat::GetMetrics, PingService,
&PingService::getMetrics>(rpc);
break;
case WireFormat::Ping::opcode:
callHandler<WireFormat::Ping, PingService, &PingService::ping>(rpc);
break;
case WireFormat::ProxyPing::opcode:
callHandler<WireFormat::ProxyPing, PingService,
&PingService::proxyPing>(rpc);
break;
case WireFormat::Kill::opcode:
callHandler<WireFormat::Kill, PingService,
&PingService::kill>(rpc);
break;
default:
throw UnimplementedRequestError(HERE);
}
}
} // namespace RAMCloud
| 31.211538
| 80
| 0.659889
|
taschik
|
5eadd409f127c8b4fcf46a006fd9a0e3ac303e55
| 1,694
|
cpp
|
C++
|
clang/test/Driver/sycl-offload.cpp
|
steffenlarsen/llvm
|
9d60c3d97773c63b8ee597c35c3f897dbc1a7f9f
|
[
"Apache-2.0"
] | null | null | null |
clang/test/Driver/sycl-offload.cpp
|
steffenlarsen/llvm
|
9d60c3d97773c63b8ee597c35c3f897dbc1a7f9f
|
[
"Apache-2.0"
] | null | null | null |
clang/test/Driver/sycl-offload.cpp
|
steffenlarsen/llvm
|
9d60c3d97773c63b8ee597c35c3f897dbc1a7f9f
|
[
"Apache-2.0"
] | null | null | null |
/// Check "-aux-target-cpu" and "target-cpu" are passed when compiling for SYCL offload device and host codes:
// RUN: %clang -### -fsycl -c %s 2>&1 | FileCheck -check-prefix=CHECK-OFFLOAD %s
// CHECK-OFFLOAD: clang{{.*}} "-cc1" {{.*}} "-fsycl-is-device"
// CHECK-OFFLOAD-SAME: "-aux-target-cpu" "[[HOST_CPU_NAME:[^ ]+]]"
// CHECK-OFFLOAD-NEXT: clang{{.*}} "-cc1" {{.*}}
// CHECK-OFFLOAD-NEXT-SAME: "-fsycl-is-host"
// CHECK-OFFLOAD-NEXT-SAME: "-target-cpu" "[[HOST_CPU_NAME]]"
/// Check "-aux-target-cpu" with "-aux-target-feature" and "-target-cpu" with "-target-feature" are passed
/// when compiling for SYCL offload device and host codes:
// RUN: %clang -fsycl -mavx -c %s -### -o %t.o 2>&1 | FileCheck -check-prefix=OFFLOAD-AVX %s
// OFFLOAD-AVX: clang{{.*}} "-cc1" {{.*}} "-fsycl-is-device"
// OFFLOAD-AVX-SAME: "-aux-target-cpu" "[[HOST_CPU_NAME:[^ ]+]]" "-aux-target-feature" "+avx"
// OFFLOAD-AVX-NEXT: clang{{.*}} "-cc1" {{.*}}
// OFFLOAD-AVX-NEXT-SAME: "-fsycl-is-host"
// OFFLOAD-AVX-NEXT-SAME: "-target-cpu" "[[HOST_CPU_NAME]]" "-target-feature" "+avx"
/// Check that the needed -fsycl -fsycl-is-device and -fsycl-is-host options
/// are passed to all of the needed compilation steps regardless of final
/// phase.
// RUN: %clang -### -fsycl -c %s 2>&1 | FileCheck -check-prefix=CHECK-OPTS %s
// RUN: %clang -### -fsycl -E %s 2>&1 | FileCheck -check-prefix=CHECK-OPTS %s
// RUN: %clang -### -fsycl -S %s 2>&1 | FileCheck -check-prefix=CHECK-OPTS %s
// RUN: %clang -### -fsycl %s 2>&1 | FileCheck -check-prefix=CHECK-OPTS %s
// CHECK-OPTS: clang{{.*}} "-cc1" {{.*}} "-fsycl" "-fsycl-is-device"
// CHECK-OPTS: clang{{.*}} "-cc1" {{.*}} "-fsycl" "-fsycl-is-host"
| 62.740741
| 110
| 0.619835
|
steffenlarsen
|
5eb6cc9ecbe82e80d5d57e365e50d79f65fe8661
| 2,054
|
cpp
|
C++
|
src/game/snake_game.cpp
|
Hippo/Snake
|
9390c34e86685bf905bad85d09819f0df8b2d7e0
|
[
"MIT"
] | null | null | null |
src/game/snake_game.cpp
|
Hippo/Snake
|
9390c34e86685bf905bad85d09819f0df8b2d7e0
|
[
"MIT"
] | null | null | null |
src/game/snake_game.cpp
|
Hippo/Snake
|
9390c34e86685bf905bad85d09819f0df8b2d7e0
|
[
"MIT"
] | null | null | null |
#include "game/snake_game.hpp"
#include <chrono>
#include <queue>
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
static std::queue<int> s_KeyQueue;
#define MILLIS() std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now().time_since_epoch()).count()
Game::Game() :
m_Window(800, 600, "Snake"),
m_Shader("assets/shader/shader.vert", "assets/shader/shader.frag") {
}
void Game::run() {
float width = static_cast<float>(m_Window.width()) / 10.0f;
float height = static_cast<float>(m_Window.height()) / 10.0f;
glm::vec4 border = glm::vec4(width / -2.0f, height / -2.0f, width / 2.0f, height / 2.0f);
m_Snake.setBorder(border);
m_Snake.spawnApple();
m_Shader.bind();
glm::mat4 projection = glm::ortho(width / -2.0f, width / 2.0f, height / -2.0f, height / 2.0f);
GLuint projectionMatrix = m_Shader.getUniformLocation("projectionMatrix");
glUniformMatrix4fv(projectionMatrix, 1, GL_FALSE, glm::value_ptr(projection));
m_Window.setKeyPressCallback(onKeyPress);
constexpr int delay = 1000 / 15;
long last = MILLIS();
while (!m_Window.shouldClose()) {
long now = MILLIS();
if (now - last >= delay) {
update();
last = now;
}
render();
m_Window.swapBuffers();
Window::pollEvents();
}
}
void Game::update() {
if (!s_KeyQueue.empty()) {
int key = s_KeyQueue.front();
s_KeyQueue.pop();
m_Snake.handleKeyPress(key);
}
m_Snake.update();
}
void Game::render() const {
glClear(GL_COLOR_BUFFER_BIT);
m_Snake.render(m_Shader);
}
void Game::onKeyPress(GLFWwindow*, int key, int, int action, int) {
if (action == GLFW_PRESS) {
switch (key) { //NOLINT
case GLFW_KEY_UP:
case GLFW_KEY_DOWN:
case GLFW_KEY_LEFT:
case GLFW_KEY_RIGHT:
s_KeyQueue.push(key);
break;
}
}
}
| 26
| 140
| 0.614898
|
Hippo
|
5ebb412f4a888654ce1059403fcbf0e730ed7023
| 1,052
|
cpp
|
C++
|
src/game/server/infclass/entities/laser-teleport.cpp
|
srdante/teeworlds-infclassR
|
8b05eae1f23297617da47403cf04bceafdc198ac
|
[
"Zlib"
] | 6
|
2021-02-24T22:15:23.000Z
|
2022-03-23T18:41:58.000Z
|
src/game/server/infclass/entities/laser-teleport.cpp
|
srdante/teeworlds-infclassR
|
8b05eae1f23297617da47403cf04bceafdc198ac
|
[
"Zlib"
] | 75
|
2021-02-02T17:48:50.000Z
|
2022-03-23T18:54:25.000Z
|
src/game/server/infclass/entities/laser-teleport.cpp
|
srdante/teeworlds-infclassR
|
8b05eae1f23297617da47403cf04bceafdc198ac
|
[
"Zlib"
] | 8
|
2021-03-13T15:06:27.000Z
|
2022-03-23T12:09:07.000Z
|
/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */
/* If you are missing that file, acquire a complete release at teeworlds.com. */
#include <game/server/gamecontext.h>
#include "laser-teleport.h"
CLaserTeleport::CLaserTeleport(CGameContext *pGameContext, vec2 StartPos, vec2 EndPos)
: CInfCEntity(pGameContext, CGameWorld::ENTTYPE_LASER_TELEPORT)
{
m_StartPos = StartPos;
m_EndPos = EndPos;
m_LaserFired = false;
GameWorld()->InsertEntity(this);
}
void CLaserTeleport::Tick()
{
if (m_LaserFired)
GameServer()->m_World.DestroyEntity(this);
}
void CLaserTeleport::Snap(int SnappingClient)
{
m_LaserFired = true;
if (Server()->GetClientAntiPing(SnappingClient))
return;
CNetObj_Laser *pObj = static_cast<CNetObj_Laser *>(Server()->SnapNewItem(NETOBJTYPE_LASER, m_ID, sizeof(CNetObj_Laser)));
if(!pObj)
return;
pObj->m_X = (int)m_EndPos.x;
pObj->m_Y = (int)m_EndPos.y;
pObj->m_FromX = (int)m_StartPos.x;
pObj->m_FromY = (int)m_StartPos.y;
pObj->m_StartTick = Server()->Tick();
}
| 27.684211
| 122
| 0.737643
|
srdante
|
5ebf84420dd74f26c0ae3a9a2ebc6a9d46fe8777
| 595
|
cpp
|
C++
|
codeforce6/1029B. Creating the Contest.cpp
|
khaled-farouk/My_problem_solving_solutions
|
46ed6481fc9b424d0714bc717cd0ba050a6638ef
|
[
"MIT"
] | null | null | null |
codeforce6/1029B. Creating the Contest.cpp
|
khaled-farouk/My_problem_solving_solutions
|
46ed6481fc9b424d0714bc717cd0ba050a6638ef
|
[
"MIT"
] | null | null | null |
codeforce6/1029B. Creating the Contest.cpp
|
khaled-farouk/My_problem_solving_solutions
|
46ed6481fc9b424d0714bc717cd0ba050a6638ef
|
[
"MIT"
] | null | null | null |
/*
Idea:
- Using cumulative sum we can determine the maximum
number of consequtive elements that form the answer.
*/
#include <bits/stdc++.h>
using namespace std;
int const N = 2e5 + 1;
int n, a[N];
bool ck[N];
int main() {
scanf("%d", &n);
for(int i = 0; i < n; ++i)
scanf("%d", a + i);
for(int i = 1; i < n; ++i)
ck[i] = a[i] <= 2 * a[i - 1];
int res = 0;
for(int i = 0; i < n; ++i) {
int j = i;
while(ck[j] == 1)
++j;
if(j != i) {
res = max(res, j - i);
i = j;
--i;
}
}
printf("%d\n", res + 1);
return 0;
}
| 14.875
| 58
| 0.457143
|
khaled-farouk
|
5ec73d33048f446fe2e21da885d82b95f5720d80
| 10,076
|
cpp
|
C++
|
BinarySearchTrees-Improved/SearchTree.cpp
|
jogdandsnehal14/BinarySearchTrees-Improved
|
0a1df1bfefdc55241cbc2e22d7e9674ba0d651fc
|
[
"MIT"
] | null | null | null |
BinarySearchTrees-Improved/SearchTree.cpp
|
jogdandsnehal14/BinarySearchTrees-Improved
|
0a1df1bfefdc55241cbc2e22d7e9674ba0d651fc
|
[
"MIT"
] | null | null | null |
BinarySearchTrees-Improved/SearchTree.cpp
|
jogdandsnehal14/BinarySearchTrees-Improved
|
0a1df1bfefdc55241cbc2e22d7e9674ba0d651fc
|
[
"MIT"
] | null | null | null |
//---------------------------------------------------------------------------
// File: SearchTree.cpp
// Author: Snehal Jogdand
// Date: 01/14/2020
// Program 1: Improved binary search trees
//
// DESCRIPTION:
// SearchTree:
// The class file for SearchTree class
// Provides the set of variables and functions to process
// a Binary Search Tree
//---------------------------------------------------------------------------
#include "SearchTree.h"
using namespace std;
/**
The binary search tree default constructor
*/
SearchTree::SearchTree() : root(nullptr)
{
}
/** The copy constructor for binary search tree
@pre None.
@param other The binary search tree to copy from
*/
SearchTree::SearchTree(const SearchTree& other)
{
root = copy(other.root);
}
/** The copy helper for binary search tree
@pre None.
@param other The binary search tree to copy from
*/
Node* SearchTree::copy(const Node* other)
{
if (other == nullptr) return nullptr;
Node* node = createNode(other->item);
node->left = copy(other->left);
node->right = copy(other->right);
node->count = other->count;
return node;
}
/** Checks if the two binary search tree are equal
@pre None.
@param node1 The root of binary search tree 1
@param node2 The root of binary search tree 2
@returns true if the two binary search tree are equal, false otherwise
*/
bool SearchTree::isEqual(const Node* node1, const Node* node2)
{
if (node1 == nullptr && node2 == nullptr) return true;
else if (node1 != nullptr && node2 == nullptr) return false;
else if (node1 == nullptr && node2 != nullptr) return false;
else if (*node1->item == *node2->item && node1->count == node2->count)
return isEqual(node1->left, node2->left)
&& isEqual(node1->right, node2->right);
return false;
}
/** Creates a new node with the given comparable item
@pre None.
@param item The comparable item
@returns The newly created Node object
*/
Node* SearchTree::createNode(Comparable* item)
{
Node* node = new Node;
node->item = item;
node->count = 1;
node->left = nullptr;
node->right = nullptr;
return node;
}
/** Iteratively inserts a Comparable into the tree or increments the count
if it is already in the tree. This method returns false if the
Comparable is found (and, thus, not inserted).
@pre None.
@param item The comparable item
@returns True if the new item is inserted
*/
bool SearchTree::insert(Comparable* item)
{
// empty tree - set the root node
if (root == nullptr)
{
root = createNode(item);
return true;
}
Node* current = root;
Node* parent = nullptr;
// find the position where the node can be inserted
while (current != nullptr)
{
parent = current;
if (*(current->item) > * item)
current = current->left;
else if (*(current->item) < *item)
current = current->right;
else
{
// duplicate node found, just increment the count and return
current->count++;
return false;
}
}
Node* node = createNode(item);
if (*(parent->item) > * item)
parent->left = node;
else if (*(parent->item) < *item)
parent->right = node;
return true;
}
/** Removes one occurrence of a Comparable from the tree. If it is the last
occurrence, remove the node. Return false if the Comparable is not found.
@pre None.
@param item The comparable item
@returns True if item is removed, false otherwise
*/
bool SearchTree::remove(const Comparable& item)
{
return deleteNode(root, item);
}
/** Removes and deallocates all of the data from the tree.
@pre None.
*/
void SearchTree::makeEmpty()
{
clear(root);
delete root;
root = nullptr;
}
/** Finds a Comparable in the tree using a key stored in the parameter.
@pre None.
@param item The comparable item
@returns The comparable item found, nullptr if not found
*/
const Comparable* SearchTree::retrieve(const Comparable& item) const
{
// get the node in the tree
Node* node = search(root, item);
// node found, return the corresponding item
if (node != nullptr) return node->item;
// no node found, return null
return nullptr;
}
/** Returns the height of the node storing the Comparable in the tree.
A leaf has height 0. Return -1 if the Comparable is not found.
@pre None.
@param item The comparable item
@returns The height of the tree
*/
int SearchTree::height(const Comparable& item) const
{
Node* node = search(root, item);
// item not found, return -1
if (node == nullptr) return -1;
return height(node);
}
/** Returns the height of the node storing the Comparable in the tree.
A leaf has height 0. Return -1 if the Comparable is not found.
@pre None.
@param node The root node
@returns The height of the tree
*/
int SearchTree::height(const Node* node) const
{
if (node == nullptr) return 0;
int leftHeight = height(node->left);
int rightHeight = height(node->right);
return 1 + (leftHeight > rightHeight ? leftHeight : rightHeight);
}
/** Searches a Comparable in the tree using the comparable item stored in the parameter.
@pre None.
@param node The root node
@param item The comparable item
@returns The node with comparable item found, nullptr if not found
*/
Node* SearchTree::search(Node* node, const Comparable& item) const
{
if (node == nullptr) return nullptr;
else if (*node->item == item)
return node;
else if (*(node->item) > item)
return search(node->left, item);
else
return search(node->right, item);
}
/** Deletes a Node in the tree which has the the comparable item in the parameter.
@pre None.
@param node The root node
@param item The comparable item
@returns True if deletion succeeds, false otherwise
*/
bool SearchTree::deleteNode(Node*& root, const Comparable& item)
{
if (root == nullptr) return false;
else if (*root->item == item)
{
if (root->count > 1)
root->count--;
else
deleteRoot(root);
return true;
}
else if (*root->item > item)
return deleteNode(root->left, item);
else
return deleteNode(root->right, item);
return false;
}
/** Deletes the root node in the tree
@pre None.
@param node The root node
*/
void SearchTree::deleteRoot(Node*& root)
{
delete root->item;
// leaf node
if (root->left == nullptr && root->right == nullptr)
{
delete root;
root = nullptr;
}
// node with one child
else if (root->left == nullptr || root->right == nullptr)
{
Node* tmp = root;
root = root->left == nullptr ? root->right : root->left;
delete tmp;
}
// node with both children
else
{
// get max from left subtree
Node* parent = root->right;
Node* maxLeft = root->right;
while (maxLeft->left != nullptr)
{
parent = maxLeft;
maxLeft = maxLeft->left;
}
parent->left = maxLeft->right;
// copy max values to the root node
root->item = maxLeft->item;
root->count = maxLeft->count;
delete maxLeft;
}
}
/** Overload assignment operator.
@pre None.
@param other The SearchTree object to copy values from
@returns The SearchTree object
*/
SearchTree SearchTree::operator=(SearchTree const& other)
{
if (&other != this)
{
SearchTree temp(other);
swap(temp.root, root);
}
return *this;
}
/** Overload equality check operator.
@pre None.
@param right The SearchTree object to compare against
@returns True if the two tree are equal
*/
bool SearchTree::operator==(const SearchTree& right)
{
return isEqual(root, right.root);
}
/** Overload not equality check operator.
@pre None.
@param right The SearchTree object to compare against
@returns True if the two tree are not equal
*/
bool SearchTree::operator!=(const SearchTree& right)
{
return !isEqual(root, right.root);
}
/** Overload << operator.
@pre None.
@param output The output stream to print the output
@param searchTree The SearchTree object to output
*/
ostream& operator<<(ostream& output, SearchTree& searchTree)
{
searchTree.inorder(output, searchTree.root);
return output;
}
/** Prints the inorder traversal of the search tree
@pre None.
@param output The output stream to print the output
@param node The root node
*/
void SearchTree::inorder(ostream& output, Node* node)
{
if (node == nullptr) return;
inorder(output, node->left);
output << *node->item << "\t" << node->count << endl;
inorder(output, node->right);
}
/**
* Destroys all the nodes in the given BS Tree in a recursive manner
*/
void SearchTree::clear(Node* node)
{
Node* nodeToDeletePtr = node;
if (node == nullptr) return;
if (node->left == nullptr && node->right == nullptr)
{
// Return node to the system
/*
if (nodeToDeletePtr->item != nullptr)
{
delete nodeToDeletePtr->item;
nodeToDeletePtr->item = nullptr;
}
*/
delete nodeToDeletePtr;
nodeToDeletePtr = nullptr;
return;
}
clear(node->left);
clear(node->right);
nodeToDeletePtr->left = nullptr;
nodeToDeletePtr->right = nullptr;
}
/**
The Search Tree destructor
*/
SearchTree::~SearchTree()
{
clear(root);
delete root;
root = nullptr;
}
| 26.585752
| 89
| 0.597261
|
jogdandsnehal14
|
5eca1173bcd8decc94a75037514d66d74e9ecacd
| 37,582
|
cpp
|
C++
|
src/algos/fmath.cpp
|
rdmenezes/fibernavigator2
|
bbb8bc8ff16790580d5b03fce7e1fad45fae1b91
|
[
"MIT"
] | null | null | null |
src/algos/fmath.cpp
|
rdmenezes/fibernavigator2
|
bbb8bc8ff16790580d5b03fce7e1fad45fae1b91
|
[
"MIT"
] | null | null | null |
src/algos/fmath.cpp
|
rdmenezes/fibernavigator2
|
bbb8bc8ff16790580d5b03fce7e1fad45fae1b91
|
[
"MIT"
] | null | null | null |
/*
* fmath.cpp
*
* Created on: Jul 17, 2012
* @author Ralph Schurade
*/
#include "fmath.h"
#include "math.h"
#include "../thirdparty/newmat10/newmatap.h"
#include "../thirdparty/newmat10/newmatio.h"
#include "../thirdparty/newmat10/newmatrm.h"
#include "../thirdparty/newmat10/precisio.h"
#include <QDebug>
#include <qmath.h>
#include <boost/math/special_functions/spherical_harmonic.hpp>
#include <float.h>
FMath::FMath() {}
FMath::~FMath() {}
ColumnVector FMath::vlog( ColumnVector v )
{
// allocate memory of output object:
ColumnVector tmp( v.Nrows() );
// for each element of the vector:
for ( int i( 1 ); i <= v.Nrows(); ++i )
{
if ( v( i ) <= 0.0 )
tmp( i ) = -1.0e+17;
else
tmp( i ) = log( v( i ) );
}
return tmp;
}
double FMath::legendre_p( int k )
{
double z = 1.0;
double n = 1.0;
for ( int i = 1; i <= k + 1; i += 2 ) z *= i;
for ( int i = 2; i <= k - 2; i += 2 ) n *= i;
if (( k / 2 ) % 2 == 0)
{
return -1.0 / ( 8 * M_PI ) * ( z / n );
}
else
{
return 1.0 / ( 8 * M_PI ) * ( z / n );
}
}
double FMath::boostLegendre_p( int order, int arg1, double arg2 )
{
return boost::math::legendre_p<double>( order, arg1, arg2 );
}
Matrix FMath::sh_base( Matrix g, int maxOrder )
{
//qDebug() << "start calculating sh base";
// allcoate result matrix
unsigned long sh_dirs( ( maxOrder + 2 ) * ( maxOrder + 1 ) / 2 );
Matrix out( g.Nrows(), sh_dirs );
out = 0.0;
// for each direction
for ( int i = 0; i < g.Nrows(); ++i )
{
// transform current direction to polar coordinates
double theta( acos( g( i + 1, 3 ) ) );
double phi( atan2( g( i + 1, 2 ), g( i + 1, 1 ) ) );
// calculate spherical harmonic base
for ( int order = 0, j = 0; order <= maxOrder; order += 2 )
{
for ( int degree( -order ); degree <= order; ++degree, ++j )
{
out( i + 1, j + 1 ) = sh_base_function( order, degree, theta, phi );
}
}
}
//qDebug() << "finished calculating sh base";
return out;
}
double FMath::sh_base_function( int order, int degree, double theta, double phi )
{
using namespace boost::math;
#if 0
double P = legendre_p<double>( order, abs(degree), cos(theta) );
if ( degree > 0 )
{
return P * cos( degree * phi );
}
else if ( degree < 0 )
{
return P * sin( -degree * phi );
}
else
{
return P;
}
#else
if ( degree > 0 )
{
return spherical_harmonic_r( order, abs( degree ), theta, phi );
}
else if ( degree < 0 )
{
return spherical_harmonic_i( order, abs( degree ), theta, phi );
}
else
{
return spherical_harmonic_r( order, 0, theta, phi );
}
#endif
}
SymmetricMatrix FMath::moment_of_inertia( const ColumnVector& values, const QVector<ColumnVector>& points )
{
SymmetricMatrix result( 3 );
result = 0.0;
double sum( 0.0 );
for ( int i = 0; i < points.size(); ++i )
{
double x( points[i]( 1 ) );
double y( points[i]( 2 ) );
double z( points[i]( 3 ) );
double val = fabs( values( i + 1 ) );
result( 1, 1 ) += x * x * val;
result( 1, 2 ) += x * y * val;
result( 1, 3 ) += x * z * val;
result( 2, 2 ) += y * y * val;
result( 2, 3 ) += y * z * val;
result( 3, 3 ) += z * z * val;
sum += val * val;
}
result = result / sum;
return result;
}
double FMath::iprod( const ColumnVector& v1, const ColumnVector& v2 )
{
double result( 0.0 );
if ( v1.Nrows() != v2.Nrows() )
{
throw std::range_error( "Vectors in scalar product need same size!" );
}
for ( int i = 1; i < v1.Nrows() + 1; ++i )
{
result += v1( i ) * v2( i );
}
return result;
}
ColumnVector FMath::cprod( const ColumnVector& v1, const ColumnVector& v2 )
{
ColumnVector result( 3 );
if ( v1.Nrows() != 3 || v2.Nrows() != 3 )
throw std::range_error( "Vectors in cross product both need size 3!" );
result( 1 ) = v1( 2 ) * v2( 3 ) - v1( 3 ) * v2( 2 );
result( 2 ) = v1( 3 ) * v2( 1 ) - v1( 1 ) * v2( 3 );
result( 3 ) = v1( 1 ) * v2( 2 ) - v1( 2 ) * v2( 1 );
result = result / sqrt( FMath::iprod( result, result ) );
return result;
}
void FMath::evd3x3( ColumnVector tensor, QVector<ColumnVector>& vecs, ColumnVector& vals )
{
double i1, i2, i3, v, s, phi, l1, l2, l3;
double ev1_x, ev1_y, ev1_z, ev2_x, ev2_y, ev2_z, ev3_x, ev3_y, ev3_z, vec_norm;
double xx = tensor( 1 );
double xy = tensor( 2 );
double xz = tensor( 3 );
double yy = tensor( 4 );
double yz = tensor( 5 );
double zz = tensor( 6 );
// three invariants of D (dt)
// i1=l1+l2+l3 (trace)
// i2=l1*l2+l1*l3+l2*l3
// i3=l1*l2*l3 (determinante)
i1 = xx + yy + zz;
i2 = xx * yy + xx * zz + yy * zz - ( pow2( xy ) + pow2( xz ) + pow2( yz ) );
i3 = xx * yy * zz + 2. * xy * xz * yz - ( zz * pow2( xy ) + yy * pow2( xz ) + xx * pow2( yz ) );
v = pow2( i1 / 3 ) - i2 / 3;
s = pow3( i1 / 3 ) - i1 * i2 / 6 + i3 / 2;
if ( ( v > 0 ) && ( pow2( s ) < pow3( v ) ) )
phi = acos( s / v * sqrt( 1. / v ) ) / 3;
else
phi = 0;
// eigenvalues
if ( phi != 0 )
{
l1 = i1 / 3 + 2 * sqrt( v ) * cos( phi );
l2 = i1 / 3 - 2 * sqrt( v ) * cos( M_PI / 3. + phi );
l3 = i1 / 3 - 2 * sqrt( v ) * cos( M_PI / 3. - phi );
}
else
l1 = l2 = l3 = 0.0;
// eigenvectors
ev1_x = ( xy * yz - ( yy - l1 ) * xz ) * ( xz * yz - ( zz - l1 ) * xy );
ev1_y = ( xz * yz - ( zz - l1 ) * xy ) * ( xz * xy - ( xx - l1 ) * yz );
ev1_z = ( xy * yz - ( yy - l1 ) * xz ) * ( xz * xy - ( xx - l1 ) * yz );
ev2_x = ( xy * yz - ( yy - l2 ) * xz ) * ( xz * yz - ( zz - l2 ) * xy );
ev2_y = ( xz * yz - ( zz - l2 ) * xy ) * ( xz * xy - ( xx - l2 ) * yz );
ev2_z = ( xy * yz - ( yy - l2 ) * xz ) * ( xz * xy - ( xx - l2 ) * yz );
ev3_x = ( xy * yz - ( yy - l3 ) * xz ) * ( xz * yz - ( zz - l3 ) * xy );
ev3_y = ( xz * yz - ( zz - l3 ) * xy ) * ( xz * xy - ( xx - l3 ) * yz );
ev3_z = ( xy * yz - ( yy - l3 ) * xz ) * ( xz * xy - ( xx - l3 ) * yz );
vec_norm = sqrt( pow2( ev1_x ) + pow2( ev1_y ) + pow2( ev1_z ) );
if ( vec_norm > 0 )
{
ev1_x = ev1_x / vec_norm;
ev1_y = ev1_y / vec_norm;
ev1_z = ev1_z / vec_norm;
}
else
ev1_x = ev1_y = ev1_z = 0.0;
vec_norm = sqrt( pow2( ev2_x ) + pow2( ev2_y ) + pow2( ev2_z ) );
if ( vec_norm > 0 )
{
ev2_x = ev2_x / vec_norm;
ev2_y = ev2_y / vec_norm;
ev2_z = ev2_z / vec_norm;
}
else
ev2_x = ev2_y = ev2_z = 0.0;
vec_norm = sqrt( pow2( ev3_x ) + pow2( ev3_y ) + pow2( ev3_z ) );
if ( vec_norm > 0 )
{
ev3_x = ev3_x / vec_norm;
ev3_y = ev3_y / vec_norm;
ev3_z = ev3_z / vec_norm;
}
else
ev3_x = ev3_y = ev3_z = 0.0;
ColumnVector ev1( 3 );
ColumnVector ev2( 3 );
ColumnVector ev3( 3 );
vals(1) = l1;
vals(2) = l2;
vals(3) = l3;
ev1( 1 ) = ev1_x;
ev1( 2 ) = ev1_y;
ev1( 3 ) = ev1_z;
ev2( 1 ) = ev2_x;
ev2( 2 ) = ev2_y;
ev2( 3 ) = ev2_z;
ev3( 1 ) = ev3_x;
ev3( 2 ) = ev3_y;
ev3( 3 ) = ev1_z;
vecs.clear();
vecs.push_back( ev3 );
vecs.push_back( ev2 );
vecs.push_back( ev1 );
}
///* ***************************************************************************
///* @file math.cpp
///* @fn Vector cart2sphere(
///*
///* const Vector& input )
///*
///* @brief Transforms a cartesian-coordinate vector to spherical coordinates.
///*
///* For further information view: <br>
///* Wikipedia article on cartesian and spherical coordinates.
///*
///* @param Vector: a in cartesian-coordinates
///*
///* @return Vector: representation of a in spherical coordinates,
///* order: r, theta, phi.
///* ***************************************************************************
ColumnVector FMath::cart2sphere( const ColumnVector& input )
{
if ( input.Nrows() != 3 )
throw std::range_error("Can only transform 3D-vectors.");
ColumnVector result( 3 );
result( 1 ) = sqrt( input( 1 ) * input( 1 ) + input( 2 ) * input( 2 ) + input( 3 ) * input( 3 ) );
result( 2 ) = acos( input( 3 ) / result( 1 ) );
result( 3 ) = atan2( input( 2 ), input( 1 ) );
return result;
}
///* ***************************************************************************
///* @file math.cpp
///* @fn Vector sphere2cart(
///*
///* const Vector& input )
///*
///* @brief Transforms a spherical-coordinate vector to cartesian-coordinates.
///*
///* For further information view: <br>
///* Wikipedia article on cartesian and spherical coordinates. <br>
///*
///* @param Vector: a in spherical-coordinates
///*
///* @return Vector: represantation of a in cartesian-coordinates, order: x,y,z.
///* ***************************************************************************
ColumnVector FMath::sphere2cart( const ColumnVector& input )
{
if ( input.Nrows() != 3 )
throw std::range_error( "Can only transform 3D-vectors." );
ColumnVector result( 3 );
result( 1 ) = input( 1 ) * sin( input( 2 ) ) * cos( input( 3 ) );
result( 2 ) = input( 1 ) * sin( input( 2 ) ) * sin( input( 3 ) );
result( 3 ) = input( 1 ) * cos( input( 2 ) );
return result;
}
ColumnVector FMath::SH_opt_max( const ColumnVector& startX, const ColumnVector& coeff )
{
ColumnVector newX( startX );
ColumnVector oldX( 3 );
// set values for computation
const double precision( 10.e-6 );
const double eps( 10.e-4 );
double delta( 1.0 );
int steps( 0 );
while ( delta > precision && steps < 100 )
{
// Update old value
++steps;
oldX = newX;
double SH_old( sh_eval( oldX, coeff ) );
// define the delta steps
ColumnVector dt( oldX );
ColumnVector dp( oldX );
dt( 2 ) += eps;
dp( 3 ) += eps;
// calculate Jacobian
double Jt( ( FMath::sh_eval( dt, coeff ) - SH_old ) );
double Jp( ( FMath::sh_eval( dp, coeff ) - SH_old ) );
// do iteration
newX( 2 ) = oldX( 2 ) + Jt;
newX( 3 ) = oldX( 3 ) + Jp;
delta = fabs( Jt ) + fabs( Jp );
//std::cout<<delta<<" ";
}
return newX;
}
///* ***************************************************************************
///* @file math.cpp
///* @fn double sh_eval(
///*
///* const Vector& position,
///* const Vector& coeff,
///* const unsigned long max_order )
///*
///* @brief Evaluates a spherical harmonic function defined by its coefficients
///* in direction of the position vector.
///*
///* important: this function works in place. <br>
///*
///* For further information view: <br>
///* Cormen, Leiversn, Rivest, and Stein: Introduction to Algorithms <br>
///* Wikipedia article on bubble sort.
///*
///* @param Vector: values the vector which determies the sorting
///* @param Vector: indices to be sorted going along
///*
///* @return TODO
///* ***************************************************************************
double FMath::sh_eval( const ColumnVector& position, const ColumnVector& coeff )
{
const int max_order( ( -3 + static_cast<int>( sqrt( 8 * coeff.Nrows() ) + 1 ) ) / 2 );
const double radius( position( 1 ) );
if ( radius == 0.0 )
{
return 0.0;
}
// for easier readability
const double theta( position( 2 ) );
const double phi( position( 3 ) );
double result( 0 );
for ( int order( 0 ), j( 1 ); order <= max_order; order += 2 )
{
for ( int degree( -order ); degree <= order; degree++, ++j )
{
result += coeff( j ) * FMath::sh_base_function( order, degree, theta, phi );
}
}
return result;
}
// calculate rotation matrix: http://en.wikipedia.org/wiki/Rotation_matrix
Matrix FMath::RotationMatrix( const double angle, const ColumnVector& axis )
{
double s( sin( angle ) );
double c( cos( angle ) );
double d( 1. - c );
Matrix R( 3, 3 );
R( 1, 1 ) = c + axis( 1 ) * axis( 1 ) * d;
R( 1, 2 ) = axis( 1 ) * axis( 2 ) * d - axis( 3 ) * s;
R( 1, 3 ) = axis( 1 ) * axis( 3 ) * d + axis( 2 ) * s;
R( 2, 1 ) = axis( 1 ) * axis( 2 ) * d + axis( 3 ) * s;
R( 2, 2 ) = c + axis( 1 ) * axis( 1 ) * d;
R( 2, 3 ) = axis( 2 ) * axis( 3 ) * d - axis( 1 ) * s;
R( 3, 1 ) = axis( 1 ) * axis( 3 ) * d - axis( 2 ) * s;
R( 3, 2 ) = axis( 2 ) * axis( 3 ) * d + axis( 1 ) * s;
R( 3, 3 ) = c + axis( 3 ) * axis( 3 ) * d;
return R;
}
void FMath::debugColumnVector3( const ColumnVector& v, QString name )
{
if ( v.Nrows() != 3 )
{
qDebug() << name << "error not 3 elements in vector";
}
qDebug() << name << v( 1 ) << v( 2 ) << v( 3 );
}
Matrix FMath::pseudoInverse( const Matrix& A )
{
/*
Matrix U( A.Nrows(), A.Ncols() );
DiagonalMatrix D( A.Ncols() );
Matrix V( A.Ncols(), A.Ncols() );
SVD( A, D, U, V );
return ( V * ( D.t() * D ) * D.t() * U.t() );
*/
return ( ( A.t() * A ).i() * A.t() );
}
void FMath::fitTensors( QVector<ColumnVector>& data, QVector<float>& b0Images, QVector<QVector3D>& bvecs, QVector<float>& bvals, QVector<Matrix>& out )
{
int N = bvecs.size();
Matrix B( N, 6 );
Matrix U( N, 6 );
Matrix V( 6, 6 );
Matrix BI( 6, N );
DiagonalMatrix D( 6 );
double mult_c;
for ( int i = 0; i < N; ++i )
{
mult_c = bvals[i] / (float) ( bvecs[i].x() * bvecs[i].x() + bvecs[i].y() * bvecs[i].y() + bvecs[i].z() * bvecs[i].z() );
B( i + 1, 1 ) = mult_c * bvecs[i].x() * bvecs[i].x();
B( i + 1, 2 ) = 2 * mult_c * bvecs[i].x() * bvecs[i].y();
B( i + 1, 3 ) = 2 * mult_c * bvecs[i].x() * bvecs[i].z();
B( i + 1, 4 ) = mult_c * bvecs[i].y() * bvecs[i].y();
B( i + 1, 5 ) = 2 * mult_c * bvecs[i].y() * bvecs[i].z();
B( i + 1, 6 ) = mult_c * bvecs[i].z() * bvecs[i].z();
}
SVD( B, D, U, V );
for ( int j = 1; j <= 6; ++j )
{
D( j ) = 1. / D( j );
}
BI = V * D * U.t();
double s0 = 0.0;
double si = 0.0;
vector<double> log_s0_si_pixel( N );
out.clear();
out.reserve( data.size() );
Matrix blank( 3, 3 );
blank = 0.0;
for ( int i = 0; i < data.size(); ++i )
{
s0 = b0Images.at( i );
if ( s0 > 0 )
{
// compute log(s0)-log(si)
s0 = log( s0 );
for ( int j = 0; j < N; ++j )
{
si = data.at( i )( j + 1 ); //dti[j*blockSize+i];
if ( si > 0 )
{
si = log( si );
}
else
{
si = 0.0;
}
log_s0_si_pixel[j] = s0 - si;
}
double value;
// compute tensor
ColumnVector t( 6 );
for ( int l = 0; l < 6; l++ )
{
value = 0;
for ( int m = 1; m <= N; ++m )
{
value += BI( l + 1, m ) * log_s0_si_pixel[m - 1];
}
t( l + 1 ) = (float) ( value ); // save the tensor components in a adjacent memory
}
Matrix m( 3, 3 );
m( 1, 1 ) = t( 1 );
m( 1, 2 ) = t( 2 );
m( 1, 3 ) = t( 3 );
m( 2, 1 ) = t( 2 );
m( 2, 2 ) = t( 4 );
m( 2, 3 ) = t( 5 );
m( 3, 1 ) = t( 3 );
m( 3, 2 ) = t( 5 );
m( 3, 3 ) = t( 6 );
out.push_back( m );
} // end if s0 > 0
else
{
out.push_back( blank );
}
}
}
void FMath::fa( QVector<Matrix>& tensors, QVector<float>& faOut )
{
int blockSize = tensors.size();
faOut.resize( blockSize );
QVector<float> trace( blockSize );
float value = 0;
for ( int i = 0; i < blockSize; ++i )
{
value = tensors.at( i )( 1, 1 );
value += tensors.at( i )( 2, 2 );
value += tensors.at( i )( 3, 3 );
trace[i] = value / 3.0;
}
QVector<float> fa( blockSize );
double xx, xy, xz, yy, yz, zz, tr, AA, DD;
for ( int i = 0; i < blockSize; ++i )
{
xx = tensors.at( i )( 1, 1 );
xy = tensors.at( i )( 1, 2 );
xz = tensors.at( i )( 1, 3 );
yy = tensors.at( i )( 2, 2 );
yz = tensors.at( i )( 2, 3 );
zz = tensors.at( i )( 3, 3 );
tr = trace[i];
AA = pow2( xx - tr ) + pow2( yy - tr ) + pow2( zz - tr ) + 2 * pow2( xy ) + 2 * pow2( xz ) + 2 * pow2( yz );
DD = pow2( xx ) + pow2( yy ) + pow2( zz ) + 2 * pow2( xy ) + 2 * pow2( xz ) + 2 * pow2( yz );
if ( DD > 0 )
{
faOut[i] = qMin( 1.0f, (float) ( sqrt( AA ) / sqrt( DD ) * sqrt( 1.5 ) ) );
}
else
{
faOut[i] = 0.0;
}
}
}
float FMath::fa( Matrix tensor )
{
float trace;
float value = 0;
value = tensor( 1, 1 );
value += tensor( 2, 2 );
value += tensor( 3, 3 );
trace = value / 3.0;
float fa;
double xx, xy, xz, yy, yz, zz, tr, AA, DD;
xx = tensor( 1, 1 );
xy = tensor( 1, 2 );
xz = tensor( 1, 3 );
yy = tensor( 2, 2 );
yz = tensor( 2, 3 );
zz = tensor( 3, 3 );
tr = trace;
AA = pow2( xx - tr ) + pow2( yy - tr ) + pow2( zz - tr ) + 2 * pow2( xy ) + 2 * pow2( xz ) + 2 * pow2( yz );
DD = pow2( xx ) + pow2( yy ) + pow2( zz ) + 2 * pow2( xy ) + 2 * pow2( xz ) + 2 * pow2( yz );
if ( DD > 0 )
{
fa = qMin( 1.0f, (float) ( sqrt( AA ) / sqrt( DD ) * sqrt( 1.5 ) ) );
}
else
{
fa = 0.0;
}
return fa;
}
void FMath::evec1( QVector<Matrix>& tensors, QVector<QVector3D>& evec1 )
{
int blockSize = tensors.size();
evec1.resize( blockSize );
double xx, xy, xz, yy, yz, zz;
double i1, i2, i3, v, s, phi, l1, l2, l3;
double vec_norm, ev1_x, ev1_y, ev1_z;
for ( int i = 0; i < blockSize; ++i )
{
xx = tensors.at( i )( 1, 1 );
xy = tensors.at( i )( 1, 2 );
xz = tensors.at( i )( 1, 3 );
yy = tensors.at( i )( 2, 2 );
yz = tensors.at( i )( 2, 3 );
zz = tensors.at( i )( 3, 3 );
// three invariants of D (dt)
// i1=l1+l2+l3 (trace)
// i2=l1*l2+l1*l3+l2*l3
// i3=l1*l2*l3 (determinante)
i1 = xx + yy + zz;
i2 = xx * yy + xx * zz + yy * zz - ( pow2( xy ) + pow2( xz ) + pow2( yz ) );
i3 = xx * yy * zz + 2. * xy * xz * yz - ( zz * pow2( xy ) + yy * pow2( xz ) + xx * pow2( yz ) );
v = pow2( i1 / 3 ) - i2 / 3;
s = pow3( i1 / 3 ) - i1 * i2 / 6 + i3 / 2;
if ( ( v > 0 ) && ( pow2( s ) < pow3( v ) ) )
phi = acos( s / v * sqrt( 1. / v ) ) / 3;
else
phi = 0;
// eigenvalues
if ( phi != 0 )
{
l1 = i1 / 3 + 2 * sqrt( v ) * cos( phi );
l2 = i1 / 3 - 2 * sqrt( v ) * cos( M_PI / 3. + phi );
l3 = i1 / 3 - 2 * sqrt( v ) * cos( M_PI / 3. - phi );
}
else
l1 = l2 = l3 = 0.0;
// eigenvectors
ev1_x = ( xy * yz - ( yy - l1 ) * xz ) * ( xz * yz - ( zz - l1 ) * xy );
ev1_y = ( xz * yz - ( zz - l1 ) * xy ) * ( xz * xy - ( xx - l1 ) * yz );
ev1_z = ( xy * yz - ( yy - l1 ) * xz ) * ( xz * xy - ( xx - l1 ) * yz );
vec_norm = sqrt( pow2( ev1_x ) + pow2( ev1_y ) + pow2( ev1_z ) );
if ( vec_norm > 0 )
{
ev1_x = ev1_x / vec_norm;
ev1_y = ev1_y / vec_norm;
ev1_z = ev1_z / vec_norm;
}
else
ev1_x = ev1_y = ev1_z = 0.0;
evec1[i].setX( ev1_x );
evec1[i].setY( ev1_y );
evec1[i].setZ( ev1_z );
}
}
void FMath::evecs( QVector<Matrix>& tensors, QVector<QVector3D>& evec1, QVector<float>& eval1,
QVector<QVector3D>& evec2, QVector<float>& eval2,
QVector<QVector3D>& evec3, QVector<float>& eval3 )
{
int blockSize = tensors.size();
evec1.resize( blockSize );
evec2.resize( blockSize );
evec3.resize( blockSize );
eval1.resize( blockSize );
eval2.resize( blockSize );
eval3.resize( blockSize );
double xx, xy, xz, yy, yz, zz;
double i1, i2, i3, v, s, phi, l1, l2, l3;
double vec_norm, ev1_x, ev1_y, ev1_z, ev2_x, ev2_y, ev2_z, ev3_x, ev3_y, ev3_z;
for ( int i = 0; i < blockSize; ++i )
{
xx = tensors.at( i )( 1, 1 );
xy = tensors.at( i )( 1, 2 );
xz = tensors.at( i )( 1, 3 );
yy = tensors.at( i )( 2, 2 );
yz = tensors.at( i )( 2, 3 );
zz = tensors.at( i )( 3, 3 );
// three invariants of D (dt)
// i1=l1+l2+l3 (trace)
// i2=l1*l2+l1*l3+l2*l3
// i3=l1*l2*l3 (determinante)
i1 = xx + yy + zz;
i2 = xx * yy + xx * zz + yy * zz - ( pow2( xy ) + pow2( xz ) + pow2( yz ) );
i3 = xx * yy * zz + 2. * xy * xz * yz - ( zz * pow2( xy ) + yy * pow2( xz ) + xx * pow2( yz ) );
v = pow2( i1 / 3 ) - i2 / 3;
s = pow3( i1 / 3 ) - i1 * i2 / 6 + i3 / 2;
if ( ( v > 0 ) && ( pow2( s ) < pow3( v ) ) )
phi = acos( s / v * sqrt( 1. / v ) ) / 3;
else
phi = 0;
// eigenvalues
if ( phi != 0 )
{
l1 = i1 / 3 + 2 * sqrt( v ) * cos( phi );
l2 = i1 / 3 - 2 * sqrt( v ) * cos( M_PI / 3. + phi );
l3 = i1 / 3 - 2 * sqrt( v ) * cos( M_PI / 3. - phi );
}
else
l1 = l2 = l3 = 0.0;
eval1[i] = l1;
eval2[i] = l2;
eval3[i] = l3;
// eigenvectors
ev1_x = ( xy * yz - ( yy - l1 ) * xz ) * ( xz * yz - ( zz - l1 ) * xy );
ev1_y = ( xz * yz - ( zz - l1 ) * xy ) * ( xz * xy - ( xx - l1 ) * yz );
ev1_z = ( xy * yz - ( yy - l1 ) * xz ) * ( xz * xy - ( xx - l1 ) * yz );
ev2_x = ( xy * yz - ( yy - l2 ) * xz ) * ( xz * yz - ( zz - l2 ) * xy );
ev2_y = ( xz * yz - ( zz - l2 ) * xy ) * ( xz * xy - ( xx - l2 ) * yz );
ev2_z = ( xy * yz - ( yy - l2 ) * xz ) * ( xz * xy - ( xx - l2 ) * yz );
ev3_x = ( xy * yz - ( yy - l3 ) * xz ) * ( xz * yz - ( zz - l3 ) * xy );
ev3_y = ( xz * yz - ( zz - l3 ) * xy ) * ( xz * xy - ( xx - l3 ) * yz );
ev3_z = ( xy * yz - ( yy - l3 ) * xz ) * ( xz * xy - ( xx - l3 ) * yz );
vec_norm = sqrt( pow2( ev1_x ) + pow2( ev1_y ) + pow2( ev1_z ) );
if ( vec_norm > 0 )
{
ev1_x = ev1_x / vec_norm;
ev1_y = ev1_y / vec_norm;
ev1_z = ev1_z / vec_norm;
}
else
ev1_x = ev1_y = ev1_z = 0.0;
vec_norm = sqrt( pow2( ev2_x ) + pow2( ev2_y ) + pow2( ev2_z ) );
if ( vec_norm > 0 )
{
ev2_x = ev2_x / vec_norm;
ev2_y = ev2_y / vec_norm;
ev2_z = ev2_z / vec_norm;
}
else
ev2_x = ev2_y = ev2_z = 0.0;
vec_norm = sqrt( pow2( ev3_x ) + pow2( ev3_y ) + pow2( ev3_z ) );
if ( vec_norm > 0 )
{
ev3_x = ev3_x / vec_norm;
ev3_y = ev3_y / vec_norm;
ev3_z = ev3_z / vec_norm;
}
else
ev3_x = ev3_y = ev3_z = 0.0;
evec1[i].setX( ev1_x );
evec1[i].setY( ev1_y );
evec1[i].setZ( ev1_z );
evec2[i].setX( ev2_x );
evec2[i].setY( ev2_y );
evec2[i].setZ( ev2_z );
evec3[i].setX( ev3_x );
evec3[i].setY( ev3_y );
evec3[i].setZ( ev3_z );
}
}
Matrix FMath::expT( Matrix& t )
{
double xx, xy, xz, yy, yz, zz;
double i1, i2, i3, v, s, phi, l1, l2, l3;
double ev1_x, ev1_y, ev1_z, ev2_x, ev2_y, ev2_z, ev3_x, ev3_y, ev3_z, vec_norm;
xx = t( 1, 1 );
xy = t( 1, 2 );
xz = t( 1, 3 );
yy = t( 2, 2 );
yz = t( 2, 3 );
zz = t( 3, 3 );
// three invariants of D (dt)
// i1=l1+l2+l3 (trace)
// i2=l1*l2+l1*l3+l2*l3
// i3=l1*l2*l3 (determinante)
i1 = xx + yy + zz;
i2 = xx * yy + xx * zz + yy * zz - ( FMath::pow2( xy ) + FMath::pow2( xz ) + FMath::pow2( yz ) );
i3 = xx * yy * zz + 2. * xy * xz * yz - ( zz * FMath::pow2( xy ) + yy * FMath::pow2( xz ) + xx * FMath::pow2( yz ) );
v = FMath::pow2( i1 / 3 ) - i2 / 3;
s = FMath::pow3( i1 / 3 ) - i1 * i2 / 6 + i3 / 2;
if ( ( v > 0 ) && ( FMath::pow2( s ) < FMath::pow3( v ) ) )
phi = acos( s / v * sqrt( 1. / v ) ) / 3;
else
phi = 0;
// eigenvalues
if ( phi != 0 )
{
l1 = i1 / 3 + 2 * sqrt( v ) * cos( phi );
l2 = i1 / 3 - 2 * sqrt( v ) * cos( M_PI / 3. + phi );
l3 = i1 / 3 - 2 * sqrt( v ) * cos( M_PI / 3. - phi );
}
else
l1 = l2 = l3 = 0.0;
/*
eval1[i] = l1;
eval2[i] = l2;
eval3[i] = l3;
*/
// eigenvectors
ev1_x = ( xy * yz - ( yy - l1 ) * xz ) * ( xz * yz - ( zz - l1 ) * xy );
ev1_y = ( xz * yz - ( zz - l1 ) * xy ) * ( xz * xy - ( xx - l1 ) * yz );
ev1_z = ( xy * yz - ( yy - l1 ) * xz ) * ( xz * xy - ( xx - l1 ) * yz );
ev2_x = ( xy * yz - ( yy - l2 ) * xz ) * ( xz * yz - ( zz - l2 ) * xy );
ev2_y = ( xz * yz - ( zz - l2 ) * xy ) * ( xz * xy - ( xx - l2 ) * yz );
ev2_z = ( xy * yz - ( yy - l2 ) * xz ) * ( xz * xy - ( xx - l2 ) * yz );
ev3_x = ( xy * yz - ( yy - l3 ) * xz ) * ( xz * yz - ( zz - l3 ) * xy );
ev3_y = ( xz * yz - ( zz - l3 ) * xy ) * ( xz * xy - ( xx - l3 ) * yz );
ev3_z = ( xy * yz - ( yy - l3 ) * xz ) * ( xz * xy - ( xx - l3 ) * yz );
vec_norm = sqrt( FMath::pow2( ev1_x ) + FMath::pow2( ev1_y ) + FMath::pow2( ev1_z ) );
if ( vec_norm > 0 )
{
ev1_x = ev1_x / vec_norm;
ev1_y = ev1_y / vec_norm;
ev1_z = ev1_z / vec_norm;
}
else
ev1_x = ev1_y = ev1_z = 0.0;
vec_norm = sqrt( FMath::pow2( ev2_x ) + FMath::pow2( ev2_y ) + FMath::pow2( ev2_z ) );
if ( vec_norm > 0 )
{
ev2_x = ev2_x / vec_norm;
ev2_y = ev2_y / vec_norm;
ev2_z = ev2_z / vec_norm;
}
else
ev2_x = ev2_y = ev2_z = 0.0;
vec_norm = sqrt( FMath::pow2( ev3_x ) + FMath::pow2( ev3_y ) + FMath::pow2( ev3_z ) );
if ( vec_norm > 0 )
{
ev3_x = ev3_x / vec_norm;
ev3_y = ev3_y / vec_norm;
ev3_z = ev3_z / vec_norm;
}
else
ev3_x = ev3_y = ev3_z = 0.0;
Matrix U( 3, 3 );
DiagonalMatrix D( 3 );
U( 1, 1 ) = ev1_x;
U( 2, 1 ) = ev1_y;
U( 3, 1 ) = ev1_z;
U( 1, 2 ) = ev2_x;
U( 2, 2 ) = ev2_y;
U( 3, 2 ) = ev2_z;
U( 1, 3 ) = ev3_x;
U( 2, 3 ) = ev3_y;
U( 3, 3 ) = ev3_z;
D( 1 ) = exp( l1 );
D( 2 ) = exp( l2 );
D( 3 ) = exp( l3 );
Matrix expM(3,3);
expM = U * D * U.t();
return expM;
}
//void evd3x3_2( ColumnVector tensor, QVector<ColumnVector>& vecs, ColumnVector& vals );
void FMath::evd3x3_2( ColumnVector &d, QVector<ColumnVector>& vec, ColumnVector& val )
{
if ( d.Nrows() != 6 )
throw std::invalid_argument( "Tensor (6-component vector) expected!" );
// calculate the eigenvalues:
val = ColumnVector( 3 );
vec.reserve( 3 );
std::vector<int> index( 3 );
ColumnVector e( 3 );
// Create work variables:
Matrix A( 3, 3 ), Q( 3, 3 );
A( 1, 1 ) = d( 1 );
A( 2, 1 ) = A( 1, 2 ) = d( 2 );
A( 3, 1 ) = A( 1, 3 ) = d( 3 );
A( 2, 2 ) = d( 4 );
A( 3, 2 ) = A( 2, 3 ) = d( 5 );
A( 3, 3 ) = d( 6 );
double m, c1, c0;
// Determine coefficients of characteristic poynomial. We write
// | a d f |
// A = | d* b e |
// | f* e* c |
double de = A( 1, 2 ) * A( 2, 3 ); // d * e
double dd = A( 1, 2 ) * A( 1, 2 ); // d^2
double ee = A( 2, 3 ) * A( 2, 3 ); // e^2
double ff = A( 1, 3 ) * A( 1, 3 ); // f^2
m = A( 1, 1 ) + A( 2, 2 ) + A( 3, 3 );
c1 = ( A( 1, 1 ) * A( 2, 2 ) + A( 1, 1 ) * A( 3, 3 ) + A( 2, 2 ) * A( 3, 3 ) ) // a*b + a*c + b*c - d^2 - e^2 - f^2
- ( dd + ee + ff );
c0 = A( 3, 3 ) * dd + A( 1, 1 ) * ee + A( 2, 2 ) * ff - A( 1, 1 ) * A( 2, 2 ) * A( 3, 3 ) - 2.0 * A( 1, 3 ) * de; // c*d^2 + a*e^2 + b*f^2 - a*b*c - 2*f*d*e)
double p, sqrt_p, q, c, s, phi;
p = m * m - 3.0 * c1;
q = m * ( p - ( 3.0 / 2.0 ) * c1 ) - ( 27.0 / 2.0 ) * c0;
sqrt_p = sqrt( fabs( p ) );
phi = 27.0 * ( 0.25 * c1 * c1 * ( p - c1 ) + c0 * ( q + 27.0 / 4.0 * c0 ) );
phi = ( 1.0 / 3.0 ) * atan2( sqrt( fabs( phi ) ), q );
c = sqrt_p * cos( phi );
s = ( 1.0 / sqrt( 3.0 ) ) * sqrt_p * sin( phi );
e( 2 ) = ( 1.0 / 3.0 ) * ( m - c );
e( 3 ) = e( 2 ) + s;
e( 1 ) = e( 2 ) + c;
e( 2 ) -= s;
if ( e( 1 ) > e( 2 ) )
{
if ( e( 1 ) > e( 3 ) )
{
if ( e( 2 ) > e( 3 ) )
{
index = { 0,1,2};
}
else
{
index = {0,2,1};
}
}
else
{
index = { 2,0,1};
}
}
else
{
if( e(2) > e(3) )
{
if( e(1) > e(3) )
{
index = { 1,0,2};
}
else
{
index = { 1,2,0};
}
}
else
{
index = {2,1,0};
}
}
for ( unsigned long i( 1 ); i < 4; ++i )
val( i ) = e( index[i-1]+1 );
double wmax = ( fabs( val( 1 ) ) > fabs( val( 3 ) ) ) ? val( 1 ) : val( 3 );
double thresh = ( 8.0 * DBL_EPSILON * wmax ) * ( 8.0 * DBL_EPSILON * wmax );
// Prepare calculation of eigenvectors:
double n0tmp = A( 1, 2 ) * A( 1, 2 ) + A( 1, 3 ) * A( 1, 3 );
double n1tmp = A( 1, 2 ) * A( 1, 2 ) + A( 2, 3 ) * A( 2, 3 );
Q( 1, 2 ) = A( 1, 2 ) * A( 2, 3 ) - A( 1, 3 ) * A( 2, 2 );
Q( 2, 2 ) = A( 1, 3 ) * A( 2, 1 ) - A( 2, 3 ) * A( 1, 1 );
Q( 3, 2 ) = A( 1, 2 ) * A( 1, 2 );
// Calculate first eigenvector by the formula
// v(0) = (A - w(0)).e1 x (A - w(0)).e2
A( 1, 1 ) -= val( 1 );
A( 2, 2 ) -= val( 1 );
Q( 1, 1 ) = Q( 1, 2 ) + A( 1, 3 ) * val( 1 );
Q( 2, 1 ) = Q( 2, 2 ) + A( 2, 3 ) * val( 1 );
Q( 3, 1 ) = A( 1, 1 ) * A( 2, 2 ) - Q( 3, 2 );
double norm = Q( 1, 1 ) * Q( 1, 1 ) + Q( 2, 1 ) * Q( 2, 1 ) + Q( 3, 1 ) * Q( 3, 1 );
double n0 = n0tmp + A( 1, 1 ) * A( 1, 1 );
double n1 = n1tmp + A( 2, 2 ) * A( 2, 2 );
double error = n0 * n1;
double t( 0 ), f( 0 );
unsigned long i( 0 ), j( 0 );
if ( n0 <= thresh ) // If the first column is zero, then (1,0,0) is an eigenvector
{
Q( 1, 1 ) = 1.0;
Q( 2, 1 ) = 0.0;
Q( 3, 1 ) = 0.0;
}
else if ( n1 <= thresh ) // If the second column is zero, then (0,1,0) is an eigenvector
{
Q( 1, 1 ) = 0.0;
Q( 2, 1 ) = 1.0;
Q( 3, 1 ) = 0.0;
}
else if ( norm < 64.0 * 64.0 * DBL_EPSILON * DBL_EPSILON * error )
{ // If angle between A(0) and A(1) is too small, don't use
t = A( 1, 2 ) * A( 1, 2 ); // cross product, but calculate v ~ (1, -A0/A1, 0)
f = -A( 1, 1 ) / A( 1, 2 );
if ( A( 2, 2 ) * A( 2, 2 ) > t )
{
t = A( 2, 2 ) * A( 2, 2 );
f = -A( 1, 2 ) / A( 2, 2 );
}
if ( A( 2, 3 ) * A( 2, 3 ) > t )
f = -A( 1, 3 ) / A( 2, 3 );
norm = 1.0 / sqrt( 1 + f * f );
Q( 1, 1 ) = norm;
Q( 2, 1 ) = f * norm;
Q( 3, 1 ) = 0.0;
}
else // This is the standard branch
{
norm = sqrt( 1.0 / norm );
for ( j = 1; j < 4; ++j )
Q( j, 1 ) = Q( j, 1 ) * norm;
}
// Prepare calculation of second eigenvector
t = val( 1 ) - val( 2 );
if ( fabs( t ) > 8.0 * DBL_EPSILON * wmax )
{
// For non-degenerate eigenvalue, calculate second eigenvector by the formula
// v(1) = (A - w(1)).e1 x (A - w(1)).e2
A( 1, 1 ) += t;
A( 2, 2 ) += t;
Q( 1, 2 ) = Q( 1, 2 ) + A( 1, 3 ) * val( 1 );
Q( 2, 2 ) = Q( 2, 2 ) + A( 2, 3 ) * val( 1 );
Q( 3, 2 ) = A( 1, 1 ) * A( 2, 2 ) - Q( 3, 2 );
norm = Q( 1, 2 ) * Q( 1, 2 ) + Q( 2, 2 ) * Q( 2, 2 ) + Q( 3, 2 ) * Q( 3, 2 );
n0 = n0tmp + A( 1, 1 ) * A( 1, 1 );
n1 = n1tmp + A( 2, 2 ) * A( 2, 2 );
error = n0 * n1;
if ( n0 <= thresh ) // If the first column is zero, then (1,0,0) is an eigenvector
{
Q( 1, 2 ) = 1.0;
Q( 2, 2 ) = 0.0;
Q( 3, 2 ) = 0.0;
}
else if ( n1 <= thresh ) // If the second column is zero, then (0,1,0) is an eigenvector
{
Q( 1, 2 ) = 0.0;
Q( 2, 2 ) = 1.0;
Q( 3, 2 ) = 0.0;
}
else if ( norm < 64.0 * DBL_EPSILON * 64.0 * DBL_EPSILON * error )
{ // If angle between A(0) and A(1) is too small, don't use
t = A( 1, 2 ) * A( 1, 2 ); // cross product, but calculate v ~ (1, -A0/A1, 0)
f = -A( 1, 1 ) / A( 1, 2 );
if ( A( 2, 2 ) * A( 2, 2 ) > t )
{
t = A( 2, 2 ) * A( 2, 2 );
f = -A( 1, 2 ) / A( 2, 2 );
}
if ( A( 2, 3 ) * A( 2, 3 ) > t )
f = -A( 1, 3 ) / A( 2, 3 );
norm = 1.0 / sqrt( 1 + f * f );
Q( 1, 2 ) = norm;
Q( 2, 2 ) = f * norm;
Q( 3, 2 ) = 0.0;
}
else
{
norm = sqrt( 1.0 / norm );
for ( j = 1; j < 4; ++j )
Q( j, 2 ) = Q( j, 2 ) * norm;
}
}
else
{
// For degenerate eigenvalue, calculate second eigenvector according to
// v(1) = v(0) x (A - w(1)).e(i)
//
// This would really get to complicated if we could not assume all of A to
// contain meaningful values.
A( 2, 1 ) = A( 1, 2 );
A( 3, 1 ) = A( 1, 3 );
A( 3, 2 ) = A( 2, 3 );
A( 1, 1 ) += val( 1 );
A( 2, 2 ) += val( 1 );
for ( i = 1; i < 4; ++i )
{
A( i, i ) -= val( 2 );
n0 = A( 1, i ) * A( 1, i ) + A( 2, i ) * A( 2, i ) + A( 3, i ) * A( 3, i );
if ( n0 > thresh )
{
Q( 1, 2 ) = Q( 2, 1 ) * A( 3, i ) - Q( 3, 1 ) * A( 2, i );
Q( 2, 2 ) = Q( 3, 1 ) * A( 1, i ) - Q( 1, 1 ) * A( 3, i );
Q( 3, 2 ) = Q( 1, 1 ) * A( 2, i ) - Q( 2, 1 ) * A( 1, i );
norm = Q( 1, 2 ) * Q( 1, 2 ) + Q( 2, 2 ) * Q( 2, 2 ) + Q( 3, 2 ) * Q( 3, 2 );
if ( norm > 256.0 * DBL_EPSILON * 256.0 * DBL_EPSILON * n0 ) // Accept cross product only if the angle between
{ // the two vectors was not too small
norm = sqrt( 1.0 / norm );
for ( j = 1; j < 4; ++j )
Q( j, 2 ) = Q( j, 2 ) * norm;
break;
}
}
}
if ( i == 4 ) // This means that any vector orthogonal to v(0) is an EV.
{
for ( j = 1; j < 4; ++j )
if ( Q( j, 1 ) != 0.0 ) // Find nonzero element of v(0) ...
{ // ... and swap it with the next one
norm = 1.0 / sqrt( Q( j, 1 ) * Q( j, 1 ) + Q( ( j + 2 ) % 3 + 1, 1 ) * Q( ( j + 1 ) % 3 + 1, 1 ) );
Q( j, 2 ) = Q( ( j + 1 ) % 3 + 1, 1 ) * norm;
Q( ( j + 1 ) % 3 + 1, 2 ) = -Q( j, 1 ) * norm;
Q( ( j + 2 ) % 3 + 1, 2 ) = 0.0;
break;
}
}
}
// Calculate third eigenvector according to
// v(2) = v(0) x v(1)
Q( 1, 3 ) = Q( 2, 1 ) * Q( 3, 2 ) - Q( 3, 1 ) * Q( 2, 2 );
Q( 2, 3 ) = Q( 3, 1 ) * Q( 1, 2 ) - Q( 1, 1 ) * Q( 3, 2 );
Q( 3, 3 ) = Q( 1, 1 ) * Q( 2, 2 ) - Q( 2, 1 ) * Q( 1, 2 );
vec.clear();
for ( int ii( 1 ); ii < 4; ++ii )
{
ColumnVector tmp( 3 );
tmp( 1 ) = Q( 1, ii );
tmp( 2 ) = Q( 2, ii );
tmp( 3 ) = Q( 3, ii );
vec.push_back( tmp );
}
}
bool FMath::linePlaneIntersection( QVector3D& contact, QVector3D ray, QVector3D rayOrigin, QVector3D normal, QVector3D coord )
{
// calculate plane
float d = QVector3D::dotProduct( normal, coord );
if ( QVector3D::dotProduct( normal, ray ) == 0 )
{
return false; // avoid divide by zero
}
// Compute the t value for the directed line ray intersecting the plane
float t = ( d - QVector3D::dotProduct( normal, rayOrigin ) ) / QVector3D::dotProduct( normal, ray );
// scale the ray by t
QVector3D newRay = ray * t;
// calc contact point
contact = rayOrigin + newRay;
if ( t >= 0.0f && t <= 1.0f )
{
return true; // line intersects plane
}
return false; // line does not
}
| 30.357027
| 161
| 0.414879
|
rdmenezes
|
5ecb86d81887a82e2049be442d56db498b130b8a
| 2,194
|
cpp
|
C++
|
codes/UVA/10001-19999/uva10641.cpp
|
JeraKrs/ACM
|
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
|
[
"Apache-2.0"
] | null | null | null |
codes/UVA/10001-19999/uva10641.cpp
|
JeraKrs/ACM
|
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
|
[
"Apache-2.0"
] | null | null | null |
codes/UVA/10001-19999/uva10641.cpp
|
JeraKrs/ACM
|
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
|
[
"Apache-2.0"
] | null | null | null |
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
const int N = 105;
const int M = 1005;
const int INF = 0x3f3f3f3f;
const double eps = 1e-6;
const double pi = atan(1.0)*4;
struct state {
int l, r, val;
}s[M];
struct point {
double x, y;
point (double x = 0, double y = 0) { this->x = x; this->y = y;}
point operator - (const point &o) const {return point(x - o.x, y - o.y);}
double det(const point &o) const {return x * o.y - y * o.x;}
}p[N], o;
int n, m, dp[N];
inline double dis(double x, double y) {
return sqrt(x*x+y*y);
}
inline int sign(double x) {return x < -eps ? -1 : x > eps;}
inline double getP(double y, double x) {
if (fabs(x) < eps) {
return y > 0 ? -pi : pi;
}
return atan2(y, x);
}
bool judge (point l, point a, point b) {
return sign((l - a).det(b - a) * (o - a).det(b - a)) < 0;
}
void cat (state& u, double xi, double yi) {
bool flag[N];
memset(flag, false, sizeof(flag));
for (int i = 0; i < n; i++) {
if (judge(point(xi, yi), p[i], p[i+1]))
flag[i] = true;
}
if (flag[0] && flag[n-1]) {
int l = n-1, r = n;
while (flag[l]) u.l = l, l--;
while (flag[r-n]) u.r = r, r++;
} else {
int l = 0, r = n-1;
while (!flag[l]) l++;
u.l = l;
while (!flag[r]) r--;
u.r = r;
}
u.r++;
if (u.r < u.l)
u.r += n;
}
void init () {
o.x = o.y = 0;
for (int i = 0; i < n; i++) {
scanf("%lf%lf", &p[i].x, &p[i].y);
o.x += p[i].x;
o.y += p[i].y;
}
o.x /= n;
o.y /= n;
p[n] = p[0];
double x, y;
int value;
scanf("%d", &m);
for (int i = 0; i < m; i++) {
scanf("%lf%lf%d", &x, &y, &value);
cat(s[i], x, y);
s[i].val = value;
}
}
bool solve () {
int ans = INF;
for (int i = 0; i < n; i++) {
memset(dp, INF, sizeof(dp));
dp[i] = 0;
for (int j = 0; j < n; j++) {
int t = i + j;
for (int x = 0; x < m; x++) {
if (s[x].l > t)
continue;
int ad = min(s[x].r, i+n);
dp[ad] = min(dp[ad], dp[t]+s[x].val);
}
}
ans = min(ans, dp[i+n]);
}
if (ans == INF)
return false;
printf("%d\n", ans);
return true;
}
int main () {
while (scanf("%d", &n) == 1 && n) {
init ();
if (!solve())
printf("Impossible.\n");
}
return 0;
}
| 17.275591
| 74
| 0.494075
|
JeraKrs
|
5eddaa1e4c73618c8bbf3056d1b2a275d5ad9ced
| 1,585
|
cxx
|
C++
|
kernel/mutex.cxx
|
SuperLeaf1995/uDOS
|
9c2236b14ccdc2a4c25ec5e725b8df4525bf8b96
|
[
"Unlicense"
] | 2
|
2022-01-23T00:11:16.000Z
|
2022-01-26T22:18:01.000Z
|
kernel/mutex.cxx
|
SuperLeaf1995/uDOS
|
9c2236b14ccdc2a4c25ec5e725b8df4525bf8b96
|
[
"Unlicense"
] | null | null | null |
kernel/mutex.cxx
|
SuperLeaf1995/uDOS
|
9c2236b14ccdc2a4c25ec5e725b8df4525bf8b96
|
[
"Unlicense"
] | 2
|
2022-02-03T22:04:59.000Z
|
2022-03-26T10:51:25.000Z
|
export module mutex;
export namespace base {
typedef volatile int short atomic_int;
struct mutex {
enum {
UNLOCKED = 0,
LOCKED = 1,
};
mutex(mutex& lhs) = delete;
mutex(const mutex& lhs) = delete;
mutex(mutex&& lhs) = delete;
mutex(const mutex&& lhs) = delete;
inline mutex()
{
// ...
}
inline ~mutex()
{
// ...
}
inline bool try_lock()
{
if(this->_lock == base::mutex::LOCKED) {
return false;
}
this->_lock = base::mutex::LOCKED;
return true;
}
inline void lock()
{
while(!this->try_lock()) {
// Loop until mutex is aquired
}
}
inline void unlock()
{
this->_lock = base::mutex::UNLOCKED;
}
atomic_int _lock = base::mutex::UNLOCKED;
};
struct scoped_mutex {
scoped_mutex() = delete;
scoped_mutex(scoped_mutex& lhs) = delete;
scoped_mutex(const scoped_mutex& lhs) = delete;
scoped_mutex(scoped_mutex&& lhs) = delete;
scoped_mutex(const scoped_mutex&& lhs) = delete;
scoped_mutex(base::mutex& _lock)
: lock{ _lock }
{
this->lock.lock();
}
~scoped_mutex()
{
this->lock.unlock();
}
base::mutex& lock;
};
};
| 22.323944
| 57
| 0.4347
|
SuperLeaf1995
|
5ee7a117d61504477aa81ee3698c1333c6fa8bef
| 563
|
cpp
|
C++
|
2.cpp
|
wuyongfa-genius/Algorithms_in_C-
|
0973fc1e2c01a818056a0f0b3bfac7a62449bc73
|
[
"MIT"
] | 1
|
2021-08-17T05:22:09.000Z
|
2021-08-17T05:22:09.000Z
|
2.cpp
|
wuyongfa-genius/Algorithms_in_C-
|
0973fc1e2c01a818056a0f0b3bfac7a62449bc73
|
[
"MIT"
] | null | null | null |
2.cpp
|
wuyongfa-genius/Algorithms_in_C-
|
0973fc1e2c01a818056a0f0b3bfac7a62449bc73
|
[
"MIT"
] | null | null | null |
#include<iostream>
#include<vector>
using namespace std;
int main(){
vector<vector<double>>in={{0.0400, 0.0800, 0.1200, 0.1600, 0.2000},
{0.2400, 0.2800, 0.3200, 0.3600, 0.4000},
{0.4400, 0.4800, 0.5200, 0.5600, 0.6000},
{0.6400, 0.6800, 0.7200, 0.7600, 0.8000},
{0.8400, 0.8800, 0.9200, 0.9600, 1.0000}};
vector<vector<vector<double>>>conv_weight=
{{{0.1000, 0.1000, 0.1000},
{0.1000, 0.1000, 0.1000},
{0.1000, 0.1000, 0.1000}},
{{0.2000, 0.2000, 0.2000},
{0.2000, 0.2000, 0.2000},
{0.2000, 0.2000, 0.2000}}};
}
| 28.15
| 71
| 0.571936
|
wuyongfa-genius
|
d67927f1561a131ccbc566922fca8e4679197cb9
| 717
|
hpp
|
C++
|
ares/fc/fc.hpp
|
moon-chilled/Ares
|
909fb098c292f8336d0502dc677050312d8b5c81
|
[
"0BSD"
] | 7
|
2020-07-25T11:44:39.000Z
|
2021-01-29T13:21:31.000Z
|
ares/fc/fc.hpp
|
jchw-forks/ares
|
d78298a1e95fd0ce65feabfd4f13b60e31210a7a
|
[
"0BSD"
] | null | null | null |
ares/fc/fc.hpp
|
jchw-forks/ares
|
d78298a1e95fd0ce65feabfd4f13b60e31210a7a
|
[
"0BSD"
] | 1
|
2021-03-22T16:15:30.000Z
|
2021-03-22T16:15:30.000Z
|
#pragma once
//started: 2011-09-05
#include <ares/ares.hpp>
#include <component/processor/mos6502/mos6502.hpp>
#include <component/audio/ym2149/ym2149.hpp>
#include <component/audio/ym2413/ym2413.hpp>
#include <component/eeprom/x24c01/x24c01.hpp>
namespace ares::Famicom {
#include <ares/inline.hpp>
struct Region {
static inline auto NTSCJ() -> bool;
static inline auto NTSCU() -> bool;
static inline auto PAL() -> bool;
};
#include <fc/controller/controller.hpp>
#include <fc/system/system.hpp>
#include <fc/cartridge/cartridge.hpp>
#include <fc/cpu/cpu.hpp>
#include <fc/apu/apu.hpp>
#include <fc/ppu/ppu.hpp>
#include <fc/fds/fds.hpp>
}
#include <fc/interface/interface.hpp>
| 23.9
| 50
| 0.707113
|
moon-chilled
|
d67a4821068d7a35b268da8e5e7661b7c65cd068
| 3,411
|
cpp
|
C++
|
src/hssh/local_topological/training/boosting_feature_selection.cpp
|
anuranbaka/Vulcan
|
56339f77f6cf64b5fda876445a33e72cd15ce028
|
[
"MIT"
] | 3
|
2020-03-05T23:56:14.000Z
|
2021-02-17T19:06:50.000Z
|
src/hssh/local_topological/training/boosting_feature_selection.cpp
|
anuranbaka/Vulcan
|
56339f77f6cf64b5fda876445a33e72cd15ce028
|
[
"MIT"
] | 1
|
2021-03-07T01:23:47.000Z
|
2021-03-07T01:23:47.000Z
|
src/hssh/local_topological/training/boosting_feature_selection.cpp
|
anuranbaka/Vulcan
|
56339f77f6cf64b5fda876445a33e72cd15ce028
|
[
"MIT"
] | 1
|
2021-03-03T07:54:16.000Z
|
2021-03-03T07:54:16.000Z
|
/* Copyright (C) 2010-2019, The Regents of The University of Michigan.
All rights reserved.
This software was developed as part of the The Vulcan project in the Intelligent Robotics Lab
under the direction of Benjamin Kuipers, kuipers@umich.edu. Use of this code is governed by an
MIT-style License that can be found at "https://github.com/h2ssh/Vulcan".
*/
#include "hssh/local_topological/area_detection/labeling/hypothesis_features.h"
#include "utils/boosting.h"
#include <algorithm>
#include <boost/filesystem.hpp>
#include <iostream>
#include <map>
#include <set>
void output_features_for_type(const std::string& type, const std::string& directory);
int main(int argc, char** argv)
{
if (argc < 2) {
std::cout << "Expected command-line: boosting_feature_selection <classifier dir>\n";
return -1;
}
output_features_for_type("path", argv[1]);
output_features_for_type("decision", argv[1]);
output_features_for_type("dest", argv[1]);
return 0;
}
void output_features_for_type(const std::string& type, const std::string& directory)
{
using namespace boost::filesystem;
using namespace vulcan;
using namespace vulcan::hssh;
// Iterate through the directory provided by the first command-line argument and load all classifiers
// containing 'likelihood' and 'ada'
// Create a set of all features used print them out, along with features not used
std::map<int, double> weights;
std::set<int> unusedFeatures;
HypothesisFeatures allFeatures;
for (int n = 0, end = allFeatures.numFeatures(); n < end; ++n) {
unusedFeatures.insert(n);
}
utils::AdaBoostClassifier classifier;
for (auto dirIt = directory_iterator(path(directory)), endIt = directory_iterator(); dirIt != endIt; ++dirIt) {
auto entry = dirIt->path().generic_string();
if ((entry.find("likelihood") != std::string::npos) && (entry.find(type) != std::string::npos)
&& (entry.find("ada") != std::string::npos)) {
if (!classifier.load(entry)) {
std::cerr << "ERROR: Failed to load classifier: " << entry << '\n';
continue;
}
// std::cout << "Loading classifier: " << entry << '\n';
for (auto& stump : classifier) {
if (weights.find(stump.featureIndex()) == weights.end()) {
weights[stump.featureIndex()] = stump.weight();
} else {
weights[stump.featureIndex()] += stump.weight();
}
unusedFeatures.erase(stump.featureIndex());
}
}
}
std::vector<std::pair<int, double>> usedFeatures;
for (auto feature : weights) {
usedFeatures.emplace_back(feature.first, feature.second);
}
std::sort(usedFeatures.begin(), usedFeatures.end(), [](auto lhs, auto rhs) {
return lhs.second > rhs.second;
});
std::cout << type << " features used by AdaBoost:\nIdx:\tName:\n";
for (auto feature : usedFeatures) {
std::cout << feature.first << '\t' << feature.second << '\t' << HypothesisFeatures::featureName(feature.first)
<< '\n';
}
std::cout << "\n\n" << type << " unused features:\nIdx:\tName:\n";
for (int idx : unusedFeatures) {
std::cout << idx << '\t' << HypothesisFeatures::featureName(idx) << '\n';
}
}
| 34.454545
| 118
| 0.61888
|
anuranbaka
|
d67acbf8f7a05b2d9fc364162a06e452d6b8c175
| 6,163
|
cpp
|
C++
|
src/gluon/app/app.cpp
|
cmourglia/gluon-old
|
9c9a55e86cd8878c0e90917882965c87c84969eb
|
[
"MIT"
] | null | null | null |
src/gluon/app/app.cpp
|
cmourglia/gluon-old
|
9c9a55e86cd8878c0e90917882965c87c84969eb
|
[
"MIT"
] | null | null | null |
src/gluon/app/app.cpp
|
cmourglia/gluon-old
|
9c9a55e86cd8878c0e90917882965c87c84969eb
|
[
"MIT"
] | 2
|
2022-02-21T19:09:02.000Z
|
2022-02-21T19:09:51.000Z
|
#include "gluon/app/app.h"
// #include "gluon/core/Utils.h"
#include <SDL.h>
#include <SDL_image.h>
#include <beard/io/io.h>
#include <nanosvg.h>
#include <vector>
#include "gluon/widgets/widget.h"
GluonApp* GluonApp::s_instance = nullptr;
GluonApp* GluonApp::instance() { return s_instance; }
GluonApp::GluonApp(int argc, char** argv)
: m_background_color{0.8f, 0.8f, 0.8f, 1.0f} {
// TODO: Do stuff with argc, argv;
UNUSED(argc);
UNUSED(argv);
ASSERT(s_instance == nullptr, "Multiple initializations");
if (s_instance == nullptr) {
s_instance = this;
// TODO: Extract window infos if set
// TODO: Error handling
SDL_Init(SDL_INIT_VIDEO);
IMG_Init(IMG_INIT_JPG | IMG_INIT_PNG | IMG_INIT_WEBP);
u32 window_flags = SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE;
m_window =
SDL_CreateWindow("Hey !", SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED, 1024, 768, window_flags);
m_surface = SDL_GetWindowSurface(m_window);
}
}
GluonApp::~GluonApp() {
SDL_DestroyWindow(m_window);
m_surface = nullptr;
m_window = nullptr;
IMG_Quit();
SDL_Quit();
}
int GluonApp::Run() {
i64 last_write_time = 0;
// auto ConvertColor = [](const glm::vec4& InColor) -> Color
//{
// return Color{static_cast<u8>(InColor.r * 255),
// static_cast<u8>(InColor.g * 255),
// static_cast<u8>(InColor.b * 255),
// static_cast<u8>(InColor.a * 255)};
// };
Widget* root_widget = nullptr;
bool should_quit = false;
while (!should_quit) {
SDL_Event event;
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_QUIT:
should_quit = true;
break;
}
}
if (should_quit) {
continue;
}
// Check if gluon file update is needed
i64 write_time = -1;
bool draw_needs_update = false;
if (auto file_content = beard::io::read_while_file_if_newer(
"test.gluon", last_write_time, &write_time);
file_content.has_value()) {
delete root_widget;
root_widget = ParseGluonBuffer(file_content.value().c_str());
draw_needs_update = true;
last_write_time = write_time;
}
if (root_widget != nullptr) {
// if (IsWindowResized())
//{
// i32 w = GetScreenWidth();
// i32 h = GetScreenHeight();
// bDrawNeedsUpdate |= root_widget->WindowResized(w, h);
// }
// Vector2 MouseDelta = GetMouseDelta();
// if (Vector2LengthSqr(MouseDelta) > 0.0f)
//{
// Vector2 MousePos = GetMousePosition();
// // bDrawNeedsUpdate |= RootWidget->MouseMoved({MousePos.x,
// // MousePos.y});
//}
if (draw_needs_update) {
m_rectangles.clear();
Widget::Evaluate();
root_widget->BuildRenderInfos(&m_rectangles);
}
}
// ClearBackground(ConvertColor(m_background_color));
// BeginDrawing();
//{
// for (const auto& Rect : m_rectangles)
// {
// Rectangle R = {Rect.Position.x, Rect.Position.y, Rect.Size.x,
// Rect.Size.y};
// f32 SmallSide = beard::min(R.width, R.height);
// f32 Roundness = beard::min(Rect.Radius, SmallSide) / SmallSide;
// if (Rect.bIsImage)
// {
// if (Rect.ImageInfo->bIsVectorial)
// {
// NSVGshape* Shape = Rect.ImageInfo->SvgImage->shapes;
// while (Shape != nullptr)
// {
// if ((Shape->flags & NSVG_FLAGS_VISIBLE) == 0)
// {
// continue;
// }
// Color ShapeColor = *(Color*)&Shape->stroke.color;
// ShapeColor.a = u8(Shape->opacity * 255);
// NSVGpath* Path = Shape->paths;
// while (Path != nullptr)
// {
// for (int i = 0; i < Path->npts - 1; i += 3)
// {
// float* P = &Path->pts[i * 2];
// DrawLineBezierCubic(Vector2{P[0] + R.x, P[1] +
// R.y},
// Vector2{P[6] + R.x, P[7] +
// R.y}, Vector2{P[2] + R.x,
// P[3] + R.y}, Vector2{P[4]
// + R.x, P[5] + R.y},
// Shape->strokeWidth,
// ShapeColor);
// }
// Path = Path->next;
// }
// Shape = Shape->next;
// }
// }
// else
// {
// Texture2D* Texture = Rect.ImageInfo->RasterImage->Texture;
// DrawTexture(*Texture,
// (int)(R.x +
// Rect.ImageInfo->RasterImage->OffsetX),
// (int)(R.y +
// Rect.ImageInfo->RasterImage->OffsetY),
// ConvertColor(Rect.FillColor));
// DrawRectangleRoundedLines(R, 0, 1, 5, BLACK);
// }
// }
// else
// {
// DrawRectangleRounded(R, Roundness, 32,
// ConvertColor(Rect.FillColor));
// if (Rect.BorderWidth > 0.0f)
// {
// DrawRectangleRoundedLines(R, Roundness, 32,
// Rect.BorderWidth, ConvertColor(Rect.BorderColor));
// }
// }
// }
//}
}
return 0;
}
void GluonApp::SetTitle(const char* title) {
SDL_SetWindowTitle(m_window, title);
}
void GluonApp::SetWindowSize(i32 w, i32 h) {
SDL_SetWindowSize(m_window, w, h);
m_width = w;
m_height = h;
}
| 29.917476
| 80
| 0.469252
|
cmourglia
|
d67ce055c71847927406dd2e774cbd3657ab1ae1
| 14,896
|
hpp
|
C++
|
src/hadt_forward_list.hpp
|
gahcep/HeterogeneousList
|
e39a6b3ceff2423e9ed3711bbf9bff5c1e5d145f
|
[
"MIT"
] | null | null | null |
src/hadt_forward_list.hpp
|
gahcep/HeterogeneousList
|
e39a6b3ceff2423e9ed3711bbf9bff5c1e5d145f
|
[
"MIT"
] | null | null | null |
src/hadt_forward_list.hpp
|
gahcep/HeterogeneousList
|
e39a6b3ceff2423e9ed3711bbf9bff5c1e5d145f
|
[
"MIT"
] | null | null | null |
#pragma once
// std::bidirectional_iterator_tag, std::forward_iterator_tag, std::iterator
#include <iterator>
// std::out_of_range, std::length_error
#include <stdexcept>
// std::cout, std::endl, std::ostream
#include <iostream>
// std::move, std::swap, std::ptrdiff_t
#include <utility>
// std::is_same, std::enable_if
#include <type_traits>
// std::initializer_list
#include <initializer_list>
#include "hadt_common.hpp"
namespace hadt {
template <class T>
class forward_list
{
protected:
template <bool IsConst = false>
class list_iterator : public std::iterator <std::forward_iterator_tag, T>
{
public:
typedef T value_type;
// T& / const T&
typedef typename hadt::node_iterator_base<T, IsConst>::iterator_reference reference;
// T* / const T*
typedef typename hadt::node_iterator_base<T, IsConst>::iterator_pointer pointer;
typedef std::ptrdiff_t difference_type;
typedef std::forward_iterator_tag iterator_category;
list_iterator() : ptr_{ nullptr } {};
explicit list_iterator(HNode<T> *ptr) : ptr_(ptr) {};
list_iterator(const list_iterator<IsConst>& it) : ptr_(it.ptr_) {};
list_iterator(const list_iterator<IsConst>&& it) : ptr_(std::move(it.ptr_)) {};
list_iterator<IsConst>& operator=(const list_iterator<IsConst>& it) = delete;
list_iterator<IsConst>& operator=(const list_iterator<IsConst>&& it) = delete;
bool operator==(const list_iterator<IsConst>& other) { return ptr_ == other.ptr_; }
bool operator!=(const list_iterator<IsConst>& other) { return ptr_ != other.ptr_; }
reference operator*() const { return ptr_->data; }
pointer operator->() const { return &(ptr_->data); } // { return &(**this) }
auto get() const -> reference { return &(ptr_->data); }
auto get_node() const -> HNode<T>* { return ptr_; }
auto operator++() -> list_iterator<IsConst>&
{
ptr_ = ptr_->next;
return *this;
}
auto operator++(int) -> list_iterator<IsConst>
{
list_iterator<IsConst> it(*this);
this->operator++();
return it;
}
private:
// HNode<T> * / const HNode<T> *
typename hadt::node_iterator_base<T, IsConst>::iterator_value_type_ptr ptr_;
};
HNode<T> *head, *tail;
HNode<T> *tail_junk;
size_t size_;
public:
typedef std::forward_iterator_tag iterator_category;
typedef list_iterator<false> iterator;
typedef list_iterator<true> const_iterator;
forward_list() :
head{ nullptr },
tail{ nullptr },
tail_junk{ nullptr } {};
virtual ~forward_list() throw() { clear(); }
// copy ctor; move ctor; copy assign; move assign
forward_list(const forward_list& node) = delete;
forward_list& operator=(const forward_list& node) = delete;
forward_list(forward_list&& node) = delete;
forward_list& operator=(forward_list&& node) = delete;
iterator begin() const { return iterator(head); }
iterator end() const { return iterator(tail_junk); }
const_iterator cbegin() const { return const_iterator(head); }
const_iterator cend() const { return const_iterator(tail_junk); }
// Insert at front
auto push_front(const T& data) throw() -> void;
auto move_front(T&& data) throw() -> void;
// Insert at back
auto push_back(const T& data) throw() -> void;
auto move_back(T&& data) throw() -> void;
// Pop(remove) from the list
auto pop_front() throw(std::length_error, std::out_of_range)->T;
auto pop_back() throw(std::length_error, std::out_of_range)->T;
auto pop_at(size_t idx) throw(std::length_error, std::out_of_range)->T;
// Populate the list
auto fill_with(std::initializer_list<T> init_list) -> void;
template <class Iter, class Enable = std::enable_if<
(std::is_same<typename std::iterator_traits<Iter>::iterator_category, std::forward_iterator_tag>::value ||
std::is_same<typename std::iterator_traits<Iter>::iterator_category, std::bidirectional_iterator_tag>::value ||
std::is_same<typename std::iterator_traits<Iter>::iterator_category, std::random_access_iterator_tag>::value) &&
std::is_same<typename std::iterator_traits<Iter>::value_type, T>::value
>::type>
//TODO: CANNOT DEDUCE TEMPLATE ARGUMENT FOR "ENABLE"
/*template <class Iter, class Enable = std::enable_if<
std::is_same<typename std::iterator_traits<Iter>::iterator_category, std::input_iterator_tag>::value &&
std::is_same<typename std::iterator_traits<Iter>::value_type, T>::value
>::type>*/
auto fill_with(const Iter& _begin, const Iter& _end) -> void;
// Append / Prepend the list
auto append_with(std::initializer_list<T> append_list) -> void;
auto prepend_with(std::initializer_list<T> prepend_list) -> void;
template <class Iter, class Enable = std::enable_if<
(std::is_same<typename std::iterator_traits<Iter>::iterator_category, std::forward_iterator_tag>::value ||
std::is_same<typename std::iterator_traits<Iter>::iterator_category, std::bidirectional_iterator_tag>::value ||
std::is_same<typename std::iterator_traits<Iter>::iterator_category, std::random_access_iterator_tag>::value) &&
std::is_same<typename std::iterator_traits<Iter>::value_type, T>::value
>::type>
auto append_with(const Iter& _begin, const Iter& _end) -> void;
template <class Iter, class Enable = std::enable_if<
(std::is_same<typename std::iterator_traits<Iter>::iterator_category, std::forward_iterator_tag>::value ||
std::is_same<typename std::iterator_traits<Iter>::iterator_category, std::bidirectional_iterator_tag>::value ||
std::is_same<typename std::iterator_traits<Iter>::iterator_category, std::random_access_iterator_tag>::value) &&
std::is_same<typename std::iterator_traits<Iter>::value_type, T>::value
>::type>
auto prepend_with(const Iter& _begin, const Iter& _end) -> void;
// Find by value/by index
// O(n)
auto find_first(T value) const -> iterator;
// O(size() - idx)
auto find_nth_to_last(size_t idx) const throw(std::out_of_range) -> iterator;
// Look at item in idx position
auto at(size_t idx) throw(std::out_of_range) -> T;
auto at_front() throw(std::out_of_range) -> T;
auto at_back() throw(std::out_of_range) -> T;
// Reverse the list
virtual auto reverse_inplace() -> void;
auto reverse(forward_list<T>& ref) -> void;
// Service functions
inline auto size() const -> size_t { return size_; };
inline auto empty() -> bool { return begin() == end(); };
// Print list
auto print(std::ostream& ostream = std::cout) const -> std::ostream&;
virtual auto print_reverse(std::ostream& ostream = std::cout) -> std::ostream&;
// Clear container
virtual auto clear() throw() -> void;
private:
// Insert HNode at front or back
virtual auto _push_front(T&& data) throw() -> void;
virtual auto _push_back(T&& data) throw() -> void;
// Remove HNode at given position
virtual auto _remove_at(size_t idx) throw(std::out_of_range) -> T;
// Return HNode at given position
auto _node_at(size_t idx) throw(std::out_of_range) -> HNode<T>*;
};
template <class T>
auto forward_list<T>::_push_front(T&& data) throw() -> void
{
HNode<T> *node = new HNode<T>(std::move(data));
if (nullptr == tail_junk)
tail_junk = new HNode<T>(T{ 55 }, nullptr, nullptr);
// Head
if (nullptr != head)
node->next = head;
head = node;
// Tail
if (nullptr == tail)
{
tail = node;
tail->next = tail_junk;
}
}
template <class T>
auto forward_list<T>::push_front(const T& data) throw() -> void
{
_push_front(std::move(T{ data }));
size_++;
}
template <class T>
auto forward_list<T>::move_front(T&& data) throw() -> void
{
_push_front(std::move(data));
size_++;
}
template <class T>
auto forward_list<T>::_push_back(T&& data) throw() -> void
{
HNode<T> *node = new HNode<T>(std::move(data));
if (tail_junk == nullptr)
tail_junk = new HNode<T>(T{}, nullptr, nullptr);
// Tail
if (nullptr != tail)
tail->next = node;
node->next = tail_junk;
tail = node;
// Head
if (nullptr == head)
head = node;
}
template <class T>
auto forward_list<T>::push_back(const T& data) throw() -> void
{
_push_back(std::move(T{ data }));
size_++;
}
template <class T>
auto forward_list<T>::move_back(T&& data) throw() -> void
{
_push_back(std::move(data));
size_++;
}
template <class T>
auto forward_list<T>::fill_with(std::initializer_list<T> init_list) -> void
{
clear();
append_with(init_list);
}
template <class T>
auto forward_list<T>::append_with(std::initializer_list<T> append_list) -> void
{
for (auto &x : append_list)
push_back(x);
}
template <class T>
auto forward_list<T>::prepend_with(std::initializer_list<T> prepend_list) -> void
{
for (auto &x : prepend_list)
push_front(x);
}
template <class T>
template <class Iter, class Enable = std::enable_if<
(std::is_same<typename std::iterator_traits<Iter>::iterator_category, std::forward_iterator_tag>::value ||
std::is_same<typename std::iterator_traits<Iter>::iterator_category, std::bidirectional_iterator_tag>::value ||
std::is_same<typename std::iterator_traits<Iter>::iterator_category, std::random_access_iterator_tag>::value) &&
std::is_same<typename std::iterator_traits<Iter>::value_type, T>::value
>::type>
auto forward_list<T>::fill_with(const Iter& _begin, const Iter& _end) -> void
{
clear();
append_with(_begin, _end);
}
template <class T>
template <class Iter, class Enable = std::enable_if<
(std::is_same<typename std::iterator_traits<Iter>::iterator_category, std::forward_iterator_tag>::value ||
std::is_same<typename std::iterator_traits<Iter>::iterator_category, std::bidirectional_iterator_tag>::value ||
std::is_same<typename std::iterator_traits<Iter>::iterator_category, std::random_access_iterator_tag>::value) &&
std::is_same<typename std::iterator_traits<Iter>::value_type, T>::value
>::type>
auto forward_list<T>::append_with(const Iter& _begin, const Iter& _end) -> void
{
auto it = _begin;
while (it != _end)
push_back(*it++);
}
template <class T>
template <class Iter, class Enable = std::enable_if<
(std::is_same<typename std::iterator_traits<Iter>::iterator_category, std::forward_iterator_tag>::value ||
std::is_same<typename std::iterator_traits<Iter>::iterator_category, std::bidirectional_iterator_tag>::value ||
std::is_same<typename std::iterator_traits<Iter>::iterator_category, std::random_access_iterator_tag>::value) &&
std::is_same<typename std::iterator_traits<Iter>::value_type, T>::value
>::type>
auto forward_list<T>::prepend_with(const Iter& _begin, const Iter& _end) -> void
{
auto it = _begin;
while (it != _end)
push_front(*it++);
}
template <class T>
auto forward_list<T>::_node_at(size_t idx) throw(std::out_of_range) -> HNode<T>*
{
if (idx >= size())
throw std::out_of_range("_node_at()");
size_t cnt{};
auto it = begin();
while (idx != 0 && it++ != end() && ++cnt != idx);
return it.get_node();
}
template <class T>
auto forward_list<T>::clear() throw() -> void
{
HNode<T> *tmp = head;
HNode<T> *it = head;
try
{
while (tmp != tail_junk)
{
tmp = it->next;
delete it;
it = tmp;
}
if (nullptr != tail_junk)
delete tail_junk;
head = tail = tail_junk = nullptr;
size_ = 0;
}
catch (...)
{
terminate();
}
}
template <class T>
auto forward_list<T>::_remove_at(size_t idx) throw(std::out_of_range) -> T
{
T val{};
if (idx >= size())
throw std::out_of_range("_remove_at()");
// At the front
if (idx == 0)
{
val = head->data;
if (size() == 1)
{
clear();
}
else
{
HNode<T> * tmp = head;
head = head->next;
delete tmp;
size_--;
}
}
// At the back
else if (idx == (size() - 1))
{
val = tail->data;
if (size() == 1)
{
clear();
}
else
{
HNode<T> * tmp = tail;
// O(n)
HNode<T> * prev = _node_at(size() - 2);
prev->next = tail_junk;
tail = prev;
delete tmp;
size_--;
}
}
// In the middle
else
{
HNode<T> * prev = _node_at(idx - 1);
HNode<T> * curr = prev->next;
HNode<T> * next = curr->next;
val = curr->data;
prev->next = next;
delete curr;
size_--;
}
return val;
}
template <class T>
auto forward_list<T>::pop_front() throw(std::length_error, std::out_of_range) -> T
{
if (empty())
throw std::length_error("list is empty");
return _remove_at(0);
}
template <class T>
auto forward_list<T>::pop_back() throw(std::length_error, std::out_of_range) -> T
{
if (empty())
throw std::length_error("list is empty");
return _remove_at(size() - 1);
}
template <class T>
auto forward_list<T>::pop_at(size_t idx) throw(std::length_error, std::out_of_range) -> T
{
if (empty())
throw std::length_error("list is empty");
return _remove_at(idx);
}
template <class T>
auto forward_list<T>::at(size_t idx) throw(std::out_of_range) -> T
{
if (idx >= size())
throw std::out_of_range("at()");
size_t cnt{};
auto it = begin();
while (idx != 0 && it++ != end() && ++cnt != idx);
return *it;
}
template <class T>
auto forward_list<T>::at_front() throw(std::out_of_range) -> T
{
return at(0);
}
template <class T>
auto forward_list<T>::at_back() throw(std::out_of_range) -> T
{
return at(size() - 1);
}
template <class T>
auto forward_list<T>::find_first(T value) const -> iterator
{
auto it = begin();
while (*it != value && ++it != end());
return it;
}
template <class T>
auto forward_list<T>::find_nth_to_last(size_t idx) const throw(std::out_of_range) -> iterator
{
if (idx >= size())
throw std::out_of_range("at()");
auto it_range_end = ++begin();
auto it_range_begin = begin();
while (it_range_end != end())
{
it_range_end++;
if (idx == 0)
it_range_begin++;
else
idx--;
}
return it_range_begin;
}
template <class T>
auto forward_list<T>::print(std::ostream& ostream = std::cout) const -> std::ostream&
{
if (size() == 0) return ostream;
auto it = begin();
ostream << *it++;
while (it != end())
ostream << "," << *it++;
return ostream;
}
template <class T>
auto forward_list<T>::print_reverse(std::ostream& ostream = std::cout) -> std::ostream&
{
if (size() == 0) return ostream;
// Reverse the list
forward_list temp{};
reverse(temp);
temp.print(ostream);
return ostream;
}
template <class T>
auto forward_list<T>::reverse_inplace() -> void
{
if (empty()) return;
HNode<T> * tmp{};
HNode<T> * curr = head;
HNode<T> * succ = curr->next;
curr->next = tail_junk;
tail = curr;
while (succ != tail_junk)
{
tmp = succ->next;
succ->next = curr;
curr = succ;
succ = tmp;
}
head = curr;
}
template <class T>
auto forward_list<T>::reverse(forward_list<T>& ref) -> void
{
ref.clear();
if (empty()) return;
auto it = begin();
while (it != end())
{
ref.push_front(*it);
it++;
}
}
}
| 24.951424
| 115
| 0.66058
|
gahcep
|
d680da63aa1e35fd53bd14dada1f39efa659114b
| 679
|
hpp
|
C++
|
RFGR Extended Camera/pch.hpp
|
Moneyl/RFGR-Extended-Camera
|
a68fa3a531f0be71eea0416bdd390bd1b1fa560e
|
[
"MIT"
] | 4
|
2020-05-25T01:42:56.000Z
|
2021-01-16T19:46:50.000Z
|
RFGR Extended Camera/pch.hpp
|
Moneyl/RFGR-Extended-Camera
|
a68fa3a531f0be71eea0416bdd390bd1b1fa560e
|
[
"MIT"
] | null | null | null |
RFGR Extended Camera/pch.hpp
|
Moneyl/RFGR-Extended-Camera
|
a68fa3a531f0be71eea0416bdd390bd1b1fa560e
|
[
"MIT"
] | null | null | null |
#pragma once
//Keep in mind that precompiled header use is actually disabled for the moment, since I was having issues getting them working properly.
#pragma warning(push, 0) //Disable warnings on included files since I can't / won't modify them to remove warnings.
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <fstream>
#include <string>
#include <ctime>
#include <iostream>
#include <iomanip>
#include <vector>
#include <map>
#include <ctype.h>
#include <tlhelp32.h>
#include <math.h>
#include <Shlwapi.h>
#pragma comment(lib, "Shlwapi.lib")
#include <filesystem>
#include <experimental/filesystem>
#include <nlohmann/json.hpp>
#pragma warning(pop)
| 26.115385
| 136
| 0.748159
|
Moneyl
|
d68582f71f2fc072e07c8f7be7c157197ab3f61b
| 4,887
|
cpp
|
C++
|
plugins/channel-safely/channel-manager.cpp
|
cppcooper/dfhack-cxxrandom
|
550ee4441473ced455ab552ccdbff77cf0978e31
|
[
"CC-BY-3.0"
] | null | null | null |
plugins/channel-safely/channel-manager.cpp
|
cppcooper/dfhack-cxxrandom
|
550ee4441473ced455ab552ccdbff77cf0978e31
|
[
"CC-BY-3.0"
] | null | null | null |
plugins/channel-safely/channel-manager.cpp
|
cppcooper/dfhack-cxxrandom
|
550ee4441473ced455ab552ccdbff77cf0978e31
|
[
"CC-BY-3.0"
] | null | null | null |
#include "channel-manager.h"
#include "inlines.h"
#include <df/block_square_event_designation_priorityst.h>
#include <LuaTools.h>
#include <LuaWrapper.h>
extern color_ostream* debug_out;
extern bool cheat_mode;
// executes dig designations for the specified tile coordinates
static bool dig_now_tile(color_ostream &out, const df::coord &map_pos) {
auto L = Lua::Core::State;
Lua::StackUnwinder top(L);
if (!lua_checkstack(L, 2) ||
!Lua::PushModulePublic(out, L, "plugins.dig-now", "dig_now_tile"))
return false;
Lua::Push(L, map_pos);
if (!Lua::SafeCall(out, L, 1, 1))
return false;
return lua_toboolean(L, -1);
}
// sets mark flags as necessary, for all designations
void ChannelManager::manage_all(color_ostream &out) {
if (debug_out) debug_out->print("manage_all()\n");
// make sure we've got a fort map to analyze
if (World::isFortressMode() && Maps::IsValid()) {
// read map / analyze designations
build_groups();
// iterate the groups we built/updated
for (const auto &group : groups) {
if (debug_out) debug_out->print("foreach group\n");
// iterate the members of each group (designated tiles)
for (auto &designation : group) {
if (debug_out) debug_out->print("foreach tile\n");
// each tile has a position and a block*
const df::coord &tile_pos = designation.first;
df::map_block* block = designation.second;
// check the safety
manage_one(out, group, tile_pos, block);
}
}
if (debug_out) debug_out->print("done managing designations\n");
}
}
// sets mark flags as necessary, for a single designation
void ChannelManager::manage_one(color_ostream &out, const df::coord &map_pos, df::map_block* block, bool manage_neighbours) {
if (!groups.count(map_pos)) {
build_groups();
}
auto iter = groups.find(map_pos);
if (iter != groups.end()) {
manage_one(out, *iter, map_pos, block);
// only if asked, and if map_pos was found mapped to a group do we want to manage neighbours
if (manage_neighbours) {
// todo: how necessary is this?
this->manage_neighbours(out, map_pos);
}
}
}
void ChannelManager::manage_one(color_ostream &out, const Group &group, const df::coord &map_pos, df::map_block* block) {
// we calculate the position inside the block*
df::coord local(map_pos);
local.x = local.x % 16;
local.y = local.y % 16;
df::tile_occupancy &tile_occupancy = block->occupancy[local.x][local.y];
// ensure that we aren't on the top-most layer
if(map_pos.z < mapz - 1) {
// next search for the designation priority
for (df::block_square_event* event : block->block_events) {
if (auto evT = virtual_cast<df::block_square_event_designation_priorityst>(event)) {
// todo: should we revise this check and disregard priority 1/2 or some such?
// we want to let the user keep some designations free of being managed
if (evT->priority[local.x][local.y] < 6000) {
if (debug_out) debug_out->print("if(has_groups_above())\n");
// check that the group has no incomplete groups directly above it
if (!has_groups_above(groups, group)) {
tile_occupancy.bits.dig_marked = false;
block->flags.bits.designated = true;
} else {
tile_occupancy.bits.dig_marked = true;
jobs.erase_and_cancel(map_pos); //cancels job if designation is an open/active job
// is it permanently unsafe? and is it safe to instantly dig the group of tiles
if (cheat_mode && !is_safe_to_dig_down(map_pos) && !is_group_occupied(groups, group)) {
tile_occupancy.bits.dig_marked = false;
dig_now_tile(out, map_pos);
}
}
}
}
}
} else {
// if we are though, it should be totally safe to dig
tile_occupancy.bits.dig_marked = false;
}
}
// sets mark flags as necessary, for a neighbourhood
void ChannelManager::manage_neighbours(color_ostream &out, const df::coord &map_pos) {
// todo: when do we actually need to manage neighbours
df::coord neighbours[8];
get_neighbours(map_pos, neighbours);
// for all the neighbours to our tile
for (auto &position : neighbours) {
// we need to ensure the position is still within the bounds of the map
if (Maps::isValidTilePos(position)) {
manage_one(out, position, Maps::getTileBlock(position));
}
}
}
| 41.415254
| 125
| 0.606916
|
cppcooper
|
d688e280038f673816c624e808145f579b1b157a
| 2,533
|
cpp
|
C++
|
fboss/agent/hw/test/dataplane_tests/HwInDiscardCounterTests.cpp
|
phshaikh/fboss
|
05e6ed1e9d62bf7db45a770886b1761e046c1722
|
[
"BSD-3-Clause"
] | 1
|
2020-03-20T22:47:21.000Z
|
2020-03-20T22:47:21.000Z
|
fboss/agent/hw/test/dataplane_tests/HwInDiscardCounterTests.cpp
|
phshaikh/fboss
|
05e6ed1e9d62bf7db45a770886b1761e046c1722
|
[
"BSD-3-Clause"
] | null | null | null |
fboss/agent/hw/test/dataplane_tests/HwInDiscardCounterTests.cpp
|
phshaikh/fboss
|
05e6ed1e9d62bf7db45a770886b1761e046c1722
|
[
"BSD-3-Clause"
] | null | null | null |
/*
* Copyright (c) 2004-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include "fboss/agent/hw/test/HwLinkStateDependentTest.h"
#include "fboss/agent/Platform.h"
#include "fboss/agent/hw/test/ConfigFactory.h"
#include "fboss/agent/hw/test/HwTestPacketUtils.h"
#include "fboss/agent/test/EcmpSetupHelper.h"
#include "fboss/agent/state/Interface.h"
#include "fboss/agent/state/SwitchState.h"
using folly::IPAddress;
using folly::IPAddressV6;
using std::string;
namespace facebook::fboss {
class HwInDiscardsCounterTest : public HwLinkStateDependentTest {
private:
cfg::SwitchConfig initialConfig() const override {
auto cfg = utility::onePortPerVlanConfig(
getHwSwitch(), masterLogicalPortIds(), cfg::PortLoopbackMode::MAC);
cfg.staticRoutesToNull.resize(2);
cfg.staticRoutesToNull[0].routerID = cfg.staticRoutesToNull[1].routerID = 0;
cfg.staticRoutesToNull[0].prefix = "0.0.0.0/0";
cfg.staticRoutesToNull[1].prefix = "::/0";
return cfg;
}
void pumpTraffic(bool isV6) {
auto vlanId = VlanID(initialConfig().vlanPorts[0].vlanID);
auto intfMac = utility::getInterfaceMac(getProgrammedState(), vlanId);
auto srcIp = IPAddress(isV6 ? "1001::1" : "10.0.0.1");
auto dstIp = IPAddress(isV6 ? "100:100:100::1" : "100.100.100.1");
auto pkt = utility::makeUDPTxPacket(
getHwSwitch(), VlanID(1), intfMac, intfMac, srcIp, dstIp, 10000, 10001);
getHwSwitch()->sendPacketOutOfPortSync(
std::move(pkt), PortID(masterLogicalPortIds()[0]));
}
protected:
void runTest(bool isV6) {
auto setup = [=]() {};
auto verify = [=]() {
auto portStatsBefore = getLatestPortStats(masterLogicalPortIds()[0]);
pumpTraffic(isV6);
auto portStatsAfter = getLatestPortStats(masterLogicalPortIds()[0]);
EXPECT_EQ(
1, portStatsAfter.inDiscardsRaw_ - portStatsBefore.inDiscardsRaw_);
EXPECT_EQ(
1,
portStatsAfter.inDstNullDiscards_ -
portStatsBefore.inDstNullDiscards_);
EXPECT_EQ(0, portStatsAfter.inDiscards_ - portStatsBefore.inDiscards_);
};
verifyAcrossWarmBoots(setup, verify);
}
};
TEST_F(HwInDiscardsCounterTest, v6) {
runTest(true);
}
TEST_F(HwInDiscardsCounterTest, v4) {
runTest(false);
}
} // namespace facebook::fboss
| 32.896104
| 80
| 0.702724
|
phshaikh
|
d6895fc87a464aec04165fc254a2ea15e733e06f
| 2,198
|
cpp
|
C++
|
utility/fsutils.cpp
|
anatolse/beam
|
43c4ce0011598641d9cdeffbfdee66fde0a49730
|
[
"Apache-2.0"
] | 2
|
2020-03-11T09:10:10.000Z
|
2020-04-17T13:45:08.000Z
|
utility/fsutils.cpp
|
anatolse/beam
|
43c4ce0011598641d9cdeffbfdee66fde0a49730
|
[
"Apache-2.0"
] | null | null | null |
utility/fsutils.cpp
|
anatolse/beam
|
43c4ce0011598641d9cdeffbfdee66fde0a49730
|
[
"Apache-2.0"
] | null | null | null |
// Copyright 2018 The Beam Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <boost/filesystem.hpp>
#include "common.h"
#include "logger.h"
#include "fsutils.h"
namespace beam::fsutils
{
bool remove(const boost::filesystem::path& path)
{
boost::system::error_code error;
boost::filesystem::remove(path, error);
if (error) LOG_ERROR() << "fsutils::remove " << path << " error: " << error.message();
return !static_cast<bool>(error);
}
bool remove(const std::string& spath)
{
#ifdef WIN32
boost::filesystem::path path(Utf8toUtf16(spath));
return fsutils::remove(path);
#else
boost::filesystem::path path(spath);
return fsutils::remove(path);
#endif
}
bool isExist(const std::string& path)
{
#ifdef WIN32
return boost::filesystem::exists(Utf8toUtf16(path.c_str()));
#else
return boost::filesystem::exists(path);
#endif
}
bool rename(const boost::filesystem::path& oldPath, const boost::filesystem::path& newPath)
{
boost::system::error_code error;
boost::filesystem::rename(oldPath, newPath, error);
if (error) LOG_ERROR() << "fsutils::rename " << oldPath << " error: " << error.message();
return !static_cast<bool>(error);
}
bool rename(const std::string& oldPath, const std::string& newPath)
{
#ifdef WIN32
boost::filesystem::path fromPath(Utf8toUtf16(oldPath));
boost::filesystem::path toPath(Utf8toUtf16(newPath));
#else
boost::filesystem::path fromPath(oldPath);
boost::filesystem::path toPath(newPath);
#endif
return fsutils::rename(fromPath, toPath);
}
}
| 31.4
| 97
| 0.66424
|
anatolse
|
d6917a653edaec9f829f04d7520029e30008ea9c
| 5,018
|
cpp
|
C++
|
experimental/Pomdog.Experimental/Rendering/Renderer.cpp
|
ValtoForks/pomdog
|
73798ae5f4a4c3b9b1e1e96239187c4b842c93b2
|
[
"MIT"
] | null | null | null |
experimental/Pomdog.Experimental/Rendering/Renderer.cpp
|
ValtoForks/pomdog
|
73798ae5f4a4c3b9b1e1e96239187c4b842c93b2
|
[
"MIT"
] | null | null | null |
experimental/Pomdog.Experimental/Rendering/Renderer.cpp
|
ValtoForks/pomdog
|
73798ae5f4a4c3b9b1e1e96239187c4b842c93b2
|
[
"MIT"
] | null | null | null |
// Copyright (c) 2013-2018 mogemimi. Distributed under the MIT license.
#include "Renderer.hpp"
#include "RenderCommand.hpp"
#include "Pomdog.Experimental/Rendering/RenderCommandProcessor.hpp"
#include "Pomdog/Graphics/GraphicsCommandList.hpp"
#include "Pomdog/Utility/Assert.hpp"
#include <algorithm>
#include <functional>
#include <typeindex>
#include <unordered_map>
#include <utility>
#include <vector>
namespace Pomdog {
namespace {
bool CompareRenderCommands(const RenderCommand& a, const RenderCommand& b)
{
if (a.GetDrawOrder() == b.GetDrawOrder()) {
return a.GetType() < b.GetType();
}
return a.GetDrawOrder() < b.GetDrawOrder();
}
} // unnamed namespace
// MARK: - Renderer::Impl
class Renderer::Impl {
public:
explicit Impl(const std::shared_ptr<GraphicsDevice>& graphicsDevice);
void AddProcessor(
const std::type_index& index,
std::unique_ptr<RenderCommandProcessor> && processor);
void Reset();
std::shared_ptr<GraphicsCommandList> Render();
void SortCommands();
public:
std::unordered_map<
std::type_index, std::unique_ptr<RenderCommandProcessor>> processors;
std::vector<std::reference_wrapper<RenderCommand>> commands;
std::shared_ptr<GraphicsCommandList> commandList;
Matrix4x4 viewMatrix;
Matrix4x4 projectionMatrix;
int drawCallCount;
bool needToSortCommandList;
};
Renderer::Impl::Impl(const std::shared_ptr<GraphicsDevice>& graphicsDevice)
: viewMatrix(Matrix4x4::Identity)
, projectionMatrix(Matrix4x4::Identity)
, drawCallCount(0)
{
POMDOG_ASSERT(graphicsDevice);
commandList = std::make_shared<GraphicsCommandList>(graphicsDevice);
}
void Renderer::Impl::Reset()
{
commands.clear();
}
void Renderer::Impl::AddProcessor(
const std::type_index& index,
std::unique_ptr<RenderCommandProcessor> && processor)
{
POMDOG_ASSERT(processor);
processors.emplace(index, std::move(processor));
}
void Renderer::Impl::SortCommands()
{
if (!needToSortCommandList) {
return;
}
std::sort(std::begin(commands), std::end(commands), CompareRenderCommands);
needToSortCommandList = false;
}
std::shared_ptr<GraphicsCommandList> Renderer::Impl::Render()
{
POMDOG_ASSERT(commandList);
commandList->Reset();
drawCallCount = 0;
const auto viewProjection = viewMatrix * projectionMatrix;
for (auto & iter : processors) {
auto & processor = iter.second;
POMDOG_ASSERT(processor);
processor->Begin(commandList, viewProjection);
}
auto prevIter = std::end(processors);
SortCommands();
for (auto & command : commands) {
auto iter = processors.find(command.get().GetType());
if (prevIter != iter) {
if (prevIter != std::end(processors)) {
auto & processor = prevIter->second;
POMDOG_ASSERT(processor);
processor->FlushBatch();
POMDOG_ASSERT(processor->GetDrawCallCount() >= 0);
drawCallCount += processor->GetDrawCallCount();
}
prevIter = iter;
}
POMDOG_ASSERT(prevIter == iter);
if (iter == std::end(processors)) {
// NOTE: If the command processor is not found, skipping rendering.
continue;
}
POMDOG_ASSERT(iter != std::end(processors));
POMDOG_ASSERT(iter->second);
auto & processor = iter->second;
processor->Draw(commandList, command);
}
if (std::end(processors) != prevIter) {
POMDOG_ASSERT(prevIter->second);
auto & processor = prevIter->second;
processor->End();
POMDOG_ASSERT(processor->GetDrawCallCount() >= 0);
drawCallCount += processor->GetDrawCallCount();
}
return commandList;
}
// MARK: - Renderer
Renderer::Renderer(const std::shared_ptr<GraphicsDevice>& graphicsDevice)
: impl(std::make_unique<Impl>(graphicsDevice))
{}
Renderer::~Renderer() = default;
std::shared_ptr<GraphicsCommandList> Renderer::Render()
{
POMDOG_ASSERT(impl);
return impl->Render();
}
void Renderer::PushCommand(std::reference_wrapper<RenderCommand> && command)
{
POMDOG_ASSERT(impl);
impl->commands.push_back(std::move(command));
impl->needToSortCommandList = true;
}
void Renderer::SetViewMatrix(const Matrix4x4& viewMatrixIn)
{
POMDOG_ASSERT(impl);
impl->viewMatrix = viewMatrixIn;
}
void Renderer::SetProjectionMatrix(const Matrix4x4& projectionMatrixIn)
{
POMDOG_ASSERT(impl);
impl->projectionMatrix = projectionMatrixIn;
}
int Renderer::GetDrawCallCount() const noexcept
{
POMDOG_ASSERT(impl);
return impl->drawCallCount;
}
void Renderer::Reset()
{
POMDOG_ASSERT(impl);
impl->Reset();
}
void Renderer::AddProcessor(std::unique_ptr<RenderCommandProcessor> && processor)
{
POMDOG_ASSERT(impl);
auto typeIndex = processor->GetCommandType();
impl->AddProcessor(std::move(typeIndex), std::move(processor));
}
} // namespace Pomdog
| 25.343434
| 81
| 0.676365
|
ValtoForks
|
d6984666bc2ca846b10e0e34b9da321c7ff06d8b
| 5,269
|
cpp
|
C++
|
ImageProcessing/HarrisCornerDetector.cpp
|
IntelSoftware/MulticoreImageProcessing
|
1dbb65b6ac893d608016f6595523f5b0b9ba342e
|
[
"Intel"
] | 14
|
2018-07-18T08:08:51.000Z
|
2021-12-24T15:32:23.000Z
|
ImageProcessing/HarrisCornerDetector.cpp
|
IntelSoftware/MulticoreImageProcessing
|
1dbb65b6ac893d608016f6595523f5b0b9ba342e
|
[
"Intel"
] | null | null | null |
ImageProcessing/HarrisCornerDetector.cpp
|
IntelSoftware/MulticoreImageProcessing
|
1dbb65b6ac893d608016f6595523f5b0b9ba342e
|
[
"Intel"
] | 7
|
2018-10-10T09:02:05.000Z
|
2021-03-20T05:34:28.000Z
|
#include "stdafx.h"
#include < math.h>
#include <fstream>
#include "omp.h"
using namespace std;
extern "C" __declspec(dllexport) int __stdcall HarrisCornerDetector(BYTE* inBGR, BYTE* outBGR, int stride, int width, int height, KVP* arr, int nArr)
{
// Pack the following structure on one-byte boundaries: smallest possible alignment
// This allows to use the minimal memory space for this type: exact fit - no padding
#pragma pack(push, 1)
struct BGRA {
BYTE B, G, R, A;
};
#pragma pack(pop) // Back to the default packing mode
// Reading the input parameters
bool openMP = parameter("openMP", 1, arr, nArr) == 1 ? true : false; // If openMP should be used for multithreading
const int radius_kernel = parameter("radius", 3, arr, nArr); // Radius of the convolution kernel
int radius_x = width / 2;
int radius_y = height / 2;
// Creating Sobel Kernels
double M[2][3][3] = { { { -1,0,1 },{ -2,0,2 },{ -1,0,1 } },{ { -1,-2,-1 },{ 0,0,0 },{ 1,2,1 } } };
// Creating Gauss Kernel
const int size_kernel = 2 * radius_kernel + 1;
double ** MGauss = new double*[size_kernel];
InitGaussian(MGauss, size_kernel);
// Creating a temporary memory to keep the Grayscale picture
BYTE* tmpBGR = new BYTE[stride*height * 4];
if (tmpBGR) {
// Allocating the needed memory to hold the 3 matrices to store the Sobel results
// Each thread will contain one matrix of each, Ix,Iy,Ixy.
// We are creating as many set of 3 matrices as the number of threads
// the machine can create.
int max_threads = omp_get_max_threads();
double *** Ix = new double**[max_threads];
double *** Iy = new double**[max_threads];
double *** Ixy = new double**[max_threads];
for (int i = 0; i < max_threads; i++) {
Ix[i] = new double*[size_kernel];
Iy[i] = new double*[size_kernel];
Ixy[i] = new double*[size_kernel];
for (int j = 0;j < size_kernel;j++) {
Ix[i][j] = new double[size_kernel];
Iy[i][j] = new double[size_kernel];
Ixy[i][j] = new double[size_kernel];
}
}
// Converting the picture into a grayscale picture
Grayscale(inBGR, tmpBGR, stride, width, height, openMP);
// If the boolean openMP is true, this directive is interpreted so that the following for loop
// will be run on multiple cores.
#pragma omp parallel for if(openMP)
for (int v = 0; v < height; ++v) {
int omp_threads = omp_get_num_threads();
auto offset = v * stride;
BGRA* p = reinterpret_cast<BGRA*>(tmpBGR + offset);
BGRA* q = reinterpret_cast<BGRA*>(outBGR + offset);
for (int u = 0; u < width; ++u) {
int x = u - radius_x;
bool skip = abs(x) > (radius_x - radius_kernel - 1) || abs(radius_y - v) > (radius_y - radius_kernel - 1);
if (skip) {
q[u] = BGRA{ 0,0,0,255 }; // if convolution not possible (near the edges)
}
else {
int id_thread = omp_get_thread_num();
// For each pixel of the kernel, apply the Sobel operator
for (int y = 0, dy = -radius_kernel; y < size_kernel; y++, dy++) {
for (int x = 0, dx = -radius_kernel; x < size_kernel; x++, dx++) {
int indexKernel = u + dx + dy * width;
// Application of the Sobel operator
double T[2];
T[0] = 0;
T[1] = 0;
for (int yS = 0, dy_S = -1; yS < 3; yS++, dy_S++) {
for (int xS = 0, dx_S = 0; xS < 3; xS++, dx_S++) {
int indexSobel = indexKernel + dx_S + dy_S * width;
T[0] += p[indexSobel].G * M[0][yS][xS];
T[1] += p[indexSobel].G * M[1][yS][xS];
}
}
// Save the results Ix2 and Iy2 and IxIy into the 3 matrices
// Considering the thread ID
double Tx(T[0]), Ty(T[1]);
Ix[id_thread][y][x] = Tx * Tx;
Iy[id_thread][y][x] = Ty * Ty;
Ixy[id_thread][y][x] = Tx * Ty;
}
}
// After the Sobel operator is applied to neighbors
// For each matrix, apply the Gaussian kernel
double Tx(0), Ty(0), Txy(0);
for (int j = 0; j < size_kernel; j++) {
for (int i = 0; i < size_kernel; i++) {
Tx += MGauss[i][j] * Ix[id_thread][i][j];
Ty += MGauss[i][j] * Iy[id_thread][i][j];
Txy += MGauss[i][j] * Ixy[id_thread][i][j];
// Reset values for the next time the thread will run
Ix[id_thread][i][j] = 0;
Iy[id_thread][i][j] = 0;
Ixy[id_thread][i][j] = 0;
}
}
// These 3 results are parts of a matrix A such as
// A = | Tx Txy|
// | Txy Ty |
// Calculation of a Score k = det(A) - lambda.trace(A)2
double det = Tx * Ty - (Txy*Txy);
double trace = (Tx + Ty);
double k = det - 0.04*trace*trace;
if (k > 100000000) // Condition for corner detection
q[u] = BGRA{ 255,255,255,255 };
else
q[u] = BGRA{ 0,0,0,255 };
}
}
}
// Delete the allocated memory for the convolution kernel and the temporary grayscale image
for (int i = 0;i < size_kernel;i++) {
delete MGauss[i];
}
delete[] MGauss;
delete tmpBGR;
// And also the allocated matrices for the Sobel operators
for (int i = 0; i < size_kernel; i++) {
for (int j = 0; j < size_kernel; j++) {
delete Ix[i][j];
delete Iy[i][j];
delete Ixy[i][j];
}
delete Ix[i];
delete Iy[i];
delete Ixy[i];
}
delete[] Ix;
delete[] Iy;
delete[] Ixy;
}
return 0;
}
| 34.89404
| 149
| 0.59423
|
IntelSoftware
|
d6998d6612575288ebed1b2c85d3f7c60738ad8a
| 440
|
cc
|
C++
|
cc/template.cc
|
asciphx/CarryLib
|
6f8c54f182525eee47feae412a109e15ead319cc
|
[
"MIT"
] | 1
|
2021-12-02T11:24:08.000Z
|
2021-12-02T11:24:08.000Z
|
cc/template.cc
|
asciphx/CarryLib
|
6f8c54f182525eee47feae412a109e15ead319cc
|
[
"MIT"
] | null | null | null |
cc/template.cc
|
asciphx/CarryLib
|
6f8c54f182525eee47feae412a109e15ead319cc
|
[
"MIT"
] | null | null | null |
#include <string>
#include <iostream>
using namespace std;
template <typename T,int N>
class Array{private:T arr[N];
public:int Size()const{return N;}};
template <typename T> void print(T& x) { std::cout << x << std::endl; }
template <typename T, typename... Args>
void print(T s, Args... a) { std::cout << s; print<Args...>(a...); }
int main(){
Array<int,5>arr;
print(arr.Size());
cin.get();
print(1, " dsag ", 1.5f, " ", 3.14);
}
| 27.5
| 71
| 0.618182
|
asciphx
|
d6a2b7460e047a9fbe289a488e5b9ebf1d56154c
| 5,326
|
hpp
|
C++
|
src/color/lab/convert/LabCH.hpp
|
ehtec/color
|
aa6d8c796303d1f3cfd7361978bfa58eac808b6e
|
[
"Apache-2.0"
] | 120
|
2015-12-31T22:30:14.000Z
|
2022-03-29T15:08:01.000Z
|
src/color/lab/convert/LabCH.hpp
|
ehtec/color
|
aa6d8c796303d1f3cfd7361978bfa58eac808b6e
|
[
"Apache-2.0"
] | 6
|
2016-08-22T02:14:56.000Z
|
2021-11-06T22:39:52.000Z
|
src/color/lab/convert/LabCH.hpp
|
ehtec/color
|
aa6d8c796303d1f3cfd7361978bfa58eac808b6e
|
[
"Apache-2.0"
] | 23
|
2016-02-03T01:56:26.000Z
|
2021-09-28T16:36:27.000Z
|
#ifndef color_lab_convert_LabCH
#define color_lab_convert_LabCH
#include "../../_internal/convert.hpp"
#include "../category.hpp"
#include "../../LabCH/LabCH.hpp"
namespace color
{
namespace _internal
{
template
<
typename lab_tag_name
,typename LabCH_tag_name
>
struct convert
<
::color::category::lab< lab_tag_name, ::color::constant::lab::CIE_entity >
,::color::category::LabCH< LabCH_tag_name >
>
{
public:
typedef ::color::category::lab< lab_tag_name, ::color::constant::lab::CIE_entity > lab_category_type, category_left_type;
typedef ::color::category::LabCH< LabCH_tag_name > LabCH_category_type, category_right_type;
typedef typename ::color::trait::scalar< lab_category_type >::instance_type scalar_type;
typedef ::color::trait::container<category_left_type> container_left_trait_type;
typedef ::color::trait::container<category_right_type> container_right_trait_type;
typedef typename container_left_trait_type::input_type container_left_input_type;
typedef typename container_right_trait_type::model_type container_right_const_input_type;
typedef typename ::color::lab< scalar_type >::category_type LABscalar_category_type;
typedef typename ::color::LabCH< scalar_type >::category_type LabCHscalar_category_type;
typedef ::color::_internal::reformat< category_left_type, LABscalar_category_type > reformatAB_type;
typedef ::color::_internal::reformat< LabCHscalar_category_type, category_right_type > reformatCH_type;
typedef ::color::constant::generic< LABscalar_category_type > generic_costant_type;
enum
{
lightness_left_p = ::color::place::_internal::lightness<category_left_type>::position_enum
};
enum
{
lightness_right_p = ::color::place::_internal::lightness<category_right_type>::position_enum
,chroma_right_p = ::color::place::_internal::chroma<category_right_type>::position_enum
,hue_right_p = ::color::place::_internal::hue<category_right_type>::position_enum
};
static void process
(
container_left_input_type left
,container_right_const_input_type right
)
{
scalar_type l = reformatCH_type::template process< 0, lightness_right_p >( container_right_trait_type::template get<lightness_right_p >( right ) );
scalar_type c = reformatCH_type::template process< 1, chroma_right_p >( container_right_trait_type::template get<chroma_right_p >( right ) );
scalar_type h = reformatCH_type::template process< 2, hue_right_p >( container_right_trait_type::template get<hue_right_p >( right ) );
scalar_type a = c * cos( h * generic_costant_type::deg2rad() );
scalar_type b = c * sin( h * generic_costant_type::deg2rad() );
container_left_trait_type::template set<lightness_left_p>( left, reformatAB_type::template process< lightness_left_p, 0 >( l ) );
container_left_trait_type::template set<1>( left, reformatAB_type::template process< 1, 1 >( a ) );
container_left_trait_type::template set<2>( left, reformatAB_type::template process< 2, 2 >( b ) );
}
};
template
<
typename lab_tag_name
,typename LabCH_tag_name
>
struct convert
<
::color::category::lab< lab_tag_name, ::color::constant::lab::Hunter_entity >
,::color::category::LabCH< LabCH_tag_name >
>
{
public:
typedef ::color::category::lab< lab_tag_name, ::color::constant::lab::Hunter_entity > lab_category_type, category_left_type;
typedef ::color::category::LabCH< LabCH_tag_name > LabCH_category_type, category_right_type;
typedef typename ::color::trait::scalar<category_left_type>::instance_type scalar_type;
typedef ::color::model< lab_category_type > lab_model_type;
typedef ::color::model< LabCH_category_type > LabCH_model_type;
typedef ::color::xyz< scalar_type > xyz_model_type;
typedef ::color::trait::container<category_left_type> container_left_trait_type;
typedef ::color::trait::container<category_right_type> container_right_trait_type;
typedef typename container_left_trait_type::input_type container_left_input_type;
typedef typename container_right_trait_type::model_type container_right_const_input_type;
static void process
(
container_left_input_type left
,container_right_const_input_type right
)
{
//::color::_internal::convert< xyz_model_type::category_type, LabCH_category_type >::process( t0, right );
//::color::_internal::convert< lab_category_type, xyz_model_type::category_type >::process( left, t0 );
left = lab_model_type( xyz_model_type( LabCH_model_type( right ) ) ).container();
}
};
}
}
#endif
| 40.656489
| 160
| 0.647953
|
ehtec
|
d6a76973891f68e41b3c62084dae8a29d8a61ab6
| 8,726
|
cpp
|
C++
|
sound-cloud/audio/Audio.cpp
|
MikaylaFischler/light-art-sound-cloud
|
31fa393d85e42fb0523579b46da5a1680fa63650
|
[
"MIT"
] | null | null | null |
sound-cloud/audio/Audio.cpp
|
MikaylaFischler/light-art-sound-cloud
|
31fa393d85e42fb0523579b46da5a1680fa63650
|
[
"MIT"
] | null | null | null |
sound-cloud/audio/Audio.cpp
|
MikaylaFischler/light-art-sound-cloud
|
31fa393d85e42fb0523579b46da5a1680fa63650
|
[
"MIT"
] | null | null | null |
#include "Audio.hpp"
AudioControlSGTL5000* Audio::board = NULL;
AudioInputI2S* Audio::input = NULL;
AudioAnalyzeFFT1024* Audio::fft_l = NULL;
AudioAnalyzeFFT1024* Audio::fft_r = NULL;
AudioConnection* Audio::fft_l_conn = NULL;
AudioConnection* Audio::fft_r_conn = NULL;
float** Audio::last_fft = NULL;
float*** Audio::fft_history = NULL;
uint8_t Audio::ready = 0;
uint8_t Audio::hysteresis = 0;
uint8_t Audio::h_idx = 0;
/**
* @brief Initialize the audio system
*
*/
void Audio::init(void) {
if (!ready) {
// allocate audio memory
AudioMemory(20);
// create objects for audio processing
board = new AudioControlSGTL5000();
input = new AudioInputI2S();
fft_l = new AudioAnalyzeFFT1024();
fft_r = new AudioAnalyzeFFT1024();
fft_l_conn = new AudioConnection(*input, 0, *fft_l, 0);
fft_r_conn = new AudioConnection(*input, 0, *fft_r, 0);
// last FFT data set
last_fft = (float**) malloc(sizeof(float*) * 2);
last_fft[AUDIO_FFT_LEFT] = (float*) malloc(sizeof(float) * 512);
last_fft[AUDIO_FFT_RIGHT] = (float*) malloc(sizeof(float) * 512);
// historical FFT data set
fft_history = (float***) malloc(sizeof(float**) * 2);
fft_history[AUDIO_FFT_LEFT] = (float**) malloc(sizeof(float*) * 512);
fft_history[AUDIO_FFT_RIGHT] = (float**) malloc(sizeof(float*) * 512);
for (uint16_t i = 0; i < 512; i++) {
fft_history[AUDIO_FFT_LEFT][i] = (float*) calloc(sizeof(float), 3);
fft_history[AUDIO_FFT_RIGHT][i] = (float*) calloc(sizeof(float), 3);
}
disableHysteresis();
// setup board
board->enable();
board->inputSelect(AUDIO_INPUT_LINEIN);
board->volume(0.5);
board->lineInLevel(15);
ready = 1;
}
}
/**
* @brief Enable hysteresis (readings will be average of last 3 values)
*
*/
void Audio::enableHysteresis(void) { hysteresis = 1; }
/**
* @brief Disable hysteresis (readings will no longer be average of last 3 values)
*
*/
void Audio::disableHysteresis(void) { hysteresis = 0; }
/**
* @brief Read the FFT into Audio's buffer, averaging if requested
*
*/
void Audio::__read_fft(void) {
// read data
for (uint16_t i = 0; i < 512; i++) {
fft_history[AUDIO_FFT_LEFT][i][h_idx] = fft_l->read(i);
fft_history[AUDIO_FFT_RIGHT][i][h_idx] = fft_r->read(i);
}
if (hysteresis) {
for (uint16_t i = 0; i < 512; i++) {
for (uint8_t s = 0; s < 3; s++) {
last_fft[AUDIO_FFT_LEFT][i] += fft_history[AUDIO_FFT_LEFT][i][s];
last_fft[AUDIO_FFT_RIGHT][i] += fft_history[AUDIO_FFT_RIGHT][i][s];
}
last_fft[AUDIO_FFT_LEFT][i] /= 3.0;
last_fft[AUDIO_FFT_RIGHT][i] /= 3.0;
}
} else {
for (uint16_t i = 0; i < 512; i++) {
last_fft[AUDIO_FFT_LEFT][i] = fft_history[AUDIO_FFT_LEFT][i][h_idx];
last_fft[AUDIO_FFT_RIGHT][i] = fft_history[AUDIO_FFT_RIGHT][i][h_idx];
}
}
if (++h_idx > 2) { h_idx = 0; }
}
/**
* @brief Get the FFT data if available
*
* @return Pointer to FFT array of last collected data
*/
float** Audio::getFFT(void) {
// check availability
if (!(fft_l->available() && fft_r->available())) {
return last_fft;
}
// read data
__read_fft();
// return the pointer for ease of use
return last_fft;
}
/**
* @brief Get the FFT data if available, if not, returns NULL
*
* @return Pointer to FFT array of the collected data or NULL if not ready
*/
float** Audio::getFFTWhenReady(void) {
// return if unavailable
if (!(fft_l->available() && fft_r->available())) { return NULL; }
// read data
__read_fft();
// return the pointer for ease of use
return last_fft;
}
/**
* @brief Get the FFT data if available, if not, this becomes blocking until data is available
*
* @return Pointer to FFT array of the collected data
*/
float** Audio::getFFTWhenReadyBlocking(void) {
// wait for availability
while (!(fft_l->available() && fft_r->available())) { __asm__ __volatile__ ("nop\n\t"); }
// read data
__read_fft();
// return the pointer for ease of use
return last_fft;
}
/**
* @brief Average together a range of FFT data points
*
* @param side Either AUDIO_FFT_LEFT, AUDIO_FFT_RIGHT, or AUDIO_FFT_COMBINED to combine them (for sepearte data, use one of the averageDualFFTRange functions)
* @param bin_start The start index (inclusive, min 0, max 511)
* @param bin_end The end index (inclusive, min 0, max 511)
* @return float The average of the FFT range
*/
float Audio::averageFFTRange(uint8_t side, uint16_t bin_start, uint16_t bin_end) {
if (bin_start > 511) { bin_start = 511; }
if (bin_end > 511) { bin_end = 511; }
float avg = 0.0;
if (side == AUDIO_FFT_LEFT || side == AUDIO_FFT_RIGHT) {
for (uint8_t i = bin_start; i <= bin_end; i++) {
avg += Audio::last_fft[side][i];
}
avg /= bin_end - bin_start + 1;
} else if (side == AUDIO_FFT_COMBINED) {
for (uint8_t i = bin_start; i <= bin_end; i++) {
avg += Audio::last_fft[AUDIO_FFT_LEFT][i];
avg += Audio::last_fft[AUDIO_FFT_RIGHT][i];
}
avg /= (bin_end - bin_start + 1) * 2.0;
}
return avg;
}
/**
* @brief 'Average' together a range of FFT data points. This sums the data, but divides not by the count, but by the provided division_factor
*
* @param side Either AUDIO_FFT_LEFT, AUDIO_FFT_RIGHT, or AUDIO_FFT_COMBINED to combine them (for sepearte data, use one of the averageDualFFTRange functions)
* @param bin_start The start index (inclusive, min 0, max 511)
* @param bin_end The end index (inclusive, min 0, max 511)
* @param division_factor The factor to divide the sum by (instead of dividing by the number of points summed)
* @return float The scaled 'pseudo-average' of the FFT range
*/
float Audio::averageFFTRangeUnbalanced(uint8_t side, uint16_t bin_start, uint16_t bin_end, float division_factor) {
if (bin_start > 511) { bin_start = 511; }
if (bin_end > 511) { bin_end = 511; }
float avg = 0.0;
if (side == AUDIO_FFT_LEFT || side == AUDIO_FFT_RIGHT) {
for (uint8_t i = bin_start; i <= bin_end; i++) {
avg += Audio::last_fft[side][i];
}
avg /= division_factor;
} else if (side == AUDIO_FFT_COMBINED) {
for (uint8_t i = bin_start; i <= bin_end; i++) {
avg += Audio::last_fft[AUDIO_FFT_LEFT][i];
avg += Audio::last_fft[AUDIO_FFT_RIGHT][i];
}
avg /= (division_factor) * 2.0;
}
return avg;
}
/**
* @brief 'Average' together a range of FFT data points. This sums the data, but divides not by the count, but by the provided division_factor.
* Returns a 2 element array, containing the left then the right data.
*
* @param bin_start The start index (inclusive, min 0, max 511)
* @param bin_end The end index (inclusive, min 0, max 511)
* @param division_factor The factor to divide the sum by (instead of dividing by the number of points summed)
* @return float The scaled 'pseudo-average' of the FFT range [left, right]
*/
float* Audio::averageDualFFTRange(uint16_t bin_start, uint16_t bin_end) {
if (bin_start > 511) { bin_start = 511; }
if (bin_end > 511) { bin_end = 511; }
static float avgs[2] = { 0.0, 0.0 };
for (uint8_t i = bin_start; i <= bin_end; i++) {
avgs[0] += Audio::last_fft[AUDIO_FFT_LEFT][i];
avgs[1] += Audio::last_fft[AUDIO_FFT_RIGHT][i];
}
avgs[0] /= bin_end - bin_start + 1;
avgs[1] /= bin_end - bin_start + 1;
return avgs;
}
/**
* @brief 'Average' together a range of FFT data points. This sums the data, but divides not by the count, but by the provided division_factor.
* Returns a 2 element array, containing the left then the right data.
*
* @param bin_start The start index (inclusive, min 0, max 511)
* @param bin_end The end index (inclusive, min 0, max 511)
* @param division_factor The factor to divide the sum by (instead of dividing by the number of points summed)
* @return float* The scaled 'pseudo-averages' of the FFT range [left, right]
*/
float* Audio::averageDualFFTRangeUnbalanced(uint16_t bin_start, uint16_t bin_end, float division_factor) {
if (bin_start > 511) { bin_start = 511; }
if (bin_end > 511) { bin_end = 511; }
static float avgs[2] = { 0.0, 0.0 };
for (uint8_t i = bin_start; i <= bin_end; i++) {
avgs[0] += Audio::last_fft[AUDIO_FFT_LEFT][i];
avgs[1] += Audio::last_fft[AUDIO_FFT_RIGHT][i];
}
avgs[0] /= division_factor;
avgs[1] /= division_factor;
return avgs;
}
/**
* @brief Convert an FFT float bin to a integer
*
* @param bin The float value
* @param scale_factor Scale the input float by this before conversion
* @param brightness_transform This allows transformation of the output before returning
* @return uint8_t 0 to 255 for LED control
*/
uint8_t Audio::fftToInt(float bin, float scale_factor, uint8_t (*brightness_transform)(uint8_t) = NULL) {
uint8_t converted = (uint8_t) round(bin * scale_factor * 255.0);
if (brightness_transform) { converted = brightness_transform(converted); }
return converted;
}
| 30.833922
| 159
| 0.683475
|
MikaylaFischler
|
d6ad47df68a2fcb10c7d062499ad5b3f4b09c858
| 260
|
cpp
|
C++
|
src/skills/Skill.cpp
|
char-lotl/traveller-cc
|
802d36d7eaa8b027655912c4c71f7ebff2f2059f
|
[
"MIT"
] | null | null | null |
src/skills/Skill.cpp
|
char-lotl/traveller-cc
|
802d36d7eaa8b027655912c4c71f7ebff2f2059f
|
[
"MIT"
] | null | null | null |
src/skills/Skill.cpp
|
char-lotl/traveller-cc
|
802d36d7eaa8b027655912c4c71f7ebff2f2059f
|
[
"MIT"
] | null | null | null |
#include <optional>
#include <string>
#include "Skill.h"
Skill::Skill(skill_type ws) : which_skill(ws) {
// nothing required here
}
Skill::Skill(skill_type ws, std::string subsk) :
which_skill(ws), specialty(subsk) {
// still nothing required here
}
| 20
| 48
| 0.7
|
char-lotl
|
d6ae0786b9df375767708406bdc7c02258a5dfb4
| 925
|
cpp
|
C++
|
src/shader.cpp
|
cbries/tetrisgl
|
a40f22140d05c2cf6116946459a99a0477c1569a
|
[
"MIT"
] | 1
|
2015-02-23T19:06:04.000Z
|
2015-02-23T19:06:04.000Z
|
src/shader.cpp
|
cbries/tetrisgl
|
a40f22140d05c2cf6116946459a99a0477c1569a
|
[
"MIT"
] | null | null | null |
src/shader.cpp
|
cbries/tetrisgl
|
a40f22140d05c2cf6116946459a99a0477c1569a
|
[
"MIT"
] | null | null | null |
/*
* Copyright (c) 2008 Christian Benjamin Ries
* License: MIT
* Website: https://github.com/cbries/tetrisgl
*/
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <iostream>
#include "shader.h"
#include "textfile.h"
GLuint setShaders( std::string filename ) {
GLuint v, f;
char *vs = NULL,*fs = NULL,*fs2 = NULL;
v = glCreateShader(GL_VERTEX_SHADER);
f = glCreateShader(GL_FRAGMENT_SHADER);
std::string vertexStr = filename + ".vert";
std::string fragmentStr = filename + ".frag";
vs = textFileRead( (char*)vertexStr.c_str() );
fs = textFileRead( (char*)fragmentStr.c_str() );
const char * ff = fs;
const char * ff2 = fs2;
const char * vv = vs;
glShaderSource(v, 1, &vv,NULL);
glShaderSource(f, 1, &ff,NULL);
free(vs); free(fs);
glCompileShader(v);
glCompileShader(f);
GLuint p = glCreateProgram();
glAttachShader(p,f);
glAttachShader(p,v);
glLinkProgram(p);
return p;
}
| 18.877551
| 49
| 0.675676
|
cbries
|
d6b42c58ecda30c17d6cfe97615a6f11bcaafbf5
| 25,018
|
cpp
|
C++
|
src/modules/processes/ColorCalibration/BackgroundNeutralizationInterface.cpp
|
fmeschia/pixinsight-class-library
|
11b956e27d6eee3e119a7b1c337d090d7a03f436
|
[
"JasPer-2.0",
"libtiff"
] | null | null | null |
src/modules/processes/ColorCalibration/BackgroundNeutralizationInterface.cpp
|
fmeschia/pixinsight-class-library
|
11b956e27d6eee3e119a7b1c337d090d7a03f436
|
[
"JasPer-2.0",
"libtiff"
] | null | null | null |
src/modules/processes/ColorCalibration/BackgroundNeutralizationInterface.cpp
|
fmeschia/pixinsight-class-library
|
11b956e27d6eee3e119a7b1c337d090d7a03f436
|
[
"JasPer-2.0",
"libtiff"
] | null | null | null |
// ____ ______ __
// / __ \ / ____// /
// / /_/ // / / /
// / ____// /___ / /___ PixInsight Class Library
// /_/ \____//_____/ PCL 2.4.9
// ----------------------------------------------------------------------------
// Standard ColorCalibration Process Module Version 1.5.1
// ----------------------------------------------------------------------------
// BackgroundNeutralizationInterface.cpp - Released 2021-04-09T19:41:48Z
// ----------------------------------------------------------------------------
// This file is part of the standard ColorCalibration PixInsight module.
//
// Copyright (c) 2003-2021 Pleiades Astrophoto S.L. All Rights Reserved.
//
// Redistribution and use in both source and binary forms, with or without
// modification, is permitted provided that the following conditions are met:
//
// 1. All redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. All redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the names "PixInsight" and "Pleiades Astrophoto", nor the names
// of their contributors, may be used to endorse or promote products derived
// from this software without specific prior written permission. For written
// permission, please contact info@pixinsight.com.
//
// 4. All products derived from this software, in any form whatsoever, must
// reproduce the following acknowledgment in the end-user documentation
// and/or other materials provided with the product:
//
// "This product is based on software from the PixInsight project, developed
// by Pleiades Astrophoto and its contributors (https://pixinsight.com/)."
//
// Alternatively, if that is where third-party acknowledgments normally
// appear, this acknowledgment must be reproduced in the product itself.
//
// THIS SOFTWARE IS PROVIDED BY PLEIADES ASTROPHOTO AND ITS CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL PLEIADES ASTROPHOTO OR ITS
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, BUSINESS
// INTERRUPTION; PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; AND LOSS OF USE,
// DATA OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
// ----------------------------------------------------------------------------
#include "BackgroundNeutralizationInterface.h"
#include "BackgroundNeutralizationProcess.h"
#include "BackgroundNeutralizationParameters.h"
#include <pcl/ErrorHandler.h>
#include <pcl/PreviewSelectionDialog.h>
#include <pcl/ViewSelectionDialog.h>
namespace pcl
{
// ----------------------------------------------------------------------------
BackgroundNeutralizationInterface* TheBackgroundNeutralizationInterface = nullptr;
// ----------------------------------------------------------------------------
BackgroundNeutralizationInterface::BackgroundNeutralizationInterface()
: instance( TheBackgroundNeutralizationProcess )
{
TheBackgroundNeutralizationInterface = this;
}
// ----------------------------------------------------------------------------
BackgroundNeutralizationInterface::~BackgroundNeutralizationInterface()
{
if ( GUI != nullptr )
delete GUI, GUI = nullptr;
}
// ----------------------------------------------------------------------------
IsoString BackgroundNeutralizationInterface::Id() const
{
return "BackgroundNeutralization";
}
// ----------------------------------------------------------------------------
MetaProcess* BackgroundNeutralizationInterface::Process() const
{
return TheBackgroundNeutralizationProcess;
}
// ----------------------------------------------------------------------------
String BackgroundNeutralizationInterface::IconImageSVGFile() const
{
return "@module_icons_dir/BackgroundNeutralization.svg";
}
// ----------------------------------------------------------------------------
InterfaceFeatures BackgroundNeutralizationInterface::Features() const
{
return InterfaceFeature::Default;
}
// ----------------------------------------------------------------------------
void BackgroundNeutralizationInterface::ApplyInstance() const
{
instance.LaunchOnCurrentView();
}
// ----------------------------------------------------------------------------
void BackgroundNeutralizationInterface::ResetInstance()
{
BackgroundNeutralizationInstance defaultInstance( TheBackgroundNeutralizationProcess );
ImportProcess( defaultInstance );
}
// ----------------------------------------------------------------------------
bool BackgroundNeutralizationInterface::Launch( const MetaProcess& P, const ProcessImplementation*, bool& dynamic, unsigned& /*flags*/ )
{
if ( GUI == nullptr )
{
GUI = new GUIData( *this );
SetWindowTitle( "BackgroundNeutralization" );
UpdateControls();
}
dynamic = false;
return &P == TheBackgroundNeutralizationProcess;
}
// ----------------------------------------------------------------------------
ProcessImplementation* BackgroundNeutralizationInterface::NewProcess() const
{
return new BackgroundNeutralizationInstance( instance );
}
// ----------------------------------------------------------------------------
bool BackgroundNeutralizationInterface::ValidateProcess( const ProcessImplementation& p, String& whyNot ) const
{
if ( dynamic_cast<const BackgroundNeutralizationInstance*>( &p ) != nullptr )
return true;
whyNot = "Not a BackgroundNeutralization instance.";
return false;
}
// ----------------------------------------------------------------------------
bool BackgroundNeutralizationInterface::RequiresInstanceValidation() const
{
return true;
}
// ----------------------------------------------------------------------------
bool BackgroundNeutralizationInterface::ImportProcess( const ProcessImplementation& p )
{
instance.Assign( p );
UpdateControls();
return true;
}
// ----------------------------------------------------------------------------
#define TARGET_IMAGE String( "<target image>" )
#define REFERENCE_ID( x ) (x.IsEmpty() ? TARGET_IMAGE : x)
#define BACKGROUND_REFERENCE_ID REFERENCE_ID( instance.backgroundReferenceViewId )
void BackgroundNeutralizationInterface::UpdateControls()
{
GUI->BackgroundReferenceView_Edit.SetText( BACKGROUND_REFERENCE_ID );
GUI->BackgroundLow_NumericControl.SetValue( instance.backgroundLow );
GUI->BackgroundHigh_NumericControl.SetValue( instance.backgroundHigh );
GUI->Mode_ComboBox.SetCurrentItem( instance.mode );
GUI->TargetBackground_NumericControl.Enable( instance.mode == BNMode::TargetBackground );
GUI->TargetBackground_NumericControl.SetValue( instance.targetBackground );
GUI->ROI_GroupBox.SetChecked( instance.useROI );
GUI->ROIX0_SpinBox.SetValue( instance.roi.x0 );
GUI->ROIY0_SpinBox.SetValue( instance.roi.y0 );
GUI->ROIWidth_SpinBox.SetValue( instance.roi.Width() );
GUI->ROIHeight_SpinBox.SetValue( instance.roi.Height() );
}
// ----------------------------------------------------------------------------
void BackgroundNeutralizationInterface::__GetFocus( Control& sender )
{
Edit* e = dynamic_cast<Edit*>( &sender );
if ( e != nullptr )
if ( e->Text() == TARGET_IMAGE )
e->Clear();
}
// ----------------------------------------------------------------------------
void BackgroundNeutralizationInterface::__EditCompleted( Edit& sender )
{
if ( sender == GUI->BackgroundReferenceView_Edit )
{
try
{
String id = sender.Text().Trimmed();
if ( id == TARGET_IMAGE )
id.Clear();
if ( !id.IsEmpty() )
if ( !View::IsValidViewId( id ) )
throw Error( "Invalid view identifier: " + id );
instance.backgroundReferenceViewId = id;
sender.SetText( BACKGROUND_REFERENCE_ID );
}
catch ( ... )
{
sender.SetText( BACKGROUND_REFERENCE_ID );
try
{
throw;
}
ERROR_HANDLER
sender.SelectAll();
sender.Focus();
}
}
}
// ----------------------------------------------------------------------------
void BackgroundNeutralizationInterface::__EditValueUpdated( NumericEdit& sender, double value )
{
if ( sender == GUI->BackgroundLow_NumericControl )
instance.backgroundLow = value;
else if ( sender == GUI->BackgroundHigh_NumericControl )
instance.backgroundHigh = value;
else if ( sender == GUI->TargetBackground_NumericControl )
instance.targetBackground = value;
}
// ----------------------------------------------------------------------------
void BackgroundNeutralizationInterface::__Click( Button& sender, bool checked )
{
if ( sender == GUI->BackgroundReferenceView_ToolButton )
{
ViewSelectionDialog d( instance.backgroundReferenceViewId );
if ( d.Execute() == StdDialogCode::Ok )
{
instance.backgroundReferenceViewId = d.Id();
GUI->BackgroundReferenceView_Edit.SetText( BACKGROUND_REFERENCE_ID );
}
}
}
// ----------------------------------------------------------------------------
void BackgroundNeutralizationInterface::__ItemSelected( ComboBox& sender, int itemIndex )
{
if ( sender == GUI->Mode_ComboBox )
{
instance.mode = itemIndex;
UpdateControls();
}
}
// ----------------------------------------------------------------------------
void BackgroundNeutralizationInterface::__ROI_Check( GroupBox& sender, bool checked )
{
if ( sender == GUI->ROI_GroupBox )
instance.useROI = checked;
}
// ----------------------------------------------------------------------------
void BackgroundNeutralizationInterface::__ROI_SpinValueUpdated( SpinBox& sender, int value )
{
if ( sender == GUI->ROIX0_SpinBox )
instance.roi.x0 = value;
else if ( sender == GUI->ROIY0_SpinBox )
instance.roi.y0 = value;
else if ( sender == GUI->ROIWidth_SpinBox )
instance.roi.x1 = instance.roi.x0 + value;
else if ( sender == GUI->ROIHeight_SpinBox )
instance.roi.y1 = instance.roi.y0 + value;
}
// ----------------------------------------------------------------------------
void BackgroundNeutralizationInterface::__ROI_Click( Button& sender, bool checked )
{
if ( sender == GUI->ROISelectPreview_Button )
{
PreviewSelectionDialog d;
if ( d.Execute() )
if ( !d.Id().IsEmpty() )
{
View view = View::ViewById( d.Id() );
if ( !view.IsNull() )
{
instance.roi = view.Window().PreviewRect( view.Id() );
UpdateControls();
}
}
}
}
// ----------------------------------------------------------------------------
void BackgroundNeutralizationInterface::__ViewDrag( Control& sender, const Point& pos, const View& view, unsigned modifiers, bool& wantsView )
{
if ( sender == GUI->BackgroundReferenceView_Edit )
wantsView = true;
else if ( sender == GUI->ROI_GroupBox || sender == GUI->ROISelectPreview_Button )
wantsView = view.IsPreview();
}
// ----------------------------------------------------------------------------
void BackgroundNeutralizationInterface::__ViewDrop( Control& sender, const Point& pos, const View& view, unsigned modifiers )
{
if ( sender == GUI->BackgroundReferenceView_Edit )
{
instance.backgroundReferenceViewId = view.FullId();
GUI->BackgroundReferenceView_Edit.SetText( BACKGROUND_REFERENCE_ID );
}
else if ( sender == GUI->ROI_GroupBox || sender == GUI->ROISelectPreview_Button )
{
if ( view.IsPreview() )
{
instance.useROI = true;
instance.roi = view.Window().PreviewRect( view.Id() );
UpdateControls();
}
}
}
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
BackgroundNeutralizationInterface::GUIData::GUIData( BackgroundNeutralizationInterface& w )
{
#define DELTA_FRAME 1
pcl::Font fnt = w.Font();
int labelWidth1 = fnt.Width( String( "Target background:" ) + 'T' );
int labelWidth2 = fnt.Width( String( "Height:" ) + 'T' );
int editWidth1 = fnt.Width( String( '0', 12 ) );
//
BackgroundReferenceView_Label.SetText( "Reference image:" );
BackgroundReferenceView_Label.SetFixedWidth( labelWidth1 );
BackgroundReferenceView_Label.SetTextAlignment( TextAlign::Right|TextAlign::VertCenter );
BackgroundReferenceView_Edit.SetToolTip( "<p>BackgroundNeutralization will use pixels read from this "
"image to compute an initial mean background level for each color channel. If you leave this field blank "
"(or with its default <target image> value), the target image will be also the background "
"reference image during the neutralization process.</p>"
"<p>You should specify a view that represents the <i>true background</i> of the image. In most cases this "
"means that you must select a view whose pixels are strongly dominated by the sky background, as it is "
"being represented on the target image. A typical example involves defining a small preview over a free "
"sky area of the target image, and selecting it here as the background reference image.</p>" );
BackgroundReferenceView_Edit.OnGetFocus( (Control::event_handler)&BackgroundNeutralizationInterface::__GetFocus, w );
BackgroundReferenceView_Edit.OnEditCompleted( (Edit::edit_event_handler)&BackgroundNeutralizationInterface::__EditCompleted, w );
BackgroundReferenceView_Edit.OnViewDrag( (Control::view_drag_event_handler)&BackgroundNeutralizationInterface::__ViewDrag, w );
BackgroundReferenceView_Edit.OnViewDrop( (Control::view_drop_event_handler)&BackgroundNeutralizationInterface::__ViewDrop, w );
BackgroundReferenceView_ToolButton.SetIcon( Bitmap( w.ScaledResource( ":/icons/select-view.png" ) ) );
BackgroundReferenceView_ToolButton.SetScaledFixedSize( 20, 20 );
BackgroundReferenceView_ToolButton.SetToolTip( "<p>Select the background reference image.</p>" );
BackgroundReferenceView_ToolButton.OnClick( (Button::click_event_handler)&BackgroundNeutralizationInterface::__Click, w );
BackgroundReferenceView_Sizer.SetSpacing( 4 );
BackgroundReferenceView_Sizer.Add( BackgroundReferenceView_Label );
BackgroundReferenceView_Sizer.Add( BackgroundReferenceView_Edit );
BackgroundReferenceView_Sizer.Add( BackgroundReferenceView_ToolButton );
BackgroundLow_NumericControl.label.SetText( "Lower limit:" );
BackgroundLow_NumericControl.label.SetFixedWidth( labelWidth1 );
BackgroundLow_NumericControl.slider.SetRange( 0, 100 );
BackgroundLow_NumericControl.slider.SetScaledMinWidth( 200 );
BackgroundLow_NumericControl.SetReal();
BackgroundLow_NumericControl.SetRange( TheBNBackgroundLowParameter->MinimumValue(), TheBNBackgroundLowParameter->MaximumValue() );
BackgroundLow_NumericControl.SetPrecision( TheBNBackgroundLowParameter->Precision() );
BackgroundLow_NumericControl.edit.SetFixedWidth( editWidth1 );
BackgroundLow_NumericControl.SetToolTip( "<p>Lower bound of the set of background pixels. Background reference "
"pixels with values less than or equal to this value will be rejected for calculation of mean background "
"levels. Note that since the minimum allowed value for this parameter is zero, black pixels are never taken "
"into account.</p>" );
BackgroundLow_NumericControl.OnValueUpdated( (NumericEdit::value_event_handler)&BackgroundNeutralizationInterface::__EditValueUpdated, w );
BackgroundHigh_NumericControl.label.SetText( "Upper limit:" );
BackgroundHigh_NumericControl.label.SetFixedWidth( labelWidth1 );
BackgroundHigh_NumericControl.slider.SetRange( 0, 100 );
BackgroundHigh_NumericControl.slider.SetScaledMinWidth( 200 );
BackgroundHigh_NumericControl.SetReal();
BackgroundHigh_NumericControl.SetRange( TheBNBackgroundHighParameter->MinimumValue(), TheBNBackgroundHighParameter->MaximumValue() );
BackgroundHigh_NumericControl.SetPrecision( TheBNBackgroundHighParameter->Precision() );
BackgroundHigh_NumericControl.edit.SetFixedWidth( editWidth1 );
BackgroundHigh_NumericControl.SetToolTip( "<p>Upper bound of the set of background pixels. Background reference "
"pixels above this value will be rejected for calculation of mean background levels.</p>" );
BackgroundHigh_NumericControl.OnValueUpdated( (NumericEdit::value_event_handler)&BackgroundNeutralizationInterface::__EditValueUpdated, w );
const char* modeToolTip = "<p>Select a background neutralization mode.</p>"
"<p>In <i>target background</i> mode, BackgroundNeutralization will force the target image to have "
"the specified mean background value (see the target background parameter below) for the three RGB "
"channels. In this mode, any resulting out-of-range values after neutralization will be truncated. "
"There can be some (usually negligible) data clipping, but only additive transformations are applied "
"to the data.</p>"
"<p>In <i>rescale</i> mode, the target image will always be rescaled after neutralization. In this "
"mode there are no data clippings, and the neutralized image maximizes dynamic range usage. However, "
"in this mode you have no control over the resulting mean background value, and the rescaling operation "
"is a multiplicative transformation that redistributes all pixel values throughout the available dynamic "
"range.</p>"
"<p>The <i>rescale as needed</i> mode is similar to <i>rescale</i>, but the target image is only rescaled "
"if there are out-of-range-values after neutralization. This is the default mode.</p>"
"<p>In <i>truncate</i> mode all resulting out-of-range pixels after neutralization will be truncated, "
"which usually results in severely clipped data. This mode is useful to perform a background subtraction "
"to a working image used for an intermediate analysis or processing step.</p>";
Mode_Label.SetText( "Working mode:" );
Mode_Label.SetFixedWidth( labelWidth1 );
Mode_Label.SetTextAlignment( TextAlign::Right|TextAlign::VertCenter );
Mode_Label.SetToolTip( modeToolTip );
Mode_ComboBox.AddItem( "Target Background" );
Mode_ComboBox.AddItem( "Rescale" );
Mode_ComboBox.AddItem( "Rescale as needed" );
Mode_ComboBox.AddItem( "Truncate" );
Mode_ComboBox.SetToolTip( modeToolTip );
Mode_ComboBox.OnItemSelected( (ComboBox::item_event_handler)&BackgroundNeutralizationInterface::__ItemSelected, w );
Mode_Sizer.SetSpacing( 4 );
Mode_Sizer.Add( Mode_Label );
Mode_Sizer.Add( Mode_ComboBox );
Mode_Sizer.AddStretch();
TargetBackground_NumericControl.label.SetText( "Target background:" );
TargetBackground_NumericControl.label.SetFixedWidth( labelWidth1 );
TargetBackground_NumericControl.slider.SetRange( 0, 100 );
TargetBackground_NumericControl.slider.SetScaledMinWidth( 200 );
TargetBackground_NumericControl.SetReal();
TargetBackground_NumericControl.SetRange( TheBNTargetBackgroundParameter->MinimumValue(), TheBNTargetBackgroundParameter->MaximumValue() );
TargetBackground_NumericControl.SetPrecision( TheBNTargetBackgroundParameter->Precision() );
TargetBackground_NumericControl.edit.SetFixedWidth( editWidth1 );
TargetBackground_NumericControl.SetToolTip( "<p>In the <i>target background</i> working mode, this is the "
"final mean background level that will be imposed to the three RGB channels of the target image.</p>"
"<p>In the rest of modes (<i>rescale</i>, <i>rescale as needed</i> and <i>truncate</i>) this parameter "
"is not used.</p>" );
TargetBackground_NumericControl.OnValueUpdated( (NumericEdit::value_event_handler)&BackgroundNeutralizationInterface::__EditValueUpdated, w );
//
ROI_GroupBox.SetTitle( "Region of Interest" );
ROI_GroupBox.EnableTitleCheckBox();
ROI_GroupBox.OnCheck( (GroupBox::check_event_handler)&BackgroundNeutralizationInterface::__ROI_Check, w );
ROI_GroupBox.OnViewDrag( (Control::view_drag_event_handler)&BackgroundNeutralizationInterface::__ViewDrag, w );
ROI_GroupBox.OnViewDrop( (Control::view_drop_event_handler)&BackgroundNeutralizationInterface::__ViewDrop, w );
const char* roiX0ToolTip = "<p>X pixel coordinate of the upper-left corner of the ROI.</p>";
ROIX0_Label.SetText( "Left:" );
ROIX0_Label.SetFixedWidth( labelWidth1 - w.LogicalPixelsToPhysical( 6 + DELTA_FRAME ) );
ROIX0_Label.SetTextAlignment( TextAlign::Right|TextAlign::VertCenter );
ROIX0_Label.SetToolTip( roiX0ToolTip );
ROIX0_SpinBox.SetRange( 0, int_max );
ROIX0_SpinBox.SetToolTip( roiX0ToolTip );
ROIX0_SpinBox.OnValueUpdated( (SpinBox::value_event_handler)&BackgroundNeutralizationInterface::__ROI_SpinValueUpdated, w );
const char* roiY0ToolTip = "<p>Y pixel coordinate of the upper-left corner of the ROI.</p>";
ROIY0_Label.SetText( "Top:" );
ROIY0_Label.SetFixedWidth( labelWidth2 );
ROIY0_Label.SetTextAlignment( TextAlign::Right|TextAlign::VertCenter );
ROIY0_Label.SetToolTip( roiY0ToolTip );
ROIY0_SpinBox.SetRange( 0, int_max );
ROIY0_SpinBox.SetToolTip( roiY0ToolTip );
ROIY0_SpinBox.OnValueUpdated( (SpinBox::value_event_handler)&BackgroundNeutralizationInterface::__ROI_SpinValueUpdated, w );
ROIRow1_Sizer.SetSpacing( 4 );
ROIRow1_Sizer.Add( ROIX0_Label );
ROIRow1_Sizer.Add( ROIX0_SpinBox );
ROIRow1_Sizer.Add( ROIY0_Label );
ROIRow1_Sizer.Add( ROIY0_SpinBox );
ROIRow1_Sizer.AddStretch();
const char* roiWidthToolTip = "<p>Width of the ROI in pixels.</p>";
ROIWidth_Label.SetText( "Width:" );
ROIWidth_Label.SetFixedWidth( labelWidth1 - w.LogicalPixelsToPhysical( 6 + DELTA_FRAME ) );
ROIWidth_Label.SetTextAlignment( TextAlign::Right|TextAlign::VertCenter );
ROIWidth_Label.SetToolTip( roiWidthToolTip );
ROIWidth_SpinBox.SetRange( 0, int_max );
ROIWidth_SpinBox.SetToolTip( roiWidthToolTip );
ROIWidth_SpinBox.OnValueUpdated( (SpinBox::value_event_handler)&BackgroundNeutralizationInterface::__ROI_SpinValueUpdated, w );
const char* roiHeightToolTip = "<p>Height of the ROI in pixels.</p>";
ROIHeight_Label.SetText( "Height:" );
ROIHeight_Label.SetFixedWidth( labelWidth2 );
ROIHeight_Label.SetTextAlignment( TextAlign::Right|TextAlign::VertCenter );
ROIHeight_Label.SetToolTip( roiHeightToolTip );
ROIHeight_SpinBox.SetRange( 0, int_max );
ROIHeight_SpinBox.SetToolTip( roiHeightToolTip );
ROIHeight_SpinBox.OnValueUpdated( (SpinBox::value_event_handler)&BackgroundNeutralizationInterface::__ROI_SpinValueUpdated, w );
ROISelectPreview_Button.SetText( "From Preview" );
ROISelectPreview_Button.SetToolTip( "<p>Import ROI coordinates from an existing preview.</p>" );
ROISelectPreview_Button.OnClick( (Button::click_event_handler)&BackgroundNeutralizationInterface::__ROI_Click, w );
ROISelectPreview_Button.OnViewDrag( (Control::view_drag_event_handler)&BackgroundNeutralizationInterface::__ViewDrag, w );
ROISelectPreview_Button.OnViewDrop( (Control::view_drop_event_handler)&BackgroundNeutralizationInterface::__ViewDrop, w );
ROIRow2_Sizer.SetSpacing( 4 );
ROIRow2_Sizer.Add( ROIWidth_Label );
ROIRow2_Sizer.Add( ROIWidth_SpinBox );
ROIRow2_Sizer.Add( ROIHeight_Label );
ROIRow2_Sizer.Add( ROIHeight_SpinBox );
ROIRow2_Sizer.AddSpacing( 12 );
ROIRow2_Sizer.Add( ROISelectPreview_Button );
ROIRow2_Sizer.AddStretch();
ROI_Sizer.SetMargin( 6 );
ROI_Sizer.SetSpacing( 4 );
ROI_Sizer.Add( ROIRow1_Sizer );
ROI_Sizer.Add( ROIRow2_Sizer );
ROI_GroupBox.SetSizer( ROI_Sizer );
//
Global_Sizer.SetMargin( 8 );
Global_Sizer.SetSpacing( 4 );
Global_Sizer.Add( BackgroundReferenceView_Sizer );
Global_Sizer.Add( BackgroundLow_NumericControl );
Global_Sizer.Add( BackgroundHigh_NumericControl );
Global_Sizer.Add( Mode_Sizer );
Global_Sizer.Add( TargetBackground_NumericControl );
Global_Sizer.Add( ROI_GroupBox );
//
w.SetSizer( Global_Sizer );
w.EnsureLayoutUpdated();
w.AdjustToContents();
w.SetFixedSize();
}
// ----------------------------------------------------------------------------
} // pcl
// ----------------------------------------------------------------------------
// EOF BackgroundNeutralizationInterface.cpp - Released 2021-04-09T19:41:48Z
| 43.509565
| 145
| 0.6664
|
fmeschia
|
d6b72ff253851c83c2993880e81f78e70d7d0fa2
| 3,323
|
hpp
|
C++
|
AdenitaCoreSE/include/SEAdenitaCoreSEAppGUI.hpp
|
edellano/Adenita-SAMSON-Edition-Win-
|
6df8d21572ef40fe3fc49165dfaa1d4318352a69
|
[
"BSD-3-Clause"
] | 2
|
2020-09-07T20:48:43.000Z
|
2021-09-03T05:49:59.000Z
|
AdenitaCoreSE/include/SEAdenitaCoreSEAppGUI.hpp
|
edellano/Adenita-SAMSON-Edition
|
6df8d21572ef40fe3fc49165dfaa1d4318352a69
|
[
"BSD-3-Clause"
] | 6
|
2020-04-05T18:39:28.000Z
|
2022-01-11T14:28:55.000Z
|
AdenitaCoreSE/include/SEAdenitaCoreSEAppGUI.hpp
|
edellano/Adenita-SAMSON-Edition-Win-
|
6df8d21572ef40fe3fc49165dfaa1d4318352a69
|
[
"BSD-3-Clause"
] | 2
|
2021-07-13T12:58:13.000Z
|
2022-01-11T13:52:00.000Z
|
#pragma once
#include "SBGApp.hpp"
#include "ui_SEAdenitaCoreSEAppGUI.h"
#include <QMessageBox>
#include <QComboBox>
#include <QSpinBox>
#include <QToolButton>
class SEAdenitaCoreSEApp;
/// This class implements the GUI of the app
// SAMSON Element generator pro tip: add GUI functionality in this class. The non-GUI functionality should go in the SEAdenitaCoreSEApp class
class SEAdenitaCoreSEAppGUI : public SBGApp {
Q_OBJECT
public:
/// \name Constructors and destructors
//@{
SEAdenitaCoreSEAppGUI(SEAdenitaCoreSEApp* t); ///< Constructs a GUI for the app
virtual ~SEAdenitaCoreSEAppGUI(); ///< Destructs the GUI of the app
//@}
/// \name App
//@{
SEAdenitaCoreSEApp* getApp() const; ///< Returns a pointer to the app
//@}
/// \name Identity
//@{
virtual SBCContainerUUID getUUID() const; ///< Returns the widget UUID
virtual QString getName() const; ///< Returns the widget name (used as a title for the embedding window)
virtual QPixmap getLogo() const; ///< Returns the widget logo
int getFormat() const; ///< Returns the widget format
virtual QString getCitation() const; ///< Returns the citation information
//@}
virtual void keyPressEvent(QKeyEvent *event);
///\name Settings
//@{
void loadSettings(SBGSettings* settings); ///< Load GUI settings
void saveSettings(SBGSettings* settings); ///< Save GUI settings
//@}
// get selected scaffold
std::string GetScaffoldFilename();
public slots:
void onChangeSelector(int idx);
// Main
void onLoadFile();
void onSaveAll();
void onSaveSelection();
void onExport();
void onSetScaffold();
void onCreateBasePair();
void onGenerateSequence();
void onSettings();
void onSetStart();
void onCalculateBindingProperties();
// Editors
void onBreakEditor();
void onConnectEditor();
void onDeleteEditor();
void onDNATwistEditor();
void onMergePartsEditor();
void onCreateStrandEditor();
void onNanotubeCreatorEditor();
void onLatticeCreatorEditor();
void onWireframeEditor();
void onTaggingEditor();
void onTwisterEditor();
// Debug
void onAddNtThreeP();
void onCenterPart();
void onCatenanes();
void onKinetoplast();
void onTestNeighbors();
void onOxDNAImport();
void onFromDatagraph();
void onHighlightXOs();
void onHighlightPosXOs();
void onExportToCanDo();
void onFixDesigns();
private slots:
void CheckForLoadedParts();
private:
void SetupUI();
std::string IsJsonCadnano(QString filename);
void HighlightEditor(QToolButton* b);
std::vector<QToolButton*> menuButtons_;
std::vector<QToolButton*> editSequencesButtons_;
std::vector<QToolButton*> modelingButtons_;
std::vector<QToolButton*> creatorsButtons_;
std::vector<QPushButton*> debugButtons_;
std::vector<QToolButton*> GetMenuButtons();
std::vector<QToolButton*> GetEditSequencesButtons();
std::vector<QToolButton*> GetModelingButtons();
std::vector<QToolButton*> GetCreatorsButtons();
std::vector<QPushButton*> GetDebugButtons();
Ui::SEAdenitaCoreSEAppGUIClass ui;
QToolButton* highlightedEditor_ = nullptr;
};
| 25.75969
| 141
| 0.676497
|
edellano
|
d6b7722e541ebf76bffe5916983ea58851b594fb
| 934
|
cpp
|
C++
|
Examples/MacroEquals/main_macro_equals.cpp
|
sapphire-devteam/SA-UnitTestHelper
|
5413b64f5554036e9fd18e2e0f7784f97aaf3c2f
|
[
"MIT"
] | null | null | null |
Examples/MacroEquals/main_macro_equals.cpp
|
sapphire-devteam/SA-UnitTestHelper
|
5413b64f5554036e9fd18e2e0f7784f97aaf3c2f
|
[
"MIT"
] | null | null | null |
Examples/MacroEquals/main_macro_equals.cpp
|
sapphire-devteam/SA-UnitTestHelper
|
5413b64f5554036e9fd18e2e0f7784f97aaf3c2f
|
[
"MIT"
] | null | null | null |
// Copyright (c) 2021 Sapphire's Suite. All Rights Reserved.. All Rights Reserved.
#include <UnitTestHelper.hpp>
using namespace Sa;
#include <limits>
struct MyClass
{
float myFloat = 0.0f;
std::string ToString() const { return std::to_string(myFloat); }
bool operator==(const MyClass& _rhs) const { return myFloat == _rhs.myFloat; }
};
int main()
{
SA_UTH_INIT();
// Single elem
float i = 4.6f;
float j = 1.25f;
/// elem1, elem2, epsilon.
SA_UTH_EQ(i, i);
SA_UTH_EQ(i, j, std::numeric_limits<float>::epsilon()); // Error
// Tab elems.
int size = 3;
float ftab1[] = { 1.45f, 8.36f, 1.247f };
float ftab2[] = { 1.45f, 8.36f, 945.9f };
/// elem1, elem2, size, epsilon.
SA_UTH_EQ(ftab1, ftab2, 2, std::numeric_limits<float>::epsilon());
SA_UTH_EQ(ftab1, ftab2, size); // Error
// Custom elem
MyClass m1{ 4.56f };
MyClass m2{ 8.15f };
SA_UTH_EQ(m1, m1);
SA_UTH_EQ(m1, m2); // Error
SA_UTH_EXIT();
}
| 18.68
| 82
| 0.647752
|
sapphire-devteam
|
d6b93ff1997f8e0b9757ff88ebc8c24bf999b815
| 21,359
|
cpp
|
C++
|
bLSM.cpp
|
sears/bLSM
|
fc49c4e0ce1ef69bd9d18b7ed5c83151aee9c91c
|
[
"Apache-2.0"
] | 114
|
2015-03-10T16:07:35.000Z
|
2022-01-11T08:36:42.000Z
|
bLSM.cpp
|
anqin/bLSM
|
fc49c4e0ce1ef69bd9d18b7ed5c83151aee9c91c
|
[
"Apache-2.0"
] | 1
|
2019-03-16T11:31:59.000Z
|
2019-03-16T11:31:59.000Z
|
bLSM.cpp
|
anqin/bLSM
|
fc49c4e0ce1ef69bd9d18b7ed5c83151aee9c91c
|
[
"Apache-2.0"
] | 36
|
2015-02-17T22:04:17.000Z
|
2021-06-06T02:38:18.000Z
|
/*
* blsm.cpp
*
* Copyright 2009-2012 Yahoo! Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include "bLSM.h"
#include "mergeScheduler.h"
#include <stasis/transactional.h>
#include <stasis/bufferManager.h>
#include <stasis/bufferManager/bufferHash.h>
#include <stasis/logger/logger2.h>
#include <stasis/logger/logHandle.h>
#include <stasis/logger/filePool.h>
#include "mergeStats.h"
// Backpressure reads to avoid merge starvation? Experimental/short-term hack
//#define BACKPRESSURE_READS
static inline double tv_to_double(struct timeval tv)
{
return static_cast<double>(tv.tv_sec) +
(static_cast<double>(tv.tv_usec) / 1000000.0);
}
/////////////////////////////////////////////////////////////////
// LOG TABLE IMPLEMENTATION
/////////////////////////////////////////////////////////////////
bLSM::bLSM(int log_mode, pageid_t max_c0_size, pageid_t internal_region_size, pageid_t datapage_region_size, pageid_t datapage_size)
{
recovering = true;
this->max_c0_size = max_c0_size;
this->mean_c0_run_length = max_c0_size;
this->num_c0_mergers = 0;
r_val = 3.0; // MIN_R
tree_c0 = NULL;
tree_c0_mergeable = NULL;
c0_is_merging = false;
tree_c1_prime = NULL;
tree_c1 = NULL;
tree_c1_mergeable = NULL;
tree_c2 = NULL;
// This bool is purely for external code.
this->accepting_new_requests = true;
this->shutting_down_ = false;
c0_flushing = false;
c1_flushing = false;
current_timestamp = 0;
expiry = 0;
this->merge_mgr = 0;
tmerger = new tupleMerger(&replace_merger);
header_mut = rwlc_initlock();
pthread_mutex_init(&rb_mut, 0);
pthread_cond_init(&c0_needed, 0);
pthread_cond_init(&c0_ready, 0);
pthread_cond_init(&c1_needed, 0);
pthread_cond_init(&c1_ready, 0);
epoch = 0;
this->internal_region_size = internal_region_size;
this->datapage_region_size = datapage_region_size;
this->datapage_size = datapage_size;
this->log_mode = log_mode;
this->batch_size = 0;
log_file = stasis_log_file_pool_open("lsm_log",
stasis_log_file_mode,
stasis_log_file_permissions);
}
bLSM::~bLSM()
{
delete merge_mgr; // shuts down pretty print thread.
if(tree_c1 != NULL)
delete tree_c1;
if(tree_c2 != NULL)
delete tree_c2;
if(tree_c0 != NULL)
{
memTreeComponent::tearDownTree(tree_c0);
}
log_file->close(log_file);
pthread_mutex_destroy(&rb_mut);
rwlc_deletelock(header_mut);
pthread_cond_destroy(&c0_needed);
pthread_cond_destroy(&c0_ready);
pthread_cond_destroy(&c1_needed);
pthread_cond_destroy(&c1_ready);
delete tmerger;
}
void bLSM::init_stasis() {
dataPage::register_stasis_page_impl();
// stasis_buffer_manager_hint_writes_are_sequential = 1;
Tinit();
}
void bLSM::deinit_stasis() { Tdeinit(); }
recordid bLSM::allocTable(int xid)
{
table_rec = Talloc(xid, sizeof(tbl_header));
mergeStats * stats = 0;
//create the big tree
tree_c2 = new diskTreeComponent(xid, internal_region_size, datapage_region_size, datapage_size, stats, 10);
//create the small tree
tree_c1 = new diskTreeComponent(xid, internal_region_size, datapage_region_size, datapage_size, stats, 10);
merge_mgr = new mergeManager(this);
merge_mgr->set_c0_size(max_c0_size);
merge_mgr->new_merge(0);
tree_c0 = new memTreeComponent::rbtree_t;
tbl_header.merge_manager = merge_mgr->talloc(xid);
tbl_header.log_trunc = 0;
update_persistent_header(xid);
return table_rec;
}
void bLSM::openTable(int xid, recordid rid) {
table_rec = rid;
Tread(xid, table_rec, &tbl_header);
tree_c2 = new diskTreeComponent(xid, tbl_header.c2_root, tbl_header.c2_state, tbl_header.c2_dp_state, 0);
tree_c1 = new diskTreeComponent(xid, tbl_header.c1_root, tbl_header.c1_state, tbl_header.c1_dp_state, 0);
tree_c0 = new memTreeComponent::rbtree_t;
merge_mgr = new mergeManager(this, xid, tbl_header.merge_manager);
merge_mgr->set_c0_size(max_c0_size);
merge_mgr->new_merge(0);
}
void bLSM::logUpdate(dataTuple * tup) {
byte * buf = tup->to_bytes();
LogEntry * e = stasis_log_write_update(log_file, 0, INVALID_PAGE, 0/*Page**/, 0/*op*/, buf, tup->byte_length());
log_file->write_entry_done(log_file,e);
free(buf);
}
void bLSM::replayLog() {
lsn_t start = tbl_header.log_trunc;
LogHandle * lh = start ? getLSNHandle(log_file, start) : getLogHandle(log_file);
const LogEntry * e;
while((e = nextInLog(lh))) {
switch(e->type) {
case UPDATELOG: {
dataTuple * tup = dataTuple::from_bytes((byte*)stasis_log_entry_update_args_cptr(e));
insertTuple(tup);
dataTuple::freetuple(tup);
} break;
case INTERNALLOG: { } break;
default: assert(e->type == UPDATELOG); abort();
}
}
freeLogHandle(lh);
recovering = false;
printf("\nLog replay complete.\n");
}
lsn_t bLSM::get_log_offset() {
if(recovering || !log_mode) { return INVALID_LSN; }
return log_file->next_available_lsn(log_file);
}
void bLSM::truncate_log() {
if(recovering) {
printf("Not truncating log until recovery is complete.\n");
} else {
if(tbl_header.log_trunc) {
printf("truncating log to %lld\n", tbl_header.log_trunc);
log_file->truncate(log_file, tbl_header.log_trunc);
}
}
}
void bLSM::update_persistent_header(int xid, lsn_t trunc_lsn) {
tbl_header.c2_root = tree_c2->get_root_rid();
tbl_header.c2_dp_state = tree_c2->get_datapage_allocator_rid();
tbl_header.c2_state = tree_c2->get_internal_node_allocator_rid();
tbl_header.c1_root = tree_c1->get_root_rid();
tbl_header.c1_dp_state = tree_c1->get_datapage_allocator_rid();
tbl_header.c1_state = tree_c1->get_internal_node_allocator_rid();
merge_mgr->marshal(xid, tbl_header.merge_manager);
if(trunc_lsn != INVALID_LSN) {
printf("\nsetting log truncation point to %lld\n", trunc_lsn);
tbl_header.log_trunc = trunc_lsn;
}
Tset(xid, table_rec, &tbl_header);
}
void bLSM::flushTable()
{
struct timeval start_tv, stop_tv;
double start, stop;
static double last_start;
static bool first = 1;
static int merge_count = 0;
gettimeofday(&start_tv,0);
start = tv_to_double(start_tv);
c0_flushing = true;
bool blocked = false;
int expmcount = merge_count;
//this waits for the previous merger of the mem-tree
//hopefullly this wont happen
while(get_c0_is_merging()) {
rwlc_cond_wait(&c0_needed, header_mut);
blocked = true;
if(expmcount != merge_count) {
return;
}
}
set_c0_is_merging(true);
merge_mgr->get_merge_stats(0)->handed_off_tree();
merge_mgr->new_merge(0);
gettimeofday(&stop_tv,0);
stop = tv_to_double(stop_tv);
pthread_cond_signal(&c0_ready);
DEBUG("Signaled c0-c1 merge thread\n");
merge_count ++;
merge_mgr->get_merge_stats(0)->starting_merge();
if(blocked && stop - start > 1.0) {
if(first)
{
printf("\nBlocked writes for %f sec\n", stop-start);
first = 0;
}
else
{
printf("\nBlocked writes for %f sec (serviced writes for %f sec)\n",
stop-start, start-last_start);
}
last_start = stop;
} else {
DEBUG("signaled c0-c1 merge\n");
}
c0_flushing = false;
}
dataTuple * bLSM::findTuple(int xid, const dataTuple::key_t key, size_t keySize)
{
// Apply proportional backpressure to reads as well as writes. This prevents
// starvation of the merge threads on fast boxes.
#ifdef BACKPRESSURE_READS
merge_mgr->tick(merge_mgr->get_merge_stats(0));
#endif
//prepare a search tuple
dataTuple *search_tuple = dataTuple::create(key, keySize);
pthread_mutex_lock(&rb_mut);
dataTuple *ret_tuple=0;
//step 1: look in tree_c0
memTreeComponent::rbtree_t::iterator rbitr = get_tree_c0()->find(search_tuple);
if(rbitr != get_tree_c0()->end())
{
DEBUG("tree_c0 size %d\n", get_tree_c0()->size());
ret_tuple = (*rbitr)->create_copy();
}
pthread_mutex_unlock(&rb_mut);
rwlc_readlock(header_mut); // XXX: FIXME with optimisitic concurrency control. Has to be before rb_mut, or we could merge the tuple with itself due to an intervening merge
bool done = false;
//step: 2 look into first in tree if exists (a first level merge going on)
if(get_tree_c0_mergeable() != 0)
{
DEBUG("old mem tree not null %d\n", (*(mergedata->old_c0))->size());
rbitr = get_tree_c0_mergeable()->find(search_tuple);
if(rbitr != get_tree_c0_mergeable()->end())
{
dataTuple *tuple = *rbitr;
if(tuple->isDelete()) //tuple deleted
done = true; //return ret_tuple
else if(ret_tuple != 0) //merge the two
{
dataTuple *mtuple = tmerger->merge(tuple, ret_tuple); //merge the two
dataTuple::freetuple(ret_tuple); //free tuple from current tree
ret_tuple = mtuple; //set return tuple to merge result
}
else //key first found in old mem tree
{
ret_tuple = tuple->create_copy();
}
//we cannot free tuple from old-tree 'cos it is not a copy
}
}
//step 2.5: check new c1 if exists
if(!done && get_tree_c1_prime() != 0)
{
DEBUG("old c1 tree not null\n");
dataTuple *tuple_oc1 = get_tree_c1_prime()->findTuple(xid, key, keySize);
if(tuple_oc1 != NULL)
{
bool use_copy = false;
if(tuple_oc1->isDelete())
done = true;
else if(ret_tuple != 0) //merge the two
{
dataTuple *mtuple = tmerger->merge(tuple_oc1, ret_tuple); //merge the two
dataTuple::freetuple(ret_tuple); //free tuple from before
ret_tuple = mtuple; //set return tuple to merge result
}
else //found for the first time
{
use_copy = true;
ret_tuple = tuple_oc1;
}
if(!use_copy)
{
dataTuple::freetuple(tuple_oc1); //free tuple from tree old c1
}
}
}
//step 3: check c1
if(!done)
{
dataTuple *tuple_c1 = get_tree_c1()->findTuple(xid, key, keySize);
if(tuple_c1 != NULL)
{
bool use_copy = false;
if(tuple_c1->isDelete()) //tuple deleted
done = true;
else if(ret_tuple != 0) //merge the two
{
dataTuple *mtuple = tmerger->merge(tuple_c1, ret_tuple); //merge the two
dataTuple::freetuple(ret_tuple); //free tuple from before
ret_tuple = mtuple; //set return tuple to merge result
}
else //found for the first time
{
use_copy = true;
ret_tuple = tuple_c1;
}
if(!use_copy)
{
dataTuple::freetuple(tuple_c1); //free tuple from tree c1
}
}
}
//step 4: check old c1 if exists
if(!done && get_tree_c1_mergeable() != 0)
{
DEBUG("old c1 tree not null\n");
dataTuple *tuple_oc1 = get_tree_c1_mergeable()->findTuple(xid, key, keySize);
if(tuple_oc1 != NULL)
{
bool use_copy = false;
if(tuple_oc1->isDelete())
done = true;
else if(ret_tuple != 0) //merge the two
{
dataTuple *mtuple = tmerger->merge(tuple_oc1, ret_tuple); //merge the two
dataTuple::freetuple(ret_tuple); //free tuple from before
ret_tuple = mtuple; //set return tuple to merge result
}
else //found for the first time
{
use_copy = true;
ret_tuple = tuple_oc1;
}
if(!use_copy)
{
dataTuple::freetuple(tuple_oc1); //free tuple from tree old c1
}
}
}
//step 5: check c2
if(!done)
{
DEBUG("Not in old first disk tree\n");
dataTuple *tuple_c2 = get_tree_c2()->findTuple(xid, key, keySize);
if(tuple_c2 != NULL)
{
bool use_copy = false;
if(tuple_c2->isDelete())
done = true;
else if(ret_tuple != 0)
{
dataTuple *mtuple = tmerger->merge(tuple_c2, ret_tuple); //merge the two
dataTuple::freetuple(ret_tuple); //free tuple from before
ret_tuple = mtuple; //set return tuple to merge result
}
else //found for the first time
{
use_copy = true;
ret_tuple = tuple_c2;
}
if(!use_copy)
{
dataTuple::freetuple(tuple_c2); //free tuple from tree c2
}
}
}
rwlc_unlock(header_mut);
dataTuple::freetuple(search_tuple);
if (ret_tuple != NULL && ret_tuple->isDelete()) {
// this is a tombstone. don't return it
dataTuple::freetuple(ret_tuple);
return NULL;
}
return ret_tuple;
}
/*
* returns the first record found with the matching key
* (not to be used together with diffs)
**/
dataTuple * bLSM::findTuple_first(int xid, dataTuple::key_t key, size_t keySize)
{
// Apply proportional backpressure to reads as well as writes. This prevents
// starvation of the merge threads on fast boxes.
#ifdef BACKPRESSURE_READS
merge_mgr->tick(merge_mgr->get_merge_stats(0));
#endif
//prepare a search tuple
dataTuple * search_tuple = dataTuple::create(key, keySize);
dataTuple *ret_tuple=0;
//step 1: look in tree_c0
pthread_mutex_lock(&rb_mut);
memTreeComponent::rbtree_t::iterator rbitr = get_tree_c0()->find(search_tuple);
if(rbitr != get_tree_c0()->end())
{
DEBUG("tree_c0 size %d\n", tree_c0->size());
ret_tuple = (*rbitr)->create_copy();
pthread_mutex_unlock(&rb_mut);
}
else
{
DEBUG("Not in mem tree %d\n", tree_c0->size());
pthread_mutex_unlock(&rb_mut);
rwlc_readlock(header_mut); // XXX FIXME WITH OCC!!
//step: 2 look into first in tree if exists (a first level merge going on)
if(get_tree_c0_mergeable() != NULL)
{
DEBUG("old mem tree not null %d\n", (*(mergedata->old_c0))->size());
rbitr = get_tree_c0_mergeable()->find(search_tuple);
if(rbitr != get_tree_c0_mergeable()->end())
{
ret_tuple = (*rbitr)->create_copy();
}
}
if(ret_tuple == 0)
{
DEBUG("Not in first disk tree\n");
//step 4: check in progress c1 if exists
if( get_tree_c1_prime() != 0)
{
DEBUG("old c1 tree not null\n");
ret_tuple = get_tree_c1_prime()->findTuple(xid, key, keySize);
}
}
if(ret_tuple == 0)
{
DEBUG("Not in old mem tree\n");
//step 3: check c1
ret_tuple = get_tree_c1()->findTuple(xid, key, keySize);
}
if(ret_tuple == 0)
{
DEBUG("Not in first disk tree\n");
//step 4: check old c1 if exists
if( get_tree_c1_mergeable() != 0)
{
DEBUG("old c1 tree not null\n");
ret_tuple = get_tree_c1_mergeable()->findTuple(xid, key, keySize);
}
}
if(ret_tuple == 0)
{
DEBUG("Not in old first disk tree\n");
//step 5: check c2
ret_tuple = get_tree_c2()->findTuple(xid, key, keySize);
}
rwlc_unlock(header_mut);
}
dataTuple::freetuple(search_tuple);
if (ret_tuple != NULL && ret_tuple->isDelete()) {
// this is a tombstone. don't return it
dataTuple::freetuple(ret_tuple);
return NULL;
}
return ret_tuple;
}
dataTuple * bLSM::insertTupleHelper(dataTuple *tuple)
{
bool need_free = false;
if(!tuple->isDelete() && expiry != 0) {
// XXX hack for paper experiment
current_timestamp++;
size_t ts_sz = sizeof(int64_t);
int64_t ts = current_timestamp;
int64_t kl = tuple->strippedkeylen();
byte * newkey = (byte*)malloc(kl + 1 + ts_sz);
memcpy(newkey, tuple->strippedkey(), kl);
newkey[kl] = 0;
memcpy(newkey+kl+1, &ts, ts_sz);
dataTuple * old = tuple;
tuple = dataTuple::create(newkey, kl+ 1+ ts_sz, tuple->data(), tuple->datalen());
assert(tuple->strippedkeylen() == old->strippedkeylen());
assert(!dataTuple::compare_obj(tuple, old));
free(newkey);
need_free = true;
} //find the previous tuple with same key in the memtree if exists
pthread_mutex_lock(&rb_mut);
memTreeComponent::rbtree_t::iterator rbitr = tree_c0->find(tuple);
dataTuple * t = 0;
dataTuple * pre_t = 0;
if(rbitr != tree_c0->end())
{
pre_t = *rbitr;
//do the merging
dataTuple *new_t = tmerger->merge(pre_t, tuple);
merge_mgr->get_merge_stats(0)->merged_tuples(new_t, tuple, pre_t);
t = new_t;
tree_c0->erase(pre_t); //remove the previous tuple
tree_c0->insert(new_t); //insert the new tuple
}
else //no tuple with same key exists in mem-tree
{
t = tuple->create_copy();
//insert tuple into the rbtree
tree_c0->insert(t);
}
pthread_mutex_unlock(&rb_mut);
if(need_free) { dataTuple::freetuple(tuple); }
return pre_t;
}
void bLSM::insertManyTuples(dataTuple ** tuples, int tuple_count) {
for(int i = 0; i < tuple_count; i++) {
merge_mgr->read_tuple_from_small_component(0, tuples[i]);
}
if(log_mode && !recovering) {
for(int i = 0; i < tuple_count; i++) {
logUpdate(tuples[i]);
}
batch_size ++;
if(batch_size >= log_mode) {
log_file->force_tail(log_file, LOG_FORCE_COMMIT);
batch_size = 0;
}
}
int num_old_tups = 0;
pageid_t sum_old_tup_lens = 0;
for(int i = 0; i < tuple_count; i++) {
dataTuple * old_tup = insertTupleHelper(tuples[i]);
if(old_tup) {
num_old_tups++;
sum_old_tup_lens += old_tup->byte_length();
dataTuple::freetuple(old_tup);
}
}
merge_mgr->read_tuple_from_large_component(0, num_old_tups, sum_old_tup_lens);
}
void bLSM::insertTuple(dataTuple *tuple)
{
if(log_mode && !recovering) {
logUpdate(tuple);
batch_size++;
if(batch_size >= log_mode) {
log_file->force_tail(log_file, LOG_FORCE_COMMIT);
batch_size = 0;
}
}
// Note, this is where we block for backpressure. Do this without holding
// any locks!
merge_mgr->read_tuple_from_small_component(0, tuple);
dataTuple * pre_t = 0; // this is a pointer to any data tuples that we'll be deleting below. We need to update the merge_mgr statistics with it, but have to do so outside of the rb_mut region.
pre_t = insertTupleHelper(tuple);
if(pre_t) {
// needs to be here; calls update_progress, which sometimes grabs mutexes..
merge_mgr->read_tuple_from_large_component(0, pre_t); // was interspersed with the erase, insert above...
dataTuple::freetuple(pre_t); //free the previous tuple
}
DEBUG("tree size %d tuples %lld bytes.\n", tsize, tree_bytes);
}
bool bLSM::testAndSetTuple(dataTuple *tuple, dataTuple *tuple2)
{
bool succ = false;
static pthread_mutex_t test_and_set_mut = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_lock(&test_and_set_mut);
dataTuple * exists = findTuple_first(-1, tuple2 ? tuple2->strippedkey() : tuple->strippedkey(), tuple2 ? tuple2->strippedkeylen() : tuple->strippedkeylen());
if(!tuple2 || tuple2->isDelete()) {
if(!exists || exists->isDelete()) {
succ = true;
} else {
succ = false;
}
} else {
if(tuple2->datalen() == exists->datalen() && !memcmp(tuple2->data(), exists->data(), tuple2->datalen())) {
succ = true;
} else {
succ = false;
}
}
if(exists) dataTuple::freetuple(exists);
if(succ) insertTuple(tuple);
pthread_mutex_unlock(&test_and_set_mut);
return succ;
}
void bLSM::registerIterator(iterator * it) {
its.push_back(it);
}
void bLSM::forgetIterator(iterator * it) {
for(unsigned int i = 0; i < its.size(); i++) {
if(its[i] == it) {
its.erase(its.begin()+i);
break;
}
}
}
void bLSM::bump_epoch() {
epoch++;
for(unsigned int i = 0; i < its.size(); i++) {
its[i]->invalidate();
}
}
| 29.706537
| 197
| 0.607145
|
sears
|
d6be3a6d75ddc19a8644ddffec93b7abf0149286
| 8,720
|
cpp
|
C++
|
deps/vision/src/kernel/Vca_VcaProxyFacilitator.cpp
|
MichaelJCaruso/vxa-node
|
4b02a17f48bed6f71f622e0bb743f87d932a2a6f
|
[
"BSD-3-Clause"
] | 30
|
2016-10-07T15:23:35.000Z
|
2020-03-25T20:01:30.000Z
|
src/kernel/Vca_VcaProxyFacilitator.cpp
|
MichaelJCaruso/vision-software-src-master
|
12b1b4f12a7531fe6e3cbb6861b40ac8e1985b92
|
[
"BSD-3-Clause"
] | 30
|
2016-10-31T19:48:08.000Z
|
2021-04-28T01:31:53.000Z
|
software/src/master/src/kernel/Vca_VcaProxyFacilitator.cpp
|
c-kuhlman/vision
|
46b25f7c0da703c059acc8f0a2eac1d5badf9f6d
|
[
"BSD-3-Clause"
] | 15
|
2016-10-07T16:44:13.000Z
|
2021-06-21T18:47:55.000Z
|
/***** VcaProxyFacilitator Implementation *****/
/************************
************************
***** Interfaces *****
************************
************************/
/********************
***** System *****
********************/
#include "Vk.h"
/******************
***** Self *****
******************/
#include "Vca_VcaProxyFacilitator.h"
/************************
***** Supporting *****
************************/
#include "Vca_CompilerHappyPill.h"
#include "VReceiver.h"
#include "Vca_IPeer.h"
#include "Vca_VcaPeer.h"
/**************************
**************************
***** Construction *****
**************************
**************************/
Vca::VcaProxyFacilitator::VcaProxyFacilitator (
VcaPeer *pSourcePeer, VcaPeer *pTargetPeer
) : m_pSourcePeer (pSourcePeer), m_pTargetPeer (pTargetPeer) {
startup ();
}
Vca::VcaProxyFacilitator::VcaProxyFacilitator (
VcaPeer *pSourcePeer, VcaPeer *pTargetPeer,
IPeer *pSourcePeerReflection, IPeer *pTargetPeerReflection
) : m_pSourcePeer (pSourcePeer)
, m_pTargetPeer (pTargetPeer)
, m_pSourcePeerReflection (pSourcePeerReflection)
, m_pTargetPeerReflection (pTargetPeerReflection) {
}
/*************************
*************************
***** Destruction *****
*************************
*************************/
Vca::VcaProxyFacilitator::~VcaProxyFacilitator () {
}
/********************
********************
***** Update *****
********************
********************/
void Vca::VcaProxyFacilitator::setSourcePeerReflection (IPeer *pPeer) {
m_pSourcePeerReflection.setTo (pPeer);
}
void Vca::VcaProxyFacilitator::setTargetPeerReflection (IPeer *pPeer) {
m_pTargetPeerReflection.setTo (pPeer);
}
/*****************
*****************
***** Use *****
*****************
*****************/
/****************************************************************************
* Routine: startup
* Operation:
* This method does the intial startup process, for a
* VcaFacilitator object to be used. It sends messages to both the source
* as well as the target peer, with the information about each other,
* also requests local interfaces for the images created by them.
****************************************************************************/
void Vca::VcaProxyFacilitator::startup () {
if (!reflectionsAreValid ()) {
VReference<IPeerReceiver> pReceiver1 (
new IPeerReceiver (this, &ThisClass::onTargetPeerReflection)
);
VReference<IPeerReceiver> pReceiver2 (
new IPeerReceiver (this, &ThisClass::onSourcePeerReflection)
);
traceInfo ("\nSending Peers for exchanging");
m_pSourcePeer->getRemoteLocalInterfaceFor (m_pTargetPeer, pReceiver1);
m_pTargetPeer->getRemoteLocalInterfaceFor (m_pSourcePeer, pReceiver2);
}
}
/****************************************************************************
* Routine: onSourcePeerReflection
* Operation:
* On getting the request for constructing an image for source peer, the
* target peer creates a source peer image and returns a local interface
* pointer by calling this routine. This method checks to see whether the other
* reflection has also arrived if so triggers the exchange of the
* reflections obtained
* Precondition: pIPeer, the reflection returned is a valid non-null pointer
****************************************************************************/
void Vca::VcaProxyFacilitator::onSourcePeerReflection (
IPeerReceiver *pReceiver, IPeer *pIPeer
) {
m_pSourcePeerReflection.setTo (pIPeer);
if (reflectionsAreValid ())
onBothReflections ();
}
void Vca::VcaProxyFacilitator::onTargetPeerReflection (
IPeerReceiver *pReceiver, IPeer *pIPeer
) {
m_pTargetPeerReflection.setTo (pIPeer);
if (reflectionsAreValid ())
onBothReflections ();
}
/****************************************************************************
* Routine: onBothReflections
* Operation:
* Once both reflections are obtained, by this facilitator it needs to
* send messages to both the source and target peer indicating their reflections
* at the other end. This method completes the phase of creating a virtual
* plumbing between the source and the target peer by the facilitator object.
* Now it can start the facilitations.
****************************************************************************/
void Vca::VcaProxyFacilitator::onBothReflections () {
traceInfo ("\nExchanging Reflections");
m_pSourcePeer->setRemoteRemoteReflectionFor (m_pTargetPeer, m_pSourcePeerReflection);
m_pTargetPeer->setRemoteRemoteReflectionFor (m_pSourcePeer, m_pTargetPeerReflection);
delegateReflections ();
delegatePendingProxies ();
}
/****************************************************************************
* Routine: delegateReflections
* Operation:
* This method delegates the reflections obtained from the source and the
* target peer. The reflections are being referenced from this facilitator
* object. So they wont be facilitated automatically as there is an internal
* usage. But to relieve this intermediary peer from serving as intermediary
* for the reflections we delegate the reflections also as part of the
* startup process.
* Out of the two reflections, the TargetPeer reflection can be facilitated
* by the current facilitator, but the SourcePeer reflection has to be
* facilitated by creating a new facilitator object which facilitates
* proxies going from the Target peer to the Source peer.
****************************************************************************/
void Vca::VcaProxyFacilitator::delegateReflections () {
traceInfo ("\nDelegating Reflection1");
delegateProxy (m_pTargetPeerReflection->oidr ());
traceInfo ("\nDelegating Reflection2");
VcaProxyFacilitator *pFacilitator;
pFacilitator = m_pTargetPeer->createProxyFacilitatorFor (
m_pSourcePeer, m_pTargetPeerReflection, m_pSourcePeerReflection
);
pFacilitator->processProxy (m_pSourcePeerReflection->oidr ());
}
void Vca::VcaProxyFacilitator::delegatePendingProxies () {
if (!reflectionsAreValid ())
return;
Iterator iterator (m_iPendingProxySet);
while (iterator.isNotAtEnd ()) {
VcaOIDR *pOIDR = *iterator;
// remove from pending list and then delegate...
iterator.Delete ();
pOIDR->deleteFacilitationTo (m_pTargetPeer);
delegateProxy (pOIDR);
}
}
/****************************************************************************
* Routine: processProxy
* Operation:
* When a proxy is being requested to be processed, first a check is made
* to determine whether the reflection are valid. If so then the proxy is
* directly delegated, else it is inserted into the pending proxy set.
****************************************************************************/
void Vca::VcaProxyFacilitator::processProxy (VcaOIDR *pOIDR) {
if (reflectionsAreValid ())
delegateProxy (pOIDR);
else
queueProxy (pOIDR);
}
void Vca::VcaProxyFacilitator::queueProxy (VcaOIDR *pOIDR) {
m_iPendingProxySet.Insert (pOIDR);
pOIDR->addFacilitationPeers (m_pTargetPeer, m_pSourcePeer);
}
/****************************************************************************
* Routine: delegateProxy
* Operation:
* This method performs the work of eliminating this process as a middle man
* in an import/export relationship between two adjacent peers. This method
* operates by manipulating the peer models of its neighbors. It is called
* after this facilitator has constructed appropriate models of the one-hop
* removed peers at those neighbors and performs its work in three steps:
* .
* 1. Send a "Fake Export" message to the upstream object exporter
* requesting that it 'export' the object to the downstream importer.
* 2. Send a "Fake Import" message to the downstream object importer
* requesting that it 'import' the object from the upstream exporter.
* 3. Send a "ReleaseImport" message to the downstream importer requesting
* that it stop importing the object from this process. This message,
* when processed by the downstream peer, will eventually result in a
* ReleaseExport message from the downstream peer absolving this process
* of the export responsibilities it is trying to free itself of.
*
****************************************************************************/
void Vca::VcaProxyFacilitator::delegateProxy (VcaOIDR *pOIDR) {
traceInfo ("\nDelegating Proxy. Calling FakeExport, FakeImport,deleteRemoteImport");
m_pSourcePeer->fakeRemoteExportTo (pOIDR, m_pTargetPeer);
m_pTargetPeer->fakeRemoteImportFrom (pOIDR, m_pSourcePeer);
m_pTargetPeer->deleteRemoteImportOf (pOIDR);
}
| 35.737705
| 89
| 0.613532
|
MichaelJCaruso
|
d6c104fa17fa520526bfcf9bb738caf35463c9d0
| 2,379
|
cpp
|
C++
|
Graph/SmartTravelAgent_mst.cpp
|
Satyabrat35/Programming
|
841ead1bf847b567d8e21963673413cbd65277f4
|
[
"Apache-2.0"
] | null | null | null |
Graph/SmartTravelAgent_mst.cpp
|
Satyabrat35/Programming
|
841ead1bf847b567d8e21963673413cbd65277f4
|
[
"Apache-2.0"
] | null | null | null |
Graph/SmartTravelAgent_mst.cpp
|
Satyabrat35/Programming
|
841ead1bf847b567d8e21963673413cbd65277f4
|
[
"Apache-2.0"
] | null | null | null |
/**************erik****************/
#include<bits/stdc++.h>
#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long int ll;
typedef unsigned long long int ull;
//map<ll,ll> mp1;
//set<int> s1;
//set<int>::iterator it;
#define maxm(a,b,c) max(a,max(c,b))
#define minm(a,b,c) min(a,min(c,b))
#define f(i,n) for(int i=1;i<n;i++)
#define rf(i,n) for(int i=n-1;i>=0;i--)
const int MAX = 10005;
int arr[MAX];
int val[MAX][MAX];
int parent[MAX];
pair<int,pair<int,int>> p[MAX];
pair<int,int> sp[MAX];
vector<int> vec[MAX];
bool vis[MAX];
queue<int> q;
int n,m,start,dest,value,ct=0;
void initialize(int n){
for(int i=1;i<=n;i++){
arr[i]=i;
}
}
void dfs(int x){
vis[x]=1;
for(int i=0;i<vec[x].size();i++){
if(vis[vec[x][i]]==0){
parent[vec[x][i]]=x;
dfs(vec[x][i]);
}
}
}
void par_chk(int source,int dest){
if(parent[dest]!=source){
int zz = parent[dest];
sp[ct] = make_pair(zz,val[zz][dest]);
ct++;
par_chk(source,zz);
}
}
int root(int x){
while(arr[x] != x){
arr[x] = arr[arr[x]];
x = arr[x];
}
return x;
}
bool find(int x,int y){
if(root(x)==root(y))
return true;
else
return false;
}
void uniwg(int x,int y){
int root_x = root(x);
int root_y = root(y);
arr[root_x] = arr[root_y];
}
void kruskal(){
int x,y;
for(int i=0;i<m;i++){
x = p[i].second.first;
y = p[i].second.second;
if(root(x)!=root(y)){
vec[x].push_back(y);
vec[y].push_back(x);
val[x][y] = p[i].first;
val[y][x] = p[i].first;
uniwg(x,y);
}
}
}
int main() {
cin>>n>>m;
initialize(n);
memset(vis,0,sizeof(vis));
for(int i=0;i<m;i++){
int x,y,wgt;
cin>>x>>y>>wgt;
p[i] = make_pair(wgt,make_pair(x,y));
}
sort(p,p+m);
reverse(p,p+m);
kruskal();
cin>>start>>dest>>value;
vis[start]=0;
dfs(start);
par_chk(start,dest);
int mn = 1e9;
cout<<start<<" ";
for(int i=ct-1;i>=0;i--){
int stop1 = sp[i].first;
int valz = sp[i].second;
mn = min(valz,mn);
cout<<stop1<<" ";
}
cout<<dest<<endl;
mn--;
float qz = (float)value / (float)mn;
cout<<ceil(qz);
return 0;
}
| 21.432432
| 45
| 0.497268
|
Satyabrat35
|
d6c1056bfef3fed68dadf7c849e6745cab5b1819
| 1,001
|
cpp
|
C++
|
opencl/test/unit_test/mocks/ult_cl_device_factory.cpp
|
8tab/compute-runtime
|
71bd96ad7184df83c7af04ffa8e0d6678ab26f99
|
[
"MIT"
] | 1
|
2020-09-03T17:10:38.000Z
|
2020-09-03T17:10:38.000Z
|
opencl/test/unit_test/mocks/ult_cl_device_factory.cpp
|
8tab/compute-runtime
|
71bd96ad7184df83c7af04ffa8e0d6678ab26f99
|
[
"MIT"
] | null | null | null |
opencl/test/unit_test/mocks/ult_cl_device_factory.cpp
|
8tab/compute-runtime
|
71bd96ad7184df83c7af04ffa8e0d6678ab26f99
|
[
"MIT"
] | null | null | null |
/*
* Copyright (C) 2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "opencl/test/unit_test/mocks/ult_cl_device_factory.h"
#include "shared/test/unit_test/mocks/ult_device_factory.h"
#include "opencl/test/unit_test/mocks/mock_cl_device.h"
using namespace NEO;
UltClDeviceFactory::UltClDeviceFactory(uint32_t rootDevicesCount, uint32_t subDevicesCount) {
auto executionEnvironment = new ClExecutionEnvironment();
pUltDeviceFactory = std::make_unique<UltDeviceFactory>(rootDevicesCount, subDevicesCount, *executionEnvironment);
for (auto &pRootDevice : pUltDeviceFactory->rootDevices) {
auto pRootClDevice = new MockClDevice{pRootDevice};
for (auto &pClSubDevice : pRootClDevice->subDevices) {
subDevices.push_back(pClSubDevice.get());
}
rootDevices.push_back(pRootClDevice);
}
}
UltClDeviceFactory::~UltClDeviceFactory() {
for (auto &pClDevice : rootDevices) {
pClDevice->decRefInternal();
}
}
| 29.441176
| 117
| 0.733267
|
8tab
|
d6cc54b5038fd2b46509fb1f732378ab4a3a6cb1
| 6,704
|
cpp
|
C++
|
export/windows/obj/src/haxe/Utf8.cpp
|
arturspon/zombie-killer
|
07848c5006916e9079537a3d703ffe3740afaa5a
|
[
"MIT"
] | null | null | null |
export/windows/obj/src/haxe/Utf8.cpp
|
arturspon/zombie-killer
|
07848c5006916e9079537a3d703ffe3740afaa5a
|
[
"MIT"
] | null | null | null |
export/windows/obj/src/haxe/Utf8.cpp
|
arturspon/zombie-killer
|
07848c5006916e9079537a3d703ffe3740afaa5a
|
[
"MIT"
] | 1
|
2021-07-16T22:57:01.000Z
|
2021-07-16T22:57:01.000Z
|
// Generated by Haxe 4.0.0-rc.2+77068e10c
#include <hxcpp.h>
#ifndef INCLUDED_haxe_Utf8
#include <haxe/Utf8.h>
#endif
HX_DEFINE_STACK_FRAME(_hx_pos_37807d8ab8df9b7c_31_new,"haxe.Utf8","new",0x67cc940b,"haxe.Utf8.new","C:\\HaxeToolkit\\haxe\\std/cpp/_std/haxe/Utf8.hx",31,0xf320feca)
HX_LOCAL_STACK_FRAME(_hx_pos_37807d8ab8df9b7c_38_addChar,"haxe.Utf8","addChar",0x9a1816c2,"haxe.Utf8.addChar","C:\\HaxeToolkit\\haxe\\std/cpp/_std/haxe/Utf8.hx",38,0xf320feca)
HX_LOCAL_STACK_FRAME(_hx_pos_37807d8ab8df9b7c_42_toString,"haxe.Utf8","toString",0xb459e121,"haxe.Utf8.toString","C:\\HaxeToolkit\\haxe\\std/cpp/_std/haxe/Utf8.hx",42,0xf320feca)
HX_LOCAL_STACK_FRAME(_hx_pos_37807d8ab8df9b7c_66_charCodeAt,"haxe.Utf8","charCodeAt",0xce7cbeab,"haxe.Utf8.charCodeAt","C:\\HaxeToolkit\\haxe\\std/cpp/_std/haxe/Utf8.hx",66,0xf320feca)
HX_LOCAL_STACK_FRAME(_hx_pos_37807d8ab8df9b7c_74_length,"haxe.Utf8","length",0x88322e1b,"haxe.Utf8.length","C:\\HaxeToolkit\\haxe\\std/cpp/_std/haxe/Utf8.hx",74,0xf320feca)
HX_LOCAL_STACK_FRAME(_hx_pos_37807d8ab8df9b7c_78_compare,"haxe.Utf8","compare",0x9f848dd0,"haxe.Utf8.compare","C:\\HaxeToolkit\\haxe\\std/cpp/_std/haxe/Utf8.hx",78,0xf320feca)
HX_LOCAL_STACK_FRAME(_hx_pos_37807d8ab8df9b7c_82_sub,"haxe.Utf8","sub",0x67d06d2b,"haxe.Utf8.sub","C:\\HaxeToolkit\\haxe\\std/cpp/_std/haxe/Utf8.hx",82,0xf320feca)
namespace haxe{
void Utf8_obj::__construct( ::Dynamic size){
HX_STACKFRAME(&_hx_pos_37807d8ab8df9b7c_31_new)
HXLINE( 32) this->__s = ::Array_obj< int >::__new();
HXLINE( 33) bool _hx_tmp;
HXDLIN( 33) if (hx::IsNotNull( size )) {
HXLINE( 33) _hx_tmp = hx::IsGreater( size,0 );
}
else {
HXLINE( 33) _hx_tmp = false;
}
HXDLIN( 33) if (_hx_tmp) {
HXLINE( 34) this->__s->reserve(( (int)(size) ));
}
}
Dynamic Utf8_obj::__CreateEmpty() { return new Utf8_obj; }
void *Utf8_obj::_hx_vtable = 0;
Dynamic Utf8_obj::__Create(hx::DynamicArray inArgs)
{
hx::ObjectPtr< Utf8_obj > _hx_result = new Utf8_obj();
_hx_result->__construct(inArgs[0]);
return _hx_result;
}
bool Utf8_obj::_hx_isInstanceOf(int inClassId) {
return inClassId==(int)0x00000001 || inClassId==(int)0x11cee8b7;
}
void Utf8_obj::addChar(int c){
HX_STACKFRAME(&_hx_pos_37807d8ab8df9b7c_38_addChar)
HXDLIN( 38) this->__s->push(c);
}
HX_DEFINE_DYNAMIC_FUNC1(Utf8_obj,addChar,(void))
::String Utf8_obj::toString(){
HX_STACKFRAME(&_hx_pos_37807d8ab8df9b7c_42_toString)
HXDLIN( 42) return ::__hxcpp_char_array_to_utf8_string(this->__s);
}
HX_DEFINE_DYNAMIC_FUNC0(Utf8_obj,toString,return )
int Utf8_obj::charCodeAt(::String s,int index){
HX_STACKFRAME(&_hx_pos_37807d8ab8df9b7c_66_charCodeAt)
HXDLIN( 66) return _hx_utf8_char_code_at(s,index);
}
STATIC_HX_DEFINE_DYNAMIC_FUNC2(Utf8_obj,charCodeAt,return )
int Utf8_obj::length(::String s){
HX_STACKFRAME(&_hx_pos_37807d8ab8df9b7c_74_length)
HXDLIN( 74) return _hx_utf8_length(s);
}
STATIC_HX_DEFINE_DYNAMIC_FUNC1(Utf8_obj,length,return )
int Utf8_obj::compare(::String a,::String b){
HX_STACKFRAME(&_hx_pos_37807d8ab8df9b7c_78_compare)
HXDLIN( 78) return _hx_string_compare(a,b);
}
STATIC_HX_DEFINE_DYNAMIC_FUNC2(Utf8_obj,compare,return )
::String Utf8_obj::sub(::String s,int pos,int len){
HX_STACKFRAME(&_hx_pos_37807d8ab8df9b7c_82_sub)
HXDLIN( 82) return _hx_utf8_sub(s,pos,len);
}
STATIC_HX_DEFINE_DYNAMIC_FUNC3(Utf8_obj,sub,return )
Utf8_obj::Utf8_obj()
{
}
void Utf8_obj::__Mark(HX_MARK_PARAMS)
{
HX_MARK_BEGIN_CLASS(Utf8);
HX_MARK_MEMBER_NAME(__s,"__s");
HX_MARK_END_CLASS();
}
void Utf8_obj::__Visit(HX_VISIT_PARAMS)
{
HX_VISIT_MEMBER_NAME(__s,"__s");
}
hx::Val Utf8_obj::__Field(const ::String &inName,hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 3:
if (HX_FIELD_EQ(inName,"__s") ) { return hx::Val( __s ); }
break;
case 7:
if (HX_FIELD_EQ(inName,"addChar") ) { return hx::Val( addChar_dyn() ); }
break;
case 8:
if (HX_FIELD_EQ(inName,"toString") ) { return hx::Val( toString_dyn() ); }
}
return super::__Field(inName,inCallProp);
}
bool Utf8_obj::__GetStatic(const ::String &inName, Dynamic &outValue, hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 3:
if (HX_FIELD_EQ(inName,"sub") ) { outValue = sub_dyn(); return true; }
break;
case 6:
if (HX_FIELD_EQ(inName,"length") ) { outValue = length_dyn(); return true; }
break;
case 7:
if (HX_FIELD_EQ(inName,"compare") ) { outValue = compare_dyn(); return true; }
break;
case 10:
if (HX_FIELD_EQ(inName,"charCodeAt") ) { outValue = charCodeAt_dyn(); return true; }
}
return false;
}
hx::Val Utf8_obj::__SetField(const ::String &inName,const hx::Val &inValue,hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 3:
if (HX_FIELD_EQ(inName,"__s") ) { __s=inValue.Cast< ::Array< int > >(); return inValue; }
}
return super::__SetField(inName,inValue,inCallProp);
}
void Utf8_obj::__GetFields(Array< ::String> &outFields)
{
outFields->push(HX_("__s",53,69,48,00));
super::__GetFields(outFields);
};
#ifdef HXCPP_SCRIPTABLE
static hx::StorageInfo Utf8_obj_sMemberStorageInfo[] = {
{hx::fsObject /* ::Array< int > */ ,(int)offsetof(Utf8_obj,__s),HX_("__s",53,69,48,00)},
{ hx::fsUnknown, 0, null()}
};
static hx::StaticInfo *Utf8_obj_sStaticStorageInfo = 0;
#endif
static ::String Utf8_obj_sMemberFields[] = {
HX_("__s",53,69,48,00),
HX_("addChar",97,a1,fc,7d),
HX_("toString",ac,d0,6e,38),
::String(null()) };
hx::Class Utf8_obj::__mClass;
static ::String Utf8_obj_sStaticFields[] = {
HX_("charCodeAt",f6,e6,54,35),
HX_("length",e6,94,07,9f),
HX_("compare",a5,18,69,83),
HX_("sub",80,a9,57,00),
::String(null())
};
void Utf8_obj::__register()
{
Utf8_obj _hx_dummy;
Utf8_obj::_hx_vtable = *(void **)&_hx_dummy;
hx::Static(__mClass) = new hx::Class_obj();
__mClass->mName = HX_("haxe.Utf8",99,32,41,f3);
__mClass->mSuper = &super::__SGetClass();
__mClass->mConstructEmpty = &__CreateEmpty;
__mClass->mConstructArgs = &__Create;
__mClass->mGetStaticField = &Utf8_obj::__GetStatic;
__mClass->mSetStaticField = &hx::Class_obj::SetNoStaticField;
__mClass->mStatics = hx::Class_obj::dupFunctions(Utf8_obj_sStaticFields);
__mClass->mMembers = hx::Class_obj::dupFunctions(Utf8_obj_sMemberFields);
__mClass->mCanCast = hx::TCanCast< Utf8_obj >;
#ifdef HXCPP_SCRIPTABLE
__mClass->mMemberStorageInfo = Utf8_obj_sMemberStorageInfo;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mStaticStorageInfo = Utf8_obj_sStaticStorageInfo;
#endif
hx::_hx_RegisterClass(__mClass->mName, __mClass);
}
} // end namespace haxe
| 32.230769
| 184
| 0.717482
|
arturspon
|
d6d4077878bdf7b27ae363f9c09f59580f36cbb2
| 4,753
|
hpp
|
C++
|
include/cppdevtk/base/posix_signals_watcher_unx.hpp
|
CoSoSys/cppdevtk
|
99d6c3d328c05a55dae54e82fcbedad93d0cfaa0
|
[
"BSL-1.0",
"Apache-2.0"
] | null | null | null |
include/cppdevtk/base/posix_signals_watcher_unx.hpp
|
CoSoSys/cppdevtk
|
99d6c3d328c05a55dae54e82fcbedad93d0cfaa0
|
[
"BSL-1.0",
"Apache-2.0"
] | null | null | null |
include/cppdevtk/base/posix_signals_watcher_unx.hpp
|
CoSoSys/cppdevtk
|
99d6c3d328c05a55dae54e82fcbedad93d0cfaa0
|
[
"BSL-1.0",
"Apache-2.0"
] | null | null | null |
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// \file
///
/// \copyright Copyright (C) 2015 - 2020 CoSoSys Ltd <info@cososys.com>\n
/// Licensed under the Apache License, Version 2.0 (the "License");\n
/// you may not use this file except in compliance with the License.\n
/// You may obtain a copy of the License at\n
/// http://www.apache.org/licenses/LICENSE-2.0\n
/// Unless required by applicable law or agreed to in writing, software\n
/// distributed under the License is distributed on an "AS IS" BASIS,\n
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n
/// See the License for the specific language governing permissions and\n
/// limitations under the License.\n
/// Please see the file COPYING.
///
/// \authors Cristian ANITA <cristian.anita@cososys.com>, <cristian_anita@yahoo.com>
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#ifndef CPPDEVTK_BASE_POSIX_SIGNALS_WATCHER_UNX_HPP_INCLUDED_
#define CPPDEVTK_BASE_POSIX_SIGNALS_WATCHER_UNX_HPP_INCLUDED_
#include "config.hpp"
#if (!CPPDEVTK_PLATFORM_UNIX)
# error "This file is Unix specific!!!"
#endif
#include "socket_pair.hpp"
#include "singletons.hpp"
#include <QtCore/QObject>
#include <QtCore/QSocketNotifier>
#include <QtCore/QString>
#include <csignal>
// non-std extension
#ifndef SIGNULL
#define SIGNULL 0
#else
#if (SIGNULL != 0)
# error "SIGNULL != 0"
#endif
#endif
namespace cppdevtk {
namespace base {
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Templates explicit instantiation.
class PosixSignalsWatcher;
#if (!defined(CPPDEVTK_BASE_POSIX_SIGNALS_WATCHER_UNX_CPP) || CPPDEVTK_COMPILER_CLANG)
CPPDEVTK_BASE_TMPL_EXPL_INST
#endif
template class CPPDEVTK_BASE_API MeyersSingleton<PosixSignalsWatcher>;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// \sa <a href="http://doc.qt.io/qt-5/unix-signals.html">Calling Qt Functions From Unix Signal Handlers</a>
/// \attention A signal argument can not be SIGNULL, SIGKILL or SIGSTOP
class CPPDEVTK_BASE_API PosixSignalsWatcher: public QObject, public MeyersSingleton<PosixSignalsWatcher> {
friend class MeyersSingleton<PosixSignalsWatcher>;
Q_OBJECT
Q_SIGNALS:
void Raised(int sig);
// Convenience signals (corresponding Raised() will be also emitted)
// Termination signals
void SigTerm();
void SigInt();
// Daemon signals
void SigHUp();
void SigChld();
void SigTStp();
void SigTtOu();
void SigTtIn();
// TODO: if needed add other convenience signals here
public Q_SLOTS:
/// \pre \a sig is not watched
/// \note By default no signal is watched.
bool Watch(int sig);
/// \pre \a sig is not watched
/// \remark Restores old signal action
bool Unwatch(int sig);
public:
bool IsWatched(int sig);
private Q_SLOTS:
void QtSignalHandler(int socket);
void Dispatch(int sig);
private:
PosixSignalsWatcher();
~PosixSignalsWatcher();
static bool MakeWriteSocketNonBlocking(int sig);
static bool CloseSocketPair(int sig);
static void PosixSignalHandler(int sig); // nothrow guarantee
static QString GetPosixSignalName(int sig);
// - NSIG is non standard extension but present on all platforms we support
// Please see NSIG on: https://www.gnu.org/software/libc/manual/html_node/Standard-Signals.html#Standard-Signals
static const int kNumSigs_ = NSIG - 1;
// - glibc guarantees that the signal numbers are allocated consecutively (this is not required by std).
// Please see Standard Signals: https://www.gnu.org/software/libc/manual/html_node/Standard-Signals.html#Standard-Signals
// This is why we use arrays.
// - sigaction() prevent the signal from being received from within its own signal handler (unless SA_NODEFER is used).
// But a different signal can interrupt current signal handler if it is not blocked by the signal mask.
// This is why we use a socket pair and a socket notifier for each signal.
static socket_t socketPairs_[kNumSigs_][2]; // socketPairs_[x][0] read, socketPairs_[x][1] write
static QSocketNotifier* socketNotifiers_[kNumSigs_];
static struct sigaction oldSigActions_[kNumSigs_];
};
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Inline functions.
} // namespace base
} // namespace cppdevtk
#endif // CPPDEVTK_BASE_POSIX_SIGNALS_WATCHER_UNX_HPP_INCLUDED_
| 35.470149
| 126
| 0.637492
|
CoSoSys
|
d6d474fa9f74a5839fb55c4fb4a80b55b004b937
| 3,072
|
cpp
|
C++
|
infer/tests/codetoanalyze/cpp/performance/array.cpp
|
sujin0529/infer
|
f08a09d6896ac2a22081ead4830eb86c64af8813
|
[
"MIT"
] | 14,499
|
2015-06-11T16:00:28.000Z
|
2022-03-31T23:43:54.000Z
|
infer/tests/codetoanalyze/cpp/performance/array.cpp
|
sujin0529/infer
|
f08a09d6896ac2a22081ead4830eb86c64af8813
|
[
"MIT"
] | 1,529
|
2015-06-11T16:55:30.000Z
|
2022-03-27T15:59:46.000Z
|
infer/tests/codetoanalyze/cpp/performance/array.cpp
|
sujin0529/infer
|
f08a09d6896ac2a22081ead4830eb86c64af8813
|
[
"MIT"
] | 2,225
|
2015-06-11T16:36:10.000Z
|
2022-03-31T05:16:59.000Z
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <algorithm>
#include <iostream>
#include <iterator>
void array_access_constant() {
float radii[8];
for (int i = 0; i < 4; ++i) {
radii[i * 2] = radii[i];
radii[i * 2 + 1] = radii[i] + 1;
}
}
void array_access_overrun_constant() {
float radii[8];
for (int i = 0; i < 4; ++i) {
radii[i * 2] = radii[i];
radii[i * 2 + 2] = radii[i] + 1;
}
}
void array_access_weird_linear(long (&optionNumerators)[], size_t length) {
for (int j = 0; j < length; ++j) {
if (10 < optionNumerators[j] + 1) {
}
}
}
bool binary_search_log_FN(std::string (&arr)[], size_t length) {
return std::binary_search(arr, arr + length, "x");
}
void fill_linear_FN(std::string (&arr)[], size_t length) {
std::fill(arr, arr + length, "x");
}
void copy_linear_FN(std::string (&arr1)[],
std::string (&arr2)[],
size_t arr1_length) {
std::copy(arr1, arr1 + arr1_length, arr2);
}
void copy_for_linear(std::string (&arr1)[],
std::string (&arr2)[],
size_t arr1_length) {
for (int i = 0; i < arr1_length; ++i) {
arr2[i] = arr1[i];
}
}
// sort_array_template does not exist in the cost-issues file.
// Clang frontend only creates procedures
// when the template is instantiated.
template <size_t N>
void sort_array_template_nlogn(const int (&arr1)[N]) {
std::sort(std::begin(arr1), std::end(arr1));
}
void sort_array_inst_constant() {
int arr1[300];
std::sort(std::begin(arr1), std::end(arr1));
}
void sort_array_nlogn_FN(size_t length) {
std::string arr1[length];
std::sort(arr1, arr1 + length);
}
// expected: O(N)
void array_loop_linear_FN(int (&N)[]) {
int i = 0;
while (i < sizeof(*N) / sizeof(N[0])) {
i++;
}
}
// expected: O(N)
void array_loop_while_while_linear_FN(int (&N)[]) {
int i = 0;
while (i < sizeof(*N) / sizeof(N[0])) {
i++;
}
int j = 0;
while (j < sizeof(*N) / sizeof(N[0])) {
j++;
}
}
// expected: O(N+M)
void array_loop_while_for_linear_FN(int (&N)[], int (&M)[]) {
int i = 0;
while (i < sizeof(*N) / sizeof(N[0])) {
i++;
}
for (int j = 0; j < sizeof(*M) / sizeof(M[0]); j++) {
}
}
// expected: O(N*M)
void array_nested_loop_while_for_FN(int (&N)[], int (&M)[]) {
int i = 0;
while (i < sizeof(*N) / sizeof(N[0])) {
for (int j = 0; j < sizeof(*M) / sizeof(M[0]); j++) {
}
i++;
}
}
int size = 10;
void loop_global_var_size_constant() {
int M[size];
for (int j = 0; j < sizeof(*M) / sizeof(M[0]); j++) {
}
}
// expected: O(N)
void array_nested_loop_while_for_linear_FN(int (&N)[]) {
int i = 0;
while (i < sizeof(*N) / sizeof(N[0])) {
loop_global_var_size_constant();
i++;
}
}
// expected: O(N*M)
void array_nested_loop_for_FN(int (&N)[], int m) {
int i = 0;
while (i < sizeof(*N) / sizeof(N[0])) {
for (int j = 0; j < m; j++) {
}
i++;
}
}
| 21.942857
| 75
| 0.57194
|
sujin0529
|
d6dbe2b458bb202daf066b4258ca621ef81265e3
| 5,335
|
cpp
|
C++
|
Source/DialogSystemEditor/Private/DialogSystemEditor.cpp
|
n3td0g/DialogSystem
|
5c7919c5d69246c3798f2322b08f0c10c736d0dc
|
[
"Apache-2.0"
] | null | null | null |
Source/DialogSystemEditor/Private/DialogSystemEditor.cpp
|
n3td0g/DialogSystem
|
5c7919c5d69246c3798f2322b08f0c10c736d0dc
|
[
"Apache-2.0"
] | null | null | null |
Source/DialogSystemEditor/Private/DialogSystemEditor.cpp
|
n3td0g/DialogSystem
|
5c7919c5d69246c3798f2322b08f0c10c736d0dc
|
[
"Apache-2.0"
] | null | null | null |
#include "DialogSystemEditor.h"
#include "Developer/AssetTools/Public/AssetTypeCategories.h"
#include "Editor/PropertyEditor/Public/PropertyEditorModule.h"
#include "Editor/WorkspaceMenuStructure/Public/WorkspaceMenuStructure.h"
#include "Editor/WorkspaceMenuStructure/Public/WorkspaceMenuStructureModule.h"
#include "ISettingsModule.h"
#include "ThumbnailRendering/ThumbnailManager.h"
#include "QaDSEditor/BrushSet.h"
#include "Dialog/DialogAssetEditor.h"
#include "Quest/QuestAssetEditor.h"
#include "AssetToolsModule.h"
#include "Dialog/DialogAssetTypeActions.h"
#include "Quest/QuestAssetTypeActions.h"
#include "TypeEditorCustomization/PhraseNodeCustomization.h"
#include "TypeEditorCustomization/DialogPhraseEventCustomization.h"
#include "TypeEditorCustomization/QuestStageCustomization.h"
#include "TypeEditorCustomization/QuestStageEventCustomization.h"
#include "QaDSSettings.h"
#include "Quest/QuestEditorNodeFactory.h"
#include "EdGraphUtilities.h"
#include "StoryKey/StoryKeyWindow.h"
DEFINE_LOG_CATEGORY(DialogModuleLog)
#define LOCTEXT_NAMESPACE "FDialogSystemModule"
void FDialogSystemEditorModule::StartupModule()
{
FBrushSet::Register();
FDialogCommands::Register();
FQuestCommands::Register();
auto& AssetTools = FModuleManager::LoadModuleChecked<FAssetToolsModule>("AssetTools").Get();
AssetCategory = AssetTools.RegisterAdvancedAssetCategory(FName(TEXT("Gameplay")), LOCTEXT("GameplayAssetCategory", "Gameplay"));
AssetTools.RegisterAssetTypeActions(MakeShareable(new FDialogAssetTypeActions(AssetCategory)));
AssetTools.RegisterAssetTypeActions(MakeShareable(new FQuestAssetTypeActions(AssetCategory)));
auto& PropertyModule = FModuleManager::LoadModuleChecked<FPropertyEditorModule>("PropertyEditor");
PropertyModule.RegisterCustomClassLayout("DialogPhraseEdGraphNode", FOnGetDetailCustomizationInstance::CreateStatic(&FPhraseNodeDetails::MakeInstance));
PropertyModule.RegisterCustomPropertyTypeLayout("DialogPhraseEvent", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FDialogPhraseEventCustomization::MakeInstance));
PropertyModule.RegisterCustomPropertyTypeLayout("DialogPhraseCondition", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FDialogPhraseEventCustomization::MakeInstance));
PropertyModule.RegisterCustomClassLayout("QuestStageEdGraphNode", FOnGetDetailCustomizationInstance::CreateStatic(&FQuestStageDetails::MakeInstance));
PropertyModule.RegisterCustomPropertyTypeLayout("QuestStageEvent", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FQuestStageEventCustomization::MakeInstance));
PropertyModule.RegisterCustomPropertyTypeLayout("QuestStageCondition", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FQuestStageEventCustomization::MakeInstance));
auto& SettingsModule = FModuleManager::LoadModuleChecked<ISettingsModule>("Settings");
SettingsModule.RegisterSettings("Project", "Plugins", "Dialog",
LOCTEXT("RuntimeSettingsName", "Dialog Editor"),
LOCTEXT("RuntimeSettingsDescription", "Dialog editor settings"),
UQaDSSettings::StaticClass()->GetDefaultObject()
);
FEdGraphUtilities::RegisterVisualNodeFactory(MakeShareable(new FQuestEditorNodeFactory));
FEdGraphUtilities::RegisterVisualNodeFactory(MakeShareable(new FDialogEditorNodeFactory));
auto& MenuStructure = WorkspaceMenu::GetMenuStructure();
auto developerCategory = MenuStructure.GetDeveloperToolsMiscCategory();
auto& SpawnerEntry = FGlobalTabmanager::Get()->RegisterNomadTabSpawner("StoryKeyWindow", FOnSpawnTab::CreateRaw(this, &FDialogSystemEditorModule::SpawnStoryKeyTab))
.SetDisplayName(LOCTEXT("StoryKey", "Story Key"))
.SetIcon(FSlateIcon("DialogSystem", "DialogSystem.StoryKeyIcon_16"));
SpawnerEntry.SetGroup(developerCategory);
}
void FDialogSystemEditorModule::ShutdownModule()
{
FDialogCommands::Unregister();
FBrushSet::Unregister();
if (FModuleManager::Get().IsModuleLoaded("Settings"))
{
auto& SettingsModule = FModuleManager::LoadModuleChecked<ISettingsModule>("Settings");
SettingsModule.UnregisterSettings("Project", "Plugins", "Dialog");
}
if (FModuleManager::Get().IsModuleLoaded("PropertyEditor"))
{
auto& PropertyModule = FModuleManager::LoadModuleChecked<FPropertyEditorModule>("PropertyEditor");
PropertyModule.UnregisterCustomClassLayout("DialogPhraseNode");
PropertyModule.UnregisterCustomPropertyTypeLayout("DialogPhraseEvent");
PropertyModule.UnregisterCustomPropertyTypeLayout("DialogPhraseCondition");
PropertyModule.UnregisterCustomClassLayout("QuestStageEdGraphNode");
PropertyModule.UnregisterCustomPropertyTypeLayout("QuestStageEvent");
PropertyModule.UnregisterCustomPropertyTypeLayout("QuestStageCondition");
}
if (FModuleManager::Get().IsModuleLoaded("AssetTools"))
{
auto& AssetTools = FModuleManager::LoadModuleChecked<FAssetToolsModule>("AssetTools").Get();
AssetTools.UnregisterAssetTypeActions(MakeShareable(new FDialogAssetTypeActions(AssetCategory)));
AssetTools.UnregisterAssetTypeActions(MakeShareable(new FQuestAssetTypeActions(AssetCategory)));
}
}
TSharedRef<SDockTab> FDialogSystemEditorModule::SpawnStoryKeyTab(const FSpawnTabArgs&)
{
TSharedRef<SDockTab> tab = SNew(SDockTab)
.TabRole(ETabRole::NomadTab);
tab->SetContent(SNew(SStoryKeyWindow));
return tab;
}
#undef LOCTEXT_NAMESPACE
IMPLEMENT_MODULE(FDialogSystemEditorModule, DialogSystemEditor)
| 48.063063
| 177
| 0.837863
|
n3td0g
|
d6e39e70fae327912f6873c30dbdedebf5e06f51
| 21,363
|
cpp
|
C++
|
src/prod/src/Common/NamingUri.cpp
|
AnthonyM/service-fabric
|
c396ea918714ea52eab9c94fd62e018cc2e09a68
|
[
"MIT"
] | 1
|
2018-03-15T02:09:21.000Z
|
2018-03-15T02:09:21.000Z
|
src/prod/src/Common/NamingUri.cpp
|
AnthonyM/service-fabric
|
c396ea918714ea52eab9c94fd62e018cc2e09a68
|
[
"MIT"
] | null | null | null |
src/prod/src/Common/NamingUri.cpp
|
AnthonyM/service-fabric
|
c396ea918714ea52eab9c94fd62e018cc2e09a68
|
[
"MIT"
] | null | null | null |
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#include "stdafx.h"
using namespace std;
namespace Common
{
GlobalWString NamingUri::NameUriScheme = make_global<std::wstring>(L"fabric");
GlobalWString NamingUri::RootAuthority = make_global<std::wstring>(L"");
GlobalWString NamingUri::RootNamingUriString = make_global<std::wstring>(L"fabric:");
GlobalWString NamingUri::InvalidRootNamingUriString = make_global<std::wstring>(L"fabric://");
GlobalWString NamingUri::NamingUriConcatenationReservedTokenDelimiter = make_global<std::wstring>(L"+");
// All reserved token delimiters should be listed here.
GlobalWString NamingUri::ReservedTokenDelimiters = make_global<std::wstring>(L"$+|~");
Global<NamingUri> NamingUri::RootNamingUri = make_global<NamingUri>(L"");
GlobalWString NamingUri::SegmentDelimiter = make_global<std::wstring>(L"/");
GlobalWString NamingUri::HierarchicalNameDelimiter = make_global<std::wstring>(L"~");
NamingUri::NamingUri(
std::wstring const & scheme,
std::wstring const & authority,
std::wstring const & path,
std::wstring const & query,
std::wstring const & fragment)
: Uri(scheme, authority, path, query, fragment)
{
ASSERT_IFNOT(IsNamingUri(*this), "Invalid naming uri");
}
NamingUri NamingUri::GetAuthorityName() const
{
return Segments.empty() ? NamingUri() : NamingUri(Segments[0]);
}
NamingUri NamingUri::GetParentName() const
{
if (Path.empty())
{
return NamingUri::RootNamingUri;
}
size_t index = Path.find_last_of(L"/");
ASSERT_IF(index == wstring::npos, "No / in path?");
wstring truncPath = Path.substr(0, index);
return NamingUri(truncPath);
}
NamingUri NamingUri::GetTrimQueryAndFragmentName() const
{
if (this->Query.empty() && this->Fragment.empty())
{
return *this;
}
else
{
return NamingUri(this->Path);
}
}
size_t NamingUri::GetHash() const
{
return StringUtility::GetHash(this->ToString());
}
size_t NamingUri::GetTrimQueryAndFragmentHash() const
{
return StringUtility::GetHash(this->GetTrimQueryAndFragment().ToString());
}
bool NamingUri::IsPrefixOf(NamingUri const & other) const
{
return Uri::IsPrefixOf(other);
}
bool NamingUri::TryParse(std::wstring const & input, __out NamingUri & output)
{
if (StringUtility::StartsWith<std::wstring>(input, InvalidRootNamingUriString))
{
Trace.WriteWarning(
Uri::TraceCategory,
"NamingUri '{0}' is invalid: authorities are not supported.",
input);
return false;
}
NamingUri uri;
if (Uri::TryParse(input, uri) && IsNamingUri(uri))
{
output = std::move(uri);
return true;
}
return false;
}
bool NamingUri::TryParse(FABRIC_URI name, __out NamingUri & output)
{
if (name == NULL)
{
Trace.WriteWarning(Uri::TraceCategory, "Invalid NULL parameter: FABRIC_URI.");
return false;
}
std::wstring tempName(name);
return NamingUri::TryParse(tempName, /*out*/output);
}
HRESULT NamingUri::TryParse(
FABRIC_URI name,
std::wstring const & traceId,
__out NamingUri & nameUri)
{
// Validate and parse the input name pointer
if (name == NULL)
{
Trace.WriteWarning(Uri::TraceCategory, traceId, "Invalid NULL parameter: name.");
return E_POINTER;
}
auto error = ParameterValidator::IsValid(
name,
ParameterValidator::MinStringSize,
CommonConfig::GetConfig().MaxNamingUriLength);
if (!error.IsSuccess())
{
Trace.WriteWarning(
Uri::TraceCategory,
traceId,
"Input uri doesn't respect parameter size limits ({0}-{1}).",
ParameterValidator::MinStringSize,
CommonConfig::GetConfig().MaxNamingUriLength);
return error.ToHResult();
}
std::wstring tempName(name);
if (!NamingUri::TryParse(tempName, /*out*/nameUri))
{
Trace.WriteWarning(Uri::TraceCategory, traceId, "{0}: Input uri is not a valid naming uri.", tempName);
return FABRIC_E_INVALID_NAME_URI;
}
return S_OK;
}
ErrorCode NamingUri::TryParse(
FABRIC_URI name,
StringLiteral const & parameterName,
__inout NamingUri & nameUri)
{
// Validate and parse the input name pointer
if (name == NULL)
{
ErrorCode innerError(ErrorCodeValue::ArgumentNull, wformatString("{0} {1}.", GET_COMMON_RC(Invalid_Null_Pointer), parameterName));
Trace.WriteWarning(Uri::TraceCategory, "NamingUri::TryParse: {0}: {1}", innerError, innerError.Message);
return innerError;
}
auto error = ParameterValidator::IsValid(
name,
ParameterValidator::MinStringSize,
CommonConfig::GetConfig().MaxNamingUriLength);
if (!error.IsSuccess())
{
ErrorCode innerError(
ErrorCodeValue::InvalidArgument,
wformatString("{0} {1}, {2}, {3}.", GET_COMMON_RC(Invalid_LPCWSTR_Length), parameterName, ParameterValidator::MinStringSize, CommonConfig::GetConfig().MaxNamingUriLength));
Trace.WriteWarning(Uri::TraceCategory, "NamingUri::TryParse: {0}: {1}", innerError, innerError.Message);
return innerError;
}
std::wstring tempName(name);
if (!NamingUri::TryParse(tempName, /*out*/nameUri))
{
ErrorCode innerError(ErrorCodeValue::InvalidNameUri, wformatString("{0} {1}.", GET_NAMING_RC(Invalid_Uri), tempName));
Trace.WriteWarning(Uri::TraceCategory, "NamingUri::TryParse: {0}: {1}", innerError, innerError.Message);
return innerError;
}
return ErrorCode::Success();
}
ErrorCode NamingUri::TryParse(
std::wstring const & nameText,
std::wstring const & traceId,
__out NamingUri & nameUri)
{
auto error = ParameterValidator::IsValid(
nameText.c_str(),
ParameterValidator::MinStringSize,
CommonConfig::GetConfig().MaxNamingUriLength);
if (!error.IsSuccess())
{
ErrorCode innerError(ErrorCodeValue::InvalidNameUri, wformatString(
"{0} {1} {2}, {3}.",
GET_COMMON_RC(Invalid_LPCWSTR_Length),
nameText,
ParameterValidator::MinStringSize,
CommonConfig::GetConfig().MaxNamingUriLength));
Trace.WriteInfo(Uri::TraceCategory, traceId, "NamingUri::TryParse: {0}: {1}", innerError, innerError.Message);
return innerError;
}
if (!TryParse(nameText, nameUri))
{
ErrorCode innerError(ErrorCodeValue::InvalidNameUri, wformatString("{0} {1}.", GET_NAMING_RC(Invalid_Uri), nameText));
Trace.WriteWarning(Uri::TraceCategory, traceId, "NamingUri::TryParse: {0}: {1}", innerError, innerError.Message);
return innerError;
}
return ErrorCode::Success();
}
bool NamingUri::IsNamingUri(Uri const & question)
{
if (question.Scheme != NameUriScheme)
{
Trace.WriteWarning(
Uri::TraceCategory,
"NamingUri '{0}' has invalid scheme: supported scheme is 'fabric:'.",
question);
return false;
}
if ((question.Type != UriType::Absolute) && (question.Type != UriType::Empty))
{
Trace.WriteWarning(
Uri::TraceCategory,
"NamingUri '{0}' is invalid: 'fabric:' scheme requires absolute path.",
question);
return false;
}
// Disallow empty segments
if (StringUtility::Contains<wstring>(question.Path, L"//"))
{
Trace.WriteWarning(
Uri::TraceCategory,
"NamingUri '{0}' is invalid: empty segments in path are not supported.",
question);
return false;
}
// List of reserved characters
for (auto delimiterIt = ReservedTokenDelimiters->begin(); delimiterIt != ReservedTokenDelimiters->end(); ++delimiterIt)
{
wstring delimiter = wformatString("{0}", *delimiterIt);
if (StringUtility::Contains<wstring>(question.Path, delimiter))
{
Trace.WriteWarning(
Uri::TraceCategory,
"NamingUri '{0}' is invalid: '{1}' is a reserved character.",
question,
delimiter);
return false;
}
}
// Disallow trailing slash
if ((question.Path.size() > 0) && (question.Path[question.Path.size() - 1] == L'/'))
{
Trace.WriteWarning(
Uri::TraceCategory,
"NamingUri '{0}' is invalid: trailing '/' is not supported.",
question);
return false;
}
return true;
}
bool NamingUri::TryCombine(std::wstring const & path, __out NamingUri & result) const
{
wstring temp(this->ToString());
if (!path.empty())
{
temp.append(L"/");
temp.append(path);
}
NamingUri uri;
if (TryParse(temp, uri))
{
result = move(uri);
return true;
}
return false;
}
NamingUri NamingUri::Combine(NamingUri const & name, wstring const & path)
{
NamingUri result;
if (!name.TryCombine(path, result))
{
Assert::CodingError("could not combine {0} and {1} into a Naming Uri", name, path);
}
return result;
}
ErrorCode NamingUri::FabricNameToId(std::wstring const & name, __inout std::wstring &escapedId)
{
std::wstring temp = name;
StringUtility::TrimLeading<std::wstring>(temp, NamingUri::RootNamingUriString);
StringUtility::TrimLeading<std::wstring>(temp, NamingUri::SegmentDelimiter);
return EscapeString(temp, escapedId);
}
ErrorCode NamingUri::FabricNameToId(std::wstring const & name, bool useDelimiter, __inout std::wstring &escapedId)
{
std::wstring temp = name;
std::wstring tempId;
NamingUri::FabricNameToId(temp, tempId);
if (useDelimiter)
{
StringUtility::Replace<std::wstring>(tempId, NamingUri::SegmentDelimiter, NamingUri::HierarchicalNameDelimiter);
}
return EscapeString(tempId, escapedId);
}
ErrorCode NamingUri::IdToFabricName(std::wstring const& scheme, std::wstring const& id, __inout std::wstring &name)
{
ASSERT_IF(scheme.empty(), "IdToFabricName - scheme cannot be empty");
std::wstring escapedId;
auto error = UnescapeString(id, escapedId);
if (!error.IsSuccess())
{
return error;
}
StringUtility::Replace<std::wstring>(escapedId, NamingUri::HierarchicalNameDelimiter, NamingUri::SegmentDelimiter);
name = wformatString("{0}{1}{2}", scheme, *NamingUri::SegmentDelimiter, escapedId);
return ErrorCode::Success();
}
void NamingUri::ParseHost(std::wstring & input, std::wstring & host, std::wstring & remain)
{
input = input.substr(1, std::string::npos);
std::size_t nextFound = remain.find(L"/");
if (nextFound == std::string::npos)
{
nextFound = remain.find(L"?");
if (nextFound == std::string::npos)
{
nextFound = remain.find(L"#");
if (nextFound == std::string::npos)
{
nextFound = input.length();
}
}
}
host = L"/";
host = host + input.substr(0, nextFound);
remain = input.substr(nextFound, std::string::npos);
}
void NamingUri::ParsePath(std::wstring & input, std::wstring & path, std::wstring & remain)
{
std::size_t nextFound = remain.find(L"?");
if (nextFound == std::string::npos)
{
nextFound = remain.find(L"#");
if (nextFound == std::string::npos)
{
nextFound = input.length();
}
}
path = input.substr(0, nextFound);
remain = input.substr(nextFound, std::string::npos);
}
ErrorCode NamingUri::ParseUnsafeUri(std::wstring const & input, std::wstring & protocol, std::wstring & host, std::wstring & path, std::wstring & queryFragment)
{
std::size_t protocolFound = input.find(L":/");
std::wstring remain;
if (protocolFound != std::string::npos)
{
protocol = input.substr(0, protocolFound + 2);
remain = input.substr(protocolFound + 2, std::string::npos);
}
else
{
remain = input;
}
// Has host
if (remain.length() > 0 && *(remain.begin()) == '/')
{
ParseHost(remain, host, remain);
}
ParsePath(remain, path, remain);
queryFragment = remain;
return ErrorCodeValue::Success;
}
ErrorCode NamingUri::EscapeString(std::wstring const & input, __inout std::wstring &output)
{
#if defined(PLATFORM_UNIX)
std::wstring protocol;
std::wstring host;
std::wstring path;
std::wstring queryFragment;
ErrorCode result = ParseUnsafeUri(input, protocol, host, path, queryFragment);
std::string pathString;
StringUtility::Utf16ToUtf8(path, pathString);
static const char lookup[] = "0123456789ABCDEF";
std::ostringstream out;
for (std::string::size_type i = 0; i < pathString.length(); i++) {
const char& c = pathString.at(i);
if (c == '[' ||
c == ']' ||
c == '&' ||
c == '^' ||
c == '`' ||
c == '{' ||
c == '}' ||
c == '|' ||
c == '"' ||
c == '<' ||
c == '>' ||
c == '\\' ||
c == ' ')
{
out << '%';
out << lookup[(c & 0xF0) >> 4];
out << lookup[(c & 0x0F)];
}
else
{
out << c;
}
}
std::wstring pathEscape;
StringUtility::Utf8ToUtf16(out.str(), pathEscape);
output = protocol + host + pathEscape + queryFragment;
#else
DWORD size = 1;
std::vector<WCHAR> buffer;
buffer.resize(size);
HRESULT hr = UrlEscape(const_cast<WCHAR*>(input.data()), buffer.data(), &size, URL_ESCAPE_AS_UTF8);
if (FAILED(hr) && hr == E_POINTER)
{
buffer.resize(size);
hr = UrlEscape(const_cast<WCHAR*>(input.data()), buffer.data(), &size, URL_ESCAPE_AS_UTF8);
if (FAILED(hr))
{
return ErrorCode::FromHResult(hr);
}
output = buffer.data();
}
else
{
return ErrorCode::FromHResult(hr);
}
#endif
return ErrorCodeValue::Success;
}
ErrorCode NamingUri::UnescapeString(std::wstring const& input, __inout std::wstring& output)
{
#if defined(PLATFORM_UNIX)
std::wstring protocol;
std::wstring host;
std::wstring path;
std::wstring queryFragment;
ErrorCode result = ParseUnsafeUri(input, protocol, host, path, queryFragment);
std::ostringstream out;
std::string pathString;
StringUtility::Utf16ToUtf8(path, pathString);
for (std::string::size_type i = 0; i < pathString.length(); i++) {
if (pathString.at(i) == '%') {
std::string temp(pathString.substr(i + 1, 2));
std::istringstream in(temp);
short c = 0;
in >> std::hex >> c;
out << static_cast<unsigned char>(c);
i += 2;
}
else {
out << pathString.at(i);
}
}
std::wstring pathUnescape;
StringUtility::Utf8ToUtf16(out.str(), pathUnescape);
output = protocol + host + pathUnescape + queryFragment;
#else
DWORD size = 1;
std::vector<WCHAR> buffer;
buffer.resize(size);
HRESULT hr = UrlUnescape(const_cast<WCHAR*>(input.data()), buffer.data(), &size, URL_UNESCAPE_AS_UTF8);
if (FAILED(hr) && hr == E_POINTER)
{
buffer.resize(size);
hr = UrlUnescape(const_cast<WCHAR*>(input.data()), buffer.data(), &size, URL_UNESCAPE_AS_UTF8);
if (FAILED(hr))
{
return ErrorCodeValue::InvalidNameUri;
}
output = buffer.data();
}
else
{
return ErrorCodeValue::InvalidNameUri;
}
#endif
return ErrorCode::Success();
}
ErrorCode NamingUri::UrlEscapeString(std::wstring const & input, std::wstring & output)
{
// Clear the output because we are appending to it.
output.clear();
wstring basicEncodedStr;
// First call escape string
auto error = NamingUri::EscapeString(input, basicEncodedStr);
// If escape returns an error, then return that error
if (!error.IsSuccess())
{
return error;
}
// Replace chars with their encodings by appending
// either the original char or its replacement to the output string
// comma(",")
// colon(":")
// dollar("$")
// plus sign("+")
// semi - colon(";")
// equals("=")
// 'At' symbol("@")
//
// ampersand ("&")
// forward slash("/")
// question mark("?")
// pound("#")
// less than and greater than("<>")
// open and close brackets("[]")
// open and close braces("{}")
// pipe("|")
// backslash("\")
// caret("^")
// space(" ")
// percent ("%") is not encoded here because it cannot be encoded twice.
for (wchar_t c : basicEncodedStr)
{
if (c == L',') // ,
{
output += L"%2C";
}
else if (c == L':') // :
{
output += L"%3A";
}
else if (c == L'$') // $
{
output += L"%24";
}
else if (c == L'+') // +
{
output += L"%2B";
}
else if (c == L';') // ;
{
output += L"%3B";
}
else if (c == L'=') // =
{
output += L"%3D";
}
else if (c == L'@') // @
{
output += L"%40";
} // The following may never be called since EscapeString may have already taken care of them (OS dependent)
else if (c == L'&') // &
{
output += L"%26";
}
else if (c == L'/') // / (forward slash)
{
output += L"%2F";
}
else if (c == L'\\') // back slash
{
output += L"%5C";
}
else if (c == L'?') // ?
{
output += L"%3F";
}
else if (c == L'#') // #
{
output += L"%23";
}
else if (c == L'<') // <
{
output += L"%3C";
}
else if (c == L'>') // >
{
output += L"%3E";
}
else if (c == L'[') // [
{
output += L"%5B";
}
else if (c == L']') // ]
{
output += L"%5D";
}
else if (c == L'{') // {
{
output += L"%7B";
}
else if (c == L'}') // }
{
output += L"%7D";
}
else if (c == L'|') // |
{
output += L"%7C";
}
else if (c == L'^') // ^
{
output += L"%5E";
}
else if (c == L' ') // space
{
output += L"%20";
}
else
{
output += c;
}
}
return ErrorCode::Success();
}
}
| 32.368182
| 188
| 0.509011
|
AnthonyM
|
d6eb8f831c53eadf73c7a302ff50b2fa9423ce2c
| 1,385
|
cpp
|
C++
|
game/game/definitions/visualfxdefinitions.cpp
|
houkama/OpenGothic
|
0a5e429bc1fd370259abe8664f19dc9e365ecac5
|
[
"MIT"
] | 576
|
2019-07-22T19:14:33.000Z
|
2022-03-31T22:27:28.000Z
|
game/game/definitions/visualfxdefinitions.cpp
|
houkama/OpenGothic
|
0a5e429bc1fd370259abe8664f19dc9e365ecac5
|
[
"MIT"
] | 208
|
2019-07-22T17:25:30.000Z
|
2022-03-14T18:53:06.000Z
|
game/game/definitions/visualfxdefinitions.cpp
|
houkama/OpenGothic
|
0a5e429bc1fd370259abe8664f19dc9e365ecac5
|
[
"MIT"
] | 67
|
2019-10-14T19:39:38.000Z
|
2022-01-27T13:58:03.000Z
|
#include "visualfxdefinitions.h"
#include <Tempest/Log>
#include "graphics/visualfx.h"
#include "gothic.h"
using namespace Tempest;
VisualFxDefinitions::VisualFxDefinitions() {
vm = Gothic::inst().createVm("VisualFx.dat");
}
VisualFxDefinitions::~VisualFxDefinitions() {
vm->clearReferences(Daedalus::IC_Pfx);
}
const VisualFx* VisualFxDefinitions::get(std::string_view name) {
std::string cname = std::string(name);
auto it = vfx.find(cname);
if(it!=vfx.end())
return it->second.get();
Daedalus::GEngineClasses::CFx_Base def;
if(!implGet(cname,def))
return nullptr;
auto ret = vfx.insert(std::make_pair<std::string,std::unique_ptr<VisualFx>>(std::move(cname),nullptr));
ret.first->second.reset(new VisualFx(def,*vm,name));
auto& vfx = *ret.first->second;
vfx.dbgName = name.data();
return &vfx;
}
bool VisualFxDefinitions::implGet(std::string_view name,
Daedalus::GEngineClasses::CFx_Base& ret) {
if(!vm || name.empty())
return false;
char buf[256] = {};
std::snprintf(buf,sizeof(buf),"%.*s",int(name.size()),name.data());
auto id = vm->getDATFile().getSymbolIndexByName(buf);
if(id==size_t(-1)) {
Log::e("invalid visual effect: \"",buf,"\"");
return false;
}
vm->initializeInstance(ret, id, Daedalus::IC_Vfx);
vm->clearReferences(Daedalus::IC_Vfx);
return true;
}
| 25.648148
| 105
| 0.66426
|
houkama
|
d6eee2708dbb00fd305fc1cc4b9964a38cf58567
| 1,332
|
cpp
|
C++
|
code/engine.vc2008/xrCore/DateTime.cpp
|
icetorch2001/xray-oxygen
|
8c210ac2824f794cea69266048fe12d584ee3f04
|
[
"Apache-2.0"
] | 1
|
2021-09-14T14:28:56.000Z
|
2021-09-14T14:28:56.000Z
|
code/engine.vc2008/xrCore/DateTime.cpp
|
icetorch2001/xray-oxygen
|
8c210ac2824f794cea69266048fe12d584ee3f04
|
[
"Apache-2.0"
] | null | null | null |
code/engine.vc2008/xrCore/DateTime.cpp
|
icetorch2001/xray-oxygen
|
8c210ac2824f794cea69266048fe12d584ee3f04
|
[
"Apache-2.0"
] | 3
|
2021-11-01T06:21:26.000Z
|
2022-01-08T16:13:23.000Z
|
#include "stdafx.h"
#include "DateTime.hpp"
Time::Time()
{
t = time(nullptr);
aTm = *localtime(&t);
}
Time::Time(time_t InTime)
: t(InTime)
{
aTm = *localtime(&t);
}
int Time::GetSeconds() const
{
return aTm.tm_sec;
}
int Time::GetMinutes() const
{
return aTm.tm_min;
}
int Time::GetHours() const
{
return aTm.tm_hour;
}
int Time::GetDay() const
{
return aTm.tm_mday;
}
int Time::GetMonth() const
{
return aTm.tm_mon + 1;
}
int Time::GetYear() const
{
return aTm.tm_year + 1900;
}
Time::string Time::GetSecondsString() const
{
return (GetSeconds() < 10) ? "0" + xr_string::ToString(GetSeconds()) : xr_string::ToString(GetSeconds());
}
Time::string Time::GetMinutesString() const
{
return (GetMinutes() < 10) ? "0" + xr_string::ToString(GetMinutes()) : xr_string::ToString(GetMinutes());
}
Time::string Time::GetHoursString() const
{
return (GetHours() < 10) ? "0" + xr_string::ToString(GetHours()) : xr_string::ToString(GetHours());
}
Time::string Time::GetDayString() const
{
return (GetDay() < 10) ? "0" + xr_string::ToString(GetDay()) : xr_string::ToString(GetDay());
}
Time::string Time::GetMonthString() const
{
return (GetMonth() < 10) ? "0" + xr_string::ToString(GetMonth()) : xr_string::ToString(GetMonth());
}
Time::string Time::GetYearString() const
{
return xr_string::ToString(GetYear());
}
| 18
| 106
| 0.671171
|
icetorch2001
|
d6f089d99a397f8a5e7b624930a39dc86f3b8f0a
| 3,682
|
cpp
|
C++
|
004_Metalights Improved Interleaved Shading/SplitGBufferPass.cpp
|
Mr-Devin/GraphicAlgorithm
|
58877e6a8dba75ab171b0d89260defaffa22d047
|
[
"MIT"
] | 1
|
2021-11-16T11:40:04.000Z
|
2021-11-16T11:40:04.000Z
|
004_Metalights Improved Interleaved Shading/SplitGBufferPass.cpp
|
younha169/GraphicAlgorithm
|
93287ae4d4171764e788371887c4fd1549304552
|
[
"MIT"
] | null | null | null |
004_Metalights Improved Interleaved Shading/SplitGBufferPass.cpp
|
younha169/GraphicAlgorithm
|
93287ae4d4171764e788371887c4fd1549304552
|
[
"MIT"
] | null | null | null |
#include "SplitGBufferPass.h"
#include "Interface.h"
#include "Common.h"
#include "Utils.h"
#include "Shader.h"
CSplitGBufferPass::CSplitGBufferPass(const std::string& vPassName, int vExcutionOrder) : IRenderPass(vPassName, vExcutionOrder)
{
}
CSplitGBufferPass::~CSplitGBufferPass()
{
}
void CSplitGBufferPass::initV()
{
auto AlbedoTexture = ElayGraphics::ResourceManager::getSharedDataByName<std::shared_ptr<ElayGraphics::STexture>>("AlbedoTexture");
auto NormalTexture = ElayGraphics::ResourceManager::getSharedDataByName<std::shared_ptr<ElayGraphics::STexture>>("NormalTexture");
auto PositionTexture = ElayGraphics::ResourceManager::getSharedDataByName<std::shared_ptr<ElayGraphics::STexture>>("PositionTexture");
auto TextureConfig4Albedo = std::make_shared<ElayGraphics::STexture>();
auto TextureConfig4Normal = std::make_shared<ElayGraphics::STexture>();
auto TextureConfig4Position = std::make_shared<ElayGraphics::STexture>();
TextureConfig4Albedo->InternalFormat = TextureConfig4Normal->InternalFormat = TextureConfig4Position->InternalFormat = GL_RGBA32F;
TextureConfig4Albedo->ExternalFormat = TextureConfig4Normal->ExternalFormat = TextureConfig4Position->ExternalFormat = GL_RGBA;
TextureConfig4Albedo->DataType = TextureConfig4Normal->DataType = TextureConfig4Position->DataType = GL_FLOAT;
TextureConfig4Albedo->Type4MinFilter = TextureConfig4Normal->Type4MinFilter = TextureConfig4Position->Type4MinFilter = GL_LINEAR;
TextureConfig4Albedo->Type4MagFilter = TextureConfig4Normal->Type4MagFilter = TextureConfig4Position->Type4MagFilter = GL_LINEAR;
TextureConfig4Albedo->ImageBindUnit= 0;
TextureConfig4Normal->ImageBindUnit = 1;
TextureConfig4Position->ImageBindUnit = 2;
genTexture(TextureConfig4Albedo);
genTexture(TextureConfig4Normal);
genTexture(TextureConfig4Position);
m_pShader = std::make_shared<CShader>("SplitGBuffer_CS.glsl");
m_pShader->activeShader();
m_pShader->setTextureUniformValue("u_InputAlbedoTexture", AlbedoTexture);
m_pShader->setTextureUniformValue("u_InputNormalTexture", NormalTexture);
m_pShader->setTextureUniformValue("u_InputPositionTexture", PositionTexture);
m_pShader->setIntUniformValue("u_WindowWidth", ElayGraphics::WINDOW_KEYWORD::getWindowWidth());
m_pShader->setIntUniformValue("u_WindowHeight", ElayGraphics::WINDOW_KEYWORD::getWindowHeight());
m_pShader->setIntUniformValue("u_SubBufferNumX", m_SubBufferNumX);
m_pShader->setIntUniformValue("u_SubBufferNumY", m_SubBufferNumY);
m_pShader->setImageUniformValue(TextureConfig4Albedo);
m_pShader->setImageUniformValue(TextureConfig4Normal);
m_pShader->setImageUniformValue(TextureConfig4Position);
std::vector<int> LocalGroupSize;
m_pShader->InquireLocalGroupSize(LocalGroupSize);
m_GlobalGroupSize.push_back((ElayGraphics::WINDOW_KEYWORD::getWindowWidth() + LocalGroupSize[0] - 1) / LocalGroupSize[0]);
m_GlobalGroupSize.push_back((ElayGraphics::WINDOW_KEYWORD::getWindowHeight() + LocalGroupSize[1] - 1) / LocalGroupSize[1]);
m_GlobalGroupSize.push_back(1);
ElayGraphics::ResourceManager::registerSharedData("SubBufferNumX", m_SubBufferNumX);
ElayGraphics::ResourceManager::registerSharedData("SubBufferNumY", m_SubBufferNumY);
ElayGraphics::ResourceManager::registerSharedData("SplitedAlbedoImage", TextureConfig4Albedo);
ElayGraphics::ResourceManager::registerSharedData("SplitedNormalImage", TextureConfig4Normal);
ElayGraphics::ResourceManager::registerSharedData("SplitedPositionImage", TextureConfig4Position);
}
void CSplitGBufferPass::updateV()
{
m_pShader->activeShader();
glDispatchCompute(m_GlobalGroupSize[0], m_GlobalGroupSize[1], m_GlobalGroupSize[2]);
glMemoryBarrier(GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);
}
| 54.955224
| 135
| 0.828083
|
Mr-Devin
|
d6f2721ece0f2de78fbe13346552ceae479b4c4a
| 373
|
cpp
|
C++
|
tests/testcases/unary.cpp
|
graydon/uint128_t
|
e7d55400adde4fa13008d6f4778ad3514d41aca7
|
[
"MIT"
] | 180
|
2015-02-23T22:18:43.000Z
|
2022-03-12T11:46:31.000Z
|
tests/testcases/unary.cpp
|
graydon/uint128_t
|
e7d55400adde4fa13008d6f4778ad3514d41aca7
|
[
"MIT"
] | 15
|
2017-06-14T13:09:42.000Z
|
2022-01-16T22:25:50.000Z
|
tests/testcases/unary.cpp
|
graydon/uint128_t
|
e7d55400adde4fa13008d6f4778ad3514d41aca7
|
[
"MIT"
] | 52
|
2015-04-08T03:44:06.000Z
|
2022-03-25T14:04:36.000Z
|
#include <gtest/gtest.h>
#include "uint128_t.h"
TEST(Arithmetic, unary_plus){
const uint128_t value(0x12345ULL);
EXPECT_EQ(+value, value);
}
TEST(Arithmetic, unary_minus){
const uint128_t val(1);
const uint128_t neg = -val;
EXPECT_EQ(-val, neg);
EXPECT_EQ(-neg, val);
EXPECT_EQ(neg, uint128_t(0xffffffffffffffffULL, 0xffffffffffffffffULL));
}
| 23.3125
| 76
| 0.705094
|
graydon
|
d6f39dfa02feb89ede21cceaec669673a72df4f6
| 763
|
cpp
|
C++
|
0049 - Group Anagrams/cpp/main.cpp
|
xiaoswu/Leetcode
|
e4ae8b2f72a312ee247084457cf4e6dbcfd20e18
|
[
"MIT"
] | 5
|
2018-10-18T06:47:19.000Z
|
2020-06-19T09:30:03.000Z
|
0049 - Group Anagrams/cpp/main.cpp
|
xiaoswu/Leetcode
|
e4ae8b2f72a312ee247084457cf4e6dbcfd20e18
|
[
"MIT"
] | null | null | null |
0049 - Group Anagrams/cpp/main.cpp
|
xiaoswu/Leetcode
|
e4ae8b2f72a312ee247084457cf4e6dbcfd20e18
|
[
"MIT"
] | null | null | null |
//
// main.cpp
// 49 - Group Anagrams
//
// Created by ynfMac on 2019/12/7.
// Copyright © 2019 ynfMac. All rights reserved.
//
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> m;
for (const string& s : strs) {
string key = s;
sort(key.begin(), key.end());
m[key].push_back(s);
}
vector<vector<string>> res;
for (const auto& p :m) {
res.push_back(p.second);
}
return res;
}
};
int main(int argc, const char * argv[]) {
std::cout << "Hello, World!\n";
return 0;
}
| 20.621622
| 64
| 0.551769
|
xiaoswu
|
d6f7bcff72dda89ef8880f3cb0501646fa1349f5
| 357
|
hpp
|
C++
|
PlanetaMatchMakerServer/source/utilities/asio_stream_compatibility.hpp
|
InstytutXR/PlanetaMatchMaker
|
4bf7503c031aea467c191c3a0d14c6dd58354f99
|
[
"MIT"
] | 6
|
2019-08-15T09:48:55.000Z
|
2021-07-25T14:40:59.000Z
|
PlanetaMatchMakerServer/source/utilities/asio_stream_compatibility.hpp
|
InstytutXR/PlanetaMatchMaker
|
4bf7503c031aea467c191c3a0d14c6dd58354f99
|
[
"MIT"
] | 43
|
2019-12-25T14:54:52.000Z
|
2022-02-24T17:22:48.000Z
|
PlanetaMatchMakerServer/source/utilities/asio_stream_compatibility.hpp
|
InstytutXR/PlanetaMatchMaker
|
4bf7503c031aea467c191c3a0d14c6dd58354f99
|
[
"MIT"
] | 2
|
2020-05-06T20:14:44.000Z
|
2020-06-02T21:21:10.000Z
|
#pragma once
#include <boost/asio.hpp>
namespace boost {
namespace asio {
std::ostream& operator <<(std::ostream& os, const basic_socket<ip::tcp>::endpoint_type& endpoint);
}
namespace system {
std::ostream& operator <<(std::ostream& os, const error_code& error_code);
std::ostream& operator <<(std::ostream& os, const system_error& error);
}
}
| 25.5
| 100
| 0.703081
|
InstytutXR
|
d6fb0c289baea16265ec7b05735877e69c88a012
| 2,301
|
cpp
|
C++
|
utility/checked_delete.cpp
|
MaxHonggg/professional_boost
|
6fff73d3b9832644068dc8fe0443be813c7237b4
|
[
"BSD-2-Clause"
] | 47
|
2016-05-20T08:49:47.000Z
|
2022-01-03T01:17:07.000Z
|
utility/checked_delete.cpp
|
MaxHonggg/professional_boost
|
6fff73d3b9832644068dc8fe0443be813c7237b4
|
[
"BSD-2-Clause"
] | null | null | null |
utility/checked_delete.cpp
|
MaxHonggg/professional_boost
|
6fff73d3b9832644068dc8fe0443be813c7237b4
|
[
"BSD-2-Clause"
] | 37
|
2016-07-25T04:52:08.000Z
|
2022-02-14T03:55:08.000Z
|
// Copyright (c) 2016
// Author: Chrono Law
#include <std.hpp>
using namespace std;
#include <boost/checked_delete.hpp>
using namespace boost;
///////////////////////////////////////
class demo_class;
void do_delete(demo_class* p)
//{ delete p;}
{ checked_delete(p);}
///////////////////////////////////////
void case1()
{
auto p1 = new int(10);
checked_delete(p1);
auto p2 = new int[10];
checked_array_delete(p2);
}
///////////////////////////////////////
class demo_class
{
public:
~demo_class()
{ cout << "dtor exec." << endl; }
};
void case2()
{
auto p1 = new demo_class;
//checked_delete(p1);
checked_deleter<demo_class>()(p1);
auto p2 = new demo_class[10];
//checked_array_delete(p2);
checked_array_deleter<demo_class>()(p2);
cout << "try for_each" << endl;
vector<demo_class*> v;
v.push_back(new demo_class);
v.push_back(new demo_class);
for_each(v.begin(),v.end(), checked_deleter<demo_class>());
}
///////////////////////////////////////
struct my_checked_deleter
{
typedef void result_type;
template<class T>
void operator()(T* x) const
{
boost::checked_delete(x);
}
};
void case3()
{
cout << "my_checked_deleter" << endl;
auto p = new int(10);
my_checked_deleter()(p);
vector<int*> v;
v.push_back(new int(10));
for_each(v.begin(), v.end(),
my_checked_deleter());
}
///////////////////////////////////////
void case4()
{
cout << "incomplete type" << endl;
auto p = new demo_class();
//auto p = (demo_class*)(1996);
do_delete(p);
}
///////////////////////////////////////
#include <boost/static_assert.hpp>
template<class Pointer> inline
void my_checked_delete(Pointer p)
{
BOOST_STATIC_ASSERT(is_pointer<Pointer>::value);
typedef typename remove_pointer<Pointer>::type T;
BOOST_STATIC_ASSERT(is_object<T>::value);
BOOST_STATIC_ASSERT(!is_array<T>::value);
BOOST_STATIC_ASSERT(sizeof(T) >0 );
delete p;
}
void case5()
{
//auto p = new int[2][2];
auto p = new int;
my_checked_delete(p);
}
///////////////////////////////////////
int main()
{
std::cout << "hello checked_delete" << std::endl;
case1();
case2();
case3();
case4();
case5();
}
| 17.044444
| 63
| 0.544111
|
MaxHonggg
|
d9010b55ad78ce4d46baa6ae6a686e8932f05969
| 121
|
hpp
|
C++
|
src/rolmodl/hpp/forwarddecl/Win.hpp
|
maximsmol/rolmodl
|
fb41b7f9f4669eea84ce6f1574cdf1be9b6f072f
|
[
"MIT"
] | 1
|
2022-02-19T21:34:42.000Z
|
2022-02-19T21:34:42.000Z
|
src/rolmodl/hpp/forwarddecl/Win.hpp
|
maximsmol/rolmodl
|
fb41b7f9f4669eea84ce6f1574cdf1be9b6f072f
|
[
"MIT"
] | null | null | null |
src/rolmodl/hpp/forwarddecl/Win.hpp
|
maximsmol/rolmodl
|
fb41b7f9f4669eea84ce6f1574cdf1be9b6f072f
|
[
"MIT"
] | 1
|
2021-12-07T09:33:42.000Z
|
2021-12-07T09:33:42.000Z
|
#pragma once
#include <cstdint>
#include <SDL.h>
namespace rolmodl {
class Win_Base;
class Win;
class Win_SW;
}
| 10.083333
| 19
| 0.68595
|
maximsmol
|
d905a9ffc825dde40cd5c10f1e3ea532268ff364
| 3,459
|
cpp
|
C++
|
Source/Engine/Engine/GameObject3D.cpp
|
Syoukei66/Animal-Space-Battle
|
edb17e2f75fd5b43697889597e1eaac2e9e9cd76
|
[
"MIT"
] | null | null | null |
Source/Engine/Engine/GameObject3D.cpp
|
Syoukei66/Animal-Space-Battle
|
edb17e2f75fd5b43697889597e1eaac2e9e9cd76
|
[
"MIT"
] | null | null | null |
Source/Engine/Engine/GameObject3D.cpp
|
Syoukei66/Animal-Space-Battle
|
edb17e2f75fd5b43697889597e1eaac2e9e9cd76
|
[
"MIT"
] | null | null | null |
#include "GameObject3D.h"
#include "GameObjectRenderState.h"
// =================================================================
// Constructor / Destructor
// =================================================================
GameObject3D::GameObject3D()
: parent_(nullptr)
, children_()
{
this->transform_ = new Transform3D(this);
this->transform_->Init();
}
GameObject3D::~GameObject3D()
{
delete this->transform_;
}
// =================================================================
// Method
// =================================================================
void GameObject3D::Init()
{
GameObject::Init();
}
void GameObject3D::ManagedPreUpdate()
{
this->PreUpdate();
for (GameObject3D* child : this->children_)
{
child->ManagedPreUpdate();
}
}
void GameObject3D::ManagedUpdate()
{
this->Update();
for (GameObject3D* child : this->children_)
{
child->ManagedUpdate();
}
}
void GameObject3D::ManagedPostUpdate()
{
this->PostUpdate();
for (GameObject3D* child : this->children_)
{
child->ManagedPostUpdate();
}
}
void GameObject3D::AddChild(GameObject3D* child)
{
child->parent_ = this;
this->children_.push_back(child);
child->FireOnPositionChanged(this);
child->FireOnScaleChanged(this);
child->FireOnRotationChanged(this);
}
void GameObject3D::RemoveChild(GameObject3D* child)
{
if (child->parent_ != this)
{
return;
}
child->parent_ = nullptr;
for (std::vector<GameObject3D*>::iterator it = this->children_.begin(); it != this->children_.end(); ++it)
{
if (child == (*it))
{
this->children_.erase(it);
return;
}
}
}
void GameObject3D::RemoveSelf()
{
if (!this->parent_)
{
return;
}
this->parent_->RemoveChild(this);
}
void GameObject3D::ClearChildren()
{
for (GameObject3D* child : this->children_)
{
child->parent_ = nullptr;
}
this->children_.clear();
}
void GameObject3D::Draw(GameObjectRenderState* state)
{
if (!this->IsVisible())
{
return;
}
this->PushMatrixStack(state);
// 自分自身の描画
this->ManagedDraw(state);
// 子の描画
for (GameObject3D* child : this->children_)
{
child->Draw(state);
}
this->PopMatrixStack(state);
}
void GameObject3D::PushMatrixStack(GameObjectRenderState* state)
{
state->PushMatrix(this->transform_->GetMatrix());
//if (this->IsBillboardingRoot())
//{
// state->PushMatrix(state->GetCamera()->GetBillboardingMatrix());
//}
}
void GameObject3D::PopMatrixStack(GameObjectRenderState* state)
{
//if (this->IsBillboardingRoot())
//{
// state->PopMatrix();
//}
state->PopMatrix();
}
// =================================================================
// Events
// =================================================================
void GameObject3D::FireOnPositionChanged(GameObject* root)
{
this->transform_->OnWorldTransformDirty();
this->OnPositionChanged(root);
for (GameObject3D* child : this->children_)
{
child->FireOnPositionChanged(root);
}
}
void GameObject3D::FireOnScaleChanged(GameObject* root)
{
this->transform_->OnWorldTransformDirty();
this->OnScaleChanged(root);
for (GameObject3D* child : this->children_)
{
child->FireOnScaleChanged(root);
}
}
void GameObject3D::FireOnRotationChanged(GameObject* root)
{
this->transform_->OnWorldTransformDirty();
this->OnRotationChanged(root);
for (GameObject3D* child : this->children_)
{
child->FireOnRotationChanged(root);
}
}
| 20.110465
| 108
| 0.596993
|
Syoukei66
|
d9069f1e1538cf1f8469e29bbc94bbd40f57f2c3
| 12,569
|
hxx
|
C++
|
opencascade/AppDef_Variational.hxx
|
mgreminger/OCP
|
92eacb99497cd52b419c8a4a8ab0abab2330ed42
|
[
"Apache-2.0"
] | null | null | null |
opencascade/AppDef_Variational.hxx
|
mgreminger/OCP
|
92eacb99497cd52b419c8a4a8ab0abab2330ed42
|
[
"Apache-2.0"
] | null | null | null |
opencascade/AppDef_Variational.hxx
|
mgreminger/OCP
|
92eacb99497cd52b419c8a4a8ab0abab2330ed42
|
[
"Apache-2.0"
] | null | null | null |
// Created on: 1996-05-14
// Created by: Philippe MANGIN / Jeannine PANCIATICI
// Copyright (c) 1996-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _AppDef_Variational_HeaderFile
#define _AppDef_Variational_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <AppDef_MultiLine.hxx>
#include <Standard_Integer.hxx>
#include <TColStd_HArray1OfReal.hxx>
#include <AppParCurves_HArray1OfConstraintCouple.hxx>
#include <TColStd_HArray1OfInteger.hxx>
#include <Standard_Real.hxx>
#include <GeomAbs_Shape.hxx>
#include <Standard_Boolean.hxx>
#include <AppParCurves_MultiBSpCurve.hxx>
#include <Standard_OStream.hxx>
#include <TColStd_Array1OfReal.hxx>
#include <math_Vector.hxx>
#include <AppParCurves_Constraint.hxx>
class AppDef_SmoothCriterion;
class math_Matrix;
class FEmTool_Curve;
class FEmTool_Assembly;
class PLib_Base;
//! This class is used to smooth N points with constraints
//! by minimization of quadratic criterium but also
//! variational criterium in order to obtain " fair Curve "
//! Computes the approximation of a Multiline by
//! Variational optimization.
class AppDef_Variational
{
public:
DEFINE_STANDARD_ALLOC
//! Constructor.
//! Initialization of the fields.
//! warning : Nc0 : number of PassagePoint consraints
//! Nc2 : number of TangencyPoint constraints
//! Nc3 : number of CurvaturePoint constraints
//! if
//! ((MaxDegree-Continuity)*MaxSegment -Nc0 - 2*Nc1
//! -3*Nc2)
//! is negative
//! The problem is over-constrained.
//!
//! Limitation : The MultiLine from AppDef has to be composed by
//! only one Line ( Dimension 2 or 3).
Standard_EXPORT AppDef_Variational(const AppDef_MultiLine& SSP, const Standard_Integer FirstPoint, const Standard_Integer LastPoint, const Handle(AppParCurves_HArray1OfConstraintCouple)& TheConstraints, const Standard_Integer MaxDegree = 14, const Standard_Integer MaxSegment = 100, const GeomAbs_Shape Continuity = GeomAbs_C2, const Standard_Boolean WithMinMax = Standard_False, const Standard_Boolean WithCutting = Standard_True, const Standard_Real Tolerance = 1.0, const Standard_Integer NbIterations = 2);
//! Makes the approximation with the current fields.
Standard_EXPORT void Approximate();
//! returns True if the creation is done
//! and correspond to the current fields.
Standard_EXPORT Standard_Boolean IsCreated() const;
//! returns True if the approximation is ok
//! and correspond to the current fields.
Standard_EXPORT Standard_Boolean IsDone() const;
//! returns True if the problem is overconstrained
//! in this case, approximation cannot be done.
Standard_EXPORT Standard_Boolean IsOverConstrained() const;
//! returns all the BSpline curves approximating the
//! MultiLine from AppDef SSP after minimization of the parameter.
Standard_EXPORT AppParCurves_MultiBSpCurve Value() const;
//! returns the maximum of the distances between
//! the points of the multiline and the approximation
//! curves.
Standard_EXPORT Standard_Real MaxError() const;
//! returns the index of the MultiPoint of ErrorMax
Standard_EXPORT Standard_Integer MaxErrorIndex() const;
//! returns the quadratic average of the distances between
//! the points of the multiline and the approximation
//! curves.
Standard_EXPORT Standard_Real QuadraticError() const;
//! returns the distances between the points of the
//! multiline and the approximation curves.
Standard_EXPORT void Distance (math_Matrix& mat);
//! returns the average error between
//! the MultiLine from AppDef and the approximation.
Standard_EXPORT Standard_Real AverageError() const;
//! returns the parameters uses to the approximations
Standard_EXPORT const Handle(TColStd_HArray1OfReal)& Parameters() const;
//! returns the knots uses to the approximations
Standard_EXPORT const Handle(TColStd_HArray1OfReal)& Knots() const;
//! returns the values of the quality criterium.
Standard_EXPORT void Criterium (Standard_Real& VFirstOrder, Standard_Real& VSecondOrder, Standard_Real& VThirdOrder) const;
//! returns the Weights (as percent) associed to the criterium used in
//! the optimization.
Standard_EXPORT void CriteriumWeight (Standard_Real& Percent1, Standard_Real& Percent2, Standard_Real& Percent3) const;
//! returns the Maximum Degree used in the approximation
Standard_EXPORT Standard_Integer MaxDegree() const;
//! returns the Maximum of segment used in the approximation
Standard_EXPORT Standard_Integer MaxSegment() const;
//! returns the Continuity used in the approximation
Standard_EXPORT GeomAbs_Shape Continuity() const;
//! returns if the approximation search to minimize the
//! maximum Error or not.
Standard_EXPORT Standard_Boolean WithMinMax() const;
//! returns if the approximation can insert new Knots or not.
Standard_EXPORT Standard_Boolean WithCutting() const;
//! returns the tolerance used in the approximation.
Standard_EXPORT Standard_Real Tolerance() const;
//! returns the number of iterations used in the approximation.
Standard_EXPORT Standard_Integer NbIterations() const;
//! Prints on the stream o information on the current state
//! of the object.
//! MaxError,MaxErrorIndex,AverageError,QuadraticError,Criterium
//! Distances,Degre,Nombre de poles, parametres, noeuds
Standard_EXPORT void Dump (Standard_OStream& o) const;
//! Define the constraints to approximate
//! If this value is incompatible with the others fields
//! this method modify nothing and returns false
Standard_EXPORT Standard_Boolean SetConstraints (const Handle(AppParCurves_HArray1OfConstraintCouple)& aConstrainst);
//! Defines the parameters used by the approximations.
Standard_EXPORT void SetParameters (const Handle(TColStd_HArray1OfReal)& param);
//! Defines the knots used by the approximations
//! If this value is incompatible with the others fields
//! this method modify nothing and returns false
Standard_EXPORT Standard_Boolean SetKnots (const Handle(TColStd_HArray1OfReal)& knots);
//! Define the Maximum Degree used in the approximation
//! If this value is incompatible with the others fields
//! this method modify nothing and returns false
Standard_EXPORT Standard_Boolean SetMaxDegree (const Standard_Integer Degree);
//! Define the maximum number of segments used in the approximation
//! If this value is incompatible with the others fields
//! this method modify nothing and returns false
Standard_EXPORT Standard_Boolean SetMaxSegment (const Standard_Integer NbSegment);
//! Define the Continuity used in the approximation
//! If this value is incompatible with the others fields
//! this method modify nothing and returns false
Standard_EXPORT Standard_Boolean SetContinuity (const GeomAbs_Shape C);
//! Define if the approximation search to minimize the
//! maximum Error or not.
Standard_EXPORT void SetWithMinMax (const Standard_Boolean MinMax);
//! Define if the approximation can insert new Knots or not.
//! If this value is incompatible with the others fields
//! this method modify nothing and returns false
Standard_EXPORT Standard_Boolean SetWithCutting (const Standard_Boolean Cutting);
//! define the Weights (as percent) associed to the criterium used in
//! the optimization.
//!
//! if Percent <= 0
Standard_EXPORT void SetCriteriumWeight (const Standard_Real Percent1, const Standard_Real Percent2, const Standard_Real Percent3);
//! define the Weight (as percent) associed to the
//! criterium Order used in the optimization : Others
//! weights are updated.
//! if Percent < 0
//! if Order < 1 or Order > 3
Standard_EXPORT void SetCriteriumWeight (const Standard_Integer Order, const Standard_Real Percent);
//! define the tolerance used in the approximation.
Standard_EXPORT void SetTolerance (const Standard_Real Tol);
//! define the number of iterations used in the approximation.
//! if Iter < 1
Standard_EXPORT void SetNbIterations (const Standard_Integer Iter);
protected:
private:
Standard_EXPORT void TheMotor (Handle(AppDef_SmoothCriterion)& J, const Standard_Real WQuadratic, const Standard_Real WQuality, Handle(FEmTool_Curve)& TheCurve, TColStd_Array1OfReal& Ecarts);
Standard_EXPORT void Adjusting (Handle(AppDef_SmoothCriterion)& J, Standard_Real& WQuadratic, Standard_Real& WQuality, Handle(FEmTool_Curve)& TheCurve, TColStd_Array1OfReal& Ecarts);
Standard_EXPORT void Optimization (Handle(AppDef_SmoothCriterion)& J, FEmTool_Assembly& A, const Standard_Boolean ToAssemble, const Standard_Real EpsDeg, Handle(FEmTool_Curve)& Curve, const TColStd_Array1OfReal& Parameters) const;
Standard_EXPORT void Project (const Handle(FEmTool_Curve)& C, const TColStd_Array1OfReal& Ti, TColStd_Array1OfReal& ProjTi, TColStd_Array1OfReal& Distance, Standard_Integer& NumPoints, Standard_Real& MaxErr, Standard_Real& QuaErr, Standard_Real& AveErr, const Standard_Integer NbIterations = 2) const;
Standard_EXPORT void ACR (Handle(FEmTool_Curve)& Curve, TColStd_Array1OfReal& Ti, const Standard_Integer Decima) const;
Standard_EXPORT void SplitCurve (const Handle(FEmTool_Curve)& InCurve, const TColStd_Array1OfReal& Ti, const Standard_Real CurveTol, Handle(FEmTool_Curve)& OutCurve, Standard_Boolean& iscut) const;
Standard_EXPORT void Init();
Standard_EXPORT void InitSmoothCriterion();
Standard_EXPORT void InitParameters (Standard_Real& Length);
Standard_EXPORT void InitCriterionEstimations (const Standard_Real Length, Standard_Real& J1, Standard_Real& J2, Standard_Real& J3) const;
Standard_EXPORT void EstTangent (const Standard_Integer ipnt, math_Vector& VTang) const;
Standard_EXPORT void EstSecnd (const Standard_Integer ipnt, const math_Vector& VTang1, const math_Vector& VTang2, const Standard_Real Length, math_Vector& VScnd) const;
Standard_EXPORT void InitCutting (const Handle(PLib_Base)& aBase, const Standard_Real CurvTol, Handle(FEmTool_Curve)& aCurve) const;
Standard_EXPORT void AssemblingConstraints (const Handle(FEmTool_Curve)& Curve, const TColStd_Array1OfReal& Parameters, const Standard_Real CBLONG, FEmTool_Assembly& A) const;
Standard_EXPORT Standard_Boolean InitTthetaF (const Standard_Integer ndimen, const AppParCurves_Constraint typcon, const Standard_Integer begin, const Standard_Integer jndex);
AppDef_MultiLine mySSP;
Standard_Integer myNbP3d;
Standard_Integer myNbP2d;
Standard_Integer myDimension;
Standard_Integer myFirstPoint;
Standard_Integer myLastPoint;
Standard_Integer myNbPoints;
Handle(TColStd_HArray1OfReal) myTabPoints;
Handle(AppParCurves_HArray1OfConstraintCouple) myConstraints;
Standard_Integer myNbConstraints;
Handle(TColStd_HArray1OfReal) myTabConstraints;
Standard_Integer myNbPassPoints;
Standard_Integer myNbTangPoints;
Standard_Integer myNbCurvPoints;
Handle(TColStd_HArray1OfInteger) myTypConstraints;
Handle(TColStd_HArray1OfReal) myTtheta;
Handle(TColStd_HArray1OfReal) myTfthet;
Standard_Integer myMaxDegree;
Standard_Integer myMaxSegment;
Standard_Integer myNbIterations;
Standard_Real myTolerance;
GeomAbs_Shape myContinuity;
Standard_Integer myNivCont;
Standard_Boolean myWithMinMax;
Standard_Boolean myWithCutting;
Standard_Real myPercent[3];
Standard_Real myCriterium[4];
Handle(AppDef_SmoothCriterion) mySmoothCriterion;
Handle(TColStd_HArray1OfReal) myParameters;
Handle(TColStd_HArray1OfReal) myKnots;
AppParCurves_MultiBSpCurve myMBSpCurve;
Standard_Real myMaxError;
Standard_Integer myMaxErrorIndex;
Standard_Real myAverageError;
Standard_Boolean myIsCreated;
Standard_Boolean myIsDone;
Standard_Boolean myIsOverConstr;
};
#endif // _AppDef_Variational_HeaderFile
| 41.896667
| 512
| 0.782003
|
mgreminger
|
d91148dff2f98caf9ebfc8bbd422ef78cc17fad9
| 4,368
|
hpp
|
C++
|
src/tools/include/benchmark.hpp
|
kovdan01/parallel-computing
|
878d836e4b05563dc7fe11b6d7ca65fea950b5b7
|
[
"Intel"
] | null | null | null |
src/tools/include/benchmark.hpp
|
kovdan01/parallel-computing
|
878d836e4b05563dc7fe11b6d7ca65fea950b5b7
|
[
"Intel"
] | null | null | null |
src/tools/include/benchmark.hpp
|
kovdan01/parallel-computing
|
878d836e4b05563dc7fe11b6d7ca65fea950b5b7
|
[
"Intel"
] | null | null | null |
#ifndef PARALLEL_COMPUTING_TOOLS_BENCHMARK_HPP_
#define PARALLEL_COMPUTING_TOOLS_BENCHMARK_HPP_
#include <chrono>
// NOTE: gcc 8.2.0 on cHARISMa does not support concepts
// Instead, use horrible std::enable_if
// #include <concepts>
#include <cstdint>
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <string_view>
#include <type_traits>
namespace my
{
template <typename T>
inline __attribute__((always_inline)) void do_not_optimize(T& value)
{
#if defined(__clang__)
asm volatile("" : "+r,m"(value) : : "memory");
#else
asm volatile("" : "+m,r"(value) : : "memory");
#endif
}
inline __attribute__((always_inline)) std::uint64_t ticks()
{
std::uint64_t tsc;
asm volatile("mfence; " // memory barrier
"rdtsc; " // read of tsc
"shl $32,%%rdx; " // shift higher 32 bits stored in rdx up
"or %%rdx,%%rax" // and or onto rax
: "=a"(tsc) // output to tsc
:
: "%rcx", "%rdx", "memory");
return tsc;
}
struct TicksAndNanoseconds
{
double ticks;
double nanoseconds;
};
class NanosecondsTimer
{
public:
NanosecondsTimer(double& result, std::size_t iterations_count = 1)
: m_result(result)
, m_iterations_count(iterations_count)
{
m_time_before = std::chrono::high_resolution_clock::now();
}
~NanosecondsTimer()
{
try
{
using namespace std::chrono;
high_resolution_clock::time_point time_after = high_resolution_clock::now();
m_result = duration_cast<nanoseconds>(time_after - m_time_before).count() / static_cast<double>(m_iterations_count);
}
catch (...)
{
std::exit(EXIT_FAILURE);
}
}
private:
double& m_result;
std::size_t m_iterations_count;
std::chrono::high_resolution_clock::time_point m_time_before;
};
class TicksTimer
{
public:
TicksTimer(double& result, std::size_t iterations_count = 1)
: m_result(result)
, m_iterations_count(iterations_count)
{
m_ticks_before = ticks();
}
~TicksTimer()
{
try
{
std::uint64_t ticks_after = ticks();
m_result = (ticks_after - m_ticks_before) / static_cast<double>(m_iterations_count);
}
catch (...)
{
std::exit(EXIT_FAILURE);
}
}
private:
double& m_result;
std::size_t m_iterations_count;
std::uint64_t m_ticks_before;
};
class Timer : public NanosecondsTimer, public TicksTimer
{
public:
Timer(TicksAndNanoseconds& result, std::size_t iterations_count = 1)
: NanosecondsTimer(result.nanoseconds, iterations_count)
, TicksTimer(result.ticks, iterations_count)
{
}
};
// NOTE: gcc 8.2.0 on cHARISMa does not support concepts
// Instead, use horrible std::enable_if
// template <typename Function>
// concept ReturnsVoid = std::same_as<std::invoke_result_t<Function>, void>;
// template <typename Function>
// concept DoesNotReturnVoid = !ReturnsVoid<Function>;
template <typename Function>
// requires DoesNotReturnVoid<Function>
std::enable_if_t<!std::is_same_v<std::invoke_result_t<Function>, void>, double>
benchmark_function(Function f, std::size_t iterations_count = 1)
{
double nanoseconds;
{
NanosecondsTimer timer(nanoseconds, iterations_count);
for (std::size_t i = 0; i < iterations_count; ++i)
{
auto result = f();
do_not_optimize(result);
}
}
return nanoseconds;
}
template <typename Function>
// requires ReturnsVoid<Function>
std::enable_if_t<std::is_same_v<std::invoke_result_t<Function>, void>, double>
benchmark_function(Function f, std::size_t iterations_count = 1)
{
double nanoseconds;
{
NanosecondsTimer timer(nanoseconds, iterations_count);
for (std::size_t i = 0; i < iterations_count; ++i)
{
f();
}
}
return nanoseconds;
}
inline void print_result(std::string_view label, double result)
{
std::cout << label;
std::cout << std::fixed;
std::cout << std::setprecision(2) << std::setfill(' ') << std::setw(15) << result << std::endl;
std::cout << std::scientific;
}
} // namespace my
#endif // PARALLEL_COMPUTING_TOOLS_BENCHMARK_HPP_
| 25.846154
| 128
| 0.633013
|
kovdan01
|
d911b4fcec81fea1c844a18f81a150e5deff5489
| 16,907
|
cpp
|
C++
|
OpenTESArena/src/Game/Game.cpp
|
Digital-Monk/OpenTESArena
|
95f0bdaa642ff090b94081795a53b00f10dc4b03
|
[
"MIT"
] | null | null | null |
OpenTESArena/src/Game/Game.cpp
|
Digital-Monk/OpenTESArena
|
95f0bdaa642ff090b94081795a53b00f10dc4b03
|
[
"MIT"
] | null | null | null |
OpenTESArena/src/Game/Game.cpp
|
Digital-Monk/OpenTESArena
|
95f0bdaa642ff090b94081795a53b00f10dc4b03
|
[
"MIT"
] | null | null | null |
#include <chrono>
#include <cmath>
#include <cstdint>
#include <sstream>
#include <stdexcept>
#include <string>
#include <thread>
#include "SDL.h"
#include "Game.h"
#include "Options.h"
#include "PlayerInterface.h"
#include "../Assets/CityDataFile.h"
#include "../Interface/Panel.h"
#include "../Media/FontManager.h"
#include "../Media/MusicFile.h"
#include "../Media/MusicName.h"
#include "../Media/TextureManager.h"
#include "../Rendering/Renderer.h"
#include "../Rendering/Surface.h"
#include "../Utilities/Platform.h"
#include "components/debug/Debug.h"
#include "components/utilities/File.h"
#include "components/utilities/String.h"
#include "components/vfs/manager.hpp"
namespace
{
// Size of scratch buffer in bytes, reset each frame.
constexpr int SCRATCH_BUFFER_SIZE = 65536;
}
Game::Game()
{
DebugLog("Initializing (Platform: " + Platform::getPlatform() + ").");
// Get the current working directory. This is most relevant for platforms
// like macOS, where the base path might be in the app's own "Resources" folder.
this->basePath = Platform::getBasePath();
// Get the path to the options folder. This is platform-dependent and points inside
// the "preferences directory" so it's always writable.
this->optionsPath = Platform::getOptionsPath();
// Parse options-default.txt and options-changes.txt (if it exists). Always prefer the
// default file before the "changes" file.
this->initOptions(this->basePath, this->optionsPath);
// Initialize virtual file system using the Arena path in the options file.
const bool arenaPathIsRelative = File::pathIsRelative(this->options.getMisc_ArenaPath().c_str());
VFS::Manager::get().initialize(std::string(
(arenaPathIsRelative ? this->basePath : "") + this->options.getMisc_ArenaPath()));
// Initialize the OpenAL Soft audio manager.
const bool midiPathIsRelative = File::pathIsRelative(this->options.getAudio_MidiConfig().c_str());
const std::string midiPath = (midiPathIsRelative ? this->basePath : "") +
this->options.getAudio_MidiConfig();
this->audioManager.init(this->options.getAudio_MusicVolume(),
this->options.getAudio_SoundVolume(), this->options.getAudio_SoundChannels(),
this->options.getAudio_SoundResampling(), this->options.getAudio_Is3DAudio(), midiPath);
// Initialize the SDL renderer and window with the given settings.
this->renderer.init(this->options.getGraphics_ScreenWidth(),
this->options.getGraphics_ScreenHeight(),
static_cast<Renderer::WindowMode>(this->options.getGraphics_WindowMode()),
this->options.getGraphics_LetterboxMode());
// Initialize the texture manager.
this->textureManager.init();
// Determine which version of the game the Arena path is pointing to.
const bool isFloppyVersion = [this, arenaPathIsRelative]()
{
// Path to the Arena folder.
const std::string fullArenaPath = [this, arenaPathIsRelative]()
{
// Include the base path if the ArenaPath is relative.
const std::string path = (arenaPathIsRelative ? this->basePath : "") +
this->options.getMisc_ArenaPath();
return String::addTrailingSlashIfMissing(path);
}();
// Check for the CD version first.
const std::string &acdExeName = ExeData::CD_VERSION_EXE_FILENAME;
const std::string acdExePath = fullArenaPath + acdExeName;
if (File::exists(acdExePath.c_str()))
{
DebugLog("CD version.");
return false;
}
// If that's not there, check for the floppy disk version.
const std::string &aExeName = ExeData::FLOPPY_VERSION_EXE_FILENAME;
const std::string aExePath = fullArenaPath + aExeName;
if (File::exists(aExePath.c_str()))
{
DebugLog("Floppy disk version.");
return true;
}
// If neither exist, it's not a valid Arena directory.
throw DebugException("\"" + fullArenaPath + "\" does not have an Arena executable.");
}();
// Load various miscellaneous assets.
this->miscAssets.init(isFloppyVersion);
// Load and set window icon.
const Surface icon = [this]()
{
const std::string iconPath = this->basePath + "data/icon.bmp";
Surface surface = Surface::loadBMP(iconPath.c_str(), Renderer::DEFAULT_PIXELFORMAT);
// Treat black as transparent.
const uint32_t black = surface.mapRGBA(0, 0, 0, 255);
SDL_SetColorKey(surface.get(), SDL_TRUE, black);
return surface;
}();
this->renderer.setWindowIcon(icon);
this->scratchAllocator.init(SCRATCH_BUFFER_SIZE);
// Initialize panel and music to default.
this->panel = Panel::defaultPanel(*this);
this->setMusic(MusicName::PercIntro);
// Use a texture as the cursor instead.
SDL_ShowCursor(SDL_FALSE);
// Leave some members null for now. The game data is initialized when the player
// enters the game world, and the "next panel" is a temporary used by the game
// to avoid corruption between panel events which change the panel.
this->gameData = nullptr;
this->nextPanel = nullptr;
this->nextSubPanel = nullptr;
// This keeps the programmer from deleting a sub-panel the same frame it's in use.
// The pop is delayed until the beginning of the next frame.
this->requestedSubPanelPop = false;
}
Panel *Game::getActivePanel() const
{
return (this->subPanels.size() > 0) ?
this->subPanels.back().get() : this->panel.get();
}
AudioManager &Game::getAudioManager()
{
return this->audioManager;
}
InputManager &Game::getInputManager()
{
return this->inputManager;
}
FontManager &Game::getFontManager()
{
return this->fontManager;
}
bool Game::gameDataIsActive() const
{
return this->gameData.get() != nullptr;
}
GameData &Game::getGameData() const
{
// The caller should not request the game data when there is no active session.
DebugAssert(this->gameDataIsActive());
return *this->gameData.get();
}
Options &Game::getOptions()
{
return this->options;
}
Renderer &Game::getRenderer()
{
return this->renderer;
}
TextureManager &Game::getTextureManager()
{
return this->textureManager;
}
MiscAssets &Game::getMiscAssets()
{
return this->miscAssets;
}
ScratchAllocator &Game::getScratchAllocator()
{
return this->scratchAllocator;
}
Profiler &Game::getProfiler()
{
return this->profiler;
}
const FPSCounter &Game::getFPSCounter() const
{
return this->fpsCounter;
}
void Game::setPanel(std::unique_ptr<Panel> nextPanel)
{
this->nextPanel = std::move(nextPanel);
}
void Game::pushSubPanel(std::unique_ptr<Panel> nextSubPanel)
{
this->nextSubPanel = std::move(nextSubPanel);
}
void Game::popSubPanel()
{
// The active sub-panel must not pop more than one sub-panel, because it may
// have unintended side effects for other panels below it.
DebugAssertMsg(!this->requestedSubPanelPop, "Already scheduled to pop sub-panel.");
// If there are no sub-panels, then there is only the main panel, and panels
// should never have any sub-panels to pop.
DebugAssertMsg(this->subPanels.size() > 0, "No sub-panels to pop.");
this->requestedSubPanelPop = true;
}
void Game::setMusic(MusicName musicName, const std::optional<MusicName> &jingleMusicName)
{
if (jingleMusicName.has_value())
{
// Play jingle first and set the main music as the next music.
const std::string &jingleFilename = MusicFile::fromName(*jingleMusicName);
const bool loop = false;
this->audioManager.playMusic(jingleFilename, loop);
std::string nextFilename = MusicFile::fromName(musicName);
this->audioManager.setNextMusic(std::move(nextFilename));
}
else
{
// Play main music immediately.
const std::string &filename = MusicFile::fromName(musicName);
const bool loop = true;
this->audioManager.playMusic(filename, loop);
}
}
void Game::setGameData(std::unique_ptr<GameData> gameData)
{
this->gameData = std::move(gameData);
}
void Game::initOptions(const std::string &basePath, const std::string &optionsPath)
{
// Load the default options first.
const std::string defaultOptionsPath(basePath + "options/" + Options::DEFAULT_FILENAME);
this->options.loadDefaults(defaultOptionsPath);
// Check if the changes options file exists.
const std::string changesOptionsPath(optionsPath + Options::CHANGES_FILENAME);
if (!File::exists(changesOptionsPath.c_str()))
{
// Make one. Since the default options object has no changes, the new file will have
// no key-value pairs.
DebugLog("Creating options file at \"" + changesOptionsPath + "\".");
this->options.saveChanges();
}
else
{
// Read in any key-value pairs in the "changes" options file.
this->options.loadChanges(changesOptionsPath);
}
}
void Game::resizeWindow(int width, int height)
{
// Resize the window, and the 3D renderer if initialized.
const bool fullGameWindow = this->options.getGraphics_ModernInterface();
this->renderer.resize(width, height,
this->options.getGraphics_ResolutionScale(), fullGameWindow);
}
void Game::saveScreenshot(const Surface &surface)
{
// Get the path + filename to use for the new screenshot.
const std::string screenshotPath = []()
{
const std::string screenshotFolder = Platform::getScreenshotPath();
const std::string screenshotPrefix("screenshot");
int imageIndex = 0;
auto getNextAvailablePath = [&screenshotFolder, &screenshotPrefix, &imageIndex]()
{
std::stringstream ss;
ss << std::setw(3) << std::setfill('0') << imageIndex;
imageIndex++;
return screenshotFolder + screenshotPrefix + ss.str() + ".bmp";
};
std::string path = getNextAvailablePath();
while (File::exists(path.c_str()))
{
path = getNextAvailablePath();
}
return path;
}();
const int status = SDL_SaveBMP(surface.get(), screenshotPath.c_str());
if (status == 0)
{
DebugLog("Screenshot saved to \"" + screenshotPath + "\".");
}
else
{
DebugCrash("Failed to save screenshot to \"" + screenshotPath + "\": " +
std::string(SDL_GetError()));
}
}
void Game::handlePanelChanges()
{
// If a sub-panel pop was requested, then pop the top of the sub-panel stack.
if (this->requestedSubPanelPop)
{
this->subPanels.pop_back();
this->requestedSubPanelPop = false;
// Unpause the panel that is now the top-most one.
const bool paused = false;
this->getActivePanel()->onPauseChanged(paused);
}
// If a new sub-panel was requested, then add it to the stack.
if (this->nextSubPanel.get() != nullptr)
{
// Pause the top-most panel.
const bool paused = true;
this->getActivePanel()->onPauseChanged(paused);
this->subPanels.push_back(std::move(this->nextSubPanel));
}
// If a new panel was requested, switch to it. If it will be the active panel
// (i.e., there are no sub-panels), then subsequent events will be sent to it.
if (this->nextPanel.get() != nullptr)
{
this->panel = std::move(this->nextPanel);
}
}
void Game::handleEvents(bool &running)
{
// Handle events for the current game state.
SDL_Event e;
while (SDL_PollEvent(&e) != 0)
{
// Application events and window resizes are handled here.
bool applicationExit = this->inputManager.applicationExit(e);
bool resized = this->inputManager.windowResized(e);
bool takeScreenshot = this->inputManager.keyPressed(e, SDLK_PRINTSCREEN);
if (applicationExit)
{
running = false;
}
if (resized)
{
int width = e.window.data1;
int height = e.window.data2;
this->resizeWindow(width, height);
// Call each panel's resize method. The panels should not be listening for
// resize events themselves because it's more of an "application event" than
// a panel event.
this->panel->resize(width, height);
for (auto &subPanel : this->subPanels)
{
subPanel->resize(width, height);
}
}
if (takeScreenshot)
{
// Save a screenshot to the local folder.
const auto &renderer = this->getRenderer();
const Surface screenshot = renderer.getScreenshot();
this->saveScreenshot(screenshot);
}
// Panel-specific events are handled by the active panel.
this->getActivePanel()->handleEvent(e);
// See if the event requested any changes in active panels.
this->handlePanelChanges();
}
}
void Game::tick(double dt)
{
// Tick the active panel.
this->getActivePanel()->tick(dt);
// See if the panel tick requested any changes in active panels.
this->handlePanelChanges();
}
void Game::render()
{
// Draw the panel's main content.
this->panel->render(this->renderer);
// Draw any sub-panels back to front.
for (auto &subPanel : this->subPanels)
{
subPanel->render(this->renderer);
}
// Call the active panel's secondary render method. Secondary render items are those
// that are hidden on panels below the active one.
Panel *activePanel = this->getActivePanel();
activePanel->renderSecondary(this->renderer);
// Get the active panel's cursor texture and alignment.
const Panel::CursorData cursor = activePanel->getCurrentCursor();
// Draw cursor if not null. Some panels do not define a cursor (like cinematics),
// so their cursor is always null.
if (cursor.getTexture() != nullptr)
{
// The panel should not be drawing the cursor themselves. It's done here
// just to make sure that the cursor is drawn only once and is always drawn last.
this->renderer.drawCursor(*cursor.getTexture(), cursor.getAlignment(),
this->inputManager.getMousePosition(), this->options.getGraphics_CursorScale());
}
this->renderer.present();
}
void Game::loop()
{
// Nanoseconds per second. Only using this much precision because it's what
// high_resolution_clock gives back. Microseconds would be fine too.
constexpr int64_t timeUnits = 1000000000;
// Longest allowed frame time.
const std::chrono::duration<int64_t, std::nano> maxFrameTime(timeUnits / Options::MIN_FPS);
// On some platforms, thread sleeping takes longer than it should, so include a value to
// help compensate.
std::chrono::nanoseconds sleepBias(0);
auto thisTime = std::chrono::high_resolution_clock::now();
// Primary game loop.
bool running = true;
while (running)
{
const auto lastTime = thisTime;
thisTime = std::chrono::high_resolution_clock::now();
// Shortest allowed frame time.
const std::chrono::duration<int64_t, std::nano> minFrameTime(
timeUnits / this->options.getGraphics_TargetFPS());
// Time since the last frame started.
const auto frameTime = [minFrameTime, &sleepBias, &thisTime, lastTime]()
{
// Delay the current frame if the previous one was too fast.
auto diff = thisTime - lastTime;
if (diff < minFrameTime)
{
const auto sleepTime = minFrameTime - diff + sleepBias;
std::this_thread::sleep_for(sleepTime);
// Compensate for sleeping too long. Thread sleeping has questionable accuracy.
const auto tempTime = std::chrono::high_resolution_clock::now();
const auto unnecessarySleepTime = [thisTime, sleepTime, tempTime]()
{
const auto tempFrameTime = tempTime - thisTime;
return tempFrameTime - sleepTime;
}();
sleepBias = -unnecessarySleepTime;
thisTime = tempTime;
diff = thisTime - lastTime;
}
return diff;
}();
// Two delta times: actual and clamped. Use the clamped delta time for game calculations
// so things don't break at low frame rates.
constexpr double timeUnitsReal = static_cast<double>(timeUnits);
const double dt = static_cast<double>(frameTime.count()) / timeUnitsReal;
const double clampedDt = std::fmin(frameTime.count(), maxFrameTime.count()) / timeUnitsReal;
// Reset scratch allocator for use with this frame.
this->scratchAllocator.clear();
// Update the input manager's state.
this->inputManager.update();
// Update the audio manager listener (if any) and check for finished sounds.
if (this->gameDataIsActive())
{
const AudioManager::ListenerData listenerData = [this]()
{
const Player &player = this->getGameData().getPlayer();
const Double3 &position = player.getPosition();
const Double3 &direction = player.getDirection();
return AudioManager::ListenerData(position, direction);
}();
this->audioManager.update(dt, &listenerData);
}
else
{
this->audioManager.update(dt, nullptr);
}
// Update FPS counter.
this->fpsCounter.updateFrameTime(dt);
// Listen for input events.
try
{
this->handleEvents(running);
}
catch (const std::exception &e)
{
DebugCrash("handleEvents() exception! " + std::string(e.what()));
}
// Animate the current game state by delta time.
try
{
// Multiply delta time by the time scale. I settled on having the effects of this
// be application-wide rather than just in the game world since it's intended to
// simulate lower DOSBox cycles.
const double timeScaledDt = clampedDt * this->options.getMisc_TimeScale();
this->tick(timeScaledDt);
}
catch (const std::exception &e)
{
DebugCrash("tick() exception! " + std::string(e.what()));
}
// Draw to the screen.
try
{
this->render();
}
catch (const std::exception &e)
{
DebugCrash("render() exception! " + std::string(e.what()));
}
}
// At this point, the program has received an exit signal, and is now
// quitting peacefully.
this->options.saveChanges();
}
| 29.250865
| 99
| 0.71497
|
Digital-Monk
|
d9150cc66db91b2e7def973f1b5f6bcf9b967920
| 667
|
hpp
|
C++
|
Murat/src/core/LayerStack.hpp
|
dilmuratjohn/openglTutorial-cpp
|
98b524db0c0f13fa9166a13e252777bee8ec60cd
|
[
"Apache-2.0"
] | null | null | null |
Murat/src/core/LayerStack.hpp
|
dilmuratjohn/openglTutorial-cpp
|
98b524db0c0f13fa9166a13e252777bee8ec60cd
|
[
"Apache-2.0"
] | null | null | null |
Murat/src/core/LayerStack.hpp
|
dilmuratjohn/openglTutorial-cpp
|
98b524db0c0f13fa9166a13e252777bee8ec60cd
|
[
"Apache-2.0"
] | null | null | null |
//
// Created by murat on 2019-08-09.
//
#ifndef M_LAYER_STACK_HPP
#define M_LAYER_STACK_HPP
#include "Layer.hpp"
#include <muratpch.hpp>
namespace Murat {
class LayerStack {
public:
LayerStack();
~LayerStack();
void pushLayer(Layer *layer);
void pushOverlay(Layer *overlay);
void popLayer(Layer *layer);
void popOverlay(Layer *overlay);
std::vector<Layer *>::iterator begin() { return m_Layers.begin(); }
std::vector<Layer *>::iterator end() { return m_Layers.end(); }
private:
std::vector<Layer *> m_Layers;
unsigned int m_LayerInsertIndex = 0;
};
}
#endif
| 18.027027
| 75
| 0.611694
|
dilmuratjohn
|
d91a238a3c440aa54ae9f3d30e36724a5c777042
| 1,971
|
cpp
|
C++
|
bezGameEngine/src/bez/Events/MouseEvent.cpp
|
Gustvo/bezGameEngine
|
8d0ac4613d1a1aac65cab51d337b9a77d56f29ec
|
[
"MIT"
] | null | null | null |
bezGameEngine/src/bez/Events/MouseEvent.cpp
|
Gustvo/bezGameEngine
|
8d0ac4613d1a1aac65cab51d337b9a77d56f29ec
|
[
"MIT"
] | null | null | null |
bezGameEngine/src/bez/Events/MouseEvent.cpp
|
Gustvo/bezGameEngine
|
8d0ac4613d1a1aac65cab51d337b9a77d56f29ec
|
[
"MIT"
] | null | null | null |
#include <stdafx.hpp>
#include <bez/Events/MouseEvent.hpp>
namespace bez {
/// Mouse Motion Event
MouseMotionEvent::MouseMotionEvent(float x, float y) {
m_mouseCoordinates = std::make_pair(x, y);
registerInput(std::make_pair(x, y));
};
std::string MouseMotionEvent::toString() const {
std::stringstream ss;
ss << "MouseMoved: [" << m_mouseCoordinates.first << " : "
<< m_mouseCoordinates.second << "]";
return ss.str();
}
void MouseMotionEvent::registerInput(std::pair<float, float> p_mousePosition) {
Input::registerMousePosition(p_mousePosition);
}
/// Mouse Button Event
MouseButtonEvent::MouseButtonEvent(MouseButton p_button) {
m_button = p_button;
}
/// Mouse Button Pressed Event
MouseButtonPressedEvent::MouseButtonPressedEvent(MouseButton p_button)
: MouseButtonEvent(p_button) {
registerInput(p_button);
}
std::string MouseButtonPressedEvent::toString() const {
std::stringstream ss;
ss << "MouseButtonPressed: " << m_button;
return ss.str();
}
void MouseButtonPressedEvent::registerInput(MouseButton p_button) {
Input::registerMouseButton(p_button, true);
}
/// Mouse Button Release Event
MouseButtonReleasedEvent::MouseButtonReleasedEvent(MouseButton p_button)
: MouseButtonEvent(p_button) {
registerInput(p_button);
}
std::string MouseButtonReleasedEvent::toString() const {
std::stringstream ss;
ss << "MouseButtonReleased: " << m_button;
return ss.str();
}
void MouseButtonReleasedEvent::registerInput(MouseButton p_button) {
Input::registerMouseButton(p_button, false);
}
/// Mouse Wheel Event
MouseWheelEvent::MouseWheelEvent(std::pair<int, int> p_direction) {
m_direction = p_direction;
}
std::pair<int, int> MouseWheelEvent::getDirection() { return m_direction; }
std::string MouseWheelEvent::toString() const {
std::stringstream ss;
ss << "MouseWheelEvent - [x, y] = [" << m_direction.first << ", "
<< m_direction.second << "]";
return ss.str();
}
} // namespace bez
| 23.464286
| 79
| 0.726027
|
Gustvo
|
d91c0500122a7a3f3517f87c43aff269db2af384
| 162
|
hpp
|
C++
|
WinApiFramework/OpenGL/Surface3.hpp
|
TonSharp/OpenWAPI
|
d61a8f006ea866c399e68f338c2661e9ef624369
|
[
"MS-PL"
] | 3
|
2021-09-17T07:54:28.000Z
|
2021-09-18T08:28:33.000Z
|
WinApiFramework/OpenGL/Surface3.hpp
|
TonSharp/WAPITIS
|
d61a8f006ea866c399e68f338c2661e9ef624369
|
[
"MS-PL"
] | 21
|
2021-09-19T18:13:55.000Z
|
2021-12-14T10:28:53.000Z
|
WinApiFramework/OpenGL/Surface3.hpp
|
TonSharp/OpenWAPI
|
d61a8f006ea866c399e68f338c2661e9ef624369
|
[
"MS-PL"
] | null | null | null |
#pragma once
#include <vector>
#include "GLContext.hpp"
using namespace std;
struct Surface3
{
Vertex normal;
Vertex points[3];
TextureCoord texCoords[3];
};
| 13.5
| 27
| 0.740741
|
TonSharp
|
d91cf6b58e0d9ef32c0b2003e5ae0186af652950
| 4,819
|
cpp
|
C++
|
src/libQts/QtsTimeStamper.cpp
|
qtlmovie/qtlmovie
|
082ad5ea6522a02d5ac0d86f23cdd6152edff613
|
[
"BSD-2-Clause"
] | 8
|
2016-08-09T14:05:58.000Z
|
2020-09-05T14:43:36.000Z
|
src/libQts/QtsTimeStamper.cpp
|
qtlmovie/qtlmovie
|
082ad5ea6522a02d5ac0d86f23cdd6152edff613
|
[
"BSD-2-Clause"
] | 15
|
2016-08-09T14:11:21.000Z
|
2022-01-15T23:39:07.000Z
|
src/libQts/QtsTimeStamper.cpp
|
qtlmovie/qtlmovie
|
082ad5ea6522a02d5ac0d86f23cdd6152edff613
|
[
"BSD-2-Clause"
] | 1
|
2017-08-26T22:08:58.000Z
|
2017-08-26T22:08:58.000Z
|
//----------------------------------------------------------------------------
//
// Copyright (c) 2013-2017, Thierry Lelegard
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
//----------------------------------------------------------------------------
//
// Qts, the Qt MPEG Transport Stream library.
// Define the class QtsTimeStamper.
//
//----------------------------------------------------------------------------
#include "QtsTimeStamper.h"
//----------------------------------------------------------------------------
// Construction and reset.
//----------------------------------------------------------------------------
QtsTimeStamper::QtsTimeStamper(const QtsDemux* demux) :
_demux(demux)
{
reset();
}
void QtsTimeStamper::reset()
{
_pid = QTS_PID_NULL;
_source = UNDEFINED;
_lastTimeStamp = 0;
_previousClock = 0;
_delta = 0;
}
void QtsTimeStamper::setDemux(const QtsDemux* demux)
{
if (_demux != demux) {
_demux = demux;
if (_source == PCR) {
reset();
}
}
}
//----------------------------------------------------------------------------
// Process a new clock value in millisecond.
//----------------------------------------------------------------------------
void QtsTimeStamper::processClock(qint64 clock)
{
if (_source == UNDEFINED) {
// Source not yet set. The first timestamp is zero by definition.
// The first clock value shall be substracted to all subsequent clock values.
_delta = -clock;
}
else if (clock < _previousClock) {
// Our clock has wrapped up after the max value.
// The clock has restarted at zero and we must add the last
// time stamp before wrapping to all subsequent clock values.
_delta = _lastTimeStamp;
}
_lastTimeStamp = qMax<qint64>(0, clock + _delta);
_previousClock = clock;
}
//----------------------------------------------------------------------------
// Get the last timestamp in milliseconds, starting with zero.
//----------------------------------------------------------------------------
quint64 QtsTimeStamper::lastTimeStamp()
{
if ((_source == UNDEFINED || _source == PCR) && _demux != 0) {
const qint64 pcr = _demux->lastPcr();
if (pcr >= 0) {
// If previously undefined, our source is now PCR.
processClock(pcr / (QTS_SYSTEM_CLOCK_FREQ / 1000));
_source = PCR;
}
else {
// If previously PCR, our source is now undefined (problably a demux reset).
_source = UNDEFINED;
}
}
return _lastTimeStamp;
}
//----------------------------------------------------------------------------
// Process one PES packet from the reference PID.
//----------------------------------------------------------------------------
void QtsTimeStamper::processPesPacket(const QtsPesPacket& packet)
{
// If our source is PCR, we ignore all PES packets.
// If the packet has no PTS, it is useless anyway.
if (_source == PCR || !packet.hasPts()) {
return;
}
// Check or set the PID.
if (_pid == QTS_PID_NULL) {
_pid = packet.getSourcePid();
}
else if (packet.getSourcePid() != QTS_PID_NULL && packet.getSourcePid() != _pid) {
// Not the same PID, reject this packet.
return;
}
// We have a PTS on the right PID, PTS will now be our source (if not already).
processClock(packet.getPts() / (QTS_SYSTEM_CLOCK_SUBFREQ / 1000));
_source = PTS;
}
| 35.696296
| 88
| 0.550322
|
qtlmovie
|
0ba804d2e7625df0820087d850d2a864b2cf2882
| 16,584
|
cpp
|
C++
|
src/Window.cpp
|
Lehdari/evolution_simulator_2
|
daf7e8699e29cc25964f3a4234e3a1385ee7b1cf
|
[
"CC0-1.0"
] | null | null | null |
src/Window.cpp
|
Lehdari/evolution_simulator_2
|
daf7e8699e29cc25964f3a4234e3a1385ee7b1cf
|
[
"CC0-1.0"
] | null | null | null |
src/Window.cpp
|
Lehdari/evolution_simulator_2
|
daf7e8699e29cc25964f3a4234e3a1385ee7b1cf
|
[
"CC0-1.0"
] | null | null | null |
//
// Project: evolution_simulator_2
// File: Window.cpp
//
// Copyright (c) 2021 Miika 'Lehdari' Lehtimäki
// You may use, distribute and modify this code under the terms
// of the licence specified in file LICENSE which is distributed
// with this source code package.
//
#include <Window.hpp>
#include <Utils.hpp>
#include <Genome.hpp>
#include <CreatureComponent.hpp>
#include <FoodComponent.hpp>
#include <WorldSingleton.hpp>
#include <ConfigSingleton.hpp>
#include <LineSingleton.hpp>
#include <ResourceSingleton.hpp>
#include <MapSingleton.hpp>
#include <EventHandlers.hpp>
#include <imgui.h>
#include <backends/imgui_impl_sdl.h>
#include <backends/imgui_impl_opengl3.h>
#include <engine/LogicComponent.hpp>
#include <engine/EventComponent.hpp>
#include <graphics/SpriteSingleton.hpp>
Window::Window(
const Window::Settings &settings
) :
_settings (settings),
_window (nullptr),
_quit (false),
_paused (false),
_viewport (_settings.window.width, _settings.window.height,
Vec2f(_settings.window.width*0.5f, _settings.window.height*0.5f), 32.0f),
_cursorPosition (0.0f, 0.0f),
_activeCreature (-1),
_activeCreatureFollow (false),
_lastTicks (0),
_frameTicks (0),
_windowContext (*this),
_eventSystem (_ecs),
_creatureSystem (_ecs),
_foodSystem (_ecs),
_collisionSystem (_ecs, _eventSystem),
_spriteSystem (_ecs),
_spriteSheetId (-1)
{
int err;
// Initialize SDL
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
printf("Error: Could not initialize SDL!\n");
return;
}
_window = SDL_CreateWindow(
_settings.window.name.c_str(),
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
(int)_settings.window.width,
(int)_settings.window.height,
SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL);
if (_window == nullptr) {
printf("Error: SDL Window could not be created! SDL_Error: %s\n", SDL_GetError());
return;
}
// Initialize OpenGL
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, _settings.gl.contextMajor);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, _settings.gl.contextMinor);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, _settings.gl.contextFlags);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, _settings.gl.profileMask);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, _settings.gl.doubleBuffer);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
_glCtx = SDL_GL_CreateContext(_window);
if (_glCtx == nullptr) {
printf("Error: SDL OpenGL context could not be created! SDL_Error: %s\n",
SDL_GetError());
return;
}
// Load OpenGL extensions
if (!gladLoadGL()) {
printf("Error: gladLoadGL failed\n");
return;
}
// Initialize OpenGL
glViewport(0, 0, _settings.window.width, _settings.window.height);
glClearColor(0.2f, 0.2f, 0.2f, 1.f);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
// Initialize ImGui
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO(); (void)io;
ImGui_ImplSDL2_InitForOpenGL(_window, _glCtx);
ImGui_ImplOpenGL3_Init("#version 420");
// Initialize world
init();
}
Window::~Window()
{
// Destroy window and quit SDL subsystems
SDL_GL_DeleteContext(_glCtx);
SDL_DestroyWindow(_window);
SDL_Quit();
}
void Window::init(void)
{
_ecs.getSingleton<fug::SpriteSingleton>()->init();
_ecs.getSingleton<fug::SpriteSingleton>()->setWindowSize(
(int)_settings.window.width, (int)_settings.window.height);
_spriteSheetId = _ecs.getSingleton<fug::SpriteSingleton>()->addSpriteSheetFromFile(
EVOLUTION_SIMULATOR_RES("sprites/sprites.png"), 128, 128);
_ecs.getSingleton<LineSingleton>()->init();
_ecs.getSingleton<LineSingleton>()->setWindowSize(
(int)_settings.window.width, (int)_settings.window.height);
_ecs.getSingleton<ResourceSingleton>()->init(_spriteSheetId);
_ecs.getSingleton<MapSingleton>();
fug::SpriteComponent creatureSpriteComponent(_spriteSheetId, 0);
creatureSpriteComponent.setOrigin(Vec2f(ConfigSingleton::spriteRadius, ConfigSingleton::spriteRadius));
fug::SpriteComponent foodSpriteComponent(_spriteSheetId, 1);
foodSpriteComponent.setOrigin(Vec2f(ConfigSingleton::spriteRadius, ConfigSingleton::spriteRadius));
foodSpriteComponent.setColor(Vec3f(0.2f, 0.6f, 0.0f));
auto& config = *_ecs.getSingleton<ConfigSingleton>();
auto& map = *_ecs.getSingleton<MapSingleton>();
// Create creatures
constexpr int nCreatures = 2000;
for (int i=0; i<nCreatures; ++i) {
// get position using rejection sampling
Vec2f p(RNDS*1024.0f, RNDS*1024.0f);
while (gauss2(p, 256.0f) < RND)
p << RNDS*1024.0f, RNDS*1024.0f;
double mass = ConfigSingleton::minCreatureMass + RND*(
ConfigSingleton::maxCreatureMass-ConfigSingleton::minCreatureMass);
createCreature(_ecs, Genome(), mass, 1.0, p, RND*M_PI*2.0f, RND);
}
// Create food
constexpr int nFoods = 5000;
auto foodPositions = map.sampleFertility(nFoods);
for (auto& p : foodPositions) {
double mass = RNDRANGE(ConfigSingleton::minFoodMass, ConfigSingleton::maxFoodMass);
createFood(_ecs, FoodComponent::Type::PLANT, mass, p);
}
}
void Window::loop(void)
{
auto& map = *_ecs.getSingleton<MapSingleton>();
// Application main loop
while (!_quit) {
// Event handling
SDL_Event event;
while (SDL_PollEvent(&event) != 0) {
handleEvent(event);
}
// Render
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
if (!_paused)
updateWorld();
_creatureSystem.setStage(CreatureSystem::Stage::PROCESS_INPUTS);
_ecs.runSystem(_creatureSystem);
updateGUI();
// Render world
map.render(_viewport);
_ecs.runSystem(_spriteSystem);
_ecs.getSingleton<fug::SpriteSingleton>()->render(_viewport);
_ecs.getSingleton<LineSingleton>()->render(_viewport);
// Render ImGui
ImGui::Render();
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
// Swap draw and display buffers
SDL_GL_SwapWindow(_window);
if (!_paused) {
// Map update (GPGPU pass)
map.diffuseFertility();
}
uint32_t curTicks = SDL_GetTicks();
_frameTicks = curTicks - _lastTicks;
_lastTicks = curTicks;
}
}
void Window::handleEvent(SDL_Event& event)
{
static auto& world = *_ecs.getSingleton<WorldSingleton>();
switch (event.type) {
case SDL_WINDOWEVENT:
switch (event.window.event) {
case SDL_WINDOWEVENT_CLOSE:
_quit = true;
break;
}
break;
case SDL_KEYDOWN:
switch (event.key.keysym.sym) {
case SDLK_ESCAPE:
_quit = true;
break;
case SDLK_PAUSE:
_paused = !_paused;
break;
case SDLK_F12:
SDL_SetWindowFullscreen(_window, SDL_GetWindowFlags(_window) ^ SDL_WINDOW_FULLSCREEN);
break;
}
case SDL_MOUSEWHEEL:
_viewport.zoom(std::pow(1.414213562373f, (float)event.wheel.y), _cursorPosition);
break;
case SDL_MOUSEMOTION:
_cursorPosition << (float)event.motion.x, (float)event.motion.y;
break;
case SDL_MOUSEBUTTONDOWN:
switch (event.button.button) {
case SDL_BUTTON_LEFT: {
Vec2f clickWorldPos = _viewport.toWorld(_cursorPosition);
static Vec2f maxRadiusVec(
ConfigSingleton::maxObjectRadius, ConfigSingleton::maxObjectRadius);
// Find the clicked creature (if any)
Vector<fug::EntityId> entities;
world.getEntities(entities, clickWorldPos-maxRadiusVec, clickWorldPos+maxRadiusVec);
for (auto& eId : entities) {
if (_ecs.getComponent<FoodComponent>(eId) != nullptr)
continue;
auto* oc = _ecs.getComponent<fug::Orientation2DComponent>(eId);
if ((oc->getPosition()-clickWorldPos).norm() <
oc->getScale()*ConfigSingleton::spriteRadius) {
_activeCreature = eId;
break;
}
}
} break;
}
}
}
void Window::updateGUI()
{
static auto& world = *_ecs.getSingleton<WorldSingleton>();
static auto& config = *_ecs.getSingleton<ConfigSingleton>();
// Start the Dear ImGui frame
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplSDL2_NewFrame(_window);
ImGui::NewFrame();
{ // Main simulation controls
ImGui::Begin("Simulation Controls");
auto nCreatures = world.getNumberOf(WorldSingleton::EntityType::CREATURE);
auto nFood = world.getNumberOf(WorldSingleton::EntityType::FOOD);
ImGui::Text("N. Creatures: %lu\n", nCreatures);
ImGui::Text("N. Food: %lu\n", nFood);
ImGui::Checkbox("Paused", &_paused);
if (ImGui::CollapsingHeader("Food Controls")) {
static double foodPerTickMin = 0.001;
static double foodPerTickMax = 100.0;
ImGui::SliderScalar("foodPerTick", ImGuiDataType_Double, &config.foodPerTick,
&foodPerTickMin, &foodPerTickMax, "%.5f", ImGuiSliderFlags_Logarithmic);
static double foodGrowthRateMin = 0.0001;
static double foodGrowthRateMax = 0.1;
ImGui::SliderScalar("foodGrowthRate", ImGuiDataType_Double, &config.foodGrowthRate,
&foodGrowthRateMin, &foodGrowthRateMax, "%.5f", ImGuiSliderFlags_Logarithmic);
}
// mutation menu
if (ImGui::CollapsingHeader("Mutation")) {
// slider bounds and drop menu item names
static const float probabilityBounds[2] = { 0.0001f, 1.0f };
static const float amplitudeBounds[2] = { 0.0001f, 1.0f };
static const char* modeTitles[] = { "Additive", "Multiplicative" };
ImGui::Indent();
int stageId = 0;
// list all stages
for (auto stageIt = config.mutationStages.begin(); stageIt < config.mutationStages.end(); ++stageIt) {
auto& stage = *stageIt;
std::stringstream stageName;
stageName << "Stage " << ++stageId;
bool stageEnabled = true; // the following CollapsingHeader will set this to false to signify stage deletion
if (ImGui::CollapsingHeader(stageName.str().c_str(), &stageEnabled)) {
// element names
std::stringstream probabilityName, amplitudeName, modeName;
probabilityName << "Probability##evolution" << stageId;
amplitudeName << "Amplitude##evolution" << stageId;
modeName << "Mode##evolution" << stageId;
// sliders for probability and amplitude
ImGui::SliderScalar(probabilityName.str().c_str(), ImGuiDataType_Float, &stage.probability,
probabilityBounds, probabilityBounds+1, "%.5f", ImGuiSliderFlags_Logarithmic);
ImGui::SliderScalar(amplitudeName.str().c_str(), ImGuiDataType_Float, &stage.amplitude,
amplitudeBounds, amplitudeBounds+1, "%.5f", ImGuiSliderFlags_Logarithmic);
// drop menu for the mutation mode
const char* currentModeTitle = modeTitles[stage.mode];
if (ImGui::BeginCombo(modeName.str().c_str(), currentModeTitle)) {
for (int n = 0; n < IM_ARRAYSIZE(modeTitles); n++)
{
bool isSelected = (currentModeTitle == modeTitles[n]);
if (ImGui::Selectable(modeTitles[n], isSelected))
stage.mode = static_cast<Genome::MutationMode>(n);
if (isSelected)
ImGui::SetItemDefaultFocus();
}
ImGui::EndCombo();
}
}
// stage is deleted
if (!stageEnabled)
stageIt = config.mutationStages.erase(stageIt);
}
// button for adding new stages
if (ImGui::Button("Add Stage")) {
config.mutationStages.emplace_back(0.1f, 0.1f, Genome::MutationMode::ADDITIVE);
}
ImGui::Unindent();
}
ImGui::End();
}
if (_activeCreature >= 0) {
// Selected creature controls
auto* cc = _ecs.getComponent<CreatureComponent>(_activeCreature);
auto* oc = _ecs.getComponent<fug::Orientation2DComponent>(_activeCreature);
auto* sc = _ecs.getComponent<fug::SpriteComponent>(_activeCreature);
if (cc != nullptr && sc != nullptr) {
ImGui::Begin("Creature");
ImGui::Text("Creature %lu", _activeCreature);
ImGui::Text("Energy: %0.5f", cc->energy);
ImGui::Checkbox("Follow", &_activeCreatureFollow);
if (_activeCreatureFollow)
_viewport.centerTo(oc->getPosition());
Vec3f color = sc->getColor();
ImGui::ColorPicker3("Creature color", color.data());
sc->setColor(color);
ImGui::End();
}
else // creature has been removed
_activeCreature = -1;
}
}
void Window::updateWorld(void)
{
static auto& world = *_ecs.getSingleton<WorldSingleton>();
static auto& config = *_ecs.getSingleton<ConfigSingleton>();
static auto& map = *_ecs.getSingleton<MapSingleton>();
// initiate pixel data transfer from GPU
map.prefetch();
_creatureSystem.setStage(CreatureSystem::Stage::COGNITION);
_ecs.runSystem(_creatureSystem);
_creatureSystem.setStage(CreatureSystem::Stage::DYNAMICS);
_ecs.runSystem(_creatureSystem);
// map the pixel data memory
map.map();
if (_activeCreature >= 0 && _ecs.getComponent<CreatureComponent>(_activeCreature) == nullptr)
_activeCreature = -1;
_creatureSystem.setStage(CreatureSystem::Stage::REPRODUCTION);
_ecs.runSystem(_creatureSystem);
{ // Create new food
static double nNewFood = 0.0;
nNewFood += config.foodPerTick;
auto foodPositions = map.sampleFertility((int)nNewFood);
for (auto& p : foodPositions) {
createFood(_ecs, FoodComponent::Type::PLANT, ConfigSingleton::minFoodMass, p);
}
nNewFood -= (int)nNewFood;
}
if (world.getNumberOf(WorldSingleton::EntityType::CREATURE) < 1000) {
for (int i = 0l; i < 1000; ++i) { // create a new creatures
if (RND > 0.0001) continue;
Vec2f p(RNDS * 1024.0f, RNDS * 1024.0f);
while (gauss2(p, 256.0f) < RND)
p << RNDS * 1024.0f, RNDS * 1024.0f;
double mass = ConfigSingleton::minCreatureMass + RND * (
ConfigSingleton::maxCreatureMass - ConfigSingleton::minCreatureMass);
createCreature(_ecs, Genome(1.0f, RNDRANGE(0.001f, 0.005f)),
mass, 1.0, p, RND * M_PI * 2.0f, RND);
}
}
_foodSystem.setStage(FoodSystem::Stage::GROW);
_ecs.runSystem(_foodSystem);
// unmap the pixel data memory
map.unmap();
addEntitiesToWorld();
_ecs.runSystem(_collisionSystem);
while (_eventSystem.swap())
_ecs.runSystem(_eventSystem);
addEntitiesToWorld();
}
void Window::addEntitiesToWorld(void)
{
_ecs.getSingleton<WorldSingleton>()->reset();
_creatureSystem.setStage(CreatureSystem::Stage::ADD_TO_WORLD);
_ecs.runSystem(_creatureSystem);
_foodSystem.setStage(FoodSystem::Stage::ADD_TO_WORLD);
_ecs.runSystem(_foodSystem);
}
| 35.435897
| 124
| 0.599855
|
Lehdari
|
0ba95ca95977bdcd247d1625b254eb9ca1388f52
| 889
|
cpp
|
C++
|
Native/Framework/source/Tools/ModelPipeline/Program.cpp
|
btrowbridge/DirectX.2D.Bespoke.Games
|
382728f7c9d50597f9fc84e222efd468c33716a5
|
[
"MS-PL"
] | null | null | null |
Native/Framework/source/Tools/ModelPipeline/Program.cpp
|
btrowbridge/DirectX.2D.Bespoke.Games
|
382728f7c9d50597f9fc84e222efd468c33716a5
|
[
"MS-PL"
] | null | null | null |
Native/Framework/source/Tools/ModelPipeline/Program.cpp
|
btrowbridge/DirectX.2D.Bespoke.Games
|
382728f7c9d50597f9fc84e222efd468c33716a5
|
[
"MS-PL"
] | null | null | null |
#include "pch.h"
using namespace std;
using namespace ModelPipeline;
using namespace Library;
int main(int argc, char* argv[])
{
#if defined(DEBUG) | defined(_DEBUG)
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
#endif
try
{
if (argc < 2)
{
throw exception("Usage: ModelPipeline pathToInputFile");
}
string inputFile = argv[1];
string inputFilename;
string inputDirectory;
Library::Utility::GetFileNameAndDirectory(inputFile, inputDirectory, inputFilename);
if (inputDirectory.empty())
{
inputDirectory = UtilityWin32::CurrentDirectory();
}
SetCurrentDirectory(Library::Utility::ToWideString(inputDirectory).c_str());
Model model = ModelProcessor::LoadModel(inputFilename, true);
string outputFilename = inputFilename + ".bin";
model.Save(outputFilename);
}
catch (exception ex)
{
cout << ex.what();
}
return 0;
}
| 21.682927
| 86
| 0.723285
|
btrowbridge
|
0bad188a8c9958ee5f94c4ca05a73f0cf8ef61b5
| 355
|
cpp
|
C++
|
codeforce3/580A. Kefa and First Steps.cpp
|
khaled-farouk/My_problem_solving_solutions
|
46ed6481fc9b424d0714bc717cd0ba050a6638ef
|
[
"MIT"
] | null | null | null |
codeforce3/580A. Kefa and First Steps.cpp
|
khaled-farouk/My_problem_solving_solutions
|
46ed6481fc9b424d0714bc717cd0ba050a6638ef
|
[
"MIT"
] | null | null | null |
codeforce3/580A. Kefa and First Steps.cpp
|
khaled-farouk/My_problem_solving_solutions
|
46ed6481fc9b424d0714bc717cd0ba050a6638ef
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
int const N = 1e5 + 1;
int n, a[N];
int main() {
cin >> n;
for(int i = 0; i < n; ++i)
cin >> a[i];
a[n] = -1;
int lst = a[0], res = 0;
for(int i = 0, tmp; i < n; ++i) {
tmp = i;
while(a[i] <= a[i + 1])
++i;
res = max(res, i - tmp + 1);
}
cout << res << endl;
return 0;
}
| 13.653846
| 35
| 0.43662
|
khaled-farouk
|
0bad32c49e39045d506aed745a89a492e63810e4
| 1,062
|
cpp
|
C++
|
gmtl-0.6.1/examples/faqexample.cpp
|
Glitch0011/QuadTree-Example
|
3558c999f68475bc98b8fa33b0f6d14076c9ec48
|
[
"MIT"
] | null | null | null |
gmtl-0.6.1/examples/faqexample.cpp
|
Glitch0011/QuadTree-Example
|
3558c999f68475bc98b8fa33b0f6d14076c9ec48
|
[
"MIT"
] | null | null | null |
gmtl-0.6.1/examples/faqexample.cpp
|
Glitch0011/QuadTree-Example
|
3558c999f68475bc98b8fa33b0f6d14076c9ec48
|
[
"MIT"
] | null | null | null |
/** This is an example about a lot of cool stuff.
* The comments in this example use a slightly special
* format to make them easy to process into
* doxygen backend stuff.
*/
/* These are the headers that we need to include.
* They are all needed because we say so.
*/
#include <gmtl/gmtl.h>
#include <gmtl/Matrix.h>
int main()
{
/* @exskip
* This is ugly stuff to skip for now.
*/
gmtl::somethingUgly();
/* @exendskip */
/**
* Example of creating a matrix and doing stuff
*/
// Test for allowing this type of comment through.
gmtl::Matrix44f test_matrix;
gmtl::invert(test_matrix);
/** Here is an example of creating a Vector */
gmtl::Vec3f test_vector;
test_vector += gmtl::Vec3f(1.0, 0.0f, 1.0f);
/** @subsection multexample Example of multiplication
*
* This is an example of matrix multiplication.
* We like to do this all the time in the code
*/
gmtl::Matrix44f mat1, mat2, mat3;
mat3 = mat1 * mat2;
// You can do it this way to.
gmtl::mult(mat3, mat1, mat2);
return 1;
}
| 24.697674
| 56
| 0.654426
|
Glitch0011
|
0bb7a8234e4429790c908a27256cde3d8ba6f2a7
| 1,220
|
cc
|
C++
|
10-More-about-MergeSort/cpp/09-Solving-Reverse-Pairs-Problem-by-MergeSort/Solution2.cc
|
OpenCreate/Play-with-DSA
|
49de3eb3e54815d1ff6520e5933e467c1f56bdfc
|
[
"MIT"
] | 9
|
2020-08-10T03:43:54.000Z
|
2021-11-12T06:26:32.000Z
|
10-More-about-MergeSort/cpp/09-Solving-Reverse-Pairs-Problem-by-MergeSort/Solution2.cc
|
OpenCreate/Play-with-DSA
|
49de3eb3e54815d1ff6520e5933e467c1f56bdfc
|
[
"MIT"
] | null | null | null |
10-More-about-MergeSort/cpp/09-Solving-Reverse-Pairs-Problem-by-MergeSort/Solution2.cc
|
OpenCreate/Play-with-DSA
|
49de3eb3e54815d1ff6520e5933e467c1f56bdfc
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <vector>
using namespace std;
class Solution2 {
public:
int reversePairs(vector<int> &nums) {
int res = 0;
vector<int> temp(nums);
res = sort(nums, 0, nums.size() - 1, temp);
return res;
}
private:
int sort(vector<int> &nums, int l, int r, vector<int> &temp) {
if (l >= r) return 0;
int mid = l + (r - l) / 2;
int res = 0;
res += sort(nums, l, mid, temp);
res += sort(nums, mid + 1, r, temp);
if (nums[mid] > nums[mid + 1]) res += merge(nums, l, mid, r, temp);
return res;
}
int merge(vector<int> &nums, int l, int mid, int r, vector<int> &temp) {
copy(nums.begin() + l, nums.begin() + r + 1, temp.begin() + l);
int i = l, j = mid + 1;
int res = 0;
for (int k = l; k <= r; k++) {
if (i > mid) {
nums[k] = temp[j];
j++;
} else if (j > r) {
nums[k] = temp[i];
i++;
} else if (temp[i] > temp[j]) {
res += mid - i + 1;
nums[k] = temp[j];
j++;
} else {
nums[k] = temp[i];
i++;
}
}
return res;
}
};
int main() {
vector<int> vec{7, 5, 6, 4};
cout << Solution2().reversePairs(vec) << endl;
return 0;
}
| 21.403509
| 74
| 0.47623
|
OpenCreate
|
0bb98d873e78976da89a6d136a3216e1db481ffe
| 2,512
|
cpp
|
C++
|
DX11 Framework/utility/Vector3D.cpp
|
kyle-robinson/dx11-framework
|
7e4f6517b4e7e3ddda405250c46815e6e970207d
|
[
"MIT"
] | 1
|
2021-04-22T03:15:56.000Z
|
2021-04-22T03:15:56.000Z
|
DX11 Framework/utility/Vector3D.cpp
|
kyle-robinson/dx11-framework
|
7e4f6517b4e7e3ddda405250c46815e6e970207d
|
[
"MIT"
] | null | null | null |
DX11 Framework/utility/Vector3D.cpp
|
kyle-robinson/dx11-framework
|
7e4f6517b4e7e3ddda405250c46815e6e970207d
|
[
"MIT"
] | null | null | null |
#include "Vector3D.h"
#include <sstream>
#include <math.h>
#include <cmath>
#include <assert.h>
#include <debugapi.h>
Vector3D::Vector3D() : x( 0 ), y( 0 ), z( 0 ) { }
Vector3D::Vector3D( float x, float y, float z ) : x( x ), y( y ), z( z ) { }
Vector3D::Vector3D( const Vector3D &vec ) : x( vec.x ), y( vec.y ), z( vec.z ) { }
Vector3D Vector3D::operator+( const Vector3D &vec )
{
return Vector3D( x + vec.x, y + vec.y, z + vec.z );
}
Vector3D& Vector3D::operator+=( const Vector3D &vec )
{
x += vec.x;
y += vec.y;
z += vec.z;
return *this;
}
Vector3D Vector3D::operator-( const Vector3D &vec )
{
return Vector3D( x - vec.x, y - vec.y, z - vec.z );
}
Vector3D& Vector3D::operator-=( const Vector3D &vec )
{
x -= vec.x;
y -= vec.y;
z -= vec.z;
return *this;
}
Vector3D Vector3D::operator*( float value )
{
return Vector3D( x * value, y * value, z * value );
}
Vector3D& Vector3D::operator*=( float value )
{
x *= value;
y *= value;
z *= value;
return *this;
}
Vector3D Vector3D::operator/( float value )
{
assert( value != 0, "Vector Division: Value was equal to 0!" );
return Vector3D( x / value, y / value, z / value );
}
Vector3D& Vector3D::operator/=( float value )
{
x *= value;
y *= value;
z *= value;
return *this;
}
Vector3D& Vector3D::operator=( const Vector3D &vec )
{
x = vec.x;
y = vec.y;
z = vec.z;
return Vector3D( x, y, z );
}
float Vector3D::DotProduct( const Vector3D &vec )
{
return ( x * vec.x + y + vec.y + x * vec.z );
}
Vector3D Vector3D::CrossProduct( const Vector3D &vec )
{
return Vector3D(
y * vec.z - z * vec.y,
z * vec.x - x * vec.z,
x * vec.y - y * vec.x
);
}
Vector3D Vector3D::Normalization()
{
float magnitude = this->Magnitude();
x /= magnitude;
y /= magnitude;
z /= magnitude;
return Vector3D( x, y, z );
}
float Vector3D::Square()
{
return pow( x, x ) + pow( y, y ) + pow( z, z );
}
float Vector3D::Distance( const Vector3D &vec )
{
return sqrt(
pow( x - ( -vec.x ), x - ( -vec.x ) ) +
pow( y - ( -vec.y ), y - ( -vec.y ) ) +
pow( z - ( -vec.z ), z - ( -vec.z ) )
);
}
float Vector3D::Magnitude()
{
float squared = this->Square();
return sqrt( squared );
}
float Vector3D::ShowX() const noexcept
{
return this->x;
}
float Vector3D::ShowY() const noexcept
{
return this->y;
}
float Vector3D::ShowZ() const noexcept
{
return this->z;
}
void Vector3D::Display() noexcept
{
std::ostringstream oss;
oss << "x: " << x;
oss << "\ty: " << y;
oss << "\tz: " << z;
OutputDebugStringA( oss.str().c_str() );
}
| 17.942857
| 82
| 0.591959
|
kyle-robinson
|
0bbac2da2f5a4bbc70f66b97e89a02a9f7006025
| 328
|
cpp
|
C++
|
Algorithm/stack-based/TOH.cpp
|
Alquama00s/DS-Algo
|
594b04e8d119a188763481209cbfcc49c62fc002
|
[
"MIT"
] | null | null | null |
Algorithm/stack-based/TOH.cpp
|
Alquama00s/DS-Algo
|
594b04e8d119a188763481209cbfcc49c62fc002
|
[
"MIT"
] | null | null | null |
Algorithm/stack-based/TOH.cpp
|
Alquama00s/DS-Algo
|
594b04e8d119a188763481209cbfcc49c62fc002
|
[
"MIT"
] | null | null | null |
#include<iostream>
using namespace std;
void TOH(int n,char I,char F,char A){
if(n==1){
cout<<"moving top disk from "<<I<<" to "<<F<<"\n";
}else{
TOH(n-1,I,A,F);
cout<<"move top disk from "<<I<<" to "<<F<<"\n";
TOH(n-1,A,F,I);
}
}
int main(){
TOH(3,'I','F','A');
return 0;
}
| 21.866667
| 59
| 0.466463
|
Alquama00s
|
0bbce92c471249cca5f10b7eb437600e68408103
| 11,997
|
cpp
|
C++
|
server/src/WSStreamer.cpp
|
urbenlegend/WebStreamer
|
562b16a4b8e10cce25c4088e38e83f93bc87e1ee
|
[
"MIT"
] | 42
|
2015-09-19T13:33:02.000Z
|
2021-08-12T18:36:51.000Z
|
server/src/WSStreamer.cpp
|
cqzhanghy/WebStreamer
|
562b16a4b8e10cce25c4088e38e83f93bc87e1ee
|
[
"MIT"
] | 3
|
2015-08-05T19:09:03.000Z
|
2017-08-08T18:30:53.000Z
|
server/src/WSStreamer.cpp
|
cqzhanghy/WebStreamer
|
562b16a4b8e10cce25c4088e38e83f93bc87e1ee
|
[
"MIT"
] | 14
|
2015-09-20T14:01:56.000Z
|
2020-01-06T17:26:28.000Z
|
#include <string>
#include <fstream>
#include <vector>
#include "boost/shared_ptr.hpp"
#include "boost/asio.hpp"
#include "websocketpp.hpp"
#include "websocket_connection_handler.hpp"
#include "utils.h"
#include "rtpdump.h"
#include "WSStreamer.h"
using namespace std;
extern ofstream debug;
vector<unsigned char> readNAL(ifstream& stream, int numOfUnits) {
vector<unsigned char> buffer;
char byte_read;
for (int i = 0; i < numOfUnits && stream.good(); i++) {
int end_count = 0;
bool extract = false;
// Extract bytes and put into vector for sending
while (true) {
stream.read(&byte_read, 1);
if (!stream.good()) {
break;
}
if (extract) {
buffer.push_back(byte_read);
}
// Check for NAL header 0 0 0 1
if (byte_read == 0 && end_count < 3 || byte_read == 1 && end_count == 3) {
end_count++;
}
else {
end_count = 0;
}
if (end_count == 4) {
// Reset NAL header count
end_count = 0;
if (extract) {
// Delete beginning of next NAL from current NAL array and decrement read pointer so that NAL is available for next read
stream.seekg(stream.tellg() - (streampos)4);
buffer.erase(buffer.end() - 4, buffer.end());
break;
}
else {
// Insert NAL header that's been detected into NAL array
for (int i = 0; i < 3; i++) {
buffer.push_back(0);
}
buffer.push_back(1);
extract = true;
}
}
}
}
return buffer;
}
int sendNAL(websocketpp::session_ptr client, shared_ptr<ifstream> file, int nals) {
if (file->good()) {
vector<unsigned char> buffer = readNAL(*file.get(), nals);
client->send(buffer);
//debug.write((char*)&buffer[0], buffer.size());
return buffer.size();
}
else {
return 0;
}
}
streamsize sendChunk(websocketpp::session_ptr client, shared_ptr<ifstream> file, int chunk_size) {
if (file->good()) {
char* read_buffer = new char[chunk_size];
vector<unsigned char> send_buffer;
file->read(read_buffer, chunk_size);
send_buffer.assign(read_buffer, read_buffer + file->gcount());
client->send(send_buffer);
delete [] read_buffer;
return file->gcount();
}
else {
return 0;
}
}
streamsize sendRTP(websocketpp::session_ptr client, shared_ptr<ifstream> file, int packets) {
if (file->good()) {
// Read file header
char packet_hdr_array[sizeof(RD_packet_t)];
file->read(packet_hdr_array, sizeof(packet_hdr_array));
RD_packet_t* packet_hdr = (RD_packet_t*)packet_hdr_array;
packet_hdr->length = ntohs(packet_hdr->length);
packet_hdr->plen = ntohs(packet_hdr->plen);
packet_hdr->offset = ntohl(packet_hdr->offset);
// Extract actual RTP packet
char* rtp_packet = new char[packet_hdr->plen];
file->read(rtp_packet, packet_hdr->plen);
vector<unsigned char> send_buffer;
send_buffer.assign(rtp_packet, rtp_packet + file->gcount());
client->send(send_buffer);
delete [] rtp_packet;
return file->gcount();
}
else {
return 0;
}
}
// Thread function that reads bytes
void wschunk_thread_func(shared_ptr<guarded_var<bool>> thread_continue, websocketpp::session_ptr client, shared_ptr<ifstream> file, int chunk_size, int sleep_time) {
vector<unsigned char> send_buffer;
while (sendChunk(client, file, chunk_size)) {
if (thread_continue->get() == false) {
break;
}
Sleep(sleep_time);
}
}
// Thread function that reads NALS
void wsnal_thread_func(shared_ptr<guarded_var<bool>> thread_continue, websocketpp::session_ptr client, shared_ptr<ifstream> file, int nals, int sleep_time) {
while (sendNAL(client, file, nals)) {
if (thread_continue->get() == false) {
break;
}
Sleep(sleep_time);
}
}
// Thread function that reads NALS
void wsrtp_thread_func(shared_ptr<guarded_var<bool>> thread_continue, websocketpp::session_ptr client, shared_ptr<ifstream> file, int packets, int sleep_time) {
while (sendRTP(client, file, packets)) {
if (thread_continue->get() == false) {
break;
}
Sleep(sleep_time);
}
}
WSStreamerHandler::WSStreamerHandler() {
}
WSStreamerHandler::~WSStreamerHandler() {
}
void WSStreamerHandler::validate(websocketpp::session_ptr client) {
// Check if requested resource exists
if (client->get_resource() == "/") {
cout << "INFO: Client is connecting without asking for a resource" << endl;
}
else {
ifstream resource(client->get_resource().substr(1).c_str(), ios::binary);
if (!resource.is_open()) {
string err = "Request for unknown resource " + client->get_resource();
cerr << err << endl;
throw(websocketpp::handshake_error(err, 404));
}
else {
cout << "INFO: Client request for " + client->get_resource() + " accepted" << endl;
resource.close();
}
}
}
void WSStreamerHandler::on_open(websocketpp::session_ptr client) {
if (client->get_resource() != "/") {
shared_ptr<ifstream> resource(new ifstream(client->get_resource().substr(1).c_str(), ios::binary));
if (resource->is_open()) {
cout << "INFO: Client has connected and opened " + client->get_resource() << endl;
// Check if it is a rtpdump file. If it is, fast foward past file header
if (resource->good()) {
streampos filestart = resource->tellg();
char* rtpdumphdr = new char[strlen(RTPPLAY_MAGIC)];
resource->read(rtpdumphdr, strlen(RTPPLAY_MAGIC));
if (resource->gcount() == strlen(RTPPLAY_MAGIC) && strncmp(rtpdumphdr, RTPPLAY_MAGIC, strlen(RTPPLAY_MAGIC)) == 0) {
cout << "INFO: Requested file is an rtpdump file. Fast forwarding past file header" << endl;
resource->ignore(sizeof(RD_hdr_t));
}
else {
// Reset file to beginning if we do not see rtpdump header
resource->seekg(filestart);
}
delete[] rtpdumphdr;
}
WSSClientInfo clientInfo;
clientInfo.resource = resource;
connections.insert(pair<websocketpp::session_ptr, WSSClientInfo>(client, clientInfo));
}
else {
cerr << "ERROR: Client has connected but server is unable to access " + client->get_resource() << endl;
client->send("ERROR: Failed to open resource");
}
}
}
void WSStreamerHandler::on_close(websocketpp::session_ptr client) {
map<websocketpp::session_ptr, WSSClientInfo>::iterator connection = connections.find(client);
if (connection != connections.end()) {
// Close file handle and remove connection from connections list.
if (connection->second.resource) {
connection->second.resource->close();
}
if (connection->second.thread) {
*(connection->second.thread_continue) = false;
connection->second.thread->join();
}
connections.erase(connection);
cout << "INFO: Client has disconnected" << endl;
}
}
void WSStreamerHandler::on_message(websocketpp::session_ptr client, const std::string &msg) {
cout << "CLIENTMSG: " << msg << endl;
// Find client info and file handle in connections map
map<websocketpp::session_ptr, WSSClientInfo>::iterator connection = connections.find(client);
if (connection == connections.end()) {
cerr << "ERROR: Received message from an unknown client" << endl;
}
WSSClientInfo& clientInfo = connection->second;
// Parse request from client and send data appropriately
vector<string> tokens;
tokenize(msg, tokens);
if (tokens.size() >= 2) {
bool continuous_stream;
if (tokens[0] == "REQUESTSTREAM") {
continuous_stream = true;
}
else if (tokens[0] == "REQUEST") {
continuous_stream = false;
}
else {
cerr << "ERROR: Client has sent an invalid request" << endl;
}
// Parse message size token
string chunk_type;
int temp_size = 0;
int byte_multiplier = 0;
int sleep_time = 0;
splitIntUnit(tokens[1], temp_size, chunk_type);
if (temp_size == 0) {
cerr << "ERROR: Client has specified an invalid request size" << endl;
return;
}
if (chunk_type == "MB") {
byte_multiplier = 1048576;
}
else if (chunk_type == "KB") {
byte_multiplier = 1024;
}
else if (chunk_type == "B") {
byte_multiplier = 1;
}
else if (chunk_type == "NAL") {
// For miscellaneous accepted units, do nothing
}
else if (chunk_type == "RTP") {
// For miscellaneous accepted units, do nothing
}
else {
cerr << "ERROR: Client has specified an invalid request unit" << endl;
return;
}
// Parse stream rate token
if (tokens.size() == 3) {
string unit;
splitIntUnit(tokens[2], sleep_time, unit);
if (sleep_time < 0 || unit != "MS") {
cerr << "ERROR: Client has specified an invalid delay time" << endl;
return;
}
}
// Initiate streaming
if (chunk_type == "MB" || chunk_type == "KB" || chunk_type == "B") {
// Send file in chunks of chunk_size bytes
unsigned int chunk_size = temp_size * byte_multiplier;
if (continuous_stream) {
if (clientInfo.thread) {
cerr << "ERROR: Already streaming data to client" << endl;
}
else {
cout << "INFO: Streaming data to client in " << chunk_size << " byte chunks with " << sleep_time << " MS delay" << endl;
clientInfo.thread_continue.reset(new guarded_var<bool>(continuous_stream));
clientInfo.thread.reset(new boost::thread(wschunk_thread_func, clientInfo.thread_continue, client, clientInfo.resource, chunk_size, sleep_time));
}
}
else {
cout << "INFO: Sending a " << chunk_size << " byte chunk to client" << endl;
sendChunk(client, clientInfo.resource, chunk_size);
}
}
else if (chunk_type == "NAL") {
// Send file in NAL units
if (continuous_stream) {
if (clientInfo.thread) {
cerr << "ERROR: Already streaming data to client" << endl;
}
else {
cout << "INFO: Streaming data to client in " << temp_size << " NAL chunks with " << sleep_time << " MS delay" << endl;
clientInfo.thread_continue.reset(new guarded_var<bool>(continuous_stream));
clientInfo.thread.reset(new boost::thread(wsnal_thread_func, clientInfo.thread_continue, client, clientInfo.resource, temp_size, sleep_time));
}
}
else {
cout << "INFO: Sending " << temp_size << " NAL chunk to client" << endl;
sendNAL(client, clientInfo.resource, temp_size);
}
}
else if (chunk_type == "RTP") {
if (continuous_stream) {
if (clientInfo.thread) {
cerr << "ERROR: Already streaming data to client" << endl;
}
else {
cout << "INFO: Streaming data to client in " << temp_size << " RTP chunks with " << sleep_time << " MS delay" << endl;
clientInfo.thread_continue.reset(new guarded_var<bool>(continuous_stream));
clientInfo.thread.reset(new boost::thread(wsrtp_thread_func, clientInfo.thread_continue, client, clientInfo.resource, temp_size, sleep_time));
}
}
else {
cout << "INFO: Sending " << temp_size << " RTP chunk to client" << endl;
sendRTP(client, clientInfo.resource, temp_size);
}
}
}
else if (tokens.size() == 1) {
if (tokens[0] == "STOPSTREAM") {
if (clientInfo.thread) {
*(clientInfo.thread_continue) = false;
clientInfo.thread->join();
clientInfo.thread = NULL;
}
}
}
else {
cerr << "ERROR: Invalid request from client" << endl;
}
}
void WSStreamerHandler::on_message(websocketpp::session_ptr client,
const std::vector<unsigned char> &data) {
// Ignore binary data
debug.write((char*)&data[0], data.size());
//char pad[] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
//debug.write(pad, 6);
//cerr << "WARNING: Discarding binary data received from client" << endl;
}
WSStreamer::WSStreamer(string host, string port) : streamer(new WSStreamerHandler()),
endpoint(tcp::v4(), atoi(port.c_str())),
server(new websocketpp::server(io_service, endpoint, streamer))
{
string full_host = host + ":" + port;
// setup server settings
server->add_host(full_host);
server->add_host("localhost:" + port);
// start the server
server->start_accept();
}
WSStreamer::~WSStreamer() {
stop();
}
void WSStreamer::run() {
if (!iosrv_thread) {
iosrv_thread = shared_ptr<boost::thread>(new boost::thread(boost::ref(*this)));
}
}
void WSStreamer::runAndBlock() {
io_service.run();
}
void WSStreamer::stop() {
io_service.stop();
iosrv_thread->join();
iosrv_thread.reset();
}
void WSStreamer::operator()() {
io_service.run();
}
| 30.372152
| 165
| 0.674752
|
urbenlegend
|
0bbe6460148f47156b49021f25cf9ea43874ee2a
| 369
|
cpp
|
C++
|
2021.09.27_homework-3/Project3/Source.cpp
|
HudzievaPolina/programming-c-2021-1course-
|
f4e0c769419d12f95c42913980bbdc053302b7c6
|
[
"Apache-2.0"
] | null | null | null |
2021.09.27_homework-3/Project3/Source.cpp
|
HudzievaPolina/programming-c-2021-1course-
|
f4e0c769419d12f95c42913980bbdc053302b7c6
|
[
"Apache-2.0"
] | null | null | null |
2021.09.27_homework-3/Project3/Source.cpp
|
HudzievaPolina/programming-c-2021-1course-
|
f4e0c769419d12f95c42913980bbdc053302b7c6
|
[
"Apache-2.0"
] | null | null | null |
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
int a = 1;
int n = 0;
cin >> n;
for (int i = 1; i <= n; ++i)
{
for (int j = 1; j <= i; ++j)
{
if (j == i || a == n)
{
cout << a << " " << endl;
a++;
break;
}
else
{
cout << a << " ";
a++;
}
}
if (a > n)
break;
}
return EXIT_SUCCESS;
}
| 11.903226
| 32
| 0.401084
|
HudzievaPolina
|
0bbf5ad61ba8db5ba02b382b9c17078337aa6faa
| 1,173
|
cpp
|
C++
|
Chapter-4-Making-Decisions/Review Questions and Exercises/Algorithm Workbench/41.cpp
|
jesushilarioh/DelMarCSi.cpp
|
6dd7905daea510452691fd25b0e3b0d2da0b06aa
|
[
"MIT"
] | 3
|
2019-02-02T16:59:48.000Z
|
2019-02-28T14:50:08.000Z
|
Chapter-4-Making-Decisions/Review Questions and Exercises/Algorithm Workbench/41.cpp
|
jesushilariohernandez/DelMarCSi.cpp
|
6dd7905daea510452691fd25b0e3b0d2da0b06aa
|
[
"MIT"
] | null | null | null |
Chapter-4-Making-Decisions/Review Questions and Exercises/Algorithm Workbench/41.cpp
|
jesushilariohernandez/DelMarCSi.cpp
|
6dd7905daea510452691fd25b0e3b0d2da0b06aa
|
[
"MIT"
] | 4
|
2020-04-10T17:22:17.000Z
|
2021-11-04T14:34:00.000Z
|
/********************************************************************
*
* 41. Match the conditional expression with the if/else
* statement that performs the same operation.
*
* A) q = x < y ? a + b : x * 2;
* B) q = x < y ? x * 2 : a + b;
* C) x < y ? q = 0 : q = 1;
* ____ if (x < y)
* q = 0;
* else
* q = 1;
*
* ____ if (x < y)
* q = a + b;
* else
* q = x * 2;
*
* ____ if (x < y)
* q = x * 2;
* else
* q = a + b;
*
* Jesus Hilario Hernandez
* February 1, 2018
*
********************************************************************/
#include <iostream>
using namespace std;
int main()
{
// Variables
int a, b, q, x, y;
// Solution for A) q = (x < y) ? (a + b) : (x * 2);
if (x < y)
q = a + b;
else
q = x * 2;
// Solution for B) q = x < y ? x * 2 : a + b;
if (x < y)
q = x * 2;
else
q = a + b;
// Solution for C) x < y ? q = 0 : q = 1;
if (x < y)
q = 0;
else
q = 1;
// Terminate program
return 0;
}
| 20.578947
| 69
| 0.311168
|
jesushilarioh
|
0bc2810b2261b1a9ce35f7563376965ba463f9f4
| 3,211
|
cpp
|
C++
|
Sesion2/main.cpp
|
Miguel445Ar/A-y-R-Algoritmos-1
|
c9b64573965d5c4371d2de1a1fff1a9425c34388
|
[
"CC0-1.0"
] | null | null | null |
Sesion2/main.cpp
|
Miguel445Ar/A-y-R-Algoritmos-1
|
c9b64573965d5c4371d2de1a1fff1a9425c34388
|
[
"CC0-1.0"
] | null | null | null |
Sesion2/main.cpp
|
Miguel445Ar/A-y-R-Algoritmos-1
|
c9b64573965d5c4371d2de1a1fff1a9425c34388
|
[
"CC0-1.0"
] | null | null | null |
#include <iostream>
#include <functional>
#include <vector>
#include <algorithm>
#include <string>
using std::cout;
using std::cin;
using std::function;
using std::vector;
using std::sort;
using std::string;
// Functores en C++ (Los de verdad)
class Inc
{
int num;
public:
Inc(int n) : num(n) { }
// This operator overloading enables calling
// operator function () on objects of increment
int operator () (int arr_num) const {
return num + arr_num;
}
int getNum(){
return num;
}
};
int sumar(int a, int b) {
int r = a + b;
return r;
}
void exec(int (*func)(int,int), int a, int b){
cout << func(a,b);
}
int sumar2(int a, int b) {
int r = a + b;
return r;
}
void exec2(function<int(int,int)> func, int a, int b){
cout << func(a,b);
}
template<class T>
struct Elem {
T value;
};
template<class T>
class MyVector {
Elem<T>** arreglo;
size_t size;
function<void(T)> show;
public:
MyVector(function<void(T)> show): show(show){
size = 0;
arreglo = nullptr;
}
void pushBack(T v){
Elem<T>* newValue = new Elem<T>;
newValue->value = v;
Elem<T>** aux = new Elem<T>*[size+1];
for(size_t i = 0; i<size;++i){
aux[i] = arreglo[i];
}
aux[size] = newValue;
if(!arreglo)
delete[] arreglo;
arreglo = aux;
++size;
}
T& operator[](size_t i){
return arreglo[i]->value;
}
size_t Size(){
return this->size;
}
void print(){
for(size_t i = 0; i<size;++i)
show(arreglo[i]->value);
}
};
class Persona {
int dni;
string nombre;
public:
Persona(int dni = 0, string nombre = ""): dni(dni), nombre(nombre){}
string mostrar(){
return std::to_string(dni) + " " + nombre;
}
};
int f(int n){
if (n == 1)
return 1;
return n * f(n-1);
}
// Serie de Fibonacci Recursiva
// Imprimir un triángulo rectángulo de * de forma recursiva
// Imprimir un triángulo equilátero de * de forma recursiva
int main(){
int a = 10;
int b = 8;
vector<int> numeros = {1,4,7,2,8,4,9};
auto comp = [](int a, int b) -> bool { return a < b;};
sort(numeros.begin(),numeros.end(), comp);
for (size_t i = 0;i <numeros.size();++i)
cout << numeros[i] << "\n";
auto show = [](Persona p) -> void {
cout << p.mostrar() << "\n";
};
MyVector<Persona> v(show);
v.pushBack(Persona(12134,"Miguel"));
v.pushBack(Persona(132454356,"Ana"));
v.print();
v.print();
v.print();
cout << "\n";
cout << f(5) << "\n";
//C++
// auto aux = sumar;
// auto aux = [](int a, int b) -> int {
//return a + b;
//};
//function<int(int,int)> aux = sumar;
//vector<function<int(int,int)>> funciones;
//function<int(int,int)> aux = [](int a, int b) -> int {
//return a + b;
//};
//exec2(aux,a,b);
//exec2([](int a, int b) -> int {return a + b; },a,b);
// C
//int (*ptr)(int,int);
//int (*ptr[2])(int,int);
//ptr[0] = sumar;
//ptr[1] = sumar2;
//ptr = &sumar;
//exec(sumar,a,b);
return 0;
}
| 20.06875
| 72
| 0.521956
|
Miguel445Ar
|
0bc71853638f5b80269dd0cd94279ff60a22cbf6
| 21,082
|
cpp
|
C++
|
source/main.cpp
|
io55/ART_IO55
|
8c7fa55955260a4ba4c780fa8ae8c0bba775e1b7
|
[
"Unlicense"
] | 1
|
2022-03-12T02:43:54.000Z
|
2022-03-12T02:43:54.000Z
|
source/main.cpp
|
io55/ART_IO55
|
8c7fa55955260a4ba4c780fa8ae8c0bba775e1b7
|
[
"Unlicense"
] | null | null | null |
source/main.cpp
|
io55/ART_IO55
|
8c7fa55955260a4ba4c780fa8ae8c0bba775e1b7
|
[
"Unlicense"
] | null | null | null |
#include <grrlib.h>
#include <stdlib.h>
#include <wiiuse/wpad.h>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <vector>
#include "icon_jpg.h"
#include "terminus_ttf.h"
#include "game/scenegenerator.cpp"
#include "globals.h"
#include "math/camera.h"
#include "menu.h"
#include "options.h"
static inline void PopulateMenuWithStride(Menu& menu, u32 fontSize, math::Vector2u position, math::Vector2u stride,
std::vector<const char*> items)
{
math::Vector2u current = position;
for (const char* item : items) {
menu.addMenuItem({ { current.m_x, current.m_y }, item, fontSize, util::white, util::red });
current.m_x += stride.m_x;
current.m_y += stride.m_y;
}
}
enum class OptionMenuItems : u8 { ObjectCount = 0, WireframeObjectCount, SpawnMode, LightCount };
enum class MainMenuItems : u8 { Start, Options, Extra, Quit };
enum class ExtraMenuItems : u8 { ChangeLog, Controls, GX_S55_1, GX_S55_2 };
int main(int argc, char** argv)
{
srand(time(NULL));
GRRLIB_Init();
WPAD_Init();
WPAD_SetDataFormat(WPAD_CHAN_0, WPAD_FMT_BTNS);
gMainCamera = new Camera({ 0, 0, 0 }, { 0, 1, 0 }, { 0, 0, 0 });
gFont.init(terminus_ttf, terminus_ttf_size);
GRRLIB_texImg* icon = GRRLIB_LoadTextureJPG(icon_jpg);
float fadeTimer = 0;
Menu mainMenu;
PopulateMenuWithStride(mainMenu, 46, math::Vector2u(64, 80 + static_cast<u32>(icon->h * 0.5f)),
math::Vector2u(0, 48), { "Start", "Options", "Extras", "Exit" });
mainMenu.reset(0);
Menu extraMenu;
PopulateMenuWithStride(extraMenu, 56, math::Vector2u(64, 64), math::Vector2u(32, 64),
{ "What's new?", "Controls", "GX_S55_S1", "GX_S55_S2" });
extraMenu.reset(0);
Menu gameMenu;
PopulateMenuWithStride(gameMenu, 26, math::Vector2u(32, 32), math::Vector2u(0, 24),
{ "Randomise scene", "Randomise size", "Randomise colours", "Randomise lights" });
gameMenu.addMenuItem({ math::Vector2u(32, 128), "PRESS 1 TO HIDE", 26, util::yellow, util::yellow, false });
gameMenu.reset(0);
Menu optionsMenu;
PopulateMenuWithStride(optionsMenu, 46, math::Vector2u(64, 64), math::Vector2u(0, 48),
{ "REPLACE", "REPLACE", "REPLACE", "REPLACE" });
optionsMenu.reset(0);
/* Main menu flow acts as such:
* -> Image fades in
* -> Image fade stops, waits for a second or two
* -> Image fades out
*
* Logo shows
* Main menu renders & updates
* Program state = ProgramState::MainMenu
*/
GRRLIB_SetBackgroundColour(0x00, 0x00, 0x00, 0xFF);
while (!gExit) {
WPAD_ScanPads();
u32 btns_down = WPAD_ButtonsDown(WPAD_CHAN_0);
u32 btns_held = WPAD_ButtonsHeld(WPAD_CHAN_0);
GRRLIB_2dMode();
if (gOptions.m_state != ProgramState::MainGame && gOptions.m_state != ProgramState::GX_S55_S1
&& gOptions.m_state != ProgramState::GX_S55_S2) {
/* Calculate the positional offset and size for each image to allow
* seamless tiled background, using the scaling of the image as well
* as an extra pane that is offset by 1 to fill a gap also generated
* by this algorithm
*/
f32 scale = 0.25f;
u32 amtX = std::ceil(rmode->fbWidth / (icon->w * scale)) + 1;
u32 amtY = std::ceil(rmode->xfbHeight / (icon->h * scale)) + 1;
static f32 scrollTimer = 0;
for (u32 x = 0; x < amtX; x++) {
for (u32 y = 0; y < amtY; y++) {
/* stepX should evaluate to 160 */
f32 stepX = rmode->fbWidth / (amtX - static_cast<f32>(1));
/* ((0 * 160) + {scrolling_offset}) - 160 = -160.? (fills
* the gap left by moving tiles)
* ((1 * 160) + {scrolling_offset}) - 160 = 0.?
* ((2 * 160) + {scrolling_offset}) - 160 = 160.?
* etc.
*/
f32 xPos = ((x * stepX) + scrollTimer) - stepX;
while (xPos > rmode->fbWidth) {
xPos -= rmode->fbWidth + stepX;
}
f32 stepY = rmode->xfbHeight / (amtY - static_cast<f32>(1));
f32 yPos = ((y * stepY) + scrollTimer) - stepY;
while (yPos > rmode->xfbHeight) {
yPos -= rmode->xfbHeight + stepY;
}
GRRLIB_DrawImg(xPos, yPos, icon, 0, scale, scale, util::getColour(0x55, 0x55, 0x55, 0x64));
}
}
scrollTimer += 0.25f;
}
switch (gOptions.m_state) {
case ProgramState::FadeInText: {
u8 alpha = std::min(255.0f, fadeTimer);
GRRLIB_DrawImg((rmode->fbWidth / static_cast<float>(2)) - (icon->w / 2),
(rmode->xfbHeight / static_cast<float>(2)) - (icon->h / 2), icon, 0, 1, 1,
util::getColour(0xFF, 0xFF, 0xFF, alpha));
if (alpha == 255) {
static u32 logoTimer = 0;
if (logoTimer > 64) {
fadeTimer = 255;
gOptions.m_state = ProgramState::FadeOutText;
}
logoTimer += 1;
break;
}
fadeTimer += 2.5f;
break;
}
case ProgramState::FadeOutText: {
u8 alpha = std::max(0.0f, fadeTimer);
GRRLIB_DrawImg((rmode->fbWidth / static_cast<float>(2)) - (icon->w / 2),
(rmode->xfbHeight / static_cast<float>(2)) - (icon->h / 2), icon, 0, 1, 1,
util::getColour(0xFF, 0xFF, 0xFF, alpha));
if (alpha == 0) {
gOptions.m_state = ProgramState::MainMenu;
}
fadeTimer -= 2.5f;
break;
}
case ProgramState::MainMenu: {
constexpr f32 scale = 0.5f;
/* Place image in the middle of the screen */
const u32 xpos = (rmode->fbWidth / static_cast<float>(2)) - ((icon->w * scale) / 2);
GRRLIB_DrawImg(xpos, 64, icon, 0, scale, scale, util::white);
for (MenuItem& item : mainMenu.getItems()) {
item.m_position.m_x = xpos;
item.render(gFont);
}
if (btns_down & WPAD_BUTTON_UP) {
mainMenu.moveSelected(MenuDirection::Up);
} else if (btns_down & WPAD_BUTTON_DOWN) {
mainMenu.moveSelected(MenuDirection::Down);
}
if (btns_down & WPAD_BUTTON_A) {
const MenuItem& selected = mainMenu.getSelected();
switch ((MainMenuItems)selected.m_index) {
case MainMenuItems::Start:
gOptions.m_state = ProgramState::MainGame;
gSceneGenerator.setup();
break;
case MainMenuItems::Options:
gOptions.m_state = ProgramState::Options;
break;
case MainMenuItems::Extra:
gOptions.m_state = ProgramState::Extras;
break;
case MainMenuItems::Quit:
gExit = true;
break;
default:
break;
}
}
break;
}
case ProgramState::Options: {
for (MenuItem& item : optionsMenu.getItems()) {
char text[0x20];
memset(text, '\0', 0x20);
switch ((OptionMenuItems)item.m_index) {
case OptionMenuItems::ObjectCount:
sprintf(text, "Object count: [%d / %d]", gOptions.m_sceneObjCount.m_x,
gOptions.m_sceneObjCount.m_y);
break;
case OptionMenuItems::WireframeObjectCount:
sprintf(text, "WF obj count: [%d / %d]", gOptions.m_wfObjCount.m_x, gOptions.m_wfObjCount.m_y);
break;
case OptionMenuItems::LightCount:
sprintf(text, "Light count: [%d / %d]", gOptions.m_lightCount.m_x, gOptions.m_lightCount.m_y);
break;
case OptionMenuItems::SpawnMode: {
char type[0x10];
switch (gOptions.m_spawnMode) {
case ObjectSpawnMode::All:
sprintf(type, "All");
break;
case ObjectSpawnMode::Cube:
sprintf(type, "Cube");
break;
case ObjectSpawnMode::Torus:
sprintf(type, "Torus");
break;
case ObjectSpawnMode::Sphere:
sprintf(type, "Sphere");
break;
}
sprintf(text, "Spawn type: [%s]", type);
break;
}
default:
break;
}
item.m_text = text;
item.render(gFont);
}
if (btns_down & WPAD_BUTTON_UP) {
optionsMenu.moveSelected(MenuDirection::Up);
} else if (btns_down & WPAD_BUTTON_DOWN) {
optionsMenu.moveSelected(MenuDirection::Down);
}
if (btns_down & WPAD_BUTTON_B) {
gOptions.m_state = ProgramState::MainMenu;
}
if (btns_down & WPAD_BUTTON_RIGHT) {
const MenuItem& item = optionsMenu.getSelected();
switch (item.m_index) {
case OptionMenuItems::ObjectCount:
gOptions.toggleOptionObjectCount(true);
break;
case OptionMenuItems::WireframeObjectCount:
gOptions.toggleOptionWfObjCount(true);
break;
case OptionMenuItems::SpawnMode:
gOptions.toggleOptionSpawnMode(true);
break;
case OptionMenuItems::LightCount:
gOptions.toggleOptionLightCount(true);
break;
default:
break;
}
} else if (btns_down & WPAD_BUTTON_LEFT) {
const MenuItem& item = optionsMenu.getSelected();
switch ((OptionMenuItems)item.m_index) {
case OptionMenuItems::ObjectCount:
gOptions.toggleOptionObjectCount(false);
break;
case OptionMenuItems::WireframeObjectCount:
gOptions.toggleOptionWfObjCount(false);
break;
case OptionMenuItems::SpawnMode:
gOptions.toggleOptionSpawnMode(false);
break;
case OptionMenuItems::LightCount:
gOptions.toggleOptionLightCount(false);
break;
default:
break;
}
}
break;
}
case ProgramState::Extras: {
for (MenuItem& item : extraMenu.getItems()) {
item.render(gFont);
}
if (btns_down & WPAD_BUTTON_UP) {
extraMenu.moveSelected(MenuDirection::Up);
} else if (btns_down & WPAD_BUTTON_DOWN) {
extraMenu.moveSelected(MenuDirection::Down);
}
if (btns_down & WPAD_BUTTON_A) {
MenuItem& selected = extraMenu.getSelected();
switch ((ExtraMenuItems)selected.m_index) {
case ExtraMenuItems::ChangeLog:
gOptions.m_state = ProgramState::ChangeLog;
break;
case ExtraMenuItems::Controls:
gOptions.m_state = ProgramState::Controls;
break;
case ExtraMenuItems::GX_S55_1:
gOptions.m_state = ProgramState::GX_S55_S1;
break;
case ExtraMenuItems::GX_S55_2:
gOptions.m_state = ProgramState::GX_S55_S2;
break;
default:
break;
}
}
if (btns_down & WPAD_BUTTON_B) {
gOptions.m_state = ProgramState::MainMenu;
}
break;
}
case ProgramState::Controls: {
if (btns_down & WPAD_BUTTON_B) {
gOptions.m_state = ProgramState::Extras;
}
gFont.printf(64, 64, "Game Controls", 46, util::white);
gFont.printf(64, 96 + 28 * 1, "1) 1 - hide UI", 26, util::white);
gFont.printf(64, 96 + 28 * 2, " (after hiding UI)", 26, util::white);
gFont.printf(64, 96 + 28 * 3, "2) 2 - regenerate scene", 26, util::white);
gFont.printf(64, 96 + 28 * 4, "3) A - stop Camera rotation", 26, util::white);
gFont.printf(64, 244, "Menu-specific Controls", 46, util::white);
gFont.printf(64, (244 + 32) + 28 * 1, "1) DPAD Up / Down - change selection", 26, util::white);
gFont.printf(64, (244 + 32) + 28 * 2, "2) DPAD Right / Left - modify selection", 26, util::white);
gFont.printf(64, (244 + 32) + 28 * 3, "3) A - select", 26, util::white);
gFont.printf(64, (244 + 32) + 28 * 4, "4) B - back", 26, util::white);
break;
}
case ProgramState::ChangeLog: {
if (btns_down & WPAD_BUTTON_B) {
gOptions.m_state = ProgramState::Extras;
}
gFont.printf(64, 64, "What's new?", 56,
util::getColour(abs(sin(gTimer / 10)) * 255, abs(cos(gTimer / 10)) * 255, 0));
gFont.printf(64, 96 + 28 * 1, "Version 1.1", 36, util::white);
gFont.printf(64, 96 + 32 * 2, "- Added extras, changelog and controls", 26, util::white);
gFont.printf(64, 96 + 32 * 3, " screen", 26, util::white);
gFont.printf(64, 96 + 32 * 4, "- Added a pause button in the main scene", 26, util::white);
gFont.printf(64, 96 + 32 * 5, "- Added scenes from an old project (GX_S55)", 26, util::white);
gFont.printf(64, 96 + 32 * 6, "- Internal code clean-up", 26, util::white);
break;
}
case ProgramState::GX_S55_S1: {
if (btns_down & WPAD_BUTTON_B) {
gOptions.m_state = ProgramState::Extras;
}
static f32 gxTimer = 0;
const f32 xyBase = (sin(gxTimer / 17.5f) * 20);
gMainCamera->position() = { xyBase - 20, xyBase - 10, static_cast<f32>((cos(gxTimer / 17.5) * 20) - 20) };
gMainCamera->lookAt() = { 0, 0, 0 };
gMainCamera->applyCamera();
GRRLIB_SetLightAmbient(util::black);
GRRLIB_SetLightDiff(0, gMainCamera->position(), 5, 2, util::getColour(0xFF, 0xAA, 0x00));
for (u32 lanes = 0; lanes < 10; lanes++) {
for (u32 i = 0; i < 15; i++) {
GRRLIB_ObjectViewInv(lanes * 1.5f, 0, i * 2 / lanes, 0, 0, gxTimer * (3 + 1.15f * i), 1, 1, 1);
GRRLIB_DrawCube(1, true, 0xFFFFFFFF);
}
}
gxTimer += 0.05f;
break;
}
case ProgramState::GX_S55_S2: {
if (btns_down & WPAD_BUTTON_B) {
gOptions.m_state = ProgramState::Extras;
}
static f32 cameraRotation = 0;
static f32 cameraYOffset = 7.5f;
constexpr f32 offset = 20.0f;
constexpr f32 cameraOffset = 25.0f;
if (btns_held & WPAD_BUTTON_LEFT) {
cameraRotation -= 0.025f;
} else if (btns_held & WPAD_BUTTON_RIGHT) {
cameraRotation += 0.025f;
}
if (btns_held & WPAD_BUTTON_UP) {
cameraYOffset = std::min(cameraYOffset + 0.1f, 42.5f);
} else if (btns_held & WPAD_BUTTON_DOWN) {
cameraYOffset = std::max(cameraYOffset - 0.1f, 2.5f);
}
gMainCamera->lookAt() = { offset, 0, offset };
gMainCamera->position() = { static_cast<f32>(offset + sin(cameraRotation) * cameraOffset), cameraYOffset,
static_cast<f32>(offset + cos(cameraRotation) * cameraOffset) };
gMainCamera->applyCamera();
GRRLIB_SetLightAmbient(0x000000FF);
guVector lightPos
= { static_cast<f32>(abs(sin(gTimer / 4) * cameraOffset)), static_cast<f32>(8 + abs(cos(gTimer))),
static_cast<f32>(abs(cos(gTimer / 4) * cameraOffset)) };
GRRLIB_ObjectViewInv(lightPos.x, lightPos.y - 2, lightPos.z, 0, 0, 0, 1, 1, 1);
GRRLIB_DrawSphere(1, 10, 10, true, util::white);
GRRLIB_SetLightDiff(0, lightPos, 10, 10, 0x623499FF);
static float timer = 0;
const f32 stride = 2;
for (u32 i = 0; i < 20; i++) {
for (u32 j = 0; j < 20; j++) {
guVector pos = { i * stride, 0, j * stride };
if (i == 10 && j == 10) {
GRRLIB_ObjectViewInv(pos.x, 3, pos.z, 0, 0, 0, 1, 1, 1);
GRRLIB_DrawCube(1, true, util::red);
}
pos.y += sin((gTimer * j) / 10) / 5;
pos.y += cos((gTimer * i) / 10) / 10;
GRRLIB_ObjectViewInv(pos.x, pos.y, pos.z, 0, 0, 0, 1, 1, 1);
GRRLIB_DrawCylinder(
1, 1.5f, 10, i % static_cast<u32>(timer) == 0 || j % static_cast<u32>(timer) == 0, util::white);
}
}
timer += 0.05f;
if (timer > 19.5f) {
timer = 0.5f;
}
break;
}
case ProgramState::MainGame: {
static f32 camRotTimer = 0;
static guVector camPos;
if (!(!gOptions.m_showUI && btns_held & WPAD_BUTTON_A)) {
camPos.x = sin(camRotTimer * 0.05f) * 20;
camPos.z = cos(camRotTimer * 0.05f) * 20;
camPos.y = 10 + sin(camRotTimer * 0.01f) * 5;
camRotTimer += 0.05f;
}
gMainCamera->position() = camPos;
gMainCamera->lookAt() = { 0, 0, 0 };
gMainCamera->applyCamera();
gSceneGenerator.render();
GRRLIB_2dMode();
if (gOptions.m_showUI) {
GRRLIB_Rectangle(32, 36, 226, 120, util::getColour(0x44, 0x44, 0x44), true);
for (MenuItem& item : gameMenu.getItems()) {
item.render(gFont);
}
if (btns_down & WPAD_BUTTON_UP) {
gameMenu.moveSelected(MenuDirection::Up);
} else if (btns_down & WPAD_BUTTON_DOWN) {
gameMenu.moveSelected(MenuDirection::Down);
}
if (btns_down & WPAD_BUTTON_A) {
const MenuItem& item = gameMenu.getSelected();
switch (item.m_index) {
case 0:
gSceneGenerator.setup();
break;
case 1:
for (auto& obj : gSceneGenerator.m_objects) {
obj.rngScaling();
}
for (auto& obj : gSceneGenerator.m_wfObjects) {
obj.rngScaling();
}
break;
case 2:
for (auto& obj : gSceneGenerator.m_objects) {
obj.rngColour();
}
for (auto& obj : gSceneGenerator.m_wfObjects) {
obj.rngColour();
}
break;
case 3:
gSceneGenerator.randomiseLights();
break;
default:
break;
}
}
} else if (btns_down & WPAD_BUTTON_2) {
gSceneGenerator.setup();
}
if (btns_down & WPAD_BUTTON_1) {
gOptions.m_showUI = !gOptions.m_showUI;
}
if (btns_down & WPAD_BUTTON_B) {
gOptions.m_state = ProgramState::MainMenu;
mainMenu.reset(0);
}
break;
}
}
GRRLIB_Render();
gTimer += 0.05f;
}
delete gMainCamera;
GRRLIB_FreeTexture(icon);
GRRLIB_Exit();
exit(0);
}
| 39.040741
| 120
| 0.482592
|
io55
|
0bcc54ac82e17955fc42528cc2f78e58a1799faf
| 350
|
hpp
|
C++
|
kernel/lib/bitmap.hpp
|
ethan4984/rock
|
751b9af1009b622bedf384c1f80970b333c436c3
|
[
"BSD-2-Clause"
] | 207
|
2020-05-27T21:57:28.000Z
|
2022-02-26T15:17:27.000Z
|
kernel/lib/bitmap.hpp
|
ethan4984/crepOS
|
751b9af1009b622bedf384c1f80970b333c436c3
|
[
"BSD-2-Clause"
] | 3
|
2020-07-26T18:14:05.000Z
|
2020-12-09T05:32:07.000Z
|
kernel/lib/bitmap.hpp
|
ethan4984/rock
|
751b9af1009b622bedf384c1f80970b333c436c3
|
[
"BSD-2-Clause"
] | 17
|
2020-07-05T19:08:48.000Z
|
2021-10-13T12:30:13.000Z
|
#ifndef BITMAP_HPP_
#define BITMAP_HPP_
#include <cstddef>
#include <cstdint>
#include <types.hpp>
namespace lib {
class bitmap {
public:
bitmap(size_t inital_size, bool can_grow = false);
bitmap() = default;
ssize_t alloc();
void free(size_t index);
private:
uint8_t *bm;
size_t bm_size;
bool can_grow;
};
}
#endif
| 13.461538
| 54
| 0.674286
|
ethan4984
|
0bd802c971a528be05a7c16576008aa2e15705f0
| 194
|
cc
|
C++
|
source/agent/addons/audioRanker/addon.cc
|
andreasunterhuber/owt-server
|
128b83714361c0b543ec44fc841c9094f4267633
|
[
"Apache-2.0"
] | 890
|
2019-03-08T08:04:10.000Z
|
2022-03-30T03:07:44.000Z
|
source/agent/addons/audioRanker/addon.cc
|
vgemv/owt-server
|
fa6070af33feeeb79a962de08307ac5092991cbf
|
[
"Apache-2.0"
] | 583
|
2019-03-11T10:27:42.000Z
|
2022-03-29T01:41:28.000Z
|
source/agent/addons/audioRanker/addon.cc
|
vgemv/owt-server
|
fa6070af33feeeb79a962de08307ac5092991cbf
|
[
"Apache-2.0"
] | 385
|
2019-03-08T07:50:13.000Z
|
2022-03-29T06:36:28.000Z
|
// Copyright (C) <2019> Intel Corporation
//
// SPDX-License-Identifier: Apache-2.0
#include "AudioRankerWrapper.h"
#include <nan.h>
using namespace v8;
NODE_MODULE(addon, AudioRanker::Init)
| 17.636364
| 41
| 0.737113
|
andreasunterhuber
|
0be023d8a91bfd830b80ba1c0fccebe175f68e89
| 6,642
|
cpp
|
C++
|
Engine/source/gfx/gl/ggl/mac/aglBind.cpp
|
camporter/Torque3D
|
938e28b6f36883cb420da4b04253b1394467a1f4
|
[
"Unlicense"
] | 13
|
2015-04-13T21:46:01.000Z
|
2017-11-20T22:12:04.000Z
|
Engine/source/gfx/gl/ggl/mac/aglBind.cpp
|
camporter/Torque3D
|
938e28b6f36883cb420da4b04253b1394467a1f4
|
[
"Unlicense"
] | 1
|
2015-11-16T23:57:12.000Z
|
2015-12-01T03:24:08.000Z
|
Engine/source/gfx/gl/ggl/mac/aglBind.cpp
|
camporter/Torque3D
|
938e28b6f36883cb420da4b04253b1394467a1f4
|
[
"Unlicense"
] | 10
|
2015-01-05T15:58:31.000Z
|
2021-11-20T14:05:46.000Z
|
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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 <err.h>
#include "agl.h"
#include "platform/platform.h"
//-----------------------------------------------------------------------------
// Instantiation of function pointers.
#define GL_GROUP_BEGIN(name)
#define GL_FUNCTION(name, type, args) type (XGL_DLL *name) args;
#define GL_GROUP_END()
#include "../generated/glcfn.h"
#undef GL_GROUP_BEGIN
#undef GL_FUNCTION
#undef GL_GROUP_END
#define EXECUTE_ONLY_ONCE() \
static bool _doneOnce = false; \
if(_doneOnce) return; \
_doneOnce = true;
namespace GL
{
//-----------------------------------------------------------------------------
// The OpenGL Bundle is shared by all the devices.
static CFBundleRef _openglFrameworkRef;
// Unlike WGL, AGL does not require a set of function pointers per
// context pixel format. All functions in the DLL are bound in a single
// table and shared by all contexts.
static AGLExtensionPtrs _LibraryFunctions;
static AGLExtensionFlags _ExtensionFlags;
bool hasExtension(const char *name,const char* extensions);
bool hasVersion(const char *name,const char* prefix,int major,int minor);
//-----------------------------------------------------------------------------
void* MacGetProcAddress(CFBundleRef bundle,char* name)
{
CFStringRef cfName = CFStringCreateWithCString(kCFAllocatorDefault, name, CFStringGetSystemEncoding());
void* ret = CFBundleGetFunctionPointerForName(bundle, cfName);
CFRelease(cfName);
return ret;
}
//-----------------------------------------------------------------------------
bool bindFunction(CFBundleRef bundle,void *&fnAddress, const char *name)
{
CFStringRef cfName = CFStringCreateWithCString(0,name,CFStringGetSystemEncoding());
fnAddress = CFBundleGetFunctionPointerForName(bundle, cfName);
CFRelease(cfName);
return fnAddress != 0;
}
//-----------------------------------------------------------------------------
bool gglBindCoreFunctions(CFBundleRef bundle,AGLExtensionPtrs* glp)
{
bool bound = true;
// Bind static functions which are quarenteed to be part of the
// OpenGL library. In this case, OpenGL 1.0 and GLX 1.0 functions
#define GL_GROUP_BEGIN(name)
#define GL_GROUP_END()
#define GL_FUNCTION(fn_name, fn_return, fn_args) \
bound &= bindFunction(bundle,*(void**)&fn_name, #fn_name);
#include "../generated/glcfn.h"
#undef GL_FUNCTION
#undef GL_GROUP_BEGIN
#undef GL_GROUP_END
// Try and bind all known extension functions. We'll check later to
// see which ones are actually valid for a context.
#define GL_GROUP_BEGIN(name)
#define GL_FUNCTION(fn_name, fn_return, fn_args) \
bindFunction(bundle,*(void**)&glp->_##fn_name, #fn_name);
#define GL_GROUP_END()
#include "../generated/glefn.h"
#undef GL_FUNCTION
#undef GL_GROUP_BEGIN
#undef GL_GROUP_END
return bound;
}
//-----------------------------------------------------------------------------
bool gglBindExtensions(GLExtensionFlags* gl)
{
dMemset(gl,0,sizeof(GLExtensionFlags));
// Get GL version and extensions
const char* glExtensions = (const char*)glGetString(GL_EXTENSIONS);
const char* glVersion = (const char*) glGetString(GL_VERSION);
if (!glExtensions || !glVersion)
return false;
// Parse the GL version string "major.minor"
const char *itr = glVersion;
int glMajor = atoi(itr);
while (isdigit(*itr))
*itr++;
int glMinor = atoi(++itr);
// Check which extensions are available on the active context.
// GL and GLX versions ubove 1.0 are also tested here.
#define GL_GROUP_BEGIN(name) \
gl->has_##name = hasVersion(#name,"GL_VERSION",glMajor,glMinor) || \
hasExtension(#name,glExtensions);
#define GL_FUNCTION(fn_name, fn_return, fn_args)
#define GL_GROUP_END()
#include "../generated/glefn.h"
#undef GL_FUNCTION
#undef GL_GROUP_BEGIN
#undef GL_GROUP_END
gl->bound = true;
return true;
}
#define _hasGLXExtension(display,name) (display->glx.has_##name)
//-----------------------------------------------------------------------------
void gglPerformBinds()
{
// Some of the following code is copied from the Apple Opengl Documentation.
// Load and bind OpenGL bundle functions
if (!_openglFrameworkRef) {
// Load OpenGL.framework
_openglFrameworkRef = CFBundleGetBundleWithIdentifier(CFSTR("com.apple.opengl"));
if (!_openglFrameworkRef) {
warn("Could not create OpenGL Framework bundle");
return;
}
if (!CFBundleLoadExecutable(_openglFrameworkRef)) {
warn("Could not load MachO executable");
return;
}
// Bind our functions.
if (!gglBindCoreFunctions(_openglFrameworkRef, &_LibraryFunctions)) {
warn("GLDevice: Failed to bind all core functions");
return;
}
// Save the pointer to the set of opengl functions
_GGLptr = &_LibraryFunctions;
}
}
//-----------------------------------------------------------------------------
void gglPerformExtensionBinds(void *context)
{
// we don't care about the passed context when binding the opengl functions,
// we only care about the current opengl context.
if( !_openglFrameworkRef || !_GGLptr )
{
gglPerformBinds();
}
gglBindExtensions( &_ExtensionFlags );
_GGLflag = &_ExtensionFlags;
}
} // Namespace
| 33.887755
| 106
| 0.631286
|
camporter
|
0be32f6e8335377b2d68fade9fd7747cca977aa9
| 3,832
|
hpp
|
C++
|
Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Middlewares/ST/TouchGFX/touchgfx/framework/include/touchgfx/widgets/ToggleButton.hpp
|
ramkumarkoppu/NUCLEO-F767ZI-ESW
|
85e129d71ee8eccbd0b94b5e07e75b6b91679ee8
|
[
"MIT"
] | 3
|
2020-11-07T07:01:59.000Z
|
2022-03-06T10:54:52.000Z
|
Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Middlewares/ST/TouchGFX/touchgfx/framework/include/touchgfx/widgets/ToggleButton.hpp
|
ramkumarkoppu/NUCLEO-F767ZI-ESW
|
85e129d71ee8eccbd0b94b5e07e75b6b91679ee8
|
[
"MIT"
] | 1
|
2020-11-14T16:53:09.000Z
|
2020-11-14T16:53:09.000Z
|
Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Middlewares/ST/TouchGFX/touchgfx/framework/include/touchgfx/widgets/ToggleButton.hpp
|
ramkumarkoppu/NUCLEO-F767ZI-ESW
|
85e129d71ee8eccbd0b94b5e07e75b6b91679ee8
|
[
"MIT"
] | 3
|
2020-03-15T14:35:38.000Z
|
2021-04-07T14:55:42.000Z
|
/**
******************************************************************************
* This file is part of the TouchGFX 4.10.0 distribution.
*
* <h2><center>© Copyright (c) 2018 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
*/
#ifndef TOGGLEBUTTON_HPP
#define TOGGLEBUTTON_HPP
#include <touchgfx/widgets/Button.hpp>
namespace touchgfx
{
/**
* @class ToggleButton ToggleButton.hpp touchgfx/widgets/ToggleButton.hpp
*
* @brief A ToggleButton is a Button specialization that swaps the two bitmaps when clicked.
*
* A ToggleButton is a Button specialization that swaps the two bitmaps when clicked,
* such that the previous "pressed" bitmap, now becomes the one displayed when button is
* not pressed.
*
* @see Button
*/
class ToggleButton : public Button
{
public:
/**
* @fn ToggleButton::ToggleButton();
*
* @brief Default constructor.
*
* Default constructor.
*/
ToggleButton();
/**
* @fn virtual void ToggleButton::setBitmaps(const Bitmap& bmpReleased, const Bitmap& bmpPressed)
*
* @brief Sets the bitmaps.
*
* Sets the bitmaps.
*
* @note This specific implementation remembers what bitmap was used as pressed, in order to
* support the ability to force the state.
*
* @param bmpReleased The bitmap to show in the "normal" state, ie when button is not pressed.
* @param bmpPressed The bitmap to show when the button is pressed.
*
* @see Button::setBitmaps
*/
virtual void setBitmaps(const Bitmap& bmpReleased, const Bitmap& bmpPressed)
{
originalPressed = bmpPressed;
Button::setBitmaps(bmpReleased, bmpPressed);
}
/**
* @fn void ToggleButton::forceState(bool activeState);
*
* @brief Force the button into a specific state.
*
* Use this function to force the button in one of the two possible states. If
* button is forced to the active state, then the pressed bitmap from the last call
* to setBitmaps becomes the one displayed when button is not pressed.
*
* @param activeState If true, display the bmpPressed bitmap when not pressed. If false display
* the bmpReleased bitmap.
*/
void forceState(bool activeState);
/**
* @fn bool ToggleButton::getState() const
*
* @brief Gets the state.
*
* Gets the state.
*
* @return true if state is currently active.
*/
bool getState() const
{
return up == originalPressed;
}
/**
* @fn virtual void ToggleButton::handleClickEvent(const ClickEvent& event);
*
* @brief Overrides handleClickEvent.
*
* Overrides handleClickEvent in order to swap the bitmaps after being clicked.
*
* @param event The event to handle.
*/
virtual void handleClickEvent(const ClickEvent& event);
/**
* @fn virtual uint16_t ToggleButton::getType() const
*
* @brief For GUI testing only.
*
* For GUI testing only. Returns type of this drawable.
*
* @return TYPE_TOGGLEBUTTON.
*/
virtual uint16_t getType() const
{
return (uint16_t)TYPE_TOGGLEBUTTON;
}
protected:
Bitmap originalPressed; ///< Contains the bitmap that was originally being displayed when button is pressed.
};
} // namespace touchgfx
#endif // TOGGLEBUTTON_HPP
| 30.412698
| 112
| 0.61143
|
ramkumarkoppu
|
0be9e2f4b4680081b0905ea468680ce0b89a4f02
| 12,781
|
hh
|
C++
|
maps/mi.hh
|
krishna-beemanapalli/PlotSim
|
5c90671798db323a6109e1cdfa6fbbf8b96fb713
|
[
"MIT"
] | 6
|
2020-03-30T15:18:23.000Z
|
2020-05-09T01:24:22.000Z
|
maps/mi.hh
|
krishna-beemanapalli/PlotSim
|
5c90671798db323a6109e1cdfa6fbbf8b96fb713
|
[
"MIT"
] | 1
|
2020-05-06T20:41:07.000Z
|
2020-05-06T20:41:07.000Z
|
maps/mi.hh
|
krishna-beemanapalli/PlotSim
|
5c90671798db323a6109e1cdfa6fbbf8b96fb713
|
[
"MIT"
] | 4
|
2020-04-22T06:48:32.000Z
|
2020-10-21T01:03:08.000Z
|
static short state[][3] =
{
0, -210, -403, 1, -211, -433, 1, -240, -432, 1, -239, -417, 1, -210, -403, 0, -157, -449, 1, -157, -469, 1, -191, -496,
1, -197, -468, 1, -187, -454, 1, -157, -449, 0, 108, -41, 1, 125, -45, 1, 136, -64, 1, 115, -66, 1, 105, -69,
1, 87, -51, 1, 108, -41, 0, 177, -120, 1, 178, -87, 1, 210, -84, 1, 211, -103, 1, 211, -123, 1, 208, -135,
1, 182, -145, 1, 170, -147, 1, 170, -141, 1, 177, -120, 0, 290, -357, 1, 263, -353, 1, 269, -328, 1, 274, -310,
1, 277, -306, 1, 284, -318, 1, 288, -341, 1, 290, -357, 0, 393, -462, 1, 413, -460, 1, 437, -460, 1, 440, -483,
1, 452, -487, 1, 464, -519, 1, 448, -562, 1, 461, -583, 1, 441, -617, 1, 422, -621, 1, 412, -617, 1, 412, -590,
1, 403, -567, 1, 387, -528, 1, 387, -499, 1, 393, -462, 0, 340, -583, 1, 347, -574, 1, 371, -581, 1, 374, -607,
1, 362, -612, 1, 348, -606, 1, 340, -583, 0, 447, -656, 1, 463, -654, 1, 466, -625, 1, 482, -630, 1, 492, -655,
1, 478, -668, 1, 461, -670, 1, 447, -656, 0, 532, -631, 1, 548, -640, 1, 551, -659, 1, 539, -660, 1, 532, -652,
1, 521, -635, 1, 532, -631, 0, 922, -743, 1, 927, -748, 1, 922, -761, 1, 911, -755, 1, 911, -749, 1, 922, -743,
0, 926, -669, 1, 931, -669, 1, 933, -675, 1, 924, -682, 1, 917, -694, 1, 904, -694, 1, 904, -684, 1, 926, -669,
0, 1009, -590, 1, 1039, -589, 1, 1052, -598, 1, 1070, -611, 1, 1050, -624, 1, 1041, -641, 1, 1027, -642, 1, 1007, -633,
1, 1000, -635, 1, 966, -650, 1, 952, -651, 1, 949, -651, 1, 967, -633, 1, 980, -605, 1, 993, -600, 1, 1009, -590,
0, 1052, -719, 1, 1069, -719, 1, 1084, -729, 1, 1085, -737, 1, 1081, -738, 1, 1057, -753, 1, 1041, -752, 1, 1029, -750,
1, 1036, -743, 1, 1052, -719, 0, 1445, -740, 1, 1467, -740, 1, 1482, -737, 1, 1514, -734, 1, 1534, -765, 1, 1535, -781,
1, 1515, -788, 1, 1502, -808, 1, 1494, -866, 1, 1468, -863, 1, 1441, -863, 1, 1437, -831, 1, 1419, -815, 1, 1397, -798,
1, 1371, -797, 1, 1358, -781, 1, 1375, -772, 1, 1385, -749, 1, 1416, -744, 1, 1445, -740, 0, 1660, -169, 1, 1653, -177,
1, 1652, -169, 1, 1667, -149, 1, 1668, -153, 1, 1660, -169, 0,-1543,-2189, 1,-1519,-2191, 1,-1485,-2206, 1,-1450,-2221,
1,-1403,-2225, 1,-1393,-2249, 1,-1394,-2261, 1,-1417,-2259, 1,-1441,-2257, 1,-1443,-2281, 1,-1408,-2296, 1,-1364,-2335,
1,-1366,-2359, 1,-1355,-2372, 1,-1331,-2373, 1,-1317,-2351, 1,-1295,-2364, 1,-1273,-2390, 1,-1215,-2418, 1,-1217,-2442,
1,-1230,-2453, 1,-1232,-2477, 1,-1196,-2480, 1,-1139,-2508, 1,-1117,-2534, 1,-1118,-2546, 1,-1166,-2542, 1,-1199,-2515,
1,-1211,-2514, 1,-1235,-2512, 1,-1279,-2473, 1,-1312,-2435, 1,-1348,-2432, 1,-1392,-2392, 1,-1451,-2376, 1,-1495,-2336,
1,-1542,-2321, 1,-1563,-2295, 1,-1608,-2256, 1,-1617,-2219, 1,-1616,-2208, 1,-1568,-2199, 1,-1543,-2189, 0,-1369, -890,
1,-1472, -974, 1,-2020,-1231, 0, -670, -116, 1, -707, -130, 1, -724, -163, 1, -748, -187, 1, -748, -210, 1, -735, -257,
1, -721, -285, 1, -721, -323, 1, -742, -337, 1, -769, -318, 1, -790, -304, 1, -810, -313, 1, -824, -309, 1, -838, -318,
1, -831, -341, 1, -810, -365, 1, -786, -374, 1, -786, -412, 1, -800, -449, 1, -779, -468, 1, -779, -496, 1, -793, -529,
1, -790, -543, 1, -772, -552, 1, -779, -585, 1, -814, -604, 1, -827, -651, 1, -848, -665, 1, -882, -655, 1, -899, -660,
1, -899, -683, 1, -910, -688, 1, -940, -674, 1, -954, -693, 1, -971, -702, 1, -971, -721, 1, -944, -730, 1, -944, -758,
1, -958, -754, 1, -968, -772, 1,-1030, -787, 1,-1064, -824, 1,-1108, -819, 1,-1153, -843, 1,-1204, -838, 1,-1228, -810,
1,-1252, -815, 1,-1283, -861, 1,-1321, -871, 1,-1369, -890, 0, 314, -375, 1, 304, -385, 1, 314, -395, 1, 334, -385,
1, 324, -375, 1, 314, -375, 0, -236, -505, 1, -256, -505, 1, -266, -525, 1, -236, -535, 1, -236, -505, 0, 1233, -965,
1, 1223,-1025, 1, 1233,-1085, 1, 1273,-1075, 1, 1293,-1035, 1, 1293,-1005, 1, 1273, -985, 1, 1233, -965, 0, 1207,-1225,
1, 1207,-1195, 1, 1217,-1165, 1, 1227,-1115, 1, 1247,-1105, 1, 1247,-1205, 1, 1287,-1225, 1, 1297,-1265, 1, 1257,-1285,
1, 1197,-1285, 1, 1187,-1265, 1, 1187,-1245, 1, 1207,-1225, 0,-2020,-1231, 1,-2047,-1268, 1,-2054,-1315, 1,-2082,-1352,
1,-2123,-1362, 1,-2136,-1390, 1,-2184,-1399, 1,-2191,-1418, 1,-2129,-1455, 1,-2116,-1436, 1,-2054,-1446, 1,-2034,-1483,
1,-1986,-1492, 1,-1897,-1539, 1,-1856,-1576, 1,-1788,-1595, 1,-1713,-1567, 1,-1686,-1567, 1,-1638,-1586, 1,-1590,-1576,
1,-1529,-1623, 1,-1481,-1623, 1,-1460,-1660, 1,-1433,-1651, 1,-1399,-1642, 1,-1372,-1679, 1,-1358,-1716, 1,-1303,-1744,
1,-1276,-1782, 1,-1235,-1810, 1,-1213,-1811, 0, 1028,-1216, 1, 1069,-1239, 1, 1093,-1239, 1, 1121,-1222, 1, 1141,-1222,
1, 1173,-1227, 1, 1180,-1216, 1, 1180,-1192, 1, 1199,-1136, 1, 1204,-1076, 1, 1195,-1047, 1, 1199,-1020, 1, 1193,-1011,
1, 1169,-1026, 1, 1156,-1008, 1, 1167, -984, 1, 1149, -970, 1, 1123, -961, 1, 1095, -961, 1, 1084, -949, 1, 1089, -931,
1, 1108, -922, 1, 1132, -937, 1, 1149, -937, 1, 1165, -925, 1, 1193, -937, 1, 1208, -925, 1, 1212, -896, 1, 1214, -872,
1, 1195, -851, 1, 1197, -827, 1, 1227, -804, 1, 1264, -798, 1, 1282, -810, 1, 1293, -801, 1, 1299, -786, 1, 1288, -756,
1, 1254, -738, 1, 1219, -741, 1, 1178, -762, 1, 1115, -750, 1, 1087, -756, 1, 1050, -780, 1, 1022, -777, 1, 1013, -765,
1, 993, -777, 1, 982, -762, 1, 978, -741, 1, 967, -759, 1, 959, -744, 1, 952, -747, 1, 948, -780, 1, 928, -798,
1, 909, -798, 1, 887, -815, 1, 870, -813, 1, 868, -795, 1, 881, -756, 1, 872, -741, 1, 872, -709, 1, 883, -682,
1, 872, -670, 1, 833, -682, 1, 809, -738, 1, 748, -818, 1, 696, -830, 1, 636, -833, 1, 610, -857, 1, 579, -872,
1, 540, -872, 1, 512, -890, 1, 482, -890, 1, 460, -872, 1, 430, -866, 1, 414, -842, 1, 414, -815, 1, 391, -786,
1, 360, -769, 1, 330, -769, 1, 309, -786, 1, 282, -790, 1, 264, -769, 1, 210, -782, 1, 154, -786, 1, 121, -774,
1, 106, -778, 1, 67, -778, 1, 64, -769, 1, 55, -749, 1, 40, -749, 1, 37, -737, 1, 37, -712, 1, 28, -688,
1, 20, -680, 1, 17, -659, 1, -10, -659, 1, -22, -651, 1, -34, -635, 1, -55, -635, 1, -73, -619, 1, -79, -586,
1, -88, -570, 1, -100, -578, 1, -106, -570, 1, -112, -545, 1, -103, -517, 1, -106, -509, 1, -130, -517, 1, -156, -557,
1, -156, -594, 1, -139, -602, 1, -127, -643, 1, -106, -659, 1, -97, -647, 1, -79, -659, 1, -88, -676, 1, -67, -708,
1, -73, -729, 1, -85, -741, 1, -106, -733, 1, -124, -708, 1, -142, -684, 1, -165, -692, 1, -186, -692, 1, -198, -716,
1, -213, -716, 1, -228, -688, 1, -225, -668, 1, -240, -651, 1, -240, -627, 1, -270, -602, 1, -288, -598, 1, -297, -574,
1, -309, -578, 1, -306, -627, 1, -320, -668, 1, -323, -684, 1, -312, -704, 1, -291, -725, 1, -300, -753, 1, -312, -753,
1, -326, -721, 1, -359, -704, 1, -368, -676, 1, -353, -631, 1, -356, -610, 1, -374, -598, 1, -413, -590, 1, -452, -545,
1, -499, -431, 1, -556, -305, 1, -598, -239, 1, -613, -191, 1, -670, -116, 0, -186, 2495, 1, 874, 2495, 1, 874, 2545,
1, 1644, 2545, 0, 1404, 755, 1, 1458, 753, 1, 1471, 742, 1, 1479, 713, 1, 1496, 713, 1, 1512, 724, 1, 1521, 713,
1, 1512, 679, 1, 1529, 645, 1, 1533, 588, 1, 1554, 548, 1, 1575, 536, 1, 1583, 548, 1, 1583, 565, 1, 1591, 559,
1, 1604, 525, 1, 1650, 491, 1, 1662, 497, 1, 1675, 457, 1, 1667, 388, 1, 1675, 343, 1, 1658, 291, 1, 1675, 229,
1, 1671, 195, 1, 1658, 189, 1, 1658, 149, 1, 1641, 86, 1, 1646, 35, 1, 1621, 41, 1, 1587, -5, 1, 1587, -33,
1, 1600, -68, 1, 1621, -73, 1, 1646, -50, 1, 1683, -45, 1, 1687, -68, 1, 1671, -79, 1, 1662, -125, 1, 1625, -147,
1, 1621, -193, 1, 1629, -199, 1, 1591, -239, 1, 1587, -273, 1, 1537, -301, 1, 1512, -284, 1, 1454, -313, 1, 1446, -335,
1, 1404, -335, 1, 1366, -387, 1, 1308, -404, 1, 1258, -409, 1, 1237, -392, 1, 1208, -409, 1, 1204, -455, 1, 1175, -472,
1, 1166, -495, 1, 1141, -512, 1, 1125, -541, 1, 1087, -546, 1, 1066, -518, 1, 1045, -535, 1, 979, -569, 1, 945, -580,
1, 920, -620, 1, 854, -637, 1, 845, -609, 1, 820, -609, 1, 779, -615, 1, 737, -620, 1, 741, -609, 1, 762, -575,
1, 737, -535, 1, 691, -512, 1, 666, -466, 1, 679, -415, 1, 674, -375, 1, 691, -341, 1, 737, -318, 1, 762, -324,
1, 770, -307, 1, 754, -290, 1, 691, -273, 1, 629, -278, 1, 599, -261, 1, 583, -233, 1, 537, -210, 1, 524, -159,
1, 541, -96, 1, 528, -22, 1, 512, 24, 1, 512, 69, 1, 491, 103, 1, 483, 115, 1, 474, 166, 1, 449, 189,
1, 437, 166, 1, 458, 120, 1, 478, 81, 1, 478, 46, 1, 487, -16, 1, 474, -28, 1, 462, -16, 1, 453, 52,
1, 428, 86, 1, 420, 132, 1, 408, 166, 1, 387, 166, 1, 391, 109, 1, 383, 86, 1, 412, 1, 1, 399, -79,
1, 416, -119, 1, 437, -113, 1, 453, -153, 1, 428, -176, 1, 403, -153, 1, 374, -142, 1, 362, -85, 1, 312, -50,
1, 312, -5, 1, 283, 24, 1, 262, 18, 1, 249, -5, 1, 233, 24, 1, 220, 52, 1, 183, 52, 1, 166, 40,
1, 154, 48, 1, 163, 92, 1, 157, 136, 1, 148, 160, 1, 151, 192, 1, 136, 217, 1, 113, 225, 1, 84, 221,
1, 57, 245, 1, 48, 277, 1, 57, 309, 1, 75, 337, 1, 75, 365, 1, 57, 401, 1, 60, 433, 1, 63, 478,
1, 54, 526, 1, 10, 566, 1, -5, 606, 1, -7, 654, 1, -25, 682, 1, -75, 727, 1, -81, 759, 1, -66, 763,
1, -54, 735, 1, -40, 731, 1, -40, 743, 1, -52, 767, 1, -78, 775, 1, -78, 795, 1, -63, 835, 1, -63, 863,
1, -57, 907, 1, -57, 935, 1, -46, 943, 1, -57, 947, 1, -66, 976, 1, -96, 1016, 1, -101, 1060, 1, -96, 1108,
0,-1213,-1811, 1,-1146,-1819, 1,-1099,-1884, 1,-1051,-1931, 1, -983,-1940, 1, -914,-1978, 1, -826,-1978, 1, -737,-1950,
1, -723,-1903, 1, -744,-1884, 1, -805,-1894, 1, -853,-1903, 1, -867,-1866, 1, -846,-1838, 1, -873,-1810, 1, -948,-1800,
1, -983,-1744, 1,-1044,-1726, 1,-1051,-1688, 1,-1051,-1651, 1,-1105,-1586, 1,-1132,-1518, 1,-1143,-1490, 1,-1138,-1432,
1,-1127,-1418, 1,-1090,-1504, 1,-1016,-1562, 1, -943,-1583, 1, -943,-1562, 1, -985,-1533, 1, -985,-1511, 1, -943,-1533,
1, -848,-1547, 1, -811,-1526, 1, -774,-1526, 1, -742,-1504, 1, -727,-1468, 1, -695,-1468, 1, -679,-1439, 1, -684,-1410,
1, -648,-1374, 1, -611,-1345, 1, -579,-1295, 1, -537,-1281, 1, -526,-1295, 1, -526,-1252, 1, -511,-1216, 1, -463,-1209,
1, -426,-1223, 1, -421,-1230, 1, -405,-1216, 1, -363,-1223, 1, -331,-1259, 1, -316,-1252, 1, -305,-1201, 1, -284,-1209,
1, -258,-1173, 1, -216,-1194, 1, -184,-1201, 1, -173,-1165, 1, -147,-1165, 1, -137,-1137, 1, -121,-1144, 1, -100,-1209,
1, -52,-1252, 1, -5,-1259, 1, 85,-1331, 1, 101,-1331, 1, 143,-1317, 1, 185,-1324, 1, 280,-1367, 1, 364,-1367,
1, 427,-1345, 1, 512,-1353, 1, 580,-1403, 1, 670,-1425, 1, 712,-1418, 1, 791,-1432, 1, 796,-1418, 1, 743,-1360,
1, 738,-1317, 1, 749,-1273, 1, 722,-1230, 1, 733,-1201, 1, 759,-1194, 1, 807,-1201, 1, 817,-1173, 1, 859,-1173,
1, 891,-1209, 1, 928,-1216, 1, 944,-1201, 1, 970,-1165, 1, 996,-1173, 1, 1028,-1216, 0, 2063, 1855, 1, 2087, 1843,
1, 2153, 1753, 1, 2162, 1707, 1, 2181, 1669, 1, 2176, 1617, 1, 2171, 1560, 1, 2190, 1521, 1, 2186, 1489, 1, 2148, 1437,
1, 2115, 1302, 1, 2091, 1083, 1, 2049, 993, 1, 2035, 897, 1, 2040, 820, 1, 1993, 736, 1, 1927, 710, 1, 1922, 684,
1, 1898, 697, 1, 1884, 691, 1, 1861, 723, 1, 1809, 723, 1, 1790, 755, 1, 1724, 762, 1, 1701, 768, 1, 1691, 807,
1, 1663, 813, 1, 1616, 813, 1, 1658, 820, 1, 1654, 865, 1, 1625, 955, 1, 1602, 961, 1, 1588, 948, 1, 1560, 974,
1, 1517, 1038, 1, 1470, 1064, 1, 1451, 1051, 1, 1432, 1013, 1, 1353, 994, 1, 1345, 955, 1, 1357, 916, 1, 1367, 813,
1, 1404, 755, 0, -96, 1108, 1, -75, 1144, 1, -58, 1232, 1, -34, 1218, 1, -48, 1246, 1, -34, 1306, 1, -11, 1366,
1, 13, 1348, 1, 23, 1352, 1, 30, 1371, 1, -4, 1385, 1, 6, 1412, 1, 30, 1445, 1, 40, 1509, 1, 43, 1542,
1, 60, 1518, 1, 74, 1518, 1, 74, 1523, 1, 54, 1542, 1, 67, 1551, 1, 47, 1551, 1, 47, 1569, 1, 60, 1643,
1, 74, 1722, 1, 74, 1791, 1, 60, 1777, 1, 54, 1786, 1, 60, 1860, 1, 43, 1943, 1, 23, 2082, 1, 13, 2156,
1, -28, 2202, 1, -48, 2257, 1, -95, 2289, 1, -105, 2317, 1, -112, 2373, 1, -142, 2442, 1, -186, 2495, 0, 1922, 2029,
1, 1964, 1997, 1, 1969, 1958, 1, 1955, 1901, 1, 1969, 1868, 1, 1993, 1855, 1, 1997, 1823, 1, 1983, 1810, 1, 1988, 1778,
1, 2026, 1753, 1, 2063, 1765, 1, 2059, 1810, 1, 2044, 1823, 1, 2063, 1855, 0, 1644, 2545, 1, 1663, 2447, 1, 1677, 2435,
1, 1682, 2473, 1, 1691, 2467, 1, 1677, 2422, 1, 1720, 2357, 1, 1757, 2357, 1, 1790, 2319, 1, 1781, 2287, 1, 1809, 2242,
1, 1809, 2164, 1, 1833, 2074, 1, 1884, 2055, 1, 1922, 2029, 0, 0, 0,
};
| 118.342593
| 122
| 0.493623
|
krishna-beemanapalli
|
0bf02dfc7db3196778d39d7f62a505c5e099aa56
| 695
|
cpp
|
C++
|
super-mario-dx10/05-SceneManager/GameObject.cpp
|
HoangTuan0611/Game
|
64bbf4396ff38d17d3516c1eae687033f954d769
|
[
"MIT"
] | null | null | null |
super-mario-dx10/05-SceneManager/GameObject.cpp
|
HoangTuan0611/Game
|
64bbf4396ff38d17d3516c1eae687033f954d769
|
[
"MIT"
] | null | null | null |
super-mario-dx10/05-SceneManager/GameObject.cpp
|
HoangTuan0611/Game
|
64bbf4396ff38d17d3516c1eae687033f954d769
|
[
"MIT"
] | null | null | null |
#include <d3dx9.h>
#include <algorithm>
#include "debug.h"
#include "Textures.h"
#include "Game.h"
#include "GameObject.h"
#include "Sprites.h"
CGameObject::CGameObject()
{
x = y = 0;
vx = vy = 0;
nx = 1;
state = -1;
isDeleted = false;
}
void CGameObject::RenderBoundingBox()
{
D3DXVECTOR3 p(x, y, 0);
RECT rect;
LPTEXTURE bbox = CTextures::GetInstance()->Get(ID_TEX_BBOX);
float l, t, r, b;
GetBoundingBox(l, t, r, b);
rect.left = 0;
rect.top = 0;
rect.right = (int)r - (int)l;
rect.bottom = (int)b - (int)t;
float cx, cy;
CGame::GetInstance()->GetCamPos(cx, cy);
CGame::GetInstance()->Draw(x - cx, y - cy, bbox, &rect, BBOX_ALPHA);
}
CGameObject::~CGameObject()
{
}
| 15.795455
| 69
| 0.634532
|
HoangTuan0611
|
0bf3c04d24efd8fc163ffca218251295659579b9
| 614
|
cpp
|
C++
|
test/ui/test-item-vector.cpp
|
antonvw/wxExtension
|
d5523346cf0b1dbd45fd20dc33bf8d679299676c
|
[
"MIT"
] | 9
|
2016-01-10T20:59:02.000Z
|
2019-01-09T14:18:13.000Z
|
test/ui/test-item-vector.cpp
|
antonvw/wxExtension
|
d5523346cf0b1dbd45fd20dc33bf8d679299676c
|
[
"MIT"
] | 31
|
2015-01-30T17:46:17.000Z
|
2017-03-04T17:33:50.000Z
|
test/ui/test-item-vector.cpp
|
antonvw/wxExtension
|
d5523346cf0b1dbd45fd20dc33bf8d679299676c
|
[
"MIT"
] | 2
|
2015-04-05T08:45:22.000Z
|
2018-08-24T06:43:24.000Z
|
////////////////////////////////////////////////////////////////////////////////
// Name: test-item-vector.cpp
// Purpose: Implementation for wex unit testing
// Author: Anton van Wezenbeek
// Copyright: (c) 2020 Anton van Wezenbeek
////////////////////////////////////////////////////////////////////////////////
#include "../test.h"
#include <wex/ui/item-vector.h>
#include <wex/ui/item.h>
TEST_SUITE_BEGIN("wex::item");
TEST_CASE("wex::item_vector")
{
const std::vector<wex::item> v({{"spin1", 0, 10, 0}});
wex::item_vector iv(&v);
REQUIRE(iv.find<int>("spin1") == 0);
}
TEST_SUITE_END();
| 25.583333
| 80
| 0.480456
|
antonvw
|
0bffc3dc70fd8e9de9cccdb7f0c8eb6b65cae632
| 579
|
cpp
|
C++
|
demos/exchange_manager_clean.cpp
|
MaximilienNaveau/shared_memory
|
1440454759cdd19e0d898753d86b8714c1aefa84
|
[
"BSD-3-Clause"
] | 2
|
2020-09-08T04:01:02.000Z
|
2021-01-28T15:02:11.000Z
|
demos/exchange_manager_clean.cpp
|
MaximilienNaveau/shared_memory
|
1440454759cdd19e0d898753d86b8714c1aefa84
|
[
"BSD-3-Clause"
] | 13
|
2019-09-24T17:21:49.000Z
|
2021-03-02T10:09:03.000Z
|
demos/exchange_manager_clean.cpp
|
MaximilienNaveau/shared_memory
|
1440454759cdd19e0d898753d86b8714c1aefa84
|
[
"BSD-3-Clause"
] | 2
|
2019-05-06T08:25:35.000Z
|
2020-04-14T11:49:02.000Z
|
#include <signal.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <iostream>
#include "shared_memory/demos/four_int_values.hpp"
#include "shared_memory/exchange_manager_producer.hpp"
#define SEGMENT_ID "exchange_demo_segment"
#define QUEUE_SIZE 2000
int main()
{
shared_memory::Exchange_manager_producer<
shared_memory::Four_int_values,
QUEUE_SIZE>::clean_mutex(std::string(SEGMENT_ID));
shared_memory::Exchange_manager_producer<
shared_memory::Four_int_values,
QUEUE_SIZE>::clean_memory(std::string(SEGMENT_ID));
}
| 27.571429
| 59
| 0.75475
|
MaximilienNaveau
|
0405eeac55d49dc3fb9f801220a850c5c48fcb26
| 1,201
|
cpp
|
C++
|
lib/src/io/Stream.cpp
|
tuanphuc/Viry3D
|
8f6e141f222ce01372ffd2183a4d39e7a076aad2
|
[
"Apache-2.0"
] | null | null | null |
lib/src/io/Stream.cpp
|
tuanphuc/Viry3D
|
8f6e141f222ce01372ffd2183a4d39e7a076aad2
|
[
"Apache-2.0"
] | null | null | null |
lib/src/io/Stream.cpp
|
tuanphuc/Viry3D
|
8f6e141f222ce01372ffd2183a4d39e7a076aad2
|
[
"Apache-2.0"
] | 1
|
2020-09-04T07:38:32.000Z
|
2020-09-04T07:38:32.000Z
|
/*
* Viry3D
* Copyright 2014-2019 by Stack - stackos@qq.com
*
* 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 "Stream.h"
namespace Viry3D
{
Stream::Stream():
m_position(0),
m_closed(false),
m_length(0)
{
}
void Stream::Close()
{
m_closed = true;
}
int Stream::Read(void* buffer, int size)
{
int read;
if (m_position + size <= m_length)
{
read = size;
}
else
{
read = m_length - m_position;
}
m_position += read;
return read;
}
int Stream::Write(void* buffer, int size)
{
int write;
if (m_position + size <= m_length)
{
write = size;
}
else
{
write = m_length - m_position;
}
m_position += write;
return write;
}
}
| 17.157143
| 74
| 0.668609
|
tuanphuc
|
040700cc399337a7b35ef964523fd9bd98b6c7a1
| 1,469
|
hpp
|
C++
|
lib/aoc2021/include/aoc2021/day3/part2.hpp
|
bencodestx/aoc-2021-cpp
|
41518858a6ec4af65754d0170f4d6bfbe4d9548d
|
[
"MIT"
] | null | null | null |
lib/aoc2021/include/aoc2021/day3/part2.hpp
|
bencodestx/aoc-2021-cpp
|
41518858a6ec4af65754d0170f4d6bfbe4d9548d
|
[
"MIT"
] | null | null | null |
lib/aoc2021/include/aoc2021/day3/part2.hpp
|
bencodestx/aoc-2021-cpp
|
41518858a6ec4af65754d0170f4d6bfbe4d9548d
|
[
"MIT"
] | null | null | null |
#pragma once
#include "aoc2021/day3/operators.hpp"
#include "aoc2021/read_vector.hpp"
#include <array>
#include <bitset>
#include <cstddef>
#include <functional>
#include <istream>
namespace aoc2021::day3 {
template <std::size_t bit_count>
auto count_bits_in_position(const std::size_t bit, const auto &reports) {
std::size_t count{};
for (const auto &report : reports) {
if (report[bit]) {
++count;
}
}
return count;
}
template <std::size_t bit_count, typename Comparison> auto rating(auto values) {
Comparison comparison{};
for (std::size_t bit = 0; bit < bit_count; ++bit) {
if (std::size(values) == 1) {
break;
}
const auto count =
count_bits_in_position<bit_count>(bit_count - bit - 1, values);
bool value_to_erase;
if (comparison(count, std::size(values) - count)) {
value_to_erase = false;
} else {
value_to_erase = true;
}
std::erase_if(values, [&](const auto &x) {
return x[bit_count - bit - 1] == value_to_erase;
});
}
return values[0].to_ulong();
}
template <std::size_t bit_count> auto part2(auto &in) {
const auto reports = read_vector<std::bitset<bit_count>>(in);
const auto oxygen_generator_rating =
rating<bit_count, std::greater_equal<std::size_t>>(reports);
const auto co2_scrubber_rating =
rating<bit_count, std::less<std::size_t>>(reports);
return oxygen_generator_rating * co2_scrubber_rating;
}
} // namespace aoc2021::day3
| 27.203704
| 80
| 0.671205
|
bencodestx
|
040942e8a5f9792ace3579338f93c58f580a870a
| 842
|
cpp
|
C++
|
to edit/menu/title.cpp
|
wengxxaa/Ninja
|
a7e11b6db16fd614234c4a282411bd80cbfb5ad3
|
[
"Apache-2.0"
] | 1
|
2019-10-23T04:39:51.000Z
|
2019-10-23T04:39:51.000Z
|
to edit/menu/title.cpp
|
wengxxaa/Ninja
|
a7e11b6db16fd614234c4a282411bd80cbfb5ad3
|
[
"Apache-2.0"
] | null | null | null |
to edit/menu/title.cpp
|
wengxxaa/Ninja
|
a7e11b6db16fd614234c4a282411bd80cbfb5ad3
|
[
"Apache-2.0"
] | 1
|
2019-10-23T04:39:52.000Z
|
2019-10-23T04:39:52.000Z
|
#include "title.h"
#include <stdlib.h>
Title::Title()
{
// empty
}
Title::~Title()
{
belt.free();
title.free();
}
void Title::load( const int& screen_w )
{
belt.setName( "title-belt" );
belt.load( "data/sprites/menu/belt.png" );
belt.setPosition( screen_w/2 - belt.getWidth()/2, 10 );
title.setName( "title-title" );
title.setFont( "data/fonts/BADABB__.TTF", 110, 0x7F, 0x99, 0x95 );
title.setText( "Ninja" );
title.setPosition( screen_w/2 - title.getWidth()/2, -8 );
}
void Title::draw( sf::RenderWindow &window )
{
window.draw( belt.get() );
window.draw( title.get() );
}
const int& Title::getBot()
{
return belt.getBot();
}
void Title::fadein( int i, int max )
{
belt.fadein( i, max );
title.fadein( i, max );
}
void Title::fadeout( int i, int min )
{
belt.fadeout( i, min );
title.fadeout( i, min );
}
| 16.84
| 67
| 0.625891
|
wengxxaa
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.