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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
215e2ba19080e1f82bcc2a2e33d9b5e21c576525
| 1,538
|
cc
|
C++
|
fhiclcpp/test/types/searchAllowedConfiguration_t.cc
|
art-framework-suite/fhicl-cpp
|
302a8ca52dba4b922812ead406599cd535676252
|
[
"BSD-3-Clause"
] | null | null | null |
fhiclcpp/test/types/searchAllowedConfiguration_t.cc
|
art-framework-suite/fhicl-cpp
|
302a8ca52dba4b922812ead406599cd535676252
|
[
"BSD-3-Clause"
] | 2
|
2021-12-10T14:54:24.000Z
|
2022-03-25T16:33:23.000Z
|
fhiclcpp/test/types/searchAllowedConfiguration_t.cc
|
art-framework-suite/fhicl-cpp
|
302a8ca52dba4b922812ead406599cd535676252
|
[
"BSD-3-Clause"
] | null | null | null |
#define BOOST_TEST_MODULE (search allowed configuration test)
#include "boost/test/unit_test.hpp"
#include "fhiclcpp/types/Atom.h"
#include "fhiclcpp/types/Sequence.h"
#include "fhiclcpp/types/Table.h"
#include "fhiclcpp/types/Tuple.h"
#include "fhiclcpp/types/detail/SearchAllowedConfiguration.h"
#include <string>
using namespace fhicl;
using namespace fhicl::detail;
using namespace std;
auto supports_key = SearchAllowedConfiguration::supports_key;
namespace {
struct S {
Atom<int> test{Name{"atom"}};
Sequence<int, 2> seq{Name{"sequence"}};
Tuple<int, double, bool> tuple{Name{"tuple"}};
struct U {
Atom<int> test{Name{"nested_atom"}};
};
Tuple<Sequence<int, 2>, bool> tuple2{Name{"tuple2"}};
Table<U> table2{Name{"table2"}};
};
}
BOOST_AUTO_TEST_SUITE(searchAllowedConfiguration_test)
BOOST_AUTO_TEST_CASE(table_t)
{
Table<S> t{Name{"table"}};
BOOST_TEST(supports_key(t, "atom"));
BOOST_TEST(!supports_key(t, "table.atom"));
BOOST_TEST(!supports_key(t, "table.sequence"));
BOOST_TEST(supports_key(t, "sequence"));
BOOST_TEST(supports_key(t, "sequence[0]"));
BOOST_TEST(!supports_key(t, "[0]"));
BOOST_TEST(supports_key(t, "table2"));
BOOST_TEST(supports_key(t, "tuple2[0][1]"));
BOOST_TEST(supports_key(t, "tuple2[1]"));
}
BOOST_AUTO_TEST_CASE(seqInSeq_t)
{
Sequence<Sequence<int, 2>> s{Name{"nestedSequence"}};
BOOST_TEST(supports_key(s, "[0]"));
BOOST_TEST(supports_key(s, "[0][0]"));
BOOST_TEST(supports_key(s, "[0][1]"));
}
BOOST_AUTO_TEST_SUITE_END()
| 26.982456
| 61
| 0.708062
|
art-framework-suite
|
216191eae850363824975047adbcbd028eb99cc8
| 13,627
|
hpp
|
C++
|
engine/common/ShadersGL.hpp
|
ColinGilbert/noobwerkz-engine
|
f5670e98ca0dada8865be9ab82d25d3acf549ebe
|
[
"Apache-2.0"
] | 23
|
2015-03-02T10:56:40.000Z
|
2021-01-27T03:32:49.000Z
|
engine/common/ShadersGL.hpp
|
ColinGilbert/noobwerkz-engine-borked
|
f5670e98ca0dada8865be9ab82d25d3acf549ebe
|
[
"Apache-2.0"
] | 73
|
2015-04-14T09:39:05.000Z
|
2020-11-11T21:49:10.000Z
|
engine/common/ShadersGL.hpp
|
ColinGilbert/noobwerkz-engine-borked
|
f5670e98ca0dada8865be9ab82d25d3acf549ebe
|
[
"Apache-2.0"
] | 3
|
2016-02-22T01:29:32.000Z
|
2018-01-02T06:07:12.000Z
|
#pragma once
namespace noob
{
namespace glsl
{
////////////////////////////////////////////////////////////
// Extremely useful for getting rid of shader conditionals
////////////////////////////////////////////////////////////
// http://theorangeduck.com/page/avoiding-shader-conditionals
static const std::string shader_conditionals(
"vec4 noob_when_eq(vec4 x, vec4 y) \n"
"{ \n"
" return 1.0 - abs(sign(x - y)); \n"
"} \n"
"vec4 noob_when_neq(vec4 x, vec4 y) \n"
"{ \n"
" return abs(sign(x - y)); \n"
"} \n"
"vec4 noob_when_gt(vec4 x, vec4 y) \n"
"{ \n"
" return max(sign(x - y), 0.0); \n"
"} \n"
"vec4 noob_when_lt(vec4 x, vec4 y) \n"
"{ \n"
" return min(1.0 - sign(x - y), 1.0); \n"
"} \n"
"vec4 noob_when_ge(vec4 x, vec4 y) \n"
"{ \n"
" return 1.0 - noob_when_lt(x, y); \n"
"} \n"
"vec4 noob_when_le(vec4 x, vec4 y) \n"
"{ \n"
" return 1.0 - noob_when_gt(x, y); \n"
"} \n"
"vec4 noob_and(vec4 a, vec4 b) \n"
"{ \n"
" return a * b; \n"
"} \n"
"vec4 noob_or(vec4 a, vec4 b) \n"
"{ \n"
" return min(a + b, 1.0); \n"
"} \n"
//"vec4 xor(vec4 a, vec4 b) \n"
//"{ \n"
//" return (a + b) % 2.0; \n"
//"} \n"
"vec4 noob_not(vec4 a) \n"
"{ \n"
" return 1.0 - a; \n"
"} \n"
"float noob_when_eq(float x, float y) \n"
"{ \n"
" return 1.0 - abs(sign(x - y)); \n"
"} \n"
"float noob_when_neq(float x, float y) \n"
"{ \n"
" return abs(sign(x - y)); \n"
"} \n"
"float noob_when_gt(float x, float y) \n"
"{ \n"
" return max(sign(x - y), 0.0); \n"
"} \n"
"float noob_when_lt(float x, float y) \n"
"{ \n"
" return min(1.0 - sign(x - y), 1.0); \n"
"} \n"
"float noob_when_ge(float x, float y) \n"
"{ \n"
" return 1.0 - noob_when_lt(x, y); \n"
"} \n"
"float noob_when_le(float x, float y) \n"
"{ \n"
" return 1.0 - noob_when_gt(x, y); \n"
"} \n");
//////////////////////////////////
// Goes before every shader
//////////////////////////////////
static const std::string shader_prefix(
"#version 300 es \n"
"precision mediump float; \n");
//////////////////////////
// Vertex shaders
//////////////////////////
static const std::string vs_instancing_src = noob::concat(shader_prefix, std::string(
"layout(location = 0) in vec4 a_pos; \n"
"layout(location = 1) in vec4 a_normal; \n"
"layout(location = 2) in vec4 a_vert_colour; \n"
"layout(location = 3) in vec4 a_instance_colour; \n"
"layout(location = 4) in mat4 a_model_mat; \n"
"uniform mat4 view_matrix; \n"
"uniform mat4 projection_matrix; \n"
"out vec4 v_world_pos; \n"
"out vec4 v_world_normal; \n"
"out vec4 v_vert_colour; \n"
"void main() \n"
"{ \n"
" v_world_pos = a_model_mat * a_pos; \n"
" mat4 modelview_mat = view_matrix * a_model_mat; \n"
" v_world_normal = a_model_mat * vec4(a_normal.xyz, 0); \n"
" v_vert_colour = a_vert_colour * a_instance_colour; \n"
" mat4 mvp_mat = projection_matrix * modelview_mat; \n"
" gl_Position = mvp_mat * a_pos; \n"
"} \n"));
static const std::string vs_terrain_src = noob::concat(shader_prefix, std::string(
"layout(location = 0) in vec4 a_pos; \n"
"layout(location = 1) in vec4 a_normal; \n"
"layout(location = 2) in vec4 a_vert_colour; \n"
"out vec4 v_world_pos; \n"
"out vec4 v_world_normal; \n"
"out vec4 v_vert_colour; \n"
"uniform mat4 mvp; \n" "uniform mat4 view_matrix; \n"
"void main() \n"
"{ \n"
" v_world_pos = a_pos; \n"
" v_world_normal = vec4(a_normal.xyz, 0); \n"
" v_vert_colour = a_vert_colour; \n"
" gl_Position = mvp * a_pos; \n"
"} \n"));
static const std::string vs_billboard_src = noob::concat(shader_prefix, std::string(
"layout(location = 0) in vec4 a_pos_uv; \n"
"layout(location = 1) in vec4 a_colour; \n"
"out vec2 v_uv; \n"
"out vec4 v_colour; \n"
"void main() \n"
"{ \n"
" v_uv = vec2(a_pos_uv[2], a_pos_uv[3]); \n"
" v_colour = a_colour; \n"
" gl_Position = vec4(a_pos_uv[0], a_pos_uv[1], 0.0, 1.0); \n"
"} \n"));
//////////////////////////
// Fragment shaders
//////////////////////////
static const std::string lambert_diffuse(
"float lambert_diffuse(vec3 light_direction, vec3 surface_normal) \n"
"{ \n"
" return max(0.0, dot(light_direction, surface_normal)); \n"
"} \n");
static const std::string blinn_phong_specular(
"float blinn_phong_specular(vec3 light_direction, vec3 view_direction, vec3 surface_normal, float shininess) \n"
"{ \n"
" vec3 H = normalize(view_direction + light_direction); \n"
" return pow(max(0.0, dot(surface_normal, H)), shininess); \n"
"} \n");
static const std::string fs_instancing_src = noob::concat(shader_prefix, lambert_diffuse, blinn_phong_specular, std::string(
"in vec4 v_world_pos; \n" "in vec4 v_world_normal; \n"
"in vec4 v_vert_colour; \n"
"layout (location = 0) out vec4 out_colour; \n"
"uniform vec3 eye_pos; \n"
"uniform vec3 directional_light; \n"
"void main() \n"
"{ \n"
" vec3 view_direction = normalize(eye_pos - v_world_pos.xyz); \n"
" float diffuse = lambert_diffuse(-directional_light, v_world_normal.xyz); \n"
" float specular = blinn_phong_specular(-directional_light, -view_direction, v_world_normal.xyz, 10.0); \n"
" float light = 0.1 + diffuse + specular; \n"
" out_colour = vec4(clamp(v_vert_colour.xyz * light, 0.0, 1.0), 1.0); \n"
"} \n"));
static const std::string fs_terrain_src = noob::concat(shader_prefix, lambert_diffuse, blinn_phong_specular, shader_conditionals, std::string(
"in vec4 v_world_pos; \n"
"in vec4 v_world_normal; \n"
"in vec4 v_vert_colour; \n"
"layout(location = 0) out vec4 out_colour; \n"
"uniform sampler2D texture_0; \n"
"uniform vec4 colour_0; \n"
"uniform vec4 colour_1; \n"
"uniform vec4 colour_2; \n"
"uniform vec4 colour_3; \n"
"uniform vec3 blend_0; \n"
"uniform vec2 blend_1; \n"
"uniform vec3 tex_scales; \n"
"uniform vec3 eye_pos; \n"
"uniform vec3 directional_light; \n"
"void main() \n"
"{ \n"
" vec3 normal_blend = normalize(max(abs(v_world_normal.xyz), 0.0001)); \n"
" float b = normal_blend.x + normal_blend.y + normal_blend.z; \n"
" normal_blend /= b; \n"
// "RGB-only. Try it out for great wisdom!
// "vec4 xaxis = vec4(1.0, 0.0, 0.0, 1.0); \n"
// "vec4 yaxis = vec4(0.0, 1.0, 0.0, 1.0); \n"
// "vec4 zaxis = vec4(0.0, 0.0, 1.0, 1.0); \n"
" vec4 xaxis = vec4(texture(texture_0, v_world_pos.yz * tex_scales.x).rgb, 1.0); \n"
" vec4 yaxis = vec4(texture(texture_0, v_world_pos.xz * tex_scales.y).rgb, 1.0); \n"
" vec4 zaxis = vec4(texture(texture_0, v_world_pos.xy * tex_scales.z).rgb, 1.0); \n"
" vec4 tex = xaxis * normal_blend.x + yaxis * normal_blend.y + zaxis * normal_blend.z; \n"
" float tex_r = blend_0.x * tex.r; \n"
" float tex_g = blend_0.y * tex.g; \n"
" float tex_b = blend_0.z * tex.b; \n"
" vec4 tex_weighted = vec4(tex_r, tex_g, tex_b, 1.0); \n"
" float tex_falloff = (tex_r + tex_g + tex_b) * 0.3333; \n"
" float ratio_0_to_1 = noob_when_le(tex_falloff, blend_1.x) * ((tex_falloff + blend_1.x) * 0.5); \n"
" float ratio_1_to_2 = noob_when_le(tex_falloff, blend_1.y) * noob_when_gt(tex_falloff, blend_1.x) * ((tex_falloff + blend_1.y) * 0.5); \n"
" float ratio_2_to_3 = noob_when_ge(tex_falloff, blend_1.y) * ((tex_falloff + 1.0) * 0.5); \n"
" vec4 tex_final = ((colour_0 + colour_1) * ratio_0_to_1) + ((colour_1 + colour_2) * ratio_1_to_2) + ((colour_2 + colour_3) * ratio_2_to_3); \n"
" vec3 view_direction = normalize(eye_pos - v_world_pos.xyz); \n"
" float diffuse = lambert_diffuse(-directional_light, v_world_normal.xyz); \n"
" float specular = blinn_phong_specular(-directional_light, -view_direction, v_world_normal.xyz, 10.0); \n"
" float light = 0.1 + diffuse + specular; \n"
" out_colour = vec4(clamp(tex_final.xyz * light, 0.0, 1.0), 1.0); \n"
"} \n"));
static const std::string fs_text_src = noob::concat(shader_prefix, std::string(
"in vec2 v_uv; \n"
"in vec4 v_colour; \n"
"layout(location = 0) out vec4 out_colour; \n"
"uniform sampler2D texture_0; \n"
"void main() \n"
"{ \n"
" float f = texture(texture_0, v_uv).x; \n"
" out_colour = vec4(v_colour.rgb, v_colour.a * f); \n"
"} \n"));
/*
static std::string get_light(
"vec3 get_light(vec3 world_pos, vec3 world_normal, vec3 eye_pos, vec3 light_pos, vec3 light_rgb) \n"
"{ \n"
" // vec3 normal = normalize(world_normal); \n"
" vec3 view_direction = normalize(eye_pos - world_pos); \n"
" vec3 light_direction = normalize(light_pos - world_pos); \n"
" float light_distance = length(light_pos - world_pos); \n"
" float falloff = attenuation_reid(light_pos, light_rgb, light_distance); \n"
" // Uncomment to use orenNayar, cookTorrance, etc \n"
" // float falloff = attenuation_madams(u_light_pos_r[ii].w, 0.5, light_distance); \n"
" // float roughness = u_rough_albedo_fresnel.x; \n"
" // float albedo = u_rough_albedo_fresnel.y; \n"
" // float fresnel = u_rough_albedo_fresnel.z; \n"
" float diffuse_coeff = lambert_diffuse(light_direction, world_normal); \n"
" // float diffuse_coeff = oren+nayar_diffuse(light_direction, view_direction, world_normal, roughness, albedo); \n"
" float diffuse = (diffuse_coeff * falloff); \n"
" // float specular = 0.0; \n"
" float specular = blinn_phong_specular(light_direction, view_direction, world_normal, u_shine); \n"
" // float specular = cook_torrance_specular(light_direction, view_direction, world_normal, roughness, fresnel); \n"
" vec3 light_colour = (diffuse + specular) * light_rgb; \n"
" return light_colour; \n"
"} \n");
static std::string vs_texture_2d_src(
"#version 300 es \n"
"layout(location = 0) in vec4 a_position; \n"
"layout(location = 1) in vec2 a_texCoord; \n"
"out vec2 v_texCoord; \n"
"void main() \n"
"{ \n"
" gl_Position = a_position; \n"
" v_texCoord = a_texCoord; \n"
"} \n");
static std::string fs_texture_2d_src(
"#version 300 es \n"
"precision mediump float; \n"
"in vec2 v_texCoord; \n"
"layout(location = 0) out vec4 outColor; \n"
"uniform sampler2D s_texture; \n"
"void main() \n"
"{ \n"
" outColor = texture( s_texture, v_texCoord ); \n"
"} \n");
static std::string vs_cubemap_src(
"#version 300 es \n"
"layout(location = 0) in vec4 a_position; \n"
"layout(location = 1) in vec3 a_normal; \n"
"out vec3 v_normal; \n"
"void main() \n"
"{ \n"
" gl_Position = a_position; \n"
" v_normal = a_normal; \n"
"} \n");
static std::string fs_cubemap_src(
"#version 300 es \n"
"precision mediump float; \n"
"in vec3 v_normal; \n"
"layout(location = 0) out vec4 outColor; \n"
"uniform samplerCube s_texture; \n"
"void main() \n"
"{ \n"
" outColor = texture(s_texture, v_normal); \n"
"} \n");
*/
}
}
| 44.825658
| 149
| 0.488736
|
ColinGilbert
|
2167af865b1236cabbe027af392640cc9abe4441
| 981
|
cpp
|
C++
|
ch15/test15_5.cpp
|
imshenzhuo/CppPrimer
|
87c74c0a36223e86571c2aedd9da428c06b04f4d
|
[
"CC0-1.0"
] | 3
|
2019-09-21T13:03:57.000Z
|
2020-04-05T02:42:53.000Z
|
ch15/test15_5.cpp
|
imshenzhuo/CppPrimer
|
87c74c0a36223e86571c2aedd9da428c06b04f4d
|
[
"CC0-1.0"
] | null | null | null |
ch15/test15_5.cpp
|
imshenzhuo/CppPrimer
|
87c74c0a36223e86571c2aedd9da428c06b04f4d
|
[
"CC0-1.0"
] | null | null | null |
/*************************************************************************
> File Name: test15_5.cpp
> Author: shenzhuo
> Mail: im.shenzhuo@gmail.com
> Created Time: 2019年09月19日 星期四 09时59分30秒
************************************************************************/
#include<iostream>
using namespace std;
class Base{
public:
int base_public;
protected:
int base_protected;
private:
int base_private;
};
class Pub_De : public Base {
public:
void f() {
cout << base_protected << endl;
}
};
class Pri_De : private Base
{
public:
void f() {
cout << base_public << endl;
cout << base_protected << endl;
// cout << base_private << endl;
}
};
int main(int argc, char const *argv[])
{
Pub_De pd;
pd.base_public = 100;
// error
// pd.base_protected = 100;
pd.f();
Pri_De ppd;
// ppd.base_protected = 100;
// ppd.base_public = 100;
ppd.f();
return 0;
}
| 17.210526
| 74
| 0.490316
|
imshenzhuo
|
216aa3a32caa8ada6f2adda842ffc176e2b4676a
| 1,491
|
cpp
|
C++
|
libnd4j/include/helpers/impl/ProviderRNG.cpp
|
KolyaIvankov/deeplearning4j
|
61c02d31fa950259d7458a021de7db167a3410ae
|
[
"Apache-2.0"
] | null | null | null |
libnd4j/include/helpers/impl/ProviderRNG.cpp
|
KolyaIvankov/deeplearning4j
|
61c02d31fa950259d7458a021de7db167a3410ae
|
[
"Apache-2.0"
] | null | null | null |
libnd4j/include/helpers/impl/ProviderRNG.cpp
|
KolyaIvankov/deeplearning4j
|
61c02d31fa950259d7458a021de7db167a3410ae
|
[
"Apache-2.0"
] | null | null | null |
/*******************************************************************************
* Copyright (c) 2015-2018 Skymind, Inc.
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
//
// Created by Yurii Shyrma on 27.01.2018
//
#include <helpers/ProviderRNG.h>
#include <NativeOps.h>
namespace nd4j {
ProviderRNG::ProviderRNG() {
Nd4jLong *buffer = new Nd4jLong[100000];
std::lock_guard<std::mutex> lock(_mutex);
#ifndef __CUDABLAS__
// at this moment we don't have streams etc, so let's just skip this for now
_rng = (nd4j::random::RandomBuffer *) initRandom(nullptr, 123, 100000, (Nd4jPointer) buffer);
#endif
// if(_rng != nullptr)
}
ProviderRNG& ProviderRNG::getInstance() {
static ProviderRNG instance;
return instance;
}
random::RandomBuffer* ProviderRNG::getRNG() const {
return _rng;
}
std::mutex ProviderRNG::_mutex;
}
| 28.673077
| 101
| 0.625755
|
KolyaIvankov
|
2173d652f61867037b50442277f36bca9603f213
| 2,651
|
cpp
|
C++
|
libs/lfd/src/resource_file.cpp
|
tiaanl/red5
|
ea7593b38f61f64f8aeb7d58854106bd58c05736
|
[
"MIT"
] | 1
|
2020-11-24T13:26:11.000Z
|
2020-11-24T13:26:11.000Z
|
libs/lfd/src/resource_file.cpp
|
tiaanl/red5
|
ea7593b38f61f64f8aeb7d58854106bd58c05736
|
[
"MIT"
] | null | null | null |
libs/lfd/src/resource_file.cpp
|
tiaanl/red5
|
ea7593b38f61f64f8aeb7d58854106bd58c05736
|
[
"MIT"
] | null | null | null |
#include "lfd/resource_file.h"
#include <base/streams/file_input_stream.h>
#include <base/streams/file_output_stream.h>
std::vector<ResourceEntry> ResourceFile::loadEntries() const {
if (!std::filesystem::exists(m_path)) {
spdlog::error("Resource file not found: {}", m_path.string());
return {};
}
spdlog::info("Loading entries from resource file: {}", m_path.string());
base::FileInputStream stream{m_path};
// TODO: Check if the file was opened successfully.
// Read ResourceMap header.
auto type = static_cast<ResourceType>(stream.readU32());
if (type != ResourceType::ResourceMap) {
spdlog::error("Invalid LFD file. ({})", m_path.string());
return {};
}
U8 name[9] = {};
stream.read(name, 8);
U32 size = stream.readU32();
#if 0
spdlog::info("ResourceMap :: type: {}, name: {}, size: {}", resourceTypeToString(type), name, size);
#endif // 0
// Skip the header block and get the details from the individual resource headers.
stream.advance(size);
std::vector<ResourceEntry> entries;
for (MemSize i = 0; i < size / 16; ++i) {
auto resource = readResourceEntry(&stream);
if (resource.has_value()) {
#if 0
spdlog::info("entry: ({}) {}", resourceTypeToString(resource.value().type()),
resource.value().name());
#endif // 0
entries.emplace_back(std::move(resource.value()));
}
}
return entries;
}
// static
std::optional<ResourceEntry> ResourceFile::readResourceEntry(base::InputStream* stream) {
ResourceType type = static_cast<ResourceType>(stream->readU32());
char name[9] = {};
stream->read(name, 8);
U32 size = stream->readU32();
std::vector<U8> data;
data.resize(size);
stream->read(data.data(), size);
return ResourceEntry{type, name, std::move(data)};
}
void writeHeader(base::OutputStream* stream, ResourceType resourceType, std::string_view name,
MemSize size) {
stream->writeU32(static_cast<U32>(resourceType));
U8 nameBuf[8] = {};
std::memcpy(nameBuf, name.data(), std::min(name.length(), sizeof(nameBuf)));
stream->write(nameBuf, sizeof(nameBuf));
stream->writeU32(static_cast<U32>(size));
}
void ResourceFile::saveEntries(const std::vector<ResourceEntry>& entries) {
base::FileOutputStream stream{m_path};
writeHeader(&stream, ResourceType::ResourceMap, "resource", entries.size() * 16);
for (auto& entry : entries) {
writeHeader(&stream, entry.type(), entry.name(), entry.data().size());
}
for (auto& entry : entries) {
writeHeader(&stream, entry.type(), entry.name(), entry.data().size());
stream.write(entry.data().data(), entry.data().size());
}
}
| 29.786517
| 102
| 0.6639
|
tiaanl
|
2175d53d0705dd963399a9aa73bb84b81a9ecb1c
| 1,056
|
cpp
|
C++
|
source/System/ThreadPool/ThreadPool.cpp
|
Fabrice-Praxinos/ULIS
|
232ad5c0804da1202d8231fda67ff4aea70f57ef
|
[
"RSA-MD"
] | 30
|
2020-09-16T17:39:36.000Z
|
2022-02-17T08:32:53.000Z
|
source/System/ThreadPool/ThreadPool.cpp
|
Fabrice-Praxinos/ULIS
|
232ad5c0804da1202d8231fda67ff4aea70f57ef
|
[
"RSA-MD"
] | 7
|
2020-11-23T14:37:15.000Z
|
2022-01-17T11:35:32.000Z
|
source/System/ThreadPool/ThreadPool.cpp
|
Fabrice-Praxinos/ULIS
|
232ad5c0804da1202d8231fda67ff4aea70f57ef
|
[
"RSA-MD"
] | 5
|
2020-09-17T00:39:14.000Z
|
2021-08-30T16:14:07.000Z
|
// IDDN FR.001.250001.004.S.X.2019.000.00000
// ULIS is subject to copyright laws and is the legal and intellectual property of Praxinos,Inc
/*
* ULIS
*__________________
* @file ThreadPool.cpp
* @author Clement Berthaud
* @brief This file provides the definition for the FThreadPool class.
* @copyright Copyright 2018-2021 Praxinos, Inc. All Rights Reserved.
* @license Please refer to LICENSE.md
*/
#include "System/ThreadPool/ThreadPool.h"
#include "System/ThreadPool/ThreadPool_Private.h"
ULIS_NAMESPACE_BEGIN
FThreadPool::~FThreadPool()
{
delete d;
}
FThreadPool::FThreadPool( uint32 iNumWorkers )
: d( new FThreadPool_Private( iNumWorkers ) )
{
}
void
FThreadPool::WaitForCompletion()
{
d->WaitForCompletion();
}
void
FThreadPool::SetNumWorkers( uint32 iNumWorkers )
{
d->SetNumWorkers( iNumWorkers );
}
uint32
FThreadPool::GetNumWorkers() const
{
return d->GetNumWorkers();
}
//static
uint32
FThreadPool::MaxWorkers()
{
return FThreadPool_Private::MaxWorkers();
}
ULIS_NAMESPACE_END
| 19.924528
| 95
| 0.726326
|
Fabrice-Praxinos
|
217ba72be5dff268cda027470b84457415138e80
| 5,641
|
hpp
|
C++
|
rmf_traffic/include/rmf_traffic/schedule/Patch.hpp
|
methylDragon/rmf_core
|
4099921bea576c2fde87c3dc852cc4d8f86a5d1a
|
[
"Apache-2.0"
] | 109
|
2019-10-31T02:02:50.000Z
|
2022-03-30T04:42:19.000Z
|
rmf_traffic/include/rmf_traffic/schedule/Patch.hpp
|
methylDragon/rmf_core
|
4099921bea576c2fde87c3dc852cc4d8f86a5d1a
|
[
"Apache-2.0"
] | 155
|
2019-11-15T04:43:31.000Z
|
2021-04-22T09:45:32.000Z
|
rmf_traffic/include/rmf_traffic/schedule/Patch.hpp
|
methylDragon/rmf_core
|
4099921bea576c2fde87c3dc852cc4d8f86a5d1a
|
[
"Apache-2.0"
] | 51
|
2019-10-31T11:30:34.000Z
|
2022-01-27T03:07:01.000Z
|
/*
* Copyright (C) 2020 Open Source Robotics Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef RMF_TRAFFIC__SCHEDULE__PATCH_HPP
#define RMF_TRAFFIC__SCHEDULE__PATCH_HPP
#include <rmf_traffic/schedule/Change.hpp>
#include <rmf_traffic/detail/bidirectional_iterator.hpp>
#include <rmf_utils/optional.hpp>
namespace rmf_traffic {
namespace schedule {
//==============================================================================
/// A container of Database changes
class Patch
{
public:
template<typename E, typename I, typename F>
using base_iterator = rmf_traffic::detail::bidirectional_iterator<E, I, F>;
class Participant
{
public:
/// Constructor
///
/// \param[in] id
/// The ID of the participant that is being changed
///
/// \param[in] erasures
/// The information about which routes to erase
///
/// \param[in] delays
/// The information about what delays have occurred
///
/// \param[in] additions
/// The information about which routes to add
Participant(
ParticipantId id,
Change::Erase erasures,
std::vector<Change::Delay> delays,
Change::Add additions);
/// The ID of the participant that this set of changes will patch.
ParticipantId participant_id() const;
/// The route erasures to perform.
///
/// These erasures should be performed before any other changes.
const Change::Erase& erasures() const;
/// The sequence of delays to apply.
///
/// These delays should be applied in sequential order after the erasures
/// are performed, and before any additions are performed.
const std::vector<Change::Delay>& delays() const;
/// The set of additions to perfom.
///
/// These additions should be applied after all other changes.
const Change::Add& additions() const;
class Implementation;
private:
rmf_utils::impl_ptr<Implementation> _pimpl;
};
class IterImpl;
using const_iterator = base_iterator<const Participant, IterImpl, Patch>;
/// Constructor. Mirrors should evaluate the fields of the Patch class in the
/// order of these constructor arguments.
///
/// \param[in] removed_participants
/// Information about which participants have been unregistered since the
/// last update.
///
/// \param[in] new_participants
/// Information about which participants have been registered since the last
/// update.
///
/// \param[in] changes
/// Information about how the participants have changed since the last
/// update.
///
/// \param[in] cull
/// Information about how the database has culled old data since the last
/// update.
///
/// \param[in] latest_version
/// The lastest version of the database that this Patch represents.
Patch(
std::vector<Change::UnregisterParticipant> removed_participants,
std::vector<Change::RegisterParticipant> new_participants,
std::vector<Participant> changes,
rmf_utils::optional<Change::Cull> cull,
Version latest_version);
// TODO(MXG): Consider using a persistent reliable topic to broadcast the
// active participant information instead of making it part of the patch.
// Ideally this information would not need to change frequently, so it doesn't
// necessarily need to be in the Patch scheme. The addition and loss of
// participants is significant enough that we should guarantee it's always
// transmitted correctly.
//
// The current scheme makes an assumption that remote mirrors will always
// either sync up before unregistered participant information is culled, or
// else they will perform a complete refresh. This might be a point of
// vulnerability if a remote mirror is not being managed correctly.
/// Get a list of which participants have been unregistered. This should be
/// evaluated first in the patch.
const std::vector<Change::UnregisterParticipant>& unregistered() const;
/// Get a list of new participants that have been registered. This should be
/// evaluated after the unregistered participants.
const std::vector<Change::RegisterParticipant>& registered() const;
/// Returns an iterator to the first element of the Patch.
const_iterator begin() const;
/// Returns an iterator to the element following the last element of the
/// Patch. This iterator acts as a placeholder; attempting to dereference it
/// results in undefined behavior.
const_iterator end() const;
/// Get the number of elements in this Patch.
std::size_t size() const;
/// Get the cull information for this patch if a cull has occurred.
const Change::Cull* cull() const;
/// Get the latest version of the Database that informed this Patch.
Version latest_version() const;
class Implementation;
private:
rmf_utils::impl_ptr<Implementation> _pimpl;
};
} // namespace schedule
namespace detail {
extern template class bidirectional_iterator<
const schedule::Patch::Participant,
schedule::Patch::IterImpl,
schedule::Patch
>;
}
} // namespace rmf_traffic
#endif // RMF_TRAFFIC__SCHEDULE__PATCH_HPP
| 32.41954
| 80
| 0.70413
|
methylDragon
|
217f4eea802c216218e09170d96722b90697c39b
| 7,191
|
cpp
|
C++
|
test/state_machine_test.cpp
|
kariem2k/rive-cpp
|
f58c3b3d48ea03947a76971bce17e7f567cf0de0
|
[
"MIT"
] | 139
|
2020-08-17T20:10:24.000Z
|
2022-03-28T12:22:44.000Z
|
test/state_machine_test.cpp
|
kariem2k/rive-cpp
|
f58c3b3d48ea03947a76971bce17e7f567cf0de0
|
[
"MIT"
] | 89
|
2020-08-28T16:41:01.000Z
|
2022-03-28T19:10:49.000Z
|
test/state_machine_test.cpp
|
kariem2k/rive-cpp
|
f58c3b3d48ea03947a76971bce17e7f567cf0de0
|
[
"MIT"
] | 19
|
2020-10-19T00:54:40.000Z
|
2022-02-28T05:34:17.000Z
|
#include <rive/core/binary_reader.hpp>
#include <rive/file.hpp>
#include <rive/animation/state_machine_bool.hpp>
#include <rive/animation/state_machine_layer.hpp>
#include <rive/animation/animation_state.hpp>
#include <rive/animation/entry_state.hpp>
#include <rive/animation/state_transition.hpp>
#include <rive/animation/state_machine_instance.hpp>
#include <rive/animation/state_machine_input_instance.hpp>
#include <rive/animation/blend_state_1d.hpp>
#include <rive/animation/blend_animation_1d.hpp>
#include <rive/animation/blend_state_direct.hpp>
#include <rive/animation/blend_state_transition.hpp>
#include "catch.hpp"
#include <cstdio>
TEST_CASE("file with state machine be read", "[file]")
{
FILE* fp = fopen("../../test/assets/rocket.riv", "r");
REQUIRE(fp != nullptr);
fseek(fp, 0, SEEK_END);
auto length = ftell(fp);
fseek(fp, 0, SEEK_SET);
uint8_t* bytes = new uint8_t[length];
REQUIRE(fread(bytes, 1, length, fp) == length);
auto reader = rive::BinaryReader(bytes, length);
rive::File* file = nullptr;
auto result = rive::File::import(reader, &file);
REQUIRE(result == rive::ImportResult::success);
REQUIRE(file != nullptr);
auto artboard = file->artboard();
REQUIRE(artboard != nullptr);
REQUIRE(artboard->animationCount() == 3);
REQUIRE(artboard->stateMachineCount() == 1);
auto stateMachine = artboard->stateMachine("Button");
REQUIRE(stateMachine != nullptr);
REQUIRE(stateMachine->layerCount() == 1);
REQUIRE(stateMachine->inputCount() == 2);
auto hover = stateMachine->input("Hover");
REQUIRE(hover != nullptr);
REQUIRE(hover->is<rive::StateMachineBool>());
auto press = stateMachine->input("Press");
REQUIRE(press != nullptr);
REQUIRE(press->is<rive::StateMachineBool>());
auto layer = stateMachine->layer(0);
REQUIRE(layer->stateCount() == 6);
REQUIRE(layer->anyState() != nullptr);
REQUIRE(layer->entryState() != nullptr);
REQUIRE(layer->exitState() != nullptr);
int foundAnimationStates = 0;
for (int i = 0; i < layer->stateCount(); i++)
{
auto state = layer->state(i);
if (state->is<rive::AnimationState>())
{
foundAnimationStates++;
REQUIRE(state->as<rive::AnimationState>()->animation() != nullptr);
}
}
REQUIRE(foundAnimationStates == 3);
REQUIRE(layer->entryState()->transitionCount() == 1);
auto stateTo = layer->entryState()->transition(0)->stateTo();
REQUIRE(stateTo != nullptr);
REQUIRE(stateTo->is<rive::AnimationState>());
REQUIRE(stateTo->as<rive::AnimationState>()->animation() != nullptr);
REQUIRE(stateTo->as<rive::AnimationState>()->animation()->name() == "idle");
auto idleState = stateTo->as<rive::AnimationState>();
REQUIRE(idleState->transitionCount() == 2);
for (int i = 0; i < idleState->transitionCount(); i++)
{
auto transition = idleState->transition(i);
if (transition->stateTo()
->as<rive::AnimationState>()
->animation()
->name() == "Roll_over")
{
// Check the condition
REQUIRE(transition->conditionCount() == 1);
}
}
rive::StateMachineInstance smi(artboard->stateMachine("Button"));
REQUIRE(smi.getBool("Hover")->name() == "Hover");
REQUIRE(smi.getBool("Press")->name() == "Press");
REQUIRE(smi.getBool("Hover") != nullptr);
REQUIRE(smi.getBool("Press") != nullptr);
REQUIRE(smi.stateChangedCount() == 0);
REQUIRE(smi.currentAnimationCount() == 0);
delete file;
delete[] bytes;
}
TEST_CASE("file with blend states loads correctly", "[file]")
{
FILE* fp = fopen("../../test/assets/blend_test.riv", "r");
REQUIRE(fp != nullptr);
fseek(fp, 0, SEEK_END);
auto length = ftell(fp);
fseek(fp, 0, SEEK_SET);
uint8_t* bytes = new uint8_t[length];
REQUIRE(fread(bytes, 1, length, fp) == length);
auto reader = rive::BinaryReader(bytes, length);
rive::File* file = nullptr;
auto result = rive::File::import(reader, &file);
REQUIRE(result == rive::ImportResult::success);
REQUIRE(file != nullptr);
auto artboard = file->artboard();
REQUIRE(artboard != nullptr);
REQUIRE(artboard->animationCount() == 4);
REQUIRE(artboard->stateMachineCount() == 2);
auto stateMachine = artboard->stateMachine("blend");
REQUIRE(stateMachine != nullptr);
REQUIRE(stateMachine->layerCount() == 1);
auto layer = stateMachine->layer(0);
REQUIRE(layer->stateCount() == 5);
REQUIRE(layer->anyState() != nullptr);
REQUIRE(layer->entryState() != nullptr);
REQUIRE(layer->exitState() != nullptr);
REQUIRE(layer->state(1)->is<rive::BlendState1D>());
REQUIRE(layer->state(2)->is<rive::BlendState1D>());
auto blendStateA = layer->state(1)->as<rive::BlendState1D>();
auto blendStateB = layer->state(2)->as<rive::BlendState1D>();
REQUIRE(blendStateA->animationCount() == 3);
REQUIRE(blendStateB->animationCount() == 3);
auto animation = blendStateA->animation(0);
REQUIRE(animation->is<rive::BlendAnimation1D>());
auto animation1D = animation->as<rive::BlendAnimation1D>();
REQUIRE(animation1D->animation() != nullptr);
REQUIRE(animation1D->animation()->name() == "horizontal");
REQUIRE(animation1D->value() == 0.0f);
animation = blendStateA->animation(1);
REQUIRE(animation->is<rive::BlendAnimation1D>());
animation1D = animation->as<rive::BlendAnimation1D>();
REQUIRE(animation1D->animation() != nullptr);
REQUIRE(animation1D->animation()->name() == "vertical");
REQUIRE(animation1D->value() == 100.0f);
animation = blendStateA->animation(2);
REQUIRE(animation->is<rive::BlendAnimation1D>());
animation1D = animation->as<rive::BlendAnimation1D>();
REQUIRE(animation1D->animation() != nullptr);
REQUIRE(animation1D->animation()->name() == "rotate");
REQUIRE(animation1D->value() == 0.0f);
REQUIRE(blendStateA->transitionCount() == 1);
REQUIRE(blendStateA->transition(0)->is<rive::BlendStateTransition>());
REQUIRE(blendStateA->transition(0)
->as<rive::BlendStateTransition>()
->exitBlendAnimation() != nullptr);
delete file;
delete[] bytes;
}
TEST_CASE("animation state with no animation doesn't crash", "[file]")
{
FILE* fp = fopen("../../test/assets/multiple_state_machines.riv", "r");
REQUIRE(fp != nullptr);
fseek(fp, 0, SEEK_END);
auto length = ftell(fp);
fseek(fp, 0, SEEK_SET);
uint8_t* bytes = new uint8_t[length];
REQUIRE(fread(bytes, 1, length, fp) == length);
auto reader = rive::BinaryReader(bytes, length);
rive::File* file = nullptr;
auto result = rive::File::import(reader, &file);
REQUIRE(result == rive::ImportResult::success);
REQUIRE(file != nullptr);
auto artboard = file->artboard();
REQUIRE(artboard != nullptr);
REQUIRE(artboard->animationCount() == 1);
REQUIRE(artboard->stateMachineCount() == 4);
auto stateMachine = artboard->stateMachine("two");
REQUIRE(stateMachine != nullptr);
REQUIRE(stateMachine->layerCount() == 1);
auto layer = stateMachine->layer(0);
REQUIRE(layer->stateCount() == 4);
REQUIRE(layer->anyState() != nullptr);
REQUIRE(layer->entryState() != nullptr);
REQUIRE(layer->exitState() != nullptr);
REQUIRE(layer->state(3)->is<rive::AnimationState>());
auto animationState = layer->state(3)->as<rive::AnimationState>();
REQUIRE(animationState->animation() == nullptr);
rive::StateMachineInstance smi(stateMachine);
smi.advance(artboard, 0.0f);
delete file;
delete[] bytes;
}
| 32.686364
| 77
| 0.695175
|
kariem2k
|
2186f8dcb78f27fa11418cdb0781536905738bba
| 1,408
|
cpp
|
C++
|
tcp_async_server.cpp
|
opensvn/boost_learning
|
7f21551a7f3db38bea2c31d95d0c8b4e00f4537e
|
[
"BSL-1.0"
] | null | null | null |
tcp_async_server.cpp
|
opensvn/boost_learning
|
7f21551a7f3db38bea2c31d95d0c8b4e00f4537e
|
[
"BSL-1.0"
] | null | null | null |
tcp_async_server.cpp
|
opensvn/boost_learning
|
7f21551a7f3db38bea2c31d95d0c8b4e00f4537e
|
[
"BSL-1.0"
] | 1
|
2021-10-01T04:27:44.000Z
|
2021-10-01T04:27:44.000Z
|
#include <iostream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
using namespace std;
using namespace boost::asio;
class server
{
private:
io_service &ios;
ip::tcp::acceptor acceptor;
typedef boost::shared_ptr<ip::tcp::socket> sock_pt;
public:
server(io_service& io):
ios(io), acceptor(ios, ip::tcp::endpoint(ip::tcp::v4(), 6688))
{
start();
}
void start()
{
sock_pt sock(new ip::tcp::socket(ios));
acceptor.async_accept(*sock,
boost::bind(&server::accept_handler, this,
placeholders::error, sock));
}
void accept_handler(const boost::system::error_code &ec, sock_pt sock)
{
if (ec)
return;
cout << "client:";
cout << sock->remote_endpoint().address() << endl;
sock->async_write_some(buffer("hello asio"),
boost::bind(&server::write_handler, this, placeholders::error));
start();
}
void write_handler(const boost::system::error_code&)
{
cout << "send msg complete." << endl;
}
};
int main()
{
try
{
cout << "server start." << endl;
io_service ios;
server s(ios);
ios.run();
}
catch (exception &e)
{
cout << e.what() << endl;
}
return 0;
}
| 22.349206
| 95
| 0.534801
|
opensvn
|
219f4474b7a0e490495e53119708bdffb0737351
| 950
|
cpp
|
C++
|
test/linux/main.cpp
|
77Z/Shadow-Engine
|
a07121d56dcf71a040580e9d4e563f36a70123a3
|
[
"MIT"
] | 3
|
2020-08-31T20:38:54.000Z
|
2021-06-17T12:31:44.000Z
|
test/linux/main.cpp
|
77Z/Shadow-Engine
|
a07121d56dcf71a040580e9d4e563f36a70123a3
|
[
"MIT"
] | 3
|
2020-08-31T19:08:43.000Z
|
2022-03-25T19:11:50.000Z
|
test/linux/main.cpp
|
77Z/Shadow-Engine
|
a07121d56dcf71a040580e9d4e563f36a70123a3
|
[
"MIT"
] | null | null | null |
//Copyright © Vince Richter 2020
//Copyright © 77Z™ 2020
#include "main.h"
void print(std::string text) {
std::cout << text << std::endl;
}
inline bool exists(const std::string& name) {
struct stat buffer;
return (stat (name.c_str(), &buffer) == 0);
}
int main() {
print("Running Linux Style Tests");
if (exists("./node_modules/electron/dist/electron")) {
print("Test 1 Passed");
} else {
print("Test 1 Failed");
exit(1);
}
if (exists("./node_modules/node-pty/build/Release/pty.node")) {
print("Test 2 Passed");
} else {
print("Test 2 Failed");
exit(1);
}
if (exists("./node_modules/uuid/dist/index.js")) {
print("Test 3 Passed");
} else {
print("Test 3 Failed");
exit(1);
}
print("All tests passed (Linux)");
//Every Test Passed, exit with code 0
return 0;
}
| 21.111111
| 68
| 0.532632
|
77Z
|
21a16fb2c835e0de58984b52ed7b0ce6a9144ce8
| 6,168
|
cpp
|
C++
|
source/function.cpp
|
Venkster123/Zhetapi
|
9a034392c06733c57d892afde300e90c4b7036f9
|
[
"MIT"
] | 27
|
2020-06-05T15:39:31.000Z
|
2022-01-07T05:03:01.000Z
|
source/function.cpp
|
Venkster123/Zhetapi
|
9a034392c06733c57d892afde300e90c4b7036f9
|
[
"MIT"
] | 1
|
2021-02-12T04:51:40.000Z
|
2021-02-12T04:51:40.000Z
|
source/function.cpp
|
Venkster123/Zhetapi
|
9a034392c06733c57d892afde300e90c4b7036f9
|
[
"MIT"
] | 4
|
2021-02-12T04:39:55.000Z
|
2021-11-15T08:00:06.000Z
|
#include "../engine/function.hpp"
#include "../engine/engine.hpp"
#include "../engine/core/operation_base.hpp"
namespace zhetapi {
// Static variables
Engine *Function::shared_context = new Engine();
double Function::h = 0.0001;
// Methods
// TODO: use macro
ZHP_TOKEN_METHOD(ftn_deriv_method)
{
// TODO: remove assert (and use a special one that throw mistch errs)
assert(args.size() == 0);
Function *fptr = dynamic_cast <Function *> (tptr);
// Differentiate on first arg by default
return fptr->differentiate(fptr->_params[0]).copy();
}
MethodTable Function::mtable ({
{"derivative", {&ftn_deriv_method, "NA"}}
});
// Constructors
Function::Function() : _threads(1), Token(&Function::mtable) {}
Function::Function(const char *str) : Function(std::string(str)) {}
// TODO: Take an Engine as an input as well: there is no need to delay rvalue resolution
Function::Function(const std::string &str, Engine *context)
: _threads(1), Token(&Function::mtable)
{
// TODO: Remove this (duplication)
std::string pack;
std::string tmp;
size_t count;
size_t index;
size_t start;
size_t end;
size_t i;
bool valid;
bool sb;
bool eb;
count = 0;
valid = false;
sb = false;
eb = false;
// Split string into expression and symbols
for (i = 0; i < str.length(); i++) {
if (str[i] == '=') {
valid = true;
index = i;
++count;
}
}
if (!valid || count != 1)
throw invalid_definition();
_symbol = str.substr(0, index);
// Determine parameters' symbols
for (start = -1, i = 0; i < _symbol.length(); i++) {
if (str[i] == '(' && start == -1) {
start = i;
sb = true;
}
if (str[i] == ')') {
end = i;
eb = true;
}
}
if (!sb || !eb)
throw invalid_definition();
pack = _symbol.substr(start + 1, end - start - 1);
for (i = 0; i < pack.length(); i++) {
if (pack[i] == ',' && !tmp.empty()) {
_params.push_back(tmp);
tmp.clear();
} else if (!isspace(pack[i])) {
tmp += pack[i];
}
}
if (!tmp.empty())
_params.push_back(tmp);
// Determine function's symbol
_symbol = _symbol.substr(0, start);
// Construct the tree manager
_manager = node_manager(context, str.substr(++index), _params);
/* using namespace std;
cout << "FUNCTION manager:" << endl;
print(); */
}
// Member-wise construction (TODO: change to Args)
Function::Function(const std::string &symbol, const std::vector
<std::string> ¶ms, const node_manager &manager) :
_symbol(symbol), _params(params),
_manager(manager), _threads(1), Token(&Function::mtable) {}
Function::Function(const Function &other) :
_symbol(other._symbol), _params(other._params),
_manager(other._manager), _threads(1),
Token(&Function::mtable) {}
// Getters
bool Function::is_variable(const std::string &str) const
{
return std::find(_params.begin(), _params.end(), str)
!= _params.end();
}
std::string &Function::symbol()
{
return _symbol;
}
const std::string Function::symbol() const
{
return _symbol;
}
void Function::set_threads(size_t threads)
{
_threads = threads;
}
// Computational utilities
Token *Function::evaluate(Engine *ctx, const std::vector<Token *> &ins)
{
// TODO: refactor params to args
// TODO: create an assert macro (or constexpr) thats throws
if (ins.size() != _params.size())
throw Functor::insufficient_args(ins.size(), _params.size());
return _manager.substitute_and_compute(ctx, ins);
}
// TODO: useless
Token *Function::compute(const std::vector <Token *> &ins, Engine *ctx)
{
if (ins.size() != _params.size())
throw Functor::insufficient_args(ins.size(), _params.size());
return _manager.substitute_and_compute(ctx, ins);
}
// TODO: remove this (no user is going to use this)
Token *Function::operator()(const std::vector <Token *> &toks, Engine *context)
{
return compute(toks, context);
}
template <class ... A>
Token *Function::derivative(const std::string &str, A ... args)
{
std::vector <Token *> Tokens;
gather(Tokens, args...);
assert(Tokens.size() == _params.size());
size_t i = index(str);
assert(i != -1);
// Right
Token *right;
Tokens[i] = detail::compute("+", {Tokens[i], new Operand <double> (h)});
for (size_t k = 0; k < Tokens.size(); k++) {
if (k != i)
Tokens[k] = Tokens[k]->copy();
}
right = _manager.substitute_and_compute(shared_context, Tokens);
// Left
Token *left;
Tokens[i] = detail::compute("-", {Tokens[i], new Operand <double> (2.0 * h)});
for (size_t k = 0; k < Tokens.size(); k++) {
if (k != i)
Tokens[k] = Tokens[k]->copy();
}
left = _manager.substitute_and_compute(shared_context, Tokens);
// Compute
Token *diff = detail::compute("-", {right, left});
diff = detail::compute("/", {diff, new Operand <double> (2.0 * h)});
return diff;
}
Function Function::differentiate(const std::string &str) const
{
// Improve naming later
std::string name = "d" + _symbol + "/d" + str;
node_manager dm = _manager;
dm.differentiate(str);
Function df = Function(name, _params, dm);
return df;
}
// Virtual functions
Token::type Function::caller() const
{
return Token::ftn;
}
std::string Function::dbg_str() const
{
return display();
}
Token *Function::copy() const
{
return new Function(*this);
}
bool Function::operator==(Token *tptr) const
{
Function *ftn = dynamic_cast <Function *> (tptr);
if (!ftn)
return false;
return ftn->_symbol == _symbol;
}
// Printing utilities
void Function::print() const
{
_manager.print();
}
std::string Function::display() const
{
std::string str = _symbol + "(";
size_t n = _params.size();
for (size_t i = 0; i < n; i++) {
str += _params[i];
if (i < n - 1)
str += ", ";
}
str += ") = " + _manager.display();
return str;
}
std::ostream &operator<<(std::ostream &os, const Function &ftr)
{
os << ftr.display();
return os;
}
// Comparing
bool operator<(const Function &a, const Function &b)
{
return a.symbol() < b.symbol();
}
bool operator>(const Function &a, const Function &b)
{
return a.symbol() > b.symbol();
}
size_t Function::index(const std::string &str) const
{
auto itr = std::find(_params.begin(), _params.end(), str);
if (itr == _params.end())
return -1;
return std::distance(_params.begin(), itr);
}
}
| 19.769231
| 88
| 0.645266
|
Venkster123
|
21a19ad1a17a1917353ab7501f275153fac025e1
| 20,888
|
cc
|
C++
|
src/benchmark.cc
|
mtrofin/benchmark
|
99cfbdd53357477fb328aa54d271178911bd2a84
|
[
"Apache-2.0"
] | null | null | null |
src/benchmark.cc
|
mtrofin/benchmark
|
99cfbdd53357477fb328aa54d271178911bd2a84
|
[
"Apache-2.0"
] | null | null | null |
src/benchmark.cc
|
mtrofin/benchmark
|
99cfbdd53357477fb328aa54d271178911bd2a84
|
[
"Apache-2.0"
] | null | null | null |
// Copyright 2015 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "benchmark/benchmark.h"
#include "benchmark_api_internal.h"
#include "benchmark_runner.h"
#include "internal_macros.h"
#ifndef BENCHMARK_OS_WINDOWS
#ifndef BENCHMARK_OS_FUCHSIA
#include <sys/resource.h>
#endif
#include <sys/time.h>
#include <unistd.h>
#endif
#include <algorithm>
#include <atomic>
#include <condition_variable>
#include <cstdio>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <limits>
#include <map>
#include <memory>
#include <random>
#include <string>
#include <thread>
#include <utility>
#include "absl/flags/flag.h"
#include "absl/flags/parse.h"
#include "absl/synchronization/mutex.h"
#include "check.h"
#include "colorprint.h"
#include "commandlineflags.h"
#include "complexity.h"
#include "counter.h"
#include "internal_macros.h"
#include "log.h"
#include "mutex.h"
#include "perf_counters.h"
#include "re.h"
#include "statistics.h"
#include "string_util.h"
#include "thread_manager.h"
#include "thread_timer.h"
ABSL_FLAG(
bool, benchmark_list_tests, false,
"Print a list of benchmarks. This option overrides all other options.");
ABSL_FLAG(std::string, benchmark_filter, ".",
"A regular expression that specifies the set of benchmarks to "
"execute. If this flag is empty, or if this flag is the string "
"\"all\", all benchmarks linked into the binary are run.");
ABSL_FLAG(
double, benchmark_min_time, 0.5,
"Minimum number of seconds we should run benchmark before results are "
"considered significant. For cpu-time based tests, this is the lower "
"bound on the total cpu time used by all threads that make up the test. "
"For real-time based tests, this is the lower bound on the elapsed time of "
"the benchmark execution, regardless of number of threads.");
ABSL_FLAG(int32_t, benchmark_repetitions, 1,
"The number of runs of each benchmark. If greater than 1, the mean "
"and standard deviation of the runs will be reported.");
ABSL_FLAG(
bool, benchmark_enable_random_interleaving, false,
"If set, enable random interleaving of repetitions of all benchmarks. See "
"http://github.com/google/benchmark/issues/1051 for details.");
ABSL_FLAG(bool, benchmark_report_aggregates_only, false,
"Report the result of each benchmark repetitions. When 'true' is "
"specified only the mean, standard deviation, and other statistics "
"are reported for repeated benchmarks. Affects all reporters.");
ABSL_FLAG(
bool, benchmark_display_aggregates_only, false,
"Display the result of each benchmark repetitions. When 'true' is "
"specified only the mean, standard deviation, and other statistics are "
"displayed for repeated benchmarks. Unlike "
"benchmark_report_aggregates_only, only affects the display reporter, but "
"*NOT* file reporter, which will still contain all the output.");
ABSL_FLAG(std::string, benchmark_format, "console",
"The format to use for console output. Valid values are 'console', "
"'json', or 'csv'.");
ABSL_FLAG(std::string, benchmark_out_format, "json",
"The format to use for file output. Valid values are 'console', "
"'json', or 'csv'.");
ABSL_FLAG(std::string, benchmark_out, "",
"The file to write additional output to.");
ABSL_FLAG(std::string, benchmark_color, "auto",
"Whether to use colors in the output. Valid values: 'true'/'yes'/1, "
"'false'/'no'/0, and 'auto'. 'auto' means to use colors if the "
"output is being sent to a terminal and the TERM environment "
"variable is set to a terminal type that supports colors.");
ABSL_FLAG(
bool, benchmark_counters_tabular, false,
"Whether to use tabular format when printing user counters to the console. "
"Valid values: 'true'/'yes'/1, 'false'/'no'/0. Defaults to false.");
ABSL_FLAG(int32_t, v, 0, "The level of verbose logging to output.");
ABSL_FLAG(std::vector<std::string>, benchmark_perf_counters, {},
"List of additional perf counters to collect, in libpfm format. For "
"more information about libpfm: "
"https://man7.org/linux/man-pages/man3/libpfm.3.html");
ABSL_FLAG(std::string, benchmark_context, "",
"Extra context to include in the output formatted as comma-separated "
"key-value pairs. Kept internal as it's only used for parsing from "
"env/command line.");
namespace benchmark {
namespace internal {
std::map<std::string, std::string>* global_context = nullptr;
// FIXME: wouldn't LTO mess this up?
void UseCharPointer(char const volatile*) {}
} // namespace internal
State::State(IterationCount max_iters, const std::vector<int64_t>& ranges,
int thread_i, int n_threads, internal::ThreadTimer* timer,
internal::ThreadManager* manager,
internal::PerfCountersMeasurement* perf_counters_measurement)
: total_iterations_(0),
batch_leftover_(0),
max_iterations(max_iters),
started_(false),
finished_(false),
error_occurred_(false),
range_(ranges),
complexity_n_(0),
counters(),
thread_index_(thread_i),
threads_(n_threads),
timer_(timer),
manager_(manager),
perf_counters_measurement_(perf_counters_measurement) {
BM_CHECK(max_iterations != 0) << "At least one iteration must be run";
BM_CHECK_LT(thread_index_, threads_)
<< "thread_index must be less than threads";
// Note: The use of offsetof below is technically undefined until C++17
// because State is not a standard layout type. However, all compilers
// currently provide well-defined behavior as an extension (which is
// demonstrated since constexpr evaluation must diagnose all undefined
// behavior). However, GCC and Clang also warn about this use of offsetof,
// which must be suppressed.
#if defined(__INTEL_COMPILER)
#pragma warning push
#pragma warning(disable : 1875)
#elif defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Winvalid-offsetof"
#endif
// Offset tests to ensure commonly accessed data is on the first cache line.
const int cache_line_size = 64;
static_assert(offsetof(State, error_occurred_) <=
(cache_line_size - sizeof(error_occurred_)),
"");
#if defined(__INTEL_COMPILER)
#pragma warning pop
#elif defined(__GNUC__)
#pragma GCC diagnostic pop
#endif
}
void State::PauseTiming() {
// Add in time accumulated so far
BM_CHECK(started_ && !finished_ && !error_occurred_);
timer_->StopTimer();
if (perf_counters_measurement_) {
auto measurements = perf_counters_measurement_->StopAndGetMeasurements();
for (const auto& name_and_measurement : measurements) {
auto name = name_and_measurement.first;
auto measurement = name_and_measurement.second;
BM_CHECK_EQ(counters[name], 0.0);
counters[name] = Counter(measurement, Counter::kAvgIterations);
}
}
}
void State::ResumeTiming() {
BM_CHECK(started_ && !finished_ && !error_occurred_);
timer_->StartTimer();
if (perf_counters_measurement_) {
perf_counters_measurement_->Start();
}
}
void State::SkipWithError(const char* msg) {
BM_CHECK(msg);
error_occurred_ = true;
{
MutexLock l(manager_->GetBenchmarkMutex());
if (manager_->results.has_error_ == false) {
manager_->results.error_message_ = msg;
manager_->results.has_error_ = true;
}
}
total_iterations_ = 0;
if (timer_->running()) timer_->StopTimer();
}
void State::SetIterationTime(double seconds) {
timer_->SetIterationTime(seconds);
}
void State::SetLabel(const char* label) {
MutexLock l(manager_->GetBenchmarkMutex());
manager_->results.report_label_ = label;
}
void State::StartKeepRunning() {
BM_CHECK(!started_ && !finished_);
started_ = true;
total_iterations_ = error_occurred_ ? 0 : max_iterations;
manager_->StartStopBarrier();
if (!error_occurred_) ResumeTiming();
}
void State::FinishKeepRunning() {
BM_CHECK(started_ && (!finished_ || error_occurred_));
if (!error_occurred_) {
PauseTiming();
}
// Total iterations has now wrapped around past 0. Fix this.
total_iterations_ = 0;
finished_ = true;
manager_->StartStopBarrier();
}
namespace internal {
namespace {
// Flushes streams after invoking reporter methods that write to them. This
// ensures users get timely updates even when streams are not line-buffered.
void FlushStreams(BenchmarkReporter* reporter) {
if (!reporter) return;
std::flush(reporter->GetOutputStream());
std::flush(reporter->GetErrorStream());
}
// Reports in both display and file reporters.
void Report(BenchmarkReporter* display_reporter,
BenchmarkReporter* file_reporter, const RunResults& run_results) {
auto report_one = [](BenchmarkReporter* reporter, bool aggregates_only,
const RunResults& results) {
assert(reporter);
// If there are no aggregates, do output non-aggregates.
aggregates_only &= !results.aggregates_only.empty();
if (!aggregates_only) reporter->ReportRuns(results.non_aggregates);
if (!results.aggregates_only.empty())
reporter->ReportRuns(results.aggregates_only);
};
report_one(display_reporter, run_results.display_report_aggregates_only,
run_results);
if (file_reporter)
report_one(file_reporter, run_results.file_report_aggregates_only,
run_results);
FlushStreams(display_reporter);
FlushStreams(file_reporter);
}
void RunBenchmarks(const std::vector<BenchmarkInstance>& benchmarks,
BenchmarkReporter* display_reporter,
BenchmarkReporter* file_reporter) {
// Note the file_reporter can be null.
BM_CHECK(display_reporter != nullptr);
// Determine the width of the name field using a minimum width of 10.
bool might_have_aggregates = absl::GetFlag(FLAGS_benchmark_repetitions) > 1;
size_t name_field_width = 10;
size_t stat_field_width = 0;
for (const BenchmarkInstance& benchmark : benchmarks) {
name_field_width =
std::max<size_t>(name_field_width, benchmark.name().str().size());
might_have_aggregates |= benchmark.repetitions() > 1;
for (const auto& Stat : benchmark.statistics())
stat_field_width = std::max<size_t>(stat_field_width, Stat.name_.size());
}
if (might_have_aggregates) name_field_width += 1 + stat_field_width;
// Print header here
BenchmarkReporter::Context context;
context.name_field_width = name_field_width;
// Keep track of running times of all instances of each benchmark family.
std::map<int /*family_index*/, BenchmarkReporter::PerFamilyRunReports>
per_family_reports;
if (display_reporter->ReportContext(context) &&
(!file_reporter || file_reporter->ReportContext(context))) {
FlushStreams(display_reporter);
FlushStreams(file_reporter);
size_t num_repetitions_total = 0;
std::vector<internal::BenchmarkRunner> runners;
runners.reserve(benchmarks.size());
for (const BenchmarkInstance& benchmark : benchmarks) {
BenchmarkReporter::PerFamilyRunReports* reports_for_family = nullptr;
if (benchmark.complexity() != oNone)
reports_for_family = &per_family_reports[benchmark.family_index()];
runners.emplace_back(benchmark, reports_for_family);
int num_repeats_of_this_instance = runners.back().GetNumRepeats();
num_repetitions_total += num_repeats_of_this_instance;
if (reports_for_family)
reports_for_family->num_runs_total += num_repeats_of_this_instance;
}
assert(runners.size() == benchmarks.size() && "Unexpected runner count.");
std::vector<size_t> repetition_indices;
repetition_indices.reserve(num_repetitions_total);
for (size_t runner_index = 0, num_runners = runners.size();
runner_index != num_runners; ++runner_index) {
const internal::BenchmarkRunner& runner = runners[runner_index];
std::fill_n(std::back_inserter(repetition_indices),
runner.GetNumRepeats(), runner_index);
}
assert(repetition_indices.size() == num_repetitions_total &&
"Unexpected number of repetition indexes.");
if (absl::GetFlag(FLAGS_benchmark_enable_random_interleaving)) {
std::random_device rd;
std::mt19937 g(rd());
std::shuffle(repetition_indices.begin(), repetition_indices.end(), g);
}
for (size_t repetition_index : repetition_indices) {
internal::BenchmarkRunner& runner = runners[repetition_index];
runner.DoOneRepetition();
if (runner.HasRepeatsRemaining()) continue;
// FIXME: report each repetition separately, not all of them in bulk.
RunResults run_results = runner.GetResults();
// Maybe calculate complexity report
if (const auto* reports_for_family = runner.GetReportsForFamily()) {
if (reports_for_family->num_runs_done ==
reports_for_family->num_runs_total) {
auto additional_run_stats = ComputeBigO(reports_for_family->Runs);
run_results.aggregates_only.insert(run_results.aggregates_only.end(),
additional_run_stats.begin(),
additional_run_stats.end());
per_family_reports.erase(
(int)reports_for_family->Runs.front().family_index);
}
}
Report(display_reporter, file_reporter, run_results);
}
}
display_reporter->Finalize();
if (file_reporter) file_reporter->Finalize();
FlushStreams(display_reporter);
FlushStreams(file_reporter);
}
// Disable deprecated warnings temporarily because we need to reference
// CSVReporter but don't want to trigger -Werror=-Wdeprecated-declarations
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#endif
std::unique_ptr<BenchmarkReporter> CreateReporter(
std::string const&& name, ConsoleReporter::OutputOptions output_opts) {
typedef std::unique_ptr<BenchmarkReporter> PtrType;
if (name == "console") {
return PtrType(new ConsoleReporter(output_opts));
} else if (name == "json") {
return PtrType(new JSONReporter);
} else if (name == "csv") {
return PtrType(new CSVReporter);
} else {
std::cerr << "Unexpected format: '" << name << "'\n";
std::exit(1);
}
}
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif
} // end namespace
bool IsZero(double n) {
return std::abs(n) < std::numeric_limits<double>::epsilon();
}
ConsoleReporter::OutputOptions GetOutputOptions(bool force_no_color) {
int output_opts = ConsoleReporter::OO_Defaults;
auto is_benchmark_color = [force_no_color]() -> bool {
if (force_no_color) {
return false;
}
if (absl::GetFlag(FLAGS_benchmark_color) == "auto") {
return IsColorTerminal();
}
return IsTruthyFlagValue(absl::GetFlag(FLAGS_benchmark_color));
};
if (is_benchmark_color()) {
output_opts |= ConsoleReporter::OO_Color;
} else {
output_opts &= ~ConsoleReporter::OO_Color;
}
if (absl::GetFlag(FLAGS_benchmark_counters_tabular)) {
output_opts |= ConsoleReporter::OO_Tabular;
} else {
output_opts &= ~ConsoleReporter::OO_Tabular;
}
return static_cast<ConsoleReporter::OutputOptions>(output_opts);
}
} // end namespace internal
size_t RunSpecifiedBenchmarks() {
return RunSpecifiedBenchmarks(nullptr, nullptr);
}
size_t RunSpecifiedBenchmarks(BenchmarkReporter* display_reporter) {
return RunSpecifiedBenchmarks(display_reporter, nullptr);
}
size_t RunSpecifiedBenchmarks(BenchmarkReporter* display_reporter,
BenchmarkReporter* file_reporter) {
std::string spec = absl::GetFlag(FLAGS_benchmark_filter);
if (spec.empty() || spec == "all")
spec = "."; // Regexp that matches all benchmarks
// Setup the reporters
std::ofstream output_file;
std::unique_ptr<BenchmarkReporter> default_display_reporter;
std::unique_ptr<BenchmarkReporter> default_file_reporter;
if (!display_reporter) {
default_display_reporter = internal::CreateReporter(
absl::GetFlag(FLAGS_benchmark_format), internal::GetOutputOptions());
display_reporter = default_display_reporter.get();
}
auto& Out = display_reporter->GetOutputStream();
auto& Err = display_reporter->GetErrorStream();
const std::string fname = absl::GetFlag(FLAGS_benchmark_out);
if (fname.empty() && file_reporter) {
Err << "A custom file reporter was provided but "
"--benchmark_out=<file> was not specified."
<< std::endl;
std::exit(1);
}
if (!fname.empty()) {
output_file.open(fname);
if (!output_file.is_open()) {
Err << "invalid file name: '" << fname << "'" << std::endl;
std::exit(1);
}
if (!file_reporter) {
default_file_reporter = internal::CreateReporter(
absl::GetFlag(FLAGS_benchmark_out_format), ConsoleReporter::OO_None);
file_reporter = default_file_reporter.get();
}
file_reporter->SetOutputStream(&output_file);
file_reporter->SetErrorStream(&output_file);
}
std::vector<internal::BenchmarkInstance> benchmarks;
if (!FindBenchmarksInternal(spec, &benchmarks, &Err)) return 0;
if (benchmarks.empty()) {
Err << "Failed to match any benchmarks against regex: " << spec << "\n";
return 0;
}
if (absl::GetFlag(FLAGS_benchmark_list_tests)) {
for (auto const& benchmark : benchmarks)
Out << benchmark.name().str() << "\n";
} else {
internal::RunBenchmarks(benchmarks, display_reporter, file_reporter);
}
return benchmarks.size();
}
void RegisterMemoryManager(MemoryManager* manager) {
internal::memory_manager = manager;
}
void AddCustomContext(const std::string& key, const std::string& value) {
if (internal::global_context == nullptr) {
internal::global_context = new std::map<std::string, std::string>();
}
if (!internal::global_context->emplace(key, value).second) {
std::cerr << "Failed to add custom context \"" << key << "\" as it already "
<< "exists with value \"" << value << "\"\n";
}
}
namespace internal {
void PrintUsageAndExit() {
fprintf(stdout,
"benchmark"
" [--benchmark_list_tests={true|false}]\n"
" [--benchmark_filter=<regex>]\n"
" [--benchmark_min_time=<min_time>]\n"
" [--benchmark_repetitions=<num_repetitions>]\n"
" [--benchmark_enable_random_interleaving={true|false}]\n"
" [--benchmark_report_aggregates_only={true|false}]\n"
" [--benchmark_display_aggregates_only={true|false}]\n"
" [--benchmark_format=<console|json|csv>]\n"
" [--benchmark_out=<filename>]\n"
" [--benchmark_out_format=<json|console|csv>]\n"
" [--benchmark_color={auto|true|false}]\n"
" [--benchmark_counters_tabular={true|false}]\n"
" [--benchmark_perf_counters=<counter>,...]\n"
" [--benchmark_context=<key>=<value>,...]\n"
" [--v=<verbosity>]\n");
exit(0);
}
void ValidateCommandLineFlags() {
for (auto const& flag : {absl::GetFlag(FLAGS_benchmark_format),
absl::GetFlag(FLAGS_benchmark_out_format)}) {
if (flag != "console" && flag != "json" && flag != "csv") {
PrintUsageAndExit();
}
}
if (absl::GetFlag(FLAGS_benchmark_color).empty()) {
PrintUsageAndExit();
}
for (const auto& kv : benchmark::KvPairsFromEnv(
absl::GetFlag(FLAGS_benchmark_context).c_str(), {})) {
AddCustomContext(kv.first, kv.second);
}
}
int InitializeStreams() {
static std::ios_base::Init init;
return 0;
}
} // end namespace internal
std::vector<char*> Initialize(int* argc, char** argv) {
using namespace benchmark;
BenchmarkReporter::Context::executable_name =
(argc && *argc > 0) ? argv[0] : "unknown";
auto unparsed = absl::ParseCommandLine(*argc, argv);
*argc = static_cast<int>(unparsed.size());
benchmark::internal::ValidateCommandLineFlags();
internal::LogLevel() = absl::GetFlag(FLAGS_v);
return unparsed;
}
void Shutdown() {
delete internal::global_context;
}
} // end namespace benchmark
| 35.463497
| 80
| 0.69121
|
mtrofin
|
426f8c942f3ef9d9433a3321aedf5ad1d7a5757f
| 1,819
|
cpp
|
C++
|
ibp_external__libtommatch_set01__bn_mp_clamp.cpp
|
dmitry-lipetsk/libtommath-for-ibprovider--set01
|
b7b8e7cf76bd0b2d265d0c31a99836a3b4bad882
|
[
"WTFPL"
] | null | null | null |
ibp_external__libtommatch_set01__bn_mp_clamp.cpp
|
dmitry-lipetsk/libtommath-for-ibprovider--set01
|
b7b8e7cf76bd0b2d265d0c31a99836a3b4bad882
|
[
"WTFPL"
] | null | null | null |
ibp_external__libtommatch_set01__bn_mp_clamp.cpp
|
dmitry-lipetsk/libtommath-for-ibprovider--set01
|
b7b8e7cf76bd0b2d265d0c31a99836a3b4bad882
|
[
"WTFPL"
] | null | null | null |
////////////////////////////////////////////////////////////////////////////////
#include <_pch_.h>
#pragma hdrstop
#include "source/external/libtommath/set01/ibp_external__libtommatch_set01__tommath_private.h"
namespace ibp{namespace external{namespace libtommath{namespace set01{
////////////////////////////////////////////////////////////////////////////////
/* LibTomMath, multiple-precision integer library -- Tom St Denis
*
* LibTomMath is a library that provides multiple-precision
* integer arithmetic as well as number theoretic functionality.
*
* The library was designed directly after the MPI library by
* Michael Fromberger but has been written from scratch with
* additional optimizations in place.
*
* The library is free for all purposes without any express
* guarantee it works.
*
* Tom St Denis, tomstdenis@gmail.com, http://libtom.org
*/
/* trim unused digits
*
* This is used to ensure that leading zero digits are
* trimed and the leading "used" digit will be non-zero
* Typically very fast. Also fixes the sign if there
* are no more leading digits
*/
void mp_clamp(mp_int* const a)
{
DEBUG_CODE(mp_debug__check_int__light(a);)
// decrease used while the most significant digit is zero.
const mp_digit* p=(a->dp + a->used);
for(;;)
{
if(p == a->dp)
{
a->used = 0;
a->sign = MP_ZPOS;
DEBUG_CODE(mp_debug__check_int__total(a);)
return;
}//if
const mp_digit* const newP = (p - 1);
if((*newP) != 0)
break;
p = newP;
}//for[ever]
assert(p != a->dp);
assert(p >= a->dp);
assert(p <= (a->dp + a->used));
a->used = (p - a->dp);
DEBUG_CODE(mp_debug__check_int__total(a);)
}//mp_clamp
////////////////////////////////////////////////////////////////////////////////
}/*nms set01*/}/*nms libtommath*/}/*nms external*/}/*nms ibp*/
| 24.581081
| 94
| 0.601979
|
dmitry-lipetsk
|
42768a0b65d6e98e69e348eb23106fa73cff1c2a
| 741
|
cc
|
C++
|
base/at_exit.cc
|
Arpan-2109/caroline
|
23aba9ac9a35697c02358aeb88ed121d3d97a99c
|
[
"MIT"
] | 1
|
2017-07-27T15:08:19.000Z
|
2017-07-27T15:08:19.000Z
|
base/at_exit.cc
|
Arpan-2109/caroline
|
23aba9ac9a35697c02358aeb88ed121d3d97a99c
|
[
"MIT"
] | null | null | null |
base/at_exit.cc
|
Arpan-2109/caroline
|
23aba9ac9a35697c02358aeb88ed121d3d97a99c
|
[
"MIT"
] | 1
|
2020-10-01T08:46:10.000Z
|
2020-10-01T08:46:10.000Z
|
// Copyright (c) 2014 The Caroline authors. All rights reserved.
// Use of this source file is governed by a MIT license that can be found in the
// LICENSE file.
// @author Aleksandr Derbenev <13alexac@gmail.com>
#include "base/at_exit.h"
namespace base {
AtExitManager* AtExitManager::instance_ = nullptr;
AtExitManager::AtExitManager()
: previous_instance_(instance_) {
instance_ = this;
}
AtExitManager::~AtExitManager() {
for (; !callbacks_.empty(); callbacks_.pop())
callbacks_.top()();
instance_ = previous_instance_;
}
// static
AtExitManager* AtExitManager::GetInstance() {
return instance_;
}
void AtExitManager::RegisterCallback(AtExitCallback callback) {
callbacks_.push(callback);
}
} // namespace base
| 22.454545
| 80
| 0.735493
|
Arpan-2109
|
428076b9e4ff076bd95fb24def4b4ac59b016772
| 2,905
|
inl
|
C++
|
Engine/Core/Headers/Molten/Renderer/Shader/Visual/VisualShaderConstant.inl
|
jimmiebergmann/CurseEngine
|
74a0502e36327f893c8e4f3e7cbe5b9d38fbe194
|
[
"MIT"
] | 2
|
2019-11-11T21:17:14.000Z
|
2019-11-11T22:07:26.000Z
|
Engine/Core/Headers/Molten/Renderer/Shader/Visual/VisualShaderConstant.inl
|
jimmiebergmann/CurseEngine
|
74a0502e36327f893c8e4f3e7cbe5b9d38fbe194
|
[
"MIT"
] | null | null | null |
Engine/Core/Headers/Molten/Renderer/Shader/Visual/VisualShaderConstant.inl
|
jimmiebergmann/CurseEngine
|
74a0502e36327f893c8e4f3e7cbe5b9d38fbe194
|
[
"MIT"
] | 1
|
2020-04-05T03:50:57.000Z
|
2020-04-05T03:50:57.000Z
|
/*
* MIT License
*
* Copyright (c) 2021 Jimmie Bergmann
*
* 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.
*
*/
namespace Molten::Shader::Visual
{
// Constant implementations.
template<typename TDataType>
OutputPin<TDataType>& Constant<TDataType>::GetOutput()
{
return m_output;
}
template<typename TDataType>
const OutputPin<TDataType>& Constant<TDataType>::GetOutput() const
{
return m_output;
}
template<typename TDataType>
VariableDataType Constant<TDataType>::GetDataType() const
{
return VariableTrait<TDataType>::dataType;
}
template<typename TDataType>
size_t Constant<TDataType>::GetOutputPinCount() const
{
return 1;
}
template<typename TDataType>
Pin* Constant<TDataType>::GetOutputPin(const size_t index)
{
if (index >= 1)
{
return nullptr;
}
return &m_output;
}
template<typename TDataType>
const Pin* Constant<TDataType>::GetOutputPin(const size_t index) const
{
if (index >= 1)
{
return nullptr;
}
return &m_output;
}
template<typename TDataType>
std::vector<Pin*> Constant<TDataType>::GetOutputPins()
{
return { &m_output };
}
template<typename TDataType>
std::vector<const Pin*> Constant<TDataType>::GetOutputPins() const
{
return { &m_output };
}
template<typename TDataType>
const TDataType& Constant<TDataType>::GetValue() const
{
return m_value;
}
template<typename TDataType>
void Constant<TDataType>::SetValue(const TDataType& value)
{
m_value = value;
}
template<typename TDataType>
Constant<TDataType>::Constant(Script& script, const TDataType& value) :
ConstantBase(script),
m_value(value),
m_output(*this)
{}
}
| 28.203883
| 80
| 0.67642
|
jimmiebergmann
|
4282699a05745276022b2dfd0b68112ee07565d8
| 2,255
|
cpp
|
C++
|
src/Hola_Common/src/Base/ShaderCompiler.cpp
|
dfnzhc/Hola
|
d0fd46e9966baafd03c994e49efaa3dd8057309e
|
[
"MIT"
] | null | null | null |
src/Hola_Common/src/Base/ShaderCompiler.cpp
|
dfnzhc/Hola
|
d0fd46e9966baafd03c994e49efaa3dd8057309e
|
[
"MIT"
] | null | null | null |
src/Hola_Common/src/Base/ShaderCompiler.cpp
|
dfnzhc/Hola
|
d0fd46e9966baafd03c994e49efaa3dd8057309e
|
[
"MIT"
] | null | null | null |
#include "stdafx.h"
#include "ShaderCompiler.h"
#include "Misc/Misc.h"
//--------------------------------------------------------------------------------------
// 哈希一串源代码,并在它的 #include 文件中递归
//--------------------------------------------------------------------------------------
size_t HashShaderString(const char *pRootDir, const char *pShader, size_t hash)
{
hash = Hash(pShader, strlen(pShader), hash);
const char *pch = pShader;
while (*pch != 0)
{
if (*pch == '/') // parse comments
{
pch++;
if (*pch != 0 && *pch == '/')
{
pch++;
while (*pch != 0 && *pch != '\n')
pch++;
}
else if (*pch != 0 && *pch == '*')
{
pch++;
while ( (*pch != 0 && *pch != '*') && (*(pch+1) != 0 && *(pch+1) != '/'))
pch++;
}
}
else if (*pch == '#') // parse #include
{
pch++;
const char include[] = "include";
int i = 0;
while ((*pch!= 0) && *pch == include[i])
{
pch++;
i++;
}
if (i == strlen(include))
{
while (*pch != 0 && *pch == ' ')
pch++;
if (*pch != 0 && *pch == '\"')
{
pch++;
const char *pName = pch;
while (*pch != 0 && *pch != '\"')
pch++;
char includeName[1024];
strcpy_s<1024>(includeName, pRootDir);
strncat_s<1024>(includeName, pName, pch - pName);
pch++;
char *pShaderCode = NULL;
if (ReadFile(includeName, &pShaderCode, NULL, false))
{
hash = HashShaderString(pRootDir, pShaderCode, hash);
free(pShaderCode);
}
}
}
}
else
{
pch++;
}
}
return hash;
}
| 29.285714
| 89
| 0.2949
|
dfnzhc
|
4285112808835de0c0cd70175a6e99999ba1b8b8
| 1,852
|
cpp
|
C++
|
modules/task_2/vodeneev_m_broadcast/ops_mpi.cpp
|
Vodeneev/pp_2020_autumn_math
|
9b7e5ec56e09474c9880810a6124e3e416bb7e16
|
[
"BSD-3-Clause"
] | null | null | null |
modules/task_2/vodeneev_m_broadcast/ops_mpi.cpp
|
Vodeneev/pp_2020_autumn_math
|
9b7e5ec56e09474c9880810a6124e3e416bb7e16
|
[
"BSD-3-Clause"
] | null | null | null |
modules/task_2/vodeneev_m_broadcast/ops_mpi.cpp
|
Vodeneev/pp_2020_autumn_math
|
9b7e5ec56e09474c9880810a6124e3e416bb7e16
|
[
"BSD-3-Clause"
] | null | null | null |
// Copyright 2020 Mikhail Vodeneev
#include <mpi.h>
#include <math.h>
#include <random>
#include <ctime>
#include <vector>
#include <algorithm>
#include "../../../modules/test_tasks/test_mpi/ops_mpi.h"
int Bcast(void* buffer, int count,
MPI_Datatype datatype, int root, MPI_Comm comm) {
int size, rank;
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
if (root > size) {
printf("Error");
return 1;
}
if ((size == 1) && (root != 0)) {
printf("Error");
return 1;
}
if (root != 0) {
if (rank == root) {
MPI_Send(buffer, count, datatype, 0, 0, MPI_COMM_WORLD);
} else if (rank == 0) {
MPI_Status status;
MPI_Recv(buffer, count, datatype, root, 0, MPI_COMM_WORLD, &status);
}
}
if ((size == 1) && (root != 0)) {
printf("Error");
return 1;
}
if (size == 1) {
return 0;
}
if (size == 2) {
if (rank == 0) {
MPI_Send(buffer, count, datatype, 1, 0, MPI_COMM_WORLD);
} else {
MPI_Status status;
MPI_Recv(buffer, count, datatype, 0, 0, MPI_COMM_WORLD, &status);
}
return 0;
}
if (rank == 0) {
MPI_Send(buffer, count, datatype, 1, 0, MPI_COMM_WORLD);
MPI_Send(buffer, count, datatype, 2, 0, MPI_COMM_WORLD);
} else {
MPI_Status status;
MPI_Recv(buffer, count, datatype,
(rank - 1) / 2, 0, MPI_COMM_WORLD, &status);
if (2 * rank + 1 < size) {
MPI_Send(buffer, count, datatype,
2 * rank + 1, 0, MPI_COMM_WORLD);
}
if (2 * rank + 2 < size) {
MPI_Send(buffer, count, datatype, 2 * rank + 2, 0, MPI_COMM_WORLD);
}
}
return 0;
}
| 25.369863
| 80
| 0.513499
|
Vodeneev
|
42875ddf68b8e6e231f1c34c497127cff79de585
| 3,214
|
hpp
|
C++
|
src/Engine/Renderer/Renderers/DebugRender.hpp
|
david49az/Radium-Engine
|
2600039e5c0658057b8b35f79222a332feceb026
|
[
"Apache-2.0"
] | 1
|
2021-02-03T17:47:04.000Z
|
2021-02-03T17:47:04.000Z
|
src/Engine/Renderer/Renderers/DebugRender.hpp
|
david49az/Radium-Engine
|
2600039e5c0658057b8b35f79222a332feceb026
|
[
"Apache-2.0"
] | null | null | null |
src/Engine/Renderer/Renderers/DebugRender.hpp
|
david49az/Radium-Engine
|
2600039e5c0658057b8b35f79222a332feceb026
|
[
"Apache-2.0"
] | null | null | null |
#pragma once
#include <Engine/RaEngine.hpp>
#include <memory>
#include <vector>
#include <Core/Containers/VectorArray.hpp>
#include <Core/Types.hpp>
#include <Core/Utils/Color.hpp>
#include <Core/Utils/Singleton.hpp>
namespace Ra {
namespace Engine {
class ShaderProgram;
class AttribArrayDisplayable;
} // namespace Engine
} // namespace Ra
namespace Ra {
namespace Engine {
/** This allow to draw debug objects.
* @todo : port this to a more Radium-style code
*/
class RA_ENGINE_API DebugRender final
{
RA_SINGLETON_INTERFACE( DebugRender );
public:
DebugRender();
~DebugRender();
void initialize();
void render( const Core::Matrix4& view, const Core::Matrix4& proj );
void
addLine( const Core::Vector3& from, const Core::Vector3& to, const Core::Utils::Color& color );
void addPoint( const Core::Vector3& p, const Core::Utils::Color& color );
void addPoints( const Core::Vector3Array& p, const Core::Utils::Color& color );
void addPoints( const Core::Vector3Array& p, const Core::Vector4Array& colors );
void addMesh( const std::shared_ptr<AttribArrayDisplayable>& mesh,
const Core::Transform& transform = Core::Transform::Identity() );
// Shortcuts
void addCross( const Core::Vector3& position, Scalar size, const Core::Utils::Color& color );
void addSphere( const Core::Vector3& center, Scalar radius, const Core::Utils::Color& color );
void addCircle( const Core::Vector3& center,
const Core::Vector3& normal,
Scalar radius,
const Core::Utils::Color& color );
void addFrame( const Core::Transform& transform, Scalar size );
void addTriangle( const Core::Vector3& p0,
const Core::Vector3& p1,
const Core::Vector3& p2,
const Core::Utils::Color& color );
void addAABB( const Core::Aabb& box, const Core::Utils::Color& color );
void addOBB( const Core::Aabb& box,
const Core::Transform& transform,
const Core::Utils::Color& color );
private:
struct Line {
Line( const Core::Vector3& la, const Core::Vector3& lb, const Core::Utils::Color& lcol ) :
a {la}, b {lb}, col {lcol} {}
Core::Vector3 a, b;
Core::Utils::Color col;
};
struct Point {
Core::Vector3 p;
Core::Vector3 c;
};
struct DbgMesh {
std::shared_ptr<AttribArrayDisplayable> mesh;
Core::Transform transform;
};
void renderLines( const Core::Matrix4f& view, const Core::Matrix4f& proj );
void renderPoints( const Core::Matrix4f& view, const Core::Matrix4f& proj );
void renderMeshes( const Core::Matrix4f& view, const Core::Matrix4f& proj );
private:
// these shaders are owned by the manager, just keep a raw copy, since the
// manager is available during whole execution.
const ShaderProgram* m_lineProg {nullptr};
const ShaderProgram* m_pointProg {nullptr};
const ShaderProgram* m_meshProg {nullptr};
std::vector<Line> m_lines;
std::vector<DbgMesh> m_meshes;
std::vector<Point> m_points;
};
} // namespace Engine
} // namespace Ra
| 30.903846
| 99
| 0.645924
|
david49az
|
4289fc2aa5fd2402e2a86bec3fa4524c70cf973e
| 4,556
|
cpp
|
C++
|
rtc_stack/utils/Worker.cpp
|
anjisuan783/media_lib
|
c09c7d48f495a803df79e39cf837bbcb1320ceb8
|
[
"MIT"
] | 9
|
2022-01-07T03:10:45.000Z
|
2022-03-31T03:29:02.000Z
|
rtc_stack/utils/Worker.cpp
|
anjisuan783/mia
|
c09c7d48f495a803df79e39cf837bbcb1320ceb8
|
[
"MIT"
] | 16
|
2021-12-17T08:32:57.000Z
|
2022-03-10T06:16:14.000Z
|
rtc_stack/utils/Worker.cpp
|
anjisuan783/media_lib
|
c09c7d48f495a803df79e39cf837bbcb1320ceb8
|
[
"MIT"
] | 1
|
2022-02-21T15:47:21.000Z
|
2022-02-21T15:47:21.000Z
|
#include "./Worker.h"
#include <algorithm>
#include <memory>
#include "myrtc/api/default_task_queue_factory.h"
#include "myrtc/rtc_base/to_queued_task.h"
namespace wa {
bool ScheduledTaskReference::isCancelled() {
return cancelled_;
}
void ScheduledTaskReference::cancel() {
cancelled_ = true;
}
////////////////////////////////////////////////////////////////////////////////
//Worker
////////////////////////////////////////////////////////////////////////////////
Worker::Worker(webrtc::TaskQueueFactory* factory, int id, std::shared_ptr<Clock> the_clock)
: factory_(factory),
id_(id),
clock_{the_clock}
{ }
void Worker::task(Task t) {
task_queue_->PostTask(webrtc::ToQueuedTask(std::forward<Task>(t)));
}
void Worker::task(Task t, const rtc::Location& r) {
task_queue_->PostTask(webrtc::ToQueuedTask(std::forward<Task>(t), r));
}
void Worker::start(const std::string& name) {
auto promise = std::make_shared<std::promise<void>>();
start(promise, name);
promise->get_future().wait();
}
void Worker::start(std::shared_ptr<std::promise<void>> start_promise,
const std::string& name) {
auto pQueue = factory_->CreateTaskQueue(name,
webrtc::TaskQueueFactory::Priority::NORMAL);
task_queue_base_ = pQueue.get();
task_queue_ = std::move(std::make_unique<rtc::TaskQueue>(std::move(pQueue)));
task_queue_->PostTask([start_promise] {
start_promise->set_value();
});
}
void Worker::close() {
closed_ = true;
task_queue_ = nullptr;
task_queue_base_ = nullptr;
}
std::shared_ptr<ScheduledTaskReference>
Worker::scheduleFromNow(Task t, duration delta) {
rtc::Location l;
return scheduleFromNow(std::forward<Task>(t), delta, l);
}
std::shared_ptr<ScheduledTaskReference>
Worker::scheduleFromNow(Task t, duration delta, const rtc::Location& l) {
auto id = std::make_shared<ScheduledTaskReference>();
task_queue_->PostDelayedTask(
webrtc::ToQueuedTask(std::forward<std::function<void()>>(
[f = std::forward<Task>(t), id]() {
if (!id->isCancelled()) {
f();
}
}), l),
ClockUtils::durationToMs(delta));
return id;
}
void Worker::scheduleEvery(ScheduledTask f, duration period) {
rtc::Location l;
scheduleEvery(std::forward<ScheduledTask>(f), period, period, l);
}
void Worker::scheduleEvery(ScheduledTask f,
duration period, const rtc::Location& l) {
scheduleEvery(std::forward<ScheduledTask>(f), period, period, l);
}
void Worker::scheduleEvery(ScheduledTask&& t,
duration period, duration next_delay, const rtc::Location& location) {
time_point start = clock_->now();
scheduleFromNow([this_ptr = shared_from_this(),
start, period, next_delay,
f = std::forward<ScheduledTask>(t), clock = clock_, location]() {
if (f()) {
duration clock_skew = clock->now() - start - next_delay;
duration delay = std::max(period - clock_skew, duration(0));
this_ptr->scheduleEvery(
std::forward<ScheduledTask>(const_cast<ScheduledTask&>(f)),
period, delay, location);
}
}, next_delay, location);
}
void Worker::unschedule(std::shared_ptr<ScheduledTaskReference> id) {
id->cancel();
}
////////////////////////////////////////////////////////////////////////////////
//ThreadPool
////////////////////////////////////////////////////////////////////////////////
static std::unique_ptr<webrtc::TaskQueueFactory> g_task_queue_factory =
webrtc::CreateDefaultTaskQueueFactory();
ThreadPool::ThreadPool(unsigned int num_workers) {
workers_.reserve(num_workers);
for (unsigned int index = 0; index < num_workers; ++index) {
workers_.push_back(
std::make_shared<Worker>(g_task_queue_factory.get(), index));
}
}
ThreadPool::~ThreadPool() {
close();
}
std::shared_ptr<Worker> ThreadPool::getLessUsedWorker() {
std::shared_ptr<Worker> chosen_worker = workers_.front();
for (auto worker : workers_) {
if (chosen_worker.use_count() > worker.use_count()) {
chosen_worker = worker;
}
}
return chosen_worker;
}
void ThreadPool::start(const std::string& name) {
std::vector<std::shared_ptr<std::promise<void>>> promises(workers_.size());
int index = 0;
for (auto worker : workers_) {
promises[index] = std::make_shared<std::promise<void>>();
worker->start(promises[index++], name);
}
for (auto promise : promises) {
promise->get_future().wait();
}
}
void ThreadPool::close() {
for (auto worker : workers_) {
worker->close();
}
}
} //namespace wa
| 28.298137
| 92
| 0.628402
|
anjisuan783
|
428b536e834ccef6abc90d9128f9c7ae8b192e75
| 15,383
|
cpp
|
C++
|
test/unit_tests/test_duration.cpp
|
slavslav/sydevs
|
3106c38d327be652638bd8bd75dbe02c938800e5
|
[
"Apache-2.0"
] | 26
|
2018-04-24T23:47:58.000Z
|
2021-05-27T16:56:27.000Z
|
test/unit_tests/test_duration.cpp
|
slavslav/sydevs
|
3106c38d327be652638bd8bd75dbe02c938800e5
|
[
"Apache-2.0"
] | 2
|
2018-08-13T23:49:55.000Z
|
2020-03-27T21:09:47.000Z
|
test/unit_tests/test_duration.cpp
|
slavslav/sydevs
|
3106c38d327be652638bd8bd75dbe02c938800e5
|
[
"Apache-2.0"
] | 9
|
2018-08-29T20:12:31.000Z
|
2021-06-09T12:08:51.000Z
|
#include <catch2/catch.hpp>
#include <sydevs/core/string_builder.h>
#include <sydevs/core/quantity.h>
namespace sydevs {
TEST_CASE("test duration constructors")
{
CHECK(!duration().valid());
CHECK(duration(0).multiplier() == 0);
CHECK(duration(0).precision() == unit);
CHECK(duration(100).multiplier() == 100);
CHECK(duration(100).precision() == unit);
CHECK(duration(-100).multiplier() == -100);
CHECK(duration(-100).precision() == unit);
CHECK(duration(100, nano).multiplier() == 100);
CHECK(duration(100, nano).precision() == nano);
CHECK(duration(-100, nano).multiplier() == -100);
CHECK(duration(-100, nano).precision() == nano);
CHECK(duration(quantity_limit - 1).multiplier() == quantity_limit - 1);
CHECK(duration(quantity_limit - 1).finite());
CHECK(!duration(quantity_limit).finite());
CHECK(!duration(quantity_limit + 1).finite());
CHECK(duration(1 - quantity_limit).multiplier() == 1 - quantity_limit);
CHECK(duration(1 - quantity_limit).finite());
CHECK(!duration(quantity_limit).finite());
CHECK(!duration(-1 - quantity_limit).finite());
}
TEST_CASE("test duration literals")
{
CHECK(0_s == duration(0));
CHECK((0_s).multiplier() == 0);
CHECK((0_s).precision() == unit);
CHECK(0_us == duration(0));
CHECK((0_us).multiplier() == 0);
CHECK((0_us).precision() == micro);
CHECK(0_Ms == duration(0));
CHECK((0_Ms).multiplier() == 0);
CHECK((0_Ms).precision() == mega);
CHECK(1_s == duration(1, unit));
CHECK(1_min == duration(60, unit));
CHECK(1_hr == duration(3600, unit));
CHECK(1_day == duration(86400, unit));
CHECK(1_yr == duration(31536000, unit));
CHECK(1_ys == duration(1, yocto));
CHECK(1_zs == duration(1, zepto));
CHECK(1_as == duration(1, atto));
CHECK(1_fs == duration(1, femto));
CHECK(1_ps == duration(1, pico));
CHECK(1_ns == duration(1, nano));
CHECK(1_us == duration(1, micro));
CHECK(1_ms == duration(1, milli));
CHECK(1_s == duration(1, unit));
CHECK(1_ks == duration(1, kilo));
CHECK(1_Ms == duration(1, mega));
CHECK(1_Gs == duration(1, giga));
CHECK(1_Ts == duration(1, tera));
CHECK(1_Ps == duration(1, peta));
CHECK(1_Es == duration(1, exa));
CHECK(1_Zs == duration(1, zetta));
CHECK(1_Ys == duration(1, yotta));
CHECK(5_min == duration(300, unit));
CHECK(7_day == duration(604800, unit));
CHECK(999999999999999_s == duration(999999999999999, unit));
CHECK(999999999999999_us == duration(999999999999999, micro));
CHECK(1000000000000000_s == duration::inf());
CHECK(1000000000000000_us == duration::inf());
CHECK(-999999999999999_s == duration(-999999999999999, unit));
CHECK(-999999999999999_us == duration(-999999999999999, micro));
CHECK(-1000000000000000_s == -duration::inf());
CHECK(-1000000000000000_us == -duration::inf());
}
TEST_CASE("test non-operator duration methods with duration return values")
{
CHECK((5_s).refined().multiplier() == 5000000000000);
CHECK((5_s).refined().precision() == pico);
CHECK((5_s).refined().fixed() == false);
CHECK((5_s).coarsened().multiplier() == 5);
CHECK((5_s).coarsened().precision() == unit);
CHECK((5_s).coarsened().fixed() == false);
CHECK((5_s).refined().coarsened().multiplier() == 5);
CHECK((5_s).refined().coarsened().precision() == unit);
CHECK((5_s).refined().coarsened().fixed() == false);
CHECK((5_s).fixed_at(nano).multiplier() == 5000000000);
CHECK((5_s).fixed_at(nano).precision() == nano);
CHECK((5_s).fixed_at(nano).fixed() == true);
CHECK((83000_us).fixed_at(milli).multiplier() == 83);
CHECK((83000_us).fixed_at(milli).precision() == milli);
CHECK((83000_us).fixed_at(milli).fixed() == true);
CHECK((83123_us).fixed_at(milli).multiplier() == 83);
CHECK((83123_us).fixed_at(milli).precision() == milli);
CHECK((83123_us).fixed_at(milli).fixed() == true);
CHECK((5_s).rescaled(nano).multiplier() == 5000000000);
CHECK((5_s).rescaled(nano).precision() == nano);
CHECK((5_s).rescaled(nano).fixed() == false);
CHECK((83000_us).rescaled(milli).multiplier() == 83);
CHECK((83000_us).rescaled(milli).precision() == milli);
CHECK((83000_us).rescaled(milli).fixed() == false);
CHECK((83123_us).rescaled(milli).multiplier() == 83);
CHECK((83123_us).rescaled(milli).precision() == milli);
CHECK((83123_us).rescaled(milli).fixed() == false);
CHECK((83000_us).fixed_at(milli).unfixed().multiplier() == 83);
CHECK((83000_us).fixed_at(milli).unfixed().precision() == milli);
CHECK((83000_us).fixed_at(milli).unfixed().fixed() == false);
CHECK((83123_us).fixed_at(milli).unfixed().multiplier() == 83);
CHECK((83123_us).fixed_at(milli).unfixed().precision() == milli);
CHECK((83123_us).fixed_at(milli).unfixed().fixed() == false);
}
TEST_CASE("test duration base-1000 floating-point addition")
{
CHECK((3_hr + 45_s) == 10845_s);
CHECK((3_hr + 45_s).precision() == unit);
CHECK((3_hr + 45_s).refined() == 10845000000000_ns);
CHECK((3_hr + 45_s).refined().precision() == nano);
CHECK((3_hr + 45_s).coarsened() == 10845_s);
CHECK((3_hr + 45_s).coarsened().precision() == unit);
CHECK((3_hr + 45_s).refined().coarsened() == 10845_s);
CHECK((3_hr + 45_s).refined().coarsened().precision() == unit);
CHECK(((1_s).rescaled(milli) + (1_s).rescaled(micro)) == 2000000_us);
CHECK(((1_s).rescaled(milli) + (1_s).rescaled(micro)).precision() == micro);
CHECK(!((1_s).fixed_at(milli) + (1_s).fixed_at(micro)).valid());
CHECK(((47_ms).rescaled(pico) + 1_yr) == 31536000047000_us);
CHECK(((47_ms).rescaled(pico) + 1_yr).precision() == micro);
CHECK(((47_ms).rescaled(femto) + 1_yr) == 31536000047000_us);
CHECK(((47_ms).rescaled(femto) + 1_yr).precision() == micro);
CHECK((47_ms).rescaled(atto) == +duration::inf());
CHECK(((47_ms).rescaled(atto) + 1_yr) == +duration::inf());
CHECK((1_yr + (47_ms).rescaled(atto)) == +duration::inf());
CHECK(((47_us).rescaled(atto) + 1_yr) == 31536000000047_us);
CHECK(((47_us).rescaled(atto) + 1_yr).precision() == micro);
CHECK((1_yr + (47_us).rescaled(atto)) == 31536000000047_us);
CHECK((1_yr + (47_us).rescaled(atto)).precision() == micro);
CHECK((500000000000000_Ms + 500000000000000_Ms) == 1000000000000_Gs);
CHECK((500000000000000_Ms + 500000000000000_Ms).precision() == giga);
CHECK(((500000000000000_Ms).fixed_at(mega) + (500000000000000_Ms).fixed_at(mega)) == +duration::inf());
CHECK(((500000000000000_Ms).fixed_at(mega) + (500000000000000_Ms).fixed_at(mega)).precision() == unit);
}
TEST_CASE("test duration negation base-1000 floating-point subtraction")
{
CHECK(-1_min == -60_s);
CHECK((-1_min).precision() == unit);
CHECK((5_min - 1_hr) == -3300_s);
CHECK((5_min - 1_hr).precision() == unit);
CHECK(((47_ms).rescaled(atto) - 1_yr) == +duration::inf());
CHECK((1_yr - (47_ms).rescaled(atto)) == -duration::inf());
CHECK(((47_us).rescaled(atto) - 1_yr) == -31535999999953_us);
CHECK(((47_us).rescaled(atto) - 1_yr).precision() == micro);
CHECK((1_yr - (47_us).rescaled(atto)) == +31535999999953_us);
CHECK((1_yr - (47_us).rescaled(atto)).precision() == micro);
CHECK((-duration::inf()) == -duration::inf());
CHECK(!(duration::inf() - duration::inf()).valid());
CHECK((1_s - 1_s).precision() == unit);
CHECK((1_ms - 1_ms).precision() == milli);
CHECK((1_us - 1_us).precision() == micro);
CHECK((1_ks - 1_ks).precision() == kilo);
}
TEST_CASE("test duration multiplication by number")
{
CHECK((1_hr*3) == 10800_s);
CHECK((1_hr*3).precision() == unit);
CHECK((3*1_hr) == 10800_s);
CHECK((3*1_hr).precision() == unit);
CHECK((1_hr*1000000000000000.0) == 3600000000000_Ms);
CHECK((1_hr*1000000000000000.0).precision() == mega);
CHECK((1_hr*0.000000000000001) == 3600000000000_ys);
CHECK((1_hr*0.000000000000001).precision() == yocto);
CHECK(((1_hr).fixed_at(unit)*3) == 10800_s);
CHECK(((1_hr).fixed_at(unit)*3).precision() == unit);
CHECK(((1_hr).fixed_at(unit)*1000000000000000.0) == +duration::inf());
CHECK(((1_hr).fixed_at(unit)*0.000000000000001) == 0_s);
CHECK(((1_hr).fixed_at(unit)*0.000000000000001).precision() == unit);
}
TEST_CASE("test duration division by number")
{
CHECK((1_hr/3) == 1200_s);
CHECK((1_hr/3).precision() == unit);
CHECK((1_hr/1000000000000000.0) == 3600_fs);
CHECK((1_hr/1000000000000000.0).precision() == femto);
CHECK((1_hr/0.000000000000001) == 3600000000000_Ms);
CHECK((1_hr/0.000000000000001).precision() == mega);
CHECK(((1_hr).fixed_at(unit)/3) == 1200_s);
CHECK(((1_hr).fixed_at(unit)/3).precision() == unit);
CHECK(((1_hr).fixed_at(unit)/1000000000000000.0) == 0_s);
CHECK(((1_hr).fixed_at(unit)/1000000000000000.0).precision() == unit);
CHECK(((1_hr).fixed_at(unit)/0.000000000000001) == +duration::inf());
}
TEST_CASE("test duration-duration division")
{
CHECK((1_hr/1_min) == 60);
CHECK((1_hr/2_s) == 1800);
CHECK((1_min/1_hr) == Approx(0.0166667));
CHECK((5_s/1_ns) == Approx(5e+09));
CHECK((1_ns/1_s) == Approx(1e-09));
}
TEST_CASE("test duration-duration comparisons")
{
CHECK((1_ns == 1_s) == false);
CHECK((1_s == 1_ns) == false);
CHECK((1_ns == 1_ns) == true);
CHECK((1_ns != 1_s) == true);
CHECK((1_s != 1_ns) == true);
CHECK((1_ns != 1_ns) == false);
CHECK((1_ns < 1_s) == true);
CHECK((1_s < 1_ns) == false);
CHECK((1_ns < 1_ns) == false);
CHECK((1_ns > 1_s) == false);
CHECK((1_s > 1_ns) == true);
CHECK((1_ns > 1_ns) == false);
CHECK((1_ns <= 1_s) == true);
CHECK((1_s <= 1_ns) == false);
CHECK((1_ns <= 1_ns) == true);
CHECK((1_ns >= 1_s) == false);
CHECK((1_s >= 1_ns) == true);
CHECK((1_ns >= 1_ns) == true);
}
TEST_CASE("test duration add/subtract/multiply/divide assignment operations")
{
auto dt = 1_hr;
SECTION("add assignment") {
CHECK((dt += 1_min) == 3660_s);
CHECK(dt == 3660_s);
CHECK(dt.precision() == unit);
}
SECTION("subtract assignment") {
CHECK((dt -= 1_min) == 3540_s);
CHECK(dt == 3540_s);
CHECK(dt.precision() == unit);
}
SECTION("multiply assignment") {
CHECK((dt *= 3.14159) == 11309724_ms);
CHECK(dt == 11309724_ms);
CHECK(dt.precision() == milli);
}
SECTION("divide assignment") {
CHECK((dt /= 4) == 900_s);
CHECK(dt == 900_s);
CHECK(dt.precision() == unit);
}
}
TEST_CASE("test max_duration")
{
CHECK(duration::max(unit) == 999999999999999_s);
CHECK(duration::max(yocto) == 999999999999999_ys);
}
TEST_CASE("test duration addition and subtraction with both fixed and unfixed operands")
{
CHECK(((1_s).fixed_at(micro) + (1_s).rescaled(nano)) == 2000000_us);
CHECK(((1_s).fixed_at(micro) + (1_s).rescaled(nano)).precision() == micro);
CHECK(((1_s).fixed_at(nano) + (1_s).rescaled(micro)) == 2000000000_ns);
CHECK(((1_s).fixed_at(nano) + (1_s).rescaled(micro)).precision() == nano);
CHECK(((1_s).rescaled(micro) + (1_s).fixed_at(nano)) == 2000000000_ns);
CHECK(((1_s).rescaled(micro) + (1_s).fixed_at(nano)).precision() == nano);
CHECK(((1_s).rescaled(nano) + (1_s).fixed_at(micro)) == 2000000_us);
CHECK(((1_s).rescaled(nano) + (1_s).fixed_at(micro)).precision() == micro);
CHECK(((2_s).fixed_at(micro) - (1_s).rescaled(nano)) == 1000000_us);
CHECK(((2_s).fixed_at(micro) - (1_s).rescaled(nano)).precision() == micro);
CHECK(((2_s).fixed_at(nano) - (1_s).rescaled(micro)) == 1000000000_ns);
CHECK(((2_s).fixed_at(nano) - (1_s).rescaled(micro)).precision() == nano);
CHECK(((2_s).rescaled(micro) - (1_s).fixed_at(nano)) == 1000000000_ns);
CHECK(((2_s).rescaled(micro) - (1_s).fixed_at(nano)).precision() == nano);
CHECK(((2_s).rescaled(nano) - (1_s).fixed_at(micro)) == 1000000_us);
CHECK(((2_s).rescaled(nano) - (1_s).fixed_at(micro)).precision() == micro);
}
TEST_CASE("test duration with assorted operations")
{
CHECK((string_builder() << (2_s).fixed_at(unit) + (3_s).fixed_at(unit)).str() == "5_s");
CHECK((string_builder() << (2_s).fixed_at(unit) - (3_s).fixed_at(unit)).str() == "-1_s");
CHECK((string_builder() << 5*(100_s).fixed_at(unit)).str() == "500_s");
CHECK((string_builder() << (1.0/5.0)*(100_s).fixed_at(unit)).str() == "20_s");
CHECK((string_builder() << (100_s).fixed_at(unit)*(1.0/5.0)).str() == "20_s");
CHECK((string_builder() << (100_s).fixed_at(unit)/5.0).str() == "20_s");
CHECK((string_builder() << (100_s).fixed_at(unit)/8.0).str() == "13_s");
CHECK(2_s > 1000_ms);
CHECK(2_s < 3000_ms);
CHECK(-8_ps < -7_ps);
CHECK(1_s == 1000_ms);
CHECK(1_s == 1000000_us);
CHECK(1000_ms == 1000000_us);
CHECK(((500_ms).fixed_at(milli) + (500_ms).fixed_at(milli)) == 1_s);
CHECK((string_builder() << (500_ms).fixed_at(milli) + (500_ms).fixed_at(milli)).str() == "1000_ms");
CHECK((string_builder() << (999999999999999_Ms).fixed_at(mega) + (1_Ms).fixed_at(mega)).str() == "duration::inf()");
CHECK((string_builder() << -1000000*(1000000000_fs).fixed_at(femto)).str() == "-duration::inf()");
CHECK((string_builder() << 3_s + 475_ms).str() == "3475_ms");
CHECK((string_builder() << 1_ks + 1_us).str() == "1000000001_us");
CHECK((string_builder() << 500_ps - 1_ns).str() == "-500_ps");
CHECK((string_builder() << (1.0/3.0)*(1_s)).str() == "333333333333333_fs");
CHECK((string_builder() << (1.0/3.0)*(1000_ms)).str() == "333333333333333_fs");
CHECK((string_builder() << 1000_ms/3.0).str() == "333333333333333_fs");
CHECK((string_builder() << (1.0/3.0)*(1000000_us)).str() == "333333333333333_fs");
CHECK((string_builder() << (999999999999999_Ms) + (1_Ms)).str() == "1000000000000_Gs");
CHECK((string_builder() << -1000000*(1000000000_fs)).str() == "-1000000000000_ps");
CHECK((10_ms/250_us) == Approx(40.0));
CHECK(((-100_s)/900_s) == Approx(-1.0/9.0));
CHECK(((123_ms)/1_s) == Approx(0.123));
CHECK(((123_ms)/1_ms) == 123);
CHECK(((123_ms)/0_s) == std::numeric_limits<float64>::infinity());
CHECK(duration::inf().precision() == unit);
CHECK(-duration::inf().precision() == unit);
CHECK(duration(0, unit).precision() == unit);
CHECK(duration(0, milli).precision() == milli);
CHECK(duration(0, micro).precision() == micro);
CHECK((string_builder() << (1_min + 40_s).fixed_at(micro)/8.0).str() == "12500000_us");
CHECK((string_builder() << (1_min + 40_s).fixed_at(milli)/8.0).str() == "12500_ms");
CHECK((string_builder() << (1_min + 40_s).fixed_at(unit)/8.0).str() == "13_s");
CHECK((string_builder() << (1_min + 40_s).rescaled(micro)/8.0).str() == "12500000_us");
CHECK((string_builder() << (1_min + 40_s).rescaled(milli)/8.0).str() == "12500_ms");
CHECK((string_builder() << (1_min + 40_s).rescaled(unit)/8.0).str() == "12500_ms");
CHECK((string_builder() << (4_s + 10_ms)).str() == "4010_ms");
CHECK((string_builder() << (4_s + 10_ms)/4).str() == "1002500_us");
CHECK((string_builder() << (4_s + 10_ms).fixed_at(milli)/4).str() == "1003_ms");
CHECK((string_builder() << (4_s + 10_ms).fixed_at(micro)/4).str() == "1002500_us");
}
} // namespace
| 45.646884
| 120
| 0.62075
|
slavslav
|
429707e171dda3277947c6ae92f83456590edfbc
| 29,271
|
cc
|
C++
|
src/JobMaker.cc
|
ganibc/btcpool
|
360c90900922edab95c4759e8da7158dd12382b5
|
[
"MIT"
] | 1
|
2018-05-29T13:13:47.000Z
|
2018-05-29T13:13:47.000Z
|
src/JobMaker.cc
|
ganibc/btcpool
|
360c90900922edab95c4759e8da7158dd12382b5
|
[
"MIT"
] | null | null | null |
src/JobMaker.cc
|
ganibc/btcpool
|
360c90900922edab95c4759e8da7158dd12382b5
|
[
"MIT"
] | 1
|
2019-02-28T06:20:07.000Z
|
2019-02-28T06:20:07.000Z
|
/*
The MIT License (MIT)
Copyright (c) [2016] [BTC.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 "JobMaker.h"
#include <iostream>
#include <stdlib.h>
#include <glog/logging.h>
#include <librdkafka/rdkafka.h>
#include <hash.h>
#include <script/script.h>
#include <uint256.h>
#include <util.h>
#include <utilstrencodings.h>
#ifdef INCLUDE_BTC_KEY_IO_H //
#include <key_io.h> // IsValidDestinationString for bch is not in this file.
#endif
#include "utilities_js.hpp"
#include "Utils.h"
#include "BitcoinUtils.h"
/////////////////////////////////// JobMaker /////////////////////////////////
JobMaker::JobMaker(shared_ptr<JobMakerHandler> handler,
const string &kafkaBrokers,
const string& zookeeperBrokers) : handler_(handler),
running_(true),
zkLocker_(zookeeperBrokers.c_str()),
kafkaBrokers_(kafkaBrokers),
kafkaProducer_(kafkaBrokers.c_str(), handler->def().jobTopic_.c_str(), RD_KAFKA_PARTITION_UA)
{
}
JobMaker::~JobMaker() {
}
void JobMaker::stop() {
if (!running_) {
return;
}
running_ = false;
LOG(INFO) << "stop jobmaker";
}
bool JobMaker::init() {
/* get lock from zookeeper */
try {
if (handler_->def().zookeeperLockPath_.empty()) {
LOG(ERROR) << "zookeeper lock path is empty!";
return false;
}
zkLocker_.getLock(handler_->def().zookeeperLockPath_.c_str());
} catch(const ZookeeperException &zooex) {
LOG(ERROR) << zooex.what();
return false;
}
/* setup kafka producer */
{
map<string, string> options;
// set to 1 (0 is an illegal value here), deliver msg as soon as possible.
options["queue.buffering.max.ms"] = "1";
if (!kafkaProducer_.setup(&options)) {
LOG(ERROR) << "kafka producer setup failure";
return false;
}
if (!kafkaProducer_.checkAlive()) {
LOG(ERROR) << "kafka producer is NOT alive";
return false;
}
}
/* setup kafka consumers */
if (!handler_->initConsumerHandlers(kafkaBrokers_, kafkaConsumerHandlers_)) {
return false;
}
return true;
}
void JobMaker::consumeKafkaMsg(rd_kafka_message_t *rkmessage, JobMakerConsumerHandler &consumerHandler)
{
// check error
if (rkmessage->err)
{
if (rkmessage->err == RD_KAFKA_RESP_ERR__PARTITION_EOF)
{
// Reached the end of the topic+partition queue on the broker.
return;
}
LOG(ERROR) << "consume error for topic " << rd_kafka_topic_name(rkmessage->rkt)
<< "[" << rkmessage->partition << "] offset " << rkmessage->offset
<< ": " << rd_kafka_message_errstr(rkmessage);
if (rkmessage->err == RD_KAFKA_RESP_ERR__UNKNOWN_PARTITION ||
rkmessage->err == RD_KAFKA_RESP_ERR__UNKNOWN_TOPIC)
{
LOG(FATAL) << "consume fatal";
stop();
}
return;
}
// set json string
LOG(INFO) << "received " << consumerHandler.kafkaTopic_ << " message len: " << rkmessage->len;
string msg((const char *)rkmessage->payload, rkmessage->len);
if (consumerHandler.messageProcessor_(msg)) {
LOG(INFO) << "handleMsg returns true, new stratum job";
produceStratumJob();
}
}
void JobMaker::produceStratumJob() {
const string jobMsg = handler_->makeStratumJobMsg();
if (!jobMsg.empty()) {
LOG(INFO) << "new " << handler_->def().jobTopic_ << " job: " << jobMsg;
kafkaProducer_.produce(jobMsg.data(), jobMsg.size());
}
lastJobTime_ = time(nullptr);
// save send timestamp to file, for monitor system
if (!handler_->def().fileLastJobTime_.empty()) {
// TODO: fix Y2K38 issue
writeTime2File(handler_->def().fileLastJobTime_.c_str(), (uint32_t)lastJobTime_);
}
}
void JobMaker::runThreadKafkaConsume(JobMakerConsumerHandler &consumerHandler) {
const int32_t timeoutMs = 1000;
while (running_) {
rd_kafka_message_t *rkmessage;
rkmessage = consumerHandler.kafkaConsumer_->consumer(timeoutMs);
if (rkmessage == nullptr) /* timeout */ {
continue;
}
consumeKafkaMsg(rkmessage, consumerHandler);
/* Return message to rdkafka */
rd_kafka_message_destroy(rkmessage);
// Don't add any sleep() here.
// Kafka will not skip any message during your sleep(), you will received
// all messages from your beginning offset to the latest in any case.
// So sleep() will cause unexpected delay before consumer a new message.
// If the producer's speed is faster than the sleep() here, the consumption
// will be delayed permanently and the latest message will never be received.
// At the same time, there is not a busy waiting.
// KafkaConsumer::consumer(timeoutMs) will return after `timeoutMs` millisecond
// if no new messages. You can increase `timeoutMs` if you want.
}
}
void JobMaker::run() {
// running consumer threads
for (JobMakerConsumerHandler &consumerhandler : kafkaConsumerHandlers_)
{
kafkaConsumerWorkers_.push_back(std::make_shared<thread>(std::bind(&JobMaker::runThreadKafkaConsume, this, consumerhandler)));
}
// produce stratum job regularly
// the stratum job producing will also be triggered by consumer threads
while (running_) {
sleep(1);
if (time(nullptr) - lastJobTime_ > handler_->def().jobInterval_) {
produceStratumJob();
}
}
// wait consumer threads exit
for (auto pWorker : kafkaConsumerWorkers_) {
if (pWorker->joinable()) {
LOG(INFO) << "wait for worker " << pWorker->get_id() << "exiting";
pWorker->join();
LOG(INFO) << "worker exited";
}
}
}
////////////////////////////////GwJobMakerHandler//////////////////////////////////
bool GwJobMakerHandler::initConsumerHandlers(const string &kafkaBrokers, vector<JobMakerConsumerHandler> &handlers)
{
JobMakerConsumerHandler handler = {
/* kafkaTopic_ = */ def_.rawGwTopic_,
/* kafkaConsumer_ = */ std::make_shared<KafkaConsumer>(kafkaBrokers.c_str(), def_.rawGwTopic_.c_str(), 0/* partition */),
/* messageProcessor_ = */ std::bind(&GwJobMakerHandler::processMsg, this, std::placeholders::_1)
};
// init kafka consumer
{
map<string, string> consumerOptions;
consumerOptions["fetch.wait.max.ms"] = "5";
if (!handler.kafkaConsumer_->setup(RD_KAFKA_OFFSET_TAIL(1), &consumerOptions)) {
LOG(ERROR) << "kafka consumer " << def_.rawGwTopic_ << " setup failure";
return false;
}
if (!handler.kafkaConsumer_->checkAlive()) {
LOG(FATAL) << "kafka consumer " << def_.rawGwTopic_ << " is NOT alive";
return false;
}
}
handlers.push_back(handler);
return true;
}
////////////////////////////////JobMakerHandlerEth//////////////////////////////////
bool JobMakerHandlerEth::processMsg(const string &msg)
{
shared_ptr<RskWork> rskWork = make_shared<RskWorkEth>();
if (rskWork->initFromGw(msg))
{
previousRskWork_ = currentRskWork_;
currentRskWork_ = rskWork;
DLOG(INFO) << "currentRskBlockJson: " << msg;
}
else {
LOG(ERROR) << "eth initFromGw failed " << msg;
return false;
}
clearTimeoutMsg();
if (nullptr == previousRskWork_ && nullptr == currentRskWork_) {
LOG(ERROR) << "no current work" << msg;
return false;
}
//first job
if (nullptr == previousRskWork_ && currentRskWork_ != nullptr)
return true;
// Check if header changes so the new workpackage is really new
return currentRskWork_->getBlockHash() != previousRskWork_->getBlockHash();
}
void JobMakerHandlerEth::clearTimeoutMsg() {
const uint32_t now = time(nullptr);
if(currentRskWork_ != nullptr && currentRskWork_->getCreatedAt() + def_.maxJobDelay_ < now)
currentRskWork_ = nullptr;
if(previousRskWork_ != nullptr && previousRskWork_->getCreatedAt() + def_.maxJobDelay_ < now)
previousRskWork_ = nullptr;
}
string JobMakerHandlerEth::makeStratumJobMsg()
{
if (nullptr == currentRskWork_)
return "";
if (0 == currentRskWork_->getRpcAddress().length())
return "";
RskWorkEth *currentRskBlockJson = dynamic_cast<RskWorkEth*>(currentRskWork_.get());
if (nullptr == currentRskBlockJson)
return "";
const string request = "{\"jsonrpc\":\"2.0\",\"method\":\"eth_getBlockByNumber\",\"params\":[\"pending\", false],\"id\":2}";
string response;
bool res = bitcoindRpcCall(currentRskBlockJson->getRpcAddress().c_str(), currentRskBlockJson->getRpcUserPwd().c_str(), request.c_str(), response);
if (!res)
LOG(ERROR) << "get pending block failed";
StratumJobEth sjob;
if (!sjob.initFromGw(*currentRskBlockJson, response)) {
LOG(ERROR) << "init stratum job message from gw str fail";
return "";
}
return sjob.serializeToJson();
}
////////////////////////////////JobMakerHandlerSia//////////////////////////////////
JobMakerHandlerSia::JobMakerHandlerSia() : time_(0)
{
}
bool JobMakerHandlerSia::processMsg(const string &msg)
{
JsonNode j;
if (!JsonNode::parse(msg.c_str(), msg.c_str() + msg.length(), j))
{
LOG(ERROR) << "deserialize sia work failed " << msg;
return false;
}
if (!validate(j))
return false;
string header = j["hHash"].str();
if (header == header_)
return false;
header_ = move(header);
time_ = j["created_at_ts"].uint32();
return processMsg(j);
}
bool JobMakerHandlerSia::processMsg(JsonNode &j)
{
target_ = j["target"].str();
return true;
}
bool JobMakerHandlerSia::validate(JsonNode &j)
{
// check fields are valid
if (j.type() != Utilities::JS::type::Obj ||
j["created_at_ts"].type() != Utilities::JS::type::Int ||
j["rpcAddress"].type() != Utilities::JS::type::Str ||
j["rpcUserPwd"].type() != Utilities::JS::type::Str ||
j["target"].type() != Utilities::JS::type::Str ||
j["hHash"].type() != Utilities::JS::type::Str) {
LOG(ERROR) << "work format not expected";
return false;
}
// check timestamp
if (j["created_at_ts"].uint32() + def_.maxJobDelay_ < time(nullptr))
{
LOG(ERROR) << "too old sia work: " << date("%F %T", j["created_at_ts"].uint32());
return false;
}
return true;
}
string JobMakerHandlerSia::makeStratumJobMsg()
{
if (0 == header_.size() ||
0 == target_.size())
return "";
const string jobIdStr = Strings::Format("%08x%08x", (uint32_t)time(nullptr), djb2(header_.c_str()));
assert(jobIdStr.length() == 16);
size_t pos;
uint64 jobId = stoull(jobIdStr, &pos, 16);
return Strings::Format("{\"created_at_ts\":%u"
",\"jobId\":%" PRIu64 ""
",\"target\":\"%s\""
",\"hHash\":\"%s\""
"}",
time_,
jobId,
target_.c_str(),
header_.c_str());
}
///////////////////////////////////JobMakerHandlerBytom//////////////////////////////////
bool JobMakerHandlerBytom::processMsg(JsonNode &j)
{
seed_ = j["sHash"].str();
return true;
}
bool JobMakerHandlerBytom::validate(JsonNode &j)
{
// check fields are valid
if (j.type() != Utilities::JS::type::Obj ||
j["created_at_ts"].type() != Utilities::JS::type::Int ||
j["rpcAddress"].type() != Utilities::JS::type::Str ||
j["rpcUserPwd"].type() != Utilities::JS::type::Str ||
j["hHash"].type() != Utilities::JS::type::Str) {
LOG(ERROR) << "work format not expected";
return false;
}
// check timestamp
if (j["created_at_ts"].uint32() + def_.maxJobDelay_ < time(nullptr))
{
LOG(ERROR) << "too old bytom work: " << date("%F %T", j["created_at_ts"].uint32());
return false;
}
return true;
}
string JobMakerHandlerBytom::makeStratumJobMsg()
{
if (0 == header_.size() ||
0 == seed_.size())
return "";
const string jobIdStr = Strings::Format("%08x%08x", (uint32_t)time(nullptr), djb2(header_.c_str()));
assert(jobIdStr.length() == 16);
size_t pos;
uint64 jobId = stoull(jobIdStr, &pos, 16);
return Strings::Format("{\"created_at_ts\":%u"
",\"jobId\":%" PRIu64 ""
",\"sHash\":\"%s\""
",\"hHash\":\"%s\""
"}",
time_,
jobId,
seed_.c_str(),
header_.c_str());
}
////////////////////////////////JobMakerHandlerBitcoin//////////////////////////////////
JobMakerHandlerBitcoin::JobMakerHandlerBitcoin() :
currBestHeight_(0), lastJobSendTime_(0),
isLastJobEmptyBlock_(false),
previousRskWork_(nullptr), currentRskWork_(nullptr),
isRskUpdate_(false)
{
}
bool JobMakerHandlerBitcoin::init(const GbtJobMakerDefinition &def) {
def_ = def;
// select chain
if (def_.testnet_) {
SelectParams(CBaseChainParams::TESTNET);
LOG(WARNING) << "using bitcoin testnet3";
} else {
SelectParams(CBaseChainParams::MAIN);
}
LOG(INFO) << "Block Version: " << std::hex << def_.blockVersion_;
LOG(INFO) << "Coinbase Info: " << def_.coinbaseInfo_;
LOG(INFO) << "Payout Address: " << def_.payoutAddr_;
// check pool payout address
if (!IsValidDestinationString(def_.payoutAddr_)) {
LOG(ERROR) << "invalid pool payout address";
return false;
}
poolPayoutAddr_ = DecodeDestination(def_.payoutAddr_);
// notify policy for RSK
RskWork::setIsCleanJob(def_.rskNotifyPolicy_ != 0);
return true;
}
bool JobMakerHandlerBitcoin::initConsumerHandlers(const string &kafkaBrokers, vector<JobMakerConsumerHandler> &handlers) {
const int32_t consumeLatestN = 20;
//
// consumer for RawGbt, offset: latest N messages
//
{
kafkaRawGbtConsumer_ = std::make_shared<KafkaConsumer>(kafkaBrokers.c_str(), def_.rawGbtTopic_.c_str(), 0/* partition */);
map<string, string> consumerOptions;
consumerOptions["fetch.wait.max.ms"] = "5";
if (!kafkaRawGbtConsumer_->setup(RD_KAFKA_OFFSET_TAIL(consumeLatestN), &consumerOptions)) {
LOG(ERROR) << "kafka consumer rawgbt setup failure";
return false;
}
if (!kafkaRawGbtConsumer_->checkAlive()) {
LOG(ERROR) << "kafka consumer rawgbt is NOT alive";
return false;
}
handlers.push_back({
def_.rawGbtTopic_,
kafkaRawGbtConsumer_,
std::bind(&JobMakerHandlerBitcoin::processRawGbtMsg, this, std::placeholders::_1)
});
}
//
// consumer for aux block
//
{
kafkaAuxPowConsumer_ = std::make_shared<KafkaConsumer>(kafkaBrokers.c_str(), def_.auxPowTopic_.c_str(), 0/* partition */);
map<string, string> consumerOptions;
consumerOptions["fetch.wait.max.ms"] = "5";
if (!kafkaAuxPowConsumer_->setup(RD_KAFKA_OFFSET_TAIL(1), &consumerOptions)) {
LOG(ERROR) << "kafka consumer aux pow setup failure";
return false;
}
if (!kafkaAuxPowConsumer_->checkAlive()) {
LOG(ERROR) << "kafka consumer aux pow is NOT alive";
return false;
}
handlers.push_back({
def_.auxPowTopic_,
kafkaAuxPowConsumer_,
std::bind(&JobMakerHandlerBitcoin::processAuxPowMsg, this, std::placeholders::_1)
});
}
//
// consumer for RSK messages
//
{
kafkaRskGwConsumer_ = std::make_shared<KafkaConsumer>(kafkaBrokers.c_str(), def_.rskRawGwTopic_.c_str(), 0/* partition */);
map<string, string> consumerOptions;
consumerOptions["fetch.wait.max.ms"] = "5";
if (!kafkaRskGwConsumer_->setup(RD_KAFKA_OFFSET_TAIL(1), &consumerOptions)) {
LOG(ERROR) << "kafka consumer rawgw block setup failure";
return false;
}
if (!kafkaRskGwConsumer_->checkAlive()) {
LOG(ERROR) << "kafka consumer rawgw block is NOT alive";
return false;
}
handlers.push_back({
def_.rskRawGwTopic_,
kafkaRskGwConsumer_,
std::bind(&JobMakerHandlerBitcoin::processRskGwMsg, this, std::placeholders::_1)
});
}
// sleep 3 seconds, wait for the latest N messages transfer from broker to client
sleep(3);
/* pre-consume some messages for initialization */
//
// consume the latest AuxPow message
//
{
rd_kafka_message_t *rkmessage;
rkmessage = kafkaAuxPowConsumer_->consumer(1000/* timeout ms */);
if (rkmessage != nullptr && !rkmessage->err) {
string msg((const char *)rkmessage->payload, rkmessage->len);
processAuxPowMsg(msg);
rd_kafka_message_destroy(rkmessage);
}
}
//
// consume the latest RSK getwork message
//
{
rd_kafka_message_t *rkmessage;
rkmessage = kafkaRskGwConsumer_->consumer(1000/* timeout ms */);
if (rkmessage != nullptr && !rkmessage->err) {
string msg((const char *)rkmessage->payload, rkmessage->len);
processRskGwMsg(msg);
rd_kafka_message_destroy(rkmessage);
}
}
//
// consume the latest N RawGbt messages
//
LOG(INFO) << "consume latest rawgbt messages from kafka...";
for (int32_t i = 0; i < consumeLatestN; i++) {
rd_kafka_message_t *rkmessage;
rkmessage = kafkaRawGbtConsumer_->consumer(5000/* timeout ms */);
if (rkmessage == nullptr || rkmessage->err) {
break;
}
string msg((const char *)rkmessage->payload, rkmessage->len);
processRawGbtMsg(msg);
rd_kafka_message_destroy(rkmessage);
}
LOG(INFO) << "consume latest rawgbt messages done";
return true;
}
bool JobMakerHandlerBitcoin::addRawGbt(const string &msg) {
JsonNode r;
if (!JsonNode::parse(msg.c_str(), msg.c_str() + msg.size(), r)) {
LOG(ERROR) << "parse rawgbt message to json fail";
return false;
}
if (r["created_at_ts"].type() != Utilities::JS::type::Int ||
r["block_template_base64"].type() != Utilities::JS::type::Str ||
r["gbthash"].type() != Utilities::JS::type::Str) {
LOG(ERROR) << "invalid rawgbt: missing fields";
return false;
}
const uint256 gbtHash = uint256S(r["gbthash"].str());
for (const auto &itr : lastestGbtHash_) {
if (gbtHash == itr) {
LOG(ERROR) << "duplicate gbt hash: " << gbtHash.ToString();
return false;
}
}
const uint32_t gbtTime = r["created_at_ts"].uint32();
const int64_t timeDiff = (int64_t)time(nullptr) - (int64_t)gbtTime;
if (labs(timeDiff) >= 60) {
LOG(WARNING) << "rawgbt diff time is more than 60, ignore it";
return false; // time diff too large, there must be some problems, so ignore it
}
if (labs(timeDiff) >= 3) {
LOG(WARNING) << "rawgbt diff time is too large: " << timeDiff << " seconds";
}
const string gbt = DecodeBase64(r["block_template_base64"].str());
assert(gbt.length() > 64); // valid gbt string's len at least 64 bytes
JsonNode nodeGbt;
if (!JsonNode::parse(gbt.c_str(), gbt.c_str() + gbt.length(), nodeGbt)) {
LOG(ERROR) << "parse gbt message to json fail";
return false;
}
assert(nodeGbt["result"]["height"].type() == Utilities::JS::type::Int);
const uint32_t height = nodeGbt["result"]["height"].uint32();
assert(nodeGbt["result"]["transactions"].type() == Utilities::JS::type::Array);
const bool isEmptyBlock = nodeGbt["result"]["transactions"].array().size() == 0;
{
ScopeLock sl(lock_);
if (!rawgbtMap_.empty()) {
const uint64_t bestKey = rawgbtMap_.rbegin()->first;
const uint32_t bestTime = gbtKeyGetTime(bestKey);
const uint32_t bestHeight = gbtKeyGetHeight(bestKey);
const bool bestIsEmpty = gbtKeyIsEmptyBlock(bestKey);
// To prevent the job's block height ups and downs
// when the block height of two bitcoind is not synchronized.
// The block height downs must past twice the time of stratumJobInterval_
// without the higher height GBT received.
if (height < bestHeight && !bestIsEmpty &&
gbtTime - bestTime < 2 * def_.jobInterval_) {
LOG(WARNING) << "skip low height GBT. height: " << height
<< ", best height: " << bestHeight
<< ", elapsed time after best GBT: " << (gbtTime - bestTime) << "s";
return false;
}
}
const uint64_t key = makeGbtKey(gbtTime, isEmptyBlock, height);
if (rawgbtMap_.find(key) == rawgbtMap_.end()) {
rawgbtMap_.insert(std::make_pair(key, gbt));
} else {
LOG(ERROR) << "key already exist in rawgbtMap: " << key;
}
}
lastestGbtHash_.push_back(gbtHash);
while (lastestGbtHash_.size() > 20) {
lastestGbtHash_.pop_front();
}
LOG(INFO) << "add rawgbt, height: "<< height << ", gbthash: "
<< r["gbthash"].str().substr(0, 16) << "..., gbtTime(UTC): " << date("%F %T", gbtTime)
<< ", isEmpty:" << isEmptyBlock;
return true;
}
bool JobMakerHandlerBitcoin::findBestRawGbt(bool isRskUpdate, string &bestRawGbt) {
static uint64_t lastSendBestKey = 0;
ScopeLock sl(lock_);
// clean expired gbt first
clearTimeoutGbt();
clearTimeoutRskGw();
if (rawgbtMap_.size() == 0) {
LOG(WARNING) << "RawGbt Map is empty";
return false;
}
bool isFindNewHeight = false;
bool needUpdateEmptyBlockJob = false;
// rawgbtMap_ is sorted gbt by (timestamp + height + emptyFlag),
// so the last item is the newest/best item.
// @see makeGbtKey()
const uint64_t bestKey = rawgbtMap_.rbegin()->first;
const uint32_t bestHeight = gbtKeyGetHeight(bestKey);
const bool currentGbtIsEmpty = gbtKeyIsEmptyBlock(bestKey);
// if last job is an empty block job, we need to
// send a new non-empty job as quick as possible.
if (bestHeight == currBestHeight_ && isLastJobEmptyBlock_ && !currentGbtIsEmpty) {
needUpdateEmptyBlockJob = true;
LOG(INFO) << "--------update last empty block job--------";
}
if (!needUpdateEmptyBlockJob && !isRskUpdate && bestKey == lastSendBestKey) {
LOG(WARNING) << "bestKey is the same as last one: " << lastSendBestKey;
return false;
}
// The height cannot reduce in normal.
// However, if there is indeed a height reduce,
// isReachTimeout() will allow the new job sending.
if (bestHeight > currBestHeight_) {
LOG(INFO) << ">>>> found new best height: " << bestHeight
<< ", curr: " << currBestHeight_ << " <<<<";
isFindNewHeight = true;
}
if (isFindNewHeight || needUpdateEmptyBlockJob || isRskUpdate || isReachTimeout()) {
lastSendBestKey = bestKey;
currBestHeight_ = bestHeight;
bestRawGbt = rawgbtMap_.rbegin()->second.c_str();
return true;
}
return false;
}
bool JobMakerHandlerBitcoin::isReachTimeout() {
uint32_t intervalSeconds = def_.jobInterval_;
if (lastJobSendTime_ + intervalSeconds <= time(nullptr)) {
return true;
}
return false;
}
void JobMakerHandlerBitcoin::clearTimeoutGbt() {
// Maps (and sets) are sorted, so the first element is the smallest,
// and the last element is the largest.
const uint32_t ts_now = time(nullptr);
for (auto itr = rawgbtMap_.begin(); itr != rawgbtMap_.end(); ) {
const uint32_t ts = gbtKeyGetTime(itr->first);
const bool isEmpty = gbtKeyIsEmptyBlock(itr->first);
const uint32_t height = gbtKeyGetHeight(itr->first);
// gbt expired time
const uint32_t expiredTime = ts + (isEmpty ? def_.emptyGbtLifeTime_ : def_.gbtLifeTime_);
if (expiredTime > ts_now) {
// not expired
++itr;
} else {
// remove expired gbt
LOG(INFO) << "remove timeout rawgbt: " << date("%F %T", ts) << "|" << ts <<
", height:" << height << ", isEmptyBlock:" << (isEmpty ? 1 : 0);
// c++11: returns an iterator to the next element in the map
itr = rawgbtMap_.erase(itr);
}
}
}
void JobMakerHandlerBitcoin::clearTimeoutRskGw() {
RskWork currentRskWork;
RskWork previousRskWork;
{
ScopeLock sl(rskWorkAccessLock_);
if (previousRskWork_ == nullptr || currentRskWork_ == nullptr) {
return;
}
const uint32_t ts_now = time(nullptr);
currentRskWork = *currentRskWork_;
if(currentRskWork.getCreatedAt() + 120u < ts_now) {
delete currentRskWork_;
currentRskWork_ = nullptr;
}
previousRskWork = *previousRskWork_;
if(previousRskWork.getCreatedAt() + 120u < ts_now) {
delete previousRskWork_;
previousRskWork_ = nullptr;
}
}
}
bool JobMakerHandlerBitcoin::triggerRskUpdate() {
RskWork currentRskWork;
RskWork previousRskWork;
{
ScopeLock sl(rskWorkAccessLock_);
if (previousRskWork_ == nullptr || currentRskWork_ == nullptr) {
return false;
}
currentRskWork = *currentRskWork_;
previousRskWork = *previousRskWork_;
}
bool notify_flag_update = def_.rskNotifyPolicy_ == 1 && currentRskWork.getNotifyFlag();
bool different_block_hashUpdate = def_.rskNotifyPolicy_ == 2 &&
(currentRskWork.getBlockHash() !=
previousRskWork.getBlockHash());
return notify_flag_update || different_block_hashUpdate;
}
bool JobMakerHandlerBitcoin::processRawGbtMsg(const string &msg) {
return addRawGbt(msg);
}
bool JobMakerHandlerBitcoin::processAuxPowMsg(const string &msg) {
// set json string
{
ScopeLock sl(auxJsonLock_);
latestAuxPowJson_ = msg;
DLOG(INFO) << "latestAuxPowJson: " << latestAuxPowJson_;
}
// auxpow message will nerver triggered a stratum job updating
return false;
}
bool JobMakerHandlerBitcoin::processRskGwMsg(const string &rawGetWork) {
// set json string
{
ScopeLock sl(rskWorkAccessLock_);
RskWork *rskWork = new RskWork();
if(rskWork->initFromGw(rawGetWork)) {
if (previousRskWork_ != nullptr) {
delete previousRskWork_;
previousRskWork_ = nullptr;
}
previousRskWork_ = currentRskWork_;
currentRskWork_ = rskWork;
DLOG(INFO) << "currentRskBlockJson: " << rawGetWork;
} else {
delete rskWork;
}
}
isRskUpdate_ = triggerRskUpdate();
return isRskUpdate_;
}
string JobMakerHandlerBitcoin::makeStratumJob(const string &gbt) {
string latestAuxPowJson;
{
ScopeLock sl(auxJsonLock_);
latestAuxPowJson = latestAuxPowJson_;
}
RskWork currentRskBlockJson;
{
ScopeLock sl(rskWorkAccessLock_);
if (currentRskWork_ != nullptr) {
currentRskBlockJson = *currentRskWork_;
}
}
StratumJob sjob;
if (!sjob.initFromGbt(gbt.c_str(), def_.coinbaseInfo_,
poolPayoutAddr_,
def_.blockVersion_,
latestAuxPowJson,
currentRskBlockJson)) {
LOG(ERROR) << "init stratum job message from gbt str fail";
return "";
}
const string jobMsg = sjob.serializeToJson();
// set last send time
// TODO: fix Y2K38 issue
lastJobSendTime_ = (uint32_t)time(nullptr);
// is an empty block job
isLastJobEmptyBlock_ = sjob.isEmptyBlock();
LOG(INFO) << "--------producer stratum job, jobId: " << sjob.jobId_
<< ", height: " << sjob.height_ << "--------";
LOG(INFO) << "sjob: " << jobMsg;
return jobMsg;
}
string JobMakerHandlerBitcoin::makeStratumJobMsg() {
string bestRawGbt;
if (!findBestRawGbt(isRskUpdate_, bestRawGbt)) {
return "";
}
isRskUpdate_ = false;
return makeStratumJob(bestRawGbt);
}
uint64_t JobMakerHandlerBitcoin::makeGbtKey(uint32_t gbtTime, bool isEmptyBlock, uint32_t height) {
assert(height < 0x7FFFFFFFU);
//
// gbtKey:
// -----------------------------------------------------------------------------------------
// | 32 bits | 31 bits | 1 bit |
// | xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx | xxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx | x |
// | gbtTime | height | nonEmptyFlag |
// -----------------------------------------------------------------------------------------
// use nonEmptyFlag (aka: !isEmptyBlock) so the key of a non-empty block
// will large than the key of an empty block.
//
return (((uint64_t)gbtTime) << 32) | (((uint64_t)height) << 1) | ((uint64_t)(!isEmptyBlock));
}
uint32_t JobMakerHandlerBitcoin::gbtKeyGetTime(uint64_t gbtKey) {
return (uint32_t)(gbtKey >> 32);
}
uint32_t JobMakerHandlerBitcoin::gbtKeyGetHeight(uint64_t gbtKey) {
return (uint32_t)((gbtKey >> 1) & 0x7FFFFFFFULL);
}
bool JobMakerHandlerBitcoin::gbtKeyIsEmptyBlock(uint64_t gbtKey) {
return !((bool)(gbtKey & 1ULL));
}
| 30.909187
| 148
| 0.633084
|
ganibc
|
429d0615f39c89daee4ce5a114d49518a0210c93
| 2,191
|
cpp
|
C++
|
code/core/chattablabel.cpp
|
detrax/gobby
|
21160017e1f7ffe1123d80acadac88a22bd7f838
|
[
"ISC"
] | 542
|
2015-01-03T21:43:38.000Z
|
2022-03-26T11:43:54.000Z
|
code/core/chattablabel.cpp
|
detrax/gobby
|
21160017e1f7ffe1123d80acadac88a22bd7f838
|
[
"ISC"
] | 116
|
2015-01-14T08:08:43.000Z
|
2021-08-03T19:24:46.000Z
|
code/core/chattablabel.cpp
|
detrax/gobby
|
21160017e1f7ffe1123d80acadac88a22bd7f838
|
[
"ISC"
] | 60
|
2015-01-03T21:43:42.000Z
|
2022-03-19T12:04:52.000Z
|
/* Gobby - GTK-based collaborative text editor
* Copyright (C) 2008-2015 Armin Burgmeier <armin@arbur.net>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "core/chattablabel.hpp"
Gobby::ChatTabLabel::ChatTabLabel(Folder& folder, ChatSessionView& view,
bool always_show_close_button):
TabLabel(folder, view,
always_show_close_button ?
"chat" :
"network-idle"),
m_always_show_close_button(always_show_close_button)
{
if(!m_always_show_close_button)
m_button.hide(); // Only show when disconnected
InfChatBuffer* buffer = INF_CHAT_BUFFER(
inf_session_get_buffer(INF_SESSION(view.get_session())));
m_add_message_handle = g_signal_connect_after(
G_OBJECT(buffer), "add-message",
G_CALLBACK(on_add_message_static), this);
}
Gobby::ChatTabLabel::~ChatTabLabel()
{
InfChatBuffer* buffer = INF_CHAT_BUFFER(
inf_session_get_buffer(INF_SESSION(m_view.get_session())));
g_signal_handler_disconnect(buffer, m_add_message_handle);
}
void Gobby::ChatTabLabel::on_notify_subscription_group()
{
InfSession* session = INF_SESSION(m_view.get_session());
if(inf_session_get_subscription_group(session) != NULL &&
!m_always_show_close_button)
{
m_button.hide();
}
else
{
m_button.show();
}
}
void Gobby::ChatTabLabel::on_changed(InfUser* author)
{
if(!m_changed)
{
InfSession* session = INF_SESSION(m_view.get_session());
if(inf_session_get_status(session) == INF_SESSION_RUNNING)
set_changed();
}
}
| 31.753623
| 75
| 0.74806
|
detrax
|
42a78b36f1ed4f5b61e6d008cc12cbd9eb5cb7b9
| 1,087
|
cpp
|
C++
|
C++/010_Regular_Expression_Matching.cpp
|
stephenkid/LeetCode-Sol
|
8cb429652e0741ca4078b6de5f9eeaddcb8607a8
|
[
"MIT"
] | 1,958
|
2015-01-30T01:19:03.000Z
|
2022-03-17T03:34:47.000Z
|
src/main/cpp/010_Regular_Expression_Matching.cpp
|
TechnoBlogger14o3/LeetCode-Sol-Res
|
04621f21a76fab29909c1fa04a37417257a88f63
|
[
"MIT"
] | 135
|
2016-03-03T04:53:10.000Z
|
2022-03-03T21:14:37.000Z
|
src/main/cpp/010_Regular_Expression_Matching.cpp
|
TechnoBlogger14o3/LeetCode-Sol-Res
|
04621f21a76fab29909c1fa04a37417257a88f63
|
[
"MIT"
] | 914
|
2015-01-27T22:27:22.000Z
|
2022-03-05T04:25:10.000Z
|
//10. Regular Expression Matching
/*
'.' Matches any single character.
'*' Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial).
The function prototype should be:
bool isMatch(const char *s, const char *p)
Some examples:
isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "a*") → true
isMatch("aa", ".*") → true
isMatch("ab", ".*") → true
isMatch("aab", "c*a*b") → true
Tag: Dynamic Programming, Backtracking, String
Author: Xinyu Liu
*/
#include <iostream>
#include <string>
using namespace std;
class Solution{
public:
bool isMatch(string s, string p){
if (p.empty()) return s.empty();
if (p[1] == '*')
return ((!s.empty() && (s[0] == p[0] || p[0] == '.') && isMatch(s.substr(1),p))|| isMatch(s,p.substr(2)));
else
return (!s.empty() && (s[0] == p[0] || p[0] == '.') && isMatch(s.substr(1),p.substr(1)));
}
};
void main(){
string s ("aaa");
string p ("a*");
Solution sol;
bool b = sol.isMatch(s,p);
}
| 22.183673
| 118
| 0.581417
|
stephenkid
|
42a8d987cbe42d8674866946c625ae148a31e200
| 730
|
cpp
|
C++
|
tests/data_structure/test_quad_tree.cpp
|
mitthy/TCC
|
4c48eb11cafd50334c5faef93edc5f03bc7fc171
|
[
"MIT"
] | null | null | null |
tests/data_structure/test_quad_tree.cpp
|
mitthy/TCC
|
4c48eb11cafd50334c5faef93edc5f03bc7fc171
|
[
"MIT"
] | null | null | null |
tests/data_structure/test_quad_tree.cpp
|
mitthy/TCC
|
4c48eb11cafd50334c5faef93edc5f03bc7fc171
|
[
"MIT"
] | null | null | null |
#include "gtest/gtest.h"
#include "geometricks/data_structure/quad_tree.hpp"
#include <tuple>
#include <type_traits>
struct element_t {
int x, y, hw, hh;
};
namespace geometricks {
namespace rectangle_customization {
template<>
struct make_rectangle<element_t> {
static constexpr geometricks::rectangle
_( const element_t& value ) {
return { value.x, value.y, value.hw, value.hh };
}
};
}
}
TEST( TestQuadTree, TestCreation ) {
geometricks::quad_tree<std::tuple<int,int,int,int>> tree{ geometricks::rectangle{ -1000, -1000, 2000, 2000 } };
for( int i = 0; i < 256; ++i ) {
tree.insert( std::make_tuple( ( i + 5 ) * 2, ( i + 5 ) * 2, 10, 10 ) );
}
}
| 21.470588
| 113
| 0.610959
|
mitthy
|
42a8e775526ada85918d187049907b4bfbaa8ac9
| 13,240
|
hpp
|
C++
|
src/xpcc/architecture/platform/cortex_m3/stm32/stm32f4/sdio/sdio_hal.hpp
|
walmis/xpcc
|
1d87c4434530c6aeac923f57d379aeaf32e11e1e
|
[
"BSD-3-Clause"
] | null | null | null |
src/xpcc/architecture/platform/cortex_m3/stm32/stm32f4/sdio/sdio_hal.hpp
|
walmis/xpcc
|
1d87c4434530c6aeac923f57d379aeaf32e11e1e
|
[
"BSD-3-Clause"
] | null | null | null |
src/xpcc/architecture/platform/cortex_m3/stm32/stm32f4/sdio/sdio_hal.hpp
|
walmis/xpcc
|
1d87c4434530c6aeac923f57d379aeaf32e11e1e
|
[
"BSD-3-Clause"
] | null | null | null |
/*
* sdio.hpp
*
* Created on: Apr 20, 2015
* Author: walmis
*/
#ifndef SRC_XPCC_ARCHITECTURE_PLATFORM_CORTEX_M3_STM32_STM32F4_SDIO_SDIO_HPP_
#define SRC_XPCC_ARCHITECTURE_PLATFORM_CORTEX_M3_STM32_STM32F4_SDIO_SDIO_HPP_
#include "../../../stm32.hpp"
namespace xpcc {
namespace stm32 {
/* ---------------------- SDIO registers bit mask ------------------------ */
/* --- CLKCR Register ---*/
/* CLKCR register clear mask */
#define CLKCR_CLEAR_MASK ((uint32_t)0xFFFF8100)
/* --- PWRCTRL Register ---*/
/* SDIO PWRCTRL Mask */
#define PWR_PWRCTRL_MASK ((uint32_t)0xFFFFFFFC)
/* --- DCTRL Register ---*/
/* SDIO DCTRL Clear Mask */
#define DCTRL_CLEAR_MASK ((uint32_t)0xFFFFFF08)
/* --- CMD Register ---*/
/* CMD Register clear mask */
#define CMD_CLEAR_MASK ((uint32_t)0xFFFFF800)
/* SDIO RESP Registers Address */
#define SDIO_RESP_ADDR ((uint32_t)(SDIO_BASE + 0x14))
/* ------------ SDIO registers bit address in the alias region ----------- */
#define SDIO_OFFSET (SDIO_BASE - PERIPH_BASE)
#define SDIO_CPSM_Disable ((uint32_t)0x00000000)
#define SDIO_CPSM_Enable ((uint32_t)0x00000400)
/* --- CLKCR Register ---*/
/* Alias word address of CLKEN bit */
#define CLKCR_OFFSET (SDIO_OFFSET + 0x04)
#define CLKEN_BitNumber 0x08
#define CLKCR_CLKEN_BB (PERIPH_BB_BASE + (CLKCR_OFFSET * 32) + (CLKEN_BitNumber * 4))
/* --- CMD Register ---*/
/* Alias word address of SDIOSUSPEND bit */
#define CMD_OFFSET (SDIO_OFFSET + 0x0C)
#define SDIOSUSPEND_BitNumber 0x0B
#define CMD_SDIOSUSPEND_BB (PERIPH_BB_BASE + (CMD_OFFSET * 32) + (SDIOSUSPEND_BitNumber * 4))
/* Alias word address of ENCMDCOMPL bit */
#define ENCMDCOMPL_BitNumber 0x0C
#define CMD_ENCMDCOMPL_BB (PERIPH_BB_BASE + (CMD_OFFSET * 32) + (ENCMDCOMPL_BitNumber * 4))
/* Alias word address of NIEN bit */
#define NIEN_BitNumber 0x0D
#define CMD_NIEN_BB (PERIPH_BB_BASE + (CMD_OFFSET * 32) + (NIEN_BitNumber * 4))
/* Alias word address of ATACMD bit */
#define ATACMD_BitNumber 0x0E
#define CMD_ATACMD_BB (PERIPH_BB_BASE + (CMD_OFFSET * 32) + (ATACMD_BitNumber * 4))
/* --- DCTRL Register ---*/
/* Alias word address of DMAEN bit */
#define DCTRL_OFFSET (SDIO_OFFSET + 0x2C)
#define DMAEN_BitNumber 0x03
#define DCTRL_DMAEN_BB (PERIPH_BB_BASE + (DCTRL_OFFSET * 32) + (DMAEN_BitNumber * 4))
/* Alias word address of RWSTART bit */
#define RWSTART_BitNumber 0x08
#define DCTRL_RWSTART_BB (PERIPH_BB_BASE + (DCTRL_OFFSET * 32) + (RWSTART_BitNumber * 4))
/* Alias word address of RWSTOP bit */
#define RWSTOP_BitNumber 0x09
#define DCTRL_RWSTOP_BB (PERIPH_BB_BASE + (DCTRL_OFFSET * 32) + (RWSTOP_BitNumber * 4))
/* Alias word address of RWMOD bit */
#define RWMOD_BitNumber 0x0A
#define DCTRL_RWMOD_BB (PERIPH_BB_BASE + (DCTRL_OFFSET * 32) + (RWMOD_BitNumber * 4))
/* Alias word address of SDIOEN bit */
#define SDIOEN_BitNumber 0x0B
#define DCTRL_SDIOEN_BB (PERIPH_BB_BASE + (DCTRL_OFFSET * 32) + (SDIOEN_BitNumber * 4))
class SDIO_HAL {
public:
enum class ClockEdge {
Rising = ((uint32_t) 0x00000000), Falling = ((uint32_t) 0x00002000)
};
enum class ClockFlags {
None = 0x00, Bypass = 0x400, PowerSave = 0x200
};
enum class BusWidth {
_1b = 0x00, _4b = 0x800, _8b = 0x1000
};
enum class HardwareFlowControl {
Disable = 0x00, Enable = 0x4000
};
enum class PowerState {
Off = 0x00, On = 0x03
};
/** @defgroup SDIO_Interrupt_sources
* @{
*/
enum Interrupt {
CCRCFAIL = ((uint32_t) 0x00000001),
DCRCFAIL = ((uint32_t) 0x00000002),
CTIMEOUT = ((uint32_t) 0x00000004),
DTIMEOUT = ((uint32_t) 0x00000008),
TXUNDERR = ((uint32_t) 0x00000010),
RXOVERR = ((uint32_t) 0x00000020),
CMDREND = ((uint32_t) 0x00000040),
CMDSENT = ((uint32_t) 0x00000080),
DATAEND = ((uint32_t) 0x00000100),
STBITERR = ((uint32_t) 0x00000200),
DBCKEND = ((uint32_t) 0x00000400),
CMDACT = ((uint32_t) 0x00000800),
TXACT = ((uint32_t) 0x00001000),
RXACT = ((uint32_t) 0x00002000),
TXFIFOHE = ((uint32_t) 0x00004000),
RXFIFOHF = ((uint32_t) 0x00008000),
TXFIFOF = ((uint32_t) 0x00010000),
RXFIFOF = ((uint32_t) 0x00020000),
TXFIFOE = ((uint32_t) 0x00040000),
RXFIFOE = ((uint32_t) 0x00080000),
TXDAVL = ((uint32_t) 0x00100000),
RXDAVL = ((uint32_t) 0x00200000),
SDIOIT = ((uint32_t) 0x00400000),
CEATAEND = ((uint32_t) 0x00800000)
};
#define IS_SDIO_IT(IT) ((((IT) & (uint32_t)0xFF000000) == 0x00) && ((IT) != (uint32_t)0x00))
/**
* @}
*/
/** @defgroup SDIO_Command_Index
* @{
*/
#define IS_SDIO_CMD_INDEX(INDEX) ((INDEX) < 0x40)
enum class ResponseType {
None = 0, Short = 0x40, Long = 0xC0
};
/** @defgroup SDIO_Wait_Interrupt_State
* @{
*/
enum class SDIOWait {
NoWait = 0,
WaitIT = 0x100,
WaitPend = 0x200
};
enum class CPSM {
Disable = 0x00, Enable = 0x400
};
enum class SDIOResp {
RESP1 = ((uint32_t) 0x00000000),
RESP2 = ((uint32_t) 0x00000004),
RESP3 = ((uint32_t) 0x00000008),
RESP4 = ((uint32_t) 0x0000000C)
};
enum class DataBlockSize {
_1b = ((uint32_t) 0x00000000),
_2b = ((uint32_t) 0x00000010),
_4b = ((uint32_t) 0x00000020),
_8b = ((uint32_t) 0x00000030),
_16b = ((uint32_t) 0x00000040),
_32b = ((uint32_t) 0x00000050),
_64b = ((uint32_t) 0x00000060),
_128b = ((uint32_t) 0x00000070),
_256b = ((uint32_t) 0x00000080),
_512b = ((uint32_t) 0x00000090),
_1024b = ((uint32_t) 0x000000A0),
_2048b = ((uint32_t) 0x000000B0),
_4096b = ((uint32_t) 0x000000C0),
_8192b = ((uint32_t) 0x000000D0),
_16384b = ((uint32_t) 0x000000E0)
};
enum class TransferDir {
ToCard = 0x00, ToSDIO = 0x02
};
enum class TransferMode {
Block = 0x0, Stream = 0x04
};
enum class DPSM {
Disable = 0, Enable = 1
};
enum ReadWaitMode {
CLK = 0x0, DATA2 = 0x01
};
static inline void init() {
RCC->APB2ENR |= RCC_APB2ENR_SDIOEN;
uint32_t tmpreg;
/* Get the SDIO CLKCR value */
tmpreg = SDIO->CLKCR;
/* Clear CLKDIV, PWRSAV, BYPASS, WIDBUS, NEGEDGE, HWFC_EN bits */
tmpreg &= CLKCR_CLEAR_MASK;
/* Set CLKDIV bits according to SDIO_ClockDiv value */
/* Set PWRSAV bit according to SDIO_ClockPowerSave value */
/* Set BYPASS bit according to SDIO_ClockBypass value */
/* Set WIDBUS bits according to SDIO_BusWide value */
/* Set NEGEDGE bits according to SDIO_ClockEdge value */
/* Set HWFC_EN bits according to SDIO_HardwareFlowControl value */
tmpreg |= (uint32_t) ClockFlags::None | (uint32_t) BusWidth::_1b
| (uint32_t) ClockEdge::Rising
| (uint32_t) HardwareFlowControl::Disable;
/* Write to SDIO CLKCR */
SDIO->CLKCR = tmpreg;
}
static inline void setClockFlags(ClockFlags flags) {
SDIO->CLKCR &= ~((1 << 9) | (1 << 10));
SDIO->CLKCR |= (uint32_t) flags;
}
static inline void setClockEdge(ClockEdge edge) {
SDIO->CLKCR &= ~((1 << 13));
SDIO->CLKCR |= (uint32_t) edge;
}
static inline void setClockDiv(uint8_t div) {
SDIO->CLKCR &= ~0xFF;
SDIO->CLKCR |= (uint32_t) div;
}
static inline void setBusWidth(BusWidth bw) {
SDIO->CLKCR &= ~((1 << 11) | (1 << 12));
SDIO->CLKCR |= (uint32_t) bw;
}
static inline void setHardwareFlowControl(HardwareFlowControl fc) {
SDIO->CLKCR &= ~((1 << 14));
SDIO->CLKCR |= (uint32_t) fc;
}
static inline void setClockState(bool state) {
*(__IO uint32_t *) CLKCR_CLKEN_BB = (uint32_t) state;
}
static inline void setPowerState(PowerState state = PowerState::On) {
SDIO->POWER = (uint32_t) state;
}
static inline PowerState getPowerState() {
return (PowerState) SDIO->POWER;
}
static inline void sendCommand(uint32_t argument, uint32_t cmdindex,
ResponseType resptype, SDIOWait wait = SDIOWait::NoWait) {
uint32_t tmpreg;
/*---------------------------- SDIO ARG Configuration ------------------------*/
/* Set the SDIO Argument value */
SDIO->ARG = argument;
/*---------------------------- SDIO CMD Configuration ------------------------*/
/* Get the SDIO CMD value */
tmpreg = SDIO->CMD;
/* Clear CMDINDEX, WAITRESP, WAITINT, WAITPEND, CPSMEN bits */
tmpreg &= CMD_CLEAR_MASK;
/* Set CMDINDEX bits according to SDIO_CmdIndex value */
/* Set WAITRESP bits according to SDIO_Response value */
/* Set WAITINT and WAITPEND bits according to SDIO_Wait value */
/* Set CPSMEN bits according to SDIO_CPSM value */
tmpreg |= ((uint32_t) cmdindex & SDIO_CMD_CMDINDEX) | ((uint32_t) resptype & SDIO_CMD_WAITRESP) | (uint32_t) wait
| SDIO_CPSM_Enable;
/* Write to SDIO CMD */
SDIO->CMD = tmpreg;
}
static inline uint8_t getCommandResponse() {
return (uint8_t) (SDIO->RESPCMD);
}
static inline uint32_t getResponse(SDIOResp resp) {
__IO uint32_t tmp = 0;
tmp = SDIO_RESP_ADDR + (uint32_t) resp;
return (*(__IO uint32_t *) tmp);
}
static inline void startDataTransaction(TransferDir dir, uint32_t length,
TransferMode mode = TransferMode::Block, DataBlockSize bs =
DataBlockSize::_512b, uint32_t timeout = 0xFFFFFFFF) {
uint32_t tmpreg;
/* Set the SDIO Data TimeOut value */
SDIO->DTIMER = timeout;
/*---------------------------- SDIO DLEN Configuration -----------------------*/
/* Set the SDIO DataLength value */
SDIO->DLEN = length;
/*---------------------------- SDIO DCTRL Configuration ----------------------*/
/* Get the SDIO DCTRL value */
tmpreg = SDIO->DCTRL;
/* Clear DEN, DTMODE, DTDIR and DBCKSIZE bits */
tmpreg &= DCTRL_CLEAR_MASK;
/* Set DEN bit according to SDIO_DPSM value */
/* Set DTMODE bit according to SDIO_TransferMode value */
/* Set DTDIR bit according to SDIO_TransferDir value */
/* Set DBCKSIZE bits according to SDIO_DataBlockSize value */
tmpreg |= (uint32_t) bs | (uint32_t) dir | (uint32_t) mode | 0x01;
/* Write to SDIO DCTRL */
SDIO->DCTRL = tmpreg;
}
static inline void resetDataPath() {
SDIO->DCTRL = 0;
}
static inline void resetCommandPath() {
SDIO->CMD = 0;
}
static inline uint32_t getDataCounter(void) {
return SDIO->DCOUNT;
}
static inline uint32_t readData(void) {
return SDIO->FIFO;
}
static inline void writeData(uint32_t Data) {
SDIO->FIFO = Data;
}
static inline uint32_t getFIFOCount(void) {
return SDIO->FIFOCNT;
}
/**
* @brief Starts the SD I/O Read Wait operation.
* @param NewState: new state of the Start SDIO Read Wait operation.
* This parameter can be: ENABLE or DISABLE.
* @retval None
*/
static inline void startSDIOReadWait(bool NewState) {
*(__IO uint32_t *) DCTRL_RWSTART_BB = (uint32_t) NewState;
}
/**
* @brief Stops the SD I/O Read Wait operation.
* @param NewState: new state of the Stop SDIO Read Wait operation.
* This parameter can be: ENABLE or DISABLE.
* @retval None
*/
static inline void stopSDIOReadWait(bool NewState) {
*(__IO uint32_t *) DCTRL_RWSTOP_BB = (uint32_t) NewState;
}
/**
* @brief Sets one of the two options of inserting read wait interval.
* @param SDIO_ReadWaitMode: SD I/O Read Wait operation mode.
* This parameter can be:
* @arg SDIO_ReadWaitMode_CLK: Read Wait control by stopping SDIOCLK
* @arg SDIO_ReadWaitMode_DATA2: Read Wait control using SDIO_DATA2
* @retval None
*/
static inline void setSDIOReadWaitMode(ReadWaitMode SDIO_ReadWaitMode) {
*(__IO uint32_t *) DCTRL_RWMOD_BB = (uint32_t) SDIO_ReadWaitMode;
}
/**
* @brief Enables or disables the SD I/O Mode Operation.
* @param NewState: new state of SDIO specific operation.
* This parameter can be: ENABLE or DISABLE.
* @retval None
*/
static inline void setSDIOOperation(bool NewState) {
*(__IO uint32_t *) DCTRL_SDIOEN_BB = (uint32_t) NewState;
}
/**
* @brief Enables or disables the SD I/O Mode suspend command sending.
* @param NewState: new state of the SD I/O Mode suspend command.
* This parameter can be: ENABLE or DISABLE.
* @retval None
*/
static inline void sendSDIOSuspendCmd(bool NewState) {
*(__IO uint32_t *) CMD_SDIOSUSPEND_BB = (uint32_t) NewState;
}
/**
* @brief Enables or disables the SDIO DMA request.
* @param NewState: new state of the selected SDIO DMA request.
* This parameter can be: ENABLE or DISABLE.
* @retval None
*/
static inline void DMACmd(bool enable) {
*(__IO uint32_t *) DCTRL_DMAEN_BB = (uint32_t) enable;
}
static inline void setInterruptMask(Interrupt it) {
SDIO->MASK = (uint32_t) it;
}
static inline void interruptConfig(Interrupt it, bool NewState) {
if (NewState) {
/* Enable the SDIO interrupts */
SDIO->MASK |= (uint32_t) it;
} else {
/* Disable the SDIO interrupts */
SDIO->MASK &= ~(uint32_t) it;
}
}
static inline uint32_t getInterruptFlags() {
return SDIO->STA;
}
static inline bool getInterruptStatus(Interrupt it) {
if ((SDIO->STA & (uint32_t) it)) {
return true;
} else {
return false;
}
}
static inline void clearInterrupt(Interrupt it) {
SDIO->ICR = (uint32_t) it;
}
};
ENUM_CLASS_FLAG(SDIO_HAL::Interrupt);
}
}
#endif /* SRC_XPCC_ARCHITECTURE_PLATFORM_CORTEX_M3_STM32_STM32F4_SDIO_SDIO_HPP_ */
| 28.908297
| 115
| 0.656193
|
walmis
|
42a9208251f39477bf054939e4474f914c29221c
| 18,316
|
cpp
|
C++
|
rclcpp/src/rclcpp/time_source.cpp
|
RTI-BDI/rclcpp
|
c29a916429285362d4d8072b698b6c200d1d2a37
|
[
"Apache-2.0"
] | 1
|
2022-02-28T21:29:12.000Z
|
2022-02-28T21:29:12.000Z
|
rclcpp/src/rclcpp/time_source.cpp
|
stokekld/rclcpp
|
025cd5ccc8202a52f7c7a3f037d8faf46f7dc3f3
|
[
"Apache-2.0"
] | null | null | null |
rclcpp/src/rclcpp/time_source.cpp
|
stokekld/rclcpp
|
025cd5ccc8202a52f7c7a3f037d8faf46f7dc3f3
|
[
"Apache-2.0"
] | null | null | null |
// Copyright 2017 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "builtin_interfaces/msg/time.hpp"
#include "rcl/time.h"
#include "rclcpp/clock.hpp"
#include "rclcpp/exceptions.hpp"
#include "rclcpp/logging.hpp"
#include "rclcpp/node.hpp"
#include "rclcpp/parameter_client.hpp"
#include "rclcpp/parameter_events_filter.hpp"
#include "rclcpp/time.hpp"
#include "rclcpp/time_source.hpp"
namespace rclcpp
{
class ClocksState final
{
public:
ClocksState()
: logger_(rclcpp::get_logger("rclcpp"))
{
}
// An internal method to use in the clock callback that iterates and enables all clocks
void enable_ros_time()
{
if (ros_time_active_) {
// already enabled no-op
return;
}
// Local storage
ros_time_active_ = true;
// Update all attached clocks to zero or last recorded time
std::lock_guard<std::mutex> guard(clock_list_lock_);
auto time_msg = std::make_shared<builtin_interfaces::msg::Time>();
if (last_msg_set_) {
time_msg = std::make_shared<builtin_interfaces::msg::Time>(last_msg_set_->clock);
}
for (auto it = associated_clocks_.begin(); it != associated_clocks_.end(); ++it) {
set_clock(time_msg, true, *it);
}
}
// An internal method to use in the clock callback that iterates and disables all clocks
void disable_ros_time()
{
if (!ros_time_active_) {
// already disabled no-op
return;
}
// Local storage
ros_time_active_ = false;
// Update all attached clocks
std::lock_guard<std::mutex> guard(clock_list_lock_);
for (auto it = associated_clocks_.begin(); it != associated_clocks_.end(); ++it) {
auto msg = std::make_shared<builtin_interfaces::msg::Time>();
set_clock(msg, false, *it);
}
}
// Check if ROS time is active
bool is_ros_time_active() const
{
return ros_time_active_;
}
// Attach a clock
void attachClock(rclcpp::Clock::SharedPtr clock)
{
if (clock->get_clock_type() != RCL_ROS_TIME) {
throw std::invalid_argument("Cannot attach clock to a time source that's not a ROS clock");
}
std::lock_guard<std::mutex> guard(clock_list_lock_);
associated_clocks_.push_back(clock);
// Set the clock to zero unless there's a recently received message
auto time_msg = std::make_shared<builtin_interfaces::msg::Time>();
if (last_msg_set_) {
time_msg = std::make_shared<builtin_interfaces::msg::Time>(last_msg_set_->clock);
}
set_clock(time_msg, ros_time_active_, clock);
}
// Detach a clock
void detachClock(rclcpp::Clock::SharedPtr clock)
{
std::lock_guard<std::mutex> guard(clock_list_lock_);
auto result = std::find(associated_clocks_.begin(), associated_clocks_.end(), clock);
if (result != associated_clocks_.end()) {
associated_clocks_.erase(result);
} else {
RCLCPP_ERROR(logger_, "failed to remove clock");
}
}
// Internal helper function used inside iterators
static void set_clock(
const builtin_interfaces::msg::Time::SharedPtr msg,
bool set_ros_time_enabled,
rclcpp::Clock::SharedPtr clock)
{
std::lock_guard<std::mutex> clock_guard(clock->get_clock_mutex());
// Do change
if (!set_ros_time_enabled && clock->ros_time_is_active()) {
auto ret = rcl_disable_ros_time_override(clock->get_clock_handle());
if (ret != RCL_RET_OK) {
rclcpp::exceptions::throw_from_rcl_error(
ret, "Failed to disable ros_time_override_status");
}
} else if (set_ros_time_enabled && !clock->ros_time_is_active()) {
auto ret = rcl_enable_ros_time_override(clock->get_clock_handle());
if (ret != RCL_RET_OK) {
rclcpp::exceptions::throw_from_rcl_error(
ret, "Failed to enable ros_time_override_status");
}
}
auto ret = rcl_set_ros_time_override(
clock->get_clock_handle(),
rclcpp::Time(*msg).nanoseconds());
if (ret != RCL_RET_OK) {
rclcpp::exceptions::throw_from_rcl_error(
ret, "Failed to set ros_time_override_status");
}
}
// Internal helper function
void set_all_clocks(
const builtin_interfaces::msg::Time::SharedPtr msg,
bool set_ros_time_enabled)
{
std::lock_guard<std::mutex> guard(clock_list_lock_);
for (auto it = associated_clocks_.begin(); it != associated_clocks_.end(); ++it) {
set_clock(msg, set_ros_time_enabled, *it);
}
}
// Cache the last clock message received
void cache_last_msg(std::shared_ptr<const rosgraph_msgs::msg::Clock> msg)
{
last_msg_set_ = msg;
}
private:
// Store (and update on node attach) logger for logging.
Logger logger_;
// A lock to protect iterating the associated_clocks_ field.
std::mutex clock_list_lock_;
// A vector to store references to associated clocks.
std::vector<rclcpp::Clock::SharedPtr> associated_clocks_;
// Local storage of validity of ROS time
// This is needed when new clocks are added.
bool ros_time_active_{false};
// Last set message to be passed to newly registered clocks
std::shared_ptr<const rosgraph_msgs::msg::Clock> last_msg_set_;
};
class TimeSource::NodeState final
{
public:
NodeState(const rclcpp::QoS & qos, bool use_clock_thread)
: use_clock_thread_(use_clock_thread),
logger_(rclcpp::get_logger("rclcpp")),
qos_(qos)
{
}
~NodeState()
{
if (
node_base_ || node_topics_ || node_graph_ || node_services_ ||
node_logging_ || node_clock_ || node_parameters_)
{
detachNode();
}
}
// Check if a clock thread will be used
bool get_use_clock_thread()
{
return use_clock_thread_;
}
// Set whether a clock thread will be used
void set_use_clock_thread(bool use_clock_thread)
{
use_clock_thread_ = use_clock_thread;
}
// Check if the clock thread is joinable
bool clock_thread_is_joinable()
{
return clock_executor_thread_.joinable();
}
// Attach a node to this time source
void attachNode(
rclcpp::node_interfaces::NodeBaseInterface::SharedPtr node_base_interface,
rclcpp::node_interfaces::NodeTopicsInterface::SharedPtr node_topics_interface,
rclcpp::node_interfaces::NodeGraphInterface::SharedPtr node_graph_interface,
rclcpp::node_interfaces::NodeServicesInterface::SharedPtr node_services_interface,
rclcpp::node_interfaces::NodeLoggingInterface::SharedPtr node_logging_interface,
rclcpp::node_interfaces::NodeClockInterface::SharedPtr node_clock_interface,
rclcpp::node_interfaces::NodeParametersInterface::SharedPtr node_parameters_interface)
{
node_base_ = node_base_interface;
node_topics_ = node_topics_interface;
node_graph_ = node_graph_interface;
node_services_ = node_services_interface;
node_logging_ = node_logging_interface;
node_clock_ = node_clock_interface;
node_parameters_ = node_parameters_interface;
// TODO(tfoote): Update QOS
logger_ = node_logging_->get_logger();
// Though this defaults to false, it can be overridden by initial parameter values for the
// node, which may be given by the user at the node's construction or even by command-line
// arguments.
rclcpp::ParameterValue use_sim_time_param;
const std::string use_sim_time_name = "use_sim_time";
if (!node_parameters_->has_parameter(use_sim_time_name)) {
use_sim_time_param = node_parameters_->declare_parameter(
use_sim_time_name,
rclcpp::ParameterValue(false));
} else {
use_sim_time_param = node_parameters_->get_parameter(use_sim_time_name).get_parameter_value();
}
if (use_sim_time_param.get_type() == rclcpp::PARAMETER_BOOL) {
if (use_sim_time_param.get<bool>()) {
parameter_state_ = SET_TRUE;
clocks_state_.enable_ros_time();
create_clock_sub();
}
} else {
RCLCPP_ERROR(
logger_, "Invalid type '%s' for parameter 'use_sim_time', should be 'bool'",
rclcpp::to_string(use_sim_time_param.get_type()).c_str());
throw std::invalid_argument("Invalid type for parameter 'use_sim_time', should be 'bool'");
}
// TODO(tfoote) use parameters interface not subscribe to events via topic ticketed #609
parameter_subscription_ = rclcpp::AsyncParametersClient::on_parameter_event(
node_topics_,
[this](std::shared_ptr<const rcl_interfaces::msg::ParameterEvent> event) {
if (node_base_ != nullptr) {
this->on_parameter_event(event);
}
// Do nothing if node_base_ is nullptr because it means the TimeSource is now
// without an attached node
});
}
// Detach the attached node
void detachNode()
{
// destroy_clock_sub() *must* be first here, to ensure that the executor
// can't possibly call any of the callbacks as we are cleaning up.
destroy_clock_sub();
clocks_state_.disable_ros_time();
parameter_subscription_.reset();
node_base_.reset();
node_topics_.reset();
node_graph_.reset();
node_services_.reset();
node_logging_.reset();
node_clock_.reset();
node_parameters_.reset();
}
void attachClock(std::shared_ptr<rclcpp::Clock> clock)
{
clocks_state_.attachClock(std::move(clock));
}
void detachClock(std::shared_ptr<rclcpp::Clock> clock)
{
clocks_state_.detachClock(std::move(clock));
}
private:
ClocksState clocks_state_;
// Dedicated thread for clock subscription.
bool use_clock_thread_;
std::thread clock_executor_thread_;
// Preserve the node reference
rclcpp::node_interfaces::NodeBaseInterface::SharedPtr node_base_{nullptr};
rclcpp::node_interfaces::NodeTopicsInterface::SharedPtr node_topics_{nullptr};
rclcpp::node_interfaces::NodeGraphInterface::SharedPtr node_graph_{nullptr};
rclcpp::node_interfaces::NodeServicesInterface::SharedPtr node_services_{nullptr};
rclcpp::node_interfaces::NodeLoggingInterface::SharedPtr node_logging_{nullptr};
rclcpp::node_interfaces::NodeClockInterface::SharedPtr node_clock_{nullptr};
rclcpp::node_interfaces::NodeParametersInterface::SharedPtr node_parameters_{nullptr};
// Store (and update on node attach) logger for logging.
Logger logger_;
// QoS of the clock subscription.
rclcpp::QoS qos_;
// The subscription for the clock callback
using SubscriptionT = rclcpp::Subscription<rosgraph_msgs::msg::Clock>;
std::shared_ptr<SubscriptionT> clock_subscription_{nullptr};
std::mutex clock_sub_lock_;
rclcpp::CallbackGroup::SharedPtr clock_callback_group_;
rclcpp::executors::SingleThreadedExecutor::SharedPtr clock_executor_;
std::promise<void> cancel_clock_executor_promise_;
// The clock callback itself
void clock_cb(std::shared_ptr<const rosgraph_msgs::msg::Clock> msg)
{
if (!clocks_state_.is_ros_time_active() && SET_TRUE == this->parameter_state_) {
clocks_state_.enable_ros_time();
}
// Cache the last message in case a new clock is attached.
clocks_state_.cache_last_msg(msg);
auto time_msg = std::make_shared<builtin_interfaces::msg::Time>(msg->clock);
if (SET_TRUE == this->parameter_state_) {
clocks_state_.set_all_clocks(time_msg, true);
}
}
// Create the subscription for the clock topic
void create_clock_sub()
{
std::lock_guard<std::mutex> guard(clock_sub_lock_);
if (clock_subscription_) {
// Subscription already created.
return;
}
rclcpp::SubscriptionOptions options;
options.qos_overriding_options = rclcpp::QosOverridingOptions(
{
rclcpp::QosPolicyKind::Depth,
rclcpp::QosPolicyKind::Durability,
rclcpp::QosPolicyKind::History,
rclcpp::QosPolicyKind::Reliability,
});
if (use_clock_thread_) {
clock_callback_group_ = node_base_->create_callback_group(
rclcpp::CallbackGroupType::MutuallyExclusive,
false
);
options.callback_group = clock_callback_group_;
rclcpp::ExecutorOptions exec_options;
exec_options.context = node_base_->get_context();
clock_executor_ =
std::make_shared<rclcpp::executors::SingleThreadedExecutor>(exec_options);
if (!clock_executor_thread_.joinable()) {
cancel_clock_executor_promise_ = std::promise<void>{};
clock_executor_thread_ = std::thread(
[this]() {
auto future = cancel_clock_executor_promise_.get_future();
clock_executor_->add_callback_group(clock_callback_group_, node_base_);
clock_executor_->spin_until_future_complete(future);
}
);
}
}
clock_subscription_ = rclcpp::create_subscription<rosgraph_msgs::msg::Clock>(
node_parameters_,
node_topics_,
"/clock",
qos_,
[this](std::shared_ptr<const rosgraph_msgs::msg::Clock> msg) {
// We are using node_base_ as an indication if there is a node attached.
// Only call the clock_cb if that is the case.
if (node_base_ != nullptr) {
clock_cb(msg);
}
},
options
);
}
// Destroy the subscription for the clock topic
void destroy_clock_sub()
{
std::lock_guard<std::mutex> guard(clock_sub_lock_);
if (clock_executor_thread_.joinable()) {
cancel_clock_executor_promise_.set_value();
clock_executor_->cancel();
clock_executor_thread_.join();
clock_executor_->remove_callback_group(clock_callback_group_);
}
clock_subscription_.reset();
}
// Parameter Event subscription
using ParamSubscriptionT = rclcpp::Subscription<rcl_interfaces::msg::ParameterEvent>;
std::shared_ptr<ParamSubscriptionT> parameter_subscription_;
// Callback for parameter updates
void on_parameter_event(std::shared_ptr<const rcl_interfaces::msg::ParameterEvent> event)
{
// Filter out events on 'use_sim_time' parameter instances in other nodes.
if (event->node != node_base_->get_fully_qualified_name()) {
return;
}
// Filter for only 'use_sim_time' being added or changed.
rclcpp::ParameterEventsFilter filter(event, {"use_sim_time"},
{rclcpp::ParameterEventsFilter::EventType::NEW,
rclcpp::ParameterEventsFilter::EventType::CHANGED});
for (auto & it : filter.get_events()) {
if (it.second->value.type != ParameterType::PARAMETER_BOOL) {
RCLCPP_ERROR(logger_, "use_sim_time parameter cannot be set to anything but a bool");
continue;
}
if (it.second->value.bool_value) {
parameter_state_ = SET_TRUE;
clocks_state_.enable_ros_time();
create_clock_sub();
} else {
parameter_state_ = SET_FALSE;
destroy_clock_sub();
clocks_state_.disable_ros_time();
}
}
// Handle the case that use_sim_time was deleted.
rclcpp::ParameterEventsFilter deleted(event, {"use_sim_time"},
{rclcpp::ParameterEventsFilter::EventType::DELETED});
for (auto & it : deleted.get_events()) {
(void) it; // if there is a match it's already matched, don't bother reading it.
// If the parameter is deleted mark it as unset but don't change state.
parameter_state_ = UNSET;
}
}
// An enum to hold the parameter state
enum UseSimTimeParameterState {UNSET, SET_TRUE, SET_FALSE};
UseSimTimeParameterState parameter_state_;
};
TimeSource::TimeSource(
std::shared_ptr<rclcpp::Node> node,
const rclcpp::QoS & qos,
bool use_clock_thread)
: TimeSource(qos, use_clock_thread)
{
attachNode(node);
}
TimeSource::TimeSource(
const rclcpp::QoS & qos,
bool use_clock_thread)
: constructed_use_clock_thread_(use_clock_thread),
constructed_qos_(qos)
{
node_state_ = std::make_shared<NodeState>(qos, use_clock_thread);
}
void TimeSource::attachNode(rclcpp::Node::SharedPtr node)
{
node_state_->set_use_clock_thread(node->get_node_options().use_clock_thread());
attachNode(
node->get_node_base_interface(),
node->get_node_topics_interface(),
node->get_node_graph_interface(),
node->get_node_services_interface(),
node->get_node_logging_interface(),
node->get_node_clock_interface(),
node->get_node_parameters_interface());
}
void TimeSource::attachNode(
rclcpp::node_interfaces::NodeBaseInterface::SharedPtr node_base_interface,
rclcpp::node_interfaces::NodeTopicsInterface::SharedPtr node_topics_interface,
rclcpp::node_interfaces::NodeGraphInterface::SharedPtr node_graph_interface,
rclcpp::node_interfaces::NodeServicesInterface::SharedPtr node_services_interface,
rclcpp::node_interfaces::NodeLoggingInterface::SharedPtr node_logging_interface,
rclcpp::node_interfaces::NodeClockInterface::SharedPtr node_clock_interface,
rclcpp::node_interfaces::NodeParametersInterface::SharedPtr node_parameters_interface)
{
node_state_->attachNode(
std::move(node_base_interface),
std::move(node_topics_interface),
std::move(node_graph_interface),
std::move(node_services_interface),
std::move(node_logging_interface),
std::move(node_clock_interface),
std::move(node_parameters_interface));
}
void TimeSource::detachNode()
{
node_state_.reset();
node_state_ = std::make_shared<NodeState>(
constructed_qos_,
constructed_use_clock_thread_);
}
void TimeSource::attachClock(std::shared_ptr<rclcpp::Clock> clock)
{
node_state_->attachClock(std::move(clock));
}
void TimeSource::detachClock(std::shared_ptr<rclcpp::Clock> clock)
{
node_state_->detachClock(std::move(clock));
}
bool TimeSource::get_use_clock_thread()
{
return node_state_->get_use_clock_thread();
}
void TimeSource::set_use_clock_thread(bool use_clock_thread)
{
node_state_->set_use_clock_thread(use_clock_thread);
}
bool TimeSource::clock_thread_is_joinable()
{
return node_state_->clock_thread_is_joinable();
}
TimeSource::~TimeSource()
{
}
} // namespace rclcpp
| 33.001802
| 100
| 0.71473
|
RTI-BDI
|
42ad3848e22a63e1e8823742916de5544ff84725
| 1,730
|
hh
|
C++
|
grasp/Grasp.hh
|
el-cangrejo/grasp
|
492dd14928b0072beecf752075b712db96f06834
|
[
"MIT"
] | 70
|
2018-10-17T17:37:22.000Z
|
2022-02-28T15:19:47.000Z
|
grasp/Grasp.hh
|
el-cangrejo/grasp
|
492dd14928b0072beecf752075b712db96f06834
|
[
"MIT"
] | 3
|
2020-12-08T13:02:17.000Z
|
2022-02-22T11:59:00.000Z
|
grasp/Grasp.hh
|
el-cangrejo/grasp
|
492dd14928b0072beecf752075b712db96f06834
|
[
"MIT"
] | 17
|
2018-10-29T04:09:45.000Z
|
2022-03-19T11:34:55.000Z
|
/*!
\file grasp/Grasp.hh
\brief Grasp representation
\author João Borrego : jsbruglie
*/
#ifndef _GRASP_HH_
#define _GRASP_HH_
// Gazebo
#include <gazebo/gazebo_client.hh>
// Open YAML config files
#include "yaml-cpp/yaml.h"
// Debug streams
#include "debug.hh"
/// \brief Grasp representation class
class Grasp
{
// Public attributes
/// Grasp candidate name
public: int id;
/// Homogenous transform matrix from gripper to object reference frame
public: ignition::math::Matrix4d t_gripper_object;
/// Grasp success metric
public: double metric {false};
/// \brief Deafult constructor
public: Grasp(int id_=0);
/// \brief Constructor
/// \param t_gripper_object_ Transform matrix from gripper to object frame
/// \param id Grasp identifier
public: Grasp(ignition::math::Matrix4d t_gripper_object_, int id_=0);
/// \brief Load set of grasps from file
/// \param file_name Input file name
/// \param robot Target robot name
/// \param object_name Target object name
/// \param grasps Set of grasps retrieved from file
public: static void loadFromYml(
const std::string & file_name,
const std::string & robot,
const std::string & object_name,
std::vector<Grasp> & grasps);
/// \brief Export set of grasps to file
/// \param file_name Output file name
/// \param robot Target robot name
/// \param object_name Target object name
/// \param grasps Set of grasps to export to file
public: static void writeToYml(
const std::string & file_name,
const std::string & robot,
const std::string & object_name,
const std::vector<Grasp> & grasps);
};
#endif
| 27.903226
| 78
| 0.666474
|
el-cangrejo
|
42b16212868354cd93abf75113e378f0054ddfd3
| 3,500
|
cpp
|
C++
|
encoderlame.cpp
|
napcode/appstream
|
f4e5452e2f3cc68899a3a1e7033435a56d8a7c79
|
[
"MIT"
] | null | null | null |
encoderlame.cpp
|
napcode/appstream
|
f4e5452e2f3cc68899a3a1e7033435a56d8a7c79
|
[
"MIT"
] | null | null | null |
encoderlame.cpp
|
napcode/appstream
|
f4e5452e2f3cc68899a3a1e7033435a56d8a7c79
|
[
"MIT"
] | null | null | null |
#include "encoderlame.h"
EncoderLame::EncoderLame(EncoderConfig c)
: Encoder(c)
{
}
EncoderLame::~EncoderLame()
{
if (_lgf) {
lame_close(_lgf);
_lgf = 0;
}
delete[] _buffer;
}
bool EncoderLame::init()
{
if (isInitialized())
return true;
int rc;
_lgf = lame_init();
/*
emit message(QString::number(_config.numInChannels));
emit message(QString::number(_config.sampleRateIn));
emit message(QString::number(_config.sampleRateOut));
emit message(QString::number(_config.bitRate));
*/
lame_set_num_channels(_lgf, _config.numInChannels);
lame_set_in_samplerate(_lgf, _config.sampleRateIn);
lame_set_out_samplerate(_lgf, _config.sampleRateOut);
if (_config.mode == EncoderConfig::CBR)
lame_set_brate(_lgf, _config.quality);
else if (_config.mode == EncoderConfig::VBR) {
lame_set_VBR(_lgf, vbr_mtrh);
lame_set_VBR_quality(_lgf, 10.0 - 10 * _config.quality);
}
if ((rc = lame_init_params(_lgf)) < 0) {
emit error("unable to init lame");
emit error("Channels " + QString::number(_config.numInChannels));
emit error("RateIn " + QString::number(_config.sampleRateIn));
emit error("RateOut " + QString::number(_config.sampleRateOut));
emit error("BitRate " + QString::number(_config.quality));
return false;
}
else {
_initialized = true;
emit message("Lame initialized");
emit message("Version: " + getVersion());
}
// default output buffer size. see lame.h
resize(DSP_BLOCKSIZE);
return true;
}
void EncoderLame::setup()
{
// nothing to do here
}
void EncoderLame::encode(sample_t* buffer, uint32_t samples)
{
int rc;
if (samples == 0 || !isInitialized())
return;
if (_allocedFrames < samples)
resize(samples);
if (_config.numInChannels == 2)
rc = lame_encode_buffer_interleaved_ieee_double(_lgf, buffer, samples / _config.numInChannels, reinterpret_cast<unsigned char*>(_buffer), _bufferSize);
else if (_config.numInChannels == 1)
rc = lame_encode_buffer_ieee_double(_lgf, buffer, buffer, samples, reinterpret_cast<unsigned char*>(_buffer), _bufferSize);
else {
emit error("Lame can't handle more than 2 channels.");
assert(0);
}
if (rc >= 0)
_bufferValid = rc;
else {
_bufferValid = 0;
handleRC(rc);
}
}
void EncoderLame::finalize()
{
}
void EncoderLame::handleRC(int rc) const
{
switch (rc) {
case -1:
emit error("Lame: out buffer to small");
break;
case -2:
emit error("Lame: unable to allocate memory");
break;
case -3:
emit error("Lame: init not called. Should never happen.");
break;
case -4:
emit error("Lame: psycho acoustic problem occurred");
break;
default:
emit error("Lame: unknown error occurred. ");
}
}
void EncoderLame::resize(uint32_t newSize)
{
delete[] _buffer;
_allocedFrames = newSize;
// default output buffer size. see lame.h
_bufferSize = 1.25 * _allocedFrames + 7200;
_buffer = new char[_bufferSize];
}
QString EncoderLame::getVersion() const
{
QString info;
if (!isInitialized()) {
emit error("lame is not initialized. Can't get version info.");
return info;
}
QString lame_version(get_lame_version());
return lame_version;
}
| 27.559055
| 159
| 0.624571
|
napcode
|
42b2b194989dff2b2dd44420dd2d5941c206551b
| 3,702
|
hpp
|
C++
|
src/integration/IntegrationNSphere.hpp
|
FrancoisGaits/utk
|
8c408dd79635f98c46ed075c098f15e23972aad0
|
[
"BSD-2-Clause-FreeBSD"
] | 44
|
2018-01-09T19:56:29.000Z
|
2022-03-03T06:38:54.000Z
|
src/integration/IntegrationNSphere.hpp
|
FrancoisGaits/utk
|
8c408dd79635f98c46ed075c098f15e23972aad0
|
[
"BSD-2-Clause-FreeBSD"
] | 16
|
2018-01-29T18:01:42.000Z
|
2022-03-31T07:01:09.000Z
|
src/integration/IntegrationNSphere.hpp
|
FrancoisGaits/utk
|
8c408dd79635f98c46ed075c098f15e23972aad0
|
[
"BSD-2-Clause-FreeBSD"
] | 12
|
2018-03-14T00:24:14.000Z
|
2022-03-03T06:40:07.000Z
|
/*
* Hélène Perrier helene.perrier@liris.cnrs.fr
* and David Coeurjolly david.coeurjolly@liris.cnrs.fr
*
* Copyright (c) 2018 CNRS Université de Lyon
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those
* of the authors and should not be interpreted as representing official policies,
* either expressed or implied, of the UTK project.
*/
#ifndef _UTK_INTEGRATION_DISK_ND_
#define _UTK_INTEGRATION_DISK_ND_
#include "../io/messageStream.hpp"
#include "../pointsets/Pointset.hpp"
#include <cmath>
#include <array>
namespace utk
{
class IntegrationNSphere
{
public:
IntegrationNSphere() { m_radius = 0.25; }
void setRadius(double arg_radius) { m_radius = arg_radius; }
template<unsigned int D, typename T, typename P>
bool compute(const Pointset<D, T, P>& arg_pointset, double& integration_value, double& analytic_value)
{
if(m_radius <= 0 && m_radius >= 0.5)
{
ERROR("IntegrationNSphere::compute radius must be in ]0, 0.5[");
return false;
}
std::array<double, D> nd_domain_extent;
for(unsigned int d=0; d<D; d++)
{
nd_domain_extent[d] = (arg_pointset.domain.pMax.pos() - arg_pointset.domain.pMin.pos())[d];
if(nd_domain_extent[d] == 0)
{
WARNING("IntegrationNSphere::compute domain extent is 0 on at least one dimension, scaling might fail");
}
if(nd_domain_extent[d] < 0)
{
ERROR("IntegrationNSphere::compute domain extent is negative on at least one dimension");
return false;
}
}
analytic_value = analyticIntegrand(D);
integration_value = 0;
for(uint i=0; i<arg_pointset.size(); i++)
{
Point<D, double> pt;
for(unsigned int d=0; d<D; d++)
pt.pos()[d] = -0.5 + (arg_pointset[i].pos() - arg_pointset.domain.pMin.pos())[d] / nd_domain_extent[d];
integration_value += sampleIntegrand<D>(pt);
}
integration_value /= (double)arg_pointset.size();
return true;
}
double analyticIntegrand(uint dim)
{
double num = pow(M_PI, (double)dim/2.0);
double denom = tgamma(((double)dim/2.0) + 1);
return (num/denom)*pow(m_radius, dim);
}
template<uint D>
double sampleIntegrand(Point<D, double>& pt)
{
double l = pt.pos().length();
if(l < m_radius)
return 1;
return 0;
}
double m_radius;
};
}//end namespace
#endif
| 32.473684
| 105
| 0.700702
|
FrancoisGaits
|
42b5735b3471a7446cdf2188bd48234ed6b3765c
| 3,014
|
hpp
|
C++
|
libbitcoin/include/bitcoin/constants.hpp
|
mousewu/bcclient
|
64ee1f6f8337103d40a4a0c3dfb73cabcd09a04c
|
[
"MIT"
] | 8
|
2019-05-31T01:37:08.000Z
|
2021-10-19T05:52:45.000Z
|
libbitcoin/include/bitcoin/constants.hpp
|
mousewu/bcclient
|
64ee1f6f8337103d40a4a0c3dfb73cabcd09a04c
|
[
"MIT"
] | 3
|
2017-12-18T17:27:09.000Z
|
2018-01-15T16:50:05.000Z
|
libbitcoin/include/bitcoin/constants.hpp
|
mousewu/bcclient
|
64ee1f6f8337103d40a4a0c3dfb73cabcd09a04c
|
[
"MIT"
] | 5
|
2018-01-09T15:05:55.000Z
|
2020-12-17T13:27:25.000Z
|
/*
* Copyright (c) 2011-2013 libbitcoin developers (see AUTHORS)
*
* This file is part of libbitcoin.
*
* libbitcoin is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef LIBBITCOIN_CONSTANTS_HPP
#define LIBBITCOIN_CONSTANTS_HPP
#include <cstdint>
#include <bitcoin/utility/big_number.hpp>
namespace libbitcoin {
constexpr uint32_t protocol_version = 60000;
constexpr uint64_t block_reward = 50;
// 210000 ~ 4 years / 10 minutes
constexpr uint64_t reward_interval = 210000;
constexpr size_t coinbase_maturity = 100;
#ifdef ENABLE_TESTNET
constexpr uint32_t protocol_port = 18333;
#else
constexpr uint32_t protocol_port = 8333;
#endif
// Threshold for nLockTime: below this value it is
// interpreted as block number, otherwise as UNIX timestamp.
// Tue Nov 5 00:53:20 1985 UTC
constexpr uint32_t locktime_threshold = 500000000;
constexpr uint64_t max_money_recursive(uint64_t current)
{
return (current > 0) ?
current + max_money_recursive(current >> 1) : 0;
}
constexpr uint64_t coin_price(uint64_t value=1)
{
return value * 100000000;
}
constexpr uint64_t max_money()
{
return reward_interval * max_money_recursive(coin_price(block_reward));
}
const hash_digest null_hash{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
const short_hash null_short_hash{0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
constexpr uint32_t max_bits = 0x1d00ffff;
big_number max_target();
uint32_t magic_value();
constexpr uint32_t max_index = std::numeric_limits<uint32_t>::max();
// Every two weeks we readjust target
constexpr uint64_t target_timespan = 14 * 24 * 60 * 60;
// Aim for blocks every 10 mins
constexpr uint64_t target_spacing = 10 * 60;
// Two weeks worth of blocks = readjust interval = 2016
constexpr uint64_t readjustment_interval = target_timespan / target_spacing;
#ifdef ENABLE_TESTNET
// Block 514 is the first block after Feb 15 2014.
// Testnet started bip16 before mainnet.
constexpr uint32_t bip16_switchover_timestamp = 1333238400;
constexpr uint32_t bip16_switchover_height = 514;
#else
// April 1 2012
constexpr uint32_t bip16_switchover_timestamp = 1333238400;
constexpr uint32_t bip16_switchover_height = 173805;
#endif
} // namespace libbitcoin
#endif
| 31.395833
| 76
| 0.736231
|
mousewu
|
42b713a94aed7da16b1cf74cfd6e5e60937a2e40
| 5,781
|
cc
|
C++
|
tensorflow_io/core/azure/azfs/azfs_client.cc
|
pshiko/io
|
a1793e6b41ed7a8db572249aba15a8e513a348a5
|
[
"Apache-2.0"
] | 1
|
2020-01-20T17:48:31.000Z
|
2020-01-20T17:48:31.000Z
|
tensorflow_io/core/azure/azfs/azfs_client.cc
|
pshiko/io
|
a1793e6b41ed7a8db572249aba15a8e513a348a5
|
[
"Apache-2.0"
] | null | null | null |
tensorflow_io/core/azure/azfs/azfs_client.cc
|
pshiko/io
|
a1793e6b41ed7a8db572249aba15a8e513a348a5
|
[
"Apache-2.0"
] | null | null | null |
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow_io/core/azure/azfs/azfs_client.h"
#include "logging.h"
namespace tensorflow {
namespace io {
/// \brief Splits a Azure path to a account, container and object.
///
/// For example,
/// "az://account-name.blob.core.windows.net/container/path/to/file.txt" gets
/// split into "account-name", "container" and "path/to/file.txt".
Status ParseAzBlobPath(StringPiece fname, bool empty_object_ok,
std::string *account, std::string *container,
std::string *object) {
if (!account || !object) {
return errors::Internal("account and object cannot be null.");
}
StringPiece scheme, accountp, objectp;
io::ParseURI(fname, &scheme, &accountp, &objectp);
if (scheme != "az") {
return errors::InvalidArgument(
"Azure Blob Storage path doesn't start with 'az://': ", fname);
}
// Consume blob.core.windows.net if it exists
absl::ConsumeSuffix(&accountp, kAzBlobEndpoint);
if (accountp.empty() || accountp.compare(".") == 0) {
return errors::InvalidArgument(
"Azure Blob Storage path doesn't contain a account name: ", fname);
}
*account = std::string(accountp);
absl::ConsumePrefix(&objectp, "/");
auto pos = objectp.find('/');
if (pos == std::string::npos) {
*container = objectp.data();
*object = "";
} else {
*container = std::string(objectp.substr(0, pos));
*object = std::string(objectp.substr(pos + 1));
}
return Status::OK();
}
std::string errno_to_string() {
switch (errno) {
/* common errors */
case invalid_parameters:
return "invalid_parameters";
/* client level */
case client_init_fail:
return "client_init_fail";
case client_already_init:
return "client_already_init";
case client_not_init:
return "client_not_init";
/* container level */
case container_already_exists:
return "container_already_exists";
case container_not_exists:
return "container_not_exists";
case container_name_invalid:
return "container_name_invalid";
case container_create_fail:
return "container_create_fail";
case container_delete_fail:
return "container_delete_fail";
/* blob level */
case blob__already_exists:
return "blob__already_exists";
case blob_not_exists:
return "blob_not_exists";
case blob_name_invalid:
return "blob_name_invalid";
case blob_delete_fail:
return "blob_delete_fail";
case blob_list_fail:
return "blob_list_fail";
case blob_copy_fail:
return "blob_copy_fail";
case blob_no_content_range:
return "blob_no_content_range";
/* unknown error */
case unknown_error:
default:
return "unknown_error - " + std::to_string(errno);
}
}
std::shared_ptr<azure::storage_lite::storage_credential> get_credential(
const std::string &account) {
const auto key = std::getenv("TF_AZURE_STORAGE_KEY");
if (key != nullptr) {
return std::make_shared<azure::storage_lite::shared_key_credential>(account,
key);
} else {
return std::make_shared<azure::storage_lite::anonymous_credential>();
}
}
azure::storage_lite::blob_client_wrapper CreateAzBlobClientWrapper(
const std::string &account) {
azure::storage_lite::logger::set_logger(
[](azure::storage_lite::log_level level, const std::string &log_msg) {
switch (level) {
case azure::storage_lite::log_level::info:
_TF_LOG_INFO << log_msg;
break;
case azure::storage_lite::log_level::error:
case azure::storage_lite::log_level::critical:
_TF_LOG_ERROR << log_msg;
break;
case azure::storage_lite::log_level::warn:
_TF_LOG_WARNING << log_msg;
break;
case azure::storage_lite::log_level::trace:
case azure::storage_lite::log_level::debug:
default:
break;
}
});
const auto use_dev_account = std::getenv("TF_AZURE_USE_DEV_STORAGE");
if (use_dev_account != nullptr) {
auto storage_account =
azure::storage_lite::storage_account::development_storage_account();
auto blob_client =
std::make_shared<azure::storage_lite::blob_client>(storage_account, 10);
azure::storage_lite::blob_client_wrapper blob_client_wrapper(blob_client);
return blob_client_wrapper;
}
const auto use_http_env = std::getenv("TF_AZURE_STORAGE_USE_HTTP");
const auto use_https = use_http_env == nullptr;
const auto blob_endpoint =
std::string(std::getenv("TF_AZURE_STORAGE_BLOB_ENDPOINT") ?: "");
auto credentials = get_credential(account);
auto storage_account = std::make_shared<azure::storage_lite::storage_account>(
account, credentials, use_https, blob_endpoint);
auto blob_client =
std::make_shared<azure::storage_lite::blob_client>(storage_account, 10);
azure::storage_lite::blob_client_wrapper blob_client_wrapper(blob_client);
return blob_client_wrapper;
}
} // namespace io
} // namespace tensorflow
| 34.207101
| 80
| 0.669953
|
pshiko
|
42b976415bed9557543a9e1dd17c9c84c33fe02a
| 593
|
cpp
|
C++
|
03/exam03.cpp
|
Sadik326-ctrl/computer_programming
|
cbae264ffa04fc487008fa6a0a32e0a1a316e01e
|
[
"MIT"
] | null | null | null |
03/exam03.cpp
|
Sadik326-ctrl/computer_programming
|
cbae264ffa04fc487008fa6a0a32e0a1a316e01e
|
[
"MIT"
] | null | null | null |
03/exam03.cpp
|
Sadik326-ctrl/computer_programming
|
cbae264ffa04fc487008fa6a0a32e0a1a316e01e
|
[
"MIT"
] | null | null | null |
// Demonstration of compound assignments
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
float x, y;
cout << "\n Please enter a starting value:
cin >> x;
";
cout << "\n Please enter the increment value: ";
cin >> y;
x += y;
cout << "\n And now multiplication! ";
cout << "\n Please enter a factor: ";
cin >> y;
x *= y;
cout << "\n Finally division.";
cout << "\n Please supply a divisor: ";
cin >> y;
x /= y;
cout << "\n And this is "
<< "your current lucky number: "
// without digits after
// the decimal point:
<< fixed << setprecision(0)
<< x << endl;
return 0;
}
| 19.766667
| 48
| 0.625632
|
Sadik326-ctrl
|
42b9e0ae70299b5c0c42b2aa5b291bf768be26c4
| 485
|
cpp
|
C++
|
Part_Fourteen/BasePtrDerivedObj.cpp
|
ayushpareek179/CPP-course
|
b2b8b8d2dd06cd772e3c9838abd5b841237bb306
|
[
"MIT"
] | null | null | null |
Part_Fourteen/BasePtrDerivedObj.cpp
|
ayushpareek179/CPP-course
|
b2b8b8d2dd06cd772e3c9838abd5b841237bb306
|
[
"MIT"
] | null | null | null |
Part_Fourteen/BasePtrDerivedObj.cpp
|
ayushpareek179/CPP-course
|
b2b8b8d2dd06cd772e3c9838abd5b841237bb306
|
[
"MIT"
] | null | null | null |
//To depict pointer to a derived class objeof base class type
#include <iostream>
using namespace std;
class parent
{
public:
void func()
{
cout<<"Base's function\n";
}
};
class child:public parent
{
public:
void meth()
{
cout<<"Derived's function\n";
}
};
int main()
{
child c;
//parent* pa = &c; - Works as well
parent* p = new child();
p->func();
//p->meth() - doesn't work
//c.meth(); - works
return 0;
}
| 16.724138
| 61
| 0.548454
|
ayushpareek179
|
42bf6c136b9f6b914ccb85044ba0132dc453ba41
| 470
|
cpp
|
C++
|
bzoj/1261.cpp
|
swwind/code
|
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
|
[
"WTFPL"
] | 3
|
2017-09-17T09:12:50.000Z
|
2018-04-06T01:18:17.000Z
|
bzoj/1261.cpp
|
swwind/code
|
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
|
[
"WTFPL"
] | null | null | null |
bzoj/1261.cpp
|
swwind/code
|
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
|
[
"WTFPL"
] | null | null | null |
#include <bits/stdc++.h>
#define ll long long
using namespace std;
int a[5050], len, n;
int mul(int val){
for(int i = 1; i <= len; i++)
a[i]*=val;
for(int i = 1; i <= len; i++){
a[i+1]+=a[i]/10;
a[i]%=10;
}
if(a[len+1])len++;
}
int main(){
scanf("%d", &n);
a[len=1]=1;
while(n > 4) mul(3), n-=3; mul(n);
printf("%d\n", len);
if(len > 100) for(int i = 0; i < 100; i++) putchar(a[len-i]+'0');
else for(int i = len; i; i--) putchar(a[i]+'0');
return 0;
}
| 19.583333
| 66
| 0.510638
|
swwind
|
42cc99107701f2f6cd3ea17c5e1ebb7147bd583b
| 340
|
cpp
|
C++
|
Proyecto_Final-Jorge_Pastor_V2/Trabajo de informatica/Trabajo_InformaticaI/propietarios.cpp
|
jorgepastor5/Spaceships-shop-manager
|
51ec0aad6042f4a247a4d385c7ff4ab9233f7c35
|
[
"MIT"
] | null | null | null |
Proyecto_Final-Jorge_Pastor_V2/Trabajo de informatica/Trabajo_InformaticaI/propietarios.cpp
|
jorgepastor5/Spaceships-shop-manager
|
51ec0aad6042f4a247a4d385c7ff4ab9233f7c35
|
[
"MIT"
] | null | null | null |
Proyecto_Final-Jorge_Pastor_V2/Trabajo de informatica/Trabajo_InformaticaI/propietarios.cpp
|
jorgepastor5/Spaceships-shop-manager
|
51ec0aad6042f4a247a4d385c7ff4ab9233f7c35
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <string.h>
#include "propietarios.h"
#include <aplicacion.h>
#include <naves.h>
using namespace std;
propietarios::propietarios(){
}
void propietarios::setPlaneta(string planeta){
this->planeta = planeta;
}
string propietarios::getPlaneta(){
return planeta;
}
propietarios::~propietarios(){
}
| 12.592593
| 46
| 0.714706
|
jorgepastor5
|
42cd05326a8fba4bdf024c553065cb2b6aaab797
| 1,716
|
cpp
|
C++
|
model/src/ConstraintBlockImpl.cpp
|
mballance-sf/open-ps
|
a5ed44ce30bfe59462801ca7de4361d16950bcd2
|
[
"Apache-2.0"
] | null | null | null |
model/src/ConstraintBlockImpl.cpp
|
mballance-sf/open-ps
|
a5ed44ce30bfe59462801ca7de4361d16950bcd2
|
[
"Apache-2.0"
] | null | null | null |
model/src/ConstraintBlockImpl.cpp
|
mballance-sf/open-ps
|
a5ed44ce30bfe59462801ca7de4361d16950bcd2
|
[
"Apache-2.0"
] | null | null | null |
/*
* ConstraintBlockImpl.cpp
*
*
* Copyright 2016 Mentor Graphics Corporation
* All Rights Reserved Worldwide
*
* Licensed under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in
* writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See
* the License for the specific language governing
* permissions and limitations under the License.
*
* Created on: May 4, 2016
* Author: ballance
*/
#include "ConstraintBlockImpl.h"
ConstraintBlockImpl::ConstraintBlockImpl(const std::string &name) :
BaseItemImpl(IBaseItem::TypeConstraint), NamedItemImpl(name) {
}
ConstraintBlockImpl::~ConstraintBlockImpl() {
// TODO Auto-generated destructor stub
}
void ConstraintBlockImpl::add(IConstraint *c) {
if (c) {
c->setParent(this);
m_constraints.push_back(c);
}
}
void ConstraintBlockImpl::add(const std::vector<IConstraint *> &cl) {
std::vector<IConstraint *>::const_iterator it;
for (it=cl.begin(); it!=cl.end(); it++) {
(*it)->setParent(this);
m_constraints.push_back(*it);
}
}
IBaseItem *ConstraintBlockImpl::clone() const {
ConstraintBlockImpl *ret = new ConstraintBlockImpl(getName());
for (std::vector<IConstraint *>::const_iterator it=getConstraints().begin();
it!=getConstraints().end(); it++) {
ret->add(dynamic_cast<IConstraint *>((*it)->clone()));
}
return ret;
}
| 26.4
| 78
| 0.685897
|
mballance-sf
|
42ce15e3ef1c818c6fa7f3164b3ea50efac752c3
| 720
|
cpp
|
C++
|
0-100/7/main.cpp
|
KevinEsh/LeetCode-Problems
|
7e29509ad1cdc907bbba339f82e89f9e210e8249
|
[
"MIT"
] | null | null | null |
0-100/7/main.cpp
|
KevinEsh/LeetCode-Problems
|
7e29509ad1cdc907bbba339f82e89f9e210e8249
|
[
"MIT"
] | null | null | null |
0-100/7/main.cpp
|
KevinEsh/LeetCode-Problems
|
7e29509ad1cdc907bbba339f82e89f9e210e8249
|
[
"MIT"
] | null | null | null |
#include <string>
#include <iostream>
#include <algorithm>
#define lower -2147483648
#define upper 2147483647
class Solution
{
public:
int reverse(int x)
{
std::string sx = x < 0 ? "-" : "";
sx += std::to_string(abs(x));
if (x < 0)
{
std::reverse(sx.begin() + 1, sx.end());
}
else
{
std::reverse(sx.begin(), sx.end());
}
long long lx = stol(sx);
if (lower <= lx && lx <= upper)
{
return (int)lx;
}
return 0;
}
};
int main()
{
Solution model = Solution();
int reversed = model.reverse(-124265343);
std::cout << reversed << std::endl;
return 0;
}
| 16.744186
| 51
| 0.475
|
KevinEsh
|
42d20121235ebecbae7e13193478f3f5503966f2
| 619
|
cpp
|
C++
|
max_profit.cpp
|
shirishbahirat/algorithm
|
ec743d4c16ab4f429f22bd6f71540341b3905b3b
|
[
"Apache-2.0"
] | null | null | null |
max_profit.cpp
|
shirishbahirat/algorithm
|
ec743d4c16ab4f429f22bd6f71540341b3905b3b
|
[
"Apache-2.0"
] | null | null | null |
max_profit.cpp
|
shirishbahirat/algorithm
|
ec743d4c16ab4f429f22bd6f71540341b3905b3b
|
[
"Apache-2.0"
] | null | null | null |
#include <iostream>
#include <vector>
using namespace std;
class Solution
{
public:
int maxProfit(vector<int> &prices)
{
int minprice = 0x7FFFFFFF;
int maxprofit = 0;
for (int i = 0; i < prices.size(); i++)
{
if (prices[i] < minprice)
minprice = prices[i];
else if (prices[i] - minprice > maxprofit)
maxprofit = prices[i] - minprice;
}
return maxprofit;
}
};
int main(int argc, char const *argv[])
{
Solution *obj = new Solution();
vector<int> prices = {7, 1, 5, 3, 6, 4};
int profit = obj->maxProfit(prices);
cout << profit << endl;
return 0;
}
| 18.205882
| 48
| 0.588045
|
shirishbahirat
|
42d36a7ff407d996315af2f45511739d597bc098
| 8,305
|
hpp
|
C++
|
SDK/PUBG_GameplayTasks_classes.hpp
|
realrespecter/PUBG-FULL-SDK
|
5e2b0f103c74c95d2329c4c9dfbfab48aa0da737
|
[
"MIT"
] | 7
|
2019-03-06T11:04:52.000Z
|
2019-07-10T20:00:51.000Z
|
SDK/PUBG_GameplayTasks_classes.hpp
|
realrespecter/PUBG-FULL-SDK
|
5e2b0f103c74c95d2329c4c9dfbfab48aa0da737
|
[
"MIT"
] | null | null | null |
SDK/PUBG_GameplayTasks_classes.hpp
|
realrespecter/PUBG-FULL-SDK
|
5e2b0f103c74c95d2329c4c9dfbfab48aa0da737
|
[
"MIT"
] | 10
|
2019-03-06T11:53:46.000Z
|
2021-02-18T14:01:11.000Z
|
#pragma once
// PUBG FULL SDK - Generated By Respecter (5.3.4.11 [06/03/2019]) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "PUBG_GameplayTasks_structs.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// Class GameplayTasks.GameplayTaskResource
// 0x0010 (0x0040 - 0x0030)
class UGameplayTaskResource : public UObject
{
public:
int ManualResourceID; // 0x0030(0x0004) (Edit, BlueprintVisible, BlueprintReadOnly, ZeroConstructor, Config, DisableEditOnInstance, IsPlainOldData)
int8_t AutoResourceID; // 0x0034(0x0001) (ZeroConstructor, IsPlainOldData)
unsigned char UnknownData00[0x3]; // 0x0035(0x0003) MISSED OFFSET
unsigned char bManuallySetID : 1; // 0x0038(0x0001) (Edit, DisableEditOnInstance)
unsigned char UnknownData01[0x7]; // 0x0039(0x0007) MISSED OFFSET
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("Class GameplayTasks.GameplayTaskResource");
return ptr;
}
};
// Class GameplayTasks.GameplayTask
// 0x0040 (0x0070 - 0x0030)
class UGameplayTask : public UObject
{
public:
unsigned char UnknownData00[0x8]; // 0x0030(0x0008) MISSED OFFSET
struct FName InstanceName; // 0x0038(0x0008) (ZeroConstructor, IsPlainOldData)
unsigned char UnknownData01[0x2]; // 0x0040(0x0002) MISSED OFFSET
ETaskResourceOverlapPolicy ResourceOverlapPolicy; // 0x0042(0x0001) (ZeroConstructor, Config, IsPlainOldData)
unsigned char UnknownData02[0x25]; // 0x0043(0x0025) MISSED OFFSET
class UGameplayTask* ChildTask; // 0x0068(0x0008) (ZeroConstructor, IsPlainOldData)
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("Class GameplayTasks.GameplayTask");
return ptr;
}
void ReadyForActivation();
void GenericGameplayTaskDelegate__DelegateSignature();
void EndTask();
};
// Class GameplayTasks.GameplayTaskOwnerInterface
// 0x0000 (0x0030 - 0x0030)
class UGameplayTaskOwnerInterface : public UInterface
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("Class GameplayTasks.GameplayTaskOwnerInterface");
return ptr;
}
};
// Class GameplayTasks.GameplayTask_ClaimResource
// 0x0000 (0x0070 - 0x0070)
class UGameplayTask_ClaimResource : public UGameplayTask
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("Class GameplayTasks.GameplayTask_ClaimResource");
return ptr;
}
void ReadyForActivation();
void GenericGameplayTaskDelegate__DelegateSignature();
void EndTask();
};
// Class GameplayTasks.GameplayTask_SpawnActor
// 0x0040 (0x00B0 - 0x0070)
class UGameplayTask_SpawnActor : public UGameplayTask
{
public:
struct FScriptMulticastDelegate SUCCESS; // 0x0070(0x0010) (ZeroConstructor, InstancedReference, BlueprintAssignable)
struct FScriptMulticastDelegate DidNotSpawn; // 0x0080(0x0010) (ZeroConstructor, InstancedReference, BlueprintAssignable)
unsigned char UnknownData00[0x18]; // 0x0090(0x0018) MISSED OFFSET
class UClass* ClassToSpawn; // 0x00A8(0x0008) (ZeroConstructor, IsPlainOldData)
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("Class GameplayTasks.GameplayTask_SpawnActor");
return ptr;
}
class UGameplayTask_SpawnActor* STATIC_SpawnActor(TScriptInterface<class UGameplayTaskOwnerInterface>* TaskOwner, struct FVector* SpawnLocation, struct FRotator* SpawnRotation, class UClass** Class, bool* bSpawnOnlyOnAuthority);
void FinishSpawningActor(class UObject** WorldContextObject, class AActor** SpawnedActor);
bool BeginSpawningActor(class UObject** WorldContextObject, class AActor** SpawnedActor);
};
// Class GameplayTasks.GameplayTask_TimeLimitedExecution
// 0x0030 (0x00A0 - 0x0070)
class UGameplayTask_TimeLimitedExecution : public UGameplayTask
{
public:
struct FScriptMulticastDelegate OnFinished; // 0x0070(0x0010) (ZeroConstructor, InstancedReference, BlueprintAssignable)
struct FScriptMulticastDelegate OnTimeExpired; // 0x0080(0x0010) (ZeroConstructor, InstancedReference, BlueprintAssignable)
unsigned char UnknownData00[0x10]; // 0x0090(0x0010) MISSED OFFSET
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("Class GameplayTasks.GameplayTask_TimeLimitedExecution");
return ptr;
}
void TaskFinishDelegate__DelegateSignature();
};
// Class GameplayTasks.GameplayTask_WaitDelay
// 0x0018 (0x0088 - 0x0070)
class UGameplayTask_WaitDelay : public UGameplayTask
{
public:
struct FScriptMulticastDelegate OnFinish; // 0x0070(0x0010) (ZeroConstructor, InstancedReference, BlueprintAssignable)
unsigned char UnknownData00[0x8]; // 0x0080(0x0008) MISSED OFFSET
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("Class GameplayTasks.GameplayTask_WaitDelay");
return ptr;
}
class UGameplayTask_WaitDelay* STATIC_TaskWaitDelay(TScriptInterface<class UGameplayTaskOwnerInterface>* TaskOwner, float* Time, unsigned char* Priority);
void TaskDelayDelegate__DelegateSignature();
};
// Class GameplayTasks.GameplayTasksComponent
// 0x0070 (0x0260 - 0x01F0)
class UGameplayTasksComponent : public UActorComponent
{
public:
unsigned char UnknownData00[0x8]; // 0x01F0(0x0008) MISSED OFFSET
TArray<class UGameplayTask*> SimulatedTasks; // 0x01F8(0x0010) (Net, ZeroConstructor)
TArray<class UGameplayTask*> TaskPriorityQueue; // 0x0208(0x0010) (ZeroConstructor)
unsigned char UnknownData01[0x10]; // 0x0218(0x0010) MISSED OFFSET
TArray<class UGameplayTask*> TickingTasks; // 0x0228(0x0010) (ZeroConstructor)
unsigned char UnknownData02[0x8]; // 0x0238(0x0008) MISSED OFFSET
struct FScriptMulticastDelegate OnClaimedResourcesChange; // 0x0240(0x0010) (BlueprintVisible, ZeroConstructor, InstancedReference)
unsigned char UnknownData03[0x10]; // 0x0250(0x0010) MISSED OFFSET
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("Class GameplayTasks.GameplayTasksComponent");
return ptr;
}
void OnRep_SimulatedTasks();
EGameplayTaskRunResult STATIC_K2_RunGameplayTask(TScriptInterface<class UGameplayTaskOwnerInterface>* TaskOwner, class UGameplayTask** Task, unsigned char* Priority, TArray<class UClass*>* AdditionalRequiredResources, TArray<class UClass*>* AdditionalClaimedResources);
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 43.710526
| 270
| 0.586635
|
realrespecter
|
42d3a2f68e017ecba874aac3207ad55e3241fd65
| 981
|
cpp
|
C++
|
src/sharding/hasher.cpp
|
oystr-foss/proxy-load-balancer
|
14a58a1db4a189f27d0671cb89cfa4a06bd8b415
|
[
"BSL-1.0"
] | 9
|
2020-10-06T16:36:11.000Z
|
2021-07-25T15:06:25.000Z
|
src/sharding/hasher.cpp
|
oystr-foss/proxy-load-balancer
|
14a58a1db4a189f27d0671cb89cfa4a06bd8b415
|
[
"BSL-1.0"
] | null | null | null |
src/sharding/hasher.cpp
|
oystr-foss/proxy-load-balancer
|
14a58a1db4a189f27d0671cb89cfa4a06bd8b415
|
[
"BSL-1.0"
] | null | null | null |
//
// Created by realngnx on 11/06/2021.
//
#include <openssl/sha.h>
#include <openssl/md5.h>
#include "./hasher.hpp"
long Digest::to_md5_hash(std::string key) {
const char * hashed = reinterpret_cast<const char *>(md5(key));
return calculate_hash(hashed);
}
long Digest::to_sha256_hash(std::string key) {
const char * hashed = reinterpret_cast<const char *>(sha256(key));
return calculate_hash(hashed);
}
long Digest::calculate_hash(const char *hashed) {
long hash = 0;
for (int i = 0; i < 4; i++) {
hash <<= 8;
hash |= ((int) hashed[i]) & 0xFF;
}
return hash;
}
const unsigned char * Digest::sha256(const std::string &key) {
char const *c = key.c_str();
return SHA256(reinterpret_cast<const unsigned char *>(c), key.length(), nullptr);
}
const unsigned char * Digest::md5(const std::string &key) {
char const *c = key.c_str();
return MD5(reinterpret_cast<const unsigned char *>(c), key.length(), nullptr);
}
| 25.815789
| 85
| 0.64526
|
oystr-foss
|
42d504427440ff4dcf5cf5f7baa66f1310cf7b39
| 917
|
cpp
|
C++
|
AddIn/DemoAddIn/cpp/DemoAddIn/EdgeBarDialog.cpp
|
XelaNimed/Samples
|
2b509c985d99b53a9de1e2fb377a5a54dae43987
|
[
"MIT"
] | 34
|
2015-06-08T05:10:28.000Z
|
2022-02-08T20:15:42.000Z
|
AddIn/DemoAddIn/cpp/DemoAddIn/EdgeBarDialog.cpp
|
kabircosta/Samples
|
3ffe1b268d49ec63686078d5c4f4d6eccb8f6f5f
|
[
"MIT"
] | 1
|
2019-04-03T06:32:23.000Z
|
2019-04-03T06:32:23.000Z
|
AddIn/DemoAddIn/cpp/DemoAddIn/EdgeBarDialog.cpp
|
kabircosta/Samples
|
3ffe1b268d49ec63686078d5c4f4d6eccb8f6f5f
|
[
"MIT"
] | 44
|
2015-03-26T17:29:45.000Z
|
2021-12-29T03:41:29.000Z
|
// EdgeBarDialog.cpp : implementation file
//
#include "stdafx.h"
#include "DemoAddIn.h"
#include "EdgeBarDialog.h"
#include "afxdialogex.h"
// CEdgeBarDialog dialog
IMPLEMENT_DYNAMIC(CEdgeBarDialog, CDialogEx)
CEdgeBarDialog::CEdgeBarDialog(CWnd* pParent /*=NULL*/)
: CDialogEx(CEdgeBarDialog::IDD, pParent)
{
}
CEdgeBarDialog::~CEdgeBarDialog()
{
}
void CEdgeBarDialog::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
DDX_Control(pDX, IDC_LIST1, m_listView);
}
BEGIN_MESSAGE_MAP(CEdgeBarDialog, CDialogEx)
ON_WM_SIZE()
END_MESSAGE_MAP()
// CEdgeBarDialog message handlers
void CEdgeBarDialog::OnSize(UINT nType, int cx, int cy)
{
CDialogEx::OnSize(nType, cx, cy);
// TODO: Add your message handler code here
RECT rect;
// Get the dialog rectangle.
GetClientRect(&rect);
// Resize CListCtrl.
if (m_listView.m_hWnd != NULL)
{
m_listView.MoveWindow(&rect, TRUE);
}
}
| 16.981481
| 55
| 0.742639
|
XelaNimed
|
42da23d3f9b47e5504e83b1de7b6fb30fa6face1
| 6,368
|
cpp
|
C++
|
analysis_pipelines/scripts/scVILP/scripts/PerfectPhy/tools/convert.cpp
|
ProSolo/benchmarking_prosolo
|
60fc1fcc990be9eedcdf024670fa81e68c0d3e2f
|
[
"MIT"
] | 2
|
2020-04-29T02:56:42.000Z
|
2021-03-04T21:17:15.000Z
|
analysis_pipelines/scripts/scVILP/scripts/PerfectPhy/tools/convert.cpp
|
ProSolo/benchmarking_prosolo
|
60fc1fcc990be9eedcdf024670fa81e68c0d3e2f
|
[
"MIT"
] | null | null | null |
analysis_pipelines/scripts/scVILP/scripts/PerfectPhy/tools/convert.cpp
|
ProSolo/benchmarking_prosolo
|
60fc1fcc990be9eedcdf024670fa81e68c0d3e2f
|
[
"MIT"
] | null | null | null |
#include<vector>
#include<fstream>
#include<iostream>
#include<cctype>
using namespace std;
enum ArgError { ERROR = -1, QUIT = 0, NONE = 1 };
ArgError handleArguments(int argc, char** argv, char &dummychar, string &index, string &mapfile ) {
const char* helpmessage =
"Usage: ./convert.out [option] \n"
"\n"
"Options:\n"
"-h, --help Displays this message then quits.\n"
"-dummy CHAR Set CHAR as a dummy state (outputs -1).\n"
"-index I Set index of dataset as I (default is 1).\n"
"-mapfile FILE Writes the state mapping to FILE\n";
string arg;
for (int i = 1; i < argc; i++) {
if (argv[i][0] != '-') {
cerr << "Bad argument: " << argv[i] << " is not a flag" << endl;
return ERROR;
}
arg = argv[i];
if (arg.compare("-dummy") == 0) {
if (argc > i + 1) {
dummychar = argv[i+1][0];
if (!isgraph(dummychar)) {
cerr << "Bad argument: dummy character must be graphical" << endl;
return ERROR;
}
i++;
}
else {
cerr << "Bad argument: " << arg << " must precede a character" << endl;
return ERROR;
}
}
else if (arg.compare("-index") == 0) {
if (argc > i + 1) {
index = argv[i+1];
for (unsigned int j = 0; j < index.size(); j++)
if ( !( isdigit(index[j]) || (j == 0 && index[j] == '-' && index.size() > 1) ) ) {
cerr << "Bad argument: index must be an integer, not " << index << endl;
return ERROR;
}
i++;
}
else {
cerr << "Bad argument: " << arg << " must precede an integer" << endl;
return ERROR;
}
}
else if (arg.compare("-mapfile") == 0) {
if (argc > i + 1) {
mapfile = argv[i+1];
i++;
}
else {
cerr << "Bad argument: " << arg << " must precede a filename" << endl;
return ERROR;
}
}
else if (arg.compare("-h") == 0 || arg.compare("--help") == 0) {
cout << helpmessage;
return QUIT;
}
else {
cerr << "Bad argument: " << arg << " is not a valid flag" << endl;
return ERROR;
}
}
return NONE;
}
class Mapping {
private:
char c;
int n;
public:
Mapping(char in, int out):c(in), n(out) {}
void printTo(ostream& outf) const { outf << c << ' ' << n << ' '; }
};
#define readinto(var) do {\
cin >> var;\
if (!cin) {\
cerr << "Input error: " << #var << " could not be read" << endl;\
cerr << "Expected input:" << endl << "n m" << endl << "(n rows of: (10-char name) (m matrix cells...) )" << endl;\
return -1;\
}\
} while(false)
int main(int argc, char** argv) {
char dummychar = '\0';
string index;
string mapfile;
#define NAMEWIDTH 10
// improve io speed since not using C streams
ios_base::sync_with_stdio(false);
ArgError argerr = handleArguments(argc, argv, dummychar, index, mapfile);
if (argerr != NONE)
return argerr;
if (index.empty())
index = "1";
bool outputmap = (mapfile.size() > 0);
// read size of matrix
int n, m;
readinto(n);
readinto(m);
vector<vector<int> > data(n, vector<int>(m));
for (int i = 0; i < n; i++) {
vector<int>& row = data[i];
char cell;
// skip over the 10-character name
cin >> noskipws;
while (cin.get() != '\n');
cin.ignore(NAMEWIDTH);
cin >> skipws;
for (int j = 0; j < m; j++) {
int& mcell = row[j];
// skip over spaces between cells
//while (cin.peek() == ' ')
// cin.get(c);
readinto(cell);
if (cell == dummychar)
mcell = -1;
else
mcell = cell;
}
}
// convert to multistate numbers without gaps
vector<int> stateMap;
vector<vector<Mapping> > allmaps;
if (outputmap) {
allmaps.resize(m);
for(int j = 0; j < m; j++)
allmaps[j].reserve(n);
}
for (int j = 0; j < m; j++) {
for (int i = 0; i < n; i++) {
int& cell = data[i][j];
if (cell == -1)
continue;
int k, statecount = stateMap.size();
for (k = 0; k < statecount; k++)
if (stateMap[k] == cell) {
cell = k;
break;
}
if (k == statecount) {
if (outputmap)
allmaps[j].push_back(Mapping(cell, k));
stateMap.push_back(cell);
cell = k;
}
}
stateMap.clear();
}
if (outputmap) {
// write mapping to mapfile
ofstream outf(mapfile.c_str());
outf << index << endl << m;
if (dummychar != '\0') {
outf << ' ';
Mapping(dummychar, -1).printTo(outf);
}
outf << endl;
for (int j = 0; j < m; j++) {
const vector<Mapping>& row = allmaps[j];
outf << (int) row.size() << " ";
for (unsigned int k = 0; k < row.size(); k++)
row[k].printTo(outf);
outf << endl;
}
}
// write data to stdout
cout << index << endl << n << ' ' << m << endl;
for (int i = 0; i < n; i++) {
const vector<int>& row = data[i];
for (int j = 0; j < m; j++)
cout << row[j] << ' ';
cout << endl;
}
return 0;
}
#undef readinto
| 26.533333
| 126
| 0.400911
|
ProSolo
|
42ddfb6b787055c1ca8ab033ae14936586fa5e59
| 2,590
|
cpp
|
C++
|
src/schemas/project/mutations/CreateTrade.cpp
|
BlockChain-Station/enjin-cpp-sdk
|
3af1cd001d7e660787bbfb2e2414a96f5a95a228
|
[
"Apache-2.0"
] | 12
|
2021-09-28T14:37:22.000Z
|
2022-03-04T17:54:11.000Z
|
src/schemas/project/mutations/CreateTrade.cpp
|
BlockChain-Station/enjin-cpp-sdk
|
3af1cd001d7e660787bbfb2e2414a96f5a95a228
|
[
"Apache-2.0"
] | null | null | null |
src/schemas/project/mutations/CreateTrade.cpp
|
BlockChain-Station/enjin-cpp-sdk
|
3af1cd001d7e660787bbfb2e2414a96f5a95a228
|
[
"Apache-2.0"
] | 8
|
2021-11-05T18:56:55.000Z
|
2022-01-10T11:14:24.000Z
|
/* Copyright 2021 Enjin Pte. Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "enjinsdk/project/CreateTrade.hpp"
#include "RapidJsonUtils.hpp"
namespace enjin::sdk::project {
CreateTrade::CreateTrade() : graphql::AbstractGraphqlRequest("enjin.sdk.project.CreateTrade") {
}
std::string CreateTrade::serialize() const {
rapidjson::Document document(rapidjson::kObjectType);
utils::join_serialized_object_to_document(document, ProjectTransactionRequestArguments::serialize());
if (asking_assets.has_value()) {
utils::set_array_member_from_type_vector<models::Trade>(document, "askingAssets", asking_assets.value());
}
if (offering_assets.has_value()) {
utils::set_array_member_from_type_vector<models::Trade>(document, "offeringAssets", offering_assets.value());
}
if (recipient_address.has_value()) {
utils::set_string_member(document, "recipientAddress", recipient_address.value());
}
return utils::document_to_string(document);
}
CreateTrade& CreateTrade::set_asking_assets(std::vector<models::Trade> assets) {
asking_assets = assets;
return *this;
}
CreateTrade& CreateTrade::set_offering_assets(std::vector<models::Trade> assets) {
offering_assets = assets;
return *this;
}
CreateTrade& CreateTrade::set_recipient_address(const std::string& recipient_address) {
CreateTrade::recipient_address = recipient_address;
return *this;
}
bool CreateTrade::operator==(const CreateTrade& rhs) const {
return static_cast<const graphql::AbstractGraphqlRequest&>(*this) ==
static_cast<const graphql::AbstractGraphqlRequest&>(rhs) &&
static_cast<const ProjectTransactionRequestArguments<CreateTrade>&>(*this) ==
static_cast<const ProjectTransactionRequestArguments<CreateTrade>&>(rhs) &&
asking_assets == rhs.asking_assets &&
offering_assets == rhs.offering_assets &&
recipient_address == rhs.recipient_address;
}
bool CreateTrade::operator!=(const CreateTrade& rhs) const {
return !(rhs == *this);
}
}
| 35.479452
| 117
| 0.72973
|
BlockChain-Station
|
0cd31c2d57119c4b743b42991bf7b19b70237050
| 915
|
cpp
|
C++
|
src/boost/archive/yaml_oarchive.cpp
|
rwols/yaml-archive
|
4afec73e557c15350c5e068c010f4e378edc95ef
|
[
"BSL-1.0"
] | 1
|
2018-01-27T23:35:21.000Z
|
2018-01-27T23:35:21.000Z
|
src/boost/archive/yaml_oarchive.cpp
|
rwols/yaml-archive
|
4afec73e557c15350c5e068c010f4e378edc95ef
|
[
"BSL-1.0"
] | 2
|
2019-08-17T05:37:36.000Z
|
2019-08-17T22:57:26.000Z
|
src/boost/archive/yaml_oarchive.cpp
|
rwols/yaml-archive
|
4afec73e557c15350c5e068c010f4e378edc95ef
|
[
"BSL-1.0"
] | 1
|
2021-03-19T11:53:53.000Z
|
2021-03-19T11:53:53.000Z
|
/** @file
*
* @brief Defines narrow concrete output archives.
*
* @author Raoul Wols
*
* @date 2017
*
* @copyright See LICENSE.md
*
*/
#if (defined _MSC_VER) && (_MSC_VER == 1200)
#pragma warning(disable : 4786) // too long name, harmless warning
#endif
#define BOOST_ARCHIVE_SOURCE
#include <boost/archive/detail/archive_serializer_map.hpp>
#include <boost/archive/yaml_oarchive.hpp>
#include <boost/serialization/config.hpp>
// explicitly instantiate for this type of yaml stream
#include <boost/archive/impl/archive_serializer_map.ipp>
#include <boost/archive/impl/basic_yaml_oarchive.ipp>
#include <boost/archive/impl/yaml_oarchive_impl.ipp>
namespace boost {
namespace archive {
template class detail::archive_serializer_map<yaml_oarchive>;
template class basic_yaml_oarchive<yaml_oarchive>;
template class yaml_oarchive_impl<yaml_oarchive>;
} // namespace archive
} // namespace boost
| 25.416667
| 66
| 0.76612
|
rwols
|
0cd88d993983b62868af471659f79d4d06a7acfd
| 1,513
|
cpp
|
C++
|
course1/Laba2/G/main.cpp
|
flydzen/ITMO_algo
|
ea251dca0fddb0d4d212377c6785cdc3667ece89
|
[
"MIT"
] | null | null | null |
course1/Laba2/G/main.cpp
|
flydzen/ITMO_algo
|
ea251dca0fddb0d4d212377c6785cdc3667ece89
|
[
"MIT"
] | null | null | null |
course1/Laba2/G/main.cpp
|
flydzen/ITMO_algo
|
ea251dca0fddb0d4d212377c6785cdc3667ece89
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
#define ui unsigned int
#define ull unsigned long long
#define us unsigned long long
#pragma GCC optimize("03")
using namespace std;
ui cur = 0;
ui a, b;
inline ui nextRand24() {
cur = cur * a + b;
return cur >> 8;
}
inline ui nextRand32() {
return (nextRand24() << 8) ^ nextRand24();
}
inline ui digit(ui num, ui i) {
return (num >> (i * 8) & 0xFF);
}
void lsd(vector<ui> &v) {
ui k = 256;
ui m = 4;
ui n = v.size();
vector<ui> nV(n);
for (ui i = 0; i < m; i++) {
vector<ui> c(k);
for (ui j = 0; j < n; j++) {
c[digit(v[j], i)]++;
}
ui count = 0;
for (ui j = 0; j < k; j++) {
ui temp = c[j];
c[j] = count;
count += temp;
}
for (ui j = 0; j < n; j++) {
ui d = digit(v[j], i);
nV[c[d]] = v[j];
c[d]++;
}
v = nV;
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
ui t, n;
cin >> t >> n;
for (ui i = 0; i < t; i++) {
cin >> a >> b;
vector<ui> vec(n);
for (ui j = 0; j < n; j++) {
vec[j] = nextRand32();
}
lsd(vec);
unsigned long long summ = 0;
for (ui ij = 0; ij < n; ij++) {
summ += (unsigned long long) (ij + 1) * vec[(size_t) ij];
}
cout << summ << endl;
vec.clear();
}
return 0;
}
| 20.173333
| 69
| 0.432254
|
flydzen
|
0cd9c66e0780db9a044edb30d4d606f462b86e57
| 3,313
|
cpp
|
C++
|
src/BlockEntities/ChestEntity.cpp
|
planetx/MCServer
|
4e119b522409af682e62ed38f4d22ddd9da40170
|
[
"Apache-2.0"
] | null | null | null |
src/BlockEntities/ChestEntity.cpp
|
planetx/MCServer
|
4e119b522409af682e62ed38f4d22ddd9da40170
|
[
"Apache-2.0"
] | null | null | null |
src/BlockEntities/ChestEntity.cpp
|
planetx/MCServer
|
4e119b522409af682e62ed38f4d22ddd9da40170
|
[
"Apache-2.0"
] | null | null | null |
#include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules
#include "ChestEntity.h"
#include "../Item.h"
#include "../Entities/Player.h"
#include "../UI/Window.h"
cChestEntity::cChestEntity(int a_BlockX, int a_BlockY, int a_BlockZ, cWorld * a_World, BLOCKTYPE a_Type) :
super(a_Type, a_BlockX, a_BlockY, a_BlockZ, ContentsWidth, ContentsHeight, a_World),
m_NumActivePlayers(0)
{
}
cChestEntity::~cChestEntity()
{
cWindow * Window = GetWindow();
if (Window != nullptr)
{
Window->OwnerDestroyed();
}
}
void cChestEntity::SendTo(cClientHandle & a_Client)
{
// The chest entity doesn't need anything sent to the client when it's created / gets in the viewdistance
// All the actual handling is in the cWindow UI code that gets called when the chest is rclked
UNUSED(a_Client);
}
void cChestEntity::UsedBy(cPlayer * a_Player)
{
// If the window is not created, open it anew:
cWindow * Window = GetWindow();
if (Window == nullptr)
{
OpenNewWindow();
Window = GetWindow();
}
// Open the window for the player:
if (Window != nullptr)
{
if (a_Player->GetWindow() != Window)
{
a_Player->OpenWindow(Window);
}
}
// This is rather a hack
// Instead of marking the chunk as dirty upon chest contents change, we mark it dirty now
// We cannot properly detect contents change, but such a change doesn't happen without a player opening the chest first.
// The few false positives aren't much to worry about
int ChunkX, ChunkZ;
cChunkDef::BlockToChunk(m_PosX, m_PosZ, ChunkX, ChunkZ);
m_World->MarkChunkDirty(ChunkX, ChunkZ, true);
}
void cChestEntity::OpenNewWindow(void)
{
// TODO: cats are an obstruction
if ((GetPosY() + 1 < cChunkDef::Height) && cBlockInfo::IsSolid(GetWorld()->GetBlock(GetPosX(), GetPosY() + 1, GetPosZ())))
{
// Obstruction, don't open
return;
}
// Callback for opening together with neighbor chest:
class cOpenDouble :
public cChestCallback
{
cChestEntity * m_ThisChest;
public:
cOpenDouble(cChestEntity * a_ThisChest) :
m_ThisChest(a_ThisChest)
{
}
virtual bool Item(cChestEntity * a_Chest) override
{
if ((a_Chest->GetPosY() + 1 < cChunkDef::Height) && cBlockInfo::IsSolid(a_Chest->GetWorld()->GetBlock(a_Chest->GetPosX(), a_Chest->GetPosY() + 1, a_Chest->GetPosZ())))
{
// Obstruction, don't open
return false;
}
// The primary chest should eb the one with lesser X or Z coord:
cChestEntity * Primary = a_Chest;
cChestEntity * Secondary = m_ThisChest;
if (
(Primary->GetPosX() > Secondary->GetPosX()) ||
(Primary->GetPosZ() > Secondary->GetPosZ())
)
{
std::swap(Primary, Secondary);
}
m_ThisChest->OpenWindow(new cChestWindow(Primary, Secondary));
return false;
}
} ;
// Scan neighbors for adjacent chests:
cOpenDouble OpenDbl(this);
if (
m_World->DoWithChestAt(m_PosX - 1, m_PosY, m_PosZ, OpenDbl) ||
m_World->DoWithChestAt(m_PosX + 1, m_PosY, m_PosZ, OpenDbl) ||
m_World->DoWithChestAt(m_PosX, m_PosY, m_PosZ - 1, OpenDbl) ||
m_World->DoWithChestAt(m_PosX, m_PosY, m_PosZ + 1, OpenDbl)
)
{
// The double-chest window has been opened in the callback
return;
}
// There is no chest neighbor, open a single-chest window:
OpenWindow(new cChestWindow(this));
}
| 23.167832
| 170
| 0.689104
|
planetx
|
0cda9a014ed43d1a287d252950ea53b778b22bfa
| 5,656
|
cpp
|
C++
|
src/libv/ui/component/stretch.cpp
|
cpplibv/libv
|
293e382f459f0acbc540de8ef6283782b38d2e63
|
[
"Zlib"
] | 2
|
2018-04-11T03:07:03.000Z
|
2019-03-29T15:24:12.000Z
|
src/libv/ui/component/stretch.cpp
|
cpplibv/libv
|
293e382f459f0acbc540de8ef6283782b38d2e63
|
[
"Zlib"
] | null | null | null |
src/libv/ui/component/stretch.cpp
|
cpplibv/libv
|
293e382f459f0acbc540de8ef6283782b38d2e63
|
[
"Zlib"
] | 1
|
2021-06-13T06:39:06.000Z
|
2021-06-13T06:39:06.000Z
|
// Project: libv.ui, File: src/libv/ui/component/stretch.cpp, Author: Császár Mátyás [Vader]
// hpp
#include <libv/ui/component/stretch.hpp>
// pro
#include <libv/ui/context/context_layout.hpp>
#include <libv/ui/context/context_render.hpp>
#include <libv/ui/context/context_style.hpp>
#include <libv/ui/context/context_ui.hpp>
#include <libv/ui/core_component.hpp>
#include <libv/ui/property_access_context.hpp>
#include <libv/ui/shader/shader_image.hpp>
#include <libv/ui/style.hpp>
#include <libv/ui/texture_2D.hpp>
namespace libv {
namespace ui {
// -------------------------------------------------------------------------------------------------
struct CoreStretch : CoreComponent {
friend class Stretch;
[[nodiscard]] inline auto handler() { return Stretch{this}; }
private:
template <typename T> static void access_properties(T& ctx);
struct Properties {
PropertyR<Color> bg_color;
PropertyL<Texture2D_view> bg_image;
PropertyR<ShaderImage_view> bg_shader;
} property;
public:
using CoreComponent::CoreComponent;
private:
virtual void doStyle(ContextStyle& ctx) override;
virtual libv::vec3f doLayout1(const ContextLayout1& environment) override;
virtual void doRender(Renderer& r) override;
};
// -------------------------------------------------------------------------------------------------
template <typename T>
void CoreStretch::access_properties(T& ctx) {
ctx.property(
[](auto& c) -> auto& { return c.property.bg_color; },
Color(1, 1, 1, 1),
pgr::appearance, pnm::bg_color,
"Background color"
);
ctx.property(
[](auto& c) -> auto& { return c.property.bg_image; },
[](auto& u) { return u.fallbackTexture2D(); },
pgr::appearance, pnm::bg_image,
"Background image"
);
ctx.property(
[](auto& c) -> auto& { return c.property.bg_shader; },
[](auto& u) { return u.shaderImage(); },
pgr::appearance, pnm::bg_shader,
"Background shader"
);
}
// -------------------------------------------------------------------------------------------------
void CoreStretch::doStyle(ContextStyle& ctx) {
PropertyAccessContext<CoreStretch> setter{*this, ctx.component, ctx.style, context()};
access_properties(setter);
CoreComponent::access_properties(setter);
}
libv::vec3f CoreStretch::doLayout1(const ContextLayout1& environment) {
(void) environment;
const auto dynamic_size_image = property.bg_image()->size().cast<float>() + padding_size();
return {dynamic_size_image, 0.f};
}
void CoreStretch::doRender(Renderer& r) {
// y3 12--13--14--15
// | / | / | / |
// y2 8---9---10--11
// | / | / | / |
// y1 4---5---6---7
// | / | / | / |
// y0 0---1---2---3
//
// x0 x1 x2 x3
const auto border_pos = min(cast<float>(property.bg_image()->size()), layout_size2()) * 0.5f;
const auto border_tex = min(layout_size2() / max(cast<float>(property.bg_image()->size()), 1.0f) * 0.5f, 0.5f);
const auto p0 = libv::vec2f{0.0f, 0.0f};
const auto p1 = border_pos;
const auto p2 = layout_size2() - border_pos;
const auto p3 = layout_size2();
const auto t0 = libv::vec2f{0.0f, 0.0f};
const auto t1 = border_tex;
const auto t2 = 1.0f - border_tex;
const auto t3 = libv::vec2f{1.0f, 1.0f};
const auto color = property.bg_color();
r.begin_triangles();
r.vertex({p0.x, p0.y, 0}, {t0.x, t0.y}, color);
r.vertex({p1.x, p0.y, 0}, {t1.x, t0.y}, color);
r.vertex({p2.x, p0.y, 0}, {t2.x, t0.y}, color);
r.vertex({p3.x, p0.y, 0}, {t3.x, t0.y}, color);
r.vertex({p0.x, p1.y, 0}, {t0.x, t1.y}, color);
r.vertex({p1.x, p1.y, 0}, {t1.x, t1.y}, color);
r.vertex({p2.x, p1.y, 0}, {t2.x, t1.y}, color);
r.vertex({p3.x, p1.y, 0}, {t3.x, t1.y}, color);
r.vertex({p0.x, p2.y, 0}, {t0.x, t2.y}, color);
r.vertex({p1.x, p2.y, 0}, {t1.x, t2.y}, color);
r.vertex({p2.x, p2.y, 0}, {t2.x, t2.y}, color);
r.vertex({p3.x, p2.y, 0}, {t3.x, t2.y}, color);
r.vertex({p0.x, p3.y, 0}, {t0.x, t3.y}, color);
r.vertex({p1.x, p3.y, 0}, {t1.x, t3.y}, color);
r.vertex({p2.x, p3.y, 0}, {t2.x, t3.y}, color);
r.vertex({p3.x, p3.y, 0}, {t3.x, t3.y}, color);
r.index_strip({4, 0, 5, 1, 6, 2, 7, 3});
r.index_strip({3, 8}); // jump
r.index_strip({8, 4, 9, 5, 10, 6, 11, 7});
r.index_strip({7, 12}); // jump
r.index_strip({12, 8, 13, 9, 14, 10, 15, 11});
r.end(property.bg_image(), property.bg_shader());
}
// -------------------------------------------------------------------------------------------------
Stretch::Stretch(std::string name) :
ComponentHandler<CoreStretch, EventHostGeneral<Stretch>>(std::move(name)) { }
Stretch::Stretch(GenerateName_t gen, const std::string_view type) :
ComponentHandler<CoreStretch, EventHostGeneral<Stretch>>(gen, type) { }
Stretch::Stretch(core_ptr core) noexcept :
ComponentHandler<CoreStretch, EventHostGeneral<Stretch>>(core) { }
// -------------------------------------------------------------------------------------------------
void Stretch::color(Color value) {
AccessProperty::manual(self(), self().property.bg_color, value);
}
const Color& Stretch::color() const noexcept {
return self().property.bg_color();
}
void Stretch::image(Texture2D_view value) {
AccessProperty::manual(self(), self().property.bg_image, std::move(value));
}
const Texture2D_view& Stretch::image() const noexcept {
return self().property.bg_image();
}
void Stretch::shader(ShaderImage_view value) {
AccessProperty::manual(self(), self().property.bg_shader, std::move(value));
}
const ShaderImage_view& Stretch::shader() const noexcept {
return self().property.bg_shader();
}
// -------------------------------------------------------------------------------------------------
} // namespace ui
} // namespace libv
| 31.248619
| 112
| 0.589993
|
cpplibv
|
0cdf589e598c31402e68e86595e88ef22d2c8193
| 9,280
|
cpp
|
C++
|
SwapChain/Driver/OpenGL/src/Win32/SwapChain.cpp
|
Gpinchon/OCRA
|
341bb07facc616f1f8a27350054d1e86f022d7c6
|
[
"Apache-2.0"
] | null | null | null |
SwapChain/Driver/OpenGL/src/Win32/SwapChain.cpp
|
Gpinchon/OCRA
|
341bb07facc616f1f8a27350054d1e86f022d7c6
|
[
"Apache-2.0"
] | null | null | null |
SwapChain/Driver/OpenGL/src/Win32/SwapChain.cpp
|
Gpinchon/OCRA
|
341bb07facc616f1f8a27350054d1e86f022d7c6
|
[
"Apache-2.0"
] | null | null | null |
#include <GL/Win32/SwapChain.hpp>
#include <GL/Win32/PresentGeometry.hpp>
#include <GL/Win32/PresentPixels.hpp>
#include <GL/Win32/PresentShader.hpp>
#include <GL/Win32/PresentTexture.hpp>
#include <GL/Surface.hpp>
#include <GL/Win32/Error.hpp>
#include <GL/Win32/OpenGL.hpp>
#include <GL/Device.hpp>
#include <GL/Image/Format.hpp>
#include <GL/Image/Image.hpp>
#include <GL/Queue/Queue.hpp>
#include <GL/Queue/Semaphore.hpp>
#include <GL/Queue/Fence.hpp>
#include <GL/Common/BufferOffset.hpp>
#include <GL/glew.h>
#include <GL/wglew.h>
#include <iostream>
#include <sstream>
namespace OCRA::SwapChain::Win32
{
void GLAPIENTRY MessageCallback(
GLenum source,
GLenum type,
GLenum id,
GLenum severity,
GLsizei length,
const GLchar* message,
const void* userParam)
{
if (type == GL_DEBUG_TYPE_ERROR)
{
std::stringstream ss{};
ss << "GL CALLBACK : **GL ERROR * *\n" <<
" type = " << type << "\n" <<
" severity = " << severity << "\n" <<
" message = " << message;
std::cerr << ss.str() << std::endl;
throw std::runtime_error(ss.str());
}
}
static inline auto CreateImages(const Device::Handle& a_Device, const Info& a_Info)
{
std::vector<Image::Handle> images;
auto win32SwapChain = std::static_pointer_cast<SwapChain::Win32::Impl>(a_Info.oldSwapchain);
for (auto i = 0u; i < a_Info.imageCount; ++i)
{
Image::Handle image;
if (win32SwapChain != nullptr) {
const auto& imageInfo = win32SwapChain->images.at(i)->info;
const bool canRecycle = imageInfo.extent.width == a_Info.imageExtent.width &&
imageInfo.extent.height == a_Info.imageExtent.height &&
imageInfo.arrayLayers == a_Info.imageArrayLayers &&
imageInfo.format == a_Info.imageFormat;
if (canRecycle) image = win32SwapChain->images.at(i);
}
if (image == nullptr) {
Image::Info imageInfo{};
imageInfo.type = Image::Type::Image2D;
imageInfo.extent.width = a_Info.imageExtent.width;
imageInfo.extent.height = a_Info.imageExtent.height;
imageInfo.mipLevels = 1;
imageInfo.arrayLayers = a_Info.imageArrayLayers;
imageInfo.format = a_Info.imageFormat;
image = Image::Create(a_Device, imageInfo);
}
images.push_back(image);
}
return images;
}
Impl::Impl(const Device::Handle& a_Device, const Info& a_Info)
: SwapChain::Impl(a_Device, a_Info)
, images(CreateImages(a_Device, a_Info))
{
const auto pixelSize = GetPixelSize(info.imageFormat);
if (info.oldSwapchain != nullptr && !info.oldSwapchain->retired) {
auto win32SwapChain = std::static_pointer_cast<SwapChain::Win32::Impl>(info.oldSwapchain);
win32SwapChain->workerThread.Wait();
hdc = win32SwapChain->hdc;
hglrc = win32SwapChain->hglrc;
presentShader.swap(win32SwapChain->presentShader);
info.oldSwapchain->Retire();
info.oldSwapchain.reset();
}
else {
hdc = GetDC(HWND(a_Info.surface->nativeWindow));
OpenGL::Win32::Initialize();
const int attribIList[] = {
WGL_DRAW_TO_WINDOW_ARB, true,
WGL_SUPPORT_OPENGL_ARB, true,
WGL_DOUBLE_BUFFER_ARB, true,
WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB,
WGL_COLORSPACE_EXT, WGL_COLORSPACE_SRGB_EXT,
WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB,
WGL_COLOR_BITS_ARB, pixelSize,
0
};
int32_t pixelFormat = 0;
uint32_t pixelFormatNbr = 0;
WIN32_CHECK_ERROR(wglChoosePixelFormatARB(HDC(hdc), attribIList, nullptr, 1, &pixelFormat, &pixelFormatNbr));
WIN32_CHECK_ERROR(pixelFormat != 0);
WIN32_CHECK_ERROR(pixelFormatNbr != 0);
WIN32_CHECK_ERROR(SetPixelFormat(HDC(hdc), pixelFormat, nullptr));
hglrc = OpenGL::Win32::CreateContext(hdc);
}
workerThread.PushCommand([this, pixelSize] {
WIN32_CHECK_ERROR(wglMakeCurrent(HDC(hdc), HGLRC(hglrc)));
if (info.presentMode == PresentMode::Immediate) {
WIN32_CHECK_ERROR(wglSwapIntervalEXT(0));
}
else WIN32_CHECK_ERROR(wglSwapIntervalEXT(1));
#ifdef _DEBUG
glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
glDebugMessageCallback(MessageCallback, 0);
#endif _DEBUG
if (presentTexture == nullptr) {
presentTexture.reset(new PresentTexture(images.front()));
presentTexture->Bind();
}
if (presentShader == nullptr) {
presentShader.reset(new PresentShader);
presentShader->Bind();
}
if (presentGeometry == nullptr) {
presentGeometry.reset(new PresentGeometry);
presentGeometry->Bind();
}
if (!WGLEW_NV_copy_image && presentPixels == nullptr) {
static bool warningPrinted = false;
if (!warningPrinted) {
std::cerr << "SwapChain : WGL_NV_copy_image unavailable, using slower path\n";
warningPrinted = true;
}
const auto transferBufferSize = info.imageExtent.width * info.imageExtent.height * pixelSize / 8;
presentPixels.reset(new PresentPixels(transferBufferSize));
presentPixels->Bind();
}
glViewport(0, 0, presentTexture->extent.width, presentTexture->extent.height);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
glActiveTexture(GL_TEXTURE0);
glBindSampler(0, presentTexture->samplerHandle);
}, false);
}
Impl::~Impl()
{
retired = true;
workerThread.PushCommand([this] {
presentTexture.reset();
presentShader.reset();
presentGeometry.reset();
presentPixels.reset();
wglMakeCurrent(nullptr, nullptr);
}, true);
if (hdc != nullptr)
ReleaseDC(HWND(info.surface->nativeWindow), HDC(hdc));
if (hglrc != nullptr)
wglDeleteContext(HGLRC(hglrc));
}
void Impl::Retire() {
SwapChain::Impl::Retire();
workerThread.PushCommand([this] {
presentShader.reset();
presentTexture.reset();
presentGeometry.reset();
presentPixels.reset();
wglMakeCurrent(nullptr, nullptr);
}, true);
images.clear();
hdc = nullptr;
hglrc = nullptr;
}
void Impl::Present(const Queue::Handle& a_Queue)
{
assert(!retired);
if (WGLEW_NV_copy_image) {
PresentNV(a_Queue);
}
else {
PresentGL(a_Queue);
}
}
void Impl::PresentNV(const Queue::Handle& a_Queue)
{
const auto& image = images.at(backBufferIndex);
const auto extent = image->info.extent;
a_Queue->PushCommand([this, extent] {
const auto& image = images.at(backBufferIndex);
auto sync = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0);
glClientWaitSync(sync, 0, 1000);
glDeleteSync(sync);
WIN32_CHECK_ERROR(wglCopyImageSubDataNV(
nullptr, image->handle, image->target, //use current context
0, 0, 0, 0,
HGLRC(hglrc), presentTexture->handle, presentTexture->target,
0, 0, 0, 0,
extent.width, extent.height, 1));
}, true);
workerThread.PushCommand([this, extent] {
presentGeometry->Draw();
WIN32_CHECK_ERROR(SwapBuffers(HDC(hdc)));
}, info.presentMode != PresentMode::Immediate);
backBufferIndex = (backBufferIndex + 1) % info.imageCount;
}
void Impl::PresentGL(const Queue::Handle& a_Queue)
{
const auto& image = images.at(backBufferIndex);
const auto extent = image->info.extent;
a_Queue->PushCommand([this, extent] {
const auto& image = images.at(backBufferIndex);
glBindTexture(image->target, image->handle);
glGetTexImage(
image->target,
0,
image->dataFormat,
image->dataType,
presentPixels->GetPtr());
glBindTexture(image->target, 0);
}, true);
workerThread.PushCommand([this, extent] {
presentPixels->Flush();
glTexSubImage2D(
presentTexture->target, 0,
0, 0, extent.width, extent.height,
presentTexture->dataFormat, presentTexture->dataType, BUFFER_OFFSET(presentPixels->offset));
presentGeometry->Draw();
WIN32_CHECK_ERROR(SwapBuffers(HDC(hdc)));
}, info.presentMode != PresentMode::Immediate);
backBufferIndex = (backBufferIndex + 1) % info.imageCount;
}
//TODO: implement a timeout
Image::Handle Impl::AcquireNextImage(
const std::chrono::nanoseconds& a_Timeout,
const Queue::Semaphore::Handle& a_Semaphore,
const Queue::Fence::Handle& a_Fence)
{
workerThread.Wait();
//We do not need to synchronize with the GPU for real here
if (a_Semaphore != nullptr) {
if (a_Semaphore->type == Queue::Semaphore::Type::Binary)
std::static_pointer_cast<Queue::Semaphore::Binary>(a_Semaphore)->SignalNoSync();
else throw std::runtime_error("Cannot wait on Timeline Semaphores when presenting");
}
if (a_Fence != nullptr) a_Fence->SignalNoSync();
return images.at(backBufferIndex);
}
}
| 35.968992
| 117
| 0.628017
|
Gpinchon
|
0ce83d17e36b56392ae66bdda1e9e462aede0061
| 865
|
cpp
|
C++
|
PAT/Advanced Level/Simulation_Math/1148 Werewolf.cpp
|
MuZi-lh/AlgorithmExecise
|
88411f52ad65ef002ed8bcbcffc402f64985958f
|
[
"MulanPSL-1.0"
] | null | null | null |
PAT/Advanced Level/Simulation_Math/1148 Werewolf.cpp
|
MuZi-lh/AlgorithmExecise
|
88411f52ad65ef002ed8bcbcffc402f64985958f
|
[
"MulanPSL-1.0"
] | null | null | null |
PAT/Advanced Level/Simulation_Math/1148 Werewolf.cpp
|
MuZi-lh/AlgorithmExecise
|
88411f52ad65ef002ed8bcbcffc402f64985958f
|
[
"MulanPSL-1.0"
] | null | null | null |
#include<iostream>
#include<vector>
using namespace std;
int N;
vector<int> p(100);
bool tellingTruth(int a, int b, int t) {
return (abs(p[t]) != a && abs(p[t]) != b && p[t] > 0) || (p[t] == -a || p[t] == -b);
}
// a, b are wolf,
// assume a, b don't point at themselves
// a tell a truth, b tell a lie
bool legal(int a, int b) {
int cnt = 0;
if (tellingTruth(a, b, a) && !tellingTruth(a, b, b)) {
for (int k = 1;k <= N;k++) {
if (k != b && !tellingTruth(a, b, k)) {
cnt++;
}
}
if (cnt == 1) return true;
}
return false;
}
// positive for human and negtive for wolf
int main() {
cin >> N;
for (int i = 1; i <= N; i++)
{
cin >> p[i];
}
for (int i = 1; i <= N - 1; i++)
{
for (int j = i + 1;j <= N;j++) {
if (legal(i, j) || legal(j, i)) {
cout << i << ' ' << j;
return 0;
}
}
}
cout << "No Solution";
return 0;
}
| 18.804348
| 85
| 0.491329
|
MuZi-lh
|
0ce92d47507b7639fa18ea1fb22e4d36ef08339a
| 9,890
|
cpp
|
C++
|
Source/Game/GameState/IntroState/IntroState.cpp
|
Crazykingjammy/bkbotz
|
6cdaa4164ff02e40f2909982f6dacad161c7d6cf
|
[
"Unlicense"
] | null | null | null |
Source/Game/GameState/IntroState/IntroState.cpp
|
Crazykingjammy/bkbotz
|
6cdaa4164ff02e40f2909982f6dacad161c7d6cf
|
[
"Unlicense"
] | null | null | null |
Source/Game/GameState/IntroState/IntroState.cpp
|
Crazykingjammy/bkbotz
|
6cdaa4164ff02e40f2909982f6dacad161c7d6cf
|
[
"Unlicense"
] | null | null | null |
#include "../GameState.h"
CIntroGameState* CIntroGameState::pInstance = 0;
void CIntroGameState::Initalize(Game* game)
{
//Get the Pointer to the game.
pGame = game;
//////////////////////////////////////////////////////////////////////////
// Lights Setup
//////////////////////////////////////////////////////////////////////////
//Set up Lights here
pRenderInterface->Light[0].m_Active = true;
pRenderInterface->Light[0].m_MyBody.centerPosition.y = 10.0f;
pRenderInterface->Light[0].m_Specular = 0.0f;
pRenderInterface->Light[0].m_Diffuse = EXColor(0.6f,0.65f,0.65f,1.0f);
pRenderInterface->Light[0].m_Ambient = EXColor(0.1f,0.1f,0.1f,1.0f);
pRenderInterface->Light[0].m_Attenuation2 = 0.0000002f;
//////////////////////////////////////////////////////////////////////////
// Lights Setup
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
// Camera Setup
//////////////////////////////////////////////////////////////////////////
Camera0 = new CFreeCamera;
Camera1 = new CFreeCamera;
Camera0->m_LinearSpeed = 5.0f;
Camera0->m_MyBody.centerPosition.y += 24.035156f;
Camera0->m_MyBody.centerPosition.x -= 35.638084f;
Camera0->m_MyBody.centerPosition.z -= 26.376434f;
Camera1->m_MyBody.centerPosition.z = -10.0f;
pRenderInterface->SetActiveCamera(Camera0);
//pRenderInterface->
//////////////////////////////////////////////////////////////////////////
// Camera Setup
//////////////////////////////////////////////////////////////////////////
m_2DScene.Set2DWorld((float)pGame->Window.WindowWidth,(float)pGame->Window.WindowHeight);
m_2DScene.sceneGravity.MakeZero();
//////////////////////////////////////////////////////////////////////////
// Object Setup
//////////////////////////////////////////////////////////////////////////
pRenderInterface->SetWorld("Models/MenuWorld.X");
Ship = new CBall;
strcpy(Ship->m_ModelName,"Models/MenuShip.X");
Ship->m_MyBody.centerPosition.y += 7.0f;
//pRenderInterface->AddObject(Ship);
//Ship->m_MyBodyIndex = m_Scene.AddBody(&Ship->m_MyBody);
Battle = new CLabel("Textures/MenuIcon_1.bmp");
pRenderInterface->AddLabel(Battle);
Battle->m_MyBody.centerPosition.x += (float)(pGame->Window.WindowWidth / 3);
Battle->m_MyBody.centerPosition.y += (float) (pGame->Window.WindowHeight / 3);
Battle->m_MyBody.radius = 10.0f;
Battle->m_MyBody.mass = 1.0f;
Battle->m_MyBodyIndex = m_2DScene.AddBody(&Battle->m_MyBody);
Credits = new CLabel("Textures/MenuIcon_3.bmp");
pRenderInterface->AddLabel(Credits);
Credits->m_MyBody.centerPosition.x += 300.0f;
Credits->m_MyBody.centerPosition.y += 450.0f;
Credits->m_MyBody.radius = 10.0f;
Credits->m_MyBody.mass = 1.0f;
Credits->m_MyBodyIndex = m_2DScene.AddBody(&Credits->m_MyBody);
Exit = new CLabel("Textures/MenuIcon_4.bmp");
pRenderInterface->AddLabel(Exit);
Exit->m_MyBody.centerPosition.x += 600.0f;
Exit->m_MyBody.centerPosition.y += 450.0f;
Exit->m_MyBody.radius = 10.0f;;
Exit->m_MyBody.mass = 1.0f;
Exit->m_MyBodyIndex = m_2DScene.AddBody(&Exit->m_MyBody);
Soccer = new CLabel("Textures/MenuIcon_2.bmp");
pRenderInterface->AddLabel(Soccer);
Soccer->m_MyBody.centerPosition.x += 600.0f;
Soccer->m_MyBody.centerPosition.y += 150.0f;
Soccer->m_MyBody.radius = 10.0f;;
Soccer->m_MyBodyIndex = m_2DScene.AddBody(&Soccer->m_MyBody);
Soccer->m_MyBody.mass = 1.0f;
Me = new CLabel("Textures/MenuIcon_0.bmp");
pRenderInterface->AddLabel(Me);
Me->m_MyBody.isNapping = false;
Me->m_MyBody.centerPosition.x += (float)(pGame->Window.WindowWidth/2);
Me->m_MyBody.centerPosition.y += (float)(pGame->Window.WindowHeight/2);
Me->m_MyBody.mass = 10.0f;
Me->m_MyBody.radius = 64.0f;;
Me->m_MyBodyIndex = m_2DScene.AddBody(&Me->m_MyBody);
//strcpy(Me->m_Text, "B");
GameText = new CLabel("Textures/jamtext.bmp");
pRenderInterface->AddLabel(GameText);
GameText->m_MyBody.centerPosition.x = 280.0f;
GameText->m_MyBody.centerPosition.y = 30.0f;
//////////////////////////////////////////////////////////////////////////
// Object Setup
//////////////////////////////////////////////////////////////////////////
//Numbers
MeForce = 27000.0f * 4.0f;
m_InputFreq = 0.05f;
CurrentSelection = 0;
//Create the Scene
pRenderInterface->CreateScene();
}
void CIntroGameState::Update(float timeDelta)
{
//m_Scene.Simulate();
m_2DScene.Simulate();
Camera0->LookAt(pRenderInterface->m_World);
cout << Me->m_MyBody.centerPosition.x << ' ' << Me->m_MyBody.centerPosition.y << ' ' << Me->m_MyBody.centerPosition.z<< endl;
//Pull toward the middle.
Battle->m_MyBody.gravityForce = CVector3f(400.0f, 300.0f, 0.0f) - Battle->m_MyBody.centerPosition;
Battle->m_MyBody.gravityForce.Normalize();
Battle->m_MyBody.gravityForce *= 5.8f;
Credits->m_MyBody.gravityForce = CVector3f(400.0f, 300.0f, 0.0f) - Credits->m_MyBody.centerPosition;
Credits->m_MyBody.gravityForce.Normalize();
Credits->m_MyBody.gravityForce *= 5.8f;
Soccer->m_MyBody.gravityForce = CVector3f(400.0f, 300.0f, 0.0f) - Soccer->m_MyBody.centerPosition;
Soccer->m_MyBody.gravityForce.Normalize();
Soccer->m_MyBody.gravityForce *= 5.8f;
Exit->m_MyBody.gravityForce = CVector3f(400.0f, 300.0f, 0.0f) - Exit->m_MyBody.centerPosition;
Exit->m_MyBody.gravityForce.Normalize();
Exit->m_MyBody.gravityForce *= 5.8f;
//Check for controls.
if (m_InputTimer.GetElapsedSeconds() >= m_InputFreq)
{
Controls();
Me->m_Rotation += 0.01f; // Me->m_MyBody.velocityVec.Magnitude();
Me->m_MyBody.Add2Force( (CVector3f((float)(pGame->Window.WindowWidth/2), (float)(pGame->Window.WindowHeight/2), 0.0f) - Me->m_MyBody.centerPosition) * 750.0f );
m_InputTimer.Reset();
}
CollisionDetection();
//attach cam to the player.
Camera1->m_MyBody.centerPosition = Ship->m_MyBody.centerPosition;
//Move camera
Camera1->m_MyBody.centerPosition.y += 4.51f;
Camera1->m_MyBody.centerPosition.x -= 0.51f;
Camera1->m_MyBody.centerPosition.z -= 3.3f;
switch(CurrentSelection)
{
char test[128];
case BATTLE:
{
sprintf(test, "Battle Game");
strcpy(GameText->m_Text,test);
if (pInput->Controller1JoyPress(0))
{
ChangeState(pGame,CBattleGameState::GetInstance());
return;
}
break;
}
case SOCCER:
{
sprintf(test, "Soccer Game");
strcpy(GameText->m_Text,test);
if (pInput->Controller1JoyPress(0))
{
ChangeState(pGame, CSoccerGameState::GetInstance());
return;
}
break;
}
case EXIT:
{
sprintf(test, "Exit Game");
strcpy(GameText->m_Text,test);
if (pInput->Controller1JoyPress(0))
{
//Only place this should be getting called :_D
PostQuitMessage(0);
}
break;
}
case CREDITS:
{
sprintf(test, "Game Credits");
strcpy(GameText->m_Text,test);
if (pInput->Controller1JoyPress(0))
{
ChangeState(pGame, CJukeBoxState::GetInstance());
return;
}
break;
}
}
}
void CIntroGameState::Shutdown()
{
//Destroy teh modles and reset the scene.
pRenderInterface->DestroyScene();
m_Scene.ClearScene();
m_2DScene.ClearScene();
delete Camera0;
delete Camera1;
delete Ship;
delete Exit;
delete Soccer;
delete Battle;
delete Credits;
//Clean Me Up.
if(pInstance)
delete pInstance;
pInstance = 0;
}
void CIntroGameState::Controls()
{
//Get input States.
pInput->SetAllStates();
if (pInput->Controller1JoyPress(1))
{
Me->m_MyBody.velocityVec.MakeZero();
}
// timer >= inpout time
// do this
if(GetAsyncKeyState('W'))
pRenderInterface->m_ActiveCamera->MoveUp();
if(GetAsyncKeyState('S'))
pRenderInterface->m_ActiveCamera->MoveDown();
if(GetAsyncKeyState('A'))
pRenderInterface->m_ActiveCamera->MoveLeft();
if(GetAsyncKeyState('D'))
pRenderInterface->m_ActiveCamera->MoveRight();
if(GetAsyncKeyState('C'))
pRenderInterface->m_ActiveCamera->MoveFoward();
if(GetAsyncKeyState('V'))
pRenderInterface->m_ActiveCamera->MoveBackward();
if(GetAsyncKeyState('F'))
pRenderInterface->m_ActiveCamera->LookLeft();
if(GetAsyncKeyState('H'))
pRenderInterface->m_ActiveCamera->LookRight();
if(GetAsyncKeyState('T'))
pRenderInterface->m_ActiveCamera->LookUp();
if(GetAsyncKeyState('G'))
pRenderInterface->m_ActiveCamera->LookDown();
if(pInput->Controller1JoyY() < -200)
{
Me->m_MyBody.Add2Force( CVector3f(0.0f,-1.0f,0.0f) * (MeForce ) );
}
if(pInput->Controller1JoyY() > 200)
{
Me->m_MyBody.Add2Force( CVector3f(0.0f,1.0f,0.0f) * MeForce );
}
if(pInput->Controller1JoyX() < -200)
{
Me->m_MyBody.Add2Force( CVector3f(-1.0f,0.0f,0.0f) * MeForce );
}
if(pInput->Controller1JoyX() > 200)
{
Me->m_MyBody.Add2Force( CVector3f(1.0f,0.0f,0.0f) * MeForce );
}
if(GetAsyncKeyState('P'))
pRenderInterface->SetActiveCamera(Camera1);
if(GetAsyncKeyState('L'))
pRenderInterface->SetActiveCamera(Camera0);
}
void CIntroGameState::CollisionDetection()
{
if(m_2DScene.HaveTheTwoBodiesCollided(Battle->m_MyBodyIndex,Me->m_MyBodyIndex))
{
CurrentSelection = BATTLE;
Camera0->m_MyBody.centerPosition.y = 24.035156f;
Camera0->m_MyBody.centerPosition.x = -35.638084f;
Camera0->m_MyBody.centerPosition.z = -26.376434f;
}
if(m_2DScene.HaveTheTwoBodiesCollided(Soccer->m_MyBodyIndex,Me->m_MyBodyIndex))
{
CurrentSelection = SOCCER;
}
if(m_2DScene.HaveTheTwoBodiesCollided(Exit->m_MyBodyIndex,Me->m_MyBodyIndex))
{
CurrentSelection = EXIT;
Camera0->m_MyBody.centerPosition.y = 23.254128f;
Camera0->m_MyBody.centerPosition.x = -58.199429f;
Camera0->m_MyBody.centerPosition.z = 19.165016f;
}
if(m_2DScene.HaveTheTwoBodiesCollided(Credits->m_MyBodyIndex,Me->m_MyBodyIndex))
{
CurrentSelection = CREDITS;
}
}
CIntroGameState* CIntroGameState::GetInstance()
{
//If there is no instance
if(pInstance == 0)
pInstance = new CIntroGameState; //We Create One
return pInstance; //Return the Instance.
}
| 25.101523
| 163
| 0.649848
|
Crazykingjammy
|
0ced71d029ec7f52b67c86ddfcffcb90d56d756d
| 9,437
|
cpp
|
C++
|
C++/vbHmmModel_GaussDiffusion.cpp
|
okamoto-kenji/varBayes-HMM
|
77afe3c336c9e1ebeb115ca4f0b2bc25060556bd
|
[
"MIT"
] | 7
|
2016-03-31T06:59:00.000Z
|
2019-11-01T06:35:57.000Z
|
C++/vbHmmModel_GaussDiffusion.cpp
|
okamoto-kenji/varBayes-HMM
|
77afe3c336c9e1ebeb115ca4f0b2bc25060556bd
|
[
"MIT"
] | null | null | null |
C++/vbHmmModel_GaussDiffusion.cpp
|
okamoto-kenji/varBayes-HMM
|
77afe3c336c9e1ebeb115ca4f0b2bc25060556bd
|
[
"MIT"
] | null | null | null |
/*
* vbHmmModel_GaussDiffusion.c
* Model-specific functions for VB-HMM-GAUSS-DIFFUSION.
*
* Created by OKAMOTO Kenji, SAKO Yasushi and RIKEN
* Copyright 2011-2018
* Cellular Informatics Laboratory, Advance Science Institute, RIKEN, Japan.
* All rights reserved.
*
* Ver. 1.0.0
* Last modified on 2018.11.26
*/
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <string>
#include "vbHmm_GaussDiffusion.h"
////////// conditions
vbHmmCond_GaussDiff::vbHmmCond_GaussDiff() : vbHmmCond() {
}
vbHmmCond_GaussDiff::vbHmmCond_GaussDiff(const vbHmmCond_GaussDiff &other) : vbHmmCond( other ) { // do not copy
}
vbHmmCond_GaussDiff::~vbHmmCond_GaussDiff() {
}
////////// model
vbHmmModel_GaussDiff::vbHmmModel_GaussDiff() : vbHmmModel() {
avgDlt = NULL;
avgLnDlt = NULL;
uAArr = NULL;
uBArr = NULL;
aDlt = NULL;
bDlt = NULL;
NiR = NULL;
RiR = NULL;
}
vbHmmModel_GaussDiff::vbHmmModel_GaussDiff(const vbHmmModel_GaussDiff &other) : vbHmmModel(other) { // do not copy
avgDlt = NULL;
avgLnDlt = NULL;
uAArr = NULL;
uBArr = NULL;
aDlt = NULL;
bDlt = NULL;
NiR = NULL;
RiR = NULL;
}
vbHmmModel_GaussDiff::~vbHmmModel_GaussDiff(){
delete avgDlt;
delete avgLnDlt;
delete uAArr;
delete uBArr;
delete aDlt;
delete bDlt;
delete NiR;
delete RiR;
}
vbHmmModel *vbHmmModel_GaussDiff::newInstance(){
return new vbHmmModel_GaussDiff();
}
void vbHmmModel_GaussDiff::setSNo( int _sNo ){
vbHmmModel::setSNo( _sNo );
avgDlt = new Vec1D( sNo );
avgLnDlt = new Vec1D( sNo );
uAArr = new Vec1D( sNo );
uBArr = new Vec1D( sNo );
aDlt = new Vec1D( sNo );
bDlt = new Vec1D( sNo );
NiR = new Vec1D( sNo );
RiR = new Vec1D( sNo );
}
void vbHmmModel_GaussDiff::initialize_modelParams( vbHmmCond *c, vbHmmData *d ){
// hyper parameter for p( delta(k) )
int i;
for( i = 0 ; i < sNo ; i++ ){
uAArr->p[i] = 1.0;
uBArr->p[i] = 0.0005;
}
}
double vbHmmModel_GaussDiff::pTilde_xn_zn( vbHmmTrace *_t, int n, int i ){
double val;
vbHmmTrace_GaussDiff *t = (vbHmmTrace_GaussDiff*)_t;
val = avgLnDlt->p[i] - log(2.0);
val -= log( t->xn->p[n] ) + avgDlt->p[i] * pow( t->xn->p[n], 2.0) / 4.0;
return exp(val);
}
void vbHmmModel_GaussDiff::calcStatsVars( vbHmmData *d ){
int i, j, r, n;
double *NiRp = NiR->p, *RiRp = RiR->p, *NiiRp = NiiR->p, **NijRp = NijR->p, *z1iRp = z1iR->p;
double **gmMat, ***xiMat;
vbHmmTrace_GaussDiff *t;
for( i = 0 ; i < sNo ; i++ ){
NiRp[i] = 1e-10;
RiRp[i] = 1e-10;
NiiRp[i] = 1e-10;
for( j = 0 ; j < sNo ; j++ ){
NijRp[i][j] = 1e-10;
} // j
z1iRp[i] = 1e-10;
} // i
for( r = 0 ; r < R ; r++ ){
t = (vbHmmTrace_GaussDiff*)d->traces[r];
gmMat = ivs[r]->gmMat->p;
xiMat = ivs[r]->xiMat->p;
for( i = 0 ; i < sNo ; i++ ){
z1iRp[i] += gmMat[0][i];
for( n = 0 ; n < t->N ; n++ ){
NiRp[i] += gmMat[n][i];
RiRp[i] += gmMat[n][i] * pow( t->xn->p[n], 2.0 );
for( j = 0 ; j < sNo ; j++ ){
NiiRp[i] += xiMat[n][i][j];
NijRp[i][j] += xiMat[n][i][j];
} // j
} // n
} // i
} // r
}
int vbHmmModel_GaussDiff::maximization_modelVars( int s ){
aDlt->p[s] = uAArr->p[s] + NiR->p[s];
bDlt->p[s] = uBArr->p[s] + RiR->p[s] / 4.0;
avgDlt->p[s] = aDlt->p[s] / bDlt->p[s];
try{
avgLnDlt->p[s] = psi( aDlt->p[s] ) - log( bDlt->p[s] );
}catch (int status){
return status;
}
return 0;
}
double vbHmmModel_GaussDiff::varLowerBound_modelTerm( vbHmmData *d ){
int s;
double lnp = 0.0;
double lnq = - sNo / 2.0;
for( s = 0 ; s < sNo ; s++ ){
try{
lnp += - lnGamma(uAArr->p[s]) + uAArr->p[s] * log(uBArr->p[s]);
}catch (int status){
return numeric_limits<float>::quiet_NaN();
}
lnp += (uAArr->p[s] - 1.0) * avgLnDlt->p[s] - uBArr->p[s] * avgDlt->p[s];
try{
lnq = - lnGamma(aDlt->p[s]) + aDlt->p[s] * log(bDlt->p[s]);
}catch (int status){
return numeric_limits<float>::quiet_NaN();
}
lnq += (aDlt->p[s] - 1.0) * avgLnDlt->p[s] - aDlt->p[s];
}
return lnp - lnq;
}
void vbHmmModel_GaussDiff::reorderParameters( vbHmmData *d ){
int r, n;
int i, j;
Vec1I index( sNo );
Vec1D store( sNo );
Mat2D s2D( sNo, sNo );
// index indicates order of avgDlt values (0=biggest avgDlt -- sNo=smallest avgDlt).
for( i = 0 ; i < sNo ; i++ ){
index.p[i] = sNo - 1;
for( j = 0 ; j < sNo ; j++ ){
if( j != i ){
if( avgDlt->p[i] < avgDlt->p[j] ){
index.p[i]--;
} else if( avgDlt->p[i] == avgDlt->p[j] ){
if( j > i )
{ index.p[i]--; }
}
}
}
}
for( i = 0 ; i < sNo ; i++ ){ store.p[index.p[i]] = avgPi->p[i]; }
for( i = 0 ; i < sNo ; i++ ){ avgPi->p[i] = store.p[i]; }
for( i = 0 ; i < sNo ; i++ ){ store.p[index.p[i]] = avgLnPi->p[i]; }
for( i = 0 ; i < sNo ; i++ ){ avgLnPi->p[i] = store.p[i]; }
for( i = 0 ; i < sNo ; i++ ){ store.p[index.p[i]] = avgDlt->p[i]; }
for( i = 0 ; i < sNo ; i++ ){ avgDlt->p[i] = store.p[i]; }
for( i = 0 ; i < sNo ; i++ ){ store.p[index.p[i]] = avgLnDlt->p[i]; }
for( i = 0 ; i < sNo ; i++ ){ avgLnDlt->p[i] = store.p[i]; }
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ s2D.p[index.p[i]][index.p[j]] = avgA->p[i][j]; }
}
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ avgA->p[i][j] = s2D.p[i][j]; }
}
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ s2D.p[index.p[i]][index.p[j]] = avgLnA->p[i][j]; }
}
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ avgLnA->p[i][j] = s2D.p[i][j]; }
}
for( i = 0 ; i < sNo ; i++ ){ store.p[index.p[i]] = NiR->p[i]; }
for( i = 0 ; i < sNo ; i++ ){ NiR->p[i] = store.p[i]; }
for( r = 0 ; r < R ; r++ ){
for( n = 0 ; n < ivs[r]->N ; n++ ){
for( i = 0 ; i < sNo ; i++ ){ store.p[index.p[i]] = ivs[r]->gmMat->p[n][i]; }
for( i = 0 ; i < sNo ; i++ ){ ivs[r]->gmMat->p[n][i] = store.p[i]; }
}
}
for( r = 0 ; r < R ; r++ ){
for( n = 0 ; n < ivs[r]->N ; n++ ){
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ s2D.p[index.p[i]][index.p[j]] = ivs[r]->xiMat->p[n][i][j]; }
}
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ ivs[r]->xiMat->p[n][i][j] = s2D.p[i][j]; }
}
}
}
}
void vbHmmModel_GaussDiff::outputResults( vbHmmData *d, fstream *logFS ){
int i, j;
char str[1024];
*logFS << " results: K = " << sNo << endl;
*logFS << " delta: ( " << avgDlt->p[0];
for( i = 1 ; i < sNo ; i++ ){
sprintf(str, ", %g", avgDlt->p[i]);
*logFS << str;
}
*logFS << " )" << endl;
*logFS << " pi: ( " << avgPi->p[0];
for( i = 1 ; i < sNo ; i++ ){
sprintf(str, ", %g", avgPi->p[i]);
*logFS << str;
}
*logFS << " )" << endl;
*logFS << " A_matrix: [";
for( i = 0 ; i < sNo ; i++ ){
sprintf(str, " ( %g", avgA->p[i][0]);
*logFS << str;
for( j = 1 ; j < sNo ; j++ ){
sprintf(str, ", %g", avgA->p[i][j]);
*logFS << str;
}
*logFS << ")";
}
*logFS << " ]" << endl << endl;
char fn[1024];
fstream fs;
int n;
sprintf( fn, "%s.param%03d", d->name.c_str(), sNo );
fs.open( fn, ios::out );
if( fs.is_open() ){
fs << "delta, pi";
for( i = 0 ; i < sNo ; i++ ){
sprintf(str, ", A%dx", i);
fs << str;
}
fs << endl;
for( i = 0 ; i < sNo ; i++ ){
sprintf(str, "%g, %g", avgDlt->p[i], avgPi->p[i]);
fs << str;
for( j = 0 ; j < sNo ; j++ ){
sprintf(str, ", %g", avgA->p[j][i]);
fs << str;
}
fs << endl;
}
fs.close();
}
sprintf( fn, "%s.Lq%03d", d->name.c_str(), sNo );
fs.open( fn, ios::out );
if( fs.is_open() ){
for( n = 0 ; n < iteration ; n++ ){
sprintf( str, "%24.20e", LqArr->p[n] );
fs << str << endl;
}
fs.close();
}
int r;
sprintf( fn, "%s.maxS%03d", d->name.c_str(), sNo );
int flag = 0;
fs.open( fn, ios::out );
if( fs.is_open() ){
n = 0;
do{
flag = 1;
for( r = 0 ; r < R ; r++ ){
if( r > 0 ){
fs << ",";
}
if( n < d->traces[r]->N ){
sprintf( str, "%d", ivs[r]->stateTraj->p[n] );
fs << str;
}
flag &= (n >= (d->traces[r]->N - 1));
}
fs << endl;
n++;
}while( !flag );
fs.close();
}
}
//
| 27.51312
| 115
| 0.431175
|
okamoto-kenji
|
0cf2f397849efc524d2c82873c589cc900e91101
| 14,286
|
cpp
|
C++
|
src/ui/screens/viewfilescreen.cpp
|
hrxcodes/cbftp
|
bf2784007dcc4cc42775a2d40157c51b80383f81
|
[
"MIT"
] | 8
|
2019-04-30T00:37:00.000Z
|
2022-02-03T13:35:31.000Z
|
src/ui/screens/viewfilescreen.cpp
|
Xtravaganz/cbftp
|
31a3465e2cd539f6cf35a5d9a0bb9c5c2f639cd5
|
[
"MIT"
] | 2
|
2019-11-19T12:46:13.000Z
|
2019-12-20T22:13:57.000Z
|
src/ui/screens/viewfilescreen.cpp
|
Xtravaganz/cbftp
|
31a3465e2cd539f6cf35a5d9a0bb9c5c2f639cd5
|
[
"MIT"
] | 9
|
2020-01-15T02:38:36.000Z
|
2022-02-15T20:05:20.000Z
|
#include "viewfilescreen.h"
#include "transfersscreen.h"
#include "../ui.h"
#include "../menuselectoption.h"
#include "../resizableelement.h"
#include "../menuselectadjustableline.h"
#include "../menuselectoptiontextbutton.h"
#include "../termint.h"
#include "../misc.h"
#include "../../transferstatus.h"
#include "../../globalcontext.h"
#include "../../sitelogicmanager.h"
#include "../../sitelogic.h"
#include "../../transfermanager.h"
#include "../../localstorage.h"
#include "../../localfilelist.h"
#include "../../filelist.h"
#include "../../file.h"
#include "../../externalfileviewing.h"
#include "../../core/types.h"
class CommandOwner;
namespace ViewFileState {
enum {
NO_SLOTS_AVAILABLE,
TOO_LARGE_FOR_INTERNAL,
NO_DISPLAY,
CONNECTING,
DOWNLOADING,
LOADING_VIEWER,
VIEWING_EXTERNAL,
VIEWING_INTERNAL
};
}
namespace {
enum KeyScopes {
KEYSCOPE_VIEWING_INTERNAL,
KEYSCOPE_VIEWING_EXTERNAL
};
enum KeyAction {
KEYACTION_ENCODING,
KEYACTION_KILL,
KEYACTION_KILL_ALL
};
}
ViewFileScreen::ViewFileScreen(Ui* ui) : UIWindow(ui, "ViewFileScreen") {
keybinds.addScope(KEYSCOPE_VIEWING_INTERNAL, "During internal viewing");
keybinds.addScope(KEYSCOPE_VIEWING_EXTERNAL, "During external viewing");
keybinds.addBind('c', KEYACTION_BACK_CANCEL, "Return");
keybinds.addBind(KEY_UP, KEYACTION_UP, "Navigate up", KEYSCOPE_VIEWING_INTERNAL);
keybinds.addBind(KEY_DOWN, KEYACTION_DOWN, "Navigate down", KEYSCOPE_VIEWING_INTERNAL);
keybinds.addBind(KEY_PPAGE, KEYACTION_PREVIOUS_PAGE, "Next page", KEYSCOPE_VIEWING_INTERNAL);
keybinds.addBind(KEY_NPAGE, KEYACTION_NEXT_PAGE, "Previous page", KEYSCOPE_VIEWING_INTERNAL);
keybinds.addBind('e', KEYACTION_ENCODING, "Switch encoding", KEYSCOPE_VIEWING_INTERNAL);
keybinds.addBind('k', KEYACTION_KILL, "Kill external viewer", KEYSCOPE_VIEWING_EXTERNAL);
}
ViewFileScreen::~ViewFileScreen() {
}
void ViewFileScreen::initialize() {
rawcontents.clear();
x = 0;
y = 0;
ymax = 0;
xmax = 0;
externallyviewable = false;
legendupdated = false;
pid = 0;
autoupdate = true;
ts.reset();
}
void ViewFileScreen::initialize(unsigned int row, unsigned int col, const std::string & site, const std::string & file, const std::shared_ptr<FileList>& fl) {
initialize();
deleteafter = true;
this->site = site;
this->file = file;
filelist = fl;
sitelogic = global->getSiteLogicManager()->getSiteLogic(site);
size = filelist->getFile(file)->getSize();
state = ViewFileState::CONNECTING;
if (global->getExternalFileViewing()->isViewable(file)) {
if (!global->getExternalFileViewing()->hasDisplay()) {
state = ViewFileState::NO_DISPLAY;
}
externallyviewable = true;
}
else {
if (size > MAXOPENSIZE) {
state = ViewFileState::TOO_LARGE_FOR_INTERNAL;
}
}
if (state == ViewFileState::CONNECTING) {
requestid = sitelogic->requestOneIdle(ui);
}
if (state == ViewFileState::DOWNLOADING) {
if (!ts) {
state = ViewFileState::NO_SLOTS_AVAILABLE;
}
else {
}
}
init(row, col);
}
void ViewFileScreen::initialize(unsigned int row, unsigned int col, const Path & dir, const std::string & file) {
initialize();
deleteafter = false;
path = dir / file;
this->file = file;
size = global->getLocalStorage()->getFileSize(path);
state = ViewFileState::LOADING_VIEWER;
if (global->getExternalFileViewing()->isViewable(file)) {
if (!global->getExternalFileViewing()->hasDisplay()) {
state = ViewFileState::NO_DISPLAY;
}
externallyviewable = true;
}
else {
if (size > MAXOPENSIZE) {
state = ViewFileState::TOO_LARGE_FOR_INTERNAL;
}
}
init(row, col);
}
void ViewFileScreen::redraw() {
ui->erase();
switch (state) {
case ViewFileState::NO_SLOTS_AVAILABLE:
ui->printStr(1, 1, "No download slots available at " + site + ".");
break;
case ViewFileState::TOO_LARGE_FOR_INTERNAL:
ui->printStr(1, 1, file + " is too large to download and open in the internal viewer.");
ui->printStr(2, 1, "The maximum file size for internal viewing is set to " + std::to_string(MAXOPENSIZE) + " bytes.");
break;
case ViewFileState::NO_DISPLAY:
ui->printStr(1, 1, file + " cannot be opened in an external viewer.");
ui->printStr(2, 1, "The DISPLAY environment variable is not set.");
break;
case ViewFileState::CONNECTING:
if (sitelogic->requestReady(requestid)) {
sitelogic->finishRequest(requestid);
const Path & temppath = global->getLocalStorage()->getTempPath();
std::shared_ptr<LocalFileList> localfl = global->getLocalStorage()->getLocalFileList(temppath);
ts = global->getTransferManager()->suggestDownload(file, sitelogic, filelist, localfl);
if (!!ts) {
state = ViewFileState::DOWNLOADING;
ts->setAwaited(true);
path = temppath / file;
expectbackendpush = true;
}
else {
state = ViewFileState::NO_SLOTS_AVAILABLE;
redraw();
}
}
else {
ui->printStr(1, 1, "Awaiting slot...");
}
break;
case ViewFileState::DOWNLOADING:
switch(ts->getState()) {
case TRANSFERSTATUS_STATE_IN_PROGRESS:
ui->printStr(1, 1, "Downloading from " + site + "...");
printTransferInfo();
break;
case TRANSFERSTATUS_STATE_FAILED:
ui->printStr(1, 1, "Download of " + file + " from " + site + " failed.");
autoupdate = false;
break;
case TRANSFERSTATUS_STATE_SUCCESSFUL:
loadViewer();
break;
}
break;
case ViewFileState::LOADING_VIEWER:
loadViewer();
break;
case ViewFileState::VIEWING_EXTERNAL:
viewExternal();
break;
case ViewFileState::VIEWING_INTERNAL:
viewInternal();
break;
}
}
void ViewFileScreen::update() {
if (pid) {
if (!global->getExternalFileViewing()->stillViewing(pid)) {
ui->returnToLast();
}
else if (!legendupdated) {
legendupdated = true;
ui->update();
ui->setLegend();
}
}
else {
redraw();
if ((state == ViewFileState::VIEWING_INTERNAL || state == ViewFileState::VIEWING_EXTERNAL)
&& !legendupdated)
{
legendupdated = true;
ui->update();
ui->setLegend();
}
}
}
bool ViewFileScreen::keyPressed(unsigned int ch) {
int scope = getCurrentScope();
int action = keybinds.getKeyAction(ch, scope);
switch(action) {
case KEYACTION_BACK_CANCEL:
ui->returnToLast();
return true;
case KEYACTION_DOWN:
if (goDown()) {
goDown();
ui->setInfo();
ui->redraw();
}
return true;
case KEYACTION_UP:
if (goUp()) {
goUp();
ui->setInfo();
ui->redraw();
}
return true;
case KEYACTION_NEXT_PAGE:
for (unsigned int i = 0; i < row / 2; i++) {
goDown();
}
ui->setInfo();
ui->redraw();
return true;
case KEYACTION_PREVIOUS_PAGE:
for (unsigned int i = 0; i < row / 2; i++) {
goUp();
}
ui->setInfo();
ui->redraw();
return true;
case KEYACTION_KILL:
if (pid) {
global->getExternalFileViewing()->killProcess(pid);
}
return true;
case KEYACTION_ENCODING:
if (state == ViewFileState::VIEWING_INTERNAL) {
if (encoding == encoding::ENCODING_CP437) {
encoding = encoding::ENCODING_CP437_DOUBLE;
}
else if (encoding == encoding::ENCODING_CP437_DOUBLE) {
encoding = encoding::ENCODING_ISO88591;
}
else if (encoding == encoding::ENCODING_ISO88591) {
encoding = encoding::ENCODING_UTF8;
}
else {
encoding = encoding::ENCODING_CP437;
}
translate();
ui->redraw();
ui->setInfo();
}
return true;
}
return false;
}
void ViewFileScreen::loadViewer() {
if (externallyviewable) {
if (!pid) {
if (deleteafter) {
pid = global->getExternalFileViewing()->viewThenDelete(path);
}
else {
pid = global->getExternalFileViewing()->view(path);
}
}
state = ViewFileState::VIEWING_EXTERNAL;
viewExternal();
}
else {
Core::BinaryData tmpdata = global->getLocalStorage()->getFileContent(path);
if (deleteafter) {
global->getLocalStorage()->requestDelete(path);
}
std::string extension = File::getExtension(file);
encoding = encoding::guessEncoding(tmpdata);
unsigned int tmpdatalen = tmpdata.size();
if (tmpdatalen > 0) {
std::string current;
for (unsigned int i = 0; i < tmpdatalen; i++) {
if (tmpdata[i] == '\n') {
rawcontents.push_back(current);
current.clear();
}
else {
current += tmpdata[i];
}
}
if (current.length() > 0) {
rawcontents.push_back(current);
}
translate();
}
autoupdate = false;
state = ViewFileState::VIEWING_INTERNAL;
viewInternal();
}
}
void ViewFileScreen::viewExternal() {
ui->printStr(1, 1, "Opening " + file + " with: " + global->getExternalFileViewing()->getViewApplication(file));
ui->printStr(3, 1, "Press 'k' to kill this external viewer instance.");
ui->printStr(4, 1, "You can always press 'K' to kill ALL external viewers.");
}
void ViewFileScreen::viewInternal() {
if (ymax <= row) {
y = 0;
}
while (ymax > row && y + row > ymax) {
--y;
}
ymax = rawcontents.size();
for (unsigned int i = 0; i < ymax; i++) {
if (translatedcontents[i].length() > xmax) {
xmax = translatedcontents[i].length();
}
}
for (unsigned int i = 0; i < row && i < ymax; i++) {
std::basic_string<unsigned int> & line = translatedcontents[y + i];
for (unsigned int j = 0; j < line.length() && j < col - 2; j++) {
ui->printChar(i, j + 1, line[j]);
}
}
printSlider(ui, row, col - 1, ymax, y);
}
std::string ViewFileScreen::getLegendText() const {
return keybinds.getLegendSummary(getCurrentScope());
}
std::string ViewFileScreen::getInfoLabel() const {
return "VIEW FILE: " + file;
}
std::string ViewFileScreen::getInfoText() const {
if (state == ViewFileState::VIEWING_INTERNAL) {
std::string enc;
switch (encoding) {
case encoding::ENCODING_CP437:
enc = "CP437";
break;
case encoding::ENCODING_CP437_DOUBLE:
enc = "Double CP437";
break;
case encoding::ENCODING_ISO88591:
enc = "ISO-8859-1";
break;
case encoding::ENCODING_UTF8:
enc = "UTF-8";
break;
}
unsigned int end = ymax < y + row ? ymax : y + row;
return "Line " + std::to_string(y) + "-" +
std::to_string(end) + "/" + std::to_string(ymax) + " Encoding: " + enc;
}
else {
return "";
}
}
void ViewFileScreen::translate() {
translatedcontents.clear();
for (unsigned int i = 0; i < rawcontents.size(); i++) {
std::basic_string<unsigned int> current;
if (encoding == encoding::ENCODING_CP437_DOUBLE) {
current = encoding::doublecp437toUnicode(rawcontents[i]);
}
else if (encoding == encoding::ENCODING_CP437) {
current = encoding::cp437toUnicode(rawcontents[i]);
}
else if (encoding == encoding::ENCODING_ISO88591) {
current = encoding::toUnicode(rawcontents[i]);
}
else {
current = encoding::utf8toUnicode(rawcontents[i]);
}
translatedcontents.push_back(current);
}
}
bool ViewFileScreen::goDown() {
if (y + row < ymax) {
y++;
return true;
}
return false;
}
bool ViewFileScreen::goUp() {
if (y > 0) {
y--;
return true;
}
return false;
}
void ViewFileScreen::printTransferInfo() {
TransferDetails td = TransfersScreen::formatTransferDetails(ts);
unsigned int y = 3;
MenuSelectOption table;
std::shared_ptr<MenuSelectAdjustableLine> msal = table.addAdjustableLine();
std::shared_ptr<MenuSelectOptionTextButton> msotb;
msotb = table.addTextButtonNoContent(y, 1, "transferred", "TRANSFERRED");
msal->addElement(msotb, 4, RESIZE_CUTEND);
msotb = table.addTextButtonNoContent(y, 3, "filename", "FILENAME");
msal->addElement(msotb, 2, RESIZE_CUTEND);
msotb = table.addTextButtonNoContent(y, 6, "remaining", "LEFT");
msal->addElement(msotb, 5, RESIZE_REMOVE);
msotb = table.addTextButtonNoContent(y, 7, "speed", "SPEED");
msal->addElement(msotb, 6, RESIZE_REMOVE);
msotb = table.addTextButtonNoContent(y, 8, "progress", "DONE");
msal->addElement(msotb, 7, RESIZE_REMOVE);
y++;
msal = table.addAdjustableLine();
msotb = table.addTextButtonNoContent(y, 1, "transferred", td.transferred);
msal->addElement(msotb, 4, RESIZE_CUTEND);
msotb = table.addTextButtonNoContent(y, 10, "filename", ts->getFile());
msal->addElement(msotb, 2, RESIZE_WITHLAST3);
msotb = table.addTextButtonNoContent(y, 60, "remaining", td.timeremaining);
msal->addElement(msotb, 5, RESIZE_REMOVE);
msotb = table.addTextButtonNoContent(y, 40, "speed", td.speed);
msal->addElement(msotb, 6, RESIZE_REMOVE);
msotb = table.addTextButtonNoContent(y, 50, "progress", td.progress);
msal->addElement(msotb, 7, RESIZE_REMOVE);
table.adjustLines(col - 3);
for (unsigned int i = 0; i < table.size(); i++) {
std::shared_ptr<ResizableElement> re = std::static_pointer_cast<ResizableElement>(table.getElement(i));
if (re->isVisible()) {
if (re->getIdentifier() == "transferred") {
std::string labeltext = re->getLabelText();
bool highlight = table.getLineIndex(table.getAdjustableLine(re)) == 1;
int charswithhighlight = highlight ? labeltext.length() * ts->getProgress() / 100 : 0;
ui->printStr(re->getRow(), re->getCol(), labeltext.substr(0, charswithhighlight), true);
ui->printStr(re->getRow(), re->getCol() + charswithhighlight, labeltext.substr(charswithhighlight));
}
else {
ui->printStr(re->getRow(), re->getCol(), re->getLabelText());
}
}
}
}
int ViewFileScreen::getCurrentScope() const {
if (state == ViewFileState::VIEWING_EXTERNAL) {
return KEYSCOPE_VIEWING_EXTERNAL;
}
if (state == ViewFileState::VIEWING_INTERNAL) {
return KEYSCOPE_VIEWING_INTERNAL;
}
return KEYSCOPE_ALL;
}
| 29.395062
| 158
| 0.635167
|
hrxcodes
|
0cf47a1d8c1d0f3b8941f22a174d4530afc93b7d
| 1,063
|
hpp
|
C++
|
alignment/files/ReaderAgglomerateImpl.hpp
|
ggraham/blasr_libcpp
|
4abef36585bbb677ebc4acb9d4e44e82331d59f7
|
[
"RSA-MD"
] | 4
|
2015-07-03T11:59:54.000Z
|
2018-05-17T00:03:22.000Z
|
alignment/files/ReaderAgglomerateImpl.hpp
|
ggraham/blasr_libcpp
|
4abef36585bbb677ebc4acb9d4e44e82331d59f7
|
[
"RSA-MD"
] | 79
|
2015-06-29T18:07:21.000Z
|
2018-09-19T13:38:39.000Z
|
alignment/files/ReaderAgglomerateImpl.hpp
|
ggraham/blasr_libcpp
|
4abef36585bbb677ebc4acb9d4e44e82331d59f7
|
[
"RSA-MD"
] | 19
|
2015-06-23T08:43:29.000Z
|
2021-04-28T18:37:47.000Z
|
#ifndef _BLASR_READER_AGGLOMERATE_IMPL_HPP_
#define _BLASR_READER_AGGLOMERATE_IMPL_HPP_
template <typename T_Sequence>
int ReaderAgglomerate::GetNext(T_Sequence &seq, int &randNum)
{
randNum = rand();
return GetNext(seq);
}
template <typename T_Sequence>
int ReadChunkByNReads(ReaderAgglomerate &reader, std::vector<T_Sequence> &reads, int maxNReads)
{
T_Sequence seq;
int nReads = 0;
while (nReads < maxNReads) {
if (reader.GetNext(seq)) {
reads.push_back(seq);
++nReads;
} else {
break;
}
}
return nReads;
}
template <typename T_Sequence>
int ReadChunkBySize(ReaderAgglomerate &reader, std::vector<T_Sequence> &reads, int maxMemorySize)
{
T_Sequence seq;
int nReads = 0;
int totalStorage = 0;
while (totalStorage < maxMemorySize) {
if (reader.GetNext(seq)) {
reads.push_back(seq);
totalStorage += seq.GetStorageSize();
nReads++;
} else {
break;
}
}
return nReads;
}
#endif
| 23.108696
| 97
| 0.627469
|
ggraham
|
0cf54ce58b46f3ba5654eef039f7fb86939d2e7e
| 375
|
cpp
|
C++
|
GameEngine/CoreEngine/CoreEngine/src/DrawSceneOperation.cpp
|
mettaursp/SuddenlyGames
|
e2ff1c2771d4ca54824650e4f1a33a527536ca61
|
[
"Apache-2.0"
] | 1
|
2021-01-17T13:05:20.000Z
|
2021-01-17T13:05:20.000Z
|
GameEngine/CoreEngine/CoreEngine/src/DrawSceneOperation.cpp
|
suddenly-games/SuddenlyGames
|
e2ff1c2771d4ca54824650e4f1a33a527536ca61
|
[
"Apache-2.0"
] | null | null | null |
GameEngine/CoreEngine/CoreEngine/src/DrawSceneOperation.cpp
|
suddenly-games/SuddenlyGames
|
e2ff1c2771d4ca54824650e4f1a33a527536ca61
|
[
"Apache-2.0"
] | null | null | null |
#include "DrawSceneOperation.h"
#include "Graphics.h"
namespace GraphicsEngine
{
void DrawSceneOperation::Configure(const std::shared_ptr<Scene>& scene)
{
CurrentScene = scene;
}
void DrawSceneOperation::Render()
{
Graphics::SetClearColor(RGBA(0x000000FF));
Graphics::ClearScreen(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
CurrentScene.lock()->Draw();
}
}
| 18.75
| 72
| 0.749333
|
mettaursp
|
0cf7d3785efe69b943c01dc937f7f1bc78493d04
| 625
|
cpp
|
C++
|
Framework/Sources/o2/Utils/Memory/Allocators/StackAllocator.cpp
|
zenkovich/o2
|
cdbf10271f1bf0f3198c8005b13b66e6ca13a9db
|
[
"MIT"
] | 181
|
2015-12-09T08:53:36.000Z
|
2022-03-26T20:48:39.000Z
|
Framework/Sources/o2/Utils/Memory/Allocators/StackAllocator.cpp
|
zenkovich/o2
|
cdbf10271f1bf0f3198c8005b13b66e6ca13a9db
|
[
"MIT"
] | 29
|
2016-04-22T08:24:04.000Z
|
2022-03-06T07:06:28.000Z
|
Framework/Sources/o2/Utils/Memory/Allocators/StackAllocator.cpp
|
zenkovich/o2
|
cdbf10271f1bf0f3198c8005b13b66e6ca13a9db
|
[
"MIT"
] | 13
|
2018-04-24T17:12:04.000Z
|
2021-11-12T23:49:53.000Z
|
#include "o2/stdafx.h"
#include "StackAllocator.h"
namespace o2
{
StackAllocator::StackAllocator(size_t capacity, IAllocator* baseAllocator /*= DefaultAllocator::GetInstance()*/):
mBaseAllocator(baseAllocator)
{
mInitialCapacity = capacity;
Initialize();
}
StackAllocator::~StackAllocator()
{
Clear();
}
void StackAllocator::Clear()
{
mBaseAllocator->Deallocate(mStack);
mStack = nullptr;
mStackEnd = nullptr;
mTop = nullptr;
}
void StackAllocator::Initialize()
{
mStack = (std::byte*)mBaseAllocator->Allocate(mInitialCapacity);
mTop = mStack;
mStackEnd = mStack + mInitialCapacity;
}
}
| 18.939394
| 114
| 0.7168
|
zenkovich
|
490922b8449248ae20f988401452233f96ebe02d
| 922
|
hpp
|
C++
|
src/app/validator-manager.hpp
|
mimo31/fluid-sim
|
481c3e5a5456350bccb8795aa119a3487dff3021
|
[
"MIT"
] | 1
|
2020-11-26T17:20:28.000Z
|
2020-11-26T17:20:28.000Z
|
src/app/validator-manager.hpp
|
mimo31/brandy0
|
481c3e5a5456350bccb8795aa119a3487dff3021
|
[
"MIT"
] | null | null | null |
src/app/validator-manager.hpp
|
mimo31/brandy0
|
481c3e5a5456350bccb8795aa119a3487dff3021
|
[
"MIT"
] | null | null | null |
/**
* validator-manager.hpp
*
* Author: Viktor Fukala
* Created on 2021/01/16
*/
#ifndef VALIDATOR_MANAGER_HPP
#define VALIDATOR_MANAGER_HPP
#include "func.hpp"
#include "vec.hpp"
namespace brandy0
{
/**
* Container for arbitrarily many bool(void) callbacks.
* Callbacks (a.k.a. validators) can be dynamically added and it can be queries whether they all evaluate to true.
* Meant primarily for user input validation -- each entry can have its validator and the form can be submitted only if all validators evaluate to true.
*/
class ValidatorManager
{
private:
/// Vector of all registered validators
vec<BoolFunc> validators;
public:
/**
* Registers a new validator
* @param validator validator to register
*/
void plug(const BoolFunc& validator);
/**
* @return true iff all currently registered validators evaluate to true
*/
bool isAllValid() const;
};
}
#endif // VALIDATOR_MANAGER_HPP
| 22.487805
| 152
| 0.736443
|
mimo31
|
490a0b2c5d3f200f97d3a3bb3d45a66064b53d8d
| 2,408
|
cpp
|
C++
|
utilities/Socket.cpp
|
JKowalsky/ftp-client
|
daa81b546b399907cdd77bc639ad61a3b17b5939
|
[
"MIT"
] | null | null | null |
utilities/Socket.cpp
|
JKowalsky/ftp-client
|
daa81b546b399907cdd77bc639ad61a3b17b5939
|
[
"MIT"
] | null | null | null |
utilities/Socket.cpp
|
JKowalsky/ftp-client
|
daa81b546b399907cdd77bc639ad61a3b17b5939
|
[
"MIT"
] | null | null | null |
/*
* File: Socket.cpp
* Author: kowalsky
*
* Created on November 30, 2014, 4:49 PM
*/
#include "Socket.h"
Socket::Socket(int port)
: port(port), clientFd(NULL_FD), serverFd(NULL_FD) {
}
Socket::~Socket() {
if (clientFd != NULL_FD)
close(clientFd);
if (serverFd != NULL_FD)
close(serverFd);
}
int Socket::getClientSocket(char ipName[]) {
return getClientSocket(ipName, 0, false);
}
int Socket::getClientSocket(char ipName[], int sndbufsize, bool nodelay) {
// Get the host entry corresponding to ipName
struct hostent* host = gethostbyname(ipName);
if (host == NULL) {
perror("Cannot find hostname.");
return NULL_FD;
}
// Fill in the structure "sendSockAddr" with the address of the server.
sockaddr_in sendSockAddr;
bzero((char*) &sendSockAddr, sizeof ( sendSockAddr));
sendSockAddr.sin_family = AF_INET; // Address Family Internet
sendSockAddr.sin_addr.s_addr =
inet_addr(inet_ntoa(*(struct in_addr*) *host->h_addr_list));
sendSockAddr.sin_port = htons(port);
// Open a TCP socket (an Internet strem socket).
if ((clientFd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
perror("Cannot open a client TCP socket.");
return NULL_FD;
}
// Set the rcvbuf option
if (sndbufsize > 0) {
cout << sndbufsize << endl;
if (setsockopt(clientFd, SOL_SOCKET, SO_SNDBUF,
(char *) &sndbufsize, sizeof ( sndbufsize)) < 0) {
perror("setsockopt SO_SNDBUF failed");
return NULL_FD;
}
}
// Set the nodelay option
if (nodelay == true) {
int on = 1;
if (setsockopt(clientFd, IPPROTO_TCP, TCP_NODELAY,
(char *) &on, sizeof ( int)) < 0) {
perror("setsockopt TCP_NODELAY failed");
return NULL_FD;
}
}
// Connect to the server.
while (connect(clientFd, (sockaddr*) & sendSockAddr,
sizeof ( sendSockAddr)) < 0);
// Connected
return clientFd;
}
int Socket::pollRecvFrom() {
struct pollfd pfd[1];
pfd[0].fd = clientFd; // declare I'll check the data availability of sd
pfd[0].events = POLLRDNORM; // declare I'm interested in only reading from sd
// check it for 2 seconds and return a positive number if sd is readable,
// otherwise return 0 or a negative number
return poll( pfd, 1, 1000 );
}
| 27.678161
| 79
| 0.616694
|
JKowalsky
|
490b9fb710f1e9195b51c1e5af31415cecfc6a0f
| 1,996
|
cpp
|
C++
|
test/test_crossentropyloss_layer.cpp
|
sdadia/deep-learning-and-optimization
|
b44be79de116e2d4b203452a161641519f18f580
|
[
"MIT"
] | 1
|
2018-10-02T15:29:14.000Z
|
2018-10-02T15:29:14.000Z
|
test/test_crossentropyloss_layer.cpp
|
sdadia/deep-learning-and-optimization
|
b44be79de116e2d4b203452a161641519f18f580
|
[
"MIT"
] | null | null | null |
test/test_crossentropyloss_layer.cpp
|
sdadia/deep-learning-and-optimization
|
b44be79de116e2d4b203452a161641519f18f580
|
[
"MIT"
] | null | null | null |
#include "crossentropyloss_layer.hpp"
#include "common.hpp"
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include <glog/logging.h>
TEST(CrossEntropyLossLayer, CheckNumInputs)
{
// if zero inputs, then a problem will occour
std::vector<dtensor_t> input(2);
std::vector<dtensor_t> labels(2);
dpl::CrossEntropyLossLayer p;
p.setUp(input, labels);
}
TEST(CrossEntropyLossLayer, forward)
{
// input, label, and true value
dtensor_t p1{123, 456, 789}, p2{1, -2, 0}, p3 {0.5,-1, 0};
dtensor_t l1{1,0,0}, l2{0,1,0}, l3{0,0,1};
dtensor_t t1{0.0,0.0,1.0}, t2{0.705384,0.035119, 0.259496}, t3{0.546549,0.121951,0.331498};
std::vector<dtensor_t> input{p1,p2,p3}, labels{l1,l2,l3}, true_values{t1,t2,t3};
dpl::CrossEntropyLossLayer p;
p.setUp(input, labels);
auto output = p.forward();
for(uint_t i=0; i<output.size(); i++)
{
auto output_raw_data = output[i].raw_data();
auto true_value_raw_data = true_values[i].raw_data();
EXPECT_TRUE(AreFloatingPointArraysEqual(output_raw_data, true_value_raw_data, output[i].size()));
}
}
TEST(CrossEntropyLossLayer, backward)
{
// input, label, and true value
dtensor_t p1{123, 456, 789}, p2{1, -2, 0}, p3 {0.5,-1, 0};
dtensor_t l1{1,0,0}, l2{0,1,0}, l3{0,0,1};
dtensor_t t1{0.0,0.0,1.0}, t2{0.705384,0.035119, 0.259496}, t3{0.546549,0.121951,0.331498};
//dtensor_t g1{}
std::vector<dtensor_t> input{p1,p2,p3}, labels{l1,l2,l3}, true_values{t1,t2,t3};
dpl::CrossEntropyLossLayer p;
p.setUp(input, labels);
auto output = p.forward();
for(uint_t i=0; i<output.size(); i++)
{
auto output_raw_data = output[i].raw_data();
auto true_value_raw_data = true_values[i].raw_data();
EXPECT_TRUE(AreFloatingPointArraysEqual(output_raw_data, true_value_raw_data, output[i].size()));
}
}
int main(int argc, char** argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 25.922078
| 105
| 0.648798
|
sdadia
|
490ead04603ff489afc8802626c59b089b8e5a47
| 2,791
|
cpp
|
C++
|
Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32F769I_EVAL/Demonstrations/TouchGFX/Gui/generated/fonts/src/Table_RobotoCondensed_Bold_42_4bpp.cpp
|
ramkumarkoppu/NUCLEO-F767ZI-ESW
|
85e129d71ee8eccbd0b94b5e07e75b6b91679ee8
|
[
"MIT"
] | null | null | null |
Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32F769I_EVAL/Demonstrations/TouchGFX/Gui/generated/fonts/src/Table_RobotoCondensed_Bold_42_4bpp.cpp
|
ramkumarkoppu/NUCLEO-F767ZI-ESW
|
85e129d71ee8eccbd0b94b5e07e75b6b91679ee8
|
[
"MIT"
] | null | null | null |
Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32F769I_EVAL/Demonstrations/TouchGFX/Gui/generated/fonts/src/Table_RobotoCondensed_Bold_42_4bpp.cpp
|
ramkumarkoppu/NUCLEO-F767ZI-ESW
|
85e129d71ee8eccbd0b94b5e07e75b6b91679ee8
|
[
"MIT"
] | null | null | null |
#include <touchgfx/Font.hpp>
#ifndef NO_USING_NAMESPACE_TOUCHGFX
using namespace touchgfx;
#endif
FONT_LOCATION_FLASH_PRAGMA
KEEP extern const touchgfx::GlyphNode glyphs_RobotoCondensed_Bold_42_4bpp[] FONT_LOCATION_FLASH_ATTRIBUTE = {
{ 0, 2, 0, 0, 0, 0, 1, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0},
{ 0, 48, 19, 30, 30, 1, 21, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0},
{ 300, 49, 12, 30, 30, 3, 21, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0},
{ 480, 50, 19, 30, 30, 1, 21, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0},
{ 780, 51, 19, 30, 30, 1, 21, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0},
{ 1080, 52, 19, 30, 30, 1, 21, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0},
{ 1380, 53, 19, 30, 30, 1, 21, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0},
{ 1680, 54, 18, 30, 30, 2, 21, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0},
{ 1950, 55, 19, 30, 30, 1, 21, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0},
{ 2250, 56, 18, 30, 30, 2, 21, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0},
{ 2520, 57, 19, 30, 30, 1, 21, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0},
{ 2820, 65, 25, 30, 30, 0, 25, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0},
{ 3210, 66, 20, 30, 30, 2, 24, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0},
{ 3510, 67, 22, 30, 30, 1, 24, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0},
{ 3840, 68, 20, 30, 30, 2, 24, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0},
{ 4140, 69, 18, 30, 30, 2, 21, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0},
{ 4410, 70, 17, 30, 30, 2, 20, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0},
{ 4680, 71, 22, 30, 30, 1, 25, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0},
{ 5010, 74, 19, 30, 30, 0, 21, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0},
{ 5310, 76, 18, 30, 30, 2, 20, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0},
{ 5580, 77, 28, 30, 30, 2, 32, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0},
{ 6000, 78, 22, 30, 30, 2, 26, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0},
{ 6330, 79, 23, 30, 30, 1, 25, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0},
{ 6690, 80, 21, 30, 30, 2, 24, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0},
{ 7020, 82, 21, 30, 30, 2, 23, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0},
{ 7350, 83, 21, 30, 30, 1, 23, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0},
{ 7680, 84, 21, 30, 30, 1, 23, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0},
{ 8010, 85, 20, 30, 30, 2, 24, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0},
{ 8310, 86, 24, 30, 30, 0, 24, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0},
{ 8670, 89, 23, 30, 30, 0, 23, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0}
};
| 66.452381
| 109
| 0.58402
|
ramkumarkoppu
|
490fbeba6c6750fd5f4936f931923bec5b4fc099
| 1,940
|
hpp
|
C++
|
caffe/include/caffe/layers/sparse_hypercolumn_extractor_layer.hpp
|
gustavla/autocolorizer
|
79d4ce1054d35c06bdfcc93236b71e161e082ebb
|
[
"BSD-3-Clause"
] | 234
|
2016-04-04T15:12:24.000Z
|
2022-03-14T12:55:09.000Z
|
caffe/include/caffe/layers/sparse_hypercolumn_extractor_layer.hpp
|
TrinhQuocNguyen/autocolorize
|
79d4ce1054d35c06bdfcc93236b71e161e082ebb
|
[
"BSD-3-Clause"
] | 20
|
2016-04-05T12:44:04.000Z
|
2022-02-22T06:02:17.000Z
|
caffe/include/caffe/layers/sparse_hypercolumn_extractor_layer.hpp
|
TrinhQuocNguyen/autocolorize
|
79d4ce1054d35c06bdfcc93236b71e161e082ebb
|
[
"BSD-3-Clause"
] | 71
|
2016-07-12T15:28:16.000Z
|
2021-12-16T12:22:57.000Z
|
#ifndef CAFFE_SPARSE_HYPERCOLUMN_LAYER_HPP
#define CAFFE_SPARSE_HYPERCOLUMN_LAYER_HPP
#include <string>
#include <utility>
#include <vector>
#include "caffe/blob.hpp"
#include "caffe/common.hpp"
#include "caffe/layer.hpp"
namespace caffe {
/**
* \ingroup ttic
* @brief This extracts locations of hypercolumns. It should be faster, and
* more importantly use less memory, than the original, since you do not need
* separate upscaling layers. It does the bilinear upscaling by itself.
*
* @author Gustav Larsson
*/
template <typename Dtype>
class SparseHypercolumnExtractorLayer : public Layer<Dtype> {
public:
explicit SparseHypercolumnExtractorLayer(const LayerParameter& param)
: Layer<Dtype>(param) {}
virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual void Reshape(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual inline const char* type() const { return "SparseHypercolumnExtractor"; }
virtual inline int MinBottomBlobs() const { return 2; }
virtual inline int ExactNumTopBlobs() const { return 1; }
protected:
virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);
int num_layers_;
int num_channels_; // in the entire hypercolumn
int num_locations_;
vector<Dtype> offsets_h_;
vector<Dtype> offsets_w_;
vector<Dtype> scales_;
vector<Dtype> activation_mults_;
vector<int> channel_offsets_;
};
} // namespace caffe
#endif // CAFFE_SPARSE_HYPERCOLUMN_LAYER_HPP
| 32.333333
| 82
| 0.737629
|
gustavla
|
49108ddf6d4c6c7194aeb7664774efa5285a70e3
| 2,316
|
cpp
|
C++
|
src/level/button/pressureButton.cpp
|
kirbyUK/duo
|
85155fcce81086ea39593750f042a8f518f09804
|
[
"MIT"
] | null | null | null |
src/level/button/pressureButton.cpp
|
kirbyUK/duo
|
85155fcce81086ea39593750f042a8f518f09804
|
[
"MIT"
] | null | null | null |
src/level/button/pressureButton.cpp
|
kirbyUK/duo
|
85155fcce81086ea39593750f042a8f518f09804
|
[
"MIT"
] | null | null | null |
/* Copyright (c) 2014, Alex Kerr
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
* OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "pressureButton.h"
#include <iostream>
#ifndef ASSETS
#define ASSETS "./assets"
#endif
#ifdef _WIN32
const std::string PressureButton::BUTTON_PATHS[2] =
{
(((std::string)ASSETS) + ((std::string)"\\sprites\\p_button.png")),
(((std::string)ASSETS) + ((std::string)"\\sprites\\p_button2.png"))
};
#else
const std::string PressureButton::BUTTON_PATHS[2] =
{
(((std::string)ASSETS) + ((std::string)"/sprites/p_button.png")),
(((std::string)ASSETS) + ((std::string)"/sprites/p_button2.png"))
};
#endif
sf::Image PressureButton::_images[2];
//The colour to remove in the images and replace with transparency:
const sf::Color PressureButton::COLOUR_MASK(0, 255, 0);
bool PressureButton::init()
{
for(unsigned int i = 0; i < 2; i++)
{
if(! _images[i].loadFromFile(BUTTON_PATHS[i]))
{
std::cerr << "Unable to load '" << BUTTON_PATHS[i] << "'.\n";
return false;
}
else
//If it loads fine, remove the green background:
_images[i].createMaskFromColor(COLOUR_MASK);
}
return true;
}
PressureButton::PressureButton(sf::Vector2f buttonPos, sf::Vector2f blockPos,
Block* block)
{
_texture.loadFromImage(_images[0]);
_sprite.setTexture(_texture);
_sprite.setPosition(buttonPos);
_block = block;
_blockPos[0] = _block->_shape.getPosition();
_blockPos[1] = blockPos;
}
void PressureButton::_handlePressed(bool isPlayerOnTop)
{
if(isPlayerOnTop)
{
_block->_shape.setPosition(_blockPos[1]);
_texture.update(_images[1]);
}
else
{
_block->_shape.setPosition(_blockPos[0]);
_texture.update(_images[0]);
}
}
| 28.592593
| 78
| 0.71848
|
kirbyUK
|
49198bef6748357995d737585a3a125683391cd6
| 5,281
|
cpp
|
C++
|
src/commands.cpp
|
rhoot/pantryman
|
4df649b811f8321efe49893ed69fefb03b0977d6
|
[
"0BSD"
] | 7
|
2021-01-30T01:27:24.000Z
|
2021-11-14T20:32:01.000Z
|
src/commands.cpp
|
rhoot/pantryman
|
4df649b811f8321efe49893ed69fefb03b0977d6
|
[
"0BSD"
] | null | null | null |
src/commands.cpp
|
rhoot/pantryman
|
4df649b811f8321efe49893ed69fefb03b0977d6
|
[
"0BSD"
] | null | null | null |
//
// Copyright (c) 2018 Johan Sköld
// License: https://opensource.org/licenses/ISC
//
#include "commands.hpp"
#include "config.hpp"
#include <cassert>
#include <cstring>
#include <algorithm>
namespace pm
{
HostCommand::HostCommand()
{ }
HostCommands::HostCommands()
: m_buffer{PM_CONFIG_COMMAND_BUFFER_SIZE}
{ }
bool HostCommands::nextCommand(HostCommand* cmd)
{
if (!m_buffer.beginRead())
{
return false;
}
cmd->type = m_buffer.read<HostCommand::Type>();
switch (cmd->type)
{
case HostCommand::CREATE_WINDOW:
{
cmd->createWindow.handle = m_buffer.read<WindowHandle>();
cmd->createWindow.width = m_buffer.read<uint16_t>();
cmd->createWindow.height = m_buffer.read<uint16_t>();
cmd->createWindow.state = m_buffer.read<WindowState>();
cmd->createWindow.style = m_buffer.read<WindowStyle>();
const uint16_t titleLen = m_buffer.read<uint16_t>();
m_buffer.read(cmd->createWindow.title, 1, titleLen);
cmd->createWindow.title[titleLen] = 0;
break;
}
case HostCommand::DESTROY_WINDOW:
cmd->windowHandle = m_buffer.read<WindowHandle>();
break;
case HostCommand::EXECUTE:
cmd->execute.function = m_buffer.read<ExecuteFn>();
cmd->execute.userPointer = m_buffer.read<void*>();
break;
case HostCommand::SET_CALLBACK:
cmd->callback.index = m_buffer.read<uint16_t>();
cmd->callback.function = m_buffer.read<ExecuteFn>();
cmd->callback.userPointer = m_buffer.read<void*>();
break;
case HostCommand::SET_WINDOW_SIZE:
cmd->windowSize.handle = m_buffer.read<WindowHandle>();
cmd->windowSize.width = m_buffer.read<uint16_t>();
cmd->windowSize.height = m_buffer.read<uint16_t>();
break;
case HostCommand::SET_WINDOW_STATE:
cmd->windowState.handle = m_buffer.read<WindowHandle>();
cmd->windowState.state = m_buffer.read<WindowState>();
break;
case HostCommand::SET_WINDOW_STYLE:
cmd->windowStyle.handle = m_buffer.read<WindowHandle>();
cmd->windowStyle.style = m_buffer.read<WindowStyle>();
break;
case HostCommand::STOP:
break;
default:
assert(!"invalid command type");
_Exit(1);
}
m_buffer.endRead();
return true;
}
void HostCommands::sendCreateWindow(WindowHandle handle, const WindowParams& params)
{
uint16_t titleLen = uint16_t(std::strlen(params.title));
if (titleLen > MAX_WINDOW_TITLE_LEN)
{
titleLen = MAX_WINDOW_TITLE_LEN;
}
m_buffer.beginWrite();
m_buffer.write(HostCommand::CREATE_WINDOW);
m_buffer.write(handle);
m_buffer.write(params.width);
m_buffer.write(params.height);
m_buffer.write(params.state);
m_buffer.write(params.style);
m_buffer.write(titleLen);
m_buffer.write(params.title, 1, titleLen);
m_buffer.endWrite();
}
void HostCommands::sendDestroyWindow(WindowHandle handle)
{
m_buffer.beginWrite();
m_buffer.write(HostCommand::DESTROY_WINDOW);
m_buffer.write(handle);
m_buffer.endWrite();
}
void HostCommands::sendExecute(ExecuteFn function, void* userPointer)
{
m_buffer.beginWrite();
m_buffer.write(HostCommand::EXECUTE);
m_buffer.write(function);
m_buffer.write(userPointer);
m_buffer.endWrite();
}
void HostCommands::sendSetCallback(uint16_t index, ExecuteFn function, void* userPointer)
{
m_buffer.beginWrite();
m_buffer.write(HostCommand::SET_CALLBACK);
m_buffer.write(index);
m_buffer.write(function);
m_buffer.write(userPointer);
m_buffer.endWrite();
}
void HostCommands::sendSetWindowSize(WindowHandle handle, uint16_t width, uint16_t height)
{
m_buffer.beginWrite();
m_buffer.write(HostCommand::SET_WINDOW_SIZE);
m_buffer.write(handle);
m_buffer.write(width);
m_buffer.write(height);
m_buffer.endWrite();
}
void HostCommands::sendSetWindowState(WindowHandle handle, WindowState state)
{
m_buffer.beginWrite();
m_buffer.write(HostCommand::SET_WINDOW_STATE);
m_buffer.write(handle);
m_buffer.write(state);
m_buffer.endWrite();
}
void HostCommands::sendSetWindowStyle(WindowHandle handle, WindowStyle style)
{
m_buffer.beginWrite();
m_buffer.write(HostCommand::SET_WINDOW_STYLE);
m_buffer.write(handle);
m_buffer.write(style);
m_buffer.endWrite();
}
void HostCommands::sendStop()
{
m_buffer.beginWrite();
m_buffer.write(HostCommand::STOP);
m_buffer.endWrite();
}
} // namespace pm
| 30.005682
| 94
| 0.589093
|
rhoot
|
491c7e635e7a39b17f3b6f7ca37a096e82866725
| 738
|
cpp
|
C++
|
UnLive2DAsset/Source/UnLive2DAsset/Private/UnLive2DMotion.cpp
|
Monocluar/UnLive2D
|
f4e255d3d5c12ebd56f6b248c65db7ffb7f58571
|
[
"MIT"
] | null | null | null |
UnLive2DAsset/Source/UnLive2DAsset/Private/UnLive2DMotion.cpp
|
Monocluar/UnLive2D
|
f4e255d3d5c12ebd56f6b248c65db7ffb7f58571
|
[
"MIT"
] | null | null | null |
UnLive2DAsset/Source/UnLive2DAsset/Private/UnLive2DMotion.cpp
|
Monocluar/UnLive2D
|
f4e255d3d5c12ebd56f6b248c65db7ffb7f58571
|
[
"MIT"
] | null | null | null |
#include "UnLive2DMotion.h"
#include "Misc/FileHelper.h"
#if WITH_EDITOR
bool UUnLive2DMotion::LoadLive2DMotionData(const FString& ReadMotionPath, EUnLive2DMotionGroup InMotionGroupType, int32 InMotionCount, float FadeInTime, float FadeOutTime)
{
const bool ReadSuc = FFileHelper::LoadFileToArray(MotionData.MotionByteData, *ReadMotionPath);
MotionData.FadeInTime = FadeInTime;
MotionData.FadeOutTime = FadeOutTime;
MotionData.MotionCount = InMotionCount;
MotionData.MotionGroupType = InMotionGroupType;
return ReadSuc;
}
void UUnLive2DMotion::SetLive2DMotionData(FUnLive2DMotionData& InMotionData)
{
MotionData = InMotionData;
}
#endif
const FUnLive2DMotionData* UUnLive2DMotion::GetMotionData()
{
return &MotionData;
}
| 23.806452
| 171
| 0.817073
|
Monocluar
|
491d4d9781e754486e2d6adee12d3b075a0aa0c8
| 734
|
hpp
|
C++
|
src/interfaces/json_storage.hpp
|
aahmed-2/telemetry
|
7e098e93ef0974739459d296f99ddfab54722c23
|
[
"Apache-2.0"
] | 4
|
2019-11-14T10:41:34.000Z
|
2021-12-09T23:54:52.000Z
|
src/interfaces/json_storage.hpp
|
aahmed-2/telemetry
|
7e098e93ef0974739459d296f99ddfab54722c23
|
[
"Apache-2.0"
] | 2
|
2021-10-04T20:12:53.000Z
|
2021-12-14T18:13:03.000Z
|
src/interfaces/json_storage.hpp
|
aahmed-2/telemetry
|
7e098e93ef0974739459d296f99ddfab54722c23
|
[
"Apache-2.0"
] | 2
|
2021-08-05T11:17:03.000Z
|
2021-12-13T15:22:48.000Z
|
#pragma once
#include <boost/serialization/strong_typedef.hpp>
#include <nlohmann/json.hpp>
#include <filesystem>
#include <optional>
#include <string>
namespace interfaces
{
class JsonStorage
{
public:
BOOST_STRONG_TYPEDEF(std::filesystem::path, FilePath)
BOOST_STRONG_TYPEDEF(std::filesystem::path, DirectoryPath)
virtual ~JsonStorage() = default;
virtual void store(const FilePath& subPath, const nlohmann::json& data) = 0;
virtual bool remove(const FilePath& subPath) = 0;
virtual bool exist(const FilePath& path) const = 0;
virtual std::optional<nlohmann::json>
load(const FilePath& subPath) const = 0;
virtual std::vector<FilePath> list() const = 0;
};
} // namespace interfaces
| 24.466667
| 80
| 0.719346
|
aahmed-2
|
491db81b8315955dbd6a8777eb20a33854432efc
| 107,574
|
cc
|
C++
|
sandboxed_api/sandbox2/syscall_defs.cc
|
oshogbo/sandboxed-api
|
8e82b900f4d873219b3abfa2fd06ecbd416edefd
|
[
"Apache-2.0"
] | 1,562
|
2019-03-07T10:02:53.000Z
|
2022-03-31T17:43:05.000Z
|
sandboxed_api/sandbox2/syscall_defs.cc
|
oshogbo/sandboxed-api
|
8e82b900f4d873219b3abfa2fd06ecbd416edefd
|
[
"Apache-2.0"
] | 70
|
2019-03-19T01:02:49.000Z
|
2022-03-30T17:26:53.000Z
|
sandboxed_api/sandbox2/syscall_defs.cc
|
oshogbo/sandboxed-api
|
8e82b900f4d873219b3abfa2fd06ecbd416edefd
|
[
"Apache-2.0"
] | 181
|
2019-03-18T19:41:30.000Z
|
2022-03-29T13:08:26.000Z
|
#include "sandboxed_api/sandbox2/syscall_defs.h"
#include <cstdint>
#include <type_traits>
#include <glog/logging.h>
#include "absl/algorithm/container.h"
#include "absl/strings/escaping.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "sandboxed_api/config.h"
#include "sandboxed_api/sandbox2/util.h"
namespace sandbox2 {
// Type of a given syscall argument. Used with argument conversion routines.
enum ArgType {
kGen = 1,
kInt,
kPath,
kHex,
kOct,
kSocketCall,
kSocketCallPtr,
kSignal,
kString,
kAddressFamily,
kSockaddr,
kSockmsghdr,
kCloneFlag,
};
// Single syscall definition
struct SyscallTable::Entry {
// Returns the number of arguments which given syscall takes.
int GetNumArgs() const {
if (num_args < 0 || num_args > syscalls::kMaxArgs) {
return syscalls::kMaxArgs;
}
return num_args;
}
static std::string GetArgumentDescription(uint64_t value, ArgType type,
pid_t pid);
std::vector<std::string> GetArgumentsDescription(
const uint64_t values[syscalls::kMaxArgs], pid_t pid) const;
static constexpr bool BySyscallNr(const SyscallTable::Entry& a,
const SyscallTable::Entry& b) {
return a.nr < b.nr;
}
int nr;
absl::string_view name;
int num_args;
std::array<ArgType, syscalls::kMaxArgs> arg_types;
};
std::string SyscallTable::Entry::GetArgumentDescription(uint64_t value,
ArgType type,
pid_t pid) {
std::string ret = absl::StrFormat("%#x", value);
switch (type) {
case kOct:
absl::StrAppendFormat(&ret, " [\\0%o]", value);
break;
case kPath:
if (auto path_or = util::ReadCPathFromPid(pid, value); path_or.ok()) {
absl::StrAppendFormat(&ret, " ['%s']",
absl::CHexEscape(path_or.value()));
} else {
absl::StrAppend(&ret, " [unreadable path]");
}
break;
case kInt:
absl::StrAppendFormat(&ret, " [%d]", value);
break;
default:
break;
}
return ret;
}
absl::string_view SyscallTable::GetName(int syscall) const {
auto it = absl::c_lower_bound(
data_, syscall, [](const SyscallTable::Entry& entry, int syscall) {
return entry.nr < syscall;
});
if (it == data_.end() || it->nr != syscall) {
return "";
}
return it->name;
}
namespace {
template <typename... ArgTypes>
constexpr SyscallTable::Entry MakeEntry(int nr, absl::string_view name,
ArgTypes... arg_types) {
static_assert(sizeof...(arg_types) <= syscalls::kMaxArgs,
"Too many arguments for syscall");
return {nr, name, sizeof...(arg_types), {arg_types...}};
}
struct UnknownArguments {};
constexpr SyscallTable::Entry MakeEntry(int nr, absl::string_view name,
UnknownArguments) {
return {nr, name, -1, {kGen, kGen, kGen, kGen, kGen, kGen}};
}
} // namespace
std::vector<std::string> SyscallTable::GetArgumentsDescription(
int syscall, const uint64_t values[], pid_t pid) const {
static SyscallTable::Entry kInvalidEntry =
MakeEntry(-1, "", UnknownArguments());
auto it = absl::c_lower_bound(
data_, syscall, [](const SyscallTable::Entry& entry, int syscall) {
return entry.nr < syscall;
});
const auto& entry =
it != data_.end() && it->nr == syscall ? *it : kInvalidEntry;
int num_args = entry.GetNumArgs();
std::vector<std::string> rv;
rv.reserve(num_args);
for (int i = 0; i < num_args; ++i) {
rv.push_back(SyscallTable::Entry::GetArgumentDescription(
values[i], entry.arg_types[i], pid));
}
return rv;
}
namespace {
// TODO(C++20) Use std::is_sorted
template <typename Container, typename Compare>
constexpr bool IsSorted(const Container& container, Compare comp) {
auto it = std::begin(container);
if (it == std::end(container)) {
return true;
}
auto last = it;
for (++it; it != std::end(container); ++it) {
if (!comp(*last, *it)) {
return false;
}
last = it;
}
return true;
}
// Syscall description table for Linux x86_64
constexpr std::array kSyscallDataX8664 = {
// clang-format off
MakeEntry(0, "read", kInt, kHex, kInt),
MakeEntry(1, "write", kInt, kHex, kInt),
MakeEntry(2, "open", kPath, kHex, kOct),
MakeEntry(3, "close", kInt),
MakeEntry(4, "stat", kPath, kGen),
MakeEntry(5, "fstat", kInt, kHex),
MakeEntry(6, "lstat", kPath, kGen),
MakeEntry(7, "poll", kGen, kInt, kInt),
MakeEntry(8, "lseek", kInt, kInt, kInt),
MakeEntry(9, "mmap", kHex, kInt, kHex, kHex, kInt, kInt),
MakeEntry(10, "mprotect", kHex, kInt, kHex),
MakeEntry(11, "munmap", kHex, kInt),
MakeEntry(12, "brk", kInt),
MakeEntry(13, "rt_sigaction", kSignal, kHex, kHex, kInt),
MakeEntry(14, "rt_sigprocmask", kInt, kHex, kHex, kInt),
MakeEntry(15, "rt_sigreturn"),
MakeEntry(16, "ioctl", kInt, kInt, kHex),
MakeEntry(17, "pread64", kInt, kHex, kInt, kInt),
MakeEntry(18, "pwrite64", kInt, kHex, kInt, kInt),
MakeEntry(19, "readv", kInt, kHex, kInt),
MakeEntry(20, "writev", kInt, kHex, kInt),
MakeEntry(21, "access", kPath, kOct),
MakeEntry(22, "pipe", kHex),
MakeEntry(23, "select", kInt, kHex, kHex, kHex, kHex),
MakeEntry(24, "sched_yield"),
MakeEntry(25, "mremap", kHex, kInt, kInt, kInt, kHex),
MakeEntry(26, "msync", kHex, kInt, kInt),
MakeEntry(27, "mincore", kHex, kInt, kHex),
MakeEntry(28, "madvise", kHex, kInt, kInt),
MakeEntry(29, "shmget", kInt, kInt, kHex),
MakeEntry(30, "shmat", kInt, kHex, kHex),
MakeEntry(31, "shmctl", kInt, kInt, kHex),
MakeEntry(32, "dup", kInt),
MakeEntry(33, "dup2", kInt, kInt),
MakeEntry(34, "pause"),
MakeEntry(35, "nanosleep", kHex, kHex),
MakeEntry(36, "getitimer", kInt, kHex),
MakeEntry(37, "alarm", kInt),
MakeEntry(38, "setitimer", kInt, kHex, kHex),
MakeEntry(39, "getpid"),
MakeEntry(40, "sendfile", kInt, kInt, kHex, kInt),
MakeEntry(41, "socket", kAddressFamily, kInt, kInt),
MakeEntry(42, "connect", kInt, kSockaddr, kInt),
MakeEntry(43, "accept", kInt, kSockaddr, kHex),
MakeEntry(44, "sendto", kInt, kHex, kInt, kHex, kSockaddr, kInt),
MakeEntry(45, "recvfrom", kInt, kHex, kInt, kHex, kSockaddr, kHex),
MakeEntry(46, "sendmsg", kInt, kSockmsghdr, kHex),
MakeEntry(47, "recvmsg", kInt, kHex, kInt),
MakeEntry(48, "shutdown", kInt, kInt),
MakeEntry(49, "bind", kInt, kSockaddr, kInt),
MakeEntry(50, "listen", kInt, kInt),
MakeEntry(51, "getsockname", kInt, kSockaddr, kHex),
MakeEntry(52, "getpeername", kInt, kSockaddr, kHex),
MakeEntry(53, "socketpair", kAddressFamily, kInt, kInt, kHex),
MakeEntry(54, "setsockopt", kInt, kInt, kInt, kHex, kHex),
MakeEntry(55, "getsockopt", kInt, kInt, kInt, kHex, kInt),
MakeEntry(56, "clone", kCloneFlag, kHex, kHex, kHex, kHex),
MakeEntry(57, "fork"),
MakeEntry(58, "vfork"),
MakeEntry(59, "execve", kPath, kHex, kHex),
MakeEntry(60, "exit", kInt),
MakeEntry(61, "wait4", kInt, kHex, kHex, kHex),
MakeEntry(62, "kill", kInt, kSignal),
MakeEntry(63, "uname", kInt),
MakeEntry(64, "semget", kInt, kInt, kHex),
MakeEntry(65, "semop", kInt, kHex, kInt),
MakeEntry(66, "semctl", kInt, kInt, kInt, kHex),
MakeEntry(67, "shmdt", kHex),
MakeEntry(68, "msgget", kInt, kHex),
MakeEntry(69, "msgsnd", kInt, kHex, kInt, kHex),
MakeEntry(70, "msgrcv", kInt, kHex, kInt, kInt, kHex),
MakeEntry(71, "msgctl", kInt, kInt, kHex),
MakeEntry(72, "fcntl", kInt, kInt, kHex),
MakeEntry(73, "flock", kInt, kInt),
MakeEntry(74, "fsync", kInt),
MakeEntry(75, "fdatasync", kInt),
MakeEntry(76, "truncate", kPath, kInt),
MakeEntry(77, "ftruncate", kInt, kInt),
MakeEntry(78, "getdents", kInt, kHex, kInt),
MakeEntry(79, "getcwd", kHex, kInt),
MakeEntry(80, "chdir", kPath),
MakeEntry(81, "fchdir", kInt),
MakeEntry(82, "rename", kPath, kPath),
MakeEntry(83, "mkdir", kPath, kOct),
MakeEntry(84, "rmdir", kPath),
MakeEntry(85, "creat", kPath, kOct),
MakeEntry(86, "link", kPath, kPath),
MakeEntry(87, "unlink", kPath),
MakeEntry(88, "symlink", kPath, kPath),
MakeEntry(89, "readlink", kPath, kHex, kInt),
MakeEntry(90, "chmod", kPath, kOct),
MakeEntry(91, "fchmod", kInt, kOct),
MakeEntry(92, "chown", kPath, kInt, kInt),
MakeEntry(93, "fchown", kInt, kInt, kInt),
MakeEntry(94, "lchown", kPath, kInt, kInt),
MakeEntry(95, "umask", kHex),
MakeEntry(96, "gettimeofday", kHex, kHex),
MakeEntry(97, "getrlimit", kInt, kHex),
MakeEntry(98, "getrusage", kInt, kHex),
MakeEntry(99, "sysinfo", kHex),
MakeEntry(100, "times", kHex),
MakeEntry(101, "ptrace", kInt, kInt, kHex, kHex),
MakeEntry(102, "getuid"),
MakeEntry(103, "syslog", kInt, kHex, kInt),
MakeEntry(104, "getgid"),
MakeEntry(105, "setuid", kInt),
MakeEntry(106, "setgid", kInt),
MakeEntry(107, "geteuid"),
MakeEntry(108, "getegid"),
MakeEntry(109, "setpgid", kInt, kInt),
MakeEntry(110, "getppid"),
MakeEntry(111, "getpgrp"),
MakeEntry(112, "setsid"),
MakeEntry(113, "setreuid", kInt, kInt),
MakeEntry(114, "setregid", kInt, kInt),
MakeEntry(115, "getgroups", kInt, kHex),
MakeEntry(116, "setgroups", kInt, kHex),
MakeEntry(117, "setresuid", kInt, kInt, kInt),
MakeEntry(118, "getresuid", kHex, kHex, kHex),
MakeEntry(119, "setresgid", kInt, kInt, kInt),
MakeEntry(120, "getresgid", kHex, kHex, kHex),
MakeEntry(121, "getpgid", kInt),
MakeEntry(122, "setfsuid", kInt),
MakeEntry(123, "setfsgid", kInt),
MakeEntry(124, "getsid", kInt),
MakeEntry(125, "capget", kHex, kHex),
MakeEntry(126, "capset", kHex, kHex),
MakeEntry(127, "rt_sigpending", kHex, kInt),
MakeEntry(128, "rt_sigtimedwait", kHex, kHex, kHex, kInt),
MakeEntry(129, "rt_sigqueueinfo", kInt, kSignal, kHex),
MakeEntry(130, "rt_sigsuspend", kHex, kInt),
MakeEntry(131, "sigaltstack", kHex, kHex),
MakeEntry(132, "utime", kPath, kHex),
MakeEntry(133, "mknod", kPath, kOct, kHex),
MakeEntry(134, "uselib", kPath),
MakeEntry(135, "personality", kHex),
MakeEntry(136, "ustat", kHex, kHex),
MakeEntry(137, "statfs", kPath, kHex),
MakeEntry(138, "fstatfs", kInt, kHex),
MakeEntry(139, "sysfs", kInt, kInt, kInt),
MakeEntry(140, "getpriority", kInt, kInt),
MakeEntry(141, "setpriority", kInt, kInt, kInt),
MakeEntry(142, "sched_setparam", kInt, kHex),
MakeEntry(143, "sched_getparam", kInt, kHex),
MakeEntry(144, "sched_setscheduler", kInt, kInt, kHex),
MakeEntry(145, "sched_getscheduler", kInt),
MakeEntry(146, "sched_get_priority_max", kInt),
MakeEntry(147, "sched_get_priority_min", kInt),
MakeEntry(148, "sched_rr_get_interval", kInt, kHex),
MakeEntry(149, "mlock", kInt, kInt),
MakeEntry(150, "munlock", kInt, kInt),
MakeEntry(151, "mlockall", kHex),
MakeEntry(152, "munlockall"),
MakeEntry(153, "vhangup"),
MakeEntry(154, "modify_ldt", kInt, kHex, kInt),
MakeEntry(155, "pivot_root", kPath, kPath),
MakeEntry(156, "_sysctl", kHex),
MakeEntry(157, "prctl", kInt, kHex, kHex, kHex, kHex),
MakeEntry(158, "arch_prctl", kInt, kHex),
MakeEntry(159, "adjtimex", kHex),
MakeEntry(160, "setrlimit", kInt, kHex),
MakeEntry(161, "chroot", kPath),
MakeEntry(162, "sync"),
MakeEntry(163, "acct", kPath),
MakeEntry(164, "settimeofday", kHex, kHex),
MakeEntry(165, "mount", kPath, kPath, kString, kHex, kGen),
MakeEntry(166, "umount2", kPath, kHex),
MakeEntry(167, "swapon", kPath, kHex),
MakeEntry(168, "swapoff", kPath),
MakeEntry(169, "reboot", kInt, kHex, kHex, kGen),
MakeEntry(170, "sethostname", kString, kInt),
MakeEntry(171, "setdomainname", kString, kInt),
MakeEntry(172, "iopl", kInt),
MakeEntry(173, "ioperm", kInt, kInt, kInt),
MakeEntry(174, "create_module", kString, kInt),
MakeEntry(175, "init_module", kGen, kInt, kString),
MakeEntry(176, "delete_module", kString, kHex),
MakeEntry(177, "get_kernel_syms", kHex),
MakeEntry(178, "query_module", kString, kInt, kGen, kInt, kGen),
MakeEntry(179, "quotactl", kInt, kPath, kInt, kGen),
MakeEntry(180, "nfsservctl", kInt, kGen, kGen),
MakeEntry(181, "getpmsg", UnknownArguments()),
MakeEntry(182, "putpmsg", UnknownArguments()),
MakeEntry(183, "afs_syscall", UnknownArguments()),
MakeEntry(184, "tuxcall", UnknownArguments()),
MakeEntry(185, "security", UnknownArguments()),
MakeEntry(186, "gettid"),
MakeEntry(187, "readahead", kInt, kInt, kInt),
MakeEntry(188, "setxattr", kPath, kString, kGen, kInt, kHex),
MakeEntry(189, "lsetxattr", kPath, kString, kGen, kInt, kHex),
MakeEntry(190, "fsetxattr", kInt, kString, kGen, kInt, kHex),
MakeEntry(191, "getxattr", kPath, kString, kGen, kInt),
MakeEntry(192, "lgetxattr", kPath, kString, kGen, kInt),
MakeEntry(193, "fgetxattr", kInt, kString, kGen, kInt),
MakeEntry(194, "listxattr", kPath, kGen, kInt),
MakeEntry(195, "llistxattr", kPath, kGen, kInt),
MakeEntry(196, "flistxattr", kInt, kGen, kInt),
MakeEntry(197, "removexattr", kPath, kString),
MakeEntry(198, "lremovexattr", kPath, kString),
MakeEntry(199, "fremovexattr", kInt, kString),
MakeEntry(200, "tkill", kInt, kSignal),
MakeEntry(201, "time", kHex),
MakeEntry(202, "futex", kGen, kInt, kInt, kGen, kGen, kInt),
MakeEntry(203, "sched_setaffinity", kInt, kInt, kHex),
MakeEntry(204, "sched_getaffinity", kInt, kInt, kHex),
MakeEntry(205, "set_thread_area", kHex),
MakeEntry(206, "io_setup", kInt, kHex),
MakeEntry(207, "io_destroy", kInt),
MakeEntry(208, "io_getevents", kInt, kInt, kInt, kHex, kHex),
MakeEntry(209, "io_submit", kInt, kInt, kHex),
MakeEntry(210, "io_cancel", kInt, kHex, kHex),
MakeEntry(211, "get_thread_area", kHex),
MakeEntry(212, "lookup_dcookie", kInt, kString, kInt),
MakeEntry(213, "epoll_create", kInt),
MakeEntry(214, "epoll_ctl_old", UnknownArguments()),
MakeEntry(215, "epoll_wait_old", UnknownArguments()),
MakeEntry(216, "remap_file_pages", kGen, kInt, kInt, kInt, kHex),
MakeEntry(217, "getdents64", kInt, kHex, kInt),
MakeEntry(218, "set_tid_address", kHex),
MakeEntry(219, "restart_syscall"),
MakeEntry(220, "semtimedop", kInt, kHex, kInt, kHex),
MakeEntry(221, "fadvise64", kInt, kInt, kInt, kInt),
MakeEntry(222, "timer_create", kInt, kHex, kHex),
MakeEntry(223, "timer_settime", kInt, kHex, kHex, kHex),
MakeEntry(224, "timer_gettime", kInt, kHex),
MakeEntry(225, "timer_getoverrun", kInt),
MakeEntry(226, "timer_delete", kInt),
MakeEntry(227, "clock_settime", kInt, kHex),
MakeEntry(228, "clock_gettime", kInt, kHex),
MakeEntry(229, "clock_getres", kInt, kHex),
MakeEntry(230, "clock_nanosleep", kInt, kHex, kHex, kHex),
MakeEntry(231, "exit_group", kInt),
MakeEntry(232, "epoll_wait", kInt, kHex, kInt, kInt),
MakeEntry(233, "epoll_ctl", kInt, kInt, kInt, kHex),
MakeEntry(234, "tgkill", kInt, kInt, kSignal),
MakeEntry(235, "utimes", kPath, kHex),
MakeEntry(236, "vserver", UnknownArguments()),
MakeEntry(237, "mbind", kGen, kInt, kInt, kHex, kInt, kHex),
MakeEntry(238, "set_mempolicy", kInt, kHex, kInt),
MakeEntry(239, "get_mempolicy", kInt, kHex, kInt, kInt, kHex),
MakeEntry(240, "mq_open", kString, kHex, kOct, kHex),
MakeEntry(241, "mq_unlink", kString),
MakeEntry(242, "mq_timedsend", kHex, kHex, kInt, kInt, kHex),
MakeEntry(243, "mq_timedreceive", kHex, kHex, kInt, kHex, kHex),
MakeEntry(244, "mq_notify", kHex, kHex),
MakeEntry(245, "mq_getsetattr", kHex, kHex, kHex),
MakeEntry(246, "kexec_load", kHex, kInt, kHex, kHex),
MakeEntry(247, "waitid", kInt, kInt, kHex, kInt, kHex),
MakeEntry(248, "add_key", kString, kString, kGen, kInt, kInt),
MakeEntry(249, "request_key", kString, kString, kHex, kInt),
MakeEntry(250, "keyctl", kInt, kInt, kInt, kInt, kInt),
MakeEntry(251, "ioprio_set", kInt, kInt, kInt),
MakeEntry(252, "ioprio_get", kInt, kInt),
MakeEntry(253, "inotify_init"),
MakeEntry(254, "inotify_add_watch", kInt, kPath, kHex),
MakeEntry(255, "inotify_rm_watch", kInt, kInt),
MakeEntry(256, "migrate_pages", kInt, kInt, kHex, kHex),
MakeEntry(257, "openat", kInt, kPath, kHex, kOct),
MakeEntry(258, "mkdirat", kInt, kPath, kOct),
MakeEntry(259, "mknodat", kInt, kPath, kOct, kHex),
MakeEntry(260, "fchownat", kInt, kPath, kInt, kInt, kHex),
MakeEntry(261, "futimesat", kInt, kPath, kHex),
MakeEntry(262, "newfstatat", kInt, kPath, kHex, kHex),
MakeEntry(263, "unlinkat", kInt, kPath, kHex),
MakeEntry(264, "renameat", kInt, kPath, kInt, kPath),
MakeEntry(265, "linkat", kInt, kPath, kInt, kPath, kHex),
MakeEntry(266, "symlinkat", kPath, kInt, kPath),
MakeEntry(267, "readlinkat", kInt, kPath, kHex, kInt),
MakeEntry(268, "fchmodat", kInt, kPath, kOct),
MakeEntry(269, "faccessat", kInt, kPath, kInt, kHex),
MakeEntry(270, "pselect6", kInt, kHex, kHex, kHex, kHex),
MakeEntry(271, "ppoll", kHex, kInt, kHex, kHex, kInt),
MakeEntry(272, "unshare", kHex),
MakeEntry(273, "set_robust_list", kHex, kInt),
MakeEntry(274, "get_robust_list", kInt, kHex, kHex),
MakeEntry(275, "splice", kInt, kHex, kInt, kHex, kInt, kHex),
MakeEntry(276, "tee", kInt, kInt, kInt, kHex),
MakeEntry(277, "sync_file_range", kInt, kInt, kInt, kHex),
MakeEntry(278, "vmsplice", kInt, kHex, kInt, kInt),
MakeEntry(279, "move_pages", kInt, kInt, kHex, kHex, kHex, kHex),
MakeEntry(280, "utimensat", kInt, kPath, kHex, kHex),
MakeEntry(281, "epoll_pwait", kInt, kHex, kInt, kInt, kHex, kInt),
MakeEntry(282, "signalfd", kInt, kHex, kHex),
MakeEntry(283, "timerfd_create", kInt, kHex),
MakeEntry(284, "eventfd", kInt),
MakeEntry(285, "fallocate", kInt, kOct, kInt, kInt),
MakeEntry(286, "timerfd_settime", kInt, kHex, kHex, kHex),
MakeEntry(287, "timerfd_gettime", kInt, kHex),
MakeEntry(288, "accept4", kInt, kHex, kHex, kInt),
MakeEntry(289, "signalfd4", kInt, kHex, kHex, kHex),
MakeEntry(290, "eventfd2", kInt, kHex),
MakeEntry(291, "epoll_create1", kHex),
MakeEntry(292, "dup3", kInt, kInt, kHex),
MakeEntry(293, "pipe2", kHex, kHex),
MakeEntry(294, "inotify_init1", kHex),
MakeEntry(295, "preadv", kInt, kHex, kInt, kInt, kInt),
MakeEntry(296, "pwritev", kInt, kHex, kInt, kInt, kInt),
MakeEntry(297, "rt_tgsigqueueinfo", kInt, kInt, kInt, kHex),
MakeEntry(298, "perf_event_open", kHex, kInt, kInt, kInt, kHex),
MakeEntry(299, "recvmmsg", kInt, kHex, kInt, kHex, kHex),
MakeEntry(300, "fanotify_init", kHex, kHex),
MakeEntry(301, "fanotify_mark", kInt, kHex, kHex, kInt, kPath),
MakeEntry(302, "prlimit64", kInt, kInt, kHex, kHex),
MakeEntry(303, "name_to_handle_at", kInt, kPath, kHex, kHex, kHex),
MakeEntry(304, "open_by_handle_at", kInt, kHex, kHex),
MakeEntry(305, "clock_adjtime", kInt, kHex),
MakeEntry(306, "syncfs", kInt),
MakeEntry(307, "sendmmsg", kInt, kHex, kInt, kHex),
MakeEntry(308, "setns", kInt, kHex),
MakeEntry(309, "getcpu", kHex, kHex, kHex),
MakeEntry(310, "process_vm_readv", kInt, kHex, kInt, kHex, kInt,
kInt),
MakeEntry(311, "process_vm_writev", kInt, kHex, kInt, kHex, kInt,
kInt),
MakeEntry(312, "kcmp", kInt, kInt, kInt, kInt, kInt),
MakeEntry(313, "finit_module", kInt, kString, kHex),
MakeEntry(314, "sched_setattr", kInt, kHex, kHex),
MakeEntry(315, "sched_getattr", kInt, kHex, kInt, kHex),
MakeEntry(316, "renameat2", kInt, kPath, kInt, kPath, kHex),
MakeEntry(317, "seccomp", kInt, kHex, kHex),
MakeEntry(318, "getrandom", kGen, kInt, kHex),
MakeEntry(319, "memfd_create", kString, kHex),
MakeEntry(320, "kexec_file_load", kInt, kInt, kInt, kString, kHex),
MakeEntry(321, "bpf", kInt, kHex, kInt),
MakeEntry(322, "execveat", kInt, kPath, kHex, kHex, kHex),
MakeEntry(323, "userfaultfd", kHex),
MakeEntry(324, "membarrier", kInt, kHex),
MakeEntry(325, "mlock2", kHex, kInt, kHex),
MakeEntry(326, "copy_file_range", kInt, kHex, kInt, kHex, kInt,
kHex),
MakeEntry(327, "preadv2", kInt, kHex, kInt, kInt, kInt, kHex),
MakeEntry(328, "pwritev2", kInt, kHex, kInt, kInt, kInt, kHex),
MakeEntry(329, "pkey_mprotect", kInt, kInt, kHex, kInt),
MakeEntry(330, "pkey_alloc", kInt, kInt),
MakeEntry(331, "pkey_free", kInt),
MakeEntry(332, "statx", kInt, kPath, kHex, kHex, kHex),
MakeEntry(333, "io_pgetevents", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(334, "rseq", kHex, kInt, kHex, kHex),
// clang-format on
};
static_assert(IsSorted(kSyscallDataX8664, SyscallTable::Entry::BySyscallNr),
"Syscalls should be sorted");
constexpr std::array kSyscallDataX8632 = {
// clang-format off
MakeEntry(0, "restart_syscall", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(1, "exit", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(2, "fork", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(3, "read", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(4, "write", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(5, "open", kPath, kHex, kOct, kHex, kHex, kHex),
MakeEntry(6, "close", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(7, "waitpid", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(8, "creat", kPath, kHex, kHex, kHex, kHex, kHex),
MakeEntry(9, "link", kPath, kPath, kHex, kHex, kHex, kHex),
MakeEntry(10, "unlink", kPath, kHex, kHex, kHex, kHex, kHex),
MakeEntry(11, "execve", kPath, kHex, kHex, kHex, kHex, kHex),
MakeEntry(12, "chdir", kPath, kHex, kHex, kHex, kHex, kHex),
MakeEntry(13, "time", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(14, "mknod", kPath, kOct, kHex, kHex, kHex, kHex),
MakeEntry(15, "chmod", kPath, kOct, kHex, kHex, kHex, kHex),
MakeEntry(16, "lchown", kPath, kInt, kInt, kHex, kHex, kHex),
MakeEntry(17, "break", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(18, "oldstat", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(19, "lseek", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(20, "getpid", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(21, "mount", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(22, "umount", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(23, "setuid", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(24, "getuid", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(25, "stime", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(26, "ptrace", kHex, kHex, kHex, kHex),
MakeEntry(27, "alarm", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(28, "oldfstat", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(29, "pause", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(30, "utime", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(31, "stty", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(32, "gtty", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(33, "access", kPath, kHex, kHex, kHex, kHex, kHex),
MakeEntry(34, "nice", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(35, "ftime", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(36, "sync", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(37, "kill", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(38, "rename", kPath, kPath, kHex, kHex, kHex, kHex),
MakeEntry(39, "mkdir", kPath, kHex, kHex, kHex, kHex, kHex),
MakeEntry(40, "rmdir", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(41, "dup", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(42, "pipe", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(43, "times", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(44, "prof", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(45, "brk", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(46, "setgid", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(47, "getgid", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(48, "signal", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(49, "geteuid", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(50, "getegid", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(51, "acct", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(52, "umount2", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(53, "lock", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(54, "ioctl", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(55, "fcntl", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(56, "mpx", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(57, "setpgid", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(58, "ulimit", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(59, "oldolduname", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(60, "umask", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(61, "chroot", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(62, "ustat", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(63, "dup2", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(64, "getppid", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(65, "getpgrp", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(66, "setsid", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(67, "sigaction", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(68, "sgetmask", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(69, "ssetmask", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(70, "setreuid", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(71, "setregid", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(72, "sigsuspend", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(73, "sigpending", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(74, "sethostname", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(75, "setrlimit", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(76, "getrlimit", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(77, "getrusage", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(78, "gettimeofday", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(79, "settimeofday", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(80, "getgroups", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(81, "setgroups", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(82, "select", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(83, "symlink", kPath, kPath, kHex, kHex, kHex, kHex),
MakeEntry(84, "oldlstat", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(85, "readlink", kPath, kHex, kInt, kHex, kHex, kHex),
MakeEntry(86, "uselib", kPath, kHex, kHex, kHex, kHex, kHex),
MakeEntry(87, "swapon", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(88, "reboot", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(89, "readdir", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(90, "mmap", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(91, "munmap", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(92, "truncate", kPath, kHex, kHex, kHex, kHex, kHex),
MakeEntry(93, "ftruncate", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(94, "fchmod", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(95, "fchown", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(96, "getpriority", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(97, "setpriority", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(98, "profil", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(99, "statfs", kPath, kHex, kHex, kHex, kHex, kHex),
MakeEntry(100, "fstatfs", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(101, "ioperm", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(102, "socketcall", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(103, "syslog", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(104, "setitimer", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(105, "getitimer", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(106, "stat", kPath, kHex, kHex, kHex, kHex, kHex),
MakeEntry(107, "lstat", kPath, kHex, kHex, kHex, kHex, kHex),
MakeEntry(108, "fstat", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(109, "olduname", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(110, "iopl", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(111, "vhangup", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(112, "idle", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(113, "vm86old", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(114, "wait4", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(115, "swapoff", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(116, "sysinfo", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(117, "ipc", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(118, "fsync", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(119, "sigreturn", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(120, "clone", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(121, "setdomainname", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(122, "uname", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(123, "modify_ldt", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(124, "adjtimex", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(125, "mprotect", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(126, "sigprocmask", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(127, "create_module", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(128, "init_module", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(129, "delete_module", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(130, "get_kernel_syms", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(131, "quotactl", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(132, "getpgid", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(133, "fchdir", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(134, "bdflush", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(135, "sysfs", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(136, "personality", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(137, "afs_syscall", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(138, "setfsuid", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(139, "setfsgid", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(140, "_llseek", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(141, "getdents", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(142, "_newselect", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(143, "flock", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(144, "msync", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(145, "readv", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(146, "writev", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(147, "getsid", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(148, "fdatasync", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(149, "_sysctl", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(150, "mlock", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(151, "munlock", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(152, "mlockall", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(153, "munlockall", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(154, "sched_setparam", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(155, "sched_getparam", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(156, "sched_setscheduler", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(157, "sched_getscheduler", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(158, "sched_yield", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(159, "sched_get_priority_max", kHex, kHex, kHex, kHex, kHex,
kHex),
MakeEntry(160, "sched_get_priority_min", kHex, kHex, kHex, kHex, kHex,
kHex),
MakeEntry(161, "sched_rr_get_interval", kHex, kHex, kHex, kHex, kHex,
kHex),
MakeEntry(162, "nanosleep", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(163, "mremap", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(164, "setresuid", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(165, "getresuid", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(166, "vm86", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(167, "query_module", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(168, "poll", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(169, "nfsservctl", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(170, "setresgid", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(171, "getresgid", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(172, "prctl", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(173, "rt_sigreturn", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(174, "rt_sigaction", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(175, "rt_sigprocmask", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(176, "rt_sigpending", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(177, "rt_sigtimedwait", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(178, "rt_sigqueueinfo", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(179, "rt_sigsuspend", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(180, "pread64", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(181, "pwrite64", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(182, "chown", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(183, "getcwd", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(184, "capget", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(185, "capset", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(186, "sigaltstack", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(187, "sendfile", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(188, "getpmsg", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(189, "putpmsg", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(190, "vfork", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(191, "ugetrlimit", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(192, "mmap2", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(193, "truncate64", kPath, kHex, kHex, kHex, kHex, kHex),
MakeEntry(194, "ftruncate64", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(195, "stat64", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(196, "lstat64", kPath, kHex, kHex, kHex, kHex, kHex),
MakeEntry(197, "fstat64", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(198, "lchown32", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(199, "getuid32", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(200, "getgid32", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(201, "geteuid32", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(202, "getegid32", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(203, "setreuid32", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(204, "setregid32", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(205, "getgroups32", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(206, "setgroups32", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(207, "fchown32", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(208, "setresuid32", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(209, "getresuid32", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(210, "setresgid32", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(211, "getresgid32", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(212, "chown32", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(213, "setuid32", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(214, "setgid32", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(215, "setfsuid32", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(216, "setfsgid32", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(217, "pivot_root", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(218, "mincore", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(219, "madvise", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(220, "getdents64", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(221, "fcntl64", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(222, "unused1-222", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(223, "unused2-223", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(224, "gettid", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(225, "readahead", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(226, "setxattr", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(227, "lsetxattr", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(228, "fsetxattr", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(229, "getxattr", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(230, "lgetxattr", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(231, "fgetxattr", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(232, "listxattr", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(233, "llistxattr", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(234, "flistxattr", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(235, "removexattr", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(236, "lremovexattr", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(237, "fremovexattr", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(238, "tkill", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(239, "sendfile64", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(240, "futex", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(241, "sched_setaffinity", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(242, "sched_getaffinity", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(243, "set_thread_area", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(244, "get_thread_area", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(245, "io_setup", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(246, "io_destroy", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(247, "io_getevents", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(248, "io_submit", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(249, "io_cancel", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(250, "fadvise64", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(251, "251-old_sys_set_zone_reclaim", kHex, kHex, kHex, kHex, kHex,
kHex),
MakeEntry(252, "exit_group", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(253, "lookup_dcookie", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(254, "epoll_create", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(255, "epoll_ctl", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(256, "epoll_wait", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(257, "remap_file_pages", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(258, "set_tid_address", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(259, "timer_create", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(260, "timer_settime", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(261, "timer_gettime", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(262, "timer_getoverrun", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(263, "timer_delete", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(264, "clock_settime", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(265, "clock_gettime", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(266, "clock_getres", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(267, "clock_nanosleep", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(268, "statfs64", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(269, "fstatfs64", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(270, "tgkill", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(271, "utimes", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(272, "fadvise64_64", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(273, "vserver", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(274, "mbind", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(275, "get_mempolicy", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(276, "set_mempolicy", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(277, "mq_open", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(278, "mq_unlink", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(279, "mq_timedsend", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(280, "mq_timedreceive", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(281, "mq_notify", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(282, "mq_getsetattr", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(283, "kexec_load", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(284, "waitid", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(285, "285-old_sys_setaltroot", kHex, kHex, kHex, kHex, kHex,
kHex),
MakeEntry(286, "add_key", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(287, "request_key", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(288, "keyctl", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(289, "ioprio_set", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(290, "ioprio_get", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(291, "inotify_init", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(292, "inotify_add_watch", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(293, "inotify_rm_watch", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(294, "migrate_pages", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(295, "openat", kHex, kPath, kOct, kHex, kHex, kHex),
MakeEntry(296, "mkdirat", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(297, "mknodat", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(298, "fchownat", kHex, kPath, kHex, kHex, kHex, kHex),
MakeEntry(299, "futimesat", kHex, kPath, kHex, kHex, kHex, kHex),
MakeEntry(300, "fstatat64", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(301, "unlinkat", kHex, kPath, kHex, kHex, kHex, kHex),
MakeEntry(302, "renameat", kHex, kPath, kHex, kPath, kHex, kHex),
MakeEntry(303, "linkat", kHex, kPath, kHex, kPath, kHex, kHex),
MakeEntry(304, "symlinkat", kPath, kHex, kPath, kHex, kHex, kHex),
MakeEntry(305, "readlinkat", kHex, kPath, kHex, kHex, kHex, kHex),
MakeEntry(306, "fchmodat", kHex, kPath, kHex, kHex, kHex, kHex),
MakeEntry(307, "faccessat", kHex, kPath, kHex, kHex, kHex, kHex),
MakeEntry(308, "pselect6", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(309, "ppoll", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(310, "unshare", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(311, "set_robust_list", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(312, "get_robust_list", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(313, "splice", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(314, "sync_file_range", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(315, "tee", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(316, "vmsplice", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(317, "move_pages", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(318, "getcpu", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(319, "epoll_pwait", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(320, "utimensat", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(321, "signalfd", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(322, "timerfd_create", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(323, "eventfd", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(324, "fallocate", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(325, "timerfd_settime", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(326, "timerfd_gettime", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(327, "signalfd4", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(328, "eventfd2", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(329, "epoll_create1", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(330, "dup3", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(331, "pipe2", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(332, "inotify_init1", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(333, "preadv", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(334, "pwritev", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(335, "rt_tgsigqueueinfo", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(336, "perf_event_open", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(337, "recvmmsg", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(338, "fanotify_init", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(339, "fanotify_mark", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(340, "prlimit64", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(341, "name_to_handle_at", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(342, "open_by_handle_at", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(343, "clock_adjtime", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(344, "syncfs", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(345, "sendmmsg", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(346, "setns", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(347, "process_vm_readv", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(348, "process_vm_writev", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(349, "kcmp", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(350, "finit_module", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(351, "sched_setattr", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(352, "sched_getattr", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(353, "renameat2", kHex, kPath, kHex, kPath, kHex, kHex),
MakeEntry(354, "seccomp", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(355, "getrandom", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(356, "memfd_create", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(357, "bpf", kHex, kHex, kHex, kHex, kHex, kHex),
// clang-format on
};
static_assert(IsSorted(kSyscallDataX8632, SyscallTable::Entry::BySyscallNr),
"Syscalls should be sorted");
// http://lxr.free-electrons.com/source/arch/powerpc/include/uapi/asm/unistd.h
// Note: PPC64 syscalls can have up to 7 register arguments, but nobody is
// using the 7th argument - probably for x64 compatibility reasons.
constexpr std::array kSyscallDataPPC64LE = {
// clang-format off
MakeEntry(0, "restart_syscall", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(1, "exit", kInt, kGen, kGen, kGen, kGen, kGen),
MakeEntry(2, "fork", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(3, "read", kInt, kHex, kInt),
MakeEntry(4, "write", kInt, kHex, kInt, kGen, kGen, kGen),
MakeEntry(5, "open", kPath, kHex, kOct, kGen, kGen, kGen),
MakeEntry(6, "close", kInt, kGen, kGen, kGen, kGen, kGen),
MakeEntry(7, "waitpid", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(8, "creat", kPath, kOct, kGen, kGen, kGen, kGen),
MakeEntry(9, "link", kPath, kPath, kGen, kGen, kGen, kGen),
MakeEntry(10, "unlink", kPath, kGen, kGen, kGen, kGen, kGen),
MakeEntry(11, "execve", kPath, kHex, kHex, kGen, kGen, kGen),
MakeEntry(12, "chdir", kPath, kGen, kGen, kGen, kGen, kGen),
MakeEntry(13, "time", kHex, kGen, kGen, kGen, kGen, kGen),
MakeEntry(14, "mknod", kPath, kOct, kHex, kGen, kGen, kGen),
MakeEntry(15, "chmod", kPath, kOct, kGen, kGen, kGen, kGen),
MakeEntry(16, "lchown", kPath, kInt, kInt, kGen, kGen, kGen),
MakeEntry(17, "break", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(18, "oldstat", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(19, "lseek", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(20, "getpid", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(21, "mount", kPath, kPath, kString, kHex, kGen, kGen),
MakeEntry(22, "umount", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(23, "setuid", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(24, "getuid", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(25, "stime", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(26, "ptrace", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(27, "alarm", kInt, kGen, kGen, kGen, kGen, kGen),
MakeEntry(28, "oldfstat", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(29, "pause", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(30, "utime", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(31, "stty", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(32, "gtty", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(33, "access", kPath, kHex, kGen, kGen, kGen, kGen),
MakeEntry(34, "nice", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(35, "ftime", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(36, "sync", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(37, "kill", kInt, kSignal, kGen, kGen, kGen, kGen),
MakeEntry(38, "rename", kPath, kPath, kGen, kGen, kGen, kGen),
MakeEntry(39, "mkdir", kPath, kOct, kGen, kGen, kGen, kGen),
MakeEntry(40, "rmdir", kPath, kGen, kGen, kGen, kGen, kGen),
MakeEntry(41, "dup", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(42, "pipe", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(43, "times", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(44, "prof", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(45, "brk", kHex, kGen, kGen, kGen, kGen, kGen),
MakeEntry(46, "setgid", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(47, "getgid", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(48, "signal", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(49, "geteuid", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(50, "getegid", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(51, "acct", kPath, kGen, kGen, kGen, kGen, kGen),
MakeEntry(52, "umount2", kPath, kHex, kGen, kGen, kGen, kGen),
MakeEntry(53, "lock", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(54, "ioctl", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(55, "fcntl", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(56, "mpx", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(57, "setpgid", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(58, "ulimit", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(59, "oldolduname", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(60, "umask", kHex, kGen, kGen, kGen, kGen, kGen),
MakeEntry(61, "chroot", kPath, kGen, kGen, kGen, kGen, kGen),
MakeEntry(62, "ustat", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(63, "dup2", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(64, "getppid", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(65, "getpgrp", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(66, "setsid", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(67, "sigaction", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(68, "sgetmask", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(69, "ssetmask", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(70, "setreuid", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(71, "setregid", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(72, "sigsuspend", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(73, "sigpending", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(74, "sethostname", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(75, "setrlimit", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(76, "getrlimit", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(77, "getrusage", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(78, "gettimeofday", kHex, kHex, kGen, kGen, kGen, kGen),
MakeEntry(79, "settimeofday", kHex, kHex, kGen, kGen, kGen, kGen),
MakeEntry(80, "getgroups", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(81, "setgroups", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(82, "select", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(83, "symlink", kPath, kPath, kGen, kGen, kGen, kGen),
MakeEntry(84, "oldlstat", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(85, "readlink", kPath, kGen, kInt, kGen, kGen, kGen),
MakeEntry(86, "uselib", kPath, kGen, kGen, kGen, kGen, kGen),
MakeEntry(87, "swapon", kPath, kHex, kGen, kGen, kGen, kGen),
MakeEntry(88, "reboot", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(89, "readdir", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(90, "mmap", kHex, kInt, kHex, kHex, kInt, kInt),
MakeEntry(91, "munmap", kHex, kHex, kGen, kGen, kGen, kGen),
MakeEntry(92, "truncate", kPath, kInt, kGen, kGen, kGen, kGen),
MakeEntry(93, "ftruncate", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(94, "fchmod", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(95, "fchown", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(96, "getpriority", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(97, "setpriority", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(98, "profil", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(99, "statfs", kPath, kGen, kGen, kGen, kGen, kGen),
MakeEntry(100, "fstatfs", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(101, "ioperm", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(102, "socketcall", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(103, "syslog", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(104, "setitimer", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(105, "getitimer", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(106, "stat", kPath, kGen, kGen, kGen, kGen, kGen),
MakeEntry(107, "lstat", kPath, kGen, kGen, kGen, kGen, kGen),
MakeEntry(108, "fstat", kInt, kHex, kGen, kGen, kGen, kGen),
MakeEntry(109, "olduname", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(110, "iopl", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(111, "vhangup", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(112, "idle", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(113, "vm86", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(114, "wait4", kInt, kHex, kHex, kHex, kGen, kGen),
MakeEntry(115, "swapoff", kPath, kGen, kGen, kGen, kGen, kGen),
MakeEntry(116, "sysinfo", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(117, "ipc", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(118, "fsync", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(119, "sigreturn", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(120, "clone", kCloneFlag, kHex, kHex, kHex, kHex, kGen),
MakeEntry(121, "setdomainname", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(122, "uname", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(123, "modify_ldt", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(124, "adjtimex", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(125, "mprotect", kHex, kHex, kHex, kGen, kGen, kGen),
MakeEntry(126, "sigprocmask", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(127, "create_module", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(128, "init_module", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(129, "delete_module", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(130, "get_kernel_syms", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(131, "quotactl", kInt, kPath, kInt, kGen, kGen, kGen),
MakeEntry(132, "getpgid", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(133, "fchdir", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(134, "bdflush", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(135, "sysfs", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(136, "personality", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(137, "afs_syscall", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(138, "setfsuid", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(139, "setfsgid", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(140, "_llseek", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(141, "getdents", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(142, "_newselect", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(143, "flock", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(144, "msync", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(145, "readv", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(146, "writev", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(147, "getsid", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(148, "fdatasync", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(149, "_sysctl", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(150, "mlock", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(151, "munlock", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(152, "mlockall", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(153, "munlockall", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(154, "sched_setparam", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(155, "sched_getparam", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(156, "sched_setscheduler", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(157, "sched_getscheduler", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(158, "sched_yield", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(159, "sched_get_priority_max", kGen, kGen, kGen, kGen, kGen,
kGen),
MakeEntry(160, "sched_get_priority_min", kGen, kGen, kGen, kGen, kGen,
kGen),
MakeEntry(161, "sched_rr_get_interval", kGen, kGen, kGen, kGen, kGen,
kGen),
MakeEntry(162, "nanosleep", kHex, kHex, kGen, kGen, kGen, kGen),
MakeEntry(163, "mremap", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(164, "setresuid", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(165, "getresuid", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(166, "query_module", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(167, "poll", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(168, "nfsservctl", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(169, "setresgid", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(170, "getresgid", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(171, "prctl", kInt, kHex, kHex, kHex, kHex, kGen),
MakeEntry(172, "rt_sigreturn", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(173, "rt_sigaction", kSignal, kHex, kHex, kInt, kGen, kGen),
MakeEntry(174, "rt_sigprocmask", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(175, "rt_sigpending", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(176, "rt_sigtimedwait", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(177, "rt_sigqueueinfo", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(178, "rt_sigsuspend", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(179, "pread64", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(180, "pwrite64", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(181, "chown", kPath, kInt, kInt, kGen, kGen, kGen),
MakeEntry(182, "getcwd", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(183, "capget", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(184, "capset", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(185, "sigaltstack", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(186, "sendfile", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(187, "getpmsg", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(188, "putpmsg", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(189, "vfork", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(190, "ugetrlimit", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(191, "readahead", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(192, "mmap2", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(193, "truncate64", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(194, "ftruncate64", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(195, "stat64", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(196, "lstat64", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(197, "fstat64", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(198, "pciconfig_read", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(199, "pciconfig_write", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(200, "pciconfig_iobase", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(201, "multiplexer", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(202, "getdents64", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(203, "pivot_root", kPath, kPath, kGen, kGen, kGen, kGen),
MakeEntry(204, "fcntl64", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(205, "madvise", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(206, "mincore", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(207, "gettid", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(208, "tkill", kInt, kSignal, kGen, kGen, kGen, kGen),
MakeEntry(209, "setxattr", kPath, kString, kGen, kInt, kHex, kGen),
MakeEntry(210, "lsetxattr", kPath, kString, kGen, kInt, kHex, kGen),
MakeEntry(211, "fsetxattr", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(212, "getxattr", kPath, kString, kGen, kInt, kGen, kGen),
MakeEntry(213, "lgetxattr", kPath, kString, kGen, kInt, kGen, kGen),
MakeEntry(214, "fgetxattr", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(215, "listxattr", kPath, kGen, kInt, kGen, kGen, kGen),
MakeEntry(216, "llistxattr", kPath, kGen, kInt, kGen, kGen, kGen),
MakeEntry(217, "flistxattr", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(218, "removexattr", kPath, kString, kGen, kGen, kGen, kGen),
MakeEntry(219, "lremovexattr", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(220, "fremovexattr", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(221, "futex", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(222, "sched_setaffinity", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(223, "sched_getaffinity", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(225, "tuxcall", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(226, "sendfile64", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(227, "io_setup", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(228, "io_destroy", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(229, "io_getevents", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(230, "io_submit", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(231, "io_cancel", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(232, "set_tid_address", kHex, kGen, kGen, kGen, kGen, kGen),
MakeEntry(233, "fadvise64", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(234, "exit_group", kInt, kGen, kGen, kGen, kGen, kGen),
MakeEntry(235, "lookup_dcookie", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(236, "epoll_create", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(237, "epoll_ctl", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(238, "epoll_wait", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(239, "remap_file_pages", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(240, "timer_create", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(241, "timer_settime", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(242, "timer_gettime", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(243, "timer_getoverrun", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(244, "timer_delete", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(245, "clock_settime", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(246, "clock_gettime", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(247, "clock_getres", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(248, "clock_nanosleep", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(249, "swapcontext", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(250, "tgkill", kInt, kInt, kSignal, kGen, kGen, kGen),
MakeEntry(251, "utimes", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(252, "statfs64", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(253, "fstatfs64", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(254, "fadvise64_64", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(255, "rtas", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(256, "sys_debug_setcontext", kHex, kHex, kHex, kHex, kHex,
kHex),
MakeEntry(258, "migrate_pages", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(259, "mbind", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(260, "get_mempolicy", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(261, "set_mempolicy", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(262, "mq_open", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(263, "mq_unlink", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(264, "mq_timedsend", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(265, "mq_timedreceive", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(266, "mq_notify", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(267, "mq_getsetattr", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(268, "kexec_load", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(269, "add_key", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(270, "request_key", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(271, "keyctl", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(272, "waitid", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(273, "ioprio_set", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(274, "ioprio_get", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(275, "inotify_init", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(276, "inotify_add_watch", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(277, "inotify_rm_watch", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(278, "spu_run", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(279, "spu_create", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(280, "pselect6", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(281, "ppoll", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(282, "unshare", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(283, "splice", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(284, "tee", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(285, "vmsplice", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(286, "openat", kGen, kPath, kOct, kHex, kGen, kGen),
MakeEntry(287, "mkdirat", kGen, kPath, kGen, kGen, kGen, kGen),
MakeEntry(288, "mknodat", kGen, kPath, kGen, kGen, kGen, kGen),
MakeEntry(289, "fchownat", kGen, kPath, kGen, kGen, kGen, kGen),
MakeEntry(290, "futimesat", kGen, kPath, kGen, kGen, kGen, kGen),
MakeEntry(291, "newfstatat", kGen, kPath, kGen, kGen, kGen, kGen),
MakeEntry(292, "unlinkat", kGen, kPath, kGen, kGen, kGen, kGen),
MakeEntry(293, "renameat", kGen, kPath, kGen, kPath, kGen, kGen),
MakeEntry(294, "linkat", kGen, kPath, kGen, kPath, kGen, kGen),
MakeEntry(295, "symlinkat", kPath, kGen, kPath, kGen, kGen, kGen),
MakeEntry(296, "readlinkat", kGen, kPath, kGen, kGen, kGen, kGen),
MakeEntry(297, "fchmodat", kGen, kPath, kGen, kGen, kGen, kGen),
MakeEntry(298, "faccessat", kGen, kPath, kGen, kGen, kGen, kGen),
MakeEntry(299, "get_robust_list", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(300, "set_robust_list", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(301, "move_pages", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(302, "getcpu", kHex, kHex, kHex, kGen, kGen, kGen),
MakeEntry(303, "epoll_pwait", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(304, "utimensat", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(305, "signalfd", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(306, "timerfd_create", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(307, "eventfd", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(308, "sync_file_range2", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(309, "fallocate", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(310, "subpage_prot", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(311, "timerfd_settime", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(312, "timerfd_gettime", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(313, "signalfd4", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(314, "eventfd2", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(315, "epoll_create1", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(316, "dup3", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(317, "pipe2", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(318, "inotify_init1", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(319, "perf_event_open", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(320, "preadv", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(321, "pwritev", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(322, "rt_tgsigqueueinfo", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(323, "fanotify_init", kHex, kHex, kInt, kGen, kGen, kGen),
MakeEntry(324, "fanotify_mark", kInt, kHex, kInt, kPath, kGen, kGen),
MakeEntry(325, "prlimit64", kInt, kInt, kHex, kHex, kGen, kGen),
MakeEntry(326, "socket", kAddressFamily, kInt, kInt, kGen, kGen, kGen),
MakeEntry(327, "bind", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(328, "connect", kInt, kSockaddr, kInt, kGen, kGen, kGen),
MakeEntry(329, "listen", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(330, "accept", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(331, "getsockname", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(332, "getpeername", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(333, "socketpair", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(334, "send", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(335, "sendto", kInt, kGen, kInt, kHex, kSockaddr, kInt),
MakeEntry(336, "recv", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(337, "recvfrom", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(338, "shutdown", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(339, "setsockopt", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(340, "getsockopt", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(341, "sendmsg", kInt, kSockmsghdr, kHex, kGen, kGen, kGen),
MakeEntry(342, "recvmsg", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(343, "recvmmsg", kInt, kHex, kHex, kHex, kGen, kGen),
MakeEntry(344, "accept4", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(345, "name_to_handle_at", kInt, kGen, kHex, kHex, kHex, kGen),
MakeEntry(346, "open_by_handle_at", kInt, kHex, kHex, kGen, kGen, kGen),
MakeEntry(347, "clock_adjtime", kInt, kHex, kGen, kGen, kGen, kGen),
MakeEntry(348, "syncfs", kInt, kGen, kGen, kGen, kGen, kGen),
MakeEntry(349, "sendmmsg", kInt, kHex, kInt, kHex, kGen, kGen),
MakeEntry(350, "setns", kInt, kHex, kGen, kGen, kGen, kGen),
MakeEntry(351, "process_vm_readv", kInt, kHex, kInt, kHex, kInt, kInt),
MakeEntry(352, "process_vm_writev", kInt, kHex, kInt, kHex, kInt, kInt),
MakeEntry(353, "finit_module", kInt, kPath, kHex, kGen, kGen, kGen),
MakeEntry(354, "kcmp", kInt, kInt, kInt, kHex, kHex, kGen),
MakeEntry(355, "sched_setattr", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(356, "sched_getattr", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(357, "renameat2", kGen, kPath, kGen, kPath, kGen, kGen),
MakeEntry(358, "seccomp", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(359, "getrandom", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(360, "memfd_create", kGen, kGen, kGen, kGen, kGen, kGen),
MakeEntry(361, "bpf", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(362, "execveat", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(363, "switch_endian", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(364, "userfaultfd", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(365, "membarrier", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(378, "mlock2", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(379, "copy_file_range", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(380, "preadv2", kHex, kHex, kHex, kHex, kHex, kHex),
MakeEntry(381, "pwritev2", kHex, kHex, kHex, kHex, kHex, kHex),
// clang-format on
};
static_assert(IsSorted(kSyscallDataPPC64LE, SyscallTable::Entry::BySyscallNr),
"Syscalls should be sorted");
// TODO(cblichmann): Confirm the entries in this list.
// https://github.com/torvalds/linux/blob/v5.8/include/uapi/asm-generic/unistd.h
constexpr std::array kSyscallDataArm64 = {
// clang-format off
MakeEntry(0, "io_setup", UnknownArguments()),
MakeEntry(1, "io_destroy", UnknownArguments()),
MakeEntry(2, "io_submit", UnknownArguments()),
MakeEntry(3, "io_cancel", UnknownArguments()),
MakeEntry(4, "io_getevents", UnknownArguments()),
MakeEntry(5, "setxattr", kPath, kString, kGen, kInt, kHex, kGen),
MakeEntry(6, "lsetxattr", kPath, kString, kGen, kInt, kHex, kGen),
MakeEntry(7, "fsetxattr", UnknownArguments()),
MakeEntry(8, "getxattr", kPath, kString, kGen, kInt, kGen, kGen),
MakeEntry(9, "lgetxattr", kPath, kString, kGen, kInt, kGen, kGen),
MakeEntry(10, "fgetxattr", UnknownArguments()),
MakeEntry(11, "listxattr", kPath, kGen, kInt, kGen, kGen, kGen),
MakeEntry(12, "llistxattr", kPath, kGen, kInt, kGen, kGen, kGen),
MakeEntry(13, "flistxattr", UnknownArguments()),
MakeEntry(14, "removexattr", kPath, kString, kGen, kGen, kGen, kGen),
MakeEntry(15, "lremovexattr", UnknownArguments()),
MakeEntry(16, "fremovexattr", UnknownArguments()),
MakeEntry(17, "getcwd", UnknownArguments()),
MakeEntry(18, "lookup_dcookie", UnknownArguments()),
MakeEntry(19, "eventfd2", UnknownArguments()),
MakeEntry(20, "epoll_create1", UnknownArguments()),
MakeEntry(21, "epoll_ctl", UnknownArguments()),
MakeEntry(22, "epoll_pwait", UnknownArguments()),
MakeEntry(23, "dup", UnknownArguments()),
MakeEntry(24, "dup3", UnknownArguments()),
MakeEntry(25, "fcntl", UnknownArguments()),
MakeEntry(26, "inotify_init1", UnknownArguments()),
MakeEntry(27, "inotify_add_watch", UnknownArguments()),
MakeEntry(28, "inotify_rm_watch", UnknownArguments()),
MakeEntry(29, "ioctl", UnknownArguments()),
MakeEntry(30, "ioprio_set", UnknownArguments()),
MakeEntry(31, "ioprio_get", UnknownArguments()),
MakeEntry(32, "flock", UnknownArguments()),
MakeEntry(33, "mknodat", kGen, kPath, kGen, kGen, kGen, kGen),
MakeEntry(34, "mkdirat", kGen, kPath, kGen, kGen, kGen, kGen),
MakeEntry(35, "unlinkat", kGen, kPath, kGen, kGen, kGen, kGen),
MakeEntry(36, "symlinkat", kPath, kGen, kPath, kGen, kGen, kGen),
MakeEntry(37, "linkat", kGen, kPath, kGen, kPath, kGen, kGen),
MakeEntry(38, "renameat", kGen, kPath, kGen, kPath, kGen, kGen),
MakeEntry(39, "umount2", kPath, kHex, kGen, kGen, kGen, kGen),
MakeEntry(40, "mount", kPath, kPath, kString, kHex, kGen, kGen),
MakeEntry(41, "pivot_root", kPath, kPath, kGen, kGen, kGen, kGen),
MakeEntry(42, "nfsservctl", UnknownArguments()),
MakeEntry(43, "statfs", kPath, kGen, kGen, kGen, kGen, kGen),
MakeEntry(44, "fstatfs", UnknownArguments()),
MakeEntry(45, "truncate", kPath, kInt, kGen, kGen, kGen, kGen),
MakeEntry(46, "ftruncate", UnknownArguments()),
MakeEntry(47, "fallocate", UnknownArguments()),
MakeEntry(48, "faccessat", kGen, kPath, kGen, kGen, kGen, kGen),
MakeEntry(49, "chdir", kPath, kGen, kGen, kGen, kGen, kGen),
MakeEntry(50, "fchdir", UnknownArguments()),
MakeEntry(51, "chroot", kPath, kGen, kGen, kGen, kGen, kGen),
MakeEntry(52, "fchmod", UnknownArguments()),
MakeEntry(53, "fchmodat", kGen, kPath, kGen, kGen, kGen, kGen),
MakeEntry(54, "fchownat", kGen, kPath, kGen, kGen, kGen, kGen),
MakeEntry(55, "fchown", UnknownArguments()),
MakeEntry(56, "openat", kGen, kPath, kOct, kHex, kGen, kGen),
MakeEntry(57, "close", kInt, kGen, kGen, kGen, kGen, kGen),
MakeEntry(58, "vhangup", UnknownArguments()),
MakeEntry(59, "pipe2", UnknownArguments()),
MakeEntry(60, "quotactl", kInt, kPath, kInt, kGen, kGen, kGen),
MakeEntry(61, "getdents64", UnknownArguments()),
MakeEntry(62, "lseek", UnknownArguments()),
MakeEntry(63, "read", kInt, kHex, kInt, kGen, kGen, kGen),
MakeEntry(64, "write", kInt, kHex, kInt, kGen, kGen, kGen),
MakeEntry(65, "readv", UnknownArguments()),
MakeEntry(66, "writev", UnknownArguments()),
MakeEntry(67, "pread64", UnknownArguments()),
MakeEntry(68, "pwrite64", UnknownArguments()),
MakeEntry(69, "preadv", UnknownArguments()),
MakeEntry(70, "pwritev", UnknownArguments()),
MakeEntry(71, "sendfile", UnknownArguments()),
MakeEntry(72, "pselect6", UnknownArguments()),
MakeEntry(73, "ppoll", UnknownArguments()),
MakeEntry(74, "signalfd4", UnknownArguments()),
MakeEntry(75, "vmsplice", UnknownArguments()),
MakeEntry(76, "splice", UnknownArguments()),
MakeEntry(77, "tee", UnknownArguments()),
MakeEntry(78, "readlinkat", kGen, kPath, kGen, kGen, kGen, kGen),
MakeEntry(79, "newfstatat", kGen, kPath, kGen, kGen, kGen, kGen),
MakeEntry(80, "fstat", kInt, kHex, kGen, kGen, kGen, kGen),
MakeEntry(81, "sync", UnknownArguments()),
MakeEntry(82, "fsync", UnknownArguments()),
MakeEntry(83, "fdatasync", UnknownArguments()),
MakeEntry(84, "sync_file_range", UnknownArguments()),
MakeEntry(85, "timerfd_create", UnknownArguments()),
MakeEntry(86, "timerfd_settime", UnknownArguments()),
MakeEntry(87, "timerfd_gettime", UnknownArguments()),
MakeEntry(88, "utimensat", UnknownArguments()),
MakeEntry(89, "acct", kPath, kGen, kGen, kGen, kGen, kGen),
MakeEntry(90, "capget", UnknownArguments()),
MakeEntry(91, "capset", UnknownArguments()),
MakeEntry(92, "personality", UnknownArguments()),
MakeEntry(93, "exit", kInt, kGen, kGen, kGen, kGen, kGen),
MakeEntry(94, "exit_group", kInt, kGen, kGen, kGen, kGen, kGen),
MakeEntry(95, "waitid", UnknownArguments()),
MakeEntry(96, "set_tid_address", kHex, kGen, kGen, kGen, kGen, kGen),
MakeEntry(97, "unshare", UnknownArguments()),
MakeEntry(98, "futex", UnknownArguments()),
MakeEntry(99, "set_robust_list", UnknownArguments()),
MakeEntry(100, "get_robust_list", UnknownArguments()),
MakeEntry(101, "nanosleep", kHex, kHex, kGen, kGen, kGen, kGen),
MakeEntry(102, "getitimer", UnknownArguments()),
MakeEntry(103, "setitimer", UnknownArguments()),
MakeEntry(104, "kexec_load", UnknownArguments()),
MakeEntry(105, "init_module", UnknownArguments()),
MakeEntry(106, "delete_module", UnknownArguments()),
MakeEntry(107, "timer_create", UnknownArguments()),
MakeEntry(108, "timer_gettime", UnknownArguments()),
MakeEntry(109, "timer_getoverrun", UnknownArguments()),
MakeEntry(110, "timer_settime", UnknownArguments()),
MakeEntry(111, "timer_delete", UnknownArguments()),
MakeEntry(112, "clock_settime", UnknownArguments()),
MakeEntry(113, "clock_gettime", UnknownArguments()),
MakeEntry(114, "clock_getres", UnknownArguments()),
MakeEntry(115, "clock_nanosleep", UnknownArguments()),
MakeEntry(116, "syslog", UnknownArguments()),
MakeEntry(117, "ptrace", UnknownArguments()),
MakeEntry(118, "sched_setparam", UnknownArguments()),
MakeEntry(119, "sched_setscheduler", UnknownArguments()),
MakeEntry(120, "sched_getscheduler", UnknownArguments()),
MakeEntry(121, "sched_getparam", UnknownArguments()),
MakeEntry(122, "sched_setaffinity", UnknownArguments()),
MakeEntry(123, "sched_getaffinity", UnknownArguments()),
MakeEntry(124, "sched_yield", UnknownArguments()),
MakeEntry(125, "sched_get_priority_max", UnknownArguments()),
MakeEntry(126, "sched_get_priority_min", UnknownArguments()),
MakeEntry(127, "sched_rr_get_interval", UnknownArguments()),
MakeEntry(128, "restart_syscall", UnknownArguments()),
MakeEntry(129, "kill", kInt, kSignal, kGen, kGen, kGen, kGen),
MakeEntry(130, "tkill", kInt, kSignal, kGen, kGen, kGen, kGen),
MakeEntry(131, "tgkill", kInt, kInt, kSignal, kGen, kGen, kGen),
MakeEntry(132, "sigaltstack", UnknownArguments()),
MakeEntry(133, "rt_sigsuspend", UnknownArguments()),
MakeEntry(134, "rt_sigaction", kSignal, kHex, kHex, kInt, kGen, kGen),
MakeEntry(135, "rt_sigprocmask", UnknownArguments()),
MakeEntry(136, "rt_sigpending", UnknownArguments()),
MakeEntry(137, "rt_sigtimedwait", UnknownArguments()),
MakeEntry(138, "rt_sigqueueinfo", UnknownArguments()),
MakeEntry(139, "rt_sigreturn", UnknownArguments()),
MakeEntry(140, "setpriority", UnknownArguments()),
MakeEntry(141, "getpriority", UnknownArguments()),
MakeEntry(142, "reboot", UnknownArguments()),
MakeEntry(143, "setregid", UnknownArguments()),
MakeEntry(144, "setgid", UnknownArguments()),
MakeEntry(145, "setreuid", UnknownArguments()),
MakeEntry(146, "setuid", UnknownArguments()),
MakeEntry(147, "setresuid", UnknownArguments()),
MakeEntry(148, "getresuid", UnknownArguments()),
MakeEntry(149, "setresgid", UnknownArguments()),
MakeEntry(150, "getresgid", UnknownArguments()),
MakeEntry(151, "setfsuid", UnknownArguments()),
MakeEntry(152, "setfsgid", UnknownArguments()),
MakeEntry(153, "times", UnknownArguments()),
MakeEntry(154, "setpgid", UnknownArguments()),
MakeEntry(155, "getpgid", UnknownArguments()),
MakeEntry(156, "getsid", UnknownArguments()),
MakeEntry(157, "setsid", UnknownArguments()),
MakeEntry(158, "getgroups", UnknownArguments()),
MakeEntry(159, "setgroups", UnknownArguments()),
MakeEntry(160, "uname", UnknownArguments()),
MakeEntry(161, "sethostname", UnknownArguments()),
MakeEntry(162, "setdomainname", UnknownArguments()),
MakeEntry(163, "getrlimit", UnknownArguments()),
MakeEntry(164, "setrlimit", UnknownArguments()),
MakeEntry(165, "getrusage", UnknownArguments()),
MakeEntry(166, "umask", kHex, kGen, kGen, kGen, kGen, kGen),
MakeEntry(167, "prctl", kInt, kHex, kHex, kHex, kHex, kGen),
MakeEntry(168, "getcpu", kHex, kHex, kHex, kGen, kGen, kGen),
MakeEntry(169, "gettimeofday", kHex, kHex, kGen, kGen, kGen, kGen),
MakeEntry(170, "settimeofday", kHex, kHex, kGen, kGen, kGen, kGen),
MakeEntry(171, "adjtimex", UnknownArguments()),
MakeEntry(172, "getpid", UnknownArguments()),
MakeEntry(173, "getppid", UnknownArguments()),
MakeEntry(174, "getuid", UnknownArguments()),
MakeEntry(175, "geteuid", UnknownArguments()),
MakeEntry(176, "getgid", UnknownArguments()),
MakeEntry(177, "getegid", UnknownArguments()),
MakeEntry(178, "gettid", UnknownArguments()),
MakeEntry(179, "sysinfo", UnknownArguments()),
MakeEntry(180, "mq_open", UnknownArguments()),
MakeEntry(181, "mq_unlink", UnknownArguments()),
MakeEntry(182, "mq_timedsend", UnknownArguments()),
MakeEntry(183, "mq_timedreceive", UnknownArguments()),
MakeEntry(184, "mq_notify", UnknownArguments()),
MakeEntry(185, "mq_getsetattr", UnknownArguments()),
MakeEntry(186, "msgget", UnknownArguments()),
MakeEntry(187, "msgctl", UnknownArguments()),
MakeEntry(188, "msgrcv", UnknownArguments()),
MakeEntry(189, "msgsnd", UnknownArguments()),
MakeEntry(190, "semget", UnknownArguments()),
MakeEntry(191, "semctl", UnknownArguments()),
MakeEntry(192, "semtimedop", UnknownArguments()),
MakeEntry(193, "semop", UnknownArguments()),
MakeEntry(194, "shmget", UnknownArguments()),
MakeEntry(195, "shmctl", UnknownArguments()),
MakeEntry(196, "shmat", UnknownArguments()),
MakeEntry(197, "shmdt", UnknownArguments()),
MakeEntry(198, "socket", kAddressFamily, kInt, kInt, kGen, kGen, kGen),
MakeEntry(199, "socketpair", UnknownArguments()),
MakeEntry(200, "bind", UnknownArguments()),
MakeEntry(201, "listen", UnknownArguments()),
MakeEntry(202, "accept", UnknownArguments()),
MakeEntry(203, "connect", kInt, kSockaddr, kInt, kGen, kGen, kGen),
MakeEntry(204, "getsockname", UnknownArguments()),
MakeEntry(205, "getpeername", UnknownArguments()),
MakeEntry(206, "sendto", kInt, kGen, kInt, kHex, kSockaddr, kInt),
MakeEntry(207, "recvfrom", UnknownArguments()),
MakeEntry(208, "setsockopt", UnknownArguments()),
MakeEntry(209, "getsockopt", UnknownArguments()),
MakeEntry(210, "shutdown", UnknownArguments()),
MakeEntry(211, "sendmsg", kInt, kSockmsghdr, kHex, kGen, kGen, kGen),
MakeEntry(212, "recvmsg", UnknownArguments()),
MakeEntry(213, "readahead", UnknownArguments()),
MakeEntry(214, "brk", kHex, kGen, kGen, kGen, kGen, kGen),
MakeEntry(215, "munmap", kHex, kHex, kGen, kGen, kGen, kGen),
MakeEntry(216, "mremap", UnknownArguments()),
MakeEntry(217, "add_key", UnknownArguments()),
MakeEntry(218, "request_key", UnknownArguments()),
MakeEntry(219, "keyctl", UnknownArguments()),
MakeEntry(220, "clone", kCloneFlag, kHex, kHex, kHex, kHex, kGen),
MakeEntry(221, "execve", kPath, kHex, kHex, kGen, kGen, kGen),
MakeEntry(222, "mmap", kHex, kInt, kHex, kHex, kInt, kInt),
MakeEntry(223, "fadvise64", UnknownArguments()),
MakeEntry(224, "swapon", kPath, kHex, kGen, kGen, kGen, kGen),
MakeEntry(225, "swapoff", kPath, kGen, kGen, kGen, kGen, kGen),
MakeEntry(226, "mprotect", kHex, kHex, kHex, kGen, kGen, kGen),
MakeEntry(227, "msync", UnknownArguments()),
MakeEntry(228, "mlock", UnknownArguments()),
MakeEntry(229, "munlock", UnknownArguments()),
MakeEntry(230, "mlockall", UnknownArguments()),
MakeEntry(231, "munlockall", UnknownArguments()),
MakeEntry(232, "mincore", UnknownArguments()),
MakeEntry(233, "madvise", UnknownArguments()),
MakeEntry(234, "remap_file_pages", UnknownArguments()),
MakeEntry(235, "mbind", UnknownArguments()),
MakeEntry(236, "get_mempolicy", UnknownArguments()),
MakeEntry(237, "set_mempolicy", UnknownArguments()),
MakeEntry(238, "migrate_pages", UnknownArguments()),
MakeEntry(239, "move_pages", UnknownArguments()),
MakeEntry(240, "rt_tgsigqueueinfo", UnknownArguments()),
MakeEntry(241, "perf_event_open", UnknownArguments()),
MakeEntry(242, "accept4", UnknownArguments()),
MakeEntry(243, "recvmmsg", kInt, kHex, kHex, kHex, kGen, kGen),
MakeEntry(260, "wait4", kInt, kHex, kHex, kHex, kGen, kGen),
MakeEntry(261, "prlimit64", kInt, kInt, kHex, kHex, kGen, kGen),
MakeEntry(262, "fanotify_init", kHex, kHex, kInt, kGen, kGen, kGen),
MakeEntry(263, "fanotify_mark", kInt, kHex, kInt, kPath, kGen, kGen),
MakeEntry(264, "name_to_handle_at", kInt, kGen, kHex, kHex, kHex, kGen),
MakeEntry(265, "open_by_handle_at", kInt, kHex, kHex, kGen, kGen, kGen),
MakeEntry(266, "clock_adjtime", kInt, kHex, kGen, kGen, kGen, kGen),
MakeEntry(267, "syncfs", kInt, kGen, kGen, kGen, kGen, kGen),
MakeEntry(268, "setns", kInt, kHex, kGen, kGen, kGen, kGen),
MakeEntry(269, "sendmmsg", kInt, kHex, kInt, kHex, kGen, kGen),
MakeEntry(270, "process_vm_readv", kInt, kHex, kInt, kHex, kInt, kInt),
MakeEntry(271, "process_vm_writev", kInt, kHex, kInt, kHex, kInt, kInt),
MakeEntry(272, "kcmp", kInt, kInt, kInt, kHex, kHex, kGen),
MakeEntry(273, "finit_module", kInt, kPath, kHex, kGen, kGen, kGen),
MakeEntry(274, "sched_setattr", UnknownArguments()),
MakeEntry(275, "sched_getattr", UnknownArguments()),
MakeEntry(276, "renameat2", kGen, kPath, kGen, kPath, kGen, kGen),
MakeEntry(277, "seccomp", UnknownArguments()),
MakeEntry(278, "getrandom", UnknownArguments()),
MakeEntry(279, "memfd_create", UnknownArguments()),
// clang-format on
};
static_assert(IsSorted(kSyscallDataArm64, SyscallTable::Entry::BySyscallNr),
"Syscalls should be sorted");
constexpr std::array kSyscallDataArm32 = {
// clang-format off
MakeEntry(0, "restart_syscall", kGen, kGen, kGen, kGen),
MakeEntry(1, "exit", kHex, kHex, kHex, kHex),
MakeEntry(2, "fork", kGen, kGen, kGen, kGen),
MakeEntry(3, "read", kInt, kHex, kInt),
MakeEntry(4, "write", kHex, kHex, kHex, kHex),
MakeEntry(5, "open", kPath, kHex, kOct),
MakeEntry(6, "close", kHex, kHex, kHex, kHex),
MakeEntry(8, "creat", kPath, kHex, kHex, kHex),
MakeEntry(9, "link", kPath, kPath),
MakeEntry(10, "unlink", kPath),
MakeEntry(11, "execve", kPath, kHex, kHex),
MakeEntry(12, "chdir", kPath),
MakeEntry(14, "mknod", kPath, kOct, kHex),
MakeEntry(15, "chmod", kPath, kOct),
MakeEntry(16, "lchown", kPath, kInt, kInt),
MakeEntry(19, "lseek", kGen, kGen, kGen, kGen),
MakeEntry(20, "getpid", kGen, kGen, kGen, kGen),
MakeEntry(21, "mount", kHex, kHex, kHex, kHex),
MakeEntry(23, "setuid", kGen, kGen, kGen, kGen),
MakeEntry(24, "getuid", kGen, kGen, kGen, kGen),
MakeEntry(26, "ptrace", kGen, kGen, kGen),
MakeEntry(29, "pause", kGen, kGen, kGen, kGen),
MakeEntry(33, "access", kPath, kHex),
MakeEntry(34, "nice", kHex, kHex, kHex, kHex),
MakeEntry(36, "sync", kGen, kGen, kGen, kGen),
MakeEntry(37, "kill", kHex, kHex, kHex, kHex),
MakeEntry(38, "rename", kPath, kPath),
MakeEntry(39, "mkdir", kPath, kHex, kHex, kHex),
MakeEntry(40, "rmdir", kHex, kHex, kHex, kHex),
MakeEntry(41, "dup", kGen, kGen, kGen, kGen),
MakeEntry(42, "pipe", kGen, kGen, kGen, kGen),
MakeEntry(43, "times", kGen, kGen, kGen, kGen),
MakeEntry(45, "brk", kHex),
MakeEntry(46, "setgid", kGen, kGen, kGen, kGen),
MakeEntry(47, "getgid", kGen, kGen, kGen, kGen),
MakeEntry(49, "geteuid", kGen, kGen, kGen, kGen),
MakeEntry(50, "getegid", kGen, kGen, kGen, kGen),
MakeEntry(51, "acct", kHex, kHex, kHex, kHex),
MakeEntry(52, "umount2", kHex, kHex, kHex, kHex),
MakeEntry(54, "ioctl", kGen, kGen, kGen, kGen),
MakeEntry(55, "fcntl", kGen, kGen, kGen, kGen),
MakeEntry(57, "setpgid", kGen, kGen, kGen, kGen),
MakeEntry(60, "umask", kHex),
MakeEntry(61, "chroot", kHex, kHex, kHex, kHex),
MakeEntry(62, "ustat", kGen, kGen, kGen, kGen),
MakeEntry(63, "dup2", kGen, kGen),
MakeEntry(64, "getppid", kGen, kGen, kGen, kGen),
MakeEntry(65, "getpgrp", kGen, kGen, kGen, kGen),
MakeEntry(66, "setsid", kGen, kGen, kGen, kGen),
MakeEntry(67, "sigaction", kHex, kHex, kHex, kHex),
MakeEntry(70, "setreuid", kGen, kGen, kGen, kGen),
MakeEntry(71, "setregid", kGen, kGen, kGen, kGen),
MakeEntry(72, "sigsuspend", kHex, kHex, kHex, kHex),
MakeEntry(73, "sigpending", kHex, kHex, kHex, kHex),
MakeEntry(74, "sethostname", kGen, kGen, kGen, kGen),
MakeEntry(75, "setrlimit", kGen, kGen, kGen, kGen),
MakeEntry(77, "getrusage", kGen, kGen, kGen, kGen),
MakeEntry(78, "gettimeofday", kHex, kHex),
MakeEntry(79, "settimeofday", kHex, kHex),
MakeEntry(80, "getgroups", kGen, kGen, kGen, kGen),
MakeEntry(81, "setgroups", kGen, kGen, kGen, kGen),
MakeEntry(83, "symlink", kPath, kPath),
MakeEntry(85, "readlink", kPath, kGen, kInt),
MakeEntry(86, "uselib", kPath),
MakeEntry(87, "swapon", kHex, kHex, kHex, kHex),
MakeEntry(88, "reboot", kGen, kGen, kGen, kGen),
MakeEntry(91, "munmap", kHex, kHex),
MakeEntry(92, "truncate", kPath, kHex, kHex, kHex),
MakeEntry(93, "ftruncate", kGen, kGen, kGen, kGen),
MakeEntry(94, "fchmod", kGen, kGen, kGen, kGen),
MakeEntry(95, "fchown", kGen, kGen, kGen, kGen),
MakeEntry(96, "getpriority", kGen, kGen, kGen, kGen),
MakeEntry(97, "setpriority", kGen, kGen, kGen, kGen),
MakeEntry(99, "statfs", kPath, kGen, kGen, kGen),
MakeEntry(100, "fstatfs", kGen, kGen, kGen, kGen),
MakeEntry(103, "syslog", kGen, kGen, kGen, kGen),
MakeEntry(104, "setitimer", kGen, kGen, kGen, kGen),
MakeEntry(105, "getitimer", kGen, kGen, kGen, kGen),
MakeEntry(106, "stat", kPath, kGen),
MakeEntry(107, "lstat", kPath, kGen),
MakeEntry(108, "fstat", kHex, kHex, kHex, kHex),
MakeEntry(111, "vhangup", kGen, kGen, kGen, kGen),
MakeEntry(114, "wait4", kHex, kHex, kHex, kHex),
MakeEntry(115, "swapoff", kHex, kHex, kHex, kHex),
MakeEntry(116, "sysinfo", kGen, kGen, kGen, kGen),
MakeEntry(118, "fsync", kGen, kGen, kGen, kGen),
MakeEntry(119, "sigreturn", kHex, kHex, kHex, kHex),
MakeEntry(120, "clone", kCloneFlag, kHex, kHex, kHex),
MakeEntry(121, "setdomainname", kGen, kGen, kGen, kGen),
MakeEntry(122, "uname", kGen, kGen, kGen, kGen),
MakeEntry(124, "adjtimex", kGen, kGen, kGen, kGen),
MakeEntry(125, "mprotect", kHex, kHex, kHex),
MakeEntry(126, "sigprocmask", kHex, kHex, kHex, kHex),
MakeEntry(128, "init_module", kGen, kGen, kGen, kGen),
MakeEntry(129, "delete_module", kGen, kGen, kGen, kGen),
MakeEntry(131, "quotactl", kHex, kHex, kHex, kHex),
MakeEntry(132, "getpgid", kGen, kGen, kGen, kGen),
MakeEntry(133, "fchdir", kGen, kGen, kGen, kGen),
MakeEntry(134, "bdflush", kHex, kHex, kHex, kHex),
MakeEntry(135, "sysfs", kGen, kGen, kGen, kGen),
MakeEntry(136, "personality", kGen, kGen, kGen, kGen),
MakeEntry(138, "setfsuid", kGen, kGen, kGen, kGen),
MakeEntry(139, "setfsgid", kGen, kGen, kGen, kGen),
MakeEntry(140, "_llseek", kHex, kHex, kHex, kHex),
MakeEntry(141, "getdents", kGen, kGen, kGen, kGen),
MakeEntry(142, "_newselect", kHex, kHex, kHex, kHex),
MakeEntry(143, "flock", kGen, kGen, kGen, kGen),
MakeEntry(144, "msync", kGen, kGen, kGen, kGen),
MakeEntry(145, "readv", kGen, kGen, kGen, kGen),
MakeEntry(146, "writev", kGen, kGen, kGen, kGen),
MakeEntry(147, "getsid", kGen, kGen, kGen, kGen),
MakeEntry(148, "fdatasync", kGen, kGen, kGen, kGen),
MakeEntry(149, "_sysctl", kGen, kGen, kGen, kGen),
MakeEntry(150, "mlock", kGen, kGen, kGen, kGen),
MakeEntry(151, "munlock", kGen, kGen, kGen, kGen),
MakeEntry(152, "mlockall", kGen, kGen, kGen, kGen),
MakeEntry(153, "munlockall", kGen, kGen, kGen, kGen),
MakeEntry(154, "sched_setparam", kGen, kGen, kGen, kGen),
MakeEntry(155, "sched_getparam", kGen, kGen, kGen, kGen),
MakeEntry(156, "sched_setscheduler", kGen, kGen, kGen, kGen),
MakeEntry(157, "sched_getscheduler", kGen, kGen, kGen, kGen),
MakeEntry(158, "sched_yield", kGen, kGen, kGen, kGen),
MakeEntry(159, "sched_get_priority_max", kGen, kGen, kGen, kGen),
MakeEntry(160, "sched_get_priority_min", kGen, kGen, kGen, kGen),
MakeEntry(161, "sched_rr_get_interval", kGen, kGen, kGen, kGen),
MakeEntry(162, "nanosleep", kHex, kHex),
MakeEntry(163, "mremap", kGen, kGen, kGen, kGen),
MakeEntry(164, "setresuid", kGen, kGen, kGen, kGen),
MakeEntry(165, "getresuid", kGen, kGen, kGen, kGen),
MakeEntry(168, "poll", kGen, kGen, kGen, kGen),
MakeEntry(169, "nfsservctl", kGen, kGen, kGen, kGen),
MakeEntry(170, "setresgid", kGen, kGen, kGen, kGen),
MakeEntry(171, "getresgid", kGen, kGen, kGen, kGen),
MakeEntry(172, "prctl", kHex, kHex, kHex, kHex),
MakeEntry(173, "rt_sigreturn", kGen, kGen, kGen, kGen),
MakeEntry(174, "rt_sigaction", kHex, kHex, kHex, kHex),
MakeEntry(175, "rt_sigprocmask", kGen, kGen, kGen, kGen),
MakeEntry(176, "rt_sigpending", kGen, kGen, kGen, kGen),
MakeEntry(177, "rt_sigtimedwait", kGen, kGen, kGen, kGen),
MakeEntry(178, "rt_sigqueueinfo", kGen, kGen, kGen, kGen),
MakeEntry(179, "rt_sigsuspend", kGen, kGen, kGen, kGen),
MakeEntry(180, "pread64", kGen, kGen, kGen, kGen),
MakeEntry(181, "pwrite64", kGen, kGen, kGen, kGen),
MakeEntry(182, "chown", kHex, kHex, kHex, kHex),
MakeEntry(183, "getcwd", kGen, kGen, kGen, kGen),
MakeEntry(184, "capget", kGen, kGen, kGen, kGen),
MakeEntry(185, "capset", kGen, kGen, kGen, kGen),
MakeEntry(186, "sigaltstack", kGen, kGen, kGen, kGen),
MakeEntry(187, "sendfile", kGen, kGen, kGen, kGen),
MakeEntry(190, "vfork", kGen, kGen, kGen, kGen),
MakeEntry(191, "ugetrlimit", kHex, kHex, kHex, kHex),
MakeEntry(192, "mmap2", kHex, kHex, kHex, kHex),
MakeEntry(193, "truncate64", kHex, kHex, kHex, kHex),
MakeEntry(194, "ftruncate64", kHex, kHex, kHex, kHex),
MakeEntry(195, "stat64", kHex, kHex, kHex, kHex),
MakeEntry(196, "lstat64", kHex, kHex, kHex, kHex),
MakeEntry(197, "fstat64", kHex, kHex, kHex, kHex),
MakeEntry(198, "lchown32", kHex, kHex, kHex, kHex),
MakeEntry(199, "getuid32", kHex, kHex, kHex, kHex),
MakeEntry(200, "getgid32", kHex, kHex, kHex, kHex),
MakeEntry(201, "geteuid32", kHex, kHex, kHex, kHex),
MakeEntry(202, "getegid32", kHex, kHex, kHex, kHex),
MakeEntry(203, "setreuid32", kHex, kHex, kHex, kHex),
MakeEntry(204, "setregid32", kHex, kHex, kHex, kHex),
MakeEntry(205, "getgroups32", kHex, kHex, kHex, kHex),
MakeEntry(206, "setgroups32", kHex, kHex, kHex, kHex),
MakeEntry(207, "fchown32", kHex, kHex, kHex, kHex),
MakeEntry(208, "setresuid32", kHex, kHex, kHex, kHex),
MakeEntry(209, "getresuid32", kHex, kHex, kHex, kHex),
MakeEntry(210, "setresgid32", kHex, kHex, kHex, kHex),
MakeEntry(211, "getresgid32", kHex, kHex, kHex, kHex),
MakeEntry(212, "chown32", kHex, kHex, kHex, kHex),
MakeEntry(213, "setuid32", kHex, kHex, kHex, kHex),
MakeEntry(214, "setgid32", kHex, kHex, kHex, kHex),
MakeEntry(215, "setfsuid32", kHex, kHex, kHex, kHex),
MakeEntry(216, "setfsgid32", kHex, kHex, kHex, kHex),
MakeEntry(217, "getdents64", kGen, kGen, kGen, kGen),
MakeEntry(218, "pivot_root", kHex, kHex, kHex, kHex),
MakeEntry(219, "mincore", kGen, kGen, kGen, kGen),
MakeEntry(220, "madvise", kGen, kGen, kGen, kGen),
MakeEntry(221, "fcntl64", kHex, kHex, kHex, kHex),
MakeEntry(224, "gettid", kGen, kGen, kGen, kGen),
MakeEntry(225, "readahead", kGen, kGen, kGen, kGen),
MakeEntry(226, "setxattr", kHex, kHex, kHex, kHex),
MakeEntry(227, "lsetxattr", kHex, kHex, kHex, kHex),
MakeEntry(228, "fsetxattr", kGen, kGen, kGen, kGen),
MakeEntry(229, "getxattr", kHex, kHex, kHex, kHex),
MakeEntry(230, "lgetxattr", kHex, kHex, kHex, kHex),
MakeEntry(231, "fgetxattr", kGen, kGen, kGen, kGen),
MakeEntry(232, "listxattr", kHex, kHex, kHex, kHex),
MakeEntry(233, "llistxattr", kHex, kHex, kHex, kHex),
MakeEntry(234, "flistxattr", kGen, kGen, kGen, kGen),
MakeEntry(235, "removexattr", kHex, kHex, kHex, kHex),
MakeEntry(236, "lremovexattr", kGen, kGen, kGen, kGen),
MakeEntry(237, "fremovexattr", kGen, kGen, kGen, kGen),
MakeEntry(238, "tkill", kHex, kHex, kHex, kHex),
MakeEntry(239, "sendfile64", kHex, kHex, kHex, kHex),
MakeEntry(240, "futex", kGen, kGen, kGen, kGen),
MakeEntry(241, "sched_setaffinity", kGen, kGen, kGen, kGen),
MakeEntry(242, "sched_getaffinity", kGen, kGen, kGen, kGen),
MakeEntry(243, "io_setup", kGen, kGen, kGen, kGen),
MakeEntry(244, "io_destroy", kGen, kGen, kGen, kGen),
MakeEntry(245, "io_getevents", kGen, kGen, kGen, kGen),
MakeEntry(246, "io_submit", kGen, kGen, kGen, kGen),
MakeEntry(247, "io_cancel", kGen, kGen, kGen, kGen),
MakeEntry(248, "exit_group", kHex, kHex, kHex, kHex),
MakeEntry(249, "lookup_dcookie", kGen, kGen, kGen, kGen),
MakeEntry(250, "epoll_create", kGen, kGen, kGen, kGen),
MakeEntry(251, "epoll_ctl", kGen, kGen, kGen, kGen),
MakeEntry(252, "epoll_wait", kGen, kGen, kGen, kGen),
MakeEntry(253, "remap_file_pages", kGen, kGen, kGen, kGen),
MakeEntry(256, "set_tid_address", kHex),
MakeEntry(257, "timer_create", kGen, kGen, kGen, kGen),
MakeEntry(258, "timer_settime", kGen, kGen, kGen, kGen),
MakeEntry(259, "timer_gettime", kGen, kGen, kGen, kGen),
MakeEntry(260, "timer_getoverrun", kGen, kGen, kGen, kGen),
MakeEntry(261, "timer_delete", kGen, kGen, kGen, kGen),
MakeEntry(262, "clock_settime", kGen, kGen, kGen, kGen),
MakeEntry(263, "clock_gettime", kGen, kGen, kGen, kGen),
MakeEntry(264, "clock_getres", kGen, kGen, kGen, kGen),
MakeEntry(265, "clock_nanosleep", kGen, kGen, kGen, kGen),
MakeEntry(266, "statfs64", kHex, kHex, kHex, kHex),
MakeEntry(267, "fstatfs64", kHex, kHex, kHex, kHex),
MakeEntry(268, "tgkill", kHex, kHex, kHex, kHex),
MakeEntry(269, "utimes", kGen, kGen, kGen, kGen),
MakeEntry(271, "pciconfig_iobase", kHex, kHex, kHex, kHex),
MakeEntry(272, "pciconfig_read", kHex, kHex, kHex, kHex),
MakeEntry(273, "pciconfig_write", kHex, kHex, kHex, kHex),
MakeEntry(274, "mq_open", kGen, kGen, kGen, kGen),
MakeEntry(275, "mq_unlink", kGen, kGen, kGen, kGen),
MakeEntry(276, "mq_timedsend", kGen, kGen, kGen, kGen),
MakeEntry(277, "mq_timedreceive", kGen, kGen, kGen, kGen),
MakeEntry(278, "mq_notify", kGen, kGen, kGen, kGen),
MakeEntry(279, "mq_getsetattr", kGen, kGen, kGen, kGen),
MakeEntry(280, "waitid", kGen, kGen, kGen, kGen),
MakeEntry(281, "socket", kAddressFamily, kInt, kInt),
MakeEntry(282, "bind", kGen, kGen, kGen, kGen),
MakeEntry(283, "connect", kInt, kSockaddr, kInt),
MakeEntry(284, "listen", kGen, kGen, kGen, kGen),
MakeEntry(285, "accept", kGen, kGen, kGen, kGen),
MakeEntry(286, "getsockname", kGen, kGen, kGen, kGen),
MakeEntry(287, "getpeername", kGen, kGen, kGen, kGen),
MakeEntry(288, "socketpair", kGen, kGen, kGen, kGen),
MakeEntry(289, "send", kHex, kHex, kHex, kHex),
MakeEntry(290, "sendto", kInt, kGen, kInt, kHex),
MakeEntry(291, "recv", kHex, kHex, kHex, kHex),
MakeEntry(292, "recvfrom", kGen, kGen, kGen, kGen),
MakeEntry(293, "shutdown", kGen, kGen, kGen, kGen),
MakeEntry(294, "setsockopt", kGen, kGen, kGen, kGen),
MakeEntry(295, "getsockopt", kGen, kGen, kGen, kGen),
MakeEntry(296, "sendmsg", kInt, kSockmsghdr, kHex),
MakeEntry(297, "recvmsg", kGen, kGen, kGen, kGen),
MakeEntry(298, "semop", UnknownArguments()),
MakeEntry(299, "semget", UnknownArguments()),
MakeEntry(300, "semctl", UnknownArguments()),
MakeEntry(301, "msgsnd", UnknownArguments()),
MakeEntry(302, "msgrcv", UnknownArguments()),
MakeEntry(303, "msgget", UnknownArguments()),
MakeEntry(304, "msgctl", UnknownArguments()),
MakeEntry(305, "shmat", UnknownArguments()),
MakeEntry(306, "shmdt", UnknownArguments()),
MakeEntry(307, "shmget", UnknownArguments()),
MakeEntry(308, "shmctl", UnknownArguments()),
MakeEntry(309, "add_key", kGen, kGen, kGen, kGen),
MakeEntry(310, "request_key", kGen, kGen, kGen, kGen),
MakeEntry(311, "keyctl", kGen, kGen, kGen, kGen),
MakeEntry(312, "semtimedop", UnknownArguments()),
MakeEntry(313, "vserver", kHex, kHex, kHex, kHex),
MakeEntry(314, "ioprio_set", kGen, kGen, kGen, kGen),
MakeEntry(315, "ioprio_get", kGen, kGen, kGen, kGen),
MakeEntry(316, "inotify_init", kGen, kGen, kGen, kGen),
MakeEntry(317, "inotify_add_watch", kGen, kGen, kGen, kGen),
MakeEntry(318, "inotify_rm_watch", kGen, kGen, kGen, kGen),
MakeEntry(319, "mbind", kGen, kGen, kGen, kGen),
MakeEntry(320, "get_mempolicy", kGen, kGen, kGen, kGen),
MakeEntry(321, "set_mempolicy", kGen, kGen, kGen, kGen),
MakeEntry(322, "openat", kGen, kPath, kOct, kHex),
MakeEntry(323, "mkdirat", kGen, kPath),
MakeEntry(324, "mknodat", kGen, kPath),
MakeEntry(325, "fchownat", kGen, kPath),
MakeEntry(326, "futimesat", kGen, kPath),
MakeEntry(327, "fstatat64", kHex, kHex, kHex, kHex),
MakeEntry(328, "unlinkat", kGen, kPath),
MakeEntry(329, "renameat", kGen, kPath, kGen, kPath),
MakeEntry(330, "linkat", kGen, kPath, kGen, kPath),
MakeEntry(331, "symlinkat", kPath, kGen, kPath),
MakeEntry(332, "readlinkat", kGen, kPath),
MakeEntry(333, "fchmodat", kGen, kPath),
MakeEntry(334, "faccessat", kGen, kPath),
MakeEntry(335, "pselect6", kGen, kGen, kGen, kGen),
MakeEntry(336, "ppoll", kGen, kGen, kGen, kGen),
MakeEntry(337, "unshare", kGen, kGen, kGen, kGen),
MakeEntry(338, "set_robust_list", kGen, kGen),
MakeEntry(339, "get_robust_list", kGen, kGen, kGen, kGen),
MakeEntry(340, "splice", kGen, kGen, kGen, kGen),
MakeEntry(342, "tee", kGen, kGen, kGen, kGen),
MakeEntry(343, "vmsplice", kGen, kGen, kGen, kGen),
MakeEntry(344, "move_pages", kGen, kGen, kGen, kGen),
MakeEntry(345, "getcpu", kHex, kHex, kHex),
MakeEntry(346, "epoll_pwait", kGen, kGen, kGen, kGen),
MakeEntry(347, "kexec_load", kGen, kGen, kGen, kGen),
MakeEntry(348, "utimensat", kGen, kGen, kGen, kGen),
MakeEntry(349, "signalfd", kGen, kGen, kGen, kGen),
MakeEntry(350, "timerfd_create", kGen, kGen, kGen, kGen),
MakeEntry(351, "eventfd", kGen, kGen, kGen, kGen),
MakeEntry(352, "fallocate", kGen, kGen, kGen, kGen),
MakeEntry(353, "timerfd_settime", kGen, kGen, kGen, kGen),
MakeEntry(354, "timerfd_gettime", kGen, kGen, kGen, kGen),
MakeEntry(355, "signalfd4", kGen, kGen, kGen, kGen),
MakeEntry(356, "eventfd2", kGen, kGen, kGen, kGen),
MakeEntry(357, "epoll_create1", kGen, kGen, kGen, kGen),
MakeEntry(358, "dup3", kGen, kGen, kGen),
MakeEntry(359, "pipe2", kGen, kGen, kGen, kGen),
MakeEntry(360, "inotify_init1", kGen, kGen, kGen, kGen),
MakeEntry(361, "preadv", kGen, kGen, kGen, kGen),
MakeEntry(362, "pwritev", kGen, kGen, kGen, kGen),
MakeEntry(363, "rt_tgsigqueueinfo", kGen, kGen, kGen, kGen),
MakeEntry(364, "perf_event_open", kGen, kGen, kGen, kGen),
MakeEntry(365, "recvmmsg", kHex, kHex, kHex, kHex),
MakeEntry(366, "accept4", kGen, kGen, kGen, kGen),
MakeEntry(367, "fanotify_init", kHex, kHex, kHex, kHex),
MakeEntry(368, "fanotify_mark", kHex, kHex, kHex, kHex),
MakeEntry(369, "prlimit64", kHex, kHex, kHex, kHex),
MakeEntry(370, "name_to_handle_at", kHex, kHex, kHex, kHex),
MakeEntry(371, "open_by_handle_at", kHex, kHex, kHex, kHex),
MakeEntry(372, "clock_adjtime", kHex, kHex, kHex, kHex),
MakeEntry(373, "syncfs", kHex, kHex, kHex, kHex),
MakeEntry(374, "sendmmsg", kHex, kHex, kHex, kHex),
MakeEntry(375, "setns", kHex, kHex, kHex, kHex),
MakeEntry(376, "process_vm_readv", kHex, kHex, kHex, kHex),
MakeEntry(377, "process_vm_writev", kHex, kHex, kHex, kHex),
MakeEntry(378, "kcmp", kHex, kHex, kHex, kHex),
MakeEntry(379, "finit_module", kHex, kHex, kHex, kHex),
MakeEntry(380, "sched_setattr", kGen, kGen, kGen, kGen),
MakeEntry(381, "sched_getattr", kGen, kGen, kGen, kGen),
MakeEntry(382, "renameat2", kGen, kPath, kGen, kPath),
MakeEntry(383, "seccomp", kGen, kGen, kGen, kGen),
MakeEntry(384, "getrandom", kGen, kGen, kGen, kGen),
MakeEntry(385, "memfd_create", kGen, kGen, kGen, kGen),
MakeEntry(386, "bpf", kHex, kHex, kHex, kHex),
MakeEntry(387, "execveat", kHex, kHex, kHex, kHex),
MakeEntry(388, "userfaultfd", kHex),
MakeEntry(389, "membarrier", kHex, kHex),
MakeEntry(390, "mlock2", kHex, kHex, kHex, kHex),
MakeEntry(391, "copy_file_range", kHex, kHex, kHex, kHex),
MakeEntry(392, "preadv2", kHex, kHex, kHex, kHex),
MakeEntry(393, "pwritev2", kHex, kHex, kHex, kHex),
MakeEntry(400, "migrate_pages", kGen, kGen, kGen, kGen),
MakeEntry(401, "kexec_file_load", kGen, kGen, kGen, kGen),
MakeEntry(0xf0001, "ARM_breakpoint", kHex, kHex, kHex, kHex),
MakeEntry(0xf0002, "ARM_cacheflush", kHex, kHex, kHex, kHex),
MakeEntry(0xf0003, "ARM_usr26", kHex, kHex, kHex, kHex),
MakeEntry(0xf0004, "ARM_usr32", kHex, kHex, kHex, kHex),
MakeEntry(0xf0005, "ARM_set_tls", kHex, kHex, kHex, kHex),
// clang-format on
};
static_assert(IsSorted(kSyscallDataArm32, SyscallTable::Entry::BySyscallNr),
"Syscalls should be sorted");
} // namespace
SyscallTable SyscallTable::get(sapi::cpu::Architecture arch) {
switch (arch) {
case sapi::cpu::kX8664:
return SyscallTable(kSyscallDataX8664);
case sapi::cpu::kX86:
return SyscallTable(kSyscallDataX8632);
case sapi::cpu::kPPC64LE:
return SyscallTable(kSyscallDataPPC64LE);
case sapi::cpu::kArm64:
return SyscallTable(kSyscallDataArm64);
case sapi::cpu::kArm:
return SyscallTable(kSyscallDataArm32);
default:
return SyscallTable();
}
}
} // namespace sandbox2
| 56.291994
| 80
| 0.652844
|
oshogbo
|
4920e34b4bc7e375aef545fb49136ef9e39dd7f1
| 34,971
|
cpp
|
C++
|
src/pvrt/PVRTMatrixF.cpp
|
aunali1/sauerbraten-ios
|
247de70e6889d424b041ce08627aa446caaef46c
|
[
"Cube",
"Zlib"
] | 1
|
2019-10-25T05:46:42.000Z
|
2019-10-25T05:46:42.000Z
|
src/pvrt/PVRTMatrixF.cpp
|
aunali1/sauerbraten-ios
|
247de70e6889d424b041ce08627aa446caaef46c
|
[
"Cube",
"Zlib"
] | 1
|
2015-05-24T01:30:20.000Z
|
2015-05-24T01:30:20.000Z
|
src/pvrt/PVRTMatrixF.cpp
|
aunali1/sauerbraten-ios
|
247de70e6889d424b041ce08627aa446caaef46c
|
[
"Cube",
"Zlib"
] | null | null | null |
/******************************************************************************
@File PVRTMatrixF.cpp
@Title
@Copyright Copyright (C) 1999 - 2008 by Imagination Technologies Limited.
@Platform ANSI compatible
@Description Set of mathematical functions involving matrices, vectors and
quaternions. The general matrix format used is directly compatible
with, for example, both DirectX and OpenGL. For the reasons why,
read this:
http://research.microsoft.com/~hollasch/cgindex/math/matrix/column-vec.html
******************************************************************************/
#include "PVRTGlobal.h"
//#include "PVRTContext.h"
#include <math.h>
#include <string.h>
#include "PVRTFixedPoint.h" // Only needed for trig function float lookups
#include "PVRTMatrix.h"
/****************************************************************************
** Constants
****************************************************************************/
static const PVRTMATRIXf c_mIdentity = {
{
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1
}
};
/****************************************************************************
** Functions
****************************************************************************/
/*!***************************************************************************
@Function PVRTMatrixIdentityF
@Output mOut Set to identity
@Description Reset matrix to identity matrix.
*****************************************************************************/
void PVRTMatrixIdentityF(PVRTMATRIXf &mOut)
{
mOut.f[ 0]=1.0f; mOut.f[ 4]=0.0f; mOut.f[ 8]=0.0f; mOut.f[12]=0.0f;
mOut.f[ 1]=0.0f; mOut.f[ 5]=1.0f; mOut.f[ 9]=0.0f; mOut.f[13]=0.0f;
mOut.f[ 2]=0.0f; mOut.f[ 6]=0.0f; mOut.f[10]=1.0f; mOut.f[14]=0.0f;
mOut.f[ 3]=0.0f; mOut.f[ 7]=0.0f; mOut.f[11]=0.0f; mOut.f[15]=1.0f;
}
/*!***************************************************************************
@Function PVRTMatrixMultiplyF
@Output mOut Result of mA x mB
@Input mA First operand
@Input mB Second operand
@Description Multiply mA by mB and assign the result to mOut
(mOut = p1 * p2). A copy of the result matrix is done in
the function because mOut can be a parameter mA or mB.
*****************************************************************************/
void PVRTMatrixMultiplyF(
PVRTMATRIXf &mOut,
const PVRTMATRIXf &mA,
const PVRTMATRIXf &mB)
{
PVRTMATRIXf mRet;
/* Perform calculation on a dummy matrix (mRet) */
mRet.f[ 0] = mA.f[ 0]*mB.f[ 0] + mA.f[ 1]*mB.f[ 4] + mA.f[ 2]*mB.f[ 8] + mA.f[ 3]*mB.f[12];
mRet.f[ 1] = mA.f[ 0]*mB.f[ 1] + mA.f[ 1]*mB.f[ 5] + mA.f[ 2]*mB.f[ 9] + mA.f[ 3]*mB.f[13];
mRet.f[ 2] = mA.f[ 0]*mB.f[ 2] + mA.f[ 1]*mB.f[ 6] + mA.f[ 2]*mB.f[10] + mA.f[ 3]*mB.f[14];
mRet.f[ 3] = mA.f[ 0]*mB.f[ 3] + mA.f[ 1]*mB.f[ 7] + mA.f[ 2]*mB.f[11] + mA.f[ 3]*mB.f[15];
mRet.f[ 4] = mA.f[ 4]*mB.f[ 0] + mA.f[ 5]*mB.f[ 4] + mA.f[ 6]*mB.f[ 8] + mA.f[ 7]*mB.f[12];
mRet.f[ 5] = mA.f[ 4]*mB.f[ 1] + mA.f[ 5]*mB.f[ 5] + mA.f[ 6]*mB.f[ 9] + mA.f[ 7]*mB.f[13];
mRet.f[ 6] = mA.f[ 4]*mB.f[ 2] + mA.f[ 5]*mB.f[ 6] + mA.f[ 6]*mB.f[10] + mA.f[ 7]*mB.f[14];
mRet.f[ 7] = mA.f[ 4]*mB.f[ 3] + mA.f[ 5]*mB.f[ 7] + mA.f[ 6]*mB.f[11] + mA.f[ 7]*mB.f[15];
mRet.f[ 8] = mA.f[ 8]*mB.f[ 0] + mA.f[ 9]*mB.f[ 4] + mA.f[10]*mB.f[ 8] + mA.f[11]*mB.f[12];
mRet.f[ 9] = mA.f[ 8]*mB.f[ 1] + mA.f[ 9]*mB.f[ 5] + mA.f[10]*mB.f[ 9] + mA.f[11]*mB.f[13];
mRet.f[10] = mA.f[ 8]*mB.f[ 2] + mA.f[ 9]*mB.f[ 6] + mA.f[10]*mB.f[10] + mA.f[11]*mB.f[14];
mRet.f[11] = mA.f[ 8]*mB.f[ 3] + mA.f[ 9]*mB.f[ 7] + mA.f[10]*mB.f[11] + mA.f[11]*mB.f[15];
mRet.f[12] = mA.f[12]*mB.f[ 0] + mA.f[13]*mB.f[ 4] + mA.f[14]*mB.f[ 8] + mA.f[15]*mB.f[12];
mRet.f[13] = mA.f[12]*mB.f[ 1] + mA.f[13]*mB.f[ 5] + mA.f[14]*mB.f[ 9] + mA.f[15]*mB.f[13];
mRet.f[14] = mA.f[12]*mB.f[ 2] + mA.f[13]*mB.f[ 6] + mA.f[14]*mB.f[10] + mA.f[15]*mB.f[14];
mRet.f[15] = mA.f[12]*mB.f[ 3] + mA.f[13]*mB.f[ 7] + mA.f[14]*mB.f[11] + mA.f[15]*mB.f[15];
/* Copy result in pResultMatrix */
mOut = mRet;
}
/*!***************************************************************************
@Function Name PVRTMatrixTranslationF
@Output mOut Translation matrix
@Input fX X component of the translation
@Input fY Y component of the translation
@Input fZ Z component of the translation
@Description Build a transaltion matrix mOut using fX, fY and fZ.
*****************************************************************************/
void PVRTMatrixTranslationF(
PVRTMATRIXf &mOut,
const float fX,
const float fY,
const float fZ)
{
mOut.f[ 0]=1.0f; mOut.f[ 4]=0.0f; mOut.f[ 8]=0.0f; mOut.f[12]=fX;
mOut.f[ 1]=0.0f; mOut.f[ 5]=1.0f; mOut.f[ 9]=0.0f; mOut.f[13]=fY;
mOut.f[ 2]=0.0f; mOut.f[ 6]=0.0f; mOut.f[10]=1.0f; mOut.f[14]=fZ;
mOut.f[ 3]=0.0f; mOut.f[ 7]=0.0f; mOut.f[11]=0.0f; mOut.f[15]=1.0f;
}
/*!***************************************************************************
@Function Name PVRTMatrixScalingF
@Output mOut Scale matrix
@Input fX X component of the scaling
@Input fY Y component of the scaling
@Input fZ Z component of the scaling
@Description Build a scale matrix mOut using fX, fY and fZ.
*****************************************************************************/
void PVRTMatrixScalingF(
PVRTMATRIXf &mOut,
const float fX,
const float fY,
const float fZ)
{
mOut.f[ 0]=fX; mOut.f[ 4]=0.0f; mOut.f[ 8]=0.0f; mOut.f[12]=0.0f;
mOut.f[ 1]=0.0f; mOut.f[ 5]=fY; mOut.f[ 9]=0.0f; mOut.f[13]=0.0f;
mOut.f[ 2]=0.0f; mOut.f[ 6]=0.0f; mOut.f[10]=fZ; mOut.f[14]=0.0f;
mOut.f[ 3]=0.0f; mOut.f[ 7]=0.0f; mOut.f[11]=0.0f; mOut.f[15]=1.0f;
}
/*!***************************************************************************
@Function Name PVRTMatrixRotationXF
@Output mOut Rotation matrix
@Input fAngle Angle of the rotation
@Description Create an X rotation matrix mOut.
*****************************************************************************/
void PVRTMatrixRotationXF(
PVRTMATRIXf &mOut,
const float fAngle)
{
float fCosine, fSine;
/* Precompute cos and sin */
#if defined(BUILD_DX9) || defined(BUILD_D3DM)
fCosine = (float)PVRTFCOS(-fAngle);
fSine = (float)PVRTFSIN(-fAngle);
#else
fCosine = (float)PVRTFCOS(fAngle);
fSine = (float)PVRTFSIN(fAngle);
#endif
/* Create the trigonometric matrix corresponding to X Rotation */
mOut.f[ 0]=1.0f; mOut.f[ 4]=0.0f; mOut.f[ 8]=0.0f; mOut.f[12]=0.0f;
mOut.f[ 1]=0.0f; mOut.f[ 5]=fCosine; mOut.f[ 9]=fSine; mOut.f[13]=0.0f;
mOut.f[ 2]=0.0f; mOut.f[ 6]=-fSine; mOut.f[10]=fCosine; mOut.f[14]=0.0f;
mOut.f[ 3]=0.0f; mOut.f[ 7]=0.0f; mOut.f[11]=0.0f; mOut.f[15]=1.0f;
}
/*!***************************************************************************
@Function Name PVRTMatrixRotationYF
@Output mOut Rotation matrix
@Input fAngle Angle of the rotation
@Description Create an Y rotation matrix mOut.
*****************************************************************************/
void PVRTMatrixRotationYF(
PVRTMATRIXf &mOut,
const float fAngle)
{
float fCosine, fSine;
/* Precompute cos and sin */
#if defined(BUILD_DX9) || defined(BUILD_D3DM)
fCosine = (float)PVRTFCOS(-fAngle);
fSine = (float)PVRTFSIN(-fAngle);
#else
fCosine = (float)PVRTFCOS(fAngle);
fSine = (float)PVRTFSIN(fAngle);
#endif
/* Create the trigonometric matrix corresponding to Y Rotation */
mOut.f[ 0]=fCosine; mOut.f[ 4]=0.0f; mOut.f[ 8]=-fSine; mOut.f[12]=0.0f;
mOut.f[ 1]=0.0f; mOut.f[ 5]=1.0f; mOut.f[ 9]=0.0f; mOut.f[13]=0.0f;
mOut.f[ 2]=fSine; mOut.f[ 6]=0.0f; mOut.f[10]=fCosine; mOut.f[14]=0.0f;
mOut.f[ 3]=0.0f; mOut.f[ 7]=0.0f; mOut.f[11]=0.0f; mOut.f[15]=1.0f;
}
/*!***************************************************************************
@Function Name PVRTMatrixRotationZF
@Output mOut Rotation matrix
@Input fAngle Angle of the rotation
@Description Create an Z rotation matrix mOut.
*****************************************************************************/
void PVRTMatrixRotationZF(
PVRTMATRIXf &mOut,
const float fAngle)
{
float fCosine, fSine;
/* Precompute cos and sin */
#if defined(BUILD_DX9) || defined(BUILD_D3DM)
fCosine = (float)PVRTFCOS(-fAngle);
fSine = (float)PVRTFSIN(-fAngle);
#else
fCosine = (float)PVRTFCOS(fAngle);
fSine = (float)PVRTFSIN(fAngle);
#endif
/* Create the trigonometric matrix corresponding to Z Rotation */
mOut.f[ 0]=fCosine; mOut.f[ 4]=fSine; mOut.f[ 8]=0.0f; mOut.f[12]=0.0f;
mOut.f[ 1]=-fSine; mOut.f[ 5]=fCosine; mOut.f[ 9]=0.0f; mOut.f[13]=0.0f;
mOut.f[ 2]=0.0f; mOut.f[ 6]=0.0f; mOut.f[10]=1.0f; mOut.f[14]=0.0f;
mOut.f[ 3]=0.0f; mOut.f[ 7]=0.0f; mOut.f[11]=0.0f; mOut.f[15]=1.0f;
}
/*!***************************************************************************
@Function Name PVRTMatrixTransposeF
@Output mOut Transposed matrix
@Input mIn Original matrix
@Description Compute the transpose matrix of mIn.
*****************************************************************************/
void PVRTMatrixTransposeF(
PVRTMATRIXf &mOut,
const PVRTMATRIXf &mIn)
{
PVRTMATRIXf mTmp;
mTmp.f[ 0]=mIn.f[ 0]; mTmp.f[ 4]=mIn.f[ 1]; mTmp.f[ 8]=mIn.f[ 2]; mTmp.f[12]=mIn.f[ 3];
mTmp.f[ 1]=mIn.f[ 4]; mTmp.f[ 5]=mIn.f[ 5]; mTmp.f[ 9]=mIn.f[ 6]; mTmp.f[13]=mIn.f[ 7];
mTmp.f[ 2]=mIn.f[ 8]; mTmp.f[ 6]=mIn.f[ 9]; mTmp.f[10]=mIn.f[10]; mTmp.f[14]=mIn.f[11];
mTmp.f[ 3]=mIn.f[12]; mTmp.f[ 7]=mIn.f[13]; mTmp.f[11]=mIn.f[14]; mTmp.f[15]=mIn.f[15];
mOut = mTmp;
}
/*!***************************************************************************
@Function PVRTMatrixInverseF
@Output mOut Inversed matrix
@Input mIn Original matrix
@Description Compute the inverse matrix of mIn.
The matrix must be of the form :
A 0
C 1
Where A is a 3x3 matrix and C is a 1x3 matrix.
*****************************************************************************/
void PVRTMatrixInverseF(
PVRTMATRIXf &mOut,
const PVRTMATRIXf &mIn)
{
PVRTMATRIXf mDummyMatrix;
double det_1;
double pos, neg, temp;
/* Calculate the determinant of submatrix A and determine if the
the matrix is singular as limited by the double precision
floating-point data representation. */
pos = neg = 0.0;
temp = mIn.f[ 0] * mIn.f[ 5] * mIn.f[10];
if (temp >= 0.0) pos += temp; else neg += temp;
temp = mIn.f[ 4] * mIn.f[ 9] * mIn.f[ 2];
if (temp >= 0.0) pos += temp; else neg += temp;
temp = mIn.f[ 8] * mIn.f[ 1] * mIn.f[ 6];
if (temp >= 0.0) pos += temp; else neg += temp;
temp = -mIn.f[ 8] * mIn.f[ 5] * mIn.f[ 2];
if (temp >= 0.0) pos += temp; else neg += temp;
temp = -mIn.f[ 4] * mIn.f[ 1] * mIn.f[10];
if (temp >= 0.0) pos += temp; else neg += temp;
temp = -mIn.f[ 0] * mIn.f[ 9] * mIn.f[ 6];
if (temp >= 0.0) pos += temp; else neg += temp;
det_1 = pos + neg;
/* Is the submatrix A singular? */
if ((det_1 == 0.0) || (PVRTABS(det_1 / (pos - neg)) < 1.0e-15))
{
/* Matrix M has no inverse */
#ifndef BADA
_RPT0(_CRT_WARN, "Matrix has no inverse : singular matrix\n");
#endif
return;
}
else
{
/* Calculate inverse(A) = adj(A) / det(A) */
det_1 = 1.0 / det_1;
mDummyMatrix.f[ 0] = ( mIn.f[ 5] * mIn.f[10] - mIn.f[ 9] * mIn.f[ 6] ) * (float)det_1;
mDummyMatrix.f[ 1] = - ( mIn.f[ 1] * mIn.f[10] - mIn.f[ 9] * mIn.f[ 2] ) * (float)det_1;
mDummyMatrix.f[ 2] = ( mIn.f[ 1] * mIn.f[ 6] - mIn.f[ 5] * mIn.f[ 2] ) * (float)det_1;
mDummyMatrix.f[ 4] = - ( mIn.f[ 4] * mIn.f[10] - mIn.f[ 8] * mIn.f[ 6] ) * (float)det_1;
mDummyMatrix.f[ 5] = ( mIn.f[ 0] * mIn.f[10] - mIn.f[ 8] * mIn.f[ 2] ) * (float)det_1;
mDummyMatrix.f[ 6] = - ( mIn.f[ 0] * mIn.f[ 6] - mIn.f[ 4] * mIn.f[ 2] ) * (float)det_1;
mDummyMatrix.f[ 8] = ( mIn.f[ 4] * mIn.f[ 9] - mIn.f[ 8] * mIn.f[ 5] ) * (float)det_1;
mDummyMatrix.f[ 9] = - ( mIn.f[ 0] * mIn.f[ 9] - mIn.f[ 8] * mIn.f[ 1] ) * (float)det_1;
mDummyMatrix.f[10] = ( mIn.f[ 0] * mIn.f[ 5] - mIn.f[ 4] * mIn.f[ 1] ) * (float)det_1;
/* Calculate -C * inverse(A) */
mDummyMatrix.f[12] = - ( mIn.f[12] * mDummyMatrix.f[ 0] + mIn.f[13] * mDummyMatrix.f[ 4] + mIn.f[14] * mDummyMatrix.f[ 8] );
mDummyMatrix.f[13] = - ( mIn.f[12] * mDummyMatrix.f[ 1] + mIn.f[13] * mDummyMatrix.f[ 5] + mIn.f[14] * mDummyMatrix.f[ 9] );
mDummyMatrix.f[14] = - ( mIn.f[12] * mDummyMatrix.f[ 2] + mIn.f[13] * mDummyMatrix.f[ 6] + mIn.f[14] * mDummyMatrix.f[10] );
/* Fill in last row */
mDummyMatrix.f[ 3] = 0.0f;
mDummyMatrix.f[ 7] = 0.0f;
mDummyMatrix.f[11] = 0.0f;
mDummyMatrix.f[15] = 1.0f;
}
/* Copy contents of dummy matrix in pfMatrix */
mOut = mDummyMatrix;
}
/*!***************************************************************************
@Function PVRTMatrixInverseExF
@Output mOut Inversed matrix
@Input mIn Original matrix
@Description Compute the inverse matrix of mIn.
Uses a linear equation solver and the knowledge that M.M^-1=I.
Use this fn to calculate the inverse of matrices that
PVRTMatrixInverse() cannot.
*****************************************************************************/
void PVRTMatrixInverseExF(
PVRTMATRIXf &mOut,
const PVRTMATRIXf &mIn)
{
PVRTMATRIXf mTmp;
float *ppfRows[4];
float pfRes[4];
float pfIn[20];
int i, j;
for(i = 0; i < 4; ++i)
ppfRows[i] = &pfIn[i * 5];
/* Solve 4 sets of 4 linear equations */
for(i = 0; i < 4; ++i)
{
for(j = 0; j < 4; ++j)
{
ppfRows[j][0] = c_mIdentity.f[i + 4 * j];
memcpy(&ppfRows[j][1], &mIn.f[j * 4], 4 * sizeof(float));
}
PVRTMatrixLinearEqSolveF(pfRes, (float**)ppfRows, 4);
for(j = 0; j < 4; ++j)
{
mTmp.f[i + 4 * j] = pfRes[j];
}
}
mOut = mTmp;
}
/*!***************************************************************************
@Function PVRTMatrixLookAtLHF
@Output mOut Look-at view matrix
@Input vEye Position of the camera
@Input vAt Point the camera is looking at
@Input vUp Up direction for the camera
@Description Create a look-at view matrix.
*****************************************************************************/
void PVRTMatrixLookAtLHF(
PVRTMATRIXf &mOut,
const PVRTVECTOR3f &vEye,
const PVRTVECTOR3f &vAt,
const PVRTVECTOR3f &vUp)
{
PVRTVECTOR3f f, vUpActual, s, u;
PVRTMATRIXf t;
f.x = vEye.x - vAt.x;
f.y = vEye.y - vAt.y;
f.z = vEye.z - vAt.z;
PVRTMatrixVec3NormalizeF(f, f);
PVRTMatrixVec3NormalizeF(vUpActual, vUp);
PVRTMatrixVec3CrossProductF(s, f, vUpActual);
PVRTMatrixVec3CrossProductF(u, s, f);
mOut.f[ 0] = s.x;
mOut.f[ 1] = u.x;
mOut.f[ 2] = -f.x;
mOut.f[ 3] = 0;
mOut.f[ 4] = s.y;
mOut.f[ 5] = u.y;
mOut.f[ 6] = -f.y;
mOut.f[ 7] = 0;
mOut.f[ 8] = s.z;
mOut.f[ 9] = u.z;
mOut.f[10] = -f.z;
mOut.f[11] = 0;
mOut.f[12] = 0;
mOut.f[13] = 0;
mOut.f[14] = 0;
mOut.f[15] = 1;
PVRTMatrixTranslationF(t, -vEye.x, -vEye.y, -vEye.z);
PVRTMatrixMultiplyF(mOut, t, mOut);
}
/*!***************************************************************************
@Function PVRTMatrixLookAtRHF
@Output mOut Look-at view matrix
@Input vEye Position of the camera
@Input vAt Point the camera is looking at
@Input vUp Up direction for the camera
@Description Create a look-at view matrix.
*****************************************************************************/
void PVRTMatrixLookAtRHF(
PVRTMATRIXf &mOut,
const PVRTVECTOR3f &vEye,
const PVRTVECTOR3f &vAt,
const PVRTVECTOR3f &vUp)
{
PVRTVECTOR3f f, vUpActual, s, u;
PVRTMATRIXf t;
f.x = vAt.x - vEye.x;
f.y = vAt.y - vEye.y;
f.z = vAt.z - vEye.z;
PVRTMatrixVec3NormalizeF(f, f);
PVRTMatrixVec3NormalizeF(vUpActual, vUp);
PVRTMatrixVec3CrossProductF(s, f, vUpActual);
PVRTMatrixVec3CrossProductF(u, s, f);
mOut.f[ 0] = s.x;
mOut.f[ 1] = u.x;
mOut.f[ 2] = -f.x;
mOut.f[ 3] = 0;
mOut.f[ 4] = s.y;
mOut.f[ 5] = u.y;
mOut.f[ 6] = -f.y;
mOut.f[ 7] = 0;
mOut.f[ 8] = s.z;
mOut.f[ 9] = u.z;
mOut.f[10] = -f.z;
mOut.f[11] = 0;
mOut.f[12] = 0;
mOut.f[13] = 0;
mOut.f[14] = 0;
mOut.f[15] = 1;
PVRTMatrixTranslationF(t, -vEye.x, -vEye.y, -vEye.z);
PVRTMatrixMultiplyF(mOut, t, mOut);
}
/*!***************************************************************************
@Function PVRTMatrixPerspectiveFovLHF
@Output mOut Perspective matrix
@Input fFOVy Field of view
@Input fAspect Aspect ratio
@Input fNear Near clipping distance
@Input fFar Far clipping distance
@Input bRotate Should we rotate it ? (for upright screens)
@Description Create a perspective matrix.
*****************************************************************************/
void PVRTMatrixPerspectiveFovLHF(
PVRTMATRIXf &mOut,
const float fFOVy,
const float fAspect,
const float fNear,
const float fFar,
const bool bRotate)
{
float f, n, fRealAspect;
if (bRotate)
fRealAspect = 1.0f / fAspect;
else
fRealAspect = fAspect;
// cotangent(a) == 1.0f / tan(a);
f = 1.0f / (float)PVRTFTAN(fFOVy * 0.5f);
n = 1.0f / (fFar - fNear);
mOut.f[ 0] = f / fRealAspect;
mOut.f[ 1] = 0;
mOut.f[ 2] = 0;
mOut.f[ 3] = 0;
mOut.f[ 4] = 0;
mOut.f[ 5] = f;
mOut.f[ 6] = 0;
mOut.f[ 7] = 0;
mOut.f[ 8] = 0;
mOut.f[ 9] = 0;
mOut.f[10] = fFar * n;
mOut.f[11] = 1;
mOut.f[12] = 0;
mOut.f[13] = 0;
mOut.f[14] = -fFar * fNear * n;
mOut.f[15] = 0;
if (bRotate)
{
PVRTMATRIXf mRotation, mTemp = mOut;
PVRTMatrixRotationZF(mRotation, 90.0f*PVRT_PIf/180.0f);
PVRTMatrixMultiplyF(mOut, mTemp, mRotation);
}
}
/*!***************************************************************************
@Function PVRTMatrixPerspectiveFovRHF
@Output mOut Perspective matrix
@Input fFOVy Field of view
@Input fAspect Aspect ratio
@Input fNear Near clipping distance
@Input fFar Far clipping distance
@Input bRotate Should we rotate it ? (for upright screens)
@Description Create a perspective matrix.
*****************************************************************************/
void PVRTMatrixPerspectiveFovRHF(
PVRTMATRIXf &mOut,
const float fFOVy,
const float fAspect,
const float fNear,
const float fFar,
const bool bRotate)
{
float f, n, fRealAspect;
if (bRotate)
fRealAspect = 1.0f / fAspect;
else
fRealAspect = fAspect;
// cotangent(a) == 1.0f / tan(a);
f = 1.0f / (float)PVRTFTAN(fFOVy * 0.5f);
n = 1.0f / (fNear - fFar);
mOut.f[ 0] = f / fRealAspect;
mOut.f[ 1] = 0;
mOut.f[ 2] = 0;
mOut.f[ 3] = 0;
mOut.f[ 4] = 0;
mOut.f[ 5] = f;
mOut.f[ 6] = 0;
mOut.f[ 7] = 0;
mOut.f[ 8] = 0;
mOut.f[ 9] = 0;
mOut.f[10] = (fFar + fNear) * n;
mOut.f[11] = -1;
mOut.f[12] = 0;
mOut.f[13] = 0;
mOut.f[14] = (2 * fFar * fNear) * n;
mOut.f[15] = 0;
if (bRotate)
{
PVRTMATRIXf mRotation, mTemp = mOut;
PVRTMatrixRotationZF(mRotation, -90.0f*PVRT_PIf/180.0f);
PVRTMatrixMultiplyF(mOut, mTemp, mRotation);
}
}
/*!***************************************************************************
@Function PVRTMatrixOrthoLHF
@Output mOut Orthographic matrix
@Input w Width of the screen
@Input h Height of the screen
@Input zn Near clipping distance
@Input zf Far clipping distance
@Input bRotate Should we rotate it ? (for upright screens)
@Description Create an orthographic matrix.
*****************************************************************************/
void PVRTMatrixOrthoLHF(
PVRTMATRIXf &mOut,
const float w,
const float h,
const float zn,
const float zf,
const bool bRotate)
{
mOut.f[ 0] = 2 / w;
mOut.f[ 1] = 0;
mOut.f[ 2] = 0;
mOut.f[ 3] = 0;
mOut.f[ 4] = 0;
mOut.f[ 5] = 2 / h;
mOut.f[ 6] = 0;
mOut.f[ 7] = 0;
mOut.f[ 8] = 0;
mOut.f[ 9] = 0;
mOut.f[10] = 1 / (zf - zn);
mOut.f[11] = zn / (zn - zf);
mOut.f[12] = 0;
mOut.f[13] = 0;
mOut.f[14] = 0;
mOut.f[15] = 1;
if (bRotate)
{
PVRTMATRIXf mRotation, mTemp = mOut;
PVRTMatrixRotationZF(mRotation, -90.0f*PVRT_PIf/180.0f);
PVRTMatrixMultiplyF(mOut, mRotation, mTemp);
}
}
/*!***************************************************************************
@Function PVRTMatrixOrthoRHF
@Output mOut Orthographic matrix
@Input w Width of the screen
@Input h Height of the screen
@Input zn Near clipping distance
@Input zf Far clipping distance
@Input bRotate Should we rotate it ? (for upright screens)
@Description Create an orthographic matrix.
*****************************************************************************/
void PVRTMatrixOrthoRHF(
PVRTMATRIXf &mOut,
const float w,
const float h,
const float zn,
const float zf,
const bool bRotate)
{
mOut.f[ 0] = 2 / w;
mOut.f[ 1] = 0;
mOut.f[ 2] = 0;
mOut.f[ 3] = 0;
mOut.f[ 4] = 0;
mOut.f[ 5] = 2 / h;
mOut.f[ 6] = 0;
mOut.f[ 7] = 0;
mOut.f[ 8] = 0;
mOut.f[ 9] = 0;
mOut.f[10] = 1 / (zn - zf);
mOut.f[11] = zn / (zn - zf);
mOut.f[12] = 0;
mOut.f[13] = 0;
mOut.f[14] = 0;
mOut.f[15] = 1;
if (bRotate)
{
PVRTMATRIXf mRotation, mTemp = mOut;
PVRTMatrixRotationZF(mRotation, -90.0f*PVRT_PIf/180.0f);
PVRTMatrixMultiplyF(mOut, mRotation, mTemp);
}
}
/*!***************************************************************************
@Function PVRTMatrixVec3LerpF
@Output vOut Result of the interpolation
@Input v1 First vector to interpolate from
@Input v2 Second vector to interpolate form
@Input s Coefficient of interpolation
@Description This function performs the linear interpolation based on
the following formula: V1 + s(V2-V1).
*****************************************************************************/
void PVRTMatrixVec3LerpF(
PVRTVECTOR3f &vOut,
const PVRTVECTOR3f &v1,
const PVRTVECTOR3f &v2,
const float s)
{
vOut.x = v1.x + s * (v2.x - v1.x);
vOut.y = v1.y + s * (v2.y - v1.y);
vOut.z = v1.z + s * (v2.z - v1.z);
}
/*!***************************************************************************
@Function PVRTMatrixVec3DotProductF
@Input v1 First vector
@Input v2 Second vector
@Return Dot product of the two vectors.
@Description This function performs the dot product of the two
supplied vectors.
*****************************************************************************/
float PVRTMatrixVec3DotProductF(
const PVRTVECTOR3f &v1,
const PVRTVECTOR3f &v2)
{
return (v1.x*v2.x + v1.y*v2.y + v1.z*v2.z);
}
/*!***************************************************************************
@Function PVRTMatrixVec3CrossProductF
@Output vOut Cross product of the two vectors
@Input v1 First vector
@Input v2 Second vector
@Description This function performs the cross product of the two
supplied vectors.
*****************************************************************************/
void PVRTMatrixVec3CrossProductF(
PVRTVECTOR3f &vOut,
const PVRTVECTOR3f &v1,
const PVRTVECTOR3f &v2)
{
PVRTVECTOR3f result;
/* Perform calculation on a dummy VECTOR (result) */
result.x = v1.y * v2.z - v1.z * v2.y;
result.y = v1.z * v2.x - v1.x * v2.z;
result.z = v1.x * v2.y - v1.y * v2.x;
/* Copy result in pOut */
vOut = result;
}
/*!***************************************************************************
@Function PVRTMatrixVec3NormalizeF
@Output vOut Normalized vector
@Input vIn Vector to normalize
@Description Normalizes the supplied vector.
*****************************************************************************/
void PVRTMatrixVec3NormalizeF(
PVRTVECTOR3f &vOut,
const PVRTVECTOR3f &vIn)
{
float f;
double temp;
temp = (double)(vIn.x * vIn.x + vIn.y * vIn.y + vIn.z * vIn.z);
temp = 1.0 / sqrt(temp);
f = (float)temp;
vOut.x = vIn.x * f;
vOut.y = vIn.y * f;
vOut.z = vIn.z * f;
}
/*!***************************************************************************
@Function PVRTMatrixVec3LengthF
@Input vIn Vector to get the length of
@Return The length of the vector
@Description Gets the length of the supplied vector.
*****************************************************************************/
float PVRTMatrixVec3LengthF(
const PVRTVECTOR3f &vIn)
{
double temp;
temp = (double)(vIn.x * vIn.x + vIn.y * vIn.y + vIn.z * vIn.z);
return (float) sqrt(temp);
}
/*!***************************************************************************
@Function PVRTMatrixQuaternionIdentityF
@Output qOut Identity quaternion
@Description Sets the quaternion to (0, 0, 0, 1), the identity quaternion.
*****************************************************************************/
void PVRTMatrixQuaternionIdentityF(
PVRTQUATERNIONf &qOut)
{
qOut.x = 0;
qOut.y = 0;
qOut.z = 0;
qOut.w = 1;
}
/*!***************************************************************************
@Function PVRTMatrixQuaternionRotationAxisF
@Output qOut Rotation quaternion
@Input vAxis Axis to rotate around
@Input fAngle Angle to rotate
@Description Create quaternion corresponding to a rotation of fAngle
radians around submitted vector.
*****************************************************************************/
void PVRTMatrixQuaternionRotationAxisF(
PVRTQUATERNIONf &qOut,
const PVRTVECTOR3f &vAxis,
const float fAngle)
{
float fSin, fCos;
fSin = (float)PVRTFSIN(fAngle * 0.5f);
fCos = (float)PVRTFCOS(fAngle * 0.5f);
/* Create quaternion */
qOut.x = vAxis.x * fSin;
qOut.y = vAxis.y * fSin;
qOut.z = vAxis.z * fSin;
qOut.w = fCos;
/* Normalise it */
PVRTMatrixQuaternionNormalizeF(qOut);
}
/*!***************************************************************************
@Function PVRTMatrixQuaternionToAxisAngleF
@Input qIn Quaternion to transform
@Output vAxis Axis of rotation
@Output fAngle Angle of rotation
@Description Convert a quaternion to an axis and angle. Expects a unit
quaternion.
*****************************************************************************/
void PVRTMatrixQuaternionToAxisAngleF(
const PVRTQUATERNIONf &qIn,
PVRTVECTOR3f &vAxis,
float &fAngle)
{
float fCosAngle, fSinAngle;
double temp;
/* Compute some values */
fCosAngle = qIn.w;
temp = 1.0f - fCosAngle*fCosAngle;
fAngle = (float)PVRTFACOS(fCosAngle)*2.0f;
fSinAngle = (float)sqrt(temp);
/* This is to avoid a division by zero */
if ((float)fabs(fSinAngle)<0.0005f)
fSinAngle = 1.0f;
/* Get axis vector */
vAxis.x = qIn.x / fSinAngle;
vAxis.y = qIn.y / fSinAngle;
vAxis.z = qIn.z / fSinAngle;
}
/*!***************************************************************************
@Function PVRTMatrixQuaternionSlerpF
@Output qOut Result of the interpolation
@Input qA First quaternion to interpolate from
@Input qB Second quaternion to interpolate from
@Input t Coefficient of interpolation
@Description Perform a Spherical Linear intERPolation between quaternion A
and quaternion B at time t. t must be between 0.0f and 1.0f
*****************************************************************************/
void PVRTMatrixQuaternionSlerpF(
PVRTQUATERNIONf &qOut,
const PVRTQUATERNIONf &qA,
const PVRTQUATERNIONf &qB,
const float t)
{
float fCosine, fAngle, A, B;
/* Parameter checking */
if (t<0.0f || t>1.0f)
{
#ifndef BADA
_RPT0(_CRT_WARN, "PVRTMatrixQuaternionSlerp : Bad parameters\n");
#endif
qOut.x = 0;
qOut.y = 0;
qOut.z = 0;
qOut.w = 1;
return;
}
/* Find sine of Angle between Quaternion A and B (dot product between quaternion A and B) */
fCosine = qA.w*qB.w + qA.x*qB.x + qA.y*qB.y + qA.z*qB.z;
if (fCosine < 0)
{
PVRTQUATERNIONf qi;
/*
<http://www.magic-software.com/Documentation/Quaternions.pdf>
"It is important to note that the quaternions q and -q represent
the same rotation... while either quaternion will do, the
interpolation methods require choosing one over the other.
"Although q1 and -q1 represent the same rotation, the values of
Slerp(t; q0, q1) and Slerp(t; q0,-q1) are not the same. It is
customary to choose the sign... on q1 so that... the angle
between q0 and q1 is acute. This choice avoids extra
spinning caused by the interpolated rotations."
*/
qi.x = -qB.x;
qi.y = -qB.y;
qi.z = -qB.z;
qi.w = -qB.w;
PVRTMatrixQuaternionSlerpF(qOut, qA, qi, t);
return;
}
fCosine = PVRT_MIN(fCosine, 1.0f);
fAngle = (float)PVRTFACOS(fCosine);
/* Avoid a division by zero */
if (fAngle==0.0f)
{
qOut = qA;
return;
}
/* Precompute some values */
A = (float)(PVRTFSIN((1.0f-t)*fAngle) / PVRTFSIN(fAngle));
B = (float)(PVRTFSIN(t*fAngle) / PVRTFSIN(fAngle));
/* Compute resulting quaternion */
qOut.x = A * qA.x + B * qB.x;
qOut.y = A * qA.y + B * qB.y;
qOut.z = A * qA.z + B * qB.z;
qOut.w = A * qA.w + B * qB.w;
/* Normalise result */
PVRTMatrixQuaternionNormalizeF(qOut);
}
/*!***************************************************************************
@Function PVRTMatrixQuaternionNormalizeF
@Modified quat Vector to normalize
@Description Normalize quaternion.
*****************************************************************************/
void PVRTMatrixQuaternionNormalizeF(PVRTQUATERNIONf &quat)
{
float fMagnitude;
double temp;
/* Compute quaternion magnitude */
temp = quat.w*quat.w + quat.x*quat.x + quat.y*quat.y + quat.z*quat.z;
fMagnitude = (float)sqrt(temp);
/* Divide each quaternion component by this magnitude */
if (fMagnitude!=0.0f)
{
fMagnitude = 1.0f / fMagnitude;
quat.x *= fMagnitude;
quat.y *= fMagnitude;
quat.z *= fMagnitude;
quat.w *= fMagnitude;
}
}
/*!***************************************************************************
@Function PVRTMatrixRotationQuaternionF
@Output mOut Resulting rotation matrix
@Input quat Quaternion to transform
@Description Create rotation matrix from submitted quaternion.
Assuming the quaternion is of the form [X Y Z W]:
| 2 2 |
| 1 - 2Y - 2Z 2XY - 2ZW 2XZ + 2YW 0 |
| |
| 2 2 |
M = | 2XY + 2ZW 1 - 2X - 2Z 2YZ - 2XW 0 |
| |
| 2 2 |
| 2XZ - 2YW 2YZ + 2XW 1 - 2X - 2Y 0 |
| |
| 0 0 0 1 |
*****************************************************************************/
void PVRTMatrixRotationQuaternionF(
PVRTMATRIXf &mOut,
const PVRTQUATERNIONf &quat)
{
const PVRTQUATERNIONf *pQ;
#if defined(BUILD_DX9) || defined(BUILD_D3DM)
PVRTQUATERNIONf qInv;
qInv.x = -quat.x;
qInv.y = -quat.y;
qInv.z = -quat.z;
qInv.w = quat.w;
pQ = &qInv;
#else
pQ = &quat;
#endif
/* Fill matrix members */
mOut.f[0] = 1.0f - 2.0f*pQ->y*pQ->y - 2.0f*pQ->z*pQ->z;
mOut.f[1] = 2.0f*pQ->x*pQ->y - 2.0f*pQ->z*pQ->w;
mOut.f[2] = 2.0f*pQ->x*pQ->z + 2.0f*pQ->y*pQ->w;
mOut.f[3] = 0.0f;
mOut.f[4] = 2.0f*pQ->x*pQ->y + 2.0f*pQ->z*pQ->w;
mOut.f[5] = 1.0f - 2.0f*pQ->x*pQ->x - 2.0f*pQ->z*pQ->z;
mOut.f[6] = 2.0f*pQ->y*pQ->z - 2.0f*pQ->x*pQ->w;
mOut.f[7] = 0.0f;
mOut.f[8] = 2.0f*pQ->x*pQ->z - 2*pQ->y*pQ->w;
mOut.f[9] = 2.0f*pQ->y*pQ->z + 2.0f*pQ->x*pQ->w;
mOut.f[10] = 1.0f - 2.0f*pQ->x*pQ->x - 2*pQ->y*pQ->y;
mOut.f[11] = 0.0f;
mOut.f[12] = 0.0f;
mOut.f[13] = 0.0f;
mOut.f[14] = 0.0f;
mOut.f[15] = 1.0f;
}
/*!***************************************************************************
@Function PVRTMatrixQuaternionMultiplyF
@Output qOut Resulting quaternion
@Input qA First quaternion to multiply
@Input qB Second quaternion to multiply
@Description Multiply quaternion A with quaternion B and return the
result in qOut.
*****************************************************************************/
void PVRTMatrixQuaternionMultiplyF(
PVRTQUATERNIONf &qOut,
const PVRTQUATERNIONf &qA,
const PVRTQUATERNIONf &qB)
{
PVRTVECTOR3f CrossProduct;
/* Compute scalar component */
qOut.w = (qA.w*qB.w) - (qA.x*qB.x + qA.y*qB.y + qA.z*qB.z);
/* Compute cross product */
CrossProduct.x = qA.y*qB.z - qA.z*qB.y;
CrossProduct.y = qA.z*qB.x - qA.x*qB.z;
CrossProduct.z = qA.x*qB.y - qA.y*qB.x;
/* Compute result vector */
qOut.x = (qA.w * qB.x) + (qB.w * qA.x) + CrossProduct.x;
qOut.y = (qA.w * qB.y) + (qB.w * qA.y) + CrossProduct.y;
qOut.z = (qA.w * qB.z) + (qB.w * qA.z) + CrossProduct.z;
/* Normalize resulting quaternion */
PVRTMatrixQuaternionNormalizeF(qOut);
}
/*!***************************************************************************
@Function PVRTMatrixLinearEqSolveF
@Input pSrc 2D array of floats. 4 Eq linear problem is 5x4
matrix, constants in first column
@Input nCnt Number of equations to solve
@Output pRes Result
@Description Solves 'nCnt' simultaneous equations of 'nCnt' variables.
pRes should be an array large enough to contain the
results: the values of the 'nCnt' variables.
This fn recursively uses Gaussian Elimination.
*****************************************************************************/
void PVRTMatrixLinearEqSolveF(
float * const pRes,
float ** const pSrc, // 2D array of floats. 4 Eq linear problem is 5x4 matrix, constants in first column.
const int nCnt)
{
int i, j, k;
float f;
#if 0
/*
Show the matrix in debug output
*/
_RPT1(_CRT_WARN, "LinearEqSolve(%d)\n", nCnt);
for(i = 0; i < nCnt; ++i)
{
_RPT1(_CRT_WARN, "%.8f |", pSrc[i][0]);
for(j = 1; j <= nCnt; ++j)
_RPT1(_CRT_WARN, " %.8f", pSrc[i][j]);
_RPT0(_CRT_WARN, "\n");
}
#endif
if(nCnt == 1)
{
#ifndef BADA
_ASSERT(pSrc[0][1] != 0);
#endif
pRes[0] = pSrc[0][0] / pSrc[0][1];
return;
}
// Loop backwards in an attempt avoid the need to swap rows
i = nCnt;
while(i)
{
--i;
if(pSrc[i][nCnt] != 0)
{
// Row i can be used to zero the other rows; let's move it to the bottom
if(i != (nCnt-1))
{
for(j = 0; j <= nCnt; ++j)
{
// Swap the two values
f = pSrc[nCnt-1][j];
pSrc[nCnt-1][j] = pSrc[i][j];
pSrc[i][j] = f;
}
}
// Now zero the last columns of the top rows
for(j = 0; j < (nCnt-1); ++j)
{
#ifndef BADA
_ASSERT(pSrc[nCnt-1][nCnt] != 0);
#endif
f = pSrc[j][nCnt] / pSrc[nCnt-1][nCnt];
// No need to actually calculate a zero for the final column
for(k = 0; k < nCnt; ++k)
{
pSrc[j][k] -= f * pSrc[nCnt-1][k];
}
}
break;
}
}
// Solve the top-left sub matrix
PVRTMatrixLinearEqSolveF(pRes, pSrc, nCnt - 1);
// Now calc the solution for the bottom row
f = pSrc[nCnt-1][0];
for(k = 1; k < nCnt; ++k)
{
f -= pSrc[nCnt-1][k] * pRes[k-1];
}
#ifndef BADA
_ASSERT(pSrc[nCnt-1][nCnt] != 0);
#endif
f /= pSrc[nCnt-1][nCnt];
pRes[nCnt-1] = f;
#if 0
{
float fCnt;
/*
Verify that the result is correct
*/
fCnt = 0;
for(i = 1; i <= nCnt; ++i)
fCnt += pSrc[nCnt-1][i] * pRes[i-1];
_ASSERT(abs(fCnt - pSrc[nCnt-1][0]) < 1e-3);
}
#endif
}
/*****************************************************************************
End of file (PVRTMatrixF.cpp)
*****************************************************************************/
| 30.436031
| 132
| 0.528552
|
aunali1
|
49221953ee2738b15d33786523097b56f7c985b5
| 384
|
cpp
|
C++
|
fre_check.cpp
|
1432junaid/cpp
|
8faf7ac856a50937f3a563dc8d23ee8e205a489c
|
[
"MIT"
] | null | null | null |
fre_check.cpp
|
1432junaid/cpp
|
8faf7ac856a50937f3a563dc8d23ee8e205a489c
|
[
"MIT"
] | null | null | null |
fre_check.cpp
|
1432junaid/cpp
|
8faf7ac856a50937f3a563dc8d23ee8e205a489c
|
[
"MIT"
] | null | null | null |
#include<iostream>
#include<cstring>
using namespace std;
int main(){
char *city = "lucknow junction";
char *c = "lucknow";
int hash[26]= {0};
int len = strlen(city);
for(int i = 0; i<len ; i++){
if(city[i] >= 97 && city[i] <= 122)
hash[city[i] - 'a']++;
}
for(int i=0; i<26;i++){
if(hash[i]>0){
cout<<char(i+'a')<<" "<<hash[i]<<endl;
}
}
// if(len)
return 0;
}
| 17.454545
| 42
| 0.533854
|
1432junaid
|
49267adedbd3f62879ef3c4aa4e7a8c28800caa1
| 6,300
|
cpp
|
C++
|
src/libs/qlib/qdmvideoout.cpp
|
3dhater/Racer
|
d7fe4014b1efefe981528547649dc397da7fa780
|
[
"Unlicense"
] | null | null | null |
src/libs/qlib/qdmvideoout.cpp
|
3dhater/Racer
|
d7fe4014b1efefe981528547649dc397da7fa780
|
[
"Unlicense"
] | null | null | null |
src/libs/qlib/qdmvideoout.cpp
|
3dhater/Racer
|
d7fe4014b1efefe981528547649dc397da7fa780
|
[
"Unlicense"
] | 1
|
2021-01-03T16:16:47.000Z
|
2021-01-03T16:16:47.000Z
|
/*
* QDMVideoOut - definition/implementation
* 13-11-99: Support for VL65 interface
* NOTES:
* - Generated by mkclass
* BUGS:
* - Same bugs apply as for QDMVideoIn; event handling of VL was changed
* to generate events for all paths in one place. Need to demultiplex.
* (C) 01-01-98 MarketGraph/RVG
*/
#include <qlib/dmvideoout.h>
#include <qlib/dmbpool.h>
#include <qlib/app.h>
#include <qlib/debug.h>
DEBUG_ENABLE
#undef DBG_CLASS
#define DBG_CLASS "QDMVideoOut"
QDMVideoOut::QDMVideoOut()
: QDMObject()
{
QVideoServer *vs;
int x,y;
DBG_C("ctor")
vs=app->GetVideoServer();
// Nodes from video to memory
srcNode=new QVideoNode(vs,VL_SRC,VL_MEM,VL_ANY);
drnNode=new QVideoNode(vs,VL_DRN,VL_VIDEO,VL_ANY);
// Create path
pathOut=new QVideoPath(vs,VL_ANY,srcNode,drnNode);
// Setup hardware
if(!pathOut->Setup(VL_SHARE,VL_SHARE))
{ qerr("QDMVideoOut: can't setup input path");
}
// Default control values
SetTiming(VL_TIMING_625_CCIR601);
//SetPacking(VL_PACKING_YVYU_422_8);
SetPacking(VL_PACKING_ABGR_8);
//drnNode->SetControl(VL_CAP_TYPE,VL_CAPTURE_NONINTERLEAVED);
//srcNode->SetControl(VL_CAP_TYPE,VL_CAPTURE_INTERLEAVED);
SetCaptureType(VL_CAPTURE_INTERLEAVED);
SetFormat(VL_FORMAT_RGB);
//srcNode->SetControl(VL_FORMAT,VL_FORMAT_RGB);
drnNode->SetControl(VL_SYNC,VL_SYNC_INTERNAL);
//srcNode->GetXYControl(VL_SIZE,&x,&y);
//SetZoomSize(x,y);
//drnNode->SetControl(VL_ORIGIN,0,16); // ??
//drnNode->SetControl(VL_ZOOM,1,1);
//srcNode->SetControl(VL_TIMING,VL_TIMING_625_CCIR601);
//drnNode->SetControl(VL_CAP_TYPE,VL_CAPTURE_INTERLEAVED);
SetLayout(VL_LAYOUT_GRAPHICS);
// Debug
//qdbg(" video in transfer size=%d\n",pathOut->GetTransferSize());
drnNode->GetXYControl(VL_SIZE,&x,&y);
//qdbg(" video in size: %dx%d\n",x,y);
}
QDMVideoOut::~QDMVideoOut()
{
delete pathOut;
delete drnNode;
delete srcNode;
}
/*******
* POOL *
*******/
void QDMVideoOut::AddConsumerParams(QDMBPool *pool)
// Get necessary params to use this input object
{
#ifdef USE_VL_65
vlDMGetParams(app->GetVideoServer()->GetSGIServer(),
pathOut->GetSGIPath(),drnNode->GetSGINode(),
pool->GetCreateParams()->GetDMparams());
#else
vlDMPoolGetParams(app->GetVideoServer()->GetSGIServer(),
pathOut->GetSGIPath(),drnNode->GetSGINode(),
pool->GetCreateParams()->GetDMparams());
#endif
qdbg("QDMVideoOut:GetPoolParams; buffersize=%d\n",
pool->GetCreateParams()->GetInt(DM_BUFFER_SIZE));
}
void QDMVideoOut::RegisterPool(QDMBPool *pool)
{
if(vlDMPoolRegister(app->GetVideoServer()->GetSGIServer(),
pathOut->GetSGIPath(),drnNode->GetSGINode(),pool->GetDMbufferpool())<0)
qerr("QDMVideoOut: can't register pool");
}
/*******
* INFO *
*******/
int QDMVideoOut::GetFD()
{
#ifdef USE_VL_65
//return drnNode->GetFD();
return srcNode->GetFD();
#else
return pathOut->GetFD();
#endif
}
void QDMVideoOut::GetSize(int *w,int *h)
{
drnNode->GetXYControl(VL_SIZE,w,h);
}
int QDMVideoOut::GetTransferSize()
{
if(!pathOut)return 0;
return pathOut->GetTransferSize();
}
void QDMVideoOut::SetSize(int w,int h)
{
//drnNode->SetControl(VL_SIZE,w,h);
srcNode->SetControl(VL_SIZE,w,h);
}
void QDMVideoOut::SetZoomSize(int w,int h)
{
drnNode->SetControl(VL_MVP_ZOOMSIZE,w,h);
}
void QDMVideoOut::SetOffset(int x,int y)
{
drnNode->SetControl(VL_SIZE,x,y);
}
void QDMVideoOut::SetOrigin(int x,int y)
{
drnNode->SetControl(VL_ORIGIN,x,y);
}
void QDMVideoOut::SetLayout(int n)
{ srcNode->SetControl(VL_LAYOUT,n);
}
void QDMVideoOut::SetFormat(int n)
{ srcNode->SetControl(VL_FORMAT,n);
}
void QDMVideoOut::SetPacking(int n)
{ srcNode->SetControl(VL_PACKING,n);
}
void QDMVideoOut::SetCaptureType(int n)
{ srcNode->SetControl(VL_CAP_TYPE,n);
}
void QDMVideoOut::SetTiming(int n)
{ drnNode->SetControl(VL_TIMING,n);
}
void QDMVideoOut::SetGenlock(bool b)
{
drnNode->SetControl(VL_SYNC,b?VL_SYNC_GENLOCK:VL_SYNC_INTERNAL);
}
void QDMVideoOut::Start()
// Start transferring
{
#ifdef FUTURE
VLTransferDescriptor xferDesc;
#endif
pathOut->SelectEvents(
VLTransferCompleteMask |
VLStreamBusyMask |
VLStreamPreemptedMask |
VLAdvanceMissedMask |
VLStreamAvailableMask |
VLSyncLostMask |
VLStreamStartedMask |
VLStreamStoppedMask |
VLSequenceLostMask |
VLControlChangedMask |
VLTransferCompleteMask |
VLTransferFailedMask |
//VLEvenVerticalRetraceMask |
//VLOddVerticalRetraceMask |
//VLFrameVerticalRetraceMask |
VLDeviceEventMask |
VLDefaultSourceMask |
VLControlRangeChangedMask |
VLControlPreemptedMask |
VLControlAvailableMask |
VLDefaultDrainMask |
VLStreamChangedMask |
VLTransferError);
/*pathOut->SelectEvents(VLTransferCompleteMask|
VLTransferFailedMask|
VLStreamPreemptedMask|
VLDeviceEventMask);*/
#ifdef FUTURE
xferDesc.mode=VL_TRANSFER_MODE_CONTINUOUS;
xferDesc.count=1;
xferDesc.delay=0;
xferDesc.trigger=VLTriggerImmediate;
#endif
pathOut->BeginTransfer();
}
void QDMVideoOut::GetEvent(VLEvent *event)
// This is actually not advised to use under USE_VL_65
// Use QVideoServer's event handling functions; this function
// will return events for ANY video path, not just the video out path (!)
{
#ifdef USE_VL_65
if(vlPending(app->GetVideoServer()->GetSGIServer())<=0)
return /*FALSE*/;
if(vlNextEvent(app->GetVideoServer()->GetSGIServer(),event)!=DM_SUCCESS)
#else
if(vlEventRecv(app->GetVideoServer()->GetSGIServer(),
pathOut->GetSGIPath(),event)!=DM_SUCCESS)
#endif
{ qerr("QDMVideoOut:GetEvent failed vlEventRecv");
return;
}
}
void QDMVideoOut::Send(DMbuffer buf)
{
#ifdef USE_VL_65
if(vlDMBufferPutValid(app->GetVideoServer()->GetSGIServer(),
pathOut->GetSGIPath(),drnNode->GetSGINode(),buf)!=0)
#else
if(vlDMBufferSend(app->GetVideoServer()->GetSGIServer(),
pathOut->GetSGIPath(),buf)!=0)
#endif
{ qerr("QDMVideoOut::Send(buf) failed; %s",vlStrError(vlGetErrno()));
}
}
| 27.272727
| 75
| 0.685079
|
3dhater
|
492baaf94ed04edfec0954b99b40d808fec4c397
| 3,165
|
cpp
|
C++
|
src/daemon/CmdListener.cpp
|
klx99/Elastos.Service.CarrierGroup
|
a1922402af66308178f048352ab6038f4c2d848b
|
[
"MIT"
] | null | null | null |
src/daemon/CmdListener.cpp
|
klx99/Elastos.Service.CarrierGroup
|
a1922402af66308178f048352ab6038f4c2d848b
|
[
"MIT"
] | null | null | null |
src/daemon/CmdListener.cpp
|
klx99/Elastos.Service.CarrierGroup
|
a1922402af66308178f048352ab6038f4c2d848b
|
[
"MIT"
] | null | null | null |
#include "CmdListener.hpp"
#include <vector>
#include <Carrier.hpp>
#include <CmdParser.hpp>
#include <DateTime.hpp>
#include <ErrCode.hpp>
#include <GroupCmdParser.hpp>
#include <Log.hpp>
#include <OptParser.hpp>
namespace elastos {
/* =========================================== */
/* === static variables initialize =========== */
/* =========================================== */
/* =========================================== */
/* === static function implement ============= */
/* =========================================== */
/* =========================================== */
/* === class public function implement ====== */
/* =========================================== */
int CmdListener::config(std::weak_ptr<Carrier> carrier)
{
this->carrier = carrier;
this->cmdParser = CmdParser::Factory::Create();
int rc = this->cmdParser->config(carrier);
CHECK_ERROR(rc);
return 0;
}
void CmdListener::onError(int errCode)
{
Log::D(Log::TAG, "%s errCode=%d", __PRETTY_FUNCTION__, errCode);
}
void CmdListener::onStatusChanged(const std::string& userId,
Status status)
{
Log::D(Log::TAG, "%s", __PRETTY_FUNCTION__);
}
void CmdListener::onFriendRequest(const std::string& friendCode,
const std::string& summary)
{
Log::D(Log::TAG, "%s", __PRETTY_FUNCTION__);
auto cmdline = CmdParser::Cmd::AddFriend + " " + friendCode + " " + summary;
int rc = cmdParser->parse(carrier,
cmdline, friendCode, 0);
if(rc < 0) {
onError(rc);
return;
}
return;
}
void CmdListener::onFriendStatusChanged(const std::string& friendCode,
Status status)
{
Log::D(Log::TAG, "%s", __PRETTY_FUNCTION__);
bool isGroup = !OptParser::GetInstance()->isManager();
if(isGroup && status == Status::Online) {
int rc = cmdParser->parse(carrier,
GroupCmdParser::Cmd::ForwardMessage,
friendCode, DateTime::CurrentNS());
CHECK_RETVAL(rc);
}
}
void CmdListener::onReceivedMessage(const std::string& friendCode,
int64_t timestamp,
const std::vector<uint8_t>& message)
{
Log::D(Log::TAG, "%s", __PRETTY_FUNCTION__);
std::string cmdline = std::string{message.begin(), message.end()};
// ignore hyper return receipt
if(cmdline == "{\"command\":\"messageSeen\"}") {
return;
}
if(cmdline.find_first_of('/') != 0) { // if not a command, exec as forward.
cmdline = GroupCmdParser::Cmd::ForwardMessage + " " + cmdline;
}
int rc = cmdParser->parse(carrier,
cmdline, friendCode, timestamp);
CHECK_RETVAL(rc);
}
/* =========================================== */
/* === class protected function implement === */
/* =========================================== */
/* =========================================== */
/* === class private function implement ===== */
/* =========================================== */
} // namespace elastos
| 29.305556
| 80
| 0.484044
|
klx99
|
49349850ebfb8542f3cc77a64fea0828cdd3fc4b
| 443
|
cpp
|
C++
|
PAT/PAT Basic/1016.cpp
|
Accelerator404/Algorithm-Demonstration
|
e40a499c23a56d363c743c76ac967d9c4247a4be
|
[
"Apache-2.0"
] | 1
|
2019-09-18T23:45:27.000Z
|
2019-09-18T23:45:27.000Z
|
PAT/PAT Basic/1016.cpp
|
Accelerator404/Algorithm-Demonstration
|
e40a499c23a56d363c743c76ac967d9c4247a4be
|
[
"Apache-2.0"
] | null | null | null |
PAT/PAT Basic/1016.cpp
|
Accelerator404/Algorithm-Demonstration
|
e40a499c23a56d363c743c76ac967d9c4247a4be
|
[
"Apache-2.0"
] | 1
|
2019-09-18T23:45:28.000Z
|
2019-09-18T23:45:28.000Z
|
#include <iostream>
#include <string>
using namespace std;
//PAT Basic No.1016 “部分A+B”
int P(string K, int Dk) {
int count = 0;
for (int i = 0; i < K.length(); ++i)
if (K.at(i) - '0' == Dk)
count++;
if (count == 0)
return 0;
else {
string Pk(count, Dk + '0');
return strtol(Pk.c_str(), nullptr, 10);
}
}
int main() {
int Da,Db;
string A, B;
cin >> A >> Da >> B >> Db;
cout << P(A, Da) + P(B, Db) << endl;;
return 0;
}
| 16.407407
| 41
| 0.532731
|
Accelerator404
|
493e6aa31a226a2337839854bbb7f925721783ea
| 1,602
|
cpp
|
C++
|
tests/DBCParserTest.cpp
|
aiekick/dbcppp
|
8f433e7b3ce5ee11aa6061ba82ba3cc4ddbbbfbe
|
[
"MIT"
] | 93
|
2019-12-26T08:35:22.000Z
|
2022-03-29T07:30:30.000Z
|
tests/DBCParserTest.cpp
|
Raufoon/dbcppp
|
f6db52bbca5a2272804ccdd8e38955e5b6cd7abd
|
[
"MIT"
] | 54
|
2020-02-26T23:12:09.000Z
|
2022-03-13T18:21:20.000Z
|
tests/DBCParserTest.cpp
|
ozzdemir/dbcppp
|
c7ea82b799c3dd945b399c75a6cf38fff6d61a4e
|
[
"MIT"
] | 26
|
2020-02-01T00:46:10.000Z
|
2022-03-29T12:40:37.000Z
|
#include <fstream>
#include <iomanip>
#include <filesystem>
#include "dbcppp/Network.h"
#include "dbcppp/Network2Functions.h"
#include "Config.h"
#include "Catch2.h"
TEST_CASE("DBCParserTest", "[]")
{
std::size_t i = 0;
for (const auto& dbc_file : std::filesystem::directory_iterator(std::filesystem::path(TEST_FILES_PATH) / "dbc"))
{
//BOOST_TEST_CHECKPOINT("DBCParserTest: Testing file '" + dbc_file.path().string() + "'");
if (dbc_file.path().extension() != ".dbc")
{
continue;
}
std::cout << "Testing DBC grammar with file: " << dbc_file.path() << std::endl;
auto dbc_file_tmp = dbc_file.path().string() + ".tmp";
std::unique_ptr<dbcppp::INetwork> spec;
std::unique_ptr<dbcppp::INetwork> test;
{
std::ifstream dbc(dbc_file.path());
spec = dbcppp::INetwork::LoadDBCFromIs(dbc);
std::ofstream tmp_dbc(dbc_file_tmp);
bool open = tmp_dbc.is_open();
using namespace dbcppp::Network2DBC;
tmp_dbc << std::setprecision(10);
tmp_dbc << *spec << std::endl;
}
{
std::ifstream dbc(dbc_file_tmp);
test = dbcppp::INetwork::LoadDBCFromIs(dbc);
REQUIRE(test);
}
auto error_msg = "Failed for " + std::to_string(i) + "th file ('" + dbc_file.path().string() + "')";
if (*spec != *test)
{
std::cout << error_msg << std::endl;
}
REQUIRE(*spec == *test);
std::filesystem::remove(dbc_file_tmp);
i++;
}
}
| 31.411765
| 116
| 0.553059
|
aiekick
|
494023c248b5d96d68510482a00fbafad820c649
| 19,717
|
cpp
|
C++
|
aby3-DB_tests/PermutaitonTests.cpp
|
vincehong/aby3
|
1a5277b37249545e967fc58a9235666a2453c104
|
[
"MIT"
] | 121
|
2019-06-25T01:35:50.000Z
|
2022-03-24T12:53:17.000Z
|
aby3-DB_tests/PermutaitonTests.cpp
|
vincehong/aby3
|
1a5277b37249545e967fc58a9235666a2453c104
|
[
"MIT"
] | 33
|
2020-01-21T16:47:09.000Z
|
2022-01-23T12:41:22.000Z
|
aby3-DB_tests/PermutaitonTests.cpp
|
vincehong/aby3
|
1a5277b37249545e967fc58a9235666a2453c104
|
[
"MIT"
] | 36
|
2019-09-05T08:35:09.000Z
|
2022-01-14T11:57:22.000Z
|
#include <cryptoTools/Network/IOService.h>
#include <cryptoTools/Network/Session.h>
#include <cryptoTools/Network/Channel.h>
#include <cryptoTools/Common/Matrix.h>
#include <aby3-DB/OblvPermutation.h>
#include <aby3-DB/OblvSwitchNet.h>
#include <cryptoTools/Crypto/PRNG.h>
#include "PermutaitonTests.h"
#include <iomanip>
using namespace oc;
void Perm3p_overwrite_Test()
{
IOService ios;
Session s01(ios, "127.0.0.1", SessionMode::Server, "01");
Session s10(ios, "127.0.0.1", SessionMode::Client, "01");
Session s02(ios, "127.0.0.1", SessionMode::Server, "02");
Session s20(ios, "127.0.0.1", SessionMode::Client, "02");
Session s12(ios, "127.0.0.1", SessionMode::Server, "12");
Session s21(ios, "127.0.0.1", SessionMode::Client, "12");
Channel chl01 = s01.addChannel();
Channel chl10 = s10.addChannel();
Channel chl02 = s02.addChannel();
Channel chl20 = s20.addChannel();
Channel chl12 = s12.addChannel();
Channel chl21 = s21.addChannel();
int rows = 1 << 16;
int bytes = 16;
std::vector<u32> perm(rows);
for (u32 i = 0; i < perm.size(); ++i)
perm[i] = i;
PRNG prng(OneBlock);
std::random_shuffle(perm.begin(), perm.end(), prng);
Matrix<u8> mtx(rows, bytes);
Matrix<u8> s1(rows, bytes);
Matrix<u8> s2(rows, bytes);
prng.get(mtx.data(), mtx.size());
//std::cout << std::endl;
//for (u32 i = 0; i < mtx.rows(); ++i)
//{
// std::cout << i << " -> " << perm[i] << " : ";
// for (u32 j = 0; j < mtx.cols(); ++j)
// {
// std::cout << " " << std::hex << int(mtx(i, j));
// }
// std::cout << std::endl;
//}
//auto t0 = std::thread([&]()
{
OblvPermutation p;
auto perm2 = perm;
p.program(chl02, chl01, perm2, prng, s1, "test");
}//);
//std::cout << std::endl;
//auto t1 = std::thread([&]()
{
OblvPermutation p;
p.send(chl10, chl12, mtx, "test");
}//);
//std::cout << std::endl;
OblvPermutation p;
p.recv(chl20, chl21, s2, rows, "test");
//t0.join();
//t1.join();
//std::cout << std::endl;
//for (u32 i = 0; i < mtx.rows(); ++i)
//{
// std::cout << i << " : ";
// for (u32 j = 0; j < mtx.cols(); ++j)
// {
// std::cout << " " << std::hex << int(s1(i, j) ^ s2(i, j));
// }
// std::cout << std::endl;
//}
bool failed = false;
for (u32 i = 0; i < mtx.rows(); ++i)
{
for (u32 j = 0; j < mtx.cols(); ++j)
{
auto val = s1(perm[i], j) ^ s2(perm[i], j);
if (mtx(i, j) != val)
{
std::cout << "mtx(" << i << ", " << j << ") != s1(" << perm[i] << ", " << j << ") ^ s2(" << perm[i] << ", " << j << ")" << std::endl;
std::cout << " " << int(mtx(i, j)) << " != " << int(s1(perm[i], j)) << " ^ " << int(s2(perm[i], j)) << std::endl;
std::cout << " " << int(mtx(i, j)) << " != " << int(s1(perm[i], j) ^ s2(perm[i], j)) << std::endl;
failed = true;
}
}
}
if (failed)
throw std::runtime_error(LOCATION);
}
void Perm3p_additive_Test()
{
IOService ios;
Session s01(ios, "127.0.0.1", SessionMode::Server, "01");
Session s10(ios, "127.0.0.1", SessionMode::Client, "01");
Session s02(ios, "127.0.0.1", SessionMode::Server, "02");
Session s20(ios, "127.0.0.1", SessionMode::Client, "02");
Session s12(ios, "127.0.0.1", SessionMode::Server, "12");
Session s21(ios, "127.0.0.1", SessionMode::Client, "12");
Channel chl01 = s01.addChannel();
Channel chl10 = s10.addChannel();
Channel chl02 = s02.addChannel();
Channel chl20 = s20.addChannel();
Channel chl12 = s12.addChannel();
Channel chl21 = s21.addChannel();
int rows = 100;
int bytes = 16;
std::vector<u32> perm(rows);
for (u32 i = 0; i < perm.size(); ++i)
perm[i] = i;
PRNG prng(OneBlock);
std::random_shuffle(perm.begin(), perm.end(), prng);
Matrix<u8> mtx(rows, bytes);
Matrix<u8> s1(rows, bytes);
Matrix<u8> s2(rows, bytes);
prng.get(mtx.data(), mtx.size());
prng.get(s1.data(), s1.size());
s2 = s1;
//std::cout << std::endl;
//for (u32 i = 0; i < mtx.rows(); ++i)
//{
// std::cout << i << " -> " << perm[i] << " : ";
// for (u32 j = 0; j < mtx.cols(); ++j)
// {
// std::cout << " " << std::hex << int(mtx(i, j));
// }
// std::cout << std::endl;
//}
//auto t0 = std::thread([&]()
{
OblvPermutation p;
auto perm2 = perm;
p.program(chl02, chl01, perm2, prng, s1, "test", OutputType::Additive);
}//);
//std::cout << std::endl;
//auto t1 = std::thread([&]()
{
OblvPermutation p;
p.send(chl10, chl12, mtx, "test");
}//);
//std::cout << std::endl;
OblvPermutation p;
p.recv(chl20, chl21, s2, rows, "test", OutputType::Additive);
//t0.join();
//t1.join();
//std::cout << std::endl;
//for (u32 i = 0; i < mtx.rows(); ++i)
//{
// std::cout << i << " : ";
// for (u32 j = 0; j < mtx.cols(); ++j)
// {
// std::cout << " " << std::hex << int(s1(i, j) ^ s2(i, j));
// }
// std::cout << std::endl;
//}
bool failed = false;
for (u32 i = 0; i < mtx.rows(); ++i)
{
for (u32 j = 0; j < mtx.cols(); ++j)
{
auto val = s1(perm[i], j) ^ s2(perm[i], j);
if (mtx(i, j) != val)
{
std::cout << "mtx(" << i << ", " << j << ") != s1(" << perm[i] << ", " << j << ") ^ s2(" << perm[i] << ", " << j << ")" << std::endl;
std::cout << " " << int(mtx(i, j)) << " != " << int(s1(perm[i], j)) << " ^ " << int(s2(perm[i], j)) << std::endl;
std::cout << " " << int(mtx(i, j)) << " != " << int(s1(perm[i], j) ^ s2(perm[i], j)) << std::endl;
failed = true;
}
}
}
if (failed)
throw std::runtime_error(LOCATION);
}
void Perm3p_subset_Test()
{
IOService ios;
Session s01(ios, "127.0.0.1", SessionMode::Server, "01");
Session s10(ios, "127.0.0.1", SessionMode::Client, "01");
Session s02(ios, "127.0.0.1", SessionMode::Server, "02");
Session s20(ios, "127.0.0.1", SessionMode::Client, "02");
Session s12(ios, "127.0.0.1", SessionMode::Server, "12");
Session s21(ios, "127.0.0.1", SessionMode::Client, "12");
Channel chl01 = s01.addChannel();
Channel chl10 = s10.addChannel();
Channel chl02 = s02.addChannel();
Channel chl20 = s20.addChannel();
Channel chl12 = s12.addChannel();
Channel chl21 = s21.addChannel();
int rows = 100;
int destRows = 50;
int bytes = 2;
std::vector<u32> perm(rows, -1);
for (u32 i = 0; i < destRows; ++i)
perm[i] = i;
PRNG prng(OneBlock);
std::random_shuffle(perm.begin(), perm.end(), prng);
Matrix<u8> mtx(rows, bytes);
Matrix<u8> s1(destRows, bytes);
Matrix<u8> s2(destRows, bytes);
prng.get(mtx.data(), mtx.size());
//std::cout << std::endl;
//for (u32 i = 0; i < mtx.rows(); ++i)
//{
// std::cout << i << " -> " << perm[i] << " : ";
// for (u32 j = 0; j < mtx.cols(); ++j)
// {
// std::cout << " " << std::hex << int(mtx(i, j));
// }
// std::cout << std::endl;
//}
//auto t0 = std::thread([&]()
{
OblvPermutation p;
auto perm2 = perm;
p.program(chl02, chl01, perm2, prng, s1, "test");
}//);
//std::cout << std::endl;
//auto t1 = std::thread([&]()
{
OblvPermutation p;
p.send(chl10, chl12, mtx, "test");
}//);
//std::cout << std::endl;
OblvPermutation p;
p.recv(chl20, chl21, s2, rows, "test");
//t0.join();
//t1.join();
//std::cout << std::endl;
//for (u32 i = 0; i < mtx.rows(); ++i)
//{
// std::cout << i << " : ";
// for (u32 j = 0; j < mtx.cols(); ++j)
// {
// std::cout << " " << std::hex << int(s1(i, j) ^ s2(i, j));
// }
// std::cout << std::endl;
//}
bool failed = false;
for (u32 i = 0; i < rows; ++i)
{
if (perm[i] != -1)
{
auto s = perm[i];
for (u32 j = 0; j < bytes; ++j)
{
auto val = s1(s, j) ^ s2(s, j);
if (mtx(i, j) != val)
{
std::cout << "mtx(" << i << ", " << j << ") != s1(" << s << ", " << j << ") ^ s2(" << s << ", " << j << ")" << std::endl;
std::cout << " " << int(mtx(i, j)) << " != " << int(s1(s, j)) << " ^ " << int(s2(s, j)) << std::endl;
std::cout << " " << int(mtx(i, j)) << " != " << int(s1(s, j) ^ s2(s, j)) << std::endl;
failed = true;
}
}
}
}
if (failed)
throw std::runtime_error(LOCATION);
}
void switch_select_test()
{
IOService ios;
Session s01(ios, "127.0.0.1", SessionMode::Server, "01");
Session s10(ios, "127.0.0.1", SessionMode::Client, "01");
Session s02(ios, "127.0.0.1", SessionMode::Server, "02");
Session s20(ios, "127.0.0.1", SessionMode::Client, "02");
Session s12(ios, "127.0.0.1", SessionMode::Server, "12");
Session s21(ios, "127.0.0.1", SessionMode::Client, "12");
Channel chl01 = s01.addChannel();
Channel chl10 = s10.addChannel();
Channel chl02 = s02.addChannel();
Channel chl20 = s20.addChannel();
Channel chl12 = s12.addChannel();
Channel chl21 = s21.addChannel();
int trials = 100;
int srcSize = 40;
int destSize = 20;
int bytes = 1;
Matrix<u8> src(srcSize, bytes);
Matrix<u8> dest0(destSize, bytes), dest1(destSize, bytes);
for (auto t = 9; t < trials; ++t)
{
PRNG prng(toBlock(t));
prng.get(src.data(), src.size());
//for (auto i = 0; i < src.rows(); ++i)
//{
// std::cout << "s[" << i << "] = ";
// for (auto j = 0; j < src.cols(); ++j)
// {
// std::cout << " " << std::setw(2) << std::hex << int(src(i, j));
// }
// std::cout << std::endl << std::dec;
//}
OblvSwitchNet::Program prog;
prog.init(srcSize, destSize);
for (u64 i = 0; i < destSize; ++i)
{
prog.addSwitch(prng.get<u32>() % srcSize, (u32)i);
//std::cout << "switch[" << i << "] = " << prog.mSrcDests[i][0] << " -> " << prog.mSrcDests[i][1] << std::endl;
}
auto t0 = std::thread([&]() {
OblvSwitchNet snet("test");
snet.programSelect(chl02, chl01, prog, prng, dest0);
});
auto t1 = std::thread([&]() {
OblvSwitchNet snet("test");
snet.sendSelect(chl10, chl12, src);
});
auto t2 = std::thread([&]() {
OblvSwitchNet snet("test");
snet.recvSelect(chl20, chl21, dest1, srcSize);
});
t0.join();
t1.join();
t2.join();
auto last = -1;
bool print = false;
if (print)
std::cout << std::endl;
bool failed = false;
for (u64 i = 0; i < prog.mSrcDests.size(); ++i)
{
auto s = prog.mSrcDests[i].mSrc;
if (s != last)
{
for (auto j = 0; j < bytes; ++j)
{
if ((dest0(i, j) ^ dest1(i, j)) != src(s, j))
{
failed = true;
}
}
if (print)
{
std::cout << "d[" << i << "] = ";
for (auto j = 0; j < bytes; ++j)
{
if ((dest0(i, j) ^ dest1(i, j)) != src(s, j))
std::cout << Color::Red;
std::cout << ' ' << std::setw(2) << std::hex << int(dest0(i, j) ^ dest1(i, j)) << ColorDefault;
}
std::cout << "\ns[" << i << "] = ";
for (auto j = 0; j < bytes; ++j)
std::cout << ' ' << std::setw(2) << std::hex << int(src(s, j));
std::cout << std::endl << std::dec;
}
last = s;
}
}
if (failed)
throw std::runtime_error("");
}
}
void switch_duplicate_test()
{
IOService ios;
Session s01(ios, "127.0.0.1", SessionMode::Server, "01");
Session s10(ios, "127.0.0.1", SessionMode::Client, "01");
Session s02(ios, "127.0.0.1", SessionMode::Server, "02");
Session s20(ios, "127.0.0.1", SessionMode::Client, "02");
Session s12(ios, "127.0.0.1", SessionMode::Server, "12");
Session s21(ios, "127.0.0.1", SessionMode::Client, "12");
Channel chl01 = s01.addChannel();
Channel chl10 = s10.addChannel();
Channel chl02 = s02.addChannel();
Channel chl20 = s20.addChannel();
Channel chl12 = s12.addChannel();
Channel chl21 = s21.addChannel();
int trials = 100;
int srcSize = 50;
int destSize = srcSize /2;
int bytes = 1;
Matrix<u8> src(srcSize, bytes);
Matrix<u8> dest0(destSize, bytes), dest1(destSize, bytes);
for (auto t = 0; t < trials; ++t)
{
PRNG prng(toBlock(t));
prng.get(src.data(), src.size());
//for (auto i = 0; i < src.rows(); ++i)
//{
// std::cout << "s[" << i << "] = ";
// for (auto j = 0; j < src.cols(); ++j)
// {
// std::cout << " " << std::setw(2) << std::hex << int(src(i, j));
// }
// std::cout << std::endl << std::dec;
//}
OblvSwitchNet::Program prog;
prog.init(srcSize, destSize);
for (u64 i = 0; i < destSize; ++i)
{
prog.addSwitch(prng.get<u32>() % srcSize, (u32)i);
//prog.addSwitch(0, i);
//std::cout << "switch[" << i << "] = " << prog.mSrcDests[i][0] << " -> " << prog.mSrcDests[i][1] << std::endl;
}
auto t0 = std::thread([&]() {
setThreadName("t0");
OblvSwitchNet snet("test");
snet.programSelect(chl02, chl01, prog, prng, dest0);
snet.programDuplicate(chl02, chl01, prog, prng, dest0);
});
auto t1 = std::thread([&]() {
setThreadName("t1");
OblvSwitchNet snet("test");
snet.sendSelect(chl10, chl12, src);
snet.helpDuplicate(chl10, destSize, bytes);
});
auto t2 = std::thread([&]() {
setThreadName("t2");
OblvSwitchNet snet("test");
snet.recvSelect(chl20, chl21, dest1, srcSize);
PRNG prng2(toBlock(585643));
snet.sendDuplicate(chl20, prng2, dest1);
});
t0.join();
t1.join();
t2.join();
bool print = false;
if (print)
std::cout << std::endl;
bool failed = false;
for (u64 i = 0; i < prog.mSrcDests.size(); ++i)
{
auto s = prog.mSrcDests[i].mSrc;
for (auto j = 0; j < bytes; ++j)
{
if ((dest0(i, j) ^ dest1(i, j)) != src(s, j))
{
failed = true;
}
}
if (print)
{
std::cout << "d[" << i << "] = ";
for (auto j = 0; j < bytes; ++j)
{
if ((dest0(i, j) ^ dest1(i, j)) != src(s, j))
std::cout << Color::Red;
std::cout << ' ' << std::setw(2) << std::hex << int(dest0(i, j) ^ dest1(i, j)) << ColorDefault;
}
std::cout << "\ns[" << i << "] = ";
for (auto j = 0; j < bytes; ++j)
std::cout << ' ' << std::setw(2) << std::hex << int(src(s, j));
std::cout << std::endl << std::dec;
}
}
if (failed)
throw std::runtime_error("");
}
}
void switch_full_test()
{
IOService ios;
Session s01(ios, "127.0.0.1", SessionMode::Server, "01");
Session s10(ios, "127.0.0.1", SessionMode::Client, "01");
Session s02(ios, "127.0.0.1", SessionMode::Server, "02");
Session s20(ios, "127.0.0.1", SessionMode::Client, "02");
Session s12(ios, "127.0.0.1", SessionMode::Server, "12");
Session s21(ios, "127.0.0.1", SessionMode::Client, "12");
Channel chl01 = s01.addChannel();
Channel chl10 = s10.addChannel();
Channel chl02 = s02.addChannel();
Channel chl20 = s20.addChannel();
Channel chl12 = s12.addChannel();
Channel chl21 = s21.addChannel();
int trials = 100;
int srcSize = 50;
int destSize = srcSize / 2;
int bytes = 1;
Matrix<u8> src(srcSize, bytes);
Matrix<u8> dest0(destSize, bytes), dest1(destSize, bytes);
for (auto t = 0; t < trials; ++t)
{
PRNG prng(toBlock(t));
prng.get(src.data(), src.size());
//for (auto i = 0; i < src.rows(); ++i)
//{
// std::cout << "s[" << i << "] = ";
// for (auto j = 0; j < src.cols(); ++j)
// {
// std::cout << " " << std::setw(2) << std::hex << int(src(i, j));
// }
// std::cout << std::endl << std::dec;
//}
OblvSwitchNet::Program prog;
prog.init(srcSize, destSize);
for (u64 i = 0; i < destSize; ++i)
{
prog.addSwitch(prng.get<u32>() % srcSize, (u32)i);
//prog.addSwitch(0, i);
//std::cout << "switch[" << i << "] = " << prog.mSrcDests[i][0] << " -> " << prog.mSrcDests[i][1] << std::endl;
}
auto t0 = std::thread([&]() {
setThreadName("t0");
OblvSwitchNet snet("test");
snet.program(chl02, chl01, prog, prng, dest0);
});
auto t1 = std::thread([&]() {
setThreadName("t1");
OblvSwitchNet snet("test");
snet.sendRecv(chl10, chl12, src, dest1);
});
auto t2 = std::thread([&]() {
setThreadName("t2");
OblvSwitchNet snet("test");
PRNG prng2(toBlock(44444));
snet.help(chl20, chl21, prng2, destSize, srcSize, bytes);
});
t0.join();
t1.join();
t2.join();
bool print = false;
if (print)
std::cout << std::endl;
bool failed = false;
for (u64 i = 0; i < prog.mSrcDests.size(); ++i)
{
auto s = prog.mSrcDests[i].mSrc;
auto d = prog.mSrcDests[i].mDest;
for (auto j = 0; j < bytes; ++j)
{
if ((dest0(d, j) ^ dest1(d, j)) != src(s, j))
{
failed = true;
}
}
if (print)
{
std::cout << "d[" << d << "] = ";
for (auto j = 0; j < bytes; ++j)
{
if ((dest0(d, j) ^ dest1(d, j)) != src(s, j))
std::cout << Color::Red;
std::cout << ' ' << std::setw(2) << std::hex << int(dest0(i, j) ^ dest1(i, j)) << ColorDefault;
}
std::cout << "\ns[" << s << "] = ";
for (auto j = 0; j < bytes; ++j)
std::cout << ' ' << std::setw(2) << std::hex << int(src(s, j));
std::cout << std::endl << std::dec;
}
}
if (failed)
throw std::runtime_error("");
}
}
| 28.95301
| 149
| 0.4417
|
vincehong
|
494363cf5e51c77fae1c46c961b84dfed7424c3c
| 2,230
|
hpp
|
C++
|
include/Aether/Screen.hpp
|
NightYoshi370/Aether
|
87d2b81f5d3143e39c363a9c81c195d440d7a4e8
|
[
"MIT"
] | 1
|
2021-02-04T07:27:46.000Z
|
2021-02-04T07:27:46.000Z
|
libs/Aether/include/Aether/Screen.hpp
|
tkgstrator/SeedHack
|
227566d993bdea7a2851a8fc664b539186509697
|
[
"MIT"
] | null | null | null |
libs/Aether/include/Aether/Screen.hpp
|
tkgstrator/SeedHack
|
227566d993bdea7a2851a8fc664b539186509697
|
[
"MIT"
] | null | null | null |
#ifndef AETHER_SCREEN_HPP
#define AETHER_SCREEN_HPP
#include "Aether/base/Container.hpp"
#include <unordered_map>
namespace Aether {
/**
* @brief A class that represents a screen layout
* Stores all screen elements for a specific screen.
*/
class Screen : public Container {
private:
/** @brief Mappings for button presses to callback functions */
std::unordered_map<Button, std::function<void()> > pressFuncs;
/** @brief Mappings for button releases to callback functions */
std::unordered_map<Button, std::function<void()> > releaseFuncs;
public:
/**
* @brief Construct a new Screen object
*/
Screen();
/**
* @brief Callback function when the screen is loaded
*/
virtual void onLoad();
/**
* @brief Callback function when the screen is unloaded
*/
virtual void onUnload();
/**
* @brief Assigns callback function for button press
* @note Setting a button callback will block the event from
* going to any other elements
*
* @param btn button to assign callback to
* @param func function to assign as callback for button press
*/
void onButtonPress(Button btn, std::function<void()> func);
/**
* @brief Assigns callback function for button release
* @note Setting a button callback will block the event from
* going to any other elements
*
* @param btn button to assign callback to
* @param func function to assign as callback for button release
*/
void onButtonRelease(Button btn, std::function<void()> func);
/**
* @brief Attempt event handling for an event that occured
*
* @param event event to handle
* @return true if event was handled
* @return false if event was not handled
*/
bool handleEvent(InputEvent *event);
};
};
#endif
| 33.283582
| 76
| 0.54843
|
NightYoshi370
|
4948f63c5fa04d8ea292d283e330409a91d25e3a
| 1,360
|
hpp
|
C++
|
inc/sexpr-ident.hpp
|
ryanvbissell/dslang
|
65379ca7bbefff0161d11343b742ac58452d37e7
|
[
"BSD-2-Clause"
] | null | null | null |
inc/sexpr-ident.hpp
|
ryanvbissell/dslang
|
65379ca7bbefff0161d11343b742ac58452d37e7
|
[
"BSD-2-Clause"
] | null | null | null |
inc/sexpr-ident.hpp
|
ryanvbissell/dslang
|
65379ca7bbefff0161d11343b742ac58452d37e7
|
[
"BSD-2-Clause"
] | null | null | null |
// vim: set tabstop=2 softtabstop=2 shiftwidth=2 expandtab :
/*
* Copyright (c) 2014-2017, Ryan V. Bissell
* All rights reserved.
*
* SPDX-License-Identifier: BSD-2-Clause
* See the enclosed "LICENSE" file for exact license terms.
*/
#ifndef DSLANG_SEXPR_IDENT_HPP
#define DSLANG_SEXPR_IDENT_HPP
#include "sexpr.hpp"
#include <string>
namespace DSL
{
class Dialect;
namespace detail
{
class SexprIdent CX_FINAL : public Sexpr
{
friend class CX::IntrusivePtr<SexprIdent>;
public:
SexprIdent(Context* sc, char const** input);
std::string Write() const;
/*
static bool Match(Dialect const& dialect, char const* text);
static Sexpr::Type Skip(Dialect const& dialect, char const** input);
static SEXPR Parse(Dialect const& dialect, char const** input);
*/
protected:
Type type() const override { return Sexpr::Type::IDENT; }
Sexpr const* transmute(char const** input) const override;
Sexpr const* eval(SexprEnv const* env) const override;
private:
std::string name_;
virtual ~SexprIdent();
};
bool SexprIdent__Match(char const* text);
Sexpr::Type SexprIdent__Skip(char const** input);
Sexpr const* SexprIdent__Parse(Context* sc, char const** input);
} // namespace detail
using SexprIDENT = CX::IntrusivePtr<detail::SexprIdent>;
} // namespace DSL
#endif // DSLANG_SEXPR_IDENT_HPP
| 21.935484
| 72
| 0.710294
|
ryanvbissell
|
4953016766edc08efab4acd6241229c0075c519d
| 3,474
|
cpp
|
C++
|
depends/acransac/conditioning.cpp
|
mmrwizard/RenderMatch-1
|
a427138e6823675eaa76c693bc31a28566b4dcd8
|
[
"MIT"
] | null | null | null |
depends/acransac/conditioning.cpp
|
mmrwizard/RenderMatch-1
|
a427138e6823675eaa76c693bc31a28566b4dcd8
|
[
"MIT"
] | null | null | null |
depends/acransac/conditioning.cpp
|
mmrwizard/RenderMatch-1
|
a427138e6823675eaa76c693bc31a28566b4dcd8
|
[
"MIT"
] | 1
|
2020-05-12T08:19:14.000Z
|
2020-05-12T08:19:14.000Z
|
// Copyright (c) 2010 libmv authors.
//
// 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.
// Copyright (c) 2012, 2013 Pierre MOULON.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include "conditioning.hpp"
namespace openMVG {
// HZ 4.4.4 pag.109
void PreconditionerFromPoints(const Mat &points, Mat3 *T) {
Vec mean, variance;
MeanAndVarianceAlongRows(points, &mean, &variance);
double xfactor = sqrt(2.0 / variance(0));
double yfactor = sqrt(2.0 / variance(1));
// If variance is equal to 0.0 set scaling factor to identity.
// -> Else it will provide nan value (because division by 0).
if (variance(0) < 1e-8)
xfactor = mean(0) = 1.0;
if (variance(1) < 1e-8)
yfactor = mean(1) = 1.0;
*T << xfactor, 0, -xfactor * mean(0), 0, yfactor, -yfactor * mean(1), 0, 0, 1;
}
void PreconditionerFromPoints(int width, int height, Mat3 *T) {
// Build the normalization matrix
double dNorm = 1.0 / sqrt(static_cast<double>(width * height));
(*T) = Mat3::Identity();
(*T)(0, 0) = (*T)(1, 1) = dNorm;
(*T)(0, 2) = -.5f * width * dNorm;
(*T)(1, 2) = -.5 * height * dNorm;
}
void ApplyTransformationToPoints(const Mat &points, const Mat3 &T, Mat *transformed_points) {
const Mat::Index n = points.cols();
transformed_points->resize(2, n);
for (Mat::Index i = 0; i < n; ++i) {
Vec3 in, out;
in << points(0, i), points(1, i), 1;
out = T * in;
(*transformed_points)(0, i) = out(0) / out(2);
(*transformed_points)(1, i) = out(1) / out(2);
}
}
void NormalizePoints(const Mat &points, Mat *normalized_points, Mat3 *T, int width, int height) {
PreconditionerFromPoints(width, height, T);
ApplyTransformationToPoints(points, *T, normalized_points);
}
void NormalizePoints(const Mat &points, Mat *normalized_points, Mat3 *T) {
PreconditionerFromPoints(points, T);
ApplyTransformationToPoints(points, *T, normalized_points);
}
// Denormalize the results. See HZ page 109.
void UnnormalizerT::Unnormalize(const Mat3 &T1, const Mat3 &T2, Mat3 *H) { *H = T2.transpose() * (*H) * T1; }
// Denormalize the results. See HZ page 109.
void UnnormalizerI::Unnormalize(const Mat3 &T1, const Mat3 &T2, Mat3 *H) { *H = T2.inverse() * (*H) * T1; }
} // namespace openMVG
| 39.477273
| 109
| 0.678181
|
mmrwizard
|
4953051a9c59971d6ec2529ea8a90a8789ebb2eb
| 5,339
|
cpp
|
C++
|
src/utils.cpp
|
molendijk/InfoClock
|
98719495800cd930d51c495e83b08ddf9b99fc5b
|
[
"MIT"
] | null | null | null |
src/utils.cpp
|
molendijk/InfoClock
|
98719495800cd930d51c495e83b08ddf9b99fc5b
|
[
"MIT"
] | null | null | null |
src/utils.cpp
|
molendijk/InfoClock
|
98719495800cd930d51c495e83b08ddf9b99fc5b
|
[
"MIT"
] | null | null | null |
/*
* utils.cpp
*
* Created on: 04.01.2017
* Author: Bartosz Bielawski
*/
#include <time.h>
#include <stdio.h>
#include <vector>
#include <memory>
#include "utils.h"
#include "config.h"
#include "Client.h"
#include "Arduino.h"
#include "FS.h"
#include "DataStore.h"
#include "WiFiUdp.h"
#include "SyslogSender.h"
#include "ESP8266WiFi.h"
#include "tasks_utils.h"
#include "LambdaTask.hpp"
extern "C" {
#include "user_interface.h"
}
uint16_t operator"" _s(long double seconds) {return seconds * 1000 / MS_PER_CYCLE;}
uint16_t operator"" _s(unsigned long long int seconds) {return seconds * 1000 / MS_PER_CYCLE;}
static char dateTimeBuffer[] = "1970-01-01T00:00:00";
static uint32_t startUpTime = 0;
uint32_t getUpTime()
{
return time(nullptr) - startUpTime;
}
String getTime()
{
time_t now = time(nullptr);
if (now == 0)
{
return "??:??:??";
}
//this saves the first timestamp when it was nonzero (it's near start-up time)
if (startUpTime == 0)
{
startUpTime = now;
}
String r;
char localBuffer[10];
auto lt = localtime(&now);
snprintf(localBuffer, sizeof(localBuffer), "%02d:%02d:%02d",
lt->tm_hour,
lt->tm_min,
lt->tm_sec);
r = localBuffer;
return r;
}
static const std::vector<const char*> dayNames{"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
//static const std::vector<const char*> dayNames{"Nd", "Pn", "Wt", "Sr", "Cz", "Pt", "Sb"};
String getDate()
{
time_t now = time(nullptr);
String r;
if (now == 0)
{
return r;
}
char localBuffer[20];
auto lt = localtime(&now);
snprintf(localBuffer, sizeof(localBuffer), "%s %02d/%02d",
dayNames[lt->tm_wday],
lt->tm_mday,
lt->tm_mon+1);
r = localBuffer;
return r;
}
static time_t previousDateTime = 0;
const char* getDateTime()
{
time_t now = time(nullptr);
if (now == previousDateTime)
return dateTimeBuffer;
auto lt = localtime(&now);
snprintf(dateTimeBuffer, 32, "%04d-%02d-%02dT%02d:%02d:%02d",
lt->tm_year-100+2000,
lt->tm_mon+1,
lt->tm_mday,
lt->tm_hour,
lt->tm_min,
lt->tm_sec);
previousDateTime = now;
return dateTimeBuffer;
}
const static char UUID_FORMAT[] PROGMEM = "%08x-%04x-4%03x-8%03x-%04x%08x";
static char UUID[36];
const char* generateRandomUUID()
{
uint32_t r1 = os_random();
uint32_t r2 = os_random();
uint32_t r3 = os_random();
uint32_t r4 = os_random();
sprintf_P(UUID, UUID_FORMAT, r1, r2 >> 16, r2 & 0xFFF, r3 >> 20, r3 & 0xFFFF, r4);
return UUID;
}
void logPPrintf(char* format, ...)
{
char localBuffer[256];
va_list argList;
va_start(argList, format);
Serial.printf("%s-%09u - ", getDateTime(), ESP.getCycleCount());
vsnprintf(localBuffer, sizeof(localBuffer), format, argList);
Serial.println(localBuffer);
va_end(argList);
}
void logPrintfX(const String& app, const String& format, ...)
{
char localBuffer[256];
String a(app);
va_list argList;
va_start(argList, format);
uint32_t bytes = snprintf(localBuffer, sizeof(localBuffer), "%s - %s: ", getDateTime(), a.c_str());
vsnprintf(localBuffer+bytes, sizeof(localBuffer)-bytes, format.c_str(), argList);
Serial.println(localBuffer);
syslogSend(app, localBuffer+bytes);
va_end(argList);
}
bool checkFileSystem()
{
bool alreadyFormatted = SPIFFS.begin();
if (not alreadyFormatted)
SPIFFS.format();
SPIFFS.end();
return alreadyFormatted;
}
void readConfigFromFlash()
{
SPIFFS.begin();
auto dir = SPIFFS.openDir(F("/config"));
while (dir.next())
{
auto f = dir.openFile("r");
auto value = f.readStringUntil('\n');
//skip the /config/ part of the path
auto name = dir.fileName().substring(8);
DataStore::value(name) = value;
//logPrintf(F("RCFF: %s = %s"), name.c_str(), value.c_str());
}
}
String readConfigWithDefault(const String& name, const String& def)
{
auto v = readConfig(name);
return v.length() != 0 ? v: def;
}
String readConfig(const String& name)
{
static bool once = true;
if (once)
{
readConfigFromFlash();
once = false;
}
return DataStore::value(name);
}
void writeConfig(const String& name, const String& value)
{
auto f = SPIFFS.open(String(F("/config/")) +name, "w+");
f.print(value);
f.print('\n');
f.close();
DataStore::value(name) = value;
}
int32_t getTimeZone()
{
return readConfig("timezone").toInt();
}
int32_t timezone = 0;
static const char uptimeFormat[] PROGMEM = "%dd%dh%dm%ds";
String dataSource(const char* name)
{
String result;
if (DataStore::hasValue(name))
{
result = DataStore::value(name);
if (result)
return result;
}
if (strcmp(name, "heap") == 0)
return String(ESP.getFreeHeap()) + " B";
if (strcmp(name, "version") == 0)
return versionString;
if (strcmp(name, "essid") == 0)
return WiFi.SSID();
if (strcmp(name, "mac") == 0)
return WiFi.macAddress();
if (strcmp(name, "uptime") == 0)
{
uint32_t ut = getUpTime();
uint32_t d = ut / (24 * 3600);
ut -= d * 24 * 3600;
uint32_t h = ut / 3600;
ut -= h * 3600;
uint32_t m = ut / 60;
ut -= m * 60;
uint32_t s = ut;
char buf[64];
snprintf_P(buf, sizeof(buf), uptimeFormat, d, h, m, s);
return String(buf);
}
return "?";
}
void rebootClock()
{
getDisplayTask().pushMessage("Rebooting...", 5_s, false);
logPrintfX(F("WS"), F("Rebooting in 5 seconds..."));
LambdaTask* lt = new LambdaTask([](){ESP.restart();});
addTask(lt, TaskDescriptor::ENABLED);
lt->sleep(5_s);
}
| 19.067857
| 100
| 0.65649
|
molendijk
|
495489fcb847b90b12ad90cef1f5bc51d903b3c3
| 691
|
cpp
|
C++
|
test/unit/api/terminal.cpp
|
jfalcou/nucog
|
186808bec04af4f1138bc5362510fffbe690fdd3
|
[
"MIT"
] | 1
|
2022-02-13T20:11:06.000Z
|
2022-02-13T20:11:06.000Z
|
test/unit/api/terminal.cpp
|
jfalcou/nucog
|
186808bec04af4f1138bc5362510fffbe690fdd3
|
[
"MIT"
] | null | null | null |
test/unit/api/terminal.cpp
|
jfalcou/nucog
|
186808bec04af4f1138bc5362510fffbe690fdd3
|
[
"MIT"
] | null | null | null |
//==================================================================================================
/**
NuCoG - Numerical Code Generator
Copyright : NuCoG Contributors & Maintainers
SPDX-License-Identifier: MIT
**/
//==================================================================================================
#include "test.hpp"
#include <nucog/expr/terminal.hpp>
TTS_CASE( "Check terminal properties" )
{
using namespace nucog::literal;
auto s1 = $(x_);
TTS_EQUAL( s1.arity(), 0 );
TTS_EQUAL( s1.tag() , nucog::tags::terminal_{} );
TTS_EQUAL( s1.value(), "x_"_sym );
TTS_EQUAL( s1.value().str(), "x_" );
}
| 31.409091
| 100
| 0.413893
|
jfalcou
|
495848907d3023ec87db4db2dde46671f499404e
| 3,311
|
cpp
|
C++
|
src/chess/Loc.cpp
|
owengage/chess
|
777ba282c66ce750a1f1604483b14a99b0122eba
|
[
"Unlicense"
] | null | null | null |
src/chess/Loc.cpp
|
owengage/chess
|
777ba282c66ce750a1f1604483b14a99b0122eba
|
[
"Unlicense"
] | null | null | null |
src/chess/Loc.cpp
|
owengage/chess
|
777ba282c66ce750a1f1604483b14a99b0122eba
|
[
"Unlicense"
] | null | null | null |
#include <chess/Loc.h>
#include <perf/StackVector.h>
#include <unordered_map>
using chess::LocInvalid;
using chess::Loc;
using chess::Sign;
namespace
{
std::vector<Loc> create_all_locs() {
std::vector<Loc> all;
all.reserve(static_cast<std::size_t>(Loc::board_size));
for (int y = 0; y < Loc::side_size; ++y) {
for (int x = 0; x < Loc::side_size; ++x) {
all.emplace_back(x, y);
}
}
return all;
}
perf::StackVector<Loc, Loc::side_size> generate_direction(Loc origin, Sign x, Sign y)
{
auto locs = perf::StackVector<Loc, 8>{};
auto sign_to_hops = [](Sign sign, int start)
{
switch (sign)
{
case Sign::positive:
return Loc::side_size - 1 - start;
case Sign::none:
return Loc::side_size - 1;
case Sign::negative:
return start;
}
};
auto max_hops_x = sign_to_hops(x, origin.x());
auto max_hops_y = sign_to_hops(y, origin.y());
auto max_hops = std::min(max_hops_x, max_hops_y);
auto hop = static_cast<int>(y)*Loc::side_size + static_cast<int>(x);
auto current = origin.index();
for (int i = 0; i < max_hops; ++i)
{
current += hop;
locs.push_back(Loc{current});
}
return locs;
}
std::size_t direction_lookup_index(Loc loc, Sign x, Sign y)
{
auto loc_part = loc.index() << 4;
auto x_part = (static_cast<int>(x) + 1) << 2;
auto y_part = (static_cast<int>(y) + 1);
return loc_part | x_part | y_part;
}
static constexpr std::size_t direction_lookup_size = (64 << 4) + (2 << 2) + 2 + 1;
std::array<perf::StackVector<Loc, 8>, direction_lookup_size> generate_direction_lookup_map()
{
std::array<perf::StackVector<Loc, 8>, direction_lookup_size> map;
std::array<Sign, 3> signs = {Sign::positive, Sign::none, Sign::negative};
for (auto loc : Loc::all_squares())
{
for (auto x : signs)
{
for (auto y : signs)
{
auto key = direction_lookup_index(loc, x, y);
auto value = generate_direction(loc, x, y);
map[key] = value;
}
}
}
return map;
}
auto direction_lookup = generate_direction_lookup_map();
}
LocInvalid::LocInvalid(int x, int y) : std::runtime_error{"Invalid Loc m_x=" + std::to_string(x) + ", y=" + std::to_string(y)}
{}
std::vector<Loc> Loc::row(int y)
{
std::vector<Loc> locs;
locs.reserve(side_size);
for (int i = 0; i < side_size; ++i)
{
locs.emplace_back(i, y);
}
return locs;
}
std::vector<Loc> const& Loc::all_squares()
{
static std::vector<Loc> all = create_all_locs();
return all;
}
perf::StackVector<Loc, Loc::side_size> Loc::direction(Loc origin, Sign x, Sign y)
{
return direction_lookup[direction_lookup_index(origin, x, y)];
}
bool chess::operator==(Loc lhs, Loc rhs)
{
return lhs.m_index == rhs.m_index;
}
bool chess::operator!=(Loc lhs, Loc rhs)
{
return !(lhs == rhs);
}
| 26.488
| 126
| 0.536998
|
owengage
|
4958a96e54b627eab4400680cdac314ae51a30c0
| 9,803
|
cpp
|
C++
|
src/stellar/stellar.arg_parser.cpp
|
marehr/dream_stellar
|
03ffc33cba4336d585108a22c8e166d0fbd7ac4b
|
[
"BSD-3-Clause"
] | null | null | null |
src/stellar/stellar.arg_parser.cpp
|
marehr/dream_stellar
|
03ffc33cba4336d585108a22c8e166d0fbd7ac4b
|
[
"BSD-3-Clause"
] | 16
|
2021-11-12T16:42:35.000Z
|
2022-01-11T15:28:23.000Z
|
src/stellar/stellar.arg_parser.cpp
|
marehr/dream_stellar
|
03ffc33cba4336d585108a22c8e166d0fbd7ac4b
|
[
"BSD-3-Clause"
] | null | null | null |
#include <stellar/app/stellar.arg_parser.hpp>
#include <seqan/seq_io.h>
namespace stellar
{
namespace app
{
///////////////////////////////////////////////////////////////////////////////
// Parses options from command line parser and writes them into options object
ArgumentParser::ParseResult
_parseOptions(ArgumentParser const & parser, StellarOptions & options)
{
getArgumentValue(options.databaseFile, parser, 0);
getArgumentValue(options.queryFile, parser, 1);
// output options
getOptionValue(options.outputFile, parser, "out");
getOptionValue(options.disabledQueriesFile, parser, "outDisabled");
getOptionValue(options.noRT, parser, "no-rt");
CharString tmp = options.outputFile;
toLower(tmp);
if (endsWith(tmp, ".gff"))
options.outputFormat = "gff";
else if (endsWith(tmp, ".txt"))
options.outputFormat = "txt";
// main options
getOptionValue(options.qGram, parser, "kmer");
getOptionValue(options.minLength, parser, "minLength");
getOptionValue(options.epsilon, parser, "epsilon");
getOptionValue(options.xDrop, parser, "xDrop");
getOptionValue(options.alphabet, parser, "alphabet");
getOptionValue(options.threadCount, parser, "threads");
if (isSet(parser, "forward") && !isSet(parser, "reverse"))
options.reverse = false;
if (!isSet(parser, "forward") && isSet(parser, "reverse"))
options.forward = false;
CharString verificationMethod;
getOptionValue(verificationMethod, parser, "verification");
if (verificationMethod == to_string(StellarVerificationMethod{AllLocal{}}))
options.verificationMethod = StellarVerificationMethod{AllLocal{}};
else if (verificationMethod == to_string(StellarVerificationMethod{BestLocal{}}))
options.verificationMethod = StellarVerificationMethod{BestLocal{}};
else if (verificationMethod == to_string(StellarVerificationMethod{BandedGlobal{}}))
options.verificationMethod = StellarVerificationMethod{BandedGlobal{}};
else if (verificationMethod == to_string(StellarVerificationMethod{BandedGlobalExtend{}}))
options.verificationMethod = StellarVerificationMethod{BandedGlobalExtend{}};
else
{
std::cerr << "Invalid parameter value: Please choose one of the --verification={exact, bestLocal, bandedGlobal, bandedGlobalExtend}" << std::endl;
return ArgumentParser::PARSE_ERROR;
}
getOptionValue(options.disableThresh, parser, "disableThresh");
getOptionValue(options.numMatches, parser, "numMatches");
getOptionValue(options.compactThresh, parser, "sortThresh");
getOptionValue(options.maxRepeatPeriod, parser, "repeatPeriod");
getOptionValue(options.minRepeatLength, parser, "repeatLength");
getOptionValue(options.qgramAbundanceCut, parser, "abundanceCut");
getOptionValue(options.verbose, parser, "verbose");
if (isSet(parser, "kmer") && options.qGram >= 1 / options.epsilon)
{
std::cerr << "Invalid parameter value: Please choose q-gram length lower than 1/epsilon." << std::endl;
return ArgumentParser::PARSE_ERROR;
}
if (options.numMatches > options.compactThresh)
{
std::cerr << "Invalid parameter values: Please choose numMatches <= sortThresh." << std::endl;
return ArgumentParser::PARSE_ERROR;
}
return ArgumentParser::PARSE_OK;
}
///////////////////////////////////////////////////////////////////////////////
// Set-Up of Argument Parser
void _setParser(ArgumentParser & parser)
{
setShortDescription(parser, "the SwifT Exact LocaL AligneR");
setDate(parser, SEQAN_DATE);
setVersion(parser, SEQAN_APP_VERSION " [" SEQAN_REVISION "]");
setCategory(parser, "Local Alignment");
addUsageLine(parser, "[\\fIOPTIONS\\fP] <\\fIFASTA FILE 1\\fP> <\\fIFASTA FILE 2\\fP>");
addDescription(parser,
"STELLAR implements the SWIFT filter algorithm (Rasmussen et al., 2006) "
"and a verification step for the SWIFT hits that applies local alignment, "
"gapped X-drop extension, and extraction of the longest epsilon-match.");
addDescription(parser,
"Input to STELLAR are two files, each containing one or more sequences "
"in FASTA format. Each sequence from file 1 will be compared to each "
"sequence in file 2. The sequences from file 1 are used as database, the "
"sequences from file 2 as queries.");
addDescription(parser, "(c) 2010-2012 by Birte Kehr");
addArgument(parser, ArgParseArgument(ArgParseArgument::INPUT_FILE, "FASTA FILE 1"));
setValidValues(parser, 0, "fa fasta"); // allow only fasta files as input
addArgument(parser, ArgParseArgument(ArgParseArgument::INPUT_FILE, "FASTA FILE 2"));
setValidValues(parser, 1, "fa fasta"); // allow only fasta files as input
// Add threads option.
addOption(parser, ArgParseOption("t", "threads", "Specify the number of threads to use.", ArgParseOption::INTEGER));
setMinValue(parser, "threads", "1");
setDefaultValue(parser, "threads", "1");
addSection(parser, "Main Options");
addOption(parser, ArgParseOption("e", "epsilon", "Maximal error rate (max 0.25).", ArgParseArgument::DOUBLE));
setDefaultValue(parser, "e", "0.05");
setMinValue(parser, "e", "0.0000001");
setMaxValue(parser, "e", "0.25");
addOption(parser, ArgParseOption("l", "minLength", "Minimal length of epsilon-matches.", ArgParseArgument::INTEGER));
setDefaultValue(parser, "l", "100");
setMinValue(parser, "l", "0");
addOption(parser, ArgParseOption("f", "forward", "Search only in forward strand of database."));
addOption(parser, ArgParseOption("r", "reverse", "Search only in reverse complement of database."));
addOption(parser, ArgParseOption("a", "alphabet",
"Alphabet type of input sequences (dna, rna, dna5, rna5, protein, char).",
ArgParseArgument::STRING));
setValidValues(parser, "a", "dna dna5 rna rna5 protein char");
addOption(parser, ArgParseOption("v", "verbose", "Set verbosity mode."));
addSection(parser, "Filtering Options");
addOption(parser, ArgParseOption("k", "kmer", "Length of the q-grams (max 32).", ArgParseArgument::INTEGER));
setMinValue(parser, "k", "1");
setMaxValue(parser, "k", "32");
addOption(parser, ArgParseOption("rp", "repeatPeriod",
"Maximal period of low complexity repeats to be filtered.", ArgParseArgument::INTEGER));
setDefaultValue(parser, "rp", "1");
addOption(parser, ArgParseOption("rl", "repeatLength",
"Minimal length of low complexity repeats to be filtered.", ArgParseArgument::INTEGER));
setDefaultValue(parser, "rl", "1000");
addOption(parser, ArgParseOption("c", "abundanceCut", "k-mer overabundance cut ratio.", ArgParseArgument::DOUBLE));
setDefaultValue(parser, "c", "1");
setMinValue(parser, "c", "0");
setMaxValue(parser, "c", "1");
addSection(parser, "Verification Options");
addOption(parser, ArgParseOption("x", "xDrop", "Maximal x-drop for extension.", ArgParseArgument::DOUBLE));
setDefaultValue(parser, "x", "5");
addOption(parser, ArgParseOption("vs", "verification", "Verification strategy: exact or bestLocal or bandedGlobal",
ArgParseArgument::STRING));
//addHelpLine(parser, "exact = compute and extend all local alignments in SWIFT hits");
//addHelpLine(parser, "bestLocal = compute and extend only best local alignment in SWIFT hits");
//addHelpLine(parser, "bandedGlobal = banded global alignment on SWIFT hits");
setDefaultValue(parser, "vs", "exact");
setValidValues(parser, "vs", "exact bestLocal bandedGlobal");
addOption(parser, ArgParseOption("dt", "disableThresh",
"Maximal number of verified matches before disabling verification for one query "
"sequence (default infinity).", ArgParseArgument::INTEGER));
setMinValue(parser, "dt", "0");
addOption(parser, ArgParseOption("n", "numMatches",
"Maximal number of kept matches per query and database. If STELLAR finds more matches, "
"only the longest ones are kept.", ArgParseArgument::INTEGER));
setDefaultValue(parser, "n", "50");
addOption(parser, ArgParseOption("s", "sortThresh",
"Number of matches triggering removal of duplicates. Choose a smaller value for saving "
"space.", ArgParseArgument::INTEGER));
setDefaultValue(parser, "s", "500");
addSection(parser, "Output Options");
addOption(parser, ArgParseOption("o", "out", "Name of output file.", ArgParseArgument::OUTPUT_FILE));
setValidValues(parser, "o", "gff txt");
setDefaultValue(parser, "o", "stellar.gff");
addOption(parser, ArgParseOption("od", "outDisabled",
"Name of output file for disabled query sequences.", ArgParseArgument::OUTPUT_FILE));
setValidValues(parser, "outDisabled", seqan::SeqFileOut::getFileExtensions());
setDefaultValue(parser, "od", "stellar.disabled.fasta");
addOption(parser, ArgParseOption("no-rt", "suppress-runtime-printing", "Suppress printing running time."));
hideOption(parser, "no-rt");
addTextSection(parser, "References");
addText(parser, "Kehr, B., Weese, D., Reinert, K.: STELLAR: fast and exact local alignments. BMC Bioinformatics, "
"12(Suppl 9):S15, 2011.");
}
} // namespace stellar::app
} // namespace stellar
| 50.530928
| 154
| 0.656738
|
marehr
|
4958e0e4495d1dcfdd543aa69b57e04b3080d15d
| 542
|
cpp
|
C++
|
leetcode/1328. Break a Palindrome/s1.cpp
|
joycse06/LeetCode-1
|
ad105bd8c5de4a659c2bbe6b19f400b926c82d93
|
[
"Fair"
] | 1
|
2021-02-11T01:23:10.000Z
|
2021-02-11T01:23:10.000Z
|
leetcode/1328. Break a Palindrome/s1.cpp
|
aerlokesh494/LeetCode
|
0f2cbb28d5a9825b51a8d3b3a0ae0c30d7ff155f
|
[
"Fair"
] | 1
|
2021-08-08T18:44:24.000Z
|
2021-08-08T18:44:24.000Z
|
leetcode/1328. Break a Palindrome/s1.cpp
|
aerlokesh494/LeetCode
|
0f2cbb28d5a9825b51a8d3b3a0ae0c30d7ff155f
|
[
"Fair"
] | 1
|
2021-03-25T17:11:14.000Z
|
2021-03-25T17:11:14.000Z
|
// OJ: https://leetcode.com/problems/break-a-palindrome/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
public:
string breakPalindrome(string palindrome) {
int N = palindrome.size(), end = N / 2;
for (int i = 0; i < end; ++i) {
if (palindrome[i] != 'a') {
palindrome[i] = 'a';
return palindrome;
}
}
if (N > 1) {
palindrome[N - 1] = 'b';
return palindrome;
}
return "";
}
};
| 25.809524
| 56
| 0.46679
|
joycse06
|
495ad89e432ab9f0af10b5534737b962cd0de0d5
| 441
|
cpp
|
C++
|
class/constructors.cpp
|
Abhilekhgautam/Cpp-college
|
3101cb061e36eee9d42226a8cfaf86ad5c695ef2
|
[
"CC0-1.0"
] | 1
|
2021-07-22T08:38:25.000Z
|
2021-07-22T08:38:25.000Z
|
class/constructors.cpp
|
Abhilekhgautam/Cpp-college
|
3101cb061e36eee9d42226a8cfaf86ad5c695ef2
|
[
"CC0-1.0"
] | null | null | null |
class/constructors.cpp
|
Abhilekhgautam/Cpp-college
|
3101cb061e36eee9d42226a8cfaf86ad5c695ef2
|
[
"CC0-1.0"
] | null | null | null |
/* A c++ program to describe "objects are destroyed int reverse order of their creation"*/
#include<iostream>
class Table{
public:
Table(){std::cout<<"Object Created"<<'\n';}
~Table(){std::cout<<"Object Destoyed"<<'\n';}
};
void f(int i)
{
Table aa;
Table bb;
if(i>0){
//cc will be created after bb and destroyed before dd is created
Table cc;
}
Table dd;
}
int main(){
f(1);
return 0;
}
| 17.64
| 90
| 0.589569
|
Abhilekhgautam
|
495d1ce5531b5f88d17985d2c1a900531e11b56a
| 484
|
cpp
|
C++
|
src/core/test/src/net/test_Socket.cpp
|
SimpleTalkCpp/libsita
|
e0c13f16cebf799f0d57b8345d21de7407f59e2b
|
[
"MIT"
] | 2
|
2021-03-19T13:19:27.000Z
|
2021-04-03T17:42:30.000Z
|
src/core/test/src/net/test_Socket.cpp
|
SimpleTalkCpp/libsita
|
e0c13f16cebf799f0d57b8345d21de7407f59e2b
|
[
"MIT"
] | null | null | null |
src/core/test/src/net/test_Socket.cpp
|
SimpleTalkCpp/libsita
|
e0c13f16cebf799f0d57b8345d21de7407f59e2b
|
[
"MIT"
] | null | null | null |
#include <sita_core/base/UnitTest.h>
#include <sita_core/net/Socket.h>
namespace sita {
class Test_Socket : public UnitTestBase {
public:
void test_resolveIPv4() {
Vector<int> a;
IPv4 ip;
ip.resolve("localhost");
SITA_DUMP_VAR(ip);
SITA_TEST_CHECK(ip == IPv4(127,0,0,1));
SITA_TEST_CHECK_SLIENT(ip == IPv4(127,0,0,1));
}
};
} // namespace
void test_Socket() {
using namespace sita;
SITA_TEST_CASE(Test_Socket, test_resolveIPv4());
}
| 17.925926
| 50
| 0.663223
|
SimpleTalkCpp
|
495d6d0beddca557ede7775b6206744dafd4081b
| 582
|
cpp
|
C++
|
snippets/cpp/VS_Snippets_Data/Classic WebData XmlElement.SetAttributeNode1 Example/CPP/source.cpp
|
BohdanMosiyuk/samples
|
59d435ba9e61e0fc19f5176c96b1cdbd53596142
|
[
"CC-BY-4.0",
"MIT"
] | 2
|
2020-03-12T19:26:36.000Z
|
2022-01-10T21:45:33.000Z
|
snippets/cpp/VS_Snippets_Data/Classic WebData XmlElement.SetAttributeNode1 Example/CPP/source.cpp
|
BohdanMosiyuk/samples
|
59d435ba9e61e0fc19f5176c96b1cdbd53596142
|
[
"CC-BY-4.0",
"MIT"
] | 555
|
2019-09-23T22:22:58.000Z
|
2021-07-15T18:51:12.000Z
|
snippets/cpp/VS_Snippets_Data/Classic WebData XmlElement.SetAttributeNode1 Example/CPP/source.cpp
|
BohdanMosiyuk/samples
|
59d435ba9e61e0fc19f5176c96b1cdbd53596142
|
[
"CC-BY-4.0",
"MIT"
] | 3
|
2020-01-29T16:31:15.000Z
|
2021-08-24T07:00:15.000Z
|
// <Snippet1>
#using <System.Xml.dll>
using namespace System;
using namespace System::IO;
using namespace System::Xml;
int main()
{
XmlDocument^ doc = gcnew XmlDocument;
doc->LoadXml( "<book xmlns:bk='urn:samples' bk:ISBN='1-861001-57-5'><title>Pride And Prejudice</title></book>" );
XmlElement^ root = doc->DocumentElement;
// Add a new attribute.
XmlAttribute^ attr = root->SetAttributeNode( "genre", "urn:samples" );
attr->Value = "novel";
Console::WriteLine( "Display the modified XML..." );
Console::WriteLine( doc->InnerXml );
}
// </Snippet1>
| 25.304348
| 116
| 0.670103
|
BohdanMosiyuk
|
495d74a4b2c72b6b43a2f4ca7d741b10949046a2
| 5,119
|
cpp
|
C++
|
src/modules/MouseUtils/FindMyMouse/dllmain.cpp
|
szlatkow/PowerToys
|
e62df46c6181551e80b7ce2cf85f03beccbfadf2
|
[
"MIT"
] | 3
|
2021-11-21T03:03:41.000Z
|
2021-11-21T23:57:28.000Z
|
src/modules/MouseUtils/FindMyMouse/dllmain.cpp
|
szlatkow/PowerToys
|
e62df46c6181551e80b7ce2cf85f03beccbfadf2
|
[
"MIT"
] | 9
|
2021-05-12T17:12:35.000Z
|
2021-10-30T14:57:56.000Z
|
src/modules/MouseUtils/FindMyMouse/dllmain.cpp
|
szlatkow/PowerToys
|
e62df46c6181551e80b7ce2cf85f03beccbfadf2
|
[
"MIT"
] | 2
|
2021-05-26T09:02:21.000Z
|
2021-05-26T09:02:22.000Z
|
#include "pch.h"
#include <interface/powertoy_module_interface.h>
#include <common/SettingsAPI/settings_objects.h>
#include "trace.h"
#include "FindMyMouse.h"
#include <thread>
#include <common/utils/logger_helper.h>
namespace
{
const wchar_t JSON_KEY_PROPERTIES[] = L"properties";
const wchar_t JSON_KEY_VALUE[] = L"value";
const wchar_t JSON_KEY_DO_NOT_ACTIVATE_ON_GAME_MODE[] = L"do_not_activate_on_game_mode";
}
extern "C" IMAGE_DOS_HEADER __ImageBase;
HMODULE m_hModule;
BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
m_hModule = hModule;
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
Trace::RegisterProvider();
break;
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
break;
case DLL_PROCESS_DETACH:
Trace::UnregisterProvider();
break;
}
return TRUE;
}
// The PowerToy name that will be shown in the settings.
const static wchar_t* MODULE_NAME = L"FindMyMouse";
// Add a description that will we shown in the module settings page.
const static wchar_t* MODULE_DESC = L"Focus the mouse pointer";
// Implement the PowerToy Module Interface and all the required methods.
class FindMyMouse : public PowertoyModuleIface
{
private:
// The PowerToy state.
bool m_enabled = false;
// Load initial settings from the persisted values.
void init_settings();
// Helper function to extract the settings
void parse_settings(PowerToysSettings::PowerToyValues& settings);
public:
// Constructor
FindMyMouse()
{
LoggerHelpers::init_logger(MODULE_NAME, L"ModuleInterface", LogSettings::findMyMouseLoggerName);
init_settings();
};
// Destroy the powertoy and free memory
virtual void destroy() override
{
delete this;
}
// Return the localized display name of the powertoy
virtual const wchar_t* get_name() override
{
return MODULE_NAME;
}
// Return the non localized key of the powertoy, this will be cached by the runner
virtual const wchar_t* get_key() override
{
return MODULE_NAME;
}
// Return JSON with the configuration options.
virtual bool get_config(wchar_t* buffer, int* buffer_size) override
{
HINSTANCE hinstance = reinterpret_cast<HINSTANCE>(&__ImageBase);
// Create a Settings object.
PowerToysSettings::Settings settings(hinstance, get_name());
settings.set_description(MODULE_DESC);
return settings.serialize_to_buffer(buffer, buffer_size);
}
// Signal from the Settings editor to call a custom action.
// This can be used to spawn more complex editors.
virtual void call_custom_action(const wchar_t* action) override
{
}
// Called by the runner to pass the updated settings values as a serialized JSON.
virtual void set_config(const wchar_t* config) override
{
try
{
// Parse the input JSON string.
PowerToysSettings::PowerToyValues values =
PowerToysSettings::PowerToyValues::from_json_string(config, get_key());
parse_settings(values);
values.save_to_settings_file();
}
catch (std::exception&)
{
// Improper JSON.
}
}
// Enable the powertoy
virtual void enable()
{
m_enabled = true;
Trace::EnableFindMyMouse(true);
std::thread([]() { FindMyMouseMain(m_hModule); }).detach();
}
// Disable the powertoy
virtual void disable()
{
m_enabled = false;
Trace::EnableFindMyMouse(false);
FindMyMouseDisable();
}
// Returns if the powertoys is enabled
virtual bool is_enabled() override
{
return m_enabled;
}
};
// Load the settings file.
void FindMyMouse::init_settings()
{
try
{
// Load and parse the settings file for this PowerToy.
PowerToysSettings::PowerToyValues settings =
PowerToysSettings::PowerToyValues::load_from_settings_file(FindMyMouse::get_key());
parse_settings(settings);
}
catch (std::exception&)
{
// Error while loading from the settings file. Let default values stay as they are.
}
}
void FindMyMouse::parse_settings(PowerToysSettings::PowerToyValues& settings)
{
FindMyMouseSetDoNotActivateOnGameMode(true);
auto settingsObject = settings.get_raw_json();
if (settingsObject.GetView().Size())
{
try
{
auto jsonPropertiesObject = settingsObject.GetNamedObject(JSON_KEY_PROPERTIES).GetNamedObject(JSON_KEY_DO_NOT_ACTIVATE_ON_GAME_MODE);
FindMyMouseSetDoNotActivateOnGameMode((bool)jsonPropertiesObject.GetNamedBoolean(JSON_KEY_VALUE));
}
catch (...)
{
Logger::warn("Failed to get 'do not activate on game mode' setting");
}
}
else
{
Logger::info("Find My Mouse settings are empty");
}
}
extern "C" __declspec(dllexport) PowertoyModuleIface* __cdecl powertoy_create()
{
return new FindMyMouse();
}
| 27.521505
| 145
| 0.671616
|
szlatkow
|
4964b54bcc941dd66b264ede259bbf384a01cb92
| 416
|
cpp
|
C++
|
functions/prime_between_two_nums.cpp
|
sahilduhan/Learn-C-plus-plus
|
80dba2ee08b36985deb297293a0318da5d6ace94
|
[
"RSA-MD"
] | null | null | null |
functions/prime_between_two_nums.cpp
|
sahilduhan/Learn-C-plus-plus
|
80dba2ee08b36985deb297293a0318da5d6ace94
|
[
"RSA-MD"
] | null | null | null |
functions/prime_between_two_nums.cpp
|
sahilduhan/Learn-C-plus-plus
|
80dba2ee08b36985deb297293a0318da5d6ace94
|
[
"RSA-MD"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
bool prime_between_two_nums(int num)
{
for (int i = 2; i < sqrt(num); i++)
if (num % 2 == 0)
{
return false;
}
else
{
return true;
}
}
int main()
{
int a, b;
for (int i = a; i <= b; i++)
{
if (prime_between_two_nums(i))
cout << i << endl;
}
return 0;
}
| 16
| 39
| 0.427885
|
sahilduhan
|
496bf95d0aaecdc00598dc9fb87e2231003b1054
| 2,591
|
cpp
|
C++
|
ffl/source/utils/FFL_Clock.cpp
|
zhenfei2016/FFL-v2
|
376c79a0611af580d4767a4bbb05822f1a4fd454
|
[
"MIT"
] | null | null | null |
ffl/source/utils/FFL_Clock.cpp
|
zhenfei2016/FFL-v2
|
376c79a0611af580d4767a4bbb05822f1a4fd454
|
[
"MIT"
] | null | null | null |
ffl/source/utils/FFL_Clock.cpp
|
zhenfei2016/FFL-v2
|
376c79a0611af580d4767a4bbb05822f1a4fd454
|
[
"MIT"
] | null | null | null |
/*
* This file is part of FFL project.
*
* The MIT License (MIT)
* Copyright (C) 2017-2018 zhufeifei All rights reserved.
*
* FFL_Clock.cpp
* Created by zhufeifei(34008081@qq.com) on 2018/04/29
* https://github.com/zhenfei2016/FFL-v2.git
*
* 时钟类,可以获取当前时间,改变时钟速度,修改时钟原点偏移
* y=ax +b
*/
#include <utils/FFL_Clock.hpp>
namespace FFL {
//
// y=(a/KA_RATIO) x +b
// 当前设置的a参数的放大倍数,实际的值= a/KA_RATIO
//
//
static const int64_t KA_RATIO = 100;
//
// y=x*a /KA_RATIO
//
static int64_t getY(int64_t x, int64_t a) {
return (int64_t)((double)(x * a) / KA_RATIO);
}
Clock::Clock():mListener(NULL){
reset();
}
Clock::~Clock() {
}
void Clock::reset() {
mB = 0;
mA = KA_RATIO;
}
IClockListener* Clock::setListener(IClockListener* listener){
IClockListener* ret = mListener;
mListener=listener;
return ret;
}
//
// 当前时间
//
int64_t Clock::nowUs() {
return nowUs(0);
}
//
// 这个时钟的当前时间 systemUs:返回系统时钟的时间
//
int64_t Clock::nowUs(int64_t* systemUs) {
int64_t now = FFL_getNowUs();
if (systemUs) {
*systemUs = now;
}
if (equalSystemClock()) {
return now;
}
//
// 转化到当前时钟的时间值
// y=ax +b
//
int64_t clockNow = getY(now, mA) + mB;
FFL_LOG_INFO("Clock x:%" lld64 " y:%" lld64 "a=%" lld64 " b=%" lld64, now, clockNow, mA, mB);
return clockNow;
}
//
// 转换当前时钟的一个时间段转成系统时钟时间段
// 例如可以把当前时钟5分钟转成系统时钟8分钟
//
int64_t Clock::clockToWorldTimeBucket(int64_t dy) {
//
// y=ax+b
// 计算dx
//
return (int64_t)(double)(dy * 100) / mA;
}
int64_t Clock::SystemToClockRelativeUs(int64_t dx) {
//
// y=ax+b
// 计算dy
//
return (int64_t)((double)(dx * mA) / 100);
}
int64_t Clock::worldToClockUs(int64_t x) {
//
// y=ax+b
// 计算dy
//
return (int64_t)getY(x, mA) + mB;
}
//
// 时钟速度,默认1.0时正常时钟值
//
uint32_t Clock::speed() {
return mA;
}
void Clock::setSpeed(uint32_t percent) {
if (percent != mA) {
int64_t x;
int64_t y = nowUs(&x);
//
// 计算新的a,b参数
// b=y-ax
//
uint32_t oldA=mA;
mA = percent;
mB = y - (int64_t)((double)(mA* x) / KA_RATIO);
if(mListener){
int32_t type=0;
if(percent>oldA)
type=1;
else if(percent<oldA)
type=-1;
mListener->onSpeedChange(type, mA);
}
}
}
//
// 偏移
//
int64_t Clock::offset() {
return mOffset;
}
void Clock::setOffset(int64_t offset) {
mOffset = offset;
}
//
// 是否系统时钟一致的
//
bool Clock::equalSystemClock() {
return mA == KA_RATIO;
}
}
| 17.868966
| 95
| 0.565033
|
zhenfei2016
|
496c85b7a32734eabd51d4fa2d7f9cce3a028f70
| 2,001
|
cpp
|
C++
|
nmainwindow.cpp
|
NeoProject/NeoPaintPrototype
|
ebfca88f7ddc2011daebf6d221c8e099f6e03645
|
[
"Info-ZIP"
] | null | null | null |
nmainwindow.cpp
|
NeoProject/NeoPaintPrototype
|
ebfca88f7ddc2011daebf6d221c8e099f6e03645
|
[
"Info-ZIP"
] | null | null | null |
nmainwindow.cpp
|
NeoProject/NeoPaintPrototype
|
ebfca88f7ddc2011daebf6d221c8e099f6e03645
|
[
"Info-ZIP"
] | null | null | null |
#include "nmainwindow.h"
#include "NGadget/nstatusbar.h"
#include "NGadget/nmenubar.h"
#include "NGadget/ntoolbar.h"
#include <QLabel>
#include <NCanvas/ncanvas.h>
#include "NGadget/nabout.h"
#include "NCanvas/ntabwidget.h"
#include <QMenu>
#include <QAction>
#include "NGadget/ntablettest.h"
#include "NDockWidget/ndockwidget.h"
#include "NGadget/nabout.h"
#include "NGadget/ntablettest.h"
#include "NCanvas/ncanvasview.h"
NMainWindow::NMainWindow(QWidget *parent)
: QMainWindow(parent),
neoStatusBar(new NStatusBar(this)),
neoMenuBar(new NMenuBar(this)),
neoToolBar(new NToolBar(this)),
neoTabWidget(new NTabWidget(this)),
neoPrototype(new NDockWidget(this)),
neoAbout(new NAbout(tr("NeoPaintPrototype"))),
neoTabletTest(new NTabletTest)
{
initWidget();
initConnection();
setDockNestingEnabled(true);
neoPrototype->setAllowedAreas(Qt::LeftDockWidgetArea);
neoPrototype->setMinimumWidth(300);
// neoTabWidget->nCanvas->setMessage(neoStatusBar->nStatusMessage);
}
NMainWindow::~NMainWindow()
{
}
void NMainWindow::initWidget()
{
setStatusBar(neoStatusBar);
setMenuBar(neoMenuBar);
addToolBar(neoToolBar);
setCentralWidget(neoTabWidget);
addDockWidget(Qt::LeftDockWidgetArea, neoPrototype);
}
void NMainWindow::initConnection()
{
connect(neoMenuBar->NFile.Close, &QAction::triggered, this, &NMainWindow::close);
connect(neoMenuBar->NHelp.About, &QAction::triggered, neoAbout, &NAbout::show);
connect(neoMenuBar->NHelp.TabletTest, &QAction::triggered, neoTabletTest, &NTabletTest::show);
connect(neoMenuBar->NFile.New, &QAction::triggered, neoTabWidget, &NTabWidget::newCanvas);
// connect(neoMenuBar, &NMenuBar::sendFileName, neoTabWidget->nView, &NCanvasView::openFile);
// connect(neoMenuBar, &NMenuBar::sendSaveFileName, neoTabWidget->nView, &NCanvasView::saveFile);
// connect(neoTabWidget->nCanvas, &NCanvas::tabletStatusChanged, neoStatusBar, &NStatusBar::changeStatus);
}
| 31.761905
| 109
| 0.74013
|
NeoProject
|
4971d7fbcdd6db28eff49825d3b8a5b959f4e86a
| 3,757
|
cpp
|
C++
|
Project/Part Five: Data Cache/Code/CacheStats.cpp
|
HernandezDerekJ/Computer-Architecture-3339
|
03785b02169a76ca0b1b38205bd5e64adde2b727
|
[
"MIT"
] | null | null | null |
Project/Part Five: Data Cache/Code/CacheStats.cpp
|
HernandezDerekJ/Computer-Architecture-3339
|
03785b02169a76ca0b1b38205bd5e64adde2b727
|
[
"MIT"
] | null | null | null |
Project/Part Five: Data Cache/Code/CacheStats.cpp
|
HernandezDerekJ/Computer-Architecture-3339
|
03785b02169a76ca0b1b38205bd5e64adde2b727
|
[
"MIT"
] | null | null | null |
/******************************
* CacheStats.cpp submitted by: Derek Hernandez (djh119)
* CS 3339 - Spring 2019
* Project 4 Branch Predictor
* Copyright 2019, all rights reserved
* Updated by Lee B. Hinkle based on prior work by Martin Burtscher and Molly O'Neil
******************************/
#include <iostream>
#include <cstdlib>
#include <iomanip>
#include "CacheStats.h"
using namespace std;
CacheStats::CacheStats() {
cout << "Cache Config: ";
if(!CACHE_EN) {
cout << "cache disabled" << endl;
} else {
cout << (SETS * WAYS * BLOCKSIZE) << " B (";
cout << BLOCKSIZE << " bytes/block, " << SETS << " sets, " << WAYS << " ways)" << endl;
cout << " Latencies: Lookup = " << LOOKUP_LATENCY << " cycles, ";
cout << "Read = " << READ_LATENCY << " cycles, ";
cout << "Write = " << WRITE_LATENCY << " cycles" << endl;
}
loads = 0;
stores = 0;
load_misses = 0;
store_misses = 0;
writebacks = 0;
/* TODO: your code here */
tag = uint32_t(0);
index = uint32_t(0);
stallLatency = 0;
for(int a = 0; a < SETS; a++){
w[a]=0;
for(int b = 0; b < WAYS; b++){
tags[a][b] = uint32_t(0);
modify[a][b] = 0;
valid[a][b] = 0;
}
}
}
int CacheStats::access(uint32_t addr, ACCESS_TYPE type) {
if(!CACHE_EN) { // cache is off
return (type == LOAD) ? READ_LATENCY : WRITE_LATENCY;
}
/* TODO: your code here */
// Vars
// Offset == log2 (32)
// Set == 3 (2^3)
index = (addr >> 5) & 0x7;
//Data to store
tag = addr >> 8;
//Reset Stall
stallLatency = 0;
//Loads and Stores
if (type == STORE)
stores++;
else if(type == LOAD)
loads++;
//HIT
//tags match and its not empty(vaild)
for(int a = 0; a < WAYS; a++){
if((tags[index][a] == tag) && (valid[index][a])){
stallLatency = LOOKUP_LATENCY;
if(type == STORE)
modify[index][a] = 1;
return stallLatency;
}
}
// Miss two types Clean, Dirty
if(type == STORE)
store_misses++;
else if(type == LOAD)
load_misses++;
//Clean Modify == 0 Latency == 30
if(modify[index][w[index]] == 0){
stallLatency = stallLatency + READ_LATENCY;
}
//Dirty Modify == 1 Latency == 10+30
else if(modify[index][w[index]] == 1){
stallLatency = stallLatency + READ_LATENCY + WRITE_LATENCY;
writebacks++;
}
//Install into cache
tags[index][w[index]] = tag;
valid[index][w[index]] = 1;
//Determine Modify,based on type
if(type == LOAD){
modify[index][w[index]] = 0;
}
else if(type == STORE){
modify[index][w[index]] = 1;
}
//Control w values, round robin 4 way, never go over 3
if (w[index] == 3){
w[index] = 0;
}
else{
w[index]++;
}
return stallLatency;
}
void CacheStats::printFinalStats() {
/* TODO: your code here (don't forget to drain the cache of writebacks) */
// Write Back == Dirty/Modified (Whenever modify is true)
for(int x = 0; x < SETS; x++){
for(int y = 0; y < WAYS; y++){
if(modify[x][y])
writebacks++;
}
}
int accesses = loads + stores;
int misses = load_misses + store_misses;
cout << "Accesses: " << accesses << endl;
cout << " Loads: " << loads << endl;
cout << " Stores: " << stores << endl;
cout << "Misses: " << misses << endl;
cout << " Load misses: " << load_misses << endl;
cout << " Store misses: " << store_misses << endl;
cout << "Writebacks: " << writebacks << endl;
cout << "Hit Ratio: " << fixed << setprecision(1) << 100.0 * (accesses - misses) / accesses;
cout << "%" << endl;
}
| 28.24812
| 94
| 0.526218
|
HernandezDerekJ
|
49724ecba26a56c2e2550a77eae9f9b0eabb32ef
| 2,919
|
cpp
|
C++
|
application/CMatrix.cpp
|
HO-COOH/Console
|
f6132e4135db0c5432a2943a8f5f367a6ce1167d
|
[
"MIT"
] | 3
|
2020-06-05T05:18:32.000Z
|
2021-07-29T01:13:07.000Z
|
application/CMatrix.cpp
|
HO-COOH/Console
|
f6132e4135db0c5432a2943a8f5f367a6ce1167d
|
[
"MIT"
] | null | null | null |
application/CMatrix.cpp
|
HO-COOH/Console
|
f6132e4135db0c5432a2943a8f5f367a6ce1167d
|
[
"MIT"
] | null | null | null |
#include "Console.h"
#include "ConsoleEngine.h"
#include "TimedEvent.hpp"
#include <iostream>
#include <thread>
#include <random>
#include <vector>
#include <array>
#include <functional>
static std::mt19937 rdEng{ std::random_device{}() };
char randomChar()
{
static std::uniform_int_distribution<int> rdNum{ '!', '}' };
return rdNum(rdEng);
}
int main(int argc, char** argv)
{
ConsoleEngine eng{ console };
eng.setAsciiMode();
const auto width = console.getWidth();
const auto height = console.getHeight();
std::uniform_int_distribution rdNumHeight{ 0, (int)height };
std::vector<short> head( width, 0);
std::vector<short> tail( width, 0);
std::vector<short> length(width, 0);
std::vector<bool> hasContent(width);
ScopedTimer t{ 60000 };
std::vector<short> emptyCol;
emptyCol.reserve(width);
while (true)
{
/*Get empty columns*/
for (auto col = 0; col < width; ++col)
{
if (!hasContent[col])
emptyCol.push_back(col);
}
/*select some empty columns*/
if (emptyCol.size() > width/2)
{
std::array<short, 10> toFill;
std::uniform_int_distribution rd{ 0, static_cast<int>(emptyCol.size() - 1) };
std::generate(toFill.begin(), toFill.end(), [&rd, &emptyCol] {return emptyCol[rd(rdEng)]; });
for (auto& col : toFill)
{
eng.buffer(0, col).Char.AsciiChar = randomChar();
eng.buffer(0, col).Attributes = static_cast<WORD>(Color::WHITE) | FOREGROUND_INTENSITY;
hasContent[col] = true;
head[col] = 1;
length[col] = rdNumHeight(rdEng);
}
}
for (auto i = 0; i < width; ++i)
{
/*generate a random char at [head] position*/
if (hasContent[i])
{
if (head[i] != 0)
{
eng.buffer(head[i], i).Char.AsciiChar = randomChar();
eng.buffer(head[i] - 1, i).Attributes = static_cast<WORD>(Color::GREEN) | FOREGROUND_INTENSITY;
eng.buffer(head[i], i).Attributes = static_cast<WORD>(Color::WHITE) | FOREGROUND_INTENSITY;
++head[i];
if (head[i] >= height)
head[i] = 0;
}
/*delete the char at [tail] position */
if ( head[i]==0||head[i]-tail[i] >= length[i])
{
eng.buffer(tail[i], i).Char.AsciiChar = ' ';
++tail[i];
if (tail[i] >= height)
{
tail[i] = 0;
hasContent[i] = false;
}
}
}
}
eng.draw();
emptyCol.clear();
t.wait();
}
}
| 31.053191
| 115
| 0.488866
|
HO-COOH
|
49777283d6c10ab1c31f8cbaa2667c61dda384cf
| 3,352
|
hh
|
C++
|
geometry2.hh
|
lnw/nano-tori
|
5f43722085154c9315ada572108a360e6601dd1a
|
[
"BSD-2-Clause-FreeBSD"
] | null | null | null |
geometry2.hh
|
lnw/nano-tori
|
5f43722085154c9315ada572108a360e6601dd1a
|
[
"BSD-2-Clause-FreeBSD"
] | null | null | null |
geometry2.hh
|
lnw/nano-tori
|
5f43722085154c9315ada572108a360e6601dd1a
|
[
"BSD-2-Clause-FreeBSD"
] | null | null | null |
// Copyright (c) 2019, Lukas Wirz
// All rights reserved.
// This file is part of 'nano-tori' which is released under the BSD-2-clause license.
// See file LICENSE in this project.
#ifndef GEOMETRY2_HH
#define GEOMETRY2_HH
#include <cassert>
#include <cmath>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include "auxiliary.hh"
using namespace std;
struct matrix2d;
struct coord2d {
double x[2];
coord2d(const double y[2]) { x[0] = y[0]; x[1] = y[1]; }
explicit coord2d(const double x_=0, const double y=0) { x[0] = x_; x[1] = y; }
coord2d operator/(const double s) const { return coord2d(*this) /= s; }
coord2d operator*(const double s) const { return coord2d(*this) *= s; }
coord2d operator+(const coord2d& y) const { return coord2d(*this) += y; }
coord2d operator-(const coord2d& y) const { return coord2d(*this) -= y; }
coord2d& operator+=(const coord2d& y){ x[0] += y[0]; x[1] += y[1]; return *this; }
coord2d& operator-=(const coord2d& y){ x[0] -= y[0]; x[1] -= y[1]; return *this; }
coord2d& operator*=(const double& y){ x[0] *= y; x[1] *= y; return *this; }
coord2d& operator/=(const double& y){ x[0] /= y; x[1] /= y; return *this; }
coord2d operator-() const {coord2d y(-x[0],-x[1]); return y;}
coord2d operator*(const matrix2d& m) const;
double& operator[](unsigned int i){ return x[i]; }
double operator[](unsigned int i) const { return x[i]; }
double norm() const {return sqrt(x[0]*x[0] + x[1]*x[1]);}
friend ostream& operator<<(ostream& S, const coord2d &c2) {
S << "{" << c2[0] << ", " << c2[1] << "}";
return S;
}
};
coord2d operator*(const double &d, const coord2d &c2d);
struct structure2d {
vector<coord2d> dat;
vector<coord2d>::iterator begin(){return dat.begin();}
vector<coord2d>::iterator end(){return dat.end();}
structure2d operator*(const matrix2d& m) const;
coord2d& operator[](unsigned int i){ return dat[i]; }
coord2d operator[](unsigned int i) const { return dat[i]; }
void push_back(const coord2d &c2d){dat.push_back(c2d);}
size_t size() const {return dat.size();}
bool contains(coord2d p) const;
void crop(double x1, double y1, double x2, double y2);
// assume that all points are consecutive, and both ends are connected
// if the curve is self-intersecting, every intersection changes the sign, but the total sign is positive
double area() const;
friend ostream& operator<<(ostream& S, const structure2d &s2) {
S << s2.dat;
return S;
}
};
struct matrix2d {
double values[4];
explicit matrix2d(const double w=0, const double x=0, const double y=0, const double z=0) { // (0,0), (0,1), (1,0), (1,1)
values[0]=w; values[1]=x; values[2]=y; values[3]=z;
}
double& operator()(int i, int j) { return values[i*2+j]; } // i: row, j: column
double operator()(int i, int j) const { return values[i*2+j]; }
double& operator[](unsigned int i) { return values[i]; }
double operator[](unsigned int i) const { return values[i]; }
coord2d operator*(const coord2d& c2d) const;
structure2d operator*(const structure2d& s2d) const;
friend ostream& operator<<(ostream& S, const matrix2d &M) {
S << "{"; for(int i=0;i<2;i++) S << vector<double>(&M.values[i*2],&M.values[(i+1)*2]) << (i+1<2?",":"}");
return S;
}
};
#endif
| 31.622642
| 123
| 0.636038
|
lnw
|
497938523755e3be70e0d1cc9bdad40f50ed3590
| 4,777
|
cpp
|
C++
|
playlistTable.cpp
|
allenyin/musicplayer2
|
429c5e86afc01df21161023d359826d65c9b35ec
|
[
"MIT"
] | 1
|
2016-06-05T15:14:22.000Z
|
2016-06-05T15:14:22.000Z
|
playlistTable.cpp
|
allenyin/musicplayer2
|
429c5e86afc01df21161023d359826d65c9b35ec
|
[
"MIT"
] | null | null | null |
playlistTable.cpp
|
allenyin/musicplayer2
|
429c5e86afc01df21161023d359826d65c9b35ec
|
[
"MIT"
] | 1
|
2019-04-17T15:19:08.000Z
|
2019-04-17T15:19:08.000Z
|
#include "playlistTable.h"
#include "playlistmodel.h"
#include <stdio.h>
#include <iostream>
#include <QApplication>
#include <QHeaderView>
#include <QMimeData>
#include <QDebug>
class PlaylistModel;
PlaylistTable::PlaylistTable(QWidget* parent) : QTableView(parent) {
// edit only when F2 is pressed
setEditTriggers(QAbstractItemView::EditKeyPressed);
setAlternatingRowColors(true);
// entire row is selected when any item is clicked
setSelectionBehavior(QAbstractItemView::SelectRows);
setSelectionMode(QAbstractItemView::ContiguousSelection);
// enable drag and drop
setDragEnabled(true);
setAcceptDrops(true);
setDropIndicatorShown(true);
setDefaultDropAction(Qt::MoveAction);
setDragDropOverwriteMode(false);
setDragDropMode(QTableView::DragDrop);
}
PlaylistTable::~PlaylistTable() {
}
void PlaylistTable::mouseDoubleClickEvent(QMouseEvent* e) {
QPoint clickPos = e->pos();
QModelIndex clickIdx = QTableView::indexAt(clickPos);
#if DEBUG_PLAYLISTVIEW
qDebug()<< "Double click at (" << clickPos.x() << ", " << clickPos.y();
qDebug()<< "ModelIndex: (" << clickIdx.row() << ", " << clickIdx.column();
#endif
emit(QTableView::activated(clickIdx));
}
void PlaylistTable::mouseReleaseEvent(QMouseEvent* e) {
if (e->button() == Qt::LeftButton) {
// Use base handler
QTableView::mouseReleaseEvent(e);
}
else {
QTableView::mouseReleaseEvent(e);
}
}
#if DEBUG_PLAYLISTVIEW
void PlaylistTable::contextMenuEvent(QContextMenuEvent* e) {
QPoint clickPos = e->pos();
QModelIndex clickIdx = QTableView::indexAt(clickPos);
qDebug() << "Right click at (" << clickPos.x() << ", " << clickPos.y() << ")";
qDebug() << "ModelIndex: (" << clickIdx.row() << ", " << clickIdx.column() << ")";
}
#endif
void PlaylistTable::keyPressEvent(QKeyEvent *event) {
// selectionMode must be contiguous
if (event->key() == Qt::Key_Delete) {
if (selectionModel()->hasSelection()) {
QModelIndexList selected = selectionModel()->selectedRows();
PlaylistModel *model = (PlaylistModel*)(QTableView::model());
model->removeMedia(selected.front().row(), selected.back().row());
}
}
else {
QTableView::keyPressEvent(event);
}
}
void PlaylistTable::dragEnterEvent(QDragEnterEvent *event) {
if (event->mimeData()->hasFormat("myMediaItem")) {
//qDebug() << "playlistTable::dragEnterEvent()";
#if DEBUG_PLAYLISTVIEW
QPoint dragPos = event->pos();
QModelIndex dragIdx = QTableView::indexAt(dragPos);
qDebug()<<"dragIdx is " << dragIdx;
#endif
event->accept();
}
else {
event->ignore();
}
}
void PlaylistTable::dragMoveEvent(QDragMoveEvent *event) {
if (event->mimeData()->hasFormat("myMediaItem")) {
//qDebug() << "playlistTable::dragMoveEvent(myMediaItem)";
event->setDropAction(Qt::MoveAction);
event->accept();
}
else {
event->ignore();
}
}
void PlaylistTable::dropEvent(QDropEvent *event) {
//qDebug()<<"PlaylistTable::dropEvent()";
if (event->mimeData()->hasFormat("myMediaItem")) {
// this is when we re-arrange items in the playlist
QByteArray itemData = event->mimeData()->data("myMediaItem");
QDataStream dataStream(&itemData, QIODevice::ReadOnly);
QString header;
dataStream >> header;
qDebug() << "Header is: " << header;
if (header == "playlistItem") {
QPoint dropPos = event->pos();
int dropRow = QTableView::indexAt(dropPos).row();
QList<int> itemRowList;
while (!dataStream.atEnd()) {
int itemRow;
dataStream >> itemRow;
itemRowList << itemRow;
}
qSort(itemRowList);
int offset = dropRow - itemRowList.back();
#if DEBUG_PLAYLISTVIEW
qDebug()<<"dropRow is " << dropRow;
#endif
PlaylistModel *model = static_cast<PlaylistModel*>(QTableView::model());
model->swapSong(dropRow, itemRowList, offset);
event->setDropAction(Qt::MoveAction);
event->accept();
}
if (header == "libraryItem") {
QList<QHash<QString, QString> > itemList;
QHash<QString, QString> hash;
while (!dataStream.atEnd()) {
dataStream >> hash;
itemList << hash;
}
PlaylistModel *model = static_cast<PlaylistModel*>(QTableView::model());
model->addMediaList(itemList);
event->setDropAction(Qt::CopyAction);
event->accept();
}
}
else {
event->ignore();
}
}
| 30.621795
| 86
| 0.609378
|
allenyin
|
497a1492afe717c7f57e2f374dd963873003af7b
| 28,261
|
cpp
|
C++
|
benchmark/message/message.cpp
|
smart-cloud/actor-zeta
|
9597d6c21843a5e24a7998d09ff041d2f948cc63
|
[
"BSD-3-Clause"
] | 20
|
2016-01-07T07:37:52.000Z
|
2019-06-02T12:04:25.000Z
|
benchmark/message/message.cpp
|
smart-cloud/actor-zeta
|
9597d6c21843a5e24a7998d09ff041d2f948cc63
|
[
"BSD-3-Clause"
] | 30
|
2017-03-10T14:47:46.000Z
|
2019-05-09T19:23:25.000Z
|
benchmark/message/message.cpp
|
jinncrafters/actor-zeta
|
9597d6c21843a5e24a7998d09ff041d2f948cc63
|
[
"BSD-3-Clause"
] | 6
|
2017-03-10T14:06:01.000Z
|
2018-08-13T18:19:37.000Z
|
#include <benchmark/benchmark.h>
#include <iostream>
#include <map>
#include <memory>
#include <string>
#include <vector>
#include <actor-zeta/make_message.hpp>
#include "fixtures.hpp"
#include "register_benchmark.hpp"
namespace benchmark_messages {
static volatile int64_t message_sz = 0;
using raw_t = actor_zeta::mailbox::message*;
using smart_t = actor_zeta::mailbox::message_ptr;
namespace by_name {
BENCHMARK_TEMPLATE_DEFINE_F(fixture_t, RawPtrMessage_Name, raw_t)
(benchmark::State& state) {
while (state.KeepRunning()) {
auto message = actor_zeta::make_message_ptr(
actor_zeta::base::address_t::empty_address(),
name_);
auto tmp = sizeof(*message);
delete message;
if (static_cast<int64_t>(tmp) > static_cast<int64_t>(benchmark_messages::message_sz))
benchmark_messages::message_sz = static_cast<int64_t>(tmp);
}
}
BENCHMARK_TEMPLATE_DEFINE_F(fixture_t, SmartPtrMessage_Name, smart_t)
(benchmark::State& state) {
while (state.KeepRunning()) {
auto message = actor_zeta::make_message(
actor_zeta::base::address_t::empty_address(),
name_);
auto tmp = sizeof(*message);
if (static_cast<int64_t>(tmp) > static_cast<int64_t>(benchmark_messages::message_sz))
benchmark_messages::message_sz = static_cast<int64_t>(tmp);
}
}
BENCHMARK_REGISTER_F(fixture_t, RawPtrMessage_Name)->DenseRange(0, 64, 8);
BENCHMARK_REGISTER_F(fixture_t, SmartPtrMessage_Name)->DenseRange(0, 64, 8);
} // namespace by_name
namespace by_args {
template<typename... Args>
auto message_arg_tmpl(uint64_t name_, Args&&... args) -> void;
namespace raw_ptr {
template<typename... Args>
auto message_arg_tmpl(uint64_t name_, Args&&... args) -> void {
auto message = actor_zeta::make_message_ptr(
actor_zeta::base::address_t::empty_address(),
name_,
std::forward<Args>(args)...);
auto tmp = sizeof(*message);
delete message;
if (static_cast<int64_t>(tmp) > static_cast<int64_t>(benchmark_messages::message_sz))
benchmark_messages::message_sz = static_cast<int64_t>(tmp);
}
template<typename T, std::size_t... I>
auto call_message_arg_tmpl(uint64_t name_, T& packed_tuple, actor_zeta::type_traits::index_sequence<I...>) -> void {
message_arg_tmpl(name_, (std::get<I>(packed_tuple))...);
}
} // namespace raw_ptr
namespace smart_ptr {
template<typename... Args>
auto message_arg_tmpl(uint64_t name_, Args&&... args) -> void {
auto message = actor_zeta::make_message(
actor_zeta::base::address_t::empty_address(),
name_,
std::forward<Args>(args)...);
auto tmp = sizeof(*message);
if (static_cast<int64_t>(tmp) > static_cast<int64_t>(benchmark_messages::message_sz))
benchmark_messages::message_sz = static_cast<int64_t>(tmp);
}
template<typename T, std::size_t... I>
auto call_message_arg_tmpl(uint64_t name_, T& packed_tuple, actor_zeta::type_traits::index_sequence<I...>) -> void {
message_arg_tmpl(name_, (std::get<I>(packed_tuple))...);
}
} // namespace smart_ptr
#define REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture, bm_name, type) REGISTER_BENCHMARK_FOR_RAWPTR_ARGS(fixture, bm_name, raw_t, benchmark_messages::by_args::raw_ptr, type)
#define REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture, bm_name, type) REGISTER_BENCHMARK_FOR_SMARTPTR_ARGS(fixture, bm_name, smart_t, benchmark_messages::by_args::smart_ptr, type)
namespace trivial_args {
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_int, int);
/*REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_int8, int8_t);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_int16, int16_t);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_int32, int32_t);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_int64, int64_t);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_short, short);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_unsigned_short, unsigned short);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_unsigned_int, unsigned int);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_unsigned_long_int, unsigned long int);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_long_int, long int);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_long_long_int, long long int);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_long_long, long long);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_long, long);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_float, float);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_double, double);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_long_double, long double);*/
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_int, int);
/*REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_int8, int8_t);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_int16, int16_t);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_int32, int32_t);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_int64, int64_t);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_short, short);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_unsigned_short, unsigned short);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_unsigned_int, unsigned int);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_unsigned_long_int, unsigned long int);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_long_int, long int);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_long_long_int, long long int);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_long_long, long long);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_long, long);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_float, float);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_double, double);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_long_double, long double);*/
} // namespace trivial_args
namespace smart_pointer_args {
//REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_shared_ptr_int, int);
/*REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_shared_ptr_int8, int8_t);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_shared_ptr_int16, int16_t);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_shared_ptr_int32, int32_t);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_shared_ptr_int64, int64_t);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_shared_ptr_short, short);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_shared_ptr_unsigned_short, unsigned short);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_shared_ptr_unsigned_int, unsigned int);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_shared_ptr_unsigned_long_int, unsigned long int);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_shared_ptr_long_int, long int);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_shared_ptr_long_long_int, long long int);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_shared_ptr_long_long, long long);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_shared_ptr_long, long);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_shared_ptr_float, float);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_shared_ptr_double, double);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_shared_ptr_long_double, long double);*/
//REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_shared_ptr_int, int);
/*REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_shared_ptr_int8, int8_t);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_shared_ptr_int16, int16_t);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_shared_ptr_int32, int32_t);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_shared_ptr_int64, int64_t);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_shared_ptr_short, short);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_shared_ptr_unsigned_short, unsigned short);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_shared_ptr_unsigned_int, unsigned int);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_shared_ptr_unsigned_long_int, unsigned long int);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_shared_ptr_long_int, long int);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_shared_ptr_long_long_int, long long int);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_shared_ptr_long_long, long long);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_shared_ptr_long, long);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_shared_ptr_float, float);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_shared_ptr_double, double);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_shared_ptr_long_double, long double);*/
} // namespace smart_pointer_args
namespace container_args {
//REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_vec_t, RawPtrMessage_Args_std_vector_int, int);
/*REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_vec_t, RawPtrMessage_Args_std_vector_int8, int8_t);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_vec_t, RawPtrMessage_Args_std_vector_int16, int16_t);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_vec_t, RawPtrMessage_Args_std_vector_int32, int32_t);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_vec_t, RawPtrMessage_Args_std_vector_int64, int64_t);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_vec_t, RawPtrMessage_Args_std_vector_short, short);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_vec_t, RawPtrMessage_Args_std_vector_unsigned_short, unsigned short);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_vec_t, RawPtrMessage_Args_std_vector_unsigned_int, unsigned int);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_vec_t, RawPtrMessage_Args_std_vector_unsigned_long_int, unsigned long int);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_vec_t, RawPtrMessage_Args_std_vector_long_int, long int);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_vec_t, RawPtrMessage_Args_std_vector_long_long_int, long long int);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_vec_t, RawPtrMessage_Args_std_vector_long_long, long long);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_vec_t, RawPtrMessage_Args_std_vector_long, long);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_vec_t, RawPtrMessage_Args_std_vector_float, float);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_vec_t, RawPtrMessage_Args_std_vector_double, double);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_vec_t, RawPtrMessage_Args_std_vector_long_double, long double);*/
//REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_list_t, RawPtrMessage_Args_std_list_int, int);
/*REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_list_t, RawPtrMessage_Args_std_list_int8, int8_t);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_list_t, RawPtrMessage_Args_std_list_int16, int16_t);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_list_t, RawPtrMessage_Args_std_list_int32, int32_t);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_list_t, RawPtrMessage_Args_std_list_int64, int64_t);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_list_t, RawPtrMessage_Args_std_list_short, short);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_list_t, RawPtrMessage_Args_std_list_unsigned_short, unsigned short);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_list_t, RawPtrMessage_Args_std_list_unsigned_int, unsigned int);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_list_t, RawPtrMessage_Args_std_list_unsigned_long_int, unsigned long int);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_list_t, RawPtrMessage_Args_std_list_long_int, long int);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_list_t, RawPtrMessage_Args_std_list_long_long_int, long long int);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_list_t, RawPtrMessage_Args_std_list_long_long, long long);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_list_t, RawPtrMessage_Args_std_list_long, long);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_list_t, RawPtrMessage_Args_std_list_float, float);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_list_t, RawPtrMessage_Args_std_list_double, double);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_list_t, RawPtrMessage_Args_std_list_long_double, long double);*/
//REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_map_t, RawPtrMessage_Args_std_map_int, int);
/*REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_map_t, RawPtrMessage_Args_std_map_int8, int8_t);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_map_t, RawPtrMessage_Args_std_map_int16, int16_t);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_map_t, RawPtrMessage_Args_std_map_int32, int32_t);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_map_t, RawPtrMessage_Args_std_map_int64, int64_t);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_map_t, RawPtrMessage_Args_std_map_short, short);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_map_t, RawPtrMessage_Args_std_map_unsigned_short, unsigned short);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_map_t, RawPtrMessage_Args_std_map_unsigned_int, unsigned int);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_map_t, RawPtrMessage_Args_std_map_unsigned_long_int, unsigned long int);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_map_t, RawPtrMessage_Args_std_map_long_int, long int);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_map_t, RawPtrMessage_Args_std_map_long_long_int, long long int);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_map_t, RawPtrMessage_Args_std_map_long_long, long long);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_map_t, RawPtrMessage_Args_std_map_long, long);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_map_t, RawPtrMessage_Args_std_map_float, float);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_map_t, RawPtrMessage_Args_std_map_double, double);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_map_t, RawPtrMessage_Args_std_map_long_double, long double);*/
//REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_set_t, RawPtrMessage_Args_std_set_int, int);
/*REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_set_t, RawPtrMessage_Args_std_set_int8, int8_t);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_set_t, RawPtrMessage_Args_std_set_int16, int16_t);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_set_t, RawPtrMessage_Args_std_set_int32, int32_t);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_set_t, RawPtrMessage_Args_std_set_int64, int64_t);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_set_t, RawPtrMessage_Args_std_set_short, short);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_set_t, RawPtrMessage_Args_std_set_unsigned_short, unsigned short);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_set_t, RawPtrMessage_Args_std_set_unsigned_int, unsigned int);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_set_t, RawPtrMessage_Args_std_set_unsigned_long_int, unsigned long int);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_set_t, RawPtrMessage_Args_std_set_long_int, long int);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_set_t, RawPtrMessage_Args_std_set_long_long_int, long long int);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_set_t, RawPtrMessage_Args_std_set_long_long, long long);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_set_t, RawPtrMessage_Args_std_set_long, long);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_set_t, RawPtrMessage_Args_std_set_float, float);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_set_t, RawPtrMessage_Args_std_set_double, double);
REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_set_t, RawPtrMessage_Args_std_set_long_double, long double);*/
//REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_vec_t, SmartPtrMessage_Args_std_vector_int, int);
/*REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_vec_t, SmartPtrMessage_Args_std_vector_int8, int8_t);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_vec_t, SmartPtrMessage_Args_std_vector_int16, int16_t);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_vec_t, SmartPtrMessage_Args_std_vector_int32, int32_t);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_vec_t, SmartPtrMessage_Args_std_vector_int64, int64_t);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_vec_t, SmartPtrMessage_Args_std_vector_short, short);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_vec_t, SmartPtrMessage_Args_std_vector_unsigned_short, unsigned short);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_vec_t, SmartPtrMessage_Args_std_vector_unsigned_int, unsigned int);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_vec_t, SmartPtrMessage_Args_std_vector_unsigned_long_int, unsigned long int);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_vec_t, SmartPtrMessage_Args_std_vector_long_int, long int);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_vec_t, SmartPtrMessage_Args_std_vector_long_long_int, long long int);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_vec_t, SmartPtrMessage_Args_std_vector_long_long, long long);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_vec_t, SmartPtrMessage_Args_std_vector_long, long);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_vec_t, SmartPtrMessage_Args_std_vector_float, float);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_vec_t, SmartPtrMessage_Args_std_vector_double, double);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_vec_t, SmartPtrMessage_Args_std_vector_long_double, long double);*/
//REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_list_t, SmartPtrMessage_Args_std_list_int, int);
/*REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_list_t, SmartPtrMessage_Args_std_list_int8, int8_t);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_list_t, SmartPtrMessage_Args_std_list_int16, int16_t);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_list_t, SmartPtrMessage_Args_std_list_int32, int32_t);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_list_t, SmartPtrMessage_Args_std_list_int64, int64_t);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_list_t, SmartPtrMessage_Args_std_list_short, short);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_list_t, SmartPtrMessage_Args_std_list_unsigned_short, unsigned short);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_list_t, SmartPtrMessage_Args_std_list_unsigned_int, unsigned int);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_list_t, SmartPtrMessage_Args_std_list_unsigned_long_int, unsigned long int);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_list_t, SmartPtrMessage_Args_std_list_long_int, long int);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_list_t, SmartPtrMessage_Args_std_list_long_long_int, long long int);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_list_t, SmartPtrMessage_Args_std_list_long_long, long long);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_list_t, SmartPtrMessage_Args_std_list_long, long);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_list_t, SmartPtrMessage_Args_std_list_float, float);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_list_t, SmartPtrMessage_Args_std_list_double, double);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_list_t, SmartPtrMessage_Args_std_list_long_double, long double);*/
//REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_map_t, SmartPtrMessage_Args_std_map_int, int);
/*REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_map_t, SmartPtrMessage_Args_std_map_int8, int8_t);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_map_t, SmartPtrMessage_Args_std_map_int16, int16_t);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_map_t, SmartPtrMessage_Args_std_map_int32, int32_t);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_map_t, SmartPtrMessage_Args_std_map_int64, int64_t);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_map_t, SmartPtrMessage_Args_std_map_short, short);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_map_t, SmartPtrMessage_Args_std_map_unsigned_short, unsigned short);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_map_t, SmartPtrMessage_Args_std_map_unsigned_int, unsigned int);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_map_t, SmartPtrMessage_Args_std_map_unsigned_long_int, unsigned long int);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_map_t, SmartPtrMessage_Args_std_map_long_int, long int);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_map_t, SmartPtrMessage_Args_std_map_long_long_int, long long int);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_map_t, SmartPtrMessage_Args_std_map_long_long, long long);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_map_t, SmartPtrMessage_Args_std_map_long, long);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_map_t, SmartPtrMessage_Args_std_map_float, float);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_map_t, SmartPtrMessage_Args_std_map_double, double);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_map_t, SmartPtrMessage_Args_std_map_long_double, long double);*/
//REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_set_t, SmartPtrMessage_Args_std_set_int, int);
/*REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_set_t, SmartPtrMessage_Args_std_set_int8, int8_t);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_set_t, SmartPtrMessage_Args_std_set_int16, int16_t);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_set_t, SmartPtrMessage_Args_std_set_int32, int32_t);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_set_t, SmartPtrMessage_Args_std_set_int64, int64_t);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_set_t, SmartPtrMessage_Args_std_set_short, short);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_set_t, SmartPtrMessage_Args_std_set_unsigned_short, unsigned short);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_set_t, SmartPtrMessage_Args_std_set_unsigned_int, unsigned int);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_set_t, SmartPtrMessage_Args_std_set_unsigned_long_int, unsigned long int);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_set_t, SmartPtrMessage_Args_std_set_long_int, long int);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_set_t, SmartPtrMessage_Args_std_set_long_long_int, long long int);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_set_t, SmartPtrMessage_Args_std_set_long_long, long long);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_set_t, SmartPtrMessage_Args_std_set_long, long);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_set_t, SmartPtrMessage_Args_std_set_float, float);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_set_t, SmartPtrMessage_Args_std_set_double, double);
REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_set_t, SmartPtrMessage_Args_std_set_long_double, long double);*/
} // namespace container_args
namespace custom_args {
//REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_custom_1, custom_1_t);
//REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_custom_1, custom_1_t);
} // namespace custom_args
} // namespace by_args
class memory_manager_t : public benchmark::MemoryManager {
void Start() BENCHMARK_OVERRIDE {}
void Stop(Result* result) BENCHMARK_OVERRIDE {
result->max_bytes_used = message_sz;
}
};
} // namespace benchmark_messages
// Run the benchmark
int main(int argc, char** argv) {
benchmark::Initialize(&argc, argv);
if (benchmark::ReportUnrecognizedArguments(argc, argv))
return 1;
std::unique_ptr<benchmark::MemoryManager> mm(new benchmark_messages::memory_manager_t());
benchmark::RegisterMemoryManager(mm.get());
benchmark::RunSpecifiedBenchmarks();
benchmark::Shutdown();
benchmark::RegisterMemoryManager(nullptr);
return 0;
}
| 81.20977
| 186
| 0.78695
|
smart-cloud
|
21a316b503d0458ef2a590ffd7f9f0cc7481d0d4
| 1,234
|
cpp
|
C++
|
Modeler/ScriptDoc.cpp
|
openlastchaos/lastchaos-source-client
|
3d88594dba7347b1bb45378136605e31f73a8555
|
[
"Apache-2.0"
] | 1
|
2022-02-14T15:46:44.000Z
|
2022-02-14T15:46:44.000Z
|
Modeler/ScriptDoc.cpp
|
openlastchaos/lastchaos-source-client
|
3d88594dba7347b1bb45378136605e31f73a8555
|
[
"Apache-2.0"
] | null | null | null |
Modeler/ScriptDoc.cpp
|
openlastchaos/lastchaos-source-client
|
3d88594dba7347b1bb45378136605e31f73a8555
|
[
"Apache-2.0"
] | 2
|
2022-01-10T22:17:06.000Z
|
2022-01-17T09:34:08.000Z
|
// ScriptDoc.cpp : implementation file
//
#include "stdafx.h"
#ifdef _DEBUG
#undef new
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CScriptDoc
IMPLEMENT_DYNCREATE(CScriptDoc, CDocument)
CScriptDoc::CScriptDoc()
{
}
BOOL CScriptDoc::OnNewDocument()
{
if (!CDocument::OnNewDocument())
return FALSE;
return TRUE;
}
CScriptDoc::~CScriptDoc()
{
}
BEGIN_MESSAGE_MAP(CScriptDoc, CDocument)
//{{AFX_MSG_MAP(CScriptDoc)
// NOTE - the ClassWizard will add and remove mapping macros here.
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CScriptDoc diagnostics
#ifdef _DEBUG
void CScriptDoc::AssertValid() const
{
CDocument::AssertValid();
}
void CScriptDoc::Dump(CDumpContext& dc) const
{
CDocument::Dump(dc);
}
#endif //_DEBUG
/////////////////////////////////////////////////////////////////////////////
// CScriptDoc serialization
void CScriptDoc::Serialize(CArchive& ar)
{
((CEditView*)m_viewList.GetHead())->SerializeRaw(ar);
}
/////////////////////////////////////////////////////////////////////////////
// CScriptDoc commands
| 18.984615
| 77
| 0.551053
|
openlastchaos
|
21a55d0c5e3ca82fd2e04d7ccd567e8d7846fe1a
| 4,204
|
cpp
|
C++
|
Source/Cache/FrameCache.cpp
|
Karshilov/Dorothy-SSR
|
cce19ed2218d76f941977370f6b3894e2f87236a
|
[
"MIT"
] | 43
|
2020-01-29T02:22:41.000Z
|
2021-12-06T04:20:12.000Z
|
Source/Cache/FrameCache.cpp
|
Jilliana8397/Dorothy-SSR
|
5ad647909c5e20cb7ebde9a1a054cdb944969dcb
|
[
"MIT"
] | 1
|
2020-03-19T16:23:12.000Z
|
2020-03-19T16:23:12.000Z
|
Source/Cache/FrameCache.cpp
|
Jilliana8397/Dorothy-SSR
|
5ad647909c5e20cb7ebde9a1a054cdb944969dcb
|
[
"MIT"
] | 8
|
2020-03-08T13:46:08.000Z
|
2021-07-19T11:30:23.000Z
|
/* Copyright (c) 2021 Jin Li, http://www.luvfight.me
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 "Const/Header.h"
#include "Cache/FrameCache.h"
#include "Const/XmlTag.h"
#include "Cache/TextureCache.h"
#include "Cache/ClipCache.h"
#include "Node/Sprite.h"
NS_DOROTHY_BEGIN
FrameActionDef* FrameCache::loadFrame(String frameStr)
{
if (Path::getExt(frameStr) == "frame"_slice) return load(frameStr);
BLOCK_START
{
auto parts = frameStr.split("::"_slice);
BREAK_IF(parts.size() != 2);
FrameActionDef* def = FrameActionDef::create();
def->clipStr = parts.front();
Vec2 origin{};
if (SharedClipCache.isClip(parts.front()))
{
Texture2D* tex = nullptr;
Rect rect;
std::tie(tex, rect) = SharedClipCache.loadTexture(parts.front());
origin = rect.origin;
}
auto tokens = parts.back().split(","_slice);
BREAK_IF(tokens.size() != 4);
auto it = tokens.begin();
float width = Slice::stof(*it);
float height = Slice::stof(*++it);
int count = Slice::stoi(*++it);
def->duration = Slice::stof(*++it);
for (int i = 0; i < count; i++)
{
def->rects.push_back(New<Rect>(origin.x + i * width, origin.y, width, height));
}
return def;
}
BLOCK_END
Warn("invalid frame str not load: \"{}\".", frameStr);
return nullptr;
}
bool FrameCache::isFrame(String frameStr) const
{
auto parts = frameStr.split("::"_slice);
if (parts.size() == 1) return Path::getExt(parts.front()) == "frame"_slice;
else if (parts.size() == 2) return parts.back().split(","_slice).size() == 4;
else return false;
}
std::shared_ptr<XmlParser<FrameActionDef>> FrameCache::prepareParser(String filename)
{
return std::shared_ptr<XmlParser<FrameActionDef>>(new Parser(FrameActionDef::create(), Path::getPath(filename)));
}
void FrameCache::Parser::xmlSAX2Text(const char* s, size_t len)
{ }
void FrameCache::Parser::xmlSAX2StartElement(const char* name, size_t len, const std::vector<AttrSlice>& attrs)
{
switch (Xml::Frame::Element(name[0]))
{
case Xml::Frame::Element::Dorothy:
{
for (int i = 0; attrs[i].first != nullptr;i++)
{
switch (Xml::Frame::Dorothy(attrs[i].first[0]))
{
case Xml::Frame::Dorothy::File:
{
Slice file(attrs[++i]);
std::string localFile = Path::concat({_path, file});
_item->clipStr = SharedContent.exist(localFile) ? localFile : file.toString();
break;
}
case Xml::Frame::Dorothy::Duration:
_item->duration = s_cast<float>(std::atof(attrs[++i].first));
break;
}
}
break;
}
case Xml::Frame::Element::Clip:
{
for (int i = 0; attrs[i].first != nullptr; i++)
{
switch (Xml::Frame::Clip(attrs[i].first[0]))
{
case Xml::Frame::Clip::Rect:
{
Slice attr(attrs[++i]);
auto tokens = attr.split(",");
AssertUnless(tokens.size() == 4, "invalid clip rect str for: \"{}\"", attr);
auto it = tokens.begin();
float x = Slice::stof(*it);
float y = Slice::stof(*++it);
float w = Slice::stof(*++it);
float h = Slice::stof(*++it);
_item->rects.push_back(New<Rect>(x, y, w, h));
break;
}
}
}
break;
}
}
}
void FrameCache::Parser::xmlSAX2EndElement(const char* name, size_t len)
{ }
NS_DOROTHY_END
| 34.178862
| 463
| 0.672217
|
Karshilov
|
21a5dad926c4e000099bd64e80dadf40be432e3f
| 381
|
hpp
|
C++
|
src/delta.hpp
|
crockeo/hc
|
a5f9eaa1051e8825fa765d120d8ea76682909a5a
|
[
"MIT"
] | null | null | null |
src/delta.hpp
|
crockeo/hc
|
a5f9eaa1051e8825fa765d120d8ea76682909a5a
|
[
"MIT"
] | null | null | null |
src/delta.hpp
|
crockeo/hc
|
a5f9eaa1051e8825fa765d120d8ea76682909a5a
|
[
"MIT"
] | null | null | null |
#ifndef _DELTA_HPP_
#define _DELTA_HPP_
//////////
// Code //
// Getting the current system time in milliseconds.
int getTimeMillis();
// A utility to do some delta timing stuff.
class Delta {
private:
int last, curr;
bool first;
public:
// Constructing a delta.
Delta();
// Getting the time since the last time this was run.
float since();
};
#endif
| 15.24
| 57
| 0.650919
|
crockeo
|
21a5f501ef3650eec5efbe46f08a594997b372d5
| 652
|
cpp
|
C++
|
Codeforces/A_Games.cpp
|
Sohelr360/my_codes
|
9bdd28f62d3850aad8f8af2a253ba66138a7057c
|
[
"MIT"
] | null | null | null |
Codeforces/A_Games.cpp
|
Sohelr360/my_codes
|
9bdd28f62d3850aad8f8af2a253ba66138a7057c
|
[
"MIT"
] | null | null | null |
Codeforces/A_Games.cpp
|
Sohelr360/my_codes
|
9bdd28f62d3850aad8f8af2a253ba66138a7057c
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
#define endl "\n"
#define pi acos(-1)
#define faster_io ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
using namespace std;
int main()
{
//freopen("/home/sohel/Documents/my_codes/out.txt", "wt", stdout);
faster_io;
int n, cnt_rep = 0, cnt = 0;
cin >> n;
int h[n], a[n];
for (int i = 0; i < n; i++) {
cin >> h[i] >> a[i];
}
for (int i = 0; i < n - 1; i++)
{
for (int j = i + 1; j < n; j++)
{
if (h[i] == a[j])
cnt++;
if(a[i] == h[j])
cnt++;
}
}
cout << cnt << endl;
return 0;
}
| 21.733333
| 77
| 0.435583
|
Sohelr360
|
21a61f52b9ddbd1d42dcc22dee17ed910b20266f
| 6,950
|
hpp
|
C++
|
include/crocoddyl/multibody/frames.hpp
|
ggory15/crocoddyl
|
4708428676f596f93ffe2df739faeb5cc38d2326
|
[
"BSD-3-Clause"
] | null | null | null |
include/crocoddyl/multibody/frames.hpp
|
ggory15/crocoddyl
|
4708428676f596f93ffe2df739faeb5cc38d2326
|
[
"BSD-3-Clause"
] | null | null | null |
include/crocoddyl/multibody/frames.hpp
|
ggory15/crocoddyl
|
4708428676f596f93ffe2df739faeb5cc38d2326
|
[
"BSD-3-Clause"
] | null | null | null |
///////////////////////////////////////////////////////////////////////////////
// BSD 3-Clause License
//
// Copyright (C) 2018-2020, LAAS-CNRS, University of Edinburgh
// Copyright note valid unless otherwise stated in individual files.
// All rights reserved.
///////////////////////////////////////////////////////////////////////////////
#ifndef CROCODDYL_MULTIBODY_FRAMES_HPP_
#define CROCODDYL_MULTIBODY_FRAMES_HPP_
#include "crocoddyl/multibody/fwd.hpp"
#include "crocoddyl/multibody/friction-cone.hpp"
#include "crocoddyl/core/mathbase.hpp"
#include <pinocchio/spatial/se3.hpp>
#include <pinocchio/spatial/motion.hpp>
#include <pinocchio/spatial/force.hpp>
namespace crocoddyl {
typedef std::size_t FrameIndex;
template <typename _Scalar>
struct FrameTranslationTpl {
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
typedef _Scalar Scalar;
typedef typename MathBaseTpl<Scalar>::Vector3s Vector3s;
explicit FrameTranslationTpl() : frame(0), oxf(Vector3s::Zero()) {}
FrameTranslationTpl(const FrameTranslationTpl<Scalar>& value) : frame(value.frame), oxf(value.oxf) {}
FrameTranslationTpl(const FrameIndex& frame, const Vector3s& oxf) : frame(frame), oxf(oxf) {}
friend std::ostream& operator<<(std::ostream& os, const FrameTranslationTpl<Scalar>& X) {
os << " frame: " << X.frame << std::endl << "translation: " << std::endl << X.oxf.transpose() << std::endl;
return os;
}
FrameIndex frame;
Vector3s oxf;
};
template <typename _Scalar>
struct FrameRotationTpl {
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
typedef _Scalar Scalar;
typedef typename MathBaseTpl<Scalar>::Matrix3s Matrix3s;
explicit FrameRotationTpl() : frame(0), oRf(Matrix3s::Identity()) {}
FrameRotationTpl(const FrameRotationTpl<Scalar>& value) : frame(value.frame), oRf(value.oRf) {}
FrameRotationTpl(const FrameIndex& frame, const Matrix3s& oRf) : frame(frame), oRf(oRf) {}
friend std::ostream& operator<<(std::ostream& os, const FrameRotationTpl<Scalar>& X) {
os << " frame: " << X.frame << std::endl << "rotation: " << std::endl << X.oRf << std::endl;
return os;
}
FrameIndex frame;
Matrix3s oRf;
};
template <typename _Scalar>
struct FramePlacementTpl {
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
typedef _Scalar Scalar;
typedef pinocchio::SE3Tpl<Scalar> SE3;
explicit FramePlacementTpl() : frame(0), oMf(SE3::Identity()) {}
FramePlacementTpl(const FramePlacementTpl<Scalar>& value) : frame(value.frame), oMf(value.oMf) {}
FramePlacementTpl(const FrameIndex& frame, const SE3& oMf) : frame(frame), oMf(oMf) {}
friend std::ostream& operator<<(std::ostream& os, const FramePlacementTpl<Scalar>& X) {
os << " frame: " << X.frame << std::endl << "placement: " << std::endl << X.oMf << std::endl;
return os;
}
FrameIndex frame;
pinocchio::SE3Tpl<Scalar> oMf;
};
template <typename _Scalar>
struct FrameMotionTpl {
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
typedef _Scalar Scalar;
typedef pinocchio::MotionTpl<Scalar> Motion;
explicit FrameMotionTpl() : frame(0), oMf(Motion::Zero()) {}
FrameMotionTpl(const FrameMotionTpl<Scalar>& value) : frame(value.frame), oMf(value.oMf) {}
FrameMotionTpl(const FrameIndex& frame, const Motion& oMf) : frame(frame), oMf(oMf) {}
friend std::ostream& operator<<(std::ostream& os, const FrameMotionTpl<Scalar>& X) {
os << " frame: " << X.frame << std::endl << "motion: " << std::endl << X.oMf << std::endl;
return os;
}
FrameIndex frame;
pinocchio::MotionTpl<Scalar> oMf;
};
template <typename _Scalar>
struct FrameForceTpl {
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
typedef _Scalar Scalar;
typedef pinocchio::ForceTpl<Scalar> Force;
explicit FrameForceTpl() : frame(0), oFf(Force::Zero()) {}
FrameForceTpl(const FrameForceTpl<Scalar>& value) : frame(value.frame), oFf(value.oFf) {}
FrameForceTpl(const FrameIndex& frame, const Force& oFf) : frame(frame), oFf(oFf) {}
friend std::ostream& operator<<(std::ostream& os, const FrameForceTpl<Scalar>& X) {
os << "frame: " << X.frame << std::endl << "force: " << std::endl << X.oFf << std::endl;
return os;
}
FrameIndex frame;
pinocchio::ForceTpl<Scalar> oFf;
};
template <typename _Scalar>
struct FrameFrictionConeTpl {
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
typedef _Scalar Scalar;
typedef FrictionConeTpl<Scalar> FrictionCone;
explicit FrameFrictionConeTpl() : frame(0), oRf(FrictionCone()) {}
FrameFrictionConeTpl(const FrameFrictionConeTpl<Scalar>& value) : frame(value.frame), oRf(value.oRf) {}
FrameFrictionConeTpl(const FrameIndex& frame, const FrictionCone& oRf) : frame(frame), oRf(oRf) {}
friend std::ostream& operator<<(std::ostream& os, const FrameFrictionConeTpl& X) {
os << "frame: " << X.frame << std::endl << " cone: " << std::endl << X.oRf << std::endl;
return os;
}
FrameIndex frame;
FrictionCone oRf;
};
template <typename _Scalar>
class FrameCoPSupportTpl {
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
typedef _Scalar Scalar;
typedef typename MathBaseTpl<Scalar>::Vector2s Vector2s;
typedef typename MathBaseTpl<Scalar>::Vector3s Vector3s;
typedef Eigen::Matrix<Scalar, 4, 6> Matrix46;
public:
explicit FrameCoPSupportTpl() : frame_(0), support_region_(Vector2s::Zero()) { update_A(); }
FrameCoPSupportTpl(const FrameCoPSupportTpl<Scalar>& value)
: frame_(value.get_frame()), support_region_(value.get_support_region()), A_(value.get_A()) {}
FrameCoPSupportTpl(const FrameIndex& frame, const Vector2s& support_region)
: frame_(frame), support_region_(support_region) {
update_A();
}
friend std::ostream& operator<<(std::ostream& os, const FrameCoPSupportTpl<Scalar>& X) {
os << " frame: " << X.get_frame() << std::endl
<< "foot dimensions: " << std::endl
<< X.get_support_region() << std::endl;
return os;
}
// Define the inequality matrix A to implement A * f >= 0. Compare eq.(18-19) in
// https://hal.archives-ouvertes.fr/hal-02108449/document
void update_A() {
A_ << Scalar(0), Scalar(0), support_region_[0] / Scalar(2), Scalar(0), Scalar(-1), Scalar(0), Scalar(0), Scalar(0),
support_region_[0] / Scalar(2), Scalar(0), Scalar(1), Scalar(0), Scalar(0), Scalar(0),
support_region_[1] / Scalar(2), Scalar(1), Scalar(0), Scalar(0), Scalar(0), Scalar(0),
support_region_[1] / Scalar(2), Scalar(-1), Scalar(0), Scalar(0);
}
void set_frame(FrameIndex frame) { frame_ = frame; }
void set_support_region(const Vector2s& support_region) {
support_region_ = support_region;
update_A();
}
const FrameIndex& get_frame() const { return frame_; }
const Vector2s& get_support_region() const { return support_region_; }
const Matrix46& get_A() const { return A_; }
private:
FrameIndex frame_; //!< contact frame ID
Vector2s support_region_; //!< cop support region = (length, width)
Matrix46 A_; //!< inequality matrix
};
} // namespace crocoddyl
#endif // CROCODDYL_MULTIBODY_FRAMES_HPP_
| 36.387435
| 119
| 0.684029
|
ggory15
|
21a97cdb8a3aca9743c770e22e6a6be248f6da18
| 1,163
|
cpp
|
C++
|
bzoj/1064.cpp
|
swwind/code
|
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
|
[
"WTFPL"
] | 3
|
2017-09-17T09:12:50.000Z
|
2018-04-06T01:18:17.000Z
|
bzoj/1064.cpp
|
swwind/code
|
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
|
[
"WTFPL"
] | null | null | null |
bzoj/1064.cpp
|
swwind/code
|
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
|
[
"WTFPL"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
inline int read(){
int x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=(x<<3)+(x<<1)+ch-'0';ch=getchar();}
return x*f;
}
const int inf = 1<<30;
int n, m, cnt, maxn, minx, ans, tmp;
struct edge{int to,nxt,val;}e[2000020];
int head[100020], vis[100020], mark[100020];
void ins(int x, int y, int v){
e[++cnt].nxt = head[x];
e[cnt].to = y;
e[head[x]=cnt].val = v;
}
void ins(int x, int y){
ins(x, y, 1); ins(y, x, -1);
}
int gcd(int a, int b){return b?gcd(b, a%b):a;}
void dfs(int x, int len){
if(vis[x]){ans = gcd(ans, abs(mark[x]-len)); return;}
vis[x] = 1; mark[x] = len;
maxn = max(maxn, len); minx = min(minx, len);
for(int i = head[x]; i; i=e[i].nxt)
dfs(e[i].to, len+e[i].val);
}
int main(){
n=read(); m=read();
for(int i = 1,x,y; i <= m; i++){
x=read();y=read();
ins(x, y);
}
for(int i = 1; i <= n; i++){
if(vis[i]) continue;
minx = inf; maxn = -inf;
dfs(i, 1);
tmp += maxn-minx+1;
}
int ans2 = 3;
if(!ans) ans = tmp;
else while(ans2<=ans&&ans%ans2)ans2++;
if(ans<3) puts("-1 -1");
else printf("%d %d\n", ans, ans2);
}
| 24.744681
| 62
| 0.545142
|
swwind
|
21afeaaaffd32f0e17161a02333cff232f80cdef
| 790
|
hpp
|
C++
|
src/beast/include/beast/core/detail/clamp.hpp
|
Py9595/Backpack-Travel-Underlying-Code
|
c5758792eba7cdd62cb6ff46e642e8e4e4e5417e
|
[
"BSL-1.0"
] | 5
|
2018-02-02T04:50:43.000Z
|
2020-10-14T08:15:01.000Z
|
src/beast/include/beast/core/detail/clamp.hpp
|
Py9595/Backpack-Travel-Underlying-Code
|
c5758792eba7cdd62cb6ff46e642e8e4e4e5417e
|
[
"BSL-1.0"
] | 10
|
2019-01-07T05:33:34.000Z
|
2020-07-15T00:09:26.000Z
|
src/beast/include/beast/core/detail/clamp.hpp
|
Py9595/Backpack-Travel-Underlying-Code
|
c5758792eba7cdd62cb6ff46e642e8e4e4e5417e
|
[
"BSL-1.0"
] | 4
|
2017-06-06T12:49:07.000Z
|
2021-07-01T07:44:49.000Z
|
//
// Copyright (c) 2013-2017 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)
//
#ifndef BEAST_CORE_DETAIL_CLAMP_HPP
#define BEAST_CORE_DETAIL_CLAMP_HPP
#include <limits>
#include <cstdlib>
namespace beast {
namespace detail {
template<class UInt>
static
std::size_t
clamp(UInt x)
{
if(x >= (std::numeric_limits<std::size_t>::max)())
return (std::numeric_limits<std::size_t>::max)();
return static_cast<std::size_t>(x);
}
template<class UInt>
static
std::size_t
clamp(UInt x, std::size_t limit)
{
if(x >= limit)
return limit;
return static_cast<std::size_t>(x);
}
} // detail
} // beast
#endif
| 19.268293
| 79
| 0.696203
|
Py9595
|
21b0580c4ba426b315ac89f33121ce92e45e01e7
| 1,098
|
cpp
|
C++
|
src/main.cpp
|
rathyon/xgp
|
8aba899746665d4d6afd51c9e83d5065e2f51abb
|
[
"MIT"
] | null | null | null |
src/main.cpp
|
rathyon/xgp
|
8aba899746665d4d6afd51c9e83d5065e2f51abb
|
[
"MIT"
] | null | null | null |
src/main.cpp
|
rathyon/xgp
|
8aba899746665d4d6afd51c9e83d5065e2f51abb
|
[
"MIT"
] | null | null | null |
#include "XGPApp.h"
using namespace xgp;
XGPApp* app;
void errorCallback(int error, const char* description) {
app->errorCallback(error, description);
}
void reshapeCallback(GLFWwindow* window, int width, int height) {
app->reshapeCallback(width, height);
}
void keyCallback(GLFWwindow* window, int key, int scancode, int action, int mods) {
app->keyCallback(key, scancode, action, mods);
}
void mouseButtonCallback(GLFWwindow* window, int button, int action, int mods) {
app->mouseButtonCallback(button, action, mods);
}
void mousePosCallback(GLFWwindow* window, double xpos, double ypos) {
app->mousePosCallback(xpos, ypos);
}
int main() {
app = new XGPApp("XGP - eXperimental Graphics Program", 640, 480);
app->init();
//Set callbacks
glfwSetErrorCallback(errorCallback);
glfwSetFramebufferSizeCallback(app->window(), reshapeCallback);
glfwSetKeyCallback(app->window(), keyCallback);
glfwSetMouseButtonCallback(app->window(), mouseButtonCallback);
glfwSetCursorPosCallback(app->window(), mousePosCallback);
app->loop();
app->cleanup();
delete app;
exit(EXIT_SUCCESS);
}
| 26.780488
| 83
| 0.752277
|
rathyon
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.