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 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 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 float64 1 77k ⌀ | 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 float64 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 653k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ac5bdee939f338383600bd2fac95904bffb04865 | 1,659 | cpp | C++ | src/core/tests/visitors/dimension.cpp | ryanloney/openvino-1 | 4e0a740eb3ee31062ba0df88fcf438564f67edb7 | [
"Apache-2.0"
] | 1,127 | 2018-10-15T14:36:58.000Z | 2020-04-20T09:29:44.000Z | src/core/tests/visitors/dimension.cpp | ryanloney/openvino-1 | 4e0a740eb3ee31062ba0df88fcf438564f67edb7 | [
"Apache-2.0"
] | 439 | 2018-10-20T04:40:35.000Z | 2020-04-19T05:56:25.000Z | src/core/tests/visitors/dimension.cpp | ryanloney/openvino-1 | 4e0a740eb3ee31062ba0df88fcf438564f67edb7 | [
"Apache-2.0"
] | 414 | 2018-10-17T05:53:46.000Z | 2020-04-16T17:29:53.000Z | // Copyright (C) 2018-2022 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "gtest/gtest.h"
#include "ngraph/ngraph.hpp"
#include "ngraph/op/util/attr_types.hpp"
#include "ngraph/opsets/opset1.hpp"
#include "ngraph/opsets/opset3.hpp"
#include "ngraph/opsets/opset4.hpp"
#include "ngraph/opsets/opset5.hpp"
#include "util/visitor.hpp"
using namespace std;
using namespace ngraph;
using ngraph::test::NodeBuilder;
using ngraph::test::ValueMap;
TEST(attributes, dimension) {
NodeBuilder builder;
AttributeVisitor& loader = builder.get_node_loader();
AttributeVisitor& saver = builder.get_node_saver();
Dimension dyn = Dimension(-1);
saver.on_attribute("dyn", dyn);
Dimension g_dyn;
loader.on_attribute("dyn", g_dyn);
EXPECT_EQ(dyn, g_dyn);
Dimension scalar = Dimension(10);
saver.on_attribute("scalar", scalar);
Dimension g_scalar;
loader.on_attribute("scalar", g_scalar);
EXPECT_EQ(scalar, g_scalar);
Dimension boundaries1 = Dimension(2, 100);
saver.on_attribute("boundaries1", boundaries1);
Dimension g_boundaries1;
loader.on_attribute("boundaries1", g_boundaries1);
EXPECT_EQ(boundaries1, g_boundaries1);
Dimension boundaries2 = Dimension(-1, 100);
saver.on_attribute("boundaries2", boundaries2);
Dimension g_boundaries2;
loader.on_attribute("boundaries2", g_boundaries2);
EXPECT_EQ(boundaries2, g_boundaries2);
Dimension boundaries3 = Dimension(5, -1);
saver.on_attribute("boundaries3", boundaries3);
Dimension g_boundaries3;
loader.on_attribute("boundaries3", g_boundaries3);
EXPECT_EQ(boundaries3, g_boundaries3);
}
| 30.722222 | 57 | 0.732369 |
ac5c29c36c2518fc591a949accccfd9aecb55958 | 24,233 | cpp | C++ | src/utils.cpp | dangerdevices/gdstk | bff6b2e5950b9da5b3b3f8bdb653778cf679e592 | [
"BSL-1.0"
] | 135 | 2020-08-12T22:32:21.000Z | 2022-03-31T04:34:56.000Z | src/utils.cpp | dangerdevices/gdstk | bff6b2e5950b9da5b3b3f8bdb653778cf679e592 | [
"BSL-1.0"
] | 80 | 2020-08-12T23:03:44.000Z | 2022-03-18T12:25:41.000Z | src/utils.cpp | dangerdevices/gdstk | bff6b2e5950b9da5b3b3f8bdb653778cf679e592 | [
"BSL-1.0"
] | 35 | 2020-09-08T15:55:01.000Z | 2022-03-29T04:52:58.000Z | /*
Copyright 2020 Lucas Heitzmann Gabrielli.
This file is part of gdstk, distributed under the terms of the
Boost Software License - Version 1.0. See the accompanying
LICENSE file or <http://www.boost.org/LICENSE_1_0.txt>
*/
#include "utils.h"
#include <assert.h>
#include <inttypes.h>
#include <limits.h>
#include <math.h>
#include <stdint.h>
#include <string.h>
#include <time.h>
#include "allocator.h"
#include "vec.h"
// Qhull
#include "libqhull_r/qhull_ra.h"
namespace gdstk {
char* copy_string(const char* str, uint64_t* len) {
uint64_t size = 1 + strlen(str);
char* result = (char*)allocate(size);
memcpy(result, str, size);
if (len) *len = size;
return result;
}
bool is_multiple_of_pi_over_2(double angle, int64_t& m) {
if (angle == 0) {
m = 0;
return true;
} else if (angle == 0.5 * M_PI) {
m = 1;
return true;
} else if (angle == -0.5 * M_PI) {
m = -1;
return true;
} else if (angle == M_PI) {
m = 2;
return true;
} else if (angle == -M_PI) {
m = -2;
return true;
} else if (angle == 1.5 * M_PI) {
m = 3;
return true;
} else if (angle == -1.5 * M_PI) {
m = -3;
return true;
} else if (angle == 2 * M_PI) {
m = 4;
return true;
} else if (angle == -2 * M_PI) {
m = -4;
return true;
}
m = (int64_t)llround(angle / (M_PI / 2));
if (fabs(m * (M_PI / 2) - angle) < 1e-16) return true;
return false;
}
uint64_t arc_num_points(double angle, double radius, double tolerance) {
assert(radius > 0);
assert(tolerance > 0);
double c = 1 - tolerance / radius;
double a = c < -1 ? M_PI : acos(c);
return (uint64_t)(0.5 + 0.5 * fabs(angle) / a);
}
static double modulo(double x, double y) {
double m = fmod(x, y);
return m < 0 ? m + y : m;
}
double elliptical_angle_transform(double angle, double radius_x, double radius_y) {
if (angle == 0 || angle == M_PI || radius_x == radius_y) return angle;
double frac = angle - (modulo(angle + M_PI, 2 * M_PI) - M_PI);
double ell_angle = frac + atan2(radius_x * sin(angle), radius_y * cos(angle));
return ell_angle;
}
double distance_to_line_sq(const Vec2 p, const Vec2 p1, const Vec2 p2) {
const Vec2 v_line = p2 - p1;
const Vec2 v_point = p - p1;
const double c = v_point.cross(v_line);
return c * c / v_line.length_sq();
}
double distance_to_line(const Vec2 p, const Vec2 p1, const Vec2 p2) {
const Vec2 v_line = p2 - p1;
const Vec2 v_point = p - p1;
return fabs(v_point.cross(v_line)) / v_line.length();
}
void segments_intersection(const Vec2 p0, const Vec2 ut0, const Vec2 p1, const Vec2 ut1, double& u0,
double& u1) {
const double den = ut0.cross(ut1);
u0 = 0;
u1 = 0;
if (den >= GDSTK_PARALLEL_EPS || den <= -GDSTK_PARALLEL_EPS) {
const Vec2 delta_p = p1 - p0;
u0 = delta_p.cross(ut1) / den;
u1 = delta_p.cross(ut0) / den;
}
}
void scale_and_round_array(const Array<Vec2> points, double scaling,
Array<IntVec2>& scaled_points) {
scaled_points.ensure_slots(points.count);
scaled_points.count = points.count;
int64_t* s = (int64_t*)scaled_points.items;
double* p = (double*)points.items;
for (uint64_t i = 2 * points.count; i > 0; i--) {
*s++ = (int64_t)llround((*p++) * scaling);
}
}
void big_endian_swap16(uint16_t* buffer, uint64_t n) {
if (IS_BIG_ENDIAN) return;
for (; n > 0; n--) {
uint16_t b = *buffer;
*buffer++ = (b << 8) | (b >> 8);
}
}
void big_endian_swap32(uint32_t* buffer, uint64_t n) {
if (IS_BIG_ENDIAN) return;
for (; n > 0; n--) {
uint32_t b = *buffer;
*buffer++ = (b << 24) | ((b & 0x0000FF00) << 8) | ((b & 0x00FF0000) >> 8) | (b >> 24);
}
}
void big_endian_swap64(uint64_t* buffer, uint64_t n) {
if (IS_BIG_ENDIAN) return;
for (; n > 0; n--) {
uint64_t b = *buffer;
*buffer++ = (b << 56) | ((b & 0x000000000000FF00) << 40) |
((b & 0x0000000000FF0000) << 24) | ((b & 0x00000000FF000000) << 8) |
((b & 0x000000FF00000000) >> 8) | ((b & 0x0000FF0000000000) >> 24) |
((b & 0x00FF000000000000) >> 40) | (b >> 56);
}
}
void little_endian_swap16(uint16_t* buffer, uint64_t n) {
if (!IS_BIG_ENDIAN) return;
for (; n > 0; n--) {
uint16_t b = *buffer;
*buffer++ = (b << 8) | (b >> 8);
}
}
void little_endian_swap32(uint32_t* buffer, uint64_t n) {
if (!IS_BIG_ENDIAN) return;
for (; n > 0; n--) {
uint32_t b = *buffer;
*buffer++ = (b << 24) | ((b & 0x0000FF00) << 8) | ((b & 0x00FF0000) >> 8) | (b >> 24);
}
}
void little_endian_swap64(uint64_t* buffer, uint64_t n) {
if (!IS_BIG_ENDIAN) return;
for (; n > 0; n--) {
uint64_t b = *buffer;
*buffer++ = (b << 56) | ((b & 0x000000000000FF00) << 40) |
((b & 0x0000000000FF0000) << 24) | ((b & 0x00000000FF000000) << 8) |
((b & 0x000000FF00000000) >> 8) | ((b & 0x0000FF0000000000) >> 24) |
((b & 0x00FF000000000000) >> 40) | (b >> 56);
}
}
uint32_t checksum32(uint32_t checksum, const uint8_t* bytes, uint64_t count) {
uint64_t c = checksum;
while (count-- > 0) c = (c + *bytes++) & 0xFFFFFFFF;
return (uint32_t)c;
}
Vec2 eval_line(double t, const Vec2 p0, const Vec2 p1) { return LERP(p0, p1, t); }
Vec2 eval_bezier2(double t, const Vec2 p0, const Vec2 p1, const Vec2 p2) {
const double t2 = t * t;
const double r = 1 - t;
const double r2 = r * r;
Vec2 result = r2 * p0 + 2 * r * t * p1 + t2 * p2;
return result;
}
Vec2 eval_bezier3(double t, const Vec2 p0, const Vec2 p1, const Vec2 p2, const Vec2 p3) {
const double t2 = t * t;
const double t3 = t2 * t;
const double r = 1 - t;
const double r2 = r * r;
const double r3 = r2 * r;
Vec2 result = r3 * p0 + 3 * r2 * t * p1 + 3 * r * t2 * p2 + t3 * p3;
return result;
}
Vec2 eval_bezier(double t, const Vec2* ctrl, uint64_t count) {
Vec2 result;
Vec2* p = (Vec2*)allocate(sizeof(Vec2) * count);
memcpy(p, ctrl, sizeof(Vec2) * count);
const double r = 1 - t;
for (uint64_t j = count - 1; j > 0; j--)
for (uint64_t i = 0; i < j; i++) p[i] = r * p[i] + t * p[i + 1];
result = p[0];
free_allocation(p);
return result;
}
#ifndef NDEBUG
// NOTE: m[rows * cols] is assumed to be stored in row-major order
void print_matrix(double* m, uint64_t rows, uint64_t cols) {
for (uint64_t r = 0; r < rows; r++) {
printf("[");
for (uint64_t c = 0; c < cols; c++) {
if (c) printf("\t");
printf("%.3g", *m++);
}
printf("]\n");
}
}
#endif
// NOTE: m[rows * cols] must be stored in row-major order
// NOTE: pivots[rows] returns the pivoting order
uint64_t gauss_jordan_elimination(double* m, uint64_t* pivots, uint64_t rows, uint64_t cols) {
assert(cols >= rows);
uint64_t result = 0;
uint64_t* p = pivots;
for (uint64_t i = 0; i < rows; ++i) {
*p++ = i;
}
for (uint64_t i = 0; i < rows; ++i) {
// Select pivot: row with largest absolute value at column i
double pivot_value = fabs(m[pivots[i] * cols + i]);
uint64_t pivot_row = i;
for (uint64_t j = i + 1; j < rows; ++j) {
double candidate = fabs(m[pivots[j] * cols + i]);
if (candidate > pivot_value) {
pivot_value = candidate;
pivot_row = j;
}
}
if (pivot_value == 0) {
result += 1;
continue;
}
uint64_t row = pivots[pivot_row];
pivots[pivot_row] = pivots[i];
pivots[i] = row;
// Scale row
double* element = m + (row * cols + i);
double factor = 1.0 / *element;
for (uint64_t j = i; j < cols; ++j) {
*element++ *= factor;
}
// Zero i-th column from other rows
for (uint64_t r = 0; r < rows; ++r) {
if (r == row) continue;
element = m + row * cols;
double* other_row = m + r * cols;
factor = other_row[i];
for (uint64_t j = 0; j < cols; ++j) {
*other_row++ -= factor * *element++;
}
}
}
return result;
}
// NOTE: Matrix stored in column-major order!
void hobby_interpolation(uint64_t count, Vec2* points, double* angles, bool* angle_constraints,
Vec2* tension, double initial_curl, double final_curl, bool cycle) {
const double A = sqrt(2.0);
const double B = 1.0 / 16.0;
const double C = 0.5 * (3.0 - sqrt(5.0));
double* m = (double*)allocate(sizeof(double) * (2 * count * (2 * count + 1)));
uint64_t* pivots = (uint64_t*)allocate(sizeof(uint64_t) * (2 * count));
Vec2* pts = points;
Vec2* tens = tension;
double* ang = angles;
bool* ang_c = angle_constraints;
uint64_t points_size = count;
uint64_t rotate = 0;
if (cycle) {
while (rotate < count && !angle_constraints[rotate]) rotate++;
if (rotate == count) {
// No angle constraints
const uint64_t rows = 2 * count;
const uint64_t cols = rows + 1;
Vec2 v = points[3] - points[0];
Vec2 v_prev = points[0] - points[3 * (count - 1)];
double length_v = v.length();
double delta_prev = v_prev.angle();
memset(m, 0, sizeof(double) * rows * cols);
for (uint64_t i = 0; i < count; i++) {
const uint64_t i_1 = i == 0 ? count - 1 : i - 1;
const uint64_t i1 = i == count - 1 ? 0 : i + 1;
const uint64_t i2 = i < count - 2 ? i + 2 : (i == count - 2 ? 0 : 1);
const uint64_t j = count + i;
const uint64_t j_1 = count + i_1;
const uint64_t j1 = count + i1;
const double delta = v.angle();
const Vec2 v_next = points[3 * i2] - points[3 * i1];
const double length_v_next = v_next.length();
double psi = delta - delta_prev;
while (psi <= -M_PI) psi += 2 * M_PI;
while (psi > M_PI) psi -= 2 * M_PI;
m[i * cols + rows] = -psi;
m[i * cols + i] = 1;
m[i * cols + j_1] = 1;
// A_i
m[j * cols + i] = length_v_next * tension[i2].u * tension[i1].u * tension[i1].u;
// B_{i+1}
m[j * cols + i1] = -length_v * tension[i].v * tension[i1].v * tension[i1].v *
(1 - 3 * tension[i2].u);
// C_{i+1}
m[j * cols + j] = length_v_next * tension[i2].u * tension[i1].u * tension[i1].u *
(1 - 3 * tension[i].v);
// D_{i+2}
m[j * cols + j1] = -length_v * tension[i].v * tension[i1].v * tension[i1].v;
v_prev = v;
v = v_next;
length_v = length_v_next;
delta_prev = delta;
}
gauss_jordan_elimination(m, pivots, rows, cols);
// NOTE: re-use the first row of m to temporarily hold the angles
double* theta = m;
double* phi = theta + count;
for (uint64_t r = 0; r < count; r++) {
theta[r] = m[pivots[r] * cols + rows];
phi[r] = m[pivots[count + r] * cols + rows];
}
Vec2* cta = points + 1;
Vec2* ctb = points + 2;
v = points[3] - points[0];
Vec2 w = cplx_from_angle(theta[0] + v.angle());
for (uint64_t i = 0; i < count; i++, cta += 3, ctb += 3) {
const uint64_t i1 = i == count - 1 ? 0 : i + 1;
const uint64_t i2 = i < count - 2 ? i + 2 : (i == count - 2 ? 0 : 1);
const double st = sin(theta[i]);
const double ct = cos(theta[i]);
const double sp = sin(phi[i]);
const double cp = cos(phi[i]);
const double alpha = A * (st - B * sp) * (sp - B * st) * (ct - cp);
const Vec2 v_next = points[3 * i2] - points[3 * i1];
const double _length_v = v.length();
const double delta_next = v_next.angle();
const Vec2 w_next = cplx_from_angle(theta[i1] + delta_next);
*cta = points[3 * i] + w * _length_v * ((2 + alpha) / (1 + (1 - C) * ct + C * cp)) /
(3 * tension[i].v);
*ctb = points[3 * i1] - w_next * _length_v *
((2 - alpha) / (1 + (1 - C) * cp + C * ct)) /
(3 * tension[i1].u);
v = v_next;
w = w_next;
}
free_allocation(m);
free_allocation(pivots);
return;
}
// Cycle, but with angle constraint.
// Rotate inputs and add append last point to cycle,
// then use open curve solver.
points_size++;
pts = (Vec2*)allocate(sizeof(Vec2) * 3 * points_size);
memcpy(pts, points + 3 * rotate, sizeof(Vec2) * 3 * (count - rotate));
memcpy(pts + 3 * (count - rotate), points, sizeof(Vec2) * 3 * (rotate + 1));
tens = (Vec2*)allocate(sizeof(Vec2) * points_size);
memcpy(tens, tension + rotate, sizeof(Vec2) * (count - rotate));
memcpy(tens + count - rotate, tension, sizeof(Vec2) * (rotate + 1));
ang = (double*)allocate(sizeof(double) * points_size);
memcpy(ang, angles + rotate, sizeof(double) * (count - rotate));
memcpy(ang + count - rotate, angles, sizeof(double) * (rotate + 1));
ang_c = (bool*)allocate(sizeof(bool) * points_size);
memcpy(ang_c, angle_constraints + rotate, sizeof(bool) * (count - rotate));
memcpy(ang_c + count - rotate, angle_constraints, sizeof(bool) * (rotate + 1));
}
{
// Open curve solver
const uint64_t n = points_size - 1;
double* theta = (double*)allocate(sizeof(double) * n);
double* phi = (double*)allocate(sizeof(double) * n);
if (ang_c[0]) theta[0] = ang[0] - (pts[3] - pts[0]).angle();
uint64_t i = 0;
while (i < n) {
uint64_t j = i + 1;
while (j < n + 1 && !ang_c[j]) j++;
if (j == n + 1)
j--;
else {
phi[j - 1] = (pts[3 * j] - pts[3 * (j - 1)]).angle() - ang[j];
if (j < n) theta[j] = ang[j] - (pts[3 * (j + 1)] - pts[3 * j]).angle();
}
// Solve curve pts[i] thru pts[j]
const uint64_t range = j - i;
const uint64_t rows = 2 * range;
const uint64_t cols = rows + 1;
memset(m, 0, sizeof(double) * rows * cols);
Vec2 v_prev = pts[3 * (i + 1)] - pts[3 * i];
double delta_prev = v_prev.angle();
double length_v_prev = v_prev.length();
for (uint64_t k = 0; k < range - 1; k++) { // [0; range - 2]
const uint64_t k1 = k + 1; // [1; range - 1]
const uint64_t i0 = i + k; // [i; j - 2]
const uint64_t i1 = i0 + 1; // [i + 1; j - 1]
const uint64_t i2 = i0 + 2; // [i + 2; j]
const uint64_t l = k + range; // [range; 2 * range - 2]
const uint64_t l1 = l + 1; // [range + 1; range - 1]
Vec2 v = pts[3 * i2] - pts[3 * i1];
const double delta = v.angle();
const double length_v = v.length();
double psi = delta - delta_prev;
while (psi <= -M_PI) psi += 2 * M_PI;
while (psi > M_PI) psi -= 2 * M_PI;
m[k1 * cols + rows] = -psi;
m[k1 * cols + k1] = 1;
m[k1 * cols + l] = 1;
// A_k
m[l * cols + k] = length_v * tens[i2].u * tens[i1].u * tens[i1].u;
// B_{k+1}
m[l * cols + k1] =
-length_v_prev * tens[i0].v * tens[i1].v * tens[i1].v * (1 - 3 * tens[i2].u);
// C_{k+1}
m[l * cols + l] =
length_v * tens[i2].u * tens[i1].u * tens[i1].u * (1 - 3 * tens[i0].v);
// D_{k+2}
m[l * cols + l1] = -length_v_prev * tens[i0].v * tens[i1].v * tens[i1].v;
delta_prev = delta;
length_v_prev = length_v;
}
if (ang_c[i]) {
m[0 * cols + rows] = theta[i];
// B_0
m[0] = 1;
// D_1
// m[0 * cols + range] = 0;
} else {
const double to3 = tens[0].v * tens[0].v * tens[0].v;
const double cti3 = initial_curl * tens[1].u * tens[1].u * tens[1].u;
// B_0
m[0] = to3 * (1 - 3 * tens[1].u) - cti3;
// D_1
m[0 * cols + range] = to3 - cti3 * (1 - 3 * tens[0].v);
}
if (ang_c[j]) {
m[(rows - 1) * cols + rows] = phi[j - 1];
// A_{range-1}
// m[(rows - 1) * cols + (range - 1)] = 0;
// C_range
m[(rows - 1) * cols + (rows - 1)] = 1;
} else {
const double ti3 = tens[n].u * tens[n].u * tens[n].u;
const double cto3 = final_curl * tens[n - 1].v * tens[n - 1].v * tens[n - 1].v;
// A_{range-1}
m[(rows - 1) * cols + (range - 1)] = ti3 - cto3 * (1 - 3 * tens[n].u);
// C_range
m[(rows - 1) * cols + (rows - 1)] = ti3 * (1 - 3 * tens[n - 1].v) - cto3;
}
if (range > 1 || !ang_c[i] || !ang_c[j]) {
// printf("Solving range [%" PRIu64 ", %" PRIu64 "]\n\n", i, j);
// print_matrix(m, rows, cols);
gauss_jordan_elimination(m, pivots, rows, cols);
for (uint64_t r = 0; r < range; r++) {
theta[i + r] = m[pivots[r] * cols + rows];
phi[i + r] = m[pivots[range + r] * cols + rows];
}
// printf("\n");
// print_matrix(m, rows, cols);
// printf("\n");
}
i = j;
}
Vec2 v = pts[3] - pts[0];
Vec2 w = cplx_from_angle(theta[0] + v.angle());
for (uint64_t ii = 0; ii < n; ii++) {
const uint64_t i1 = ii + 1;
const uint64_t i2 = ii == n - 1 ? 0 : ii + 2;
const uint64_t ci = ii + rotate >= count ? ii + rotate - count : ii + rotate;
const double st = sin(theta[ii]);
const double ct = cos(theta[ii]);
const double sp = sin(phi[ii]);
const double cp = cos(phi[ii]);
const double alpha = A * (st - B * sp) * (sp - B * st) * (ct - cp);
const Vec2 v_next = pts[3 * i2] - pts[3 * i1];
const double length_v = v.length();
const Vec2 w_next = ii == n - 1 ? cplx_from_angle(v.angle() - phi[n - 1])
: cplx_from_angle(theta[i1] + v_next.angle());
points[3 * ci + 1] = pts[3 * ii] + w * length_v *
((2 + alpha) / (1 + (1 - C) * ct + C * cp)) /
(3 * tens[ii].v);
points[3 * ci + 2] = pts[3 * i1] - w_next * length_v *
((2 - alpha) / (1 + (1 - C) * cp + C * ct)) /
(3 * tens[i1].u);
v = v_next;
w = w_next;
}
if (cycle) {
free_allocation(pts);
free_allocation(tens);
free_allocation(ang);
free_allocation(ang_c);
}
free_allocation(theta);
free_allocation(phi);
}
free_allocation(m);
free_allocation(pivots);
}
void convex_hull(const Array<Vec2> points, Array<Vec2>& result) {
if (points.count < 4) {
result.extend(points);
return;
} else if (points.count > INT_MAX) {
Array<Vec2> partial;
partial.count = INT_MAX - 1;
partial.items = points.items;
Array<Vec2> temp = {0};
convex_hull(partial, temp);
partial.count = points.count - (INT_MAX - 1);
partial.items = points.items + (INT_MAX - 1);
temp.extend(partial);
convex_hull(temp, result);
temp.clear();
return;
}
qhT qh;
QHULL_LIB_CHECK;
qh_zero(&qh, stderr);
char command[256] = "qhull";
int exitcode = qh_new_qhull(&qh, 2, (int)points.count, (double*)points.items, false, command,
NULL, stderr);
if (exitcode == 0) {
result.ensure_slots(qh.num_facets);
Vec2* point = result.items + result.count;
result.count += qh.num_facets;
vertexT* qh_vertex = NULL;
facetT* qh_facet = qh_nextfacet2d(qh.facet_list, &qh_vertex);
for (int64_t i = qh.num_facets; i > 0; i--, point++) {
point->x = qh_vertex->point[0];
point->y = qh_vertex->point[1];
qh_facet = qh_nextfacet2d(qh_facet, &qh_vertex);
}
} else if (exitcode == qh_ERRsingular) {
// QHull errors for singular input (collinear points in 2D)
Vec2 min = {DBL_MAX, DBL_MAX};
Vec2 max = {-DBL_MAX, -DBL_MAX};
Vec2* p = points.items;
for (uint64_t num = points.count; num > 0; num--, p++) {
if (p->x < min.x) min.x = p->x;
if (p->x > max.x) max.x = p->x;
if (p->y < min.y) min.y = p->y;
if (p->y > max.y) max.y = p->y;
}
if (min.x < max.x) {
result.append(min);
result.append(max);
}
} else {
// The least we can do
result.extend(points);
}
#ifdef qh_NOmem
qh_freeqhull(&qh, qh_ALL);
#else
int curlong, totlong;
qh_freeqhull(&qh, !qh_ALL); /* free long memory */
qh_memfreeshort(&qh, &curlong, &totlong); /* free short memory and memory allocator */
if (curlong || totlong) {
fprintf(
stderr,
"[GDSTK] Qhull internal warning: did not free %d bytes of long memory (%d pieces)\n",
totlong, curlong);
}
#endif
}
char* double_print(double value, uint32_t precision, char* buffer, size_t buffer_size) {
uint64_t len = snprintf(buffer, buffer_size, "%.*f", precision, value);
if (precision) {
while (buffer[--len] == '0')
;
if (buffer[len] != '.') len++;
buffer[len] = 0;
}
return buffer;
}
tm* get_now(tm& result) {
time_t t = time(NULL);
#ifdef _WIN32
localtime_s(&result, &t);
#else
localtime_r(&t, &result);
#endif
return &result;
}
// Kenneth Kelly's 22 colors of maximum contrast (minus B/W: "F2F3F4", "222222")
const char* colors[] = {"F3C300", "875692", "F38400", "A1CAF1", "BE0032", "C2B280", "848482",
"008856", "E68FAC", "0067A5", "F99379", "604E97", "F6A600", "B3446C",
"DCD300", "882D17", "8DB600", "654522", "E25822", "2B3D26"};
inline static const char* default_color(Tag tag) {
return colors[(2 + get_layer(tag) + get_type(tag) * 13) % COUNT(colors)];
}
const char* default_svg_shape_style(Tag tag) {
static char buffer[] = "stroke: #XXXXXX; fill: #XXXXXX; fill-opacity: 0.5;";
const char* c = default_color(tag);
memcpy(buffer + 9, c, 6);
memcpy(buffer + 24, c, 6);
return buffer;
}
const char* default_svg_label_style(Tag tag) {
static char buffer[] = "stroke: none; fill: #XXXXXX;";
const char* c = default_color(tag);
memcpy(buffer + 21, c, 6);
return buffer;
}
} // namespace gdstk
| 36.007429 | 100 | 0.48566 |
ac5ddef4331a6936289da6c40d87dc448eaf254e | 2,985 | cpp | C++ | traffic_count_hw_design/fromFrameToBlobCount.cpp | necst/fard | ce9078a50235f3a519ef4b2ce7a0e87f1de794e4 | [
"Apache-2.0"
] | 3 | 2019-07-09T08:03:22.000Z | 2019-12-03T14:26:16.000Z | traffic_count_hw_design/fromFrameToBlobCount.cpp | necst/fard | ce9078a50235f3a519ef4b2ce7a0e87f1de794e4 | [
"Apache-2.0"
] | 1 | 2021-07-16T17:58:18.000Z | 2021-07-16T17:58:18.000Z | traffic_count_hw_design/fromFrameToBlobCount.cpp | necst/fard | ce9078a50235f3a519ef4b2ce7a0e87f1de794e4 | [
"Apache-2.0"
] | null | null | null | #include <stdio.h>
#include <stdlib.h>
#include "fromFrameToBlobCount.h"
//Images
unsigned char background[WIDTH*HEIGHT*DEPTH], input[WIDTH*HEIGHT*DEPTH];
unsigned char input_grey[WIDTH*HEIGHT];
unsigned char foreground[WIDTH*HEIGHT], foreground_clean[WIDTH*HEIGHT];
void fromFrameToBlobCount(UIntStream &streamIn, UIntStream &streamOut, int action, int md_threshold, int erosion_iteration, int dilate_iteration, int second_erosion_iteration)
{
unsigned int width = WIDTH;
unsigned int height = HEIGHT;
#pragma HLS INTERFACE axis register port=streamIn
#pragma HLS INTERFACE axis register port=streamOut
#pragma HLS INTERFACE s_axilite register port=action bundle=control
#pragma HLS INTERFACE s_axilite register port=width bundle=control
#pragma HLS INTERFACE s_axilite register port=height bundle=control
#pragma HLS INTERFACE s_axilite register port=md_threshold bundle=control
#pragma HLS INTERFACE s_axilite register port=erosion_iteration bundle=control
#pragma HLS INTERFACE s_axilite register port=dilate_iteration bundle=control
#pragma HLS INTERFACE s_axilite register port=second_erosion_iteration bundle=control
#pragma HLS INTERFACE s_axilite register port=return bundle=control
//DMA auxintData
int intData, numOfInt;
int mask = 0xFF;
//Aux
unsigned int i, j, k, count, blobs;
numOfInt = (WIDTH*HEIGHT*DEPTH)/4;
if (action == LOAD) {
/*Load background*/
for(i = 0; i < numOfInt; i++) {
#pragma HLS PIPELINE II=1
intData = streamPop < int, UIntAxis, UIntStream > (streamIn);
((int *)background)[i] = intData;
}
rgb2grey(background, background);
} else if (action == PROCESS) {
/*Load frame*/
numOfInt = (WIDTH*HEIGHT*DEPTH)/4;
for(i = 0; i < numOfInt; i++)
{
#pragma HLS PIPELINE II=1
intData = streamPop < int, UIntAxis, UIntStream > (streamIn);
((int *)input)[i] = intData;
}
/*Image processing*/
//Grey scale conversion
rgb2grey(input, input_grey);
//Foreground extraction
foregroundExtraction(input_grey, background, foreground, md_threshold);
//Erosion filter
for(i = 0; i < erosion_iteration; i++)
{
erode_filter<180,180,3>(foreground, foreground_clean);
copy(foreground_clean, foreground);
}
//Dilation filter
for(i = 0; i < dilate_iteration; i++)
{
dilate(foreground, foreground_clean);
copy(foreground_clean, foreground);
}
//second erosion filter
for(i = 0; i < second_erosion_iteration; i++)
{
erode_filter<180,180,3>(foreground, foreground_clean);
copy(foreground_clean, foreground);
}
//Clean borders
cleanBorders(foreground_clean);
//Blobs count
count = blobsCount(foreground_clean);
streamPush < unsigned int, UIntAxis, UIntStream > (count, 1, streamOut, BIT_WIDTH);
}
}
| 31.09375 | 175 | 0.676047 |
ac5e1706224622eb8bbd928ba02326fa6394a112 | 1,282 | hh | C++ | src/test/resources/samples/langs/Hack/HomeController.hh | JavascriptID/sourcerer-app | 9ad05f7c6a18c03793c8b0295a2cb318118f6245 | [
"MIT"
] | 8,271 | 2015-01-01T15:04:43.000Z | 2022-03-31T06:18:14.000Z | src/test/resources/samples/langs/Hack/HomeController.hh | JavascriptID/sourcerer-app | 9ad05f7c6a18c03793c8b0295a2cb318118f6245 | [
"MIT"
] | 3,238 | 2015-01-01T14:25:12.000Z | 2022-03-30T17:37:51.000Z | src/test/resources/samples/langs/Hack/HomeController.hh | JavascriptID/sourcerer-app | 9ad05f7c6a18c03793c8b0295a2cb318118f6245 | [
"MIT"
] | 4,070 | 2015-01-01T11:40:51.000Z | 2022-03-31T13:45:53.000Z | <?hh // strict
/**
* Copyright (c) 2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
require_once $_SERVER['DOCUMENT_ROOT'].'/core/controller/init.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/core/controller/standard-page/init.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/vendor/hhvm/xhp/src/init.php';
class HomeController extends GetController {
use StandardPage;
protected function getTitle(): string {
return 'Hack Cookbook';
}
protected function renderMainColumn(): :xhp {
return <div>
<h1>Cookbook</h1>
<p>
The Hack Cookbook helps you write Hack code by giving you examples of
Hack code. It is written in Hack and is open source. If you
<a href="http://github.com/facebook/hack-example-site">
head over to GitHub,
</a>
you can read the code, check out the repository, and run it
yourself. The recipes in this cookbook are small examples that
illustrate how to use Hack to solve common and interesting problems.
</p>
</div>;
}
}
| 32.871795 | 81 | 0.686427 |
ac5e933da290a583caceecbddee618722d84403a | 2,215 | cc | C++ | poj/1/1540.cc | eagletmt/procon | adbe503eb3c1bbcc1538b2ee8988aa353937e8d4 | [
"MIT"
] | 1 | 2015-04-17T09:54:23.000Z | 2015-04-17T09:54:23.000Z | poj/1/1540.cc | eagletmt/procon | adbe503eb3c1bbcc1538b2ee8988aa353937e8d4 | [
"MIT"
] | null | null | null | poj/1/1540.cc | eagletmt/procon | adbe503eb3c1bbcc1538b2ee8988aa353937e8d4 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <map>
using namespace std;
struct edge
{
string word, output;
int to;
};
void do_output(const string& out, char c)
{
if (out == "\b") {
cout << c;
} else {
cout << out;
}
}
void operate(const vector<vector<edge> >& g)
{
int n = 1; // START
while (n != 0) {
int c = cin.get();
int def_to = -1;
string def_out;
for (vector<edge>::const_iterator it = g[n].begin(); it != g[n].end(); ++it) {
if (it->word == "\b") {
def_to = it->to;
def_out = it->output;
} else if (it->word.find(c) != string::npos) {
n = it->to;
do_output(it->output, c);
goto NEXT;
}
}
if (def_to == -1) {
throw "incorrect";
}
n = def_to;
do_output(def_out, c);
NEXT:
;
}
}
void normalize(string& s)
{
for (string::iterator it = s.begin(); it != s.end(); ++it) {
if (*it == '\\') {
it = s.erase(it);
switch (*it) {
case 'b':
*it = ' '; break;
case 'n':
*it = '\n'; break;
case '\\':
break;
case '0':
s = ""; return;
case 'c':
s = "\b"; return;
default:
throw "unknown sequence";
}
}
}
}
int main()
{
int N;
for (int Ti = 1; cin >> N && N != 0; Ti++) {
map<string,int> d;
d["END"] = 0; d["START"] = 1;
vector<vector<edge> >g(2);
for (int i = 0; i < N; i++) {
string name;
int M;
cin >> name >> M;
int u;
if (d.count(name)) {
u = d[name];
} else {
u = d[name] = g.size();
g.push_back(vector<edge>());
}
for (int j = 0; j < M; j++) {
edge e;
string label;
cin >> e.word >> label >> e.output;
normalize(e.word);
normalize(e.output);
if (d.count(label)) {
e.to = d[label];
} else {
e.to = d[label] = g.size();
g.push_back(vector<edge>());
}
g[u].push_back(e);
}
}
int c = cin.get();
while (c != '\n') {
c = cin.get();
}
cout << "Finite State Machine " << Ti << ":" << endl;
operate(g);
}
return 0;
}
| 19.429825 | 82 | 0.428442 |
ac5fcec114a163f12d822091aba08574cff84eba | 2,383 | cpp | C++ | Game/UI_Element_Slider.cpp | Chr157i4n/OpenGL_Space_Game | b4cd4ab65385337c37f26af641597c5fc9126f04 | [
"MIT"
] | 3 | 2020-08-05T00:02:30.000Z | 2021-08-23T00:41:24.000Z | Game/UI_Element_Slider.cpp | Chr157i4n/OpenGL_Space_Game | b4cd4ab65385337c37f26af641597c5fc9126f04 | [
"MIT"
] | null | null | null | Game/UI_Element_Slider.cpp | Chr157i4n/OpenGL_Space_Game | b4cd4ab65385337c37f26af641597c5fc9126f04 | [
"MIT"
] | 2 | 2021-07-03T19:32:08.000Z | 2021-08-19T18:48:52.000Z | #include "UI_Element_Slider.h"
#include "Game.h"
UI_Element_Slider::UI_Element_Slider(int x, int y, int w, int h, uint64 lifespan, std::string label, glm::vec4 foreColor, glm::vec4 backColor, bool isDebugInfo) : UI_Element(x, y, w, h, lifespan, foreColor, backColor, isDebugInfo)
{
this->label = label;
labelOffsetX = 0;
labelOffsetY = h/2;
}
void UI_Element_Slider::drawUI_Element()
{
float _x = x;
float _y = y;
float _w = w;
float _h = h;
float barThickness = 0.01;
float SliderThickness = 0.04;
float _value = (value - minValue) / (maxValue - minValue);
_x /= Game::getWindowWidth();
_y /= Game::getWindowHeight();
_w /= Game::getWindowWidth();
_h /= Game::getWindowHeight();
_x = _x * 2 - 1;
_y = _y * 2 - 1;
_w = _w * 2;
_h = _h * 2;
if (isSelected)
{
backColor.a = 1;
}
else
{
backColor.a = 0.4;
}
//background
glColor4f(backColor.r, backColor.g, backColor.b, backColor.a);
glBegin(GL_QUADS);
glVertex2f(_x , _y + 0.25*_h - barThickness);
glVertex2f(_x + _w, _y + 0.25*_h - barThickness);
glVertex2f(_x + _w, _y + 0.25*_h);
glVertex2f(_x, _y + 0.25*_h);
glEnd();
//Slider
glColor4f(foreColor.r, foreColor.g, foreColor.b, 1);
glBegin(GL_QUADS);
glVertex2f(_x + _value * _w - SliderThickness / 2, _y + 0.25 * _h - SliderThickness / 2); //left bottom
glVertex2f(_x + _value * _w + SliderThickness / 2, _y + 0.25 * _h - SliderThickness / 2); //right bottom
glVertex2f(_x + _value * _w + SliderThickness / 2, _y + 0.25 * _h + SliderThickness / 2); //right top
glVertex2f(_x + _value * _w - SliderThickness / 2, _y + 0.25 * _h + SliderThickness / 2); //left top
glEnd();
UI::drawString(x + labelOffsetX, y+labelOffsetY, label, foreColor);
}
int UI_Element_Slider::onMouseDrag(float mouseX, float mouseY, SDL_MouseButtonEvent* buttonEvent)
{
float newValue = (mouseX - this->getX()) / this->getW();
if (newValue < 0.05) newValue = 0;
if (newValue > 0.95) newValue = 1;
newValue = newValue * (maxValue - minValue) + minValue;
this->setValue(newValue);
return this->callCallBack();
}
int UI_Element_Slider::increase()
{
this->setValue(this->getValue() + 1 * (maxValue - minValue) * 0.5 * Game::getDelta()/1000);
return this->callCallBack();
}
int UI_Element_Slider::decrease()
{
this->setValue(this->getValue() - 1 * (maxValue - minValue) * 0.5 * Game::getDelta()/1000);
return this->callCallBack();
}
| 27.390805 | 230 | 0.664289 |
ac60947c206cb6be3969c04c3c524a5d8698d7c6 | 753 | cpp | C++ | codeforces/1392B.cpp | sgrade/cpptest | 84ade6ec03ea394d4a4489c7559d12b4799c0b62 | [
"MIT"
] | null | null | null | codeforces/1392B.cpp | sgrade/cpptest | 84ade6ec03ea394d4a4489c7559d12b4799c0b62 | [
"MIT"
] | null | null | null | codeforces/1392B.cpp | sgrade/cpptest | 84ade6ec03ea394d4a4489c7559d12b4799c0b62 | [
"MIT"
] | null | null | null | // B. Omkar and Infinity Clock
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(){
int t;
cin >> t;
while(t--){
int n;
unsigned long long k;
cin >> n >> k;
vector<int> v(n);
for (int i=0; i<n; ++i){
cin >> v[i];
}
unsigned long long operations = 1;
if (k>1) {
operations = k%2 != 0 ? 3 : 2;
}
while (operations--){
int vMax = *max_element(v.begin(), v.end()) ;
for (int i = 0; i<n; ++i){
v[i] = vMax - v[i];
}
}
for (auto it: v){
cout << it << ' ';
}
cout << endl;
}
return 0;
} | 16.733333 | 57 | 0.393094 |
ac63cbc6bfe1c0fa5008a3241dcbd4d707479905 | 11,982 | hpp | C++ | include/ModernDD/NodeBddReducer.hpp | DanielKowalczyk1984/Decision-Diagrams-in-Modern-C | 0d04e1e31316281ab20c559a37fdc14a881fecb5 | [
"Unlicense"
] | null | null | null | include/ModernDD/NodeBddReducer.hpp | DanielKowalczyk1984/Decision-Diagrams-in-Modern-C | 0d04e1e31316281ab20c559a37fdc14a881fecb5 | [
"Unlicense"
] | null | null | null | include/ModernDD/NodeBddReducer.hpp | DanielKowalczyk1984/Decision-Diagrams-in-Modern-C | 0d04e1e31316281ab20c559a37fdc14a881fecb5 | [
"Unlicense"
] | null | null | null | #ifndef NODE_BDD_REDUCER_HPP
#define NODE_BDD_REDUCER_HPP
#include <cassert> // for assert
#include <cstddef> // for size_t
#include <ext/alloc_traits.h> // for __alloc_traits<>::value_type
#include <memory> // for allocator_traits<>::value_type
#include <range/v3/view/enumerate.hpp>
#include <range/v3/view/reverse.hpp>
#include <span> // for span
#include <unordered_set> // for unordered_set
#include <vector> // for vector
#include "NodeBddTable.hpp" // for TableHandler, NodeTableEntity
#include "NodeId.hpp" // for NodeId
#include "util/MyHashTable.hpp" // for MyHashDefault
template <typename T, bool BDD, bool ZDD>
class DdReducer {
TableHandler<T> oldDiagram;
NodeTableEntity<T>& input;
TableHandler<T> newDiagram;
NodeTableEntity<T>& output;
std::vector<std::vector<NodeId>> newIdTable;
std::vector<std::vector<NodeId*>> rootPtr;
size_t counter = 1;
bool readyForSequentialReduction;
public:
explicit DdReducer(TableHandler<T>& diagram, bool useMP = false)
: oldDiagram(std::move(diagram)),
input(*oldDiagram),
newDiagram(input.numRows()),
output(*newDiagram),
newIdTable(input.numRows()),
rootPtr(input.numRows()),
readyForSequentialReduction(false) {
diagram = std::move(newDiagram);
input.initTerminals();
input.makeIndex(useMP);
newIdTable[0].resize(2);
newIdTable[0][0] = 0;
newIdTable[0][1] = 1;
}
private:
/**
* Applies the node deletion rules.
* It is required before serial reduction (Algorithm-R)
* in order to make lower-level index safe.
*/
void makeReadyForSequentialReduction() {
if (readyForSequentialReduction) {
return;
}
for (auto i = 2UL; i < input.numRows(); ++i) {
// size_t const m = input[i].size();
// std::span const tt{input[i].data(), input[i].size()};
// T* const tt = input[i].data();
for (auto& it : input[i]) {
for (auto& f : it) {
// NodeId& f = it[b];
if (f.row() == 0) {
continue;
}
NodeId f0 = input.child(f, 0);
NodeId deletable = 0;
bool del = true;
for (size_t bb = ZDD ? 1UL : 0UL; bb < 2; ++bb) {
if (input.child(f, bb) != deletable) {
del = false;
}
}
if (del) {
f = f0;
}
}
}
}
input.makeIndex();
readyForSequentialReduction = true;
}
public:
/**
* Sets a root node.
* @param root reference to a root node ID storage.
*/
void setRoot(NodeId& root) { rootPtr[root.row()].push_back(&root); }
/**
* Reduces one level.
* @param i level.
* @param useMP use an algorithm for multiple processors.
*/
void reduce(size_t i) {
if (BDD) {
algorithmZdd(i);
} else if (ZDD) {
algorithmR(i);
}
}
private:
/**
* Reduces one level using Algorithm-R.
* @param i level.
*/
void algorithmR(size_t i) {
makeReadyForSequentialReduction();
size_t const m = input[i].size();
// T* const tt = input[i].data();
std::vector<NodeId>& newId = newIdTable[i];
newId.resize(m);
// for (size_t j = m - 1; j + 1 > 0; --j) {
for (auto&& [j, f] :
input[i] | ranges::views::enumerate | ranges::views::reverse) {
auto& f0 = f[0];
auto& f1 = f[1];
if (f0.row() != 0) {
f0 = newIdTable[f0.row()][f0.col()];
}
if (f1.row() != 0) {
f1 = newIdTable[f1.row()][f1.col()];
}
if (ZDD && f1 == 0) {
newId[j] = f0;
} else {
newId[j] =
NodeId(counter + 1, m); // tail of f0-equivalent list
}
}
{
auto const& levels = input.lowerLevels(counter);
for (auto& t : levels) {
newIdTable[t].clear();
}
}
size_t mm = 0;
for (size_t j = 0; j < m; ++j) {
assert(newId[j].row() <= counter + 1);
if (newId[j].row() <= counter) {
continue;
}
auto& g0 = input[i][j][0];
assert(newId[j].row() == counter + 1);
newId[j] = NodeId(counter, mm++, g0.hasEmpty());
}
auto const& levels = input.lowerLevels(counter);
for (const auto& t : levels) {
input[t].clear();
}
if (mm > 0U) {
output.initRow(counter, mm);
std::span<T> nt{output[counter].data(), output[counter].size()};
for (size_t j = 0; j < m; ++j) {
// NodeId const& f0 = tt[j].branch[0];
auto const& f1 = input[i][j][1];
if (ZDD && f1 == 0) { // forwarded
assert(newId[j].row() < counter);
} else {
assert(newId[j].row() == counter);
auto k = newId[j].col();
nt[k] = input[i][j];
nt[k].set_node_id_label(newId[j]);
if (nt[k].get_ptr_node_id() != 0) {
nt[k].set_ptr_node_id(newId[j]);
}
}
}
counter++;
}
for (auto& k : rootPtr[i]) {
NodeId& root = *k;
root = newId[root.col()];
}
}
/**
* Reduces one level using Algorithm-R.
* @param i level.
*/
void algorithmZdd(size_t i) {
makeReadyForSequentialReduction();
size_t const m = input[i].size();
std::span<T> const tt{input[i].data(), input[i].size()};
NodeId const mark(i, m);
auto& newId = newIdTable[i];
newId.resize(m);
for (size_t j = m - 1; j + 1 > 0; --j) {
auto& f0 = tt[j][0];
auto& f1 = tt[j][1];
if (f0.row() != 0) {
f0 = newIdTable[f0.row()][f0.col()];
}
if (f1.row() != 0) {
f1 = newIdTable[f1.row()][f1.col()];
}
if (ZDD && f1 == 0) {
newId[j] = f0;
} else {
auto& f00 = input.child(f0, 0UL);
auto& f01 = input.child(f0, 1UL);
if (f01 != mark) { // the first touch from this level
f01 = mark; // mark f0 as touched
newId[j] = NodeId(i + 1, m); // tail of f0-equivalent list
} else {
newId[j] = f00; // next of f0-equivalent list
}
f00 = NodeId(i + 1, j); // new head of f0-equivalent list
}
}
{
auto const& levels = input.lowerLevels(i);
for (auto& t : levels) {
newIdTable[t].clear();
}
}
size_t mm = 0;
for (auto j = 0UL; j < m; ++j) {
NodeId const f(i, j);
assert(newId[j].row() <= i + 1);
if (newId[j].row() <= i) {
continue;
}
for (auto k = j; k < m;) { // for each g in f0-equivalent list
assert(j <= k);
NodeId const g(i, k);
auto& g0 = tt[k][0];
auto& g1 = tt[k][1];
auto& g10 = input.child(g1, 0);
auto& g11 = input.child(g1, 1);
assert(g1 != mark);
assert(newId[k].row() == i + 1);
auto next = newId[k].col();
if (g11 != f) { // the first touch to g1 in f0-equivalent list
g11 = f; // mark g1 as touched
g10 = g; // record g as a canonical node for <f0,g1>
newId[k] = NodeId(i, mm++, g0.hasEmpty());
} else {
g0 = g10; // make a forward link
g1 = mark; // mark g as forwarded
newId[k] = 0;
}
k = next;
}
}
auto const& levels = input.lowerLevels(i);
for (auto& t : levels) {
input[t].clear();
}
if (mm > 0U) {
output.initRow(i, mm);
std::span<T> nt{output[i].data(), output[i].size()};
for (size_t j = 0; j < m; ++j) {
auto const& f0 = tt[j][0];
auto const& f1 = tt[j][1];
if (f1 == mark) { // forwarded
assert(f0.row() == i);
assert(newId[j] == 0);
newId[j] = newId[f0.col()];
} else if (ZDD && f1 == 0) { // forwarded
assert(newId[j].row() < i);
} else {
assert(newId[j].row() == i);
auto k = newId[j].col();
nt[k] = tt[j];
nt[k].set_node_id_label(newId[j]);
}
}
counter++;
}
for (auto& k : rootPtr[i]) {
auto& root = *k;
root = newId[root.col()];
}
}
/**
* Reduces one level.
* @param i level.
*/
void reduce_(int i) {
auto const m = input[i].size();
newIdTable[i].resize(m);
auto jj = 0UL;
{
std::unordered_set<T const*> uniq(m * 2, MyHashDefault<T const*>(),
MyHashDefault<T const*>());
for (auto j = 0UL; j < m; ++j) {
auto* const p0 = input[i].data();
auto& f = input[i][j];
// make f canonical
auto& f0 = f[0];
f0 = newIdTable[f0.row()][f0.col()];
auto deletable = BDD ? f0 : 0;
auto del = BDD || ZDD || (f0 == 0);
for (int b = 1; b < 2; ++b) {
NodeId& ff = f[b];
ff = newIdTable[ff.row()][ff.col()];
if (ff != deletable) {
del = false;
}
}
if (del) { // f is redundant
newIdTable[i][j] = f0;
} else {
auto const* pp = uniq.add(&f);
if (pp == &f) {
newIdTable[i][j] = NodeId(i, jj++, f0.hasEmpty());
} else {
newIdTable[i][j] = newIdTable[i][pp - p0];
}
}
}
}
std::vector<int> const& levels = input.lowerLevels(i);
for (const auto& t : levels) {
newIdTable[t].clear();
}
output.initRow(i, jj);
for (auto j = 0UL; j < m; ++j) {
auto const& ff = newIdTable[i][j];
if (ff.row() == i) {
output[i][ff.col()] = input[i][j];
output[i][ff.col()].child[0] =
&(output.node(output[i][ff.col()][0]));
output[i][ff.col()].child[1] =
&(output.node(output[i][ff.col()][1]));
}
}
input[i].clear();
for (auto k = 0UL; k < rootPtr[i].size(); ++k) {
NodeId& root = *rootPtr[i][k];
root = newIdTable[i][root.col()];
}
}
};
#endif // NODE_BDD_REDUCER_HPP
| 30.881443 | 79 | 0.408363 |
ac6b85c1faf5fc4c0540d0babded351d39970599 | 19,405 | cpp | C++ | src/kits/storage/NodeInfo.cpp | stasinek/BHAPI | 5d9aa61665ae2cc5c6e34415957d49a769325b2b | [
"BSD-3-Clause",
"MIT"
] | 3 | 2018-05-21T15:32:32.000Z | 2019-03-21T13:34:55.000Z | src/kits/storage/NodeInfo.cpp | stasinek/BHAPI | 5d9aa61665ae2cc5c6e34415957d49a769325b2b | [
"BSD-3-Clause",
"MIT"
] | null | null | null | src/kits/storage/NodeInfo.cpp | stasinek/BHAPI | 5d9aa61665ae2cc5c6e34415957d49a769325b2b | [
"BSD-3-Clause",
"MIT"
] | null | null | null | /*
* Copyright 2002-2010 Haiku, Inc. All rights reserved.
* Distributed under the terms of the MIT License.
*
* Authors:
* Ingo Weinhold, bonefish@users.sf.net
* Axel Dörfler, axeld@pinc-software.de
*/
//-----------------------------------------------------------------------------
#include <NodeInfo.h>
//-----------------------------------------------------------------------------
#include <MimeTypes.h>
#include <Bitmap.h>
#include <Entry.h>
#include <IconUtils.h>
#include <Node.h>
#include <Path.h>
#include <Rect.h>
//-----------------------------------------------------------------------------
#include <fs_attr.h>
#include <fs_info.h>
#include <new>
//-----------------------------------------------------------------------------
using namespace std;
using namespace bhapi;
//-----------------------------------------------------------------------------
// attribute names
#define NI_BEOS "BEOS"
static const char* kNITypeAttribute = NI_BEOS ":TYPE";
static const char* kNIPreferredAppAttribute = NI_BEOS ":PREF_APP";
static const char* kNIAppHintAttribute = NI_BEOS ":PPATH";
static const char* kNIMiniIconAttribute = NI_BEOS ":M:STD_ICON";
static const char* kNILargeIconAttribute = NI_BEOS ":L:STD_ICON";
static const char* kNIIconAttribute = NI_BEOS ":ICON";
// #pragma mark - BNodeInfo
//-----------------------------------------------------------------------------
BNodeInfo::BNodeInfo()
:
fNode(NULL),
fCStatus(B_NO_INIT)
{
}
//-----------------------------------------------------------------------------
BNodeInfo::BNodeInfo(BNode* node)
:
fNode(NULL),
fCStatus(B_NO_INIT)
{
fCStatus = SetTo(node);
}
//-----------------------------------------------------------------------------
BNodeInfo::~BNodeInfo()
{
}
//-----------------------------------------------------------------------------
status_t BNodeInfo::SetTo(BNode* node)
{
fNode = NULL;
// check parameter
fCStatus = (node && node->InitCheck() == B_OK ? B_OK : B_BAD_VALUE);
if (fCStatus == B_OK)
fNode = node;
return fCStatus;
}
//-----------------------------------------------------------------------------
status_t BNodeInfo::InitCheck() const
{
return fCStatus;
}
//-----------------------------------------------------------------------------
status_t BNodeInfo::GetType(char* type) const
{
// check parameter and initialization
status_t result = (type ? B_OK : B_BAD_VALUE);
if (result == B_OK && InitCheck() != B_OK)
result = B_NO_INIT;
// get the attribute info and check type and length of the attr contents
attr_info attrInfo;
if (result == B_OK)
result = fNode->GetAttrInfo(kNITypeAttribute, &attrInfo);
if (result == B_OK && attrInfo.type != B_MIME_STRING_TYPE)
result = B_BAD_TYPE;
if (result == B_OK && attrInfo.size > B_MIME_TYPE_LENGTH)
result = B_BAD_DATA;
// read the data
if (result == B_OK) {
ssize_t read = fNode->ReadAttr(kNITypeAttribute, attrInfo.type, 0,
type, attrInfo.size);
if (read < 0)
result = read;
else if (read != attrInfo.size)
result = B_ERROR;
if (result == B_OK) {
// attribute strings doesn't have to be null terminated
type[min_c(attrInfo.size, B_MIME_TYPE_LENGTH - 1)] = '\0';
}
}
return result;
}
//-----------------------------------------------------------------------------
status_t BNodeInfo::SetType(const char* type)
{
// check parameter and initialization
status_t result = B_OK;
if (result == B_OK && type && strlen(type) >= B_MIME_TYPE_LENGTH)
result = B_BAD_VALUE;
if (result == B_OK && InitCheck() != B_OK)
result = B_NO_INIT;
// write/remove the attribute
if (result == B_OK) {
if (type != NULL) {
size_t toWrite = strlen(type) + 1;
ssize_t written = fNode->WriteAttr(kNITypeAttribute,
B_MIME_STRING_TYPE, 0, type, toWrite);
if (written < 0)
result = written;
else if (written != (ssize_t)toWrite)
result = B_ERROR;
} else
result = fNode->RemoveAttr(kNITypeAttribute);
}
return result;
}
//-----------------------------------------------------------------------------
status_t BNodeInfo::GetIcon(BBitmap* icon, icon_size which) const
{
const char* iconAttribute = kNIIconAttribute;
const char* miniIconAttribute = kNIMiniIconAttribute;
const char* largeIconAttribute = kNILargeIconAttribute;
return BIconUtils::GetIcon(fNode, iconAttribute, miniIconAttribute,
largeIconAttribute, which, icon);
}
//-----------------------------------------------------------------------------
status_t BNodeInfo::SetIcon(const BBitmap* icon, icon_size which)
{
status_t result = B_OK;
// set some icon size related variables
const char* attribute = NULL;
BRect bounds;
uint32 attrType = 0;
size_t attrSize = 0;
switch (which) {
case B_MINI_ICON:
attribute = kNIMiniIconAttribute;
bounds.Set(0, 0, 15, 15);
attrType = B_MINI_ICON_TYPE;
attrSize = 16 * 16;
break;
case B_LARGE_ICON:
attribute = kNILargeIconAttribute;
bounds.Set(0, 0, 31, 31);
attrType = B_LARGE_ICON_TYPE;
attrSize = 32 * 32;
break;
default:
result = B_BAD_VALUE;
break;
}
// check parameter and initialization
if (result == B_OK && icon != NULL
&& (icon->InitCheck() != B_OK || icon->Bounds() != bounds)) {
result = B_BAD_VALUE;
}
if (result == B_OK && InitCheck() != B_OK)
result = B_NO_INIT;
// write/remove the attribute
if (result == B_OK) {
if (icon != NULL) {
bool otherColorSpace = (icon->ColorSpace() != B_CMAP8);
ssize_t written = 0;
if (otherColorSpace) {
BBitmap bitmap(bounds, B_BITMAP_NO_SERVER_LINK, B_CMAP8);
result = bitmap.InitCheck();
if (result == B_OK)
result = bitmap.ImportBits(icon);
if (result == B_OK) {
written = fNode->WriteAttr(attribute, attrType, 0,
bitmap.Bits(), attrSize);
}
} else {
written = fNode->WriteAttr(attribute, attrType, 0,
icon->Bits(), attrSize);
}
if (result == B_OK) {
if (written < 0)
result = written;
else if (written != (ssize_t)attrSize)
result = B_ERROR;
}
} else {
// no icon given => remove
result = fNode->RemoveAttr(attribute);
}
}
return result;
}
//-----------------------------------------------------------------------------
status_t BNodeInfo::GetIcon(uint8** data, size_t* size, type_code* type) const
{
// check params
if (data == NULL || size == NULL || type == NULL)
return B_BAD_VALUE;
// check initialization
if (InitCheck() != B_OK)
return B_NO_INIT;
// get the attribute info and check type and size of the attr contents
attr_info attrInfo;
status_t result = fNode->GetAttrInfo(kNIIconAttribute, &attrInfo);
if (result != B_OK)
return result;
// chicken out on unrealisticly large attributes
if (attrInfo.size > 128 * 1024)
return B_ERROR;
// fill the params
*type = attrInfo.type;
*size = attrInfo.size;
*data = new (nothrow) uint8[*size];
if (*data == NULL)
return B_NO_MEMORY;
// featch the data
ssize_t read = fNode->ReadAttr(kNIIconAttribute, *type, 0, *data, *size);
if (read != attrInfo.size) {
delete[] *data;
*data = NULL;
return B_ERROR;
}
return B_OK;
}
//-----------------------------------------------------------------------------
status_t BNodeInfo::SetIcon(const uint8* data, size_t size)
{
// check initialization
if (InitCheck() != B_OK)
return B_NO_INIT;
status_t result = B_OK;
// write/remove the attribute
if (data && size > 0) {
ssize_t written = fNode->WriteAttr(kNIIconAttribute,
B_VECTOR_ICON_TYPE, 0, data, size);
if (written < 0)
result = (status_t)written;
else if (written != (ssize_t)size)
result = B_ERROR;
} else {
// no icon given => remove
result = fNode->RemoveAttr(kNIIconAttribute);
}
return result;
}
//-----------------------------------------------------------------------------
status_t BNodeInfo::GetPreferredApp(char* signature, app_verb verb) const
{
// check parameter and initialization
status_t result = (signature && verb == B_OPEN ? B_OK : B_BAD_VALUE);
if (result == B_OK && InitCheck() != B_OK)
result = B_NO_INIT;
// get the attribute info and check type and length of the attr contents
attr_info attrInfo;
if (result == B_OK)
result = fNode->GetAttrInfo(kNIPreferredAppAttribute, &attrInfo);
if (result == B_OK && attrInfo.type != B_MIME_STRING_TYPE)
result = B_BAD_TYPE;
if (result == B_OK && attrInfo.size > B_MIME_TYPE_LENGTH)
result = B_BAD_DATA;
// read the data
if (result == B_OK) {
ssize_t read = fNode->ReadAttr(kNIPreferredAppAttribute, attrInfo.type,
0, signature, attrInfo.size);
if (read < 0)
result = read;
else if (read != attrInfo.size)
result = B_ERROR;
if (result == B_OK) {
// attribute strings doesn't have to be null terminated
signature[min_c(attrInfo.size, B_MIME_TYPE_LENGTH - 1)] = '\0';
}
}
return result;
}
//-----------------------------------------------------------------------------
status_t BNodeInfo::SetPreferredApp(const char* signature, app_verb verb)
{
// check parameters and initialization
status_t result = (verb == B_OPEN ? B_OK : B_BAD_VALUE);
if (result == B_OK && signature && strlen(signature) >= B_MIME_TYPE_LENGTH)
result = B_BAD_VALUE;
if (result == B_OK && InitCheck() != B_OK)
result = B_NO_INIT;
// write/remove the attribute
if (result == B_OK) {
if (signature) {
size_t toWrite = strlen(signature) + 1;
ssize_t written = fNode->WriteAttr(kNIPreferredAppAttribute,
B_MIME_STRING_TYPE, 0, signature, toWrite);
if (written < 0)
result = written;
else if (written != (ssize_t)toWrite)
result = B_ERROR;
} else
result = fNode->RemoveAttr(kNIPreferredAppAttribute);
}
return result;
}
//-----------------------------------------------------------------------------
status_t BNodeInfo::GetAppHint(entry_ref* ref) const
{
// check parameter and initialization
status_t result = (ref ? B_OK : B_BAD_VALUE);
if (result == B_OK && InitCheck() != B_OK)
result = B_NO_INIT;
// get the attribute info and check type and length of the attr contents
attr_info attrInfo;
if (result == B_OK)
result = fNode->GetAttrInfo(kNIAppHintAttribute, &attrInfo);
// NOTE: The attribute type should be B_STRING_TYPE, but R5 uses
// B_MIME_STRING_TYPE.
if (result == B_OK && attrInfo.type != B_MIME_STRING_TYPE)
result = B_BAD_TYPE;
if (result == B_OK && attrInfo.size > B_PATH_NAME_LENGTH)
result = B_BAD_DATA;
// read the data
if (result == B_OK) {
char path[B_PATH_NAME_LENGTH];
ssize_t read = fNode->ReadAttr(kNIAppHintAttribute, attrInfo.type, 0,
path, attrInfo.size);
if (read < 0)
result = read;
else if (read != attrInfo.size)
result = B_ERROR;
// get the entry_ref for the path
if (result == B_OK) {
// attribute strings doesn't have to be null terminated
path[min_c(attrInfo.size, B_PATH_NAME_LENGTH - 1)] = '\0';
result = get_ref_for_path(path, ref);
}
}
return result;
}
//-----------------------------------------------------------------------------
status_t BNodeInfo::SetAppHint(const entry_ref* ref)
{
// check parameter and initialization
if (InitCheck() != B_OK)
return B_NO_INIT;
status_t result = B_OK;
if (ref != NULL) {
// write/remove the attribute
BPath path;
result = path.SetTo(ref);
if (result == B_OK) {
size_t toWrite = strlen(path.Path()) + 1;
ssize_t written = fNode->WriteAttr(kNIAppHintAttribute,
B_MIME_STRING_TYPE, 0, path.Path(), toWrite);
if (written < 0)
result = written;
else if (written != (ssize_t)toWrite)
result = B_ERROR;
}
} else
result = fNode->RemoveAttr(kNIAppHintAttribute);
return result;
}
//-----------------------------------------------------------------------------
status_t BNodeInfo::GetTrackerIcon(BBitmap* icon, icon_size which) const
{
if (icon == NULL)
return B_BAD_VALUE;
// set some icon size related variables
BRect bounds;
switch (which) {
case B_MINI_ICON:
bounds.Set(0, 0, 15, 15);
break;
case B_LARGE_ICON:
bounds.Set(0, 0, 31, 31);
break;
default:
// result = B_BAD_VALUE;
// NOTE: added to be less strict and support scaled icons
bounds = icon->Bounds();
break;
}
// check parameters and initialization
if (icon->InitCheck() != B_OK || icon->Bounds() != bounds)
return B_BAD_VALUE;
if (InitCheck() != B_OK)
return B_NO_INIT;
// Ask GetIcon() first.
if (GetIcon(icon, which) == B_OK)
return B_OK;
// If not successful, see if the node has a type available at all.
// If no type is available, use one of the standard types.
status_t result = B_OK;
char mimeString[B_MIME_TYPE_LENGTH];
if (GetType(mimeString) != B_OK) {
// Get the icon from a mime type...
BMimeType type;
struct stat stat;
result = fNode->GetStat(&stat);
if (result == B_OK) {
// no type available -- get the icon for the appropriate type
// (file/dir/etc.)
if (S_ISREG(stat.st_mode)) {
// is it an application (executable) or just a regular file?
if ((stat.st_mode & S_IXUSR) != 0)
type.SetTo(B_APP_MIME_TYPE);
else
type.SetTo(B_FILE_MIME_TYPE);
} else if (S_ISDIR(stat.st_mode)) {
// it's either a volume or just a standard directory
fs_info info;
if (fs_stat_dev(stat.st_dev, &info) == 0
&& stat.st_ino == info.root) {
type.SetTo(B_VOLUME_MIME_TYPE);
} else
type.SetTo(B_DIRECTORY_MIME_TYPE);
} else if (S_ISLNK(stat.st_mode))
type.SetTo(B_SYMLINK_MIME_TYPE);
} else {
// GetStat() failed. Return the icon for
// "application/octet-stream" from the MIME database.
type.SetTo(B_FILE_MIME_TYPE);
}
return type.GetIcon(icon, which);
} else {
// We know the mimetype of the node.
bool success = false;
// Get the preferred application and ask the MIME database, if that
// application has a special icon for the node's file type.
char signature[B_MIME_TYPE_LENGTH];
if (GetPreferredApp(signature) == B_OK) {
BMimeType type(signature);
success = type.GetIconForType(mimeString, icon, which) == B_OK;
}
// ToDo: Confirm Tracker asks preferred app icons before asking
// mime icons.
BMimeType nodeType(mimeString);
// Ask the MIME database for the preferred application for the node's
// file type and whether this application has a special icon for the
// type.
if (!success && nodeType.GetPreferredApp(signature) == B_OK) {
BMimeType type(signature);
success = type.GetIconForType(mimeString, icon, which) == B_OK;
}
// Ask the MIME database whether there is an icon for the node's file
// type.
if (!success)
success = nodeType.GetIcon(icon, which) == B_OK;
// Get the super type if still no success.
BMimeType superType;
if (!success && nodeType.GetSupertype(&superType) == B_OK) {
// Ask the MIME database for the preferred application for the
// node's super type and whether this application has a special
// icon for the type.
if (superType.GetPreferredApp(signature) == B_OK) {
BMimeType type(signature);
success = type.GetIconForType(superType.Type(), icon,
which) == B_OK;
}
// Get the icon of the super type itself.
if (!success)
success = superType.GetIcon(icon, which) == B_OK;
}
if (success)
return B_OK;
}
return B_ERROR;
}
//-----------------------------------------------------------------------------
status_t BNodeInfo::GetTrackerIcon(const entry_ref* ref, BBitmap* icon, icon_size which)
{
// check ref param
status_t result = (ref ? B_OK : B_BAD_VALUE);
// init a BNode
BNode node;
if (result == B_OK)
result = node.SetTo(ref);
// init a BNodeInfo
BNodeInfo nodeInfo;
if (result == B_OK)
result = nodeInfo.SetTo(&node);
// let the non-static GetTrackerIcon() do the dirty work
if (result == B_OK)
result = nodeInfo.GetTrackerIcon(icon, which);
return result;
}
//-----------------------------------------------------------------------------
/*! This method is provided for binary compatibility purposes
(for example the program "Guido" depends on it.)
*/
extern "C" status_t GetTrackerIcon__9BNodeInfoP9entry_refP7BBitmap9icon_size(
BNodeInfo* nodeInfo, entry_ref* ref,
BBitmap* bitmap, icon_size iconSize)
{
// NOTE: nodeInfo is ignored - maybe that's wrong!
return BNodeInfo::GetTrackerIcon(ref, bitmap, iconSize);
}
//-----------------------------------------------------------------------------
void BNodeInfo::_ReservedNodeInfo1() {}
void BNodeInfo::_ReservedNodeInfo2() {}
void BNodeInfo::_ReservedNodeInfo3() {}
//-----------------------------------------------------------------------------
/*! Assignment operator is declared private to prevent it from being created
automatically by the compiler.
*/
BNodeInfo& BNodeInfo::operator=(const BNodeInfo &nodeInfo)
{
return *this;
}
//-----------------------------------------------------------------------------
/*! Copy constructor is declared private to prevent it from being created
automatically by the compiler.
*/
BNodeInfo::BNodeInfo(const BNodeInfo &)
{
}
//-----------------------------------------------------------------------------
| 31.916118 | 88 | 0.524916 |
ac6c6bddc8d811b7ae25f6bbb9f8ce0e716e12c5 | 323 | cpp | C++ | maximum-difference-between-increasing-elements/maximum-difference-between-increasing-elements.cpp | sharmishtha2401/leetcode | 0c7389877afb64b3ff277f075ed9c87b24cb587b | [
"MIT"
] | 1 | 2022-02-14T07:57:07.000Z | 2022-02-14T07:57:07.000Z | maximum-difference-between-increasing-elements/maximum-difference-between-increasing-elements.cpp | sharmishtha2401/leetcode | 0c7389877afb64b3ff277f075ed9c87b24cb587b | [
"MIT"
] | null | null | null | maximum-difference-between-increasing-elements/maximum-difference-between-increasing-elements.cpp | sharmishtha2401/leetcode | 0c7389877afb64b3ff277f075ed9c87b24cb587b | [
"MIT"
] | null | null | null | class Solution {
public:
int maximumDifference(vector<int>& nums) {
int diff=0;
int minimum=INT_MAX;
for(int n : nums)
{
if(n<minimum)
minimum=n;
if(n-minimum>diff)
diff=n-minimum;
}
return diff==0?-1:diff;
}
}; | 21.533333 | 46 | 0.458204 |
ac6ecd4799d50f8520d54d5cf0337cbc916110bf | 283 | cpp | C++ | sxaccelerate/src/io/examples/plugins/SxPluginA.cpp | ashtonmv/sphinx_vdw | 5896fee0d92c06e883b72725cb859d732b8b801f | [
"Apache-2.0"
] | 1 | 2020-02-29T03:26:32.000Z | 2020-02-29T03:26:32.000Z | sxaccelerate/src/io/examples/plugins/SxPluginA.cpp | ashtonmv/sphinx_vdw | 5896fee0d92c06e883b72725cb859d732b8b801f | [
"Apache-2.0"
] | null | null | null | sxaccelerate/src/io/examples/plugins/SxPluginA.cpp | ashtonmv/sphinx_vdw | 5896fee0d92c06e883b72725cb859d732b8b801f | [
"Apache-2.0"
] | null | null | null | #include <SxPluginA.h>
#include <stdio.h>
SxPluginA::SxPluginA (SxPluginManager *parent_, void *)
: SxDemoPluginBase (parent_)
{
//empty
}
SxPluginA::~SxPluginA ()
{
printf ("About to destroy plugin A.\n");
}
void SxPluginA::foo ()
{
printf ("This is plugin A.\n");
} | 14.894737 | 55 | 0.650177 |
ac6f4c0bcd49e1cd1ef543efe8fede81bd300cd0 | 2,687 | hpp | C++ | src/api/c/graphics_common.hpp | JuliaComputing/arrayfire | 93427f09ff928f97df29c0e358c3fcf6b478bec6 | [
"BSD-3-Clause"
] | 1 | 2018-06-14T23:49:18.000Z | 2018-06-14T23:49:18.000Z | src/api/c/graphics_common.hpp | JuliaComputing/arrayfire | 93427f09ff928f97df29c0e358c3fcf6b478bec6 | [
"BSD-3-Clause"
] | 1 | 2015-07-02T15:53:02.000Z | 2015-07-02T15:53:02.000Z | src/api/c/graphics_common.hpp | JuliaComputing/arrayfire | 93427f09ff928f97df29c0e358c3fcf6b478bec6 | [
"BSD-3-Clause"
] | 1 | 2018-02-26T17:11:03.000Z | 2018-02-26T17:11:03.000Z | /*******************************************************
* Copyright (c) 2014, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#pragma once
#if defined(WITH_GRAPHICS)
#include <af/graphics.h>
#include <forge.h>
#include <map>
// default to f32(float) type
template<typename T>
fg::FGType getGLType();
// Print for OpenGL errors
// Returns 1 if an OpenGL error occurred, 0 otherwise.
GLenum glErrorSkip(const char *msg, const char* file, int line);
GLenum glErrorCheck(const char *msg, const char* file, int line);
GLenum glForceErrorCheck(const char *msg, const char* file, int line);
#define CheckGL(msg) glErrorCheck (msg, __FILE__, __LINE__)
#define ForceCheckGL(msg) glForceErrorCheck(msg, __FILE__, __LINE__)
#define CheckGLSkip(msg) glErrorSkip (msg, __FILE__, __LINE__)
namespace graphics
{
enum Defaults {
WIDTH = 1280,
HEIGHT= 720
};
static const long long _16BIT = 0x000000000000FFFF;
static const long long _32BIT = 0x00000000FFFFFFFF;
static const long long _48BIT = 0x0000FFFFFFFFFFFF;
typedef std::map<long long, fg::Image*> ImageMap_t;
typedef std::map<long long, fg::Plot*> PlotMap_t;
typedef std::map<long long, fg::Histogram*> HistogramMap_t;
typedef ImageMap_t::iterator ImgMapIter;
typedef PlotMap_t::iterator PltMapIter;
typedef HistogramMap_t::iterator HstMapIter;
/**
* ForgeManager class follows a single pattern. Any user of this class, has
* to call ForgeManager::getInstance inorder to use Forge resources for rendering.
* It manages the windows, and other renderables (given below) that are drawed
* onto chosen window.
* Renderables:
* fg::Image
* fg::Plot
* fg::Histogram
* */
class ForgeManager
{
private:
ImageMap_t mImgMap;
PlotMap_t mPltMap;
HistogramMap_t mHstMap;
public:
static ForgeManager& getInstance();
~ForgeManager();
fg::Font* getFont(const bool dontCreate=false);
fg::Window* getMainWindow(const bool dontCreate=false);
fg::Image* getImage(int w, int h, fg::ColorMode mode, fg::FGType type);
fg::Plot* getPlot(int nPoints, fg::FGType type);
fg::Histogram* getHistogram(int nBins, fg::FGType type);
protected:
ForgeManager() {}
ForgeManager(ForgeManager const&);
void operator=(ForgeManager const&);
void destroyResources();
};
}
#define MAIN_WINDOW graphics::ForgeManager::getInstance().getMainWindow(true)
#endif
| 29.206522 | 82 | 0.670636 |
ac73d7723b986f9918a84f5b983ca76be10bff40 | 409 | cpp | C++ | tests/common/FunexTest.cpp | boldowa/GIEPY | 5aa326b264ef19f71d2e0ab5513b08fac7bca941 | [
"MIT"
] | 8 | 2018-03-15T22:01:35.000Z | 2019-07-13T18:04:41.000Z | tests/common/FunexTest.cpp | telinc1/GIEPY | 9c87ad1070e519637fc4b11b6bef01f998961678 | [
"MIT"
] | 21 | 2018-02-18T06:25:40.000Z | 2018-07-13T17:54:40.000Z | tests/common/FunexTest.cpp | telinc1/GIEPY | 9c87ad1070e519637fc4b11b6bef01f998961678 | [
"MIT"
] | 2 | 2018-07-25T21:04:23.000Z | 2022-01-01T08:40:13.000Z | /**
* FunexTest.cpp
*/
#include <bolib.h>
#include "common/Funex.h"
#include "CppUTest/TestHarness.h"
TEST_GROUP(Funex)
{
void setup()
{
}
void teardown()
{
}
};
TEST(Funex, FunexMatch)
{
}
TEST(Funex, ishex)
{
}
TEST(Funex, atoh)
{
}
TEST(Funex, IsSpace)
{
}
TEST(Funex, CutOffTailSpaces)
{
}
TEST(Funex, SkipUntilSpaces)
{
}
TEST(Funex, SkipSpacesRev)
{
}
TEST(Funex, SkipUntilChar)
{
}
| 7.865385 | 33 | 0.640587 |
ac75db0aa1c9874d955232f8b76b7cb84a7b0012 | 2,022 | hpp | C++ | src/trafficsim/RoadTile.hpp | lutrarutra/trafsim | 05e87b263b48e39d63f699dcaa456f10ca61e9a4 | [
"Apache-2.0"
] | 12 | 2019-12-28T21:45:23.000Z | 2022-03-28T12:40:44.000Z | src/trafficsim/RoadTile.hpp | lutrarutra/trafsim | 05e87b263b48e39d63f699dcaa456f10ca61e9a4 | [
"Apache-2.0"
] | null | null | null | src/trafficsim/RoadTile.hpp | lutrarutra/trafsim | 05e87b263b48e39d63f699dcaa456f10ca61e9a4 | [
"Apache-2.0"
] | 1 | 2021-05-31T10:22:41.000Z | 2021-05-31T10:22:41.000Z | #pragma once
#include <array>
#include <climits> // UINT_MAX
#include <SFML/Graphics.hpp>
#include "Tile.hpp"
#include "TrafficLight.hpp"
namespace ts
{
/*
* Every Road type is derived from this class
* RoadTile is abstract class, and is derived from Tile
*
* Functions inherited from Tile:
* getNode()
* getPos()
* getTileIndex()
*
* Overrided function from Tile:
* getType()
*
* Functions to implement in derived classes:
* getType()
* connect()
* connectableFrom()
* canConnectTo()
*/
enum RoadType
{
StraightRoadType = 0,
RoadTurnType,
IntersectionType,
TrisectionType,
JunctionType,
HomeRoadType,
// Keep as last
RoadTypeCount,
};
class RoadTile : public Tile
{
public:
RoadTile(const Tile &tile);
virtual TileCategory getCategory() const { return TileCategory::RoadCategory; };
virtual RoadType getType() const = 0;
// Direction of the road
// Up: { 0, 1 }, Right { 1, 0 }, Down { 0, -1 }, Left { -1, 0 }
const sf::Vector2f &getDir() const { return dir_; }
bool isFlipped() const { return right_turn_; }
TrafficLight *getLight() { return light_.get(); }
void rotate();
virtual void flip();
void addLight(unsigned int handler_id, float green_time);
unsigned int removeLight();
// Auto rotates road if there is neighbor, only RoadTurn has own implementation
virtual void autoRotate(std::array<Tile *, 4> &neighbors);
// Pure virtual functions
virtual void connect(std::array<Tile *, 4> &neighbors) = 0;
virtual bool connectableFrom(NeighborIndex n_index) const = 0;
virtual bool canConnectTo(NeighborIndex n_index) const = 0;
virtual void draw(sf::RenderTarget &target, sf::RenderStates states) const;
protected:
// Up: { 0, 1 }, Right { 1, 0 }, Down { 0, -1 }, Left { -1, 0 }
sf::Vector2f dir_;
bool right_turn_ = true;
std::unique_ptr<TrafficLight> light_ = nullptr;
void connectTo(Tile *another, NeighborIndex from);
};
} // namespace ts | 24.658537 | 84 | 0.661721 |
ac79048ad80efb870bcb63c70d9ac6b7cd605a77 | 654 | cpp | C++ | src/base/math/trig.cpp | dyuri/vizzu-lib | e5eb4bee98445a85c0a6a61b820ad355851f38c8 | [
"Apache-2.0"
] | 1,159 | 2021-09-23T14:53:16.000Z | 2022-03-30T21:23:41.000Z | src/base/math/trig.cpp | dyuri/vizzu-lib | e5eb4bee98445a85c0a6a61b820ad355851f38c8 | [
"Apache-2.0"
] | 29 | 2021-10-05T13:28:01.000Z | 2022-03-29T16:16:20.000Z | src/base/math/trig.cpp | dyuri/vizzu-lib | e5eb4bee98445a85c0a6a61b820ad355851f38c8 | [
"Apache-2.0"
] | 47 | 2021-09-30T14:04:25.000Z | 2022-02-21T16:01:58.000Z | #include "trig.h"
#include <array>
#include <cmath>
float Math::atan2(float y, float x)
{
const auto ONEQTR_PI = (float)(M_PI / 4.0);
const auto THRQTR_PI = (float)(3.0 * M_PI / 4.0);
float r;
float angle;
float abs_y = fabs(y) + 1e-10f; // kludge to prevent 0/0 condition
if ( x < 0.0f )
{
r = (x + abs_y) / (abs_y - x);
angle = THRQTR_PI;
}
else
{
r = (x - abs_y) / (x + abs_y);
angle = ONEQTR_PI;
}
angle += (0.1963f * r * r - 0.9817f) * r;
if ( y < 0.0f )
return( -angle ); // negate if in quad III or IV
else
return( angle );
}
int Math::rad2quadrant(double angle)
{
return (int)round(angle / (M_PI / 2.0));
}
| 19.235294 | 72 | 0.574924 |
ac79c816f4f43e7b2101141a3716b678589576d4 | 13,006 | cpp | C++ | frameworks/object/modules/basic/dmzObjectModuleGridBasic.cpp | dmzgroup/dmz | fc2d9ddcb04ed71f4106b8d33539529807b3dea6 | [
"MIT"
] | 2 | 2015-11-05T03:03:43.000Z | 2017-05-15T12:55:39.000Z | frameworks/object/modules/basic/dmzObjectModuleGridBasic.cpp | dmzgroup/dmz | fc2d9ddcb04ed71f4106b8d33539529807b3dea6 | [
"MIT"
] | null | null | null | frameworks/object/modules/basic/dmzObjectModuleGridBasic.cpp | dmzgroup/dmz | fc2d9ddcb04ed71f4106b8d33539529807b3dea6 | [
"MIT"
] | null | null | null | #include <dmzObjectAttributeMasks.h>
#include "dmzObjectModuleGridBasic.h"
#include <dmzRuntimeConfigToTypesBase.h>
#include <dmzRuntimeConfigToVector.h>
#include <dmzRuntimePluginFactoryLinkSymbol.h>
#include <dmzRuntimePluginInfo.h>
#include <dmzTypesVolume.h>
/*!
\class dmz::ObjectModuleGridBasic
\ingroup Object
\brief Basic ObjectModuleGrid implementation.
\details This provids a basic implementation of the ObjectModuleGrid.
\code
<dmz>
<dmzObjectModuleGridBasic>
<grid>
<cell x="X cell dimension" y="Y cell dimension"/>
<min x="min x" y="min y" z="min z"/>
<max x="max x" y="max y" z="max z"/>
</grid>
</dmzObjectModuleGridBasic>
</dmz>
\endcode
*/
//! \cond
dmz::ObjectModuleGridBasic::ObjectModuleGridBasic (
const PluginInfo &Info,
Config &local) :
Plugin (Info),
ObjectModuleGrid (Info),
ObjectObserverUtil (Info, local),
_log (Info),
_primaryAxis (VectorComponentX),
_secondaryAxis (VectorComponentZ),
_xCoordMax (100),
_yCoordMax (100),
_maxGrid (100000.0, 0.0, 100000.0),
_xCellSize (0.0),
_yCellSize (0.0),
_grid (0) {
_init (local);
}
dmz::ObjectModuleGridBasic::~ObjectModuleGridBasic () {
if (_grid) { delete []_grid; _grid = 0; }
_objTable.empty ();
_obsTable.empty ();
}
// Plugin Interface
void
dmz::ObjectModuleGridBasic::update_plugin_state (
const PluginStateEnum State,
const UInt32 Level) {
if (State == PluginStateInit) {
}
else if (State == PluginStateStart) {
}
else if (State == PluginStateStop) {
}
else if (State == PluginStateShutdown) {
}
}
void
dmz::ObjectModuleGridBasic::discover_plugin (
const PluginDiscoverEnum Mode,
const Plugin *PluginPtr) {
if (Mode == PluginDiscoverAdd) {
}
else if (Mode == PluginDiscoverRemove) {
}
}
// ObjectModuleGrid Interface
dmz::Boolean
dmz::ObjectModuleGridBasic::register_object_observer_grid (ObjectObserverGrid &observer) {
Boolean result (False);
ObserverStruct *os (_obsTable.lookup (observer.get_object_observer_grid_handle ()));
if (!os) {
os = new ObserverStruct (observer);
if (!_obsTable.store (os->ObsHandle, os)) { delete os; os = 0; }
result = update_object_observer_grid (observer);
}
return result;
}
dmz::Boolean
dmz::ObjectModuleGridBasic::update_object_observer_grid (ObjectObserverGrid &observer) {
Boolean result (False);
ObserverStruct *os (_obsTable.lookup (observer.get_object_observer_grid_handle ()));
if (os) {
const Volume &SearchSpace = os->obs.get_observer_volume ();
Vector origin, min, max;
SearchSpace.get_extents (origin, min, max);
Int32 minX = 0, minY = 0, maxX = 0, maxY = 0;
_map_point_to_coord (min, minX, minY);
_map_point_to_coord (max, maxX, maxY);
Boolean updateExtents = False;
if (
(minX != os->minX) ||
(maxX != os->maxX) ||
(minY != os->minY) ||
(maxY != os->maxY)) { updateExtents = True; }
if (updateExtents && (os->minX >= 0)) {
for (Int32 ix = os->minX; ix <= os->maxX; ix++) {
for (Int32 jy = os->minY; jy <= os->maxY; jy++) {
const Int32 Place = _map_coord (ix, jy);
_grid[Place].obsTable.remove (os->ObsHandle);
HashTableHandleIterator it;
GridStruct *cell = &(_grid[Place]);
ObjectStruct *current = cell->objTable.get_first (it);
while (current) {
if (!SearchSpace.contains_point (current->pos) &&
os->objects.remove (current->Object)) {
observer.update_object_grid_state (
ObjectGridStateExit,
current->Object,
current->Type,
current->pos);
}
current = cell->objTable.get_next (it);
}
}
}
}
os->minX = minX;
os->maxX = maxX;
os->minY = minY;
os->maxY = maxX;
for (Int32 ix = os->minX; ix <= os->maxX; ix++) {
for (Int32 jy = os->minY; jy <= os->maxY; jy++) {
const Int32 Place = _map_coord (ix, jy);
GridStruct *cell = &(_grid[Place]);
if (updateExtents) { cell->obsTable.store (os->ObsHandle, os); }
HashTableHandleIterator it;
ObjectStruct *current = cell->objTable.get_first (it);
while (current) {
_update_observer (SearchSpace, *current, *os);
current = cell->objTable.get_next (it);
}
}
}
result = True;
}
return result;
}
dmz::Boolean
dmz::ObjectModuleGridBasic::release_object_observer_grid (ObjectObserverGrid &observer) {
Boolean result (False);
ObserverStruct *os (_obsTable.remove (observer.get_object_observer_grid_handle ()));
if (os) {
for (Int32 ix = os->minX; ix <= os->maxX; ix++) {
for (Int32 jy = os->minY; jy <= os->maxY; jy++) {
const Int32 Place = _map_coord (ix, jy);
_grid[Place].obsTable.remove (os->ObsHandle);
}
}
delete os; os = 0;
result = True;
}
return result;
}
void
dmz::ObjectModuleGridBasic::find_objects (
const Volume &SearchSpace,
HandleContainer &objects,
const ObjectTypeSet *IncludeTypes,
const ObjectTypeSet *ExcludeTypes) {
Vector origin, min, max;
SearchSpace.get_extents (origin, min, max);
Int32 minX = 0, minY = 0, maxX = 0, maxY = 0;
_map_point_to_coord (min, minX, minY);
_map_point_to_coord (max, maxX, maxY);
ObjectStruct *list (0);
// HandleContainer found;
for (Int32 ix = minX; ix <= maxX; ix++) {
for (Int32 jy = minY; jy <= maxY; jy++) {
HashTableHandleIterator it;
GridStruct *cell = &(_grid[_map_coord (ix, jy)]);
ObjectStruct *current = cell->objTable.get_first (it);
while (current) {
Boolean test (True);
if (IncludeTypes && !IncludeTypes->contains_type (current->Type)) {
test = False;
}
else if (ExcludeTypes && ExcludeTypes->contains_type (current->Type)) {
test = False;
}
if (test && SearchSpace.contains_point (current->pos)) {
#if 0
if (!found.add_handle (current->Object)) {
_log.error << "origin: " << origin << endl
<< "minX: " << minX << endl
<< "minY: " << minY << endl
<< "maxX: " << maxX << endl
<< "maxY: " << maxY << endl;
HandleContainer cc;
for (Int32 xx = minX; xx <= maxX; xx++) {
for (Int32 yy = minY; yy <= maxY; yy++) {
Boolean s = cc.add_handle ((Handle)_map_coord (xx, yy));
_log.error << (s ? "" : "##### NOT UNIQUE ") << xx << " " << yy << " = " << _map_coord (xx, yy) << endl;
}
}
}
#endif // 0
current->distanceSquared = (origin - current->pos).magnitude_squared ();
current->next = 0;
if (!list) { list = current; }
else {
ObjectStruct *p = 0, *c = list;
Boolean done (False);
while (!done) {
if (c->distanceSquared > current->distanceSquared) {
if (!c->next) { c->next = current; done = True; }
else {
p = c; c = c->next;
if (!c) { p->next = current; done = True; }
}
}
else {
if (p) { p->next = current; }
else { list = current; }
current->next = c;
done = True;
}
}
}
}
current = cell->objTable.get_next (it);
}
}
}
while (list) {
if (!objects.add (list->Object)) {
_log.error << "Loop detected in object list for object: " << list->Object
<< endl;
list = 0;
}
else { list = list->next; }
}
}
// Object Observer Interface
void
dmz::ObjectModuleGridBasic::create_object (
const UUID &Identity,
const Handle ObjectHandle,
const ObjectType &Type,
const ObjectLocalityEnum Locality) {
ObjectStruct *os = new ObjectStruct (ObjectHandle, Type);
if (!_objTable.store (ObjectHandle, os)) { delete os; os = 0; }
}
void
dmz::ObjectModuleGridBasic::destroy_object (
const UUID &Identity,
const Handle ObjectHandle) {
ObjectStruct *os (_objTable.remove (ObjectHandle));
if (os) {
_remove_object_from_grid (*os);
if (os->place >= 0) {
HashTableHandleIterator it;
ObserverStruct *obs = _grid[os->place].obsTable.get_first (it);
while (obs) {
obs->objects.remove (ObjectHandle);
obs = _grid[os->place].obsTable.get_next (it);
}
}
delete os; os = 0;
}
}
void
dmz::ObjectModuleGridBasic::update_object_position (
const UUID &Identity,
const Handle ObjectHandle,
const Handle AttributeHandle,
const Vector &Value,
const Vector *PreviousValue) {
ObjectStruct *current (_objTable.lookup (ObjectHandle));
if (current && _grid) {
current->pos = Value;
const Int32 OldPlace = current->place;
const Int32 Place = _map_point (Value);
if (Place != current->place) {
_remove_object_from_grid (*current);
current->place = Place;
_grid[Place].objTable.store (current->Object, current);
}
if ((Place != OldPlace) && (OldPlace >= 0)) {
HashTableHandleIterator it;
GridStruct *cell = &(_grid[OldPlace]);
ObserverStruct *os = cell->obsTable.get_first (it);
HandleContainer tested;
while (os) {
tested.add (os->ObsHandle);
_update_observer (
os->obs.get_observer_volume (),
*current,
*os);
os = cell->obsTable.get_next (it);
}
cell = &(_grid[Place]);
os = cell->obsTable.get_first (it);
while (os) {
if (!tested.contains (os->ObsHandle)) {
_update_observer (
os->obs.get_observer_volume (),
*current,
*os);
}
os = cell->obsTable.get_next (it);
}
}
else {
HashTableHandleIterator it;
GridStruct *cell = &(_grid[Place]);
ObserverStruct *os = cell->obsTable.get_first (it);
while (os) {
_update_observer (
os->obs.get_observer_volume (),
*current,
*os);
os = cell->obsTable.get_next (it);
}
}
}
}
void
dmz::ObjectModuleGridBasic::_remove_object_from_grid (ObjectStruct &obj) {
if (_grid && obj.place >= 0) {
_grid[obj.place].objTable.remove (obj.Object);
}
}
void
dmz::ObjectModuleGridBasic::_update_observer (
const Volume &SearchSpace,
const ObjectStruct &Obj,
ObserverStruct &os) {
const Boolean Contains = SearchSpace.contains_point (Obj.pos);
if (Contains && os.objects.add (Obj.Object)) {
os.obs.update_object_grid_state (
ObjectGridStateEnter,
Obj.Object,
Obj.Type,
Obj.pos);
}
else if (!Contains && os.objects.remove (Obj.Object)) {
os.obs.update_object_grid_state (
ObjectGridStateExit,
Obj.Object,
Obj.Type,
Obj.pos);
}
}
void
dmz::ObjectModuleGridBasic::_init (Config &local) {
_xCoordMax = config_to_int32 ("grid.cell.x", local, _xCoordMax);
_yCoordMax = config_to_int32 ("grid.cell.y", local, _yCoordMax);
_minGrid = config_to_vector ("grid.min", local, _minGrid);
_maxGrid = config_to_vector ("grid.max", local, _maxGrid);
_log.info << "grid: " << _xCoordMax << "x" << _yCoordMax << endl;
_log.info << "extents:" << endl
<< "\t" << _minGrid << endl
<< "\t" << _maxGrid << endl;
Vector vec (_maxGrid - _minGrid);
_xCellSize = vec.get (_primaryAxis) / (Float64)(_xCoordMax);
_yCellSize = vec.get (_secondaryAxis) / (Float64)(_yCoordMax);
_log.info << "cell count: " << _xCoordMax * _yCoordMax << endl;
if (is_zero64 (_xCellSize)) { _xCellSize = 1.0; }
if (is_zero64 (_yCellSize)) { _yCellSize = 1.0; }
_grid = new GridStruct[_xCoordMax * _yCoordMax];
activate_default_object_attribute (
ObjectCreateMask | ObjectDestroyMask | ObjectPositionMask);
}
//! \endcond
extern "C" {
DMZ_PLUGIN_FACTORY_LINK_SYMBOL dmz::Plugin *
create_dmzObjectModuleGridBasic (
const dmz::PluginInfo &Info,
dmz::Config &local,
dmz::Config &global) {
return new dmz::ObjectModuleGridBasic (Info, local);
}
};
| 23.908088 | 104 | 0.559819 |
ac7e355aa09967071872ab16dec7e9db570d1f19 | 10,590 | cpp | C++ | Led_RGB.cpp | GoogleBing/My-library | a41ee2665b0ad0cc92829d9d042364cb704db9e7 | [
"MIT"
] | null | null | null | Led_RGB.cpp | GoogleBing/My-library | a41ee2665b0ad0cc92829d9d042364cb704db9e7 | [
"MIT"
] | null | null | null | Led_RGB.cpp | GoogleBing/My-library | a41ee2665b0ad0cc92829d9d042364cb704db9e7 | [
"MIT"
] | null | null | null | #include "Led_RGB.h"
//--------------------------------------------------------------------------------------------------------------------------------------
led_RGB::led_RGB(){}
//-------------BEGIN SETUP--------------------------------------------------------------------------------------------------------------
void led_RGB::begin(uint8_t RED_PIN,uint8_t GREEN_PIN,uint8_t BLUE_PIN,bool type)
{
_bright=100;
begin(RED_PIN,GREEN_PIN,BLUE_PIN,type,_bright);
}
//--------------------------------------------------------------------------------------------------------------------------------------
void led_RGB::begin(uint8_t RED_PIN,uint8_t GREEN_PIN,uint8_t BLUE_PIN,bool type,uint8_t bright)
{
_redPin=RED_PIN;
_greenPin=GREEN_PIN;
_bluePin=BLUE_PIN;
_bright=bright;
pinMode(_redPin,OUTPUT);
pinMode(_greenPin,OUTPUT);
pinMode(_bluePin,OUTPUT);
}
//-------------EFFECT------------------------------------------------------------------------------------------------------------------
void led_RGB::turnoff()
{
digitalWrite(_redPin,LOW);
digitalWrite(_greenPin,LOW);
digitalWrite(_bluePin,LOW);
}
//-------------DISPLAY-----------------------------------------------------------------------------------------------------------------
void led_RGB::display(uint8_t color[3])
{
display(color,_bright);
}
//--------------------------------------------------------------------------------------------------------------------------------------
void led_RGB::display(uint8_t color[3],uint8_t bright)
{
if (type) for (byte i=0;i<=2;i++) color[i]=~(color[i]*bright/100);
else for(byte i=0;i<=2;i++) color[i]=color[i]*bright/100;
Serial.print(" Xuat ra : ");
batbo(color);
dem++;
analogWrite(_redPin,color[0]);
analogWrite(_greenPin,color[1]);
analogWrite(_bluePin,color[2]);
}
//--------------------------------------------------------------------------------------------------------------------------------------
void led_RGB::display(uint8_t color[3],uint8_t bright,int time)
{
display(color,bright);
delay(time);
}
//--------------------------------------------------------------------------------------------------------------------------------------
void led_RGB::display(uint8_t _RED,uint8_t _GREEN,uint8_t _BLUE)
{
uint8_t color[3];
color[0]=_RED;
color[1]=_GREEN;
color[2]=_BLUE;
display(color,_bright);
}
//--------------------------------------------------------------------------------------------------------------------------------------
void led_RGB::display(uint8_t _RED,uint8_t _GREEN,uint8_t _BLUE,uint8_t bright)
{
uint8_t color[3];
color[0]=_RED;
color[1]=_GREEN;
color[2]=_BLUE;
display(color,bright);
}
//--------------------------------------------------------------------------------------------------------------------------------------
void led_RGB::display(uint8_t _RED,uint8_t _GREEN,uint8_t _BLUE,uint8_t bright,int time)
{
uint8_t color[3];
color[0]=_RED;
color[1]=_GREEN;
color[2]=_BLUE;
display(color,bright);
delay(time);
}
//--------------CHANGE COLOR-----------------------------------------------------------------------------------------------------------
void led_RGB::changeColor(uint8_t _from_color[3], uint8_t _to_color[3],uint8_t level,uint8_t bright,int time)
{
dem=0;
byte i;
for (i=0;i<=2;i++)
{
from_color[i]=_from_color[i];
to_color[i]=_to_color[i];
}
step=level_exact[level];
group_start=classify_group(from_color);
max1_start=max1;
max2_start=max2;
min_start=max3;
group_stop=classify_group(to_color);
max1_stop=max1;
max2_stop=max2;
min_stop=max3;
//Chuyen gia tri ve gan step nhat
for (i=0;i<=2;i++)
{
from_color[i]=round(float(from_color[i])/float(step))*step;
to_color[i]=round(float(to_color[i])/float(step))*step;
}
Serial.println("Lam tron");
batbo(from_color);
batbo(to_color);
Serial.print("group_start=");
Serial.println(group_start);
Serial.print("group_stop=");
Serial.println(group_stop);
//-----------------------------------------------------------------------------------------------------------------------------
delay_step=calc_time(time);
// chuyen ve cac gia tri chia het cho step de code-----------------------------------------------------------------------------
Serial.println("Giai doan chuyen thanh format");
//chuyen RGB Start thanh gia tri theo format (1 gia tri =225 va mot gia tri la 0)
while ( (from_color[max1_start]<255)|(from_color[min_start]>0) )
{
display(from_color,bright,delay_step);
if (from_color[max1_start]<255)
{
from_color[max1_start]+=step;
from_color[max2_start]+=step;
}
if (from_color[min_start]>0) from_color[min_start]-=step;
}
//Giai doan display_per_step-------------------------------------------------------------------------------
repeat=false;
Serial.println("Giai doan display per step");
display_per_step(bright);
if (repeat==true) display_per_step(bright);
//Giai doan cung nhom
from_color[0]=red;
from_color[1]=green;
from_color[2]=blue;
for (i=1;i<=b-1;i++)
{
display(from_color,bright,delay_step);
if (group_stop%2==0) from_color[max2_start]-=step;
else from_color[max2_start]+=step;
}
display(from_color,bright,delay_step);
//Step change to stop---------------------------------------------------------------------------------------
Serial.println("Giai doan change to stop");
while ((from_color[0]!=to_color[0])||(from_color[1]!=to_color[1])||(from_color[2]!=to_color[2]))
{
if (from_color[0]>to_color[0]) from_color[0]-=step;
else if (from_color[0]<to_color[0])from_color[0]+=step;
if (from_color[1]>to_color[1]) from_color[1]-=step;
else if (from_color[1]<to_color[1]) from_color[1]+=step;
if (from_color[2]>to_color[2]) from_color[2]-=step;
else if (from_color[2]< to_color[2]) from_color[2]+=step;
display(from_color,bright,delay_step);
}
Serial.print("Dem la ");
Serial.println(dem);
}
//--------------------------------------------------------------------------------------------------------------------------------------
void led_RGB::display_per_step(uint8_t bright)
{
switch (group_start)
{
case 1:
{
red=255;green=from_color[max2_start];blue=0;
if (group_stop==group_start) {max2_start=1;break;}
else
{
group_start++;
for (green;green<=(255-step);green+=step) display(red,green,blue,bright,delay_step);
from_color[max2_start]=255;
}
}
case 2:
{
red=from_color[max2_start];green=255;blue=0;
if (group_stop==group_start) {max2_start=0;break;}
else
{
group_start++;
for (red;red>=step;red-=step) display(red,green,blue,bright,delay_step);
from_color[max2_start]=0;
}
}
case 3:
{
red=0;green=255;blue=from_color[max2_start];
if (group_stop==group_start) {max2_start=2;break;}
else
{
++group_start;
for (blue;blue<=(255-step);blue+=step) display(red,green,blue,bright,delay_step);
from_color[max2_start]=255;
}
}
case 4:
{
red=0;green=from_color[max2_start];blue=255;
if (group_stop==group_start) {max2_start=1;break;}
else
{
group_start++;
for (green;green>=step;green-=step) display(red,green,blue,bright,delay_step);
from_color[max2_start]=0;
}
}
case 5:
{
red=from_color[max2_start];green=0;blue=255;
if (group_stop==group_start) {max2_start=0;break;}
else
{
group_start++;
for (red;red<=(255-step);red+=step) display(red,green,blue,bright,delay_step);
from_color[max2_start]=255;
}
}
case 6:
{
red=255;blue=from_color[max2_start];green=0;
if (group_stop==group_start) {max2_start=2;break;}
else
{
group_start=1;
for (blue;blue>=step;blue-=step) display(red,green,blue,bright,delay_step);
from_color[max2_start]=0;
repeat=true;
}
}
}
}
//--------------------------------------------------------------------------------------------------------------------------------------
uint8_t led_RGB::classify_group(uint8_t array1[3])
{
max1=0;
max2=1;
max3=2; //max 3 la Min cua mang
if (array1[max1]<array1[max2]) {max1=1; max2=0;}
if (array1[max1]<array1[2]) {max2=max1; max1=2;}
else if (array1[max2]<array1[2]) max2=2;
for (byte i=0;i<=2;i++) if ((max1!=i) && (max2!=i)) max3=i;
byte a=max1*10+max2;
switch (a)
{
case 01:
{
if ((array1[max1]-array1[max2])<=22){return(2);break;}
else {return(1);break;}
}
case 10: {return(2);break;}
case 12:
{
if ((array1[max1]-array1[max2])<=22){return(4);break;}
else {return(3);break;}
}
case 21: {return(4);break;}
case 20: {return(5);break;}
case 02: {return(6);break;}
}
}
//--------------------------------------------------------------------------------------------------------------------------------------
int led_RGB::calc_time(int time)
{
int step_get_format,step_changeto_stop,step_change_group;
step_get_format=max(((255-from_color[max1_start])/step+1),(from_color[min_start]/step+1));
step_changeto_stop=max(((255-to_color[max1_stop])/step),(to_color[min_stop]/step))-1;
if (group_start%2==1) a=(from_color[max1_start]-from_color[max2_start])/step;
else a=(255-from_color[max1_start]+from_color[max2_start])/step;
if (group_stop%2==1) b=(255-to_color[max1_stop]+to_color[max2_stop])/step+1;
else b=(to_color[max1_stop]-to_color[max2_stop])/step+1;
if (group_start<group_stop) step_change_group=(group_stop-group_start-1)*(255/step)+a+b;
else if (group_start>group_stop) step_change_group=((5-group_start+group_stop)*(255/step))+a+b;
else //(group_start==group_stop)
{
if ((a+b)>(255/step)) step_change_group=a+b-255/step ;
else if((a+b)<(255/step)) step_change_group=255/step-a-b+2;
else step_change_group=1; //from_color=to_color @@
}
Serial.print("So buoc la: ");
Serial.println(step_get_format+step_change_group+step_changeto_stop);
return(time/(step_get_format+step_change_group+step_changeto_stop));
}
//--------------------------------------------------------------------------------------------------------------------------------------
void led_RGB::batbo(uint8_t value[3])
{
//Serial.print("Mang la ");
for (uint8_t j=0; j<=2;j++)
{
Serial.print(value[j]);
Serial.print(" ");
}
Serial.println();
// delay(2000);
}
| 34.835526 | 137 | 0.509537 |
ac7ec77ea103427b85401cf12cbcdde234ceabdd | 15,125 | cpp | C++ | Caesar/Hack/Aimbot/Aimbot.cpp | danielkrupinski/caesar | 8d84261f2b9e01c0c0d40220db301b5a0d508b3d | [
"MIT"
] | 27 | 2018-08-31T18:57:24.000Z | 2022-02-13T22:58:05.000Z | Caesar/Hack/Aimbot/Aimbot.cpp | danielkrupinski/caesar | 8d84261f2b9e01c0c0d40220db301b5a0d508b3d | [
"MIT"
] | 6 | 2018-09-19T21:50:38.000Z | 2020-07-28T13:48:47.000Z | Caesar/Hack/Aimbot/Aimbot.cpp | danielkrupinski/caesar | 8d84261f2b9e01c0c0d40220db301b5a0d508b3d | [
"MIT"
] | 9 | 2018-10-07T09:10:20.000Z | 2021-04-30T16:44:43.000Z | #include "../../Required.h"
#include "../../Config.h"
extern Config config;
CAimBot g_AimBot;
void SmoothAimAngles(QAngle MyViewAngles, QAngle AimAngles, QAngle &OutAngles, float Smoothing, bool bSpiral, float SpiralX, float SpiralY)
{
if (Smoothing < 1)
{
OutAngles = AimAngles;
return;
}
OutAngles = AimAngles - MyViewAngles;
OutAngles.Normalize();
Vector vecViewAngleDelta = OutAngles;
if (bSpiral && SpiralX != 0 && SpiralY != 0)
vecViewAngleDelta += Vector(vecViewAngleDelta.y / SpiralX, vecViewAngleDelta.x / SpiralY, 0.0f);
if (!isnan(Smoothing))
vecViewAngleDelta /= Smoothing;
OutAngles = MyViewAngles + vecViewAngleDelta;
OutAngles.Normalize();
}
void CAimBot::Run(struct usercmd_s *cmd)
{
if (config.aimbot.enabled)
{
RageAimbot(cmd);
}
else
{
LegitAimbot(cmd);
Trigger(cmd);
}
}
void CAimBot::Trigger(struct usercmd_s *cmd)
{
if (config.trigger_key > 0 && config.trigger_key < 255)
{
static DWORD dwTemporaryBlockTimer = 0;
if (GetTickCount() - dwTemporaryBlockTimer > 200)
{
if (g_Menu.keys[config.trigger_key]) {
TriggerKeyStatus = !TriggerKeyStatus;
dwTemporaryBlockTimer = GetTickCount();
}
}
if (!TriggerKeyStatus)
return;
}
if (!IsCurWeaponGun() || !CanAttack())
return;
unsigned int m_iWeaponID = g_Local.weapon.m_iWeaponID;
if (!config.legit[m_iWeaponID].trigger)
return;
if (config.trigger_only_zoomed && IsCurWeaponSniper() && g_Local.iFOV == DEFAULT_FOV)
return;
std::deque<unsigned int> Hitboxes;
if (config.legit[m_iWeaponID].trigger_head)
{
Hitboxes.push_back(11);
}
if (config.legit[m_iWeaponID].trigger_chest)
{
Hitboxes.push_back(7);
Hitboxes.push_back(8);
Hitboxes.push_back(9);
Hitboxes.push_back(10);
Hitboxes.push_back(11);
Hitboxes.push_back(12);
Hitboxes.push_back(17);
}
if (config.legit[m_iWeaponID].trigger_stomach)
{
Hitboxes.push_back(0);
}
float flAccuracy = config.legit[m_iWeaponID].trigger_accuracy;
Vector vecSpreadDir, vecForward, vecRight, vecUp, vecRandom;
QAngle QAngles;
g_Engine.GetViewAngles(QAngles);
if (flAccuracy > 0)//Recoil
{
QAngles[0] += g_Local.vPunchangle[0];
QAngles[1] += g_Local.vPunchangle[1];
QAngles[2] = NULL;
}
QAngles.Normalize();
QAngles.AngleVectors(&vecForward, &vecRight, &vecUp);
if (flAccuracy > 1)//Recoil / Spread
{
g_NoSpread.GetSpreadXY(g_Local.weapon.random_seed, 1, vecRandom);
vecSpreadDir = vecForward + (vecRight * vecRandom[0]) + (vecUp * vecRandom[1]);
vecSpreadDir.Normalize();
}
else {//Empty or Recoil
vecSpreadDir = vecForward;
vecSpreadDir.Normalize();
}
for (int id = 1; id <= g_Engine.GetMaxClients(); ++id)
{
if (id == g_Local.iIndex)
continue;
if (!g_Player[id].bAlive)
continue;
if (!g_Player[id].bVisible)
continue;
if (g_Player[id].bFriend)
continue;
if (!config.legit_teammates && g_Player[id].iTeam == g_Local.iTeam)
continue;
for (auto &&hitbox : Hitboxes)
{
if (g_Utils.IsBoxIntersectingRay(g_PlayerExtraInfoList[id].vHitboxMin[hitbox], g_PlayerExtraInfoList[id].vHitboxMax[hitbox], g_Local.vEye, vecSpreadDir))
{
cmd->buttons |= IN_ATTACK;
break;
}
}
}
}
void CAimBot::LegitAimbot(struct usercmd_s *cmd)
{
static DWORD dwBlockAttack = 0;
static float flSpeedSpiralX = 1.3;
static float flSpeedSpiralY = 3.7;
m_flCurrentFOV = 0;
if (!IsCurWeaponGun() || g_Local.weapon.m_iInReload || g_Local.weapon.m_iClip < 1 || g_Local.weapon.m_flNextAttack > 0.0)
return;
unsigned int iWeaponID = g_Local.weapon.m_iWeaponID;
if (!config.legit[iWeaponID].aim)
return;
float flFOV = config.legit[iWeaponID].aim_fov;
if (flFOV <= 0)
return;
float flSpeed = config.legit[iWeaponID].aim_speed_in_attack;
if (config.legit[iWeaponID].aim_speed > 0 && !(cmd->buttons & IN_ATTACK))//Auto aim smooth
flSpeed = config.legit[iWeaponID].aim_speed;
if (flSpeed <= 0)
return;
std::deque<unsigned int> Hitboxes;
if (config.legit[iWeaponID].aim_head)
Hitboxes.push_back(11);
if (config.legit[iWeaponID].aim_chest)
{
Hitboxes.push_back(7);
Hitboxes.push_back(8);
Hitboxes.push_back(9);
Hitboxes.push_back(10);
Hitboxes.push_back(12);
Hitboxes.push_back(17);
}
if (config.legit[iWeaponID].aim_stomach)
Hitboxes.push_back(0);
if (Hitboxes.empty())
return;
float flReactionTime = config.legit[iWeaponID].aim_reaction_time;
if (flReactionTime > 0 && GetTickCount() - dwReactionTime < flReactionTime)
return;
float flSpeedScaleFov = config.legit[iWeaponID].aim_speed_scale_fov;
bool bSpeedSpiral = config.legit[iWeaponID].aim_humanize;
if (!g_Local.vPunchangle.IsZero2D())
bSpeedSpiral = false;
float flRecoilCompensationPitch = 0.02f * config.legit[iWeaponID].aim_recoil_compensation_pitch;
float flRecoilCompensationYaw = 0.02f * config.legit[iWeaponID].aim_recoil_compensation_yaw;
int iRecoilCompensationAfterShotsFired = static_cast<int>(config.legit[iWeaponID].aim_recoil_compensation_after_shots_fired);
if (iRecoilCompensationAfterShotsFired > 0 && g_Local.weapon.m_iShotsFired <= iRecoilCompensationAfterShotsFired)
{
flRecoilCompensationPitch = 0;
flRecoilCompensationYaw = 0;
}
float flBlockAttackAfterKill = config.block_attack_after_kill;
float flAccuracy = config.legit[iWeaponID].aim_accuracy;
float flPSilent = config.legit[iWeaponID].aim_psilent;
Vector vecFOV = {};
{
QAngle QAngles = cmd->viewangles + g_Local.vPunchangle * 2;
QAngles.Normalize();
QAngles.AngleVectors(&vecFOV, NULL, NULL);
vecFOV.Normalize();
}
m_flCurrentFOV = flFOV;
unsigned int iTarget = 0;
unsigned int iHitbox = 0;
float flBestFOV = flFOV;
for (int id = 1; id <= g_Engine.GetMaxClients(); ++id)
{
if (id == g_Local.iIndex)
continue;
if (!g_Player[id].bAlive)
continue;
if (!g_Player[id].bVisible)
continue;
if (g_Player[id].bFriend)
continue;
if (!config.legit_teammates && g_Player[id].iTeam == g_Local.iTeam)
continue;
for (auto &&hitbox : Hitboxes)
{
if (!g_PlayerExtraInfoList[id].bHitboxVisible[hitbox])
continue;
if (config.legit[iWeaponID].aim_head && (config.legit[iWeaponID].aim_chest || config.legit[iWeaponID].aim_stomach) && hitbox == 11 && (!(g_Local.weapon.m_iFlags & FL_ONGROUND) || g_Local.flVelocity > 140 || g_Local.weapon.m_iShotsFired > 5))
continue;
if (config.legit[iWeaponID].aim_chest && config.legit[iWeaponID].aim_stomach && hitbox != 0 && hitbox != 11 && (!(g_Local.weapon.m_iFlags & FL_ONGROUND) || g_Local.weapon.m_iShotsFired > 15))
continue;
float fov = vecFOV.AngleBetween(g_PlayerExtraInfoList[id].vHitbox[hitbox] - g_Local.vEye);
if (fov < flBestFOV)
{
flBestFOV = fov;
iTarget = id;
iHitbox = hitbox;
}
}
}
if (iTarget > 0)
{
bool bAttack = false;
bool bBlock = false;//Block IN_ATTACK?
if (config.legit[iWeaponID].aim_quick_stop)
{
cmd->forwardmove = 0;
cmd->sidemove = 0;
cmd->upmove = 0;
}
QAngle QMyAngles, QAimAngles, QNewAngles, QSmoothAngles;
Vector vAimOrigin = g_PlayerExtraInfoList[iTarget].vHitbox[iHitbox];
g_Engine.GetViewAngles(QMyAngles);
g_Utils.VectorAngles(vAimOrigin - g_Local.vEye, QAimAngles);
if (flPSilent > 0 && flPSilent <= 1 && CanAttack())
{
QAngle QAnglePerfectSilent = QAimAngles;
QAnglePerfectSilent += g_Local.vPunchangle;
QAnglePerfectSilent.Normalize();
g_NoSpread.GetSpreadOffset(g_Local.weapon.random_seed, 1, QAnglePerfectSilent, QAnglePerfectSilent);
Vector vecPsilentFOV;
QAnglePerfectSilent.AngleVectors(&vecPsilentFOV, NULL, NULL);
vecPsilentFOV.Normalize();
float fov = vecPsilentFOV.AngleBetween(g_PlayerExtraInfoList[iTarget].vHitbox[iHitbox] - g_Local.vEye);
if (fov <= flPSilent)
{
cmd->buttons |= IN_ATTACK;
g_Utils.MakeAngle(false, QAnglePerfectSilent, cmd);
g_Utils.bSendpacket(false);
dwBlockAttack = GetTickCount();
return;
}
}
QNewAngles[0] = QAimAngles[0] - g_Local.vPunchangle[0] * flRecoilCompensationPitch;
QNewAngles[1] = QAimAngles[1] - g_Local.vPunchangle[1] * flRecoilCompensationYaw;
QNewAngles[2] = 0;
QNewAngles.Normalize();
/*if (cmd->buttons & IN_ATTACK && CanAttack())
g_NoSpread.GetSpreadOffset(g_Local.weapon.random_seed, 1, QNewAngles, QNewAngles);*/
if (flSpeedScaleFov > 0 && flSpeedScaleFov <= 100 && g_Local.vPunchangle.IsZero() && !isnan(g_PlayerExtraInfoList[iTarget].fHitboxFOV[iHitbox]))
flSpeed = flSpeed - (((g_PlayerExtraInfoList[iTarget].fHitboxFOV[iHitbox] * (flSpeed / m_flCurrentFOV)) * flSpeedScaleFov) / 100);//speed - (((fov * (speed / 180)) * scale) / 100)
SmoothAimAngles(QMyAngles, QNewAngles, QSmoothAngles, flSpeed, bSpeedSpiral, flSpeedSpiralX, flSpeedSpiralY);
if (flAccuracy > 0)
{
bBlock = true;
QAngle QAngleAccuracy = QAimAngles;
Vector vecSpreadDir;
if (flAccuracy == 1)//Aiming
{
QSmoothAngles.AngleVectors(&vecSpreadDir, NULL, NULL);
vecSpreadDir.Normalize();
}
else if (flAccuracy == 2) //Recoil
{
Vector vecRandom, vecForward;
SmoothAimAngles(QMyAngles, QAimAngles, QAngleAccuracy, flSpeed, bSpeedSpiral, flSpeedSpiralX, flSpeedSpiralY);
QAngleAccuracy[0] += g_Local.vPunchangle[0];
QAngleAccuracy[1] += g_Local.vPunchangle[1];
QAngleAccuracy[2] = NULL;
QAngleAccuracy.Normalize();
QAngleAccuracy.AngleVectors(&vecForward, NULL, NULL);
vecSpreadDir = vecForward;
vecSpreadDir.Normalize();
}
else //Recoil / Spread
{
Vector vecRandom, vecRight, vecUp, vecForward;
SmoothAimAngles(QMyAngles, QAimAngles, QAngleAccuracy, flSpeed, bSpeedSpiral, flSpeedSpiralX, flSpeedSpiralY);
QAngleAccuracy[0] += g_Local.vPunchangle[0];
QAngleAccuracy[1] += g_Local.vPunchangle[1];
QAngleAccuracy[2] = NULL;
QAngleAccuracy.Normalize();
QAngleAccuracy.AngleVectors(&vecForward, &vecRight, &vecRight);
g_NoSpread.GetSpreadXY(g_Local.weapon.random_seed, 1, vecRandom);
vecSpreadDir = vecForward + (vecRight * vecRandom[0]) + (vecUp * vecRandom[1]);
vecSpreadDir.Normalize();
}
for (unsigned int x = 0; x < Hitboxes.size(); x++)
{
unsigned int hitbox = Hitboxes[x];
if (g_Utils.IsBoxIntersectingRay(g_PlayerExtraInfoList[iTarget].vHitboxMin[hitbox], g_PlayerExtraInfoList[iTarget].vHitboxMax[hitbox], g_Local.vEye, vecSpreadDir))
{
bBlock = false;
break;
}
}
}
if (cmd->buttons & IN_ATTACK)
bAttack = true;
else if (config.legit[iWeaponID].aim_speed > 0)//Auto aim
{
bAttack = true;
bBlock = true;
}
if (bAttack)
{
QSmoothAngles.Normalize();
g_Utils.MakeAngle(false, QSmoothAngles, cmd);
g_Engine.SetViewAngles(QSmoothAngles);
if (!bBlock)
cmd->buttons |= IN_ATTACK;
else if (cmd->buttons & IN_ATTACK)
cmd->buttons &= ~IN_ATTACK;
if (!g_Local.vPunchangle.IsZero2D())
dwBlockAttack = GetTickCount();
}
}
else if (flBlockAttackAfterKill > 0 && GetTickCount() - dwBlockAttack < flBlockAttackAfterKill)
{
cmd->buttons &= ~IN_ATTACK;
}
}
void CAimBot::RageAimbot(struct usercmd_s *cmd)
{
if (!config.aimbot.enabled && !IsCurWeaponGun() || !CanAttack())
return;
std::deque<unsigned int> Hitboxes;
if (config.aimbot.hitbox == 1)//"Head", "Neck", "Chest", "Stomach"
{
Hitboxes.push_back(11);
}
else if (config.aimbot.hitbox == 2)
{
Hitboxes.push_back(10);
}
else if (config.aimbot.hitbox == 3)
{
Hitboxes.push_back(7);
}
else if (config.aimbot.hitbox == 4)
{
Hitboxes.push_back(0);
}
else if (config.aimbot.hitbox == 5)//All
{
for (unsigned int j = 0; j <= 11; j++)
Hitboxes.push_front(j);
for (int k = 12; k < g_Local.iMaxHitboxes; k++)
Hitboxes.push_back(k);
}
else if (config.aimbot.hitbox == 6)//Vital
{
for (unsigned int j = 0; j <= 11; j++)
Hitboxes.push_front(j);
}
if (Hitboxes.empty())
return;
unsigned int m_iTarget = 0;
int m_iHitbox = -1;
int m_iPoint = -1;
float m_flBestFOV = 180;
float m_flBestDist = 8192;
for (int id = 1; id <= g_Engine.GetMaxClients(); ++id)
{
if (id == g_Local.iIndex)
continue;
if (!g_Player[id].bAlive)
continue;
if (g_Player[id].bFriend)
continue;
if (!g_Player[id].bVisible)
continue;
if (!config.aimbot.teammates && g_Player[id].iTeam == g_Local.iTeam)
continue;
if (config.aimbot.delayShot)
{
cl_entity_s *ent = g_Engine.GetEntityByIndex(id);
if (ent && ent->curstate.frame != 0)
continue;
}
for (auto &&hitbox : Hitboxes)
{
if (g_PlayerExtraInfoList[id].bHitboxVisible[hitbox])
{
m_iHitbox = hitbox;
break;
}
}
if (m_iHitbox == -1)
{
for (auto &&hitbox : Hitboxes)
{
if (config.aimbot.multiPoint > 0)
{
if (config.aimbot.multiPoint == 1 && hitbox != 11)
continue;
if (config.aimbot.multiPoint == 2 && hitbox > 11)
continue;
for (unsigned int point = 0; point <= 8; ++point)
{
if (g_PlayerExtraInfoList[id].bHitboxPointsVisible[hitbox][point] && !g_PlayerExtraInfoList[id].bHitboxVisible[hitbox])
{
m_iPoint = point;
m_iHitbox = hitbox;
break;
}
}
}
}
}
if (m_iHitbox < 0 || m_iHitbox > g_Local.iMaxHitboxes)
continue;
if (g_Player[id].bPriority)
{
m_iTarget = id;
break;
}
//"Field of view", "Distance", "Cycle"
if (config.aimbot.targetSelection == 1)
{
if (g_PlayerExtraInfoList[id].fHitboxFOV[m_iHitbox] < m_flBestFOV)
{
m_flBestFOV = g_PlayerExtraInfoList[id].fHitboxFOV[m_iHitbox];
m_iTarget = id;
}
}
else if (config.aimbot.targetSelection == 2)
{
if (g_Player[id].flDist < m_flBestDist)
{
m_flBestDist = g_Player[id].flDist;
m_iTarget = id;
}
}
else if (config.aimbot.targetSelection == 3)
{
if (g_PlayerExtraInfoList[id].fHitboxFOV[m_iHitbox] < m_flBestFOV)
{
if (g_Player[id].flDist < m_flBestDist)
{
m_flBestFOV = g_PlayerExtraInfoList[id].fHitboxFOV[m_iHitbox];
m_flBestDist = g_Player[id].flDist;
m_iTarget = id;
}
}
}
}
if (m_iTarget > 0)
{
if (config.quick_stop_duck)
{
cmd->forwardmove = 0;
cmd->sidemove = 0;
cmd->upmove = 0;
cmd->buttons |= IN_DUCK;
}
else if (config.quick_stop)
{
cmd->forwardmove = 0;
cmd->sidemove = 0;
cmd->upmove = 0;
}
if (config.aimbot.autoscope && IsCurWeaponSniper() && g_Local.iFOV == DEFAULT_FOV)
{
cmd->buttons |= IN_ATTACK2;
}
else if (CanAttack())
{
QAngle QMyAngles, QAimAngles, QSmoothAngles;
Vector vAimOrigin;
if(m_iPoint >= 0 && m_iPoint < 8)
vAimOrigin = g_PlayerExtraInfoList[m_iTarget].vHitboxPoints[m_iHitbox][m_iPoint];
else
vAimOrigin = g_PlayerExtraInfoList[m_iTarget].vHitbox[m_iHitbox];
g_Engine.GetViewAngles(QMyAngles);
g_Utils.VectorAngles(vAimOrigin - g_Local.vEye, QAimAngles);
if (config.aimbot.perfectSilent)
{
g_Utils.MakeAngle(false, QAimAngles, cmd);
g_Utils.bSendpacket(false);
}
else {
g_Utils.MakeAngle(false, QAimAngles, cmd);
if (!config.aimbot.silent)
g_Engine.SetViewAngles(QAimAngles);
}
cmd->buttons |= IN_ATTACK;
}
else {
cmd->buttons &= ~IN_ATTACK;
}
}
} | 23.341049 | 244 | 0.686479 |
ac7f583280c773e6d73aa692d441c3b074a3beed | 2,230 | cpp | C++ | src/mainwindow.cpp | ashleyshu/sway | 3c89ed47773267914ba9840bc4c85714403ca137 | [
"MIT"
] | null | null | null | src/mainwindow.cpp | ashleyshu/sway | 3c89ed47773267914ba9840bc4c85714403ca137 | [
"MIT"
] | null | null | null | src/mainwindow.cpp | ashleyshu/sway | 3c89ed47773267914ba9840bc4c85714403ca137 | [
"MIT"
] | null | null | null | #include <QDebug>
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "tasklistdialog.h"
#include "conslistdialog.h"
#include "taskinputdialog.h"
#include "consinputdialog.h"
#include "schedulecreator.h"
#include "googlecal.h"
//! Main Window Class
/*!
\Author: Group 33
Description: Main window from where user can select options and use program.
*/
//! Construction
/*!
\Authors: Group 33
Description: Constructor
@param controller the input controller
@param parent the parent of this widget
*/
MainWindow::MainWindow(InputController *controller, QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow),
m_controller (controller)
{
Q_ASSERT(controller != nullptr);
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
//! Opens tasks view
void MainWindow::on_bTaskView_clicked()
{
TaskListDialog tasklistdialog(m_controller);
tasklistdialog.setModal(true);
tasklistdialog.exec();
}
//! Opens constraintss view
void MainWindow::on_bConsView_clicked()
{
ConsListDialog conslistdialog(m_controller);
conslistdialog.setModal(true);
conslistdialog.exec();
}
//! Opens task input screen
void MainWindow::on_bTaskAdd_clicked()
{
TaskInputDialog taskinputdialog(m_controller);
taskinputdialog.setModal(true);
taskinputdialog.exec();
}
//! Opens constraint input view
void MainWindow::on_bConsAdd_clicked()
{
ConsInputDialog consinputdialog(m_controller);
consinputdialog.setModal(true);
consinputdialog.exec();
}
//! Generatives schedule and saves as CSV
void MainWindow::on_bSchedGen_clicked()
{
ScheduleCreator scheduleCreator(m_controller);
scheduleCreator.createSchedule();
}
//! Opens google calendar dialog
void MainWindow::on_bGoogleCal_clicked()
{
GoogleCal googleCal;
googleCal.setModal(true);
googleCal.exec();
}
//! Save task and constraint inputs
void MainWindow::on_bSchedSave_clicked() {
m_controller->saveInputs();
}
//! Load task and constraint inputs
void MainWindow::on_bSchedLoad_clicked() {
m_controller->loadInputs();
}
| 20.272727 | 81 | 0.690583 |
ac80c716b8c45340677a672b95e9b7cdead5efcb | 3,025 | cpp | C++ | modcode/Client.cpp | eezstreet/Rapture | 1022f1013d7a7a3a84ea3ba56518420daf4733fc | [
"ISC"
] | 2 | 2017-10-25T03:22:34.000Z | 2020-04-02T16:33:40.000Z | modcode/Client.cpp | eezstreet/Rapture | 1022f1013d7a7a3a84ea3ba56518420daf4733fc | [
"ISC"
] | 12 | 2016-07-03T21:08:25.000Z | 2016-07-30T06:17:26.000Z | modcode/Client.cpp | eezstreet/Rapture | 1022f1013d7a7a3a84ea3ba56518420daf4733fc | [
"ISC"
] | 3 | 2016-03-02T06:56:42.000Z | 2018-04-13T14:37:06.000Z | #include "Client.h"
#include "ClientDisplay.h"
#include "ClientFont.h"
namespace Client {
static bool bInitialized = false;
/*
Packet serialization/deserialization functions.
The serialization function is called when a packet is next in the queue to be written.
The deserialization function is conversely called when a packet is received.
The deserialization function is expected to call the appropriate handler for the data as well.
If a serialization function is null, the engine will throw a warning upon queueing it for send from modcode.
If a deserialization function is null, the engine will throw a warning upon receipt.
*/
packetSerializationFunc clientFuncs[PACKET_MAX] = {
nullptr, // PACKET_PING
nullptr, // PACKET_PONG
nullptr, // PACKET_DROP
nullptr, // PACKET_CLIENTATTEMPT
nullptr, // PACKET_CLIENTACCEPT
nullptr, // PACKET_CLIENTDENIED
nullptr, // PACKET_INFOREQUEST
nullptr, // PACKET_INFOREQUESTED
nullptr, // PACKET_SENDCHAT // FIXME
nullptr, // PACKET_RECVCHAT // FIXME
};
packetDeserializationFunc dclientFuncs[PACKET_MAX] = {
nullptr, // PACKET_PING
nullptr, // PACKET_PONG
nullptr, // PACKET_DROP
nullptr, // PACKET_CLIENTATTEMPT
nullptr, // PACKET_CLIENTACCEPT
nullptr, // PACKET_CLIENTDENIED
nullptr, // PACKET_INFOREQUEST
nullptr, // PACKET_INFOREQUESTED
nullptr, // PACKET_SENDCHAT // FIXME
nullptr, // PACKET_RECVCHAT // FIXME
};
/* Initialization code */
void Initialize() {
if (bInitialized) {
return;
}
ClientFont::Initialize();
ClientDisplay::Initialize();
trap->printf(PRIORITY_MESSAGE, "Waiting for additional elements to complete...\n");
ClientFont::FinishInitialization();
trap->printf(PRIORITY_MESSAGE, "Client initialized successfully.\n");
bInitialized = true;
}
/* Shutdown code */
void Shutdown() {
if (!bInitialized) {
return;
}
ClientDisplay::Shutdown();
bInitialized = false;
}
/* Code that gets run every frame */
void Frame() {
ClientDisplay::DrawDisplay();
}
/*
Packet serialization function.
This calls the appropriate function in clientFuncs (or returns false if it doesn't exist)
Called from the engine when a send packet attempt has been dequeued.
The data isn't sent across the wire in clientFuncs, it's translated to packetData.
*/
bool SerializePacket(Packet& packet, int clientNum, void* extraData) {
if (clientFuncs[packet.packetHead.type]) {
clientFuncs[packet.packetHead.type](packet, clientNum, extraData);
return true;
}
return false;
}
/*
Packet deserialization function.
This calls the appropriate function in dclientFuncs (or returns false if it doesn't exist)
Called from the engine when we have received a packet.
The data is both deserialized and used in dclientFuncs
*/
bool DeserializePacket(Packet& packet, int clientNum) {
if (dclientFuncs[packet.packetHead.type]) {
dclientFuncs[packet.packetHead.type](packet, clientNum);
return true;
}
return false;
}
} | 30.867347 | 110 | 0.729587 |
ac8209cc98e70c57ba64947689f569a1c3d585e4 | 1,195 | hpp | C++ | experimental/Pomdog.Experimental/Gameplay2D/Animator.hpp | bis83/pomdog | 133a9262958d539ae6d93664e6cb2207b5b6c7ff | [
"MIT"
] | null | null | null | experimental/Pomdog.Experimental/Gameplay2D/Animator.hpp | bis83/pomdog | 133a9262958d539ae6d93664e6cb2207b5b6c7ff | [
"MIT"
] | null | null | null | experimental/Pomdog.Experimental/Gameplay2D/Animator.hpp | bis83/pomdog | 133a9262958d539ae6d93664e6cb2207b5b6c7ff | [
"MIT"
] | null | null | null | // Copyright (c) 2013-2015 mogemimi.
// Distributed under the MIT license. See LICENSE.md file for details.
#ifndef POMDOG_ANIMATOR_0CFC0E37_HPP
#define POMDOG_ANIMATOR_0CFC0E37_HPP
#include "Pomdog.Experimental/Gameplay/Component.hpp"
#include "Pomdog/Application/Duration.hpp"
#include <string>
#include <memory>
namespace Pomdog {
class Skeleton;
class SkeletonTransform;
class AnimationGraph;
class Animator: public Component<Animator> {
public:
Animator(std::shared_ptr<Skeleton> const& skeleton,
std::shared_ptr<SkeletonTransform> const& skeletonTransform,
std::shared_ptr<AnimationGraph> const& animationGraph);
~Animator();
void Update(Duration const& frameDuration);
void CrossFade(std::string const& state, Duration const& transitionDuration);
void Play(std::string const& state);
float PlaybackRate() const;
void PlaybackRate(float playbackRate);
void SetFloat(std::string const& name, float value);
void SetBool(std::string const& name, bool value);
std::string GetCurrentStateName() const;
private:
class Impl;
std::unique_ptr<Impl> impl;
};
} // namespace Pomdog
#endif // POMDOG_ANIMATOR_0CFC0E37_HPP
| 24.895833 | 81 | 0.745607 |
ac841a98df20217c9d4e857dfdf68828aaff42cf | 6,100 | hpp | C++ | pomdog/pomdog.hpp | mogemimi/pomdog | 6dc6244d018f70d42e61c6118535cf94a9ee0618 | [
"MIT"
] | 163 | 2015-03-16T08:42:32.000Z | 2022-01-11T21:40:22.000Z | pomdog/pomdog.hpp | mogemimi/pomdog | 6dc6244d018f70d42e61c6118535cf94a9ee0618 | [
"MIT"
] | 17 | 2015-04-12T20:57:50.000Z | 2020-10-10T10:51:45.000Z | pomdog/pomdog.hpp | mogemimi/pomdog | 6dc6244d018f70d42e61c6118535cf94a9ee0618 | [
"MIT"
] | 21 | 2015-04-12T20:45:11.000Z | 2022-01-14T20:50:16.000Z | // Copyright mogemimi. Distributed under the MIT license.
#pragma once
/// Root namespace for the Pomdog game engine.
namespace pomdog {
} // namespace pomdog
#include "pomdog/application/game.hpp"
#include "pomdog/application/game_host.hpp"
#include "pomdog/application/game_window.hpp"
#include "pomdog/application/mouse_cursor.hpp"
#include "pomdog/chrono/duration.hpp"
#include "pomdog/chrono/game_clock.hpp"
#include "pomdog/chrono/time_point.hpp"
#include "pomdog/chrono/timer.hpp"
#include "pomdog/audio/audio_channels.hpp"
#include "pomdog/audio/audio_clip.hpp"
#include "pomdog/audio/audio_emitter.hpp"
#include "pomdog/audio/audio_engine.hpp"
#include "pomdog/audio/audio_listener.hpp"
#include "pomdog/audio/sound_effect.hpp"
#include "pomdog/audio/sound_state.hpp"
#include "pomdog/content/asset_builders/pipeline_state_builder.hpp"
#include "pomdog/content/asset_builders/shader_builder.hpp"
#include "pomdog/content/asset_manager.hpp"
#include "pomdog/filesystem/file_system.hpp"
#include "pomdog/math/bounding_box.hpp"
#include "pomdog/math/bounding_box2d.hpp"
#include "pomdog/math/bounding_circle.hpp"
#include "pomdog/math/bounding_frustum.hpp"
#include "pomdog/math/bounding_sphere.hpp"
#include "pomdog/math/color.hpp"
#include "pomdog/math/containment_type.hpp"
#include "pomdog/math/degree.hpp"
#include "pomdog/math/math.hpp"
#include "pomdog/math/matrix2x2.hpp"
#include "pomdog/math/matrix3x2.hpp"
#include "pomdog/math/matrix3x3.hpp"
#include "pomdog/math/matrix4x4.hpp"
#include "pomdog/math/plane.hpp"
#include "pomdog/math/plane_intersection_type.hpp"
#include "pomdog/math/point2d.hpp"
#include "pomdog/math/point3d.hpp"
#include "pomdog/math/quaternion.hpp"
#include "pomdog/math/radian.hpp"
#include "pomdog/math/ray.hpp"
#include "pomdog/math/rectangle.hpp"
#include "pomdog/math/vector2.hpp"
#include "pomdog/math/vector3.hpp"
#include "pomdog/math/vector4.hpp"
#include "pomdog/network/array_view.hpp"
#include "pomdog/network/http_client.hpp"
#include "pomdog/network/http_method.hpp"
#include "pomdog/network/http_request.hpp"
#include "pomdog/network/http_response.hpp"
#include "pomdog/network/io_service.hpp"
#include "pomdog/network/tcp_stream.hpp"
#include "pomdog/network/tls_stream.hpp"
#include "pomdog/network/udp_stream.hpp"
#include "pomdog/logging/log.hpp"
#include "pomdog/logging/log_channel.hpp"
#include "pomdog/logging/log_entry.hpp"
#include "pomdog/logging/log_level.hpp"
#include "pomdog/graphics/blend_description.hpp"
#include "pomdog/graphics/blend_factor.hpp"
#include "pomdog/graphics/blend_operation.hpp"
#include "pomdog/graphics/buffer_usage.hpp"
#include "pomdog/graphics/comparison_function.hpp"
#include "pomdog/graphics/constant_buffer.hpp"
#include "pomdog/graphics/cull_mode.hpp"
#include "pomdog/graphics/depth_stencil_buffer.hpp"
#include "pomdog/graphics/depth_stencil_description.hpp"
#include "pomdog/graphics/depth_stencil_operation.hpp"
#include "pomdog/graphics/effect_annotation.hpp"
#include "pomdog/graphics/effect_constant_description.hpp"
#include "pomdog/graphics/effect_reflection.hpp"
#include "pomdog/graphics/effect_variable.hpp"
#include "pomdog/graphics/effect_variable_class.hpp"
#include "pomdog/graphics/effect_variable_type.hpp"
#include "pomdog/graphics/fill_mode.hpp"
#include "pomdog/graphics/graphics_command_list.hpp"
#include "pomdog/graphics/graphics_command_queue.hpp"
#include "pomdog/graphics/graphics_device.hpp"
#include "pomdog/graphics/index_buffer.hpp"
#include "pomdog/graphics/index_element_size.hpp"
#include "pomdog/graphics/input_classification.hpp"
#include "pomdog/graphics/input_element.hpp"
#include "pomdog/graphics/input_element_format.hpp"
#include "pomdog/graphics/input_layout_description.hpp"
#include "pomdog/graphics/input_layout_helper.hpp"
#include "pomdog/graphics/pipeline_state.hpp"
#include "pomdog/graphics/pipeline_state_description.hpp"
#include "pomdog/graphics/presentation_parameters.hpp"
#include "pomdog/graphics/primitive_topology.hpp"
#include "pomdog/graphics/rasterizer_description.hpp"
#include "pomdog/graphics/render_pass.hpp"
#include "pomdog/graphics/render_target2d.hpp"
#include "pomdog/graphics/render_target_blend_description.hpp"
#include "pomdog/graphics/sampler_description.hpp"
#include "pomdog/graphics/sampler_state.hpp"
#include "pomdog/graphics/shader.hpp"
#include "pomdog/graphics/shader_language.hpp"
#include "pomdog/graphics/shader_pipeline_stage.hpp"
#include "pomdog/graphics/stencil_operation.hpp"
#include "pomdog/graphics/surface_format.hpp"
#include "pomdog/graphics/texture.hpp"
#include "pomdog/graphics/texture2d.hpp"
#include "pomdog/graphics/texture_address_mode.hpp"
#include "pomdog/graphics/texture_filter.hpp"
#include "pomdog/graphics/vertex_buffer.hpp"
#include "pomdog/graphics/viewport.hpp"
#include "pomdog/input/button_state.hpp"
#include "pomdog/input/gamepad.hpp"
#include "pomdog/input/gamepad_buttons.hpp"
#include "pomdog/input/gamepad_capabilities.hpp"
#include "pomdog/input/gamepad_dpad.hpp"
#include "pomdog/input/gamepad_state.hpp"
#include "pomdog/input/gamepad_thumbsticks.hpp"
#include "pomdog/input/gamepad_uuid.hpp"
#include "pomdog/input/key_state.hpp"
#include "pomdog/input/keyboard.hpp"
#include "pomdog/input/keyboard_state.hpp"
#include "pomdog/input/keys.hpp"
#include "pomdog/input/mouse.hpp"
#include "pomdog/input/mouse_buttons.hpp"
#include "pomdog/input/mouse_state.hpp"
#include "pomdog/input/player_index.hpp"
#include "pomdog/input/touch_location.hpp"
#include "pomdog/input/touch_location_state.hpp"
#include "pomdog/signals/connection.hpp"
#include "pomdog/signals/connection_list.hpp"
#include "pomdog/signals/delegate.hpp"
#include "pomdog/signals/event_queue.hpp"
#include "pomdog/signals/scoped_connection.hpp"
#include "pomdog/signals/signal.hpp"
#include "pomdog/signals/signal_helpers.hpp"
#include "pomdog/utility/assert.hpp"
#include "pomdog/utility/errors.hpp"
#include "pomdog/utility/path_helper.hpp"
#include "pomdog/utility/string_helper.hpp"
#include "pomdog/basic/export.hpp"
#include "pomdog/basic/platform.hpp"
#include "pomdog/basic/version.hpp"
| 38.853503 | 67 | 0.812623 |
ac848d83a6dede8aa29e7e0e403c35e2b9d7b5ce | 879 | hpp | C++ | include/utils/platform.hpp | afreakana/cfs-spmv | cdd139c5d80b774708806298868a456ad8df1669 | [
"BSD-3-Clause"
] | 1 | 2021-02-16T12:19:25.000Z | 2021-02-16T12:19:25.000Z | include/utils/platform.hpp | afreakana/cfs-spmv | cdd139c5d80b774708806298868a456ad8df1669 | [
"BSD-3-Clause"
] | null | null | null | include/utils/platform.hpp | afreakana/cfs-spmv | cdd139c5d80b774708806298868a456ad8df1669 | [
"BSD-3-Clause"
] | 1 | 2020-04-30T12:52:48.000Z | 2020-04-30T12:52:48.000Z | #ifndef PLATFORM_HPP
#define PLATFORM_HPP
#include <cmath>
#include "cfs_config.hpp"
#ifdef _INTEL_COMPILER
#define PRAGMA_IVDEP _Pragma("ivdep")
#else
#define PRAGMA_IVDEP _Pragma("GCC ivdep")
//#define PRAGMA_IVDEP
#endif
namespace cfs {
namespace util {
using namespace std;
enum class Platform { cpu };
enum class Kernel { SpDMV };
enum class Tuning { None, Aggressive };
enum class Format { none, csr, sss, hyb };
inline int iceildiv(const int a, const int b) { return (a + b - 1) / b; }
inline bool isEqual(float x, float y) {
const float epsilon = 1e-4;
return abs(x - y) <= epsilon * abs(x);
// see Knuth section 4.2.2 pages 217-218
}
inline bool isEqual(double x, double y) {
const double epsilon = 1e-8;
return abs(x - y) <= epsilon * abs(x);
// see Knuth section 4.2.2 pages 217-218
}
} // end of namespace util
} // end of namespace cfs
#endif
| 20.44186 | 73 | 0.688282 |
ac8574ba1f8f6017a639557901393ab589ca2519 | 918 | cpp | C++ | LuoguCodes/CF980B.cpp | Anguei/OI-Codes | 0ef271e9af0619d4c236e314cd6d8708d356536a | [
"MIT"
] | null | null | null | LuoguCodes/CF980B.cpp | Anguei/OI-Codes | 0ef271e9af0619d4c236e314cd6d8708d356536a | [
"MIT"
] | null | null | null | LuoguCodes/CF980B.cpp | Anguei/OI-Codes | 0ef271e9af0619d4c236e314cd6d8708d356536a | [
"MIT"
] | null | null | null | #include <cstdio>
#include <string>
#include <iostream>
#include <algorithm>
const int kMaxN = 99;
char map[4 + 5][kMaxN + 5];
int main()
{
for (int i = 0; i < 9; ++i)
for (int j = 0; j < 99 + 5; ++j)
map[i][j] = ';.';;
int n, k;
std::cin >> n >> k;
if (k == 0)
{
std::cout << "YES" << std::endl;
for (int i = 1; i <= 4; ++i)
{
for (int j = 1; j <= n; ++j)
std::cout << ".";
std::cout << std::endl;
}
return 0;
}
if (k % 2)
{
map[2][n / 2 + 1] = ';#';;
--k;
}
//int pos = 2;
for (int i = 2; i <= 4 - 1; ++i)
{
for (int j = 2; j < n / 2 + 1; ++j)
{
if (k <= 0)
goto output;
map[i][j] = map[i][n - j + 1] = ';#';;
k -= 2;
}
}
if (k == 2)
map[2][n / 2 + 1] = map[3][n / 2 + 1] = ';#';;
output:
std::cout << "YES" << std::endl;
for (int i = 1; i <= 4; ++i)
{
for (int j = 1; j <= n; ++j)
std::cout << map[i][j];
std::cout << std::endl;
}
} | 17 | 48 | 0.400871 |
ac8631435d960d1bee2d98002a8909bba8a22693 | 13,119 | cc | C++ | Digit_Example/opt_two_step/gen/opt/J_u_rightToeHeight_digit.cc | prem-chand/Cassie_CFROST | da4bd51442f86e852cbb630cc91c9a380a10b66d | [
"BSD-3-Clause"
] | null | null | null | Digit_Example/opt_two_step/gen/opt/J_u_rightToeHeight_digit.cc | prem-chand/Cassie_CFROST | da4bd51442f86e852cbb630cc91c9a380a10b66d | [
"BSD-3-Clause"
] | null | null | null | Digit_Example/opt_two_step/gen/opt/J_u_rightToeHeight_digit.cc | prem-chand/Cassie_CFROST | da4bd51442f86e852cbb630cc91c9a380a10b66d | [
"BSD-3-Clause"
] | null | null | null | /*
* Automatically Generated from Mathematica.
* Fri 5 Nov 2021 16:30:17 GMT-04:00
*/
#ifdef MATLAB_MEX_FILE
#include <stdexcept>
#include <cmath>
#include<math.h>
/**
* Copied from Wolfram Mathematica C Definitions file mdefs.hpp
* Changed marcos to inline functions (Eric Cousineau)
*/
inline double Power(double x, double y) { return pow(x, y); }
inline double Sqrt(double x) { return sqrt(x); }
inline double Abs(double x) { return fabs(x); }
inline double Exp(double x) { return exp(x); }
inline double Log(double x) { return log(x); }
inline double Sin(double x) { return sin(x); }
inline double Cos(double x) { return cos(x); }
inline double Tan(double x) { return tan(x); }
inline double ArcSin(double x) { return asin(x); }
inline double ArcCos(double x) { return acos(x); }
inline double ArcTan(double x) { return atan(x); }
/* update ArcTan function to use atan2 instead. */
inline double ArcTan(double x, double y) { return atan2(y,x); }
inline double Sinh(double x) { return sinh(x); }
inline double Cosh(double x) { return cosh(x); }
inline double Tanh(double x) { return tanh(x); }
const double E = 2.71828182845904523536029;
const double Pi = 3.14159265358979323846264;
const double Degree = 0.01745329251994329576924;
inline double Sec(double x) { return 1/cos(x); }
inline double Csc(double x) { return 1/sin(x); }
#endif
/*
* Sub functions
*/
static void output1(double *p_output1,const double *var1)
{
double t125;
double t1504;
double t1473;
double t1481;
double t1506;
double t1560;
double t1487;
double t1508;
double t1536;
double t1432;
double t1561;
double t1574;
double t1589;
double t1611;
double t1546;
double t1593;
double t1603;
double t1407;
double t1613;
double t1645;
double t1676;
double t1720;
double t1608;
double t1678;
double t1703;
double t1325;
double t1748;
double t1763;
double t1783;
double t1903;
double t1709;
double t1851;
double t1876;
double t1324;
double t1906;
double t1909;
double t1942;
double t1960;
double t1882;
double t1946;
double t1952;
double t1308;
double t1961;
double t1966;
double t1968;
double t1982;
double t1957;
double t1973;
double t1975;
double t1295;
double t1985;
double t1996;
double t1999;
double t1244;
double t90;
double t2071;
double t2076;
double t2082;
double t2049;
double t2051;
double t2065;
double t2112;
double t2115;
double t2129;
double t2067;
double t2085;
double t2091;
double t2154;
double t2156;
double t2157;
double t2098;
double t2141;
double t2148;
double t2191;
double t2196;
double t2198;
double t2153;
double t2160;
double t2180;
double t2211;
double t2221;
double t2222;
double t2184;
double t2199;
double t2201;
double t2007;
double t2274;
double t2283;
double t2285;
double t2299;
double t2302;
double t2308;
double t2295;
double t2309;
double t2310;
double t2321;
double t2326;
double t2330;
double t2313;
double t2337;
double t2340;
double t2344;
double t2347;
double t2353;
double t2341;
double t2359;
double t2363;
double t2368;
double t2371;
double t2375;
double t2364;
double t2380;
double t2381;
double t2387;
double t2390;
double t2392;
double t2383;
double t2400;
double t2405;
double t2415;
double t2420;
double t2424;
double t2456;
double t2459;
double t2460;
double t2461;
double t2464;
double t2468;
double t2469;
double t2467;
double t2471;
double t2472;
double t2488;
double t2489;
double t2490;
double t2481;
double t2493;
double t2494;
double t2498;
double t2500;
double t2505;
double t2497;
double t2506;
double t2508;
double t2511;
double t2512;
double t2513;
double t2509;
double t2514;
double t2517;
double t2522;
double t2531;
double t2532;
double t2560;
double t2562;
double t2563;
double t2567;
double t2568;
double t2569;
double t2571;
double t2572;
double t2573;
double t2570;
double t2576;
double t2580;
double t2582;
double t2583;
double t2586;
double t2581;
double t2588;
double t2590;
double t2592;
double t2594;
double t2595;
double t2591;
double t2596;
double t2598;
double t2609;
double t2634;
double t2636;
double t2659;
double t2664;
double t2667;
double t2668;
double t2671;
double t2675;
double t2684;
double t2686;
double t2672;
double t2688;
double t2695;
double t2698;
double t2699;
double t2700;
double t2697;
double t2702;
double t2704;
double t2709;
double t2710;
double t2714;
double t2744;
double t2750;
double t2753;
double t2754;
double t2760;
double t2764;
double t2757;
double t2767;
double t2768;
double t2776;
double t2780;
double t2781;
double t2810;
double t2811;
double t2812;
double t2814;
double t2816;
double t2819;
double t2823;
double t2824;
double t2847;
double t2848;
double t2850;
double t2838;
double t2852;
double t2853;
double t2854;
t125 = Sin(var1[4]);
t1504 = Cos(var1[21]);
t1473 = Cos(var1[4]);
t1481 = Sin(var1[21]);
t1506 = Sin(var1[5]);
t1560 = Cos(var1[22]);
t1487 = t1473*t1481;
t1508 = -1.*t1504*t125*t1506;
t1536 = t1487 + t1508;
t1432 = Sin(var1[22]);
t1561 = -1.*t1504*t1473;
t1574 = -1.*t1481*t125*t1506;
t1589 = t1561 + t1574;
t1611 = Cos(var1[23]);
t1546 = t1432*t1536;
t1593 = t1560*t1589;
t1603 = t1546 + t1593;
t1407 = Sin(var1[23]);
t1613 = t1560*t1536;
t1645 = -1.*t1432*t1589;
t1676 = t1613 + t1645;
t1720 = Cos(var1[24]);
t1608 = t1407*t1603;
t1678 = t1611*t1676;
t1703 = t1608 + t1678;
t1325 = Sin(var1[24]);
t1748 = t1611*t1603;
t1763 = -1.*t1407*t1676;
t1783 = t1748 + t1763;
t1903 = Cos(var1[25]);
t1709 = t1325*t1703;
t1851 = t1720*t1783;
t1876 = t1709 + t1851;
t1324 = Sin(var1[25]);
t1906 = t1720*t1703;
t1909 = -1.*t1325*t1783;
t1942 = t1906 + t1909;
t1960 = Cos(var1[26]);
t1882 = -1.*t1324*t1876;
t1946 = t1903*t1942;
t1952 = t1882 + t1946;
t1308 = Sin(var1[26]);
t1961 = t1903*t1876;
t1966 = t1324*t1942;
t1968 = t1961 + t1966;
t1982 = Cos(var1[30]);
t1957 = t1308*t1952;
t1973 = t1960*t1968;
t1975 = t1957 + t1973;
t1295 = Sin(var1[30]);
t1985 = t1960*t1952;
t1996 = -1.*t1308*t1968;
t1999 = t1985 + t1996;
t1244 = Cos(var1[31]);
t90 = Cos(var1[5]);
t2071 = t1560*t1473*t90*t1481;
t2076 = t1504*t1473*t90*t1432;
t2082 = t2071 + t2076;
t2049 = t1504*t1560*t1473*t90;
t2051 = -1.*t1473*t90*t1481*t1432;
t2065 = t2049 + t2051;
t2112 = t1611*t2082;
t2115 = -1.*t2065*t1407;
t2129 = t2112 + t2115;
t2067 = t1611*t2065;
t2085 = t2082*t1407;
t2091 = t2067 + t2085;
t2154 = t1720*t2129;
t2156 = t2091*t1325;
t2157 = t2154 + t2156;
t2098 = t1720*t2091;
t2141 = -1.*t2129*t1325;
t2148 = t2098 + t2141;
t2191 = t1903*t2157;
t2196 = t2148*t1324;
t2198 = t2191 + t2196;
t2153 = t1903*t2148;
t2160 = -1.*t2157*t1324;
t2180 = t2153 + t2160;
t2211 = t1960*t2198;
t2221 = t2180*t1308;
t2222 = t2211 + t2221;
t2184 = t1960*t2180;
t2199 = -1.*t2198*t1308;
t2201 = t2184 + t2199;
t2007 = Sin(var1[31]);
t2274 = t1481*t125;
t2283 = t1504*t1473*t1506;
t2285 = t2274 + t2283;
t2299 = t1504*t125;
t2302 = -1.*t1473*t1481*t1506;
t2308 = t2299 + t2302;
t2295 = -1.*t1432*t2285;
t2309 = t1560*t2308;
t2310 = t2295 + t2309;
t2321 = t1560*t2285;
t2326 = t1432*t2308;
t2330 = t2321 + t2326;
t2313 = -1.*t1407*t2310;
t2337 = t1611*t2330;
t2340 = t2313 + t2337;
t2344 = t1611*t2310;
t2347 = t1407*t2330;
t2353 = t2344 + t2347;
t2341 = -1.*t1325*t2340;
t2359 = t1720*t2353;
t2363 = t2341 + t2359;
t2368 = t1720*t2340;
t2371 = t1325*t2353;
t2375 = t2368 + t2371;
t2364 = t1324*t2363;
t2380 = t1903*t2375;
t2381 = t2364 + t2380;
t2387 = t1903*t2363;
t2390 = -1.*t1324*t2375;
t2392 = t2387 + t2390;
t2383 = -1.*t1308*t2381;
t2400 = t1960*t2392;
t2405 = t2383 + t2400;
t2415 = t1960*t2381;
t2420 = t1308*t2392;
t2424 = t2415 + t2420;
t2456 = -1.*t1504*t125;
t2459 = t1473*t1481*t1506;
t2460 = t2456 + t2459;
t2461 = -1.*t1560*t2460;
t2464 = t2295 + t2461;
t2468 = -1.*t1432*t2460;
t2469 = t2321 + t2468;
t2467 = -1.*t1407*t2464;
t2471 = t1611*t2469;
t2472 = t2467 + t2471;
t2488 = t1611*t2464;
t2489 = t1407*t2469;
t2490 = t2488 + t2489;
t2481 = -1.*t1325*t2472;
t2493 = t1720*t2490;
t2494 = t2481 + t2493;
t2498 = t1720*t2472;
t2500 = t1325*t2490;
t2505 = t2498 + t2500;
t2497 = t1324*t2494;
t2506 = t1903*t2505;
t2508 = t2497 + t2506;
t2511 = t1903*t2494;
t2512 = -1.*t1324*t2505;
t2513 = t2511 + t2512;
t2509 = -1.*t1308*t2508;
t2514 = t1960*t2513;
t2517 = t2509 + t2514;
t2522 = t1960*t2508;
t2531 = t1308*t2513;
t2532 = t2522 + t2531;
t2560 = t1432*t2285;
t2562 = t1560*t2460;
t2563 = t2560 + t2562;
t2567 = -1.*t1407*t2563;
t2568 = -1.*t1611*t2469;
t2569 = t2567 + t2568;
t2571 = t1611*t2563;
t2572 = -1.*t1407*t2469;
t2573 = t2571 + t2572;
t2570 = -1.*t1325*t2569;
t2576 = t1720*t2573;
t2580 = t2570 + t2576;
t2582 = t1720*t2569;
t2583 = t1325*t2573;
t2586 = t2582 + t2583;
t2581 = t1324*t2580;
t2588 = t1903*t2586;
t2590 = t2581 + t2588;
t2592 = t1903*t2580;
t2594 = -1.*t1324*t2586;
t2595 = t2592 + t2594;
t2591 = -1.*t1308*t2590;
t2596 = t1960*t2595;
t2598 = t2591 + t2596;
t2609 = t1960*t2590;
t2634 = t1308*t2595;
t2636 = t2609 + t2634;
t2659 = t1407*t2563;
t2664 = t2659 + t2471;
t2667 = -1.*t1325*t2664;
t2668 = -1.*t1720*t2573;
t2671 = t2667 + t2668;
t2675 = t1720*t2664;
t2684 = -1.*t1325*t2573;
t2686 = t2675 + t2684;
t2672 = t1324*t2671;
t2688 = t1903*t2686;
t2695 = t2672 + t2688;
t2698 = t1903*t2671;
t2699 = -1.*t1324*t2686;
t2700 = t2698 + t2699;
t2697 = -1.*t1308*t2695;
t2702 = t1960*t2700;
t2704 = t2697 + t2702;
t2709 = t1960*t2695;
t2710 = t1308*t2700;
t2714 = t2709 + t2710;
t2744 = t1325*t2664;
t2750 = t2744 + t2576;
t2753 = -1.*t1324*t2750;
t2754 = t2753 + t2688;
t2760 = -1.*t1903*t2750;
t2764 = t2760 + t2699;
t2757 = -1.*t1308*t2754;
t2767 = t1960*t2764;
t2768 = t2757 + t2767;
t2776 = t1960*t2754;
t2780 = t1308*t2764;
t2781 = t2776 + t2780;
t2810 = t1903*t2750;
t2811 = t1324*t2686;
t2812 = t2810 + t2811;
t2814 = -1.*t1960*t2812;
t2816 = t2757 + t2814;
t2819 = -1.*t1308*t2812;
t2823 = t2776 + t2819;
t2824 = t1982*t2823;
t2847 = t1308*t2754;
t2848 = t1960*t2812;
t2850 = t2847 + t2848;
t2838 = -1.*t1295*t2823;
t2852 = -1.*t1295*t2850;
t2853 = t2852 + t2824;
t2854 = -1.*t2007*t2853;
p_output1[0]=1.;
p_output1[1]=0.05456*(t1244*(-1.*t1295*t1975 + t1982*t1999) - 1.*(t1975*t1982 + t1295*t1999)*t2007) + 0.0315*t125*t90;
p_output1[2]=0.0315*t1473*t1506 + 0.05456*(t1244*(t1982*t2201 - 1.*t1295*t2222) - 1.*t2007*(t1295*t2201 + t1982*t2222));
p_output1[3]=0.05456*(t1244*(t1982*t2405 - 1.*t1295*t2424) - 1.*t2007*(t1295*t2405 + t1982*t2424));
p_output1[4]=0.05456*(t1244*(t1982*t2517 - 1.*t1295*t2532) - 1.*t2007*(t1295*t2517 + t1982*t2532));
p_output1[5]=0.05456*(t1244*(t1982*t2598 - 1.*t1295*t2636) - 1.*t2007*(t1295*t2598 + t1982*t2636));
p_output1[6]=0.05456*(t1244*(t1982*t2704 - 1.*t1295*t2714) - 1.*t2007*(t1295*t2704 + t1982*t2714));
p_output1[7]=0.05456*(t1244*(t1982*t2768 - 1.*t1295*t2781) - 1.*t2007*(t1295*t2768 + t1982*t2781));
p_output1[8]=0.05456*(-1.*t2007*(t1295*t2816 + t2824) + t1244*(t1982*t2816 + t2838));
p_output1[9]=0.05456*(t1244*(t2838 - 1.*t1982*t2850) + t2854);
p_output1[10]=0.05456*(-1.*t1244*(t1295*t2823 + t1982*t2850) + t2854);
}
#ifdef MATLAB_MEX_FILE
#include "mex.h"
/*
* Main function
*/
void mexFunction( int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[] )
{
size_t mrows, ncols;
double *var1;
double *p_output1;
/* Check for proper number of arguments. */
if( nrhs != 1)
{
mexErrMsgIdAndTxt("MATLAB:MShaped:invalidNumInputs", "One input(s) required (var1).");
}
else if( nlhs > 1)
{
mexErrMsgIdAndTxt("MATLAB:MShaped:maxlhs", "Too many output arguments.");
}
/* The input must be a noncomplex double vector or scaler. */
mrows = mxGetM(prhs[0]);
ncols = mxGetN(prhs[0]);
if( !mxIsDouble(prhs[0]) || mxIsComplex(prhs[0]) ||
( !(mrows == 36 && ncols == 1) &&
!(mrows == 1 && ncols == 36)))
{
mexErrMsgIdAndTxt( "MATLAB:MShaped:inputNotRealVector", "var1 is wrong.");
}
/* Assign pointers to each input. */
var1 = mxGetPr(prhs[0]);
/* Create matrices for return arguments. */
plhs[0] = mxCreateDoubleMatrix((mwSize) 11, (mwSize) 1, mxREAL);
p_output1 = mxGetPr(plhs[0]);
/* Call the calculation subroutine. */
output1(p_output1,var1);
}
#else // MATLAB_MEX_FILE
#include "J_u_rightToeHeight_digit.hh"
namespace LeftStance
{
void J_u_rightToeHeight_digit_raw(double *p_output1, const double *var1)
{
// Call Subroutines
output1(p_output1, var1);
}
}
#endif // MATLAB_MEX_FILE
| 22.311224 | 122 | 0.650659 |
ac87d1e1be13ef149210fbd942410e7b7c7e384f | 2,521 | cpp | C++ | src/api/pipy.cpp | keveinliu/pipy | 9a03d33631c8aa8eee2f5acf9aa4d19fcc682b9a | [
"BSL-1.0"
] | 1 | 2021-12-02T02:41:30.000Z | 2021-12-02T02:41:30.000Z | src/api/pipy.cpp | keveinliu/pipy | 9a03d33631c8aa8eee2f5acf9aa4d19fcc682b9a | [
"BSL-1.0"
] | null | null | null | src/api/pipy.cpp | keveinliu/pipy | 9a03d33631c8aa8eee2f5acf9aa4d19fcc682b9a | [
"BSL-1.0"
] | null | null | null | /*
* Copyright (c) 2019 by flomesh.io
*
* Unless prior written consent has been obtained from the copyright
* owner, the following shall not be allowed.
*
* 1. The distribution of any source codes, header files, make files,
* or libraries of the software.
*
* 2. Disclosure of any source codes pertaining to the software to any
* additional parties.
*
* 3. Alteration or removal of any notices in or on the software or
* within the documentation included within the software.
*
* ALL SOURCE CODE AS WELL AS ALL DOCUMENTATION INCLUDED WITH THIS
* SOFTWARE IS PROVIDED IN AN “AS IS” CONDITION, 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 "pipy.hpp"
#include "codebase.hpp"
#include "configuration.hpp"
#include "worker.hpp"
#include "utils.hpp"
namespace pipy {
void Pipy::operator()(pjs::Context &ctx, pjs::Object *obj, pjs::Value &ret) {
pjs::Value ret_obj;
pjs::Object *context_prototype = nullptr;
if (!ctx.arguments(0, &context_prototype)) return;
if (context_prototype && context_prototype->is_function()) {
auto *f = context_prototype->as<pjs::Function>();
(*f)(ctx, 0, nullptr, ret_obj);
if (!ctx.ok()) return;
if (!ret_obj.is_object()) {
ctx.error("function did not return an object");
return;
}
context_prototype = ret_obj.o();
}
try {
auto config = Configuration::make(context_prototype);
ret.set(config);
} catch (std::runtime_error &err) {
ctx.error(err);
}
}
} // namespace pipy
namespace pjs {
using namespace pipy;
template<> void ClassDef<Pipy>::init() {
super<Function>();
ctor();
method("load", [](Context &ctx, Object*, Value &ret) {
std::string filename;
if (!ctx.arguments(1, &filename)) return;
auto path = utils::path_normalize(filename);
ret.set(Codebase::current()->get(path));
});
method("restart", [](Context&, Object*, Value&) {
Worker::restart();
});
method("exit", [](Context &ctx, Object*, Value&) {
int exit_code = 0;
if (!ctx.arguments(0, &exit_code)) return;
Worker::exit(exit_code);
});
}
} // namespace pjs
| 29.658824 | 77 | 0.676716 |
12c2663764bf2f911c51e7c31ef0d53add7afc91 | 1,884 | cpp | C++ | Game/Source/Game/src/MY_Scene_MenuBase.cpp | SweetheartSquad/GameJam2016 | e5787a6521add448fde8182ada0bce250ba831ea | [
"MIT"
] | null | null | null | Game/Source/Game/src/MY_Scene_MenuBase.cpp | SweetheartSquad/GameJam2016 | e5787a6521add448fde8182ada0bce250ba831ea | [
"MIT"
] | null | null | null | Game/Source/Game/src/MY_Scene_MenuBase.cpp | SweetheartSquad/GameJam2016 | e5787a6521add448fde8182ada0bce250ba831ea | [
"MIT"
] | null | null | null | #pragma once
#include <MY_Scene_MenuBase.h>
#include <RenderSurface.h>
#include <StandardFrameBuffer.h>
MY_Scene_MenuBase::MY_Scene_MenuBase(Game * _game) :
MY_Scene_Base(_game),
screenSurfaceShader(new Shader("assets/RenderSurface_2", false, true)),
screenSurface(new RenderSurface(screenSurfaceShader)),
screenFBO(new StandardFrameBuffer(true))
{
}
void MY_Scene_MenuBase::update(Step * _step){
// Screen shader update
// Screen shaders are typically loaded from a file instead of built using components, so to update their uniforms
// we need to use the OpenGL API calls
screenSurfaceShader->bindShader(); // remember that we have to bind the shader before it can be updated
GLint test = glGetUniformLocation(screenSurfaceShader->getProgramId(), "time");
checkForGlError(0,__FILE__,__LINE__);
if(test != -1){
glUniform1f(test, _step->time);
checkForGlError(0,__FILE__,__LINE__);
}
if(keyboard->keyJustDown(GLFW_KEY_L)){
screenSurfaceShader->unload();
screenSurfaceShader->loadFromFile(screenSurfaceShader->vertSource, screenSurfaceShader->fragSource);
screenSurfaceShader->load();
}
MY_Scene_Base::update(_step);
}
void MY_Scene_MenuBase::render(sweet::MatrixStack * _matrixStack, RenderOptions * _renderOptions){
// keep our screen framebuffer up-to-date with the game's viewport
screenFBO->resize(game->viewPortWidth, game->viewPortHeight);
// bind our screen framebuffer
FrameBufferInterface::pushFbo(screenFBO);
// render the scene
MY_Scene_Base::render(_matrixStack, _renderOptions);
// unbind our screen framebuffer, rebinding the previously bound framebuffer
// since we didn't have one bound before, this will be the default framebuffer (i.e. the one visible to the player)
FrameBufferInterface::popFbo();
// render our screen framebuffer using the standard render surface
screenSurface->render(screenFBO->getTextureId());
}
| 34.888889 | 116 | 0.778662 |
12c32c4855f70cff9c763dc607ab73041f32f6c0 | 878 | cpp | C++ | main.cpp | onodera-punpun/writebotu | 22146f06dcb197056bd5b89b18cf954a80e7a446 | [
"BSL-1.0"
] | 1 | 2020-03-25T10:11:48.000Z | 2020-03-25T10:11:48.000Z | main.cpp | onodera-punpun/writebotu | 22146f06dcb197056bd5b89b18cf954a80e7a446 | [
"BSL-1.0"
] | null | null | null | main.cpp | onodera-punpun/writebotu | 22146f06dcb197056bd5b89b18cf954a80e7a446 | [
"BSL-1.0"
] | null | null | null | #include <avr/interrupt.h>
#include <avr/io.h>
#include "drawer.h"
#include "millis.h"
#include "stepper.h"
#include "svg.h"
// Define our left pins and ports.
#define PINL_DDR DDRC
#define PINL_PORT PORTC
#define PINL_0 PC0
#define PINL_1 PC1
#define PINL_2 PC2
#define PINL_3 PC3
// Define our right pins and ports.
#define PINR_DDR DDRL
#define PINR_PORT PORTL
#define PINR_0 PL0
#define PINR_1 PL1
#define PINR_2 PL2
#define PINR_3 PL3
int main() {
// Initialize the millis library.
millis_init();
// Enable interrupts.
sei();
// Create Stepper objects.
Stepper lstepper(&PINL_DDR, &PINL_PORT, PINL_0, PINL_1, PINL_2,
PINL_3);
Stepper rstepper(&PINR_DDR, &PINR_PORT, PINR_0, PINR_1, PINR_2,
PINR_3);
// Initialize the Drawer object and draw the generated svg file.
Drawer d(lstepper, rstepper);
svg(d);
d.low();
return 0;
}
| 19.511111 | 65 | 0.703872 |
12c4d966933ab0e5976f87e85c8ebbf1f4f5303f | 4,116 | hpp | C++ | jni/Player.hpp | kaitokidi/androidSpaceTongue | 0c839dd92fe6393fa095735b08cb8966c771c36a | [
"MIT"
] | null | null | null | jni/Player.hpp | kaitokidi/androidSpaceTongue | 0c839dd92fe6393fa095735b08cb8966c771c36a | [
"MIT"
] | null | null | null | jni/Player.hpp | kaitokidi/androidSpaceTongue | 0c839dd92fe6393fa095735b08cb8966c771c36a | [
"MIT"
] | null | null | null | #ifndef PLAYER_HPP
#define PLAYER_HPP
#include "utils.hpp"
class Player {
public:
sf::SoundBuffer expbuf;
sf::Texture ship;
Player() :
pos(sf::Vector2f(0,0)), speed(sf::Vector2f(0,0))
{
expbuf.loadFromFile("res/explos.ogg");
expl.setBuffer(expbuf);
expl.setVolume(100);
alive = true;
spriteTimer = 0.0;
spriteAnimation = 0.0;
timeSinceNextSprite = 0.2;
angle = speedToRad(speed);
ship.loadFromFile("res/ship.png");
sprite.setTexture(ship);
spriteHeight = ship.getSize().y;
spriteWidth = ship.getSize().x/15;
sprite.setTextureRect(sf::IntRect(spriteAnimation*spriteWidth, 0, spriteWidth, spriteHeight));
sprite.setOrigin(sprite.getGlobalBounds().width/2,sprite.getGlobalBounds().height/2);
licked = tensioning = false;
tipofuerza = 0;
}
void setPosition(sf::Vector2f newPos){
pos = newPos;
sprite.setPosition(pos);
}
void setSpeed(sf::Vector2f newSpeed){
speed = newSpeed;
}
void update(float deltaTime) {
if (!alive) return;
if (licked) timeSinceTriggered += deltaTime;
if (tipofuerza==0)
evoluciona(deltaTime);
else
evolucionabis(deltaTime);
angle = radToAngle(speedToRad(speed))+90;
sprite.setPosition(pos);
spriteTimer += deltaTime;
if(spriteTimer >= timeSinceNextSprite){
++spriteAnimation;
spriteAnimation = (int)spriteAnimation % 15;
}
}
void draw(sf::RenderWindow &window) {
if (!alive) return;
sprite.setTextureRect(sf::IntRect(spriteAnimation*spriteWidth, 0, spriteWidth, spriteHeight));
sprite.setRotation(angle);sprite.setScale(sf::Vector2f(scalePlayer,scalePlayer));
window.draw(sprite);
}
sf::Vector2f getPosition() {
return pos;
}
void setLicked(bool b, sf::Vector2f cPos, int tipofuerza) {
this->tipofuerza = tipofuerza;
camaleonPos = cPos;
licked = b;
if (!b) {
tensioning = false;
timeSinceTriggered = 0;
}
}
void setAlive(bool b) {
if (!b && alive) {
alive = b;
expl.play();
}
}
bool isAlive() {
return alive;
}
sf::Vector2f getSpeed() {
return speed;
}
sf::CircleShape getBox() {
sf::CircleShape aux(spriteWidth/2*scalePlayer*0.5);
aux.setPosition(pos);
return aux;
}
//Private functions
private:
//Player properties
sf::Sound expl;
sf::Vector2f pos;
sf::Sprite sprite;
sf::Vector2f speed;
float angle;
float spriteTimer;
float spriteWidth;
float spriteHeight;
float spriteAnimation;
float timeSinceNextSprite;
int tipofuerza;
// Camaleon related things
bool licked;
bool tensioning;
float timeSinceTriggered;
sf::Vector2f camaleonPos;
void evoluciona(float fdelta){
double delta=fdelta;
point p=vector2point(pos);
point v=vector2point(speed);
point c=vector2point(camaleonPos);
if (not licked || timeSinceTriggered < animationTime) {
p+=v*delta;
pos=point2vector(p);
return;
}
if (not tensioning) {
p+=v*delta;
pos=point2vector(p);
if (prodesc(v,p-c)>=0)
tensioning=true;
return;
}
p-=c;
double modulov=abs(v);
double desp=modulov*delta;
double r=abs(p);
double alfa=desp/r;
int signo=prodvec(p,v)>0?1:-1;
p*=std::polar(1.0,signo*alfa);
v=p*std::polar(1.0,signo*M_PI/2.0);
v=(modulov/abs(v))*v;
p+=c;
pos=point2vector(p);
speed=point2vector(v);
}
double fuerza(double distancia)
{
if (tipofuerza==1)
return sqrt(abs(distancia))*5;
if (tipofuerza==2)
return abs(distancia)/200;
//return 30;
//return 5000000/(distancia*distancia);
}
void evolucionabis(float fdelta)
{
double delta=fdelta;
point p=vector2point(pos);
point v=vector2point(speed);
if (not licked || timeSinceTriggered < animationTime) {
p+=v*delta;
pos=point2vector(p);
return;
}
point c=vector2point(camaleonPos);
int pasos=100;
delta/=pasos;
for (int paso=0;paso<pasos;paso++) {
point dir=c-p;
v=v+(fuerza(abs(dir))*delta/abs(dir))*dir;
p=p+v*delta;
}
pos=point2vector(p);
speed=point2vector(v);
}
// Comido
bool alive;
};
#endif // PLAYER_HPP
| 20.683417 | 98 | 0.654276 |
12cae306250db20416675aa5d23e43b3faae64ed | 4,176 | cpp | C++ | Codeforces/Gym102823B.cpp | HeRaNO/OI-ICPC-Codes | 4a4639cd3e347b472520065ca6ab8caadde6906d | [
"MIT"
] | 18 | 2019-01-01T13:16:59.000Z | 2022-02-28T04:51:50.000Z | Codeforces/Gym102823B.cpp | HeRaNO/OI-ICPC-Codes | 4a4639cd3e347b472520065ca6ab8caadde6906d | [
"MIT"
] | null | null | null | Codeforces/Gym102823B.cpp | HeRaNO/OI-ICPC-Codes | 4a4639cd3e347b472520065ca6ab8caadde6906d | [
"MIT"
] | 5 | 2019-09-13T08:48:17.000Z | 2022-02-19T06:59:03.000Z | #include<bits/stdc++.h>
using namespace std;
#define fi first
#define se second
#define SZ(x) ((int)x.size())
#define lowbit(x) x&-x
#define pb push_back
#define ALL(x) (x).begin(),(x).end()
#define UNI(x) sort(ALL(x)),x.resize(unique(ALL(x))-x.begin())
#define GETPOS(c,x) (lower_bound(ALL(c),x)-c.begin())
#define LEN(x) strlen(x)
#define MS0(x) memset((x),0,sizeof((x)))
#define Rint register int
#define ls (u<<1)
#define rs (u<<1|1)
typedef unsigned int unit;
typedef long long ll;
typedef unsigned long long ull;
typedef double db;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef vector<int> Vi;
typedef vector<ll> Vll;
typedef vector<pii> Vpii;
template<class T> void _R(T &x) { cin >> x; }
void _R(int &x) { scanf("%d", &x); }
void _R(ll &x) { scanf("%lld", &x); }
void _R(ull &x) { scanf("%llu", &x); }
void _R(double &x) { scanf("%lf", &x); }
void _R(char &x) { scanf(" %c", &x); }
void _R(char *x) { scanf("%s", x); }
void R() {}
template<class T, class... U> void R(T &head, U &... tail) { _R(head); R(tail...); }
template<class T> void _W(const T &x) { cout << x; }
void _W(const int &x) { printf("%d", x); }
void _W(const ll &x) { printf("%lld", x); }
void _W(const double &x) { printf("%.16f", x); }
void _W(const char &x) { putchar(x); }
void _W(const char *x) { printf("%s", x); }
template<class T,class U> void _W(const pair<T,U> &x) {_W(x.fi);putchar(' '); _W(x.se);}
template<class T> void _W(const vector<T> &x) { for (auto i = x.begin(); i != x.end(); _W(*i++)) if (i != x.cbegin()) putchar(' '); }
void W() {}
template<class T, class... U> void W(const T &head, const U &... tail) { _W(head); putchar(sizeof...(tail) ? ' ' : '\n'); W(tail...); }
const int MOD=998244353,mod=998244353;
ll qpow(ll a,ll b) {ll res=1;a%=MOD; assert(b>=0); for(;b;b>>=1){if(b&1)res=res*a%MOD;a=a*a%MOD;}return res;}
const int MAXN=5e5+10,MAXM=2e6+10;
const int INF=INT_MAX,SINF=0x3f3f3f3f;
const ll llINF=LLONG_MAX;
const int inv2=(MOD+1)/2;
const int Lim=1<<20;
int add (int a, int b) { return (a += b) >= mod ? a - mod : a; }
int sub (int a, int b) { return (a -= b) >= 0 ? a : a + mod; }
int mul (long long a, int b) { return a * b % mod; }
int ksm (ll a, ll b) { ll ret = 1; while (b) { if (b & 1) ret = 1ll * ret * a % mod; a = 1ll * a * a % mod; b >>= 1; } return ret; }
int rev[Lim+5],lg2[Lim+5],rt[Lim+5],irt[Lim+5];
int k,lim,type;
void init() //��ԭ��
{
for(int i=2;i<=Lim;i++)lg2[i]=lg2[i>>1]+1;
rt[0]=1;
rt[1]=ksm(3,(MOD-1)/Lim); //��һ��ԭ��
irt[0]=1;
irt[1]=ksm(rt[1],MOD-2); //����С
for(int i=2;i<=Lim;i++)
{
rt[i]=mul(rt[i-1],rt[1]);
irt[i]=mul(irt[i-1],irt[1]);
}
}
void NTT(Vi &f,int type,int lim)
{
f.resize(lim);
int w,y,l=lg2[lim]-1;
for(int i=1;i<lim;i++)
{
rev[i]=(rev[i>>1]>>1)|((i&1)<<l);
if(i>=rev[i])continue;
swap(f[i],f[rev[i]]); //����
}
l=Lim>>1;
for(int mid=1;mid<lim;mid<<=1)
{
for(int j=0;j<lim;j+=(mid<<1))
{
for(int k=0;k<mid;k++)
{
w=type==1?rt[l*k]:irt[l*k];
y=mul(w,f[j|k|mid]);
f[j|k|mid]=sub(f[j|k],y);
f[j|k]=add(f[j|k],y);
}
}
l>>=1;
}
if(type==1)return;
y=ksm(lim,MOD-2);
for(int i=0;i<lim;i++)
f[i]=mul(f[i],y);
}
void NTTTMD(Vi &F,Vi &G)
{
int n=SZ(F)+SZ(G);
lim=1;
while(lim<=n)lim<<=1;
F.resize(lim);G.resize(lim);
NTT(F,1,lim),NTT(G,1,lim);
for(int i=0;i<lim;i++)F[i]=mul(F[i],G[i]);
NTT(F,-1,lim);
F.resize(n-1);
}
int n,a[MAXN],L,m;
ll inv[MAXN];
int getinv(int x)
{
if(x==0)return 1;
return ksm(x,MOD-2);
}
void solve()
{
R(n,L,m);
for(int i=0;i<n;i++)R(a[i]);
reverse(a,a+n);
Vi t1,t2;
t1.resize(n),t2.resize(n);
ll tmp=1;t1[0]=tmp;
for(int i=1;i<n;i++)
{
tmp=mul(tmp,m-1+i);
tmp=mul(tmp,inv[i]);
t1[i]=tmp;
}
tmp=1;
t2[0]=1;
for(int i=1;i*L<n&&i<=m;i++)
{
tmp=mul(tmp,m-i+1);
tmp=mul(tmp,inv[i]);
t2[i*L]=tmp;
if(i&1)t2[i*L]=(MOD-t2[i*L])%MOD;
}
NTTTMD(t1,t2);
Vi t3;
for(int i=0;i<n;i++)t3.pb(a[i]);
NTTTMD(t3,t1);
t3.resize(n);
reverse(ALL(t3));
W(t3);
}
int main()
{
inv[1]=1;
for (int i=2;i<=300000;i++) inv[i]=1ll*(MOD-MOD/i)*inv[MOD%i]%MOD;
init();
int T;
scanf("%d",&T);
for(int kase=1;kase<=T;kase++)
{
printf("Case %d: ",kase);
solve();
}
return 0;
} | 24.710059 | 135 | 0.554358 |
12cc90aa410589156f8780d3316bea673f55b192 | 22,105 | cpp | C++ | cocos2d-x-2.2/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.cpp | centrallydecentralized/ufo | 29e8f9ce4ce92635ed22f8a051c917cfe6e0313d | [
"BSD-3-Clause"
] | 58 | 2015-01-05T04:40:48.000Z | 2021-12-17T06:01:28.000Z | cocos2d-x-2.2/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.cpp | centrallydecentralized/ufo | 29e8f9ce4ce92635ed22f8a051c917cfe6e0313d | [
"BSD-3-Clause"
] | null | null | null | cocos2d-x-2.2/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.cpp | centrallydecentralized/ufo | 29e8f9ce4ce92635ed22f8a051c917cfe6e0313d | [
"BSD-3-Clause"
] | 46 | 2015-01-03T06:20:54.000Z | 2020-04-18T13:32:52.000Z |
#include "cocos-ext.h"
#include "../ExtensionsTest.h"
#include "SceneEditorTest.h"
#include "TriggerCode/EventDef.h"
#include "../../testResource.h"
using namespace cocos2d;
using namespace cocos2d::extension;
using namespace cocos2d::ui;
CCLayer *Next();
CCLayer *Back();
CCLayer *Restart();
static int s_nIdx = -1;
CCLayer *createTests(int index)
{
CCLayer *pLayer = NULL;
switch(index)
{
case TEST_LOADSCENEEDITORFILE:
pLayer = new LoadSceneEdtiorFileTest();
break;
case TEST_SPIRTECOMPONENT:
pLayer = new SpriteComponentTest();
break;
case TEST_ARMATURECOMPONENT:
pLayer = new ArmatureComponentTest();
break;
case TEST_UICOMPONENT:
pLayer = new UIComponentTest();
break;
case TEST_TMXMAPCOMPONENT:
pLayer = new TmxMapComponentTest();
break;
case TEST_PARTICLECOMPONENT:
pLayer = new ParticleComponentTest();
break;
case TEST_EFEECTCOMPONENT:
pLayer = new EffectComponentTest();
break;
case TEST_BACKGROUNDCOMPONENT:
pLayer = new BackgroundComponentTest();
break;
case TEST_ATTRIBUTECOMPONENT:
pLayer = new AttributeComponentTest();
break;
case TEST_TRIGGER:
pLayer = new TriggerTest();
pLayer->init();
break;
default:
break;
}
return pLayer;
}
CCLayer *Next()
{
++s_nIdx;
s_nIdx = s_nIdx % TEST_SCENEEDITOR_COUNT;
CCLayer *pLayer = createTests(s_nIdx);
pLayer->autorelease();
return pLayer;
}
CCLayer *Back()
{
--s_nIdx;
if( s_nIdx < 0 )
s_nIdx += TEST_SCENEEDITOR_COUNT;
CCLayer *pLayer = createTests(s_nIdx);
pLayer->autorelease();
return pLayer;
}
CCLayer *Restart()
{
CCLayer *pLayer = createTests(s_nIdx);
pLayer->autorelease();
return pLayer;
}
SceneEditorTestScene::SceneEditorTestScene(bool bPortrait)
{
TestScene::init();
}
void SceneEditorTestScene::runThisTest()
{
s_nIdx = -1;
addChild(Next());
CCDirector::sharedDirector()->replaceScene(this);
}
void SceneEditorTestScene::MainMenuCallback(CCObject *pSender)
{
TestScene::MainMenuCallback(pSender);
}
const char* SceneEditorTestLayer::m_loadtypeStr[2] = {"change to load \nwith binary file","change to load \nwith json file"};
void SceneEditorTestLayer::onEnter()
{
CCLayer::onEnter();
// add title and subtitle
std::string str = title();
const char *pTitle = str.c_str();
CCLabelTTF *label = CCLabelTTF::create(pTitle, "Arial", 18);
label->setColor(ccc3(255, 255, 255));
addChild(label, 100, 10000);
label->setPosition( ccp(VisibleRect::center().x, VisibleRect::top().y - 30) );
std::string strSubtitle = subtitle();
if( ! strSubtitle.empty() )
{
CCLabelTTF *l = CCLabelTTF::create(strSubtitle.c_str(), "Arial", 18);
l->setColor(ccc3(0, 0, 0));
addChild(l, 1, 10001);
l->setPosition( ccp(VisibleRect::center().x, VisibleRect::top().y - 60) );
}
// change button
m_isCsbLoad = false;
m_loadtypelb = CCLabelTTF::create(m_loadtypeStr[0], "Arial", 12);
// #endif
CCMenuItemLabel* itemlb = CCMenuItemLabel::create(m_loadtypelb, this, menu_selector(SceneEditorTestLayer::changeLoadTypeCallback));
CCMenu* loadtypemenu = CCMenu::create(itemlb, NULL);
loadtypemenu->setPosition(ccp(VisibleRect::rightTop().x -50,VisibleRect::rightTop().y -20));
addChild(loadtypemenu,100);
// add menu
backItem = CCMenuItemImage::create(s_pPathB1, s_pPathB2, this, menu_selector(SceneEditorTestLayer::backCallback) );
restartItem = CCMenuItemImage::create(s_pPathR1, s_pPathR2, this, menu_selector(SceneEditorTestLayer::restartCallback) );
nextItem = CCMenuItemImage::create(s_pPathF1, s_pPathF2, this, menu_selector(SceneEditorTestLayer::nextCallback) );
CCMenu *menu = CCMenu::create(backItem, restartItem, nextItem, NULL);
float fScale = 0.5f;
menu->setPosition(ccp(0, 0));
backItem->setPosition(ccp(VisibleRect::center().x - restartItem->getContentSize().width * 2 * fScale, VisibleRect::bottom().y + restartItem->getContentSize().height / 2));
backItem->setScale(fScale);
restartItem->setPosition(ccp(VisibleRect::center().x, VisibleRect::bottom().y + restartItem->getContentSize().height / 2));
restartItem->setScale(fScale);
nextItem->setPosition(ccp(VisibleRect::center().x + restartItem->getContentSize().width * 2 * fScale, VisibleRect::bottom().y + restartItem->getContentSize().height / 2));
nextItem->setScale(fScale);
addChild(menu, 100);
setShaderProgram(CCShaderCache::sharedShaderCache()->programForKey(kCCShader_PositionTextureColor));
}
void SceneEditorTestLayer::onExit()
{
removeAllChildren();
backItem = restartItem = nextItem = NULL;
}
std::string SceneEditorTestLayer::title()
{
return "SceneReader Test LoadSceneEditorFile";
}
std::string SceneEditorTestLayer::subtitle()
{
return "";
}
void SceneEditorTestLayer::restartCallback(CCObject *pSender)
{
CCScene *s = new SceneEditorTestScene();
s->addChild(Restart());
CCDirector::sharedDirector()->replaceScene(s);
s->release();
}
void SceneEditorTestLayer::nextCallback(CCObject *pSender)
{
CCScene *s = new SceneEditorTestScene();
s->addChild(Next());
CCDirector::sharedDirector()->replaceScene(s);
s->release();
}
void SceneEditorTestLayer::backCallback(CCObject *pSender)
{
CCScene *s = new SceneEditorTestScene();
s->addChild(Back());
CCDirector::sharedDirector()->replaceScene(s);
s->release();
}
void SceneEditorTestLayer::draw()
{
CCLayer::draw();
}
void SceneEditorTestLayer::changeLoadTypeCallback( CCObject *pSender)
{
m_isCsbLoad = !m_isCsbLoad;
m_loadtypelb->setString(m_loadtypeStr[(int)m_isCsbLoad]);
loadFileChangeHelper(m_filePathName);
if(m_rootNode != NULL)
{
this->removeChild(m_rootNode);
m_rootNode = SceneReader::sharedSceneReader()->createNodeWithSceneFile(m_filePathName.c_str());
if (m_rootNode == NULL)
{
return ;
}
defaultPlay();
this->addChild(m_rootNode);
}
}
void SceneEditorTestLayer::loadFileChangeHelper(string& filePathName)
{
int n = filePathName.find_last_of(".");
if(-1 == n)
return;
filePathName = filePathName.substr(0,n);
if(m_isCsbLoad)
filePathName.append(".csb");
else
filePathName.append(".json");
}
LoadSceneEdtiorFileTest::LoadSceneEdtiorFileTest()
{
}
LoadSceneEdtiorFileTest::~LoadSceneEdtiorFileTest()
{
}
std::string LoadSceneEdtiorFileTest::title()
{
return "LoadSceneEdtiorFile Test";
}
void LoadSceneEdtiorFileTest::onEnter()
{
SceneEditorTestLayer::onEnter();
do
{
CCNode *root = createGameScene();
CC_BREAK_IF(!root);
this->addChild(root, 0, 1);
} while (0);
}
void LoadSceneEdtiorFileTest::onExit()
{
CCArmatureDataManager::purge();
SceneReader::purge();
ActionManager::purge();
GUIReader::purge();
SceneEditorTestLayer::onExit();
}
cocos2d::CCNode* LoadSceneEdtiorFileTest::createGameScene()
{
m_filePathName = "scenetest/LoadSceneEdtiorFileTest/FishJoy2.json"; //default is json
m_rootNode = SceneReader::sharedSceneReader()->createNodeWithSceneFile(m_filePathName.c_str());
if (m_rootNode == NULL)
{
return NULL;
}
defaultPlay();
return m_rootNode;
}
void LoadSceneEdtiorFileTest::defaultPlay()
{
cocos2d::extension::ActionManager::shareManager()->playActionByName("startMenu_1.json","Animation1");
}
SpriteComponentTest::SpriteComponentTest()
{
}
SpriteComponentTest::~SpriteComponentTest()
{
}
std::string SpriteComponentTest::title()
{
return "Sprite Component Test";
}
void SpriteComponentTest::onEnter()
{
SceneEditorTestLayer::onEnter();
do
{
CCNode *root = createGameScene();
CC_BREAK_IF(!root);
this->addChild(root, 0, 1);
} while (0);
}
void SpriteComponentTest::onExit()
{
CCArmatureDataManager::purge();
SceneReader::purge();
ActionManager::purge();
GUIReader::purge();
SceneEditorTestLayer::onExit();
}
cocos2d::CCNode* SpriteComponentTest::createGameScene()
{
m_filePathName = "scenetest/SpriteComponentTest/SpriteComponentTest.json";
m_rootNode = SceneReader::sharedSceneReader()->createNodeWithSceneFile(m_filePathName.c_str());
if (m_rootNode == NULL)
{
return NULL;
}
defaultPlay();
return m_rootNode;
}
void SpriteComponentTest::defaultPlay()
{
CCActionInterval* action1 = CCBlink::create(2, 10);
CCActionInterval* action2 = CCBlink::create(2, 5);
CCComRender *pSister1 = static_cast<CCComRender*>(m_rootNode->getChildByTag(10003)->getComponent("CCSprite"));
pSister1->getNode()->runAction(action1);
CCComRender *pSister2 = static_cast<CCComRender*>(m_rootNode->getChildByTag(10004)->getComponent("CCSprite"));
pSister2->getNode()->runAction(action2);
}
ArmatureComponentTest::ArmatureComponentTest()
{
}
ArmatureComponentTest::~ArmatureComponentTest()
{
}
std::string ArmatureComponentTest::title()
{
return "Armature Component Test";
}
void ArmatureComponentTest::onEnter()
{
SceneEditorTestLayer::onEnter();
do
{
CCNode *root = createGameScene();
CC_BREAK_IF(!root);
this->addChild(root, 0, 1);
} while (0);
}
void ArmatureComponentTest::onExit()
{
CCArmatureDataManager::purge();
SceneReader::purge();
ActionManager::purge();
GUIReader::purge();
SceneEditorTestLayer::onExit();
}
cocos2d::CCNode* ArmatureComponentTest::createGameScene()
{
m_filePathName = "scenetest/ArmatureComponentTest/ArmatureComponentTest.json";
m_rootNode = SceneReader::sharedSceneReader()->createNodeWithSceneFile(m_filePathName.c_str());
if (m_rootNode == NULL)
{
return NULL;
}
defaultPlay();
return m_rootNode;
}
void ArmatureComponentTest::defaultPlay()
{
CCComRender *pBlowFish = static_cast<CCComRender*>(m_rootNode->getChildByTag(10007)->getComponent("CCArmature"));
pBlowFish->getNode()->runAction(CCMoveBy::create(10.0f, ccp(-1000.0f, 0)));
CCComRender *pButterflyfish = static_cast<CCComRender*>(m_rootNode->getChildByTag(10008)->getComponent("CCArmature"));
pButterflyfish->getNode()->runAction(CCMoveBy::create(10.0f, ccp(-1000.0f, 0)));
}
UIComponentTest::UIComponentTest()
{
}
UIComponentTest::~UIComponentTest()
{
}
std::string UIComponentTest::title()
{
return "UI Component Test";
}
void UIComponentTest::onEnter()
{
SceneEditorTestLayer::onEnter();
do
{
CCNode *root = createGameScene();
CC_BREAK_IF(!root);
this->addChild(root, 0, 1);
} while (0);
}
void UIComponentTest::onExit()
{
CCArmatureDataManager::purge();
SceneReader::purge();
ActionManager::purge();
GUIReader::purge();
SceneEditorTestLayer::onExit();
}
cocos2d::CCNode* UIComponentTest::createGameScene()
{
m_filePathName = "scenetest/UIComponentTest/UIComponentTest.json";
m_rootNode = SceneReader::sharedSceneReader()->createNodeWithSceneFile(m_filePathName.c_str());
if (m_rootNode == NULL)
{
return NULL;
}
defaultPlay();
return m_rootNode;
}
void UIComponentTest::touchEvent(CCObject *pSender, TouchEventType type)
{
switch (type)
{
case TOUCH_EVENT_BEGAN:
{
CCComRender *pBlowFish = static_cast<CCComRender*>(m_rootNode->getChildByTag(10010)->getComponent("CCArmature"));
pBlowFish->getNode()->runAction(CCMoveBy::create(10.0f, ccp(-1000.0f, 0)));
CCComRender *pButterflyfish = static_cast<CCComRender*>(m_rootNode->getChildByTag(10011)->getComponent("CCArmature"));
pButterflyfish->getNode()->runAction(CCMoveBy::create(10.0f, ccp(-1000.0f, 0)));
}
break;
default:
break;
}
}
void UIComponentTest::defaultPlay()
{
CCComRender *render = static_cast<CCComRender*>(m_rootNode->getChildByTag(10025)->getComponent("GUIComponent"));
cocos2d::ui::TouchGroup* touchGroup = static_cast<cocos2d::ui::TouchGroup*>(render->getNode());
UIWidget* widget = static_cast<UIWidget*>(touchGroup->getWidgetByName("Panel_154"));
UIButton* button = static_cast<UIButton*>(widget->getChildByName("Button_156"));
button->addTouchEventListener(this, toucheventselector(UIComponentTest::touchEvent));
}
TmxMapComponentTest::TmxMapComponentTest()
{
}
TmxMapComponentTest::~TmxMapComponentTest()
{
}
std::string TmxMapComponentTest::title()
{
return "TmxMap Component Test";
}
void TmxMapComponentTest::onEnter()
{
SceneEditorTestLayer::onEnter();
do
{
CCNode *root = createGameScene();
CC_BREAK_IF(!root);
this->addChild(root, 0, 1);
} while (0);
}
void TmxMapComponentTest::onExit()
{
CCArmatureDataManager::purge();
SceneReader::purge();
ActionManager::purge();
GUIReader::purge();
SceneEditorTestLayer::onExit();
}
cocos2d::CCNode* TmxMapComponentTest::createGameScene()
{
m_filePathName = "scenetest/TmxMapComponentTest/TmxMapComponentTest.json";
m_rootNode = SceneReader::sharedSceneReader()->createNodeWithSceneFile(m_filePathName.c_str());
if (m_rootNode == NULL)
{
return NULL;
}
defaultPlay();
return m_rootNode;
}
void TmxMapComponentTest::defaultPlay()
{
CCComRender *tmxMap = static_cast<CCComRender*>(m_rootNode->getChildByTag(10015)->getComponent("CCTMXTiledMap"));
CCActionInterval *actionTo = CCSkewTo::create(2, 0.f, 2.f);
CCActionInterval *rotateTo = CCRotateTo::create(2, 61.0f);
CCActionInterval *actionScaleTo = CCScaleTo::create(2, -0.44f, 0.47f);
CCActionInterval *actionScaleToBack = CCScaleTo::create(2, 1.0f, 1.0f);
CCActionInterval *rotateToBack = CCRotateTo::create(2, 0);
CCActionInterval *actionToBack = CCSkewTo::create(2, 0, 0);
tmxMap->getNode()->runAction(CCSequence::create(actionTo, actionToBack, NULL));
tmxMap->getNode()->runAction(CCSequence::create(rotateTo, rotateToBack, NULL));
tmxMap->getNode()->runAction(CCSequence::create(actionScaleTo, actionScaleToBack, NULL));
}
ParticleComponentTest::ParticleComponentTest()
{
}
ParticleComponentTest::~ParticleComponentTest()
{
}
std::string ParticleComponentTest::title()
{
return "Particle Component Test";
}
void ParticleComponentTest::onEnter()
{
SceneEditorTestLayer::onEnter();
do
{
CCNode *root = createGameScene();
CC_BREAK_IF(!root);
this->addChild(root, 0, 1);
} while (0);
}
void ParticleComponentTest::onExit()
{
CCArmatureDataManager::purge();
SceneReader::purge();
ActionManager::purge();
GUIReader::purge();
SceneEditorTestLayer::onExit();
}
cocos2d::CCNode* ParticleComponentTest::createGameScene()
{
m_filePathName = "scenetest/ParticleComponentTest/ParticleComponentTest.json";
m_rootNode = SceneReader::sharedSceneReader()->createNodeWithSceneFile(m_filePathName.c_str());
if (m_rootNode == NULL)
{
return NULL;
}
defaultPlay();
return m_rootNode;
}
void ParticleComponentTest::defaultPlay()
{
CCComRender* Particle = static_cast<CCComRender*>(m_rootNode->getChildByTag(10020)->getComponent("CCParticleSystemQuad"));
CCActionInterval* jump = CCJumpBy::create(5, ccp(-500,0), 50, 4);
CCFiniteTimeAction* action = CCSequence::create( jump, jump->reverse(), NULL);
Particle->getNode()->runAction(action);
}
EffectComponentTest::EffectComponentTest()
{
}
EffectComponentTest::~EffectComponentTest()
{
}
std::string EffectComponentTest::title()
{
return "Effect Component Test";
}
void EffectComponentTest::onEnter()
{
SceneEditorTestLayer::onEnter();
do
{
CCNode *root = createGameScene();
CC_BREAK_IF(!root);
this->addChild(root, 0, 1);
} while (0);
}
void EffectComponentTest::onExit()
{
CCArmatureDataManager::purge();
SceneReader::purge();
ActionManager::purge();
GUIReader::purge();
SceneEditorTestLayer::onExit();
}
cocos2d::CCNode* EffectComponentTest::createGameScene()
{
m_filePathName = "scenetest/EffectComponentTest/EffectComponentTest.json";
m_rootNode = SceneReader::sharedSceneReader()->createNodeWithSceneFile(m_filePathName.c_str());
if (m_rootNode == NULL)
{
return NULL;
}
defaultPlay();
return m_rootNode;
}
void EffectComponentTest::animationEvent(cocos2d::extension::CCArmature *armature, cocos2d::extension::MovementEventType movementType, const char *movementID)
{
std::string id = movementID;
if (movementType == LOOP_COMPLETE)
{
if (id.compare("Fire") == 0)
{
CCComAudio *pAudio = static_cast<CCComAudio*>(m_rootNode->getChildByTag(10015)->getComponent("CCComAudio"));
pAudio->playEffect();
}
}
}
void EffectComponentTest::defaultPlay()
{
CCComRender *pRender = static_cast<CCComRender*>(m_rootNode->getChildByTag(10015)->getComponent("CCArmature"));
CCArmature *pAr = static_cast<CCArmature*>(pRender->getNode());
pAr->getAnimation()->setMovementEventCallFunc(this, movementEvent_selector(EffectComponentTest::animationEvent));
}
BackgroundComponentTest::BackgroundComponentTest()
{
}
BackgroundComponentTest::~BackgroundComponentTest()
{
}
std::string BackgroundComponentTest::title()
{
return "Background Component Test";
}
void BackgroundComponentTest::onEnter()
{
SceneEditorTestLayer::onEnter();
do
{
CCNode *root = createGameScene();
CC_BREAK_IF(!root);
this->addChild(root, 0, 1);
} while (0);
}
void BackgroundComponentTest::onExit()
{
CCArmatureDataManager::purge();
SceneReader::purge();
ActionManager::purge();
GUIReader::purge();
SceneEditorTestLayer::onExit();
}
cocos2d::CCNode* BackgroundComponentTest::createGameScene()
{
m_filePathName = "scenetest/BackgroundComponentTest/BackgroundComponentTest.json";
m_rootNode = SceneReader::sharedSceneReader()->createNodeWithSceneFile(m_filePathName.c_str());
if (m_rootNode == NULL)
{
return NULL;
}
defaultPlay();
return m_rootNode;
}
void BackgroundComponentTest::defaultPlay()
{
cocos2d::extension::ActionManager::shareManager()->playActionByName("startMenu_1.json","Animation1");
CCComAudio *Audio = static_cast<CCComAudio*>(m_rootNode->getComponent("CCBackgroundAudio"));
Audio->playBackgroundMusic();
}
AttributeComponentTest::AttributeComponentTest()
{
}
AttributeComponentTest::~AttributeComponentTest()
{
}
std::string AttributeComponentTest::title()
{
return "Attribute Component Test";
}
void AttributeComponentTest::onEnter()
{
SceneEditorTestLayer::onEnter();
do
{
CCNode *root = createGameScene();
initData();
CC_BREAK_IF(!root);
this->addChild(root, 0, 1);
} while (0);
}
void AttributeComponentTest::onExit()
{
CCArmatureDataManager::purge();
SceneReader::purge();
ActionManager::purge();
GUIReader::purge();
SceneEditorTestLayer::onExit();
}
bool AttributeComponentTest::initData()
{
bool bRet = false;
do {
CC_BREAK_IF(m_rootNode == NULL);
CCComAttribute *pAttribute = static_cast<CCComAttribute*>(m_rootNode->getChildByTag(10015)->getComponent("CCComAttribute"));
CCLog("Name: %s, HP: %f, MP: %f", pAttribute->getCString("name"), pAttribute->getFloat("maxHP"), pAttribute->getFloat("maxMP"));
bRet = true;
} while (0);
return bRet;
}
cocos2d::CCNode* AttributeComponentTest::createGameScene()
{
m_filePathName = "scenetest/AttributeComponentTest/AttributeComponentTest.json";
m_rootNode = SceneReader::sharedSceneReader()->createNodeWithSceneFile(m_filePathName.c_str());
if (m_rootNode == NULL)
{
return NULL;
}
return m_rootNode;
}
void AttributeComponentTest::defaultPlay()
{
initData();
}
TriggerTest::TriggerTest()
{
m_rootNode = NULL;
}
TriggerTest::~TriggerTest()
{
}
std::string TriggerTest::title()
{
return "Trigger Test";
}
bool TriggerTest::init()
{
sendEvent(TRIGGEREVENT_INITSCENE);
return true;
}
void TriggerTest::onEnter()
{
SceneEditorTestLayer::onEnter();
CCNode *root = createGameScene();
this->addChild(root, 0, 1);
}
void TriggerTest::onExit()
{
sendEvent(TRIGGEREVENT_LEAVESCENE);
this->unschedule(schedule_selector(TriggerTest::gameLogic));
this->setTouchEnabled(false);
CCArmatureDataManager::purge();
SceneReader::purge();
ActionManager::purge();
GUIReader::purge();
SceneEditorTestLayer::onExit();
}
bool TriggerTest::ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent)
{
sendEvent(TRIGGEREVENT_TOUCHBEGAN);
return true;
}
void TriggerTest::ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent)
{
sendEvent(TRIGGEREVENT_TOUCHMOVED);
}
void TriggerTest::ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent)
{
sendEvent(TRIGGEREVENT_TOUCHENDED);
}
void TriggerTest::ccTouchCancelled(CCTouch *pTouch, CCEvent *pEvent)
{
sendEvent(TRIGGEREVENT_TOUCHCANCELLED);
}
void TriggerTest::gameLogic(float dt)
{
sendEvent(TRIGGEREVENT_UPDATESCENE);
}
static ActionObject* actionObject = NULL;
cocos2d::CCNode* TriggerTest::createGameScene()
{
m_filePathName = "scenetest/TriggerTest/TriggerTest.json";
m_rootNode = SceneReader::sharedSceneReader()->createNodeWithSceneFile(m_filePathName.c_str());
if (m_rootNode == NULL)
{
return NULL;
}
defaultPlay();
return m_rootNode;
}
void TriggerTest::defaultPlay()
{
//ui action
actionObject = cocos2d::extension::ActionManager::shareManager()->playActionByName("startMenu_1.json","Animation1");
this->schedule(schedule_selector(TriggerTest::gameLogic));
this->setTouchEnabled(true);
this->setTouchMode(kCCTouchesOneByOne);
sendEvent(TRIGGEREVENT_ENTERSCENE);
}
| 24.977401 | 176 | 0.688803 |
12ccb19ceb3c1569112a3e7b2c3147bd87d652aa | 12,812 | cpp | C++ | src/windows/Undo.cpp | hhyyrylainen/DualViewPP | 1fb4a1db85a8509342e16d68c75d4ec7721ced9e | [
"MIT"
] | null | null | null | src/windows/Undo.cpp | hhyyrylainen/DualViewPP | 1fb4a1db85a8509342e16d68c75d4ec7721ced9e | [
"MIT"
] | null | null | null | src/windows/Undo.cpp | hhyyrylainen/DualViewPP | 1fb4a1db85a8509342e16d68c75d4ec7721ced9e | [
"MIT"
] | null | null | null | // ------------------------------------ //
#include "Undo.h"
#include "resources/DatabaseAction.h"
#include "Database.h"
#include "DualView.h"
#include "Settings.h"
using namespace DV;
// ------------------------------------ //
UndoWindow::UndoWindow() :
ClearHistory("Clear History"), HistorySizeLabel("History items to keep"),
MainContainer(Gtk::ORIENTATION_VERTICAL), ListContainer(Gtk::ORIENTATION_VERTICAL),
NothingToShow("No history items available")
{
signal_delete_event().connect(sigc::mem_fun(*this, &BaseWindow::_OnClosed));
add_events(Gdk::KEY_PRESS_MASK);
signal_key_press_event().connect(
sigc::mem_fun(*this, &UndoWindow::_StartSearchFromKeypress));
auto accelGroup = Gtk::AccelGroup::create();
set_default_size(500, 300);
property_resizable() = true;
Menu.set_image_from_icon_name("open-menu-symbolic");
// Window specific controls
ClearHistory.property_relief() = Gtk::RELIEF_NONE;
ClearHistory.signal_clicked().connect(sigc::mem_fun(*this, &UndoWindow::_ClearHistory));
MenuPopover.Container.pack_start(ClearHistory);
MenuPopover.Container.pack_start(Separator1);
MenuPopover.Container.pack_start(HistorySizeLabel);
HistorySize.property_editable() = true;
HistorySize.property_input_purpose() = Gtk::INPUT_PURPOSE_NUMBER;
HistorySize.property_snap_to_ticks() = true;
HistorySize.property_snap_to_ticks() = true;
HistorySize.set_range(1, 250);
HistorySize.set_increments(1, 10);
HistorySize.set_digits(0);
HistorySize.set_value(DualView::Get().GetSettings().GetActionHistorySize());
MenuPopover.Container.pack_start(HistorySize);
MenuPopover.show_all_children();
MenuPopover.signal_closed().connect(
sigc::mem_fun(*this, &UndoWindow::_ApplyPrimaryMenuSettings));
Menu.set_popover(MenuPopover);
SearchButton.set_image_from_icon_name("edit-find-symbolic");
SearchButton.add_accelerator("clicked", accelGroup, GDK_KEY_f,
Gdk::ModifierType::CONTROL_MASK, Gtk::AccelFlags::ACCEL_VISIBLE);
HeaderBar.property_title() = "Latest Actions";
HeaderBar.property_show_close_button() = true;
HeaderBar.pack_end(Menu);
HeaderBar.pack_end(SearchButton);
set_titlebar(HeaderBar);
//
// Content area
//
MainContainer.property_vexpand() = true;
MainContainer.property_hexpand() = true;
Search.signal_search_changed().connect(sigc::mem_fun(*this, &UndoWindow::_SearchUpdated));
SearchBar.property_search_mode_enabled() = false;
SearchActiveBinding = Glib::Binding::bind_property(SearchButton.property_active(),
SearchBar.property_search_mode_enabled(), Glib::BINDING_BIDIRECTIONAL);
SearchBar.add(Search);
MainContainer.add(SearchBar);
QueryingDatabase.property_active() = true;
MainArea.add_overlay(QueryingDatabase);
ListScroll.set_policy(Gtk::POLICY_NEVER, Gtk::POLICY_ALWAYS);
ListScroll.property_vexpand() = true;
ListScroll.property_hexpand() = true;
ListContainer.property_vexpand() = true;
ListContainer.property_hexpand() = true;
NothingToShow.property_halign() = Gtk::ALIGN_CENTER;
NothingToShow.property_hexpand() = true;
NothingToShow.property_valign() = Gtk::ALIGN_CENTER;
NothingToShow.property_vexpand() = true;
ListContainer.set_spacing(4);
ListContainer.property_margin_top() = 4;
ListContainer.property_margin_bottom() = 4;
ListContainer.property_margin_start() = 4;
ListContainer.property_margin_end() = 4;
ListContainer.add(NothingToShow);
ListScroll.add(ListContainer);
MainArea.add(ListScroll);
MainContainer.add(MainArea);
add(MainContainer);
add_accel_group(accelGroup);
show_all_children();
_SearchUpdated();
}
UndoWindow::~UndoWindow()
{
Close();
}
void UndoWindow::_OnClose() {}
// ------------------------------------ //
bool UndoWindow::_StartSearchFromKeypress(GdkEventKey* event)
{
return SearchBar.handle_event(event);
}
// ------------------------------------ //
void UndoWindow::Clear()
{
while(!FoundActions.empty()) {
ListContainer.remove(*FoundActions.back());
FoundActions.pop_back();
}
}
// ------------------------------------ //
void UndoWindow::_SearchUpdated()
{
NothingToShow.property_visible() = false;
QueryingDatabase.property_visible() = true;
const std::string search = Search.property_text().get_value();
auto isalive = GetAliveMarker();
DualView::Get().QueueDBThreadFunction([=]() {
auto actions = DualView::Get().GetDatabase().SelectLatestDatabaseActions(search);
DualView::Get().InvokeFunction([this, isalive, actions{std::move(actions)}]() {
INVOKE_CHECK_ALIVE_MARKER(isalive);
_FinishedQueryingDB(actions);
});
});
}
// ------------------------------------ //
void UndoWindow::_FinishedQueryingDB(
const std::vector<std::shared_ptr<DatabaseAction>>& actions)
{
QueryingDatabase.property_visible() = false;
Clear();
for(const auto& action : actions) {
FoundActions.push_back(std::make_shared<ActionDisplay>(action));
ListContainer.add(*FoundActions.back());
FoundActions.back()->show();
}
if(FoundActions.empty())
NothingToShow.property_visible() = true;
}
// ------------------------------------ //
void UndoWindow::_ApplyPrimaryMenuSettings()
{
// This makes sure the up to date value is available for reading
HistorySize.update();
int newSize = static_cast<int>(HistorySize.property_value());
auto& settings = DualView::Get().GetSettings();
// TODO: it isn't the cleanest thing to do all of this manipulation here
if(newSize != settings.GetActionHistorySize()) {
settings.SetActionHistorySize(newSize);
LOG_INFO("Updating setting max history size to: " +
std::to_string(settings.GetActionHistorySize()));
DualView::Get().GetDatabase().SetMaxActionHistory(settings.GetActionHistorySize());
}
}
void UndoWindow::_ClearHistory()
{
auto dialog = Gtk::MessageDialog(*this, "Clear action history?", false,
Gtk::MESSAGE_QUESTION, Gtk::BUTTONS_YES_NO, true);
dialog.set_secondary_text("It is <b>NOT</b> possible to undo this action. This will "
"permanently delete all deleted images.",
true);
int result = dialog.run();
if(result != Gtk::RESPONSE_YES) {
return;
}
set_sensitive(false);
auto isalive = GetAliveMarker();
DualView::Get().QueueDBThreadFunction([=]() {
auto& db = DualView::Get().GetDatabase();
GUARD_LOCK_OTHER(db);
db.PurgeOldActionsUntilSpecificCount(guard, 0);
DualView::Get().InvokeFunction([this, isalive]() {
INVOKE_CHECK_ALIVE_MARKER(isalive);
Clear();
set_sensitive(true);
_SearchUpdated();
});
});
}
// ------------------------------------ //
// ActionDisplay
ActionDisplay::ActionDisplay(const std::shared_ptr<DatabaseAction>& action) :
MainBox(Gtk::ORIENTATION_HORIZONTAL), LeftSide(Gtk::ORIENTATION_VERTICAL),
RightSide(Gtk::ORIENTATION_HORIZONTAL), Edit("Edit"), UndoRedo("Loading"), Action(action)
{
if(!Action)
throw InvalidState("given nullptr for action");
// The description generation accesses the database so we do that in the background
Description.property_halign() = Gtk::ALIGN_START;
Description.property_valign() = Gtk::ALIGN_START;
// Description.property_margin_start() = 8;
Description.property_margin_top() = 3;
Description.property_label() =
"Loading description for action " + std::to_string(Action->GetID());
Description.property_max_width_chars() = 80;
Description.property_wrap() = true;
LeftSide.pack_start(Description, false, false);
ResourcePreviews.property_vexpand() = true;
ResourcePreviews.set_min_content_width(140);
ResourcePreviews.set_min_content_height(80);
ResourcePreviews.SetItemSize(LIST_ITEM_SIZE::TINY);
ContainerFrame.add(ResourcePreviews);
LeftSide.pack_end(ContainerFrame, true, true);
MainBox.pack_start(LeftSide, true, true);
Edit.property_valign() = Gtk::ALIGN_CENTER;
Edit.property_halign() = Gtk::ALIGN_CENTER;
Edit.property_sensitive() = false;
Edit.property_tooltip_text() = "Edit this action and redo it";
Edit.signal_clicked().connect(sigc::mem_fun(*this, &ActionDisplay::_EditPressed));
RightSide.pack_start(Edit, false, false);
UndoRedo.property_valign() = Gtk::ALIGN_CENTER;
UndoRedo.property_halign() = Gtk::ALIGN_CENTER;
UndoRedo.property_always_show_image() = true;
UndoRedo.property_sensitive() = false;
UndoRedo.signal_clicked().connect(sigc::mem_fun(*this, &ActionDisplay::_UndoRedoPressed));
RightSide.pack_start(UndoRedo, false, false);
RightSide.set_homogeneous(true);
RightSide.set_spacing(2);
MainBox.pack_end(RightSide, false, false);
MainBox.set_spacing(3);
add(MainBox);
show_all_children();
RefreshData();
// Start listening for changes
action->ConnectToNotifiable(this);
}
ActionDisplay::~ActionDisplay()
{
GUARD_LOCK();
ReleaseParentHooks(guard);
}
// ------------------------------------ //
void ActionDisplay::RefreshData()
{
auto isalive = GetAliveMarker();
DualView::Get().QueueDBThreadFunction([action = this->Action, this, isalive]() {
auto description = action->GenerateDescription();
auto previewItems = action->LoadPreviewItems(10);
if(action->IsDeleted()) {
description = "DELETED FROM HISTORY " + description;
}
DualView::Get().InvokeFunction(
[this, isalive, description, previewItems = std::move(previewItems)]() {
INVOKE_CHECK_ALIVE_MARKER(isalive);
_OnDataRetrieved(description, previewItems);
});
});
_UpdateStatusButtons();
}
void ActionDisplay::_OnDataRetrieved(const std::string& description,
const std::vector<std::shared_ptr<ResourceWithPreview>>& previewitems)
{
// There's a small chance that this isn't always fully up to date but this is good enough
FetchingData = false;
DualView::IsOnMainThreadAssert();
Description.property_label() = description;
if(previewitems.empty()) {
ContainerFrame.property_visible() = false;
ResourcePreviews.Clear();
} else {
ContainerFrame.property_visible() = true;
ResourcePreviews.SetShownItems(previewitems.begin(), previewitems.end());
}
}
void ActionDisplay::_UpdateStatusButtons()
{
if(Action->IsDeleted()) {
UndoRedo.property_sensitive() = false;
Edit.property_sensitive() = false;
return;
}
UndoRedo.property_sensitive() = true;
if(Action->IsPerformed()) {
UndoRedo.set_image_from_icon_name("edit-undo-symbolic");
UndoRedo.property_label() = "Undo";
} else {
UndoRedo.set_image_from_icon_name("edit-redo-symbolic");
UndoRedo.property_label() = "Redo";
}
Edit.property_sensitive() = Action->SupportsEditing();
}
// ------------------------------------ //
void ActionDisplay::_UndoRedoPressed()
{
try {
if(Action->IsPerformed()) {
if(!Action->Undo())
throw Leviathan::Exception("Unknown error in action undo");
} else {
if(!Action->Redo())
throw Leviathan::Exception("Unknown error in action redo");
}
} catch(const Leviathan::Exception& e) {
Gtk::Window* parent = dynamic_cast<Gtk::Window*>(this->get_toplevel());
if(!parent)
return;
auto dialog = Gtk::MessageDialog(*parent, "Performing the action failed", false,
Gtk::MESSAGE_ERROR, Gtk::BUTTONS_CLOSE, true);
dialog.set_secondary_text("Error: " + std::string(e.what()));
dialog.run();
}
}
void ActionDisplay::_EditPressed()
{
try {
Action->OpenEditingWindow();
} catch(const Leviathan::Exception& e) {
Gtk::Window* parent = dynamic_cast<Gtk::Window*>(this->get_toplevel());
if(!parent)
return;
auto dialog = Gtk::MessageDialog(*parent, "Can't edit this action", false,
Gtk::MESSAGE_ERROR, Gtk::BUTTONS_CLOSE, true);
dialog.set_secondary_text("Error: " + std::string(e.what()));
dialog.run();
}
}
void ActionDisplay::OnNotified(
Lock& ownlock, Leviathan::BaseNotifierAll* parent, Lock& parentlock)
{
if(FetchingData)
return;
FetchingData = true;
auto isalive = GetAliveMarker();
DualView::Get().InvokeFunction([this, isalive]() {
INVOKE_CHECK_ALIVE_MARKER(isalive);
RefreshData();
});
}
| 29.934579 | 94 | 0.659694 |
12cd0c8624857f397b3b211bbf5a91aae9415f1f | 7,310 | cpp | C++ | Jx3Full/Source/Source/Tools/GameDesignerEditor/AtlKG3DEngineProxy/IndeSource/SO3Represent/case/actionobject/krlscene.cpp | RivenZoo/FullSource | cfd7fd7ad422fd2dae5d657a18839c91ff9521fd | [
"MIT"
] | 2 | 2021-07-31T15:35:01.000Z | 2022-02-28T05:54:54.000Z | Jx3Full/Source/Source/Tools/GameDesignerEditor/AtlKG3DEngineProxy/IndeSource/SO3Represent/case/actionobject/krlscene.cpp | RivenZoo/FullSource | cfd7fd7ad422fd2dae5d657a18839c91ff9521fd | [
"MIT"
] | null | null | null | Jx3Full/Source/Source/Tools/GameDesignerEditor/AtlKG3DEngineProxy/IndeSource/SO3Represent/case/actionobject/krlscene.cpp | RivenZoo/FullSource | cfd7fd7ad422fd2dae5d657a18839c91ff9521fd | [
"MIT"
] | 5 | 2021-02-03T10:25:39.000Z | 2022-02-23T07:08:37.000Z | #include "stdafx.h"
#include "../../../SO3World/KPlayer.h"
#include "./krlscene.h"
#include "./krlcamera.h"
#include "./krlcursor.h"
#include "./krltarget.h"
#include "../../SO3Represent.h"
KRLScene::KRLScene()
: m_pRLCamera(NULL)
, m_pRLCursor(NULL)
, m_pRLTarget(NULL)
, m_dwScene(0)
, m_p3DScene(NULL)
, m_nOutputWindowID(-1)
{
}
KRLScene::~KRLScene()
{
}
int KRLScene::Init()
{
int nRetCode = false;
int nResult = false;
int nInitModelGCMgr = false;
int nInitMissileMgr = false;
int nInitCharacterMgr = false;
int nInitRidesMgr = false;
int nInitDoodadMgr = false;
int nInitCharacterGCMgr = false;
int nInitRidesGCMgr = false;
int nInitDoodadGCMgr = false;
int nInitCursor = false;
int nInitTarget = false;
nRetCode = m_ModelGCMgr.Init();
KGLOG_PROCESS_ERROR(nRetCode);
nInitModelGCMgr = true;
nRetCode = m_MissileMgr.Init();
KGLOG_PROCESS_ERROR(nRetCode);
nInitMissileMgr = true;
nRetCode = m_CharacterMgr.Init();
KGLOG_PROCESS_ERROR(nRetCode);
nInitCharacterMgr = true;
nRetCode = m_RidesMgr.Init();
KGLOG_PROCESS_ERROR(nRetCode);
nInitRidesMgr = true;
nRetCode = m_DoodadMgr.Init();
KGLOG_PROCESS_ERROR(nRetCode);
nInitDoodadMgr = true;
nRetCode = m_CharacterGCMgr.Init();
KGLOG_PROCESS_ERROR(nRetCode);
nInitCharacterGCMgr = true;
nRetCode = m_RidesGCMgr.Init();
KGLOG_PROCESS_ERROR(nRetCode);
nInitRidesGCMgr = true;
nRetCode = m_DoodadGCMgr.Init();
KGLOG_PROCESS_ERROR(nRetCode);
nInitDoodadGCMgr = true;
nRetCode = InitCursor();
KGLOG_PROCESS_ERROR(nRetCode);
nInitCursor = true;
nRetCode = InitTarget();
KGLOG_PROCESS_ERROR(nRetCode);
nInitTarget = true;
nResult = true;
Exit0:
if (!nResult)
{
if (nInitTarget)
{
ExitTarget();
nInitTarget = false;
}
if (nInitCursor)
{
ExitCursor();
nInitCursor = false;
}
if (nInitDoodadMgr)
{
m_DoodadMgr.Exit();
nInitDoodadMgr = false;
}
if (nInitCharacterMgr)
{
m_CharacterMgr.Exit();
nInitCharacterMgr = false;
}
if (nInitRidesMgr)
{
m_RidesMgr.Exit();
nInitRidesMgr = false;
}
if (nInitMissileMgr)
{
m_MissileMgr.Exit();
nInitMissileMgr = false;
}
if (nInitDoodadGCMgr)
{
m_DoodadGCMgr.Exit();
nInitDoodadGCMgr = false;
}
if (nInitCharacterGCMgr)
{
m_CharacterGCMgr.Exit();
nInitCharacterGCMgr = false;
}
if (nInitRidesGCMgr)
{
m_RidesGCMgr.Exit();
nInitRidesGCMgr = false;
}
if (nInitModelGCMgr)
{
m_ModelGCMgr.Exit();
nInitModelGCMgr = false;
}
}
return nResult;
}
void KRLScene::Exit()
{
ExitTarget();
ExitCursor();
m_DoodadMgr.Exit();
m_CharacterMgr.Exit();
m_RidesMgr.Exit();
m_MissileMgr.Exit();
m_DoodadGCMgr.Exit();
m_CharacterGCMgr.Exit();
m_RidesGCMgr.Exit();
m_ModelGCMgr.Exit();
}
BOOL KRLScene::Reset()
{
int nRetCode = false;
nRetCode = m_CharacterMgr.Reset();
KGLOG_PROCESS_ERROR(nRetCode);
nRetCode = m_RidesMgr.Reset();
KGLOG_PROCESS_ERROR(nRetCode);
nRetCode = m_DoodadMgr.Reset();
KGLOG_PROCESS_ERROR(nRetCode);
nRetCode = m_CharacterGCMgr.Reset();
KGLOG_PROCESS_ERROR(nRetCode);
nRetCode = m_RidesGCMgr.Reset();
KGLOG_PROCESS_ERROR(nRetCode);
nRetCode = m_DoodadGCMgr.Reset();
KGLOG_PROCESS_ERROR(nRetCode);
nRetCode = m_MissileMgr.Reset();
KGLOG_PROCESS_ERROR(nRetCode);
nRetCode = m_ModelGCMgr.Reset();
KGLOG_PROCESS_ERROR(nRetCode);
return TRUE;
Exit0:
return FALSE;
}
BOOL KRLScene::Activate(double fTime, double fTimeLast, DWORD dwGameLoop, BOOL bFrame)
{
m_SkillEffectResult.Activate(fTime, fTimeLast, dwGameLoop, bFrame);
m_MissileMgr.Activate(fTime, fTimeLast, dwGameLoop, bFrame);
m_CharacterMgr.Activate(fTime, fTimeLast, dwGameLoop, bFrame);
m_RidesMgr.Activate(fTime, fTimeLast, dwGameLoop, bFrame);
m_DoodadMgr.Activate(fTime, fTimeLast, dwGameLoop, bFrame);
m_CharacterGCMgr.Activate(fTime, fTimeLast, dwGameLoop, bFrame);
m_RidesGCMgr.Activate(fTime, fTimeLast, dwGameLoop, bFrame);
m_DoodadGCMgr.Activate(fTime, fTimeLast, dwGameLoop, bFrame);
if (m_pRLCamera)
m_pRLCamera->UpdateLocal(fTime, fTimeLast, dwGameLoop, bFrame);
if (m_pRLCursor)
m_pRLCursor->Update(fTime, fTimeLast, dwGameLoop, bFrame);
if (m_pRLTarget)
m_pRLTarget->Update(fTime, fTimeLast, dwGameLoop, bFrame);
m_ModelGCMgr.Activate(fTime, fTimeLast, dwGameLoop, bFrame);
return TRUE;
}
BOOL KRLScene::InitCamera()
{
HRESULT hr = E_FAIL;
KRLCamera* pCamera = NULL;
IKG3DScene* p3DScene = NULL;
IKG3DCamera* p3DCamera = NULL;
KG_PROCESS_SUCCESS(m_p3DScene == NULL);
ASSERT(m_pRLCamera == NULL);
p3DCamera = m_p3DScene->GetCurrentCamera();
KG_PROCESS_SUCCESS(p3DCamera == NULL);
m_pRLCamera = new(std::nothrow) KRLCamera;
KGLOG_PROCESS_ERROR(m_pRLCamera);
hr = m_pRLCamera->SetCamera(p3DCamera, m_p3DScene);
KGLOG_COM_PROCESS_ERROR(hr);
Exit1:
return TRUE;
Exit0:
ExitCamera();
return FALSE;
}
void KRLScene::ExitCamera()
{
SAFE_DELETE(m_pRLCamera);
}
BOOL KRLScene::InitCursor()
{
HRESULT hr = E_FAIL;
KG_PROCESS_SUCCESS(m_p3DScene == NULL);
ASSERT(m_pRLCursor == NULL);
m_pRLCursor = new(std::nothrow) KRLCursor;
KGLOG_PROCESS_ERROR(m_pRLCursor);
hr = m_pRLCursor->Init(this);
KGLOG_COM_PROCESS_ERROR(hr);
hr = m_pRLCursor->Hide();
KGLOG_COM_PROCESS_ERROR(hr);
Exit1:
return TRUE;
Exit0:
ExitCursor();
return FALSE;
}
void KRLScene::ExitCursor()
{
HRESULT hr = E_FAIL;
if (m_pRLCursor)
{
hr = m_pRLCursor->Exit();
KGLOG_COM_CHECK_ERROR(hr);
SAFE_DELETE(m_pRLCursor);
}
}
BOOL KRLScene::InitTarget()
{
HRESULT hr = E_FAIL;
KG_PROCESS_SUCCESS(m_p3DScene == NULL);
ASSERT(m_pRLTarget == NULL);
m_pRLTarget = new(std::nothrow) KRLTarget;
KGLOG_PROCESS_ERROR(m_pRLTarget);
hr = m_pRLTarget->Init(this);
KGLOG_COM_PROCESS_ERROR(hr);
hr = m_pRLTarget->Hide();
KGLOG_COM_PROCESS_ERROR(hr);
Exit1:
return TRUE;
Exit0:
ExitTarget();
return FALSE;
}
void KRLScene::ExitTarget()
{
HRESULT hr = E_FAIL;
if (m_pRLTarget)
{
hr = m_pRLTarget->Exit();
KGLOG_COM_CHECK_ERROR(hr);
SAFE_DELETE(m_pRLTarget);
}
}
KRLDoodad* GetRLDoodad(DWORD dwDoodad)
{
KDoodad* pDoodad = GetDoodad(dwDoodad);
return reinterpret_cast<KRLDoodad*>(pDoodad ? pDoodad->m_pRepresentObject : NULL);
}
KRLCharacter* GetRLCharacter(DWORD dwCharacter)
{
KRLCharacter* pRLCharacter = NULL;
if (IS_PLAYER(dwCharacter))
{
KPlayer* pPlayer = GetPlayer(dwCharacter);
pRLCharacter = reinterpret_cast<KRLCharacter*>(pPlayer ? pPlayer->m_pRepresentObject : NULL);
}
else
{
KNpc* pNpc = GetNpc(dwCharacter);
pRLCharacter = reinterpret_cast<KRLCharacter*>(pNpc ? pNpc->m_pRepresentObject : NULL);
}
return pRLCharacter;
}
| 20.19337 | 99 | 0.657045 |
12d6710714f7de44b43a998ec1f72793984562dc | 367 | hpp | C++ | library/ATF/tagCONTROLINFO.hpp | lemkova/Yorozuya | f445d800078d9aba5de28f122cedfa03f26a38e4 | [
"MIT"
] | 29 | 2017-07-01T23:08:31.000Z | 2022-02-19T10:22:45.000Z | library/ATF/tagCONTROLINFO.hpp | kotopes/Yorozuya | 605c97d3a627a8f6545cc09f2a1b0a8afdedd33a | [
"MIT"
] | 90 | 2017-10-18T21:24:51.000Z | 2019-06-06T02:30:33.000Z | library/ATF/tagCONTROLINFO.hpp | kotopes/Yorozuya | 605c97d3a627a8f6545cc09f2a1b0a8afdedd33a | [
"MIT"
] | 44 | 2017-12-19T08:02:59.000Z | 2022-02-24T23:15:01.000Z | // This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually
#pragma once
#include <common/common.h>
#include <HACCEL__.hpp>
START_ATF_NAMESPACE
struct tagCONTROLINFO
{
unsigned int cb;
HACCEL__ *hAccel;
unsigned __int16 cAccel;
unsigned int dwFlags;
};
END_ATF_NAMESPACE
| 21.588235 | 108 | 0.694823 |
12d841fe91ab05fa85fe36eaffd84ab7a5a0861c | 13,129 | cpp | C++ | processData.cpp | npthinh1996/DSA172A01 | e487ccaac426eae029aaf00c7414cce82bebc319 | [
"MIT"
] | null | null | null | processData.cpp | npthinh1996/DSA172A01 | e487ccaac426eae029aaf00c7414cce82bebc319 | [
"MIT"
] | null | null | null | processData.cpp | npthinh1996/DSA172A01 | e487ccaac426eae029aaf00c7414cce82bebc319 | [
"MIT"
] | null | null | null | /*
* =========================================================================================
* Name : processData.cpp
* Description : student code for Assignment 1 - Data structures and Algorithms - Spring 2018
* =========================================================================================
*/
#include "requestLib.h"
#include "dbLib.h"
/// Initialize and Finalize any global data that you use in the program
bool initVGlobalData(void** pGData) {
// TODO: allocate global data if you think it is necessary.
/// pGData contains the address of a pointer. You should allocate data for the global data
/// and then assign its address to *pGData
return true;
}
void releaseVGlobalData(void* pGData) {
// TODO: release the data if you finish using it
}
bool processRequest(VRequest& request, L1List<VRecord>& recList, void* pGData) {
// TODO: Your code comes here
/// NOTE: The output of the request will be printed on one line
/// end by the end-line '\n' character.
string req = request.code;
cout<<req<<": ";
// Tính số lượng thiết bị trong database
if(req == "CNV"){
int idx, s = 0;
int size = recList.getSize();
char* arr[size];
for(int i = 0; i < size; i++){
idx = 0;
char* tmp = recList.at(i).id;
for(int j = 0; j < s; j++){
if(strcmp(arr[j], tmp) == 0){
break;
}
idx++;
}
if(idx == s){
arr[s] = tmp;
s++;
}
}
cout<<s<<endl;
}
// Tìm thiết bị được lưu trữ đầu tiên
if(req == "VFF"){
cout<<recList.at(0).id<<endl;
}
// Tìm thiết bị được lưu trữ cuối cùng
if(req == "VFL"){
int idx, s = 0;
int size = recList.getSize();
char* arr[size];
for(int i = 0; i < size; i++){
idx = 0;
char* tmp = recList.at(i).id;
for(int j = 0; j < s; j++){
if(strcmp(arr[j], tmp) == 0){
break;
}
idx++;
}
if(idx == s){
arr[s] = tmp;
s++;
}
}
cout<<arr[s-1]<<endl;
}
// Tìm tọa độ y được lưu trữ đầu tiên của thiết bị <ID>
if(req.substr(0,3) == "VFY"){
int i = 0;
int size = recList.getSize();
string tmp = req.substr(3,req.length() - 3);
while(i < size && tmp != recList.at(i).id){
i++;
}
if(i != size) cout<<recList.at(i).y<<endl;
else cout<<"not found!"<<endl;
}
// Tìm tọa độ x được lưu trữ đầu tiên của thiết bị <ID>
if(req.substr(0,3) == "VFX"){
int i = 0;
int size = recList.getSize();
string tmp = req.substr(3,req.length() - 3);
while(i < size && tmp != recList.at(i).id){
i++;
}
if(i != size) cout<<recList.at(i).x<<endl;
else cout<<"not found!"<<endl;
}
// Tìm tọa độ y được lưu trữ cuối cùng của thiết bị <ID>
if(req.substr(0,3) == "VLY"){
int i = recList.getSize() - 1;
string tmp = req.substr(3,req.length() - 3);
while(i >= 0 && tmp != recList.at(i).id){
i--;
}
if(i != -1) cout<<recList.at(i).y<<endl;
else cout<<"not found!"<<endl;
}
// Tìm tọa độ x được lưu trữ cuối cùng của thiết bị <ID>
if(req.substr(0,3) == "VLX"){
int i = recList.getSize() - 1;
string tmp = req.substr(3,req.length() - 3);
while(i >= 0 && tmp != recList.at(i).id){
i--;
}
if(i != -1) cout<<recList.at(i).x<<endl;
else cout<<"not found!"<<endl;
}
// Tìm thời điểm bắt đầu lưu trữ của thiết bị <ID>
if(req.substr(0,3) == "VFT"){
int i = 0;
int size = recList.getSize();
string tmp = req.substr(3,req.length() - 3);
while(i < size && tmp != recList.at(i).id){
i++;
}
if(i != size){
char* des = new char();
strPrintTime(des, recList.at(i).timestamp);
cout<<des<<endl;
}
else cout<<"not found!"<<endl;
}
// Tìm thời điểm kết thúc lưu trữ của thiết bị <ID>
if(req.substr(0,3) == "VLT"){
int i = recList.getSize() - 1;
string tmp = req.substr(3,req.length() - 3);
while(i >= 0 && tmp != recList.at(i).id){
i--;
}
if(i != -1){
char* des = new char();
strPrintTime(des, recList.at(i).timestamp);
cout<<des<<endl;
}
else cout<<"not found!"<<endl;
}
// Tính số lượng record của thiết bị <ID>
if(req.substr(0,3) == "VCR"){
int k = 0;
int size = recList.getSize();
string tmp = req.substr(3,req.length() - 3);
for(int i = 0; i < size; i++){
if(tmp == recList.at(i).id) k++;
}
if(k != 0) cout<<k<<endl;
else cout<<"not found!"<<endl;
}
// Tính độ dài hành trình của thiết bị <ID>
if(req.substr(0,3) == "VCL"){
int i = 0;
int size = recList.getSize();
double x, y, k = 0;
string tmp = req.substr(3,req.length() - 3);
while(i < size && tmp != recList.at(i).id){
i++;
}
if(i != size){
x = recList.at(i).x;
y = recList.at(i).y;
}
for(i++; i < size; i++){
if(tmp == recList.at(i).id){
k += distanceVR(y, x, recList.at(i).y, recList.at(i).x);
x = recList.at(i).x;
y = recList.at(i).y;
}
}
cout<<k<<endl;
}
// Tính thời gian di chuyển của thiết bị <ID>
if(req.substr(0,3) == "VMT"){
int t = 0, i = 0;
int size = recList.getSize();
time_t times;
double x, y;
string tmp = req.substr(3,req.length() - 3);
while(i < size && tmp != recList.at(i).id){
i++;
}
if(i != size){
x = recList.at(i).x;
y = recList.at(i).y;
times = recList.at(i).timestamp;
}
for(i++; i < size; i++){
if(tmp == recList.at(i).id){
if(distanceVR(y, x, recList.at(i).y, recList.at(i).x) > 0.005){
t += recList.at(i).timestamp - times;
}
x = recList.at(i).x;
y = recList.at(i).y;
times = recList.at(i).timestamp;
}
}
cout<<t<<endl;
}
// Tìm điểm dừng đầu tiên của thiết bị <ID>, xuất (x y)
if(req.substr(0,3) == "VFS"){
int t = 0, i = 0;
int size = recList.getSize();
double x, y;
string tmp = req.substr(3,req.length() - 3);
while(i < size && tmp != recList.at(i).id){
i++;
}
if(i != size){
x = recList.at(i).x;
y = recList.at(i).y;
}
for(i++; i < size; i++){
if(tmp == recList.at(i).id){
if(distanceVR(y, x, recList.at(i).y, recList.at(i).x) < 0.005){
t = 1;
break;
}
x = recList.at(i).x;
y = recList.at(i).y;
}
}
if(t == 1) cout<<"("<<x<<", "<<y<<")"<<endl;
else cout<<"non stop!"<<endl;
}
// Tìm điểm dừng cuối cùng của thiết bị <ID>
if(req.substr(0,3) == "VLS"){
int t = 0;
int i = recList.getSize() - 1;
double x, y;
string tmp = req.substr(3,req.length() - 3);
while(i >= 0 && tmp != recList.at(i).id){
i--;
}
if(i != -1){
x = recList.at(i).x;
y = recList.at(i).y;
}
for(i--; i >= 0; i--){
if(tmp == recList.at(i).id){
if(distanceVR(y, x, recList.at(i).y, recList.at(i).x) < 0.005){
x = recList.at(i).x;
y = recList.at(i).y;
t = 1;
break;
}
x = recList.at(i).x;
y = recList.at(i).y;
}
}
if(t == 1) cout<<"("<<x<<", "<<y<<")"<<endl;
else cout<<"non stop!"<<endl;
}
// Tìm thời gian dừng lâu nhất của thiết bị <ID>
if(req.substr(0,3) == "VMS"){
int t = 0, i = 0, max = 0;
int size = recList.getSize();
time_t times;
double x, y;
string tmp = req.substr(3,req.length() - 3);
while(i < size && tmp != recList.at(i).id){
i++;
}
if(i != size){
x = recList.at(i).x;
y = recList.at(i).y;
times = recList.at(i).timestamp;
}
for(i++; i < size; i++){
if(tmp == recList.at(i).id){
if(distanceVR(y, x, recList.at(i).y, recList.at(i).x) < 0.005){
t = recList.at(i).timestamp - times;
if(t > max) max = t;
}
x = recList.at(i).x;
y = recList.at(i).y;
times = recList.at(i).timestamp;
}
}
if(max != 0) cout<<max<<endl;
else cout<<"non stop!"<<endl;
}
// Tìm khoảng cách trung bình giữa 2 lần thu thập dữ liệu của thiết bị <ID>
if(req.substr(0,3) == "VAS"){
int i = 0, j = 0;
int size = recList.getSize();
double x, y, k = 0;
string tmp = req.substr(3,req.length() - 3);
while(i < size && tmp != recList.at(i).id){
i++;
}
if(i != size){
x = recList.at(i).x;
y = recList.at(i).y;
}
for(i++; i < size; i++){
if(tmp == recList.at(i).id){
k += distanceVR(y, x, recList.at(i).y, recList.at(i).x);
x = recList.at(i).x;
y = recList.at(i).y;
j++;
}
}
if(j != 0) cout<<(k/j)*1000<<" meter"<<endl;
else cout<<0<<endl;
}
// TODO: Tìm thời lượng dừng lâu nhất của tất cả các thiết bị
if(req == "MST"){
}
// Tính số lượng record trong database
if(req == "CNR"){
cout<<recList.getSize()<<endl;
}
// Tìm thiết bị có số lượng record nhiều nhất
if(req == "MRV"){
int idx, s = 0, max = 0;
int size = recList.getSize();
char* arr[size];
int count[size];
for(int i = 0; i < size; i++){
idx = 0;
char* tmp = recList.at(i).id;
for(int j = 0; j < s; j++){
if(strcmp(arr[j], tmp) == 0){
count[j] += 1;
break;
}
idx++;
}
if(idx == s){
arr[s] = tmp;
count[s] = 1;
s++;
}
}
for(int i = 0; i < s; i++){
if(max < count[i]){
max = count[i];
idx = i;
}
}
cout<<arr[idx]<<endl;
}
// Tìm thiết bị có số lượng record ít nhất
if(req == "LRV"){
int idx, s = 0, max = 0;
int size = recList.getSize();
char* arr[size];
int count[size];
for(int i = 0; i < size; i++){
idx = 0;
char* tmp = recList.at(i).id;
for(int j = 0; j < s; j++){
if(strcmp(arr[j], tmp) == 0){
count[j] += 1;
break;
}
idx++;
}
if(idx == s){
arr[s] = tmp;
count[s] = 1;
s++;
}
}
for(int i = 0; i < s; i++){
if(count[i] == 1){
idx = i;
break;
}
}
cout<<arr[idx]<<endl;
}
// TODO: Tìm thiết bị có tổng thời gian di chuyển lâu nhất
if(req == "MTV"){
}
// TODO: Tìm thiết bị có vận tốc di chuyển trung bình nhanh nhất
if(req == "MVV"){
}
// TODO: Tính số lượng thiết bị luôn di chuyển và không dừng
if(req == "CNS"){
}
// TODO: Tính khoảng cách trung bình khi thu thập dữ liệu của tất cả các thiết bị
if(req == "CAS"){
}
// TODO: Tìm thiết bị có hành trình dài nhất
if(req == "LPV"){
}
// TODO: Tìm thiết bị có hành trình ngắn nhất
if(req == "SPV"){
}
// Xóa các record của thiết bị <ID>
if(req.substr(0,3) == "RVR"){
int i = 0;
int size = recList.getSize();
string tmp = req.substr(3,req.length() - 3);
while(i < size && tmp != recList.at(i).id){
i++;
}
if(i != size){
recList.remove(i);
size = recList.getSize();
for(i; i < size; i++){
if(tmp == recList.at(i).id){
recList.remove(i);
size = recList.getSize();
}
}
cout<<"success!"<<endl;
} else cout<<"not found!"<<endl;
}
return true;
}
| 30.891765 | 94 | 0.413436 |
12da3d353b84c8f6e8db0831ff11a4ef89ac2d7c | 751 | hpp | C++ | NINJA/TreeBuilder.hpp | jebrosen/NINJA | db4f4216fc402e73ae16be65a1fc8e5ecfeef79b | [
"MIT"
] | null | null | null | NINJA/TreeBuilder.hpp | jebrosen/NINJA | db4f4216fc402e73ae16be65a1fc8e5ecfeef79b | [
"MIT"
] | null | null | null | NINJA/TreeBuilder.hpp | jebrosen/NINJA | db4f4216fc402e73ae16be65a1fc8e5ecfeef79b | [
"MIT"
] | null | null | null | /*
* TreeBuilder.hpp
*
* Created on: Jan 24, 2016
* Author: michel
*/
#ifndef TREEBUILDER_HPP
#define TREEBUILDER_HPP
#include <string>
#include <vector>
#include "TreeNode.hpp"
class TreeBuilder{
public:
TreeBuilder (std::string** names, int** distances, int namesSize);
~TreeBuilder();
TreeNode* build ();
static bool distInMem;
static bool rebuildStepsConstant;
static float rebuildStepRatio;
static int rebuildSteps;
static const int clustCnt = 30;
static int candidateIters;
static int verbose;
int K;
protected:
std::string** names;
int** D;
long int *R;
TreeNode **nodes;
int *redirect;
int *nextActiveNode;
int *prevActiveNode;
int firstActiveNode;
void finishMerging();
};
#endif
| 16.326087 | 68 | 0.695073 |
12dc67b55f9c7450ed3bcec0f1c28b951e5b360f | 2,072 | cpp | C++ | tgc/src/compressed_references.cpp | IntelLabs/IFLC-LIB | 4317e191081cd48ad373ea41874d90830594ca4b | [
"Apache-2.0",
"BSD-2-Clause"
] | 21 | 2017-04-12T21:31:52.000Z | 2017-10-14T16:11:19.000Z | tgc/src/compressed_references.cpp | csabahruska/flrc-lib | c2bccdbeecf6a0128988ac93e80f599ff2bfd5a8 | [
"Apache-2.0",
"BSD-2-Clause"
] | 2 | 2017-04-16T21:21:38.000Z | 2020-02-03T15:31:24.000Z | tgc/src/compressed_references.cpp | csabahruska/flrc-lib | c2bccdbeecf6a0128988ac93e80f599ff2bfd5a8 | [
"Apache-2.0",
"BSD-2-Clause"
] | 6 | 2017-04-13T13:26:12.000Z | 2019-11-09T19:44:28.000Z | /*
* 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 AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "tgc/gc_header.h"
#include "tgc/remembered_set.h"
#include "tgc/compressed_references.h"
#ifndef DISALLOW_RUNTIME_SELECTION_OF_COMPRESSED_REFERENCES
bool gc_references_are_compressed = false;
#endif // !DISALLOW_RUNTIME_SELECTION_OF_COMPRESSED_REFERENCES
void *Slot::cached_heap_base = NULL;
void *Slot::cached_heap_ceiling = NULL;
// This function returns TRUE if references within objects and vector elements
// will be treated by GC as uint32 offsets rather than raw pointers.
GCEXPORT(Boolean, gc_supports_compressed_references) ()
{
#ifdef DISALLOW_RUNTIME_SELECTION_OF_COMPRESSED_REFERENCES
return gc_references_are_compressed ? TRUE : FALSE;
#else // !DISALLOW_RUNTIME_SELECTION_OF_COMPRESSED_REFERENCES
return orp_references_are_compressed();
#endif // !DISALLOW_RUNTIME_SELECTION_OF_COMPRESSED_REFERENCES
}
| 49.333333 | 118 | 0.801641 |
12dcb012f3f002228dd0a921c0ad4641999309d4 | 235 | cpp | C++ | src/queries/comparer.cpp | wojtex/dragon-cxx | 3aa4a200d2e9826d9ab9d8dd5823891fbed9b563 | [
"MIT"
] | null | null | null | src/queries/comparer.cpp | wojtex/dragon-cxx | 3aa4a200d2e9826d9ab9d8dd5823891fbed9b563 | [
"MIT"
] | null | null | null | src/queries/comparer.cpp | wojtex/dragon-cxx | 3aa4a200d2e9826d9ab9d8dd5823891fbed9b563 | [
"MIT"
] | null | null | null | #include "comparer.hpp"
#include "../ast/source.hpp"
namespace dragon
{
void Comparer::visit ( Identifier &n )
{
if(auto tt = arg.is<Identifier>())
{
ret = (tt->text == n.text);
return;
}
ret = false;
return;
}
} | 14.6875 | 40 | 0.582979 |
12e04e64918cc8d28817aad7ffa7a06225d5a7f7 | 2,322 | cpp | C++ | Fw/Cmd/CmdString.cpp | SSteve/fprime | 12c478bd79c2c4ba2d9f9e634e47f8b6557c54a8 | [
"Apache-2.0"
] | 5 | 2019-10-22T03:41:02.000Z | 2022-01-16T12:48:31.000Z | Fw/Cmd/CmdString.cpp | JPLOpenSource/fprime-sw-Rel1.0 | 18364596c24fa369c938ef8758e5aa945ecc6a9b | [
"Apache-2.0"
] | 42 | 2021-06-10T23:31:10.000Z | 2021-06-25T00:35:31.000Z | Fw/Cmd/CmdString.cpp | JPLOpenSource/fprime-sw-Rel1.0 | 18364596c24fa369c938ef8758e5aa945ecc6a9b | [
"Apache-2.0"
] | 3 | 2019-01-01T18:44:37.000Z | 2019-08-01T01:19:39.000Z | #include <Fw/Types/StringType.hpp>
#include <Fw/Types/BasicTypes.hpp>
#include <Fw/Cmd/CmdString.hpp>
#include <Fw/Types/Assert.hpp>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
namespace Fw {
CmdStringArg::CmdStringArg(const char* src) : StringBase() {
this->copyBuff(src,this->getCapacity());
}
CmdStringArg::CmdStringArg(const StringBase& src) : StringBase() {
this->copyBuff(src.toChar(),this->getCapacity());
}
CmdStringArg::CmdStringArg(const CmdStringArg& src) : StringBase() {
this->copyBuff(src.m_buf,this->getCapacity());
}
CmdStringArg::CmdStringArg(void) : StringBase() {
this->m_buf[0] = 0;
}
CmdStringArg::~CmdStringArg(void) {
}
NATIVE_UINT_TYPE CmdStringArg::length(void) const {
return strnlen(this->m_buf,sizeof(this->m_buf));
}
const char* CmdStringArg::toChar(void) const {
return this->m_buf;
}
void CmdStringArg::copyBuff(const char* buff, NATIVE_UINT_TYPE size) {
FW_ASSERT(buff);
// check for self copy
if (buff != this->m_buf) {
(void)strncpy(this->m_buf,buff,size);
// NULL terminate
this->terminate(sizeof(this->m_buf));
}
}
const CmdStringArg& CmdStringArg::operator=(const CmdStringArg& other) {
this->copyBuff(other.m_buf,this->getCapacity());
return *this;
}
SerializeStatus CmdStringArg::serialize(SerializeBufferBase& buffer) const {
NATIVE_UINT_TYPE strSize = strnlen(this->m_buf,sizeof(this->m_buf));
// serialize string
return buffer.serialize((U8*)this->m_buf,strSize);
}
SerializeStatus CmdStringArg::deserialize(SerializeBufferBase& buffer) {
NATIVE_UINT_TYPE maxSize = sizeof(this->m_buf);
// deserialize string
SerializeStatus stat = buffer.deserialize((U8*)this->m_buf,maxSize);
// make sure it is null-terminated
this->terminate(maxSize);
return stat;
}
NATIVE_UINT_TYPE CmdStringArg::getCapacity(void) const {
return FW_CMD_STRING_MAX_SIZE;
}
void CmdStringArg::terminate(NATIVE_UINT_TYPE size) {
// null terminate the string
this->m_buf[size < sizeof(this->m_buf)?size:sizeof(this->m_buf)-1] = 0;
}
}
| 29.392405 | 80 | 0.639104 |
12e1ea4e39550673c30f59bd9bc947d4f9ffc50d | 1,819 | hpp | C++ | ObjectHandler/Examples/ExampleObjects/Objects/accountobject.hpp | txu2014/quantlib | 95c7d94906c30d0c3c4e0758a2ebfe2a62b075ec | [
"BSD-3-Clause"
] | null | null | null | ObjectHandler/Examples/ExampleObjects/Objects/accountobject.hpp | txu2014/quantlib | 95c7d94906c30d0c3c4e0758a2ebfe2a62b075ec | [
"BSD-3-Clause"
] | null | null | null | ObjectHandler/Examples/ExampleObjects/Objects/accountobject.hpp | txu2014/quantlib | 95c7d94906c30d0c3c4e0758a2ebfe2a62b075ec | [
"BSD-3-Clause"
] | 1 | 2022-02-24T04:54:18.000Z | 2022-02-24T04:54:18.000Z |
/*!
Copyright (C) 2004, 2005, 2006, 2007 Eric Ehlers
This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/
QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license. You should have received a
copy of the license along with this program; if not, please email
<quantlib-dev@lists.sf.net>. The license is also available online at
<http://quantlib.org/license.shtml>.
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 license for more details.
*/
#ifndef example_account_object_hpp
#define example_account_object_hpp
#include <oh/libraryobject.hpp>
#include <ExampleObjects/Library/account.hpp>
namespace AccountExample {
class AccountObject : public ObjectHandler::LibraryObject<Account> {
public:
AccountObject(
const boost::shared_ptr<ObjectHandler::ValueObject>& properties,
const boost::shared_ptr<Customer>& customer,
const Account::Type &type,
const long &number,
const double &balance,
bool permanent)
: ObjectHandler::LibraryObject<Account>(properties, permanent) {
libraryObject_ = boost::shared_ptr<Account>(
new Account(customer, type, number, balance));
}
void setBalance(const double &balance) {
libraryObject_->setBalance(balance);
}
const double &balance() {
return libraryObject_->balance();
}
std::string type() {
return libraryObject_->type();
}
};
}
#endif
| 28.873016 | 78 | 0.672347 |
12e2bbd0fd4211ed71f3ca599a3633bc077a2eee | 2,292 | hpp | C++ | code/source/util/profiling.hpp | crafn/clover | 586acdbcdb34c3550858af125e9bb4a6300343fe | [
"MIT"
] | 12 | 2015-01-12T00:19:20.000Z | 2021-08-05T10:47:20.000Z | code/source/util/profiling.hpp | crafn/clover | 586acdbcdb34c3550858af125e9bb4a6300343fe | [
"MIT"
] | null | null | null | code/source/util/profiling.hpp | crafn/clover | 586acdbcdb34c3550858af125e9bb4a6300343fe | [
"MIT"
] | null | null | null | #ifndef CLOVER_UTIL_PROFILING_HPP
#define CLOVER_UTIL_PROFILING_HPP
#include "build.hpp"
#include "util/preproc_join.hpp"
#include <thread>
// No profiling on windows due to odd crashes with mingw 4.8.2
#define PROFILING_ENABLED (ATOMIC_PTR_READWRITE == true)
namespace clover {
namespace util {
namespace detail {
struct BlockInfo {
const char* funcName;
uint32 line;
/// Don't assume that labels with same string will point to
/// the same memory - depends on compiler optimizations
const char* label;
uint64 exclusiveMemAllocs;
uint64 inclusiveMemAllocs;
};
struct BlockProfiler {
static BlockInfo createBlockInfo( const char* func,
uint32 line,
const char* label);
BlockProfiler(BlockInfo& info);
~BlockProfiler();
};
struct StackJoiner {
StackJoiner();
~StackJoiner();
};
struct StackDetacher {
StackDetacher();
~StackDetacher();
};
void setSuperThread(std::thread::id super_id);
} // detail
/// Call in main() -- we don't want to see any impl defined pre-main stuff
void tryEnableProfiling();
#if PROFILING_ENABLED
/// Should be called on system memory allocation
void profileSystemMemAlloc();
#else
inline void profileSystemMemAlloc() {};
#endif
} // util
} // clover
#if PROFILING_ENABLED
/// Same as PROFILE but with a label
#define PROFILE_(label)\
static util::detail::BlockInfo JOIN(profiler_block_info_, __LINE__)= \
util::detail::BlockProfiler::createBlockInfo( \
__PRETTY_FUNCTION__, \
__LINE__, \
label); \
util::detail::BlockProfiler JOIN(profiler_, __LINE__)(JOIN(profiler_block_info_, __LINE__))
/// Marks current block to be profiled
#define PROFILE()\
PROFILE_(nullptr)
/// Notifies profiler of a super thread
#define PROFILER_SUPER_THREAD(thread_id)\
util::detail::setSuperThread(thread_id)
/// Joins callstacks of this and super thread in current scope
#define PROFILER_STACK_JOIN()\
util::detail::StackJoiner JOIN(stack_joiner_, __LINE__)
/// Detaches callstacks of this and super thread in current scope
#define PROFILER_STACK_DETACH()\
util::detail::StackDetacher JOIN(stack_detacher_, __LINE__)
#else
#define PROFILE_(label)
#define PROFILE()
#define PROFILER_SUPER_THREAD(thread_id)
#define PROFILER_STACK_JOIN()
#define PROFILER_STACK_DETACH()
#endif
#endif // CLOVER_UTIL_PROFILING_HPP
| 23.387755 | 92 | 0.756108 |
12e58bca092d23af2cab801bee2e0b6248e5d27d | 7,949 | cpp | C++ | loginframe.cpp | mobile-pos/amp | efe4eb4fda1e6f1ad2ee6113c3bf0a9a61068763 | [
"MIT"
] | 6 | 2020-09-12T08:16:46.000Z | 2020-11-19T04:05:35.000Z | loginframe.cpp | mobile-pos/amp | efe4eb4fda1e6f1ad2ee6113c3bf0a9a61068763 | [
"MIT"
] | null | null | null | loginframe.cpp | mobile-pos/amp | efe4eb4fda1e6f1ad2ee6113c3bf0a9a61068763 | [
"MIT"
] | 2 | 2020-12-11T02:27:56.000Z | 2021-11-18T02:15:01.000Z | #include "loginframe.h"
#include <QLabel>
#include <QLineEdit>
#include <QDebug>
#include <QCryptographicHash>
#include <QMessageBox>
#include "vkeyboardex.h"
#include "datathread.h"
#include "mainwindow.h"
extern MainWindow* gWnd;
///////////////////////////////////////////////////////////
/// \brief LoginFrame::LoginFrame
/// \param parent
///
LoginFrame::LoginFrame(QWidget *parent) :
QFrame(parent)
{
this->setObjectName("loginWnd");
this->setStyleSheet("LoginFrame#loginWnd{ border-image: url(:/res/img/grass.jpg);}");
_layout = new GridLayoutEx(15, this);
_layout->setObjectName("loginArea");
_layout->setStyleSheet("#loginArea{ background: gray;}");
_layout->setCellBord(0);
//半透明设置
// _layout->setWindowFlags(Qt::FramelessWindowHint);
// _layout->setAttribute(Qt::WA_TranslucentBackground);
_layout->setWindowOpacity(0.5);
_vkb = new VKeyboardEx(this);
_vkb->setObjectName("virtualKB");
_vkb->setCellBord(0);
_vkb->setStyleSheet("#virtualKB{ background: rgb(116, 122, 131);}");
init();
}
LoginFrame::~LoginFrame()
{
}
void LoginFrame::init() {
/**
+------------------------+
| title |
| name: |
| pwd : |
|------------------------|
| OK cancel |
|------------------------|
| virtual keyboard |
+------------------------+
*/
qDebug() << "LoginFrame::init";
//1行15个单元
{
//title
{
QLabel* _l = new QLabel("", _layout);
_layout->addWidget(_l, 3, 2);
}
{
QLabel* _l = new POSLabelEx(QObject::tr("请登录"), _layout);
// _l->setStyleSheet("background-color: rgb(80, 114, 165)");
_l->setAlignment(Qt::AlignCenter);
_l->setObjectName("LoginTitle");
_layout->addWidget(_l, 10, 2);
}
{
QLabel* _l = new QLabel("", _layout);
_layout->addWidget(_l, 2, 2);
}
} {
//输入用户名
{
QLabel* _l = new POSLabelEx(QObject::tr("账号:"), _layout);
_l->setAlignment(Qt::AlignRight |Qt::AlignCenter);
_layout->addWidget(_l, 4, 2);
} {
LineEditEx* _e = new LineEditEx(_layout);
this->connect(_e, SIGNAL(focussed(QWidget*, bool)), this, SLOT(focussed(QWidget*, bool)));
_e->setPlaceholderText(QObject::tr("请输入账号"));
_e->setObjectName("LoginAccout");
_e->setText("demoroot");
_layout->addWidget(_e, 10, 2, 1000);
}
{
QLabel* _l = new QLabel("", _layout);
_layout->addWidget(_l, 1, 2);
}
}{
//输入密码
{
QLabel* _l = new POSLabelEx(QObject::tr("密码:"), _layout);
_l->setAlignment(Qt::AlignRight |Qt::AlignCenter);
_layout->addWidget(_l, 4, 2);
} {
LineEditEx* _e = new LineEditEx(_layout);
this->connect(_e, SIGNAL(focussed(QWidget*, bool)), this, SLOT(focussed(QWidget*, bool)));
_e->setEchoMode(QLineEdit::Password);
_e->setPlaceholderText(QObject::tr("请输入密码"));
_e->setObjectName("LoginPasswd");
_e->setText("1356@aiwaiter");
_layout->addWidget(_e, 10, 2, 1001);
}
{
QLabel* _l = new QLabel("", _layout);
_layout->addWidget(_l, 1, 2);
}
} {
//空行
{
QLabel* _l = new QLabel("", _layout);
_layout->addWidget(_l, 15, 1);
}
} {
{
QLabel* _l = new QLabel("", _layout);
_layout->addWidget(_l, 3, 2);
}
{
VKeyItemButton* _btn = new VKeyItemButton("OK", this, _layout);
_btn->setText(QObject::tr("点击登录"));
_btn->setStyleSheet("background-color: rgb(80, 114, 165)");
_btn->setFocus();
_layout->addWidget(_btn, 3, 2);
}
{
QLabel* _l = new QLabel("", _layout);
_layout->addWidget(_l, 3, 2);
}
{
VKeyItemButton* _btn = new VKeyItemButton("Cancel", this, _layout);
_btn->setText(QObject::tr("重置"));
_btn->setStyleSheet("background-color: rgb(80, 114, 165)");
_layout->addWidget(_btn, 3, 2);
}
{
QLabel* _l = new QLabel("", _layout);
_layout->addWidget(_l, 3, 2);
}
} {
//空一行
{
QLabel* _l = new QLabel("", _layout);
_layout->addWidget(_l, 15, 1);
}
} {
_vkb->init(0);
_vkb->hide();
}
qDebug() << "LoginFrame::init end";
}
void LoginFrame::login(bool isAdmin) {
QLabel* lab = dynamic_cast<QLabel*>( _layout->getItembyObjectName("LoginTitle") );
if(true == isAdmin) {
lab->setText(tr("请管理员登陆"));
} else {
lab->setText(tr("请登陆"));
}
this->showMaximized();
}
void LoginFrame::resizeEvent(QResizeEvent* e) {
QFrame::resizeEvent(e);
QRect rect = this->geometry();
int w = 400;
int h = 200;
QRect center( rect.width()/2 - w/2, rect.height() * 0.3 - h/2, w, h);
_layout->setRowHeight(h/10);
_layout->setGeometry(center);
QRect lrect = _layout->geometry();
_vkb->setGeometry(lrect.left() - 100, lrect.bottom() + 5, lrect.width() + 200, rect.height() -lrect.bottom() - 30);
}
void LoginFrame::onKeyDown(const QString& value) {
qDebug() << "onKeyDown: " << value;
if( "Cancel" == value) {
LineEditEx* _edit = dynamic_cast<LineEditEx*>(_layout->getItembyID(1000));
_edit->setText("");
_edit = dynamic_cast<LineEditEx*>(_layout->getItembyID(1001));
_edit->setText("");
} else if("OK" == value) {
//调用登录接口
LineEditEx* _en = dynamic_cast<LineEditEx*>(dynamic_cast<LineEditEx*>(_layout->getItembyID(1000)));
LineEditEx* _ep = dynamic_cast<LineEditEx*>(dynamic_cast<LineEditEx*>(_layout->getItembyID(1001)));
QString name = _en->text();
QString pwd = _ep->text();
if(name == "") {
_en->setPlaceholderText(QObject::tr("账号不能为空"));
return;
}
if(pwd == "") {
_en->setPlaceholderText(QObject::tr("密码不能为空"));
return;
}
QString key = name + pwd;
QString md5 = QString(QCryptographicHash::hash( key.toUtf8(),QCryptographicHash::Md5).toHex());
QVariantMap ret = DataThread::inst().login(name, md5);
// //@Task Todo for test
// ret["account"] = "r002";
// ret["id"] = 2;
if(ret.empty() || 0 != ret["code"].toInt()) {
QMessageBox::warning(this, "登录失败", QString("用户名或密码不对,请重试 或是网络异常: %1").arg(ret["msg"].toString()));
gWnd->recordPOSEvent("login", "login failed, 用户名或密码不对,请重试 或是网络异常");
return;
}
if( ret["id"].toInt() != DataThread::inst().getRestaurantInfo()["rid"].toInt()) {
QMessageBox::warning(this, "登录失败", "非本店账号不能登录");
gWnd->recordPOSEvent("login", "login failed, 非本店账号不能登录");
return;
}
DataThread::inst().setLogin(ret["account"].toString(), ret);
_ep->setText("");
this->hide();
gWnd->Home();
gWnd->updateLoginInfo();
//
if(0 != DataThread::inst().updateTables2Cloud()) {
QMessageBox::warning(this, "出错", "更新桌台信息到云端失败,可能影响到扫码点餐");
}
gWnd->recordPOSEvent("login", "login OK");
}
}
void LoginFrame::onVKeyDown(const QString& value) {
qDebug() << "onVKeyDown: " << value;
if("OK" == value) {
}
}
void LoginFrame::focussed(QWidget* _this, bool hasFocus) {
if(true == hasFocus) {
LineEditEx* _edit = dynamic_cast<LineEditEx*>(_this);
// _edit->setStyleSheet("background-color: red(255, 255, 255)");
_vkb->setTarget( _edit );
_vkb->show();
} else {
_vkb->hide();
}
}
| 29.550186 | 119 | 0.525349 |
12ea62d0db69b61036a551c835420cfeb49ab506 | 3,229 | cxx | C++ | modules/ardrivo/test/Servo.cxx | platisd/group-09 | a905c8c6409c0a3d73f53884e167571d8f482667 | [
"Apache-2.0"
] | 4 | 2020-06-02T16:01:10.000Z | 2021-10-17T22:23:26.000Z | modules/ardrivo/test/Servo.cxx | platisd/group-09 | a905c8c6409c0a3d73f53884e167571d8f482667 | [
"Apache-2.0"
] | 76 | 2020-04-03T09:15:45.000Z | 2020-12-17T16:55:14.000Z | modules/ardrivo/test/Servo.cxx | platisd/group-09 | a905c8c6409c0a3d73f53884e167571d8f482667 | [
"Apache-2.0"
] | 1 | 2020-06-02T15:52:31.000Z | 2020-06-02T15:52:31.000Z | #include <catch2/catch.hpp>
#include <range/v3/algorithm/for_each.hpp>
#include "BoardDataDef.hxx"
#include "Entrypoint.hxx"
#include "Servo.h"
static void init_fake() {
if(board_data)
(delete board_data), board_data = nullptr;
if(board_info)
(delete board_info), board_info = nullptr;
auto loc_board_data = std::make_unique<BoardData>();
loc_board_data->interrupt_mut = std::make_unique<std::recursive_mutex>();
loc_board_data->pwm_values = std::vector<std::atomic_uint8_t>(255);
auto loc_board_info = std::make_unique<BoardInfo>();
loc_board_info->pins_caps.resize(255);
ranges::for_each(loc_board_info->pins_caps, [](PinCapability& pin) { pin.pwm_able = true; });
loc_board_info->pins_caps[2].pwm_able = false;
init(loc_board_data.release(), loc_board_info.release());
}
bool writtenSuccessful(Servo currentServo, int attchedPin, int expectWrittenValue) {
return currentServo.read() == expectWrittenValue && board_data->pwm_values[attchedPin].load() == expectWrittenValue;
}
TEST_CASE("Attach pin", "[Attach]") {
init_fake();
Servo test;
test.attach(1);
REQUIRE(test.attached());
// Attach pin out of the boundary
test.detach();
board_data->silence_errors = true;
test.attach(500);
REQUIRE(!test.attached());
// Attach PWM-unable pin
test.attach(2);
REQUIRE(!test.attached());
board_data->silence_errors = false;
REQUIRE_THROWS_AS(test.attach(500), std::runtime_error);
REQUIRE_THROWS_AS(test.attach(2), std::runtime_error);
}
TEST_CASE("Attached", "[Attached]") {
init_fake();
Servo test;
REQUIRE(!test.attached());
test.attach(1);
REQUIRE(test.attached());
}
TEST_CASE("Detach pin", "[Detach]") {
init_fake();
Servo test;
test.attach(1);
REQUIRE(test.attached());
test.detach();
REQUIRE(!test.attached());
}
TEST_CASE("Write servo value", "[Write]") {
init_fake();
Servo test;
// Unattached case
test.write(100);
REQUIRE(test.read() == -1);
// Attached cases
test.attach(1);
REQUIRE(test.attached());
test.write(100); // Inside boundary
REQUIRE(writtenSuccessful(test, 1, 100));
test.write(-100); // Lower than boundary
REQUIRE(writtenSuccessful(test, 1, 0));
test.write(1000); // Higher than boundary
REQUIRE(writtenSuccessful(test, 1, 180));
}
TEST_CASE("Write servo value as MicroSeconds", "[WriteMicroseconds]") {
init_fake();
Servo test;
// Unattached case
test.write(1500);
REQUIRE(test.read() == -1);
// Attached cases
test.attach(1);
REQUIRE(test.attached());
test.writeMicroseconds(1500); // Inside boundary
REQUIRE(writtenSuccessful(test, 1, 89));
test.writeMicroseconds(500); // Lower than boundary
REQUIRE(writtenSuccessful(test, 1, 0));
test.writeMicroseconds(2500); // Higher than boundary
REQUIRE(writtenSuccessful(test, 1, 179));
}
TEST_CASE("Read servo value", "[Read]") {
init_fake();
Servo test;
// Unattached case
test.write(90);
REQUIRE(test.read() == -1);
// Attached case
test.attach(1);
REQUIRE(test.attached());
test.write(90);
REQUIRE(writtenSuccessful(test, 1, 90));
}
| 29.09009 | 120 | 0.663983 |
12eb3ee17b7645d9c852af55f8621a97b515b1e0 | 4,197 | cpp | C++ | hihope_neptune-oh_hid/00_src/v0.1/base/global/i18n_lite/frameworks/i18n/src/date_time_data.cpp | dawmlight/vendor_oh_fun | bc9fb50920f06cd4c27399f60076f5793043c77d | [
"Apache-2.0"
] | 1 | 2022-02-15T08:51:55.000Z | 2022-02-15T08:51:55.000Z | hihope_neptune-oh_hid/00_src/v0.1/base/global/i18n_lite/frameworks/i18n/src/date_time_data.cpp | dawmlight/vendor_oh_fun | bc9fb50920f06cd4c27399f60076f5793043c77d | [
"Apache-2.0"
] | null | null | null | hihope_neptune-oh_hid/00_src/v0.1/base/global/i18n_lite/frameworks/i18n/src/date_time_data.cpp | dawmlight/vendor_oh_fun | bc9fb50920f06cd4c27399f60076f5793043c77d | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2021 Huawei Device Co., 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 "date_time_data.h"
using namespace OHOS::I18N;
using namespace std;
DateTimeData::DateTimeData(const string &amPmMarkers, const char *sepAndHour, const int size)
{
this->amPmMarkers = amPmMarkers;
// size must >= 2, The first 2 element of sepAndHour need to be extracted, the first element
// is the time separator and the second is the default hour.
if (sepAndHour && size >= 2) {
timeSeparator = sepAndHour[0];
defaultHour = sepAndHour[1];
}
}
/**
* split str with "_"
*/
string DateTimeData::Parse(const string &str, int32_t count)
{
if (str.empty()) {
return "";
}
int length = str.size();
int tempCount = 0;
int ind = 0;
while ((ind < length) && (tempCount < count)) {
if (str.at(ind) == '_') {
++tempCount;
}
++ind;
}
int last = ind;
--ind;
while (last < length) {
if (str.at(last) == '_') {
break;
}
++last;
}
if (last - ind - 1 <= 0) {
return "";
}
return str.substr(ind + 1, last - ind - 1);
}
string DateTimeData::GetMonthName(int32_t index, DateTimeDataType type)
{
if ((index < 0) || (index >= MONTH_SIZE)) {
return "";
}
switch (type) {
case DateTimeDataType::FORMAT_ABBR: {
return Parse(formatAbbreviatedMonthNames, index);
}
case DateTimeDataType::FORMAT_WIDE: {
return Parse(formatWideMonthNames, index);
}
case DateTimeDataType::STANDALONE_ABBR: {
return Parse(standaloneAbbreviatedMonthNames, index);
}
default: {
return Parse(standaloneWideMonthNames, index);
}
}
}
string DateTimeData::GetDayName(int32_t index, DateTimeDataType type)
{
if ((index < 0) || (index >= DAY_SIZE)) {
return "";
}
switch (type) {
case DateTimeDataType::FORMAT_ABBR: {
return Parse(formatAbbreviatedDayNames, index);
}
case DateTimeDataType::FORMAT_WIDE: {
return Parse(formatWideDayNames, index);
}
case DateTimeDataType::STANDALONE_ABBR: {
return Parse(standaloneAbbreviatedDayNames, index);
}
default: {
return Parse(standaloneWideDayNames, index);
}
}
}
string DateTimeData::GetAmPmMarker(int32_t index, DateTimeDataType type)
{
if ((index < 0) || (index >= AM_SIZE)) {
return "";
}
return (amPmMarkers != "") ? Parse(amPmMarkers, index) : "";
}
char DateTimeData::GetTimeSeparator(void) const
{
return timeSeparator;
}
char DateTimeData::GetDefaultHour(void) const
{
return defaultHour;
}
std::string DateTimeData::GetPattern(int32_t index, PatternType type)
{
switch (type) {
case PatternType::HOUR_MINUTE_SECOND_PATTERN: {
if ((index < 0) || (index >= HOUR_MINUTE_SECOND_PATTERN_SIZE)) {
return "";
}
return Parse(hourMinuteSecondPatterns, index);
}
case PatternType::REGULAR_PATTERN: {
if ((index < 0) || (index >= REGULAR_PATTERN_SIZE)) {
return "";
}
return Parse(patterns, index);
}
default: {
if ((index < 0) || (index >= FULL_MEDIUM_SHORT_PATTERN_SIZE)) {
return "";
}
return Parse(fullMediumShortPatterns, index);
}
}
} | 28.746575 | 97 | 0.573505 |
12ec1ed28f7742e603f70263f0fc5939e8d1c872 | 2,807 | cpp | C++ | moe/natj/natj/natj-cxxtests/src/test/native/binding/Functions.cpp | ark100/multi-os-engine | f71d66a58b3d7e5eb2a68541480b7a0d88c7b908 | [
"Apache-2.0"
] | 3 | 2016-08-25T03:26:16.000Z | 2017-04-23T11:42:36.000Z | moe/natj/natj/natj-cxxtests/src/test/native/binding/Functions.cpp | ark100/multi-os-engine | f71d66a58b3d7e5eb2a68541480b7a0d88c7b908 | [
"Apache-2.0"
] | 1 | 2016-11-23T03:11:01.000Z | 2016-11-23T03:11:01.000Z | moe/natj/natj/natj-cxxtests/src/test/native/binding/Functions.cpp | ark100/multi-os-engine | f71d66a58b3d7e5eb2a68541480b7a0d88c7b908 | [
"Apache-2.0"
] | 7 | 2016-09-10T02:19:04.000Z | 2021-07-29T17:19:41.000Z | /*
Copyright 2014-2016 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "Functions.hpp"
namespace ns_fn = natj::cxx::tests::binding::functions;
void testFunctionSimple() {
ns_fn::lastInvocation = ns_fn::FunctionID::SIMPLE;
}
namespace natj { namespace cxx { namespace tests { namespace binding {
namespace functions {
enum FunctionID lastInvocation = FunctionID::ILLEGAL;
void testFunctionWhichHasAUniqueName() {
lastInvocation = FunctionID::UNIQUENAME;
}
}
} } } }
void testFunctionLotsOfArgsTest1(int a, float b, long long c, bool d, double e) {
__NATJ_ASSERT(a == 1);
__NATJ_ASSERT(b == 3.5);
__NATJ_ASSERT(c == 156);
__NATJ_ASSERT(d == 0);
__NATJ_ASSERT(e == 89165.4151);
ns_fn::lastInvocation = ns_fn::FunctionID::TEST1;
}
void testFunctionLotsOfArgsTest2(int p1, int p2, int p3, int p4, int p5, int p6, int p7,
int p8, int p9, int p10, int p11, int p12, int p13, int p14,
int p15, int p16, int p17, int p18, int p19, int p20,
int p21, int p22, int p23, int p24, int p25, int p26,
int p27, int p28, int p29, int p30, int p31, int p32,
int p33, int p34, int p35, int p36, int p37, int p38,
int p39, int p40, long long p41, int p42, int p43, int p44,
int p45, int p46, int p47, int p48, int p49, int p50,
int p51, int p52, int p53, int p54, int p55, int p56,
int p57, int p58, int p59, int p60, int p61, int p62,
int p63, int p64) {
auto result = p1 + p2 + p3 + p4 + p5 + p6 + p7 + p8 + p9 + p10 + p11 + p12 +
p13 + p14 + p15 + p16 + p17 + p18 + p19 + p20 + p21 + p22 + p23 + p24 + p25
+ p26 + p27 + p28 + p29 + p30 + p31 + p32 + p33 + p34 + p35 + p36 + p37
+ p38 + p39 + p40 + p41 + p42 + p43 + p44 + p45 + p46 + p47 + p48 + p49
+ p50 + p51 + p52 + p53 + p54 + p55 + p56 + p57 + p58 + p59 + p60 + p61
+ p62 + p63 + p64;
ns_fn::lastInvocation = ns_fn::FunctionID::TEST2;
__NATJ_ASSERT(result == 2080);
}
void testThrowsIntegerException() {
throw 20;
}
| 41.279412 | 93 | 0.58746 |
12ec4045586b0a03ddb1f52dc847cd06f99b7244 | 7,183 | cpp | C++ | libgpopt/src/operators/CLogicalDynamicGet.cpp | khannaekta/gporca | 94e509d0a2456851a2cabf02e933c3523946b87b | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2019-03-05T10:08:56.000Z | 2019-03-05T10:08:56.000Z | libgpopt/src/operators/CLogicalDynamicGet.cpp | khannaekta/gporca | 94e509d0a2456851a2cabf02e933c3523946b87b | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | libgpopt/src/operators/CLogicalDynamicGet.cpp | khannaekta/gporca | 94e509d0a2456851a2cabf02e933c3523946b87b | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | //---------------------------------------------------------------------------
// Greenplum Database
// Copyright (C) 2012 EMC Corp.
//
// @filename:
// CLogicalDynamicGet.cpp
//
// @doc:
// Implementation of dynamic table access
//---------------------------------------------------------------------------
#include "gpos/base.h"
#include "gpopt/base/CUtils.h"
#include "gpopt/base/CConstraintInterval.h"
#include "gpopt/base/CColRefSet.h"
#include "gpopt/base/CPartIndexMap.h"
#include "gpopt/base/CColRefSetIter.h"
#include "gpopt/base/CColRefTable.h"
#include "gpopt/base/COptCtxt.h"
#include "gpopt/operators/CExpressionHandle.h"
#include "gpopt/operators/CLogicalDynamicGet.h"
#include "gpopt/metadata/CTableDescriptor.h"
#include "gpopt/metadata/CName.h"
using namespace gpopt;
//---------------------------------------------------------------------------
// @function:
// CLogicalDynamicGet::CLogicalDynamicGet
//
// @doc:
// ctor - for pattern
//
//---------------------------------------------------------------------------
CLogicalDynamicGet::CLogicalDynamicGet
(
IMemoryPool *pmp
)
:
CLogicalDynamicGetBase(pmp)
{
}
//---------------------------------------------------------------------------
// @function:
// CLogicalDynamicGet::CLogicalDynamicGet
//
// @doc:
// ctor
//
//---------------------------------------------------------------------------
CLogicalDynamicGet::CLogicalDynamicGet
(
IMemoryPool *pmp,
const CName *pnameAlias,
CTableDescriptor *ptabdesc,
ULONG ulPartIndex,
DrgPcr *pdrgpcrOutput,
DrgDrgPcr *pdrgpdrgpcrPart,
ULONG ulSecondaryPartIndexId,
BOOL fPartial,
CPartConstraint *ppartcnstr,
CPartConstraint *ppartcnstrRel
)
:
CLogicalDynamicGetBase(pmp, pnameAlias, ptabdesc, ulPartIndex, pdrgpcrOutput, pdrgpdrgpcrPart, ulSecondaryPartIndexId, fPartial, ppartcnstr, ppartcnstrRel)
{
}
//---------------------------------------------------------------------------
// @function:
// CLogicalDynamicGet::CLogicalDynamicGet
//
// @doc:
// ctor
//
//---------------------------------------------------------------------------
CLogicalDynamicGet::CLogicalDynamicGet
(
IMemoryPool *pmp,
const CName *pnameAlias,
CTableDescriptor *ptabdesc,
ULONG ulPartIndex
)
:
CLogicalDynamicGetBase(pmp, pnameAlias, ptabdesc, ulPartIndex)
{
}
//---------------------------------------------------------------------------
// @function:
// CLogicalDynamicGet::~CLogicalDynamicGet
//
// @doc:
// dtor
//
//---------------------------------------------------------------------------
CLogicalDynamicGet::~CLogicalDynamicGet()
{
}
//---------------------------------------------------------------------------
// @function:
// CLogicalDynamicGet::UlHash
//
// @doc:
// Operator specific hash function
//
//---------------------------------------------------------------------------
ULONG
CLogicalDynamicGet::UlHash() const
{
ULONG ulHash = gpos::UlCombineHashes(COperator::UlHash(), m_ptabdesc->Pmdid()->UlHash());
ulHash = gpos::UlCombineHashes(ulHash, CUtils::UlHashColArray(m_pdrgpcrOutput));
return ulHash;
}
//---------------------------------------------------------------------------
// @function:
// CLogicalDynamicGet::FMatch
//
// @doc:
// Match function on operator level
//
//---------------------------------------------------------------------------
BOOL
CLogicalDynamicGet::FMatch
(
COperator *pop
)
const
{
return CUtils::FMatchDynamicScan(this, pop);
}
//---------------------------------------------------------------------------
// @function:
// CLogicalDynamicGet::PopCopyWithRemappedColumns
//
// @doc:
// Return a copy of the operator with remapped columns
//
//---------------------------------------------------------------------------
COperator *
CLogicalDynamicGet::PopCopyWithRemappedColumns
(
IMemoryPool *pmp,
HMUlCr *phmulcr,
BOOL fMustExist
)
{
DrgPcr *pdrgpcrOutput = NULL;
if (fMustExist)
{
pdrgpcrOutput = CUtils::PdrgpcrRemapAndCreate(pmp, m_pdrgpcrOutput, phmulcr);
}
else
{
pdrgpcrOutput = CUtils::PdrgpcrRemap(pmp, m_pdrgpcrOutput, phmulcr, fMustExist);
}
DrgDrgPcr *pdrgpdrgpcrPart = PdrgpdrgpcrCreatePartCols(pmp, pdrgpcrOutput, m_ptabdesc->PdrgpulPart());
CName *pnameAlias = GPOS_NEW(pmp) CName(pmp, *m_pnameAlias);
m_ptabdesc->AddRef();
CPartConstraint *ppartcnstr = m_ppartcnstr->PpartcnstrCopyWithRemappedColumns(pmp, phmulcr, fMustExist);
CPartConstraint *ppartcnstrRel = m_ppartcnstrRel->PpartcnstrCopyWithRemappedColumns(pmp, phmulcr, fMustExist);
return GPOS_NEW(pmp) CLogicalDynamicGet(pmp, pnameAlias, m_ptabdesc, m_ulScanId, pdrgpcrOutput, pdrgpdrgpcrPart, m_ulSecondaryScanId, m_fPartial, ppartcnstr, ppartcnstrRel);
}
//---------------------------------------------------------------------------
// @function:
// CLogicalDynamicGet::FInputOrderSensitive
//
// @doc:
// Not called for leaf operators
//
//---------------------------------------------------------------------------
BOOL
CLogicalDynamicGet::FInputOrderSensitive() const
{
GPOS_ASSERT(!"Unexpected function call of FInputOrderSensitive");
return false;
}
//---------------------------------------------------------------------------
// @function:
// CLogicalDynamicGet::PxfsCandidates
//
// @doc:
// Get candidate xforms
//
//---------------------------------------------------------------------------
CXformSet *
CLogicalDynamicGet::PxfsCandidates
(
IMemoryPool *pmp
)
const
{
CXformSet *pxfs = GPOS_NEW(pmp) CXformSet(pmp);
(void) pxfs->FExchangeSet(CXform::ExfDynamicGet2DynamicTableScan);
return pxfs;
}
//---------------------------------------------------------------------------
// @function:
// CLogicalDynamicGet::OsPrint
//
// @doc:
// debug print
//
//---------------------------------------------------------------------------
IOstream &
CLogicalDynamicGet::OsPrint
(
IOstream &os
)
const
{
if (m_fPattern)
{
return COperator::OsPrint(os);
}
else
{
os << SzId() << " ";
// alias of table as referenced in the query
m_pnameAlias->OsPrint(os);
// actual name of table in catalog and columns
os << " (";
m_ptabdesc->Name().OsPrint(os);
os <<"), ";
m_ppartcnstr->OsPrint(os);
os << "), Columns: [";
CUtils::OsPrintDrgPcr(os, m_pdrgpcrOutput);
os << "] Scan Id: " << m_ulScanId << "." << m_ulSecondaryScanId;
if (!m_ppartcnstr->FUnbounded())
{
os << ", ";
m_ppartcnstr->OsPrint(os);
}
}
return os;
}
//---------------------------------------------------------------------------
// @function:
// CLogicalDynamicGet::PstatsDerive
//
// @doc:
// Load up statistics from metadata
//
//---------------------------------------------------------------------------
IStatistics *
CLogicalDynamicGet::PstatsDerive
(
IMemoryPool *pmp,
CExpressionHandle &exprhdl,
DrgPstat * // not used
)
const
{
CReqdPropRelational *prprel = CReqdPropRelational::Prprel(exprhdl.Prp());
IStatistics *pstats = PstatsDeriveFilter(pmp, exprhdl, prprel->PexprPartPred());
CColRefSet *pcrs = GPOS_NEW(pmp) CColRefSet(pmp, m_pdrgpcrOutput);
CUpperBoundNDVs *pubndv = GPOS_NEW(pmp) CUpperBoundNDVs(pcrs, pstats->DRows());
CStatistics::PstatsConvert(pstats)->AddCardUpperBound(pubndv);
return pstats;
}
// EOF
| 24.940972 | 174 | 0.540303 |
12ee154c18c8d7d109812ea326b135f82a7bdae4 | 6,486 | cpp | C++ | src/customprofession.cpp | jimhester/dwarftherapist | 44b48fc87f07011d348be12b9abdf5206d54ba40 | [
"MIT"
] | 3 | 2015-03-21T00:24:13.000Z | 2021-08-04T07:18:46.000Z | src/customprofession.cpp | jimhester/dwarftherapist | 44b48fc87f07011d348be12b9abdf5206d54ba40 | [
"MIT"
] | null | null | null | src/customprofession.cpp | jimhester/dwarftherapist | 44b48fc87f07011d348be12b9abdf5206d54ba40 | [
"MIT"
] | null | null | null | /*
Dwarf Therapist
Copyright (c) 2009 Trey Stout (chmod)
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 <QtGui>
#include "customprofession.h"
#include "gamedatareader.h"
#include "ui_customprofession.h"
#include "dwarf.h"
#include "defines.h"
#include "labor.h"
#include "profession.h"
/*!
Default ctor. Creates a blank skill template with no name
*/
CustomProfession::CustomProfession(QObject *parent)
: QObject(parent)
, ui(new Ui::CustomProfessionEditor)
, m_dwarf(0)
, m_dialog(0)
{}
/*!
When passed in a pointer to a Dwarf, this new custom profession
will adopt whatever labors that Dwarf has enabled as its
own template.
This is used by the "Create custom profession from this dwarf..." action.
\param[in] d The Dwarf to use as a labor template
\param[in] parent The Qt owner of this object
*/
CustomProfession::CustomProfession(Dwarf *d, QObject *parent)
: QObject(parent)
, ui(new Ui::CustomProfessionEditor)
, m_dialog(0)
, m_dwarf(d)
{
GameDataReader *gdr = GameDataReader::ptr();
QList<Labor*> labors = gdr->get_ordered_labors();
foreach(Labor *l, labors) {
if (m_dwarf && m_dwarf->labor_enabled(l->labor_id) && l->labor_id != -1)
add_labor(l->labor_id);
}
}
/*!
Change the enabled status of a template labor. This doesn't
affect any dwarves using this custom profession, only the
template itself.
\param[in] labor_id The id of the labor to change
\param[in] active Should the labor be enabled or not
*/
void CustomProfession::set_labor(int labor_id, bool active) {
if (m_active_labors.contains(labor_id) && !active)
m_active_labors.remove(labor_id);
if (active)
m_active_labors.insert(labor_id, true);
}
/*!
Check if the template has a labor enabled
\param[in] labor_id The id of the labor to check
\returns true if this labor is enabled
*/
bool CustomProfession::is_active(int labor_id) {
return m_active_labors.value(labor_id, false);
}
/*!
Get a vector of all enabled labors in this template by labor_id
*/
QVector<int> CustomProfession::get_enabled_labors() {
QVector<int> labors;
foreach(int labor, m_active_labors.uniqueKeys()) {
if (m_active_labors.value(labor) && labor != -1) {
labors << labor;
}
}
return labors;
}
/*!
Pops up a dialog box asking for a name for this object as well
as a list of labors that can be enabled/disabled via checkboxes
\param[in] parent If set, the dialog will launch as a model under parent
\returns QDialog::exec() result (int)
*/
int CustomProfession::show_builder_dialog(QWidget *parent) {
GameDataReader *gdr = GameDataReader::ptr();
m_dialog = new QDialog(parent);
ui->setupUi(m_dialog);
ui->name_edit->setText(m_name);
connect(ui->name_edit, SIGNAL(textChanged(const QString &)), this, SLOT(set_name(QString)));
connect(ui->buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
QList<Labor*> labors = gdr->get_ordered_labors();
int num_active = 0;
foreach(Labor *l, labors) {
if (l->is_weapon)
continue;
QListWidgetItem *item = new QListWidgetItem(l->name, ui->labor_list);
item->setData(Qt::UserRole, l->labor_id);
item->setFlags(item->flags() | Qt::ItemIsUserCheckable);
if (is_active(l->labor_id)) {
item->setCheckState(Qt::Checked);
num_active++;
} else {
item->setCheckState(Qt::Unchecked);
}
ui->labor_list->addItem(item);
}
connect(ui->labor_list,
SIGNAL(itemChanged(QListWidgetItem*)),
this,
SLOT(item_check_state_changed(QListWidgetItem*)));
ui->lbl_skill_count->setNum(num_active);
int code = m_dialog->exec();
m_dialog->deleteLater();
return code;
}
/*!
Called when the show_builder_dialog widget's OK button is pressed, or the
dialog is otherwise accepted by the user
We intercept this call to verify the form is valid before saving it.
\sa is_valid()
*/
void CustomProfession::accept() {
if (!is_valid()) {
return;
}
m_dialog->accept();
}
/*!
Called after the show_builder_dialog widget is accepted, used to verify that
the CustomProfession has all needed information to save
\returns true if this instance is ok to save.
*/
bool CustomProfession::is_valid() {
if (!m_dialog)
return true;
QString proposed_name = ui->name_edit->text();
if (proposed_name.isEmpty()) {
QMessageBox::warning(m_dialog, tr("Naming Error!"),
tr("You must enter a name for this custom profession!"));
return false;
}
/* Let's not do this...
QHash<short, Profession*> profs = GameDataReader::ptr()->get_professions();
foreach(Profession *p, profs) {
if (proposed_name == p->name(true)) {
QMessageBox::warning(m_dialog, tr("Naming Error!"),
tr("The profession '%1' is a default game profession, please choose a different name.").arg(proposed_name));
return false;
}
}
*/
return true;
}
void CustomProfession::item_check_state_changed(QListWidgetItem *item) {
if (item->checkState() == Qt::Checked) {
add_labor(item->data(Qt::UserRole).toInt());
ui->lbl_skill_count->setNum(ui->lbl_skill_count->text().toInt() + 1);
} else {
remove_labor(item->data(Qt::UserRole).toInt());
ui->lbl_skill_count->setNum(ui->lbl_skill_count->text().toInt() - 1);
}
}
void CustomProfession::delete_from_disk() {
QSettings s(QSettings::IniFormat, QSettings::UserScope, COMPANY, PRODUCT, this);
s.beginGroup("custom_professions");
s.remove(m_name);
s.endGroup();
}
| 30.739336 | 113 | 0.707524 |
12ef742d3c9a363edfe3a16ac10836266ef09723 | 6,179 | cpp | C++ | visualization/determinant/determinant.cpp | mika314/simuleios | 0b05660c7df0cd6e31eb5e70864cbedaec29b55a | [
"MIT"
] | 197 | 2015-07-26T02:04:17.000Z | 2022-01-21T11:53:33.000Z | visualization/determinant/determinant.cpp | shiffman/simuleios | 57239350d2cbed10893483bda65fa323e5e3a06d | [
"MIT"
] | 18 | 2015-08-04T22:55:46.000Z | 2020-11-06T02:33:48.000Z | visualization/determinant/determinant.cpp | shiffman/simuleios | 57239350d2cbed10893483bda65fa323e5e3a06d | [
"MIT"
] | 55 | 2015-08-02T21:43:18.000Z | 2021-12-13T18:25:08.000Z | /*-------------determinant.cpp------------------------------------------------//
*
* Purpose: Simple multiplication to help visualize eigenvectors
*
* Notes: compile with:
* g++ -I /usr/include/eigen3/ eigentest.cpp -Wno-ignored-attributes -Wno-deprecated-declarations
*
*-----------------------------------------------------------------------------*/
#include <iostream>
#include <Eigen/Core>
#include <vector>
#include <fstream>
using namespace Eigen;
int main(){
// Opening file to writing
std::ofstream output;
output.open("out.dat");
int size = 2, count=0;
// setting up positions of all the desired points to transform
double x[size*size*size], y[size*size*size], z[size*size*size],
x2[size*size*size], y2[size*size*size], z2[size*size*size],
xval = -1, yval = -1, zval = -1;
MatrixXd Arr(3, 3);
MatrixXd pos(3, 1);
// Putting in "random" values for matrix
Arr << 1, 2, 0,
2, 1, 0,
0, 0, -3;
/*
Arr << 1, 0, 0,
0, 1, 0,
0, 0, 1;
*/
std::cout << Arr << '\n';
// Creating initial x, y, and z locations
for (int i = 0; i < size; ++i){
for (int j = 0; j < size; ++j){
for (int k = 0; k < size; ++k){
xval = -1 + 2 * ((double)i / ((double)size - 1));
yval = -1 + 2 * ((double)j / ((double)size - 1));
zval = -1 + 2 * ((double)k / ((double)size - 1));
x[count] = xval;
y[count] = yval;
z[count] = zval;
// Performing multiplication / setting up vector
pos(0) = xval;
pos(1) = yval;
pos(2) = zval;
pos = Arr * pos;
// Storing values in x2, y2, and z2
x2[count] = pos(0);
y2[count] = pos(1);
z2[count] = pos(2);
count += 1;
}
}
}
count = 8;
for (int i = 0; i < count; ++i){
std::cout << x[i] << '\t' << y[i] << '\t' << z[i] << '\n';
pos(0) = x[i];
pos(1) = y[i];
pos(2) = z[i];
pos = Arr * pos;
// Storing values in x2, y2, and z2
x2[i] = pos(0);
y2[i] = pos(1);
z2[i] = pos(2);
}
/*
// Creating initial x, y, and z locations
for (int i = 0; i < size; ++i){
for (int j = 0; j < size; ++j){
for (int k = 0; k < size; ++k){
xval = -1 + 2 * ((double)i / (double)size);
yval = -1 + 2 * ((double)j / (double)size);
zval = -1 + 2 * ((double)k / (double)size);
x[count] = xval;
y[count] = yval;
z[count] = zval;
// Performing multiplication / setting up vector
pos(0) = xval;
pos(1) = yval;
pos(2) = zval;
pos = Arr * pos;
// Storing values in x2, y2, and z2
x2[count] = pos(0);
y2[count] = pos(1);
z2[count] = pos(2);
count += 1;
}
}
}
// Writing to file in correct format
count = 0;
for (int i = 0; i < size; ++i){
for (int j = 0; j < size; ++j){
for (int k = 0; k < size; ++k){
output << x[count] << '\t' << y[count]
<< '\t' << z[count] << '\t' << count << '\n';
count++;
}
}
}
output << '\n' << '\n';
count = 0;
for (int i = 0; i < size; ++i){
for (int j = 0; j < size; ++j){
for (int k = 0; k < size; ++k){
output << x2[count] << '\t' << y2[count]
<< '\t' << z2[count] << '\t' << count << '\n';
count++;
}
}
}
*/
int frames = 60;
count = 0;
double xvel[size*size*size], yvel[size*size*size], zvel[size*size*size];
double vid_time = 1.0;
count = 8;
for (int i = 0; i < count; ++i){
xvel[i] = (x[i] - x2[i]) / vid_time;
yvel[i] = (y[i] - y2[i]) / vid_time;
zvel[i] = (z[i] - z2[i]) / vid_time;
}
for (int f = 0; f < frames; ++f){
for (int i = 0; i < count; ++i){
xval = x[i] + ((x2[i] - x[i])
* ((double)f / (double)frames));
yval = y[i] + ((y2[i] - y[i])
* ((double)f / (double)frames));
zval = z[i] + ((z2[i] - z[i])
* ((double)f / (double)frames));
output << xval << '\t' << yval
<< '\t' << zval << '\t'
<< xvel[i] << '\t' << yvel[i] << '\t'
<< zvel[i] << '\t' << 1 << '\t' << i << '\n';
}
output << '\n' << '\n';
}
/*
for (int i = 0; i < size; ++i){
for (int j = 0; j < size; ++j){
for (int k = 0; k < size; ++k){
xvel[count] = (x[count] - x2[count]) / vid_time;
yvel[count] = (y[count] - y2[count]) / vid_time;
zvel[count] = (z[count] - z2[count]) / vid_time;
count = count + 1;
}
}
}
for (int f = 0; f < frames; ++f){
count = 0;
for (int i = 0; i < size; ++i){
for (int j = 0; j < size; ++j){
for (int k = 0; k < size; ++k){
xval = x[count] + ((x2[count] - x[count])
* ((double)f / (double)frames));
yval = y[count] + ((y2[count] - y[count])
* ((double)f / (double)frames));
zval = z[count] + ((z2[count] - z[count])
* ((double)f / (double)frames));
output << xval << '\t' << yval
<< '\t' << zval << '\t'
<< xvel[count] << '\t' << yvel[count] << '\t'
<< zvel[count] << '\t' << 1 << '\t' << count << '\n';
count++;
}
}
}
output << '\n' << '\n';
}
*/
output.close();
}
| 29.564593 | 107 | 0.362195 |
12f20952bf329e98c0583356186b08930a02c495 | 4,514 | hpp | C++ | include/GlobalNamespace/BeatmapEditorSceneSetupData.hpp | Fernthedev/BeatSaber-Quest-Codegen | 716e4ff3f8608f7ed5b83e2af3be805f69e26d9e | [
"Unlicense"
] | null | null | null | include/GlobalNamespace/BeatmapEditorSceneSetupData.hpp | Fernthedev/BeatSaber-Quest-Codegen | 716e4ff3f8608f7ed5b83e2af3be805f69e26d9e | [
"Unlicense"
] | null | null | null | include/GlobalNamespace/BeatmapEditorSceneSetupData.hpp | Fernthedev/BeatSaber-Quest-Codegen | 716e4ff3f8608f7ed5b83e2af3be805f69e26d9e | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
#include "extern/beatsaber-hook/shared/utils/byref.hpp"
// Including type: SceneSetupData
#include "GlobalNamespace/SceneSetupData.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Type namespace:
namespace GlobalNamespace {
// Size: 0x20
#pragma pack(push, 1)
// Autogenerated type: BeatmapEditorSceneSetupData
// [TokenAttribute] Offset: FFFFFFFF
class BeatmapEditorSceneSetupData : public GlobalNamespace::SceneSetupData {
public:
// private System.String _levelDirPath
// Size: 0x8
// Offset: 0x10
::Il2CppString* levelDirPath;
// Field size check
static_assert(sizeof(::Il2CppString*) == 0x8);
// private System.String _levelAssetPath
// Size: 0x8
// Offset: 0x18
::Il2CppString* levelAssetPath;
// Field size check
static_assert(sizeof(::Il2CppString*) == 0x8);
// Creating value type constructor for type: BeatmapEditorSceneSetupData
BeatmapEditorSceneSetupData(::Il2CppString* levelDirPath_ = {}, ::Il2CppString* levelAssetPath_ = {}) noexcept : levelDirPath{levelDirPath_}, levelAssetPath{levelAssetPath_} {}
// Get instance field reference: private System.String _levelDirPath
::Il2CppString*& dyn__levelDirPath();
// Get instance field reference: private System.String _levelAssetPath
::Il2CppString*& dyn__levelAssetPath();
// public System.String get_levelDirPath()
// Offset: 0x11EB008
::Il2CppString* get_levelDirPath();
// public System.String get_levelAssetPath()
// Offset: 0x11EB010
::Il2CppString* get_levelAssetPath();
// public System.Void .ctor(System.String levelDirPath, System.String levelAssetPath)
// Offset: 0x11EB018
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static BeatmapEditorSceneSetupData* New_ctor(::Il2CppString* levelDirPath, ::Il2CppString* levelAssetPath) {
static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::BeatmapEditorSceneSetupData::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<BeatmapEditorSceneSetupData*, creationType>(levelDirPath, levelAssetPath)));
}
}; // BeatmapEditorSceneSetupData
#pragma pack(pop)
static check_size<sizeof(BeatmapEditorSceneSetupData), 24 + sizeof(::Il2CppString*)> __GlobalNamespace_BeatmapEditorSceneSetupDataSizeCheck;
static_assert(sizeof(BeatmapEditorSceneSetupData) == 0x20);
}
DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::BeatmapEditorSceneSetupData*, "", "BeatmapEditorSceneSetupData");
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: GlobalNamespace::BeatmapEditorSceneSetupData::get_levelDirPath
// Il2CppName: get_levelDirPath
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppString* (GlobalNamespace::BeatmapEditorSceneSetupData::*)()>(&GlobalNamespace::BeatmapEditorSceneSetupData::get_levelDirPath)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::BeatmapEditorSceneSetupData*), "get_levelDirPath", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::BeatmapEditorSceneSetupData::get_levelAssetPath
// Il2CppName: get_levelAssetPath
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppString* (GlobalNamespace::BeatmapEditorSceneSetupData::*)()>(&GlobalNamespace::BeatmapEditorSceneSetupData::get_levelAssetPath)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::BeatmapEditorSceneSetupData*), "get_levelAssetPath", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::BeatmapEditorSceneSetupData::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
| 55.728395 | 208 | 0.746566 |
12f215192f86742dedb82ba99afe65550028fa23 | 886 | cpp | C++ | mcomp_C/common/datatypes/path/Path.cpp | kasmaslrn/MCOMP_Team_Project_2017-2018 | 5e20c49c0d7a30083944ddc71ed9d595783a12a5 | [
"MIT"
] | 1 | 2019-03-18T14:27:46.000Z | 2019-03-18T14:27:46.000Z | mcomp_C/common/datatypes/path/Path.cpp | kasmaslrn/MCOMP_Team_Project_2017-2018 | 5e20c49c0d7a30083944ddc71ed9d595783a12a5 | [
"MIT"
] | null | null | null | mcomp_C/common/datatypes/path/Path.cpp | kasmaslrn/MCOMP_Team_Project_2017-2018 | 5e20c49c0d7a30083944ddc71ed9d595783a12a5 | [
"MIT"
] | null | null | null | /*
* mcomp_C.ino
*
* Created on: 26 Nov 2017
* Author: David Avery 15823926
*
*/
#include "Path.h"
#include "../Waypoint.h"
int length;
Path::Path(Waypoint w) {
destination = new LinkedItem(w);
head = nullptr;
lastItem = nullptr;
length = 0;
}
Path::~Path() {
// TODO Auto-generated destructor stub
}
void Path::addNode(Waypoint w) {
if (length > 0) {
(*lastItem).setNext(new LinkedItem(w));
lastItem = (*lastItem).getNext();
} else {
head = new LinkedItem(w);
lastItem = head;
}
length++;
}
Waypoint Path::poll() {
Waypoint res = (*destination).getData();
if (length > 0) {
res = (*head).getData();
head = (*head).getNext();
if (head == nullptr) {
lastItem = nullptr;
}
length--;
}
return res;
}
int Path::getLength() {
return length;
}
| 15.821429 | 44 | 0.544018 |
12f3fcf8b2653271ac4021d0de49448b66472c07 | 17,881 | cpp | C++ | OpenXaml/XamlObjects/TextBlock.cpp | benroywillis/OpenXaml | a6313c096b5221344ee2dbcfe6e5a4db8345115c | [
"MIT"
] | 1 | 2019-09-23T03:11:04.000Z | 2019-09-23T03:11:04.000Z | OpenXaml/XamlObjects/TextBlock.cpp | benroywillis/OpenXaml | a6313c096b5221344ee2dbcfe6e5a4db8345115c | [
"MIT"
] | null | null | null | OpenXaml/XamlObjects/TextBlock.cpp | benroywillis/OpenXaml | a6313c096b5221344ee2dbcfe6e5a4db8345115c | [
"MIT"
] | 2 | 2019-11-03T01:12:22.000Z | 2022-03-07T16:59:32.000Z | #include "OpenXaml/XamlObjects/TextBlock.h"
#include "OpenXaml/Environment/Environment.h"
#include "OpenXaml/Environment/Window.h"
#include "OpenXaml/GL/GLConfig.h"
#include "OpenXaml/Properties/Alignment.h"
#include "OpenXaml/Properties/TextWrapping.h"
#include <algorithm>
#include <codecvt>
#include <glad/glad.h>
#include <harfbuzz/hb.h>
#include <iostream>
#include <locale>
#include <cmath>
#include <sstream>
#include <string>
#include <utility>
using namespace std;
namespace OpenXaml::Objects
{
void TextBlock::Draw()
{
glBindVertexArray(TextBlock::VAO);
glUseProgram(GL::xamlShader);
int vertexColorLocation = glGetUniformLocation(GL::xamlShader, "thecolor");
int modeLoc = glGetUniformLocation(GL::xamlShader, "mode");
glUniform4f(vertexColorLocation, 0.0F, 0.0F, 0.0F, 1.0F);
glUniform1i(modeLoc, 2);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, edgeBuffer);
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glBindTexture(GL_TEXTURE_2D, font->getFontAtlasTexture());
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), nullptr);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void *)(2 * sizeof(float)));
glDrawElements(GL_TRIANGLES, 6 * glyphCount, GL_UNSIGNED_SHORT, nullptr);
}
void TextBlock::Initialize()
{
glGenVertexArrays(1, &(TextBlock::VAO));
glBindVertexArray(TextBlock::VAO);
glGenBuffers(1, &edgeBuffer);
glGenBuffers(1, &vertexBuffer);
Update();
}
void TextBlock::Update()
{
XamlObject::Update();
font = Environment::GetFont(FontProperties{FontFamily, FontSize});
if (font == nullptr)
{
return;
}
vector<size_t> indexes;
for (size_t i = 0; i < Text.size(); i++)
{
char32_t a = Text.at(i);
if (a == U'\n')
{
indexes.push_back(i);
}
}
float wordWidth = 0; //width of current word
size_t currentIndex = 0;
int lineCount = 0; //number of lines
float width = 0; //width of current line
float maxWidth = 0; //max line width
size_t charsToRender = 0;
float fBounds = (localMax.x - localMin.x);
vector<u32string> splitStrings;
for (uint32_t i = 0; i < indexes.size() + 1; i++)
{
size_t index = i == indexes.size() ? Text.size() : indexes.at(i);
u32string subString = Text.substr(currentIndex, index - currentIndex);
if (i < indexes.size())
{
currentIndex = indexes.at(i) + 1;
}
//we should render this line
auto formattedText = font->FormatText(subString);
for (auto character : formattedText)
{
wordWidth += character.xAdvance;
if (font->IsSeperator(character.Character))
{
if (TextWrapping != TextWrapping::NoWrap && width + wordWidth > fBounds)
{
lineCount++;
maxWidth = std::max(maxWidth, width);
width = wordWidth;
wordWidth = 0;
}
else
{
width += wordWidth;
wordWidth = 0;
}
}
}
//we now know the number of lines in this 'line' as well as its width, so increment and set the width
lineCount++;
maxWidth = std::max(maxWidth, wordWidth);
charsToRender += formattedText.size();
}
maxWidth = std::max(maxWidth, width);
//we now know the true number of lines and the true width
//so we can start rendering
if (charsToRender == 0)
{
lineCount = 0;
//return;
}
auto *vBuffer = (float *)calloc(16 * charsToRender, sizeof(float));
auto *eBuffer = (unsigned short *)calloc(6 * charsToRender, sizeof(unsigned short));
wordWidth = 0;
width = 0;
int height = (font->Height >> 6);
float fWidth = maxWidth;
float fHeight = height * lineCount;
switch (VerticalAlignment)
{
case VerticalAlignment::Bottom:
{
minRendered.y = localMin.y;
maxRendered.y = min(localMax.y, localMin.y + fHeight);
break;
}
case VerticalAlignment::Top:
{
maxRendered.y = localMax.y;
minRendered.y = max(localMin.y, localMax.y - fHeight);
break;
}
case VerticalAlignment::Center:
{
float mean = 0.5F * (localMax.y + localMin.y);
maxRendered.y = min(localMax.y, mean + fHeight / 2);
minRendered.y = max(localMin.y, mean - fHeight / 2);
break;
}
case VerticalAlignment::Stretch:
{
maxRendered.y = localMax.y;
minRendered.y = localMin.y;
break;
}
}
switch (HorizontalAlignment)
{
case HorizontalAlignment::Left:
{
minRendered.x = localMin.x;
maxRendered.x = min(localMax.x, localMin.x + fWidth);
break;
}
case HorizontalAlignment::Right:
{
maxRendered.x = localMax.x;
minRendered.x = max(localMin.x, localMax.x - fWidth);
break;
}
case HorizontalAlignment::Center:
{
float mean = 0.5F * (localMax.x + localMin.x);
maxRendered.x = min(localMax.x, mean + fWidth / 2);
minRendered.x = max(localMin.x, mean - fWidth / 2);
break;
}
case HorizontalAlignment::Stretch:
{
maxRendered.x = localMax.x;
minRendered.x = localMin.x;
break;
}
}
int arrayIndex = 0;
float penX;
float penY = maxRendered.y - (height - (font->VerticalOffset >> 6));
currentIndex = 0;
for (uint32_t i = 0; i < indexes.size() + 1; i++)
{
int priorIndex = 0;
int ppIndex = 0;
size_t index = i == indexes.size() ? Text.size() : indexes.at(i);
u32string subString = Text.substr(currentIndex, index - currentIndex);
if (i < indexes.size())
{
currentIndex = indexes.at(i) + 1;
}
auto formattedText = font->FormatText(subString);
int k = 0;
for (auto character : formattedText)
{
wordWidth += character.xAdvance;
if (font->IsSeperator(character.Character))
{
if (TextWrapping != TextWrapping::NoWrap && width + wordWidth > fBounds)
{
switch (TextAlignment)
{
case TextAlignment::Center:
{
penX = (minRendered.x + maxRendered.x) * 0.5F - width * 0.5F;
break;
}
case TextAlignment::End:
{
penX = (maxRendered.x) - width;
break;
}
case TextAlignment::Start:
{
penX = minRendered.x;
break;
}
}
for (int j = priorIndex; j < ppIndex + 1; j++)
{
if (penX > localMax.x)
{
break;
}
RenderCharacter(formattedText.at(j), penX, penY, vBuffer, eBuffer, arrayIndex);
}
priorIndex = ++ppIndex;
penY -= height;
if (penY < localMin.y - height)
{
break;
}
width = wordWidth;
}
else
{
width += wordWidth;
}
wordWidth = 0;
ppIndex = k;
}
k++;
}
switch (TextAlignment)
{
case TextAlignment::Center:
{
penX = (minRendered.x + maxRendered.x) * 0.5F - wordWidth * 0.5F;
break;
}
case TextAlignment::End:
{
penX = (maxRendered.x) - width;
break;
}
case TextAlignment::Start:
{
penX = minRendered.x;
break;
}
}
for (uint32_t j = priorIndex; j < formattedText.size(); j++)
{
if (penX > localMax.x)
{
break;
}
RenderCharacter(formattedText.at(j), penX, penY, vBuffer, eBuffer, arrayIndex);
}
penY -= height;
width = 0;
}
boxWidth = (maxRendered.x - minRendered.x);
boxHeight = (maxRendered.y - minRendered.y);
glBindVertexArray(TextBlock::VAO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, edgeBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, 6 * (size_t)arrayIndex * sizeof(unsigned short), eBuffer, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, 16 * (size_t)arrayIndex * sizeof(float), vBuffer, GL_STATIC_DRAW);
std::free(eBuffer);
std::free(vBuffer);
glyphCount = arrayIndex;
}
void TextBlock::RenderCharacter(UChar ch, float &penX, float &penY, float *vertexBuffer, unsigned short *edgeBuffer, int &index)
{
auto uchar = font->GlyphMap[ch.Character];
float x0;
float x1;
float y0;
float y1;
float tx0;
float tx1;
float ty0;
float ty1;
float dx0;
float dx1;
float dy0;
float dy1;
dx0 = penX + (ch.xOffset + uchar.xBearingH);
dx1 = dx0 + uchar.width;
dy1 = penY + (ch.yOffset + uchar.yBearingH);
dy0 = dy1 - uchar.height;
x0 = clamp(dx0, localMin.x, localMax.x);
x1 = clamp(dx1, localMin.x, localMax.x);
y0 = clamp(dy0, localMin.y, localMax.y);
y1 = clamp(dy1, localMin.y, localMax.y);
float dwidth = dx1 - dx0;
float dheight = dy1 - dy0;
auto textureLoc = font->GlyphMap[ch.Character];
//handle the font textures, note that they are upside down
if (x0 != dx0)
{
//we are missing part of the left
tx0 = textureLoc.txMax - (textureLoc.txMax - textureLoc.txMin) * (x1 - x0) / dwidth;
}
else
{
tx0 = textureLoc.txMin;
}
if (x1 != dx1)
{
//we are missing part of the right
tx1 = textureLoc.txMin + (textureLoc.txMax - textureLoc.txMin) * (x1 - x0) / dwidth;
}
else
{
tx1 = textureLoc.txMax;
}
if (y0 != dy0)
{
//we are missing part of the bottom
ty0 = textureLoc.tyMax - (textureLoc.tyMax - textureLoc.tyMin) * (y1 - y0) / dheight;
}
else
{
ty0 = textureLoc.tyMin;
}
if (y1 != dy1)
{
//we are missing part of the bottom
ty1 = textureLoc.tyMin + (textureLoc.tyMax - textureLoc.tyMin) * (y1 - y0) / dheight;
}
else
{
ty1 = textureLoc.tyMax;
}
vertexBuffer[16 * index + 0] = x0;
vertexBuffer[16 * index + 1] = y1;
vertexBuffer[16 * index + 2] = tx0;
vertexBuffer[16 * index + 3] = ty1;
vertexBuffer[16 * index + 4] = x1;
vertexBuffer[16 * index + 5] = y1;
vertexBuffer[16 * index + 6] = tx1;
vertexBuffer[16 * index + 7] = ty1;
vertexBuffer[16 * index + 8] = x0;
vertexBuffer[16 * index + 9] = y0;
vertexBuffer[16 * index + 10] = tx0;
vertexBuffer[16 * index + 11] = ty0;
vertexBuffer[16 * index + 12] = x1;
vertexBuffer[16 * index + 13] = y0;
vertexBuffer[16 * index + 14] = tx1;
vertexBuffer[16 * index + 15] = ty0;
edgeBuffer[6 * index + 0] = 0 + 4 * index;
edgeBuffer[6 * index + 1] = 1 + 4 * index;
edgeBuffer[6 * index + 2] = 2 + 4 * index;
edgeBuffer[6 * index + 3] = 1 + 4 * index;
edgeBuffer[6 * index + 4] = 2 + 4 * index;
edgeBuffer[6 * index + 5] = 3 + 4 * index;
index++;
penX += ch.xAdvance;
penY -= ch.yAdvance;
}
TextBlock::TextBlock()
{
boxHeight = 0;
boxWidth = 0;
edgeBuffer = 0;
vertexBuffer = 0;
font = nullptr;
}
TextBlock::~TextBlock()
{
//glBindVertexArray(TextBlock::VAO);
//glDeleteVertexArrays(1, &TextBlock::VAO);
XamlObject::~XamlObject();
}
void TextBlock::setText(u32string text)
{
this->Text = std::move(text);
}
u32string TextBlock::getText()
{
return this->Text;
}
void TextBlock::setText(const string &text)
{
std::wstring_convert<codecvt_utf8<char32_t>, char32_t> conv;
this->Text = conv.from_bytes(text);
}
void TextBlock::setTextWrapping(OpenXaml::TextWrapping textWrapping)
{
this->TextWrapping = textWrapping;
}
TextWrapping TextBlock::getTextWrapping()
{
return this->TextWrapping;
}
void TextBlock::setFontFamily(string family)
{
this->FontFamily = std::move(family);
}
string TextBlock::getFontFamily()
{
return this->FontFamily;
}
void TextBlock::setFontSize(float size)
{
this->FontSize = size;
}
float TextBlock::getFontSize() const
{
return this->FontSize;
}
void TextBlock::setFill(unsigned int fill)
{
this->Fill = fill;
}
unsigned int TextBlock::getFill() const
{
return this->Fill;
}
void TextBlock::setTextAlignment(OpenXaml::TextAlignment alignment)
{
this->TextAlignment = alignment;
}
TextAlignment TextBlock::getTextAlignment()
{
return this->TextAlignment;
}
int TextBlock::getWidth()
{
return std::ceil(max(this->Width, this->boxWidth));
}
int TextBlock::getHeight()
{
return std::ceil(max(this->Height, this->boxHeight));
}
vec2<float> TextBlock::getDesiredDimensions()
{
if (font == nullptr)
{
font = Environment::GetFont(FontProperties{FontFamily, FontSize});
}
vec2<float> result = {0, 0};
vector<size_t> indexes;
for (size_t i = 0; i < Text.size(); i++)
{
char32_t a = Text.at(i);
if (a == U'\n')
{
indexes.push_back(i);
}
}
float wordWidth = 0; //width of current word
size_t currentIndex = 0;
int lineCount = 0; //number of lines
float width = 0; //width of current line
float maxWidth = 0; //max line width
size_t charsToRender = 0;
vector<u32string> splitStrings;
for (uint32_t i = 0; i < indexes.size() + 1; i++)
{
size_t index = i == indexes.size() ? Text.size() : indexes.at(i);
u32string subString = Text.substr(currentIndex, index - currentIndex);
if (i < indexes.size())
{
currentIndex = indexes.at(i) + 1;
}
//we should render this line
auto formattedText = font->FormatText(subString);
for (auto character : formattedText)
{
wordWidth += character.xAdvance;
if (font->IsSeperator(character.Character))
{
width += wordWidth;
wordWidth = 0;
}
}
//we now know the number of lines in this 'line' as well as its width, so increment and set the width
lineCount++;
maxWidth = std::max(maxWidth, wordWidth);
charsToRender += formattedText.size();
}
maxWidth = std::max(maxWidth, width);
result.x = std::ceil(maxWidth);
result.y = lineCount * (font->Height >> 6);
return result;
}
} // namespace OpenXaml::Objects | 34.189293 | 133 | 0.472904 |
12f46b29d5676b69947ac6fcd389eb7817116c7a | 17,917 | cpp | C++ | export/windows/obj/src/openfl/_internal/stage3D/atf/ATFReader.cpp | seanbashaw/frozenlight | 47c540d30d63e946ea2dc787b4bb602cc9347d21 | [
"MIT"
] | null | null | null | export/windows/obj/src/openfl/_internal/stage3D/atf/ATFReader.cpp | seanbashaw/frozenlight | 47c540d30d63e946ea2dc787b4bb602cc9347d21 | [
"MIT"
] | null | null | null | export/windows/obj/src/openfl/_internal/stage3D/atf/ATFReader.cpp | seanbashaw/frozenlight | 47c540d30d63e946ea2dc787b4bb602cc9347d21 | [
"MIT"
] | null | null | null | // Generated by Haxe 3.4.7
#include <hxcpp.h>
#ifndef INCLUDED_haxe_io_Bytes
#include <haxe/io/Bytes.h>
#endif
#ifndef INCLUDED_lime_utils_Log
#include <lime/utils/Log.h>
#endif
#ifndef INCLUDED_openfl__internal_stage3D_atf_ATFReader
#include <openfl/_internal/stage3D/atf/ATFReader.h>
#endif
#ifndef INCLUDED_openfl_errors_Error
#include <openfl/errors/Error.h>
#endif
#ifndef INCLUDED_openfl_errors_IllegalOperationError
#include <openfl/errors/IllegalOperationError.h>
#endif
#ifndef INCLUDED_openfl_utils_ByteArrayData
#include <openfl/utils/ByteArrayData.h>
#endif
#ifndef INCLUDED_openfl_utils_IDataInput
#include <openfl/utils/IDataInput.h>
#endif
#ifndef INCLUDED_openfl_utils_IDataOutput
#include <openfl/utils/IDataOutput.h>
#endif
#ifndef INCLUDED_openfl_utils__ByteArray_ByteArray_Impl_
#include <openfl/utils/_ByteArray/ByteArray_Impl_.h>
#endif
HX_DEFINE_STACK_FRAME(_hx_pos_9e15a0b592410441_30_new,"openfl._internal.stage3D.atf.ATFReader","new",0x0b38c27e,"openfl._internal.stage3D.atf.ATFReader.new","openfl/_internal/stage3D/atf/ATFReader.hx",30,0x63888776)
HX_LOCAL_STACK_FRAME(_hx_pos_9e15a0b592410441_82_readHeader,"openfl._internal.stage3D.atf.ATFReader","readHeader",0x33e29b25,"openfl._internal.stage3D.atf.ATFReader.readHeader","openfl/_internal/stage3D/atf/ATFReader.hx",82,0x63888776)
HX_LOCAL_STACK_FRAME(_hx_pos_9e15a0b592410441_126_readTextures,"openfl._internal.stage3D.atf.ATFReader","readTextures",0x07ab1ed0,"openfl._internal.stage3D.atf.ATFReader.readTextures","openfl/_internal/stage3D/atf/ATFReader.hx",126,0x63888776)
HX_LOCAL_STACK_FRAME(_hx_pos_9e15a0b592410441_163___readUInt24,"openfl._internal.stage3D.atf.ATFReader","__readUInt24",0xb1c572f4,"openfl._internal.stage3D.atf.ATFReader.__readUInt24","openfl/_internal/stage3D/atf/ATFReader.hx",163,0x63888776)
HX_LOCAL_STACK_FRAME(_hx_pos_9e15a0b592410441_174___readUInt32,"openfl._internal.stage3D.atf.ATFReader","__readUInt32",0xb1c573d1,"openfl._internal.stage3D.atf.ATFReader.__readUInt32","openfl/_internal/stage3D/atf/ATFReader.hx",174,0x63888776)
namespace openfl{
namespace _internal{
namespace stage3D{
namespace atf{
void ATFReader_obj::__construct( ::openfl::utils::ByteArrayData data,int byteArrayOffset){
HX_GC_STACKFRAME(&_hx_pos_9e15a0b592410441_30_new)
HXLINE( 38) this->version = (int)0;
HXLINE( 44) data->position = byteArrayOffset;
HXLINE( 45) ::String signature = data->readUTFBytes((int)3);
HXLINE( 46) data->position = byteArrayOffset;
HXLINE( 48) if ((signature != HX_("ATF",f3,9b,31,00))) {
HXLINE( 50) HX_STACK_DO_THROW( ::openfl::errors::IllegalOperationError_obj::__alloc( HX_CTX ,HX_("ATF signature not found",a0,f7,2f,3a)));
}
HXLINE( 54) int length = (int)0;
HXLINE( 57) if ((data->b->__get((byteArrayOffset + (int)6)) == (int)255)) {
HXLINE( 59) this->version = data->b->__get((byteArrayOffset + (int)7));
HXLINE( 60) data->position = (byteArrayOffset + (int)8);
HXLINE( 61) length = this->_hx___readUInt32(data);
}
else {
HXLINE( 65) this->version = (int)0;
HXLINE( 66) data->position = (byteArrayOffset + (int)3);
HXLINE( 67) length = this->_hx___readUInt24(data);
}
HXLINE( 71) int _hx_tmp = (byteArrayOffset + length);
HXDLIN( 71) if ((_hx_tmp > ::openfl::utils::_ByteArray::ByteArray_Impl__obj::get_length(data))) {
HXLINE( 73) HX_STACK_DO_THROW( ::openfl::errors::IllegalOperationError_obj::__alloc( HX_CTX ,HX_("ATF length exceeds byte array length",d7,29,45,0f)));
}
HXLINE( 77) this->data = data;
}
Dynamic ATFReader_obj::__CreateEmpty() { return new ATFReader_obj; }
void *ATFReader_obj::_hx_vtable = 0;
Dynamic ATFReader_obj::__Create(hx::DynamicArray inArgs)
{
hx::ObjectPtr< ATFReader_obj > _hx_result = new ATFReader_obj();
_hx_result->__construct(inArgs[0],inArgs[1]);
return _hx_result;
}
bool ATFReader_obj::_hx_isInstanceOf(int inClassId) {
return inClassId==(int)0x00000001 || inClassId==(int)0x687242c6;
}
bool ATFReader_obj::readHeader(int _hx___width,int _hx___height,bool cubeMap){
HX_GC_STACKFRAME(&_hx_pos_9e15a0b592410441_82_readHeader)
HXLINE( 84) int tdata = this->data->readUnsignedByte();
HXLINE( 85) int type = ((int)tdata >> (int)(int)7);
HXLINE( 87) bool _hx_tmp;
HXDLIN( 87) if (!(cubeMap)) {
HXLINE( 87) _hx_tmp = (type != (int)0);
}
else {
HXLINE( 87) _hx_tmp = false;
}
HXDLIN( 87) if (_hx_tmp) {
HXLINE( 89) HX_STACK_DO_THROW( ::openfl::errors::IllegalOperationError_obj::__alloc( HX_CTX ,HX_("ATF Cube map not expected",a7,74,ca,c8)));
}
HXLINE( 93) bool _hx_tmp1;
HXDLIN( 93) if (cubeMap) {
HXLINE( 93) _hx_tmp1 = (type != (int)1);
}
else {
HXLINE( 93) _hx_tmp1 = false;
}
HXDLIN( 93) if (_hx_tmp1) {
HXLINE( 95) HX_STACK_DO_THROW( ::openfl::errors::IllegalOperationError_obj::__alloc( HX_CTX ,HX_("ATF Cube map expected",fa,fe,ed,52)));
}
HXLINE( 99) this->cubeMap = cubeMap;
HXLINE( 101) this->atfFormat = ((int)tdata & (int)(int)127);
HXLINE( 104) bool _hx_tmp2;
HXDLIN( 104) if ((this->atfFormat != (int)3)) {
HXLINE( 104) _hx_tmp2 = (this->atfFormat != (int)5);
}
else {
HXLINE( 104) _hx_tmp2 = false;
}
HXDLIN( 104) if (_hx_tmp2) {
HXLINE( 106) ::lime::utils::Log_obj::warn(HX_("Only ATF block compressed textures without JPEG-XR+LZMA are supported",25,8c,50,6a),hx::SourceInfo(HX_("ATFReader.hx",e8,b6,75,e1),106,HX_("openfl._internal.stage3D.atf.ATFReader",8c,6b,52,5f),HX_("readHeader",83,ed,7b,f6)));
}
HXLINE( 110) this->width = ((int)(int)1 << (int)this->data->readUnsignedByte());
HXLINE( 111) this->height = ((int)(int)1 << (int)this->data->readUnsignedByte());
HXLINE( 113) bool _hx_tmp3;
HXDLIN( 113) if ((this->width == _hx___width)) {
HXLINE( 113) _hx_tmp3 = (this->height != _hx___height);
}
else {
HXLINE( 113) _hx_tmp3 = true;
}
HXDLIN( 113) if (_hx_tmp3) {
HXLINE( 115) HX_STACK_DO_THROW( ::openfl::errors::IllegalOperationError_obj::__alloc( HX_CTX ,HX_("ATF width and height dont match",3f,49,15,70)));
}
HXLINE( 119) this->mipCount = this->data->readUnsignedByte();
HXLINE( 121) return (this->atfFormat == (int)5);
}
HX_DEFINE_DYNAMIC_FUNC3(ATFReader_obj,readHeader,return )
void ATFReader_obj::readTextures( ::Dynamic uploadCallback){
HX_GC_STACKFRAME(&_hx_pos_9e15a0b592410441_126_readTextures)
HXLINE( 130) int gpuFormats;
HXDLIN( 130) if ((this->version < (int)3)) {
HXLINE( 130) gpuFormats = (int)3;
}
else {
HXLINE( 130) gpuFormats = (int)4;
}
HXLINE( 131) int sideCount;
HXDLIN( 131) if (this->cubeMap) {
HXLINE( 131) sideCount = (int)6;
}
else {
HXLINE( 131) sideCount = (int)1;
}
HXLINE( 133) {
HXLINE( 133) int _g1 = (int)0;
HXDLIN( 133) int _g = sideCount;
HXDLIN( 133) while((_g1 < _g)){
HXLINE( 133) _g1 = (_g1 + (int)1);
HXDLIN( 133) int side = (_g1 - (int)1);
HXLINE( 134) {
HXLINE( 134) int _g3 = (int)0;
HXDLIN( 134) int _g2 = this->mipCount;
HXDLIN( 134) while((_g3 < _g2)){
HXLINE( 134) _g3 = (_g3 + (int)1);
HXDLIN( 134) int level = (_g3 - (int)1);
HXLINE( 136) {
HXLINE( 136) int _g5 = (int)0;
HXDLIN( 136) int _g4 = gpuFormats;
HXDLIN( 136) while((_g5 < _g4)){
HXLINE( 136) _g5 = (_g5 + (int)1);
HXDLIN( 136) int gpuFormat = (_g5 - (int)1);
HXLINE( 138) int blockLength;
HXDLIN( 138) if ((this->version == (int)0)) {
HXLINE( 138) blockLength = this->_hx___readUInt24(this->data);
}
else {
HXLINE( 138) blockLength = this->_hx___readUInt32(this->data);
}
HXLINE( 140) int a = (this->data->position + blockLength);
HXDLIN( 140) int b = ::openfl::utils::_ByteArray::ByteArray_Impl__obj::get_length(this->data);
HXDLIN( 140) bool aNeg = (a < (int)0);
HXDLIN( 140) bool bNeg = (b < (int)0);
HXDLIN( 140) bool _hx_tmp;
HXDLIN( 140) if ((aNeg != bNeg)) {
HXLINE( 140) _hx_tmp = aNeg;
}
else {
HXLINE( 140) _hx_tmp = (a > b);
}
HXDLIN( 140) if (_hx_tmp) {
HXLINE( 142) HX_STACK_DO_THROW( ::openfl::errors::IllegalOperationError_obj::__alloc( HX_CTX ,HX_("Block length exceeds ATF file length",15,23,c0,24)));
}
HXLINE( 146) bool aNeg1 = (blockLength < (int)0);
HXDLIN( 146) bool bNeg1 = ((int)0 < (int)0);
HXDLIN( 146) bool _hx_tmp1;
HXDLIN( 146) if ((aNeg1 != bNeg1)) {
HXLINE( 146) _hx_tmp1 = aNeg1;
}
else {
HXLINE( 146) _hx_tmp1 = (blockLength > (int)0);
}
HXDLIN( 146) if (_hx_tmp1) {
HXLINE( 148) ::haxe::io::Bytes bytes = ::haxe::io::Bytes_obj::alloc(blockLength);
HXLINE( 149) ::openfl::utils::ByteArrayData _hx_tmp2 = this->data;
HXDLIN( 149) _hx_tmp2->readBytes(::openfl::utils::_ByteArray::ByteArray_Impl__obj::fromArrayBuffer(bytes),(int)0,blockLength);
HXLINE( 151) int _hx_tmp3 = ((int)this->width >> (int)level);
HXDLIN( 151) uploadCallback(side,level,gpuFormat,_hx_tmp3,((int)this->height >> (int)level),blockLength,bytes);
}
}
}
}
}
}
}
}
HX_DEFINE_DYNAMIC_FUNC1(ATFReader_obj,readTextures,(void))
int ATFReader_obj::_hx___readUInt24( ::openfl::utils::ByteArrayData data){
HX_STACKFRAME(&_hx_pos_9e15a0b592410441_163___readUInt24)
HXLINE( 165) int value = ((int)data->readUnsignedByte() << (int)(int)16);
HXLINE( 167) value = ((int)value | (int)((int)data->readUnsignedByte() << (int)(int)8));
HXLINE( 168) value = ((int)value | (int)data->readUnsignedByte());
HXLINE( 169) return value;
}
HX_DEFINE_DYNAMIC_FUNC1(ATFReader_obj,_hx___readUInt24,return )
int ATFReader_obj::_hx___readUInt32( ::openfl::utils::ByteArrayData data){
HX_STACKFRAME(&_hx_pos_9e15a0b592410441_174___readUInt32)
HXLINE( 176) int value = ((int)data->readUnsignedByte() << (int)(int)24);
HXLINE( 178) value = ((int)value | (int)((int)data->readUnsignedByte() << (int)(int)16));
HXLINE( 179) value = ((int)value | (int)((int)data->readUnsignedByte() << (int)(int)8));
HXLINE( 180) value = ((int)value | (int)data->readUnsignedByte());
HXLINE( 181) return value;
}
HX_DEFINE_DYNAMIC_FUNC1(ATFReader_obj,_hx___readUInt32,return )
hx::ObjectPtr< ATFReader_obj > ATFReader_obj::__new( ::openfl::utils::ByteArrayData data,int byteArrayOffset) {
hx::ObjectPtr< ATFReader_obj > __this = new ATFReader_obj();
__this->__construct(data,byteArrayOffset);
return __this;
}
hx::ObjectPtr< ATFReader_obj > ATFReader_obj::__alloc(hx::Ctx *_hx_ctx, ::openfl::utils::ByteArrayData data,int byteArrayOffset) {
ATFReader_obj *__this = (ATFReader_obj*)(hx::Ctx::alloc(_hx_ctx, sizeof(ATFReader_obj), true, "openfl._internal.stage3D.atf.ATFReader"));
*(void **)__this = ATFReader_obj::_hx_vtable;
__this->__construct(data,byteArrayOffset);
return __this;
}
ATFReader_obj::ATFReader_obj()
{
}
void ATFReader_obj::__Mark(HX_MARK_PARAMS)
{
HX_MARK_BEGIN_CLASS(ATFReader);
HX_MARK_MEMBER_NAME(atfFormat,"atfFormat");
HX_MARK_MEMBER_NAME(cubeMap,"cubeMap");
HX_MARK_MEMBER_NAME(data,"data");
HX_MARK_MEMBER_NAME(height,"height");
HX_MARK_MEMBER_NAME(mipCount,"mipCount");
HX_MARK_MEMBER_NAME(version,"version");
HX_MARK_MEMBER_NAME(width,"width");
HX_MARK_END_CLASS();
}
void ATFReader_obj::__Visit(HX_VISIT_PARAMS)
{
HX_VISIT_MEMBER_NAME(atfFormat,"atfFormat");
HX_VISIT_MEMBER_NAME(cubeMap,"cubeMap");
HX_VISIT_MEMBER_NAME(data,"data");
HX_VISIT_MEMBER_NAME(height,"height");
HX_VISIT_MEMBER_NAME(mipCount,"mipCount");
HX_VISIT_MEMBER_NAME(version,"version");
HX_VISIT_MEMBER_NAME(width,"width");
}
hx::Val ATFReader_obj::__Field(const ::String &inName,hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 4:
if (HX_FIELD_EQ(inName,"data") ) { return hx::Val( data ); }
break;
case 5:
if (HX_FIELD_EQ(inName,"width") ) { return hx::Val( width ); }
break;
case 6:
if (HX_FIELD_EQ(inName,"height") ) { return hx::Val( height ); }
break;
case 7:
if (HX_FIELD_EQ(inName,"cubeMap") ) { return hx::Val( cubeMap ); }
if (HX_FIELD_EQ(inName,"version") ) { return hx::Val( version ); }
break;
case 8:
if (HX_FIELD_EQ(inName,"mipCount") ) { return hx::Val( mipCount ); }
break;
case 9:
if (HX_FIELD_EQ(inName,"atfFormat") ) { return hx::Val( atfFormat ); }
break;
case 10:
if (HX_FIELD_EQ(inName,"readHeader") ) { return hx::Val( readHeader_dyn() ); }
break;
case 12:
if (HX_FIELD_EQ(inName,"readTextures") ) { return hx::Val( readTextures_dyn() ); }
if (HX_FIELD_EQ(inName,"__readUInt24") ) { return hx::Val( _hx___readUInt24_dyn() ); }
if (HX_FIELD_EQ(inName,"__readUInt32") ) { return hx::Val( _hx___readUInt32_dyn() ); }
}
return super::__Field(inName,inCallProp);
}
hx::Val ATFReader_obj::__SetField(const ::String &inName,const hx::Val &inValue,hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 4:
if (HX_FIELD_EQ(inName,"data") ) { data=inValue.Cast< ::openfl::utils::ByteArrayData >(); return inValue; }
break;
case 5:
if (HX_FIELD_EQ(inName,"width") ) { width=inValue.Cast< int >(); return inValue; }
break;
case 6:
if (HX_FIELD_EQ(inName,"height") ) { height=inValue.Cast< int >(); return inValue; }
break;
case 7:
if (HX_FIELD_EQ(inName,"cubeMap") ) { cubeMap=inValue.Cast< bool >(); return inValue; }
if (HX_FIELD_EQ(inName,"version") ) { version=inValue.Cast< int >(); return inValue; }
break;
case 8:
if (HX_FIELD_EQ(inName,"mipCount") ) { mipCount=inValue.Cast< int >(); return inValue; }
break;
case 9:
if (HX_FIELD_EQ(inName,"atfFormat") ) { atfFormat=inValue.Cast< int >(); return inValue; }
}
return super::__SetField(inName,inValue,inCallProp);
}
void ATFReader_obj::__GetFields(Array< ::String> &outFields)
{
outFields->push(HX_HCSTRING("atfFormat","\xaa","\xd3","\x04","\x9c"));
outFields->push(HX_HCSTRING("cubeMap","\xa7","\x4c","\xd0","\x8c"));
outFields->push(HX_HCSTRING("data","\x2a","\x56","\x63","\x42"));
outFields->push(HX_HCSTRING("height","\xe7","\x07","\x4c","\x02"));
outFields->push(HX_HCSTRING("mipCount","\x9b","\x6a","\x51","\x0e"));
outFields->push(HX_HCSTRING("version","\x18","\xe7","\xf1","\x7c"));
outFields->push(HX_HCSTRING("width","\x06","\xb6","\x62","\xca"));
super::__GetFields(outFields);
};
#if HXCPP_SCRIPTABLE
static hx::StorageInfo ATFReader_obj_sMemberStorageInfo[] = {
{hx::fsInt,(int)offsetof(ATFReader_obj,atfFormat),HX_HCSTRING("atfFormat","\xaa","\xd3","\x04","\x9c")},
{hx::fsBool,(int)offsetof(ATFReader_obj,cubeMap),HX_HCSTRING("cubeMap","\xa7","\x4c","\xd0","\x8c")},
{hx::fsObject /*::openfl::utils::ByteArrayData*/ ,(int)offsetof(ATFReader_obj,data),HX_HCSTRING("data","\x2a","\x56","\x63","\x42")},
{hx::fsInt,(int)offsetof(ATFReader_obj,height),HX_HCSTRING("height","\xe7","\x07","\x4c","\x02")},
{hx::fsInt,(int)offsetof(ATFReader_obj,mipCount),HX_HCSTRING("mipCount","\x9b","\x6a","\x51","\x0e")},
{hx::fsInt,(int)offsetof(ATFReader_obj,version),HX_HCSTRING("version","\x18","\xe7","\xf1","\x7c")},
{hx::fsInt,(int)offsetof(ATFReader_obj,width),HX_HCSTRING("width","\x06","\xb6","\x62","\xca")},
{ hx::fsUnknown, 0, null()}
};
static hx::StaticInfo *ATFReader_obj_sStaticStorageInfo = 0;
#endif
static ::String ATFReader_obj_sMemberFields[] = {
HX_HCSTRING("atfFormat","\xaa","\xd3","\x04","\x9c"),
HX_HCSTRING("cubeMap","\xa7","\x4c","\xd0","\x8c"),
HX_HCSTRING("data","\x2a","\x56","\x63","\x42"),
HX_HCSTRING("height","\xe7","\x07","\x4c","\x02"),
HX_HCSTRING("mipCount","\x9b","\x6a","\x51","\x0e"),
HX_HCSTRING("version","\x18","\xe7","\xf1","\x7c"),
HX_HCSTRING("width","\x06","\xb6","\x62","\xca"),
HX_HCSTRING("readHeader","\x83","\xed","\x7b","\xf6"),
HX_HCSTRING("readTextures","\xae","\x44","\x04","\xa1"),
HX_HCSTRING("__readUInt24","\xd2","\x98","\x1e","\x4b"),
HX_HCSTRING("__readUInt32","\xaf","\x99","\x1e","\x4b"),
::String(null()) };
static void ATFReader_obj_sMarkStatics(HX_MARK_PARAMS) {
HX_MARK_MEMBER_NAME(ATFReader_obj::__mClass,"__mClass");
};
#ifdef HXCPP_VISIT_ALLOCS
static void ATFReader_obj_sVisitStatics(HX_VISIT_PARAMS) {
HX_VISIT_MEMBER_NAME(ATFReader_obj::__mClass,"__mClass");
};
#endif
hx::Class ATFReader_obj::__mClass;
void ATFReader_obj::__register()
{
hx::Object *dummy = new ATFReader_obj;
ATFReader_obj::_hx_vtable = *(void **)dummy;
hx::Static(__mClass) = new hx::Class_obj();
__mClass->mName = HX_HCSTRING("openfl._internal.stage3D.atf.ATFReader","\x8c","\x6b","\x52","\x5f");
__mClass->mSuper = &super::__SGetClass();
__mClass->mConstructEmpty = &__CreateEmpty;
__mClass->mConstructArgs = &__Create;
__mClass->mGetStaticField = &hx::Class_obj::GetNoStaticField;
__mClass->mSetStaticField = &hx::Class_obj::SetNoStaticField;
__mClass->mMarkFunc = ATFReader_obj_sMarkStatics;
__mClass->mStatics = hx::Class_obj::dupFunctions(0 /* sStaticFields */);
__mClass->mMembers = hx::Class_obj::dupFunctions(ATFReader_obj_sMemberFields);
__mClass->mCanCast = hx::TCanCast< ATFReader_obj >;
#ifdef HXCPP_VISIT_ALLOCS
__mClass->mVisitFunc = ATFReader_obj_sVisitStatics;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mMemberStorageInfo = ATFReader_obj_sMemberStorageInfo;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mStaticStorageInfo = ATFReader_obj_sStaticStorageInfo;
#endif
hx::_hx_RegisterClass(__mClass->mName, __mClass);
}
} // end namespace openfl
} // end namespace _internal
} // end namespace stage3D
} // end namespace atf
| 41.86215 | 274 | 0.673718 |
12f5591da05d6c59955f5a184bef2c6547d7eee4 | 1,465 | cpp | C++ | gym/100283/I.cpp | albexl/codeforces-gym-submissions | 2a51905c50fcf5d7f417af81c4c49ca5217d0753 | [
"MIT"
] | 1 | 2021-07-16T19:59:39.000Z | 2021-07-16T19:59:39.000Z | gym/100283/I.cpp | albexl/codeforces-gym-submissions | 2a51905c50fcf5d7f417af81c4c49ca5217d0753 | [
"MIT"
] | null | null | null | gym/100283/I.cpp | albexl/codeforces-gym-submissions | 2a51905c50fcf5d7f417af81c4c49ca5217d0753 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
#ifdef Adrian
#include "debug.h"
#else
#define debug(...)
#endif
typedef long long ll;
typedef long double ld;
typedef complex<ll> point;
#define F first
#define S second
const double EPS=1e-8,oo=1e9;
struct fraction
{
ll x,y;
fraction(ll _x, ll _y)
{
ll g = __gcd(_x,_y);
x = _x / g;
y = _y / g;
}
bool operator <(const fraction other)const
{
return x * other.y < y * other.x;
}
fraction operator -(fraction other)
{
return fraction(other.y * x - other.x * y, y * other.y);
}
fraction operator +(fraction other)
{
return fraction(other.y * x + other.x * y, y * other.y);
}
void print()
{
cout<<x<<"/"<<y<<'\n';
}
};
void generate(vector<fraction> &v, ll pos, fraction f)
{
if(f.x != 0)
v.push_back(f);
if(pos == 14) return;
for(ll i = 0; i<pos; i++)
{
fraction temp = f + fraction(i,pos);
if(temp < fraction(1,1))
generate(v, pos + 1, temp);
}
}
int main()
{
freopen("zanzibar.in", "r", stdin);
ios_base::sync_with_stdio(0), cin.tie(0);
vector<fraction> v;
generate(v, 2, fraction(0, 1));
v.push_back(fraction(1,1));
v.push_back(fraction(0,1));
sort(v.begin(), v.end());
int t;
cin>>t;
for(int c = 1; c<=t; c++)
{
ll x,y;
cin>>x>>y;
fraction f(x,y);
int pos = lower_bound(v.begin(), v.end(), f) - v.begin();
fraction ans = v[pos] - f;
if(pos != 0)
ans = min(ans, f - v[pos - 1]);
cout<<"Case "<<c<<": ";
ans.print();
}
return 0;
} | 16.647727 | 59 | 0.585666 |
12f7be9f7629a42b832273f37c6216f2e392e102 | 40,235 | cpp | C++ | aes_fast.cpp | s0uthwood/CNSPP-lab | 75700c5807834972756001f4aea79542d5c29485 | [
"MIT"
] | null | null | null | aes_fast.cpp | s0uthwood/CNSPP-lab | 75700c5807834972756001f4aea79542d5c29485 | [
"MIT"
] | null | null | null | aes_fast.cpp | s0uthwood/CNSPP-lab | 75700c5807834972756001f4aea79542d5c29485 | [
"MIT"
] | 1 | 2021-12-25T15:40:06.000Z | 2021-12-25T15:40:06.000Z | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <emmintrin.h>
#include <time.h>
int aes_sbox[256] = {
0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76,
0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,
0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,
0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,
0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,
0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,
0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,
0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,
0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,
0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16
};
int aes_sbox_inv[256] = {
0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb,
0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb,
0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e,
0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25,
0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92,
0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84,
0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06,
0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b,
0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73,
0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e,
0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b,
0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4,
0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f,
0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef,
0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61,
0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d
};
unsigned int TBOX0[256] = {
0xa56363c6, 0x847c7cf8, 0x997777ee, 0x8d7b7bf6, 0x0df2f2ff, 0xbd6b6bd6, 0xb16f6fde, 0x54c5c591, 0x50303060, 0x03010102, 0xa96767ce, 0x7d2b2b56, 0x19fefee7, 0x62d7d7b5, 0xe6abab4d, 0x9a7676ec,
0x45caca8f, 0x9d82821f, 0x40c9c989, 0x877d7dfa, 0x15fafaef, 0xeb5959b2, 0xc947478e, 0x0bf0f0fb, 0xecadad41, 0x67d4d4b3, 0xfda2a25f, 0xeaafaf45, 0xbf9c9c23, 0xf7a4a453, 0x967272e4, 0x5bc0c09b,
0xc2b7b775, 0x1cfdfde1, 0xae93933d, 0x6a26264c, 0x5a36366c, 0x413f3f7e, 0x02f7f7f5, 0x4fcccc83, 0x5c343468, 0xf4a5a551, 0x34e5e5d1, 0x08f1f1f9, 0x937171e2, 0x73d8d8ab, 0x53313162, 0x3f15152a,
0x0c040408, 0x52c7c795, 0x65232346, 0x5ec3c39d, 0x28181830, 0xa1969637, 0x0f05050a, 0xb59a9a2f, 0x0907070e, 0x36121224, 0x9b80801b, 0x3de2e2df, 0x26ebebcd, 0x6927274e, 0xcdb2b27f, 0x9f7575ea,
0x1b090912, 0x9e83831d, 0x742c2c58, 0x2e1a1a34, 0x2d1b1b36, 0xb26e6edc, 0xee5a5ab4, 0xfba0a05b, 0xf65252a4, 0x4d3b3b76, 0x61d6d6b7, 0xceb3b37d, 0x7b292952, 0x3ee3e3dd, 0x712f2f5e, 0x97848413,
0xf55353a6, 0x68d1d1b9, 0x00000000, 0x2cededc1, 0x60202040, 0x1ffcfce3, 0xc8b1b179, 0xed5b5bb6, 0xbe6a6ad4, 0x46cbcb8d, 0xd9bebe67, 0x4b393972, 0xde4a4a94, 0xd44c4c98, 0xe85858b0, 0x4acfcf85,
0x6bd0d0bb, 0x2aefefc5, 0xe5aaaa4f, 0x16fbfbed, 0xc5434386, 0xd74d4d9a, 0x55333366, 0x94858511, 0xcf45458a, 0x10f9f9e9, 0x06020204, 0x817f7ffe, 0xf05050a0, 0x443c3c78, 0xba9f9f25, 0xe3a8a84b,
0xf35151a2, 0xfea3a35d, 0xc0404080, 0x8a8f8f05, 0xad92923f, 0xbc9d9d21, 0x48383870, 0x04f5f5f1, 0xdfbcbc63, 0xc1b6b677, 0x75dadaaf, 0x63212142, 0x30101020, 0x1affffe5, 0x0ef3f3fd, 0x6dd2d2bf,
0x4ccdcd81, 0x140c0c18, 0x35131326, 0x2fececc3, 0xe15f5fbe, 0xa2979735, 0xcc444488, 0x3917172e, 0x57c4c493, 0xf2a7a755, 0x827e7efc, 0x473d3d7a, 0xac6464c8, 0xe75d5dba, 0x2b191932, 0x957373e6,
0xa06060c0, 0x98818119, 0xd14f4f9e, 0x7fdcdca3, 0x66222244, 0x7e2a2a54, 0xab90903b, 0x8388880b, 0xca46468c, 0x29eeeec7, 0xd3b8b86b, 0x3c141428, 0x79dedea7, 0xe25e5ebc, 0x1d0b0b16, 0x76dbdbad,
0x3be0e0db, 0x56323264, 0x4e3a3a74, 0x1e0a0a14, 0xdb494992, 0x0a06060c, 0x6c242448, 0xe45c5cb8, 0x5dc2c29f, 0x6ed3d3bd, 0xefacac43, 0xa66262c4, 0xa8919139, 0xa4959531, 0x37e4e4d3, 0x8b7979f2,
0x32e7e7d5, 0x43c8c88b, 0x5937376e, 0xb76d6dda, 0x8c8d8d01, 0x64d5d5b1, 0xd24e4e9c, 0xe0a9a949, 0xb46c6cd8, 0xfa5656ac, 0x07f4f4f3, 0x25eaeacf, 0xaf6565ca, 0x8e7a7af4, 0xe9aeae47, 0x18080810,
0xd5baba6f, 0x887878f0, 0x6f25254a, 0x722e2e5c, 0x241c1c38, 0xf1a6a657, 0xc7b4b473, 0x51c6c697, 0x23e8e8cb, 0x7cdddda1, 0x9c7474e8, 0x211f1f3e, 0xdd4b4b96, 0xdcbdbd61, 0x868b8b0d, 0x858a8a0f,
0x907070e0, 0x423e3e7c, 0xc4b5b571, 0xaa6666cc, 0xd8484890, 0x05030306, 0x01f6f6f7, 0x120e0e1c, 0xa36161c2, 0x5f35356a, 0xf95757ae, 0xd0b9b969, 0x91868617, 0x58c1c199, 0x271d1d3a, 0xb99e9e27,
0x38e1e1d9, 0x13f8f8eb, 0xb398982b, 0x33111122, 0xbb6969d2, 0x70d9d9a9, 0x898e8e07, 0xa7949433, 0xb69b9b2d, 0x221e1e3c, 0x92878715, 0x20e9e9c9, 0x49cece87, 0xff5555aa, 0x78282850, 0x7adfdfa5,
0x8f8c8c03, 0xf8a1a159, 0x80898909, 0x170d0d1a, 0xdabfbf65, 0x31e6e6d7, 0xc6424284, 0xb86868d0, 0xc3414182, 0xb0999929, 0x772d2d5a, 0x110f0f1e, 0xcbb0b07b, 0xfc5454a8, 0xd6bbbb6d, 0x3a16162c
};
unsigned int TBOX1[256] = {
0x6363c6a5, 0x7c7cf884, 0x7777ee99, 0x7b7bf68d, 0xf2f2ff0d, 0x6b6bd6bd, 0x6f6fdeb1, 0xc5c59154, 0x30306050, 0x01010203, 0x6767cea9, 0x2b2b567d, 0xfefee719, 0xd7d7b562, 0xabab4de6, 0x7676ec9a,
0xcaca8f45, 0x82821f9d, 0xc9c98940, 0x7d7dfa87, 0xfafaef15, 0x5959b2eb, 0x47478ec9, 0xf0f0fb0b, 0xadad41ec, 0xd4d4b367, 0xa2a25ffd, 0xafaf45ea, 0x9c9c23bf, 0xa4a453f7, 0x7272e496, 0xc0c09b5b,
0xb7b775c2, 0xfdfde11c, 0x93933dae, 0x26264c6a, 0x36366c5a, 0x3f3f7e41, 0xf7f7f502, 0xcccc834f, 0x3434685c, 0xa5a551f4, 0xe5e5d134, 0xf1f1f908, 0x7171e293, 0xd8d8ab73, 0x31316253, 0x15152a3f,
0x0404080c, 0xc7c79552, 0x23234665, 0xc3c39d5e, 0x18183028, 0x969637a1, 0x05050a0f, 0x9a9a2fb5, 0x07070e09, 0x12122436, 0x80801b9b, 0xe2e2df3d, 0xebebcd26, 0x27274e69, 0xb2b27fcd, 0x7575ea9f,
0x0909121b, 0x83831d9e, 0x2c2c5874, 0x1a1a342e, 0x1b1b362d, 0x6e6edcb2, 0x5a5ab4ee, 0xa0a05bfb, 0x5252a4f6, 0x3b3b764d, 0xd6d6b761, 0xb3b37dce, 0x2929527b, 0xe3e3dd3e, 0x2f2f5e71, 0x84841397,
0x5353a6f5, 0xd1d1b968, 0x00000000, 0xededc12c, 0x20204060, 0xfcfce31f, 0xb1b179c8, 0x5b5bb6ed, 0x6a6ad4be, 0xcbcb8d46, 0xbebe67d9, 0x3939724b, 0x4a4a94de, 0x4c4c98d4, 0x5858b0e8, 0xcfcf854a,
0xd0d0bb6b, 0xefefc52a, 0xaaaa4fe5, 0xfbfbed16, 0x434386c5, 0x4d4d9ad7, 0x33336655, 0x85851194, 0x45458acf, 0xf9f9e910, 0x02020406, 0x7f7ffe81, 0x5050a0f0, 0x3c3c7844, 0x9f9f25ba, 0xa8a84be3,
0x5151a2f3, 0xa3a35dfe, 0x404080c0, 0x8f8f058a, 0x92923fad, 0x9d9d21bc, 0x38387048, 0xf5f5f104, 0xbcbc63df, 0xb6b677c1, 0xdadaaf75, 0x21214263, 0x10102030, 0xffffe51a, 0xf3f3fd0e, 0xd2d2bf6d,
0xcdcd814c, 0x0c0c1814, 0x13132635, 0xececc32f, 0x5f5fbee1, 0x979735a2, 0x444488cc, 0x17172e39, 0xc4c49357, 0xa7a755f2, 0x7e7efc82, 0x3d3d7a47, 0x6464c8ac, 0x5d5dbae7, 0x1919322b, 0x7373e695,
0x6060c0a0, 0x81811998, 0x4f4f9ed1, 0xdcdca37f, 0x22224466, 0x2a2a547e, 0x90903bab, 0x88880b83, 0x46468cca, 0xeeeec729, 0xb8b86bd3, 0x1414283c, 0xdedea779, 0x5e5ebce2, 0x0b0b161d, 0xdbdbad76,
0xe0e0db3b, 0x32326456, 0x3a3a744e, 0x0a0a141e, 0x494992db, 0x06060c0a, 0x2424486c, 0x5c5cb8e4, 0xc2c29f5d, 0xd3d3bd6e, 0xacac43ef, 0x6262c4a6, 0x919139a8, 0x959531a4, 0xe4e4d337, 0x7979f28b,
0xe7e7d532, 0xc8c88b43, 0x37376e59, 0x6d6ddab7, 0x8d8d018c, 0xd5d5b164, 0x4e4e9cd2, 0xa9a949e0, 0x6c6cd8b4, 0x5656acfa, 0xf4f4f307, 0xeaeacf25, 0x6565caaf, 0x7a7af48e, 0xaeae47e9, 0x08081018,
0xbaba6fd5, 0x7878f088, 0x25254a6f, 0x2e2e5c72, 0x1c1c3824, 0xa6a657f1, 0xb4b473c7, 0xc6c69751, 0xe8e8cb23, 0xdddda17c, 0x7474e89c, 0x1f1f3e21, 0x4b4b96dd, 0xbdbd61dc, 0x8b8b0d86, 0x8a8a0f85,
0x7070e090, 0x3e3e7c42, 0xb5b571c4, 0x6666ccaa, 0x484890d8, 0x03030605, 0xf6f6f701, 0x0e0e1c12, 0x6161c2a3, 0x35356a5f, 0x5757aef9, 0xb9b969d0, 0x86861791, 0xc1c19958, 0x1d1d3a27, 0x9e9e27b9,
0xe1e1d938, 0xf8f8eb13, 0x98982bb3, 0x11112233, 0x6969d2bb, 0xd9d9a970, 0x8e8e0789, 0x949433a7, 0x9b9b2db6, 0x1e1e3c22, 0x87871592, 0xe9e9c920, 0xcece8749, 0x5555aaff, 0x28285078, 0xdfdfa57a,
0x8c8c038f, 0xa1a159f8, 0x89890980, 0x0d0d1a17, 0xbfbf65da, 0xe6e6d731, 0x424284c6, 0x6868d0b8, 0x414182c3, 0x999929b0, 0x2d2d5a77, 0x0f0f1e11, 0xb0b07bcb, 0x5454a8fc, 0xbbbb6dd6, 0x16162c3a
};
unsigned int TBOX2[256] = {
0x63c6a563, 0x7cf8847c, 0x77ee9977, 0x7bf68d7b, 0xf2ff0df2, 0x6bd6bd6b, 0x6fdeb16f, 0xc59154c5, 0x30605030, 0x01020301, 0x67cea967, 0x2b567d2b, 0xfee719fe, 0xd7b562d7, 0xab4de6ab, 0x76ec9a76,
0xca8f45ca, 0x821f9d82, 0xc98940c9, 0x7dfa877d, 0xfaef15fa, 0x59b2eb59, 0x478ec947, 0xf0fb0bf0, 0xad41ecad, 0xd4b367d4, 0xa25ffda2, 0xaf45eaaf, 0x9c23bf9c, 0xa453f7a4, 0x72e49672, 0xc09b5bc0,
0xb775c2b7, 0xfde11cfd, 0x933dae93, 0x264c6a26, 0x366c5a36, 0x3f7e413f, 0xf7f502f7, 0xcc834fcc, 0x34685c34, 0xa551f4a5, 0xe5d134e5, 0xf1f908f1, 0x71e29371, 0xd8ab73d8, 0x31625331, 0x152a3f15,
0x04080c04, 0xc79552c7, 0x23466523, 0xc39d5ec3, 0x18302818, 0x9637a196, 0x050a0f05, 0x9a2fb59a, 0x070e0907, 0x12243612, 0x801b9b80, 0xe2df3de2, 0xebcd26eb, 0x274e6927, 0xb27fcdb2, 0x75ea9f75,
0x09121b09, 0x831d9e83, 0x2c58742c, 0x1a342e1a, 0x1b362d1b, 0x6edcb26e, 0x5ab4ee5a, 0xa05bfba0, 0x52a4f652, 0x3b764d3b, 0xd6b761d6, 0xb37dceb3, 0x29527b29, 0xe3dd3ee3, 0x2f5e712f, 0x84139784,
0x53a6f553, 0xd1b968d1, 0x00000000, 0xedc12ced, 0x20406020, 0xfce31ffc, 0xb179c8b1, 0x5bb6ed5b, 0x6ad4be6a, 0xcb8d46cb, 0xbe67d9be, 0x39724b39, 0x4a94de4a, 0x4c98d44c, 0x58b0e858, 0xcf854acf,
0xd0bb6bd0, 0xefc52aef, 0xaa4fe5aa, 0xfbed16fb, 0x4386c543, 0x4d9ad74d, 0x33665533, 0x85119485, 0x458acf45, 0xf9e910f9, 0x02040602, 0x7ffe817f, 0x50a0f050, 0x3c78443c, 0x9f25ba9f, 0xa84be3a8,
0x51a2f351, 0xa35dfea3, 0x4080c040, 0x8f058a8f, 0x923fad92, 0x9d21bc9d, 0x38704838, 0xf5f104f5, 0xbc63dfbc, 0xb677c1b6, 0xdaaf75da, 0x21426321, 0x10203010, 0xffe51aff, 0xf3fd0ef3, 0xd2bf6dd2,
0xcd814ccd, 0x0c18140c, 0x13263513, 0xecc32fec, 0x5fbee15f, 0x9735a297, 0x4488cc44, 0x172e3917, 0xc49357c4, 0xa755f2a7, 0x7efc827e, 0x3d7a473d, 0x64c8ac64, 0x5dbae75d, 0x19322b19, 0x73e69573,
0x60c0a060, 0x81199881, 0x4f9ed14f, 0xdca37fdc, 0x22446622, 0x2a547e2a, 0x903bab90, 0x880b8388, 0x468cca46, 0xeec729ee, 0xb86bd3b8, 0x14283c14, 0xdea779de, 0x5ebce25e, 0x0b161d0b, 0xdbad76db,
0xe0db3be0, 0x32645632, 0x3a744e3a, 0x0a141e0a, 0x4992db49, 0x060c0a06, 0x24486c24, 0x5cb8e45c, 0xc29f5dc2, 0xd3bd6ed3, 0xac43efac, 0x62c4a662, 0x9139a891, 0x9531a495, 0xe4d337e4, 0x79f28b79,
0xe7d532e7, 0xc88b43c8, 0x376e5937, 0x6ddab76d, 0x8d018c8d, 0xd5b164d5, 0x4e9cd24e, 0xa949e0a9, 0x6cd8b46c, 0x56acfa56, 0xf4f307f4, 0xeacf25ea, 0x65caaf65, 0x7af48e7a, 0xae47e9ae, 0x08101808,
0xba6fd5ba, 0x78f08878, 0x254a6f25, 0x2e5c722e, 0x1c38241c, 0xa657f1a6, 0xb473c7b4, 0xc69751c6, 0xe8cb23e8, 0xdda17cdd, 0x74e89c74, 0x1f3e211f, 0x4b96dd4b, 0xbd61dcbd, 0x8b0d868b, 0x8a0f858a,
0x70e09070, 0x3e7c423e, 0xb571c4b5, 0x66ccaa66, 0x4890d848, 0x03060503, 0xf6f701f6, 0x0e1c120e, 0x61c2a361, 0x356a5f35, 0x57aef957, 0xb969d0b9, 0x86179186, 0xc19958c1, 0x1d3a271d, 0x9e27b99e,
0xe1d938e1, 0xf8eb13f8, 0x982bb398, 0x11223311, 0x69d2bb69, 0xd9a970d9, 0x8e07898e, 0x9433a794, 0x9b2db69b, 0x1e3c221e, 0x87159287, 0xe9c920e9, 0xce8749ce, 0x55aaff55, 0x28507828, 0xdfa57adf,
0x8c038f8c, 0xa159f8a1, 0x89098089, 0x0d1a170d, 0xbf65dabf, 0xe6d731e6, 0x4284c642, 0x68d0b868, 0x4182c341, 0x9929b099, 0x2d5a772d, 0x0f1e110f, 0xb07bcbb0, 0x54a8fc54, 0xbb6dd6bb, 0x162c3a16
};
unsigned int TBOX3[256] = {
0xc6a56363, 0xf8847c7c, 0xee997777, 0xf68d7b7b, 0xff0df2f2, 0xd6bd6b6b, 0xdeb16f6f, 0x9154c5c5, 0x60503030, 0x02030101, 0xcea96767, 0x567d2b2b, 0xe719fefe, 0xb562d7d7, 0x4de6abab, 0xec9a7676,
0x8f45caca, 0x1f9d8282, 0x8940c9c9, 0xfa877d7d, 0xef15fafa, 0xb2eb5959, 0x8ec94747, 0xfb0bf0f0, 0x41ecadad, 0xb367d4d4, 0x5ffda2a2, 0x45eaafaf, 0x23bf9c9c, 0x53f7a4a4, 0xe4967272, 0x9b5bc0c0,
0x75c2b7b7, 0xe11cfdfd, 0x3dae9393, 0x4c6a2626, 0x6c5a3636, 0x7e413f3f, 0xf502f7f7, 0x834fcccc, 0x685c3434, 0x51f4a5a5, 0xd134e5e5, 0xf908f1f1, 0xe2937171, 0xab73d8d8, 0x62533131, 0x2a3f1515,
0x080c0404, 0x9552c7c7, 0x46652323, 0x9d5ec3c3, 0x30281818, 0x37a19696, 0x0a0f0505, 0x2fb59a9a, 0x0e090707, 0x24361212, 0x1b9b8080, 0xdf3de2e2, 0xcd26ebeb, 0x4e692727, 0x7fcdb2b2, 0xea9f7575,
0x121b0909, 0x1d9e8383, 0x58742c2c, 0x342e1a1a, 0x362d1b1b, 0xdcb26e6e, 0xb4ee5a5a, 0x5bfba0a0, 0xa4f65252, 0x764d3b3b, 0xb761d6d6, 0x7dceb3b3, 0x527b2929, 0xdd3ee3e3, 0x5e712f2f, 0x13978484,
0xa6f55353, 0xb968d1d1, 0x00000000, 0xc12ceded, 0x40602020, 0xe31ffcfc, 0x79c8b1b1, 0xb6ed5b5b, 0xd4be6a6a, 0x8d46cbcb, 0x67d9bebe, 0x724b3939, 0x94de4a4a, 0x98d44c4c, 0xb0e85858, 0x854acfcf,
0xbb6bd0d0, 0xc52aefef, 0x4fe5aaaa, 0xed16fbfb, 0x86c54343, 0x9ad74d4d, 0x66553333, 0x11948585, 0x8acf4545, 0xe910f9f9, 0x04060202, 0xfe817f7f, 0xa0f05050, 0x78443c3c, 0x25ba9f9f, 0x4be3a8a8,
0xa2f35151, 0x5dfea3a3, 0x80c04040, 0x058a8f8f, 0x3fad9292, 0x21bc9d9d, 0x70483838, 0xf104f5f5, 0x63dfbcbc, 0x77c1b6b6, 0xaf75dada, 0x42632121, 0x20301010, 0xe51affff, 0xfd0ef3f3, 0xbf6dd2d2,
0x814ccdcd, 0x18140c0c, 0x26351313, 0xc32fecec, 0xbee15f5f, 0x35a29797, 0x88cc4444, 0x2e391717, 0x9357c4c4, 0x55f2a7a7, 0xfc827e7e, 0x7a473d3d, 0xc8ac6464, 0xbae75d5d, 0x322b1919, 0xe6957373,
0xc0a06060, 0x19988181, 0x9ed14f4f, 0xa37fdcdc, 0x44662222, 0x547e2a2a, 0x3bab9090, 0x0b838888, 0x8cca4646, 0xc729eeee, 0x6bd3b8b8, 0x283c1414, 0xa779dede, 0xbce25e5e, 0x161d0b0b, 0xad76dbdb,
0xdb3be0e0, 0x64563232, 0x744e3a3a, 0x141e0a0a, 0x92db4949, 0x0c0a0606, 0x486c2424, 0xb8e45c5c, 0x9f5dc2c2, 0xbd6ed3d3, 0x43efacac, 0xc4a66262, 0x39a89191, 0x31a49595, 0xd337e4e4, 0xf28b7979,
0xd532e7e7, 0x8b43c8c8, 0x6e593737, 0xdab76d6d, 0x018c8d8d, 0xb164d5d5, 0x9cd24e4e, 0x49e0a9a9, 0xd8b46c6c, 0xacfa5656, 0xf307f4f4, 0xcf25eaea, 0xcaaf6565, 0xf48e7a7a, 0x47e9aeae, 0x10180808,
0x6fd5baba, 0xf0887878, 0x4a6f2525, 0x5c722e2e, 0x38241c1c, 0x57f1a6a6, 0x73c7b4b4, 0x9751c6c6, 0xcb23e8e8, 0xa17cdddd, 0xe89c7474, 0x3e211f1f, 0x96dd4b4b, 0x61dcbdbd, 0x0d868b8b, 0x0f858a8a,
0xe0907070, 0x7c423e3e, 0x71c4b5b5, 0xccaa6666, 0x90d84848, 0x06050303, 0xf701f6f6, 0x1c120e0e, 0xc2a36161, 0x6a5f3535, 0xaef95757, 0x69d0b9b9, 0x17918686, 0x9958c1c1, 0x3a271d1d, 0x27b99e9e,
0xd938e1e1, 0xeb13f8f8, 0x2bb39898, 0x22331111, 0xd2bb6969, 0xa970d9d9, 0x07898e8e, 0x33a79494, 0x2db69b9b, 0x3c221e1e, 0x15928787, 0xc920e9e9, 0x8749cece, 0xaaff5555, 0x50782828, 0xa57adfdf,
0x038f8c8c, 0x59f8a1a1, 0x09808989, 0x1a170d0d, 0x65dabfbf, 0xd731e6e6, 0x84c64242, 0xd0b86868, 0x82c34141, 0x29b09999, 0x5a772d2d, 0x1e110f0f, 0x7bcbb0b0, 0xa8fc5454, 0x6dd6bbbb, 0x2c3a1616,
};
unsigned int deTBOX0[256] = {
0x50a7f451, 0x5365417e, 0xc3a4171a, 0x965e273a, 0xcb6bab3b, 0xf1459d1f, 0xab58faac, 0x9303e34b, 0x55fa3020, 0xf66d76ad, 0x9176cc88, 0x254c02f5, 0xfcd7e54f, 0xd7cb2ac5, 0x80443526, 0x8fa362b5,
0x495ab1de, 0x671bba25, 0x980eea45, 0xe1c0fe5d, 0x02752fc3, 0x12f04c81, 0xa397468d, 0xc6f9d36b, 0xe75f8f03, 0x959c9215, 0xeb7a6dbf, 0xda595295, 0x2d83bed4, 0xd3217458, 0x2969e049, 0x44c8c98e,
0x6a89c275, 0x78798ef4, 0x6b3e5899, 0xdd71b927, 0xb64fe1be, 0x17ad88f0, 0x66ac20c9, 0xb43ace7d, 0x184adf63, 0x82311ae5, 0x60335197, 0x457f5362, 0xe07764b1, 0x84ae6bbb, 0x1ca081fe, 0x942b08f9,
0x58684870, 0x19fd458f, 0x876cde94, 0xb7f87b52, 0x23d373ab, 0xe2024b72, 0x578f1fe3, 0x2aab5566, 0x0728ebb2, 0x03c2b52f, 0x9a7bc586, 0xa50837d3, 0xf2872830, 0xb2a5bf23, 0xba6a0302, 0x5c8216ed,
0x2b1ccf8a, 0x92b479a7, 0xf0f207f3, 0xa1e2694e, 0xcdf4da65, 0xd5be0506, 0x1f6234d1, 0x8afea6c4, 0x9d532e34, 0xa055f3a2, 0x32e18a05, 0x75ebf6a4, 0x39ec830b, 0xaaef6040, 0x069f715e, 0x51106ebd,
0xf98a213e, 0x3d06dd96, 0xae053edd, 0x46bde64d, 0xb58d5491, 0x055dc471, 0x6fd40604, 0xff155060, 0x24fb9819, 0x97e9bdd6, 0xcc434089, 0x779ed967, 0xbd42e8b0, 0x888b8907, 0x385b19e7, 0xdbeec879,
0x470a7ca1, 0xe90f427c, 0xc91e84f8, 0x00000000, 0x83868009, 0x48ed2b32, 0xac70111e, 0x4e725a6c, 0xfbff0efd, 0x5638850f, 0x1ed5ae3d, 0x27392d36, 0x64d90f0a, 0x21a65c68, 0xd1545b9b, 0x3a2e3624,
0xb1670a0c, 0x0fe75793, 0xd296eeb4, 0x9e919b1b, 0x4fc5c080, 0xa220dc61, 0x694b775a, 0x161a121c, 0x0aba93e2, 0xe52aa0c0, 0x43e0223c, 0x1d171b12, 0x0b0d090e, 0xadc78bf2, 0xb9a8b62d, 0xc8a91e14,
0x8519f157, 0x4c0775af, 0xbbdd99ee, 0xfd607fa3, 0x9f2601f7, 0xbcf5725c, 0xc53b6644, 0x347efb5b, 0x7629438b, 0xdcc623cb, 0x68fcedb6, 0x63f1e4b8, 0xcadc31d7, 0x10856342, 0x40229713, 0x2011c684,
0x7d244a85, 0xf83dbbd2, 0x1132f9ae, 0x6da129c7, 0x4b2f9e1d, 0xf330b2dc, 0xec52860d, 0xd0e3c177, 0x6c16b32b, 0x99b970a9, 0xfa489411, 0x2264e947, 0xc48cfca8, 0x1a3ff0a0, 0xd82c7d56, 0xef903322,
0xc74e4987, 0xc1d138d9, 0xfea2ca8c, 0x360bd498, 0xcf81f5a6, 0x28de7aa5, 0x268eb7da, 0xa4bfad3f, 0xe49d3a2c, 0x0d927850, 0x9bcc5f6a, 0x62467e54, 0xc2138df6, 0xe8b8d890, 0x5ef7392e, 0xf5afc382,
0xbe805d9f, 0x7c93d069, 0xa92dd56f, 0xb31225cf, 0x3b99acc8, 0xa77d1810, 0x6e639ce8, 0x7bbb3bdb, 0x097826cd, 0xf418596e, 0x01b79aec, 0xa89a4f83, 0x656e95e6, 0x7ee6ffaa, 0x08cfbc21, 0xe6e815ef,
0xd99be7ba, 0xce366f4a, 0xd4099fea, 0xd67cb029, 0xafb2a431, 0x31233f2a, 0x3094a5c6, 0xc066a235, 0x37bc4e74, 0xa6ca82fc, 0xb0d090e0, 0x15d8a733, 0x4a9804f1, 0xf7daec41, 0x0e50cd7f, 0x2ff69117,
0x8dd64d76, 0x4db0ef43, 0x544daacc, 0xdf0496e4, 0xe3b5d19e, 0x1b886a4c, 0xb81f2cc1, 0x7f516546, 0x04ea5e9d, 0x5d358c01, 0x737487fa, 0x2e410bfb, 0x5a1d67b3, 0x52d2db92, 0x335610e9, 0x1347d66d,
0x8c61d79a, 0x7a0ca137, 0x8e14f859, 0x893c13eb, 0xee27a9ce, 0x35c961b7, 0xede51ce1, 0x3cb1477a, 0x59dfd29c, 0x3f73f255, 0x79ce1418, 0xbf37c773, 0xeacdf753, 0x5baafd5f, 0x146f3ddf, 0x86db4478,
0x81f3afca, 0x3ec468b9, 0x2c342438, 0x5f40a3c2, 0x72c31d16, 0x0c25e2bc, 0x8b493c28, 0x41950dff, 0x7101a839, 0xdeb30c08, 0x9ce4b4d8, 0x90c15664, 0x6184cb7b, 0x70b632d5, 0x745c6c48, 0x4257b8d0
};
unsigned int deTBOX1[256] = {
0xa7f45150, 0x65417e53, 0xa4171ac3, 0x5e273a96, 0x6bab3bcb, 0x459d1ff1, 0x58faacab, 0x03e34b93, 0x0fa32055, 0x6d76adf6, 0x76cc8891, 0x4c02f525, 0xd7e54ffc, 0xcb2ac5d7, 0x44352680, 0xa362b58f,
0x5ab1de49, 0x1bba2567, 0x0eea4598, 0xc0fe5de1, 0x752fc302, 0xf04c8112, 0x97468da3, 0xf9d36bc6, 0x5f8f03e7, 0x9c921595, 0x7a6dbfeb, 0x595295da, 0x83bed42d, 0x217458d3, 0x69e04929, 0xc8c98e44,
0x89c2756a, 0x798ef478, 0x3e58996b, 0x71b927dd, 0x4fe1beb6, 0xad88f017, 0xac20c966, 0x3ace7db4, 0x4adf6318, 0x311ae582, 0x33519760, 0x7f536245, 0x7764b1e0, 0xae6bbb84, 0xa081fe1c, 0x2b08f994,
0x68487058, 0xfd458f19, 0x6cde9487, 0xf87b52b7, 0xd373ab23, 0x024b72e2, 0x8f1fe357, 0xab55662a, 0x28ebb207, 0xc2b52f03, 0x7bc5869a, 0x0837d3a5, 0x872830f2, 0xa5bf23b2, 0x6a0302ba, 0x8216ed5c,
0x1ccf8a2b, 0xb479a792, 0xf207f3f0, 0xe2694ea1, 0xf4da65cd, 0xbe0506d5, 0x6234d11f, 0xfea6c48a, 0x532e349d, 0x55f3a2a0, 0xe18a0532, 0xebf6a475, 0xec830b39, 0xef6040aa, 0x9f715e06, 0x106ebd51,
0x8a213ef9, 0x06dd963d, 0x053eddae, 0xbde64d46, 0x8d5491b5, 0x5dc47105, 0xd406046f, 0x155060ff, 0xfb981924, 0xe9bdd697, 0x434089cc, 0x9ed96777, 0x42e8b0bd, 0x8b890788, 0x5b19e738, 0xeec879db,
0x0a7ca147, 0x0f427ce9, 0x1e84f8c9, 0x00000000, 0x86800983, 0xed2b3248, 0x70111eac, 0x725a6c4e, 0xff0efdfb, 0x38850f56, 0xd5ae3d1e, 0x392d3627, 0xd90f0a64, 0xa65c6821, 0x545b9bd1, 0x2e36243a,
0x670a0cb1, 0xe757930f, 0x96eeb4d2, 0x919b1b9e, 0xc5c0804f, 0x20dc61a2, 0x4b775a69, 0x1a121c16, 0xba93e20a, 0x2aa0c0e5, 0xe0223c43, 0x171b121d, 0x0d090e0b, 0xc78bf2ad, 0xa8b62db9, 0xa91e14c8,
0x19f15785, 0x0775af4c, 0xdd99eebb, 0x607fa3fd, 0x2601f79f, 0xf5725cbc, 0x3b6644c5, 0x7efb5b34, 0x29438b76, 0xc623cbdc, 0xfcedb668, 0xf1e4b863, 0xdc31d7ca, 0x85634210, 0x22971340, 0x11c68420,
0x244a857d, 0x3dbbd2f8, 0x32f9ae11, 0xa129c76d, 0x2f9e1d4b, 0x30b2dcf3, 0x52860dec, 0xe3c177d0, 0x16b32b6c, 0xb970a999, 0x489411fa, 0x64e94722, 0x8cfca8c4, 0x3ff0a01a, 0x2c7d56d8, 0x903322ef,
0x4e4987c7, 0xd138d9c1, 0xa2ca8cfe, 0x0bd49836, 0x81f5a6cf, 0xde7aa528, 0x8eb7da26, 0xbfad3fa4, 0x9d3a2ce4, 0x9278500d, 0xcc5f6a9b, 0x467e5462, 0x138df6c2, 0xb8d890e8, 0xf7392e5e, 0xafc382f5,
0x805d9fbe, 0x93d0697c, 0x2dd56fa9, 0x1225cfb3, 0x99acc83b, 0x7d1810a7, 0x639ce86e, 0xbb3bdb7b, 0x7826cd09, 0x18596ef4, 0xb79aec01, 0x9a4f83a8, 0x6e95e665, 0xe6ffaa7e, 0xcfbc2108, 0xe815efe6,
0x9be7bad9, 0x366f4ace, 0x099fead4, 0x7cb029d6, 0xb2a431af, 0x233f2a31, 0x94a5c630, 0x66a235c0, 0xbc4e7437, 0xca82fca6, 0xd090e0b0, 0xd8a73315, 0x9804f14a, 0xdaec41f7, 0x50cd7f0e, 0xf691172f,
0xd64d768d, 0xb0ef434d, 0x4daacc54, 0x0496e4df, 0xb5d19ee3, 0x886a4c1b, 0x1f2cc1b8, 0x5165467f, 0xea5e9d04, 0x358c015d, 0x7487fa73, 0x410bfb2e, 0x1d67b35a, 0xd2db9252, 0x5610e933, 0x47d66d13,
0x61d79a8c, 0x0ca1377a, 0x14f8598e, 0x3c13eb89, 0x27a9ceee, 0xc961b735, 0xe51ce1ed, 0xb1477a3c, 0xdfd29c59, 0x73f2553f, 0xce141879, 0x37c773bf, 0xcdf753ea, 0xaafd5f5b, 0x6f3ddf14, 0xdb447886,
0xf3afca81, 0xc468b93e, 0x3424382c, 0x40a3c25f, 0xc31d1672, 0x25e2bc0c, 0x493c288b, 0x950dff41, 0x01a83971, 0xb30c08de, 0xe4b4d89c, 0xc1566490, 0x84cb7b61, 0xb632d570, 0x5c6c4874, 0x57b8d042
};
unsigned int deTBOX2[256] = {
0xf45150a7, 0x417e5365, 0x171ac3a4, 0x273a965e, 0xab3bcb6b, 0x9d1ff145, 0xfaacab58, 0xe34b9303, 0x302055fa, 0x76adf66d, 0xcc889176, 0x02f5254c, 0xe54ffcd7, 0x2ac5d7cb, 0x35268044, 0x62b58fa3,
0xb1de495a, 0xba25671b, 0xea45980e, 0xfe5de1c0, 0x2fc30275, 0x4c8112f0, 0x468da397, 0xd36bc6f9, 0x8f03e75f, 0x9215959c, 0x6dbfeb7a, 0x5295da59, 0xbed42d83, 0x7458d321, 0xe0492969, 0xc98e44c8,
0xc2756a89, 0x8ef47879, 0x58996b3e, 0xb927dd71, 0xe1beb64f, 0x88f017ad, 0x20c966ac, 0xce7db43a, 0xdf63184a, 0x1ae58231, 0x51976033, 0x5362457f, 0x64b1e077, 0x6bbb84ae, 0x81fe1ca0, 0x08f9942b,
0x48705868, 0x458f19fd, 0xde94876c, 0x7b52b7f8, 0x73ab23d3, 0x4b72e202, 0x1fe3578f, 0x55662aab, 0xebb20728, 0xb52f03c2, 0xc5869a7b, 0x37d3a508, 0x2830f287, 0xbf23b2a5, 0x0302ba6a, 0x16ed5c82,
0xcf8a2b1c, 0x79a792b4, 0x07f3f0f2, 0x694ea1e2, 0xda65cdf4, 0x0506d5be, 0x34d11f62, 0xa6c48afe, 0x2e349d53, 0xf3a2a055, 0x8a0532e1, 0xf6a475eb, 0x830b39ec, 0x6040aaef, 0x715e069f, 0x6ebd5110,
0x213ef98a, 0xdd963d06, 0x3eddae05, 0xe64d46bd, 0x5491b58d, 0xc471055d, 0x06046fd4, 0x5060ff15, 0x981924fb, 0xbdd697e9, 0x4089cc43, 0xd967779e, 0xe8b0bd42, 0x8907888b, 0x19e7385b, 0xc879dbee,
0x7ca1470a, 0x427ce90f, 0x84f8c91e, 0x00000000, 0x80098386, 0x2b3248ed, 0x111eac70, 0x5a6c4e72, 0x0efdfbff, 0x850f5638, 0xae3d1ed5, 0x2d362739, 0x0f0a64d9, 0x5c6821a6, 0x5b9bd154, 0x36243a2e,
0x0a0cb167, 0x57930fe7, 0xeeb4d296, 0x9b1b9e91, 0xc0804fc5, 0xdc61a220, 0x775a694b, 0x121c161a, 0x93e20aba, 0xa0c0e52a, 0x223c43e0, 0x1b121d17, 0x090e0b0d, 0x8bf2adc7, 0xb62db9a8, 0x1e14c8a9,
0xf1578519, 0x75af4c07, 0x99eebbdd, 0x7fa3fd60, 0x01f79f26, 0x725cbcf5, 0x6644c53b, 0xfb5b347e, 0x438b7629, 0x23cbdcc6, 0xedb668fc, 0xe4b863f1, 0x31d7cadc, 0x63421085, 0x97134022, 0xc6842011,
0x4a857d24, 0xbbd2f83d, 0xf9ae1132, 0x29c76da1, 0x9e1d4b2f, 0xb2dcf330, 0x860dec52, 0xc177d0e3, 0xb32b6c16, 0x70a999b9, 0x9411fa48, 0xe9472264, 0xfca8c48c, 0xf0a01a3f, 0x7d56d82c, 0x3322ef90,
0x4987c74e, 0x38d9c1d1, 0xca8cfea2, 0xd498360b, 0xf5a6cf81, 0x7aa528de, 0xb7da268e, 0xad3fa4bf, 0x3a2ce49d, 0x78500d92, 0x5f6a9bcc, 0x7e546246, 0x8df6c213, 0xd890e8b8, 0x392e5ef7, 0xc382f5af,
0x5d9fbe80, 0xd0697c93, 0xd56fa92d, 0x25cfb312, 0xacc83b99, 0x1810a77d, 0x9ce86e63, 0x3bdb7bbb, 0x26cd0978, 0x596ef418, 0x9aec01b7, 0x4f83a89a, 0x95e6656e, 0xffaa7ee6, 0xbc2108cf, 0x15efe6e8,
0xe7bad99b, 0x6f4ace36, 0x9fead409, 0xb029d67c, 0xa431afb2, 0x3f2a3123, 0xa5c63094, 0xa235c066, 0x4e7437bc, 0x82fca6ca, 0x90e0b0d0, 0xa73315d8, 0x04f14a98, 0xec41f7da, 0xcd7f0e50, 0x91172ff6,
0x4d768dd6, 0xef434db0, 0xaacc544d, 0x96e4df04, 0xd19ee3b5, 0x6a4c1b88, 0x2cc1b81f, 0x65467f51, 0x5e9d04ea, 0x8c015d35, 0x87fa7374, 0x0bfb2e41, 0x67b35a1d, 0xdb9252d2, 0x10e93356, 0xd66d1347,
0xd79a8c61, 0xa1377a0c, 0xf8598e14, 0x13eb893c, 0xa9ceee27, 0x61b735c9, 0x1ce1ede5, 0x477a3cb1, 0xd29c59df, 0xf2553f73, 0x141879ce, 0xc773bf37, 0xf753eacd, 0xfd5f5baa, 0x3ddf146f, 0x447886db,
0xafca81f3, 0x68b93ec4, 0x24382c34, 0xa3c25f40, 0x1d1672c3, 0xe2bc0c25, 0x3c288b49, 0x0dff4195, 0xa8397101, 0x0c08deb3, 0xb4d89ce4, 0x566490c1, 0xcb7b6184, 0x32d570b6, 0x6c48745c, 0xb8d04257
};
unsigned int deTBOX3[256] = {
0x5150a7f4, 0x7e536541, 0x1ac3a417, 0x3a965e27, 0x3bcb6bab, 0x1ff1459d, 0xacab58fa, 0x4b9303e3, 0x2055fa30, 0xadf66d76, 0x889176cc, 0xf5254c02, 0x4ffcd7e5, 0xc5d7cb2a, 0x26804435, 0xb58fa362,
0xde495ab1, 0x25671bba, 0x45980eea, 0x5de1c0fe, 0xc302752f, 0x8112f04c, 0x8da39746, 0x6bc6f9d3, 0x03e75f8f, 0x15959c92, 0xbfeb7a6d, 0x95da5952, 0xd42d83be, 0x58d32174, 0x492969e0, 0x8e44c8c9,
0x756a89c2, 0xf478798e, 0x996b3e58, 0x27dd71b9, 0xbeb64fe1, 0xf017ad88, 0xc966ac20, 0x7db43ace, 0x63184adf, 0xe582311a, 0x97603351, 0x62457f53, 0xb1e07764, 0xbb84ae6b, 0xfe1ca081, 0xf9942b08,
0x70586848, 0x8f19fd45, 0x94876cde, 0x52b7f87b, 0xab23d373, 0x72e2024b, 0xe3578f1f, 0x662aab55, 0xb20728eb, 0x2f03c2b5, 0x869a7bc5, 0xd3a50837, 0x30f28728, 0x23b2a5bf, 0x02ba6a03, 0xed5c8216,
0x8a2b1ccf, 0xa792b479, 0xf3f0f207, 0x4ea1e269, 0x65cdf4da, 0x06d5be05, 0xd11f6234, 0xc48afea6, 0x349d532e, 0xa2a055f3, 0x0532e18a, 0xa475ebf6, 0x0b39ec83, 0x40aaef60, 0x5e069f71, 0xbd51106e,
0x3ef98a21, 0x963d06dd, 0xddae053e, 0x4d46bde6, 0x91b58d54, 0x71055dc4, 0x046fd406, 0x60ff1550, 0x1924fb98, 0xd697e9bd, 0x89cc4340, 0x67779ed9, 0xb0bd42e8, 0x07888b89, 0xe7385b19, 0x79dbeec8,
0xa1470a7c, 0x7ce90f42, 0xf8c91e84, 0x00000000, 0x09838680, 0x3248ed2b, 0x1eac7011, 0x6c4e725a, 0xfdfbff0e, 0x0f563885, 0x3d1ed5ae, 0x3627392d, 0x0a64d90f, 0x6821a65c, 0x9bd1545b, 0x243a2e36,
0x0cb1670a, 0x930fe757, 0xb4d296ee, 0x1b9e919b, 0x804fc5c0, 0x61a220dc, 0x5a694b77, 0x1c161a12, 0xe20aba93, 0xc0e52aa0, 0x3c43e022, 0x121d171b, 0x0e0b0d09, 0xf2adc78b, 0x2db9a8b6, 0x14c8a91e,
0x578519f1, 0xaf4c0775, 0xeebbdd99, 0xa3fd607f, 0xf79f2601, 0x5cbcf572, 0x44c53b66, 0x5b347efb, 0x8b762943, 0xcbdcc623, 0xb668fced, 0xb863f1e4, 0xd7cadc31, 0x42108563, 0x13402297, 0x842011c6,
0x857d244a, 0xd2f83dbb, 0xae1132f9, 0xc76da129, 0x1d4b2f9e, 0xdcf330b2, 0x0dec5286, 0x77d0e3c1, 0x2b6c16b3, 0xa999b970, 0x11fa4894, 0x472264e9, 0xa8c48cfc, 0xa01a3ff0, 0x56d82c7d, 0x22ef9033,
0x87c74e49, 0xd9c1d138, 0x8cfea2ca, 0x98360bd4, 0xa6cf81f5, 0xa528de7a, 0xda268eb7, 0x3fa4bfad, 0x2ce49d3a, 0x500d9278, 0x6a9bcc5f, 0x5462467e, 0xf6c2138d, 0x90e8b8d8, 0x2e5ef739, 0x82f5afc3,
0x9fbe805d, 0x697c93d0, 0x6fa92dd5, 0xcfb31225, 0xc83b99ac, 0x10a77d18, 0xe86e639c, 0xdb7bbb3b, 0xcd097826, 0x6ef41859, 0xec01b79a, 0x83a89a4f, 0xe6656e95, 0xaa7ee6ff, 0x2108cfbc, 0xefe6e815,
0xbad99be7, 0x4ace366f, 0xead4099f, 0x29d67cb0, 0x31afb2a4, 0x2a31233f, 0xc63094a5, 0x35c066a2, 0x7437bc4e, 0xfca6ca82, 0xe0b0d090, 0x3315d8a7, 0xf14a9804, 0x41f7daec, 0x7f0e50cd, 0x172ff691,
0x768dd64d, 0x434db0ef, 0xcc544daa, 0xe4df0496, 0x9ee3b5d1, 0x4c1b886a, 0xc1b81f2c, 0x467f5165, 0x9d04ea5e, 0x015d358c, 0xfa737487, 0xfb2e410b, 0xb35a1d67, 0x9252d2db, 0xe9335610, 0x6d1347d6,
0x9a8c61d7, 0x377a0ca1, 0x598e14f8, 0xeb893c13, 0xceee27a9, 0xb735c961, 0xe1ede51c, 0x7a3cb147, 0x9c59dfd2, 0x553f73f2, 0x1879ce14, 0x73bf37c7, 0x53eacdf7, 0x5f5baafd, 0xdf146f3d, 0x7886db44,
0xca81f3af, 0xb93ec468, 0x382c3424, 0xc25f40a3, 0x1672c31d, 0xbc0c25e2, 0x288b493c, 0xff41950d, 0x397101a8, 0x08deb30c, 0xd89ce4b4, 0x6490c156, 0x7b6184cb, 0xd570b632, 0x48745c6c, 0xd04257b8
};
int columns_matrix[16] = {
2, 3, 1, 1,
1, 2, 3, 1,
1, 1, 2, 3,
3, 1, 1, 2
};
int columns_matrix_inv[16] = {
0xe, 0xb, 0xd, 0x9,
0x9, 0xe, 0xb, 0xd,
0xd, 0x9, 0xe, 0xb,
0xb, 0xd, 0x9, 0xe
};
void add_padding(char* in, int len) {
int padding_length = 16 - (len % 16);
for (int i = 0; i < padding_length; ++i) {
in[len + i] = padding_length;
}
}
void print_mm(__m128i* in) {
unsigned char* val = (unsigned char*)in;
for (int i = 0; i < 16; ++i)
printf("%02x", val[i]);
printf("\n");
}
void key_exp(__m128i* last_key, __m128i* next_key, char rcon) {
unsigned char* tmp_last_key = (unsigned char*)last_key;
unsigned char* tmp_next_key = (unsigned char*)next_key;
tmp_next_key[0] = aes_sbox[tmp_last_key[13]] ^ rcon;
tmp_next_key[1] = aes_sbox[tmp_last_key[14]];
tmp_next_key[2] = aes_sbox[tmp_last_key[15]];
tmp_next_key[3] = aes_sbox[tmp_last_key[12]];
unsigned int* int_last_key = (unsigned int*)last_key;
unsigned int* int_next_key = (unsigned int*)next_key;
int_next_key[0] ^= int_last_key[0];
int_next_key[1] = int_last_key[1] ^ int_next_key[0];
int_next_key[2] = int_last_key[2] ^ int_next_key[1];
int_next_key[3] = int_last_key[3] ^ int_next_key[2];
}
void load_round_key(__m128i* key_schedule, unsigned char* init_key) {
key_schedule[0] = _mm_loadu_si128((__m128i*)init_key);
key_exp(&key_schedule[0], &key_schedule[1], (char)0x1);
key_exp(&key_schedule[1], &key_schedule[2], (char)0x2);
key_exp(&key_schedule[2], &key_schedule[3], (char)0x4);
key_exp(&key_schedule[3], &key_schedule[4], (char)0x8);
key_exp(&key_schedule[4], &key_schedule[5], (char)0x10);
key_exp(&key_schedule[5], &key_schedule[6], (char)0x20);
key_exp(&key_schedule[6], &key_schedule[7], (char)0x40);
key_exp(&key_schedule[7], &key_schedule[8], (char)0x80);
key_exp(&key_schedule[8], &key_schedule[9], (char)0x1b);
key_exp(&key_schedule[9], &key_schedule[10], (char)0x36);
}
void load_round_key_decrypt(__m128i* key_schedule, unsigned char* init_key) {
key_schedule[0] = _mm_loadu_si128((__m128i*)init_key);
key_exp(&key_schedule[0], &key_schedule[1], (char)0x1);
key_exp(&key_schedule[1], &key_schedule[2], (char)0x2);
key_exp(&key_schedule[2], &key_schedule[3], (char)0x4);
key_exp(&key_schedule[3], &key_schedule[4], (char)0x8);
key_exp(&key_schedule[4], &key_schedule[5], (char)0x10);
key_exp(&key_schedule[5], &key_schedule[6], (char)0x20);
key_exp(&key_schedule[6], &key_schedule[7], (char)0x40);
key_exp(&key_schedule[7], &key_schedule[8], (char)0x80);
key_exp(&key_schedule[8], &key_schedule[9], (char)0x1b);
key_exp(&key_schedule[9], &key_schedule[10], (char)0x36);
for(int i = 1; i < 10; ++i){
unsigned int *int_key = (unsigned int *)&key_schedule[i];
int_key[0] = deTBOX0[aes_sbox[(int_key[0]) & 0xFF]] ^ deTBOX1[aes_sbox[(int_key[0] >> 8) & 0xFF]]^deTBOX2[aes_sbox[(int_key[0]>>16) & 0xFF]]^deTBOX3[aes_sbox[(int_key[0] >> 24) & 0xFF]];
int_key[1] = deTBOX0[aes_sbox[(int_key[1]) & 0xFF]] ^ deTBOX1[aes_sbox[(int_key[1] >> 8) & 0xFF]]^deTBOX2[aes_sbox[(int_key[1]>>16) & 0xFF]]^deTBOX3[aes_sbox[(int_key[1] >> 24) & 0xFF]];
int_key[2] = deTBOX0[aes_sbox[(int_key[2]) & 0xFF]] ^ deTBOX1[aes_sbox[(int_key[2] >> 8) & 0xFF]]^deTBOX2[aes_sbox[(int_key[2]>>16) & 0xFF]]^deTBOX3[aes_sbox[(int_key[2] >> 24) & 0xFF]];
int_key[3] = deTBOX0[aes_sbox[(int_key[3]) & 0xFF]] ^ deTBOX1[aes_sbox[(int_key[3] >> 8) & 0xFF]]^deTBOX2[aes_sbox[(int_key[3]>>16) & 0xFF]]^deTBOX3[aes_sbox[(int_key[3] >> 24) & 0xFF]];
}
}
void round_function(__m128i* in) {
unsigned int* pint_in = (unsigned int*)in;
unsigned int out[4];
out[0] = TBOX0[pint_in[0] & 0xFF] ^ TBOX1[(pint_in[1] >> 8) & 0xFF] ^ TBOX2[(pint_in[2] >> 16) & 0xFF] ^ TBOX3[(pint_in[3] >> 24) & 0xFF];
out[1] = TBOX0[pint_in[1] & 0xFF] ^ TBOX1[(pint_in[2] >> 8) & 0xFF] ^ TBOX2[(pint_in[3] >> 16) & 0xFF] ^ TBOX3[(pint_in[0] >> 24) & 0xFF];
out[2] = TBOX0[pint_in[2] & 0xFF] ^ TBOX1[(pint_in[3] >> 8) & 0xFF] ^ TBOX2[(pint_in[0] >> 16) & 0xFF] ^ TBOX3[(pint_in[1] >> 24) & 0xFF];
out[3] = TBOX0[pint_in[3] & 0xFF] ^ TBOX1[(pint_in[0] >> 8) & 0xFF] ^ TBOX2[(pint_in[1] >> 16) & 0xFF] ^ TBOX3[(pint_in[2] >> 24) & 0xFF];
memcpy(in, out, 16);
}
__m128i aes_fast_encrypt(__m128i plain, __m128i* key) {
plain = _mm_xor_si128(plain, key[0]);
// print_mm(&plain);
unsigned int out[4];
unsigned int* pint_in = (unsigned int*)&plain;
for (register int i = 1; i < 10; ++i) {
//round_function(&plain);
out[0] = TBOX0[pint_in[0] & 0xFF] ^ TBOX1[(pint_in[1] >> 8) & 0xFF] ^ TBOX2[(pint_in[2] >> 16) & 0xFF] ^ TBOX3[(pint_in[3] >> 24) & 0xFF];
out[1] = TBOX0[pint_in[1] & 0xFF] ^ TBOX1[(pint_in[2] >> 8) & 0xFF] ^ TBOX2[(pint_in[3] >> 16) & 0xFF] ^ TBOX3[(pint_in[0] >> 24) & 0xFF];
out[2] = TBOX0[pint_in[2] & 0xFF] ^ TBOX1[(pint_in[3] >> 8) & 0xFF] ^ TBOX2[(pint_in[0] >> 16) & 0xFF] ^ TBOX3[(pint_in[1] >> 24) & 0xFF];
out[3] = TBOX0[pint_in[3] & 0xFF] ^ TBOX1[(pint_in[0] >> 8) & 0xFF] ^ TBOX2[(pint_in[1] >> 16) & 0xFF] ^ TBOX3[(pint_in[2] >> 24) & 0xFF];
unsigned int* int_key = (unsigned int*)&key[i];
pint_in[0] = int_key[0] ^ out[0];
pint_in[1] = int_key[1] ^ out[1];
pint_in[2] = int_key[2] ^ out[2];
pint_in[3] = int_key[3] ^ out[3];
}
char output[16];
char* pchar_plain = (char*)&plain;
output[ 0] = aes_sbox[pchar_plain[ 0] & 0xFF];
output[ 1] = aes_sbox[pchar_plain[ 5] & 0xFF];
output[ 2] = aes_sbox[pchar_plain[10] & 0xFF];
output[ 3] = aes_sbox[pchar_plain[15] & 0xFF];
output[ 4] = aes_sbox[pchar_plain[ 4] & 0xFF];
output[ 5] = aes_sbox[pchar_plain[ 9] & 0xFF];
output[ 6] = aes_sbox[pchar_plain[14] & 0xFF];
output[ 7] = aes_sbox[pchar_plain[ 3] & 0xFF];
output[ 8] = aes_sbox[pchar_plain[ 8] & 0xFF];
output[ 9] = aes_sbox[pchar_plain[13] & 0xFF];
output[10] = aes_sbox[pchar_plain[ 2] & 0xFF];
output[11] = aes_sbox[pchar_plain[ 7] & 0xFF];
output[12] = aes_sbox[pchar_plain[12] & 0xFF];
output[13] = aes_sbox[pchar_plain[ 1] & 0xFF];
output[14] = aes_sbox[pchar_plain[ 6] & 0xFF];
output[15] = aes_sbox[pchar_plain[11] & 0xFF];
plain = _mm_xor_si128(*(__m128i*)output, key[10]);
//print_mm(&plain);
//plain = _mm_xor_si128(plain, key[10]);
//printf("%s\n", key[10]);
//print_mm(&plain);
return plain;
}
__m128i aes_fast_decrypt(__m128i cipher, __m128i* key){
cipher = _mm_xor_si128(cipher, key[10]);
unsigned int* pint_in = (unsigned int*)&cipher;
unsigned int wa0, wa1, wa2, wa3, wb0, wb1, wb2, wb3;
unsigned int* int_key = (unsigned int*)&key[9];
wb0 = deTBOX0[pint_in[0] & 0xFF] ^ deTBOX1[(pint_in[3] >> 8) & 0xFF] ^ deTBOX2[(pint_in[2] >> 16) & 0xFF] ^ deTBOX3[(pint_in[1] >> 24) & 0xFF] ^ int_key[0];
wb1 = deTBOX0[pint_in[1] & 0xFF] ^ deTBOX1[(pint_in[0] >> 8) & 0xFF] ^ deTBOX2[(pint_in[3] >> 16) & 0xFF] ^ deTBOX3[(pint_in[2] >> 24) & 0xFF] ^ int_key[1];
wb2 = deTBOX0[pint_in[2] & 0xFF] ^ deTBOX1[(pint_in[1] >> 8) & 0xFF] ^ deTBOX2[(pint_in[0] >> 16) & 0xFF] ^ deTBOX3[(pint_in[3] >> 24) & 0xFF] ^ int_key[2];
wb3 = deTBOX0[pint_in[3] & 0xFF] ^ deTBOX1[(pint_in[2] >> 8) & 0xFF] ^ deTBOX2[(pint_in[1] >> 16) & 0xFF] ^ deTBOX3[(pint_in[0] >> 24) & 0xFF] ^ int_key[3];
for (register int i = 8; i > 0; --i) {
int_key = (unsigned int*)&key[i];
wa0 = deTBOX0[wb0 & 0xFF] ^ deTBOX1[(wb3 >> 8) & 0xFF] ^ deTBOX2[(wb2 >> 16) & 0xFF] ^ deTBOX3[(wb1 >> 24) & 0xFF] ^ int_key[0];
wa1 = deTBOX0[wb1 & 0xFF] ^ deTBOX1[(wb0 >> 8) & 0xFF] ^ deTBOX2[(wb3 >> 16) & 0xFF] ^ deTBOX3[(wb2 >> 24) & 0xFF] ^ int_key[1];
wa2 = deTBOX0[wb2 & 0xFF] ^ deTBOX1[(wb1 >> 8) & 0xFF] ^ deTBOX2[(wb0 >> 16) & 0xFF] ^ deTBOX3[(wb3 >> 24) & 0xFF] ^ int_key[2];
wa3 = deTBOX0[wb3 & 0xFF] ^ deTBOX1[(wb2 >> 8) & 0xFF] ^ deTBOX2[(wb1 >> 16) & 0xFF] ^ deTBOX3[(wb0 >> 24) & 0xFF] ^ int_key[3];
int_key = (unsigned int*)&key[--i];
wb0 = deTBOX0[wa0 & 0xFF] ^ deTBOX1[(wa3 >> 8) & 0xFF] ^ deTBOX2[(wa2 >> 16) & 0xFF] ^ deTBOX3[(wa1 >> 24) & 0xFF] ^ int_key[0];
wb1 = deTBOX0[wa1 & 0xFF] ^ deTBOX1[(wa0 >> 8) & 0xFF] ^ deTBOX2[(wa3 >> 16) & 0xFF] ^ deTBOX3[(wa2 >> 24) & 0xFF] ^ int_key[1];
wb2 = deTBOX0[wa2 & 0xFF] ^ deTBOX1[(wa1 >> 8) & 0xFF] ^ deTBOX2[(wa0 >> 16) & 0xFF] ^ deTBOX3[(wa3 >> 24) & 0xFF] ^ int_key[2];
wb3 = deTBOX0[wa3 & 0xFF] ^ deTBOX1[(wa2 >> 8) & 0xFF] ^ deTBOX2[(wa1 >> 16) & 0xFF] ^ deTBOX3[(wa0 >> 24) & 0xFF] ^ int_key[3];
}
char output[16];
output[ 0] = aes_sbox_inv[ wb0 & 0xFF];
output[ 1] = aes_sbox_inv[(wb3 >> 8) & 0xFF];
output[ 2] = aes_sbox_inv[(wb2 >> 16) & 0xFF];
output[ 3] = aes_sbox_inv[(wb1 >> 24) & 0xFF];
output[ 4] = aes_sbox_inv[ wb1 & 0xFF];
output[ 5] = aes_sbox_inv[(wb0 >> 8) & 0xFF];
output[ 6] = aes_sbox_inv[(wb3 >> 16) & 0xFF];
output[ 7] = aes_sbox_inv[(wb2 >> 24) & 0xFF];
output[ 8] = aes_sbox_inv[ wb2 & 0xFF];
output[ 9] = aes_sbox_inv[(wb1 >> 8) & 0xFF];
output[10] = aes_sbox_inv[(wb0 >> 16) & 0xFF];
output[11] = aes_sbox_inv[(wb3 >> 24) & 0xFF];
output[12] = aes_sbox_inv[ wb3 & 0xFF];
output[13] = aes_sbox_inv[(wb2 >> 8) & 0xFF];
output[14] = aes_sbox_inv[(wb1 >> 16) & 0xFF];
output[15] = aes_sbox_inv[(wb0 >> 24) & 0xFF];
cipher = _mm_xor_si128(*(__m128i*)output, key[0]);
//print_mm(&cipher);
//cipher = _mm_xor_si128(cipher, key[10]);
//printf("%s\n", key[10]);
// print_mm(&cipher);
return cipher;
}
int main() {
unsigned char plain[17] = "\x01\x23\x45\x67\x89\xab\xcd\xef\xfe\xdc\xba\x98\x76\x54\x32\x10";
unsigned char key[17] = "\x0f\x15\x71\xc9\x47\xd9\xe8\x59\x0c\xb7\xad\xd6\xaf\x7f\x67\x98";
__m128i mm_plain = _mm_loadu_si128((__m128i*)plain);
__m128i mm_key[20];
mm_key[0] = _mm_loadu_si128((__m128i*)key);
// unsigned char *var = (unsigned char *) &mm_key[0];
// var[0] = 0x1f;
load_round_key(mm_key, key);
clock_t start, end;
mm_plain = aes_fast_encrypt(mm_plain, mm_key);
print_mm(&mm_plain);
__m128i mm_key_decrypt[20];
load_round_key_decrypt(mm_key_decrypt, key);
mm_plain = aes_fast_decrypt(mm_plain, mm_key_decrypt);
print_mm(&mm_plain);
start = clock();
for (register int i = 0; i < 0x1000000; ++i)
mm_plain = aes_fast_encrypt(mm_plain, mm_key);
end = clock();
print_mm(&mm_plain);
printf("time=%lfs\n", (double)(end - start) / CLOCKS_PER_SEC);
start = clock();
for (register int i = 0; i < 0x1000000; ++i)
mm_plain = aes_fast_decrypt(mm_plain, mm_key_decrypt);
end = clock();
print_mm(&mm_plain);
printf("time=%lfs\n", (double)(end - start) / CLOCKS_PER_SEC);
return 0;
}
/*
test data of key
0f 15 71 c9 47 d9 e8 59 0c b7 ad d6 af 7f 67 98
dc 90 37 b0 9b 49 df e9 97 fe 72 3f 38 81 15 a7
d2 c9 6b b7 49 80 b4 5e de 7e c6 61 e6 ff d3 c6
c0 af df 39 89 2f 6b 67 57 51 ad 06 b1 ae 7e c0
2c 5c 65 f1 a5 73 0e 96 f2 22 a3 90 43 8c dd 50
58 9d 36 eb fd ee 38 7d 0f cc 9b ed 4c 40 46 bd
71 c7 4c c2 8c 29 74 bf 83 e5 ef 52 cf a5 a9 ef
37 14 93 48 bb 3d e7 f7 38 d8 08 a5 f7 7d a1 4a
48 26 45 20 f3 1b a2 d7 cb c3 aa 72 3c be 0b 38
fd 0d 42 cb 0e 16 e0 1c c5 d5 4a 6e f9 6b 41 56
b4 8e f3 52 ba 98 13 4e 7f 4d 59 20 86 26 18 76
*/
| 95.343602 | 195 | 0.739108 |
12fa35681afdd9d47b492f8d6cb3746d2046c83e | 5,953 | hpp | C++ | src/snapshot.hpp | weixiaoqimath/HERMES | a8881f301fc1a720bb0a9983467b4f912089b081 | [
"MIT"
] | 7 | 2020-12-26T22:06:10.000Z | 2021-10-05T14:14:02.000Z | src/snapshot.hpp | weixiaoqimath/HERMES | a8881f301fc1a720bb0a9983467b4f912089b081 | [
"MIT"
] | null | null | null | src/snapshot.hpp | weixiaoqimath/HERMES | a8881f301fc1a720bb0a9983467b4f912089b081 | [
"MIT"
] | 3 | 2021-02-21T20:27:49.000Z | 2021-11-09T17:13:43.000Z | #include "alpha_shape.hpp"
#include "rips_shape.hpp"
class EdgeRadiusCompare{
public:
AlphaShape* m_alpha;
EdgeRadiusCompare(AlphaShape* alpha){
m_alpha = alpha;
}
bool operator()(const EdgeIterator& ei1, const EdgeIterator& ei2) const{
return m_alpha->edgeAlpha(ei1) < m_alpha->edgeAlpha(ei2);
}
};
class FacetRadiusCompare{
public:
AlphaShape* m_alpha;
FacetRadiusCompare(AlphaShape* alpha){
m_alpha = alpha;
}
bool operator()(const FacetIterator& fi1, const FacetIterator& fi2) const{
return m_alpha->facetAlpha(fi1) < m_alpha->facetAlpha(fi2);
}
};
class CellRadiusCompare{
public:
AlphaShape* m_alpha;
CellRadiusCompare(AlphaShape* alpha){
m_alpha = alpha;
}
bool operator()(const CellIterator& ci1, const CellIterator& ci2) const{
return m_alpha->cellAlpha(ci1) < m_alpha->cellAlpha(ci2);
}
};
typedef std::priority_queue<EdgeIterator, std::vector<EdgeIterator>, EdgeRadiusCompare> EdgePriorityQueue;
typedef std::priority_queue<FacetIterator, std::vector<FacetIterator>, FacetRadiusCompare> FacetPriorityQueue;
typedef std::priority_queue<CellIterator, std::vector<CellIterator>, CellRadiusCompare> CellPriorityQueue;
class Snapshot{
protected:
AlphaShape m_alpha;
RipsShape m_rips;
std::unordered_map<EdgeIterator, double, EdgeIteratorHash> m_edge_radius;
std::unordered_map<FacetIterator, double, FacetIteratorHash> m_facet_radius;
std::unordered_map<CellIterator, double, CellIteratorHash> m_cell_radius;
double m_edge_length_min;
double m_edge_length_max;
std::vector<EdgeIterator> m_sorted_edges;
std::vector<FacetIterator> m_sorted_facets;
std::vector<CellIterator> m_sorted_cells;
std::unordered_map<EdgeIterator, int, EdgeIteratorHash> m_sorted_edge_idx;
std::unordered_map<FacetIterator, int, FacetIteratorHash> m_sorted_facet_idx;
std::unordered_map<CellIterator, int, CellIteratorHash> m_sorted_cell_idx;
// min heap
EdgePriorityQueue* m_edge_heap;
FacetPriorityQueue* m_facet_heap;
CellPriorityQueue* m_cell_heap;
std::vector<double> m_filtration;
int m_num_eigenvalues;
double m_p = 0.; // p-persistence
char m_complex = 'a'; // 'a' for alpha complex and 'r' for rips complex
int numVertices, numEdges, numFacets, numCells;
std::unique_ptr<matlab::engine::MATLABEngine> m_matlab_engine;
std::vector<std::vector<double>> m_vertex_snapshots;
std::vector<std::vector<double>> m_edge_snapshots;
std::vector<std::vector<double>> m_facet_snapshots;
public:
void initializeParameters(int num_eigenvalues);
void initializeParameters(int num_eigenvalues, double p);
void initializeParameters(int num_eigenvalues, double p, char complex);
void readFiltration(const std::string& filename);
void buildAlphaShape(const std::string& filename);
void buildRipsShape(const std::string& filename);
void preprocess();
void takeSnapshots();
void write();
void debug();
protected:
void setNumElements();
void computeMinMaxEdgeLength();
void computeRadius();
void buildPriorityQueue();
void assembleSortedElements();
void indexSortedElements();
protected:
void computeEdgeRadius();
void computeFacetRadius();
void computeCellRadius();
void buildEdgePriorityQueue();
void buildFacetPriorityQueue();
void buildCellPrioiryQueue();
void assembleSortedEdges();
void assembleSortedFacets();
void assembleSortedCells();
void indexSortedEdges();
void indexSortedFacets();
void indexSortedCells();
void writeVertexSnapshots();
void writeEdgeSnapshots();
void writeFacetSnapshots();
protected:
void determineNextEdgeSize(const int& current_size, int& next_size, double filtration);
void determineNextFacetSize(const int& current_size, int& next_size, double filtration);
void determineNextCellSize(const int& current_size, int& next_size, double filtration);
// build exteior derivative operator (transpose of boundary operator)
void fillED0T(SparseMatrix& ED0T, const int& current_size, const int& next_size);
void fillED1T(SparseMatrix& ED1T, const int& current_size, const int& next_size);
void fillED2T(SparseMatrix& ED2T, const int& current_size, const int& next_size);
void buildLaplacian0(SparseMatrix& L0, const SparseMatrix& ED0T, const int& edge_size);
void buildLaplacian1(SparseMatrix& L1, const SparseMatrix& ED0T, const SparseMatrix& ED1T, const int& edge_size, const int& facet_size);
void buildLaplacian2(SparseMatrix& L2, const SparseMatrix& ED1T, const SparseMatrix& ED2T, const int& edge_size, const int& facet_size, const int& cell_size);
void buildPersistentLaplacian0(SparseMatrix& L0, const SparseMatrix& ED0T, const SparseMatrix& ED1T, const int& edge_size, const double filtration, double p);
void buildPersistentLaplacian1(SparseMatrix& L1, const SparseMatrix& ED0T, const SparseMatrix& ED1T, const int& edge_size, const int& facet_size, const double filtration, double p);
void buildPersistentLaplacian2(SparseMatrix& L2, const SparseMatrix& ED1T, const SparseMatrix& ED2T, const int& edge_size, const int& facet_size, const int& cell_size, const double filtration, double p);
void takeVertexSnapshots(const SparseMatrix& L0, const int matrix_size); // beta_0
void takeEdgeSnapshots(const SparseMatrix& L1, const int matrix_size); // beta_1
void takeFacetSnapshots(const SparseMatrix& L2, const int matrix_size); // beta_2
protected:
void startMatlab();
void matlabEIGS(std::vector<double>& eval, std::vector<ColumnVector>& evec, int matrix_size,
std::vector<double>& row, std::vector<double>& col, std::vector<double>& val, int m);
private:
//debug
void writeVertices();
void testEdgeFiltration();
void testFacetFiltration();
void testCellFiltration();
};
| 36.975155 | 207 | 0.741139 |
12fa797a258ef128ff053fdf0cdc7bb9d06a08bc | 4,803 | hpp | C++ | test_interface.hpp | Anadani/oop4 | 133508256b02dd3cd45569b51cea2367cf880c7a | [
"MIT"
] | null | null | null | test_interface.hpp | Anadani/oop4 | 133508256b02dd3cd45569b51cea2367cf880c7a | [
"MIT"
] | null | null | null | test_interface.hpp | Anadani/oop4 | 133508256b02dd3cd45569b51cea2367cf880c7a | [
"MIT"
] | null | null | null | #ifndef TEST_INTERFACE_HPP
#define TEST_INTERFACE_HPP
#include <iostream>
#include <iomanip>
#include <limits>
#include <string>
#include <sstream>
#include "tests.hpp"
#include "Money.hpp"
#include "HotdogStand.hpp"
void TEST_INSERTION(bool sign);
void TEST_EXTRACTION(bool dSign);
void runTests()
{
using std::cout;
using std::left;
using std::setw;
using std::endl;
namespace MAB = MyAwesomeBusiness;
char prev = cout.fill('.');
cout << "Money Class Tests\n";
cout << setw(40) << left << "Negative (+ -> -)" << (IS_EQUAL(-550, (-(MAB::Money(5.50)).getPennies()))) << endl;
cout << setw(40) << left << "Negative (- -> +)" << (IS_EQUAL(550, (-(MAB::Money(-5.50)).getPennies()))) << endl;
cout << setw(40) << left << "Equality (T)" << (EXPECT_TRUE((MAB::Money(6) == MAB::Money(6)))) << endl;
cout << setw(40) << left << "Equality (F)" << (EXPECT_FALSE((MAB::Money(6) == MAB::Money(2)))) << endl;
cout << setw(40) << left << "Prefix++" << (IS_EQUAL(MAB::Money(6), ++(MAB::Money(5)))) << endl;
cout << setw(40) << left << "Postfix++" << (IS_EQUAL(MAB::Money(5), (MAB::Money(5))++)) << endl;
cout << setw(40) << left << "Prefix--" << (IS_EQUAL(MAB::Money(6), --(MAB::Money(7)))) << endl;
cout << setw(40) << left << "Postfix--" << (IS_EQUAL(MAB::Money(6), (MAB::Money(6))--)) << endl;
cout << setw(40) << left << "Addition" << (IS_EQUAL(MAB::Money(7), (MAB::Money(2.5) + MAB::Money(4, 50)))) << endl;
cout << setw(40) << left << "Multiplication (Money x int)" << (IS_EQUAL(MAB::Money(11), (MAB::Money(2.75) * 4))) << endl;
cout << setw(40) << left << "Multiplication (int x Money)" << (IS_EQUAL(MAB::Money(11), (4 * MAB::Money(2.75)))) << endl;
cout << setw(40) << left << "Multiplication (Money x double)" << (IS_EQUAL(MAB::Money(2.75), (MAB::Money(11) * 0.25))) << endl;
cout << setw(40) << left << "Multiplication (double x Money)" << (IS_EQUAL(MAB::Money(2.75), (0.25 * MAB::Money(11)))) << endl;
cout << setw(40) << left << "Less Than (T)" << (EXPECT_TRUE((MAB::Money(1) < MAB::Money(6)))) << endl;
cout << setw(40) << left << "Less Than (F)" << (EXPECT_FALSE((MAB::Money(10) < MAB::Money(2)))) << endl;
cout << setw(40) << left << "Less Than (F, ==)" << (EXPECT_FALSE((MAB::Money(2) < MAB::Money(2)))) << endl;
cout << setw(40) << left << "Less Than or Equal (T)" << (EXPECT_TRUE((MAB::Money(6) <= MAB::Money(6)))) << endl;
cout << setw(40) << left << "Less Than or Equal (T, ==)" << (EXPECT_TRUE((MAB::Money(6) <= MAB::Money(6)))) << endl;
cout << setw(40) << left << "Less Than or Equal (F)" << (EXPECT_FALSE((MAB::Money(6) <= MAB::Money(2)))) << endl;
cout << setw(40) << left << "Greater Than (T)" << (EXPECT_TRUE((MAB::Money(6) > MAB::Money(4)))) << endl;
cout << setw(40) << left << "Greater Than (F)" << (EXPECT_FALSE((MAB::Money(2) > MAB::Money(6)))) << endl;
cout << setw(40) << left << "Greater Than (F, ==)" << (EXPECT_FALSE((MAB::Money(6) > MAB::Money(6)))) << endl;
cout << setw(40) << left << "Greater Than or Equal (T)" << (EXPECT_TRUE((MAB::Money(6) >= MAB::Money(5)))) << endl;
cout << setw(40) << left << "Greater Than or Equal (T, ==)" << (EXPECT_TRUE((MAB::Money(6) >= MAB::Money(6)))) << endl;
cout << setw(40) << left << "Greater Than or Equal (F)" << (EXPECT_FALSE((MAB::Money(2) >= MAB::Money(6)))) << endl;
cout << setw(40) << left << "Inequality (T)" << (EXPECT_TRUE((MAB::Money(2) != MAB::Money(6)))) << endl;
cout << setw(40) << left << "Inequality (F)" << (EXPECT_FALSE((MAB::Money(6) != MAB::Money(6)))) << endl;
cout << setw(40) << left << "Insertion (<<, +)"; (TEST_INSERTION(true)); std::cout << endl;
cout << setw(40) << left << "Insertion (<<, -)"; (TEST_INSERTION(false)); std::cout << endl;
cout << setw(40) << left << "Extraction (>>, $)"; (TEST_EXTRACTION(true)); std::cout << endl;
cout << setw(40) << left << "Extraction (>>)"; (TEST_EXTRACTION(false)); std::cout << endl;
cout.fill(prev);
}
void TEST_INSERTION(bool sign)
{
namespace MAB = MyAwesomeBusiness;
std::stringstream ss;
std::string str;
if (sign) {
MAB::Money money(5, 75);
ss << money;
str = ss.str();
std::cout << (IS_EQUAL(std::string("$5.75"), str));
} else {
MAB::Money money(-5, -75);
ss << money;
str = ss.str();
std::cout << (IS_EQUAL(std::string("($5.75)"), str));
}
ss.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
void TEST_EXTRACTION(bool dSign)
{
namespace MAB = MyAwesomeBusiness;
std::stringstream ss;
std::string str;
if (dSign)
ss << "$5.75";
else
ss << "5.75";
MAB::Money money;
ss >> money;
std::cout << (IS_EQUAL(575, money.getPennies()));
}
#endif
| 48.515152 | 131 | 0.549865 |
4200baf926ba130cc05eadf27485415b61f69176 | 21,419 | cpp | C++ | numscene.cpp | Kcazer/plusra-psp | 8e465a391b2f8d7e34e6672c26c9c523e6c485b5 | [
"MIT"
] | null | null | null | numscene.cpp | Kcazer/plusra-psp | 8e465a391b2f8d7e34e6672c26c9c523e6c485b5 | [
"MIT"
] | null | null | null | numscene.cpp | Kcazer/plusra-psp | 8e465a391b2f8d7e34e6672c26c9c523e6c485b5 | [
"MIT"
] | null | null | null | #include "numscene.h"
NumScene::NumScene(void) {
int i;
// Chargement des donnees
_loaded = loadData();
loadScores();
// Repetitions des touches
oslSetKeyAutorepeat(OSL_KEYMASK_UP | OSL_KEYMASK_RIGHT | OSL_KEYMASK_DOWN | OSL_KEYMASK_LEFT, 15, 5);
// Initialisation
for (i = 0; i < 20; i++) _arrows[i].x = 500;
for (i = 0; i < 8; i++) _playerName[i] = 42;
oslPlaySound(_bgm.menu, 0);
_status = GAME_MENU;
_menuItem = 0;
}
NumScene::~NumScene(void) {
// Free Image
oslDeleteImage(_img.arrow);
oslDeleteImage(_img.background);
oslDeleteImage(_img.block);
oslDeleteImage(_img.boomRed);
oslDeleteImage(_img.boomWhite);
oslDeleteImage(_img.combo);
oslDeleteImage(_img.cursor);
oslDeleteImage(_img.font);
oslDeleteImage(_img.fontMini);
oslDeleteImage(_img.goal32);
oslDeleteImage(_img.goal40);
oslDeleteImage(_img.menu);
oslDeleteImage(_img.name);
oslDeleteImage(_img.playArea);
oslDeleteImage(_img.pressKey);
oslDeleteImage(_img.score);
oslDeleteImage(_img.slide);
oslDeleteImage(_img.title);
// Free Audio
oslDeleteSound(_bgm.menu);
oslDeleteSound(_bgm.game);
oslDeleteSound(_se.move);
oslDeleteSound(_se.success);
oslDeleteSound(_se.fail);
}
bool NumScene::loaded(void) {
return _loaded;
}
bool NumScene::loadData(void) {
bool success = true;
success &= loadImage("data/imgArrow.png", &(_img.arrow), 0, 0, 16, 16, 32, 32);
success &= loadImage("data/imgBackground.png", &(_img.background), -32, 0, 0, 0, 0, 0);
success &= loadImage("data/imgBlock.png", &(_img.block), 0, 0, 0, 0, 32, 32);
success &= loadImage("data/imgBoomRed.png", &(_img.boomRed), 0, 0, 0, 0, 0, 0);
success &= loadImage("data/imgBoomWhite.png", &(_img.boomWhite), 0, 0, 0, 0, 0, 0);
success &= loadImage("data/imgCombo.png", &(_img.combo), 0, 0, 0, 0, 0, 0);
success &= loadImage("data/imgCursor.png", &(_img.cursor), 0, 0, 0, 0, 0, 0);
success &= loadImage("data/imgFont.png", &(_img.font), 0, 0, 0, 0, 12, 12);
success &= loadImage("data/imgFontMini.png", &(_img.fontMini), 0, 0, 0, 0, 6, 6);
success &= loadImage("data/imgGoal32.png", &(_img.goal32), 38, 0, 0, 0, 32, 32);
success &= loadImage("data/imgGoal40.png", &(_img.goal40), 20, 155, 0, 0, 40, 40);
success &= loadImage("data/imgMenu.png", &(_img.menu), 0, 0, 0, 0, 204, 22);
success &= loadImage("data/imgName.png", &(_img.name), 0, 0, 0, 0, 0, 0);
success &= loadImage("data/imgPlayArea.png", &(_img.playArea), 0, 0, 0, 0, 0, 0);
success &= loadImage("data/imgPressKey.png", &(_img.pressKey), 146, 242, 0, 0, 0, 0);
success &= loadImage("data/imgScore.png", &(_img.score), 0, 0, 0, 0, 0, 0);
success &= loadImage("data/imgSlide.png", &(_img.slide), -64, 0, 0, 0, 0, 0);
success &= loadImage("data/imgTitle.png", &(_img.title), 112, 16, 0, 0, 0, 0);
success &= loadSound("data/bgmGame.bgm", &(_bgm.game), true, true);
success &= loadSound("data/bgmMenu.bgm", &(_bgm.menu), true, true);
success &= loadSound("data/seFail.wav", &(_se.fail), false, false);
success &= loadSound("data/seMove.wav", &(_se.move), false, false);
success &= loadSound("data/seSuccess.wav", &(_se.success), false, false);
return success;
}
bool NumScene::loadImage(char *file, OSL_IMAGE **img, int x, int y, int centerX, int centerY, int frameX, int frameY) {
(*img) = oslLoadImageFile(file, OSL_IN_RAM, OSL_PF_8888);
if (!(*img)) return false;
(*img)->x = x;
(*img)->y = y;
(*img)->centerX = centerX;
(*img)->centerY = centerY;
if (frameX && frameY) oslSetImageFrameSize((*img), frameX, frameY);
return true;
}
bool NumScene::loadSound(char *file, OSL_SOUND **snd, bool streamed, bool repeat) {
(*snd) = oslLoadSoundFile(file, (streamed) ? OSL_FMT_STREAM : OSL_FMT_NONE);
if (!(*snd)) return false;
oslSetSoundLoop((*snd), repeat);
return true;
}
void NumScene::update(void) {
switch (_status) {
case GAME_MENU:
updateMenu();
drawMenu();
break;
case GAME_PLAYING:
updateGame();
drawGame();
break;
case GAME_PAUSED:
updatePause();
drawPause();
break;
case GAME_OVER:
updateGameOver();
drawGameOver();
break;
case GAME_HSCORES:
updateHighScores();
drawHighScores();
break;
case GAME_CREDITS:
updateCredits();
drawCredits();
break;
default:
// Will never happen
break;
}
}
void NumScene::updateMenu(void) {
// Deplacement dans le menu
if (osl_pad.pressed.up) {
_menuItem = (_menuItem + 2) % 3;
oslPlaySound(_se.move, 1);
} else if (osl_pad.pressed.down) {
_menuItem = (_menuItem + 1) % 3;
oslPlaySound(_se.move, 1);
}
if (osl_pad.pressed.circle) {
switch (_menuItem) {
case 0:
startGame();
break;
case 1:
_oldStatus = GAME_MENU;
_status = GAME_HSCORES;
break;
case 2:
_status = GAME_CREDITS;
break;
default:
break;
}
}
}
void NumScene::drawMenu(void) {
int i;
// Deplacement des fleches
for (i = 0; i < 20; i++)
if (_arrows[i].x > 500) {
_arrows[i].color = rand() % 4;
_arrows[i].y = rand() % 240 + 16;
_arrows[i].x = rand() % 500 - 500;
_arrows[i].angle = rand() % 360;
} else {
_arrows[i].x += 5;
_arrows[i].angle += 4;
}
// Affichage
oslDrawFillRect(0, 0, 480, 272, 0xFFFFFFFF);
for (i = 0; i < 20; i++) {
_img.arrow->x = _arrows[i].x;
_img.arrow->y = _arrows[i].y;
_img.arrow->angle = _arrows[i].angle;
oslSetImageFrame(_img.arrow, _arrows[i].color);
oslDrawImage(_img.arrow);
}
oslDrawImage(_img.title);
oslSetImageFrame(_img.menu, _menuItem);
_img.menu->x = 111;
_img.menu->y = 135 + 48 * _menuItem;
oslDrawImage(_img.menu);
for (i = 0; i < 3; i++) {
oslSetImageFrame(_img.menu, i);
_img.menu->x = 48 + 64 * ((i == _menuItem) ? 1 : 0);
_img.menu->y = 136 + 48 * i;
oslDrawImage(_img.menu);
}
}
void NumScene::updateGame(void) {
int x, y, oldX, oldY;
bool loseHP, fusion = false;
/*// Pause ?
if (osl_pad.pressed.start) {
_status = GAME_PAUSED;
return;
}
*/
// Deplacement des blocs libres
for (y = 0; y < 8; y++)
for (x = 0; x < 12; x++) {
// Pas de bloc
if (_map[y][x].value == -1) continue;
// Bloc en position finale
if (_map[y][x].position == 0) {
// Ne peut pas bouger
if (x == 0 || _map[y][x - 1].value != -1) continue;
// Se transfere au bloc inferieur
_map[y][x - 1].value = _map[y][x].value;
_map[y][x].value = -1;
_map[y][x - 1].position = 32 - _speed;;
} else _map[y][x].position -= _speed;;
}
// Gestion du respawn
_timer--;
if (osl_pad.pressed.square || _timer == 0) {
if (osl_pad.pressed.square) _hp -= 2;
_timer = 120;
addBlock();
}
// Déplacement du curseur
oldX = _cursor.x;
oldY = _cursor.y;
if (osl_pad.pressed.up) _cursor.y = (_cursor.y + 7) % 8;
else if (osl_pad.pressed.down) _cursor.y = (_cursor.y + 1) % 8;
if (osl_pad.pressed.left) _cursor.x = (_cursor.x + 11) % 12;
else if (osl_pad.pressed.right) _cursor.x = (_cursor.x + 1) % 12;
// Son de deplacement
if (oldX != _cursor.x || oldY != _cursor.y) oslPlaySound(_se.move, 1);
// Test fusion de blocs
if (osl_pad.held.circle && _map[oldY][oldX].value != -1 // Cercle enfonc� et ancien bloc non vide
&& (oslAbs(_cursor.x - oldX) + oslAbs(_cursor.y - oldY)) == 1) { // Et pas en diagonale
// Deplacement sur un bloc vide ou occup� ?
if (_map[_cursor.y][_cursor.x].value == -1) {
_map[_cursor.y][_cursor.x].value = _map[oldY][oldX].value;
_combo = 1;
} else {
_map[_cursor.y][_cursor.x].value += _map[oldY][oldX].value;
fusion = true;
}
_map[oldY][oldX].value = -1;
}
// Si il y a eu fusion
if (fusion) {
if (_map[_cursor.y][_cursor.x].value == _goal[0]) {
// Fusion reussie
oslPlaySound(_se.success, 2);
_score += _goal[0] * _combo;
_combo += 1;
if (_combo > _maxCombo) _maxCombo = _combo;
_map[_cursor.y][_cursor.x].value = -1;
_map[_cursor.y][_cursor.x].effectDisplay = EFFECT_WHITE;
_map[_cursor.y][_cursor.x].effectTimer = 30;
addGoal();
} else if (_map[_cursor.y][_cursor.x].value > 9) {
oslPlaySound(_se.fail, 2);
_hp -= _map[_cursor.y][_cursor.x].value;
_combo = 1;
_map[_cursor.y][_cursor.x].value -= 10;
_map[_cursor.y][_cursor.x].effectDisplay = EFFECT_RED;
_map[_cursor.y][_cursor.x].effectTimer = 30;
}
}
// Cas d'une ligne remplie
for (y = 0; y < 8; y++) {
loseHP = true;
for (x = 0; x < 12; x++) loseHP &= (_map[y][x].value != -1);
if (loseHP) {
_hp--;
break;
}
}
// Hp restant
if (_hp <= 0) {
_hp = 0;
_maxCombo--;
_currentChar = 0;
_status = GAME_OVER;
}
}
void NumScene::drawGame(void) {
int x, y;
int explosionSize;
OSL_IMAGE *boom;
// Déplacement du background
_img.background->x++;
if (_img.background->x == 0) _img.background->x = -32;
_img.slide->x += 2;
if (_img.slide->x == 480) _img.slide->x = -128;
// Gestion des explosions
for (y = 0; y < 8; y++)
for (x = 0; x < 12; x++) {
if (_map[y][x].effectDisplay == EFFECT_NONE) continue;
_map[y][x].effectTimer -= 5;
if (_map[y][x].effectTimer < 0) _map[y][x].effectDisplay = EFFECT_NONE;
}
// Background
oslDrawImage(_img.background);
oslDrawImage(_img.slide);
oslDrawImage(_img.playArea);
// Dessine les blocs
for (y = 0; y < 8; y++)
for (x = 0; x < 12; x++) {
if (_map[y][x].value == -1) continue;
_img.block->x = (x << 5) + 88 + _map[y][x].position;
_img.block->y = (y << 5) + 8;
oslSetImageFrame(_img.block, _map[y][x].value);
oslDrawImage(_img.block);
}
// Dessine les explosions
for (y = 0; y < 8; y++)
for (x = 0; x < 12; x++) {
if (_map[y][x].effectDisplay == EFFECT_NONE) continue;
if (_map[y][x].effectDisplay == EFFECT_RED) boom = _img.boomRed;
else boom = _img.boomWhite;
explosionSize = 60 + _map[y][x].effectTimer;
boom->stretchX = explosionSize;
boom->stretchY = explosionSize;
boom->x = (x << 5) + 104 - (explosionSize >> 1);
boom->y = (y << 5) + 24 - (explosionSize >> 1);
oslDrawImage(boom);
}
// Le curseur
_img.cursor->x = (_cursor.x << 5) + 88;
_img.cursor->y = (_cursor.y << 5) + 8;
oslDrawImage(_img.cursor);
// Score et HP
printNum(8, 26, _score, 6, false);
printNum(8, 90, _hp, 3, true);
// Blocs suivants
oslSetImageFrame(_img.goal40, _goal[0]);
oslDrawImage(_img.goal40);
_img.goal32->y = 196;
oslSetImageFrame(_img.goal32, _goal[1]);
oslDrawImage(_img.goal32);
_img.goal32->y = 229;
oslSetImageFrame(_img.goal32, _goal[2]);
oslDrawImage(_img.goal32);
}
void NumScene::updatePause(void) {
// Gestion des touches
if (osl_pad.pressed.start) _status = GAME_PLAYING;
}
void NumScene::drawPause(void) {
drawGame();
oslDrawFillRect(0, 0, 480, 272, 0xCCFFFFFF);
printText(202, 110, "Paused");
printText(110, 144, "Press Start to resume");
}
void NumScene::updateHighScores(void) {
// Gestion des touches
if (osl_pad.pressed.circle) {
_status = GAME_MENU;
if (_oldStatus == GAME_OVER) {
oslStopSound(_bgm.game);
oslPlaySound(_bgm.menu, 0);
}
}
}
void NumScene::drawHighScores(void) {
int i;
if (_oldStatus == GAME_OVER) drawGame();
else if (_oldStatus == GAME_MENU) drawMenu();
else oslDrawFillRect(0, 0, 480, 272, 0xFFFFFFFF); // Will never happen
oslDrawFillRect(0, 0, 480, 272, 0xCCFFFFFF);
oslDrawImageXY(_img.name, 92, 20);
oslDrawImageXY(_img.combo, 228, 20);
oslDrawImageXY(_img.score, 342, 20);
oslDrawImage(_img.pressKey);
for (i = 0; i < 10; i++) {
printRawText(64, 46 + 18 * i, _highScores[i].name, 8);
printNum(230, 46 + 18 * i, _highScores[i].combo, 3, true);
printNum(330, 46 + 18 * i, _highScores[i].score, 6, false);
}
}
void NumScene::updateGameOver(void) {
int i, j, k;
char c;
if (osl_pad.pressed.circle) {
// En cas de nouveau highscore
if (_score > _highScores[9].score) {
// On copie les infos en derniere position
for (i = 0; i < 8; i++) _highScores[9].name[i] = _playerName[i];
_highScores[9].combo = _maxCombo;
_highScores[9].score = _score;
// Et on remonte le score tant qu'il est superieur
i = 9;
while (1) {
if (i == 0) break;
else if (_highScores[i].score < _highScores[i - 1].score) break;
else if (_highScores[i].score == _highScores[i - 1].score &&
_highScores[i].combo < _highScores[i - 1].combo)
break;
// Inversion des noms
for (j = 0; j < 8; j++) {
c = _highScores[i].name[j];
_highScores[i].name[j] = _highScores[i - 1].name[j];
_highScores[i - 1].name[j] = c;
}
// Inversion des scores / combo
k = _highScores[i].combo;
_highScores[i].combo = _highScores[i - 1].combo;
_highScores[i - 1].combo = k;
k = _highScores[i].score;
_highScores[i].score = _highScores[i - 1].score;
_highScores[i - 1].score = k;
i--;
}
saveScores();
}
_oldStatus = GAME_OVER;
_status = GAME_HSCORES;
}
if (_score > _highScores[9].score) {
if (osl_pad.pressed.left) _currentChar = (_currentChar + 7) % 8;
else if (osl_pad.pressed.right) _currentChar = (_currentChar + 1) % 8;
if (osl_pad.pressed.up) _playerName[_currentChar] = (_playerName[_currentChar] + 1) % 43;
else if (osl_pad.pressed.down) _playerName[_currentChar] = (_playerName[_currentChar] + 42) % 43;
}
}
void NumScene::drawGameOver(void) {
drawGame();
oslDrawFillRect(0, 0, 480, 272, 0xCCFFFFFF);
printText(186, 35, "Game Over");
oslDrawImageXY(_img.combo, 215, 70);
printNum(222, 90, _maxCombo, 3, true);
oslDrawImageXY(_img.score, 215, 120);
printNum(205, 140, _score, 6, false);
if (_score > _highScores[9].score) {
printText(150, 180, "Enter your Name");
oslDrawLine(191, 213, 289, 213, 0xFF000000);
oslDrawFillRect(191 + 12 * _currentChar, 199, 204 + 12 * _currentChar, 213, 0x80FF0000);
printRawText(192, 200, _playerName, 8);
}
oslDrawImage(_img.pressKey);
}
void NumScene::updateCredits(void) {
if (osl_pad.pressed.circle) _status = GAME_MENU;
}
void NumScene::drawCredits(void) {
int y = 14;
drawMenu();
oslDrawFillRect(0, 0, 480, 272, 0xCCFFFFFF);
printText(20, y, "Credits");
y += 10;
printTextMini(30, y += 18, "Coding : Kcazer");
printTextMini(44, y += 12, "http://tsundere.fr");
printTextMini(30, y += 18, "Original idea : Gil Bear");
printTextMini(44, y += 12, "http://gil.nobody.jp");
printTextMini(30, y += 18, "PSP Library : OSLib");
printTextMini(44, y += 12, "http://oslib.playeradvance.org");
printTextMini(30, y += 18, "BGM : SILDRA COMPANY");
printTextMini(44, y += 12, "http://sildra.ddo.jp");
printTextMini(30, y += 18, "Sound effects : OSA");
printTextMini(44, y += 12, "http://osabisi.sakura.ne.jp");
printTextMini(30, y += 18, "Fonts :");
printTextMini(44, y += 12, "- MW QUOIN : http://www.milkwort.org");
printTextMini(44, y += 12, "- Visitor");
oslDrawImage(_img.pressKey);
}
void NumScene::startGame(void) {
int x, y;
// Initialisation map
for (y = 0; y < 8; y++)
for (x = 0; x < 12; x++) {
_map[y][x].value = ((x < 3) ? rand() % 10 : -1);
_map[y][x].effectDisplay = EFFECT_NONE;
_map[y][x].position = 0;
}
// Divers
_hp = 100;
_speed = 8;
_score = 0;
_combo = 1;
_maxCombo = 1;
_status = GAME_PLAYING;
oslStopSound(_bgm.menu);
oslPlaySound(_bgm.game, 0);
_timer = 5;
addGoal();
addGoal();
addGoal();
}
void NumScene::addBlock(void) {
int y = rand() % 8;
_map[y][11].value = rand() % 10;
_map[y][11].position = 0;
}
void NumScene::addGoal(void) {
_goal[0] = _goal[1];
_goal[1] = _goal[2];
_goal[2] = 5 + rand() % 12;
}
void NumScene::printRawText(int x, int y, char *text, int size) {
char c;
int i = 0;
_img.font->x = x;
_img.font->y = y;
while (size-- != 0) {
c = text[i++];
if (c < 42) {
oslSetImageFrame(_img.font, c);
oslDrawImage(_img.font);
}
_img.font->x += 12;
}
}
void NumScene::printText(int x, int y, char *text) {
int i = 0;
char c;
_img.font->x = x;
_img.font->y = y;
while ((c = text[i++]) != 0) {
if (c >= '0' && c <= '9') c = c - '0';
else if (c >= 'a' && c <= 'z') c = c - 'a' + 10;
else if (c >= 'A' && c <= 'Z') c = c - 'A' + 10;
else if (c == ' ') c = -1;
else if (c == '@') c = 36;
else if (c == '-') c = 37;
else if (c == '_') c = 38;
else if (c == ':') c = 39;
else if (c == '.') c = 40;
else if (c == '/') c = 41;
else c = -1;
if (c >= 0) {
oslSetImageFrame(_img.font, c);
oslDrawImage(_img.font);
}
_img.font->x += 12;
}
}
void NumScene::printTextMini(int x, int y, char *text) {
int i = 0;
char c;
_img.fontMini->x = x;
_img.fontMini->y = y;
while ((c = text[i++]) != 0) {
if (c >= '0' && c <= '9') c = c - '0';
else if (c >= 'a' && c <= 'z') c = c - 'a' + 10;
else if (c >= 'A' && c <= 'Z') c = c - 'A' + 10;
else if (c == ' ') c = -1; // Optimisation
else if (c == '@') c = 36;
else if (c == '-') c = 37;
else if (c == '_') c = 38;
else if (c == ':') c = 39;
else if (c == '.') c = 40;
else if (c == '/') c = 41;
else c = -1;
if (c >= 0) {
oslSetImageFrame(_img.fontMini, c);
oslDrawImage(_img.fontMini);
}
_img.fontMini->x += 6;
}
}
void NumScene::printNum(int x, int y, int num, int pad, bool hideZero) {
int num2 = num;
bool first = true;
if (pad == 0) while (num2 /= 10) pad++;
_img.font->x = x + 12 * (pad - 1);
_img.font->y = y;
while (pad > 0 || num != 0) {
oslSetImageFrame(_img.font, num % 10);
if (num != 0 || !hideZero || first) oslDrawImage(_img.font);
num = (num - (num % 10)) / 10;
_img.font->x -= 12;
first = false;
pad--;
}
}
void NumScene::loadScores(void) {
int i, j, b0, b1, b2, b3;
FILE *f = fopen("scores.dat", "rb");
if (f == NULL) {
for (i = 0; i < 10; i++) {
for (j = 0; j < 8; j++) _highScores[i].name[j] = 37;
_highScores[i].combo = 0;
_highScores[i].score = 0;
}
saveScores();
} else {
for (i = 0; i < 10; i++) {
for (j = 0; j < 8; j++) _highScores[i].name[j] = fgetc(f);
b1 = fgetc(f);
b0 = fgetc(f);
_highScores[i].combo = (b1 << 8) | b0;
b3 = fgetc(f);
b2 = fgetc(f);
b1 = fgetc(f);
b0 = fgetc(f);
_highScores[i].score = (b3 << 0x18) | (b2 << 0x10) | (b1 << 0x08) | b0;
}
}
fclose(f);
}
void NumScene::saveScores(void) {
int i, j;
FILE *f = fopen("scores.dat", "wb");
if (f == NULL) oslDebug("Error saving HighScores");
else {
for (i = 0; i < 10; i++) {
for (j = 0; j < 8; j++) fputc(_highScores[i].name[j], f);
fputc((_highScores[i].combo >> 0x08) & 0xFF, f);
fputc((_highScores[i].combo >> 0x00) & 0xFF, f);
fputc((_highScores[i].score >> 0x18) & 0xFF, f);
fputc((_highScores[i].score >> 0x10) & 0xFF, f);
fputc((_highScores[i].score >> 0x08) & 0xFF, f);
fputc((_highScores[i].score >> 0x00) & 0xFF, f);
}
fclose(f);
}
}
| 32.851227 | 120 | 0.524534 |
420173a5e0f49f6d9fc8da4b577e813c3708bfdc | 2,152 | hh | C++ | yagi/include/typemanager.hh | IDAPluginProject/Yagi | a4528c83dff7f87c804140727b06e0359aca1d99 | [
"Apache-2.0"
] | null | null | null | yagi/include/typemanager.hh | IDAPluginProject/Yagi | a4528c83dff7f87c804140727b06e0359aca1d99 | [
"Apache-2.0"
] | null | null | null | yagi/include/typemanager.hh | IDAPluginProject/Yagi | a4528c83dff7f87c804140727b06e0359aca1d99 | [
"Apache-2.0"
] | null | null | null | #ifndef __YAGI_TYPEMANAGER__
#define __YAGI_TYPEMANAGER__
#include <libdecomp.hh>
#include <vector>
#include <string>
#include <optional>
#include <map>
#include <string>
#include "yagiarchitecture.hh"
namespace yagi
{
/*!
* \brief Factory become a manager because it's based on the factory backend link to IDA
*/
class TypeManager : public TypeFactory
{
protected:
/*!
* \brief pointer the global architecture
*/
YagiArchitecture* m_archi;
/*!
* \brief find type by inner id
* \param n name of the type
* \param id id of the type
* \return found type
*/
Datatype* findById(const string& n, uint8 id) override;
/*!
* \brief inject API is not available throw normal API
* We need to use XML tricks...
* \param fd function data to update
* \param inject_name name of th injection
*/
void setInjectAttribute(Funcdata& fd, std::string inject_name);
public:
/*!
* \brief ctor
*/
explicit TypeManager(YagiArchitecture* architecture);
virtual ~TypeManager() = default;
/*!
* \brief Disable copy of IdaTypeFactory prefer moving
*/
TypeManager(const TypeManager&) = delete;
TypeManager& operator=(const TypeManager&) = delete;
/*!
* \brief Moving is allowed because unique_ptr allow it
* and we use std map as container
*/
TypeManager(TypeManager&&) noexcept = default;
TypeManager& operator=(TypeManager&&) noexcept = default;
/*!
* \brief Parse a function information type interface
* Try to create a Ghidra type code
* \param typeInfo backend type information
*/
TypeCode* parseFunc(const FuncInfo& typeInfo);
/*!
* \brief parse a type information generic interface
* to transform into ghidra type
* \param backend type information interface
* \return ghidra type
*/
Datatype* parseTypeInfo(const TypeInfo& typeInfo);
/*!
* \brief Find a type from typeinformation interface
* \param typeInfo interface to find
* \return ghidra type
*/
Datatype* findByTypeInfo(const TypeInfo& typeInfo);
/*!
* \brief update function information data
*/
void update(Funcdata& func);
};
}
#endif | 23.139785 | 89 | 0.687268 |
4202991db01e0316b69e96b60cf6cbb67b6cd5c4 | 4,708 | hh | C++ | RAVL2/Math/Optimisation/ObsVectorBiGaussian.hh | isuhao/ravl2 | 317e0ae1cb51e320b877c3bad6a362447b5e52ec | [
"BSD-Source-Code"
] | null | null | null | RAVL2/Math/Optimisation/ObsVectorBiGaussian.hh | isuhao/ravl2 | 317e0ae1cb51e320b877c3bad6a362447b5e52ec | [
"BSD-Source-Code"
] | null | null | null | RAVL2/Math/Optimisation/ObsVectorBiGaussian.hh | isuhao/ravl2 | 317e0ae1cb51e320b877c3bad6a362447b5e52ec | [
"BSD-Source-Code"
] | null | null | null | // This file is part of RAVL, Recognition And Vision Library
// Copyright (C) 2002, University of Surrey
// This code may be redistributed under the terms of the GNU Lesser
// General Public License (LGPL). See the lgpl.licence file for details or
// see http://www.gnu.org/copyleft/lesser.html
// file-header-ends-here
#ifndef RAVLMATH_OBSVECTORBIGAUSSIAN_HEADER
#define RAVLMATH_OBSVECTORBIGAUSSIAN_HEADER 1
//! userlevel=Normal
//! author="Phil McLauchlan"
//! date="24/7/2002"
//! rcsid="$Id: ObsVectorBiGaussian.hh 6819 2008-05-30 12:01:36Z ees1wc $"
//! docentry="Ravl.API.Pattern Recognition.Optimisation2"
//! lib=RavlOptimise
//! file="Ravl/Math/Optimisation/ObsVectorBiGaussian.hh"
#include "Ravl/ObsVector.hh"
namespace RavlN {
//! userlevel=Develop
//: Robust bi-gaussian observation vector body.
class ObsVectorBiGaussianBodyC
: public ObsVectorBodyC
{
public:
ObsVectorBiGaussianBodyC(const VectorC &z, const MatrixRSC &Ni,
RealT varScale, RealT chi2Thres);
//: Constructor.
ObsVectorBiGaussianBodyC(const VectorC &z, const MatrixRSC &Ni,
const VectorC &zstep,
RealT varScale, RealT chi2Thres);
//: Constructor.
virtual double Residual(const VectorC &v, const MatrixRSC &Ni);
//: Return residual adjusted for any robust aspects to the observation
virtual bool AdjustInformation(MatrixRSC &Aterm, VectorC &aterm);
//: Adjust information matrix/vector term for any robustness
virtual bool Restore();
//: Restore values are an aborted modification
bool Outlier() const;
//: Get outlier flag
void SetAsInlier();
//: Set observation to be an inlier
void SetAsOutlier();
//: Set observation to be an outlier
protected:
RealT varInvScale; // inverse scaling of outlier covariance
RealT chi2Thres; // cut-off point for chi^2 to switch to outlier
// distribution
RealT chi2Offset; // adjustment to chi^2 residual for outlier distribution
bool outlier; // whether the observation is an outlier (true) or an inlier
bool previousOutlierFlag; // stored outlier flag
};
//! userlevel=Normal
//! autoLink=on
//: Robust bi-gaussian observation vector class
// This class adds robustness to the ObsVectorC class, using a simple
// bi-Gaussian error model with a narrow inlier Gaussian and a wider
// outlier Gaussian distribution, as described
// <a href="../../../LevenbergMarquardt/node1.html">here</a>.
class ObsVectorBiGaussianC
: public ObsVectorC
{
public:
ObsVectorBiGaussianC(const VectorC &z, const MatrixRSC &Ni,
RealT varScale, RealT chi2Thres)
: ObsVectorC(*new ObsVectorBiGaussianBodyC(z,Ni,varScale,chi2Thres))
{}
//: Constructor
// varScale is the covariance scaling K parameter in the
// <a href="../../../LevenbergMarquardt/node1.html">theory document</a>,
// and chi2Thres is the chi-squared cutoff parameter.
ObsVectorBiGaussianC(const VectorC &z, const MatrixRSC &Ni,
const VectorC &zstep,
RealT varScale, RealT chi2Thres)
: ObsVectorC(*new ObsVectorBiGaussianBodyC(z,Ni,zstep,varScale,chi2Thres))
{}
//: Constructor
// varScale is the covariance scaling K parameter in the
// <a href="../../../LevenbergMarquardt/node1.html">theory document</a>,
// and chi2Thres is the chi-squared cutoff parameter.
// This constructor also allows you to specify a vector zstep of step
// sizes for numerical differentiation with respect to the elements of z,
// overriding the default step size (1e-6).
ObsVectorBiGaussianC(const ObsVectorC &obs)
: ObsVectorC(dynamic_cast<const ObsVectorBiGaussianBodyC *>(BodyPtr(obs)))
{}
//: Base class constructor.
ObsVectorBiGaussianC()
{}
//: Default constructor.
// Creates an invalid handle.
protected:
ObsVectorBiGaussianC(ObsVectorBiGaussianBodyC &bod)
: ObsVectorC(bod)
{}
//: Body constructor.
ObsVectorBiGaussianC(const ObsVectorBiGaussianBodyC *bod)
: ObsVectorC(bod)
{}
//: Body constructor.
ObsVectorBiGaussianBodyC &Body()
{ return static_cast<ObsVectorBiGaussianBodyC &>(ObsVectorC::Body()); }
//: Access body.
const ObsVectorBiGaussianBodyC &Body() const
{ return static_cast<const ObsVectorBiGaussianBodyC &>(ObsVectorC::Body()); }
//: Access body.
public:
bool Outlier() const
{ return Body().Outlier(); }
//: Get outlier flag
void SetAsInlier()
{ Body().SetAsInlier(); }
//: Set observation to be an inlier
void SetAsOutlier()
{ Body().SetAsOutlier(); }
//: Set observation to be an outlier
};
}
#endif
| 32.468966 | 81 | 0.692863 |
4205cdc7e2b4bddf33ed0e00e0733c4c3dc1878f | 2,809 | cpp | C++ | sim/fb_verilator.cpp | mattvenn/xor_vga_fpga | 1fd00b155d253505d44124ec649e13e262e99402 | [
"Apache-2.0"
] | 10 | 2021-04-19T19:55:02.000Z | 2022-03-17T00:19:30.000Z | sim/fb_verilator.cpp | kelu124/xor_vga_fpga | 1fd00b155d253505d44124ec649e13e262e99402 | [
"Apache-2.0"
] | null | null | null | sim/fb_verilator.cpp | kelu124/xor_vga_fpga | 1fd00b155d253505d44124ec649e13e262e99402 | [
"Apache-2.0"
] | 2 | 2021-04-19T19:55:05.000Z | 2021-05-28T05:23:18.000Z | #include <iostream>
#include <cmath>
#include <vector>
#include <cstdlib>
#include <SDL2/SDL.h>
#include "Vxor.h"
#include "verilated.h"
#define WINDOW_WIDTH 640
#define WINDOW_HEIGHT 480
int main(int argc, char **argv) {
std::vector< uint8_t > framebuffer(WINDOW_WIDTH * WINDOW_HEIGHT * 4, 0);
Verilated::commandArgs(argc, argv);
Vxor *top = new Vxor;
// perform a reset
top->clk = 0;
top->eval();
top->reset_n = 0;
top->clk = 1;
top->eval();
top->reset_n = 1;
SDL_Init(SDL_INIT_VIDEO);
SDL_Window* window =
SDL_CreateWindow(
"Framebuffer Verilator",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
WINDOW_WIDTH,
WINDOW_HEIGHT,
0
);
SDL_Renderer* renderer =
SDL_CreateRenderer(
window,
-1,
SDL_RENDERER_ACCELERATED
);
SDL_SetRenderDrawColor(renderer, 0, 0, 0, SDL_ALPHA_OPAQUE);
SDL_RenderClear(renderer);
SDL_Event e;
SDL_Texture* texture =
SDL_CreateTexture(
renderer,
SDL_PIXELFORMAT_ARGB8888,
SDL_TEXTUREACCESS_STREAMING,
WINDOW_WIDTH,
WINDOW_HEIGHT
);
bool quit = false;
int hnum = 0;
int vnum = 0;
while (!quit) {
while (SDL_PollEvent(&e) == 1) {
if (e.type == SDL_QUIT) {
quit = true;
} else if (e.type == SDL_KEYDOWN) {
switch (e.key.keysym.sym) {
case SDLK_q:
quit = true;
default:
break;
}
}
}
auto keystate = SDL_GetKeyboardState(NULL);
top->reset_n = !keystate[SDL_SCANCODE_ESCAPE];
top->but1 = keystate[SDL_SCANCODE_1];
top->but2 = keystate[SDL_SCANCODE_2];
top->but3 = keystate[SDL_SCANCODE_3];
// simulate for 20000 clocks
for (int i = 0; i < 20000; ++i) {
top->clk = 0;
top->eval();
top->clk = 1;
top->eval();
// h and v blank logic
if ((0 == top->hsync) && (0 == top->vsync)) {
hnum = -128;
vnum = -28;
}
// active frame
if ((hnum >= 0) && (hnum < 640) && (vnum >= 0) && (vnum < 480)) {
framebuffer.at((vnum * WINDOW_WIDTH + hnum) * 4 + 0) = (top->rrggbb & 0b000011) >> 0 << 6;
framebuffer.at((vnum * WINDOW_WIDTH + hnum) * 4 + 1) = (top->rrggbb & 0b001100) >> 2 << 6;
framebuffer.at((vnum * WINDOW_WIDTH + hnum) * 4 + 2) = (top->rrggbb & 0b110000) >> 4 << 6;
}
// keep track of encountered fields
hnum++;
if (hnum >= 640 + 24 + 40) {
hnum = -128;
vnum++;
}
if (vnum >= 480 + 9 + 3) {
vnum = -28;
}
}
SDL_UpdateTexture(
texture,
NULL,
framebuffer.data(),
WINDOW_WIDTH * 4
);
SDL_RenderCopy(
renderer,
texture,
NULL,
NULL
);
SDL_RenderPresent(renderer);
}
top->final();
delete top;
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
return EXIT_SUCCESS;
}
| 18.726667 | 94 | 0.585974 |
4209ff0888a7f6dca51e4085495aad3986c64da4 | 4,052 | cpp | C++ | qamsource/podmgr/podserver/cardmanager/cardMibAcc.cpp | rdkcmf/rdk-mediaframework | 55c7753eedaeb15719c5825f212372857459a87e | [
"Apache-2.0"
] | null | null | null | qamsource/podmgr/podserver/cardmanager/cardMibAcc.cpp | rdkcmf/rdk-mediaframework | 55c7753eedaeb15719c5825f212372857459a87e | [
"Apache-2.0"
] | null | null | null | qamsource/podmgr/podserver/cardmanager/cardMibAcc.cpp | rdkcmf/rdk-mediaframework | 55c7753eedaeb15719c5825f212372857459a87e | [
"Apache-2.0"
] | null | null | null | /*
* If not stated otherwise in this file or this component's LICENSE file the
* following copyright and licenses apply:
*
* Copyright 2011 RDK Management
*
* 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 <unistd.h>
#ifdef GCC4_XXX
#include <list>
#else
#include <list.h>
#endif
//#include "pfcresource.h"
#include "cardUtils.h"
#include "cmhash.h"
#include "rmf_osal_event.h"
#include "core_events.h"
#include "cardmanager.h"
#include "cmevents.h"
#include "cardMibAcc.h"
//#include "pfcpluginbase.h"
//#include "pmt.h"
#include "poddriver.h"
#include "cm_api.h"
//#include <string.h>
#define __MTAG__ VL_CARD_MANAGER
cCardMibAcc::cCardMibAcc(CardManager *cm,char *name):CMThread(name)
{
//RDK_LOG(RDK_LOG_DEBUG, "LOG.RDK.TARGET","cCardRes::cCardRes()\n");
RDK_LOG(RDK_LOG_DEBUG, "LOG.RDK.POD","Entered ..... cCardMibAcc::cCardMibAcc ###################### \n");
this->cm = cm;
event_queue = 0;
}
cCardMibAcc::~cCardMibAcc(){}
void cCardMibAcc::initialize(void)
{
rmf_osal_eventmanager_handle_t em = get_pod_event_manager();
rmf_osal_eventqueue_handle_t eq ;
rmf_osal_eventqueue_create ( (const uint8_t* ) "cCardMibAcc",
&eq );
// PodMgrEventListener *listener;
RDK_LOG(RDK_LOG_DEBUG, "LOG.RDK.POD","Entered ..... cCardMibAcc::initialize ###################### \n");
RDK_LOG(RDK_LOG_DEBUG, "LOG.RDK.TARGET","cCardMibAcc::initialize()\n");
rmf_osal_eventmanager_register_handler(
em, eq, RMF_OSAL_EVENT_CATEGORY_CARD_MIB_ACC
);
this->event_queue = eq;
//listener = new PodMgrEventListener(cm, eq,"ResourceManagerThread);
////VLALLOC_INFO2(listener, sizeof(PodMgrEventListener));
RDK_LOG(RDK_LOG_DEBUG, "LOG.RDK.TARGET","cCardMibAcc::initialize() eq=%p\n",(void *)eq);
//listener->start();
}
//static vlCableCardCertInfo_t CardCertInfo;
void cCardMibAcc::run(void )
{
rmf_osal_eventmanager_handle_t em = get_pod_event_manager();
rmf_osal_event_handle_t event_handle_rcv;
rmf_osal_event_params_t event_params_rcv = {0};
rmf_osal_event_category_t event_category;
uint32_t event_type;
RDK_LOG(RDK_LOG_DEBUG, "LOG.RDK.POD","Entered ..... cCardMibAcc::run ###################### \n");
RDK_LOG(RDK_LOG_DEBUG, "LOG.RDK.TARGET","cCardMibAcc::Run()\n");
cardMibAcc_init();
while (1)
{
int result = 0;
RDK_LOG(RDK_LOG_DEBUG, "LOG.RDK.POD","#############cCardMibAcc::run waiting for Event #################\n");
rmf_osal_eventqueue_get_next_event( event_queue,
&event_handle_rcv, &event_category, &event_type, &event_params_rcv);
RDK_LOG(RDK_LOG_DEBUG, "LOG.RDK.POD","#############cCardMibAcc::After run waiting for Event #################\n");
switch (event_category)
{
case RMF_OSAL_EVENT_CATEGORY_CARD_MIB_ACC:
RDK_LOG(RDK_LOG_DEBUG, "LOG.RDK.TARGET","cCardMibAcc::PFC_EVENT_CATEGORY_CARD_MIB_ACC\n");
RDK_LOG(RDK_LOG_DEBUG, "LOG.RDK.POD"," ########### cCardMibAcc:RMF_OSAL_EVENT_CATEGORY_CARD_MIB_ACC ######### \n");
RDK_LOG(RDK_LOG_DEBUG, "LOG.RDK.POD"," ########### calling cardMibAccProc ########## \n");
if( event_params_rcv.data ) cardMibAccProc(event_params_rcv.data);
// GetCableCardCertInfo(&CardCertInfo);
break;
default:
RDK_LOG(RDK_LOG_DEBUG, "LOG.RDK.TARGET","cCardMibAcc::default\n");
break;
}
rmf_osal_event_delete(event_handle_rcv);
}
}
| 31.905512 | 131 | 0.662142 |
420a42cce075876c01340818edbe4721e3914442 | 2,370 | hpp | C++ | include/mgpp/signals/dispatcher.hpp | mjgigli/libmgpp | 87cec591ccb2a9d9e1f0eb4a2121ff95128c0bb0 | [
"MIT"
] | 1 | 2018-12-22T17:35:45.000Z | 2018-12-22T17:35:45.000Z | include/mgpp/signals/dispatcher.hpp | mjgigli/libmgpp | 87cec591ccb2a9d9e1f0eb4a2121ff95128c0bb0 | [
"MIT"
] | null | null | null | include/mgpp/signals/dispatcher.hpp | mjgigli/libmgpp | 87cec591ccb2a9d9e1f0eb4a2121ff95128c0bb0 | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2018 Matt Gigli
*
* 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.
*/
#ifndef MGPP_SIGNALS_DISPATCHER_HPP_
#define MGPP_SIGNALS_DISPATCHER_HPP_
#include <memory>
#include <unordered_map>
#include <boost/signals2.hpp>
#include <mgpp/signals/event.hpp>
namespace mgpp {
namespace signals {
// Define callback templates and pointer types
using EventCallbackTemplate = void(EventConstPtr);
using EventCallback = std::function<EventCallbackTemplate>;
template <typename T>
using EventMemberCallback = void (T::*)(EventConstPtr);
// Use boost signals2 signals/slots for the event dispatcher
typedef boost::signals2::signal<EventCallbackTemplate> EventSignal;
typedef boost::signals2::connection Connection;
// Subscribe functions
Connection Subscribe(const int id, const EventCallback cb);
template <typename T>
Connection Subscribe(const int id, const EventMemberCallback<T> mcb,
const T &obj) {
return Subscribe(id, boost::bind(mcb, const_cast<T *>(&obj), _1));
}
// Unsubscribe functions
void Unsubscribe(const int id, const Connection &conn);
// UnsubscribeAll function
void UnsubscribeAll(const int id = -1);
// Publish function
void Publish(EventConstPtr event);
int NumSlots(const int id);
} // namespace signals
} // namespace mgpp
#endif // MGPP_SIGNALS_DISPATCHER_HPP_
| 32.465753 | 79 | 0.760338 |
420a73e53d87a32974de4f226355d88e52041e13 | 1,245 | hpp | C++ | gvsoc/gvsoc_gap/models/pulp/udma/sfu/udma_sfu_v1_empty.hpp | 00-01/gap_sdk | 25444d752b26ccf0b848301c381692d77172852c | [
"Apache-2.0"
] | 118 | 2018-05-22T08:45:59.000Z | 2022-03-30T07:00:45.000Z | gvsoc/gvsoc_gap/models/pulp/udma/sfu/udma_sfu_v1_empty.hpp | 00-01/gap_sdk | 25444d752b26ccf0b848301c381692d77172852c | [
"Apache-2.0"
] | 213 | 2018-07-25T02:37:32.000Z | 2022-03-30T18:04:01.000Z | gvsoc/gvsoc_gap/models/pulp/udma/sfu/udma_sfu_v1_empty.hpp | 00-01/gap_sdk | 25444d752b26ccf0b848301c381692d77172852c | [
"Apache-2.0"
] | 76 | 2018-07-04T08:19:27.000Z | 2022-03-24T09:58:05.000Z | /*
* Copyright (C) 2020 GreenWaves Technologies, SAS
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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 <https://www.gnu.org/licenses/>.
*/
/*
* Authors: Vladimir Popovic, GreenWaves Technologies (vladimir.popovic@greenwaves-technologies.com)
*/
#ifndef __PULP_UDMA_UDMA_SFU_V1_EMPTY_HPP__
#define __PULP_UDMA_UDMA_SFU_V1_EMPTY_HPP__
#include <vp/vp.hpp>
#include "../udma_impl.hpp"
class Sfu_periph_empty : public Udma_periph
{
public:
Sfu_periph_empty(udma *top, int id, int itf_id);
vp::io_req_status_e custom_req(vp::io_req *req, uint64_t offset);
vp::trace trace;
private:
vp::wire_master<bool> irq;
};
#endif | 27.666667 | 100 | 0.738956 |
420eea7d8446fc86ddd296db29aee2919795b575 | 1,733 | cpp | C++ | inference-engine/tests/functional/plugin/shared/src/low_precision_transformations/fake_quantize_transformation.cpp | szabi-luxonis/openvino | c8dd831fc3ba68a256ab47edb4f6bf3cb5e804be | [
"Apache-2.0"
] | 2 | 2020-11-18T14:14:06.000Z | 2020-11-28T04:55:57.000Z | inference-engine/tests/functional/plugin/shared/src/low_precision_transformations/fake_quantize_transformation.cpp | szabi-luxonis/openvino | c8dd831fc3ba68a256ab47edb4f6bf3cb5e804be | [
"Apache-2.0"
] | 30 | 2020-11-13T11:44:07.000Z | 2022-02-21T13:03:16.000Z | inference-engine/tests/functional/plugin/shared/src/low_precision_transformations/fake_quantize_transformation.cpp | szabi-luxonis/openvino | c8dd831fc3ba68a256ab47edb4f6bf3cb5e804be | [
"Apache-2.0"
] | 1 | 2020-12-18T15:47:45.000Z | 2020-12-18T15:47:45.000Z | // Copyright (C) 2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "low_precision_transformations/fake_quantize_transformation.hpp"
#include <memory>
#include <tuple>
#include <vector>
#include <string>
#include <ie_core.hpp>
#include <transformations/init_node_info.hpp>
namespace LayerTestsDefinitions {
std::string FakeQuantizeTransformation::getTestCaseName(testing::TestParamInfo<FakeQuantizeTransformationParams> obj) {
InferenceEngine::Precision netPrecision;
InferenceEngine::SizeVector inputShapes;
std::string targetDevice;
ngraph::pass::low_precision::LayerTransformation::Params params;
ngraph::builder::subgraph::FakeQuantizeOnData fakeQuantizeOnData;
std::tie(netPrecision, inputShapes, targetDevice, params, fakeQuantizeOnData) = obj.param;
std::ostringstream result;
result << getTestCaseNameByParams(netPrecision, inputShapes, targetDevice, params) << "_" << fakeQuantizeOnData;
return result.str();
}
void FakeQuantizeTransformation::SetUp() {
InferenceEngine::SizeVector inputShape;
InferenceEngine::Precision netPrecision;
ngraph::pass::low_precision::LayerTransformation::Params params;
ngraph::builder::subgraph::FakeQuantizeOnData fakeQuantizeOnData;
std::tie(netPrecision, inputShape, targetDevice, params, fakeQuantizeOnData) = this->GetParam();
function = ngraph::builder::subgraph::FakeQuantizeFunction::getOriginal(
FuncTestUtils::PrecisionUtils::convertIE2nGraphPrc(netPrecision),
inputShape,
fakeQuantizeOnData);
ngraph::pass::InitNodeInfo().run_on_function(function);
}
TEST_P(FakeQuantizeTransformation, CompareWithRefImpl) {
Run();
};
} // namespace LayerTestsDefinitions
| 34.66 | 119 | 0.772072 |
420fa54eaa3be9dcf96fa5c8b82d540805cf1f24 | 2,021 | cpp | C++ | src/test/mempool_sync_tests.cpp | MONIMAKER365/BitcoinUnlimited | 8aea282c44ee23ca65cdd895c99b3f6347f46dfc | [
"MIT"
] | 535 | 2015-09-04T15:10:08.000Z | 2022-03-17T20:51:05.000Z | src/test/mempool_sync_tests.cpp | MONIMAKER365/BitcoinUnlimited | 8aea282c44ee23ca65cdd895c99b3f6347f46dfc | [
"MIT"
] | 1,269 | 2016-01-31T20:21:24.000Z | 2022-03-16T01:20:08.000Z | src/test/mempool_sync_tests.cpp | MONIMAKER365/BitcoinUnlimited | 8aea282c44ee23ca65cdd895c99b3f6347f46dfc | [
"MIT"
] | 295 | 2015-10-19T16:12:29.000Z | 2021-08-02T20:05:17.000Z | // Copyright (c) 2018-2019 The Bitcoin Unlimited developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "blockrelay/mempool_sync.h"
#include "serialize.h"
#include "streams.h"
#include "test/test_bitcoin.h"
#include <boost/test/unit_test.hpp>
#include <cassert>
#include <iostream>
BOOST_FIXTURE_TEST_SUITE(mempool_sync_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(mempool_sync_can_serde)
{
uint64_t sync_version = DEFAULT_MEMPOOL_SYNC_MAX_VERSION_SUPPORTED;
uint64_t nReceiverMemPoolTx = 0;
uint64_t nSenderMempoolPlusBlock = 1;
uint64_t shorttxidk0 = 7;
uint64_t shorttxidk1 = 11;
CBlock block;
CTransaction tx;
CDataStream stream(
ParseHex("01000000010b26e9b7735eb6aabdf358bab62f9816a21ba9ebdb719d5299e88607d722c190000000008b4830450220070aca4"
"4506c5cef3a16ed519d7c3c39f8aab192c4e1c90d065f37b8a4af6141022100a8e160b856c2d43d27d8fba71e5aef6405b864"
"3ac4cb7cb3c462aced7f14711a0141046d11fee51b0e60666d5049a9101a72741df480b96ee26488a4d3466b95c9a40ac5eee"
"f87e10a5cd336c19a84565f80fa6c547957b7700ff4dfbdefe76036c339ffffffff021bff3d11000000001976a91404943fdd"
"508053c75000106d3bc6e2754dbcff1988ac2f15de00000000001976a914a266436d2965547608b9e15d9032a7b9d64fa4318"
"8ac00000000"),
SER_DISK, CLIENT_VERSION);
stream >> tx;
std::vector<uint256> senderMempoolTxHashes;
std::vector<uint256> receiverMempoolTxHashes;
senderMempoolTxHashes.push_back(tx.GetHash());
CMempoolSync senderMempoolSync(
senderMempoolTxHashes, nReceiverMemPoolTx, nSenderMempoolPlusBlock, shorttxidk0, shorttxidk1, sync_version);
CMempoolSync receiverMempoolSync(sync_version);
CDataStream ss(SER_DISK, 0);
ss << senderMempoolSync;
ss >> receiverMempoolSync;
receiverMempoolSync.pGrapheneSet->Reconcile(receiverMempoolTxHashes);
}
BOOST_AUTO_TEST_SUITE_END()
| 41.244898 | 120 | 0.787234 |
4216b89205de378cc7124b41a1112dcc6c99396b | 1,804 | cpp | C++ | pyis/bindings/python/model_context_exports.cpp | microsoft/python-inference-script | cbbbe9d16be0839e4df357b1bd9e8274ca44f1f7 | [
"MIT"
] | 5 | 2021-11-29T01:49:22.000Z | 2022-02-23T10:26:46.000Z | pyis/bindings/python/model_context_exports.cpp | microsoft/python-inference-script | cbbbe9d16be0839e4df357b1bd9e8274ca44f1f7 | [
"MIT"
] | 1 | 2021-11-01T02:22:32.000Z | 2021-11-01T02:22:32.000Z | pyis/bindings/python/model_context_exports.cpp | microsoft/python-inference-script | cbbbe9d16be0839e4df357b1bd9e8274ca44f1f7 | [
"MIT"
] | null | null | null | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include "pyis/share/model_context.h"
namespace pyis {
namespace python {
namespace py = pybind11;
void init_model_context(py::module& m) {
py::class_<ModelContext, std::shared_ptr<ModelContext>>(m, "ModelContext")
.def(py::init<std::string, std::string>(), py::arg("model_path"), py::arg("data_archive") = "",
R"pbdoc(
Create a ModelContext for loading and saving external data files.
The data file should contains two columns, separated by WHITESPACE characters.
The first and second columns are source words and target words correspondingly. For example,
Args:
model_path (str): The model file path.
data_archive (str): If specified, the external data files will be archived into
a single archive file. By default, external files are not archived and live in the same
directory as model file.
)pbdoc")
.def("set_file_prefix", &ModelContext::SetFilePrefix, py::arg("prefix"),
R"pbdoc(
Add a common prefix to model file and all external data files. It is useful to avoid file path
conflicts.
If the model file name already starts with the prefix, the prefix will be ignored. But it still works
for external files.
Args:
prefix (str): Common prefix.
)pbdoc")
.def_static("activate", &ModelContext::Activate)
.def_static("deactivate", &ModelContext::Deactivate);
}
} // namespace python
} // namespace pyis
| 39.217391 | 118 | 0.618625 |
42190727be040632b2fb81d13aac31992fd155d3 | 1,333 | cpp | C++ | f9tws/ExgTradingLineFixFactory.cpp | fonwin/Plan | 3bfa9407ab04a26293ba8d23c2208bbececb430e | [
"Apache-2.0"
] | 21 | 2019-01-29T14:41:46.000Z | 2022-03-11T00:22:56.000Z | f9tws/ExgTradingLineFixFactory.cpp | fonwin/Plan | 3bfa9407ab04a26293ba8d23c2208bbececb430e | [
"Apache-2.0"
] | null | null | null | f9tws/ExgTradingLineFixFactory.cpp | fonwin/Plan | 3bfa9407ab04a26293ba8d23c2208bbececb430e | [
"Apache-2.0"
] | 9 | 2019-01-27T14:19:33.000Z | 2022-03-11T06:18:24.000Z | // \file f9tws/ExgTradingLineFixFactory.cpp
// \author fonwinz@gmail.com
#include "f9tws/ExgTradingLineFixFactory.hpp"
#include "fon9/fix/FixBusinessReject.hpp"
namespace f9tws {
ExgTradingLineFixFactory::ExgTradingLineFixFactory(std::string fixLogPathFmt, Named&& name)
: base(std::move(fixLogPathFmt), std::move(name)) {
ExgTradingLineFix::InitFixConfig(this->FixConfig_);
f9fix::InitRecvRejectMessage(this->FixConfig_);
}
fon9::io::SessionSP ExgTradingLineFixFactory::CreateTradingLine(ExgTradingLineMgr& lineMgr,
const fon9::IoConfigItem& cfg,
std::string& errReason) {
ExgTradingLineFixArgs args;
args.Market_ = lineMgr.Market_;
errReason = ExgTradingLineFixArgsParser(args, ToStrView(cfg.SessionArgs_));
if (!errReason.empty())
return fon9::io::SessionSP{};
std::string fixLogPath;
errReason = this->MakeLogPath(fixLogPath);
if (!errReason.empty())
return fon9::io::SessionSP{};
fon9::fix::IoFixSenderSP fixSender;
errReason = MakeExgTradingLineFixSender(args, &fixLogPath, fixSender);
if (!errReason.empty())
return fon9::io::SessionSP{};
return this->CreateTradingLineFix(lineMgr, args, std::move(fixSender));
}
} // namespaces
| 35.078947 | 94 | 0.672918 |
421973a95cbe356d815d7aec228dca6a50238f5f | 17,585 | cpp | C++ | aws-cpp-sdk-appflow/source/model/ConnectorConfiguration.cpp | truthiswill/aws-sdk-cpp | 6e854b6a8bc7945f150c3a11551196bda341962a | [
"Apache-2.0"
] | 1 | 2022-02-12T08:09:30.000Z | 2022-02-12T08:09:30.000Z | aws-cpp-sdk-appflow/source/model/ConnectorConfiguration.cpp | truthiswill/aws-sdk-cpp | 6e854b6a8bc7945f150c3a11551196bda341962a | [
"Apache-2.0"
] | 1 | 2021-10-14T16:57:00.000Z | 2021-10-18T10:47:24.000Z | aws-cpp-sdk-appflow/source/model/ConnectorConfiguration.cpp | truthiswill/aws-sdk-cpp | 6e854b6a8bc7945f150c3a11551196bda341962a | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/appflow/model/ConnectorConfiguration.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace Appflow
{
namespace Model
{
ConnectorConfiguration::ConnectorConfiguration() :
m_canUseAsSource(false),
m_canUseAsSourceHasBeenSet(false),
m_canUseAsDestination(false),
m_canUseAsDestinationHasBeenSet(false),
m_supportedDestinationConnectorsHasBeenSet(false),
m_supportedSchedulingFrequenciesHasBeenSet(false),
m_isPrivateLinkEnabled(false),
m_isPrivateLinkEnabledHasBeenSet(false),
m_isPrivateLinkEndpointUrlRequired(false),
m_isPrivateLinkEndpointUrlRequiredHasBeenSet(false),
m_supportedTriggerTypesHasBeenSet(false),
m_connectorMetadataHasBeenSet(false),
m_connectorType(ConnectorType::NOT_SET),
m_connectorTypeHasBeenSet(false),
m_connectorLabelHasBeenSet(false),
m_connectorDescriptionHasBeenSet(false),
m_connectorOwnerHasBeenSet(false),
m_connectorNameHasBeenSet(false),
m_connectorVersionHasBeenSet(false),
m_connectorArnHasBeenSet(false),
m_connectorModesHasBeenSet(false),
m_authenticationConfigHasBeenSet(false),
m_connectorRuntimeSettingsHasBeenSet(false),
m_supportedApiVersionsHasBeenSet(false),
m_supportedOperatorsHasBeenSet(false),
m_supportedWriteOperationsHasBeenSet(false),
m_connectorProvisioningType(ConnectorProvisioningType::NOT_SET),
m_connectorProvisioningTypeHasBeenSet(false),
m_connectorProvisioningConfigHasBeenSet(false),
m_logoURLHasBeenSet(false),
m_registeredAtHasBeenSet(false),
m_registeredByHasBeenSet(false)
{
}
ConnectorConfiguration::ConnectorConfiguration(JsonView jsonValue) :
m_canUseAsSource(false),
m_canUseAsSourceHasBeenSet(false),
m_canUseAsDestination(false),
m_canUseAsDestinationHasBeenSet(false),
m_supportedDestinationConnectorsHasBeenSet(false),
m_supportedSchedulingFrequenciesHasBeenSet(false),
m_isPrivateLinkEnabled(false),
m_isPrivateLinkEnabledHasBeenSet(false),
m_isPrivateLinkEndpointUrlRequired(false),
m_isPrivateLinkEndpointUrlRequiredHasBeenSet(false),
m_supportedTriggerTypesHasBeenSet(false),
m_connectorMetadataHasBeenSet(false),
m_connectorType(ConnectorType::NOT_SET),
m_connectorTypeHasBeenSet(false),
m_connectorLabelHasBeenSet(false),
m_connectorDescriptionHasBeenSet(false),
m_connectorOwnerHasBeenSet(false),
m_connectorNameHasBeenSet(false),
m_connectorVersionHasBeenSet(false),
m_connectorArnHasBeenSet(false),
m_connectorModesHasBeenSet(false),
m_authenticationConfigHasBeenSet(false),
m_connectorRuntimeSettingsHasBeenSet(false),
m_supportedApiVersionsHasBeenSet(false),
m_supportedOperatorsHasBeenSet(false),
m_supportedWriteOperationsHasBeenSet(false),
m_connectorProvisioningType(ConnectorProvisioningType::NOT_SET),
m_connectorProvisioningTypeHasBeenSet(false),
m_connectorProvisioningConfigHasBeenSet(false),
m_logoURLHasBeenSet(false),
m_registeredAtHasBeenSet(false),
m_registeredByHasBeenSet(false)
{
*this = jsonValue;
}
ConnectorConfiguration& ConnectorConfiguration::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("canUseAsSource"))
{
m_canUseAsSource = jsonValue.GetBool("canUseAsSource");
m_canUseAsSourceHasBeenSet = true;
}
if(jsonValue.ValueExists("canUseAsDestination"))
{
m_canUseAsDestination = jsonValue.GetBool("canUseAsDestination");
m_canUseAsDestinationHasBeenSet = true;
}
if(jsonValue.ValueExists("supportedDestinationConnectors"))
{
Array<JsonView> supportedDestinationConnectorsJsonList = jsonValue.GetArray("supportedDestinationConnectors");
for(unsigned supportedDestinationConnectorsIndex = 0; supportedDestinationConnectorsIndex < supportedDestinationConnectorsJsonList.GetLength(); ++supportedDestinationConnectorsIndex)
{
m_supportedDestinationConnectors.push_back(ConnectorTypeMapper::GetConnectorTypeForName(supportedDestinationConnectorsJsonList[supportedDestinationConnectorsIndex].AsString()));
}
m_supportedDestinationConnectorsHasBeenSet = true;
}
if(jsonValue.ValueExists("supportedSchedulingFrequencies"))
{
Array<JsonView> supportedSchedulingFrequenciesJsonList = jsonValue.GetArray("supportedSchedulingFrequencies");
for(unsigned supportedSchedulingFrequenciesIndex = 0; supportedSchedulingFrequenciesIndex < supportedSchedulingFrequenciesJsonList.GetLength(); ++supportedSchedulingFrequenciesIndex)
{
m_supportedSchedulingFrequencies.push_back(ScheduleFrequencyTypeMapper::GetScheduleFrequencyTypeForName(supportedSchedulingFrequenciesJsonList[supportedSchedulingFrequenciesIndex].AsString()));
}
m_supportedSchedulingFrequenciesHasBeenSet = true;
}
if(jsonValue.ValueExists("isPrivateLinkEnabled"))
{
m_isPrivateLinkEnabled = jsonValue.GetBool("isPrivateLinkEnabled");
m_isPrivateLinkEnabledHasBeenSet = true;
}
if(jsonValue.ValueExists("isPrivateLinkEndpointUrlRequired"))
{
m_isPrivateLinkEndpointUrlRequired = jsonValue.GetBool("isPrivateLinkEndpointUrlRequired");
m_isPrivateLinkEndpointUrlRequiredHasBeenSet = true;
}
if(jsonValue.ValueExists("supportedTriggerTypes"))
{
Array<JsonView> supportedTriggerTypesJsonList = jsonValue.GetArray("supportedTriggerTypes");
for(unsigned supportedTriggerTypesIndex = 0; supportedTriggerTypesIndex < supportedTriggerTypesJsonList.GetLength(); ++supportedTriggerTypesIndex)
{
m_supportedTriggerTypes.push_back(TriggerTypeMapper::GetTriggerTypeForName(supportedTriggerTypesJsonList[supportedTriggerTypesIndex].AsString()));
}
m_supportedTriggerTypesHasBeenSet = true;
}
if(jsonValue.ValueExists("connectorMetadata"))
{
m_connectorMetadata = jsonValue.GetObject("connectorMetadata");
m_connectorMetadataHasBeenSet = true;
}
if(jsonValue.ValueExists("connectorType"))
{
m_connectorType = ConnectorTypeMapper::GetConnectorTypeForName(jsonValue.GetString("connectorType"));
m_connectorTypeHasBeenSet = true;
}
if(jsonValue.ValueExists("connectorLabel"))
{
m_connectorLabel = jsonValue.GetString("connectorLabel");
m_connectorLabelHasBeenSet = true;
}
if(jsonValue.ValueExists("connectorDescription"))
{
m_connectorDescription = jsonValue.GetString("connectorDescription");
m_connectorDescriptionHasBeenSet = true;
}
if(jsonValue.ValueExists("connectorOwner"))
{
m_connectorOwner = jsonValue.GetString("connectorOwner");
m_connectorOwnerHasBeenSet = true;
}
if(jsonValue.ValueExists("connectorName"))
{
m_connectorName = jsonValue.GetString("connectorName");
m_connectorNameHasBeenSet = true;
}
if(jsonValue.ValueExists("connectorVersion"))
{
m_connectorVersion = jsonValue.GetString("connectorVersion");
m_connectorVersionHasBeenSet = true;
}
if(jsonValue.ValueExists("connectorArn"))
{
m_connectorArn = jsonValue.GetString("connectorArn");
m_connectorArnHasBeenSet = true;
}
if(jsonValue.ValueExists("connectorModes"))
{
Array<JsonView> connectorModesJsonList = jsonValue.GetArray("connectorModes");
for(unsigned connectorModesIndex = 0; connectorModesIndex < connectorModesJsonList.GetLength(); ++connectorModesIndex)
{
m_connectorModes.push_back(connectorModesJsonList[connectorModesIndex].AsString());
}
m_connectorModesHasBeenSet = true;
}
if(jsonValue.ValueExists("authenticationConfig"))
{
m_authenticationConfig = jsonValue.GetObject("authenticationConfig");
m_authenticationConfigHasBeenSet = true;
}
if(jsonValue.ValueExists("connectorRuntimeSettings"))
{
Array<JsonView> connectorRuntimeSettingsJsonList = jsonValue.GetArray("connectorRuntimeSettings");
for(unsigned connectorRuntimeSettingsIndex = 0; connectorRuntimeSettingsIndex < connectorRuntimeSettingsJsonList.GetLength(); ++connectorRuntimeSettingsIndex)
{
m_connectorRuntimeSettings.push_back(connectorRuntimeSettingsJsonList[connectorRuntimeSettingsIndex].AsObject());
}
m_connectorRuntimeSettingsHasBeenSet = true;
}
if(jsonValue.ValueExists("supportedApiVersions"))
{
Array<JsonView> supportedApiVersionsJsonList = jsonValue.GetArray("supportedApiVersions");
for(unsigned supportedApiVersionsIndex = 0; supportedApiVersionsIndex < supportedApiVersionsJsonList.GetLength(); ++supportedApiVersionsIndex)
{
m_supportedApiVersions.push_back(supportedApiVersionsJsonList[supportedApiVersionsIndex].AsString());
}
m_supportedApiVersionsHasBeenSet = true;
}
if(jsonValue.ValueExists("supportedOperators"))
{
Array<JsonView> supportedOperatorsJsonList = jsonValue.GetArray("supportedOperators");
for(unsigned supportedOperatorsIndex = 0; supportedOperatorsIndex < supportedOperatorsJsonList.GetLength(); ++supportedOperatorsIndex)
{
m_supportedOperators.push_back(OperatorsMapper::GetOperatorsForName(supportedOperatorsJsonList[supportedOperatorsIndex].AsString()));
}
m_supportedOperatorsHasBeenSet = true;
}
if(jsonValue.ValueExists("supportedWriteOperations"))
{
Array<JsonView> supportedWriteOperationsJsonList = jsonValue.GetArray("supportedWriteOperations");
for(unsigned supportedWriteOperationsIndex = 0; supportedWriteOperationsIndex < supportedWriteOperationsJsonList.GetLength(); ++supportedWriteOperationsIndex)
{
m_supportedWriteOperations.push_back(WriteOperationTypeMapper::GetWriteOperationTypeForName(supportedWriteOperationsJsonList[supportedWriteOperationsIndex].AsString()));
}
m_supportedWriteOperationsHasBeenSet = true;
}
if(jsonValue.ValueExists("connectorProvisioningType"))
{
m_connectorProvisioningType = ConnectorProvisioningTypeMapper::GetConnectorProvisioningTypeForName(jsonValue.GetString("connectorProvisioningType"));
m_connectorProvisioningTypeHasBeenSet = true;
}
if(jsonValue.ValueExists("connectorProvisioningConfig"))
{
m_connectorProvisioningConfig = jsonValue.GetObject("connectorProvisioningConfig");
m_connectorProvisioningConfigHasBeenSet = true;
}
if(jsonValue.ValueExists("logoURL"))
{
m_logoURL = jsonValue.GetString("logoURL");
m_logoURLHasBeenSet = true;
}
if(jsonValue.ValueExists("registeredAt"))
{
m_registeredAt = jsonValue.GetDouble("registeredAt");
m_registeredAtHasBeenSet = true;
}
if(jsonValue.ValueExists("registeredBy"))
{
m_registeredBy = jsonValue.GetString("registeredBy");
m_registeredByHasBeenSet = true;
}
return *this;
}
JsonValue ConnectorConfiguration::Jsonize() const
{
JsonValue payload;
if(m_canUseAsSourceHasBeenSet)
{
payload.WithBool("canUseAsSource", m_canUseAsSource);
}
if(m_canUseAsDestinationHasBeenSet)
{
payload.WithBool("canUseAsDestination", m_canUseAsDestination);
}
if(m_supportedDestinationConnectorsHasBeenSet)
{
Array<JsonValue> supportedDestinationConnectorsJsonList(m_supportedDestinationConnectors.size());
for(unsigned supportedDestinationConnectorsIndex = 0; supportedDestinationConnectorsIndex < supportedDestinationConnectorsJsonList.GetLength(); ++supportedDestinationConnectorsIndex)
{
supportedDestinationConnectorsJsonList[supportedDestinationConnectorsIndex].AsString(ConnectorTypeMapper::GetNameForConnectorType(m_supportedDestinationConnectors[supportedDestinationConnectorsIndex]));
}
payload.WithArray("supportedDestinationConnectors", std::move(supportedDestinationConnectorsJsonList));
}
if(m_supportedSchedulingFrequenciesHasBeenSet)
{
Array<JsonValue> supportedSchedulingFrequenciesJsonList(m_supportedSchedulingFrequencies.size());
for(unsigned supportedSchedulingFrequenciesIndex = 0; supportedSchedulingFrequenciesIndex < supportedSchedulingFrequenciesJsonList.GetLength(); ++supportedSchedulingFrequenciesIndex)
{
supportedSchedulingFrequenciesJsonList[supportedSchedulingFrequenciesIndex].AsString(ScheduleFrequencyTypeMapper::GetNameForScheduleFrequencyType(m_supportedSchedulingFrequencies[supportedSchedulingFrequenciesIndex]));
}
payload.WithArray("supportedSchedulingFrequencies", std::move(supportedSchedulingFrequenciesJsonList));
}
if(m_isPrivateLinkEnabledHasBeenSet)
{
payload.WithBool("isPrivateLinkEnabled", m_isPrivateLinkEnabled);
}
if(m_isPrivateLinkEndpointUrlRequiredHasBeenSet)
{
payload.WithBool("isPrivateLinkEndpointUrlRequired", m_isPrivateLinkEndpointUrlRequired);
}
if(m_supportedTriggerTypesHasBeenSet)
{
Array<JsonValue> supportedTriggerTypesJsonList(m_supportedTriggerTypes.size());
for(unsigned supportedTriggerTypesIndex = 0; supportedTriggerTypesIndex < supportedTriggerTypesJsonList.GetLength(); ++supportedTriggerTypesIndex)
{
supportedTriggerTypesJsonList[supportedTriggerTypesIndex].AsString(TriggerTypeMapper::GetNameForTriggerType(m_supportedTriggerTypes[supportedTriggerTypesIndex]));
}
payload.WithArray("supportedTriggerTypes", std::move(supportedTriggerTypesJsonList));
}
if(m_connectorMetadataHasBeenSet)
{
payload.WithObject("connectorMetadata", m_connectorMetadata.Jsonize());
}
if(m_connectorTypeHasBeenSet)
{
payload.WithString("connectorType", ConnectorTypeMapper::GetNameForConnectorType(m_connectorType));
}
if(m_connectorLabelHasBeenSet)
{
payload.WithString("connectorLabel", m_connectorLabel);
}
if(m_connectorDescriptionHasBeenSet)
{
payload.WithString("connectorDescription", m_connectorDescription);
}
if(m_connectorOwnerHasBeenSet)
{
payload.WithString("connectorOwner", m_connectorOwner);
}
if(m_connectorNameHasBeenSet)
{
payload.WithString("connectorName", m_connectorName);
}
if(m_connectorVersionHasBeenSet)
{
payload.WithString("connectorVersion", m_connectorVersion);
}
if(m_connectorArnHasBeenSet)
{
payload.WithString("connectorArn", m_connectorArn);
}
if(m_connectorModesHasBeenSet)
{
Array<JsonValue> connectorModesJsonList(m_connectorModes.size());
for(unsigned connectorModesIndex = 0; connectorModesIndex < connectorModesJsonList.GetLength(); ++connectorModesIndex)
{
connectorModesJsonList[connectorModesIndex].AsString(m_connectorModes[connectorModesIndex]);
}
payload.WithArray("connectorModes", std::move(connectorModesJsonList));
}
if(m_authenticationConfigHasBeenSet)
{
payload.WithObject("authenticationConfig", m_authenticationConfig.Jsonize());
}
if(m_connectorRuntimeSettingsHasBeenSet)
{
Array<JsonValue> connectorRuntimeSettingsJsonList(m_connectorRuntimeSettings.size());
for(unsigned connectorRuntimeSettingsIndex = 0; connectorRuntimeSettingsIndex < connectorRuntimeSettingsJsonList.GetLength(); ++connectorRuntimeSettingsIndex)
{
connectorRuntimeSettingsJsonList[connectorRuntimeSettingsIndex].AsObject(m_connectorRuntimeSettings[connectorRuntimeSettingsIndex].Jsonize());
}
payload.WithArray("connectorRuntimeSettings", std::move(connectorRuntimeSettingsJsonList));
}
if(m_supportedApiVersionsHasBeenSet)
{
Array<JsonValue> supportedApiVersionsJsonList(m_supportedApiVersions.size());
for(unsigned supportedApiVersionsIndex = 0; supportedApiVersionsIndex < supportedApiVersionsJsonList.GetLength(); ++supportedApiVersionsIndex)
{
supportedApiVersionsJsonList[supportedApiVersionsIndex].AsString(m_supportedApiVersions[supportedApiVersionsIndex]);
}
payload.WithArray("supportedApiVersions", std::move(supportedApiVersionsJsonList));
}
if(m_supportedOperatorsHasBeenSet)
{
Array<JsonValue> supportedOperatorsJsonList(m_supportedOperators.size());
for(unsigned supportedOperatorsIndex = 0; supportedOperatorsIndex < supportedOperatorsJsonList.GetLength(); ++supportedOperatorsIndex)
{
supportedOperatorsJsonList[supportedOperatorsIndex].AsString(OperatorsMapper::GetNameForOperators(m_supportedOperators[supportedOperatorsIndex]));
}
payload.WithArray("supportedOperators", std::move(supportedOperatorsJsonList));
}
if(m_supportedWriteOperationsHasBeenSet)
{
Array<JsonValue> supportedWriteOperationsJsonList(m_supportedWriteOperations.size());
for(unsigned supportedWriteOperationsIndex = 0; supportedWriteOperationsIndex < supportedWriteOperationsJsonList.GetLength(); ++supportedWriteOperationsIndex)
{
supportedWriteOperationsJsonList[supportedWriteOperationsIndex].AsString(WriteOperationTypeMapper::GetNameForWriteOperationType(m_supportedWriteOperations[supportedWriteOperationsIndex]));
}
payload.WithArray("supportedWriteOperations", std::move(supportedWriteOperationsJsonList));
}
if(m_connectorProvisioningTypeHasBeenSet)
{
payload.WithString("connectorProvisioningType", ConnectorProvisioningTypeMapper::GetNameForConnectorProvisioningType(m_connectorProvisioningType));
}
if(m_connectorProvisioningConfigHasBeenSet)
{
payload.WithObject("connectorProvisioningConfig", m_connectorProvisioningConfig.Jsonize());
}
if(m_logoURLHasBeenSet)
{
payload.WithString("logoURL", m_logoURL);
}
if(m_registeredAtHasBeenSet)
{
payload.WithDouble("registeredAt", m_registeredAt.SecondsWithMSPrecision());
}
if(m_registeredByHasBeenSet)
{
payload.WithString("registeredBy", m_registeredBy);
}
return payload;
}
} // namespace Model
} // namespace Appflow
} // namespace Aws
| 34.616142 | 223 | 0.799488 |
4221d95f7fba35dfefa01fc155e4456ebdb81482 | 1,188 | cpp | C++ | lang/C++/zeckendorf-number-representation-1.cpp | ethansaxenian/RosettaDecode | 8ea1a42a5f792280b50193ad47545d14ee371fb7 | [
"MIT"
] | 5 | 2021-01-29T20:08:05.000Z | 2022-03-22T06:16:05.000Z | lang/C++/zeckendorf-number-representation-1.cpp | ethansaxenian/RosettaDecode | 8ea1a42a5f792280b50193ad47545d14ee371fb7 | [
"MIT"
] | null | null | null | lang/C++/zeckendorf-number-representation-1.cpp | ethansaxenian/RosettaDecode | 8ea1a42a5f792280b50193ad47545d14ee371fb7 | [
"MIT"
] | 1 | 2021-04-13T04:19:31.000Z | 2021-04-13T04:19:31.000Z | // For a class N which implements Zeckendorf numbers:
// I define an increment operation ++()
// I define a comparison operation <=(other N)
// Nigel Galloway October 22nd., 2012
#include <iostream>
class N {
private:
int dVal = 0, dLen;
public:
N(char const* x = "0"){
int i = 0, q = 1;
for (; x[i] > 0; i++);
for (dLen = --i/2; i >= 0; i--) {
dVal+=(x[i]-48)*q;
q*=2;
}}
const N& operator++() {
for (int i = 0;;i++) {
if (dLen < i) dLen = i;
switch ((dVal >> (i*2)) & 3) {
case 0: dVal += (1 << (i*2)); return *this;
case 1: dVal += (1 << (i*2)); if (((dVal >> ((i+1)*2)) & 1) != 1) return *this;
case 2: dVal &= ~(3 << (i*2));
}}}
const bool operator<=(const N& other) const {return dVal <= other.dVal;}
friend std::ostream& operator<<(std::ostream&, const N&);
};
N operator "" N(char const* x) {return N(x);}
std::ostream &operator<<(std::ostream &os, const N &G) {
const static std::string dig[] {"00","01","10"}, dig1[] {"","1","10"};
if (G.dVal == 0) return os << "0";
os << dig1[(G.dVal >> (G.dLen*2)) & 3];
for (int i = G.dLen-1; i >= 0; i--) os << dig[(G.dVal >> (i*2)) & 3];
return os;
}
| 33 | 87 | 0.509259 |
4224193f63fde7260b305d76f39e2554c9c08301 | 1,050 | hpp | C++ | TypeTraits/IsClassType.hpp | jlandess/LandessDevCore | 3319c36c3232415d6bdba7da8b4896c0638badf2 | [
"BSD-3-Clause"
] | 2 | 2021-06-09T00:38:46.000Z | 2021-09-04T21:55:33.000Z | TypeTraits/IsClassType.hpp | jlandess/LandessDevCore | 3319c36c3232415d6bdba7da8b4896c0638badf2 | [
"BSD-3-Clause"
] | null | null | null | TypeTraits/IsClassType.hpp | jlandess/LandessDevCore | 3319c36c3232415d6bdba7da8b4896c0638badf2 | [
"BSD-3-Clause"
] | 1 | 2021-08-30T00:46:12.000Z | 2021-08-30T00:46:12.000Z | //
// Created by James Landess on 2/4/20.
//
#ifndef LANDESSDEVCORE_ISCLASSTYPE_HPP
#define LANDESSDEVCORE_ISCLASSTYPE_HPP
#include "TypeTraits/IsIntegralType.hpp"
#include "TypeTraits/IsUnion.hpp"
namespace LD
{
namespace Detail
{
template<typename T>
struct IsClassType
{
static const bool value = !IsIntegrelType<T>::value;
};
//template <bool _Bp, class _Tp = void> using Enable_If_T = typename EnableIf<_Bp, _Tp>::type;
template<typename T> using IsClassType_V = typename IsClassType<T>::value;
}
}
namespace LD
{
namespace Detail
{
template <class T>
LD::Detail::IntegralConstant<bool, !LD::Detail::IsUnion<T>::value> test(int T::*);
template <class>
LD::FalseType test(...);
template <class T>
struct IsClass : decltype(LD::Detail::test<T>(nullptr))
{};
}
template<typename T>
constexpr bool IsClass = LD::Detail::IsClass<T>::value;
}
#endif //LANDESSDEVCORE_ISCLASSTYPE_HPP
| 18.421053 | 102 | 0.630476 |
4224b28d0f04b68fc399e1a3533d685b15c63cfe | 6,066 | cpp | C++ | Source/WebCore/loader/ResourceCryptographicDigest.cpp | jacadcaps/webkitty | 9aebd2081349f9a7b5d168673c6f676a1450a66d | [
"BSD-2-Clause"
] | 6 | 2021-07-05T16:09:39.000Z | 2022-03-06T22:44:42.000Z | Source/WebCore/loader/ResourceCryptographicDigest.cpp | jacadcaps/webkitty | 9aebd2081349f9a7b5d168673c6f676a1450a66d | [
"BSD-2-Clause"
] | 7 | 2022-03-15T13:25:39.000Z | 2022-03-15T13:25:44.000Z | Source/WebCore/loader/ResourceCryptographicDigest.cpp | jacadcaps/webkitty | 9aebd2081349f9a7b5d168673c6f676a1450a66d | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright (C) 2017 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 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 APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "ResourceCryptographicDigest.h"
#include "ParsingUtilities.h"
#include <pal/crypto/CryptoDigest.h>
#include <wtf/Optional.h>
#include <wtf/text/Base64.h>
#include <wtf/text/StringParsingBuffer.h>
namespace WebCore {
template<typename CharacterType> static Optional<ResourceCryptographicDigest::Algorithm> parseHashAlgorithmAdvancingPosition(StringParsingBuffer<CharacterType>& buffer)
{
// FIXME: This would be much cleaner with a lookup table of pairs of label / algorithm enum values, but I can't
// figure out how to keep the labels compiletime strings for skipExactlyIgnoringASCIICase.
if (skipExactlyIgnoringASCIICase(buffer, "sha256"))
return ResourceCryptographicDigest::Algorithm::SHA256;
if (skipExactlyIgnoringASCIICase(buffer, "sha384"))
return ResourceCryptographicDigest::Algorithm::SHA384;
if (skipExactlyIgnoringASCIICase(buffer, "sha512"))
return ResourceCryptographicDigest::Algorithm::SHA512;
return WTF::nullopt;
}
template<typename CharacterType> static Optional<ResourceCryptographicDigest> parseCryptographicDigestImpl(StringParsingBuffer<CharacterType>& buffer)
{
if (buffer.atEnd())
return WTF::nullopt;
auto algorithm = parseHashAlgorithmAdvancingPosition(buffer);
if (!algorithm)
return WTF::nullopt;
if (!skipExactly(buffer, '-'))
return WTF::nullopt;
auto beginHashValue = buffer.position();
skipWhile<isBase64OrBase64URLCharacter>(buffer);
skipExactly(buffer, '=');
skipExactly(buffer, '=');
if (buffer.position() == beginHashValue)
return WTF::nullopt;
Vector<uint8_t> digest;
StringView hashValue(beginHashValue, buffer.position() - beginHashValue);
if (!base64Decode(hashValue, digest, Base64ValidatePadding)) {
if (!base64URLDecode(hashValue, digest))
return WTF::nullopt;
}
return ResourceCryptographicDigest { *algorithm, WTFMove(digest) };
}
Optional<ResourceCryptographicDigest> parseCryptographicDigest(StringParsingBuffer<UChar>& buffer)
{
return parseCryptographicDigestImpl(buffer);
}
Optional<ResourceCryptographicDigest> parseCryptographicDigest(StringParsingBuffer<LChar>& buffer)
{
return parseCryptographicDigestImpl(buffer);
}
template<typename CharacterType> static Optional<EncodedResourceCryptographicDigest> parseEncodedCryptographicDigestImpl(StringParsingBuffer<CharacterType>& buffer)
{
if (buffer.atEnd())
return WTF::nullopt;
auto algorithm = parseHashAlgorithmAdvancingPosition(buffer);
if (!algorithm)
return WTF::nullopt;
if (!skipExactly(buffer, '-'))
return WTF::nullopt;
auto beginHashValue = buffer.position();
skipWhile<isBase64OrBase64URLCharacter>(buffer);
skipExactly(buffer, '=');
skipExactly(buffer, '=');
if (buffer.position() == beginHashValue)
return WTF::nullopt;
return EncodedResourceCryptographicDigest { *algorithm, String(beginHashValue, buffer.position() - beginHashValue) };
}
Optional<EncodedResourceCryptographicDigest> parseEncodedCryptographicDigest(StringParsingBuffer<UChar>& buffer)
{
return parseEncodedCryptographicDigestImpl(buffer);
}
Optional<EncodedResourceCryptographicDigest> parseEncodedCryptographicDigest(StringParsingBuffer<LChar>& buffer)
{
return parseEncodedCryptographicDigestImpl(buffer);
}
Optional<ResourceCryptographicDigest> decodeEncodedResourceCryptographicDigest(const EncodedResourceCryptographicDigest& encodedDigest)
{
Vector<uint8_t> digest;
if (!base64Decode(encodedDigest.digest, digest, Base64ValidatePadding)) {
if (!base64URLDecode(encodedDigest.digest, digest))
return WTF::nullopt;
}
return ResourceCryptographicDigest { encodedDigest.algorithm, WTFMove(digest) };
}
static PAL::CryptoDigest::Algorithm toCryptoDigestAlgorithm(ResourceCryptographicDigest::Algorithm algorithm)
{
switch (algorithm) {
case ResourceCryptographicDigest::Algorithm::SHA256:
return PAL::CryptoDigest::Algorithm::SHA_256;
case ResourceCryptographicDigest::Algorithm::SHA384:
return PAL::CryptoDigest::Algorithm::SHA_384;
case ResourceCryptographicDigest::Algorithm::SHA512:
return PAL::CryptoDigest::Algorithm::SHA_512;
}
ASSERT_NOT_REACHED();
return PAL::CryptoDigest::Algorithm::SHA_512;
}
ResourceCryptographicDigest cryptographicDigestForBytes(ResourceCryptographicDigest::Algorithm algorithm, const void* bytes, size_t length)
{
auto cryptoDigest = PAL::CryptoDigest::create(toCryptoDigestAlgorithm(algorithm));
cryptoDigest->addBytes(bytes, length);
return { algorithm, cryptoDigest->computeHash() };
}
}
| 38.392405 | 168 | 0.760303 |
4225050630bbee8dac61f9eab48420340b96eec3 | 624 | cpp | C++ | thirdparty/ULib/tests/ulib/test_twilio.cpp | liftchampion/nativejson-benchmark | 6d575ffa4359a5c4230f74b07d994602a8016fb5 | [
"MIT"
] | null | null | null | thirdparty/ULib/tests/ulib/test_twilio.cpp | liftchampion/nativejson-benchmark | 6d575ffa4359a5c4230f74b07d994602a8016fb5 | [
"MIT"
] | null | null | null | thirdparty/ULib/tests/ulib/test_twilio.cpp | liftchampion/nativejson-benchmark | 6d575ffa4359a5c4230f74b07d994602a8016fb5 | [
"MIT"
] | null | null | null | // test_twilio.cpp
#include <ulib/net/client/twilio.h>
int main(int argc, char *argv[])
{
U_ULIB_INIT(argv);
U_TRACE(5,"main(%d)",argc)
UTwilioClient tc(U_STRING_FROM_CONSTANT("SID"), U_STRING_FROM_CONSTANT("TOKEN"));
bool ok = tc.getCompletedCalls();
U_INTERNAL_ASSERT(ok)
ok = tc.makeCall(U_CONSTANT_TO_PARAM("xxx-xxx-xxxx"), U_CONSTANT_TO_PARAM("xxx-xxx-xxxx"), U_CONSTANT_TO_PARAM("http://xxxx"));
U_INTERNAL_ASSERT(ok)
ok = tc.sendSMS(U_CONSTANT_TO_PARAM("xxx-xxx-xxxx"), U_CONSTANT_TO_PARAM("xxx-xxx-xxxx"), U_CONSTANT_TO_PARAM("\"Hello, how are you?\""));
U_INTERNAL_ASSERT(ok)
}
| 24.96 | 141 | 0.709936 |
422833be4725423ad37c6953658757a96f12a245 | 21,894 | cpp | C++ | src/lib.cpp | anticrisis/act-http | 18a48a35efc76c54e38a1eac762828bd7addf8c0 | [
"BSD-3-Clause"
] | 2 | 2021-02-05T21:20:09.000Z | 2022-01-19T13:43:39.000Z | src/lib.cpp | anticrisis/tcl-http | 18a48a35efc76c54e38a1eac762828bd7addf8c0 | [
"BSD-3-Clause"
] | null | null | null | src/lib.cpp | anticrisis/tcl-http | 18a48a35efc76c54e38a1eac762828bd7addf8c0 | [
"BSD-3-Clause"
] | null | null | null | #include "dllexport.h"
#include "http_tcl/http_tcl.h"
#include "util.h"
#include "version.h"
#include <algorithm>
#include <iostream>
#include <memory>
#include <optional>
#include <tcl.h>
#include <thread>
#include <vector>
// need a macro for compile-time string concatenation
#define theNamespaceName "::act::http"
#define theUrlNamespaceName "::act::url"
static constexpr auto theParentNamespace = "::act";
static constexpr auto thePackageName = "act::http";
static constexpr auto thePackageVersion = PROJECT_VERSION;
// Configuration structure with refcounted Tcl objects. Managed using
// the 'http::configure' command.
//
// TCL callbacks have the following specifications:
//
// OPTIONS: -> {status content content_type} or see below
// HEAD: -> {status content_length content_type}
// GET: -> {status content content_type}
// POST: -> {status content content_type}
// PUT: -> {status}
// DELETE: -> {status content content_type}
//
// where
//
// target = string request path, e.g. "/foo"
// body = string request body
// status = integer HTTP status code
// content_length = integer to place in 'Content-Length' header
// content_type = string to place in 'Content-Type' header
//
// and
//
// Each callback, not just OPTIONS, may optionally return an additional value
// as the last element of the list. That value is a dictionary of key/value
// pairs to add to the response headers. For example:
//
// proc post {target body} {
// list 200 "hello" "text/plain" {Set-Cookie foo X-Other-Header bar}
// }
//
struct config_t
{
bool valid{ false };
TclObj options{};
TclObj head{};
TclObj get{};
TclObj post{};
TclObj put{};
TclObj delete_{};
TclObj req_target{};
TclObj req_body{};
TclObj req_headers{};
TclObj host{};
TclObj port{};
TclObj exit_target{};
TclObj max_connections{};
void
init();
};
void
config_t::init()
{
// call after Tcl_InitStubs
auto empty_string = [] {
return Tcl_NewStringObj("", 0);
};
options = empty_string();
head = empty_string();
get = empty_string();
post = empty_string();
put = empty_string();
delete_ = empty_string();
req_target = empty_string();
req_body = empty_string();
req_headers = empty_string();
host = empty_string();
port = empty_string();
exit_target = empty_string();
max_connections = empty_string();
valid = true;
}
struct tcl_handler final : public http_tcl::thread_safe_handler<tcl_handler>
{
Tcl_Interp* interp_;
config_t config_;
void
set_target(std::string_view target)
{
maybe_set_var(interp_, config_.req_target.value(), target);
}
void
set_body(std::string_view body)
{
maybe_set_var(interp_, config_.req_body.value(), body);
}
void
set_headers(headers_access&& get_headers)
{
// only ask server to copy headers out of its internal
// structure if we're actually going to use them.
auto var_name_sv = get_string(config_.req_headers.value());
if (! var_name_sv.empty())
{
auto dict = to_dict(interp_, get_headers());
Tcl_ObjSetVar2(interp_,
config_.req_headers.value(),
nullptr,
dict,
TCL_GLOBAL_ONLY | TCL_LEAVE_ERR_MSG);
}
}
std::optional<int>
get_int(Tcl_Obj* obj)
{
int val{ 0 };
if (Tcl_GetIntFromObj(interp_, obj, &val) == TCL_OK)
return val;
return std::nullopt;
}
std::optional<std::tuple<int, Tcl_Obj**>>
get_list(Tcl_Obj* list)
{
int length{ 0 };
Tcl_Obj** objv;
if (Tcl_ListObjGetElements(interp_, list, &length, &objv) != TCL_OK)
return std::nullopt;
return std::make_tuple(length, objv);
}
std::optional<http_tcl::headers>
get_dict(Tcl_Obj* dict)
{
return ::get_dict(interp_, dict);
}
std::optional<std::tuple<int, Tcl_Obj**>>
eval_to_list(Tcl_Obj* obj)
{
if (Tcl_EvalObjEx(interp_, obj, TCL_EVAL_GLOBAL) != TCL_OK)
return std::nullopt;
return get_list(Tcl_GetObjResult(interp_));
}
std::string
error_info()
{
if (auto cs = Tcl_GetVar(interp_, "errorInfo", TCL_GLOBAL_ONLY); cs)
return cs;
return "";
}
public:
void
init(Tcl_Interp* i)
{
interp_ = i;
config_.init();
}
auto&
config()
{
return config_;
}
options_r
do_options(std::string_view target,
std::string_view body,
headers_access&& get_headers)
{
constexpr auto req_args = 3;
const auto make_error = [&](char const* msg = nullptr) -> options_r {
return { 500, std::nullopt, msg ? msg : error_info(), "text/plain" };
};
// Not-so-secret back door to force exit, only if -exittarget is set. This
// is used for test suites.
if (auto exit = get_string(config_.exit_target.value()); ! exit.empty())
{
if (target == exit)
{
// exit after 50ms, hopefully enough time to cleanly complete the
// response
std::thread{
[] {
using namespace std::chrono_literals;
std::this_thread::sleep_for(100ms);
Tcl_Exit(0);
}
}.detach();
return { 204, std::nullopt, "", "" };
}
}
set_target(target);
set_body(body);
set_headers(std::move(get_headers));
auto list = eval_to_list(config_.options.value());
if (! list)
return make_error();
auto [objc, objv] = *list;
if (objc < req_args)
return make_error("wrong number of items returned from callback");
auto sc = get_int(*objv++);
auto res_body = get_string(*objv++);
auto content_type = get_string(*objv++);
std::optional<http_tcl::headers> headers;
if (objc > req_args)
headers = get_dict(*objv++);
if (! sc)
return make_error(
"could not understand status code returned from callback");
return { *sc,
headers,
{ res_body.data(), res_body.size() },
{ content_type.data(), content_type.size() } };
}
head_r
do_head(std::string_view target, headers_access&& get_headers)
{
static const auto error
= std::make_tuple(500, std::nullopt, 0, "text/plain");
constexpr auto req_args = 3;
set_target(target);
set_body("");
set_headers(std::move(get_headers));
auto list = eval_to_list(config_.head.value());
if (! list)
return error;
auto [objc, objv] = *list;
if (objc < req_args)
return error;
auto sc = get_int(*objv++);
auto content_length = get_int(*objv++);
auto content_type = get_string(*objv++);
std::optional<http_tcl::headers> headers;
if (objc > req_args)
headers = get_dict(*objv++);
if (! sc || ! content_length)
return error;
return { *sc,
headers,
static_cast<size_t>(*content_length),
{ content_type.data(), content_type.size() } };
}
get_r
do_get(std::string_view target, headers_access&& get_headers)
{
constexpr auto req_args = 3;
const auto make_error = [&](char const* msg = nullptr) -> get_r {
return { 500, std::nullopt, msg ? msg : error_info(), "text/plain" };
};
set_target(target);
set_body("");
set_headers(std::move(get_headers));
auto list = eval_to_list(config_.get.value());
if (! list)
return make_error();
auto [objc, objv] = *list;
if (objc < req_args)
return make_error("wrong number of items returned from callback");
auto sc = get_int(*objv++);
auto body = get_string(*objv++);
auto content_type = get_string(*objv++);
std::optional<http_tcl::headers> headers;
if (objc > req_args)
headers = get_dict(*objv++);
if (! sc)
return make_error(
"could not understand status code returned from callback");
return { *sc,
headers,
{ body.data(), body.size() },
{ content_type.data(), content_type.size() } };
}
post_r
do_post(std::string_view target,
std::string_view body,
headers_access&& get_headers)
{
constexpr auto req_args = 3;
const auto make_error = [&](char const* msg = nullptr) -> post_r {
return { 500, std::nullopt, msg ? msg : error_info(), "text/plain" };
};
set_target(target);
set_body(body);
set_headers(std::move(get_headers));
auto list = eval_to_list(config_.post.value());
if (! list)
return make_error();
auto [objc, objv] = *list;
if (objc < req_args)
return make_error("wrong number of items returned from callback");
auto sc = get_int(*objv++);
auto res_body = get_string(*objv++);
auto content_type = get_string(*objv++);
std::optional<http_tcl::headers> headers;
if (objc > req_args)
headers = get_dict(*objv++);
if (! sc)
return make_error(
"could not understand status code returned from callback");
return { *sc,
headers,
{ res_body.data(), res_body.size() },
{ content_type.data(), content_type.size() } };
}
put_r
do_put(std::string_view target,
std::string_view body,
headers_access&& get_headers)
{
static const auto error = std::make_tuple(500, http_tcl::headers{});
constexpr auto req_args = 1;
set_target(target);
set_body(body);
set_headers(std::move(get_headers));
auto list = eval_to_list(config_.put.value());
if (! list)
return error;
auto [objc, objv] = *list;
if (objc < req_args)
return error;
auto sc = get_int(*objv++);
std::optional<http_tcl::headers> headers;
if (objc > req_args)
headers = get_dict(*objv++);
if (! sc)
return error;
return { *sc, headers };
}
delete_r
do_delete_(std::string_view target,
std::string_view body,
headers_access&& get_headers)
{
constexpr auto req_args = 3;
const auto make_error = [&](char const* msg = nullptr) -> delete_r {
return { 500, std::nullopt, msg ? msg : error_info(), "text/plain" };
};
set_target(target);
set_body(body);
set_headers(std::move(get_headers));
auto list = eval_to_list(config_.delete_.value());
if (! list)
return make_error();
auto [objc, objv] = *list;
if (objc < req_args)
return make_error("wrong number of items returned from callback");
auto sc = get_int(*objv++);
auto res_body = get_string(*objv++);
auto content_type = get_string(*objv++);
std::optional<http_tcl::headers> headers;
if (objc > req_args)
headers = get_dict(*objv++);
if (! sc)
return make_error(
"could not understand status code returned from callback");
return { *sc,
headers,
{ res_body.data(), res_body.size() },
{ content_type.data(), content_type.size() } };
}
};
struct client_data
{
tcl_handler handler;
void
init(Tcl_Interp*);
};
void
client_data::init(Tcl_Interp* i)
{
handler.init(i);
}
// global
client_data theClientData;
//
int
configure(ClientData cd, Tcl_Interp* i, int objc, Tcl_Obj* const objv[])
{
static const char* options[] = { "-head",
"-get",
"-post",
"-put",
"-delete",
"-reqtargetvariable",
"-reqbodyvariable",
"-reqheadersvariable",
"-host",
"-port",
"-options",
"-exittarget",
"-maxconnections",
nullptr };
auto cd_ptr = static_cast<client_data*>(cd);
auto& my_config = cd_ptr->handler.config();
if (objc == 2)
{
// return value of single option
int opt{ -1 };
if (Tcl_GetIndexFromObj(i, objv[1], options, "option", 0, &opt) != TCL_OK)
return TCL_ERROR;
std::vector<Tcl_Obj*> objv;
switch (opt)
{
case 0: objv.push_back(my_config.head.value()); break;
case 1: objv.push_back(my_config.get.value()); break;
case 2: objv.push_back(my_config.post.value()); break;
case 3: objv.push_back(my_config.put.value()); break;
case 4: objv.push_back(my_config.delete_.value()); break;
case 5: objv.push_back(my_config.req_target.value()); break;
case 6: objv.push_back(my_config.req_body.value()); break;
case 7: objv.push_back(my_config.req_headers.value()); break;
case 8: objv.push_back(my_config.host.value()); break;
case 9: objv.push_back(my_config.port.value()); break;
case 10: objv.push_back(my_config.options.value()); break;
case 11: objv.push_back(my_config.exit_target.value()); break;
case 12: objv.push_back(my_config.max_connections.value()); break;
default: return TCL_ERROR;
}
auto list = Tcl_NewListObj(objv.size(), objv.data());
Tcl_SetObjResult(i, list);
return TCL_OK;
}
// require odd number of arguments
if (objc % 2 == 0)
{
Tcl_WrongNumArgs(
i,
objc,
objv,
"?-host host? ?-port port? ?-head headCmd? ?-get getCmd? "
"?-post postCmd? ?-put "
"putCmd? ?-delete delCmd? ?-options optCmd? ?-reqtargetvariable varName? "
"?-reqbodyvariable varName? ?-reqheadersvariable varName? ?-exittarget "
"target? ?-maxconnections n?");
return TCL_ERROR;
}
if (objc == 1)
{
// return list of configuration
std::vector<Tcl_Obj*> objv;
objv.reserve(20);
objv.push_back(Tcl_NewStringObj("-host", -1));
objv.push_back(my_config.host.value());
objv.push_back(Tcl_NewStringObj("-port", -1));
objv.push_back(my_config.port.value());
objv.push_back(Tcl_NewStringObj("-head", -1));
objv.push_back(my_config.head.value());
objv.push_back(Tcl_NewStringObj("-get", -1));
objv.push_back(my_config.get.value());
objv.push_back(Tcl_NewStringObj("-post", -1));
objv.push_back(my_config.post.value());
objv.push_back(Tcl_NewStringObj("-put", -1));
objv.push_back(my_config.put.value());
objv.push_back(Tcl_NewStringObj("-delete", -1));
objv.push_back(my_config.delete_.value());
objv.push_back(Tcl_NewStringObj("-options", -1));
objv.push_back(my_config.options.value());
objv.push_back(Tcl_NewStringObj("-reqtargetvariable", -1));
objv.push_back(my_config.req_target.value());
objv.push_back(Tcl_NewStringObj("-reqbodyvariable", -1));
objv.push_back(my_config.req_body.value());
objv.push_back(Tcl_NewStringObj("-reqheadersvariable", -1));
objv.push_back(my_config.req_headers.value());
objv.push_back(Tcl_NewStringObj("-exittarget", -1));
objv.push_back(my_config.exit_target.value());
objv.push_back(Tcl_NewStringObj("-maxconnections", -1));
objv.push_back(my_config.max_connections.value());
auto list = Tcl_NewListObj(objv.size(), objv.data());
Tcl_SetObjResult(i, list);
return TCL_OK;
}
for (auto idx = 1; idx < objc - 1; idx += 2)
{
int opt{ -1 };
if (Tcl_GetIndexFromObj(i, objv[idx], options, "option", 0, &opt) != TCL_OK)
return TCL_ERROR;
auto obj = objv[idx + 1];
switch (opt)
{
case 0: my_config.head = obj; break;
case 1: my_config.get = obj; break;
case 2: my_config.post = obj; break;
case 3: my_config.put = obj; break;
case 4: my_config.delete_ = obj; break;
case 5: my_config.req_target = obj; break;
case 6: my_config.req_body = obj; break;
case 7: my_config.req_headers = obj; break;
case 8: my_config.host = obj; break;
case 9: my_config.port = obj; break;
case 10: my_config.options = obj; break;
case 11: my_config.exit_target = obj; break;
case 12: my_config.max_connections = obj; break;
default: return TCL_ERROR;
}
}
return TCL_OK;
}
int
http_client(ClientData cd, Tcl_Interp* i, int objc, Tcl_Obj* const objv[])
{
static const char* options[]
= { "-host", "-port", "-target", "-method", "-body", "-headers", nullptr };
auto const error = [&i, &objc, &objv] {
Tcl_WrongNumArgs(
i,
objc,
objv,
"?-host host? ?-port port? ?-target target? ?-method http-method? "
"?-body body? ?-headers headerDict?");
return TCL_ERROR;
};
// require odd number of arguments
if (objc % 2 == 0)
return error();
std::string host;
std::string port{ "80" };
std::string target{ "/" };
std::string method{ "get" };
std::string body;
std::optional<http_tcl::headers> headers;
for (auto idx = 1; idx < objc - 1; idx += 2)
{
int opt{ -1 };
if (Tcl_GetIndexFromObj(i, objv[idx], options, "option", 0, &opt) != TCL_OK)
return TCL_ERROR;
auto obj = objv[idx + 1];
switch (opt)
{
case 0: host = get_string(obj); break;
case 1: port = get_string(obj); break;
case 2: target = get_string(obj); break;
case 3: method = get_string(obj); break;
case 4: body = get_string(obj); break;
case 5: headers = get_dict(i, obj); break;
default: return TCL_ERROR;
}
}
if (host.empty())
return error();
tolower(method);
auto [sc, heads, res_body]
= http_tcl::http_client(method, host, port, target, headers, body);
std::vector<Tcl_Obj*> resv{
Tcl_NewStringObj(std::to_string(sc).c_str(), -1),
to_dict(i, heads),
Tcl_NewStringObj(res_body.c_str(), -1),
};
auto list = Tcl_NewListObj(resv.size(), resv.data());
Tcl_SetObjResult(i, list);
return TCL_OK;
}
int
run(ClientData cd, Tcl_Interp* i, int objc, Tcl_Obj* const objv[])
{
auto cd_ptr = static_cast<client_data*>(cd);
auto& my_config = cd_ptr->handler.config();
auto host = Tcl_GetString(my_config.host.value());
int port{ 0 };
int max_connections{ 0 };
if (Tcl_GetIntFromObj(i, my_config.port.value(), &port) != TCL_OK)
{
Tcl_SetObjResult(i, Tcl_NewStringObj("Invalid port number.", -1));
return TCL_ERROR;
}
// if bad value or not set, ignore the option and use server's default
if (Tcl_GetIntFromObj(i, my_config.max_connections.value(), &max_connections)
!= TCL_OK)
max_connections = 0;
if (max_connections)
http_tcl::run(host, port, &cd_ptr->handler, max_connections);
else
http_tcl::run(host, port, &cd_ptr->handler);
return TCL_OK;
}
int
percent_encode(ClientData cd, Tcl_Interp* i, int objc, Tcl_Obj* const objv[])
{
if (objc != 2)
{
Tcl_WrongNumArgs(i, objc, objv, "string");
return TCL_ERROR;
}
auto in = get_string(objv[1]);
auto out = url::percent_encode(in);
Tcl_SetObjResult(i, Tcl_NewStringObj(out.c_str(), out.size()));
return TCL_OK;
}
int
percent_decode(ClientData cd, Tcl_Interp* i, int objc, Tcl_Obj* const objv[])
{
if (objc != 2)
{
Tcl_WrongNumArgs(i, objc, objv, "string");
return TCL_ERROR;
}
auto in = get_string(objv[1]);
auto out = url::percent_decode(in);
if (out)
{
Tcl_SetObjResult(i, Tcl_NewStringObj(out->c_str(), out->size()));
return TCL_OK;
}
else
{
Tcl_AddErrorInfo(i, "could not decode string.");
return TCL_ERROR;
}
}
extern "C"
{
DllExport int
Act_http_Init(Tcl_Interp* i)
{
if (Tcl_InitStubs(i, TCL_VERSION, 0) == nullptr)
return TCL_ERROR;
theClientData.init(i);
#define def(name, func) \
Tcl_CreateObjCommand(i, \
theNamespaceName "::" name, \
(func), \
&theClientData, \
nullptr)
#define urldef(name, func) \
Tcl_CreateObjCommand(i, \
theUrlNamespaceName "::" name, \
(func), \
&theClientData, \
nullptr)
auto parent_ns
= Tcl_CreateNamespace(i, theParentNamespace, nullptr, nullptr);
auto ns = Tcl_CreateNamespace(i, theNamespaceName, nullptr, nullptr);
auto url_ns = Tcl_CreateNamespace(i, theUrlNamespaceName, nullptr, nullptr);
def("configure", configure);
def("run", run);
def("client", http_client);
urldef("encode", percent_encode);
urldef("decode", percent_decode);
if (Tcl_Export(i, ns, "*", 0) != TCL_OK)
return TCL_ERROR;
if (Tcl_Export(i, url_ns, "*", 0) != TCL_OK)
return TCL_ERROR;
if (Tcl_Export(i, parent_ns, "*", 0) != TCL_OK)
return TCL_ERROR;
Tcl_CreateEnsemble(i, theNamespaceName, ns, 0);
Tcl_CreateEnsemble(i, theUrlNamespaceName, url_ns, 0);
Tcl_PkgProvide(i, thePackageName, thePackageVersion);
return TCL_OK;
#undef def
#undef urldef
}
DllExport int
Act_http_Unload(Tcl_Interp* i, int flags)
{
auto ns = Tcl_FindNamespace(i, theNamespaceName, nullptr, 0);
auto url_ns = Tcl_CreateNamespace(i, theUrlNamespaceName, nullptr, nullptr);
Tcl_DeleteNamespace(ns);
Tcl_DeleteNamespace(url_ns);
// init client data again to free variables in the prior configuration
theClientData.init(i);
return TCL_OK;
}
}
| 27.784264 | 80 | 0.591669 |
42284a1b50025daf4b313acf93994d4c4491247c | 4,314 | hxx | C++ | ImageSharpOpenJpegNative/src/openjpeg.stream.hxx | cinderblocks/ImageSharp.OpenJpeg | bf5c976a6dbfa0d2666be566c845a7410440cea2 | [
"Apache-2.0"
] | null | null | null | ImageSharpOpenJpegNative/src/openjpeg.stream.hxx | cinderblocks/ImageSharp.OpenJpeg | bf5c976a6dbfa0d2666be566c845a7410440cea2 | [
"Apache-2.0"
] | null | null | null | ImageSharpOpenJpegNative/src/openjpeg.stream.hxx | cinderblocks/ImageSharp.OpenJpeg | bf5c976a6dbfa0d2666be566c845a7410440cea2 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2022 Sjofn LLC. 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.
*/
#ifndef _ISOJ_OPENJPEG_OPENJP2_OPENJPEG_STREAM_H_
#define _ISOJ_OPENJPEG_OPENJP2_OPENJPEG_STREAM_H_
#include "ImageSharpOpenJpeg_Exports.hxx"
#include "shared.hxx"
IMAGESHARPOPENJPEG_EXPORT void openjpeg_openjp2_opj_stream_destroy(opj_stream_t* p_stream)
{
::opj_stream_destroy(p_stream);
}
IMAGESHARPOPENJPEG_EXPORT const opj_stream_t* openjpeg_openjp2_opj_stream_default_create(const bool p_is_read_stream)
{
const auto b = p_is_read_stream ? OPJ_TRUE : OPJ_FALSE;
return ::opj_stream_default_create(b);
}
IMAGESHARPOPENJPEG_EXPORT const opj_stream_t* openjpeg_openjp2_opj_stream_create(const uint64_t p_buffer_size,
const bool p_is_read_stream)
{
const auto b = p_is_read_stream ? OPJ_TRUE : OPJ_FALSE;
return ::opj_stream_create(p_buffer_size, b);
}
IMAGESHARPOPENJPEG_EXPORT void openjpeg_openjp2_opj_stream_set_read_function(opj_stream_t* p_stream,
const opj_stream_read_fn p_function)
{
::opj_stream_set_read_function(p_stream, p_function);
}
IMAGESHARPOPENJPEG_EXPORT void openjpeg_openjp2_opj_stream_set_write_function(opj_stream_t* p_stream,
const opj_stream_write_fn p_function)
{
::opj_stream_set_write_function(p_stream, p_function);
}
IMAGESHARPOPENJPEG_EXPORT void openjpeg_openjp2_opj_stream_set_skip_function(opj_stream_t* p_stream,
const opj_stream_skip_fn p_function)
{
::opj_stream_set_skip_function(p_stream, p_function);
}
IMAGESHARPOPENJPEG_EXPORT void openjpeg_openjp2_opj_stream_set_seek_function(opj_stream_t* p_stream,
const opj_stream_seek_fn p_function)
{
::opj_stream_set_seek_function(p_stream, p_function);
}
IMAGESHARPOPENJPEG_EXPORT void openjpeg_openjp2_opj_stream_set_user_data(opj_stream_t* p_stream,
void* p_data,
const opj_stream_free_user_data_fn p_function)
{
::opj_stream_set_user_data(p_stream, p_data, p_function);
}
IMAGESHARPOPENJPEG_EXPORT void openjpeg_openjp2_opj_stream_set_user_data_length(opj_stream_t* p_stream,
const uint64_t data_length)
{
::opj_stream_set_user_data_length(p_stream, data_length);
}
IMAGESHARPOPENJPEG_EXPORT const opj_stream_t* openjpeg_openjp2_opj_stream_create_default_file_stream(const char *fname,
const uint32_t fname_len,
const bool p_is_read_stream)
{
const auto str = std::string(fname, fname_len);
const auto b = p_is_read_stream ? OPJ_TRUE : OPJ_FALSE;
return ::opj_stream_create_default_file_stream(str.c_str(), b);
}
IMAGESHARPOPENJPEG_EXPORT const opj_stream_t* openjpeg_openjp2_opj_stream_create_file_stream(const char *fname,
const uint32_t fname_len,
const uint64_t p_buffer_size,
const bool p_is_read_stream)
{
const auto str = std::string(fname, fname_len);
const auto b = p_is_read_stream ? OPJ_TRUE : OPJ_FALSE;
return ::opj_stream_create_file_stream(str.c_str(), p_buffer_size, b);
}
#endif // _CPP_OPENJPEG_OPENJP2_OPENJPEG_STREAM_H_ | 44.474227 | 119 | 0.64905 |
422a2115bc21c765bd1cca906ed584b4d1ca0c01 | 3,783 | cpp | C++ | .RemoteTalk/Plugin/RemoteTalkCeVIOCS/rtcvTalkServer.cpp | i-saint/RemoteTalk | 3ac2528ab66ed923cb9c56596944effdeaecee50 | [
"MIT"
] | 36 | 2018-12-18T22:33:36.000Z | 2021-10-31T07:03:15.000Z | .RemoteTalk/Plugin/RemoteTalkCeVIOCS/rtcvTalkServer.cpp | i-saint/RemoteTalk | 3ac2528ab66ed923cb9c56596944effdeaecee50 | [
"MIT"
] | 1 | 2020-04-04T16:13:43.000Z | 2020-04-05T05:08:17.000Z | .RemoteTalk/Plugin/RemoteTalkCeVIOCS/rtcvTalkServer.cpp | i-saint/RemoteTalk | 3ac2528ab66ed923cb9c56596944effdeaecee50 | [
"MIT"
] | 3 | 2019-04-12T17:37:23.000Z | 2020-09-30T15:50:31.000Z | #include "pch.h"
#include "rtcvCommon.h"
#include "rtcvHookHandler.h"
#include "rtcvTalkServer.h"
namespace rtcv {
TalkServer::TalkServer()
{
auto exe_path = rt::GetMainModulePath();
auto config_path = rt::GetCurrentModuleDirectory() + "\\" + rtcvConfigFile;
auto settings = rt::GetOrAddServerSettings(config_path, exe_path, rtcvDefaultPort);
m_settings.port = settings.port;
m_tmp_path = rt::GetCurrentModuleDirectory() + "\\tmp.wav";
}
void TalkServer::addMessage(MessagePtr mes)
{
super::addMessage(mes);
processMessages();
}
bool TalkServer::isReady()
{
return false;
}
TalkServer::Status TalkServer::onStats(StatsMessage& mes)
{
auto ifs = rtGetTalkInterface_();
auto& stats = mes.stats;
ifs->getParams(stats.params);
{
int n = ifs->getNumCasts();
for (int i = 0; i < n; ++i)
stats.casts.push_back(*ifs->getCastInfo(i));
}
stats.host = ifs->getClientName();
stats.plugin_version = ifs->getPluginVersion();
stats.protocol_version = ifs->getProtocolVersion();
return Status::Succeeded;
}
TalkServer::Status TalkServer::onTalk(TalkMessage& mes)
{
if (m_task_talk.valid()) {
if (m_task_talk.wait_for(std::chrono::milliseconds(0)) == std::future_status::timeout)
return Status::Failed;
}
m_params = mes.params;
auto ifs = rtGetTalkInterface_();
ifs->setParams(mes.params);
ifs->setText(mes.text.c_str());
if (m_mode == Mode::ExportFile) {
ifs->setTempFilePath(m_tmp_path.c_str());
if (!ifs->play())
return Status::Failed;
auto data = std::make_shared<rt::AudioData>();
if (!rt::ImportWave(*data, m_tmp_path.c_str()))
return Status::Failed;
std::remove(m_tmp_path.c_str());
m_data_queue.push_back(data);
m_data_queue.push_back(std::make_shared<rt::AudioData>());
}
else {
ifs->setTempFilePath("");
WaveOutHandler::getInstance().mute = m_params.mute;
if (!ifs->play())
Status::Failed;
m_task_talk = std::async(std::launch::async, [this, ifs]() {
ifs->wait();
WaveOutHandler::getInstance().mute = false;
{
auto terminator = std::make_shared<rt::AudioData>();
std::unique_lock<std::mutex> lock(m_data_mutex);
m_data_queue.push_back(terminator);
}
});
}
mes.task = std::async(std::launch::async, [this, &mes]() {
std::vector<rt::AudioDataPtr> tmp;
for (;;) {
{
std::unique_lock<std::mutex> lock(m_data_mutex);
tmp = m_data_queue;
m_data_queue.clear();
}
for (auto& ad : tmp) {
ad->serialize(*mes.respond_stream);
}
if (!tmp.empty() && tmp.back()->data.empty())
break;
else
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
});
return Status::Succeeded;
}
TalkServer::Status TalkServer::onStop(StopMessage& mes)
{
auto ifs = rtGetTalkInterface_();
return ifs->stop() ? Status::Succeeded : Status::Failed;
}
#ifdef rtDebug
TalkServer::Status TalkServer::onDebug(DebugMessage& mes)
{
return rtGetTalkInterface_()->onDebug() ? Status::Succeeded : Status::Failed;
}
#endif
void TalkServer::onUpdateBuffer(const rt::AudioData& data)
{
auto ifs = rtGetTalkInterface_();
if (!ifs->isPlaying())
return;
auto tmp = std::make_shared<rt::AudioData>(data);
if (m_params.force_mono)
tmp->convertToMono();
{
std::unique_lock<std::mutex> lock(m_data_mutex);
m_data_queue.push_back(tmp);
}
}
} // namespace rtcv
| 27.215827 | 94 | 0.597409 |
422abceab02e1f78d551c813dcfafaeb7b3316f8 | 1,027 | cpp | C++ | DSA Crack Sheet/solutions/4. Sort An Array Of 0s 1s And 2s.cpp | sumanthbolle/DataStructures-Algorithms | d04edbcdd0794f5668e26bd003b46548150eccbc | [
"MIT"
] | 1 | 2021-02-11T15:07:17.000Z | 2021-02-11T15:07:17.000Z | DSA Crack Sheet/solutions/4. Sort An Array Of 0s 1s And 2s.cpp | sumanthbolle/DataStructures-Algorithms | d04edbcdd0794f5668e26bd003b46548150eccbc | [
"MIT"
] | null | null | null | DSA Crack Sheet/solutions/4. Sort An Array Of 0s 1s And 2s.cpp | sumanthbolle/DataStructures-Algorithms | d04edbcdd0794f5668e26bd003b46548150eccbc | [
"MIT"
] | null | null | null | // O(nlogn)
#include <bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin >> t;
while (t--)
{
int n;
cin >> n;
vector<int> arr(n, 0);
for (int i = 0; i < n; ++i)
cin >> arr[i];
sort(arr.begin(), arr.end());
for (int i = 0; i < n; ++i)
cout << arr[i] << " ";
cout << endl;
}
return 0;
}
/* =============================== */
// O(n)
#include <bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin >> t;
while (t--)
{
int n;
cin >> n;
vector<int> arr(n, 0);
int num[3] = {0};
for (int i = 0; i < n; ++i)
{
cin >> arr[i];
num[arr[i]]++;
}
for (int i = 0; i < n; ++i)
{
if (num[0])
{
arr[i] = 0;
num[0]--;
}
else if (num[1])
{
arr[i] = 1;
num[1]--;
}
else if (num[2])
{
arr[i] = 2;
num[2]--;
}
}
for (int i = 0; i < n; ++i)
cout << arr[i] << " ";
cout << endl;
}
return 0;
} | 13.693333 | 37 | 0.351509 |
422f8f65625cf6e361471362aadeddbdb1afa670 | 2,040 | cpp | C++ | als/main.cpp | al-petrushin/kubsu-cpp-tasks | c280a7c7a743742f5b0ba2bb8bc0e02cd2e7bdc9 | [
"MIT"
] | null | null | null | als/main.cpp | al-petrushin/kubsu-cpp-tasks | c280a7c7a743742f5b0ba2bb8bc0e02cd2e7bdc9 | [
"MIT"
] | null | null | null | als/main.cpp | al-petrushin/kubsu-cpp-tasks | c280a7c7a743742f5b0ba2bb8bc0e02cd2e7bdc9 | [
"MIT"
] | null | null | null | //
// Created by Александр Петрушин on 26.04.2021.
//
#include <vector>
#include <functional>
#include <iostream>
#include <fstream>
#include "linear_regression.h"
#include "gradient.h"
#include "errors.h"
//#include "matplotlibcpp.h"
using namespace std;
std::function<double(double)> Eval(vector<double> input, vector<double> output, vector<double> start_params)
{
auto function = [](double v, vector<double> params) {
return params[0] * (v * v) + params[1] * v + params[2];
};
auto minized = [input, output, function](vector<double> params) {
vector<double> result(input.size());
for (int i = 0; i < input.size(); i++) {
result[i] = function(input[i], params);
}
return MSE(result, output);
};
auto best_params = GradientSolve((std::function<double(vector<double>)>)minized, start_params, 0.01, 1000);
return [best_params, function](double v) {
return function(v, best_params);
};
}
int main()
{
vector<double> input = {1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75, 3};
vector<double> output = {5.21, 4.196, 3.759, 3.672, 4.592, 4.621, 5.758, 7.173, 9.269};
int size = input.size();
auto evalFunc = Eval(input, output, {1, 1, 1});
auto regression = LinearRegression(input, output);
vector<double> nonLinearRegressionOut(size), linearRegressionOut(size);
for (int i = 0; i < size; i++) {
nonLinearRegressionOut[i] = evalFunc(input[i]);
linearRegressionOut[i] = regression(input[i]);
}
cout << "MSE for non-linear regression = " << MSE(output, nonLinearRegressionOut) << endl;
cout << "MSE for linear regression = " << MSE(output, linearRegressionOut) << endl;
// matplotlibcpp::figure_size(1200, 780);
// matplotlibcpp::named_plot("target", input);
// matplotlibcpp::named_plot("linear", out2);
// matplotlibcpp::named_plot("linear", out1);
// matplotlibcpp::title("Sample figure");
// matplotlibcpp::legend();
// matplotlibcpp::save("./basic.png");
return 0;
} | 29.565217 | 111 | 0.631373 |
4230390bb7e512943db7e5e32ea2f6b9d20132e2 | 4,489 | cpp | C++ | Classes/dragondash/TowerManager.cpp | Dotosoft/game02-cpp-blueprints | 781db6935658cdef7e07087a88f9ce1a22aee2d5 | [
"MIT"
] | 1 | 2016-08-25T15:33:09.000Z | 2016-08-25T15:33:09.000Z | Classes/dragondash/TowerManager.cpp | Dotosoft/game02-cpp-blueprints | 781db6935658cdef7e07087a88f9ce1a22aee2d5 | [
"MIT"
] | null | null | null | Classes/dragondash/TowerManager.cpp | Dotosoft/game02-cpp-blueprints | 781db6935658cdef7e07087a88f9ce1a22aee2d5 | [
"MIT"
] | 2 | 2020-03-06T01:00:56.000Z | 2020-03-25T06:07:52.000Z | #include "dragondash\TowerManager.h"
using namespace dragondash;
dragondash::TowerManager::TowerManager(Vec2 position)
{
this->lowerSprite = NULL;
this->upperSprite = NULL;
this->position = position;
}
dragondash::TowerManager::TowerManager(GameWorld * parent)
{
// save reference to GameWorld
this->gameworld = parent;
this->screenSize = parent->screenSize;
// initialise variables
// this->towers = [];
this->towerSpriteSize = Size::ZERO;
this->firstTowerIndex = 0;
this->lastTowerIndex = 0;
}
bool dragondash::TowerManager::init()
{
// record size of the tower's sprite
this->towerSpriteSize = SpriteFrameCache::getInstance()->getSpriteFrameByName("opst_02")->getOriginalSize() * this->gameworld->scaleFactor;
// create the first pair of towers
// they should be two whole screens away from the dragon
auto initialPosition = Vec2(this->screenSize.width * 2, this->screenSize.height*0.5);
this->firstTowerIndex = 0;
this->createTower(initialPosition);
// create the remaining towers
this->lastTowerIndex = 0;
this->createTower(this->getNextTowerPosition());
this->lastTowerIndex = 1;
this->createTower(this->getNextTowerPosition());
this->lastTowerIndex = 2;
return true;
}
void dragondash::TowerManager::createTower(Vec2 position)
{
// create a new tower and add it to the array
auto tower = new TowerManager(position);
this->towers.pushBack(tower);
// create lower tower sprite & add it to GameWorld's batch node
tower->lowerSprite = Sprite::createWithSpriteFrameName("opst_02");
tower->lowerSprite->setScale(this->gameworld->scaleFactor);
tower->lowerSprite->setPositionX(position.x);
tower->lowerSprite->setPositionY(position.y + VERT_GAP_BWN_TOWERS * -0.5 + this->towerSpriteSize.height * -0.5);
this->gameworld->spriteBatchNode->addChild(tower->lowerSprite, E_ZORDER::E_LAYER_TOWER);
// create upper tower sprite & add it to GameWorld's batch node
tower->upperSprite = Sprite::createWithSpriteFrameName("opst_01");
tower->upperSprite->setScale(this->gameworld->scaleFactor);
tower->upperSprite->setPositionX(position.x);
tower->upperSprite->setPositionY(position.y + VERT_GAP_BWN_TOWERS * 0.5 + this->towerSpriteSize.height * 0.5);
this->gameworld->spriteBatchNode->addChild(tower->upperSprite, E_ZORDER::E_LAYER_TOWER);
}
void dragondash::TowerManager::update()
{
TowerManager* tower;
for (int i = 0; i < this->towers.size(); ++i)
{
tower = this->towers.at(i);
// first update the position of the tower
tower->position.x -= MAX_SCROLLING_SPEED;
tower->lowerSprite->setPosition(tower->position.x, tower->lowerSprite->getPositionY());
tower->upperSprite->setPosition(tower->position.x, tower->upperSprite->getPositionY());
// if the tower has moved out of the screen, reposition them at the end
if (tower->position.x < this->towerSpriteSize.width * -0.5)
{
this->repositionTower(i);
// this tower now becomes the tower at the end
this->lastTowerIndex = i;
// that means some other tower has become first
this->firstTowerIndex = ((i + 1) >= this->towers.size()) ? 0 : (i + 1);
}
}
}
void dragondash::TowerManager::repositionTower(int index)
{
auto tower = this->towers.at(index);
// update tower's position and sprites
tower->position = this->getNextTowerPosition();
tower->lowerSprite->setPosition(tower->position.x, tower->position.y + VERT_GAP_BWN_TOWERS * -0.5 + this->towerSpriteSize.height * -0.5);
tower->upperSprite->setPosition(tower->position.x, tower->position.y + VERT_GAP_BWN_TOWERS * 0.5 + this->towerSpriteSize.height * 0.5);
}
Vec2 dragondash::TowerManager::getNextTowerPosition()
{
// randomly select either above or below last tower
bool isAbove = (CCRANDOM_0_1() > 0.5);
float offset = CCRANDOM_0_1() * VERT_GAP_BWN_TOWERS * 0.75;
offset *= (isAbove) ? 1 : -1;
// new position calculated by adding to last tower's position
float newPositionX = this->towers.at(this->lastTowerIndex)->position.x + this->screenSize.width * 0.5f;
float newPositionY = this->towers.at(this->lastTowerIndex)->position.y + offset;
// limit the point to stay within 30-80% of the screen
if (newPositionY >= this->screenSize.height * 0.8) {
newPositionY -= VERT_GAP_BWN_TOWERS;
} else if (newPositionY <= this->screenSize.height * 0.3) {
newPositionY += VERT_GAP_BWN_TOWERS;
}
// return the new tower position
return Vec2(newPositionX, newPositionY);
}
dragondash::TowerManager* dragondash::TowerManager::getFrontTower()
{
return this->towers.at(this->firstTowerIndex);
}
| 36.495935 | 140 | 0.736021 |
42343997e5cbaabd2bfbd8b043a5e62720235bc0 | 3,837 | cpp | C++ | sysy2riscv/ast_tigger.cpp | Yibo-He/sysyCompiler | fd95b17153b565d9ccb69c296cdcc8be64670b11 | [
"MIT"
] | 7 | 2021-06-06T05:26:38.000Z | 2021-12-25T08:19:43.000Z | sysy2riscv/ast_tigger.cpp | Yibo-He/sysyCompiler | fd95b17153b565d9ccb69c296cdcc8be64670b11 | [
"MIT"
] | null | null | null | sysy2riscv/ast_tigger.cpp | Yibo-He/sysyCompiler | fd95b17153b565d9ccb69c296cdcc8be64670b11 | [
"MIT"
] | null | null | null | #include "ast_tigger.hpp"
int string2num(const string s){
return atoi(s.c_str());
}
string num2string_3(int num){
string ans = to_string(num);
return ans;
}
int op2int(string op){
if(!strcmp(op.c_str(),"+")) return Plus;
if(!strcmp(op.c_str(),"-")) return Minus;
if(!strcmp(op.c_str(),"*")) return Multi;
if(!strcmp(op.c_str(),"/")) return Divi;
if(!strcmp(op.c_str(),"%")) return Mod;
if(!strcmp(op.c_str(),"!")) return Not;
if(!strcmp(op.c_str(),">")) return More;
if(!strcmp(op.c_str(),"<")) return Less;
if(!strcmp(op.c_str(),">=")) return MorEq;
if(!strcmp(op.c_str(),"<=")) return LorEq;
if(!strcmp(op.c_str(),"&&")) return And;
if(!strcmp(op.c_str(),"||")) return Or;
if(!strcmp(op.c_str(),"!=")) return Neq;
if(!strcmp(op.c_str(),"==")) return Eq;
return -1;
}
void ProgramAST::generator(){
for(auto i:varDecls) i->generator();
riscvCode.push_back(" ");
for(auto i:funDefs) i->generator();
for(auto &i: riscvCode)
cout << i << endl;
cout << endl;
}
void GlobalVarDeclAST::generator(){
if(isMalloc){
riscvCode.push_back(" .comm "+ varName +", "+ num +", 4");
}else{
riscvCode.push_back(" .global " + varName);
riscvCode.push_back(" .section .sdata");
riscvCode.push_back(" .align 2");
riscvCode.push_back(" .type " + varName + ", @object");
riscvCode.push_back(" .size " + varName + ", 4");
riscvCode.push_back(varName + ":");
riscvCode.push_back(" .word " + num);
}
}
void FunctionDefAST::generator(){
funHead->generator();
exps->generator();
funEnd->generator();
}
void FunctionHeaderAST::generator(){
riscvCode.push_back(" .text");
riscvCode.push_back(" .align 2");
riscvCode.push_back(" .global " + funName);
riscvCode.push_back(" .type " + funName + ", @function");
riscvCode.push_back(funName + ":");
int STK = (n2 / 4 + 1) * 16;
vector<BaseTiggerAST*>::iterator itBegin = dynamic_cast<ExpressionsAST*>(dynamic_cast<FunctionDefAST*>(funDef)->exps)->exp.begin();
vector<BaseTiggerAST*>::iterator itEnd = dynamic_cast<ExpressionsAST*>(dynamic_cast<FunctionDefAST*>(funDef)->exps)->exp.end();
for(itBegin;itBegin!=itEnd;++itBegin){
(*itBegin)->STK = STK;
}
if(STK<=2047 && STK>=-2048){
riscvCode.push_back(" addi sp, sp, -" + num2string_3(STK));
riscvCode.push_back(" sw ra, " + num2string_3(STK-4) + "(sp)");
}else {
riscvCode.push_back(" li s0, " + num2string_3(STK));
riscvCode.push_back(" sub sp, sp, s0");
riscvCode.push_back(" add s0, s0, sp");
riscvCode.push_back(" sw ra, -4(s0)");
}
}
void ExpressionsAST::generator(){
for(auto i: exp){
i->generator();
}
}
void FunctionEndAST::generator(){
riscvCode.push_back(" .size " + funName + ", .-" + funName);
}
void ExpressionAST::generator(){
list<string>::iterator it = riscvAction.begin();
if(!strcmp(it->c_str(), "ret")){
if(STK<=2047 && STK>=-2048){
string tmp;
tmp = " lw ra, "+num2string_3(STK-4)+"(sp)";
riscvCode.push_back(tmp);
tmp = " addi sp, sp, "+num2string_3(STK);
riscvCode.push_back(tmp);
tmp = " ret";
riscvCode.push_back(tmp);
}else {
riscvCode.push_back(" li s0, " + num2string_3(STK));
riscvCode.push_back(" add s0, s0, sp");
riscvCode.push_back(" lw ra, -4(s0)");
riscvCode.push_back(" li s0, " + num2string_3(STK));
riscvCode.push_back(" add sp, sp, s0");
riscvCode.push_back(" ret");
}
} else {
riscvCode.splice(riscvCode.end(), riscvAction);
}
} | 35.201835 | 135 | 0.562419 |
4236cbcd2e4cad1781694ca6d2e1c343d97cd435 | 775 | cpp | C++ | System/test_Triangle/Triangle1.cpp | Mr-Hunter/Linux | dc222abe4e961a65282d7bc8ac6a301657386ddc | [
"Apache-2.0"
] | 2 | 2018-10-30T08:06:57.000Z | 2019-12-12T03:05:58.000Z | System/test_Triangle/Triangle1.cpp | Mr-Hunter/Linux | dc222abe4e961a65282d7bc8ac6a301657386ddc | [
"Apache-2.0"
] | null | null | null | System/test_Triangle/Triangle1.cpp | Mr-Hunter/Linux | dc222abe4e961a65282d7bc8ac6a301657386ddc | [
"Apache-2.0"
] | null | null | null | /*************************************************************************
> File Name: Triangle1.cpp
> Author: Hunter
> Mail: hunter.520@qq.com
> Created Time: Tue 02 Apr 2019 11:21:37 PM PDT
************************************************************************/
#include <iostream>
#include <stdio.h>
using namespace std;
int main(int argc, char* argv[])
{
int i,j,n=0,a[17]={1},b[17];
while(n<1 || n>16)
{ printf("请输入杨辉三角形的行数:");
scanf("%d",&n);
}
for(i=0;i<n;i++)
{ b[0]=a[0];
for(j=1;j<=i;j++)
b[j]=a[j-1]+a[j]; /*每个数是上面两数之和*/
for(j=0;j<=i;j++) /*输出杨辉三角*/
{ a[j]=b[j]; /*把算得的新行赋给a,用于打印和下一次计算*/
printf("%5d",a[j]);
}
printf("\n");
}
return 0;
}
| 24.21875 | 74 | 0.383226 |
4236d0f908e7d559293bd761abda432e8267c9c3 | 4,973 | cpp | C++ | source/scene/Scene.cpp | freneticmonkey/epsilonc | 0fb7c6c4c6342a770e2882bfd67ed34719e79066 | [
"MIT"
] | null | null | null | source/scene/Scene.cpp | freneticmonkey/epsilonc | 0fb7c6c4c6342a770e2882bfd67ed34719e79066 | [
"MIT"
] | null | null | null | source/scene/Scene.cpp | freneticmonkey/epsilonc | 0fb7c6c4c6342a770e2882bfd67ed34719e79066 | [
"MIT"
] | null | null | null | #include "scene/Scene.h"
namespace epsilon
{
Scene::Ptr Scene::Create(std::string name)
{
Scene::Ptr newScene = std::make_shared<Scene>(private_struct(), name);
newScene->Setup();
return newScene;
}
Scene::Scene(const private_struct &, std::string sceneName) : name(sceneName)
{
}
Scene::~Scene(void)
{
Destroy();
}
void Scene::Destroy()
{
if (rootNode != nullptr)
{
rootNode->OnDestroy();
rootNode = nullptr;
}
}
// Initialise the default values of the scene
void Scene::Setup()
{
// Create a root node for the scene
rootNode = SceneNode::Create("root");
// Set the this scene as the current scene
rootNode->SetScene(ThisPtr());
// Get the new node's transform as the scene root transform
rootTransform = rootNode->GetTransform();
// Attach a node with a camera as the default scene camera
SceneNode::Ptr camNode = rootNode->CreateChild("camera_node");
// Set the new camera as the default / active camera
SetActiveCamera(camNode->CreateCamera("main_camera"));
// Move default camera to a suitable position
camNode->transform->SetPosition(0, 1, -10);
//camNode->transform->LookAt(Vector3(0, 1, 0));
}
bool Scene::operator==(Scene::Ptr other)
{
return name == other->name;
}
bool Scene::operator==(std::string otherName)
{
return name == otherName;
}
void Scene::Update(float el)
{
rootTransform->_update(true, false);
}
void Scene::SetActiveCamera(Camera::Ptr camera)
{
// Add the camera
AddCamera(camera);
// Set it as the active camera
activeCamera = camera;
std::for_each(sceneCameras.begin(), sceneCameras.end(), [](Camera::Ptr camera){
camera->SetActive(false);
});
camera->SetActive(true);
}
void Scene::SetActiveCamera(std::string name)
{
// Find the camera
bool found = false;
CameraList::iterator cam = std::find_if(sceneCameras.begin(), sceneCameras.end(), [name](Camera::Ptr camera) {
return camera->GetName() == name;
});
// if a camera with name 'name' wasn't found
if (cam == sceneCameras.end())
{
Log("Error setting active camera. Unknown camera: " + name);
}
else
{
// Set the found camera as the active camera
SetActiveCamera(*cam);
}
}
bool Scene::AddCamera(Camera::Ptr newCamera)
{
// Find the camera
bool added = false;
CameraList::iterator it = std::find_if(sceneCameras.begin(), sceneCameras.end(), [&](Camera::Ptr cam){
return cam->GetId() == newCamera->GetId();
});
// if a new camera
if (it == sceneCameras.end())
{
// keep track of it
sceneCameras.push_back(newCamera);
added = true;
}
// Return the result of the add
return added;
}
bool Scene::RemoveCamera(Camera::Ptr camera)
{
// Find the camera
bool found = false;
CameraList::iterator it = std::find_if(sceneCameras.begin(), sceneCameras.end(), [&](Camera::Ptr cam){
return cam == camera;
});
if (it != sceneCameras.end())
{
sceneCameras.erase(it);
found = true;
}
// Return the result
return found;
}
bool Scene::RemoveCamera(std::string name)
{
// Find the camera
bool found = false;
CameraList::iterator it = std::find_if(sceneCameras.begin(), sceneCameras.end(), [&](Camera::Ptr cam){
return cam->GetName() == name;
});
if (it != sceneCameras.end())
{
sceneCameras.erase(it);
found = true;
}
// Return the result
return found;
}
Camera::Ptr Scene::GetCamera(std::string name)
{
Camera::Ptr foundCam;
CameraList::iterator it = std::find_if(sceneCameras.begin(), sceneCameras.end(), [&](Camera::Ptr cam){
return cam->GetName() == name;
});
if (it != sceneCameras.end())
{
foundCam = (*it);
}
return foundCam;
}
bool Scene::AddLight(Light::Ptr light)
{
bool success = false;
LightList::iterator it = std::find_if(sceneLights.begin(), sceneLights.end(), [&](Light::Ptr light){
return light->GetName() == name;
});
if (it == sceneLights.end())
{
sceneLights.push_back(light);
success = true;
}
return success;
}
bool Scene::RemoveLight(Light::Ptr light)
{
bool success = false;
LightList::iterator it = std::find_if(sceneLights.begin(), sceneLights.end(), [&](Light::Ptr sLight){
return light == sLight;
});
if (it == sceneLights.end())
{
sceneLights.erase(it);
success = true;
}
return success;
}
bool Scene::RemoveLight(std::string name)
{
bool success = false;
LightList::iterator it = std::find_if(sceneLights.begin(), sceneLights.end(), [&](Light::Ptr light){
return light->GetName() == name;
});
if (it == sceneLights.end())
{
sceneLights.erase(it);
success = true;
}
return success;
}
Light::Ptr Scene::GetLight(std::string name)
{
Light::Ptr foundLight;
LightList::iterator it = std::find_if(sceneLights.begin(), sceneLights.end(), [&](Light::Ptr light){
return light->GetName() == name;
});
if (it != sceneLights.end())
{
foundLight = *it;
}
return foundLight;
}
}
| 20.052419 | 112 | 0.645285 |
4236f3c151d40f8581667f417cbe6145c80ffa77 | 2,335 | hpp | C++ | addons/main/weapons/CfgWeapMG.hpp | johnb432/Weapons-Balance-FOW | 9d72a7f5a86b59ed6c651b62a39cc08dd21f694e | [
"MIT"
] | null | null | null | addons/main/weapons/CfgWeapMG.hpp | johnb432/Weapons-Balance-FOW | 9d72a7f5a86b59ed6c651b62a39cc08dd21f694e | [
"MIT"
] | null | null | null | addons/main/weapons/CfgWeapMG.hpp | johnb432/Weapons-Balance-FOW | 9d72a7f5a86b59ed6c651b62a39cc08dd21f694e | [
"MIT"
] | null | null | null | //https://old.weaponsystems.net/weaponsystem/AA06%20-%20Bren.html
class fow_w_bren: fow_rifle_base {
ACE_barrelLength = 635;
ACE_barrelTwist = 254;
ACE_Overheating_allowSwapBarrel = 1;
displayName = "Bren Mk.II";
magazineReloadTime = 0;
magazineWell[] += {"CBA_303B_BREN"};
class WeaponSlotsInfo: WeaponSlotsInfo {
mass = 228.2;
};
};
class fow_w_fg42: fow_rifle_base {
ACE_barrelLength = 500;
ACE_barrelTwist = 240;
displayName = "FG 42";
magazineWell[] += {"CBA_792x57_FG42"};
class WeaponSlotsInfo: WeaponSlotsInfo {
mass = 93;
};
};
class fow_w_m1918a2: fow_rifle_base {
ACE_barrelLength = 610;
ACE_barrelTwist = 254;
displayName = "M1918A2 BAR";
magazineWell[] += {"CBA_3006_BAR"};
};
class fow_w_m1918a2_bak: fow_w_m1918a2 {
displayName = "M1918A2 BAR (Bakelite)";
};
class fow_w_m1919: fow_rifle_base {
ACE_barrelLength = 610;
ACE_barrelTwist = 254;
ACE_Overheating_allowSwapBarrel = 1;
displayName = "M1919A4";
magazineWell[] += {"CBA_3006_Belt"};
class WeaponSlotsInfo: WeaponSlotsInfo {};
};
class fow_w_m1919a4: fow_w_m1919 {
displayName = "M1919A4";
class WeaponSlotsInfo: WeaponSlotsInfo {
mass = 310;
};
};
class fow_w_m1919a6: fow_w_m1919 {
displayName = "M1919A6";
class WeaponSlotsInfo: WeaponSlotsInfo {
mass = 330.7;
};
};
class fow_w_mg34: fow_rifle_base {
ACE_barrelLength = 627;
ACE_barrelTwist = 240;
ACE_Overheating_allowSwapBarrel = 1;
displayName = "MG 34";
magazineReloadTime = 0;
magazineWell[] += {"CBA_792x57_LINKS"};
class WeaponSlotsInfo: WeaponSlotsInfo {
mass = 264.5;
};
};
class fow_w_mg42: fow_rifle_base {
ACE_barrelLength = 530;
ACE_barrelTwist = 240;
ACE_Overheating_allowSwapBarrel = 1;
displayName = "MG 42";
magazineReloadTime = 0;
magazineWell[] += {"CBA_792x57_LINKS"};
class WeaponSlotsInfo: WeaponSlotsInfo {
mass = 254.5;
};
};
class fow_w_type99_lmg: fow_rifle_base {
ACE_barrelLength = 550;
ACE_barrelTwist = 254;
ACE_Overheating_allowSwapBarrel = 1;
displayName = "Type 99 LMG";
magazineReloadTime = 0;
magazineWell[] += {"CBA_77x58_Type99"};
class WeaponSlotsInfo: WeaponSlotsInfo {
mass = 299;
};
};
| 25.944444 | 65 | 0.667238 |
42370348e04d00d16d863f09edf9807461c0286b | 2,982 | cpp | C++ | src/kmr_behaviortree/plugins/action/plan_manipulator_path.cpp | stoic-roboticist/kmriiwa_ws_devel | 582c2477ec29c9eb68bd826c64f2ec1f76feb4a6 | [
"Apache-2.0"
] | 22 | 2020-04-06T16:35:33.000Z | 2022-03-29T07:47:38.000Z | src/kmr_behaviortree/plugins/action/plan_manipulator_path.cpp | stoic-roboticist/kmriiwa_ws_devel | 582c2477ec29c9eb68bd826c64f2ec1f76feb4a6 | [
"Apache-2.0"
] | 2 | 2020-09-04T10:09:25.000Z | 2021-11-30T20:43:50.000Z | src/kmr_behaviortree/plugins/action/plan_manipulator_path.cpp | stoic-roboticist/kmriiwa_ws_devel | 582c2477ec29c9eb68bd826c64f2ec1f76feb4a6 | [
"Apache-2.0"
] | 10 | 2020-06-16T08:36:56.000Z | 2022-03-29T07:48:11.000Z |
// Copyright 2019 Nina Marie Wahl and Charlotte Heggem.
// Copyright 2019 Norwegian University of Science and Technology.
//
// 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 "kmr_behaviortree/bt_action_node.hpp"
#include "kmr_msgs/action/plan_to_frame.hpp"
#include "trajectory_msgs/msg/joint_trajectory.hpp"
#include <geometry_msgs/msg/pose_stamped.hpp>
#include <iostream>
namespace kmr_behavior_tree
{
class PlanManipulatorPathAction : public BtActionNode<kmr_msgs::action::PlanToFrame>
{
public:
PlanManipulatorPathAction(
const std::string & xml_tag_name,
const std::string & action_name,
const BT::NodeConfiguration & conf)
: BtActionNode<kmr_msgs::action::PlanToFrame>(xml_tag_name, action_name, conf)
{
}
void on_tick() override
{
if (!getInput("plan_to_frame", plan_to_frame)) {
RCLCPP_ERROR(node_->get_logger(),"PlanToFrameAction: frame not provided");
return;
}
goal_.frame = plan_to_frame;
RCLCPP_INFO(node_->get_logger(),"Start planning to %s", plan_to_frame.c_str());
if (plan_to_frame == "object"){
geometry_msgs::msg::PoseStamped pose_msg;
getInput("object_pose",pose_msg);
goal_.pose = pose_msg;
}
}
BT::NodeStatus on_success() override
{
setOutput("manipulator_path", result_.result->path);
setOutput("move_to_frame", plan_to_frame);
return BT::NodeStatus::SUCCESS;
}
static BT::PortsList providedPorts()
{
return providedBasicPorts(
{
BT::InputPort<std::string>("plan_to_frame", "The frame MoveIt should plan to"),
BT::InputPort<geometry_msgs::msg::PoseStamped>("object_pose", "Pose of the object manipulator should move to"),
BT::OutputPort<trajectory_msgs::msg::JointTrajectory>("manipulator_path", "The path MoveIt has planned for the manipulator"),
BT::OutputPort<std::string>("move_to_frame", "Frame we should move to"),
});
}
private:
std::string plan_to_frame;
};
} // namespace kmr_behavior_tree
//register our custom TreeNodes into the BehaviorTreeFactory
#include "behaviortree_cpp_v3/bt_factory.h"
BT_REGISTER_NODES(factory)
{
BT::NodeBuilder builder =
[](const std::string & name, const BT::NodeConfiguration & config)
{
return std::make_unique<kmr_behavior_tree::PlanManipulatorPathAction>(
name, "/moveit/frame", config);
};
factory.registerBuilder<kmr_behavior_tree::PlanManipulatorPathAction>(
"PlanManipulatorPath", builder);
} | 33.505618 | 133 | 0.724346 |
423765ec487b397f7871841a4b4f5ae931495248 | 1,882 | cpp | C++ | src/ColdTowerShopItem.cpp | dgi09/Tower-Defence | 2edd53d50c9f913d00de26e7e2bdc5e8b950cc02 | [
"BSD-2-Clause"
] | 1 | 2021-07-28T15:24:00.000Z | 2021-07-28T15:24:00.000Z | src/ColdTowerShopItem.cpp | dgi09/Tower-Defence | 2edd53d50c9f913d00de26e7e2bdc5e8b950cc02 | [
"BSD-2-Clause"
] | null | null | null | src/ColdTowerShopItem.cpp | dgi09/Tower-Defence | 2edd53d50c9f913d00de26e7e2bdc5e8b950cc02 | [
"BSD-2-Clause"
] | null | null | null | #include "ColdTowerShopItem.h"
#include "GamePlayMediator.h"
#include "ArenaHeap.h"
#include <functional>
#include "GUISystem.h"
#include "TowerCreationTool.h"
#include "ToolManager.h"
#include "SplashCreationTool.h"
ColdTowerShopItem::ColdTowerShopItem(void)
{
}
ColdTowerShopItem::~ColdTowerShopItem(void)
{
}
void ColdTowerShopItem::updateState(PlayerStat & stat)
{
if(stat.gold < itemCost)
{
button->loadImageFromFile("Data/ShopImages/coldTurretUnavailable.png");
state = UNACTIVE;
}
else
{
button->loadImageFromFile("Data/ShopImages/coldTurret.png");
state = ACTIVE;
}
button->setWidth(buttonW);
button->setHeight(buttonH);
}
void ColdTowerShopItem::init()
{
initGUI("Cold Tower","Data/ShopImages/coldTurret.png");
button->subsribeEvent(PRESS,new MemberSubsciber<ColdTowerShopItem>(&ColdTowerShopItem::onClick,this));
tower = ArenaHeap::getPtr()->ColdTowers.New();
tower->init();
}
void ColdTowerShopItem::onDestroy()
{
destroyGUI();
tower->destroy();
tower->removeFromHeap();
}
void ColdTowerShopItem::onClick(Widget * sender)
{
if(state == ACTIVE)
{
TowerCreationTool * tool = new TowerCreationTool();
tool->setTower(tower->copy());
tool->setTowerCost(itemCost);
ToolManager::getPtr()->setActiveTool(tool);
}
}
void ColdTowerShopItem::setDamage(double damage)
{
tower->setDamageValue(damage);
}
void ColdTowerShopItem::setAmmoSpeed(int speed)
{
tower->setAmmoSpeed(speed);
}
void ColdTowerShopItem::setRange(double range)
{
tower->setRangeValue(range);
}
void ColdTowerShopItem::setShootRate(int ms)
{
tower->setShootRate(ms);
}
void ColdTowerShopItem::setSlowDuration(int ms)
{
tower->setSlowingDuration(ms);
}
void ColdTowerShopItem::setSpeedDecrease(int speedDecrease)
{
tower->setSpeedDecrease(speedDecrease);
}
void ColdTowerShopItem::postPropertySet()
{
ic.init(itemCost,tower);
ic.attach(info);
}
| 17.109091 | 103 | 0.745484 |
423e648f5f47046258fed6b8938ba99d024c7d8f | 3,229 | cpp | C++ | src/qt/qtbase/examples/widgets/graphicsview/boxes/glextensions.cpp | power-electro/phantomjs-Gohstdriver-DIY-openshift | a571d301a9658a4c1b524d07e15658b45f8a0579 | [
"BSD-3-Clause"
] | 1 | 2020-04-30T15:47:35.000Z | 2020-04-30T15:47:35.000Z | src/qt/qtbase/examples/widgets/graphicsview/boxes/glextensions.cpp | power-electro/phantomjs-Gohstdriver-DIY-openshift | a571d301a9658a4c1b524d07e15658b45f8a0579 | [
"BSD-3-Clause"
] | null | null | null | src/qt/qtbase/examples/widgets/graphicsview/boxes/glextensions.cpp | power-electro/phantomjs-Gohstdriver-DIY-openshift | a571d301a9658a4c1b524d07e15658b45f8a0579 | [
"BSD-3-Clause"
] | null | null | null | /****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the demonstration applications of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** As a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "glextensions.h"
#define RESOLVE_GL_FUNC(f) ok &= bool((f = (_gl##f) context->getProcAddress(QLatin1String("gl" #f))));
bool GLExtensionFunctions::resolve(const QGLContext *context)
{
bool ok = true;
RESOLVE_GL_FUNC(GenFramebuffersEXT)
RESOLVE_GL_FUNC(GenRenderbuffersEXT)
RESOLVE_GL_FUNC(BindRenderbufferEXT)
RESOLVE_GL_FUNC(RenderbufferStorageEXT)
RESOLVE_GL_FUNC(DeleteFramebuffersEXT)
RESOLVE_GL_FUNC(DeleteRenderbuffersEXT)
RESOLVE_GL_FUNC(BindFramebufferEXT)
RESOLVE_GL_FUNC(FramebufferTexture2DEXT)
RESOLVE_GL_FUNC(FramebufferRenderbufferEXT)
RESOLVE_GL_FUNC(CheckFramebufferStatusEXT)
RESOLVE_GL_FUNC(ActiveTexture)
RESOLVE_GL_FUNC(TexImage3D)
RESOLVE_GL_FUNC(GenBuffers)
RESOLVE_GL_FUNC(BindBuffer)
RESOLVE_GL_FUNC(BufferData)
RESOLVE_GL_FUNC(DeleteBuffers)
RESOLVE_GL_FUNC(MapBuffer)
RESOLVE_GL_FUNC(UnmapBuffer)
return ok;
}
bool GLExtensionFunctions::fboSupported() {
return GenFramebuffersEXT
&& GenRenderbuffersEXT
&& BindRenderbufferEXT
&& RenderbufferStorageEXT
&& DeleteFramebuffersEXT
&& DeleteRenderbuffersEXT
&& BindFramebufferEXT
&& FramebufferTexture2DEXT
&& FramebufferRenderbufferEXT
&& CheckFramebufferStatusEXT;
}
bool GLExtensionFunctions::openGL15Supported() {
return ActiveTexture
&& TexImage3D
&& GenBuffers
&& BindBuffer
&& BufferData
&& DeleteBuffers
&& MapBuffer
&& UnmapBuffer;
}
#undef RESOLVE_GL_FUNC
| 35.483516 | 102 | 0.691855 |
4244cf3519c3f83103e5e498a05f02df486a4631 | 91 | cc | C++ | muduo/net/boilerplate.cc | 923310233/muduoTest | 03c291df5605479ece4fc031ab3dd619c8c8f73a | [
"BSD-3-Clause"
] | null | null | null | muduo/net/boilerplate.cc | 923310233/muduoTest | 03c291df5605479ece4fc031ab3dd619c8c8f73a | [
"BSD-3-Clause"
] | null | null | null | muduo/net/boilerplate.cc | 923310233/muduoTest | 03c291df5605479ece4fc031ab3dd619c8c8f73a | [
"BSD-3-Clause"
] | null | null | null |
#include "muduo/net/BoilerPlate.h"
using namespace muduo;
using namespace muduo::net;
| 10.111111 | 34 | 0.747253 |
424639e79751125238e05d98a96dd490fced1f81 | 1,074 | cpp | C++ | workshop8/IntlPhone.cpp | PavanKamra96/BTP200 | 516f5ed60452da53d47206caef22423825a3145e | [
"MIT"
] | null | null | null | workshop8/IntlPhone.cpp | PavanKamra96/BTP200 | 516f5ed60452da53d47206caef22423825a3145e | [
"MIT"
] | null | null | null | workshop8/IntlPhone.cpp | PavanKamra96/BTP200 | 516f5ed60452da53d47206caef22423825a3145e | [
"MIT"
] | null | null | null | #include <iostream>
#include "Phone.h"
IntlPhone::IntlPhone(){
country_Code = 0;
}
IntlPhone::IntlPhone(int regionCode, int areaCode, int localNumber): Phone(areaCode, localNumber) {
//ctor
if (regionCode >= 1 && regionCode <= 999) {
country_Code = regionCode;
} else
*this = IntlPhone();
}
void IntlPhone::display() const {
std::cout << country_Code << '-';
Phone::display();
}
bool IntlPhone::isValid() const {
return country_Code != 0;
}
std::istream & operator >> (std::istream & is, IntlPhone & p) {
int tempRegionCode;
int tempAreaCode;
int tempLocaleNumber;
std::cout << "Country : ";
is >> tempRegionCode;
if (tempRegionCode >= 1 && tempRegionCode <= 999) {
std::cout << "Area Code : ";
is >> tempAreaCode;
std::cout << "Local No. : ";
is >> tempLocaleNumber;
}
IntlPhone temp(tempRegionCode, tempAreaCode, tempLocaleNumber);
p = temp;
return is;
}
std::ostream & operator << (std::ostream & os,
const IntlPhone & p) {
p.display();
return os;
} | 21.918367 | 100 | 0.608007 |
42465f2891251668ec041517ceea4841891deed4 | 800 | cpp | C++ | src/components/src/core/Component.cpp | walter-strazak/chimarrao | b4c9f9d726eb5e46d61b33e10b7579cc5512cd09 | [
"MIT"
] | 6 | 2021-04-20T10:32:29.000Z | 2021-06-05T11:48:56.000Z | src/components/src/core/Component.cpp | walter-strazak/chimarrao | b4c9f9d726eb5e46d61b33e10b7579cc5512cd09 | [
"MIT"
] | 1 | 2021-05-18T21:00:12.000Z | 2021-06-02T07:59:03.000Z | src/components/src/core/Component.cpp | walter-strazak/chimarrao | b4c9f9d726eb5e46d61b33e10b7579cc5512cd09 | [
"MIT"
] | 3 | 2020-09-12T08:54:04.000Z | 2021-04-17T11:16:36.000Z | #include "Component.h"
#include "ComponentOwner.h"
namespace components::core
{
Component::Component(ComponentOwner* ownerInit) : owner{ownerInit} {}
void Component::loadDependentComponents() {}
void Component::update(utils::DeltaTime, const input::Input&) {}
void Component::lateUpdate(utils::DeltaTime, const input::Input&) {}
void Component::enable()
{
enabled = true;
}
void Component::disable()
{
enabled = false;
}
bool Component::isEnabled() const
{
return enabled;
}
std::string Component::getOwnerName() const
{
return owner->getName();
}
unsigned int Component::getOwnerId() const
{
return owner->getId();
}
bool Component::shouldBeRemoved() const
{
return owner->shouldBeRemoved();
}
ComponentOwner& Component::getOwner() const
{
return *owner;
}
} | 16 | 69 | 0.70625 |
4247f6d342a62cdcce8c0dab9c859a873e016ffa | 13,178 | cpp | C++ | Nacro/SDK/FN_BP_FortExpeditionListItem_functions.cpp | Milxnor/Nacro | eebabf662bbce6d5af41820ea0342d3567a0aecc | [
"BSD-2-Clause"
] | 11 | 2021-08-08T23:25:10.000Z | 2022-02-19T23:07:22.000Z | Nacro/SDK/FN_BP_FortExpeditionListItem_functions.cpp | Milxnor/Nacro | eebabf662bbce6d5af41820ea0342d3567a0aecc | [
"BSD-2-Clause"
] | 1 | 2022-01-01T22:51:59.000Z | 2022-01-08T16:14:15.000Z | Nacro/SDK/FN_BP_FortExpeditionListItem_functions.cpp | Milxnor/Nacro | eebabf662bbce6d5af41820ea0342d3567a0aecc | [
"BSD-2-Clause"
] | 8 | 2021-08-09T13:51:54.000Z | 2022-01-26T20:33:37.000Z | // Fortnite (1.8) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "../SDK.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Functions
//---------------------------------------------------------------------------
// Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Update Bang State
// (Public, BlueprintCallable, BlueprintEvent)
// Parameters:
// class UFortAccountItem* Item (Parm, ZeroConstructor, IsPlainOldData)
void UBP_FortExpeditionListItem_C::Update_Bang_State(class UFortAccountItem* Item)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Update Bang State");
UBP_FortExpeditionListItem_C_Update_Bang_State_Params params;
params.Item = Item;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Success Chance
// (Public, BlueprintCallable, BlueprintEvent)
// Parameters:
// class UFortExpeditionItem* Item (Parm, ZeroConstructor, IsPlainOldData)
void UBP_FortExpeditionListItem_C::Set_Success_Chance(class UFortExpeditionItem* Item)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Success Chance");
UBP_FortExpeditionListItem_C_Set_Success_Chance_Params params;
params.Item = Item;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Vehicle Icon
// (Public, HasDefaults, BlueprintCallable, BlueprintEvent)
// Parameters:
// class UFortExpeditionItem* Expedition (ConstParm, Parm, ZeroConstructor, IsPlainOldData)
void UBP_FortExpeditionListItem_C::Set_Vehicle_Icon(class UFortExpeditionItem* Expedition)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Vehicle Icon");
UBP_FortExpeditionListItem_C_Set_Vehicle_Icon_Params params;
params.Expedition = Expedition;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Expedition Returns Data
// (Public, BlueprintCallable, BlueprintEvent)
// Parameters:
// class UFortExpeditionItem* InputPin (Parm, ZeroConstructor, IsPlainOldData)
void UBP_FortExpeditionListItem_C::Set_Expedition_Returns_Data(class UFortExpeditionItem* InputPin)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Expedition Returns Data");
UBP_FortExpeditionListItem_C_Set_Expedition_Returns_Data_Params params;
params.InputPin = InputPin;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set In Progress State
// (Public, BlueprintCallable, BlueprintEvent)
// Parameters:
// class UFortExpeditionItem* Item (Parm, ZeroConstructor, IsPlainOldData)
void UBP_FortExpeditionListItem_C::Set_In_Progress_State(class UFortExpeditionItem* Item)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set In Progress State");
UBP_FortExpeditionListItem_C_Set_In_Progress_State_Params params;
params.Item = Item;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Remaining Expiration Time
// (Public, BlueprintCallable, BlueprintEvent)
// Parameters:
// class UFortExpeditionItem* Item (Parm, ZeroConstructor, IsPlainOldData)
void UBP_FortExpeditionListItem_C::Set_Remaining_Expiration_Time(class UFortExpeditionItem* Item)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Remaining Expiration Time");
UBP_FortExpeditionListItem_C_Set_Remaining_Expiration_Time_Params params;
params.Item = Item;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Rarity
// (Public, HasDefaults, BlueprintCallable, BlueprintEvent)
// Parameters:
// class UFortItem* Item (Parm, ZeroConstructor, IsPlainOldData)
void UBP_FortExpeditionListItem_C::Set_Rarity(class UFortItem* Item)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Rarity");
UBP_FortExpeditionListItem_C_Set_Rarity_Params params;
params.Item = Item;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Rating
// (Public, BlueprintCallable, BlueprintEvent)
// Parameters:
// class UFortExpeditionItem* Item (Parm, ZeroConstructor, IsPlainOldData)
void UBP_FortExpeditionListItem_C::Set_Rating(class UFortExpeditionItem* Item)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Rating");
UBP_FortExpeditionListItem_C_Set_Rating_Params params;
params.Item = Item;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Rewards
// (Public, HasDefaults, BlueprintCallable, BlueprintEvent)
// Parameters:
// class UFortItem* Item (Parm, ZeroConstructor, IsPlainOldData)
void UBP_FortExpeditionListItem_C::Set_Rewards(class UFortItem* Item)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Rewards");
UBP_FortExpeditionListItem_C_Set_Rewards_Params params;
params.Item = Item;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Get Expedition Item Definition
// (Public, HasOutParms, BlueprintCallable, BlueprintEvent, BlueprintPure)
// Parameters:
// class UFortItem* Item (Parm, ZeroConstructor, IsPlainOldData)
// class UFortExpeditionItemDefinition* Item_Def (Parm, OutParm, ZeroConstructor, IsPlainOldData)
void UBP_FortExpeditionListItem_C::Get_Expedition_Item_Definition(class UFortItem* Item, class UFortExpeditionItemDefinition** Item_Def)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Get Expedition Item Definition");
UBP_FortExpeditionListItem_C_Get_Expedition_Item_Definition_Params params;
params.Item = Item;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (Item_Def != nullptr)
*Item_Def = params.Item_Def;
}
// Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Name
// (Public, HasDefaults, BlueprintCallable, BlueprintEvent)
// Parameters:
// class UFortItem* Item (Parm, ZeroConstructor, IsPlainOldData)
void UBP_FortExpeditionListItem_C::Set_Name(class UFortItem* Item)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Name");
UBP_FortExpeditionListItem_C_Set_Name_Params params;
params.Item = Item;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Setup Base Item Data
// (Public, HasDefaults, BlueprintCallable, BlueprintEvent)
// Parameters:
// class UFortExpeditionItem* Expedition (Parm, ZeroConstructor, IsPlainOldData)
void UBP_FortExpeditionListItem_C::Setup_Base_Item_Data(class UFortExpeditionItem* Expedition)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Setup Base Item Data");
UBP_FortExpeditionListItem_C_Setup_Base_Item_Data_Params params;
params.Expedition = Expedition;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.SetData
// (Event, Public, BlueprintCallable, BlueprintEvent)
// Parameters:
// class UObject** InData (Parm, ZeroConstructor, IsPlainOldData)
// class UCommonListView** OwningList (Parm, ZeroConstructor, IsPlainOldData)
void UBP_FortExpeditionListItem_C::SetData(class UObject** InData, class UCommonListView** OwningList)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.SetData");
UBP_FortExpeditionListItem_C_SetData_Params params;
params.InData = InData;
params.OwningList = OwningList;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.OnSelected
// (Event, Protected, BlueprintEvent)
void UBP_FortExpeditionListItem_C::OnSelected()
{
static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.OnSelected");
UBP_FortExpeditionListItem_C_OnSelected_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.OnItemChanged
// (Event, Protected, BlueprintEvent)
void UBP_FortExpeditionListItem_C::OnItemChanged()
{
static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.OnItemChanged");
UBP_FortExpeditionListItem_C_OnItemChanged_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.OnDeselected
// (Event, Protected, BlueprintEvent)
void UBP_FortExpeditionListItem_C::OnDeselected()
{
static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.OnDeselected");
UBP_FortExpeditionListItem_C_OnDeselected_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.BndEvt__InProgressSwitcher_K2Node_ComponentBoundEvent_17_OnActiveWidgetChanged__DelegateSignature
// (BlueprintEvent)
// Parameters:
// class UWidget* ActiveWidget (Parm, ZeroConstructor, IsPlainOldData)
// int ActiveWidgetIndex (Parm, ZeroConstructor, IsPlainOldData)
void UBP_FortExpeditionListItem_C::BndEvt__InProgressSwitcher_K2Node_ComponentBoundEvent_17_OnActiveWidgetChanged__DelegateSignature(class UWidget* ActiveWidget, int ActiveWidgetIndex)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.BndEvt__InProgressSwitcher_K2Node_ComponentBoundEvent_17_OnActiveWidgetChanged__DelegateSignature");
UBP_FortExpeditionListItem_C_BndEvt__InProgressSwitcher_K2Node_ComponentBoundEvent_17_OnActiveWidgetChanged__DelegateSignature_Params params;
params.ActiveWidget = ActiveWidget;
params.ActiveWidgetIndex = ActiveWidgetIndex;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.OnHovered
// (Event, Protected, BlueprintEvent)
void UBP_FortExpeditionListItem_C::OnHovered()
{
static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.OnHovered");
UBP_FortExpeditionListItem_C_OnHovered_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.ExecuteUbergraph_BP_FortExpeditionListItem
// ()
// Parameters:
// int EntryPoint (Parm, ZeroConstructor, IsPlainOldData)
void UBP_FortExpeditionListItem_C::ExecuteUbergraph_BP_FortExpeditionListItem(int EntryPoint)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.ExecuteUbergraph_BP_FortExpeditionListItem");
UBP_FortExpeditionListItem_C_ExecuteUbergraph_BP_FortExpeditionListItem_Params params;
params.EntryPoint = EntryPoint;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 33.277778 | 213 | 0.773258 |
4249a13c522a0727ca53058a12a138656bd75265 | 3,962 | cxx | C++ | Google_hashcode/2018/main.cxx | mstrechen/cp | ffac439840a71f70580a0ef197e47479e167a0eb | [
"MIT"
] | null | null | null | Google_hashcode/2018/main.cxx | mstrechen/cp | ffac439840a71f70580a0ef197e47479e167a0eb | [
"MIT"
] | null | null | null | Google_hashcode/2018/main.cxx | mstrechen/cp | ffac439840a71f70580a0ef197e47479e167a0eb | [
"MIT"
] | null | null | null | #include<iostream>
#include<vector>
#include<random>
#include<algorithm>
#include<tuple>
using namespace std;
const int INF = 2000*1000*1000;
struct Ride{
int x1, y1;
int x2, y2;
int l, r;
int index;
int getLen(int, int, int) const;
int getCost(int, int, int) const;
};
int Ride::getLen(int x, int y, int t) const{
int first_len = t + max(abs(x1 - x) + abs(y1 - y), l);
int second_len = abs(x1 - x2) + abs(y1 - y2);
if(first_len + second_len >= r)
return INF;
return first_len + second_len;
}
int Ride::getCost(int x, int y, int t) const {
int first_len = t + max(abs(x1 - x) + abs(y1 - y), l);
int second_len = abs(x1 - x2) + abs(y1 - y2);
if(first_len + second_len >= r)
return INF;
return first_len;
}
struct City{
int R, C, F, N, B, T;
vector<Ride> rides;
vector<tuple<int, int, int> > currentPos;
vector<vector<int> > finalRides;
void calculateRides();
};
void City::calculateRides(){
srand(0);
int max_iterations_cnt = 1000*10;
while(max_iterations_cnt-- && rides.size()){
int i = rand() % finalRides.size();
auto & currentCar = currentPos[i];
auto get_optimal = [&](const auto & a, const auto & b){
int t1 = a.getCost(get<0>(currentCar), get<1>(currentCar), get<2>(currentCar));
int t2 = b.getCost(get<0>(currentCar), get<1>(currentCar), get<2>(currentCar));
return t1 > t2; };
auto it = max_element(rides.begin(), rides.end(),
get_optimal);
int tmp = 41;
while(it->getLen(get<0>(currentCar), get<1>(currentCar), get<2>(currentCar)) != INF){
finalRides[i].push_back(it->index);
currentCar = make_tuple(it->x2, it->y2, it->getLen(get<0>(currentCar), get<1>(currentCar), get<2>(currentCar)));
rides.erase(it);
if(rides.size() == 0 || tmp-- == 0)
break;
it = max_element(rides.begin(), rides.end(),
get_optimal);
}
}
/*
for(int _i = 0; _i < iterations_count; _i++){
int i = UID(gen);
auto & currentCar = currentPos[i];
auto it = max_element(rides.begin(), rides.end(),
[&](const auto & a, const auto & b){
int t1 = a.getCost(get<0>(currentCar), get<1>(currentCar), get<2>(currentCar));
int t2 = b.getCost(get<0>(currentCar), get<1>(currentCar), get<2>(currentCar));
return t1 < t2;}
);
finalRides[i].push_back(it->index);
currentCar = {it->y1, it->y2, it->getLen(get<0>(currentCar),
get<1>(currentCar),
get<2>(currentCar))};
rides.erase(it);
}
*/
}
istream & operator >> (istream & in, Ride & toRead){
in >> toRead.x1 >> toRead.y1
>> toRead.x2 >> toRead.y2
>> toRead.l >> toRead.r;
return in;
}
istream & operator >> (istream & in, City & toRead){
in >> toRead.R >> toRead.C
>> toRead.F >> toRead.N
>> toRead.B >> toRead.T;
toRead.rides.resize(toRead.N);
toRead.finalRides.resize(toRead.F);
toRead.currentPos.assign(toRead.F, tuple<int, int, int>(0, 0, 0));
int j = 0;
for(auto & i : toRead.rides){
in >> i;
i.index = j;
j++;
}
return in;
};
ostream & operator << (ostream & out, const City & toWrite){
for(auto & i : toWrite.finalRides){
cout << i.size();
for(auto & j : i)
cout << ' ' << j;
cout << '\n';
}
return out;
}
int main(int argc, char ** argv){
int MIA = atoi(argv[1]);
ios::sync_with_stdio(false);
cin.tie(nullptr);
City city;
cin >> city;
city.calculateRides();
cout << city;
return 0;
} | 25.235669 | 124 | 0.513882 |
424b58ad8420784e1df4081159cab8fabb0cb5d7 | 1,073 | cpp | C++ | CodeChef/TSHIRTS.cpp | ggml1/Competitive-Programming | 1f5aa8f8d2f8addffd5a22c9ccd998f05b6faf79 | [
"MIT"
] | null | null | null | CodeChef/TSHIRTS.cpp | ggml1/Competitive-Programming | 1f5aa8f8d2f8addffd5a22c9ccd998f05b6faf79 | [
"MIT"
] | null | null | null | CodeChef/TSHIRTS.cpp | ggml1/Competitive-Programming | 1f5aa8f8d2f8addffd5a22c9ccd998f05b6faf79 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll mod = 1e9 + 7;
const int ms = 123;
const int mv = 11;
ll dp[ms][1 << mv];
ll ways(int x, ll mask, ll limit, vector<int> shirts[], int n){
if(shirts[x].size() == 0) return ways(x+1, mask, limit, shirts, n);
if(mask == limit){
return 1;
}
if(x >= 101) return 0;
if(dp[x][mask] != -1){
return dp[x][mask];
}
ll ans = ways(x+1, mask, limit, shirts, n);
for(int j = 0, c = shirts[x].size(); j < c; ++j){
if(!(mask & (1 << shirts[x][j]))){
ans += ways(x+1, mask | (1 << shirts[x][j]), limit, shirts, n);
ans %= mod;
}
}
return dp[x][mask] = ans;
}
int main(){
ios::sync_with_stdio(0); cin.tie(0);
int t; cin >> t;
while(t--){
int n; cin >> n; cin.ignore();
vector<int> shirts[ms];
for(int i = 0; i < n; ++i){
int x;
string k; getline(cin, k);
stringstream ss(k);
while(ss >> x){
shirts[x].push_back(i);
}
}
memset(dp, -1, sizeof(dp));
cout << ways(0, 0, (1 << n) - 1, shirts, n) << endl;
}
return 0;
}
| 17.031746 | 68 | 0.520969 |
424b68c2de65ac475af42da66f7a935a66b8460f | 299 | cpp | C++ | 13_ploymorph/main.cpp | Aaron-labo/Cpp_StudyNotes | afff37736468b26dad87e9b5cda90f1e5f1efb06 | [
"Unlicense"
] | 1 | 2021-06-17T11:37:42.000Z | 2021-06-17T11:37:42.000Z | 13_ploymorph/main.cpp | Aaron-labo/Cpp_StudyNotes | afff37736468b26dad87e9b5cda90f1e5f1efb06 | [
"Unlicense"
] | null | null | null | 13_ploymorph/main.cpp | Aaron-labo/Cpp_StudyNotes | afff37736468b26dad87e9b5cda90f1e5f1efb06 | [
"Unlicense"
] | null | null | null | #include "Circle.h"
#include "Rect.h"
int main()
{
Circle c(1, 2, 3);
Rect r(10, 20, 30, 40);
Shape s(1, 2);
s.show();
int input;
while (1) {
cin >> input;
switch (input)
{
case 1:
s = &c;;
s->show();
break;
case 2:
s = &r;;
s->show();
break;
}
}
return 0;
} | 10.678571 | 24 | 0.478261 |
424f0a9d20c8f5343f00778ce197924e1945e367 | 1,178 | cpp | C++ | Based_Engine/Based_Engine/TextureResource.cpp | Sanmopre/Based_Engine | 2a408dc501f6357bde9872e2eef70f67295e0a3a | [
"MIT"
] | null | null | null | Based_Engine/Based_Engine/TextureResource.cpp | Sanmopre/Based_Engine | 2a408dc501f6357bde9872e2eef70f67295e0a3a | [
"MIT"
] | null | null | null | Based_Engine/Based_Engine/TextureResource.cpp | Sanmopre/Based_Engine | 2a408dc501f6357bde9872e2eef70f67295e0a3a | [
"MIT"
] | null | null | null | #include "TextureResource.h"
#include "FileSystem.h"
TextureResource::TextureResource(uint uid, const char* assetsFile, const char* libraryFile)
: Resource(uid, FileType::IMAGE, assetsFile, libraryFile)
{
}
TextureResource::~TextureResource()
{
}
const Texture TextureResource::GetTexture() const
{
return texture;
}
bool TextureResource::LoadInMemory()
{
texture = TextureLoader::Load(assetsFile.c_str());
if (texture.id != NULL)
return true;
return false;
}
bool TextureResource::Unload()
{
texture = { NULL, NULL, NULL };
return true;
}
//void Input::ProccesImage(std::string file)
//{
// GameObject* object = App->objects->selected;
// if (!object)
// {
// object = App->objects->AddObject(nullptr, App->objects->selected, true, "Plane");
// object->AddMeshComponent("Library/Meshes/plane.monki", file.c_str());
// }
// else
// {
// bool found = false;
// for (uint c = 0; c < object->components.size(); c++)
// {
// if (object->components[c]->AddTexture(file.c_str()))
// {
// found = true;
// break;
// }
// }
// if (!found)
// object->AddMeshComponent("Library/Meshes/plane.monki", file.c_str());
// }
//}
| 20.666667 | 91 | 0.643463 |
4250158ef2b3d006b1cdb28c80860f418155bc23 | 1,269 | cpp | C++ | 508 - A4-spbspu-labs-2020-904-3/spbspu-labs-2020-904-3-master-yakovlev.alexey/3/common/base-types.cpp | NekoSilverFox/CPP | c6797264fceda4a65ac3452acca496e468d1365a | [
"Apache-2.0"
] | 5 | 2020-02-08T20:57:21.000Z | 2021-12-23T06:24:41.000Z | 508 - A4-spbspu-labs-2020-904-3/spbspu-labs-2020-904-3-master-yakovlev.alexey/3/common/base-types.cpp | NekoSilverFox/CPP | c6797264fceda4a65ac3452acca496e468d1365a | [
"Apache-2.0"
] | 2 | 2020-03-02T14:44:55.000Z | 2020-11-11T16:25:33.000Z | 508 - A4-spbspu-labs-2020-904-3/spbspu-labs-2020-904-3-master-yakovlev.alexey/3/common/base-types.cpp | NekoSilverFox/CPP | c6797264fceda4a65ac3452acca496e468d1365a | [
"Apache-2.0"
] | 4 | 2020-09-27T17:30:03.000Z | 2022-02-16T09:48:23.000Z | #include "base-types.hpp"
#include <ostream>
#include <cmath>
bool yakovlev::operator==(const point_t & lhs, const point_t & rhs) noexcept
{
return (lhs.x == rhs.x) && (lhs.y == rhs.y);
}
bool yakovlev::operator!=(const point_t & lhs, const point_t & rhs) noexcept
{
return !(lhs == rhs);
}
std::ostream& yakovlev::operator<<(std::ostream & os, const point_t & point)
{
return os << '(' << point.x << ", " << point.y << ')';
}
namespace
{
double square(double x) noexcept;
}
double yakovlev::getDistanceBetweenPoints(const point_t & p1, const point_t & p2) noexcept
{
return sqrt(square(p1.x - p2.x) + square(p1.y - p2.y));
}
bool yakovlev::areOverlapping(const rectangle_t & lhs, const rectangle_t & rhs) noexcept
{
return (abs(lhs.pos.x - rhs.pos.x) < ((lhs.width + rhs.width) / 2.0))
&& (abs(lhs.pos.y - rhs.pos.y) < ((lhs.height + rhs.height) / 2.0));
}
bool yakovlev::operator==(const rectangle_t & lhs, const rectangle_t & rhs) noexcept
{
return (lhs.width == rhs.width)
&& (lhs.height == rhs.height)
&& (lhs.pos == rhs.pos);
}
bool yakovlev::operator!=(const rectangle_t & lhs, const rectangle_t & rhs) noexcept
{
return !(lhs == rhs);
}
namespace
{
double square(double x) noexcept
{
return x * x;
}
}
| 22.660714 | 90 | 0.63357 |
4252acccfbd215a271503823aa57cb38bd306a22 | 25,064 | cc | C++ | videoenhan/src/VideoenhanClient.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 89 | 2018-02-02T03:54:39.000Z | 2021-12-13T01:32:55.000Z | videoenhan/src/VideoenhanClient.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 89 | 2018-03-14T07:44:54.000Z | 2021-11-26T07:43:25.000Z | videoenhan/src/VideoenhanClient.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 69 | 2018-01-22T09:45:52.000Z | 2022-03-28T07:58:38.000Z | /*
* Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/videoenhan/VideoenhanClient.h>
#include <alibabacloud/core/SimpleCredentialsProvider.h>
using namespace AlibabaCloud;
using namespace AlibabaCloud::Location;
using namespace AlibabaCloud::Videoenhan;
using namespace AlibabaCloud::Videoenhan::Model;
namespace
{
const std::string SERVICE_NAME = "videoenhan";
}
VideoenhanClient::VideoenhanClient(const Credentials &credentials, const ClientConfiguration &configuration) :
RpcServiceClient(SERVICE_NAME, std::make_shared<SimpleCredentialsProvider>(credentials), configuration)
{
auto locationClient = std::make_shared<LocationClient>(credentials, configuration);
endpointProvider_ = std::make_shared<EndpointProvider>(locationClient, configuration.regionId(), SERVICE_NAME, "videoenhan");
}
VideoenhanClient::VideoenhanClient(const std::shared_ptr<CredentialsProvider>& credentialsProvider, const ClientConfiguration & configuration) :
RpcServiceClient(SERVICE_NAME, credentialsProvider, configuration)
{
auto locationClient = std::make_shared<LocationClient>(credentialsProvider, configuration);
endpointProvider_ = std::make_shared<EndpointProvider>(locationClient, configuration.regionId(), SERVICE_NAME, "videoenhan");
}
VideoenhanClient::VideoenhanClient(const std::string & accessKeyId, const std::string & accessKeySecret, const ClientConfiguration & configuration) :
RpcServiceClient(SERVICE_NAME, std::make_shared<SimpleCredentialsProvider>(accessKeyId, accessKeySecret), configuration)
{
auto locationClient = std::make_shared<LocationClient>(accessKeyId, accessKeySecret, configuration);
endpointProvider_ = std::make_shared<EndpointProvider>(locationClient, configuration.regionId(), SERVICE_NAME, "videoenhan");
}
VideoenhanClient::~VideoenhanClient()
{}
VideoenhanClient::AbstractEcommerceVideoOutcome VideoenhanClient::abstractEcommerceVideo(const AbstractEcommerceVideoRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return AbstractEcommerceVideoOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return AbstractEcommerceVideoOutcome(AbstractEcommerceVideoResult(outcome.result()));
else
return AbstractEcommerceVideoOutcome(outcome.error());
}
void VideoenhanClient::abstractEcommerceVideoAsync(const AbstractEcommerceVideoRequest& request, const AbstractEcommerceVideoAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, abstractEcommerceVideo(request), context);
};
asyncExecute(new Runnable(fn));
}
VideoenhanClient::AbstractEcommerceVideoOutcomeCallable VideoenhanClient::abstractEcommerceVideoCallable(const AbstractEcommerceVideoRequest &request) const
{
auto task = std::make_shared<std::packaged_task<AbstractEcommerceVideoOutcome()>>(
[this, request]()
{
return this->abstractEcommerceVideo(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
VideoenhanClient::AbstractFilmVideoOutcome VideoenhanClient::abstractFilmVideo(const AbstractFilmVideoRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return AbstractFilmVideoOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return AbstractFilmVideoOutcome(AbstractFilmVideoResult(outcome.result()));
else
return AbstractFilmVideoOutcome(outcome.error());
}
void VideoenhanClient::abstractFilmVideoAsync(const AbstractFilmVideoRequest& request, const AbstractFilmVideoAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, abstractFilmVideo(request), context);
};
asyncExecute(new Runnable(fn));
}
VideoenhanClient::AbstractFilmVideoOutcomeCallable VideoenhanClient::abstractFilmVideoCallable(const AbstractFilmVideoRequest &request) const
{
auto task = std::make_shared<std::packaged_task<AbstractFilmVideoOutcome()>>(
[this, request]()
{
return this->abstractFilmVideo(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
VideoenhanClient::AddFaceVideoTemplateOutcome VideoenhanClient::addFaceVideoTemplate(const AddFaceVideoTemplateRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return AddFaceVideoTemplateOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return AddFaceVideoTemplateOutcome(AddFaceVideoTemplateResult(outcome.result()));
else
return AddFaceVideoTemplateOutcome(outcome.error());
}
void VideoenhanClient::addFaceVideoTemplateAsync(const AddFaceVideoTemplateRequest& request, const AddFaceVideoTemplateAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, addFaceVideoTemplate(request), context);
};
asyncExecute(new Runnable(fn));
}
VideoenhanClient::AddFaceVideoTemplateOutcomeCallable VideoenhanClient::addFaceVideoTemplateCallable(const AddFaceVideoTemplateRequest &request) const
{
auto task = std::make_shared<std::packaged_task<AddFaceVideoTemplateOutcome()>>(
[this, request]()
{
return this->addFaceVideoTemplate(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
VideoenhanClient::AdjustVideoColorOutcome VideoenhanClient::adjustVideoColor(const AdjustVideoColorRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return AdjustVideoColorOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return AdjustVideoColorOutcome(AdjustVideoColorResult(outcome.result()));
else
return AdjustVideoColorOutcome(outcome.error());
}
void VideoenhanClient::adjustVideoColorAsync(const AdjustVideoColorRequest& request, const AdjustVideoColorAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, adjustVideoColor(request), context);
};
asyncExecute(new Runnable(fn));
}
VideoenhanClient::AdjustVideoColorOutcomeCallable VideoenhanClient::adjustVideoColorCallable(const AdjustVideoColorRequest &request) const
{
auto task = std::make_shared<std::packaged_task<AdjustVideoColorOutcome()>>(
[this, request]()
{
return this->adjustVideoColor(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
VideoenhanClient::ChangeVideoSizeOutcome VideoenhanClient::changeVideoSize(const ChangeVideoSizeRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return ChangeVideoSizeOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return ChangeVideoSizeOutcome(ChangeVideoSizeResult(outcome.result()));
else
return ChangeVideoSizeOutcome(outcome.error());
}
void VideoenhanClient::changeVideoSizeAsync(const ChangeVideoSizeRequest& request, const ChangeVideoSizeAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, changeVideoSize(request), context);
};
asyncExecute(new Runnable(fn));
}
VideoenhanClient::ChangeVideoSizeOutcomeCallable VideoenhanClient::changeVideoSizeCallable(const ChangeVideoSizeRequest &request) const
{
auto task = std::make_shared<std::packaged_task<ChangeVideoSizeOutcome()>>(
[this, request]()
{
return this->changeVideoSize(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
VideoenhanClient::ConvertHdrVideoOutcome VideoenhanClient::convertHdrVideo(const ConvertHdrVideoRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return ConvertHdrVideoOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return ConvertHdrVideoOutcome(ConvertHdrVideoResult(outcome.result()));
else
return ConvertHdrVideoOutcome(outcome.error());
}
void VideoenhanClient::convertHdrVideoAsync(const ConvertHdrVideoRequest& request, const ConvertHdrVideoAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, convertHdrVideo(request), context);
};
asyncExecute(new Runnable(fn));
}
VideoenhanClient::ConvertHdrVideoOutcomeCallable VideoenhanClient::convertHdrVideoCallable(const ConvertHdrVideoRequest &request) const
{
auto task = std::make_shared<std::packaged_task<ConvertHdrVideoOutcome()>>(
[this, request]()
{
return this->convertHdrVideo(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
VideoenhanClient::DeleteFaceVideoTemplateOutcome VideoenhanClient::deleteFaceVideoTemplate(const DeleteFaceVideoTemplateRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DeleteFaceVideoTemplateOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DeleteFaceVideoTemplateOutcome(DeleteFaceVideoTemplateResult(outcome.result()));
else
return DeleteFaceVideoTemplateOutcome(outcome.error());
}
void VideoenhanClient::deleteFaceVideoTemplateAsync(const DeleteFaceVideoTemplateRequest& request, const DeleteFaceVideoTemplateAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, deleteFaceVideoTemplate(request), context);
};
asyncExecute(new Runnable(fn));
}
VideoenhanClient::DeleteFaceVideoTemplateOutcomeCallable VideoenhanClient::deleteFaceVideoTemplateCallable(const DeleteFaceVideoTemplateRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DeleteFaceVideoTemplateOutcome()>>(
[this, request]()
{
return this->deleteFaceVideoTemplate(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
VideoenhanClient::EnhanceVideoQualityOutcome VideoenhanClient::enhanceVideoQuality(const EnhanceVideoQualityRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return EnhanceVideoQualityOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return EnhanceVideoQualityOutcome(EnhanceVideoQualityResult(outcome.result()));
else
return EnhanceVideoQualityOutcome(outcome.error());
}
void VideoenhanClient::enhanceVideoQualityAsync(const EnhanceVideoQualityRequest& request, const EnhanceVideoQualityAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, enhanceVideoQuality(request), context);
};
asyncExecute(new Runnable(fn));
}
VideoenhanClient::EnhanceVideoQualityOutcomeCallable VideoenhanClient::enhanceVideoQualityCallable(const EnhanceVideoQualityRequest &request) const
{
auto task = std::make_shared<std::packaged_task<EnhanceVideoQualityOutcome()>>(
[this, request]()
{
return this->enhanceVideoQuality(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
VideoenhanClient::EraseVideoLogoOutcome VideoenhanClient::eraseVideoLogo(const EraseVideoLogoRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return EraseVideoLogoOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return EraseVideoLogoOutcome(EraseVideoLogoResult(outcome.result()));
else
return EraseVideoLogoOutcome(outcome.error());
}
void VideoenhanClient::eraseVideoLogoAsync(const EraseVideoLogoRequest& request, const EraseVideoLogoAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, eraseVideoLogo(request), context);
};
asyncExecute(new Runnable(fn));
}
VideoenhanClient::EraseVideoLogoOutcomeCallable VideoenhanClient::eraseVideoLogoCallable(const EraseVideoLogoRequest &request) const
{
auto task = std::make_shared<std::packaged_task<EraseVideoLogoOutcome()>>(
[this, request]()
{
return this->eraseVideoLogo(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
VideoenhanClient::EraseVideoSubtitlesOutcome VideoenhanClient::eraseVideoSubtitles(const EraseVideoSubtitlesRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return EraseVideoSubtitlesOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return EraseVideoSubtitlesOutcome(EraseVideoSubtitlesResult(outcome.result()));
else
return EraseVideoSubtitlesOutcome(outcome.error());
}
void VideoenhanClient::eraseVideoSubtitlesAsync(const EraseVideoSubtitlesRequest& request, const EraseVideoSubtitlesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, eraseVideoSubtitles(request), context);
};
asyncExecute(new Runnable(fn));
}
VideoenhanClient::EraseVideoSubtitlesOutcomeCallable VideoenhanClient::eraseVideoSubtitlesCallable(const EraseVideoSubtitlesRequest &request) const
{
auto task = std::make_shared<std::packaged_task<EraseVideoSubtitlesOutcome()>>(
[this, request]()
{
return this->eraseVideoSubtitles(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
VideoenhanClient::GenerateVideoOutcome VideoenhanClient::generateVideo(const GenerateVideoRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return GenerateVideoOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return GenerateVideoOutcome(GenerateVideoResult(outcome.result()));
else
return GenerateVideoOutcome(outcome.error());
}
void VideoenhanClient::generateVideoAsync(const GenerateVideoRequest& request, const GenerateVideoAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, generateVideo(request), context);
};
asyncExecute(new Runnable(fn));
}
VideoenhanClient::GenerateVideoOutcomeCallable VideoenhanClient::generateVideoCallable(const GenerateVideoRequest &request) const
{
auto task = std::make_shared<std::packaged_task<GenerateVideoOutcome()>>(
[this, request]()
{
return this->generateVideo(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
VideoenhanClient::GetAsyncJobResultOutcome VideoenhanClient::getAsyncJobResult(const GetAsyncJobResultRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return GetAsyncJobResultOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return GetAsyncJobResultOutcome(GetAsyncJobResultResult(outcome.result()));
else
return GetAsyncJobResultOutcome(outcome.error());
}
void VideoenhanClient::getAsyncJobResultAsync(const GetAsyncJobResultRequest& request, const GetAsyncJobResultAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, getAsyncJobResult(request), context);
};
asyncExecute(new Runnable(fn));
}
VideoenhanClient::GetAsyncJobResultOutcomeCallable VideoenhanClient::getAsyncJobResultCallable(const GetAsyncJobResultRequest &request) const
{
auto task = std::make_shared<std::packaged_task<GetAsyncJobResultOutcome()>>(
[this, request]()
{
return this->getAsyncJobResult(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
VideoenhanClient::InterpolateVideoFrameOutcome VideoenhanClient::interpolateVideoFrame(const InterpolateVideoFrameRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return InterpolateVideoFrameOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return InterpolateVideoFrameOutcome(InterpolateVideoFrameResult(outcome.result()));
else
return InterpolateVideoFrameOutcome(outcome.error());
}
void VideoenhanClient::interpolateVideoFrameAsync(const InterpolateVideoFrameRequest& request, const InterpolateVideoFrameAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, interpolateVideoFrame(request), context);
};
asyncExecute(new Runnable(fn));
}
VideoenhanClient::InterpolateVideoFrameOutcomeCallable VideoenhanClient::interpolateVideoFrameCallable(const InterpolateVideoFrameRequest &request) const
{
auto task = std::make_shared<std::packaged_task<InterpolateVideoFrameOutcome()>>(
[this, request]()
{
return this->interpolateVideoFrame(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
VideoenhanClient::MergeVideoFaceOutcome VideoenhanClient::mergeVideoFace(const MergeVideoFaceRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return MergeVideoFaceOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return MergeVideoFaceOutcome(MergeVideoFaceResult(outcome.result()));
else
return MergeVideoFaceOutcome(outcome.error());
}
void VideoenhanClient::mergeVideoFaceAsync(const MergeVideoFaceRequest& request, const MergeVideoFaceAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, mergeVideoFace(request), context);
};
asyncExecute(new Runnable(fn));
}
VideoenhanClient::MergeVideoFaceOutcomeCallable VideoenhanClient::mergeVideoFaceCallable(const MergeVideoFaceRequest &request) const
{
auto task = std::make_shared<std::packaged_task<MergeVideoFaceOutcome()>>(
[this, request]()
{
return this->mergeVideoFace(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
VideoenhanClient::MergeVideoModelFaceOutcome VideoenhanClient::mergeVideoModelFace(const MergeVideoModelFaceRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return MergeVideoModelFaceOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return MergeVideoModelFaceOutcome(MergeVideoModelFaceResult(outcome.result()));
else
return MergeVideoModelFaceOutcome(outcome.error());
}
void VideoenhanClient::mergeVideoModelFaceAsync(const MergeVideoModelFaceRequest& request, const MergeVideoModelFaceAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, mergeVideoModelFace(request), context);
};
asyncExecute(new Runnable(fn));
}
VideoenhanClient::MergeVideoModelFaceOutcomeCallable VideoenhanClient::mergeVideoModelFaceCallable(const MergeVideoModelFaceRequest &request) const
{
auto task = std::make_shared<std::packaged_task<MergeVideoModelFaceOutcome()>>(
[this, request]()
{
return this->mergeVideoModelFace(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
VideoenhanClient::QueryFaceVideoTemplateOutcome VideoenhanClient::queryFaceVideoTemplate(const QueryFaceVideoTemplateRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return QueryFaceVideoTemplateOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return QueryFaceVideoTemplateOutcome(QueryFaceVideoTemplateResult(outcome.result()));
else
return QueryFaceVideoTemplateOutcome(outcome.error());
}
void VideoenhanClient::queryFaceVideoTemplateAsync(const QueryFaceVideoTemplateRequest& request, const QueryFaceVideoTemplateAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, queryFaceVideoTemplate(request), context);
};
asyncExecute(new Runnable(fn));
}
VideoenhanClient::QueryFaceVideoTemplateOutcomeCallable VideoenhanClient::queryFaceVideoTemplateCallable(const QueryFaceVideoTemplateRequest &request) const
{
auto task = std::make_shared<std::packaged_task<QueryFaceVideoTemplateOutcome()>>(
[this, request]()
{
return this->queryFaceVideoTemplate(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
VideoenhanClient::SuperResolveVideoOutcome VideoenhanClient::superResolveVideo(const SuperResolveVideoRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return SuperResolveVideoOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return SuperResolveVideoOutcome(SuperResolveVideoResult(outcome.result()));
else
return SuperResolveVideoOutcome(outcome.error());
}
void VideoenhanClient::superResolveVideoAsync(const SuperResolveVideoRequest& request, const SuperResolveVideoAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, superResolveVideo(request), context);
};
asyncExecute(new Runnable(fn));
}
VideoenhanClient::SuperResolveVideoOutcomeCallable VideoenhanClient::superResolveVideoCallable(const SuperResolveVideoRequest &request) const
{
auto task = std::make_shared<std::packaged_task<SuperResolveVideoOutcome()>>(
[this, request]()
{
return this->superResolveVideo(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
VideoenhanClient::ToneSdrVideoOutcome VideoenhanClient::toneSdrVideo(const ToneSdrVideoRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return ToneSdrVideoOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return ToneSdrVideoOutcome(ToneSdrVideoResult(outcome.result()));
else
return ToneSdrVideoOutcome(outcome.error());
}
void VideoenhanClient::toneSdrVideoAsync(const ToneSdrVideoRequest& request, const ToneSdrVideoAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, toneSdrVideo(request), context);
};
asyncExecute(new Runnable(fn));
}
VideoenhanClient::ToneSdrVideoOutcomeCallable VideoenhanClient::toneSdrVideoCallable(const ToneSdrVideoRequest &request) const
{
auto task = std::make_shared<std::packaged_task<ToneSdrVideoOutcome()>>(
[this, request]()
{
return this->toneSdrVideo(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
| 35.703704 | 214 | 0.787464 |
4252b1138e785857031adf5a59146588d37796ea | 5,448 | cc | C++ | chromeos/components/string_matching/prefix_matcher.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 575 | 2015-06-18T23:58:20.000Z | 2022-03-23T09:32:39.000Z | chromeos/components/string_matching/prefix_matcher.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | chromeos/components/string_matching/prefix_matcher.cc | Yannic/chromium | ab32e8aacb08c9fce0dc4bf09eec456ba46e3710 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 52 | 2015-07-14T10:40:50.000Z | 2022-03-15T01:11:49.000Z | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chromeos/components/string_matching/prefix_matcher.h"
#include "base/check.h"
#include "base/macros.h"
#include "chromeos/components/string_matching/tokenized_string.h"
#include "chromeos/components/string_matching/tokenized_string_char_iterator.h"
namespace chromeos {
namespace string_matching {
namespace {
// The factors below are applied when the current char of query matches
// the current char of the text to be matched. Different factors are chosen
// based on where the match happens. kIsPrefixMultiplier is used when the
// matched portion is a prefix of both the query and the text, which implies
// that the matched chars are at the same position in query and text. This is
// the most preferred case thus it has the highest score. When the current char
// of the query and the text does not match, the algorithm moves to the next
// token in the text and try to match from there. kIsFrontOfWordMultipler will
// be used if the first char of the token matches the current char of the query.
// Otherwise, the match is considered as weak and kIsWeakHitMultiplier is
// used.
// Examples:
// Suppose the text to be matched is 'Google Chrome'.
// Query 'go' would yield kIsPrefixMultiplier for each char.
// Query 'gc' would use kIsPrefixMultiplier for 'g' and
// kIsFrontOfWordMultipler for 'c'.
// Query 'ch' would use kIsFrontOfWordMultipler for 'c' and
// kIsWeakHitMultiplier for 'h'.
const double kIsPrefixMultiplier = 1.0;
const double kIsFrontOfWordMultipler = 0.8;
const double kIsWeakHitMultiplier = 0.6;
// A relevance score that represents no match.
const double kNoMatchScore = 0.0;
} // namespace
PrefixMatcher::PrefixMatcher(const TokenizedString& query,
const TokenizedString& text)
: query_iter_(query),
text_iter_(text),
current_match_(gfx::Range::InvalidRange()),
current_relevance_(kNoMatchScore) {}
bool PrefixMatcher::Match() {
while (!RunMatch()) {
// No match found and no more states to try. Bail out.
if (states_.empty()) {
current_relevance_ = kNoMatchScore;
current_hits_.clear();
return false;
}
PopState();
// Skip restored match to try other possibilities.
AdvanceToNextTextToken();
}
if (current_match_.IsValid())
current_hits_.push_back(current_match_);
return true;
}
PrefixMatcher::State::State() : relevance(kNoMatchScore) {}
PrefixMatcher::State::~State() = default;
PrefixMatcher::State::State(double relevance,
const gfx::Range& current_match,
const Hits& hits,
const TokenizedStringCharIterator& query_iter,
const TokenizedStringCharIterator& text_iter)
: relevance(relevance),
current_match(current_match),
hits(hits.begin(), hits.end()),
query_iter_state(query_iter.GetState()),
text_iter_state(text_iter.GetState()) {}
PrefixMatcher::State::State(const PrefixMatcher::State& state) = default;
bool PrefixMatcher::RunMatch() {
bool have_match_already = false;
while (!query_iter_.end() && !text_iter_.end()) {
if (query_iter_.Get() == text_iter_.Get()) {
PushState();
if (query_iter_.GetArrayPos() == text_iter_.GetArrayPos())
current_relevance_ += kIsPrefixMultiplier;
else if (text_iter_.IsFirstCharOfToken())
current_relevance_ += kIsFrontOfWordMultipler;
else
current_relevance_ += kIsWeakHitMultiplier;
if (!current_match_.IsValid())
current_match_.set_start(text_iter_.GetArrayPos());
current_match_.set_end(text_iter_.GetArrayPos() +
text_iter_.GetCharSize());
query_iter_.NextChar();
text_iter_.NextChar();
have_match_already = true;
} else {
// There are two possibilities here:
// 1. Need to AdvanceToNextTextToken() after having at least a match in
// current token (e.g. match the first character of the token) and the
// next character doesn't match.
// 2. Need to AdvanceToNextTextToken() because there is no match in
// current token.
// If there is no match in current token and we already have match (in
// previous tokens) before, a token is skipped and we consider this as no
// match.
if (text_iter_.IsFirstCharOfToken() && have_match_already)
return false;
AdvanceToNextTextToken();
}
}
return query_iter_.end();
}
void PrefixMatcher::AdvanceToNextTextToken() {
if (current_match_.IsValid()) {
current_hits_.push_back(current_match_);
current_match_ = gfx::Range::InvalidRange();
}
text_iter_.NextToken();
}
void PrefixMatcher::PushState() {
states_.push_back(State(current_relevance_, current_match_, current_hits_,
query_iter_, text_iter_));
}
void PrefixMatcher::PopState() {
DCHECK(!states_.empty());
State& last_match = states_.back();
current_relevance_ = last_match.relevance;
current_match_ = last_match.current_match;
current_hits_.swap(last_match.hits);
query_iter_.SetState(last_match.query_iter_state);
text_iter_.SetState(last_match.text_iter_state);
states_.pop_back();
}
} // namespace string_matching
} // namespace chromeos
| 35.607843 | 80 | 0.699523 |
425910854db17bb669017bdfa2a84c766c6bd3a7 | 4,533 | cc | C++ | layout_constants/layout_constants_pattern.cc | Sima214/esochrom | 5d000cf48b606135381b1211688c429dc307e8f2 | [
"BSD-2-Clause"
] | null | null | null | layout_constants/layout_constants_pattern.cc | Sima214/esochrom | 5d000cf48b606135381b1211688c429dc307e8f2 | [
"BSD-2-Clause"
] | null | null | null | layout_constants/layout_constants_pattern.cc | Sima214/esochrom | 5d000cf48b606135381b1211688c429dc307e8f2 | [
"BSD-2-Clause"
] | null | null | null | #include <fstream>
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <string>
extern "C" {
#define INI_IMPLEMENTATION
#include "ini.h"
}
static const char* CONFIG_NAME = "/.config/chromium/layout.ini";
#if defined(OS_MACOSX)
#define COCOA_LAYOUT_NAME "CocoaLayoutConstant"
static const char* COCOA_LAYOUT_LABELS[] = {
/* CocoaLayoutLabels */
};
#define COCOA_LAYOUT_LENGTH (sizeof(COCOA_LAYOUT_LABELS) / sizeof(char*))
#else
#define COCOA_LAYOUT_LENGTH 0
#endif
#define LAYOUT_NAME "LayoutConstant"
static const char* LAYOUT_LABELS[] = {
/* LayoutLabels */
};
#define LAYOUT_LENGTH (sizeof(LAYOUT_LABELS) / sizeof(char*))
#define LAYOUT_INSETS_NAME "LayoutInsets"
static const char* LAYOUT_INSETS_LABELS[] = {
/* LayoutInsetsLabels */
};
#define LAYOUT_INSETS_LENGTH (sizeof(LAYOUT_INSETS_LABELS) / sizeof(char*))
#define LAYOUT_TOTAL_LENGTH (COCOA_LAYOUT_LENGTH + LAYOUT_LENGTH + LAYOUT_INSETS_LENGTH)
static int loaded_layout[LAYOUT_TOTAL_LENGTH] = {};
#define INI_DO_SECTION(name, length, labels, offset) \
section = ini_find_section(ini, name, 0); \
if (section != INI_NOT_FOUND) { \
for (int i = 0; i < length; i++) { \
int index = ini_find_property(ini, section, labels[i], 0); \
if (index != INI_NOT_FOUND) { \
int value = std::atoi(ini_property_value(ini, section, index)); \
loaded_layout[offset + i] = value; \
} \
else { \
std::printf("LayoutConstants: Couldn't load `%s::%s`!", name, labels[i]); \
} \
} \
} \
else { \
std::printf("LayoutConstants: Couldn't find `%s` section!\n", name); \
}
static void load_layout_constants() {
std::string config_name(CONFIG_NAME);
std::string home_path(getenv("HOME"));
std::string final_path = home_path + config_name;
std::ifstream config(final_path.c_str(), std::ios::in);
if(config.good()) {
// Config file exists.
config.seekg(0, std::ios::end);
size_t filesize = config.tellg();
std::string contents(filesize, '\n');
config.seekg(0);
config.read(&contents[0], filesize);
config.close();
// Parse ini properties.
ini_t* ini = ini_load(contents.c_str(), NULL);
int section = INI_NOT_FOUND;
#if defined(OS_MACOSX)
// CocoaLayoutConstant
INI_DO_SECTION(COCOA_LAYOUT_NAME, COCOA_LAYOUT_LENGTH, COCOA_LAYOUT_LABELS, 0);
#endif
// LayoutConstant
INI_DO_SECTION(LAYOUT_NAME, LAYOUT_LENGTH, LAYOUT_LABELS, COCOA_LAYOUT_LENGTH);
// LayoutInsets
INI_DO_SECTION(LAYOUT_INSETS_NAME, LAYOUT_INSETS_LENGTH, LAYOUT_INSETS_LABELS, COCOA_LAYOUT_LENGTH + LAYOUT_LENGTH);
ini_destroy(ini);
} else {
std::printf("LayoutConstants: couldn't load %s\n", final_path.c_str());
return;
}
}
__attribute__((constructor))
static void init_layout_constants() {
std::fill_n(loaded_layout, LAYOUT_TOTAL_LENGTH, 16);
load_layout_constants();
}
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/layout_constants.h"
#include "base/logging.h"
#include "ui/base/material_design/material_design_controller.h"
#if defined(OS_MACOSX)
int GetCocoaLayoutConstant(LayoutConstant constant) {
size_t offset = 0;
switch (constant) {
/* CocoaLayoutConstant */
default:
return GetLayoutConstant(constant);
}
}
#endif
int GetLayoutConstant(LayoutConstant constant) {
size_t offset = COCOA_LAYOUT_LENGTH;
switch (constant) {
/* LayoutConstant */
default:
break;
}
NOTREACHED();
return 0;
}
gfx::Insets GetLayoutInsets(LayoutInset inset) {
size_t offset = COCOA_LAYOUT_LENGTH + LAYOUT_LENGTH;
switch (inset) {
/* LayoutInsets */
}
NOTREACHED();
return gfx::Insets();
}
| 33.828358 | 120 | 0.590117 |
425a0925749b56a4129bb1aa0bb244bc4080c218 | 2,543 | cc | C++ | src/app-framework/LookupHandler.cc | taless474/plexil1 | 0da24f0330404c41a695ea367bb760fb9c7ee8dd | [
"BSD-3-Clause"
] | 1 | 2022-03-30T20:16:43.000Z | 2022-03-30T20:16:43.000Z | src/app-framework/LookupHandler.cc | taless474/plexil1 | 0da24f0330404c41a695ea367bb760fb9c7ee8dd | [
"BSD-3-Clause"
] | null | null | null | src/app-framework/LookupHandler.cc | taless474/plexil1 | 0da24f0330404c41a695ea367bb760fb9c7ee8dd | [
"BSD-3-Clause"
] | null | null | null | /* Copyright (c) 2006-2021, Universities Space Research Association (USRA).
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Universities Space Research Association nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY USRA ``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 USRA 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.
*/
//
// Default methods for LookupHandler
//
#include "LookupHandler.hh"
#include "AdapterExecInterface.hh"
#include "Debug.hh"
#include "LookupReceiver.hh"
#include "State.hh"
namespace PLEXIL
{
bool LookupHandler::initialize()
{
return true;
}
void LookupHandler::lookupNow(const State &state, LookupReceiver * /* rcvr */)
{
debugMsg("LookupHandler:defaultLookupNow", ' ' << state);
}
void LookupHandler::setThresholds(const State &state, Real hi, Real lo)
{
debugMsg("LookupHandler:defaultSetThresholds",
' ' << state << " (Real) " << hi << "," << lo);
}
void LookupHandler::setThresholds(const State &state, Integer hi, Integer lo)
{
debugMsg("LookupHandler:defaultSetThresholds",
' ' << state << " (Integer) " << hi << "," << lo);
}
void LookupHandler::clearThresholds(const State &state)
{
debugMsg("LookupHandler:defaultClearThresholds", ' ' << state);
}
}
| 36.855072 | 80 | 0.714117 |
425b96f71cb7f3ec403821d7c11418ca6bf893b4 | 2,999 | hpp | C++ | include/libtorrent/aux_/websocket_tracker_connection.hpp | redchief/libtorrent | 42917790b1606b5ea0cf5385fde44536c7040a27 | [
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | include/libtorrent/aux_/websocket_tracker_connection.hpp | redchief/libtorrent | 42917790b1606b5ea0cf5385fde44536c7040a27 | [
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | include/libtorrent/aux_/websocket_tracker_connection.hpp | redchief/libtorrent | 42917790b1606b5ea0cf5385fde44536c7040a27 | [
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | /*
Copyright (c) 2019 Paul-Louis Ageneau
Copyright (c) 2020, Paul-Louis Ageneau
All rights reserved.
You may use, distribute and modify this code under the terms of the BSD license,
see LICENSE file.
*/
#ifndef TORRENT_WEBSOCKET_TRACKER_CONNECTION_HPP_INCLUDED
#define TORRENT_WEBSOCKET_TRACKER_CONNECTION_HPP_INCLUDED
#include "libtorrent/config.hpp"
#if TORRENT_USE_RTC
#include "libtorrent/aux_/rtc_signaling.hpp" // for rtc_offer and rtc_answer
#include "libtorrent/aux_/websocket_stream.hpp"
#include "libtorrent/error_code.hpp"
#include "libtorrent/io_context.hpp"
#include "libtorrent/peer_id.hpp"
#include "libtorrent/aux_/resolver_interface.hpp"
#include "libtorrent/aux_/tracker_manager.hpp" // for tracker_connection
#include "libtorrent/aux_/ssl.hpp"
#include <boost/beast/core/flat_buffer.hpp>
#include <map>
#include <memory>
#include <queue>
#include <tuple>
#include <variant>
#include <optional>
namespace libtorrent::aux {
struct tracker_answer
{
sha1_hash info_hash;
peer_id pid;
aux::rtc_answer answer;
};
struct TORRENT_EXTRA_EXPORT websocket_tracker_connection : tracker_connection
{
friend class tracker_manager;
websocket_tracker_connection(
io_context& ios
, tracker_manager& man
, tracker_request const& req
, std::weak_ptr<request_callback> cb);
~websocket_tracker_connection() override = default;
void start() override;
void close() override;
bool is_started() const;
bool is_open() const;
void queue_request(tracker_request req, std::weak_ptr<request_callback> cb);
void queue_answer(tracker_answer ans);
private:
std::shared_ptr<websocket_tracker_connection> shared_from_this()
{
return std::static_pointer_cast<websocket_tracker_connection>(
tracker_connection::shared_from_this());
}
void send_pending();
void do_send(tracker_request const& req);
void do_send(tracker_answer const& ans);
void do_read();
void on_timeout(error_code const& ec) override;
void on_connect(error_code const& ec);
void on_read(error_code ec, std::size_t bytes_read);
void on_write(error_code const& ec, std::size_t bytes_written);
void fail(operation_t op, error_code const& ec);
io_context& m_io_context;
ssl::context m_ssl_context;
std::shared_ptr<aux::websocket_stream> m_websocket;
boost::beast::flat_buffer m_read_buffer;
std::string m_write_data;
using tracker_message = std::variant<tracker_request, tracker_answer>;
std::queue<std::tuple<tracker_message, std::weak_ptr<request_callback>>> m_pending;
std::map<sha1_hash, std::weak_ptr<request_callback>> m_callbacks;
bool m_sending = false;
};
struct websocket_tracker_response {
sha1_hash info_hash;
std::optional<tracker_response> resp;
std::optional<aux::rtc_offer> offer;
std::optional<aux::rtc_answer> answer;
};
TORRENT_EXTRA_EXPORT std::variant<websocket_tracker_response, std::string>
parse_websocket_tracker_response(span<char const> message, error_code &ec);
}
#endif // TORRENT_USE_RTC
#endif // TORRENT_WEBSOCKET_TRACKER_CONNECTION_HPP_INCLUDED
| 27.263636 | 84 | 0.791931 |
425cb4ef757c75bd9497830c265e4ba465955905 | 1,577 | cpp | C++ | ch3/useEigen/hw.cpp | MrCocoaCat/slambook | 1eb2c3b081c6f668f342ae8d3fa536748bedc77d | [
"MIT"
] | 3 | 2018-02-13T05:39:05.000Z | 2019-06-15T17:35:25.000Z | ch3/useEigen/hw.cpp | MrCocoaCat/slambook | 1eb2c3b081c6f668f342ae8d3fa536748bedc77d | [
"MIT"
] | null | null | null | ch3/useEigen/hw.cpp | MrCocoaCat/slambook | 1eb2c3b081c6f668f342ae8d3fa536748bedc77d | [
"MIT"
] | 1 | 2018-12-21T13:59:20.000Z | 2018-12-21T13:59:20.000Z | //
// Created by liyubo on 12/15/17.
//
#include <iostream>
using namespace std;
#include <ctime>
// Eigen 部分
#include <Eigen/Core>
// 稠密矩阵的代数运算(逆,特征值等)
#include <Eigen/Dense>
#include"hw.h"
#define MATRIX_SIZE 50
void homework()
{
//作业
Eigen::MatrixXd matrix_A;
matrix_A = Eigen::MatrixXd::Random( 100, 100 );
Eigen::MatrixXd matrix_b;
matrix_b = Eigen::MatrixXd::Random( 100, 1 );
Eigen::MatrixXd x;
// cout << matrix_A << endl;
// cout << matrix_b << endl;
x = matrix_A.llt().solve(matrix_b); //llt Cholesky来解方程
/*******************时间比较*********************/
clock_t time_stt = clock();
x = matrix_A.colPivHouseholderQr().solve(matrix_b); //利用QR分解求解方程
cout <<"time use in Qr decomposition is " <<1000* (clock() - time_stt)/(double)CLOCKS_PER_SEC <<"ms" << endl;
time_stt = clock();
x = matrix_A.fullPivLu().solve(matrix_b); //LU
cout <<"time use in fullPivLu is " <<1000* (clock() - time_stt)/(double)CLOCKS_PER_SEC <<"ms" << endl;
time_stt = clock();
x = matrix_A.inverse()*matrix_b;; //利用求逆来解方程
cout <<"time use in normal inverse is " <<1000* (clock() - time_stt)/(double)CLOCKS_PER_SEC <<"ms" << endl;
time_stt = clock();
x = matrix_A.llt().solve(matrix_b); //llt Cholesky来解方程
cout <<"time use in llt(Cholesky) is " <<1000* (clock() - time_stt)/(double)CLOCKS_PER_SEC <<"ms" << endl;
time_stt = clock();
x = matrix_A.ldlt().solve(matrix_b); //ldlt
cout <<"time use in ldlt is " <<1000* (clock() - time_stt)/(double)CLOCKS_PER_SEC <<"ms"<< endl;
}
| 28.672727 | 114 | 0.608751 |