blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 986
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 23
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 145
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 122
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
366251a53bd473d15b3305aa878b3d6d51bee819 | 6ac96a57f2d6e1f1fca264209b76811909df8681 | /cf/526/b.cpp | 4cd92e724e73e505179d672e0709fb8ef001c62e | [] | no_license | SBidaibek/acm | ac85ca9b5ae158113e95c3d851c76c61ccd04c6f | b358a79f8753d2c3f9888ab8a5b22b0ec25d15db | refs/heads/master | 2020-04-22T17:19:43.625322 | 2019-02-15T06:22:14 | 2019-02-15T06:22:14 | 170,537,539 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,299 | cpp | #include <bits/stdc++.h>
using namespace std;
#define forn(i, x, n) for (int i = int(x); i <= int(n); ++i)
#define for1(i, n, x) for (int i = int(n); i >= int(x); --i)
#define F first
#define S second
#define pb push_back
typedef long long ll;
typedef pair <int, int> pii;
typedef pair <ll, ll> pll;
typedef double ld;
typedef vector <int> vi;
const int N = 3e5 + 10;
const ll INF = 1e18;
const int B = 1e9 + 7;
int main() {
#ifdef black
freopen("in", "r", stdin);
#endif // black
ios_base :: sync_with_stdio(0);
cin.tie(0);
ll n, k;
cin >> n >> k;
string a, b;
cin >> a >> b;
if (a == b || k == 1) {
cout << n << "\n";
return 0;
}
ll ans = 0;
ll cur = 0;
ll free = 0;
int i = 0;
while (a[i] == b[i]) ++i;
ans = i + 2, k -= 2, cur = 2;
forn(j, i + 1, n - 1) {
if (k == 0) {
ans += ((n - 1) - j + 1) * cur;
break;
}
ans += cur;
ll sides = (a[j] != 'b') + (b[j] != 'a');
//ll new_free = free * 2 + sides;
ll add = min(k, free + sides);
ans += add;
cur += add;
k -= add;
free += free + sides;
}
cout << ans << "\n";
return 0;
}
| [
"sanzhar.bidaibek@gmail.com"
] | sanzhar.bidaibek@gmail.com |
2335c4db417e44903e6fd265f9361eb2258c67e2 | d87b74caa36c207a10e4340ca91bc93a6a0e3384 | /src/Popo/BaseItem.h | 351949a2171cb592ccf5e910e387870691ae58cb | [
"Unlicense"
] | permissive | yangzhiming/popo | aeb82a1cad13ccb40358fbcaa8847a33c77516f7 | 598b93befa2f00214b6d236050048d7da231443f | refs/heads/master | 2020-05-31T16:47:27.514938 | 2013-09-26T09:33:32 | 2013-09-26T09:33:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 272 | h | #ifndef _BASE_ITEM_H_
#define _BASE_ITEM_H_
class BaseItem
{
public:
BaseItem(void) {}
virtual ~BaseItem(void) {}
virtual void Draw(Graphics* pGraph) = 0;
virtual BaseItem* Clone() = 0;
virtual void Update(float fDelta) = 0;
};
#endif //_BASE_ITEM_H_ | [
"yzmforever@163.com"
] | yzmforever@163.com |
c7f58301e3046e7f513284722fd7255473dcd422 | 7002f9baf2a838a4d148b1df221b2fb2dbcbcaaf | /Simulator/srSimulator/Systems/NAO/Ball.cpp | c879820d4061831bd9e7e2413a9beceea231a0bf | [] | no_license | jainajinkya/Sejong_Dynamic_Control_Toolkit | 7edfd69696408a19fe95f4a5594e2767d25cc97e | 811d4ff64b89a06f6a8e1cc9dcf851163c8f06e1 | refs/heads/master | 2021-08-14T23:02:50.910091 | 2017-11-16T23:42:21 | 2017-11-16T23:42:21 | 111,034,351 | 0 | 0 | null | 2017-11-16T23:35:41 | 2017-11-16T23:35:41 | null | UTF-8 | C++ | false | false | 863 | cpp | #include "Ball.h"
Ball::Ball(double x, double y, double z, double d, double mass, double rest){
for( int i(0); i<NUM_BALL; ++i){
ball_.GetGeomInfo().SetShape(srGeometryInfo::SPHERE);
ball_.GetGeomInfo().SetColor(0.324f, 0.12f, 0.12f);
ball_.GetGeomInfo().SetDimension(d, 0.0, 0.0);
ball_.SetFriction(0.1);
ball_.SetDamping(0.001);
ball_.SetRestitution(rest);
}
ball_.m_Inertia.SetMass(mass);
ball_.SetFrame(EulerZYX(Vec3(0.0, 0.0, 0.0), Vec3(x, y, z) ) );
// Collision
for (int i(0); i<NUM_BALL; ++i){
collision_.GetGeomInfo().SetShape(ball_.GetGeomInfo().GetShape());
collision_.GetGeomInfo().SetDimension(ball_.GetGeomInfo().GetDimension());
ball_.AddCollision(& collision_);
}
this->SetBaseLink(&ball_);
this->SetBaseLinkType(srSystem::DYNAMIC);
}
| [
"dk6587@utexas.edu"
] | dk6587@utexas.edu |
ff91b99f8604bfd42c435ff1dad0b19007c256ce | 2b7607fa78bf83b2515b9de2f9b40d15c81c2ab2 | /Examples/include/CheckTopology.h | 4f4412b548660a949e73a9d88f29b28a01474336 | [
"Apache-2.0"
] | permissive | ANTsX/ANTs | 3176341b8de664939eafde3e1ebf8c449809a9dd | dfd9e6664f2fc5f0dbd05c6c23d5e4895e82abee | refs/heads/master | 2023-08-24T20:43:33.986495 | 2023-08-08T18:23:45 | 2023-08-08T18:23:45 | 7,777,650 | 899 | 286 | Apache-2.0 | 2023-09-10T18:38:59 | 2013-01-23T15:43:41 | C++ | UTF-8 | C++ | false | false | 304 | h |
#ifndef CHECKTOPOLOGY_H
#define CHECKTOPOLOGY_H
namespace ants
{
extern int
CheckTopology(std::vector<std::string>, // equivalent to argv of command line parameters to main()
std::ostream * out_stream // [optional] output stream to write
);
} // namespace ants
#endif // CHECKTOPOLOGY_H
| [
"hans-johnson@uiowa.edu"
] | hans-johnson@uiowa.edu |
2f8490aaa091d7ece7860b51ab82932c3849068f | 9eaee5c68f53ee3749167fb8d941f6d4d841ba9e | /Editor/QStringAndQVariant.h | c6f52b06d37fd5ce32206049fd9f42931de69e76 | [] | no_license | 0xlitf/Editor | ad78293b27a198b1699c0f0ae5b062e8fe772c7e | 61baaf8fcf2f516eb2b2e66970dcddb1bc421f69 | refs/heads/master | 2023-05-24T02:39:01.996225 | 2016-01-02T17:00:25 | 2016-01-02T17:00:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 353 | h | #ifndef QStringAndQVariant_h__
#define QStringAndQVariant_h__
#include <QString>
#include <QVariant>
class QStringAndQVariant
{
public:
QStringAndQVariant(void);
~QStringAndQVariant(void);
static QVariant stringToVariant(QVariant::Type type, const QString &);
static QString vairantToString(const QVariant &);
};
#endif // QStringAndQVariant_h__
| [
"calciferlorain@gmail.com"
] | calciferlorain@gmail.com |
2a077ac5955bfbbd79cc1fc6f8689c4346073803 | e7810ab9687b6e929eb081f4e50e4fec43330b8a | /fit_curve/fit_curve.cpp | 9ab000802a0e92109edf835f2c194f5ac00c66fb | [] | no_license | marcel1hruska/fit_curve | a0a28167ed8f9761ce6e46bfd8f33b77ff49ac77 | d4435f82877972f6957ab5200a6d8de819434e7f | refs/heads/master | 2020-09-13T14:29:50.308480 | 2019-11-20T00:32:43 | 2019-11-20T00:32:43 | 222,816,672 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,959 | cpp | /*
C++ implementation of
An Algorithm for Automatically Fitting Digitized Curves
by Philip J. Schneider
from "Graphics Gems", Academic Press, 1990
*/
#include<string>
#include<iostream>
#include<cmath>
#include"fit_curve.h"
#define MAXPOINTS 1000
using namespace std;
/*
* FitCurve :
* Fit a Bezier curve to a set of points.
*/
vector<BezierCurve> FitCurve(vector<cv::Point2d> const& d, int startIndex, int endIndex, double error)
{
if (error <= 0.0) throw "error value must be greater than 0.0";
cv::Point2d tHat1, tHat2; // Unit tangent vectors at endpoints.
vector<BezierCurve> bezCurves; // The vector that will store the BezierCurve
// values to be returned once the curve fitting
// is complete.
// if startIndex is the beginning of the curve.
tHat1 = computeLeftTangent(d, startIndex);
// if endIndex is the end of the curve.
tHat2 = computeRightTangent(d, endIndex - 1);
FitCubic(d, &bezCurves, startIndex, endIndex - 1, tHat1, tHat2, error);
return bezCurves;
}
void addBezierCurve(vector<cv::Vec2d> const& bezCurve, vector<BezierCurve>* bezCurves)
{
// add curve to an array of curves which will then be returned on FitCurve.
BezierCurve newBezier;
newBezier.pt1 = bezCurve[0];
newBezier.pt2 = bezCurve[3];
newBezier.c1 = bezCurve[1];
newBezier.c2 = bezCurve[2];
bezCurves->push_back(newBezier);
}
/*
* FitCubic :
* Fit a Bezier curve to a (sub)set of points
*/
void FitCubic(vector<cv::Point2d> const& d, vector<BezierCurve>* bezCurves,
int first, int last, cv::Vec2d tHat1, cv::Vec2d tHat2, double error)
{
// Control points of fitted Bezier curve;
vector<cv::Vec2d> bezCurve(4);
// Parameter values for point
vector<double>* u = new vector<double>(last - first + 1);
// Improved parameter values
vector<double>* uPrime = new vector<double>(last - first + 1);
double maxError; // Maximum fitting error
int splitPoint; // Point to split point set at
int nPts; // Number of points in subset
double iterationError; // Error below which you try iterating
int maxIterations = 20; // Max times to try iterating
cv::Point2d tHatCenter; // Unit tangent vector at splitPoint
int i;
iterationError = error * error;
nPts = last - first + 1;
if (nPts == 1)
{
cout << "Only have 1 point, so no fitting" << endl;
return;
}
// Use heuristic if region only has two points in it
if (nPts == 2)
{
double dist = getDistance(d[last], d[first]) / 3.0;
bezCurve[0] = d[first];
bezCurve[3] = d[last];
bezCurve[1] = bezCurve[0] + scaleVec(tHat1, dist);
bezCurve[2] = bezCurve[3] + scaleVec(tHat2, dist);
addBezierCurve(bezCurve, bezCurves);
cout << "Fit 2 Points, use heuristic" << endl;
return;
}
// Parameterize points, and attempt to fit curve
chordLengthParameterize(d, first, last, u);
generateBezier(d, &bezCurve, first, last, *u, tHat1, tHat2);
// Find max deviation of points to fitted curve
maxError = computeMaxError(d, first, last, &bezCurve, *u, &splitPoint);
//cout << maxError << endl;
//cout << splitPoint << endl;
if (maxError < error) {
addBezierCurve(bezCurve, bezCurves);
return;
}
// If error not too large, try some reparameterization
// and iteration
if (maxError < iterationError) {
for (i = 0; i < maxIterations; ++i) {
uPrime = reparameterize(d, first, last, *u, &bezCurve);
generateBezier(d, &bezCurve, first, last, *uPrime, tHat1, tHat2);
maxError = computeMaxError(d, first, last, &bezCurve, *uPrime, &splitPoint);
if (maxError < error) {
addBezierCurve(bezCurve, bezCurves);
return;
}
u = uPrime;
}
}
// Fitting failed -- split at max error point and fit recursively
tHatCenter = computeCenterTangent(d, splitPoint);
FitCubic(d, bezCurves, first, splitPoint, tHat1, tHatCenter, error);
FitCubic(d, bezCurves, splitPoint, last, -tHatCenter, tHat2, error);
}
void generateBezier(vector<cv::Point2d> const& d, vector<cv::Vec2d>* bezCurve,
int first, int last, vector<double> const& uPrime, cv::Vec2d tHat1, cv::Vec2d tHat2)
{
cv::Vec2d A[MAXPOINTS][2]; // Precomputed rhs for eqn
int nPts; // Number of pts in sub-curve
double C[2][2]; // Matrix C
double X[2]; // Matrix X
double det_C0_C1, det_C0_X, det_X_C1; // Determinants of matrices
double alpha_l, alpha_r; // Alpha values, left and right
cv::Point2d tmp; // Utility variable
nPts = last - first + 1;
// Compute the A
for (int i = 0; i < nPts; ++i)
{
cv::Vec2d v1, v2;
v1 = scaleVec(tHat1, B1(uPrime[i]));
v2 = scaleVec(tHat2, B2(uPrime[i]));
A[i][0] = v1;
A[i][1] = v2;
}
// Create the C and X matrices
C[0][0] = 0.0;
C[0][1] = 0.0;
C[1][0] = 0.0;
C[1][1] = 0.0;
X[0] = 0.0;
X[1] = 0.0;
for (int i = 0; i < nPts; i++) {
C[0][0] += A[i][0].dot(A[i][0]);
C[0][1] += A[i][0].dot(A[i][1]);
C[1][0] = C[0][1];
C[1][1] += A[i][1].dot(A[i][1]);
tmp = (d[first + i]) -
((d[first] * B0(uPrime[i])) +
((d[first] * B1(uPrime[i])) +
((d[last] * B2(uPrime[i])) +
(d[last] * B3(uPrime[i])))));
X[0] += A[i][0].dot(tmp);
X[1] += A[i][1].dot(tmp);
}
// Compute the determinants of C and X
det_C0_C1 = C[0][0] * C[1][1] - C[1][0] * C[0][1];
det_C0_X = C[0][0] * X[1] - C[1][0] * X[0];
det_X_C1 = X[0] * C[1][1] - X[1] * C[0][1];
// Finally, derive alpha values
alpha_l = (det_C0_C1 == 0) ? 0.0 : det_X_C1 / det_C0_C1;
alpha_r = (det_C0_C1 == 0) ? 0.0 : det_C0_X / det_C0_C1;
// Checks for "dangerous" points, meaning that the alpha_l or alpha_r are abnormally large
// from here http://newsgroups.derkeiler.com/Archive/Comp/comp.graphics.algorithms/2005-08/msg00419.html
// This is a common problem with this algoithm.
double dif1 = getDistance(d[first], d[last]);
bool danger = false;
if ((alpha_l > dif1 * 2) || (alpha_r > dif1 * 2)) {
first += 0;
danger = true;
}
// If alpha negative, use the Wu/Barsky heuristic (see text)
// (if alpha is 0, you get coincident control points that lead to
// divide by zero in any subsequent NewtonRaphsonRootFind() call.
double segLength = getDistance(d[first], d[last]);
double epsilon = 1.0e-6 * segLength;
if (alpha_l < epsilon || alpha_r < epsilon || danger)
{
// fall back on standard (probably inaccurate) formula, and subdivide further if needed.
double dist = segLength / 3.0;
bezCurve->at(0) = d[first];
bezCurve->at(3) = d[last];
bezCurve->at(1) = bezCurve->at(0) + scaleVec(tHat1, dist);
bezCurve->at(2) = bezCurve->at(3) + scaleVec(tHat2, dist);
return; //bezCurve;
}
// First and last control points of the Bezier curve are
// positioned exactly at the first and last data points
// Control points 1 and 2 are positioned an alpha distance out
// on the tangent vectors, left and right, respectively
bezCurve->at(0) = d[first];
bezCurve->at(3) = d[last];
bezCurve->at(1) = bezCurve->at(0) + scaleVec(tHat1, alpha_l);
bezCurve->at(2) = bezCurve->at(3) + scaleVec(tHat2, alpha_r);
}
/*
* Reparameterize:
* Given set of points and their parameterization, try to find
* a better parameterization.
*/
vector<double>* reparameterize(vector<cv::Point2d> const& d, int first, int last, vector<double> const& u, vector<cv::Vec2d>* bezCurve)
{
int nPts = last - first + 1;
vector<double>* uPrime = new vector<double>(nPts); // New parameter values
for (int i = first; i <= last; i++) {
uPrime->at(i - first) = newtonRaphsonRootFind(*bezCurve, d[i], u.at(i - first));
}
return uPrime;
}
/*
* NewtonRaphsonRootFind :
* Use Newton-Raphson iteration to find better root.
*/
double newtonRaphsonRootFind(vector<cv::Vec2d> const& Q, cv::Point2d P, double u)
{
double numerator, denominator;
vector<cv::Vec2d> Q1(3), Q2(2); // Q' and Q''
cv::Vec2d Q_u, Q1_u, Q2_u; // u evaluated at Q, Q', & Q''
double uPrime; // Improved u
// Compute Q(u)
Q_u = bezierII(3, Q, u);
// Generate control vertices for Q'
for (int i = 0; i <= 2; i++) {
Q1[i][0] = (Q[i + 1][0] - Q[i][0]) * 3.0;
Q1[i][1] = (Q[i + 1][1] - Q[i][1]) * 3.0;
}
// Generate control vertices for Q''
for (int i = 0; i <= 1; i++) {
Q2[i][0] = (Q1[i + 1][0] - Q1[i][0]) * 2.0;
Q2[i][1] = (Q1[i + 1][1] - Q1[i][1]) * 2.0;
}
// Compute Q'(u) and Q''(u)
Q1_u = bezierII(2, Q1, u);
Q2_u = bezierII(1, Q2, u);
// Compute f(u)/f'(u)
numerator = (Q_u[0] - P.x) * (Q1_u[0]) + (Q_u[1] - P.y) * (Q1_u[1]);
denominator = (Q1_u[0]) * (Q1_u[0]) + (Q1_u[1]) * (Q1_u[1]) +
(Q_u[0] - P.x) * (Q2_u[0]) + (Q_u[1] - P.y) * (Q2_u[1]);
if (denominator == 0.0) return u;
// u = u - f(u)/f'(u)
uPrime = u - (numerator / denominator);
return (uPrime);
}
/*
* Bezier :
* Evaluate a Bezier curve at a particular parameter value
*/
cv::Point2d bezierII(int degree, vector<cv::Vec2d> const& V, double t)
{
cv::Point2d Q; // Point on curve at parameter t
cv::Vec2d* Vtemp; // Local copy of control points
// copy array
Vtemp = new cv::Vec2d[degree + 1];
for (int i = 0; i <= degree; ++i)
{
Vtemp[i] = V[i];
}
// Triangle computation
for (int i = 1; i <= degree; i++) {
for (int j = 0; j <= degree - i; j++) {
Vtemp[j][0] = (1.0 - t) * Vtemp[j][0] + t * Vtemp[j + 1][0];
Vtemp[j][1] = (1.0 - t) * Vtemp[j][1] + t * Vtemp[j + 1][1];
}
}
Q = Vtemp[0];
return Q;
}
/*
* B0, B1, B2, B3 :
* Bezier multipliers
*/
double B0(double u)
{
double tmp = 1.0 - u;
return (tmp * tmp * tmp);
}
double B1(double u)
{
double tmp = 1.0 - u;
return (3 * u * (tmp * tmp));
}
double B2(double u)
{
double tmp = 1.0 - u;
return (3 * u * u * tmp);
}
double B3(double u)
{
return (u * u * u);
}
/*
* ComputeLeftTangent, ComputeRightTangent, ComputeCenterTangent :
* Approximate unit tangents at endpoints and "center" of the curve.
*/
cv::Vec2d computeLeftTangent(vector<cv::Point2d> const& d, int end)
{
cv::Vec2d tHat1;
if (end == 0)
{
tHat1 = d[end + 1] - d[end];
}
else {
tHat1 = d[end + 1] - d[end - 1];
}
cv::normalize(tHat1, tHat1);
return tHat1;
}
cv::Vec2d computeRightTangent(vector<cv::Point2d> const& d, int end)
{
cv::Vec2d tHat2;
if (end == d.size() - 1)
{
tHat2 = d[end - 1] - d[end];
}
else {
tHat2 = d[end - 1] - d[end + 1];
}
cv::normalize(tHat2, tHat2);
return tHat2;
}
cv::Vec2d computeCenterTangent(vector<cv::Point2d> const& d, int center)
{
cv::Vec2d V1, V2, tHatCenter;
V1 = d[center - 1] - d[center];
V2 = d[center] - d[center + 1];
tHatCenter[0] = (V1[0] + V2[0]) / 2.0;
tHatCenter[1] = (V1[1] + V2[1]) / 2.0;
cv::normalize(tHatCenter, tHatCenter);
return tHatCenter;
}
/*
* ChordLengthParameterize :
* Assign parameter values to points
* using relative distances between points.
*/
void chordLengthParameterize(vector<cv::Point2d> const& d, int first, int last, vector<double>* u)
{
int i;
u->at(0) = 0.0;
for (i = first + 1; i <= last; ++i)
{
u->at(i - first) = u->at(i - first - 1) + getDistance(d[i], d[i - 1]);
}
for (i = first + 1; i <= last; ++i)
{
u->at(i - first) = u->at(i - first) / u->at(last - first);
}
}
/*
* ComputeMaxError :
* Find the maximum squared distance of digitized points
* to fitted curve.
*/
double computeMaxError(vector<cv::Point2d> const& d, int first, int last,
vector<cv::Vec2d>* bezCurve, vector<double> const& u, int* splitPoint)
{
double maxDist; // Maximum error
double dist; // Current error
cv::Point2d P; // Point on curve
cv::Vec2d v; // Vector from point to curve
*splitPoint = (last - first + 1) / 2;
maxDist = 0.0;
for (int i = first + 1; i < last; ++i)
{
P = bezierII(3, *bezCurve, u[i - first]);
v = P - d[i];
dist = v[0] * v[0] + v[1] * v[1];
if (dist >= maxDist)
{
maxDist = dist;
*splitPoint = i;
}
}
return (maxDist);
}
double getDistance(cv::Point2d p0, cv::Point p1)
{
double dx = p0.x - p1.x;
double dy = p0.y - p1.y;
return sqrt(dx * dx + dy * dy);
}
cv::Vec2d scaleVec(cv::Vec2d v, double newlen)
{
double len = sqrt(v[0] * v[0] + v[1] * v[1]);
if (len != 0.0)
{
v[0] *= newlen / len;
v[1] *= newlen / len;
}
return v;
} | [
"marcel1hruska@gmail.com"
] | marcel1hruska@gmail.com |
e2e15ca8627308286c8d64b12ceddc88fa85d655 | 5b80db0924330e5d76618662421d0bcac07af132 | /src/optimization/LocalCompression.cpp | 1e48be499d833af0d45101a28670990b785427b1 | [
"MIT"
] | permissive | Mookel/VC4C | 25129e2260c3ae5cdbdc92e8dc0f392fc3118a30 | d72978253820e4175fa591206dedda6c586068b3 | refs/heads/master | 2023-06-07T10:43:58.594891 | 2021-06-21T15:20:13 | 2021-06-21T15:20:24 | 357,043,822 | 0 | 0 | MIT | 2021-04-12T03:20:39 | 2021-04-12T03:20:39 | null | UTF-8 | C++ | false | false | 5,083 | cpp | /*
* Author: doe300
*
* See the file "LICENSE" for the full license governing this code.
*/
#include "LocalCompression.h"
#include "../InstructionWalker.h"
#include "../Method.h"
#include "../intermediate/VectorHelper.h"
#include "../intermediate/operators.h"
#include "CompilationError.h"
#include "log.h"
#include <string>
#include <vector>
using namespace vc4c;
using namespace vc4c::optimizations;
using namespace vc4c::operators;
static const std::vector<BuiltinLocal::Type> workGroupLocalNames = {BuiltinLocal::Type::LOCAL_IDS,
BuiltinLocal::Type::LOCAL_SIZES, BuiltinLocal::Type::GROUP_ID_X, BuiltinLocal::Type::GROUP_ID_Y,
BuiltinLocal::Type::GROUP_ID_Z, BuiltinLocal::Type::NUM_GROUPS_X, BuiltinLocal::Type::NUM_GROUPS_Y,
BuiltinLocal::Type::NUM_GROUPS_Z, BuiltinLocal::Type::GLOBAL_OFFSET_X, BuiltinLocal::Type::GLOBAL_OFFSET_Y,
BuiltinLocal::Type::GLOBAL_OFFSET_Z, BuiltinLocal::Type::WORK_DIMENSIONS, BuiltinLocal::Type::GLOBAL_DATA_ADDRESS};
static NODISCARD InstructionWalker compressLocalWrite(
Method& method, InstructionWalker it, const BuiltinLocal& local, const Local& container, unsigned char index)
{
CPPLOG_LAZY(logging::Level::DEBUG,
log << "Compressing write of local '" << local.name << "' into container '" << container.name
<< "' at position " << index << " at: " << it->to_string() << logging::endl);
if(auto source = it->getMoveSource())
{
// directly use the source of the assignment and insert it into vector
it = intermediate::insertVectorInsertion(
it, method, container.createReference(), Value(SmallImmediate(index), TYPE_INT8), *source);
it.erase();
return it;
}
if(auto op = it.get<intermediate::Operation>())
{
if(op->writesLocal(&local) && op->readsLocal(&local) && op->readsLiteral() && !op->hasSideEffects() &&
!op->hasConditionalExecution())
{
// replace local with index in container and make calculation only applicable for this index, e.g. for
// work-group loop group-id increment
auto cond = assignNop(it) = selectSIMDElement(index);
op->replaceLocal(&local, &container, LocalUse::Type::BOTH);
op->setCondition(cond);
it.nextInBlock();
return it;
}
}
const Value tmp = method.addNewLocal(local.type);
it->replaceLocal(&local, tmp.local(), LocalUse::Type::WRITER);
it.nextInBlock();
return intermediate::insertVectorInsertion(
it, method, container.createReference(), Value(SmallImmediate(index), TYPE_INT8), tmp);
}
static NODISCARD InstructionWalker compressLocalRead(
Method& method, InstructionWalker it, const BuiltinLocal& local, const Local& container, unsigned char index)
{
CPPLOG_LAZY(logging::Level::DEBUG,
log << "Compressing read of local '" << local.name << "' from container '" << container.name << "' at position "
<< index << " at: " << it->to_string() << logging::endl);
const Value tmp = method.addNewLocal(local.type);
it = intermediate::insertVectorExtraction(
it, method, container.createReference(), Value(SmallImmediate(index), TYPE_INT8), tmp);
it->replaceLocal(&local, tmp.local(), LocalUse::Type::READER);
return it;
}
static void compressLocalIntoRegister(
Method& method, const BuiltinLocal& local, const Local& container, unsigned char index)
{
if(index > 15)
throw CompilationError(CompilationStep::OPTIMIZER, "Container index out of bounds", std::to_string(index));
if(local.type.getVectorWidth() != 1)
throw CompilationError(CompilationStep::OPTIMIZER, "Can't compress local of vector-type: ", local.to_string());
// TODO most efficient way of finding iterator for instruction?
for(BasicBlock& bb : method)
{
auto it = bb.walk();
while(!it.isEndOfBlock())
{
if(it.get() && it->writesLocal(&local))
// replace all writes with write to container at given position
it = compressLocalWrite(method, it, local, container, index);
else if(it.get() && it->readsLocal(&local))
// replace all reads with reads of container at given position
it = compressLocalRead(method, it, local, container, index);
else
it.nextInBlock();
}
}
}
bool optimizations::compressWorkGroupLocals(const Module& module, Method& method, const Configuration& config)
{
if(method.empty() || method.begin()->empty())
return false;
unsigned char index = 0;
const Value container = method.addNewLocal(TYPE_INT32.toVectorType(16), "%work_group_info");
method.begin()->walk().nextInBlock().emplace(new intermediate::MoveOperation(container, INT_ZERO));
for(auto type : workGroupLocalNames)
{
if(auto local = method.findBuiltin(type))
{
compressLocalIntoRegister(method, *local, *container.local(), index);
++index;
}
}
return false;
}
| [
"stadeldani@web.de"
] | stadeldani@web.de |
46927eca55c611b623381ae689653f629aecf300 | 1b1114a96b826f8d1de0eafca1e38db57d4ff7c7 | /src/algorithm/deimosV1.cpp | 3bf4c7d7fe67b06079e7e53f7647a2b48c8e0de9 | [
"MIT"
] | permissive | TheSonOfDeimos/network-routing-optimization | beb0d19c7020ca106a02e23406daf28c97bc1406 | 7030b5cf333f19ab68952b6841463f4cfd664895 | refs/heads/main | 2023-05-08T01:02:08.619010 | 2021-06-05T20:47:44 | 2021-06-05T20:47:44 | 341,121,037 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,101 | cpp | #include "deimosV1.hpp"
#include "types.hpp"
DeimosV1::DeimosV1(int maxPathLength, double reqSpeed, double reqPacketloss, double reqPing)
: m_maxPathLength(maxPathLength),
m_reqSpeed(reqSpeed),
m_reqPacketloss(reqPacketloss),
m_reqPing(reqPing)
{
}
status_t DeimosV1::adoptStartMatrix(ConnectMatrix_t &startMatrix)
{
status_t status = ERROR_OK;
for (auto &line : startMatrix)
{
for (auto &element : line.second)
{
EXIT_IF(element.second.cost != -1, ERROR_LOGIC);
element.second.cost = 0;
}
}
exit:
return status;
}
status_t DeimosV1::isPathPossible(hostAddress_t startLineAddr, const std::pair<hostAddress_t, Cell> &startElement, hostAddress_t prevLineAddr, const std::pair<hostAddress_t, Cell> &prevElement)
{
status_t status = ERROR_RESULT_TRUE;
EXIT_IF(prevLineAddr == prevElement.first, ERROR_RESULT_FALSE);
EXIT_IF(prevLineAddr == startElement.first && prevElement.first == startLineAddr, ERROR_RESULT_FALSE);
EXIT_IF(prevElement.second.path.back() != startElement.second.path.front(), ERROR_LOGIC);
// Check req
EXIT_IF(prevElement.second.path.size() >= static_cast<std::size_t>(m_maxPathLength), ERROR_RESULT_FALSE);
{
double expSpeed = std::min(startElement.second.speed, prevElement.second.speed);
double expPacketLoss = (1 - ((100 - startElement.second.packetLoss) / 100) * ((100 - prevElement.second.packetLoss) / 100)) * 100;
double expPing = startElement.second.ping + prevElement.second.ping;
EXIT_IF(expSpeed < m_reqSpeed, ERROR_RESULT_FALSE);
EXIT_IF(expPacketLoss > m_reqPacketloss, ERROR_RESULT_FALSE);
EXIT_IF(expPing > m_reqPing, ERROR_RESULT_FALSE);
}
// Find cycles
{
std::vector<hostAddress_t> se = startElement.second.path;
std::vector<hostAddress_t> pe = prevElement.second.path;
std::sort(se.begin(), se.end());
std::sort(pe.begin(), pe.end());
std::vector<hostAddress_t> intersect;
std::set_intersection(se.begin(), se.end(),
pe.begin(), pe.end(),
std::back_inserter(intersect));
EXIT_IF(intersect.size() > 1, ERROR_RESULT_FALSE);
}
exit:
return status;
}
status_t DeimosV1::appentToNextMatrix(hostAddress_t startLineAddr, const std::pair<hostAddress_t, Cell> &startElement, hostAddress_t prevLineAddr, const std::pair<hostAddress_t, Cell> &prevElement, ConnectMatrix_t &nextMatrix)
{
status_t status = ERROR_OK;
Cell newCell = prevElement.second;
newCell.path.push_back(startElement.first);
newCell.speed = std::min(startElement.second.speed, prevElement.second.speed);
newCell.packetLoss = (1 - ((100 - startElement.second.packetLoss) / 100) * ((100 - prevElement.second.packetLoss) / 100)) * 100;
newCell.ping = startElement.second.ping + prevElement.second.ping;
std::vector<double> weightVector = {};
weightVector.push_back((1 / newCell.speed) / (1 / m_reqSpeed));
weightVector.push_back(newCell.packetLoss / m_reqPacketloss);
weightVector.push_back(newCell.ping / m_reqPing);
std::sort(weightVector.begin(), weightVector.end(), std::greater<double>());
newCell.cost = prevElement.second.cost + weightVector.front();
nextMatrix[prevLineAddr][startElement.first] = newCell;
exit:
return status;
}
RouteTable_t DeimosV1::mergeMatrixToRouteTable(const std::vector<ConnectMatrix_t> &matrixVec)
{
RouteTable_t table;
for (auto& matrix : matrixVec)
{
for (auto& line : matrix)
{
for (auto& elem : line.second)
{
table.push_back({});
table.back().cost = elem.second.cost;
table.back().source = line.first;
table.back().destination = elem.first;
table.back().path = elem.second.path;
}
}
}
std::sort(table.begin(), table.end(), [](Route& cell_1, Route& cell_2)
{
return cell_1.cost < cell_2.cost;
});
return table;
}
| [
"l.kargalov@yandex.ru"
] | l.kargalov@yandex.ru |
159f4d2a65520355ce925b9e19bfca8291e96c2b | 5cb7861cf5787dec2ff4bb0d5f2f96803e4b7ede | /tensorflow/core/tfrt/saved_model/tests/saved_model_test.cc | 1c532843ff41cff7f9f83315ca43dd5bbafdbeb1 | [
"Apache-2.0",
"MIT",
"BSD-2-Clause"
] | permissive | VeriSilicon/tensorflow | c94887193d562c9d320b5c56d476629682c4ce58 | 2a1fa53a7c3a06eedec16b8aa751fb7deba8f4c5 | refs/heads/xla_npu_v270 | 2022-06-02T16:53:51.549104 | 2022-04-18T10:19:46 | 2022-04-18T10:19:46 | 93,762,772 | 4 | 29 | Apache-2.0 | 2022-04-18T10:19:47 | 2017-06-08T15:05:39 | C++ | UTF-8 | C++ | false | false | 34,906 | cc | /* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <memory>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "tensorflow/cc/saved_model/loader.h"
#include "tensorflow/cc/saved_model/reader.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/platform/resource_loader.h"
#include "tensorflow/core/tfrt/run_handler_thread_pool/run_handler_concurrent_work_queue.h"
#include "tensorflow/core/tfrt/saved_model/saved_model_testutil.h"
namespace tfrt {
namespace saved_model_test {
namespace {
struct TestParams {
bool enable_native_ops = false;
bool enable_grappler = false;
bool enable_lazy_loading = false;
};
class SavedModelTest : public testing::TestWithParam<TestParams> {};
TEST_P(SavedModelTest, BasicV1) {
// SavedModel toy contains a graph of a single 'tf.AddV2' op. It is generated
// using the following python code:
// x = tf.placeholder(tf.int32, shape=(3))
// y = tf.compat.v1.get_variable(name='y', initializer=[1, 2, 3])
// r = tf.matmul(x, y)
std::string saved_model_dir = tensorflow::GetDataDependencyFilepath(
"tensorflow/core/tfrt/saved_model/tests/toy_v1");
auto runtime = DefaultTfrtRuntime(/*num_threads=*/1);
auto options = DefaultSavedModelOptions(runtime.get());
options.enable_lazy_loading = GetParam().enable_lazy_loading;
options.compile_options.enable_native_ops = GetParam().enable_native_ops;
options.compile_options.enable_grappler = GetParam().enable_grappler;
tensorflow::Status status;
auto saved_model =
SavedModelImpl::LoadSavedModel(options, saved_model_dir,
/*tags=*/{"serve"}, &status);
TF_CHECK_OK(status);
// Set input 'x' to [[1, 1, 1]]
std::vector<tensorflow::Tensor> inputs;
inputs.push_back(
CreateTfTensor<int32_t>(/*shape=*/{1, 3}, /*data=*/{1, 1, 1}));
tfrt::SavedModel::RunOptions run_options;
std::vector<tensorflow::Tensor> outputs;
TF_ASSERT_OK(saved_model->Run(run_options, "toy", inputs, &outputs));
ASSERT_EQ(outputs.size(), 1);
EXPECT_THAT(GetTfTensorData<int32_t>(outputs[0]),
testing::ElementsAreArray({6}));
}
// Tests all the value combinations of `TestParams`. For readability, use
// integers instead of booleans.
INSTANTIATE_TEST_SUITE_P(
SavedModelLiteTest, SavedModelTest,
testing::Values(
// The values below are for:
// enable_native_ops, enable_grappler, enable_lazy_loading
TestParams{0, 0, 0}, TestParams{0, 0, 1}, TestParams{0, 1, 0},
TestParams{0, 1, 1}, TestParams{1, 0, 0}, TestParams{1, 0, 1},
TestParams{1, 1, 0}, TestParams{1, 1, 1}));
TEST(SavedModelTest, BasicV2) {
// SavedModel toy contains a graph of a single 'tf.AddV2' op. It is generated
// using the following python code:
// self.w = tf.Variable(tf.ones((3)), name='w')
// r = tf.matmul(x, self.w)
std::string saved_model_dir = tensorflow::GetDataDependencyFilepath(
"tensorflow/core/tfrt/saved_model/tests/toy_v2");
TFRTSavedModelTest test(saved_model_dir);
// Set input 'x' to [[1, 1, 1]]
std::vector<tensorflow::Tensor> inputs;
inputs.emplace_back(tensorflow::DT_INT32,
/*shape=*/tensorflow::TensorShape{1, 3});
auto flat = inputs.back().flat<int32_t>();
flat(0) = 1;
flat(1) = 1;
flat(2) = 1;
std::vector<tensorflow::Tensor> outputs;
TF_ASSERT_OK(
test.GetSavedModel()->Run({}, "serving_default", inputs, &outputs));
ASSERT_EQ(outputs.size(), 1);
auto& output = outputs[0];
ASSERT_EQ(output.NumElements(), 1);
EXPECT_EQ(output.flat<int32_t>()(0), 6);
}
std::vector<tensorflow::Tensor> CreateExpectedOutputs(
const FunctionMetadata& function_metadata,
const std::vector<std::pair<std::string, tensorflow::Tensor>>&
named_outputs) {
std::vector<tensorflow::Tensor> outputs;
absl::flat_hash_map<std::string, tensorflow::Tensor> name_to_outputs;
for (const auto& name_and_output : named_outputs) {
name_to_outputs[name_and_output.first] = name_and_output.second;
}
for (const auto& name : function_metadata.GetOutputNames()) {
outputs.push_back(name_to_outputs.at(name));
}
return outputs;
}
TEST(SavedModelTest, LoadSavedModelWithMetaGraphDef) {
// SavedModel toy contains a graph of a single 'tf.AddV2' op. It is generated
// using the following python code:
// x = tf.placeholder(tf.int32, shape=(3))
// y = tf.compat.v1.get_variable(name='y', initializer=[1, 2, 3])
// r = tf.matmul(x, y)
std::string saved_model_dir = tensorflow::GetDataDependencyFilepath(
"tensorflow/core/tfrt/saved_model/tests/toy_v1");
auto runtime = DefaultTfrtRuntime(/*num_threads=*/1);
auto options = DefaultSavedModelOptions(runtime.get());
tensorflow::MetaGraphDef meta_graph_def;
TF_CHECK_OK(tensorflow::ReadMetaGraphDefFromSavedModel(
saved_model_dir, /*tags=*/{"serve"}, &meta_graph_def));
tensorflow::Status status;
auto saved_model = SavedModelImpl::LoadSavedModel(
options, saved_model_dir, std::move(meta_graph_def), &status);
TF_CHECK_OK(status);
// Set input 'x' to [[1, 1, 1]]
std::vector<tensorflow::Tensor> inputs;
inputs.push_back(
CreateTfTensor<int32_t>(/*shape=*/{1, 3}, /*data=*/{1, 1, 1}));
std::vector<tensorflow::Tensor> outputs;
TF_ASSERT_OK(saved_model->Run({}, "toy", inputs, &outputs));
ASSERT_EQ(outputs.size(), 1);
EXPECT_THAT(GetTfTensorData<int32_t>(outputs[0]),
testing::ElementsAreArray({6}));
}
TEST(SavedModelTest, RunMultipleSignatures) {
std::string saved_model_dir = tensorflow::GetDataDependencyFilepath(
"tensorflow/core/tfrt/saved_model/tests/toy_v1");
auto runtime = DefaultTfrtRuntime(/*num_threads=*/1);
auto options = DefaultSavedModelOptions(runtime.get());
tensorflow::Status status;
auto saved_model =
SavedModelImpl::LoadSavedModel(options, saved_model_dir,
/*tags=*/{"serve"}, &status);
TF_CHECK_OK(status);
std::vector<tensorflow::Tensor> toy_inputs;
toy_inputs.push_back(CreateTfTensor<int32_t>(/*shape=*/{1, 3},
/*data=*/{1, 1, 1}));
std::vector<tensorflow::Tensor> another_toy_inputs;
another_toy_inputs.push_back(CreateTfTensor<int32_t>(/*shape=*/{1, 3},
/*data=*/{2, 2, 2}));
std::vector<tensorflow::Tensor> yet_another_toy_inputs;
yet_another_toy_inputs.push_back(CreateTfTensor<int32_t>(/*shape=*/{1, 3},
/*data=*/{3, 3, 3}));
// TODO(b/183220175): Construct `inputs` in place once `TenserHandle` is
// copyable.
std::vector<std::vector<tensorflow::Tensor>> inputs;
inputs.push_back(std::move(toy_inputs));
inputs.push_back(std::move(another_toy_inputs));
inputs.push_back(std::move(yet_another_toy_inputs));
std::vector<std::vector<tensorflow::Tensor>> outputs;
std::vector<std::string> names = {"toy", "another_toy", "yet_another_toy"};
TF_ASSERT_OK(saved_model->RunMultipleSignatures(/*run_options=*/{}, names,
inputs, &outputs));
ASSERT_EQ(outputs.size(), 3);
{
auto toy_metadata = saved_model->GetFunctionMetadata("toy");
ASSERT_TRUE(toy_metadata.has_value());
std::vector<std::pair<std::string, tensorflow::Tensor>>
expected_toy_named_outputs;
expected_toy_named_outputs.push_back(
{"r1", CreateTfTensor<int32_t>(/*shape=*/{1}, /*data=*/{6})});
std::vector<tensorflow::Tensor> expected_toy_outputs =
CreateExpectedOutputs(*toy_metadata, expected_toy_named_outputs);
ASSERT_EQ(outputs[0].size(), 1);
EXPECT_THAT(GetTfTensorData<int32_t>(outputs[0][0]),
testing::ElementsAreArray(
GetTfTensorData<int32_t>(expected_toy_outputs[0])));
}
{
auto another_toy_metadata = saved_model->GetFunctionMetadata("another_toy");
ASSERT_TRUE(another_toy_metadata.has_value());
std::vector<std::pair<std::string, tensorflow::Tensor>>
expected_another_toy_named_outputs;
expected_another_toy_named_outputs.push_back(
{"r21", CreateTfTensor<int32_t>(/*shape=*/{1}, /*data=*/{12})});
expected_another_toy_named_outputs.push_back(
{"r22", CreateTfTensor<int32_t>(/*shape=*/{1}, /*data=*/{18})});
std::vector<tensorflow::Tensor> expected_another_toy_outputs =
CreateExpectedOutputs(*another_toy_metadata,
expected_another_toy_named_outputs);
ASSERT_EQ(outputs[1].size(), 2);
EXPECT_THAT(GetTfTensorData<int32_t>(outputs[1][0]),
testing::ElementsAreArray(
GetTfTensorData<int32_t>(expected_another_toy_outputs[0])));
EXPECT_THAT(GetTfTensorData<int32_t>(outputs[1][1]),
testing::ElementsAreArray(
GetTfTensorData<int32_t>(expected_another_toy_outputs[1])));
}
{
auto yet_another_toy_metadata =
saved_model->GetFunctionMetadata("yet_another_toy");
ASSERT_TRUE(yet_another_toy_metadata.has_value());
std::vector<std::pair<std::string, tensorflow::Tensor>>
expected_yet_another_toy_named_outputs;
expected_yet_another_toy_named_outputs.push_back(
{"r31", CreateTfTensor<int32_t>(/*shape=*/{1}, /*data=*/{18})});
expected_yet_another_toy_named_outputs.push_back(
{"r32", CreateTfTensor<int32_t>(/*shape=*/{1, 3},
/*data=*/{21, 21, 21})});
expected_yet_another_toy_named_outputs.push_back(
{"r33", CreateTfTensor<int32_t>(/*shape=*/{1, 3},
/*data=*/{24, 24, 24})});
std::vector<tensorflow::Tensor> expected_yet_another_toy_outputs =
CreateExpectedOutputs(*yet_another_toy_metadata,
expected_yet_another_toy_named_outputs);
ASSERT_EQ(outputs[2].size(), 3);
EXPECT_THAT(GetTfTensorData<int32_t>(outputs[2][0]),
testing::ElementsAreArray(GetTfTensorData<int32_t>(
expected_yet_another_toy_outputs[0])));
EXPECT_THAT(GetTfTensorData<int32_t>(outputs[2][1]),
testing::ElementsAreArray(GetTfTensorData<int32_t>(
expected_yet_another_toy_outputs[1])));
EXPECT_THAT(GetTfTensorData<int32_t>(outputs[2][2]),
testing::ElementsAreArray(GetTfTensorData<int32_t>(
expected_yet_another_toy_outputs[2])));
}
}
TEST(SavedModelTest, RunMultipleSignatures_OverlappingNodes) {
std::string saved_model_dir = tensorflow::GetDataDependencyFilepath(
"tensorflow/core/tfrt/saved_model/tests/toy_v1");
auto runtime = DefaultTfrtRuntime(/*num_threads=*/1);
auto options = DefaultSavedModelOptions(runtime.get());
tensorflow::Status status;
auto saved_model =
SavedModelImpl::LoadSavedModel(options, saved_model_dir,
/*tags=*/{"serve"}, &status);
TF_CHECK_OK(status);
std::vector<std::vector<tensorflow::Tensor>> inputs = {
{CreateTfTensor<int32_t>(/*shape=*/{1, 3},
/*data=*/{1, 1, 1})},
{CreateTfTensor<int32_t>(/*shape=*/{1, 3},
/*data=*/{1, 1, 1})},
{CreateTfTensor<int32_t>(/*shape=*/{1, 3},
/*data=*/{1, 1, 1})}};
std::vector<std::vector<tensorflow::Tensor>> outputs;
std::vector<std::string> names = {"toy", "another_toy", "toy"};
TF_ASSERT_OK(saved_model->RunMultipleSignatures(/*run_options=*/{}, names,
inputs, &outputs));
ASSERT_EQ(outputs.size(), 3);
ASSERT_EQ(outputs[0].size(), 1);
EXPECT_THAT(GetTfTensorData<int32_t>(outputs[0][0]),
testing::ElementsAreArray({6}));
{
auto another_toy_metadata = saved_model->GetFunctionMetadata("another_toy");
ASSERT_TRUE(another_toy_metadata.has_value());
std::vector<std::pair<std::string, tensorflow::Tensor>>
expected_another_toy_named_outputs;
expected_another_toy_named_outputs.push_back(
{"r21", CreateTfTensor<int32_t>(/*shape=*/{1}, /*data=*/{6})});
expected_another_toy_named_outputs.push_back(
{"r22", CreateTfTensor<int32_t>(/*shape=*/{1}, /*data=*/{12})});
std::vector<tensorflow::Tensor> expected_another_toy_outputs =
CreateExpectedOutputs(*another_toy_metadata,
expected_another_toy_named_outputs);
ASSERT_EQ(outputs[1].size(), 2);
EXPECT_THAT(GetTfTensorData<int32_t>(outputs[1][0]),
testing::ElementsAreArray(
GetTfTensorData<int32_t>(expected_another_toy_outputs[0])));
EXPECT_THAT(GetTfTensorData<int32_t>(outputs[1][1]),
testing::ElementsAreArray(
GetTfTensorData<int32_t>(expected_another_toy_outputs[1])));
}
ASSERT_EQ(outputs[2].size(), 1);
EXPECT_THAT(GetTfTensorData<int32_t>(outputs[2][0]),
testing::ElementsAreArray({6}));
}
class SavedModelRunByTensorNamesTest : public ::testing::Test {
protected:
void SetUp() override {
auto saved_model_dir = tensorflow::GetDataDependencyFilepath(
"tensorflow/core/tfrt/saved_model/tests/toy_v1");
runtime_ = DefaultTfrtRuntime(/*num_threads=*/1);
auto options = DefaultSavedModelOptions(runtime_.get());
tensorflow::Status status;
saved_model_.reset(static_cast<SavedModelImpl*>(
SavedModelImpl::LoadSavedModel(options, saved_model_dir,
/*tags=*/{"serve"}, &status)
.release()));
TF_CHECK_OK(status);
inputs_.push_back(
std::make_pair("input1", CreateTfTensor<int32_t>(/*shape=*/{1, 3},
/*data=*/{1, 1, 1})));
inputs_.push_back(
std::make_pair("input2", CreateTfTensor<int32_t>(/*shape=*/{1, 3},
/*data=*/{2, 2, 2})));
inputs_.push_back(
std::make_pair("input3", CreateTfTensor<int32_t>(/*shape=*/{1, 3},
/*data=*/{3, 3, 3})));
}
std::unique_ptr<tensorflow::tfrt_stub::Runtime> runtime_;
std::unique_ptr<SavedModelImpl> saved_model_;
std::vector<std::pair<std::string, tensorflow::Tensor>> inputs_;
std::vector<std::string> output_tensor_names_{"result1", "result21",
"result31"};
std::vector<std::string> target_node_names_{"result22", "result32"};
};
TEST_F(SavedModelRunByTensorNamesTest, Basic) {
std::vector<tensorflow::Tensor> outputs;
TF_ASSERT_OK(saved_model_->RunByTensorNames(/*run_options=*/{}, inputs_,
output_tensor_names_,
target_node_names_, &outputs));
ASSERT_EQ(outputs.size(), 3);
// Check output "r1".
EXPECT_THAT(GetTfTensorData<int32_t>(outputs[0]), testing::ElementsAre(6));
// Check output "r21".
EXPECT_THAT(GetTfTensorData<int32_t>(outputs[1]), testing::ElementsAre(12));
// Check output "r31".
EXPECT_THAT(GetTfTensorData<int32_t>(outputs[2]), testing::ElementsAre(18));
}
TEST_F(SavedModelRunByTensorNamesTest, NoTargetNodes) {
std::vector<tensorflow::Tensor> outputs;
TF_ASSERT_OK(saved_model_->RunByTensorNames(
/*run_options=*/{}, inputs_, output_tensor_names_,
/*target_node_names=*/{}, &outputs));
ASSERT_EQ(outputs.size(), 3);
// Check output "r1".
EXPECT_THAT(GetTfTensorData<int32_t>(outputs[0]), testing::ElementsAre(6));
// Check output "r21".
EXPECT_THAT(GetTfTensorData<int32_t>(outputs[1]), testing::ElementsAre(12));
// Check output "r31".
EXPECT_THAT(GetTfTensorData<int32_t>(outputs[2]), testing::ElementsAre(18));
}
TEST_F(SavedModelRunByTensorNamesTest, NoOutputNodes) {
std::vector<tensorflow::Tensor> outputs;
outputs.emplace_back(); // Test outputs is first cleared.
TF_ASSERT_OK(saved_model_->RunByTensorNames(
/*run_options=*/{}, inputs_, /*output_tensor_names=*/{},
target_node_names_, &outputs));
ASSERT_EQ(outputs.size(), 0);
}
TEST_F(SavedModelRunByTensorNamesTest, ShuffleInputsAndOutputs) {
std::vector<std::pair<std::string, tensorflow::Tensor>> inputs = {
{"input2", CreateTfTensor<int32_t>(/*shape=*/{1, 3}, /*data=*/{4, 4, 4})},
{"input1", CreateTfTensor<int32_t>(/*shape=*/{1, 3}, /*data=*/{1, 1, 1})},
{"input3", CreateTfTensor<int32_t>(/*shape=*/{1, 3}, /*data=*/{3, 3, 3})},
};
std::vector<std::string> output_tensor_names{"result22", "result1",
"result31"};
std::vector<tensorflow::Tensor> outputs;
TF_ASSERT_OK(saved_model_->RunByTensorNames(
/*run_options=*/{}, inputs, output_tensor_names, {}, &outputs));
ASSERT_EQ(outputs.size(), 3);
// Check output "r22".
EXPECT_THAT(GetTfTensorData<int32_t>(outputs[0]), testing::ElementsAre(30));
// Check output "r1".
EXPECT_THAT(GetTfTensorData<int32_t>(outputs[1]), testing::ElementsAre(6));
// Check output "r31".
EXPECT_THAT(GetTfTensorData<int32_t>(outputs[2]), testing::ElementsAre(18));
}
TEST(SavedModelTest, CustomWorkQueue) {
std::string saved_model_dir = tensorflow::GetDataDependencyFilepath(
"tensorflow/core/tfrt/saved_model/tests/toy_v1");
tfrt::tf::RunHandlerThreadWorkQueue::Options queue_options;
queue_options.num_complementary_threads = 1;
queue_options.num_main_threads = 1;
queue_options.init_timeout_ms = 100;
auto runtime = tensorflow::tfrt_stub::Runtime::Create(
std::make_unique<tfrt::tf::RunHandlerThreadWorkQueue>(queue_options));
auto options = DefaultSavedModelOptions(runtime.get());
options.compile_options.enable_native_ops = false;
tensorflow::Status status;
auto saved_model =
SavedModelImpl::LoadSavedModel(options, saved_model_dir,
/*tags=*/{"serve"}, &status);
TF_CHECK_OK(status);
// Set input 'x' to [[1, 1, 1]]
std::vector<tensorflow::Tensor> inputs;
inputs.push_back(
CreateTfTensor<int32_t>(/*shape=*/{1, 3}, /*data=*/{1, 1, 1}));
std::vector<tensorflow::Tensor> outputs;
TF_ASSERT_OK(saved_model->Run({}, "toy", inputs, &outputs));
ASSERT_EQ(outputs.size(), 1);
EXPECT_THAT(GetTfTensorData<int32_t>(outputs[0]),
testing::ElementsAreArray({6}));
// Run one more time to check per-request state is correct set up.
outputs.clear();
TF_ASSERT_OK(saved_model->Run({}, "toy", inputs, &outputs));
ASSERT_EQ(outputs.size(), 1);
EXPECT_THAT(GetTfTensorData<int32_t>(outputs[0]),
testing::ElementsAreArray({6}));
}
// Verifies the savedmodel runs correctly with work queues specified in
// RunOptions.
TEST(SavedModelTest, RunOptionsWorkQueue) {
std::string saved_model_dir = tensorflow::GetDataDependencyFilepath(
"tensorflow/core/tfrt/saved_model/tests/toy_v1");
auto runtime = tensorflow::tfrt_stub::Runtime::Create();
auto options = DefaultSavedModelOptions(runtime.get());
options.compile_options.enable_native_ops = false;
tensorflow::Status status;
auto saved_model =
SavedModelImpl::LoadSavedModel(options, saved_model_dir,
/*tags=*/{"serve"}, &status);
TF_CHECK_OK(status);
// Set input 'x' to [[1, 1, 1]]
std::vector<tensorflow::Tensor> inputs;
inputs.push_back(
CreateTfTensor<int32_t>(/*shape=*/{1, 3}, /*data=*/{1, 1, 1}));
std::vector<tensorflow::Tensor> outputs;
tfrt::tf::RunHandlerThreadWorkQueue::Options queue_options;
queue_options.num_complementary_threads = 1;
queue_options.num_main_threads = 1;
queue_options.init_timeout_ms = 100;
tfrt::tf::RunHandlerThreadWorkQueue run_handler_queue(queue_options);
tfrt::SavedModel::RunOptions run_options;
run_options.work_queue = &run_handler_queue;
TF_ASSERT_OK(saved_model->Run(run_options, "toy", inputs, &outputs));
ASSERT_EQ(outputs.size(), 1);
EXPECT_THAT(GetTfTensorData<int32_t>(outputs[0]),
testing::ElementsAreArray({6}));
// Run one more time to check per-request state is correct set up.
outputs.clear();
TF_ASSERT_OK(saved_model->Run(run_options, "toy", inputs, &outputs));
ASSERT_EQ(outputs.size(), 1);
EXPECT_THAT(GetTfTensorData<int32_t>(outputs[0]),
testing::ElementsAreArray({6}));
}
TEST(SavedModelTest, FunctionMetadata) {
std::string saved_model_dir = tensorflow::GetDataDependencyFilepath(
"tensorflow/core/tfrt/saved_model/tests/toy_v1");
TFRTSavedModelTest test(saved_model_dir);
auto* saved_model = test.GetSavedModel();
auto function_metadata = saved_model->GetFunctionMetadata("toy");
ASSERT_TRUE(function_metadata.has_value());
EXPECT_THAT(function_metadata->GetInputNames(),
testing::ElementsAreArray({"x1"}));
EXPECT_THAT(
function_metadata->GetInputSpecs(),
testing::ElementsAreArray({TensorSpec(tensorflow::DT_INT32, {1, 3})}));
EXPECT_THAT(function_metadata->GetOutputNames(),
testing::ElementsAreArray({"r1"}));
EXPECT_THAT(function_metadata->GetOutputSpecs(),
// Shape inference disabled, thus we only match dtype.
testing::ElementsAreArray(
{testing::Field(&TensorSpec::dtype, tensorflow::DT_INT32)}));
}
TEST(SavedModelTest, WrongShape) {
// SavedModel toy contains a graph of a single 'tf.AddV2' op. It is generated
// using the following python code:
// self.w = tf.Variable(tf.ones((3)), name='w')
// r = tf.matmul(x, self.w)
std::string saved_model_dir = tensorflow::GetDataDependencyFilepath(
"tensorflow/core/tfrt/saved_model/tests/toy_v2");
TFRTSavedModelTest test(saved_model_dir);
// Set input 'x' to a wrong shape [[1, 1]]
std::vector<tensorflow::Tensor> inputs;
inputs.push_back(CreateTfTensor<int32_t>(/*shape=*/{1, 2}, /*data=*/{1, 1}));
std::vector<tensorflow::Tensor> outputs;
tfrt::SavedModel::RunOptions run_options;
run_options.validate_input_specs = true;
auto status = test.GetSavedModel()->Run(run_options, "serving_default",
inputs, &outputs);
ASSERT_FALSE(status.ok());
EXPECT_THAT(status.error_message(),
testing::HasSubstr("input shape is wrong"));
}
TEST(SavedModelTest, RefTypeTensorInput) {
// This test checks the loading does not fail for signatures with ref type
// input/output.
//
// TODO(b/188580685): This is a short term workaround to skip signatures with
// ref type input. We need to add correctness testing here for ref type inputs
// once it is supported.
std::string saved_model_dir = tensorflow::GetDataDependencyFilepath(
"tensorflow/core/tfrt/saved_model/tests/ref_type_tensor_input");
auto runtime = DefaultTfrtRuntime(/*num_threads=*/1);
auto options = DefaultSavedModelOptions(runtime.get());
options.compile_options.enable_grappler = true;
tensorflow::Status status;
auto saved_model =
SavedModelImpl::LoadSavedModel(options, saved_model_dir,
/*tags=*/{"serve"}, &status);
TF_ASSERT_OK(status);
EXPECT_THAT(
saved_model->GetFunctionNames(),
testing::UnorderedElementsAre(
"non_ref", "__tf_saved_model_session_initializer_save/restore_all"));
}
TEST(SavedModelTest, HashTableAssetV1) {
std::string saved_model_dir = tensorflow::GetDataDependencyFilepath(
"tensorflow/core/tfrt/saved_model/tests/"
"hash_table_asset_v1");
auto runtime = DefaultTfrtRuntime(/*num_threads=*/1);
auto options = DefaultSavedModelOptions(runtime.get());
options.compile_options.enable_native_ops = false;
options.compile_options.enable_grappler = true;
options.compile_options.hoist_invariant_ops = true;
tensorflow::Status status;
auto saved_model =
SavedModelImpl::LoadSavedModel(options, saved_model_dir,
/*tags=*/{"serve"}, &status);
TF_CHECK_OK(status);
std::vector<tensorflow::Tensor> inputs;
inputs.push_back(CreateTfStringTensor(/*shape=*/{}, /*data=*/{"cat"}));
std::vector<tensorflow::Tensor> outputs;
TF_ASSERT_OK(saved_model->Run({}, "serving_default", inputs, &outputs));
ASSERT_EQ(outputs.size(), 1);
EXPECT_THAT(GetTfTensorData<int64_t>(outputs[0]),
testing::ElementsAreArray({0}));
}
TEST(ControlFlowTest, CtrlFlow) {
std::string saved_model_dir = tensorflow::GetDataDependencyFilepath(
"tensorflow/core/tfrt/saved_model/tests/if_v1");
TFRTSavedModelTest test(saved_model_dir);
std::vector<int32_t> x_data = {-1};
std::vector<tensorflow::Tensor> inputs;
inputs.push_back(CreateTfTensor<int32_t>(
/*shape=*/{}, absl::MakeConstSpan(x_data)));
std::vector<tensorflow::Tensor> outputs;
TF_ASSERT_OK(
test.GetSavedModel()->Run({}, "serving_default", inputs, &outputs));
ASSERT_EQ(outputs.size(), 1);
auto function_metadata =
test.GetSavedModel()->GetFunctionMetadata("serving_default");
ASSERT_TRUE(function_metadata.has_value());
tensorflow::Tensor x(tensorflow::DT_INT32, tensorflow::TensorShape({}));
std::copy(std::begin(x_data), std::end(x_data), x.flat<int32_t>().data());
std::vector<tensorflow::Tensor> tf_inputs = {x};
std::vector<tensorflow::Tensor> tf_outputs;
ComputeCurrentTFResult(saved_model_dir, /*signature_name=*/"serving_default",
function_metadata->GetInputNames(), tf_inputs,
function_metadata->GetOutputNames(), &tf_outputs);
ASSERT_EQ(tf_outputs.size(), 1);
EXPECT_THAT(
GetTfTensorData<int32_t>(outputs[0]),
testing::ElementsAreArray(std::vector<int32_t>(
tf_outputs[0].flat<int32_t>().data(),
tf_outputs[0].flat<int32_t>().data() + tf_outputs[0].NumElements())));
}
TEST(SavedModelTest, ResourceGather) {
std::string saved_model_dir = tensorflow::GetDataDependencyFilepath(
"tensorflow/core/tfrt/saved_model/tests/resource_gather_v1");
TFRTSavedModelTest test(saved_model_dir);
std::vector<int32_t> x_data = {1};
std::vector<tensorflow::Tensor> inputs;
inputs.push_back(CreateTfTensor<int32_t>(
/*shape=*/{}, absl::MakeConstSpan(x_data)));
std::vector<tensorflow::Tensor> outputs;
TF_ASSERT_OK(
test.GetSavedModel()->Run({}, "serving_default", inputs, &outputs));
ASSERT_EQ(outputs.size(), 1);
auto function_metadata =
test.GetSavedModel()->GetFunctionMetadata("serving_default");
ASSERT_TRUE(function_metadata.has_value());
tensorflow::Tensor x(tensorflow::DT_INT32, tensorflow::TensorShape({}));
std::copy(std::begin(x_data), std::end(x_data), x.flat<int32_t>().data());
std::vector<tensorflow::Tensor> tf_inputs = {x};
std::vector<tensorflow::Tensor> tf_outputs;
ComputeCurrentTFResult(saved_model_dir, /*signature_name=*/"serving_default",
function_metadata->GetInputNames(), tf_inputs,
function_metadata->GetOutputNames(), &tf_outputs);
ASSERT_EQ(tf_outputs.size(), 1);
EXPECT_THAT(
GetTfTensorData<int32_t>(outputs[0]),
testing::ElementsAreArray(std::vector<int32_t>(
tf_outputs[0].flat<int32_t>().data(),
tf_outputs[0].flat<int32_t>().data() + tf_outputs[0].NumElements())));
}
TEST(SavedModelTest, DTypeCoverage) {
std::string saved_model_dir = tensorflow::GetDataDependencyFilepath(
"tensorflow/core/tfrt/saved_model/tests/dtype_coverage_v1");
TFRTSavedModelTest test(saved_model_dir);
std::vector<tensorflow::Tensor> inputs;
std::vector<tensorflow::Tensor> outputs;
TF_ASSERT_OK(
test.GetSavedModel()->Run({}, "serving_default", inputs, &outputs));
ASSERT_EQ(outputs.size(), 16);
auto function_metadata =
test.GetSavedModel()->GetFunctionMetadata("serving_default");
ASSERT_TRUE(function_metadata.has_value());
std::vector<tensorflow::Tensor> tf_inputs;
std::vector<tensorflow::Tensor> tf_outputs;
ComputeCurrentTFResult(saved_model_dir, /*signature_name=*/"serving_default",
function_metadata->GetInputNames(), tf_inputs,
function_metadata->GetOutputNames(), &tf_outputs);
ASSERT_EQ(tf_outputs.size(), 16);
for (int i = 0; i < 16; ++i) {
ExpectTensorEqual(outputs[i], tf_outputs[i]);
}
}
TEST(SavedModelTest, Error) {
std::string saved_model_dir = tensorflow::GetDataDependencyFilepath(
"tensorflow/core/tfrt/saved_model/tests/error_v1");
auto runtime = DefaultTfrtRuntime(/*num_threads=*/1);
auto options = DefaultSavedModelOptions(runtime.get());
tensorflow::Status status;
auto saved_model =
SavedModelImpl::LoadSavedModel(options, saved_model_dir,
/*tags=*/{"serve"}, &status);
TF_ASSERT_OK(status);
std::vector<tensorflow::Tensor> outputs;
status = saved_model->Run({}, "serving_default", {}, &outputs);
ASSERT_FALSE(status.ok());
EXPECT_EQ(status.code(), tensorflow::error::INVALID_ARGUMENT);
EXPECT_TRUE(absl::StrContains(
status.error_message(), "You must feed a value for placeholder tensor"));
}
class SavedModelPowTest : public testing::TestWithParam<std::string> {};
TEST_P(SavedModelPowTest, Pow) {
std::string saved_model_dir =
tensorflow::GetDataDependencyFilepath(GetParam());
auto runtime = DefaultTfrtRuntime(/*num_threads=*/1);
auto options = DefaultSavedModelOptions(runtime.get());
options.compile_options.enable_grappler = true;
tensorflow::Status status;
auto saved_model =
SavedModelImpl::LoadSavedModel(options, saved_model_dir,
/*tags=*/{"serve"}, &status);
TF_CHECK_OK(status);
std::vector<int32_t> data = {2};
std::vector<tensorflow::Tensor> inputs;
inputs.push_back(
CreateTfTensor<int32_t>(/*shape=*/{}, absl::MakeConstSpan(data)));
std::vector<tensorflow::Tensor> outputs;
TF_ASSERT_OK(saved_model->Run({}, "serving_default", inputs, &outputs));
ASSERT_EQ(outputs.size(), 1);
EXPECT_THAT(GetTfTensorData<int32_t>(outputs[0]), testing::ElementsAre(8));
}
INSTANTIATE_TEST_SUITE_P(
SavedModelPowTest, SavedModelPowTest,
testing::Values("tensorflow/core/tfrt/saved_model/tests/pow",
"tensorflow/core/tfrt/saved_model/tests/pow_v2"));
TEST(SavedModelTest, ControlFlowV1) {
// This test checks that loading a savedmodel with V1 control flows works
// properly. The current workflow requires functionalization on V1 control
// flows and may insert extra functions. This test is to guard on errors due
// to handling V1 control flows (eg. adding different functions with name
// conflicts).
std::string saved_model_dir = tensorflow::GetDataDependencyFilepath(
"tensorflow/core/tfrt/saved_model/tests/control_flow_v1");
auto runtime = DefaultTfrtRuntime(/*num_threads=*/1);
auto options = DefaultSavedModelOptions(runtime.get());
options.compile_options.enable_grappler = true;
tensorflow::Status status;
auto saved_model =
SavedModelImpl::LoadSavedModel(options, saved_model_dir,
/*tags=*/{"serve"}, &status);
TF_ASSERT_OK(status);
}
TEST(SavedModelTest, WhileLoopV1) {
// This test checks that loading a savedmodel with V1 while works properly.
// The current workflow applies functionalization which may change nodes in
// the original graph. We insert additional nodes to prevent it from changing
// fetch nodes.
std::string saved_model_dir = tensorflow::GetDataDependencyFilepath(
"tensorflow/core/tfrt/saved_model/tests/while_v1");
auto runtime = DefaultTfrtRuntime(/*num_threads=*/1);
auto options = DefaultSavedModelOptions(runtime.get());
options.compile_options.enable_grappler = true;
tensorflow::Status status;
auto saved_model =
SavedModelImpl::LoadSavedModel(options, saved_model_dir,
/*tags=*/{"serve"}, &status);
TF_ASSERT_OK(status);
std::vector<int32_t> data = {0};
std::vector<tensorflow::Tensor> inputs;
inputs.push_back(
CreateTfTensor<int32_t>(/*shape=*/{}, absl::MakeConstSpan(data)));
std::vector<tensorflow::Tensor> outputs;
TF_ASSERT_OK(saved_model->Run({}, "serving_default", inputs, &outputs));
ASSERT_EQ(outputs.size(), 1);
EXPECT_THAT(GetTfTensorData<int32_t>(outputs[0]), testing::ElementsAre(10));
}
TEST(SavedModelTest, SparseTensorInput) {
// This test checks the loading does not fail for signatures with sparse
// input/output.
//
// TODO(b/184675681): This is a short term workaround to skip signatures with
// sparse input. We need to add correctness testing here for sparse inputs
// once it is supported.
std::string saved_model_dir = tensorflow::GetDataDependencyFilepath(
"tensorflow/core/tfrt/saved_model/tests/sparse_tensor_input");
auto runtime = DefaultTfrtRuntime(/*num_threads=*/1);
auto options = DefaultSavedModelOptions(runtime.get());
options.compile_options.enable_grappler = true;
tensorflow::Status status;
auto saved_model =
SavedModelImpl::LoadSavedModel(options, saved_model_dir,
/*tags=*/{"serve"}, &status);
TF_ASSERT_OK(status);
EXPECT_THAT(saved_model->GetFunctionNames(), testing::ElementsAre("dense"));
}
TEST(SavedModelTest, DeadlineExceeded) {
std::string saved_model_dir = tensorflow::GetDataDependencyFilepath(
"tensorflow/core/tfrt/saved_model/tests/toy_v1");
auto runtime = DefaultTfrtRuntime(/*num_threads=*/1);
auto options = DefaultSavedModelOptions(runtime.get());
tensorflow::Status status;
auto saved_model =
SavedModelImpl::LoadSavedModel(options, saved_model_dir,
/*tags=*/{"serve"}, &status);
TF_CHECK_OK(status);
// Set input 'x' to [[1, 1, 1]]
std::vector<tensorflow::Tensor> inputs;
inputs.push_back(
CreateTfTensor<int32_t>(/*shape=*/{1, 3}, /*data=*/{1, 1, 1}));
std::vector<tensorflow::Tensor> outputs;
tfrt::SavedModel::RunOptions run_options;
run_options.deadline = absl::ToChronoTime(absl::Now());
status = saved_model->Run(run_options, "toy", inputs, &outputs);
ASSERT_FALSE(status.ok());
EXPECT_THAT(status.error_message(), testing::HasSubstr("Deadline exceeded"));
}
} // namespace
} // namespace saved_model_test
} // namespace tfrt
| [
"gardener@tensorflow.org"
] | gardener@tensorflow.org |
0deec34884ac3ff53ca8a82b0b75ee39aad46a3b | 6db9478ab57690420b2aa98b450d346f7a9f3b7d | /z_unclassified/1026.cpp | 2a24cc0763fed2796b5b76f64b86b92460f79de4 | [] | no_license | siosio34/AlgorithmStudy | d23266e0d4576a3aab123aee7b571021ec619009 | b5626a0e4eb14f9553fe48aacacb1696a927c740 | refs/heads/master | 2020-03-19T09:15:13.167353 | 2019-05-22T13:50:41 | 2019-05-22T13:50:41 | 136,272,154 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 593 | cpp | #include <iostream>
using namespace std;
int main()
{
int num;
int temp;
int sum = 0;
cin >> num;
int *a = new int[num];
int *b = new int[num];
for (int i = 0; i<num; i++)
{
cin >> a[i];
}
for (int i = 0; i<num; i++)
{
cin >> b[i];
}
for (int i = 1; i<num; i++)
{
for (int j = 0; j<num - 1; j++)
{
if (a[i] < a[j])
{
temp = a[j];
a[j] = a[i];
a[i] = temp;
}
if (b[i] < b[j])
{
temp = b[j];
b[j] = b[i];
b[i] = temp;
}
}
}
for (int i = 0; i<num; i++)
{
sum += (a[i] * b[num - 1 - i]);
}
cout << sum;
return 0;
} | [
"siosio34@nate.com"
] | siosio34@nate.com |
a8d893e3dd4256a000b1ee55026810f0f3cd3561 | c7e26dc37573e8766e472990ab09ae046f49b3ef | /src/media/audio/audio_core/channel_attributes_unittest.cc | 27cf2e0d6d81dfcb2d9c7869f53c8d2da2e95612 | [
"BSD-2-Clause"
] | permissive | lambdaxymox/fuchsia | 03b72b387cbe14360868c98875ed0ed2d2bd8bf5 | 27dc297f40159d6fbd1368830b894d1299710cb5 | refs/heads/master | 2022-11-15T02:50:25.363189 | 2022-10-19T16:49:21 | 2022-10-19T16:49:21 | 296,795,562 | 1 | 2 | BSD-2-Clause | 2022-10-19T07:11:19 | 2020-09-19T05:47:00 | C++ | UTF-8 | C++ | false | false | 3,636 | cc | // Copyright 2020 The Fuchsia 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 "src/media/audio/audio_core/channel_attributes.h"
#include <fuchsia/media/cpp/fidl.h>
#include <vector>
#include <gtest/gtest.h>
namespace media::audio {
namespace {
constexpr uint32_t kTestAudibleFrequency = 2000;
constexpr uint32_t kTestUltrasonicFrequency = 27000;
// Return true if it overlaps the audible range at all. Must include more than just boundary value.
TEST(ChannelAttributesTest, ChannelIncludesAudible) {
EXPECT_FALSE(ChannelAttributes().IncludesAudible());
EXPECT_FALSE(ChannelAttributes(0, 0).IncludesAudible());
EXPECT_FALSE(ChannelAttributes(ChannelAttributes::kAudibleUltrasonicBoundaryHz,
fuchsia::media::MAX_PCM_FRAMES_PER_SECOND)
.IncludesAudible());
EXPECT_TRUE(ChannelAttributes(0, 1).IncludesAudible());
EXPECT_TRUE(ChannelAttributes(ChannelAttributes::kAudibleUltrasonicBoundaryHz - 1,
ChannelAttributes::kAudibleUltrasonicBoundaryHz)
.IncludesAudible());
EXPECT_TRUE(ChannelAttributes(kTestAudibleFrequency, kTestAudibleFrequency).IncludesAudible());
}
// Return true if it overlaps ultrasonic range. Must include more than just the boundary value.
TEST(ChannelAttributesTest, ChannelIncludesUltrasonic) {
EXPECT_FALSE(ChannelAttributes().IncludesUltrasonic());
EXPECT_FALSE(
ChannelAttributes(0, ChannelAttributes::kAudibleUltrasonicBoundaryHz).IncludesUltrasonic());
EXPECT_FALSE(ChannelAttributes(fuchsia::media::MAX_PCM_FRAMES_PER_SECOND / 2,
fuchsia::media::MAX_PCM_FRAMES_PER_SECOND)
.IncludesUltrasonic());
EXPECT_TRUE(ChannelAttributes(0, ChannelAttributes::kAudibleUltrasonicBoundaryHz + 1)
.IncludesUltrasonic());
EXPECT_TRUE(ChannelAttributes(fuchsia::media::MAX_PCM_FRAMES_PER_SECOND / 2 - 1,
fuchsia::media::MAX_PCM_FRAMES_PER_SECOND)
.IncludesUltrasonic());
EXPECT_TRUE(
ChannelAttributes(kTestUltrasonicFrequency, kTestUltrasonicFrequency).IncludesUltrasonic());
}
// If any channel includes any of the range, then the channel set supports audible
TEST(ChannelAttributesTest, VectorIncludesAudible) {
std::vector<ChannelAttributes> channel_attribs;
EXPECT_FALSE(ChannelAttributes::IncludesAudible(channel_attribs));
channel_attribs.push_back({0, 0});
channel_attribs.push_back(
{ChannelAttributes::kAudibleUltrasonicBoundaryHz, fuchsia::media::MAX_PCM_FRAMES_PER_SECOND});
EXPECT_FALSE(ChannelAttributes::IncludesAudible(channel_attribs));
channel_attribs.push_back({kTestAudibleFrequency, kTestAudibleFrequency});
EXPECT_TRUE(ChannelAttributes::IncludesAudible(channel_attribs));
}
// The set of channels must cover the entire ultrasonic range, contiguously
TEST(ChannelAttributesTest, VectorIncludesUltrasonic) {
std::vector<ChannelAttributes> channel_attribs;
EXPECT_FALSE(ChannelAttributes::IncludesUltrasonic(channel_attribs));
channel_attribs.push_back({0, ChannelAttributes::kAudibleUltrasonicBoundaryHz});
channel_attribs.push_back(
{fuchsia::media::MAX_PCM_FRAMES_PER_SECOND / 2, fuchsia::media::MAX_PCM_FRAMES_PER_SECOND});
EXPECT_FALSE(ChannelAttributes::IncludesUltrasonic(channel_attribs));
channel_attribs.push_back({kTestUltrasonicFrequency, kTestUltrasonicFrequency});
EXPECT_TRUE(ChannelAttributes::IncludesUltrasonic(channel_attribs));
}
} // namespace
} // namespace media::audio
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
17a5367da91a7af5e932cd69933c810b244539ec | e4a386ecc62121a124a68fc530483c582a9f2c29 | /PlayFabServerSDK/PlayFabLocalizationAPI.h | ef0a8c0e0cdd60f2dddd8640c75b950b7ad0a15b | [
"Apache-2.0",
"MIT"
] | permissive | PlayFab/Cocos2d-xSDK | f3d08059bb25018970dc312d58de51702fba4664 | b0ba5c90ff0731b9ffb6fb56fcdaaafaa6dca6b9 | refs/heads/master | 2021-01-23T16:20:56.759161 | 2020-12-01T00:19:33 | 2020-12-01T00:19:33 | 23,086,480 | 7 | 8 | NOASSERTION | 2020-12-01T00:19:34 | 2014-08-18T21:06:50 | C++ | UTF-8 | C++ | false | false | 942 | h | #ifndef PLAYFAB_LOCALIZATIONAPI_H_
#define PLAYFAB_LOCALIZATIONAPI_H_
#include "IHttpRequester.h"
#include "PlayFabError.h"
#include "PlayFabLocalizationDataModels.h"
#include <string>
namespace PlayFab
{
class PlayFabLocalizationAPI
{
public:
template<typename ResType> using ProcessApiCallback = std::function<void(const ResType& result, void* userData)>;
// ------------ Generated API calls
static void GetLanguageList(LocalizationModels::GetLanguageListRequest& request, ProcessApiCallback<LocalizationModels::GetLanguageListResponse> callback, ErrorCallback errorCallback = nullptr, void* userData = nullptr);
private:
// ------------ Private constructor, to enforce all-static class
PlayFabLocalizationAPI();
// ------------ Generated result handlers
static void OnGetLanguageListResult(int httpStatus, HttpRequest* request, void* userData);
};
};
#endif
| [
"jenkins-bot@playfab.com"
] | jenkins-bot@playfab.com |
f49b250cae82aa2cac8d228e9e2338f8729050d8 | 1e82e51bfca5cfbaf8e4c0c3fa018101036791e1 | /src/core/public/query/DgR2QueryDiskDisk.h | 5d73d48cf6444195f25b6196a0d43625f024e07a | [
"MIT"
] | permissive | int-Frank/DgLib-deprecated | 74bc2df68fed9b60359189d9a03601f7fa3331dc | 2683c48d84b995b00c6fb13f9e02257d3c93e80c | refs/heads/master | 2022-04-02T17:05:22.205320 | 2020-01-04T07:49:23 | 2020-01-04T07:49:23 | 33,456,765 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 457 | h | //! @file DgR3QueryLineSphere.h
//!
//! @author: Adapted from http://www.geometrictools.com
//! @date 29/05/2016
//!
//! Class declaration: TIQuery
#ifndef DGR3QUERYDISKDISK_H
#define DGR3QUERYDISKDISK_H
#include "..\impl\DgFPCQueryHypersphereHypersphere.h"
namespace Dg
{
namespace R2
{
template<typename Real>
using FPCDiskDisk = impl::FPCQuery<Real, 2, impl::Hypersphere_generic<Real, 2>, impl::Hypersphere_generic<Real, 2>>;
}
}
#endif | [
"frankhart010@gmail.com"
] | frankhart010@gmail.com |
e15e145204331f13e2502b41b93bcabdd97745ed | 08e953330f88590b0a1ffc0a04b286c449669b55 | /src/QtHuman/Human/nFaceShapes.cpp | d4c304d3bf517198011b4ea9e8ca9d9cf15ebe84 | [
"MIT"
] | permissive | Vladimir-Lin/QtHuman | 1edd2ccb0fc2b236cb85c82b3cebf480b8a83f00 | 37e81cc3940748c2f30bdd3a6f54c3c1b0798b00 | refs/heads/main | 2023-05-27T14:10:10.060446 | 2021-06-16T09:26:10 | 2021-06-16T09:26:10 | 377,440,565 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 26,647 | cpp | #include <qthuman.h>
N::FaceShapes:: FaceShapes ( QWidget * parent , Plan * p )
: ListDock ( parent , p )
, PeopleManager ( p )
, CommandSequence ( new QTimer ( this ) )
, Commanding ( false )
, dropAction ( false )
{
WidgetClass ;
Configure ( ) ;
}
N::FaceShapes::~FaceShapes(void)
{
}
QSize N::FaceShapes::sizeHint(void) const
{
return QSize ( 172 , 192 ) ;
}
void N::FaceShapes::Configure(void)
{
setWindowTitle ( tr("Face shapes") ) ;
setViewMode ( IconMode ) ;
setIconSize ( QSize(128,128) ) ;
setGridSize ( QSize(144,192) ) ;
setMovement ( Snap ) ;
setResizeMode ( Adjust ) ;
setSelectionMode ( SingleSelection ) ;
setWordWrap ( true ) ;
setMouseTracking ( true ) ;
setWrapping ( true ) ;
setTextElideMode ( Qt::ElideNone ) ;
setHorizontalScrollBarPolicy ( Qt::ScrollBarAsNeeded ) ;
setVerticalScrollBarPolicy ( Qt::ScrollBarAsNeeded ) ;
setMinimumSize ( QSize(172,144) ) ;
setDragDropMode ( DragDrop ) ;
setDropFlag ( DropPicture , true ) ;
setDropFlag ( DropPeople , true ) ;
plan -> setFont ( this ) ;
////////////////////////////////////////////////////////////////////
LimitValues [ 49 ] = 1 ;
LimitValues [ 60 ] = 10 ;
LimitValues [ 61 ] = 10 ;
LimitValues [ 37714 ] = 300 ;
////////////////////////////////////////////////////////////////////
if (plan->Booleans["Phone"]) setViewMode ( QListView::ListMode ) ;
CommandSequence -> setParent ( this ) ;
nConnect ( this , SIGNAL ( TriggerCommand ( ) ) ,
this , SLOT ( StartCommand ( ) ) ) ;
nConnect ( CommandSequence , SIGNAL ( timeout ( ) ) ,
this , SLOT ( CommandHandler ( ) ) ) ;
nConnect ( this , SIGNAL (setIcon (QImage*,QListWidgetItem*)) ,
this , SLOT (setItemIcon(QImage*,QListWidgetItem*)) ) ;
nConnect ( this , SIGNAL (listItems (ListWidgetItems&)) ,
this , SLOT (appendItems(ListWidgetItems&)) ) ;
}
bool N::FaceShapes::FocusIn(void)
{
AssignAction ( Label , windowTitle ( ) ) ;
LinkAction ( Refresh , startup ( ) ) ;
LinkAction ( Insert , New ( ) ) ;
LinkAction ( Copy , Copy ( ) ) ;
return true ;
}
QMimeData * N::FaceShapes::dragMime(void)
{
QListWidgetItem * IT = currentItem() ;
if (IsNull(IT)) return NULL ;
SUID uuid = nListUuid(IT) ;
QMimeData * mime = new QMimeData() ;
setMime ( mime , "faceshape/uuid" , uuid ) ;
if (NotNull(IT)) {
QIcon icon = IT->icon() ;
if (!icon.isNull()) {
QSize s = iconSize() ;
QImage image = icon . pixmap(s) . toImage() ;
if (!image.isNull()) {
mime -> setImageData(image) ;
} ;
} ;
mime -> setText ( IT->text() ) ;
} ;
return mime ;
}
bool N::FaceShapes::hasItem(void)
{
QListWidgetItem * item = currentItem() ;
return NotNull ( item ) ;
}
bool N::FaceShapes::startDrag(QMouseEvent * event)
{
QListWidgetItem * atItem = itemAt(event->pos()) ;
if (IsNull(atItem)) return false ;
if (!IsMask(event->buttons(),Qt::LeftButton)) return false ;
dragPoint = event->pos() ;
if (!atItem->isSelected()) return false ;
if (!PassDragDrop) return true ;
return false ;
}
bool N::FaceShapes::fetchDrag(QMouseEvent * event)
{
if (!IsMask(event->buttons(),Qt::LeftButton)) return false ;
QPoint pos = event->pos() ;
pos -= dragPoint ;
return ( pos.manhattanLength() > qApp->startDragDistance() ) ;
}
void N::FaceShapes::dragDone(Qt::DropAction dropIt,QMimeData * mime)
{
}
bool N::FaceShapes::finishDrag(QMouseEvent * event)
{
return true ;
}
bool N::FaceShapes::acceptDrop(QWidget * source,const QMimeData * mime)
{
return dropHandler ( mime ) ;
}
QString N::FaceShapes::MimeType(const QMimeData * mime)
{
return AbstractGui::MimeType (
mime ,
"picture/uuid;picture/uuids;"
"people/uuid;people/uuids"
) ;
}
UUIDs N::FaceShapes::MimeUuids(const QMimeData * mime,QString mimetype)
{
UUIDs Uuids ;
QByteArray data = mime->data(mimetype) ;
if (data.size()<=0) return Uuids ;
if (mimetype=="picture/uuid") {
Uuids << GetUuid(data) ;
} else
if (mimetype=="picture/uuids") {
Uuids = GetUuids ( data ) ;
} else
if (mimetype=="people/uuid") {
Uuids << GetUuid(data) ;
} else
if (mimetype=="people/uuids") {
Uuids = GetUuids ( data ) ;
} ;
return Uuids ;
}
bool N::FaceShapes::dropNew(QWidget * source,const QMimeData * mime,QPoint pos)
{
QString mtype ;
UUIDs Uuids ;
if (source==this) return false ;
mtype = MimeType (mime ) ;
Uuids = MimeUuids (mime,mtype) ;
if (mtype=="picture/uuid" ||
mtype=="picture/uuids" )
plan->showMessage (
tr("Assign %1 icon from %2" )
.arg(Uuids.count() )
.arg(source->windowTitle()) ) ;
if (mtype=="people/uuid" ||
mtype=="people/uuids" )
plan->showMessage (
tr("Copy %1 people from %2" )
.arg(Uuids.count() )
.arg(source->windowTitle()) ) ;
return true ;
}
bool N::FaceShapes::dropMoving(QWidget * source,const QMimeData * mime,QPoint pos)
{
if (dropAction) return false ;
if (source==this) {
QListWidgetItem * atItem = itemAt(pos) ;
if (IsNull (atItem)) return false ;
if (NotNull(atItem) && atItem->isSelected()) return false ;
} ;
return true ;
}
bool N::FaceShapes::dropAppend(QWidget * source,const QMimeData * mime,QPoint pos)
{
if (dropAction) return false ;
return dropItems ( source , mime , pos ) ;
}
void N::FaceShapes::run(int Type,ThreadData * data)
{ Q_UNUSED ( data ) ;
switch ( Type ) {
case 10001 :
FetchUUIDs ( ) ;
break ;
case 10003 :
FetchIcons ( ) ;
break ;
} ;
}
void N::FaceShapes::StartCommand(void)
{
nDropOut ( Commanding ) ;
CommandSequence -> start ( LimitValues [ 37714 ] ) ;
}
void N::FaceShapes::CommandHandler(void)
{
nDropOut ( Commanding ) ;
Commanding = true ;
while ( Sequences.count() > 0 ) {
RunCommand ( Sequences[0] ) ;
Sequences . takeAt ( 0 ) ;
} ;
CommandSequence -> stop ( ) ;
Commanding = false ;
}
bool N::FaceShapes::RunCommand(VarArgs & arguments)
{
if (arguments.count()<1) return false ;
VarArgs V = arguments ;
UUIDs U ;
int c = V [ 0 ] . toInt ( ) ;
switch ( c ) {
case 10001 :
start ( 10001 ) ;
break ;
case 10002 :
ArgsToUuids ( 1 , V , U ) ;
plan -> processEvents ( ) ;
ListIcons ( U ) ;
break ;
default :
return false ;
} ;
return true ;
}
bool N::FaceShapes::startup(void)
{
clear ( ) ;
start ( 10001 ) ;
return true ;
}
void N::FaceShapes::setItemIcon (
QImage * image ,
QListWidgetItem * item )
{
QSize IS = iconSize ( ) ;
PictureManager PM ( plan ) ;
QIcon icon = PM . Icon (image,IS) ;
item -> setIcon ( icon ) ;
delete image ;
}
void N::FaceShapes::FetchUUIDs(void)
{
UUIDs Uuids ;
EnterSQL ( SC , plan->sql ) ;
Uuids = SC . Uuids (
PlanTable(FaceShapes) ,
"uuid" ,
SC.OrderByAsc("id") ) ;
LeaveSQL ( SC , plan->sql ) ;
if (Uuids.count()>0) {
N::VarArgs V ;
V << 10002 ;
V << Uuids . count ( ) ;
toVariants ( Uuids , V ) ;
addSequence ( V ) ;
//////////////////////////////////
emit TriggerCommand ( ) ;
} ;
}
void N::FaceShapes::ListIcons(UUIDs & Uuids)
{
QIcon icon = plan -> Icon (
Types :: FaceShape ,
1 ,
0 ,
QIcon(":/images/faces.png") ) ;
SUID uuid ;
foreach (uuid,Uuids) {
NewListWidgetItem ( TWI ) ;
TWI -> setText ( " " ) ;
TWI -> setIcon ( icon ) ;
TWI -> setData ( Qt::UserRole , uuid ) ;
QListWidget::addItem ( TWI ) ;
} ;
start ( 10003 ) ;
}
void N::FaceShapes::FetchIcons(void)
{
GroupItems GI ( plan ) ;
PictureManager PM ( plan ) ;
GI . AutoMap = true ;
GI . GroupTable = GI . LookTable (
Types :: FaceShape ,
Types :: Picture ,
Groups :: Icon ) ;
EnterSQL ( SC , plan->sql ) ;
QListWidgetItem * it ;
QString name ;
SUID uuid ;
SUID puid ;
for (int i=0;i<count();i++) {
it = item ( i ) ;
uuid = nListUuid ( it ) ;
name = Name(SC,uuid,vLanguageId) ;
it -> setText ( name ) ;
it -> setToolTip ( name ) ;
puid = GI.FindSecond (
SC ,
uuid ,
Types :: FaceShape ,
Types :: Picture ,
Groups :: Icon ,
"order by position asc limit 0,1" ) ;
QImage * image = PM.Thumb (SC,puid) ;
if (NotNull(image)) {
emit setIcon ( image , it ) ;
} ;
} ;
LeaveSQL ( SC , plan->sql ) ;
Alert ( Done ) ;
}
void N::FaceShapes::List(void)
{
ListWidgetItems Items ;
GroupItems GI ( plan ) ;
PictureManager PM ( plan ) ;
EnterSQL ( SC , plan->sql ) ;
QString name ;
SUID uuid ;
UUIDs Uuids = SC.Uuids (
PlanTable(FaceShapes) ,
"uuid" ,
SC.OrderByAsc("id") ) ;
foreach (uuid,Uuids) {
NewListWidgetItem ( TWI ) ;
// QIcon icon ;
name = Name(SC,uuid,vLanguageId) ;
TWI -> setText ( name ) ;
TWI -> setToolTip ( name ) ;
TWI -> setData ( Qt::UserRole , uuid ) ;
SUID puid = GI.FindSecond (
SC ,
uuid ,
Types :: FaceShape ,
Types :: Picture ,
Groups :: Icon ,
"order by position asc limit 0,1" ) ;
QImage * image = PM.Thumb (SC,puid) ;
if (NotNull(image)) {
emit setIcon ( image , TWI ) ;
// } else {
// icon = plan->Icon(Types::FaceShape,1,0,QIcon(":/images/faces.png")) ;
} ;
Items << TWI ;
} ;
LeaveSQL ( SC , plan->sql ) ;
emit listItems ( Items ) ;
Alert ( Done ) ;
}
void N::FaceShapes::Copy(void)
{
QMimeData * mime = dragMime ( ) ;
if (IsNull(mime)) return ;
qApp->clipboard()->setMimeData ( mime ) ;
}
bool N::FaceShapes::Menu(QPoint pos)
{
nScopedMenu ( mm , this ) ;
QMdiSubWindow * mdi = Casting(QMdiSubWindow,parent()) ;
QDockWidget * dock = Casting(QDockWidget ,parent()) ;
QListWidgetItem * item = itemAt(pos) ;
QPoint global = mapToGlobal(pos) ;
QAction * a ;
mm.add(202,tr("Refresh" )) ;
mm.add(201,tr("New face shape")) ;
if (NotNull(item)) {
mm . addSeparator ( ) ;
mm.add(101,tr("People" )) ;
mm.add(102,tr("Gallery")) ;
mm.add(103,tr("Shape equation")) ;
} ;
mm . addSeparator ( ) ;
if (!plan->Booleans["Phone"]) {
if (viewMode()==QListView::IconMode) mm.add(301,tr("List view")) ;
if (viewMode()==QListView::ListMode) mm.add(302,tr("Icon view")) ;
} ;
mm . add ( 401 , tr("Translations") ) ;
mm . addSeparator ( ) ;
nIfSafe(dock) mm.add(1000001,tr("Move to window area")) ;
nIfSafe(mdi ) mm.add(1000002,tr("Move to dock area" )) ;
mm . setFont ( plan ) ;
a = mm.exec(global) ;
if (IsNull(a)) return true ;
switch (mm[a]) {
case 101 :
emit People ( nListUuid(item),Types::FaceShape,item->text() ) ;
break ;
case 102 :
emit Gallery ( item->text(),nListUuid(item),Types::FaceShape ) ;
break ;
case 103 :
emit ShapeEquation(nListUuid(item),Types::FaceShape,item->text()) ;
break ;
case 201 :
New ( ) ;
break ;
case 202 :
startup ( ) ;
break ;
case 301 :
setViewMode ( QListView::ListMode ) ;
break ;
case 302 :
setViewMode ( QListView::IconMode ) ;
break ;
case 401 :
if (count()>0) {
UUIDs u = ItemUuids() ;
emit Translations ( windowTitle() , u ) ;
} ;
break ;
case 1000001 :
emit attachMdi (this,Qt::Vertical) ;
break ;
case 1000002 :
emit attachDock (
this ,
windowTitle() ,
Qt::RightDockWidgetArea ,
Qt::TopDockWidgetArea |
Qt::BottomDockWidgetArea |
Qt::LeftDockWidgetArea |
Qt::RightDockWidgetArea ) ;
break ;
default :
break ;
} ;
return true ;
}
bool N::FaceShapes::dropPictures(QWidget * source,QPointF psf,const UUIDs & Uuids)
{
if (source==this) return true ;
QPoint pos = psf.toPoint() ;
QListWidgetItem * atItem = itemAt(pos) ;
if (IsNull(atItem)) return true ;
if (Uuids.count()<=0) return true ;
SUID face = nListUuid(atItem) ;
dropAction = true ;
GroupItems GI(plan) ;
EnterSQL(SC,plan->sql) ;
UUIDs u = Uuids ;
GI . Join (
SC ,
face ,
Types::FaceShape ,
Types::Picture ,
Groups::Subordination ,
0 ,
u ) ;
LeaveSQL(SC,plan->sql) ;
Alert ( Done ) ;
dropAction = false ;
startup() ;
return true ;
}
bool N::FaceShapes::dropPeople(QWidget * source,QPointF psf,const UUIDs & Uuids)
{
QPoint pos = psf.toPoint() ;
QListWidgetItem * atItem = itemAt(pos) ;
if (source==this) return true ;
if (IsNull(atItem)) return true ;
dropAction = true ;
SUID auid = nListUuid(atItem) ;
UUIDs AUIDs = Uuids ;
GroupItems GI(plan) ;
EnterSQL(SC,plan->sql) ;
GI.Join (
SC , auid ,
Types::FaceShape ,
Types::People ,
Groups::Subordination ,
0 , AUIDs ) ;
LeaveSQL(SC,plan->sql) ;
Alert ( Done ) ;
dropAction = false ;
return true ;
}
void N::FaceShapes::New(void)
{
NewListWidgetItem ( LWI ) ;
QIcon icon ;
icon = plan->Icon(Types::FaceShape,1,0,QIcon(":/images/faces.png")) ;
LWI->setIcon ( icon ) ;
LWI->setData ( Qt::UserRole , 0 ) ;
QListWidget :: addItem ( LWI ) ;
scrollToItem ( LWI ) ;
setCurrentItem ( LWI ) ;
ItemEditing = LWI ;
QRect R = visualItemRect(LWI) ;
QLineEdit * l = new QLineEdit(this) ;
QFont f = font() ;
QRect L ;
L . setTop ( R.bottom () ) ;
L . setLeft ( R.left () ) ;
L . setWidth ( R.width () ) ;
L . setHeight ( f.pixelSize () + 2 ) ;
setItemWidget ( ItemEditing , l ) ;
l -> setGeometry ( L ) ;
l -> setFont ( f ) ;
ItemWidget = l ;
connect(l ,SIGNAL(editingFinished()) ,
this,SLOT (editingFinished()) ) ;
l->setFocus(Qt::TabFocusReason) ;
}
void N::FaceShapes::editingFinished(void)
{
QLineEdit * l = Casting(QLineEdit,ItemWidget) ;
if (IsNull(l)) return ;
////////////////////////////////////////////////////////////
QString name = l->text() ;
removeItemWidget(ItemEditing) ;
if (name.length()<=0) {
takeItem(row(ItemEditing)) ;
ItemEditing = NULL ;
ItemWidget = NULL ;
return ;
} ;
ItemEditing->setText(name) ;
////////////////////////////////////////////////////////////
Bustle ( ) ;
SqlConnection SC(plan->sql) ;
if (SC.open("FaceShapes","editingFinished")) {
SUID u = 0 ;
u = SC.Unique ( PlanTable(MajorUuid),"uuid",3576 ) ;
if (u>0) {
SC.assureUuid(PlanTable(MajorUuid),u,Types::FaceShape) ;
SC.insertUuid(PlanTable(FaceShapes),u,"uuid") ;
SC.assureName(PlanTable(Names),u,vLanguageId,name) ;
} ;
SC . close ( ) ;
if (u>0) ItemEditing->setData ( Qt::UserRole,u ) ;
} else {
takeItem(row(ItemEditing)) ;
} ;
SC . remove ( ) ;
Vacancy ( ) ;
////////////////////////////////////////////////////////////
ItemEditing = NULL ;
ItemWidget = NULL ;
Alert ( Done ) ;
}
| [
"lin.vladimir@gmail.com"
] | lin.vladimir@gmail.com |
aae04d9838f4ddee82600589139070538df51c72 | c72f1ba091332e289791afb5ed723c7b619046f9 | /4 JSON Parser HTTP Cache/C++ Parser+HTTP+Cache iOS w calabash/include/Poco/Data/LOB.h | c257ea5288db9ce3fd094e33fe4f4993e5f2cfbe | [] | no_license | ravindranathakila/Sogeti-MasterThesis-CrossPlatformMobileDevelopment | 7d7823ed17c37945f6b600550625a7ebaf9edd27 | 6042d67950d18302972758038dcbe5066d585726 | refs/heads/master | 2021-01-20T23:03:47.956283 | 2013-07-07T07:59:30 | 2013-07-07T07:59:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,959 | h | //
// LOB.h
//
// $Id: //poco/Main/Data/include/Poco/Data/LOB.h#12 $
//
// Library: Data
// Package: DataCore
// Module: LOB
//
// Definition of the LOB class.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#ifndef Data_LOB_INCLUDED
#define Data_LOB_INCLUDED
#include "Poco/Data/Data.h"
#include "Poco/SharedPtr.h"
#include "Poco/Dynamic/VarHolder.h"
#include "Poco/Exception.h"
#include <vector>
#include <algorithm>
namespace Poco {
namespace Data {
template <typename T>
class LOB
/// Representation of a Large OBject.
///
/// A LOB can hold arbitrary data.
/// The maximum size depends on the underlying database.
///
/// The LOBInputStream and LOBOutputStream classes provide
/// a convenient way to access the data in a LOB.
{
public:
typedef typename std::vector<T>::const_iterator Iterator;
typedef T ValueType;
typedef typename std::vector<T> Container;
typedef Poco::SharedPtr<Container> ContentPtr;
LOB(): _pContent(new std::vector<T>())
/// Creates an empty LOB.
{
}
LOB(const std::vector<T>& content):
_pContent(new std::vector<T>(content))
/// Creates the LOB, content is deep-copied.
{
}
LOB(const T* const pContent, std::size_t size):
_pContent(new std::vector<T>(pContent, pContent + size))
/// Creates the LOB by deep-copying pContent.
{
}
LOB(const std::basic_string<T>& content):
_pContent(new std::vector<T>(content.begin(), content.end()))
/// Creates a LOB from a string.
{
}
LOB(const LOB& other): _pContent(other._pContent)
/// Creates a LOB by copying another one.
{
}
~LOB()
/// Destroys the LOB.
{
}
LOB& operator = (const LOB& other)
/// Assignment operator.
{
LOB tmp(other);
swap(tmp);
return *this;
}
bool operator == (const LOB& other) const
/// Compares for equality LOB by value.
{
return *_pContent == *other._pContent;
}
bool operator != (const LOB& other) const
/// Compares for inequality LOB by value.
{
return *_pContent != *other._pContent;
}
void swap(LOB& other)
/// Swaps the LOB with another one.
{
using std::swap;
swap(_pContent, other._pContent);
}
const std::vector<T>& content() const
/// Returns the content.
{
return *_pContent;
}
const T* rawContent() const
/// Returns the raw content.
///
/// If the LOB is empty, returns NULL.
{
if (_pContent->empty())
return 0;
else
return &(*_pContent)[0];
}
void assignVal(std::size_t count, const T& val)
/// Assigns raw content to internal storage.
{
ContentPtr tmp = new Container(count, val);
_pContent.swap(tmp);
}
void assignRaw(const T* ptr, std::size_t count)
/// Assigns raw content to internal storage.
{
poco_assert_dbg (ptr);
LOB tmp(ptr, count);
swap(tmp);
}
void appendRaw(const T* pChar, std::size_t count)
/// Assigns raw content to internal storage.
{
poco_assert_dbg (pChar);
_pContent->insert(_pContent->end(), pChar, pChar+count);
}
void clear(bool doCompact = false)
/// Clears the content of the blob.
/// If doCompact is true, trims the excess capacity.
{
_pContent->clear();
if (doCompact) compact();
}
void compact()
/// Trims the internal storage excess capacity.
{
std::vector<T>(*_pContent).swap(*_pContent);
}
Iterator begin() const
{
return _pContent->begin();
}
Iterator end() const
{
return _pContent->end();
}
std::size_t size() const
/// Returns the size of the LOB in bytes.
{
return static_cast<std::size_t>(_pContent->size());
}
private:
ContentPtr _pContent;
};
typedef LOB<unsigned char> BLOB;
typedef LOB<char> CLOB;
//
// inlines
//
template <typename T>
inline void swap(LOB<T>& b1, LOB<T>& b2)
{
b1.swap(b2);
}
} } // namespace Poco::Data
namespace std
{
using std::swap;
template<>
inline void swap<Poco::Data::BLOB>(Poco::Data::BLOB& b1,
Poco::Data::BLOB& b2)
/// Full template specalization of std:::swap for BLOB
{
b1.swap(b2);
}
template<>
inline void swap<Poco::Data::CLOB>(Poco::Data::CLOB& c1,
Poco::Data::CLOB& c2)
/// Full template specalization of std:::swap for CLOB
{
c1.swap(c2);
}
}
//
// VarHolderImpl<LOB>
//
namespace Poco {
namespace Dynamic {
template <>
class VarHolderImpl<Poco::Data::BLOB>: public VarHolder
{
public:
VarHolderImpl(const Poco::Data::BLOB& val): _val(val)
{
}
~VarHolderImpl()
{
}
const std::type_info& type() const
{
return typeid(Poco::Data::BLOB);
}
void convert(std::string& val) const
{
val.assign(_val.begin(), _val.end());
}
VarHolder* clone() const
{
return new VarHolderImpl(_val);
}
const Poco::Data::BLOB& value() const
{
return _val;
}
private:
VarHolderImpl();
Poco::Data::BLOB _val;
};
template <>
class VarHolderImpl<Poco::Data::CLOB>: public VarHolder
{
public:
VarHolderImpl(const Poco::Data::CLOB& val): _val(val)
{
}
~VarHolderImpl()
{
}
const std::type_info& type() const
{
return typeid(Poco::Data::CLOB);
}
void convert(std::string& val) const
{
val.assign(_val.begin(), _val.end());
}
VarHolder* clone() const
{
return new VarHolderImpl(_val);
}
const Poco::Data::CLOB& value() const
{
return _val;
}
private:
VarHolderImpl();
Poco::Data::CLOB _val;
};
} } // namespace Poco::Dynamic
#endif // Data_LOB_INCLUDED
| [
"dev.david.karlsson@gmail.com"
] | dev.david.karlsson@gmail.com |
fac6f25ea63d73a4cbdfeebacb5c227fad16d64d | cafcf6a79e61ae811c461e9b57016bb5c77eda24 | /datacenter/RedisAgent.h | d266643423e1219522e2bf2fc56fbfb6c04f22b5 | [
"MIT"
] | permissive | jj4jj/playground | fa3f3a0da0e4f112b0e407a1cce8faf002151b4f | be0ab129d28359199008af8282e7395186a211a5 | refs/heads/master | 2021-01-22T04:40:44.470282 | 2014-11-05T16:53:01 | 2014-11-05T16:53:01 | 23,486,561 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,479 | h | #pragma once
#include "base/stdinc.h"
#include "base/Buffer.h"
#include "base/Singleton.hpp"
struct redisAsyncContext;
struct redisReply;
struct RedisAddr
{
string ip;
int port;
uint dbidx;
};
struct RedisClientContext
{
RedisAddr addr;
redisAsyncContext* ctx;
int db_selected;
///////////////////////////
RedisClientContext()
{
ctx = NULL;
db_selected = false;
}
};
class RedisCommandListener
{
public:
virtual int OnCommand(redisReply *reply,Buffer & cb,bool timeout = false) = 0;
};
typedef shared_ptr<RedisCommandListener> RedisCommandListenerPtr;
//////////////////////////////////////////////////////////////////////////////////
struct RedisAgentCallBack
{
Buffer cb;
uint32_t time;
};
class RedisAgent : public Singleton<RedisAgent>
{
private:
RedisAgent();
~RedisAgent();
DeclareSingltonSupport(RedisAgent)
public:
static void CommandCallback(redisAsyncContext *c, void *r, void *privdata);
static void ConnectCallback(const redisAsyncContext *c, int status);
static void DisConnectCallback(const redisAsyncContext *c, int status);
public:
RedisAgentCallBack * FindCallBack(uint32_t cbid);
void OnCommand(redisAsyncContext *c,redisReply *reply,uint32_t cbid);
bool AllContextReady();
int Init(const vector<RedisAddr> & addrList,RedisCommandListenerPtr lisener_);
void Stop();
int Polling(int chkPerTick);
public:
int Get(string & key,const Buffer & cb);
int Update(string & key,const Buffer & obj,const Buffer & cb);
int Remove(string & key,const Buffer & cb);
int Command(const Buffer & cb,const char * pszFormat,...);
protected:
RedisClientContext* FindContext(const redisAsyncContext *c);
void CheckTimeOut(int iChkNum = 10);
void OnSelectDB(redisAsyncContext *c,redisReply *reply,Buffer & cb);
void SelectDB(int dbidx);
private:
RedisCommandListenerPtr m_listener;
uint32_t m_dwCallBackSeq;
unordered_map<uint32_t,RedisAgentCallBack> m_mpCallBackPool;
uint32_t m_chkTimeOut;
vector<RedisClientContext> redisCtxList;
int m_iConnected;
int m_closing;
};
| [
"resc@vip.qq.com"
] | resc@vip.qq.com |
519f2cf03e22949615bcbdee8e9c7641dc8b2b03 | 2748d0af8c89e0975bdfde2a24b5e567bfcac0ab | /perception/pointcloud_tools/sq_fitting/tests/es_tests_2.cpp | 72afd2347779eee0130ef2f7f06a5f731aa0d725 | [] | no_license | shenglixu/golems | 184384574958112690719c9295e9c08b75ccb093 | ae516ce6d70cfd07e8806f243686536ca42d662d | refs/heads/master | 2021-01-22T21:37:32.705276 | 2016-11-14T23:44:29 | 2016-11-14T23:44:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,465 | cpp | /**
* @file es_tests_2.cpp
* @brief Test a set of random cases for noise and partiality using threads
*/
#include "perception/pointcloud_tools/sq_fitting/evaluated_eqs.h"
#include "perception/pointcloud_tools/sq_fitting/SQ_utils.h"
#include <pcl/common/centroid.h>
#include <pcl/filters/voxel_grid.h>
#include <future>
#include <thread>
typedef pcl::PointXYZ PointT;
/**
* @brief Structure used to store output lines
*/
struct output_sq{
SQ_parameters par;
double t;
double er_g, er_r;
double er_v;
double er_e1;
double er_e2;
};
// Global variables
const int gnF = 5;
char* fx_names[gnF] = { "Radial", "Solina", "Ichim", "Chevalier", "F5"};
int fx_sq[gnF] = {SQ_FX_RADIAL, SQ_FX_SOLINA, SQ_FX_ICHIM, SQ_FX_CHEVALIER, SQ_FX_5};
const double gDev = 0.0025;
const int gNum_threads = 7;
int gT = 50;
std::string gFilename;
double gD = 0.015;
// Global variables to generate noise
std::random_device rd;
std::mt19937 gen(rd());
// Functions to get partial and noisy versions of original pointcloud
pcl::PointCloud<PointT>::Ptr downsampling( const pcl::PointCloud<PointT>::Ptr &_input,
const double &_voxelSize );
pcl::PointCloud<PointT>::Ptr cut_cloud( const pcl::PointCloud<PointT>::Ptr &_cloud );
pcl::PointCloud<PointT>::Ptr get_noisy( const pcl::PointCloud<PointT>::Ptr &_cloud,
const double &_dev );
double getRand( const double &_minVal, const double &_maxVal );
double beta( double z,double w);
double volSQ( double a, double b, double c, double e1, double e2 );
void saveParams( std::ofstream &_output, const SQ_parameters &_par, double _t,
double _eg, double _er,
double _e_e1, double _e_e2,
double _e_v );
std::vector<output_sq> createCases( int _id );
std::vector<output_sq> createCase();
/**
* @function main
*/
int main( int argc, char*argv[] ) {
/* initialize random seed: */
srand (time(NULL));
// Initialize, in case user does not enter values of e1 and e2
gFilename = std::string("test_2_result.txt");
int v;
while( (v=getopt(argc, argv, "t:n:h")) != -1 ) {
switch(v) {
case 'n' : {
gFilename.assign(optarg);
} break;
case 't' : {
gT = atoi(optarg);
} break;
case 'h' : {
printf("Executable to save T randomized runs to test noise and partial view \n");
printf("Usage: ./executable -t T -n output_filename.txt \n");
return 0;
} break;
} // switch end
}
struct timespec start, finish;
double elapsed;
clock_gettime(CLOCK_MONOTONIC, &start);
srand(time(NULL));
std::ofstream output( gFilename.c_str(), std::ofstream::out );
output << gT << std::endl;
// Launch threads
std::vector<std::future< std::vector<output_sq> > > futures;
for( int i = 0; i < gNum_threads; ++i ) {
futures.push_back( std::async( std::launch::async, &createCases, i) );
}
for( size_t i = 0; i < futures.size(); ++i ) {
futures[i].wait();
}
for( size_t i = 0; i < futures.size(); ++i ) {
std::vector<output_sq> s;
s = futures[i].get();
for( int m = 0; m < s.size(); ++m ) {
saveParams( output, s[m].par, s[m].t, s[m].er_g, s[m].er_r,
s[m].er_e1, s[m].er_e2, s[m].er_v );
}
}
clock_gettime(CLOCK_MONOTONIC, &finish);
elapsed = (finish.tv_sec - start.tv_sec);
elapsed += (finish.tv_nsec - start.tv_nsec) / 1000000000.0;
printf("* Total time: %f \n", elapsed );
output.close();
return 0;
}
/**
* @function createCases
* @brief Create cases per each thread
*/
std::vector<output_sq> createCases(int _id ) {
std::vector<output_sq> ss;
std::vector<output_sq> si;
for( int i = _id; i < gT; i = i + gNum_threads ) {
si = createCase();
for( int j = 0; j < si.size(); ++j ) {
ss.push_back( si[j] );
}
}
return ss;
}
/**
* @function createCase
* @brief Create individual case (base + 6*4 tests)
*/
std::vector<output_sq> createCase() {
std::vector<output_sq> output;
pcl::PointCloud<PointT>::Ptr input( new pcl::PointCloud<PointT>() );
pcl::PointCloud<PointT>::Ptr down( new pcl::PointCloud<PointT>() );
std::vector<pcl::PointCloud<PointT>::Ptr> testCloud(4);
SQ_parameters par;
double er_g, er_r, er_d;
evaluated_sqs es;
// Dimensions
par.dim[0] = getRand(0.025, 0.39);
par.dim[1] = getRand(0.025, 0.39);
par.dim[2] = getRand(0.025, 0.39);
// Translations
par.trans[0] = getRand(-0.8, 0.8);
par.trans[1] = getRand(-0.8, 0.8);
par.trans[2] = getRand(0.3, 1.4);
// Rotation
par.rot[0] = getRand(-M_PI, M_PI);
par.rot[1] = getRand(-M_PI, M_PI);
par.rot[2] = getRand(-M_PI, M_PI);
// E parameters
par.e[0] = getRand(0.1,1.9);
par.e[1] = getRand(0.1,1.9);
// Store original data
output_sq base;
base.par = par;
base.er_r = 0; base.er_g = 0; base.t = 0; base.er_v = 0;
base.er_e1 = 0; base.er_e2 = 0;
output.push_back( base );
// 1. Generate clean pointcloud
input = sampleSQ_uniform<PointT>( par );
struct timespec ts, tf;
double elapsed;
double d;
double vr, vc;
output_sq oi;
if( gD == 0 ) { down = input; }
else { down = downsampling( input, gD ); }
testCloud[0] = down;
testCloud[1]= get_noisy( testCloud[0], gDev );
testCloud[2] = cut_cloud( testCloud[0] );
testCloud[3] = cut_cloud( testCloud[1] );
for( int i = 0; i < gnF; ++i ) {
for( int j = 0; j < 4; ++j ) {
clock_gettime(CLOCK_MONOTONIC, &ts);
es.minimize( testCloud[j], par, er_g, er_r, er_d, fx_sq[i] );
clock_gettime(CLOCK_MONOTONIC, &tf);
error_metric<PointT>( par,input, er_g, er_r, er_d );
elapsed = (tf.tv_sec - ts.tv_sec);
elapsed += (tf.tv_nsec - ts.tv_nsec) / 1000000000.0;
oi.par = par;
oi.er_g = er_g; oi.er_r = er_r; oi.t = elapsed;
oi.er_e1 = fabs(base.par.e[0] - par.e[0]);
oi.er_e2 = fabs(base.par.e[1] - par.e[1]);
vc = volSQ(par.dim[0], par.dim[1], par.dim[2], par.e[0], par.e[1]);
vr = volSQ(base.par.dim[0],base.par.dim[1],base.par.dim[2], base.par.e[0], base.par.e[1] );
oi.er_v = (vc - vr)/vr*100.0;
output.push_back( oi );
}
}
return output;
}
/**
* @function downsampling
*/
pcl::PointCloud<PointT>::Ptr downsampling( const pcl::PointCloud<PointT>::Ptr &_input,
const double &_voxelSize ) {
pcl::PointCloud<PointT>::Ptr cloud_downsampled( new pcl::PointCloud<PointT>() );
// Create the filtering object
pcl::VoxelGrid< PointT > downsampler;
// Set input cloud
downsampler.setInputCloud( _input );
// Set size of voxel
downsampler.setLeafSize( _voxelSize, _voxelSize, _voxelSize );
// Downsample
downsampler.filter( *cloud_downsampled );
return cloud_downsampled;
}
/**
* @function cut_cloud
* @brief Slice cloud by half, leaving only the "visible"points (points towards the eye point (0,0,0))
*/
pcl::PointCloud<PointT>::Ptr cut_cloud( const pcl::PointCloud<PointT>::Ptr &_cloud ) {
pcl::PointCloud<PointT>::Ptr output( new pcl::PointCloud<PointT>() );
// Get eigenvectors and centroid of pointcloud
Eigen::Vector4d c;
pcl::compute3DCentroid( *_cloud, c );
// Get the normal w.r.t. the centroid
Eigen::Vector3d N; N = Eigen::Vector3d(0,0,0) - Eigen::Vector3d(c(0), c(1), c(2) );
double d;
// Plane equation n(0)x + n(1)y + n(2)z + d = 0. Find d using the centroid
d = -( N(0)*c(0) + N(1)*c(1) + N(2)*c(2) );
// Cut it
for( pcl::PointCloud<PointT>::iterator it = _cloud->begin();
it != _cloud->end(); it++ ) {
if( (N(0)*((*it).x) + N(1)*((*it).y) + N(2)*((*it).z) + d) > 0 ) {
PointT p;
p = *it;
output->points.push_back( p );
}
}
output->height = 1; output->width = output->points.size();
return output;
}
/**
* @function get_noisy
*/
pcl::PointCloud<PointT>::Ptr get_noisy( const pcl::PointCloud<PointT>::Ptr &_cloud,
const double &_dev ) {
pcl::PointCloud<PointT>::Ptr output( new pcl::PointCloud<PointT>() );
std::normal_distribution<double> d(0,_dev);
// Make it dirty
for( pcl::PointCloud<PointT>::iterator it = _cloud->begin();
it != _cloud->end(); it++ ) {
PointT p;
p.x = (*it).x + d(gen);
p.y = (*it).y + d(gen);
p.z = (*it).z + d(gen);
output->points.push_back( p );
}
output->height = 1; output->width = output->points.size();
return output;
}
/**
* @function getRand
*/
double getRand( const double &_minVal, const double &_maxVal ) {
return _minVal + (_maxVal - _minVal)*((double)rand() / (double)RAND_MAX);
}
double beta( double z,double w) {
double gz, gw, gzw;
gz = tgamma(z);
gw = tgamma(w);
gzw = tgamma(z+w);
return gz*gw/gzw;
}
double volSQ( double a, double b, double c, double e1, double e2 ) {
return 2*a*b*c*e1*e2*beta(e1*0.5, e1+1)*beta(e2*0.5, e2*0.5+1);
}
/**
* @function saveParams
*/
void saveParams( std::ofstream &_output,
const SQ_parameters &_par,
double _t,
double _eg, double _er,
double _e_e1, double _e_e2,
double _e_v ) {
_output << _par.dim[0] << " " << _par.dim[1] << " " << _par.dim[2] << " "
<< _par.e[0] << " " << _par.e[1] << " "
<< _par.trans[0] << " " << _par.trans[1] << " " << _par.trans[2] << " "
<< _par.rot[0] << " " << _par.rot[1] << " " << _par.rot[2]
<< " " << _t << " "<< _eg << " " << _er << " " << _e_e1 << " "
<< _e_e2 << " "<< _e_v << std::endl;
}
| [
"ahuaman3@gatech.edu"
] | ahuaman3@gatech.edu |
6cc99318098544f33729114d233f057e23e4fb23 | bada30d01f229cbfb5c315d44f31b0038f15a523 | /ability/node/ChangeAbilityInfoNode.cpp | a65231b534dc6be08cdab7d42fb03330cd74a64f | [] | no_license | calmackenzie/VG1819 | 97d8c6d5823a1dbb618fd1ca7c21c5393fd8aff3 | 7bc8f3ba380209668ce281054fd9e024b4455d82 | refs/heads/master | 2021-10-26T12:24:19.940811 | 2019-04-11T19:59:10 | 2019-04-11T19:59:10 | 133,898,562 | 1 | 2 | null | 2019-04-11T01:21:31 | 2018-05-18T03:32:31 | C++ | UTF-8 | C++ | false | false | 358 | cpp | #pragma once
#include "ability/node/AbilityNode.h"
#include "ability/AbilityInfoPackage.h"
//Rock
namespace ability
{
ChangeAbilityInfoNode::ChangeAbilityInfoNode()
{
}
int ChangeAbilityInfoNode::effect(ability::AbilityInfoPackage* p_pack, const std::string& p_valueName, int p_value)
{
p_pack->m_intValue[p_valueName] += p_value;
return 0;
}
} | [
"you0rock0@gmail.com"
] | you0rock0@gmail.com |
163278772b2d2d310ad675d9e9ee21f6aaf1c466 | 4258763312424d1fbd34ad597216491f934e12f9 | /Swan/src/Scene/Scene.cpp | 5f864a17506798a7f5d299217a04512caed32cf2 | [
"MIT"
] | permissive | ranoke/swan3d | cbe97736e9aa093991fe4562352f1f56a7972bf2 | 4ce1f0461b38f12cee73b2fc2d2a28c7e1e0b31d | refs/heads/main | 2023-02-16T02:30:10.052093 | 2021-01-14T18:59:27 | 2021-01-14T18:59:27 | 311,061,070 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,096 | cpp | #include "pch.h"
#include "Scene.h"
#include "Renderer/Renderer.h"
#include "Entity.h"
namespace Swan
{
Entity Scene::CreateEntity(const std::string& name)
{
Entity entity = { m_Registry.create(), this };
entity.AddComponent<TransformComponent>();
auto& tag = entity.AddComponent<TagComponent>();
tag.Tag = name.empty() ? "Entity" : name;
return entity;
}
void Scene::DestroyEntity(Entity entity)
{
m_Registry.destroy(entity);
}
void Scene::OnLoad()
{
}
void Scene::OnUpdate(Timestep ts, Camera& camera)
{
glm::mat4 view = glm::mat4(1.0f);
view = glm::translate(view, glm::vec3(0.f, 3.f, 5.0f));
Renderer::BeginScene(camera, view);
auto group = m_Registry.group<TransformComponent>(entt::get<MeshComponent>);
for (auto entity : group)
{
const auto [transform, mesh] = group.get<TransformComponent, MeshComponent>(entity);
auto t = transform.GetTransform();
Renderer::RenderBuffer(mesh.mesh, t, glm::vec3(255), nullptr);
}
Renderer::EndScene();
}
}// namespace Swan
| [
"ranokpvp@gmail.com"
] | ranokpvp@gmail.com |
a35314ff40e9b258dc9ab9cf3b6c51c7e47aa229 | 500396f79d674e893c607db3b42d0d04a9d6ee89 | /MGL/MGLFileLoaderMGL.cpp | fdb3d63136c07123b94eed3cdab558b2a0d0298d | [] | no_license | MrMCG/MGL_old | a682a9e69c4fe9022411fa1cd1717f476dac50b6 | 82a5a2aae78d4cb788a1c65fc65476ac0129ab13 | refs/heads/master | 2021-06-05T13:03:44.988814 | 2016-09-22T01:00:42 | 2016-09-22T01:00:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,422 | cpp | #include "stdafx.h"
#include "MGLFileLoaderMGL.h"
#include "MGLMesh.h"
#include "MGLExceptions.h"
#include "MGLLog.h"
#include "MGLTimer.h"
#include "MGLMeshGenerator.h"
MGLMesh* MGLFileLoaderMGL::Load(std::string fileName) {
MGLTimer timer = MGLTimer();
timer.Start();
std::vector<GLfloat>* buffer = LoadFileToVec<GLfloat>(fileName);
#ifdef MGL_USER_INCLUDE_FILETC
try {
// buffers not null
MGLException_IsNullptr::Test(buffer);
// buffer size is large enough (for DetermineFileSize())
MGLException_IsLessThan::Test(buffer->size(), (std::size_t)MGL_FILELOADERMGL_BUFFERMINSIZE);
// buffer size is what is expected
MGLException_IsNotEqual::Test(DetermineFileSize(
(GLuint)buffer->at(2), (GLuint)buffer->at(3), (GLint)buffer->at(4)) + 1, buffer->size());
}
catch (MGLException_IsNullptr& e) {
//std::cerr << e.what() << ": FILE SIZE ERROR " << fileName << std::endl;
MGLI_Log->AddLog(MGL_LOG_ERROR, GL_TRUE, "%s%s", e.what(), ": Null Buffer");
delete buffer;
return MGLMeshGenerator::Triangle();
}
catch (MGLException& e) {
//std::cerr << e.what() << ": FILE SIZE ERROR " << fileName << std::endl;
MGLI_Log->AddLog(MGL_LOG_ERROR, GL_TRUE, "%s%s%s", e.what(), ": FILE SIZE ERROR ", fileName.c_str());
delete buffer;
return MGLMeshGenerator::Triangle();
}
#endif // MGL_USER_INCLUDE_FILETC
MGLMesh* mesh = LoadMesh(buffer);
mesh->BufferAllData();
delete buffer;
timer.End();
MGLI_Log->AddLog(MGL_LOG_MAIN, GL_TRUE, "MGL Load: %s : %i vertices in %f", fileName.c_str(), mesh->GetNumVertices(), timer.GetTime());
return mesh;
}
std::size_t MGLFileLoaderMGL::DetermineFileSize(const GLuint numVertices, const GLuint numIndices, const GLint colourVal) const {
// number of floats in vectors
GLuint vec4Size = 4;
GLuint vec3Size = 3;
GLuint vec2Size = 2;
GLuint total = 5; // fileVersion, type, numVertices, numIndices, colourVal
total += numVertices * (vec3Size * 2); // vertices, normals
total += numVertices * vec2Size; // texCoords
if (colourVal == -1) {
total += vec4Size; // colours
}
else if (colourVal > 0) {
total += colourVal * vec4Size; // colours
}
total += numIndices;
return (std::size_t)total;
}
MGLMesh* MGLFileLoaderMGL::LoadMesh(const MGLvecf* buffer) {
GLuint fileVersion, type, numVertices, numIndices;
GLint colourVal;
GLuint loc = 0;
// build mesh from vector
fileVersion = (GLuint)buffer->at(loc);
type = (GLuint)buffer->at(++loc);
numVertices = (GLuint)buffer->at(++loc);
numIndices = (GLuint)buffer->at(++loc);
colourVal = (GLint)buffer->at(++loc);
MGLvecv3* vertices = new MGLvecv3(numVertices);
MGLvecv2* texCoords = new MGLvecv2(numVertices);
MGLvecv3* normals = new MGLvecv3(numVertices);
MGLvecv4* colours = new MGLvecv4(numVertices);
MGLvecu* indices = new MGLvecu(numIndices);
MGLMesh* mesh = new MGLMesh();
mesh->SetNumIndices(numIndices);
mesh->SetNumVertices(numVertices);
mesh->SetType(type);
// vertices
for (GLuint i = 0; i < numVertices; ++i) {
glm::vec3 vec;
vec.x = buffer->at(++loc);
vec.y = buffer->at(++loc);
vec.z = buffer->at(++loc);
vertices->at(i) = vec;
}
mesh->SetVertices(vertices);
// TexCoords
for (GLuint i = 0; i < numVertices; ++i) {
glm::vec2 vec;
vec.x = buffer->at(++loc);
vec.y = buffer->at(++loc);
texCoords->at(i) = vec;
}
mesh->SetTexCoords(texCoords);
// Normals
for (GLuint i = 0; i < numVertices; ++i) {
glm::vec3 vec;
vec.x = buffer->at(++loc);
vec.y = buffer->at(++loc);
vec.z = buffer->at(++loc);
normals->at(i) = vec;
}
mesh->SetNormals(normals);
// Colours
if (colourVal < 1)
{
glm::vec4 vec;
if (colourVal == -1) {
vec.x = buffer->at(++loc);
vec.y = buffer->at(++loc);
vec.z = buffer->at(++loc);
vec.w = buffer->at(++loc);
}
else if (colourVal == 0) {
vec = MGL::WHITE;
}
mesh->SetColours(colours);
mesh->SetNewColours(vec, GL_FALSE);
}
else {
for (GLuint i = 0; i < numVertices; ++i) {
glm::vec4 vec;
vec.x = buffer->at(++loc);
vec.y = buffer->at(++loc);
vec.z = buffer->at(++loc);
vec.w = buffer->at(++loc);
colours->at(i) = vec;
}
mesh->SetColours(colours);
}
// Indices
for (GLuint i = 0; i < numIndices; ++i) {
GLuint temp;
temp = (GLuint)buffer->at(++loc);
indices->at(i) = temp;
}
mesh->SetIndices(indices);
vertices = nullptr;
texCoords = nullptr;
normals = nullptr;
colours = nullptr;
indices = nullptr;
return mesh;
} | [
"mark.gentles@hotmail.co.uk"
] | mark.gentles@hotmail.co.uk |
98f0a7efd60a341164a4326f2c01b0ecf89741b3 | 300980256f6482567c5d9dc1795bb01aa20f01c7 | /leetcode/leetcode-019.cc | b70e5c750be13fa59c68788d2105ae0c05b0b4c2 | [] | no_license | zgnMark/Algorithm | 50886932c426be3575caaff152b09e85c70c861f | 7c6e2c2848e3aa0cd484f51a175fd57d3d135b4a | refs/heads/master | 2020-07-29T06:20:52.208876 | 2018-10-28T12:30:58 | 2018-10-28T12:30:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,013 | cc | #include <bits/stdc++.h>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
} ;
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
if (head == NULL)
return head;
/*if (head->next == NULL)
return NULL;*/
ListNode* p = NULL;
ListNode* q = NULL;
while (/*p->next != NULL && */n > 0) {
if (p == NULL)
p = head;
else
p = p->next;
--n;
}
while (p->next != NULL) {
p = p->next;
if (q == NULL)
q = head;
else
q = q->next;
}
ListNode* tmp = NULL;
if (q == NULL) {
tmp = head;
head = head->next;
} else {
tmp = q->next;
q->next = q->next->next;
}
delete tmp;
return head;
}
};
// No need debug | [
"nitingge@126.com"
] | nitingge@126.com |
d18e94f1843c2c94181e9233808ae4fa12c2d5ca | 843bc3b2e82f52d0bd13eaf7e3b7aae2f04f689e | /Fucking_test.cpp | 7fbba0da5cfcaeb2ee2e9163ea353416268a3594 | [] | no_license | 1o-o1/graphics_lab | 2a5b189eeb7557ddfe614180bf0a2607b2701389 | f324100ff88eec44e3a864bb37a6b0ed5abdaea2 | refs/heads/main | 2023-01-25T01:35:22.593778 | 2020-12-08T15:08:11 | 2020-12-08T15:08:11 | 319,394,389 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 9,869 | cpp | #include<bits/stdc++.h>
#include <stdio.h>
#include <GL/glut.h>
#include <windows.h>
#include <mmsystem.h>
#define b1 first.first
#define b2 first.second
#define b3 second.first
#define b4 second.second
#define s second
#define f first
#define pbk push_back
using namespace std;
typedef long long int ll;
typedef pair<double,double> pd;
typedef pair<bool,bool> pb;
typedef pair<pb,pb> pbb;
const int mx=1e6;
double xmin,xmax,ymin,ymax;
vector<vector<pd>> v,ans;
vector<pd> neew;
vector<vector<pbb>> bit;
pbb bit_cal(int x,int y)
{
pbb tmp;
tmp.b1=0;tmp.b2=0;tmp.b3=0;tmp.b4=0;
if(y>ymax)
tmp.b1=1;
if(y<ymin)
tmp.b2=1;
if(x>xmax)
tmp.b3=1;
if(x<xmin)
tmp.b4=1;
return tmp;
}
int clipable(int i)
{
int sum=0,andsum=0;
sum+=(bit[i][0].b1+bit[i][1].b1);
andsum+=(bit[i][0].b1&bit[i][1].b1);
sum+=(bit[i][0].b2+bit[i][1].b2);
andsum+=(bit[i][0].b2&bit[i][1].b2);
sum+=(bit[i][0].b3+bit[i][1].b3);
andsum+=(bit[i][0].b3&bit[i][1].b3);
sum+=(bit[i][0].b4+bit[i][1].b4);
andsum+=(bit[i][0].b4&bit[i][1].b4);
if(sum==0)
return 0;
else if(andsum==0)
return 1;
else
return -1;
}
void bit_init(void)
{
int i,j;
for(i=0;i<v.size();i++)
{
vector<pbb> bit2;
for(j=0;j<v[i].size();j++)
{
pbb tmp;
tmp=bit_cal(v[i][j].f,v[i][j].s);
bit2.pbk(tmp);
}
bit.pbk(bit2);
}
}
void cohen(void)
{
bit_init();
int i,j;
for(i=0;i<v.size();i++)
{
if(clipable(i)==0)
ans.push_back(v[i]);
else if(clipable(i)==1)
{
double y1=v[i][0].s,y2=v[i][1].s;
double x1=v[i][0].f,x2=v[i][1].f;
double dy=y1-y2,dx=x1-x2;
double m=dy/dx;
double c=y1-m*x1;
for(j=0;j<v[i].size();j++)
{
int f=0;
if(bit[i][j].b1)
{v[i][j].s=ymax;f=1;}
if(bit[i][j].b2)
{v[i][j].s=ymin;f=1;}
if(f==1&&dy!=0&&dx!=0)
v[i][j].f=(v[i][j].s-c)/m;
else{
if(bit[i][j].b3)
{v[i][j].f=xmax;f=2;}
if(bit[i][j].b4)
{v[i][j].f=xmin;f=2;}
if(f==2&&dy!=0&&dx!=0)
v[i][j].s=m*v[i][j].f+c;}
}
ans.push_back(v[i]);
}
}
}
void liang(void){
int i,j;
for(i=0;i<v.size();i++)
{
double y1=v[i][0].s,y2=v[i][1].s;
double x1=v[i][0].f,x2=v[i][1].f;
double dy=y2-y1,dx=x2-x1;
double p[4]={-1*dx,dx,-1*dy,dy},r[4],u1=0,u2=1;
double q[4]={x1-xmin,xmax-x1,y1-ymin,ymax-y1};
bool f=0;
for(j=0;j<4;j++)
{
//cout<<p[j]<<" "<<q[j]<<endl;
if(p[j]==0&&q[j]<0)
{
f=1;break;
}
else if(p[j]<0)
{
r[j]=q[j]/p[j];
u1=max(u1,r[j]);
}
else if(p[j]>0)
{
r[j]=q[j]/p[j];
u2=min(u2,r[j]);
}
}
if(u1<=u2&&!f)
{
v[i][0].f=x1+dx*u1;
v[i][0].s=y1+dy*u1;
v[i][1].f=x1+dx*u2;
v[i][1].s=y1+dy*u2;
ans.push_back(v[i]);
}
}
}
int clipable(pbb i,pbb j)
{
int sum=0,andsum=0;
sum+=(i.b1+j.b1);
andsum+=(i.b1&j.b1);
sum+=(i.b2+j.b2);
andsum+=(i.b2&j.b2);
sum+=(i.b3+j.b3);
andsum+=(i.b3&j.b3);
sum+=(i.b4+j.b4);
andsum+=(i.b4&j.b4);
if(sum==0)
return 0;
else if(andsum==0)
return 1;
else
return -1;
}
void drawline(vector<pd> l)
{
glBegin(GL_LINE_STRIP);
glColor3ub(100, 200, 200);
glVertex2d(l[0].f+2000,l[0].s);
glVertex2d(l[1].f+2000,l[1].s);
glEnd();
}
void mid_point_clip(vector<pd> line)
{
pbb a=bit_cal(line[0].f,line[0].s);
pbb b=bit_cal(line[1].f,line[1].s);
int clip=clipable(a,b);
if(clip==0)
{
drawline(line);
}
else if(clip==-1)
return;
double midx = (line[0].f+line[1].f)/2,midy=(line[0].s+line[1].s)/2;
vector<pd> line1=line,line2=line;
line1[1]=make_pair(midx,midy);
line2[0]= make_pair(midx, midy);
if( abs(midx -line[1].f)>1 && abs(midy - line[1].s)>1) //if line2!=current line
mid_point_clip(line2);
if(abs(midx -line[1].f)>1 && abs(midy - line[1].s)>1) //if line1!=current line
mid_point_clip(line1);
}
void midPoint(void)
{
for(int i=0;i<v.size();i++)
mid_point_clip(v[i]);
}
typedef enum
{
Top,Bottom, Left, Right
} side;
bool get_stat(pd p , side e)
{
if(e==Left&& p.f < xmin)
return 0;
else if(e==Right&& p.f > xmax)
return 0;
else if(e==Top&& p.s > ymax)
return 0;
else if(e==Bottom&& p.s < ymin)
return 0;
return 1;
}
pd Intersect(vector<pd> line, side e)
{
double x,y;
switch(e)
{
case Left :
y = line[0].s + ((line[1].s-line[0].s)*(xmin-line[0].f))/(line[1].f-line[0].f);
x = xmin;
break;
case Right :
y = line[0].s + ((line[1].s-line[0].s)*(xmax-line[0].f))/(line[1].f-line[0].f);
x = xmax;
break;
case Top :
x = line[0].f + ((line[1].f-line[0].f)*(ymax-line[0].s))/(line[1].s - line[0].s);
y = ymax;
break;
case Bottom :
x = line[0].f + ((line[1].f-line[0].f)*(ymin-line[0].s))/(line[1].s - line[0].s);
y = ymin;
break;
}
return make_pair(x,y);
}
void suther(void)
{
ans=v;
for (int e=1;e<2;e++) //1 edge
{
// only oneside works at a time
//because of while calculating line there create devided by zero
side ee=(side)e;
int j,k=0;
vector<pd> tmp;
for(j=0;j<=ans[k].size();j++)
{
pd p1=ans[k][j];
pd p2=ans[k][(j+1)%v[k].size()];
bool c1= get_stat(p1,ee);
bool c2= get_stat(p2,ee);
vector<pd> line;
line.push_back(p1);
line.push_back(p2);
if(c1&&c2) //both inside i i
tmp.push_back(p2); //second one pushed
else if(c1&&!c2) // inside-outside
tmp.push_back(Intersect(line,ee));
else if(!c1&&c2) //outside-inside
{
tmp.push_back(Intersect(line,ee));
tmp.push_back(p2);
}
}
// neew.clear();
//cout<<tmp.size()<<endl;
ans[k].clear();
ans[k]=tmp;
//cout<<e<<endl;
}
}
void(weiler)
void draw_poly(int x)
{
glBegin(GL_POLYGON);
glColor3ub(100, 200, 200);
for(int j=0;j<v[0].size();j++)
glVertex2d(v[0][j].f+x,v[0][j].s);
glEnd();
}
void draw_polyans(int x)
{
glBegin(GL_POLYGON);
glColor3ub(100, 200, 200);
for(int j=0;j<ans[0].size();j++)
glVertex2d(ans[0][j].f+x,ans[0][j].s);
glEnd();
}
void draw_rect(int x)
{
glBegin(GL_LINE_STRIP);
glColor3ub(200,100,100);
glVertex2d(xmin+x,ymin);
glVertex2d(xmin+x,ymax);
glVertex2d(xmax+x,ymax);
glVertex2d(xmax+x,ymin);
glVertex2d(xmin+x,ymin);
glEnd();
}
void drawlines()
{
for(int i =0;i<v.size();i++)
{
glBegin(GL_LINE_STRIP);
glColor3ub(100, 200, 200);
glVertex2d(v[i][0].f,v[i][0].s);
glVertex2d(v[i][1].f,v[i][1].s);
glEnd();
}
}
void drawline_ans(int x)
{
for(int i =0;i<ans.size();i++)
{
glBegin(GL_LINE_STRIP);
glColor3ub(100, 200, 200);
glVertex2d(ans[i][0].f+x,ans[i][0].s);
glVertex2d(ans[i][1].f+x,ans[i][1].s);
glEnd();
}
}
void myDisplay(void)
{
/*
drawlines();
draw_rect(0);
midPoint();
//drawline_ans(2000);
draw_rect(2000);
*/
draw_poly(0);
draw_rect(0);
suther();
//cout<<v[0].size()<<endl;
draw_polyans(2000);
draw_rect(2000);
glFlush();
glutPostRedisplay();
glutSwapBuffers();
}
void myInit(void)
{
glClearColor(0.0, 0.0, 0.0, 0.0);
glColor3f(1.0f, 1.0f, 1.0f);
glPointSize(0.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(-200.0, 4000.0, -1000.0, 2000.0);
}
int main(int argc, char** argv)
{
int i,j,n,l;
cout<<"Enter clip window xmin ymin xmax ymax\n"; ///"change it"
cin>>xmin>>ymin>>xmax>>ymax;
cout<<"Enter number of shape\n";///"change it"
cin>>n;
for (i=0; i<n; i++)
{
cout<<"enter number of vertex and them n x y\n";
cin>>l;
pd point;
vector<pd> shape;
for(j=0;j<l;j++)
{cin>>point.f>>point.s;
shape.pbk(point);}
v.pbk(shape);
}
neew=v[0];
/* for(i=0; ans.size(); i++)
{
for(j=0;j<ans[i].size();j++)
{cout<<ans[i][j].f<<" "<<ans[i][j].s<<" : ";
//cout<<bit[i][j].b1<<" "<<bit[i][j].b2<<" "<<bit[i][j].b3<<" "<<bit[i][j].b4<<" : ";
}
cout<<endl;
}*/
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(2000, 2000);
glutInitWindowPosition(0, 0);
glutCreateWindow("Clipping");
glutDisplayFunc(myDisplay);
myInit();
glutMainLoop();
// return 0;
}
/*
100 200 900 800
5
2
300 700
300 1000
2
200 300
800 400
2
800 900
600 600
2
-100 700
1100 100
2
1100 1000
1100 600
polygon
100 200 900 800
1
4
-100 700
300 1000
1100 600
1100 100
polygon
100 200 900 800
1
3
300 700
200 0
700 100
*/
| [
"noreply@github.com"
] | 1o-o1.noreply@github.com |
aca0083f1cb8b884057b780856f35c1abdc6a88c | 1d21e7f12c0db31afd0860c13f46877a6ee691a4 | /Project1/OrdinaryOrder.cpp | 37562ab0f18be337c3570f19e7dac2dd9f0d36d3 | [] | no_license | kav113/exam | 8d4375f5f1590499786e6e7a0e4cfee3e3343a68 | 0ceaeb128221039fad955109d7fcbb328f37ae4f | refs/heads/master | 2021-03-25T22:50:57.974944 | 2020-03-21T19:45:52 | 2020-03-21T19:45:52 | 247,651,701 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 1,397 | cpp | #include "OrdinaryOrder.h"
#include <fstream>
#include<string>
#include <cstring>
using namespace std;
OrdinaryOrder::OrdinaryOrder(Date date, Time time, Order id)
{
}
OrdinaryOrder::OrdinaryOrder()
{
id ++;
date = date;
time = time;
}
void OrdinaryOrder::toString()
{
cout << "Заказ № " << id
<< "\nСоздан : " << Date() << Time() <<endl;
}
OrdinaryOrder & OrdinaryOrder::operator=(const Order & obj)
{
return *this;
}
void OrdinaryOrder::toFile()
{
ofstream OrderList;
OrderList.open("OrdinaryOrder.bin", ios::app);
if (OrderList.is_open()) {
OrderList << id << " " << Date() << Time() << " ";
OrderList.close();
cout << "OK\n";
}
else {
cout << "Error\n";
}
return;
}
string OrdinaryOrder::fromFile()
{
string lineId, lineDate, lineTime;
ifstream OrderList;
OrderList.open("OrdinaryOrder.bin", ios::in);
if (OrderList.is_open()) {
OrderList >> lineId >> lineDate >> lineTime;
OrderList.close();
cout << "Заказ № " << id
<< "\nСоздан : " << lineDate <<" "<< lineTime << endl;
}
else {
cout << "Error\n";
}
return string();
}
ostream & operator<<(ostream & out, const OrdinaryOrder & id)
{
out << id;
return out;
}
istream & operator>>(istream & in, OrdinaryOrder & id)
{
cout << "Введите id заказа: "; in >> id;
return in;
}
| [
"noreply@github.com"
] | kav113.noreply@github.com |
361bc814380c7552c0b6323d528e1030dce21798 | 0bf4e9718ac2e2845b2227d427862e957701071f | /google_code_jam/all/final_09/d/lq.cpp | 4d0367312899483f5b9035bdf0a0ad70a85535ad | [] | no_license | unjambonakap/prog_contest | adfd6552d396f4845132f3ad416f98d8a5c9efb8 | e538cf6a1686539afb1d06181252e9b3376e8023 | refs/heads/master | 2022-10-18T07:33:46.591777 | 2022-09-30T14:44:47 | 2022-09-30T15:00:33 | 145,024,455 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,640 | cpp | #include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <stack>
#include <algorithm>
#include <numeric>
#include <utility>
#include <iostream>
#include <cstdlib>
#include <string>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <cassert>
//#include <ext/hash_map>
using namespace std;
using namespace __gnu_cxx;
#define PI asin(1)*2.
#define EPS 10e-8
#define REP(i,n) for(i = 0; i < (n); i++)
#define REPC(i,n,c) for(i = 0; (i < (n)) && (c); i++)
#define REPV(i, n) for (i = (n) - 1; i >= 0; i--)
#define REPVC(i, n, c) for (i = (n) - 1; (i >= 0) && (c); i--)
#define FOR(i, a, b) for(i = (a); i <= (b); i++)
#define FORC(i, a, b, c) for(i = (a); (i <= (b)) && (c); i++)
#define FORV(i, a, b) for(i = (a); i >= (b); i--)
#define FORVC(i, a, b, c) for(i = (a); (i >= (b)) && (c); i--)
#define FE(i,t) for (typeof(t.begin())i=t.begin();i!=t.end();i++)
#define FEV(i,t) for (typeof(t.rbegin())i=t.rbegin();i!=t.rend();i++)
#define MAX(a,b) (((a) < (b)) ? (b) : (a))
#define MIN(a,b) (((a) < (b)) ? (a) : (b))
#define pb push_back
#define ST first
#define ND second
#define SZ(a) ((a).size())
#define two(x) (1 << (x))
#define twoll(x) (1LL << (x))
#define ALL(a) (a).begin(), (a).end()
#define CLR(a) (a).clear()
#define SWAP(a,b,c) (c=a, a=b, b=c)
#define SQR(x) (pow((x),2))
#define DIST(x,y) (SQR(x)+SQR(y))
#define MDIST(x,y,a,b) (abs((a)-(x))+abs((b)-(y)))
#define CMP(x,y) ((fabs((x)-(y)) < EPS) ? 0 : ((x) < (y)) ? -1 : 1)
#define ST first
#define ND second
#define ll long long
inline int count_bit(int n){return (n == 0)?0:(n&1)+count_bit(n>>1);}
typedef pair<int,int> pii;
typedef vector<int> vi;
typedef vector<string> vs;
typedef queue<int> qi;
#define MAX_N 500
class WT{
public:
WT(){}
//WT(int _x, int _y, int _c, int _r){x=_x, y=_y, c=_c, r=_r;}
int x, y, c, r;
};
vi edge[MAX_N];
WT wl[MAX_N];
int n;
int solve(){
int i, j, k, c, nc;
vi::iterator it;
c=-1;
REP(i, two(n)){
nc=0;
REP(k, n)
if (i&two(k)){
nc+=wl[k].c;
for(it=edge[k].begin(); it!=edge[k].end(); it++)
if (!(i&two(*it)))break;
if (it != edge[k].end())break;
}
if (k != n)continue;
c=MAX(c, nc);
}
return c;
}
int main(){
int i, j, k, T;
scanf("%d", &T);
REP(i, T){
scanf("%d", &n);
REP(j, n)
scanf("%d %d %d %d", &wl[j].x, &wl[j].y, &wl[j].r, &wl[j].c);
REP(j, n){
CLR(edge[j]);
REP(k, n)
if (DIST(wl[k].x-wl[j].x, wl[k].y-wl[j].y) <= SQR(wl[j].r))
edge[j].pb(k);
}
printf("Case #%d: %d\n", i+1, solve());
}
return EXIT_SUCCESS;
}
| [
"benoit@uuu.com"
] | benoit@uuu.com |
3441aa064543fae7331516d6b5fc8157c04f374e | 1aa372fe482daf2bd122aae1a29b5823dfcaad27 | /packages/git-travel/node_modules/nodegit/src/tag.cc | 29726c64e60e1d627c141ee4b072ad005a513d96 | [
"MIT"
] | permissive | maartenvw/atom-settings | 74ea62fe376d5508b52427955be11c58f5d7308f | 9b0963c013db7d84bd281f7e31d572dd9eb1dcaa | refs/heads/master | 2020-12-24T07:04:11.496569 | 2016-11-10T12:58:57 | 2016-11-10T12:58:57 | 73,382,020 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 47,300 | cc | // This is a generated file, modify: generate/templates/class_content.cc.
#include <nan.h>
#include <string.h>
extern "C" {
#include <git2.h>
}
#include "../include/functions/copy.h"
#include "../include/tag.h"
#include "../include/functions/sleep_for_ms.h"
#include "../include/oid.h"
#include "../include/repository.h"
#include "../include/object.h"
#include "../include/signature.h"
#include "../include/strarray.h"
#include <iostream>
using namespace std;
using namespace v8;
using namespace node;
GitTag::GitTag(git_tag *raw, bool selfFreeing) {
this->raw = raw;
this->selfFreeing = selfFreeing;
}
GitTag::~GitTag() {
if (this->selfFreeing) {
git_tag_free(this->raw);
this->raw = NULL;
}
// this will cause an error if you have a non-self-freeing object that also needs
// to save values. Since the object that will eventually free the object has no
// way of knowing to free these values.
}
void GitTag::InitializeComponent(Local<v8::Object> target) {
Nan::HandleScope scope;
Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(JSNewFunction);
tpl->InstanceTemplate()->SetInternalFieldCount(1);
tpl->SetClassName(Nan::New("Tag").ToLocalChecked());
Nan::SetMethod(tpl, "annotationCreate", AnnotationCreate);
Nan::SetMethod(tpl, "create", Create);
Nan::SetMethod(tpl, "createLightweight", CreateLightweight);
Nan::SetMethod(tpl, "delete", Delete);
Nan::SetPrototypeMethod(tpl, "free", Free);
Nan::SetPrototypeMethod(tpl, "id", Id);
Nan::SetMethod(tpl, "list", List);
Nan::SetMethod(tpl, "listMatch", ListMatch);
Nan::SetMethod(tpl, "lookup", Lookup);
Nan::SetMethod(tpl, "lookupPrefix", LookupPrefix);
Nan::SetPrototypeMethod(tpl, "message", Message);
Nan::SetPrototypeMethod(tpl, "name", Name);
Nan::SetPrototypeMethod(tpl, "owner", Owner);
Nan::SetPrototypeMethod(tpl, "peel", Peel);
Nan::SetPrototypeMethod(tpl, "tagger", Tagger);
Nan::SetPrototypeMethod(tpl, "target", Target);
Nan::SetPrototypeMethod(tpl, "targetId", TargetId);
Nan::SetPrototypeMethod(tpl, "targetType", TargetType);
Local<Function> _constructor_template = Nan::GetFunction(tpl).ToLocalChecked();
constructor_template.Reset(_constructor_template);
Nan::Set(target, Nan::New("Tag").ToLocalChecked(), _constructor_template);
}
NAN_METHOD(GitTag::JSNewFunction) {
if (info.Length() == 0 || !info[0]->IsExternal()) {
return Nan::ThrowError("A new GitTag cannot be instantiated.");
}
GitTag* object = new GitTag(static_cast<git_tag *>(Local<External>::Cast(info[0])->Value()), Nan::To<bool>(info[1]).FromJust());
object->Wrap(info.This());
info.GetReturnValue().Set(info.This());
}
Local<v8::Value> GitTag::New(void *raw, bool selfFreeing) {
Nan::EscapableHandleScope scope;
Local<v8::Value> argv[2] = { Nan::New<External>((void *)raw), Nan::New(selfFreeing) };
return scope.Escape(Nan::NewInstance(Nan::New(GitTag::constructor_template), 2, argv).ToLocalChecked());
}
git_tag *GitTag::GetValue() {
return this->raw;
}
git_tag **GitTag::GetRefValue() {
return this->raw == NULL ? NULL : &this->raw;
}
void GitTag::ClearValue() {
this->raw = NULL;
}
/*
* @param Repository repo
* @param String tag_name
* @param Object target
* @param Signature tagger
* @param String message
* @param Oid callback
*/
NAN_METHOD(GitTag::AnnotationCreate) {
if (info.Length() == 0 || !info[0]->IsObject()) {
return Nan::ThrowError("Repository repo is required.");
}
if (info.Length() == 1 || !info[1]->IsString()) {
return Nan::ThrowError("String tag_name is required.");
}
if (info.Length() == 2 || !info[2]->IsObject()) {
return Nan::ThrowError("Object target is required.");
}
if (info.Length() == 3 || !info[3]->IsObject()) {
return Nan::ThrowError("Signature tagger is required.");
}
if (info.Length() == 4 || !info[4]->IsString()) {
return Nan::ThrowError("String message is required.");
}
if (info.Length() == 5 || !info[5]->IsFunction()) {
return Nan::ThrowError("Callback is required and must be a Function.");
}
AnnotationCreateBaton* baton = new AnnotationCreateBaton;
baton->error_code = GIT_OK;
baton->error = NULL;
baton->oid = (git_oid *)malloc(sizeof(git_oid ));
// start convert_from_v8 block
git_repository * from_repo;
from_repo = Nan::ObjectWrap::Unwrap<GitRepository>(info[0]->ToObject())->GetValue();
// end convert_from_v8 block
baton->repo = from_repo;
// start convert_from_v8 block
const char * from_tag_name;
String::Utf8Value tag_name(info[1]->ToString());
from_tag_name = (const char *) strdup(*tag_name);
// end convert_from_v8 block
baton->tag_name = from_tag_name;
// start convert_from_v8 block
const git_object * from_target;
from_target = Nan::ObjectWrap::Unwrap<GitObject>(info[2]->ToObject())->GetValue();
// end convert_from_v8 block
baton->target = from_target;
// start convert_from_v8 block
const git_signature * from_tagger;
from_tagger = Nan::ObjectWrap::Unwrap<GitSignature>(info[3]->ToObject())->GetValue();
// end convert_from_v8 block
baton->tagger = from_tagger;
// start convert_from_v8 block
const char * from_message;
String::Utf8Value message(info[4]->ToString());
from_message = (const char *) strdup(*message);
// end convert_from_v8 block
baton->message = from_message;
Nan::Callback *callback = new Nan::Callback(Local<Function>::Cast(info[5]));
AnnotationCreateWorker *worker = new AnnotationCreateWorker(baton, callback);
if (!info[0]->IsUndefined() && !info[0]->IsNull())
worker->SaveToPersistent("repo", info[0]->ToObject());
if (!info[1]->IsUndefined() && !info[1]->IsNull())
worker->SaveToPersistent("tag_name", info[1]->ToObject());
if (!info[2]->IsUndefined() && !info[2]->IsNull())
worker->SaveToPersistent("target", info[2]->ToObject());
if (!info[3]->IsUndefined() && !info[3]->IsNull())
worker->SaveToPersistent("tagger", info[3]->ToObject());
if (!info[4]->IsUndefined() && !info[4]->IsNull())
worker->SaveToPersistent("message", info[4]->ToObject());
Nan::AsyncQueueWorker(worker);
return;
}
void GitTag::AnnotationCreateWorker::Execute() {
int result = git_tag_annotation_create(
baton->oid,baton->repo,baton->tag_name,baton->target,baton->tagger,baton->message );
baton->error_code = result;
if (result != GIT_OK && giterr_last() != NULL) {
baton->error = git_error_dup(giterr_last());
}
}
void GitTag::AnnotationCreateWorker::HandleOKCallback() {
if (baton->error_code == GIT_OK) {
Local<v8::Value> to;
// start convert_to_v8 block
if (baton->oid != NULL) {
// GitOid baton->oid
to = GitOid::New((void *)baton->oid, false);
}
else {
to = Nan::Null();
}
// end convert_to_v8 block
Local<v8::Value> result = to;
Local<v8::Value> argv[2] = {
Nan::Null(),
result
};
callback->Call(2, argv);
} else {
if (baton->error) {
Local<v8::Value> argv[1] = {
Nan::Error(baton->error->message)
};
callback->Call(1, argv);
if (baton->error->message)
free((void *)baton->error->message);
free((void *)baton->error);
} else if (baton->error_code < 0) {
std::queue< Local<v8::Value> > workerArguments;
workerArguments.push(GetFromPersistent("repo"));
workerArguments.push(GetFromPersistent("tag_name"));
workerArguments.push(GetFromPersistent("target"));
workerArguments.push(GetFromPersistent("tagger"));
workerArguments.push(GetFromPersistent("message"));
bool callbackFired = false;
while(!workerArguments.empty()) {
Local<v8::Value> node = workerArguments.front();
workerArguments.pop();
if (
!node->IsObject()
|| node->IsArray()
|| node->IsBooleanObject()
|| node->IsDate()
|| node->IsFunction()
|| node->IsNumberObject()
|| node->IsRegExp()
|| node->IsStringObject()
) {
continue;
}
Local<v8::Object> nodeObj = node->ToObject();
Local<v8::Value> checkValue = nodeObj->GetHiddenValue(Nan::New("NodeGitPromiseError").ToLocalChecked());
if (!checkValue.IsEmpty() && !checkValue->IsNull() && !checkValue->IsUndefined()) {
Local<v8::Value> argv[1] = {
checkValue->ToObject()
};
callback->Call(1, argv);
callbackFired = true;
break;
}
Local<v8::Array> properties = nodeObj->GetPropertyNames();
for (unsigned int propIndex = 0; propIndex < properties->Length(); ++propIndex) {
Local<v8::String> propName = properties->Get(propIndex)->ToString();
Local<v8::Value> nodeToQueue = nodeObj->Get(propName);
if (!nodeToQueue->IsUndefined()) {
workerArguments.push(nodeToQueue);
}
}
}
if (!callbackFired) {
Local<v8::Object> err = Nan::Error("Method annotationCreate has thrown an error.")->ToObject();
err->Set(Nan::New("errno").ToLocalChecked(), Nan::New(baton->error_code));
Local<v8::Value> argv[1] = {
err
};
callback->Call(1, argv);
}
} else {
callback->Call(0, NULL);
}
}
free((void *)baton->tag_name);
free((void *)baton->message);
delete baton;
}
/*
* @param Repository repo
* @param String tag_name
* @param Object target
* @param Signature tagger
* @param String message
* @param Number force
* @param Oid callback
*/
NAN_METHOD(GitTag::Create) {
if (info.Length() == 0 || !info[0]->IsObject()) {
return Nan::ThrowError("Repository repo is required.");
}
if (info.Length() == 1 || !info[1]->IsString()) {
return Nan::ThrowError("String tag_name is required.");
}
if (info.Length() == 2 || !info[2]->IsObject()) {
return Nan::ThrowError("Object target is required.");
}
if (info.Length() == 3 || !info[3]->IsObject()) {
return Nan::ThrowError("Signature tagger is required.");
}
if (info.Length() == 4 || !info[4]->IsString()) {
return Nan::ThrowError("String message is required.");
}
if (info.Length() == 5 || !info[5]->IsNumber()) {
return Nan::ThrowError("Number force is required.");
}
if (info.Length() == 6 || !info[6]->IsFunction()) {
return Nan::ThrowError("Callback is required and must be a Function.");
}
CreateBaton* baton = new CreateBaton;
baton->error_code = GIT_OK;
baton->error = NULL;
baton->oid = (git_oid *)malloc(sizeof(git_oid ));
// start convert_from_v8 block
git_repository * from_repo;
from_repo = Nan::ObjectWrap::Unwrap<GitRepository>(info[0]->ToObject())->GetValue();
// end convert_from_v8 block
baton->repo = from_repo;
// start convert_from_v8 block
const char * from_tag_name;
String::Utf8Value tag_name(info[1]->ToString());
from_tag_name = (const char *) strdup(*tag_name);
// end convert_from_v8 block
baton->tag_name = from_tag_name;
// start convert_from_v8 block
const git_object * from_target;
from_target = Nan::ObjectWrap::Unwrap<GitObject>(info[2]->ToObject())->GetValue();
// end convert_from_v8 block
baton->target = from_target;
// start convert_from_v8 block
const git_signature * from_tagger;
from_tagger = Nan::ObjectWrap::Unwrap<GitSignature>(info[3]->ToObject())->GetValue();
// end convert_from_v8 block
baton->tagger = from_tagger;
// start convert_from_v8 block
const char * from_message;
String::Utf8Value message(info[4]->ToString());
from_message = (const char *) strdup(*message);
// end convert_from_v8 block
baton->message = from_message;
// start convert_from_v8 block
int from_force;
from_force = (int) info[5]->ToNumber()->Value();
// end convert_from_v8 block
baton->force = from_force;
Nan::Callback *callback = new Nan::Callback(Local<Function>::Cast(info[6]));
CreateWorker *worker = new CreateWorker(baton, callback);
if (!info[0]->IsUndefined() && !info[0]->IsNull())
worker->SaveToPersistent("repo", info[0]->ToObject());
if (!info[1]->IsUndefined() && !info[1]->IsNull())
worker->SaveToPersistent("tag_name", info[1]->ToObject());
if (!info[2]->IsUndefined() && !info[2]->IsNull())
worker->SaveToPersistent("target", info[2]->ToObject());
if (!info[3]->IsUndefined() && !info[3]->IsNull())
worker->SaveToPersistent("tagger", info[3]->ToObject());
if (!info[4]->IsUndefined() && !info[4]->IsNull())
worker->SaveToPersistent("message", info[4]->ToObject());
if (!info[5]->IsUndefined() && !info[5]->IsNull())
worker->SaveToPersistent("force", info[5]->ToObject());
Nan::AsyncQueueWorker(worker);
return;
}
void GitTag::CreateWorker::Execute() {
int result = git_tag_create(
baton->oid,baton->repo,baton->tag_name,baton->target,baton->tagger,baton->message,baton->force );
baton->error_code = result;
if (result != GIT_OK && giterr_last() != NULL) {
baton->error = git_error_dup(giterr_last());
}
}
void GitTag::CreateWorker::HandleOKCallback() {
if (baton->error_code == GIT_OK) {
Local<v8::Value> to;
// start convert_to_v8 block
if (baton->oid != NULL) {
// GitOid baton->oid
to = GitOid::New((void *)baton->oid, false);
}
else {
to = Nan::Null();
}
// end convert_to_v8 block
Local<v8::Value> result = to;
Local<v8::Value> argv[2] = {
Nan::Null(),
result
};
callback->Call(2, argv);
} else {
if (baton->error) {
Local<v8::Value> argv[1] = {
Nan::Error(baton->error->message)
};
callback->Call(1, argv);
if (baton->error->message)
free((void *)baton->error->message);
free((void *)baton->error);
} else if (baton->error_code < 0) {
std::queue< Local<v8::Value> > workerArguments;
workerArguments.push(GetFromPersistent("repo"));
workerArguments.push(GetFromPersistent("tag_name"));
workerArguments.push(GetFromPersistent("target"));
workerArguments.push(GetFromPersistent("tagger"));
workerArguments.push(GetFromPersistent("message"));
workerArguments.push(GetFromPersistent("force"));
bool callbackFired = false;
while(!workerArguments.empty()) {
Local<v8::Value> node = workerArguments.front();
workerArguments.pop();
if (
!node->IsObject()
|| node->IsArray()
|| node->IsBooleanObject()
|| node->IsDate()
|| node->IsFunction()
|| node->IsNumberObject()
|| node->IsRegExp()
|| node->IsStringObject()
) {
continue;
}
Local<v8::Object> nodeObj = node->ToObject();
Local<v8::Value> checkValue = nodeObj->GetHiddenValue(Nan::New("NodeGitPromiseError").ToLocalChecked());
if (!checkValue.IsEmpty() && !checkValue->IsNull() && !checkValue->IsUndefined()) {
Local<v8::Value> argv[1] = {
checkValue->ToObject()
};
callback->Call(1, argv);
callbackFired = true;
break;
}
Local<v8::Array> properties = nodeObj->GetPropertyNames();
for (unsigned int propIndex = 0; propIndex < properties->Length(); ++propIndex) {
Local<v8::String> propName = properties->Get(propIndex)->ToString();
Local<v8::Value> nodeToQueue = nodeObj->Get(propName);
if (!nodeToQueue->IsUndefined()) {
workerArguments.push(nodeToQueue);
}
}
}
if (!callbackFired) {
Local<v8::Object> err = Nan::Error("Method create has thrown an error.")->ToObject();
err->Set(Nan::New("errno").ToLocalChecked(), Nan::New(baton->error_code));
Local<v8::Value> argv[1] = {
err
};
callback->Call(1, argv);
}
} else {
callback->Call(0, NULL);
}
}
free((void *)baton->tag_name);
free((void *)baton->message);
delete baton;
}
/*
* @param Repository repo
* @param String tag_name
* @param Object target
* @param Number force
* @param Oid callback
*/
NAN_METHOD(GitTag::CreateLightweight) {
if (info.Length() == 0 || !info[0]->IsObject()) {
return Nan::ThrowError("Repository repo is required.");
}
if (info.Length() == 1 || !info[1]->IsString()) {
return Nan::ThrowError("String tag_name is required.");
}
if (info.Length() == 2 || !info[2]->IsObject()) {
return Nan::ThrowError("Object target is required.");
}
if (info.Length() == 3 || !info[3]->IsNumber()) {
return Nan::ThrowError("Number force is required.");
}
if (info.Length() == 4 || !info[4]->IsFunction()) {
return Nan::ThrowError("Callback is required and must be a Function.");
}
CreateLightweightBaton* baton = new CreateLightweightBaton;
baton->error_code = GIT_OK;
baton->error = NULL;
baton->oid = (git_oid *)malloc(sizeof(git_oid ));
// start convert_from_v8 block
git_repository * from_repo;
from_repo = Nan::ObjectWrap::Unwrap<GitRepository>(info[0]->ToObject())->GetValue();
// end convert_from_v8 block
baton->repo = from_repo;
// start convert_from_v8 block
const char * from_tag_name;
String::Utf8Value tag_name(info[1]->ToString());
from_tag_name = (const char *) strdup(*tag_name);
// end convert_from_v8 block
baton->tag_name = from_tag_name;
// start convert_from_v8 block
const git_object * from_target;
from_target = Nan::ObjectWrap::Unwrap<GitObject>(info[2]->ToObject())->GetValue();
// end convert_from_v8 block
baton->target = from_target;
// start convert_from_v8 block
int from_force;
from_force = (int) info[3]->ToNumber()->Value();
// end convert_from_v8 block
baton->force = from_force;
Nan::Callback *callback = new Nan::Callback(Local<Function>::Cast(info[4]));
CreateLightweightWorker *worker = new CreateLightweightWorker(baton, callback);
if (!info[0]->IsUndefined() && !info[0]->IsNull())
worker->SaveToPersistent("repo", info[0]->ToObject());
if (!info[1]->IsUndefined() && !info[1]->IsNull())
worker->SaveToPersistent("tag_name", info[1]->ToObject());
if (!info[2]->IsUndefined() && !info[2]->IsNull())
worker->SaveToPersistent("target", info[2]->ToObject());
if (!info[3]->IsUndefined() && !info[3]->IsNull())
worker->SaveToPersistent("force", info[3]->ToObject());
Nan::AsyncQueueWorker(worker);
return;
}
void GitTag::CreateLightweightWorker::Execute() {
int result = git_tag_create_lightweight(
baton->oid,baton->repo,baton->tag_name,baton->target,baton->force );
baton->error_code = result;
if (result != GIT_OK && giterr_last() != NULL) {
baton->error = git_error_dup(giterr_last());
}
}
void GitTag::CreateLightweightWorker::HandleOKCallback() {
if (baton->error_code == GIT_OK) {
Local<v8::Value> to;
// start convert_to_v8 block
if (baton->oid != NULL) {
// GitOid baton->oid
to = GitOid::New((void *)baton->oid, false);
}
else {
to = Nan::Null();
}
// end convert_to_v8 block
Local<v8::Value> result = to;
Local<v8::Value> argv[2] = {
Nan::Null(),
result
};
callback->Call(2, argv);
} else {
if (baton->error) {
Local<v8::Value> argv[1] = {
Nan::Error(baton->error->message)
};
callback->Call(1, argv);
if (baton->error->message)
free((void *)baton->error->message);
free((void *)baton->error);
} else if (baton->error_code < 0) {
std::queue< Local<v8::Value> > workerArguments;
workerArguments.push(GetFromPersistent("repo"));
workerArguments.push(GetFromPersistent("tag_name"));
workerArguments.push(GetFromPersistent("target"));
workerArguments.push(GetFromPersistent("force"));
bool callbackFired = false;
while(!workerArguments.empty()) {
Local<v8::Value> node = workerArguments.front();
workerArguments.pop();
if (
!node->IsObject()
|| node->IsArray()
|| node->IsBooleanObject()
|| node->IsDate()
|| node->IsFunction()
|| node->IsNumberObject()
|| node->IsRegExp()
|| node->IsStringObject()
) {
continue;
}
Local<v8::Object> nodeObj = node->ToObject();
Local<v8::Value> checkValue = nodeObj->GetHiddenValue(Nan::New("NodeGitPromiseError").ToLocalChecked());
if (!checkValue.IsEmpty() && !checkValue->IsNull() && !checkValue->IsUndefined()) {
Local<v8::Value> argv[1] = {
checkValue->ToObject()
};
callback->Call(1, argv);
callbackFired = true;
break;
}
Local<v8::Array> properties = nodeObj->GetPropertyNames();
for (unsigned int propIndex = 0; propIndex < properties->Length(); ++propIndex) {
Local<v8::String> propName = properties->Get(propIndex)->ToString();
Local<v8::Value> nodeToQueue = nodeObj->Get(propName);
if (!nodeToQueue->IsUndefined()) {
workerArguments.push(nodeToQueue);
}
}
}
if (!callbackFired) {
Local<v8::Object> err = Nan::Error("Method createLightweight has thrown an error.")->ToObject();
err->Set(Nan::New("errno").ToLocalChecked(), Nan::New(baton->error_code));
Local<v8::Value> argv[1] = {
err
};
callback->Call(1, argv);
}
} else {
callback->Call(0, NULL);
}
}
free((void *)baton->tag_name);
delete baton;
}
/*
* @param Repository repo
* @param String tag_name
*/
NAN_METHOD(GitTag::Delete) {
if (info.Length() == 0 || !info[0]->IsObject()) {
return Nan::ThrowError("Repository repo is required.");
}
if (info.Length() == 1 || !info[1]->IsString()) {
return Nan::ThrowError("String tag_name is required.");
}
if (info.Length() == 2 || !info[2]->IsFunction()) {
return Nan::ThrowError("Callback is required and must be a Function.");
}
DeleteBaton* baton = new DeleteBaton;
baton->error_code = GIT_OK;
baton->error = NULL;
// start convert_from_v8 block
git_repository * from_repo;
from_repo = Nan::ObjectWrap::Unwrap<GitRepository>(info[0]->ToObject())->GetValue();
// end convert_from_v8 block
baton->repo = from_repo;
// start convert_from_v8 block
const char * from_tag_name;
String::Utf8Value tag_name(info[1]->ToString());
from_tag_name = (const char *) strdup(*tag_name);
// end convert_from_v8 block
baton->tag_name = from_tag_name;
Nan::Callback *callback = new Nan::Callback(Local<Function>::Cast(info[2]));
DeleteWorker *worker = new DeleteWorker(baton, callback);
if (!info[0]->IsUndefined() && !info[0]->IsNull())
worker->SaveToPersistent("repo", info[0]->ToObject());
if (!info[1]->IsUndefined() && !info[1]->IsNull())
worker->SaveToPersistent("tag_name", info[1]->ToObject());
Nan::AsyncQueueWorker(worker);
return;
}
void GitTag::DeleteWorker::Execute() {
int result = git_tag_delete(
baton->repo,baton->tag_name );
baton->error_code = result;
if (result != GIT_OK && giterr_last() != NULL) {
baton->error = git_error_dup(giterr_last());
}
}
void GitTag::DeleteWorker::HandleOKCallback() {
if (baton->error_code == GIT_OK) {
Local<v8::Value> result = Nan::Undefined();
Local<v8::Value> argv[2] = {
Nan::Null(),
result
};
callback->Call(2, argv);
} else {
if (baton->error) {
Local<v8::Value> argv[1] = {
Nan::Error(baton->error->message)
};
callback->Call(1, argv);
if (baton->error->message)
free((void *)baton->error->message);
free((void *)baton->error);
} else if (baton->error_code < 0) {
std::queue< Local<v8::Value> > workerArguments;
workerArguments.push(GetFromPersistent("repo"));
workerArguments.push(GetFromPersistent("tag_name"));
bool callbackFired = false;
while(!workerArguments.empty()) {
Local<v8::Value> node = workerArguments.front();
workerArguments.pop();
if (
!node->IsObject()
|| node->IsArray()
|| node->IsBooleanObject()
|| node->IsDate()
|| node->IsFunction()
|| node->IsNumberObject()
|| node->IsRegExp()
|| node->IsStringObject()
) {
continue;
}
Local<v8::Object> nodeObj = node->ToObject();
Local<v8::Value> checkValue = nodeObj->GetHiddenValue(Nan::New("NodeGitPromiseError").ToLocalChecked());
if (!checkValue.IsEmpty() && !checkValue->IsNull() && !checkValue->IsUndefined()) {
Local<v8::Value> argv[1] = {
checkValue->ToObject()
};
callback->Call(1, argv);
callbackFired = true;
break;
}
Local<v8::Array> properties = nodeObj->GetPropertyNames();
for (unsigned int propIndex = 0; propIndex < properties->Length(); ++propIndex) {
Local<v8::String> propName = properties->Get(propIndex)->ToString();
Local<v8::Value> nodeToQueue = nodeObj->Get(propName);
if (!nodeToQueue->IsUndefined()) {
workerArguments.push(nodeToQueue);
}
}
}
if (!callbackFired) {
Local<v8::Object> err = Nan::Error("Method delete has thrown an error.")->ToObject();
err->Set(Nan::New("errno").ToLocalChecked(), Nan::New(baton->error_code));
Local<v8::Value> argv[1] = {
err
};
callback->Call(1, argv);
}
} else {
callback->Call(0, NULL);
}
}
free((void *)baton->tag_name);
delete baton;
}
/*
*/
NAN_METHOD(GitTag::Free) {
Nan::EscapableHandleScope scope;
if (Nan::ObjectWrap::Unwrap<GitTag>(info.This())->GetValue() != NULL) {
git_tag_free(
Nan::ObjectWrap::Unwrap<GitTag>(info.This())->GetValue()
);
Nan::ObjectWrap::Unwrap<GitTag>(info.This())->ClearValue();
}
return info.GetReturnValue().Set(scope.Escape(Nan::Undefined()));
}
/*
* @return Oid result */
NAN_METHOD(GitTag::Id) {
Nan::EscapableHandleScope scope;
const git_oid * result = git_tag_id(
Nan::ObjectWrap::Unwrap<GitTag>(info.This())->GetValue()
);
// null checks on pointers
if (!result) {
return info.GetReturnValue().Set(scope.Escape(Nan::Undefined()));
}
Local<v8::Value> to;
// start convert_to_v8 block
if (result != NULL) {
// GitOid result
to = GitOid::New((void *)result, false);
}
else {
to = Nan::Null();
}
// end convert_to_v8 block
return info.GetReturnValue().Set(scope.Escape(to));
}
/*
* @param Repository repo
* @param Array callback
*/
NAN_METHOD(GitTag::List) {
if (info.Length() == 0 || !info[0]->IsObject()) {
return Nan::ThrowError("Repository repo is required.");
}
if (info.Length() == 1 || !info[1]->IsFunction()) {
return Nan::ThrowError("Callback is required and must be a Function.");
}
ListBaton* baton = new ListBaton;
baton->error_code = GIT_OK;
baton->error = NULL;
baton->tag_names = (git_strarray *)malloc(sizeof(git_strarray ));
// start convert_from_v8 block
git_repository * from_repo;
from_repo = Nan::ObjectWrap::Unwrap<GitRepository>(info[0]->ToObject())->GetValue();
// end convert_from_v8 block
baton->repo = from_repo;
Nan::Callback *callback = new Nan::Callback(Local<Function>::Cast(info[1]));
ListWorker *worker = new ListWorker(baton, callback);
if (!info[0]->IsUndefined() && !info[0]->IsNull())
worker->SaveToPersistent("repo", info[0]->ToObject());
Nan::AsyncQueueWorker(worker);
return;
}
void GitTag::ListWorker::Execute() {
int result = git_tag_list(
baton->tag_names,baton->repo );
}
void GitTag::ListWorker::HandleOKCallback() {
if (baton->error_code == GIT_OK) {
Local<v8::Value> to;
// start convert_to_v8 block
Local<Array> tmpArray = Nan::New<Array>(baton->tag_names->count);
for (unsigned int i = 0; i < baton->tag_names->count; i++) {
Nan::Set(tmpArray, Nan::New<Number>(i), Nan::New<String>(baton->tag_names->strings[i]).ToLocalChecked());
}
to = tmpArray;
// end convert_to_v8 block
Local<v8::Value> result = to;
Local<v8::Value> argv[2] = {
Nan::Null(),
result
};
callback->Call(2, argv);
} else {
if (baton->error) {
Local<v8::Value> argv[1] = {
Nan::Error(baton->error->message)
};
callback->Call(1, argv);
if (baton->error->message)
free((void *)baton->error->message);
free((void *)baton->error);
} else if (baton->error_code < 0) {
std::queue< Local<v8::Value> > workerArguments;
workerArguments.push(GetFromPersistent("repo"));
bool callbackFired = false;
while(!workerArguments.empty()) {
Local<v8::Value> node = workerArguments.front();
workerArguments.pop();
if (
!node->IsObject()
|| node->IsArray()
|| node->IsBooleanObject()
|| node->IsDate()
|| node->IsFunction()
|| node->IsNumberObject()
|| node->IsRegExp()
|| node->IsStringObject()
) {
continue;
}
Local<v8::Object> nodeObj = node->ToObject();
Local<v8::Value> checkValue = nodeObj->GetHiddenValue(Nan::New("NodeGitPromiseError").ToLocalChecked());
if (!checkValue.IsEmpty() && !checkValue->IsNull() && !checkValue->IsUndefined()) {
Local<v8::Value> argv[1] = {
checkValue->ToObject()
};
callback->Call(1, argv);
callbackFired = true;
break;
}
Local<v8::Array> properties = nodeObj->GetPropertyNames();
for (unsigned int propIndex = 0; propIndex < properties->Length(); ++propIndex) {
Local<v8::String> propName = properties->Get(propIndex)->ToString();
Local<v8::Value> nodeToQueue = nodeObj->Get(propName);
if (!nodeToQueue->IsUndefined()) {
workerArguments.push(nodeToQueue);
}
}
}
if (!callbackFired) {
Local<v8::Object> err = Nan::Error("Method list has thrown an error.")->ToObject();
err->Set(Nan::New("errno").ToLocalChecked(), Nan::New(baton->error_code));
Local<v8::Value> argv[1] = {
err
};
callback->Call(1, argv);
}
} else {
callback->Call(0, NULL);
}
free((void*)baton->tag_names);
}
free((void *)baton->tag_names);
delete baton;
}
/*
* @param Strarray tag_names
* @param String pattern
* @param Repository repo
* @return Number result */
NAN_METHOD(GitTag::ListMatch) {
Nan::EscapableHandleScope scope;
if (info.Length() == 0 || !(Nan::To<bool>(info[0]).FromJust())) {
return Nan::ThrowError("Array, String Object, or string tag_names is required.");
}
if (info.Length() == 1 || !info[1]->IsString()) {
return Nan::ThrowError("String pattern is required.");
}
if (info.Length() == 2 || !info[2]->IsObject()) {
return Nan::ThrowError("Repository repo is required.");
}
// start convert_from_v8 block
git_strarray * from_tag_names;
from_tag_names = StrArrayConverter::Convert(info[0]);
// end convert_from_v8 block
// start convert_from_v8 block
const char * from_pattern;
String::Utf8Value pattern(info[1]->ToString());
from_pattern = (const char *) strdup(*pattern);
// end convert_from_v8 block
// start convert_from_v8 block
git_repository * from_repo;
from_repo = Nan::ObjectWrap::Unwrap<GitRepository>(info[2]->ToObject())->GetValue();
// end convert_from_v8 block
int result = git_tag_list_match(
from_tag_names
,from_pattern
,from_repo
);
Local<v8::Value> to;
// start convert_to_v8 block
to = Nan::New<Number>( result);
// end convert_to_v8 block
return info.GetReturnValue().Set(scope.Escape(to));
}
/*
* @param Repository repo
* @param Oid id
* @param Tag callback
*/
NAN_METHOD(GitTag::Lookup) {
if (info.Length() == 0 || !info[0]->IsObject()) {
return Nan::ThrowError("Repository repo is required.");
}
if (info.Length() == 1
|| (!info[1]->IsObject() && !info[1]->IsString())) {
return Nan::ThrowError("Oid id is required.");
}
if (info.Length() == 2 || !info[2]->IsFunction()) {
return Nan::ThrowError("Callback is required and must be a Function.");
}
LookupBaton* baton = new LookupBaton;
baton->error_code = GIT_OK;
baton->error = NULL;
// start convert_from_v8 block
git_repository * from_repo;
from_repo = Nan::ObjectWrap::Unwrap<GitRepository>(info[0]->ToObject())->GetValue();
// end convert_from_v8 block
baton->repo = from_repo;
// start convert_from_v8 block
const git_oid * from_id;
if (info[1]->IsString()) {
// Try and parse in a string to a git_oid
String::Utf8Value oidString(info[1]->ToString());
git_oid *oidOut = (git_oid *)malloc(sizeof(git_oid));
if (git_oid_fromstr(oidOut, (const char *) strdup(*oidString)) != GIT_OK) {
free(oidOut);
if (giterr_last()) {
return Nan::ThrowError(giterr_last()->message);
} else {
return Nan::ThrowError("Unknown Error");
}
}
from_id = oidOut;
}
else {
from_id = Nan::ObjectWrap::Unwrap<GitOid>(info[1]->ToObject())->GetValue();
}
// end convert_from_v8 block
baton->id = from_id;
baton->idNeedsFree = info[1]->IsString();
Nan::Callback *callback = new Nan::Callback(Local<Function>::Cast(info[2]));
LookupWorker *worker = new LookupWorker(baton, callback);
if (!info[0]->IsUndefined() && !info[0]->IsNull())
worker->SaveToPersistent("repo", info[0]->ToObject());
if (!info[1]->IsUndefined() && !info[1]->IsNull())
worker->SaveToPersistent("id", info[1]->ToObject());
Nan::AsyncQueueWorker(worker);
return;
}
void GitTag::LookupWorker::Execute() {
int result = git_tag_lookup(
&baton->out,baton->repo,baton->id );
baton->error_code = result;
if (result != GIT_OK && giterr_last() != NULL) {
baton->error = git_error_dup(giterr_last());
}
}
void GitTag::LookupWorker::HandleOKCallback() {
if (baton->error_code == GIT_OK) {
Local<v8::Value> to;
// start convert_to_v8 block
if (baton->out != NULL) {
// GitTag baton->out
to = GitTag::New((void *)baton->out, false);
}
else {
to = Nan::Null();
}
// end convert_to_v8 block
Local<v8::Value> result = to;
Local<v8::Value> argv[2] = {
Nan::Null(),
result
};
callback->Call(2, argv);
} else {
if (baton->error) {
Local<v8::Value> argv[1] = {
Nan::Error(baton->error->message)
};
callback->Call(1, argv);
if (baton->error->message)
free((void *)baton->error->message);
free((void *)baton->error);
} else if (baton->error_code < 0) {
std::queue< Local<v8::Value> > workerArguments;
workerArguments.push(GetFromPersistent("repo"));
workerArguments.push(GetFromPersistent("id"));
bool callbackFired = false;
while(!workerArguments.empty()) {
Local<v8::Value> node = workerArguments.front();
workerArguments.pop();
if (
!node->IsObject()
|| node->IsArray()
|| node->IsBooleanObject()
|| node->IsDate()
|| node->IsFunction()
|| node->IsNumberObject()
|| node->IsRegExp()
|| node->IsStringObject()
) {
continue;
}
Local<v8::Object> nodeObj = node->ToObject();
Local<v8::Value> checkValue = nodeObj->GetHiddenValue(Nan::New("NodeGitPromiseError").ToLocalChecked());
if (!checkValue.IsEmpty() && !checkValue->IsNull() && !checkValue->IsUndefined()) {
Local<v8::Value> argv[1] = {
checkValue->ToObject()
};
callback->Call(1, argv);
callbackFired = true;
break;
}
Local<v8::Array> properties = nodeObj->GetPropertyNames();
for (unsigned int propIndex = 0; propIndex < properties->Length(); ++propIndex) {
Local<v8::String> propName = properties->Get(propIndex)->ToString();
Local<v8::Value> nodeToQueue = nodeObj->Get(propName);
if (!nodeToQueue->IsUndefined()) {
workerArguments.push(nodeToQueue);
}
}
}
if (!callbackFired) {
Local<v8::Object> err = Nan::Error("Method lookup has thrown an error.")->ToObject();
err->Set(Nan::New("errno").ToLocalChecked(), Nan::New(baton->error_code));
Local<v8::Value> argv[1] = {
err
};
callback->Call(1, argv);
}
} else {
callback->Call(0, NULL);
}
}
if (baton->idNeedsFree) {
baton->idNeedsFree = false;
free((void *)baton->id);
}
delete baton;
}
/*
* @param Repository repo
* @param Oid id
* @param Number len
* @param Tag callback
*/
NAN_METHOD(GitTag::LookupPrefix) {
if (info.Length() == 0 || !info[0]->IsObject()) {
return Nan::ThrowError("Repository repo is required.");
}
if (info.Length() == 1
|| (!info[1]->IsObject() && !info[1]->IsString())) {
return Nan::ThrowError("Oid id is required.");
}
if (info.Length() == 2 || !info[2]->IsNumber()) {
return Nan::ThrowError("Number len is required.");
}
if (info.Length() == 3 || !info[3]->IsFunction()) {
return Nan::ThrowError("Callback is required and must be a Function.");
}
LookupPrefixBaton* baton = new LookupPrefixBaton;
baton->error_code = GIT_OK;
baton->error = NULL;
// start convert_from_v8 block
git_repository * from_repo;
from_repo = Nan::ObjectWrap::Unwrap<GitRepository>(info[0]->ToObject())->GetValue();
// end convert_from_v8 block
baton->repo = from_repo;
// start convert_from_v8 block
const git_oid * from_id;
if (info[1]->IsString()) {
// Try and parse in a string to a git_oid
String::Utf8Value oidString(info[1]->ToString());
git_oid *oidOut = (git_oid *)malloc(sizeof(git_oid));
if (git_oid_fromstr(oidOut, (const char *) strdup(*oidString)) != GIT_OK) {
free(oidOut);
if (giterr_last()) {
return Nan::ThrowError(giterr_last()->message);
} else {
return Nan::ThrowError("Unknown Error");
}
}
from_id = oidOut;
}
else {
from_id = Nan::ObjectWrap::Unwrap<GitOid>(info[1]->ToObject())->GetValue();
}
// end convert_from_v8 block
baton->id = from_id;
baton->idNeedsFree = info[1]->IsString();
// start convert_from_v8 block
size_t from_len;
from_len = (size_t) info[2]->ToNumber()->Value();
// end convert_from_v8 block
baton->len = from_len;
Nan::Callback *callback = new Nan::Callback(Local<Function>::Cast(info[3]));
LookupPrefixWorker *worker = new LookupPrefixWorker(baton, callback);
if (!info[0]->IsUndefined() && !info[0]->IsNull())
worker->SaveToPersistent("repo", info[0]->ToObject());
if (!info[1]->IsUndefined() && !info[1]->IsNull())
worker->SaveToPersistent("id", info[1]->ToObject());
if (!info[2]->IsUndefined() && !info[2]->IsNull())
worker->SaveToPersistent("len", info[2]->ToObject());
Nan::AsyncQueueWorker(worker);
return;
}
void GitTag::LookupPrefixWorker::Execute() {
int result = git_tag_lookup_prefix(
&baton->out,baton->repo,baton->id,baton->len );
baton->error_code = result;
if (result != GIT_OK && giterr_last() != NULL) {
baton->error = git_error_dup(giterr_last());
}
}
void GitTag::LookupPrefixWorker::HandleOKCallback() {
if (baton->error_code == GIT_OK) {
Local<v8::Value> to;
// start convert_to_v8 block
if (baton->out != NULL) {
// GitTag baton->out
to = GitTag::New((void *)baton->out, false);
}
else {
to = Nan::Null();
}
// end convert_to_v8 block
Local<v8::Value> result = to;
Local<v8::Value> argv[2] = {
Nan::Null(),
result
};
callback->Call(2, argv);
} else {
if (baton->error) {
Local<v8::Value> argv[1] = {
Nan::Error(baton->error->message)
};
callback->Call(1, argv);
if (baton->error->message)
free((void *)baton->error->message);
free((void *)baton->error);
} else if (baton->error_code < 0) {
std::queue< Local<v8::Value> > workerArguments;
workerArguments.push(GetFromPersistent("repo"));
workerArguments.push(GetFromPersistent("id"));
workerArguments.push(GetFromPersistent("len"));
bool callbackFired = false;
while(!workerArguments.empty()) {
Local<v8::Value> node = workerArguments.front();
workerArguments.pop();
if (
!node->IsObject()
|| node->IsArray()
|| node->IsBooleanObject()
|| node->IsDate()
|| node->IsFunction()
|| node->IsNumberObject()
|| node->IsRegExp()
|| node->IsStringObject()
) {
continue;
}
Local<v8::Object> nodeObj = node->ToObject();
Local<v8::Value> checkValue = nodeObj->GetHiddenValue(Nan::New("NodeGitPromiseError").ToLocalChecked());
if (!checkValue.IsEmpty() && !checkValue->IsNull() && !checkValue->IsUndefined()) {
Local<v8::Value> argv[1] = {
checkValue->ToObject()
};
callback->Call(1, argv);
callbackFired = true;
break;
}
Local<v8::Array> properties = nodeObj->GetPropertyNames();
for (unsigned int propIndex = 0; propIndex < properties->Length(); ++propIndex) {
Local<v8::String> propName = properties->Get(propIndex)->ToString();
Local<v8::Value> nodeToQueue = nodeObj->Get(propName);
if (!nodeToQueue->IsUndefined()) {
workerArguments.push(nodeToQueue);
}
}
}
if (!callbackFired) {
Local<v8::Object> err = Nan::Error("Method lookupPrefix has thrown an error.")->ToObject();
err->Set(Nan::New("errno").ToLocalChecked(), Nan::New(baton->error_code));
Local<v8::Value> argv[1] = {
err
};
callback->Call(1, argv);
}
} else {
callback->Call(0, NULL);
}
}
if (baton->idNeedsFree) {
baton->idNeedsFree = false;
free((void *)baton->id);
}
delete baton;
}
/*
* @return String result */
NAN_METHOD(GitTag::Message) {
Nan::EscapableHandleScope scope;
const char * result = git_tag_message(
Nan::ObjectWrap::Unwrap<GitTag>(info.This())->GetValue()
);
// null checks on pointers
if (!result) {
return info.GetReturnValue().Set(scope.Escape(Nan::Undefined()));
}
Local<v8::Value> to;
// start convert_to_v8 block
if (result){
to = Nan::New<String>(result).ToLocalChecked();
}
else {
to = Nan::Null();
}
// end convert_to_v8 block
return info.GetReturnValue().Set(scope.Escape(to));
}
/*
* @return String result */
NAN_METHOD(GitTag::Name) {
Nan::EscapableHandleScope scope;
const char * result = git_tag_name(
Nan::ObjectWrap::Unwrap<GitTag>(info.This())->GetValue()
);
// null checks on pointers
if (!result) {
return info.GetReturnValue().Set(scope.Escape(Nan::Undefined()));
}
Local<v8::Value> to;
// start convert_to_v8 block
if (result){
to = Nan::New<String>(result).ToLocalChecked();
}
else {
to = Nan::Null();
}
// end convert_to_v8 block
return info.GetReturnValue().Set(scope.Escape(to));
}
/*
* @return Repository result */
NAN_METHOD(GitTag::Owner) {
Nan::EscapableHandleScope scope;
git_repository * result = git_tag_owner(
Nan::ObjectWrap::Unwrap<GitTag>(info.This())->GetValue()
);
// null checks on pointers
if (!result) {
return info.GetReturnValue().Set(scope.Escape(Nan::Undefined()));
}
Local<v8::Value> to;
// start convert_to_v8 block
if (result != NULL) {
// GitRepository result
to = GitRepository::New((void *)result, false);
}
else {
to = Nan::Null();
}
// end convert_to_v8 block
return info.GetReturnValue().Set(scope.Escape(to));
}
/*
* @param Object tag_target_out
* @return Number result */
NAN_METHOD(GitTag::Peel) {
Nan::EscapableHandleScope scope;
if (info.Length() == 0 || !info[0]->IsObject()) {
return Nan::ThrowError("Object tag_target_out is required.");
}
// start convert_from_v8 block
git_object ** from_tag_target_out;
from_tag_target_out = Nan::ObjectWrap::Unwrap<GitObject>(info[0]->ToObject())->GetRefValue();
// end convert_from_v8 block
int result = git_tag_peel(
from_tag_target_out
,Nan::ObjectWrap::Unwrap<GitTag>(info.This())->GetValue()
);
Local<v8::Value> to;
// start convert_to_v8 block
to = Nan::New<Number>( result);
// end convert_to_v8 block
return info.GetReturnValue().Set(scope.Escape(to));
}
/*
* @return Signature result */
NAN_METHOD(GitTag::Tagger) {
Nan::EscapableHandleScope scope;
const git_signature * result = git_tag_tagger(
Nan::ObjectWrap::Unwrap<GitTag>(info.This())->GetValue()
);
// null checks on pointers
if (!result) {
return info.GetReturnValue().Set(scope.Escape(Nan::Undefined()));
}
Local<v8::Value> to;
// start convert_to_v8 block
if (result != NULL) {
// GitSignature result
to = GitSignature::New((void *)result, false);
}
else {
to = Nan::Null();
}
// end convert_to_v8 block
return info.GetReturnValue().Set(scope.Escape(to));
}
/*
* @return Object target_out */
NAN_METHOD(GitTag::Target) {
Nan::EscapableHandleScope scope;
git_object * target_out = 0;
int result = git_tag_target(
&target_out
,Nan::ObjectWrap::Unwrap<GitTag>(info.This())->GetValue()
);
Local<v8::Value> to;
// start convert_to_v8 block
if (target_out != NULL) {
// GitObject target_out
to = GitObject::New((void *)target_out, false);
}
else {
to = Nan::Null();
}
// end convert_to_v8 block
return info.GetReturnValue().Set(scope.Escape(to));
}
/*
* @return Oid result */
NAN_METHOD(GitTag::TargetId) {
Nan::EscapableHandleScope scope;
const git_oid * result = git_tag_target_id(
Nan::ObjectWrap::Unwrap<GitTag>(info.This())->GetValue()
);
// null checks on pointers
if (!result) {
return info.GetReturnValue().Set(scope.Escape(Nan::Undefined()));
}
Local<v8::Value> to;
// start convert_to_v8 block
if (result != NULL) {
// GitOid result
to = GitOid::New((void *)result, false);
}
else {
to = Nan::Null();
}
// end convert_to_v8 block
return info.GetReturnValue().Set(scope.Escape(to));
}
/*
* @return Number result */
NAN_METHOD(GitTag::TargetType) {
Nan::EscapableHandleScope scope;
git_otype result = git_tag_target_type(
Nan::ObjectWrap::Unwrap<GitTag>(info.This())->GetValue()
);
Local<v8::Value> to;
// start convert_to_v8 block
to = Nan::New<Number>( result);
// end convert_to_v8 block
return info.GetReturnValue().Set(scope.Escape(to));
}
Nan::Persistent<Function> GitTag::constructor_template;
| [
"maarten.vanwingerden@hotmail.com"
] | maarten.vanwingerden@hotmail.com |
732c47ab46c1ee26b2216524892e3c34d20f3a34 | 2ce066f36aaa5e24ed8d07c3039b6b9e5cf12877 | /View/ModulAccount/account_view.h | 15acd05cc1c71e66098b6d852a1f78666d3d6909 | [] | no_license | Euclidis/Dictionary | b638c968dba1bc84e5467afca5ab1e601aaca07e | a9fc540a13b64c0eca480829780742218ecb8d48 | refs/heads/master | 2020-12-24T16:50:22.218791 | 2016-03-13T11:59:37 | 2016-03-13T11:59:37 | 52,585,927 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,071 | h | #ifndef ACCOUNTVIEW_H
#define ACCOUNTVIEW_H
#ifndef ACCOUNTVIEWINTERFACE_H
#include "account_viewinterface.h"
#endif
namespace Ui {
class AccountView;
}
class AccountView :
public QWidget,
public AccountViewInterface
{
Q_OBJECT
public:
explicit AccountView(QWidget *parent = 0);
~AccountView();
//______________AccountViewInterfaceAccount__
void messageNameUserEmpty();
void messageNameUserExist();
void messageNameUserNotFound();
void showView();
void hideView();
void setListLK(QAbstractItemModel* model);
void setListLL(QAbstractItemModel* model);
void initialize_();
//____________________________________
private:
QAbstractItemModel* listLK_ = nullptr;
QAbstractItemModel* listLL_ = nullptr;
private:
void message(const QString& text);
private slots:
void on_pbLogin_clicked();
void on_pbRegister_clicked();
void on_lwLK_clicked(const QModelIndex &index);
void on_lwLL_clicked(const QModelIndex &index);
private:
Ui::AccountView *ui;
};
#endif // ACCOUNTVIEW_H
| [
"amirberetar@gmail.com"
] | amirberetar@gmail.com |
2de3bf4747419ebbc7c192ded50ec98231e7b421 | 2aef8e6ed65c879ba9557d34bb5c8ae6a7eda4f1 | /cpp/nearest_lucky_numbers_329.cpp | 0cdfd3ea807417be782e304cf729a48cddbd53d7 | [] | no_license | Anarcroth/daily-code-challenges | 987d1597eb0bd96b4f932874f084e41deb6fee69 | 46e9add896855aee3028858c06f7e46eb453d4aa | refs/heads/master | 2021-06-04T17:30:03.339100 | 2018-12-29T16:31:14 | 2020-01-10T12:35:05 | 109,251,734 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,331 | cpp | // Description
//
// A Lucky Number is a natural number in a set which is generated by a certain "sieve". This sieve is similar to the Sieve of Eratosthenes that generates the primes, but it eliminates numbers based on their position in the remaining set, instead of their value (or position in the initial set of natural numbers).
// The set of lucky numbers can be obtained by:-
// Begin with a list of integers starting with 1:
// 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
// Starting with 1, remove every other element (i.e. every even number) from this set. We are left with:
// 1 3 5 7 9 11 13 15 17 19 21 23 25
// After 1, the next number in the set is 3. So, remove every 3rd number. Clearly, 5 is removed because it's the third number in the above set. Go on and keep removing every 3rd number.
// Your new set is:
// 1 3 7 9 13 15 19 21 25...
// Here, the next remaining number you have after 3 is 7. Now, at this point, it's obvious that there's no way 1 and 3 are ever getting eliminated. Thus, we can conclude that 1 and 3 are lucky numbers.
// Now remove every 7th number. Clearly, 19 would be the first to be wiped out.
// You're left with:
// 1 3 7 9 13 15 21 25 ...
// Now it's time to proceed to the next remaining number after 7, i.e., 9. Remove every 9th number. Note that at this point, 7 cannot be eliminated. 7 is a lucky number too.
// Keep proceeding in a similar fashion in order to get a list of lucky numbers.
// Numbers remaining after this procedure has been carried out completely are called lucky numbers. The first few are
// 1, 3, 7, 9, 13, 15, 21, 25, 31, 33, 37, ...
// Today's challenge is to find the nearest lucky number. This might remind you of Challenge #326. In fact, this has been inspired from it. Bruteforcing is the most obvious option, but it's certainly not the most efficient.
// Input Description
//
// The input will be a positive integer.
// Output Description
//
// The output will be
// previous lucky number < n < next lucky number
// where n is your input.
// If n is a lucky number, then display
// n is a lucky number.
// Challenge Input
//
// 103
// 225
// 997
// Challenge Output
//
// 99 < 103 < 105
// 223 < 225 < 231
// 997 is a lucky number
// Bonus
//
// Find every lucky number all the way up to 500010,000,000 and post your the time it took to run. This is so that you can compete amongst everyone else to see who has the most efficient one.
#include <iostream>
#include <vector>
int main()
{
std::cout << "Enter a number: ";
int n;
std::cin >> n;
std::vector<int> numbers;
for (int i = 1; i <= n; i++)
{
numbers.push_back(i);
}
for (size_t i = 1; i < numbers.size(); i++)
{
numbers.erase(numbers.begin() + i);
}
int step = 1;
while (step < (int)numbers.size())
{
for (int i = numbers.at(step) - 1; i < (int)numbers.size(); i += numbers[step] - 1)
{
numbers.erase(numbers.begin() + step);
}
step += 1;
}
for (auto it = numbers.begin(); it != numbers.end(); ++it)
{
if (*it == n)
{
std::cout << "The Lucky number is: " << *it << std::endl;
}
else
{
std::cout << *--it << " " << n << " " << *++it << std::endl;
}
}
return 0;
}
| [
"mnestorov@protonmail.com"
] | mnestorov@protonmail.com |
377387af2c1646aefa7ae6715f9b2eaa332bb3de | a9acfe1965a5a6c197cffe6ebcdd35140b0ee1ca | /main.cpp | 25715b5e867017c7679b335e6aaf5140932b04af | [] | no_license | kindow/LaneLineDetection | d50d6b6cd44a3b59029d8a16d7fce9df8ceaeae3 | 7406792fe49cf82c30715e2fa20cb84447f879d2 | refs/heads/master | 2022-01-10T13:39:13.276112 | 2019-07-09T17:32:34 | 2019-07-09T17:32:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,860 | cpp | //
// main.cpp
// opencv4_test
//
// Created by Rahul Aggarwal on 6/26/19.
// Copyright © 2019 Rahul Aggarwal. All rights reserved.
//
#include <opencv2/opencv.hpp>
#include "cpuUtils.hpp"
#include <iostream>
#include <stdio.h>
#include "LaneLine.hpp"
#include "LaneLineHistory.hpp"
#include "AdvancedLaneDetectorWithMemory.hpp"
int main(int argc, char** argv)
{
cv::String imageNames[8];
for (int i = 1; i < 7; i++) {
imageNames[i-1] = cv::String("/Users/Infinity/Desktop/test_images/test" + std::to_string(i) + ".jpg");
}
imageNames[6] = cv::String("/Users/Infinity/Desktop/test_images/straight_lines1.jpg");
imageNames[7] = cv::String("/Users/Infinity/Desktop/test_images/straight_lines2.jpg");
cv::Mat straight_lines1 = cv::imread(imageNames[7], cv::IMREAD_COLOR);
cv:: Mat test6 = cv::imread(imageNames[5], cv::IMREAD_COLOR);
cv::Mat test5 = cv::imread(imageNames[4], cv::IMREAD_COLOR);
if(test6.empty() || straight_lines1.empty() || test5.empty()) {
std::cout << "Could not open or find the image" << std::endl;
return -1;
}
//Video testing
//cv::VideoCapture cap(cv::String("/Users/Infinity/Desktop/test_images/project_video.mp4"));
cv::VideoCapture cap(0);
cv::Mat frame;
if (!cap.isOpened()) {
throw "Error when reading the file";
}
//std::vector<cv::Point2f> src_pts{cv::Point2f(210, 720 - 1), cv::Point2f(595, 450), cv::Point2f(690, 450), cv::Point2f(1110, 720 - 1)};
//std::vector<cv::Point2f> dst_pts{cv::Point2f(200, 720 - 1), cv::Point2f(200, 0), cv::Point2f(1000, 0), cv::Point2f(1000, 720 - 1)};
std::vector<cv::Point2f> src_pts{cv::Point2f(105, 359), cv::Point2f(297, 225), cv::Point2f(345, 225), cv::Point2f(555, 359)};
std::vector<cv::Point2f> dst_pts{cv::Point2f(100, 359), cv::Point2f(100, 0), cv::Point2f(500, 0), cv::Point2f(500, 359)};
cv::Mat M_psp = cv::getPerspectiveTransform(src_pts, dst_pts);
//AdvancedLaneDetectorWithMemory ld(src_pts, dst_pts, 20, 100, 50);
AdvancedLaneDetectorWithMemory ld(src_pts, dst_pts, 20, 100, 50, cv::Size(640, 360));
cv::Mat channels[3];
while(true) {
cap >> frame;
//std::cout << frame.size() << std::endl;
if(frame.empty()) {
break;
}
/*cv::resize(frame, frame, cv::Size(640, 360));
cv::Mat test = cpu::combinedSobelThresholdImage(frame);
cv::warpPerspective(test, test, M_psp, cv::Size(test.cols, test.rows));
std::array<LaneLine, 2> laneLines = ld.computeLaneLines(test);
ld.drawLaneLines(test, frame, laneLines[0], laneLines[1]);*/
ld.processImage(frame);
cv::imshow("Display Window", frame);
if(cv::waitKey(1) >= 0) {
break;
}
}
cv::waitKey(0);
return 0;
}
| [
"rahulaggarwal965@gmail.com"
] | rahulaggarwal965@gmail.com |
7dbbf7696884555192b07035e46d5067928e43a3 | 9fccdc430b35121301d9a2e3ef4143f4a74e0f36 | /include/nbdl/concept/Store.hpp | db0a91f4193024b3fec7d32e56a17a8dc2413066 | [
"BSL-1.0"
] | permissive | drorspei/nbdl | 2668e49e1fa5147a59a2788e21af57d4aa579dc2 | 6ebac56d8d6910e7271819432febb5d0b76be68b | refs/heads/master | 2020-05-21T01:05:02.193382 | 2019-02-12T03:35:33 | 2019-02-12T03:35:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 641 | hpp | //
// Copyright Jason Rice 2016
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef NBDL_CONCEPT_STORE_HPP
#define NBDL_CONCEPT_STORE_HPP
#include <nbdl/fwd/concept/Store.hpp>
#include <nbdl/fwd/match.hpp>
#include <boost/hana/core/default.hpp>
#include <boost/hana/core/tag_of.hpp>
namespace nbdl
{
namespace hana = boost::hana;
template <typename T>
struct Store
{
using Tag = typename hana::tag_of<T>::type;
static constexpr bool value = !hana::is_default<nbdl::match_impl<Tag>>::value;
};
}
#endif
| [
"ricejasonf@gmail.com"
] | ricejasonf@gmail.com |
4388689d95289590cd1c6f9d84e7bb4c58728da0 | 7ea36abac559442702154d80254ea218c2b176d0 | /cpp/cpp2/cpp2.cpp | ee3c7b064ab7d4d2f1823636a2f2f6611fcfbcf8 | [] | no_license | danzaleta/c_cpp | 9dd30f112cf01cc784a1729139d69571684ac660 | 4cd9c31e223ccc241ded4a915a28e061e84ed710 | refs/heads/master | 2023-07-18T04:42:48.326575 | 2021-09-07T17:04:07 | 2021-09-07T17:04:07 | 304,169,853 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,156 | cpp | #include <iostream>
using namespace std;
int main(int argc, char const *argv[])
{
// SETTINGS
bool gameOn = true;
//USER INFO
string name;
int edad;
int peso;
// CASES
int option;
int arr[10];
while (gameOn)
{
cout << "[0] Nueva partida \n[1] Continuar \n[2] Cargar \n[3] Salir" << endl;
cin >> option;
switch (option)
{
case 0:
cout << "Usuario:" << endl;
cin >> name;
cout << "Edad:" << endl;
cin >> edad;
cout << "Peso:" << endl;
cin >> peso;
cout << "Usuario: " << name <<endl;
cout << "Edad: " << edad << " anios" << endl;
cout << "Peso: " << peso << " kg" <<endl;
break;
case 1:
break;
case 2:
break;
case 3:
cout << "Saliendo..." << endl;
gameOn = false;
break;
default:
cout << "Entrada incorrecta" << endl;
break;
}
}
return 0;
}
| [
"zaletadaniel@gmail.com"
] | zaletadaniel@gmail.com |
45c46a692879a16f68fa28c542755cc18cb49df4 | 2dbbcbdceb9c3e1647a401103bf55afabe156eac | /sca/samples/BigBank/Accounts/AccountServiceImpl_AccountDataService_Proxy.h | ff5c6e6d8779052b58496ce94cef81dc805df470 | [
"Apache-2.0"
] | permissive | lelou13/tuscany-sca-cpp | bd30f5967f0c3a95382d80f38ee41a16ec7420ca | b06cb5b2608c0802c15c75c708589e82a9c60e2d | refs/heads/cpp-M1 | 2021-01-15T08:04:32.276885 | 2009-11-16T06:23:13 | 2009-11-16T06:23:13 | 49,079,719 | 0 | 0 | null | 2016-01-05T16:58:49 | 2016-01-05T16:58:49 | null | UTF-8 | C++ | false | false | 1,513 | h | /*
* Copyright 2005 The Apache Software Foundation or its licensors, as applicable.
*
* 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.
*/
#if defined(WIN32) || defined (_WINDOWS)
#pragma warning(disable: 4786)
#endif
#ifndef AccountServiceImpl_AccountDataService_Proxy_h
#define AccountServiceImpl_AccountDataService_Proxy_h
#include "AccountDataService.h"
#include "tuscany/sca/core/ServiceWrapper.h"
class AccountServiceImpl_AccountDataService_Proxy : public com::bigbank::account::AccountDataService
{
public:
AccountServiceImpl_AccountDataService_Proxy(tuscany::sca::ServiceWrapper*);
virtual ~AccountServiceImpl_AccountDataService_Proxy();
virtual commonj::sdo::DataObjectPtr getCheckingAccount(const char* id);
virtual commonj::sdo::DataObjectPtr getSavingsAccount(const char* id);
virtual commonj::sdo::DataObjectPtr getStockAccount(const char* id);
private:
tuscany::sca::ServiceWrapper* target;
};
#endif // AccountServiceImpl_AccountDataService_Proxy_h
| [
"edslattery@apache.org"
] | edslattery@apache.org |
925dfb4988476ce5b87a8c8b466a7130d072b798 | 17cc523c6bfd5b5146cc9152bad60d138cb20a2f | /Castle/CustomGlow.cpp | 1b20f7c67921b3c519550cc103c130710c4a89c9 | [] | no_license | MyCoolCheats/Antario | a1e631fccb00445ba8f31491ea8f479bde134bb9 | fe49c8413935740b69f356406b5ec6417de21e11 | refs/heads/master | 2021-07-19T21:15:24.313243 | 2017-10-24T12:08:30 | 2017-10-24T12:08:30 | 108,400,816 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,288 | cpp | #include "Features.h"
std::vector<std::pair<int, int>> custom_glow_entities;
void CustomGlow::FrameStageNotify(ClientFrameStage_t stage)
{
// Skip reserved slots that are guaranteed to be managed by the engine.
//scalar => zero-initialization because c++98
//68 because 64-67 are used by some useless shit check it urself with cl_findent
for (int i{68}; i < pEntityList->GetHighestEntityIndex(); i++)
{
C_BaseEntity* entity = pEntityList->GetClientEntity(i);
// Register custom entities into the glow object definitions array.
if (pEngine->IsInGame() && entity && entity->GetClientClass()->m_ClassID == EClassIds::CBaseAnimating)
{
if (!pGlowManager->HasGlowEffect(entity))
{
int array_index = pGlowManager->RegisterGlowObject(entity);
if (array_index != -1)
custom_glow_entities.emplace_back(i, array_index);
}
}
else
{
// Remove any entities that no longer exist.
auto iterator = std::find_if(custom_glow_entities.begin(), custom_glow_entities.end(),
[&](const std::pair<int, int>& p) {
return p.first == i;
}
);
if (iterator != custom_glow_entities.end())
{
pGlowManager->UnregisterGlowObject(iterator->second);
custom_glow_entities.erase(iterator);
}
}
}
}
| [
"noreply@github.com"
] | MyCoolCheats.noreply@github.com |
6ae77c142a3ae790adb180205fa403acad8c7472 | 3c5b5f9853eba27d74ca8d2817c3b75d5eddb6f3 | /Wave2.h | 84d3bcb740d23283b10a4216cef2843dd8faaf9d | [] | no_license | 657122411/Lidar | 44770da6d5da6f34b14037d4ffdde0a91feb141c | 63d23606a03f7aed134f01a08c4964f04e19ce06 | refs/heads/master | 2020-03-20T00:18:11.718688 | 2018-06-12T08:20:43 | 2018-06-12T08:20:43 | 137,039,065 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 553 | h | #pragma once
#include "iostream"
#include "fstream"
class Wave2
{
public:
Wave2();
~Wave2();
int data[320];
void init(FILE *fp);
void linearSmooth3(double in[], double out[], int N);
void linearSmooth5(double in[], double out[], int N);
void linearSmooth7(double in[], double out[], int N);
void quadraticSmooth5(double in[], double out[], int N);
void quadraticSmooth7(double in[], double out[], int N);
void cubicSmooth5(double in[], double out[], int N);
void cubicSmooth7(double in[], double out[], int N);
}; | [
"noreply@github.com"
] | 657122411.noreply@github.com |
d6b1ca364b4ac467d7cbf340d378ed3d638cfbaa | 853398fb9eec1bb663577837bb4f9da759b7cd56 | /2D_shooter_v2/src/DebugEngine.cpp | 75ee733ad6070e93692810c786cac375a4b2bbe0 | [] | no_license | kelj0/gamedevplayground | ab597b42aeb2408f3cf7a5b07fb8c901aa3e924d | 0b538293b32bd9a2c61d53250918abe045d73fdf | refs/heads/master | 2023-05-01T07:37:44.644478 | 2021-05-24T11:41:25 | 2021-05-24T11:41:25 | 342,294,787 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 892 | cpp | #include "DebugEngine.h"
DebugEngine::DebugEngine(sf::RenderWindow &window, std::vector<Player*> players, sf::Font font) {
this->_window = &window;
this->_font = font;
this->_players = players;
}
void DebugEngine::updateData(){
sf::Text t;
t.setFont(_font);
std::string b = "";
for (Player *p: _players) {
b += p->name + ": " + std::to_string(p->x) + ", " + std::to_string(p->y) + "\n";
b += "m_vector: " + std::to_string(p->vec_movement.x) + ", " + std::to_string(p->vec_movement.y) + "\n";
b += "speed: " + std::to_string(p->getSpeed()) + "\n";
b += "on_floor: " + std::to_string(p->on_floor) + "\n";
}
t.setString(b);
t.setCharacterSize(20);
t.setFillColor(sf::Color::Red);
this->_window->draw(t);
}
void DebugEngine::tick() {
this->_window->clear();
updateData();
this->_window->display();
}
| [
"kelj0@protonmail.com"
] | kelj0@protonmail.com |
ca4a2ad8d7a2616d4153654bf4eeadd06cfa5564 | 69be9b20ec28d319ebac8db566f994fa20650df1 | /src/Encoders.cpp | 4127419dd8150e567630c6f894033b5705eb3649 | [] | no_license | jiezhi320/ADRC-1 | 252b3d554fc85687c5743e4fa3b1d73095dffa11 | e9a32c71fc6b5e98c68213d589df9c296ef62ddf | refs/heads/master | 2021-05-13T12:53:13.550491 | 2015-11-04T02:27:04 | 2015-11-04T02:27:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 804 | cpp | #include "Encoders.h"
#include <fcntl.h>
#include <iostream>
#include <unistd.h>
#include <sys/mman.h>
using namespace std;
Encoders::Encoders() {
m_file = open(MOTOR_DEVICE_NAME, O_RDWR | O_SYNC);
if(m_file == -1) {
cout << "Error: couldn't open the analog device." << endl;
return;
}
m_p_device = (MOTORDATA*)mmap(0, sizeof(MOTORDATA)*vmOUTPUTS,
PROT_READ | PROT_WRITE,
MAP_FILE | MAP_SHARED, m_file, 0);
if(m_p_device == MAP_FAILED) {
cout << "Error: failed to map the analog device." << endl;
}
}
Encoders::~Encoders() {
if(m_file != -1) {
close(m_file);
}
}
int Encoders::ReadCount(const unsigned int port) const {
return m_p_device[port].TachoSensor;
}
int Encoders::ReadSpeed(const unsigned int port) const {
return m_p_device[port].Speed;
}
| [
"psiorx@gmail.com"
] | psiorx@gmail.com |
fc5d646cc8688b837dc675cab8cdeb150220f334 | be4952850ad6a8b0abe50de671c495c6add9fae7 | /codeforce/CF_58A.cpp | 338bb2f8d98709eb0a6f016afb436c3bdedd197b | [] | no_license | ss5ssmi/OJ | 296cb936ecf7ef292e91f24178c9c08bd2d241b5 | 267184cef5f1bc1f222950a71fe705bbc5f0bb3e | refs/heads/master | 2022-10-29T18:15:14.290028 | 2022-10-12T04:42:47 | 2022-10-12T04:42:47 | 103,818,651 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 614 | cpp | #include<stdio.h>
#include<string.h>
int main(){
char s[100];
int i,h,e,l1,l2,o;
while(scanf("%s",&s)!=EOF){
h=e=l1=l2=o=0;
for(i=0;i<strlen(s);i++){
if(s[i]=='h'){
h=i;
break;
}
}
for(i+=1;i<strlen(s);i++){
if(s[i]=='e'){
e=i;
break;
}
}
for(i+=1;i<strlen(s);i++){
if(s[i]=='l'){
l1=i;
break;
}
}
for(i+=1;i<strlen(s);i++){
if(s[i]=='l'){
l2=i;
break;
}
}
for(i+=1;i<strlen(s);i++){
if(s[i]=='o'){
o=i;
break;
}
}
if(o>l2 && l2>l1 && l1>e && e>h){
printf("YES\n");
}else{
printf("NO\n");
}
}
return 0;
}
| [
"imss5ss@outlook.com"
] | imss5ss@outlook.com |
85668a7d828245ac86bc3f22ba7d15e298300ba1 | 539bff0ab3912fc0b570ff09a94562f3815079ba | /board.cpp | f97af3a845ea354e7a81ed5cc2d5613bdd218bd6 | [
"Apache-2.0"
] | permissive | volkertb/4steps | 78cea28a3435c21973457cb875305f1be29f0817 | ce3c04790a15847783130e7340f0f1c2b57991a7 | refs/heads/master | 2022-04-26T14:28:00.822943 | 2022-01-05T01:10:09 | 2022-01-05T01:12:15 | 120,374,551 | 0 | 0 | null | 2018-02-05T23:18:51 | 2018-02-05T23:18:51 | null | UTF-8 | C++ | false | false | 35,664 | cpp | #include <QMouseEvent>
#include <QToolTip>
#include <QPainter>
#include "board.hpp"
#include "globals.hpp"
#include "messagebox.hpp"
#include "io.hpp"
#include "palette.hpp"
Board::Board(Globals& globals_,NodePtr currentNode_,const bool explore_,const Side viewpoint,const bool soundOn,const std::array<bool,NUM_SIDES>& controllableSides_,const TurnState* const customSetup_,QWidget* const parent,const Qt::WindowFlags f) :
QWidget(parent,f),
explore(explore_),
southIsUp(viewpoint==SECOND_SIDE),
currentNode(currentNode_),
globals(globals_),
potentialSetup(customSetup_==nullptr ? GameState() : GameState(*customSetup_)),
controllableSides(controllableSides_),
autoRotate(false),
drag{NO_SQUARE,NO_SQUARE},
colorKeys{"regular",
"goal_south",
"goal_north",
"trap_south",
"trap_north",
"highlight_light",
"highlight_dark",
"highlight_mild_light",
"highlight_mild_dark",
"alternative",
"goal_south_alternative",
"goal_north_alternative",
"trap_south_alternative",
"trap_north_alternative",
"highlight_light_alternative",
"highlight_dark_alternative",
"highlight_mild_light_alternative",
"highlight_mild_dark_alternative"}
{
fill(customColors,REGULAR);
setContextMenuPolicy(Qt::NoContextMenu);
qMediaPlayer.setPlaylist(&qMediaPlaylist);
toggleSound(soundOn);
if (!customSetup())
initSetup();
globals.settings.beginGroup("Board");
const auto stepMode=globals.settings.value("step_mode").toBool();
const auto iconSet=static_cast<PieceIcons::Set>(globals.settings.value("icon_set",PieceIcons::VECTOR).toInt());
const auto coordinateDisplay=static_cast<CoordinateDisplay>(globals.settings.value("coordinate_display",TRAPS_ONLY).toInt());
const auto animate=globals.settings.value("animate",true).toBool();
const auto animationDelay=globals.settings.value("animation_delay",375).toInt();
const auto volume=globals.settings.value("volume",100).toInt();
const auto confirm=globals.settings.value("confirm",true).toBool();
globals.settings.endGroup();
globals.settings.beginGroup("Colors");
const QString defaultMainColors[2]={"#89657B","#C92D0C"};
const QString defaultTrapColors[NUM_SIDES]={"#F66610","#4200F2"};
const QString defaultHighLightColors[NUM_SIDES]={"#FFFFFF","#000000"};
const QString defaultMildHighLightColors[NUM_SIDES]={"#C9C9C9","#232323"};
const QString defaultColors[NUM_SQUARE_COLORS]={
defaultMainColors[0],
defaultMainColors[0],
defaultMainColors[0],
defaultTrapColors[FIRST_SIDE],
defaultTrapColors[SECOND_SIDE],
defaultHighLightColors[FIRST_SIDE],
defaultHighLightColors[SECOND_SIDE],
defaultMildHighLightColors[FIRST_SIDE],
defaultMildHighLightColors[SECOND_SIDE],
defaultMainColors[1],
defaultMainColors[1],
defaultMainColors[1],
defaultTrapColors[FIRST_SIDE],
defaultTrapColors[SECOND_SIDE],
defaultHighLightColors[FIRST_SIDE],
defaultHighLightColors[SECOND_SIDE],
defaultMildHighLightColors[FIRST_SIDE],
defaultMildHighLightColors[SECOND_SIDE],
};
QColor colors[NUM_SQUARE_COLORS];
for (unsigned int colorIndex=0;colorIndex<Board::NUM_SQUARE_COLORS;++colorIndex)
colors[colorIndex]=globals.settings.value(colorKeys[colorIndex],defaultColors[colorIndex]).toString();
globals.settings.endGroup();
setStepMode(stepMode);
setIconSet(iconSet);
setCoordinateDisplay(coordinateDisplay);
setAnimate(animate);
setAnimationDelay(animationDelay);
setVolume(volume);
setConfirm(confirm);
for (unsigned int colorIndex=0;colorIndex<Board::NUM_SQUARE_COLORS;++colorIndex)
setColor(colorIndex,colors[colorIndex]);
connect(this,&Board::boardChanged,this,[this](const bool refresh) {
if (refresh)
refreshHighlights(true);
});
connect(this,&Board::boardChanged,this,static_cast<void (Board::*)()>(&Board::update));
connect(&animationTimer,&QTimer::timeout,this,&Board::animateNextStep);
}
bool Board::customSetup() const
{
return currentNode.get()==nullptr;
}
bool Board::setupPhase() const
{
return customSetup() || currentNode->inSetup();
}
bool Board::setupPlacementPhase() const
{
return !customSetup() && currentNode->inSetup() && currentSetupPiece>FIRST_PIECE_TYPE;
}
Side Board::sideToMove() const
{
return customSetup() ? potentialSetup.sideToMove : currentNode->gameState.sideToMove;
}
const GameState& Board::gameState() const
{
return setupPhase() ? potentialSetup :
(potentialMove.get().empty() ? currentNode->gameState : std::get<RESULTING_STATE>(potentialMove.get().back()));
}
const GameState& Board::displayedGameState() const
{
if (isAnimating()) {
const auto& previousNode=currentNode->previousNode;
assert(previousNode!=nullptr);
const auto& previousMove=currentNode->move;
if (nextAnimatedStep==previousMove.begin())
return previousNode->gameState;
else
return std::get<RESULTING_STATE>(*--decltype(nextAnimatedStep)(nextAnimatedStep));
}
else
return gameState();
}
Placements Board::currentPlacements() const
{
return gameState().placements(sideToMove());
}
std::pair<Placements,ExtendedSteps> Board::tentativeMove() const
{
std::pair<Placements,ExtendedSteps> result;
if (setupPhase())
result.first=currentPlacements();
else
result.second=potentialMove.get().current();
return result;
}
std::string Board::tentativeMoveString() const
{
if (setupPhase())
return toString(currentPlacements());
else
return toString(potentialMove.get().current());
}
bool Board::gameEnd() const
{
return !customSetup() && currentNode->result.endCondition!=NO_END;
}
bool Board::playable() const
{
return !gameEnd() && (explore || controllableSides[sideToMove()]);
}
bool Board::setNode(NodePtr newNode,const bool silent,bool keepState)
{
keepState&=(newNode==currentNode.get());
const bool transition=(newNode->previousNode==currentNode.get() && potentialMove.data.empty());
currentNode=std::move(newNode);
if (!keepState || !silent)
disableAnimation();
if (!silent && currentNode->previousNode!=nullptr) {
if (currentNode->previousNode->inSetup())
playSound("qrc:/finished-setup.wav");
else if (animate)
animateMove(!transition);
else
playStepSounds(currentNode->move,true);
}
if (!keepState) {
endDrag();
if (setupPhase())
initSetup();
else
potentialMove.data.clear();
}
if (autoRotate)
setViewpoint(sideToMove());
emit boardChanged();
return !keepState;
}
void Board::playMoveSounds(const Node& node)
{
if (node.previousNode!=nullptr) {
if (node.previousNode->inSetup())
playSound("qrc:/finished-setup.wav");
else
playStepSounds(node.move,true);
}
}
void Board::proposeMove(const Node& child,const unsigned int playedOutSteps)
{
if (currentNode->inSetup())
proposeSetup(child);
else {
const auto& move=child.move;
doSteps(move,false,move.size()-playedOutSteps);
}
}
void Board::proposeCustomSetup(const TurnState& turnState)
{
assert(customSetup());
endDrag();
potentialSetup.sideToMove=turnState.sideToMove;
potentialSetup.squarePieces=turnState.squarePieces;
emit boardChanged();
}
bool Board::proposeSetup(const Placements& placements)
{
if (playable()) {
endDrag();
if (!customSetup())
clearSetup();
potentialSetup.add(placements);
if (customSetup() || !nextSetupPiece(false))
emit boardChanged();
return true;
}
else
return false;
}
void Board::proposeSetup(const Node& child)
{
if (proposeSetup(child.playedPlacements())) {
assert(potentialSetup.sideToMove!=child.gameState.sideToMove);
assert(potentialSetup.squarePieces==child.gameState.squarePieces);
}
}
void Board::doSteps(const ExtendedSteps& steps,const bool sound,const int undoneSteps)
{
const bool updated=(int(steps.size())!=undoneSteps);
if (!steps.empty() && (playable() || !updated)) {
potentialMove.data.append(steps);
potentialMove.data.shiftEnd(-undoneSteps);
if (sound && !explore)
playStepSounds(steps,false);
if (updated)
endDrag();
if (!autoFinalize(true) && updated)
emit boardChanged();
}
}
void Board::undoSteps(const bool all)
{
bool updated=potentialMove.data.shiftEnd(false,all);
if (explore && !updated && currentNode->previousNode!=nullptr) {
const auto oldNode=currentNode;
setNode(currentNode->previousNode);
if (!all) {
if (currentNode->inSetup())
proposeSetup(*oldNode.get());
else {
const auto& move=oldNode->move;
doSteps(move,false,move.size()==MAX_STEPS_PER_MOVE ? 1 : 0);
}
}
updated=true;
}
if (updated) {
endDrag();
emit boardChanged();
}
}
void Board::redoSteps(const bool all)
{
if (playable()) {
const bool updated=potentialMove.data.shiftEnd(true,all);
if (updated)
endDrag();
if (!autoFinalize(updated) && updated)
emit boardChanged();
}
}
void Board::redoSteps(const ExtendedSteps& steps)
{
if (playable()) {
potentialMove.data.set(steps,steps.size());
endDrag();
if (!autoFinalize(true))
emit boardChanged();
}
}
void Board::animateMove(const bool showStart)
{
if (customSetup() || currentNode->isGameStart())
return;
else if (currentNode->move.empty())
playSound("qrc:/finished-setup.wav");
else {
qMediaPlaylist.clear();
const auto& previousMove=currentNode->move;
nextAnimatedStep=previousMove.begin();
assert(nextAnimatedStep!=previousMove.end());
if (showStart) {
animationTimer.start();
update();
}
else
animateNextStep();
}
}
void Board::rotate()
{
southIsUp=!southIsUp;
refreshHighlights(false);
update();
emit boardRotated(southIsUp);
}
void Board::setViewpoint(const Side side)
{
if ((side==SECOND_SIDE)!=southIsUp)
rotate();
}
void Board::setAutoRotate(const bool on)
{
if (on) {
autoRotate=true;
setViewpoint(sideToMove());
}
else
autoRotate=false;
}
void Board::toggleSound(const bool soundOn_)
{
soundOn=soundOn_;
if (!soundOn)
qMediaPlayer.stop();
}
void Board::setStepMode(const bool newStepMode)
{
setSetting(stepMode,newStepMode,"step_mode");
setMouseTracking(stepMode);
if (refreshHighlights(true))
update();
}
void Board::setIconSet(const PieceIcons::Set newIconSet)
{
if (setSetting(iconSet,newIconSet,"icon_set"))
update();
}
void Board::setCoordinateDisplay(const CoordinateDisplay newCoordinateDisplay)
{
if (setSetting(coordinateDisplay,newCoordinateDisplay,"coordinate_display"))
update();
}
void Board::setAnimate(const bool newAnimate)
{
setSetting(animate,newAnimate,"animate");
}
void Board::setAnimationDelay(const int newAnimationDelay)
{
if (setSetting(animationDelay,newAnimationDelay,"animation_delay"))
animationTimer.setInterval(animationDelay);
}
void Board::setVolume(const int newVolume)
{
if (setSetting(volume,newVolume,"volume"))
qMediaPlayer.setVolume(newVolume);
}
void Board::setConfirm(const bool newConfirm)
{
setSetting(confirm,newConfirm,"confirm");
}
void Board::setColor(const unsigned int colorIndex,const QColor& newColor)
{
auto& currentColor=colors[colorIndex];
if (newColor!=currentColor.data) {
currentColor=newColor;
globals.settings.beginGroup("Colors");
globals.settings.setValue(colorKeys[colorIndex],newColor.name());
globals.settings.endGroup();
update();
}
}
void Board::playSound(const QString& soundFile,const bool override)
{
if (soundOn || override) {
qMediaPlaylist.clear();
qMediaPlaylist.addMedia(QUrl(soundFile));
qMediaPlayer.play();
}
}
void Board::setExploration(const bool on)
{
explore=on;
if (on)
autoFinalize(false);
else if (!playable()) {
endDrag();
undoSteps(true);
}
update();
}
void Board::setControllable(const std::array<bool,NUM_SIDES>& controllableSides_)
{
controllableSides=controllableSides_;
if (playable())
update();
else
endDrag();
}
int Board::squareWidth() const
{
return width()/NUM_FILES;
}
int Board::squareHeight() const
{
return height()/NUM_RANKS;
}
void Board::normalizeOrientation(unsigned int& file,unsigned int& rank) const
{
if (southIsUp)
file=NUM_FILES-1-file;
else
rank=NUM_RANKS-1-rank;
}
QRect Board::visualRectangle(unsigned int file,unsigned int rank) const
{
normalizeOrientation(file,rank);
return QRect(file*squareWidth(),rank*squareHeight(),squareWidth(),squareHeight());
}
SquareIndex Board::orientedSquare(unsigned int file,unsigned int rank) const
{
if (isValidSquare(file,rank)) {
normalizeOrientation(file,rank);
return toSquare(file,rank);
}
else
return NO_SQUARE;
}
SquareIndex Board::positionToSquare(const QPoint& position) const
{
const int file=floorDiv(position.x(),squareWidth());
const int rank=floorDiv(position.y(),squareHeight());
return orientedSquare(file,rank);
}
int Board::closestAxisDirection(unsigned int value,const unsigned int size)
{
value*=2;
if (value<size)
return -1;
else if (value>size)
return 1;
else
return 0;
}
SquareIndex Board::closestAdjacentSquare(const QPoint& position) const
{
const int file=floorDiv(position.x(),squareWidth());
const int rank=floorDiv(position.y(),squareHeight());
const int localX=position.x()%squareWidth();
const int localY=position.y()%squareHeight();
const int widthDirection=(file==0 ? 1 : (file==NUM_FILES-1 ? -1 : closestAxisDirection(localX,squareWidth())));
const int heightDirection=(rank==0 ? 1 : (rank==NUM_RANKS-1 ? -1 : closestAxisDirection(localY,squareHeight())));
const int distanceX=( widthDirection==1) ? squareWidth() -localX : localX;
const int distanceY=(heightDirection==1) ? squareHeight()-localY : localY;
const int diffDistance=distanceX*squareHeight()-distanceY*squareWidth();
if (diffDistance<0) {
if (widthDirection!=0)
return orientedSquare(file+widthDirection,rank);
}
else if (diffDistance>0)
if (heightDirection!=0)
return orientedSquare(file,rank+heightDirection);
return NO_SQUARE;
}
bool Board::isSetupSquare(const Side side,const SquareIndex square) const
{
return customSetup() ? square!=NO_SQUARE : ::isSetupSquare(side,square);
}
bool Board::validDrop() const
{
return setupPhase() ? (isSetupSquare(sideToMove(),drag[DESTINATION]) && drag[ORIGIN]!=drag[DESTINATION]) : !dragSteps.empty();
}
bool Board::isAnimating() const
{
return animationTimer.isActive();
}
template<class Type>
bool Board::setSetting(readonly<Board,Type>& currentValue,const Type newValue,const QString& key)
{
if (currentValue==newValue)
return false;
else {
currentValue=newValue;
globals.settings.beginGroup("Board");
globals.settings.setValue(key,currentValue.get());
globals.settings.endGroup();
return true;
}
}
void Board::clearSetup()
{
potentialSetup=currentNode->gameState;
for (SquareIndex square=FIRST_SQUARE;square<NUM_SQUARES;increment(square))
if (isSetupSquare(sideToMove(),square))
potentialSetup.squarePieces[square]=NO_PIECE;
}
void Board::initSetup()
{
clearSetup();
nextSetupPiece();
}
bool Board::nextSetupPiece(const bool finalize)
{
std::array<unsigned int,NUM_PIECE_TYPES> numPiecesPerType=numStartingPiecesPerType;
for (SquareIndex square=FIRST_SQUARE;square<NUM_SQUARES;increment(square)) {
const PieceTypeAndSide squarePiece=potentialSetup.squarePieces[square];
if (squarePiece!=NO_PIECE && isSetupSquare(sideToMove(),square)) {
assert(isSide(squarePiece,sideToMove()));
--numPiecesPerType[toPieceType(squarePiece)];
}
}
currentSetupPiece=static_cast<PieceType>(NUM_PIECE_TYPES-1);
for (auto numPiecesIter=numPiecesPerType.crbegin();numPiecesIter!=numPiecesPerType.crend();++numPiecesIter,decrement(currentSetupPiece))
if (currentSetupPiece==FIRST_PIECE_TYPE) {
// Fill remaining squares with most numerous piece type.
const PieceTypeAndSide piece=toPieceTypeAndSide(FIRST_PIECE_TYPE,sideToMove());
for (SquareIndex square=FIRST_SQUARE;square<NUM_SQUARES;increment(square)) {
PieceTypeAndSide& squarePiece=potentialSetup.squarePieces[square];
if (squarePiece==NO_PIECE && isSetupSquare(sideToMove(),square))
squarePiece=piece;
}
if (finalize)
autoFinalize(true);
emit boardChanged();
return true;
}
else if (*numPiecesIter>0)
break;
return false;
}
bool Board::setUpPiece(const SquareIndex destination)
{
if (isSetupSquare(sideToMove(),destination)) {
auto& squarePieces=potentialSetup.squarePieces;
if (std::all_of(squarePieces.begin(),squarePieces.end(),[](const PieceTypeAndSide& piece){return piece==NO_PIECE;}))
emit gameStarted();
squarePieces[destination]=toPieceTypeAndSide(currentSetupPiece,sideToMove());
emit boardChanged();
nextSetupPiece();
return true;
}
else
return false;
}
bool Board::refreshHighlights(const bool clearSelected)
{
if (stepMode && !setupPlacementPhase())
return updateStepHighlights();
else {
bool change=(highlighted[DESTINATION]!=NO_SQUARE);
highlighted[DESTINATION]=NO_SQUARE;
if (clearSelected) {
change|=(highlighted[ORIGIN]!=NO_SQUARE);
highlighted[ORIGIN]=NO_SQUARE;
}
return change;
}
}
bool Board::updateStepHighlights()
{
return updateStepHighlights(mapFromGlobal(QCursor::pos()));
}
bool Board::updateStepHighlights(const QPoint& mousePosition)
{
const std::array<SquareIndex,2> oldSelected=highlighted;
highlighted[ORIGIN]=positionToSquare(mousePosition);
highlighted[DESTINATION]=closestAdjacentSquare(mousePosition);
if (setupPhase()) {
if (!isSetupSquare(sideToMove(),highlighted[ORIGIN]) || potentialSetup.squarePieces[highlighted[ORIGIN]]==NO_PIECE)
fill(highlighted,NO_SQUARE);
else if (!isSetupSquare(sideToMove(),highlighted[DESTINATION]))
highlighted[DESTINATION]=NO_SQUARE;
}
else {
Squares legalDestinations=gameState().legalDestinations(highlighted[ORIGIN]);
if (legalDestinations.empty()) {
legalDestinations=gameState().legalDestinations(highlighted[DESTINATION]);
if (legalDestinations.empty())
fill(highlighted,NO_SQUARE);
else
std::swap(highlighted[ORIGIN],highlighted[DESTINATION]);
}
if (!found(legalDestinations,highlighted[DESTINATION]))
highlighted[DESTINATION]=NO_SQUARE;
}
return oldSelected!=highlighted;
}
bool Board::singleSquareAction(const SquareIndex square)
{
if (square==NO_SQUARE)
return false;
else if (setupPlacementPhase()) {
if (setUpPiece(square)) {
refreshHighlights(true);
return true;
}
}
else if (stepMode)
return doubleSquareAction(highlighted[ORIGIN],highlighted[DESTINATION]);
else {
if (highlighted[ORIGIN]==NO_SQUARE) {
if (setupPhase() ? (isSetupSquare(sideToMove(),square) && potentialSetup.squarePieces[square]!=NO_PIECE) : gameState().legalOrigin(square)) {
highlighted[ORIGIN]=square;
return true;
}
}
else if (highlighted[ORIGIN]==square) {
highlighted[ORIGIN]=NO_SQUARE;
return true;
}
else
return doubleSquareAction(highlighted[ORIGIN],square);
}
return false;
}
bool Board::doubleSquareAction(const SquareIndex origin,const SquareIndex destination)
{
if (origin==NO_SQUARE || destination==NO_SQUARE)
return false;
else if (setupPhase())
return doubleSquareSetupAction(origin,destination);
else {
const ExtendedSteps route=gameState().preferredRoute(origin,destination);
if (!route.empty()) {
doSteps(route,true);
return true;
}
}
return false;
}
bool Board::doubleSquareSetupAction(const SquareIndex origin,const SquareIndex destination)
{
if (destination==NO_SQUARE) {
potentialSetup.squarePieces[origin]=NO_PIECE;
if (!customSetup())
nextSetupPiece();
emit boardChanged();
return true;
}
else if (isSetupSquare(sideToMove(),destination)) {
auto& squarePieces=potentialSetup.squarePieces;
if (customSetup()) {
squarePieces[destination]=squarePieces[origin];
squarePieces[origin]=NO_PIECE;
}
else
std::swap(squarePieces[origin],squarePieces[destination]);
emit boardChanged();
return true;
}
else
return false;
}
void Board::finalizeSetup(const Placements& placements)
{
const auto newNode=Node::addSetup(currentNode,placements,explore);
currentNode=std::move(newNode);
if (sideToMove()==SECOND_SIDE)
initSetup();
else
potentialMove.data.clear();
emit boardChanged();
emit sendNodeChange(newNode,currentNode);
if (autoRotate)
setViewpoint(sideToMove());
}
void Board::finalizeMove(const ExtendedSteps& move)
{
const auto newNode=Node::makeMove(currentNode,move,explore);
currentNode=std::move(newNode);
potentialMove.data.clear();
emit boardChanged();
emit sendNodeChange(newNode,currentNode);
if (autoRotate && currentNode->result.endCondition==NO_END)
setViewpoint(sideToMove());
}
void Board::endDrag()
{
drag[ORIGIN]=NO_SQUARE;
dragSteps.clear();
update();
}
bool Board::autoFinalize(const bool stepsTaken)
{
if (!customSetup() && explore) {
if (currentNode->inSetup()) {
if (currentSetupPiece<=FIRST_PIECE_TYPE)
finalizeSetup(currentPlacements());
else if (const auto& child=currentNode->findPartialMatchingChild(currentPlacements()).first) {
proposeSetup(*child.get());
return true;
}
else
return false;
}
else {
const auto& currentSteps=potentialMove.get().current();
if (gameState().stepsAvailable==0 || (!stepsTaken && currentNode->findMatchingChild(currentSteps).first!=nullptr)) {
if (currentNode->legalMove(gameState())==MoveLegality::LEGAL)
finalizeMove(currentSteps);
else
return false;
}
else {
if (const auto& child=currentNode->findPartialMatchingChild(potentialMove.get().all()).first)
potentialMove.data.set(child->move,currentSteps.size());
return false;
}
}
if (const auto& child=currentNode->child(0))
proposeMove(*child.get(),0);
return true;
}
else
return false;
}
bool Board::confirmMove()
{
if (confirm && !explore && found(controllableSides,false))
return MessageBox(QMessageBox::Question,tr("Confirm move"),tr("Do you want to submit this move?"),QMessageBox::Yes|QMessageBox::No,this).exec()==QMessageBox::Yes;
else
return true;
}
bool Board::event(QEvent* event)
{
if (event->type()==QEvent::ToolTip) {
const auto helpEvent=static_cast<QHelpEvent*>(event);
const auto squareIndex=positionToSquare(helpEvent->pos());
if (squareIndex!=NO_SQUARE) {
QToolTip::showText(helpEvent->globalPos(),toCoordinates(squareIndex).data());
return true;
}
}
return QWidget::event(event);
}
void Board::mousePressEvent(QMouseEvent* event)
{
disableAnimation();
const SquareIndex square=positionToSquare(event->pos());
switch (event->button()) {
case Qt::LeftButton:
if (square!=NO_SQUARE && playable()) {
const PieceTypeAndSide currentPiece=gameState().squarePieces[square];
if (customSetup() ? currentPiece!=NO_PIECE : (currentNode->inSetup() ? isSide(currentPiece,sideToMove()) : gameState().legalOrigin(square))) {
fill(drag,square);
dragSteps.clear();
update();
}
}
break;
case Qt::RightButton:
if (playable()) {
if (drag[ORIGIN]!=NO_SQUARE) {
endDrag();
break;
}
else if (!stepMode && highlighted[ORIGIN]!=NO_SQUARE) {
highlighted[ORIGIN]=NO_SQUARE;
update();
break;
}
else if (customSetup()) {
if (square!=NO_SQUARE)
new Palette(*this,square);
break;
}
}
emit customContextMenuRequested(event->pos());
break;
case Qt::BackButton:
if (!customSetup())
undoSteps(false);
break;
case Qt::ForwardButton:
if (!customSetup())
redoSteps(false);
break;
default:
event->ignore();
return;
break;
}
event->accept();
}
void Board::mouseMoveEvent(QMouseEvent* event)
{
if (!playable()) {
event->ignore();
return;
}
event->accept();
if ((event->buttons()&Qt::LeftButton)!=0) {
disableAnimation();
if (drag[ORIGIN]!=NO_SQUARE) {
const SquareIndex square=positionToSquare(event->pos());
if (drag[DESTINATION]!=square) {
drag[DESTINATION]=square;
if (square==NO_SQUARE || drag[ORIGIN]==drag[DESTINATION])
dragSteps.clear();
else if (!setupPhase())
dragSteps=gameState().preferredRoute(drag[ORIGIN],drag[DESTINATION],dragSteps);
}
update();
}
}
if (refreshHighlights(false))
update();
}
void Board::mouseReleaseEvent(QMouseEvent* event)
{
switch (event->button()) {
case Qt::LeftButton:
disableAnimation();
if (playable()) {
const SquareIndex eventSquare=positionToSquare(event->pos());
if (drag[ORIGIN]!=NO_SQUARE) {
assert(eventSquare==drag[DESTINATION]);
if (drag[ORIGIN]==eventSquare)
singleSquareAction(eventSquare);
else if (setupPhase())
doubleSquareSetupAction(drag[ORIGIN],eventSquare);
else
doSteps(dragSteps,true);
endDrag();
}
else if (singleSquareAction(eventSquare))
update();
}
break;
case Qt::MidButton:
break;
default:
disableAnimation();
event->ignore();
return;
break;
}
event->accept();
}
void Board::mouseDoubleClickEvent(QMouseEvent* event)
{
if (!playable()) {
event->ignore();
return;
}
switch (event->button()) {
case Qt::LeftButton: {
disableAnimation();
const SquareIndex eventSquare=positionToSquare(event->pos());
if ((eventSquare==NO_SQUARE || gameState().squarePieces[eventSquare]==NO_PIECE) && (!stepMode || found(highlighted,NO_SQUARE))) {
if (customSetup()) {
if (potentialSetup.hasFloatingPieces())
MessageBox(QMessageBox::Critical,tr("Illegal position"),tr("Unprotected piece on trap."),QMessageBox::NoButton,this).exec();
else {
const auto node=std::make_shared<Node>(nullptr,ExtendedSteps(),potentialSetup);
if (!node->inSetup() && node->result.endCondition==NO_END) {
emit sendNodeChange(node,currentNode);
currentNode=std::move(node);
if (autoRotate)
setViewpoint(sideToMove());
emit boardChanged();
}
else
MessageBox(QMessageBox::Critical,tr("Terminal position"),tr("Game already finished in this position."),QMessageBox::NoButton,this).exec();
}
}
else if (currentNode->inSetup()) {
if (currentSetupPiece<=FIRST_PIECE_TYPE && confirmMove()) {
if (!explore)
playSound("qrc:/finished-setup.wav");
finalizeSetup(currentPlacements());
}
}
else {
const auto& playedMove=potentialMove.get().current();
switch (currentNode->legalMove(gameState())) {
case MoveLegality::LEGAL:
if (confirmMove()) {
if (!explore)
playSound("qrc:/loud-step.wav");
finalizeMove(playedMove);
}
break;
case MoveLegality::ILLEGAL_PUSH_INCOMPLETION:
playSound("qrc:/illegal-move.wav");
MessageBox(QMessageBox::Critical,tr("Incomplete push"),tr("Push was not completed."),QMessageBox::NoButton,this).exec();
break;
case MoveLegality::ILLEGAL_PASS:
playSound("qrc:/illegal-move.wav");
if (!playedMove.empty())
MessageBox(QMessageBox::Critical,tr("Illegal pass"),tr("Move did not change board."),QMessageBox::NoButton,this).exec();
break;
case MoveLegality::ILLEGAL_REPETITION:
playSound("qrc:/illegal-move.wav");
MessageBox(QMessageBox::Critical,tr("Illegal repetition"),tr("Move would repeat board and side to move too often."),QMessageBox::NoButton,this).exec();
break;
}
}
}
}
break;
case Qt::RightButton:
disableAnimation();
break;
case Qt::BackButton:
if (!customSetup()) {
disableAnimation();
undoSteps(true);
}
break;
case Qt::ForwardButton:
if (!customSetup()) {
disableAnimation();
redoSteps(true);
}
break;
default:
event->ignore();
return;
break;
}
event->accept();
}
void Board::wheelEvent(QWheelEvent* event)
{
if (!customSetup()) {
disableAnimation();
if (event->angleDelta().y()<0)
undoSteps(false);
else
redoSteps(false);
}
event->accept();
}
void Board::focusOutEvent(QFocusEvent*)
{
endDrag();
}
void Board::paintEvent(QPaintEvent*)
{
QPainter qPainter(this);
if (coordinateDisplay!=NONE) {
qreal factor=squareHeight()/static_cast<qreal>(qPainter.fontMetrics().height());
for (SquareIndex square=FIRST_SQUARE;square<NUM_SQUARES;increment(square))
if (coordinateDisplay==ALL || isTrap(square))
factor=std::min(factor,squareWidth()/static_cast<qreal>(qPainter.fontMetrics().horizontalAdvance(toCoordinates(square,'A').data())));
if (factor>0) {
QFont qFont(qPainter.font());
qFont.setPointSizeF(qFont.pointSizeF()*factor);
qPainter.setFont(qFont);
}
}
const GameState& gameState_=displayedGameState();
const auto previousPieces=(customSetup() || currentNode->move.empty() ? nullptr : ¤tNode->previousNode->gameState.squarePieces);
QPen qPen(Qt::SolidPattern,1);
const QPoint mousePosition=mapFromGlobal(QCursor::pos());
const bool alternativeColoring=(explore && found(controllableSides,false));
const auto startingColor=&colors[alternativeColoring ? ALTERNATIVE : REGULAR];
for (unsigned int pass=0;pass<2;++pass)
for (SquareIndex square=FIRST_SQUARE;square<NUM_SQUARES;increment(square)) {
const unsigned int file=toFile(square);
const unsigned int rank=toRank(square);
const bool isTrapSquare=isTrap(file,rank);
if (!isAnimating() && (drag[ORIGIN]==NO_SQUARE ? found(highlighted,square) || (gameState_.inPush && square==gameState_.followupDestination)
: square==drag[DESTINATION] && validDrop())) {
if (pass==0)
continue;
else {
qPainter.setBrush((startingColor+HIGHLIGHT+sideToMove())->data);
qPen.setColor(*(startingColor+HIGHLIGHT+otherSide(sideToMove())));
}
}
else if (pass==1)
continue;
else {
if (!isAnimating() && !setupPhase() && (square==drag[ORIGIN] || found<ORIGIN>(dragSteps,square)))
qPainter.setBrush((startingColor+HIGHLIGHT_MILD+sideToMove())->data);
else if (setupPhase() ? !customSetup() && playable() && isSetupRank(sideToMove(),rank)
: (isAnimating() || gameState_.stepsAvailable==MAX_STEPS_PER_MOVE) &&
previousPieces!=nullptr && (*previousPieces)[square]!=gameState_.squarePieces[square])
qPainter.setBrush((startingColor+HIGHLIGHT+otherSide(sideToMove()))->data);
else {
const auto customColor=customColors[square];
if (customColor!=REGULAR)
qPainter.setBrush((startingColor+customColor)->data);
else {
if (customSetup())
qPainter.setBrush((startingColor+HIGHLIGHT_MILD+sideToMove())->data);
else
qPainter.setBrush((startingColor+REGULAR)->data);
if (isTrapSquare) {
const QColor trapColors[NUM_SIDES]={(startingColor+TRAP+ FIRST_SIDE)->data,
(startingColor+TRAP+SECOND_SIDE)->data};
if (!customSetup() || trapColors[FIRST_SIDE]!=trapColors[SECOND_SIDE])
qPainter.setBrush(trapColors[rank<NUM_RANKS/2 ? FIRST_SIDE : SECOND_SIDE]);
}
else {
const QColor goalColors[NUM_SIDES]={(startingColor+GOAL+SECOND_SIDE)->data,
(startingColor+GOAL+ FIRST_SIDE)->data};
if (!customSetup() || goalColors[FIRST_SIDE]!=goalColors[SECOND_SIDE])
for (Side side=FIRST_SIDE;side<NUM_SIDES;increment(side))
if (isGoal(square,side)) {
qPainter.setBrush(goalColors[side]);
break;
}
}
}
}
qPen.setColor(*(startingColor+HIGHLIGHT+sideToMove()));
}
qPainter.setPen(qPen);
const QRect qRect=visualRectangle(file,rank);
qPainter.drawRect(qRect);
if (coordinateDisplay==ALL || (coordinateDisplay==TRAPS_ONLY && isTrapSquare)) {
if (gameEnd())
qPainter.setPen(colors[alternativeColoring ? REGULAR : ALTERNATIVE]);
qPainter.drawText(qRect,Qt::AlignCenter,toCoordinates(file,rank,'A').data());
}
if (square!=drag[ORIGIN] || isAnimating()) {
const PieceTypeAndSide pieceOnSquare=gameState_.squarePieces[square];
if (pieceOnSquare!=NO_PIECE)
globals.pieceIcons.drawPiece(qPainter,iconSet,pieceOnSquare,qRect);
}
}
if (playable() && setupPlacementPhase())
globals.pieceIcons.drawPiece(qPainter,iconSet,toPieceTypeAndSide(currentSetupPiece,sideToMove()),QRect((NUM_FILES-1)/2.0*squareWidth(),(NUM_RANKS-1)/2.0*squareHeight(),squareWidth(),squareHeight()));
if (drag[ORIGIN]!=NO_SQUARE && !isAnimating())
globals.pieceIcons.drawPiece(qPainter,iconSet,gameState_.squarePieces[drag[ORIGIN]],QRect(mousePosition.x()-squareWidth()/2,mousePosition.y()-squareHeight()/2,squareWidth(),squareHeight()));
qPainter.end();
}
void Board::animateNextStep()
{
const auto lastStep=currentNode->move.end();
if (soundOn) {
if (qMediaPlayer.state()==QMediaPlayer::StoppedState)
qMediaPlaylist.clear();
if (!playCaptureSound(*nextAnimatedStep++))
qMediaPlaylist.addMedia(QUrl(nextAnimatedStep==lastStep ? "qrc:/loud-step.wav" : "qrc:/soft-step.wav"));
qMediaPlayer.play();
}
else
++nextAnimatedStep;
if (nextAnimatedStep==lastStep)
animationTimer.stop();
else
animationTimer.start();
update();
}
void Board::disableAnimation()
{
if (isAnimating()) {
animationTimer.stop();
update();
}
}
void Board::playStepSounds(const ExtendedSteps& steps,const bool emphasize)
{
if (soundOn) {
qMediaPlaylist.clear();
for (const auto& step:steps)
playCaptureSound(step);
if (qMediaPlaylist.isEmpty())
qMediaPlaylist.addMedia(QUrl(emphasize ? "qrc:/loud-step.wav" : "qrc:/soft-step.wav"));
qMediaPlayer.play();
}
}
bool Board::playCaptureSound(const ExtendedStep& step)
{
assert(soundOn);
const auto trappedPiece=std::get<TRAPPED_PIECE>(step);
if (trappedPiece==NO_PIECE)
return false;
else {
if (toSide(trappedPiece)==std::get<RESULTING_STATE>(step).sideToMove)
qMediaPlaylist.addMedia(QUrl("qrc:/dropped-piece.wav"));
else
qMediaPlaylist.addMedia(QUrl("qrc:/captured-piece.wav"));
return true;
}
}
| [
"TFiFiE@users.noreply.github.com"
] | TFiFiE@users.noreply.github.com |
e9676507c5ee1fee7c8ab9a193980c18cb47fd9d | df05196c665c668dd8862df136f09a20b057829c | /release/moc_board_model.cpp | 400c74d7054b3d8f7f432928b9aaa3bf6ef3d566 | [] | no_license | Hjvf01/15 | 8ed81198fff6df49d9890574e1fd6f6724ccc0d6 | b0add06d8e65c425dc653c7279348c7777c5d9aa | refs/heads/master | 2021-06-27T11:18:33.265997 | 2017-09-12T13:25:04 | 2017-09-12T13:25:04 | 102,881,086 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,134 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'board_model.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.6.2)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../src/board_model.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'board_model.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.6.2. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
struct qt_meta_stringdata_BoardModel_t {
QByteArrayData data[4];
char stringdata0[29];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_BoardModel_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_BoardModel_t qt_meta_stringdata_BoardModel = {
{
QT_MOC_LITERAL(0, 0, 10), // "BoardModel"
QT_MOC_LITERAL(1, 11, 11), // "sizeChanged"
QT_MOC_LITERAL(2, 23, 0), // ""
QT_MOC_LITERAL(3, 24, 4) // "size"
},
"BoardModel\0sizeChanged\0\0size"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_BoardModel[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
1, 14, // methods
1, 20, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
1, // signalCount
// signals: name, argc, parameters, tag, flags
1, 0, 19, 2, 0x06 /* Public */,
// signals: parameters
QMetaType::Void,
// properties: name, type, flags
3, QMetaType::Int, 0x00495001,
// properties: notify_signal_id
0,
0 // eod
};
void BoardModel::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
BoardModel *_t = static_cast<BoardModel *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->sizeChanged(); break;
default: ;
}
} else if (_c == QMetaObject::IndexOfMethod) {
int *result = reinterpret_cast<int *>(_a[0]);
void **func = reinterpret_cast<void **>(_a[1]);
{
typedef void (BoardModel::*_t)();
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&BoardModel::sizeChanged)) {
*result = 0;
return;
}
}
}
#ifndef QT_NO_PROPERTIES
else if (_c == QMetaObject::ReadProperty) {
BoardModel *_t = static_cast<BoardModel *>(_o);
Q_UNUSED(_t)
void *_v = _a[0];
switch (_id) {
case 0: *reinterpret_cast< int*>(_v) = _t->size(); break;
default: break;
}
} else if (_c == QMetaObject::WriteProperty) {
} else if (_c == QMetaObject::ResetProperty) {
}
#endif // QT_NO_PROPERTIES
Q_UNUSED(_a);
}
const QMetaObject BoardModel::staticMetaObject = {
{ &QAbstractListModel::staticMetaObject, qt_meta_stringdata_BoardModel.data,
qt_meta_data_BoardModel, qt_static_metacall, Q_NULLPTR, Q_NULLPTR}
};
const QMetaObject *BoardModel::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *BoardModel::qt_metacast(const char *_clname)
{
if (!_clname) return Q_NULLPTR;
if (!strcmp(_clname, qt_meta_stringdata_BoardModel.stringdata0))
return static_cast<void*>(const_cast< BoardModel*>(this));
return QAbstractListModel::qt_metacast(_clname);
}
int BoardModel::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QAbstractListModel::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 1)
qt_static_metacall(this, _c, _id, _a);
_id -= 1;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 1)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 1;
}
#ifndef QT_NO_PROPERTIES
else if (_c == QMetaObject::ReadProperty || _c == QMetaObject::WriteProperty
|| _c == QMetaObject::ResetProperty || _c == QMetaObject::RegisterPropertyMetaType) {
qt_static_metacall(this, _c, _id, _a);
_id -= 1;
} else if (_c == QMetaObject::QueryPropertyDesignable) {
_id -= 1;
} else if (_c == QMetaObject::QueryPropertyScriptable) {
_id -= 1;
} else if (_c == QMetaObject::QueryPropertyStored) {
_id -= 1;
} else if (_c == QMetaObject::QueryPropertyEditable) {
_id -= 1;
} else if (_c == QMetaObject::QueryPropertyUser) {
_id -= 1;
}
#endif // QT_NO_PROPERTIES
return _id;
}
// SIGNAL 0
void BoardModel::sizeChanged()
{
QMetaObject::activate(this, &staticMetaObject, 0, Q_NULLPTR);
}
QT_END_MOC_NAMESPACE
| [
"mail@email.com"
] | mail@email.com |
ddcf1238306684ac13e6444bab63473d9bc0d6a2 | 470385354ed332fc9f700c2fc46ebc28e7918512 | /listas/lista_1/h_squats.cpp | 9014923261175e33fd292091de6db3d50ef3e2de | [] | no_license | sconetto/ppc | 3a97c092d4b235989bb92250c191aeb1258f88c3 | bfd70be6722a358b8488bdcdfb6316707458c755 | refs/heads/master | 2020-07-04T23:44:57.254823 | 2019-11-25T00:51:57 | 2019-11-25T00:51:57 | 202,459,597 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 917 | cpp | #include <iostream>
#include <string>
using namespace std;
int main(int argc, char const *argv[]) {
int n, su = 0, sd = 0, mins = 0;
char aux;
string hams;
cin >> n;
if (n < 2 || n > 200 || (n % 2) != 0) {
exit(1);
}
for (size_t i = 0; i < n; i++) {
cin >> aux;
hams.push_back(aux);
if (aux == 'x') {
sd++;
} else if (aux == 'X') {
su++;
}
}
while(true) {
if (su > sd) {
mins++;
su--;
sd++;
for (size_t i = 0; i < hams.size(); i++) {
if (hams[i] == 'X') {
hams[i] = 'x';
break;
}
}
} else if (sd > su) {
mins++;
sd--;
su++;
for (size_t i = 0; i < hams.size(); i++) {
if (hams[i] == 'x') {
hams[i] = 'X';
break;
}
}
} else if (sd == su) {
break;
}
}
cout << mins << endl << hams << endl;
return 0;
}
| [
"sconetto.joao@gmail.com"
] | sconetto.joao@gmail.com |
ccfdb3266ca1b5e8d331fa8defba63d4b57a7aa5 | bcb834d26c7dd8f5e915969cc9783b8360281cc3 | /Test/GoogleTest/ClangSetup/main.cpp | d1c92a41a472389cd90cc07f04bdbb60503a6570 | [] | no_license | alexander190591/funMRI | 00d01b256724e9244ce10a2fdf17569f2b7c7663 | 30094f992c32658074ce2030eedbc01778cacf83 | refs/heads/master | 2022-12-19T00:54:51.056141 | 2020-09-22T20:27:57 | 2020-09-22T20:27:57 | 247,016,091 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 960 | cpp | /****************************************************************************
* Copyright (C) Kamstrup A/S, 2020. All rights reserved.
****************************************************************************/
#ifndef __main_2020__
#define __main_2020__
/**
*
* @file main.cpp
*
* Created:
* @author Nikolaj Emil Sørensen <nikolaj.eriksen@gmail.com>
* @date Wednesday, 15th January 2020 1:06:53
*
*
* Modified:
* mod @author Nikolaj Emil Sørensen <nikolaj.eriksen@gmail.com>
* mod @date Wednesday, 15th January 2020 3:02:29
*
*/
#include "Class.hpp"
#include "MyFile.hpp"
#include <stdbool.h>
#include <string.h>
/**
*
* brief
*
* @param argc
* @param args
* @return int
*/
int main( int argc, char** args )
{
MyClass firstObject;
MyClass secondObject( 10, '2', false );
MyClass thirdObject( std::string( "supz" ) );
}
/****************************************************************************/
#endif // __main.cpp__
| [
"alexander190591@gmail.com"
] | alexander190591@gmail.com |
0bbf841e761a2e7881cf0cb7336d5e017b0c39b5 | a636c55ab78abd56273ef5c9bf2e9a7bf0b8f20a | /src/sem/depth_multisampled_texture_type.cc | 6f11f1a23772bc82a7938b481526c9540e19c5c0 | [
"Apache-2.0"
] | permissive | sunnyps/tint | 97432995d0829c6e3db900b66918de29f3d4cb79 | 22daca166bbc412345fc60d4f60646d6d2f3ada0 | refs/heads/main | 2023-08-27T17:07:28.621015 | 2021-10-04T14:54:37 | 2021-10-04T14:54:37 | 411,415,283 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,603 | cc | // Copyright 2021 The Tint Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "src/sem/depth_multisampled_texture_type.h"
#include "src/program_builder.h"
TINT_INSTANTIATE_TYPEINFO(tint::sem::DepthMultisampledTexture);
namespace tint {
namespace sem {
namespace {
bool IsValidDepthDimension(ast::TextureDimension dim) {
return dim == ast::TextureDimension::k2d;
}
} // namespace
DepthMultisampledTexture::DepthMultisampledTexture(ast::TextureDimension dim)
: Base(dim) {
TINT_ASSERT(Semantic, IsValidDepthDimension(dim));
}
DepthMultisampledTexture::DepthMultisampledTexture(DepthMultisampledTexture&&) =
default;
DepthMultisampledTexture::~DepthMultisampledTexture() = default;
std::string DepthMultisampledTexture::type_name() const {
std::ostringstream out;
out << "__depth_multisampled_texture_" << dim();
return out.str();
}
std::string DepthMultisampledTexture::FriendlyName(const SymbolTable&) const {
std::ostringstream out;
out << "texture_depth_multisampled_" << dim();
return out.str();
}
} // namespace sem
} // namespace tint
| [
"tint-scoped@luci-project-accounts.iam.gserviceaccount.com"
] | tint-scoped@luci-project-accounts.iam.gserviceaccount.com |
853f537749c87d144d420d9b6ca44ab6821cce2b | 48e1edbdd9188a8e53dda852248de0e09b8e8e8f | /A350Systems/A350Systems/Waypoint.h | ad77ca4aea3a8bce9727c659d01926ee7405ec1f | [] | no_license | SimJobs/A350 | 1ac6369a2fde6c5e4a02b464ce1a1c7627df95ed | 9462fb665ca16bdc81bb92d0f2a0ef55c25318fd | refs/heads/master | 2021-01-23T04:09:44.137894 | 2014-10-21T16:40:40 | 2014-10-21T16:40:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 947 | h | #ifndef WAYPOINT_H
#define WAYPOINT_H
#include <string>
using namespace std;
namespace Backend
{
struct Waypoint
{
private:
//location
float longitude;
float latitude;
//name
string name;
//data for waypoint
int altitude;
int speed;
public:
Waypoint(float latitude, float longitude, string name, int altitude = 0, int speed = 0);
float getLongitude()
{
return longitude;
}
void setLongitude(float longitude)
{
this->longitude = longitude;
}
float getLatitude()
{
return latitude;
}
void setLatitude(float latitude)
{
this->latitude = latitude;
}
string getName()
{
return name;
}
void setName(string name)
{
this->name = name;
}
int getAltitude()
{
return altitude;
}
void setAltitude(int altitude)
{
this->altitude = altitude;
}
int getSpeed()
{
return speed;
}
void setSpeed(int speed)
{
this->speed = speed;
}
};
}
#endif | [
"simjobsinc@gmail.com"
] | simjobsinc@gmail.com |
c67baf25ec6b3caf29664f5384e4bde4bef8dae7 | bd2f117637be64d13d7b94093c537d346ca3257f | /Tests/Core/Text/test.cpp | 9bf1f38555318799c98e9672708fa550e0344a26 | [
"Zlib"
] | permissive | animehunter/clanlib-2.3 | e6d6a09ff58016809d687c101b64ed4da1467562 | 7013c39f4cd1f25b0dad3bedfdb7a5cf593b1bb7 | refs/heads/master | 2016-09-10T12:56:23.015390 | 2011-12-15T20:58:59 | 2011-12-15T20:58:59 | 3,001,221 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,562 | cpp | /*
** ClanLib SDK
** Copyright (c) 1997-2011 The ClanLib Team
**
** This software is provided 'as-is', without any express or implied
** warranty. In no event will the authors be held liable for any damages
** arising from the use of this software.
**
** Permission is granted to anyone to use this software for any purpose,
** including commercial applications, and to alter it and redistribute it
** freely, subject to the following restrictions:
**
** 1. The origin of this software must not be misrepresented; you must not
** claim that you wrote the original software. If you use this software
** in a product, an acknowledgment in the product documentation would be
** appreciated but is not required.
** 2. Altered source versions must be plainly marked as such, and must not be
** misrepresented as being the original software.
** 3. This notice may not be removed or altered from any source distribution.
**
** Note: Some of the libraries ClanLib may link to may have additional
** requirements or restrictions.
**
** File Author(s):
**
** Mark Page
** (if your name is missing here, please add it)
*/
#include "test.h"
int g_bConstructor = 0;
int g_bDestructor = 0;
// This is the Program class that is called by CL_ClanApplication
class Program
{
public:
static int main(const std::vector<CL_String> &args)
{
// Initialize ClanLib base components
CL_SetupCore setup_core;
// Start the Application
TestApp app;
int retval = app.main(args);
return retval;
}
};
// Instantiate CL_ClanApplication, informing it where the Program is located
CL_ClanApplication app(&Program::main);
int TestApp::main(const std::vector<CL_String> &args)
{
// Create a console window for text-output if not available
CL_ConsoleWindow console("Console");
try
{
CL_Console::write_line("ClanLib Test Suite:");
CL_Console::write_line("-------------------");
#ifdef WIN32
CL_Console::write_line("Target: WIN32");
#else
CL_Console::write_line("Target: LINUX");
#endif
CL_Console::write_line("Directory: API/Core/Text");
str = "hello!";
CL_Console::write_line(" - %1", test_stringref());
test_string();
CL_Console::write_line("All Tests Complete");
console.display_close_message();
}
catch(CL_Exception error)
{
CL_Console::write_line("Exception caught:");
CL_Console::write_line(error.message);
console.display_close_message();
return -1;
}
return 0;
}
CL_StringRef TestApp::test_stringref()
{
return str;
}
void TestApp::fail(void)
{
throw CL_Exception("Failed Test");
}
| [
"rombust@cc39f7f4-b520-0410-a30f-b56705a9c917"
] | rombust@cc39f7f4-b520-0410-a30f-b56705a9c917 |
1d46dc09a5b43581107715c6e9d18cff9409bda4 | c2757b08e4a3a27438141423e669adcae6594ccc | /FG_Course9_cpp_group_asteroids/FG_Course9_cpp_group_asteroids/src/ResourceManager.cpp | 6c7c23a034e4b72a622a8b866b9ed42aff4c7eb1 | [] | no_license | TinyKenny/FG_Course9_cpp_group | f59ddaf4b6d2bf779ac0a4bae14c54648331e4ed | 17fbd9f21d403fd29c81b093bb524046c0199e0e | refs/heads/main | 2023-03-22T17:23:45.326030 | 2021-03-12T10:42:50 | 2021-03-12T10:42:50 | 343,375,207 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 743 | cpp | #include "ResourceManager.h"
ResourceManager::ResourceManager()
{
loadedFonts["default"] = TTF_OpenFont("res/comic.ttf", 20);
loadedSounds["shot"] = Mix_LoadWAV("res/shot.wav");
loadedSounds["hit"] = Mix_LoadWAV("res/hit.wav");
}
ResourceManager::~ResourceManager()
{
for (auto const& x : loadedSounds)
{
Mix_FreeChunk(x.second);
}
}
TTF_Font* ResourceManager::getFont(const std::string& name)
{
auto font = loadedFonts.find(name);
if (font == loadedFonts.end())
{
return nullptr;
}
else
{
return font->second;
}
}
Mix_Chunk* ResourceManager::getSoundClip(const std::string& name)
{
auto chunk = loadedSounds.find(name);
if (chunk == loadedSounds.end())
{
return nullptr;
}
else
{
return chunk->second;
}
} | [
"37851342+TeoC00l@users.noreply.github.com"
] | 37851342+TeoC00l@users.noreply.github.com |
0a58fbb9a48c2b5e1e8fc809c41766235669852c | 629a05d73fcccc21003b43d7733e5afc37b214c1 | /src/robotX/utils/TimeUtils.cpp | fb7d4d03a87321ee92373685e4f3e4103df9b6bb | [] | no_license | glee0413/robotX | 4179872b9f90194dc9dcdd9ebf344a38a526c556 | a8c9fd0b27c31ef7907248350ff4e1ef0c85e146 | refs/heads/master | 2021-01-17T19:23:51.397200 | 2017-02-14T13:43:09 | 2017-02-14T13:43:09 | 59,926,184 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,273 | cpp | /*
* TimeUtils.cpp
*
* Created on: 2016年5月11日
* Author: light
*/
#include <sys/time.h>
#include <time.h>
#include <string.h>
#include <stdio.h>
#include <utils/TimeUtils.h>
namespace Utils {
TimeUtils::TimeUtils() {
// TODO Auto-generated constructor stub
gettimeofday(&this->m_current,NULL);
}
TimeUtils::~TimeUtils() {
// TODO Auto-generated destructor stub
}
const char* TimeUtils::getLocalTime(char* time_str) {
//TODO:线程不安全,time_str,需要保存足够的长度
time_t now;
struct tm *timenow;
time(&now);
timenow = localtime(&now);
strcpy(time_str, asctime(timenow));
time_str[strlen(time_str)-1] = 0;
return time_str;
}
const char* TimeUtils::getTimeOfDay(char* time_str) {
time_t now;
struct tm *timenow;
struct timeval tv;
gettimeofday(&tv,NULL);
time(&now);
timenow = localtime(&now);
sprintf(time_str,"%02d:%02d:%02d.%06ld",timenow->tm_hour,timenow->tm_min,timenow->tm_sec,tv.tv_usec);
return time_str;
}
int TimeUtils::getDiff() {
int diff = 0;
gettimeofday(&this->m_diff, NULL);
diff = (m_diff.tv_sec - m_current.tv_sec) * 1000
+ (m_diff.tv_usec - m_current.tv_usec);
memcpy(&m_current, &m_diff, sizeof(m_current));
return diff;
}
} /* namespace Utils */
| [
"glee-0413@163.com"
] | glee-0413@163.com |
5c717326a2aa0618c3f91c7d2a007ecd4bf1de79 | 41b8c46b39698d8642df8d3b947384996e6d2167 | /src/trajectory_optimizer/cubic_bezier_curve.cpp | cb4ac4561d65970e617825e117e0c1a1b974f789 | [] | no_license | ColleyLi/TrajectoryOptimizer | dbe579258bfcfb71e06b91100aad2ffd9d7659cb | e38cd47041d3c47285db3e881a611c71b8df7d2e | refs/heads/master | 2023-04-21T21:39:30.620452 | 2021-05-19T06:02:55 | 2021-05-19T06:02:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,587 | cpp | /******************************************************************************
* Copyright 2020 The zhejiang lab Authors. All Rights Reserved.
*****************************************************************************/
/**
* @file cubic_bezier_curve.cc
**/
#include "cubic_bezier_curve.h"
namespace localPlanner
{
CubicBezierCurve::CubicBezierCurve(){}
CubicBezierTrajectory CubicBezierCurve::GetCubicBezierTrajectory(const Pointxy& p0, const Pointxy& p1, const Pointxy& p2, const Pointxy& p3, const double dt)
{
CubicBezierTrajectory trajectory;
p0_ = p0;
p1_ = p1;
p2_ = p2;
p3_ = p3;
trajectory.p0 = p0;
trajectory.p1 = p1;
trajectory.p2 = p2;
trajectory.p3 = p3;
CubicBezierCurveInterpolation(dt);
trajectory.poses = poses_;
trajectory.maxk = GetMaxCurvature();
trajectory.k0 = GetCurvatureatInitPoint();
return trajectory;
}
Pointxy CubicBezierCurve::Evaluate(const int order, const double t)
{
Pointxy point;
switch (order)
{
case 0: {
point.x = (1-t)*(1-t)*(1-t)*p0_.x+3*(1-t)*(1-t)*t*p1_.x+3*(1-t)*t*t*p2_.x+t*t*t*p3_.x;
point.y = (1-t)*(1-t)*(1-t)*p0_.y+3*(1-t)*(1-t)*t*p1_.y+3*(1-t)*t*t*p2_.y+t*t*t*p3_.y;
break;
}
case 1: {
point.x = 3*(1-t)*(1-t)*(p1_.x-p0_.x)+6*(1-t)*t*(p2_.x-p1_.x)+3*t*t*(p3_.x-p2_.x);
point.y = 3*(1-t)*(1-t)*(p1_.y-p0_.y)+6*(1-t)*t*(p2_.y-p1_.y)+3*t*t*(p3_.y-p2_.y);
break;
}
case 2: {
point.x = 6*(1-t)*(p2_.x-2*p1_.x+p0_.x)+6*t*(p3_.x-2*p2_.x+p1_.x);
point.y = 6*(1-t)*(p2_.y-2*p1_.y+p0_.y)+6*t*(p3_.y-2*p2_.y+p1_.y);
break;
}
case 3: {
point.x = -6*p0_.x+18*p1_.x-18*p2_.x+6*p3_.x;
point.y = -6*p0_.y+18*p1_.y-18*p2_.y+6*p3_.y;
break;
}
default:
point.x = 0.0;
point.y = 0.0;
}
return point;
}
double CubicBezierCurve::GetCurvatureatInitPoint(){return k0_;}
double CubicBezierCurve::GetMaxCurvature()
{
auto maxPosition = std::max_element(abscurvatures_.begin(), abscurvatures_.end());
return *maxPosition;
}
double CubicBezierCurve::GetMinCurvature()
{
auto minPosition = std::min_element(abscurvatures_.begin(), abscurvatures_.end());
return *minPosition;
}
std::vector<Pose> CubicBezierCurve::GetTrajectoryPoses()
{
return poses_;
}
std::vector<double> CubicBezierCurve::GetAllCurvatures()
{
return abscurvatures_;
}
void CubicBezierCurve::CubicBezierCurveInterpolation(const double dt)
{
poses_.clear();
abscurvatures_.clear();
double t = 0.0;
while (t <= 1.0)
{
Pose pose;
Pointxy p = Evaluate(0, t);
Pointxy dp = Evaluate(1, t);
Pointxy ddp = Evaluate(2, t);
pose.x = p.x;
pose.y = p.y;
pose.theta = std::atan2(dp.y, dp.x);
pose.kappa = (dp.x * ddp.y - dp.y * ddp.x) / pow(dp.x * dp.x + dp.y * dp.y, 1.5);
poses_.push_back(std::move(pose));
abscurvatures_.push_back(fabs((dp.x*ddp.y-dp.y*ddp.x)/pow(dp.x*dp.x+dp.y*dp.y ,1.5)));
if (t == 0.0)
{
k0_ = (dp.x*ddp.y-dp.y*ddp.x)/pow(dp.x*dp.x+dp.y*dp.y ,1.5);
}
t += dt;
}
}
} // localPlanner
| [
"shenzheng@zhejianglab.com"
] | shenzheng@zhejianglab.com |
e8cd26d509386423936089f2dc8fd0cf831da3f7 | 828ba76e1e18870bee0cc3be87a81a2f6a9ce5ea | /metUnit4NANO-bmp280/metUnit4NANO-bmp280.ino | 385aecd766867caf824d5a60096e1ca68b1103dc | [
"LicenseRef-scancode-other-permissive"
] | permissive | filipecebr1980/arduMet | 12c1148944bb42d33c0bb6b70e3d1d126c6965d2 | fb9f9dadfb38a8fa11b6b606abab0f44f22ac435 | refs/heads/master | 2022-12-25T16:23:51.818524 | 2020-10-03T23:32:32 | 2020-10-03T23:32:32 | 291,845,840 | 0 | 0 | null | 2020-10-03T23:32:33 | 2020-08-31T23:21:21 | C++ | UTF-8 | C++ | false | false | 4,794 | ino | /* Meteorological Unit - Temp, Umid and Pressure and Air Density
* V 1.2.0 - Air density enabled
*Created by Filipe Brandao Using
*Sparkfun GY-BME280 Library
*SMS0408E2 Library
*Using examples from Adafruit and Sparkfun Libraries.
*
The GY-BME280 is using address 0x76 (jumper closed)
Hardware connections:
BME280 -> Arduino
GND -> GND
3.3 -> 3.3
SDA -> A4
SCL -> A5
SUNMAN SMS0408E2
LCD -> Arduino
VDD -> 12
DI -> 11
VSS -> 10
CLK -> 9
REQUIRES the following Arduino libraries:
- https://github.com/sparkfun/SparkFun_BME280_Arduino_Library
- Adafruit Unified Sensor Lib: https://github.com/adafruit/Adafruit_Sensor
- SUNMAN SMS0408E2 LDC 7 Segments display: https://github.com/filipecebr1980/Sunman-SMS0408E2
*/
#include <Adafruit_Sensor.h>
#include <Sms0408.h>
#include <Wire.h>
#include "SparkFunBME280.h"
uint32_t delayMS=2000;
int VDD_PIN=12;
int DI_PIN=11;
int VSS_PIN=10;
int CLK_PIN=9;
int BLA_PIN=8;
int BLK_PIN=7;
//create an LCD object
Sms0408 myLCD(DI_PIN,CLK_PIN,BLK_PIN);
//create sensor object
BME280 mySensor;
void setup() {
//Configure Pins as OUTPUT
pinMode(VSS_PIN,OUTPUT);
pinMode(VDD_PIN,OUTPUT);
pinMode(CLK_PIN,OUTPUT);
pinMode(DI_PIN,OUTPUT);
pinMode(BLA_PIN,OUTPUT);
pinMode(BLK_PIN,OUTPUT);
//powers up SUNMAN SMS0408
digitalWrite(VDD_PIN, HIGH);
digitalWrite(VSS_PIN, LOW);
digitalWrite(BLA_PIN, HIGH);
digitalWrite(BLK_PIN, LOW);
Serial.begin(9600);
Serial.println("System started");
Wire.begin();
mySensor.setI2CAddress(0x76); //Connect to sensor
if(mySensor.beginI2C() == false) {
Serial.println("Sensor B connect failed!");
myLCD.displayError();
myLCD.adjust();
while(1){}
}
Serial.println("Sensor conection OK!");
//tests lcd (all segments ON for 1 second
testLcd();
delay(delayMS);
}
void loop() {
//shows temperature in C°
//displayTemp(-10.0);
displayTemp(mySensor.readTempC());
delay(delayMS);
sendSerial();
//shows humidity in %
displayHumid(mySensor.readFloatHumidity());
delay(delayMS);
sendSerial();
//shows pressure in hPa (millibar)
displayPressure(mySensor.readFloatPressure()/100.0);
delay(delayMS);
sendSerial();
//shows air density in kg/m³
displayPressure(airDensity());
delay(delayMS);
sendSerial();
}
void displayTemp(float temp){
//shows temperature in C°
if (temp>=0.0){
myLCD.clearLCD();
myLCD.displayInt((int)temp);
myLCD.codig(18,0);
myLCD.adjust();
}
else {
//for negative temperature
myLCD.clearLCD();
myLCD.codig(19,0);
myLCD.displayInt((int)(abs(temp)));
myLCD.codig(18,0);
myLCD.adjust();
}
}
void displayHumid(float humid){
//shows relative humidity, not more than 99%
if (humid >=100.0){
humid=99.0;
}
myLCD.clearLCD();
myLCD.showColumn();
myLCD.codig(17,0);
myLCD.codig(16,0);
myLCD.displayInt((int)humid);
myLCD.adjust();
}
void displayPressure(float pressure){
myLCD.clearLCD();
if(pressure < 1000.0){
myLCD.displayFloatAuto(pressure);
}
else
{
myLCD.displayInt((int)pressure);
}
myLCD.adjust();
}
void displayAirDensity(){
myLCD.clearLCD();
myLCD.displayFloatAuto(airDensity());
myLCD.adjust();
}
void testLcd(){
//fills LCD (all segments on- good to test if has any
//bad segment
myLCD.fillLCD();
delay(1000);
myLCD.clearLCD();
}
/*This funcion calculates air density as funcion of Temp, Press and Rel.Humidity
* Uses the methodology of defining dry air pressure and water vapor pressure
* as well as using the universal constants for ideal gases for both water vapor and dry air.
* For more detail about this calculation, visit: https://www.omnicalculator.com/physics/air-density
*/
float airDensity(){
double t,p,rh,p1,pv,pd,Rd,Rv,density;
//Specific gas constant for dry air: 287.058 J/(Kg.K)
Rd=287.058;
//Specific gas constant for water vapor 461.495 J/(Kg.K)
Rv=461.495;
//reads temp in C°
t=(double)mySensor.readTempC();
//read pressure in Pa
p=(double)mySensor.readFloatPressure();
//reads rel humidity
rh=(double)mySensor.readFloatHumidity();
//calculates the saturation vapor pressure, temperature converted to Kelvin
p1=6.1078*pow(10,7.5*t/(t+237.3));
//actual vapor pressure in function of relative humidity and temperature
pv=p1*rh;
//actual dry air pressure
pd=p-pv;
//temperatute in kelvin:
t=t+273.15;
//calculates air density:
density = (pd/(Rd*t))+(pv/(Rv*t));
return (float)density;
}
void sendSerial(){
Serial.print((String)mySensor.readTempC()+" " + (String)mySensor.readFloatHumidity()+ " " + (String)mySensor.readFloatPressure()+" ");
Serial.println(airDensity(),3);
}
| [
"filipecebr@gmail.com"
] | filipecebr@gmail.com |
60b4b9e051b95945cdca4e8f2ceda5e560c1163d | c776476e9d06b3779d744641e758ac3a2c15cddc | /examples/litmus/c/run-scripts/tmp_1/MP+dmb.sy+data-wsi-rfi-addr-[fr-rf].c.cbmc.cpp | 38485c36e024b6bac75ced7496c0bfaadc1b8c75 | [] | no_license | ashutosh0gupta/llvm_bmc | aaac7961c723ba6f7ffd77a39559e0e52432eade | 0287c4fb180244e6b3c599a9902507f05c8a7234 | refs/heads/master | 2023-08-02T17:14:06.178723 | 2023-07-31T10:46:53 | 2023-07-31T10:46:53 | 143,100,825 | 3 | 4 | null | 2023-05-25T05:50:55 | 2018-08-01T03:47:00 | C++ | UTF-8 | C++ | false | false | 57,353 | cpp | // 0:vars:3
// 3:atom_1_X0_1:1
// 8:thr1:1
// 9:thr2:1
// 4:atom_1_X5_2:1
// 5:atom_1_X7_0:1
// 6:atom_1_X9_1:1
// 7:thr0:1
#define ADDRSIZE 10
#define NPROC 4
#define NCONTEXT 1
#define ASSUME(stmt) __CPROVER_assume(stmt)
#define ASSERT(stmt) __CPROVER_assert(stmt, "error")
#define max(a,b) (a>b?a:b)
char __get_rng();
char get_rng( char from, char to ) {
char ret = __get_rng();
ASSUME(ret >= from && ret <= to);
return ret;
}
char get_rng_th( char from, char to ) {
char ret = __get_rng();
ASSUME(ret >= from && ret <= to);
return ret;
}
int main(int argc, char **argv) {
// declare arrays for intial value version in contexts
int meminit_[ADDRSIZE*NCONTEXT];
#define meminit(x,k) meminit_[(x)*NCONTEXT+k]
int coinit_[ADDRSIZE*NCONTEXT];
#define coinit(x,k) coinit_[(x)*NCONTEXT+k]
int deltainit_[ADDRSIZE*NCONTEXT];
#define deltainit(x,k) deltainit_[(x)*NCONTEXT+k]
// declare arrays for running value version in contexts
int mem_[ADDRSIZE*NCONTEXT];
#define mem(x,k) mem_[(x)*NCONTEXT+k]
int co_[ADDRSIZE*NCONTEXT];
#define co(x,k) co_[(x)*NCONTEXT+k]
int delta_[ADDRSIZE*NCONTEXT];
#define delta(x,k) delta_[(x)*NCONTEXT+k]
// declare arrays for local buffer and observed writes
int buff_[NPROC*ADDRSIZE];
#define buff(x,k) buff_[(x)*ADDRSIZE+k]
int pw_[NPROC*ADDRSIZE];
#define pw(x,k) pw_[(x)*ADDRSIZE+k]
// declare arrays for context stamps
char cr_[NPROC*ADDRSIZE];
#define cr(x,k) cr_[(x)*ADDRSIZE+k]
char iw_[NPROC*ADDRSIZE];
#define iw(x,k) iw_[(x)*ADDRSIZE+k]
char cw_[NPROC*ADDRSIZE];
#define cw(x,k) cw_[(x)*ADDRSIZE+k]
char cx_[NPROC*ADDRSIZE];
#define cx(x,k) cx_[(x)*ADDRSIZE+k]
char is_[NPROC*ADDRSIZE];
#define is(x,k) is_[(x)*ADDRSIZE+k]
char cs_[NPROC*ADDRSIZE];
#define cs(x,k) cs_[(x)*ADDRSIZE+k]
char crmax_[NPROC*ADDRSIZE];
#define crmax(x,k) crmax_[(x)*ADDRSIZE+k]
char sforbid_[ADDRSIZE*NCONTEXT];
#define sforbid(x,k) sforbid_[(x)*NCONTEXT+k]
// declare arrays for synchronizations
int cl[NPROC];
int cdy[NPROC];
int cds[NPROC];
int cdl[NPROC];
int cisb[NPROC];
int caddr[NPROC];
int cctrl[NPROC];
int cstart[NPROC];
int creturn[NPROC];
// declare arrays for contexts activity
int active[NCONTEXT];
int ctx_used[NCONTEXT];
__LOCALS__
buff(0,0) = 0;
pw(0,0) = 0;
cr(0,0) = 0;
iw(0,0) = 0;
cw(0,0) = 0;
cx(0,0) = 0;
is(0,0) = 0;
cs(0,0) = 0;
crmax(0,0) = 0;
buff(0,1) = 0;
pw(0,1) = 0;
cr(0,1) = 0;
iw(0,1) = 0;
cw(0,1) = 0;
cx(0,1) = 0;
is(0,1) = 0;
cs(0,1) = 0;
crmax(0,1) = 0;
buff(0,2) = 0;
pw(0,2) = 0;
cr(0,2) = 0;
iw(0,2) = 0;
cw(0,2) = 0;
cx(0,2) = 0;
is(0,2) = 0;
cs(0,2) = 0;
crmax(0,2) = 0;
buff(0,3) = 0;
pw(0,3) = 0;
cr(0,3) = 0;
iw(0,3) = 0;
cw(0,3) = 0;
cx(0,3) = 0;
is(0,3) = 0;
cs(0,3) = 0;
crmax(0,3) = 0;
buff(0,4) = 0;
pw(0,4) = 0;
cr(0,4) = 0;
iw(0,4) = 0;
cw(0,4) = 0;
cx(0,4) = 0;
is(0,4) = 0;
cs(0,4) = 0;
crmax(0,4) = 0;
buff(0,5) = 0;
pw(0,5) = 0;
cr(0,5) = 0;
iw(0,5) = 0;
cw(0,5) = 0;
cx(0,5) = 0;
is(0,5) = 0;
cs(0,5) = 0;
crmax(0,5) = 0;
buff(0,6) = 0;
pw(0,6) = 0;
cr(0,6) = 0;
iw(0,6) = 0;
cw(0,6) = 0;
cx(0,6) = 0;
is(0,6) = 0;
cs(0,6) = 0;
crmax(0,6) = 0;
buff(0,7) = 0;
pw(0,7) = 0;
cr(0,7) = 0;
iw(0,7) = 0;
cw(0,7) = 0;
cx(0,7) = 0;
is(0,7) = 0;
cs(0,7) = 0;
crmax(0,7) = 0;
buff(0,8) = 0;
pw(0,8) = 0;
cr(0,8) = 0;
iw(0,8) = 0;
cw(0,8) = 0;
cx(0,8) = 0;
is(0,8) = 0;
cs(0,8) = 0;
crmax(0,8) = 0;
buff(0,9) = 0;
pw(0,9) = 0;
cr(0,9) = 0;
iw(0,9) = 0;
cw(0,9) = 0;
cx(0,9) = 0;
is(0,9) = 0;
cs(0,9) = 0;
crmax(0,9) = 0;
cl[0] = 0;
cdy[0] = 0;
cds[0] = 0;
cdl[0] = 0;
cisb[0] = 0;
caddr[0] = 0;
cctrl[0] = 0;
cstart[0] = get_rng(0,NCONTEXT-1);
creturn[0] = get_rng(0,NCONTEXT-1);
buff(1,0) = 0;
pw(1,0) = 0;
cr(1,0) = 0;
iw(1,0) = 0;
cw(1,0) = 0;
cx(1,0) = 0;
is(1,0) = 0;
cs(1,0) = 0;
crmax(1,0) = 0;
buff(1,1) = 0;
pw(1,1) = 0;
cr(1,1) = 0;
iw(1,1) = 0;
cw(1,1) = 0;
cx(1,1) = 0;
is(1,1) = 0;
cs(1,1) = 0;
crmax(1,1) = 0;
buff(1,2) = 0;
pw(1,2) = 0;
cr(1,2) = 0;
iw(1,2) = 0;
cw(1,2) = 0;
cx(1,2) = 0;
is(1,2) = 0;
cs(1,2) = 0;
crmax(1,2) = 0;
buff(1,3) = 0;
pw(1,3) = 0;
cr(1,3) = 0;
iw(1,3) = 0;
cw(1,3) = 0;
cx(1,3) = 0;
is(1,3) = 0;
cs(1,3) = 0;
crmax(1,3) = 0;
buff(1,4) = 0;
pw(1,4) = 0;
cr(1,4) = 0;
iw(1,4) = 0;
cw(1,4) = 0;
cx(1,4) = 0;
is(1,4) = 0;
cs(1,4) = 0;
crmax(1,4) = 0;
buff(1,5) = 0;
pw(1,5) = 0;
cr(1,5) = 0;
iw(1,5) = 0;
cw(1,5) = 0;
cx(1,5) = 0;
is(1,5) = 0;
cs(1,5) = 0;
crmax(1,5) = 0;
buff(1,6) = 0;
pw(1,6) = 0;
cr(1,6) = 0;
iw(1,6) = 0;
cw(1,6) = 0;
cx(1,6) = 0;
is(1,6) = 0;
cs(1,6) = 0;
crmax(1,6) = 0;
buff(1,7) = 0;
pw(1,7) = 0;
cr(1,7) = 0;
iw(1,7) = 0;
cw(1,7) = 0;
cx(1,7) = 0;
is(1,7) = 0;
cs(1,7) = 0;
crmax(1,7) = 0;
buff(1,8) = 0;
pw(1,8) = 0;
cr(1,8) = 0;
iw(1,8) = 0;
cw(1,8) = 0;
cx(1,8) = 0;
is(1,8) = 0;
cs(1,8) = 0;
crmax(1,8) = 0;
buff(1,9) = 0;
pw(1,9) = 0;
cr(1,9) = 0;
iw(1,9) = 0;
cw(1,9) = 0;
cx(1,9) = 0;
is(1,9) = 0;
cs(1,9) = 0;
crmax(1,9) = 0;
cl[1] = 0;
cdy[1] = 0;
cds[1] = 0;
cdl[1] = 0;
cisb[1] = 0;
caddr[1] = 0;
cctrl[1] = 0;
cstart[1] = get_rng(0,NCONTEXT-1);
creturn[1] = get_rng(0,NCONTEXT-1);
buff(2,0) = 0;
pw(2,0) = 0;
cr(2,0) = 0;
iw(2,0) = 0;
cw(2,0) = 0;
cx(2,0) = 0;
is(2,0) = 0;
cs(2,0) = 0;
crmax(2,0) = 0;
buff(2,1) = 0;
pw(2,1) = 0;
cr(2,1) = 0;
iw(2,1) = 0;
cw(2,1) = 0;
cx(2,1) = 0;
is(2,1) = 0;
cs(2,1) = 0;
crmax(2,1) = 0;
buff(2,2) = 0;
pw(2,2) = 0;
cr(2,2) = 0;
iw(2,2) = 0;
cw(2,2) = 0;
cx(2,2) = 0;
is(2,2) = 0;
cs(2,2) = 0;
crmax(2,2) = 0;
buff(2,3) = 0;
pw(2,3) = 0;
cr(2,3) = 0;
iw(2,3) = 0;
cw(2,3) = 0;
cx(2,3) = 0;
is(2,3) = 0;
cs(2,3) = 0;
crmax(2,3) = 0;
buff(2,4) = 0;
pw(2,4) = 0;
cr(2,4) = 0;
iw(2,4) = 0;
cw(2,4) = 0;
cx(2,4) = 0;
is(2,4) = 0;
cs(2,4) = 0;
crmax(2,4) = 0;
buff(2,5) = 0;
pw(2,5) = 0;
cr(2,5) = 0;
iw(2,5) = 0;
cw(2,5) = 0;
cx(2,5) = 0;
is(2,5) = 0;
cs(2,5) = 0;
crmax(2,5) = 0;
buff(2,6) = 0;
pw(2,6) = 0;
cr(2,6) = 0;
iw(2,6) = 0;
cw(2,6) = 0;
cx(2,6) = 0;
is(2,6) = 0;
cs(2,6) = 0;
crmax(2,6) = 0;
buff(2,7) = 0;
pw(2,7) = 0;
cr(2,7) = 0;
iw(2,7) = 0;
cw(2,7) = 0;
cx(2,7) = 0;
is(2,7) = 0;
cs(2,7) = 0;
crmax(2,7) = 0;
buff(2,8) = 0;
pw(2,8) = 0;
cr(2,8) = 0;
iw(2,8) = 0;
cw(2,8) = 0;
cx(2,8) = 0;
is(2,8) = 0;
cs(2,8) = 0;
crmax(2,8) = 0;
buff(2,9) = 0;
pw(2,9) = 0;
cr(2,9) = 0;
iw(2,9) = 0;
cw(2,9) = 0;
cx(2,9) = 0;
is(2,9) = 0;
cs(2,9) = 0;
crmax(2,9) = 0;
cl[2] = 0;
cdy[2] = 0;
cds[2] = 0;
cdl[2] = 0;
cisb[2] = 0;
caddr[2] = 0;
cctrl[2] = 0;
cstart[2] = get_rng(0,NCONTEXT-1);
creturn[2] = get_rng(0,NCONTEXT-1);
buff(3,0) = 0;
pw(3,0) = 0;
cr(3,0) = 0;
iw(3,0) = 0;
cw(3,0) = 0;
cx(3,0) = 0;
is(3,0) = 0;
cs(3,0) = 0;
crmax(3,0) = 0;
buff(3,1) = 0;
pw(3,1) = 0;
cr(3,1) = 0;
iw(3,1) = 0;
cw(3,1) = 0;
cx(3,1) = 0;
is(3,1) = 0;
cs(3,1) = 0;
crmax(3,1) = 0;
buff(3,2) = 0;
pw(3,2) = 0;
cr(3,2) = 0;
iw(3,2) = 0;
cw(3,2) = 0;
cx(3,2) = 0;
is(3,2) = 0;
cs(3,2) = 0;
crmax(3,2) = 0;
buff(3,3) = 0;
pw(3,3) = 0;
cr(3,3) = 0;
iw(3,3) = 0;
cw(3,3) = 0;
cx(3,3) = 0;
is(3,3) = 0;
cs(3,3) = 0;
crmax(3,3) = 0;
buff(3,4) = 0;
pw(3,4) = 0;
cr(3,4) = 0;
iw(3,4) = 0;
cw(3,4) = 0;
cx(3,4) = 0;
is(3,4) = 0;
cs(3,4) = 0;
crmax(3,4) = 0;
buff(3,5) = 0;
pw(3,5) = 0;
cr(3,5) = 0;
iw(3,5) = 0;
cw(3,5) = 0;
cx(3,5) = 0;
is(3,5) = 0;
cs(3,5) = 0;
crmax(3,5) = 0;
buff(3,6) = 0;
pw(3,6) = 0;
cr(3,6) = 0;
iw(3,6) = 0;
cw(3,6) = 0;
cx(3,6) = 0;
is(3,6) = 0;
cs(3,6) = 0;
crmax(3,6) = 0;
buff(3,7) = 0;
pw(3,7) = 0;
cr(3,7) = 0;
iw(3,7) = 0;
cw(3,7) = 0;
cx(3,7) = 0;
is(3,7) = 0;
cs(3,7) = 0;
crmax(3,7) = 0;
buff(3,8) = 0;
pw(3,8) = 0;
cr(3,8) = 0;
iw(3,8) = 0;
cw(3,8) = 0;
cx(3,8) = 0;
is(3,8) = 0;
cs(3,8) = 0;
crmax(3,8) = 0;
buff(3,9) = 0;
pw(3,9) = 0;
cr(3,9) = 0;
iw(3,9) = 0;
cw(3,9) = 0;
cx(3,9) = 0;
is(3,9) = 0;
cs(3,9) = 0;
crmax(3,9) = 0;
cl[3] = 0;
cdy[3] = 0;
cds[3] = 0;
cdl[3] = 0;
cisb[3] = 0;
caddr[3] = 0;
cctrl[3] = 0;
cstart[3] = get_rng(0,NCONTEXT-1);
creturn[3] = get_rng(0,NCONTEXT-1);
// Dumping initializations
mem(0+0,0) = 0;
mem(0+1,0) = 0;
mem(0+2,0) = 0;
mem(3+0,0) = 0;
mem(8+0,0) = 0;
mem(9+0,0) = 0;
mem(4+0,0) = 0;
mem(5+0,0) = 0;
mem(6+0,0) = 0;
mem(7+0,0) = 0;
// Dumping context matching equalities
co(0,0) = 0;
delta(0,0) = -1;
co(1,0) = 0;
delta(1,0) = -1;
co(2,0) = 0;
delta(2,0) = -1;
co(3,0) = 0;
delta(3,0) = -1;
co(4,0) = 0;
delta(4,0) = -1;
co(5,0) = 0;
delta(5,0) = -1;
co(6,0) = 0;
delta(6,0) = -1;
co(7,0) = 0;
delta(7,0) = -1;
co(8,0) = 0;
delta(8,0) = -1;
co(9,0) = 0;
delta(9,0) = -1;
// Dumping thread 1
int ret_thread_1 = 0;
cdy[1] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[1] >= cstart[1]);
T1BLOCK0:
// call void @llvm.dbg.value(metadata i8* %arg, metadata !39, metadata !DIExpression()), !dbg !48
// br label %label_1, !dbg !49
goto T1BLOCK1;
T1BLOCK1:
// call void @llvm.dbg.label(metadata !47), !dbg !50
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !40, metadata !DIExpression()), !dbg !51
// call void @llvm.dbg.value(metadata i64 2, metadata !43, metadata !DIExpression()), !dbg !51
// store atomic i64 2, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !52
// ST: Guess
iw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW
old_cw = cw(1,0);
cw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM
// Check
ASSUME(active[iw(1,0)] == 1);
ASSUME(active[cw(1,0)] == 1);
ASSUME(sforbid(0,cw(1,0))== 0);
ASSUME(iw(1,0) >= 0);
ASSUME(iw(1,0) >= 0);
ASSUME(cw(1,0) >= iw(1,0));
ASSUME(cw(1,0) >= old_cw);
ASSUME(cw(1,0) >= cr(1,0));
ASSUME(cw(1,0) >= cl[1]);
ASSUME(cw(1,0) >= cisb[1]);
ASSUME(cw(1,0) >= cdy[1]);
ASSUME(cw(1,0) >= cdl[1]);
ASSUME(cw(1,0) >= cds[1]);
ASSUME(cw(1,0) >= cctrl[1]);
ASSUME(cw(1,0) >= caddr[1]);
// Update
caddr[1] = max(caddr[1],0);
buff(1,0) = 2;
mem(0,cw(1,0)) = 2;
co(0,cw(1,0))+=1;
delta(0,cw(1,0)) = -1;
ASSUME(creturn[1] >= cw(1,0));
// call void (...) @dmbsy(), !dbg !53
// dumbsy: Guess
old_cdy = cdy[1];
cdy[1] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[1] >= old_cdy);
ASSUME(cdy[1] >= cisb[1]);
ASSUME(cdy[1] >= cdl[1]);
ASSUME(cdy[1] >= cds[1]);
ASSUME(cdy[1] >= cctrl[1]);
ASSUME(cdy[1] >= cw(1,0+0));
ASSUME(cdy[1] >= cw(1,0+1));
ASSUME(cdy[1] >= cw(1,0+2));
ASSUME(cdy[1] >= cw(1,3+0));
ASSUME(cdy[1] >= cw(1,8+0));
ASSUME(cdy[1] >= cw(1,9+0));
ASSUME(cdy[1] >= cw(1,4+0));
ASSUME(cdy[1] >= cw(1,5+0));
ASSUME(cdy[1] >= cw(1,6+0));
ASSUME(cdy[1] >= cw(1,7+0));
ASSUME(cdy[1] >= cr(1,0+0));
ASSUME(cdy[1] >= cr(1,0+1));
ASSUME(cdy[1] >= cr(1,0+2));
ASSUME(cdy[1] >= cr(1,3+0));
ASSUME(cdy[1] >= cr(1,8+0));
ASSUME(cdy[1] >= cr(1,9+0));
ASSUME(cdy[1] >= cr(1,4+0));
ASSUME(cdy[1] >= cr(1,5+0));
ASSUME(cdy[1] >= cr(1,6+0));
ASSUME(cdy[1] >= cr(1,7+0));
ASSUME(creturn[1] >= cdy[1]);
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !44, metadata !DIExpression()), !dbg !54
// call void @llvm.dbg.value(metadata i64 1, metadata !46, metadata !DIExpression()), !dbg !54
// store atomic i64 1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !55
// ST: Guess
iw(1,0+1*1) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW
old_cw = cw(1,0+1*1);
cw(1,0+1*1) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM
// Check
ASSUME(active[iw(1,0+1*1)] == 1);
ASSUME(active[cw(1,0+1*1)] == 1);
ASSUME(sforbid(0+1*1,cw(1,0+1*1))== 0);
ASSUME(iw(1,0+1*1) >= 0);
ASSUME(iw(1,0+1*1) >= 0);
ASSUME(cw(1,0+1*1) >= iw(1,0+1*1));
ASSUME(cw(1,0+1*1) >= old_cw);
ASSUME(cw(1,0+1*1) >= cr(1,0+1*1));
ASSUME(cw(1,0+1*1) >= cl[1]);
ASSUME(cw(1,0+1*1) >= cisb[1]);
ASSUME(cw(1,0+1*1) >= cdy[1]);
ASSUME(cw(1,0+1*1) >= cdl[1]);
ASSUME(cw(1,0+1*1) >= cds[1]);
ASSUME(cw(1,0+1*1) >= cctrl[1]);
ASSUME(cw(1,0+1*1) >= caddr[1]);
// Update
caddr[1] = max(caddr[1],0);
buff(1,0+1*1) = 1;
mem(0+1*1,cw(1,0+1*1)) = 1;
co(0+1*1,cw(1,0+1*1))+=1;
delta(0+1*1,cw(1,0+1*1)) = -1;
ASSUME(creturn[1] >= cw(1,0+1*1));
// ret i8* null, !dbg !56
ret_thread_1 = (- 1);
// Dumping thread 2
int ret_thread_2 = 0;
cdy[2] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[2] >= cstart[2]);
T2BLOCK0:
// call void @llvm.dbg.value(metadata i8* %arg, metadata !59, metadata !DIExpression()), !dbg !103
// br label %label_2, !dbg !85
goto T2BLOCK1;
T2BLOCK1:
// call void @llvm.dbg.label(metadata !102), !dbg !105
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !62, metadata !DIExpression()), !dbg !106
// %0 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !88
// LD: Guess
old_cr = cr(2,0+1*1);
cr(2,0+1*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN LDCOM
// Check
ASSUME(active[cr(2,0+1*1)] == 2);
ASSUME(cr(2,0+1*1) >= iw(2,0+1*1));
ASSUME(cr(2,0+1*1) >= 0);
ASSUME(cr(2,0+1*1) >= cdy[2]);
ASSUME(cr(2,0+1*1) >= cisb[2]);
ASSUME(cr(2,0+1*1) >= cdl[2]);
ASSUME(cr(2,0+1*1) >= cl[2]);
// Update
creg_r0 = cr(2,0+1*1);
crmax(2,0+1*1) = max(crmax(2,0+1*1),cr(2,0+1*1));
caddr[2] = max(caddr[2],0);
if(cr(2,0+1*1) < cw(2,0+1*1)) {
r0 = buff(2,0+1*1);
} else {
if(pw(2,0+1*1) != co(0+1*1,cr(2,0+1*1))) {
ASSUME(cr(2,0+1*1) >= old_cr);
}
pw(2,0+1*1) = co(0+1*1,cr(2,0+1*1));
r0 = mem(0+1*1,cr(2,0+1*1));
}
ASSUME(creturn[2] >= cr(2,0+1*1));
// call void @llvm.dbg.value(metadata i64 %0, metadata !64, metadata !DIExpression()), !dbg !106
// %conv = trunc i64 %0 to i32, !dbg !89
// call void @llvm.dbg.value(metadata i32 %conv, metadata !60, metadata !DIExpression()), !dbg !103
// %xor = xor i32 %conv, %conv, !dbg !90
creg_r1 = max(creg_r0,creg_r0);
ASSUME(active[creg_r1] == 2);
r1 = r0 ^ r0;
// call void @llvm.dbg.value(metadata i32 %xor, metadata !65, metadata !DIExpression()), !dbg !103
// %add = add nsw i32 %xor, 1, !dbg !91
creg_r2 = max(creg_r1,0);
ASSUME(active[creg_r2] == 2);
r2 = r1 + 1;
// call void @llvm.dbg.value(metadata i32 %add, metadata !66, metadata !DIExpression()), !dbg !103
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !67, metadata !DIExpression()), !dbg !111
// %conv1 = sext i32 %add to i64, !dbg !93
// call void @llvm.dbg.value(metadata i64 %conv1, metadata !69, metadata !DIExpression()), !dbg !111
// store atomic i64 %conv1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !93
// ST: Guess
iw(2,0+2*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW
old_cw = cw(2,0+2*1);
cw(2,0+2*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM
// Check
ASSUME(active[iw(2,0+2*1)] == 2);
ASSUME(active[cw(2,0+2*1)] == 2);
ASSUME(sforbid(0+2*1,cw(2,0+2*1))== 0);
ASSUME(iw(2,0+2*1) >= creg_r2);
ASSUME(iw(2,0+2*1) >= 0);
ASSUME(cw(2,0+2*1) >= iw(2,0+2*1));
ASSUME(cw(2,0+2*1) >= old_cw);
ASSUME(cw(2,0+2*1) >= cr(2,0+2*1));
ASSUME(cw(2,0+2*1) >= cl[2]);
ASSUME(cw(2,0+2*1) >= cisb[2]);
ASSUME(cw(2,0+2*1) >= cdy[2]);
ASSUME(cw(2,0+2*1) >= cdl[2]);
ASSUME(cw(2,0+2*1) >= cds[2]);
ASSUME(cw(2,0+2*1) >= cctrl[2]);
ASSUME(cw(2,0+2*1) >= caddr[2]);
// Update
caddr[2] = max(caddr[2],0);
buff(2,0+2*1) = r2;
mem(0+2*1,cw(2,0+2*1)) = r2;
co(0+2*1,cw(2,0+2*1))+=1;
delta(0+2*1,cw(2,0+2*1)) = -1;
ASSUME(creturn[2] >= cw(2,0+2*1));
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !70, metadata !DIExpression()), !dbg !113
// call void @llvm.dbg.value(metadata i64 2, metadata !72, metadata !DIExpression()), !dbg !113
// store atomic i64 2, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !95
// ST: Guess
iw(2,0+2*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW
old_cw = cw(2,0+2*1);
cw(2,0+2*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM
// Check
ASSUME(active[iw(2,0+2*1)] == 2);
ASSUME(active[cw(2,0+2*1)] == 2);
ASSUME(sforbid(0+2*1,cw(2,0+2*1))== 0);
ASSUME(iw(2,0+2*1) >= 0);
ASSUME(iw(2,0+2*1) >= 0);
ASSUME(cw(2,0+2*1) >= iw(2,0+2*1));
ASSUME(cw(2,0+2*1) >= old_cw);
ASSUME(cw(2,0+2*1) >= cr(2,0+2*1));
ASSUME(cw(2,0+2*1) >= cl[2]);
ASSUME(cw(2,0+2*1) >= cisb[2]);
ASSUME(cw(2,0+2*1) >= cdy[2]);
ASSUME(cw(2,0+2*1) >= cdl[2]);
ASSUME(cw(2,0+2*1) >= cds[2]);
ASSUME(cw(2,0+2*1) >= cctrl[2]);
ASSUME(cw(2,0+2*1) >= caddr[2]);
// Update
caddr[2] = max(caddr[2],0);
buff(2,0+2*1) = 2;
mem(0+2*1,cw(2,0+2*1)) = 2;
co(0+2*1,cw(2,0+2*1))+=1;
delta(0+2*1,cw(2,0+2*1)) = -1;
ASSUME(creturn[2] >= cw(2,0+2*1));
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !74, metadata !DIExpression()), !dbg !115
// %1 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !97
// LD: Guess
old_cr = cr(2,0+2*1);
cr(2,0+2*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN LDCOM
// Check
ASSUME(active[cr(2,0+2*1)] == 2);
ASSUME(cr(2,0+2*1) >= iw(2,0+2*1));
ASSUME(cr(2,0+2*1) >= 0);
ASSUME(cr(2,0+2*1) >= cdy[2]);
ASSUME(cr(2,0+2*1) >= cisb[2]);
ASSUME(cr(2,0+2*1) >= cdl[2]);
ASSUME(cr(2,0+2*1) >= cl[2]);
// Update
creg_r3 = cr(2,0+2*1);
crmax(2,0+2*1) = max(crmax(2,0+2*1),cr(2,0+2*1));
caddr[2] = max(caddr[2],0);
if(cr(2,0+2*1) < cw(2,0+2*1)) {
r3 = buff(2,0+2*1);
} else {
if(pw(2,0+2*1) != co(0+2*1,cr(2,0+2*1))) {
ASSUME(cr(2,0+2*1) >= old_cr);
}
pw(2,0+2*1) = co(0+2*1,cr(2,0+2*1));
r3 = mem(0+2*1,cr(2,0+2*1));
}
ASSUME(creturn[2] >= cr(2,0+2*1));
// call void @llvm.dbg.value(metadata i64 %1, metadata !76, metadata !DIExpression()), !dbg !115
// %conv7 = trunc i64 %1 to i32, !dbg !98
// call void @llvm.dbg.value(metadata i32 %conv7, metadata !73, metadata !DIExpression()), !dbg !103
// %xor8 = xor i32 %conv7, %conv7, !dbg !99
creg_r4 = max(creg_r3,creg_r3);
ASSUME(active[creg_r4] == 2);
r4 = r3 ^ r3;
// call void @llvm.dbg.value(metadata i32 %xor8, metadata !77, metadata !DIExpression()), !dbg !103
// %add10 = add nsw i32 0, %xor8, !dbg !100
creg_r5 = max(0,creg_r4);
ASSUME(active[creg_r5] == 2);
r5 = 0 + r4;
// %idxprom = sext i32 %add10 to i64, !dbg !100
// %arrayidx = getelementptr inbounds [3 x i64], [3 x i64]* @vars, i64 0, i64 %idxprom, !dbg !100
r6 = 0+r5*1;
ASSUME(creg_r6 >= 0);
ASSUME(creg_r6 >= creg_r5);
ASSUME(active[creg_r6] == 2);
// call void @llvm.dbg.value(metadata i64* %arrayidx, metadata !79, metadata !DIExpression()), !dbg !120
// %2 = load atomic i64, i64* %arrayidx monotonic, align 8, !dbg !100
// LD: Guess
old_cr = cr(2,r6);
cr(2,r6) = get_rng(0,NCONTEXT-1);// 2 ASSIGN LDCOM
// Check
ASSUME(active[cr(2,r6)] == 2);
ASSUME(cr(2,r6) >= iw(2,r6));
ASSUME(cr(2,r6) >= creg_r6);
ASSUME(cr(2,r6) >= cdy[2]);
ASSUME(cr(2,r6) >= cisb[2]);
ASSUME(cr(2,r6) >= cdl[2]);
ASSUME(cr(2,r6) >= cl[2]);
// Update
creg_r7 = cr(2,r6);
crmax(2,r6) = max(crmax(2,r6),cr(2,r6));
caddr[2] = max(caddr[2],creg_r6);
if(cr(2,r6) < cw(2,r6)) {
r7 = buff(2,r6);
} else {
if(pw(2,r6) != co(r6,cr(2,r6))) {
ASSUME(cr(2,r6) >= old_cr);
}
pw(2,r6) = co(r6,cr(2,r6));
r7 = mem(r6,cr(2,r6));
}
ASSUME(creturn[2] >= cr(2,r6));
// call void @llvm.dbg.value(metadata i64 %2, metadata !81, metadata !DIExpression()), !dbg !120
// %conv13 = trunc i64 %2 to i32, !dbg !102
// call void @llvm.dbg.value(metadata i32 %conv13, metadata !78, metadata !DIExpression()), !dbg !103
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !83, metadata !DIExpression()), !dbg !122
// %3 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !104
// LD: Guess
old_cr = cr(2,0);
cr(2,0) = get_rng(0,NCONTEXT-1);// 2 ASSIGN LDCOM
// Check
ASSUME(active[cr(2,0)] == 2);
ASSUME(cr(2,0) >= iw(2,0));
ASSUME(cr(2,0) >= 0);
ASSUME(cr(2,0) >= cdy[2]);
ASSUME(cr(2,0) >= cisb[2]);
ASSUME(cr(2,0) >= cdl[2]);
ASSUME(cr(2,0) >= cl[2]);
// Update
creg_r8 = cr(2,0);
crmax(2,0) = max(crmax(2,0),cr(2,0));
caddr[2] = max(caddr[2],0);
if(cr(2,0) < cw(2,0)) {
r8 = buff(2,0);
} else {
if(pw(2,0) != co(0,cr(2,0))) {
ASSUME(cr(2,0) >= old_cr);
}
pw(2,0) = co(0,cr(2,0));
r8 = mem(0,cr(2,0));
}
ASSUME(creturn[2] >= cr(2,0));
// call void @llvm.dbg.value(metadata i64 %3, metadata !85, metadata !DIExpression()), !dbg !122
// %conv17 = trunc i64 %3 to i32, !dbg !105
// call void @llvm.dbg.value(metadata i32 %conv17, metadata !82, metadata !DIExpression()), !dbg !103
// %cmp = icmp eq i32 %conv, 1, !dbg !106
// %conv18 = zext i1 %cmp to i32, !dbg !106
// call void @llvm.dbg.value(metadata i32 %conv18, metadata !86, metadata !DIExpression()), !dbg !103
// call void @llvm.dbg.value(metadata i64* @atom_1_X0_1, metadata !87, metadata !DIExpression()), !dbg !126
// %4 = zext i32 %conv18 to i64
// call void @llvm.dbg.value(metadata i64 %4, metadata !89, metadata !DIExpression()), !dbg !126
// store atomic i64 %4, i64* @atom_1_X0_1 seq_cst, align 8, !dbg !108
// ST: Guess
iw(2,3) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW
old_cw = cw(2,3);
cw(2,3) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM
// Check
ASSUME(active[iw(2,3)] == 2);
ASSUME(active[cw(2,3)] == 2);
ASSUME(sforbid(3,cw(2,3))== 0);
ASSUME(iw(2,3) >= max(creg_r0,0));
ASSUME(iw(2,3) >= 0);
ASSUME(cw(2,3) >= iw(2,3));
ASSUME(cw(2,3) >= old_cw);
ASSUME(cw(2,3) >= cr(2,3));
ASSUME(cw(2,3) >= cl[2]);
ASSUME(cw(2,3) >= cisb[2]);
ASSUME(cw(2,3) >= cdy[2]);
ASSUME(cw(2,3) >= cdl[2]);
ASSUME(cw(2,3) >= cds[2]);
ASSUME(cw(2,3) >= cctrl[2]);
ASSUME(cw(2,3) >= caddr[2]);
// Update
caddr[2] = max(caddr[2],0);
buff(2,3) = (r0==1);
mem(3,cw(2,3)) = (r0==1);
co(3,cw(2,3))+=1;
delta(3,cw(2,3)) = -1;
ASSUME(creturn[2] >= cw(2,3));
// %cmp22 = icmp eq i32 %conv7, 2, !dbg !109
// %conv23 = zext i1 %cmp22 to i32, !dbg !109
// call void @llvm.dbg.value(metadata i32 %conv23, metadata !90, metadata !DIExpression()), !dbg !103
// call void @llvm.dbg.value(metadata i64* @atom_1_X5_2, metadata !91, metadata !DIExpression()), !dbg !129
// %5 = zext i32 %conv23 to i64
// call void @llvm.dbg.value(metadata i64 %5, metadata !93, metadata !DIExpression()), !dbg !129
// store atomic i64 %5, i64* @atom_1_X5_2 seq_cst, align 8, !dbg !111
// ST: Guess
iw(2,4) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW
old_cw = cw(2,4);
cw(2,4) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM
// Check
ASSUME(active[iw(2,4)] == 2);
ASSUME(active[cw(2,4)] == 2);
ASSUME(sforbid(4,cw(2,4))== 0);
ASSUME(iw(2,4) >= max(creg_r3,0));
ASSUME(iw(2,4) >= 0);
ASSUME(cw(2,4) >= iw(2,4));
ASSUME(cw(2,4) >= old_cw);
ASSUME(cw(2,4) >= cr(2,4));
ASSUME(cw(2,4) >= cl[2]);
ASSUME(cw(2,4) >= cisb[2]);
ASSUME(cw(2,4) >= cdy[2]);
ASSUME(cw(2,4) >= cdl[2]);
ASSUME(cw(2,4) >= cds[2]);
ASSUME(cw(2,4) >= cctrl[2]);
ASSUME(cw(2,4) >= caddr[2]);
// Update
caddr[2] = max(caddr[2],0);
buff(2,4) = (r3==2);
mem(4,cw(2,4)) = (r3==2);
co(4,cw(2,4))+=1;
delta(4,cw(2,4)) = -1;
ASSUME(creturn[2] >= cw(2,4));
// %cmp27 = icmp eq i32 %conv13, 0, !dbg !112
// %conv28 = zext i1 %cmp27 to i32, !dbg !112
// call void @llvm.dbg.value(metadata i32 %conv28, metadata !94, metadata !DIExpression()), !dbg !103
// call void @llvm.dbg.value(metadata i64* @atom_1_X7_0, metadata !95, metadata !DIExpression()), !dbg !132
// %6 = zext i32 %conv28 to i64
// call void @llvm.dbg.value(metadata i64 %6, metadata !97, metadata !DIExpression()), !dbg !132
// store atomic i64 %6, i64* @atom_1_X7_0 seq_cst, align 8, !dbg !114
// ST: Guess
iw(2,5) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW
old_cw = cw(2,5);
cw(2,5) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM
// Check
ASSUME(active[iw(2,5)] == 2);
ASSUME(active[cw(2,5)] == 2);
ASSUME(sforbid(5,cw(2,5))== 0);
ASSUME(iw(2,5) >= max(creg_r7,0));
ASSUME(iw(2,5) >= 0);
ASSUME(cw(2,5) >= iw(2,5));
ASSUME(cw(2,5) >= old_cw);
ASSUME(cw(2,5) >= cr(2,5));
ASSUME(cw(2,5) >= cl[2]);
ASSUME(cw(2,5) >= cisb[2]);
ASSUME(cw(2,5) >= cdy[2]);
ASSUME(cw(2,5) >= cdl[2]);
ASSUME(cw(2,5) >= cds[2]);
ASSUME(cw(2,5) >= cctrl[2]);
ASSUME(cw(2,5) >= caddr[2]);
// Update
caddr[2] = max(caddr[2],0);
buff(2,5) = (r7==0);
mem(5,cw(2,5)) = (r7==0);
co(5,cw(2,5))+=1;
delta(5,cw(2,5)) = -1;
ASSUME(creturn[2] >= cw(2,5));
// %cmp32 = icmp eq i32 %conv17, 1, !dbg !115
// %conv33 = zext i1 %cmp32 to i32, !dbg !115
// call void @llvm.dbg.value(metadata i32 %conv33, metadata !98, metadata !DIExpression()), !dbg !103
// call void @llvm.dbg.value(metadata i64* @atom_1_X9_1, metadata !99, metadata !DIExpression()), !dbg !135
// %7 = zext i32 %conv33 to i64
// call void @llvm.dbg.value(metadata i64 %7, metadata !101, metadata !DIExpression()), !dbg !135
// store atomic i64 %7, i64* @atom_1_X9_1 seq_cst, align 8, !dbg !117
// ST: Guess
iw(2,6) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW
old_cw = cw(2,6);
cw(2,6) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM
// Check
ASSUME(active[iw(2,6)] == 2);
ASSUME(active[cw(2,6)] == 2);
ASSUME(sforbid(6,cw(2,6))== 0);
ASSUME(iw(2,6) >= max(creg_r8,0));
ASSUME(iw(2,6) >= 0);
ASSUME(cw(2,6) >= iw(2,6));
ASSUME(cw(2,6) >= old_cw);
ASSUME(cw(2,6) >= cr(2,6));
ASSUME(cw(2,6) >= cl[2]);
ASSUME(cw(2,6) >= cisb[2]);
ASSUME(cw(2,6) >= cdy[2]);
ASSUME(cw(2,6) >= cdl[2]);
ASSUME(cw(2,6) >= cds[2]);
ASSUME(cw(2,6) >= cctrl[2]);
ASSUME(cw(2,6) >= caddr[2]);
// Update
caddr[2] = max(caddr[2],0);
buff(2,6) = (r8==1);
mem(6,cw(2,6)) = (r8==1);
co(6,cw(2,6))+=1;
delta(6,cw(2,6)) = -1;
ASSUME(creturn[2] >= cw(2,6));
// ret i8* null, !dbg !118
ret_thread_2 = (- 1);
// Dumping thread 3
int ret_thread_3 = 0;
cdy[3] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[3] >= cstart[3]);
T3BLOCK0:
// call void @llvm.dbg.value(metadata i8* %arg, metadata !140, metadata !DIExpression()), !dbg !145
// br label %label_3, !dbg !46
goto T3BLOCK1;
T3BLOCK1:
// call void @llvm.dbg.label(metadata !144), !dbg !147
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !141, metadata !DIExpression()), !dbg !148
// call void @llvm.dbg.value(metadata i64 1, metadata !143, metadata !DIExpression()), !dbg !148
// store atomic i64 1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !49
// ST: Guess
iw(3,0) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STIW
old_cw = cw(3,0);
cw(3,0) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STCOM
// Check
ASSUME(active[iw(3,0)] == 3);
ASSUME(active[cw(3,0)] == 3);
ASSUME(sforbid(0,cw(3,0))== 0);
ASSUME(iw(3,0) >= 0);
ASSUME(iw(3,0) >= 0);
ASSUME(cw(3,0) >= iw(3,0));
ASSUME(cw(3,0) >= old_cw);
ASSUME(cw(3,0) >= cr(3,0));
ASSUME(cw(3,0) >= cl[3]);
ASSUME(cw(3,0) >= cisb[3]);
ASSUME(cw(3,0) >= cdy[3]);
ASSUME(cw(3,0) >= cdl[3]);
ASSUME(cw(3,0) >= cds[3]);
ASSUME(cw(3,0) >= cctrl[3]);
ASSUME(cw(3,0) >= caddr[3]);
// Update
caddr[3] = max(caddr[3],0);
buff(3,0) = 1;
mem(0,cw(3,0)) = 1;
co(0,cw(3,0))+=1;
delta(0,cw(3,0)) = -1;
ASSUME(creturn[3] >= cw(3,0));
// ret i8* null, !dbg !50
ret_thread_3 = (- 1);
// Dumping thread 0
int ret_thread_0 = 0;
cdy[0] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[0] >= cstart[0]);
T0BLOCK0:
// %thr0 = alloca i64, align 8
// %thr1 = alloca i64, align 8
// %thr2 = alloca i64, align 8
// call void @llvm.dbg.value(metadata i32 %argc, metadata !158, metadata !DIExpression()), !dbg !224
// call void @llvm.dbg.value(metadata i8** %argv, metadata !159, metadata !DIExpression()), !dbg !224
// %0 = bitcast i64* %thr0 to i8*, !dbg !111
// call void @llvm.lifetime.start.p0i8(i64 8, i8* %0) #7, !dbg !111
// call void @llvm.dbg.declare(metadata i64* %thr0, metadata !160, metadata !DIExpression()), !dbg !226
// %1 = bitcast i64* %thr1 to i8*, !dbg !113
// call void @llvm.lifetime.start.p0i8(i64 8, i8* %1) #7, !dbg !113
// call void @llvm.dbg.declare(metadata i64* %thr1, metadata !164, metadata !DIExpression()), !dbg !228
// %2 = bitcast i64* %thr2 to i8*, !dbg !115
// call void @llvm.lifetime.start.p0i8(i64 8, i8* %2) #7, !dbg !115
// call void @llvm.dbg.declare(metadata i64* %thr2, metadata !165, metadata !DIExpression()), !dbg !230
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !166, metadata !DIExpression()), !dbg !231
// call void @llvm.dbg.value(metadata i64 0, metadata !168, metadata !DIExpression()), !dbg !231
// store atomic i64 0, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !118
// ST: Guess
iw(0,0+2*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,0+2*1);
cw(0,0+2*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,0+2*1)] == 0);
ASSUME(active[cw(0,0+2*1)] == 0);
ASSUME(sforbid(0+2*1,cw(0,0+2*1))== 0);
ASSUME(iw(0,0+2*1) >= 0);
ASSUME(iw(0,0+2*1) >= 0);
ASSUME(cw(0,0+2*1) >= iw(0,0+2*1));
ASSUME(cw(0,0+2*1) >= old_cw);
ASSUME(cw(0,0+2*1) >= cr(0,0+2*1));
ASSUME(cw(0,0+2*1) >= cl[0]);
ASSUME(cw(0,0+2*1) >= cisb[0]);
ASSUME(cw(0,0+2*1) >= cdy[0]);
ASSUME(cw(0,0+2*1) >= cdl[0]);
ASSUME(cw(0,0+2*1) >= cds[0]);
ASSUME(cw(0,0+2*1) >= cctrl[0]);
ASSUME(cw(0,0+2*1) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,0+2*1) = 0;
mem(0+2*1,cw(0,0+2*1)) = 0;
co(0+2*1,cw(0,0+2*1))+=1;
delta(0+2*1,cw(0,0+2*1)) = -1;
ASSUME(creturn[0] >= cw(0,0+2*1));
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !169, metadata !DIExpression()), !dbg !233
// call void @llvm.dbg.value(metadata i64 0, metadata !171, metadata !DIExpression()), !dbg !233
// store atomic i64 0, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !120
// ST: Guess
iw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,0+1*1);
cw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,0+1*1)] == 0);
ASSUME(active[cw(0,0+1*1)] == 0);
ASSUME(sforbid(0+1*1,cw(0,0+1*1))== 0);
ASSUME(iw(0,0+1*1) >= 0);
ASSUME(iw(0,0+1*1) >= 0);
ASSUME(cw(0,0+1*1) >= iw(0,0+1*1));
ASSUME(cw(0,0+1*1) >= old_cw);
ASSUME(cw(0,0+1*1) >= cr(0,0+1*1));
ASSUME(cw(0,0+1*1) >= cl[0]);
ASSUME(cw(0,0+1*1) >= cisb[0]);
ASSUME(cw(0,0+1*1) >= cdy[0]);
ASSUME(cw(0,0+1*1) >= cdl[0]);
ASSUME(cw(0,0+1*1) >= cds[0]);
ASSUME(cw(0,0+1*1) >= cctrl[0]);
ASSUME(cw(0,0+1*1) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,0+1*1) = 0;
mem(0+1*1,cw(0,0+1*1)) = 0;
co(0+1*1,cw(0,0+1*1))+=1;
delta(0+1*1,cw(0,0+1*1)) = -1;
ASSUME(creturn[0] >= cw(0,0+1*1));
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !172, metadata !DIExpression()), !dbg !235
// call void @llvm.dbg.value(metadata i64 0, metadata !174, metadata !DIExpression()), !dbg !235
// store atomic i64 0, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !122
// ST: Guess
iw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,0);
cw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,0)] == 0);
ASSUME(active[cw(0,0)] == 0);
ASSUME(sforbid(0,cw(0,0))== 0);
ASSUME(iw(0,0) >= 0);
ASSUME(iw(0,0) >= 0);
ASSUME(cw(0,0) >= iw(0,0));
ASSUME(cw(0,0) >= old_cw);
ASSUME(cw(0,0) >= cr(0,0));
ASSUME(cw(0,0) >= cl[0]);
ASSUME(cw(0,0) >= cisb[0]);
ASSUME(cw(0,0) >= cdy[0]);
ASSUME(cw(0,0) >= cdl[0]);
ASSUME(cw(0,0) >= cds[0]);
ASSUME(cw(0,0) >= cctrl[0]);
ASSUME(cw(0,0) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,0) = 0;
mem(0,cw(0,0)) = 0;
co(0,cw(0,0))+=1;
delta(0,cw(0,0)) = -1;
ASSUME(creturn[0] >= cw(0,0));
// call void @llvm.dbg.value(metadata i64* @atom_1_X0_1, metadata !175, metadata !DIExpression()), !dbg !237
// call void @llvm.dbg.value(metadata i64 0, metadata !177, metadata !DIExpression()), !dbg !237
// store atomic i64 0, i64* @atom_1_X0_1 monotonic, align 8, !dbg !124
// ST: Guess
iw(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,3);
cw(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,3)] == 0);
ASSUME(active[cw(0,3)] == 0);
ASSUME(sforbid(3,cw(0,3))== 0);
ASSUME(iw(0,3) >= 0);
ASSUME(iw(0,3) >= 0);
ASSUME(cw(0,3) >= iw(0,3));
ASSUME(cw(0,3) >= old_cw);
ASSUME(cw(0,3) >= cr(0,3));
ASSUME(cw(0,3) >= cl[0]);
ASSUME(cw(0,3) >= cisb[0]);
ASSUME(cw(0,3) >= cdy[0]);
ASSUME(cw(0,3) >= cdl[0]);
ASSUME(cw(0,3) >= cds[0]);
ASSUME(cw(0,3) >= cctrl[0]);
ASSUME(cw(0,3) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,3) = 0;
mem(3,cw(0,3)) = 0;
co(3,cw(0,3))+=1;
delta(3,cw(0,3)) = -1;
ASSUME(creturn[0] >= cw(0,3));
// call void @llvm.dbg.value(metadata i64* @atom_1_X5_2, metadata !178, metadata !DIExpression()), !dbg !239
// call void @llvm.dbg.value(metadata i64 0, metadata !180, metadata !DIExpression()), !dbg !239
// store atomic i64 0, i64* @atom_1_X5_2 monotonic, align 8, !dbg !126
// ST: Guess
iw(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,4);
cw(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,4)] == 0);
ASSUME(active[cw(0,4)] == 0);
ASSUME(sforbid(4,cw(0,4))== 0);
ASSUME(iw(0,4) >= 0);
ASSUME(iw(0,4) >= 0);
ASSUME(cw(0,4) >= iw(0,4));
ASSUME(cw(0,4) >= old_cw);
ASSUME(cw(0,4) >= cr(0,4));
ASSUME(cw(0,4) >= cl[0]);
ASSUME(cw(0,4) >= cisb[0]);
ASSUME(cw(0,4) >= cdy[0]);
ASSUME(cw(0,4) >= cdl[0]);
ASSUME(cw(0,4) >= cds[0]);
ASSUME(cw(0,4) >= cctrl[0]);
ASSUME(cw(0,4) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,4) = 0;
mem(4,cw(0,4)) = 0;
co(4,cw(0,4))+=1;
delta(4,cw(0,4)) = -1;
ASSUME(creturn[0] >= cw(0,4));
// call void @llvm.dbg.value(metadata i64* @atom_1_X7_0, metadata !181, metadata !DIExpression()), !dbg !241
// call void @llvm.dbg.value(metadata i64 0, metadata !183, metadata !DIExpression()), !dbg !241
// store atomic i64 0, i64* @atom_1_X7_0 monotonic, align 8, !dbg !128
// ST: Guess
iw(0,5) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,5);
cw(0,5) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,5)] == 0);
ASSUME(active[cw(0,5)] == 0);
ASSUME(sforbid(5,cw(0,5))== 0);
ASSUME(iw(0,5) >= 0);
ASSUME(iw(0,5) >= 0);
ASSUME(cw(0,5) >= iw(0,5));
ASSUME(cw(0,5) >= old_cw);
ASSUME(cw(0,5) >= cr(0,5));
ASSUME(cw(0,5) >= cl[0]);
ASSUME(cw(0,5) >= cisb[0]);
ASSUME(cw(0,5) >= cdy[0]);
ASSUME(cw(0,5) >= cdl[0]);
ASSUME(cw(0,5) >= cds[0]);
ASSUME(cw(0,5) >= cctrl[0]);
ASSUME(cw(0,5) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,5) = 0;
mem(5,cw(0,5)) = 0;
co(5,cw(0,5))+=1;
delta(5,cw(0,5)) = -1;
ASSUME(creturn[0] >= cw(0,5));
// call void @llvm.dbg.value(metadata i64* @atom_1_X9_1, metadata !184, metadata !DIExpression()), !dbg !243
// call void @llvm.dbg.value(metadata i64 0, metadata !186, metadata !DIExpression()), !dbg !243
// store atomic i64 0, i64* @atom_1_X9_1 monotonic, align 8, !dbg !130
// ST: Guess
iw(0,6) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,6);
cw(0,6) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,6)] == 0);
ASSUME(active[cw(0,6)] == 0);
ASSUME(sforbid(6,cw(0,6))== 0);
ASSUME(iw(0,6) >= 0);
ASSUME(iw(0,6) >= 0);
ASSUME(cw(0,6) >= iw(0,6));
ASSUME(cw(0,6) >= old_cw);
ASSUME(cw(0,6) >= cr(0,6));
ASSUME(cw(0,6) >= cl[0]);
ASSUME(cw(0,6) >= cisb[0]);
ASSUME(cw(0,6) >= cdy[0]);
ASSUME(cw(0,6) >= cdl[0]);
ASSUME(cw(0,6) >= cds[0]);
ASSUME(cw(0,6) >= cctrl[0]);
ASSUME(cw(0,6) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,6) = 0;
mem(6,cw(0,6)) = 0;
co(6,cw(0,6))+=1;
delta(6,cw(0,6)) = -1;
ASSUME(creturn[0] >= cw(0,6));
// %call = call i32 @pthread_create(i64* noundef %thr0, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t0, i8* noundef null) #7, !dbg !131
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,0+2));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,8+0));
ASSUME(cdy[0] >= cw(0,9+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cw(0,6+0));
ASSUME(cdy[0] >= cw(0,7+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,0+2));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,8+0));
ASSUME(cdy[0] >= cr(0,9+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(cdy[0] >= cr(0,6+0));
ASSUME(cdy[0] >= cr(0,7+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cstart[1] >= cdy[0]);
// %call13 = call i32 @pthread_create(i64* noundef %thr1, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t1, i8* noundef null) #7, !dbg !132
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,0+2));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,8+0));
ASSUME(cdy[0] >= cw(0,9+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cw(0,6+0));
ASSUME(cdy[0] >= cw(0,7+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,0+2));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,8+0));
ASSUME(cdy[0] >= cr(0,9+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(cdy[0] >= cr(0,6+0));
ASSUME(cdy[0] >= cr(0,7+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cstart[2] >= cdy[0]);
// %call14 = call i32 @pthread_create(i64* noundef %thr2, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t2, i8* noundef null) #7, !dbg !133
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,0+2));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,8+0));
ASSUME(cdy[0] >= cw(0,9+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cw(0,6+0));
ASSUME(cdy[0] >= cw(0,7+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,0+2));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,8+0));
ASSUME(cdy[0] >= cr(0,9+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(cdy[0] >= cr(0,6+0));
ASSUME(cdy[0] >= cr(0,7+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cstart[3] >= cdy[0]);
// %3 = load i64, i64* %thr0, align 8, !dbg !134, !tbaa !135
// LD: Guess
old_cr = cr(0,7);
cr(0,7) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,7)] == 0);
ASSUME(cr(0,7) >= iw(0,7));
ASSUME(cr(0,7) >= 0);
ASSUME(cr(0,7) >= cdy[0]);
ASSUME(cr(0,7) >= cisb[0]);
ASSUME(cr(0,7) >= cdl[0]);
ASSUME(cr(0,7) >= cl[0]);
// Update
creg_r10 = cr(0,7);
crmax(0,7) = max(crmax(0,7),cr(0,7));
caddr[0] = max(caddr[0],0);
if(cr(0,7) < cw(0,7)) {
r10 = buff(0,7);
} else {
if(pw(0,7) != co(7,cr(0,7))) {
ASSUME(cr(0,7) >= old_cr);
}
pw(0,7) = co(7,cr(0,7));
r10 = mem(7,cr(0,7));
}
ASSUME(creturn[0] >= cr(0,7));
// %call15 = call i32 @pthread_join(i64 noundef %3, i8** noundef null), !dbg !139
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,0+2));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,8+0));
ASSUME(cdy[0] >= cw(0,9+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cw(0,6+0));
ASSUME(cdy[0] >= cw(0,7+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,0+2));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,8+0));
ASSUME(cdy[0] >= cr(0,9+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(cdy[0] >= cr(0,6+0));
ASSUME(cdy[0] >= cr(0,7+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cdy[0] >= creturn[1]);
// %4 = load i64, i64* %thr1, align 8, !dbg !140, !tbaa !135
// LD: Guess
old_cr = cr(0,8);
cr(0,8) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,8)] == 0);
ASSUME(cr(0,8) >= iw(0,8));
ASSUME(cr(0,8) >= 0);
ASSUME(cr(0,8) >= cdy[0]);
ASSUME(cr(0,8) >= cisb[0]);
ASSUME(cr(0,8) >= cdl[0]);
ASSUME(cr(0,8) >= cl[0]);
// Update
creg_r11 = cr(0,8);
crmax(0,8) = max(crmax(0,8),cr(0,8));
caddr[0] = max(caddr[0],0);
if(cr(0,8) < cw(0,8)) {
r11 = buff(0,8);
} else {
if(pw(0,8) != co(8,cr(0,8))) {
ASSUME(cr(0,8) >= old_cr);
}
pw(0,8) = co(8,cr(0,8));
r11 = mem(8,cr(0,8));
}
ASSUME(creturn[0] >= cr(0,8));
// %call16 = call i32 @pthread_join(i64 noundef %4, i8** noundef null), !dbg !141
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,0+2));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,8+0));
ASSUME(cdy[0] >= cw(0,9+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cw(0,6+0));
ASSUME(cdy[0] >= cw(0,7+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,0+2));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,8+0));
ASSUME(cdy[0] >= cr(0,9+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(cdy[0] >= cr(0,6+0));
ASSUME(cdy[0] >= cr(0,7+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cdy[0] >= creturn[2]);
// %5 = load i64, i64* %thr2, align 8, !dbg !142, !tbaa !135
// LD: Guess
old_cr = cr(0,9);
cr(0,9) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,9)] == 0);
ASSUME(cr(0,9) >= iw(0,9));
ASSUME(cr(0,9) >= 0);
ASSUME(cr(0,9) >= cdy[0]);
ASSUME(cr(0,9) >= cisb[0]);
ASSUME(cr(0,9) >= cdl[0]);
ASSUME(cr(0,9) >= cl[0]);
// Update
creg_r12 = cr(0,9);
crmax(0,9) = max(crmax(0,9),cr(0,9));
caddr[0] = max(caddr[0],0);
if(cr(0,9) < cw(0,9)) {
r12 = buff(0,9);
} else {
if(pw(0,9) != co(9,cr(0,9))) {
ASSUME(cr(0,9) >= old_cr);
}
pw(0,9) = co(9,cr(0,9));
r12 = mem(9,cr(0,9));
}
ASSUME(creturn[0] >= cr(0,9));
// %call17 = call i32 @pthread_join(i64 noundef %5, i8** noundef null), !dbg !143
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,0+2));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,8+0));
ASSUME(cdy[0] >= cw(0,9+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cw(0,6+0));
ASSUME(cdy[0] >= cw(0,7+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,0+2));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,8+0));
ASSUME(cdy[0] >= cr(0,9+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(cdy[0] >= cr(0,6+0));
ASSUME(cdy[0] >= cr(0,7+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cdy[0] >= creturn[3]);
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !188, metadata !DIExpression()), !dbg !258
// %6 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) seq_cst, align 8, !dbg !145
// LD: Guess
old_cr = cr(0,0);
cr(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,0)] == 0);
ASSUME(cr(0,0) >= iw(0,0));
ASSUME(cr(0,0) >= 0);
ASSUME(cr(0,0) >= cdy[0]);
ASSUME(cr(0,0) >= cisb[0]);
ASSUME(cr(0,0) >= cdl[0]);
ASSUME(cr(0,0) >= cl[0]);
// Update
creg_r13 = cr(0,0);
crmax(0,0) = max(crmax(0,0),cr(0,0));
caddr[0] = max(caddr[0],0);
if(cr(0,0) < cw(0,0)) {
r13 = buff(0,0);
} else {
if(pw(0,0) != co(0,cr(0,0))) {
ASSUME(cr(0,0) >= old_cr);
}
pw(0,0) = co(0,cr(0,0));
r13 = mem(0,cr(0,0));
}
ASSUME(creturn[0] >= cr(0,0));
// call void @llvm.dbg.value(metadata i64 %6, metadata !190, metadata !DIExpression()), !dbg !258
// %conv = trunc i64 %6 to i32, !dbg !146
// call void @llvm.dbg.value(metadata i32 %conv, metadata !187, metadata !DIExpression()), !dbg !224
// %cmp = icmp eq i32 %conv, 2, !dbg !147
// %conv18 = zext i1 %cmp to i32, !dbg !147
// call void @llvm.dbg.value(metadata i32 %conv18, metadata !191, metadata !DIExpression()), !dbg !224
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !193, metadata !DIExpression()), !dbg !262
// %7 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) seq_cst, align 8, !dbg !149
// LD: Guess
old_cr = cr(0,0+1*1);
cr(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,0+1*1)] == 0);
ASSUME(cr(0,0+1*1) >= iw(0,0+1*1));
ASSUME(cr(0,0+1*1) >= 0);
ASSUME(cr(0,0+1*1) >= cdy[0]);
ASSUME(cr(0,0+1*1) >= cisb[0]);
ASSUME(cr(0,0+1*1) >= cdl[0]);
ASSUME(cr(0,0+1*1) >= cl[0]);
// Update
creg_r14 = cr(0,0+1*1);
crmax(0,0+1*1) = max(crmax(0,0+1*1),cr(0,0+1*1));
caddr[0] = max(caddr[0],0);
if(cr(0,0+1*1) < cw(0,0+1*1)) {
r14 = buff(0,0+1*1);
} else {
if(pw(0,0+1*1) != co(0+1*1,cr(0,0+1*1))) {
ASSUME(cr(0,0+1*1) >= old_cr);
}
pw(0,0+1*1) = co(0+1*1,cr(0,0+1*1));
r14 = mem(0+1*1,cr(0,0+1*1));
}
ASSUME(creturn[0] >= cr(0,0+1*1));
// call void @llvm.dbg.value(metadata i64 %7, metadata !195, metadata !DIExpression()), !dbg !262
// %conv22 = trunc i64 %7 to i32, !dbg !150
// call void @llvm.dbg.value(metadata i32 %conv22, metadata !192, metadata !DIExpression()), !dbg !224
// %cmp23 = icmp eq i32 %conv22, 1, !dbg !151
// %conv24 = zext i1 %cmp23 to i32, !dbg !151
// call void @llvm.dbg.value(metadata i32 %conv24, metadata !196, metadata !DIExpression()), !dbg !224
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !198, metadata !DIExpression()), !dbg !266
// %8 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) seq_cst, align 8, !dbg !153
// LD: Guess
old_cr = cr(0,0+2*1);
cr(0,0+2*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,0+2*1)] == 0);
ASSUME(cr(0,0+2*1) >= iw(0,0+2*1));
ASSUME(cr(0,0+2*1) >= 0);
ASSUME(cr(0,0+2*1) >= cdy[0]);
ASSUME(cr(0,0+2*1) >= cisb[0]);
ASSUME(cr(0,0+2*1) >= cdl[0]);
ASSUME(cr(0,0+2*1) >= cl[0]);
// Update
creg_r15 = cr(0,0+2*1);
crmax(0,0+2*1) = max(crmax(0,0+2*1),cr(0,0+2*1));
caddr[0] = max(caddr[0],0);
if(cr(0,0+2*1) < cw(0,0+2*1)) {
r15 = buff(0,0+2*1);
} else {
if(pw(0,0+2*1) != co(0+2*1,cr(0,0+2*1))) {
ASSUME(cr(0,0+2*1) >= old_cr);
}
pw(0,0+2*1) = co(0+2*1,cr(0,0+2*1));
r15 = mem(0+2*1,cr(0,0+2*1));
}
ASSUME(creturn[0] >= cr(0,0+2*1));
// call void @llvm.dbg.value(metadata i64 %8, metadata !200, metadata !DIExpression()), !dbg !266
// %conv28 = trunc i64 %8 to i32, !dbg !154
// call void @llvm.dbg.value(metadata i32 %conv28, metadata !197, metadata !DIExpression()), !dbg !224
// %cmp29 = icmp eq i32 %conv28, 2, !dbg !155
// %conv30 = zext i1 %cmp29 to i32, !dbg !155
// call void @llvm.dbg.value(metadata i32 %conv30, metadata !201, metadata !DIExpression()), !dbg !224
// call void @llvm.dbg.value(metadata i64* @atom_1_X0_1, metadata !203, metadata !DIExpression()), !dbg !270
// %9 = load atomic i64, i64* @atom_1_X0_1 seq_cst, align 8, !dbg !157
// LD: Guess
old_cr = cr(0,3);
cr(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,3)] == 0);
ASSUME(cr(0,3) >= iw(0,3));
ASSUME(cr(0,3) >= 0);
ASSUME(cr(0,3) >= cdy[0]);
ASSUME(cr(0,3) >= cisb[0]);
ASSUME(cr(0,3) >= cdl[0]);
ASSUME(cr(0,3) >= cl[0]);
// Update
creg_r16 = cr(0,3);
crmax(0,3) = max(crmax(0,3),cr(0,3));
caddr[0] = max(caddr[0],0);
if(cr(0,3) < cw(0,3)) {
r16 = buff(0,3);
} else {
if(pw(0,3) != co(3,cr(0,3))) {
ASSUME(cr(0,3) >= old_cr);
}
pw(0,3) = co(3,cr(0,3));
r16 = mem(3,cr(0,3));
}
ASSUME(creturn[0] >= cr(0,3));
// call void @llvm.dbg.value(metadata i64 %9, metadata !205, metadata !DIExpression()), !dbg !270
// %conv34 = trunc i64 %9 to i32, !dbg !158
// call void @llvm.dbg.value(metadata i32 %conv34, metadata !202, metadata !DIExpression()), !dbg !224
// call void @llvm.dbg.value(metadata i64* @atom_1_X5_2, metadata !207, metadata !DIExpression()), !dbg !273
// %10 = load atomic i64, i64* @atom_1_X5_2 seq_cst, align 8, !dbg !160
// LD: Guess
old_cr = cr(0,4);
cr(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,4)] == 0);
ASSUME(cr(0,4) >= iw(0,4));
ASSUME(cr(0,4) >= 0);
ASSUME(cr(0,4) >= cdy[0]);
ASSUME(cr(0,4) >= cisb[0]);
ASSUME(cr(0,4) >= cdl[0]);
ASSUME(cr(0,4) >= cl[0]);
// Update
creg_r17 = cr(0,4);
crmax(0,4) = max(crmax(0,4),cr(0,4));
caddr[0] = max(caddr[0],0);
if(cr(0,4) < cw(0,4)) {
r17 = buff(0,4);
} else {
if(pw(0,4) != co(4,cr(0,4))) {
ASSUME(cr(0,4) >= old_cr);
}
pw(0,4) = co(4,cr(0,4));
r17 = mem(4,cr(0,4));
}
ASSUME(creturn[0] >= cr(0,4));
// call void @llvm.dbg.value(metadata i64 %10, metadata !209, metadata !DIExpression()), !dbg !273
// %conv38 = trunc i64 %10 to i32, !dbg !161
// call void @llvm.dbg.value(metadata i32 %conv38, metadata !206, metadata !DIExpression()), !dbg !224
// call void @llvm.dbg.value(metadata i64* @atom_1_X7_0, metadata !211, metadata !DIExpression()), !dbg !276
// %11 = load atomic i64, i64* @atom_1_X7_0 seq_cst, align 8, !dbg !163
// LD: Guess
old_cr = cr(0,5);
cr(0,5) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,5)] == 0);
ASSUME(cr(0,5) >= iw(0,5));
ASSUME(cr(0,5) >= 0);
ASSUME(cr(0,5) >= cdy[0]);
ASSUME(cr(0,5) >= cisb[0]);
ASSUME(cr(0,5) >= cdl[0]);
ASSUME(cr(0,5) >= cl[0]);
// Update
creg_r18 = cr(0,5);
crmax(0,5) = max(crmax(0,5),cr(0,5));
caddr[0] = max(caddr[0],0);
if(cr(0,5) < cw(0,5)) {
r18 = buff(0,5);
} else {
if(pw(0,5) != co(5,cr(0,5))) {
ASSUME(cr(0,5) >= old_cr);
}
pw(0,5) = co(5,cr(0,5));
r18 = mem(5,cr(0,5));
}
ASSUME(creturn[0] >= cr(0,5));
// call void @llvm.dbg.value(metadata i64 %11, metadata !213, metadata !DIExpression()), !dbg !276
// %conv42 = trunc i64 %11 to i32, !dbg !164
// call void @llvm.dbg.value(metadata i32 %conv42, metadata !210, metadata !DIExpression()), !dbg !224
// call void @llvm.dbg.value(metadata i64* @atom_1_X9_1, metadata !215, metadata !DIExpression()), !dbg !279
// %12 = load atomic i64, i64* @atom_1_X9_1 seq_cst, align 8, !dbg !166
// LD: Guess
old_cr = cr(0,6);
cr(0,6) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,6)] == 0);
ASSUME(cr(0,6) >= iw(0,6));
ASSUME(cr(0,6) >= 0);
ASSUME(cr(0,6) >= cdy[0]);
ASSUME(cr(0,6) >= cisb[0]);
ASSUME(cr(0,6) >= cdl[0]);
ASSUME(cr(0,6) >= cl[0]);
// Update
creg_r19 = cr(0,6);
crmax(0,6) = max(crmax(0,6),cr(0,6));
caddr[0] = max(caddr[0],0);
if(cr(0,6) < cw(0,6)) {
r19 = buff(0,6);
} else {
if(pw(0,6) != co(6,cr(0,6))) {
ASSUME(cr(0,6) >= old_cr);
}
pw(0,6) = co(6,cr(0,6));
r19 = mem(6,cr(0,6));
}
ASSUME(creturn[0] >= cr(0,6));
// call void @llvm.dbg.value(metadata i64 %12, metadata !217, metadata !DIExpression()), !dbg !279
// %conv46 = trunc i64 %12 to i32, !dbg !167
// call void @llvm.dbg.value(metadata i32 %conv46, metadata !214, metadata !DIExpression()), !dbg !224
// %and = and i32 %conv42, %conv46, !dbg !168
creg_r20 = max(creg_r18,creg_r19);
ASSUME(active[creg_r20] == 0);
r20 = r18 & r19;
// call void @llvm.dbg.value(metadata i32 %and, metadata !218, metadata !DIExpression()), !dbg !224
// %and47 = and i32 %conv38, %and, !dbg !169
creg_r21 = max(creg_r17,creg_r20);
ASSUME(active[creg_r21] == 0);
r21 = r17 & r20;
// call void @llvm.dbg.value(metadata i32 %and47, metadata !219, metadata !DIExpression()), !dbg !224
// %and48 = and i32 %conv34, %and47, !dbg !170
creg_r22 = max(creg_r16,creg_r21);
ASSUME(active[creg_r22] == 0);
r22 = r16 & r21;
// call void @llvm.dbg.value(metadata i32 %and48, metadata !220, metadata !DIExpression()), !dbg !224
// %and49 = and i32 %conv30, %and48, !dbg !171
creg_r23 = max(max(creg_r15,0),creg_r22);
ASSUME(active[creg_r23] == 0);
r23 = (r15==2) & r22;
// call void @llvm.dbg.value(metadata i32 %and49, metadata !221, metadata !DIExpression()), !dbg !224
// %and50 = and i32 %conv24, %and49, !dbg !172
creg_r24 = max(max(creg_r14,0),creg_r23);
ASSUME(active[creg_r24] == 0);
r24 = (r14==1) & r23;
// call void @llvm.dbg.value(metadata i32 %and50, metadata !222, metadata !DIExpression()), !dbg !224
// %and51 = and i32 %conv18, %and50, !dbg !173
creg_r25 = max(max(creg_r13,0),creg_r24);
ASSUME(active[creg_r25] == 0);
r25 = (r13==2) & r24;
// call void @llvm.dbg.value(metadata i32 %and51, metadata !223, metadata !DIExpression()), !dbg !224
// %cmp52 = icmp eq i32 %and51, 1, !dbg !174
// br i1 %cmp52, label %if.then, label %if.end, !dbg !176
old_cctrl = cctrl[0];
cctrl[0] = get_rng(0,NCONTEXT-1);
ASSUME(cctrl[0] >= old_cctrl);
ASSUME(cctrl[0] >= creg_r25);
ASSUME(cctrl[0] >= 0);
if((r25==1)) {
goto T0BLOCK1;
} else {
goto T0BLOCK2;
}
T0BLOCK1:
// call void @__assert_fail(i8* noundef getelementptr inbounds ([2 x i8], [2 x i8]* @.str, i64 0, i64 0), i8* noundef getelementptr inbounds ([120 x i8], [120 x i8]* @.str.1, i64 0, i64 0), i32 noundef 93, i8* noundef getelementptr inbounds ([23 x i8], [23 x i8]* @__PRETTY_FUNCTION__.main, i64 0, i64 0)) #8, !dbg !177
// unreachable, !dbg !177
r26 = 1;
T0BLOCK2:
// %13 = bitcast i64* %thr2 to i8*, !dbg !180
// call void @llvm.lifetime.end.p0i8(i64 8, i8* %13) #7, !dbg !180
// %14 = bitcast i64* %thr1 to i8*, !dbg !180
// call void @llvm.lifetime.end.p0i8(i64 8, i8* %14) #7, !dbg !180
// %15 = bitcast i64* %thr0 to i8*, !dbg !180
// call void @llvm.lifetime.end.p0i8(i64 8, i8* %15) #7, !dbg !180
// ret i32 0, !dbg !181
ret_thread_0 = 0;
ASSERT(r26== 0);
}
| [
"tuan-phong.ngo@it.uu.se"
] | tuan-phong.ngo@it.uu.se |
56e08704d4831c92de58b97105790bc4df04ad6d | 7a2e4fb0ef75367e88112160713f94b1eee06eea | /src/NodeRpcProxy/NodeRpcProxy.h | eefd98e042d28ec5adf867488b3ace0ca1874bad | [] | no_license | rainmanp7/digitalnote45 | 0ba02600369f19c729841c736f5809893bc45034 | c64310a220f12b6d4e7f4820c8014026a4266a02 | refs/heads/master | 2020-03-17T16:02:22.867091 | 2018-05-17T01:33:53 | 2018-05-17T01:33:53 | 133,733,725 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,447 | h | // Copyright (c) 2011-2016 The Cryptonote developers
// Copyright (c) 2014-2017 XDN-project developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#pragma once
#include <atomic>
#include <condition_variable>
#include <mutex>
#include <string>
#include <thread>
#include <unordered_set>
#include "Common/ObserverManager.h"
#include "INode.h"
namespace System {
class ContextGroup;
class Dispatcher;
class Event;
}
namespace CryptoNote {
class HttpClient;
class INodeRpcProxyObserver {
public:
virtual ~INodeRpcProxyObserver() {}
virtual void connectionStatusUpdated(bool connected) {}
};
class NodeRpcProxy : public CryptoNote::INode {
public:
NodeRpcProxy(const std::string& nodeHost, unsigned short nodePort);
virtual ~NodeRpcProxy();
virtual bool addObserver(CryptoNote::INodeObserver* observer) override;
virtual bool removeObserver(CryptoNote::INodeObserver* observer) override;
virtual bool addObserver(CryptoNote::INodeRpcProxyObserver* observer);
virtual bool removeObserver(CryptoNote::INodeRpcProxyObserver* observer);
virtual void init(const Callback& callback) override;
virtual bool shutdown() override;
virtual size_t getPeerCount() const override;
virtual uint32_t getLastLocalBlockHeight() const override;
virtual uint32_t getLastKnownBlockHeight() const override;
virtual uint32_t getLocalBlockCount() const override;
virtual uint32_t getKnownBlockCount() const override;
virtual uint64_t getLastLocalBlockTimestamp() const override;
virtual void relayTransaction(const CryptoNote::Transaction& transaction, const Callback& callback) override;
virtual void getRandomOutsByAmounts(std::vector<uint64_t>&& amounts, uint64_t outsCount, std::vector<COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::outs_for_amount>& result, const Callback& callback) override;
virtual void getNewBlocks(std::vector<Crypto::Hash>&& knownBlockIds, std::vector<CryptoNote::block_complete_entry>& newBlocks, uint32_t& startHeight, const Callback& callback) override;
virtual void getTransactionOutsGlobalIndices(const Crypto::Hash& transactionHash, std::vector<uint32_t>& outsGlobalIndices, const Callback& callback) override;
virtual void queryBlocks(std::vector<Crypto::Hash>&& knownBlockIds, uint64_t timestamp, std::vector<BlockShortEntry>& newBlocks, uint32_t& startHeight, const Callback& callback) override;
virtual void getPoolSymmetricDifference(std::vector<Crypto::Hash>&& knownPoolTxIds, Crypto::Hash knownBlockId, bool& isBcActual,
std::vector<std::unique_ptr<ITransactionReader>>& newTxs, std::vector<Crypto::Hash>& deletedTxIds, const Callback& callback) override;
virtual void getMultisignatureOutputByGlobalIndex(uint64_t amount, uint32_t gindex, MultisignatureOutput& out, const Callback& callback) override;
virtual void getBlocks(const std::vector<uint32_t>& blockHeights, std::vector<std::vector<BlockDetails>>& blocks, const Callback& callback) override;
virtual void getBlocks(const std::vector<Crypto::Hash>& blockHashes, std::vector<BlockDetails>& blocks, const Callback& callback) override;
virtual void getBlocks(uint64_t timestampBegin, uint64_t timestampEnd, uint32_t blocksNumberLimit, std::vector<BlockDetails>& blocks, uint32_t& blocksNumberWithinTimestamps, const Callback& callback) override;
virtual void getTransactions(const std::vector<Crypto::Hash>& transactionHashes, std::vector<TransactionDetails>& transactions, const Callback& callback) override;
virtual void getTransactionsByPaymentId(const Crypto::Hash& paymentId, std::vector<TransactionDetails>& transactions, const Callback& callback) override;
virtual void getPoolTransactions(uint64_t timestampBegin, uint64_t timestampEnd, uint32_t transactionsNumberLimit, std::vector<TransactionDetails>& transactions, uint64_t& transactionsNumberWithinTimestamps, const Callback& callback) override;
virtual void isSynchronized(bool& syncStatus, const Callback& callback) override;
unsigned int rpcTimeout() const { return m_rpcTimeout; }
void rpcTimeout(unsigned int val) { m_rpcTimeout = val; }
private:
void resetInternalState();
void workerThread(const Callback& initialized_callback);
std::vector<Crypto::Hash> getKnownTxsVector() const;
void pullNodeStatusAndScheduleTheNext();
void updateNodeStatus();
void updateBlockchainStatus();
bool updatePoolStatus();
void updatePeerCount(size_t peerCount);
void updatePoolState(const std::vector<std::unique_ptr<ITransactionReader>>& addedTxs, const std::vector<Crypto::Hash>& deletedTxsIds);
std::error_code doRelayTransaction(const CryptoNote::Transaction& transaction);
std::error_code doGetRandomOutsByAmounts(std::vector<uint64_t>& amounts, uint64_t outsCount,
std::vector<COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::outs_for_amount>& result);
std::error_code doGetNewBlocks(std::vector<Crypto::Hash>& knownBlockIds,
std::vector<CryptoNote::block_complete_entry>& newBlocks, uint32_t& startHeight);
std::error_code doGetTransactionOutsGlobalIndices(const Crypto::Hash& transactionHash,
std::vector<uint32_t>& outsGlobalIndices);
std::error_code doQueryBlocksLite(const std::vector<Crypto::Hash>& knownBlockIds, uint64_t timestamp,
std::vector<CryptoNote::BlockShortEntry>& newBlocks, uint32_t& startHeight);
std::error_code doGetPoolSymmetricDifference(std::vector<Crypto::Hash>&& knownPoolTxIds, Crypto::Hash knownBlockId, bool& isBcActual,
std::vector<std::unique_ptr<ITransactionReader>>& newTxs, std::vector<Crypto::Hash>& deletedTxIds);
void scheduleRequest(std::function<std::error_code()>&& procedure, const Callback& callback);
template <typename Request, typename Response>
std::error_code binaryCommand(const std::string& url, const Request& req, Response& res);
template <typename Request, typename Response>
std::error_code jsonCommand(const std::string& url, const Request& req, Response& res);
template <typename Request, typename Response>
std::error_code jsonRpcCommand(const std::string& method, const Request& req, Response& res);
enum State {
STATE_NOT_INITIALIZED,
STATE_INITIALIZING,
STATE_INITIALIZED
};
private:
State m_state = STATE_NOT_INITIALIZED;
std::mutex m_mutex;
std::condition_variable m_cv_initialized;
std::thread m_workerThread;
System::Dispatcher* m_dispatcher = nullptr;
System::ContextGroup* m_context_group = nullptr;
Tools::ObserverManager<CryptoNote::INodeObserver> m_observerManager;
Tools::ObserverManager<CryptoNote::INodeRpcProxyObserver> m_rpcProxyObserverManager;
const std::string m_nodeHost;
const unsigned short m_nodePort;
unsigned int m_rpcTimeout;
HttpClient* m_httpClient = nullptr;
System::Event* m_httpEvent = nullptr;
uint64_t m_pullInterval;
// Internal state
bool m_stop = false;
std::atomic<size_t> m_peerCount;
std::atomic<uint32_t> m_nodeHeight;
std::atomic<uint32_t> m_networkHeight;
//protect it with mutex if decided to add worker threads
Crypto::Hash m_lastKnowHash;
std::atomic<uint64_t> m_lastLocalBlockTimestamp;
std::unordered_set<Crypto::Hash> m_knownTxs;
bool m_connected;
};
}
| [
"muslimsoap@gmail.com"
] | muslimsoap@gmail.com |
ae6476e08c8d8d62d6b6014b829704600cd5780e | af9e53fdbc56abed24f2ba8236103c64032c82eb | /代码/3.cpp | b636a88e8d77e69b83a532fa0bf1c3db56a59a02 | [] | no_license | syj716/CodeSet | 9f271a4fcf647c3c368f0753a38414c189c66e93 | 0695ee0a79438d9760622cf8b0acc232cd1d374a | refs/heads/master | 2022-11-09T09:51:37.481250 | 2020-06-29T04:00:11 | 2020-06-29T04:00:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,358 | cpp | #include<stdio.h>
#include<string.h>
int dates[3002][13][32];
char NameofWeek[7][20] =
{
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
};
int dayOfMonth[13][2] = {
0,0,
31,31,
28,29,
31,31,
30,30,
31,31,
30,30,
31,31,
31,31,
30,30,
31,31,
30,30,
31,31
};
char NameofMonth[13][20] =
{
"",
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
};
int isleap(int year) {
if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0))
return 1;
return 0;
}
struct date {
int year;
int month;
int day;
int cnt;
date(int y, int m, int d, int c) :year(y), month(m), day(d), cnt(c) {}
void nextday() {
int index = isleap(year);
while (year < 3001) {
dates[year][month][day] = cnt;
day++;
cnt++;
if (day > dayOfMonth[month][index]) {
day = 1;
month++;
if (month > 12) {
month = 1;
year++;
index = isleap(year);
}
}
}
}
};
int main() {
date start(1000, 1, 1, 0);
start.nextday();
int year, month, day;
char tmp[10];
scanf("%d %s %d", &day, tmp, &year);
for (int i = 1;i < 13;i++) {
if (strcmp(NameofMonth[i], tmp) == 0) {
month = i;
break;
}
}
int days = dates[2020][1][24] - dates[year][month][day];
printf("%s", NameofWeek[(12-days % 7) % 7]);
return 0;
}
| [
"1523646952@qq.com"
] | 1523646952@qq.com |
f7ebb5c51c5faee6086b93c816be4ea490f3402f | 90047daeb462598a924d76ddf4288e832e86417c | /chrome/browser/ui/page_info/page_info_ui.cc | 401b5cd12f5307c98b44dc619dbf3c8189db364e | [
"BSD-3-Clause"
] | permissive | massbrowser/android | 99b8c21fa4552a13c06bbedd0f9c88dd4a4ad080 | a9c4371682c9443d6e1d66005d4db61a24a9617c | refs/heads/master | 2022-11-04T21:15:50.656802 | 2017-06-08T12:31:39 | 2017-06-08T12:31:39 | 93,747,579 | 2 | 2 | BSD-3-Clause | 2022-10-31T10:34:25 | 2017-06-08T12:36:07 | null | UTF-8 | C++ | false | false | 17,811 | cc | // Copyright (c) 2012 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/page_info/page_info_ui.h"
#include <utility>
#include "base/command_line.h"
#include "base/macros.h"
#include "chrome/browser/content_settings/host_content_settings_map_factory.h"
#include "chrome/browser/permissions/permission_manager.h"
#include "chrome/browser/permissions/permission_result.h"
#include "chrome/browser/permissions/permission_util.h"
#include "chrome/browser/plugins/plugin_utils.h"
#include "chrome/browser/plugins/plugins_field_trial.h"
#include "chrome/common/chrome_features.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/grit/chromium_strings.h"
#include "chrome/grit/generated_resources.h"
#include "chrome/grit/theme_resources.h"
#include "components/strings/grit/components_chromium_strings.h"
#include "components/strings/grit/components_strings.h"
#include "ppapi/features/features.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/image/image.h"
#include "url/gurl.h"
#if defined(OS_ANDROID)
#include "chrome/browser/android/android_theme_resources.h"
#else
#include "chrome/app/vector_icons/vector_icons.h"
#include "ui/gfx/color_palette.h"
#include "ui/gfx/paint_vector_icon.h"
#endif
namespace {
const int kInvalidResourceID = -1;
// The resource IDs for the strings that are displayed on the permissions
// button if the permission setting is managed by policy.
const int kPermissionButtonTextIDPolicyManaged[] = {
kInvalidResourceID,
IDS_PAGE_INFO_PERMISSION_ALLOWED_BY_POLICY,
IDS_PAGE_INFO_PERMISSION_BLOCKED_BY_POLICY,
IDS_PAGE_INFO_PERMISSION_ASK_BY_POLICY,
kInvalidResourceID,
kInvalidResourceID};
static_assert(arraysize(kPermissionButtonTextIDPolicyManaged) ==
CONTENT_SETTING_NUM_SETTINGS,
"kPermissionButtonTextIDPolicyManaged array size is incorrect");
// The resource IDs for the strings that are displayed on the permissions
// button if the permission setting is managed by an extension.
const int kPermissionButtonTextIDExtensionManaged[] = {
kInvalidResourceID,
IDS_PAGE_INFO_PERMISSION_ALLOWED_BY_EXTENSION,
IDS_PAGE_INFO_PERMISSION_BLOCKED_BY_EXTENSION,
IDS_PAGE_INFO_PERMISSION_ASK_BY_EXTENSION,
kInvalidResourceID,
kInvalidResourceID};
static_assert(arraysize(kPermissionButtonTextIDExtensionManaged) ==
CONTENT_SETTING_NUM_SETTINGS,
"kPermissionButtonTextIDExtensionManaged array size is "
"incorrect");
// The resource IDs for the strings that are displayed on the permissions
// button if the permission setting is managed by the user.
const int kPermissionButtonTextIDUserManaged[] = {
kInvalidResourceID,
IDS_PAGE_INFO_BUTTON_TEXT_ALLOWED_BY_USER,
IDS_PAGE_INFO_BUTTON_TEXT_BLOCKED_BY_USER,
IDS_PAGE_INFO_BUTTON_TEXT_ASK_BY_USER,
kInvalidResourceID,
IDS_PAGE_INFO_BUTTON_TEXT_DETECT_IMPORTANT_CONTENT_BY_USER};
static_assert(arraysize(kPermissionButtonTextIDUserManaged) ==
CONTENT_SETTING_NUM_SETTINGS,
"kPermissionButtonTextIDUserManaged array size is incorrect");
// The resource IDs for the strings that are displayed on the permissions
// button if the permission setting is the global default setting.
const int kPermissionButtonTextIDDefaultSetting[] = {
kInvalidResourceID,
IDS_PAGE_INFO_BUTTON_TEXT_ALLOWED_BY_DEFAULT,
IDS_PAGE_INFO_BUTTON_TEXT_BLOCKED_BY_DEFAULT,
IDS_PAGE_INFO_BUTTON_TEXT_ASK_BY_DEFAULT,
kInvalidResourceID,
IDS_PAGE_INFO_BUTTON_TEXT_DETECT_IMPORTANT_CONTENT_BY_DEFAULT};
static_assert(arraysize(kPermissionButtonTextIDDefaultSetting) ==
CONTENT_SETTING_NUM_SETTINGS,
"kPermissionButtonTextIDDefaultSetting array size is incorrect");
struct PermissionsUIInfo {
ContentSettingsType type;
int string_id;
int blocked_icon_id;
int allowed_icon_id;
};
const PermissionsUIInfo kPermissionsUIInfo[] = {
{CONTENT_SETTINGS_TYPE_COOKIES, 0, IDR_BLOCKED_COOKIES,
IDR_ACCESSED_COOKIES},
{CONTENT_SETTINGS_TYPE_IMAGES, IDS_PAGE_INFO_TYPE_IMAGES,
IDR_BLOCKED_IMAGES, IDR_ALLOWED_IMAGES},
{CONTENT_SETTINGS_TYPE_JAVASCRIPT, IDS_PAGE_INFO_TYPE_JAVASCRIPT,
IDR_BLOCKED_JAVASCRIPT, IDR_ALLOWED_JAVASCRIPT},
{CONTENT_SETTINGS_TYPE_POPUPS, IDS_PAGE_INFO_TYPE_POPUPS,
IDR_BLOCKED_POPUPS, IDR_ALLOWED_POPUPS},
#if BUILDFLAG(ENABLE_PLUGINS)
{CONTENT_SETTINGS_TYPE_PLUGINS, IDS_PAGE_INFO_TYPE_FLASH,
IDR_BLOCKED_PLUGINS, IDR_ALLOWED_PLUGINS},
#endif
{CONTENT_SETTINGS_TYPE_GEOLOCATION, IDS_PAGE_INFO_TYPE_LOCATION,
IDR_BLOCKED_LOCATION, IDR_ALLOWED_LOCATION},
{CONTENT_SETTINGS_TYPE_NOTIFICATIONS, IDS_PAGE_INFO_TYPE_NOTIFICATIONS,
IDR_BLOCKED_NOTIFICATION, IDR_ALLOWED_NOTIFICATION},
{CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC, IDS_PAGE_INFO_TYPE_MIC,
IDR_BLOCKED_MIC, IDR_ALLOWED_MIC},
{CONTENT_SETTINGS_TYPE_MEDIASTREAM_CAMERA, IDS_PAGE_INFO_TYPE_CAMERA,
IDR_BLOCKED_CAMERA, IDR_ALLOWED_CAMERA},
{CONTENT_SETTINGS_TYPE_AUTOMATIC_DOWNLOADS,
IDS_AUTOMATIC_DOWNLOADS_TAB_LABEL, IDR_BLOCKED_DOWNLOADS,
IDR_ALLOWED_DOWNLOADS},
{CONTENT_SETTINGS_TYPE_MIDI_SYSEX, IDS_PAGE_INFO_TYPE_MIDI_SYSEX,
IDR_BLOCKED_MIDI_SYSEX, IDR_ALLOWED_MIDI_SYSEX},
{CONTENT_SETTINGS_TYPE_BACKGROUND_SYNC, IDS_PAGE_INFO_TYPE_BACKGROUND_SYNC,
IDR_BLOCKED_BACKGROUND_SYNC, IDR_ALLOWED_BACKGROUND_SYNC},
// Autoplay is Android-only at the moment, and the Page Info popup on
// Android ignores these block/allow icon pairs, so we can specify 0 there.
{CONTENT_SETTINGS_TYPE_AUTOPLAY, IDS_PAGE_INFO_TYPE_AUTOPLAY, 0, 0},
{CONTENT_SETTINGS_TYPE_SUBRESOURCE_FILTER, IDS_SUBRESOURCE_FILTER_HEADER,
IDR_ALLOWED_SUBRESOURCE_FILTER, IDR_BLOCKED_SUBRESOURCE_FILTER},
};
std::unique_ptr<PageInfoUI::SecurityDescription> CreateSecurityDescription(
int summary_id,
int details_id) {
std::unique_ptr<PageInfoUI::SecurityDescription> security_description(
new PageInfoUI::SecurityDescription());
security_description->summary = l10n_util::GetStringUTF16(summary_id);
security_description->details = l10n_util::GetStringUTF16(details_id);
return security_description;
}
// Gets the actual setting for a ContentSettingType, taking into account what
// the default setting value is and whether Html5ByDefault is enabled.
ContentSetting GetEffectiveSetting(Profile* profile,
ContentSettingsType type,
ContentSetting setting,
ContentSetting default_setting) {
ContentSetting effective_setting = setting;
if (effective_setting == CONTENT_SETTING_DEFAULT)
effective_setting = default_setting;
#if BUILDFLAG(ENABLE_PLUGINS)
HostContentSettingsMap* host_content_settings_map =
HostContentSettingsMapFactory::GetForProfile(profile);
effective_setting = PluginsFieldTrial::EffectiveContentSetting(
host_content_settings_map, type, effective_setting);
// Display the UI string for ASK instead of DETECT for HTML5 by Default.
// TODO(tommycli): Once HTML5 by Default is shipped and the feature flag
// is removed, just migrate the actual content setting to ASK.
if (PluginUtils::ShouldPreferHtmlOverPlugins(host_content_settings_map) &&
effective_setting == CONTENT_SETTING_DETECT_IMPORTANT_CONTENT) {
effective_setting = CONTENT_SETTING_ASK;
}
#endif
return effective_setting;
}
} // namespace
PageInfoUI::CookieInfo::CookieInfo() : allowed(-1), blocked(-1) {}
PageInfoUI::PermissionInfo::PermissionInfo()
: type(CONTENT_SETTINGS_TYPE_DEFAULT),
setting(CONTENT_SETTING_DEFAULT),
default_setting(CONTENT_SETTING_DEFAULT),
source(content_settings::SETTING_SOURCE_NONE),
is_incognito(false) {}
PageInfoUI::ChosenObjectInfo::ChosenObjectInfo(
const PageInfo::ChooserUIInfo& ui_info,
std::unique_ptr<base::DictionaryValue> object)
: ui_info(ui_info), object(std::move(object)) {}
PageInfoUI::ChosenObjectInfo::~ChosenObjectInfo() {}
PageInfoUI::IdentityInfo::IdentityInfo()
: identity_status(PageInfo::SITE_IDENTITY_STATUS_UNKNOWN),
connection_status(PageInfo::SITE_CONNECTION_STATUS_UNKNOWN),
show_ssl_decision_revoke_button(false) {}
PageInfoUI::IdentityInfo::~IdentityInfo() {}
std::unique_ptr<PageInfoUI::SecurityDescription>
PageInfoUI::IdentityInfo::GetSecurityDescription() const {
std::unique_ptr<PageInfoUI::SecurityDescription> security_description(
new PageInfoUI::SecurityDescription());
switch (identity_status) {
case PageInfo::SITE_IDENTITY_STATUS_INTERNAL_PAGE:
#if defined(OS_ANDROID)
// We provide identical summary and detail strings for Android, which
// deduplicates them in the UI code.
return CreateSecurityDescription(IDS_PAGE_INFO_INTERNAL_PAGE,
IDS_PAGE_INFO_INTERNAL_PAGE);
#endif
// Internal pages on desktop have their own UI implementations which
// should never call this function.
NOTREACHED();
case PageInfo::SITE_IDENTITY_STATUS_CERT:
case PageInfo::SITE_IDENTITY_STATUS_EV_CERT:
case PageInfo::SITE_IDENTITY_STATUS_CERT_REVOCATION_UNKNOWN:
case PageInfo::SITE_IDENTITY_STATUS_ADMIN_PROVIDED_CERT:
switch (connection_status) {
case PageInfo::SITE_CONNECTION_STATUS_INSECURE_ACTIVE_SUBRESOURCE:
return CreateSecurityDescription(IDS_PAGE_INFO_NOT_SECURE_SUMMARY,
IDS_PAGE_INFO_NOT_SECURE_DETAILS);
case PageInfo::SITE_CONNECTION_STATUS_INSECURE_FORM_ACTION:
return CreateSecurityDescription(IDS_PAGE_INFO_MIXED_CONTENT_SUMMARY,
IDS_PAGE_INFO_NOT_SECURE_DETAILS);
case PageInfo::SITE_CONNECTION_STATUS_INSECURE_PASSIVE_SUBRESOURCE:
return CreateSecurityDescription(IDS_PAGE_INFO_MIXED_CONTENT_SUMMARY,
IDS_PAGE_INFO_MIXED_CONTENT_DETAILS);
default:
return CreateSecurityDescription(IDS_PAGE_INFO_SECURE_SUMMARY,
IDS_PAGE_INFO_SECURE_DETAILS);
}
case PageInfo::SITE_IDENTITY_STATUS_MALWARE:
return CreateSecurityDescription(IDS_PAGE_INFO_MALWARE_SUMMARY,
IDS_PAGE_INFO_MALWARE_DETAILS);
case PageInfo::SITE_IDENTITY_STATUS_SOCIAL_ENGINEERING:
return CreateSecurityDescription(
IDS_PAGE_INFO_SOCIAL_ENGINEERING_SUMMARY,
IDS_PAGE_INFO_SOCIAL_ENGINEERING_DETAILS);
case PageInfo::SITE_IDENTITY_STATUS_UNWANTED_SOFTWARE:
return CreateSecurityDescription(IDS_PAGE_INFO_UNWANTED_SOFTWARE_SUMMARY,
IDS_PAGE_INFO_UNWANTED_SOFTWARE_DETAILS);
case PageInfo::SITE_IDENTITY_STATUS_DEPRECATED_SIGNATURE_ALGORITHM:
case PageInfo::SITE_IDENTITY_STATUS_UNKNOWN:
case PageInfo::SITE_IDENTITY_STATUS_NO_CERT:
default:
return CreateSecurityDescription(IDS_PAGE_INFO_NOT_SECURE_SUMMARY,
IDS_PAGE_INFO_NOT_SECURE_DETAILS);
}
}
PageInfoUI::~PageInfoUI() {}
// static
base::string16 PageInfoUI::PermissionTypeToUIString(ContentSettingsType type) {
for (const PermissionsUIInfo& info : kPermissionsUIInfo) {
if (info.type == type)
return l10n_util::GetStringUTF16(info.string_id);
}
NOTREACHED();
return base::string16();
}
// static
base::string16 PageInfoUI::PermissionActionToUIString(
Profile* profile,
ContentSettingsType type,
ContentSetting setting,
ContentSetting default_setting,
content_settings::SettingSource source) {
ContentSetting effective_setting =
GetEffectiveSetting(profile, type, setting, default_setting);
const int* button_text_ids = NULL;
switch (source) {
case content_settings::SETTING_SOURCE_USER:
if (setting == CONTENT_SETTING_DEFAULT) {
button_text_ids = kPermissionButtonTextIDDefaultSetting;
break;
}
// Fallthrough.
case content_settings::SETTING_SOURCE_POLICY:
case content_settings::SETTING_SOURCE_EXTENSION:
button_text_ids = kPermissionButtonTextIDUserManaged;
break;
case content_settings::SETTING_SOURCE_WHITELIST:
case content_settings::SETTING_SOURCE_NONE:
default:
NOTREACHED();
return base::string16();
}
int button_text_id = button_text_ids[effective_setting];
DCHECK_NE(button_text_id, kInvalidResourceID);
return l10n_util::GetStringUTF16(button_text_id);
}
// static
int PageInfoUI::GetPermissionIconID(ContentSettingsType type,
ContentSetting setting) {
bool use_blocked = (setting == CONTENT_SETTING_BLOCK);
for (const PermissionsUIInfo& info : kPermissionsUIInfo) {
if (info.type == type)
return use_blocked ? info.blocked_icon_id : info.allowed_icon_id;
}
NOTREACHED();
return IDR_INFO;
}
// static
base::string16 PageInfoUI::PermissionDecisionReasonToUIString(
Profile* profile,
const PageInfoUI::PermissionInfo& permission,
const GURL& url) {
ContentSetting effective_setting = GetEffectiveSetting(
profile, permission.type, permission.setting, permission.default_setting);
int message_id = kInvalidResourceID;
switch (permission.source) {
case content_settings::SettingSource::SETTING_SOURCE_POLICY:
message_id = kPermissionButtonTextIDPolicyManaged[effective_setting];
break;
case content_settings::SettingSource::SETTING_SOURCE_EXTENSION:
message_id = kPermissionButtonTextIDExtensionManaged[effective_setting];
break;
default:
break;
}
if (permission.setting == CONTENT_SETTING_BLOCK &&
PermissionUtil::IsPermission(permission.type)) {
PermissionResult permission_result =
PermissionManager::Get(profile)->GetPermissionStatus(permission.type,
url, url);
switch (permission_result.source) {
case PermissionStatusSource::MULTIPLE_DISMISSALS:
case PermissionStatusSource::SAFE_BROWSING_BLACKLIST:
message_id = IDS_PAGE_INFO_PERMISSION_AUTOMATICALLY_BLOCKED;
break;
default:
break;
}
}
if (message_id == kInvalidResourceID)
return base::string16();
return l10n_util::GetStringUTF16(message_id);
}
// static
SkColor PageInfoUI::GetPermissionDecisionTextColor() {
return SK_ColorGRAY;
}
// static
const gfx::Image& PageInfoUI::GetPermissionIcon(const PermissionInfo& info) {
ContentSetting setting = info.setting;
if (setting == CONTENT_SETTING_DEFAULT)
setting = info.default_setting;
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
return rb.GetNativeImageNamed(GetPermissionIconID(info.type, setting));
}
// static
base::string16 PageInfoUI::ChosenObjectToUIString(
const ChosenObjectInfo& object) {
base::string16 name;
object.object->GetString(object.ui_info.ui_name_key, &name);
return name;
}
// static
const gfx::Image& PageInfoUI::GetChosenObjectIcon(
const ChosenObjectInfo& object,
bool deleted) {
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
return rb.GetNativeImageNamed(deleted ? object.ui_info.blocked_icon_id
: object.ui_info.allowed_icon_id);
}
#if defined(OS_ANDROID)
// static
int PageInfoUI::GetIdentityIconID(PageInfo::SiteIdentityStatus status) {
int resource_id = IDR_PAGEINFO_INFO;
switch (status) {
case PageInfo::SITE_IDENTITY_STATUS_UNKNOWN:
case PageInfo::SITE_IDENTITY_STATUS_INTERNAL_PAGE:
break;
case PageInfo::SITE_IDENTITY_STATUS_CERT:
case PageInfo::SITE_IDENTITY_STATUS_EV_CERT:
resource_id = IDR_PAGEINFO_GOOD;
break;
case PageInfo::SITE_IDENTITY_STATUS_CERT_REVOCATION_UNKNOWN:
resource_id = IDR_PAGEINFO_WARNING_MINOR;
break;
case PageInfo::SITE_IDENTITY_STATUS_NO_CERT:
resource_id = IDR_PAGEINFO_WARNING_MAJOR;
break;
case PageInfo::SITE_IDENTITY_STATUS_ERROR:
resource_id = IDR_PAGEINFO_BAD;
break;
case PageInfo::SITE_IDENTITY_STATUS_ADMIN_PROVIDED_CERT:
resource_id = IDR_PAGEINFO_ENTERPRISE_MANAGED;
break;
case PageInfo::SITE_IDENTITY_STATUS_DEPRECATED_SIGNATURE_ALGORITHM:
resource_id = IDR_PAGEINFO_WARNING_MINOR;
break;
default:
NOTREACHED();
break;
}
return resource_id;
}
// static
int PageInfoUI::GetConnectionIconID(PageInfo::SiteConnectionStatus status) {
int resource_id = IDR_PAGEINFO_INFO;
switch (status) {
case PageInfo::SITE_CONNECTION_STATUS_UNKNOWN:
case PageInfo::SITE_CONNECTION_STATUS_INTERNAL_PAGE:
break;
case PageInfo::SITE_CONNECTION_STATUS_ENCRYPTED:
resource_id = IDR_PAGEINFO_GOOD;
break;
case PageInfo::SITE_CONNECTION_STATUS_INSECURE_PASSIVE_SUBRESOURCE:
case PageInfo::SITE_CONNECTION_STATUS_INSECURE_FORM_ACTION:
resource_id = IDR_PAGEINFO_WARNING_MINOR;
break;
case PageInfo::SITE_CONNECTION_STATUS_UNENCRYPTED:
resource_id = IDR_PAGEINFO_WARNING_MAJOR;
break;
case PageInfo::SITE_CONNECTION_STATUS_INSECURE_ACTIVE_SUBRESOURCE:
case PageInfo::SITE_CONNECTION_STATUS_ENCRYPTED_ERROR:
resource_id = IDR_PAGEINFO_BAD;
break;
}
return resource_id;
}
#else // !defined(OS_ANDROID)
// static
const gfx::ImageSkia PageInfoUI::GetCertificateIcon() {
return gfx::CreateVectorIcon(kCertificateIcon, 16, gfx::kChromeIconGrey);
}
#endif
// static
bool PageInfoUI::ShouldShowCertificateLink() {
return base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kShowCertLink);
}
| [
"xElvis89x@gmail.com"
] | xElvis89x@gmail.com |
005d1e01f5dd184750d598c1477bef73f4128fd0 | 9332aa1506f44d1f7053cc81d02f71140eb7c0f0 | /Brown belt/5 week/Budget professional mobile legacy version/budget_bad_base.cpp | 381d51b75663d78860bdb5c080a7c7b1ec64307e | [] | no_license | arkud/C-plus-plus-modern-development-basics | 39c2d8ef7d3140258ed6d272810a88a769c51f36 | ea324252ab0d0632cfbab5ec17d317773bfd51db | refs/heads/master | 2022-12-18T14:35:33.685055 | 2020-09-27T10:03:22 | 2020-09-27T10:03:22 | 298,999,163 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,813 | cpp | #include <array>
#include <cassert>
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <optional>
#include <sstream>
#include <stdexcept>
#include <string_view>
#include <utility>
using namespace std;
pair<string_view, optional<string_view>> SplitTwoStrict(string_view s, string_view delimiter = " ") {
const size_t pos = s.find(delimiter);
if (pos == s.npos) {
return {s, nullopt};
} else {
return {s.substr(0, pos), s.substr(pos + delimiter.length())};
}
}
pair<string_view, string_view> SplitTwo(string_view s, string_view delimiter = " ") {
const auto[lhs, rhs_opt] = SplitTwoStrict(s, delimiter);
return {lhs, rhs_opt.value_or("")};
}
string_view ReadToken(string_view &s, string_view delimiter = " ") {
const auto[lhs, rhs] = SplitTwo(s, delimiter);
s = rhs;
return lhs;
}
int ConvertToInt(string_view str) {
// use std::from_chars when available to git rid of string copy
size_t pos;
const int result = stoi(string(str), &pos);
if (pos != str.length()) {
std::stringstream error;
error << "string " << str << " contains " << (str.length() - pos) << " trailing chars";
throw invalid_argument(error.str());
}
return result;
}
template<typename Number>
void ValidateBounds(Number number_to_check, Number min_value, Number max_value) {
if (number_to_check < min_value || number_to_check > max_value) {
std::stringstream error;
error << number_to_check << " is out of [" << min_value << ", " << max_value << "]";
throw out_of_range(error.str());
}
}
class Date {
public:
static Date FromString(string_view str) {
const int year = ConvertToInt(ReadToken(str, "-"));
const int month = ConvertToInt(ReadToken(str, "-"));
ValidateBounds(month, 1, 12);
const int day = ConvertToInt(str);
ValidateBounds(day, 1, 31);
return {year, month, day};
}
// Weird legacy, can't wait for std::chrono::year_month_day
time_t AsTimestamp() const {
std::tm t;
t.tm_sec = 0;
t.tm_min = 0;
t.tm_hour = 0;
t.tm_mday = day_;
t.tm_mon = month_ - 1;
t.tm_year = year_ - 1900;
t.tm_isdst = 0;
return mktime(&t);
}
private:
int year_;
int month_;
int day_;
Date(int year, int month, int day)
: year_(year), month_(month), day_(day) {}
};
int ComputeDaysDiff(const Date &date_to, const Date &date_from) {
const time_t timestamp_to = date_to.AsTimestamp();
const time_t timestamp_from = date_from.AsTimestamp();
static constexpr int SECONDS_IN_DAY = 60 * 60 * 24;
return (timestamp_to - timestamp_from) / SECONDS_IN_DAY;
}
static const Date START_DATE = Date::FromString("2000-01-01");
static const Date END_DATE = Date::FromString("2100-01-01");
static const size_t DAY_COUNT = ComputeDaysDiff(END_DATE, START_DATE);
static const size_t DAY_COUNT_P2 = 1 << 16;
static const size_t VERTEX_COUNT = DAY_COUNT_P2 * 2;
size_t ComputeDayIndex(const Date &date) {
return ComputeDaysDiff(date, START_DATE);
}
struct MoneyState{
double earned_ = 0.0;
double spent_ = 0.0;
};
array<double, VERTEX_COUNT> tree_add, tree_factor, tree_spent;
array<MoneyState, VERTEX_COUNT> tree_values;
void Init() {
tree_values.fill({0,0});
tree_add.fill(0);
tree_spent.fill(0);
tree_factor.fill(1);
}
void Push(size_t v, size_t l, size_t r) {
for (size_t w = v * 2; w <= v * 2 + 1; ++w) {
if (w < VERTEX_COUNT) {
tree_factor[w] *= tree_factor[v];
(tree_add[w] *= tree_factor[v]) += tree_add[v];
tree_spent[w] += tree_add[v];
(tree_values[w].earned_ *= tree_factor[v]) += tree_add[v] * (r - l) / 2;
tree_values[w].spent_ += tree_spent[v] * (r - l) / 2;
}
}
tree_factor[v] = 1;
tree_add[v] = 0;
tree_spent[v] = 0;
}
double ComputeSum(size_t v, size_t l, size_t r, size_t ql, size_t qr) {
if (v >= VERTEX_COUNT || qr <= l || r <= ql) {
return 0;
}
Push(v, l, r);
if (ql <= l && r <= qr) {
return tree_values[v].earned_ - tree_values[v].spent_;
}
return ComputeSum(v * 2, l, (l + r) / 2, ql, qr)
+ ComputeSum(v * 2 + 1, (l + r) / 2, r, ql, qr);
}
void Add(size_t v, size_t l, size_t r, size_t ql, size_t qr, double value) {
if (v >= VERTEX_COUNT || qr <= l || r <= ql) {
return;
}
Push(v, l, r);
if (ql <= l && r <= qr) {
tree_add[v] += value;
tree_values[v].earned_ += value * (r - l);
return;
}
Add(v * 2, l, (l + r) / 2, ql, qr, value);
Add(v * 2 + 1, (l + r) / 2, r, ql, qr, value);
tree_values[v].earned_ =
(v * 2 < VERTEX_COUNT ? tree_values[v * 2].earned_ : 0)
+ (v * 2 + 1 < VERTEX_COUNT ? tree_values[v * 2 + 1].earned_ : 0);
}
void Spend(size_t v, size_t l, size_t r, size_t ql, size_t qr, double value) {
if (v >= VERTEX_COUNT || qr <= l || r <= ql) {
return;
}
Push(v, l, r);
if (ql <= l && r <= qr) {
tree_spent[v] += value;
tree_values[v].spent_ += value * (r - l);
return;
}
Spend(v * 2, l, (l + r) / 2, ql, qr, value);
Spend(v * 2 + 1, (l + r) / 2, r, ql, qr, value);
tree_values[v].spent_ =
(v * 2 < VERTEX_COUNT ? tree_values[v * 2].spent_ : 0)
+ (v * 2 + 1 < VERTEX_COUNT ? tree_values[v * 2 + 1].spent_ : 0);
}
void Multiply(size_t v, size_t l, size_t r, size_t ql, size_t qr, int tax_percentage) {
if (v >= VERTEX_COUNT || qr <= l || r <= ql) {
return;
}
Push(v, l, r);
if (ql <= l && r <= qr) {
tree_factor[v] *= 1.0 - tax_percentage / 100.0;
tree_add[v] *= 1.0 - tax_percentage / 100.0;
tree_values[v].earned_ *= 1.0 - tax_percentage / 100.0;
return;
}
Multiply(v * 2, l, (l + r) / 2, ql, qr, tax_percentage);
Multiply(v * 2 + 1, (l + r) / 2, r, ql, qr, tax_percentage);
tree_values[v].earned_ =
(v * 2 < VERTEX_COUNT ? tree_values[v * 2].earned_ : 0)
+ (v * 2 + 1 < VERTEX_COUNT ? tree_values[v * 2 + 1].earned_ : 0);
}
int main() {
cout.precision(25);
assert(DAY_COUNT <= DAY_COUNT_P2 && DAY_COUNT_P2 < DAY_COUNT * 2);
Init();
int q;
cin >> q;
for (int i = 0; i < q; ++i) {
string query_type;
cin >> query_type;
string date_from_str, date_to_str;
cin >> date_from_str >> date_to_str;
auto idx_from = ComputeDayIndex(Date::FromString(date_from_str));
auto idx_to = ComputeDayIndex(Date::FromString(date_to_str)) + 1;
//cerr << query_type << " " << date_from_str << " " << date_to_str << " ";
if (query_type == "ComputeIncome") {
cout << ComputeSum(1, 0, DAY_COUNT_P2, idx_from, idx_to) << endl;
} else if (query_type == "PayTax") {
int tax_percentage;
cin >> tax_percentage;
//cerr << tax_percentage;
Multiply(1, 0, DAY_COUNT_P2, idx_from, idx_to, tax_percentage);
} else if (query_type == "Earn") {
double value;
cin >> value;
//cerr << value;
Add(1, 0, DAY_COUNT_P2, idx_from, idx_to, value / (idx_to - idx_from));
} else if (query_type == "Spend") {
double value;
cin >> value;
//cerr << value;
Spend(1, 0, DAY_COUNT_P2, idx_from, idx_to, value / (idx_to - idx_from));
}
//cerr << endl;
}
return 0;
}
| [
"artyomiius@gmail.com"
] | artyomiius@gmail.com |
c761e1f520b94b81eff95a74b7d9b842d6d9b048 | cf36b5f820198a5807f1c6343fd3c8c61de034e7 | /include/spmCalculator/spmCalculator.hpp | f1a9c89c87678edb36f595bb3952197848c7c24b | [] | no_license | kunaljathal/Simple-SPM | df72a128be1138f7123880050e38b2c1d1044365 | fd35e7f253dcf6f465a52fee38d97c237400b4f9 | refs/heads/master | 2016-09-16T03:05:18.496028 | 2015-08-11T17:40:37 | 2015-08-11T17:40:37 | 40,556,173 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 382 | hpp | #ifndef SPMCALCULATOR_H
#define SPMCALCULATOR_H
class spmCalculator
{
public:
static int spmCalculate(double *xAccValues, double *yAccValues, double *zAccValues, unsigned int samplingRate, unsigned int windowSizeInSeconds);
private:
static double singleAxisEstimate(double *accValues, const unsigned int windowSizeSamples, const unsigned int samplesPerMinute);
};
#endif
| [
"Kunal@Kunals-MacBook-Air.local"
] | Kunal@Kunals-MacBook-Air.local |
8b657049df30665f18183ef0822ec2455a1e3abf | 3028bcee07ca7b245a9e134fd70e9c791a2d75f8 | /Lab3_Event/Lab3_Event/main.cpp | cbe218910b1ec36a72fae3f885e0bdc1ea08346a | [] | no_license | Smartkin/os-labs | 49d48592b17f580abd06de9d74002db5c3d680d6 | 5cb91048a161db38456c85f4edfc571ee317b256 | refs/heads/master | 2020-03-28T09:53:16.456288 | 2018-12-24T00:40:16 | 2018-12-24T00:40:16 | 148,067,022 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 889 | cpp | #include <Windows.h>
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
//Helper for Lab_3
//Emulates chat between 2 processes
int main(int argc, char** argv)
{
HANDLE event = 0x0;
std::string ev_name;
std::string search_str;
std::cout << "Enter event name: ";
std::cin >> ev_name; std::cin.ignore();
std::cout << "Enter string to find: ";
std::cin >> search_str; std::cin.ignore();
std::ofstream task_f("..//..//event.txt", std::ofstream::out);
task_f << search_str;
task_f.close();
std::cout << "Waiting for opened event...\n";
while (event == 0x0)
{
event = OpenEvent(SYNCHRONIZE, TRUE, ev_name.c_str());
}
WaitForSingleObject(event, INFINITE);
std::ifstream file("..//..//event.txt", std::ifstream::in);
std::stringstream res;
res << file.rdbuf();
std::cout << res.str() << std::endl;
file.close();
system("pause");
return 0;
} | [
"vladislav5019@gmail.com"
] | vladislav5019@gmail.com |
a3f34c3f5a895122ef39e8e644b5fea22ffd2043 | ba732d80d942509dcd3f305ec8b0d95834e79808 | /ref_book/01_cpp_games/ch14/05_queue.cpp | e27ec171730f0ba43ffb1e029b240164fbefaee3 | [] | no_license | minsa97/lecture_cpp | 198e0c55a72f2c4edfcfa264995a5c18c77c9eb5 | efa53e033af7014ef73156673d273f93c5a215ce | refs/heads/main | 2023-05-11T13:12:40.584750 | 2021-05-31T09:21:16 | 2021-05-31T09:21:16 | 343,638,422 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 411 | cpp | // 05_queue.cpp
#include <iostream>
#include <queue>
using namespace std;
int main(){
queue<int> que;
int count;
cout << "피보나치 수의 개수를 입력하세요: ";
cin >> count;
cout << "피보나치 수열 = ";
que.push(0);
que.push(1);
for (int i = 0; i < count; i++) {
int x = que.front();
que.pop();
cout << x << " ";
que.push(x + que.front());
}
cout << endl;
return 0;
} | [
"minsa97@naver.com"
] | minsa97@naver.com |
2ed681d453deb5985daa5da761bbb383d92db22f | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_5744014401732608_0/C++/kobebryant24/B.cpp | 96212efd64a7d6e281e355dd7236513a17df4e0e | [] | no_license | alexandraback/datacollection | 0bc67a9ace00abbc843f4912562f3a064992e0e9 | 076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf | refs/heads/master | 2021-01-24T18:27:24.417992 | 2017-05-23T09:23:38 | 2017-05-23T09:23:38 | 84,313,442 | 2 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 1,419 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef vector<int> vi;
typedef pair<int,int> pi;
typedef vector<string> vs;
typedef vector<pi> vpi;
#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define forall(i,a,b) for(int i=a;i<b;++i)
#define max(a,b) ( (a) > (b) ? (a) : (b))
#define min(a,b) ( (a) < (b) ? (a) : (b))
#define mes(a,b) memset(a,b,sizeof a)
#define endl "\n"
#define ll long long
const int oo = 1000000009;
const double eps = 1e-9;
const int mod = 1000000007;
int main(){
int t;cin >> t;
forall(test,0,t){
int b,m;cin >> b >> m;
cout << "Case #" << test+1 << ": ";
if(b==2 && m>1) cout << "IMPOSSIBLE" << endl;
else if(b==2){
cout << "POSSIBLE" << endl;
cout << "01" << endl;
cout << "00" << endl;
}
else{
int ct=0,mat[20][20],y[20];
forall(i,0,20) forall(j,0,20) mat[i][j]=0;
forall(i,0,20) y[i]=0;
y[1]=1;++ct;mat[1][b]=1;
for(int i=2;i<b&&ct<m;++i){
mat[1][i]=1;mat[i][b]=1;
++ct;
y[i]++;
for(int j=i-1;j>1&&ct<m;--j){
if(ct+y[j]<=m) {
mat[i][j]=1;
ct+=y[j];
y[i]+=y[j];
}
}
}
if(m!=ct) cout << "IMPOSSIBLE" << endl;
else{
cout << "POSSIBLE" << endl;
forall(i,1,b+1){
forall(j,1,b+1){
cout << mat[i][j];
}
cout << endl;
}
}
}
}
} | [
"alexandra1.back@gmail.com"
] | alexandra1.back@gmail.com |
9f953dc461d6c19379e00b4d9a19d6be83c45cb7 | 85d8b496ba390a8890c023f20ffa41e32cadc1b3 | /nekBone/setup.cpp | 2f565b2106a65c684ef71edced193d5ddcae3d2c | [
"BSD-3-Clause"
] | permissive | luspi/nekBench | 8570a25ec546381247b28f3edc440359f196913c | 7363779d6696aca1e786fe5671d6d7c350b5a180 | refs/heads/master | 2023-01-02T13:46:46.340135 | 2020-06-16T09:09:12 | 2020-06-16T09:09:12 | 273,134,966 | 0 | 0 | NOASSERTION | 2020-08-02T02:15:51 | 2020-06-18T03:42:45 | null | UTF-8 | C++ | false | false | 13,626 | cpp | /*
The MIT License (MIT)
Copyright (c) 2017 Tim Warburton, Noel Chalmers, Jesse Chan, Ali Karakus
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 <unistd.h>
#include "BP.hpp"
#include "../axhelm/kernelHelper.cpp"
void reportMemoryUsage(occa::device &device, const char *mess);
BP_t *setup(mesh_t *mesh, dfloat lambda1, occa::properties &kernelInfo, setupAide &options){
BP_t *BP = new BP_t();
BP->BPid = 5;
BP->Nfields = 1;
//options.getArgs("NUMBER OF FIELDS", BP->Nfields);
if(BP->Nfields > 1) BP->BPid = 6;
options.getArgs("MESH DIMENSION", BP->dim);
options.getArgs("ELEMENT TYPE", BP->elementType);
BP->mesh = mesh;
BP->options = options;
solveSetup(BP, lambda1, kernelInfo);
const dlong Ndof = mesh->Np*(mesh->Nelements+mesh->totalHaloPairs);
BP->fieldOffset = Ndof;
const dlong Nall = BP->Nfields*Ndof;
BP->r = (dfloat*) calloc(Nall, sizeof(dfloat));
BP->x = (dfloat*) calloc(Nall, sizeof(dfloat));
BP->q = (dfloat*) calloc(Nall, sizeof(dfloat));
// setup RHS
for(dlong e=0;e<mesh->Nelements;++e){
for(int n=0;n<mesh->Np;++n){
dfloat JW = mesh->ggeo[mesh->Np*(e*mesh->Nggeo + GWJID) + n];
dlong id = n+e*mesh->Np;
dfloat xn = mesh->x[id];
dfloat yn = mesh->y[id];
dfloat zn = mesh->z[id];
dfloat mode = 1;
for(int fld=0;fld<BP->Nfields;++fld){
dlong fldid = id + fld*Ndof;
// mass projection rhs
BP->r[fldid] =
(3.*M_PI*M_PI*mode*mode+lambda1)*JW*cos(mode*M_PI*xn)*cos(mode*M_PI*yn)*cos(mode*M_PI*zn);
BP->x[fldid] = 0;
}
}
}
BP->o_r = mesh->device.malloc(Nall*sizeof(dfloat), BP->r);
BP->o_x = mesh->device.malloc(Nall*sizeof(dfloat), BP->x);
BP->lambda = (dfloat*) calloc(2*Nall, sizeof(dfloat));
for(int i=0; i<BP->fieldOffset; i++) {
BP->lambda[i] = 1.0;
BP->lambda[i+BP->fieldOffset] = lambda1;
}
BP->o_lambda = mesh->device.malloc(2*Nall*sizeof(dfloat), BP->lambda);
char *suffix = strdup("Hex3D");
if(options.compareArgs("DISCRETIZATION","CONTINUOUS"))
ogsGatherScatterMany(BP->o_r, BP->Nfields, Ndof, ogsDfloat, ogsAdd, mesh->ogs);
if (mesh->rank==0)
reportMemoryUsage(mesh->device, "setup done");
return BP;
}
void solveSetup(BP_t *BP, dfloat lambda1, occa::properties &kernelInfo){
mesh_t *mesh = BP->mesh;
setupAide options = BP->options;
int knlId = 0;
options.getArgs("KERNEL ID", knlId);
BP->knlId = knlId;
dlong Ntotal = mesh->Np*mesh->Nelements;
dlong Nhalo = mesh->Np*mesh->totalHaloPairs;
dlong Nall = (Ntotal + Nhalo)*BP->Nfields;
dlong Nblock = mymax(1,(Ntotal+blockSize-1)/blockSize);
dlong Nblock2 = mymax(1,(Nblock+blockSize-1)/blockSize);
dlong NthreadsUpdatePCG = 256;
//dlong NblocksUpdatePCG = mymin((Ntotal+NthreadsUpdatePCG-1)/NthreadsUpdatePCG, 32);
dlong NblocksUpdatePCG = (Ntotal+NthreadsUpdatePCG-1)/NthreadsUpdatePCG;
BP->NthreadsUpdatePCG = NthreadsUpdatePCG;
BP->NblocksUpdatePCG = NblocksUpdatePCG;
BP->NsolveWorkspace = 4;
BP->offsetSolveWorkspace = Nall;
/*
const int PAGESIZE = 512; // in bytes
const int pageW = PAGESIZE/sizeof(dfloat);
if (BP->offsetSolveWorkspace%pageW) BP->offsetSolveWorkspace = (BP->offsetSolveWorkspace + 1)*pageW;
dfloat *scratch = (dfloat*) calloc(BP->offsetSolveWorkspace*BP->NsolveWorkspace, sizeof(dfloat));
occa::memory o_scratch = mesh->device.malloc(BP->offsetSolveWorkspace*BP->NsolveWorkspace*sizeof(dfloat), scratch);
*/
BP->o_solveWorkspace = new occa::memory[BP->NsolveWorkspace];
for(int wk=0;wk<BP->NsolveWorkspace;++wk) {
BP->o_solveWorkspace[wk] = mesh->device.malloc(Nall*sizeof(dfloat), BP->solveWorkspace);
//BP->o_solveWorkspace[wk] = o_scratch.slice(wk*BP->offsetSolveWorkspace*sizeof(dfloat));
}
if(options.compareArgs("PRECONDITIONER", "JACOBI")){
BP->o_invDiagA = mesh->device.malloc(Nall*sizeof(dfloat));
int *mapB = (int*) calloc(Nall, sizeof(int));
BP->o_mapB = mesh->device.malloc(Nall*sizeof(int), mapB);
free(mapB);
}
BP->tmp = (dfloat*) calloc(Nblock, sizeof(dfloat));
// BP->tmp2 = (dfloat*) calloc(Nblock2, sizeof(dfloat));
BP->o_tmp = mesh->device.malloc(Nblock*sizeof(dfloat), BP->tmp);
BP->o_tmp2 = mesh->device.malloc(Nblock2*sizeof(dfloat), BP->tmp);
BP->tmpNormr = (dfloat*) calloc(BP->NblocksUpdatePCG,sizeof(dfloat));
BP->o_tmpNormr = mesh->device.malloc(BP->NblocksUpdatePCG*sizeof(dfloat), BP->tmpNormr);
BP->tmpAtomic = (dfloat*) calloc(1,sizeof(dfloat));
BP->o_tmpAtomic = mesh->device.malloc(1*sizeof(dfloat), BP->tmpAtomic);
BP->o_zeroAtomic = mesh->device.malloc(1*sizeof(dfloat), BP->tmpAtomic);
//setup async halo stream
BP->defaultStream = mesh->defaultStream;
BP->dataStream = mesh->dataStream;
dlong Nbytes = BP->Nfields*mesh->totalHaloPairs*mesh->Np*sizeof(dfloat);
if(Nbytes>0){
BP->sendBuffer =
(dfloat*) occaHostMallocPinned(mesh->device, Nbytes, NULL, BP->o_sendBuffer, BP->h_sendBuffer);
BP->recvBuffer =
(dfloat*) occaHostMallocPinned(mesh->device, Nbytes, NULL, BP->o_recvBuffer, BP->h_recvBuffer);
}else{
BP->sendBuffer = NULL;
BP->recvBuffer = NULL;
}
mesh->device.setStream(BP->defaultStream);
BP->type = strdup(dfloatString);
BP->Nblock = Nblock;
BP->Nblock2 = Nblock2;
// count total number of elements
hlong NelementsLocal = mesh->Nelements;
hlong NelementsGlobal = 0;
MPI_Allreduce(&NelementsLocal, &NelementsGlobal, 1, MPI_HLONG, MPI_SUM, mesh->comm);
BP->NelementsGlobal = NelementsGlobal;
//check all the bounaries for a Dirichlet
bool allNeumann = (lambda1==0) ? true :false;
BP->allNeumannPenalty = 1.;
hlong localElements = (hlong) mesh->Nelements;
hlong totalElements = 0;
MPI_Allreduce(&localElements, &totalElements, 1, MPI_HLONG, MPI_SUM, mesh->comm);
BP->allNeumannScale = 1./sqrt((dfloat)mesh->Np*totalElements);
BP->EToB = (int *) calloc(mesh->Nelements*mesh->Nfaces,sizeof(int));
int lallNeumann, gallNeumann;
lallNeumann = allNeumann ? 0:1;
MPI_Allreduce(&lallNeumann, &gallNeumann, 1, MPI_INT, MPI_SUM, mesh->comm);
BP->allNeumann = (gallNeumann>0) ? false: true;
//printf("allNeumann = %d \n", BP->allNeumann);
//copy boundary flags
BP->o_EToB = mesh->device.malloc(mesh->Nelements*mesh->Nfaces*sizeof(int), BP->EToB);
//setup an unmasked gs handle
meshParallelGatherScatterSetup(mesh, Ntotal, mesh->globalIds, mesh->comm, 0);
//make a masked version of the global id numbering
mesh->maskedGlobalIds = (hlong *) calloc(Ntotal,sizeof(hlong));
memcpy(mesh->maskedGlobalIds, mesh->globalIds, Ntotal*sizeof(hlong));
//use the masked ids to make another gs handle
BP->ogs = ogsSetup(Ntotal, mesh->maskedGlobalIds, mesh->comm, 1, mesh->device);
BP->o_invDegree = BP->ogs->o_invDegree;
kernelInfo["defines/p_Nalign"] = USE_OCCA_MEM_BYTE_ALIGN;
kernelInfo["defines/" "p_blockSize"]= blockSize;
kernelInfo["defines/" "p_Nfields"]= BP->Nfields;
string threadModel;
options.getArgs("THREAD MODEL", threadModel);
string arch = "VOLTA";
options.getArgs("ARCH", arch);
int bpid = BP->BPid;
for (int r=0;r<2;r++){
if ((r==0 && mesh->rank==0) || (r==1 && mesh->rank>0)) {
mesh->addScalarKernel =
mesh->device.buildKernel(DBP "/kernel/utils.okl",
"addScalar",
kernelInfo);
mesh->maskKernel =
mesh->device.buildKernel(DBP "/kernel/utils.okl",
"mask",
kernelInfo);
mesh->sumKernel =
mesh->device.buildKernel(DBP "/kernel/utils.okl",
"sum",
kernelInfo);
BP->innerProductKernel =
mesh->device.buildKernel(DBP "/kernel/utils.okl", "innerProduct", kernelInfo);
BP->weightedNorm2Kernel =
mesh->device.buildKernel(DBP "/kernel/utils.okl", "weightedNorm2", kernelInfo);
BP->weightedMultipleNorm2Kernel =
mesh->device.buildKernel(DBP "/kernel/utils.okl", "weightedMultipleNorm2", kernelInfo);
BP->scaledAddKernel =
mesh->device.buildKernel(DBP "/kernel/utils.okl", "scaledAdd", kernelInfo);
BP->dotMultiplyKernel =
mesh->device.buildKernel(DBP "/kernel/utils.okl", "dotMultiply", kernelInfo);
BP->vecCopyKernel =
mesh->device.buildKernel(DBP "/kernel/utils.okl", "vecCopy", kernelInfo);
BP->vecInvKernel =
mesh->device.buildKernel(DBP "/kernel/utils.okl", "vecInv", kernelInfo);
BP->vecScaleKernel =
mesh->device.buildKernel(DBP "/kernel/utils.okl", "vecScale", kernelInfo);
BP->updateJacobiKernel =
mesh->device.buildKernel(DBP "/kernel/updateJacobi.okl", "updateJacobi", kernelInfo);
/*
BP->vecAtomicGatherKernel =
mesh->device.buildKernel(DBP "/kernel/utils.okl", "vecAtomicGather", kernelInfo);
BP->vecAtomicMultipleGatherKernel =
mesh->device.buildKernel(DBP "/kernel/utils.okl", "vecAtomicMultipleGather", kernelInfo);
BP->vecAtomicInnerProductKernel =
mesh->device.buildKernel(DBP "/kernel/utils.okl", "vecAtomicInnerProduct", kernelInfo);
*/
// add custom defines
kernelInfo["defines/" "p_NpTet"]= mesh->Np;
kernelInfo["defines/" "p_NpP"]= (mesh->Np+mesh->Nfp*mesh->Nfaces);
kernelInfo["defines/" "p_Nverts"]= mesh->Nverts;
int Nmax = mymax(mesh->Np, mesh->Nfaces*mesh->Nfp);
int maxNodes = mymax(mesh->Np, (mesh->Nfp*mesh->Nfaces));
int NblockV = mymax(1,maxNthreads/mesh->Np); // works for CUDA
int NnodesV = 1; //hard coded for now
int NblockS = mymax(1,maxNthreads/maxNodes); // works for CUDA
int NblockP = mymax(1,maxNthreads/(4*mesh->Np)); // get close to maxNthreads threads
int NblockG;
if(mesh->Np<=32) NblockG = ( 32/mesh->Np );
else NblockG = maxNthreads/mesh->Np;
kernelInfo["defines/" "p_Nmax"]= Nmax;
kernelInfo["defines/" "p_maxNodes"]= maxNodes;
kernelInfo["defines/" "p_NblockV"]= NblockV;
kernelInfo["defines/" "p_NnodesV"]= NnodesV;
kernelInfo["defines/" "p_NblockS"]= NblockS;
kernelInfo["defines/" "p_NblockP"]= NblockP;
kernelInfo["defines/" "p_NblockG"]= NblockG;
kernelInfo["defines/" "p_halfC"]= (int)((mesh->cubNq+1)/2);
kernelInfo["defines/" "p_halfN"]= (int)((mesh->Nq+1)/2);
kernelInfo["defines/" "p_NthreadsUpdatePCG"] = (int) NthreadsUpdatePCG; // WARNING SHOULD BE MULTIPLE OF 32
kernelInfo["defines/" "p_NwarpsUpdatePCG"] = (int) (NthreadsUpdatePCG/32); // WARNING: CUDA SPECIFIC
BP->BPKernel = (occa::kernel*) new occa::kernel[20];
int combineDot = 0;
combineDot = 0; //options.compareArgs("COMBINE DOT PRODUCT", "TRUE");
occa::properties props = kernelInfo;
if(strstr(threadModel.c_str(), "NATIVE")) props["okl/enabled"] = false;
string fileName = DBP "/kernel/" + arch + "/updatePCG.okl";
if(strstr(threadModel.c_str(), "NATIVE+SERIAL") || strstr(threadModel.c_str(), "NATIVE+OPENMP"))
fileName = "kernel/" + arch + "/updatePCG.c";
BP->updatePCGKernel =
mesh->device.buildKernel(fileName.c_str(), "BPUpdatePCG", props);
BP->updateMultiplePCGKernel =
mesh->device.buildKernel(fileName.c_str(), "BPMultipleUpdatePCG", props);
fileName = DBP "/kernel/utils.okl";
if(strstr(threadModel.c_str(), "NATIVE+SERIAL") || strstr(threadModel.c_str(), "NATIVE+OPENMP"))
fileName = "kernel/" + arch + "/weightedInnerProduct.c";
BP->weightedInnerProduct2Kernel =
mesh->device.buildKernel(fileName.c_str(), "weightedInnerProduct2", props);
BP->weightedMultipleInnerProduct2Kernel =
mesh->device.buildKernel(fileName.c_str(), "weightedMultipleInnerProduct2", props);
occa::kernel nothingKernel = mesh->device.buildKernel(DBP "/kernel/utils.okl", "nothingKernel", kernelInfo);
nothingKernel();
}
MPI_Barrier(mesh->comm);
}
string kernelName = "axhelm";
if(BP->Nfields > 1) kernelName += "_n" + std::to_string(BP->Nfields);
kernelName += "_v" + std::to_string(knlId);
BP->BPKernel[bpid] = loadAxKernel(mesh->device, threadModel, arch, kernelName, mesh->N, mesh->Nelements);
// WARNING C0 appropriate only
mesh->sumKernel(mesh->Nelements*mesh->Np, BP->o_invDegree, BP->o_tmp);
BP->o_tmp.copyTo(BP->tmp);
dfloat nullProjectWeightLocal = 0;
dfloat nullProjectWeightGlobal = 0;
for(dlong n=0;n<BP->Nblock;++n)
nullProjectWeightLocal += BP->tmp[n];
MPI_Allreduce(&nullProjectWeightLocal, &nullProjectWeightGlobal, 1, MPI_DFLOAT, MPI_SUM, mesh->comm);
BP->nullProjectWeightGlobal = 1./nullProjectWeightGlobal;
}
| [
"stefanke@gpu03.ftm.alcf.anl.gov"
] | stefanke@gpu03.ftm.alcf.anl.gov |
37376ef68df587ce1671bf3921841995bf8fe21d | dde6e0373d64418ceac8da010144cc921d33eec7 | /HTest1/src/GOffAxisCamera.h | c7a1be2597c9969e0494079456eb0309962c1e2a | [] | no_license | fengxiuyaun/OgreHavokTest | 25eb1e9f7eba0712e12e51bc6e8233223a314ebd | 7bac456c4bc5513ccbe0ae0695e9fa28f7c4316b | refs/heads/master | 2020-04-05T23:34:01.993161 | 2011-08-01T03:54:47 | 2011-08-01T03:54:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,512 | h | #ifndef __GOFFAXKIS_HEADER__
#define __GOFFAXKIS_HEADER__
#include "Singleton.h"
#include <windows.h>
#include <stdlib.h>
#include <stdio.h>
#include <vector>
#include "ExampleApplication.h"
#pragma once
#define NUMBER_OF_DISPLAYS 4
class GOffAxisCamera : public HK::Singleton<GOffAxisCamera> {
friend class HK::Singleton<GOffAxisCamera>;
protected:
GOffAxisCamera();
~GOffAxisCamera();
public:
Ogre::SceneNode *GetUberNode(){return _uberNode;}
bool LoadIni(char *file);
void Start(){_bStart = true;}
void EnableOffAxisProjection(Ogre::Camera *camera);
void MoveCamera(Ogre::Vector3 rot, Ogre::Vector3 trans);
void SetPosition(Ogre::Vector3 pos){
_uberNode->setPosition(pos); //Update uber node
_dummyCam->setPosition(pos); //Update dummy camera
};
Ogre::Vector3 GetPosition(){return _uberNode->getPosition();}
void SetOrientation(Ogre::Quaternion o){_uberNode->setOrientation(o);}
Ogre::Quaternion GetOrientation(){return _uberNode->getOrientation();}
Ogre::Quaternion GetRealCameraOrientation(){return _dummyCam->getRealOrientation();}
void SetMatrix(Ogre::Matrix4 m){_offAxis = m;}
void SetCamera(Ogre::Camera *c){
_camera = c;
_uberNode->attachObject(_camera);
}
void Update();
private:
double _dFOVLeft,_dFOVRight,_dFOVTop,_dFOVBottom;
double _dCaveRoll, _dCavePitch, _dCaveYaw;
double _dCaveFOV;
bool _bStart;
int _nDisplays;
Ogre::Matrix4 _offAxis;
Ogre::Camera *_camera;
Ogre::SceneNode *_uberNode;
Ogre::Camera *_dummyCam;
};
#endif // __GDEBUGGER_HEADER__ | [
"jerdak@gmail.com"
] | jerdak@gmail.com |
58937a7cc330d6119d46923904850fce73d25a3f | 378969fa995f5f4d479ec7af87d7fb7e42332be2 | /lib/shader.hpp | c883f47988581fd97cf577cec07eadc4dab79b5d | [
"Unlicense"
] | permissive | mewbak/ying | b995551f132e91a1d1fd319a72921d5b632ba505 | 8daccccc2de5a2dbf2430146adbbbf67c26551d9 | refs/heads/master | 2020-04-16T07:54:54.530756 | 2019-01-12T17:13:10 | 2019-01-12T17:13:10 | 165,403,759 | 0 | 0 | null | 2019-01-12T15:33:58 | 2019-01-12T15:33:57 | null | UTF-8 | C++ | false | false | 5,329 | hpp | #ifndef SHADER_H
#define SHADER_H
// System Headers
#include <glad/glad.h>
#include <glm/glm.hpp>
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
class Shader {
public:
// The program id
unsigned int ID;
// Constructor reads and builds the Shader
Shader(const char* vertexPath, const char* fragmentPath) {
// 1. Retrieve the vertex/fragment source code from filePath
std::string vertexCode;
std::string fragmentCode;
std::ifstream vShaderFile;
std::ifstream fShaderFile;
// ensure ifstream objects can throw exceptions:
vShaderFile.exceptions (std::ifstream::failbit | std::ifstream::badbit);
fShaderFile.exceptions (std::ifstream::failbit | std::ifstream::badbit);
try {
// Open files
vShaderFile.open(vertexPath);
fShaderFile.open(fragmentPath);
std::stringstream vShaderStream, fShaderStream;
// Read file's buffer contents intro streams
vShaderStream << vShaderFile.rdbuf();
fShaderStream << fShaderFile.rdbuf();
// Close file handlers
vShaderFile.close();
fShaderFile.close();
// Convert stream into string
vertexCode = vShaderStream.str();
fragmentCode = fShaderStream.str();
} catch (std::ifstream::failure e) {
throw std::runtime_error("SHADER::FILE_NOT_SUCCESSFULLY_READ: " + e.code().message());
}
const char* vShaderCode = vertexCode.c_str();
const char* fShaderCode = fragmentCode.c_str();
// 2. Compile shaders
unsigned int vertex, fragment;
// Vertex shader
vertex = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertex, 1, &vShaderCode, nullptr);
glCompileShader(vertex);
checkCompileErrors(vertex, "VERTEX");
// Fragment shader
fragment = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragment, 1, &fShaderCode, nullptr);
glCompileShader(fragment);
checkCompileErrors(fragment, "FRAGMENT");
// Shader Program
ID = glCreateProgram();
glAttachShader(ID, vertex);
glAttachShader(ID, fragment);
glLinkProgram(ID);
checkCompileErrors(ID, "PROGRAM");
// Delete the shaders as they're linked into our program now and no longer necessary
glDeleteShader(vertex);
glDeleteShader(fragment);
}
// Use/activate the Shader
void use() {
glUseProgram(ID);
}
// Utility uniform functions
void setBool(const std::string &name, bool value) const {
glUniform1i(glGetUniformLocation(ID, name.c_str()), (int)value);
}
void setInt(const std::string &name, int value) const {
glUniform1i(glGetUniformLocation(ID, name.c_str()), value);
}
void setFloat(const std::string &name, float value) const {
glUniform1f(glGetUniformLocation(ID, name.c_str()), value);
}
void setVec2(const std::string &name, const glm::vec2 &value) const {
glUniform2fv(glGetUniformLocation(ID, name.c_str()), 1, &value[0]);
}
void setVec2(const std::string &name, float x, float y) const {
glUniform2f(glGetUniformLocation(ID, name.c_str()), x, y);
}
void setVec3(const std::string &name, const glm::vec3 &value) const {
glUniform3fv(glGetUniformLocation(ID, name.c_str()), 1, &value[0]);
}
void setVec3(const std::string &name, float x, float y, float z) const {
glUniform3f(glGetUniformLocation(ID, name.c_str()), x, y, z);
}
void setVec4(const std::string &name, const glm::vec4 &value) const {
glUniform4fv(glGetUniformLocation(ID, name.c_str()), 1, &value[0]);
}
void setVec4(const std::string &name, float x, float y, float z, float w) const {
glUniform4f(glGetUniformLocation(ID, name.c_str()), x, y, z, w);
}
void setMat2(const std::string &name, const glm::mat2 &mat) const {
glUniformMatrix2fv(glGetUniformLocation(ID, name.c_str()), 1, GL_FALSE, &mat[0][0]);
}
void setMat3(const std::string &name, const glm::mat3 &mat) const {
glUniformMatrix3fv(glGetUniformLocation(ID, name.c_str()), 1, GL_FALSE, &mat[0][0]);
}
void setMat4(const std::string &name, const glm::mat4 &mat) const {
glUniformMatrix4fv(glGetUniformLocation(ID, name.c_str()), 1, GL_FALSE, &mat[0][0]);
}
private:
// Utility function for checking shader compilation/linking errors.
void checkCompileErrors(unsigned int shader, std::string type) {
int success;
char infoLog[1024];
if (type != "PROGRAM") {
// Print compile errors if any
glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
if (success) {
return;
}
glGetShaderInfoLog(shader, 1024, nullptr, infoLog);
throw std::runtime_error("VERTEX::COMPILATION_ERROR of type: " + type + " " + std::string(infoLog));
} else {
glGetProgramiv(shader, GL_LINK_STATUS, &success);
if (success) {
return;
}
glGetProgramInfoLog(shader, 1024, nullptr, infoLog);
throw std::runtime_error("PROGRAM_LINKING_ERROR of type: " + type + " " + std::string(infoLog));
}
}
};
#endif
| [
"henry@karlek.io"
] | henry@karlek.io |
dfb6247e47d201d3c3565423dbd3be55c844fb0c | cda270bdbce3f32e7e764acb8657466bb3a90044 | /src/data_types.cpp | 53b6021d74fcd4bf8d76d4666063511950a08688 | [] | no_license | make-j64/focus-stacking | 6e177d8bddc6729e07be035d01479601f275dc7d | d0e46e3904a3f4f0323adfea32c01bfd9aae394c | refs/heads/master | 2022-03-10T21:51:28.985736 | 2019-11-26T10:11:49 | 2019-11-26T10:11:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 150 | cpp | #include "data_types.h"
std::ostream& operator << (std::ostream& os, coordinate &c)
{
os << "(" << c.x << ", " << c.y << ")";
return os;
}
| [
"markosloizou@hotmail.com"
] | markosloizou@hotmail.com |
becb7aa59ae134fdb492ff13cf50f0376bfb18e6 | 7873fa1647bab7ecac2bc5a98367aa96f32fb94a | /AFS.cpp | 47446ceba569bb9b1bd8e1c09fd19202c8e52d7f | [] | no_license | pegasus1/SPOJ | 81158badc827e978db0e9c429dc34181f0bfe1ee | eff901d039b63b6a337148dfbe37c1536918bbf8 | refs/heads/master | 2021-01-10T05:32:37.535098 | 2015-06-05T18:20:38 | 2015-06-05T18:20:38 | 36,937,530 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 765 | cpp | #include<iostream>
using namespace std;
#include<stdio.h>
int main()
{
int t;
unsigned long long n,st,lt,i,sum,p,s1;
scanf("%d",&t);
while(t--)
{
sum = 0;
scanf("%llu",&n);
if(n<=3)
printf("%d\n",n-1);
else
{
for(i=2;i*i<=n;i++)
{
p = n/i;
sum+=(p-1)*i;
st = p+1;
lt = n/(i-1);
s1 = ((lt-st+1)*(st+lt))/2;
s1 = s1 * (i-2);
sum = sum+s1;
}
for(;i<st;i++)
{
p = n/i;
sum = sum + (p-1)*i;
}
sum+=n-1;
printf("%llu\n",sum);
}
}
return 0;
}
| [
"ayush.rajoria@outlook.com"
] | ayush.rajoria@outlook.com |
8818c85b84b7efefffc574673e7e79eb3fb32adb | 23378c451e396684f712fc9f9e2a65a53a61a8a8 | /Dynamic_Programming/1872.Stone-Game-VIII/1872.Stone-Game-VIII.cpp | 2b974ed34f7972069362459a6bdcf72b4ceba80e | [] | no_license | wisdompeak/LeetCode | 25676a8bf606c0511dd9844d4e61388235de82f4 | f3d38bbe9e40ceb0ab9780a4cb0dec938eae578e | refs/heads/master | 2023-09-01T18:45:36.056015 | 2023-08-28T08:01:22 | 2023-08-28T08:01:22 | 83,542,585 | 5,153 | 1,209 | null | 2023-07-22T18:15:25 | 2017-03-01T10:30:52 | C++ | UTF-8 | C++ | false | false | 542 | cpp | class Solution {
public:
int stoneGameVIII(vector<int>& stones)
{
int n = stones.size();
stones.insert(stones.begin(), 0);
vector<int>presum(n+1);
for (int i=1; i<=n; i++)
presum[i] = presum[i-1]+stones[i];
vector<int>dp(n+1);
dp[1] = 0;
dp[2] = presum[n] - dp[1];
for (int i=3; i<=n; i++)
{
dp[i] = max(dp[i-1], presum[n-i+2]-dp[i-1]);
}
return dp[n];
}
};
| [
"noreply@github.com"
] | wisdompeak.noreply@github.com |
60bc4cc438b1fb32b7356bb403af21e2fac0dd37 | a49ad8d5b41bd36f7d4f7b96c7770e7a39bfdba1 | /BSc (H) Sem 18-94033-45/serious stuff/CALC.cpp | 383c32251e4ad5a0fe87220be0f7db2ce2849b4d | [] | no_license | Legedith/1st-sem | 7fd10a58d9b80fa5668f9a38966f8452569f7f12 | ed99f573c5132be1047b774bc9e12268ccbae7a9 | refs/heads/master | 2020-06-29T23:18:06.147719 | 2019-10-23T00:59:40 | 2019-10-23T00:59:40 | 200,653,230 | 0 | 1 | null | 2019-10-23T00:59:41 | 2019-08-05T12:42:05 | C++ | UTF-8 | C++ | false | false | 4,128 | cpp | #include <iostream>
#include <conio.h>
using namespace std;
void HomePage(float []);
void menu(float []);
void Switch(char, float []);
void ca();
float add( float [] );
float sub( float [] );
float multiply( float [] );
float div( float [] );
int mod( float [] );
int limit;
float result;
string choice;
int main()
{
ca();
return 0;
}
void HomePage(float array[])
{
while (choice!="Exit" && choice!="exit" && choice!= "EXIT" && choice!="2")
{
cout<<" *************************************************"<<endl;
cout<<" * WELCOME *"<<endl;
cout<<" * ------- *"<<endl;
cout<<" * 1.Menu *"<<endl;
cout<<" * 2.Exit *"<<endl;
cout<<" * *"<<endl;
cout<<" *************************************************"<<endl;
cout<<"Enter your choice - ";
cin>>choice;
cout<<endl<<endl<<endl;
if (choice=="Exit" || choice=="exit" || choice== "EXIT" || choice=="2")
{
break;
}
else if( choice=="Menu" || choice=="menu" || choice == "MENU" || choice == "1")
{
menu(array);
break;
}
else
cout<<"\nWrong choice entered\n\n\n\n\n";
}
}
void menu(float array[])
{
char ch,en='y';
while(en=='y' || en=='Y')
{
cout<<" #**************************#"<<endl;
cout<<" * Menu *"<<endl;
cout<<" * ______ *"<<endl;
cout<<" * A.Addition *"<<endl;
cout<<" * B.Subtraction *"<<endl;
cout<<" * C.Multiplication *"<<endl;
cout<<" * D.Division *"<<endl;
cout<<" * E.Modulus *"<<endl;
cout<<" * F.Go Back *"<<endl;
cout<<" #**************************#"<<endl;
cout<<" CAUTION - Precision will be lost in case of modulo function.\n";
cout<<" (Decimals will be converted to integers)\n\n\n ";
cout<<" Select an operation - ";
cin>>ch;
cout<<endl<<endl;
Switch(ch, array);
cout<<" Do you want to continue\n (Reply y or Y to continue) - ";
cin>>en;
}
}
void Switch(char ch, float array[])
{
switch(ch)
{
case 'a':
case 'A':
case '1': result= add(array);
cout<<"The sum of the numbers is "<<result<<endl<<endl;
break;
case 'b':
case 'B':
case '2':result=sub(array);
cout<<"The difference of the numbers is "<<result<<endl<<endl;
break;
case 'c':
case 'C':
case '3':result= multiply(array);
cout<<"The product of the numbers is "<<result<<endl<<endl;
break;
case 'd':
case 'D':
case '4':result=div(array);
cout<<"The result is "<<result<<endl<<endl;
break;
case 'e':
case 'E':
case '5':result=mod(array);
cout<<"The result is "<<result<<endl<<endl;
break;
case 'f':
case 'F':
case '6': HomePage(array);
choice="exit";
break;
default:
cout<<"You have entered wrong input\n\n\n\n";
menu(array);
}
}
float add( float array[] )
{
float sum=0;
for(int i=0; i<limit; i++ )
sum = sum + array[i];
return sum;
}
float multiply( float array[] )
{
float pro=1;
for(int i=0; i<limit; i++ )
pro = pro * array[i];
return pro;
}
float sub( float array[] )
{
int n1,n2;
cout<<"Select element 1 - ";
cin>>n1;
cout<<"Select element 2 - ";
cin>>n2;
n1--;
n2--;
result = array[n1]-array[n2];
return result;
}
float div( float array[] )
{
int n1,n2;
cout<<"Select element 1 - ";
cin>>n1;
cout<<"Select element 2 - ";
cin>>n2;
n1--;
n2--;
result = array[n1]/array[n2];
return result;
}
int mod( float array[] )
{
int n1,n2;
cout<<"Select element 1 - ";
cin>>n1;
cout<<"Select element 2 - ";
cin>>n2;
n1--;
n2--;
int num1= static_cast<int>(array[n1]);
int num2= array[n2];
cout<<num1<<"Is num1 and \n"<<endl<<num2<<" is num2";
result = num1%num2;
cout<<endl<<result<<endl;
return result;
}
void ca()
{
cout<<"On how many numbers would you like to perform the calculations - ";
cin>>limit;
cout<<endl;
float array[ limit ];
for (int i=0,j=1; i<limit;i++,j++)
{
cout<<"Enter number "<<j <<" - "<<"\n";
cin>>array[i];
}
HomePage(array);
}
| [
"jatindehmiwal@gmail.com"
] | jatindehmiwal@gmail.com |
a68c239156ad1cd518b926b9a23b210b8310e418 | 6bcd0eb0cf8a2ecf4fb60f1a354424ad3e8ce5e7 | /DeviceEnumeration/cpp/BackgroundDeviceWatcherTaskCpp/BackgroundDeviceWatcherTaskCpp.h | d2a78cd21f10e7bdbc54c24b56ab108f0873a12a | [
"MIT"
] | permissive | mhdubose/Windows-universal-samples | 8e0fa492ca624b96f60a28913753066eac8e09f4 | 7c3abf2bc631dccdd19c1a55fc16109c3d3e78d5 | refs/heads/master | 2021-01-14T12:35:20.616148 | 2015-08-27T23:11:19 | 2015-08-27T23:15:06 | 38,263,630 | 0 | 0 | null | 2015-06-29T18:27:38 | 2015-06-29T18:27:37 | null | UTF-8 | C++ | false | false | 409 | h | // Copyright (c) Microsoft Corporation. All rights reserved.
#pragma once
using namespace Windows::ApplicationModel::Background;
namespace BackgroundDeviceWatcherTaskCpp
{
[Windows::Foundation::Metadata::WebHostHidden]
public ref class BackgroundDeviceWatcher sealed : public IBackgroundTask
{
public:
BackgroundDeviceWatcher() {}
virtual void Run(IBackgroundTaskInstance^ taskInstance);
};
}
| [
"IrinVoso@users.noreply.github.com"
] | IrinVoso@users.noreply.github.com |
326290c4ecf7545c941af67142c603da0505e157 | 63daf225819636397fda6ef7e52783331c27f295 | /python-call-so/testLib.cpp | bbf6a8f55cc42027b4cbcec402ee07baefe0a278 | [] | no_license | cash2one/language-Python | e332ecfb4e9321a11407b29987ee64d44e552b15 | 8adb4f2fd2f023f9cc89b4edce1da5f71a3332ab | refs/heads/master | 2021-06-16T15:15:08.346420 | 2017-04-20T02:44:16 | 2017-04-20T02:44:16 | 112,173,361 | 1 | 0 | null | 2017-11-27T09:08:57 | 2017-11-27T09:08:57 | null | UTF-8 | C++ | false | false | 345 | cpp | #include <stdio.h>
#include "testLib.h"
CTestLib::CTestLib()
{
}
CTestLib::~CTestLib()
{
}
int CTestLib::sum(int a, int b)
{
int result = a + b;
show(result);
return result;
}
void CTestLib::show(int value)
{
printf("[class] result: %d\n", value);
}
extern "C" {
CTestLib obj;
int sum(int a, int b)
{
return obj.sum(a, b);
}
}
| [
"finetang@gmail.com"
] | finetang@gmail.com |
1b43d695bb39c699a7e2dea6a30fb26f9029cea6 | 6d4bb1fd018e732e190c3967c8738313340e9b0a | /src/Wrapper/HK/include/HK/DVRStatementImpl.h | b01fe1980b73ffdd8ac6df2911ed5f8fbef68b34 | [] | no_license | anyboo/Phoenix | 5c14f39bce905b2cc26e037973e28012dcb9da34 | 13b9608e402e5f3ce2feabb4bad5a0e7c862699a | refs/heads/RefireCode | 2020-04-12T03:05:30.351331 | 2016-09-28T10:12:47 | 2016-09-28T10:12:47 | 62,291,017 | 3 | 5 | null | 2016-09-28T10:12:47 | 2016-06-30T07:48:54 | C | UTF-8 | C++ | false | false | 1,200 | h | #pragma once
#include "HKLite.h"
#include "DVR/DVRStatementImpl.h"
#include "HK/Utility.h"
namespace DVR {
namespace HKLite {
class HKLite_API DVRStatementImpl : public DVR::DVRStatementImpl
{
public:
DVRStatementImpl(DVR::DVRSessionImpl& rSession, Utility::HANDLE pDvr);
~DVRStatementImpl();
long donwloadByName(const RecordFile& rf, const std::string& filename);
void downloadByTime(const Poco::DateTime& time);
int getdownloadPos(const long handle);
int playByName(const RecordFile& filename, HWND& hwnd);
void playByTime(const Poco::DateTime& time);
void stopPlayback(const int playhandle);
void setplayPos(const int playhandle, const int proValue);
int getplayPos(const int playhandle);
void list(const Poco::DateTime& beginTime, const Poco::DateTime& endTime, const std::vector<int>& channels, std::vector<RecordFile>& files);
bool canDownloadByName();
bool canPlayByName();
typedef void (*ProcessCallbackType)(long lPlayHandle, long lTotalSize, long lDownLoadSize, long dwUser);
private:
Utility::HANDLE _handle;
int _state;
};
inline bool DVRStatementImpl::canDownloadByName()
{
return true;
}
inline bool DVRStatementImpl::canPlayByName()
{
return true;
}
}}
| [
"zyf079@gmail.com"
] | zyf079@gmail.com |
3eb45ce17fdc3f412c3ba5d21c490254f36407ed | d077e40e376f16c9420f32001decf946a34a6e71 | /NumCore/HypreGMRESsolver.h | 75f51ed9a15f506a626c6bfec34cda62c70ee4e5 | [
"MIT"
] | permissive | jnbrunet/febio2 | 43196e79f8c54a5c92f3f592aa7437fd3b3fe842 | fdbedae97c7d2ecad3dc89d25c8343cfbdeb195a | refs/heads/master | 2021-07-21T01:04:58.828864 | 2020-05-19T06:47:31 | 2020-05-19T06:47:31 | 203,228,954 | 0 | 0 | null | 2019-08-19T18:38:29 | 2019-08-19T18:38:28 | null | UTF-8 | C++ | false | false | 2,212 | h | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2019 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include <FECore/LinearSolver.h>
#include "CompactUnSymmMatrix.h"
//-----------------------------------------------------------------------------
// This class implements the HYPRE GMRES solver
class HypreGMRESsolver : public LinearSolver
{
class Implementation;
public:
HypreGMRESsolver();
~HypreGMRESsolver();
void SetPrintLevel(int n);
void SetMaxIterations(int n);
void SetConvergencTolerance(double tol);
public:
// allocate storage
bool PreProcess();
//! Factor the matrix (for iterative solvers, this can be used for creating pre-conditioner)
bool Factor();
//! Calculate the solution of RHS b and store solution in x
bool BackSolve(vector<double>& x, vector<double>& b);
//! Return a sparse matrix compatible with this solver
SparseMatrix* CreateSparseMatrix(Matrix_Type ntype);
//! set the sparse matrix
bool SetSparseMatrix(SparseMatrix* A) override;
private:
Implementation* imp;
};
| [
"mherron@omen.sci.utah.edu"
] | mherron@omen.sci.utah.edu |
80e08b81a41f4c07118a85f3a3eca02143564dca | b794490c0e89db4a3a4daabe91b2f057a32878f0 | /Hook/Hook_Ring3/KeboardHook/KeboardHook.cpp | f3da580ad465121fa1c2f64a311fd1c5958d21d6 | [] | no_license | FusixGit/hf-2011 | 8ad747ee208183a194d0ce818f07d312899a44d2 | e0f1d9743238d75ea81f1c8d0a3ea1b5a2320a16 | refs/heads/master | 2021-01-10T17:31:14.137939 | 2012-11-05T12:43:24 | 2012-11-05T12:43:24 | 50,957,230 | 3 | 8 | null | null | null | null | GB18030 | C++ | false | false | 95 | cpp | // KeboardHook.cpp : 定义 DLL 应用程序的导出函数。
//
#include "stdafx.h"
| [
"hongfu830202@gmail.com"
] | hongfu830202@gmail.com |
3df6c4edd068d49ee25386a20c261446f8034967 | f3a316a2f25b37793e1741295d7e932e3d8e7c09 | /source/common/simpleformatter.cpp | ae17a0500518a892e7588f2ee3299c664cb9c56b | [
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"NAIST-2003",
"BSD-3-Clause",
"LicenseRef-scancode-unicode",
"ICU",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | CdTCzech/ICU | 3cb59891b9efcbcfa5fb6e75d394d666561650a3 | 4c9b8dfefd9a26096f7642c556fa3b4bd887317e | refs/heads/master | 2023-03-01T19:23:09.347544 | 2021-02-09T13:01:11 | 2021-02-09T13:01:11 | 257,857,185 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,246 | cpp | // © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
******************************************************************************
* Copyright (C) 2014-2016, International Business Machines
* Corporation and others. All Rights Reserved.
******************************************************************************
* simpleformatter.cpp
*/
#include "unicode/utypes.h"
#include "unicode/simpleformatter.h"
#include "unicode/unistr.h"
#include "uassert.h"
U_NAMESPACE_BEGIN
namespace {
/**
* Argument numbers must be smaller than this limit.
* Text segment lengths are offset by this much.
* This is currently the only unused char value in compiled patterns,
* except it is the maximum value of the first unit (max arg +1).
*/
const int32_t ARG_NUM_LIMIT = 0x100;
/**
* Initial and maximum char/UChar value set for a text segment.
* Segment length char values are from ARG_NUM_LIMIT+1 to this value here.
* Normally 0xffff, but can be as small as ARG_NUM_LIMIT+1 for testing.
*/
const UChar SEGMENT_LENGTH_PLACEHOLDER_CHAR = 0xffff;
/**
* Maximum length of a text segment. Longer segments are split into shorter ones.
*/
const int32_t MAX_SEGMENT_LENGTH = SEGMENT_LENGTH_PLACEHOLDER_CHAR - ARG_NUM_LIMIT;
enum {
APOS = 0x27,
DIGIT_ZERO = 0x30,
DIGIT_ONE = 0x31,
DIGIT_NINE = 0x39,
OPEN_BRACE = 0x7b,
CLOSE_BRACE = 0x7d
};
inline UBool isInvalidArray(const void *array, int32_t length) {
return (length < 0 || (array == NULL && length != 0));
}
} // namespace
SimpleFormatter &SimpleFormatter::operator=(const SimpleFormatter& other) {
if (this == &other) {
return *this;
}
compiledPattern = other.compiledPattern;
return *this;
}
SimpleFormatter::~SimpleFormatter() {}
UBool SimpleFormatter::applyPatternMinMaxArguments(
const UnicodeString &pattern,
int32_t min, int32_t max,
UErrorCode &errorCode) {
if (U_FAILURE(errorCode)) {
return FALSE;
}
// Parse consistent with MessagePattern, but
// - support only simple numbered arguments
// - build a simple binary structure into the result string
const UChar *patternBuffer = pattern.getBuffer();
int32_t patternLength = pattern.length();
// Reserve the first char for the number of arguments.
compiledPattern.setTo((UChar)0);
int32_t textLength = 0;
int32_t maxArg = -1;
UBool inQuote = FALSE;
for (int32_t i = 0; i < patternLength;) {
UChar c = patternBuffer[i++];
if (c == APOS) {
if (i < patternLength && (c = patternBuffer[i]) == APOS) {
// double apostrophe, skip the second one
++i;
} else if (inQuote) {
// skip the quote-ending apostrophe
inQuote = FALSE;
continue;
} else if (c == OPEN_BRACE || c == CLOSE_BRACE) {
// Skip the quote-starting apostrophe, find the end of the quoted literal text.
++i;
inQuote = TRUE;
} else {
// The apostrophe is part of literal text.
c = APOS;
}
} else if (!inQuote && c == OPEN_BRACE) {
if (textLength > 0) {
compiledPattern.setCharAt(compiledPattern.length() - textLength - 1,
(UChar)(ARG_NUM_LIMIT + textLength));
textLength = 0;
}
int32_t argNumber;
if ((i + 1) < patternLength &&
0 <= (argNumber = patternBuffer[i] - DIGIT_ZERO) && argNumber <= 9 &&
patternBuffer[i + 1] == CLOSE_BRACE) {
i += 2;
} else {
// Multi-digit argument number (no leading zero) or syntax error.
// MessagePattern permits PatternProps.skipWhiteSpace(pattern, index)
// around the number, but this class does not.
argNumber = -1;
if (i < patternLength && DIGIT_ONE <= (c = patternBuffer[i++]) && c <= DIGIT_NINE) {
argNumber = c - DIGIT_ZERO;
while (i < patternLength &&
DIGIT_ZERO <= (c = patternBuffer[i++]) && c <= DIGIT_NINE) {
argNumber = argNumber * 10 + (c - DIGIT_ZERO);
if (argNumber >= ARG_NUM_LIMIT) {
break;
}
}
}
if (argNumber < 0 || c != CLOSE_BRACE) {
errorCode = U_ILLEGAL_ARGUMENT_ERROR;
return FALSE;
}
}
if (argNumber > maxArg) {
maxArg = argNumber;
}
compiledPattern.append((UChar)argNumber);
continue;
} // else: c is part of literal text
// Append c and track the literal-text segment length.
if (textLength == 0) {
// Reserve a char for the length of a new text segment, preset the maximum length.
compiledPattern.append(SEGMENT_LENGTH_PLACEHOLDER_CHAR);
}
compiledPattern.append(c);
if (++textLength == MAX_SEGMENT_LENGTH) {
textLength = 0;
}
}
if (textLength > 0) {
compiledPattern.setCharAt(compiledPattern.length() - textLength - 1,
(UChar)(ARG_NUM_LIMIT + textLength));
}
int32_t argCount = maxArg + 1;
if (argCount < min || max < argCount) {
errorCode = U_ILLEGAL_ARGUMENT_ERROR;
return FALSE;
}
compiledPattern.setCharAt(0, (UChar)argCount);
return TRUE;
}
UnicodeString& SimpleFormatter::format(
const UnicodeString &value0,
UnicodeString &appendTo, UErrorCode &errorCode) const {
const UnicodeString *values[] = { &value0 };
return formatAndAppend(values, 1, appendTo, NULL, 0, errorCode);
}
UnicodeString& SimpleFormatter::format(
const UnicodeString &value0,
const UnicodeString &value1,
UnicodeString &appendTo, UErrorCode &errorCode) const {
const UnicodeString *values[] = { &value0, &value1 };
return formatAndAppend(values, 2, appendTo, NULL, 0, errorCode);
}
UnicodeString& SimpleFormatter::format(
const UnicodeString &value0,
const UnicodeString &value1,
const UnicodeString &value2,
UnicodeString &appendTo, UErrorCode &errorCode) const {
const UnicodeString *values[] = { &value0, &value1, &value2 };
return formatAndAppend(values, 3, appendTo, NULL, 0, errorCode);
}
UnicodeString& SimpleFormatter::formatAndAppend(
const UnicodeString *const *values, int32_t valuesLength,
UnicodeString &appendTo,
int32_t *offsets, int32_t offsetsLength, UErrorCode &errorCode) const {
if (U_FAILURE(errorCode)) {
return appendTo;
}
if (isInvalidArray(values, valuesLength) || isInvalidArray(offsets, offsetsLength) ||
valuesLength < getArgumentLimit()) {
errorCode = U_ILLEGAL_ARGUMENT_ERROR;
return appendTo;
}
return format(compiledPattern.getBuffer(), compiledPattern.length(), values,
appendTo, NULL, TRUE,
offsets, offsetsLength, errorCode);
}
UnicodeString &SimpleFormatter::formatAndReplace(
const UnicodeString *const *values, int32_t valuesLength,
UnicodeString &result,
int32_t *offsets, int32_t offsetsLength, UErrorCode &errorCode) const {
if (U_FAILURE(errorCode)) {
return result;
}
if (isInvalidArray(values, valuesLength) || isInvalidArray(offsets, offsetsLength)) {
errorCode = U_ILLEGAL_ARGUMENT_ERROR;
return result;
}
const UChar *cp = compiledPattern.getBuffer();
int32_t cpLength = compiledPattern.length();
if (valuesLength < getArgumentLimit(cp, cpLength)) {
errorCode = U_ILLEGAL_ARGUMENT_ERROR;
return result;
}
// If the pattern starts with an argument whose value is the same object
// as the result, then we keep the result contents and append to it.
// Otherwise we replace its contents.
int32_t firstArg = -1;
// If any non-initial argument value is the same object as the result,
// then we first copy its contents and use that instead while formatting.
UnicodeString resultCopy;
if (getArgumentLimit(cp, cpLength) > 0) {
for (int32_t i = 1; i < cpLength;) {
int32_t n = cp[i++];
if (n < ARG_NUM_LIMIT) {
if (values[n] == &result) {
if (i == 2) {
firstArg = n;
} else if (resultCopy.isEmpty() && !result.isEmpty()) {
resultCopy = result;
}
}
} else {
i += n - ARG_NUM_LIMIT;
}
}
}
if (firstArg < 0) {
result.remove();
}
return format(cp, cpLength, values,
result, &resultCopy, FALSE,
offsets, offsetsLength, errorCode);
}
UnicodeString SimpleFormatter::getTextWithNoArguments(
const UChar *compiledPattern,
int32_t compiledPatternLength,
int32_t* offsets,
int32_t offsetsLength) {
for (int32_t i = 0; i < offsetsLength; i++) {
offsets[i] = -1;
}
int32_t capacity = compiledPatternLength - 1 -
getArgumentLimit(compiledPattern, compiledPatternLength);
UnicodeString sb(capacity, 0, 0); // Java: StringBuilder
for (int32_t i = 1; i < compiledPatternLength;) {
int32_t n = compiledPattern[i++];
if (n > ARG_NUM_LIMIT) {
n -= ARG_NUM_LIMIT;
sb.append(compiledPattern + i, n);
i += n;
} else if (n < offsetsLength) {
// TODO(ICU-20406): This does not distinguish between "{0}{1}" and "{1}{0}".
// Consider removing this function and replacing it with an iterator interface.
offsets[n] = sb.length();
}
}
return sb;
}
UnicodeString &SimpleFormatter::format(
const UChar *compiledPattern, int32_t compiledPatternLength,
const UnicodeString *const *values,
UnicodeString &result, const UnicodeString *resultCopy, UBool forbidResultAsValue,
int32_t *offsets, int32_t offsetsLength,
UErrorCode &errorCode) {
if (U_FAILURE(errorCode)) {
return result;
}
for (int32_t i = 0; i < offsetsLength; i++) {
offsets[i] = -1;
}
for (int32_t i = 1; i < compiledPatternLength;) {
int32_t n = compiledPattern[i++];
if (n < ARG_NUM_LIMIT) {
const UnicodeString *value = values[n];
if (value == NULL) {
errorCode = U_ILLEGAL_ARGUMENT_ERROR;
return result;
}
if (value == &result) {
if (forbidResultAsValue) {
errorCode = U_ILLEGAL_ARGUMENT_ERROR;
return result;
}
if (i == 2) {
// We are appending to result which is also the first value object.
if (n < offsetsLength) {
offsets[n] = 0;
}
} else {
if (n < offsetsLength) {
offsets[n] = result.length();
}
result.append(*resultCopy);
}
} else {
if (n < offsetsLength) {
offsets[n] = result.length();
}
result.append(*value);
}
} else {
int32_t length = n - ARG_NUM_LIMIT;
result.append(compiledPattern + i, length);
i += length;
}
}
return result;
}
U_NAMESPACE_END
| [
"hrncirmirek@outlook.com"
] | hrncirmirek@outlook.com |
355fb36ac25fb1c5292dbfe146a98a4acb94e1a2 | 8b59552ce92fab023f5efb462a12a3616bb44464 | /RemoteControl/RemoteControlView.cpp | 1949468eef60359b2b8b83019c5c91e0e38378ca | [] | no_license | 0x6666/RemoteControl | bbdb8a7f7507bbf305ee5d439f0926ad6f89adba | 08d9330534a1d8fa73d7f98209ceb681db374a6e | refs/heads/master | 2021-06-12T15:29:59.614740 | 2015-05-03T14:13:43 | 2015-05-03T14:13:43 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 10,434 | cpp | ///////////////////////////////////////////////////////////////
//
// FileName : RemoteControlView.cpp
// Creator : 杨松
// Date : 2013年2月27日, 20:10:26
// Comment : 远控控制服务器文档视图结构中的视图类的实现
//
//////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "RemoteControl.h"
#include "RemoteControlDoc.h"
#include "RemoteControlView.h"
#include "clientItemView.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CRemoteControlView
IMPLEMENT_DYNCREATE(CRemoteControlView, CView)
BEGIN_MESSAGE_MAP(CRemoteControlView, CView)
ON_WM_SIZE()
ON_MESSAGE(WM_ITEM_VIEW_SBCLICK , OnItemViewDBClick)
ON_MESSAGE(WM_FULLS_CREEN , OnFullScreen)
ON_MESSAGE(WM_MONITORINT_CLIENT , OnStopMonitoringClient)
ON_WM_NCCALCSIZE()
ON_WM_VSCROLL()
ON_WM_MOVE()
END_MESSAGE_MAP()
// CRemoteControlView 构造/析构
CRemoteControlView::CRemoteControlView()
/*_APS_NEXT_CONTROL_VALUE是编译器生成的下一个控件的ID
因为客户端视图是动态创建,需要ID且不能重复,所以在这里
将m_iLastClientID设置为_APS_NEXT_CONTROL_VALUE的值(动
态设置,每次添加或者删除了控件后手动设置)
*/
: m_iLastClientID(1037)
, m_pFullViewItem(NULL)
, m_curRowIndex(0)
, m_iRowCount(2) //2
, m_iColumnCount(3) //3
{
// TODO: 在此处添加构造代码
}
CRemoteControlView::~CRemoteControlView()
{
}
BOOL CRemoteControlView::PreCreateWindow(CREATESTRUCT& cs)
{
// TODO: 在此处通过修改
// CREATESTRUCT cs 来修改窗口类或样式
return CView::PreCreateWindow(cs);
}
// CRemoteControlView 绘制
void CRemoteControlView::OnDraw(CDC* /*pDC*/)
{
CRemoteControlDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
if (!pDoc)
return;
// TODO: 在此处为本机数据添加绘制代码
}
// CRemoteControlView 诊断
#ifdef _DEBUG
void CRemoteControlView::AssertValid() const
{
CView::AssertValid();
}
void CRemoteControlView::Dump(CDumpContext& dc) const
{
CView::Dump(dc);
}
CRemoteControlDoc* CRemoteControlView::GetDocument() const // 非调试版本是内联的
{
ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CRemoteControlDoc)));
return (CRemoteControlDoc*)m_pDocument;
}
#endif //_DEBUG
BOOL CRemoteControlView::AddNewClient( PClientDescripter clientDes )
{
if (NULL == clientDes)
return FALSE;//貌似参数有问题
for (ClientViewList::iterator it = m_lstClient.begin()
; it != m_lstClient.end() ; ++it)
{
if ((*it)->GetClientIP() == clientDes->mIP)//客户端已经存在了
return FALSE;
}
ClientItemView* item = new ClientItemView( clientDes/*name , strIP , port */, GetDocument());
if(FALSE == item->Create( this , ++m_iLastClientID ))
{//创建失败
delete item;
--m_iLastClientID;
return FALSE;
}
else
{//创建成功
m_lstClient.push_back(item);
AdjustItemViewPosition(FALSE);
//调整滚动条的滚动范围
AdjustScrollSize();
}
return TRUE;
}
// CRemoteControlView 消息处理程序
void CRemoteControlView::OnSize(UINT nType, int cx, int cy)
{
CView::OnSize(nType, cx, cy);
AdjustItemViewPosition();
}
void CRemoteControlView::DispatchMsg( const CString& ip, USHORT port, const void* msg )
{
//将消息派送派送到指定的客户端视图
ClientViewList::iterator it = m_lstClient.begin();
for ( ; it != m_lstClient.end() ; ++it )
{
if ((*it)->GetClientIP() == ip)
{
(*it)->OnRcMessage( port, msg );
return ;
}
}
}
LRESULT CRemoteControlView::OnItemViewDBClick( WPARAM wParam , LPARAM lParam )
{
ASSERT(wParam != NULL);
CString ip = *((CString*)wParam);
if(!IsWindow(m_pFullViewItem->GetSafeHwnd()))
m_pFullViewItem = NULL;
if ((NULL != m_pFullViewItem) && (m_pFullViewItem->GetClientIP() == ip))
{//已经是full view了,那就重新排列
m_pFullViewItem->SetDrawEdge(TRUE);
m_pFullViewItem = NULL;
AdjustItemViewPosition(FALSE);
}else
{//设置full view
for ( ClientViewList::iterator it = m_lstClient.begin() ;
it != m_lstClient.end() ; ++it )
{
if ((*it)->GetClientIP() == ip)
{
m_pFullViewItem = *it;
m_pFullViewItem->SetDrawEdge(FALSE);
CRect rc;
GetClientRect(&rc);
m_pFullViewItem->MoveWindow(0 , 0 , rc.Width() , rc.Height() , TRUE);
m_pFullViewItem->ShowWindow(SW_SHOW);
//m_pFullViewItem->SetWindowPos(NULL , 0 , 0 , rc.Width() , rc.Height() , SWP_SHOWWINDOW);
}else{
(*it)->ShowWindow(SW_HIDE);
}
}
}
//调整滚动范围
AdjustScrollSize();
Invalidate(TRUE);
return 0;
}
void CRemoteControlView::AdjustItemViewPosition(BOOL keepFull /*= TRUE*/)
{
if (keepFull && m_pFullViewItem)
{//保持原有的fullView
//先调整滚动范围
AdjustScrollSize();
CRect rc;
GetClientRect(&rc);
m_pFullViewItem->SetWindowPos(NULL , 0 , 0 , rc.Width() , rc.Height() , SWP_SHOWWINDOW);
}
else
{//不需要保持原有的fullView
if (NULL != m_pFullViewItem)
{//原来就是全屏的
m_pFullViewItem->SetDrawEdge(TRUE);
m_pFullViewItem = NULL;
}
ClientViewList::iterator it = m_lstClient.begin();
int height = 0;
int width = 0;
GetItenSize( width , height);
int i = 0;
//先跳过前面隐藏的
for ( i = 0 ; it != m_lstClient.end() &&
(i < m_curRowIndex * m_iColumnCount) ; ++it , ++i)
{//可以显示的就调整一下位置
(*it)->ShowWindow(SW_HIDE);
}
for ( i = 0 ; it != m_lstClient.end() &&
(i != (m_iRowCount * m_iColumnCount)) ;
++it , ++i )
{//可以显示的就调整一下位置
(*it)->MoveWindow((i % m_iColumnCount) * width ,
(/*(*/i / m_iColumnCount/*) / m_iRowCount*/) * height ,
width , height ,TRUE);
(*it)->ShowWindow(SW_SHOW);
}
//后面的也不需要显示了
for ( ; it != m_lstClient.end() ; ++it )
{//可以显示的就调整一下位置
(*it)->ShowWindow(SW_HIDE);
}
//先调整滚动范围
AdjustScrollSize();
}
}
void CRemoteControlView::DestroyView()
{
for (ClientViewList::iterator it = m_lstClient.begin() ; it != m_lstClient.end() ; ++it)
{
ClientItemView* pView = *it;
pView->DestroyWindow();
delete pView;
// it = m_lstClient.begin();
}
m_lstClient.clear();
}
void CRemoteControlView::ClientDropped( const CString& ip )
{
for(ClientViewList::iterator it = m_lstClient.begin() ; it != m_lstClient.end() ; ++it)
{
if ((*it)->GetClientIP() == ip)
{//找到了制定的客户端视图
(*it)->Dropped();
break;
}
}
}
LRESULT CRemoteControlView::OnStopMonitoringClient( WPARAM wParam , LPARAM lParam )
{
CString strIP = *((CString*)wParam);
CRemoteControlDoc* pDoc = GetDocument();
pDoc->StopMonitoring(strIP);
//从客户端视图链表中删除指定的客户端
for(ClientViewList::iterator it = m_lstClient.begin() ; it != m_lstClient.end() ; ++it)
{
if ((*it)->GetClientIP() == strIP)
{//找到了制定的客户端视图
ClientItemView* view = *it;
if (m_pFullViewItem == view)
{//是全屏的
m_pFullViewItem = NULL;
}
view->DestroyWindow();
delete view;
m_lstClient.remove(view);
break;
}
}
if ((0 != m_curRowIndex) && (GetRowCount() - m_curRowIndex) < m_iRowCount)
{//有隐藏但是当前显示区域没有填满
--m_curRowIndex;
SetScrollPos(SB_VERT , m_curRowIndex , TRUE);
}
//调整各个视图的位置
AdjustItemViewPosition(FALSE);
return 0;
}
LRESULT CRemoteControlView::OnFullScreen( WPARAM wParam , LPARAM lParam )
{
ASSERT(wParam != NULL);
CString ip = *((CString*)wParam);
if ((NULL != m_pFullViewItem) && (m_pFullViewItem->GetClientIP() == ip))
{//已经是full view了
return 0;
}else
{//设置full view
for ( ClientViewList::iterator it = m_lstClient.begin() ;
it != m_lstClient.end() ; ++it )
{
if ((*it)->GetClientIP() == ip)
{
m_pFullViewItem = *it;
m_pFullViewItem->SetDrawEdge(FALSE);
CRect rc;
GetClientRect(&rc);
m_pFullViewItem->MoveWindow(0 , 0 , rc.Width() , rc.Height() , TRUE);
m_pFullViewItem->ShowWindow(SW_SHOW);
//m_pFullViewItem->SetWindowPos(NULL , 0 , 0 , rc.Width() , rc.Height() , SWP_SHOWWINDOW);
}
else
{//其他的不需要显示的都隐藏
(*it)->ShowWindow(SW_HIDE);
}
}
}
Invalidate(TRUE);
return 0;
}
void CRemoteControlView::OnInitialUpdate()
{
CView::OnInitialUpdate();
SCROLLINFO si = {0};
si.cbSize = sizeof(SCROLLINFO);
si.fMask = SIF_PAGE ;
si.nPage = 1;
SetScrollInfo(SB_VERT , &si , TRUE);
}
void CRemoteControlView::AdjustScrollSize()
{
if (NULL != m_pFullViewItem)
{//全屏时需要隐藏滚动条
ShowScrollBar(SB_VERT , FALSE);
}
else
{//非全屏
if((int)m_lstClient.size() > (m_iRowCount * m_iColumnCount))
{//需要显示滚动条
//计算滚动区域的大小
int rCnt = GetRowCount();
rCnt -= (m_iRowCount - 1);
SetScrollRange(SB_VERT , 0 , rCnt-1);
ShowScrollBar(SB_VERT , TRUE);
}
else
{//不需要显示滚动条
ShowScrollBar(SB_VERT , FALSE);
}
}
}
void CRemoteControlView::GetItenSize( int& w , int& h )
{
CRect rc;
GetClientRect(&rc);
h = rc.Height() / m_iRowCount;
w = rc.Width() / m_iColumnCount;
}
void CRemoteControlView::OnVScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar)
{
// TODO: 在此添加消息处理程序代码和/或调用默认值
switch (nSBCode)
{
case SB_BOTTOM:
case SB_TOP:
case SB_ENDSCROLL:
break;
case SB_LINEDOWN:
case SB_PAGEDOWN:
{
int rCnt = GetRowCount();//行数
if (rCnt > m_curRowIndex + 1)
{//还可以下滚
++m_curRowIndex;
AdjustItemViewPosition(TRUE);
SetScrollPos(SB_VERT , m_curRowIndex , TRUE);
}
}
break;
case SB_LINEUP:
case SB_PAGEUP:
{
if (0 < m_curRowIndex )
{//还可以下滚
--m_curRowIndex;
AdjustItemViewPosition(TRUE);
SetScrollPos(SB_VERT , m_curRowIndex , TRUE);
}
}
break;
case SB_THUMBPOSITION:
break;
case SB_THUMBTRACK:
{//拖动到制定位置
if (m_curRowIndex != nPos)
{//位置有调整
m_curRowIndex = nPos;
AdjustItemViewPosition(TRUE);
SetScrollPos(SB_VERT , m_curRowIndex , TRUE);
}
}
break;
default:
ASSERT(FALSE);
}
CView::OnVScroll(nSBCode, nPos, pScrollBar);
}
int CRemoteControlView::GetRowCount()
{
int rCnt = m_lstClient.size();
rCnt = (rCnt / m_iRowCount) + ((rCnt % m_iRowCount)? 1 : 0);
return rCnt;
}
void CRemoteControlView::OnMove(int x, int y)
{
CView::OnMove(x, y);
for (ClientViewList::iterator it = m_lstClient.begin() ; it != m_lstClient.end(); ++it)
{
(*it)->PostMessage(WM_MOVE , 0 , 0);
}
}
| [
"yangsongfwd@sina.com"
] | yangsongfwd@sina.com |
cc140bfb72092d443e89dcb5eda7761848b64fce | 2b45998c5472e30ea7058603bca3a77700b86b70 | /실패작 개똥벌레.cpp | e563801434de367dbf8c850235ef3f149f04619e | [] | no_license | forybm/CodeMountain | c6b5e404bc5947f2a41df76331bb1ba078dcbe41 | 7a3c8bc76db7f57ad68638f800513d0ea0a7c5a2 | refs/heads/master | 2021-06-21T15:05:30.653346 | 2017-07-27T06:03:55 | 2017-07-27T06:03:55 | 98,499,311 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 788 | cpp | #include <stdio.h>
#include <algorithm>
using namespace std;
int H[500000]={0};
int main()
{
int length,high; //동굴의 길이, 동굴의 높이
int n[200000]; //종유석 갯
scanf("%d%d",&length,&high);
for(int i=1;i<=length;i++)
{
scanf("%d",&n[i]);
}
for(int i=1;i<=length;i++)
{
if(i%2==0) //짝수번째 종유석은 위세어 아래로
{
for(int j=high;j>=1;j--)
{
H[j]++;
n[i]--;
if(n[i]==0) break;
}
}
else if(i%2==1) //홀수번째 종유석은 아래에서 위
{
for(int j=1;j<=high;j++)
{
H[j]++;
n[i]--;
if(n[i]==0) break;
}
}
}
int count=0;
sort(H+1,H+high+1);
for(int i=1;i<=high;i++)
{
if(H[1]==H[i]) count++;
else if(H[i]>H[1]) break;
}
printf("%d %d",H[1],count);
}
| [
"forybm1@naver.com"
] | forybm1@naver.com |
7eb155845bd7602ff96c60bfbf4e3f5a8af43255 | c5fb286e9adb0132f87ffecd0091f71a9907c197 | /ext/aip/src/lib/aptl/memory/BaseArena.h | c1e3125a2e0086761afeb9e5ca9973867ef2695f | [
"Apache-2.0"
] | permissive | sovaai/sova-engine | 2dc00ca554fd464cc2fd693c02c8de4acb4dcc5c | 783b04072bb243891bc332fcb0f61e938e456f4f | refs/heads/master | 2022-12-31T20:32:14.158432 | 2020-10-28T19:07:39 | 2020-10-28T19:07:39 | 289,885,115 | 50 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 11,581 | h | #ifndef _BASEARENA_H_
#define _BASEARENA_H_
#include <assert.h>
#include <stdlib.h>
#include <_include/cc_compat.h>
#include <_include/_string.h>
namespace Arena
{
struct DefaultPolicy
{
static const size_t defaultBlockSize = 8UL * 1024 * 1024;
};
template< typename MemberType >
struct BaseSetMember : public MemberType
{
BaseSetMember() : MemberType() { }
BaseSetMember *next;
BaseSetMember **pPrev;
};
template< typename Policy, typename MemberType >
class BaseSet
{
typedef typename Policy::StatusType StatusType;
public:
BaseSet() : first( 0 ) { }
StatusType initialize() { first = 0; return Policy::statusSuccess; }
StatusType add( MemberType &item )
{
item.next = first;
if ( !isEmpty() )
first->pPrev = &item.next;
first = &item;
item.pPrev = &first;
return Policy::statusSuccess;
}
MemberType *getFirst() { return first; }
MemberType *getNext( MemberType *item ) { return item->next; }
void remove( MemberType &item )
{
if ( item.next != 0 )
item.next->pPrev = item.pPrev;
*item.pPrev = item.next;
}
bool isEmpty() const { return first == 0; }
protected:
MemberType *first;
};
struct Block
{
volatile uint8_t *area;
};
template< typename Policy, typename BlockType, typename BlocksSetType >
class BaseAreaEngine
{
typedef typename Policy::StatusType StatusType;
public:
typedef BlockType AreaBlockType;
public:
BaseAreaEngine() : blockSize( Policy::defaultBlockSize ) { }
StatusType create( size_t blockSize, BlocksSetType &/* blocks */ )
{
this->blockSize = blockSize;
return Policy::statusSuccess;
}
bool notEnoughSpace( size_t offset, size_t amount ) { return offset + amount > blockSize; }
StatusType allocBlock( BlockType *&block )
{
size_t sizeToAlloc = ( blockSize + sizeof( BlockType ) + 0xF ) & ( ~(static_cast<size_t>( 0xF )) );
block = reinterpret_cast<BlockType *>( ::malloc( sizeToAlloc ) );
if ( unlikely(block == 0) )
return Policy::statusErrorAlloc;
block->area = reinterpret_cast<uint8_t *>( block ) + sizeToAlloc - blockSize;
return Policy::statusSuccess;
}
StatusType allocInBlock( BlockType *activeBlock, uint8_t *&area, size_t &offset, size_t amount )
{
area = (uint8_t *)( activeBlock->area ) + offset;
offset += amount;
return Policy::statusSuccess;
}
StatusType shrink( BlocksSetType &set, size_t &offset, uint8_t *area, size_t areaSize, size_t shrinkAreaSize )
{
if ( areaSize == shrinkAreaSize )
return Policy::statusSuccess;
if ( unlikely(set.isEmpty() || ( areaSize < shrinkAreaSize )) )
return Policy::statusErrorInvalidArg;
BlockType *activeBlock = set.getFirst();
if ( unlikely(( area + areaSize ) != ( activeBlock->area + offset )) )
return Policy::statusErrorInvalidArg;
offset -= ( areaSize - shrinkAreaSize );
return Policy::statusSuccess;
}
StatusType addBlockToSet( BlockType &block, BlocksSetType &set ) { return set.add( block ); }
StatusType destroyBlock( BlockType *block )
{
::free( block );
return Policy::statusSuccess;
}
StatusType freeBlock( BlockType *block, BlocksSetType &set )
{
set.remove( *block );
return destroyBlock( block, set );
}
StatusType rewind( size_t &offset )
{
offset = 0;
return Policy::statusSuccess;
}
static size_t allocationCostBytes() { return 0; }
protected:
size_t blockSize;
};
template< typename Policy, typename BlockType, typename BlocksSetType >
class BaseAreaEngineWithReuse : public BaseAreaEngine< Policy, BlockType, BlocksSetType >
{
typedef BaseAreaEngine< Policy, BlockType, BlocksSetType > Base;
typedef typename Policy::StatusType StatusType;
public:
BaseAreaEngineWithReuse() : Base(), freeBlocks() { }
~BaseAreaEngineWithReuse()
{
while ( !freeBlocks.isEmpty() )
{
BlockType *block = freeBlocks.getFirst();
freeBlocks.remove( *block );
Base::destroyBlock( block );
}
}
StatusType create( size_t blockSize, BlocksSetType &blocks )
{
StatusType status = Base::create( blockSize, blocks );
if ( unlikely(status != Policy::statusSuccess) )
return status;
return freeBlocks.initialize();
}
StatusType allocBlock( BlockType *&block )
{
if ( freeBlocks.isEmpty() )
return Base::allocBlock( block );
block = freeBlocks.getFirst();
freeBlocks.remove( *block );
return Policy::statusSuccess;
}
StatusType freeBlock( BlockType *block, BlocksSetType &set )
{
set.remove( *block );
return freeBlocks.add( *block );
}
protected:
BlocksSetType freeBlocks;
};
template< typename Policy, typename BlockType, typename BlocksSetType, typename AreaEngine >
class BaseArea : public AreaEngine
{
typedef typename Policy::StatusType StatusType;
public:
BaseArea() :
AreaEngine(),
blocks(),
offset( 0 )
{
}
~BaseArea()
{
while ( !blocks.isEmpty() )
{
BlockType *block = blocks.getFirst();
blocks.remove( *block );
AreaEngine::destroyBlock( block );
}
}
StatusType create( size_t blockSize )
{
StatusType status = AreaEngine::create( blockSize, blocks );
if ( unlikely(status != Policy::statusSuccess) )
return status;
offset = 0;
return blocks.initialize();
}
static size_t allocationCostBytes() { return AreaEngine::allocationCostBytes(); }
template< typename T >
StatusType alloc( T *&ptr, size_t amount = sizeof( T ) )
{
uint8_t *tmpArea;
StatusType status = allocGeneric( tmpArea, amount );
if ( unlikely(status != Policy::statusSuccess) )
return status;
ptr = reinterpret_cast<T *>( tmpArea );
return Policy::statusSuccess;
}
StatusType allocGeneric( uint8_t *&area, size_t amount )
{
if ( unlikely(amount > AreaEngine::blockSize) )
return Policy::statusErrorSmallBlock;
area = 0;
if ( blocks.isEmpty() || AreaEngine::notEnoughSpace( offset, amount ) )
{
BlockType *block;
StatusType status = AreaEngine::allocBlock( block );
if ( unlikely(status != Policy::statusSuccess) )
return status;
status = AreaEngine::addBlockToSet( *block, blocks );
if ( unlikely(status != Policy::statusSuccess) )
return status;
status = AreaEngine::rewind( offset );
if ( unlikely(status != Policy::statusSuccess) )
return status;
}
return AreaEngine::allocInBlock( blocks.getFirst(), area, offset, amount );
}
StatusType freeAll()
{
while ( !blocks.isEmpty() )
{
StatusType status = AreaEngine::freeBlock( blocks.getFirst(), blocks );
if ( unlikely(status != Policy::statusSuccess) )
return status;
}
return Policy::statusSuccess;
}
StatusType shrink( uint8_t *area, size_t areaSize, size_t shrinkAreaSize )
{
return AreaEngine::shrink( blocks, offset, area, areaSize, shrinkAreaSize );
}
StatusType rewind() { return AreaEngine::rewind( offset ); }
protected:
BlocksSetType blocks;
size_t offset;
};
template< typename Policy, typename AreaType, typename AreasSetType >
class BaseArenaEngine
{
typedef typename Policy::StatusType StatusType;
public:
StatusType create() { return Policy::statusSuccess; }
StatusType allocArea( AreaType *&area )
{
area = new AreaType;
if ( unlikely(area == 0) )
return Policy::statusErrorAlloc;
return Policy::statusSuccess;
}
StatusType freeArea( AreaType *area )
{
delete area;
return Policy::statusSuccess;
}
};
template< typename Policy, typename AreaType, typename AreasSetType, typename ArenaEngine >
class BaseArena : public ArenaEngine
{
typedef typename Policy::StatusType StatusType;
public:
typedef AreaType Area;
public:
BaseArena() :
ArenaEngine(),
areas(),
isCreated( false )
{
}
~BaseArena()
{
while ( !areas.isEmpty() )
{
Area *area = areas.getFirst();
areas.remove( *area );
ArenaEngine::freeArea( area );
}
}
StatusType create()
{
if ( unlikely(isCreated) )
return Policy::statusErrorAlreadyCreated;
StatusType status = areas.initialize();
if ( unlikely(status != Policy::statusSuccess) )
return status;
status = ArenaEngine::create();
if ( unlikely(status != Policy::statusSuccess) )
return status;
isCreated = true;
return Policy::statusSuccess;
}
StatusType makeArea( Area *&area, size_t blockSize = Policy::defaultBlockSize )
{
if ( unlikely(!isCreated) )
return Policy::statusErrorNotCreated;
StatusType status = ArenaEngine::allocArea( area );
if ( unlikely(status != Policy::statusSuccess) )
return status;
status = area->create( blockSize );
if ( unlikely(status != Policy::statusSuccess) )
{
ArenaEngine::freeArea( area );
return status;
}
status = areas.add( *area );
if ( unlikely(status != Policy::statusSuccess) )
{
ArenaEngine::freeArea( area );
return status;
}
return Policy::statusSuccess;
}
protected:
AreasSetType areas;
bool isCreated;
};
}
#endif /* _BASEARENA_H_ */
| [
"fedor.zorky@gmail.com"
] | fedor.zorky@gmail.com |
cc6946f0915aa96352d543d8ceac5e5067e33945 | 4feaaccdbd7359309f348a066ade183c2994449f | /strategy/strategy.cpp | 6d3bcce7c5bd78c5c7153a42443d6556bc1d637b | [] | no_license | sirjofri/patterns | 8c0d07fb0750c09008853f0c9093c087fe1411a2 | be0908a9ce0c0709ec844fd4a346e04d7d8e5aae | refs/heads/master | 2020-03-08T09:22:49.373068 | 2018-04-04T11:22:51 | 2018-04-04T11:22:51 | 128,045,716 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,206 | cpp | #include "strategy.h"
#include <iostream>
#include <sstream>
std::string Strategy::getStr(std::string in)
{
return "No Strategy!";
}
int Strategy::str()
{
return -1;
}
std::string AStrategy::getStr(std::string in)
{
std::ostringstream ret;
ret << "Strategy A: " << in << ":";
return ret.str();
}
int AStrategy::str()
{
return 1;
}
std::string BStrategy::getStr(std::string in)
{
std::ostringstream ret;
ret << "Strategy B: " << in << ":";
return ret.str();
}
int BStrategy::str()
{
return 2;
}
Entity::Entity(Strategy *s)
: strategy(s)
{}
std::string Entity::getStrategy()
{
std::ostringstream ret;
ret << "Current Strategy: " << strategy->getStr("Test String");
return ret.str();
}
int Entity::str()
{
return strategy->str();
}
int main(int argc, char **argv)
{
Strategy *a_str = new AStrategy();
Strategy *b_str = new BStrategy();
Entity *e_a = new Entity(a_str);
Entity *e_b = new Entity(b_str);
std::cout << "Entity with Strategy A:\n\t" << e_a->getStrategy() << std::endl;
std::cout << "Entity with Strategy B:\n\t" << e_b->getStrategy() << std::endl;
int e_a_str = e_a->str();
int e_b_str = e_b->str();
if(e_a_str != 1 && e_b_str != 2)
return 1;
return 0;
}
| [
"sirjofri@gmx.de"
] | sirjofri@gmx.de |
998f09f75e090e68113e7c20f007c1f8c7be75da | 49b05e95d9003b7f1f4f66620c3e051a27648d91 | /Applications/Terminal/Terminal.h | 82d13a546f8d70bff9c4f449119dfd16727b8972 | [
"BSD-2-Clause"
] | permissive | ygorko/serenity | 8f1d25b8d48465c9353c585b64e4e089c3434bbf | ccc6e69a294edacf7bec77cb2c2640ada7fe1f77 | refs/heads/master | 2020-05-31T03:40:53.063797 | 2019-06-03T17:52:31 | 2019-06-03T19:17:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,652 | h | #pragma once
#include <AK/AKString.h>
#include <AK/Types.h>
#include <AK/Vector.h>
#include <LibCore/CConfigFile.h>
#include <LibCore/CNotifier.h>
#include <LibCore/CTimer.h>
#include <LibGUI/GFrame.h>
#include <SharedGraphics/GraphicsBitmap.h>
#include <SharedGraphics/Rect.h>
class Font;
class Terminal final : public GFrame {
public:
explicit Terminal(int ptm_fd, RetainPtr<CConfigFile> config);
virtual ~Terminal() override;
void create_window();
void on_char(byte);
void flush_dirty_lines();
void force_repaint();
void apply_size_increments_to_window(GWindow&);
void set_opacity(float);
float opacity() { return m_opacity; };
bool should_beep() { return m_should_beep; }
void set_should_beep(bool sb) { m_should_beep = sb; };
RetainPtr<CConfigFile> config() const { return m_config; }
private:
typedef Vector<unsigned, 4> ParamVector;
virtual void event(CEvent&) override;
virtual void paint_event(GPaintEvent&) override;
virtual void resize_event(GResizeEvent&) override;
virtual void keydown_event(GKeyEvent&) override;
virtual const char* class_name() const override { return "Terminal"; }
void scroll_up();
void scroll_down();
void newline();
void set_cursor(unsigned row, unsigned column);
void put_character_at(unsigned row, unsigned column, byte ch);
void invalidate_cursor();
void set_window_title(const String&);
void inject_string(const String&);
void unimplemented_escape();
void unimplemented_xterm_escape();
void escape$A(const ParamVector&);
void escape$B(const ParamVector&);
void escape$C(const ParamVector&);
void escape$D(const ParamVector&);
void escape$H(const ParamVector&);
void escape$J(const ParamVector&);
void escape$K(const ParamVector&);
void escape$M(const ParamVector&);
void escape$G(const ParamVector&);
void escape$X(const ParamVector&);
void escape$d(const ParamVector&);
void escape$m(const ParamVector&);
void escape$s(const ParamVector&);
void escape$u(const ParamVector&);
void escape$t(const ParamVector&);
void escape$r(const ParamVector&);
void escape$S(const ParamVector&);
void escape$T(const ParamVector&);
void escape$L(const ParamVector&);
void escape$h_l(bool, bool, const ParamVector&);
void clear();
void set_size(word columns, word rows);
word columns() const { return m_columns; }
word rows() const { return m_rows; }
Rect glyph_rect(word row, word column);
Rect row_rect(word row);
void update_cursor();
struct Attribute {
Attribute() { reset(); }
static byte default_foreground_color;
static byte default_background_color;
void reset()
{
foreground_color = default_foreground_color;
background_color = default_background_color;
flags = Flags::NoAttributes;
}
byte foreground_color;
byte background_color;
enum Flags
{
NoAttributes = 0x00,
Bold = 0x01,
Italic = 0x02,
Underline = 0x04,
Negative = 0x08,
Blink = 0x10,
};
// TODO: it would be really nice if we had a helper for enums that
// exposed bit ops for class enums...
int flags = Flags::NoAttributes;
bool operator==(const Attribute& other) const
{
return foreground_color == other.foreground_color && background_color == other.background_color && flags == other.flags;
}
bool operator!=(const Attribute& other) const
{
return !(*this == other);
}
};
struct Line {
explicit Line(word columns);
~Line();
void clear(Attribute);
bool has_only_one_background_color() const;
byte* characters { nullptr };
Attribute* attributes { nullptr };
bool dirty { false };
word length { 0 };
};
Line& line(size_t index)
{
ASSERT(index < m_rows);
return *m_lines[index];
}
Vector<OwnPtr<Line>> m_lines;
int m_scroll_region_top { 0 };
int m_scroll_region_bottom { 0 };
word m_columns { 0 };
word m_rows { 0 };
byte m_cursor_row { 0 };
byte m_cursor_column { 0 };
byte m_saved_cursor_row { 0 };
byte m_saved_cursor_column { 0 };
bool m_stomp { false };
bool m_should_beep { false };
Attribute m_current_attribute;
void execute_escape_sequence(byte final);
void execute_xterm_command();
enum EscapeState
{
Normal,
ExpectBracket,
ExpectParameter,
ExpectIntermediate,
ExpectFinal,
ExpectXtermParameter1,
ExpectXtermParameter2,
ExpectXtermFinal,
};
EscapeState m_escape_state { Normal };
Vector<byte> m_parameters;
Vector<byte> m_intermediates;
Vector<byte> m_xterm_param1;
Vector<byte> m_xterm_param2;
byte m_final { 0 };
byte* m_horizontal_tabs { nullptr };
bool m_belling { false };
int m_pixel_width { 0 };
int m_pixel_height { 0 };
int m_inset { 2 };
int m_line_spacing { 4 };
int m_line_height { 0 };
int m_ptm_fd { -1 };
bool m_swallow_current { false };
bool m_in_active_window { false };
bool m_need_full_flush { false };
CNotifier m_notifier;
float m_opacity { 1 };
bool m_needs_background_fill { true };
bool m_cursor_blink_state { true };
int m_glyph_width { 0 };
CTimer m_cursor_blink_timer;
CTimer m_visual_beep_timer;
RetainPtr<CConfigFile> m_config;
};
| [
"awesomekling@gmail.com"
] | awesomekling@gmail.com |
03132ecf0ea8c074928ddfedc34853f11d17826a | 78f38f9968e1b8d31e1969c26f7b5588118ec085 | /AdventOfCode2016/AdventOfCode2016/AOC_23/AOC_23.cpp | a8b83bbd30f30b0221369c1001ff09dc502c6529 | [] | no_license | RTwTools/AdventOfCode | dfb5368b9dc08a59f225f0707f39ea66cb4515de | 9f8bb65e2e973cc664995781d6d409c158c6c655 | refs/heads/master | 2020-06-12T22:13:36.175924 | 2018-12-23T18:50:09 | 2018-12-23T18:50:09 | 75,435,362 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,617 | cpp | #include "AOC_23.h"
AOC_23::AOC_23(std::string fileName) :
passReg(4, 0),
line(0)
{
//open input file
std::string input = readFile(fileName);
if (input == "") return;
//split string at '\n', split commands at ' '
std::vector<std::string> lines = splitString(input, '\n');
for (int i = 0; i < (int)lines.size(); i++)
commands.push_back(splitString(lines[i], ' '));
//execute commands
passReg[0] = 7;
for (;;)
{
if (line >= (int)commands.size()) break;
line += executeCommand(commands[line]);
}
std::cout << "--- Challenge 23 A ---" << std::endl;
std::cout << "The value in reg A is [" << passReg[0] << "]." << std::endl;
//reset all values for part B
passReg[1] = passReg[2] = passReg[3] = line = 0;
passReg[0] = 12;
//re-read commands because the new command 'tgl' changes the initial values
commands.clear();
for (int i = 0; i < (int)lines.size(); i++)
commands.push_back(splitString(lines[i], ' '));
for (;;)
{
if (line >= (int)commands.size()) break;
line += executeCommand(commands[line]);
}
std::cout << "--- Challenge 23 B ---" << std::endl;
std::cout << "The value in reg A is [" << passReg[0] << "]." << std::endl;
std::cout << std::endl;
}
int AOC_23::executeCommand(std::vector<std::string> command)
{
//optimization for my specific input
if (line == 4)
{
passReg[0] = passReg[1] * passReg[3];
passReg[2] = passReg[3] = 0;
line = 10;
return 0;
}
if (command[0] == "cpy")
{
if (isRegister(command[2]))
passReg[getRegIndex(command[2])] = getValue(command[1]);
}
else if (command[0] == "inc")
passReg[getRegIndex(command[1])] += 1;
else if (command[0] == "dec")
passReg[getRegIndex(command[1])] -= 1;
else if (command[0] == "jnz")
{
int value = getValue(command[1]);
if (value != 0)
return (getValue(command[2]));
}
else if (command[0] == "tgl")
{
int commandID = getValue(command[1]) + line;
if (commandID >= 0 && commandID < (int)commands.size())
{
if (commands[commandID].size() == ONE_ARGUMENT)
commands[commandID][0] = (commands[commandID][0] == "inc") ? "dec" : "inc";
else if (commands[commandID].size() == TWO_ARGUMENTS)
commands[commandID][0] = (commands[commandID][0] == "jnz") ? "cpy" : "jnz";
}
}
else
std::cout << "invalid command: [" << command[0] << "]." << std::endl;
return 1;
}
int AOC_23::getValue(std::string str)
{
if (isRegister(str))
return passReg[getRegIndex(str)];
else
return std::stoi(str);
}
bool AOC_23::isRegister(std::string str)
{
return (str[0] >= 'a' && str[0] <= 'd');
}
int AOC_23::getRegIndex(std::string reg)
{
return (int)reg[0] - (int)'a';
} | [
"JeroenJacobs@Outlook.com"
] | JeroenJacobs@Outlook.com |
4ae5b93d68c44d5c4f9a9fbcb01c3f8459b2b053 | 2694b5757220afebf0a07cc2c14e487c81219654 | /450-DSA-Cracker/String/count-and-say.cpp | 8c760b8c4ff31c92c16bf56db01947ebdd7d06f6 | [] | no_license | sumitrathawani1810/Data-Structure-Algorithm | 64254e3116aad331b7e3019b5eebadf885bf9dc5 | 7ad452368e721c970f4b0ca9cde39d436bba2533 | refs/heads/main | 2023-08-31T20:26:23.648931 | 2021-10-23T04:07:39 | 2021-10-23T04:07:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,191 | cpp | #include<bits/stdc++.h>
using namespace std;
class Solution{
public:
string countAndSay(int n){
// We will check for 1 and 2 individually,
if(n==1)
return "1";
if(n==2)
return "11";
// Now for any entry greater than 2, we will :
string s="11";
for(int i =3;i<n;i++){
string t = "";
int c =1 ;
s = s + '&'; // This is a Delimiter
int len = s.length();
for(int j=1;j<len;j++)
{
if(s[j]!=s[j-1])
{
// If they're not equall,
// convert count to string n and add to t, n ewset count to 1
t=t+to_string(c);
t=t+s[j-1];
c=1;
}
else
// Count to see the number of characters aresmae
c++;
}
s=t;
}return s;
}
}asy;
int main(void)
{
int n;
cin >>n;
cout<<asy.countAndSay(n);
} | [
"iamlucif3r@localhost.localdomain"
] | iamlucif3r@localhost.localdomain |
0296c1524210d3ace54d4184939eaf0e1675ea76 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/git/gumtree/git_repos_function_4711_git-2.1.4.cpp | 008446ce15498fee9b8a68b786ccba945a3be1d3 | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 872 | cpp | static int git_clean_config(const char *var, const char *value, void *cb)
{
if (starts_with(var, "column."))
return git_column_config(var, value, "clean", &colopts);
/* honors the color.interactive* config variables which also
applied in git-add--interactive and git-stash */
if (!strcmp(var, "color.interactive")) {
clean_use_color = git_config_colorbool(var, value);
return 0;
}
if (starts_with(var, "color.interactive.")) {
int slot = parse_clean_color_slot(var +
strlen("color.interactive."));
if (slot < 0)
return 0;
if (!value)
return config_error_nonbool(var);
color_parse(value, var, clean_colors[slot]);
return 0;
}
if (!strcmp(var, "clean.requireforce")) {
force = !git_config_bool(var, value);
return 0;
}
/* inspect the color.ui config variable and others */
return git_color_default_config(var, value, cb);
} | [
"993273596@qq.com"
] | 993273596@qq.com |
7bbf92a4274078f823e2d125ce8cb7ce20f510bf | 4882847af716e5342f437569970795fe1fc9a853 | /Code/MUD/Implementations/mud/Game/Areas/Room.hpp | a3f558a1bd16a783961c3c5342a60dc91ec37cc6 | [] | no_license | Aslai/MUD | 059a40976cbd501265a5097e08a70ec8773bab01 | 86b3828fe343ee787f799d59b1d9f6ad2226a614 | refs/heads/master | 2020-06-06T15:46:33.822555 | 2014-10-13T02:06:07 | 2014-10-13T02:06:07 | 18,485,230 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,088 | hpp | //Be sure that Realm is defined in the case of a circular reference
#ifndef MUD_GAME_AREAS_ROOM_DEFINED
#define MUD_GAME_AREAS_ROOM_DEFINED
namespace MUD{
namespace Game{
class Room;
}
}
#endif // MUD_GAME_AREAS_REALM_DEFINED
#ifndef MUD_GAME_AREAS_ROOM_HPP
#define MUD_GAME_AREAS_ROOM_HPP
#include "Game/Areas/Zone.hpp"
#include "Game/Areas/Room.hpp"
#include "Lua/Lua.hpp"
#include "Game/Actors/Actor.hpp"
#include "Memory/RefCounter.hpp"
namespace MUD{
namespace Game{
class Room{
Zone& MyZone;
Lua::Value Properties;
std::string id;
std::vector<RefCounter<Actor>> Actors;
Lua::Script RoomScript;
public:
enum class Exit{
North = 0,
East,
South,
West,
Up,
Down,
NotAnExit
};
static Room& GetRoomByID( std::string RealmID, std::string ZoneID, std::string RoomID );
};
}
}
#endif
| [
"kaslai@kaslai.com"
] | kaslai@kaslai.com |
7bbeb7fa849d18319876dc16d1cb205919a6ff4b | 66c655a05d79ecfbc104b9b40a147c90b9efe242 | /Client/Store.cpp | 591ee9b431b701213d49fa686e8ae09e8a941545 | [] | no_license | a110b1110/MapleStory | 244cdb3a98aed43244341b1b815b86cd1b0c0f15 | 03d627fad6224ac41ac9d92a2243d1caa05a6b35 | refs/heads/master | 2021-01-01T06:29:04.838321 | 2017-08-15T09:10:24 | 2017-08-15T09:10:24 | 97,435,142 | 0 | 0 | null | 2017-07-17T04:26:52 | 2017-07-17T04:26:52 | null | UHC | C++ | false | false | 12,311 | cpp | #include "stdafx.h"
#include "Store.h"
#include "BitMapMgr.h"
#include "BitMap.h"
#include "ObjMgr.h"
#include "Mouse.h"
#include "KeyMgr.h"
//Item----------------------------
#include "Npc.h"
#include "Item.h"
#include "Armor.h"
#include "Glove.h"
#include "Accessory.h"
#include "Helmet.h"
#include "Shoes.h"
#include "Potion.h"
#include "Weapon.h"
//--------------------------------
typedef list<CItem*>::iterator ITEMITER;
CStore::CStore(void)
{
m_eUiType = UI_STORE;
ZeroMemory(&m_tEscButton_Rect, sizeof(RECT));
ZeroMemory(&m_tEscButton_Info, sizeof(INFO));
ZeroMemory(&m_tScroll_Rect, sizeof(RECT));
ZeroMemory(&m_tScroll_Info, sizeof(INFO));
m_pStore_Npc = NULL;
}
CStore::~CStore(void)
{
Release();
}
void CStore::Initialize(void)
{
m_tInfo.fx = 200.f;
m_tInfo.fy = 100.f;
m_tInfo.fcx = 508.f;
m_tInfo.fcy = 505.f;
//Esc Button
m_tEscButton_Info.fx = m_tInfo.fx + m_tInfo.fcx / 2.f;
m_tEscButton_Info.fy = m_tInfo.fy + 10.f;
m_tEscButton_Info.fcx = 9.f;
m_tEscButton_Info.fcy = 9.f;
//Scroll
m_tScroll_Info.fx = m_tInfo.fx + 258.f;
m_tScroll_Info.fy = m_tInfo.fy + 134.f;
m_tScroll_Info.fcx = 9.f;
m_tScroll_Info.fcy = 26.f;
#pragma region Item List
//Store Item
//----------------------------------------------------------------------------------
//Armor (Armor, Armor1)
CItem* pArmor = new CArmor(L"Armor");
((CArmor*)pArmor)->Initialize();
((CArmor*)pArmor)->SetArmor_Data(5, 5, 5, 5, 10, 5, 1000, 0);
pArmor->SetItemDescription(L"기본 갑옷");
m_Store_ItemList.push_back(pArmor);
pArmor = new CArmor(L"Armor1");
((CArmor*)pArmor)->Initialize();
((CArmor*)pArmor)->SetArmor_Data(10, 10, 10, 10, 15, 10, 2000, 1);
pArmor->SetItemDescription(L"고급 갑옷");
m_Store_ItemList.push_back(pArmor);
//----------------------------------------------------------------------------------
//Weapon (Weapon, Weapon1)
CItem* pWeapon = new CWeapon(L"Weapon");
((CWeapon*)pWeapon)->Initialize();
((CWeapon*)pWeapon)->SetWeapon_Data(10, 2, 2, 2, 0, 0, 1000, 2);
pWeapon->SetItemDescription(L"기본 무기");
m_Store_ItemList.push_back(pWeapon);
pWeapon = new CWeapon(L"Weapon1");
((CWeapon*)pWeapon)->Initialize();
((CWeapon*)pWeapon)->SetWeapon_Data(20, 4, 4, 4, 0, 0, 2000, 3);
pWeapon->SetItemDescription(L"고급 무기");
m_Store_ItemList.push_back(pWeapon);
//----------------------------------------------------------------------------------
//Glove (Glove, Glove1)
CItem* pGlove = new CGlove(L"Glove");
((CGlove*)pGlove)->Initialize();
((CGlove*)pGlove)->SetGlove_Data(2, 2, 2, 2, 5, 0, 500, 4);
pGlove->SetItemDescription(L"기본 장갑");
m_Store_ItemList.push_back(pGlove);
pGlove = new CGlove(L"Glove1");
((CGlove*)pGlove)->Initialize();
((CGlove*)pGlove)->SetGlove_Data(4, 4, 4, 4, 10, 0, 1000, 5);
pGlove->SetItemDescription(L"고급 장갑");
m_Store_ItemList.push_back(pGlove);
//----------------------------------------------------------------------------------
//Helmet
CItem* pHelmet = new CHelmet(L"Helmet");
((CHelmet*)pHelmet)->Initialize();
((CHelmet*)pHelmet)->SetHelmet_Data(4, 4, 4, 4, 5, 5, 500, 6);
pHelmet->SetItemDescription(L"투구");
m_Store_ItemList.push_back(pHelmet);
//----------------------------------------------------------------------------------
//Accessory
CItem* pAcs = new CAccessory(L"Accessory", ITEM_RING);
((CAccessory*)pAcs)->Initialize();
((CAccessory*)pAcs)->SetAccessory_Data(2, 2, 2, 2, 3, 3, 500, 7);
pAcs->SetItemDescription(L"메이플 반지");
m_Store_ItemList.push_back(pAcs);
pAcs = new CAccessory(L"Accessory1", ITEM_RING);
((CAccessory*)pAcs)->Initialize();
((CAccessory*)pAcs)->SetAccessory_Data(4, 4, 4, 4, 6, 6, 1000, 8);
pAcs->SetItemDescription(L"고급 반지");
m_Store_ItemList.push_back(pAcs);
//----------------------------------------------------------------------------------
//Shoes
CItem* pShoes = new CShoes(L"Shoes");
((CShoes*)pShoes)->Initialize();
((CShoes*)pShoes)->SetShoes_Data(2, 2, 2, 2, 0, 0, 500, 9);
pShoes->SetItemDescription(L"기본 신발");
m_Store_ItemList.push_back(pShoes);
pShoes = new CShoes(L"Shoes1");
((CShoes*)pShoes)->Initialize();
((CShoes*)pShoes)->SetShoes_Data(4, 4, 4, 4, 2, 2, 1000, 10);
pShoes->SetItemDescription(L"고급 신발");
m_Store_ItemList.push_back(pShoes);
//----------------------------------------------------------------------------------
//Potion
CItem* pPotion = new CPotion(L"Hp_Potion", ITEM_HP_POTION);
((CPotion*)pPotion)->Initialize();
((CPotion*)pPotion)->SetPotion_Data(0, 0, 0, 0, 1000, 0, 100, 11);
pPotion->SetItemDescription(L"생명력 포션");
m_Store_ItemList.push_back(pPotion);
pPotion = new CPotion(L"Mp_Potion", ITEM_MP_POTION);
((CPotion*)pPotion)->Initialize();
((CPotion*)pPotion)->SetPotion_Data(0, 0, 0, 0, 0, 1000, 100, 12);
pPotion->SetItemDescription(L"마나 포션");
m_Store_ItemList.push_back(pPotion);
//----------------------------------------------------------------------------------
float fx = 10.f;
float fy = 125.f;
int iIndex = 0;
ITEMITER iter = m_Store_ItemList.begin();
for (iter; iter != m_Store_ItemList.end(); ++iter, ++iIndex)
{
(*iter)->SetPos(m_tInfo.fx + fx, m_tInfo.fy + fy + (42.5f * iIndex));
}
#pragma endregion
m_eRenderType = RENDER_UI;
}
int CStore::Update(void)
{
//Button Rect
m_tEscButton_Rect.left = long(m_tEscButton_Info.fx + (m_tEscButton_Info.fcx / 2.f) - m_tEscButton_Info.fcx / 2);
m_tEscButton_Rect.right = long(m_tEscButton_Info.fx + (m_tEscButton_Info.fcx / 2.f) + m_tEscButton_Info.fcx / 2);
m_tEscButton_Rect.top = long(m_tEscButton_Info.fy + (m_tEscButton_Info.fcy / 2.f) - m_tEscButton_Info.fcy / 2);
m_tEscButton_Rect.bottom = long(m_tEscButton_Info.fy + (m_tEscButton_Info.fcy / 2.f) + m_tEscButton_Info.fcy / 2);
//Scroll Rect
m_tScroll_Rect.left = long(m_tScroll_Info.fx + (m_tScroll_Info.fcx / 2.f) - m_tScroll_Info.fcx / 2);
m_tScroll_Rect.right = long(m_tScroll_Info.fx + (m_tScroll_Info.fcx / 2.f) + m_tScroll_Info.fcx / 2);
m_tScroll_Rect.top = long(m_tScroll_Info.fy + (m_tScroll_Info.fcy / 2.f) - m_tScroll_Info.fcy / 2);
m_tScroll_Rect.bottom = long(m_tScroll_Info.fy + (m_tScroll_Info.fcy / 2.f) + m_tScroll_Info.fcy / 2);
if (m_bVisible == true)
{
Scroll_Move();
Item_View_Control();
}
return 0;
}
void CStore::Render(HDC _dc)
{
if (m_bVisible == true)
{
TransparentBlt(_dc,
int(m_tInfo.fx), int(m_tInfo.fy),
int(m_tInfo.fcx), int(m_tInfo.fcy),
GETS(CBitMapMgr)->FindImage(L"Store")->GetMemDC(),
0, 0,
int(m_tInfo.fcx), int(m_tInfo.fcy),
RGB(0, 0, 0));
TransparentBlt(_dc,
int(m_tEscButton_Info.fx), int(m_tEscButton_Info.fy),
int(m_tEscButton_Info.fcx), int(m_tEscButton_Info.fcy),
GETS(CBitMapMgr)->FindImage(L"Button_Esc")->GetMemDC(),
0, 0,
int(m_tEscButton_Info.fcx), int(m_tEscButton_Info.fcy),
RGB(1, 1, 1));
TransparentBlt(_dc,
int(m_tScroll_Info.fx), int(m_tScroll_Info.fy),
int(m_tScroll_Info.fcx), int(m_tScroll_Info.fcy),
GETS(CBitMapMgr)->FindImage(L"UI_Scroll")->GetMemDC(),
0, 0,
int(m_tScroll_Info.fcx), int(m_tScroll_Info.fcy),
RGB(0, 0, 0));
/*
Rectangle(_dc,
m_tEscButton_Rect.left,
m_tEscButton_Rect.top,
m_tEscButton_Rect.right,
m_tEscButton_Rect.bottom);
Rectangle(_dc,
m_tScroll_Rect.left,
m_tScroll_Rect.top,
m_tScroll_Rect.right,
m_tScroll_Rect.bottom);
*/
ITEMITER iter = m_Store_ItemList.begin();
float fx = 10.f;
float fy = 125.f;
int iIndex = 0;
for (iter; iter != m_Store_ItemList.end(); ++iter, ++iIndex)
{
if (iIndex < 9)
{
(*iter)->Render(_dc);
(*iter)->SetPos(m_tInfo.fx + fx, m_tInfo.fy + fy + (42.5f * iIndex));
(*iter)->SetItemDescription_Render(_dc, m_tInfo.fx + 50.f, m_tInfo.fy + 125.f + (42.5f * iIndex));
}
}
}
}
void CStore::Release(void)
{
ITEMITER iter_Item = m_Store_ItemList.begin();
ITEMITER iter_Item_End = m_Store_ItemList.end();
for (iter_Item; iter_Item != iter_Item_End; ++iter_Item)
{
delete *iter_Item;
}
m_Store_ItemList.clear();
}
void CStore::Scroll_Move(void)
{
//마우스로 클릭하고 밑으로 내릴때 스크롤 바가 움직이게 한다.
static bool bMove = false;
POINT pt;
pt = CMouse::GetPos();
if (PtInRect(&m_tScroll_Rect, pt) && GETS(CKeyMgr)->GetKeyState(VK_LBUTTON))
bMove = true;
if (!GETS(CKeyMgr)->GetKeyState(VK_LBUTTON) && bMove == true)
bMove = false;
if (bMove == true)
{
if (m_tScroll_Info.fy < m_tInfo.fy + 134.f)
{
m_tScroll_Info.fy = m_tInfo.fy + 134.f;
return;
}
if (m_tScroll_Info.fy > 559.f)
{
m_tScroll_Info.fy = 559.f;
return;
}
//Scroll Move
m_tScroll_Info.fy = pt.y - m_tScroll_Info.fcx / 2.f;
}
}
void CStore::Item_View_Control(void)
{
/*
아이템 리스트에서 스크롤이 될 경우에 리스트의 맨 앞에 있는 것이 빠지고
그 밑에 있는 것들이 위로 올라오는 식으로 보여 주어야 한다.
지금 상태는 미리 13개 아이템을 다 넣어논 상태이고 지금 13개 다 보여주고 있다.
기준은 스크롤 바의 좌표 값을 기준으로 잡아보자.
*/
static bool bMoveUp = false;
if (m_tScroll_Info.fy < m_tInfo.fy + 134.f)
{
bMoveUp = false;
return;
}
else if (m_tScroll_Info.fy > m_tInfo.fy + 134.f && m_tScroll_Info.fy < 559.f)
{
ITEMITER iter = m_Store_ItemList.begin();
ITEMITER iter_End = m_Store_ItemList.end();
float fx = 10.f;
float fy = 125.f;
int iIndex = 0;
//스크롤바를 밑으로 내릴시에
if (bMoveUp == false)
{
if (m_tScroll_Info.fy >= 315 && m_tScroll_Info.fy < 396)
{
for (iter; iter != iter_End;)
{
if ((*iter)->GetItemData()->m_dwOption == 0)
{
m_Store_ItemList.erase(iter);
iter = m_Store_ItemList.begin();
iter_End = m_Store_ItemList.end();
}
else
++iter;
}
}
else if (m_tScroll_Info.fy >= 396 && m_tScroll_Info.fy < 477)
{
for (iter; iter != iter_End;)
{
if ((*iter)->GetItemData()->m_dwOption == 1)
{
m_Store_ItemList.erase(iter);
iter = m_Store_ItemList.begin();
iter_End = m_Store_ItemList.end();
}
else
++iter;
}
}
else if (m_tScroll_Info.fy >= 477 && m_tScroll_Info.fy < 558)
{
for (iter; iter != iter_End;)
{
if ((*iter)->GetItemData()->m_dwOption == 2)
{
m_Store_ItemList.erase(iter);
iter = m_Store_ItemList.begin();
iter_End = m_Store_ItemList.end();
}
else
++iter;
}
}
else if (m_tScroll_Info.fy >= 558 && m_tScroll_Info.fy < 559)
{
for (iter; iter != iter_End;)
{
if ((*iter)->GetItemData()->m_dwOption == 3)
{
m_Store_ItemList.erase(iter);
iter = m_Store_ItemList.begin();
iter_End = m_Store_ItemList.end();
}
else
++iter;
}
}
}
//스크롤 바를 위로 올릴시에
if (bMoveUp == true)
{
if (m_tScroll_Info.fy <= 315 && m_tScroll_Info.fy > 234)
{
CItem* pArmor = new CArmor(L"Armor");
((CArmor*)pArmor)->Initialize();
((CArmor*)pArmor)->SetArmor_Data(5, 5, 5, 5, 10, 5, 1000, 0);
pArmor->SetItemDescription(L"기본 갑옷");
m_Store_ItemList.push_front(pArmor);
}
else if (m_tScroll_Info.fy <= 396 && m_tScroll_Info.fy > 315)
{
CItem* pArmor = new CArmor(L"Armor1");
((CArmor*)pArmor)->Initialize();
((CArmor*)pArmor)->SetArmor_Data(10, 10, 10, 10, 15, 10, 2000, 1);
pArmor->SetItemDescription(L"고급 갑옷");
m_Store_ItemList.push_front(pArmor);
}
else if (m_tScroll_Info.fy <= 477 && m_tScroll_Info.fy > 396)
{
CItem* pWeapon = new CWeapon(L"Weapon");
((CWeapon*)pWeapon)->Initialize();
((CWeapon*)pWeapon)->SetWeapon_Data(10, 2, 2, 2, 0, 0, 1000, 2);
pWeapon->SetItemDescription(L"기본 무기");
m_Store_ItemList.push_front(pWeapon);
}
else if (m_tScroll_Info.fy <= 558 && m_tScroll_Info.fy > 477)
{
CItem* pWeapon = new CWeapon(L"Weapon1");
((CWeapon*)pWeapon)->Initialize();
((CWeapon*)pWeapon)->SetWeapon_Data(20, 4, 4, 4, 0, 0, 2000, 3);
pWeapon->SetItemDescription(L"고급 무기");
m_Store_ItemList.push_front(pWeapon);
}
}
/*
system("cls");
cout << m_tScroll_Info.fy << endl;
cout << m_tScroll_Rect.top << endl;
cout << m_tScroll_Rect.bottom << endl;
*/
}
}
| [
"ygchoi2001@naver.com"
] | ygchoi2001@naver.com |
0e6e560bb8cda7980ff82d974bce9815e29788dd | 40cdb94b52db41bb7b06f0b304a554247a8c9754 | /Gpu_Rvd/header/cuda/cuda_polygon.h | 63e90237b8359ce810f8b2d05a1dde11b75610a6 | [
"MIT"
] | permissive | stormHan/gpu_rvd | adb86de5e2d236ac63476c8d598d4021deb9b2d5 | 4029bfa604117c723c712445b42842b4aa499db2 | refs/heads/master | 2020-06-23T03:13:14.648566 | 2017-03-29T12:40:34 | 2017-03-29T12:40:34 | 74,668,863 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 542 | h | /*
*
*/
#ifndef CUDA_POLYGON_H
#define CUDA_POLYGON_H
namespace Gpu_Rvd{
/*
* \brief Cuda polygon vertex.
* \detials x, y, z is the spatial position of a vertxt.
* w is the weight of a vextex. neigh_s is the nearby seed
* of the current point.
*/
struct CudaVertex
{
double x;
double y;
double z;
double w;
int neigh_s = -1;
};
/*
* \brief Cuda polygon. A smart data stuction to store the clipped triangle.
*/
struct CudaPolygon
{
CudaVertex vertex[15];
index_t vertex_nb;
};
}
#endif /* CUDA_POLYGON_H */ | [
"stormhan1205@gmail.com"
] | stormhan1205@gmail.com |
e086d8de5a7d3349357bb1d7a885c19b1e96e908 | 7292da3fcac24ba18579466b44b4b8e053464eb6 | /Server/recomandare.cpp | 947c016670f227fd8a3510b5732e18d787f22634 | [] | no_license | raresmihai/readsprofiler | 16b12e2c58703094fe5280ead5ce0945088eed65 | c32315322675727fe9c41437224b2d8d84f8ca80 | refs/heads/master | 2021-01-19T03:13:46.835065 | 2016-07-23T19:13:45 | 2016-07-23T19:13:45 | 48,611,239 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,829 | cpp | #include "recomandare.h"
void recomandare_carti(int client_descriptor)
{
int caz_recomandare;
if(read(client_descriptor,&caz_recomandare,4)<0)
{
perror("Eroare la citirea cazului de recomandare.\n");
}
char username[50];
if(read(client_descriptor,&username,50)<0)
{
perror("Eroare la citirea usernameului pentru recomandare.\n");
}
char isbn[20];
if(caz_recomandare == 2)
{
if(read(client_descriptor,&isbn,20)<0)
{
perror("Eroare la citirea isbn-ului pentru recomandare.\n");
}
}
switch(caz_recomandare)
{
case 1:
recomanda_top_5_carti(client_descriptor);
break;
case 2:
recomandari_similare(client_descriptor,isbn);
break;
case 3:
recomandari_dupa_istoric(client_descriptor,username);
break;
}
}
void recomandari_dupa_istoric(int client_descriptor, char *username)
{
SugestieCarte recomandariCarti[1000];
bzero(&recomandariCarti,sizeof(recomandariCarti));
Tabela tabele[3];
strcpy(tabele[0].denumire_tabela,"cautari_utilizatori");
tabele[0].importanta_tabela = 1;
strcpy(tabele[1].denumire_tabela,"accesari_utilizatori");
tabele[1].importanta_tabela = 2;
strcpy(tabele[2].denumire_tabela,"descarcari_utilizatori");
tabele[2].importanta_tabela = 3;
char interogare[1000];
QSqlQuery query_tabelaPrincipala;
char isbn[20];
for(int i=0;i<3;i++)
{
sprintf(interogare,"SELECT isbn FROM %s WHERE username = '%s'",tabele[i].denumire_tabela,username);
if(!query_tabelaPrincipala.exec(interogare)){
qDebug() << "Eroare la selectarea isbnurilor de baza in recomandare:\n" << query_tabelaPrincipala.lastError();
}
while(query_tabelaPrincipala.next())
{
strcpy(isbn,query_tabelaPrincipala.value(0).toString().toStdString().c_str());
adauga_recomandari(recomandariCarti,tabele[i].importanta_tabela,isbn,username);
}
}
int nr_recomandari = sortare_dupa_grad(recomandariCarti);
int caz_recomandare_client = 3;
if(nr_recomandari < 5)
{
if(nr_recomandari == 0)
{
caz_recomandare_client = 1;
write(client_descriptor,&caz_recomandare_client,4);
recomanda_top_5_carti(client_descriptor);
}
else
{
write(client_descriptor,&caz_recomandare_client,4);
SugestieCarte topCarti[1000];
bzero(&topCarti,sizeof(topCarti));
int nr_top_recomandari = top_carti_dupa_rating(topCarti);
int i=0;
while(nr_recomandari<5 && i<nr_top_recomandari)
{
if(cartea_nu_a_fost_deja_adaugata(recomandariCarti,topCarti[i].isbn))
{
recomandariCarti[nr_recomandari] = topCarti[i];
nr_recomandari++;
}
i++;
}
trimite_recomandarile_clientului(client_descriptor,recomandariCarti);
}
}
else
{
write(client_descriptor,&caz_recomandare_client,4);
trimite_recomandarile_clientului(client_descriptor,recomandariCarti);
}
}
void adauga_recomandari(SugestieCarte *recomandariCarti, int importanta_tabela, char *isbn, char *username)
{
char interogare[1000];
QSqlQuery query;
//selectare rating
sprintf(interogare,"SELECT rating_acordat FROM rating_utilizatori WHERE isbn = '%s' AND username = '%s'",isbn,username);
if(!query.exec(interogare)){
qDebug() << "Eroare la selectarea ratingului de baza in recomandare:\n" << query.lastError();
}
int rating_carte_de_baza = 0;
if(query.size()>0){
query.first();
rating_carte_de_baza = query.value(0).toInt();
}
//selectare id_autor
sprintf(interogare,"SELECT id_autor FROM carti WHERE isbn = '%s'",isbn);
if(!query.exec(interogare)){
qDebug() << "Eroare la selectarea autorului in recomandare:\n" << query.lastError();
}
query.first();
int id_autor = query.value(0).toInt();
//selectare an_aparitie
sprintf(interogare,"SELECT an_aparitie FROM carti WHERE isbn = '%s'",isbn);
if(!query.exec(interogare)){
qDebug() << "Eroare la selectarea anului in recomandare:\n" << query.lastError();
}
query.first();
int an_aparitie = query.value(0).toInt();
//selectare genuri
sprintf(interogare,"SELECT id_gen FROM genuri_carte WHERE isbn = '%s'",isbn);
if(!query.exec(interogare)){
qDebug() << "Eroare la selectarea genurilor in recomandare:\n" << query.lastError();
}
int nr_genuri = query.size();
int genuri[nr_genuri];
int k=0;
while(query.next())
{
genuri[k]=query.value(0).toInt();
k++;
}
//selectare subgenuri
sprintf(interogare,"SELECT id_subgen FROM subgenuri_carte WHERE isbn = '%s'",isbn);
if(!query.exec(interogare)){
qDebug() << "Eroare la selectarea subgenurilor in recomandare:\n" << query.lastError();
}
int nr_subgenuri = query.size();
int subgenuri[nr_subgenuri];
k=0;
while(query.next())
{
subgenuri[k]=query.value(0).toInt();
k++;
}
//setare campuri pentru interogari
int nr_interogari = 2 + nr_genuri + nr_subgenuri;
InterogareDinamica interogari[nr_interogari];
strcpy(interogari[0].nume_tabela,"carti");
strcpy(interogari[0].nume_camp,"id_autor");
interogari[0].valoare_camp = id_autor;
interogari[0].importanta_camp = 3;
strcpy(interogari[1].nume_tabela,"carti");
strcpy(interogari[1].nume_camp,"an_aparitie");
interogari[1].valoare_camp = an_aparitie;
interogari[1].importanta_camp = 2;
for(int i=2;i<2+nr_genuri;i++)
{
strcpy(interogari[i].nume_tabela,"genuri_carte");
strcpy(interogari[i].nume_camp,"id_gen");
interogari[i].valoare_camp = genuri[i-2];
interogari[i].importanta_camp = 5;
}
for(int i=2+nr_genuri;i<nr_interogari;i++)
{
strcpy(interogari[i].nume_tabela,"subgenuri_carte");
strcpy(interogari[i].nume_camp,"id_subgen");
interogari[i].valoare_camp = subgenuri[i-2-nr_genuri];
interogari[i].importanta_camp = 4;
}
//INTEROGARI
char isbn_sugestie[20];
for(int i=0;i<nr_interogari;i++)
{
sprintf(interogare,"SELECT isbn FROM %s WHERE isbn != '%s' AND %s = %d",interogari[i].nume_tabela,isbn,interogari[i].nume_camp,interogari[i].valoare_camp);
if(!query.exec(interogare)){
qDebug() << "Eroare la selectarea isbnului recomandarii:\n" << query.lastError();
}
while(query.next())
{
strcpy(isbn_sugestie,query.value(0).toString().toStdString().c_str());
if(user_nu_a_mai_accesat_cartea(username,isbn_sugestie))
{
double rating_carte_sugestie = rating_carte(isbn_sugestie);
double grad_recomandare = calculare_grad_recomandare(importanta_tabela,interogari[i].importanta_camp,rating_carte_de_baza,rating_carte_sugestie);
adauga_sugestie_noua(recomandariCarti,isbn_sugestie,grad_recomandare);
}
}
}
}
void adauga_sugestie_noua(SugestieCarte *recomandariCarti, char *isbn_sugestie, double grad_recomandare)
{
bool sugestieGasita = false;
int lungime = 0;
while(recomandariCarti[lungime].grad_recomandare>0)
{
if(strcmp(recomandariCarti[lungime].isbn,isbn_sugestie)==0)
{
recomandariCarti[lungime].grad_recomandare+=grad_recomandare;
sugestieGasita = true;
break;
}
lungime++;
}
if(sugestieGasita==false)
{
recomandariCarti[lungime].grad_recomandare=grad_recomandare;
strcpy(recomandariCarti[lungime].isbn,isbn_sugestie);
}
}
double calculare_grad_recomandare(int importanta_tabela, int importanta_camp, int rating_carte_de_baza, double rating_carte_sugestie)
{
return (double)(importanta_tabela * importanta_tabela * (3*rating_carte_sugestie + 2*importanta_camp + rating_carte_de_baza));
}
int sortare_dupa_grad(SugestieCarte *recomandariCarti)
{
int lungime = 0;
while(recomandariCarti[lungime].grad_recomandare>0) lungime++;
SugestieCarte aux;
for(int i = 0;i<lungime-1;i++)
{
for(int j = i+1; j<lungime;j++)
{
if(recomandariCarti[i].grad_recomandare<recomandariCarti[j].grad_recomandare)
{
aux = recomandariCarti[i];
recomandariCarti[i]=recomandariCarti[j];
recomandariCarti[j]=aux;
}
}
}
return lungime;
}
int top_carti_dupa_rating(SugestieCarte *topCarti)
{
QSqlQuery query;
if(!query.exec("SELECT isbn,valoare/nr_voturi FROM rating WHERE nr_voturi > 3 ORDER BY valoare/nr_voturi DESC")){
qDebug() << "Eroare la selectarea TOP recomandari:\n" << query.lastError();
}
int nr_top_carti = 0;
while(query.next()&&nr_top_carti<30)
{
strcpy(topCarti[nr_top_carti].isbn,query.value(0).toString().toStdString().c_str());
topCarti[nr_top_carti].grad_recomandare = query.value(1).toDouble();
nr_top_carti++;
}
return nr_top_carti;
}
double rating_carte(char *isbn)
{
char interogare[1000];
QSqlQuery query;
sprintf(interogare,"SELECT IFNULL(valoare/nr_voturi,2.5) FROM rating WHERE isbn = '%s'",isbn);
if(!query.exec(interogare)){
qDebug() << "Eroare la selectarea ratingului cartii sugestie in recomandare:\n" << query.lastError();
}
query.first();
double rating = query.value(0).toDouble();
return rating;
}
bool user_nu_a_mai_accesat_cartea(char *username, char *isbn)
{
char interogare[1000];
QSqlQuery query;
sprintf(interogare,"SELECT id FROM accesari_utilizatori WHERE username = '%s' AND isbn = '%s'",username,isbn);
if(!query.exec(interogare)){
qDebug() << "Eroare la verificare accesare in recomandare:\n" << query.lastError();
}
if(query.size()==0)
{
return true;
}
return false;
}
void recomanda_top_5_carti(int client_descriptor)
{
QSqlQuery query;
if(!query.exec("SELECT isbn FROM rating WHERE nr_voturi > 3 ORDER BY valoare/nr_voturi DESC LIMIT 5")){
qDebug() << "Eroare la top 5 recomandari:\n" << query.lastError();
}
SugestieCarte top5[5];
int index = 0;
while(query.next())
{
strcpy(top5[index].isbn,query.value(0).toString().toStdString().c_str());
index++;
}
trimite_recomandarile_clientului(client_descriptor,top5);
}
bool cartea_nu_a_fost_deja_adaugata(SugestieCarte *recomandari, char *isbn)
{
int i = 0;
while(recomandari[i].grad_recomandare>0)
{
if(strcmp(recomandari[i].isbn,isbn)==0)
{
return false;
}
i++;
}
return true;
}
void recomandari_similare(int client_descriptor,char *isbn)
{
SugestieCarte recomandariSimilare[1000];
bzero(&recomandariSimilare,sizeof(recomandariSimilare));
char interogare[1000];
char username_similar[50];
char isbn_sugestie[20];
int nr_voturi;
QSqlQuery query;
QSqlQuery query_nrVoturi;
QSqlQuery query_isbn;
sprintf(interogare,"SELECT username FROM rating_utilizatori WHERE isbn = '%s'",isbn);
if(!query.exec(interogare)){
qDebug() << "Eroare la select usernames in recomandare:\n" << query.lastError();
}
while(query.next())
{
strcpy(username_similar,query.value(0).toString().toStdString().c_str());
sprintf(interogare,"SELECT isbn FROM rating_utilizatori WHERE username = '%s' AND isbn != '%s'",username_similar,isbn);
if(!query_isbn.exec(interogare)){
qDebug() << "Eroare la selectarea isbnurilor recomandarilor similare:\n" << query.lastError();
}
while(query_isbn.next())
{
strcpy(isbn_sugestie,query_isbn.value(0).toString().toStdString().c_str());
sprintf(interogare,"SELECT nr_voturi FROM rating WHERE isbn = '%s'",isbn_sugestie);
if(!query_nrVoturi.exec(interogare)){
qDebug() << "Eroare la selectarea isbnurilor recomandarilor similare:\n" << query.lastError();
}
query_nrVoturi.first();
nr_voturi = query_nrVoturi.value(0).toInt();
adauga_sugestie_noua(recomandariSimilare,isbn_sugestie,(double)nr_voturi);
}
}
int nr_recomandari = sortare_dupa_grad(recomandariSimilare);
int caz_recomandare_client = 2;
if(nr_recomandari < 5)
{
if(nr_recomandari == 0)
{
caz_recomandare_client = 1;
write(client_descriptor,&caz_recomandare_client,4);
recomanda_top_5_carti(client_descriptor);
}
else
{
write(client_descriptor,&caz_recomandare_client,4);
SugestieCarte topCarti[1000];
bzero(&topCarti,sizeof(topCarti));
int nr_top_recomandari = top_carti_dupa_rating(topCarti);
int i=0;
while(nr_recomandari<5 && i<nr_top_recomandari)
{
if(cartea_nu_a_fost_deja_adaugata(recomandariSimilare,topCarti[i].isbn))
{
recomandariSimilare[nr_recomandari] = topCarti[i];
nr_recomandari++;
}
i++;
}
trimite_recomandarile_clientului(client_descriptor,recomandariSimilare);
}
}
else
{
write(client_descriptor,&caz_recomandare_client,4);
trimite_recomandarile_clientului(client_descriptor,recomandariSimilare);
}
}
void trimite_recomandarile_clientului(int client_descriptor, SugestieCarte *recomandari)
{
QSqlQuery query;
char interogare[1000];
for(int i=0;i<5;i++)
{
if(write(client_descriptor,&recomandari[i].isbn,20)<=0){
perror("Eroare la scrierea isbnului in recomandare.\n");
}
sprintf(interogare,"SELECT coperta FROM carti WHERE isbn = '%s'",recomandari[i].isbn);
if(!query.exec(interogare)){
qDebug() << "Eroare la selectarea copertii cartii in recomandare:\n" << query.lastError();
}
query.first();
QByteArray outByteArray = query.value(0).toByteArray();
int dimens = (int)outByteArray.size();
if(write(client_descriptor,&dimens,4)<=0){
perror("Eroare la scrierea dimensiunii copertii in recomandare.\n");
}
char img_data[dimens];
for(int i=0;i<dimens;i++)
{
img_data[i]=outByteArray[i];
}
if(write(client_descriptor,&img_data,dimens)!=dimens){
perror("Eroare la scrierea copertii in recomandare.\n");
}
}
}
| [
"raresbabuta@gmail.com"
] | raresbabuta@gmail.com |
282cb6bc3252bcbb409f65049f47506d495e82c5 | e08b2ee4b3c34fc9ef03fbdda7fffa8ec9ef1077 | /sim/program.h | bf74e989853f3021577814c5e71db46f7bd2f7bf | [] | no_license | trnila/ledcube | d1c04f80629e51474f44f9b6a7c3f49ee250fafd | 3dd814b2ac0cec53c8656cc33416a6d3bbbda1a7 | refs/heads/master | 2020-03-22T16:31:27.790283 | 2018-07-09T19:23:20 | 2018-07-09T19:23:20 | 140,332,313 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 464 | h | #pragma once
#include <glm/glm.hpp>
class Program {
public:
Program(const char *vertex, const char *fragment);
void setUniform(const char *attr, glm::mat4 coord);
void setUniform(const char *attr, glm::vec3 vec);
void activate();
void configureCoord();
private:
GLuint program;
GLint getUniformHandle(const char *attribute_name);
GLint getAttributeHandle(const char *attribute_name);
GLuint createShader(const char *filename, GLenum type);
};
| [
"daniel.trnka@gmail.com"
] | daniel.trnka@gmail.com |
d4dcd077dcd08cdf5c50423f2e3b60ad7d724d90 | 2f85ea1b415b0a5b14c3f67a43bc7c8266c2d1b3 | /Bitmanipulation/clearallbit.cpp | 60d17ef0ab26b050bf191ab92ace6446566c6fe2 | [] | no_license | ratankumar19/Competitive-Programming | 960c565fcbf91c282bcfb0d8141ed85335985310 | d19f1678f4695b8057d619651a8c05310f212c5c | refs/heads/master | 2022-11-13T22:06:59.396406 | 2020-07-11T13:16:08 | 2020-07-11T13:16:08 | 278,863,021 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 287 | cpp | int clearAllBits(int n, int i){
/* Don't write main().
* Don't read input, it is passed as function argument.
* Return output and don't print it.
* Taking input and printing output is handled automatically.
*/
int mask= (1<<i)-1;
n=n&mask;
return n;
}
| [
"ratankumar086@gmail.com"
] | ratankumar086@gmail.com |
9418324f5f67691190bb0ff12b9a7e48c993f21a | 350db570521d3fc43f07df645addb9d6e648c17e | /0155_Min_Stack/solution.cpp | 5f0290ad67573f5fcc955ab398e5f2eb808a06c6 | [] | no_license | benjaminhuanghuang/ben-leetcode | 2efcc9185459a1dd881c6e2ded96c42c5715560a | a2cd0dc5e098080df87c4fb57d16877d21ca47a3 | refs/heads/master | 2022-12-10T02:30:06.744566 | 2022-11-27T04:06:52 | 2022-11-27T04:06:52 | 236,252,145 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 943 | cpp | /*
155. Min Stack
Level: Easy
https://leetcode.com/problems/min-stack
*/
#include <vector>
#include <string>
#include <stack>
#include <algorithm>
#include "common/ListNode.h"
#include "common/TreeNode.h"
using namespace std;
/*
Solution:
*/
class MinStack
{
private:
stack<int> valStack;
stack<int> minStack;
public:
/** initialize your data structure here. */
MinStack()
{
}
void push(int x)
{
valStack.push(x);
if (minStack.empty())
{
minStack.push(x);
}
else
{
minStack.push(min(x, minStack.top()));
}
}
void pop()
{
valStack.pop();
minStack.pop();
}
int top()
{
return valStack.top();
}
int getMin()
{
return minStack.top();
}
};
/**
* Your MinStack object will be instantiated and called as such:
* MinStack* obj = new MinStack();
* obj->push(x);
* obj->pop();
* int param_3 = obj->top();
* int param_4 = obj->getMin();
*/ | [
"bhuang@rms.com"
] | bhuang@rms.com |
60256069d7654e75f62ddcee04320b6bfec10236 | 535e18dcaa3d0fb0d85b171f426b77d44c5082f8 | /wifi/wifi.cpp | 23e9b90db808e7b84716e9f0549a1fbbfc9f79de | [] | no_license | raspberrydev/WiFiDirect | 0ea38c03892ecda3738935054ea269c7b3fbd700 | 6b185f4266f00291e395a57873c47b2d27d5c544 | refs/heads/master | 2022-03-25T19:57:05.829784 | 2019-12-26T09:45:29 | 2019-12-26T09:45:29 | 230,236,103 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 607 | cpp | #include "stdafx.h"
#include "console.h"
#include "hostednetwork.h"
using namespace ABI::Windows::Foundation;
using namespace Microsoft::WRL;
using namespace Microsoft::WRL::Wrappers;
using namespace std;
int main(int argc, char** argv)
{
// Initialize the Windows Runtime.
RoInitializeWrapper initialize(RO_INIT_MULTITHREADED);
if (FAILED(initialize))
{
std::cout << "Failed to initialize Windows Runtime" << std::endl;
return static_cast<HRESULT>(initialize);
}
SimpleConsole console;
console.RunConsole(argv);
return 0;
}
| [
"noreply@github.com"
] | raspberrydev.noreply@github.com |
e44cba589706d446a3f2fd25f4643f5074c0e6f6 | 3f435b73e0fd7701828ea7e569e0586d38f98edb | /Begginers/sumodd.cpp | 50a727297bd3a748b063bd9867ec42f74de48e84 | [] | no_license | lhpdev/URIJudgeExercises | 44adb7912c5abf4ac623e2053c041099950ec429 | 87293f5ab12f2a92dce3fb9dc02c403ad9a0e60f | refs/heads/master | 2021-09-22T09:06:09.539693 | 2018-09-06T21:15:00 | 2018-09-06T21:15:00 | 93,896,132 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,317 | cpp | #include <stdio.h>
#include <iostream>
using namespace std;
int main(int argc, char const *argv[])
{
int X,Y,i,sum,sumX,sumY,auxX, auxY;
scanf("%d" , &X);
scanf("%d" , &Y);
sum = 0;
sumX = 0;
sumY= 0;
if (( X < 0) && (Y < 0)){ // OK
auxX = -X;
auxY = -Y;
if( auxX > auxY){
for (int i = (auxY + 1); i < auxX; ++i)
{
if ( i%2 != 0){
sum = sum + i;
}
}
}else{
for (int i = (auxX + 1); i < auxY; ++i)
{
if ( i%2 != 0){
sum = sum + i;
}
}
}
printf("%d\n",-sum);
}
if ((X > 0) && (Y >0)){ // OK
if( X > Y){
for (int i = (Y + 1); i < X; ++i)
{
if ( i%2 != 0){
sum = sum + i;
}
}
}else{
for (int i = (X + 1); i < Y; ++i)
{
if ( i%2 != 0){
sum = sum + i;
}
}
}
printf("%d\n",sum);
}
if ((X > 0) && (Y < 0)){
auxY = -Y;
for (int i = 0; i < X; ++i)
{
if ( i%2 != 0){
sumX = sumX + i;
}
}
for (int i = 0; i < auxY; ++i)
{
if ( i%2 != 0){
sumY = sumY + i;
}
}
printf("%d\n",sumX -sumY);
}
if ((X < 0) && (Y > 0)){
auxX = -X;
for (int i = 0; i < auxX; ++i)
{
if ( i%2 != 0){
sumX = sumX + i;
}
}
for (int i = 0; i < Y; ++i)
{
if ( i%2 != 0){
sumY = sumY + i;
}
}
printf("%d\n",sumY - sumX);
}
return 0;
} | [
"lucass.hauptmann@gmail.com"
] | lucass.hauptmann@gmail.com |
d7d7e220ecf925cd816e2e497288e6e987343e29 | 11cd4f066c28c0b23272b6724f741dd6231c5614 | /Codeforces/1325-A.cpp | 9a9a92121c246e50a2c8e100a239a50f878cf286 | [] | no_license | Maruf089/Competitive-Programming | 155161c95a7a517cdbf7e59242c6e3fc25dd02b7 | 26ce0d2884842d4db787b5770c10d7959245086e | refs/heads/master | 2021-06-24T11:00:55.928489 | 2021-06-01T05:45:58 | 2021-06-01T05:45:58 | 222,057,521 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,197 | cpp | /**Bismillahir Rahmanir Rahim.**/
#include<bits/stdc++.h>
using namespace std;
#define ln '\n'
#define inp(x) scanf("%lld",&x)
#define inp2(a,b) scanf("%lld %lld",&a,&b)
#define f0(i,b) for(int i=0;i<(b);i++)
#define f1(i,b) for(int i=1;i<=(b);i++)
#define MOD 1000000007
#define PI acos(-1)
#define ll long long int
typedef pair<int,int> pii;
typedef pair<ll, ll> pll;
#define pb push_back
#define F first
#define S second
#define sz size()
#define LCM(a,b) (a*(b/__gcd(a,b)))
//#define harmonic(n) 0.57721566490153286060651209+log(n)+1.0/(2*n)
#define SORT_UNIQUE(c) (sort(c.begin(),c.end()), c.resize(distance(c.begin(),unique(c.begin(),c.end()))))
#define all(v) v.begin(),v.end()
#define MEM(a, b) memset(a, b, sizeof(a))
#define fast ios_base::sync_with_stdio(false)
/*
#include <ext/pb_ds/assoc_container.hpp> // Common file
#include <ext/pb_ds/tree_policy.hpp> // Including */
//using namespace __gnu_pbds;
/*
template<typename T>
using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
template<typename F, typename S>
using ordered_map = tree<F, S, less<F>, rb_tree_tag, tree_order_statistics_node_update>;
// find_by_order(k) – ফাংশনটি kth ordered element এর একটা পয়েন্টার রিটার্ন করে। অর্থাৎ তুমি চাইলেই kth ইন্ডেক্সে কি আছে, সেটা জেনে ফেলতে পারছো!
// order_of_key(x) – ফাংশনটি x এলিমࡆɠǍটটޠকোন পজিশনে আছে সেটা বলে দেয়।
*/
///Inline functions
inline bool EQ(double a, double b) { return fabs(a-b) < 1e-9; }
inline bool isLeapYear(ll year) { return (year%400==0) | (year%4==0 && year%100!=0); }
inline void normal(ll &a) { a %= MOD; (a < 0) && (a += MOD); }
inline ll modMul(ll a, ll b) { a %= MOD, b %= MOD; normal(a), normal(b); return (a*b)%MOD; }
inline ll modAdd(ll a, ll b) { a %= MOD, b %= MOD; normal(a), normal(b); return (a+b)%MOD; }
inline ll modSub(ll a, ll b) { a %= MOD, b %= MOD; normal(a), normal(b); a -= b; normal(a); return a; }
inline ll modPow(ll b, ll p) { ll r = 1; while(p) { if(p&1) r = modMul(r, b); b = modMul(b, b); p >>= 1; } return r; }
inline ll modInverse(ll a) { return modPow(a, MOD-2); }
inline ll modDiv(ll a, ll b) { return modMul(a, modInverse(b)); }
inline bool isInside(pii p,ll n,ll m){ return (p.first>=0&&p.first<n&&p.second>=0&&p.second<m); }
inline bool isInside(pii p,ll n){ return (p.first>=0&&p.first<n&&p.second>=0&&p.second<n); }
inline bool isSquare(ll x){ ll s = sqrt(x); return (s*s==x); }
inline bool isFib(ll x) { return isSquare(5*x*x+4)|| isSquare(5*x*x-4); }
inline bool isPowerOfTwo(ll x){ return ((1LL<<(ll)log2(x))==x); }
/// DEBUG --------------------------------------------------------------------------------->>>>>>
///**
template < typename F, typename S >
ostream& operator << ( ostream& os, const pair< F, S > & p )
{
return os << "(" << p.first << ", " << p.second << ")";
}
template < typename T >
ostream &operator << ( ostream & os, const vector< T > &v )
{
os << "{";
for (auto it = v.begin(); it != v.end(); ++it)
{
if ( it != v.begin() )
os << ", ";
os << *it;
}
return os << "}";
}
template < typename T >
ostream &operator << ( ostream & os, const set< T > &v )
{
os << "[";
for (auto it = v.begin(); it != v.end(); ++it)
{
if ( it != v.begin())
os << ", ";
os << *it;
}
return os << "]";
}
template < typename F, typename S >
ostream &operator << ( ostream & os, const map< F, S > &v )
{
os << "[";
for (auto it = v.begin(); it != v.end(); ++it)
{
if ( it != v.begin() )
os << ", ";
os << it -> first << " = " << it -> second ;
}
return os << "]";
}
#define dbg(args...) do {cerr << #args << " : "; faltu(args); } while(0)
clock_t tStart = clock();
#define timeStamp dbg("Execution Time: ", (double)(clock() - tStart)/CLOCKS_PER_SEC)
void faltu ()
{
cerr << endl;
}
template <typename T>
void faltu( T a[], int n )
{
for (int i = 0; i < n; ++i)
cerr << a[i] << ' ';
cerr << endl;
}
template <typename T, typename ... hello>
void faltu( T arg, const hello &... rest)
{
cerr << arg << ' ';
faltu(rest...);
}
/// TEMPLATE ----------------------------------------------------------------------->>>>>>
struct func
{
//this is a sample overloading function for sorting stl
bool operator()(pii const &a, pii const &b)
{
if(a.F==b.F)
return (a.S<b.S);
return (a.F<b.F);
}
};
/*------------------------------Graph Moves----------------------------*/
//Rotation: S -> E -> N -> W
//const int fx[] = {0, +1, 0, -1};
//const int fy[] = {-1, 0, +1, 0};
//const int fx[]={+0,+0,+1,-1,-1,+1,-1,+1}; // Kings Move
//const int fy[]={-1,+1,+0,+0,+1,+1,-1,-1}; // Kings Move
//const int fx[]={-2, -2, -1, -1, 1, 1, 2, 2}; // Knights Move
//const int fy[]={-1, 1, -2, 2, -2, 2, -1, 1}; // Knights Move
/*---------------------------------------------------------------------*/
/// Bit Operations
/// count set bit C = (num * 0x200040008001ULL & 0x111111111111111ULL) % 0xf; /// 32 bit integer
/// inline bool checkBit(ll n, int i) { return n&(1LL<<i); }
/// inline ll setBit(ll n, int i) { return n|(1LL<<i); }
/// inline ll resetBit(ll n, int i) { return n&(~(1LL<<i)); }
/// ************************************** Code starts here ****************************************** */
const ll INF = 0x3f3f3f3f3f3f3f3f;
const long double EPS = 1e-9;
const int inf = 0x3f3f3f3f;
const int mx = (int)1e5+9;
ll n,m,a,b,t,i,j,d,cs=0,counT=0,k,ans=0,l=0,sum1=0,sum=0,Max,Min,num;
vector<ll>vc;
map<ll,ll>mp;
int main()
{
fast ;
// freopen("in.txt","r",stdin);
cin >> t ;
while(t--)
{
cin >> n ;
cout << 1 << ' ' << n-1 << ln ;
}
/// Comment the debugger section
}
| [
"noreply@github.com"
] | Maruf089.noreply@github.com |
62a79fc795b079f4d7ff06235ddc99dcd0b42430 | b28305dab0be0e03765c62b97bcd7f49a4f8073d | /ash/wallpaper/wallpaper_widget_controller.cc | 809500b80b531cd952e9dd2552a2039a139b46f8 | [
"BSD-3-Clause"
] | permissive | svarvel/browser-android-tabs | 9e5e27e0a6e302a12fe784ca06123e5ce090ced5 | bd198b4c7a1aca2f3e91f33005d881f42a8d0c3f | refs/heads/base-72.0.3626.105 | 2020-04-24T12:16:31.442851 | 2019-08-02T19:15:36 | 2019-08-02T19:15:36 | 171,950,555 | 1 | 2 | NOASSERTION | 2019-08-02T19:15:37 | 2019-02-21T21:47:44 | null | UTF-8 | C++ | false | false | 8,191 | cc | // Copyright (c) 2012 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 "ash/wallpaper/wallpaper_widget_controller.h"
#include <utility>
#include "ash/ash_export.h"
#include "ash/root_window_controller.h"
#include "ash/shell.h"
#include "ash/wallpaper/wallpaper_controller.h"
#include "base/scoped_observer.h"
#include "ui/aura/window.h"
#include "ui/aura/window_observer.h"
#include "ui/compositor/layer_animation_observer.h"
#include "ui/compositor/scoped_layer_animation_settings.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_observer.h"
namespace ash {
// Observes a wallpaper widget state, and notifies WallpaperWidgetController
// about relevant widget changes:
// * when widget is being destroyed
// * when the widgets implicit animations finish.
// Additionally, provides methods to manage wallpaper widget state - e.g. to
// show widget, reparent widget, or change the widget blur.
class WallpaperWidgetController::WidgetHandler
: public ui::ImplicitAnimationObserver,
public views::WidgetObserver,
public aura::WindowObserver {
public:
WidgetHandler(WallpaperWidgetController* controller, views::Widget* widget)
: controller_(controller),
widget_(widget),
parent_window_(widget->GetNativeWindow()->parent()),
widget_observer_(this),
window_observer_(this) {
DCHECK(controller_);
DCHECK(widget_);
widget_observer_.Add(widget_);
window_observer_.Add(parent_window_);
}
~WidgetHandler() override { Reset(true /*close*/); }
views::Widget* widget() { return widget_; }
// ui::ImplicitAnimationObserver:
void OnImplicitAnimationsCompleted() override {
observing_implicit_animations_ = false;
StopObservingImplicitAnimations();
controller_->WidgetFinishedAnimating(this);
}
// views::WidgetObserver:
void OnWidgetDestroying(views::Widget* widget) override {
Reset(false /*close*/);
// NOTE: Do not use |this| past this point - |controller_| will delete this
// instance.
controller_->WidgetHandlerReset(this);
}
// aura::WindowObserver:
void OnWindowBoundsChanged(aura::Window* window,
const gfx::Rect& old_bounds,
const gfx::Rect& new_bounds,
ui::PropertyChangeReason reason) override {
widget_->SetBounds(new_bounds);
}
void Show() {
ui::ScopedLayerAnimationSettings settings(
widget_->GetLayer()->GetAnimator());
observing_implicit_animations_ = true;
settings.AddObserver(this);
// When |widget_| shows, AnimateShowWindowCommon() is called to do the
// animation. Sets transition duration to 0 to avoid animating to the
// show animation's initial values.
settings.SetTransitionDuration(base::TimeDelta());
widget_->Show();
}
bool Reparent(aura::Window* new_parent) {
if (parent_window_ == new_parent)
return false;
window_observer_.Remove(parent_window_);
if (has_blur_cache_)
parent_window_->layer()->RemoveCacheRenderSurfaceRequest();
new_parent->AddChild(widget_->GetNativeWindow());
parent_window_ = widget_->GetNativeWindow()->parent();
window_observer_.Add(parent_window_);
has_blur_cache_ = widget_->GetLayer()->layer_blur() > 0.0f;
if (has_blur_cache_)
parent_window_->layer()->AddCacheRenderSurfaceRequest();
return true;
}
void SetBlur(float blur_sigma) {
widget_->GetLayer()->SetLayerBlur(blur_sigma);
const bool old_has_blur_cache = has_blur_cache_;
has_blur_cache_ = blur_sigma > 0.0f;
if (!old_has_blur_cache && has_blur_cache_) {
parent_window_->layer()->AddCacheRenderSurfaceRequest();
} else if (old_has_blur_cache && !has_blur_cache_) {
parent_window_->layer()->RemoveCacheRenderSurfaceRequest();
}
}
void StopAnimating() { widget_->GetLayer()->GetAnimator()->StopAnimating(); }
private:
void Reset(bool close) {
if (reset_)
return;
reset_ = true;
window_observer_.RemoveAll();
widget_observer_.RemoveAll();
if (observing_implicit_animations_) {
observing_implicit_animations_ = false;
StopObservingImplicitAnimations();
}
if (has_blur_cache_)
parent_window_->layer()->RemoveCacheRenderSurfaceRequest();
parent_window_ = nullptr;
if (close)
widget_->CloseNow();
widget_ = nullptr;
}
WallpaperWidgetController* controller_;
views::Widget* widget_;
aura::Window* parent_window_;
bool reset_ = false;
bool has_blur_cache_ = false;
bool observing_implicit_animations_ = false;
ScopedObserver<views::Widget, WidgetHandler> widget_observer_;
ScopedObserver<aura::Window, WidgetHandler> window_observer_;
DISALLOW_COPY_AND_ASSIGN(WidgetHandler);
};
WallpaperWidgetController::WallpaperWidgetController(
base::OnceClosure wallpaper_set_callback)
: wallpaper_set_callback_(std::move(wallpaper_set_callback)) {}
WallpaperWidgetController::~WallpaperWidgetController() = default;
views::Widget* WallpaperWidgetController::GetWidget() {
if (!active_widget_)
return nullptr;
return active_widget_->widget();
}
views::Widget* WallpaperWidgetController::GetAnimatingWidget() {
if (!animating_widget_)
return nullptr;
return animating_widget_->widget();
}
bool WallpaperWidgetController::IsAnimating() const {
return animating_widget_.get();
}
void WallpaperWidgetController::EndPendingAnimation() {
if (!IsAnimating())
return;
animating_widget_->StopAnimating();
}
void WallpaperWidgetController::AddAnimationEndCallback(
base::OnceClosure callback) {
animation_end_callbacks_.emplace_back(std::move(callback));
}
void WallpaperWidgetController::SetWallpaperWidget(views::Widget* widget,
float blur_sigma) {
DCHECK(widget);
// If there is a widget currently being shown, finish the animation and set it
// as the primary widget, before starting transition to the new wallpaper.
if (animating_widget_) {
SetAnimatingWidgetAsActive();
active_widget_->StopAnimating();
}
animating_widget_ = std::make_unique<WidgetHandler>(this, widget);
animating_widget_->SetBlur(blur_sigma);
animating_widget_->Show();
}
bool WallpaperWidgetController::Reparent(aura::Window* root_window,
int container) {
aura::Window* new_parent = root_window->GetChildById(container);
bool moved_widget = active_widget_ && active_widget_->Reparent(new_parent);
bool moved_animating_widget =
animating_widget_ && animating_widget_->Reparent(new_parent);
return moved_widget || moved_animating_widget;
}
void WallpaperWidgetController::SetWallpaperBlur(float blur_sigma) {
if (animating_widget_)
animating_widget_->SetBlur(blur_sigma);
if (active_widget_)
active_widget_->SetBlur(blur_sigma);
}
void WallpaperWidgetController::ResetWidgetsForTesting() {
animating_widget_.reset();
active_widget_.reset();
}
void WallpaperWidgetController::WidgetHandlerReset(WidgetHandler* widget) {
if (widget == active_widget_.get()) {
SetAnimatingWidgetAsActive();
if (active_widget_)
active_widget_->StopAnimating();
} else if (widget == animating_widget_.get()) {
animating_widget_.reset();
}
}
void WallpaperWidgetController::WidgetFinishedAnimating(WidgetHandler* widget) {
if (widget != animating_widget_.get())
return;
SetAnimatingWidgetAsActive();
}
void WallpaperWidgetController::SetAnimatingWidgetAsActive() {
active_widget_ = std::move(animating_widget_);
if (!active_widget_)
return;
if (wallpaper_set_callback_)
std::move(wallpaper_set_callback_).Run();
// Notify observers that animation finished.
RunAnimationEndCallbacks();
Shell::Get()->wallpaper_controller()->OnWallpaperAnimationFinished();
}
void WallpaperWidgetController::RunAnimationEndCallbacks() {
std::list<base::OnceClosure> callbacks;
animation_end_callbacks_.swap(callbacks);
for (auto& callback : callbacks)
std::move(callback).Run();
}
} // namespace ash
| [
"artem@brave.com"
] | artem@brave.com |
8819e6252b12de94972dc95f5c918bfe01856186 | 37bd9a94cddce57c8699a1ddc037b531c82eaa51 | /src/wallet/message_store.cpp | d0ca8dca8d31db5a31844257d3d718927f6e3cb3 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | Vireonidae/vireo | 607366c8f97c6878bc72721e79a04601e50b80fb | 750e16bf5c242b864acb7b37b8c10652929e5f3f | refs/heads/master | 2022-11-12T10:24:09.275176 | 2020-06-29T22:13:28 | 2020-06-29T22:38:26 | 271,019,442 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 51,319 | cpp | // Copyright (c) 2018, The Monero Project
//
// 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.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "message_store.h"
#include <boost/archive/portable_binary_oarchive.hpp>
#include <boost/archive/portable_binary_iarchive.hpp>
#include <boost/format.hpp>
#include <boost/algorithm/string.hpp>
#include <fstream>
#include <sstream>
#include "file_io_utils.h"
#include "storages/http_abstract_invoke.h"
#include "wallet_errors.h"
#include "serialization/binary_utils.h"
#include "common/base58.h"
#include "common/util.h"
#include "string_tools.h"
#undef MONERO_DEFAULT_LOG_CATEGORY
#define MONERO_DEFAULT_LOG_CATEGORY "wallet.mms"
namespace mms
{
message_store::message_store(std::unique_ptr<epee::net_utils::http::abstract_http_client> http_client) : m_transporter(std::move(http_client))
{
m_active = false;
m_auto_send = false;
m_next_message_id = 1;
m_num_authorized_signers = 0;
m_num_required_signers = 0;
m_nettype = cryptonote::network_type::UNDEFINED;
m_run = true;
}
namespace
{
// MMS options handling mirrors what "wallet2" is doing for its options, on-demand init and all
// It's not very clean to initialize Bitmessage-specific options here, but going one level further
// down still into "message_transporter" for that is a little bit too much
struct options
{
const command_line::arg_descriptor<std::string> bitmessage_address = {"bitmessage-address", mms::message_store::tr("Use PyBitmessage instance at URL <arg>"), "http://localhost:8442/"};
const command_line::arg_descriptor<std::string> bitmessage_login = {"bitmessage-login", mms::message_store::tr("Specify <arg> as username:password for PyBitmessage API"), "username:password"};
};
}
void message_store::init_options(boost::program_options::options_description& desc_params)
{
const options opts{};
command_line::add_arg(desc_params, opts.bitmessage_address);
command_line::add_arg(desc_params, opts.bitmessage_login);
}
void message_store::init(const multisig_wallet_state &state, const std::string &own_label,
const std::string &own_transport_address, uint32_t num_authorized_signers, uint32_t num_required_signers)
{
m_num_authorized_signers = num_authorized_signers;
m_num_required_signers = num_required_signers;
m_signers.clear();
m_messages.clear();
m_next_message_id = 1;
// The vector "m_signers" gets here once the required number of elements, one for each authorized signer,
// and is never changed again. The rest of the code relies on "size(m_signers) == m_num_authorized_signers"
// without further checks.
authorized_signer signer;
for (uint32_t i = 0; i < m_num_authorized_signers; ++i)
{
signer.me = signer.index == 0; // Strict convention: The very first signer is fixed as / must be "me"
m_signers.push_back(signer);
signer.index++;
}
set_signer(state, 0, own_label, own_transport_address, state.address);
m_nettype = state.nettype;
set_active(true);
m_filename = state.mms_file;
save(state);
}
void message_store::set_options(const boost::program_options::variables_map& vm)
{
const options opts{};
std::string bitmessage_address = command_line::get_arg(vm, opts.bitmessage_address);
epee::wipeable_string bitmessage_login = command_line::get_arg(vm, opts.bitmessage_login);
set_options(bitmessage_address, bitmessage_login);
}
void message_store::set_options(const std::string &bitmessage_address, const epee::wipeable_string &bitmessage_login)
{
m_transporter.set_options(bitmessage_address, bitmessage_login);
}
void message_store::set_signer(const multisig_wallet_state &state,
uint32_t index,
const boost::optional<std::string> &label,
const boost::optional<std::string> &transport_address,
const boost::optional<cryptonote::account_public_address> monero_address)
{
THROW_WALLET_EXCEPTION_IF(index >= m_num_authorized_signers, tools::error::wallet_internal_error, "Invalid signer index " + std::to_string(index));
authorized_signer &m = m_signers[index];
if (label)
{
m.label = label.get();
}
if (transport_address)
{
m.transport_address = transport_address.get();
}
if (monero_address)
{
m.monero_address_known = true;
m.monero_address = monero_address.get();
}
// Save to minimize the chance to loose that info (at least while in beta)
save(state);
}
const authorized_signer &message_store::get_signer(uint32_t index) const
{
THROW_WALLET_EXCEPTION_IF(index >= m_num_authorized_signers, tools::error::wallet_internal_error, "Invalid signer index " + std::to_string(index));
return m_signers[index];
}
bool message_store::signer_config_complete() const
{
for (uint32_t i = 0; i < m_num_authorized_signers; ++i)
{
const authorized_signer &m = m_signers[i];
if (m.label.empty() || m.transport_address.empty() || !m.monero_address_known)
{
return false;
}
}
return true;
}
// Check if all signers have a label set (as it's a requirement for starting auto-config
// by the "manager")
bool message_store::signer_labels_complete() const
{
for (uint32_t i = 0; i < m_num_authorized_signers; ++i)
{
const authorized_signer &m = m_signers[i];
if (m.label.empty())
{
return false;
}
}
return true;
}
void message_store::get_signer_config(std::string &signer_config)
{
std::stringstream oss;
boost::archive::portable_binary_oarchive ar(oss);
ar << m_signers;
signer_config = oss.str();
}
void message_store::unpack_signer_config(const multisig_wallet_state &state, const std::string &signer_config,
std::vector<authorized_signer> &signers)
{
try
{
std::stringstream iss;
iss << signer_config;
boost::archive::portable_binary_iarchive ar(iss);
ar >> signers;
}
catch (...)
{
THROW_WALLET_EXCEPTION_IF(true, tools::error::wallet_internal_error, "Invalid structure of signer config");
}
uint32_t num_signers = (uint32_t)signers.size();
THROW_WALLET_EXCEPTION_IF(num_signers != m_num_authorized_signers, tools::error::wallet_internal_error, "Wrong number of signers in config: " + std::to_string(num_signers));
}
void message_store::process_signer_config(const multisig_wallet_state &state, const std::string &signer_config)
{
// The signers in "signer_config" and the resident wallet signers are matched not by label, but
// by Monero address, and ALL labels will be set from "signer_config", even the "me" label.
// In the auto-config process as implemented now the auto-config manager is responsible for defining
// the labels, and right at the end of the process ALL wallets use the SAME labels. The idea behind this
// is preventing problems like duplicate labels and confusion (Bob choosing a label "IamAliceHonest").
// (Of course signers are free to re-define any labels they don't like AFTER auto-config.)
//
// Usually this method will be called with only the "me" signer defined in the wallet, and may
// produce unexpected behaviour if that wallet contains additional signers that have nothing to do with
// those arriving in "signer_config".
std::vector<authorized_signer> signers;
unpack_signer_config(state, signer_config, signers);
uint32_t new_index = 1;
for (uint32_t i = 0; i < m_num_authorized_signers; ++i)
{
const authorized_signer &m = signers[i];
uint32_t index;
uint32_t take_index;
bool found = get_signer_index_by_monero_address(m.monero_address, index);
if (found)
{
// Redefine existing (probably "me", under usual circumstances)
take_index = index;
}
else
{
// Add new; neglect that we may erroneously overwrite already defined signers
// (but protect "me")
take_index = new_index;
if ((new_index + 1) < m_num_authorized_signers)
{
new_index++;
}
}
authorized_signer &modify = m_signers[take_index];
modify.label = m.label; // ALWAYS set label, see comments above
if (!modify.me)
{
modify.transport_address = m.transport_address;
modify.monero_address_known = m.monero_address_known;
if (m.monero_address_known)
{
modify.monero_address = m.monero_address;
}
}
}
save(state);
}
void message_store::start_auto_config(const multisig_wallet_state &state)
{
for (uint32_t i = 0; i < m_num_authorized_signers; ++i)
{
authorized_signer &m = m_signers[i];
if (!m.me)
{
setup_signer_for_auto_config(i, create_auto_config_token(), true);
}
m.auto_config_running = true;
}
save(state);
}
// Check auto-config token string and convert to standardized form;
// Try to make it as foolproof as possible, with built-in tolerance to make up for
// errors in transmission that still leave the token recognizable.
bool message_store::check_auto_config_token(const std::string &raw_token,
std::string &adjusted_token) const
{
std::string prefix(AUTO_CONFIG_TOKEN_PREFIX);
uint32_t num_hex_digits = (AUTO_CONFIG_TOKEN_BYTES + 1) * 2;
uint32_t full_length = num_hex_digits + prefix.length();
uint32_t raw_length = raw_token.length();
std::string hex_digits;
if (raw_length == full_length)
{
// Prefix must be there; accept it in any casing
std::string raw_prefix(raw_token.substr(0, 3));
boost::algorithm::to_lower(raw_prefix);
if (raw_prefix != prefix)
{
return false;
}
hex_digits = raw_token.substr(3);
}
else if (raw_length == num_hex_digits)
{
// Accept the token without the prefix if it's otherwise ok
hex_digits = raw_token;
}
else
{
return false;
}
// Convert to strict lowercase and correct any common misspellings
boost::algorithm::to_lower(hex_digits);
std::replace(hex_digits.begin(), hex_digits.end(), 'o', '0');
std::replace(hex_digits.begin(), hex_digits.end(), 'i', '1');
std::replace(hex_digits.begin(), hex_digits.end(), 'l', '1');
// Now it must be correct hex with correct checksum, no further tolerance possible
std::string token_bytes;
if (!epee::string_tools::parse_hexstr_to_binbuff(hex_digits, token_bytes))
{
return false;
}
const crypto::hash &hash = crypto::cn_fast_hash(token_bytes.data(), token_bytes.size() - 1);
if (token_bytes[AUTO_CONFIG_TOKEN_BYTES] != hash.data[0])
{
return false;
}
adjusted_token = prefix + hex_digits;
return true;
}
// Create a new auto-config token with prefix, random 8-hex digits plus 2 checksum digits
std::string message_store::create_auto_config_token()
{
unsigned char random[AUTO_CONFIG_TOKEN_BYTES];
crypto::rand(AUTO_CONFIG_TOKEN_BYTES, random);
std::string token_bytes;
token_bytes.append((char *)random, AUTO_CONFIG_TOKEN_BYTES);
// Add a checksum because technically ANY four bytes are a valid token, and without a checksum we would send
// auto-config messages "to nowhere" after the slightest typo without knowing it
const crypto::hash &hash = crypto::cn_fast_hash(token_bytes.data(), token_bytes.size());
token_bytes += hash.data[0];
std::string prefix(AUTO_CONFIG_TOKEN_PREFIX);
return prefix + epee::string_tools::buff_to_hex_nodelimer(token_bytes);
}
// Add a message for sending "me" address data to the auto-config transport address
// that can be derived from the token and activate auto-config
size_t message_store::add_auto_config_data_message(const multisig_wallet_state &state,
const std::string &auto_config_token)
{
authorized_signer &me = m_signers[0];
me.auto_config_token = auto_config_token;
setup_signer_for_auto_config(0, auto_config_token, false);
me.auto_config_running = true;
auto_config_data data;
data.label = me.label;
data.transport_address = me.transport_address;
data.monero_address = me.monero_address;
std::stringstream oss;
boost::archive::portable_binary_oarchive ar(oss);
ar << data;
return add_message(state, 0, message_type::auto_config_data, message_direction::out, oss.str());
}
// Process a single message with auto-config data, destined for "message.signer_index"
void message_store::process_auto_config_data_message(uint32_t id)
{
// "auto_config_data" contains the label that the auto-config data sender uses for "me", but that's
// more for completeness' sake, and right now it's not used. In general, the auto-config manager
// decides/defines the labels, and right after completing auto-config ALL wallets use the SAME labels.
const message &m = get_message_ref_by_id(id);
auto_config_data data;
try
{
std::stringstream iss;
iss << m.content;
boost::archive::portable_binary_iarchive ar(iss);
ar >> data;
}
catch (...)
{
THROW_WALLET_EXCEPTION_IF(true, tools::error::wallet_internal_error, "Invalid structure of auto config data");
}
authorized_signer &signer = m_signers[m.signer_index];
// "signer.label" does NOT change, see comment above
signer.transport_address = data.transport_address;
signer.monero_address_known = true;
signer.monero_address = data.monero_address;
signer.auto_config_running = false;
}
void message_store::stop_auto_config()
{
for (uint32_t i = 0; i < m_num_authorized_signers; ++i)
{
authorized_signer &m = m_signers[i];
if (!m.auto_config_transport_address.empty())
{
// Try to delete the chan that was used for auto-config
m_transporter.delete_transport_address(m.auto_config_transport_address);
}
m.auto_config_token.clear();
m.auto_config_public_key = crypto::null_pkey;
m.auto_config_secret_key = crypto::null_skey;
m.auto_config_transport_address.clear();
m.auto_config_running = false;
}
}
void message_store::setup_signer_for_auto_config(uint32_t index, const std::string token, bool receiving)
{
// It may be a little strange to hash the textual hex digits of the auto config token into
// 32 bytes and turn that into a Monero public/secret key pair, instead of doing something
// much less complicated like directly using the underlying random 40 bits as key for a
// symmetric cipher, but everything is there already for encrypting and decrypting messages
// with such key pairs, and furthermore it would be trivial to use tokens with a different
// number of bytes.
//
// In the wallet of the auto-config manager each signer except "me" gets set its own
// auto-config parameters. In the wallet of somebody using the token to send auto-config
// data the auto-config parameters are stored in the "me" signer and taken from there
// to send that data.
THROW_WALLET_EXCEPTION_IF(index >= m_num_authorized_signers, tools::error::wallet_internal_error, "Invalid signer index " + std::to_string(index));
authorized_signer &m = m_signers[index];
m.auto_config_token = token;
crypto::hash_to_scalar(token.data(), token.size(), m.auto_config_secret_key);
crypto::secret_key_to_public_key(m.auto_config_secret_key, m.auto_config_public_key);
m.auto_config_transport_address = m_transporter.derive_transport_address(m.auto_config_token);
}
bool message_store::get_signer_index_by_monero_address(const cryptonote::account_public_address &monero_address, uint32_t &index) const
{
for (uint32_t i = 0; i < m_num_authorized_signers; ++i)
{
const authorized_signer &m = m_signers[i];
if (m.monero_address == monero_address)
{
index = m.index;
return true;
}
}
MWARNING("No authorized signer with Vireo address " << account_address_to_string(monero_address));
return false;
}
bool message_store::get_signer_index_by_label(const std::string label, uint32_t &index) const
{
for (uint32_t i = 0; i < m_num_authorized_signers; ++i)
{
const authorized_signer &m = m_signers[i];
if (m.label == label)
{
index = m.index;
return true;
}
}
MWARNING("No authorized signer with label " << label);
return false;
}
void message_store::process_wallet_created_data(const multisig_wallet_state &state, message_type type, const std::string &content)
{
switch(type)
{
case message_type::key_set:
// Result of a "prepare_multisig" command in the wallet
// Send the key set to all other signers
case message_type::additional_key_set:
// Result of a "make_multisig" command or a "exchange_multisig_keys" in the wallet in case of M/N multisig
// Send the additional key set to all other signers
case message_type::multisig_sync_data:
// Result of a "export_multisig_info" command in the wallet
// Send the sync data to all other signers
for (uint32_t i = 1; i < m_num_authorized_signers; ++i)
{
add_message(state, i, type, message_direction::out, content);
}
break;
case message_type::partially_signed_tx:
// Result of a "transfer" command in the wallet, or a "sign_multisig" command
// that did not yet result in the minimum number of signatures required
// Create a message "from me to me" as a container for the tx data
if (m_num_required_signers == 1)
{
// Probably rare, but possible: The 1 signature is already enough, correct the type
// Easier to correct here than asking all callers to detect this rare special case
type = message_type::fully_signed_tx;
}
add_message(state, 0, type, message_direction::in, content);
break;
case message_type::fully_signed_tx:
add_message(state, 0, type, message_direction::in, content);
break;
default:
THROW_WALLET_EXCEPTION(tools::error::wallet_internal_error, "Illegal message type " + std::to_string((uint32_t)type));
break;
}
}
size_t message_store::add_message(const multisig_wallet_state &state,
uint32_t signer_index, message_type type, message_direction direction,
const std::string &content)
{
message m;
m.id = m_next_message_id++;
m.type = type;
m.direction = direction;
m.content = content;
m.created = (uint64_t)time(NULL);
m.modified = m.created;
m.sent = 0;
m.signer_index = signer_index;
if (direction == message_direction::out)
{
m.state = message_state::ready_to_send;
}
else
{
m.state = message_state::waiting;
};
m.wallet_height = (uint32_t)state.num_transfer_details;
if (m.type == message_type::additional_key_set)
{
m.round = state.multisig_rounds_passed;
}
else
{
m.round = 0;
}
m.signature_count = 0; // Future expansion for signature counting when signing txs
m.hash = crypto::null_hash;
m_messages.push_back(m);
// Save for every new message right away (at least while in beta)
save(state);
MINFO(boost::format("Added %s message %s for signer %s of type %s")
% message_direction_to_string(direction) % m.id % signer_index % message_type_to_string(type));
return m_messages.size() - 1;
}
// Get the index of the message with id "id", return false if not found
bool message_store::get_message_index_by_id(uint32_t id, size_t &index) const
{
for (size_t i = 0; i < m_messages.size(); ++i)
{
if (m_messages[i].id == id)
{
index = i;
return true;
}
}
MWARNING("No message found with an id of " << id);
return false;
}
// Get the index of the message with id "id" that must exist
size_t message_store::get_message_index_by_id(uint32_t id) const
{
size_t index;
bool found = get_message_index_by_id(id, index);
THROW_WALLET_EXCEPTION_IF(!found, tools::error::wallet_internal_error, "Invalid message id " + std::to_string(id));
return index;
}
// Get the modifiable message with id "id" that must exist; private/internal use!
message& message_store::get_message_ref_by_id(uint32_t id)
{
return m_messages[get_message_index_by_id(id)];
}
// Get the message with id "id", return false if not found
// This version of the method allows to check whether id is valid without triggering an error
bool message_store::get_message_by_id(uint32_t id, message &m) const
{
size_t index;
bool found = get_message_index_by_id(id, index);
if (found)
{
m = m_messages[index];
}
return found;
}
// Get the message with id "id" that must exist
message message_store::get_message_by_id(uint32_t id) const
{
message m;
bool found = get_message_by_id(id, m);
THROW_WALLET_EXCEPTION_IF(!found, tools::error::wallet_internal_error, "Invalid message id " + std::to_string(id));
return m;
}
bool message_store::any_message_of_type(message_type type, message_direction direction) const
{
for (size_t i = 0; i < m_messages.size(); ++i)
{
if ((m_messages[i].type == type) && (m_messages[i].direction == direction))
{
return true;
}
}
return false;
}
bool message_store::any_message_with_hash(const crypto::hash &hash) const
{
for (size_t i = 0; i < m_messages.size(); ++i)
{
if (m_messages[i].hash == hash)
{
return true;
}
}
return false;
}
// Count the ids in the vector that are set i.e. not 0, while ignoring index 0
// Mostly used to check whether we have a message for each authorized signer except me,
// with the signer index used as index into 'ids'; the element at index 0, for me,
// is ignored, to make constant subtractions of 1 for indices when filling the
// vector unnecessary
size_t message_store::get_other_signers_id_count(const std::vector<uint32_t> &ids) const
{
size_t count = 0;
for (size_t i = 1 /* and not 0 */; i < ids.size(); ++i)
{
if (ids[i] != 0)
{
count++;
}
}
return count;
}
// Is in every element of vector 'ids' (except at index 0) a message id i.e. not 0?
bool message_store::message_ids_complete(const std::vector<uint32_t> &ids) const
{
return get_other_signers_id_count(ids) == (ids.size() - 1);
}
void message_store::delete_message(uint32_t id)
{
delete_transport_message(id);
size_t index = get_message_index_by_id(id);
m_messages.erase(m_messages.begin() + index);
}
void message_store::delete_all_messages()
{
for (size_t i = 0; i < m_messages.size(); ++i)
{
delete_transport_message(m_messages[i].id);
}
m_messages.clear();
}
// Make a message text, which is "attacker controlled data", reasonably safe to display
// This is mostly geared towards the safe display of notes sent by "mms note" with a "mms show" command
void message_store::get_sanitized_message_text(const message &m, std::string &sanitized_text) const
{
sanitized_text.clear();
// Restrict the size to fend of DOS-style attacks with heaps of data
size_t length = std::min(m.content.length(), (size_t)1000);
for (size_t i = 0; i < length; ++i)
{
char c = m.content[i];
if ((int)c < 32)
{
// Strip out any controls, especially ESC for getting rid of potentially dangerous
// ANSI escape sequences that a console window might interpret
c = ' ';
}
else if ((c == '<') || (c == '>'))
{
// Make XML or HTML impossible that e.g. might contain scripts that Qt might execute
// when displayed in the GUI wallet
c = ' ';
}
sanitized_text += c;
}
}
void message_store::write_to_file(const multisig_wallet_state &state, const std::string &filename)
{
std::stringstream oss;
boost::archive::portable_binary_oarchive ar(oss);
ar << *this;
std::string buf = oss.str();
crypto::chacha_key key;
crypto::generate_chacha_key(&state.view_secret_key, sizeof(crypto::secret_key), key, 1);
file_data write_file_data = {};
write_file_data.magic_string = "MMS";
write_file_data.file_version = 0;
write_file_data.iv = crypto::rand<crypto::chacha_iv>();
std::string encrypted_data;
encrypted_data.resize(buf.size());
crypto::chacha20(buf.data(), buf.size(), key, write_file_data.iv, &encrypted_data[0]);
write_file_data.encrypted_data = encrypted_data;
std::stringstream file_oss;
boost::archive::portable_binary_oarchive file_ar(file_oss);
file_ar << write_file_data;
bool success = epee::file_io_utils::save_string_to_file(filename, file_oss.str());
THROW_WALLET_EXCEPTION_IF(!success, tools::error::file_save_error, filename);
}
void message_store::read_from_file(const multisig_wallet_state &state, const std::string &filename)
{
boost::system::error_code ignored_ec;
bool file_exists = boost::filesystem::exists(filename, ignored_ec);
if (!file_exists)
{
// Simply do nothing if the file is not there; allows e.g. easy recovery
// from problems with the MMS by deleting the file
MINFO("No message store file found: " << filename);
return;
}
std::string buf;
bool success = epee::file_io_utils::load_file_to_string(filename, buf);
THROW_WALLET_EXCEPTION_IF(!success, tools::error::file_read_error, filename);
file_data read_file_data;
try
{
std::stringstream iss;
iss << buf;
boost::archive::portable_binary_iarchive ar(iss);
ar >> read_file_data;
}
catch (const std::exception &e)
{
MERROR("MMS file " << filename << " has bad structure <iv,encrypted_data>: " << e.what());
THROW_WALLET_EXCEPTION_IF(true, tools::error::file_read_error, filename);
}
crypto::chacha_key key;
crypto::generate_chacha_key(&state.view_secret_key, sizeof(crypto::secret_key), key, 1);
std::string decrypted_data;
decrypted_data.resize(read_file_data.encrypted_data.size());
crypto::chacha20(read_file_data.encrypted_data.data(), read_file_data.encrypted_data.size(), key, read_file_data.iv, &decrypted_data[0]);
try
{
std::stringstream iss;
iss << decrypted_data;
boost::archive::portable_binary_iarchive ar(iss);
ar >> *this;
}
catch (const std::exception &e)
{
MERROR("MMS file " << filename << " has bad structure: " << e.what());
THROW_WALLET_EXCEPTION_IF(true, tools::error::file_read_error, filename);
}
m_filename = filename;
}
// Save to the same file this message store was loaded from
// Called after changes deemed "important", to make it less probable to lose messages in case of
// a crash; a better and long-term solution would of course be to use LMDB ...
void message_store::save(const multisig_wallet_state &state)
{
if (!m_filename.empty())
{
write_to_file(state, m_filename);
}
}
bool message_store::get_processable_messages(const multisig_wallet_state &state,
bool force_sync, std::vector<processing_data> &data_list, std::string &wait_reason)
{
uint32_t wallet_height = (uint32_t)state.num_transfer_details;
data_list.clear();
wait_reason.clear();
// In all scans over all messages looking for complete sets (1 message for each signer),
// if there are duplicates, the OLDEST of them is taken. This may not play a role with
// any of the current message types, but may with future ones, and it's probably a good
// idea to have a clear and somewhat defensive strategy.
std::vector<uint32_t> auto_config_messages(m_num_authorized_signers, 0);
bool any_auto_config = false;
for (size_t i = 0; i < m_messages.size(); ++i)
{
message &m = m_messages[i];
if ((m.type == message_type::auto_config_data) && (m.state == message_state::waiting))
{
if (auto_config_messages[m.signer_index] == 0)
{
auto_config_messages[m.signer_index] = m.id;
any_auto_config = true;
}
// else duplicate auto config data, ignore
}
}
if (any_auto_config)
{
bool auto_config_complete = message_ids_complete(auto_config_messages);
if (auto_config_complete)
{
processing_data data;
data.processing = message_processing::process_auto_config_data;
data.message_ids = auto_config_messages;
data.message_ids.erase(data.message_ids.begin());
data_list.push_back(data);
return true;
}
else
{
wait_reason = tr("Auto-config cannot proceed because auto config data from other signers is not complete");
return false;
// With ANY auto config data present but not complete refuse to check for any
// other processing. Manually delete those messages to abort such an auto config
// phase if needed.
}
}
// Any signer config that arrived will be processed right away, regardless of other things that may wait
for (size_t i = 0; i < m_messages.size(); ++i)
{
message &m = m_messages[i];
if ((m.type == message_type::signer_config) && (m.state == message_state::waiting))
{
processing_data data;
data.processing = message_processing::process_signer_config;
data.message_ids.push_back(m.id);
data_list.push_back(data);
return true;
}
}
// ALL of the following processings depend on the signer info being complete
if (!signer_config_complete())
{
wait_reason = tr("The signer config is not complete.");
return false;
}
if (!state.multisig)
{
if (!any_message_of_type(message_type::key_set, message_direction::out))
{
// With the own key set not yet ready we must do "prepare_multisig" first;
// Key sets from other signers may be here already, but if we process them now
// the wallet will go multisig too early: we can't produce our own key set any more!
processing_data data;
data.processing = message_processing::prepare_multisig;
data_list.push_back(data);
return true;
}
// Ids of key set messages per signer index, to check completeness
// Naturally, does not care about the order of the messages and is trivial to secure against
// key sets that were received more than once
// With full M/N multisig now possible consider only key sets of the right round, i.e.
// with not yet multisig the only possible round 0
std::vector<uint32_t> key_set_messages(m_num_authorized_signers, 0);
for (size_t i = 0; i < m_messages.size(); ++i)
{
message &m = m_messages[i];
if ((m.type == message_type::key_set) && (m.state == message_state::waiting)
&& (m.round == 0))
{
if (key_set_messages[m.signer_index] == 0)
{
key_set_messages[m.signer_index] = m.id;
}
// else duplicate key set, ignore
}
}
bool key_sets_complete = message_ids_complete(key_set_messages);
if (key_sets_complete)
{
// Nothing else can be ready to process earlier than this, ignore everything else and give back
processing_data data;
data.processing = message_processing::make_multisig;
data.message_ids = key_set_messages;
data.message_ids.erase(data.message_ids.begin());
data_list.push_back(data);
return true;
}
else
{
wait_reason = tr("Wallet can't go multisig because key sets from other signers are missing or not complete.");
return false;
}
}
if (state.multisig && !state.multisig_is_ready)
{
// In the case of M/N multisig the call 'wallet2::multisig' returns already true
// after "make_multisig" but with calls to "exchange_multisig_keys" still needed, and
// sets the parameter 'ready' to false to document this particular "in-between" state.
// So what may be possible here, with all necessary messages present, is a call to
// "exchange_multisig_keys".
// Consider only messages belonging to the next round to do, which has the number
// "state.multisig_rounds_passed".
std::vector<uint32_t> additional_key_set_messages(m_num_authorized_signers, 0);
for (size_t i = 0; i < m_messages.size(); ++i)
{
message &m = m_messages[i];
if ((m.type == message_type::additional_key_set) && (m.state == message_state::waiting)
&& (m.round == state.multisig_rounds_passed))
{
if (additional_key_set_messages[m.signer_index] == 0)
{
additional_key_set_messages[m.signer_index] = m.id;
}
// else duplicate key set, ignore
}
}
bool key_sets_complete = message_ids_complete(additional_key_set_messages);
if (key_sets_complete)
{
processing_data data;
data.processing = message_processing::exchange_multisig_keys;
data.message_ids = additional_key_set_messages;
data.message_ids.erase(data.message_ids.begin());
data_list.push_back(data);
return true;
}
else
{
wait_reason = tr("Wallet can't start another key exchange round because key sets from other signers are missing or not complete.");
return false;
}
}
// Properly exchanging multisig sync data is easiest and most transparent
// for the user if a wallet sends its own data first and processes any received
// sync data afterwards so that's the order that the MMS enforces here.
// (Technically, it seems to work also the other way round.)
//
// To check whether a NEW round of syncing is necessary the MMS works with a
// "wallet state": new state means new syncing needed.
//
// The MMS monitors the "wallet state" by recording "wallet heights" as
// numbers of transfers present in a wallet at the time of message creation. While
// not watertight, this quite simple scheme should already suffice to trigger
// and orchestrate a sensible exchange of sync data.
if (state.has_multisig_partial_key_images || force_sync)
{
// Sync is necessary and not yet completed: Processing of transactions
// will only be possible again once properly synced
// Check first whether we generated already OUR sync info; take note of
// any processable sync info from other signers on the way in case we need it
bool own_sync_data_created = false;
std::vector<uint32_t> sync_messages(m_num_authorized_signers, 0);
for (size_t i = 0; i < m_messages.size(); ++i)
{
message &m = m_messages[i];
if ((m.type == message_type::multisig_sync_data) && (force_sync || (m.wallet_height == wallet_height)))
// It's data for the same "round" of syncing, on the same "wallet height", therefore relevant
// With "force_sync" take ANY waiting sync data, maybe it will work out
{
if (m.direction == message_direction::out)
{
own_sync_data_created = true;
// Ignore whether sent already or not, and assume as complete if several other signers there
}
else if ((m.direction == message_direction::in) && (m.state == message_state::waiting))
{
if (sync_messages[m.signer_index] == 0)
{
sync_messages[m.signer_index] = m.id;
}
// else duplicate sync message, ignore
}
}
}
if (!own_sync_data_created)
{
// As explained above, creating sync data BEFORE processing such data from
// other signers reliably works, so insist on that here
processing_data data;
data.processing = message_processing::create_sync_data;
data_list.push_back(data);
return true;
}
uint32_t id_count = (uint32_t)get_other_signers_id_count(sync_messages);
// Do we have sync data from ALL other signers?
bool all_sync_data = id_count == (m_num_authorized_signers - 1);
// Do we have just ENOUGH sync data to have a minimal viable sync set?
// In cases like 2/3 multisig we don't need messages from ALL other signers, only
// from enough of them i.e. num_required_signers minus 1 messages
bool enough_sync_data = id_count >= (m_num_required_signers - 1);
bool sync = false;
wait_reason = tr("Syncing not done because multisig sync data from other signers are missing or not complete.");
if (all_sync_data)
{
sync = true;
}
else if (enough_sync_data)
{
if (force_sync)
{
sync = true;
}
else
{
// Don't sync, but give a hint how this minimal set COULD be synced if really wanted
wait_reason += (boost::format("\nUse \"mms next sync\" if you want to sync with just %s out of %s authorized signers and transact just with them")
% (m_num_required_signers - 1) % (m_num_authorized_signers - 1)).str();
}
}
if (sync)
{
processing_data data;
data.processing = message_processing::process_sync_data;
for (size_t i = 0; i < sync_messages.size(); ++i)
{
uint32_t id = sync_messages[i];
if (id != 0)
{
data.message_ids.push_back(id);
}
}
data_list.push_back(data);
return true;
}
else
{
// We can't proceed to any transactions until we have synced; "wait_reason" already set above
return false;
}
}
bool waiting_found = false;
bool note_found = false;
bool sync_data_found = false;
for (size_t i = 0; i < m_messages.size(); ++i)
{
message &m = m_messages[i];
if (m.state == message_state::waiting)
{
waiting_found = true;
switch (m.type)
{
case message_type::fully_signed_tx:
{
// We can either submit it ourselves, or send it to any other signer for submission
processing_data data;
data.processing = message_processing::submit_tx;
data.message_ids.push_back(m.id);
data_list.push_back(data);
data.processing = message_processing::send_tx;
for (uint32_t j = 1; j < m_num_authorized_signers; ++j)
{
data.receiving_signer_index = j;
data_list.push_back(data);
}
return true;
}
case message_type::partially_signed_tx:
{
if (m.signer_index == 0)
{
// We started this ourselves, or signed it but with still signatures missing:
// We can send it to any other signer for signing / further signing
// In principle it does not make sense to send it back to somebody who
// already signed, but the MMS does not / not yet keep track of that,
// because that would be somewhat complicated.
processing_data data;
data.processing = message_processing::send_tx;
data.message_ids.push_back(m.id);
for (uint32_t j = 1; j < m_num_authorized_signers; ++j)
{
data.receiving_signer_index = j;
data_list.push_back(data);
}
return true;
}
else
{
// Somebody else sent this to us: We can sign it
// It would be possible to just pass it on, but that's not directly supported here
processing_data data;
data.processing = message_processing::sign_tx;
data.message_ids.push_back(m.id);
data_list.push_back(data);
return true;
}
}
case message_type::note:
note_found = true;
break;
case message_type::multisig_sync_data:
sync_data_found = true;
break;
default:
break;
}
}
}
if (waiting_found)
{
wait_reason = tr("There are waiting messages, but nothing is ready to process under normal circumstances");
if (sync_data_found)
{
wait_reason += tr("\nUse \"mms next sync\" if you want to force processing of the waiting sync data");
}
if (note_found)
{
wait_reason += tr("\nUse \"mms note\" to display the waiting notes");
}
}
else
{
wait_reason = tr("There are no messages waiting to be processed.");
}
return false;
}
void message_store::set_messages_processed(const processing_data &data)
{
for (size_t i = 0; i < data.message_ids.size(); ++i)
{
set_message_processed_or_sent(data.message_ids[i]);
}
}
void message_store::set_message_processed_or_sent(uint32_t id)
{
message &m = get_message_ref_by_id(id);
if (m.state == message_state::waiting)
{
// So far a fairly cautious and conservative strategy: Only delete from Bitmessage
// when fully processed (and e.g. not already after reception and writing into
// the message store file)
delete_transport_message(id);
m.state = message_state::processed;
}
else if (m.state == message_state::ready_to_send)
{
m.state = message_state::sent;
}
m.modified = (uint64_t)time(NULL);
}
void message_store::encrypt(crypto::public_key public_key, const std::string &plaintext,
std::string &ciphertext, crypto::public_key &encryption_public_key, crypto::chacha_iv &iv)
{
crypto::secret_key encryption_secret_key;
crypto::generate_keys(encryption_public_key, encryption_secret_key);
crypto::key_derivation derivation;
bool success = crypto::generate_key_derivation(public_key, encryption_secret_key, derivation);
THROW_WALLET_EXCEPTION_IF(!success, tools::error::wallet_internal_error, "Failed to generate key derivation for message encryption");
crypto::chacha_key chacha_key;
crypto::generate_chacha_key(&derivation, sizeof(derivation), chacha_key, 1);
iv = crypto::rand<crypto::chacha_iv>();
ciphertext.resize(plaintext.size());
crypto::chacha20(plaintext.data(), plaintext.size(), chacha_key, iv, &ciphertext[0]);
}
void message_store::decrypt(const std::string &ciphertext, const crypto::public_key &encryption_public_key, const crypto::chacha_iv &iv,
const crypto::secret_key &view_secret_key, std::string &plaintext)
{
crypto::key_derivation derivation;
bool success = crypto::generate_key_derivation(encryption_public_key, view_secret_key, derivation);
THROW_WALLET_EXCEPTION_IF(!success, tools::error::wallet_internal_error, "Failed to generate key derivation for message decryption");
crypto::chacha_key chacha_key;
crypto::generate_chacha_key(&derivation, sizeof(derivation), chacha_key, 1);
plaintext.resize(ciphertext.size());
crypto::chacha20(ciphertext.data(), ciphertext.size(), chacha_key, iv, &plaintext[0]);
}
void message_store::send_message(const multisig_wallet_state &state, uint32_t id)
{
message &m = get_message_ref_by_id(id);
const authorized_signer &me = m_signers[0];
const authorized_signer &receiver = m_signers[m.signer_index];
transport_message dm;
crypto::public_key public_key;
dm.timestamp = (uint64_t)time(NULL);
dm.subject = "MMS V0 " + tools::get_human_readable_timestamp(dm.timestamp);
dm.source_transport_address = me.transport_address;
dm.source_monero_address = me.monero_address;
if (m.type == message_type::auto_config_data)
{
// Encrypt with the public key derived from the auto-config token, and send to the
// transport address likewise derived from that token
public_key = me.auto_config_public_key;
dm.destination_transport_address = me.auto_config_transport_address;
// The destination Monero address is not yet known
memset(&dm.destination_monero_address, 0, sizeof(cryptonote::account_public_address));
}
else
{
// Encrypt with the receiver's view public key
public_key = receiver.monero_address.m_view_public_key;
const authorized_signer &receiver = m_signers[m.signer_index];
dm.destination_monero_address = receiver.monero_address;
dm.destination_transport_address = receiver.transport_address;
}
encrypt(public_key, m.content, dm.content, dm.encryption_public_key, dm.iv);
dm.type = (uint32_t)m.type;
dm.hash = crypto::cn_fast_hash(dm.content.data(), dm.content.size());
dm.round = m.round;
crypto::generate_signature(dm.hash, me.monero_address.m_view_public_key, state.view_secret_key, dm.signature);
m_transporter.send_message(dm);
m.state=message_state::sent;
m.sent= (uint64_t)time(NULL);
}
bool message_store::check_for_messages(const multisig_wallet_state &state, std::vector<message> &messages)
{
m_run.store(true, std::memory_order_relaxed);
const authorized_signer &me = m_signers[0];
std::vector<std::string> destinations;
destinations.push_back(me.transport_address);
for (uint32_t i = 1; i < m_num_authorized_signers; ++i)
{
const authorized_signer &m = m_signers[i];
if (m.auto_config_running)
{
destinations.push_back(m.auto_config_transport_address);
}
}
std::vector<transport_message> transport_messages;
bool r = m_transporter.receive_messages(destinations, transport_messages);
if (!m_run.load(std::memory_order_relaxed))
{
// Stop was called, don't waste time processing the messages
// (but once started processing them, don't react to stop request anymore, avoid receiving them "partially)"
return false;
}
bool new_messages = false;
for (size_t i = 0; i < transport_messages.size(); ++i)
{
transport_message &rm = transport_messages[i];
if (any_message_with_hash(rm.hash))
{
// Already seen, do not take again
}
else
{
uint32_t sender_index;
bool take = false;
message_type type = static_cast<message_type>(rm.type);
crypto::secret_key decrypt_key = state.view_secret_key;
if (type == message_type::auto_config_data)
{
// Find out which signer sent it by checking which auto config transport address
// the message was sent to
for (uint32_t i = 1; i < m_num_authorized_signers; ++i)
{
const authorized_signer &m = m_signers[i];
if (m.auto_config_transport_address == rm.destination_transport_address)
{
take = true;
sender_index = i;
decrypt_key = m.auto_config_secret_key;
break;
}
}
}
else if (type == message_type::signer_config)
{
// Typically we can't check yet whether we know the sender, so take from any
// and pretend it's from "me" because we might have nothing else yet
take = true;
sender_index = 0;
}
else
{
// Only accept from senders that are known as signer here, otherwise just ignore
take = get_signer_index_by_monero_address(rm.source_monero_address, sender_index);
}
if (take && (type != message_type::auto_config_data))
{
// If the destination address is known, check it as well; this additional filter
// allows using the same transport address for multiple signers
take = rm.destination_monero_address == me.monero_address;
}
if (take)
{
crypto::hash actual_hash = crypto::cn_fast_hash(rm.content.data(), rm.content.size());
THROW_WALLET_EXCEPTION_IF(actual_hash != rm.hash, tools::error::wallet_internal_error, "Message hash mismatch");
bool signature_valid = crypto::check_signature(actual_hash, rm.source_monero_address.m_view_public_key, rm.signature);
THROW_WALLET_EXCEPTION_IF(!signature_valid, tools::error::wallet_internal_error, "Message signature not valid");
std::string plaintext;
decrypt(rm.content, rm.encryption_public_key, rm.iv, decrypt_key, plaintext);
size_t index = add_message(state, sender_index, (message_type)rm.type, message_direction::in, plaintext);
message &m = m_messages[index];
m.hash = rm.hash;
m.transport_id = rm.transport_id;
m.sent = rm.timestamp;
m.round = rm.round;
m.signature_count = rm.signature_count;
messages.push_back(m);
new_messages = true;
}
}
}
return new_messages;
}
void message_store::delete_transport_message(uint32_t id)
{
const message &m = get_message_by_id(id);
if (!m.transport_id.empty())
{
m_transporter.delete_message(m.transport_id);
}
}
std::string message_store::account_address_to_string(const cryptonote::account_public_address &account_address) const
{
return get_account_address_as_str(m_nettype, false, account_address);
}
const char* message_store::message_type_to_string(message_type type)
{
switch (type)
{
case message_type::key_set:
return tr("key set");
case message_type::additional_key_set:
return tr("additional key set");
case message_type::multisig_sync_data:
return tr("multisig sync data");
case message_type::partially_signed_tx:
return tr("partially signed tx");
case message_type::fully_signed_tx:
return tr("fully signed tx");
case message_type::note:
return tr("note");
case message_type::signer_config:
return tr("signer config");
case message_type::auto_config_data:
return tr("auto-config data");
default:
return tr("unknown message type");
}
}
const char* message_store::message_direction_to_string(message_direction direction)
{
switch (direction)
{
case message_direction::in:
return tr("in");
case message_direction::out:
return tr("out");
default:
return tr("unknown message direction");
}
}
const char* message_store::message_state_to_string(message_state state)
{
switch (state)
{
case message_state::ready_to_send:
return tr("ready to send");
case message_state::sent:
return tr("sent");
case message_state::waiting:
return tr("waiting");
case message_state::processed:
return tr("processed");
case message_state::cancelled:
return tr("cancelled");
default:
return tr("unknown message state");
}
}
// Convert a signer to string suitable for a column in a list, with 'max_width'
// Format: label: transport_address
std::string message_store::signer_to_string(const authorized_signer &signer, uint32_t max_width)
{
std::string s = "";
s.reserve(max_width);
uint32_t avail = max_width;
uint32_t label_len = signer.label.length();
if (label_len > avail)
{
s.append(signer.label.substr(0, avail - 2));
s.append("..");
return s;
}
s.append(signer.label);
avail -= label_len;
uint32_t transport_addr_len = signer.transport_address.length();
if ((transport_addr_len > 0) && (avail > 10))
{
s.append(": ");
avail -= 2;
if (transport_addr_len <= avail)
{
s.append(signer.transport_address);
}
else
{
s.append(signer.transport_address.substr(0, avail-2));
s.append("..");
}
}
return s;
}
}
| [
"cam@camthegeek.net"
] | cam@camthegeek.net |
fdff192bbe4c7dda9e0d42dfeeef939d4304a3d1 | 52896a1d66e157f966105bee46cf8a7e48c26df2 | /src/renderer.h | 41718bdb6c8da498e335cb7fba120b9f1f8826b8 | [] | no_license | AntonHakansson/c_physics | 9b86027263a1d3c2900806069308e7ecc5ca4c5b | fc8a71f7ba04287c9f69010af633ecfc1a995602 | refs/heads/main | 2023-08-19T10:08:41.625908 | 2021-09-23T16:34:48 | 2021-09-23T16:40:52 | 349,856,320 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,122 | h | #pragma once
#include <raylib.h>
#include "language_layer.h"
constexpr u32 MAX_DRAW_CALLS = 1024;
enum RENDER_COMMAND_TYPE {
FILLED_RECT,
SCALED_TEX_RECT,
CIRCLE,
LINE,
TEXT,
MAX_RENDER_COMMANDS,
};
struct RenderCommand {
RENDER_COMMAND_TYPE type;
u8 flags;
union {
// NOTE(anton) : render command RECT
struct {
v2 pos;
v2 size;
Color c;
f32 angle;
} rect;
// NOTE(anton) : render command RECT
struct {
v2 pos;
v2 size;
Texture2D texture;
Color tint;
f32 angle;
} texture;
// NOTE(anton) : render command CIRCLE
struct {
v2 pos;
f32 radius;
Color c;
} circle;
// NOTE(anton) : render command LINE
struct {
v2 start_pos;
v2 end_pos;
Color c;
} line;
// NOTE(anton) : render command TEXT
struct {
v2 pos;
Color c;
f32 font_scale;
const char *text;
} text;
};
};
struct Renderer {
RenderCommand render_commands[MAX_DRAW_CALLS];
u32 render_commands_count;
Camera2D world_camera;
u32 left, right, top, bottom;
};
| [
"anton.hakansson98@gmail.com"
] | anton.hakansson98@gmail.com |
1e2b5e7193f95d59054ec19ef1aeed89ec11660a | 5bae8b53fed74f9e093f2fdedc08485182aa8d47 | /src/MG5_aMCNLO/Commons/read_slha_MEKD.cc | 39568adbde5c02086a008755783c3c5af76d7834 | [] | no_license | odysei/MEKD | eac098ea7241f287dde1fb625aaaeb7138823d8b | 1614a2192a1e7725cc96e3cb773b02f62ac3c52b | refs/heads/master | 2020-12-25T17:14:26.875430 | 2018-12-01T19:31:44 | 2018-12-01T19:31:44 | 10,505,338 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,302 | cc | #ifndef READ_SLHA_MEKD_CC
#define READ_SLHA_MEKD_CC
#include <algorithm>
#include <iostream>
#include <fstream>
#include "read_slha_MEKD.h"
using namespace std;
void SLHABlock_MEKD::set_entry(vector<int> indices, complex<double> value)
{
if (_entries.size() == 0)
_indices = indices.size();
else if (indices.size() != _indices)
throw "Wrong number of indices in set_entry";
_entries[indices] = value;
}
complex<double> SLHABlock_MEKD::get_entry(vector<int> indices,
complex<double> def_val)
{
if (_entries.find(indices) == _entries.end()) {
cout << "Warning: No such entry in " << _name
<< ", using default value " << def_val << endl;
return def_val;
}
return _entries[indices];
}
void SLHAReader_MEKD::read_slha_file(string file_name)
{
ifstream param_card;
param_card.open(file_name.c_str(), ifstream::in);
if (!param_card.good()) {
cerr << "Error while opening param card\n"; /// Old-school warning
throw "Error while opening param card";
}
// cout << "Opened slha file " << file_name << " for reading" << endl;
char buf[200];
string line;
string block("");
while (param_card.good()) {
param_card.getline(buf, 200);
line = buf;
// Change to lowercase
transform(line.begin(), line.end(), line.begin(),
(int (*)(int))tolower);
if (line != "" && line[0] != '#') {
if (block != "") {
// Look for double index blocks
double dindex1, dindex2;
complex<double> value;
stringstream linestr2(line);
if (linestr2 >> dindex1 >> dindex2 >> value &&
dindex1 == int(dindex1) and dindex2 == int(dindex2)) {
vector<int> indices;
indices.push_back(int(dindex1));
indices.push_back(int(dindex2));
set_block_entry(block, indices, value);
// Done with this line, read next
continue;
}
stringstream linestr1(line);
// Look for single index blocks
if (linestr1 >> dindex1 >> value && dindex1 == int(dindex1)) {
vector<int> indices;
indices.push_back(int(dindex1));
set_block_entry(block, indices, value);
// Done with this line, read next
continue;
}
}
// Look for block
if (line.find("block ") != line.npos) {
line = line.substr(6);
// Get rid of spaces between block and block name
while (line[0] == ' ')
line = line.substr(1);
// Now find end of block name
size_t space_pos = line.find(' ');
if (space_pos != line.npos)
line = line.substr(0, space_pos);
block = line;
continue;
}
// Look for decay
if (line.find("decay ") == 0) {
line = line.substr(6);
block = "";
stringstream linestr(line);
int pdg_code;
complex<double> value;
if (linestr >> pdg_code >> value)
set_block_entry("decay", pdg_code, value);
else
cout << "Warning: Wrong format for decay block " << line
<< endl;
continue;
}
}
}
if (_blocks.size() == 0)
throw "No information read from SLHA card";
param_card.close();
}
complex<double> SLHAReader_MEKD::get_block_entry(string block_name,
vector<int> indices,
complex<double> def_val)
{
if (_blocks.find(block_name) == _blocks.end()) {
cout << "No such block " << block_name << ", using default value "
<< def_val << endl;
return def_val;
}
return _blocks[block_name].get_entry(indices);
}
complex<double> SLHAReader_MEKD::get_block_entry(string block_name, int index,
complex<double> def_val)
{
vector<int> indices;
indices.push_back(index);
return get_block_entry(block_name, indices, def_val);
}
void SLHAReader_MEKD::set_block_entry(string block_name, vector<int> indices,
complex<double> value)
{
if (_blocks.find(block_name) == _blocks.end()) {
SLHABlock_MEKD block(block_name);
_blocks[block_name] = block;
}
_blocks[block_name].set_entry(indices, value);
/* cout << "Set block " << block_name << " entry ";
for (int i=0;i < indices.size();i++)
cout << indices[i] << " ";
cout << "to " << _blocks[block_name].get_entry(indices) << endl;*/
}
void SLHAReader_MEKD::set_block_entry(string block_name, int index,
complex<double> value)
{
vector<int> indices;
indices.push_back(index);
set_block_entry(block_name, indices, value);
}
#endif
| [
"odysei@gmail.com"
] | odysei@gmail.com |
5caae901f14254a8128f9b5cd9b6ccd98a037612 | 4255fcba4718c888eb32e4530b736ef037882d28 | /APIs_Drivers/DigitalOut_ex_1/main.cpp | 6ddc38d6f7c0a63b167b6b048932d80350173bf6 | [
"Apache-2.0"
] | permissive | ARMmbed/mbed-os-examples-docs_only | e2fb92478a847c2578c7950a510ae2730b3eccc4 | d955550449cc6ac7d1151550f2a058803a2986ee | refs/heads/master | 2023-07-05T06:05:59.974508 | 2021-09-19T22:47:14 | 2021-09-19T22:47:14 | 152,603,832 | 6 | 28 | Apache-2.0 | 2021-09-19T22:47:15 | 2018-10-11T14:19:44 | C++ | UTF-8 | C++ | false | false | 643 | cpp | /*
* Copyright (c) 2006-2020 Arm Limited and affiliates.
* SPDX-License-Identifier: Apache-2.0
*/
#include "mbed.h"
DigitalOut myled(LED1);
int main()
{
// check that myled object is initialized and connected to a pin
if (myled.is_connected()) {
printf("myled is initialized and connected!\n\r");
}
// Blink LED
while (1) {
myled = 1; // set LED1 pin to high
printf("myled = %d \n\r", (uint8_t)myled);
ThisThread::sleep_for(500);
myled.write(0); // set LED1 pin to low
printf("myled = %d \n\r", myled.read());
ThisThread::sleep_for(500);
}
}
| [
"maciej.bocianski@gmail.com"
] | maciej.bocianski@gmail.com |
7f33e43d78ed28a2063adc7bda8920f31b67abb2 | 31d6eddaa5c6b62a7591fe29578ceb537cd7d40f | /pub/Publisher.cpp | 7347dd0fec0cab4bb11541a2d02d0f01c252be85 | [] | no_license | StudyforLife/MyIce | 091a66ccddcb37a3967f3a87e276ad263e2cf34f | 7e848afad5cafd2c220ecac27cb3ec656325d0eb | refs/heads/master | 2020-04-11T02:51:38.891815 | 2018-12-16T10:48:01 | 2018-12-16T10:48:01 | 161,458,988 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,541 | cpp | #include<iostream>
#include<IceStorm/IceStorm.h>
#include<Ice/Ice.h>
#include<sstream>
#include<vector>
#include<time.h>
#include<cstdio>
#include<sys/types.h>
#include<sys/stat.h>
#include"Station.h"
using namespace std;
using namespace StationDemo;
myTopicList create_topic()
{
myTopicList m;
int size=100;
stringstream ss;
m.reserve(size);
for(int i=1;i<=size;i++)
{
ss<<i;
string s="主题"+ss.str();
m.push_back(s);
ss.clear();
ss.str("");
}
return m;
}
vector<int> create_Data(myTopicList m)
{
vector<int> v;
int sum=0;
for(int i=1;i<=m.size();i++)
{
sum+=i;
v.push_back(sum);
}
return v;
}
int main(int argc,char* argv[])
{
myTopicList m=create_topic();
Ice::CommunicatorPtr ic;
//读取配置文件
Ice::InitializationData initData;
initData.properties=Ice::createProperties();
initData.properties->load("Config/config.client");
ic=Ice::initialize(initData);
Ice::ObjectPrx obj=ic->propertyToProxy("client.proxy");
/*
//直接初始化
ic=Ice::initialize();
Ice::ObjectPrx obj=ic->stringToProxy("StationTest/TopicManager:default -h localhost -p 9999");*/
IceStorm::TopicManagerPrx topicManager=IceStorm::TopicManagerPrx::checkedCast(obj);
//存储主题代理
IceStorm::TopicPrx TopicList[m.size()];
for(int i=0;i<m.size();i++)
{
try{
TopicList[i]=topicManager->retrieve(m[i]);
}catch(const IceStorm::NoSuchTopic&){
try{
TopicList[i]=topicManager->create(m[i]);
}catch(const IceStorm::TopicExists&){
//error
}
}
}
StationMessagePrx station[m.size()];
for(int j=0;j<m.size();j++)
{
Ice::ObjectPrx pub=TopicList[j]->getPublisher();
station[j]=StationMessagePrx::uncheckedCast(pub);
}
//操作调用
time_t t;
char str[255]={};
vector<int> v1=create_Data(m);
Message msg;
stringstream ss;
msg.flag=0;
while(true)
{
msg.flag+=1;
for(int i=0;i<m.size();i++)
{
time(&t);
tm* p=localtime(&t);
sprintf(str,"%4d/%d/%d-%d:%d:%d",p->tm_year+1900,\
p->tm_mon+1,p->tm_mday,p->tm_hour,p->tm_min,p->tm_sec);
string message="江陵路-近江-远江-边疆-新疆-下沙-上沙-中沙-自定义消息";
msg.tpName=m[i];
ss<<v1[i];
msg.data=ss.str()+": "+message;
ss.clear();
ss.str("");
msg.time=str;
int size1=msg.data.length()+msg.tpName.length()+msg.time.length();
cout<<"数据大小:"<<size1<<endl;
station[i]->getMsg(msg);
usleep(30000);
//sleep(5);
}
cout<<"flag: "<<msg.flag<<endl;
while(msg.flag>=1000)
{
msg.flag=0;
}
}
if(ic)
ic->destroy();
}
| [
"840431307@qq.com"
] | 840431307@qq.com |
6094c04c1b4f7ff3716e230b238a20611bc1e4c7 | 9e882dab9db411cc1c24f3dc82c4eb734c956130 | /src/ParticlePhysics/MuonTomography/Hit.h | a5b071a15019092fc356cc541701379b5e16be93 | [] | no_license | OpenCMT/uLib | 8d4a2541fb60e596c07c139a151ae5cc2eb97931 | b7c775ee3510296b7cc1a29de3f5443ce518a68d | refs/heads/master | 2023-04-09T14:04:22.232237 | 2023-02-22T10:20:56 | 2023-02-22T10:20:56 | 36,926,725 | 4 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 1,630 | h | /*//////////////////////////////////////////////////////////////////////////////
// CMT Cosmic Muon Tomography project //////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
Copyright (c) 2014, Universita' degli Studi di Padova, INFN sez. di Padova
All rights reserved
Authors: Andrea Rigoni Garola < andrea.rigoni@pd.infn.it >
------------------------------------------------------------------
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3.0 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library.
//////////////////////////////////////////////////////////////////////////////*/
#ifndef U_PPMUTOM_HIT_H
#define U_PPMUTOM_HIT_H
#include <Core/Types.h>
#include <Math/Dense.h>
namespace uLib {
template <typename Type, typename Code>
class Hit {
Code m_Code;
Type m_DriftTime;
};
class HitMC {
public:
virtual Id_t GetChamber() = 0;
virtual Vector3f GetPosition() = 0;
virtual Scalarf GetDritfTime() = 0;
protected:
virtual ~HitMC() {}
};
} // uLib
#endif // HIT_H
| [
"andrea.rigoni@pd.infn.it"
] | andrea.rigoni@pd.infn.it |
fe20a07562f747220d02cd166472b964841d9ab1 | 33b567f6828bbb06c22a6fdf903448bbe3b78a4f | /opencascade/TColgp_HArray1OfPnt2d.hxx | ff851b63fc00c2db908b1562e14bede163b46782 | [
"Apache-2.0"
] | permissive | CadQuery/OCP | fbee9663df7ae2c948af66a650808079575112b5 | b5cb181491c9900a40de86368006c73f169c0340 | refs/heads/master | 2023-07-10T18:35:44.225848 | 2023-06-12T18:09:07 | 2023-06-12T18:09:07 | 228,692,262 | 64 | 28 | Apache-2.0 | 2023-09-11T12:40:09 | 2019-12-17T20:02:11 | C++ | UTF-8 | C++ | false | false | 997 | hxx | // Created on: 1993-03-10
// Created by: Philippe DAUTRY
// Copyright (c) 1993-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef TColgp_HArray1OfPnt2d_HeaderFile
#define TColgp_HArray1OfPnt2d_HeaderFile
#include <gp_Pnt2d.hxx>
#include <TColgp_Array1OfPnt2d.hxx>
#include <NCollection_DefineHArray1.hxx>
DEFINE_HARRAY1(TColgp_HArray1OfPnt2d, TColgp_Array1OfPnt2d)
#endif
| [
"adam.jan.urbanczyk@gmail.com"
] | adam.jan.urbanczyk@gmail.com |
582b0b8098367699d94e3d818a7c325ae44110e6 | 04579fb7426b9cf8d7b3877334bc927bb0c79e87 | /Source/TestingGrounds/AI/PatrolRoute.h | e644b210412a43b10ee3212c2f08c68a66fad081 | [] | no_license | SeanSiders/TestingGrounds | ad3fab8ce9b3b9c5df7e1ecea6effc54f8dde511 | 0335f849227ed3f123021094d9ed4e0ccff3893a | refs/heads/master | 2022-01-18T16:38:32.225650 | 2022-01-13T19:35:19 | 2022-01-13T19:35:19 | 170,135,997 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 430 | h | #pragma once
#include "CoreMinimal.h"
#include "Components/ActorComponent.h"
#include "PatrolRoute.generated.h"
UCLASS( ClassGroup=(Custom), meta=(BlueprintSpawnableComponent) )
class TESTINGGROUNDS_API UPatrolRoute : public UActorComponent
{
GENERATED_BODY()
public:
TArray<AActor*> GetPatrolPoints() const;
private:
UPROPERTY(EditInstanceOnly, Category = "Patrol Route")
TArray<AActor*> PatrolPoints;
};
| [
"sean.siders@icloud.com"
] | sean.siders@icloud.com |
b2ba115e0b7acba4127081a54a81adb38a0192c9 | e431a1685ace7e541da641d9005195db89cb1b6f | /10_v1.cpp | 33f34f5c670deef562caddedaf2e1ba5ced688ed | [] | no_license | jianminchen/LeetCode-17 | 7f82230be3510fdfb60847bcee521e6796b33ea9 | 68080d07819bf81823a0c9d25ec84f2a19d422a6 | refs/heads/master | 2021-01-19T07:07:30.481800 | 2016-07-17T08:08:56 | 2016-07-17T08:08:56 | 67,087,459 | 1 | 0 | null | 2016-09-01T01:35:35 | 2016-09-01T01:35:34 | null | UTF-8 | C++ | false | false | 1,343 | cpp | /*
10_v1.cpp
Regular Expression Matching
My first submission got WA because I forgot to initialize the f array as
false. I don't quite understand why my second submission got WA since I
believe bool f[lenS + 1][lenP + 1] = {false} should have already initialized
all values of f.
Turns out this is incorrect. Basically "int f[100] = {0}" would zero out the
whole array but "int f[n] = {0}" would not. In fact VS cannot even compile
this.
*/
class Solution {
bool isCharMatch(char s, char p) { return s == p || p == '.'; }
public:
bool isMatch(string s, string p) {
int lenS = s.size(), lenP = p.size();
bool f[lenS + 1][lenP + 1] = {false};
f[0][0] = true;
bool flag = true;
for (int i = 1; i <= lenP; i++) {
if (p[i - 1] != '*' && (i < lenP && p[i] != '*')) flag = false;
if (flag && p[i - 1] == '*')
f[0][i] = true;
else
f[0][i] = false;
}
for (int i = 1; i <= lenS; i++) {
for (int j = 1; j <= lenP; j++) {
char sc = s[i - 1], sp = p[j - 1];
if (sp != '*') {
if (isCharMatch(sc, sp))
f[i][j] = f[i - 1][j - 1];
else
f[i][j] = false;
} else {
f[i][j] = f[i][j - 2] || (f[i - 1][j] && isCharMatch(sc, p[j - 2]));
}
}
}
return f[lenS][lenP];
}
}; | [
"phoenixinter@gmail.com"
] | phoenixinter@gmail.com |
8b0ff0aede8cbda87552556eb34e49429901eaa3 | 9f0c51ab161e4adc1207e0bef70200c4ec4d20c5 | /src/kdc_arm_tf2/src/kdc_pose_tf.cpp | 60a1db28a13d50a47eca8f99584389052111a09b | [] | no_license | tartanBot/BOOST1 | b3f8229e20142a9d27c48f901d0b4a567e189105 | 637c2cfaac46eb3c41547bf56172c8f01ef456d4 | refs/heads/master | 2021-06-25T08:05:54.460186 | 2017-08-20T02:38:03 | 2017-08-20T02:38:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,082 | cpp | #include <ros/ros.h>
#include <tf2_ros/transform_listener.h>
#include <tf2_ros/transform_broadcaster.h>
#include <geometry_msgs/TransformStamped.h>
void arucoPoseCallback(const geometry_msgs::TransformStamped::ConstPtr& msg)
{
static tf2_ros::TransformBroadcaster br;
geometry_msgs::TransformStamped transformStamped;
transformStamped.header.stamp = ros::Time::now();
transformStamped.header.frame_id = "duo3d_camera";
transformStamped.child_frame_id = "board1";
transformStamped.transform = msg->transform;
br.sendTransform(transformStamped);
}
int main(int argc, char** argv){
ros::init(argc, argv, "kdc_tf2_listener");
ros::NodeHandle node;
ros::Subscriber sub;
sub = node.subscribe("/ar_single_board/transform", 10, &arucoPoseCallback);
ros::spin();
return 0;
};
// void tfCallback(const geometry_msgs::TransformStamped& transformStamped){
// static tf2_ros::TransformBroadcaster br;
// tf2_ros::Buffer tfBuffer;
// tf2_ros::TransformListener tfListener(tfBuffer);
// transformStamped = tfBuffer.lookupTransform("board1", "base_link", ros::Time(0));
// br.sendTransform(transformStamped);
// }
// int main(int argc, char** argv){
// ros::init(argc, argv, "kdc_tf2_listener");
// ros::NodeHandle node;
// ros::Subscriber sub = node.subscribe("/ar_single_board/transform", 10 &tfCallback);
// ros::Publisher board_tf =
// node.advertise<geometry_msgs::TransformStamped>("kdc_arm", 10);
// // tf2_ros::Buffer tfBuffer;
// // tf2_ros::TransformListener tfListener(tfBuffer);
// // ros::Rate rate(10.0);
// // while (node.ok()){
// // geometry_msgs::TransformStamped transformStamped;
// // try{
// // transformStamped = tfBuffer.lookupTransform("board1", "base_link",
// // ros::Time(0));
// // }
// // catch (tf2::TransformException &ex) {
// // ROS_WARN("%s",ex.what());
// // ros::Duration(1.0).sleep();
// // continue;
// // }
// // board_tf.publish(transformStamped);
// rate.sleep();
// }
// return 0;
// }; | [
"merrittj@andrew.cmu.edu"
] | merrittj@andrew.cmu.edu |
6e01a71d125d05a9514200080186ec69ff8a507a | 34aadfb024f98b6de7441f17b4796c39af168b93 | /lookup/src/LookupInterface.cpp | fb47a0797de31f167a1d33d1945ba6751a2f4ee7 | [] | no_license | cbuchxrn/argus_utils | 5a393014ed9a6dd977995d176fe8ca5f3eea81fc | d19be5bdd54e324d1bb23e10625462bf2c6bd5e0 | refs/heads/master | 2022-01-12T14:17:12.322705 | 2018-04-10T17:57:32 | 2018-04-10T17:57:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,949 | cpp | #include "lookup/LookupInterface.h"
#include <boost/thread/thread.hpp>
namespace argus
{
LookupInterface::LookupInterface()
: nodeHandle(), lookupNamespace( "/lookup/" ) {}
LookupInterface::LookupInterface( const ros::NodeHandle& nh )
: nodeHandle( nh ), lookupNamespace( "/lookup/" ) {}
void LookupInterface::SetLookupNamespace( const std::string& ns )
{
lookupNamespace = ns;
if( lookupNamespace.back() != '/' ) { lookupNamespace += "/"; }
}
void LookupInterface::WriteNamespace( const std::string& targetName, const std::string& ns )
{
std::string resolvedNamespace = CleanPath( nodeHandle.resolveName( ns ) );
std::string lookupPath = FormLookupPath( targetName );
ROS_INFO_STREAM( "Registering target (" << targetName
<< ") with fully resolved namespace (" << resolvedNamespace
<< ") at lookup path (" << lookupPath << ")" );
nodeHandle.setParam( lookupPath, resolvedNamespace );
}
bool LookupInterface::ReadNamespace( const std::string& targetName,
std::string& resolvedNamespace,
const ros::Duration& timeout )
{
std::string path = FormLookupPath( targetName );
if( nodeHandle.getParam( path, resolvedNamespace ) ) { return true; }
else if( timeout.toSec() == 0.0 ) { return false; }
ros::Time start = ros::Time::now();
do
{
boost::this_thread::sleep( boost::posix_time::milliseconds(500) );
// ros::Duration( 0.5 ).sleep();
if( nodeHandle.getParam( path, resolvedNamespace ) ) { return true; }
} while( ros::Time::now() < start + timeout );
return false;
}
std::string LookupInterface::CleanPath( const std::string& path )
{
std::string p = path;
if( p.back() != '/' ) { p += "/"; }
return p;
}
std::string LookupInterface::FormLookupPath( const std::string& key ) const
{
std::string lookupPath = CleanPath( lookupNamespace + key );
//lookupPath += "namespace";
return lookupPath;
}
} // end namespace lookup
| [
"humhu@cmu.edu"
] | humhu@cmu.edu |
416898df56d0412e5c0adad54b07ce3dc83ead70 | 8b01178a3b58043681ee138961ed366db46fb749 | /src/coincontrol.h | ecceb0bf6ce746ea7c8a69c672620ad3c905d823 | [
"MIT"
] | permissive | awardprj/AwardCoin | a574c3475bf6a69fa544257c5d5e80d424d9a461 | 5c3703129c716f177da3a1d7ef0421778abef62e | refs/heads/master | 2020-05-21T21:57:52.593996 | 2019-05-12T16:49:58 | 2019-05-12T16:49:58 | 186,162,973 | 3 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 2,240 | h | // Copyright (c) 2011-2013 The Bitcoin developers
// Copyright (c) 2014-2016 The Dash developers
// Copyright (c) 2017-2018 The PIVX developers
// Copyright (c) 2019 The AwardCoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_COINCONTROL_H
#define BITCOIN_COINCONTROL_H
#include "primitives/transaction.h"
#include "script/standard.h"
/** Coin Control Features. */
class CCoinControl
{
public:
CTxDestination destChange;
bool useObfuScation;
bool useSwiftTX;
bool fSplitBlock;
int nSplitBlock;
//! If false, allows unselected inputs, but requires all selected inputs be used
bool fAllowOtherInputs;
//! Includes watch only addresses which match the ISMINE_WATCH_SOLVABLE criteria
bool fAllowWatchOnly;
//! Minimum absolute fee (not per kilobyte)
CAmount nMinimumTotalFee;
CCoinControl()
{
SetNull();
}
void SetNull()
{
destChange = CNoDestination();
setSelected.clear();
useSwiftTX = false;
useObfuScation = false;
fAllowOtherInputs = false;
fAllowWatchOnly = true;
nMinimumTotalFee = 0;
fSplitBlock = false;
nSplitBlock = 1;
}
bool HasSelected() const
{
return (setSelected.size() > 0);
}
bool IsSelected(const uint256& hash, unsigned int n) const
{
COutPoint outpt(hash, n);
return (setSelected.count(outpt) > 0);
}
void Select(const COutPoint& output)
{
setSelected.insert(output);
}
void UnSelect(const COutPoint& output)
{
setSelected.erase(output);
}
void UnSelectAll()
{
setSelected.clear();
}
void ListSelected(std::vector<COutPoint>& vOutpoints)
{
vOutpoints.assign(setSelected.begin(), setSelected.end());
}
unsigned int QuantitySelected()
{
return setSelected.size();
}
void SetSelection(std::set<COutPoint> setSelected)
{
this->setSelected.clear();
this->setSelected = setSelected;
}
private:
std::set<COutPoint> setSelected;
};
#endif // BITCOIN_COINCONTROL_H
| [
"root@ubuntu16.local"
] | root@ubuntu16.local |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.