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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
cee9c2e788615a4b2a76f79e1347a27ce246b765
| 19,539
|
cpp
|
C++
|
fm_Btraj/src/Btraj/third_party/sdf_tools/src/sdf_tools/sdf.cpp
|
Sunshinehualong/motion_Planning
|
ea127de8cd8f32e9994538416d0c74b99054214f
|
[
"MIT"
] | 11
|
2019-08-24T08:28:17.000Z
|
2021-04-28T05:23:42.000Z
|
fm_Btraj/src/Btraj/third_party/sdf_tools/src/sdf_tools/sdf.cpp
|
lvhualong/motion_Planning
|
ea127de8cd8f32e9994538416d0c74b99054214f
|
[
"MIT"
] | null | null | null |
fm_Btraj/src/Btraj/third_party/sdf_tools/src/sdf_tools/sdf.cpp
|
lvhualong/motion_Planning
|
ea127de8cd8f32e9994538416d0c74b99054214f
|
[
"MIT"
] | 6
|
2019-08-24T08:28:19.000Z
|
2020-10-19T12:47:20.000Z
|
#include <stdlib.h>
#include <stdio.h>
#include <vector>
#include <string>
#include <sstream>
#include <iostream>
#include <fstream>
#include <stdexcept>
#include <unordered_map>
#include <zlib.h>
#include <ros/ros.h>
#include <arc_utilities/eigen_helpers_conversions.hpp>
#include <arc_utilities/zlib_helpers.hpp>
#include <sdf_tools/sdf.hpp>
#include <sdf_tools/SDF.h>
using namespace sdf_tools;
std::vector<uint8_t> SignedDistanceField::GetInternalBinaryRepresentation(const std::vector<float>& field_data)
{
std::vector<uint8_t> raw_binary_data(field_data.size() * 4);
for (size_t field_index = 0, binary_index = 0; field_index < field_data.size(); field_index++, binary_index+=4)
{
// Convert the float at the current index into 4 bytes and store them
float field_value = field_data[field_index];
std::vector<uint8_t> binary_value = FloatToBinary(field_value);
raw_binary_data[binary_index] = binary_value[0];
raw_binary_data[binary_index + 1] = binary_value[1];
raw_binary_data[binary_index + 2] = binary_value[2];
raw_binary_data[binary_index + 3] = binary_value[3];
}
return raw_binary_data;
}
std::vector<float> SignedDistanceField::UnpackFieldFromBinaryRepresentation(std::vector<uint8_t>& binary)
{
if ((binary.size() % 4) != 0)
{
std::cerr << "Invalid binary representation - length is not a multiple of 4" << std::endl;
return std::vector<float>();
}
uint64_t data_size = binary.size() / 4;
std::vector<float> field_data(data_size);
for (size_t field_index = 0, binary_index = 0; field_index < field_data.size(); field_index++, binary_index+=4)
{
std::vector<uint8_t> binary_block{binary[binary_index], binary[binary_index + 1], binary[binary_index + 2], binary[binary_index + 3]};
field_data[field_index] = FloatFromBinary(binary_block);
}
return field_data;
}
bool SignedDistanceField::SaveToFile(const std::string& filepath)
{
// Convert to message representation
sdf_tools::SDF message_rep = GetMessageRepresentation();
// Save message to file
try
{
std::ofstream output_file(filepath.c_str(), std::ios::out|std::ios::binary);
uint32_t serialized_size = ros::serialization::serializationLength(message_rep);
std::unique_ptr<uint8_t> ser_buffer(new uint8_t[serialized_size]);
ros::serialization::OStream ser_stream(ser_buffer.get(), serialized_size);
ros::serialization::serialize(ser_stream, message_rep);
output_file.write((char*)ser_buffer.get(), serialized_size);
output_file.close();
return true;
}
catch (...)
{
return false;
}
}
bool SignedDistanceField::LoadFromFile(const std::string &filepath)
{
try
{
// Load message from file
std::ifstream input_file(filepath.c_str(), std::ios::in|std::ios::binary);
input_file.seekg(0, std::ios::end);
std::streampos end = input_file.tellg();
input_file.seekg(0, std::ios::beg);
std::streampos begin = input_file.tellg();
uint32_t serialized_size = end - begin;
std::unique_ptr<uint8_t> deser_buffer(new uint8_t[serialized_size]);
input_file.read((char*) deser_buffer.get(), serialized_size);
ros::serialization::IStream deser_stream(deser_buffer.get(), serialized_size);
sdf_tools::SDF new_message;
ros::serialization::deserialize(deser_stream, new_message);
// Load state from the message
bool success = LoadFromMessageRepresentation(new_message);
return success;
}
catch (...)
{
return false;
}
}
sdf_tools::SDF SignedDistanceField::GetMessageRepresentation()
{
sdf_tools::SDF message_rep;
// Populate message
message_rep.header.frame_id = frame_;
const Eigen::Affine3d& origin_transform = distance_field_.GetOriginTransform();
message_rep.origin_transform.translation.x = origin_transform.translation().x();
message_rep.origin_transform.translation.y = origin_transform.translation().y();
message_rep.origin_transform.translation.z = origin_transform.translation().z();
const Eigen::Quaterniond origin_transform_rotation(origin_transform.rotation());
message_rep.origin_transform.rotation.x = origin_transform_rotation.x();
message_rep.origin_transform.rotation.y = origin_transform_rotation.y();
message_rep.origin_transform.rotation.z = origin_transform_rotation.z();
message_rep.origin_transform.rotation.w = origin_transform_rotation.w();
message_rep.dimensions.x = distance_field_.GetXSize();
message_rep.dimensions.y = distance_field_.GetYSize();
message_rep.dimensions.z = distance_field_.GetZSize();
message_rep.sdf_cell_size = GetResolution();
message_rep.OOB_value = distance_field_.GetDefaultValue();
message_rep.initialized = initialized_;
message_rep.locked = locked_;
const std::vector<float>& raw_data = distance_field_.GetRawData();
std::vector<uint8_t> binary_data = GetInternalBinaryRepresentation(raw_data);
message_rep.data = ZlibHelpers::CompressBytes(binary_data);
return message_rep;
}
bool SignedDistanceField::LoadFromMessageRepresentation(sdf_tools::SDF& message)
{
// Make a new voxel grid inside
Eigen::Translation3d origin_translation(message.origin_transform.translation.x, message.origin_transform.translation.y, message.origin_transform.translation.z);
Eigen::Quaterniond origin_rotation(message.origin_transform.rotation.w, message.origin_transform.rotation.x, message.origin_transform.rotation.y, message.origin_transform.rotation.z);
Eigen::Affine3d origin_transform = origin_translation * origin_rotation;
VoxelGrid::VoxelGrid<float> new_field(origin_transform, message.sdf_cell_size, message.dimensions.x, message.dimensions.y, message.dimensions.z, message.OOB_value);
// Unpack the binary data
std::vector<uint8_t> binary_data = ZlibHelpers::DecompressBytes(message.data);
std::vector<float> unpacked = UnpackFieldFromBinaryRepresentation(binary_data);
if (unpacked.empty())
{
std::cerr << "Unpack returned an empty SDF" << std::endl;
return false;
}
bool success = new_field.SetRawData(unpacked);
if (!success)
{
std::cerr << "Unable to set internal representation of the SDF" << std::endl;
return false;
}
// Set it
distance_field_ = new_field;
frame_ = message.header.frame_id;
initialized_ = message.initialized;
locked_ = message.locked;
return true;
}
visualization_msgs::Marker SignedDistanceField::ExportForDisplay(float alpha) const
{
// Assemble a visualization_markers::Marker representation of the SDF to display in RViz
visualization_msgs::Marker display_rep;
// Populate the header
display_rep.header.frame_id = frame_;
// Populate the options
display_rep.ns = "sdf_display";
display_rep.id = 1;
display_rep.type = visualization_msgs::Marker::CUBE_LIST;
display_rep.action = visualization_msgs::Marker::ADD;
display_rep.lifetime = ros::Duration(0.0);
display_rep.frame_locked = false;
const Eigen::Affine3d base_transform = Eigen::Affine3d::Identity();
display_rep.pose = EigenHelpersConversions::EigenAffine3dToGeometryPose(base_transform);
display_rep.scale.x = GetResolution();
display_rep.scale.y = GetResolution();
display_rep.scale.z = GetResolution();
// Add all the cells of the SDF to the message
double min_distance = 0.0;
double max_distance = 0.0;
for (int64_t x_index = 0; x_index < distance_field_.GetNumXCells(); x_index++)
{
for (int64_t y_index = 0; y_index < distance_field_.GetNumYCells(); y_index++)
{
for (int64_t z_index = 0; z_index < distance_field_.GetNumZCells(); z_index++)
{
// Update minimum/maximum distance variables
float distance = Get(x_index, y_index, z_index);
if (distance < min_distance)
{
min_distance = distance;
}
if (distance > max_distance)
{
max_distance = distance;
}
// Convert SDF indices into a real-world location
std::vector<double> location = distance_field_.GridIndexToLocation(x_index, y_index, z_index);
geometry_msgs::Point new_point;
new_point.x = location[0];
new_point.y = location[1];
new_point.z = location[2];
display_rep.points.push_back(new_point);
}
}
}
// Add colors for all the cells of the SDF to the message
for (int64_t x_index = 0; x_index < distance_field_.GetNumXCells(); x_index++)
{
for (int64_t y_index = 0; y_index < distance_field_.GetNumYCells(); y_index++)
{
for (int64_t z_index = 0; z_index < distance_field_.GetNumZCells(); z_index++)
{
// Update minimum/maximum distance variables
float distance = Get(x_index, y_index, z_index);
std_msgs::ColorRGBA new_color;
new_color.a = alpha;
if (distance > 0.0)
{
new_color.b = 0.0;
new_color.g = (fabs(distance / max_distance) * 0.8) + 0.2;
new_color.r = 0.0;
}
else if (distance < 0.0)
{
new_color.b = 0.0;
new_color.g = 0.0;
new_color.r = (fabs(distance / min_distance) * 0.8) + 0.2;
}
else
{
new_color.b = 1.0;
new_color.g = 0.0;
new_color.r = 0.0;
}
display_rep.colors.push_back(new_color);
}
}
}
return display_rep;
}
visualization_msgs::Marker SignedDistanceField::ExportForDisplayCollisionOnly(float alpha) const
{
// Assemble a visualization_markers::Marker representation of the SDF to display in RViz
visualization_msgs::Marker display_rep;
// Populate the header
display_rep.header.frame_id = frame_;
// Populate the options
display_rep.ns = "sdf_display";
display_rep.id = 1;
display_rep.type = visualization_msgs::Marker::CUBE_LIST;
display_rep.action = visualization_msgs::Marker::ADD;
display_rep.lifetime = ros::Duration(0.0);
display_rep.frame_locked = false;
const Eigen::Affine3d base_transform = Eigen::Affine3d::Identity();
display_rep.pose = EigenHelpersConversions::EigenAffine3dToGeometryPose(base_transform);
display_rep.scale.x = GetResolution();
display_rep.scale.y = GetResolution();
display_rep.scale.z = GetResolution();
// Add all the cells of the SDF to the message
for (int64_t x_index = 0; x_index < distance_field_.GetNumXCells(); x_index++)
{
for (int64_t y_index = 0; y_index < distance_field_.GetNumYCells(); y_index++)
{
for (int64_t z_index = 0; z_index < distance_field_.GetNumZCells(); z_index++)
{
// Update minimum/maximum distance variables
float distance = Get(x_index, y_index, z_index);
if (distance <= 0.0)
{
// Convert SDF indices into a real-world location
std::vector<double> location = distance_field_.GridIndexToLocation(x_index, y_index, z_index);
geometry_msgs::Point new_point;
new_point.x = location[0];
new_point.y = location[1];
new_point.z = location[2];
display_rep.points.push_back(new_point);
// Color it
std_msgs::ColorRGBA new_color;
new_color.a = alpha;
new_color.b = 0.0;
new_color.g = 0.0;
new_color.r = 1.0;
display_rep.colors.push_back(new_color);
}
}
}
}
return display_rep;
}
visualization_msgs::Marker SignedDistanceField::ExportForDebug(float alpha) const
{
// Assemble a visualization_markers::Marker representation of the SDF to display in RViz
visualization_msgs::Marker display_rep;
// Populate the header
display_rep.header.frame_id = frame_;
// Populate the options
display_rep.ns = "sdf_display";
display_rep.id = 1;
display_rep.type = visualization_msgs::Marker::CUBE_LIST;
display_rep.action = visualization_msgs::Marker::ADD;
display_rep.lifetime = ros::Duration(0.0);
display_rep.frame_locked = false;
const Eigen::Affine3d base_transform = Eigen::Affine3d::Identity();
display_rep.pose = EigenHelpersConversions::EigenAffine3dToGeometryPose(base_transform);
display_rep.scale.x = GetResolution();
display_rep.scale.y = GetResolution();
display_rep.scale.z = GetResolution();
// Add all the cells of the SDF to the message
for (int64_t x_index = 0; x_index < distance_field_.GetNumXCells(); x_index++)
{
for (int64_t y_index = 0; y_index < distance_field_.GetNumYCells(); y_index++)
{
for (int64_t z_index = 0; z_index < distance_field_.GetNumZCells(); z_index++)
{
// Convert SDF indices into a real-world location
std::vector<double> location = distance_field_.GridIndexToLocation(x_index, y_index, z_index);
geometry_msgs::Point new_point;
new_point.x = location[0];
new_point.y = location[1];
new_point.z = location[2];
display_rep.points.push_back(new_point);
// Color it
std_msgs::ColorRGBA new_color;
new_color.a = alpha;
new_color.b = 0.0;
new_color.g = 1.0;
new_color.r = 1.0;
display_rep.colors.push_back(new_color);
}
}
}
return display_rep;
}
void SignedDistanceField::FollowGradientsToLocalMaximaUnsafe(VoxelGrid::VoxelGrid<Eigen::Vector3d>& watershed_map, const int64_t x_index, const int64_t y_index, const int64_t z_index) const
{
// First, check if we've already found the local maxima for the current cell
const Eigen::Vector3d& stored = watershed_map.GetImmutable(x_index, y_index, z_index).first;
if (stored.x() != -INFINITY && stored.y() != -INFINITY && stored.z() != -INFINITY)
{
// We've already found it for this cell, so we can skip it
return;
}
// Second, check if it's inside an obstacle
float stored_distance = Get(x_index, y_index, z_index);
if (stored_distance <= 0.0)
{
// It's inside an object, so we can skip it
return;
}
else
{
// Find the local maxima
std::vector<double> raw_gradient = GetGradient(x_index, y_index, z_index, true);
Eigen::Vector3d current_gradient(raw_gradient[0], raw_gradient[1], raw_gradient[2]);
if (GradientIsEffectiveFlat(current_gradient))
{
std::vector<double> location = GridIndexToLocation(x_index, y_index, z_index);
Eigen::Vector3d local_maxima(location[0], location[1], location[2]);
watershed_map.SetValue(x_index, y_index, z_index, local_maxima);
}
else
{
// Follow the gradient, one cell at a time, until we reach a local maxima
std::unordered_map<VoxelGrid::GRID_INDEX, int8_t> path;
VoxelGrid::GRID_INDEX current_index(x_index, y_index, z_index);
path[current_index] = 1;
Eigen::Vector3d local_maxima(-INFINITY, -INFINITY, -INFINITY);
while (true)
{
if (path.size() == 10000)
{
std::cerr << "Warning, gradient path is long (i.e >= 10000 steps)" << std::endl;
}
current_index = GetNextFromGradient(current_index, current_gradient);
if (path[current_index] != 0)
{
//std::cerr << "LMAX found by cycle detect" << std::endl;
// If we've already been here, then we are done
std::vector<double> location = GridIndexToLocation(current_index);
local_maxima = Eigen::Vector3d(location[0], location[1], location[2]);
break;
}
// Check if we've been pushed past the edge
if (current_index.x < 0 || current_index.y < 0 || current_index.z < 0 || current_index.x >= watershed_map.GetNumXCells() || current_index.y >= watershed_map.GetNumYCells() || current_index.z >= watershed_map.GetNumZCells())
{
// We have the "off the grid" local maxima
local_maxima = Eigen::Vector3d(INFINITY, INFINITY, INFINITY);
break;
}
path[current_index] = 1;
// Check if the new index has already been checked
const Eigen::Vector3d& new_stored = watershed_map.GetImmutable(current_index).first;
if (new_stored.x() != -INFINITY && new_stored.y() != -INFINITY && new_stored.z() != -INFINITY)
{
// We have the local maxima
local_maxima = new_stored;
break;
}
else
{
raw_gradient = GetGradient(current_index, true);
current_gradient = Eigen::Vector3d(raw_gradient[0], raw_gradient[1], raw_gradient[2]);
if (GradientIsEffectiveFlat(current_gradient))
{
//std::cerr << "LMAX found by flat detect" << std::endl;
// We have the local maxima
std::vector<double> location = GridIndexToLocation(current_index);
local_maxima = Eigen::Vector3d(location[0], location[1], location[2]);
break;
}
}
}
// Now, go back and mark the entire explored path with the local maxima
std::unordered_map<VoxelGrid::GRID_INDEX, int8_t>::const_iterator path_itr;
for (path_itr = path.begin(); path_itr != path.end(); ++path_itr)
{
const VoxelGrid::GRID_INDEX& index = path_itr->first;
watershed_map.SetValue(index, local_maxima);
}
}
}
}
VoxelGrid::VoxelGrid<Eigen::Vector3d> SignedDistanceField::ComputeLocalMaximaMap() const
{
VoxelGrid::VoxelGrid<Eigen::Vector3d> watershed_map(GetOriginTransform(), GetResolution(), GetXSize(), GetYSize(), GetZSize(), Eigen::Vector3d(-INFINITY, -INFINITY, -INFINITY));
for (int64_t x_idx = 0; x_idx < watershed_map.GetNumXCells(); x_idx++)
{
for (int64_t y_idx = 0; y_idx < watershed_map.GetNumYCells(); y_idx++)
{
for (int64_t z_idx = 0; z_idx < watershed_map.GetNumZCells(); z_idx++)
{
// We use an "unsafe" function here because we know all the indices we provide it will be safe
FollowGradientsToLocalMaximaUnsafe(watershed_map, x_idx, y_idx, z_idx);
}
}
}
return watershed_map;
}
| 44.406818
| 239
| 0.625825
|
Sunshinehualong
|
ceebbbbde132f1148d9ce7fb589a3c0c04854e84
| 186
|
cpp
|
C++
|
NJUPT-ACM/12.3/C.cpp
|
ZsgsDesign/My_ACM_Life
|
9cd5e6dedbf58d8dd2322d5f06ea9d86583f7c46
|
[
"CC-BY-4.0"
] | 4
|
2019-02-17T15:14:21.000Z
|
2019-03-30T11:34:19.000Z
|
NJUPT-ACM/12.3/C.cpp
|
ZsgsDesign/My_ACM_Life
|
9cd5e6dedbf58d8dd2322d5f06ea9d86583f7c46
|
[
"CC-BY-4.0"
] | null | null | null |
NJUPT-ACM/12.3/C.cpp
|
ZsgsDesign/My_ACM_Life
|
9cd5e6dedbf58d8dd2322d5f06ea9d86583f7c46
|
[
"CC-BY-4.0"
] | null | null | null |
#include <bits\stdc++.h>
using namespace std;
double a,b,c;
int main ()
{
while (cin >> a >> b >> c) printf("%.5lf\n",(a*b+b*(b-1))/(a+b-c-1)/(a+b));
return 0;
}
| 15.5
| 81
| 0.473118
|
ZsgsDesign
|
ceebf52041f3ca6247ade48f10a248de52cb2ee2
| 212
|
cpp
|
C++
|
数学规律/89.格雷编码/grayCode.cpp
|
YichengZhong/Top-Interview-Questions
|
124828d321f482a0eaa30012b3706267487bfd24
|
[
"MIT"
] | 1
|
2019-10-21T14:40:39.000Z
|
2019-10-21T14:40:39.000Z
|
数学规律/89.格雷编码/grayCode.cpp
|
YichengZhong/Top-Interview-Questions
|
124828d321f482a0eaa30012b3706267487bfd24
|
[
"MIT"
] | null | null | null |
数学规律/89.格雷编码/grayCode.cpp
|
YichengZhong/Top-Interview-Questions
|
124828d321f482a0eaa30012b3706267487bfd24
|
[
"MIT"
] | 1
|
2020-11-04T07:33:34.000Z
|
2020-11-04T07:33:34.000Z
|
class Solution {
public:
vector<int> grayCode(int n) {
vector<int> ans;
int powN = 1 << n;
for(int i = 0; i < powN; ++i)
ans.push_back(i^i>>1);
return ans;
}
};
| 21.2
| 37
| 0.466981
|
YichengZhong
|
ceed005071b3cfd486a386d2a472bd32ffe498e7
| 1,975
|
cpp
|
C++
|
src/main.cpp
|
teuthid/eq
|
4b7f0bd68fa8d3e186b076df8a606600cf482d82
|
[
"BSD-3-Clause"
] | null | null | null |
src/main.cpp
|
teuthid/eq
|
4b7f0bd68fa8d3e186b076df8a606600cf482d82
|
[
"BSD-3-Clause"
] | null | null | null |
src/main.cpp
|
teuthid/eq
|
4b7f0bd68fa8d3e186b076df8a606600cf482d82
|
[
"BSD-3-Clause"
] | null | null | null |
/*
eq - transcendental fan controller ;)
Copyright (c) 2018-2019 Mariusz Przygodzki
*/
#include "eq_eeprom.h"
#include "eq_pwm_timer.h"
#include "eq_tasks.h"
#include <TaskScheduler.h>
#if defined(EQ_UNIT_TEST)
#include <AUnitVerbose.h>
#include "eq_display.h"
#include "test_eq.h"
#endif // defined(EQ_UNIT_TEST)
Scheduler eqController;
Scheduler eqHPController; // high priority scheduler
void setup() {
Serial.begin(115200);
#if !defined(EQ_UNIT_TEST)
#if defined(EQ_DEBUG)
Serial.print(F("Initializing... "));
#endif
if (EqConfig::init()) {
eqHPController.addTask(eqTaskItSensorControl());
eqController.addTask(eqTaskHeartbeat());
eqController.addTask(eqTaskHtSensorControl());
eqController.addTask(eqTaskFanControl());
eqController.addTask(eqTaskBlowingControl());
#if defined(EQ_DEBUG)
eqController.addTask(eqTaskDebug());
#endif
eqController.setHighPriorityScheduler(&eqHPController);
eqController.enableAll();
#if defined(EQ_DEBUG)
Serial.println();
EqConfig::showSettings();
Serial.println(F("Running..."));
#endif
eqController.startNow();
} else {
EqConfig::showAlert();
abort();
}
#else // defined(EQ_UNIT_TEST)
Serial.println(F("Testing..."));
EqConfig::init();
eqDisplay().off();
#endif
}
void loop() {
#if !defined(EQ_UNIT_TEST)
eqController.execute();
#else
aunit::TestRunner::run();
#endif
}
void EqConfig::disableAllTasks() {
// disable all tasks in both schedulers
eqController.disableAll();
}
void EqConfig::saveWatchdogPoint() {
if (saveWatchdogPoint_) {
Task &__t = eqController.currentTask();
#if defined(EQ_DEBUG)
uint8_t __cp = __t.getControlPoint();
if (__cp == 0) // control point is not set
__cp = __t.getId();
EqEeprom::writeValue<uint8_t>(EqEeprom::LastWatchdogPoint, __cp);
#else
EqEeprom::writeValue<uint8_t>(EqEeprom::LastWatchdogPoint,
static_cast<uint8_t>(__t.getId()));
#endif
}
}
| 23.795181
| 69
| 0.695696
|
teuthid
|
ceedc0673542880bed81b97a16351850bc41e9d6
| 13,638
|
cpp
|
C++
|
src/main/cpp/LivePresetsExtension.cpp
|
Burtan/LivePresetsExtension
|
bbac7a6bcdf584c1b1794e5affa5ce0ba5659a48
|
[
"MIT"
] | 2
|
2020-04-08T19:06:53.000Z
|
2020-04-11T15:50:33.000Z
|
src/main/cpp/LivePresetsExtension.cpp
|
Burtan/LivePresetsExtension
|
bbac7a6bcdf584c1b1794e5affa5ce0ba5659a48
|
[
"MIT"
] | null | null | null |
src/main/cpp/LivePresetsExtension.cpp
|
Burtan/LivePresetsExtension
|
bbac7a6bcdf584c1b1794e5affa5ce0ba5659a48
|
[
"MIT"
] | null | null | null |
/******************************************************************************
/ LivePresetsExtension
/
/ Base extension class
/
/ Copyright (c) 2020 and later Dr. med. Frederik Bertling
/
/
/ 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 <sstream>
#include <functional>
#include <LivePresetsExtension.h>
#include <plugins/lpe_ultimate.h>
#include <plugins/reaper_plugin_functions.h>
#include <data/models/HotkeyCommand.h>
#include <data/models/ActionCommand.h>
#include <ui/LivePresetsListAdapter.h>
#include <util/util.h>
/*
Main entry point, is called when the extension is loaded.
*/
LPE::LPE(REAPER_PLUGIN_HINSTANCE hInstance, HWND mainHwnd) : mMainHwnd(mainHwnd), mInstance(hInstance) {
//register commands and project config with reaper
mActions.add(new HotkeyCommand(
"LPE_OPENTOGGLE_MAIN",
"LPE - Opens/Closes the LivePresetsExtension main window",
std::bind(&LPE::toggleMainWindow, this)
));
mActions.add(new HotkeyCommand(
"LPE_OPENTOGGLE_ABOUT",
"LPE - Opens/Closes the LivePresetsExtension about window",
std::bind(&LPE::toggleAboutWindow, this)
));
//create control view action only on ultimate
if (Licensing_IsUltimate()) {
mActions.add(new HotkeyCommand(
"LPE_OPENTOGGLE_CONTROL",
"LPE - Opens/Closes the LivePresetsExtension ControlView window",
std::bind(&LPE::toggleControlView, this)
));
}
mActions.add(new HotkeyCommand(
"LPE_TRACKSAVEALL",
"LPE - Saves the track data into all presets",
std::bind(&LPE::onApplySelectedTrackConfigsToAllPresets, this)
));
mActions.add(new HotkeyCommand(
"LPE_TOGGLEMUTEDVISIBILITY",
"LPE - Shows/Hides muted tracks in TCP",
std::bind(&LPE::toggleMutedTracksVisibility, this)
));
mActions.add(new HotkeyCommand(
"LPE_ADDPRESET",
"LPE - Creates a new preset",
std::bind(&LPE::createPreset, this)
));
mActions.add(new HotkeyCommand(
"LPE_UPDATEPRESET",
"LPE - Updates the selected preset",
std::bind(&LPE::updatePreset, this)
));
mActions.add(new HotkeyCommand(
"LPE_EDITPRESET",
"LPE - Edits the selected preset",
std::bind(&LPE::editPreset, this)
));
mActions.add(new HotkeyCommand(
"LPE_REMOVEORESET",
"LPE - Removes the selected presets",
std::bind(&LPE::removePresets, this)
));
mActions.add(new HotkeyCommand(
"LPE_SHOWSETTINGS",
"LPE - Shows/Hides the settings menu",
std::bind(&LPE::showSettings, this)
));
using namespace std::placeholders;
mActions.add(new ActionCommand(
"LPE_SELECTPRESET",
"LPE - Selects a preset",
std::bind(&LPE::onRecallPreset, this, _1, _2, _3, _4)
));
}
/**
* another thing you can register is "hookcommand", which you pass a callback:
NON_API: bool runCommand(int command, int flag);
register("hookcommand",runCommand);
note: it's OK to call Main_OnCommand() within your runCommand, however you MUST check for recursion if doing so!
in fact, any use of this hook should benefit from a simple reentrancy test...
* @param iCmd
* @param flag is usually 0 but can sometimes have useful info depending on the message.
* @return TRUE to eat (process) the command.
*/
bool LPE::onActionExecuted(int iCmd, int) {
return mActions.run(iCmd);
}
/**
* you can also register "hookcommand2", which you pass a callback:
NON_API: bool onAction(KbdSectionInfo *sec, int command, int val, int valhw, int relmode, HWND hwnd);
register("hookcommand2",onAction);
val/valhw are used for actions learned with MIDI/OSC.
* @param sec
* @param cmdId
* @param val val = [0..127] and valhw = -1 for MIDI CC,
* @param valhw valhw >=0 for MIDI pitch or OSC with value = (valhw|val<<7)/16383.0,
* @param relmode absolute(0) or 1/2/3 for relative adjust modes
* @param hwnd
* @return TRUE to eat (process) the command.
*/
bool LPE::onActionExecutedEx(KbdSectionInfo*, int cmdId, int val, int valhw, int relmode, HWND hwnd) {
return mActions.run(cmdId, val, valhw, relmode, hwnd);
}
/**
* Called when a menu is opened, you can add a custom menu entry
* @param menustr the identifier string of the menu, available strings:
* "Track control panel context"
* "Main toolbar"
* "Main extensions"
* @param menu the menu object on which you can add further menus
* @param flag 0 means new menu, 1 means menu was already created at least once
*/
void LPE::onMenuClicked(const char* menustr, HMENU menu, int flag) {
if (strcmp(menustr, "Main extensions") == 0 && flag == 0) {
//show LPE submenu
HMENU subMenu = CreatePopupMenu();
MENUITEMINFO mii{};
mii.fMask |= MIIM_TYPE | MIIM_ID | MIIM_SUBMENU;
mii.fType |= MFT_STRING;
mii.cbSize = sizeof(MENUITEMINFO);
std::string text = "LivePresets";
mii.dwTypeData = text.data();
mii.cch = text.size();
mii.hSubMenu = subMenu;
InsertMenuItem(menu, 0, true, &mii);
mii = MENUITEMINFO();
mii.cbSize = sizeof(MENUITEMINFO);
mii.fMask = MIIM_TYPE | MIIM_ID;
mii.fType = MFT_STRING;
text = "Presets";
mii.dwTypeData = text.data();
mii.cch = text.size();
mii.wID = NamedCommandLookup("_LPE_OPENTOGGLE_MAIN");
InsertMenuItem(subMenu, 0, true, &mii);
//show control menu only in ultimate version
if (Licensing_IsUltimate()) {
mii = MENUITEMINFO();
mii.cbSize = sizeof(MENUITEMINFO);
mii.fMask = MIIM_TYPE | MIIM_ID;
mii.fType = MFT_STRING;
text = "Control View";
mii.dwTypeData = text.data();
mii.cch = text.size();
mii.wID = NamedCommandLookup("_LPE_OPENTOGGLE_CONTROL");
InsertMenuItem(subMenu, 1, true, &mii);
}
//seperator
mii = MENUITEMINFO();
mii.cbSize = sizeof(MENUITEMINFO);
mii.fType = MFT_SEPARATOR;
InsertMenuItem(subMenu, 0, false, &mii);
//show about
mii = MENUITEMINFO();
mii.cbSize = sizeof(MENUITEMINFO);
mii.fMask = MIIM_TYPE | MIIM_ID;
mii.fType = MFT_STRING;
text = "About LPE";
mii.dwTypeData = text.data();
mii.cch = text.size();
mii.wID = NamedCommandLookup("_LPE_OPENTOGGLE_ABOUT");
InsertMenuItem(subMenu, GetMenuItemCount(subMenu), true, &mii);
}
if (strcmp(menustr, "Track control panel context") == 0 && flag == 0) {
HMENU subMenu = CreatePopupMenu();
MENUITEMINFO mii{};
mii.fMask |= MIIM_TYPE | MIIM_ID | MIIM_SUBMENU;
mii.fType |= MFT_STRING;
mii.cbSize = sizeof(MENUITEMINFO);
std::string text = "LivePresets";
mii.dwTypeData = text.data();
mii.cch = text.size();
mii.hSubMenu = subMenu;
InsertMenuItem(menu, GetMenuItemCount(menu), true, &mii);
MENUITEMINFO smii{};
smii.fMask |= MIIM_TYPE | MIIM_ID;
smii.fType |= MFT_STRING;
smii.cbSize = sizeof(MENUITEMINFO);
std::string subtext = "Save track settings to all presets";
smii.dwTypeData = subtext.data();
smii.cch = subtext.size();
smii.wID = NamedCommandLookup("_LPE_TRACKSAVEALL");
InsertMenuItem(subMenu, 0, true, &smii);
}
}
/**
* Creates a new preset
*/
void LPE::createPreset() {
mController.createPreset();
}
/**
* Updates the selected preset
*/
void LPE::updatePreset() {
mController.updateSelectedPreset();
}
/**
* Edits the selected preset
*/
void LPE::editPreset() {
mController.editSelectedPreset();
}
/**
* Removes the selected preset
*/
void LPE::removePresets() {
mController.removeSelectedPresets();
}
void LPE::showSettings() {
mController.showSettings();
}
/*
* Recall a preset by its GUID which is encoded in all 4 variables
*/
void LPE::recallPresetByGuid(int data1, int data2, int data3, HWND data4) {
mModel->recallPresetByGuid(IntsToGuid(data1, data2, data3, (long) data4));
}
/**
* Called when Reaper receives a command to call the action "LPE_SELECT"
* @param val val/valhw are used for actions learned with MIDI/OSC. val = [0..127] and valhw = -1 for MIDI CC,
* @param valhw valhw >=0 for MIDI pitch or OSC with value = (valhw|val<<7)/16383.0,
* @param relmode absolute(0) or 1/2/3 for relative adjust modes
* @param hwnd
*/
void LPE::onRecallPreset(int val, int valhw, int, HWND) {
if (valhw == -1) {
//MIDI CC value
mModel->recallByValue(val);
} else {
//OSC or MIDI pitch value
//calculate integer as float value (0-16383)
auto osc = (127 - val) * 128 + (128 - valhw);
if (osc == 16384) osc = 0;
mModel->recallByValue(osc);
}
}
/**
* Returns if there is a muted track shown in TCP
*/
bool LPE::isMutedShown() {
bool mutedShown = false;
for (int i = 0; i < GetNumTracks(); i++) {
MediaTrack* track = GetTrack(nullptr, i);
if (GetMediaTrackInfo_Value(track, B_MUTE) != 0) {
mutedShown = mutedShown || GetMediaTrackInfo_Value(track, B_SHOWINTCP) != 0;
}
}
return mutedShown;
}
/**
* Hide/Show muted tracks in TCP
*/
void LPE::toggleMutedTracksVisibility() {
//check if there are muted shown tracks, then hide them otherwise show all
bool mutedShown = isMutedShown();
for (int i = 0; i < GetNumTracks(); i++) {
MediaTrack* track = GetTrack(nullptr, i);
if (GetMediaTrackInfo_Value(track, B_MUTE) != 0) {
SetMediaTrackInfo_Value(track, B_SHOWINTCP, !mutedShown);
}
}
TrackList_AdjustWindows(true);
}
/**
* Saves the current track configs in all presets
*/
void LPE::onApplySelectedTrackConfigsToAllPresets() {
std::vector<MediaTrack*> selectedTracks;
int trackCount = CountSelectedTracks(nullptr);
selectedTracks.reserve(trackCount);
for (int i = 0; i < trackCount; i++) {
selectedTracks.push_back(GetSelectedTrack(nullptr, i));
}
mModel->onApplySelectedTrackConfigsToAllPresets(selectedTracks);
}
void LPE::toggleMainWindow() {
mController.toggleVisibility();
}
void LPE::toggleControlView() {
ControlViewController_ToggleVisibility(&mControlView);
}
void LPE::toggleAboutWindow() {
mAboutController.toggleVisibility();
}
/***********************************************************************************************************************
* State functions
**********************************************************************************************************************/
/*
* Change the current project
*/
void LPE::onProjectChanged(ReaProject *proj) {
mProject = proj;
mModel = &mModels[proj];
mController.reset();
ControlViewController_Reset(&mControlView);
}
/*
* Extension data is read here. Is also called on Undo/Redo to get an old persisted state
*/
bool LPE::recallState(ProjectStateContext* ctx, bool) {
// Go through all lines until the src part ends
char buf[4096];
LineParser lp;
while (!ctx->GetLine(buf, sizeof(buf)) && !lp.parse(buf)) {
// objects start with <OBJECTNAME
auto *proj = GetCurrentProjectInLoadSave();
const auto *token = lp.gettoken_str(0);
if (strcmp(token, "<LIVEPRESETSMODEL") == 0) {
mModels[proj] = LivePresetsModel(ctx);
}
// data finished on >
if (strcmp(buf, ">") == 0)
break;
}
//Update ui after loading data or returning to persisted state via undo/redo
if (mController.mList) {
auto adapter = std::make_unique<LivePresetsListAdapter>(&mModel->mPresets);
mController.mList->setAdapter(move(adapter));
}
return true;
}
void LPE::saveState(ProjectStateContext* ctx, bool) {
auto *proj = GetCurrentProjectInLoadSave();
WDL_FastString chunk;
mModels[proj].persist(chunk);
std::string out;
std::istringstream ss(chunk.Get());
while (getline(ss, out)) {
ctx->AddLine("%s", out.data());
}
}
void LPE::resetState(bool) {
//cleaning data from model
auto *proj = GetCurrentProjectInLoadSave();
mModels[proj].reset();
//cleaning data from ui
mController.reset();
ControlViewController_Reset(&mControlView);
}
| 31.208238
| 120
| 0.628025
|
Burtan
|
ceefe13672448d3d24143c5737dc2e9cdcda244b
| 814
|
cpp
|
C++
|
binarysearch.io/medium/All-Sublists-Sum.cpp
|
wingkwong/competitive-programming
|
e8bf7aa32e87b3a020b63acac20e740728764649
|
[
"MIT"
] | 18
|
2020-08-27T05:27:50.000Z
|
2022-03-08T02:56:48.000Z
|
binarysearch.io/medium/All-Sublists-Sum.cpp
|
wingkwong/competitive-programming
|
e8bf7aa32e87b3a020b63acac20e740728764649
|
[
"MIT"
] | null | null | null |
binarysearch.io/medium/All-Sublists-Sum.cpp
|
wingkwong/competitive-programming
|
e8bf7aa32e87b3a020b63acac20e740728764649
|
[
"MIT"
] | 1
|
2020-10-13T05:23:58.000Z
|
2020-10-13T05:23:58.000Z
|
/*
All Sublists Sum
https://binarysearch.io/problems/All-Sublists-Sum
Given a list of integers nums, consider every contiguous sublist. Sum each of these sublists and return the sum of all these values. Mod the result by 10 ** 9 + 7.
Constraints
Length of nums is at most 5000.
Example 1
Input
nums = [2, 3, 5]
Output
33
Explanation
We have the following subarrays:
[2]
[3]
[5]
[2, 3]
[3, 5]
[2, 3, 5]
The sum of all of these is 33.
*/
#include "solution.hpp"
using namespace std;
typedef long long ll;
class Solution {
public:
int solve(vector<int>& nums) {
// (n-i)+(n-i)*i
// (n-i)(i+1)
int n = (int)nums.size();
ll ans=0, MOD=1e9+7;;
for(int i=0;i<n;i++){
ans=(ans+(nums[i]*(ll)(i+1)*(ll)(n-i)))%MOD;
}
return ans;
}
};
| 16.958333
| 163
| 0.594595
|
wingkwong
|
300083e191105ac9064acaf34b70d1a7bb193e25
| 236,031
|
cpp
|
C++
|
src/currency_core/blockchain_storage.cpp
|
Virie/Virie
|
fc5ad5816678b06b88d08a6842e43d4205915b39
|
[
"MIT"
] | 1
|
2021-03-07T13:26:43.000Z
|
2021-03-07T13:26:43.000Z
|
src/currency_core/blockchain_storage.cpp
|
Virie/Virie
|
fc5ad5816678b06b88d08a6842e43d4205915b39
|
[
"MIT"
] | null | null | null |
src/currency_core/blockchain_storage.cpp
|
Virie/Virie
|
fc5ad5816678b06b88d08a6842e43d4205915b39
|
[
"MIT"
] | null | null | null |
// Copyright (c) 2014-2020 The Virie Project
// Copyright (c) 2012-2013 The Cryptonote developers
// Copyright (c) 2012-2013 The Boolberry developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <set>
#include <algorithm>
#include <cstdio>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/algorithm/string/replace.hpp>
#include "include_base_utils.h"
#include "common/db_backend_lmdb.h"
#include "common/command_line.h"
#include "blockchain_storage.h"
#include "currency_format_utils.h"
#include "currency_boost_serialization.h"
#include "currency_core/currency_config.h"
#include "miner.h"
#include "misc_language.h"
#include "profile_tools.h"
#include "file_io_utils.h"
#include "common/boost_serialization_helper.h"
#include "warnings.h"
#include "crypto/hash.h"
#include "miner_common.h"
#include "storages/portable_storage_template_helper.h"
#include "common/db_backend_lmdb.h"
#include "common/container_utils.h"
#include "version.h"
#undef LOG_DEFAULT_CHANNEL
#define LOG_DEFAULT_CHANNEL "core"
ENABLE_CHANNEL_BY_DEFAULT("core", "Currency core default channel.")
using namespace std;
using namespace epee;
using namespace currency;
#define BLOCKCHAIN_STORAGE_CONTAINER_BLOCKS "blocks"
#define BLOCKCHAIN_STORAGE_CONTAINER_BLOCKS_INDEX "blocks_index"
#define BLOCKCHAIN_STORAGE_CONTAINER_TRANSACTIONS "transactions"
#define BLOCKCHAIN_STORAGE_CONTAINER_SPENT_KEYS "spent_keys"
#define BLOCKCHAIN_STORAGE_CONTAINER_OUTPUTS "outputs"
#define BLOCKCHAIN_STORAGE_CONTAINER_MULTISIG_OUTS "multisig_outs"
#define BLOCKCHAIN_STORAGE_CONTAINER_INVALID_BLOCKS "invalid_blocks"
#define BLOCKCHAIN_STORAGE_CONTAINER_SOLO_OPTIONS "solo"
#define BLOCKCHAIN_STORAGE_CONTAINER_ALIASES "aliases"
#define BLOCKCHAIN_STORAGE_CONTAINER_ADDR_TO_ALIAS "addr_to_alias"
#define BLOCKCHAIN_STORAGE_CONTAINER_TX_FEE_MEDIAN "median_fee2"
#define BLOCKCHAIN_STORAGE_CONTAINER_GINDEX_INCS "gindex_increments"
#define BLOCKCHAIN_STORAGE_OPTIONS_ID_CURRENT_BLOCK_CUMUL_SZ_LIMIT 0
#define BLOCKCHAIN_STORAGE_OPTIONS_ID_CURRENT_PRUNED_RS_HEIGHT 1
#define BLOCKCHAIN_STORAGE_OPTIONS_ID_LAST_WORKED_VERSION 2
#define BLOCKCHAIN_STORAGE_OPTIONS_ID_STORAGE_MAJOR_COMPATIBILITY_VERSION 3 //mismatch here means full resync
#define BLOCKCHAIN_STORAGE_OPTIONS_ID_STORAGE_MINOR_COMPATIBILITY_VERSION 4 //mismatch here means some reinitializations
DISABLE_VS_WARNINGS(4267)
namespace
{
const command_line::arg_descriptor<uint32_t> arg_db_cache_l1 = { "db_cache_l1", "Specify size of memory mapped db cache file", 0, command_line::flag_t::not_use_default };
const command_line::arg_descriptor<uint32_t> arg_db_cache_l2 = { "db_cache_l2", "Specify cached elements in db helpers", 0, command_line::flag_t::not_use_default };
}
//------------------------------------------------------------------
blockchain_storage::blockchain_storage(tx_memory_pool& tx_pool) :m_tx_pool(tx_pool),
m_services_mgr(nullptr),
m_read_lock(m_rw_lock),
m_db(std::shared_ptr<tools::db::i_db_backend>(new tools::db::lmdb_db_backend), m_rw_lock),
m_db_blocks(m_db),
m_db_blocks_index(m_db),
m_db_transactions(m_db),
m_db_spent_keys(m_db),
m_db_solo_options(m_db),
m_db_current_block_cumul_sz_limit(BLOCKCHAIN_STORAGE_OPTIONS_ID_CURRENT_BLOCK_CUMUL_SZ_LIMIT, m_db_solo_options),
m_db_current_pruned_rs_height(BLOCKCHAIN_STORAGE_OPTIONS_ID_CURRENT_PRUNED_RS_HEIGHT, m_db_solo_options),
m_db_last_worked_version(BLOCKCHAIN_STORAGE_OPTIONS_ID_LAST_WORKED_VERSION, m_db_solo_options),
m_db_storage_major_compatibility_version(BLOCKCHAIN_STORAGE_OPTIONS_ID_STORAGE_MAJOR_COMPATIBILITY_VERSION, m_db_solo_options),
m_db_storage_minor_compatibility_version(BLOCKCHAIN_STORAGE_OPTIONS_ID_STORAGE_MINOR_COMPATIBILITY_VERSION, m_db_solo_options),
m_db_outputs(m_db),
m_db_multisig_outs(m_db),
m_db_aliases(m_db),
m_db_addr_to_alias(m_db),
m_db_per_block_gindex_incs(m_db),
m_is_in_checkpoint_zone(false),
m_is_blockchain_storing(false),
m_core_runtime_config(get_default_core_runtime_config()),
//m_bei_stub(AUTO_VAL_INIT(m_bei_stub)),
m_interprocess_locker_file(0),
m_diff_cache(),
m_current_fee_median(0),
m_current_fee_median_effective_index(0)
{
m_services_mgr.set_core_runtime_config(m_core_runtime_config);
m_services_mgr.set_event_handler(get_event_handler());
m_performance_data.epic_failure_happend = false;
}
//------------------------------------------------------------------
bool blockchain_storage::have_tx(const crypto::hash &id) const
{
CRITICAL_REGION_LOCAL(m_read_lock);
return m_db_transactions.find(id) != m_db_transactions.end();
}
//------------------------------------------------------------------
bool blockchain_storage::have_tx_keyimg_as_spent(const crypto::key_image &key_im, uint64_t before_height /* = UINT64_MAX */) const
{
CRITICAL_REGION_LOCAL(m_read_lock);
auto it_ptr = m_db_spent_keys.get(key_im);
if (!it_ptr)
return false;
return *it_ptr < before_height;
}
//------------------------------------------------------------------
std::shared_ptr<transaction> blockchain_storage::get_tx(const crypto::hash &id) const
{
CRITICAL_REGION_LOCAL(m_read_lock);
auto it = m_db_transactions.find(id);
if (it == m_db_transactions.end())
return std::shared_ptr<transaction>(nullptr);
return std::make_shared<transaction>(it->tx);
}
//------------------------------------------------------------------
void blockchain_storage::init_options(boost::program_options::options_description& desc)
{
command_line::add_arg(desc, arg_db_cache_l1);
command_line::add_arg(desc, arg_db_cache_l2);
}
//------------------------------------------------------------------
uint64_t blockchain_storage::get_block_h_older_then(uint64_t timestamp) const
{
// get avarage block position
uint64_t last_block_timestamp = m_db_blocks.back()->bl.timestamp;
if (timestamp >= last_block_timestamp)
return get_top_block_height();
uint64_t difference = last_block_timestamp - timestamp;
uint64_t n_blocks = difference / (DIFFICULTY_TOTAL_TARGET);
if (n_blocks >= get_top_block_height())
return 0;
uint64_t index = get_top_block_height() - n_blocks;
while (true)
{
if (index == 0)
return 0;
if (m_db_blocks[index]->bl.timestamp < timestamp)
return index;
index--;
}
return 0;
}
//------------------------------------------------------------------
uint64_t blockchain_storage::get_current_blockchain_size() const
{
CRITICAL_REGION_LOCAL(m_read_lock);
return m_db_blocks.size();
}
//------------------------------------------------------------------
uint64_t blockchain_storage::get_top_block_height() const
{
CRITICAL_REGION_LOCAL(m_read_lock);
return m_db_blocks.size() - 1;
}
//------------------------------------------------------------------
bool blockchain_storage::validate_instance(const std::string& path)
{
std::string locker_name = path + "/" + std::string(CURRENCY_CORE_INSTANCE_LOCK_FILE);
bool r = epee::file_io_utils::open_and_lock_file(locker_name, m_interprocess_locker_file);
if (r)
return true;
else
{
LOG_ERROR("Failed to initialize db: some other instance is already running");
return false;
}
}
//------------------------------------------------------------------
bool blockchain_storage::init(const std::string& config_folder, const boost::program_options::variables_map& vm)
{
// CRITICAL_REGION_LOCAL(m_read_lock);
if (!validate_instance(config_folder))
{
LOG_ERROR("Failed to initialize instance");
return false;
}
uint64_t cache_size = CACHE_SIZE;
if (command_line::has_arg(vm, arg_db_cache_l1))
{
cache_size = command_line::get_arg(vm, arg_db_cache_l1);
}
LOG_PRINT_GREEN("Using db file cache size(L1): " << cache_size, LOG_LEVEL_0);
m_config_folder = config_folder;
LOG_PRINT_L0("Loading blockchain...");
const std::string folder_name = m_config_folder + "/" CURRENCY_BLOCKCHAINDATA_FOLDERNAME;
tools::create_directories_if_necessary(folder_name);
bool res = m_db.open(folder_name, cache_size);
CHECK_AND_ASSERT_MES(res, false, "Failed to initialize database in folder: " << folder_name);
res = m_db_blocks.init(BLOCKCHAIN_STORAGE_CONTAINER_BLOCKS);
CHECK_AND_ASSERT_MES(res, false, "Unable to init db container");
res = m_db_blocks_index.init(BLOCKCHAIN_STORAGE_CONTAINER_BLOCKS_INDEX);
CHECK_AND_ASSERT_MES(res, false, "Unable to init db container");
res = m_db_transactions.init(BLOCKCHAIN_STORAGE_CONTAINER_TRANSACTIONS);
CHECK_AND_ASSERT_MES(res, false, "Unable to init db container");
res = m_db_spent_keys.init(BLOCKCHAIN_STORAGE_CONTAINER_SPENT_KEYS);
CHECK_AND_ASSERT_MES(res, false, "Unable to init db container");
res = m_db_outputs.init(BLOCKCHAIN_STORAGE_CONTAINER_OUTPUTS);
CHECK_AND_ASSERT_MES(res, false, "Unable to init db container");
res = m_db_multisig_outs.init(BLOCKCHAIN_STORAGE_CONTAINER_MULTISIG_OUTS);
CHECK_AND_ASSERT_MES(res, false, "Unable to init db container");
res = m_db_solo_options.init(BLOCKCHAIN_STORAGE_CONTAINER_SOLO_OPTIONS);
CHECK_AND_ASSERT_MES(res, false, "Unable to init db container");
res = m_db_aliases.init(BLOCKCHAIN_STORAGE_CONTAINER_ALIASES);
CHECK_AND_ASSERT_MES(res, false, "Unable to init db container");
res = m_db_addr_to_alias.init(BLOCKCHAIN_STORAGE_CONTAINER_ADDR_TO_ALIAS);
CHECK_AND_ASSERT_MES(res, false, "Unable to init db container");
res = m_db_per_block_gindex_incs.init(BLOCKCHAIN_STORAGE_CONTAINER_GINDEX_INCS);
CHECK_AND_ASSERT_MES(res, false, "Unable to init db container");
if (command_line::has_arg(vm, arg_db_cache_l2))
{
uint64_t cache_size = command_line::get_arg(vm, arg_db_cache_l2);
LOG_PRINT_GREEN("Using db items cache size(L2): " << cache_size, LOG_LEVEL_0);
m_db_blocks_index.set_cache_size(cache_size);
m_db_blocks.set_cache_size(cache_size);
m_db_blocks_index.set_cache_size(cache_size);
m_db_transactions.set_cache_size(cache_size);
m_db_spent_keys.set_cache_size(cache_size);
//m_db_outputs.set_cache_size(cache_size);
m_db_multisig_outs.set_cache_size(cache_size);
m_db_solo_options.set_cache_size(cache_size);
m_db_aliases.set_cache_size(cache_size);
m_db_addr_to_alias.set_cache_size(cache_size);
}
bool need_reinit = false;
bool need_reinit_medians = false;
if (!m_db_blocks.size())
{
need_reinit = true;
}
else if (m_db_storage_major_compatibility_version != BLOCKCHAIN_STORAGE_MAJOR_COMPATIBILITY_VERSION)
{
need_reinit = true;
LOG_PRINT_MAGENTA("DB storage needs reinit because it has major compatibility ver " << m_db_storage_major_compatibility_version << ", expected : " << BLOCKCHAIN_STORAGE_MAJOR_COMPATIBILITY_VERSION, LOG_LEVEL_0);
}
else if (m_db_storage_minor_compatibility_version != BLOCKCHAIN_STORAGE_MINOR_COMPATIBILITY_VERSION)
{
if (m_db_storage_minor_compatibility_version < 1)
need_reinit_medians = true;
}
if (need_reinit)
{
clear();
block bl = boost::value_initialized<block>();
block_verification_context bvc = boost::value_initialized<block_verification_context>();
generate_genesis_block(bl);
add_new_block(bl, bvc);
CHECK_AND_ASSERT_MES(!bvc.m_verification_failed, false, "Failed to add genesis block to blockchain");
LOG_PRINT_MAGENTA("Storage initialized with genesis", LOG_LEVEL_0);
}
if (need_reinit_medians)
{
bool r = rebuild_tx_fee_medians();
CHECK_AND_ASSERT_MES(r, false, "failed to rebuild_tx_fee_medians()");
}
initialize_db_solo_options_values();
m_services_mgr.init(config_folder, vm);
//print information message
uint64_t timestamp_diff = m_core_runtime_config.get_core_time() - m_db_blocks.back()->bl.timestamp;
if(!m_db_blocks.back()->bl.timestamp)
timestamp_diff = m_core_runtime_config.get_core_time() - 1341378000;
LOG_PRINT_GREEN("Blockchain initialized. (v:" << m_db_storage_major_compatibility_version << ") last block: " << m_db_blocks.size() - 1 << ENDL
<< "genesis: " << get_block_hash(m_db_blocks[0]->bl) << ENDL
<< "last block: " << m_db_blocks.size() - 1 << ", " << misc_utils::get_time_interval_string(timestamp_diff) << " time ago" << ENDL
<< "current pos difficulty: " << get_next_diff_conditional(true) << ENDL
<< "current pow difficulty: " << get_next_diff_conditional(false) << ENDL
<< "total tansactions: " << m_db_transactions.size(),
LOG_LEVEL_0);
return true;
}
//------------------------------------------------------------------
void blockchain_storage::initialize_db_solo_options_values()
{
transaction_region tr(m_db, transaction_region::event_t::commit);
CHECK_AND_ASSERT_MES(tr, , "failed to begin_transaction");
m_db_storage_major_compatibility_version = BLOCKCHAIN_STORAGE_MAJOR_COMPATIBILITY_VERSION;
m_db_storage_minor_compatibility_version = BLOCKCHAIN_STORAGE_MINOR_COMPATIBILITY_VERSION;
m_db_last_worked_version = std::string(PROJECT_VERSION_LONG);
}
//------------------------------------------------------------------
bool blockchain_storage::deinit()
{
bool r = true;
if (!m_db.close())
r = false;
if (!epee::file_io_utils::unlock_and_close_file(m_interprocess_locker_file))
r = false;
return r;
}
//------------------------------------------------------------------
bool blockchain_storage::pop_block_from_blockchain(bool add_txs_to_pool)
{
CRITICAL_REGION_LOCAL(m_read_lock);
CHECK_AND_ASSERT_MES(m_db_blocks.size() > 1, false, "pop_block_from_blockchain: can't pop from blockchain with size = " << m_db_blocks.size());
size_t h = m_db_blocks.size()-1;
auto bei_ptr = m_db_blocks[h];
CHECK_AND_ASSERT_MES(bei_ptr.get(), false, "pop_block_from_blockchain: can't pop from blockchain");
uint64_t fee_total = 0;
bool r = purge_block_data_from_blockchain(bei_ptr->bl, bei_ptr->bl.tx_hashes.size(), fee_total, add_txs_to_pool);
CHECK_AND_ASSERT_MES(r, false, "Failed to purge_block_data_from_blockchain for block " << get_block_hash(bei_ptr->bl) << " on height " << h);
pop_block_from_per_block_increments(bei_ptr->height);
//remove from index
r = m_db_blocks_index.erase_validate(get_block_hash(bei_ptr->bl));
CHECK_AND_ASSERT_MES_NO_RET(r, "pop_block_from_blockchain: block id not found in m_blocks_index while trying to delete it");
//pop block from core
m_db_blocks.pop_back();
on_block_removed(*bei_ptr);
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::set_checkpoints(checkpoints&& chk_pts)
{
m_checkpoints = chk_pts;
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::validate_checkpoints(uint64_t &valid_blockchain_size)
{
auto get_block_hash_func = [this] (uint64_t height) -> crypto::hash {
return get_block_id_by_height(height);
};
try
{
transaction_region tr(m_db);
CHECK_AND_ASSERT_MES(tr, false, "failed to begin_transaction");
if (m_db_blocks.size() < m_checkpoints.get_top_checkpoint_height())
m_is_in_checkpoint_zone = true;
prune_ring_signatures_and_attachments_if_need();
tr.will_commit();
}
catch (const std::exception& ex)
{
LOG_ERROR("UNKNOWN EXCEPTION WHILE PRUNE RING SIGNATURES AND ATTACHMENTS: " << ex.what());
}
catch (...)
{
LOG_ERROR("UNKNOWN EXCEPTION WHILE PRUNE RING SIGNATURES AND ATTACHMENTS.");
}
return m_checkpoints.check_blocks(get_block_hash_func, get_top_block_height(), valid_blockchain_size);
}
//------------------------------------------------------------------
bool blockchain_storage::prune_ring_signatures_and_attachments(uint64_t height, uint64_t& transactions_pruned, uint64_t& signatures_pruned, uint64_t& attachments_pruned)
{
CRITICAL_REGION_LOCAL(m_read_lock);
CHECK_AND_ASSERT_MES(height < m_db_blocks.size(), false, "prune_ring_signatures called with wrong parameter: " << height << ", m_blocks.size() " << m_db_blocks.size());
auto vptr = m_db_blocks[height];
CHECK_AND_ASSERT_MES(vptr.get(), false, "Failed to get block on height");
for (const auto& h : vptr->bl.tx_hashes)
{
auto it = m_db_transactions.find(h);
CHECK_AND_ASSERT_MES(it != m_db_transactions.end(), false, "failed to find transaction " << h << " in blockchain index, in block on height = " << height);
CHECK_AND_ASSERT_MES(it->m_keeper_block_height == height, false,
"failed to validate extra check, it->second.m_keeper_block_height = " << it->m_keeper_block_height <<
"is mot equal to height = " << height << " in blockchain index, for block on height = " << height);
transaction_chain_entry lolcal_chain_entry = *it;
signatures_pruned += lolcal_chain_entry.tx.signatures.size();
attachments_pruned += lolcal_chain_entry.tx.attachment.size();
lolcal_chain_entry.tx.signatures.clear();
lolcal_chain_entry.tx.attachment.clear();
//reassign to db
if (!m_db_transactions.set(h, lolcal_chain_entry))
LOG_ERROR("failed to m_db_transactions.set");
++transactions_pruned;
}
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::prune_ring_signatures_and_attachments_if_need()
{
CRITICAL_REGION_LOCAL(m_read_lock);
if(m_db_blocks.size() && m_checkpoints.get_top_checkpoint_height() && m_checkpoints.get_top_checkpoint_height() > m_db_current_pruned_rs_height)
{
LOG_PRINT_CYAN("Starting pruning ring signatues and attachments...", LOG_LEVEL_0);
uint64_t tx_count = 0, sig_count = 0, attach_count = 0;
for(uint64_t height = m_db_current_pruned_rs_height; height < m_db_blocks.size() && height <= m_checkpoints.get_top_checkpoint_height(); height++)
{
bool res = prune_ring_signatures_and_attachments(height, tx_count, sig_count, attach_count);
CHECK_AND_ASSERT_MES(res, false, "failed to prune_ring_signatures_and_attachments for height = " << height);
}
m_db_current_pruned_rs_height = m_checkpoints.get_top_checkpoint_height();
LOG_PRINT_CYAN("Transaction pruning finished: " << sig_count << " signatures and " << attach_count << " attachments released in " << tx_count << " transactions.", LOG_LEVEL_0);
}
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::clear()
{
//CRITICAL_REGION_LOCAL(m_read_lock);
transaction_region tr(m_db, transaction_region::event_t::abort, [this] () { m_diff_cache.reset(); });
CHECK_AND_ASSERT_MES(tr, false, "failed to begin_transaction");
m_db_blocks.clear();
m_db_blocks_index.clear();
m_db_transactions.clear();
m_db_spent_keys.clear();
m_db_solo_options.clear();
initialize_db_solo_options_values();
m_db_outputs.clear();
m_db_multisig_outs.clear();
m_db_aliases.clear();
m_db_addr_to_alias.clear();
m_db_per_block_gindex_incs.clear();
tr.will_commit();
{
CRITICAL_REGION_LOCAL(m_invalid_blocks_lock);
m_invalid_blocks.clear(); // crypto::hash -> block_extended_info
}
{
CRITICAL_REGION_LOCAL(m_alternative_chains_lock);
m_alternative_chains.clear();
m_altblocks_keyimages.clear();
m_alternative_chains_txs.clear();
}
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::reset_and_set_genesis_block(const block& b)
{
clear();
block_verification_context bvc = boost::value_initialized<block_verification_context>();
auto r = add_new_block(b, bvc);
if(!r || bvc.m_verification_failed)
{
LOG_ERROR("Blockchain reset failed.");
return false;
}
LOG_PRINT_GREEN("Blockchain reset. Genesis block: " << get_block_hash(b) << ", " << misc_utils::get_time_interval_string(m_core_runtime_config.get_core_time() - b.timestamp) << " ago", LOG_LEVEL_0);
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::purge_transaction_keyimages_from_blockchain(const transaction& tx, bool strict_check)
{
CRITICAL_REGION_LOCAL(m_read_lock);
struct purge_transaction_visitor: public boost::static_visitor<bool>
{
blockchain_storage& m_bcs;
key_images_container& m_spent_keys;
bool m_strict_check;
purge_transaction_visitor(blockchain_storage& bcs, key_images_container& spent_keys, bool strict_check):
m_bcs(bcs),
m_spent_keys(spent_keys),
m_strict_check(strict_check){}
bool operator()(const txin_to_key& inp) const
{
bool r = m_spent_keys.erase_validate(inp.k_image);
CHECK_AND_ASSERT_MES( !(!r && m_strict_check), false, "purge_transaction_keyimages_from_blockchain: key image " << inp.k_image << " was not found");
if(inp.key_offsets.size() == 1)
{
//direct spend detected
if(!m_bcs.update_spent_tx_flags_for_input(inp.amount, inp.key_offsets[0], false))
{
//internal error
LOG_PRINT_L0("Failed to update_spent_tx_flags_for_input");
return false;
}
}
return true;
}
bool operator()(const txin_gen& inp) const
{
return true;
}
bool operator()(const txin_multisig& inp) const
{
if (!m_bcs.update_spent_tx_flags_for_input(inp.multisig_out_id, 0))
{
LOG_PRINT_L0("update_spent_tx_flags_for_input failed for multisig id " << inp.multisig_out_id << " amount: " << inp.amount);
return false;
}
return true;
}
};
BOOST_FOREACH(const txin_v& in, tx.vin)
{
bool r = boost::apply_visitor(purge_transaction_visitor(*this, m_db_spent_keys, strict_check), in);
CHECK_AND_ASSERT_MES(!strict_check || r, false, "failed to process purge_transaction_visitor");
}
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::purge_transaction_from_blockchain(const crypto::hash& tx_id, uint64_t& fee, bool add_to_pool)
{
fee = 0;
CRITICAL_REGION_LOCAL(m_read_lock);
auto tx_res_ptr = m_db_transactions.find(tx_id);
CHECK_AND_ASSERT_MES(tx_res_ptr != m_db_transactions.end(), false, "transaction " << tx_id << " is not found in blockchain index!!");
const transaction& tx = tx_res_ptr->tx;
fee = get_tx_fee(tx_res_ptr->tx);
auto r = purge_transaction_keyimages_from_blockchain(tx, true);
CHECK_AND_ASSERT_MES(r, false, "failed to purge_transaction_keyimages_from_blockchain for tx" << tx_id);
r = unprocess_blockchain_tx_extra(tx);
CHECK_AND_ASSERT_MES(r, false, "failed to unprocess_blockchain_tx_extra for tx " << tx_id);
r = unprocess_blockchain_tx_attachments(tx, get_current_blockchain_size(), 0/*TODO: add valid timestamp here in future if need*/);
CHECK_AND_ASSERT_MES(r, false, "failed to unprocess_blockchain_tx_attachments for tx " << tx_id);
bool added_to_the_pool = false;
if (add_to_pool && !is_coinbase(tx))
{
currency::tx_verification_context tvc = AUTO_VAL_INIT(tvc);
added_to_the_pool = m_tx_pool.add_tx(tx, 0, tvc, true, true); // don't check min fee because form the chain
CHECK_AND_ASSERT_MES(added_to_the_pool, false, "failed to add transaction " << tx_id << " to transaction pool");
}
bool res = pop_transaction_from_global_index(tx, tx_id);
CHECK_AND_ASSERT_MES_NO_RET(res, "pop_transaction_from_global_index failed for tx " << tx_id);
bool res_erase = m_db_transactions.erase_validate(tx_id);
CHECK_AND_ASSERT_MES_NO_RET(res_erase, "Failed to m_transactions.erase with id = " << tx_id);
LOG_PRINT_L1("transaction " << tx_id << (added_to_the_pool ? " was removed from blockchain history -> to the pool" : " was removed from blockchain history"));
return res;
}
//------------------------------------------------------------------
bool blockchain_storage::purge_block_data_from_blockchain(const block& b, size_t processed_tx_count)
{
uint64_t total_fee = 0;
return purge_block_data_from_blockchain(b, processed_tx_count, total_fee);
}
//------------------------------------------------------------------
bool blockchain_storage::purge_block_data_from_blockchain(const block& bl, size_t processed_tx_count, uint64_t& fee_total, bool add_txs_to_pool)
{
CRITICAL_REGION_LOCAL(m_read_lock);
fee_total = 0;
uint64_t fee = 0;
bool res = true;
CHECK_AND_ASSERT_MES(processed_tx_count <= bl.tx_hashes.size(), false, "wrong processed_tx_count in purge_block_data_from_blockchain");
for(size_t count = 0; count != processed_tx_count; count++)
{
res = purge_transaction_from_blockchain(bl.tx_hashes[(processed_tx_count -1)- count], fee, add_txs_to_pool) && res;
fee_total += fee;
}
res = purge_transaction_from_blockchain(get_transaction_hash(bl.miner_tx), fee) && res;
return res;
}
//------------------------------------------------------------------
crypto::hash blockchain_storage::get_top_block_id(uint64_t& height) const
{
CRITICAL_REGION_LOCAL(m_read_lock);
height = get_top_block_height();
return get_top_block_id();
}
//------------------------------------------------------------------
crypto::hash blockchain_storage::get_top_block_id() const
{
CRITICAL_REGION_LOCAL(m_read_lock);
crypto::hash id = null_hash;
if(m_db_blocks.size())
{
auto val_ptr = m_db_blocks.back();
CHECK_AND_ASSERT_MES(val_ptr, null_hash, "m_blocks.back() returned null");
get_block_hash(val_ptr->bl, id);
}
return id;
}
//------------------------------------------------------------------
bool blockchain_storage::get_top_block(block& b) const
{
CRITICAL_REGION_LOCAL(m_read_lock);
CHECK_AND_ASSERT_MES(m_db_blocks.size(), false, "Wrong blockchain state, m_blocks.size()=0!");
auto val_ptr = m_db_blocks.back();
CHECK_AND_ASSERT_MES(val_ptr.get(), false, "m_blocks.back() returned null");
b = val_ptr->bl;
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::get_short_chain_history(std::list<crypto::hash>& ids)const
{
CRITICAL_REGION_LOCAL(m_read_lock);
tools::container_utils::get_short_chain_history<10>(m_db_blocks, ids, [](const typename blocks_container::shared_value_type& e) -> crypto::hash
{
return currency::get_block_hash(e->bl);
});
return true;
}
//------------------------------------------------------------------
crypto::hash blockchain_storage::get_block_id_by_height(uint64_t height) const
{
CRITICAL_REGION_LOCAL(m_read_lock);
if(height >= m_db_blocks.size())
return null_hash;
return get_block_hash(m_db_blocks[height]->bl);
}
//------------------------------------------------------------------
bool blockchain_storage::get_block_by_hash(const crypto::hash &bl_id, block &blk) const
{
CRITICAL_REGION_LOCAL(m_read_lock);
// try to find block in main chain
uint64_t height = 0;
if (checked_get_height_by_id(bl_id, height))
{
blk = m_db_blocks[height]->bl;
return true;
}
// try to find block in alternative chain
CRITICAL_REGION_LOCAL1(m_alternative_chains_lock);
auto it_alt = m_alternative_chains.find(bl_id);
if (m_alternative_chains.end() != it_alt)
{
blk = it_alt->second.bl;
return true;
}
return false;
}
bool blockchain_storage::is_tx_related_to_altblock(crypto::hash tx_id) const
{
CRITICAL_REGION_LOCAL1(m_alternative_chains_lock);
auto it = m_alternative_chains_txs.find(tx_id);
return it != m_alternative_chains_txs.end();
}
//------------------------------------------------------------------
bool blockchain_storage::get_block_extended_info_by_hash(const crypto::hash &bl_id, block_extended_info &blk) const
{
CRITICAL_REGION_LOCAL(m_read_lock);
// try to find block in main chain
uint64_t height = 0;
if (checked_get_height_by_id(bl_id, height))
{
return get_block_extended_info_by_height(height, blk);
}
// try to find block in alternative chain
CRITICAL_REGION_LOCAL1(m_alternative_chains_lock);
auto it_alt = m_alternative_chains.find(bl_id);
if (m_alternative_chains.end() != it_alt)
{
blk = it_alt->second;
return true;
}
return false;
}
//------------------------------------------------------------------
bool blockchain_storage::get_block_extended_info_by_height(uint64_t h, block_extended_info &blk) const
{
CRITICAL_REGION_LOCAL(m_read_lock);
if (h >= m_db_blocks.size())
return false;
blk = *m_db_blocks[h];
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::get_block_by_height(uint64_t h, block &blk) const
{
CRITICAL_REGION_LOCAL(m_read_lock);
if(h >= m_db_blocks.size() )
return false;
blk = m_db_blocks[h]->bl;
return true;
}
//------------------------------------------------------------------
// void blockchain_storage::get_all_known_block_ids(std::list<crypto::hash> &main, std::list<crypto::hash> &alt, std::list<crypto::hash> &invalid) const
// {
// CRITICAL_REGION_LOCAL(m_blockchain_lock);
//
// for (auto &v : m_blocks_index)
// main.push_back(v.first);
//
// for (auto &v : m_alternative_chains)
// alt.push_back(v.first);
//
// for(auto &v: m_invalid_blocks)
// invalid.push_back(v.first);
// }
//------------------------------------------------------------------
bool blockchain_storage::rollback_blockchain_switching_old(std::list<block>& original_chain, size_t rollback_height)
{
CRITICAL_REGION_LOCAL(m_read_lock);
//remove failed subchain
for (size_t i = m_db_blocks.size() - 1; i >= rollback_height; i--)
{
bool r = pop_block_from_blockchain();
CHECK_AND_ASSERT_MES(r, false, "PANIC!!! failed to remove block while chain switching during the rollback!");
}
//return back original chain
BOOST_FOREACH(auto& bl, original_chain)
{
block_verification_context bvc = boost::value_initialized<block_verification_context>();
bool r = handle_block_to_main_chain(bl, bvc);
CHECK_AND_ASSERT_MES(r && bvc.m_added_to_main_chain, false, "PANIC!!! failed to add (again) block while chain switching during the rollback!");
}
LOG_PRINT_L0("Rollback success.");
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::rollback_blockchain_switching(size_t rollback_height)
{
CRITICAL_REGION_LOCAL(m_read_lock);
for (size_t i = m_db_blocks.size() - 1; i >= rollback_height; i--)
{
auto &b = m_db_blocks[i]->bl;
for (auto &tx_id : b.tx_hashes)
{
auto tx_res_ptr = m_db_transactions.find(tx_id);
CHECK_AND_ASSERT_MES(tx_res_ptr != m_db_transactions.end(), false, "transaction " << tx_id << " is not found in blockchain index!!");
auto &tx = tx_res_ptr->tx;
if (is_coinbase(tx))
continue;
currency::tx_verification_context tvc = AUTO_VAL_INIT(tvc);
bool r = m_tx_pool.add_tx(tx, 0, tvc, true, true); // don't check min fee because form the chain
CHECK_AND_ASSERT_MES(r, false, "failed to add transaction " << tx_id << " to transaction pool");
}
}
LOG_PRINT_L0("Rollback success.");
return true;
}
//------------------------------------------------------------------
void blockchain_storage::add_alt_block_txs_hashs(const block& b)
{
CRITICAL_REGION_LOCAL(m_alternative_chains_lock);
for (const auto& tx_hash : b.tx_hashes)
{
m_alternative_chains_txs[tx_hash]++;
}
}
//------------------------------------------------------------------
void blockchain_storage::purge_alt_block_txs_hashs(const block& b)
{
CRITICAL_REGION_LOCAL(m_alternative_chains_lock);
for (const auto& h : b.tx_hashes)
{
auto it = m_alternative_chains_txs.find(h);
if (it == m_alternative_chains_txs.end())
{
LOG_ERROR("Internal error: tx with hash " << h << " not found in m_alternative_chains_txs while removing block " << get_block_hash(b));
continue;
}
if (it->second >= 1)
{
it->second--;
}
else
{
LOG_ERROR("Internal error: tx with hash " << h << " has invalid m_alternative_chains_txs entry (zero count) while removing block " << get_block_hash(b));
}
if (it->second == 0)
m_alternative_chains_txs.erase(it);
}
}
//------------------------------------------------------------------
void blockchain_storage::do_erase_altblock(alt_chain_container::iterator it)
{
if (!purge_altblock_keyimages_from_big_heap(it->second.bl, get_block_hash(it->second.bl)))
LOG_ERROR("failed to purge_altblock_keyimages_from_big_heap");
purge_alt_block_txs_hashs(it->second.bl);
m_alternative_chains.erase(it);
}
//------------------------------------------------------------------
bool blockchain_storage::switch_to_alternative_blockchain(alt_chain_type& alt_chain, bool &had_rollback)
{
CRITICAL_REGION_LOCAL(m_read_lock);
bool r = validate_blockchain_prev_links();
CHECK_AND_ASSERT_MES(r, false, "EPIC FAIL!");
CHECK_AND_ASSERT_MES(alt_chain.size(), false, "switch_to_alternative_blockchain: empty chain passed");
size_t split_height = alt_chain.front()->second.height;
CHECK_AND_ASSERT_MES(m_db_blocks.size() >= split_height, false, "switch_to_alternative_blockchain: blockchain size is lower than split height" << ENDL
<< " alt chain: " << ENDL << print_alt_chain(alt_chain) << ENDL
<< " main chain: " << ENDL << get_blockchain_string(m_db_blocks.size() - 10, CURRENCY_MAX_BLOCK_NUMBER)
);
//disconnecting old chain
std::list<block> disconnected_chain;
for (size_t i = m_db_blocks.size() - 1; i >= split_height; i--)
{
block b = m_db_blocks[i]->bl;
r = pop_block_from_blockchain();
CHECK_AND_ASSERT_MES(r, false, "failed to remove block " << get_block_hash(b) << " @ " << get_block_height(b) << " on chain switching");
disconnected_chain.push_front(b);
CHECK_AND_ASSERT_MES(validate_blockchain_prev_links(), false, "EPIC FAIL!");
}
//connecting new alternative chain
for (auto alt_ch_iter = alt_chain.begin(); alt_ch_iter != alt_chain.end(); alt_ch_iter++)
{
auto ch_ent = *alt_ch_iter;
block_verification_context bvc = boost::value_initialized<block_verification_context>();
r = handle_block_to_main_chain(ch_ent->second.bl, bvc);
if (!r || !bvc.m_added_to_main_chain)
{
LOG_PRINT_L0("Failed to switch to alternative blockchain");
if (!rollback_blockchain_switching(split_height))
LOG_ERROR("failed to rollback_blockchain_switching");
had_rollback = true;
LOG_PRINT_L0("The block was inserted as invalid while connecting new alternative chain, block_id: " << get_block_hash(ch_ent->second.bl));
for (; alt_ch_iter != alt_chain.end(); ++alt_ch_iter)
{
if (!add_block_as_invalid((*alt_ch_iter)->second, (*alt_ch_iter)->first))
LOG_ERROR("failed to add_block_as_invalid");
do_erase_altblock(*alt_ch_iter);
}
CHECK_AND_ASSERT_MES(validate_blockchain_prev_links(), false, "EPIC FAIL!");
return false;
}
}
//pushing old chain as alternative chain
for (auto& old_ch_ent : disconnected_chain)
{
block_verification_context bvc = boost::value_initialized<block_verification_context>();
r = handle_alternative_block(old_ch_ent, get_block_hash(old_ch_ent), bvc);
if (!r)
{
LOG_ERROR("Failed to push ex-main chain blocks to alternative chain ");
if (!rollback_blockchain_switching(split_height))
LOG_ERROR("failed to rollback_blockchain_switching");
had_rollback = true;
CHECK_AND_ASSERT_MES(validate_blockchain_prev_links(), false, "EPIC FAIL!");
//can't do return false here, because of the risc to get stuck in "PANIC" mode when nor of
//new chain nor altchain can be inserted into main chain. Got core caught in this trap when
//when machine time was wrongly set for a few hours back, then blocks which was detached from main chain
//couldn't be added as alternative due to timestamps validation(timestamps assumed as from future)
//thanks @Gigabyted for reporting this problem
break;
}
}
//removing all_chain entries from alternative chain
for (auto ch_ent : alt_chain)
do_erase_altblock(ch_ent);
LOG_PRINT_GREEN("REORGANIZE SUCCESS! on height: " << split_height << ", new blockchain size: " << m_db_blocks.size(), LOG_LEVEL_0);
return true;
}
//------------------------------------------------------------------
wide_difficulty_type blockchain_storage::get_next_diff_conditional(bool pos) const
{
CRITICAL_REGION_LOCAL(m_read_lock);
std::vector<uint64_t> timestamps;
std::vector<wide_difficulty_type> commulative_difficulties;
size_t count = 0;
if (!m_db_blocks.size())
return DIFFICULTY_STARTER;
//skip genesis timestamp
uint64_t stop_ind = 0;
uint64_t blocks_size = m_db_blocks.size();
timestamps.reserve(DIFFICULTY_WINDOW);
commulative_difficulties.reserve(DIFFICULTY_WINDOW);
for (uint64_t cur_ind = blocks_size - 1; cur_ind != stop_ind && count < DIFFICULTY_WINDOW; cur_ind--)
{
auto beiptr = m_db_blocks[cur_ind];
bool is_pos_bl = is_pos_block(beiptr->bl);
if (pos != is_pos_bl)
continue;
timestamps.push_back(beiptr->bl.timestamp);
commulative_difficulties.push_back(beiptr->cumulative_diff_precise);
++count;
}
auto diff = next_difficulty(timestamps, commulative_difficulties, pos ? DIFFICULTY_POS_TARGET : DIFFICULTY_POW_TARGET);
m_diff_cache.set(diff, pos, m_db_blocks.size());
return diff;
}
//------------------------------------------------------------------
wide_difficulty_type blockchain_storage::get_next_diff_conditional2(bool pos, const alt_chain_type& alt_chain, uint64_t split_height, const alt_block_extended_info& abei) const
{
CRITICAL_REGION_LOCAL(m_read_lock);
std::vector<uint64_t> timestamps;
std::vector<wide_difficulty_type> commulative_difficulties;
size_t count = 0;
if (!m_db_blocks.size())
return DIFFICULTY_STARTER;
timestamps.reserve(DIFFICULTY_WINDOW);
commulative_difficulties.reserve(DIFFICULTY_WINDOW);
auto cb = [&](const block_extended_info& bei, bool is_main){
if (!bei.height)
return false;
bool is_pos_bl = is_pos_block(bei.bl);
if (pos != is_pos_bl)
return true;
timestamps.push_back(bei.bl.timestamp);
commulative_difficulties.push_back(bei.cumulative_diff_precise);
++count;
if (count >= DIFFICULTY_WINDOW)
return false;
return true;
};
enum_blockchain(cb, alt_chain, split_height);
return next_difficulty(timestamps, commulative_difficulties, pos ? DIFFICULTY_POS_TARGET : DIFFICULTY_POW_TARGET);
}
//------------------------------------------------------------------
wide_difficulty_type blockchain_storage::get_cached_next_difficulty(bool pos) const
{
auto cached_diff = m_diff_cache.get(pos, m_db_blocks.size());
return cached_diff != 0 ? cached_diff : get_next_diff_conditional(pos);
}
//------------------------------------------------------------------
std::shared_ptr<block_extended_info> blockchain_storage::get_last_block_of_type(bool looking_for_pos, const alt_chain_type& alt_chain, uint64_t split_height) const
{
CRITICAL_REGION_LOCAL(m_read_lock);
std::shared_ptr<block_extended_info> pbei(nullptr);
auto cb = [&](const block_extended_info& bei_local, bool is_main){
if (looking_for_pos == is_pos_block(bei_local.bl))
{
pbei.reset(new block_extended_info(bei_local));
return false;
}
return true;
};
enum_blockchain(cb, alt_chain, split_height);
return pbei;
}
//------------------------------------------------------------------
bool blockchain_storage::prevalidate_miner_transaction(const block& b, uint64_t height, bool pos) const
{
CHECK_AND_ASSERT_MES((pos ? is_pos_coinbase(b.miner_tx) : is_pow_coinbase(b.miner_tx)), false, "coinbase transaction in the block has the wrong type");
if(boost::get<txin_gen>(b.miner_tx.vin[0]).height != height)
{
LOG_PRINT_RED_L0("The miner transaction in block has invalid height: " << boost::get<txin_gen>(b.miner_tx.vin[0]).height << ", expected: " << height);
return false;
}
CHECK_AND_ASSERT_MES(get_tx_unlock_time(b.miner_tx) == height + CURRENCY_MINED_MONEY_UNLOCK_WINDOW,
false,
"coinbase transaction has wrong unlock time: " << get_tx_unlock_time(b.miner_tx) << ", expected: " << height + CURRENCY_MINED_MONEY_UNLOCK_WINDOW);
//check outs overflow
if(!check_outs_overflow(b.miner_tx))
{
LOG_PRINT_RED_L0("miner transaction have money overflow in block " << get_block_hash(b));
return false;
}
CHECK_AND_ASSERT_MES(b.miner_tx.attachment.empty(), false, "coinbase transaction has attachments; attachments are not allowed for coinbase transactions.");
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::validate_miner_transaction(const block& b,
size_t cumulative_block_size,
uint64_t fee,
uint64_t& base_reward,
uint64_t already_generated_coins) const
{
CRITICAL_REGION_LOCAL(m_read_lock);
//validate reward
uint64_t money_in_use = get_outs_money_amount(b.miner_tx);
uint64_t pos_income = 0;
if (is_pos_block(b))
{
CHECK_AND_ASSERT_MES(b.miner_tx.vin[1].type() == typeid(txin_to_key), false, "Wrong miner tx_in");
pos_income = boost::get<txin_to_key>(b.miner_tx.vin[1]).amount;
}
std::vector<size_t> last_blocks_sizes;
auto r = get_last_n_blocks_sizes(last_blocks_sizes, CURRENCY_REWARD_BLOCKS_WINDOW);
CHECK_AND_ASSERT_MES(r, false, "failed to get_last_n_blocks_sizes");
size_t blocks_size_median = misc_utils::median(last_blocks_sizes);
if (!get_block_reward(is_pos_block(b), blocks_size_median, cumulative_block_size, already_generated_coins, base_reward, get_block_height(b)))
{
LOG_PRINT_L0("block size " << cumulative_block_size << " is bigger than allowed for this blockchain");
return false;
}
if (base_reward + pos_income + fee < money_in_use)
{
LOG_ERROR("coinbase transaction spend too much money (" << print_money(money_in_use) << "). Block reward is " << print_money(base_reward + pos_income + fee) << "(" << print_money(base_reward) << "+" << print_money(pos_income) << "+" << print_money(fee)
<< ", blocks_size_median = " << blocks_size_median
<< ", cumulative_block_size = " << cumulative_block_size
<< ", fee = " << fee
<< ", already_generated_coins = " << already_generated_coins
<< "), tx:");
LOG_PRINT_L0(currency::obj_to_json_str(b.miner_tx));
return false;
}
if (base_reward + pos_income + fee != money_in_use)
{
LOG_ERROR("coinbase transaction doesn't use full amount of block reward: spent: (" << print_money(money_in_use) << "). Block reward is " << print_money(base_reward + pos_income + fee) << "(" << print_money(base_reward) << "+" << print_money(pos_income) << "+" << print_money(fee)
<< ", blocks_size_median = " << blocks_size_median
<< ", cumulative_block_size = " << cumulative_block_size
<< ", fee = " << fee
<< ", already_generated_coins = " << already_generated_coins
<< "), tx:");
LOG_PRINT_L0(currency::obj_to_json_str(b.miner_tx));
return false;
}
LOG_PRINT_MAGENTA("Mining tx verification ok, blocks_size_median = " << blocks_size_median, LOG_LEVEL_2);
return true;
}
//------------------------------------------------------------------
blockchain_storage::performnce_data& blockchain_storage::get_performnce_data()const
{
if (!m_db.get_backend()->get_stat_info(m_performance_data.si))
LOG_ERROR("failed to get_stat_info");
return m_performance_data;
}
//------------------------------------------------------------------
bool blockchain_storage::get_backward_blocks_sizes(size_t from_height, std::vector<size_t>& sz, size_t count)const
{
CRITICAL_REGION_LOCAL(m_read_lock);
CHECK_AND_ASSERT_MES(from_height < m_db_blocks.size(), false, "Internal error: get_backward_blocks_sizes called with from_height=" << from_height << ", blockchain height = " << m_db_blocks.size());
size_t start_offset = (from_height+1) - std::min((from_height+1), count);
for(size_t i = start_offset; i != from_height+1; i++)
sz.push_back(m_db_blocks[i]->block_cumulative_size);
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::get_last_n_blocks_sizes(std::vector<size_t>& sz, size_t count) const
{
CRITICAL_REGION_LOCAL(m_read_lock);
if(!m_db_blocks.size())
return true;
return get_backward_blocks_sizes(m_db_blocks.size() -1, sz, count);
}
//------------------------------------------------------------------
uint64_t blockchain_storage::get_current_comulative_blocksize_limit() const
{
CRITICAL_REGION_LOCAL(m_read_lock);
return m_db_current_block_cumul_sz_limit;
}
//------------------------------------------------------------------
bool blockchain_storage::create_block_template(block& b,
const account_public_address& miner_address,
wide_difficulty_type& diffic,
uint64_t& height,
const blobdata& ex_nonce) const
{
return create_block_template(b, miner_address, miner_address, diffic, height, ex_nonce, false, pos_entry());
}
//------------------------------------------------------------------
bool blockchain_storage::create_block_template(block& b,
const account_public_address& miner_address,
const account_public_address& stakeholder_address,
wide_difficulty_type& diffic,
uint64_t& height,
const blobdata& ex_nonce,
bool pos,
const pos_entry& pe,
fill_block_template_func_t custom_fill_block_template_func /* = nullptr */) const
{
create_block_template_params params = AUTO_VAL_INIT(params);
params.miner_address = miner_address;
params.stakeholder_address = stakeholder_address;
params.ex_nonce = ex_nonce;
params.pos = pos;
params.pe = pe;
params.p_custom_fill_block_template_func = custom_fill_block_template_func;
create_block_template_response resp = AUTO_VAL_INIT(resp);
bool r = create_block_template(params, resp);
b = resp.b;
diffic = resp.difficulty;
height = resp.height;
return r;
}
//------------------------------------------------------------------
bool blockchain_storage::create_block_template(const create_block_template_params& params, create_block_template_response& resp) const
{
const auto& miner_address = params.miner_address;
const auto& stakeholder_address = params.stakeholder_address;
const auto& ex_nonce = params.ex_nonce;
const auto& pos = params.pos;
const auto& pe = params.pe;
auto * const p_custom_fill_block_template_func = params.p_custom_fill_block_template_func;
auto& height = resp.height;
auto& b = resp.b;
auto& difficulty = resp.difficulty;
size_t median_size;
uint64_t already_generated_coins;
CRITICAL_REGION_BEGIN(m_read_lock);
b.major_version = CURRENT_BLOCK_MAJOR_VERSION;
b.minor_version = CURRENT_BLOCK_MINOR_VERSION;
b.prev_id = get_top_block_id();
b.timestamp = m_core_runtime_config.get_core_time();
b.nonce = 0;
b.flags = 0;
if (pos)
{
b.flags |= CURRENCY_BLOCK_FLAG_POS_BLOCK;
b.timestamp = 0;
}
difficulty = get_cached_next_difficulty(pos);
CHECK_AND_ASSERT_MES(difficulty, false, "difficulty overhead.");
height = m_db_blocks.size();
median_size = m_db_current_block_cumul_sz_limit / 2;
already_generated_coins = m_db_blocks.back()->already_generated_coins;
CRITICAL_REGION_END();
size_t txs_size;
uint64_t fee;
bool block_filled = false;
if (p_custom_fill_block_template_func == nullptr)
block_filled = m_tx_pool.fill_block_template(b, pos, median_size, already_generated_coins, txs_size, fee, height);
else
block_filled = (*p_custom_fill_block_template_func)(b, pos, median_size, already_generated_coins, txs_size, fee, height);
if (!block_filled)
return false;
/*
instead of complicated two-phase template construction and adjustment of cumulative size with block reward we
use CURRENCY_COINBASE_BLOB_RESERVED_SIZE as penalty-free coinbase transaction reservation.
*/
bool r = construct_miner_tx(height, median_size, already_generated_coins,
txs_size,
fee,
miner_address,
stakeholder_address,
b.miner_tx, ex_nonce,
CURRENCY_MINER_TX_MAX_OUTS,
pos,
pe);
CHECK_AND_ASSERT_MES(r, false, "Failed to construc miner tx, first chance");
uint64_t coinbase_size = get_object_blobsize(b.miner_tx);
// "- 100" - to reserve room for PoS additions into miner tx
CHECK_AND_ASSERT_MES(coinbase_size < CURRENCY_COINBASE_BLOB_RESERVED_SIZE - 100, false, "Failed to get block template (coinbase_size = " << coinbase_size << ") << coinbase structue: "
<< ENDL << obj_to_json_str(b.miner_tx));
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::print_transactions_statistics() const
{
LOG_ERROR("print_transactions_statistics not implemented yet");
// CRITICAL_REGION_LOCAL(m_blockchain_lock);
// LOG_PRINT_L0("Started to collect transaction statistics, pleas wait...");
// size_t total_count = 0;
// size_t coinbase_count = 0;
// size_t total_full_blob = 0;
// size_t total_cropped_blob = 0;
// for(auto tx_entry: m_db_transactions)
// {
// ++total_count;
// if(is_coinbase(tx_entry.second.tx))
// ++coinbase_count;
// else
// {
// total_full_blob += get_object_blobsize<transaction>(tx_entry.second.tx);
// transaction tx = tx_entry.second.tx;
// tx.signatures.clear();
// total_cropped_blob += get_object_blobsize<transaction>(tx);
// }
// }
// LOG_PRINT_L0("Done" << ENDL
// << "total transactions: " << total_count << ENDL
// << "coinbase transactions: " << coinbase_count << ENDL
// << "avarage size of transaction: " << total_full_blob/(total_count-coinbase_count) << ENDL
// << "avarage size of transaction without ring signatures: " << total_cropped_blob/(total_count-coinbase_count) << ENDL
// );
return true;
}
void blockchain_storage::reset_db_cache() const
{
m_db_blocks.clear_cache();
m_db_blocks_index.clear_cache();
m_db_transactions.clear_cache();
m_db_spent_keys.clear_cache();
m_db_solo_options.clear_cache();
m_db_multisig_outs.clear_cache();
m_db_aliases.clear_cache();
m_db_addr_to_alias.clear_cache();
}
//------------------------------------------------------------------
void blockchain_storage::clear_altblocks()
{
CRITICAL_REGION_LOCAL(m_alternative_chains_lock);
m_alternative_chains.clear();
m_alternative_chains_txs.clear();
m_altblocks_keyimages.clear();
}
//------------------------------------------------------------------
bool blockchain_storage::complete_timestamps_vector(uint64_t start_top_height, std::vector<uint64_t>& timestamps, size_t elements_count) const
{
if(timestamps.size() >= elements_count)
return true;
CRITICAL_REGION_LOCAL(m_read_lock);
size_t need_elements = elements_count - timestamps.size();
CHECK_AND_ASSERT_MES(start_top_height < m_db_blocks.size(), false, "internal error: passed start_height = " << start_top_height << " not less then m_blocks.size()=" << m_db_blocks.size());
size_t stop_offset = start_top_height > need_elements ? start_top_height - need_elements + 1 : 1;
for (; stop_offset <= start_top_height; stop_offset++)
timestamps.push_back(m_db_blocks[stop_offset]->bl.timestamp);
return true;
}
//------------------------------------------------------------------
std::string blockchain_storage::print_alt_chain(alt_chain_type alt_chain)
{
std::stringstream ss;
for (auto it = alt_chain.begin(); it != alt_chain.end(); it++)
{
ss << "[" << (*it)->second.height << "] " << (*it)->first << "(cumul_dif: " << (*it)->second.cumulative_diff_adjusted << "), parent_id: " << (*it)->second.bl.prev_id << ENDL;
}
return ss.str();
}
//------------------------------------------------------------------
bool blockchain_storage::append_altblock_keyimages_to_big_heap(const crypto::hash& block_id, const std::set<crypto::key_image>& alt_block_keyimages)
{
for (auto& ki : alt_block_keyimages)
m_altblocks_keyimages[ki].push_back(block_id);
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::purge_keyimage_from_big_heap(const crypto::key_image& ki, const crypto::hash& id)
{
auto it = m_altblocks_keyimages.find(ki);
CHECK_AND_ASSERT_MES(it != m_altblocks_keyimages.end(), false, "internal error: keyimage " << ki
<< "from altblock " << id << "not found in m_altblocks_keyimages in purge_keyimage_from_big_heap");
//TODO: at the moment here is simple liner algo since having the same txs in few altblocks is rare case
std::list<crypto::hash>& ki_blocks_ids = it->second;
bool found = false;
for (auto it_in_blocks = ki_blocks_ids.begin(); it_in_blocks != ki_blocks_ids.end(); it_in_blocks++)
{
if (*it_in_blocks == id)
{
//found, erase this entry
ki_blocks_ids.erase(it_in_blocks);
found = true;
break;
}
}
CHECK_AND_ASSERT_MES(found, false, "internal error: keyimage " << ki
<< "from altblock " << id << "not found in m_altblocks_keyimages in purge_keyimage_from_big_heap");
if (!ki_blocks_ids.size())
m_altblocks_keyimages.erase(it);
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::purge_altblock_keyimages_from_big_heap(const block& b, const crypto::hash& id)
{
if (is_pos_block(b) && !purge_keyimage_from_big_heap(boost::get<txin_to_key>(b.miner_tx.vin[1]).k_image, id))
LOG_ERROR("failed to purge_keyimage_from_big_heap");
for (auto tx_id : b.tx_hashes)
{
std::shared_ptr<transaction> tx_ptr;
if (!get_transaction_from_pool_or_db(tx_id, tx_ptr))
{
LOG_ERROR("failed to get alt block tx " << tx_id << " on block detach from alts");
continue;
}
transaction& tx = *tx_ptr;
for (size_t n = 0; n < tx.vin.size(); ++n)
{
if (tx.vin[n].type() == typeid(txin_to_key))
{
if (!purge_keyimage_from_big_heap(boost::get<txin_to_key>(tx.vin[n]).k_image, id))
LOG_ERROR("failed to purge_keyimage_from_big_heap");
}
}
}
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::build_alt_subchain(alt_chain_type &alt_chain, const block& b, const crypto::hash& id)
{
//build alternative subchain, front -> mainchain, back -> alternative head
auto it = m_alternative_chains.find(b.prev_id);
while (it != m_alternative_chains.end())
{
alt_chain.push_front(it);
it = m_alternative_chains.find(it->second.bl.prev_id);
}
if (alt_chain.empty())
return true;
//make sure that it has right connection to main chain
CHECK_AND_ASSERT_MES(m_db_blocks.size() >= alt_chain.front()->second.height, false,
"main blockchain wrong height: m_db_blocks.size() = " << m_db_blocks.size()
<< " and alt_chain.front()->second.height = " << alt_chain.front()->second.height
<< " for block " << id << ", prev_id=" << b.prev_id << ENDL
<< " alt chain: " << ENDL << print_alt_chain(alt_chain) << ENDL
<< " main chain: " << ENDL << get_blockchain_string(m_db_blocks.size() - 10, CURRENCY_MAX_BLOCK_NUMBER)
);
crypto::hash h = null_hash;
auto r = get_block_hash(m_db_blocks.get(alt_chain.front()->second.height - 1)->bl, h);
CHECK_AND_ASSERT_MES(r && h == alt_chain.front()->second.bl.prev_id, false,
"alternative chain have wrong connection to main chain");
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::handle_alternative_block(const block& b, const crypto::hash& id, crypto::hash &proof, alt_chain_type &alt_chain, block_verification_context& bvc)
{
uint64_t coinbase_height = get_block_height(b);
bool r = m_checkpoints.is_height_passed_zone(coinbase_height, get_top_block_height());
CHECK_AND_ASSERT_MES_CUSTOM(!r, false, bvc.m_verification_failed = true, "Block with id: " << id << "[" << coinbase_height << "]" << ENDL << " for alternative chain, is under checkpoint zone, declined");
TRY_ENTRY()
CRITICAL_REGION_LOCAL(m_read_lock);
CRITICAL_REGION_LOCAL1(m_alternative_chains_lock);
r = build_alt_subchain(alt_chain, b, id);
CHECK_AND_ASSERT_MES_CUSTOM(r, false, bvc.m_verification_failed = true, "failed to build alternative subchain");
uint64_t height_main_prev = 0;
const bool prev_in_main = alt_chain.empty();
if (prev_in_main)
{
if (!checked_get_height_by_id(b.prev_id, height_main_prev))
{
bvc.m_marked_as_orphaned = true;
LOG_ERROR("Block recognized as orphaned and rejected, id = " << id << "," << ENDL << "parent id = " << b.prev_id << ENDL << "height = " << coinbase_height);
CHECK_AND_ASSERT_MES(validate_blockchain_prev_links(), false, "EPIC FAIL!");
return true;
}
}
{
std::vector<uint64_t> timestamps;
timestamps.reserve(BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW);
for (auto it = alt_chain.crbegin(); it != alt_chain.crend() && timestamps.size() < BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW; ++it)
timestamps.push_back((*it)->second.bl.timestamp);
if (timestamps.size() < BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW)
{
const uint64_t index_to_timestamps_complete = prev_in_main ? height_main_prev : alt_chain.front()->second.height - 1;
r = complete_timestamps_vector(index_to_timestamps_complete, timestamps, BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW);
CHECK_AND_ASSERT_MES_CUSTOM(r, false, bvc.m_verification_failed = true, "failed to complete_timestamps_vector");
}
r = check_block_timestamp(std::move(timestamps), b);
CHECK_AND_ASSERT_MES_CUSTOM(r, false, bvc.m_verification_failed = true, "Block with id: " << id << ENDL << " for alternative chain, have invalid timestamp: " << b.timestamp);
}
alt_block_extended_info abei = AUTO_VAL_INIT(abei);
{
abei.bl = b;
abei.height = prev_in_main ? height_main_prev + 1 : alt_chain.back()->second.height + 1;
CHECK_AND_ASSERT_MES_CUSTOM(coinbase_height == abei.height, false, bvc.m_verification_failed = true, "block coinbase height doesn't match with altchain height, declined");
}
uint64_t connection_height = prev_in_main ? abei.height : alt_chain.front()->second.height;
CHECK_AND_ASSERT_MES_CUSTOM(connection_height, false, bvc.m_verification_failed = true, "INTERNAL ERROR: Wrong connection_height==0 in handle_alternative_block");
{
if (m_checkpoints.is_in_checkpoint_zone(abei.height))
{
r = m_checkpoints.check_block(abei.height, id);
CHECK_AND_ASSERT_MES_CUSTOM(r, false, bvc.m_verification_failed = true, "checkpoint validation failed");
}
}
bool is_pos = is_pos_block(abei.bl);
CHECK_AND_ASSERT_MES_CUSTOM(!(is_pos && abei.height < m_core_runtime_config.pos_minimum_heigh), false, bvc.m_verification_failed = true, "PoS block is not allowed on this height");
wide_difficulty_type current_diff = get_next_diff_conditional2(is_pos, alt_chain, connection_height, abei);
CHECK_AND_ASSERT_MES_CUSTOM(current_diff, false, bvc.m_verification_failed = true, "!!!!!!! DIFFICULTY OVERHEAD !!!!!!!");
auto proof_of_work = null_hash;
uint64_t pos_amount = 0;
wide_difficulty_type pos_diff_final = 0;
{
if (is_pos)
{
r = validate_pos_block(abei.bl, current_diff, pos_amount, pos_diff_final, abei.stake_hash, id, true, alt_chain, connection_height);
CHECK_AND_ASSERT_MES_CUSTOM(r, false, bvc.m_verification_failed = true, "Failed to validate_pos_block on alternative block, height = " << abei.height << ", block id: " << get_block_hash(abei.bl));
}
else
{
proof_of_work = get_block_longhash(abei.bl);
r = check_hash(proof_of_work, current_diff);
CHECK_AND_ASSERT_MES_CUSTOM(r, false, bvc.m_verification_failed = true, "Block with id: " << id
<< ENDL << " for alternative chain, have not enough proof of work: " << proof_of_work
<< ENDL << " expected difficulty: " << current_diff);
}
}
r = prevalidate_miner_transaction(b, abei.height, is_pos);
CHECK_AND_ASSERT_MES_CUSTOM(r, false, bvc.m_verification_failed = true, "Block with id: " << string_tools::pod_to_hex(id) << " (as alternative) have wrong miner transaction.");
std::set<crypto::key_image> alt_block_keyimages;
uint64_t ki_lookup_total = 0;
r = validate_alt_block_txs(b, id, alt_block_keyimages, abei, alt_chain, connection_height, ki_lookup_total);
CHECK_AND_ASSERT_MES_CUSTOM(r, false, bvc.m_verification_failed = true, "Alternative block " << id << " @ " << abei.height << " has invalid transactions. Rejected.");
std::size_t sequence_factor = get_current_sequence_factor_for_alt(alt_chain, is_pos, connection_height);
{
abei.difficulty = current_diff;
abei.cumulative_diff_adjusted = prev_in_main ? m_db_blocks[height_main_prev]->cumulative_diff_adjusted : alt_chain.back()->second.cumulative_diff_adjusted;
wide_difficulty_type cumulative_diff_delta = !is_pos ? current_diff : get_adjusted_cumulative_difficulty_for_next_alt_pos(alt_chain, abei.height, current_diff, connection_height);
if (abei.height >= m_core_runtime_config.pos_minimum_heigh)
cumulative_diff_delta = correct_difficulty_with_sequence_factor(sequence_factor, cumulative_diff_delta);
abei.cumulative_diff_adjusted += cumulative_diff_delta;
abei.cumulative_diff_precise = get_last_alt_x_block_cumulative_precise_difficulty(alt_chain, abei.height, is_pos);
abei.cumulative_diff_precise += current_diff;
}
#ifdef _DEBUG
auto it = m_alternative_chains.find(id);
CHECK_AND_ASSERT_MES_CUSTOM(it == m_alternative_chains.end(), false, bvc.m_verification_failed = true, "insertion of new alternative block " << id << " returned as it already exist");
#endif
auto insert_res = m_alternative_chains.insert(alt_chain_container::value_type(id, abei));
CHECK_AND_ASSERT_MES_CUSTOM(insert_res.second, false, bvc.m_verification_failed = true, "insertion of new alternative block " << id << " returned as it already exist");
r = append_altblock_keyimages_to_big_heap(id, alt_block_keyimages);
CHECK_AND_ASSERT_MES_CUSTOM(r, false, bvc.m_verification_failed = true, "failed to append_altblock_keyimages_to_big_heap");
add_alt_block_txs_hashs(insert_res.first->second.bl);
alt_chain.push_back(insert_res.first);
bvc.m_height_difference = get_top_block_height() >= abei.height ? get_top_block_height() - abei.height : 0;
proof = is_pos ? abei.stake_hash : proof_of_work;
std::stringstream ss_pow_pos_info;
if (is_pos)
ss_pow_pos_info << "PoS:\t" << abei.stake_hash << ", stake amount: " << print_money(pos_amount) << ", final_difficulty: " << pos_diff_final;
else
ss_pow_pos_info << "PoW:\t" << proof_of_work;
LOG_PRINT_BLUE("----- BLOCK ADDED AS ALTERNATIVE ON HEIGHT " << abei.height << (is_pos ? " [PoS] Sq: " : " [PoW] Sq: ") << sequence_factor << ", altchain sz: " << alt_chain.size() << ", split h: " << connection_height
<< ENDL << "id:\t" << id
<< ENDL << "prev\t" << abei.bl.prev_id
<< ENDL << ss_pow_pos_info.str()
<< ENDL << "HEIGHT " << abei.height << ", difficulty: " << abei.difficulty << ", cumul_diff_precise: " << abei.cumulative_diff_precise << ", cumul_diff_adj: " << abei.cumulative_diff_adjusted << " (current mainchain cumul_diff_adj: " << m_db_blocks.back()->cumulative_diff_adjusted << ", ki lookup total: " << ki_lookup_total <<")"
, LOG_LEVEL_0);
bvc.m_added_to_altchain = true;
return true;
CATCH_ENTRY_CUSTOM("blockchain_storage::handle_alternative_block", bvc.m_verification_failed = true, false)
}
//------------------------------------------------------------------
bool blockchain_storage::handle_alternative_block(const block& b, const crypto::hash& id, block_verification_context& bvc)
{
auto proof = null_hash;
alt_chain_type alt_chain;
return handle_alternative_block(b, id, proof, alt_chain, bvc);
}
//------------------------------------------------------------------
bool blockchain_storage::is_reorganize_required(const block_extended_info& main_chain_bei, const block_extended_info& alt_chain_bei, const crypto::hash& proof_alt)
{
if (main_chain_bei.cumulative_diff_adjusted < alt_chain_bei.cumulative_diff_adjusted)
return true;
else if (main_chain_bei.cumulative_diff_adjusted > alt_chain_bei.cumulative_diff_adjusted)
return false;
else // main_chain_bei.cumulative_diff_adjusted == alt_chain_bei.cumulative_diff_adjusted
{
if (!is_pos_block(main_chain_bei.bl))
return false; // do not reorganize on the same cummul diff if it's a PoW block
//in case of simultaneous PoS blocks are happened on the same height (quite common for PoS)
//we also try to weight them to guarantee consensus in network
if (std::memcmp(&main_chain_bei.stake_hash, &proof_alt, sizeof(main_chain_bei.stake_hash)) >= 0)
return false;
LOG_PRINT_L2("[is_reorganize_required]:TRUE, \"by order of memcmp\" main_stake_hash:" << &main_chain_bei.stake_hash << ", alt_stake_hash" << proof_alt);
return true;
}
}
//------------------------------------------------------------------
bool blockchain_storage::pre_validate_relayed_block(block& bl, block_verification_context& bvc, const crypto::hash& id)const
{
TRY_ENTRY()
CRITICAL_REGION_LOCAL(m_read_lock);
if (!(bl.prev_id == get_top_block_id()))
{
bvc.m_added_to_main_chain = false;
bvc.m_verification_failed = false;
return true;
}
//check proof of work
bool is_pos_bl = is_pos_block(bl);
wide_difficulty_type current_diffic = get_cached_next_difficulty(is_pos_bl);
CHECK_AND_ASSERT_MES_CUSTOM(current_diffic, false, bvc.m_verification_failed = true, "!!!!!!!!! difficulty overhead !!!!!!!!!");
crypto::hash proof_hash = AUTO_VAL_INIT(proof_hash);
if (is_pos_bl)
{
wide_difficulty_type this_coin_diff = 0;
uint64_t amount = 0;
bool r = validate_pos_block(bl, current_diffic, amount, this_coin_diff, proof_hash, id, false);
CHECK_AND_ASSERT_MES_CUSTOM(r, false, bvc.m_verification_failed = true, "validate_pos_block failed!!");
}
else
{
proof_hash = get_block_longhash(bl);
if (!check_hash(proof_hash, current_diffic))
{
LOG_PRINT_L0("Block with id: " << id << ENDL
<< " : " << proof_hash << ENDL
<< "unexpected difficulty: " << current_diffic);
bvc.m_verification_failed = true;
return false;
}
}
bvc.m_added_to_main_chain = true;
return true;
CATCH_ENTRY_CUSTOM("blockchain_storage::pre_validate_relayed_block", bvc.m_verification_failed = true, false)
}
//------------------------------------------------------------------
bool blockchain_storage::get_blocks(uint64_t start_offset, size_t count, std::list<block>& blocks, std::list<transaction>& txs) const
{
CRITICAL_REGION_LOCAL(m_read_lock);
if(start_offset >= m_db_blocks.size())
return false;
for(size_t i = start_offset; i < start_offset + count && i < m_db_blocks.size();i++)
{
blocks.push_back(m_db_blocks[i]->bl);
std::list<crypto::hash> missed_ids;
auto r = get_transactions(m_db_blocks[i]->bl.tx_hashes, txs, missed_ids);
CHECK_AND_ASSERT_MES(r && !missed_ids.size(), false, "have missed transactions in own block in main blockchain");
}
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::get_tx_rpc_details(const crypto::hash& h, tx_rpc_extended_info& tei, uint64_t timestamp, bool is_short) const
{
CRITICAL_REGION_LOCAL(m_read_lock);
auto tx_ptr = m_db_transactions.get(h);
if (!tx_ptr)
{
tei.keeper_block = -1; // tx is not confirmed yet, probably it's in the pool
return false;
}
if (tx_ptr && !timestamp)
{
timestamp = get_actual_timestamp(m_db_blocks[tx_ptr->m_keeper_block_height]->bl);
}
tei.keeper_block = static_cast<int64_t>(tx_ptr->m_keeper_block_height);
if (!fill_tx_rpc_details(tei, tx_ptr->tx, &(*tx_ptr), h, timestamp, is_short))
LOG_ERROR("failed to fill_tx_rpc_details");
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::search_by_id(const crypto::hash& id, std::list<std::string>& res) const
{
auto block_ptr = m_db_blocks_index.get(id);
if (block_ptr)
{
res.push_back("block");
}
auto tx_ptr = m_db_transactions.get(id);
if (tx_ptr)
{
res.push_back("tx");
}
auto ki_ptr = m_db_spent_keys.get( *reinterpret_cast<const crypto::key_image*>(&id));
if (ki_ptr)
{
res.push_back("key_image");
}
auto ms_ptr = m_db_multisig_outs.get(id);
if (ms_ptr)
{
res.push_back(std::string("multisig_id:") + epee::string_tools::pod_to_hex(ms_ptr->tx_id) + ":" + std::to_string(ms_ptr->out_no));
}
if (m_alternative_chains.end() != m_alternative_chains.find(id))
{
res.push_back("alt_block");
}
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::get_global_index_details(const COMMAND_RPC_GET_TX_GLOBAL_OUTPUTS_INDEXES_BY_AMOUNT::request& req, COMMAND_RPC_GET_TX_GLOBAL_OUTPUTS_INDEXES_BY_AMOUNT::response & resp) const
{
CRITICAL_REGION_LOCAL(m_read_lock);
try
{
auto out_ptr = m_db_outputs.get_subitem(req.amount, req.i); // get_subitem can rise an out_of_range exception
if (!out_ptr)
return false;
resp.tx_id = out_ptr->tx_id;
resp.out_no = out_ptr->out_no;
return true;
}
catch (std::out_of_range&)
{
return false;
}
}
//------------------------------------------------------------------
bool blockchain_storage::get_multisig_id_details(const COMMAND_RPC_GET_MULTISIG_INFO::request& req, COMMAND_RPC_GET_MULTISIG_INFO::response & resp) const
{
CRITICAL_REGION_LOCAL(m_read_lock);
return get_multisig_id_details(req.ms_id, resp.tx_id, resp.out_no);
}
//------------------------------------------------------------------
bool blockchain_storage::get_multisig_id_details(const crypto::hash& ms_id, crypto::hash& tx_id, uint64_t& out_no) const
{
auto out_ptr = m_db_multisig_outs.get(ms_id);
if (!out_ptr)
return false;
tx_id = out_ptr->tx_id;
out_no = out_ptr->out_no;
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::get_main_block_rpc_details(uint64_t i, block_rpc_extended_info& bei) const
{
CRITICAL_REGION_LOCAL(m_read_lock);
auto core_bei_ptr = m_db_blocks[i];
crypto::hash id = get_block_hash(core_bei_ptr->bl);
bei.is_orphan = false;
bei.total_fee = 0;
bei.total_txs_size = 0;
if (true/*!ignore_transactions*/)
{
crypto::hash coinbase_id = get_transaction_hash(core_bei_ptr->bl.miner_tx);
//load transactions details
bei.transactions_details.push_back(tx_rpc_extended_info());
if (!get_tx_rpc_details(coinbase_id, bei.transactions_details.back(), get_actual_timestamp(core_bei_ptr->bl), true))
LOG_ERROR("failed to get_tx_rpc_details");
for (auto& h : core_bei_ptr->bl.tx_hashes)
{
bei.transactions_details.push_back(tx_rpc_extended_info());
if (!get_tx_rpc_details(h, bei.transactions_details.back(), get_actual_timestamp(core_bei_ptr->bl), true))
LOG_ERROR("failed to get_tx_rpc_details");
bei.total_fee += bei.transactions_details.back().fee;
bei.total_txs_size += bei.transactions_details.back().blob_size;
}
}
if (!fill_block_rpc_details(bei, *core_bei_ptr, id))
LOG_ERROR("failed to fill_block_rpc_details");
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::get_main_block_rpc_details(const crypto::hash& id, block_rpc_extended_info& bei) const
{
CRITICAL_REGION_LOCAL(m_read_lock);
uint64_t h = 0;
if (!checked_get_height_by_id(id, h))
return false;
return get_main_block_rpc_details(h, bei);
}
//------------------------------------------------------------------
bool blockchain_storage::get_alt_blocks_rpc_details(uint64_t start_offset, uint64_t count, std::vector<block_rpc_extended_info>& blocks) const
{
CRITICAL_REGION_LOCAL(m_read_lock);
CRITICAL_REGION_LOCAL1(m_alternative_chains_lock);
if (start_offset >= m_alternative_chains.size() || count == 0)
return true; // empty result
if (start_offset + count >= m_alternative_chains.size())
count = m_alternative_chains.size() - start_offset; // correct count if it's too big
// collect iterators to all the alt blocks for speedy sorting
std::vector<alt_chain_container::const_iterator> blocks_its;
blocks_its.reserve(m_alternative_chains.size());
for (alt_chain_container::const_iterator it = m_alternative_chains.begin(); it != m_alternative_chains.end(); ++it)
blocks_its.push_back(it);
// partially sort blocks by height, so only 0...(start_offset+count-1) first blocks are sorted
std::partial_sort(blocks_its.begin(), blocks_its.begin() + start_offset + count, blocks_its.end(),
[](const alt_chain_container::const_iterator &lhs, const alt_chain_container::const_iterator& rhs) ->bool {
return lhs->second.height < rhs->second.height;
}
);
// erase blocks from 0 till start_offset-1
blocks_its.erase(blocks_its.begin(), blocks_its.begin() + start_offset);
// erase the tail
blocks_its.erase(blocks_its.begin() + count, blocks_its.end());
// populate the result
blocks.reserve(blocks_its.size());
for(auto it : blocks_its)
{
blocks.push_back(block_rpc_extended_info());
if (!get_alt_block_rpc_details(it->second, it->first, blocks.back()))
LOG_ERROR("failed to get_alt_block_rpc_details");
}
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::get_alt_block_rpc_details(const crypto::hash& id, block_rpc_extended_info& bei) const
{
CRITICAL_REGION_LOCAL(m_read_lock);
CRITICAL_REGION_LOCAL1(m_alternative_chains_lock);
auto it = m_alternative_chains.find(id);
if (it == m_alternative_chains.end())
return false;
const block_extended_info& bei_core = it->second;
return get_alt_block_rpc_details(bei_core, id, bei);
}
//------------------------------------------------------------------
bool blockchain_storage::get_alt_block_rpc_details(const block_extended_info& bei_core, const crypto::hash& id, block_rpc_extended_info& bei) const
{
CRITICAL_REGION_LOCAL(m_read_lock);
CRITICAL_REGION_LOCAL1(m_alternative_chains_lock);
bei.is_orphan = true;
crypto::hash coinbase_id = get_transaction_hash(bei_core.bl.miner_tx);
//load transactions details
bei.transactions_details.push_back(tx_rpc_extended_info());
if (!fill_tx_rpc_details(bei.transactions_details.back(), bei_core.bl.miner_tx, nullptr, coinbase_id, get_actual_timestamp(bei_core.bl)))
LOG_ERROR("failed to fill_tx_rpc_details");
bei.total_fee = 0;
for (auto& h : bei_core.bl.tx_hashes)
{
bei.transactions_details.push_back(tx_rpc_extended_info());
if (!get_tx_rpc_details(h, bei.transactions_details.back(), get_actual_timestamp(bei_core.bl), true))
{
//tx not in blockchain, supposed to be in tx pool
m_tx_pool.get_transaction_details(h, bei.transactions_details.back());
}
bei.total_fee += bei.transactions_details.back().fee;
}
if (!fill_block_rpc_details(bei, bei_core, id))
LOG_ERROR("failed to fill_block_rpc_details");
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::get_main_blocks_rpc_details(uint64_t start_offset, size_t count, bool ignore_transactions, std::list<block_rpc_extended_info>& blocks) const
{
CRITICAL_REGION_LOCAL(m_read_lock);
if (start_offset >= m_db_blocks.size())
return false;
for (size_t i = start_offset; i < start_offset + count && i < m_db_blocks.size(); i++)
{
blocks.push_back(block_rpc_extended_info());
block_rpc_extended_info& bei = blocks.back();
if (!get_main_block_rpc_details(i, bei))
LOG_ERROR("failed to get_main_block_rpc_details");
}
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::get_blocks(uint64_t start_offset, size_t count, std::list<block>& blocks)const
{
CRITICAL_REGION_LOCAL(m_read_lock);
if(start_offset >= m_db_blocks.size())
return false;
for(size_t i = start_offset; i < start_offset + count && i < m_db_blocks.size();i++)
blocks.push_back(m_db_blocks[i]->bl);
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::handle_get_objects(NOTIFY_REQUEST_GET_OBJECTS::request& arg, NOTIFY_RESPONSE_GET_OBJECTS::request& rsp)const
{
CRITICAL_REGION_LOCAL(m_read_lock);
rsp.current_blockchain_height = get_current_blockchain_size();
std::list<block> blocks;
auto r = get_blocks(arg.blocks, blocks, rsp.missed_ids);
CHECK_AND_ASSERT_MES(r, false, "failed to get_blocks");
BOOST_FOREACH(const auto& bl, blocks)
{
std::list<transaction> txs;
r = get_transactions(bl.tx_hashes, txs, rsp.missed_ids);
CHECK_AND_ASSERT_MES(r && !rsp.missed_ids.size(), false, "Host have requested block with missed transactions missed_tx_id.size()=" << rsp.missed_ids.size()
<< ENDL << "for block id = " << get_block_hash(bl));
rsp.blocks.push_back(block_complete_entry());
block_complete_entry& e = rsp.blocks.back();
//pack block
e.block = t_serializable_object_to_blob(bl);
//pack transactions
BOOST_FOREACH(transaction& tx, txs)
e.txs.push_back(t_serializable_object_to_blob(tx));
}
//get another transactions, if need
std::list<transaction> txs;
r = get_transactions(arg.txs, txs, rsp.missed_ids);
CHECK_AND_ASSERT_MES(r, false, "failed to get_transactions");
//pack aside transactions
BOOST_FOREACH(const auto& tx, txs)
rsp.txs.push_back(t_serializable_object_to_blob(tx));
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::get_transactions_daily_stat(uint64_t& daily_cnt, uint64_t& daily_volume) const
{
CRITICAL_REGION_LOCAL(m_read_lock);
daily_cnt = daily_volume = 0;
for(size_t i = (m_db_blocks.size() > CURRENCY_BLOCKS_PER_DAY ? m_db_blocks.size() - CURRENCY_BLOCKS_PER_DAY:0 ); i!=m_db_blocks.size(); i++)
{
auto ptr = m_db_blocks[i];
for(auto& h : ptr->bl.tx_hashes)
{
++daily_cnt;
auto tx_ptr = m_db_transactions.find(h);
CHECK_AND_ASSERT_MES(tx_ptr, false, "Wrong transaction hash " << h << " in block on height " << i);
uint64_t am = 0;
bool r = get_inputs_money_amount(tx_ptr->tx, am);
CHECK_AND_ASSERT_MES(r, false, "failed to get_inputs_money_amount");
daily_volume += am;
}
}
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::check_keyimages(const std::list<crypto::key_image>& images, std::list<uint64_t>& images_stat) const
{
//true - unspent, false - spent
CRITICAL_REGION_LOCAL(m_read_lock);
for (auto& ki : images)
{
auto ki_ptr = m_db_spent_keys.get(ki);
if(ki_ptr)
images_stat.push_back(*ki_ptr);
else
images_stat.push_back(0);
}
return true;
}
//------------------------------------------------------------------
uint64_t blockchain_storage::get_seconds_between_last_n_block(size_t n) const
{
CRITICAL_REGION_LOCAL(m_read_lock);
if (m_db_blocks.size() <= n)
return 0;
uint64_t top_block_ts = get_actual_timestamp(m_db_blocks[m_db_blocks.size() - 1]->bl);
uint64_t n_block_ts = get_actual_timestamp(m_db_blocks[m_db_blocks.size() - 1 - n]->bl);
return top_block_ts > n_block_ts ? top_block_ts - n_block_ts : 0;
}
//------------------------------------------------------------------
uint64_t blockchain_storage::get_current_hashrate(size_t aprox_count) const
{
CRITICAL_REGION_LOCAL(m_read_lock);
if (aprox_count == 0 || m_db_blocks.size() <= aprox_count)
return 0; // incorrect parameters
uint64_t nearest_front_pow_block_i = m_db_blocks.size() - 1;
while (nearest_front_pow_block_i != 0)
{
if (!is_pos_block(m_db_blocks[nearest_front_pow_block_i]->bl))
break;
--nearest_front_pow_block_i;
}
uint64_t nearest_back_pow_block_i = m_db_blocks.size() - aprox_count;
while (nearest_back_pow_block_i != 0)
{
if (!is_pos_block(m_db_blocks[nearest_back_pow_block_i]->bl))
break;
--nearest_back_pow_block_i;
}
std::shared_ptr<const block_extended_info> front_blk_ptr = m_db_blocks[nearest_front_pow_block_i];
std::shared_ptr<const block_extended_info> back_blk_ptr = m_db_blocks[nearest_back_pow_block_i];
uint64_t front_blk_ts = front_blk_ptr->bl.timestamp;
uint64_t back_blk_ts = back_blk_ptr->bl.timestamp;
uint64_t ts_delta = front_blk_ts > back_blk_ts ? front_blk_ts - back_blk_ts : DIFFICULTY_POW_TARGET;
wide_difficulty_type w_hr = (front_blk_ptr->cumulative_diff_precise - back_blk_ptr->cumulative_diff_precise) / ts_delta;
return w_hr.convert_to<uint64_t>();
}
//------------------------------------------------------------------
bool blockchain_storage::get_alternative_blocks(std::list<block>& blocks) const
{
CRITICAL_REGION_LOCAL(m_read_lock);
CRITICAL_REGION_LOCAL1(m_alternative_chains_lock);
BOOST_FOREACH(const auto& alt_bl, m_alternative_chains)
{
blocks.push_back(alt_bl.second.bl);
}
return true;
}
//------------------------------------------------------------------
size_t blockchain_storage::get_alternative_blocks_count() const
{
CRITICAL_REGION_LOCAL(m_read_lock);
CRITICAL_REGION_LOCAL1(m_alternative_chains_lock);
return m_alternative_chains.size();
}
//------------------------------------------------------------------
bool blockchain_storage::add_out_to_get_random_outs(COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::outs_for_amount& result_outs, uint64_t amount, size_t i, uint64_t mix_count, bool use_only_forced_to_mix) const
{
CRITICAL_REGION_LOCAL(m_read_lock);
auto out_ptr = m_db_outputs.get_subitem(amount, i);
auto tx_ptr = m_db_transactions.find(out_ptr->tx_id);
CHECK_AND_ASSERT_MES(tx_ptr, false, "internal error: transaction with id " << out_ptr->tx_id << ENDL <<
", used in mounts global index for amount=" << amount << ": i=" << i << "not found in transactions index");
CHECK_AND_ASSERT_MES(tx_ptr->tx.vout.size() > out_ptr->out_no, false, "internal error: in global outs index, transaction out index="
<< out_ptr->out_no << " more than transaction outputs = " << tx_ptr->tx.vout.size() << ", for tx id = " << out_ptr->tx_id);
const transaction& tx = tx_ptr->tx;
CHECK_AND_ASSERT_MES(tx.vout[out_ptr->out_no].target.type() == typeid(txout_to_key), false, "unknown tx out type");
CHECK_AND_ASSERT_MES(tx_ptr->m_spent_flags.size() == tx.vout.size(), false, "internal error");
//do not use outputs that obviously spent for mixins
if (tx_ptr->m_spent_flags[out_ptr->out_no])
return false;
//check if transaction is unlocked
if (!is_tx_spendtime_unlocked(get_tx_unlock_time(tx)))
return false;
//use appropriate mix_attr out
uint8_t mix_attr = boost::get<txout_to_key>(tx.vout[out_ptr->out_no].target).mix_attr;
if(mix_attr == CURRENCY_TO_KEY_OUT_FORCED_NO_MIX)
return false; //COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS call means that ring signature will have more than one entry.
else if(use_only_forced_to_mix && mix_attr == CURRENCY_TO_KEY_OUT_RELAXED)
return false; //relaxed not allowed
else if(mix_attr != CURRENCY_TO_KEY_OUT_RELAXED && mix_attr > mix_count)
return false;//mix_attr set to specific minimum, and mix_count is less then desired count
COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::out_entry& oen = *result_outs.outs.insert(result_outs.outs.end(), COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::out_entry());
oen.global_amount_index = i;
oen.out_key = boost::get<txout_to_key>(tx.vout[out_ptr->out_no].target).key;
return true;
}
//------------------------------------------------------------------
size_t blockchain_storage::find_end_of_allowed_index(uint64_t amount) const
{
CRITICAL_REGION_LOCAL(m_read_lock);
uint64_t sz = m_db_outputs.get_item_size(amount);
if (!sz)
return 0;
uint64_t i = sz;
do
{
--i;
auto out_ptr = m_db_outputs.get_subitem(amount, i);
auto tx_ptr = m_db_transactions.find(out_ptr->tx_id);
CHECK_AND_ASSERT_MES(tx_ptr, 0, "internal error: failed to find transaction from outputs index with tx_id=" << out_ptr->tx_id);
if (tx_ptr->m_keeper_block_height + CURRENCY_MINED_MONEY_UNLOCK_WINDOW <= get_current_blockchain_size())
return i+1;
} while (i != 0);
return 0;
}
//------------------------------------------------------------------
bool blockchain_storage::get_random_outs_for_amounts(const COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::request& req, COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::response& res)const
{
CRITICAL_REGION_LOCAL(m_read_lock);
BOOST_FOREACH(uint64_t amount, req.amounts)
{
COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::outs_for_amount& result_outs = *res.outs.insert(res.outs.end(), COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::outs_for_amount());
result_outs.amount = amount;
uint64_t outs_container_size = m_db_outputs.get_item_size(amount);
if (!outs_container_size)
{
LOG_ERROR("COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS: not outs for amount " << amount << ", wallet should use some real outs when it lookup for some mix, so, at least one out for this amount should exist");
continue;//actually this is strange situation, wallet should use some real outs when it lookup for some mix, so, at least one out for this amount should exist
}
//it is not good idea to use top fresh outs, because it increases possibility of transaction canceling on split
//lets find upper bound of not fresh outs
size_t up_index_limit = find_end_of_allowed_index(amount);
CHECK_AND_ASSERT_MES(up_index_limit <= outs_container_size, false, "internal error: find_end_of_allowed_index returned wrong index=" << up_index_limit << ", with amount_outs.size = " << outs_container_size);
if (up_index_limit >= req.outs_count)
{
std::set<size_t> used;
size_t try_count = 0;
for(uint64_t j = 0; j != req.outs_count && try_count < up_index_limit;)
{
size_t i = crypto::rand<size_t>()%up_index_limit;
if(used.count(i))
continue;
bool added = add_out_to_get_random_outs(result_outs, amount, i, req.outs_count, req.use_forced_mix_outs);
used.insert(i);
if(added)
++j;
++try_count;
}
if (result_outs.outs.size() < req.outs_count)
{
LOG_PRINT_RED_L0("Not enough inputs for amount " << amount << ", needed " << req.outs_count << ", added " << result_outs.outs.size() << " good outs from " << up_index_limit << " unlocked of " << outs_container_size << " total");
}
}else
{
size_t added = 0;
for (size_t i = 0; i != up_index_limit; i++)
added += add_out_to_get_random_outs(result_outs, amount, i, req.outs_count, req.use_forced_mix_outs) ? 1 : 0;
LOG_PRINT_RED_L0("Not enough inputs for amount " << amount << ", needed " << req.outs_count << ", added " << added << " good outs from " << up_index_limit << " unlocked of " << outs_container_size << " total - respond with all good outs");
}
}
return true;
}
//------------------------------------------------------------------
uint64_t blockchain_storage::total_coins() const
{
CRITICAL_REGION_LOCAL(m_read_lock);
if (!m_db_blocks.size())
return 0;
return m_db_blocks.back()->already_generated_coins;
}
//------------------------------------------------------------------
bool blockchain_storage::is_pos_allowed() const
{
return get_top_block_height() >= m_core_runtime_config.pos_minimum_heigh;
}
//------------------------------------------------------------------
bool blockchain_storage::update_spent_tx_flags_for_input(uint64_t amount, const txout_v& o, bool spent)
{
if (o.type() == typeid(ref_by_id))
return update_spent_tx_flags_for_input(boost::get<ref_by_id>(o).tx_id, boost::get<ref_by_id>(o).n, spent);
else if (o.type() == typeid(uint64_t))
return update_spent_tx_flags_for_input(amount, boost::get<uint64_t>(o), spent);
LOG_ERROR("Unknown txout_v type");
return false;
}
//------------------------------------------------------------------
bool blockchain_storage::update_spent_tx_flags_for_input(uint64_t amount, uint64_t global_index, bool spent)
{
CRITICAL_REGION_LOCAL(m_read_lock);
uint64_t outs_count = m_db_outputs.get_item_size(amount);
CHECK_AND_ASSERT_MES(outs_count, false, "Amount " << amount << " have not found during update_spent_tx_flags_for_input()");
CHECK_AND_ASSERT_MES(global_index < outs_count, false, "Global index" << global_index << " for amount " << amount << " bigger value than amount's vector size()=" << outs_count);
auto out_ptr = m_db_outputs.get_subitem(amount, global_index);
return update_spent_tx_flags_for_input(out_ptr->tx_id, out_ptr->out_no, spent);
}
//------------------------------------------------------------------
bool blockchain_storage::update_spent_tx_flags_for_input(const crypto::hash& tx_id, size_t n, bool spent)
{
CRITICAL_REGION_LOCAL(m_read_lock);
auto tx_ptr = m_db_transactions.find(tx_id);
CHECK_AND_ASSERT_MES(tx_ptr, false, "Can't find transaction id: " << tx_id);
transaction_chain_entry tce_local = *tx_ptr;
CHECK_AND_ASSERT_MES(n < tce_local.m_spent_flags.size(), false, "Wrong input offset: " << n << " in transaction id: " << tx_id);
tce_local.m_spent_flags[n] = spent;
auto r = m_db_transactions.set(tx_id, tce_local);
CHECK_AND_ASSERT_MES(r, false, "failed to m_db_transactions.set");
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::update_spent_tx_flags_for_input(const crypto::hash& multisig_id, uint64_t spent_height)
{
CRITICAL_REGION_LOCAL(m_read_lock);
auto ms_ptr = m_db_multisig_outs.find(multisig_id);
CHECK_AND_ASSERT_MES(ms_ptr, false, "unable to find multisig_id " << multisig_id);
// update spent height at ms container
ms_output_entry msoe_local = *ms_ptr;
if (msoe_local.spent_height != 0 && spent_height != 0)
{
LOG_PRINT_YELLOW(LOCATION_SS << ": WARNING: ms out " << multisig_id << " was already marked as SPENT at height " << msoe_local.spent_height << ", new spent_height: " << spent_height , LOG_LEVEL_0);
}
msoe_local.spent_height = spent_height;
auto r = m_db_multisig_outs.set(multisig_id, msoe_local);
CHECK_AND_ASSERT_MES(r, false, "failed to m_db_multisig_outs.set");
return update_spent_tx_flags_for_input(ms_ptr->tx_id, ms_ptr->out_no, spent_height != 0);
}
//------------------------------------------------------------------
bool blockchain_storage::has_multisig_output(const crypto::hash& multisig_id) const
{
CRITICAL_REGION_LOCAL(m_read_lock);
return static_cast<bool>(m_db_multisig_outs.find(multisig_id));
}
//------------------------------------------------------------------
bool blockchain_storage::is_multisig_output_spent(const crypto::hash& multisig_id) const
{
CRITICAL_REGION_LOCAL(m_read_lock);
auto multisig_ptr = m_db_multisig_outs.find(multisig_id);
if (!multisig_ptr)
return false; // there's no such output - treat as not spent
const crypto::hash& source_tx_id = multisig_ptr->tx_id;
size_t ms_out_index = multisig_ptr->out_no; // index of multisig output in source tx
auto source_tx_ptr = m_db_transactions.find(source_tx_id);
CHECK_AND_ASSERT_MES(source_tx_ptr, true, "Internal error: source tx not found for ms out " << multisig_id << ", ms out is treated as spent for safety");
CHECK_AND_ASSERT_MES(ms_out_index < source_tx_ptr->m_spent_flags.size(), true, "Internal error: ms out " << multisig_id << " has incorrect index " << ms_out_index << " in source tx " << source_tx_id << ", ms out is treated as spent for safety");
return source_tx_ptr->m_spent_flags[ms_out_index];
}
//------------------------------------------------------------------
// bool blockchain_storage::resync_spent_tx_flags()
// {
// LOG_PRINT_L0("Started re-building spent tx outputs data...");
// CRITICAL_REGION_LOCAL(m_blockchain_lock);
// for(auto& tx: m_db_transactions)
// {
// if(is_coinbase(tx.second.tx))
// continue;
//
// for(auto& in: tx.second.tx.vin)
// {
// CHECKED_GET_SPECIFIC_VARIANT(in, txin_to_key, in_to_key, false);
// if(in_to_key.key_offsets.size() != 1)
// continue;
//
// //direct spending
// if(!update_spent_tx_flags_for_input(in_to_key.amount, in_to_key.key_offsets[0], true))
// return false;
//
// }
// }
// LOG_PRINT_L0("Finished re-building spent tx outputs data");
// return true;
// }
//------------------------------------------------------------------
bool blockchain_storage::find_blockchain_supplement(const std::list<crypto::hash>& qblock_ids, uint64_t& starter_offset) const
{
CRITICAL_REGION_LOCAL(m_read_lock);
starter_offset = 0;
if (!qblock_ids.size() /*|| !req.m_total_height*/)
{
LOG_PRINT_RED_L0("Client sent wrong NOTIFY_REQUEST_CHAIN: m_block_ids.size()=" << qblock_ids.size() << /*", m_height=" << req.m_total_height <<*/ ", dropping connection");
return false;
}
//check genesis match
const auto genesis_hash = get_block_hash(m_db_blocks[0]->bl);
if (qblock_ids.back() != genesis_hash)
{
LOG_ERROR("Client sent wrong NOTIFY_REQUEST_CHAIN: genesis block missmatch: " << ENDL << "id: "
<< string_tools::pod_to_hex(qblock_ids.back()) << ", " << ENDL << "expected: " << genesis_hash
<< "," << ENDL << " dropping connection");
return false;
}
/* Figure out what blocks we should request to get state_normal */
for (const auto& bl_id: qblock_ids)
{
uint64_t h = 0;
if (checked_get_height_by_id(bl_id, h))
{
//we start to put block ids INCLUDING last known id, just to make other side be sure
starter_offset = h;
return true;
}
}
LOG_ERROR("Internal error handling connection, can't find split point");
return false;
}
//------------------------------------------------------------------
wide_difficulty_type blockchain_storage::block_difficulty(size_t i) const
{
CRITICAL_REGION_LOCAL(m_read_lock);
CHECK_AND_ASSERT_MES(i < m_db_blocks.size(), false, "wrong block index i = " << i << " at blockchain_storage::block_difficulty()");
return m_db_blocks[i]->difficulty;
}
//------------------------------------------------------------------
bool blockchain_storage::forecast_difficulty(std::vector<std::pair<uint64_t, wide_difficulty_type>> &out_height_2_diff_vector, bool pos) const
{
CRITICAL_REGION_LOCAL(m_read_lock);
std::vector<uint64_t> timestamps;
std::vector<wide_difficulty_type> cumulative_difficulties;
uint64_t blocks_size = m_db_blocks.size();
size_t count = 0;
uint64_t max_block_height_for_this_type = 0;
uint64_t min_block_height_for_this_type = UINT64_MAX;
wide_difficulty_type last_block_diff_for_this_type = 0;
timestamps.reserve(DIFFICULTY_WINDOW);
cumulative_difficulties.reserve(DIFFICULTY_WINDOW);
for (uint64_t cur_ind = blocks_size - 1; cur_ind != 0 && count < DIFFICULTY_WINDOW; cur_ind--)
{
auto beiptr = m_db_blocks[cur_ind];
bool is_pos_bl = is_pos_block(beiptr->bl);
if (pos != is_pos_bl)
continue;
if (max_block_height_for_this_type < beiptr->height)
max_block_height_for_this_type = beiptr->height;
if (min_block_height_for_this_type > beiptr->height)
min_block_height_for_this_type = beiptr->height;
if (last_block_diff_for_this_type == 0)
last_block_diff_for_this_type = beiptr->difficulty;
timestamps.push_back(beiptr->bl.timestamp);
cumulative_difficulties.push_back(beiptr->cumulative_diff_precise);
++count;
}
if (count != DIFFICULTY_WINDOW)
return false;
const uint64_t target_seconds = pos ? DIFFICULTY_POS_TARGET : DIFFICULTY_POW_TARGET;
const uint64_t avg_interval = std::max(static_cast<uint64_t>(1), (max_block_height_for_this_type - min_block_height_for_this_type) / count);
uint64_t height = max_block_height_for_this_type;
out_height_2_diff_vector.clear();
out_height_2_diff_vector.reserve(DIFFICULTY_CUT + 1);
out_height_2_diff_vector.push_back(std::make_pair(height, last_block_diff_for_this_type)); // the first element corresponds to the last block of this type
for (size_t i = 0; i < DIFFICULTY_CUT; ++i)
{
wide_difficulty_type diff = next_difficulty(timestamps, cumulative_difficulties, target_seconds); /// TODO: check
height += avg_interval;
out_height_2_diff_vector.push_back(std::make_pair(height, diff));
timestamps.pop_back(); // keep sorted in descending order
timestamps.insert(timestamps.begin(), timestamps.front() + target_seconds); // increment time so it won't be affected by sorting in next_difficulty
cumulative_difficulties.pop_back();
cumulative_difficulties.insert(cumulative_difficulties.begin(), 0); // does not matter
}
return true;
}
//------------------------------------------------------------------
size_t blockchain_storage::get_current_sequence_factor(bool pos) const
{
size_t n = 0;
CRITICAL_REGION_LOCAL(m_read_lock);
uint64_t sz = m_db_blocks.size();
if (!sz)
return n;
for (uint64_t i = sz - 1; i != 0; --i, n++)
{
if (pos != is_pos_block(m_db_blocks[i]->bl))
break;
}
return n;
}
//------------------------------------------------------------------
size_t blockchain_storage::get_current_sequence_factor_for_alt(alt_chain_type& alt_chain, bool pos, uint64_t connection_height) const
{
size_t n = 0;
for (auto it = alt_chain.rbegin(); it != alt_chain.rend(); it++, n++)
{
if (pos != is_pos_block((*it)->second.bl))
return n;
}
CRITICAL_REGION_LOCAL(m_read_lock);
for (uint64_t h = connection_height - 1; h != 0; --h, n++)
{
if (pos != is_pos_block(m_db_blocks[h]->bl))
{
return n;
}
}
return n;
}
//------------------------------------------------------------------
std::string blockchain_storage::get_blockchain_string(uint64_t start_index, uint64_t end_index) const
{
std::stringstream ss;
CRITICAL_REGION_LOCAL(m_read_lock);
if (start_index >= m_db_blocks.size())
{
LOG_PRINT_L0("Wrong starter index set: " << start_index << ", expected max index " << m_db_blocks.size() - 1);
return ss.str();
}
for (size_t i = start_index; i != m_db_blocks.size() && i != end_index; i++)
{
ss << (is_pos_block(m_db_blocks[i]->bl) ? "[PoS]" : "[PoW]") << "h: " << i << ", timestamp: " << m_db_blocks[i]->bl.timestamp << "(" << epee::misc_utils::get_time_str_v2(m_db_blocks[i]->bl.timestamp) << ")"
<< ", cumul_diff_adj: " << m_db_blocks[i]->cumulative_diff_adjusted
<< ", cumul_diff_pcs: " << m_db_blocks[i]->cumulative_diff_precise
<< ", cumul_size: " << m_db_blocks[i]->block_cumulative_size
<< ", id: " << get_block_hash(m_db_blocks[i]->bl)
<< ", difficulty: " << block_difficulty(i) << ", nonce " << m_db_blocks[i]->bl.nonce << ", tx_count " << m_db_blocks[i]->bl.tx_hashes.size() << ENDL;
}
return ss.str();
}
//------------------------------------------------------------------
void blockchain_storage::print_blockchain(std::ostream &s, uint64_t start_index, uint64_t end_index) const
{
//LOG_ERROR("NOT IMPLEMENTED YET");
s << "Current blockchain:" << ENDL << get_blockchain_string(start_index, end_index);
s << "Blockchain printed with log level 1";
}
void blockchain_storage::print_blockchain_with_tx(uint64_t start_index, uint64_t end_index) const
{
boost::filesystem::ofstream ss;
ss.exceptions(/*std::ifstream::failbit |*/ std::ifstream::badbit);
std::wstring log_file_path = epee::string_encoding::utf8_to_wstring(log_space::log_singletone::get_default_log_folder() + "/blockchain_with_tx.txt");
ss.open(log_file_path, std::ios_base::binary | std::ios_base::out | std::ios_base::trunc);
CRITICAL_REGION_LOCAL(m_read_lock);
if (start_index >= m_db_blocks.size())
{
LOG_PRINT_L0("Wrong starter index set: " << start_index << ", expected max index " << m_db_blocks.size() - 1);
return;
}
for (size_t i = start_index; i != m_db_blocks.size() && i != end_index; i++)
{
ss << (is_pos_block(m_db_blocks[i]->bl) ? "[PoS]" : "[PoW]") << "h: " << i << ", timestamp: " << m_db_blocks[i]->bl.timestamp << "(" << epee::misc_utils::get_time_str_v2(m_db_blocks[i]->bl.timestamp) << ")"
<< ", cumul_diff_adj: " << m_db_blocks[i]->cumulative_diff_adjusted
<< ", cumul_diff_pcs: " << m_db_blocks[i]->cumulative_diff_precise
<< ", cumul_size: " << m_db_blocks[i]->block_cumulative_size
<< ", id: " << get_block_hash(m_db_blocks[i]->bl)
<< ", difficulty: " << block_difficulty(i) << ", nonce " << m_db_blocks[i]->bl.nonce << ", tx_count " << m_db_blocks[i]->bl.tx_hashes.size() << ENDL;
ss << "[miner id]: " << get_transaction_hash(m_db_blocks[i]->bl.miner_tx) << ENDL << currency::obj_to_json_str(m_db_blocks[i]->bl.miner_tx) << ENDL;
for (size_t j = 0; j != m_db_blocks[i]->bl.tx_hashes.size(); j++)
{
auto tx_it = m_db_transactions.find(m_db_blocks[i]->bl.tx_hashes[j]);
if (tx_it == m_db_transactions.end())
{
LOG_ERROR("internal error: tx id " << m_db_blocks[i]->bl.tx_hashes[j] << " not found in transactions index");
continue;
}
ss << "[id]:" << m_db_blocks[i]->bl.tx_hashes[j] << ENDL << currency::obj_to_json_str(tx_it->tx) << ENDL;
}
}
ss.close();
}
//------------------------------------------------------------------
void blockchain_storage::print_blockchain_index() const
{
LOG_ERROR("NOT IMPLEMENTED YET");
// std::stringstream ss;
// CRITICAL_REGION_LOCAL(m_blockchain_lock);
// BOOST_FOREACH(const blocks_by_id_index::value_type& v, m_db_blocks_index)
// ss << "id\t\t" << v.first << " height" << v.second << ENDL << "";
//
// LOG_PRINT_L0("Current blockchain index:" << ENDL << ss.str());
}
//------------------------------------------------------------------
void blockchain_storage::print_db_cache_perfeormance_data(std::ostream &s) const
{
#define DB_CONTAINER_PERF_DATA_ENTRY(container_name) \
<< #container_name << ": hit_percent: " << m_db_blocks.get_performance_data().hit_percent.get_avg() << "%," \
<< " read_cache: " << container_name.get_performance_data().read_cache_microsec.get_avg() \
<< " read_db: " << container_name.get_performance_data().read_db_microsec.get_avg() \
<< " upd_cache: " << container_name.get_performance_data().update_cache_microsec.get_avg() \
<< " write_cache: " << container_name.get_performance_data().write_to_cache_microsec.get_avg() \
<< " write_db: " << container_name.get_performance_data().write_to_db_microsec.get_avg() \
<< " native_db_set_t: " << container_name.get_performance_data_native().backend_set_t_time.get_avg() \
<< " native_db_set_pod: " << container_name.get_performance_data_native().backend_set_pod_time.get_avg() \
<< " native_db_seriz: " << container_name.get_performance_data_native().set_serialize_t_time.get_avg()
s << "DB_PERFORMANCE_DATA: " << ENDL
DB_CONTAINER_PERF_DATA_ENTRY(m_db_blocks) << ENDL
DB_CONTAINER_PERF_DATA_ENTRY(m_db_blocks_index) << ENDL
DB_CONTAINER_PERF_DATA_ENTRY(m_db_transactions) << ENDL
DB_CONTAINER_PERF_DATA_ENTRY(m_db_spent_keys) << ENDL
//DB_CONTAINER_PERF_DATA_ENTRY(m_db_outputs) << ENDL
DB_CONTAINER_PERF_DATA_ENTRY(m_db_multisig_outs) << ENDL
DB_CONTAINER_PERF_DATA_ENTRY(m_db_solo_options) << ENDL
DB_CONTAINER_PERF_DATA_ENTRY(m_db_aliases) << ENDL
DB_CONTAINER_PERF_DATA_ENTRY(m_db_addr_to_alias) << ENDL
//DB_CONTAINER_PERF_DATA_ENTRY(m_db_per_block_gindex_incs) << ENDL
//DB_CONTAINER_PERF_DATA_ENTRY(m_tx_fee_median) << ENDL
;
}
//------------------------------------------------------------------
void blockchain_storage::print_blockchain_outs_stat() const
{
LOG_ERROR("NOT IMPLEMENTED YET");
// std::stringstream ss;
// CRITICAL_REGION_LOCAL(m_blockchain_lock);
// BOOST_FOREACH(const outputs_container::value_type& v, m_db_outputs)
// {
// const std::vector<std::pair<crypto::hash, size_t> >& vals = v.second;
// if (vals.size())
// {
// ss << "amount: " << print_money(v.first);
// uint64_t total_count = vals.size();
// uint64_t unused_count = 0;
// for (size_t i = 0; i != vals.size(); i++)
// {
// bool used = false;
// auto it_tx = m_db_transactions.find(vals[i].first);
// if (it_tx == m_db_transactions.end())
// {
// LOG_ERROR("Tx with id not found " << vals[i].first);
// }
// else
// {
// if (vals[i].second >= it_tx->second.m_spent_flags.size())
// {
// LOG_ERROR("Tx with id " << vals[i].first << " in global index have wrong entry in global index, offset in tx = " << vals[i].second
// << ", it_tx->second.m_spent_flags.size()=" << it_tx->second.m_spent_flags.size()
// << ", it_tx->second.tx.vin.size()=" << it_tx->second.tx.vin.size());
// }
// used = it_tx->second.m_spent_flags[vals[i].second];
//
// }
// if (!used)
// ++unused_count;
// }
// ss << "\t total: " << total_count << "\t unused: " << unused_count << ENDL;
// }
// }
// LOG_PRINT_L0("OUTS: " << ENDL << ss.str());
}
//------------------------------------------------------------------
void blockchain_storage::print_blockchain_outs(const std::string& file) const
{
LOG_ERROR("NOT IMPLEMENTED YET");
// std::stringstream ss;
// CRITICAL_REGION_LOCAL(m_blockchain_lock);
// BOOST_FOREACH(const outputs_container::value_type& v, m_db_outputs)
// {
// const std::vector<std::pair<crypto::hash, size_t> >& vals = v.second;
// if(vals.size())
// {
// ss << "amount: " << print_money(v.first) << ENDL;
// for (size_t i = 0; i != vals.size(); i++)
// {
// bool used = false;
// auto it_tx = m_db_transactions.find(vals[i].first);
// if (it_tx == m_db_transactions.end())
// {
// LOG_ERROR("Tx with id not found " << vals[i].first);
// }
// else
// {
// if (vals[i].second >= it_tx->second.m_spent_flags.size())
// {
// LOG_ERROR("Tx with id " << vals[i].first << " in global index have wrong entry in global index, offset in tx = " << vals[i].second
// << ", it_tx->second.m_spent_flags.size()=" << it_tx->second.m_spent_flags.size()
// << ", it_tx->second.tx.vin.size()=" << it_tx->second.tx.vin.size());
// }
// used = it_tx->second.m_spent_flags[vals[i].second];
// }
//
// ss << "\t" << vals[i].first << ": " << vals[i].second << ",used:" << used << ENDL;
// }
// }
// }
// if(file_io_utils::save_string_to_file(file, ss.str()))
// {
// LOG_PRINT_L0("Current outputs index writen to file: " << file);
// }else
// {
// LOG_PRINT_L0("Failed to write current outputs index to file: " << file);
// }
}
//------------------------------------------------------------------
//------------------------------------------------------------------
bool blockchain_storage::find_blockchain_supplement(const std::list<crypto::hash>& qblock_ids, NOTIFY_RESPONSE_CHAIN_ENTRY::request& resp)const
{
CRITICAL_REGION_LOCAL(m_read_lock);
if(!find_blockchain_supplement(qblock_ids, resp.start_height))
return false;
resp.total_height = get_current_blockchain_size();
size_t count = 0;
block_context_info* pprevinfo = nullptr;
size_t i = 0;
for (i = resp.start_height; i != m_db_blocks.size() && count < BLOCKS_IDS_SYNCHRONIZING_DEFAULT_COUNT; i++, count++)
{
resp.m_block_ids.push_back(block_context_info());
if (pprevinfo)
pprevinfo->h = m_db_blocks[i]->bl.prev_id;
resp.m_block_ids.back().cumul_size = m_db_blocks[i]->block_cumulative_size;
pprevinfo = &resp.m_block_ids.back();
}
if (pprevinfo)
pprevinfo->h = get_block_hash(m_db_blocks[--i]->bl);
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::find_blockchain_supplement(const std::list<crypto::hash>& qblock_ids, std::list<std::pair<block, std::list<transaction> > >& blocks, uint64_t& total_height, uint64_t& start_height, size_t max_count)const
{
CRITICAL_REGION_LOCAL(m_read_lock);
blocks_direct_container blocks_direct;
if (!find_blockchain_supplement(qblock_ids, blocks_direct, total_height, start_height, max_count))
return false;
for (auto& bd : blocks_direct)
{
blocks.push_back(std::pair<block, std::list<transaction> >());
blocks.back().first = bd.first->bl;
for (auto& tx_ptr : bd.second)
{
blocks.back().second.push_back(tx_ptr->tx);
}
}
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::find_blockchain_supplement(const std::list<crypto::hash>& qblock_ids, blocks_direct_container& blocks, uint64_t& total_height, uint64_t& start_height, size_t max_count)const
{
CRITICAL_REGION_LOCAL(m_read_lock);
if (qblock_ids.empty())
start_height = 0;
else if (!find_blockchain_supplement(qblock_ids, start_height))
return false;
total_height = get_current_blockchain_size();
size_t count = 0;
for (size_t i = start_height; i < m_db_blocks.size() && count < max_count; i++, count++)
{
blocks.resize(blocks.size() + 1);
blocks.back().first = m_db_blocks[i];
std::list<crypto::hash> mis;
auto r = get_transactions_direct(m_db_blocks[i]->bl.tx_hashes, blocks.back().second, mis);
CHECK_AND_ASSERT_MES(r && !mis.size(), false, "internal error, transaction from block not found");
}
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::add_block_as_invalid(const block& bl, const crypto::hash& h)
{
block_extended_info bei = AUTO_VAL_INIT(bei);
bei.bl = bl;
return add_block_as_invalid(bei, h);
}
//------------------------------------------------------------------
bool blockchain_storage::add_block_as_invalid(const block_extended_info& bei, const crypto::hash& h)
{
CRITICAL_REGION_LOCAL(m_read_lock);
CRITICAL_REGION_LOCAL1(m_invalid_blocks_lock);
auto i_res = m_invalid_blocks.insert(std::map<crypto::hash, block_extended_info>::value_type(h, bei));
CHECK_AND_ASSERT_MES(i_res.second, false, "at insertion invalid by tx returned status existed");
LOG_PRINT_L0("BLOCK ADDED AS INVALID: " << h << ENDL << ", prev_id=" << bei.bl.prev_id << ", m_invalid_blocks count=" << m_invalid_blocks.size());
CHECK_AND_ASSERT_MES(validate_blockchain_prev_links(), false, "EPIC FAIL!");
return true;
}
//------------------------------------------------------------------
void blockchain_storage::inspect_blocks_index()const
{
CRITICAL_REGION_LOCAL(m_read_lock);
LOG_PRINT_L0("Started block index inspecting....");
m_db_blocks_index.enumerate_items([&](uint64_t count, const crypto::hash& id, uint64_t index)
{
CHECK_AND_ASSERT_MES(index < m_db_blocks.size(), true, "invalid index " << index << "(m_db_blocks.size()=" << m_db_blocks.size() << ") for id " << id << " ");
crypto::hash calculated_id = get_block_hash(m_db_blocks[index]->bl);
CHECK_AND_ASSERT_MES(id == calculated_id, true, "ID MISSMATCH ON INDEX " << index << ENDL
<< "m_db_blocks_index keeps: " << id << ENDL
<< "referenced to block with id " << calculated_id
);
return true;
});
LOG_PRINT_L0("Block index inspecting finished");
}
//------------------------------------------------------------------
bool blockchain_storage::have_block(const crypto::hash& id)const
{
CRITICAL_REGION_LOCAL(m_read_lock);
if(m_db_blocks_index.find(id))
return true;
{
CRITICAL_REGION_LOCAL1(m_alternative_chains_lock);
if (m_alternative_chains.count(id))
return true;
}
/*if(m_orphaned_blocks.get<by_id>().count(id))
return true;*/
/*if(m_orphaned_by_tx.count(id))
return true;*/
{
CRITICAL_REGION_LOCAL1(m_invalid_blocks_lock);
if (m_invalid_blocks.count(id))
return true;
}
return false;
}
//------------------------------------------------------------------
bool blockchain_storage::handle_block_to_main_chain(const block& bl, block_verification_context& bvc)
{
crypto::hash id = get_block_hash(bl);
return handle_block_to_main_chain(bl, id, bvc);
}
//------------------------------------------------------------------
bool blockchain_storage::push_transaction_to_global_outs_index(const transaction& tx, const crypto::hash& tx_id, std::vector<uint64_t>& global_indexes)
{
CRITICAL_REGION_LOCAL(m_read_lock);
size_t i = 0;
BOOST_FOREACH(const auto& ot, tx.vout)
{
if (ot.target.type() == typeid(txout_to_key))
{
m_db_outputs.push_back_item(ot.amount, global_output_entry::construct(tx_id, i));
global_indexes.push_back(m_db_outputs.get_item_size(ot.amount) - 1);
}
else if (ot.target.type() == typeid(txout_multisig))
{
crypto::hash multisig_out_id = get_multisig_out_id(tx, i);
CHECK_AND_ASSERT_MES(multisig_out_id != null_hash, false, "internal error during handling get_multisig_out_id() with tx id " << tx_id);
CHECK_AND_ASSERT_MES(!m_db_multisig_outs.find(multisig_out_id), false, "Internal error: already have multisig_out_id " << multisig_out_id << "in multisig outs index");
if (!m_db_multisig_outs.set(multisig_out_id, ms_output_entry::construct(tx_id, i)))
LOG_ERROR("failed to m_db_multisig_outs.set");
global_indexes.push_back(0); // just stub to make other code easier
}
++i;
}
return true;
}
//------------------------------------------------------------------
size_t blockchain_storage::get_total_transactions()const
{
CRITICAL_REGION_LOCAL(m_read_lock);
return m_db_transactions.size();
}
//------------------------------------------------------------------
bool blockchain_storage::get_outs(uint64_t amount, std::list<crypto::public_key>& pkeys)const
{
CRITICAL_REGION_LOCAL(m_read_lock);
uint64_t sz = m_db_outputs.get_item_size(amount);
if (!sz)
return true;
for (uint64_t i = 0; i != sz; i++)
{
auto out_entry_ptr = m_db_outputs.get_subitem(amount, i);
auto tx_ptr = m_db_transactions.find(out_entry_ptr->tx_id);
CHECK_AND_ASSERT_MES(tx_ptr, false, "transactions outs global index consistency broken: can't find tx " << out_entry_ptr->tx_id << " in DB, for amount: " << amount << ", gindex: " << i);
CHECK_AND_ASSERT_MES(tx_ptr->tx.vout.size() > out_entry_ptr->out_no, false, "transactions outs global index consistency broken: index in tx_outx == " << out_entry_ptr->out_no << " is greather than tx.vout size == " << tx_ptr->tx.vout.size() << ", for amount: " << amount << ", gindex: " << i);
CHECK_AND_ASSERT_MES(tx_ptr->tx.vout[out_entry_ptr->out_no].target.type() == typeid(txout_to_key), false, "transactions outs global index consistency broken: out #" << out_entry_ptr->out_no << " in tx " << out_entry_ptr->tx_id << " has wrong type, for amount: " << amount << ", gindex: " << i);
pkeys.push_back(boost::get<txout_to_key>(tx_ptr->tx.vout[out_entry_ptr->out_no].target).key);
}
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::pop_transaction_from_global_index(const transaction& tx, const crypto::hash& tx_id)
{
CRITICAL_REGION_LOCAL(m_read_lock);
size_t i = tx.vout.size()-1;
BOOST_REVERSE_FOREACH(const auto& ot, tx.vout)
{
if (ot.target.type() == typeid(txout_to_key))
{
uint64_t sz= m_db_outputs.get_item_size(ot.amount);
CHECK_AND_ASSERT_MES(sz, false, "transactions outs global index: empty index for amount: " << ot.amount);
auto back_item = m_db_outputs.get_subitem(ot.amount, sz - 1);
CHECK_AND_ASSERT_MES(back_item->tx_id == tx_id, false, "transactions outs global index consistency broken: tx id missmatch");
CHECK_AND_ASSERT_MES(back_item->out_no == i, false, "transactions outs global index consistency broken: in transaction index missmatch");
m_db_outputs.pop_back_item(ot.amount);
//do not let to exist empty m_outputs entries - this will broke scratchpad selector
//if (!it->second.size())
// m_db_outputs.erase(it);
}
else if (ot.target.type() == typeid(txout_multisig))
{
crypto::hash multisig_out_id = get_multisig_out_id(tx, i);
CHECK_AND_ASSERT_MES(multisig_out_id != null_hash, false, "internal error during handling get_multisig_out_id() with tx id " << tx_id);
bool res = m_db_multisig_outs.erase_validate(multisig_out_id);
CHECK_AND_ASSERT_MES(res, false, "Internal error: multisig out not found, multisig_out_id " << multisig_out_id << "in multisig outs index");
}
--i;
}
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::unprocess_blockchain_tx_extra(const transaction& tx)
{
tx_extra_info ei = AUTO_VAL_INIT(ei);
bool r = parse_and_validate_tx_extra(tx, ei);
CHECK_AND_ASSERT_MES(r, false, "failed to validate transaction extra on unprocess_blockchain_tx_extra");
if(ei.m_alias.m_alias.size())
{
r = pop_alias_info(ei.m_alias);
CHECK_AND_ASSERT_MES(r, false, "failed to pop_alias_info");
}
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::get_alias_info(const std::string& alias, extra_alias_entry_base& info)const
{
CRITICAL_REGION_LOCAL(m_read_lock);
auto al_ptr = m_db_aliases.find(alias);
if (al_ptr)
{
if (al_ptr->size())
{
info = al_ptr->back();
return true;
}
}
return false;
}
//------------------------------------------------------------------
uint64_t blockchain_storage::get_aliases_count() const
{
CRITICAL_REGION_LOCAL(m_read_lock);
return m_db_aliases.size();
}
//------------------------------------------------------------------
std::string blockchain_storage::get_alias_by_address(const account_public_address& addr)const
{
auto alias_ptr = m_db_addr_to_alias.find(addr);
if (alias_ptr && alias_ptr->size())
{
return *(alias_ptr->begin());
}
return "";
}
//------------------------------------------------------------------
bool blockchain_storage::pop_alias_info(const extra_alias_entry& ai)
{
CRITICAL_REGION_LOCAL(m_read_lock);
CHECK_AND_ASSERT_MES(ai.m_alias.size(), false, "empty name in pop_alias_info");
auto alias_history_ptr = m_db_aliases.find(ai.m_alias);
CHECK_AND_ASSERT_MES(alias_history_ptr && alias_history_ptr->size(), false, "empty name list in pop_alias_info");
auto addr_to_alias_ptr = m_db_addr_to_alias.find(alias_history_ptr->back().m_address);
if (addr_to_alias_ptr)
{
//update db
address_to_aliases_container::t_value_type local_v = *addr_to_alias_ptr;
auto it_in_set = local_v.find(ai.m_alias);
CHECK_AND_ASSERT_MES(it_in_set != local_v.end(), false, "it_in_set != it->second.end() validation failed");
local_v.erase(it_in_set);
if (!local_v.size())
{
//delete the whole record from db
m_db_addr_to_alias.erase(alias_history_ptr->back().m_address);
}
else
{
//update db
auto r = m_db_addr_to_alias.set(alias_history_ptr->back().m_address, local_v);
CHECK_AND_ASSERT_MES(r, false, "failed to m_db_addr_to_alias.set");
}
}
else
{
LOG_ERROR("In m_addr_to_alias not found " << get_account_address_as_str(alias_history_ptr->back().m_address));
}
aliases_container::t_value_type local_alias_hist = *alias_history_ptr;
local_alias_hist.pop_back();
if(local_alias_hist.size())
{
auto r = m_db_aliases.set(ai.m_alias, local_alias_hist);
CHECK_AND_ASSERT_MES(r, false, "failed to m_db_aliases.set");
}
else
m_db_aliases.erase(ai.m_alias);
if (local_alias_hist.size())
{
address_to_aliases_container::t_value_type local_copy = AUTO_VAL_INIT(local_copy);
auto set_ptr = m_db_addr_to_alias.get(local_alias_hist.back().m_address);
if (set_ptr)
local_copy = *set_ptr;
local_copy.insert(ai.m_alias);
auto r = m_db_addr_to_alias.set(local_alias_hist.back().m_address, local_copy);
CHECK_AND_ASSERT_MES(r, false, "failed to m_db_addr_to_alias.set");
}
LOG_PRINT_MAGENTA("[ALIAS_UNREGISTERED]: " << ai.m_alias << ": " << get_account_address_as_str(ai.m_address) << " -> " << (!local_alias_hist.empty() ? get_account_address_as_str(local_alias_hist.back().m_address) : "(available)"), LOG_LEVEL_1);
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::put_alias_info(const transaction & tx, extra_alias_entry & ai)
{
CRITICAL_REGION_LOCAL(m_read_lock);
CHECK_AND_ASSERT_MES(ai.m_alias.size(), false, "empty name in put_alias_info");
aliases_container::t_value_type local_alias_history = AUTO_VAL_INIT(local_alias_history);
auto alias_history_ptr_ = m_db_aliases.get(ai.m_alias);
if (alias_history_ptr_)
local_alias_history = *alias_history_ptr_;
if (!local_alias_history.size())
{
//update alias entry in db
local_alias_history.push_back(ai);
auto r = m_db_aliases.set(ai.m_alias, local_alias_history);
CHECK_AND_ASSERT_MES(r, false, "failed to m_db_aliases.set");
//update addr-to-alias db entry
address_to_aliases_container::t_value_type addr_to_alias_local = AUTO_VAL_INIT(addr_to_alias_local);
auto addr_to_alias_ptr_ = m_db_addr_to_alias.get(local_alias_history.back().m_address);
if (addr_to_alias_ptr_)
addr_to_alias_local = *addr_to_alias_ptr_;
addr_to_alias_local.insert(ai.m_alias);
r = m_db_addr_to_alias.set(local_alias_history.back().m_address, addr_to_alias_local);
CHECK_AND_ASSERT_MES(r, false, "failed to m_db_addr_to_alias.set");
//@@ remove get_tx_fee_median();
LOG_PRINT_MAGENTA("[ALIAS_REGISTERED]: " << ai.m_alias << ": " << get_account_address_as_str(ai.m_address) << ", fee median: " << get_tx_fee_median(), LOG_LEVEL_1);
rise_core_event(CORE_EVENT_ADD_ALIAS, alias_info_to_rpc_alias_info(ai));
}else
{
//update procedure
CHECK_AND_ASSERT_MES(ai.m_sign.size() == 1, false, "alias " << ai.m_alias << " can't be update, wrong ai.m_sign.size() count: " << ai.m_sign.size());
//std::string signed_buff;
//make_tx_extra_alias_entry(signed_buff, ai, true);
std::string old_address = currency::get_account_address_as_str(local_alias_history.back().m_address);
bool r = crypto::check_signature(get_sign_buff_hash_for_alias_update(ai), local_alias_history.back().m_address.m_spend_public_key, ai.m_sign.back());
CHECK_AND_ASSERT_MES(r, false, "Failed to check signature, alias update failed." << ENDL
<< "alias: " << ai.m_alias << ENDL
<< "signed_buff_hash: " << get_sign_buff_hash_for_alias_update(ai) << ENDL
<< "public key: " << local_alias_history.back().m_address.m_spend_public_key << ENDL
<< "new_address: " << get_account_address_as_str(ai.m_address) << ENDL
<< "signature: " << epee::string_tools::pod_to_hex(ai.m_sign) << ENDL
<< "alias_history.size() = " << local_alias_history.size());
//update adr-to-alias db
auto addr_to_alias_ptr_ = m_db_addr_to_alias.find(local_alias_history.back().m_address);
if (addr_to_alias_ptr_)
{
address_to_aliases_container::t_value_type addr_to_alias_local = *addr_to_alias_ptr_;
auto it_in_set = addr_to_alias_local.find(ai.m_alias);
if (it_in_set == addr_to_alias_local.end())
{
LOG_ERROR("it_in_set == it->second.end()");
}
else
{
addr_to_alias_local.erase(it_in_set);
}
if (!addr_to_alias_local.size())
m_db_addr_to_alias.erase(local_alias_history.back().m_address);
else
{
r = m_db_addr_to_alias.set(local_alias_history.back().m_address, addr_to_alias_local);
CHECK_AND_ASSERT_MES(r, false, "failed to m_db_addr_to_alias.set");
}
}
else
{
LOG_ERROR("Wrong m_addr_to_alias state: address not found " << get_account_address_as_str(local_alias_history.back().m_address));
}
//update alias db
local_alias_history.push_back(ai);
r = m_db_aliases.set(ai.m_alias, local_alias_history);
CHECK_AND_ASSERT_MES(r, false, "failed to m_db_aliases.set");
//update addr_to_alias db
address_to_aliases_container::t_value_type addr_to_alias_local2 = AUTO_VAL_INIT(addr_to_alias_local2);
auto addr_to_alias_ptr_2 = m_db_addr_to_alias.get(local_alias_history.back().m_address);
if (addr_to_alias_ptr_2)
addr_to_alias_local2 = *addr_to_alias_ptr_2;
addr_to_alias_local2.insert(ai.m_alias);
r = m_db_addr_to_alias.set(local_alias_history.back().m_address, addr_to_alias_local2);
CHECK_AND_ASSERT_MES(r, false, "failed to m_db_addr_to_alias.set");
LOG_PRINT_MAGENTA("[ALIAS_UPDATED]: " << ai.m_alias << ": from: " << old_address << " to " << get_account_address_as_str(ai.m_address), LOG_LEVEL_1);
rise_core_event(CORE_EVENT_UPDATE_ALIAS, alias_info_to_rpc_update_alias_info(ai, old_address));
}
return true;
}
//------------------------------------------------------------------
uint64_t blockchain_storage::validate_alias_reward(const transaction& tx, const std::string& alias) const
{
//validate alias cost
uint64_t fee_for_alias = get_alias_cost(alias);
//validate the price had been paid
uint64_t found_alias_reward = get_amount_for_zero_pubkeys(tx);
//@#@
//work around for net 68's generation
#if CURRENCY_FORMATION_VERSION == 68
if (alias == "bhrfrrrtret" && get_transaction_hash(tx) == epee::string_tools::parse_tpod_from_hex_string<crypto::hash>("760b85546678d2235a1843e18d8a016a2e4d9b8273cc4d7c09bebff1f6fa7eaf") )
return true;
if (alias == "test-420" && get_transaction_hash(tx) == epee::string_tools::parse_tpod_from_hex_string<crypto::hash>("10f8a2539b2551bd0919bf7e3b1dfbae7553eca63e58cd2264ae60f90030edf8"))
return true;
#endif
CHECK_AND_ASSERT_MES(found_alias_reward >= fee_for_alias, false, "registration of alias '"
<< alias << "' goes with a reward of " << print_money(found_alias_reward) << " which is less than expected: " << print_money(fee_for_alias)
<<"(fee median: " << get_tx_fee_median() << ")"
<< ", tx: " << get_transaction_hash(tx));
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::prevalidate_alias_info(const transaction& tx, extra_alias_entry& eae)
{
bool r = validate_alias_name(eae.m_alias);
CHECK_AND_ASSERT_MES(r, false, "failed to validate alias name!");
bool already_have_alias = false;
{
CRITICAL_REGION_LOCAL(m_read_lock);
auto existing_ptr = m_db_aliases.find(eae.m_alias);
if (existing_ptr && existing_ptr->size())
{
already_have_alias = true;
}
}
//auto alias_history_ptr_ = m_db_aliases.get(eae.m_alias);
if (!already_have_alias)
{
bool r = validate_alias_reward(tx, eae.m_alias);
CHECK_AND_ASSERT_MES(r, false, "failed to validate_alias_reward");
if (eae.m_alias.size() < ALIAS_MINIMUM_PUBLIC_SHORT_NAME_ALLOWED)
{
//short alias name, this aliases should be issued only by specific authority
CHECK_AND_ASSERT_MES(eae.m_sign.size() == 1, false, "alias " << eae.m_alias << " can't be update, wrong ai.m_sign.size() count: " << eae.m_sign.size());
bool r = crypto::check_signature(get_sign_buff_hash_for_alias_update(eae), m_core_runtime_config.alias_validation_pubkey, eae.m_sign.back());
CHECK_AND_ASSERT_MES(r, false, "Failed to check signature, short alias registration failed." << ENDL
<< "alias: " << eae.m_alias << ENDL
<< "signed_buff_hash: " << get_sign_buff_hash_for_alias_update(eae) << ENDL
<< "public key: " << m_core_runtime_config.alias_validation_pubkey << ENDL
<< "new_address: " << get_account_address_as_str(eae.m_address) << ENDL
<< "signature: " << epee::string_tools::pod_to_hex(eae.m_sign));
}
}
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::process_blockchain_tx_extra(const transaction& tx)
{
//check transaction extra
tx_extra_info ei = AUTO_VAL_INIT(ei);
bool r = parse_and_validate_tx_extra(tx, ei);
CHECK_AND_ASSERT_MES(r, false, "failed to validate transaction extra");
if (ei.m_alias.m_alias.size())
{
r = prevalidate_alias_info(tx, ei.m_alias);
CHECK_AND_ASSERT_MES(r, false, "failed to prevalidate_alias_info");
r = put_alias_info(tx, ei.m_alias);
CHECK_AND_ASSERT_MES(r, false, "failed to put_alias_info");
}
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::get_outs_index_stat(outs_index_stat& outs_stat) const
{
CRITICAL_REGION_LOCAL(m_read_lock);
outs_stat.amount_0_001 = m_db_outputs.get_item_size(COIN / 1000);
outs_stat.amount_0_01 = m_db_outputs.get_item_size(COIN / 100);
outs_stat.amount_0_1 = m_db_outputs.get_item_size(COIN / 10);
outs_stat.amount_1 = m_db_outputs.get_item_size(COIN);
outs_stat.amount_10 = m_db_outputs.get_item_size(COIN * 10);
outs_stat.amount_100 = m_db_outputs.get_item_size(COIN * 100);
outs_stat.amount_1000 = m_db_outputs.get_item_size(COIN * 1000);
outs_stat.amount_10000 = m_db_outputs.get_item_size(COIN * 10000);
outs_stat.amount_100000 = m_db_outputs.get_item_size(COIN * 100000);
outs_stat.amount_1000000 = m_db_outputs.get_item_size(COIN * 1000000);
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::process_blockchain_tx_attachments(const transaction& tx, uint64_t h, const crypto::hash& bl_id, uint64_t timestamp)
{
uint64_t count = 0;
for (const auto& at : tx.attachment)
{
if (at.type() == typeid(tx_service_attachment))
{
m_services_mgr.handle_entry_push(boost::get<tx_service_attachment>(at), count, tx, h, bl_id, timestamp); //handle service
++count;
}
}
return true;
}
//------------------------------------------------------------------
uint64_t blockchain_storage::get_tx_fee_median() const
{
uint64_t h = m_db_blocks.size();
if (m_current_fee_median_effective_index != get_tx_fee_median_effective_index(h))
{
m_current_fee_median = tx_fee_median_for_height(h);
m_current_fee_median_effective_index = get_tx_fee_median_effective_index(h);
}
if (!m_current_fee_median)
m_current_fee_median = ALIAS_VERY_INITAL_COST;
return m_current_fee_median;
}
//------------------------------------------------------------------
uint64_t blockchain_storage::get_alias_cost(const std::string& alias) const
{
uint64_t median_fee = get_tx_fee_median();
//CHECK_AND_ASSERT_MES_NO_RET(median_fee, "can't calculate median");
if (!median_fee)
median_fee = ALIAS_VERY_INITAL_COST;
return get_alias_cost_from_fee(alias, median_fee);
}
//------------------------------------------------------------------
bool blockchain_storage::unprocess_blockchain_tx_attachments(const transaction& tx, uint64_t h, uint64_t timestamp)
{
size_t cnt_serv_attach = get_service_attachments_count_in_tx(tx);
if (cnt_serv_attach == 0)
return true;
--cnt_serv_attach;
for (auto it = tx.attachment.rbegin(); it != tx.attachment.rend(); it++)
{
auto& at = *it;
if (at.type() == typeid(tx_service_attachment))
{
m_services_mgr.handle_entry_pop(boost::get<tx_service_attachment>(at), cnt_serv_attach, tx, h, timestamp);
--cnt_serv_attach;
}
}
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::validate_tx_service_attachments_in_services(const tx_service_attachment& a, size_t i, const transaction& tx) const
{
return m_services_mgr.validate_entry(a, i, tx);
}
//------------------------------------------------------------------
namespace currency
{
struct add_transaction_input_visitor : public boost::static_visitor<bool>
{
blockchain_storage& m_bcs;
blockchain_storage::key_images_container& m_db_spent_keys;
const crypto::hash& m_tx_id;
const crypto::hash& m_bl_id;
const uint64_t m_bl_height;
add_transaction_input_visitor(blockchain_storage& bcs, blockchain_storage::key_images_container& m_db_spent_keys, const crypto::hash& tx_id, const crypto::hash& bl_id, const uint64_t bl_height) :
m_bcs(bcs),
m_db_spent_keys(m_db_spent_keys),
m_tx_id(tx_id),
m_bl_id(bl_id),
m_bl_height(bl_height)
{}
bool operator()(const txin_to_key& in) const
{
const crypto::key_image& ki = in.k_image;
auto ki_ptr = m_db_spent_keys.get(ki);
if (ki_ptr)
{
//double spend detected
LOG_PRINT_RED_L0("tx with id: " << m_tx_id << " in block id: " << m_bl_id << " have input marked as spent with key image: " << ki << ", block declined");
return false;
}
auto r = m_db_spent_keys.set(ki, m_bl_height);
CHECK_AND_ASSERT_MES(r, false, "failed to m_db_spent_keys.set");
if (in.key_offsets.size() == 1)
{
//direct spend detected
if (!m_bcs.update_spent_tx_flags_for_input(in.amount, in.key_offsets[0], true))
{
//internal error
LOG_PRINT_RED_L0("Failed to update_spent_tx_flags_for_input");
return false;
}
}
return true;
}
bool operator()(const txin_gen& in) const { return true; }
bool operator()(const txin_multisig& in) const
{
//mark out as spent
if (!m_bcs.update_spent_tx_flags_for_input(in.multisig_out_id, m_bl_height))
{
//internal error
LOG_PRINT_RED_L0("Failed to update_spent_tx_flags_for_input");
return false;
}
return true;
}
};
}
bool blockchain_storage::add_transaction_from_block(const transaction& tx, const crypto::hash& tx_id, const crypto::hash& bl_id, uint64_t bl_height, uint64_t timestamp)
{
bool need_to_profile = !is_coinbase(tx);
TIME_MEASURE_START_PD(tx_append_rl_wait);
CRITICAL_REGION_LOCAL(m_read_lock);
TIME_MEASURE_FINISH_PD_COND(need_to_profile, tx_append_rl_wait);
TIME_MEASURE_START_PD(tx_append_is_expired);
CHECK_AND_ASSERT_MES(!is_tx_expired(tx), false, "Transaction can't be added to the blockchain since it's already expired. tx expiration time: " << get_tx_expiration_time(tx) << ", blockchain median time: " << get_tx_expiration_median());
TIME_MEASURE_FINISH_PD_COND(need_to_profile, tx_append_is_expired);
TIME_MEASURE_START_PD(tx_process_extra);
bool r = process_blockchain_tx_extra(tx);
CHECK_AND_ASSERT_MES(r, false, "failed to process_blockchain_tx_extra");
TIME_MEASURE_FINISH_PD_COND(need_to_profile, tx_process_extra);
TIME_MEASURE_START_PD(tx_process_attachment);
process_blockchain_tx_attachments(tx, bl_height, bl_id, timestamp);
TIME_MEASURE_FINISH_PD_COND(need_to_profile, tx_process_attachment);
TIME_MEASURE_START_PD(tx_process_inputs);
BOOST_FOREACH(const txin_v& in, tx.vin)
{
if(!boost::apply_visitor(add_transaction_input_visitor(*this, m_db_spent_keys, tx_id, bl_id, bl_height), in))
{
LOG_ERROR("critical internal error: add_transaction_input_visitor failed. but key_images should be already checked");
r = purge_transaction_keyimages_from_blockchain(tx, false);
CHECK_AND_ASSERT_MES(r, false, "failed to purge_transaction_keyimages_from_blockchain");
r = unprocess_blockchain_tx_extra(tx);
CHECK_AND_ASSERT_MES(r, false, "failed to unprocess_blockchain_tx_extra");
r = unprocess_blockchain_tx_attachments(tx, bl_height, timestamp);
CHECK_AND_ASSERT_MES(r, false, "failed to unprocess_blockchain_tx_attachments");
return false;
}
}
TIME_MEASURE_FINISH_PD_COND(need_to_profile, tx_process_inputs);
//check if there is already transaction with this hash
TIME_MEASURE_START_PD(tx_check_exist);
auto tx_entry_ptr = m_db_transactions.get(tx_id);
if (tx_entry_ptr)
{
LOG_ERROR("critical internal error: tx with id: " << tx_id << " in block id: " << bl_id << " already in blockchain");
purge_transaction_keyimages_from_blockchain(tx, true);
r = unprocess_blockchain_tx_extra(tx);
CHECK_AND_ASSERT_MES(r, false, "failed to unprocess_blockchain_tx_extra");
unprocess_blockchain_tx_attachments(tx, bl_height, timestamp);
return false;
}
TIME_MEASURE_FINISH_PD_COND(need_to_profile, tx_check_exist);
TIME_MEASURE_START_PD(tx_push_global_index);
transaction_chain_entry ch_e;
ch_e.m_keeper_block_height = bl_height;
ch_e.m_spent_flags.resize(tx.vout.size(), false);
ch_e.tx = tx;
r = push_transaction_to_global_outs_index(tx, tx_id, ch_e.m_global_output_indexes);
CHECK_AND_ASSERT_MES(r, false, "failed to return push_transaction_to_global_outs_index tx id " << tx_id);
TIME_MEASURE_FINISH_PD_COND(need_to_profile, tx_push_global_index);
//store everything to db
TIME_MEASURE_START_PD(tx_store_db);
r = m_db_transactions.set(tx_id, ch_e);
TIME_MEASURE_FINISH_PD_COND(need_to_profile, tx_store_db);
CHECK_AND_ASSERT_MES(r, false, "failed to m_db_transactions.set");
TIME_MEASURE_START_PD(tx_print_log);
LOG_PRINT_L1("Added tx to blockchain: " << tx_id << " via block at " << bl_height << " id " << print16(bl_id)
<< ", ins: " << tx.vin.size() << ", outs: " << tx.vout.size() << ", outs sum: " << print_money_brief(get_outs_money_amount(tx)) << " (fee: " << (is_coinbase(tx) ? "0[coinbase]" : print_money_brief(get_tx_fee(tx))) << ")");
TIME_MEASURE_FINISH_PD_COND(need_to_profile, tx_print_log);
//@#@ del me
// LOG_PRINT_L0("APPEND_TX_TIME_INNER: " << m_performance_data.tx_append_rl_wait.get_last_val()
// << " | " << m_performance_data.tx_append_is_expired.get_last_val()
// << " | " << m_performance_data.tx_process_extra.get_last_val()
// << " | " << m_performance_data.tx_process_attachment.get_last_val()
// << " | " << m_performance_data.tx_process_inputs.get_last_val()
// << " | " << m_performance_data.tx_check_exist.get_last_val()
// << " | " << m_performance_data.tx_push_global_index.get_last_val()
// << " | " << m_performance_data.tx_store_db.get_last_val()
// << " | " << m_performance_data.tx_print_log.get_last_val()
// );
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::get_tx_outputs_gindexs(const crypto::hash& tx_id, std::vector<uint64_t>& indexs)const
{
CRITICAL_REGION_LOCAL(m_read_lock);
auto tx_ptr = m_db_transactions.find(tx_id);
if (!tx_ptr)
{
LOG_PRINT_RED_L0("warning: get_tx_outputs_gindexs failed to find transaction with id = " << tx_id);
return false;
}
CHECK_AND_ASSERT_MES(tx_ptr->m_global_output_indexes.size(), false, "internal error: global indexes for transaction " << tx_id << " is empty");
indexs = tx_ptr->m_global_output_indexes;
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::check_tx_inputs(const transaction& tx, const crypto::hash& tx_prefix_hash, uint64_t& max_used_block_height, crypto::hash& max_used_block_id) const
{
CRITICAL_REGION_LOCAL(m_read_lock);
bool res = check_tx_inputs(tx, tx_prefix_hash, &max_used_block_height);
if(!res) return false;
CHECK_AND_ASSERT_MES(max_used_block_height < m_db_blocks.size(), false, "internal error: max used block index=" << max_used_block_height << " is not less then blockchain size = " << m_db_blocks.size());
auto r = get_block_hash(m_db_blocks[max_used_block_height]->bl, max_used_block_id);
CHECK_AND_ASSERT_MES(r, false, "failed to get_block_hash");
return true;
}
//------------------------------------------------------------------
#define PERIOD_DISABLED 0xffffffffffffffffLL
bool blockchain_storage::rebuild_tx_fee_medians()
{
transaction_region tr(m_db, transaction_region::event_t::abort, [this] () { m_diff_cache.reset(); });
CHECK_AND_ASSERT_MES(tr, false, "failed to begin_transaction");
uint64_t sz = m_db_blocks.size();
LOG_PRINT_L0("Started reinitialization of median fee...");
math_helper::once_a_time_seconds<10> log_idle;
epee::misc_utils::median_helper<uint64_t, uint64_t> blocks_median;
for (uint64_t i = 0; i != sz; i++)
{
log_idle.do_call([&]() {LOG_PRINT_L0("block " << i << " of " << sz << std::endl); return true; });
auto bptr = m_db_blocks[i];
block_extended_info new_bei = *bptr;
//assign effective median
new_bei.effective_tx_fee_median = blocks_median.get_median();
//calculate current median for this particular block
std::vector<uint64_t> fees;
for (auto& h: new_bei.bl.tx_hashes)
{
auto txptr = get_tx_chain_entry(h);
CHECK_AND_ASSERT_MES(txptr, false, "failed to find tx id " << h << " from block " << i);
fees.push_back(get_tx_fee(txptr->tx));
}
new_bei.this_block_tx_fee_median = epee::misc_utils::median(fees);
if (!m_db_blocks.set(i, new_bei))
LOG_ERROR("failed to m_db_blocks.set");
//prepare median helper for next block
if(new_bei.this_block_tx_fee_median)
blocks_median.push_item(new_bei.this_block_tx_fee_median, i);
//create callbacks
bool is_pos_allowed_l = i >= m_core_runtime_config.pos_minimum_heigh;
uint64_t period = is_pos_allowed_l ? ALIAS_COST_PERIOD : ALIAS_COST_PERIOD / 2;
if (period >= i+1)
continue;
uint64_t starter_block_index = i+1 - period;
uint64_t purge_recent_period = is_pos_allowed_l ? ALIAS_COST_RECENT_PERIOD : ALIAS_COST_RECENT_PERIOD / 2;
uint64_t purge_recent_block_index = 0;
if (purge_recent_period >= i + 1)
purge_recent_block_index = PERIOD_DISABLED;
else
purge_recent_block_index = i + 1 - purge_recent_period;
auto cb = [&](uint64_t fee, uint64_t height)
{
if (height >= starter_block_index)
return true;
return false;
};
auto cb_final_eraser = [&](uint64_t fee, uint64_t height)
{
if (purge_recent_block_index == PERIOD_DISABLED)
return true;
if (height >= purge_recent_block_index)
return true;
return false;
};
blocks_median.scan_items(cb, cb_final_eraser);
}
tr.will_commit();
LOG_PRINT_L0("Reinitialization of median fee finished!");
return true;
}
//------------------------------------------------------------------
uint64_t blockchain_storage::get_tx_fee_median_effective_index(uint64_t h)const
{
if (h <= ALIAS_MEDIAN_RECALC_INTERWAL + 1)
return 0;
h -= 1; // for transactions of block that h%ALIAS_MEDIAN_RECALC_INTERWAL==0 we still handle fee median from previous day
return h - (h % ALIAS_MEDIAN_RECALC_INTERWAL);
}
//------------------------------------------------------------------
uint64_t blockchain_storage::tx_fee_median_for_height(uint64_t h)const
{
uint64_t effective_index = get_tx_fee_median_effective_index(h);
CHECK_AND_ASSERT_THROW_MES(effective_index < m_db_blocks.size(), "internal error: effective_index= " << effective_index << " while m_db_blocks.size()=" << m_db_blocks.size());
return m_db_blocks[effective_index]->effective_tx_fee_median;
}
//------------------------------------------------------------------
bool blockchain_storage::validate_all_aliases_for_new_median_mode()
{
LOG_PRINT_L0("Started reinitialization of median fee...");
math_helper::once_a_time_seconds<10> log_idle;
uint64_t sz = m_db_blocks.size();
for (uint64_t i = 0; i != sz; i++)
{
log_idle.do_call([&]() {std::cout << "block " << i << " of " << sz << std::endl; return true; });
auto bptr = m_db_blocks[i];
for (auto& tx_id : bptr->bl.tx_hashes)
{
auto tx_ptr = m_db_transactions.find(tx_id);
CHECK_AND_ASSERT_MES(tx_ptr, false, "Internal error: tx " << tx_id << " from block " << i << " not found");
tx_extra_info tei = AUTO_VAL_INIT(tei);
bool r = parse_and_validate_tx_extra(tx_ptr->tx, tei);
CHECK_AND_ASSERT_MES(r, false, "Internal error: tx " << tx_id << " from block " << i << " was failed to parse");
if (tei.m_alias.m_alias.size() && !tei.m_alias.m_sign.size())
{
//reward
//validate alias cost
uint64_t median_fee = tx_fee_median_for_height(i);
uint64_t fee_for_alias = get_alias_cost_from_fee(tei.m_alias.m_alias, median_fee);
//validate the price had been paid
uint64_t found_alias_reward = get_amount_for_zero_pubkeys(tx_ptr->tx);
if (found_alias_reward < fee_for_alias)
{
LOG_PRINT_RED_L0("[" << i << "]Found collision on alias: " << tei.m_alias.m_alias
<< ", expected fee: " << print_money(fee_for_alias) << "(median:" << print_money(median_fee) << ")"
<<" found reward: " << print_money(found_alias_reward) <<". tx_id: " << tx_id);
}
}
}
}
LOG_PRINT_L0("Finished.");
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::have_tx_keyimges_as_spent(const transaction &tx) const
{
// check all tx's inputs for being already spent
for (const txin_v& in : tx.vin)
{
if (in.type() == typeid(txin_to_key))
{
if (have_tx_keyimg_as_spent(boost::get<const txin_to_key>(in).k_image))
return true;
}
else if (in.type() == typeid(txin_multisig))
{
if (is_multisig_output_spent(boost::get<const txin_multisig>(in).multisig_out_id))
return true;
}
else if (in.type() == typeid(txin_gen))
{
// skip txin_gen
}
else
{
LOG_ERROR("Unexpected input type: " << in.type().name());
}
}
return false;
}
//------------------------------------------------------------------
// bool blockchain_storage::check_tx_inputs(const transaction& tx, uint64_t* pmax_used_block_height) const
// {
// TIME_MEASURE_START_PD(tx_check_inputs_prefix_hash);
// crypto::hash tx_prefix_hash = get_transaction_prefix_hash(tx);
// TIME_MEASURE_FINISH_PD(tx_check_inputs_prefix_hash);
// return check_tx_inputs(tx, tx_prefix_hash, pmax_used_block_height);
// }
//------------------------------------------------------------------
bool blockchain_storage::check_tx_inputs(const transaction& tx, const crypto::hash& tx_prefix_hash, uint64_t* pmax_used_block_height) const
{
size_t sig_index = 0;
if(pmax_used_block_height)
*pmax_used_block_height = 0;
std::vector<crypto::signature> sig_stub;
const std::vector<crypto::signature>* psig = &sig_stub;
TIME_MEASURE_START_PD(tx_check_inputs_loop);
BOOST_FOREACH(const auto& txin, tx.vin)
{
if (!m_is_in_checkpoint_zone)
{
CHECK_AND_ASSERT_MES(sig_index < tx.signatures.size(), false, "Wrong transaction: missing signature entry for input #" << sig_index << " tx: " << tx_prefix_hash);
psig = &tx.signatures[sig_index];
}
if (txin.type() == typeid(txin_to_key))
{
const txin_to_key& in_to_key = boost::get<txin_to_key>(txin);
CHECK_AND_ASSERT_MES(in_to_key.key_offsets.size(), false, "Empty in_to_key.key_offsets for input #" << sig_index << " tx: " << tx_prefix_hash);
TIME_MEASURE_START_PD(tx_check_inputs_loop_kimage_check);
if (have_tx_keyimg_as_spent(in_to_key.k_image))
{
LOG_ERROR("Key image was already spent in blockchain: " << string_tools::pod_to_hex(in_to_key.k_image) << " for input #" << sig_index << " tx: " << tx_prefix_hash);
return false;
}
TIME_MEASURE_FINISH_PD(tx_check_inputs_loop_kimage_check);
if (!check_tx_input(tx, sig_index, in_to_key, tx_prefix_hash, *psig, pmax_used_block_height))
{
LOG_ERROR("Failed to validate input #" << sig_index << " tx: " << tx_prefix_hash);
return false;
}
}
else if (txin.type() == typeid(txin_multisig))
{
const txin_multisig& in_ms = boost::get<txin_multisig>(txin);
if (!check_tx_input(tx, sig_index, in_ms, tx_prefix_hash, *psig, pmax_used_block_height))
{
LOG_ERROR("Failed to validate multisig input #" << sig_index << " (ms out id: " << in_ms.multisig_out_id << ") in tx: " << tx_prefix_hash);
return false;
}
}
sig_index++;
}
TIME_MEASURE_FINISH_PD(tx_check_inputs_loop);
TIME_MEASURE_START_PD(tx_check_inputs_attachment_check);
if (!m_is_in_checkpoint_zone)
{
CHECK_AND_ASSERT_MES(tx.signatures.size() == sig_index, false, "tx signatures count differs from inputs");
if (!(get_tx_flags(tx)&TX_FLAG_SIGNATURE_MODE_SEPARATE))
{
bool r = validate_attachment_info(tx.extra, tx.attachment, false);
CHECK_AND_ASSERT_MES(r, false, "Failed to validate attachments in tx " << tx_prefix_hash << ": incorrect extra_attachment_info in tx.extra");
}
}
TIME_MEASURE_FINISH_PD(tx_check_inputs_attachment_check);
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::is_tx_spendtime_unlocked(uint64_t unlock_time) const
{
return currency::is_tx_spendtime_unlocked(unlock_time, get_current_blockchain_size(), m_core_runtime_config.get_core_time());
}
//------------------------------------------------------------------
bool blockchain_storage::check_tx_input(const transaction& tx, size_t in_index, const txin_to_key& txin, const crypto::hash& tx_prefix_hash, const std::vector<crypto::signature>& sig, uint64_t* pmax_related_block_height) const
{
CRITICAL_REGION_LOCAL(m_read_lock);
//TIME_MEASURE_START_PD(tx_check_inputs_loop_ch_in_get_keys_loop);
std::vector<crypto::public_key> output_keys;
if(!get_output_keys_for_input_with_checks(txin, output_keys, pmax_related_block_height))
{
LOG_PRINT_L0("Failed to get output keys for input #" << in_index << " (amount = " << print_money(txin.amount) << ", key_offset.size = " << txin.key_offsets.size() << ")");
return false;
}
//TIME_MEASURE_FINISH_PD(tx_check_inputs_loop_ch_in_get_keys_loop);
std::vector<const crypto::public_key *> output_keys_ptrs;
output_keys_ptrs.reserve(output_keys.size());
for (auto& ptr : output_keys)
output_keys_ptrs.push_back(&ptr);
return check_tokey_input(tx, in_index, txin, tx_prefix_hash, sig, output_keys_ptrs);
}
//------------------------------------------------------------------
// Checks each referenced output for:
// 1) source tx unlock time validity
// 2) mixin restrictions
// 3) general gindex/ref_by_id corectness
bool blockchain_storage::get_output_keys_for_input_with_checks(const txin_to_key& txin, std::vector<crypto::public_key>& output_keys, uint64_t* pmax_related_block_height /* = NULL */) const
{
CRITICAL_REGION_LOCAL(m_read_lock);
struct outputs_visitor
{
std::vector<crypto::public_key >& m_results_collector;
const blockchain_storage& m_bch;
outputs_visitor(std::vector<crypto::public_key>& results_collector,
const blockchain_storage& bch) :m_results_collector(results_collector), m_bch(bch)
{}
bool handle_output(const transaction& tx, const tx_out& out)
{
//check tx unlock time
if (!m_bch.is_tx_spendtime_unlocked(get_tx_unlock_time(tx)))
{
LOG_PRINT_L0("One of outputs for one of inputs have wrong tx.unlock_time = " << get_tx_unlock_time(tx));
return false;
}
if(out.target.type() != typeid(txout_to_key))
{
LOG_PRINT_L0("Output have wrong type id, which=" << out.target.which());
return false;
}
crypto::public_key pk = boost::get<txout_to_key>(out.target).key;
m_results_collector.push_back(pk);
return true;
}
};
outputs_visitor vi(output_keys, *this);
return scan_outputkeys_for_indexes(txin, vi, pmax_related_block_height);
}
//------------------------------------------------------------------
// Note: this function can be used for checking to_key inputs against either main chain or alt chain, that's why it has output_keys_ptrs parameter
// Doesn't check spent flags, the caller must check it.
bool blockchain_storage::check_tokey_input(const transaction& tx, size_t in_index, const txin_to_key& txin, const crypto::hash& tx_prefix_hash, const std::vector<crypto::signature>& sig, const std::vector<const crypto::public_key*>& output_keys_ptrs) const
{
CRITICAL_REGION_LOCAL(m_read_lock);
TIME_MEASURE_START_PD(tx_check_inputs_loop_ch_in_val_sig);
if (txin.key_offsets.size() != output_keys_ptrs.size())
{
LOG_PRINT_L0("Output keys for tx with amount = " << txin.amount << " and count indexes " << txin.key_offsets.size() << " returned wrong keys count " << output_keys_ptrs.size());
return false;
}
if(m_is_in_checkpoint_zone)
return true;
if (get_tx_flags(tx) & TX_FLAG_SIGNATURE_MODE_SEPARATE)
{
// check attachments, mentioned directly in this input
bool r = validate_attachment_info(txin.etc_details, tx.attachment, in_index != tx.vin.size() - 1); // attachment info can be omitted for all inputs, except the last one
CHECK_AND_ASSERT_MES(r, false, "Failed to validate attachments in tx " << tx_prefix_hash << ": incorrect extra_attachment_info in etc_details in input #" << in_index);
}
else
{
// make sure normal tx does not have extra_attachment_info in etc_details
CHECK_AND_ASSERT_MES(!have_type_in_variant_container<extra_attachment_info>(txin.etc_details), false, "Incorrect using of extra_attachment_info in etc_details in input #" << in_index << " for tx " << tx_prefix_hash);
}
// check signatures
size_t expected_signatures_count = output_keys_ptrs.size();
bool need_to_check_extra_sign = false;
if (get_tx_flags(tx)&TX_FLAG_SIGNATURE_MODE_SEPARATE && in_index == tx.vin.size() - 1)
{
expected_signatures_count++;
need_to_check_extra_sign = true;
}
CHECK_AND_ASSERT_MES(expected_signatures_count == sig.size(), false, "internal error: tx signatures count=" << sig.size() << " mismatch with outputs keys count for inputs=" << expected_signatures_count);
crypto::hash tx_hash_for_signature = prepare_prefix_hash_for_sign(tx, in_index, tx_prefix_hash);
CHECK_AND_ASSERT_MES(tx_hash_for_signature != null_hash, false, "failed to prepare_prefix_hash_for_sign");
LOG_PRINT_L4("CHECK RING SIGNATURE: tx_prefix_hash " << tx_prefix_hash
<< "tx_hash_for_signature" << tx_hash_for_signature
<< "txin.k_image" << txin.k_image
<< "key_ptr:" << *output_keys_ptrs[0]
<< "signature:" << sig[0]);
bool r = crypto::validate_key_image(txin.k_image);
CHECK_AND_ASSERT_MES(r, false, "key image for input #" << in_index << " is invalid: " << txin.k_image);
r = crypto::check_ring_signature(tx_hash_for_signature, txin.k_image, output_keys_ptrs, sig.data());
CHECK_AND_ASSERT_MES(r, false, "failed to check ring signature for input #" << in_index << ENDL << dump_ring_sig_data(tx_hash_for_signature, txin.k_image, output_keys_ptrs, sig));
if (need_to_check_extra_sign)
{
//here we check extra signature to validate that transaction was finalized by authorized subject
r = crypto::check_signature(tx_prefix_hash, get_tx_pub_key_from_extra(tx), sig.back());
CHECK_AND_ASSERT_MES(r, false, "failed to check extra signature for last input with TX_FLAG_SIGNATURE_MODE_SEPARATE");
}
TIME_MEASURE_FINISH_PD(tx_check_inputs_loop_ch_in_val_sig);
return r;
}
//------------------------------------------------------------------
// Note: this function doesn't check spent flags by design (to be able to use either for main chain and alt chains).
// The caller MUST check spent flags.
bool blockchain_storage::check_ms_input(const transaction& tx, size_t in_index, const txin_multisig& txin, const crypto::hash& tx_prefix_hash, const std::vector<crypto::signature>& sig, const transaction& source_tx, size_t out_n) const
{
#define LOC_CHK(cond, msg) CHECK_AND_ASSERT_MES(cond, false, "ms input check failed: ms_id: " << txin.multisig_out_id << ", input #" << in_index << " in tx " << tx_prefix_hash << ", refers to ms output #" << out_n << " in source tx " << get_transaction_hash(source_tx) << ENDL << msg)
CRITICAL_REGION_LOCAL(m_read_lock);
uint64_t unlock_time = get_tx_unlock_time(source_tx);
LOC_CHK(is_tx_spendtime_unlocked(unlock_time), "Source transaction is LOCKED! unlock_time: " << unlock_time << ", now is " << m_core_runtime_config.get_core_time() << ", blockchain size is " << get_current_blockchain_size());
LOC_CHK(source_tx.vout.size() > out_n, "internal error: out_n==" << out_n << " is out-of-bounds of source_tx.vout, size=" << source_tx.vout.size());
const tx_out& source_tx_out = source_tx.vout[out_n];
const txout_multisig& source_ms_out_target = boost::get<txout_multisig>(source_tx_out.target);
LOC_CHK(txin.sigs_count == source_ms_out_target.minimum_sigs,
"ms input's sigs_count (" << txin.sigs_count << ") does not match to ms output's minimum signatures expected (" << source_ms_out_target.minimum_sigs << ")"
<< ", source_tx_out.amount=" << print_money(source_tx_out.amount)
<< ", txin.amount = " << print_money(txin.amount));
LOC_CHK(source_tx_out.amount == txin.amount,
"amount missmatch"
<< ", source_tx_out.amount=" << print_money(source_tx_out.amount)
<< ", txin.amount = " << print_money(txin.amount));
if (m_is_in_checkpoint_zone)
return true;
if (get_tx_flags(tx) & TX_FLAG_SIGNATURE_MODE_SEPARATE)
{
// check attachments, mentioned directly in this input
bool r = validate_attachment_info(txin.etc_details, tx.attachment, in_index != tx.vin.size() - 1); // attachment info can be omitted for all inputs, except the last one
LOC_CHK(r, "Failed to validate attachments in tx " << tx_prefix_hash << ": incorrect extra_attachment_info in etc_details in input #" << in_index);
}
else
{
// make sure normal tx does not have extra_attachment_info in etc_details
LOC_CHK(!have_type_in_variant_container<extra_attachment_info>(txin.etc_details), "Incorrect using of extra_attachment_info in etc_details in input #" << in_index << " for tx " << tx_prefix_hash);
}
LOC_CHK(tx.signatures.size() > in_index, "ms input index is out of signatures container bounds, tx.signatures.size() = " << tx.signatures.size());
const std::vector<crypto::signature>& input_signatures = tx.signatures[in_index];
size_t expected_signatures_count = txin.sigs_count;
bool need_to_check_extra_sign = false;
if (get_tx_flags(tx)&TX_FLAG_SIGNATURE_MODE_SEPARATE && in_index == tx.vin.size() - 1) // last input in TX_FLAG_SIGNATURE_MODE_SEPARATE must contain one more signature to ensure that tx was completed by an authorized subject
{
expected_signatures_count++;
need_to_check_extra_sign = true;
}
LOC_CHK(expected_signatures_count == input_signatures.size(), "Invalid input's signatures count: " << input_signatures.size() << ", expected: " << expected_signatures_count);
crypto::hash tx_hash_for_signature = prepare_prefix_hash_for_sign(tx, in_index, tx_prefix_hash);
LOC_CHK(tx_hash_for_signature != null_hash, "prepare_prefix_hash_for_sign failed");
LOC_CHK(txin.sigs_count <= source_ms_out_target.keys.size(), "source tx invariant failed: ms output's minimum sigs == ms input's sigs_count (" << txin.sigs_count << ") is GREATHER than keys.size() = " << source_ms_out_target.keys.size()); // NOTE: sig_count == minimum_sigs as checked above
size_t out_key_index = 0; // index in source_ms_out_target.keys
for (size_t i = 0; i != txin.sigs_count; /* nothing */)
{
// if we run out of keys for this signature, then it's invalid signature
LOC_CHK(out_key_index < source_ms_out_target.keys.size(), "invalid signature #" << i << ": " << input_signatures[i]);
// check signature #i against ms output key #out_key_index
if (crypto::check_signature(tx_hash_for_signature, source_ms_out_target.keys[out_key_index], input_signatures[i]))
{
// match: go for the next signature and the next key
i++;
out_key_index++;
}
else
{
// missmatch: go for the next key for this signature
out_key_index++;
}
}
if (need_to_check_extra_sign)
{
//here we check extra signature to validate that transaction was finalized by authorized subject
bool r = crypto::check_signature(tx_prefix_hash, get_tx_pub_key_from_extra(tx), tx.signatures[in_index].back());
LOC_CHK(r, "failed to check extra signature for last out with TX_FLAG_SIGNATURE_MODE_SEPARATE");
}
return true;
#undef LOC_CHK
}
//------------------------------------------------------------------
bool blockchain_storage::check_tx_input(const transaction& tx, size_t in_index, const txin_multisig& txin, const crypto::hash& tx_prefix_hash, const std::vector<crypto::signature>& sig, uint64_t* pmax_related_block_height) const
{
CRITICAL_REGION_LOCAL(m_read_lock);
auto multisig_ptr = m_db_multisig_outs.find(txin.multisig_out_id);
CHECK_AND_ASSERT_MES(multisig_ptr, false, "Unable to find txin.multisig_out_id=" << txin.multisig_out_id << " for ms input #" << in_index << " in tx " << tx_prefix_hash);
const crypto::hash& source_tx_id = multisig_ptr->tx_id; // source tx hash
size_t n = multisig_ptr->out_no; // index of multisig output in source tx
#define LOC_CHK(cond, msg) CHECK_AND_ASSERT_MES(cond, false, "ms input check failed: ms_id: " << txin.multisig_out_id << ", input #" << in_index << " in tx " << tx_prefix_hash << ", refers to ms output #" << n << " in source tx " << source_tx_id << ENDL << msg)
LOC_CHK(multisig_ptr->spent_height == 0, "ms output is already spent on height " << multisig_ptr->spent_height);
auto source_tx_ptr = m_db_transactions.find(source_tx_id);
LOC_CHK(source_tx_ptr, "Can't find source transaction");
LOC_CHK(source_tx_ptr->tx.vout.size() > n, "ms output index is incorrect, source tx's vout size is " << source_tx_ptr->tx.vout.size());
LOC_CHK(source_tx_ptr->tx.vout[n].target.type() == typeid(txout_multisig), "ms output has wrong type, txout_multisig expected");
LOC_CHK(source_tx_ptr->m_spent_flags.size() > n, "Internal error, m_spent_flags size (" << source_tx_ptr->m_spent_flags.size() << ") less then expected, n: " << n);
LOC_CHK(source_tx_ptr->m_spent_flags[n] == false, "Internal error, ms output is already spent"); // should never happen as multisig_ptr->spent_height is checked above
if (!check_ms_input(tx, in_index, txin, tx_prefix_hash, sig, source_tx_ptr->tx, n))
return false;
if (pmax_related_block_height != nullptr)
*pmax_related_block_height = source_tx_ptr->m_keeper_block_height;
return true;
#undef LOC_CHK
}
//------------------------------------------------------------------
uint64_t blockchain_storage::get_adjusted_time() const
{
//TODO: add collecting median time
return m_core_runtime_config.get_core_time();
}
//------------------------------------------------------------------
std::vector<uint64_t> blockchain_storage::get_last_n_blocks_timestamps(size_t n) const
{
CRITICAL_REGION_LOCAL(m_read_lock);
std::vector<uint64_t> timestamps;
size_t array_size = m_db_blocks.size() <= n ? m_db_blocks.size() : n;
timestamps.reserve(array_size);
if (m_db_blocks.size() == 0)
return timestamps;
complete_timestamps_vector(m_db_blocks.size() - 1, timestamps, n);
return timestamps;
}
//------------------------------------------------------------------
uint64_t blockchain_storage::get_last_n_blocks_timestamps_median(size_t n) const
{
CRITICAL_REGION_LOCAL(m_read_lock);
auto it = m_timestamps_median_cache.find(n);
if (it != m_timestamps_median_cache.end())
return it->second;
std::vector<uint64_t> timestamps = get_last_n_blocks_timestamps(n);
uint64_t median_res = epee::misc_utils::median(timestamps);
m_timestamps_median_cache[n] = median_res;
return median_res;
}
//------------------------------------------------------------------
uint64_t blockchain_storage::get_last_timestamps_check_window_median() const
{
return get_last_n_blocks_timestamps_median(BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW);
}
//------------------------------------------------------------------
uint64_t blockchain_storage::get_tx_expiration_median() const
{
return get_last_n_blocks_timestamps_median(TX_EXPIRATION_TIMESTAMP_CHECK_WINDOW);
}
//------------------------------------------------------------------
bool blockchain_storage::check_block_timestamp_main(const block& b) const
{
if(b.timestamp > get_adjusted_time() + CURRENCY_BLOCK_FUTURE_TIME_LIMIT)
{
LOG_PRINT_L0("Timestamp of block with id: " << get_block_hash(b) << ", " << b.timestamp << ", bigger than adjusted time + " + epee::misc_utils::get_time_interval_string(CURRENCY_BLOCK_FUTURE_TIME_LIMIT));
return false;
}
if (is_pos_block(b) && b.timestamp > get_adjusted_time() + CURRENCY_POS_BLOCK_FUTURE_TIME_LIMIT)
{
LOG_PRINT_L0("Timestamp of PoS block with id: " << get_block_hash(b) << ", " << b.timestamp << ", bigger than adjusted time + " + epee::misc_utils::get_time_interval_string(CURRENCY_POS_BLOCK_FUTURE_TIME_LIMIT) + ": " << get_adjusted_time() << " (" << b.timestamp - get_adjusted_time() << ")");
return false;
}
std::vector<uint64_t> timestamps = get_last_n_blocks_timestamps(BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW);
return check_block_timestamp(std::move(timestamps), b);
}
//------------------------------------------------------------------
bool blockchain_storage::check_block_timestamp(std::vector<uint64_t> timestamps, const block& b) const
{
if(timestamps.size() < BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW)
return true;
if (is_pos_block(b) && b.timestamp > get_adjusted_time() + CURRENCY_POS_BLOCK_FUTURE_TIME_LIMIT)
{
LOG_PRINT_L0("Timestamp of PoS block with id: " << get_block_hash(b) << ", " << b.timestamp << ", bigger than adjusted time + " + epee::misc_utils::get_time_interval_string(CURRENCY_POS_BLOCK_FUTURE_TIME_LIMIT) + ": " << get_adjusted_time() << " (" << b.timestamp - get_adjusted_time() << ")");
return false;
}
uint64_t median_ts = epee::misc_utils::median(timestamps);
if(b.timestamp < median_ts)
{
LOG_PRINT_L0("Timestamp of block with id: " << get_block_hash(b) << ", " << b.timestamp << ", less than median of last " << BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW << " blocks, " << median_ts);
return false;
}
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::is_tx_expired(const transaction& tx) const
{
return currency::is_tx_expired(tx, get_tx_expiration_median());
}
//------------------------------------------------------------------
std::shared_ptr<const transaction_chain_entry> blockchain_storage::find_key_image_and_related_tx(const crypto::key_image& ki, crypto::hash& id_result) const
{
CRITICAL_REGION_LOCAL(m_read_lock);
auto ki_index_ptr = m_db_spent_keys.find(ki);
if (!ki_index_ptr)
return std::shared_ptr<transaction_chain_entry>();
auto block_entry = m_db_blocks[*ki_index_ptr];
if (!block_entry)
{
LOG_ERROR("Internal error: broken index, key image " << ki
<< " reffered to height " << *ki_index_ptr << " but couldnot find block on this height");
return std::shared_ptr<const transaction_chain_entry>();
}
//look up coinbase
for (auto& in: block_entry->bl.miner_tx.vin)
{
if (in.type() == typeid(txin_to_key))
{
if (boost::get<txin_to_key>(in).k_image == ki)
{
id_result = get_transaction_hash(block_entry->bl.miner_tx);
return get_tx_chain_entry(id_result);
}
}
}
//lookup transactions
for (auto& tx_id : block_entry->bl.tx_hashes)
{
auto tx_chain_entry = get_tx_chain_entry(tx_id);
if (!tx_chain_entry)
{
LOG_ERROR("Internal error: broken index, tx_id " << tx_id
<< " not found in tx index, block no " << *ki_index_ptr);
return std::shared_ptr<const transaction_chain_entry>();
}
for (auto& in : tx_chain_entry->tx.vin)
{
if (in.type() == typeid(txin_to_key))
{
if (boost::get<txin_to_key>(in).k_image == ki)
{
id_result = get_transaction_hash(tx_chain_entry->tx);
return tx_chain_entry;
}
}
}
}
return std::shared_ptr<const transaction_chain_entry>();
}
//------------------------------------------------------------------
bool blockchain_storage::prune_aged_alt_blocks()
{
CRITICAL_REGION_LOCAL(m_read_lock);
CRITICAL_REGION_LOCAL1(m_alternative_chains_lock);
uint64_t current_height = get_current_blockchain_size();
for(auto it = m_alternative_chains.begin(); it != m_alternative_chains.end();)
{
if (current_height > it->second.height && current_height - it->second.height > CURRENCY_ALT_BLOCK_LIVETIME_COUNT)
{
do_erase_altblock(it++);
}
else
{
++it;
}
}
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::validate_pos_block(const block& b, const crypto::hash& id, bool for_altchain) const
{
//validate
wide_difficulty_type basic_diff = get_cached_next_difficulty(true);
return validate_pos_block(b, basic_diff, id, for_altchain);
}
//------------------------------------------------------------------
bool blockchain_storage::validate_pos_block(const block& b, wide_difficulty_type basic_diff, const crypto::hash& id, bool for_altchain) const
{
uint64_t coin_age = 0;
wide_difficulty_type final_diff = 0;
crypto::hash proof_hash = null_hash;
return validate_pos_block(b, basic_diff, coin_age, final_diff, proof_hash, id, for_altchain);
}
//------------------------------------------------------------------
#define POS_STAKE_TO_DIFF_COEFF 100 // total_coins_in_minting * POS_STAKE_TO_DIFF_COEFF =~ pos_difficulty
void blockchain_storage::get_pos_mining_estimate(uint64_t amount_coins,
uint64_t time,
uint64_t& estimate_result,
uint64_t& pos_diff_and_amount_rate,
std::vector<uint64_t>& days) const
{
estimate_result = 0;
if (!is_pos_allowed())
return;
// new algo
// 1. get (CURRENCY_BLOCKS_PER_DAY / 2) PoS blocks (a day in case of PoS/PoW==50/50)
// 2. calculate total minted money C (normalized for 1 day interval) and average difficulty D (based on last (CURRENCY_BLOCKS_PER_DAY / 2) PoS blocks)
// 3. calculate total coins participating in PoS minting as M = D / pos_diff_ratio
// 4. calculate owner's money proportion as P = amount_coins / (M + amount_coins)
// 5. estimate PoS minting income for this day as I = C * P
// 6. amount_coins += I, goto 3
epee::critical_region_t<decltype(m_read_lock)> read_lock_region(m_read_lock);
size_t estimated_pos_blocks_count_per_day = CURRENCY_BLOCKS_PER_DAY / 2; // 50% of all blocks in a perfect world
uint64_t pos_ts_min = UINT64_MAX, pos_ts_max = 0;
size_t pos_blocks_count = 0;
uint64_t pos_total_minted_money = 0;
wide_difficulty_type pos_avg_difficulty = 0;
// scan blockchain backward for PoS blocks and collect data
for (size_t h = m_db_blocks.size() - 1; h != 0 && pos_blocks_count < estimated_pos_blocks_count_per_day; --h)
{
auto bei = m_db_blocks[h];
if (!is_pos_block(bei->bl))
continue;
uint64_t ts = get_actual_timestamp(bei->bl);
pos_ts_min = min(pos_ts_min, ts);
pos_ts_max = max(pos_ts_max, ts);
pos_total_minted_money += get_reward_from_miner_tx(bei->bl.miner_tx);
pos_avg_difficulty += bei->difficulty;
++pos_blocks_count;
}
if (pos_blocks_count < estimated_pos_blocks_count_per_day || pos_ts_max <= pos_ts_min)
return; // too little pos blocks found or invalid ts
pos_avg_difficulty /= pos_blocks_count;
uint64_t found_blocks_interval = pos_ts_max - pos_ts_min; // will be close to 24 * 60 * 60 in case of PoS/PoW == 50/50
uint64_t pos_last_day_total_minted_money = pos_total_minted_money * (24 * 60 * 60) / found_blocks_interval; // total minted money normalized for 1 day interval
uint64_t estimated_total_minting_coins = static_cast<uint64_t>(pos_avg_difficulty / POS_STAKE_TO_DIFF_COEFF);
uint64_t current_amount = amount_coins;
uint64_t days_count = time / (60 * 60 * 24);
for (uint64_t d = 0; d != days_count; d++)
{
double user_minting_coins_proportion = static_cast<double>(current_amount) / (estimated_total_minting_coins + current_amount);
current_amount += pos_last_day_total_minted_money * user_minting_coins_proportion;
days.push_back(current_amount);
}
estimate_result = current_amount;
}
//------------------------------------------------------------------
bool blockchain_storage::validate_pos_block(const block& b,
wide_difficulty_type basic_diff,
uint64_t& amount,
wide_difficulty_type& final_diff,
crypto::hash& proof_hash,
const crypto::hash& id,
bool for_altchain,
const alt_chain_type& alt_chain,
uint64_t split_height
)const
{
bool is_pos = is_pos_block(b);
CHECK_AND_ASSERT_MES(is_pos, false, "is_pos_block() returned false validate_pos_block()");
//check timestamp
CHECK_AND_ASSERT_MES(b.timestamp%POS_SCAN_STEP == 0, false, "wrong timestamp in PoS block(b.timestamp%POS_SCAN_STEP == 0), b.timestamp = " <<b.timestamp);
//check keyimage
CHECK_AND_ASSERT_MES(b.miner_tx.vin[1].type() == typeid(txin_to_key), false, "coinstake transaction in the block has the wrong type");
const txin_to_key& in_to_key = boost::get<txin_to_key>(b.miner_tx.vin[1]);
if (!for_altchain && have_tx_keyimg_as_spent(in_to_key.k_image))
{
LOG_PRINT_L0("Key image in coinstake already spent in blockchain: " << string_tools::pod_to_hex(in_to_key.k_image));
return false;
}
//check actual time if it there
uint64_t actual_ts = get_actual_timestamp(b);
if ((actual_ts > b.timestamp && actual_ts - b.timestamp > POS_MAC_ACTUAL_TIMESTAMP_TO_MINED) ||
(actual_ts < b.timestamp && b.timestamp - actual_ts > POS_MAC_ACTUAL_TIMESTAMP_TO_MINED)
)
{
LOG_PRINT_L0("PoS block actual timestamp " << actual_ts << " differs from b.timestamp " << b.timestamp << " by " << ((int64_t)actual_ts - (int64_t)b.timestamp) << " s, it's more than allowed " << POS_MAC_ACTUAL_TIMESTAMP_TO_MINED << " s.");
return false;
}
//check kernel
stake_kernel sk = AUTO_VAL_INIT(sk);
stake_modifier_type sm = AUTO_VAL_INIT(sm);
bool r = build_stake_modifier(sm, alt_chain, split_height);
CHECK_AND_ASSERT_MES(r, false, "failed to build_stake_modifier");
amount = 0;
r = build_kernel(b, sk, amount, sm);
CHECK_AND_ASSERT_MES(r, false, "failed to build kernel_stake");
CHECK_AND_ASSERT_MES(amount!=0, false, "failed to build kernel_stake, amount == 0");
proof_hash = crypto::cn_fast_hash(&sk, sizeof(sk));
LOG_PRINT_L2("STAKE KERNEL for bl ID: " << get_block_hash(b) << ENDL
<< print_stake_kernel_info(sk)
<< "amount: " << print_money(amount) << ENDL
<< "kernel_hash: " << proof_hash);
final_diff = basic_diff / amount;
if (!check_hash(proof_hash, final_diff))
{
LOG_ERROR("PoS difficulty check failed for block " << get_block_hash(b) << " @ HEIGHT " << get_block_height(b) << ":" << ENDL
<< " basic_diff: " << basic_diff << ENDL
<< " final_diff: " << final_diff << ENDL
<< " amount: " << print_money_brief(amount) << ENDL
<< " kernel_hash: " << proof_hash << ENDL
);
return false;
}
//validate signature
uint64_t max_related_block_height = 0;
const txin_to_key& coinstake_in = boost::get<txin_to_key>(b.miner_tx.vin[1]);
CHECK_AND_ASSERT_MES(b.miner_tx.signatures.size() == 1, false, "PoS block's miner_tx has incorrect signatures size = " << b.miner_tx.signatures.size() << ", block_id = " << get_block_hash(b));
if (!for_altchain)
{
// Do coinstake input validation for main chain only.
// Txs in alternative PoS blocks (including miner_tx) are validated by validate_alt_block_txs()
r = check_tx_input(b.miner_tx, 1, coinstake_in, id, b.miner_tx.signatures[0], &max_related_block_height);
CHECK_AND_ASSERT_MES(r, false, "Failed to validate coinstake input in miner tx, block_id = " << get_block_hash(b));
}
uint64_t block_height = for_altchain ? split_height + alt_chain.size() : m_db_blocks.size();
uint64_t coinstake_age = block_height - max_related_block_height - 1;
CHECK_AND_ASSERT_MES(coinstake_age >= m_core_runtime_config.min_coinstake_age, false,
"Coinstake age is: " << coinstake_age << " is less than minimum expected: " << m_core_runtime_config.min_coinstake_age);
return true;
}
//------------------------------------------------------------------
wide_difficulty_type blockchain_storage::get_adjusted_cumulative_difficulty_for_next_pos(wide_difficulty_type next_diff) const
{
CRITICAL_REGION_LOCAL(m_read_lock);
wide_difficulty_type last_pow_diff = 0;
wide_difficulty_type last_pos_diff = 0;
const uint64_t sz = m_db_blocks.size();
if (!sz)
return next_diff;
for (uint64_t h = sz - 1; h != 0 && !(last_pow_diff && last_pos_diff); --h)
{
const auto ptr_bei = m_db_blocks[h];
if (is_pos_block(ptr_bei->bl))
{
if (!last_pos_diff)
{
last_pos_diff = ptr_bei->difficulty;
}
}
else
{
if (!last_pow_diff)
{
last_pow_diff = ptr_bei->difficulty;
}
}
}
if (!last_pos_diff)
return next_diff;
if (!last_pow_diff)
last_pow_diff = m_db_blocks[0]->difficulty; // DIFFICULTY_STARTER
return next_diff * last_pow_diff / last_pos_diff;
}
//------------------------------------------------------------------
wide_difficulty_type blockchain_storage::get_adjusted_cumulative_difficulty_for_next_alt_pos(alt_chain_type& alt_chain, uint64_t block_height, wide_difficulty_type next_diff, uint64_t connection_height) const
{
wide_difficulty_type last_pow_diff = 0;
wide_difficulty_type last_pos_diff = 0;
for (auto it = alt_chain.rbegin(); it != alt_chain.rend() && !(last_pos_diff && last_pow_diff); ++it)
{
const auto & alt_bei = (*it)->second;
if (is_pos_block(alt_bei.bl))
{
if (!last_pos_diff)
{
last_pos_diff = alt_bei.difficulty;
}
}
else
{
if (!last_pow_diff)
{
last_pow_diff = alt_bei.difficulty;
}
}
}
CRITICAL_REGION_LOCAL(m_read_lock);
for (uint64_t h = connection_height - 1; h != 0 && !(last_pos_diff && last_pow_diff); --h)
{
const auto ptr_bei = m_db_blocks[h];
if (is_pos_block(ptr_bei->bl))
{
if (!last_pos_diff)
{
last_pos_diff = ptr_bei->difficulty;
}
}
else
{
if (!last_pow_diff)
{
last_pow_diff = ptr_bei->difficulty;
}
}
}
if (!last_pos_diff)
return next_diff;
if (!last_pow_diff)
last_pow_diff = m_db_blocks[0]->difficulty; // DIFFICULTY_STARTER
return next_diff * last_pow_diff / last_pos_diff;
}
//------------------------------------------------------------------
uint64_t blockchain_storage::get_last_x_block_height(bool pos) const
{
CRITICAL_REGION_LOCAL(m_read_lock);
const uint64_t sz = m_db_blocks.size();
if (!sz)
return 0;
for (uint64_t i = sz-1; i != 0; i--)
{
if (is_pos_block(m_db_blocks[i]->bl) == pos)
return i;
}
return 0;
}
//------------------------------------------------------------------
wide_difficulty_type blockchain_storage::get_last_alt_x_block_cumulative_precise_difficulty(alt_chain_type& alt_chain, uint64_t block_height, bool pos) const
{
uint64_t main_chain_first_block = block_height - 1;
for (auto it = alt_chain.rbegin(); it != alt_chain.rend(); it++)
{
if (is_pos_block((*it)->second.bl) == pos)
return (*it)->second.cumulative_diff_precise;
main_chain_first_block = (*it)->second.height - 1;
}
CRITICAL_REGION_LOCAL(m_read_lock);
CHECK_AND_ASSERT_MES(main_chain_first_block < m_db_blocks.size(), false, "Intrnal error: main_chain_first_block(" << main_chain_first_block << ") < m_blocks.size() (" << m_db_blocks.size() << ")");
for (uint64_t i = main_chain_first_block; i != 0; i--)
{
if (is_pos_block(m_db_blocks[i]->bl) == pos)
return m_db_blocks[i]->cumulative_diff_precise;
}
return 0;
}
//------------------------------------------------------------------
bool blockchain_storage::handle_block_to_main_chain(const block& bl, const crypto::hash& id, block_verification_context& bvc)
{
TIME_MEASURE_START_PD_MS(block_processing_time_0_ms)
CRITICAL_REGION_LOCAL(m_read_lock);
TIME_MEASURE_START_PD(block_processing_time_1)
CHECK_AND_ASSERT_MES(bl.prev_id == get_top_block_id(), false, "Block with id: " << id << ENDL << "have wrong prev_id: " << bl.prev_id << ENDL << "expected: " << get_top_block_id());
#ifdef _DEBUG
uint64_t h = get_block_height(bl);
#endif // _DEBUG
bool r = check_block_timestamp_main(bl);
CHECK_AND_ASSERT_MES_CUSTOM(r, false, bvc.m_verification_failed = true, "Block with id: " << id << ENDL << "have invalid timestamp: " << bl.timestamp);
const uint64_t height = get_current_blockchain_size();
{
m_is_in_checkpoint_zone = m_checkpoints.is_in_checkpoint_zone(height);
if (m_is_in_checkpoint_zone)
{
r = m_checkpoints.check_block(height, id);
CHECK_AND_ASSERT_MES_CUSTOM(r, false, bvc.m_verification_failed = true, "checkpoint validation failed");
}
}
bool is_pos = is_pos_block(bl);
CHECK_AND_ASSERT_MES_CUSTOM(!(is_pos && m_db_blocks.size() < m_core_runtime_config.pos_minimum_heigh), false, bvc.m_verification_failed = true, "PoS block not allowed on height " << m_db_blocks.size());
TIME_MEASURE_START_PD(target_calculating_time_2)
wide_difficulty_type current_diff = get_next_diff_conditional(is_pos);
CHECK_AND_ASSERT_MES_CUSTOM(current_diff, false, bvc.m_verification_failed = true, "!!!!!!!!! difficulty overhead !!!!!!!!!");
TIME_MEASURE_FINISH_PD(target_calculating_time_2)
auto proof = null_hash;
uint64_t pos_amount = 0;
wide_difficulty_type pos_diff_final = 0;
TIME_MEASURE_START_PD(longhash_calculating_time_3)
if (is_pos)
{
r = validate_pos_block(bl, current_diff, pos_amount, pos_diff_final, proof, id, false);
CHECK_AND_ASSERT_MES_CUSTOM(r, false, bvc.m_verification_failed = true, "validate_pos_block failed!!");
}
else
{
proof = get_block_longhash(bl);
r = check_hash(proof, current_diff);
CHECK_AND_ASSERT_MES_CUSTOM(r, false, bvc.m_verification_failed = true, "Block with id: " << id << ENDL << " : " << proof << ENDL << "unexpected difficulty: " << current_diff);
}
TIME_MEASURE_FINISH_PD(longhash_calculating_time_3)
std::size_t aliases_count_before_block = m_db_aliases.size();
r = prevalidate_miner_transaction(bl, m_db_blocks.size(), is_pos);
CHECK_AND_ASSERT_MES_CUSTOM(r, false, bvc.m_verification_failed = true, "Block with id: " << id << " failed to pass prevalidation");
size_t cumulative_block_size = 0;
size_t coinbase_blob_size = get_object_blobsize(bl.miner_tx);
/*
instead of complicated two-phase template construction and adjustment of cumulative size with block reward we
use CURRENCY_COINBASE_BLOB_RESERVED_SIZE as penalty-free coinbase transaction reservation.
*/
if (coinbase_blob_size > CURRENCY_COINBASE_BLOB_RESERVED_SIZE)
{
cumulative_block_size += coinbase_blob_size;
LOG_PRINT_CYAN("Big coinbase transaction detected: coinbase_blob_size = " << coinbase_blob_size, LOG_LEVEL_0);
}
std::vector<uint64_t> block_fees;
block_fees.reserve(bl.tx_hashes.size());
//process transactions
TIME_MEASURE_START_PD(all_txs_insert_time_5)
r = add_transaction_from_block(bl.miner_tx, get_transaction_hash(bl.miner_tx), id, height, get_actual_timestamp(bl));
CHECK_AND_ASSERT_MES_CUSTOM(r, false, bvc.m_verification_failed = true, "Block with id: " << id << " failed to add transaction to blockchain storage");
//preserve extra data to support alt pos blocks validation
//amount = > gindex_increment; a map to store how many txout_to_key outputs with such amount this block has in its transactions(including miner tx)
std::unordered_map<uint64_t, uint32_t> gindices;
append_per_block_increments_for_tx(bl.miner_tx, gindices);
size_t tx_processed_count = 0;
uint64_t fee_summary = 0;
for (const auto& tx_id : bl.tx_hashes)
{
transaction tx;
size_t blob_size = 0;
uint64_t fee = 0;
if (!m_tx_pool.take_tx(tx_id, tx, blob_size, fee))
{
LOG_PRINT_L0("Block with id: " << id << " has at least one unknown transaction with id: " << tx_id);
if (!purge_block_data_from_blockchain(bl, tx_processed_count))
LOG_ERROR("failed to purge_block_data_from_blockchain");
bvc.m_verification_failed = true;
return false;
}
append_per_block_increments_for_tx(tx, gindices);
//If we under checkpoints, ring signatures should be pruned
if (m_is_in_checkpoint_zone)
{
tx.signatures.clear();
tx.attachment.clear();
}
TIME_MEASURE_START_PD(tx_add_one_tx_time)
TIME_MEASURE_START_PD(tx_check_inputs_time)
if (!check_tx_inputs(tx, tx_id))
{
LOG_PRINT_L0("Block with id: " << id << " has at least one transaction (id: " << tx_id << ") with wrong inputs.");
currency::tx_verification_context tvc = AUTO_VAL_INIT(tvc);
const uint64_t tx_min_fee = currency::get_tx_minimum_fee(height);
bool add_res = m_tx_pool.add_tx(tx, tx_min_fee, tvc, true, true);
m_tx_pool.add_transaction_to_black_list(tx);
CHECK_AND_ASSERT_MES_NO_RET(add_res, "handle_block_to_main_chain: failed to add transaction back to transaction pool");
if (!purge_block_data_from_blockchain(bl, tx_processed_count))
LOG_ERROR("failed to purge_block_data_from_blockchain");
add_block_as_invalid(bl, id);
LOG_PRINT_L0("Block with id " << id << " added as invalid because of wrong inputs in transactions");
bvc.m_verification_failed = true;
return false;
}
TIME_MEASURE_FINISH_PD(tx_check_inputs_time)
TIME_MEASURE_START_PD(tx_prapare_append)
uint64_t current_bc_size = get_current_blockchain_size();
uint64_t actual_timestamp = get_actual_timestamp(bl);
TIME_MEASURE_FINISH_PD(tx_prapare_append)
TIME_MEASURE_START_PD(tx_append_time)
if(!add_transaction_from_block(tx, tx_id, id, current_bc_size, actual_timestamp))
{
LOG_PRINT_L0("Block with id: " << id << " failed to add transaction to blockchain storage");
currency::tx_verification_context tvc = AUTO_VAL_INIT(tvc);
const uint64_t tx_min_fee = currency::get_tx_minimum_fee(height);
bool add_res = m_tx_pool.add_tx(tx, tx_min_fee, tvc, true, true);
m_tx_pool.add_transaction_to_black_list(tx);
CHECK_AND_ASSERT_MES_NO_RET(add_res, "handle_block_to_main_chain: failed to add transaction back to transaction pool");
if (!purge_block_data_from_blockchain(bl, tx_processed_count))
LOG_ERROR("failed to purge_block_data_from_blockchain");
bvc.m_verification_failed = true;
return false;
}
TIME_MEASURE_FINISH_PD(tx_append_time)
TIME_MEASURE_FINISH_PD(tx_add_one_tx_time)
fee_summary += fee;
cumulative_block_size += blob_size;
++tx_processed_count;
if (fee)
block_fees.push_back(fee);
}
TIME_MEASURE_FINISH_PD(all_txs_insert_time_5)
TIME_MEASURE_START_PD(etc_stuff_6)
//check aliases count
if (m_db_aliases.size() - aliases_count_before_block > MAX_ALIAS_PER_BLOCK)
{
LOG_PRINT_L0("Block with id: " << id
<< " have registered too many aliases " << m_db_aliases.size() - aliases_count_before_block << ", expected no more than " << MAX_ALIAS_PER_BLOCK);
if (!purge_block_data_from_blockchain(bl, tx_processed_count))
LOG_ERROR("failed to purge_block_data_from_blockchain");
bvc.m_verification_failed = true;
return false;
}
uint64_t base_reward = 0;
uint64_t already_generated_coins = m_db_blocks.size() ? m_db_blocks.back()->already_generated_coins : 0;
if (!validate_miner_transaction(bl, cumulative_block_size, fee_summary, base_reward, already_generated_coins))
{
LOG_PRINT_L0("Block with id: " << id
<< " have wrong miner transaction");
if (!purge_block_data_from_blockchain(bl, tx_processed_count))
LOG_ERROR("failed to purge_block_data_from_blockchain");
bvc.m_verification_failed = true;
return false;
}
//fill block_extended_info
block_extended_info bei = AUTO_VAL_INIT(bei);
bei.bl = bl;
bei.height = m_db_blocks.size();
bei.block_cumulative_size = cumulative_block_size;
bei.difficulty = current_diff;
if (is_pos)
bei.stake_hash = proof;
std::size_t sequence_factor = get_current_sequence_factor(is_pos);
//precise difficulty - difficulty used to calculate next difficulty
uint64_t last_x_h = get_last_x_block_height(is_pos);
bei.cumulative_diff_precise = last_x_h ? m_db_blocks[last_x_h]->cumulative_diff_precise + current_diff : current_diff;
if (m_db_blocks.size())
bei.cumulative_diff_adjusted = m_db_blocks.back()->cumulative_diff_adjusted;
//adjusted difficulty - difficulty used to switch blockchain
wide_difficulty_type cumulative_diff_delta = is_pos ? get_adjusted_cumulative_difficulty_for_next_pos(current_diff) : current_diff;
if (bei.height >= m_core_runtime_config.pos_minimum_heigh)
cumulative_diff_delta = correct_difficulty_with_sequence_factor(sequence_factor, cumulative_diff_delta);
bei.cumulative_diff_adjusted += cumulative_diff_delta;
//etc
bei.already_generated_coins = already_generated_coins + base_reward;
auto blocks_index_ptr = m_db_blocks_index.get(id);
if (blocks_index_ptr)
{
LOG_ERROR("block with id: " << id << " already in block indexes");
if (!purge_block_data_from_blockchain(bl, tx_processed_count))
LOG_ERROR("failed to purge_block_data_from_blockchain");
bvc.m_verification_failed = true;
return false;
}
if (bei.height % ALIAS_MEDIAN_RECALC_INTERWAL)
bei.effective_tx_fee_median = get_tx_fee_median();
else
{
if (bei.height == 0)
bei.effective_tx_fee_median = 0;
else
{
LOG_PRINT_L0("Recalculating median fee...");
std::vector<uint64_t> blocks_medians;
blocks_medians.reserve(ALIAS_COST_PERIOD);
for (uint64_t i = bei.height - 1; i != 0 && ALIAS_COST_PERIOD >= bei.height - i ; i--)
{
uint64_t i_median = m_db_blocks[i]->this_block_tx_fee_median;
if (i_median)
blocks_medians.push_back(i_median);
}
bei.effective_tx_fee_median = epee::misc_utils::median(blocks_medians);
LOG_PRINT_L0("Median fee recalculated for h = " << bei.height << " as " << print_money(bei.effective_tx_fee_median));
}
}
if (block_fees.size())
{
uint64_t block_fee_median = epee::misc_utils::median(block_fees);
bei.this_block_tx_fee_median = block_fee_median;
}
m_db_blocks_index.set(id, bei.height);
push_block_to_per_block_increments(bei.height, gindices);
TIME_MEASURE_FINISH_PD(etc_stuff_6)
TIME_MEASURE_START_PD(insert_time_4)
m_db_blocks.push_back(bei);
TIME_MEASURE_FINISH_PD(insert_time_4)
TIME_MEASURE_FINISH_PD(block_processing_time_1)
TIME_MEASURE_FINISH_PD_MS(block_processing_time_0_ms)
//print result
stringstream powpos_str_entry, timestamp_str_entry;
if (is_pos)
{ // PoS
int64_t actual_ts = get_actual_timestamp(bei.bl); // signed int is intentionally used here
int64_t ts_diff = actual_ts - m_core_runtime_config.get_core_time();
powpos_str_entry << "PoS:\t" << proof << ", stake amount: " << print_money_brief(pos_amount) << ", final_difficulty: " << pos_diff_final;
timestamp_str_entry << ", actual ts: " << actual_ts << " (diff: " << std::showpos << ts_diff << "s) block ts: " << std::noshowpos << bei.bl.timestamp << " (shift: " << std::showpos << static_cast<int64_t>(bei.bl.timestamp) - actual_ts << ")";
}
else
{ // PoW
int64_t ts_diff = bei.bl.timestamp - static_cast<int64_t>(m_core_runtime_config.get_core_time());
powpos_str_entry << "PoW:\t" << proof;
timestamp_str_entry << ", block ts: " << bei.bl.timestamp << " (diff: " << std::showpos << ts_diff << "s)";
}
LOG_PRINT_L1("+++++ BLOCK SUCCESSFULLY ADDED " << (is_pos ? "[PoS]" : "[PoW]") << " Sq: " << sequence_factor
<< ENDL << "id:\t" << id << timestamp_str_entry.str()
<< ENDL << powpos_str_entry.str()
<< ENDL << "HEIGHT " << bei.height << ", difficulty: " << current_diff << ", cumul_diff_precise: " << bei.cumulative_diff_precise << ", cumul_diff_adj: " << bei.cumulative_diff_adjusted << " (+" << cumulative_diff_delta << ")"
<< ENDL << "block reward: " << print_money_brief(base_reward + fee_summary) << " (" << print_money_brief(base_reward) << " + " << print_money_brief(fee_summary)
<< ")" << ", coinbase_blob_size: " << coinbase_blob_size << ", cumulative size: " << cumulative_block_size << ", tx_count: " << bei.bl.tx_hashes.size()
<< ", " << block_processing_time_0_ms
<< "(" << block_processing_time_1
<< "/" << target_calculating_time_2
<< "/" << longhash_calculating_time_3
<< "/" << insert_time_4
<< "/" << all_txs_insert_time_5
<< "/" << etc_stuff_6
<< ")micrs");
on_block_added(bei, id, is_pos);
bvc.m_added_to_main_chain = true;
return true;
}
void blockchain_storage::on_block_added(const block_extended_info& bei, const crypto::hash& id, bool pos)
{
if (!update_next_comulative_size_limit())
LOG_ERROR("failed to update_next_comulative_size_limit");
m_timestamps_median_cache.clear();
m_tx_pool.on_blockchain_inc(bei.height, id);
TIME_MEASURE_START_PD(raise_block_core_event);
rise_core_event(CORE_EVENT_BLOCK_ADDED, void_struct());
TIME_MEASURE_FINISH_PD(raise_block_core_event);
}
//------------------------------------------------------------------
void blockchain_storage::on_block_removed(const block_extended_info& bei)
{
m_tx_pool.on_blockchain_dec(m_db_blocks.size() - 1, get_top_block_id());
m_timestamps_median_cache.clear();
LOG_PRINT_L2("block at height " << bei.height << " was removed from the blockchain");
}
//------------------------------------------------------------------
void blockchain_storage::on_abort_transaction()
{
m_event_handlers.on_clear_events();
CHECK_AND_ASSERT_MES_NO_RET(validate_blockchain_prev_links(), "EPIC FAIL! 4");
m_timestamps_median_cache.clear();
}
//------------------------------------------------------------------
bool blockchain_storage::update_next_comulative_size_limit()
{
std::vector<size_t> sz;
get_last_n_blocks_sizes(sz, CURRENCY_REWARD_BLOCKS_WINDOW);
uint64_t median = misc_utils::median(sz);
if(median <= CURRENCY_BLOCK_GRANTED_FULL_REWARD_ZONE)
median = CURRENCY_BLOCK_GRANTED_FULL_REWARD_ZONE;
m_db_current_block_cumul_sz_limit = median * 2;
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::add_new_block(const block& bl_, block_verification_context& bvc)
{
transaction_region tr(m_db, transaction_region::event_t::abort, [this] () { m_diff_cache.reset(); });
CHECK_AND_ASSERT_MES(tr, false, "failed to begin_transaction");
try
{
block bl = bl_;
crypto::hash id = get_block_hash(bl);
CRITICAL_REGION_LOCAL(m_tx_pool);
//CRITICAL_REGION_LOCAL1(m_read_lock);
if (have_block(id))
{
LOG_PRINT_L3("block with id = " << id << " already exists");
bvc.m_already_exists = true;
CHECK_AND_ASSERT_MES(validate_blockchain_prev_links(), false, "EPIC FAIL! 1");
return false;
}
//check that block refers to chain tail
if (!(bl.prev_id == get_top_block_id()))
{
//chain switching or wrong block
bvc.m_added_to_main_chain = false;
auto proof = null_hash;
alt_chain_type alt_chain;
bool r = handle_alternative_block(bl, id, proof, alt_chain, bvc);
if (!r || bvc.m_verification_failed)
{
CHECK_AND_ASSERT_MES(validate_blockchain_prev_links(), false, "EPIC FAIL! 2.2");
m_tx_pool.on_finalize_db_transaction();
return r;
}
if (bvc.m_added_to_altchain)
{
auto abei = m_alternative_chains[id];
if (is_reorganize_required(*m_db_blocks.back(), abei, proof))
{
bvc.m_added_to_altchain = false;
//do reorganize!
LOG_PRINT_GREEN("###### REORGANIZE on height: " << alt_chain.front()->second.height << " of " << m_db_blocks.size() - 1 << " with cumulative_diff_adjusted " << m_db_blocks.back()->cumulative_diff_adjusted
<< ENDL << " alternative blockchain size: " << alt_chain.size() << " with cumulative_diff_adjusted " << abei.cumulative_diff_adjusted, LOG_LEVEL_0);
bool had_rollback = false;
r = switch_to_alternative_blockchain(alt_chain, had_rollback);
if (r)
bvc.m_added_to_main_chain = true;
else
bvc.m_verification_failed = true;
if (!had_rollback) {
tr.commit();
CHECK_AND_ASSERT_MES(validate_blockchain_prev_links(), false, "EPIC FAIL! 2");
m_tx_pool.on_finalize_db_transaction();
}
}
}
return r;
//never relay alternative blocks
}
bool r = handle_block_to_main_chain(bl, id, bvc);
if (bvc.m_verification_failed || !r)
{
m_tx_pool.on_finalize_db_transaction();
on_abort_transaction();
m_event_handlers.on_clear_events();
return r;
}
tr.commit();
CHECK_AND_ASSERT_MES(validate_blockchain_prev_links(), false, "EPIC FAIL! 3");
m_tx_pool.on_finalize_db_transaction();
m_event_handlers.on_complete_events();
return r;
}
catch (const std::exception& ex)
{
bvc.m_verification_failed = true;
bvc.m_added_to_main_chain = false;
m_tx_pool.on_finalize_db_transaction();
on_abort_transaction();
LOG_ERROR("UNKNOWN EXCEPTION WHILE ADDINIG NEW BLOCK: " << ex.what());
return false;
}
catch (...)
{
bvc.m_verification_failed = true;
bvc.m_added_to_main_chain = false;
m_tx_pool.on_finalize_db_transaction();
on_abort_transaction();
LOG_ERROR("UNKNOWN EXCEPTION WHILE ADDINIG NEW BLOCK.");
return false;
}
}
//------------------------------------------------------------------
bool blockchain_storage::truncate_blockchain(uint64_t to_height)
{
transaction_region tr(m_db, transaction_region::event_t::abort, [this] () { m_diff_cache.reset(); });
CHECK_AND_ASSERT_MES(tr, false, "failed to begin_transaction");
bool res = true;
const uint64_t inital_height = get_current_blockchain_size();
while (get_current_blockchain_size() > to_height)
{
bool r = pop_block_from_blockchain(false);
if (!r)
{
LOG_ERROR("pop_block_from_blockchain() did't pop block");
res = false;
break;
}
}
CRITICAL_REGION_LOCAL(m_alternative_chains_lock);
m_alternative_chains.clear();
m_altblocks_keyimages.clear();
m_alternative_chains_txs.clear();
LOG_PRINT_MAGENTA("Blockchain truncated from " << inital_height << " to " << get_current_blockchain_size(), LOG_LEVEL_0);
tr.will_commit();
return res;
}
//------------------------------------------------------------------
bool blockchain_storage::calc_tx_cummulative_blob(const block& bl)const
{
uint64_t cummulative_size_pool = 0;
uint64_t cummulative_size_calc = 0;
uint64_t cummulative_size_serialized = 0;
uint64_t i = 0;
std::stringstream ss;
uint64_t calculated_sz_miner = get_object_blobsize(bl.miner_tx);
blobdata b = t_serializable_object_to_blob(bl.miner_tx);
uint64_t serialized_size_miner = b.size();
ss << "[COINBASE]: " << calculated_sz_miner << "|" << serialized_size_miner << ENDL;
for (auto& h : bl.tx_hashes)
{
uint64_t calculated_sz = 0;
uint64_t serialized_size = 0;
tx_memory_pool::tx_details td = AUTO_VAL_INIT(td);
bool in_pool = m_tx_pool.get_transaction(h, td);
if (in_pool)
{
calculated_sz = get_object_blobsize(td.tx);
blobdata b = t_serializable_object_to_blob(td.tx);
serialized_size = b.size();
if (td.blob_size != calculated_sz || calculated_sz != serialized_size)
{
LOG_PRINT_RED("BLOB SIZE MISMATCH IN TX: " << h << " calculated_sz: " << calculated_sz
<< " serialized_size: " << serialized_size
<< " td.blob_size: " << td.blob_size, LOG_LEVEL_0);
}
cummulative_size_pool += td.blob_size;
}
else
{
auto tx_ptr = m_db_transactions.get(h);
CHECK_AND_ASSERT_MES(tx_ptr, false, "tx " << h << " not found in blockchain nor tx_pool");
calculated_sz = get_object_blobsize(tx_ptr->tx);
blobdata b = t_serializable_object_to_blob(tx_ptr->tx);
serialized_size = b.size();
if (calculated_sz != serialized_size)
{
LOG_PRINT_RED("BLOB SIZE MISMATCH IN TX: " << h << " calculated_sz: " << calculated_sz
<< " serialized_size: " << serialized_size, LOG_LEVEL_0);
}
}
cummulative_size_calc += calculated_sz;
cummulative_size_serialized += serialized_size;
ss << "[" << i << "]" << h << ": " << calculated_sz << ENDL;
i++;
}
LOG_PRINT_MAGENTA("CUMMULATIVE_BLOCK_SIZE_TRACE: " << get_block_hash(bl) << ENDL
<< "cummulative_size_calc: " << cummulative_size_calc << ENDL
<< "cummulative_size_serialized: " << cummulative_size_serialized << ENDL
<< "cummulative_size_pool: " << cummulative_size_pool << ENDL
<< ss.str(), LOG_LEVEL_0);
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::build_kernel(const block& bl, stake_kernel& kernel, uint64_t& amount, const stake_modifier_type& stake_modifier) const
{
CHECK_AND_ASSERT_MES(is_pos_coinbase(bl.miner_tx), false, "wrong miner transaction");
const txin_to_key& txin = boost::get<txin_to_key>(bl.miner_tx.vin[1]);
CHECK_AND_ASSERT_MES(txin.key_offsets.size(), false, "wrong miner transaction");
amount = txin.amount;
return build_kernel(txin.amount, txin.k_image, kernel, stake_modifier, bl.timestamp);
}
//------------------------------------------------------------------
bool blockchain_storage::build_stake_modifier(stake_modifier_type& sm, const alt_chain_type& alt_chain, uint64_t split_height, crypto::hash *p_last_block_hash /* = nullptr */) const
{
CRITICAL_REGION_LOCAL(m_read_lock);
sm = stake_modifier_type();
auto pbei_last_pos = get_last_block_of_type(true, alt_chain, split_height);
auto pbei_last_pow = get_last_block_of_type(false, alt_chain, split_height);
CHECK_AND_ASSERT_THROW_MES(pbei_last_pow, "Internal error: pbei_last_pow is null");
if (pbei_last_pos)
sm.last_pos_kernel_id = pbei_last_pos->stake_hash;
else
{
bool r = string_tools::parse_tpod_from_hex_string(POS_STARTER_KERNEL_HASH, sm.last_pos_kernel_id);
CHECK_AND_ASSERT_MES(r, false, "Failed to parse POS_STARTER_KERNEL_HASH");
}
sm.last_pow_id = get_block_hash(pbei_last_pow->bl);
if (p_last_block_hash != nullptr)
*p_last_block_hash = get_block_hash(m_db_blocks.back()->bl);
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::build_kernel(uint64_t amount,
const crypto::key_image& ki,
stake_kernel& kernel,
const stake_modifier_type& stake_modifier,
uint64_t timestamp)const
{
currency::build_kernel(ki, kernel, stake_modifier, timestamp);
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::scan_pos(const COMMAND_RPC_SCAN_POS::request& sp, COMMAND_RPC_SCAN_POS::response& rsp) const
{
uint64_t timstamp_start = 0;
wide_difficulty_type basic_diff = 0;
CRITICAL_REGION_BEGIN(m_read_lock);
timstamp_start = m_db_blocks.back()->bl.timestamp;
basic_diff = get_cached_next_difficulty(true);
CRITICAL_REGION_END();
stake_modifier_type sm = AUTO_VAL_INIT(sm);
bool r = build_stake_modifier(sm);
CHECK_AND_ASSERT_MES(r, false, "failed to build_stake_modifier");
for (size_t i = 0; i != sp.pos_entries.size(); i++)
{
stake_kernel sk = AUTO_VAL_INIT(sk);
build_kernel(sp.pos_entries[i].amount, sp.pos_entries[i].keyimage, sk, sm, 0);
for (uint64_t ts = timstamp_start; ts < timstamp_start + POS_SCAN_WINDOW; ts++)
{
sk.block_timestamp = ts;
crypto::hash kernel_hash = crypto::cn_fast_hash(&sk, sizeof(sk));
wide_difficulty_type this_coin_diff = basic_diff / sp.pos_entries[i].amount;
if (!check_hash(kernel_hash, this_coin_diff))
continue;
else
{
//found kernel
LOG_PRINT_GREEN("Found kernel: amount=" << print_money(sp.pos_entries[i].amount) << ", key_image" << sp.pos_entries[i].keyimage, LOG_LEVEL_0);
rsp.index = i;
rsp.block_timestamp = ts;
rsp.status = CORE_RPC_STATUS_OK;
return true;
}
}
}
rsp.status = CORE_RPC_STATUS_NOT_FOUND;
return false;
}
//------------------------------------------------------------------
void blockchain_storage::set_core_runtime_config(const core_runtime_config& pc) const
{
m_core_runtime_config = pc;
m_services_mgr.set_core_runtime_config(pc);
}
//------------------------------------------------------------------
const core_runtime_config& blockchain_storage::get_core_runtime_config() const
{
return m_core_runtime_config;
}
//------------------------------------------------------------------
std::shared_ptr<const transaction_chain_entry> blockchain_storage::get_tx_chain_entry(const crypto::hash& tx_hash) const
{
CRITICAL_REGION_LOCAL(m_read_lock);
return m_db_transactions.find(tx_hash);
}
//------------------------------------------------------------------
bool blockchain_storage::validate_blockchain_prev_links(size_t last_n_blocks_to_check /* = 10 */) const
{
CRITICAL_REGION_LOCAL(m_read_lock);
TRY_ENTRY()
if (m_db_blocks.size() < 2 || last_n_blocks_to_check < 1)
return true;
bool ok = true;
for(size_t attempt_counter = 1; attempt_counter <= 2; ++attempt_counter)
{
ok = true;
for (size_t height = m_db_blocks.size() - 1, blocks_to_check = last_n_blocks_to_check; height != 0 && blocks_to_check != 0; --height, --blocks_to_check)
{
auto bei_ptr = m_db_blocks[height];
auto& bei = *bei_ptr;
if (bei.height != height)
{
LOG_ERROR("bei.height = " << bei.height << ", expected: " << height);
ok = false;
}
auto prev_bei_ptr = m_db_blocks[height - 1];
auto& prev_bei = *prev_bei_ptr;
crypto::hash prev_id = get_block_hash(prev_bei.bl);
if (bei.bl.prev_id != prev_id)
{
LOG_ERROR("EPIC FAIL: Block " << get_block_hash(bei.bl) << " @ " << height << " has prev_id == " << bei.bl.prev_id <<
" while block @ " << height - 1 << " has id: " << prev_id << ENDL <<
"Block @" << height << ":" << ENDL << currency::obj_to_json_str(bei.bl) << ENDL <<
"Block @" << height - 1 << ":" << ENDL << currency::obj_to_json_str(prev_bei.bl));
m_performance_data.epic_failure_happend = true;
ok = false;
}
}
if (ok && attempt_counter == 1)
{
break;
}
else if (!ok && attempt_counter == 1)
{
LOG_PRINT_YELLOW("************* EPIC FAIL workaround attempt: try to reset DB cache and re-check *************", LOG_LEVEL_0);
reset_db_cache();
continue;
}
else if (!ok && attempt_counter == 2)
{
LOG_PRINT_RED("************* EPIC FAIL workaround attempt failed *************", LOG_LEVEL_0);
break;
}
else if (ok && attempt_counter == 2)
{
LOG_PRINT_GREEN("************* EPIC FAIL workaround attempt succeded! *************", LOG_LEVEL_0);
break;
}
else
{
LOG_ERROR("should never get here");
return false;
}
LOG_ERROR("should never get here also");
return false;
}
return ok;
CATCH_ENTRY2(false);
}
//------------------------------------------------------------------
void blockchain_storage::push_block_to_per_block_increments(uint64_t height_, std::unordered_map<uint64_t, uint32_t>& gindices)
{
CRITICAL_REGION_LOCAL(m_read_lock);
uint32_t height = static_cast<uint32_t>(height_);
block_gindex_increments bgi = AUTO_VAL_INIT(bgi);
bgi.increments.reserve(gindices.size());
for (auto& v : gindices)
bgi.increments.push_back(gindex_increment::construct(v.first, v.second));
if (!m_db_per_block_gindex_incs.set(height, bgi))
LOG_ERROR("failed to m_db_per_block_gindex_incs.set");
}
//------------------------------------------------------------------
void blockchain_storage::pop_block_from_per_block_increments(uint64_t height_)
{
CRITICAL_REGION_LOCAL(m_read_lock);
uint32_t height = static_cast<uint32_t>(height_);
m_db_per_block_gindex_incs.erase(height);
}
//------------------------------------------------------------------
void blockchain_storage::calculate_local_gindex_lookup_table_for_height(uint64_t height, std::map<uint64_t, uint64_t>& gindexes) const
{
gindexes.clear();
CHECK_AND_ASSERT_THROW_MES(m_db_per_block_gindex_incs.size() == m_db_blocks.size(), "invariant failure: m_db_per_block_gindex_incs.size() == " << m_db_per_block_gindex_incs.size() << ", m_db_blocks.size() == " << m_db_blocks.size());
CRITICAL_REGION_LOCAL(m_read_lock);
// Calculate total number of outputs for each amount in the main chain from given height
const size_t top_block_height = static_cast<size_t>(m_db_blocks.size()) - 1;
for (uint64_t h = height; h <= top_block_height; ++h)
{
const auto p = m_db_per_block_gindex_incs.get(h);
CHECK_AND_ASSERT_THROW_MES(p, "null p for height " << h);
for (auto& el : p->increments)
gindexes[el.amount] += el.increment;
}
// Translate total number of outputs for each amount into global output indexes these amounts had at given height.
// (those amounts which are not present in the main chain after given height have the same gindexes at given height and at the most recent block)
for (auto & gindex : gindexes)
{
uint64_t & ref_index = gindex.second;
const uint64_t amount = gindex.first;
const uint64_t gindexes_in_mainchain = m_db_outputs.get_item_size(amount);
CHECK_AND_ASSERT_THROW_MES(gindexes_in_mainchain >= ref_index, "inconsistent gindex increments for amount " << amount << ": gindexes_in_mainchain == " << gindexes_in_mainchain << ", gindex increment for height " << height << " is " << ref_index);
ref_index = gindexes_in_mainchain - ref_index;
}
}
//------------------------------------------------------------------
bool blockchain_storage::validate_alt_block_input(const transaction& input_tx, std::set<crypto::key_image>& collected_keyimages, const crypto::hash& bl_id, const crypto::hash& input_tx_hash, size_t input_index,
const std::vector<crypto::signature>& input_sigs, uint64_t split_height, const alt_chain_type& alt_chain, const std::set<crypto::hash>& alt_chain_block_ids, uint64_t& ki_lookuptime,
uint64_t* p_max_related_block_height /* = nullptr */) const
{
// Main and alt chain outline:
//
// A- A- A- B- B- B- B- <-- main chain
// |
// \- C- C- C- <-- alt chain
// ^
// |
// split height
//
// List of possible cases
//
// | src tx | another | this tx |
// # | output | tx input | input | meaning
// ------------ bad cases ------------------
// b1 A A C already spent in main chain
// b2 A C C already spent in alt chain
// b3 C C C already spent in alt chain
// b4 B B/- C output not found (in case there's no valid outs in altchain C)
// ------------ good cases ------------------
// g1 A - C normal spending output from main chain A
// g2 A B C normal spending output from main chain A (although it is spent in main chain B as well)
// g3 C - C normal spending output from alt chain C
// g4 B,C - C src tx added to both main chain B and alt chain C
// g5 B,C B C src tx added to both main chain B and alt chain C, also spent in B
CRITICAL_REGION_LOCAL(m_read_lock);
bool r = false;
if (p_max_related_block_height != nullptr)
*p_max_related_block_height = 0;
CHECK_AND_ASSERT_MES(input_index < input_tx.vin.size() && input_tx.vin[input_index].type() == typeid(txin_to_key), false, "invalid input index: " << input_index);
const txin_to_key& input = boost::get<txin_to_key>(input_tx.vin[input_index]);
// check case b1: key_image spent status in main chain, should be either non-spent or has spent height >= split_height
auto p = m_db_spent_keys.get(input.k_image);
CHECK_AND_ASSERT_MES(p == nullptr || *p >= split_height, false, "key image " << input.k_image << " has been already spent in main chain at height " << *p << ", split height: " << split_height);
TIME_MEASURE_START(ki_lookup_time);
//check key_image in altchain
//check among this alt block already collected key images first
if (collected_keyimages.find(input.k_image) != collected_keyimages.end())
{
// cases b2, b3
LOG_ERROR("key image " << input.k_image << " already spent in this alt block");
return false;
}
auto ki_it = m_altblocks_keyimages.find(input.k_image);
if (ki_it != m_altblocks_keyimages.end())
{
//have some entry for this key image. Check if this key image belongs to this alt chain
const std::list<crypto::hash>& key_image_block_ids = ki_it->second;
for (auto& h : key_image_block_ids)
{
if (alt_chain_block_ids.find(h) != alt_chain_block_ids.end())
{
// cases b2, b3
LOG_ERROR("key image " << input.k_image << " already spent in altchain");
return false;
}
}
}
//update altchain with key image
collected_keyimages.insert(input.k_image);
TIME_MEASURE_FINISH(ki_lookup_time);
ki_lookuptime = ki_lookup_time;
std::vector<txout_v> abs_key_offsets = relative_output_offsets_to_absolute(input.key_offsets);
CHECK_AND_ASSERT_MES(abs_key_offsets.size() > 0 && abs_key_offsets.size() == input.key_offsets.size(), false, "internal error: abs_key_offsets.size()==" << abs_key_offsets.size() << ", input.key_offsets.size()==" << input.key_offsets.size());
// eventually we should found all public keys for all outputs this input refers to, for checking ring signature
std::vector<crypto::public_key> pub_keys(abs_key_offsets.size(), null_pkey);
//
// let's try to resolve references and populate pub keys container for check_tokey_input()
//
uint64_t global_outs_for_amount = 0;
//figure out if this amount touched alt_chain amount's index and if it is, get
bool amount_touched_altchain = false;
//auto abg_it = abei.gindex_lookup_table.find(input.amount);
//if (abg_it == abei.gindex_lookup_table.end())
if (!alt_chain.empty())
{
auto abg_it = alt_chain.back()->second.gindex_lookup_table.find(input.amount);
if (abg_it != alt_chain.back()->second.gindex_lookup_table.end())
{
amount_touched_altchain = true;
//Notice: since transactions is not allowed to refer to each other in one block, then we can consider that index in
//tx input would be always less then top for previous block, so just take it
global_outs_for_amount = abg_it->second;
}
else
{
//quite easy,
global_outs_for_amount = m_db_outputs.get_item_size(input.amount);
}
}
else
{
//quite easy,
global_outs_for_amount = m_db_outputs.get_item_size(input.amount);
}
CHECK_AND_ASSERT_MES(pub_keys.size() == abs_key_offsets.size(), false, "pub_keys.size()==" << pub_keys.size() << " != abs_key_offsets.size()==" << abs_key_offsets.size()); // just a little bit of paranoia
std::vector<const crypto::public_key*> pub_key_pointers;
for (size_t pk_n = 0; pk_n < pub_keys.size(); ++pk_n)
{
crypto::public_key& pk = pub_keys[pk_n];
crypto::hash tx_id = null_hash;
uint64_t out_n = UINT64_MAX;
auto &off = abs_key_offsets[pk_n];
if (off.type() == typeid(uint64_t))
{
uint64_t offset_gindex = boost::get<uint64_t>(off);
CHECK_AND_ASSERT_MES(offset_gindex < global_outs_for_amount, false,
"invalid global output index " << offset_gindex << " for amount=" << input.amount <<
", max is " << global_outs_for_amount <<
", referred to by offset #" << pk_n <<
", amount_touched_altchain = " << amount_touched_altchain);
if (amount_touched_altchain)
{
bool found_the_key = false;
for (auto alt_it = alt_chain.rbegin(); alt_it != alt_chain.rend(); alt_it++)
{
auto it_aag = (*alt_it)->second.gindex_lookup_table.find(input.amount);
if (it_aag == (*alt_it)->second.gindex_lookup_table.end())
{
CHECK_AND_ASSERT_MES(alt_it != alt_chain.rbegin(), false, "internal error: was marked as amount_touched_altchain but unable to find on first entry");
//item supposed to be in main chain
break;
}
if (offset_gindex >= it_aag->second)
{
//GOT IT!!
//TODO: At the moment we ignore check of mix_attr again mixing to simplify alt chain check, but in future consider it for stronger validation
uint64_t local_offset = offset_gindex - it_aag->second;
auto& alt_keys = (*alt_it)->second.outputs_pub_keys;
CHECK_AND_ASSERT_MES(local_offset < alt_keys[input.amount].size(), false, "Internal error: local_offset=" << local_offset << " while alt_keys[" << input.amount << " ].size()=" << alt_keys.size());
pk = alt_keys[input.amount][local_offset];
pub_key_pointers.push_back(&pk);
found_the_key = true;
break;
}
}
if (found_the_key)
break;
//otherwise lookup in main chain index
}
auto p = m_db_outputs.get_subitem(input.amount, offset_gindex);
CHECK_AND_ASSERT_MES(p != nullptr, false, "global output was not found, amount: " << input.amount << ", gindex: " << offset_gindex << ", referred to by offset #" << pk_n);
tx_id = p->tx_id;
out_n = p->out_no;
}
else if (off.type() == typeid(ref_by_id))
{
auto &rbi = boost::get<ref_by_id>(off);
tx_id = rbi.tx_id;
out_n = rbi.n;
}
auto p = m_db_transactions.get(tx_id);
CHECK_AND_ASSERT_MES(p != nullptr && out_n < p->tx.vout.size(), false, "can't find output #" << out_n << " for tx " << tx_id << " referred by offset #" << pk_n);
auto &t = p->tx.vout[out_n].target;
CHECK_AND_ASSERT_MES(t.type() == typeid(txout_to_key), false, "txin_to_key input offset #" << pk_n << " refers to incorrect output type " << t.type().name());
auto& out_tk = boost::get<txout_to_key>(t);
pk = out_tk.key;
bool mixattr_ok = is_mixattr_applicable_for_fake_outs_counter(out_tk.mix_attr, abs_key_offsets.size() - 1);
CHECK_AND_ASSERT_MES(mixattr_ok, false, "input offset #" << pk_n << " violates mixin restrictions: mix_attr = " << static_cast<uint32_t>(out_tk.mix_attr) << ", input's key_offsets.size = " << abs_key_offsets.size());
// case b4 (make sure source tx in the main chain is preceding split point, otherwise this referece is invalid)
CHECK_AND_ASSERT_MES(p->m_keeper_block_height < split_height, false, "input offset #" << pk_n << " refers to main chain tx " << tx_id << " at height " << p->m_keeper_block_height << " while split height is " << split_height);
if (p_max_related_block_height != nullptr && *p_max_related_block_height < p->m_keeper_block_height)
*p_max_related_block_height = p->m_keeper_block_height;
// TODO: consider checking p->tx for unlock time validity as it's checked in get_output_keys_for_input_with_checks()
// make sure it was actually found
// let's disable this check due to missing equal check in main chain validation code
//TODO: implement more strict validation with next hard fork
//CHECK_AND_ASSERT_MES(pk != null_pkey, false, "Can't determine output public key for offset " << pk_n << " in related tx: " << tx_id << ", out_n = " << out_n);
pub_key_pointers.push_back(&pk);
}
// do input checks (attachment_info, ring signature and extra signature, etc.)
r = check_tokey_input(input_tx, input_index, input, input_tx_hash, input_sigs, pub_key_pointers);
CHECK_AND_ASSERT_MES(r, false, "to_key input validation failed");
// TODO: consider checking input_tx for valid extra attachment info as it's checked in check_tx_inputs()
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::validate_alt_block_ms_input(const transaction& input_tx, const crypto::hash& input_tx_hash, size_t input_index, const std::vector<crypto::signature>& input_sigs, uint64_t split_height, const alt_chain_type& alt_chain) const
{
// Main and alt chain outline:
//
// A- A- A- B- B- B- B- <-- main chain
// |
// \- C- C- C- <-- alt chain
// ^
// |
// split height
//
// List of possible cases
//
// | src tx | another | this tx |
// # | output | tx input | input | meaning
// ------------ bad cases ------------------
// b1 A A C already spent in main chain
// b2 A C C already spent in alt chain
// b3 C C C already spent in alt chain
// b4 B B/- C output not found (in case there's no valid outs in altchain C)
// ------------ good cases ------------------
// g1 A - C normal spending output from main chain A
// g2 A B C normal spending output from main chain A (although it is spent in main chain B as well)
// g3 C - C normal spending output from alt chain C
// g4 B,C - C src tx added to both main chain B and alt chain C
// g5 B,C B C src tx added to both main chain B and alt chain C, also spent in B
CRITICAL_REGION_LOCAL(m_read_lock);
bool r = false;
CHECK_AND_ASSERT_MES(input_index < input_tx.vin.size() && input_tx.vin[input_index].type() == typeid(txin_multisig), false, "invalid ms input index: " << input_index << " or type");
const txin_multisig& input = boost::get<txin_multisig>(input_tx.vin[input_index]);
// check corresponding ms out in the main chain
auto p = m_db_multisig_outs.get(input.multisig_out_id);
if (p != nullptr)
{
// check case b1 (note: need to distinguish from case g2)
CHECK_AND_ASSERT_MES(p->spent_height == 0 || p->spent_height >= split_height, false, "ms output was already spent in main chain at height " << p->spent_height << " while split_height is " << split_height);
const crypto::hash& source_tx_id = p->tx_id;
auto p_source_tx = m_db_transactions.get(source_tx_id);
CHECK_AND_ASSERT_MES(p_source_tx != nullptr, false, "source tx for ms output " << source_tx_id << " was not found, ms out id: " << input.multisig_out_id);
if (p_source_tx->m_keeper_block_height < split_height)
{
// cases g1, g2
return check_ms_input(input_tx, input_index, input, input_tx_hash, input_sigs, p_source_tx->tx, p->out_no);
}
// p_source_tx is above split_height in main chain B, so it can't be a source for this input
// do nohting here and proceed to alt chain scan for possible cases b4, g4, g5
}
else
{
// ms out was not found in DB
// do nothing here and proceed to alt chain scan for possible cases b2, b3, g3, g4, g5
}
// walk the alt chain backward (from the the last added alt block towards split point -- it important as we stop scanning when find correct output, need to make sure it was not already spent)
for (alt_chain_type::const_reverse_iterator it = alt_chain.rbegin(); it != alt_chain.rend(); ++it)
{
const block_extended_info& bei = (*it)->second;
const block& b = bei.bl;
bool output_found = false;
auto tx_altchain_checker = [&](const transaction& tx, const crypto::hash& tx_id) -> bool
{
// check ms out being already spent in current alt chain
for (auto& in : tx.vin)
{
if (in.type() == typeid(txin_multisig))
{
// check cases b2, b3
CHECK_AND_ASSERT_MES(input.multisig_out_id != boost::get<txin_multisig>(in).multisig_out_id, false, "ms out " << input.multisig_out_id << " has been already spent in altchain by tx " << tx_id << " in block " << get_block_hash(b) << " height " << bei.height);
}
}
for (size_t out_n = 0; out_n < tx.vout.size(); ++out_n)
{
const tx_out& out = tx.vout[out_n];
if (out.target.type() == typeid(txout_multisig))
{
const crypto::hash& ms_out_id = get_multisig_out_id(tx, out_n);
if (ms_out_id == input.multisig_out_id)
{
// cases g3, g4, g5
output_found = true;
return check_ms_input(input_tx, input_index, input, input_tx_hash, input_sigs, tx, out_n);
}
}
}
return true;
};
// for each alt block look into miner_tx and txs
CHECK_AND_ASSERT_MES(tx_altchain_checker(b.miner_tx, get_transaction_hash(b.miner_tx)), false, "tx_altchain_checker failed for miner tx");
if (output_found)
return true; // g3, g4, g5
for (auto& tx_id : b.tx_hashes)
{
std::shared_ptr<transaction> tx_ptr;
r = get_transaction_from_pool_or_db(tx_id, tx_ptr, split_height);
CHECK_AND_ASSERT_MES(r, false, "can't get transaction " << tx_id << " for alt block " << get_block_hash(b) << " height " << bei.height << ", split height is " << split_height);
transaction& tx = *tx_ptr;
CHECK_AND_ASSERT_MES(tx_altchain_checker(tx, tx_id), false, "tx_altchain_checker failed for tx " << tx_id);
if (output_found)
return true; // g3, g4, g5
}
}
// case b4
LOG_ERROR("ms outout " << input.multisig_out_id << " was not found neither in main chain, nor in alt chain");
return false;
}
//------------------------------------------------------------------
bool blockchain_storage::get_transaction_from_pool_or_db(const crypto::hash& tx_id, std::shared_ptr<transaction>& tx_ptr, uint64_t min_allowed_block_height /* = 0 */) const
{
tx_ptr.reset(new transaction());
if (!m_tx_pool.get_transaction(tx_id, *tx_ptr)) // first try to get from the pool
{
auto p = m_db_transactions.get(tx_id); // if not found in the pool -- get from the DB
CHECK_AND_ASSERT_MES(p != nullptr, false, "can't get tx " << tx_id << " neither from the pool, nor from db_transactions");
CHECK_AND_ASSERT_MES(p->m_keeper_block_height >= min_allowed_block_height, false, "tx " << tx_id << " found in the main chain at height " << p->m_keeper_block_height << " while required min allowed height is " << min_allowed_block_height);
*tx_ptr = p->tx;
}
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::update_alt_out_indexes_for_tx_in_block(const transaction& tx, alt_block_extended_info& abei) const
{
//add tx outputs to gindex_lookup_table
for (auto o : tx.vout)
{
if (o.target.type() == typeid(txout_to_key))
{
//LOG_PRINT_MAGENTA("ALT_OUT KEY ON H[" << abei.height << "] AMOUNT: " << o.amount, LOG_LEVEL_0);
// first, look at local gindexes tables
if (abei.gindex_lookup_table.find(o.amount) == abei.gindex_lookup_table.end())
{
// amount was not found in altchain gindexes container, start indexing from current main chain gindex
abei.gindex_lookup_table[o.amount] = m_db_outputs.get_item_size(o.amount);
//LOG_PRINT_MAGENTA("FIRST TOUCH: size=" << abei.gindex_lookup_table[o.amount], LOG_LEVEL_0);
}
abei.outputs_pub_keys[o.amount].push_back(boost::get<txout_to_key>(o.target).key);
//TODO: At the moment we ignore check of mix_attr again mixing to simplify alt chain check, but in future consider it for stronger validation
}
}
return true;
}
bool blockchain_storage::validate_alt_block_txs(const block& b, const crypto::hash& id, std::set<crypto::key_image>& collected_keyimages, alt_block_extended_info& abei, const alt_chain_type& alt_chain, uint64_t split_height, uint64_t& ki_lookup_time_total) const
{
uint64_t height = abei.height;
bool r = false;
std::set<crypto::hash> alt_chain_block_ids;
alt_chain_block_ids.insert(id);
// prepare data structure for output global indexes tracking within current alt chain
if (alt_chain.size())
{
//TODO: in this two lines we scarify memory to earn speed for algo, but need to be careful with RAM consuming on long switches
abei.gindex_lookup_table = alt_chain.back()->second.gindex_lookup_table;
//adjust indices for next alt block entry according to emount of pubkeys in txs of prev block
auto& prev_alt_keys = alt_chain.back()->second.outputs_pub_keys;
for (auto it = prev_alt_keys.begin(); it != prev_alt_keys.end(); it++)
{
auto it_amont_in_abs_ind = abei.gindex_lookup_table.find(it->first);
CHECK_AND_ASSERT_MES(it_amont_in_abs_ind != abei.gindex_lookup_table.end(), false, "internal error: not found amount " << it->first << "in gindex_lookup_table");
//increase index starter for amount of outputs in prev block
it_amont_in_abs_ind->second += it->second.size();
}
//generate set of alt block ids
for (auto& ch : alt_chain)
{
alt_chain_block_ids.insert(get_block_hash(ch->second.bl));
}
}
else
{
// initialize alt chain entry with initial gindexes
calculate_local_gindex_lookup_table_for_height(split_height, abei.gindex_lookup_table);
}
if (is_pos_block(b))
{
// check PoS block miner tx in a special way
CHECK_AND_ASSERT_MES(is_pos_coinbase(b.miner_tx), false, "invalid PoS block's miner_tx, signatures size = " << b.miner_tx.signatures.size() << ", miner_tx.vin.size() = " << b.miner_tx.vin.size());
uint64_t max_related_block_height = 0;
uint64_t ki_lookup = 0;
r = validate_alt_block_input(b.miner_tx, collected_keyimages, id, get_block_hash(b), 1, b.miner_tx.signatures[0], split_height, alt_chain, alt_chain_block_ids, ki_lookup, &max_related_block_height);
CHECK_AND_ASSERT_MES(r, false, "miner tx " << get_transaction_hash(b.miner_tx) << ": validation failed");
ki_lookup_time_total += ki_lookup;
// check stake age
uint64_t coinstake_age = height - max_related_block_height - 1;
CHECK_AND_ASSERT_MES(coinstake_age >= m_core_runtime_config.min_coinstake_age, false,
"miner tx's coinstake age is " << coinstake_age << ", that is less than minimum required " << m_core_runtime_config.min_coinstake_age << "; max_related_block_height == " << max_related_block_height);
}
r = update_alt_out_indexes_for_tx_in_block(b.miner_tx, abei);
CHECK_AND_ASSERT_MES(r, false, "failed to update_alt_out_indexes_for_tx_in_block");
for (auto tx_id : b.tx_hashes)
{
std::shared_ptr<transaction> tx_ptr;
CHECK_AND_ASSERT_MES(get_transaction_from_pool_or_db(tx_id, tx_ptr, split_height), false, "failed to get alt block tx " << tx_id << " with split_height == " << split_height);
transaction& tx = *tx_ptr;
CHECK_AND_ASSERT_MES(tx.signatures.size() == tx.vin.size(), false, "invalid tx: tx.signatures.size() == " << tx.signatures.size() << ", tx.vin.size() == " << tx.vin.size());
for (size_t n = 0; n < tx.vin.size(); ++n)
{
if (tx.vin[n].type() == typeid(txin_to_key))
{
uint64_t ki_lookup = 0;
r = validate_alt_block_input(tx, collected_keyimages, id, tx_id, n, tx.signatures[n], split_height, alt_chain, alt_chain_block_ids, ki_lookup);
CHECK_AND_ASSERT_MES(r, false, "tx " << tx_id << ", input #" << n << ": validation failed");
ki_lookup_time_total += ki_lookup;
}
else if (tx.vin[n].type() == typeid(txin_multisig))
{
r = validate_alt_block_ms_input(tx, tx_id, n, tx.signatures[n], split_height, alt_chain);
CHECK_AND_ASSERT_MES(r, false, "tx " << tx_id << ", input #" << n << " (multisig): validation failed");
}
else if (tx.vin[n].type() == typeid(txin_gen))
{
// genesis can't be in tx_hashes
CHECK_AND_ASSERT_MES(false, false, "input #" << n << " has unexpected type (" << tx.vin[n].type().name() << ", genesis can't be in tx_hashes), tx " << tx_id);
}
else
{
CHECK_AND_ASSERT_MES(false, false, "input #" << n << " has unexpected type (" << tx.vin[n].type().name() << "), tx " << tx_id);
}
}
// Updating abei (and not updating alt_chain) during this cycle is safe because txs in the same block can't reference one another,
// so only valid references are either to previous alt blocks (accessed via alt_chain) or to main chain blocks.
r = update_alt_out_indexes_for_tx_in_block(tx, abei);
CHECK_AND_ASSERT_MES(r, false, "failed to update_alt_out_indexes_for_tx_in_block");
}
return true;
}
| 43.839339
| 348
| 0.667823
|
Virie
|
300a0a37296f82fdac346cc4df893959b5d58866
| 2,009
|
cpp
|
C++
|
src/lib/Actions/SetChildAction.cpp
|
romoadri21/boi
|
deef8e7148b50fbb36886ba4ff491a6c0e18ad67
|
[
"BSD-3-Clause"
] | null | null | null |
src/lib/Actions/SetChildAction.cpp
|
romoadri21/boi
|
deef8e7148b50fbb36886ba4ff491a6c0e18ad67
|
[
"BSD-3-Clause"
] | null | null | null |
src/lib/Actions/SetChildAction.cpp
|
romoadri21/boi
|
deef8e7148b50fbb36886ba4ff491a6c0e18ad67
|
[
"BSD-3-Clause"
] | null | null | null |
/* Copyright (c) 2010, Piet Hein Schouten. All rights reserved.
* This code is licensed under a BSD-style license that can be
* found in the LICENSE file. The license can also be found at:
* http://www.boi-project.org/license
*/
#include "ASI.h"
#include "StandardActions.h"
#include "Events/TouchEvent.h"
#include "Actions/SetChildAction.h"
namespace BOI {
SetChildAction::SetChildAction()
: Action(BOI_STD_A(SetChild)),
m_cref()
{
}
ActionCommand SetChildAction::Start(ASI* pSI, const ActionArgs* pArgs)
{
Q_UNUSED(pArgs);
m_numTouchStreams = 0;
m_cref = pSI->ActiveComponent();
if (!m_cref.IsValid())
{
return BOI_AC_STOP;
}
return BOI_AC_CONTINUE;
}
void SetChildAction::Stop(ASI* pSI)
{
Q_UNUSED(pSI);
m_cref.Reset();
}
bool SetChildAction::AcceptTouchStream()
{
return (m_numTouchStreams == 0);
}
ActionCommand SetChildAction::HandleTouchEvent(ASI* pSI, TouchEvent* pEvent)
{
int eventType = pEvent->type;
if (eventType == TouchEvent::Type_Press)
{
QPoint point(pEvent->x, pEvent->y);
int viewLayers = ViewLayerId_Main |
ViewLayerId_Overlay |
ViewLayerId_Underlay;
CRefList crefs = pSI->ComponentsAtViewPoint(point, viewLayers);
if (crefs.Count() > 0)
{
CRef child = crefs.Value(0);
if (pSI->IsSelected(child))
{
crefs = pSI->Selection();
int numCRefs = crefs.Count();
for (int i=0; i < numCRefs; i++)
{
child = crefs.Value(i);
pSI->SetParent(child, m_cref);
}
}
else
{
pSI->SetParent(child, m_cref);
}
}
m_numTouchStreams++;
}
else if (eventType == TouchEvent::Type_Release)
{
m_numTouchStreams--;
}
return BOI_AC_CONTINUE;
}
} // namespace BOI
| 19.891089
| 76
| 0.568442
|
romoadri21
|
300b47b05f32a191a9c26de5d6e716bbdedc5ac5
| 4,710
|
cpp
|
C++
|
src/Project/projecthistory.cpp
|
congpp/TABEx
|
91da62a326f70d7aa79a33e00790dce5d8088b6c
|
[
"MIT"
] | 1
|
2021-09-15T13:42:25.000Z
|
2021-09-15T13:42:25.000Z
|
src/Project/projecthistory.cpp
|
congpp/TABEx
|
91da62a326f70d7aa79a33e00790dce5d8088b6c
|
[
"MIT"
] | null | null | null |
src/Project/projecthistory.cpp
|
congpp/TABEx
|
91da62a326f70d7aa79a33e00790dce5d8088b6c
|
[
"MIT"
] | 1
|
2021-07-22T02:43:59.000Z
|
2021-07-22T02:43:59.000Z
|
#include "projecthistory.h"
#include "commondefine.h"
#include <QDir>
#include <QJsonDocument>
#include <QJsonArray>
#include <QJsonObject>
#include <QFile>
#include <QTextStream>
#include <QDateTime>
const QString HISTORY_FILE_PATH("history.json");
const int MAX_HISTROY_SIZE = 10;
ProjectHistory::ProjectHistory()
{
open();
}
ProjectHistory::~ProjectHistory()
{
save();
}
bool ProjectHistory::add(QString projFile, QString uuid)
{
for (auto it = m_history.begin(); it != m_history.end();)
{
if (it->filePath.compare(projFile, Qt::CaseInsensitive) == 0)
it = m_history.erase(it);
else
it++;
}
ProjectHistoryInfo hi;
hi.filePath = projFile;
hi.uuid = uuid;
hi.timeAccess = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
m_history.push_front(hi);
while (m_history.size() > MAX_HISTROY_SIZE)
m_history.removeLast();
return true;
}
bool ProjectHistory::save()
{
if (m_history.isEmpty())
return true;
QString filePath = getSavePath();
QFile file(filePath);
if (!file.open(QIODevice::WriteOnly|QIODevice::Text))
return false;
QJsonDocument jsDoc;
QJsonArray arr;
for (auto it : m_history)
{
QJsonObject obj;
obj.insert("filePath", it.filePath);
obj.insert("uuid", it.uuid);
obj.insert("timeAccess", it.timeAccess);
arr.append(obj);
}
jsDoc.setArray(arr);
QTextStream out(&file);
out.setCodec("UTF-8");
out << jsDoc.toJson(QJsonDocument::Indented);
file.close();
return true;
}
bool ProjectHistory::open()
{
m_history.clear();
QString filePath = getSavePath();
QFile file(filePath);
file.open(QIODevice::ReadOnly);
QByteArray data = file.readAll();
file.close();
QJsonDocument jsDoc = QJsonDocument::fromJson(data);
if (jsDoc.isNull() || jsDoc.isEmpty())
return false;
QJsonArray arr = jsDoc.array();
for (auto it : arr)
{
ProjectHistoryInfo hi;
QJsonObject obj = it.toObject();
hi.filePath = obj.take("filePath").toString();
//if (!QFile::exists(hi.filePath))
// continue;
hi.uuid = obj.take("uuid").toString();
hi.timeAccess = obj.take("timeAccess").toString();
m_history.push_back(hi);
if (m_history.size() > MAX_HISTROY_SIZE)
break;
}
//unique
auto it = std::unique(m_history.begin(), m_history.end(), [&](ProjectHistoryInfo& l, ProjectHistoryInfo& r)->bool{
return l.filePath.compare(r.filePath, Qt::CaseInsensitive) == 0;
});
m_history.erase(it, m_history.end());
return true;
}
ProjectHisotryInfoList ProjectHistory::getHistrory()
{
return m_history;
}
bool ProjectHistory::getProjectHistory(QString projFile, ProjectHistoryInfo& hist)
{
for(auto it : m_history)
{
if (it.filePath.compare(projFile, Qt::CaseInsensitive) == 0)
{
hist = it;
return true;
}
}
return false;
}
bool ProjectHistory::removeRows(int row, int count, const QModelIndex &parent)
{
int index = row * columnCount(parent) + count;
if (index < m_history.size())
{
m_history.erase(m_history.begin() + index);
QModelIndex idx = createIndex(row, count);
emit dataChanged(idx, idx);
}
return true;
}
int ProjectHistory::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
int size = m_history.size();
int col = columnCount(parent);
return size / col + (size % col != 0);
}
int ProjectHistory::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return 2;
}
QVariant ProjectHistory::data(const QModelIndex &index, int role) const
{
Q_UNUSED(index);
Q_UNUSED(role);
if (role == Qt::DisplayRole)
{
int col = index.column(), row = index.row();
int colCount = columnCount(index);
int index = row * colCount + col;
if (index >= m_history.size())
return QVariant();
ProjectHistoryInfo phi = m_history.at(index);
QStringList strs;
strs << phi.filePath << phi.timeAccess;
return QVariant(strs);
}
return QVariant();
}
Qt::ItemFlags ProjectHistory::flags(const QModelIndex &index) const
{
Q_UNUSED(index);
return Qt::ItemIsEnabled|Qt::ItemIsSelectable;
}
QString ProjectHistory::getSavePath()
{
return QDir::homePath() + PROJ_PATH_ROOT + "/" + HISTORY_FILE_PATH;
}
| 24.659686
| 119
| 0.602972
|
congpp
|
300b6e61ed6750fd7f85511a04b40ca630f7ad0d
| 6,094
|
cpp
|
C++
|
plugins/broker/src/writer.cpp
|
rdettai/vast
|
0b3cf41011df5fe8a4e8430fa6a1d6f1c50a18fa
|
[
"BSD-3-Clause"
] | 249
|
2019-08-26T01:44:45.000Z
|
2022-03-26T14:12:32.000Z
|
plugins/broker/src/writer.cpp
|
rdettai/vast
|
0b3cf41011df5fe8a4e8430fa6a1d6f1c50a18fa
|
[
"BSD-3-Clause"
] | 586
|
2019-08-06T13:10:36.000Z
|
2022-03-31T08:31:00.000Z
|
plugins/broker/src/writer.cpp
|
rdettai/vast
|
0b3cf41011df5fe8a4e8430fa6a1d6f1c50a18fa
|
[
"BSD-3-Clause"
] | 37
|
2019-08-16T02:01:14.000Z
|
2022-02-21T16:13:59.000Z
|
// _ _____ __________
// | | / / _ | / __/_ __/ Visibility
// | |/ / __ |_\ \ / / Across
// |___/_/ |_/___/ /_/ Space and Time
//
// SPDX-FileCopyrightText: (c) 2021 The VAST Contributors
// SPDX-License-Identifier: BSD-3-Clause
#include "broker/writer.hpp"
#include "broker/zeek.hpp"
#include <vast/logger.hpp>
#include <vast/table_slice.hpp>
#include <vast/type.hpp>
#include <broker/data.hh>
#include <new>
namespace vast::plugins::broker {
namespace {
caf::error convert(view<data> in, ::broker::data& out, const type& field_type) {
auto f = detail::overload{
[&](const auto& x, const auto& y) -> caf::error {
return caf::make_error(ec::type_clash, detail::pretty_type_name(x),
detail::pretty_type_name(y));
},
[&](caf::none_t, const auto&) -> caf::error {
out = {};
return {};
},
[&](view<bool> x, const bool_type&) -> caf::error {
out = x;
return {};
},
[&](view<integer> x, const integer_type&) -> caf::error {
if (field_type.name() == "port") {
out = ::broker::port{static_cast<::broker::port::number_type>(x.value),
::broker::port::protocol::unknown};
return {};
}
out = x.value;
return {};
},
[&](view<count> x, const count_type&) -> caf::error {
out = x;
return {};
},
[&](view<time> x, const time_type&) -> caf::error {
out = x;
return {};
},
[&](view<duration> x, const duration_type&) -> caf::error {
out = x;
return {};
},
[&](view<std::string> x, const string_type&) -> caf::error {
out = std::string{x};
return {};
},
[&](view<pattern> x, const pattern_type&) -> caf::error {
out = std::string{x.string()};
return {};
},
[&](view<address> x, const address_type&) -> caf::error {
auto bytes = as_bytes(x);
auto ptr = std::launder(reinterpret_cast<const uint32_t*>(bytes.data()));
out = ::broker::address{ptr, ::broker::address::family::ipv6,
::broker::address::byte_order::network};
return {};
},
[&](view<subnet> x, const subnet_type&) -> caf::error {
auto bytes = as_bytes(x.network());
auto ptr = std::launder(reinterpret_cast<const uint32_t*>(bytes.data()));
auto addr = ::broker::address{ptr, ::broker::address::family::ipv6,
::broker::address::byte_order::network};
out = ::broker::subnet(addr, x.length());
return {};
},
[&](view<enumeration> x, const enumeration_type& y) -> caf::error {
auto field = y.field(x);
if (field.empty())
return caf::make_error(ec::invalid_argument, "enum out of bounds");
out = ::broker::enum_value{std::string{field}};
return {};
},
[&](view<list> xs, const list_type& l) -> caf::error {
::broker::vector result;
result.resize(xs.size());
for (size_t i = 0; i < result.size(); ++i)
if (auto err = convert(xs->at(i), result[i], l.value_type()))
return err;
out = std::move(result);
return {};
},
[&](view<map> xs, const map_type& m) -> caf::error {
::broker::table result;
for (size_t i = 0; i < result.size(); ++i) {
::broker::data key;
::broker::data value;
auto [key_view, value_view] = xs->at(i);
if (auto err = convert(key_view, key, m.key_type()))
return err;
if (auto err = convert(value_view, value, m.value_type()))
return err;
result.emplace(std::move(key), std::move(value));
}
out = std::move(result);
return {};
},
[&](view<record>, const record_type&) -> caf::error {
return caf::make_error(ec::invalid_argument, //
"records must be flattened");
},
};
return caf::visit(f, in, field_type);
}
} // namespace
writer::writer(const caf::settings& options) {
std::string category = "vast.export.broker";
endpoint_ = make_endpoint(options, category);
status_subscriber_ = std::make_unique<::broker::status_subscriber>(
endpoint_->make_status_subscriber());
topic_ = caf::get_or(options, category + '.' + "topic", "vast/data");
event_name_ = caf::get_or(options, category + '.' + "event", "VAST::data");
}
caf::error writer::write(const table_slice& slice) {
// First check the control plane: did something change with our peering?
for (const auto& x : status_subscriber_->poll()) {
auto f = detail::overload{
[&](::broker::none) -> caf::error {
VAST_WARN("{} ignores invalid Broker status", name());
return {};
},
[&](const ::broker::error& error) -> caf::error {
VAST_WARN("{} got Broker error: {}", name(), to_string(error));
return error;
},
[&](const ::broker::status& status) -> caf::error {
VAST_INFO("{} got Broker status: {}", name(), to_string(status));
return {};
},
};
if (auto err = caf::visit(f, x))
return err;
}
// Ship data to Zeek via Broker, one event per row.
for (size_t row = 0; row < slice.rows(); ++row) {
::broker::vector xs;
const auto& layout = slice.layout();
const auto flat_layout = flatten(caf::get<record_type>(layout));
const auto columns = flat_layout.num_fields();
xs.reserve(columns);
for (size_t col = 0; col < columns; ++col) {
::broker::data x;
auto field_type = flat_layout.field(col).type;
if (auto err = convert(slice.at(row, col), x, std::move(field_type)))
return err;
xs.push_back(std::move(x));
}
::broker::vector args(2);
args[0] = std::string{layout.name()};
args[1] = std::move(xs);
auto event = ::broker::zeek::Event{event_name_, std::move(args)};
endpoint_->publish(topic_, std::move(event));
}
return caf::none;
}
caf::expected<void> writer::flush() {
return caf::no_error;
}
const char* writer::name() const {
return "broker-writer";
}
} // namespace vast::plugins::broker
| 32.940541
| 80
| 0.56088
|
rdettai
|
301dafbd11fb67c026db15b2689f07ca37af19c7
| 9,113
|
cpp
|
C++
|
code/common/string_utils.cpp
|
SamWindell/AudioUtils
|
83f81194755dcb534663ea9998749ba48e2d0466
|
[
"BSD-3-Clause"
] | 11
|
2020-05-26T18:33:39.000Z
|
2022-02-24T15:14:23.000Z
|
code/common/string_utils.cpp
|
SamWindell/AudioUtils
|
83f81194755dcb534663ea9998749ba48e2d0466
|
[
"BSD-3-Clause"
] | 5
|
2020-05-26T13:48:06.000Z
|
2022-03-26T09:38:43.000Z
|
code/common/string_utils.cpp
|
SamWindell/AudioUtils
|
83f81194755dcb534663ea9998749ba48e2d0466
|
[
"BSD-3-Clause"
] | 1
|
2021-12-30T04:08:09.000Z
|
2021-12-30T04:08:09.000Z
|
#include "string_utils.h"
#include <regex>
#include "doctest.hpp"
#include "filesystem.hpp"
bool EndsWith(std::string_view str, std::string_view suffix) {
return suffix.size() <= str.size() && str.compare(str.size() - suffix.size(), suffix.size(), suffix) == 0;
}
bool StartsWith(std::string_view str, std::string_view prefix) {
return prefix.size() <= str.size() && str.compare(0, prefix.size(), prefix) == 0;
}
bool Contains(std::string_view haystack, std::string_view needle) {
return haystack.find(needle) != std::string_view::npos;
}
std::string PutNumberInAngleBracket(usize num) { return "<" + std::to_string(num) + ">"; }
bool Replace(std::string &str, const char a, const char b) {
bool changed = false;
for (auto &c : str) {
if (c == a) {
c = b;
changed = true;
}
}
return changed;
}
bool Replace(std::string &str, std::string_view a, std::string_view b) {
bool replaced = false;
usize pos = 0;
while ((pos = str.find(a.data(), pos, a.size())) != std::string::npos) {
str.replace(pos, a.size(), b.data(), b.size());
pos += b.size();
replaced = true;
}
return replaced;
}
bool RegexReplace(std::string &str, std::string pattern, std::string replacement) {
const std::regex r {pattern};
const auto result = std::regex_replace(str, r, replacement);
if (result != str) {
str = result;
return true;
}
return false;
}
static bool NeedsRegexEscape(const char c) {
static const std::string_view special_chars = R"([]-{}()*+?.\^$|)";
for (const char &special_char : special_chars) {
if (c == special_char) {
return true;
}
}
return false;
}
bool WildcardMatch(std::string_view pattern, std::string_view name) {
std::string re_pattern;
re_pattern.reserve(pattern.size() * 2);
for (usize i = 0; i < pattern.size(); ++i) {
if (pattern[i] == '*') {
if (i + 1 < pattern.size() && pattern[i + 1] == '*') {
re_pattern += ".*";
i++;
} else {
re_pattern += "[^\\/]*";
}
} else {
if (NeedsRegexEscape(pattern[i])) {
re_pattern += '\\';
}
re_pattern += pattern[i];
}
}
const std::regex regex {re_pattern};
return std::regex_match(std::string(name), regex);
}
std::string GetJustFilenameWithNoExtension(fs::path path) {
auto filename = path.filename();
filename.replace_extension("");
return filename.generic_string();
}
std::string TrimWhitespace(std::string_view str) {
while (str.size() && std::isspace(str.back())) {
str.remove_suffix(1);
}
return std::string(str);
}
void Lowercase(std::string &str) {
for (auto &c : str) {
c = (char)std::tolower(c);
}
}
std::string ToSnakeCase(const std::string_view str) {
std::string result {str};
Lowercase(result);
Replace(result, ' ', '_');
Replace(result, '-', '_');
return result;
}
std::string ToCamelCase(const std::string_view str) {
std::string result;
result.reserve(str.size());
bool capitalise_next = true;
for (const auto c : str) {
if (c == ' ') {
capitalise_next = true;
} else {
result += capitalise_next ? (char)std::toupper(c) : c;
capitalise_next = std::isdigit(c);
}
}
return result;
}
std::string WrapText(const std::string_view text, const unsigned width) {
std::string result;
result.reserve(text.size() * 3 / 2);
usize col = 0;
for (usize i = 0; i < text.size(); ++i) {
const auto c = text[i];
if (c == '\n' || c == '\r') {
if (i != (text.size() - 1) &&
((c == '\n' && text[i + 1] == '\r') || (c == '\r' && text[i + 1] == '\n'))) {
i++;
}
result += '\n';
col = 0;
} else if (col >= width) {
bool found_space = false;
int pos = (int)result.size() - 1;
while (pos >= 0) {
if (std::isspace(result[pos])) {
result[pos] = '\n';
found_space = true;
break;
}
pos--;
}
if (found_space) {
col = (int)result.size() - pos;
} else {
result += '\n';
col = 0;
}
result += c;
} else {
result += c;
if (c >= ' ') {
col++;
}
}
}
return result;
}
std::string IndentText(const std::string_view text, usize num_indent_spaces) {
if (!num_indent_spaces) return std::string {text};
std::string spaces(num_indent_spaces, ' ');
std::string result {spaces + std::string(text)};
std::string replacement {"\n" + spaces};
Replace(result, "\n", replacement);
return result;
}
std::vector<std::string_view>
Split(std::string_view str, const std::string_view delim, bool include_empties) {
std::vector<std::string_view> result;
size_t pos = 0;
while ((pos = str.find(delim)) != std::string_view::npos) {
if (const auto section = str.substr(0, pos); section.size() || include_empties) {
result.push_back(section);
}
str.remove_prefix(pos + delim.size());
}
if (str.size()) {
result.push_back(str);
}
return result;
}
std::optional<std::string> Get3CharAlphaIdentifier(unsigned counter) {
if (counter >= 26 * 26 * 26) {
return {};
}
std::string result;
result += (char)('a' + ((counter / (26 * 26))));
counter -= (counter / (26 * 26)) * (26 * 26);
result += (char)('a' + (counter / 26));
counter -= (counter / 26) * 26;
result += (char)('a' + (counter % 26));
return result;
}
bool IsAbsoluteDirectory(std::string_view path) {
#if _WIN32
// https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file#fully-qualified-vs-relative-paths
if (StartsWith(path, "\\\\") || StartsWith(path, "//")) return true;
if (path.size() >= 3) return path[1] == ':' && (path[2] == '\\') || (path[2] == '/');
return false;
#else
return path.size() && path[0] == '/';
#endif
}
bool IsPathSyntacticallyCorrect(std::string_view path, std::string *error) {
if (error) error->clear();
#if _WIN32
if (IsAbsoluteDirectory(path)) {
path = path.substr(2);
}
char invalid_chars[] = {'<', '>', ':', '\"', '|', '?', '*'};
bool invalid = false;
for (auto c : path) {
for (auto &invalid_char : invalid_chars) {
if (invalid_char == c) {
invalid_char = '\0';
invalid = true;
if (error) error->append(1, c);
}
}
}
if (!invalid)
error->clear();
else {
error->insert(0, "The path contains the following invalid characters: (");
error->append(") ");
}
return !invalid;
#else
(void)path;
return true;
#endif
}
TEST_CASE("String Utils") {
{
std::string s {"th<>sef<> < seofi>"};
REQUIRE(Replace(s, "<>", ".."));
REQUIRE(s == "th..sef.. < seofi>");
s = "only one";
REQUIRE(Replace(s, "one", "two"));
REQUIRE(s == "only two");
REQUIRE(!Replace(s, "foo", ""));
s = "file_c-1_C4.wav";
REQUIRE(Replace(s, "c-1", "0"));
REQUIRE(s == "file_0_C4.wav");
s = "foo * * *";
REQUIRE(Replace(s, "*", "\\*"));
REQUIRE(s == "foo \\* \\* \\*");
}
{
std::string s {"HI"};
Lowercase(s);
REQUIRE(s == "hi");
}
{
REQUIRE(*Get3CharAlphaIdentifier(0) == "aaa");
REQUIRE(*Get3CharAlphaIdentifier(1) == "aab");
REQUIRE(*Get3CharAlphaIdentifier(26) == "aba");
REQUIRE(*Get3CharAlphaIdentifier(26 * 26) == "baa");
REQUIRE(*Get3CharAlphaIdentifier(26 * 26 * 2) == "caa");
REQUIRE(*Get3CharAlphaIdentifier(26 * 26 * 25) == "zaa");
REQUIRE(*Get3CharAlphaIdentifier(26 * 26 * 25 + 26 * 25) == "zza");
REQUIRE(*Get3CharAlphaIdentifier(26 * 26 * 25 + 26 * 25 + 25) == "zzz");
REQUIRE(!Get3CharAlphaIdentifier(26 * 26 * 25 + 26 * 25 + 26));
}
{
REQUIRE(ToSnakeCase("Two Words") == "two_words");
REQUIRE(ToCamelCase("folder name") == "FolderName");
REQUIRE(ToCamelCase("123 what who") == "123WhatWho");
}
{
const auto s = Split("hey,there,yo,", ",");
const auto expected = {"hey", "there", "yo"};
REQUIRE(s.size() == expected.size());
for (usize i = 0; i < s.size(); ++i) {
REQUIRE(s[i] == expected.begin()[i]);
}
}
{
const auto s = Split("hey\n||\nthere||yo||", "||");
const auto expected = {"hey\n", "\nthere", "yo"};
REQUIRE(s.size() == expected.size());
for (usize i = 0; i < s.size(); ++i) {
REQUIRE(s[i] == expected.begin()[i]);
}
}
}
| 29.022293
| 110
| 0.51443
|
SamWindell
|
3022d0af1ebd47f2fc2ebbff4257a9f27410e6c6
| 383
|
cpp
|
C++
|
modules/multi_shader_material/register_types.cpp
|
838116504/MultiShaderMaterial
|
b663d7665c53d42cdeb90762576593308f73399c
|
[
"Unlicense"
] | 2
|
2020-12-10T12:43:01.000Z
|
2021-06-28T02:48:00.000Z
|
modules/multi_shader_material/register_types.cpp
|
838116504/MultiShaderMaterial
|
b663d7665c53d42cdeb90762576593308f73399c
|
[
"Unlicense"
] | null | null | null |
modules/multi_shader_material/register_types.cpp
|
838116504/MultiShaderMaterial
|
b663d7665c53d42cdeb90762576593308f73399c
|
[
"Unlicense"
] | null | null | null |
#include <core/class_db.h>
#include "register_types.h"
#include "multi_shader_material.h"
void register_multi_shader_material_types()
{
ClassDB::register_class<MultiShaderMaterial>();
MultiShaderMaterial::get_shader_manager() = memnew(MultiShaderMaterial::ShaderManager);
}
void unregister_multi_shader_material_types()
{
memdelete(MultiShaderMaterial::get_shader_manager());
}
| 25.533333
| 88
| 0.819843
|
838116504
|
30268be5d9fdb84f7455860ee668f0fdf1062ddc
| 4,685
|
hpp
|
C++
|
lib/sml/protocol/src/parser/obis_parser.hpp
|
solosTec/node
|
e35e127867a4f66129477b780cbd09c5231fc7da
|
[
"MIT"
] | 2
|
2020-03-03T12:40:29.000Z
|
2021-05-06T06:20:19.000Z
|
lib/sml/protocol/src/parser/obis_parser.hpp
|
solosTec/node
|
e35e127867a4f66129477b780cbd09c5231fc7da
|
[
"MIT"
] | 7
|
2020-01-14T20:38:04.000Z
|
2021-05-17T09:52:07.000Z
|
lib/sml/protocol/src/parser/obis_parser.hpp
|
solosTec/node
|
e35e127867a4f66129477b780cbd09c5231fc7da
|
[
"MIT"
] | 2
|
2019-11-09T09:14:48.000Z
|
2020-03-03T12:40:30.000Z
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2018 Sylko Olzscher
*
*/
#ifndef NODE_LIB_SML_OBIS_PARSER_HPP
#define NODE_LIB_SML_OBIS_PARSER_HPP
#include <smf/sml/parser/obis_parser.h>
#include <boost/spirit/home/support/attributes.hpp> // transform_attribute
#include <boost/spirit/include/phoenix.hpp> // enable assignment of values like cyy::object
namespace node
{
namespace sml
{
/**
* The string representation of an OBIS is xxx-xxx:xxx.xxx.xxx*xxx where xxx is a decimal number
* in the range from 0 up to 255. Also a hexadecimal representation is accepted in the form
* xx xx xx xx xx xx
* The parser also supports a short representation like 0.1.0 or 0.1.2*97. The special case F.F is
* also suppported.
*/
template <typename InputIterator>
obis_parser< InputIterator >::obis_parser()
: obis_parser::base_type(r_start)
{
r_start
= boost::spirit::qi::lit("F.F")[boost::spirit::qi::_val = boost::phoenix::construct<node::sml::obis>(0, 0, 97, 97, 0, 255)]
| r_obis_medium[boost::spirit::qi::_val = boost::spirit::qi::_1]
| r_obis_short[boost::spirit::qi::_val = boost::spirit::qi::_1]
| r_obis_dec[boost::spirit::qi::_val = boost::spirit::qi::_1]
| r_obis_hex[boost::spirit::qi::_val = boost::spirit::qi::_1]
;
// example: 0.1.2&04
// ToDo: set 'manual reset' flag
// The '&' signals the values has been reset manually
r_obis_medium
= (boost::spirit::qi::ushort_
>> '.'
>> boost::spirit::qi::ushort_
>> '.'
>> boost::spirit::qi::ushort_
>> '*'
>> boost::spirit::qi::ushort_)[boost::spirit::qi::_val = boost::phoenix::construct<obis>(0, 0, boost::spirit::qi::_1, boost::spirit::qi::_2, boost::spirit::qi::_3, boost::spirit::qi::_4)]
| (boost::spirit::qi::ushort_
>> '.'
>> boost::spirit::qi::ushort_
>> '.'
>> boost::spirit::qi::ushort_
>> '&'
>> boost::spirit::qi::ushort_)[boost::spirit::qi::_val = boost::phoenix::construct<obis>(0, 0, boost::spirit::qi::_1, boost::spirit::qi::_2, boost::spirit::qi::_3, boost::spirit::qi::_4)]
;
// example: 0.1.0
r_obis_short
= (boost::spirit::qi::ushort_
>> '.'
>> boost::spirit::qi::ushort_
>> '.'
>> boost::spirit::qi::ushort_)[boost::spirit::qi::_val = boost::phoenix::construct<obis>(0, 0, boost::spirit::qi::_1, boost::spirit::qi::_2, boost::spirit::qi::_3, 255)]
| (boost::spirit::qi::lit("C.")
>> boost::spirit::qi::ushort_
>> '.'
>> boost::spirit::qi::ushort_)[boost::spirit::qi::_val = boost::phoenix::construct<obis>(0, 0, 96, boost::spirit::qi::_1, boost::spirit::qi::_2, 255)]
| (boost::spirit::qi::lit("F.")
>> boost::spirit::qi::ushort_
>> '.'
>> boost::spirit::qi::ushort_)[boost::spirit::qi::_val = boost::phoenix::construct<obis>(0, 0, 97, boost::spirit::qi::_1, boost::spirit::qi::_2, 255)]
| (boost::spirit::qi::lit("L.")
>> boost::spirit::qi::ushort_
>> '.'
>> boost::spirit::qi::ushort_)[boost::spirit::qi::_val = boost::phoenix::construct<obis>(0, 0, 98, boost::spirit::qi::_1, boost::spirit::qi::_2, 255)]
| (boost::spirit::qi::lit("P.")
>> boost::spirit::qi::ushort_
>> '.'
>> boost::spirit::qi::ushort_)[boost::spirit::qi::_val = boost::phoenix::construct<obis>(0, 0, 99, boost::spirit::qi::_1, boost::spirit::qi::_2, 255)]
;
//
// accepts: 1-1:1.2.1 and 1-1:1.2.1*255 are the same
//
r_obis_dec
= (boost::spirit::qi::ushort_
>> '-'
>> boost::spirit::qi::ushort_
>> ':'
>> boost::spirit::qi::ushort_
>> '.'
>> boost::spirit::qi::ushort_
>> '.'
>> boost::spirit::qi::ushort_
>> '*'
>> boost::spirit::qi::ushort_)
[boost::spirit::qi::_val = boost::phoenix::construct<node::sml::obis>(boost::spirit::qi::_1, boost::spirit::qi::_2, boost::spirit::qi::_3, boost::spirit::qi::_4, boost::spirit::qi::_5, boost::spirit::qi::_6)]
| (boost::spirit::qi::ushort_
>> '-'
>> boost::spirit::qi::ushort_
>> ':'
>> boost::spirit::qi::ushort_
>> '.'
>> boost::spirit::qi::ushort_
>> '.'
>> boost::spirit::qi::ushort_)
[boost::spirit::qi::_val = boost::phoenix::construct<node::sml::obis>(boost::spirit::qi::_1, boost::spirit::qi::_2, boost::spirit::qi::_3, boost::spirit::qi::_4, boost::spirit::qi::_5, 255)]
;
r_obis_hex
= (r_byte
>> r_byte
>> r_byte
>> r_byte
>> r_byte
>> r_byte)[boost::spirit::qi::_val = boost::phoenix::construct<node::sml::obis>(boost::spirit::qi::_1, boost::spirit::qi::_2, boost::spirit::qi::_3, boost::spirit::qi::_4, boost::spirit::qi::_5, boost::spirit::qi::_6)]
;
}
}
}
#endif
| 36.889764
| 222
| 0.594237
|
solosTec
|
3027d6dddd03260f25df5a1d08318d7d8e95c310
| 418
|
cc
|
C++
|
src/native.cc
|
shin1m/xemmai
|
dbeb22058ffdec0dda7d2575b86e750b87ed4197
|
[
"MIT",
"Unlicense"
] | 5
|
2015-11-01T22:08:39.000Z
|
2021-06-08T04:44:38.000Z
|
src/native.cc
|
shin1m/xemmai
|
dbeb22058ffdec0dda7d2575b86e750b87ed4197
|
[
"MIT",
"Unlicense"
] | null | null | null |
src/native.cc
|
shin1m/xemmai
|
dbeb22058ffdec0dda7d2575b86e750b87ed4197
|
[
"MIT",
"Unlicense"
] | null | null | null |
#include <xemmai/global.h>
namespace xemmai
{
size_t t_type_of<t_native>::f_do_call(t_object* a_this, t_pvalue* a_stack, size_t a_n)
{
auto& p = a_this->f_as<t_native>();
p.v_function(&p.v_library->f_as<t_library>(), a_stack, a_n);
return -1;
}
size_t t_type_of<t_native>::f_do_get_at(t_object* a_this, t_pvalue* a_stack)
{
a_stack[0] = xemmai::f_new<t_method>(f_global(), a_this, a_stack[2]);
return -1;
}
}
| 20.9
| 86
| 0.712919
|
shin1m
|
6f787b548eda97a7b572a2cae44519bc3884946e
| 103
|
hpp
|
C++
|
handsome/cpp_src/BitmapWriter.hpp
|
bracket/handsome
|
c93d34f94d0eea24f5514efc9bc423eb28b44a6b
|
[
"BSD-2-Clause"
] | null | null | null |
handsome/cpp_src/BitmapWriter.hpp
|
bracket/handsome
|
c93d34f94d0eea24f5514efc9bc423eb28b44a6b
|
[
"BSD-2-Clause"
] | null | null | null |
handsome/cpp_src/BitmapWriter.hpp
|
bracket/handsome
|
c93d34f94d0eea24f5514efc9bc423eb28b44a6b
|
[
"BSD-2-Clause"
] | null | null | null |
#pragma once
struct SampleBuffer;
void write_bitmap(char const * path, SampleBuffer const & Buffer);
| 17.166667
| 66
| 0.776699
|
bracket
|
6f78b79f023d3e27fd3ebdb9b3577623823b91e8
| 1,179
|
cpp
|
C++
|
lintcode/isPalindor.cpp
|
Broadroad/learnLeetcode
|
c4af121b3451caa4d53819c5f8c62b38e8e5fb87
|
[
"Apache-2.0"
] | null | null | null |
lintcode/isPalindor.cpp
|
Broadroad/learnLeetcode
|
c4af121b3451caa4d53819c5f8c62b38e8e5fb87
|
[
"Apache-2.0"
] | null | null | null |
lintcode/isPalindor.cpp
|
Broadroad/learnLeetcode
|
c4af121b3451caa4d53819c5f8c62b38e8e5fb87
|
[
"Apache-2.0"
] | null | null | null |
class Solution {
public:
/*
* @param s: A string
* @return: A list of lists of string
*/
vector<vector<string>> partition(string &s) {
// write your code here
vector<vector<string>> results;
if (s.size() == 0) {
return results;
}
vector<string> result;
dfs(s, results, result, 0);
return results;
}
private:
void dfs(string &s, vector<vector<string>> &results, vector<string>& result, int index) {
if (index == s.size()) {
results.push_back(result);
return;
}
for (int i = index; i < s.size(); i++) {
string sub = s.substr(index, i+1-index);
if (!isPalindor(sub))
continue;
result.push_back(sub);
dfs(s, results, result, i+1);
result.pop_back();
}
}
bool isPalindor(string &s) {
int len = s.size();
bool flag = true;
int i = 0, j = len-1;
for (int i = 0; i <= j; i++,j--) {
if (s[i] != s[j]) {
return false;
}
}
return true;
}
};
| 23.58
| 93
| 0.449534
|
Broadroad
|
6f7f362a2c56bbbc25a155ed6f55157202385ffd
| 2,212
|
cpp
|
C++
|
vsl/Parser/ErrorListener.cpp
|
VegaLib/VSL
|
c110b1b8ce6aa7a88d2bc97a3e99385e638dfc6d
|
[
"MS-PL"
] | null | null | null |
vsl/Parser/ErrorListener.cpp
|
VegaLib/VSL
|
c110b1b8ce6aa7a88d2bc97a3e99385e638dfc6d
|
[
"MS-PL"
] | null | null | null |
vsl/Parser/ErrorListener.cpp
|
VegaLib/VSL
|
c110b1b8ce6aa7a88d2bc97a3e99385e638dfc6d
|
[
"MS-PL"
] | null | null | null |
/*
* Microsoft Public License (Ms-PL) - Copyright (c) 2020-2021 Sean Moss
* This file is subject to the terms and conditions of the Microsoft Public License, the text of which can be found in
* the 'LICENSE' file at the root of this repository, or online at <https://opensource.org/licenses/MS-PL>.
*/
#include "./ErrorListener.hpp"
#include "./Parser.hpp"
#define STRMATCH(mstr) (msg.find(mstr)!=string::npos)
#define ISRULE(rule) (ruleIdx==grammar::VSL::Rule##rule)
namespace vsl
{
// ====================================================================================================================
ErrorListener::ErrorListener(Parser* parser)
: parser_{ parser }
{
}
// ====================================================================================================================
ErrorListener::~ErrorListener()
{
}
// ====================================================================================================================
void ErrorListener::syntaxError(antlr4::Recognizer* recognizer, antlr4::Token* badToken, size_t line,
size_t charPosition, const std::string& msg, std::exception_ptr e)
{
using namespace antlr4;
// Extract extra error information from the exception
const RuleContext* ctx{ nullptr };
string badText = badToken ? badToken->getText() : "";
if (e) {
try { std::rethrow_exception(e); }
catch (const RecognitionException& ex) {
ctx = ex.getCtx();
if (badText.empty() && ex.getOffendingToken()) {
badText = ex.getOffendingToken()->getText();
}
}
}
const size_t ruleIdx = ctx ? ctx->getRuleIndex() : SIZE_MAX;
// The customized error text (TODO: Expand this by exhaustively testing the different errors)
string errorMsg{};
// Check all of the known error combinations
if (false) {
}
else {
// Fallback for errors we have not customized a response to
errorMsg = mkstr("(Rule '%s') (Bad Text: '%s') - %s",
(ruleIdx == SIZE_MAX) ? "none" : recognizer->getRuleNames()[ruleIdx].c_str(),
badText.c_str(), msg.c_str());
}
// Set the parser error
parser_->error_ = ShaderError(errorMsg, uint32(line), uint32(charPosition));
if (!badText.empty()) {
parser_->error_.badText(badText);
}
}
} // namespace vsl
| 30.722222
| 119
| 0.580922
|
VegaLib
|
6f806d3812068b0f1eb74c4db116985ecdadab53
| 22
|
cpp
|
C++
|
SpaceCube/UI/Transpose.cpp
|
marci07iq/SpaceCube
|
464bc3fa1090bed273bcaa3257aebeacc4e8d3b0
|
[
"MIT"
] | 2
|
2019-11-05T14:48:34.000Z
|
2019-11-05T14:49:30.000Z
|
SpaceCube/UI/Transpose.cpp
|
marci07iq/SpaceCube
|
464bc3fa1090bed273bcaa3257aebeacc4e8d3b0
|
[
"MIT"
] | null | null | null |
SpaceCube/UI/Transpose.cpp
|
marci07iq/SpaceCube
|
464bc3fa1090bed273bcaa3257aebeacc4e8d3b0
|
[
"MIT"
] | null | null | null |
#include "Transpose.h"
| 22
| 22
| 0.772727
|
marci07iq
|
6f8a7a146c91c14100a4a395aeac24c3c407438a
| 2,963
|
cpp
|
C++
|
src/Kmers_Validator.cpp
|
jurikuronen/cuttlefish
|
af041879e0322748155081271676c189b26f3a59
|
[
"BSD-3-Clause"
] | 43
|
2020-07-29T21:36:21.000Z
|
2022-03-22T14:36:34.000Z
|
src/Kmers_Validator.cpp
|
jurikuronen/cuttlefish
|
af041879e0322748155081271676c189b26f3a59
|
[
"BSD-3-Clause"
] | 10
|
2020-10-28T14:09:00.000Z
|
2022-02-06T22:22:48.000Z
|
src/Kmers_Validator.cpp
|
jurikuronen/cuttlefish
|
af041879e0322748155081271676c189b26f3a59
|
[
"BSD-3-Clause"
] | 2
|
2021-02-15T15:58:38.000Z
|
2021-11-03T12:14:39.000Z
|
#include "Validator.hpp"
#include "Directed_Kmer.hpp"
#include "Kmer_Container.hpp"
#include "BBHash/BooPHF.h"
#include "spdlog/sinks/stdout_color_sinks.h"
#include <fstream>
template <uint16_t k>
void Validator<k>::validate_kmer_set(bool& result) const
{
console->info("Testing validation of the uniqueness of the k-mers and completeness of the k-mer set in the produced unitigs.\n");
const std::string& kmc_db_path = params.kmc_db_path();
const std::string& cdbg_file_path = params.cdbg_file_path();
const Kmer_Container<k> kmer_container(kmc_db_path);
const uint64_t kmer_count = kmer_container.size();
console->info("Number of k-mers in the database: {}\n", kmer_count);
std::vector<bool> is_present(kmer_count);
uint64_t kmers_seen = 0;
uint64_t kmers_repeated = 0;
uint64_t unitigs_processed = 0;
uint64_t kmers_invalid = 0;
// Scan through the unitigs one-by-one.
std::string unitig;
std::ifstream input(cdbg_file_path.c_str(), std::ifstream::in);
while(input >> unitig)
{
const Kmer<k> first_kmer(unitig, 0);
Directed_Kmer<k> kmer(first_kmer);
// Scan through the k-mers one-by-one.
for(size_t kmer_idx = 0; kmer_idx <= unitig.length() - k; ++kmer_idx)
{
uint64_t hash_val = mph->lookup(kmer.canonical());
// Encountered a k-mer that is absent at the k-mer database and hashes outside of the valid range.
if(hash_val >= kmer_count)
{
console->error("Invalid k-mer encountered.\n");
kmers_invalid++;
}
// Encountered a k-mer for the first time that is either a k-mer present at the database, or is
// absent there but hashes to the value of a present one (and that present one hasn't been seen yet).
else if(!is_present[hash_val])
is_present[hash_val] = true;
// A repeated k-mer is seen.
else
{
console->info("Repeated k-mer encountered.\n");
kmers_repeated++;
}
if(kmer_idx < unitig.length() - k)
kmer.roll_to_next_kmer(unitig[kmer_idx + k]);
}
kmers_seen += unitig.length() - k + 1;
unitigs_processed++;
if(unitigs_processed % PROGRESS_GRAIN_SIZE == 0)
console->info("Validated {}M unitigs.\n", unitigs_processed / 1000000);
}
console->info("Total number of repeated k-mers: {}\n", kmers_repeated);
console->info("Total number of invalid k-mers: {}\n", kmers_invalid);
console->info("Total number of k-mers seen: {}\n", kmers_seen);
console->info("Total number of k-mers expected: {}\n", kmer_count);
input.close();
result = (!kmers_repeated && !kmers_invalid && kmers_seen == kmer_count);
}
// Template instantiations for the required specializations.
ENUMERATE(INSTANCE_COUNT, INSTANTIATE, Validator)
| 34.057471
| 133
| 0.633142
|
jurikuronen
|
6f91b98ab0b9f7a1956093001fd4486862c51eb7
| 4,843
|
cpp
|
C++
|
android-31/java/time/chrono/MinguoDate.cpp
|
YJBeetle/QtAndroidAPI
|
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
|
[
"Apache-2.0"
] | 12
|
2020-03-26T02:38:56.000Z
|
2022-03-14T08:17:26.000Z
|
android-31/java/time/chrono/MinguoDate.cpp
|
YJBeetle/QtAndroidAPI
|
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
|
[
"Apache-2.0"
] | 1
|
2021-01-27T06:07:45.000Z
|
2021-11-13T19:19:43.000Z
|
android-29/java/time/chrono/MinguoDate.cpp
|
YJBeetle/QtAndroidAPI
|
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
|
[
"Apache-2.0"
] | 3
|
2021-02-02T12:34:55.000Z
|
2022-03-08T07:45:57.000Z
|
#include "../../io/ObjectInputStream.hpp"
#include "../../../JObject.hpp"
#include "../../../JString.hpp"
#include "../Clock.hpp"
#include "../LocalDate.hpp"
#include "../LocalTime.hpp"
#include "../ZoneId.hpp"
#include "./MinguoChronology.hpp"
#include "./MinguoEra.hpp"
#include "../temporal/ValueRange.hpp"
#include "./MinguoDate.hpp"
namespace java::time::chrono
{
// Fields
// QJniObject forward
MinguoDate::MinguoDate(QJniObject obj) : JObject(obj) {}
// Constructors
// Methods
java::time::chrono::MinguoDate MinguoDate::from(JObject arg0)
{
return callStaticObjectMethod(
"java.time.chrono.MinguoDate",
"from",
"(Ljava/time/temporal/TemporalAccessor;)Ljava/time/chrono/MinguoDate;",
arg0.object()
);
}
java::time::chrono::MinguoDate MinguoDate::now()
{
return callStaticObjectMethod(
"java.time.chrono.MinguoDate",
"now",
"()Ljava/time/chrono/MinguoDate;"
);
}
java::time::chrono::MinguoDate MinguoDate::now(java::time::Clock arg0)
{
return callStaticObjectMethod(
"java.time.chrono.MinguoDate",
"now",
"(Ljava/time/Clock;)Ljava/time/chrono/MinguoDate;",
arg0.object()
);
}
java::time::chrono::MinguoDate MinguoDate::now(java::time::ZoneId arg0)
{
return callStaticObjectMethod(
"java.time.chrono.MinguoDate",
"now",
"(Ljava/time/ZoneId;)Ljava/time/chrono/MinguoDate;",
arg0.object()
);
}
java::time::chrono::MinguoDate MinguoDate::of(jint arg0, jint arg1, jint arg2)
{
return callStaticObjectMethod(
"java.time.chrono.MinguoDate",
"of",
"(III)Ljava/time/chrono/MinguoDate;",
arg0,
arg1,
arg2
);
}
JObject MinguoDate::atTime(java::time::LocalTime arg0) const
{
return callObjectMethod(
"atTime",
"(Ljava/time/LocalTime;)Ljava/time/chrono/ChronoLocalDateTime;",
arg0.object()
);
}
jboolean MinguoDate::equals(JObject arg0) const
{
return callMethod<jboolean>(
"equals",
"(Ljava/lang/Object;)Z",
arg0.object<jobject>()
);
}
java::time::chrono::MinguoChronology MinguoDate::getChronology() const
{
return callObjectMethod(
"getChronology",
"()Ljava/time/chrono/MinguoChronology;"
);
}
java::time::chrono::MinguoEra MinguoDate::getEra() const
{
return callObjectMethod(
"getEra",
"()Ljava/time/chrono/MinguoEra;"
);
}
jlong MinguoDate::getLong(JObject arg0) const
{
return callMethod<jlong>(
"getLong",
"(Ljava/time/temporal/TemporalField;)J",
arg0.object()
);
}
jint MinguoDate::hashCode() const
{
return callMethod<jint>(
"hashCode",
"()I"
);
}
jint MinguoDate::lengthOfMonth() const
{
return callMethod<jint>(
"lengthOfMonth",
"()I"
);
}
java::time::chrono::MinguoDate MinguoDate::minus(JObject arg0) const
{
return callObjectMethod(
"minus",
"(Ljava/time/temporal/TemporalAmount;)Ljava/time/chrono/MinguoDate;",
arg0.object()
);
}
java::time::chrono::MinguoDate MinguoDate::minus(jlong arg0, JObject arg1) const
{
return callObjectMethod(
"minus",
"(JLjava/time/temporal/TemporalUnit;)Ljava/time/chrono/MinguoDate;",
arg0,
arg1.object()
);
}
java::time::chrono::MinguoDate MinguoDate::plus(JObject arg0) const
{
return callObjectMethod(
"plus",
"(Ljava/time/temporal/TemporalAmount;)Ljava/time/chrono/MinguoDate;",
arg0.object()
);
}
java::time::chrono::MinguoDate MinguoDate::plus(jlong arg0, JObject arg1) const
{
return callObjectMethod(
"plus",
"(JLjava/time/temporal/TemporalUnit;)Ljava/time/chrono/MinguoDate;",
arg0,
arg1.object()
);
}
java::time::temporal::ValueRange MinguoDate::range(JObject arg0) const
{
return callObjectMethod(
"range",
"(Ljava/time/temporal/TemporalField;)Ljava/time/temporal/ValueRange;",
arg0.object()
);
}
jlong MinguoDate::toEpochDay() const
{
return callMethod<jlong>(
"toEpochDay",
"()J"
);
}
JString MinguoDate::toString() const
{
return callObjectMethod(
"toString",
"()Ljava/lang/String;"
);
}
JObject MinguoDate::until(JObject arg0) const
{
return callObjectMethod(
"until",
"(Ljava/time/chrono/ChronoLocalDate;)Ljava/time/chrono/ChronoPeriod;",
arg0.object()
);
}
jlong MinguoDate::until(JObject arg0, JObject arg1) const
{
return callMethod<jlong>(
"until",
"(Ljava/time/temporal/Temporal;Ljava/time/temporal/TemporalUnit;)J",
arg0.object(),
arg1.object()
);
}
java::time::chrono::MinguoDate MinguoDate::with(JObject arg0) const
{
return callObjectMethod(
"with",
"(Ljava/time/temporal/TemporalAdjuster;)Ljava/time/chrono/MinguoDate;",
arg0.object()
);
}
java::time::chrono::MinguoDate MinguoDate::with(JObject arg0, jlong arg1) const
{
return callObjectMethod(
"with",
"(Ljava/time/temporal/TemporalField;J)Ljava/time/chrono/MinguoDate;",
arg0.object(),
arg1
);
}
} // namespace java::time::chrono
| 22.737089
| 81
| 0.68057
|
YJBeetle
|
6f972cbe44688a519eb5aa3781a345d4b740312d
| 4,152
|
cpp
|
C++
|
src/main.cpp
|
RigoLigoRLC/QuikMCAsset
|
f075485f36f52416756d9d0dbd5628fee77c5e34
|
[
"MIT"
] | 1
|
2020-02-28T16:43:22.000Z
|
2020-02-28T16:43:22.000Z
|
src/main.cpp
|
RigoLigoRLC/QuikMCAsset
|
f075485f36f52416756d9d0dbd5628fee77c5e34
|
[
"MIT"
] | null | null | null |
src/main.cpp
|
RigoLigoRLC/QuikMCAsset
|
f075485f36f52416756d9d0dbd5628fee77c5e34
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <string>
#include <cstdio>
#include "rapidjson.hpp"
using std::string;
using std::cout;
using std::cin;
using std::endl;
using rapidjson::FileReadStream;
using rapidjson::Document;
using rapidjson::Value;
//#define TEST_SUPPLY_FILE_PATH
int restoreHierachy(const string&, const string&);
int processFile(const string&, const string&, const string&, const string&);
int createDirectory(const string&);
bool isDirectoryExist(const string& path);
int copyFile(const string&, const string&);
void findAndReplaceString(std::string& subject, const std::string& search, const std::string& replace);
string lastFileDirectory;
int main()
{
string jsonFilePath, outputFolderPath;
# ifdef TEST_SUPPLY_FILE_PATH
# ifdef WIN32
jsonFilePath = "E:\\MultiMC\\assets\\indexes\\1.13.json";
outputFolderPath = "E:\\MCASSETS\\";
# else
jsonFilePath = "/home/rigoligo/.local/share/multimc/assets/indexes/1.15.json";
outputFolderPath = "/mnt/iw_entertainment/ASSETS/";
# endif
# else
cout << "Enter the absolute path of .../assets/indexes/[GAME_VERSION].json: ";
getline(cin, jsonFilePath);
cout << "Enter the absolute path of output directory: ";
getline(cin, outputFolderPath);
//jsonFilePath.pop_back();
//outputFolderPath.pop_back();
# endif
# ifdef _WIN32
if(outputFolderPath[outputFolderPath.size() - 1] != '\\')
outputFolderPath += '\\';
# else
if(outputFolderPath[outputFolderPath.size() - 1] != '/')
outputFolderPath += '/';
# endif
restoreHierachy(jsonFilePath, outputFolderPath);
return 0;
}
int restoreHierachy(const string &jsonPath, const string &outputPath)
{
std::FILE *parseFile = std::fopen(jsonPath.c_str(), "r");
char *readbuffer = new char[BUFSIZ];
FileReadStream fileReader(parseFile, readbuffer, BUFSIZ);
Document parsedDoc;
Value *objObjects;
parsedDoc.ParseStream(fileReader);
std::fclose(parseFile);
if(parsedDoc.HasParseError())
{
cout << "\tError when parsing file \"" << jsonPath << "\":\n"
<< "\tError code " << parsedDoc.GetParseError() << " at offset "
<< parsedDoc.GetErrorOffset() << ".\n";
throw "Cannot parse JSON.";
}
if(parsedDoc.HasMember("objects"))
{
objObjects = &parsedDoc["objects"];
if(!objObjects->IsObject())
throw "Wrong type of \"objects\".";
}
else
throw "\"objects\" not found.";
string objHash, objFilename, assetObjectPath;
# ifdef WIN32
assetObjectPath = jsonPath.substr(0, jsonPath.find_last_of('\\') - 7);
# else
assetObjectPath = jsonPath.substr(0, jsonPath.find_last_of('/') - 7);
# endif
for(auto i = objObjects->MemberBegin(); i != objObjects->MemberEnd(); i++)
{
objFilename = i->name.GetString();
objHash = i->value["hash"].GetString();
# ifdef WIN32
findAndReplaceString(objFilename, "/", "\\");
# endif
cout << objHash << ": " << objFilename << endl;
processFile(objHash, objFilename, outputPath, assetObjectPath);
}
return 0;
};
int processFile(const string& hash, const string& filename, const string& fullDestination,const string& assetPath)
{
//First determine if this file is in the same directory as the last one
//If so then just copy, don't create directory
# ifdef _WIN32
string thisDirectory = filename.substr(0, filename.find_last_of('\\') + 1);
# else
string thisDirectory = filename.substr(0, filename.find_last_of('/') + 1);
# endif
if(thisDirectory != lastFileDirectory)
{
if(!isDirectoryExist(fullDestination + thisDirectory))
createDirectory(fullDestination + thisDirectory);
lastFileDirectory = thisDirectory;
}
# ifdef _WIN32
copyFile(assetPath + "objects\\" + hash.substr(0, 2) + "\\" + hash, fullDestination + filename);
# else
copyFile(assetPath + "objects/" + hash.substr(0, 2) + "/" + hash, fullDestination + filename);
# endif
return 0;
}
void findAndReplaceString(std::string& subject, const std::string& search, const std::string& replace) {
size_t pos = 0;
while ((pos = subject.find(search, pos)) != std::string::npos)
{
subject.replace(pos, search.length(), replace);
pos += replace.length();
}
}
| 29.034965
| 114
| 0.685212
|
RigoLigoRLC
|
6f9a6bb8f819f22c502388e8f5b0638ba8859891
| 5,258
|
cpp
|
C++
|
src/main_camshift.cpp
|
LorisFriedel/learning-sign-language
|
f87767c43a11c01885628c1de10daa9d1a58e6ad
|
[
"MIT"
] | null | null | null |
src/main_camshift.cpp
|
LorisFriedel/learning-sign-language
|
f87767c43a11c01885628c1de10daa9d1a58e6ad
|
[
"MIT"
] | null | null | null |
src/main_camshift.cpp
|
LorisFriedel/learning-sign-language
|
f87767c43a11c01885628c1de10daa9d1a58e6ad
|
[
"MIT"
] | null | null | null |
//
// @author Loris Friedel
//
#include <tclap/CmdLine.h>
#include <cv.hpp>
#include "../inc/code.h"
#include "../inc/log.h"
#include "../inc/VideoStreamReader.hpp"
#include "../inc/ObjectDetector.hpp"
#include "../inc/CamshiftRunner.hpp"
#include "../inc/KeyInputHandler.hpp"
#include "../inc/colors.h"
#include "../inc/constant.h"
int runCamshiftTrack(VideoStreamReader &vsr, const cv::CascadeClassifier &cascade);
// Main
int main(int argc, const char **argv) {
try {
TCLAP::CmdLine cmd("!!! Help for camshift tracking program. It uses a pre-configured classifier for object detect and camshift calibration. !!!"
"\n=> Press '$' to stop the program. "
"\n=> Press '*' to toggle backprojection display."
"\n=> Press '!' to force the tracker to recalibrate using object detection."
"\nWritten by Loris Friedel",
' ', "1.0");
TCLAP::ValueArg<std::string> cascadeArg("c", "cascade", "Specify the config file to use for the object detection. Default value is " + Default::CASCADE_PATH,
false, Default::CASCADE_PATH, "PATH_TO_XML", cmd);
TCLAP::ValueArg<std::string> inputArg("i", "input",
"Specify the video input file name (can be a webcam ID, e.g. 0, or a video file, e.g. 'video_test.avi'). Default value is " + Default::INPUT,
false, Default::INPUT, "VIDEO_INPUT_FILE", cmd);
//// Parse the argv array
cmd.parse(argc, argv);
//// Get the value parsed by each arg
// Load pre-trained cascade data
std::string &cascadeName = cascadeArg.getValue();
cv::CascadeClassifier cascade;
if (!cascade.load(cascadeName)) {
LOG_E("ERROR: Could not load classifier cascade");
return Code::CASCADE_LOAD_ERROR;
}
// Get file to read image from for image detection
std::string &inputFilename = inputArg.getValue();
int webcamId;
bool isWebcam = false;
if (inputFilename.empty() || (isdigit(inputFilename[0]) && inputFilename.size() == 1)) {
webcamId = inputFilename.empty() ? 0 : inputFilename[0] - '0';
isWebcam = true;
}
// Init video reader
VideoStreamReader vsr;
int openCodeResult = isWebcam ? vsr.openStream(webcamId) : vsr.openStream(inputFilename);
if (openCodeResult == Code::ERROR) {
LOG_E("ERROR: Video capturing failed");
return Code::ERROR;
}
// If image capture has successfully started, start detecting objects regarding mode
LOG_I("Video capturing has been started ...");
return runCamshiftTrack(vsr, cascade);
} catch (TCLAP::ArgException &e) { // catch any exceptions
LOG_E("error: " << e.error() << " for arg " << e.argId());
}
LOG_E("Program exited with errors");
return Code::ERROR;
}
/*
* -------- Camshift track ---------
*/
int runCamshiftTrack(VideoStreamReader &vsr, const cv::CascadeClassifier &cascade) {
ObjectDetector objectDetector(cascade);
CamshiftRunner cRunner(vsr, objectDetector);
// Init slider to tweak thresholds..
cv::namedWindow("CamShift", 0);
cv::createTrackbar("Vmin", "CamShift", &cRunner.cTracker.vMin, 256, 0);
cv::createTrackbar("Vmax", "CamShift", &cRunner.cTracker.vMax, 256, 0);
cv::createTrackbar("Smin", "CamShift", &cRunner.cTracker.sMin, 256, 0);
cv::createTrackbar("Brutal threshold", "CamShift", &cRunner.cTracker.threshold, 256, 0);
// Control variables
bool backprojDisplay = false;
// Bind shortcuts
KeyInputHandler keyHandler;
std::function<void(const int &)> actionStop([&cRunner](const int &k) {
cRunner.stop();
});
keyHandler.bind('$', &actionStop);
std::function<void(const int &)> actionRecalibrate([&cRunner](const int &k) {
cRunner.recalibrate();
LOG_I("Ask for recalibration");
});
keyHandler.bind('!', &actionRecalibrate);
std::function<void(const int &)> actionBackprojDisplay([&backprojDisplay](const int &k) {
backprojDisplay = !backprojDisplay;
LOG_I("Backproj display " << (backprojDisplay ? "enabled" : "disabled"));
});
keyHandler.bind('*', &actionBackprojDisplay);
const std::function<void(CamshiftTracker &, const cv::Mat &, const cv::RotatedRect &, const bool)>
track_callback([&keyHandler, &backprojDisplay]
(CamshiftTracker &cTracker, const cv::Mat &img,
const cv::RotatedRect &objectTracked, const bool objectFound) {
// Read input key
int key = cv::waitKey(1);
keyHandler.apply(key);
// Drawings and display
if (backprojDisplay) {
cv::cvtColor(cTracker.getBackproj(), img, cv::COLOR_GRAY2BGR);
}
if (objectFound) {
cv::ellipse(img, objectTracked, Color::GREEN, 2, CV_AA);
}
cv::imshow("CamShift", img);
});
return cRunner.runTracking(&track_callback);
}
| 39.238806
| 187
| 0.594332
|
LorisFriedel
|
6fa047e31a5f6bb59ffbf6d050d98b419a1bff91
| 1,399
|
cpp
|
C++
|
code/pyramids/image.cpp
|
liaojing/Image-Morphing
|
5a093965e4d9016eac58acbe25ffd77ba56a0ca2
|
[
"MIT"
] | 109
|
2015-01-04T09:03:27.000Z
|
2022-03-28T07:45:51.000Z
|
code/pyramids/image.cpp
|
liaojing/Image-Morphing
|
5a093965e4d9016eac58acbe25ffd77ba56a0ca2
|
[
"MIT"
] | 1
|
2015-07-22T05:55:45.000Z
|
2016-01-20T07:28:11.000Z
|
code/pyramids/image.cpp
|
liaojing/Image-Morphing
|
5a093965e4d9016eac58acbe25ffd77ba56a0ca2
|
[
"MIT"
] | 45
|
2015-01-24T09:09:02.000Z
|
2021-08-11T12:40:09.000Z
|
#include <cstring>
#include <cctype>
#include "extension.h"
#include "image.h"
#include "error.h"
static extension::clamp clamp;
namespace image {
template<>
int load(cv::Mat& image, image::rgba<float> *rgba) {
if (image.rows!=0&&image.cols!=0)
{
int width=image.cols;
int height=image.rows;
rgba->resize(height, width);
const float tof = (1.f/255.f);
#pragma omp parallel for
for (int i = height-1; i >= 0; i--) {
for (int j = 0; j < width; j++) {
int p = i*width+j; // flip image so y is up
Vec3b v=image.at<Vec3b>(i,j);
rgba->r[p] = color::srgbuncurve(v[2]*tof);
rgba->g[p] = color::srgbuncurve(v[1]*tof);
rgba->b[p] = color::srgbuncurve(v[0]*tof);
rgba->a[p] = 1.0f;
}
}
return 1;
}
else
{
return 0;
}
}
template<>
int store(cv::Mat& image, const image::rgba<float> &rgba) {
int height=rgba.height();
int width=rgba.width();
#pragma omp parallel for
for (int i = height-1; i >= 0; i--) {
for (int j = 0; j < width; j++) {
int p = i*width+j; // flip image so y is up
float r = color::srgbcurve(clamp(rgba.r[p]));
float g = color::srgbcurve(clamp(rgba.g[p]));
float b = color::srgbcurve(clamp(rgba.b[p]));
Vec3b v;
v[0]=(uchar)(255.f*b);
v[1]=(uchar)(255.f*g);
v[2]=(uchar)(255.f*r);
image.at<Vec3b>(i,j)=v;
}
}
return 1;
}
}
| 22.564516
| 62
| 0.555397
|
liaojing
|
6fa66b2cebf9b544e3cd6fb9404ef2de87d48abe
| 751
|
cpp
|
C++
|
Source/CBoundBullet.cpp
|
DegitechWorldClass/Who-am-I_Game
|
ae90c7a60b747667d6571557c72e2b29dc1fc767
|
[
"Apache-2.0"
] | null | null | null |
Source/CBoundBullet.cpp
|
DegitechWorldClass/Who-am-I_Game
|
ae90c7a60b747667d6571557c72e2b29dc1fc767
|
[
"Apache-2.0"
] | null | null | null |
Source/CBoundBullet.cpp
|
DegitechWorldClass/Who-am-I_Game
|
ae90c7a60b747667d6571557c72e2b29dc1fc767
|
[
"Apache-2.0"
] | null | null | null |
#include "DXUT.h"
#include "CBoundBullet.h"
#include "CEffect.h"
CBoundBullet::CBoundBullet()
{
}
CBoundBullet::~CBoundBullet()
{
}
void CBoundBullet::Init()
{
}
void CBoundBullet::Update()
{
}
void CBoundBullet::Render()
{
}
void CBoundBullet::Release()
{
}
void CBoundBullet::OnCollisionEnter(CObject * _pObject)
{
if (_pObject->GetObjectTag() == Tag::Floor)
{
i++;
if (i == 3)
{
auto Effect = OBJECT.AddObject();
Effect->Transform->SetPosition(this->Transform->GetPosition() - Vector3(50,75,0));
Effect->AddComponent<CEffect>()->SetAnimation("ENEMY01_EFFECT");
this->m_pObject->Destroy();
}
}
}
void CBoundBullet::OnCollisionStay(CObject * _pObject)
{
}
void CBoundBullet::OnCollisionExit(CObject * _pObject)
{
}
| 13.907407
| 85
| 0.684421
|
DegitechWorldClass
|
6fab3d361acbb7411f10033d0063719fcb6d040d
| 2,995
|
inl
|
C++
|
Library/Sources/Stroika/Foundation/Memory/ObjectFieldUtilities.inl
|
SophistSolutions/Stroika
|
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
|
[
"MIT"
] | 28
|
2015-09-22T21:43:32.000Z
|
2022-02-28T01:35:01.000Z
|
Library/Sources/Stroika/Foundation/Memory/ObjectFieldUtilities.inl
|
SophistSolutions/Stroika
|
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
|
[
"MIT"
] | 98
|
2015-01-22T03:21:27.000Z
|
2022-03-02T01:47:00.000Z
|
Library/Sources/Stroika/Foundation/Memory/ObjectFieldUtilities.inl
|
SophistSolutions/Stroika
|
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
|
[
"MIT"
] | 4
|
2019-02-21T16:45:25.000Z
|
2022-02-18T13:40:04.000Z
|
/*
* Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved
*/
#ifndef _Stroika_Foundation_Memory_ObjectFieldUtilities_inl_
#define _Stroika_Foundation_Memory_ObjectFieldUtilities_inl_ 1
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
#include "../Debug/Assertions.h"
namespace Stroika::Foundation::Memory {
/*
********************************************************************************
*********************** ConvertPointerToDataMemberToOffset *********************
********************************************************************************
*/
template <typename OUTER_OBJECT, typename DATA_MEMBER_TYPE>
inline size_t ConvertPointerToDataMemberToOffset (DATA_MEMBER_TYPE (OUTER_OBJECT::*dataMember))
{
//https://stackoverflow.com/questions/12141446/offset-from-member-pointer-without-temporary-instance
return reinterpret_cast<char*> (&(((OUTER_OBJECT*)0)->*dataMember)) - reinterpret_cast<char*> (0);
}
/*
********************************************************************************
*************************** GetObjectOwningField *******************************
********************************************************************************
*/
template <typename APPARENT_MEMBER_TYPE, typename OUTER_OBJECT, typename AGGREGATED_OBJECT_TYPE>
inline OUTER_OBJECT* GetObjectOwningField (APPARENT_MEMBER_TYPE* aggregatedMember, AGGREGATED_OBJECT_TYPE (OUTER_OBJECT::*aggregatedPtrToMember))
{
RequireNotNull (aggregatedMember);
RequireNotNull (aggregatedPtrToMember);
std::byte* adjustedAggregatedMember = reinterpret_cast<std::byte*> (static_cast<AGGREGATED_OBJECT_TYPE*> (aggregatedMember));
ptrdiff_t adjustment = static_cast<ptrdiff_t> (ConvertPointerToDataMemberToOffset (aggregatedPtrToMember));
return reinterpret_cast<OUTER_OBJECT*> (adjustedAggregatedMember - adjustment);
}
template <typename APPARENT_MEMBER_TYPE, typename OUTER_OBJECT, typename AGGREGATED_OBJECT_TYPE>
inline const OUTER_OBJECT* GetObjectOwningField (const APPARENT_MEMBER_TYPE* aggregatedMember, AGGREGATED_OBJECT_TYPE (OUTER_OBJECT::*aggregatedPtrToMember))
{
RequireNotNull (aggregatedMember);
RequireNotNull (aggregatedPtrToMember);
const std::byte* adjustedAggregatedMember = reinterpret_cast<const std::byte*> (static_cast<const AGGREGATED_OBJECT_TYPE*> (aggregatedMember));
ptrdiff_t adjustment = static_cast<ptrdiff_t> (ConvertPointerToDataMemberToOffset (aggregatedPtrToMember));
return reinterpret_cast<const OUTER_OBJECT*> (adjustedAggregatedMember - adjustment);
}
}
#endif /*_Stroika_Foundation_Memory_ObjectFieldUtilities_inl_*/
| 54.454545
| 161
| 0.590651
|
SophistSolutions
|
6fb531138f1e004716c1635c7fbe2612979292e7
| 1,392
|
cpp
|
C++
|
tests/tests_transactional.cpp
|
Dwarfobserver/cpp-sandbox
|
e20bdc0694efac11ff3476e51a2821a2575b63cb
|
[
"MIT"
] | 3
|
2018-01-10T01:04:02.000Z
|
2019-03-29T15:23:42.000Z
|
tests/tests_transactional.cpp
|
Dwarfobserver/cpp-sandbox
|
e20bdc0694efac11ff3476e51a2821a2575b63cb
|
[
"MIT"
] | null | null | null |
tests/tests_transactional.cpp
|
Dwarfobserver/cpp-sandbox
|
e20bdc0694efac11ff3476e51a2821a2575b63cb
|
[
"MIT"
] | null | null | null |
#include "catch.hpp"
#include <transactional.hpp>
namespace {
std::atomic_int ctorsCounter;
std::atomic_int movesCounter;
std::atomic_int copiesCounter;
std::atomic_int dtorsCounter;
class Dummy {
public:
Dummy() {
ctorsCounter++;
}
~Dummy() {
dtorsCounter++;
}
Dummy(Dummy && old) noexcept {
movesCounter++;
}
Dummy& operator=(Dummy && old) noexcept {
movesCounter++;
return *this;
}
Dummy(Dummy const& clone) {
copiesCounter++;
}
Dummy& operator=(Dummy const& clone) {
copiesCounter++;
return *this;
}
};
}
TEST_CASE("transactional ctors, moves & copies count", "[transactional]") {
sc::transactional<Dummy> dummy;
{
sc::transactional<Dummy>::handle_t handle;
REQUIRE(dummy.empty());
{
handle = dummy.create();
auto h2 = handle;
dummy.modify(h2, [](Dummy &val) noexcept {});
REQUIRE(ctorsCounter == 1);
REQUIRE(movesCounter == 0);
REQUIRE(copiesCounter == 1);
REQUIRE(dtorsCounter == 0);
}
dummy.update(handle);
dummy.clear();
REQUIRE(dtorsCounter == 1);
}
dummy.clear();
REQUIRE(dtorsCounter == 2);
}
| 22.819672
| 75
| 0.512931
|
Dwarfobserver
|
6fb61cdc2c763ccc14f86ec30e8a9abfd27c7c3b
| 1,582
|
cpp
|
C++
|
libs/cegui/src/cegui/toolbox/append_row.cpp
|
cpreh/spacegameengine
|
313a1c34160b42a5135f8223ffaa3a31bc075a01
|
[
"BSL-1.0"
] | 2
|
2016-01-27T13:18:14.000Z
|
2018-05-11T01:11:32.000Z
|
libs/cegui/src/cegui/toolbox/append_row.cpp
|
cpreh/spacegameengine
|
313a1c34160b42a5135f8223ffaa3a31bc075a01
|
[
"BSL-1.0"
] | null | null | null |
libs/cegui/src/cegui/toolbox/append_row.cpp
|
cpreh/spacegameengine
|
313a1c34160b42a5135f8223ffaa3a31bc075a01
|
[
"BSL-1.0"
] | 3
|
2018-05-11T01:11:34.000Z
|
2021-04-24T19:47:45.000Z
|
// Copyright Carl Philipp Reh 2006 - 2019.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <sge/cegui/exception.hpp>
#include <sge/cegui/toolbox/append_row.hpp>
#include <sge/cegui/toolbox/row.hpp>
#include <fcppt/literal.hpp>
#include <fcppt/make_int_range.hpp>
#include <fcppt/text.hpp>
#include <fcppt/config/external_begin.hpp>
#include <CEGUI/Base.h>
#include <CEGUI/widgets/ListboxTextItem.h>
#include <CEGUI/widgets/MultiColumnList.h>
#include <fcppt/config/external_end.hpp>
void sge::cegui::toolbox::append_row(
CEGUI::MultiColumnList &_list, sge::cegui::toolbox::row const &_mapper)
{
if (static_cast<sge::cegui::toolbox::row::size_type>(_list.getColumnCount()) != _mapper.size())
{
throw sge::cegui::exception{FCPPT_TEXT("toolbox::append_row: Invalid size!")};
}
if (_mapper.empty())
{
throw sge::cegui::exception{FCPPT_TEXT("toolbox::append_row: mapper is empty!")};
}
CEGUI::uint const index(_list.addRow(
// NOLINTNEXTLINE(cppcoreguidelines-owning-memory)
new CEGUI::ListboxTextItem(_mapper[0], 0, nullptr),
0));
for (sge::cegui::toolbox::row::size_type const cur : fcppt::make_int_range(
fcppt::literal<sge::cegui::toolbox::row::size_type>(1U), _mapper.size()))
{
_list.setItem(
// NOLINTNEXTLINE(cppcoreguidelines-owning-memory)
new CEGUI::ListboxTextItem(_mapper[cur], 0, nullptr),
static_cast<CEGUI::uint>(cur),
index);
}
}
| 34.391304
| 97
| 0.695322
|
cpreh
|
6fbe972e5da8045c909d7b9cb7928a6f8ae5ebf2
| 15,314
|
hpp
|
C++
|
code/linear/gauss.hpp
|
Brunovsky/competitive
|
41cf49378e430ca20d844f97c67aa5059ab1e973
|
[
"MIT"
] | 1
|
2020-02-10T09:15:59.000Z
|
2020-02-10T09:15:59.000Z
|
code/linear/gauss.hpp
|
Brunovsky/kickstart
|
41cf49378e430ca20d844f97c67aa5059ab1e973
|
[
"MIT"
] | null | null | null |
code/linear/gauss.hpp
|
Brunovsky/kickstart
|
41cf49378e430ca20d844f97c67aa5059ab1e973
|
[
"MIT"
] | null | null | null |
#pragma once
#include "linear/matrix.hpp"
// ***** Gauss with modnum/fields
// Compute inverse of square matrix, T must be invertible. Returns nullopt if det=0
template <typename T>
optional<mat<T>> inverse(mat<T> a) {
assert(a.n == a.m && "Matrix inverse operand is not square");
auto b = mat<T>::identity(a.n);
for (int j = 0, i; j < a.n; j++) {
for (i = j; i < a.n; i++) {
if (a[i][j]) {
break;
}
}
if (i == a.n) {
return std::nullopt;
}
if (i != j) {
for (int k = 0; k < a.n; k++) {
swap(a[i][k], a[j][k]);
swap(b[i][k], b[j][k]);
}
}
T div = T(1) / a[j][j];
for (int k = 0; k < a.n; k++) {
b[j][k] *= div;
}
for (int k = a.n - 1; k >= j; k--) {
a[j][k] *= div;
}
for (i = j + 1; i < a.n; i++) {
if (a[i][j]) {
for (int k = 0; k < a.n; k++) {
b[i][k] -= a[i][j] * b[j][k];
}
for (int k = a.n - 1; k >= j; k--) {
a[i][k] -= a[i][j] * a[j][k];
}
}
}
}
for (int j = a.n - 1; j >= 0; j--)
for (int i = 0; i < j; i++)
for (int k = 0; k < a.n; k++)
b[i][k] -= a[i][j] * b[j][k];
return b;
}
// Solve any linear system, T must be a field. Returns empty vector if no solution.
template <typename T>
auto solve_linear_system(mat<T> a, vector<T> b) {
assert(a.n == int(b.size()));
int r = 0, c = 0;
vector<int> cols, nonzero;
for (int i; r < a.n && c < a.m; c++) {
for (i = r; i < a.n; i++) {
if (a[i][c]) {
break;
}
}
if (i == a.n) {
continue;
}
if (i != r) {
swap(b[i], b[r]);
for (int k = 0; k < a.m; k++) {
swap(a[i][k], a[r][k]);
}
}
T div = T(1) / a[r][c];
b[r] *= div;
for (int k = a.m - 1; k >= c; k--) {
if (a[r][k]) {
a[r][k] *= div;
nonzero.push_back(k);
}
}
for (i = r + 1; i < a.n; i++) {
if (a[i][c]) {
b[i] -= a[i][c] * b[r];
for (int k : nonzero) {
a[i][k] -= a[i][c] * a[r][k];
}
}
}
cols.push_back(c), nonzero.clear(), r++;
}
// Verify system is indeed solved
for (int i = r; i < a.n; i++) {
if (b[i]) {
return vector<T>();
}
}
// Complete the row reduction, but only for relevant columns
for (int i = r - 1; i > 0; i--) {
for (int y = r - 1; y >= i; y--) {
if (a[i][cols[y]]) {
nonzero.push_back(cols[y]);
}
}
for (int k = i - 1; k >= 0; k--) {
if (a[k][cols[i]]) {
b[k] -= a[k][cols[i]] * b[i];
for (int j : nonzero) {
a[k][j] -= a[k][cols[i]] * a[i][j];
}
}
}
nonzero.clear();
}
vector<T> ans(a.m);
for (int i = r - 1; i >= 0; i--) {
ans[cols[i]] = b[i];
}
return ans;
}
// Solve any linear system and get solution space basis. Returns {sol, sol space basis}
template <typename T>
auto solve_linear_system_basis(mat<T> a, vector<T> b) {
assert(a.n == int(b.size()));
int r = 0, c = 0;
vector<int> cols, other, nonzero;
for (int i; r < a.n && c < a.m; c++) {
for (i = r; i < a.n; i++) {
if (a[i][c]) {
break;
}
}
if (i == a.n) {
other.push_back(c);
continue;
}
if (i != r) {
swap(b[i], b[r]);
for (int k = 0; k < a.m; k++) {
swap(a[i][k], a[r][k]);
}
}
T div = T(1) / a[r][c];
b[r] *= div;
for (int k = a.m - 1; k >= c; k--) {
if (a[r][k]) {
a[r][k] *= div;
nonzero.push_back(k);
}
}
for (i = r + 1; i < a.n; i++) {
if (a[i][c]) {
b[i] -= a[i][c] * b[r];
for (int k : nonzero) {
a[i][k] -= a[i][c] * a[r][k];
}
}
}
cols.push_back(c), nonzero.clear(), r++;
}
// Verify system is indeed solved
for (int i = r; i < a.n; i++) {
if (b[i]) {
return make_pair(vector<T>(), vector<vector<T>>());
}
}
// Remaining solution basis columns
while (c < a.m) {
other.push_back(c++);
}
// Complete the row reduction, including other columns
for (int i = r - 1; i > 0; i--) {
for (int j = a.m - 1; j >= cols[i]; j--) {
if (a[i][j]) {
nonzero.push_back(j);
}
}
for (int k = i - 1; k >= 0; k--) {
if (a[k][cols[i]]) {
b[k] -= a[k][cols[i]] * b[i];
for (int j : nonzero) {
a[k][j] -= a[k][cols[i]] * a[i][j];
}
}
}
nonzero.clear();
}
// One solution of the system
vector<T> ans(a.m);
for (int i = 0; i < r; i++) {
ans[cols[i]] = b[i];
}
// The space of solutions, possibly empty
int rank = other.size();
vector<vector<T>> basis(rank);
for (int p = 0; p < rank; p++) {
basis[p].resize(a.m);
basis[p][other[p]] = -1;
}
// For basis[p], set the column other[p] to -1, then for each of the A basis rows
// a[0], ..., a[r-1] compute the coefficient for column cols[0], ..., cols[r-1]
for (int i = 0; i < r; i++) {
for (int p = 0; p < rank; p++) {
basis[p][cols[i]] = a[i][other[p]];
}
}
return make_pair(move(ans), move(basis));
}
// Row reduction inplace to compute rank and determinant, T must be a field.
template <typename T>
auto gauss_elimination(mat<T>& a, bool full = true) {
int r = 0, c = 0;
T determinant = 1;
vector<int> nonzero, cols;
for (int i; r < a.n && c < a.m; c++) {
for (i = r; i < a.n; i++) {
if (a[i][c]) {
break;
}
}
if (i == a.n) {
determinant = 0;
continue;
}
if (i != r) {
for (int k = 0; k < a.m; k++) {
swap(a[i][k], a[r][k]);
}
determinant = -determinant;
}
T div = T(1) / a[r][c];
determinant *= a[r][c];
for (int k = a.m - 1; k >= c; k--) {
if (a[r][k]) {
a[r][k] *= div;
nonzero.push_back(k);
}
}
for (i = r + 1; i < a.n; i++) {
if (a[i][c]) {
for (int k : nonzero) {
a[i][k] -= a[i][c] * a[r][k];
}
}
}
nonzero.clear(), r++;
cols.push_back(c);
}
// Complete the row reduction, including other columns
for (int i = r - 1; full && i > 0; i--) {
for (int j = a.m - 1; j >= cols[i]; j--) {
if (a[i][j]) {
nonzero.push_back(j);
}
}
for (int k = i - 1; k >= 0; k--) {
if (a[k][cols[i]]) {
for (int j : nonzero) {
a[k][j] -= a[k][cols[i]] * a[i][j];
}
}
}
nonzero.clear();
}
return make_tuple(determinant, r, move(cols));
}
// ***** Gauss with floating point
// Compute inverse of square matrix. Returns nullopt if det=0
template <typename D>
optional<mat<D>> float_inverse(mat<D> a) {
constexpr D eps = 1e2 * numeric_limits<D>::epsilon();
assert(a.n == a.m && "Matrix inverse operand is not square");
int n = a.n;
auto b = mat<D>::identity(n);
for (int j = 0, i, x; j < n; j++) {
for (i = x = j; x < n; x++) {
if (abs(a[i][j]) < abs(a[x][j])) {
i = x;
}
}
if (i == n || abs(a[i][j] <= eps)) {
return std::nullopt;
}
if (i != j) {
for (int k = 0; k < n; k++) {
swap(a[i][k], a[j][k]);
swap(b[i][k], b[j][k]);
}
}
for (int k = 0; k < n; k++)
b[j][k] /= a[j][j];
for (int k = n - 1; k >= j; k--)
a[j][k] /= a[j][j];
for (i = j + 1; i < n; i++) {
for (int k = 0; k < n; k++)
b[i][k] -= a[i][j] * b[j][k];
for (int k = n - 1; k >= j; k--)
a[i][k] -= a[i][j] * a[j][k];
}
}
for (int j = n - 1; j >= 0; j--)
for (int i = 0; i < j; i++)
for (int k = 0; k < n; k++)
b[i][k] -= a[i][j] * b[j][k];
return b;
}
// Solve any linear system. Returns empty vector for no solution.
template <typename D>
auto solve_float_linear_system(mat<D> a, vector<D> b, bool trim = true) {
constexpr D eps = 1e2 * numeric_limits<D>::epsilon();
assert(a.n == int(b.size()));
int r = 0, c = 0;
vector<int> cols, nonzero;
for (int i, x; r < a.n && c < a.m; c++) {
for (i = x = r; x < a.n; x++) {
if (abs(a[i][c]) < abs(a[x][c])) {
i = x;
}
}
if (i == a.n || abs(a[i][c]) <= eps) {
continue;
}
if (i != r) {
swap(b[i], b[r]);
for (int k = 0; k < a.m; k++) {
swap(a[i][k], a[r][k]);
}
}
b[r] /= a[r][c];
for (int k = a.m - 1; k >= c; k--) {
a[r][k] /= a[r][c];
if (!trim || abs(a[r][k]) > eps) {
nonzero.push_back(k);
}
}
for (i = r + 1; i < a.n; i++) {
b[i] -= a[i][c] * b[r];
for (int k : nonzero) {
a[i][k] -= a[i][c] * a[r][k];
}
}
cols.push_back(c), nonzero.clear(), r++;
}
// Verify system is indeed solved
for (int i = r; i < a.n; i++) {
if (abs(b[i]) > eps) {
return vector<D>();
}
}
// Complete the row reduction
for (int i = r - 1; i > 0; i--) {
for (int y = r - 1; y >= i; y--) {
if (!trim || abs(a[i][cols[y]]) > eps) {
nonzero.push_back(cols[y]);
}
}
for (int k = i - 1; k >= 0; k--) {
b[k] -= a[k][cols[i]] * b[i];
for (int j : nonzero) {
a[k][j] -= a[k][cols[i]] * a[i][j];
}
}
nonzero.clear();
}
vector<D> ans(a.m);
for (int i = r - 1; i >= 0; i--) {
ans[cols[i]] = b[i];
}
return ans;
}
// Solve any linear system and get solution space basis. Returns {sol, sol space basis}
template <typename D>
auto solve_float_linear_system_basis(mat<D> a, vector<D> b, bool trim = true) {
constexpr D eps = 1e2 * numeric_limits<D>::epsilon();
assert(a.n == int(b.size()));
int r = 0, c = 0;
vector<int> cols, other, nonzero;
for (int i, x; r < a.n && c < a.m; c++) {
for (i = x = r; i < a.n; i++) {
if (abs(a[i][c]) < abs(a[x][c])) {
i = x;
}
}
if (i == a.n || abs(a[i][c]) <= eps) {
other.push_back(c);
continue;
}
if (i != r) {
swap(b[i], b[r]);
for (int k = 0; k < a.m; k++) {
swap(a[i][k], a[r][k]);
}
}
b[r] /= a[r][c];
for (int k = a.m - 1; k >= c; k--) {
a[r][k] /= a[r][c];
if (!trim || abs(a[r][k]) > eps) {
nonzero.push_back(k);
}
}
for (i = r + 1; i < a.n; i++) {
b[i] -= a[i][c] * b[r];
for (int k : nonzero) {
a[i][k] -= a[i][c] * a[r][k];
}
}
cols.push_back(c), nonzero.clear(), r++;
}
// Verify system is indeed solved
for (int i = r; i < a.n; i++) {
if (abs(b[i]) > eps) {
return make_pair(vector<D>(), vector<vector<D>>());
}
}
// Remaining solution basis columns
while (c < a.m) {
other.push_back(c++);
}
// Complete the row reduction, including other columns
for (int i = r - 1; i > 0; i--) {
for (int j = a.m - 1; j >= cols[i]; j--) {
if (!trim || abs(a[i][j]) > eps) {
nonzero.push_back(j);
}
}
for (int k = i - 1; k >= 0; k--) {
b[k] -= a[k][cols[i]] * b[i];
for (int j : nonzero) {
a[k][j] -= a[k][cols[i]] * a[i][j];
}
}
nonzero.clear();
}
// One solution of the system
vector<D> ans(a.m);
for (int i = 0; i < r; i++) {
ans[cols[i]] = b[i];
}
// The space of solutions, possibly empty
int rank = other.size();
vector<vector<D>> basis(rank);
for (int p = 0; p < rank; p++) {
basis[p].resize(a.m);
basis[p][other[p]] = -1;
}
// For basis[p], set the column other[p] to -1, then for each of the A basis rows
// a[0], ..., a[r-1] compute the coefficient for column cols[0], ..., cols[r-1]
for (int i = 0; i < r; i++) {
for (int p = 0; p < rank; p++) {
basis[p][cols[i]] = a[i][other[p]];
}
}
return make_pair(move(ans), move(basis));
}
// Row reduction inplace with partial pivoting to compute rank and determinant.
template <typename D>
auto float_gauss_elimination(mat<D>& a, bool full = true, bool trim = true) {
constexpr D eps = 1e2 * numeric_limits<D>::epsilon();
int r = 0, c = 0;
D determinant = 1;
vector<int> nonzero, cols;
for (int i, x; r < a.n && c < a.m; c++) {
for (i = x = r; x < a.n; x++) {
if (abs(a[i][c]) < abs(a[x][c])) {
i = x;
}
}
if (i == a.n || abs(a[i][c]) <= eps) {
determinant = 0;
continue;
}
if (i != r) {
for (int k = 0; k < a.m; k++) {
swap(a[i][k], a[r][k]);
}
determinant = -determinant;
}
determinant *= a[r][c];
for (int k = a.m - 1; k >= c; k--) {
a[r][k] /= a[r][c];
if (!trim || abs(a[r][k]) > eps) {
nonzero.push_back(k);
}
}
for (i = r + 1; i < a.n; i++) {
for (int k : nonzero) {
a[i][k] -= a[i][c] * a[r][k];
}
}
nonzero.clear(), r++;
cols.push_back(c);
}
// Complete the row reduction, including other columns
for (int i = r - 1; i > 0; i--) {
for (int j = a.m - 1; j >= cols[i]; j--) {
if (!trim || abs(a[i][j]) > eps) {
nonzero.push_back(j);
}
}
for (int k = i - 1; k >= 0; k--) {
for (int j : nonzero) {
a[k][j] -= a[k][cols[i]] * a[i][j];
}
}
nonzero.clear();
}
return make_tuple(determinant, r, move(cols));
}
| 29.735922
| 87
| 0.366854
|
Brunovsky
|
6fc52b753f1ddd7513f0c0563a39ce6c810541bc
| 1,714
|
cpp
|
C++
|
Geometry/IndexedTriangleSet.cpp
|
jess22664/x3ogre
|
9de430859d877407ae0308908390c9fa004b0e84
|
[
"MIT"
] | 1
|
2021-09-18T12:50:35.000Z
|
2021-09-18T12:50:35.000Z
|
Geometry/IndexedTriangleSet.cpp
|
jess22664/x3ogre
|
9de430859d877407ae0308908390c9fa004b0e84
|
[
"MIT"
] | null | null | null |
Geometry/IndexedTriangleSet.cpp
|
jess22664/x3ogre
|
9de430859d877407ae0308908390c9fa004b0e84
|
[
"MIT"
] | null | null | null |
/*
* IndexedTriangleSet.cpp
*
* Created on: 05.12.2013
* Author: baudenri_local
*/
#include <Geometry/IndexedTriangleSet.h>
#include <OgreMeshManager.h>
#include <GeoShape/Utils.h>
#include <core/OgreMeshAdapter.h>
#include <Geometry/Coordinate.h>
#include <Geometry/Normal.h>
#include <Geometry/TextureCoordinate.h>
#include <Geometry/Color.h>
namespace X3D {
void IndexedTriangleSet::index(const std::vector<int>& index) {
_index.insert(_index.end(), index.begin(), index.end());
}
void IndexedTriangleSet::normalPerVertex(const bool& val) {
_normalPerVertex = val;
}
void IndexedTriangleSet::loadResource(Ogre::Resource* resource) {
std::vector<Ogre::Vector3> points = _coordinate->point();
std::vector<Ogre::Vector3> normalsGen;
std::vector<Ogre::Vector2> texCoord;
std::vector<Ogre::Vector3> colorsLocal;
if(_textureCoordinate) {
texCoord = _textureCoordinate->point();
}
if (not _normal) {
if (_normalPerVertex) {
GeoShape::GenerateNormals(_index, points, normalsGen);
} else {
std::vector<Ogre::Vector3> tmp;
GeoShape::DuplicateByIndex(_index, points, tmp);
points.swap(tmp);
GeoShape::GenerateNormals(points, normalsGen);
_index.clear();
}
}
const auto& normals = _normal ? _normal->vector() : normalsGen;
const auto& colors = _color ? _color->getColor() : colorsLocal;
OgreMeshAdapter(static_cast<Ogre::Mesh*>(resource), Ogre::RenderOperation::OT_TRIANGLE_LIST, _index, points, normals, texCoord, colors);
auto ci = _coordinate->interpolator();
if(ci) {
ci->addToMesh(static_cast<Ogre::Mesh*>(resource));
}
}
}
| 27.206349
| 140
| 0.668611
|
jess22664
|
6fcd87b0927704405b0eb4b5ed459d89104fe197
| 1,924
|
cpp
|
C++
|
android-28/android/bluetooth/BluetoothSocket.cpp
|
YJBeetle/QtAndroidAPI
|
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
|
[
"Apache-2.0"
] | 12
|
2020-03-26T02:38:56.000Z
|
2022-03-14T08:17:26.000Z
|
android-28/android/bluetooth/BluetoothSocket.cpp
|
YJBeetle/QtAndroidAPI
|
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
|
[
"Apache-2.0"
] | 1
|
2021-01-27T06:07:45.000Z
|
2021-11-13T19:19:43.000Z
|
android-30/android/bluetooth/BluetoothSocket.cpp
|
YJBeetle/QtAndroidAPI
|
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
|
[
"Apache-2.0"
] | 3
|
2021-02-02T12:34:55.000Z
|
2022-03-08T07:45:57.000Z
|
#include "./BluetoothDevice.hpp"
#include "../../java/io/InputStream.hpp"
#include "../../java/io/OutputStream.hpp"
#include "./BluetoothSocket.hpp"
namespace android::bluetooth
{
// Fields
jint BluetoothSocket::TYPE_L2CAP()
{
return getStaticField<jint>(
"android.bluetooth.BluetoothSocket",
"TYPE_L2CAP"
);
}
jint BluetoothSocket::TYPE_RFCOMM()
{
return getStaticField<jint>(
"android.bluetooth.BluetoothSocket",
"TYPE_RFCOMM"
);
}
jint BluetoothSocket::TYPE_SCO()
{
return getStaticField<jint>(
"android.bluetooth.BluetoothSocket",
"TYPE_SCO"
);
}
// QJniObject forward
BluetoothSocket::BluetoothSocket(QJniObject obj) : JObject(obj) {}
// Constructors
// Methods
void BluetoothSocket::close() const
{
callMethod<void>(
"close",
"()V"
);
}
void BluetoothSocket::connect() const
{
callMethod<void>(
"connect",
"()V"
);
}
jint BluetoothSocket::getConnectionType() const
{
return callMethod<jint>(
"getConnectionType",
"()I"
);
}
java::io::InputStream BluetoothSocket::getInputStream() const
{
return callObjectMethod(
"getInputStream",
"()Ljava/io/InputStream;"
);
}
jint BluetoothSocket::getMaxReceivePacketSize() const
{
return callMethod<jint>(
"getMaxReceivePacketSize",
"()I"
);
}
jint BluetoothSocket::getMaxTransmitPacketSize() const
{
return callMethod<jint>(
"getMaxTransmitPacketSize",
"()I"
);
}
java::io::OutputStream BluetoothSocket::getOutputStream() const
{
return callObjectMethod(
"getOutputStream",
"()Ljava/io/OutputStream;"
);
}
android::bluetooth::BluetoothDevice BluetoothSocket::getRemoteDevice() const
{
return callObjectMethod(
"getRemoteDevice",
"()Landroid/bluetooth/BluetoothDevice;"
);
}
jboolean BluetoothSocket::isConnected() const
{
return callMethod<jboolean>(
"isConnected",
"()Z"
);
}
} // namespace android::bluetooth
| 18.862745
| 77
| 0.685551
|
YJBeetle
|
6fdf2bc882a887b3e119b39b441bdede59686ee5
| 4,384
|
cpp
|
C++
|
src/Headers.cpp
|
Good-Pudge/OkHttpFork
|
b179350d6262f281c1c27d69d944c62f536fe1ba
|
[
"BSL-1.0",
"Apache-2.0",
"OpenSSL"
] | 10
|
2019-02-21T06:21:48.000Z
|
2022-02-22T08:01:24.000Z
|
src/Headers.cpp
|
Good-Pudge/OkHttpFork
|
b179350d6262f281c1c27d69d944c62f536fe1ba
|
[
"BSL-1.0",
"Apache-2.0",
"OpenSSL"
] | 2
|
2018-02-04T20:16:46.000Z
|
2018-02-04T20:19:00.000Z
|
src/Headers.cpp
|
Good-Pudge/OkHttpFork
|
b179350d6262f281c1c27d69d944c62f536fe1ba
|
[
"BSL-1.0",
"Apache-2.0",
"OpenSSL"
] | 10
|
2018-10-15T10:17:00.000Z
|
2022-02-17T02:28:51.000Z
|
//
// Created by Good_Pudge.
//
#include <iostream>
#include <iomanip>
#include <sstream>
#include <algorithm>
#include <ohf/Headers.hpp>
#include <ohf/Exception.hpp>
#include <ohf/RangeException.hpp>
#include "util/string.hpp"
#include "util/util.hpp"
namespace ohf {
Headers::Headers(const std::map<std::string, std::string> &headers) {
auto begin = headers.begin();
for (Uint32 i = 0; i < headers.size(); i++) {
auto header = std::next(begin, i);
std::string headerName = header->first;
std::string headerValue = header->second;
if(headerName.empty() || headerValue.empty()) {
throw Exception(Exception::Code::HEADER_IS_EMPTY, "Header is empty: name: \"" + headerName
+ "\" value: \"" + headerValue
+ "\" index: " + std::to_string(i));
}
namesValues.push_back(headerName);
namesValues.push_back(headerValue);
}
}
const Headers::Iterator Headers::begin() const {
return {0, this};
}
Headers::Iterator Headers::begin() {
return {0, this};
}
const Headers::Iterator Headers::end() const {
return {this->size(), this};
}
Headers::Iterator Headers::end() {
return {this->size(), this};
}
std::string Headers::get(std::string name) const {
util::string::toLower(name);
for (auto it = namesValues.begin(); it != namesValues.end(); it += 2) {
std::string element = *it;
util::string::toLower(element);
if (name == element)
return *(++it);
}
return std::string();
}
TimeUnit Headers::getDate() const {
return TimeUnit::seconds(util::parseDate(this->get("Date"), "%a, %d %b %Y %H:%M:%S GMT"));
}
std::string Headers::name(Uint32 index) const {
Uint32 i = index * 2;
if (i >= namesValues.size())
throw RangeException(index);
return namesValues[i];
}
std::vector<std::string> Headers::names() const {
std::vector<std::string> names;
for (auto it = namesValues.begin(); it != namesValues.end(); it += 2) {
if (std::find(names.begin(), names.end(), *it) == names.end())
names.push_back(*it);
}
return names;
}
Headers::Builder Headers::newBuilder() const {
Headers::Builder builder;
builder.namesValues = namesValues;
return builder;
}
Uint32 Headers::size() const {
return (Uint32) namesValues.size() / 2;
}
std::string Headers::value(Uint32 index) const {
Uint32 i = index * 2 + 1;
if (i >= namesValues.size())
throw RangeException(index);
return namesValues[i];
}
std::vector<std::string> Headers::values(std::string name) const {
util::string::toLower(name);
std::vector<std::string> values;
for (auto it = namesValues.begin(); it != namesValues.end(); it += 2) {
std::string it_name = *it;
util::string::toLower(it_name);
if (it_name == name) values.push_back(*(it + 1));
}
return values;
}
Headers::Pair Headers::pair(Uint32 index) const {
return {this->name(index), this->value(index)};
}
std::string Headers::toString() const {
std::stringstream ss;
auto begin = namesValues.begin();
for (unsigned int i = 0; i < namesValues.size(); i += 2) {
ss << *begin << ": ";
++begin;
ss << *begin << "\r\n";
++begin;
}
return ss.str();
}
std::string Headers::operator [](const std::string &name) const {
return get(name);
}
bool Headers::operator ==(const Headers &headers) const {
auto nav1 = headers.namesValues;
std::sort(nav1.begin(), nav1.end());
auto nav2 = this->namesValues;
std::sort(nav2.begin(), nav2.end());
return nav1 == nav2;
}
std::ostream &operator <<(std::ostream &stream, const Headers &headers) {
stream << headers.toString();
return stream;
}
Headers::Headers(const Builder *builder) : namesValues(builder->namesValues) {}
}
| 30.234483
| 106
| 0.535812
|
Good-Pudge
|
6fe0979360862ec103ae24d67f2b27f5daa5e1f5
| 12,960
|
hpp
|
C++
|
include/algorithm/concurrent/concurrent_vector.hpp
|
chill-nemesis/horizon_algorithm
|
8514125ac8cf4e16259fc0c9460f7d4248312ca7
|
[
"Zlib"
] | null | null | null |
include/algorithm/concurrent/concurrent_vector.hpp
|
chill-nemesis/horizon_algorithm
|
8514125ac8cf4e16259fc0c9460f7d4248312ca7
|
[
"Zlib"
] | null | null | null |
include/algorithm/concurrent/concurrent_vector.hpp
|
chill-nemesis/horizon_algorithm
|
8514125ac8cf4e16259fc0c9460f7d4248312ca7
|
[
"Zlib"
] | null | null | null |
//
// @brief
// @details
// @author Steffen Peikert (ch3ll)
// @email Horizon@ch3ll.com
// @version 1.0.0
// @date 01/01/2020 13:58
// @project Horizon
//
#pragma once
#include "concurrent_base.hpp"
#include <vector>
#include <algorithm>
namespace HORIZON::ALGORITHM::CONCURRENT
{
/*!
* @ingroup group_algorithm_concurrent
*
* @brief A concurrent vector.
* @copydetails concurrent_base
*
* @tparam T The element type.
* @tparam Alloc The underlying allocator.
*
* @note This implementation is by no means complete and gets extended upon need!
*/
template<typename T,
typename Alloc = std::allocator<T>>
class concurrent_vector : public virtual concurrent_base
{
public:
using value_type = T;
using allocator_type = Alloc;
using container_type = std::vector<value_type, allocator_type>;
using size_type = typename container_type::size_type;
using reference = value_type&;
using const_reference = value_type const&;
using access_type = size_type;
using iterator = typename container_type::iterator;
using const_iterator = typename container_type::const_iterator;
using reverse_iterator = typename container_type::reverse_iterator;
using const_reverse_iterator = typename container_type::const_reverse_iterator;
private:
container_type _container;
public:
// TODO construcotrs
/*!
* @return Gets the capacity of the container.
*/
[[nodiscard]] inline size_type capacity() const
{ return capacity(std::move(Guard())); }
/*!
* @brief Gets the capacity of the container if it is owned by the calling thread.
* @warning The calling thread must provide the corresponding access token!
* @param token The access token.
* @return The capacity of the container.
*/
[[nodiscard]] inline size_type capacity(access_token const& token) const
{
CheckForOwnership(token);
return _container.capacity();
}
/*!
* @return Gets the size of the container.
*/
[[nodiscard]] inline size_type size() const
{ return size(std::move(Guard())); }
/*!
* @brief Gets the size of hte container if it is owned by the calling thread.
* @warning The calling thread must provide the corresponding access token!
* @param token The access token.
* @return The size of the container.
*/
[[nodiscard]] inline size_type size(access_token const& token) const
{
CheckForOwnership(token);
return _container.size();
}
using concurrent_base::empty;
[[nodiscard]] inline bool empty(access_token const& token) const override
{
CheckForOwnership(token);
return _container.empty();
}
/*!
* @brief Resizes the container.
* @param size The new size of the container (in elements).
*/
void resize(size_type size)
{ resize(size, std::move(Guard())); }
/*!
* @brief Resizes the container if it is owned by the calling thread.
* @warning The calling thread must provide the corresponding access token!
* @param size The new size of the container.
* @param token The access token.
*/
void resize(size_type size, access_token const& token) const
{
CheckForOwnership(token);
_container.resize(size);
}
/*!
* @brief Resizes the container and initialises with a default element.
* @param size The new size of the container.
* @param def The default value of the container.
*/
void resize(size_type size, value_type const& def)
{ resize(size, def, std::move(Guard())); }
/*!
* @brief Resizes the container and initialises with a default element if it is owned by the calling thread.
* @param size The new size of the container.
* @param def The default value of the container.
* @param token The access token.
*/
void resize(size_type size, value_type const& def, access_token const& token)
{
CheckForOwnership(token);
_container.resize(size, def);
}
/*!
* @brief Reserves space in the container without initialising.
* @param size The new capacity of the container.
*/
void reserve(size_type size)
{ reserve(size, std::move(Guard())); }
/*!
* @brief Reserves space in the container without initialising.
* @param size The new capacity of the container.
* @param token The access token.
*/
void reserve(size_type size, access_token const& token)
{
CheckForOwnership(token);
_container.reserve(size);
}
/*!
* @brief Places the given element at the end of the vector.
* @param item The element to add.
*/
void push_back(value_type const& item)
{ push_back(item, std::move(Guard())); }
/*!
* @brief Places the given element at the end of the vector if the vector is owned by the calling thread.
* @param item The item to add.
* @param token The access token.
*/
void push_back(value_type const& item, access_token const& token)
{
CheckForOwnership(token);
_container.push_back(item);
}
/*!
* @brief Inplace creates the given element at the end of the vector.
* @param item The item to add.
*/
void push_back(value_type&& item)
{ push_back(std::forward<value_type>(item), std::move(Guard())); }
/*!
* @brief Inplace creates the given element at the end of the vector if the container is owned by the calling thread.
* @param item The item to add.
* @param token The access token.
*/
void push_back(value_type&& item, access_token const& token)
{
CheckForOwnership(token);
_container.push_back(std::forward<value_type>(item));
}
/*!
* @brief Swaps two elements of the container.
* @param first The index of the first element.
* @param second THe index of the second element.
*
* @throws out_of_range If either first or second is out of bounds.
*/
void SwapElements(access_type const& first, access_type const& second)
{ SwapElements(first, second, std::move(Guard())); }
/*!
* @brief Swaps two elements of the container if the container is owned by the calling thread.
* @param first The index of the first element.
* @param second The index of the second element.
* @param token The access token.
*
* @throws out_of_range If either first or second is out of bounds.
*/
void SwapElements(access_type const& first, access_type const& second, access_token const& token)
{
// do not swap the same element
if (first == second) return;
// <0 is (currently) impossible since access_type is unsigned
if (first >= size(token)) throw std::out_of_range("Parameter \"first\" is out of bounds.");
if (second >= size(token)) throw std::out_of_range("Parameter \"second\" is out of bounds.");
CheckForOwnership(token);
std::iter_swap(begin() + first, begin() + second);
}
/*!
* Swaps the given element with the last element.
* @param index The index of the element.
*
* @throws out_of_range If @p index is out of range.
*/
void SwapElements(access_type const& index)
{ swap(index, std::move(Guard())); }
/*!
* Swaps the given element with the last element if the container is owned by the calling thread.
* @param index The index of the element.
* @param token The access token.
*
* @throws out_of_range If @p index is out of range.
*/
void SwapElements(access_type const& index, access_token const& token)
{
CheckForOwnership(token);
// TODO: this might block if an error is thrown...
std::iter_swap(index, end(token) - 1);
}
/*!
* @brief Gets an iterator to the beginning of the container.
*
* @details Iterators are THE problem for concurrent containers. There is no guarantee that the container is owned by the thread requesting
* the iterator, thus resulting in race conditions. I decided to expose the underlying container iterator, but only in "locked" methods. If
* you need to use iterators (and lets be honest, they are pretty neat), make sure you follow this principle:
* @code{.cpp}
* {
* auto token = container.Guard();
* auto it = container.begin(token);
* ...
* }
* @endcode
* This ensures that the container is locked until the iterator is out of scope (curly-brackets). It is not as nice as just using the
* standard begin, and prevents the "default" usage of containers in stl algorithms but emphasises the need for ownership.
* If I feel the need
* for it, I'll implement a custom iterator that locks the container until it is destroyed.
*
* @param token The access token.
* @warning This is inherently unsafe!
*/
iterator begin(access_token const& token) noexcept
{
CheckForOwnership(token);
return _container.begin();
}
// copydetails apparently copies param and warning
/*!
* @brief Gets a reverse iterator to the beginning of the container.
* @copydetails begin()
*/
reverse_iterator rbegin(access_token const& token) noexcept
{
CheckForOwnership(token);
return _container.rbegin();
}
/*!
* @brief Gets an iterator to the end of the container.
* @copydetails begin()
*/
iterator end(access_token const& token) noexcept
{
CheckForOwnership(token);
return _container.end();
}
/*!
* @brief Gets a reverse iterator to the end of the container.
* @copydetails begin()
*/
reverse_iterator rend(access_token const& token) noexcept
{
CheckForOwnership(token);
return _container.rend();
}
/*!
* @brief Gets an iterator to the beginning of the container.
* @copydetails begin()
*/
const_iterator begin(access_token const& token) const noexcept
{
CheckForOwnership(token);
return _container.begin();
}
/*!
* @brief Gets a reversed iterator to the beginning of the container.
* @copydetails begin()
*/
const_reverse_iterator rbegin(access_token const& token) const noexcept
{
CheckForOwnership(token);
return _container.rbegin();
}
/*!
* @brief Gets an iterator to the end of the container.
* @copydetails begin()
*/
const_iterator end(access_token const& token) const noexcept
{
CheckForOwnership(token);
return _container.end();
}
/*!
* @brief Gets a reverse iterator to the end of the container.
* @copydetails begin()
*/
const_reverse_iterator rend(access_token const& token) const noexcept
{
CheckForOwnership(token);
return _container.rend();
}
/*!
* @brief Clears the container.
*
* @note Calling this method takes ownership of the container for the duration of the clear. If the container is currently owned by
* another thread, this method will block until the other thread releases the container.
*
* @sa clear(access_token const&)
*/
void clear() noexcept
{ clear(std::move(Guard())); }
/*!
* @brief Clears the container.
* @details Calling this method requires the caller to provide an ownership token of the corresponding queue object.
* @param token The access token of this container.
*/
void clear(access_token const& token) noexcept
{
CheckForOwnership(token);
_container.clear();
}
};
}
| 34.468085
| 147
| 0.585494
|
chill-nemesis
|
6fe1123e3f47a5e96f96c46837d280f95880cf38
| 2,793
|
cpp
|
C++
|
Leetcode/L146.cpp
|
yanjinbin/Foxconn
|
d8340d228deb35bd8ec244f6156374da8a1f0aa0
|
[
"CC0-1.0"
] | 8
|
2021-02-14T01:48:09.000Z
|
2022-01-29T09:12:55.000Z
|
Leetcode/L146.cpp
|
yanjinbin/Foxconn
|
d8340d228deb35bd8ec244f6156374da8a1f0aa0
|
[
"CC0-1.0"
] | null | null | null |
Leetcode/L146.cpp
|
yanjinbin/Foxconn
|
d8340d228deb35bd8ec244f6156374da8a1f0aa0
|
[
"CC0-1.0"
] | null | null | null |
// 146. LRU 缓存机制
#include <vector>
#include <iostream>
#include <queue>
#include <map>
#include <unordered_map>
#include <algorithm>
#include <functional>
#include <stack>
#include <cmath>
using namespace std;
const int MAX_VALUE = 0x7FFFFFFF, MIN_VALUE = 0x80000000, INF = 0x3F3F3F3F, MOD = 1E9 + 7;
#define fastio ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
#define debug puts("pigtoria bling bling ⚡️⚡️");
#define FOR(i, a, b) for (int i = a; i < b; i++)
#define pii pair<int, int>
#define LL long long
#define LD long double
#define PB push_back
#define EB emplace_back
#define MP make_pair
#define FI first
#define SE second
struct DLinkedNode {
int key;
int value;
DLinkedNode *prev;
DLinkedNode *next;
DLinkedNode() : key(0), value(0) {}
DLinkedNode(int _key, int _value) {
this->key = _key;
this->value = _value;
}
};
// GET PUT操作都是O(1)
class LRUCache {
private:
unordered_map<int, DLinkedNode *> cache;
DLinkedNode *head;// 维护head tail 两个虚拟节点
DLinkedNode *tail;
int size;
int cap;
public:
LRUCache(int capacity) {
this->cap = capacity;
size = 0;
head = new DLinkedNode();
tail = new DLinkedNode();
head->next = tail;
tail->prev = head;
}
int get(int key) {
if (!cache.count(key))return -1;
DLinkedNode *node = cache[key];
moveToHead(node);
return node->value;
}
void put(int key, int value) {
if (!cache.count(key)) {
DLinkedNode *newNode = new DLinkedNode(key, value);
cache[key] = newNode;
addToHead(newNode);
size++;
if (size > cap) {
DLinkedNode* removed = removeTail();
cache.erase(removed->key);
delete removed;
size--;
}
} else {
DLinkedNode *node = cache[key];
node->value = value;
moveToHead(node);
}
}
void moveToHead(DLinkedNode *node) {
removeNode(node);
addToHead(node);
}
DLinkedNode *removeTail() {
DLinkedNode *node = tail->prev;
removeNode(node);
return node;
}
void removeNode(DLinkedNode *target) {
DLinkedNode *prev = target->prev;
DLinkedNode *next = target->next;
prev->next = next;
next->prev = prev;
}
void addToHead(DLinkedNode *node) {//
DLinkedNode *nxt = head->next;
head->next = node;
node->prev = head;
nxt->prev = node;
node->next = nxt;
}
};
/**
* Your LRUCache object will be instantiated and called as such:
* LRUCache* obj = new LRUCache(capacity);
* int param_1 = obj->get(key);
* obj->put(key,value);
*/
| 23.275
| 90
| 0.570354
|
yanjinbin
|
6fe14e6833dcc4759c20af194573d03244a5ca90
| 15,619
|
cpp
|
C++
|
avs/vis_avs/r_transition.cpp
|
Const-me/vis_avs_dx
|
da1fd9f4323d7891dea233147e6ae16790ad9ada
|
[
"MIT"
] | 33
|
2019-01-28T03:32:17.000Z
|
2022-02-12T18:17:26.000Z
|
avs/vis_avs/r_transition.cpp
|
visbot/vis_avs_dx
|
03e55f8932a97ad845ff223d3602ff2300c3d1d4
|
[
"MIT"
] | 2
|
2019-11-18T17:54:58.000Z
|
2020-07-21T18:11:21.000Z
|
avs/vis_avs/r_transition.cpp
|
Const-me/vis_avs_dx
|
da1fd9f4323d7891dea233147e6ae16790ad9ada
|
[
"MIT"
] | 5
|
2019-02-16T23:00:11.000Z
|
2022-03-27T15:22:10.000Z
|
/*
LICENSE
-------
Copyright 2005 Nullsoft, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of Nullsoft nor the names of its contributors may be used to
endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "stdafx.h"
#include "draw.h"
#include "resource.h"
#include "cfgwnd.h"
#include "r_defs.h"
#include "r_unkn.h"
#include "r_transition.h"
#include "render.h"
#include <Interop/Utils/dbgSetThreadName.h>
#include <Threads/threadsApi.h>
extern char *scanstr_back( char *str, char *toscan, char *defval );
static const char *transitionmodes[] =
{
"Random",
"Cross dissolve",
"L/R Push",
"R/L Push",
"T/B Push",
"B/T Push",
"9 Random Blocks",
"Split L/R Push",
"L/R to Center Push",
"L/R to Center Squeeze",
"L/R Wipe",
"R/L Wipe",
"T/B Wipe",
"B/T Wipe",
"Dot Dissolve",
};
static C_RenderTransitionClass *g_this;
C_RenderTransitionClass::C_RenderTransitionClass()
{
last_file[ 0 ] = 0;
l_w = l_h = 0;
enabled = 0;
start_time = 0;
_dotransitionflag = 0;
initThread = 0;
createTransitionInstance();
}
C_RenderTransitionClass::~C_RenderTransitionClass()
{
if( initThread )
{
WaitForSingleObject( initThread, INFINITE );
CloseHandle( initThread );
initThread = 0;
}
}
unsigned int WINAPI C_RenderTransitionClass::m_initThread( LPVOID p )
{
dbgSetThreadName( "AVS Transition Thread" );
C_RenderTransitionClass *_this = (C_RenderTransitionClass*)p;
FILETIME ft;
GetSystemTimeAsFileTime( &ft );
srand( ft.dwLowDateTime | ft.dwHighDateTime^GetCurrentThreadId() );
/* if( cfg_transitions2 & 32 )
{
int d = GetThreadPriority( g_hThread );
if( d == THREAD_PRIORITY_TIME_CRITICAL ) d = THREAD_PRIORITY_HIGHEST;
else if( d == THREAD_PRIORITY_HIGHEST ) d = THREAD_PRIORITY_ABOVE_NORMAL;
else if( d == THREAD_PRIORITY_ABOVE_NORMAL ) d = THREAD_PRIORITY_NORMAL;
else if( d == THREAD_PRIORITY_NORMAL ) d = THREAD_PRIORITY_BELOW_NORMAL;
else if( d == THREAD_PRIORITY_BELOW_NORMAL ) d = THREAD_PRIORITY_LOWEST;
else if( d == THREAD_PRIORITY_LOWEST ) d = THREAD_PRIORITY_IDLE;
SetThreadPriority( GetCurrentThread(), d );
} */
int *fb = (int *)GlobalAlloc( GPTR, _this->l_w*_this->l_h * sizeof( int ) );
char last_visdata[ 2 ][ 2 ][ 576 ] = { 0, };
g_render_effects2->render( last_visdata, 0x80000000, fb, fb, _this->l_w, _this->l_h );
GlobalFree( (HGLOBAL)fb );
_this->_dotransitionflag = 2;
return 0;
}
int C_RenderTransitionClass::LoadPreset( char *file, int which, C_UndoItem *item )
{
if( initThread )
{
if( WaitForSingleObject( initThread, 0 ) == WAIT_TIMEOUT )
{
DDraw_SetStatusText( "loading [wait]...", 1000 * 100 );
return 2;
}
CloseHandle( initThread );
initThread = 0;
}
UPDATE_PRESET();
if( enabled )
{
enabled = 0;
}
int r = 0;
if( item )
{
g_render_effects2->__LoadPresetFromUndo( *item, 1 );
last_which = which;
_dotransitionflag = 2;
}
else
{
lstrcpyn( last_file, file, sizeof( last_file ) );
if( file[ 0 ] ) r = g_render_effects2->__LoadPreset( file, 1 );
else
{
g_render_effects2->clearRenders();
}
if( !r && l_w && l_h && ( cfg_transitions2&which ) && ( ( cfg_transitions2 & 128 ) || DDraw_IsFullScreen() ) )
{
DWORD id;
last_which = which;
_dotransitionflag = 1;
initThread = (HANDLE)_beginthreadex( NULL, 0, m_initThread, (LPVOID)this, 0, (unsigned int*)&id );
DDraw_SetStatusText( "loading...", 1000 * 100 );
}
else
{
last_which = which;
_dotransitionflag = 2;
}
if( r )
{
char s[ MAX_PATH * 2 ];
wsprintf( s, "error loading: %s", scanstr_back( last_file, "\\", last_file - 1 ) + 1 );
DDraw_SetStatusText( s );
_dotransitionflag = 3;
}
C_UndoStack::clear();
C_UndoStack::saveundo( 1 );
C_UndoStack::cleardirty();
}
return !!r;
}
extern int g_rnd_cnt;
int C_RenderTransitionClass::render( uint16_t visdata[ 2 ][ 2 ][ 576 ], int isBeat, int *framebuffer, int *fbout, int w, int h )
{
iTransition* pTrans = getTransition();
if( nullptr == pTrans )
{
// This happens on shutdown, we first shut down our stuff, like D3D, only then this thread. So the thread may run a few times before quit.
return 0;
}
if( _dotransitionflag || enabled ) g_rnd_cnt = 0;
if( _dotransitionflag == 2 || _dotransitionflag == 3 )
{
int notext = _dotransitionflag == 3;
_dotransitionflag = 0;
if( cfg_transitions&last_which )
{
curtrans = ( cfg_transition_mode & 0x7fff ) ? ( cfg_transition_mode & 0x7fff ) : ( rand() % ( ( sizeof( transitionmodes ) / sizeof( transitionmodes[ 0 ] ) ) - 1 ) ) + 1;
if( cfg_transition_mode & 0x8000 ) curtrans |= 0x8000;
ep[ 0 ] = 0;
ep[ 1 ] = 2;
mask = 0;
start_time = 0;
enabled = 1;
}
C_RenderListClass *temp = g_render_effects;
g_render_effects = g_render_effects2;
g_render_effects2 = temp;
extern int need_repop;
extern char *extension( char *fn );
need_repop = 1;
PostMessage( g_hwndDlg, WM_USER + 20, 0, 0 );
if( !notext && _stricmp( "aph", extension( last_file ) ) )
{
char buf[ 512 ];
strncpy( buf, scanstr_back( last_file, "\\", last_file - 1 ) + 1, 510 );
buf[ 510 ] = 0;
scanstr_back( buf, ".", buf + strlen( buf ) )[ 0 ] = 0;
strcat( buf, " " );
DDraw_SetStatusText( buf );
}
}
if( !enabled )
{
l_w = w;
l_h = h;
if( !initThread && g_render_effects2->getNumRenders() )
g_render_effects2->clearRenders();
// return g_render_effects->render( visdata, isBeat, framebuffer, fbout, w, h );
pTrans->renderSingle( visdata, isBeat, g_render_effects );
return 0;
}
int ttime = 250 * cfg_transitions_speed;
if( ttime < 100 ) ttime = 100;
int n;
if( !start_time )
{
n = 0;
start_time = GetTickCount();
}
else
n = MulDiv( GetTickCount() - start_time, 256, ttime );
if( n >= 255 ) n = 255;
float sintrans = (float)( sin( ( (float)n / 255 ) * M_PI - M_PI / 2 ) / 2 + 0.5 ); // used for smoothing transitions
// now sintrans does a smooth curve from 0 to 1
if( curtrans & 0x8000 )
pTrans->renderTransition( visdata, isBeat, g_render_effects2, g_render_effects, curtrans & 0x7fff, sintrans );
else
pTrans->renderSingle( visdata, isBeat, g_render_effects );
/* switch( curtrans & 0x7fff )
{
case 1: // Crossfade
mmx_adjblend_block( o, d, p, x, n );
break;
case 2: // Left to right push
{
int i = (int)( sintrans*w );
int j;
for( j = 0; j < h; j++ )
{
memcpy( framebuffer + ( j*w ), d + ( j*w ) + ( w - i ), i * 4 );
memcpy( framebuffer + ( j*w ) + i, p + ( j*w ), ( w - i ) * 4 );
}
}
break;
case 3: // Right to left push
{
int i = (int)( sintrans*w );
int j;
for( j = 0; j < h; j++ )
{
memcpy( framebuffer + ( j*w ), p + ( i + j * w ), ( w - i ) * 4 );
memcpy( framebuffer + ( j*w ) + ( w - i ), d + ( j*w ), i * 4 );
}
}
break;
case 4: // Top to bottom push
{
int i = (int)( sintrans*h );
memcpy( framebuffer, d + ( h - i )*w, w*i * 4 );
memcpy( framebuffer + w * i, p, w*( h - i ) * 4 );
}
break;
case 5: // Bottom to Top push
{
int i = (int)( sintrans*h );
memcpy( framebuffer, p + i * w, w*( h - i ) * 4 );
memcpy( framebuffer + w * ( h - i ), d, w*i * 4 );
}
break;
case 6: // 9 random blocks
{
if( !( mask&( 1 << ( 10 + n / 28 ) ) ) )
{
int r = 0;
if( ( mask & 0x1ff ) != 0x1ff )
{
do
{
r = rand() % 9;
} while( ( 1 << r ) & mask );
}
mask |= ( 1 << r ) | ( 1 << ( 10 + n / 28 ) );
}
int j;
int tw = w / 3, th = h / 3;
int twr = w - 2 * tw;
memcpy( framebuffer, p, w*h * 4 );
int i;
for( i = 0; i < 9; i++ )
{
if( mask & ( 1 << i ) )
{
int end = i / 3 * th + th;
if( i > 5 ) end = h;
for( j = i / 3 * th; j < end; j++ )
memcpy( framebuffer + ( j*w ) + ( i % 3 )*tw, d + ( j*w ) + ( i % 3 )*tw, ( i % 3 == 2 ) ? twr * 4 : tw * 4 );
}
}
}
break;
case 7: // Left/Right to Right/Left
{
int i = (int)( sintrans*w );
int j;
for( j = 0; j < h / 2; j++ )
{
memcpy( framebuffer + ( i + j * w ), p + ( j*w ), ( w - i ) * 4 );
memcpy( framebuffer + ( j*w ), d + ( ( j + 1 )*w ) - i, i * 4 );
}
for( j = h / 2; j < h; j++ )
{
memcpy( framebuffer + ( j*w ), p + ( i + j * w ), ( w - i ) * 4 );
memcpy( framebuffer + ( j*w ) + ( w - i ), d + ( j*w ), i * 4 );
}
}
break;
case 8: // Left/Right to Center
{
int i = (int)( sintrans*w / 2 );
int j;
for( j = 0; j < h; j++ )
{
memcpy( framebuffer + ( j*w ), d + ( ( j + 1 )*w - i - w / 2 ), i * 4 );
memcpy( framebuffer + ( ( j + 1 )*w - i ), d + ( j*w + w / 2 ), i * 4 );
memcpy( framebuffer + ( j*w ) + i, p + ( j*w ) + i, ( w - i * 2 ) * 4 );
}
}
break;
case 9: // Left/Right to Center, squeeze
{
int i = (int)( sintrans*w / 2 );
int j;
for( j = 0; j < h; j++ )
{
if( i )
{
int xl = i;
int xp = 0;
int dxp = ( ( w / 2 ) << 16 ) / xl;
int *ot = framebuffer + ( j*w );
int *it = d + ( j*w );
while( xl-- )
{
*ot++ = it[ xp >> 16 ];
xp += dxp;
}
}
if( i * 2 != w )
{
int xl = w - i * 2;
int xp = 0;
int dxp = ( w << 16 ) / xl;
int *ot = framebuffer + ( j*w ) + i;
int *it = p + ( j*w );
while( xl-- )
{
*ot++ = it[ xp >> 16 ];
xp += dxp;
}
}
if( i )
{
int xl = i;
int xp = 0;
int dxp = ( ( w / 2 ) << 16 ) / xl;
int *ot = framebuffer + ( j*w ) + w - i;
int *it = d + ( j*w ) + w / 2;
while( xl-- )
{
*ot++ = it[ xp >> 16 ];
xp += dxp;
}
}
}
}
break;
case 10: // Left to right wipe
{
int i = (int)( sintrans*w );
int j;
for( j = 0; j < h; j++ )
{
memcpy( framebuffer + ( i + j * w ), p + ( j*w ) + i, ( w - i ) * 4 );
memcpy( framebuffer + ( j*w ), d + ( j*w ), i * 4 );
}
}
break;
case 11: // Right to left wipe
{
int i = (int)( sintrans*w );
int j;
for( j = 0; j < h; j++ )
{
memcpy( framebuffer + ( j*w ), p + ( j*w ), ( w - i ) * 4 );
memcpy( framebuffer + ( j*w ) + ( w - i ), d + ( j*w ) + ( w - i ), i * 4 );
}
}
break;
case 12: // Top to bottom wipe
{
int i = (int)( sintrans*h );
memcpy( framebuffer, d, w*i * 4 );
memcpy( framebuffer + w * i, p + w * i, w*( h - i ) * 4 );
}
break;
case 13: // Bottom to top wipe
{
int i = (int)( sintrans*h );
memcpy( framebuffer, p, w*( h - i ) * 4 );
memcpy( framebuffer + w * ( h - i ), d + w * ( h - i ), w*i * 4 );
}
break;
case 14: // dot dissolve
{
int i = ( (int)( sintrans * 5 ) ) - 5;
int j;
int t = 0;
int dir = 1;
if( i < 0 )
{
dir = !dir;
i++;
i = -i;
}
i = 1 << i;
for( j = 0; j < h; j++ )
{
if( t++ == i )
{
int x = w;
t = 0;
int t2 = 0;
int *of = framebuffer + j * w;
int *p2 = ( dir ? p : d ) + j * w;
int *d2 = ( dir ? d : p ) + j * w;
while( x-- )
{
if( t2++ == i )
{
of[ 0 ] = p2[ 0 ];
t2 = 0;
}
else of[ 0 ] = d2[ 0 ];
p2++;
d2++;
of++;
}
}
else
memcpy( framebuffer + j * w, ( dir ? d : p ) + j * w, w * sizeof( int ) );
}
}
break;
default:
break;
} */
if( n == 255 )
{
enabled = 0;
start_time = 0;
g_render_effects2->clearRenders();
}
return 0;
}
BOOL CALLBACK C_RenderTransitionClass::g_DlgProc( HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam )
{
switch( uMsg )
{
case WM_INITDIALOG:
{
int x;
for( x = 0; x < sizeof( transitionmodes ) / sizeof( transitionmodes[ 0 ] ); x++ )
SendDlgItemMessage( hwndDlg, IDC_TRANSITION, CB_ADDSTRING, 0, (LPARAM)transitionmodes[ x ] );
SendDlgItemMessage( hwndDlg, IDC_TRANSITION, CB_SETCURSEL, (WPARAM)cfg_transition_mode & 0x7fff, 0 );
SendDlgItemMessage( hwndDlg, IDC_SPEED, TBM_SETRANGE, TRUE, MAKELONG( 1, 32 ) );
SendDlgItemMessage( hwndDlg, IDC_SPEED, TBM_SETPOS, TRUE, cfg_transitions_speed );
if( cfg_transition_mode & 0x8000 ) CheckDlgButton( hwndDlg, IDC_CHECK9, BST_CHECKED );
if( cfg_transitions & 1 ) CheckDlgButton( hwndDlg, IDC_CHECK2, BST_CHECKED );
if( cfg_transitions & 2 ) CheckDlgButton( hwndDlg, IDC_CHECK1, BST_CHECKED );
if( cfg_transitions & 4 ) CheckDlgButton( hwndDlg, IDC_CHECK8, BST_CHECKED );
if( cfg_transitions2 & 1 ) CheckDlgButton( hwndDlg, IDC_CHECK10, BST_CHECKED );
if( cfg_transitions2 & 2 ) CheckDlgButton( hwndDlg, IDC_CHECK11, BST_CHECKED );
if( cfg_transitions2 & 4 ) CheckDlgButton( hwndDlg, IDC_CHECK3, BST_CHECKED );
if( cfg_transitions2 & 32 ) CheckDlgButton( hwndDlg, IDC_CHECK4, BST_CHECKED );
if( !( cfg_transitions2 & 128 ) ) CheckDlgButton( hwndDlg, IDC_CHECK5, BST_CHECKED );
}
return 1;
case WM_COMMAND:
switch( LOWORD( wParam ) )
{
case IDC_TRANSITION:
if( HIWORD( wParam ) == CBN_SELCHANGE )
{
int r = SendDlgItemMessage( hwndDlg, IDC_TRANSITION, CB_GETCURSEL, 0, 0 );
if( r != CB_ERR )
{
cfg_transition_mode &= ~0x7fff;
cfg_transition_mode |= r;
}
}
break;
case IDC_CHECK9:
cfg_transition_mode &= 0x7fff;
cfg_transition_mode |= IsDlgButtonChecked( hwndDlg, IDC_CHECK9 ) ? 0x8000 : 0;
break;
case IDC_CHECK2:
cfg_transitions &= ~1;
cfg_transitions |= IsDlgButtonChecked( hwndDlg, IDC_CHECK2 ) ? 1 : 0;
break;
case IDC_CHECK1:
cfg_transitions &= ~2;
cfg_transitions |= IsDlgButtonChecked( hwndDlg, IDC_CHECK1 ) ? 2 : 0;
break;
case IDC_CHECK8:
cfg_transitions &= ~4;
cfg_transitions |= IsDlgButtonChecked( hwndDlg, IDC_CHECK8 ) ? 4 : 0;
break;
case IDC_CHECK10:
cfg_transitions2 &= ~1;
cfg_transitions2 |= IsDlgButtonChecked( hwndDlg, IDC_CHECK10 ) ? 1 : 0;
break;
case IDC_CHECK11:
cfg_transitions2 &= ~2;
cfg_transitions2 |= IsDlgButtonChecked( hwndDlg, IDC_CHECK11 ) ? 2 : 0;
break;
case IDC_CHECK3:
cfg_transitions2 &= ~4;
cfg_transitions2 |= IsDlgButtonChecked( hwndDlg, IDC_CHECK3 ) ? 4 : 0;
break;
case IDC_CHECK4:
cfg_transitions2 &= ~32;
cfg_transitions2 |= IsDlgButtonChecked( hwndDlg, IDC_CHECK4 ) ? 32 : 0;
break;
case IDC_CHECK5:
cfg_transitions2 &= ~128;
cfg_transitions2 |= IsDlgButtonChecked( hwndDlg, IDC_CHECK5 ) ? 0 : 128;
break;
}
break;
case WM_NOTIFY:
if( LOWORD( wParam ) == IDC_SPEED )
cfg_transitions_speed = SendDlgItemMessage( hwndDlg, IDC_SPEED, TBM_GETPOS, 0, 0 );
break;
}
return 0;
}
HWND C_RenderTransitionClass::conf( HINSTANCE hInstance, HWND hwndParent )
{
g_this = this;
return CreateDialog( hInstance, MAKEINTRESOURCE( IDD_GCFG_TRANSITIONS ), hwndParent, g_DlgProc );
}
| 26.790738
| 172
| 0.600679
|
Const-me
|
6fe203e5f0d5412ecaac18c0901295b10e28142e
| 1,171
|
cpp
|
C++
|
src/armnn/backends/RefWorkloads/RefFullyConnectedFloat32Workload.cpp
|
Air000/armnn_s32v
|
ec3ee60825d6b7642a70987c4911944cef7a3ee6
|
[
"MIT"
] | 1
|
2019-03-19T08:44:28.000Z
|
2019-03-19T08:44:28.000Z
|
src/armnn/backends/RefWorkloads/RefFullyConnectedFloat32Workload.cpp
|
Air000/armnn_s32v
|
ec3ee60825d6b7642a70987c4911944cef7a3ee6
|
[
"MIT"
] | null | null | null |
src/armnn/backends/RefWorkloads/RefFullyConnectedFloat32Workload.cpp
|
Air000/armnn_s32v
|
ec3ee60825d6b7642a70987c4911944cef7a3ee6
|
[
"MIT"
] | 1
|
2019-10-11T05:58:56.000Z
|
2019-10-11T05:58:56.000Z
|
//
// Copyright © 2017 Arm Ltd. All rights reserved.
// See LICENSE file in the project root for full license information.
//
#include "RefFullyConnectedFloat32Workload.hpp"
#include "FullyConnected.hpp"
#include "RefWorkloadUtils.hpp"
#include "Profiling.hpp"
namespace armnn
{
void RefFullyConnectedFloat32Workload::Execute() const
{
ARMNN_SCOPED_PROFILING_EVENT(Compute::CpuRef, "RefFullyConnectedFloat32Workload_Execute");
const TensorInfo& inputInfo = GetTensorInfo(m_Data.m_Inputs[0]);
const TensorInfo& outputInfo = GetTensorInfo(m_Data.m_Outputs[0]);
float* outputData = GetOutputTensorDataFloat(0, m_Data);
const float* inputData = GetInputTensorDataFloat(0, m_Data);
const float* weightData = m_Data.m_Weight->GetConstTensor<float>();
const float* biasData = m_Data.m_Parameters.m_BiasEnabled ? m_Data.m_Bias->GetConstTensor<float>() : nullptr;
FullyConnected(inputData,
outputData,
inputInfo,
outputInfo,
weightData,
biasData,
m_Data.m_Parameters.m_TransposeWeightMatrix);
}
} //namespace armnn
| 30.815789
| 115
| 0.69257
|
Air000
|
6fe460882832275af6988e4e6ad433e38edddeaa
| 184
|
hh
|
C++
|
src/network/simple_router.hh
|
zzunny97/Graduate-Velox
|
d820e7c8cee52f22d7cd9027623bd82ca59733ca
|
[
"Apache-2.0"
] | 17
|
2016-11-27T13:13:40.000Z
|
2021-09-07T06:42:25.000Z
|
src/network/simple_router.hh
|
zzunny97/Graduate-Velox
|
d820e7c8cee52f22d7cd9027623bd82ca59733ca
|
[
"Apache-2.0"
] | 22
|
2017-01-18T06:10:18.000Z
|
2019-05-15T03:49:19.000Z
|
src/network/simple_router.hh
|
zzunny97/Graduate-Velox
|
d820e7c8cee52f22d7cd9027623bd82ca59733ca
|
[
"Apache-2.0"
] | 5
|
2017-07-24T15:19:32.000Z
|
2022-02-19T09:11:01.000Z
|
#pragma once
#include "router.hh"
namespace eclipse {
//
class SimpleRouter: public Router {
public:
void on_read(messages::Message*, Channel*) override;
};
} /* eclipse */
| 14.153846
| 56
| 0.673913
|
zzunny97
|
6fe4b7b2c20f22365fb5e0a4cdb3d09fd396c4fd
| 10,419
|
cc
|
C++
|
proc/binfmt/elf.cc
|
PoisonNinja/quark
|
0cc2b8191f0c5cbd856caac688bfdac54a7d3369
|
[
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] | 3
|
2019-08-01T03:16:31.000Z
|
2022-02-17T06:52:26.000Z
|
proc/binfmt/elf.cc
|
PoisonNinja/quark
|
0cc2b8191f0c5cbd856caac688bfdac54a7d3369
|
[
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] | 32
|
2018-03-26T20:10:44.000Z
|
2020-07-13T03:01:42.000Z
|
proc/binfmt/elf.cc
|
PoisonNinja/quark
|
0cc2b8191f0c5cbd856caac688bfdac54a7d3369
|
[
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] | 1
|
2018-08-29T21:31:06.000Z
|
2018-08-29T21:31:06.000Z
|
#include <arch/mm/layout.h>
#include <errno.h>
#include <kernel.h>
#include <kernel/init.h>
#include <lib/string.h>
#include <mm/physical.h>
#include <mm/virtual.h>
#include <proc/binfmt/binfmt.h>
#include <proc/binfmt/elf.h>
#include <proc/process.h>
#include <proc/sched.h>
#include <proc/uthread.h>
extern "C" void signal_return();
void* signal_return_location = reinterpret_cast<void*>(&signal_return);
namespace elf
{
void setup_registers(struct thread_context& ctx, addr_t entry, uint64_t argc,
addr_t argv, addr_t envp, addr_t uthread, addr_t stack);
class ELF : public binfmt::binfmt
{
public:
virtual const char* name() override;
virtual bool
is_match(libcxx::intrusive_ptr<filesystem::descriptor> file) override;
int load(struct ::binfmt::binprm& prm) override;
};
const char* ELF::name()
{
return "ELF";
}
bool ELF::is_match(libcxx::intrusive_ptr<filesystem::descriptor> file)
{
uint8_t buffer[sizeof(elf_ehdr)];
file->pread(buffer, sizeof(elf_ehdr), 0);
elf_ehdr* header = reinterpret_cast<elf_ehdr*>(buffer);
if (libcxx::memcmp(header->e_ident, ELFMAG, 4)) {
return false;
}
return true;
}
int ELF::load(struct ::binfmt::binprm& prm)
{
process* current_process = scheduler::get_current_process();
uint8_t buffer[sizeof(elf_ehdr)];
prm.file->pread(buffer, sizeof(elf_ehdr), 0);
process* process = scheduler::get_current_process();
elf_ehdr* header = reinterpret_cast<elf_ehdr*>(buffer);
if (libcxx::memcmp(header->e_ident, ELFMAG, 4)) {
log::printk(log::log_level::ERROR,
"Binary passed in is not an ELF file!\n");
return -EINVAL;
}
log::printk(log::log_level::DEBUG, "Section header offset: %p\n",
header->e_shoff);
log::printk(log::log_level::DEBUG, "Program header offset: %p\n",
header->e_phoff);
elf_phdr* tls_phdr = nullptr;
for (int i = 0; i < header->e_phnum; i++) {
uint8_t phdr_buffer[sizeof(elf_phdr)];
prm.file->pread(phdr_buffer, sizeof(elf_phdr),
header->e_phoff + (header->e_phentsize * i));
elf_phdr* phdr = reinterpret_cast<elf_phdr*>(phdr_buffer);
log::printk(log::log_level::DEBUG, "Header type: %X\n", phdr->p_type);
if (phdr->p_type == PT_TLS) {
log::printk(log::log_level::DEBUG, "Found TLS section\n");
process->set_tls_data(phdr->p_offset, phdr->p_filesz, phdr->p_memsz,
phdr->p_align);
tls_phdr = phdr;
}
if (phdr->p_type == PT_LOAD) {
log::printk(log::log_level::DEBUG, "Flags: %X\n",
phdr->p_flags);
log::printk(log::log_level::DEBUG, "Offset: %p\n",
phdr->p_offset);
log::printk(log::log_level::DEBUG, "Virtual address: %p\n",
phdr->p_vaddr);
log::printk(log::log_level::DEBUG, "Physical address: %p\n",
phdr->p_paddr);
log::printk(log::log_level::DEBUG, "File size: %p\n",
phdr->p_filesz);
log::printk(log::log_level::DEBUG, "Memory size: %p\n",
phdr->p_memsz);
log::printk(log::log_level::DEBUG, "Align: %p\n",
phdr->p_align);
// Compute the mmap prot from ELF flags
int prot = 0;
if (phdr->p_flags & PF_R) {
prot |= PROT_READ;
}
if (phdr->p_flags & PF_W) {
prot |= PROT_WRITE;
}
if (phdr->p_flags & PF_X) {
prot |= PROT_EXEC;
}
// Compute mmap flags
int flags = MAP_FIXED | MAP_PRIVATE;
process->mmap(phdr->p_vaddr, phdr->p_memsz, prot, flags, prm.file,
phdr->p_offset);
if (phdr->p_filesz < phdr->p_memsz) {
// We're supposed to zero out the remaining
log::printk(log::log_level::DEBUG,
"Memory size is larger than file size\n");
/*
* There are two possible scenarios*
*
* First case, memsz will still fit into the same page as
* before, we don't need anything else.
*
* Second case, memsz will spill over into additional page(s),
* we'll simply map another anonymous page beyond.
*/
if (memory::virt::align_down(phdr->p_vaddr + phdr->p_memsz) ==
memory::virt::align_down(phdr->p_vaddr + phdr->p_filesz)) {
libcxx::memset(
reinterpret_cast<void*>(phdr->p_vaddr + phdr->p_filesz),
0, phdr->p_memsz - phdr->p_filesz);
} else {
addr_t file_end = phdr->p_vaddr + phdr->p_filesz;
addr_t mem_end = phdr->p_vaddr + phdr->p_memsz;
addr_t page_end =
memory::virt::align_up(phdr->p_vaddr + phdr->p_filesz);
libcxx::memset(reinterpret_cast<void*>(file_end), 0,
page_end - file_end);
size_t to_map = memory::virt::align_up(mem_end - page_end);
process->mmap(page_end, to_map, prot, flags | MAP_ANONYMOUS,
nullptr, 0);
}
}
}
}
log::printk(log::log_level::DEBUG, "Entry point: %p\n", header->e_entry);
// TODO: More sanity checks
size_t argv_size =
sizeof(char*) * (prm.argc + 1); // argv is null terminated
size_t envp_size =
sizeof(char*) * (prm.envc + 1); // envp is null terminated
for (int i = 0; i < prm.argc; i++) {
argv_size += libcxx::strlen(prm.argv[i]) + 1;
};
for (int i = 0; i < prm.envc; i++) {
envp_size += libcxx::strlen(prm.envp[i]) + 1;
}
size_t tls_raw_size =
libcxx::round_up(tls_phdr->p_memsz, tls_phdr->p_align);
size_t tls_size = libcxx::round_up(tls_raw_size + sizeof(struct uthread),
tls_phdr->p_align);
void* argv_zone =
current_process->mmap(USER_START, argv_size, PROT_READ | PROT_WRITE,
MAP_ANONYMOUS, nullptr, 0);
if (argv_zone) {
log::printk(log::log_level::DEBUG, "argv located at %p\n", argv_zone);
} else {
log::printk(log::log_level::ERROR, "Failed to locate argv\n");
return false;
}
void* envp_zone =
current_process->mmap(USER_START, envp_size, PROT_READ | PROT_WRITE,
MAP_ANONYMOUS, nullptr, 0);
if (envp_zone) {
log::printk(log::log_level::DEBUG, "envp located at %p\n", envp_zone);
} else {
log::printk(log::log_level::ERROR, "Failed to locate envp\n");
return false;
}
void* stack_zone =
current_process->mmap(USER_START, 0x1000, PROT_READ | PROT_WRITE,
MAP_ANONYMOUS | MAP_GROWSDOWN, nullptr, 0);
if (stack_zone) {
log::printk(log::log_level::DEBUG, "Stack located at %p\n", stack_zone);
} else {
log::printk(log::log_level::ERROR, "Failed to locate stack\n");
return false;
}
void* sigreturn_zone = current_process->mmap(
USER_START, 0x1000, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_ANONYMOUS,
nullptr, 0);
if (sigreturn_zone) {
log::printk(log::log_level::DEBUG, "Sigreturn page located at %p\n",
sigreturn_zone);
} else {
log::printk(log::log_level::ERROR, "Failed to locate sigreturn page\n");
return false;
}
void* tls_zone =
current_process->mmap(USER_START, tls_size, PROT_READ | PROT_WRITE,
MAP_ANONYMOUS, nullptr, 0);
if (tls_zone) {
log::printk(log::log_level::DEBUG, "TLS copy located at %p\n",
tls_zone);
} else {
log::printk(log::log_level::ERROR, "Failed to locate TLS copy\n");
return false;
}
current_process->set_sigreturn(reinterpret_cast<addr_t>(sigreturn_zone));
// Copy in sigreturn trampoline code
libcxx::memcpy(reinterpret_cast<void*>(sigreturn_zone),
signal_return_location, 0x1000);
// Make it unwritable
memory::virt::protect(reinterpret_cast<addr_t>(sigreturn_zone), PAGE_USER);
// Copy TLS data into thread specific data
libcxx::memcpy(reinterpret_cast<void*>(tls_zone),
reinterpret_cast<void*>(tls_phdr->p_offset),
tls_phdr->p_filesz);
libcxx::memset(reinterpret_cast<void*>(tls_zone + tls_phdr->p_filesz), 0,
tls_phdr->p_memsz - tls_phdr->p_filesz);
struct uthread* uthread =
reinterpret_cast<struct uthread*>(tls_zone + tls_raw_size);
uthread->self = uthread;
char* target =
reinterpret_cast<char*>(argv_zone + (sizeof(char*) * (prm.argc + 1)));
char** target_argv = reinterpret_cast<char**>(argv_zone);
for (int i = 0; i < prm.argc; i++) {
libcxx::strcpy(target, prm.argv[i]);
target_argv[i] = target;
target += libcxx::strlen(prm.argv[i]) + 1;
}
target_argv[prm.argc] = 0;
target =
reinterpret_cast<char*>(envp_zone + (sizeof(char*) * (prm.envc + 1)));
char** target_envp = reinterpret_cast<char**>(envp_zone);
for (int i = 0; i < prm.envc; i++) {
libcxx::strcpy(target, prm.envp[i]);
target_envp[i] = target;
target += libcxx::strlen(prm.envp[i]) + 1;
}
target_envp[prm.envc] = 0;
libcxx::memset(reinterpret_cast<void*>(stack_zone), 0, 0x1000);
// Let the architecture setup the registers
setup_registers(prm.ctx, header->e_entry, prm.argc,
reinterpret_cast<addr_t>(target_argv),
reinterpret_cast<addr_t>(target_envp),
reinterpret_cast<addr_t>(uthread),
reinterpret_cast<addr_t>(stack_zone) + 0x1000);
scheduler::get_current_thread()->set_context(prm.ctx);
return 0;
}
namespace
{
ELF elf;
int init()
{
binfmt::add(elf);
return 0;
}
CORE_INITCALL(init);
} // namespace
} // namespace elf
| 38.025547
| 80
| 0.562914
|
PoisonNinja
|
6fe637ead03efcd628decb7955efac53f46d9514
| 383
|
cpp
|
C++
|
src/World/Chunk.cpp
|
olesgedz/Cube
|
12f0b48cc89a8fbb381e3e47e482bb6f3fcf04d6
|
[
"Apache-2.0"
] | null | null | null |
src/World/Chunk.cpp
|
olesgedz/Cube
|
12f0b48cc89a8fbb381e3e47e482bb6f3fcf04d6
|
[
"Apache-2.0"
] | null | null | null |
src/World/Chunk.cpp
|
olesgedz/Cube
|
12f0b48cc89a8fbb381e3e47e482bb6f3fcf04d6
|
[
"Apache-2.0"
] | null | null | null |
//
// Created by Jeromy Black on 12/25/20.
//
#include "Chunk.h"
#include "Quad.h"
#include <cmath>
#include "World.h"
void Chunk::generate()
{
}
Chunk::~Chunk()
{
}
Chunk::Chunk(vec3 p)
{
}
BlockType *** Chunk::allocateChunk()
{
}
void Chunk::setBlock(BlockType b_type, vec3 &pos, bool *neighbors)
{
}
void Chunk::setNeighbors()
{
}
void Chunk::generateTerrain()
{
}
| 8.704545
| 66
| 0.637076
|
olesgedz
|
6fe77d1b707b8ee15c86e5a5efcc960f716ed616
| 578
|
cpp
|
C++
|
201411_201509/0523_ABC024/ABC024_D.cpp
|
kazunetakahashi/atcoder
|
16ce65829ccc180260b19316e276c2fcf6606c53
|
[
"MIT"
] | 7
|
2019-03-24T14:06:29.000Z
|
2020-09-17T21:16:36.000Z
|
201411_201509/0523_ABC024/ABC024_D.cpp
|
kazunetakahashi/atcoder
|
16ce65829ccc180260b19316e276c2fcf6606c53
|
[
"MIT"
] | null | null | null |
201411_201509/0523_ABC024/ABC024_D.cpp
|
kazunetakahashi/atcoder
|
16ce65829ccc180260b19316e276c2fcf6606c53
|
[
"MIT"
] | 1
|
2020-07-22T17:27:09.000Z
|
2020-07-22T17:27:09.000Z
|
#include <iostream>
using namespace std;
const int W = 1000000007;
const int M = 1000000007;
typedef long long ll;
ll inv(ll i) {
if (i == 1) return 1;
return ((M - inv(M%i)) * (M/i))%M;
}
int main() {
ll x, y, z;
cin >> x >> y >> z;
ll r, c;
if (x%M != 0) { // xはMの倍数にならない。
ll A = (((y + M - x)%M) * inv(x))%M;
ll B = (((z + M - x)%M) * inv(x))%M;
ll ab = (A*B)%M;
if ((ab-1+M)%M != 0) {
r = (((ab + A)%M) * inv((1+M-ab)%M))%M;
c = (B * (r+1)%M)%M;
} else {
r = 1;
c = 0;
}
}
cout << r << " " << c << endl;
}
| 18.0625
| 45
| 0.408304
|
kazunetakahashi
|
6ff063624c694db88a430d8a31c3cf77bc96a1b6
| 210
|
cpp
|
C++
|
hello-cpp-world.cpp
|
AlanU/cppmsgSamples
|
8b4688dd3a67ae07e9b48d7c0015238aa2221c03
|
[
"MIT"
] | 1
|
2016-03-05T02:39:54.000Z
|
2016-03-05T02:39:54.000Z
|
hello-cpp-world.cpp
|
AlanU/cppmsgSamples
|
8b4688dd3a67ae07e9b48d7c0015238aa2221c03
|
[
"MIT"
] | null | null | null |
hello-cpp-world.cpp
|
AlanU/cppmsgSamples
|
8b4688dd3a67ae07e9b48d7c0015238aa2221c03
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <memory>
#include "test.h"
//alan uthoff
int main() {
std::unique_ptr<interface> iptr(new anotherClass());
iptr->foo();
std::cout << "Hello World!" << std::endl;
}
| 14
| 56
| 0.614286
|
AlanU
|
6ff26909776df94c86d919824a44170597aafe5a
| 370
|
cpp
|
C++
|
Engine/Source/Sapphire/Rendering/Framework/Primitives/Mesh/IMesh.cpp
|
SapphireSuite/Sapphire
|
f4ec03f2602eb3fb6ba8c5fa8abf145f66179a47
|
[
"MIT"
] | 2
|
2020-03-18T09:06:21.000Z
|
2020-04-09T00:07:56.000Z
|
Engine/Source/Sapphire/Rendering/Framework/Primitives/Mesh/IMesh.cpp
|
SapphireSuite/Sapphire
|
f4ec03f2602eb3fb6ba8c5fa8abf145f66179a47
|
[
"MIT"
] | null | null | null |
Engine/Source/Sapphire/Rendering/Framework/Primitives/Mesh/IMesh.cpp
|
SapphireSuite/Sapphire
|
f4ec03f2602eb3fb6ba8c5fa8abf145f66179a47
|
[
"MIT"
] | null | null | null |
// Copyright 2020 Sapphire development team. All Rights Reserved.
#include <Rendering/Framework/Primitives/Mesh/IMesh.hpp>
namespace Sa
{
std::shared_ptr<VertexLayout> IMesh::GetLayout() const noexcept
{
return mLayout;
}
void IMesh::Create(const IRenderInstance& _instance, const RawMesh& _rawMesh)
{
(void)_instance;
mLayout = _rawMesh.GetLayout();
}
}
| 20.555556
| 78
| 0.748649
|
SapphireSuite
|
6ff830f863310e6a993de60c280d1f1848695db4
| 2,480
|
cpp
|
C++
|
competitive programming/leetcode/40. Combination Sum II.cpp
|
sureshmangs/Code
|
de91ffc7ef06812a31464fb40358e2436734574c
|
[
"MIT"
] | 16
|
2020-06-02T19:22:45.000Z
|
2022-02-05T10:35:28.000Z
|
competitive programming/leetcode/40. Combination Sum II.cpp
|
codezoned/Code
|
de91ffc7ef06812a31464fb40358e2436734574c
|
[
"MIT"
] | null | null | null |
competitive programming/leetcode/40. Combination Sum II.cpp
|
codezoned/Code
|
de91ffc7ef06812a31464fb40358e2436734574c
|
[
"MIT"
] | 2
|
2020-08-27T17:40:06.000Z
|
2022-02-05T10:33:52.000Z
|
Given a collection of candidate numbers (candidates) and a target number (target),
find all unique combinations in candidates where the candidate numbers sums to target.
Each number in candidates may only be used once in the combination.
Note:
All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
Example 1:
Input: candidates = [10,1,2,7,6,1,5], target = 8,
A solution set is:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]
Example 2:
Input: candidates = [2,5,2,1,2], target = 5,
A solution set is:
[
[1,2,2],
[5]
]
// TC: 2^n
// SC: O(1)
class Solution {
public:
void combSum(vector<int> &candidates, int target, int cur, vector<int> &comb, vector<vector<int>> &res){
if (target == 0){
res.push_back(comb);
return;
}
if (target < 0) return;
for (int i = cur; i < candidates.size(); i++){
if (i > 0 && candidates[i] == candidates[i - 1] && i > cur) continue; // check for duplicates
comb.push_back(candidates[i]);
combSum(candidates, target - candidates[i], i + 1, comb, res); // i + 1 because we can consider one element only once
comb.erase(comb.end() - 1); // backtrack
}
}
vector <vector<int>> combinationSum2(vector <int> &candidates, int target) {
vector <vector<int> > res;
vector <int> comb;
sort(candidates.begin(), candidates.end());
combSum(candidates, target, 0, comb, res);
return res;
}
};
// TC: 2^n
// SC: O(n)
class Solution {
public:
void combSum(vector<int>& candidates, int target, int next, vector<int> &comb, set<vector<int> > &resSet ){
if(target==0){
resSet.insert(comb);
return;
} else if(target<0) return;
for(int i=next;i<candidates.size();i++){
comb.push_back(candidates[i]);
combSum(candidates, target-candidates[i], i+1, comb, resSet);
comb.erase(comb.end()-1); // backtrack
}
}
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
vector<vector<int> > res;
set<vector<int> > resSet;
vector<int> comb;
sort(candidates.begin(), candidates.end());
combSum(candidates, target, 0, comb, resSet);
for(auto &x: resSet) res.push_back(x);
return res;
}
};
| 22.342342
| 130
| 0.572984
|
sureshmangs
|
6ff87760e9ee770cccc4d350f1ede176dddb1d5e
| 5,129
|
cpp
|
C++
|
Core/MaquetteGrid/MaquetteGridTabsList.cpp
|
Feldrise/SieloNavigateurBeta
|
faa5fc785271b49d26237a5e9985d6fa22565076
|
[
"MIT"
] | 89
|
2018-04-26T14:28:13.000Z
|
2019-07-03T03:58:17.000Z
|
Core/MaquetteGrid/MaquetteGridTabsList.cpp
|
inviu/webBrowser
|
37b24eded2e168e43b3f9c9ccc0487ee59410332
|
[
"MIT"
] | 51
|
2018-04-26T12:43:00.000Z
|
2019-04-24T20:39:59.000Z
|
Core/MaquetteGrid/MaquetteGridTabsList.cpp
|
inviu/webBrowser
|
37b24eded2e168e43b3f9c9ccc0487ee59410332
|
[
"MIT"
] | 34
|
2018-05-11T07:09:36.000Z
|
2019-04-19T08:12:40.000Z
|
/***********************************************************************************
** MIT License **
** **
** Copyright (c) 2018 Victor DENIS (victordenis01@gmail.com) **
** **
** 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 "MaquetteGridTabsList.hpp"
#include <QMimeData>
#include "Utils/AutoSaver.hpp"
#include "MaquetteGrid/MaquetteGridManager.hpp"
#include "Application.hpp"
namespace Sn
{
MaquetteGridTabsList::MaquetteGridTabsList(MaquetteGridManager* manager, QWidget* parent) :
QListWidget(parent),
m_maquetteGridManager(manager)
{
setObjectName(QLatin1String("maquettegrid-tabslist"));
setMinimumSize(218, 218);
setAcceptDrops(true);
setDragEnabled(true);
setDropIndicatorShown(true);
setDefaultDropAction(Qt::MoveAction);
setDragDropMode(QAbstractItemView::DragDrop);
setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
m_deleteButton = new QPushButton("X", this);
m_deleteButton->setObjectName(QLatin1String("maquettegrid-tabslist-btn-delete-tabsspace"));
m_deleteButton->hide();
m_addTabButton = new QPushButton("+", this);
m_addTabButton->setObjectName(QLatin1String("maquettegrid-tabslist-btn-addtab"));
m_addTabButton->hide();
connect(m_deleteButton, &QPushButton::clicked, this, &MaquetteGridTabsList::deleteItem);
connect(m_addTabButton, &QPushButton::clicked, this, &MaquetteGridTabsList::addTab);
}
MaquetteGridTabsList::~MaquetteGridTabsList()
{
// Empty
}
void MaquetteGridTabsList::setParentLayout(QVBoxLayout* layout)
{
m_parentLayout = layout;
}
TabsSpaceSplitter::SavedTabsSpace MaquetteGridTabsList::tabsSpace()
{
TabsSpaceSplitter::SavedTabsSpace tabsSpace{this};
return tabsSpace;
}
void MaquetteGridTabsList::deleteItem()
{
if (!currentItem())
return;
delete currentItem();
if (count() <= 0)
m_maquetteGridManager->removeTabsSpace(this);
else
m_maquetteGridManager->saver()->changeOccurred();
}
void MaquetteGridTabsList::addTab()
{
QListWidgetItem* newTab{
new QListWidgetItem(Application::getAppIcon("webpage"), QString("%1 (%2)").arg(tr("New Tab")).arg("https://"))
};
newTab->setData(MaquetteGridManager::TitleRole, tr("New Tab"));
newTab->setData(MaquetteGridManager::UrlRole, QUrl("https://"));
addItem(newTab);
m_maquetteGridManager->saver()->changeOccurred();
}
void MaquetteGridTabsList::dropEvent(QDropEvent* event)
{
if (event->dropAction() == Qt::IgnoreAction)
return;
MaquetteGridTabsList* source = qobject_cast<MaquetteGridTabsList*>(event->source());
int count = source->count();
QListWidget::dropEvent(event);
m_maquetteGridManager->saver()->changeOccurred();
if (source->count() <= 1)
m_maquetteGridManager->removeTabsSpace(source);
}
void MaquetteGridTabsList::enterEvent(QEvent* event)
{
m_deleteButton->move(width() - m_deleteButton->width(), 0);
m_addTabButton->move(width() - m_addTabButton->width(), m_deleteButton->height());
m_deleteButton->show();
m_addTabButton->show();
}
void MaquetteGridTabsList::leaveEvent(QEvent* event)
{
m_deleteButton->move(width() - m_deleteButton->width(), 0);
m_addTabButton->move(width() - m_addTabButton->width(), m_deleteButton->height());
m_deleteButton->hide();
m_addTabButton->hide();
}
void MaquetteGridTabsList::keyPressEvent(QKeyEvent* event)
{
if ((event->key() == Qt::Key_Delete || event->key() == Qt::Key_Backspace) && model())
deleteItem();
else
QListWidget::keyPressEvent(event);
}
}
| 34.422819
| 112
| 0.639111
|
Feldrise
|
6ff9d2b4007c3ca544714c1b20eb92ba30df4fc8
| 1,346
|
cpp
|
C++
|
audio/XaDevice.cpp
|
quyse/inanity
|
a39225c5a41f879abe5aa492bb22b500dbe77433
|
[
"MIT"
] | 26
|
2015-04-22T05:25:25.000Z
|
2020-11-15T11:07:56.000Z
|
audio/XaDevice.cpp
|
quyse/inanity
|
a39225c5a41f879abe5aa492bb22b500dbe77433
|
[
"MIT"
] | 2
|
2015-01-05T10:41:27.000Z
|
2015-01-06T20:46:11.000Z
|
audio/XaDevice.cpp
|
quyse/inanity
|
a39225c5a41f879abe5aa492bb22b500dbe77433
|
[
"MIT"
] | 5
|
2016-08-02T11:13:57.000Z
|
2018-10-26T11:19:27.000Z
|
#include "XaDevice.hpp"
#include "XaSystem.hpp"
#include "XaBufferedSound.hpp"
#include "XaStreamedSound.hpp"
#include "Source.hpp"
#include "../File.hpp"
#include "../Exception.hpp"
BEGIN_INANITY_AUDIO
XaDevice::XaDevice(ptr<XaSystem> system, IXAudio2MasteringVoice* voice)
: system(system), voice(voice)
{
if(FAILED(voice->GetChannelMask(&channelMask)))
THROW("Can't get XAudio2 mastering voice channel mask");
XAUDIO2_VOICE_DETAILS details;
voice->GetVoiceDetails(&details);
channelsCount = details.InputChannels;
}
XaDevice::~XaDevice()
{
voice->DestroyVoice();
}
XaSystem* XaDevice::GetSystem() const
{
return system;
}
DWORD XaDevice::GetChannelMask() const
{
return channelMask;
}
uint32_t XaDevice::GetChannelsCount() const
{
return channelsCount;
}
ptr<Sound> XaDevice::CreateBufferedSound(ptr<Source> source)
{
return NEW(XaBufferedSound(this, source->GetFormat(), source->GetData()));
}
ptr<Sound> XaDevice::CreateStreamedSound(ptr<Source> source)
{
return NEW(XaStreamedSound(this, source));
}
void XaDevice::SetListenerPosition(const Math::vec3& position)
{
// not implemented yet
}
void XaDevice::SetListenerOrientation(const Math::vec3& forward, const Math::vec3& up)
{
// not implemented yet
}
void XaDevice::SetListenerVelocity(const Math::vec3& velocity)
{
// not implemented yet
}
END_INANITY_AUDIO
| 19.794118
| 86
| 0.755572
|
quyse
|
6ffb05ca413a62c1cb0c9b5fc326f725599c06e0
| 805
|
hpp
|
C++
|
include/parsers/std_restoration_plan_parser.hpp
|
fhamonic/landscape_opt
|
7f32749336590c8d8b5875300228196a05137267
|
[
"BSL-1.0"
] | 1
|
2021-09-23T11:56:09.000Z
|
2021-09-23T11:56:09.000Z
|
include/parsers/std_restoration_plan_parser.hpp
|
fhamonic/landscape_opt
|
7f32749336590c8d8b5875300228196a05137267
|
[
"BSL-1.0"
] | null | null | null |
include/parsers/std_restoration_plan_parser.hpp
|
fhamonic/landscape_opt
|
7f32749336590c8d8b5875300228196a05137267
|
[
"BSL-1.0"
] | 1
|
2022-03-27T16:58:19.000Z
|
2022-03-27T16:58:19.000Z
|
#ifndef STD_RESTORATION_PLAN_PARSER_HPP
#define STD_RESTORATION_PLAN_PARSER_HPP
#include <fstream>
#include <iostream>
#include "parsers/concept/parser.hpp"
#include "solvers/concept/restoration_plan.hpp"
#include "landscape/mutable_landscape.hpp"
class StdRestorationPlanParser
: public concepts::Parser<RestorationPlan<MutableLandscape>> {
private:
const MutableLandscape & landscape;
public:
StdRestorationPlanParser(const MutableLandscape & l);
~StdRestorationPlanParser();
RestorationPlan<MutableLandscape> parse(std::filesystem::path file_path);
bool write(const RestorationPlan<MutableLandscape> & plan,
const std::filesystem::path output, const std::string name,
bool use_range_ids = true);
};
#endif // STD_RESTORATION_PLAN_PARSER_HPP
| 29.814815
| 77
| 0.765217
|
fhamonic
|
6ffcc979caaf76ecad0985ac2ce959d43b5e53da
| 101
|
cpp
|
C++
|
App/main.cpp
|
frinkr/FontViewer
|
69b5706e557ecd33515c5c8d6ba8fc1d6f06e0c0
|
[
"MIT"
] | 2
|
2019-05-08T06:31:34.000Z
|
2020-08-30T00:35:09.000Z
|
App/main.cpp
|
frinkr/FontViewer
|
69b5706e557ecd33515c5c8d6ba8fc1d6f06e0c0
|
[
"MIT"
] | 1
|
2018-05-07T09:29:02.000Z
|
2018-05-07T09:29:02.000Z
|
App/main.cpp
|
frinkr/FontViewer
|
69b5706e557ecd33515c5c8d6ba8fc1d6f06e0c0
|
[
"MIT"
] | 2
|
2018-09-10T07:16:28.000Z
|
2022-01-07T06:41:01.000Z
|
#include "UI-Qt/QXMain.h"
int main(int argc, char *argv[])
{
return qxMain(argc, argv);
}
| 14.428571
| 33
| 0.594059
|
frinkr
|
6ffceefa6e7803ed93b15517ee87ea64714a6c48
| 1,112
|
hpp
|
C++
|
src/rage/RageVector4.hpp
|
MidflightDigital/stepmania
|
dbce5016978e5ab51aaa6a4fb21ef2c7ce68e52e
|
[
"MIT"
] | 7
|
2019-01-06T01:09:55.000Z
|
2021-01-21T00:00:19.000Z
|
src/rage/RageVector4.hpp
|
MidflightDigital/stepmania
|
dbce5016978e5ab51aaa6a4fb21ef2c7ce68e52e
|
[
"MIT"
] | 6
|
2020-07-29T17:45:36.000Z
|
2020-07-29T18:48:03.000Z
|
src/rage/RageVector4.hpp
|
MidflightDigital/stepmania
|
dbce5016978e5ab51aaa6a4fb21ef2c7ce68e52e
|
[
"MIT"
] | 5
|
2019-01-06T01:48:34.000Z
|
2021-11-25T21:19:07.000Z
|
#ifndef RAGE_VECTOR_4_HPP_
#define RAGE_VECTOR_4_HPP_
#include "RageMatrix.hpp"
namespace Rage
{
struct Vector4
{
public:
Vector4();
Vector4(float a, float b, float c, float d);
// assignment operators
Vector4& operator += (Vector4 const & rhs);
Vector4& operator -= (Vector4 const & rhs);
Vector4& operator *= (float rhs);
Vector4& operator /= (float rhs);
/** @brief Transform the coordinates into a new vector. */
Vector4 TransformCoords(Matrix const &mat) const;
float x, y, z, w;
};
inline bool operator==(Vector4 const & lhs, Vector4 const & rhs)
{
return
lhs.x == rhs.x &&
lhs.y == rhs.y &&
lhs.z == rhs.z &&
lhs.w == rhs.w;
}
inline bool operator!=(Vector4 const & lhs, Vector4 const & rhs)
{
return !operator==(lhs, rhs);
}
inline Vector4 operator+(Vector4 lhs, Vector4 const & rhs)
{
lhs += rhs;
return lhs;
}
inline Vector4 operator-(Vector4 lhs, Vector4 const & rhs)
{
lhs -= rhs;
return lhs;
}
inline Vector4 operator*(Vector4 lhs, float rhs)
{
lhs *= rhs;
return lhs;
}
inline Vector4 operator/(Vector4 lhs, float rhs)
{
lhs /= rhs;
return lhs;
}
}
#endif
| 16.848485
| 64
| 0.669065
|
MidflightDigital
|
6fff743f52037428515a9c7466ba20d88e6416d6
| 882
|
cpp
|
C++
|
old application/application/src/ReSyLib/periphery/actor/servo.cpp
|
deeply-embedded/Servo
|
606b13cd079337dd5bba50827b623561fc578cae
|
[
"CC0-1.0"
] | null | null | null |
old application/application/src/ReSyLib/periphery/actor/servo.cpp
|
deeply-embedded/Servo
|
606b13cd079337dd5bba50827b623561fc578cae
|
[
"CC0-1.0"
] | null | null | null |
old application/application/src/ReSyLib/periphery/actor/servo.cpp
|
deeply-embedded/Servo
|
606b13cd079337dd5bba50827b623561fc578cae
|
[
"CC0-1.0"
] | 1
|
2021-04-25T18:26:05.000Z
|
2021-04-25T18:26:05.000Z
|
/*
* servo.cpp
*
* @date 26.10.2015
* @author Yannic, Moritz
*/
#include "../../GPIO.h"
#include "../../GPIO_PWM.h"
#include "../../HWManager.h"
#include "./Servo.h"
namespace RSL {
using namespace RSL_core;
Servo::Servo(GPIOPin servoPin) {
currentPosition = 0;
this->servoPin = move(unique_ptr<GPIO_PWM>(static_cast<GPIO_PWM*>(HWManager::getInstance().createGPIOResource(PWM,servoPin).release())));
}
Servo::~Servo() {
// todo use interfaces for unregister servo
// todo release pin stuff (set to default settings)
}
double Servo::getPosition(void) {
return currentPosition;
}
void Servo::setPosition(double position) {
currentPosition = position;
// todo check for min max value
servoPin->setDuty(1000000 + (1000000 * position));
}
void Servo::enableServo() {
servoPin->enablePWM();
}
void Servo::disableServo() {
servoPin->disablePWM();
}
}
| 18
| 138
| 0.684807
|
deeply-embedded
|
b50f9b098e9f566843e4ae8a82a24d6b0757046f
| 15,776
|
cpp
|
C++
|
src/cpp/IdpRouter.cpp
|
VitalElement/IdpProtocol
|
323531da023d853ddb59794d225fb7e39c0a6943
|
[
"MIT"
] | 2
|
2018-10-02T19:06:41.000Z
|
2019-03-14T02:20:08.000Z
|
src/cpp/IdpRouter.cpp
|
VitalElement/IdpProtocol
|
323531da023d853ddb59794d225fb7e39c0a6943
|
[
"MIT"
] | null | null | null |
src/cpp/IdpRouter.cpp
|
VitalElement/IdpProtocol
|
323531da023d853ddb59794d225fb7e39c0a6943
|
[
"MIT"
] | null | null | null |
// Copyright (c) VitalElement. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for
// full license information.
#include "IdpRouter.h"
#include "Trace.h"
#include <algorithm>
static constexpr uint16_t AdaptorNone = 0xFFFF;
IdpRouter::IdpRouter () : IdpNode (RouterGuid, "Network.Router")
{
_currentlyEnumeratingAdaptor = nullptr;
_lastAdaptorId = -1;
Manager ().RegisterCommand (
static_cast<uint16_t> (NodeCommand::RouterPoll),
[&](std::shared_ptr<IncomingTransaction> incoming,
std::shared_ptr<OutgoingTransaction> outgoing) {
return IdpResponseCode::OK;
});
Manager ().RegisterCommand (
static_cast<uint16_t> (NodeCommand::RouterDetect),
[&](std::shared_ptr<IncomingTransaction> incoming,
std::shared_ptr<OutgoingTransaction> outgoing) {
auto address = incoming->Read<uint16_t> ();
if (this->Address () == UnassignedAddress)
{
this->Address (address);
outgoing->Write (true);
outgoing->WithResponseCode (IdpResponseCode::OK);
IdpNode::SendRequest (incoming->Source (), outgoing);
return ::IdpResponseCode::Deferred;
}
else
{
outgoing->Write (false);
return IdpResponseCode::OK;
}
});
Manager ().RegisterCommand (
static_cast<uint16_t> (NodeCommand::RouterEnumerateNode),
[&](std::shared_ptr<IncomingTransaction> incoming,
std::shared_ptr<OutgoingTransaction> outgoing) {
auto address = incoming->Read<uint16_t> ();
return this->HandleEnumerateNodesCommand (incoming->Source (),
address, outgoing);
});
Manager ().RegisterCommand (
static_cast<uint16_t> (NodeCommand::RouterEnumerateAdaptor),
[&](std::shared_ptr<IncomingTransaction> incoming,
std::shared_ptr<OutgoingTransaction> outgoing) {
auto address = incoming->Read<uint16_t> ();
auto transactionId = incoming->Read<uint32_t> ();
return this->HandleEnumerateAdaptorCommand (
incoming->Source (), address, transactionId, outgoing);
});
Manager ().RegisterCommand (
static_cast<uint16_t> (NodeCommand::RouterPrepareToEnumerateAdaptors),
[&](std::shared_ptr<IncomingTransaction> incoming,
std::shared_ptr<OutgoingTransaction> outgoing) {
auto it = _adaptors.begin ();
while (it != _adaptors.end ())
{
it->second->IsReEnumerated (false);
it++;
}
return IdpResponseCode::OK;
});
Manager ().RegisterCommand (
static_cast<uint16_t> (NodeCommand::MarkAdaptorConnected),
[&](std::shared_ptr<IncomingTransaction> incoming,
std::shared_ptr<OutgoingTransaction> outgoing) {
if (_currentlyEnumeratingAdaptor != nullptr)
{
_currentlyEnumeratingAdaptor->IsEnumerated (true);
_currentlyEnumeratingAdaptor = nullptr;
}
else if (_lastAdaptorId != -1)
{
_adaptors[_lastAdaptorId]->IsEnumerated (true);
_lastAdaptorId = -1;
}
return IdpResponseCode::OK;
});
// Routers endpoint is themselves, routing tables will find the correct
// adaptor.
TransmitEndpoint (*this);
_nextAdaptorId = 1;
}
IdpRouter::~IdpRouter ()
{
}
void IdpRouter::OnPollTimerTick ()
{
IdpNode::OnPollTimerTick ();
auto it1 = _adaptors.begin ();
while (it1 != _adaptors.end ())
{
if (it1->second->IsEnumerated ())
{
auto outgoingTransaction = OutgoingTransaction ::Create (
static_cast<uint16_t> (NodeCommand::RouterPoll),
this->CreateTransactionId ());
auto adaptor = it1->second;
auto handler = [&, adaptor](std::shared_ptr<IdpResponse> response) {
if (response != nullptr &&
response->ResponseCode () == IdpResponseCode::OK)
{
}
else
{
adaptor->IsEnumerated (false);
}
};
Manager ().RegisterOneTimeResponseHandler (
outgoingTransaction->TransactionId (), handler);
auto result = it1->second->Transmit (
outgoingTransaction->ToPacket (Address (), RouterPollAddress));
if (!result)
{
Manager ().UnregisterOneTimeResponseHandler (
outgoingTransaction->TransactionId ());
it1->second->IsEnumerated (false);
Trace::WriteLine ("Failed to router ping");
}
}
it1++;
}
}
void IdpRouter::OnReset ()
{
auto it = _enumeratedNodes.begin ();
while (it != _enumeratedNodes.end ())
{
if (it->second->Address () != 0x0001)
{
MarkUnenumerated (*it->second);
it = _enumeratedNodes.erase (it);
}
else
{
it++;
}
}
auto it1 = _adaptors.begin ();
while (it1 != _adaptors.end ())
{
it1->second->IsEnumerated (false);
it1++;
}
IdpNode::OnReset ();
}
bool IdpRouter::SendRequest (IPacketTransmit& adaptor, uint16_t source,
uint16_t destination,
std::shared_ptr<OutgoingTransaction> request)
{
return adaptor.Transmit (request->ToPacket (source, destination));
}
IdpNode* IdpRouter::FindNode (uint16_t address)
{
auto it = _enumeratedNodes.find (address);
if (it != _enumeratedNodes.end ())
{
return _enumeratedNodes[address];
}
return nullptr;
}
bool IdpRouter::AddAdaptor (IAdaptor& adaptor)
{
adaptor.SetLocal (*this);
adaptor.AdaptorId (_nextAdaptorId); // TODO assign unique id.
_adaptors[_nextAdaptorId] = &adaptor;
_nextAdaptorId++;
return true;
}
bool IdpRouter::AddNode (IdpNode& node)
{
bool result = false;
if (node.Address () == UnassignedAddress)
{
_unenumeratedNodes.push_front (&node);
result = true;
}
else
{
auto existing = FindNode (node.Address ());
if (existing == nullptr)
{
_enumeratedNodes[node.Address ()] = &node;
result = true;
}
}
if (result)
{
node.TransmitEndpoint (*this);
}
node.Enabled (true);
return result;
}
void IdpRouter::RemoveNode (IdpNode& node)
{
if (node.Address () == UnassignedAddress)
{
_unenumeratedNodes.remove (&node);
}
else if (FindNode (node.Address ()) != nullptr)
{
auto it = _enumeratedNodes.find (node.Address ());
if (it != _enumeratedNodes.end ())
{
_enumeratedNodes.erase (it);
}
}
node.Address (UnassignedAddress);
}
bool IdpRouter::MarkEnumerated (IdpNode& node)
{
bool result = false;
if (FindNode (node.Address ()) == nullptr)
{
auto it = std::find (_unenumeratedNodes.begin (),
_unenumeratedNodes.end (), &node);
if (it != _unenumeratedNodes.end ())
{
_unenumeratedNodes.erase (it);
}
_enumeratedNodes[node.Address ()] = &node;
result = true;
}
return result;
}
void IdpRouter::MarkUnenumerated (IdpNode& node)
{
auto it = std::find (_unenumeratedNodes.begin (), _unenumeratedNodes.end (),
&node);
if (it == _unenumeratedNodes.end ())
{
_unenumeratedNodes.push_front (&node);
}
}
bool IdpRouter::Transmit (std::shared_ptr<IdpPacket> packet)
{
return Transmit (AdaptorNone, packet);
}
IdpResponseCode IdpRouter::HandleEnumerateNodesCommand (
uint16_t source, uint16_t address,
std::shared_ptr<OutgoingTransaction> outgoing)
{
auto it = _enumeratedNodes.begin ();
while (it != _enumeratedNodes.end ())
{
if (it->second->Address () == UnassignedAddress)
{
MarkUnenumerated (*it->second);
it = _enumeratedNodes.erase (it);
}
else
{
it++;
}
}
if (!_unenumeratedNodes.empty ())
{
auto& node = *_unenumeratedNodes.back ();
node.Address (address);
if (MarkEnumerated (node))
{
outgoing->Write (true);
outgoing->WithResponseCode (IdpResponseCode::OK);
IdpNode::SendRequest (address, source, outgoing);
return IdpResponseCode::Deferred;
}
else
{
node.Address (UnassignedAddress);
outgoing->Write (false);
return IdpResponseCode::InvalidParameters;
}
}
else
{
outgoing->Write (false);
}
return IdpResponseCode::OK;
}
IdpResponseCode IdpRouter::HandleEnumerateAdaptorCommand (
uint16_t source, uint16_t address, uint32_t transcationId,
std::shared_ptr<OutgoingTransaction> outgoing)
{
auto adaptor = GetNextUnenumeratedAdaptor (true);
if (adaptor == nullptr)
{
/*Trace::WriteLine ("No Adaptor found on Router: %u", "IdpRouter",
Address ());*/
outgoing->Write (false);
return IdpResponseCode::OK;
}
else
{
adaptor->IsReEnumerated (true);
auto outgoingTransaction =
OutgoingTransaction::Create (
static_cast<uint16_t> (NodeCommand::RouterDetect),
transcationId, IdpCommandFlags::None)
->Write (address);
bool adaptorSent = false;
if (!adaptor->IsEnumerated ())
{
adaptorSent =
SendRequest (*adaptor, source, 0xFFFF, outgoingTransaction);
if (adaptorSent)
{
_currentlyEnumeratingAdaptor = adaptor;
}
}
/*Trace::WriteLine ("Adaptor (%s) found on Router: %u, active: %s",
"IdpRouter", adaptor->Name (), Address (),
adaptor->IsEnumerated () ? "true" : "false");*/
outgoing->Write (true)
->Write (adaptorSent)
->WithResponseCode (IdpResponseCode::OK);
IdpNode::SendRequest (source, outgoing);
return IdpResponseCode::Deferred;
}
}
IAdaptor* IdpRouter::GetNextUnenumeratedAdaptor (bool reenumeration)
{
auto it = _adaptors.begin ();
while (it != _adaptors.end ())
{
if (reenumeration && !it->second->IsReEnumerated ())
{
break;
}
if (!reenumeration && !it->second->IsEnumerated ())
{
break;
}
it++;
}
if (it != _adaptors.end ())
{
return it->second;
}
return nullptr;
}
bool IdpRouter::Transmit (uint16_t adaptorId, std::shared_ptr<IdpPacket> packet)
{
auto source = packet->Source ();
if (source != UnassignedAddress && adaptorId != 0xFFFF)
{
_lastAdaptorId = adaptorId;
if (!(source == 1 &&
_routingTable.find (source) != _routingTable.end ()))
{
_routingTable[source] =
adaptorId; // replace any existing route with
// the one the packet just came from.
}
}
return Route (packet);
}
bool IdpRouter::Route (std::shared_ptr<IdpPacket> packet)
{
auto source = packet->Source ();
if (source == UnassignedAddress)
{
return false;
}
auto destination = packet->Destination ();
/* packet->ResetReadToPayload ();
auto command = packet->Read<uint16_t> ();
auto transactionId = packet->Read<uint32_t> ();
packet->Read<uint8_t> ();
// if ((source == 1 && destination >= 10) ||
// (destination == 1 && source >= 10))
// if (command == 0xa006)
// if (source >= 9 || destination >= 9)
{
if (command == (uint16_t) NodeCommand::Response)
{
packet->Read<uint8_t> ();
auto response = packet->Read<uint16_t> ();
Trace::Write (
"R:0x%04x S:0x%04x D:0x%04x "
"C:0x%04x I:0x%04x<%s ",
"IdpRouter", Address (), source, destination, command,
transactionId,
IdpNode::GetNodeCommandDescription ((NodeCommand) response));
}
else
{
Trace::Write (
"R:0x%04x S:0x%04x D:0x%04x "
"C:0x%04x I:0x%04x>%s ",
"IdpRouter", Address (), source, destination, command,
transactionId,
IdpNode::GetNodeCommandDescription ((NodeCommand) command));
}
if (packet->Length () <= 32)
{
Trace::AppendBuffer (packet->Data (), packet->Length ());
}
Trace::AppendLine ("");
}*/
packet->ResetRead ();
if (destination == 0)
{
auto ait = _adaptors.begin ();
auto receivedOn = _routingTable.find (source);
while (ait != _adaptors.end ())
{
if (receivedOn == _routingTable.end () ||
ait->second != _adaptors[receivedOn->second])
{
packet->ResetRead ();
ait->second->Transmit (packet);
}
ait++;
}
auto it = _enumeratedNodes.begin ();
while (it != _enumeratedNodes.end ())
{
packet->ResetRead ();
auto response = it->second->ProcessPacket (packet);
if (response != nullptr)
{
Route (response);
}
it++;
}
packet->ResetRead ();
auto response = ProcessPacket (packet);
if (response != nullptr)
{
Route (response);
}
return true;
}
else if (destination == RouterPollAddress &&
Address () != UnassignedAddress)
{
auto response = ProcessPacket (packet);
if (response != nullptr)
{
return Route (response);
}
return false;
}
else
{
IdpNode* node = nullptr;
if (destination == Address ())
{
node = this;
}
else if (Address () != UnassignedAddress)
{
node = FindNode (packet->Destination ());
}
if (node != nullptr)
{
auto responsePacket = node->ProcessPacket (packet);
if (responsePacket != nullptr)
{
return Route (responsePacket);
}
return true;
}
else
{
auto it = _routingTable.find (destination);
if (it != _routingTable.end ())
{
auto receivedOn = _routingTable.find (source);
if (receivedOn != it) // not sure if this is correct.
{
return _adaptors[it->second]->Transmit (packet);
}
}
else if (destination != UnassignedAddress)
{
// Probably safe to assume that we should transmit in same
// route as master?
Trace::WriteLine ("Packet Dropped: Unknown Route", "IdpRouter");
return false;
}
}
}
Trace::WriteLine ("Route Failed", "IdpRouter");
return false;
}
| 25.363344
| 80
| 0.532961
|
VitalElement
|
b510d0a4baa3254512143d4c07ab1e834f345756
| 2,887
|
hpp
|
C++
|
vlite/unary_expr_vector.hpp
|
verri/vlite
|
c4677dad17070b8fb0cbabd06018b3bcbb162860
|
[
"Zlib"
] | null | null | null |
vlite/unary_expr_vector.hpp
|
verri/vlite
|
c4677dad17070b8fb0cbabd06018b3bcbb162860
|
[
"Zlib"
] | null | null | null |
vlite/unary_expr_vector.hpp
|
verri/vlite
|
c4677dad17070b8fb0cbabd06018b3bcbb162860
|
[
"Zlib"
] | null | null | null |
#ifndef VLITE_UNARY_EXPR_VECTOR_HPP_INCLUDED
#define VLITE_UNARY_EXPR_VECTOR_HPP_INCLUDED
#include <vlite/common_vector_base.hpp>
#include <vlite/expr_vector.hpp>
#include <iterator>
namespace vlite
{
template <typename It, typename Op>
class unary_expr_vector : public expr_vector<Op>,
public common_vector_base<unary_expr_vector<It, Op>>
{
using iterator_result = decltype(*std::declval<It>());
public:
using value_type = std::decay_t<std::result_of_t<Op(iterator_result)>>;
using typename expr_vector<Op>::size_type;
using typename expr_vector<Op>::difference_type;
class iterator
{
friend class unary_expr_vector<It, Op>;
public:
using iterator_category = std::input_iterator_tag;
using value_type = std::decay_t<std::result_of_t<Op(iterator_result)>>;
using difference_type = std::ptrdiff_t;
using reference = void;
using pointer = void;
constexpr iterator() = default;
constexpr iterator(const iterator& source) = default;
constexpr iterator(iterator&& source) noexcept = default;
constexpr iterator& operator=(const iterator& source) = default;
constexpr iterator& operator=(iterator&& source) noexcept = default;
constexpr auto operator++() -> iterator&
{
++it_;
return *this;
}
constexpr auto operator++(int) -> iterator
{
auto copy = *this;
++(*this);
return copy;
}
constexpr auto operator==(const iterator& other) const { return it_ == other.it_; }
constexpr auto operator!=(const iterator& other) const { return !(*this == other); }
constexpr auto operator*() const -> value_type { return source_->operate(*it_); }
private:
constexpr iterator(It it, const unary_expr_vector* source)
: it_{it}
, source_{source}
{
}
It it_;
const unary_expr_vector* source_;
};
using const_iterator = iterator;
public:
unary_expr_vector(It it_first, It it_last, Op op, std::size_t size)
: expr_vector<Op>(std::move(op), size)
, it_first_{it_first}
, it_last_{it_last}
{
}
unary_expr_vector(const unary_expr_vector& source) = delete;
unary_expr_vector(unary_expr_vector&& source) noexcept = delete;
auto operator=(const unary_expr_vector& source) -> unary_expr_vector& = delete;
auto operator=(unary_expr_vector&& source) noexcept -> unary_expr_vector& = delete;
auto begin() const -> const_iterator { return cbegin(); }
auto end() const -> const_iterator { return cend(); }
auto cbegin() const -> iterator { return {it_first_, this}; }
auto cend() const -> iterator { return {it_last_, this}; }
using expr_vector<Op>::size;
private:
It it_first_, it_last_;
};
template <typename It, typename Op>
unary_expr_vector(It, It, Op, std::size_t)->unary_expr_vector<It, Op>;
} // namespace vlite
#endif // VLITE_UNARY_EXPR_VECTOR_HPP_INCLUDED
| 26.486239
| 88
| 0.694146
|
verri
|
b5123bacd97fe3c650cce1e935f920257fedf47f
| 4,742
|
cpp
|
C++
|
naive_sol/sensornode.cpp
|
acse-qq219/Optimal_Drone_Recharging_Scheduling
|
6c86a0bc7dd835f30eb70b108365bcf762ecc228
|
[
"MIT"
] | 1
|
2022-03-06T15:27:17.000Z
|
2022-03-06T15:27:17.000Z
|
naive_sol/sensornode.cpp
|
acse-qq219/Optimal_Drone_Recharging_Scheduling
|
6c86a0bc7dd835f30eb70b108365bcf762ecc228
|
[
"MIT"
] | null | null | null |
naive_sol/sensornode.cpp
|
acse-qq219/Optimal_Drone_Recharging_Scheduling
|
6c86a0bc7dd835f30eb70b108365bcf762ecc228
|
[
"MIT"
] | null | null | null |
/*! @file sensornode.cpp
*
* @warning This is the internal source of the ODP project.
* Do not use it directly in other code. Please note that this file
* is based on the open source code from
* <a href="https://github.com/achu6393/dynamicWeightedClustering">
* dynamicWeightedClustering
* </a>
* Copyright (C) Qiuchen Qian, 2020
* Imperial College, London
*/
#include <iostream>
#include <algorithm>
#include "sensornode.h"
template <class T>
SensorNode<T>::SensorNode() {
this->pos = Point<T>();
this->SC_V = 3.4;
this->SC_E = 17.34;
this->weight = 10;
this->fails = 0;
this->p_sensor_type = true;
}
template <class T>
SensorNode<T>::SensorNode(float x, float y, double v, int w, bool p_type) {
// Common public member variables
this->pos = Point<T>(x, y);
this->SC_V = v;
this->weight = w;
this->p_sensor_type = p_type;
this->sense_cycle = 2e-3;
this->comm_cycle = 0.5;
this->fails = 0;
if (p_type) {
//! Specific public member variables
this->SC_C = 3;
this->time_to_change = 1;
this->time_to_reset = 1;
//! Protected member variables
this->SC_Vmax = 5.;
this->SC_Vmin = 3.5;
this->SC_Vcritical = 3.3;
this->V_sense = 3.3;
this->I_sense = 1.2e-3;
this->I_idle = 4e-6;
this->idle_cycle = 9.498;
}
else {
//! Public member variables
this->SC_C = 6;
this->time_to_change = 10;
this->time_to_reset = 10;
//! Protected member variables
this->SC_Vmax = 2.5;
this->SC_Vmin = 1.75;
this->SC_Vcritical = 1.5;
this->V_sense = 1.5;
this->I_sense = 5.4e-6;
this->I_idle = 4e-9;
this->idle_cycle = 99.498;
}
this->SC_E = 0.5 * this->SC_C * this->SC_V * this->SC_V;
}
template <class T>
SensorNode<T>::~SensorNode() {}
template <class T>
void SensorNode<T>::updateVolt(double& v) {
double temp_v = 2 * this->SC_E / this->SC_C;
v = sqrt(temp_v);
}
template <class T>
void SensorNode<T>::updateEnergy(double& e) {
e = 0.5 * this->SC_C * this->SC_V * this->SC_V;
}
template <class T>
void SensorNode<T>::updateEnergy(const double& t, double& e) {
// t - unit: s
int cycles = static_cast<int>(floor(t / (3 * this->time_to_reset)));
e -= (cycles * this->sense_cycle * this->V_sense * this->I_sense
+ cycles * this->idle_cycle * this->I_idle * this->V_sense
+ cycles * this->comm_cycle * 2.45e-3);
}
template <class T>
void SensorNode<T>::updateWeight(const double& v, int& w) {
if (this->SC_Vmax - v <= 0.25) w = 10; /*!< Be considered as full voltage */
else if (this->SC_Vmax - v > 0.25 && this->SC_Vmax - v <= 0.5) w = 9;
else if (this->SC_Vmax - v > 0.5 && this->SC_Vmax - v <= 0.75) w = 8;
else if (this->SC_Vmax - v > 0.75 && this->SC_Vmax - v <= 1.) w = 7;
else if (this->SC_Vmax - v > 1. && this->SC_Vmax - v <= 1.25) w = 6;
else if (this->SC_Vmax - v > 1.25 && this->SC_Vmax - v <= 1.5) w = 5;
else if (this->SC_Vmax - v > 1.5 && this->SC_Vmax - v <= 1.75) w = 4;
else w = 3; /*!< Be considered as the lowest voltage */
}
template <class T>
double SensorNode<T>::acousTransfer(const double& d) {
//! Acoustic frequency is 4.75 kHz, the unit of d is meter.
double g_coeff = exp(-1. * pow(2 * PI * 47500, EFF_ACOUS) * d * ALPHA_MAT);
double temp_e = EFF_PIEZO * EFF_PIEZO * EFF_ACOUS2DC * g_coeff * ACOUS_ENERGY_SEND;
this->SC_E += temp_e;
this->updateVolt(this->SC_V);
//! Total voltage cannot exceed the maximum voltage level.
this->SC_V = std::min(this->SC_V, this->SC_Vmax);
return temp_e;
}
template <class T>
void SensorNode<T>::printSensorNodeInfo() {
this->pos.printPointLoc();
std::cout << "Sensor Node Information:" << std::endl << std::endl
<< "Capacitance: \t" << this->SC_C << " F" << std::endl
<< "Capacitor Energy: \t" << this->SC_E << " J" << std::endl
<< "Capacitor Voltage: \t" << this->SC_E << " V" << std::endl
<< "Weight: \t" << this->weight << std::endl
<< "T: \t" << this->time_to_change << " s" << std::endl
<< "Original T: \t" << this->time_to_reset << " s" << std::endl
<< "Fail times: \t" << this->fails << std::endl
<< "P sensor type? \t" << this->time_to_reset << std::endl
<< "Maximum Voltage: \t" << this->SC_Vmax << " V" << std::endl
<< "Minimum Voltage: \t" << this->SC_Vmin << " V" << std::endl
<< "Critical Voltage: \t" << this->SC_Vcritical << " V" << std::endl
<< "Current Voltage: \t" << this->SC_V << " V" << std::endl
<< "Sense Voltage: \t" << this->V_sense << " V" << std::endl
<< "Sense Current: \t" << this->I_sense << " A" << std::endl
<< "Idle Current: \t" << this->I_idle << " A" << std::endl
<< "Sense cycle duration: \t" << this->sense_cycle << " s" << std::endl
<< "Idle cycle duration: \t" << this->idle_cycle << " s" << std::endl
<< "Communication cycle duration: \t" << this->comm_cycle << " s" << std::endl
<< std::endl;
}
| 32.479452
| 84
| 0.613454
|
acse-qq219
|
b51a8f1adb0f5acbf5cfb94ec3226c522b8c0722
| 874
|
cpp
|
C++
|
P1/b.cpp
|
SsorryQaQ/Algorithm-competition
|
ee2ed79438ecaf15015d9b043d3e099cfa3829c5
|
[
"MIT"
] | 1
|
2019-12-01T01:37:56.000Z
|
2019-12-01T01:37:56.000Z
|
P1/b.cpp
|
SsorryQaQ/Algorithm-competition
|
ee2ed79438ecaf15015d9b043d3e099cfa3829c5
|
[
"MIT"
] | null | null | null |
P1/b.cpp
|
SsorryQaQ/Algorithm-competition
|
ee2ed79438ecaf15015d9b043d3e099cfa3829c5
|
[
"MIT"
] | null | null | null |
#include <cstdio>
#include <iostream>
#include <vector>
using namespace std;
const int maxn = 30000 + 10;
const int maxm = 500 + 10;
int fa[maxn];
void init_union(int n){
for (int i=0;i<n;i++) fa[i] = i;
}
int find(int x){
if (fa[x]==x) return fa[x];
return fa[x] = find(fa[x]);
}
// int find(int x){
// if (x!=fa[x]) fa[x] = find(fa[x]);
// return fa[x];
// }
void union_union(int x,int y){
x = find(x); y = find(y);
if (x!=y) fa[x] = y;
}
int n,m,k;
int main(){
while (~scanf("%d%d",&n,&m)&&n){
init_union(n);
int x1; int x;
for (int j=0;j<m;j++){
scanf("%d",&k);
for (int i=0;i<k;i++){
if (i==0) scanf("%d",&x1);
else{
scanf("%d",&x);
union_union(x,x1);
}
}
}
int cnt = 0;
for (int i=0;i<n;i++) {find(i)==find(0)?cnt++:cnt;}
cout << cnt << endl;
}
}
| 19
| 56
| 0.475973
|
SsorryQaQ
|
dde22cdfbbd3a7aeaa6e8b4f0934ce03087ae490
| 76,933
|
cpp
|
C++
|
daemon/src/vpn.cpp
|
realrasengan/desktop
|
41213ed9efd70955bdd5872c68425868040afae2
|
[
"Apache-2.0"
] | 1
|
2020-09-08T00:41:27.000Z
|
2020-09-08T00:41:27.000Z
|
daemon/src/vpn.cpp
|
realrasengan/desktop
|
41213ed9efd70955bdd5872c68425868040afae2
|
[
"Apache-2.0"
] | null | null | null |
daemon/src/vpn.cpp
|
realrasengan/desktop
|
41213ed9efd70955bdd5872c68425868040afae2
|
[
"Apache-2.0"
] | null | null | null |
// Copyright (c) 2019 London Trust Media Incorporated
//
// This file is part of the Private Internet Access Desktop Client.
//
// The Private Internet Access Desktop Client is free software: you can
// redistribute it and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation, either version 3 of
// the License, or (at your option) any later version.
//
// The Private Internet Access Desktop Client is distributed in the hope that
// it will be useful, but WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with the Private Internet Access Desktop Client. If not, see
// <https://www.gnu.org/licenses/>.
#include "common.h"
#line SOURCE_FILE("connection.cpp")
#include "vpn.h"
#include "daemon.h"
#include "path.h"
#include "brand.h"
#include <QFile>
#include <QTextStream>
#include <QTcpSocket>
#include <QTimer>
#include <QHostInfo>
#include <QRandomGenerator>
// For use by findInterfaceIp on Mac/Linux
#ifdef Q_OS_UNIX
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <unistd.h>
#endif
// List of settings which require a reconnection.
static std::initializer_list<const char*> g_connectionSettingNames = {
"location",
"protocol",
"remotePortUDP",
"remotePortTCP",
"localPort",
"automaticTransport",
"cipher",
"auth",
"serverCertificate",
"overrideDNS",
"routeDefault",
"blockIPv6",
"mtu",
"enableMACE",
"windowsIpMethod",
"proxy",
"proxyCustom",
"proxyShadowsocksLocation"
};
namespace
{
// Maximum number of measurements in _intervalMeasurements
const std::size_t g_maxMeasurementIntervals{32};
// This seed is run by PIA Ops, this is used in addition to hnsd's
// hard-coded seeds. It has a static IP address but it's also resolvable
// as hsd.londontrustmedia.com.
//
// The base32 blob is a public key used to authenticate the node.
const QString hnsdSeed = QStringLiteral("aixqwzdsxogyjqwxjtdm27pqv7d23wkxi4tynqcfnqgpefsmbemj2@209.95.51.184");
// This seed is run by HNScan.
const QString hnscanSeed = QStringLiteral("ak2hy7feae2o5pfzsdzw3cxkxsu3lxypykcl6iphnup4adf2ply6a@138.68.61.31");
// Arguments for hnsd
const QStringList &hnsdArgs{"-n", hnsdLocalAddress + ":1053",
"-r", hnsdLocalAddress + ":53",
"--seeds", hnsdSeed + "," + hnscanSeed};
// Restart strategy for hnsd
const RestartStrategy::Params hnsdRestart{std::chrono::milliseconds(100), // Min restart delay
std::chrono::seconds(3), // Max restart delay
std::chrono::seconds(30)}; // Min "successful" run time
// Restart strategy for shadowsocks
const RestartStrategy::Params shadowsocksRestart{std::chrono::milliseconds(100),
std::chrono::seconds(5),
std::chrono::seconds(5)};
// Sync timeout for hnsd. This should be shorter than the "successful" time
// in the RestartStrategy, so the warning doesn't flap if hnsd fails for a
// while, then starts up, but fails to sync.
const std::chrono::seconds hnsdSyncTimeout{5};
// Timeout for preferred transport before starting to try alternate transports
const std::chrono::seconds preferredTransportTimeout{30};
// All IPv4 LAN and loopback subnets
using SubnetPair = QPair<QHostAddress, int>;
std::array<SubnetPair, 5> ipv4LocalSubnets{
QHostAddress::parseSubnet(QStringLiteral("192.168.0.0/16")),
QHostAddress::parseSubnet(QStringLiteral("172.16.0.0/12")),
QHostAddress::parseSubnet(QStringLiteral("10.0.0.0/8")),
QHostAddress::parseSubnet(QStringLiteral("169.254.0.0/16")),
QHostAddress::parseSubnet(QStringLiteral("127.0.0.0/8"))
};
// Test if an address is an IPv4 LAN or loopback address
bool isIpv4Local(const QHostAddress &addr)
{
return std::any_of(ipv4LocalSubnets.begin(), ipv4LocalSubnets.end(),
[&](const SubnetPair &subnet) {return addr.isInSubnet(subnet);});
}
}
HnsdRunner::HnsdRunner(RestartStrategy::Params restartParams)
: ProcessRunner{std::move(restartParams)}
{
setObjectName(QStringLiteral("hnsd"));
_hnsdSyncTimer.setSingleShot(true);
_hnsdSyncTimer.setInterval(msec(hnsdSyncTimeout));
connect(&_hnsdSyncTimer, &QTimer::timeout, this,
[this]()
{
// hnsd is not syncing. Don't stop it (it continues to try to
// connect to peers), but indicate the failure to display a UI
// warning
qInfo() << "hnsd has not synced any blocks, reporting error";
emit hnsdSyncFailure(true);
});
connect(this, &ProcessRunner::stdoutLine, this,
[this](const QByteArray &line)
{
if(line.contains(QByteArrayLiteral(" new height: ")))
{
// At least 1 block has been synced, handshake is connected.
_hnsdSyncTimer.stop();
emit hnsdSyncFailure(false);
// We just want to show some progress of hnsd's sync in the log.
// Qt regexes don't work on byte arrays but this check works
// well enough to trace every 1000 blocks.
if(line.endsWith(QByteArrayLiteral("000")))
qInfo() << objectName() << "-" << line;
}
});
// We never clear hnsdSyncFailure() when hnsd starts / stops / restarts. We
// try to avoid reporting it spuriously (by stopping the timer if hnsd
// stops; the failing warning covers this state). Once we _do_ report it
// though, we don't want to clear it until hnsd really does sync a block, to
// avoid a flapping warning.
connect(this, &ProcessRunner::started, this,
[this]()
{
// Start (or restart) the sync timer.
_hnsdSyncTimer.start();
});
// 'succeeded' means that the process has been running for long enough that
// ProcessRunner considers it successful. It hasn't necessarily synced any
// blocks yet; don't emit hnsdSyncFailure() at all.
connect(this, &ProcessRunner::succeeded, this, &HnsdRunner::hnsdSucceeded);
connect(this, &ProcessRunner::failed, this,
[this](std::chrono::milliseconds failureDuration)
{
emit hnsdFailed(failureDuration);
// Stop the sync timer since hnsd isn't running. The failure
// signal covers this state, avoid spuriously emitting a sync
// failure too (though these states _can_ overlap so we do still
// tolerate this in the client UI).
_hnsdSyncTimer.stop();
});
}
void HnsdRunner::setupProcess(UidGidProcess &process)
{
#ifdef Q_OS_LINUX
if(hasNetBindServiceCapability())
// Drop root privileges ("nobody" is a low-priv account that should exist on all Linux systems)
process.setUser("nobody");
else
qWarning() << Path::HnsdExecutable << "did not have cap_net_bind_service set; running hnsd as root.";
#endif
#ifdef Q_OS_UNIX
// Setting this group allows us to manage hnsd firewall rules
process.setGroup(BRAND_CODE "hnsd");
#endif
}
bool HnsdRunner::enable(QString program, QStringList arguments)
{
#ifdef Q_OS_MACOS
::shellExecute(QStringLiteral("ifconfig lo0 alias %1 up").arg(::hnsdLocalAddress));
#endif
// Invoke the original
return ProcessRunner::enable(std::move(program), std::move(arguments));
}
void HnsdRunner::disable()
{
// Invoke the original
ProcessRunner::disable();
// Not syncing or failing to sync since hnsd is no longer enabled.
_hnsdSyncTimer.stop();
emit hnsdSyncFailure(false);
#ifdef Q_OS_MACOS
QByteArray out;
std::tie(std::ignore, out, std::ignore) = ::shellExecute(QStringLiteral("ifconfig lo0"));
// Only try to remove the alias if it exists
if(out.contains(::hnsdLocalAddress.toLatin1()))
{
::shellExecute(QStringLiteral("ifconfig lo0 -alias %1").arg(::hnsdLocalAddress));
}
#endif
}
// Check if Hnsd can bind to low ports without requiring root
bool HnsdRunner::hasNetBindServiceCapability()
{
#ifdef Q_OS_LINUX
int exitCode;
QByteArray out;
std::tie(exitCode, out, std::ignore) = ::shellExecute(QStringLiteral("getcap %1").arg(Path::HnsdExecutable));
if(exitCode != 0)
return false;
else
return out.contains("cap_net_bind_service");
#else
return false;
#endif
}
ShadowsocksRunner::ShadowsocksRunner(RestartStrategy::Params restartParams)
: ProcessRunner{std::move(restartParams)}, _localPort{0}
{
connect(this, &ShadowsocksRunner::stdoutLine, this, [this](const QByteArray &line)
{
qInfo() << objectName() << "- stdout:" << line;
QByteArray marker{QByteArrayLiteral("listening on TCP port ")};
auto pos = line.indexOf(marker);
if(pos >= 0)
{
_localPort = line.mid(pos + marker.length()).toUShort();
if(_localPort)
{
qInfo() << objectName() << "assigned port:" << _localPort;
emit localPortAssigned();
}
else
{
qInfo() << objectName() << "Could not detect assigned port:"
<< line;
// This is no good, kill the process and try again
kill();
}
}
});
connect(this, &ShadowsocksRunner::started, this, [this]()
{
qInfo() << objectName() << "started, waiting for local port";
_localPort = 0;
});
}
bool ShadowsocksRunner::enable(QString program, QStringList arguments)
{
if(ProcessRunner::enable(std::move(program), std::move(arguments)))
{
// Wipe the local port since the process is being restarted; doConnect()
// will wait for the next process startup rather than attempting a
// connection that will definitely fail.
// Note that this could race with a process restart if the process is
// crashing, so we could still observe an assigned port before the
// process restarts. In that case, we might still make an extra
// connection attempt while ss-local is restarting, which is fine.
if(_localPort)
{
qInfo() << objectName() << "- restarting due to parameter change, clear assigned port";
_localPort = 0;
}
return true;
}
return false;
}
void ShadowsocksRunner::setupProcess(UidGidProcess &process)
{
#ifdef Q_OS_UNIX
process.setUser(QStringLiteral("nobody"));
#endif
}
// Custom logging for our OriginalNetworkScan struct
QDebug operator<<(QDebug debug, const OriginalNetworkScan& netScan) {
QDebugStateSaver saver(debug);
debug.nospace() << QStringLiteral("Network(gatewayIp: %1, interfaceName: %2, ipAddress: %3)")
.arg(netScan.gatewayIp(), netScan.interfaceName(), netScan.ipAddress());
return debug;
}
TransportSelector::TransportSelector()
: _preferred{QStringLiteral("udp"), 0}, _lastUsed{QStringLiteral("udp"), 0}, _alternates{},
_nextAlternate{0}, _startAlternates{-1}, _status{Status::Connecting}
{
}
void TransportSelector::addAlternates(const QString &protocol,
const ServerLocation &location,
const QVector<uint> &ports)
{
Transport nextTransport{protocol, 0};
// Add the implicit default port if it's not in the list of ports
nextTransport.resolvePort(location);
if(_preferred != nextTransport && !ports.contains(nextTransport.port()))
_alternates.emplace_back(nextTransport);
for(unsigned port : ports)
{
nextTransport.port(port);
if(_preferred != nextTransport)
_alternates.emplace_back(nextTransport);
}
}
QHostAddress TransportSelector::findInterfaceIp(const QString &interfaceName)
{
#ifdef Q_OS_UNIX
ifreq ifr = {};
int fd = socket(AF_INET, SOCK_DGRAM, 0);
// We're interested in the IPv4 address
ifr.ifr_addr.sa_family = AF_INET;
strncpy(ifr.ifr_name, qPrintable(interfaceName), IFNAMSIZ - 1);
// Request the interface address
if(ioctl(fd, SIOCGIFADDR, &ifr))
{
qWarning() << "Unable to retrieve interface ip:" << qt_error_string(errno);
close(fd);
return {};
}
close(fd);
quint32 address = reinterpret_cast<sockaddr_in*>(&ifr.ifr_addr)->sin_addr.s_addr;
return QHostAddress{ntohl(address)};
#else
return {};
#endif
}
QHostAddress TransportSelector::findLocalAddress(const QString &remoteAddress)
{
// Determine what local address we will use to make this connection.
// A "UDP connect" doesn't actually send any packets, it just determines
// the local address to use for a connection.
QUdpSocket connTest;
connTest.connectToHost(remoteAddress, 8080);
return connTest.localAddress();
}
void TransportSelector::scanNetworkRoutes(OriginalNetworkScan &netScan)
{
QString out, err;
QStringList result;
int exitCode{-1}; // Default to -1 so it fails on windows for now
// TODO: use system APIs for this rather than relying on flaky and changeable system tools (in terms of their output format)
#if defined(Q_OS_MACOS)
// This awk script is necessary as the macOS 10.14 and 10.15 output of netstat has changed. As a result we need to actually locate the columns
// we're interested in, we can't just hard-code a column number
auto commandString = QStringLiteral("netstat -nr -f inet | sed '1,3 d' | awk 'NR==1 { for (i=1; i<=NF; i++) { f[$i] = i } } NR>1 && $(f[\"Destination\"])==\"default\" { print $(f[\"Gateway\"]), $(f[\"Netif\"]) ; exit }'");
#elif defined(Q_OS_LINUX)
auto commandString = QStringLiteral("netstat -nr | tee /dev/stderr | awk '$1==\"default\" || ($1==\"0.0.0.0\" && $3==\"0.0.0.0\") { print $2, $8; exit }'");
#endif
#ifdef Q_OS_UNIX
std::tie(exitCode, out, err) = ::shellExecute(commandString);
if(exitCode == 0)
{
result = out.split(' ');
netScan.gatewayIp(result.first());
netScan.interfaceName(result.last());
}
#else
// Not needed for Windows
netScan.gatewayIp(QStringLiteral("N/A"));
netScan.interfaceName(QStringLiteral("N/A"));
#endif
}
QHostAddress TransportSelector::validLastLocalAddress() const
{
if(_lastUsed.protocol() == QStringLiteral("udp"))
return _lastLocalUdpAddress;
else
return _lastLocalTcpAddress;
}
void TransportSelector::reset(Transport preferred, bool useAlternates,
const ServerLocation &location,
const QVector<uint> &udpPorts,
const QVector<uint> &tcpPorts)
{
_preferred = preferred;
_preferred.resolvePort(location);
_alternates.clear();
_nextAlternate = 0;
_startAlternates.setRemainingTime(msec(preferredTransportTimeout));
_status = Status::Connecting;
_useAlternateNext = false;
// Reset local addresses; doesn't really matter since we redetect them for
// each beginAttempt()
_lastLocalUdpAddress.clear();
_lastLocalTcpAddress.clear();
if(useAlternates)
{
// The expected count is just udpPorts.size() + tcpPorts.size().
// There are two implicit "default" choices, but the UDP one is
// eliminated since 8080 appears in the list (all regions use 8080 by
// default currently). The TCP default is 500, which is not in the
// list, but one other possibility will be eliminated because it's the
// preferred transport.
_alternates.reserve(udpPorts.size() + tcpPorts.size());
// Prefer to stay on the user's preferred protocol; try those first.
if(_preferred.protocol() == QStringLiteral("udp"))
{
addAlternates(QStringLiteral("udp"), location, udpPorts);
addAlternates(QStringLiteral("tcp"), location, tcpPorts);
}
else
{
addAlternates(QStringLiteral("tcp"), location, tcpPorts);
addAlternates(QStringLiteral("udp"), location, udpPorts);
}
}
}
OriginalNetworkScan TransportSelector::scanNetwork(const ServerLocation *pLocation,
const QString &protocol)
{
OriginalNetworkScan netScan;
// Get the gatewayIp and interfaceName
scanNetworkRoutes(netScan);
// The findLocalAddress() code is only broken on macOS, so let's limit the ioctl() approach to there for now.
// On macOS we add a 'bound route' (-ifscope route) that sometimes hangs around after changing network - this bound route can interfere with assigning source IPs
// to sockets and so using the findLocalAddress() approach can sometimes return the incorrect IP. Using findInterfaceIp() we can query the interface for
// its IP address which should always give us the correct result (assuming we ask the correct interface). The assumption behind using findInterfaceIp() is that
// the interface associated with the "first" default route after changing networks is added by the system and is always correct.
// TODO: extend this change to Linux as well?
#ifdef Q_OS_MACOS
netScan.ipAddress(findInterfaceIp(netScan.interfaceName()).toString());
#else
if(pLocation)
{
if(protocol == QStringLiteral("udp"))
netScan.ipAddress(findLocalAddress(pLocation->udpHost()).toString());
else
netScan.ipAddress(findLocalAddress(pLocation->tcpHost()).toString());
}
#endif
return netScan;
}
QHostAddress TransportSelector::lastLocalAddress() const
{
// If the last transport is the preferred transport, always allow any local
// address, even if we have alternate transport configurations to try.
//
// This ensures that we behave the same as prior releases most of the time,
// either when "Try Alternate Transports" is turned off or for connections
// using the preferred transport setting when it is on.
if(_lastUsed == _preferred)
return {};
// When using an alternate transport, restrict to the last local address we
// found. If the network connection changes, we don't want an alternate
// transport to succeed by chance, we want it to fail so we can try the
// preferred transport again.
return validLastLocalAddress();
}
bool TransportSelector::beginAttempt(const ServerLocation &location,
OriginalNetworkScan &netScan)
{
scanNetworkRoutes(netScan);
// Find the local addresses that we would use to connect to either the
// TCP or UDP addresses for this location. If they change, we reset and go
// back to the preferred transport only.
#ifdef Q_OS_MACOS
QHostAddress localUdpAddress = findInterfaceIp(netScan.interfaceName());
// Source IP is the same regardless of protocol
QHostAddress localTcpAddress = localUdpAddress;
#else
QHostAddress localUdpAddress = findLocalAddress(location.udpHost());
QHostAddress localTcpAddress = findLocalAddress(location.tcpHost());
#endif
netScan.ipAddress({});
// If either address has changed, a network connectivity change has
// occurred. Reset and try the preferred transport only for a while.
//
// If Try Alternate Transports is turned off, this has no effect, because we
// don't have any alternate transports to try in that case.
if(localUdpAddress != _lastLocalUdpAddress || localTcpAddress != _lastLocalTcpAddress)
{
qInfo() << "UDP:" << localUdpAddress << "->" << location.udpHost();
qInfo() << "TCP:" << localTcpAddress << "->" << location.tcpHost();
qInfo() << "Network connectivity has changed since last attempt, start over from preferred transport";
_lastLocalUdpAddress = localUdpAddress;
_lastLocalTcpAddress = localTcpAddress;
_nextAlternate = 0;
_startAlternates.setRemainingTime(msec(preferredTransportTimeout));
_status = Status::Connecting;
_useAlternateNext = false;
}
// Advance status when the alternate timer elapses
if(_status == Status::Connecting && _startAlternates.hasExpired())
{
if(_alternates.empty() || _lastLocalUdpAddress.isNull() ||
_lastLocalTcpAddress.isNull())
{
// Can't try alternates - they're not enabled, or we weren't able to
// detect a local address (we probably aren't connected right now).
_status = Status::TroubleConnecting;
}
else
{
_status = Status::TryingAlternates;
}
}
bool delayNext = true;
// Always use the preferred transport if:
// - there are no alternates
// - the preferred transport interval hasn't elapsed (still in Connecting)
// - we failed to detect a local IP address for the connection (this means
// we are not connected to a network right now, and we don't want to
// attempt an alternate transport with "any" local address)
if(_alternates.empty() || _status == Status::Connecting ||
_lastLocalUdpAddress.isNull() || _lastLocalTcpAddress.isNull())
{
_lastUsed = _preferred;
}
// After a few failures, start trying alternates. After each retry delay,
// we try the preferred settings, then immediately try one alternate if that
// still fails (to minimize the possibility that the timing of network
// connections, etc. could cause us to fail over spuriously).
//
// To do that, alternate between the preferred settings with no delay, and
// the next alternate with the usual delay.
else if(!_useAlternateNext)
{
// Try preferred settings.
_useAlternateNext = true;
_lastUsed = _preferred;
// No delay since we'll try an alternate next.
delayNext = false;
}
else
{
// Try the next alternate
if(_nextAlternate >= _alternates.size())
_nextAlternate = 0;
_lastUsed = _alternates[_nextAlternate];
++_nextAlternate;
_useAlternateNext = false;
}
netScan.ipAddress(validLastLocalAddress().toString());
return delayNext;
}
QHostAddress ConnectionConfig::parseIpv4Host(const QString &host)
{
// The proxy address must be a literal IPv4 address, we cannot
// resolve hostnames due DNS being blocked during reconnection. For
// any failure, leave the resulting QHostAddress clear.
QHostAddress socksTestAddress;
if(socksTestAddress.setAddress(host))
{
// Only IPv4 is supported currently
if(socksTestAddress.protocol() != QAbstractSocket::NetworkLayerProtocol::IPv4Protocol)
{
qWarning() << "Invalid SOCKS proxy network protocol"
<< socksTestAddress.protocol() << "for address"
<< socksTestAddress << "- parsed from" << host;
}
}
else
{
qInfo() << "Invalid SOCKS proxy address:" << host;
}
return socksTestAddress;
}
ConnectionConfig::ConnectionConfig()
: _vpnLocationAuto{false}, _proxyType{ProxyType::None},
_shadowsocksLocationAuto{false}
{}
ConnectionConfig::ConnectionConfig(DaemonSettings &settings, DaemonState &state)
: ConnectionConfig{}
{
// Grab the next VPN location. Copy it in case the locations in DaemonState
// are updated.
if(state.vpnLocations().nextLocation())
_pVpnLocation.reset(new ServerLocation{*state.vpnLocations().nextLocation()});
_vpnLocationAuto = !state.vpnLocations().chosenLocation();
if(settings.proxy() == QStringLiteral("custom"))
{
_proxyType = ProxyType::Custom;
_customProxy = settings.proxyCustom();
// The proxy address must be a literal IPv4 address, we cannot resolve
// hostnames due DNS being blocked during reconnection. For any
// failure, leave _socksHostAddress clear, which will be detected as a
// nonfatal error later.
_socksHostAddress = parseIpv4Host(_customProxy.host());
}
else if(settings.proxy() == QStringLiteral("shadowsocks"))
{
_proxyType = ProxyType::Shadowsocks;
_socksHostAddress = QHostAddress{0x7f000001}; // 127.0.0.1
if(state.shadowsocksLocations().nextLocation())
_pShadowsocksLocation.reset(new ServerLocation{*state.shadowsocksLocations().nextLocation()});
_shadowsocksLocationAuto = !state.shadowsocksLocations().chosenLocation();
}
}
bool ConnectionConfig::canConnect() const
{
if(!vpnLocation())
{
qWarning() << "No VPN location found, cannot connect";
return false; // Always required for any connection
}
switch(proxyType())
{
default:
case ProxyType::None:
break;
case ProxyType::Shadowsocks:
if(!shadowsocksLocation() || !shadowsocksLocation()->shadowsocks())
{
qWarning() << "No Shadowsocks location found when using Shadowsocks proxy, cannot connect";
return false;
}
// Invariant; always 127.0.0.1 in this state
Q_ASSERT(!socksHost().isNull());
break;
case ProxyType::Custom:
if(socksHost().isNull())
{
qWarning() << "SOCKS5 host invalid when using SOCKS5 proxy, cannot connect";
return false;
}
break;
}
return true;
}
bool ConnectionConfig::hasChanged(const ConnectionConfig &other) const
{
// Only consider location changes if the location ID has changed. Ignore
// changes in latency, metadata, etc.; we don't need to reset for these.
QString vpnLocationId = vpnLocation() ? vpnLocation()->id() : QString{};
QString ssLocationId = shadowsocksLocation() ? shadowsocksLocation()->id() : QString{};
QString otherVpnLocationId = other.vpnLocation() ? other.vpnLocation()->id() : QString{};
QString otherSsLocationId = other.shadowsocksLocation() ? other.shadowsocksLocation()->id() : QString{};
return proxyType() != other.proxyType() ||
socksHost() != other.socksHost() ||
customProxy() != other.customProxy() ||
vpnLocationId != otherVpnLocationId ||
ssLocationId != otherSsLocationId;
}
VPNConnection::VPNConnection(QObject* parent)
: QObject(parent)
, _state(State::Disconnected)
, _connectionStep{ConnectionStep::Initializing}
, _openvpn(nullptr)
, _hnsdRunner{hnsdRestart}
, _shadowsocksRunner{shadowsocksRestart}
, _connectionAttemptCount(0)
, _receivedByteCount(0)
, _sentByteCount(0)
, _lastReceivedByteCount(0)
, _lastSentByteCount(0)
, _needsReconnect(false)
{
_shadowsocksRunner.setObjectName("shadowsocks");
_connectTimer.setSingleShot(true);
connect(&_connectTimer, &QTimer::timeout, this, &VPNConnection::beginConnection);
connect(&_hnsdRunner, &HnsdRunner::hnsdSucceeded, this, &VPNConnection::hnsdSucceeded);
connect(&_hnsdRunner, &HnsdRunner::hnsdFailed, this, &VPNConnection::hnsdFailed);
connect(&_hnsdRunner, &HnsdRunner::hnsdSyncFailure, this, &VPNConnection::hnsdSyncFailure);
// The succeeded/failed signals from _shadowsocksRunner are ignored. It
// rarely fails, particularly since it does not do much of anything until we
// try to make a connection through it. Most failures would be covered by
// the general proxy diagnostics anyway (failed to connect, etc.) The only
// unique failure mode is if ss-local crashes while connected, this will
// give a general connection failure but potentially could give a specific
// error.
connect(&_shadowsocksRunner, &ShadowsocksRunner::localPortAssigned, this, [this]()
{
// This signal happens any time Shadowsocks is restarted, including if
// it crashed while we were connected.
// We only need to invoke doConnect() if we were specifically waiting on
// this port to be assigned, otherwise, let the connection drop and
// retry normally.
if((_state == State::Connecting || _state == State::Reconnecting ||
_state == State::StillConnecting || _state == State::StillReconnecting) &&
_connectionStep == ConnectionStep::StartingProxy)
{
qInfo() << "Shadowsocks proxy assigned local port"
<< _shadowsocksRunner.localPort() << "- continue connecting";
doConnect();
}
else
{
qWarning() << "Shadowsocks proxy assigned local port"
<< _shadowsocksRunner.localPort()
<< "but we were not waiting on it to connect";
}
});
}
void VPNConnection::activateMACE()
{
// To activate MACE, we need to send a TCP packet to 209.222.18.222 port 1111.
// This sets the DNS servers to block queries for known tracking domains
// As a fallback, we also need to send another packet 5 seconds later
// (see pia_manager's openvpn_manager.rb for original implementation)
//
// We can later test if we need a second packet, but it might be used to mitigate
// issues occured by sending a packet immediately.
auto maceActivate1 = new QTcpSocket();
qDebug () << "Sending MACE Packet 1";
maceActivate1->connectToHost(QStringLiteral("209.222.18.222"), 1111);
// Tested if error condition is hit by changing the port/invalid IP
connect(maceActivate1,QOverload<QAbstractSocket::SocketError>::of(&QAbstractSocket::error), this,
[maceActivate1](QAbstractSocket::SocketError socketError) {
qError() << "Failed to activate MACE packet 1 " << socketError;
maceActivate1->deleteLater();
});
connect(maceActivate1, &QAbstractSocket::connected, this, [maceActivate1]() {
qDebug () << "MACE Packet 1 connected succesfully";
maceActivate1->close();
maceActivate1->deleteLater();
});
QTimer::singleShot(std::chrono::milliseconds(5000).count(), this, [this]() {
auto maceActivate2 = new QTcpSocket();
qDebug () << "Sending MACE Packet 2";
maceActivate2->connectToHost(QStringLiteral("209.222.18.222"), 1111);
connect(maceActivate2,QOverload<QAbstractSocket::SocketError>::of(&QAbstractSocket::error), this,
[maceActivate2](QAbstractSocket::SocketError socketError) {
qError() << "Failed to activate MACE packet 2 " << socketError;
maceActivate2->deleteLater();
});
connect(maceActivate2, &QAbstractSocket::connected, this, [maceActivate2]() {
qDebug () << "MACE Packet 2 connected succesfully";
maceActivate2->close();
maceActivate2->deleteLater();
});
});
}
bool VPNConnection::needsReconnect()
{
if (!_openvpn || _state == State::Disconnecting || _state == State::DisconnectingToReconnect || _state == State::Disconnected)
return _needsReconnect = false;
if (_needsReconnect)
return true;
for (auto name : g_connectionSettingNames)
{
QJsonValue storedValue = _connectionSettings.value(QLatin1String(name));
QJsonValue currentValue = g_settings.get(name);
if (storedValue != currentValue)
return _needsReconnect = true;
}
return false;
}
void VPNConnection::scanNetwork(const ServerLocation *pLocation, const QString &protocol)
{
emit scannedOriginalNetwork(_transportSelector.scanNetwork(pLocation, protocol));
}
void VPNConnection::connectVPN(bool force)
{
switch (_state)
{
case State::Connected:
Q_ASSERT(_connectedConfig.vpnLocation()); // Valid in this state
// If settings haven't changed, there's nothing to do.
if (!force && !needsReconnect())
return;
// Otherwise, change to DisconnectingToReconnect
copySettings(State::DisconnectingToReconnect, State::Disconnecting);
Q_ASSERT(_openvpn); // Valid in this state
_openvpn->shutdown();
return;
case State::Connecting:
case State::StillConnecting:
case State::Reconnecting:
case State::StillReconnecting:
// If settings haven't changed, there's nothing to do.
if (!force && !needsReconnect())
return;
// fallthrough
if (_openvpn)
{
_openvpn->shutdown();
copySettings(State::DisconnectingToReconnect, State::Disconnecting);
}
else
{
// Don't go to the DisconnectingToReconnect state since we weren't
// actively attempting a connection. Instead, go directly to the
// Connecting or Reconnecting state.
auto newState = _connectedConfig.vpnLocation() ? State::Reconnecting : State::Connecting;
copySettings(newState, State::Disconnected);
// We already queued a connection attempt when entering the
// Interrupted state; nothing else to do.
}
return;
case State::DisconnectingToReconnect:
// If we're already disconnecting to reconnect, there's nothing to do.
// We'll reconnect as planned with the new settings when OpenVPN exits.
return;
default:
qWarning() << "Connecting in unhandled state " << _state;
// fallthrough
case State::Disconnected:
_connectionAttemptCount = 0;
_connectedConfig = {};
if(copySettings(State::Connecting, State::Disconnected))
queueConnectionAttempt();
return;
}
}
void VPNConnection::disconnectVPN()
{
if (_state != State::Disconnected)
{
_connectingConfig = {};
setState(State::Disconnecting);
if (_openvpn && _openvpn->state() < OpenVPNProcess::Exiting)
_openvpn->shutdown();
if (!_openvpn || _openvpn->state() == OpenVPNProcess::Exited)
{
setState(State::Disconnected);
}
}
}
void VPNConnection::beginConnection()
{
_connectionStep = ConnectionStep::Initializing;
doConnect();
}
void VPNConnection::doConnect()
{
switch (_state)
{
case State::Interrupted:
setState(State::Reconnecting);
break;
case State::DisconnectingToReconnect:
// Will transition to Reconnecting when the disconnect completes.
qInfo() << "Currently disconnecting to reconnect; doConnect ignored";
return;
case State::Connecting:
case State::Reconnecting:
case State::StillConnecting:
case State::StillReconnecting:
break;
case State::Connected:
qInfo() << "Already connected; doConnect ignored";
return;
case State::Disconnected:
case State::Disconnecting:
// 'Disconnected' and 'Disconnecting' should have transitioned where the
// call to doConnect was scheduled (normally connectVPN()), we should
// only observe these here if disconnectVPN() was then called before the
// deferred call to doConnect().
qInfo() << "doConnect() called after disconnect, ignored";
return;
default:
qError() << "Called doConnect in unknown state" << qEnumToString(_state);
return;
}
if (_openvpn)
{
qWarning() << "OpenVPN process already exists; doConnect ignored";
return;
}
// Handle pre-connection steps. Note that these _cannot_ fail with nonfatal
// errors - we need to apply the failure logic later to set the next request
// delay and possibly change state. Nonfatal errors have to be detected
// later when we're about to start OpenVPN.
if(_connectionStep == ConnectionStep::Initializing)
{
// Copy settings to begin the attempt (may reset the attempt count)
if(!copySettings(_state, State::Disconnected))
{
// Failed to load locations, already traced by copySettings, just
// bail now that we are in the Disconnected state
return;
}
// Consequence of copySettings(), required below
Q_ASSERT(_connectingConfig.vpnLocation());
_connectionStep = ConnectionStep::FetchingIP;
// Do we need to fetch the non-VPN IP address? Do this for the first
// connection attempt (which resets if the network connection changes).
// However, we can't do it at all if we're reconnecting, because the
// killswitch blocks DNS resolution.
if(_connectionAttemptCount == 0 &&
(_state == State::Connecting || _state == State::StillConnecting))
{
// We're not retrying this request if it fails - we don't want to hold
// up the connection attempt; this information isn't critical.
ApiClient::instance()
->getIp(QStringLiteral("status"))
->notify(this, [this](const Error& error, const QJsonDocument& json) {
if (!error)
{
QString ip = json[QStringLiteral("ip")].toString();
if (!ip.isEmpty())
{
g_state.externalIp(ip);
}
}
doConnect();
}, Qt::QueuedConnection); // Deliver results asynchronously so we never recurse
return;
}
}
// We either finished fetching the IP or we skipped it. Do we need to
// start a proxy?
if(_connectionStep == ConnectionStep::FetchingIP)
{
_connectionStep = ConnectionStep::StartingProxy;
if(_connectingConfig.shadowsocksLocation() && _connectingConfig.shadowsocksLocation()->shadowsocks())
{
const auto &pSsServer = _connectingConfig.shadowsocksLocation()->shadowsocks();
_shadowsocksRunner.enable(Path::SsLocalExecutable,
QStringList{QStringLiteral("-s"), pSsServer->host(),
QStringLiteral("-p"), QString::number(pSsServer->port()),
QStringLiteral("-k"), pSsServer->key(),
QStringLiteral("-b"), QStringLiteral("127.0.0.1"),
QStringLiteral("-l"), QStringLiteral("0"),
QStringLiteral("-m"), pSsServer->cipher()});
// If we don't already know a listening port, wait for it to tell
// us (we could already know if the SS client was already running)
if(_shadowsocksRunner.localPort() == 0)
{
qInfo() << "Wait for local proxy port to be assigned";
return;
}
else
{
qInfo() << "Local proxy has already assigned port"
<< _shadowsocksRunner.localPort();
}
}
else
_shadowsocksRunner.disable();
}
// We either finished starting a proxy or we skipped it. We're ready to connect
Q_ASSERT(_connectionStep == ConnectionStep::StartingProxy);
_connectionStep = ConnectionStep::ConnectingOpenVPN;
if (_connectionAttemptCount == 0)
{
// We shouldn't have any problems json_cast()ing these values since they
// came from DaemonSettings; just use defaults if it does happen
// somehow.
QString protocol;
uint selectedPort;
bool automaticTransport;
if(!json_cast(_connectionSettings.value("protocol"), protocol))
protocol = QStringLiteral("udp");
// Shadowsocks proxies require TCP; UDP relays aren't enabled on PIA
// servers.
if(_connectingConfig.proxyType() == ConnectionConfig::ProxyType::Shadowsocks &&
protocol != QStringLiteral("tcp"))
{
qInfo() << "Using TCP transport due to Shadowsocks proxy setting";
protocol = QStringLiteral("tcp");
}
if(protocol == QStringLiteral("udp"))
{
if(!json_cast(_connectionSettings.value("remotePortUDP"), selectedPort))
selectedPort = 0;
}
else
{
if(!json_cast(_connectionSettings.value("remotePortTCP"), selectedPort))
selectedPort = 0;
}
if(!json_cast(_connectionSettings.value("automaticTransport"), automaticTransport))
automaticTransport = true;
// Automatic transport isn't supported when a SOCKS proxy is also
// configured. (We can't be confident that a failure to connect is due
// to a port being blocked.)
if(_connectingConfig.proxyType() != ConnectionConfig::ProxyType::None)
automaticTransport = false;
// Reset the transport selection sequence
_transportSelector.reset({protocol, selectedPort}, automaticTransport,
*_connectingConfig.vpnLocation(),
g_data.udpPorts(), g_data.tcpPorts());
}
// Reset traffic counters since we have a new process
_lastReceivedByteCount = 0;
_lastSentByteCount = 0;
_intervalMeasurements.clear();
emit byteCountsChanged();
// Reset any running connect timer, just in case
_connectTimer.stop();
OriginalNetworkScan netScan;
bool delayNext = _transportSelector.beginAttempt(*_connectingConfig.vpnLocation(), netScan);
// Emit the current network configuration, so it can be used for split
// tunnel if it's known. If we did find it (and it doesn't change by the
// time we connect), this avoids a blip for excluded apps where they might
// route into the VPN tunnel once OpenVPN sets up the routes.
//
// This scan is not reliable though - the network could come up or change
// between now and when OpenVPN starts. We do another scan just after
// connecting to be sure that we get the correct config. (If those scans
// differ, there may be a connectivity blip, but the network connections
// changed so a blip is OK.)
emit scannedOriginalNetwork(netScan);
// Set when the next earliest reconnect attempt is allowed
if(delayNext)
{
switch (_state)
{
case State::Connecting:
_timeUntilNextConnectionAttempt.setRemainingTime(ConnectionAttemptInterval);
break;
case State::StillConnecting:
_timeUntilNextConnectionAttempt.setRemainingTime(SlowConnectionAttemptInterval);
break;
case State::Reconnecting:
_timeUntilNextConnectionAttempt.setRemainingTime(ReconnectionAttemptInterval);
break;
case State::StillReconnecting:
_timeUntilNextConnectionAttempt.setRemainingTime(SlowReconnectionAttemptInterval);
break;
default:
break;
}
}
else
_timeUntilNextConnectionAttempt.setRemainingTime(0);
++_connectionAttemptCount;
if (_state == State::Connecting && _connectionAttemptCount > SlowConnectionAttemptLimit)
setState(State::StillConnecting);
else if (_state == State::Reconnecting && _connectionAttemptCount > SlowReconnectionAttemptLimit)
setState(State::StillReconnecting);
emit connectingStatus(_transportSelector.status());
QStringList arguments;
try
{
arguments += QStringLiteral("--verb");
arguments += QStringLiteral("4");
_networkAdapter = g_daemon->getNetworkAdapter();
if (_networkAdapter)
{
QString devNode = _networkAdapter->devNode();
if (!devNode.isEmpty())
{
arguments += QStringLiteral("--dev-node");
arguments += devNode;
}
}
arguments += QStringLiteral("--script-security");
arguments += QStringLiteral("2");
auto escapeArg = [](QString arg)
{
// Escape backslashes and spaces in the command. Note this is the
// same even on Windows, because OpenVPN parses this command line
// with its internal parser, then re-joins and re-quotes it on
// Windows with Windows quoting conventions.
arg.replace(QLatin1String(R"(\)"), QLatin1String(R"(\\)"));
arg.replace(QLatin1String(R"( )"), QLatin1String(R"(\ )"));
return arg;
};
QString updownCmd;
#ifdef Q_OS_WIN
updownCmd += escapeArg(QString::fromLocal8Bit(qgetenv("WINDIR")) + "\\system32\\cmd.exe");
updownCmd += QStringLiteral(" /C call ");
#endif
updownCmd += escapeArg(Path::OpenVPNUpDownScript);
#ifdef Q_OS_WIN
// Only the Windows updown script supports logging right now. Enable it
// if debug logging is turned on.
if(g_settings.debugLogging())
{
updownCmd += " --log ";
updownCmd += escapeArg(Path::UpdownLogFile);
}
#endif
// Pass DNS server addresses
QStringList dnsServers = getDNSServers(_dnsServers);
if(!dnsServers.isEmpty())
{
updownCmd += " --dns ";
updownCmd += dnsServers.join(':');
}
// Terminate PIA args with '--' (OpenVPN passes several subsequent
// arguments)
updownCmd += " --";
#ifdef Q_OS_WIN
if(g_settings.windowsIpMethod() == QStringLiteral("static"))
{
// Static configuration on Windows - use OpenVPN's netsh method, use
// updown script to apply DNS with netsh
arguments += "--ip-win32";
arguments += "netsh";
// Use the same script for --up and --down
arguments += "--up";
arguments += updownCmd;
arguments += "--down";
arguments += updownCmd;
}
else
{
// DHCP configuration on Windows - use OpenVPN's default ip-win32
// method, pass DNS servers as DHCP options
for(const auto &dnsServer : dnsServers)
{
arguments += "--dhcp-option";
arguments += "DNS";
arguments += dnsServer;
}
}
#else
// Mac and Linux - always use updown script for DNS
// Use the same script for --up and --down
arguments += "--up";
arguments += updownCmd;
arguments += "--down";
arguments += updownCmd;
#endif
arguments += QStringLiteral("--config");
QFile configFile(Path::OpenVPNConfigFile);
if (!configFile.open(QIODevice::WriteOnly | QIODevice::Text) ||
!writeOpenVPNConfig(configFile))
{
throw Error(HERE, Error::OpenVPNConfigFileWriteError);
}
configFile.close();
arguments += Path::OpenVPNConfigFile;
}
catch (const Error& ex)
{
// Do _not_ call raiseError() here because it would immediately schedule
// another connection attempt for nonfatal errors (we haven't created
// _openvpn yet). Schedule the next attempt so we back off the retry
// interval. There are no fatal errors that can occur here (the only
// fatal error is an auth error, which is signaled by OpenVPN after it's
// started).
emit error(ex);
scheduleNextConnectionAttempt();
return;
}
if (_networkAdapter)
{
// Ensure our tunnel has priority over other interfaces. This is especially important for DNS.
_networkAdapter->setMetricToLowest();
}
_openvpn = new OpenVPNProcess(this);
// TODO: this can be hooked up to support in-process up/down script handling via scripts that print magic strings
connect(_openvpn, &OpenVPNProcess::stdoutLine, this, &VPNConnection::openvpnStdoutLine);
connect(_openvpn, &OpenVPNProcess::stderrLine, this, &VPNConnection::openvpnStderrLine);
connect(_openvpn, &OpenVPNProcess::managementLine, this, &VPNConnection::openvpnManagementLine);
connect(_openvpn, &OpenVPNProcess::stateChanged, this, &VPNConnection::openvpnStateChanged);
connect(_openvpn, &OpenVPNProcess::exited, this, &VPNConnection::openvpnExited);
connect(_openvpn, &OpenVPNProcess::error, this, &VPNConnection::openvpnError);
_openvpn->run(arguments);
}
void VPNConnection::openvpnStdoutLine(const QString& line)
{
FUNCTION_LOGGING_CATEGORY("openvpn.stdout");
qDebug().noquote() << line;
checkStdoutErrors(line);
}
void VPNConnection::checkStdoutErrors(const QString &line)
{
// Check for specific errors that we can detect from OpenVPN's output.
if(line.contains("socks_username_password_auth: server refused the authentication"))
{
raiseError({HERE, Error::Code::OpenVPNProxyAuthenticationError});
return;
}
// This error can be logged by socks_handshake and recv_socks_reply, others
// might be possible too.
if(line.contains(QRegExp("socks.*: TCP port read failed")))
{
raiseError({HERE, Error::Code::OpenVPNProxyError});
return;
}
// This error occurs if OpenVPN fails to open a TCP connection. If it's
// reported for the SOCKS proxy, report it as a proxy error, otherwise let
// it be handled as a general failure.
QRegExp tcpFailRegex{R"(TCP: connect to \[AF_INET\]([\d\.]+):\d+ failed:)"};
if(line.contains(tcpFailRegex))
{
QHostAddress failedHost;
if(failedHost.setAddress(tcpFailRegex.cap(1)) &&
failedHost == _connectingConfig.socksHost())
{
raiseError({HERE, Error::Code::OpenVPNProxyError});
return;
}
}
}
void VPNConnection::openvpnStderrLine(const QString& line)
{
FUNCTION_LOGGING_CATEGORY("openvpn.stderr");
qDebug().noquote() << line;
checkForMagicStrings(line);
}
void VPNConnection::checkForMagicStrings(const QString& line)
{
QRegExp tunDeviceNameRegex{R"(Using device:([^ ]+) address:([^ ]+))"};
if(line.contains(tunDeviceNameRegex))
{
emit usingTunnelDevice(tunDeviceNameRegex.cap(1), tunDeviceNameRegex.cap(2));
}
// TODO: extract this out into a more general error mechanism, where the "!!!" prefix
// indicates an error condition followed by the code.
if (line.startsWith("!!!updown.sh!!!dnsConfigFailure")) {
raiseError(Error(HERE, Error::OpenVPNDNSConfigError));
}
}
bool VPNConnection::respondToMgmtAuth(const QString &line, const QString &user,
const QString &password)
{
// Extract the auth type from the prompt - such as `Auth` or `SOCKS Proxy`.
// The line looks like:
// >PASSWORD:Need 'Auth' username/password
auto quotes = line.midRef(15).split('\'');
if (quotes.size() >= 3)
{
auto id = quotes[1].toString();
auto cmd = QStringLiteral("username \"%1\" \"%2\"\npassword \"%1\" \"%3\"")
.arg(id, user, password);
_openvpn->sendManagementCommand(QLatin1String(cmd.toLatin1()));
return true;
}
qError() << "Invalid password request";
return false;
}
void VPNConnection::openvpnManagementLine(const QString& line)
{
FUNCTION_LOGGING_CATEGORY("openvpn.mgmt");
qDebug().noquote() << line;
if (!line.isEmpty() && line[0] == '>')
{
if (line.startsWith(QLatin1String(">PASSWORD:")))
{
// SOCKS proxy auth
if (line.startsWith(QLatin1String(">PASSWORD:Need 'SOCKS Proxy'")))
{
if(respondToMgmtAuth(line, _connectingConfig.customProxy().username(),
_connectingConfig.customProxy().password()))
{
return;
}
}
// Normal password authentication
// The type is usually 'Auth', but use these creds by default to
// preserve existing behavior.
else if (line.startsWith(QLatin1String(">PASSWORD:Need ")))
{
if(respondToMgmtAuth(line, _openvpnUsername, _openvpnPassword))
return;
}
else if (line.startsWith(QLatin1String(">PASSWORD:Auth-Token:")))
{
// TODO: PIA servers aren't set up to use this properly yet
return;
}
else if (line.startsWith(QLatin1String(">PASSWORD:Verification Failed: ")))
{
raiseError(Error(HERE, Error::OpenVPNAuthenticationError));
return;
}
// All unhandled cases
raiseError(Error(HERE, Error::OpenVPNAuthenticationError));
}
else if (line.startsWith(QLatin1String(">BYTECOUNT:")))
{
auto params = line.midRef(11).split(',');
if (params.size() >= 2)
{
bool ok = false;
quint64 up, down;
if (((down = params[0].toULongLong(&ok)), ok) && ((up = params[1].toULongLong(&ok)), ok))
{
updateByteCounts(down, up);
}
}
}
}
}
void VPNConnection::openvpnStateChanged()
{
OpenVPNProcess::State openvpnState = _openvpn ? _openvpn->state() : OpenVPNProcess::Exited;
State newState = _state;
switch (openvpnState)
{
case OpenVPNProcess::Connected:
switch (_state)
{
default:
qWarning() << "OpenVPN connected in unexpected state" << qEnumToString(_state);
Q_FALLTHROUGH();
case State::Connecting:
case State::StillConnecting:
case State::Reconnecting:
case State::StillReconnecting:
// The connection was established, so the connecting location is now
// the connected location.
_connectedConfig = std::move(_connectingConfig);
_connectingConfig = {};
// Do a new network scan now that we've connected. If split tunnel
// is enabled (now or later while connected), this is necessary to
// ensure that we have the correct local IP address. If the network
// configuration changes at any point after this (or even if it had
// already changed since the connection was established), we'll drop
// the OpenVPN connection and re-scan when we connect again.
scanNetwork(_connectedConfig.vpnLocation().get(), _transportSelector.lastUsed().protocol());
// If DNS is set to Handshake, start it now, since we've connected
if(isDNSHandshake(_dnsServers))
_hnsdRunner.enable(Path::HnsdExecutable, hnsdArgs);
newState = State::Connected;
break;
case State::Disconnecting:
case State::Disconnected:
case State::DisconnectingToReconnect:
// In these cases, we should have already told it to shutdown, and
// the connection raced with the shutdown. Just in case, tell it to
// shutdown again; can't hurt anything and ensures that we don't get
// stuck in this state.
if (_openvpn)
_openvpn->shutdown();
break;
}
break;
case OpenVPNProcess::Reconnecting:
// In some rare cases OpenVPN reconnects on its own (e.g. TAP adapter I/O failure),
// but we don't want it to try to reconnect on its own; send a SIGTERM instead.
qWarning() << "OpenVPN trying to reconnect internally, sending SIGTERM";
if (_openvpn)
_openvpn->shutdown();
break;
case OpenVPNProcess::Exiting:
if (_state == State::Connected)
{
// Reconnect to the same location again
_connectingConfig = _connectedConfig;
newState = State::Interrupted;
queueConnectionAttempt();
}
break;
case OpenVPNProcess::Exited:
switch (_state)
{
case State::Connected:
// Reconnect to the same location again
_connectingConfig = _connectedConfig;
newState = State::Interrupted;
queueConnectionAttempt();
break;
case State::DisconnectingToReconnect:
// If we were connected before, go to the 'reconnecting' state, not
// the 'connecting' state. If the location stayed the same, the
// client will show a specific 'reconnecting' notification.
if(_connectedConfig.vpnLocation())
newState = State::Reconnecting;
else
newState = State::Connecting;
scheduleNextConnectionAttempt();
break;
case State::Connecting:
case State::StillConnecting:
case State::Reconnecting:
case State::StillReconnecting:
scheduleNextConnectionAttempt();
break;
case State::Interrupted:
newState = State::Reconnecting;
scheduleNextConnectionAttempt();
break;
case State::Disconnecting:
newState = State::Disconnected;
break;
default:
qWarning() << "OpenVPN exited in unexpected state" << qEnumToString(_state);
break;
}
break;
default:
break;
}
setState(newState);
}
void VPNConnection::openvpnExited(int exitCode)
{
if (_networkAdapter)
{
// Ensure we return our tunnel metric to how it was before we lowered it.
_networkAdapter->restoreOriginalMetric();
_networkAdapter.clear();
}
_openvpn->deleteLater();
_openvpn = nullptr;
openvpnStateChanged();
}
void VPNConnection::openvpnError(const Error& err)
{
raiseError(err);
}
void VPNConnection::raiseError(const Error& err)
{
switch (err.code())
{
// Non-critical errors that are merely warnings
//case ...:
// break;
// Hard errors that should abort all connection attempts.
// Few errors should really be fatal - only errors that definitely will not
// resolve by themselves. If there's any possibility that an error might
// resolve with no user intervention, we should keep trying to connect.
case Error::OpenVPNAuthenticationError:
disconnectVPN();
break;
// This error should abort the current connection attempt, but we keep attempting to reconnect
// as a user may fix their DNS enabling an eventual connection.
case Error::OpenVPNDNSConfigError:
// fallthrough
// All other errors should cancel current attempt and retry
default:
if (_openvpn)
_openvpn->shutdown();
else
queueConnectionAttempt();
}
emit error(err);
}
void VPNConnection::setState(State state)
{
if (state != _state)
{
if(state == State::Disconnected)
{
// We have completely disconnected, drop the measurement intervals.
_intervalMeasurements.clear();
emit byteCountsChanged();
// Stop shadowsocks if it was running.
_shadowsocksRunner.disable();
}
// Several members are only valid in the [Still]Connecting and
// [Still]Reconnecting states. If we're going to any other state, clear
// them.
if(state != State::Connecting && state != State::StillConnecting &&
state != State::Reconnecting && state != State::StillReconnecting)
{
_connectionStep = ConnectionStep::Initializing;
_connectionAttemptCount = 0;
_connectTimer.stop();
}
// In any state other than Connected, stop hnsd, even if that's our
// current DNS setting. (If we're reconnecting while Handshake is
// selected, it'll be restarted after we connect.)
if(state != State::Connected)
_hnsdRunner.disable();
_state = state;
// Sanity-check location invariants and grab transports if they're
// reported in this state
nullable_t<Transport> preferredTransport, actualTransport;
switch(_state)
{
default:
Q_ASSERT(false);
break;
case State::Connecting:
case State::StillConnecting:
Q_ASSERT(_connectingConfig.vpnLocation());
Q_ASSERT(!_connectedConfig.vpnLocation());
preferredTransport = _transportSelector.preferred();
break;
case State::Reconnecting:
case State::StillReconnecting:
Q_ASSERT(_connectingConfig.vpnLocation());
Q_ASSERT(_connectedConfig.vpnLocation());
preferredTransport = _transportSelector.preferred();
break;
case State::Interrupted:
Q_ASSERT(_connectingConfig.vpnLocation());
Q_ASSERT(_connectedConfig.vpnLocation());
break;
case State::Connected:
Q_ASSERT(!_connectingConfig.vpnLocation());
Q_ASSERT(_connectedConfig.vpnLocation());
preferredTransport = _transportSelector.preferred();
actualTransport = _transportSelector.lastUsed();
break;
case State::Disconnecting:
case State::Disconnected:
Q_ASSERT(!_connectingConfig.vpnLocation());
// _connectedConfig.vpnLocation() depends on whether we had a connection before
break;
case State::DisconnectingToReconnect:
Q_ASSERT(_connectingConfig.vpnLocation());
// _connectedConfig.vpnLocation() depends on whether we had a connection before
break;
}
// Resolve '0' ports to actual effective ports
if(_connectedConfig.vpnLocation())
{
if(preferredTransport)
preferredTransport->resolvePort(*_connectedConfig.vpnLocation());
if(actualTransport)
actualTransport->resolvePort(*_connectedConfig.vpnLocation());
}
emit stateChanged(_state, _connectingConfig, _connectedConfig,
preferredTransport, actualTransport);
}
}
void VPNConnection::updateByteCounts(quint64 received, quint64 sent)
{
quint64 intervalReceived = received - _lastReceivedByteCount;
quint64 intervalSent = sent - _lastSentByteCount;
_lastReceivedByteCount = received;
_lastSentByteCount = sent;
// Add to perpetual totals
_receivedByteCount += intervalReceived;
_sentByteCount += intervalSent;
// If we've reached the maximum number of measurements, discard one before
// adding a new one
if(_intervalMeasurements.size() == g_maxMeasurementIntervals)
_intervalMeasurements.takeFirst();
_intervalMeasurements.push_back({intervalReceived, intervalSent});
// The interval measurements always change even if the perpetual totals do
// not (we added a 0,0 entry).
emit byteCountsChanged();
}
void VPNConnection::scheduleNextConnectionAttempt()
{
quint64 remaining = _timeUntilNextConnectionAttempt.remainingTime();
if (remaining > 0)
_connectTimer.start((int)remaining);
else
queueConnectionAttempt();
}
void VPNConnection::queueConnectionAttempt()
{
// Begin a new connection attempt now
QMetaObject::invokeMethod(this, &VPNConnection::beginConnection, Qt::QueuedConnection);
}
bool VPNConnection::copySettings(State successState, State failureState)
{
// successState must be a state where the connecting locations are valid
Q_ASSERT(successState == State::Connecting || successState == State::StillConnecting ||
successState == State::Reconnecting || successState == State::StillReconnecting ||
successState == State::DisconnectingToReconnect ||
successState == State::Interrupted);
// failureState must be a state where the connecting locations are clear
Q_ASSERT(failureState == State::Disconnected ||
failureState == State::Connected ||
failureState == State::Disconnecting);
QJsonObject settings;
for (auto name : g_connectionSettingNames)
{
settings.insert(name, g_settings.get(name));
}
QString username = g_account.openvpnUsername();
QString password = g_account.openvpnPassword();
DaemonSettings::DNSSetting dnsServers = g_settings.overrideDNS();
ConnectionConfig newConfig{g_settings, g_state};
bool changed = _connectionSettings != settings ||
_openvpnUsername != username || _openvpnPassword != password ||
dnsServers != _dnsServers || newConfig.hasChanged(_connectingConfig);
_connectionSettings.swap(settings);
_openvpnUsername.swap(username);
_openvpnPassword.swap(password);
_dnsServers = std::move(dnsServers);
_connectingConfig = std::move(newConfig);
_needsReconnect = false;
// Reset to the first attempt; settings have changed
if(changed)
_connectionAttemptCount = 0;
// If we failed to load any required data, fail
if(!_connectingConfig.canConnect())
{
qWarning() << "Failed to load a required location - VPN location:"
<< !!_connectingConfig.vpnLocation() << "- Proxy type:"
<< traceEnum(_connectingConfig.proxyType())
<< "- Shadowsocks location:"
<< !!_connectingConfig.shadowsocksLocation();
qWarning() << "Go to state" << traceEnum(failureState) << "instead of"
<< traceEnum(successState) << "due to failure to load locations";
// Clear everything
_connectingConfig = {};
// Go to the failure state
setState(failureState);
return false;
}
// Locations were loaded
setState(successState);
return true;
}
bool VPNConnection::writeOpenVPNConfig(QFile& outFile)
{
QTextStream out{&outFile};
const char endl = '\n';
auto sanitize = [](const QString& s) {
QString result;
result.reserve(s.size());
for (auto& c : s)
{
switch (c.unicode())
{
case '\n':
case '\t':
case '\r':
case '\v':
case '"':
case '\'':
break;
default:
result.push_back(c);
break;
}
}
return result;
};
if (!_connectingConfig.vpnLocation())
return false;
out << "pia-signal-settings" << endl;
out << "client" << endl;
out << "dev tun" << endl;
QString remoteServer;
if (_transportSelector.lastUsed().protocol() == QStringLiteral("tcp"))
{
out << "proto tcp-client" << endl;
remoteServer = sanitize(_connectingConfig.vpnLocation()->tcpHost());
}
else
{
out << "proto udp" << endl;
out << "explicit-exit-notify" << endl;
remoteServer = sanitize(_connectingConfig.vpnLocation()->udpHost());
}
if (remoteServer.isEmpty())
return false;
out << "remote " << remoteServer << ' ' << _transportSelector.lastUsed().port() << endl;
if (!_connectingConfig.vpnLocation()->serial().isEmpty())
out << "verify-x509-name " << sanitize(_connectingConfig.vpnLocation()->serial()) << " name" << endl;
// OpenVPN's default setting is 'ping-restart 120'. This means it takes up
// to 2 minutes to notice loss of connection. (On some OSes/systems it may
// notice a change in local network connectivity more quickly, but this is
// not reliable and cannot detect connection loss due to an upstream
// change.) This affects both TCP and UDP.
//
// 2 minutes is longer than most users seem to wait for the app to
// reconnect, based on feedback and reports they usually give up and try to
// reconnect manually before then.
//
// We've also seen examples where OpenVPN does not seem to actually exit
// following connection loss, though we have not been able to reproduce
// this. It's possible that this has to do with the default 'ping-restart'
// vs. 'ping-exit'.
//
// Enable ping-exit 25 to attempt to detect connection loss more quickly and
// ensure OpenVPN exits on connection loss.
out << "ping 5" << endl;
out << "ping-exit 25" << endl;
out << "persist-remote-ip" << endl;
out << "resolv-retry 0" << endl;
out << "route-delay 0" << endl;
out << "reneg-sec 0" << endl;
out << "server-poll-timeout 10s" << endl;
out << "tls-client" << endl;
out << "tls-exit" << endl;
out << "remote-cert-tls server" << endl;
out << "auth-user-pass" << endl;
out << "pull-filter ignore \"auth-token\"" << endl;
// Increasing sndbuf/rcvbuf can boost throughput, which is what most users
// prioritize. For now, just copy the values used in the previous client.
out << "sndbuf 262144" << endl;
out << "rcvbuf 262144" << endl;
if (g_settings.routeDefault())
{
out << "redirect-gateway def1 bypass-dhcp";
if (!g_settings.blockIPv6())
out << " ipv6";
// When using a SOCKS proxy, handle the VPN endpoint route ourselves.
if(_connectingConfig.proxyType() != ConnectionConfig::ProxyType::None)
out << " local";
out << endl;
// When using a SOCKS proxy, if that proxy is on the Internet, we need
// to route it back to the default gateway (like we do with the VPN
// server).
if(_connectingConfig.proxyType() != ConnectionConfig::ProxyType::None)
{
QHostAddress remoteHost;
switch(_connectingConfig.proxyType())
{
default:
case ConnectionConfig::ProxyType::None:
Q_ASSERT(false);
break;
case ConnectionConfig::ProxyType::Custom:
remoteHost = _connectingConfig.socksHost();
break;
case ConnectionConfig::ProxyType::Shadowsocks:
{
QSharedPointer<ShadowsocksServer> _pSsServer;
if(_connectingConfig.shadowsocksLocation())
_pSsServer = _connectingConfig.shadowsocksLocation()->shadowsocks();
if(_pSsServer)
remoteHost = ConnectionConfig::parseIpv4Host(_pSsServer->host());
break;
}
}
// If the remote host address couldn't be parsed, fail now.
if(remoteHost.isNull())
throw Error{HERE, Error::Code::OpenVPNProxyResolveError};
// We do _not_ want this route if the SOCKS proxy is on LAN or
// localhost. (It actually mostly works, but on Windows with a LAN
// proxy it does reroute the traffic through the gateway.)
//
// This may be incorrect with nested LANs - a SOCKS proxy on the outer
// LAN is detected as LAN, but we actually do want this route since it's
// not on _our_ LAN. We don't fully support nested LANs right now, and
// the only fix for that is to actually read the entire routing table.
// Users can work around this by manually creating this route to the
// SOCKS proxy.
if(isIpv4Local(remoteHost))
{
qInfo() << "Not creating route for local proxy" << remoteHost;
}
else
{
qInfo() << "Creating gateway route for Internet proxy"
<< remoteHost;
// OpenVPN still creates a route to the remote endpoint when doing
// this, which might seem unnecessary but is still desirable if the
// proxy is running on localhost. (Or even if the proxy is not
// actually on localhost but ends up communicating over this host,
// such as a proxy running in a VM on this host.)
out << "route " << remoteHost.toString()
<< " 255.255.255.255 net_gateway 0" << endl;
}
// We still want to route the VPN server back to the default gateway
// too. If the proxy communicates via localhost, we need this
// route. (Otherwise, traffic would be recursively routed back into
// the proxy.) This is needed for proxies on localhost, on a VM
// running on this host, etc., and it doesn't hurt anything when
// it's not needed. The killswitch still blocks these connections
// by default though, so this also requires turning killswitch off
// or manually creating firewall rules to exempt the proxy.
//
// We do this ourselves because OpenVPN inconsistently substitutes
// the SOCKS proxy address in the redirect-gateway route (it's not
// clear why it does that occasionally but not always).
out << "route " << remoteServer << " 255.255.255.255 net_gateway 0"
<< endl;
}
}
else
{
// Add a default route with much a worse metric, so traffic can still
// be routed on the tunnel opt-in by binding to the tunnel interface.
out << "route 0.0.0.0 0.0.0.0 vpn_gateway 1000" << endl;
// Ignore pushed settings to add default route
out << "pull-filter ignore \"redirect-gateway \"" << endl;
}
// Set the local address only for alternate transports
const QHostAddress &localAddress = _transportSelector.lastLocalAddress();
if(!localAddress.isNull())
{
out << "local " << localAddress.toString() << endl;
// We can't use nobind with a specific local address. We can set lport
// to 0 to let the network stack pick an ephemeral port though.
out << "lport " << g_settings.localPort() << endl;
}
else if (g_settings.localPort() == 0)
out << "nobind" << endl;
else
out << "lport " << g_settings.localPort() << endl;
out << "cipher " << sanitize(g_settings.cipher()) << endl;
if (!g_settings.cipher().endsWith("GCM"))
out << "auth " << sanitize(g_settings.auth()) << endl;
if (g_settings.mtu() > 0)
{
// TODO: For UDP it's also possible to use "fragment" to enable
// internal datagram fragmentation, allowing us to deal with whatever
// is sent into the tunnel. Unfortunately, this is a setting that
// needs to be matched on the server side; maybe in the future we can
// amend pia-signal-settings with it?
out << "mssfix " << g_settings.mtu() << endl;
}
if(_connectingConfig.proxyType() != ConnectionConfig::ProxyType::None)
{
// If the host resolve step failed, _socksRouteAddress is not set, fail.
if(_connectingConfig.socksHost().isNull())
throw Error{HERE, Error::Code::OpenVPNProxyResolveError};
uint port = 0;
// A Shadowsocks local proxy uses an ephemeral port
if(_connectingConfig.proxyType() == ConnectionConfig::ProxyType::Shadowsocks)
port = _shadowsocksRunner.localPort();
else
port = _connectingConfig.customProxy().port();
// Default to 1080 ourselves - OpenVPN doesn't like 0 here, and we can't
// leave the port blank if we also need to specify "stdin" for auth.
if(port == 0)
port = 1080;
out << "socks-proxy " << _connectingConfig.socksHost().toString() << " " << port;
// If we have a username / password, ask OpenVPN to prompt over the
// management interface.
if(!_connectingConfig.customProxy().username().isEmpty() ||
!_connectingConfig.customProxy().password().isEmpty())
{
out << " stdin";
}
out << endl;
// The default timeout is very long (2 minutes), use a shorter timeout.
// This applies to both the SOCKS and OpenVPN connections, we might
// apply this even when not using a proxy in the future.
out << "connect-timeout 30" << endl;
}
// Always ignore pushed DNS servers and use our own settings.
out << "pull-filter ignore \"dhcp-option DNS \"" << endl;
out << "pull-filter ignore \"dhcp-option DOMAIN local\"" << endl;
out << "<ca>" << endl;
for (const auto& line : g_data.getCertificateAuthority(g_settings.serverCertificate()))
out << line << endl;
out << "</ca>" << endl;
return true;
}
| 38.543587
| 227
| 0.626805
|
realrasengan
|
dde53c0d51fee5b89cc1de9cf7ce3266b65310d8
| 2,167
|
cpp
|
C++
|
UnitManager.cpp
|
Kodeman010/TurnBasedStrategy
|
3a9cd195552dd30cd024322b347d529c87c3597d
|
[
"Zlib"
] | 1
|
2019-11-17T22:31:11.000Z
|
2019-11-17T22:31:11.000Z
|
UnitManager.cpp
|
Kodeman010/TurnBasedStrategy
|
3a9cd195552dd30cd024322b347d529c87c3597d
|
[
"Zlib"
] | null | null | null |
UnitManager.cpp
|
Kodeman010/TurnBasedStrategy
|
3a9cd195552dd30cd024322b347d529c87c3597d
|
[
"Zlib"
] | null | null | null |
#include <fstream>
#include <sstream>
#include "UnitManager.h"
#include "Unit.h"
#include "GameState.h"
#include "GameMap.h"
UnitManager::UnitManager(GameState *gameState)
{
this->gameState = gameState;
}
Unit* UnitManager::FindByPosition(sf::Vector2f position)
{
for (int i = 0; i < units.size(); ++i)
{
if (units[i]->sprite.getPosition() == position)
{
return units[i];
}
}
return nullptr;
}
void UnitManager::LoadUnit()
{
std::ifstream unitFile;
std::string mapName = "maps/";
mapName += gameState->game->mapName;
mapName += "Unit.txt";
unitFile.open(mapName);
if (unitFile.good() == false)
exit(-4);
// load map tiles from file
std::string line = "";
int lineNumber = 1;
int x, y, faction;
std::string name;
while (getline(unitFile, line))
{
switch (lineNumber)
{
case 1: name = line; break;
case 2: faction = atoi(line.c_str()); break;
case 3: x = atoi(line.c_str()); break;
case 4: y = atoi(line.c_str()); break;
}
if (lineNumber % 4 == 0)
{
lineNumber = 0;
Unit *unit = &ReadFromFile(name);
unit->faction = (Faction)faction;
unit->sprite.setPosition(x, y);
for (int i = 0; i < gameState->gameMap->mapTiles.size(); ++i)
{
if (unit->sprite.getPosition() == gameState->gameMap->mapTiles[i].sprite.getPosition())
{
unit->tile = &gameState->gameMap->mapTiles[i];
break;
}
}
if (unit->faction == Red)
unit->sprite.setColor(sf::Color(255, 150, 150));
else if (unit->faction == Blue)
unit->sprite.setColor(sf::Color(150, 150, 255));
units.push_back(unit);
}
++lineNumber;
}
unitFile.close();
}
void UnitManager::SaveToFile(Unit *unit)
{
std::stringstream path;
path << "config/units/" << unit->name << ".txt";
std::ofstream file(path.str());
file << *unit; // store the object to file
file.close();
}
Unit& UnitManager::ReadFromFile(std::string name)
{
std::stringstream path;
path << "config/units/" << name << ".txt";
std::ifstream file(path.str());
Unit *unit = new Unit(gameState);
file >> *unit;
file.close();
return *unit;
}
| 22.572917
| 92
| 0.602677
|
Kodeman010
|
ddedfd68e1f4213a57caff436cb28f74bbad86c9
| 2,086
|
cpp
|
C++
|
android-31/java/text/CollationElementIterator.cpp
|
YJBeetle/QtAndroidAPI
|
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
|
[
"Apache-2.0"
] | 12
|
2020-03-26T02:38:56.000Z
|
2022-03-14T08:17:26.000Z
|
android-31/java/text/CollationElementIterator.cpp
|
YJBeetle/QtAndroidAPI
|
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
|
[
"Apache-2.0"
] | 1
|
2021-01-27T06:07:45.000Z
|
2021-11-13T19:19:43.000Z
|
android-29/java/text/CollationElementIterator.cpp
|
YJBeetle/QtAndroidAPI
|
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
|
[
"Apache-2.0"
] | 3
|
2021-02-02T12:34:55.000Z
|
2022-03-08T07:45:57.000Z
|
#include "../../JIntArray.hpp"
#include "../../JString.hpp"
#include "../lang/StringBuffer.hpp"
#include "./RuleBasedCollator.hpp"
#include "./CollationElementIterator.hpp"
namespace java::text
{
// Fields
jint CollationElementIterator::NULLORDER()
{
return getStaticField<jint>(
"java.text.CollationElementIterator",
"NULLORDER"
);
}
// QJniObject forward
CollationElementIterator::CollationElementIterator(QJniObject obj) : JObject(obj) {}
// Constructors
// Methods
jint CollationElementIterator::primaryOrder(jint arg0)
{
return callStaticMethod<jint>(
"java.text.CollationElementIterator",
"primaryOrder",
"(I)I",
arg0
);
}
jshort CollationElementIterator::secondaryOrder(jint arg0)
{
return callStaticMethod<jshort>(
"java.text.CollationElementIterator",
"secondaryOrder",
"(I)S",
arg0
);
}
jshort CollationElementIterator::tertiaryOrder(jint arg0)
{
return callStaticMethod<jshort>(
"java.text.CollationElementIterator",
"tertiaryOrder",
"(I)S",
arg0
);
}
jint CollationElementIterator::getMaxExpansion(jint arg0) const
{
return callMethod<jint>(
"getMaxExpansion",
"(I)I",
arg0
);
}
jint CollationElementIterator::getOffset() const
{
return callMethod<jint>(
"getOffset",
"()I"
);
}
jint CollationElementIterator::next() const
{
return callMethod<jint>(
"next",
"()I"
);
}
jint CollationElementIterator::previous() const
{
return callMethod<jint>(
"previous",
"()I"
);
}
void CollationElementIterator::reset() const
{
callMethod<void>(
"reset",
"()V"
);
}
void CollationElementIterator::setOffset(jint arg0) const
{
callMethod<void>(
"setOffset",
"(I)V",
arg0
);
}
void CollationElementIterator::setText(JString arg0) const
{
callMethod<void>(
"setText",
"(Ljava/lang/String;)V",
arg0.object<jstring>()
);
}
void CollationElementIterator::setText(JObject arg0) const
{
callMethod<void>(
"setText",
"(Ljava/text/CharacterIterator;)V",
arg0.object()
);
}
} // namespace java::text
| 18.460177
| 85
| 0.675935
|
YJBeetle
|
ddf1a54d7bd8f520010f7bf14893b7f49c3bccbf
| 788
|
cpp
|
C++
|
hyper/src/hyper/ast/expressions/binary_expression.cpp
|
HyperionOrg/HyperLang
|
30f7a1707d00fb5cc6dc22913764389a3b998f09
|
[
"MIT"
] | null | null | null |
hyper/src/hyper/ast/expressions/binary_expression.cpp
|
HyperionOrg/HyperLang
|
30f7a1707d00fb5cc6dc22913764389a3b998f09
|
[
"MIT"
] | null | null | null |
hyper/src/hyper/ast/expressions/binary_expression.cpp
|
HyperionOrg/HyperLang
|
30f7a1707d00fb5cc6dc22913764389a3b998f09
|
[
"MIT"
] | null | null | null |
/*
* Copyright (c) 2022-present, SkillerRaptor <skillerraptor@protonmail.com>
*
* SPDX-License-Identifier: MIT
*/
#include "hyper/ast/expressions/binary_expression.hpp"
namespace hyper
{
BinaryExpression::BinaryExpression(
SourceRange source_range,
Operation operation,
Expression *left,
Expression *right)
: Expression(source_range)
, m_operation(operation)
, m_left(std::move(left))
, m_right(std::move(right))
{
}
BinaryExpression::~BinaryExpression()
{
delete m_left;
delete m_right;
}
BinaryExpression::Operation BinaryExpression::operation() const
{
return m_operation;
}
const Expression *BinaryExpression::left() const
{
return m_left;
}
const Expression *BinaryExpression::right() const
{
return m_right;
}
} // namespace hyper
| 17.909091
| 75
| 0.727157
|
HyperionOrg
|
ddf89d2d0aaaf1d235d4cc3fb97bbad7a553a749
| 364
|
cpp
|
C++
|
vSRO-GameServer/Silkroad/CRegionManagerBody.cpp
|
m1xawy/vSRO-ServerAddon
|
ff7971c4846bbf28e4758bad79cafb64133456bf
|
[
"MIT"
] | 13
|
2021-07-11T19:41:49.000Z
|
2022-03-14T23:43:55.000Z
|
vSRO-GameServer/Silkroad/CRegionManagerBody.cpp
|
m1xawy/vSRO-ServerAddon
|
ff7971c4846bbf28e4758bad79cafb64133456bf
|
[
"MIT"
] | 10
|
2021-07-12T21:41:03.000Z
|
2022-02-08T16:56:55.000Z
|
vSRO-GameServer/Silkroad/CRegionManagerBody.cpp
|
m1xawy/vSRO-ServerAddon
|
ff7971c4846bbf28e4758bad79cafb64133456bf
|
[
"MIT"
] | 11
|
2021-07-12T13:05:09.000Z
|
2022-03-10T02:11:59.000Z
|
#include "CRegionManagerBody.h"
CRegionManagerBody* CRegionManagerBody::GetInstance()
{
return *reinterpret_cast<CRegionManagerBody**>(0x400000 + 0x8C387C);
}
bool CRegionManagerBody::ResolveCellAndHeight(NavInfo* NavInfoPtr)
{
return reinterpret_cast<bool(__thiscall*)(CRegionManagerBody*, NavInfo*, int)>(0x400000 + 0x58B1D0)(GetInstance(), NavInfoPtr, 0);
}
| 33.090909
| 131
| 0.796703
|
m1xawy
|
ddfa6b005f4d0f9449adf8375cc1ad67fb1545bc
| 435
|
cpp
|
C++
|
git_C++/SET I/Prob3/main.cpp
|
soryncrash13/old-C-stuff
|
d6f7b3573c1f81597795cea75c5f76fd95c4395b
|
[
"MIT"
] | 1
|
2017-09-30T09:58:07.000Z
|
2017-09-30T09:58:07.000Z
|
git_C++/SET I/Prob3/main.cpp
|
sorinmiroiu97/old-CPP-stuff
|
d6f7b3573c1f81597795cea75c5f76fd95c4395b
|
[
"MIT"
] | null | null | null |
git_C++/SET I/Prob3/main.cpp
|
sorinmiroiu97/old-CPP-stuff
|
d6f7b3573c1f81597795cea75c5f76fd95c4395b
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
int main()
{
int x,y,aux;
cout << "Introduceti primul numar:";cin >> x;
cout << "Introduceti al doilea numar:";cin >> y;
cout << "Primul numar este: " << x << endl;
cout << "Al doilea numar este: " << y << endl;
aux=y;
y=x;
x=aux;
cout << "Valorile celor 2 numere interschimbate sunt: " << x << " " << y << endl;
return 1;
}
| 19.772727
| 88
| 0.514943
|
soryncrash13
|
ddfb799da4aea8441793b32182d314d95a5b8df2
| 2,105
|
cpp
|
C++
|
Final_Fantasy_Mystery_World/Final_Fantasy_Mystery_World/p1Follow.cpp
|
polarpathgames/Polar-Path
|
cf0eed03bbd6478c4fdd1eb074f48a2ceb78e0d6
|
[
"MIT"
] | 9
|
2019-03-05T07:26:04.000Z
|
2019-10-09T15:57:45.000Z
|
Final_Fantasy_Mystery_World/Final_Fantasy_Mystery_World/p1Follow.cpp
|
polarpathgames/Polar-Path
|
cf0eed03bbd6478c4fdd1eb074f48a2ceb78e0d6
|
[
"MIT"
] | 114
|
2019-03-10T09:35:12.000Z
|
2019-06-10T21:39:12.000Z
|
Final_Fantasy_Mystery_World/Final_Fantasy_Mystery_World/p1Follow.cpp
|
polarpathgames/Polar-Path
|
cf0eed03bbd6478c4fdd1eb074f48a2ceb78e0d6
|
[
"MIT"
] | 3
|
2019-02-25T16:12:40.000Z
|
2019-11-19T20:48:06.000Z
|
#include "p1Follow.h"
#include "p1Particle.h"
#include "m1Render.h"
#include "App.h"
#include "p2Log.h"
p1Follow::p1Follow(e1Entity* element, iPoint* object, SDL_Rect initial_rect, iPoint area, iPoint timelife, int num_textures, int num_particles, bool active, bool mouse, const iPoint& offset):
area(area), number_particles(num_particles), isMouse(mouse),timelife(timelife),n_textures(num_textures),size_rect(initial_rect.w), offset(offset)
{
if (element != nullptr)
{
pos.x = element->GetPosition().x + offset.x;
pos.y = element->GetPosition().y + offset.y;
element_to_follow = element;
object_follow = nullptr;
}
else
{
pos.x = object->x + offset.x;
pos.y = object->y + offset.y;
object_follow = object;
element_to_follow = nullptr;
}
for (int i = 0; i < num_particles; i++)
{
p1Particle* temp = DBG_NEW p1Particle(pos, area, timelife, fPoint(0,0), P_NON, initial_rect, size_rect, num_textures, active);
particle.push_back(temp);
}
}
p1Follow::~p1Follow()
{
}
bool p1Follow::Update(float dt)
{
if (element_to_follow != nullptr)
{
pos.x = element_to_follow->GetPosition().x + offset.x;
pos.y = element_to_follow->GetPosition().y + offset.y;
}
else
{
Update_position(object_follow);
}
return true;
}
bool p1Follow::PostUpdate()
{
render(pos);
return true;
}
void p1Follow::render(fPoint pos)
{
if (active)
{
for (int i = 0; i < number_particles; i++)
{
if (particle[i]->isDead())
{
particle[i]->Modify(pos, area, timelife, iPoint(0, n_textures));
}
}
}
for (int i = 0; i < number_particles; i++)
{
particle[i]->render();
}
}
void p1Follow::Update_position(iPoint* element)
{
if (isMouse == false)
{
pos.x = element->x + offset.x;
pos.y = element->y + offset.y;
}
else
{
pos.x = element->x + offset.x - App->render->camera.x * 0.5F;
pos.y = element->y + offset.y - App->render->camera.y * 0.5F;
}
}
void p1Follow::SetEntityToFollow(e1Entity * ent)
{
object_follow = nullptr;
element_to_follow = ent;
}
void p1Follow::SetObjectToFollow(iPoint * obj)
{
object_follow = obj;
element_to_follow = nullptr;
}
| 20.637255
| 191
| 0.674584
|
polarpathgames
|
ddfda440e98ee8b0e70e5fef9bc7bd8615bbcaaf
| 1,148
|
cpp
|
C++
|
test/src/ConcurrentQueueTest.cpp
|
rsitko92/thread-pool
|
997281de2978acf6527ebfa725f9326b210988c8
|
[
"MIT"
] | 1
|
2020-12-18T02:18:20.000Z
|
2020-12-18T02:18:20.000Z
|
test/src/ConcurrentQueueTest.cpp
|
rsitko92/thread-pool
|
997281de2978acf6527ebfa725f9326b210988c8
|
[
"MIT"
] | null | null | null |
test/src/ConcurrentQueueTest.cpp
|
rsitko92/thread-pool
|
997281de2978acf6527ebfa725f9326b210988c8
|
[
"MIT"
] | null | null | null |
#include "ConcurrentQueue.hpp"
#include "gtest/gtest.h"
#include <memory>
#include <vector>
namespace
{
using namespace thread_pool;
using namespace ::testing;
}
class ConcurrentQueueTest : public Test
{
protected:
using ItemType = std::unique_ptr<int>;
void addItemToQueue(int value)
{
auto item = std::make_unique<int>(value);
m_queue.push(std::move(item));
}
ConcurrentQueue<ItemType> m_queue;
};
TEST_F(ConcurrentQueueTest, PushItemsAndPop)
{
addItemToQueue(3);
addItemToQueue(15);
addItemToQueue(1);
ASSERT_FALSE(m_queue.empty());
ASSERT_EQ(m_queue.size(), 3u);
ItemType item;
ASSERT_TRUE(m_queue.pop(item));
ASSERT_TRUE(item);
ASSERT_EQ(*item, 3);
ASSERT_TRUE(m_queue.pop(item));
ASSERT_TRUE(item);
ASSERT_EQ(*item, 15);
ASSERT_TRUE(m_queue.pop(item));
ASSERT_TRUE(item);
ASSERT_EQ(*item, 1);
ASSERT_TRUE(m_queue.empty());
ASSERT_EQ(m_queue.size(), 0u);
}
TEST_F(ConcurrentQueueTest, TryPopItemOnStoppedEmptyQueue)
{
ASSERT_TRUE(m_queue.empty());
ASSERT_EQ(m_queue.size(), 0u);
ItemType item;
m_queue.stop();
ASSERT_FALSE(m_queue.pop(item));
ASSERT_FALSE(item);
}
| 19.133333
| 58
| 0.714286
|
rsitko92
|
ddffd821da3bb3b3e5cc5377a21423beb20b3a7d
| 322
|
cpp
|
C++
|
Easy/Add_digits.cpp
|
AnanyaDas162/Leetcode-Solutions
|
00f3982f2a48cc7ef3341565b237a1f9637d26f5
|
[
"MIT"
] | 1
|
2021-11-21T16:04:59.000Z
|
2021-11-21T16:04:59.000Z
|
Easy/Add_digits.cpp
|
AnanyaDas162/Leetcode-Solutions
|
00f3982f2a48cc7ef3341565b237a1f9637d26f5
|
[
"MIT"
] | null | null | null |
Easy/Add_digits.cpp
|
AnanyaDas162/Leetcode-Solutions
|
00f3982f2a48cc7ef3341565b237a1f9637d26f5
|
[
"MIT"
] | null | null | null |
class Solution {
public:
int addDigits(int num) {
int result;
if (num == 0)
{
result = 0;
}
else if (num % 9 == 0)
{
result = 9;
}
else
{
result = num % 9;
}
cout<<result;
return result;
}
};
| 16.1
| 29
| 0.350932
|
AnanyaDas162
|
ddfff1a42a80156c33e7392f7f64e1343ca1b7ec
| 181
|
cc
|
C++
|
apps/cinder_app_main.cc
|
aadarshkrishnan/CinderChess
|
5b055f000f96814081f0404a9e010b30e5e430d3
|
[
"MIT"
] | null | null | null |
apps/cinder_app_main.cc
|
aadarshkrishnan/CinderChess
|
5b055f000f96814081f0404a9e010b30e5e430d3
|
[
"MIT"
] | null | null | null |
apps/cinder_app_main.cc
|
aadarshkrishnan/CinderChess
|
5b055f000f96814081f0404a9e010b30e5e430d3
|
[
"MIT"
] | null | null | null |
#include "game.h"
using chess::Game;
void prepareSettings(Game::Settings *settings) {
settings->setResizable(false);
}
CINDER_APP(Game, ci::app::RendererGl, prepareSettings);
| 20.111111
| 55
| 0.740331
|
aadarshkrishnan
|
fb000316f4243052b4c8dee45df263553e466391
| 2,634
|
cpp
|
C++
|
NamelessEngine/Transform.cpp
|
mattateusb7/NamelessEngine
|
14055477b6f873baab7b01ef8508f559a0b72fc0
|
[
"MIT"
] | 2
|
2018-07-19T12:19:08.000Z
|
2018-07-20T15:20:32.000Z
|
NamelessEngine/Transform.cpp
|
mattateusb7/NamelessEngine-Framework
|
14055477b6f873baab7b01ef8508f559a0b72fc0
|
[
"MIT"
] | null | null | null |
NamelessEngine/Transform.cpp
|
mattateusb7/NamelessEngine-Framework
|
14055477b6f873baab7b01ef8508f559a0b72fc0
|
[
"MIT"
] | null | null | null |
#include "Transform.h"
_NL::Component::Transform::Transform()
{
}
char* _NL::Component::Transform::getTypeName()
{
return "_NL::Component::Transform";
}
_NL::Component::Transform::~Transform()
{
}
glm::vec3 _NL::Component::Transform::getRotatedForwardVector()
{
return this->transform.QuaternionRotation * this->forwardVector;
}
glm::vec3 _NL::Component::Transform::getParentedVector(glm::vec3 Vector)
{
return this->transform.QuaternionRotation * Vector;
}
glm::vec3 _NL::Component::Transform::eulerAngles()
{
return glm::eulerAngles(transform.QuaternionRotation);
}
glm::quat _NL::Component::Transform::LookAt(glm::vec3 target, GLfloat x, GLfloat y, GLfloat z)
{
return LookAt(target, glm::vec3(x, y, z));
}
glm::quat _NL::Component::Transform::LookAt(glm::vec3 target, glm::vec3 EyeAxis)
{
glm::vec3 forward = glm::normalize(target - transform.position); //get new Local Z
glm::vec3 worldForward = EyeAxis; //get World Z
GLfloat dot = glm::dot(worldForward, forward); //getAngle LocalZ > WorldZ
GLfloat rotationAngle = glm::acos(dot); //AngleIn degrees
glm::vec3 rotationAxis = glm::normalize(glm::cross(forward, worldForward)); //localUP
return glm::toQuat(glm::rotate(glm::mat4(), rotationAngle, -rotationAxis));
}
//glm::quat _NL::Component::Transform::QuaternionFromAxisAngle(glm::vec3 ax, GLfloat angle) {
//
// ax = glm::normalize(ax);
// GLfloat qw = cos(angle / 2);
// GLfloat qx = ax.x * sin(angle / 2);
// GLfloat qy = ax.y * sin(angle / 2);
// GLfloat qz = ax.z * sin(angle / 2);
// return glm::normalize(glm::quat(qw, qx, qy, qz));
//}
glm::quat _NL::Component::Transform::EulerRotation(GLfloat x, GLfloat y, GLfloat z)
{
return glm::quat(glm::vec3(x, y, z));
}
glm::quat _NL::Component::Transform::EulerRotation(glm::vec3 eulerAngles)
{
return glm::quat(eulerAngles);
}
void _NL::Component::Transform::getModelMatrixDecompose(glm::vec3& Translation, glm::quat& Rotation, glm::vec3 Scale)
{
glm::decompose(ModelMatrix, glm::vec3(), glm::quat(), Translation, glm::vec3(), glm::vec4());
}
glm::vec3 _NL::Component::Transform::getModelMatrixTranslation()
{
glm::vec3 Translation;
glm::decompose(ModelMatrix, glm::vec3(), glm::quat(), Translation, glm::vec3(), glm::vec4());
return Translation;
}
glm::quat _NL::Component::Transform::getModelMatrixRotation()
{
glm::quat Rotation;
glm::decompose(ModelMatrix, glm::vec3(), Rotation, glm::vec3(), glm::vec3(), glm::vec4());
return Rotation;
}
glm::vec3 _NL::Component::Transform::getModelMatrixScale()
{
glm::vec3 Scale;
glm::decompose(ModelMatrix, Scale, glm::quat(), glm::vec3(), glm::vec3(), glm::vec4());
return Scale;
}
| 27.4375
| 117
| 0.702354
|
mattateusb7
|
fb05bd2fd174037f457dad798be09746603437c1
| 2,628
|
cpp
|
C++
|
test/beast/json/key_param.cpp
|
djarek/BeastLounge
|
353b2397cf8507d6e36ed913d6682ae2d827a1ab
|
[
"BSL-1.0"
] | null | null | null |
test/beast/json/key_param.cpp
|
djarek/BeastLounge
|
353b2397cf8507d6e36ed913d6682ae2d827a1ab
|
[
"BSL-1.0"
] | null | null | null |
test/beast/json/key_param.cpp
|
djarek/BeastLounge
|
353b2397cf8507d6e36ed913d6682ae2d827a1ab
|
[
"BSL-1.0"
] | null | null | null |
//
// Copyright (c) 2018-2019 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/boostorg/beast
//
// Test that header file is self-contained.
#include <boost/beast/_experimental/json/key_param.hpp>
#include <boost/beast/_experimental/unit_test/suite.hpp>
namespace boost {
namespace beast {
namespace json {
namespace {
enum class te
{
a, b, c
};
string_view
make_key_string(te e)
{
switch(e)
{
case te::a: return "a";
case te::b: return "b";
case te::c:
break;
}
return "c";
}
} // (anon)
template<>
struct is_key_enum<te> : std::true_type
{
};
class key_param_test : public unit_test::suite
{
public:
using kp = key_param;
BOOST_STATIC_ASSERT(
is_key_enum<te>::value);
static
string_view
ks(string_view s)
{
return s;
}
void
testMembers()
{
BEAST_EXPECT(kp("x") == "x");
BEAST_EXPECT(kp("y") == "y");
BEAST_EXPECT(kp(te::a) == "a");
BEAST_EXPECT(kp(te::b) == "b");
BEAST_EXPECT(kp(te::c) == "c");
BEAST_EXPECT(! (kp("a") == kp("b")));
BEAST_EXPECT( kp("a") != kp("b"));
BEAST_EXPECT( kp("a") < kp("b"));
BEAST_EXPECT( kp("a") <= kp("b"));
BEAST_EXPECT(! (kp("a") > kp("b")));
BEAST_EXPECT(! (kp("a") >= kp("b")));
BEAST_EXPECT(! (kp(te::a) == kp("b")));
BEAST_EXPECT( kp(te::a) != kp("b"));
BEAST_EXPECT( kp(te::a) < kp("b"));
BEAST_EXPECT( kp(te::a) <= kp("b"));
BEAST_EXPECT(! (kp(te::a) > kp("b")));
BEAST_EXPECT(! (kp(te::a) >= kp("b")));
BEAST_EXPECT(! (kp("a") == kp(te::b)));
BEAST_EXPECT( kp("a") != kp(te::b));
BEAST_EXPECT( kp("a") < kp(te::b));
BEAST_EXPECT( kp("a") <= kp(te::b));
BEAST_EXPECT(! (kp("a") > kp(te::b)));
BEAST_EXPECT(! (kp("a") >= kp(te::b)));
BEAST_EXPECT(! (kp(te::a) == kp(te::b)));
BEAST_EXPECT( kp(te::a) != kp(te::b));
BEAST_EXPECT( kp(te::a) < kp(te::b));
BEAST_EXPECT( kp(te::a) <= kp(te::b));
BEAST_EXPECT(! (kp(te::a) > kp(te::b)));
BEAST_EXPECT(! (kp(te::a) >= kp(te::b)));
BEAST_EXPECT(ks(kp("a")) == "a");
BEAST_EXPECT(ks(kp(te::b)) == "b");
}
void run() override
{
testMembers();
}
};
BEAST_DEFINE_TESTSUITE(beast,json,key_param);
} // json
} // beast
} // boost
| 23.256637
| 79
| 0.521309
|
djarek
|
fb0f90eb95376d7a47abd46b3b52b37d4f6de9d0
| 6,094
|
cpp
|
C++
|
src/modules/entropyMap.cpp
|
EvilzoneLabs/BinDyn
|
ddaba9f001ab907aed0e7f719ba647beec2cf182
|
[
"MIT"
] | 4
|
2017-06-30T10:46:36.000Z
|
2021-04-26T18:25:10.000Z
|
src/modules/entropyMap.cpp
|
EvilzoneLabs/BinDyn
|
ddaba9f001ab907aed0e7f719ba647beec2cf182
|
[
"MIT"
] | 1
|
2015-04-13T14:15:13.000Z
|
2015-04-13T14:15:13.000Z
|
src/modules/entropyMap.cpp
|
EvilzoneLabs/BinDyn
|
ddaba9f001ab907aed0e7f719ba647beec2cf182
|
[
"MIT"
] | null | null | null |
/***************************************
* entropyMap.cpp
* Defines the Class declared in entropyMap.h
*
* PreConditions: Program Started, User/File loaded
* Main Use: Scan file generate plot based on entropy
* of windows at specified jump distances.
* jumpsize and windowsize can be played with
* for best effect.
* PostCondtions: Done scanning / reporting.
*
* Gotchas: currently a floating point error on files
* less than 1 kb, have not found time to
* find it yet.
* Yes there are lot's of casts, it sucks,
* I know.
**************************************/
#include "entropyMap.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QString>
#include <cmath>
EntropyMap::EntropyMap()
{
//Dat Layout Objects
locality = new QCheckBox(" Preserve Locality?");
output = new QTextEdit;
threshold = new QLineEdit( );
threshold -> setText( "150" );
jump = new QSlider( Qt::Horizontal );
jump -> setRange( 1, 20 );
jump -> setValue( 10 );
range = new QSlider( Qt::Horizontal );
range -> setRange( 50, 500 );
range -> setValue( 150 );
plot = new Plotter( );
scroll = new QScrollArea( );
scroll -> setWidget( plot );
QLabel * rangeLabel = new QLabel( "Window Size" );
QLabel * jumpLabel = new QLabel( "Jump Size" );
QLabel * thresholdLabel = new QLabel( "Entropy Threshold" );
listThreshold = new QCheckBox( "List Positions Over Entropy Threshold?" );
//Dat Layout.
QVBoxLayout * layout = new QVBoxLayout( );
QHBoxLayout * bottom = new QHBoxLayout( );
QHBoxLayout * buttons = new QHBoxLayout( );
buttons -> addWidget(locality);
buttons -> addWidget( listThreshold );
buttons -> addWidget( thresholdLabel );
buttons -> addWidget( threshold );
buttons -> addWidget( jumpLabel );
buttons -> addWidget( jump );
buttons -> addWidget( rangeLabel );
buttons -> addWidget( range );
bottom -> addWidget( scroll );
bottom -> addWidget( output );
output -> setMaximumWidth( 250 );
layout -> addLayout( buttons );
layout -> addLayout( bottom );
setLayout( layout );
}
void EntropyMap::clean()
{
output -> clear();
plot -> clean();
}
void EntropyMap::analysis( char * fileString, size_t fileSize, QProgressBar * pb )
{
//Set up some variables
unsigned int jumpSize = jump -> value();
unsigned int windowRange = range -> value();
double entropyThreshold = threshold -> text().toDouble();
unsigned char tempEntropy = 0;
//Set up the Point array
point * localPoints = new point[ fileSize / jumpSize ];
//Progress bar thing
size_t pbChunk = (fileSize / jumpSize) / 100;
if (!pbChunk) pbChunk = 1;
if (!locality->isChecked())
{
//Get Sizes
unsigned int width = scroll->width() - 10;
unsigned int height = scroll->height();
//Get Pensize
unsigned int penSize = sqrt((width * height) / ( fileSize / jumpSize ));
if ( penSize == 0 ) { penSize = 1; }
for ( size_t counter = 0; counter < (fileSize - windowRange) / jumpSize; counter++ )
{
if (!(counter % pbChunk)) pb->setValue(pb->value() + 1); //Progress bar.
tempEntropy = entropy(reinterpret_cast<unsigned char*>(fileString + counter * jumpSize) , windowRange);
if ( tempEntropy < entropyThreshold )
{
localPoints[ counter ].r = tempEntropy;
localPoints[ counter ].b = 0;
localPoints[ counter ].g = 0;
}
else
{
if (listThreshold -> isChecked())
{
output -> append("testtest");
}
localPoints[ counter ].b = tempEntropy;
localPoints[ counter ].r = 0;
localPoints[ counter ].g = 0;
}
localPoints[ counter ].x = (counter % (width / penSize)) * penSize;
localPoints[ counter ].y = (counter / (width / penSize)) * penSize ;
}
plot -> plot(localPoints, penSize, fileSize / jumpSize, width, (fileSize / jumpSize / width)*penSize);
}
else
{
//Get penSize
unsigned int penSize = sqrt( (scroll->width() * scroll->height()) / fileSize);
if ( penSize == 0 ) { penSize = 1; }
//Generate N, N must be a value that is a power of 2, IE 128,256,512,1024,etc.
// Will limit these to 1024, sorry folks with high res, use the other monitor for porn
unsigned int dimension;
unsigned int testSize= scroll->width() / penSize;
for (dimension = 2; dimension * 2 < testSize && dimension != 1024; dimension *= 2);
unsigned int blockSize = dimension * dimension;
//Will need these later
int tempX;
int tempY;
//Do the same thing as above but with awful awful things at the end
unsigned int blockCount = 0;
for ( size_t counter = 0; counter < (fileSize - windowRange) / jumpSize; counter++ )
{
//Progress bar.
if (!(counter % pbChunk)) pb->setValue(pb->value() + 1);
//Increase if we're in a new block
if (!(counter % blockSize) && counter != 0) blockCount += 1;
//Get moar entropy
tempEntropy = entropy(reinterpret_cast<unsigned char*>( fileString + counter * jumpSize ), windowRange);
if ( tempEntropy < entropyThreshold )
{
localPoints[ counter ].r = tempEntropy;
localPoints[ counter ].b = localPoints[ counter ].g = 0;
}
else
{
if (listThreshold -> isChecked())
{
output -> append("testtest");
}
localPoints[ counter ].b = tempEntropy;
localPoints[ counter ].r = localPoints[ counter ].g = 0;
}
plot->d2xy(dimension, counter % blockSize, &tempX, &tempY);
localPoints[ counter ].x = penSize * tempX;
localPoints[ counter ].y = penSize * (tempY + (blockCount * dimension ));
}
plot->plot(localPoints, penSize, fileSize / jumpSize, penSize*dimension, penSize*fileSize/dimension);
}
}
unsigned char EntropyMap::entropy(unsigned char *passed, unsigned int size)
{
//Generate a buffer, find the entropy via histrogram, return.
double entropy = 0.0;
unsigned int i;
int temp[256] = {0};
for (i = 0; i < size; ++i) ++temp[passed[i]];
for (i = 0; i < 256; ++i)
if (temp[i])
entropy -= static_cast<double>(temp[i]) / size * log2(static_cast<double>(temp[i])/size);
return static_cast<unsigned char>(entropy * 30);
}
| 34.822857
| 110
| 0.637184
|
EvilzoneLabs
|
fb14f148ccc66fe043318da9d717ba199d77f783
| 322
|
cpp
|
C++
|
Class 4 - solve class/J.cpp
|
pioneerAlpha/CP_Beginner_B1
|
fd743b956188e927ac999e108df2f081d4f5fcb2
|
[
"Apache-2.0"
] | 4
|
2020-07-10T06:37:52.000Z
|
2022-01-03T17:14:21.000Z
|
Class 4 - solve class/J.cpp
|
pioneerAlpha/CP_Beginner_B1
|
fd743b956188e927ac999e108df2f081d4f5fcb2
|
[
"Apache-2.0"
] | null | null | null |
Class 4 - solve class/J.cpp
|
pioneerAlpha/CP_Beginner_B1
|
fd743b956188e927ac999e108df2f081d4f5fcb2
|
[
"Apache-2.0"
] | 4
|
2020-11-23T16:58:45.000Z
|
2021-01-06T20:20:57.000Z
|
#include<bits/stdc++.h>
#define fastio ios_base::sync_with_stdio(false),cin.tie(NULL)
#define ll long long
using namespace std;
/*fast io
ios_base::sync_with_stdio(false);
cin.tie(NULL);
*/
int main()
{
fastio;
ll n;
cin>>n;
if(n&1) cout<<(n-1)/2 - n<<endl;
else cout<<n/2<<endl;
return 0;
}
| 13.416667
| 61
| 0.621118
|
pioneerAlpha
|
fb151009dd9ebb97b04faf982ddafaf48deead67
| 570
|
cpp
|
C++
|
server/server.cpp
|
serkanturkkolu/tcpip_abstraction
|
2d317abc53c20ea8118449b2878a70c37816a5e4
|
[
"MIT"
] | null | null | null |
server/server.cpp
|
serkanturkkolu/tcpip_abstraction
|
2d317abc53c20ea8118449b2878a70c37816a5e4
|
[
"MIT"
] | null | null | null |
server/server.cpp
|
serkanturkkolu/tcpip_abstraction
|
2d317abc53c20ea8118449b2878a70c37816a5e4
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include "include/tcpip.h"
using namespace std;
int main()
{
TcpIp server(TcpIp::Server);
auto sk = server.socket(8881);
std::cout << "Sock: " << sk << endl;
auto bd=server.bind();
std::cout << "Bind: " << bd << endl;
auto ls = server.listen();
std::cout << "Listened: " << ls << endl;
auto ac = server.accept();
std::cout << "Accepted: " << ac << endl;
server.write((u_char*)"test",4);
std::cout << "Connected Ip Address: " << server.getConnectedIpAddress() << std::endl;
cin.get();
return 0;
}
| 28.5
| 90
| 0.570175
|
serkanturkkolu
|
fb15ffdcf9a2e30a90cf703e36287f45d6c38259
| 813
|
cpp
|
C++
|
CODECHEF/SEPT15/MSTEP/main.cpp
|
AssemblerTC/Workspace
|
bdb27e2165ab61471b3515c4a1684e5bdf2238d6
|
[
"Unlicense"
] | null | null | null |
CODECHEF/SEPT15/MSTEP/main.cpp
|
AssemblerTC/Workspace
|
bdb27e2165ab61471b3515c4a1684e5bdf2238d6
|
[
"Unlicense"
] | null | null | null |
CODECHEF/SEPT15/MSTEP/main.cpp
|
AssemblerTC/Workspace
|
bdb27e2165ab61471b3515c4a1684e5bdf2238d6
|
[
"Unlicense"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
struct RTC{~RTC(){cerr << "Time: " << clock() * 1.0 / CLOCKS_PER_SEC <<" seconds\n";}} runtimecount;
#define DBG(X) cerr << #X << " = " << X << '\n';
#define mp make_pair
#define mt make_tuple
#define pb push_back
#define eb emplace_back
#define sz(x) ((int)(x).size())
#define all(c) (c).begin(),(c).end()
#define forn(i, n) for (int i = 0; i < (n); i++)
pair<int,int> p[500 * 500 + 2];
int main() {
int t;
scanf("%d", &t);
while (t--) {
int n;
scanf("%d", &n);
forn (i, n) forn (j, n) {
int x;
scanf("%d", &x);
p[x] = {i, j};
}
int ans = 0;
for (int upto = n * n, i = 2; i <= upto; i++)
ans += abs(p[i].first - p[i - 1].first) + abs(p[i].second - p[i - 1].second);
printf("%d\n", ans);
}
return 0;
}
| 23.911765
| 100
| 0.503075
|
AssemblerTC
|
fb1ca728d5b325dfd821e546875935bd15f09ae0
| 13,481
|
cpp
|
C++
|
src/caffe/layers/pooling_td_layer.cpp
|
niuchuangnn/Caffe_custom
|
9e347d238ffcfb7af0b628230a2feb7ddd98adda
|
[
"BSD-2-Clause"
] | null | null | null |
src/caffe/layers/pooling_td_layer.cpp
|
niuchuangnn/Caffe_custom
|
9e347d238ffcfb7af0b628230a2feb7ddd98adda
|
[
"BSD-2-Clause"
] | null | null | null |
src/caffe/layers/pooling_td_layer.cpp
|
niuchuangnn/Caffe_custom
|
9e347d238ffcfb7af0b628230a2feb7ddd98adda
|
[
"BSD-2-Clause"
] | null | null | null |
//
// Created by Niu Chuang on 17-9-26.
//
#include <algorithm>
#include <cfloat>
#include <vector>
#include <cstdio>
#include <iostream>
using namespace std;
#include "caffe/common.hpp"
#include "caffe/layer.hpp"
#include "caffe/syncedmem.hpp"
#include "caffe/util/math_functions.hpp"
#include "caffe/layers/pooling_td_layer.hpp"
namespace caffe {
using std::min;
using std::max;
template <typename Dtype>
void PoolingTDLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
UnpoolingParameter unpool_param = this->layer_param_.unpooling_param();
CHECK(!unpool_param.has_kernel_size() !=
!(unpool_param.has_kernel_h() && unpool_param.has_kernel_w()))
<< "Filter size is kernel_size OR kernel_h and kernel_w; not both";
CHECK(unpool_param.has_kernel_size() ||
(unpool_param.has_kernel_h() && unpool_param.has_kernel_w()))
<< "For non-square filters both kernel_h and kernel_w are required.";
CHECK((!unpool_param.has_pad() && unpool_param.has_pad_h()
&& unpool_param.has_pad_w())
|| (!unpool_param.has_pad_h() && !unpool_param.has_pad_w()))
<< "pad is pad OR pad_h and pad_w are required.";
CHECK((!unpool_param.has_stride() && unpool_param.has_stride_h()
&& unpool_param.has_stride_w())
|| (!unpool_param.has_stride_h() && !unpool_param.has_stride_w()))
<< "Stride is stride OR stride_h and stride_w are required.";
CHECK((!unpool_param.has_unpool_size() && unpool_param.has_unpool_h()
&& unpool_param.has_unpool_w())
|| (unpool_param.has_unpool_size() &&!unpool_param.has_unpool_h()
&& !unpool_param.has_unpool_w()))
<< "Unpool is unpool_size OR unpool_h and unpool_w are required.";
if (unpool_param.has_kernel_size()) {
kernel_h_ = kernel_w_ = unpool_param.kernel_size();
} else {
kernel_h_ = unpool_param.kernel_h();
kernel_w_ = unpool_param.kernel_w();
}
CHECK_GT(kernel_h_, 0) << "Filter dimensions cannot be zero.";
CHECK_GT(kernel_w_, 0) << "Filter dimensions cannot be zero.";
if (!unpool_param.has_pad_h()) {
pad_h_ = pad_w_ = unpool_param.pad();
} else {
pad_h_ = unpool_param.pad_h();
pad_w_ = unpool_param.pad_w();
}
CHECK_EQ(pad_h_, 0) << "currently, only zero padding is allowed.";
CHECK_EQ(pad_w_, 0) << "currently, only zero padding is allowed.";
if (!unpool_param.has_stride_h()) {
stride_h_ = stride_w_ = unpool_param.stride();
} else {
stride_h_ = unpool_param.stride_h();
stride_w_ = unpool_param.stride_w();
}
if (pad_h_ != 0 || pad_w_ != 0) {
CHECK(UnpoolingParameter_UnpoolMethod_MAX == unpool_param.unpool())
<< "Padding implemented only for max unpooling.";
CHECK_LT(pad_h_, kernel_h_);
CHECK_LT(pad_w_, kernel_w_);
}
if (unpool_param.has_unpool_size()) {
unpooled_height_ = unpooled_width_ = unpool_param.unpool_size();
} else if (unpool_param.has_unpool_h() &&
unpool_param.has_unpool_w()) {
unpooled_height_ = unpool_param.unpool_h();
unpooled_width_ = unpool_param.unpool_w();
} else {
// in this case, you should recompute unpooled_width, height
unpooled_height_ = -1;
unpooled_width_ = -1;
}
}
template <typename Dtype>
void PoolingTDLayer<Dtype>::Reshape(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
channels_ = bottom[0]->channels();
height_ = bottom[0]->height();
width_ = bottom[0]->width();
if (unpooled_height_ < 0 || unpooled_width_ < 0) {
// unpooled_height_ = (height_ - 1) * stride_h_ + kernel_h_ - 2 * pad_h_;
// unpooled_width_ = (width_ - 1) * stride_w_ + kernel_w_ - 2 * pad_w_;
unpooled_height_ = max((height_ - 1) * stride_h_ + kernel_h_ - 2 * pad_h_,
height_ * stride_h_ - pad_h_ + 1);
unpooled_width_ = max((width_ - 1) * stride_w_ + kernel_w_ - 2 * pad_w_,
width_ * stride_w_ - pad_w_ + 1);
}
top[0]->Reshape(bottom[0]->num(), channels_, unpooled_height_,
unpooled_width_);
// check bottom[1] and top shape
vector<int> activation_shape;
activation_shape = bottom[1]->shape();
vector<int> top_shape;
top_shape = top[0]->shape();
for (int i=0; i < activation_shape.size(); ++i){
CHECK_EQ(top_shape[i], activation_shape[i]) << "top shape must equal to bottom[1] shape";
}
vector<int> pooled_shape;
pooled_shape = bottom[2]->shape();
vector<int> bottom_shape;
bottom_shape = bottom[0]->shape();
for (int i=0; i < bottom_shape.size(); ++i){
CHECK_EQ(pooled_shape[i], bottom_shape[i]) << "bottom[0] shape must equal to bottom[2] shape";
}
}
// TODO(Yangqing): Is there a faster way to do unpooling in the channel-first
// case?
template <typename Dtype>
void PoolingTDLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
const Dtype* bottom_data = bottom[0]->cpu_data();
Dtype* top_data = top[0]->mutable_cpu_data();
const Dtype* activation_data = bottom[1]->cpu_data();
const Dtype* pooled_data = bottom[2]->cpu_data();
const int top_count = top[0]->count();
caffe_set(top_count, Dtype(0), top_data);
// We'll get the mask from bottom[1] if it's of size >1.
// const bool use_bottom_mask = bottom.size() > 1;
// const Dtype* bottom_mask = NULL;
// Different unpooling methods. We explicitly do the switch outside the for
// loop to save time, although this results in more code.
switch (this->layer_param_.unpooling_param().unpool()) {
case UnpoolingParameter_UnpoolMethod_MAX:
NOT_IMPLEMENTED;
break;
case UnpoolingParameter_UnpoolMethod_AVE:
// The main loop
for (int n = 0; n < top[0]->num(); ++n) {
for (int c = 0; c < channels_; ++c) {
for (int ph = 0; ph < height_; ++ph) {
for (int pw = 0; pw < width_; ++pw) {
int hstart = ph * stride_h_ - pad_h_;
int wstart = pw * stride_w_ - pad_w_;
int hend = min(hstart + kernel_h_, unpooled_height_ + pad_h_);
int wend = min(wstart + kernel_w_, unpooled_width_ + pad_w_);
int pool_size = (hend - hstart) * (wend - wstart);
hstart = max(hstart, 0);
wstart = max(wstart, 0);
hend = min(hend, unpooled_height_);
wend = min(wend, unpooled_width_);
Dtype bsum = pooled_data[ph * width_ + pw] * pool_size;
for (int h = hstart; h < hend; ++h) {
for (int w = wstart; w < wend; ++w) {
// top_data[h * unpooled_width_ + w] +=
// bottom_data[ph * width_ + pw] / pool_size;
top_data[h * unpooled_width_ + w] += bsum > Dtype(0) ?
(activation_data[h * unpooled_width_ + w] * bottom_data[ph * width_ + pw] / bsum):Dtype(0);
}
}
}
}
// offset
bottom_data += bottom[0]->offset(0, 1);
top_data += top[0]->offset(0, 1);
pooled_data += bottom[2]->offset(0, 1);
activation_data += bottom[1]->offset(0, 1);
}
}
break;
case UnpoolingParameter_UnpoolMethod_TILE:
NOT_IMPLEMENTED;
break;
default:
LOG(FATAL) << "Unknown unpooling method.";
}
}
template <typename Dtype>
void PoolingTDLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) {
if (!(propagate_down[0] || propagate_down[1])) {
return;
}
const Dtype* top_diff = top[0]->cpu_diff();
const Dtype* bottom_data = bottom[0]->cpu_data();
Dtype* bottom_diff = bottom[0]->mutable_cpu_diff();
Dtype* activation_diff = bottom[1]->mutable_cpu_diff();
const Dtype* activation_data = bottom[1]->cpu_data();
const Dtype* pooled_data = bottom[2]->cpu_data();
// Different unpooling methods. We explicitly do the switch outside the for
// loop to save time, although this results in more codes.
caffe_set(bottom[0]->count(), Dtype(0), bottom_diff);
caffe_set(bottom[1]->count(), Dtype(0), activation_diff);
// We'll output the mask to top[1] if it's of size >1.
// const bool use_bottom_mask = bottom.size() > 1;
// const Dtype* bottom_mask = NULL;
switch (this->layer_param_.unpooling_param().unpool()) {
case UnpoolingParameter_UnpoolMethod_MAX:
NOT_IMPLEMENTED;
break;
case UnpoolingParameter_UnpoolMethod_AVE:
for (int i = 0; i < bottom[0]->count(); ++i) {
bottom_diff[i] = 0;
}
for (int i = 0; i < bottom[1]->count(); ++i) {
activation_diff[i] = 0;
}
// The main loop
for (int n = 0; n < bottom[0]->num(); ++n) {
for (int c = 0; c < channels_; ++c) {
for (int ph = 0; ph < height_; ++ph) {
for (int pw = 0; pw < width_; ++pw) {
int hstart = ph * stride_h_ - pad_h_;
int wstart = pw * stride_w_ - pad_w_;
int hend = min(hstart + kernel_h_, unpooled_height_ + pad_h_);
int wend = min(wstart + kernel_w_, unpooled_width_ + pad_w_);
int pool_size = (hend - hstart) * (wend - wstart);
hstart = max(hstart, 0);
wstart = max(wstart, 0);
hend = min(hend, unpooled_height_);
wend = min(wend, unpooled_width_);
Dtype bsum = pooled_data[ph * width_ + pw] * pool_size;
for (int h = hstart; h < hend; ++h) {
for (int w = wstart; w < wend; ++w) {
// bottom_diff[ph * width_ + pw] +=
// top_diff[h * unpooled_width_ + w];
bottom_diff[ph * width_ + pw] += bsum > Dtype(0) ?
(activation_data[h * unpooled_width_ + w] * top_diff[h * unpooled_width_ + w] / bsum) : Dtype(0);
}
}
for (int h = hstart; h < hend; ++h){
for (int w = wstart; w < wend; ++w){
activation_diff[h * unpooled_width_ + w] += bsum > Dtype(0) ?
(top_diff[h*unpooled_width_ + w] - bottom_diff[ph * width_ + pw]) * (bottom_data[ph * width_ + pw] / bsum) : Dtype(0);
}
}
// bottom_diff[ph * width_ + pw] /= pool_size;
}
}
// compute offset
bottom_diff += bottom[0]->offset(0, 1);
top_diff += top[0]->offset(0, 1);
bottom_data += bottom[0]->offset(0, 1);
pooled_data += bottom[2]->offset(0, 1);
activation_data += bottom[1]->offset(0, 1);
activation_diff += bottom[1]->offset(0, 1);
}
}
break;
case UnpoolingParameter_UnpoolMethod_TILE:
NOT_IMPLEMENTED;
break;
default:
LOG(FATAL) << "Unknown unpooling method.";
}
}
#ifdef CPU_ONLY
STUB_GPU(PoolingTDLayer);
#endif
INSTANTIATE_CLASS(PoolingTDLayer);
REGISTER_LAYER_CLASS(PoolingTD);
} // namespace caffe
| 48.318996
| 170
| 0.493509
|
niuchuangnn
|
fb1f3ba39e49360effb23ec0726334742a50de9b
| 730
|
cpp
|
C++
|
UI_bar.cpp
|
SarwanShah/C-Game-Hoshruba
|
a47da529748a9af8085500757cc8e0b7378b0723
|
[
"Apache-2.0"
] | null | null | null |
UI_bar.cpp
|
SarwanShah/C-Game-Hoshruba
|
a47da529748a9af8085500757cc8e0b7378b0723
|
[
"Apache-2.0"
] | null | null | null |
UI_bar.cpp
|
SarwanShah/C-Game-Hoshruba
|
a47da529748a9af8085500757cc8e0b7378b0723
|
[
"Apache-2.0"
] | null | null | null |
#include "UI_Bar.h"
UIBar::UIBar(LTexture* textureSheet, SDL_Rect* textureRect, int x_pos, int y_pos, int x_size, int y_size):OnScreenTexture(textureSheet, textureRect, x_pos, y_pos, x_size, y_size)
{
cout << "UI Bar Constructor Called" << endl;
}
UIBar::~UIBar()
{
cout << "UI Bar Destructor Called" << endl;
}
void UIBar::render(SDL_Renderer* gRenderer)
{
textureSheet->render(x_pos, y_pos, gRenderer, &textureRect[0], x_size, y_size);
for (int i = 0; i < 13; i++)
{
textureSheet->render(x_pos+(x_size*(i+1)), y_pos, gRenderer, &textureRect[1], x_size, y_size);
}
textureSheet->render(x_pos+(x_size*(13+1)), y_pos, gRenderer, &textureRect[2], x_size, y_size);
}
| 30.416667
| 179
| 0.649315
|
SarwanShah
|
fb27bf1a2ac1928155aa190a6f01d56edc944ae6
| 1,224
|
cpp
|
C++
|
ut/source/test_ck_server_threaded.cpp
|
dicroce/cppkit
|
dc64dacacc54665b079836a1bc7d8fb028616ffe
|
[
"BSD-2-Clause-FreeBSD"
] | 12
|
2015-03-27T21:29:02.000Z
|
2016-11-26T23:43:52.000Z
|
ut/source/test_ck_server_threaded.cpp
|
dicroce/cppkit
|
dc64dacacc54665b079836a1bc7d8fb028616ffe
|
[
"BSD-2-Clause-FreeBSD"
] | 1
|
2017-01-18T00:32:12.000Z
|
2017-01-18T00:32:12.000Z
|
ut/source/test_ck_server_threaded.cpp
|
dicroce/cppkit
|
dc64dacacc54665b079836a1bc7d8fb028616ffe
|
[
"BSD-2-Clause-FreeBSD"
] | 6
|
2015-02-08T13:10:27.000Z
|
2017-01-18T00:24:47.000Z
|
#include "framework.h"
#include "test_ck_server_threaded.h"
#include "cppkit/ck_server_threaded.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <thread>
#include <mutex>
#include <condition_variable>
using namespace std;
using namespace cppkit;
REGISTER_TEST_FIXTURE(test_ck_server_threaded);
void test_ck_server_threaded::setup()
{
}
void test_ck_server_threaded::teardown()
{
}
void test_ck_server_threaded::test_basic()
{
int port = RTF_NEXT_PORT();
ck_server_threaded<ck_socket> s( port, [](ck_buffered_socket<ck_socket>& conn){
uint32_t inv;
conn.recv( &inv, 4 );
++inv;
conn.send( &inv, 4 );
conn.close();
} );
thread t([&](){
s.start();
});
try
{
usleep(1000000);
ck_socket socket;
RTF_ASSERT_NO_THROW( socket.connect( "127.0.0.1", port ) );
uint32_t val = 41;
socket.send( &val, 4 );
socket.recv( &val, 4 );
RTF_ASSERT( val == 42 );
socket.close();
s.stop();
t.join();
}
catch(ck_exception& ex)
{
printf("%s\n",ex.what());
}
catch(exception& ex)
{
printf("%s\n",ex.what());
}
}
| 17.73913
| 83
| 0.581699
|
dicroce
|
fb2cbf29e7d0ac35a071e49719271c5ab0e65040
| 4,752
|
hpp
|
C++
|
src/cxx/soDebugCallback.hpp
|
BenSolus/vulkan-engine
|
04a7114b7f9b2617cf6b5133e71190b1f48c0575
|
[
"MIT"
] | null | null | null |
src/cxx/soDebugCallback.hpp
|
BenSolus/vulkan-engine
|
04a7114b7f9b2617cf6b5133e71190b1f48c0575
|
[
"MIT"
] | null | null | null |
src/cxx/soDebugCallback.hpp
|
BenSolus/vulkan-engine
|
04a7114b7f9b2617cf6b5133e71190b1f48c0575
|
[
"MIT"
] | null | null | null |
/*
* Copyright (C) 2017-2018 by Bennet Carstensen
*
* 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.
*/
/**
* @file soDebugCallback.hpp
* @author Bennet Carstensen
* @date 2018
* @copyright Copyright (c) 2017-2018 Bennet Carstensen
*
* 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.
*/
#pragma once
#include "soDefinitions.hpp"
#include "soMacroDispatcher.hpp"
#include "soPrettyFunctionSig.hpp"
#include "soReturnT.hpp"
namespace so {
enum class
DebugCode
{
info,
infoItem,
verbose,
error
};
typedef void (*DebugCallback) (DebugCode const,
std::string const&,
std::string const&,
index_t const,
std::string const&);
void
setDebugCallback(DebugCallback callback);
void
executeDebugCallback(DebugCode const code,
std::string const& message,
std::string const& funcSig,
index_t const line,
std::string const& file);
} // namespace so
#define DEBUG_CALLBACK(...) MACRO_DISPATCHER(DEBUG_CALLBACK, __VA_ARGS__)
#define DEBUG_CALLBACK2(code, message) \
so::executeDebugCallback(code, \
message, \
PRETTY_FUNCTION_SIG, \
__LINE__, \
__FILE__)
#define DEBUG_CALLBACK3(code, message, function) \
so::executeDebugCallback(code, \
message, \
getPrettyFunctionSig<decltype(&function)>(), \
__LINE__, \
__FILE__)
#define DEBUG_CALLBACK4(code, message, trgClass, function) \
so::executeDebugCallback \
(code, \
message, \
getPrettyFunctionSig<decltype(trgClass::*function)>(), \
__LINE__, \
__FILE__)
constexpr so::DebugCode info = so::DebugCode::info;
constexpr so::DebugCode infoItem = so::DebugCode::infoItem;
constexpr so::DebugCode verbose = so::DebugCode::verbose;
constexpr so::DebugCode error = so::DebugCode::error;
| 39.932773
| 79
| 0.590278
|
BenSolus
|
fb3176843070d5710e32f03208efac74de544d3d
| 583
|
cpp
|
C++
|
Source/freeze.cpp
|
bergice/Kingslayer
|
21ba00fd0d518369de870fd4eefc61ee25c2821d
|
[
"MIT"
] | null | null | null |
Source/freeze.cpp
|
bergice/Kingslayer
|
21ba00fd0d518369de870fd4eefc61ee25c2821d
|
[
"MIT"
] | null | null | null |
Source/freeze.cpp
|
bergice/Kingslayer
|
21ba00fd0d518369de870fd4eefc61ee25c2821d
|
[
"MIT"
] | null | null | null |
#include "freeze.h"
#include "program.h"
#include "boost\\lexical_cast.hpp"
#include "player.h"
void FreezeThread (void)
{
while(true)
{
for (unsigned i=0; i<program->frozen.size(); i++)
{
if (program->frozen[i].player)
{
time_t now; time(&now);
double seconds = difftime(now, program->frozen[i].time);
if (seconds>=0)
{
std::string msg = "/unfreezeid ";
msg.append(boost::lexical_cast<std::string>(program->frozen[i].player->id));
sendRcon(msg);
program->frozen.erase(program->frozen.begin()+i);
}
}
}
Sleep(2000);
}
}
| 19.433333
| 81
| 0.61235
|
bergice
|
fb3b97eb2c306b3f5217fbbddde03378a8c8d902
| 724
|
cpp
|
C++
|
test/misc/shape/numel.cpp
|
jfalcou/kiwaku
|
1115516643245f61c5412b837e0be9cbff47608f
|
[
"MIT"
] | 16
|
2020-11-17T18:25:16.000Z
|
2022-03-19T15:12:19.000Z
|
test/misc/shape/numel.cpp
|
jfalcou/kiwaku
|
1115516643245f61c5412b837e0be9cbff47608f
|
[
"MIT"
] | 6
|
2021-08-17T16:13:46.000Z
|
2022-03-04T09:32:48.000Z
|
test/misc/shape/numel.cpp
|
jfalcou/kiwaku
|
1115516643245f61c5412b837e0be9cbff47608f
|
[
"MIT"
] | null | null | null |
//==================================================================================================
/**
KIWAKU - Containers Well Made
Copyright 2020 Joel FALCOU
Licensed under the MIT License <http://opensource.org/licenses/MIT>.
SPDX-License-Identifier: MIT
**/
//==================================================================================================
#include "test.hpp"
#include <kiwaku/shape.hpp>
TTS_CASE( "numel behavior on nD shape" )
{
TTS_EQUAL( (kwk::shape{4,2,6,9}.numel()), 432 );
TTS_EQUAL( (kwk::shape{4,2,6,1}.numel()), 48 );
TTS_EQUAL( (kwk::shape{4,2,1,1}.numel()), 8 );
TTS_EQUAL( (kwk::shape{4,1,1,1}.numel()), 4 );
TTS_EQUAL( (kwk::shape{1,1,1,1}.numel()), 1 );
};
| 34.47619
| 100
| 0.453039
|
jfalcou
|
fb3c1f6c5373224f58d4bbb00aff963299aef9ba
| 1,237
|
cpp
|
C++
|
8INF259-TP2/ChromoCell.cpp
|
Hexzhe/8INF259-TP2
|
ed72ba14544fdc346b4555e4619f969197735da9
|
[
"MIT"
] | null | null | null |
8INF259-TP2/ChromoCell.cpp
|
Hexzhe/8INF259-TP2
|
ed72ba14544fdc346b4555e4619f969197735da9
|
[
"MIT"
] | null | null | null |
8INF259-TP2/ChromoCell.cpp
|
Hexzhe/8INF259-TP2
|
ed72ba14544fdc346b4555e4619f969197735da9
|
[
"MIT"
] | null | null | null |
#include "pch.h"
#include "ChromoCell.h"
ChromoCell::ChromoCell(ChromoPair* pair1, ChromoPair* pair2, ChromoPair* pair3, ChromoPair* pair4)
{
this->pair1 = pair1;
this->pair2 = pair2;
this->pair3 = pair3;
this->pair4 = pair4;
}
ChromoCell::~ChromoCell()
{
pair1 = pair2 = pair3 = pair4 = nullptr;
delete pair1, pair2, pair3, pair4;
}
std::istream& operator >> (std::istream& in, ChromoCell& cell)
{
std::string tmp;
in >> tmp;
cell.pair1 = new ChromoPair(tmp.at(0), tmp.at(1));
in >> tmp;
cell.pair2 = new ChromoPair(tmp.at(0), tmp.at(1));
in >> tmp;
cell.pair3 = new ChromoPair(tmp.at(0), tmp.at(1));
in >> tmp;
cell.pair4 = new ChromoPair(tmp.at(0), tmp.at(1));
return in;
}
ChromoCell* operator + (ChromoCell& a, ChromoCell& b)
{
ChromoCell* c = new ChromoCell;
c->pair1 = *a.pair1 + *b.pair1;
c->pair2 = *a.pair2 + *b.pair2;
c->pair3 = *a.pair3 + *b.pair3;
c->pair4 = *a.pair4 + *b.pair4;
return c;
}
std::ostream& operator << (std::ostream& out, const ChromoCell& cell)
{
out << cell.pair1->a << cell.pair1->b << " ";
out << cell.pair2->a << cell.pair2->b << " ";
out << cell.pair3->a << cell.pair3->b << " ";
out << cell.pair4->a << cell.pair4->b << " ";
out << std::flush;
return out;
}
| 20.616667
| 98
| 0.616815
|
Hexzhe
|
fb3c5ccc83e27a63a292bd82474580057a543a91
| 1,228
|
cpp
|
C++
|
test/Core/TestFPSCounter.cpp
|
Simmesimme/illusion-3d
|
48520d87ea0677bb8852b20bb6fbfbe1a49402d2
|
[
"MIT"
] | 8
|
2019-12-05T15:57:23.000Z
|
2022-01-19T19:37:23.000Z
|
test/Core/TestFPSCounter.cpp
|
Schneegans/illusion
|
48520d87ea0677bb8852b20bb6fbfbe1a49402d2
|
[
"MIT"
] | null | null | null |
test/Core/TestFPSCounter.cpp
|
Schneegans/illusion
|
48520d87ea0677bb8852b20bb6fbfbe1a49402d2
|
[
"MIT"
] | 1
|
2019-01-15T10:35:13.000Z
|
2019-01-15T10:35:13.000Z
|
////////////////////////////////////////////////////////////////////////////////////////////////////
// //
// _) | | _) This code may be used and modified under the terms //
// | | | | | (_-< | _ \ \ of the MIT license. See the LICENSE file for details. //
// _| _| _| \_,_| ___/ _| \___/ _| _| Copyright (c) 2018-2019 Simon Schneegans //
// //
////////////////////////////////////////////////////////////////////////////////////////////////////
#include <Illusion/Core/FPSCounter.hpp>
#include <doctest.h>
#include <thread>
namespace Illusion::Core {
TEST_CASE("Illusion::Core::FPSCounter") {
// Create a auto-starting FPSCounter.
FPSCounter<20> counter;
for (size_t i(0); i < 50; ++i) {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
counter.step();
CHECK(counter.pFrameTime.get() == doctest::Approx(0.01).epsilon(0.001));
CHECK(counter.pFPS.get() == doctest::Approx(100).epsilon(0.1));
}
}
} // namespace Illusion::Core
| 40.933333
| 100
| 0.393322
|
Simmesimme
|
fb40cbad9e88899b1728b6d350345f1de612e631
| 571
|
hpp
|
C++
|
generator/translator_geo_objects.hpp
|
letko-dmitry/omim
|
83797b2070e22f8d67f36d9c7e291e31ea2480ea
|
[
"Apache-2.0"
] | 1
|
2019-05-27T02:45:22.000Z
|
2019-05-27T02:45:22.000Z
|
generator/translator_geo_objects.hpp
|
Mahmoudabdelmobdy/omim
|
1d444650803b27e507b5e9532551d41bab621a53
|
[
"Apache-2.0"
] | 1
|
2019-05-14T15:26:55.000Z
|
2019-05-16T11:00:33.000Z
|
generator/translator_geo_objects.hpp
|
vmihaylenko/omim
|
00087f340e723fc611cbc82e0ae898b9053b620a
|
[
"Apache-2.0"
] | null | null | null |
#pragma once
#include "generator/emitter_interface.hpp"
#include "generator/translator.hpp"
#include <memory>
namespace cache
{
class IntermediateDataReader;
} // namespace cache
namespace generator
{
// The TranslatorGeoObjects class implements translator for building geo objects.
// Every GeoObject is either a building or a POI.
class TranslatorGeoObjects : public Translator
{
public:
explicit TranslatorGeoObjects(std::shared_ptr<EmitterInterface> emitter,
cache::IntermediateDataReader & cache);
};
} // namespace generator
| 23.791667
| 81
| 0.749562
|
letko-dmitry
|
fb4508c2905a027430aff4310f8a4d30242f7013
| 1,067
|
hpp
|
C++
|
src/rynx/application/visualisation/renderer.hpp
|
Apodus/rynx
|
3e1babc2f2957702ba2b09d78be3a959f2f4ea18
|
[
"MIT"
] | 11
|
2019-08-19T08:44:14.000Z
|
2020-09-22T20:04:46.000Z
|
src/rynx/application/visualisation/renderer.hpp
|
Apodus/rynx
|
3e1babc2f2957702ba2b09d78be3a959f2f4ea18
|
[
"MIT"
] | null | null | null |
src/rynx/application/visualisation/renderer.hpp
|
Apodus/rynx
|
3e1babc2f2957702ba2b09d78be3a959f2f4ea18
|
[
"MIT"
] | null | null | null |
#pragma once
#include <rynx/tech/ecs.hpp>
#include <memory>
#include <vector>
namespace rynx {
namespace scheduler {
class context;
}
namespace application {
class igraphics_step {
public:
virtual ~igraphics_step() {}
virtual void execute() = 0;
virtual void prepare(rynx::scheduler::context* ctx) = 0;
};
class graphics_step : public igraphics_step {
public:
graphics_step& add_graphics_step(std::unique_ptr<igraphics_step> graphics_step, bool front = false) {
if (front) {
m_graphics_steps.insert(m_graphics_steps.begin(), std::move(graphics_step));
}
else {
m_graphics_steps.emplace_back(std::move(graphics_step));
}
return *this;
}
void execute() override {
for (auto& graphics_step : m_graphics_steps) {
graphics_step->execute();
}
}
void prepare(rynx::scheduler::context* ctx) override {
for (auto& graphics_step : m_graphics_steps) {
graphics_step->prepare(ctx);
}
}
private:
std::vector<std::unique_ptr<igraphics_step>> m_graphics_steps;
};
}
}
| 21.34
| 104
| 0.676664
|
Apodus
|
fb45deee763271822a084fa9a5855da35dd6e95b
| 568
|
cpp
|
C++
|
_includes/leet524/leet524_1.cpp
|
mingdaz/leetcode
|
64f2e5ad0f0446d307e23e33a480bad5c9e51517
|
[
"MIT"
] | null | null | null |
_includes/leet524/leet524_1.cpp
|
mingdaz/leetcode
|
64f2e5ad0f0446d307e23e33a480bad5c9e51517
|
[
"MIT"
] | 8
|
2019-12-19T04:46:05.000Z
|
2022-02-26T03:45:22.000Z
|
_includes/leet524/leet524_1.cpp
|
mingdaz/leetcode
|
64f2e5ad0f0446d307e23e33a480bad5c9e51517
|
[
"MIT"
] | null | null | null |
class Solution {
public:
string findLongestWord(string s, vector<string>& d) {
string res = "";
for(auto substr:d){
if(substr.size()>res.size()||(substr.size()==res.size()&&substr.compare(res)<0)){
if(match(s,substr)) res = substr;
}
}
return res;
}
private:
bool match(string a, string b){
if(b.size()>a.size()) return false;
int i,j;
for(i=0,j=0;j<b.size()&&i<a.size();i++){
if(a[i]==b[j]) j++;
}
return j==b.size();
}
};
| 25.818182
| 93
| 0.466549
|
mingdaz
|
fb472d40c6458f368f79372fc2a08e9896693141
| 466
|
cpp
|
C++
|
src/16000/16471.cpp17.cpp
|
upple/BOJ
|
e6dbf9fd17fa2b458c6a781d803123b14c18e6f1
|
[
"MIT"
] | 8
|
2018-04-12T15:54:09.000Z
|
2020-06-05T07:41:15.000Z
|
src/16000/16471.cpp17.cpp
|
upple/BOJ
|
e6dbf9fd17fa2b458c6a781d803123b14c18e6f1
|
[
"MIT"
] | null | null | null |
src/16000/16471.cpp17.cpp
|
upple/BOJ
|
e6dbf9fd17fa2b458c6a781d803123b14c18e6f1
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
int a[100001], b[100001];
int n;
int solve(int x, int y)
{
if(x>n || y>n) return 0;
if(a[x]<b[y]) return 1+solve(x+1, y+1);
return solve(x, y+1);
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cin>>n;
for(int i=1; i<=n; i++)
cin>>a[i];
for(int i=1; i<=n; i++)
cin>>b[i];
sort(a+1, a+n+1);
sort(b+1, b+n+1);
cout<<(solve(1, 1)>n/2?"YES":"NO");
}
| 16.068966
| 43
| 0.491416
|
upple
|
fb47c5b5787b2b6649b7321e072b268928fe13e1
| 1,100
|
cpp
|
C++
|
src/char_array_allocator.cpp
|
chloro-pn/pnlog
|
0280539ff388db6bcc823a85c987b52b261fa920
|
[
"MIT"
] | null | null | null |
src/char_array_allocator.cpp
|
chloro-pn/pnlog
|
0280539ff388db6bcc823a85c987b52b261fa920
|
[
"MIT"
] | null | null | null |
src/char_array_allocator.cpp
|
chloro-pn/pnlog
|
0280539ff388db6bcc823a85c987b52b261fa920
|
[
"MIT"
] | 1
|
2020-04-01T13:36:51.000Z
|
2020-04-01T13:36:51.000Z
|
#include "../include/char_array_allocator.h"
#include <cassert>
namespace pnlog {
CharArrayAllocator::CharArrayAllocator():size_(0) {
}
std::shared_ptr<CharArrayAllocator> CharArrayAllocator::instance() {
static std::shared_ptr<CharArrayAllocator> instance_(new CharArrayAllocator());
return instance_;
}
std::shared_ptr<CharArray> CharArrayAllocator::apply(int index) {
std::unique_lock<lock_type> mut(m_);
if(bufs_.empty() == true) {
if (size_ < max_size_) {
bufs_.emplace_back(new CharArray(4096, index));
++size_;
}
else {
cv_.wait(mut, [this]()->bool {
return !bufs_.empty();
});
}
//bufs_.emplace_back(new CharArray(4096, index));
}
std::shared_ptr<CharArray> result = bufs_.back();
bufs_.pop_back();
result->index_ = index;
return result;
}
void CharArrayAllocator::give_back(std::shared_ptr<CharArray> item) {
std::unique_lock<lock_type> mut(m_);
bufs_.push_back(item);
cv_.notify_one();
}
CharArrayAllocator::~CharArrayAllocator() {
//assert(size_ == static_cast<int>(bufs_.size()));
}
}
| 24.444444
| 81
| 0.673636
|
chloro-pn
|
fb4e98fb3839025ace91ec7aedecc9c2ededab59
| 6,359
|
cpp
|
C++
|
code-demo/list/list_insert_anywhere-k19lesson3.cpp
|
kzhereb/knu-is-progr2019
|
6a85b3659103800d8ec4a8097df2a547d6c8dda4
|
[
"MIT"
] | null | null | null |
code-demo/list/list_insert_anywhere-k19lesson3.cpp
|
kzhereb/knu-is-progr2019
|
6a85b3659103800d8ec4a8097df2a547d6c8dda4
|
[
"MIT"
] | null | null | null |
code-demo/list/list_insert_anywhere-k19lesson3.cpp
|
kzhereb/knu-is-progr2019
|
6a85b3659103800d8ec4a8097df2a547d6c8dda4
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
namespace k19lesson3 {
struct Node {
int dat;
Node *next;
Node *prev;
};
//-------------------------
Node *first(int);
void add(Node **, int);
void add_ref(Node *&, int);
Node *find(Node * const, int);
bool remove(Node **, Node **, int);
Node *insert(Node * const, Node **, int, int);
void lprint(Node *);
void ldel(Node *);
//-------------------------
void pointers_demo2() {
int i = 5;
int* ptr = &i;
cout << *ptr << endl;
cout << ptr << endl;
*ptr = 6;
cout << *ptr << endl;
cout << ptr << endl;
int j = 7;
ptr = &j;
cout << *ptr << endl;
cout << ptr << endl;
ptr = nullptr;
//cout<<*ptr<<endl;
cout << ptr << endl;
ptr = new int(12);
cout << *ptr << endl;
cout << ptr << endl;
*ptr = 15;
cout << *ptr << endl;
cout << ptr << endl;
cout << "int **" << endl;
int ** pptr = &ptr;
cout << pptr << endl;
cout << *pptr << endl;
cout << **pptr << endl;
**pptr = 23;
cout << pptr << endl;
cout << *pptr << endl;
cout << **pptr << endl;
*pptr = new int(25);
cout << pptr << endl;
cout << *pptr << endl;
cout << **pptr << endl;
int* ptr2 = new int(32);
pptr = &ptr2;
cout << pptr << endl;
cout << *pptr << endl;
cout << **pptr << endl;
}
// index points to a gap between elements
// negative index: same as 0
// big positive index: same as length
Node* find_by_index(Node* const p_begin, int index) {
if (index<0) {
return p_begin;
}
int counter = 0;
Node* tmp = p_begin;
while (tmp) {
if (counter == index) {
return tmp;
}
tmp = tmp->next;
counter++;
}
return nullptr;
}
// [0:1]->[1:2]->...->[9:10]->nullptr
//0 1 2 9 10
// new_node found
Node* insert_anywhere(Node*& p_begin, Node*& p_end, int index, int value) {
Node* found = find_by_index(p_begin, index);
Node* new_node = new Node;
new_node->dat = value;
new_node->next = found;
if (found) {
new_node->prev = found->prev;
if (found->prev) {
found->prev->next = new_node;
} else {
p_begin = new_node;
}
found->prev = new_node;
} else {
p_end->next = new_node;
new_node->prev = p_end;
p_end = new_node;
}
return new_node;
}
int main_k19lesson3() {
// pointers_demo();
// return 0;
int nn, k, m;
//визначаємось з кількістю елементів
//cout << "Number = ";
//cin >> nn;
nn = 10;
cout << endl;
Node *pbeg = first(1); //формування першого елемента списку
Node *pend = pbeg; //список складаєтьсчя з одного елемента
Node *p;
//додавання елементів в кінець списку 2, 3, ..., nn
// for (int i = 2; i <= nn; i++) add(&pend, i);
for (int i = 2; i <= nn; i++)
add_ref(pend, i);
lprint(pbeg); //виведення списку
Node* found = find_by_index(pbeg, 3);
cout << "found: " << found->dat << endl;
cout << "insert anywhere end" << endl;
insert_anywhere(pbeg, pend, 10, 3456);
lprint(pbeg);
cout << "insert anywhere" << endl;
insert_anywhere(pbeg, pend, 1, 1234);
lprint(pbeg);
cout << "insert anywhere beginning" << endl;
insert_anywhere(pbeg, pend, 0, 2345);
lprint(pbeg);
cout << "insert anywhere negative" << endl;
insert_anywhere(pbeg, pend, -10, 4567);
lprint(pbeg);
//вставка елемента k після елемента m
cout << "Insert = ";
cin >> k;
cout << endl;
cout << "After = ";
cin >> m;
cout << endl;
p = insert(pbeg, &pend, m, k);
lprint(pbeg); //виведення списку
//вилучення елемента k
cout << "Delete = ";
cin >> k;
cout << endl;
if (!remove(&pbeg, &pend, k))
cout << "no find " << endl;
lprint(pbeg); //виведення списку
ldel(pbeg); //знищення списку
//system("pause");
return 0;
}
//--------------------------------------------------------
//формування першого елемента списку
Node *first(int d) {
Node *pv = new Node;
pv->dat = d;
pv->next = NULL;
pv->prev = NULL;
return pv;
}
//--------------------------------------------------------
//додавання елементів в кінець списку 2, 3, ..., nn
void add(Node **pend, int d) {
Node *pv = new Node;
pv->dat = d;
pv->next = NULL;
pv->prev = *pend;
(*pend)->next = pv;
*pend = pv;
}
//--------------------------------------------------------
//додавання елементів в кінець списку 2, 3, ..., nn
void add_ref(Node *& pend, int d) {
Node *pv = new Node;
pv->dat = d;
pv->next = NULL;
pv->prev = pend;
pend->next = pv;
pend = pv;
}
//--------------------------------------------------------
//пошук елемента за ключем
Node *find(Node * const pbeg, int d) {
Node *pv = pbeg;
while (pv) {
if (pv->dat == d)
break;
pv = pv->next;
}
return pv;
}
//-------------------------------------------------------
//вилучення елемента
bool remove(Node **pbeg, Node **pend, int key) {
if (Node *pkey = find(*pbeg, key)) {
if (pkey == *pbeg) {
*pbeg = (*pbeg)->next;
(*pbeg)->prev = NULL;
} else if (pkey == *pend) {
*pend = (*pend)->prev;
(*pend)->next = NULL;
} else {
(pkey->prev)->next = pkey->next;
(pkey->next)->prev = pkey->prev;
}
delete pkey;
return true;
}
return false;
}
//-------------------------------------------------------
//вставка елемента
Node *insert(Node * const pbeg, Node **pend, int key, int d) {
if (Node *pkey = find(pbeg, key)) {
Node *pv = new Node;
pv->dat = d;
pv->next = pkey->next; //зв`язок нового вузла з наступним
pv->prev = pkey; //зв`язок нового вузла з попереднім
pkey->next = pv; //зв`язок попереднього з новим вузлом
//зв`язок наступного з новим вузлом
if (pkey != *pend)
(pv->next)->prev = pv;
else
*pend = pv; //якщо вузол стає останнім, змінюємо покажчик на кінець
return pv;
}
return NULL; //місце для вставки не було знайдено
//можна було б реалізовувати іншу обробку
//наприклад, вставку в кінець списку,
//передбачивши можливу порожність списку
}
//-------------------------------------------------------
//виведення списку
void lprint(Node *pbeg) {
Node *pv = pbeg;
while (pv) {
cout << pv->dat << ' ';
pv = pv->next;
}
cout << endl;
}
//-------------------------------------------------------
//знищення списку
void ldel(Node *pbeg) {
Node *pv;
while (pbeg) {
pv = pbeg;
pbeg = pbeg->next;
delete pv;
}
}
}
| 22.710714
| 76
| 0.51722
|
kzhereb
|
fb5339d48152cd0c96b00caf3d0c202470a4f523
| 923
|
cpp
|
C++
|
fpstimer.cpp
|
alxistn/ar-blackboard
|
73263c18d37645180565353316085bbcfe361018
|
[
"MIT"
] | 1
|
2016-10-12T12:01:59.000Z
|
2016-10-12T12:01:59.000Z
|
fpstimer.cpp
|
alxistn/ar-blackboard
|
73263c18d37645180565353316085bbcfe361018
|
[
"MIT"
] | null | null | null |
fpstimer.cpp
|
alxistn/ar-blackboard
|
73263c18d37645180565353316085bbcfe361018
|
[
"MIT"
] | null | null | null |
#include "cmath"
#include "fpstimer.h"
FPSTimer::FPSTimer(float maxFPS)
: _maxFPS(maxFPS), _minFrameTime((1.0f / maxFPS) * 1000.0f)
{
}
FPSTimer::FPSTimer()
: _maxFPS(0), _minFrameTime(0.0f)
{
}
void FPSTimer::start()
{
_currentTime = SDL_GetTicks();
}
void FPSTimer::update()
{
_oldTime = _currentTime;
_currentTime = SDL_GetTicks();
_frameTime = (_currentTime - _oldTime);
if (_minFrameTime > 0.0f) {
Uint32 sleep_time = roundf(_minFrameTime - _frameTime);
if (sleep_time > 0) {
SDL_Delay(sleep_time);
_currentTime = SDL_GetTicks();
_frameTime = (_currentTime - _oldTime);
}
}
}
float FPSTimer::getFPS() const
{
if (_frameTime == 0.0f)
return 1000.0f;
return 1000.0f / _frameTime;
}
float FPSTimer::getFrameTime() const
{
if (_frameTime == 0.0f)
return 0.0f;
return _frameTime / 1000.0f;
}
| 19.229167
| 63
| 0.614301
|
alxistn
|
fb6298634b7718e8677ff7f2b588c3b56464c602
| 6,909
|
cpp
|
C++
|
SmartRockets/SmartRocketsApp.cpp
|
ElectroBean/SmartRockets
|
fc4bd2a98b4e59929583f3b9b185401d168d8f7b
|
[
"MIT"
] | null | null | null |
SmartRockets/SmartRocketsApp.cpp
|
ElectroBean/SmartRockets
|
fc4bd2a98b4e59929583f3b9b185401d168d8f7b
|
[
"MIT"
] | null | null | null |
SmartRockets/SmartRocketsApp.cpp
|
ElectroBean/SmartRockets
|
fc4bd2a98b4e59929583f3b9b185401d168d8f7b
|
[
"MIT"
] | null | null | null |
#include "SmartRocketsApp.h"
#include "Texture.h"
#include "Font.h"
#include "Input.h"
#include <glm\gtc\random.hpp>
#include <string>
#include <iostream>
SmartRocketsApp::SmartRocketsApp() {
}
SmartRocketsApp::~SmartRocketsApp() {
}
bool SmartRocketsApp::startup() {
m_2dRenderer = new aie::Renderer2D();
// TODO: remember to change this when redistributing a build!
// the following path would be used instead: "./font/consolas.ttf"
m_font = new aie::Font("./font/consolas.ttf", 32);
std::function<glm::vec2()> f = std::bind(&SmartRocketsApp::GetRandomVector2, this);
std::function<float(int)> t = std::bind(&SmartRocketsApp::GetFitness, this, std::placeholders::_1);
srand(time(NULL));
PopulationSize = 100;
bestGen = 1;
WindowX = Application::getWindowWidth();
WindowY = Application::getWindowHeight();
m_EndGoal = glm::vec2(WindowX / 2, WindowY - 100);
m_obstacle1 = glm::vec2(WindowX / 2, WindowY / 2);
m_obstacles[0] = new Obstacles(glm::vec2(WindowX / 2, WindowY / 2), glm::vec2(800, 5));
m_obstacles[1] = new Obstacles(glm::vec2(WindowX / 2, WindowY - 120), glm::vec2(100, 5));
m_GA = new GeneticAlgorithm<glm::vec2>(100, 250, f, t, 2.0f);
totalMembers = 0;
totalMembers += PopulationSize;
membersCompleted = 0;
for (int i = 0; i < PopulationSize; i++)
{
auto iter = m_GA->Population.begin();
std::advance(iter, i);
DNA<glm::vec2>* genes = (*iter);
m_Population[i] = new Rocket(genes);
}
return true;
}
void SmartRocketsApp::shutdown() {
delete m_font;
delete m_2dRenderer;
delete m_GA;
for (int i = 0; i < PopulationSize; i++)
{
delete m_Population[i];
}
for (int i = 0; i < 2; i++)
{
delete m_obstacles[i];
}
}
void SmartRocketsApp::update(float deltaTime) {
// input example
aie::Input* input = aie::Input::getInstance();
int popCount = 0;
for (int i = 0; i < PopulationSize; i++)
{
m_Population[i]->Update(deltaTime);
if (m_Population[i]->reachedEnd || m_Population[i]->crashed)
{
popCount++;
}
}
if (popCount == PopulationSize)
{
m_GA->NewGeneration();
totalMembers += PopulationSize;
for (int i = 0; i < PopulationSize; i++)
{
delete m_Population[i];
}
for (int i = 0; i < PopulationSize; i++)
{
auto iter = m_GA->Population.begin();
std::advance(iter, i);
DNA<glm::vec2>* genes = (*iter);
m_Population[i] = new Rocket(genes);
}
}
CheckCollisions();
// exit the application
if (input->isKeyDown(aie::INPUT_KEY_ESCAPE))
quit();
}
void SmartRocketsApp::draw() {
// wipe the screen to the background colour
clearScreen();
// begin drawing sprites
m_2dRenderer->begin();
// draw your stuff here!
for (int i = 0; i < PopulationSize; i++)
{
if (m_Population[i]->crashed)
{
m_2dRenderer->setRenderColour(255, 0, 0);
m_2dRenderer->drawCircle(m_Population[i]->position.x, m_Population[i]->position.y, 5, 1.0f);
m_2dRenderer->setRenderColour(255, 255, 255);
}
else if (m_Population[i]->completed)
{
m_2dRenderer->setRenderColour(0, 255, 0);
m_2dRenderer->drawCircle(m_Population[i]->position.x, m_Population[i]->position.y, 5, 1.0f);
m_2dRenderer->setRenderColour(255, 255, 255);
}
else
{
m_2dRenderer->setRenderColour(255, 255, 255);
m_2dRenderer->drawCircle(m_Population[i]->position.x, m_Population[i]->position.y, 5, 1.0f);
m_2dRenderer->setRenderColour(255, 255, 255);
}
}
m_2dRenderer->drawBox(m_EndGoal.x, m_EndGoal.y, 20, 20);
for (int i = 0; i < 2; i++)
{
m_obstacles[i]->Draw(m_2dRenderer);
}
// output some text, uses the last used colour
m_2dRenderer->drawText(m_font, "Press ESC to quit", 0, 0);
bestGen = std::to_string(m_GA->generationNumber);
m_2dRenderer->drawText(m_font, bestGen.c_str(), 0, getWindowHeight() - 25);
//draw best fitness
std::string bestFitness = std::to_string(m_GA->bestFitness);
m_2dRenderer->drawText(m_font, bestFitness.c_str(), 0, getWindowHeight() - 50);
//draw total members and members completed;
std::string totalMembersstr = std::to_string(totalMembers);
m_2dRenderer->drawText(m_font, "Total Members: ", 0, getWindowHeight() - 75);
m_2dRenderer->drawText(m_font, totalMembersstr.c_str(), 250, getWindowHeight() - 75);
//draw completed
std::string completedMems = std::to_string(membersCompleted);
m_2dRenderer->drawText(m_font, "Total completed: ", 0, getWindowHeight() - 100);
m_2dRenderer->drawText(m_font, completedMems.c_str(), 285, getWindowHeight() - 100);
////draw success percentage
//double division = (membersCompleted / totalMembers);
//double percent = division * 100;
//std::string percentage = std::to_string(percent);
//m_2dRenderer->drawText(m_font, "Success Percentage: ", 0, getWindowHeight() - 125);
//m_2dRenderer->drawText(m_font, percentage.c_str(), 335, getWindowHeight() - 125);
// done drawing sprites
m_2dRenderer->end();
}
glm::vec2 SmartRocketsApp::GetRandomVector2()
{
float first = (-1) + static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / (1 - (-1))));
float second = (-1) + static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / (1 - (-1))));
return glm::vec2(first, second);
}
float SmartRocketsApp::GetFitness(int index)
{
glm::vec2 asd = m_EndGoal;
m_Population[index]->positions.sort([asd](glm::vec2 lhs, glm::vec2 rhs) {return glm::distance(asd, rhs) < glm::distance(asd, lhs); });
float d = glm::distance(*(m_Population[index]->positions.begin()), m_EndGoal);
//store positions constantly, base score off closest position to end
float fitness = 1 / d;
if (m_Population[index]->completed)
d -= m_Population[index]->duration *= 1.5f;
if (m_Population[index]->position.y > m_EndGoal.y)
{
fitness *= 5;
}
else
{
fitness /= 5;
}
if (m_Population[index]->crashed)
{
fitness /= 10;
}
else
{
fitness *= 10;
}
if (m_Population[index]->completed)
{
fitness *= 25;
membersCompleted++;
}
return fitness;
}
void SmartRocketsApp::CheckCollisions()
{
for (int i = 0; i < PopulationSize; i++)
{
glm::vec2 min1 = glm::vec2(m_Population[i]->position.x - 5.0f, m_Population[i]->position.y - 5.0f);
glm::vec2 max1 = glm::vec2(m_Population[i]->position.x + 5.0f, m_Population[i]->position.y + 5.0f);
glm::vec2 endMin = m_EndGoal - glm::vec2(10.0f, 10.0f);
glm::vec2 endMax = m_EndGoal + glm::vec2(10.0f, 10.0f);
for (int j = 0; j < 2; j++)
{
bool collision = (max1.x < m_obstacles[j]->min.x || m_obstacles[j]->max.x < min1.x || max1.y < m_obstacles[j]->min.y || m_obstacles[j]->max.y < min1.y);
if (!collision)
m_Population[i]->setCrashed();
}
if (m_Population[i]->position.x > WindowX || m_Population[i]->position.x < 0
|| m_Population[i]->position.y > WindowY || m_Population[i]->position.y < 0)
{
m_Population[i]->setCrashed();
}
bool collisionEnd = (max1.x < endMin.x || endMax.x < min1.x || max1.y < endMin.y || endMax.y < min1.y);
if (!collisionEnd)
{
m_Population[i]->completed = true;
}
}
}
| 26.988281
| 155
| 0.669417
|
ElectroBean
|
fb67e61e5aa8f3f8640c947438d9de4ad3a4a232
| 542
|
cpp
|
C++
|
Chapter 18/stack.cpp
|
nikhilbadyal/learn-cpp-primer
|
48587c4b138d2c26ba56633c8e0f12d9a6dbea38
|
[
"MIT"
] | null | null | null |
Chapter 18/stack.cpp
|
nikhilbadyal/learn-cpp-primer
|
48587c4b138d2c26ba56633c8e0f12d9a6dbea38
|
[
"MIT"
] | null | null | null |
Chapter 18/stack.cpp
|
nikhilbadyal/learn-cpp-primer
|
48587c4b138d2c26ba56633c8e0f12d9a6dbea38
|
[
"MIT"
] | null | null | null |
#include<iostream>
using namespace std;
int main() {
int opc;
bool aux = true;
cin.exceptions(std::istream::failbit);
do {
try {
cout << "PLEASE INSERT VALUE:" << endl;
cin >> opc;
aux = true;
}
catch (std::ios_base::failure &fail) {
aux = false;
cout << "PLEASE INSERT A VALID OPTION." << endl;
cin.clear();
std::string tmp;
getline(cin, tmp);
}
} while (aux == false);
system("PAUSE");
}
| 23.565217
| 60
| 0.46679
|
nikhilbadyal
|
fb6edb931e25578d4b852d21b25c053e70112508
| 1,211
|
cpp
|
C++
|
src/nativefunc.cpp
|
end2endzone/msbuildreorder
|
9df4df177092e2ad141692ec7b43eb814b806d9b
|
[
"MIT"
] | 9
|
2018-12-18T11:56:26.000Z
|
2022-01-17T07:51:10.000Z
|
src/nativefunc.cpp
|
end2endzone/msbuildreorder
|
9df4df177092e2ad141692ec7b43eb814b806d9b
|
[
"MIT"
] | 15
|
2018-02-09T21:37:10.000Z
|
2019-07-20T19:31:41.000Z
|
src/nativefunc.cpp
|
end2endzone/msbuildreorder
|
9df4df177092e2ad141692ec7b43eb814b806d9b
|
[
"MIT"
] | 3
|
2018-12-18T11:56:29.000Z
|
2022-03-07T09:26:25.000Z
|
#include "nativefunc.h"
#ifdef WIN32
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN 1
#endif
#include <windows.h> // for Sleep()
#undef min
#undef max
#elif _POSIX_C_SOURCE >= 199309L
#include <time.h> // for nanosleep()
#else
#include <unistd.h> // for usleep()
#endif
namespace nativefunc
{
int millisleep(uint32_t milliseconds)
{
//code from https://stackoverflow.com/a/14818830 and https://stackoverflow.com/a/28827188
#if defined(WIN32)
SetLastError(0);
Sleep(milliseconds);
return GetLastError() ?-1 :0;
#elif _POSIX_C_SOURCE >= 199309L
/* prefer to use nanosleep() */
const struct timespec ts = {
(__time_t)milliseconds / 1000, /* seconds */
((__syscall_slong_t)milliseconds % 1000) * 1000 * 1000 /* nano seconds */
};
return nanosleep(&ts, NULL);
#elif _BSD_SOURCE || \
(_XOPEN_SOURCE >= 500 || \
_XOPEN_SOURCE && _XOPEN_SOURCE_EXTENDED) && \
!(_POSIX_C_SOURCE >= 200809L || _XOPEN_SOURCE >= 700)
/* else fallback to obsolte usleep() */
return usleep(1000 * milliseconds);
#else
# error ("No millisecond sleep available for this platform!")
return -1;
#endif
}
}; //nativefunc
| 25.229167
| 93
| 0.656482
|
end2endzone
|
fb71d1db2b1fc0f103665dd2dc91063f7604ba88
| 357
|
cc
|
C++
|
other/unordered_map/02.cc
|
chanchann/workflow_annotation
|
f986e65af82a91d9257a655ba7a4ece272b89c26
|
[
"MIT"
] | 66
|
2021-10-17T11:54:11.000Z
|
2022-03-29T13:05:02.000Z
|
other/unordered_map/02.cc
|
xjchilli/workflow_annotation
|
e91795aa91ee6c0d40f1ca0edd7e9c1338479e77
|
[
"MIT"
] | 1
|
2021-11-24T18:37:18.000Z
|
2021-11-29T12:49:47.000Z
|
other/unordered_map/02.cc
|
xjchilli/workflow_annotation
|
e91795aa91ee6c0d40f1ca0edd7e9c1338479e77
|
[
"MIT"
] | 17
|
2021-09-27T03:47:50.000Z
|
2022-03-22T08:22:12.000Z
|
#include <iostream>
#include <unordered_map>
int main()
{
std::unordered_map<std::string, std::string> map;
map["123"] = "abc";
map["4"] = "d";
std::unordered_map<std::string, std::string> map2;
map2 = std::move(map);
for(auto &m : map2)
{
std::cout << m.first << " : " << m.second << std::endl;
}
return 0;
}
| 18.789474
| 63
| 0.535014
|
chanchann
|
fb78746f889f253e934aef4eb56c3d66683ec97b
| 7,649
|
cpp
|
C++
|
test/nse_sequential_test.cpp
|
ahorn/smt-kit
|
d163b9a45ddf931820759e14f58f21b808ee7f57
|
[
"BSD-3-Clause"
] | 31
|
2015-01-31T03:56:01.000Z
|
2021-10-02T09:52:39.000Z
|
test/nse_sequential_test.cpp
|
ahorn/smt-kit
|
d163b9a45ddf931820759e14f58f21b808ee7f57
|
[
"BSD-3-Clause"
] | null | null | null |
test/nse_sequential_test.cpp
|
ahorn/smt-kit
|
d163b9a45ddf931820759e14f58f21b808ee7f57
|
[
"BSD-3-Clause"
] | 4
|
2015-01-13T12:32:42.000Z
|
2020-10-01T03:03:55.000Z
|
#include "nse_sequential.h"
// Include <gtest/gtest.h> _after_ "nse_sequential.h.h"
#include "gtest/gtest.h"
using namespace crv;
TEST(NseSequentialTest, Pointer)
{
Internal<char[]> array;
Internal<size_t> index;
index = 1;
array[0] = 'A';
array[1] = 'B';
array[2] = 'C';
Internal<char*> ptr = array;
EXPECT_TRUE(ptr[0].is_literal());
EXPECT_EQ('A', ptr[0].literal());
EXPECT_TRUE((*ptr).is_literal());
EXPECT_EQ('A', (*ptr).literal());
EXPECT_TRUE(ptr[1].is_literal());
EXPECT_EQ('B', ptr[1].literal());
EXPECT_TRUE(ptr[index].is_literal());
EXPECT_EQ('B', ptr[index].literal());
ptr++;
EXPECT_TRUE(ptr[0].is_literal());
EXPECT_EQ('B', ptr[0].literal());
EXPECT_TRUE((*ptr).is_literal());
EXPECT_EQ('B', (*ptr).literal());
EXPECT_TRUE(ptr[1].is_literal());
EXPECT_EQ('C', ptr[1].literal());
EXPECT_TRUE(ptr[index].is_literal());
EXPECT_EQ('C', ptr[index].literal());
ptr--;
EXPECT_TRUE(ptr[0].is_literal());
EXPECT_EQ('A', ptr[0].literal());
EXPECT_TRUE((*ptr).is_literal());
EXPECT_EQ('A', (*ptr).literal());
EXPECT_TRUE(ptr[1].is_literal());
EXPECT_EQ('B', ptr[1].literal());
EXPECT_TRUE(ptr[index].is_literal());
EXPECT_EQ('B', ptr[index].literal());
Internal<char*> ptr_copy(ptr);
++ptr_copy;
EXPECT_TRUE(ptr_copy[0].is_literal());
EXPECT_EQ('B', ptr_copy[0].literal());
EXPECT_TRUE((*ptr_copy).is_literal());
EXPECT_EQ('B', (*ptr_copy).literal());
EXPECT_TRUE(ptr_copy[1].is_literal());
EXPECT_EQ('C', ptr_copy[1].literal());
EXPECT_TRUE(ptr_copy[index].is_literal());
EXPECT_EQ('C', ptr_copy[index].literal());
constexpr size_t N = 5;
Internal<char[N]> n_array;
n_array[0] = 'A';
n_array[1] = 'B';
n_array[2] = 'C';
Internal<char*> n_ptr = n_array;
EXPECT_TRUE(n_ptr[0].is_literal());
EXPECT_EQ('A', n_ptr[0].literal());
EXPECT_TRUE((*n_ptr).is_literal());
EXPECT_EQ('A', (*n_ptr).literal());
EXPECT_TRUE(n_ptr[1].is_literal());
EXPECT_EQ('B', n_ptr[1].literal());
EXPECT_TRUE(n_ptr[index].is_literal());
EXPECT_EQ('B', n_ptr[index].literal());
array[1] = 'Y';
n_array[1] = 'Y';
// assignment operators
n_ptr = n_array;
EXPECT_EQ('Y', (*(++n_ptr)).literal());
ptr = array;
EXPECT_EQ('Y', (*(++ptr)).literal());
}
TEST(NseSequentialTest, UnaryIncrement)
{
Internal<int> a = 5;
Internal<int> b = a++;
Internal<int> c = ++a;
EXPECT_TRUE(a.is_literal());
EXPECT_TRUE(b.is_literal());
EXPECT_TRUE(c.is_literal());
EXPECT_EQ(7, a.literal());
EXPECT_EQ(5, b.literal());
EXPECT_EQ(7, c.literal());
}
TEST(NseSequentialTest, UnaryDecrement)
{
Internal<int> a = 5;
Internal<int> b = a--;
Internal<int> c = --a;
EXPECT_TRUE(a.is_literal());
EXPECT_TRUE(b.is_literal());
EXPECT_TRUE(c.is_literal());
EXPECT_EQ(3, a.literal());
EXPECT_EQ(5, b.literal());
EXPECT_EQ(3, c.literal());
}
TEST(NseSequentialTest, MakeZero)
{
Internal<int> a = 5;
Internal<int[3]> b;
make_zero(a);
EXPECT_TRUE(a.is_literal());
EXPECT_EQ(0, a.literal());
make_zero(b);
EXPECT_TRUE(b[0].is_literal());
EXPECT_TRUE(b[1].is_literal());
EXPECT_TRUE(b[2].is_literal());
EXPECT_EQ(0, b[0].literal());
EXPECT_EQ(0, b[1].literal());
EXPECT_EQ(0, b[2].literal());
}
TEST(NseSequentialTest, PointerChecks)
{
SequentialDfsChecker c0;
Internal<char[]> array;
Internal<char*> ptr = array;
EXPECT_FALSE(c0.branch(ptr[3] == 'D'));
c0.add_error(ptr[3] == 'D');
EXPECT_EQ(smt::unsat, c0.check());
EXPECT_TRUE(c0.find_next_path());
EXPECT_TRUE(c0.branch(ptr[3] == 'D'));
c0.add_error(ptr[3] == 'D');
EXPECT_EQ(smt::sat, c0.check());
EXPECT_FALSE(c0.find_next_path());
BacktrackDfsChecker c1;
make_any(array);
ptr = array;
EXPECT_FALSE(c1.branch(ptr[3] == 'D'));
c1.add_error(ptr[3] == 'D');
EXPECT_EQ(smt::unsat, c1.check());
EXPECT_TRUE(c1.find_next_path());
EXPECT_TRUE(c1.branch(ptr[3] == 'D'));
c1.add_error(ptr[3] == 'D');
EXPECT_EQ(smt::sat, c1.check());
EXPECT_FALSE(c1.find_next_path());
}
TEST(NseSequentialTest, SequentialDfsChecker)
{
SequentialDfsChecker checker;
// if (a < 7) { skip } ; if (a < 4) { skip }
Internal<int> a;
EXPECT_FALSE(checker.branch(a < 7));
EXPECT_FALSE(checker.branch(a < 4));
EXPECT_TRUE(checker.find_next_path());
EXPECT_FALSE(checker.branch(a < 7));
EXPECT_TRUE(checker.branch(a < 4));
// ignored because "a >= 7 and a < 4" is unsat
EXPECT_FALSE(checker.branch(a < 1));
EXPECT_FALSE(checker.branch(a < 2));
EXPECT_FALSE(checker.branch(a < 3));
EXPECT_TRUE(checker.find_next_path());
EXPECT_TRUE(checker.branch(a < 7));
EXPECT_FALSE(checker.branch(a < 4));
EXPECT_TRUE(checker.find_next_path());
EXPECT_TRUE(checker.branch(a < 7));
EXPECT_TRUE(checker.branch(a < 4));
EXPECT_FALSE(checker.find_next_path());
checker.reset();
Internal<int> b;
checker.add_assertion(b < 7);
EXPECT_TRUE(checker.branch(b < 7));
EXPECT_FALSE(checker.branch(b < 4));
EXPECT_TRUE(checker.find_next_path());
checker.add_assertion(b < 7);
EXPECT_TRUE(checker.branch(b < 7));
EXPECT_TRUE(checker.branch(b < 4));
EXPECT_FALSE(checker.find_next_path());
checker.reset();
Internal<int> c;
checker.add_assertion(c < 4);
EXPECT_TRUE(checker.branch(c < 7));
EXPECT_TRUE(checker.branch(c < 4));
EXPECT_FALSE(checker.find_next_path());
}
TEST(NseSequentialTest, Backtrack)
{
BacktrackDfsChecker checker;
// if (a < 7) { skip } ; if (a < 4) { skip }
Internal<int> a;
EXPECT_FALSE(checker.branch(a < 7));
EXPECT_FALSE(checker.branch(a < 4));
EXPECT_TRUE(checker.find_next_path());
EXPECT_FALSE(checker.branch(a < 7));
EXPECT_TRUE(checker.branch(a < 4));
// ignored because "a >= 7 and a < 4" is unsat
EXPECT_FALSE(checker.branch(a < 1));
EXPECT_FALSE(checker.branch(a < 2));
EXPECT_FALSE(checker.branch(a < 3));
EXPECT_TRUE(checker.find_next_path());
EXPECT_TRUE(checker.branch(a < 7));
EXPECT_FALSE(checker.branch(a < 4));
EXPECT_TRUE(checker.find_next_path());
EXPECT_TRUE(checker.branch(a < 7));
EXPECT_TRUE(checker.branch(a < 4));
EXPECT_FALSE(checker.find_next_path());
checker.reset();
// BacktrackDfsChecker may not prune as
// many paths as SequentialDfsChecker
Internal<int> b;
checker.add_assertion(b < 7);
EXPECT_FALSE(checker.branch(b < 7));
EXPECT_FALSE(checker.branch(b < 4));
EXPECT_TRUE(checker.find_next_path());
checker.add_assertion(b < 7);
EXPECT_TRUE(checker.branch(b < 7));
EXPECT_FALSE(checker.branch(b < 4));
EXPECT_TRUE(checker.find_next_path());
checker.add_assertion(b < 7);
EXPECT_TRUE(checker.branch(b < 7));
EXPECT_TRUE(checker.branch(b < 4));
EXPECT_FALSE(checker.find_next_path());
checker.reset();
// assertion at the end
EXPECT_FALSE(checker.branch(b < 7));
EXPECT_FALSE(checker.branch(b < 4));
checker.add_assertion(a < 7);
checker.add_assertion(b < 7);
EXPECT_TRUE(checker.find_next_path());
EXPECT_TRUE(checker.branch(b < 7));
EXPECT_FALSE(checker.branch(b < 4));
checker.add_assertion(a < 7);
checker.add_assertion(b < 7);
EXPECT_TRUE(checker.find_next_path());
EXPECT_TRUE(checker.branch(b < 7));
EXPECT_TRUE(checker.branch(b < 4));
checker.add_assertion(a < 7);
checker.add_assertion(b < 7);
EXPECT_FALSE(checker.find_next_path());
}
TEST(NseSequentialTest, NumericConditional)
{
BacktrackDfsChecker c0;
SequentialDfsChecker c1;
Internal<int> x;
c0.branch(x);
EXPECT_TRUE(c0.find_next_path());
c0.branch(x);
EXPECT_FALSE(c0.find_next_path());
c1.branch(x);
EXPECT_TRUE(c1.find_next_path());
c1.branch(x);
EXPECT_FALSE(c1.find_next_path());
}
| 23.46319
| 55
| 0.664139
|
ahorn
|
fb7ac381dceb1534684779aaaaf56c0826600701
| 9,199
|
cpp
|
C++
|
engine/renderer/gf3d_device.cpp
|
ddembner/gf3d_plusplus
|
cc426866bdf210645ad0e1d42056170a81083cec
|
[
"MIT"
] | null | null | null |
engine/renderer/gf3d_device.cpp
|
ddembner/gf3d_plusplus
|
cc426866bdf210645ad0e1d42056170a81083cec
|
[
"MIT"
] | null | null | null |
engine/renderer/gf3d_device.cpp
|
ddembner/gf3d_plusplus
|
cc426866bdf210645ad0e1d42056170a81083cec
|
[
"MIT"
] | null | null | null |
#include "core/gf3d_logger.h"
#include "gf3d_device.h"
#include "gf3d_validations.h"
#include "vulkan_functions.h"
#include "containers/vector.hpp"
void Gf3dDevice::init(Gf3dWindow* window)
{
assert(window);
gf3dWindow = window;
createInstance();
if (isValidationLayersEnabled()) {
setupDebugCallback();
LOGGER_DEBUG("Validation layers are enabled");
}
surface = window->createWindowSurface(instance);
findPhysicalDevice();
createLogicalDevice();
createMemoryAllocator();
createCommandPool();
}
void Gf3dDevice::createSurface()
{
surface = gf3dWindow->createWindowSurface(instance);
}
void Gf3dDevice::cleanup()
{
vkDestroyCommandPool(device, commandPool, nullptr);
vmaDestroyAllocator(allocator);
vkDestroyDevice(device, nullptr);
vkDestroySurfaceKHR(instance, surface, nullptr);
DestroyDebugUtilsMessengerEXT(instance, callback, nullptr);
vkDestroyInstance(instance, nullptr);
}
const u32 Gf3dDevice::GetQueueIndex(VkQueueFlags queueFlag)
{
switch (queueFlag)
{
case VK_QUEUE_GRAPHICS_BIT:
return queueIndices.graphics;
case VK_QUEUE_COMPUTE_BIT:
return queueIndices.compute;
case VK_QUEUE_TRANSFER_BIT:
return queueIndices.transfer;
default:
return 0;
}
}
void Gf3dDevice::createInstance()
{
VkApplicationInfo appInfo = {};
appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
appInfo.pNext = nullptr;
appInfo.apiVersion = VK_API_VERSION_1_2;
appInfo.applicationVersion = 1;
appInfo.engineVersion = 1;
appInfo.pApplicationName = "";
appInfo.pEngineName = "";
VkInstanceCreateInfo instanceInfo = {};
instanceInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
instanceInfo.pNext = nullptr;
instanceInfo.pApplicationInfo = &appInfo;
gf3d::vector<const char*> validationLayers = getValidationLayers();
if (isValidationLayersEnabled()) {
instanceInfo.enabledLayerCount = static_cast<u32>(validationLayers.size());
instanceInfo.ppEnabledLayerNames = validationLayers.data();
}
else {
instanceInfo.enabledLayerCount = 0;
}
u32 glfwExtensionCount = 0;
const char** glfwExtensions;
glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount);
gf3d::vector<const char*> extensions(glfwExtensions, glfwExtensions + glfwExtensionCount);
if (isValidationLayersEnabled()) {
extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
}
instanceInfo.enabledExtensionCount = static_cast<u32>(extensions.size());
instanceInfo.ppEnabledExtensionNames = extensions.data();
VK_CHECK(vkCreateInstance(&instanceInfo, nullptr, &instance));
if (!instance) {
LOGGER_ERROR("Failed to create vulkan insatnce");
}
}
void Gf3dDevice::setupDebugCallback()
{
VkDebugUtilsMessengerCreateInfoEXT createInfo = {};
createInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
createInfo.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT;
createInfo.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
createInfo.pfnUserCallback = gf3dVkValidationDebugCallback;
VK_CHECK(CreateDebugUtilsMessengerEXT(instance, reinterpret_cast<const VkDebugUtilsMessengerCreateInfoEXT*>(&createInfo), nullptr, &callback));
if (!callback) {
LOGGER_ERROR("Failed to create vulkan debug callbacks");
}
}
void Gf3dDevice::findPhysicalDevice()
{
u32 deviceCount;
vkEnumeratePhysicalDevices(instance, &deviceCount, nullptr);
assert(deviceCount > 0);
gf3d::vector<VkPhysicalDevice> devices(deviceCount);
vkEnumeratePhysicalDevices(instance, &deviceCount, devices.data());
for (u32 i = 0; i < devices.size(); i++) {
vkGetPhysicalDeviceProperties(devices[i], &physicalDeviceInfo.deviceProperties);
if (physicalDeviceInfo.deviceProperties.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU) {
physicalDevice = devices[i];
vkGetPhysicalDeviceFeatures(devices[i], &physicalDeviceInfo.deviceFeatures);
vkGetPhysicalDeviceMemoryProperties(devices[i], &physicalDeviceInfo.deviceMemoryProperties);
LOGGER_DEBUG("Picking discrete gpu: {}", physicalDeviceInfo.deviceProperties.deviceName);
return;
}
}
//default to first device
physicalDevice = devices[0];
vkGetPhysicalDeviceProperties(devices[0], &physicalDeviceInfo.deviceProperties);
vkGetPhysicalDeviceFeatures(devices[0], &physicalDeviceInfo.deviceFeatures);
vkGetPhysicalDeviceMemoryProperties(devices[0], &physicalDeviceInfo.deviceMemoryProperties);
LOGGER_DEBUG("Using fallback gpu: {}", physicalDeviceInfo.deviceProperties.deviceName);
}
void Gf3dDevice::createLogicalDevice()
{
const float queuePriority = 1.0f;
gf3d::vector<VkDeviceQueueCreateInfo> queueInfos;
gf3d::vector<const char*> deviceExtensions = { VK_KHR_SWAPCHAIN_EXTENSION_NAME };
VkPhysicalDeviceFeatures enabledDeviceFeatures = {};
queueIndices.graphics = findQueueFamilyIndex(VK_QUEUE_GRAPHICS_BIT);
VkDeviceQueueCreateInfo graphicsInfo = { VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO };
graphicsInfo.queueCount = 1;
graphicsInfo.pQueuePriorities = &queuePriority;
graphicsInfo.queueFamilyIndex = queueIndices.graphics;
queueInfos.push_back(graphicsInfo);
queueIndices.compute = findQueueFamilyIndex(VK_QUEUE_COMPUTE_BIT);
if (queueIndices.graphics != queueIndices.compute) {
VkDeviceQueueCreateInfo computeInfo = { VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO };
computeInfo.queueCount = 1;
computeInfo.pQueuePriorities = &queuePriority;
computeInfo.queueFamilyIndex = queueIndices.compute;
queueInfos.push_back(computeInfo);
}
queueIndices.transfer = findQueueFamilyIndex(VK_QUEUE_TRANSFER_BIT);
if (queueIndices.transfer != queueIndices.graphics && queueIndices.transfer != queueIndices.compute) {
VkDeviceQueueCreateInfo transferInfo = { VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO };
transferInfo.queueCount = 1;
transferInfo.pQueuePriorities = &queuePriority;
transferInfo.queueFamilyIndex = queueIndices.transfer;
queueInfos.push_back(transferInfo);
}
LOGGER_DEBUG("Graphics queue index: {}", queueIndices.graphics);
LOGGER_DEBUG("Compute queue index: {}", queueIndices.compute);
LOGGER_DEBUG("Transfer queue index: {}", queueIndices.transfer);
VkDeviceCreateInfo deviceInfo = { VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO };
deviceInfo.queueCreateInfoCount = static_cast<u32>(queueInfos.size());
deviceInfo.pQueueCreateInfos = queueInfos.data();
deviceInfo.enabledExtensionCount = static_cast<u32>(deviceExtensions.size());
deviceInfo.ppEnabledExtensionNames = deviceExtensions.data();
deviceInfo.pEnabledFeatures = &enabledDeviceFeatures;
VK_CHECK(vkCreateDevice(physicalDevice, &deviceInfo, nullptr, &device));
if (!physicalDevice) {
LOGGER_ERROR("Failed to find suitable gpu");
}
vkGetDeviceQueue(device, queueIndices.graphics, 0, &graphicsQueue);
vkGetDeviceQueue(device, queueIndices.compute, 0, &computeQueue);
vkGetDeviceQueue(device, queueIndices.transfer, 0, &transferQueue);
}
void Gf3dDevice::createMemoryAllocator()
{
VmaAllocatorCreateInfo createInfo = {};
createInfo.instance = instance;
createInfo.physicalDevice = physicalDevice;
createInfo.device = device;
createInfo.vulkanApiVersion = VK_API_VERSION_1_2;
vmaCreateAllocator(&createInfo, &allocator);
if (!allocator) {
LOGGER_ERROR("Failed to create allocator");
}
}
void Gf3dDevice::createCommandPool()
{
VkCommandPoolCreateInfo createInfo = { VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO };
createInfo.queueFamilyIndex = queueIndices.graphics;
createInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
VK_CHECK(vkCreateCommandPool(device, &createInfo, nullptr, &commandPool));
if (!allocator) {
LOGGER_ERROR("Failed to create command pool");
}
}
u32 Gf3dDevice::findQueueFamilyIndex(VkQueueFlags queueFlag)
{
u32 propertyCount;
vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &propertyCount, nullptr);
gf3d::vector<VkQueueFamilyProperties> queueFamilyProperties(propertyCount);
vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &propertyCount, queueFamilyProperties.data());
//Get dedicated compute queue
if (queueFlag & VK_QUEUE_COMPUTE_BIT) {
u32 queueIndex = 0;
for (u32 i = 0; i < static_cast<u32>(queueFamilyProperties.size()); i++) {
VkBool32 presentSupport;
vkGetPhysicalDeviceSurfaceSupportKHR(physicalDevice, i, surface, &presentSupport);
if (presentSupport) {
if (queueFamilyProperties[i].queueFlags & VK_QUEUE_COMPUTE_BIT &&
!(queueFamilyProperties[i].queueFlags & VK_QUEUE_GRAPHICS_BIT)) {
return i;
}
queueIndex = i;
}
}
return queueIndex;
}
//Get dedicated transfer queue
if (queueFlag & VK_QUEUE_TRANSFER_BIT) {
for (u32 i = 0; i < static_cast<u32>(queueFamilyProperties.size()); i++) {
if ((queueFamilyProperties[i].queueFlags & VK_QUEUE_TRANSFER_BIT) && !(queueFamilyProperties[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) && !(queueFamilyProperties[i].queueFlags & VK_QUEUE_COMPUTE_BIT)) {
return i;
}
}
}
//Get the index from any queue that supports flag
for (u32 i = 0; i < queueFamilyProperties.size(); i++) {
if (queueFamilyProperties[i].queueFlags & queueFlag) {
return i;
}
}
LOGGER_ERROR("Could not find a matching family index for the queue");
return UINT32_MAX;
}
| 33.695971
| 202
| 0.791608
|
ddembner
|
fb7ac8ea24cdccaaa589cf3dd339ed894cdea915
| 489
|
cpp
|
C++
|
Src/Mcal/X86PC_MSVC/Bsw/Mcal/Wdg/Wdg.cpp
|
miaozhendaoren/autosar-framework
|
abcf11970470c082b2137da16e9b1a460e72fd74
|
[
"BSL-1.0"
] | 31
|
2016-04-15T13:47:28.000Z
|
2022-01-26T17:40:26.000Z
|
Src/Mcal/X86PC_MSVC/Bsw/Mcal/Wdg/Wdg.cpp
|
myGiter/autosar-framework
|
abcf11970470c082b2137da16e9b1a460e72fd74
|
[
"BSL-1.0"
] | null | null | null |
Src/Mcal/X86PC_MSVC/Bsw/Mcal/Wdg/Wdg.cpp
|
myGiter/autosar-framework
|
abcf11970470c082b2137da16e9b1a460e72fd74
|
[
"BSL-1.0"
] | 21
|
2016-03-25T10:52:07.000Z
|
2022-03-25T22:58:39.000Z
|
///////////////////////////////////////////////////////
// Copyright 2013 Stephan Hage.
// Copyright 2013 Christopher Kormanyos.
// Distributed under the Boost
// Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt
// or copy at http://www.boost.org/LICENSE_1_0.txt )
//
#include <Bsw/Mcal/Wdg/Wdg.h>
EXTERN_C
void Wdg_Init(const Wdg_ConfigType* ConfigPtr)
{
static_cast<void>(ConfigPtr);
}
EXTERN_C
void Wdg_Trigger(void)
{
static_cast<void>(0U);
}
| 21.26087
| 56
| 0.638037
|
miaozhendaoren
|
fb8906fa16c0f99c125ef9fb2cffff43500f6d53
| 10,688
|
cpp
|
C++
|
DataStructure/tree/rbt.cpp
|
CloudHolic/algorithms
|
cfae9b723e432fd9a84600c2a0082a5412759821
|
[
"MIT"
] | null | null | null |
DataStructure/tree/rbt.cpp
|
CloudHolic/algorithms
|
cfae9b723e432fd9a84600c2a0082a5412759821
|
[
"MIT"
] | null | null | null |
DataStructure/tree/rbt.cpp
|
CloudHolic/algorithms
|
cfae9b723e432fd9a84600c2a0082a5412759821
|
[
"MIT"
] | null | null | null |
#include <queue>
#include <stack>
#include "rbt.h"
rbt::rbt() : root_(nullptr) {}
rbt:: rbt(const rbt& prev) : root_(nullptr)
{
root_ = copy(prev.root_);
}
rbt::rbt(rbt&& prev) noexcept : root_(nullptr)
{
*this = std::move(prev);
}
rbt::~rbt()
{
internal_clear(root_);
}
rbt& rbt::operator=(const rbt& prev)
{
if (this != &prev)
{
clear();
root_ = copy(prev.root_);
}
return *this;
}
rbt& rbt::operator=(rbt&& prev) noexcept
{
if (this != &prev)
{
clear();
std::swap(root_, prev.root_);
if (root_->left != nullptr)
root_->left->parent = root_;
if (root_->right != nullptr)
root_->right->parent = root_;
}
return *this;
}
void rbt::insert(const int value)
{
node* new_node = new node(value);
if (root_ == nullptr)
{
new_node->color = BLACK;
root_ = new_node;
}
else
{
node* target = search(value);
if (target->data == value)
return;
new_node->parent = target;
if (value < target->data)
target->left = new_node;
else
target->right = new_node;
fix_double_red(new_node);
}
}
void rbt::remove(const int value)
{
if (root_ == nullptr)
return;
node* target = search(value);
if (target->data != value)
return;
node* replace = find_replaceable(target);
node* parent = target->parent;
bool both_black = target->color == BLACK && (replace == nullptr || replace->color == BLACK);
if (replace == nullptr)
{
if (target == root_)
root_ = nullptr;
else
{
if (both_black)
fix_double_black(target);
else
if (target->sibling() != nullptr)
target->sibling()->color = RED;
if (target->is_left())
parent->left = nullptr;
else
parent->right = nullptr;
}
delete target;
}
else if (replace->left == nullptr || replace->right == nullptr)
{
if (target == root_)
{
target->data = replace->data;
target->left = target->right = nullptr;
delete replace;
}
else
{
if (target->is_left())
parent->left = replace;
else
parent->right = replace;
delete target;
replace->parent = parent;
if (both_black)
fix_double_black(replace);
else
replace->color = BLACK;
}
}
else
{
swap_value(target, replace);
remove(value);
}
}
bool rbt::exist(const int value) const
{
return search(value)->data == value;
}
vector<int> rbt::inorder() const
{
vector<int> result;
if (root_ == nullptr)
return result;
stack<node*> node_stack;
node* cur_node = root_;
while (cur_node != nullptr || !node_stack.empty())
{
while (cur_node != nullptr)
{
node_stack.push(cur_node);
cur_node = cur_node->left;
}
cur_node = node_stack.top();
node_stack.pop();
result.push_back(cur_node->data);
cur_node = cur_node->right;
}
return result;
}
vector<int> rbt::levelorder() const
{
vector<int> result;
if (root_ == nullptr)
return result;
queue<node*> node_queue;
node* cur_node = root_;
node_queue.push(cur_node);
while (!node_queue.empty())
{
cur_node = node_queue.front();
node_queue.pop();
result.push_back(cur_node->data);
if (cur_node->left != nullptr)
node_queue.push(cur_node->left);
if (cur_node->right != nullptr)
node_queue.push(cur_node->right);
}
return result;
}
void rbt::clear()
{
internal_clear(root_);
}
rbt::node* rbt::copy(const node* root) const
{
node* new_node = new node(root->data);
if (root->left != nullptr)
{
new_node->left = copy(root->left);
new_node->left->parent = new_node;
}
if (root->right != nullptr)
{
new_node->right = copy(root->right);
new_node->right->parent = new_node;
}
return new_node;
}
rbt::node* rbt::search(const int value) const
{
node* temp = root_;
while (temp != nullptr)
{
if (value < temp->data)
{
if (temp->left != nullptr)
break;
else
temp = temp->left;
}
else if (value > temp->data)
{
if (temp->right != nullptr)
break;
else
temp = temp->right;
}
else
break;
}
}
rbt::node* rbt::find_replaceable(node* target)
{
if (target->left != nullptr && target->right != nullptr)
{
node* temp = target->right;
while (temp->left != nullptr)
temp = temp->left;
return temp;
}
if (target->left == nullptr && target->right == nullptr)
return nullptr;
if (target->left != nullptr)
return target->left;
else
return target->right;
}
void rbt::fix_double_red(node* target)
{
if (target == root_)
{
target->color = BLACK;
return;
}
node* parent = target->parent;
node* grandparent = target->parent->parent;
node* uncle = target->uncle();
if (parent->color != BLACK)
{
if (uncle != nullptr && uncle->color == RED)
{
parent->color = BLACK;
uncle->color = BLACK;
grandparent->color = RED;
fix_double_red(grandparent);
}
else
{
if (parent->is_left())
{
if (target->is_left())
swap_color(parent, grandparent);
else
{
left_rotate(parent);
swap_color(target, grandparent);
}
right_rotate(grandparent);
}
else
{
if (target->is_left())
{
right_rotate(parent);
swap_color(target, grandparent);
}
else
swap_color(parent, grandparent);
left_rotate(grandparent);
}
}
}
}
void rbt::fix_double_black(node* target)
{
if (target == root_)
return;
node* parent = target->parent;
node* sibling = target->sibling();
if (sibling == nullptr)
fix_double_black(parent);
else
{
if (sibling->color == RED)
{
parent->color = RED;
sibling->color = BLACK;
if (sibling->is_left())
right_rotate(parent);
else
left_rotate(parent);
fix_double_black(target);
}
else
{
if (sibling->left != nullptr && sibling->left->color == RED)
{
if (sibling->is_left())
{
sibling->left->color = sibling->color;
sibling->color = parent->color;
right_rotate(parent);
}
else
{
sibling->left->color = parent->color;
right_rotate(sibling);
left_rotate(parent);
}
parent->color = BLACK;
}
else if (sibling->right != nullptr && sibling->right->color == RED)
{
if (sibling->is_left())
{
sibling->right->color = parent->color;
left_rotate(sibling);
right_rotate(parent);
}
else
{
sibling->right->color = sibling->color;
sibling->color = parent->color;
left_rotate(parent);
}
parent->color = BLACK;
}
else
{
sibling->color = RED;
if (parent->color == BLACK)
fix_double_black(parent);
else
parent->color = BLACK;
}
}
}
}
void rbt::left_rotate(node* target)
{
node* new_parent = target->right;
if (target == root_)
root_ = new_parent;
target->move_down(new_parent);
target->right = new_parent->left;
if (new_parent != nullptr)
new_parent->left->parent = target;
new_parent->left = target;
}
void rbt::right_rotate(node* target)
{
node* new_parent = target->left;
if (target == root_)
root_ = new_parent;
target->move_down(new_parent);
target->left = new_parent->right;
if (new_parent != nullptr)
new_parent->right->parent = target;
new_parent->right = target;
}
void rbt::swap_color(node* target1, node* target2)
{
node_color temp = target1->color;
target1->color = target2->color;
target2->color = temp;
}
void rbt::swap_value(node* target1, node* target2)
{
int temp = target1->data;
target1->data = target2->data;
target2->data = temp;
}
void rbt::internal_clear(node* root)
{
if (root->left != nullptr)
internal_clear(root->left);
if (root->right != nullptr)
internal_clear(root->right);
if (root->parent != nullptr)
{
if (root->parent->left == root)
root->parent->left = nullptr;
else if (root->parent->right == root)
root->parent->right = nullptr;
root->parent = nullptr;
}
delete root;
}
rbt::node::node(int value) : data(value)
{
left = right = parent = nullptr;
color = RED;
}
rbt::node* rbt::node::uncle()
{
if (parent == nullptr || parent->parent == nullptr)
return nullptr;
if (parent->is_left())
return parent->parent->right;
else
return parent->parent->left;
}
rbt::node* rbt::node::sibling()
{
if (parent == nullptr)
return nullptr;
if (is_left())
return parent->right;
return parent->left;
}
bool rbt::node::is_left()
{
return this == parent->left;
}
void rbt::node::move_down(node* new_parent)
{
if (parent != nullptr)
{
if (is_left())
parent->left = new_parent;
else
parent->right = new_parent;
}
new_parent->parent = parent;
parent = new_parent;
}
| 21.376
| 96
| 0.490457
|
CloudHolic
|
fb8976a813c3824c59f2ac5b121126d4a76287f1
| 192
|
cpp
|
C++
|
test/transport_test.cpp
|
quixai/quix-streams
|
d060dc8898bca807fc71e118cdb8b33a0381318c
|
[
"Apache-2.0"
] | 5
|
2022-01-24T23:21:09.000Z
|
2022-03-07T16:09:18.000Z
|
test/transport_test.cpp
|
quixai/quix-streams
|
d060dc8898bca807fc71e118cdb8b33a0381318c
|
[
"Apache-2.0"
] | null | null | null |
test/transport_test.cpp
|
quixai/quix-streams
|
d060dc8898bca807fc71e118cdb8b33a0381318c
|
[
"Apache-2.0"
] | null | null | null |
#include "gtest/gtest.h"
#include "transport/transport.h"
TEST(blaTest, test1) {
//arrange
Quix::Transport transport(5);
//act
//assert
EXPECT_EQ (transport.get (), 5);
}
| 19.2
| 37
| 0.630208
|
quixai
|
651f174fa5d668cd6576b4259c55d922877df658
| 1,136
|
cpp
|
C++
|
core/src/game/base_game.cpp
|
Darckore/SpaceAssault
|
287db7eff40e83fe08a34d50f617eedfaccb3a55
|
[
"MIT"
] | null | null | null |
core/src/game/base_game.cpp
|
Darckore/SpaceAssault
|
287db7eff40e83fe08a34d50f617eedfaccb3a55
|
[
"MIT"
] | null | null | null |
core/src/game/base_game.cpp
|
Darckore/SpaceAssault
|
287db7eff40e83fe08a34d50f617eedfaccb3a55
|
[
"MIT"
] | null | null | null |
#include "game/base_game.hpp"
#include "game/scene.hpp"
namespace engine
{
// Special members
base_game::base_game() noexcept :
m_engine{ *this }
{
}
// Private members
bool base_game::init() noexcept
{
if (!before_run())
{
// todo: error
return false;
}
update(time_type{});
return true;
}
void base_game::update(time_type dt) noexcept
{
scene().update(dt);
on_update(dt);
}
void base_game::render() noexcept
{
scene().render();
on_render();
}
// Protected members
void base_game::run() noexcept
{
m_engine.run();
}
void base_game::quit() noexcept
{
m_engine.shutdown();
}
base_game::graphics_type& base_game::gfx() noexcept
{
return m_engine.gfx();
}
base_game::scene_type& base_game::scene() noexcept
{
return *m_curScene;
}
bool base_game::switch_scene(scene_type& s) noexcept
{
if (!s)
{
// todo: Report error here
return false;
}
m_curScene = &s;
return true;
}
base_game::component_store& base_game::components() noexcept
{
return m_components;
}
}
| 15.561644
| 62
| 0.606514
|
Darckore
|
65288b560df5df25e7ef64e3d12cb872ecf1e822
| 2,179
|
cxx
|
C++
|
tests/city32.cxx
|
ogatatsu/consthash
|
25b21c8faab85cb19c2f566592f973048e7a250a
|
[
"MIT"
] | 34
|
2015-01-11T03:33:20.000Z
|
2022-01-06T07:00:46.000Z
|
tests/city32.cxx
|
ogatatsu/consthash
|
25b21c8faab85cb19c2f566592f973048e7a250a
|
[
"MIT"
] | 1
|
2015-01-25T21:56:38.000Z
|
2015-04-23T17:11:32.000Z
|
tests/city32.cxx
|
ogatatsu/consthash
|
25b21c8faab85cb19c2f566592f973048e7a250a
|
[
"MIT"
] | 6
|
2015-01-11T03:33:25.000Z
|
2022-01-06T07:00:46.000Z
|
#include "tests.hxx"
#include <consthash/cityhash32.hxx>
#include <cityhash/city.h>
#define CH_DET_TEST_FUNC_WITH(FUNCNAME, WITH_WHAT) \
TEST(city_utility, FUNCNAME) { WITH_WHAT(FUNCNAME); };
uint32_t Hash32Len0to4(const char *s, size_t len);
uint32_t Hash32Len5to12(const char *s, size_t len);
uint32_t Hash32Len13to24(const char *s, size_t len);
struct Hash32Len0to4_traits
{
static constexpr uint32_t hash_ct(const char* str, size_t len)
{
return consthash::__detail::Hash32Len0to4(str, len);
}
static uint32_t hash_rt(const char* str, size_t len)
{
return Hash32Len0to4(str, len);
}
template<uint32_t ct_res>
inline static void compare(uint32_t rt_res)
{
ASSERT_EQ(rt_res, ct_res);
}
};
HASHER_TEST_0to4(Hash32Len0to4, Hash32Len0to4_traits, RT2CT_NULL);
struct Hash32Len5to12_traits
{
static constexpr uint32_t hash_ct(const char* str, size_t len)
{
return consthash::__detail::Hash32Len5to12(str, len);
}
static uint32_t hash_rt(const char* str, size_t len)
{
return Hash32Len5to12(str, len);
}
template<uint32_t ct_res>
inline static void compare(uint32_t rt_res)
{
ASSERT_EQ(rt_res, ct_res);
}
};
HASHER_TEST_5to12(Hash32Len5to12, Hash32Len5to12_traits, RT2CT_NULL);
struct Hash32Len13to24_traits
{
static constexpr uint32_t hash_ct(const char* str, size_t len)
{
return consthash::__detail::Hash32Len13to24(str, len);
}
static uint32_t hash_rt(const char* str, size_t len)
{
return Hash32Len13to24(str, len);
}
template<uint32_t ct_res>
inline static void compare(uint32_t rt_res)
{
ASSERT_EQ(rt_res, ct_res);
}
};
HASHER_TEST_13to24(Hash32Len13to24, Hash32Len13to24_traits, RT2CT_NULL);
struct city32_traits
{
static constexpr uint32_t hash_ct(const char* str, size_t len)
{
return consthash::city32(str, len);
}
static uint32_t hash_rt(const char* str, size_t len)
{
return CityHash32(str, len);
}
template<uint32_t ct_res>
inline static void compare(uint32_t rt_res)
{
ASSERT_EQ(rt_res, ct_res);
}
};
HASHER_TEST_ALL_STD_TRAITS(city32, RT2CT_NULL);
| 22.697917
| 72
| 0.710418
|
ogatatsu
|
652f0a10b154cafa2f966c41ee2a8ec914efcbb1
| 42,359
|
hpp
|
C++
|
External/Console-Utils_0.1.4/Includes/ConsoleUtils/console-utils.hpp
|
ReverieWisp/ASCIIPlayer
|
678a6957b16fd48a20ff6ed97cba6886cbd5a51c
|
[
"BSD-3-Clause"
] | 5
|
2018-02-03T19:49:30.000Z
|
2020-09-07T12:29:19.000Z
|
External/Console-Utils_0.1.4/Includes/ConsoleUtils/console-utils.hpp
|
ReverieWisp/ASCIIPlayer
|
678a6957b16fd48a20ff6ed97cba6886cbd5a51c
|
[
"BSD-3-Clause"
] | 9
|
2018-02-27T06:37:12.000Z
|
2020-03-25T05:43:56.000Z
|
External/Console-Utils_0.1.4/Includes/ConsoleUtils/console-utils.hpp
|
ReverieWisp/ASCIIPlayer
|
678a6957b16fd48a20ff6ed97cba6886cbd5a51c
|
[
"BSD-3-Clause"
] | 2
|
2018-02-09T06:47:21.000Z
|
2019-05-12T07:04:01.000Z
|
// This is a combination header file that accounts for all sorts of console drawing and whatnot,
// expanding functionality and ease of use of rlutil.h by Tapio Vierros.
//
// Version: 1.4
// Date: Nov. 2016
//
// Console Utils Implementation by:
// Reverie Wisp
// JoShadow
///////////////////////////////////////////////////////////////////////
//rlutil.h
///////////////////////////////////////////////////////////////////////
#pragma once
/**
* File: rlutil.h
*
* About: Description
* This file provides some useful utilities for console mode
* roguelike game development with C and C++. It is aimed to
* be cross-platform (at least Windows and Linux).
*
* About: Copyright
* (C) 2010 Tapio Vierros
*
* About: Licensing (DWTFYW)
* See <License> (DWTFYW)
*
* Minor tweaks to this specific file: 2016 Reverie Wisp
*/
/// Define: RLUTIL_USE_ANSI
/// Define this to use ANSI escape sequences also on Windows
/// (defaults to using WinAPI instead).
#if 0
#define RLUTIL_USE_ANSI
#endif
/// Define: RLUTIL_STRING_T
/// Define/typedef this to your preference to override rlutil's string type.
///
/// Defaults to std::string with C++ and char* with C.
#if 0
#define RLUTIL_STRING_T char*
#endif
#ifdef __cplusplus
/// Common C++ headers
#include <iostream>
#include <string>
#include <sstream>
#include <cstring>
/// Namespace forward declarations
namespace rlutil {
void locate(int x, int y);
}
#else
void locate(int x, int y); // Forward declare for C to avoid warnings
#endif // __cplusplus
#ifndef RLUTIL_INLINE
#ifdef _MSC_VER
#define RLUTIL_INLINE __inline
#else
#define RLUTIL_INLINE __inline__
#endif
#endif
#ifdef _WIN32
#include <windows.h> // for WinAPI and Sleep()
#define _NO_OLDNAMES // for MinGW compatibility
#include <conio.h> // for getch() and kbhit()
#define getch _getch
#define kbhit _kbhit
#else
#ifdef __cplusplus
#include <cstdio> // for getch()
#else // __cplusplus
#include <stdio.h> // for getch()
#endif // __cplusplus
#include <termios.h> // for getch() and kbhit()
#include <unistd.h> // for getch(), kbhit() and (u)sleep()
#include <sys/ioctl.h> // for getkey()
#include <sys/types.h> // for kbhit()
#include <sys/time.h> // for kbhit()
/// Function: getch
/// Get character without waiting for Return to be pressed.
/// Windows has this in conio.h
RLUTIL_INLINE int getch(void) {
// Here be magic.
struct termios oldt, newt;
int ch;
tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
ch = getchar();
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
return ch;
}
/// Function: kbhit
/// Determines if keyboard has been hit.
/// Windows has this in conio.h
RLUTIL_INLINE int kbhit(void) {
// Here be dragons.
static struct termios oldt, newt;
int cnt = 0;
tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON | ECHO);
newt.c_iflag = 0; // input mode
newt.c_oflag = 0; // output mode
newt.c_cc[VMIN] = 1; // minimum time to wait
newt.c_cc[VTIME] = 1; // minimum characters to wait for
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
ioctl(0, FIONREAD, &cnt); // Read count
struct timeval tv;
tv.tv_sec = 0;
tv.tv_usec = 100;
select(STDIN_FILENO+1, NULL, NULL, NULL, &tv); // A small time delay
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
return cnt; // Return number of characters
}
#endif // _WIN32
#ifndef gotoxy
/// Function: gotoxy
/// Same as <rlutil.locate>.
RLUTIL_INLINE void gotoxy(int x, int y) {
#ifdef __cplusplus
rlutil::
#endif
locate(x,y);
}
#endif // gotoxy
#ifdef __cplusplus
/// Namespace: rlutil
/// In C++ all functions except <getch>, <kbhit> and <gotoxy> are arranged
/// under namespace rlutil. That is because some platforms have them defined
/// outside of rlutil.
namespace rlutil {
#endif
/**
* Defs: Internal typedefs and macros
* RLUTIL_STRING_T - String type depending on which one of C or C++ is used
* RLUTIL_PRINT(str) - Printing macro independent of C/C++
*/
#ifdef __cplusplus
#ifndef RLUTIL_STRING_T
typedef std::string RLUTIL_STRING_T;
#endif // RLUTIL_STRING_T
inline void RLUTIL_PRINT(RLUTIL_STRING_T st) { std::cout << st; }
#else // __cplusplus
#ifndef RLUTIL_STRING_T
typedef char* RLUTIL_STRING_T;
#endif // RLUTIL_STRING_T
#define RLUTIL_PRINT(st) printf("%s", st)
#endif // __cplusplus
/**
* Enums: Color codes
*
* BLACK - Black
* BLUE - Blue
* GREEN - Green
* CYAN - Cyan
* RED - Red
* MAGENTA - Magenta / purple
* BROWN - Brown / dark yellow
* GREY - Grey / dark white
* DARKGREY - Dark grey / light black
* LIGHTBLUE - Light blue
* LIGHTGREEN - Light green
* LIGHTCYAN - Light cyan
* LIGHTRED - Light red
* LIGHTMAGENTA - Light magenta / light purple
* YELLOW - Yellow (bright)
* WHITE - White (bright)
*/
enum {
BLACK,
BLUE,
GREEN,
CYAN,
RED,
MAGENTA,
BROWN,
GREY,
DARKGREY,
LIGHTBLUE,
LIGHTGREEN,
LIGHTCYAN,
LIGHTRED,
LIGHTMAGENTA,
YELLOW,
WHITE
};
/**
* Consts: ANSI color strings
*
* ANSI_CLS - Clears screen
* ANSI_BLACK - Black
* ANSI_RED - Red
* ANSI_GREEN - Green
* ANSI_BROWN - Brown / dark yellow
* ANSI_BLUE - Blue
* ANSI_MAGENTA - Magenta / purple
* ANSI_CYAN - Cyan
* ANSI_GREY - Grey / dark white
* ANSI_DARKGREY - Dark grey / light black
* ANSI_LIGHTRED - Light red
* ANSI_LIGHTGREEN - Light green
* ANSI_YELLOW - Yellow (bright)
* ANSI_LIGHTBLUE - Light blue
* ANSI_LIGHTMAGENTA - Light magenta / light purple
* ANSI_LIGHTCYAN - Light cyan
* ANSI_WHITE - White (bright)
*/
const RLUTIL_STRING_T ANSI_CLS = "\033[2J";
const RLUTIL_STRING_T ANSI_BLACK = "\033[22;30m";
const RLUTIL_STRING_T ANSI_RED = "\033[22;31m";
const RLUTIL_STRING_T ANSI_GREEN = "\033[22;32m";
const RLUTIL_STRING_T ANSI_BROWN = "\033[22;33m";
const RLUTIL_STRING_T ANSI_BLUE = "\033[22;34m";
const RLUTIL_STRING_T ANSI_MAGENTA = "\033[22;35m";
const RLUTIL_STRING_T ANSI_CYAN = "\033[22;36m";
const RLUTIL_STRING_T ANSI_GREY = "\033[22;37m";
const RLUTIL_STRING_T ANSI_DARKGREY = "\033[01;30m";
const RLUTIL_STRING_T ANSI_LIGHTRED = "\033[01;31m";
const RLUTIL_STRING_T ANSI_LIGHTGREEN = "\033[01;32m";
const RLUTIL_STRING_T ANSI_YELLOW = "\033[01;33m";
const RLUTIL_STRING_T ANSI_LIGHTBLUE = "\033[01;34m";
const RLUTIL_STRING_T ANSI_LIGHTMAGENTA = "\033[01;35m";
const RLUTIL_STRING_T ANSI_LIGHTCYAN = "\033[01;36m";
const RLUTIL_STRING_T ANSI_WHITE = "\033[01;37m";
/// Function: getANSIColor
/// Return ANSI color escape sequence for specified number 0-15.
///
/// See <Color Codes>
RLUTIL_INLINE RLUTIL_STRING_T getANSIColor(const int c) {
switch (c) {
case 0 : return ANSI_BLACK;
case 1 : return ANSI_BLUE; // non-ANSI
case 2 : return ANSI_GREEN;
case 3 : return ANSI_CYAN; // non-ANSI
case 4 : return ANSI_RED; // non-ANSI
case 5 : return ANSI_MAGENTA;
case 6 : return ANSI_BROWN;
case 7 : return ANSI_GREY;
case 8 : return ANSI_DARKGREY;
case 9 : return ANSI_LIGHTBLUE; // non-ANSI
case 10: return ANSI_LIGHTGREEN;
case 11: return ANSI_LIGHTCYAN; // non-ANSI;
case 12: return ANSI_LIGHTRED; // non-ANSI;
case 13: return ANSI_LIGHTMAGENTA;
case 14: return ANSI_YELLOW; // non-ANSI
case 15: return ANSI_WHITE;
default: return "";
}
}
/// Function: setColor
/// Change color specified by number (Windows / QBasic colors).
///
/// See <Color Codes>
RLUTIL_INLINE void setColor(int c) {
#if defined(_WIN32) && !defined(RLUTIL_USE_ANSI)
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hConsole, (WORD)c);
#else
RLUTIL_PRINT(getANSIColor(c));
#endif
}
/// Function: locate
/// Sets the cursor position to 1-based x,y.
RLUTIL_INLINE void locate(int x, int y) {
#if defined(_WIN32) && !defined(RLUTIL_USE_ANSI)
COORD coord;
coord.X = (SHORT)x-1;
coord.Y = (SHORT)y-1; // Windows uses 0-based coordinates
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
#else // _WIN32 || USE_ANSI
#ifdef __cplusplus
std::ostringstream oss;
oss << "\033[" << y << ";" << x << "H";
RLUTIL_PRINT(oss.str());
#else // __cplusplus
char buf[32];
sprintf(buf, "\033[%d;%df", y, x);
RLUTIL_PRINT(buf);
#endif // __cplusplus
#endif // _WIN32 || USE_ANSI
}
/// Function: hidecursor
/// Hides the cursor.
RLUTIL_INLINE void hidecursor(void) {
#if defined(_WIN32) && !defined(RLUTIL_USE_ANSI)
HANDLE hConsoleOutput;
CONSOLE_CURSOR_INFO structCursorInfo;
hConsoleOutput = GetStdHandle( STD_OUTPUT_HANDLE );
GetConsoleCursorInfo( hConsoleOutput, &structCursorInfo ); // Get current cursor size
structCursorInfo.bVisible = FALSE;
SetConsoleCursorInfo( hConsoleOutput, &structCursorInfo );
#else // _WIN32 || USE_ANSI
RLUTIL_PRINT("\033[?25l");
#endif // _WIN32 || USE_ANSI
}
/// Function: showcursor
/// Shows the cursor.
RLUTIL_INLINE void showcursor(void) {
#if defined(_WIN32) && !defined(RLUTIL_USE_ANSI)
HANDLE hConsoleOutput;
CONSOLE_CURSOR_INFO structCursorInfo;
hConsoleOutput = GetStdHandle( STD_OUTPUT_HANDLE );
GetConsoleCursorInfo( hConsoleOutput, &structCursorInfo ); // Get current cursor size
structCursorInfo.bVisible = TRUE;
SetConsoleCursorInfo( hConsoleOutput, &structCursorInfo );
#else // _WIN32 || USE_ANSI
RLUTIL_PRINT("\033[?25h");
#endif // _WIN32 || USE_ANSI
}
/// Function: msleep
/// Waits given number of milliseconds before continuing.
RLUTIL_INLINE void msleep(unsigned int ms) {
#ifdef _WIN32
Sleep(ms);
#else
// usleep argument must be under 1 000 000
if (ms > 1000) sleep(ms/1000000);
usleep((ms % 1000000) * 1000);
#endif
}
/// Function: trows
/// Get the number of rows in the terminal window or -1 on error.
RLUTIL_INLINE int trows(void) {
#ifdef _WIN32
CONSOLE_SCREEN_BUFFER_INFO csbi;
if (!GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi))
return -1;
else
return csbi.srWindow.Bottom - csbi.srWindow.Top + 1; // Window height
// return csbi.dwSize.Y; // Buffer height
#else
#ifdef TIOCGSIZE
struct ttysize ts;
ioctl(STDIN_FILENO, TIOCGSIZE, &ts);
return ts.ts_lines;
#elif defined(TIOCGWINSZ)
struct winsize ts;
ioctl(STDIN_FILENO, TIOCGWINSZ, &ts);
return ts.ws_row;
#else // TIOCGSIZE
return -1;
#endif // TIOCGSIZE
#endif // _WIN32
}
/// Function: tcols
/// Get the number of columns in the terminal window or -1 on error.
RLUTIL_INLINE int tcols(void) {
#ifdef _WIN32
CONSOLE_SCREEN_BUFFER_INFO csbi;
if (!GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi))
return -1;
else
return csbi.srWindow.Right - csbi.srWindow.Left + 1; // Window width
// return csbi.dwSize.X; // Buffer width
#else
#ifdef TIOCGSIZE
struct ttysize ts;
ioctl(STDIN_FILENO, TIOCGSIZE, &ts);
return ts.ts_cols;
#elif defined(TIOCGWINSZ)
struct winsize ts;
ioctl(STDIN_FILENO, TIOCGWINSZ, &ts);
return ts.ws_col;
#else // TIOCGSIZE
return -1;
#endif // TIOCGSIZE
#endif // _WIN32
}
/// Function: cls
/// Clears screen and moves cursor home.
RLUTIL_INLINE void cls(void) {
if (trows() == 0 || tcols() == 0)
return;
#if defined(_WIN32) && !defined(RLUTIL_USE_ANSI)
system("cls");
#else
RLUTIL_PRINT("\033[2J\033[H");
#endif
}
#ifndef min
/// Function: min
/// Returns the lesser of the two arguments.
#ifdef __cplusplus
template <class T> const T& min ( const T& a, const T& b ) { return (a<b)?a:b; }
#else
#define min(a,b) (((a)<(b))?(a):(b))
#endif // __cplusplus
#endif // min
#ifndef max
/// Function: max
/// Returns the greater of the two arguments.
#ifdef __cplusplus
template <class T> const T& max ( const T& a, const T& b ) { return (b<a)?a:b; }
#else
#define max(a,b) (((b)<(a))?(a):(b))
#endif // __cplusplus
#endif // max
// Classes are here at the end so that documentation is pretty.
#ifdef __cplusplus
/// Class: CursorHider
/// RAII OOP wrapper for <rlutil.hidecursor>.
/// Hides the cursor and shows it again
/// when the object goes out of scope.
struct CursorHider {
CursorHider() { hidecursor(); }
~CursorHider() { showcursor(); }
};
} // namespace rlutil
#endif
///////////////////////////////////////////////////////////////////////
//Colors.hpp
///////////////////////////////////////////////////////////////////////
#pragma once
namespace RConsole
{
//Colors!
enum Color
{
//Acquire rlutil info where possible--
BLACK = rlutil::BLACK,
BLUE = rlutil::BLUE,
GREEN = rlutil::GREEN,
CYAN = rlutil::CYAN,
RED = rlutil::RED,
MAGENTA = rlutil::MAGENTA,
BROWN = rlutil::BROWN,
GREY = rlutil::GREY,
DARKGREY = rlutil::DARKGREY,
LIGHTBLUE = rlutil::LIGHTBLUE,
LIGHTGREEN = rlutil::LIGHTGREEN,
LIGHTCYAN = rlutil::LIGHTCYAN,
LIGHTRED = rlutil::LIGHTRED,
LIGHTMAGENTA = rlutil::LIGHTMAGENTA,
YELLOW = rlutil::YELLOW,
WHITE = rlutil::WHITE,
// Add custom values
//DEFAULT = rlutil::DEFAULT, // BROKEN //Added custom to the rlutil header.
PREVIOUS_COLOR
};
}
///////////////////////////////////////////////////////////////////////
//Field2D.hpp
///////////////////////////////////////////////////////////////////////
// For strict unused variable warnings.
#define UNUSED(x) (void)(x)
/////// OS DEFINES /////////
// Windows
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__)
#define OS_WINDOWS
#endif
// MacOSX
#if defined(__APPLE__)
#define OS_MACOSX
#endif
// Linux
#if defined(__linux__)
#define OS_LINUX
#endif
#if defined(OS_MACOSX) || defined(OS_LINUX)
#define OS_POSIX
#endif
/////// COMPILER DEFINES /////////
#if defined(_MSC_VER)
#define COMPILER_VS
#endif
/////// CONSOLE SETTINGS /////////
#define RConsole_CLIP_CONSOLE // Define we want console clipping
#define RConsole_NO_THREADING // Define we aren't threading- printf becomes unsafe, but faster.
#ifdef COMPILER_VS
// VS complains about unused functions.
#pragma warning(disable: 4505) //Unreferenced local function has been removed
#else
// g++/clang++ complain about unused functions.
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-function"
#endif
namespace RFuncs
{
// Absolute value of int.
static int Abs(int x)
{
if (x < 0)
return -x;
return x;
}
}
#ifdef COMPILER_VS
// restore VS warning
#pragma warning(default: 4505) //Unreferenced local function has been removed
#else
// restore g++/glang warnings
#pragma GCC diagnostic pop
#endif
namespace RConsole
{
// Forward declare Field2D for use later.
template <typename T>
class Field2D;
// A proxy class for the [] operator, allowing you to use the [] operator
template <typename T>
class Field2DProxy
{
// Mark the Field2D as my friend!
friend Field2D<T>;
public:
// Operator Overload
T &operator[](unsigned int y);
private:
// Private constructor, friends only!
Field2DProxy(Field2D<T> *parentField, unsigned int xPos);
// Variables
Field2D<T> *field_;
const int x_;
};
// A 2D way to represent a 1D line of continuous memory.
// The 2D Field keeps track of the current index you are at in memory, allowing really
// cheap O(K) reading if you have the spot selected, with a single add.
// Note that this is not guarded- if you reach the "end" of the width, it will
// let you freely step onto the next row of the 2D array you have set up.
template <typename T>
class Field2D
{
// Friensd can see ALL!
friend Field2DProxy<T>;
public:
// Constructor
Field2D(unsigned int w, unsigned int h);
Field2D(unsigned int w, unsigned int h, const T defaultVal);
Field2D &operator=(const Field2D &rhs);
Field2D(const Field2D &rhs);
~Field2D();
// Structure Info
unsigned int Width() const;
unsigned int Height() const;
unsigned int Length() const;
// Member Functions - Complex Manipulation
void Zero();
void Set(const T &newItem);
T &Get(unsigned int x, unsigned int y);
Field2DProxy<T> operator[](unsigned int xPos);
void GoTo(unsigned int x, unsigned int y);
const T& Get(unsigned int x, unsigned int y) const;
const T& Peek(unsigned int x, unsigned int y) const;
const T& Peek(unsigned int index) const;
void Fill(const T &objToUse);
void Fill(const T &objToUse, unsigned int startIndex, unsigned int endIndex);
// Basic Manipulation
T &Get();
T* GetHead() { return data_;}
const T &Get() const;
void IncrementX();
void IncrementY();
void DecrementX();
void DecrementY();
unsigned int GetIndex();
void SetIndex(unsigned int index);
private:
// Variables
unsigned int index_;
unsigned int width_;
unsigned int height_;
T *data_;
};
}
// Template implementations: Place in separate file:
namespace RConsole
{
//////////////////////////////////
// Field2DProxy Methods and Co. //
//////////////////////////////////
template <typename T>
inline Field2DProxy<T>::Field2DProxy(Field2D<T> *parentField, unsigned int xPos)
: field_(parentField)
, x_(xPos)
{ }
// [] Operator Overload.
// Note- This sets the current index!
template <typename T>
inline T &Field2DProxy<T>::operator[](unsigned int y)
{
field_->GoTo(x_, y);
return field_->Get();
}
////////////////////
// Structure Info //
////////////////////
// Gets the width of the Field2D
template <typename T>
inline unsigned int Field2D<T>::Width() const
{
return width_;
}
// Gets the height of the Field2D
template <typename T>
inline unsigned int Field2D<T>::Height() const
{
return height_;
}
template <typename T>
inline unsigned int Field2D<T>::Length() const
{
return width_ * height_;
}
/////////////////////////////
// Field2D Methods and Co. //
/////////////////////////////
// Constructor
// Defaults by setting everything to 0.
template <typename T>
inline Field2D<T>::Field2D(unsigned int w, unsigned int h)
: index_(0)
, width_(w)
, height_(h)
, data_(nullptr)
{
data_ = new T[w * h];
Zero();
};
// Sets all values to given default.
template <typename T>
inline Field2D<T>::Field2D(unsigned int w, unsigned int h, const T defaultVal)
: index_(0)
, width_(w)
, height_(h)
, data_(nullptr)
{
T* adsf = new T[w * h];
data_ = adsf;
for (unsigned int i = 0; i < w; ++i)
for (unsigned int j = 0; j < h; ++j)
{
Set(defaultVal);
IncrementX();
}
index_ = 0;
}
template <typename T>
inline Field2D<T>::Field2D(const Field2D<T> &rhs)
{
if (data_)
{
delete[] data_;
data_ = nullptr;
}
data_ = new T[rhs.width_ * rhs.height_];
width_ = rhs.width_;
height_ = rhs.height_;
index_ = rhs.index_;
for (unsigned int i = 0; i < width_ * height_; ++i)
data_[i] = rhs.data_[i];
}
// Assignment operator
template <typename T>
inline Field2D<T> & Field2D<T>::operator=(const Field2D<T> &rhs)
{
if (&rhs != this)
{
if (data_)
{
delete[] data_;
data_ = nullptr;
}
data_ = new T[rhs.width_ * rhs.height_];
width_ = rhs.width_;
height_ = rhs.height_;
index_ = rhs.index_;
for (unsigned int i = 0; i < width_ * height_; ++i)
data_[i] = rhs.data_[i];
}
return *this;
}
// Destructor
template <typename T>
inline Field2D<T>::~Field2D()
{
index_ = 0;
delete[] data_;
data_ = nullptr;
}
////////////////////////
// Complex Operations //
////////////////////////
// Get the item at the position X, Y.
// Does not set the actual index of the Field!
template <typename T>
inline T &Field2D<T>::Get(unsigned int x, unsigned int y)
{
GoTo(x, y);
return Get();
}
// Const version of get that returns const reference.
template <typename T>
inline const T &Field2D<T>::Get(unsigned int x, unsigned int y) const
{
return Get(x, y);
}
// Get the first part of a 2D array operator
template <typename T>
inline Field2DProxy<T> Field2D<T>::operator[](unsigned int xPos)
{
return Field2DProxy<T>(this, xPos);
}
// Set the value at the current index
template <typename T>
inline void Field2D<T>::Set(const T &newItem)
{
data_[index_] = newItem;
}
// Glance at a read-only version of a specified location. Does NOT set index.
template <typename T>
inline const T& Field2D<T>::Peek(unsigned int x, unsigned int y) const
{
return data_[x + y * width_];
}
// Get the value at the specified index.
template <typename T>
inline const T& Field2D<T>::Peek(unsigned int index) const
{
return data_[index];
}
// Chance selected index to specified point.
template <typename T>
inline void Field2D<T>::GoTo(unsigned int x, unsigned int y)
{
index_ = x + y * width_;
}
// Sets all memory to 0. Does NOT modify index!
template <typename T>
inline void Field2D<T>::Zero()
{
memset(data_, 0, sizeof(T) * width_ * height_);
}
// Sets all memory to whatever you want.
template <typename T>
inline void Field2D<T>::Fill(const T &objToUse)
{
Fill(objToUse, 0, Length());
}
// Fills a specific range to whatever I want, inclusive for start index and
// excludes end index.
template <typename T>
inline void Field2D<T>::Fill(const T &objToUse, unsigned int startIndex, unsigned int endIndex)
{
unsigned int prevIndex = index_;
index_ = startIndex;
for (unsigned int i = startIndex; i < endIndex; ++i)
{
Set(objToUse);
IncrementX();
}
index_ = prevIndex;
}
//////////////////////
// Cheap operations //
//////////////////////
// Get the value at the current index.
template <typename T>
inline T &Field2D<T>::Get()
{
return data_[index_];
}
// Const get.
template <typename T>
inline const T& Field2D<T>::Get() const
{
return data_[index_];
}
// Increment X location by 1 in the 2D field
template <typename T>
inline void Field2D<T>::IncrementX()
{
++index_;
}
// Increment Y location by 1 in the 2D field
template <typename T>
inline void Field2D<T>::IncrementY()
{
index_ += width_;
}
// Decrement X location by 1 in the 2D field
template <typename T>
inline void Field2D<T>::DecrementX()
{
--index_;
}
// Decrement Y location by 1 in the 2D Field
template <typename T>
inline void Field2D<T>::DecrementY()
{
index_ -= width_;
}
// Gets the index that the 2D Field currently has.
template <typename T>
inline unsigned int Field2D<T>::GetIndex()
{
return index_;
}
// Gets the index that the 2D Field currently has.
template <typename T>
inline void Field2D<T>::SetIndex(unsigned int index)
{
index_ = index;
}
}
///////////////////////////////////////////////////////////////////////
//CanvasRaster.hpp
///////////////////////////////////////////////////////////////////////
namespace RConsole
{
// The raster info struct, holds info on what is to be drawn at a location and the color.
struct RasterInfo
{
RasterInfo();
RasterInfo(const char val, Color col);
bool operator ==(const RasterInfo &rhs) const;
bool operator !=(const RasterInfo &rhs) const;
char Value;
Color C;
};
// Console raster class
class Canvas;
class CanvasRaster
{
friend Canvas;
public:
// Constructors
CanvasRaster(unsigned int width, unsigned int height);
// Method Prototypes
bool WriteChar(char toDraw, float x, float y, Color color = PREVIOUS_COLOR);
bool WriteString(const char *toWrite, size_t len, float x, float y, Color color = PREVIOUS_COLOR);
const Field2D<RasterInfo>& GetRasterData() const;
void Fill(const RasterInfo &ri);
void Zero();
// General
unsigned int GetRasterWidth() const;
unsigned int GetRasterHeight() const;
private:
// Private member functions
Field2D<RasterInfo>& GetRasterData();
// Variables
unsigned int width_;
unsigned int height_;
Field2D<RasterInfo> data_;
};
}
///////////////////////////////////////////////////////////////////////
//Canvas.hpp
///////////////////////////////////////////////////////////////////////
namespace RConsole
{
class Canvas
{
public:
// Init call
static void ReInit(unsigned int width, unsigned int height);
// Basic drawing calls
static bool Update();
static void FillCanvas(const RasterInfo &ri = RasterInfo(' ', WHITE));
static void Draw(char toWrite, float x, float y, Color color = PREVIOUS_COLOR);
static void Draw(char toWrite, int x, int y, Color color = PREVIOUS_COLOR);
static void DrawString(const char* toDraw, float xStart, float yStart, Color color = PREVIOUS_COLOR);
static void DrawString(const char* toDraw, int xStart, int yStart, Color color = PREVIOUS_COLOR);
static void DrawAlpha(float x, float y, Color color, float opacity);
static void Shutdown();
// EXPENSIVE ONE-TIME CALLS! UNDEFINED RASTER BEHAVIOR IF THERE ARE THINGS IN IT. DO NOT CALL EVERY FRAME.
static void ForceClearEverything() { fullClear(); }
// Advanced drawing calls
static void DrawPartialPoint(float x, float y, Color color);
static void DrawBox(char toWrite, float x1, float y1, float x2, float y2, Color color);
static void SetCursorVisible(bool isVisible);
static void DumpRaster(FILE *fp = stdout);
static void CropRaster(FILE *fp = stdout, char toTrim = ' ');
// Data related calls
static unsigned int GetConsoleWidth();
static unsigned int GetConsoleHeight();
private:
// Hidden Constructors- no instantiating publicly!
Canvas() { };
Canvas(const Canvas &rhs) { *this = rhs; }
// Private methods.
static void clearPrevious();
static void fullClear();
static void setColor(const Color &color);
static bool writeRaster(CanvasRaster &r);
static int putC(int character, FILE * stream );
static void setCloseHandler();
// Any rasters we have. Could be expanded to have two, so you could "swap" them,
// Although practicality of that is limited given the clearing technique.
static CanvasRaster r_;
static CanvasRaster prev_;
// The tabs on what was last modified. This is important, because we will only update
// what we care about.
static bool hasLazyInit_;
static bool isDrawing_;
static unsigned int width_;
static unsigned int height_;
static Field2D<bool> modified_;
};
}
///////////////////////////////////////////////////////////////////////
//CanvasRaster.cpp
///////////////////////////////////////////////////////////////////////
namespace RConsole
{
/////////////////////////
// Raster info object //
////////////////////////
//
//constructor, no character and just the previous color.
inline RasterInfo::RasterInfo() : Value(0), C(Color::PREVIOUS_COLOR)
{ }
// Non-Default constructor, specifies const character and color.
inline RasterInfo::RasterInfo(const char val, Color col) : Value(val), C(col)
{ }
// Overloaded comparision operator that checks all fields.
inline bool RasterInfo::operator ==(const RasterInfo &rhs) const
{
if (rhs.C == C && rhs.Value == Value)
return true;
return false;
}
// Overloaded comparison operator that checks all fields.
inline bool RasterInfo::operator !=(const RasterInfo &rhs) const
{
return !(*this == rhs);
}
///////////////////////////
// Console Raster object //
///////////////////////////
// Default constructor for the CanvasRaster- Zeros data and gets width and height.
inline CanvasRaster::CanvasRaster(unsigned int width, unsigned int height)
: width_(width)
, height_(height)
, data_(width, height, RasterInfo(' ', RConsole::WHITE))
{ }
// Draws a character to the screen. Returns if it was successful or not.
inline bool CanvasRaster::WriteChar(char toDraw, float x, float y, Color color)
{
#ifdef RConsole_CLIP_CONSOLE
if (x > width_) return false;
if (y > height_) return false;
#endif // RConsole_CLIP_CONSOLE
data_.GoTo(static_cast<int>(x), static_cast<int>(y));
data_.Set(RasterInfo(toDraw, color));
//Everything completed correctly.
return true;
}
// Writes a string to the field
inline bool CanvasRaster::WriteString(const char *toWrite, size_t len, float x, float y, Color color)
{
//Establish and check for a string of a usable size.
data_.GoTo(static_cast<int>(x), static_cast<int>(y));
for (unsigned int i = 0; i < len; ++i)
{
data_.Set(RasterInfo(toWrite[i], color));
data_.IncrementX();
}
//Return success.
return true;
}
// Writes a mass of spaces to the screen.
inline void CanvasRaster::Fill(const RasterInfo &ri)
{
data_.Fill(ri);
}
// Clears out all of the data written to the raster. Does NOT move cursor to 0,0.
inline void CanvasRaster::Zero()
{
data_.Zero();
}
// Get a constant reference to the existing raster.
inline const Field2D<RasterInfo>& CanvasRaster::GetRasterData() const
{
return data_;
}
// Underlying raster exposing.
inline Field2D<RasterInfo>& CanvasRaster::GetRasterData()
{
return data_;
}
// Gets console width.
inline unsigned int CanvasRaster::GetRasterWidth() const
{
return width_;
}
// Get console height
inline unsigned int CanvasRaster::GetRasterHeight() const
{
return height_;
}
}
///////////////////////////////////////////////////////////////////////
//Canvas.cpp
///////////////////////////////////////////////////////////////////////
#include <cstdio> // PutC
#include <iostream> // ostream access
#include <csignal> // Signal termination.
#include <chrono> // Time related info for sleeping.
#include <thread> // Sleep on exit to allow for update to finish.
#include <string> // String for parsing.
namespace RConsole
{
#define DEFAULT_WIDTH_SIZE (rlutil::tcols() - 1)
#define DEFAULT_HEIGHT_SIZE rlutil::trows()
//// Static initialization in non-guaranteed order.
//CanvasRaster Canvas::r_ = CanvasRaster(DEFAULT_WIDTH_SIZE, DEFAULT_HEIGHT_SIZE);
//CanvasRaster Canvas::prev_ = CanvasRaster(DEFAULT_WIDTH_SIZE, DEFAULT_HEIGHT_SIZE);
//bool Canvas::hasLazyInit_ = false;
//bool Canvas::isDrawing_ = true;
//unsigned int Canvas::width_ = DEFAULT_WIDTH_SIZE;
//unsigned int Canvas::height_ = DEFAULT_HEIGHT_SIZE;
//Field2D<bool> Canvas::modified_ = Field2D<bool>(DEFAULT_WIDTH_SIZE, DEFAULT_HEIGHT_SIZE);
/////////////////////////////
// Public Member Functions //
/////////////////////////////
// Setup with width and height. Can be re-init
inline void Canvas::ReInit(unsigned int width, unsigned int height)
{
std::cout << std::flush;
if (width == 0)
width = 1;
if (height == 0)
height = 1;
width_ = width;
height_ = height;
r_ = CanvasRaster(width, height);
prev_ = CanvasRaster(width, height);
modified_ = Field2D<bool>(width, height);
}
// Clear out the screen that the user sees.
// Note: More expensive than clearing just the previous spaces
// but less expensive than clearing entire buffer with command.
inline void Canvas::FillCanvas(const RasterInfo &ri)
{
r_.Fill(ri);
}
// Write the specific character in a specific color to a specific location on the console.
inline void Canvas::Draw(char toWrite, float x, float y, Color color)
{
#ifdef RConsole_CLIP_CONSOLE
if (x >= width_) return;
if (y >= height_) return;
if (x <= 0) return;
if (y <= 0) return;
#endif // RConsole_CLIP_CONSOLE
modified_.GoTo(static_cast<int>(x), static_cast<int>(y));
modified_.Set(true);
r_.WriteChar(toWrite, x, y, color);
}
// Write the specific character in a specific color to a specific location on the console.
inline void Canvas::Draw(char toWrite, int x, int y, Color color)
{
Canvas::Draw(toWrite, static_cast<float>(x), static_cast<float>(y), color);
}
// Draw a string based on ints
inline void Canvas::DrawString(const char* toDraw, int xStart, int yStart, Color color)
{
Canvas::DrawString(toDraw, static_cast<float>(xStart), static_cast<float>(yStart), color);
}
// Draw a string
inline void Canvas::DrawString(const char* toDraw, float xStart, float yStart, Color color)
{
size_t len = strlen(toDraw);
if (len <= 0) return;
#ifdef RConsole_CLIP_CONSOLE
// Bounds check.
if (xStart > width_) return;
if (yStart > height_) return;
if (xStart < 0) return;
if (yStart < 0) return;
// Set the memory we are using to modified.
modified_.GoTo(static_cast<int>(xStart), static_cast<int>(yStart));
unsigned int index = modified_.GetIndex();
// Trim index if past the end
if (index + len + 1 > modified_.Length())
return;
// Checks the length and adjusts if it will be past.
int writeLen = static_cast<int>(len);
if (writeLen + index >= modified_.Length())
writeLen = static_cast<int>(modified_.Length()) - static_cast<int>(index);
// If our length plus the index we are at exceeds the end of the buffer,
if(writeLen > 0)
memset(modified_.GetHead() + index, true, static_cast<size_t>(writeLen));
#else
// Just blindly set modified for the length.
modified_.GoTo(static_cast<int>(xStart), static_cast<int>(yStart));
unsigned int index = modified_.GetIndex();
memset(modified_.GetHead() + index, true, len);
#endif
// Write string
r_.WriteString(toDraw, len, xStart, yStart, color);
}
// Updates the current raster by drawing it to the screen.
inline bool Canvas::Update()
{
if (!isDrawing_) return false;
if (!hasLazyInit_)
{
setCloseHandler();
hasLazyInit_ = true;
}
clearPrevious();
writeRaster(r_);
// Write and reset the raster.
memcpy(prev_.GetRasterData().GetHead(), r_.GetRasterData().GetHead(), width_ * height_ * sizeof(RasterInfo));
r_.Zero();
rlutil::setColor(WHITE);
return true;
}
// Draws a point with ASCII to attempt to represent alpha values in 4 steps.
inline void Canvas::DrawAlpha(float x, float y, Color color, float opacity)
{
// All characters use represent alt-codes.
if (opacity < .25)
Draw(static_cast<unsigned char>(176), x, y, color);
else if (opacity < .5)
Draw(static_cast<unsigned char>(177), x, y, color);
else if (opacity < .75)
Draw(static_cast<unsigned char>(178), x, y, color);
else
Draw(static_cast<unsigned char>(219), x, y, color);
}
// Stops the update loop.
inline void Canvas::Shutdown()
{
isDrawing_ = false;
}
// Draws a point with ASCII to attempt to represent location in a square.
inline void Canvas::DrawPartialPoint(float x, float y, Color color)
{
// Get first two decimal places from location.
int xDec = static_cast<int>(x * 100) % 100;
int yDec = static_cast<int>(x * 100) % 100;
UNUSED(xDec);
UNUSED(yDec);
//If Y is closer to a border, use it for placement.
if (RFuncs::Abs(50 - static_cast<int>(x)) < RFuncs::Abs(50 - static_cast<int>(y)))
{
if (x > 50)
return Draw(static_cast<unsigned char>(222), x, y, color);
return Draw(static_cast<unsigned char>(221), x, y, color);
}
//Otherwise, X is closer to a border.
else
{
if (y > 50)
return Draw(static_cast<unsigned char>(223), x, y, color);
return Draw(static_cast<unsigned char>(220), x, y, color);
}
}
// Drawing box
inline void Canvas::DrawBox(char toWrite, float x1, float y1, float x2, float y2, Color color)
{
if(x1 > x2)
{
float temp = x1;
x2 = x1;
temp = x2;
}
if(y1 > y2)
{
float temp = y1;
y2 = y1;
temp = y2;
}
// At this point it can be assumed that x1 and y1 and lower than x2 and y2 respectively.
for(unsigned int x = static_cast<unsigned int>(x1); x < x2; ++x)
{
for(unsigned int y = static_cast<unsigned int>(x1); y < y2; ++y)
{
Draw(toWrite, static_cast<float>(x), static_cast<float>(y), color);
}
}
}
//Set visibility of cursor to specified bool.
inline void Canvas::SetCursorVisible(bool isVisible)
{
if (!isVisible)
rlutil::hidecursor();
else
rlutil::showcursor();
}
// Gets the width of the console
inline unsigned int Canvas::GetConsoleWidth()
{
return width_;
}
// Gets the height of the console
inline unsigned int Canvas::GetConsoleHeight()
{
return height_;
}
//////////////////////////////
// Private Member Functions //
//////////////////////////////
// Clears out the screen based on the previous items written. Clear character is a space.
inline void Canvas::clearPrevious()
{
// Walk through, write over only what was modified.
modified_.SetIndex(0);
unsigned int maxIndex = width_ * height_;
unsigned int index = 0;
while (index < maxIndex)
{
index = modified_.GetIndex();
const RasterInfo &curr = r_.GetRasterData().Peek(index);
const RasterInfo &prev = prev_.GetRasterData().Peek(index);
// If we have not modified the space,
// and we don't have the same character as last time,
// and we don't have the same color.
if (!modified_.Get() && curr != prev)
{
// Compute X and Y location
unsigned int xLoc = (index % width_) + 1;
unsigned int yLoc = (index / width_) + 1;
// locate on screen and set color
rlutil::locate(xLoc, yLoc);
putC(' ', stdout);
}
modified_.IncrementX();
}
// Set things back to zero.
modified_.Zero();
}
// Explicitly clears every possible index. This is expensive!
inline void Canvas::fullClear()
{
rlutil::cls();
}
// Set the color in the console using utility, if applicable.
inline void Canvas::setColor(const Color &color)
{
if (color != PREVIOUS_COLOR)
rlutil::setColor(color);
}
// Write the raster we were attempting to write.
inline bool Canvas::writeRaster(CanvasRaster &r)
{
// Set initial position.
unsigned int maxIndex = width_ * height_;
r.GetRasterData().SetIndex(0);
unsigned int index = 0;
while(index < maxIndex)
{
index = r.GetRasterData().GetIndex();
const RasterInfo& ri = r.GetRasterData().Get();
if (ri.Value != 0 && prev_.GetRasterData().Peek(index) != ri)
{
unsigned int xLoc = (index % width_) + 1;
unsigned int yLoc = (index / width_) + 1;
// Handle clipping the console if we define that tag.
#ifdef RConsole_CLIP_CONSOLE
// Handle X
if (xLoc > width_)
return false;
// Handle Y
if (yLoc > height_)
return false;
#endif
// locate on screen and set color
rlutil::locate(xLoc, yLoc);
// Set color of cursor
setColor(ri.C);
// Print out to the console in the preferred fashion
int retVal = 0;
retVal = putC(ri.Value, stdout);
if (!retVal)
return false;
}
// Increment X location
r.GetRasterData().IncrementX();
}
// Return we successfully printed the raster!
return true;
}
// Cross-platform putc
inline int Canvas::putC(int character, FILE * stream )
{
#if defined(RConsole_NO_THREADING) && defined(OS_WINDOWS)
return _putc_nolock(character, stream);
#else
return putc(character, stream);
#endif
}
// print out the formatted raster.
// Note that because of console color formatting, we use the RLUTIL coloring option when
// we are printing to the console, or have no file output specified.
inline void Canvas::DumpRaster(FILE * fp)
{
// Dump only relevant part of stream.
for (unsigned int i = 0; i < height_; ++i)
{
for (unsigned int j = 0; j < width_; ++j)
{
const RasterInfo &ri = r_.GetRasterData().Peek(j, i);
if (fp == stdout)
{
rlutil::setColor(ri.C);
std::cout << ri.Value;//fprintf(fp, "%c", ri.Value);
}
else
{
std::string line = rlutil::getANSIColor(ri.C) + ri.Value;
fprintf(fp, "%s", line.c_str());
}
}
std::cout << std::endl;
//fprintf(fp, "\n");
}
// Set end color to white when we're done.
if (fp == stdout)
rlutil::setColor(WHITE);
}
// Crops all of the raster
inline void Canvas::CropRaster(FILE *fp, char toTrim)
{
// Establish borders.
unsigned int Xmin = width_;
unsigned int Xmax = 0;
unsigned int Ymin = height_;
unsigned int Ymax = 0;
for (unsigned int i = 0; i < width_; ++i)
{
for (unsigned int j = 0; j < height_; ++j)
{
if (r_.GetRasterData().Peek(i, j).Value != toTrim)
{
if (i < Xmin) Xmin = i;
if (j < Ymin) Ymin = j;
if (i > Xmax) Xmax = i;
if (j > Ymax) Ymax = j;
}
}
}
// If we're trimming everything, don't even bother.
if (Xmin > Xmax) return;
if (Ymin > Ymax) return;
// Dump only relevant part of stream.
for (unsigned int j = Ymin; j <= Ymax; ++j)
{
for (unsigned int i = Xmin; i <= Xmax; ++i)
{
const RasterInfo &ri = r_.GetRasterData().Peek(i, j);
if (fp == stdout)
{
rlutil::setColor(ri.C);
fprintf(fp, "%c", ri.Value);
}
else
{
std::string line = rlutil::getANSIColor(ri.C) + ri.Value;
fprintf(fp, "%s", line.c_str());
}
}
fprintf(fp, "\n");
}
// Set end color to white when we're done.
if (fp == stdout)
rlutil::setColor(WHITE);
}
// Handle closing the window
static void signalHandler(int signalNum)
{
Canvas::Shutdown();
std::this_thread::sleep_for(std::chrono::milliseconds(500));
int height = rlutil::trows();
rlutil::locate(0, height);
rlutil::setColor(WHITE);
std::cout << std::endl;
exit(signalNum);
}
inline void Canvas::setCloseHandler()
{
signal(SIGTERM, signalHandler);
signal(SIGINT, signalHandler);
}
}
#define CONSOLE_WIDTH_FUNC (rlutil::tcols() - 1)
#define CONSOLE_HEIGHT_FUNC (rlutil::trows())
| 25.486763
| 113
| 0.631578
|
ReverieWisp
|
653614359c1ceabfbcfec1b202ec1f7845cfc577
| 589
|
hpp
|
C++
|
test/__mocks__/game/skirmish/gui/skirmishguifactorymock.hpp
|
namelessvoid/qrwar
|
bbc4036cd3bab6b0edcaccbc95286379ef51f12b
|
[
"MIT"
] | 3
|
2015-03-28T02:51:58.000Z
|
2018-11-08T16:49:53.000Z
|
test/__mocks__/game/skirmish/gui/skirmishguifactorymock.hpp
|
namelessvoid/qrwar
|
bbc4036cd3bab6b0edcaccbc95286379ef51f12b
|
[
"MIT"
] | 39
|
2015-05-18T08:29:16.000Z
|
2020-07-18T21:17:44.000Z
|
test/__mocks__/game/skirmish/gui/skirmishguifactorymock.hpp
|
namelessvoid/qrwar
|
bbc4036cd3bab6b0edcaccbc95286379ef51f12b
|
[
"MIT"
] | null | null | null |
#ifndef QRWTEST_SKIRMISHGUIFACTORYMOCK_HPP
#define QRWTEST_SKIRMISHGUIFACTORYMOCK_HPP
#include <gmock/gmock.h>
#include "game/skirmish/gui/skirmishguifactory.hpp"
#include "__mocks__/game/skirmish/mapmanagermock.hpp"
class SkirmishGuiFactoryMock : public qrw::SkirmishGuiFactory
{
public:
SkirmishGuiFactoryMock() : qrw::SkirmishGuiFactory(mapManagerMock) {}
MOCK_CONST_METHOD2(createMapEditorToolBar, qrw::MapEditorToolBar*(unsigned int initialBoardWidth, unsigned int initialBoardHeight));
private:
MapManagerMock mapManagerMock;
};
#endif //QRWTEST_SKIRMISHGUIFACTORYMOCK_HPP
| 26.772727
| 133
| 0.837012
|
namelessvoid
|
65481e4b4c0f2b7cec93502f2f36162690a5552e
| 1,224
|
hpp
|
C++
|
graph/mst/Prim.hpp
|
shiomusubi496/library
|
907f72eb6ee4ac6ef617bb359693588167f779e7
|
[
"MIT"
] | 3
|
2021-11-04T08:45:12.000Z
|
2021-11-29T08:44:26.000Z
|
graph/mst/Prim.hpp
|
shiomusubi496/library
|
907f72eb6ee4ac6ef617bb359693588167f779e7
|
[
"MIT"
] | null | null | null |
graph/mst/Prim.hpp
|
shiomusubi496/library
|
907f72eb6ee4ac6ef617bb359693588167f779e7
|
[
"MIT"
] | null | null | null |
#pragma once
#include "../../other/template.hpp"
#include "../Graph.hpp"
#include "../../data-struct/unionfind/UnionFind.hpp"
template<class T> T Prim(const Graph<T>& G) {
const int N = G.size();
std::vector<bool> seen(N, false); seen[0] = true;
prique<edge<T>> que;
each_const (e : G[0]) que.emplace(e);
T res = 0;
while (!que.empty()) {
const edge<T> cre = que.top(); que.pop();
if (seen[cre.to]) continue;
res += cre.cost;
seen[cre.to] = true;
each_const (e : G[cre.to]) {
if (seen[e.to]) continue;
que.emplace(e);
}
}
return res;
}
template<class T> Edges<T> Prim_vec(const Graph<T>& G) {
const int N = G.size();
std::vector<bool> seen(N, false); seen[0] = true;
prique<edge<T>> que;
each_const (e : G[0]) que.emplace(e);
Edges<T> res;
while (!que.empty()) {
const edge<T> cre = que.top(); que.pop();
if (seen[cre.to]) continue;
res.emplace(cre);
seen[cre.to] = true;
each_const (e : G[cre.to]) {
if (seen[e.to]) continue;
que.emplace(e);
}
}
return res;
}
/**
* @brief Prim(プリム法)
* @docs docs/Prim.md
*/
| 24.979592
| 56
| 0.520425
|
shiomusubi496
|
654c7990e3e5e729a8f80bfcf9d1587a523665c5
| 506
|
cpp
|
C++
|
chapter1/11.cpp
|
anatolykabakov/cpp-tasks
|
82927d4334e8a0709424b61fe25b9be326244d78
|
[
"MIT"
] | null | null | null |
chapter1/11.cpp
|
anatolykabakov/cpp-tasks
|
82927d4334e8a0709424b61fe25b9be326244d78
|
[
"MIT"
] | null | null | null |
chapter1/11.cpp
|
anatolykabakov/cpp-tasks
|
82927d4334e8a0709424b61fe25b9be326244d78
|
[
"MIT"
] | null | null | null |
/*
Task 11: Write the program to convert m/sec to km/h.
*/
#include <iostream>
constexpr double KMH_TO_METERS_PER_SECONDS = 0.277778;
double convert_velocity_ms_to_kmh(const double velocity_ms) {
return velocity_ms / KMH_TO_METERS_PER_SECONDS;
}
int main() {
double velocity = 0;
std::cout << "Enter the velocity in m/sec" << std::endl;
std::cin>>velocity;
std::cout << "Entered velocity is " << convert_velocity_ms_to_kmh(velocity) << " km/h" << std::endl;
return EXIT_SUCCESS;
}
| 29.764706
| 104
| 0.701581
|
anatolykabakov
|
65511d11524aa0823262709bd7d8276cca1031fb
| 10,476
|
hpp
|
C++
|
include/fc/io/raw.hpp
|
SatoshiFantasy/fantasybit
|
5fc51cd3c056ce01b661ef5e3fb7dcad130fc9a1
|
[
"BSD-3-Clause"
] | 77
|
2015-06-09T14:39:00.000Z
|
2022-02-04T07:21:48.000Z
|
include/fc/io/raw.hpp
|
SatoshiFantasy/fantasybit
|
5fc51cd3c056ce01b661ef5e3fb7dcad130fc9a1
|
[
"BSD-3-Clause"
] | 2
|
2018-05-24T11:12:59.000Z
|
2018-07-16T05:44:11.000Z
|
include/fc/io/raw.hpp
|
SatoshiFantasy/fantasybit
|
5fc51cd3c056ce01b661ef5e3fb7dcad130fc9a1
|
[
"BSD-3-Clause"
] | 25
|
2016-03-18T17:36:53.000Z
|
2021-12-09T15:09:05.000Z
|
#pragma once
#include <fc/reflect/reflect.hpp>
#include <fc/io/datastream.hpp>
#include <fc/io/varint.hpp>
#include <fc/optional.hpp>
#include <fc/fwd.hpp>
#include <fc/array.hpp>
#include <fc/time.hpp>
#include <fc/io/raw_fwd.hpp>
#include <fc/exception/exception.hpp>
#define MAX_ARRAY_ALLOC_SIZE (1024*1024*10)
namespace fc {
namespace raw {
template<typename Stream>
inline void pack( Stream& s, const fc::time_point_sec& tp )
{
uint32_t usec = tp.sec_since_epoch();
s.write( (const char*)&usec, sizeof(usec) );
}
template<typename Stream>
inline void unpack( Stream& s, fc::time_point_sec& tp )
{
uint32_t sec;
s.read( (char*)&sec, sizeof(sec) );
tp = fc::time_point() + fc::seconds(sec);
}
template<typename Stream>
inline void pack( Stream& s, const fc::time_point& tp )
{
uint64_t usec = tp.time_since_epoch().count();
s.write( (const char*)&usec, sizeof(usec) );
}
template<typename Stream>
inline void unpack( Stream& s, fc::time_point& tp )
{
uint64_t usec;
s.read( (char*)&usec, sizeof(usec) );
tp = fc::time_point() + fc::microseconds(usec);
}
template<typename Stream, typename T, size_t N>
inline void pack( Stream& s, const fc::array<T,N>& v) {
s.write((const char*)&v.data[0],N*sizeof(T));
}
template<typename Stream, typename T, size_t N>
inline void unpack( Stream& s, fc::array<T,N>& v) {
s.read((char*)&v.data[0],N*sizeof(T));
}
template<typename Stream> inline void pack( Stream& s, const signed_int& v ) {
uint32_t val = (v.value<<1) ^ (v.value>>31);
do {
uint8_t b = uint8_t(val) & 0x7f;
val >>= 7;
b |= ((val > 0) << 7);
s.write((char*)&b,1);//.put(b);
} while( val );
}
template<typename Stream> inline void pack( Stream& s, const unsigned_int& v ) {
uint64_t val = v.value;
do {
uint8_t b = uint8_t(val) & 0x7f;
val >>= 7;
b |= ((val > 0) << 7);
s.write((char*)&b,1);//.put(b);
}while( val );
}
template<typename Stream> inline void unpack( Stream& s, signed_int& vi ) {
uint32_t v = 0; char b = 0; int by = 0;
do {
s.get(b);
v |= uint32_t(uint8_t(b) & 0x7f) << by;
by += 7;
} while( uint8_t(b) & 0x80 );
vi.value = ((v>>1) ^ (v>>31)) + (v&0x01);
vi.value = v&0x01 ? vi.value : -vi.value;
vi.value = -vi.value;
}
template<typename Stream> inline void unpack( Stream& s, unsigned_int& vi ) {
uint64_t v = 0; char b = 0; uint8_t by = 0;
do {
s.get(b);
v |= uint32_t(uint8_t(b) & 0x7f) << by;
by += 7;
} while( uint8_t(b) & 0x80 );
vi.value = v;
}
template<typename Stream> inline void pack( Stream& s, const char* v ) { pack( s, fc::string(v) ); }
// optional
template<typename Stream, typename T>
inline void pack( Stream& s, const fc::optional<T>& v ) {
pack( s, bool(!!v) );
if( !!v ) pack( s, *v );
}
template<typename Stream, typename T>
void unpack( Stream& s, fc::optional<T>& v ) {
bool b; unpack( s, b );
if( b ) { v = T(); unpack( s, *v ); }
}
// std::vector<char>
template<typename Stream> inline void pack( Stream& s, const std::vector<char>& value ) {
pack( s, unsigned_int(value.size()) );
if( value.size() )
s.write( &value.front(), value.size() );
}
template<typename Stream> inline void unpack( Stream& s, std::vector<char>& value ) {
unsigned_int size; unpack( s, size );
FC_ASSERT( size.value < MAX_ARRAY_ALLOC_SIZE );
value.resize(size.value);
if( value.size() )
s.read( value.data(), value.size() );
}
// fc::string
template<typename Stream> inline void pack( Stream& s, const fc::string& v ) {
pack( s, unsigned_int(v.size()) );
if( v.size() ) s.write( v.c_str(), v.size() );
}
template<typename Stream> inline void unpack( Stream& s, fc::string& v ) {
std::vector<char> tmp; unpack(s,tmp);
if( tmp.size() )
v = fc::string(tmp.data(),tmp.data()+tmp.size());
else v = fc::string();
}
// bool
template<typename Stream> inline void pack( Stream& s, const bool& v ) { pack( s, uint8_t(v) ); }
template<typename Stream> inline void unpack( Stream& s, bool& v ) { uint8_t b; unpack( s, b ); v=b; }
namespace detail {
template<typename Stream, typename Class>
struct pack_object_visitor {
pack_object_visitor(const Class& _c, Stream& _s)
:c(_c),s(_s){}
template<typename T, typename C, T(C::*p)>
void operator()( const char* name )const {
raw::pack( s, c.*p );
}
private:
const Class& c;
Stream& s;
};
template<typename Stream, typename Class>
struct unpack_object_visitor {
unpack_object_visitor(Class& _c, Stream& _s)
:c(_c),s(_s){}
template<typename T, typename C, T(C::*p)>
inline void operator()( const char* name )const {
raw::unpack( s, c.*p );
}
private:
Class& c;
Stream& s;
};
template<typename IsClass=fc::true_type>
struct if_class{
template<typename Stream, typename T>
static inline void pack( Stream& s, const T& v ) { s << v; }
template<typename Stream, typename T>
static inline void unpack( Stream& s, T& v ) { s >> v; }
};
template<>
struct if_class<fc::false_type> {
template<typename Stream, typename T>
static inline void pack( Stream& s, const T& v ) {
s.write( (char*)&v, sizeof(v) );
}
template<typename Stream, typename T>
static inline void unpack( Stream& s, T& v ) {
s.read( (char*)&v, sizeof(v) );
}
};
template<typename IsReflected=fc::false_type>
struct if_reflected {
template<typename Stream, typename T>
static inline void pack( Stream& s, const T& v ) {
if_class<typename fc::is_class<T>::type>::pack(s,v);
}
template<typename Stream, typename T>
static inline void unpack( Stream& s, T& v ) {
if_class<typename fc::is_class<T>::type>::unpack(s,v);
}
};
template<>
struct if_reflected<fc::true_type> {
template<typename Stream, typename T>
static inline void pack( Stream& s, const T& v ) {
fc::reflector<T>::visit( pack_object_visitor<Stream,T>( v, s ) );
}
template<typename Stream, typename T>
static inline void unpack( Stream& s, T& v ) {
fc::reflector<T>::visit( unpack_object_visitor<Stream,T>( v, s ) );
}
};
} // namesapce detail
template<typename Stream, typename T>
inline void pack( Stream& s, const std::unordered_set<T>& value ) {
pack( s, unsigned_int(value.size()) );
auto itr = value.begin();
auto end = value.end();
while( itr != end ) {
fc::raw::pack( s, *itr );
++itr;
}
}
template<typename Stream, typename T>
inline void unpack( Stream& s, std::unordered_set<T>& value ) {
unsigned_int size; unpack( s, size );
value.clear();
FC_ASSERT( size.value*sizeof(T) < MAX_ARRAY_ALLOC_SIZE );
value.reserve(size.value);
for( uint32_t i = 0; i < size.value; ++i )
{
T tmp;
fc::raw::unpack( s, tmp );
value.insert( std::move(tmp) );
}
}
template<typename Stream, typename T>
inline void pack( Stream& s, const std::vector<T>& value ) {
pack( s, unsigned_int(value.size()) );
auto itr = value.begin();
auto end = value.end();
while( itr != end ) {
fc::raw::pack( s, *itr );
++itr;
}
}
template<typename Stream, typename T>
inline void unpack( Stream& s, std::vector<T>& value ) {
unsigned_int size; unpack( s, size );
FC_ASSERT( size.value*sizeof(T) < MAX_ARRAY_ALLOC_SIZE );
value.resize(size.value);
auto itr = value.begin();
auto end = value.end();
while( itr != end ) {
fc::raw::unpack( s, *itr );
++itr;
}
}
template<typename Stream, typename T>
inline void pack( Stream& s, const std::set<T>& value ) {
pack( s, unsigned_int(value.size()) );
auto itr = value.begin();
auto end = value.end();
while( itr != end ) {
fc::raw::pack( s, *itr );
++itr;
}
}
template<typename Stream, typename T>
inline void unpack( Stream& s, std::set<T>& value ) {
unsigned_int size; unpack( s, size );
for( uint64_t i = 0; i < size.value; ++i )
{
T tmp;
unpack( s, tmp );
value.insert( std::move(tmp) );
}
}
template<typename Stream, typename T>
inline void pack( Stream& s, const T& v ) {
fc::raw::detail::if_reflected< typename fc::reflector<T>::is_defined >::pack(s,v);
}
template<typename Stream, typename T>
inline void unpack( Stream& s, T& v ) {
fc::raw::detail::if_reflected< typename fc::reflector<T>::is_defined >::unpack(s,v);
}
template<typename T>
inline std::vector<char> pack( const T& v ) {
datastream<size_t> ps;
raw::pack(ps,v );
std::vector<char> vec(ps.tellp());
if( vec.size() ) {
datastream<char*> ds( vec.data(), size_t(vec.size()) );
raw::pack(ds,v);
}
return vec;
}
template<typename T>
inline T unpack( const std::vector<char>& s ) {
T tmp;
if( s.size() ) {
datastream<const char*> ds( s.data(), size_t(s.size()) );
raw::unpack(ds,tmp);
}
return tmp;
}
template<typename T>
inline void pack( char* d, uint32_t s, const T& v ) {
datastream<char*> ds(d,s);
raw::pack(ds,v );
}
template<typename T>
inline T unpack( const char* d, uint32_t s ) {
T v;
datastream<const char*> ds( d, s );
raw::unpack(ds,v);
return v;
}
template<typename T>
inline void unpack( const char* d, uint32_t s, T& v ) {
datastream<const char*> ds( d, s );
raw::unpack(ds,v);
return v;
}
} } // namespace fc::raw
| 30.277457
| 113
| 0.546583
|
SatoshiFantasy
|
65522603ed822726602b0d3b47bbfb4a5dfe99ae
| 258
|
cpp
|
C++
|
lights/sink.cpp
|
wherewindblow/lights
|
0cc01b34de1cc6e440be4e065048277822c040db
|
[
"Apache-2.0"
] | 1
|
2020-12-10T12:08:41.000Z
|
2020-12-10T12:08:41.000Z
|
lights/sink.cpp
|
wherewindblow/spaceless
|
891ef66cf22d268dd742ea15b15f944a9ba8185f
|
[
"Apache-2.0"
] | null | null | null |
lights/sink.cpp
|
wherewindblow/spaceless
|
891ef66cf22d268dd742ea15b15f944a9ba8185f
|
[
"Apache-2.0"
] | null | null | null |
/**
* sink.cpp
* @author wherewindblow
* @date Feb 16, 2019
*/
#include "sink.h"
namespace lights {
void FormatSink<Sink>::append(std::size_t num, char ch)
{
for (std::size_t i = 0; i < num; ++i)
{
this->append(ch);
}
}
} // namespace lights
| 12.285714
| 55
| 0.596899
|
wherewindblow
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.