blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
264
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 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 905
values | visit_date
timestamp[us]date 2015-08-09 11:21:18
2023-09-06 10:45:07
| revision_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-17 19:19:19
| committer_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-06 06:22:19
| github_id
int64 3.89k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us]date 2012-06-07 00:51:45
2023-09-14 21:58:39
⌀ | gha_created_at
timestamp[us]date 2008-03-27 23:40:48
2023-08-21 23:17:38
⌀ | gha_language
stringclasses 141
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 115
values | content
stringlengths 3
10.4M
| authors
sequencelengths 1
1
| author_id
stringlengths 0
158
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ae34634048245275ac1c40a17ae7eb07e7c44563 | 643983e0a5e81c445f8cf8573a093d85472f51af | /src/cc/ccsdtq_1a.cxx | 66d8354ac060223b5aceb52c39481e33f139b2b3 | [
"BSD-3-Clause"
] | permissive | devinamatthews/aquarius | e946a1fb713cfcf37e9cb239ba9505b946dda3d1 | 9b75a7a1e86c4c2898fa96f1a127b743270ad3ab | refs/heads/stable | 2022-02-24T00:54:25.913880 | 2022-02-10T17:48:23 | 2022-02-10T17:48:23 | 12,163,435 | 19 | 9 | BSD-3-Clause | 2022-02-10T17:48:24 | 2013-08-16T16:53:15 | C++ | UTF-8 | C++ | false | false | 11,886 | cxx | #include "ccsdtq_1a.hpp"
using namespace aquarius::op;
using namespace aquarius::input;
using namespace aquarius::tensor;
using namespace aquarius::task;
using namespace aquarius::time;
namespace aquarius
{
namespace cc
{
template <typename U>
CCSDTQ_1a<U>::CCSDTQ_1a(const string& name, Config& config)
: Iterative<U>(name, config), diis(config.get("diis"))
{
vector<Requirement> reqs;
reqs.push_back(Requirement("moints", "H"));
this->addProduct(Product("double", "mp2", reqs));
this->addProduct(Product("double", "energy", reqs));
this->addProduct(Product("double", "convergence", reqs));
this->addProduct(Product("double", "S2", reqs));
this->addProduct(Product("double", "multiplicity", reqs));
this->addProduct(Product("ccsdtq-1a.T", "T", reqs));
this->addProduct(Product("ccsdtq-1a.Hbar", "Hbar", reqs));
}
template <typename U>
bool CCSDTQ_1a<U>::run(task::TaskDAG& dag, const Arena& arena)
{
const auto& H = this->template get<TwoElectronOperator<U>>("H");
const Space& occ = H.occ;
const Space& vrt = H.vrt;
auto& T = this->put ( "T", new ExcitationOperator<U,3>("T", arena, occ, vrt));
auto& Z = this->puttmp( "Z", new ExcitationOperator<U,3>("Z", arena, occ, vrt));
auto& Tau = this->puttmp("Tau", new SpinorbitalTensor <U >("Tau", H.getABIJ()));
auto& D = this->puttmp( "D", new Denominator <U >(H));
this->puttmp( "FAE", new SpinorbitalTensor<U>( "F(ae)", H.getAB()));
this->puttmp( "FMI", new SpinorbitalTensor<U>( "F(mi)", H.getIJ()));
this->puttmp( "FME", new SpinorbitalTensor<U>( "F(me)", H.getIA()));
this->puttmp("WMNIJ", new SpinorbitalTensor<U>("W(mn,ij)", H.getIJKL()));
this->puttmp("WMNEJ", new SpinorbitalTensor<U>("W(mn,ej)", H.getIJAK()));
this->puttmp("WAMIJ", new SpinorbitalTensor<U>("W(am,ij)", H.getAIJK()));
this->puttmp("WAMEI", new SpinorbitalTensor<U>("W(am,ei)", H.getAIBJ()));
this->puttmp("WABEF", new SpinorbitalTensor<U>("W(ab,ef)", H.getABCD()));
this->puttmp("WABEJ", new SpinorbitalTensor<U>("W(ab,ej)", H.getABCI()));
this->puttmp("WAMEF", new SpinorbitalTensor<U>("W(am,ef)", H.getAIBC()));
this->puttmp("T4", new SpinorbitalTensor<U>("T(abcd,ijkl)", arena,
H.getABIJ().getGroup(),
{vrt, occ}, {4, 0},
{0, 4}));
this->puttmp("WABCEJK", new SpinorbitalTensor<U>("W~(abc,ejk)", arena,
H.getABIJ().getGroup(),
{vrt, occ}, {3, 0},
{1, 2}));
this->puttmp("WABMIJK", new SpinorbitalTensor<U>("W~(abm,ijk)", arena,
H.getABIJ().getGroup(),
{vrt, occ}, {2, 1},
{0, 3}));
Z(0) = (U)0.0;
T(0) = (U)0.0;
T(1) = H.getAI();
T(2) = H.getABIJ();
T(3) = (U)0.0;
T.weight(D);
Tau["abij"] = T(2)["abij"];
Tau["abij"] += 0.5*T(1)["ai"]*T(1)["bj"];
double mp2 = real(scalar(H.getAI()*T(1))) + 0.25*real(scalar(H.getABIJ()*Tau));
Logger::log(arena) << "MP2 energy = " << setprecision(15) << mp2 << endl;
this->put("mp2", new U(mp2));
CTF_Timer_epoch ep(this->name.c_str());
ep.begin();
Iterative<U>::run(dag, arena);
ep.end();
this->put("energy", new U(this->energy()));
this->put("convergence", new U(this->conv()));
if (this->isUsed("Hbar"))
{
this->put("Hbar", new STTwoElectronOperator<U>("Hbar", H, T, true));
}
return true;
}
template <typename U>
void CCSDTQ_1a<U>::iterate(const Arena& arena)
{
const auto& H = this->template get<TwoElectronOperator<U>>("H");
const SpinorbitalTensor<U>& fAI = H.getAI();
const SpinorbitalTensor<U>& fME = H.getIA();
const SpinorbitalTensor<U>& fAE = H.getAB();
const SpinorbitalTensor<U>& fMI = H.getIJ();
const SpinorbitalTensor<U>& VABIJ = H.getABIJ();
const SpinorbitalTensor<U>& VMNEF = H.getIJAB();
const SpinorbitalTensor<U>& VAMEF = H.getAIBC();
const SpinorbitalTensor<U>& VABEJ = H.getABCI();
const SpinorbitalTensor<U>& VABEF = H.getABCD();
const SpinorbitalTensor<U>& VMNIJ = H.getIJKL();
const SpinorbitalTensor<U>& VMNEJ = H.getIJAK();
const SpinorbitalTensor<U>& VAMIJ = H.getAIJK();
const SpinorbitalTensor<U>& VAMEI = H.getAIBJ();
auto& T = this->template get <ExcitationOperator<U,3>>( "T");
auto& D = this->template gettmp<Denominator <U >>( "D");
auto& Z = this->template gettmp<ExcitationOperator<U,3>>( "Z");
auto& Tau = this->template gettmp<SpinorbitalTensor <U >>("Tau");
auto& T4 = this->template gettmp<SpinorbitalTensor<U>>("T4");
auto& FME = this->template gettmp<SpinorbitalTensor<U>>( "FME");
auto& FAE = this->template gettmp<SpinorbitalTensor<U>>( "FAE");
auto& FMI = this->template gettmp<SpinorbitalTensor<U>>( "FMI");
auto& WMNIJ = this->template gettmp<SpinorbitalTensor<U>>( "WMNIJ");
auto& WMNEJ = this->template gettmp<SpinorbitalTensor<U>>( "WMNEJ");
auto& WAMIJ = this->template gettmp<SpinorbitalTensor<U>>( "WAMIJ");
auto& WAMEI = this->template gettmp<SpinorbitalTensor<U>>( "WAMEI");
auto& WABEF = this->template gettmp<SpinorbitalTensor<U>>( "WABEF");
auto& WABEJ = this->template gettmp<SpinorbitalTensor<U>>( "WABEJ");
auto& WAMEF = this->template gettmp<SpinorbitalTensor<U>>( "WAMEF");
auto& WABCEJK = this->template gettmp<SpinorbitalTensor<U>>("WABCEJK");
auto& WABMIJK = this->template gettmp<SpinorbitalTensor<U>>("WABMIJK");
Tau["abij"] = T(2)["abij"];
Tau["abij"] += 0.5*T(1)["ai"]*T(1)["bj"];
/**************************************************************************
*
* Intermediates for CCSD
*/
FME[ "me"] = fME[ "me"];
FME[ "me"] += VMNEF["mnef"]*T(1)[ "fn"];
FMI[ "mi"] = fMI[ "mi"];
FMI[ "mi"] += 0.5*VMNEF["mnef"]*T(2)["efin"];
FMI[ "mi"] += FME[ "me"]*T(1)[ "ei"];
FMI[ "mi"] += VMNEJ["nmfi"]*T(1)[ "fn"];
FAE[ "ae"] = fAE[ "ae"];
FAE[ "ae"] -= 0.5*VMNEF["mnef"]*T(2)["afmn"];
FAE[ "ae"] -= FME[ "me"]*T(1)[ "am"];
FAE[ "ae"] += VAMEF["amef"]*T(1)[ "fm"];
WMNIJ["mnij"] = VMNIJ["mnij"];
WMNIJ["mnij"] += 0.5*VMNEF["mnef"]* Tau["efij"];
WMNIJ["mnij"] += VMNEJ["mnej"]*T(1)[ "ei"];
WMNEJ["mnej"] = VMNEJ["mnej"];
WMNEJ["mnej"] += VMNEF["mnef"]*T(1)[ "fj"];
WAMIJ["amij"] = VAMIJ["amij"];
WAMIJ["amij"] += 0.5*VAMEF["amef"]* Tau["efij"];
WAMIJ["amij"] += VAMEI["amej"]*T(1)[ "ei"];
WAMEI["amei"] = VAMEI["amei"];
WAMEI["amei"] += 0.5*VMNEF["mnef"]*T(2)["afni"];
WAMEI["amei"] += VAMEF["amef"]*T(1)[ "fi"];
WAMEI["amei"] -= WMNEJ["nmei"]*T(1)[ "an"];
/*
*************************************************************************/
/**************************************************************************
*
* CCSD Iteration
*/
Z(1)[ "ai"] = fAI[ "ai"];
Z(1)[ "ai"] += fAE[ "ae"]*T(1)[ "ei"];
Z(1)[ "ai"] -= FMI[ "mi"]*T(1)[ "am"];
Z(1)[ "ai"] -= VAMEI["amei"]*T(1)[ "em"];
Z(1)[ "ai"] += FME[ "me"]*T(2)["aeim"];
Z(1)[ "ai"] += 0.5*VAMEF["amef"]* Tau["efim"];
Z(1)[ "ai"] -= 0.5*WMNEJ["mnei"]*T(2)["eamn"];
Z(2)["abij"] = VABIJ["abij"];
Z(2)["abij"] += VABEJ["abej"]*T(1)[ "ei"];
Z(2)["abij"] -= WAMIJ["amij"]*T(1)[ "bm"];
Z(2)["abij"] += FAE[ "af"]*T(2)["fbij"];
Z(2)["abij"] -= FMI[ "ni"]*T(2)["abnj"];
Z(2)["abij"] += 0.5*VABEF["abef"]* Tau["efij"];
Z(2)["abij"] += 0.5*WMNIJ["mnij"]* Tau["abmn"];
Z(2)["abij"] += WAMEI["amei"]*T(2)["ebjm"];
/*
*************************************************************************/
/**************************************************************************
*
* Intermediates for CCSDT
*/
WAMIJ["amij"] += WMNEJ["nmej"]*T(2)[ "aein"];
WAMIJ["amij"] -= WMNIJ["nmij"]*T(1)[ "an"];
WAMIJ["amij"] += FME[ "me"]*T(2)[ "aeij"];
WAMIJ["amij"] += 0.5*VMNEF["mnef"]*T(3)["aefijn"];
WAMEI["amei"] += 0.5*VMNEF["mnef"]*T(2)[ "afni"];
WAMEI["amei"] += 0.5*WMNEJ["nmei"]*T(1)[ "an"];
WABEJ["abej"] = VABEJ["abej"];
WABEJ["abej"] += VAMEF["amef"]*T(2)[ "fbmj"];
WABEJ["abej"] += 0.5*WMNEJ["mnej"]*T(2)[ "abmn"];
WABEJ["abej"] += VABEF["abef"]*T(1)[ "fj"];
WABEJ["abej"] -= WAMEI["amej"]*T(1)[ "bm"];
WABEJ["abej"] -= 0.5*VMNEF["mnef"]*T(3)["afbmnj"];
WAMEI["amei"] -= 0.5*WMNEJ["nmei"]*T(1)[ "an"];
WABEF["abef"] = VABEF["abef"];
WABEF["abef"] -= VAMEF["amef"]*T(1)[ "bm"];
WABEF["abef"] += 0.5*VMNEF["mnef"]* Tau[ "abmn"];
WAMEF["amef"] = VAMEF["amef"];
WAMEF["amef"] -= VMNEF["nmef"]*T(1)[ "an"];
/*
*************************************************************************/
/**************************************************************************
*
* CCSDT Iteration
*/
Z(1)[ "ai"] += 0.25*VMNEF["mnef"]*T(3)["aefimn"];
Z(2)[ "abij"] += 0.5*WAMEF["bmef"]*T(3)["aefijm"];
Z(2)[ "abij"] -= 0.5*WMNEJ["mnej"]*T(3)["abeinm"];
Z(2)[ "abij"] += FME[ "me"]*T(3)["abeijm"];
Z(3)["abcijk"] = WABEJ["bcek"]*T(2)[ "aeij"];
Z(3)["abcijk"] -= WAMIJ["bmjk"]*T(2)[ "acim"];
Z(3)["abcijk"] += FAE[ "ce"]*T(3)["abeijk"];
Z(3)["abcijk"] -= FMI[ "mk"]*T(3)["abcijm"];
Z(3)["abcijk"] += 0.5*WABEF["abef"]*T(3)["efcijk"];
Z(3)["abcijk"] += 0.5*WMNIJ["mnij"]*T(3)["abcmnk"];
Z(3)["abcijk"] += WAMEI["amei"]*T(3)["ebcjmk"];
/*
**************************************************************************/
/**************************************************************************
*
* Intermediates for CCSDTQ-1a
*/
WABCEJK["abcejk"] = 0.5*VABEF["abef"]*T(2)[ "fcjk"];
WABMIJK["abmijk"] = VAMEI["amek"]*T(2)[ "ebij"];
WABMIJK["abmijk"] -= 0.5*VMNIJ["mnkj"]*T(2)[ "abin"];
/*
*************************************************************************/
/**************************************************************************
*
* CCSDTQ-1a Iteration
*/
T4["abcdijkl"] = WABCEJK["abcejk"]*T(2)[ "edil"];
T4["abcdijkl"] -= WABMIJK["abmijk"]*T(2)[ "cdml"];
T4["abcdijkl"] += VABEJ[ "abej"]*T(3)[ "ecdikl"];
T4["abcdijkl"] -= VAMIJ[ "amij"]*T(3)[ "bcdmkl"];
T4.weight({&D.getDA(), &D.getDI()}, {&D.getDa(), &D.getDi()});
Z(2)[ "abij"] += 0.25*VMNEF[ "mnef"]* T4["abefijmn"];
Z(3)[ "abcijk"] += fME[ "me"]* T4["abceijkm"];
/*
**************************************************************************/
Z.weight(D);
T += Z;
Tau["abij"] = T(2)["abij"];
Tau["abij"] += 0.5*T(1)["ai"]*T(1)["bj"];
this->energy() = real(scalar(H.getAI()*T(1))) + 0.25*real(scalar(H.getABIJ()*Tau));
this->conv() = Z.norm(00);
diis.extrapolate(T, Z);
}
}
}
static const char* spec = R"!(
convergence?
double 1e-9,
max_iterations?
int 50,
conv_type?
enum { MAXE, RMSE, MAE },
diis?
{
damping?
double 0.0,
start?
int 1,
order?
int 5,
jacobi?
bool false
}
)!";
INSTANTIATE_SPECIALIZATIONS(aquarius::cc::CCSDTQ_1a);
REGISTER_TASK(aquarius::cc::CCSDTQ_1a<double>,"ccsdtq-1a",spec);
| [
"[email protected]"
] | |
b4b0e96779b82e35a34076b3c858608e7c79d4f2 | e9668710663ddce4f42aa0b35f307d060b1d98f4 | /cell/mesh/mesh.h | 48c4d48a11f560c79fcc0770a33a9b2ad180f25c | [] | no_license | paubertin/Cell | 5d362d3566299233d26151c64d01958bef029ccf | 286209f9e459edbd42358a3120a935c27779d81c | refs/heads/master | 2021-01-22T14:25:18.706735 | 2016-08-17T18:54:06 | 2016-08-17T18:54:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,665 | h | #ifndef CELL_MESH_H
#define CELL_MESH_H
#include <vector>
#include <math/linear_algebra/vector.h>
namespace Cell
{
/* NOTE(Joey):
Manually define a list of topology types as we don't want to
directly link a mesh to an OpenGL toplogy type as this would
reduce the renderer's cross compatbility.
Yes, yes I know that we still have OpenGL indices in here (
VAO, VBO, EBO) which we will eventually get rid of in a
cross renderer way.
*/
enum TOPOLOGY
{
POINTS,
LINES,
LINE_STRIP,
TRIANGLES,
TRIANGLE_STRIP,
TRIANGLE_FAN,
};
/* NOTE(Joey):
Mesh
*/
class Mesh
{
// NOTE(Joey): public for now for testing and easy access; will eventually be private and only visible to renderer (as a friend class)
public:
unsigned int m_VAO = 0;
unsigned int m_VBO;
unsigned int m_EBO;
public:
std::vector<math::vec3> Positions;
std::vector<math::vec2> UV;
std::vector<math::vec3> Normals;
std::vector<math::vec3> Tangents;
std::vector<math::vec3> Bitangents;
TOPOLOGY Topology;
std::vector<unsigned int> Indices;
// NOTE(Joey): we support multiple ways of initializing a mesh
Mesh();
Mesh(std::vector<math::vec3> positions, std::vector<unsigned int> indices);
Mesh(std::vector<math::vec3> positions, std::vector<math::vec2> uv, std::vector<unsigned int> indices);
Mesh(std::vector<math::vec3> positions, std::vector<math::vec2> uv, std::vector<math::vec3> normals, std::vector<unsigned int> indices);
Mesh(std::vector<math::vec3> positions, std::vector<math::vec2> uv, std::vector<math::vec3> normals, std::vector<math::vec3> tangents, std::vector<math::vec3> bitangents, std::vector<unsigned int> indices);
// NOTE(Joey): set vertex data manually
// TODO(Joey): not sure if these are required if we can directly set vertex data from public fields; construct several use-cases to test.
void SetPositions(std::vector<math::vec3> positions);
void SetUVs(std::vector<math::vec2> uv);
void SetNormals(std::vector<math::vec3> normals);
void SetTangents(std::vector<math::vec3> tangents, std::vector<math::vec3> bitangents); // NOTE(Joey): you can only set both tangents and bitangents at the same time to prevent mismatches
// NOTE(Joey): commits all buffers and attributes to the renderer
void Finalize(bool interleaved = true);
private:
void calculateNormals(bool smooth = true);
void calculateTangents();
};
}
#endif | [
"[email protected]"
] | |
3f00b9b255ea881a4e7dbf66660e4549f6f31962 | 859c7702acb643557f7cb6de1e8d4adf20ea358c | /tests/utils/ext/enoki/include/enoki/cuda.h | 13f669cf3efcf3e691ca499174207b34386b0f6f | [
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-free-unknown"
] | permissive | geometryprocessing/acorns-benchmark | a0ebc6f74c223ca71ed8a3f2df1e7b3c8a341a8e | df5f43af90a32f4c1578cdea1f4f412237e18c75 | refs/heads/master | 2023-08-11T11:32:49.141348 | 2021-09-24T21:20:06 | 2021-09-24T21:20:06 | 175,263,974 | 1 | 1 | MIT | 2021-09-24T21:29:18 | 2019-03-12T17:26:57 | C++ | UTF-8 | C++ | false | false | 34,379 | h | /*
enoki/cuda.h -- CUDA-backed Enoki dynamic array with JIT compilation
Enoki is a C++ template library that enables transparent vectorization
of numerical kernels using SIMD instruction sets available on current
processor architectures.
Copyrighe (c) 2019 Wenzel Jakob <[email protected]>
All rights reserved. Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.
*/
#pragma once
#define ENOKI_CUDA 1
#include <enoki/array.h>
NAMESPACE_BEGIN(enoki)
// -----------------------------------------------------------------------
//! @{ \name Imports from libenoki-cuda.so
// -----------------------------------------------------------------------
/// Initialize the tracing JIT
extern ENOKI_IMPORT void cuda_init();
/// Delete the trace, requires a subsequent call by cuda_init()
extern ENOKI_IMPORT void cuda_shutdown();
/// Compile and evaluate the trace up to the current instruction
extern ENOKI_IMPORT void cuda_eval(bool log_assembly /* = false */);
/// Invokes 'cuda_eval' if the given variable has not been evaluated yet
extern ENOKI_IMPORT void cuda_eval_var(uint32_t index, bool log_assembly = false);
/// Increase the reference count of a variable
extern ENOKI_IMPORT void cuda_inc_ref_ext(uint32_t);
/// Decrease the reference count of a variable
extern ENOKI_IMPORT void cuda_dec_ref_ext(uint32_t);
/// Return the size of a variable
extern ENOKI_IMPORT size_t cuda_var_size(uint32_t);
/// Return the pointer address of a variable (in device memory)
extern ENOKI_IMPORT void* cuda_var_ptr(uint32_t);
/// Retroactively adjust the recorded size of a variable
extern ENOKI_IMPORT uint32_t cuda_var_set_size(uint32_t index, size_t size, bool copy = false);
/// Mark a variable as dirty (e.g. due to scatter)
extern ENOKI_IMPORT void cuda_var_mark_dirty(uint32_t);
/// Attach a label to a variable (written to PTX assembly)
extern ENOKI_IMPORT void cuda_var_set_label(uint32_t, const char *);
/// Needed to mark certain instructions with side effects (e.g. scatter)
extern ENOKI_IMPORT void cuda_var_mark_side_effect(uint32_t);
/// Set the current scatter/source operand array
extern ENOKI_IMPORT void cuda_set_scatter_gather_operand(uint32_t index, bool gather);
/// Append an operation to the trace (0 arguments)
extern ENOKI_IMPORT uint32_t cuda_trace_append(EnokiType type,
const char *op);
/// Append an operation to the trace (1 argument)
extern ENOKI_IMPORT uint32_t cuda_trace_append(EnokiType type,
const char *op,
uint32_t arg1);
/// Append an operation to the trace (2 arguments)
extern ENOKI_IMPORT uint32_t cuda_trace_append(EnokiType type,
const char *op,
uint32_t arg1,
uint32_t arg2);
/// Append an operation to the trace (3 arguments)
extern ENOKI_IMPORT uint32_t cuda_trace_append(EnokiType type,
const char *op,
uint32_t arg1,
uint32_t arg2,
uint32_t arg3);
/// Insert a "printf" instruction for the given instruction
extern ENOKI_IMPORT void cuda_trace_printf(const char *fmt, uint32_t narg,
uint32_t *arg);
/// Computes the horizontal sum of a given memory region
template <typename T> extern ENOKI_IMPORT T* cuda_hsum(size_t, const T *);
/// Computes the horizontal product of a given memory region
template <typename T> extern ENOKI_IMPORT T* cuda_hprod(size_t, const T *);
/// Computes the horizontal maximum of a given memory region
template <typename T> extern ENOKI_IMPORT T* cuda_hmax(size_t, const T *);
/// Computes the horizontal minimum of a given memory region
template <typename T> extern ENOKI_IMPORT T* cuda_hmin(size_t, const T *);
/// Compute the number of entries set to 'true'
extern ENOKI_IMPORT size_t cuda_count(size_t, const bool *);
template <typename T>
extern ENOKI_IMPORT void cuda_compress(size_t, const T *, const bool *mask,
T **, size_t *);
/// Computes a horizontal reduction of a mask array via AND
extern ENOKI_IMPORT bool cuda_all(size_t, const bool *);
/// Computes a horizontal reduction of a mask array via OR
extern ENOKI_IMPORT bool cuda_any(size_t, const bool *);
/// Sort 'ptrs' and return unique instances and their count, as well as a permutation
extern ENOKI_IMPORT size_t cuda_partition(size_t size, const void **ptrs,
void ***unique_out,
uint32_t **counts_out,
uint32_t ***perm_out);
/// Copy some host memory region to the device and wrap it in a variable
extern ENOKI_IMPORT uint32_t cuda_var_copy_to_device(EnokiType type,
size_t size, const void *value);
/// Create a variable that stores a pointer to some (device) memory region
extern ENOKI_IMPORT uint32_t cuda_var_register_ptr(const void *ptr);
/// Register a memory region (in device memory) as a variable
extern ENOKI_IMPORT uint32_t cuda_var_register(EnokiType type, size_t size,
void *ptr, bool dealloc);
/// Fetch a scalar value from a CUDA array (in device memory)
extern ENOKI_IMPORT void cuda_fetch_element(void *, uint32_t, size_t, size_t);
/// Copy a memory region to the device
extern ENOKI_IMPORT void cuda_memcpy_to_device(void *dst, const void *src, size_t size);
extern ENOKI_IMPORT void cuda_memcpy_to_device_async(void *dst, const void *src, size_t size);
/// Copy a memory region from the device
extern ENOKI_IMPORT void cuda_memcpy_from_device(void *dst, const void *src, size_t size);
extern ENOKI_IMPORT void cuda_memcpy_from_device_async(void *dst, const void *src, size_t size);
/// Return the free and total amount of memory (Wrapper around cudaMemGetInfo)
extern ENOKI_IMPORT void cuda_mem_get_info(size_t *free, size_t *total);
/// Allocate device-local memory (wrapper around cudaMalloc)
extern ENOKI_IMPORT void* cuda_malloc(size_t);
/// Allocate unified memory (wrapper around cudaMallocManaged)
extern ENOKI_IMPORT void* cuda_managed_malloc(size_t size);
/// Allocate host-pinned memory (wrapper around cudaMallocHost)
extern ENOKI_IMPORT void* cuda_host_malloc(size_t);
/// Allocate zero-initialized device-local memory (wrapper around cudaMalloc & cudaMemsetAsync)
extern ENOKI_IMPORT void* cuda_malloc_zero(size_t);
/// Allocate unified memory (wrapper around cudaMalloc & analogues of cudaMemsetAsync)
extern ENOKI_IMPORT void* cuda_malloc_fill(size_t, uint8_t values);
extern ENOKI_IMPORT void* cuda_malloc_fill(size_t, uint16_t values);
extern ENOKI_IMPORT void* cuda_malloc_fill(size_t, uint32_t values);
extern ENOKI_IMPORT void* cuda_malloc_fill(size_t, uint64_t values);
/// Release device-local or unified memory
extern ENOKI_IMPORT void cuda_free(void *);
/// Release host-local memory
extern ENOKI_IMPORT void cuda_host_free(void *);
/// Release any unused held memory back to the device
extern ENOKI_IMPORT void cuda_malloc_trim();
/// Wait for all work queued on the device to finish
extern ENOKI_IMPORT void cuda_sync();
/// Print detailed information about currently allocated arrays
extern ENOKI_IMPORT char *cuda_whos();
/// Register a callback that will be invoked before cuda_eval()
extern void cuda_register_callback(void (*callback)(void *), void *payload);
/// Unregister a callback installed via 'cuda_register_callback()'
extern void cuda_unregister_callback(void (*callback)(void *), void *payload);
/**
* \brief Current log level (0: none, 1: kernel launches,
* 2: +ptxas statistics, 3: +ptx source, 4: +jit trace, 5: +ref counting)
*/
extern ENOKI_IMPORT void cuda_set_log_level(uint32_t);
extern ENOKI_IMPORT uint32_t cuda_log_level();
//! @}
// -----------------------------------------------------------------------
template <typename Value>
struct CUDAArray : ArrayBase<value_t<Value>, CUDAArray<Value>> {
template <typename T> friend struct CUDAArray;
using Index = uint32_t;
static constexpr EnokiType Type = enoki_type_v<Value>;
static constexpr bool IsCUDA = true;
static constexpr bool Approx = std::is_floating_point_v<Value>;
template <typename T> using ReplaceValue = CUDAArray<T>;
using MaskType = CUDAArray<bool>;
using ArrayType = CUDAArray;
CUDAArray() = default;
~CUDAArray() {
cuda_dec_ref_ext(m_index);
}
CUDAArray(const CUDAArray &a) : m_index(a.m_index) {
cuda_inc_ref_ext(m_index);
}
CUDAArray(CUDAArray &&a) : m_index(a.m_index) {
a.m_index = 0;
}
template <typename T> CUDAArray(const CUDAArray<T> &v) {
const char *op;
if (std::is_floating_point_v<T> && std::is_integral_v<Value>)
op = "cvt.rzi.$t1.$t2 $r1, $r2";
else if (std::is_integral_v<T> && std::is_floating_point_v<Value>)
op = "cvt.rn.$t1.$t2 $r1, $r2";
else
op = "cvt.$t1.$t2 $r1, $r2";
m_index = cuda_trace_append(Type, op, v.index_());
}
template <typename T>
CUDAArray(const CUDAArray<T> &v, detail::reinterpret_flag) {
static_assert(sizeof(T) == sizeof(Value));
if (std::is_integral_v<T> != std::is_integral_v<Value>) {
m_index = cuda_trace_append(Type, "mov.$b1 $r1, $r2", v.index_());
} else {
m_index = v.index_();
cuda_inc_ref_ext(m_index);
}
}
template <typename T, enable_if_t<std::is_scalar_v<T>> = 0>
CUDAArray(const T &value, detail::reinterpret_flag)
: CUDAArray(memcpy_cast<Value>(value)) { }
template <typename T, enable_if_t<std::is_scalar_v<T>> = 0>
CUDAArray(T value) : CUDAArray((Value) value) { }
CUDAArray(Value value) {
const char *fmt = nullptr;
switch (Type) {
case EnokiType::Float16:
fmt = "mov.$t1 $r1, %04x";
break;
case EnokiType::Float32:
fmt = "mov.$t1 $r1, 0f%08x";
break;
case EnokiType::Float64:
fmt = "mov.$t1 $r1, 0d%016llx";
break;
case EnokiType::Bool:
fmt = "mov.$t1 $r1, %i";
break;
case EnokiType::Int8:
case EnokiType::UInt8:
fmt = "mov.$t1 $r1, 0x%02x";
break;
case EnokiType::Int16:
case EnokiType::UInt16:
fmt = "mov.$t1 $r1, 0x%04x";
break;
case EnokiType::Int32:
case EnokiType::UInt32:
fmt = "mov.$t1 $r1, 0x%08x";
break;
case EnokiType::Pointer:
case EnokiType::Int64:
case EnokiType::UInt64:
fmt = "mov.$t1 $r1, 0x%016llx";
break;
default:
fmt = "<<invalid format during cast>>";
break;
}
char tmp[32];
snprintf(tmp, 32, fmt, memcpy_cast<uint_array_t<Value>>(value));
m_index = cuda_trace_append(Type, tmp);
}
template <typename... Args, enable_if_t<(sizeof...(Args) > 1)> = 0>
CUDAArray(Args&&... args) {
Value data[] = { (Value) args... };
m_index = cuda_var_copy_to_device(Type, sizeof...(Args), data);
}
CUDAArray &operator=(const CUDAArray &a) {
cuda_inc_ref_ext(a.m_index);
cuda_dec_ref_ext(m_index);
m_index = a.m_index;
return *this;
}
CUDAArray &operator=(CUDAArray &&a) {
std::swap(m_index, a.m_index);
return *this;
}
CUDAArray add_(const CUDAArray &v) const {
const char *op = std::is_floating_point_v<Value>
? "add.rn.ftz.$t1 $r1, $r2, $r3"
: "add.$t1 $r1, $r2, $r3";
return CUDAArray::from_index_(
cuda_trace_append(Type, op, index_(), v.index_()));
}
CUDAArray sub_(const CUDAArray &v) const {
const char *op = std::is_floating_point_v<Value>
? "sub.rn.ftz.$t1 $r1, $r2, $r3"
: "sub.$t1 $r1, $r2, $r3";
return CUDAArray::from_index_(
cuda_trace_append(Type, op, index_(), v.index_()));
}
CUDAArray mul_(const CUDAArray &v) const {
const char *op = std::is_floating_point_v<Value>
? "mul.rn.ftz.$t1 $r1, $r2, $r3"
: "mul.lo.$t1 $r1, $r2, $r3";
return CUDAArray::from_index_(
cuda_trace_append(Type, op, index_(), v.index_()));
}
CUDAArray mulhi_(const CUDAArray &v) const {
return CUDAArray::from_index_(cuda_trace_append(
Type, "mul.hi.$t1 $r1, $r2, $r3", index_(), v.index_()));
}
CUDAArray div_(const CUDAArray &v) const {
const char *op = std::is_floating_point_v<Value>
? "div.rn.ftz.$t1 $r1, $r2, $r3"
: "div.$t1 $r1, $r2, $r3";
return CUDAArray::from_index_(
cuda_trace_append(Type, op, index_(), v.index_()));
}
CUDAArray mod_(const CUDAArray &v) const {
return CUDAArray::from_index_(cuda_trace_append(Type,
"rem.$t1 $r1, $r2, $r3", index_(), v.index_()));
}
CUDAArray fmadd_(const CUDAArray &a, const CUDAArray &b) const {
const char *op = std::is_floating_point_v<Value>
? "fma.rn.ftz.$t1 $r1, $r2, $r3, $r4"
: "mad.lo.$t1 $r1, $r2, $r3, $r4";
return CUDAArray::from_index_(
cuda_trace_append(Type, op, index_(), a.index_(), b.index_()));
}
CUDAArray fmsub_(const CUDAArray &a, const CUDAArray &b) const {
return fmadd_(a, -b);
}
CUDAArray fnmadd_(const CUDAArray &a, const CUDAArray &b) const {
return fmadd_(-a, b);
}
CUDAArray fnmsub_(const CUDAArray &a, const CUDAArray &b) const {
return -fmadd_(a, b);
}
CUDAArray max_(const CUDAArray &v) const {
return CUDAArray::from_index_(cuda_trace_append(Type,
"max.ftz.$t1 $r1, $r2, $r3", index_(), v.index_()));
}
CUDAArray min_(const CUDAArray &v) const {
return CUDAArray::from_index_(cuda_trace_append(Type,
"min.ftz.$t1 $r1, $r2, $r3", index_(), v.index_()));
}
CUDAArray abs_() const {
return CUDAArray::from_index_(cuda_trace_append(Type,
"abs.ftz.$t1 $r1, $r2", index_()));
}
CUDAArray neg_() const {
return CUDAArray::from_index_(cuda_trace_append(Type,
"neg.ftz.$t1 $r1, $r2", index_()));
}
CUDAArray sqrt_() const {
return CUDAArray::from_index_(cuda_trace_append(Type,
"sqrt.rn.ftz.$t1 $r1, $r2", index_()));
}
CUDAArray exp_() const {
CUDAArray scaled = Value(1.4426950408889634074) * *this;
return CUDAArray::from_index_(cuda_trace_append(Type,
"ex2.approx.ftz.$t1 $r1, $r2", scaled.index_()));
}
CUDAArray log_() const {
return CUDAArray::from_index_(cuda_trace_append(
Type, "lg2.approx.ftz.$t1 $r1, $r2",
index_())) * Value(0.69314718055994530942);
}
CUDAArray sin_() const {
return CUDAArray::from_index_(cuda_trace_append(Type,
"sin.approx.ftz.$t1 $r1, $r2", index_()));
}
CUDAArray cos_() const {
return CUDAArray::from_index_(cuda_trace_append(Type,
"cos.approx.ftz.$t1 $r1, $r2", index_()));
}
std::pair<CUDAArray, CUDAArray> sincos_() const {
return { sin_(), cos_() };
}
CUDAArray rcp_() const {
return CUDAArray::from_index_(cuda_trace_append(Type,
"rcp.approx.ftz.$t1 $r1, $r2", index_()));
}
CUDAArray rsqrt_() const {
return CUDAArray::from_index_(cuda_trace_append(Type,
"rsqrt.approx.ftz.$t1 $r1, $r2", index_()));
}
CUDAArray floor_() const {
return CUDAArray::from_index_(cuda_trace_append(Type,
"cvt.rmi.$t1.$t1 $r1, $r2", index_()));
}
CUDAArray ceil_() const {
return CUDAArray::from_index_(cuda_trace_append(Type,
"cvt.rpi.$t1.$t1 $r1, $r2", index_()));
}
CUDAArray round_() const {
return CUDAArray::from_index_(cuda_trace_append(Type,
"cvt.rni.$t1.$t1 $r1, $r2", index_()));
}
CUDAArray trunc_() const {
return CUDAArray::from_index_(cuda_trace_append(Type,
"cvt.rzi.$t1.$t1 $r1, $r2", index_()));
}
template <typename T> T floor2int_() const {
return T::from_index_(cuda_trace_append(T::Type,
"cvt.rmi.$t1.$t2 $r1, $r2", index_()));
}
template <typename T> T ceil2int_() const {
return T::from_index_(cuda_trace_append(T::Type,
"cvt.rpi.$t1.$t2 $r1, $r2", index_()));
}
CUDAArray sl_(const CUDAArray &v) const {
if constexpr (sizeof(Value) == 4)
return CUDAArray::from_index_(cuda_trace_append(Type,
"shl.$b1 $r1, $r2, $r3", index_(), v.index_()));
else
return CUDAArray::from_index_(cuda_trace_append(Type,
"shl.$b1 $r1, $r2, $r3", index_(), CUDAArray<int32_t>(v).index_()));
}
CUDAArray sr_(const CUDAArray &v) const {
if constexpr (sizeof(Value) == 4)
return CUDAArray::from_index_(cuda_trace_append(Type,
"shr.$b1 $r1, $r2, $r3", index_(), v.index_()));
else
return CUDAArray::from_index_(cuda_trace_append(Type,
"shr.$b1 $r1, $r2, $r3", index_(), CUDAArray<int32_t>(v).index_()));
}
template <size_t Imm> CUDAArray sl_() const { return sl_(Value(Imm)); }
template <size_t Imm> CUDAArray sr_() const { return sr_(Value(Imm)); }
CUDAArray not_() const {
return CUDAArray::from_index_(cuda_trace_append(Type,
"not.$b1 $r1, $r2", index_()));
}
CUDAArray popcnt_() const {
return CUDAArray::from_index_(cuda_trace_append(Type,
"popc.$b1 $r1, $r2", index_()));
}
CUDAArray lzcnt_() const {
return CUDAArray::from_index_(cuda_trace_append(Type,
"clz.$b1 $r1, $r2", index_()));
}
CUDAArray tzcnt_() const {
return CUDAArray::from_index_(cuda_trace_append(Type,
"brev.$b1 $r1, $r2;\n clz.$b1 $r1, $r1", index_()));
}
template <typename T>
CUDAArray or_(const CUDAArray<T> &v) const {
Value all_ones = memcpy_cast<Value>(int_array_t<Value>(-1));
ENOKI_MARK_USED(all_ones);
if constexpr (std::is_same_v<T, Value>)
return CUDAArray::from_index_(cuda_trace_append(Type,
"or.$b1 $r1, $r2, $r3", index_(), v.index_()));
else
return CUDAArray::from_index_(cuda_trace_append(Type,
"selp.$t1 $r1, $r2, $r3, $r4", CUDAArray(all_ones).index_(),
index_(), v.index_()));
}
template <typename T>
CUDAArray and_(const CUDAArray<T> &v) const {
Value all_zeros = memcpy_cast<Value>(int_array_t<Value>(0));
ENOKI_MARK_USED(all_zeros);
if constexpr (std::is_same_v<T, Value>)
return CUDAArray::from_index_(cuda_trace_append(Type,
"and.$b1 $r1, $r2, $r3", index_(), v.index_()));
else
return CUDAArray::from_index_(cuda_trace_append(Type,
"selp.$t1 $r1, $r2, $r3, $r4", index_(),
CUDAArray(all_zeros).index_(), v.index_()));
}
template <typename T> CUDAArray andnot_(const CUDAArray<T> &v) const {
return and_(!v);
}
CUDAArray xor_(const CUDAArray &v) const {
return CUDAArray::from_index_(cuda_trace_append(Type,
"xor.$b1 $r1, $r2, $r3", index_(), v.index_()));
}
MaskType gt_(const CUDAArray &v) const {
const char *op = std::is_signed_v<Value>
? "setp.gt.$t2 $r1, $r2, $r3"
: "setp.hi.$t2 $r1, $r2, $r3";
return MaskType::from_index_(cuda_trace_append(
EnokiType::Bool, op, index_(), v.index_()));
}
MaskType ge_(const CUDAArray &v) const {
const char *op = std::is_signed_v<Value>
? "setp.ge.$t2 $r1, $r2, $r3"
: "setp.hs.$t2 $r1, $r2, $r3";
return MaskType::from_index_(cuda_trace_append(
EnokiType::Bool, op, index_(), v.index_()));
}
MaskType lt_(const CUDAArray &v) const {
const char *op = std::is_signed_v<Value>
? "setp.lt.$t2 $r1, $r2, $r3"
: "setp.lo.$t2 $r1, $r2, $r3";
return MaskType::from_index_(cuda_trace_append(
EnokiType::Bool, op, index_(), v.index_()));
}
MaskType le_(const CUDAArray &v) const {
const char *op = std::is_signed_v<Value>
? "setp.le.$t2 $r1, $r2, $r3"
: "setp.ls.$t2 $r1, $r2, $r3";
return MaskType::from_index_(cuda_trace_append(
EnokiType::Bool, op, index_(), v.index_()));
}
MaskType eq_(const CUDAArray &v) const {
const char *op = !std::is_same_v<Value, bool>
? "setp.eq.$t2 $r1, $r2, $r3" :
"xor.$t2 $r1, $r2, $r3;\n not.$t2 $r1, $r1";
return MaskType::from_index_(cuda_trace_append(
EnokiType::Bool, op, index_(), v.index_()));
}
MaskType neq_(const CUDAArray &v) const {
const char *op = !std::is_same_v<Value, bool>
? "setp.ne.$t2 $r1, $r2, $r3" :
"xor.$t2 $r1, $r2, $r3";
return MaskType::from_index_(cuda_trace_append(
EnokiType::Bool, op, index_(), v.index_()));
}
static CUDAArray select_(const MaskType &m, const CUDAArray &t, const CUDAArray &f) {
if constexpr (!std::is_same_v<Value, bool>) {
return CUDAArray::from_index_(cuda_trace_append(Type,
"selp.$t1 $r1, $r2, $r3, $r4", t.index_(), f.index_(), m.index_()));
} else {
return (m & t) | (~m & f);
}
}
static CUDAArray arange_(ssize_t start, ssize_t stop, ssize_t step) {
size_t size = size_t((stop - start + step - (step > 0 ? 1 : -1)) / step);
using UInt32 = CUDAArray<uint32_t>;
UInt32 index = UInt32::from_index_(
cuda_trace_append(EnokiType::UInt32, "mov.u32 $r1, $r2", 2));
cuda_var_set_size(index.index_(), size);
if (start == 0 && step == 1)
return index;
else
return fmadd(index, CUDAArray((Value) step), CUDAArray((Value) start));
}
static CUDAArray linspace_(Value min, Value max, size_t size) {
using UInt32 = CUDAArray<uint32_t>;
UInt32 index = UInt32::from_index_(
cuda_trace_append(EnokiType::UInt32, "mov.u32 $r1, $r2", 2));
cuda_var_set_size(index.index_(), size);
Value step = (max - min) / Value(size - 1);
return fmadd(index, CUDAArray(step), CUDAArray(min));
}
static CUDAArray empty_(size_t size) {
return CUDAArray::from_index_(cuda_var_register(
Type, size, cuda_malloc(size * sizeof(Value)), true));
}
static CUDAArray zero_(size_t size) {
if (size == 1)
return CUDAArray(Value(0));
else
return CUDAArray::from_index_(cuda_var_register(
Type, size, cuda_malloc_zero(size * sizeof(Value)), true));
}
static CUDAArray full_(const Value &value, size_t size) {
if (size == 1)
return CUDAArray(value);
else
return CUDAArray::from_index_(cuda_var_register(
Type, size, cuda_malloc_fill(size, memcpy_cast<uint_array_t<Value>>(value)), true));
}
CUDAArray hsum_() const {
size_t n = size();
if (n == 1) {
return *this;
} else {
cuda_eval_var(m_index);
Value *result = cuda_hsum(n, (const Value *) cuda_var_ptr(m_index));
return CUDAArray::from_index_(cuda_var_register(Type, 1, result, true));
}
}
CUDAArray hprod_() const {
size_t n = size();
if (n == 1) {
return *this;
} else {
cuda_eval_var(m_index);
Value *result = cuda_hprod(n, (const Value *) cuda_var_ptr(m_index));
return CUDAArray::from_index_(cuda_var_register(Type, 1, result, true));
}
}
CUDAArray hmax_() const {
size_t n = size();
if (n == 1) {
return *this;
} else {
cuda_eval_var(m_index);
Value *result = cuda_hmax(n, (const Value *) cuda_var_ptr(m_index));
return CUDAArray::from_index_(cuda_var_register(Type, 1, result, true));
}
}
CUDAArray hmin_() const {
size_t n = size();
if (n == 1) {
return *this;
} else {
cuda_eval_var(m_index);
Value *result = cuda_hmin(n, (const Value *) cuda_var_ptr(m_index));
return CUDAArray::from_index_(cuda_var_register(Type, 1, result, true));
}
}
bool all_() const {
size_t n = size();
if (n == 1) {
return coeff(0);
} else {
cuda_eval_var(m_index);
return cuda_all(n, (const Value *) cuda_var_ptr(m_index));
}
}
bool any_() const {
size_t n = size();
if (n == 1) {
return coeff(0);
} else {
cuda_eval_var(m_index);
return cuda_any(n, (const Value *) cuda_var_ptr(m_index));
}
}
size_t count_() const {
cuda_eval_var(m_index);
return cuda_count(cuda_var_size(m_index), (const Value *) cuda_var_ptr(m_index));
}
static CUDAArray map(void *ptr, size_t size, bool dealloc = false) {
return CUDAArray::from_index_(cuda_var_register(Type, size, ptr, dealloc));
}
static CUDAArray copy(void *ptr, size_t size) {
return CUDAArray::from_index_(cuda_var_copy_to_device(Type, size, ptr));
}
template <typename T = Value, enable_if_t<std::is_pointer_v<T>> = 0>
std::vector<std::pair<Value, CUDAArray<uint32_t>>> partition_() const {
cuda_eval_var(m_index);
void **unique = nullptr;
uint32_t *counts = nullptr;
uint32_t **perm = nullptr;
size_t num_unique = cuda_partition(size(), (const void **) data(),
&unique, &counts, &perm);
std::vector<std::pair<Value, CUDAArray<uint32_t>>> result;
result.reserve(num_unique);
for (size_t i = 0; i < num_unique; ++i) {
result.emplace_back(
(Value) unique[i],
CUDAArray<uint32_t>::from_index_(cuda_var_register(
EnokiType::UInt32, counts[i], perm[i], true)));
}
free(unique);
free(counts);
free(perm);
return result;
}
template <size_t Stride, typename Index, typename Mask>
static CUDAArray gather_(const void *ptr_, const Index &index,
const Mask &mask) {
using UInt64 = CUDAArray<uint64_t>;
UInt64 ptr = UInt64::from_index_(cuda_var_register_ptr(ptr_)),
addr = fmadd(UInt64(index), (uint64_t) Stride, ptr);
if constexpr (!std::is_same_v<Value, bool>) {
return CUDAArray::from_index_(cuda_trace_append(
Type,
"@$r3 ld.global.$t1 $r1, [$r2];\n @!$r3 mov.$b1 $r1, 0",
addr.index_(), mask.index_()));
} else {
return neq(CUDAArray<uint32_t>::from_index_(cuda_trace_append(
EnokiType::UInt32,
"@$r3 ld.global.u8 $r1, [$r2];\n @!$r3 mov.$b1 $r1, 0",
addr.index_(), mask.index_())), 0u);
}
}
template <size_t Stride, typename Index, typename Mask>
ENOKI_INLINE void scatter_(void *ptr_, const Index &index, const Mask &mask) const {
using UInt64 = CUDAArray<uint64_t>;
UInt64 ptr = UInt64::from_index_(cuda_var_register_ptr(ptr_)),
addr = fmadd(UInt64(index), (uint64_t) Stride, ptr);
CUDAArray::Index var;
if constexpr (!std::is_same_v<Value, bool>) {
var = cuda_trace_append(EnokiType::UInt64,
"@$r4 st.global.$t3 [$r2], $r3",
addr.index_(), m_index, mask.index_()
);
} else {
using UInt32 = CUDAArray<uint32_t>;
UInt32 value = select(*this, UInt32(1), UInt32(0));
var = cuda_trace_append(EnokiType::UInt64,
"@$r4 st.global.u8 [$r2], $r3",
addr.index_(), value.index_(), mask.index_()
);
}
cuda_var_mark_side_effect(var);
}
template <size_t Stride, typename Index, typename Mask>
void scatter_add_(void *ptr_, const Index &index, const Mask &mask) const {
using UInt64 = CUDAArray<uint64_t>;
UInt64 ptr = UInt64::from_index_(cuda_var_register_ptr(ptr_)),
addr = fmadd(UInt64(index), (uint64_t) Stride, ptr);
CUDAArray::Index var = cuda_trace_append(Type,
"@$r4 atom.global.add.$t1 $r1, [$r2], $r3",
addr.index_(), m_index, mask.index_()
);
cuda_var_mark_side_effect(var);
}
template <typename Mask> CUDAArray compress_(const Mask &mask) const {
if (mask.size() == 0)
return CUDAArray();
else if (size() == 1 && mask.size() != 0)
return *this;
else if (mask.size() != size())
throw std::runtime_error("CUDAArray::compress_(): size mismatch!");
cuda_eval_var(m_index);
cuda_eval_var(mask.index_());
Value *ptr;
size_t new_size;
cuda_compress(size(), (const Value *) data(),
(const bool *) mask.data(), &ptr, &new_size);
return map(ptr, new_size, true);
}
auto operator->() const {
using BaseType = std::decay_t<std::remove_pointer_t<Value>>;
return call_support<BaseType, CUDAArray>(*this);
}
Index index_() const { return m_index; }
size_t size() const { return cuda_var_size(m_index); }
bool empty() const { return size() == 0; }
const void *data() const { return cuda_var_ptr(m_index); }
void *data() { return cuda_var_ptr(m_index); }
void resize(size_t size) {
m_index = cuda_var_set_size(m_index, size, true);
}
Value coeff(size_t i) const {
Value result = (Value) 0;
cuda_fetch_element(&result, m_index, i, sizeof(Value));
return result;
}
static CUDAArray from_index_(Index index) {
CUDAArray a;
a.m_index = index;
return a;
}
protected:
Index m_index = 0;
};
template <typename T, enable_if_t<!is_diff_array_v<T> && is_cuda_array_v<T>> = 0>
ENOKI_INLINE void set_label(const T& a, const char *label) {
if constexpr (array_depth_v<T> >= 2) {
for (size_t i = 0; i < T::Size; ++i)
set_label(a.coeff(i), (std::string(label) + "." + std::to_string(i)).c_str());
} else {
cuda_var_set_label(a.index_(), label);
}
}
template <typename T> class cuda_managed_allocator {
public:
using value_type = T;
using reference = T &;
using const_reference = const T &;
cuda_managed_allocator() = default;
template <typename T2>
cuda_managed_allocator(const cuda_managed_allocator<T2> &) { }
value_type *allocate(size_t n) {
return (value_type *) cuda_managed_malloc(n * sizeof(T));
}
void deallocate(value_type *ptr, size_t) {
cuda_free(ptr);
}
bool operator==(const cuda_managed_allocator &) { return true; }
bool operator!=(const cuda_managed_allocator &) { return false; }
};
template <typename T> class cuda_host_allocator {
public:
using value_type = T;
using reference = T &;
using const_reference = const T &;
cuda_host_allocator() = default;
template <typename T2>
cuda_host_allocator(const cuda_host_allocator<T2> &) { }
value_type *allocate(size_t n) {
return (value_type *) cuda_host_malloc(n * sizeof(T));
}
void deallocate(value_type *ptr, size_t) {
cuda_host_free(ptr);
}
bool operator==(const cuda_host_allocator &) { return true; }
bool operator!=(const cuda_host_allocator &) { return false; }
};
#define ENOKI_PINNED_OPERATOR_NEW() \
void *operator new(size_t size) { return cuda_host_malloc(size); } \
void operator delete(void *ptr) { cuda_host_free(ptr); } \
void *operator new(size_t size, std::align_val_t) { \
return operator new(size); \
} \
void *operator new[](size_t size) { return operator new(size); } \
void *operator new[](size_t size, std::align_val_t) { \
return operator new(size); \
} \
void operator delete(void *ptr, std::align_val_t) { \
operator delete(ptr); \
} \
void operator delete[](void *ptr) { operator delete(ptr); } \
void operator delete[](void *ptr, std::align_val_t) { \
operator delete(ptr); \
}
#if defined(ENOKI_AUTODIFF) && !defined(ENOKI_BUILD)
extern ENOKI_IMPORT template struct Tape<CUDAArray<float>>;
extern ENOKI_IMPORT template struct DiffArray<CUDAArray<float>>;
extern ENOKI_IMPORT template struct Tape<CUDAArray<double>>;
extern ENOKI_IMPORT template struct DiffArray<CUDAArray<double>>;
#endif
NAMESPACE_END(enoki)
| [
"[email protected]"
] | |
987261cb715375923269165e627b56837ba7557c | 4e97f5b16d06e91e1731df2c5e0cb1c8983a6add | /链表/leetcode_27.h | 567ea95faa17b3cf3b8fe913e9a1a0774565234f | [] | no_license | Xiaoctw/LeetCode_Cplus | 951bec0808e738f9d7beafbb0eda3989cd884084 | 18858b7f35421a2839f69fc784e2d09eb0bd6fff | refs/heads/master | 2020-04-18T22:03:31.085853 | 2019-02-09T05:45:04 | 2019-02-09T05:45:04 | 167,783,116 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 832 | h | //
// Created by xiao on 19-1-26.
//
#ifndef LEETCODE_移除链表元素_27_H
#define LEETCODE_移除链表元素_27_H
#include <malloc.h>
#include <cstdio>
#include <cstdlib>
struct ListNode {
int val;
ListNode *next;
explicit ListNode(int x) : val(x), next(nullptr) {}
};
/**
* 移除链表元素
*/
class leetcode_27 {
ListNode* removeElements(ListNode* head, int val) {
auto * newHead=new ListNode(0);
newHead->next=head;
ListNode* pre=newHead;
ListNode* p=head;
while (p!=nullptr){
if (p->val==val){
pre->next=p->next;
p=p->next;
} else{
p=p->next;
pre=pre->next;
}
}
return newHead->next;
}
};
#endif //LEETCODE_移除链表元素_27_H
| [
"[email protected]"
] | |
cd0c5a73de0cfed31673bf50a27034f8b4667495 | 28c470efa11a7ffff10e24a73c337a93f3a0b9f4 | /T13IO/MyWidget.cpp | 4bc4c3a2a05e632a4a96eb52cf2c8da5d196e29a | [] | no_license | N7Utb/QT-Study-note | f9b237e19ce32b8c535784bb83d84856fd86af99 | 138c9c65c770518e8d1d0c052bce0424a502a139 | refs/heads/master | 2022-11-17T01:32:08.256996 | 2020-07-10T12:47:30 | 2020-07-10T12:47:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,860 | cpp | #include "MyWidget.h"
MyWidget::MyWidget(QWidget *parent) : QWidget(parent)
{
#if 0
QFile file("../MyTest.txt");
file.open(QIODevice::ReadWrite);
file.write("abc",4);
file.close();
#endif
#if 0
QByteArray ba("asds");
QString str("asds");
qDebug()<<ba.size()<<str.size();
#endif
#if 0
QBuffer buffer;
buffer.open(QIODevice::ReadWrite);
buffer.write("abc");
buffer.write("aabbcc");
buffer.close();
qDebug() << buffer.buffer();
#endif
#if 0
QBuffer buffer;
buffer.open(QIODevice::ReadWrite);
QPixmap pixmap("../abc.png");
pixmap.save(&buffer,"PNG");
buffer.close();
QPixmap pixmap2;
pixmap2.loadFromData(buffer.buffer());
QLabel* label = new QLabel(this);
label->setPixmap(pixmap2);
#endif
#if 0
QFile file("../textstream.txt");
file.open(QIODevice::ReadWrite);
QTextStream textstream(file);
textstream << 1 << "abc" << 1.2;
file.close();
#endif
#if 0
QFile file("../datastream.txt");
file.open(QIODevice::ReadWrite);
QDataStream datastream(&file);
datastream << 1 << "abc" << 1.2;
file.close();
#endif
QFile file("../map.data");
file.open(QIODevice::ReadWrite);
file.seek(65535);
file.write("1");
file.close();
file.open(QIODevice::ReadWrite);
uchar* ptr = file.map(0,64*1024);
*ptr = 'a';
ptr[1] = 'b';
file.unmap(ptr);
file.close();
}
int main(int argc,char* argv[])
{
QApplication app(argc,argv);
#if 0
TcpServe s;
s.show();
TcpClient c;
c.show();
s.setWindowTitle("server");
c.setWindowTitle("Client");
#endif
Udp1 udp1;
udp1.show();
Udp2 udp2;
udp2.show();
udp1.setWindowTitle("udp1");
udp2.setWindowTitle("udp2");
app.exec();
}
| [
"[email protected]"
] | |
2e206cc6012e1c814c1198c6c34703ddc1199d55 | e5a37a543ca382ed3eaab28c37d267b04ad667c0 | /probrems/SRM454div2/easy.cpp | 351fd126338b6b08d2e1415363f0a88cd1c531a8 | [] | no_license | akawashiro/competitiveProgramming | 6dfbe626c2e2433d5e702e9431ee9de2c41337ed | ee8a582c80dbd5716ae900a02e8ea67ff8daae4b | refs/heads/master | 2018-09-02T19:49:22.460865 | 2018-06-30T05:45:51 | 2018-06-30T05:45:51 | 71,694,415 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 415 | cpp | #include <math.h>
#include <vector>
using namespace std;
class MinimalDifference{
public:
int digitSum(int n)
{
int r=0;
while(0<n){
r+=n%10;
n/=10;
}
return r;
}
int findNumber(int A, int B, int C)
{
int cDig=digitSum(C);
int ans=min(A,B);
for(int i=min(A,B);i<=max(A,B);i++)
if( abs(cDig-digitSum(i)) < abs(cDig-digitSum(ans)) )
ans=i;
return ans;
}
};
| [
"[email protected]"
] | |
7f9988bc64d7e3836ebd2a990b528677ee5a1997 | 979e2b52c768d0fd031812c0c9787be24476b693 | /Mythology/GameEngine/Commands/Render/UpdateInstanceCommand.h | 9743770aedc72b736f7e918ab30bbf8228c63d4b | [] | no_license | JPMMaia/mythology-legacy | cf54215a6fb435d13b56985ea836b0d203b19c21 | f34ac9e6b2c1c407d48ee942d5aba8204d2604aa | refs/heads/master | 2021-03-30T16:12:46.015866 | 2017-12-29T16:39:10 | 2017-12-29T16:39:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 586 | h | #pragma once
#include "../ICommand.h"
#include "Interfaces/IRenderScene.h"
namespace GameEngine
{
class UpdateInstanceCommand : public ICommand
{
public:
UpdateInstanceCommand(IRenderScene& scene, const std::string& meshName, const std::shared_ptr<InstancedMeshComponent>& instance) :
m_scene(scene),
m_meshName(meshName),
m_instance(instance)
{
}
public:
void Execute() override
{
m_scene.UpdateInstance(m_meshName, m_instance);
}
private:
IRenderScene & m_scene;
std::string m_meshName;
std::shared_ptr<InstancedMeshComponent> m_instance;
};
}
| [
"[email protected]"
] | |
6788c837b7a609efb03488c446d7feaa9970ac85 | 989aa92c9dab9a90373c8f28aa996c7714a758eb | /HydraIRC/MainFrm.h | 7e1b9ee3e821cace7f04608a12abc640e5da4b71 | [] | no_license | john-peterson/hydrairc | 5139ce002e2537d4bd8fbdcebfec6853168f23bc | f04b7f4abf0de0d2536aef93bd32bea5c4764445 | refs/heads/master | 2021-01-16T20:14:03.793977 | 2010-04-03T02:10:39 | 2010-04-03T02:10:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 21,079 | h | /*
HydraIRC
Copyright (C) 2002-2006 Dominic Clifton aka Hydra
HydraIRC limited-use source license
1) You can:
1.1) Use the source to create improvements and bug-fixes to send to the
author to be incorporated in the main program.
1.2) Use it for review/educational purposes.
2) You can NOT:
2.1) Use the source to create derivative works. (That is, you can't release
your own version of HydraIRC with your changes in it)
2.2) Compile your own version and sell it.
2.3) Distribute unmodified, modified source or compiled versions of HydraIRC
without first obtaining permission from the author. (I want one place
for people to come to get HydraIRC from)
2.4) Use any of the code or other part of HydraIRC in anything other than
HydraIRC.
3) All code submitted to the project:
3.1) Must not be covered by any license that conflicts with this license
(e.g. GPL code)
3.2) Will become the property of HydraIRC's author.
*/
// MainFrm.h : interface of the CMainFrame class
//
/////////////////////////////////////////////////////////////////////////////
#pragma once
class CChildFrame;
typedef dockwins::CDockingFrameTraitsT< dockwins::CVC7LikeAutoHidePaneTraits, dockwins::CSimpleSplitterBar<3>,
WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN | WS_CLIPSIBLINGS,
WS_EX_APPWINDOW | WS_EX_WINDOWEDGE> CMainFrameTraits;
class CMainFrame :
public dockwins::CAutoHideMDIDockingFrameImpl<CMainFrame, CHidingMDIWindow, CMainFrameTraits, dockwins::CVC7LikeAutoHidePaneTraits>,
public CUpdateUI<CMainFrame>,
public CMessageFilter,
public CIdleHandler
{
protected:
typedef CMainFrame thisClass;
typedef dockwins::CAutoHideMDIDockingFrameImpl<CMainFrame, CHidingMDIWindow, CMainFrameTraits, dockwins::CVC7LikeAutoHidePaneTraits> baseClass;
public:
#ifdef USE_XPCOMMANDBAR
CMDICommandBarXPCtrl m_CmdBar;
//CMDICommandBarCtrl m_CmdBar;
#else
#ifdef USE_TABBEDMDI
CTabbedMDIClient<CDotNetTabCtrl<CTabViewTabItem> > m_tabbedClient;
CTabbedMDICommandBarCtrl m_CmdBar;
#else
CMDICommandBarCtrl m_CmdBar;
#endif
#endif // !USE_XPCOMMANDBAR
private:
int m_StatusBarWidths[4];
HWND createToolbar();
void SetStatusPaneWidths(int* arrWidths, int nPanes);
void UpdateStatusBar( void );
char m_StatusBarText[SETSTATUSBARTEXT_BUFFER_SIZE];
char m_StatusBarNick[SETSTATUSBARNICK_BUFFER_SIZE];
time_t m_StatusBarTime;
BOOL m_StatusBarDirty;
int m_StatusBarIconID;
int m_StatusBarNickIconID;
IDManager m_FavoriteIDs;
int m_FavoriteRootItems;
void MinimizeToSystray( void );
CTaskBarIcon m_TI;
BOOL m_WasMaximized; // store the state of the window before hiding it
// used to decide where to send the USERLIST context menu command messages
HWND m_LastUserListMenuWindow;
CUserListView *m_pLastUserListMenuView;
public:
DECLARE_FRAME_WND_CLASS(NULL, IDR_MAINFRAME)
// Gui stuff
sstate::CWindowStateMgr m_stateMgr;
CServerListView m_ServerListView;
CUserListView m_UserListView;
COutputView m_OutputView;
CChannelMonitorView m_ChannelMonitorView;
CServerMonitorView m_ServerMonitorView;
CMultiPaneStatusBarCtrl m_Status;
IDManager m_ToolbarUserIDs;
CImageList m_images_toolbar;
IDManager m_ToolbarImageListIDs;
CMainFrame()
: m_ChannelMonitorView(IDI_CHANNELMONITOR,&g_EventManager),
m_ServerMonitorView(IDI_SERVERMONITOR,&g_EventManager),
m_OutputView(IDI_OUTPUT,&g_EventManager),
// m_stateMgr(NULL,SW_SHOWMAXIMIZED), // SW_SHOWMAXIMIZED is ignored due to call to m_stateMgr->Initialise()
m_ServerListView(IDI_SERVER),
m_UserListView((IRCChannel *)NULL,IDI_USERLIST,&g_EventManager)
{
m_Timer = NULL;
m_OkToQuit = 0;
strcpy(m_StatusBarText,g_DefaultStrings[DEFSTR_DefaultStatusBarMessage]);
m_StatusBarNick[0] = 0;
m_StatusBarTime = time(NULL);
m_StatusBarIconID = STATUS_ICON_NONE;
m_StatusBarNickIconID = ICONID_USERS;
m_StatusBarDirty = TRUE;
m_FavoriteRootItems = 0;
m_FavoriteIDs.SetIDRange(ID_FAVORITES_FIRST,ID_FAVORITES_LAST);
m_ToolbarUserIDs.SetIDRange(ID_TOOLBARUSER_FIRST,ID_TOOLBARUSER_LAST);
m_ToolbarImageListIDs.SetIDRange(1,255);
m_LastUserListMenuWindow = NULL;
m_pLastUserListMenuView = NULL;
}
~CMainFrame( void );
// other stuff.
CImageList m_images_serverlist; // public, because the serverlist class uses it..
short m_OkToQuit;
// Timer for the event manager
INT_PTR m_Timer; // uses TID_MAINFRAME
virtual BOOL PreTranslateMessage(MSG* pMsg);
virtual BOOL OnIdle();
virtual bool IsToolbarVisible(int ID) const;
void UpdateGlobalUserList(IRCChannel *pChannel, BOOL Clear = FALSE, BOOL Refresh = FALSE);
void ClearGlobalUserList( void );
void DoPrefs( int PageNum = -1);
void BuildFavoritesMenu( void );
void RestoreWindow( void );
void RefreshAllChildWindows( void ); // called by prefs and after some /set commands.
void SetStatusBar( const int IconID, const char *message );
void ChangeGUILayoutStyle(int LayoutStyle);
void ToggleMonitoring(CChildFrame *pChildWnd);
void ToggleTimeStamps(CChildFrame *pChild);
void ToggleLogging(CChildFrame *pChild);
void SetUserListMenuWindow(HWND hWnd)
{ m_LastUserListMenuWindow = hWnd; }
void SetUserListMenuInstance(CUserListView *pUserListView)
{ m_pLastUserListMenuView = pUserListView; }
BEGIN_MSG_MAP(CMainFrame)
//sys_Printf(BIC_GUI,"message: %x - code: %x\n",uMsg, uMsg == WM_NOTIFY ? ((LPNMHDR)lParam)->code : 0);
MESSAGE_HANDLER(CWM_INITIALIZE, OnInitialize)
MESSAGE_HANDLER(WM_COPYDATA,OnCopyData)
MESSAGE_HANDLER(WMU_WHERE_ARE_YOU, onWhereAreYou)
MESSAGE_HANDLER(WM_IDENTDEVENT, g_pIdentd->OnIdentdEvent)
MESSAGE_HANDLER(WM_TRANSFEREVENT, g_pTransfersManager->OnTransferEvent)
MESSAGE_HANDLER(WM_PROCESSDCCS, g_pTransfersManager->OnProcessDCCs)
MESSAGE_HANDLER(WM_REQUESTAUTOTILE,OnRequestAutoTile)
MESSAGE_HANDLER(WM_REQUESTSCROLLTOEND,OnRequestScrollToEnd)
MESSAGE_HANDLER(WM_CHILDFRAMECLOSED,OnChildFrameClosed)
MESSAGE_HANDLER(WM_CREATE, OnCreate)
MESSAGE_HANDLER(WM_DESTROY, OnDestroy)
MESSAGE_HANDLER(WM_CLOSE, OnClose)
MESSAGE_HANDLER(WM_TIMER, OnTimer)
MESSAGE_HANDLER(WM_SIZE, OnSize)
MESSAGE_HANDLER(WM_SYSCOMMAND, OnSysCommand)
// required by docking framework.
MESSAGE_HANDLER(WM_SETTINGCHANGE, OnSettingChange)
MESSAGE_HANDLER(WM_SYSCOLORCHANGE, OnSysColorChange)
// misc
COMMAND_ID_HANDLER(ID_APP_EXIT, OnFileExit)
COMMAND_ID_HANDLER(ID_FILE_NEW, OnFileNew)
COMMAND_ID_HANDLER(ID_FILE_CLOSE, OnFileCloseWindow)
COMMAND_ID_HANDLER(ID_FILE_DISCONNECT, OnFileDisconnect)
COMMAND_ID_HANDLER(ID_FILE_CONNECT, OnFileConnect)
// view menu
COMMAND_ID_HANDLER(ID_VIEW_TOOLBAR, OnViewToolBar)
COMMAND_ID_HANDLER(ID_VIEW_STATUS_BAR, OnViewStatusBar)
// these turn on and off docking windows..
COMMAND_TOGGLE_MEMBER_HANDLER(ID_VIEW_IRCSERVERLIST ,m_ServerListView)
COMMAND_TOGGLE_MEMBER_HANDLER(ID_VIEW_GLOBALUSERLIST ,m_UserListView)
COMMAND_TOGGLE_MEMBER_HANDLER(ID_VIEW_OUTPUT ,m_OutputView)
COMMAND_TOGGLE_MEMBER_HANDLER(ID_VIEW_CHANNELMONITOR ,m_ChannelMonitorView)
COMMAND_TOGGLE_MEMBER_HANDLER(ID_VIEW_SERVERMONITOR ,m_ServerMonitorView)
COMMAND_TOGGLE_MEMBER_HANDLER_PTR(ID_VIEW_EVENTLOG ,g_pEventLogManager->m_pEventLogView)
COMMAND_TOGGLE_MEMBER_HANDLER_PTR(ID_VIEW_PRIVMSGQUEUE ,g_pPrivMsgQueueManager->m_pTextQueueView)
COMMAND_TOGGLE_MEMBER_HANDLER_PTR(ID_VIEW_NOTICEQUEUE ,g_pNoticeQueueManager->m_pTextQueueView)
COMMAND_TOGGLE_MEMBER_HANDLER_PTR(ID_VIEW_URLCATCHER ,g_pUrlCatcherManager->m_pTextQueueView)
COMMAND_TOGGLE_MEMBER_HANDLER_PTR(ID_VIEW_TRANSFERS ,g_pTransfersManager->m_pTransfersView)
COMMAND_ID_HANDLER(ID_GUILAYOUT_LAYOUT1,OnViewGuiLayout);
COMMAND_ID_HANDLER(ID_GUILAYOUT_LAYOUT2,OnViewGuiLayout);
COMMAND_ID_HANDLER(ID_GUILAYOUT_LAYOUT3,OnViewGuiLayout);
COMMAND_ID_HANDLER(ID_GUILAYOUT_LAYOUT4,OnViewGuiLayout);
COMMAND_ID_HANDLER(ID_GUILAYOUT_LAYOUT5,OnViewGuiLayout);
COMMAND_ID_HANDLER(ID_GUILAYOUT_HIDEALLDOCKERS,OnViewGuiLayout);
// favorites menu
COMMAND_ID_HANDLER(ID_FAVORITES_ORGANIZEFAVORITES, OnFavoritesOrganizeFavorites)
COMMAND_ID_HANDLER(ID_FAVORITES_ADDTOFAVORITES, OnFavoritesAddToFavorites)
COMMAND_RANGE_HANDLER(ID_FAVORITES_FIRST, ID_FAVORITES_LAST, OnFavoritesItemSelected)
// help menu
COMMAND_ID_HANDLER(ID_HELP_DOCUMENTATION,OnHelpDocumentation)
COMMAND_ID_HANDLER(ID_HELP_ONLINEDOCUMENTATION,OnHelpOnlineDocumentation)
COMMAND_ID_HANDLER(ID_HELP_RECENTCHANGES,OnHelpRecentChanges)
COMMAND_ID_HANDLER(ID_HELP_HYDRAIRCONTHEWEB,OnHelpHydraIRCOnTheWeb)
COMMAND_ID_HANDLER(ID_HELP_DONATE,OnHelpDonate)
COMMAND_ID_HANDLER(ID_HELP_REPORTABUG,OnHelpReportABug)
COMMAND_ID_HANDLER(ID_HELP_FORUMS,OnHelpForums)
COMMAND_ID_HANDLER(ID_APP_ABOUT, OnHelpAppAbout)
// Windows menu
COMMAND_ID_HANDLER(ID_WINDOW_CASCADE, OnWindowCascade)
COMMAND_ID_HANDLER(ID_WINDOW_TILE_HORZ, OnWindowTileHorz)
COMMAND_ID_HANDLER(ID_WINDOW_TILE_VERT, OnWindowTileVert)
COMMAND_ID_HANDLER(ID_WINDOW_MINIMIZEALLWINDOWS, OnWindowMinimizeAllWindows)
COMMAND_ID_HANDLER(ID_WINDOW_MINIMIZEACTIVEWINDOW, OnWindowMinimizeActiveWindow)
//COMMAND_ID_HANDLER(ID_WINDOW_ARRANGE, OnWindowArrangeIcons)
// toolbar and menus
COMMAND_ID_HANDLER(ID_OPTIONS_TOGGLEINFO, OnToggleInfo)
COMMAND_ID_HANDLER(ID_OPTIONS_TOGGLEHEADER, OnToggleHeader)
COMMAND_ID_HANDLER(ID_OPTIONS_TOGGLEUSERLIST, OnToggleUserList)
COMMAND_ID_HANDLER(ID_CHANNEL_MONITOR, OnToggleChannelMonitor)
COMMAND_ID_HANDLER(ID_CHANNEL_SHOWSERVER, OnChannelShowServer)
COMMAND_ID_HANDLER(ID_CHANNEL_PROPERTIES, OnChannelProperties)
COMMAND_ID_HANDLER(ID_CHANNEL_CHANNELLIST, OnChannelChannelList)
// options menu
COMMAND_ID_HANDLER(ID_OPTIONS_LOGGING, OnToggleOptionLogging)
COMMAND_ID_HANDLER(ID_OPTIONS_TIMESTAMPS, OnToggleOptionTimeStamps)
COMMAND_ID_HANDLER(ID_OPTIONS_AUDIOMUTE, OnToggleOptionsAudioMute)
COMMAND_ID_HANDLER(ID_OPTIONS_PREFS, OnOptionsPrefs)
COMMAND_RANGE_HANDLER(ID_TOOLBARUSER_FIRST, ID_TOOLBARUSER_LAST, OnToolbarUserItemSelected)
// edit menu
COMMAND_ID_HANDLER(ID_EDIT_CUT,OnEditCut)
COMMAND_ID_HANDLER(ID_EDIT_COPY,OnEditCopy)
COMMAND_ID_HANDLER(ID_EDIT_PASTE,OnEditPaste)
COMMAND_ID_HANDLER(ID_EDIT_COPYBUFFER,OnEditCopyBuffer)
COMMAND_ID_HANDLER(ID_EDIT_CLEARBUFFER,OnEditClearBuffer)
// commands, only because of testxp's context menu handling
COMMAND_RANGE_HANDLER(ID_EVENTLOGMENU_FIRST,ID_EVENTLOGMENU_LAST,OnEventLogCommands)
COMMAND_RANGE_HANDLER(ID_TRANSFERSMENU_FIRST,ID_TRANSFERSMENU_LAST,OnTransfersCommands)
COMMAND_RANGE_HANDLER(ID_SERVERLISTMENU_FIRST,ID_SERVERLISTMENU_LAST,OnServerListCommands)
// need this one to forward the userlist command messages back to the right MDI child
// if we don't do this they get sent to the active mdi window
// by the macro CHAIN_MDI_CHILD_COMMANDS, the active mdi window
// might not be the right one in the case of users
// selecting items from the global user list while an MDI server window is active.
COMMAND_RANGE_HANDLER(ID_USERLISTFIRST,ID_USERLISTLAST,OnUserListCommands)
// systray icon
TASKBAR_MESSAGE_HANDLER(m_TI, WM_LBUTTONUP, OnSystrayIconClick)
// systray menu
COMMAND_ID_HANDLER(ID_TASKBARMENU_RESTORE, OnTaskBarMenuRestore)
CHAIN_MDI_CHILD_COMMANDS()
CHAIN_MSG_MAP_MEMBER(m_TI)
CHAIN_MSG_MAP(CUpdateUI<CMainFrame>)
CHAIN_MSG_MAP(baseClass)
END_MSG_MAP()
BEGIN_UPDATE_UI_MAP(CMainFrame)
UPDATE_ELEMENT(ID_VIEW_EVENTLOG, UPDUI_MENUPOPUP | UPDUI_TOOLBAR)
UPDATE_ELEMENT(ID_VIEW_TRANSFERS, UPDUI_MENUPOPUP | UPDUI_TOOLBAR)
UPDATE_ELEMENT(ID_VIEW_NOTICEQUEUE, UPDUI_MENUPOPUP)// | UPDUI_TOOLBAR)
UPDATE_ELEMENT(ID_VIEW_PRIVMSGQUEUE, UPDUI_MENUPOPUP)// | UPDUI_TOOLBAR)
UPDATE_ELEMENT(ID_VIEW_URLCATCHER, UPDUI_MENUPOPUP)// | UPDUI_TOOLBAR)
UPDATE_ELEMENT(ID_VIEW_CHANNELMONITOR, UPDUI_MENUPOPUP | UPDUI_TOOLBAR)
UPDATE_ELEMENT(ID_VIEW_SERVERMONITOR, UPDUI_MENUPOPUP | UPDUI_TOOLBAR)
UPDATE_ELEMENT(ID_VIEW_OUTPUT, UPDUI_MENUPOPUP | UPDUI_TOOLBAR)
UPDATE_ELEMENT(ID_VIEW_IRCSERVERLIST, UPDUI_MENUPOPUP | UPDUI_TOOLBAR)
UPDATE_ELEMENT(ID_VIEW_GLOBALUSERLIST, UPDUI_MENUPOPUP | UPDUI_TOOLBAR)
UPDATE_ELEMENT(ID_VIEW_STATUS_BAR, UPDUI_MENUPOPUP)
UPDATE_ELEMENT(ID_VIEW_TOOLBAR, UPDUI_MENUPOPUP)
UPDATE_ELEMENT(ID_EDIT_CUT, UPDUI_MENUPOPUP)
UPDATE_ELEMENT(ID_EDIT_COPY, UPDUI_MENUPOPUP)
UPDATE_ELEMENT(ID_EDIT_PASTE, UPDUI_MENUPOPUP)
UPDATE_ELEMENT(ID_EDIT_COPYBUFFER, UPDUI_MENUPOPUP)
UPDATE_ELEMENT(ID_EDIT_CLEARBUFFER, UPDUI_MENUPOPUP)
UPDATE_ELEMENT(ID_FILE_CLOSE, UPDUI_MENUPOPUP)
UPDATE_ELEMENT(ID_FILE_CONNECT, UPDUI_MENUPOPUP | UPDUI_TOOLBAR)
UPDATE_ELEMENT(ID_FILE_DISCONNECT, UPDUI_MENUPOPUP | UPDUI_TOOLBAR)
UPDATE_ELEMENT(ID_CHANNEL_MONITOR, UPDUI_MENUPOPUP | UPDUI_TOOLBAR)
UPDATE_ELEMENT(ID_CHANNEL_SHOWSERVER, UPDUI_MENUPOPUP)
UPDATE_ELEMENT(ID_CHANNEL_PROPERTIES, UPDUI_MENUPOPUP)
UPDATE_ELEMENT(ID_CHANNEL_CHANNELLIST, UPDUI_MENUPOPUP)
UPDATE_ELEMENT(ID_OPTIONS_LOGGING, UPDUI_MENUPOPUP | UPDUI_TOOLBAR)
UPDATE_ELEMENT(ID_OPTIONS_TIMESTAMPS, UPDUI_MENUPOPUP)
UPDATE_ELEMENT(ID_OPTIONS_AUDIOMUTE, UPDUI_MENUPOPUP | UPDUI_TOOLBAR)
UPDATE_ELEMENT(ID_OPTIONS_TOGGLEINFO, UPDUI_MENUPOPUP)
UPDATE_ELEMENT(ID_OPTIONS_TOGGLEHEADER, UPDUI_MENUPOPUP)
UPDATE_ELEMENT(ID_OPTIONS_TOGGLEUSERLIST, UPDUI_MENUPOPUP | UPDUI_TOOLBAR)
END_UPDATE_UI_MAP()
// Handler prototypes (uncomment arguments if needed):
// LRESULT MessageHandler(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
// LRESULT CommandHandler(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
// LRESULT NotifyHandler(int /*idCtrl*/, LPNMHDR /*pnmh*/, BOOL& /*bHandled*/)
// file menu
LRESULT OnFileExit(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
LRESULT OnFileNew(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
LRESULT OnFileCloseWindow(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
LRESULT OnFileConnect(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
LRESULT OnFileDisconnect(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
// view menu
LRESULT OnViewToolBar(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
LRESULT OnViewStatusBar(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
LRESULT OnViewGuiLayout(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
// favorites menu
LRESULT OnFavoritesOrganizeFavorites(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
LRESULT OnFavoritesAddToFavorites(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
LRESULT OnFavoritesItemSelected(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
// help menu
LRESULT OnHelpAppAbout(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
LRESULT OnHelpHydraIRCOnTheWeb(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
LRESULT OnHelpDonate(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
LRESULT OnHelpDocumentation(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
LRESULT OnHelpOnlineDocumentation(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
LRESULT OnHelpRecentChanges(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
LRESULT OnHelpReportABug(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
LRESULT OnHelpForums(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
// window menu
LRESULT OnWindowCascade(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
LRESULT OnWindowTileHorz(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
LRESULT OnWindowTileVert(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
LRESULT OnWindowMinimizeAllWindows(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
LRESULT OnWindowMinimizeActiveWindow(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
// channel menu
LRESULT OnChannelShowServer(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
LRESULT OnChannelProperties(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
LRESULT OnChannelChannelList(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
// systray menu
LRESULT OnTaskBarMenuRestore(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
LRESULT OnToggleInfo(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
LRESULT OnToggleHeader(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
LRESULT OnToggleUserList(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
// channel related stuff
LRESULT OnToggleChannelMonitor(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
// server related stuff
LRESULT OnToggleServerMonitor(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
// option menu
LRESULT OnToggleOptionLogging(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
LRESULT OnToggleOptionTimeStamps(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
LRESULT OnToggleOptionsAudioMute(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
LRESULT OnOptionsPrefs(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
// Edit menu
LRESULT OnEditCut(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
LRESULT OnEditCopy(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
LRESULT OnEditPaste(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
LRESULT OnEditClearBuffer(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
LRESULT OnEditCopyBuffer(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
// Toolbar user buttons
LRESULT OnToolbarUserItemSelected(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
// general stuff
LRESULT OnEventLogCommands(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
LRESULT OnTransfersCommands(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
LRESULT OnServerListCommands(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
LRESULT OnUserListCommands(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
LRESULT OnInitialize(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/);
LRESULT OnCreate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/);
LRESULT OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/);
LRESULT OnClose(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled);
LRESULT OnSize(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled);
LRESULT OnSystrayIconClick(LPARAM /*uMsg*/, BOOL& /*bHandled*/);
LRESULT OnSysCommand(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled);
LRESULT OnTimer(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled);
LRESULT OnSettingChange(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/);
LRESULT OnSysColorChange(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled);
LRESULT OnRequestAutoTile(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& bHandled);
LRESULT OnRequestScrollToEnd(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& bHandled);
LRESULT OnChildFrameClosed(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& bHandled);
LRESULT OnCopyData(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& bHandled);
LRESULT onWhereAreYou(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{ return WMU_WHERE_ARE_YOU; }
LRESULT OnEnLink(int idCtrl, LPNMHDR pnmh, BOOL& bHandled);
void MDIActivate(HWND hWndChildToActivate);
};
| [
"hydra@b2473a34-e2c4-0310-847b-bd686bddb4b0"
] | hydra@b2473a34-e2c4-0310-847b-bd686bddb4b0 |
55b7f94cec2867a937fdaf39d0fc73572425de55 | 3af7ad136f6f21421d8ade905b1de01ce16b0860 | /speedy/src/java8speedy/parser/cpp_src/JavaLabeledParserBaseListener.cpp | b8413eed387223318b45303be81e4505df068d4e | [
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause",
"GPL-3.0-only"
] | permissive | m-zakeri/CodART | 75ba8324068d0bac93893f6c3a57fd684038e80a | 9e1031dbfda3b76fa1781be261bc4083ec8b5323 | refs/heads/main | 2023-08-18T13:28:37.812033 | 2023-08-05T21:44:44 | 2023-08-05T21:44:44 | 311,091,478 | 39 | 68 | MIT | 2023-01-19T07:45:33 | 2020-11-08T15:20:52 | Python | UTF-8 | C++ | false | false | 102 | cpp |
// Generated from JavaLabeledParser.g4 by ANTLR 4.9.3
#include "JavaLabeledParserBaseListener.h"
| [
"[email protected]"
] | |
1360d6a676d90d0a1f01511130e79ee7553f2463 | bb050105ba25fe1f3ca2e84d1f6b4689b02da4ce | /ErgonomieappTest/tst_controllertest.h | 6c6f22123857c8769ce1aecd244bc88e7309df93 | [] | no_license | Frank112/BP38Ergonomie | 0436deda83666b69ca37eb2dd3102c1acb238238 | d9474ec2b5a7942e453e6bb688c11af6c336ddef | refs/heads/master | 2020-04-06T16:20:52.350092 | 2015-04-27T14:55:54 | 2015-04-27T14:55:54 | 27,220,012 | 0 | 1 | null | 2015-03-28T10:43:35 | 2014-11-27T10:18:45 | C++ | UTF-8 | C++ | false | false | 6,029 | h | #ifndef TST_CONTROLLERTEST
#define TST_CONTROLLERTEST
#include <QObject>
#include <QtTest>
#include "../control/controller.h"
class ControllerTest : public QObject {
Q_OBJECT
public:
ControllerTest();
private Q_SLOTS:
void initTestCase();
void createAnalystSuccessfulTest();
void createAnalystFailedTest();
void deleteAnalystSuccessfulTest();
void deleteAnalystFailedTest();
void selectAnalystSuccessfulTest();
void selectAnalystFailedTest();
void createBlankRecording();
void setBranchOfIndustrySuccessfulTest();
void setBranchOfIndustryFailedTest();
void saveBranchOfIndustrySuccessfulTest();
void saveBranchOfIndustryFailedTest();
void setCorperationSuccessfulTest();
void setCorperationFailedTest();
void saveCorperationSuccessfulTest();
void saveCorperationFailedTest();
void setFactorySuccessfulTest();
void setFactoryFailedTest();
void saveFactorySuccessfulTest();
void saveFactoryFailedTest();
void setRecordingSuccessfulTest();
void setRecordingFailedTest();
void saveRecordingSuccessfulTest();
void saveRecordingFailedTest();
void createWorkplaceSuccessfulTest();
void createWorkplaceFailedTest();
void deleteWorkplaceSuccessfulTest();
void deleteWorkplaceFailedTest();
void selectWorkplaceSuccessfulTest();
void selectWorkplaceFailedTest();
void saveWorkplaceSuccessfulTest();
void saveWorkplaceFailedTest();
void saveCommentSuccessfulTest();
void saveCommentFailedTest();
void createLineSuccessfulTest();
void createLineFailedTest();
void editLineSuccessfulTest();
void editLineFailedTest();
void saveLineSuccessfulTest();
void saveLineFailedTest();
void deleteLineSuccessfulTest();
void deleteLineFailedTest();
void selectLineSuccessfulTest();
void selectLineFailedTest();
void createProductSuccessfulTest();
void createProductFailedTest();
void saveProductSuccessfulTest();
void saveProductFailedTest();
void deleteProductSuccessfulTest();
void deleteProductFailedTest();
void createActivitySuccessfulTest();
void createActivityFailedTest();
void deleteActivitySuccessfulTest();
void deleteActivityFailedTest();
void selectActivitySuccessfulTest();
void selectActivityFailedTest();
void saveActivitySuccessfulTest();
void saveActivityFailedTest();
void editActivitySuccessfulTest();
void editActivityFailedTest();
void createEquipmentSuccessfulTest();
void createEquipmentFailedTest();
void saveEquipmentSuccessfulTest();
void saveEquipmentFailedTest();
void deleteEquipmentSuccessfulTest();
void deleteEquipmentFailedTest();
void createTransportationSuccessfulTest();
void createTransportationFailedTest();
void saveTransportationSuccessfulTest();
void saveTransportationFailedTest();
void deleteTransportationSuccessfulTest();
void deleteTransportationFailedTest();
void saveLoadHandlingSuccessfulTest();
void saveLoadHandlingFailedTest();
void saveBodyPostureSuccessfulTest();
void saveBodyPostureFailedTest();
void saveAppliedForceSuccessfulTest();
void saveAppliedForceFailedTest();
void saveExecutionConditionSuccessfulTest();
void saveExecutionConditionFailedTest();
void saveWorkprocessSuccessfulTest();
void saveWorkprocessFailedTest();
void createWorkprocessSuccessfulTest();
void createWorkprocessFailedTest();
void createWorkprocessListSuccessfulTest();
void createWorkprocessListFailedTest();
void selectNextWorkprocessSuccessfulTest();
void selectPreviousWorkprocessSuccessfulTest();
void workprocessTypeChangedTest();
void resetWorkprocessesTest();
void workprocessDurationChangedSuccessfulTest();
void workprocessDurationChangedFailedTest();
void selectWorkprocessSuccessfulTest();
void selectWorkprocessFailedTest();
void saveWorkprocessFrequenceSuccessfulTest();
void saveWorkprocessFrequenceFailedTest();
void createEmployeeSuccessfulTest();
void createEmployeeFailedTest();
void createEmployeeBodyMeasurementSuccessfulTest();
void createEmployeeBodyMeasurementFailedTest();
void deleteEmployeeSuccessfulTest();
void deleteEmployeeFailedTest();
void selectEmployeeSuccessfulTest();
void selectEmployeeFailedTest();
void saveEmployeeSuccessfulTest();
void saveEmployeeFailedTest();
void setSelectedEmployeeSuccessfulTest();
void setSelectedEmployeeFailedTest();
void resetEmployeeSelectionTest();
void saveBodyMeasurementSuccessfulTest();
void saveBodyMeasurementFailedTest();
void saveShiftSuccessfulTest();
void saveShiftFailedTest();
void createRotationGroupEntrySuccessfulTest();
void createRotationGroupEntryFailedTest();
void createRotationGroupBreakEntrySuccessfulTest();
void createRotationGroupBreakEntryFailedTest();
void deleteRotationGroupEntrySuccessfulTest();
void deleteRotationGroupEntryFailedTest();
void moveRotationGroupEntryUpSuccessfulTest();
void moveRotationGroupEntryUpFailedTest();
void moveRotationGroupEntryDownSuccessfulTest();
void moveRotationGroupEntryDownFailedTest();
void createRotationGroupTaskSuccessfulTest();
void createRotationGroupTaskFailedTest();
void deleteRotationGroupTaskSuccessfulTest();
void deleteRotationGroupTaskFailedTest();
void selectRotationGroupTaskSuccessfulTest();
void selectRotationGroupTaskFailedTest();
void saveRotationGroupTaskSuccessfulTest();
void saveRotationGroupTaskFailedTest();
void createRotationGroupTaskEntrySuccessfulTest();
void createRotationGroupTaskEntryFailedTest();
void deleteRotationGroupTaskEntrySuccessfulTest();
void deleteRotationGroupTaskEntryFailedTest();
void resetDatabaseFactoryTest();
void cleanupTestCase();
private:
Controller *c;
};
#endif // TST_CONTROLLERTEST
| [
"[email protected]"
] | |
800a6ca4143acdb95db536183a47035d934d9563 | a77a50f3f25853ec6a7b5b8548a13b7a4b4b3980 | /src/CameraSystem.cpp | 2ba5e74a3b0863750eb2b94fe34aef5a78f494a3 | [] | no_license | nidoro/PointlessWars | f051b41cb71df783141e5953d2c03d9cf305150a | 2e8a9c073026ebb07454922cc3caec41d8c68f29 | refs/heads/master | 2021-03-27T13:12:04.182891 | 2016-11-08T15:23:16 | 2016-11-08T15:23:16 | 71,281,107 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,476 | cpp | #include "CameraSystem.h"
CameraSystem::CameraSystem(){
addRequirement(Component::CAMERA_MAN);
addSubscription(SHAKE_CAMERA);
shakeTime = 0.5;
shaking = false;
shakeIntensity = 8;
}
CameraSystem::~CameraSystem(){
//dtor
}
void CameraSystem::start(EntitiesManager* eManager, sf::RenderWindow* window, double targetUPS){
this->eManager = eManager;
this->window = window;
this->targetUPS = targetUPS;
/*
wWindow = window->getView().getSize().x;
hWindow = window->getView().getSize().y;
cxWindow = wWindow/2;
cyWindow = hWindow/2;
*/
wWindow = 1280;
hWindow = 720;
cxWindow = wWindow/2;
cyWindow = hWindow/2;
for(list<Message>::iterator i = subscripts.begin(); i != subscripts.end(); i++){
subscribe(*i);
}
}
void CameraSystem::update(){
double wView = 1280;
double hView = 720;
if (shaking){
sf::View view = sf::View(sf::FloatRect(0, 0, wView, hView));
double w = wWindow-20;
double h = w*9.f/16.f;
view.setSize(w, h);
sf::Vector2f center = sf::Vector2f(wWindow/2, hWindow/2);
double d = shakeIntensity;
view.setCenter(randomDouble(center.x - d/2, center.x + d/2), randomDouble(center.y - d/2, center.y + d/2));
window->setView(view);
if (shakeClock.getElapsedTime().asSeconds() >= shakeTime){
shaking = false;
view.setCenter(center.x, center.y);
view.setSize(wWindow, hWindow);
window->setView(view);
}
}else if (!entities.empty()){
Entity* eCamMan = entities.front();
if (!eManager->isDead(eCamMan)){
if (eCamMan->has(Component::POSITION)){
sf::View v(sf::FloatRect(0, 0, wView, hView));
v.setCenter(eCamMan->get<CPosition>()->x, eCamMan->get<CPosition>()->y);
window->setView(v);
}
}
}else{
sf::View view = sf::View(sf::FloatRect(0, 0, wView, hView));
view.setCenter(cxWindow, cyWindow);
window->setView(view);
}
}
void CameraSystem::onShakeCamera(Entity* e){
if (shaking){
shakeIntensity = max(e->get<CCameraShake>()->intensity, shakeIntensity);
shakeTime = max(e->get<CCameraShake>()->duration, shakeTime);
}else{
shaking = true;
shakeIntensity = e->get<CCameraShake>()->intensity;
shakeTime = e->get<CCameraShake>()->duration;
}
shakeClock.restart();
}
| [
"[email protected]"
] | |
aa3117a621bc96c0222d8b9d2f93dbc114dbd4e2 | 4ffca8ba04cf99773e14ba3ce82d8bd80bbb3d27 | /src/graphlab/graph/ingress/distributed_hdrf_ingress.hpp | cad70002152fc4b54e271198e79d697509896d60 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | lqhl/PowerWalk | 3f491dd42d16988b97f7b08dc0fef49b7496ce0f | 36aeeaeaa4eb44c76ab9633ace27972260cc098f | refs/heads/master | 2020-12-28T08:30:01.070302 | 2017-01-03T05:28:24 | 2017-01-03T05:28:30 | 38,031,557 | 16 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 4,340 | hpp | /**
* Copyright (c) 2009 Carnegie Mellon University.
* 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.
*
* For more about this software visit:
*
* http://www.graphlab.ml.cmu.edu
*
*/
#ifndef GRAPHLAB_DISTRIBUTED_HDRF_INGRESS_HPP
#define GRAPHLAB_DISTRIBUTED_HDRF_INGRESS_HPP
#include <graphlab/graph/graph_basic_types.hpp>
#include <graphlab/graph/ingress/distributed_ingress_base.hpp>
#include <graphlab/graph/ingress/ingress_edge_decision.hpp>
#include <graphlab/graph/distributed_graph.hpp>
#include <graphlab/rpc/buffered_exchange.hpp>
#include <graphlab/rpc/distributed_event_log.hpp>
#include <graphlab/util/dense_bitset.hpp>
#include <graphlab/util/cuckoo_map_pow2.hpp>
#include <graphlab/macros_def.hpp>
namespace graphlab {
template<typename VertexData, typename EdgeData>
class distributed_graph;
template<typename VertexData, typename EdgeData>
class distributed_hdrf_ingress:
public distributed_ingress_base<VertexData, EdgeData> {
public:
typedef distributed_graph<VertexData, EdgeData> graph_type;
/// The type of the vertex data stored in the graph
typedef VertexData vertex_data_type;
/// The type of the edge data stored in the graph
typedef EdgeData edge_data_type;
typedef typename graph_type::vertex_record vertex_record;
typedef typename graph_type::mirror_type mirror_type;
typedef distributed_ingress_base<VertexData, EdgeData> base_type;
typedef fixed_dense_bitset<RPC_MAX_N_PROCS> bin_counts_type;
/** Type of the replica degree hash table:
* a map from vertex id to a bitset of length num_procs.
*/
typedef cuckoo_map_pow2<vertex_id_type, bin_counts_type,3,uint32_t> degree_hash_table_type;
degree_hash_table_type dht;
/** Type of the vertex degree hash table:
* a map from vertex id to a bitset of length num_procs.
*/
typedef cuckoo_map_pow2<vertex_id_type, size_t,3,uint32_t> true_degree_hash_table_type;
true_degree_hash_table_type degree_dht;
/** Array of number of edges on each proc. */
std::vector<size_t> proc_num_edges;
/** Ingress tratis. */
bool usehash;
bool userecent;
public:
distributed_hdrf_ingress(distributed_control& dc, graph_type& graph, bool usehash = false, bool userecent = false) :
base_type(dc, graph),
dht(-1),degree_dht(-1),proc_num_edges(dc.numprocs()), usehash(usehash), userecent(userecent) {
//INITIALIZE_TRACER(ob_ingress_compute_assignments, "Time spent in compute assignment");
}
~distributed_hdrf_ingress() { }
/** Add an edge to the ingress object using hdrf greedy assignment. */
void add_edge(vertex_id_type source, vertex_id_type target,
const EdgeData& edata) {
dht[source]; dht[target];
degree_dht[source]; degree_dht[target];
const procid_t owning_proc =
base_type::edge_decision.edge_to_proc_hdrf(source, target, dht[source], dht[target], degree_dht[source], degree_dht[target], proc_num_edges, usehash, userecent);
typedef typename base_type::edge_buffer_record edge_buffer_record;
edge_buffer_record record(source, target, edata);
base_type::edge_exchange.send(owning_proc, record);
} // end of add edge
virtual void finalize() {
dht.clear();
degree_dht.clear();
distributed_ingress_base<VertexData, EdgeData>::finalize();
size_t count = 0;
for(std::vector<size_t>::iterator it = proc_num_edges.begin(); it != proc_num_edges.end(); ++it) {
count = count + *it;
}
logstream(LOG_EMPH) << "TOTAL PROCESSED ELEMENTS: " << count << std::endl;
}
}; // end of distributed_ob_ingress
}; // end of namespace graphlab
#include <graphlab/macros_undef.hpp>
#endif
| [
"[email protected]"
] | |
f43ed55db6545762dd3b04de896c32e2f9150a6a | f85958e3fd8c49545e02d111816525c10617e25a | /test/dyno/example/any_range.cpp | 4c5c7f2e4b4cb34f2389f39f46203dee9172a15b | [
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"BSL-1.0"
] | permissive | mikosz/caramel-poly | c20d00c2e9706f0d0d07263b1b00a9fe2d16997e | 03201b98db5ac4ba9aeb85e6cd2d9fc5228b10bd | refs/heads/master | 2022-09-29T10:21:33.395529 | 2018-11-25T21:09:30 | 2018-11-25T21:09:30 | 130,270,326 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,304 | cpp | // Copyright Louis Dionne 2017
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
#include <gtest/gtest.h>
#include "any_iterator.hpp"
#include "caramel-poly/Poly.hpp"
#include <algorithm>
#include <iterator>
#include <list>
#include <utility>
#include <vector>
//
// Example of creating an erased range type for holding anything that has
// begin() and end() functions.
//
namespace /* anonymous */ {
constexpr auto begin_LABEL = POLY_FUNCTION_LABEL("begin");
constexpr auto end_LABEL = POLY_FUNCTION_LABEL("end");
constexpr auto cbegin_LABEL = POLY_FUNCTION_LABEL("cbegin");
constexpr auto cend_LABEL = POLY_FUNCTION_LABEL("cend");
template <typename Value, typename Category>
struct Range : decltype(caramel::poly::requires(
begin_LABEL = caramel::poly::function<any_iterator<Value, Category>(caramel::poly::SelfPlaceholder&)>,
end_LABEL = caramel::poly::function<any_iterator<Value, Category>(caramel::poly::SelfPlaceholder&)>,
cbegin_LABEL = caramel::poly::function<any_iterator<Value const, Category>(caramel::poly::SelfPlaceholder const&)>,
cend_LABEL = caramel::poly::function<any_iterator<Value const, Category>(caramel::poly::SelfPlaceholder const&)>
)) { };
} // anonymous namespace
template <typename Value, typename Category, typename R>
auto const caramel::poly::defaultConceptMap<Range<Value, Category>, R> = caramel::poly::makeConceptMap(
begin_LABEL = [](R& range) -> any_iterator<Value, Category> {
return any_iterator<Value, Category>{range.begin()};
},
end_LABEL = [](R& range) -> any_iterator<Value, Category> {
return any_iterator<Value, Category>{range.end()};
},
cbegin_LABEL = [](R const& range) -> any_iterator<Value const, Category> {
return any_iterator<Value const, Category>{range.cbegin()};
},
cend_LABEL = [](R const& range) -> any_iterator<Value const, Category> {
return any_iterator<Value const, Category>{range.cend()};
}
);
namespace /* anonymous */ {
template <typename Value, typename Category>
struct any_range {
template <typename Range>
any_range(Range&& r) : poly_{std::forward<Range>(r)} { }
auto begin() { return poly_.virtual_(begin_LABEL)(poly_); }
auto end() { return poly_.virtual_(end_LABEL)(poly_); }
auto begin() const { return cbegin(); }
auto end() const { return cend(); }
auto cbegin() const { return poly_.virtual_(cbegin_LABEL)(poly_); }
auto cend() const { return poly_.virtual_(cend_LABEL)(poly_); }
private:
caramel::poly::Poly<Range<Value, Category>> poly_;
};
//
// Tests
//
TEST(DynoTest, AnyRangeExample) {
using Range = any_range<int, std::forward_iterator_tag>;
{
Range vector = std::vector<int>{1, 2, 3, 4, 5};
Range list = std::list<int>{1, 2, 3, 4, 5};
EXPECT_TRUE(std::equal(vector.begin(), vector.end(), list.begin(), list.end()));
}
{
Range const cvector = std::vector<int>{1, 2, 3, 4, 5};
Range const clist = std::list<int>{1, 2, 3, 4, 5};
EXPECT_TRUE(std::equal(cvector.begin(), cvector.end(), clist.begin(), clist.end()));
}
{
Range vector = std::vector<int>{1, 2, 3, 4, 5};
Range list = std::list<int>{1, 2, 3, 4, 5};
EXPECT_TRUE(std::equal(vector.cbegin(), vector.cend(), list.cbegin(), list.cend()));
}
}
} // anonymous namespace
| [
"[email protected]"
] | |
7623648525c77113af87e7fade1aac6536b081f0 | 6b9a8ae4dc911960761e942ccd1fe1fe7d16392e | /src/lab5/tcpsocket.cc | 2f4604f7506d2860628bc35df7a1d701650e6ecd | [] | no_license | jakkra/Etrax-InternetInuti | e4a2dc8008b1689275809c3f1076746a6c8db113 | 1c6ef2af6154077720be840152e43c2309eecb3b | refs/heads/master | 2021-01-10T10:29:25.050551 | 2016-03-11T09:57:48 | 2016-03-11T09:57:48 | 51,094,641 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,790 | cc | /*!***************************************************************************
*!
*! FILE NAME : tcpsocket.cc
*!
*! DESCRIPTION: TCP Socket
*!
*!***************************************************************************/
/****************** INCLUDE FILES SECTION ***********************************/
#include "compiler.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
extern "C"
{
#include "system.h"
#include "timr.h"
}
#include "iostream.hh"
#include "tcp.hh"
#include "ip.hh"
#include "tcpsocket.hh"
#include "threads.hh"
//#define D_TCP
#ifdef D_TCP
#define trace cout
#else
#define trace if(false) cout
#endif
/****************** TCPSocket DEFINITION SECTION *************************/
//----------------------------------------------------------------------------
//
TCPSocket::TCPSocket(TCPConnection* theConnection):
myConnection(theConnection),
myReadSemaphore(Semaphore::createQueueSemaphore("Read", 0)),
myWriteSemaphore(Semaphore::createQueueSemaphore("Write", 0))
{
}
byte*
TCPSocket::Read(udword& theLength)
{
myReadSemaphore->wait(); // Wait for available data
theLength = myReadLength;
byte* aData = myReadData;
myReadLength = 0;
myReadData = 0;
return aData;
}
void
TCPSocket::socketDataReceived(byte* theData, udword theLength)
{
myReadData = new byte[theLength];
memcpy(myReadData, theData, theLength);
myReadLength = theLength;
myReadSemaphore->signal(); // Data is available
}
void
TCPSocket::Write(byte* theData, udword theLength)
{
myConnection->Send(theData, theLength);
myWriteSemaphore->wait(); // Wait until the data is acknowledged
}
void
TCPSocket::socketDataSent()
{
trace << "TCPSocket: all data has been ack'ed" << endl;
myWriteSemaphore->signal(); // The data has been acknowledged
}
void
TCPSocket::socketEof()
{
eofFound = true;
myReadSemaphore->signal();
}
bool
TCPSocket::isEof() {
return eofFound;
// True if a FIN has been received from the remote host.
}
void
TCPSocket::Close(){
myConnection->AppClose();
}
SimpleApplication::SimpleApplication(TCPSocket* theSocket):
mySocket(theSocket){
}
void
SimpleApplication::doit()
{
trace << "SimpleApplication::doit" << endl;
udword aLength;
byte* aData;
bool done = false;
while (!done && !mySocket->isEof()){
aData = mySocket->Read(aLength);
if (aLength > 0)
{
mySocket->Write(aData, aLength);
if ((char)*aData == 'q')
{
trace << "-------SimpleApplication::doit found q in stream-------" << endl;
done = true;
} else if((char)*aData == 's'){
trace << "-------SimpleApplication::doit found s in stream-------" << endl;
byte* space = (byte*) malloc(1000*1000);
for (int i = 0; i < 1000*1000; i++)
{
space[i] = 'A' + i % (0x5B-0x41);
}
mySocket->Write(space, 1000*1000);
delete space;
} else if((char)*aData == 'r') {
trace << "-------SimpleApplication::doit found r in stream-------" << endl;
byte* space = (byte*) malloc(10000);
for (int i = 0; i < 10000; i++)
{
space[i] = 'Z' - i % (0x5B-0x41);
}
mySocket->Write(space, 10000);
delete space;
} else if((char)*aData == 't') {
trace << "-------SimpleApplication::doit found t in stream-------" << endl;
byte* space = (byte*) malloc(360);
for (int i = 0; i < 360; i++)
{
space[i] = '0' + i % 10;
}
mySocket->Write(space, 360);
delete space;
}
delete aData;
}
}
mySocket->Close();
}
| [
"[email protected]"
] | |
f2e46ae3e76b02a539b4be9f27e848e96e281a2b | 92d71ab05aa84bd3e6e08d1e0d7bd62312bd20cc | /DeckLoader/test/mock/DeckMock.h | 9f1e5a926c26bfb31ea4dd588029a3597b979cb3 | [] | no_license | szcz761/Black_Jack_TDD | 769452aa035e2282b44a62204cfd632f82c6728a | 9d23541cce123ac4c4658874acbfba5f3224a612 | refs/heads/master | 2021-05-09T08:18:02.371297 | 2018-01-29T13:31:38 | 2018-01-29T13:31:38 | 119,386,147 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 515 | h |
//
// Created by szymon on 19.11.17.
//
#ifndef GAMEAPP_DECKLOADERMOCK_H
#define GAMEAPP_DECKLOADERMOCK_H
#include <gmock/gmock.h>
#include "../../IDeckLoader.h"
namespace loader{
namespace test {
namespace mock
{
class DeckLoaderMock : public IDeckLoader
{
public:
~DeckLoaderMock() override = default;
MOCK_METHOD0(load,std::vector<GameCore::Card>());
};
}
}
}
#endif //GAMEAPP_DECKLOADERMOCK_H
| [
"[email protected]"
] | |
10ba7587fbc117378f66209b722f9dad594b0898 | 5e1dee44b9f5708793b1da7c84b66bf363312daf | /src/test-case/status.cpp | eb0b3599432b3d492d6ff1732276ecf998f890b3 | [
"MIT"
] | permissive | dbc60/cxxhttp | 0c4841f0797433ba7812a37f2acfabd89049c016 | d874b17e6c2bbf7d66983d43944c53b105aec51b | refs/heads/master | 2021-04-15T18:51:44.918670 | 2017-06-25T17:13:40 | 2017-06-25T17:13:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,147 | cpp | /* Test cases for the status line handlers.
*
* HTTP prefaces server headers with a status line. There's a few functions to
* look up and otherwise deal with those in the code, and this file tests them.
*
* See also:
* * Project Documentation: https://ef.gy/documentation/cxxhttp
* * Project Source Code: https://github.com/ef-gy/cxxhttp
* * Licence Terms: https://github.com/ef-gy/cxxhttp/blob/master/COPYING
*
* @copyright
* This file is part of the cxxhttp project, which is released as open source
* under the terms of an MIT/X11-style licence, described in the COPYING file.
*/
#include <ef.gy/test-case.h>
#include <cxxhttp/http-status.h>
using namespace cxxhttp;
/* Test status description lookup.
* @log Test output stream.
*
* Performs a few lookups, including deliberately invalid status codes, to make
* sure that works as expected.
*
* @return 'true' on success, 'false' otherwise.
*/
bool testDescription(std::ostream &log) {
struct sampleData {
unsigned in;
std::string out;
};
std::vector<sampleData> tests{
{0, "Other Status"}, {100, "Continue"}, {404, "Not Found"},
};
for (const auto &tt : tests) {
const auto v = http::statusLine::getDescription(tt.in);
if (v != tt.out) {
log << "http::statusLine::getDescription(" << tt.in << ")='" << v
<< "', expected '" << tt.out << "'\n";
return false;
}
}
return true;
}
/* Test status parsing.
* @log Test output stream.
*
* Parses some status lines to see if that works as expected.
*
* @return 'true' on success, 'false' otherwise.
*/
bool testParse(std::ostream &log) {
struct sampleData {
std::string in;
bool valid;
unsigned code;
std::string protocol, description;
};
std::vector<sampleData> tests{
{"", false, 0, "", ""},
{"frob", false, 0, "", ""},
{"HTTP/1.1 glorb", false, 0, "", ""},
{"HTTP/1.1 555 glorb\r", true, 555, "HTTP/1.1", "glorb"},
{"HTTP/1.1 999 glorb\r", false, 999, "HTTP/1.1", "glorb"},
{"HTTP/1.0 200 OK", true, 200, "HTTP/1.0", "OK"},
};
for (const auto &tt : tests) {
const http::statusLine v(tt.in);
if (v.valid() != tt.valid) {
log << "http::statusLine(" << tt.in << ") has incorrect result\n";
return false;
}
if (v.valid()) {
if (v.code != tt.code) {
log << "http::statusLine(" << tt.in << ").code='" << v.code
<< "', expected'" << tt.code << "'\n";
return false;
}
if (v.protocol() != tt.protocol) {
log << "http::statusLine(" << tt.in << ").protocol='" << v.protocol()
<< "', expected'" << tt.protocol << "'\n";
return false;
}
if (v.description != tt.description) {
log << "http::statusLine(" << tt.in << ").description='"
<< v.description << "', expected'" << tt.description << "'\n";
return false;
}
}
}
return true;
}
/* Test header generation.
* @log Test output stream.
*
* Generates a few status lines, including incorrect ones, to make sure no
* un-parseable lines are generated by us.
*
* @return 'true' on success, 'false' otherwise.
*/
bool testGenerate(std::ostream &log) {
struct sampleData {
std::string in;
bool valid;
unsigned code;
std::string protocol, description, out;
};
std::vector<sampleData> tests{
{"", false, 0, "HTTP/0.0", "", "HTTP/1.1 500 Bad Status Line\r\n"},
{"frob", false, 0, "HTTP/0.0", "", "HTTP/1.1 500 Bad Status Line\r\n"},
{"HTTP/1.1 glorb", false, 0, "HTTP/0.0", "",
"HTTP/1.1 500 Bad Status Line\r\n"},
{"HTTP/1.1 555 glorb\r", true, 555, "HTTP/1.1", "glorb",
"HTTP/1.1 555 glorb\r\n"},
{"HTTP/1.1 999 glorb\r", false, 999, "HTTP/1.1", "glorb",
"HTTP/1.1 500 Bad Status Line\r\n"},
{"HTTP/1.0 200 OK", true, 200, "HTTP/1.0", "OK", "HTTP/1.0 200 OK\r\n"},
{"HTTP/1.0 666 OK", false, 666, "HTTP/1.0", "OK",
"HTTP/1.1 500 Bad Status Line\r\n"},
};
for (const auto &tt : tests) {
const http::statusLine v(tt.in);
if (v.valid() != tt.valid) {
log << "http::statusLine(" << tt.in << ") has incorrect result\n";
return false;
}
if (v.code != tt.code) {
log << "http::statusLine(" << tt.in << ").code='" << v.code
<< "', expected'" << tt.code << "'\n";
return false;
}
if (v.protocol() != tt.protocol) {
log << "http::statusLine(" << tt.in << ").protocol='" << v.protocol()
<< "', expected'" << tt.protocol << "'\n";
return false;
}
if (v.description != tt.description) {
log << "http::statusLine(" << tt.in << ").description='" << v.description
<< "', expected'" << tt.description << "'\n";
return false;
}
if (std::string(v) != tt.out) {
log << "http::statusLine(" << tt.in << ").out='" << std::string(v)
<< "', expected'" << tt.out << "'\n";
return false;
}
}
return true;
}
namespace test {
using efgy::test::function;
static function description(testDescription);
static function parse(testParse);
static function generate(testGenerate);
}
| [
"[email protected]"
] | |
3414c7aee6a542c103fc90408d33ad89a321e951 | 562aaeeb36128a12f31245b49b52584409ac9e79 | /10.0.15063.0/winrt/internal/Windows.Phone.ApplicationModel.1.h | 063a6e9300f4dc06cc64cc92752eb61842d8f66a | [
"LicenseRef-scancode-generic-cla",
"MIT"
] | permissive | PlainRubbish/cppwinrt | af6b2fde4bb56a8c310f338b440e8db7943e2f2e | 532b09e3796bd883394f510ce7b4c35a2fc75743 | refs/heads/master | 2021-01-19T05:06:17.990730 | 2017-03-31T20:03:28 | 2017-03-31T20:03:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,343 | h | // C++ for the Windows Runtime v1.0.170331.7
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
#pragma once
#include "../base.h"
#include "Windows.Phone.ApplicationModel.0.h"
WINRT_EXPORT namespace winrt {
namespace ABI::Windows::Phone::ApplicationModel {
struct __declspec(uuid("d5008ab4-7e7a-11e1-a7f2-b0a14824019b")) __declspec(novtable) IApplicationProfileStatics : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall get_Modes(winrt::Windows::Phone::ApplicationModel::ApplicationProfileModes * value) = 0;
};
}
namespace ABI {
}
namespace Windows::Phone::ApplicationModel {
template <typename D>
struct WINRT_EBO impl_IApplicationProfileStatics
{
Windows::Phone::ApplicationModel::ApplicationProfileModes Modes() const;
};
}
namespace impl {
template <> struct traits<Windows::Phone::ApplicationModel::IApplicationProfileStatics>
{
using abi = ABI::Windows::Phone::ApplicationModel::IApplicationProfileStatics;
template <typename D> using consume = Windows::Phone::ApplicationModel::impl_IApplicationProfileStatics<D>;
};
template <> struct traits<Windows::Phone::ApplicationModel::ApplicationProfile>
{
static constexpr const wchar_t * name() noexcept { return L"Windows.Phone.ApplicationModel.ApplicationProfile"; }
};
}
}
| [
"[email protected]"
] | |
f04e5c5745d52fa04794f3b6e8197a807e2426ed | 1791461e6740f81c2dd6704ae6a899a6707ee6b1 | /Contest/The 2020 ICPC Asia Nanjing Regional Contest/H.cpp | d8e50c6d999858b9cb8f390f4a1b89da58451a68 | [
"MIT"
] | permissive | HeRaNO/OI-ICPC-Codes | b12569caa94828c4bedda99d88303eb6344f5d6e | 4f542bb921914abd4e2ee7e17d8d93c1c91495e4 | refs/heads/master | 2023-08-06T10:46:32.714133 | 2023-07-26T08:10:44 | 2023-07-26T08:10:44 | 163,658,110 | 22 | 6 | null | null | null | null | UTF-8 | C++ | false | false | 709 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int a[30][30]=
{
{66, 390, 1800, 6120, 13680, 15120},
{390, 3198, 13176, 27000, 13680, 15120},
{1800, 13176 ,24336, 4320},
{6120, 27000, 4320, 4320},
{13680, 13680},
{15120 ,15120},
};
const int MOD=1e9+7;
ll ksm(ll x,int v)
{
ll ans=1;
while(v)
{
if(v&1)(ans=ans*x%MOD);
x=x*x%MOD;
v>>=1;
}
return ans;
}
void solve()
{
int n,m;
scanf("%d%d",&n,&m);
ll ans=ksm(3,n*m);
if(n==1||m==1)
{
printf("%lld\n",0);
return;
}
ll res=0;
if(n<=10&&m<=10)
{
res=a[n-2][m-2];
printf("%lld\n",(ans-res+MOD)%MOD);
}
else printf("%lld\n",ans);
}
int main()
{
int t;
scanf("%d",&t);
while(t--)solve();
return 0;
}
| [
"[email protected]"
] | |
288e3d467de223914dc2b9e0a088f71354bf4a98 | 6f322bef28e4a663ce8d2b5baba11e6d3c564dc4 | /Sandbox/Source/Utils/Log/ConsoleLog.cpp | 0a967084081cd75bc2a16f924cfaa05d8f9d9b6d | [
"MIT"
] | permissive | Clymiaru/GDPARCM_Sandbox | f6f9682c8b99f0b589e7b660b7de6012ae78dd8d | 21d6d7ccaef1b03a4d631e757cb824341e84e5d6 | refs/heads/main | 2023-03-22T18:27:03.040792 | 2021-03-18T08:13:43 | 2021-03-18T08:13:43 | 343,672,782 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 399 | cpp | #include "pch.h"
#include "ConsoleLog.h"
#include <spdlog/sinks/basic_file_sink.h>
#include <spdlog/sinks/stdout_color_sinks.h>
#include "Utils/TypeAlias.h"
SharedPtr<spdlog::logger> Utils::ConsoleLog::logger;
void Utils::ConsoleLog::Init()
{
#if DEBUG
logger = spdlog::stdout_color_mt("CONSOLE_LOG");
logger->set_level(spdlog::level::trace);
logger->set_pattern("%^[%T] %n: %v%$");
#endif
}
| [
"[email protected]"
] | |
cf3bbce5599ab2cc98da368eaf23bc1d86599c98 | 134c6436b782489b4bcf39cb41f5a1a233541965 | /Win32Project1_d2d(201411010) (3)/Win32Project1_d2d/stdafx.h | 2eb72e40d9080271082f508fb416a562f0d7e5ac | [] | no_license | ThrowingDobie/ys2D | e27d4a9939b331f96bfc30610dbc17151942397f | a71a244104b1aa8e6f999fa60ee5507ac94766a1 | refs/heads/master | 2020-05-19T07:42:58.437646 | 2014-11-12T07:16:45 | 2014-11-12T07:16:45 | 26,473,260 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 1,719 | h | // stdafx.h : 자주 사용하지만 자주 변경되지는 않는
// 표준 시스템 포함 파일 및 프로젝트 관련 포함 파일이
// 들어 있는 포함 파일입니다.
//
#pragma once
#pragma comment( lib, "d2d1.lib" )
#pragma comment( lib, "WindowsCodecs.lib" )
#include "targetver.h"
#define WIN32_LEAN_AND_MEAN // 거의 사용되지 않는 내용은 Windows 헤더에서 제외합니다.
// Windows 헤더 파일:
#include <windows.h>
// C 런타임 헤더 파일입니다.
#include <stdlib.h>
#include <malloc.h>
#include <memory.h>
#include <tchar.h>
// TODO: 프로그램에 필요한 추가 헤더는 여기에서 참조합니다.
extern HWND g_hWnd;
extern class cGameManager;
extern float Miracle;
// 인게임
extern int Stage;
extern POINT MouseMove;
extern POINT MouseLD;
extern POINT MouseRD;
extern POINT MouseState;
extern int MainTile[256][256];
extern POINT g_Camera;
extern POINT Screen;
extern POINT PlayerPos;
extern POINT TileSize; // 타일크기
extern POINT StageA_Size; // 맵사이즈
extern POINT Resolution; // 해상도
extern int PlayerSpeed;
extern float PlayerHp;
extern float PlayerAttack;
extern float PlayerDefense;
extern RECT MonsterTile;
extern int TileTypeL;
extern int TileTypeR;
extern int TileTypeU;
extern int TileTypeD;
extern BOOL bRight;
extern BOOL bLeft;
extern BOOL bUp;
extern BOOL bDown;
extern BOOL bSp;
extern BOOL bEnt;
extern float g_Delta;
extern BOOL KeepPotion;
extern BOOL SetPotion;
// D2D1
#include <cassert>
#include <commdlg.h>
#include <wincodec.h>
#include <d2d1.h>
#include <d2d1helper.h>
template <typename T>
inline void SafeRelease(T *&p)
{
if (NULL != p)
{
p->Release();
p = NULL;
}
}
| [
"[email protected]"
] | |
244da7a8a7d9d8b13ddf9ec2c3bd942958eb3740 | 32709d5de776d864df9581b1a9c2d9d966c3c31f | /Shooting_Game_Classic/2019 5 17 총알/CAssetManager.h | ed9380c926e8e6e8d841ab109b09bb292519185c | [] | no_license | dadm8473/DirectX_Class | 76010b18e490306cd44c21554cc8ab31f53df1ce | 34dd319d39d93c1f73a7c7dd6c2047aa20694e69 | refs/heads/master | 2022-03-16T05:30:41.434207 | 2019-11-10T12:45:37 | 2019-11-10T12:45:37 | 186,415,853 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 183 | h | #pragma once
class CAssetManager
{
public:
CTexture* playerTexture;
CTexture* playerBulletTexture;
void InitAssets();
void TermAssets();
};
extern CAssetManager* gAssetManager;
| [
"[email protected]"
] | |
536920d1ac67ae5fbd8e77671e5ce7ea7b97a8d3 | 5b53ad8f492224e26630f3083ab477707cd118c7 | /ficha4/exe6.cpp | c03d99901309f9bc9e3dc62e43e16b7c33e43467 | [] | no_license | MrDuDe98/progamaca_objetos | a33559e185ec542ea2b8987019fc87126ae89a12 | 0862725cbd3b318791831ffc868281d8dacefacd | refs/heads/master | 2020-03-14T11:55:43.967262 | 2018-04-30T13:31:22 | 2018-04-30T13:31:22 | 131,599,786 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 367 | cpp | #include<iostream>
using namespace std;
int main(){
int op = 1;
while((op > 0) && (op < 3)){
cout<<"\n MENU DE COMANDOS"<<"\n\n";
cout<<" 0. Sair \n";
cout<<" 1. Mostrar\n";
cout<<" 2. Apresentar\n\n";
cout<<" Escolha uma opcao: ";
cin>>op;
}
}
| [
"[email protected]"
] | |
81bc65d039821107bad7e9dc610cacf8688a32b1 | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_5751500831719424_0/C++/rowanhao/main.cpp | a3c780c49edaf44b0f6d5957666c834b06e768dd | [] | 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 | 2,435 | cpp | #include <iostream>
#include <cstdio>
#include<vector>
#include <cstring>
#include<algorithm>
#include<queue>
using namespace std;
#define maxn 111
#define INF 99999999
vector<int>vecb;
vector<int>veca;
vector<int>vec[110];
char str[110][110];
int dp[110][110];
int main()
{
freopen("data.in","r",stdin);
freopen("data.out","w",stdout);
int T,t,i,j,n,k;
scanf("%d",&T);
for(t=1; t<=T; t++)
{
veca.clear();
vecb.clear();
for(i=0; i<=100; i++)vec[i].clear();
scanf("%d",&n);
for(i=1; i<=n; i++)scanf("%s",str[i]);
int len=strlen(str[1]);
int l=1;
veca.push_back(str[1][0]);
int as=0;
for(i=1; i<len; i++)
{
if(str[1][i]!=str[1][i-1])
{
veca.push_back(l);
vec[as].push_back(l);
as++;
veca.push_back(str[1][i]);
l=1;
}
else l++;
}
veca.push_back(l);
vec[as].push_back(l);
printf("Case #%d: ",t);
for(i=2; i<=n; i++)
{
vecb.clear();
vecb.push_back(str[i][0]);
int len=strlen(str[i]);
l=1;
for(j=1; j<len; j++)
{
if(str[i][j]!=str[i][j-1])
{
vecb.push_back(l);
vecb.push_back(str[i][j]);
l=1;
}
else l++;
}
vecb.push_back(l);
int lena=veca.size();
int lenb=vecb.size();
if(lena!=lenb)break;
for(j=0;j<lena;j+=2)
{
if(veca[j]!=vecb[j])break;
vec[j/2].push_back(vecb[j+1]);
}
if(j<lena)break;
}
if(i<=n)
{
cout<<"Fegla Won"<<endl;
continue;
}
int minn=0;
for(i=0;i<=as;i++)
{
int ps=0,ks=9999999;
for(j=0;j<vec[i].size();j++)
{
ps=0;
for(k=0;k<vec[i].size();k++)
{
ps+=abs(vec[i][k]-vec[i][j]);
}
ks=min(ks,ps);
}
minn+=ks;
}
cout<<minn<<endl;
}
return 0;
}
| [
"[email protected]"
] | |
4cd241fa46213577b6589b8ec2778eded3dbb5f3 | 0e95319900ba58a76a764526839d010000f38464 | /Surfacer/Game/GameLevel.h | 0257311814f1890dfb8a6631e20b2f3684d577f0 | [] | no_license | aismann/Surfacer | 9f134ce7e51fa1dfef4bcdee038ea4e34509a37d | 09803894a4886d3e8242bd9a91a96654306ca89b | refs/heads/master | 2023-04-08T02:35:12.192804 | 2016-08-17T23:16:39 | 2016-08-17T23:16:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,573 | h | #pragma once
//
// SurfaceGameLevel.h
// Surfacer
//
// Created by Shamyl Zakariya on 7/7/11.
// Copyright 2011 Shamyl Zakariya. All rights reserved.
//
#include "Level.h"
#include "ParticleSystem.h"
#include "Filters.h"
#include "Terrain.h"
namespace game {
class ActionDispatcher;
class Background;
class Fluid;
class HealthComponent;
class PlayerHud;
class Player;
class ViewportController;
/**
subclass of core::Level with various gameplay behaviors and effects
*/
class GameLevel : public core::Level {
public:
struct init : public core::Level::init
{
real defaultZoom;
init():
defaultZoom(10)
{}
//JsonInitializable
virtual void initialize( const ci::JsonTree &v )
{
core::Level::init::initialize(v);
JSON_READ(v,defaultZoom);
}
};
public:
GameLevel();
virtual ~GameLevel();
JSON_INITIALIZABLE_INITIALIZE();
// Level
virtual void initialize( const init &initializer );
const init &initializer() const { return _initializer; }
virtual void addedToScenario( core::Scenario * );
virtual void removedFromScenario( core::Scenario * );
virtual cpBB bounds() const;
virtual void ready();
virtual void update( const core::time_state & );
virtual void addObject( core::GameObject *object );
// NotificationListener
virtual void notificationReceived( const core::Notification ¬e );
// GameLevel
ViewportController *cameraController() const { return _cameraController; }
UniversalParticleSystemController *cutTerrainEffect() const { return _cutEffect; }
UniversalParticleSystemController *dustEffect() const { return _dustEffect; }
UniversalParticleSystemController *fireEffect() const { return _fireEffect; }
UniversalParticleSystemController *smokeEffect() const { return _smokeEffect; }
UniversalParticleSystemController *monsterInjuryEffect() const { return _monsterInjuryEffect; }
terrain::Terrain* terrain() const { return _terrain; }
Player *player() const { return _player; }
ActionDispatcher *actionDispatcher() const { return _actionDispatcher; }
/**
Get the Level's acid engine.
Monsters emit acid sometimes for injury, and sometimes as an attack. Instead of each
monster having its own acid instance, the Level provides a single one which is shared.
*/
Fluid *acid() const { return _acid; }
virtual void setAcid( Fluid *acid );
void emitAcid( const Vec2r &position, const Vec2r &vel = Vec2r(0,0));
void emitAcidInCircularVolume( const Vec2r &position, real radius, const Vec2r &vel = Vec2r(0,0));
/**
Get the PlayerHud ui::Layer, used to display player stats, etc
*/
PlayerHud *playerHudLayer() const { return _playerHudLayer; }
/**
Get the notification layer.
This layer should be used to display gameplay message boxes, info, warnings, etc.
*/
core::ui::Layer *notificationLayer() const { return _notificationLayer; }
/*
Create a GameObject or Behavior from Json, and add it.
The ci::JsonTree should look something like:
{
"class" : "Battery",
"enabled" : true,
"initializer" : {
"amount" : 10,
"type" : "BATTERY",
"position" : {
"x" : 199,
"y" : 144
}
}
}
The ci::JsonTree's root level contains:
- the classname
- an optional boolean 'enabled' which if false will early exit
- an object initializer to configure the thing being created.
If successful, the object is added to the level and is returned. Otherwise,
if the object couldn't be created or initialized, this method does not add anything
to the level and returns NULL.
*/
core::Object *create( const ci::JsonTree &recipe );
protected:
virtual void _setTerrain( terrain::Terrain *t );
virtual void _setPlayer( Player * );
void _collision_Object_Terrain( const core::collision_info &info, bool &discard );
void _collision_Monster_Monster( const core::collision_info &info, bool &discard );
void _collision_Monster_Object( const core::collision_info &info, bool &discard );
void _terrainWasCut( const Vec2rVec &positions, TerrainCutType::cut_type cutType );
void _createEffectEmitters();
private:
init _initializer;
terrain::Terrain *_terrain;
Player *_player;
Fluid *_acid;
UniversalParticleSystemController *_cutEffect, *_dustEffect, *_fireEffect, *_smokeEffect, *_monsterInjuryEffect;
PlayerHud *_playerHudLayer;
core::ui::Layer *_notificationLayer;
ActionDispatcher *_actionDispatcher;
ViewportController *_cameraController;
};
} // end namespace game | [
"[email protected]"
] | |
b999e81fd0a47ea891afc736253abac062f90144 | cd7b1702730a5d888cf3f7ba8a1f4947d8186af9 | /D5_oop_constructor_static_this_const_friend/HelloWorld5.cpp | 06dc6ab2d1bb04acb56f0b3a3f157841c974b5d3 | [] | no_license | jiangbaoyu18/cppBase | 488b26b30bee0d815f79bd4f7f76f3ac8bfe8ecb | a8f8d8f00142190515143b5fc88884ed99abe9e0 | refs/heads/master | 2023-01-24T06:06:41.229033 | 2020-11-26T12:01:29 | 2020-11-26T12:01:29 | 312,254,806 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 12,190 | cpp | //
// Created by aaab on 11/5/20.
//
#include <iostream>
#include <string>
#include <string.h>
using namespace std;
/**
*
* //C语言封装属性和行为分开处理了, 类型检测不够完善
* // in c++ ,struct和class是一个意思,唯一的不同 默认权限 ,struct是public, 但是class默认权限是private
*
* 构造函数 ,析构函数
* 构造函数调用顺序 (父类构造函数-> 成员变量构造函数-> 本类构造函数-----本类析构函数-> 成员变量析构函数->父类析构函数)
* //按照参数进行分类 无参构造函数(默认构造函数) 有参构造函数
* //按照类型进行分类 普通构造函数拷贝构造函数
* 拷贝构造函数调用时机, 构造函数的调用规则
* 深拷贝和浅拷贝
* 初始化列表
* 类对象作为类成员时候,构造顺序:先将类对象构造(按照成员变量的声明顺序),然后构造自己, 析构的顺序是相反的
* explicit关键字修饰构造函数,防止隐式类型转换
*
* 在运行时动态分配堆区内存 (new):
* 它带有内置的长度计算、类型转换和安全检查
* call the corresponding constructor
* 需要相应的delete 来释放堆内存
*
* 静态成员变量 ,静态成员函数
*
* singleton
* 字节对齐
* this pointer : this指针指向调用成员函数的对象的地址 (this指针是指针常量,指针指向的地址不能改变,指向的地址的值可以改变)
* 空指针访问成员函数
* 常函数与常对象
* 友元函数: 全局函数做友元函数,成员函数做友元函数, 友元类
*
*
*/
class Person{
public:
Person(int a){// constructor 与类名相同,没有返回值.不写void,可以发生重载(可以有参数)
this->age=a;
cout<<"constructor"<<a<<endl;
}
Person(){
cout<<"constructor"<<endl;
}
Person(const Person &p){ // 拷贝构造函数
cout<<"copy constructor "<<endl;
this->age=p.age;
}
~Person(){////析构函数写法,与类名相同类名前面加一一个符号“~”,也没有返回值,不写void, 不可以有参数(不能发生重载)
cout<<"person destructor"<<endl;
}
int age;
};
void test1(){
// Person p; //默认构造函数不要加() Person p3(); //编译器认为这行是函数的声明
// Person p1(32);
// Person p2(p1);
// Person p=Person(32);
// Person p2=Person(p);
// Person(100);//匿名对象,如果编译器发现了对象是匿名的,那么在这行代码结束后就释放这个对象
// Person(p1); //不能用 copy构造函数初始化匿名对象
//隐式类型转换
// Person p7=123; //相当于调用了Person p7 = Person(123)
// Person p8=p7;//Person p8=Person(p7);
}
void doWork(Person p1){ // Person p1=Person(p)
}
//static Person p;
Person doWork2(){
// return Person(12);
// return p;
}
Person& doWork3(){
// return p;
}
// 拷贝构造函数调用时机
void test2(){
Person p;
Person p2(p);//1、用已经创建好的对象来初始化新的对象 same like Person p5=p;
doWork(p);//2.以值传递的方式给函数参数传值
Person p3=doWork2();//3,以值方式(create a new Person obj) (可能会有编译器优化,不会调用copy constructor)
Person& p4=doWork3();// non new Person obj created
}
//构造函数的调用规则
void test3(){
// Person p; // 1,当我们提供了有参构造函数,那么系统就不会提供默认构造函数
// Person p2(p); // 2, 但是系统还会提供默认拷贝构造函数,对类中非静态成员属性简单值拷贝 ;
// 3. 当我们提供了拷贝构造,系统就不会提供其他构造函数
}
class Person2{
public:
char* name;
int age;
Person2(char* name,int age){
this->name=(char *)malloc(strlen(name)+1);
strcpy(this->name,name);
}
Person2(int age):age(age){//初始化列表 this->age=age; 如果成员变量是引用类型,该类型需要提供带有相应类型参数的构造函数
}
/**
* 系统默认提供的拷贝构造会 进行简单的值拷贝。
* 如果属性里有指向堆区空间的数据( char* ),那么简单的浅拷贝会复制内存地址,在释放内存的时候导致重复释放内存的异常
*/
Person2(const Person2& p){ //deep copy
this->age=p.age;
this->name= (char *)malloc(strlen(p.name)+1);// 对于引用类型的字段,重新分配堆内存空间,然后再对新的堆内存空间赋值
strcpy(this->name,p.name);
}
~Person2(){
if(name!=NULL){
free(name);
name=NULL;
}
cout<<"destructor"<<endl;
}
};
void test4(){
Person2 p1("zs",12);
Person2 p2(p1);
}
//初始化列表
void test5(){
Person2 p1(1);
cout<<p1.age<<endl;
}
class Phone{
public:
string name;
Phone(){
cout<<"phone cons"<<endl;
}
Phone(string name):name(name){
cout<<"phone cons"<<endl;
}
~Phone(){
cout<<"phone des"<<endl;
}
};
class Student{
public :
Student(){
cout<<"student cons"<<endl;
}
Student(string name,string m_name):name(name),phone(m_name){ // phone(m_name) 调用Phone的带有string 参数的构造函数
cout<<"student cons"<<endl;
}
~Student(){
cout<<"student des"<<endl;
}
Phone phone;
string name;
void display(){
cout<<name<<" "<<phone.name<<endl;
}
};
// 类对象作为类成员时候,构造顺序:先将类对象构造(按照成员变量的声明顺序),然后构造自己, 析构的顺序是相反的
void test6(){
Student s("aaab","iphone");
s.display();
}
class Test{
public:
explicit Test(int a){ // explicit关键字,防止隐式类型转换
}
};
void test7(){
// Test t=0;
Test t2(34);
}
//new operator
void test8(){
// Person p1;//栈区开辟
// cout<<new Person<<endl; // return heap address
// Person* p2=new Person; // in heap
// p2->age=123;
// cout<<p2->age<<endl;
// delete p2; // call destructor
// Person* p3=new Person(123);
// cout<<p3->age<<endl;
// delete p3;
// void* p4=new Person;
// delete p4;//当用void*接受new出来的指针,会出现释放的问题,无法释放p
Person* persons=new Person[10]; // call Person default constructor 10 times
Person parr2[2]={Person(123),Person(456)};// //在栈.上开辟数组,可以指定有参构造 , 在方法调用完成后自动释放
delete[] persons;//如果在new表达式中使用[]必须在相应的delete表达式中也使用[]
cout<<"before end test8 call "<<endl;
}
//static
class Person3{
public :
static int class_id;// /静态成员变量,在类内声明,类外进行初始化
int print_private(){
cout<<private_id<<endl;
}
static int static_print_private(){ // //静态成员函数 不可以访问普通成员变量
cout<<private_id<<endl;
}
private:
static int private_id;
};
int Person3::class_id=0;// 类外进行初始化
int Person3::private_id=9;
void test9(){
Person3 p;
p.class_id=123;
Person3::class_id=1234;
Person3 p2;
cout<<p2.class_id<<endl;
p2.print_private();
Person3::static_print_private();
}
//singleton
class Chairman{
private:
Chairman(string name){
this->name=name;
}
Chairman(const Chairman& c);//拷贝构造私有化
static Chairman* instance;
string name;
public :
static Chairman* getInstance(){
return instance;
}
void print_name(){
cout<<name<<endl;
}
};
Chairman* Chairman::instance=new Chairman("xjp");
void test10(){
Chairman* c=Chairman::getInstance();
cout<<c->getInstance()<<endl;
cout<<c->getInstance()<<endl;
cout<<c->getInstance()<<endl;
c->getInstance()->print_name();
// Chairman* c2=new Chairman(*c);
// cout<<c2<<endl;
}
//成员变量和成员属性分开存储,only 非静态成员变量属于对象 ( sizeof(Class),sizeof(object) )
// //空类的大小为1,由于没有成员变量的class也能创建对象,对于创建的每个实例对象 都需要一个独一无二的地址,因此空类内部需要一个一字节的字段来表示每个对象的地址;
#pragma pack(1) // 防止字节对齐
class Person4{
public:
int m_age;
double price; //m_age 不够8Byte,因此凑够8Byte后再加上 double的8Byte
static int age2;
void test_fun(){
cout<<"test"<<endl;
}
void print_age(){
if(this==NULL){
return;
}
cout<<m_age<<endl;
}
Person4& addAge(int age){ //注意此时函数的返回类型为Person4类型对象的引用,如果没有&则为值拷贝(调用拷贝构造函数),会新建一个对象
cout<<"add"<<endl;
this->m_age+=age;
return *this; // 通过this指针实现链式调用
}
};
void test11(){
cout<< sizeof(Person4)<<endl;
Person4 p1;
cout<< sizeof(p1)<<endl;
}
//this
void test12(){
Person4 p1;
p1.m_age=10;
p1.addAge(10).addAge(20).addAge(30);
cout<<p1.m_age<<endl;
}
//空指针访问成员函数
void test13(){
Person4* p=NULL;
p->test_fun(); //如果成员函数没有用到this,那么空指针可以直接访问。 NullPointerException in java
p->print_age();//如果成员函数中用到this指针,就要注意,可以加if判断 this is NULL or not
Person4& p2= *(p);
p2.test_fun();
}
// 常函数 与 常对象
class Person5{
public:
int m_a;
mutable int m_b; //就算是常函数我还是执意要修改
Person5(){
this->m_a=0;
this->m_b=0;
}
//this指针是指针常量,指针指向的地址不能改变,指向的地址的值可以改变
//在常函数中,不允许修改this指针指向的地址中对象的值 : const Person5* const this_pointer;
void showInfo() const{
// this->m_a=123; //error
this->m_b=123;
}
void show(){
cout<<"show"<<endl;
}
};
void test14(){
Person5 p1;
p1.m_a=1234;
const Person5 p2;//常对象不允许修改属性,除了 mutable成员变量
// p2.m_a=567;//error
// p2.show();//常对象不可以调用普通成员函数
p2.showInfo();//常对象可以调用常函数
}
//友元函数 (注意两个类的声明和类中方法实现的顺序 (依赖关系))
class Building;
class GoodGay{
public :
GoodGay(Building* building){
this->building=building;
}
void visit();
void visit2();
private:
Building* building;
};
class Building{
friend void GoodGay::visit2();// 成员函数做友元函数
friend void goodGay(Building* building);// 全局函数做友元函数,使得友元函数中可以访问类中的私有成员变量和成员函数
// friend class GoodGay; // 友元类(GoodGay中所有的方法都可以访问Building的私有成员变量和成员函数),友元类是单向,不可传递的。
public:
string sitting_room;
Building(){
this->bed_room="bed";
this->sitting_room="sitting";
}
private:
string bed_room;
void print(){
cout<<"private print"<<endl;
}
};
void GoodGay::visit() {
cout<<building->sitting_room<<endl;
// cout<<building->bed_room<<endl;
// building->print();
}
void GoodGay::visit2() {
cout<<building->sitting_room<<endl;
cout<<building->bed_room<<endl;
building->print();
}
void goodGay(Building* building){
cout<<building->sitting_room<<endl;
// 友元函数中可以访问类中的私有成员变量和成员函数
cout<<building->bed_room<<endl;
building->print();
}
void test15(){
Building* b=new Building;
// goodGay(b);
GoodGay* gg=new GoodGay(b);
gg->visit();
gg->visit2();
}
int main(){
// test1();
test2();
// cout<<"end call"<<endl;
// test3();
// test4();
// test5();
// test6();
// test7();
// test8();
// cout<<"end test8 "<<endl;
// test9();
// test10();
// test11();
// test12();
// test13();
// test14();
// test15();
return EXIT_SUCCESS;
}
| [
"[email protected]"
] | |
eac44954f06d28fa67e2fded08c2839d441be937 | 434604177f36c2237b1254817e56e1608233aae9 | /src/rpcwallet.cpp | d49ba5771576d9d6ef397b2e7659897d20516f81 | [
"MIT"
] | permissive | GoldRushGOLDR/Gold-Rush_GOLDR | aede8eddfaa95b47915b977aca17b3c6d1646e5a | 97c25d6e1fcdd2e8a243d267b2c3c280e6fa8ad4 | refs/heads/master | 2016-09-05T21:59:10.737941 | 2015-06-25T11:37:04 | 2015-06-25T11:37:04 | 38,046,567 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 55,161 | cpp | // Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <boost/assign/list_of.hpp>
#include "wallet.h"
#include "walletdb.h"
#include "bitcoinrpc.h"
#include "init.h"
#include "base58.h"
using namespace std;
using namespace boost;
using namespace boost::assign;
using namespace json_spirit;
int64 nWalletUnlockTime;
static CCriticalSection cs_nWalletUnlockTime;
std::string HelpRequiringPassphrase()
{
return pwalletMain && pwalletMain->IsCrypted()
? "\nrequires wallet passphrase to be set with walletpassphrase first"
: "";
}
void EnsureWalletIsUnlocked()
{
if (pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
}
void WalletTxToJSON(const CWalletTx& wtx, Object& entry)
{
int confirms = wtx.GetDepthInMainChain();
entry.push_back(Pair("confirmations", confirms));
if (wtx.IsCoinBase())
entry.push_back(Pair("generated", true));
if (confirms > 0)
{
entry.push_back(Pair("blockhash", wtx.hashBlock.GetHex()));
entry.push_back(Pair("blockindex", wtx.nIndex));
entry.push_back(Pair("blocktime", (boost::int64_t)(mapBlockIndex[wtx.hashBlock]->nTime)));
}
entry.push_back(Pair("txid", wtx.GetHash().GetHex()));
entry.push_back(Pair("normtxid", wtx.GetNormalizedHash().GetHex()));
entry.push_back(Pair("time", (boost::int64_t)wtx.GetTxTime()));
entry.push_back(Pair("timereceived", (boost::int64_t)wtx.nTimeReceived));
BOOST_FOREACH(const PAIRTYPE(string,string)& item, wtx.mapValue)
entry.push_back(Pair(item.first, item.second));
}
string AccountFromValue(const Value& value)
{
string strAccount = value.get_str();
if (strAccount == "*")
throw JSONRPCError(RPC_WALLET_INVALID_ACCOUNT_NAME, "Invalid account name");
return strAccount;
}
Value getinfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getinfo\n"
"Returns an object containing various state info.");
proxyType proxy;
GetProxy(NET_IPV4, proxy);
Object obj;
obj.push_back(Pair("version", (int)CLIENT_VERSION));
obj.push_back(Pair("protocolversion",(int)PROTOCOL_VERSION));
if (pwalletMain) {
obj.push_back(Pair("walletversion", pwalletMain->GetVersion()));
obj.push_back(Pair("balance", ValueFromAmount(pwalletMain->GetBalance())));
}
obj.push_back(Pair("blocks", (int)nBestHeight));
obj.push_back(Pair("timeoffset", (boost::int64_t)GetTimeOffset()));
obj.push_back(Pair("connections", (int)vNodes.size()));
obj.push_back(Pair("proxy", (proxy.first.IsValid() ? proxy.first.ToStringIPPort() : string())));
obj.push_back(Pair("difficulty", (double)GetDifficulty()));
obj.push_back(Pair("testnet", fTestNet));
if (pwalletMain) {
obj.push_back(Pair("keypoololdest", (boost::int64_t)pwalletMain->GetOldestKeyPoolTime()));
obj.push_back(Pair("keypoolsize", (int)pwalletMain->GetKeyPoolSize()));
}
obj.push_back(Pair("paytxfee", ValueFromAmount(nTransactionFee)));
obj.push_back(Pair("mininput", ValueFromAmount(nMinimumInputValue)));
if (pwalletMain && pwalletMain->IsCrypted())
obj.push_back(Pair("unlocked_until", (boost::int64_t)nWalletUnlockTime));
obj.push_back(Pair("errors", GetWarnings("statusbar")));
return obj;
}
Value getnewaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getnewaddress [account]\n"
"Returns a new GOLDRUSHCOIN address for receiving payments. "
"If [account] is specified (recommended), it is added to the address book "
"so payments received with the address will be credited to [account].");
// Parse the account first so we don't generate a key if there's an error
string strAccount;
if (params.size() > 0)
strAccount = AccountFromValue(params[0]);
if (!pwalletMain->IsLocked())
pwalletMain->TopUpKeyPool();
// Generate a new key that is added to wallet
CPubKey newKey;
if (!pwalletMain->GetKeyFromPool(newKey, false))
throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
CKeyID keyID = newKey.GetID();
pwalletMain->SetAddressBookName(keyID, strAccount);
return CBitcoinAddress(keyID).ToString();
}
CBitcoinAddress GetAccountAddress(string strAccount, bool bForceNew=false)
{
CWalletDB walletdb(pwalletMain->strWalletFile);
CAccount account;
walletdb.ReadAccount(strAccount, account);
bool bKeyUsed = false;
// Check if the current key has been used
if (account.vchPubKey.IsValid())
{
CScript scriptPubKey;
scriptPubKey.SetDestination(account.vchPubKey.GetID());
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin();
it != pwalletMain->mapWallet.end() && account.vchPubKey.IsValid();
++it)
{
const CWalletTx& wtx = (*it).second;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
if (txout.scriptPubKey == scriptPubKey)
bKeyUsed = true;
}
}
// Generate a new key
if (!account.vchPubKey.IsValid() || bForceNew || bKeyUsed)
{
if (!pwalletMain->GetKeyFromPool(account.vchPubKey, false))
throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
pwalletMain->SetAddressBookName(account.vchPubKey.GetID(), strAccount);
walletdb.WriteAccount(strAccount, account);
}
return CBitcoinAddress(account.vchPubKey.GetID());
}
Value getaccountaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getaccountaddress <account>\n"
"Returns the current GOLDRUSHCOIN address for receiving payments to this account.");
// Parse the account first so we don't generate a key if there's an error
string strAccount = AccountFromValue(params[0]);
Value ret;
ret = GetAccountAddress(strAccount).ToString();
return ret;
}
Value setaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"setaccount <goldrushcoinaddress> <account>\n"
"Sets the account associated with the given address.");
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid GOLDRUSHCOIN address");
string strAccount;
if (params.size() > 1)
strAccount = AccountFromValue(params[1]);
// Detect when changing the account of an address that is the 'unused current key' of another account:
if (pwalletMain->mapAddressBook.count(address.Get()))
{
string strOldAccount = pwalletMain->mapAddressBook[address.Get()];
if (address == GetAccountAddress(strOldAccount))
GetAccountAddress(strOldAccount, true);
}
pwalletMain->SetAddressBookName(address.Get(), strAccount);
return Value::null;
}
Value getaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getaccount <goldrushcoinaddress>\n"
"Returns the account associated with the given address.");
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid GOLDRUSHCOIN address");
string strAccount;
map<CTxDestination, string>::iterator mi = pwalletMain->mapAddressBook.find(address.Get());
if (mi != pwalletMain->mapAddressBook.end() && !(*mi).second.empty())
strAccount = (*mi).second;
return strAccount;
}
Value getaddressesbyaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getaddressesbyaccount <account>\n"
"Returns the list of addresses for the given account.");
string strAccount = AccountFromValue(params[0]);
// Find all addresses that have the given account
Array ret;
BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, string)& item, pwalletMain->mapAddressBook)
{
const CBitcoinAddress& address = item.first;
const string& strName = item.second;
if (strName == strAccount)
ret.push_back(address.ToString());
}
return ret;
}
Value setmininput(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 1)
throw runtime_error(
"setmininput <amount>\n"
"<amount> is a real and is rounded to the nearest 0.00000001");
// Amount
int64 nAmount = 0;
if (params[0].get_real() != 0.0)
nAmount = AmountFromValue(params[0]); // rejects 0.0 amounts
nMinimumInputValue = nAmount;
return true;
}
Value sendtoaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 4)
throw runtime_error(
"sendtoaddress <goldrushcoinaddress> <amount> [comment] [comment-to]\n"
"<amount> is a real and is rounded to the nearest 0.00000001"
+ HelpRequiringPassphrase());
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid GOLDRUSHCOIN address");
// Amount
int64 nAmount = AmountFromValue(params[1]);
// Wallet comments
CWalletTx wtx;
if (params.size() > 2 && params[2].type() != null_type && !params[2].get_str().empty())
wtx.mapValue["comment"] = params[2].get_str();
if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())
wtx.mapValue["to"] = params[3].get_str();
if (pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx);
if (strError != "")
throw JSONRPCError(RPC_WALLET_ERROR, strError);
return wtx.GetHash().GetHex();
}
Value listaddressgroupings(const Array& params, bool fHelp)
{
if (fHelp)
throw runtime_error(
"listaddressgroupings\n"
"Lists groups of addresses which have had their common ownership\n"
"made public by common use as inputs or as the resulting change\n"
"in past transactions");
Array jsonGroupings;
map<CTxDestination, int64> balances = pwalletMain->GetAddressBalances();
BOOST_FOREACH(set<CTxDestination> grouping, pwalletMain->GetAddressGroupings())
{
Array jsonGrouping;
BOOST_FOREACH(CTxDestination address, grouping)
{
Array addressInfo;
addressInfo.push_back(CBitcoinAddress(address).ToString());
addressInfo.push_back(ValueFromAmount(balances[address]));
{
LOCK(pwalletMain->cs_wallet);
if (pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get()) != pwalletMain->mapAddressBook.end())
addressInfo.push_back(pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get())->second);
}
jsonGrouping.push_back(addressInfo);
}
jsonGroupings.push_back(jsonGrouping);
}
return jsonGroupings;
}
Value signmessage(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 2)
throw runtime_error(
"signmessage <goldrushcoinaddress> <message>\n"
"Sign a message with the private key of an address");
EnsureWalletIsUnlocked();
string strAddress = params[0].get_str();
string strMessage = params[1].get_str();
CBitcoinAddress addr(strAddress);
if (!addr.IsValid())
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address");
CKeyID keyID;
if (!addr.GetKeyID(keyID))
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
CKey key;
if (!pwalletMain->GetKey(keyID, key))
throw JSONRPCError(RPC_WALLET_ERROR, "Private key not available");
CHashWriter ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << strMessage;
vector<unsigned char> vchSig;
if (!key.SignCompact(ss.GetHash(), vchSig))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Sign failed");
return EncodeBase64(&vchSig[0], vchSig.size());
}
Value verifymessage(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 3)
throw runtime_error(
"verifymessage <goldrushcoinaddress> <signature> <message>\n"
"Verify a signed message");
string strAddress = params[0].get_str();
string strSign = params[1].get_str();
string strMessage = params[2].get_str();
CBitcoinAddress addr(strAddress);
if (!addr.IsValid())
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address");
CKeyID keyID;
if (!addr.GetKeyID(keyID))
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
bool fInvalid = false;
vector<unsigned char> vchSig = DecodeBase64(strSign.c_str(), &fInvalid);
if (fInvalid)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Malformed base64 encoding");
CHashWriter ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << strMessage;
CPubKey pubkey;
if (!pubkey.RecoverCompact(ss.GetHash(), vchSig))
return false;
return (pubkey.GetID() == keyID);
}
Value getreceivedbyaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getreceivedbyaddress <goldrushcoinaddress> [minconf=1]\n"
"Returns the total amount received by <goldrushcoinaddress> in transactions with at least [minconf] confirmations.");
// Bitcoin address
CBitcoinAddress address = CBitcoinAddress(params[0].get_str());
CScript scriptPubKey;
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid GOLDRUSHCOIN address");
scriptPubKey.SetDestination(address.Get());
if (!IsMine(*pwalletMain,scriptPubKey))
return (double)0.0;
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
// Tally
int64 nAmount = 0;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || !wtx.IsFinal())
continue;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
if (txout.scriptPubKey == scriptPubKey)
if (wtx.GetDepthInMainChain() >= nMinDepth)
nAmount += txout.nValue;
}
return ValueFromAmount(nAmount);
}
void GetAccountAddresses(string strAccount, set<CTxDestination>& setAddress)
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination, string)& item, pwalletMain->mapAddressBook)
{
const CTxDestination& address = item.first;
const string& strName = item.second;
if (strName == strAccount)
setAddress.insert(address);
}
}
Value getreceivedbyaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getreceivedbyaccount <account> [minconf=1]\n"
"Returns the total amount received by addresses with <account> in transactions with at least [minconf] confirmations.");
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
// Get the set of pub keys assigned to account
string strAccount = AccountFromValue(params[0]);
set<CTxDestination> setAddress;
GetAccountAddresses(strAccount, setAddress);
// Tally
int64 nAmount = 0;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || !wtx.IsFinal())
continue;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{
CTxDestination address;
if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*pwalletMain, address) && setAddress.count(address))
if (wtx.GetDepthInMainChain() >= nMinDepth)
nAmount += txout.nValue;
}
}
return (double)nAmount / (double)COIN;
}
int64 GetAccountBalance(CWalletDB& walletdb, const string& strAccount, int nMinDepth)
{
int64 nBalance = 0;
// Tally wallet transactions
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (!wtx.IsFinal())
continue;
int64 nReceived, nSent, nFee;
wtx.GetAccountAmounts(strAccount, nReceived, nSent, nFee);
if (nReceived != 0 && wtx.GetDepthInMainChain() >= nMinDepth)
nBalance += nReceived;
nBalance -= nSent + nFee;
}
// Tally internal accounting entries
nBalance += walletdb.GetAccountCreditDebit(strAccount);
return nBalance;
}
int64 GetAccountBalance(const string& strAccount, int nMinDepth)
{
CWalletDB walletdb(pwalletMain->strWalletFile);
return GetAccountBalance(walletdb, strAccount, nMinDepth);
}
Value getbalance(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"getbalance [account] [minconf=1]\n"
"If [account] is not specified, returns the server's total available balance.\n"
"If [account] is specified, returns the balance in the account.");
if (params.size() == 0)
return ValueFromAmount(pwalletMain->GetBalance());
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
if (params[0].get_str() == "*") {
// Calculate total balance a different way from GetBalance()
// (GetBalance() sums up all unspent TxOuts)
// getbalance and getbalance '*' 0 should return the same number
int64 nBalance = 0;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (!wtx.IsConfirmed())
continue;
int64 allFee;
string strSentAccount;
list<pair<CTxDestination, int64> > listReceived;
list<pair<CTxDestination, int64> > listSent;
wtx.GetAmounts(listReceived, listSent, allFee, strSentAccount);
if (wtx.GetDepthInMainChain() >= nMinDepth)
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listReceived)
nBalance += r.second;
}
BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listSent)
nBalance -= r.second;
nBalance -= allFee;
}
return ValueFromAmount(nBalance);
}
string strAccount = AccountFromValue(params[0]);
int64 nBalance = GetAccountBalance(strAccount, nMinDepth);
return ValueFromAmount(nBalance);
}
Value movecmd(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 3 || params.size() > 5)
throw runtime_error(
"move <fromaccount> <toaccount> <amount> [minconf=1] [comment]\n"
"Move from one account in your wallet to another.");
string strFrom = AccountFromValue(params[0]);
string strTo = AccountFromValue(params[1]);
int64 nAmount = AmountFromValue(params[2]);
if (params.size() > 3)
// unused parameter, used to be nMinDepth, keep type-checking it though
(void)params[3].get_int();
string strComment;
if (params.size() > 4)
strComment = params[4].get_str();
CWalletDB walletdb(pwalletMain->strWalletFile);
if (!walletdb.TxnBegin())
throw JSONRPCError(RPC_DATABASE_ERROR, "database error");
int64 nNow = GetAdjustedTime();
// Debit
CAccountingEntry debit;
debit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb);
debit.strAccount = strFrom;
debit.nCreditDebit = -nAmount;
debit.nTime = nNow;
debit.strOtherAccount = strTo;
debit.strComment = strComment;
walletdb.WriteAccountingEntry(debit);
// Credit
CAccountingEntry credit;
credit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb);
credit.strAccount = strTo;
credit.nCreditDebit = nAmount;
credit.nTime = nNow;
credit.strOtherAccount = strFrom;
credit.strComment = strComment;
walletdb.WriteAccountingEntry(credit);
if (!walletdb.TxnCommit())
throw JSONRPCError(RPC_DATABASE_ERROR, "database error");
return true;
}
Value sendfrom(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 3 || params.size() > 6)
throw runtime_error(
"sendfrom <fromaccount> <togoldrushcoinaddress> <amount> [minconf=1] [comment] [comment-to]\n"
"<amount> is a real and is rounded to the nearest 0.00000001"
+ HelpRequiringPassphrase());
string strAccount = AccountFromValue(params[0]);
CBitcoinAddress address(params[1].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid GOLDRUSHCOIN address");
int64 nAmount = AmountFromValue(params[2]);
int nMinDepth = 1;
if (params.size() > 3)
nMinDepth = params[3].get_int();
CWalletTx wtx;
wtx.strFromAccount = strAccount;
if (params.size() > 4 && params[4].type() != null_type && !params[4].get_str().empty())
wtx.mapValue["comment"] = params[4].get_str();
if (params.size() > 5 && params[5].type() != null_type && !params[5].get_str().empty())
wtx.mapValue["to"] = params[5].get_str();
EnsureWalletIsUnlocked();
// Check funds
int64 nBalance = GetAccountBalance(strAccount, nMinDepth);
if (nAmount > nBalance)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds");
// Send
string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx);
if (strError != "")
throw JSONRPCError(RPC_WALLET_ERROR, strError);
return wtx.GetHash().GetHex();
}
Value sendmany(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 4)
throw runtime_error(
"sendmany <fromaccount> {address:amount,...} [minconf=1] [comment]\n"
"amounts are double-precision floating point numbers"
+ HelpRequiringPassphrase());
string strAccount = AccountFromValue(params[0]);
Object sendTo = params[1].get_obj();
int nMinDepth = 1;
if (params.size() > 2)
nMinDepth = params[2].get_int();
CWalletTx wtx;
wtx.strFromAccount = strAccount;
if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())
wtx.mapValue["comment"] = params[3].get_str();
set<CBitcoinAddress> setAddress;
vector<pair<CScript, int64> > vecSend;
int64 totalAmount = 0;
BOOST_FOREACH(const Pair& s, sendTo)
{
CBitcoinAddress address(s.name_);
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid GOLDRUSHCOIN address: ")+s.name_);
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+s.name_);
setAddress.insert(address);
CScript scriptPubKey;
scriptPubKey.SetDestination(address.Get());
int64 nAmount = AmountFromValue(s.value_);
totalAmount += nAmount;
vecSend.push_back(make_pair(scriptPubKey, nAmount));
}
EnsureWalletIsUnlocked();
// Check funds
int64 nBalance = GetAccountBalance(strAccount, nMinDepth);
if (totalAmount > nBalance)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds");
// Send
CReserveKey keyChange(pwalletMain);
int64 nFeeRequired = 0;
string strFailReason;
bool fCreated = pwalletMain->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired, strFailReason);
if (!fCreated)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, strFailReason);
if (!pwalletMain->CommitTransaction(wtx, keyChange))
throw JSONRPCError(RPC_WALLET_ERROR, "Transaction commit failed");
return wtx.GetHash().GetHex();
}
//
// Used by addmultisigaddress / createmultisig:
//
static CScript _createmultisig(const Array& params)
{
int nRequired = params[0].get_int();
const Array& keys = params[1].get_array();
// Gather public keys
if (nRequired < 1)
throw runtime_error("a multisignature address must require at least one key to redeem");
if ((int)keys.size() < nRequired)
throw runtime_error(
strprintf("not enough keys supplied "
"(got %"PRIszu" keys, but need at least %d to redeem)", keys.size(), nRequired));
std::vector<CPubKey> pubkeys;
pubkeys.resize(keys.size());
for (unsigned int i = 0; i < keys.size(); i++)
{
const std::string& ks = keys[i].get_str();
// Case 1: GOLDRUSHCOIN address and we have full public key:
CBitcoinAddress address(ks);
if (pwalletMain && address.IsValid())
{
CKeyID keyID;
if (!address.GetKeyID(keyID))
throw runtime_error(
strprintf("%s does not refer to a key",ks.c_str()));
CPubKey vchPubKey;
if (!pwalletMain->GetPubKey(keyID, vchPubKey))
throw runtime_error(
strprintf("no full public key for address %s",ks.c_str()));
if (!vchPubKey.IsFullyValid())
throw runtime_error(" Invalid public key: "+ks);
pubkeys[i] = vchPubKey;
}
// Case 2: hex public key
else if (IsHex(ks))
{
CPubKey vchPubKey(ParseHex(ks));
if (!vchPubKey.IsFullyValid())
throw runtime_error(" Invalid public key: "+ks);
pubkeys[i] = vchPubKey;
}
else
{
throw runtime_error(" Invalid public key: "+ks);
}
}
CScript result;
result.SetMultisig(nRequired, pubkeys);
return result;
}
Value addmultisigaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 3)
{
string msg = "addmultisigaddress <nrequired> <'[\"key\",\"key\"]'> [account]\n"
"Add a nrequired-to-sign multisignature address to the wallet\"\n"
"each key is a GOLDRUSHCOIN address or hex-encoded public key\n"
"If [account] is specified, assign address to [account].";
throw runtime_error(msg);
}
string strAccount;
if (params.size() > 2)
strAccount = AccountFromValue(params[2]);
// Construct using pay-to-script-hash:
CScript inner = _createmultisig(params);
CScriptID innerID = inner.GetID();
pwalletMain->AddCScript(inner);
pwalletMain->SetAddressBookName(innerID, strAccount);
return CBitcoinAddress(innerID).ToString();
}
Value createmultisig(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 2)
{
string msg = "createmultisig <nrequired> <'[\"key\",\"key\"]'>\n"
"Creates a multi-signature address and returns a json object\n"
"with keys:\n"
"address : goldrushcoin address\n"
"redeemScript : hex-encoded redemption script";
throw runtime_error(msg);
}
// Construct using pay-to-script-hash:
CScript inner = _createmultisig(params);
CScriptID innerID = inner.GetID();
CBitcoinAddress address(innerID);
Object result;
result.push_back(Pair("address", address.ToString()));
result.push_back(Pair("redeemScript", HexStr(inner.begin(), inner.end())));
return result;
}
struct tallyitem
{
int64 nAmount;
int nConf;
vector<uint256> txids;
tallyitem()
{
nAmount = 0;
nConf = std::numeric_limits<int>::max();
}
};
Value ListReceived(const Array& params, bool fByAccounts)
{
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
// Whether to include empty accounts
bool fIncludeEmpty = false;
if (params.size() > 1)
fIncludeEmpty = params[1].get_bool();
// Tally
map<CBitcoinAddress, tallyitem> mapTally;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || !wtx.IsFinal())
continue;
int nDepth = wtx.GetDepthInMainChain();
if (nDepth < nMinDepth)
continue;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{
CTxDestination address;
if (!ExtractDestination(txout.scriptPubKey, address) || !IsMine(*pwalletMain, address))
continue;
tallyitem& item = mapTally[address];
item.nAmount += txout.nValue;
item.nConf = min(item.nConf, nDepth);
item.txids.push_back(wtx.GetHash());
}
}
// Reply
Array ret;
map<string, tallyitem> mapAccountTally;
BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, string)& item, pwalletMain->mapAddressBook)
{
const CBitcoinAddress& address = item.first;
const string& strAccount = item.second;
map<CBitcoinAddress, tallyitem>::iterator it = mapTally.find(address);
if (it == mapTally.end() && !fIncludeEmpty)
continue;
int64 nAmount = 0;
int nConf = std::numeric_limits<int>::max();
if (it != mapTally.end())
{
nAmount = (*it).second.nAmount;
nConf = (*it).second.nConf;
}
if (fByAccounts)
{
tallyitem& item = mapAccountTally[strAccount];
item.nAmount += nAmount;
item.nConf = min(item.nConf, nConf);
}
else
{
Object obj;
obj.push_back(Pair("address", address.ToString()));
obj.push_back(Pair("account", strAccount));
obj.push_back(Pair("amount", ValueFromAmount(nAmount)));
obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf)));
Array transactions;
if (it != mapTally.end())
{
BOOST_FOREACH(const uint256& item, (*it).second.txids)
{
transactions.push_back(item.GetHex());
}
}
obj.push_back(Pair("txids", transactions));
ret.push_back(obj);
}
}
if (fByAccounts)
{
for (map<string, tallyitem>::iterator it = mapAccountTally.begin(); it != mapAccountTally.end(); ++it)
{
int64 nAmount = (*it).second.nAmount;
int nConf = (*it).second.nConf;
Object obj;
obj.push_back(Pair("account", (*it).first));
obj.push_back(Pair("amount", ValueFromAmount(nAmount)));
obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf)));
ret.push_back(obj);
}
}
return ret;
}
Value listreceivedbyaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"listreceivedbyaddress [minconf=1] [includeempty=false]\n"
"[minconf] is the minimum number of confirmations before payments are included.\n"
"[includeempty] whether to include addresses that haven't received any payments.\n"
"Returns an array of objects containing:\n"
" \"address\" : receiving address\n"
" \"account\" : the account of the receiving address\n"
" \"amount\" : total amount received by the address\n"
" \"confirmations\" : number of confirmations of the most recent transaction included\n"
" \"txids\" : list of transactions with outputs to the address\n");
return ListReceived(params, false);
}
Value listreceivedbyaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"listreceivedbyaccount [minconf=1] [includeempty=false]\n"
"[minconf] is the minimum number of confirmations before payments are included.\n"
"[includeempty] whether to include accounts that haven't received any payments.\n"
"Returns an array of objects containing:\n"
" \"account\" : the account of the receiving addresses\n"
" \"amount\" : total amount received by addresses with this account\n"
" \"confirmations\" : number of confirmations of the most recent transaction included");
return ListReceived(params, true);
}
static void MaybePushAddress(Object & entry, const CTxDestination &dest)
{
CBitcoinAddress addr;
if (addr.Set(dest))
entry.push_back(Pair("address", addr.ToString()));
}
void ListTransactions(const CWalletTx& wtx, const string& strAccount, int nMinDepth, bool fLong, Array& ret)
{
int64 nFee;
string strSentAccount;
list<pair<CTxDestination, int64> > listReceived;
list<pair<CTxDestination, int64> > listSent;
wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount);
bool fAllAccounts = (strAccount == string("*"));
// Sent
if ((!listSent.empty() || nFee != 0) && (fAllAccounts || strAccount == strSentAccount))
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& s, listSent)
{
Object entry;
entry.push_back(Pair("account", strSentAccount));
MaybePushAddress(entry, s.first);
entry.push_back(Pair("category", "send"));
entry.push_back(Pair("amount", ValueFromAmount(-s.second)));
entry.push_back(Pair("fee", ValueFromAmount(-nFee)));
if (fLong)
WalletTxToJSON(wtx, entry);
ret.push_back(entry);
}
}
// Received
if (listReceived.size() > 0 && wtx.GetDepthInMainChain() >= nMinDepth)
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& r, listReceived)
{
string account;
if (pwalletMain->mapAddressBook.count(r.first))
account = pwalletMain->mapAddressBook[r.first];
if (fAllAccounts || (account == strAccount))
{
Object entry;
entry.push_back(Pair("account", account));
MaybePushAddress(entry, r.first);
if (wtx.IsCoinBase())
{
if (wtx.GetDepthInMainChain() < 1)
entry.push_back(Pair("category", "orphan"));
else if (wtx.GetBlocksToMaturity() > 0)
entry.push_back(Pair("category", "immature"));
else
entry.push_back(Pair("category", "generate"));
}
else
{
entry.push_back(Pair("category", "receive"));
}
entry.push_back(Pair("amount", ValueFromAmount(r.second)));
if (fLong)
WalletTxToJSON(wtx, entry);
ret.push_back(entry);
}
}
}
}
void AcentryToJSON(const CAccountingEntry& acentry, const string& strAccount, Array& ret)
{
bool fAllAccounts = (strAccount == string("*"));
if (fAllAccounts || acentry.strAccount == strAccount)
{
Object entry;
entry.push_back(Pair("account", acentry.strAccount));
entry.push_back(Pair("category", "move"));
entry.push_back(Pair("time", (boost::int64_t)acentry.nTime));
entry.push_back(Pair("amount", ValueFromAmount(acentry.nCreditDebit)));
entry.push_back(Pair("otheraccount", acentry.strOtherAccount));
entry.push_back(Pair("comment", acentry.strComment));
ret.push_back(entry);
}
}
Value listtransactions(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 3)
throw runtime_error(
"listtransactions [account] [count=10] [from=0]\n"
"Returns up to [count] most recent transactions skipping the first [from] transactions for account [account].");
string strAccount = "*";
if (params.size() > 0)
strAccount = params[0].get_str();
int nCount = 10;
if (params.size() > 1)
nCount = params[1].get_int();
int nFrom = 0;
if (params.size() > 2)
nFrom = params[2].get_int();
if (nCount < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative count");
if (nFrom < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative from");
Array ret;
std::list<CAccountingEntry> acentries;
CWallet::TxItems txOrdered = pwalletMain->OrderedTxItems(acentries, strAccount);
// iterate backwards until we have nCount items to return:
for (CWallet::TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
{
CWalletTx *const pwtx = (*it).second.first;
if (pwtx != 0)
ListTransactions(*pwtx, strAccount, 0, true, ret);
CAccountingEntry *const pacentry = (*it).second.second;
if (pacentry != 0)
AcentryToJSON(*pacentry, strAccount, ret);
if ((int)ret.size() >= (nCount+nFrom)) break;
}
// ret is newest to oldest
if (nFrom > (int)ret.size())
nFrom = ret.size();
if ((nFrom + nCount) > (int)ret.size())
nCount = ret.size() - nFrom;
Array::iterator first = ret.begin();
std::advance(first, nFrom);
Array::iterator last = ret.begin();
std::advance(last, nFrom+nCount);
if (last != ret.end()) ret.erase(last, ret.end());
if (first != ret.begin()) ret.erase(ret.begin(), first);
std::reverse(ret.begin(), ret.end()); // Return oldest to newest
return ret;
}
Value listaccounts(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"listaccounts [minconf=1]\n"
"Returns Object that has account names as keys, account balances as values.");
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
map<string, int64> mapAccountBalances;
BOOST_FOREACH(const PAIRTYPE(CTxDestination, string)& entry, pwalletMain->mapAddressBook) {
if (IsMine(*pwalletMain, entry.first)) // This address belongs to me
mapAccountBalances[entry.second] = 0;
}
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
int64 nFee;
string strSentAccount;
list<pair<CTxDestination, int64> > listReceived;
list<pair<CTxDestination, int64> > listSent;
wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount);
mapAccountBalances[strSentAccount] -= nFee;
BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& s, listSent)
mapAccountBalances[strSentAccount] -= s.second;
if (wtx.GetDepthInMainChain() >= nMinDepth)
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& r, listReceived)
if (pwalletMain->mapAddressBook.count(r.first))
mapAccountBalances[pwalletMain->mapAddressBook[r.first]] += r.second;
else
mapAccountBalances[""] += r.second;
}
}
list<CAccountingEntry> acentries;
CWalletDB(pwalletMain->strWalletFile).ListAccountCreditDebit("*", acentries);
BOOST_FOREACH(const CAccountingEntry& entry, acentries)
mapAccountBalances[entry.strAccount] += entry.nCreditDebit;
Object ret;
BOOST_FOREACH(const PAIRTYPE(string, int64)& accountBalance, mapAccountBalances) {
ret.push_back(Pair(accountBalance.first, ValueFromAmount(accountBalance.second)));
}
return ret;
}
Value listsinceblock(const Array& params, bool fHelp)
{
if (fHelp)
throw runtime_error(
"listsinceblock [blockhash] [target-confirmations]\n"
"Get all transactions in blocks since block [blockhash], or all transactions if omitted");
CBlockIndex *pindex = NULL;
int target_confirms = 1;
if (params.size() > 0)
{
uint256 blockId = 0;
blockId.SetHex(params[0].get_str());
pindex = CBlockLocator(blockId).GetBlockIndex();
}
if (params.size() > 1)
{
target_confirms = params[1].get_int();
if (target_confirms < 1)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
}
int depth = pindex ? (1 + nBestHeight - pindex->nHeight) : -1;
Array transactions;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); it++)
{
CWalletTx tx = (*it).second;
if (depth == -1 || tx.GetDepthInMainChain() < depth)
ListTransactions(tx, "*", 0, true, transactions);
}
uint256 lastblock;
if (target_confirms == 1)
{
lastblock = hashBestChain;
}
else
{
int target_height = pindexBest->nHeight + 1 - target_confirms;
CBlockIndex *block;
for (block = pindexBest;
block && block->nHeight > target_height;
block = block->pprev) { }
lastblock = block ? block->GetBlockHash() : 0;
}
Object ret;
ret.push_back(Pair("transactions", transactions));
ret.push_back(Pair("lastblock", lastblock.GetHex()));
return ret;
}
Value gettransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"gettransaction <txid>\n"
"Get detailed information about in-wallet transaction <txid>");
uint256 hash;
hash.SetHex(params[0].get_str());
Object entry;
if (!pwalletMain->mapWallet.count(hash))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid or non-wallet transaction id");
const CWalletTx& wtx = pwalletMain->mapWallet[hash];
int64 nCredit = wtx.GetCredit();
int64 nDebit = wtx.GetDebit();
int64 nNet = nCredit - nDebit;
int64 nFee = (wtx.IsFromMe() ? wtx.GetValueOut() - nDebit : 0);
entry.push_back(Pair("amount", ValueFromAmount(nNet - nFee)));
if (wtx.IsFromMe())
entry.push_back(Pair("fee", ValueFromAmount(nFee)));
WalletTxToJSON(wtx, entry);
Array details;
ListTransactions(wtx, "*", 0, false, details);
entry.push_back(Pair("details", details));
return entry;
}
Value backupwallet(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"backupwallet <destination>\n"
"Safely copies wallet.dat to destination, which can be a directory or a path with filename.");
string strDest = params[0].get_str();
if (!BackupWallet(*pwalletMain, strDest))
throw JSONRPCError(RPC_WALLET_ERROR, "Error: Wallet backup failed!");
return Value::null;
}
Value keypoolrefill(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 0)
throw runtime_error(
"keypoolrefill\n"
"Fills the keypool."
+ HelpRequiringPassphrase());
EnsureWalletIsUnlocked();
pwalletMain->TopUpKeyPool();
if (pwalletMain->GetKeyPoolSize() < GetArg("-keypool", 100))
throw JSONRPCError(RPC_WALLET_ERROR, "Error refreshing keypool.");
return Value::null;
}
void ThreadTopUpKeyPool(void* parg)
{
// Make this thread recognisable as the key-topping-up thread
RenameThread("bitcoin-key-top");
pwalletMain->TopUpKeyPool();
}
void ThreadCleanWalletPassphrase(void* parg)
{
// Make this thread recognisable as the wallet relocking thread
RenameThread("bitcoin-lock-wa");
int64 nMyWakeTime = GetTimeMillis() + *((int64*)parg) * 1000;
ENTER_CRITICAL_SECTION(cs_nWalletUnlockTime);
if (nWalletUnlockTime == 0)
{
nWalletUnlockTime = nMyWakeTime;
do
{
if (nWalletUnlockTime==0)
break;
int64 nToSleep = nWalletUnlockTime - GetTimeMillis();
if (nToSleep <= 0)
break;
LEAVE_CRITICAL_SECTION(cs_nWalletUnlockTime);
MilliSleep(nToSleep);
ENTER_CRITICAL_SECTION(cs_nWalletUnlockTime);
} while(1);
if (nWalletUnlockTime)
{
nWalletUnlockTime = 0;
pwalletMain->Lock();
}
}
else
{
if (nWalletUnlockTime < nMyWakeTime)
nWalletUnlockTime = nMyWakeTime;
}
LEAVE_CRITICAL_SECTION(cs_nWalletUnlockTime);
delete (int64*)parg;
}
Value walletpassphrase(const Array& params, bool fHelp)
{
if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2))
throw runtime_error(
"walletpassphrase <passphrase> <timeout>\n"
"Stores the wallet decryption key in memory for <timeout> seconds.");
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrase was called.");
if (!pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_ALREADY_UNLOCKED, "Error: Wallet is already unlocked.");
// Note that the walletpassphrase is stored in params[0] which is not mlock()ed
SecureString strWalletPass;
strWalletPass.reserve(100);
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
strWalletPass = params[0].get_str().c_str();
if (strWalletPass.length() > 0)
{
if (!pwalletMain->Unlock(strWalletPass))
throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect.");
}
else
throw runtime_error(
"walletpassphrase <passphrase> <timeout>\n"
"Stores the wallet decryption key in memory for <timeout> seconds.");
NewThread(ThreadTopUpKeyPool, NULL);
int64* pnSleepTime = new int64(params[1].get_int64());
NewThread(ThreadCleanWalletPassphrase, pnSleepTime);
return Value::null;
}
Value walletpassphrasechange(const Array& params, bool fHelp)
{
if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2))
throw runtime_error(
"walletpassphrasechange <oldpassphrase> <newpassphrase>\n"
"Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>.");
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrasechange was called.");
// TODO: get rid of these .c_str() calls by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
SecureString strOldWalletPass;
strOldWalletPass.reserve(100);
strOldWalletPass = params[0].get_str().c_str();
SecureString strNewWalletPass;
strNewWalletPass.reserve(100);
strNewWalletPass = params[1].get_str().c_str();
if (strOldWalletPass.length() < 1 || strNewWalletPass.length() < 1)
throw runtime_error(
"walletpassphrasechange <oldpassphrase> <newpassphrase>\n"
"Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>.");
if (!pwalletMain->ChangeWalletPassphrase(strOldWalletPass, strNewWalletPass))
throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect.");
return Value::null;
}
Value walletlock(const Array& params, bool fHelp)
{
if (pwalletMain->IsCrypted() && (fHelp || params.size() != 0))
throw runtime_error(
"walletlock\n"
"Removes the wallet encryption key from memory, locking the wallet.\n"
"After calling this method, you will need to call walletpassphrase again\n"
"before being able to call any methods which require the wallet to be unlocked.");
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletlock was called.");
{
LOCK(cs_nWalletUnlockTime);
pwalletMain->Lock();
nWalletUnlockTime = 0;
}
return Value::null;
}
Value encryptwallet(const Array& params, bool fHelp)
{
if (!pwalletMain->IsCrypted() && (fHelp || params.size() != 1))
throw runtime_error(
"encryptwallet <passphrase>\n"
"Encrypts the wallet with <passphrase>.");
if (fHelp)
return true;
if (pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an encrypted wallet, but encryptwallet was called.");
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
SecureString strWalletPass;
strWalletPass.reserve(100);
strWalletPass = params[0].get_str().c_str();
if (strWalletPass.length() < 1)
throw runtime_error(
"encryptwallet <passphrase>\n"
"Encrypts the wallet with <passphrase>.");
if (!pwalletMain->EncryptWallet(strWalletPass))
throw JSONRPCError(RPC_WALLET_ENCRYPTION_FAILED, "Error: Failed to encrypt the wallet.");
// BDB seems to have a bad habit of writing old data into
// slack space in .dat files; that is bad if the old data is
// unencrypted private keys. So:
StartShutdown();
return "wallet encrypted; GOLDRUSHCOIN server stopping, restart to run with encrypted wallet. The keypool has been flushed, you need to make a new backup.";
}
class DescribeAddressVisitor : public boost::static_visitor<Object>
{
public:
Object operator()(const CNoDestination &dest) const { return Object(); }
Object operator()(const CKeyID &keyID) const {
Object obj;
CPubKey vchPubKey;
pwalletMain->GetPubKey(keyID, vchPubKey);
obj.push_back(Pair("isscript", false));
obj.push_back(Pair("pubkey", HexStr(vchPubKey)));
obj.push_back(Pair("iscompressed", vchPubKey.IsCompressed()));
return obj;
}
Object operator()(const CScriptID &scriptID) const {
Object obj;
obj.push_back(Pair("isscript", true));
CScript subscript;
pwalletMain->GetCScript(scriptID, subscript);
std::vector<CTxDestination> addresses;
txnouttype whichType;
int nRequired;
ExtractDestinations(subscript, whichType, addresses, nRequired);
obj.push_back(Pair("script", GetTxnOutputType(whichType)));
Array a;
BOOST_FOREACH(const CTxDestination& addr, addresses)
a.push_back(CBitcoinAddress(addr).ToString());
obj.push_back(Pair("addresses", a));
if (whichType == TX_MULTISIG)
obj.push_back(Pair("sigsrequired", nRequired));
return obj;
}
};
Value validateaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"validateaddress <goldrushcoinaddress>\n"
"Return information about <goldrushcoinaddress>.");
CBitcoinAddress address(params[0].get_str());
bool isValid = address.IsValid();
Object ret;
ret.push_back(Pair("isvalid", isValid));
if (isValid)
{
CTxDestination dest = address.Get();
string currentAddress = address.ToString();
ret.push_back(Pair("address", currentAddress));
bool fMine = pwalletMain ? IsMine(*pwalletMain, dest) : false;
ret.push_back(Pair("ismine", fMine));
if (fMine) {
Object detail = boost::apply_visitor(DescribeAddressVisitor(), dest);
ret.insert(ret.end(), detail.begin(), detail.end());
}
if (pwalletMain && pwalletMain->mapAddressBook.count(dest))
ret.push_back(Pair("account", pwalletMain->mapAddressBook[dest]));
}
return ret;
}
Value lockunspent(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"lockunspent unlock? [array-of-Objects]\n"
"Updates list of temporarily unspendable outputs.");
if (params.size() == 1)
RPCTypeCheck(params, list_of(bool_type));
else
RPCTypeCheck(params, list_of(bool_type)(array_type));
bool fUnlock = params[0].get_bool();
if (params.size() == 1) {
if (fUnlock)
pwalletMain->UnlockAllCoins();
return true;
}
Array outputs = params[1].get_array();
BOOST_FOREACH(Value& output, outputs)
{
if (output.type() != obj_type)
throw JSONRPCError(-8, "Invalid parameter, expected object");
const Object& o = output.get_obj();
RPCTypeCheck(o, map_list_of("txid", str_type)("vout", int_type));
string txid = find_value(o, "txid").get_str();
if (!IsHex(txid))
throw JSONRPCError(-8, "Invalid parameter, expected hex txid");
int nOutput = find_value(o, "vout").get_int();
if (nOutput < 0)
throw JSONRPCError(-8, "Invalid parameter, vout must be positive");
COutPoint outpt(uint256(txid), nOutput);
if (fUnlock)
pwalletMain->UnlockCoin(outpt);
else
pwalletMain->LockCoin(outpt);
}
return true;
}
Value listlockunspent(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 0)
throw runtime_error(
"listlockunspent\n"
"Returns list of temporarily unspendable outputs.");
vector<COutPoint> vOutpts;
pwalletMain->ListLockedCoins(vOutpts);
Array ret;
BOOST_FOREACH(COutPoint &outpt, vOutpts) {
Object o;
o.push_back(Pair("txid", outpt.hash.GetHex()));
o.push_back(Pair("vout", (int)outpt.n));
ret.push_back(o);
}
return ret;
}
| [
"[email protected]"
] | |
845127eaf9e420defa99fdab62c51e13fa826435 | 569288c10e9cc8c5be2bf381aa853740d211bdd1 | /plc4cpp/api/src/main/cpp/org/apache/plc4x/cpp/api/exceptions/PlcConnectionException.h | 7eedd8ab0a907b4ad5ff0d71cb5bc9e09632de9f | [
"Apache-2.0"
] | permissive | fukewei/plc4x | db192ac49c38bc1358f8406e9a66f9c036ccd40d | f23cbec12d0c8c00138f3df617cae152c055781e | refs/heads/master | 2020-05-18T05:16:27.206892 | 2019-04-05T10:18:03 | 2019-04-05T10:18:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,540 | h | /*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
#ifndef _PLC_CONNECTION_EXCEPTION
#define _PLC_CONNECTION_EXCEPTION
#include "PlcException.h"
namespace org
{
namespace apache
{
namespace plc4x
{
namespace cpp
{
namespace api
{
namespace exceptions
{
class PlcConnectionException : public PlcException
{
public:
PlcConnectionException(): PlcException() {}
explicit PlcConnectionException(const std::string &message): PlcException(message){}
PlcConnectionException(const std::string &message, const std::exception &exception): PlcException(message, exception){}
explicit PlcConnectionException(const std::exception &exception): PlcException(exception){}
};
}
}
}
}
}
}
#endif
| [
"[email protected]"
] | |
c613aa85aa8fc84cacc05bec88bcdb6082f2205e | a316628f23fdd80823c9bc8a9b500e46d6b39c97 | /Graph/toi12_pipe.cpp | 8d25248eb46fddbbc4f59015b16e7212a7d6df68 | [] | no_license | boyplus/POSN3-Tutorial | 959e8f4145bc24bb04dee84d133cd31e6a021a16 | e185218edac36fdc925300a5893b84dd53dbce39 | refs/heads/main | 2023-01-23T00:45:28.701022 | 2020-12-05T21:19:55 | 2020-12-05T21:19:55 | 305,589,762 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 779 | cpp | #include <cstdio>
#include <algorithm>
#include <vector>
using namespace std;
const int maxN = 15001,INF = (int)1e9;
int dist[maxN],x[maxN],y[maxN];
bool visited[maxN];
vector<int> md;
int main(){
int n,k;
scanf("%d %d",&n,&k);
for(int i=0;i<n;i++){
scanf("%d %d",&x[i],&y[i]);
dist[i] = INF;
}
int choose = 0;
for(int i=0;i<n;++i){
int current = choose, mn = INF;
visited[current] = true;
for(int j=0;j<n;++j){
if(visited[j] == true) continue;
int d = abs(x[current]-x[j])+abs(y[current]-y[j]);
dist[j] = min(dist[j],d);
if(mn > dist[j]){
choose = j;
mn = dist[j];
}
}
md.push_back(mn);
}
long long sum = 0;
sort(md.begin(),md.end());
int last = n-k;
for(int i=0;i<last;++i){
sum += md[i];
}
printf("%lld\n",sum);
return 0;
} | [
"[email protected]"
] | |
bb0427f941854f450c8662ab6f4e637839cbc50f | 9319c75ce405c9c9c9c307e189cfc1cc9437e1fe | /Data-Structure-Cpp/01.DataStructure&Algorithm/05.Advanced/Exercise05_SlidingWindow.h | e625aaf5edd6beb67eb4934d6057db4f76c7b575 | [] | no_license | thatWangCheng/Data-Structure-Cpp | ebd0ebcea001144262ba2f8dc049b7db91223b6a | 3c4d0a53a436eba19ae59cbaa407cceb6c963b13 | refs/heads/master | 2022-04-07T08:38:19.901377 | 2020-01-07T08:54:28 | 2020-01-07T08:54:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,249 | h | #pragma once
#include "Exercise00_AdvancedTools.h"
// [L..R)
class SlideWindow {
public:
SlideWindow(const vector<int>& arr) :
arr(arr),
left(0),
right(0),
q(deque<int>())
{}
int Max() {
if (q.empty()) {
return INT_MIN;
}
return arr[q.front()];
}
vector<int> Window() {
auto l = arr.begin() + left;
auto r = arr.begin() + right;
vector<int> window(l, r);
return window;
}
void MoveRightSlider() {
if (arr.size() < 1 || right + 1 == arr.size()) {
return;
}
right++;
if (q.empty()) {
q.push_back(right - 1);
}
else {
while (!q.empty()) {
if (arr[q.back()] < arr[right - 1]) {
q.pop_back();
}
else {
break;
}
}
q.push_back(right - 1);
}
}
void MoveLeftSlider() {
if (arr.size() < 1 || left > right) {
return;
}
if (q.front() == left++) {
q.pop_front();
}
}
public:
vector<int> arr;
int left;
int right;
deque<int> q;
}; | [
"[email protected]"
] | |
c2d5b6cc18c7cc3122cd9361dadc05b9f6a89afb | bb03c60d676c543678aa01102565243bdb172372 | /mainwindow.h | 15d9ba3a796417d29468350d38ae811ed86a6991 | [] | no_license | RoscaS/cpp_cp3 | d205d1a95c58ac0b67d8e3e1ddb134828c8587cd | d80379cccbad63c26d3b57c46e5a07ca9a138a06 | refs/heads/master | 2020-05-18T02:40:29.511972 | 2019-04-29T18:35:10 | 2019-04-29T18:35:10 | 184,123,569 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 437 | h | #pragma once
#include "table.h"
#include "ui_mainwindow.h"
class MainWindow : public QMainWindow, private Ui::mainwindow {
Q_OBJECT
private:
Diagram *diagram;
Table *table;
public:
explicit MainWindow(QWidget *parent = nullptr);
private:
private slots:
void about();
public slots:
void on_a_exit_triggered() { close(); }
void on_a_about_triggered() { about(); }
void on_a_print_triggered() { diagram->print(); }
};
| [
"[email protected]"
] | |
ae415cf31338d560c03af41b1565c618609da373 | 5a01a3eb7b04532095d3c9e876ef05037e986d7d | /C++TorrentDownloader/MagnetLinkParser.h | b594dbcad49ec6787d5eb1ce5e446695fbd75748 | [] | no_license | Spaceslug/C-TorrentDownloader | e930cca8c8b0c117a08af78e9ecb7595ee2fc941 | 2107d98da37dd65e2786ba71fd2ba14d7b626148 | refs/heads/master | 2021-01-19T02:41:54.116323 | 2016-07-13T17:20:07 | 2016-07-13T17:20:07 | 62,922,719 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 286 | h | #pragma once
#include <unordered_map>
#include <string>
#include "Torrent.h"
class MagnetLinkParser
{
public:
MagnetLinkParser();
~MagnetLinkParser();
static std::shared_ptr<Torrent> parse(std::string magnetLink, std::shared_ptr<Torrent> torrent = std::make_shared<Torrent>());
};
| [
"[email protected]"
] | |
5533fb1873d306d76eec498f62fac51788a82802 | 3418bbb7d9e5a4e9d6315700a9a965b453907123 | /src/experimentloader.h | 1a84730074cee5b9ee240435dfaba9ac7d1e0f35 | [] | no_license | fabiochiusano/SwitchingBandit | a3eadb633b7a8c70fdc1b674c579f1bdc4aec22e | 89e501b4f343386432e324f458d51b98e145dc9c | refs/heads/master | 2021-03-27T12:01:39.385580 | 2018-09-13T20:57:29 | 2018-09-13T20:57:29 | 116,937,442 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 532 | h | /**
* @file experimentloader.h
* @author Fabio Chiusano
* @date 08/06/2018
* @version 1.0
*/
#ifndef MABLOADER_H
#define MABLOADER_H
#include <vector>
#include "experiment.h"
using namespace std;
/**
* @brief class whose main goal is to offer a static method which returns a vector of experiments
* loaded from a configuration file.
*/
class ExperimentLoader {
public:
/**
* @return a vector of experiments loaded from a configuration file.
*/
static vector<Experiment*>* load_experiments();
};
#endif
| [
"[email protected]"
] | |
eb9970ca242d2767a612fb4fd16636e22facb020 | b95d9ae3634ef2e535f3956379aaaa697a311dfa | /NPB-TBB/common/wtime_sgi64.cpp | aae26073453c23dcd7ebb3cd61d14eb7185a0c6f | [
"MIT"
] | permissive | hipa211a/NPB-CPP | 456af74e20e9aefa955de3f5055a6ce5cb68a7b0 | 2f77a1bce83c4efda56c4bafb555bcf9abe85dd2 | refs/heads/master | 2023-08-29T14:52:16.706635 | 2021-07-21T22:01:23 | 2021-07-21T22:01:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,458 | cpp | /*
MIT License
Copyright (c) 2021 Parallel Applications Modelling Group - GMAP
GMAP website: https://gmap.pucrs.br
Pontifical Catholic University of Rio Grande do Sul (PUCRS)
Av. Ipiranga, 6681, Porto Alegre - Brazil, 90619-900
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.
------------------------------------------------------------------------------
The original NPB 3.4.1 version was written in Fortran and belongs to:
http://www.nas.nasa.gov/Software/NPB/
------------------------------------------------------------------------------
The serial C++ version is a translation of the original NPB 3.4.1
Serial C++ version: https://github.com/GMAP/NPB-CPP/tree/master/NPB-SER
Authors of the C++ code:
Dalvan Griebler <[email protected]>
Gabriell Araujo <[email protected]>
Júnior Löff <[email protected]>
*/
#include <sys/types.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/syssgi.h>
#include <sys/immu.h>
#include <cerrno>
#include <cstdio>
/* the following works on SGI Power Challenge systems */
typedef unsigned long iotimer_t;
unsigned int cycleval;
volatile iotimer_t *iotimer_addr, base_counter;
double resolution;
/* address_t is an integer type big enough to hold an address */
typedef unsigned long address_t;
void timer_init(){
int fd;
char *virt_addr;
address_t phys_addr, page_offset, pagemask, pagebase_addr;
pagemask = getpagesize() - 1;
errno = 0;
phys_addr = syssgi(SGI_QUERY_CYCLECNTR, &cycleval);
if (errno != 0) {
perror("SGI_QUERY_CYCLECNTR");
exit(1);
}
/* rel_addr = page offset of physical address */
page_offset = phys_addr & pagemask;
pagebase_addr = phys_addr - page_offset;
fd = open("/dev/mmem", O_RDONLY);
virt_addr = mmap(0, pagemask, PROT_READ, MAP_PRIVATE, fd, pagebase_addr);
virt_addr = virt_addr + page_offset;
iotimer_addr = (iotimer_t *)virt_addr;
/* cycleval in picoseconds to this gives resolution in seconds */
resolution = 1.0e-12*cycleval;
base_counter = *iotimer_addr;
}
void wtime_(double *time){
static int initialized = 0;
volatile iotimer_t counter_value;
if(!initialized){
timer_init();
initialized = 1;
}
counter_value = *iotimer_addr - base_counter;
*time = (double)counter_value * resolution;
}
void wtime(double *time){
static int initialized = 0;
volatile iotimer_t counter_value;
if (!initialized) {
timer_init();
initialized = 1;
}
counter_value = *iotimer_addr - base_counter;
*time = (double)counter_value * resolution;
}
| [
"[email protected]"
] | |
697f02087eb479091b9fa02727d8b9817350d191 | 5cb2c472994004a84e6bb3efca09660584706e32 | /daily_problem/148_sort_list.cpp | 66d7361a473376cffada60b94648d31833459285 | [] | no_license | sysu18364114/LeetCode-Exercise | 221e41d181b6d6e482e7fb03968ae71328130f46 | 8b93c14362d25ce3785616238fbc0703bd50a588 | refs/heads/master | 2022-04-22T00:06:01.442530 | 2020-04-19T11:42:12 | 2020-04-19T11:42:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,575 | cpp |
// 2020/2/13 //
#include "0_linklist.h"
ListNode* merge1(ListNode* node1, ListNode* node2)
{
if(node1 == nullptr)
{
return node2;
}
if(node2 == nullptr)
{
return node1;
}
if(node1->val <= node2->val)
{
node1->next = merge1(node1->next, node2);
return node1;
}
else
{
node2->next = merge1(node2->next, node1);
return node2;
}
}
// ? recursion version
ListNode* sortList1(ListNode* head)
{
if(head == nullptr || head->next == nullptr)
{
return head;
}
ListNode* left = head;
ListNode* middle = head;
ListNode* right = head;
while(right != nullptr && right->next != nullptr)
{
middle = left;
left = left->next;
right = right->next->next;
}
middle->next = nullptr;
return merge1(sortList1(head), sortList1(left));
}
ListNode* cut(ListNode* head, int n)
{
ListNode* ptr = head;
// using "--n" to get the previous node of the new head of list
while(--n && ptr != nullptr)
{
ptr = ptr->next;
}
if(ptr == nullptr) // check "n" is longer than length of list
{
return nullptr;
}
ListNode* newHead = ptr->next; // temporary store
ptr->next = nullptr; // cut
return newHead;
}
ListNode* merge(ListNode* node1, ListNode* node2)
{
ListNode dummyHead(0);
ListNode* ptr = &dummyHead;
while(node1 != nullptr && node2 != nullptr) // merge two lists
{
// confirm the less one
if(node1->val <= node2->val)
{
ptr->next = node1;
ptr = node1;
node1 = node1->next;
}
else
{
ptr->next = node2;
ptr = node2;
node2 = node2->next;
}
}
ptr->next = (node1 != nullptr) ? node1 : node2; // link least part
return dummyHead.next;
}
ListNode* sortList(ListNode* head)
{
ListNode dummyHead(0);
dummyHead.next = head;
int length = getListLen(head); // get the length of list
for(int size = 1; size < length; size <<= 1) // confirm the length of sorting
{
ListNode* curr = dummyHead.next;
ListNode* tail = &dummyHead;
while(curr != nullptr)
{
ListNode* left = curr;
ListNode* right = cut(left, size);
curr = cut(right, size);
tail->next = merge(left, right);
while(tail->next != nullptr)
{
tail = tail->next;
}
}
}
return dummyHead.next;
} | [
"[email protected]"
] | |
24664d1472bb66135e94586c11e16d936ef2373a | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/curl/gumtree/curl_repos_function_6_curl-7.14.0.cpp | 951e8597d462f5ff0f7148e30faa69e1b63c8899 | [] | 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 | 627 | cpp | int main(int argc, char **argv)
{
pthread_t tid[4];
int i;
int error;
for(i=0; i< 4; i++) {
error = pthread_create(&tid[i],
NULL, /* default attributes please */
pull_one_url,
urls[i]);
if(0 != error)
fprintf(stderr, "Couldn't run thread number %d, errno %d\n", i, error);
else
fprintf(stderr, "Thread %d, gets %s\n", i, urls[i]);
}
/* now wait for all threads to terminate */
for(i=0; i< 4; i++) {
error = pthread_join(tid[i], NULL);
fprintf(stderr, "Thread %d terminated\n", i);
}
return 0;
} | [
"[email protected]"
] | |
3e99ea81332f9e85ecfa46bac402bac660f0d351 | 678ac658687122c5a8692be6ac4f923a9ebf5d11 | /src/KDScene.cpp | f6bff3c67efcab6f081ae08ab5824e39e2e209fb | [
"MIT"
] | permissive | vfro/kaleidoscope-game | dc987fd8e0d08eb031a2800620c8b5bed655b79c | 0875c96c74683e1ee8f80822b3e4a478ffcf3334 | refs/heads/master | 2021-01-19T13:53:19.771929 | 2015-03-16T22:15:10 | 2015-03-16T22:15:10 | 32,141,773 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,773 | cpp | #include "StdAfx.h"
#include <string>
#include <fstream>
#include <cassert>
#include <algorithm>
#include "KDScene.h"
#include "KDFormats.h"
template<typename TSavedType>
void KDSaveToFile/*<TSavedType>*/(std::ostream& os, const TSavedType& value)
{
const char* savedValue = reinterpret_cast<const char*>(&value);
os.write(savedValue, sizeof(TSavedType));
}
template<typename TLoadedType>
void KDLoadFromFile/*<TLoadedType>*/(std::istream& is, TLoadedType& value)
{
char* loadedValue = reinterpret_cast<char*>(&value);
is.read(loadedValue, sizeof(TLoadedType));
}
void KDSaveObjectList(std::ostream& os, aHexObjectList& hexList)
{
int border = -1;
KDSaveToFile(os, border);
int hexCount = hexList.size();
KDSaveToFile(os, hexCount);
for(aHexObjectList::iterator where = hexList.begin();
where != hexList.end();
++where
)
{
CPoint Pos = (*where)->GetPosition();
KDSaveToFile(os, Pos.x);
KDSaveToFile(os, Pos.y);
for (size_t colorNum = 0; colorNum < KDHexFormat::triAmount; ++colorNum)
{
int triColor = (*where)->GetColor(colorNum);
KDSaveToFile(os, triColor);
}
}
}
void KDLoadObjectList(std::istream& is,
aHexObjectList& hexList,
CDC& dcPattern,
KDHexFormat::aHexColorParam& colorPattern
)
{
int border = 0;
KDLoadFromFile(is, border);
assert(border == -1);
hexList.clear();
int hexCount = 0;
KDLoadFromFile(is, hexCount);
for(int i = 0; i < hexCount; ++i)
{
CPoint hexPos;
KDLoadFromFile(is, hexPos.x);
KDLoadFromFile(is, hexPos.y);
bool grayHexagone = true;
KDHexFormat::hexArray triColors;
for (size_t colorNum = 0; colorNum < KDHexFormat::triAmount; ++colorNum)
{
KDLoadFromFile(is, triColors[colorNum]);
if (triColors[colorNum] != 0)
grayHexagone = false;
}
if (grayHexagone)
{
aGrayHexagon* newHex = new aGrayHexagon(dcPattern, hexPos, colorPattern);
hexList.push_back(newHex);
}
else
{
aHexagon* newHex = new aHexagon(dcPattern, hexPos, colorPattern, triColors);
hexList.push_back(newHex);
}
}
}
aKDScene::aKDScene()
: sceneBitmap(0),
param(0),
moving(false),
sceneState(false),
backGround(0),
hexCount(0),
winState(false),
winStatus(false)
{
objectList.clear();
movableObjectList.clear();
rotateObjectList.clear();
hexInGridList.clear();
}
aKDScene::~aKDScene()
{
if (backGround != 0)
delete backGround;
DestroyObjects();
DeleteBitmap();
}
void aKDScene::SaveGame(std::ostream& os)
{
int gameType = param.GetColorsAmount() - KDFormats::minColors;
KDSaveToFile(os, gameType);
int scores = gamePlay.GetScore();
KDSaveToFile(os, scores);
int trashed = gamePlay.GetTrashed();
KDSaveToFile(os, trashed);
KDSaveToFile(os, hexCount);
int colorsArray = param.GetColorsArray();
KDSaveToFile(os, colorsArray);
KDSaveObjectList(os, rotateObjectList);
KDSaveObjectList(os, hexInGridList);
}
int aKDScene::GetColorSet() const
{
return param.GetColorsAmount() - KDFormats::minColors - 1;
}
void aKDScene::LoadGame(std::istream& is)
{
sceneState = true;
winState = true;
winStatus = false;
int gameType = 0;
KDLoadFromFile(is, gameType);
int scores = 0;
KDLoadFromFile(is, scores);
int trashed = 0;
KDLoadFromFile(is, trashed);
KDLoadFromFile(is, hexCount);
int colorArray = 0;
KDLoadFromFile(is, colorArray);
param.CustomizeColors(gameType + KDFormats::minColors, colorArray);
gamePlay.StartGame();
gamePlay.SetScore(scores);
gamePlay.SetTrashed(trashed);
aHexObjectList sceneObjects;
KDLoadObjectList(is, sceneObjects, sceneDevice, param);
objectList.clear();
movableObjectList.clear();
rotateObjectList.clear();
objectList.insert(objectList.begin(), sceneObjects.begin(), sceneObjects.end());
movableObjectList.insert(movableObjectList.begin(), sceneObjects.begin(), sceneObjects.end());
rotateObjectList.insert(rotateObjectList.begin(), sceneObjects.begin(), sceneObjects.end());
sceneObjects.clear();
KDLoadObjectList(is, sceneObjects, sceneDevice, param);
hexInGridList.clear();
objectList.insert(objectList.begin(), sceneObjects.begin(), sceneObjects.end());
hexInGridList.insert(hexInGridList.begin(), sceneObjects.begin(), sceneObjects.end());
if (hexCount == backGround->GridSize())
{
winState = false;
winStatus = true;
}
}
bool aKDScene::loadSave(CWnd* parrent)
{
bool gameLoaded = false;
char szFilters[]=
"Kaleidoscope Saves (*.kds)|*.kds|All Files (*.*)|*.*||";
char szExtention[] = "kds";
if (sceneState)
{
if (winState == false)
return false;
CFileDialog dlg(FALSE, szExtention, 0,
OFN_PATHMUSTEXIST | OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
szFilters, parrent
);
if (dlg.DoModal() != IDOK)
return false;
std::string fileName = dlg.GetPathName();
std::string errorString = std::string();
std::ofstream outFile(fileName.c_str(), std::ios::binary);
if (!outFile)
{
errorString = "Current game cannot be saved to file \"";
errorString += fileName;
errorString += "\" because file is not writable.";
}
else
{
try
{
SaveGame(outFile);
}
catch(std::exception& exp)
{
errorString = exp.what();
}
}
if (errorString != std::string())
{
::MessageBox(0, errorString.c_str(), "Kaleidoscope", MB_ICONWARNING | MB_OK | MB_TASKMODAL);
}
outFile.close();
}
else
{
CFileDialog dlg(TRUE, szExtention, 0,
OFN_FILEMUSTEXIST | OFN_HIDEREADONLY,
szFilters, parrent
);
if (dlg.DoModal() != IDOK)
return false;
std::string fileName = dlg.GetPathName();
std::string errorString = std::string();
std::ifstream inFile(fileName.c_str(), std::ios::binary);
if (!inFile)
{
errorString = "Game cannot be restored from file \"";
errorString += fileName;
errorString += "\" because file is not readable.";
}
else
{
try
{
LoadGame(inFile);
}
catch(std::exception& exp)
{
errorString = exp.what();
}
}
if (errorString != std::string())
{
::MessageBox(0, errorString.c_str(), "Kaleidoscope", MB_ICONWARNING | MB_OK | MB_TASKMODAL);
}
else
{
gameLoaded = true;
}
inFile.close();
}
return gameLoaded;
}
void aKDScene::SelectDC(CDC& dc)
{
CreateBitmap();
sceneDevice.CreateCompatibleDC(&dc);
sceneBitmap->CreateCompatibleBitmap( &dc ,
KDFormats::sceneWidth,
KDFormats::sceneHeight
);
sceneDevice.SelectObject(sceneBitmap);
if (backGround == 0)
backGround = new aKDBackGround(dc);
}
void aKDScene::Draw( CDC& dc)
{
CreateAppearance();
dc.BitBlt( KDFormats::sceneLeft, KDFormats::sceneTop,
KDFormats::sceneWidth, KDFormats::sceneHeight,
&sceneDevice, 0, 0, SRCCOPY);
}
void aKDScene::GenerateObjects()
{
DestroyObjects();
int i;
int delta = 48;
if (sceneState)
{
for (i = 0; i < 3; i++)
{
aHexagon* hex = new aHexagon(sceneDevice, CPoint(20 + i*delta, 340), param);
AddObject(hex);
AddMovableObject(hex);
AddRotateObject(hex);
}
}
}
void aKDScene::CreateAppearance()
{
// if (backGround != 0)
backGround->Draw(sceneDevice);
DrawObjects();
if (sceneState)
gamePlay.Draw(sceneDevice,param);
}
void aKDScene::CreateBitmap()
{
if (sceneBitmap != 0)
delete sceneBitmap;
sceneBitmap = new CBitmap;
}
void aKDScene::DeleteBitmap()
{
if (sceneBitmap != 0)
delete sceneBitmap;
sceneBitmap = 0;
}
void aKDScene::DestroyObjects()
{
for (aObjectList::const_iterator i = objectList.begin(); i != objectList.end(); i++)
delete *i;
objectList.clear();
movableObjectList.clear();
rotateObjectList.clear();
hexInGridList.clear();
}
void aKDScene::DrawObjects()
{
for (aObjectList::iterator i = objectList.begin(); i != objectList.end(); i++)
(*i)->Draw( sceneDevice );
}
void aKDScene::AddObject(aKDSceneObject* obj)
{
objectList.push_back(obj);
}
void aKDScene::AddMovableObject(aKDSceneObject* obj)
{
movableObjectList.push_back(obj);
}
void aKDScene::AddRotateObject(aHexagon* obj)
{
rotateObjectList.push_back(obj);
}
void aKDScene::OnMoveCursor(UINT /*nFlags*/, CPoint point)
{
CPoint moveTo;
if (!sceneState)
return;
if (!winState)
return;
if (moving)
{
moveTo = point - movingDelta;
if (moveTo.x < 0)
moveTo.x = 0;
if (moveTo.y < 0)
moveTo.y = 0;
if (moveTo.x > KDFormats::sceneWidth - moveObject->GetSize().cx)
moveTo.x = KDFormats::sceneWidth - moveObject->GetSize().cx;
if (moveTo.y > KDFormats::sceneHeight - moveObject->GetSize().cy)
moveTo.y = KDFormats::sceneHeight - moveObject->GetSize().cy;
moveObject->ReMove(moveTo);
}
}
void aKDScene::OnRightButtonDown(UINT /*nFlags*/, CPoint point)
{
if (!sceneState)
return;
if (!winState)
return;
aHexagon* obj = GetRotatedObject(point);
if (obj != 0)
obj->Rotate(true, param);
}
bool aKDScene::WinStatus(int& score)
{
score = 0;
if (sceneState)
score = gamePlay.GetScore();
return winStatus;
}
void aKDScene::OnLeftButtonUp(UINT /*nFlags*/, CPoint /*point*/)
{
int coincide;
if (!sceneState)
return;
if (!winState)
return;
if (!moving)
return;
moving = false;
CPoint newPlace =
backGround->GetPlace(KDFormats::aHexParam::getHexCenter(
moveObject->GetPosition(),KDFormats::gridHexSize));
aObjectList::iterator itObj;
if (newPlace == CPoint(-1, -1))
newPlace = oldPlace;
if ((oldPlace != newPlace) && (backGround->IsGrid(newPlace)))
{
moveObject->ReMove(newPlace);
coincide = moveObject->InteractWithGrid(hexInGridList, objectList);
if ( coincide == -1)
{
newPlace = oldPlace;
moveObject->ReMove(newPlace);
} else
{
hexCount++;
RemoveMoveableObject(moveObject);
RemoveRotateObject(moveObject);
gamePlay.AddHexagon(coincide, param);
if (hexCount == backGround->GridSize())
{
winState = false;
winStatus = true;
}
}
} else
if (oldPlace != newPlace)
for (aObjectList::iterator i = objectList.begin();
i != objectList.end(); i++)
if ((moveObject != (*i)) &&
(newPlace == (*i)->GetPosition()))
newPlace = oldPlace;
moveObject->ReMove(newPlace);
if (backGround->IsTrash(newPlace))
{
InTrash(moveObject);
gamePlay.InTrash(param);
if (gamePlay.GetScore() < 0)
{
winState = false;
}
}
if (newPlace == CPoint(-1, -1))
InTrash(moveObject);
if ((sceneState) &&
(newPlace != oldPlace) &&
(backGround->IsGet(oldPlace))
)
{
aHexagon* hex;
if (rand() % 100 < KDFormats::procentGray)
hex = new aGrayHexagon(sceneDevice, CPoint(oldPlace), param);
else
hex = new aHexagon(sceneDevice, CPoint(oldPlace), param);
AddObject(hex);
AddMovableObject(hex);
AddRotateObject(hex);
}
}
void aKDScene::OnLeftButtonDown(UINT /*nFlags*/, CPoint point)
{
aKDSceneObject* obj;
aObjectList::iterator i;
if (!sceneState)
return;
if (!winState)
return;
if (moving)
return;
obj = GetMovedObject(point);
if (obj == 0)
return;
moving = true;
moveObject = obj;
movingDelta.x = point.x - obj->GetPosition().x;
movingDelta.y = point.y - obj->GetPosition().y;
oldPlace = obj->GetPosition();
}
aKDSceneObject* aKDScene::GetMovedObject(CPoint pos)
{
CPoint objPos;
CSize objSize;
aKDSceneObject* obj;
aObjectList::iterator itObj;
aHexagon* objRotate;
aRotateObjectList::iterator itRotate;
for (aObjectList::iterator i = movableObjectList.begin();
i != movableObjectList.end(); i++
)
{
objPos = (*i)->GetPosition();
objSize = (*i)->GetSize();
if (((objPos.x < pos.x ) && (objPos.x + objSize.cx > pos.x)) &&
((objPos.y < pos.y ) && (objPos.y + objSize.cy > pos.y)))
{
obj = *i;
movableObjectList.erase(i);
movableObjectList.push_front(obj);
itObj = std::find(objectList.begin(), objectList.end(), obj);
if (*itObj == obj)
{
objectList.erase(itObj);
objectList.push_back(obj);
}
itRotate = std::find(rotateObjectList.begin(),
rotateObjectList.end(), obj);
if (dynamic_cast<aKDSceneObject*>(*itRotate) == obj)
{
objRotate = (*itRotate);
rotateObjectList.erase(itRotate);
rotateObjectList.push_front(objRotate);
}
return obj;
}
}
return 0;
}
aHexagon* aKDScene::GetRotatedObject(CPoint pos)
{
CPoint objPos;
CSize objSize;
for (aRotateObjectList::const_iterator i = rotateObjectList.begin();
i != rotateObjectList.end(); i++
)
{
objPos = (*i)->GetPosition();
objSize = (*i)->GetSize();
if (((objPos.x < pos.x ) && (objPos.x + objSize.cx > pos.x)) &&
((objPos.y < pos.y ) && (objPos.y + objSize.cy > pos.y)))
return *i;
}
return 0;
}
void aKDScene::StartGame(int colorSet)
{
sceneState = true;
winState = true;
winStatus = false;
hexCount = 0;
param.CustomizeColors(colorSet + KDFormats::minColors + 1);
GenerateObjects();
gamePlay.StartGame();
}
void aKDScene::StopGame()
{
sceneState = false;
winState = false;
winStatus = false;
moving = false;
hexCount = 0;
GenerateObjects();
gamePlay.StopGame();
}
void aKDScene::InTrash(aKDSceneObject* obj)
{
RemoveObject(obj);
delete obj;
}
void aKDScene::RemoveObject(aKDSceneObject* obj)
{
aObjectList::iterator itObj;
itObj = std::find(objectList.begin(),
objectList.end(),obj
);
if (itObj != objectList.end())
objectList.erase(itObj);
RemoveMoveableObject(obj);
RemoveRotateObject(obj);
}
void aKDScene::RemoveMoveableObject(aKDSceneObject* obj)
{
aObjectList::iterator itObj;
itObj = std::find(movableObjectList.begin(),
movableObjectList.end(),obj
);
if (itObj != movableObjectList.end())
movableObjectList.erase(itObj);
}
void aKDScene::RemoveRotateObject(aKDSceneObject* obj)
{
aRotateObjectList::iterator itRotate;
itRotate = std::find(rotateObjectList.begin(),
rotateObjectList.end(),obj
);
if (itRotate != rotateObjectList.end())
rotateObjectList.erase(itRotate);
}
aHexagon* aKDScene::findObj(const CPoint& point)
{
for (aHexObjectList::iterator i = hexInGridList.begin();
i != hexInGridList.end(); i++
)
{
if ( (*i)->GetPosition() == point)
return (*i);
}
return 0;
}
| [
"[email protected]"
] | |
92d8d31c715a1a5b0eca5edffb0af066e53a6a51 | aa13e1d93b7a8017e1e610a900bd05f6df91604f | /spoj/classicals/archive/ARRAYSUB.cpp | 1c74305bf1e927288c397f6e43a52e18d0361cd7 | [] | no_license | laveesingh/Competitive-Programming | 3ce3272eab525635f9ce400f7467ee09de8b51df | 41047f47c23bc8572a1891e891a03cc3f751e588 | refs/heads/master | 2021-01-24T09:51:00.332543 | 2017-10-30T17:11:48 | 2017-10-30T17:11:48 | 52,956,650 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 470 | cpp | #include <iostream>
#include <set>
#include <algorithm>
using namespace std;
int main(void){
int n;
cin >> n;
int a[n];
for (int i = 0; i < n; i += 1){
cin >> a[i];
}
int k;
cin >> k;
multiset<int> myset(a,a+k);
cout << *myset.rbegin();
multiset<int>::iterator it1, it2;
for(int i = 0; i < n-k; i += 1){
it1 = myset.find(a[i]);
it2 = it1;
it2++;
myset.erase(it1,it2);
myset.insert(a[i+k]);
cout << " " << *myset.rbegin() ;
}
cout << endl;
} | [
"[email protected]"
] | |
314cc1cad2c1c17f310719ba12d468775d211747 | 46c8ea9088dd6161476a00df34e36b625b74c08d | /CGA/SceneView.h | b6820c0cf50a3390a7556e749b9852428ffdf547 | [] | no_license | HIqueRS/CGA | ddc06e2979e7e93212af6a79f486fb5197dbbbda | 2a010d848a36f0677387a146ab7ef2586150c7ce | refs/heads/master | 2022-06-15T21:16:11.137335 | 2020-05-06T18:02:19 | 2020-05-06T18:02:19 | 255,915,203 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 60 | h | #pragma once
class SceneView
{
public:
void execute();
};
| [
"[email protected]"
] | |
1d5c9d58115be5404bdcd5662b32427e7b324f05 | e93b39df60b5a1fb15743be50cc42f0948bc0540 | /com267/PA5/pqueue1.h | f6c9ee3776078b6ae906677840739a1a1adddc1e | [] | no_license | zek/okul | 39b1ed12dde992144b1270b6cbe7d0b050039080 | 866f208670d95046f77ee75084dfc2e908fde5fc | refs/heads/master | 2021-01-11T08:16:17.577269 | 2019-03-26T17:50:51 | 2019-03-26T17:50:51 | 76,625,469 | 6 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,743 | h | // FILE: pqueue1.h
// CLASS PROVIDED: PriorityQueue (a priority queue of items)
//
// TYPEDEF for the PriorityQueue class:
// typedef _____ Item
// The type Item is the data type of the items in the Priority Queue.
// It may be any of the C++ built-in types (int, char, etc.), or a class
// with a default constructor, a copy constructor, and assignment operator.
//
// CONSTRUCTOR for the PriorityQueue class:
// PriorityQueue( )
// Postcondition: The PriorityQueue has been initialized with no Items.
//
// MODIFICATION MEMBER FUNCTIONS for the PriorityQueue class:
// void insert(const Item& entry, unsigned int priority)
// Postcondition: A new copy of entry has been inserted with the specified
// priority.
//
// Item get_front( )
// Precondition: size( ) > 0.
// Postcondition: The highest priority item has been returned and has been
// removed from the PriorityQueue. (If several items have equal priority,
// then the one that entered first will come out first.)
//
// CONSTANT MEMBER FUNCTIONS for the PriorityQueue class:
// size_t size( ) const
// Postcondition: Return value is the total number of items in the
// PriorityQueue.
//
// bool is_empty( ) const
// Postcondition: Return value is true if the PriorityQueue is empty.
//
// VALUE SEMANTICS for the PriorityQueue class:
// Assignments and the copy constructor may be used with
// PriorityQueue objects
#ifndef PQUEUE_H
#define PQUEUE_H
#include <stdlib.h> // Provides size_t
struct Node; // This will be completely defined below.
class PriorityQueue
{
public:
typedef int Item;
PriorityQueue( );
PriorityQueue(const PriorityQueue& source);
~PriorityQueue( );
void operator =(const PriorityQueue& source);
size_t size( ) const;
void insert(const Item& entry, unsigned int priority);
Item get_front( );
bool is_empty( ) const;
// student must list all the prototypes here including
// the copy constructor, assignment operator, and destructor
private:
// Note: head_ptr is the head pointer for a linked list that
// contains the items along with their priorities. These nodes are
// kept in order from highest priority (at the head of the list)
// to lowest priority (at the tail of the list). The private member
// variable, many_nodes, indicates how many nodes are on the list.
// The data type Node is completely defined below.
Node *head_ptr;
size_t many_nodes;
};
struct Node
{ // Node for a linked list
PriorityQueue::Item data;
unsigned int priority;
Node *link;
};
#endif | [
"[email protected]"
] | |
249fb8d491315dd03204aeac9a0cbbfa67cb562d | 4cb346998f62a0c754c84a4a6a09211dedadd760 | /sw_academy/D4_6-1251-ref.cpp | 2e4e70f45561186a320877e9685cc7198c531443 | [] | no_license | Ohrotan/algorithms | 39b81baa56def295b5bf1700dd1fe44ed51fc567 | 3daefba8db463c6a62172f17e6a604234ff342cd | refs/heads/master | 2023-02-07T21:08:47.459390 | 2020-12-22T09:04:59 | 2020-12-22T09:04:59 | 283,636,906 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,801 | cpp | #define _CRT_SECURE_NO_WARNINGS
#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
typedef long long ll;
const int INF = 987654321;
struct Edge {
ll s, e, c;
const bool operator< (const Edge& rhs) const {
return c < rhs.c;
}
};
int N;
double E;
ll x[1000], y[1000], p[1000];
//bool visit[1000];
vector<Edge> edge;
inline ll dist(ll x1, ll y1, ll x2, ll y2) {
return ((x1 - x2) * (x1 - x2)) + ((y1 - y2) * (y1 - y2));
}
inline ll Find(ll x) {
return x == p[x] ? x : p[x] = Find(p[x]);
}
inline void Union(ll x, ll y) {
x = Find(x);
y = Find(y);
if (x < y)
p[y] = x;
else
p[x] = y;
}
int main() {
freopen("input.txt", "r", stdin);
int tc; scanf("%d", &tc);
for (int t = 1; t <= tc; ++t) {
//memset(visit, false, sizeof(visit));
scanf("%d", &N);
for (int i = 0; i < N; ++i) {
scanf("%lld", &x[i]);
p[i] = i;
}
for (int i = 0; i < N; ++i) {
scanf("%lld", &y[i]);
}
scanf("%lf", &E);
edge.clear();
for (int i = 0; i < N - 1; ++i) {
for (int j = i + 1; j < N; ++j) {
//if ((i == j) || visit[j])
//continue;
edge.push_back({ i,j,dist(x[i],y[i],x[j],y[j]) });
}
//visit[i] = true;
}
sort(edge.begin(), edge.end());
ll ans = 0;
for (int i = 0; i < (int)edge.size(); ++i) {
Edge e = edge[i];
ll start = Find(e.s);
ll end = Find(e.e);
if (start != end) {
Union(start, end);
ans += e.c;
}
}
printf("#%d %.0f\n", t, ans * E);
}
return 0;
} | [
"[email protected]"
] | |
971555556a3a2b76bdd956cdefc9367b8ccc1e4c | 268c3ec74b3fa5139191c373cea3cebdd04a2dfa | /8. String to Integer (atoi).cpp | c5cb2af659af6b9bd54f85b805bc8c75cc56731a | [] | no_license | zslomo/leetcode | 0dd8f3437b9900763dd0add37623a6e5bd9ad878 | 5ad09a331126db97fbe57adb63d93dfdcb729847 | refs/heads/master | 2021-01-10T01:49:26.398856 | 2016-10-27T14:50:55 | 2016-10-27T14:50:55 | 50,284,580 | 12 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 891 | cpp | //#include"Inc.h"
//class Solution {
//public:
// int myAtoi(string str) {
// if (str.empty()) return 0;
// bool IsPos = true;
// int i = 0;
// int count = 0;
// long ans = 0;
// while (str[i] == ' ') i++;
// if (str[i] > '9' || str[i] < '0') {
// if (str[i] == '+') IsPos = true;
// else if (str[i] == '-') IsPos = false;
// else return 0;
// }
// else ans = str[i] - 48;
// for (i++; i < str.size(); i++) {
// count++;
// if (count<12) {
// if (str[i] > '9' || str[i] < '0') {
// break;
// }
// else {
// ans = ans * 10 + str[i] - 48;
// }
// }
// else {
// if (IsPos) return 2147483647;
// else return -2147483648;
// }
// }
// if (IsPos) {
// if (ans < 2147483647) return ans;
// else return 2147483647;
// }
// else {
// ans = 0 - ans;
// if (ans > -2147483648) return ans;
// else return -2147483648;
// }
//
// }
//}; | [
"[email protected]"
] | |
08fbabb019be2f5cc6a2f16849634da48c4ef696 | 16ad74d73b9090626c8db72dbd13d841942a64c0 | /common/GA.h | 7ef5f859f7019579459d36ef9e065f8aba546975 | [] | no_license | FudanYuan/CADPRO | 65b18cd5f5f1a9237078b994acf35b45ead5be7f | e89678fd19bb146751d555c9ddefb5ab9a8f5452 | refs/heads/master | 2021-09-22T11:14:44.645028 | 2018-09-09T04:23:28 | 2018-09-09T04:23:28 | 119,213,918 | 4 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 4,323 | h | #ifndef GA_H
#define GA_H
#include <qmath.h>
#include <QVector>
#include "debug.h"
// 基因组类
class Genome
{
public:
friend class GA;
Genome();
Genome(QVector<double> vec, double f=0);
void setGenome(QVector<double> g);
QVector<double> getGenome();
QVector<double> getGenome(int start, int end);
void setFitness(double f);
double getFitness();
void swap(int index1, int index2);
bool isNull();
friend Q_DECL_CONSTEXPR inline bool operator==(const Genome &, const Genome &);
friend Q_DECL_CONSTEXPR inline bool operator==(const Genome &, const Genome &);
friend Q_DECL_CONSTEXPR inline bool operator!=(const Genome &, const Genome &);
friend Q_DECL_CONSTEXPR inline bool operator>(const Genome &, const Genome &);
friend Q_DECL_CONSTEXPR inline bool operator<(const Genome &, const Genome &);
private:
QVector<double> genome; // 基因组向量
double fitness; // 适应度评分
};
/*****************************************************************************
Genome inline functions
*****************************************************************************/
Q_DECL_CONSTEXPR inline bool operator==(const Genome &g1, const Genome &g2){
return g1.fitness == g2.fitness;
}
Q_DECL_CONSTEXPR inline bool operator!=(const Genome &g1, const Genome &g2){
return g1.fitness != g2.fitness;
}
Q_DECL_CONSTEXPR inline bool operator>(const Genome &g1, const Genome &g2){
return g1.fitness > g2.fitness;
}
Q_DECL_CONSTEXPR inline bool operator<(const Genome &g1, const Genome &g2){
return g1.fitness < g2.fitness;
}
// 遗传算法
class GA
{
public:
explicit GA(int size, int gLenght, int cf, double distance,
double p, double (*fitnessFunc)(Genome &genemo),
double score=0.95,
double cRate=0.7, double mRate=0.05);
~GA();
void initPopulation(); // 初始化种群
void evaluateFitness(); // 评估适应度
void sortPopulation(QVector<Genome> &vector); // 将原始种群降序排列
void calculateHammingDistance(QVector<Genome> &vector); // 计算海明距离
Genome selection(); // 选择,物竞天择(轮盘赌)
Genome crossover(Genome parent1, Genome parent2); // 交叉
Genome mutationLocation(Genome genome); // 位置变异
Genome mutationRotate(Genome genome); // 旋转变异
Genome getNewChild(); // 产生新后代
void getNewGeneration(); // 产生最新一代
Genome getFittestGenome(); // 获取最优个体
bool isStop(); // 获取停止位标识
template<typename T>
static T randT(T lower, T upper); //产生任意类型随机数函数
private:
double (*calculateFitness)(Genome &genemo); // 适应度计算函数
QVector<Genome> population; // 种群集合
QVector<Genome> memoryPop; // 记忆种群集合
int popSize; // 人口(种群)数量
int genLength; // 每一条染色体的基因的总数目
int CF; // 排挤因子
double similarity; // 相似距离
double punish; // 惩罚因子
double fitnessMax; // 最优值阈值
double crossoverRate; // 基因交叉的概率一般设为0.7
double crossoverOneRate; // 基因单点交叉的概率
double crossoverTwoRate; // 基因双点交叉的概率
double mutationRate; // 旋转变异概率
double mutationRotateRate; // 旋转变异概率
double mutationLocationRate; // 位置变异概率
Genome fittestGenome; // 最适应的个体在m_vecPop容器里面的索引号
double totalFitness; // 所有个体对应的适应性评分的总和
double bestFitness; // 在所有个体当中最适应的个体的适应性评分
double worstFitness; // 在所有个体当中最不适应的个体的适应性评分
double averageFitness; // 所有个体的适应性评分的平均值
int generation; // 代数的记数器
int crossoverCount; // 交叉计数器
int crossoverOneCount; // 单点交叉计数器
int crossoverTwoCount; // 双点交叉计数器
int mutationCount; // 变异计数器
int mutationLocationCount; // 位置变异计数器
int mutationRotateCount; // 旋转变异计数器
bool stop; // 终止标识
int seed; // 随机值种子
};
#endif // !GA_H
| [
"[email protected]"
] | |
7d86d63a90b1b276c9f5fdac8650af1d3fa269ee | f3d12ae1cf653c88fa949e921d47c915ded0936a | /NetworkLib/NetworkClient.cpp | ece5716c01e792cc3273697cb9819ecebf154a96 | [] | no_license | minhoolee/Networking | fb3ddd7e26ffa4d8f34fa3107e060343c3cb0bb3 | d07e0ed33fb0772133635439d5aea281bd7937a0 | refs/heads/master | 2021-03-19T14:55:02.174686 | 2015-09-13T05:23:36 | 2015-09-13T05:23:39 | 42,384,798 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,622 | cpp | #include "NetworkClient.h"
#include "Log.h"
namespace NetworkLib {
NetworkClient::NetworkClient(std::string host, std::string server_port, unsigned short local_port) :
socket(io_service, udp::endpoint(udp::v4(), local_port)),
service_thread(&NetworkClient::run_service, this)
{
udp::resolver resolver(io_service);
udp::resolver::query query(udp::v4(), host, server_port);
server_endpoint = *resolver.resolve(query);
Send("");
}
NetworkClient::~NetworkClient()
{
io_service.stop();
service_thread.join();
}
void NetworkClient::start_receive()
{
socket.async_receive_from(asio::buffer(recv_buffer), remote_endpoint,
[this](std::error_code ec, std::size_t bytes_recvd){ this->handle_receive(ec, bytes_recvd); });
}
void NetworkClient::handle_receive(const std::error_code& error, std::size_t bytes_transferred)
{
if (!error)
{
std::string message(recv_buffer.data(), recv_buffer.data() + bytes_transferred);
incomingMessages.push(message);
statistics.RegisterReceivedMessage(bytes_transferred);
}
else
{
Log::Error("NetworkClient::handle_receive:", error);
}
start_receive();
}
void NetworkClient::Send(std::string message)
{
socket.send_to(asio::buffer(message), server_endpoint);
statistics.RegisterSentMessage(message.size());
}
void NetworkClient::run_service()
{
start_receive();
while (!io_service.stopped()) {
try {
io_service.run();
}
catch (const std::exception& e) {
Log::Warning("Client: network exception: ", e.what());
}
catch (...) {
Log::Error("Unknown exception in client network thread");
}
}
}
} | [
"[email protected]"
] | |
fe5d92fa65852a7d37bd489be426729c9703d73a | 0fe70f4d4e959a4b7f530a82a27618167aa0130d | /TPV2/components/ShowAtOppositeSide.h | 7d955da89fcf397436b85a226d81ea0cb3210329 | [] | no_license | IvanPradoEchegaray/TPV2Practica | e0ae1bfd0242a157db51032f0c2bf0a101600231 | ab3dd63f670799e04a6c3ed354a0b62096969561 | refs/heads/main | 2023-05-05T08:13:16.985059 | 2021-05-30T15:33:39 | 2021-05-30T15:33:39 | 345,721,172 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 740 | h | // This file is part of the course TPV2@UCM - Samir Genaim
#pragma once
#include "../ecs/Component.h"
#include "../ecs/Entity.h"
#include "Transform.h"
#include "../sdlutils/SDLUtils.h"
class ShowAtOppositeSide : public Component {
public:
ShowAtOppositeSide(Transform* tr) :
tr_(tr) {
}
virtual ~ShowAtOppositeSide() {
}
void update() {
auto& pos = tr_->getPos();
auto w = tr_->getW();
auto h = tr_->getH();
if (pos.getX() < 0) {
pos.setX(sdlutils().width() - w);
}
else if (pos.getX() + w > sdlutils().width()) {
pos.setX(0.0);
}
if (pos.getY() < 0) {
pos.setY(sdlutils().height() - h);
}
else if (pos.getY() + h > sdlutils().height()) {
pos.setY(0.0);
}
}
private:
Transform* tr_;
};
| [
"[email protected]"
] | |
e0e9e0af91a49ddef865739ce53cb4ac8b5d8f87 | 3c4f9342362d7122434687bae06828c63f51970d | /Homework04/main.cpp | 45adc60679c7e03ff3f5b36778addbb9d581268f | [] | no_license | tterrag1098/COSC482 | 379c22abaf7d7f0ee5fd6bbf780eed89a2e46797 | c48ee732123d33c9f53ed7243d20aec1200f8e83 | refs/heads/master | 2021-01-21T13:04:06.548261 | 2016-05-17T03:57:03 | 2016-05-17T03:57:03 | 51,627,743 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,026 | cpp | #include <GL/glew.h>
#include <SFML/Graphics.hpp>
#include <SFML/OpenGL.hpp>
#include <SFML/System.hpp>
#include <iostream>
#include <string>
#include "GraphicsEngine.h"
#include "UI.h"
/**
\mainpage Homework 04
\tableofcontents
\section intro Introduction
This program allows the user to create and remove boxes on the screen, as well as manipulate them using the mouse and keyboard.
\author Don Spickler,
\version 1.2
\date Written: 1/9/2016 <BR> Revised: 2/26/2016
\section usage Usage
\subsection run Running the Program
- The program can be run through explorer by double-clicking the executable name.
\subsection options User Options
If no modifier keys are pressed:
- Right Click: Adds a new box at the cursor position
- Left Click and Drag: Grabs all boxes under the cursor and drags them.
- C: Clears the boxes from the screen.
- P: Toggles secret mode.
- Escape: Ends the program.
- M: Toggles between fill mode and line mode to draw the triangles.
- R: Resets the window size to 700 X 500.
- A: Resets the window size to 600 X 600.
- F9: Saves a screen shot of the graphics window to a png file.
- F10: Saves a screen shot of the graphics window to a jpeg file.
- Left: Moves the boxes to the left.
- Right: Moves the boxes to the right.
- Up: Moves the boxes up.
- Down: Moves the boxes down.
If the control key is down:
- Right Click: Deletes any boxes underneath the cursor.
\section output Output
The console window will display your graphics card OpenGL version support and the
graphics window will display a blank screen. The title bar of the window will also
display the number of frames per second for the last second. Upon right clicking, a
new box is created at the cursor position. The user can click and drag any box on
the screen around. The arrow keys will move all boxes at once.
---
\copyright
GNU Public License.
This software is provided as-is, without warranty of ANY KIND, either expressed or implied,
including but not limited to the implied warranties of merchant ability and/or fitness for a
particular purpose. The authors shall NOT be held liable for ANY damage to you, your computer,
or to anyone or anything else, that may result from its use, or misuse.
All trademarks and other registered names contained in this package are the property
of their respective owners. USE OF THIS SOFTWARE INDICATES THAT YOU AGREE TO THE ABOVE CONDITIONS.
*/
/**
\file main.cpp
\brief Main driver for the program.
This is the main program driver that sets up the graphics engine, the user interface
class, and links the two.
\author Don Spickler,
\version 1.2
\date Written: 1/9/2016 <BR> Revised: 2/26/2016
*/
/**
\brief The Main function, program entry point.
\return Standard EXIT_SUCCESS return on successful run.
This is the main function, responsible for initializing GLEW and setting up
the SFML interface for OpenGL.
*/
int main()
{
std::string progName = "Homework #4";
GraphicsEngine ge(progName, 700, 500);
UI ui(&ge);
long framecount = 0;
// Display OpenGL version. Not needed in general, just a check.
std::cout << "OpenGL Version: " << glGetString(GL_VERSION) << std::endl;
sf::Clock clock;
sf::Time time = clock.restart();
// Start the Game/GUI loop
while (ge.isOpen())
{
// Process any events.
ui.processEvents();
// Call the display function to do the OpenGL rendering.
ge.display();
// Increment frame counts
framecount++;
// Get Elapsed Time
float timesec = clock.getElapsedTime().asSeconds();
char titlebar[128];
// If another second has elapsed, display the FPS and total FPS.
if (timesec > 1.0)
{
float fps = framecount / timesec;
sprintf(titlebar, "%s FPS: %.2f", progName.c_str(), fps);
ge.setTitle(titlebar);
time = clock.restart();
framecount = 0;
}
}
return EXIT_SUCCESS;
}
| [
"[email protected]"
] | |
e65de8a534d4096994144e3416a1c792ae83388d | c2239a4e2f88d072021113fe355c02eedefe9110 | /public/ToolZ/OMTopology.h | da709dd41c359bd2e63c09f12d0b02305173307d | [] | no_license | mzoll/ToolZ | d581258655c61a5958ed25004ee1d4b15cabd28c | 6f8dcaf439db172ad8c5248f71d644ffbe9566c7 | refs/heads/master | 2020-03-29T16:18:13.566897 | 2018-09-24T13:41:50 | 2018-09-24T13:41:50 | 150,108,017 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,941 | h | /**
* \file OMTopology.h
*
* (c) 2012 the IceCube Collaboration
*
* $Id: OMTopology.h 129966 2015-03-07 20:57:35Z mzoll $
* \version $Revision: 129966 $
* \date $Date: 2015-03-07 21:57:35 +0100 (lör, 07 mar 2015) $
* \author mzoll <[email protected]>
*
* Describes the different topological settings for a DOM in which it can possibly end up in
*/
#ifndef OMTOPOLOGY_H
#define OMTOPOLOGY_H
#include <cstdlib>
#include <set>
#include <vector>
#include <map>
#include "icetray/I3FrameObject.h"
#include "icetray/OMKey.h"
#include "dataclasses/I3Map.h"
//serialization
#include "icetray/serialization.h" //NOTE I3FrameObjects and derivatives will always have to use icetray/serialization
#include "ToolZ/__SERIALIZATION.h"
static const unsigned omtopology_version_ = 0;
///List of all available flags
/// NOTE might be expanded, but NEVER shortened or reshuffled without breaking old code
static const char* _flags_init[] = {
//general positions
"IceTop",
"InIce",
//DOM topologies
"IceCube",
"DeepCore",
"Gen2",
"Pingu",
//analysis defined
"DeepCoreFidutial", //bottom part of DeepCore + DOMs on surrounding IC strings
"DeepCoreCap" //top part of DeepCore (VetoCap) + DOMs on surrounding IC strings
};
/** Define OMTopologies, which can be found in the detector
* NOTE if you consider adding more flags, append them to the list
*/
class OMTopology : public I3FrameObject {
#if SERIALIZATION_ENABLED
friend class SERIALIZATION_NS::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int version);
#endif //SERIALIZATION_ENABLED
private:
///holds the flag string definitions
static const std::vector<std::string> flags_;
///is the bitmap to the set flags
int flag_holder_;
public: //constructor
///constructor
OMTopology();
///constructor full initialized
template <class InputIterator>
OMTopology(InputIterator first, InputIterator last);
OMTopology(const std::vector<std::string>& flags);
OMTopology(const std::list<std::string>& flags);
OMTopology(const std::set<std::string>& flags);
public: //methods
///in the comparision of two OMTopologies, do they have common flags?
bool Common(const OMTopology& o) const;
//is the Flag set?
bool GetFlag(const std::string& flag) const;
// set the Flag to a value (default=true)
void SetFlag(const std::string& flag, const bool val=true);
// get all flags that are set by name
std::list<std::string> GetFlags() const;
};
I3_POINTER_TYPEDEFS(OMTopology);
#if SERIALIZATION_ENABLED
SERIALIZATION_CLASS_VERSION(OMTopology, omtopology_version_);
#endif //SERIALIZATION_ENABLED
std::ostream& operator<< (std::ostream& oss, const OMTopology& omt);
typedef I3Map<OMKey, OMTopology> OMTopologyMap;
I3_POINTER_TYPEDEFS(OMTopologyMap);
#if SERIALIZATION_ENABLED
SERIALIZATION_CLASS_VERSION(OMTopologyMap, omtopology_version_);
#endif //SERIALIZATION_ENABLED
/**
* Facilitates comparision of OMTopology types on a OMTopologyMap
* aka. tells if a DOM in a detector configuration is of ANY of the specified types
*/
class OMTopologyMap_Comparator{
private: //properties
///holds the Flags that should be compared
const OMTopology omtopoflags_;
///holds the OMTopologyMap
const OMTopologyMap omtopomap_;
public: //methods
///constructor
OMTopologyMap_Comparator(
const OMTopology& omt,
const OMTopologyMap& omtmap);
///comparision of this OMKey if it has the specified flags
bool operator() (const OMKey& omkey) const;
///returns a list of all OMKeys that have ANY of the specified flags
std::list<OMKey> AllCommon() const;
};
typedef boost::shared_ptr<OMTopologyMap_Comparator> OMTopologyMap_ComparatorPtr;
typedef boost::shared_ptr<const OMTopologyMap_Comparator> OMTopologyMap_ComparatorConstPtr;
///==============================================================
///=================== IMPLEMENTATION ===========================
///==============================================================
//============== CLASS OMTopology =================
#if SERIALIZATION_ENABLED
template<class Archive>
void OMTopology::serialize(Archive & ar, const unsigned int version){
ar & SERIALIZATION_BASE_OBJECT_NVP(I3FrameObject);
ar & SERIALIZATION_NS::make_nvp("flag_holder", flag_holder_);
};
#endif //SERIALIZATION_ENABLED
template <class InputIterator>
OMTopology::OMTopology(InputIterator first, InputIterator last)
{
while (first!=last) {
const std::string& flag_name = *first;
size_t pos=0;
while(pos< flags_.size()) {
if (flags_.at(pos)==flag_name) {
const int flag_pos = 1<<pos;
flag_holder_ |= flag_pos;
break;
}
pos++;
}
if (pos== flags_.size())
log_error_stream("Unknown flag name : "<<flag_name);
first++;
}
};
inline
bool OMTopology::Common(const OMTopology& o) const {
return (bool)(flag_holder_ & o.flag_holder_);
};
#endif //OMTOPOLOGY_H
| [
"[email protected]"
] | |
fcff05ff58efa0cb85bcc63d6d7a271974e87458 | a558ba3bf296feb61820564aa94844f45636f279 | /factor.cpp | 6f92d9f2f414f81ecea6f265d2529e4cf4ad9f5a | [
"MIT"
] | permissive | SofiaSL/ord23 | 06384476633bc3651af1063ddb9b74f30db7ef4a | 6af53d03bbf12a879f8de4b817c1e3a43b3544a6 | refs/heads/main | 2023-06-30T14:17:26.679029 | 2021-08-03T23:55:11 | 2021-08-03T23:55:11 | 366,446,681 | 1 | 2 | MIT | 2021-05-26T21:52:58 | 2021-05-11T16:24:15 | C++ | UTF-8 | C++ | false | false | 43,202 | cpp | /* factor -- print prime factors of n.
Copyright (C) 1986-2020 Free Software Foundation, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>. */
/* Originally written by Paul Rubin <[email protected]>.
Adapted for GNU, fixed to factor UINT_MAX by Jim Meyering.
Arbitrary-precision code adapted by James Youngman from Torbjörn
Granlund's factorize.c, from GNU MP version 4.2.2.
In 2012, the core was rewritten by Torbjörn Granlund and Niels Möller.
Contains code from GNU MP. */
/* Efficiently factor numbers that fit in one or two words (word = uintmax_t),
or, with GMP, numbers of any size.
Code organisation:
The factoring code for two words will fall into the code for one word when
progress allows that.
Using GMP is optional. Define HAVE_GMP to make this code include GMP
factoring code. The GMP factoring code is based on GMP's demos/factorize.c
(last synced 2012-09-07). The GMP-based factoring code will stay in GMP
factoring code even if numbers get small enough for using the two-word
code.
Algorithm:
(1) Perform trial division using a small primes table, but without hardware
division since the primes table store inverses modulo the word base.
(The GMP variant of this code doesn't make use of the precomputed
inverses, but instead relies on GMP for fast divisibility testing.)
(2) Check the nature of any non-factored part using Miller-Rabin for
detecting composites, and Lucas for detecting primes.
(3) Factor any remaining composite part using the Pollard-Brent rho
algorithm or if USE_SQUFOF is defined to 1, try that first.
Status of found factors are checked again using Miller-Rabin and Lucas.
We prefer using Hensel norm in the divisions, not the more familiar
Euclidian norm, since the former leads to much faster code. In the
Pollard-Brent rho code and the prime testing code, we use Montgomery's
trick of multiplying all n-residues by the word base, allowing cheap Hensel
reductions mod n.
Improvements:
* Use modular inverses also for exact division in the Lucas code, and
elsewhere. A problem is to locate the inverses not from an index, but
from a prime. We might instead compute the inverse on-the-fly.
* Tune trial division table size (not forgetting that this is a standalone
program where the table will be read from disk for each invocation).
* Implement less naive powm, using k-ary exponentiation for k = 3 or
perhaps k = 4.
* Try to speed trial division code for single uint64_t numbers, i.e., the
code using DIVBLOCK. It currently runs at 2 cycles per prime (Intel SBR,
IBR), 3 cycles per prime (AMD Stars) and 5 cycles per prime (AMD BD) when
using gcc 4.6 and 4.7. Some software pipelining should help; 1, 2, and 4
respectively cycles ought to be possible.
* The redcify function could be vastly improved by using (plain Euclidian)
pre-inversion (such as GMP's invert_limb) and udiv_qrnnd_preinv (from
GMP's gmp-impl.h). The redcify2 function could be vastly improved using
similar methoods. These functions currently dominate run time when using
the -w option.
*/
/* Whether to recursively factor to prove primality,
or run faster probabilistic tests. */
#ifndef PROVE_PRIMALITY
# define PROVE_PRIMALITY 1
#endif
#ifdef __GNUC__
# define LIKELY(cond) __builtin_expect ((cond), 1)
# define UNLIKELY(cond) __builtin_expect ((cond), 0)
#else
# define LIKELY(cond) (cond)
# define UNLIKELY(cond) (cond)
#endif
#include "utils.h"
#include <getopt.h>
#include <stdio.h>
#include <assert.h>
#include "error.h"
/* The official name of this program (e.g., no 'g' prefix). */
#define PROGRAM_NAME "factor"
#define AUTHORS \
proper_name ("Paul Rubin"), \
proper_name_utf8 ("Torbjorn Granlund", "Torbj\303\266rn Granlund"), \
proper_name_utf8 ("Niels Moller", "Niels M\303\266ller")
/* Token delimiters when reading from a file. */
#define DELIM "\n\t "
#define USE_LONGLONG_H 1
template <typename T>
void lbuf_putc(T a)
{
std::cout << a;
}
/* Make definitions for longlong.h to make it do what it can do for us */
/* bitcount for uint64_t */
#define W_TYPE_SIZE 64
# define UWtype uintmax_t
# undef UDWtype
# if HAVE_ATTRIBUTE_MODE
typedef unsigned int UQItype __attribute__ ((mode (QI)));
typedef int SItype __attribute__ ((mode (SI)));
typedef unsigned int USItype __attribute__ ((mode (SI)));
typedef int DItype __attribute__ ((mode (DI)));
typedef unsigned int UDItype __attribute__ ((mode (DI)));
# else
typedef unsigned char UQItype;
typedef long SItype;
typedef unsigned long int USItype;
# if HAVE_LONG_LONG_INT
typedef long long int DItype;
typedef unsigned long long int UDItype;
# else /* Assume `long' gives us a wide enough type. Needed for hppa2.0w. */
typedef long int DItype;
typedef unsigned long int UDItype;
# endif
# endif
# define LONGLONG_STANDALONE /* Don't require GMP's longlong.h mdep files */
# ifndef __GMP_GNUC_PREREQ
# define __GMP_GNUC_PREREQ(a,b) 1
# endif
# include "longlong.h"
# ifdef COUNT_LEADING_ZEROS_NEED_CLZ_TAB
const unsigned char factor_clz_tab[129] =
{
1,2,3,3,4,4,4,4,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
9
};
# endif
/* 2*3*5*7*11...*101 is 128 bits, and has 26 prime factors */
#define MAX_NFACTS 26
//static void factor (uintmax_t, uintmax_t, struct factors *);
void factor (std::uint64_t t0, struct factors *factors);
#ifndef umul_ppmm
# define umul_ppmm(w1, w0, u, v) \
do { \
uint64_t __x0, __x1, __x2, __x3; \
unsigned long int __ul, __vl, __uh, __vh; \
uint64_t __u = (u), __v = (v); \
\
__ul = __ll_lowpart (__u); \
__uh = __ll_highpart (__u); \
__vl = __ll_lowpart (__v); \
__vh = __ll_highpart (__v); \
\
__x0 = (uintmax_t) __ul * __vl; \
__x1 = (uintmax_t) __ul * __vh; \
__x2 = (uintmax_t) __uh * __vl; \
__x3 = (uintmax_t) __uh * __vh; \
\
__x1 += __ll_highpart (__x0);/* this can't give carry */ \
__x1 += __x2; /* but this indeed can */ \
if (__x1 < __x2) /* did we get it? */ \
__x3 += __ll_B; /* yes, add it in the proper pos. */ \
\
(w1) = __x3 + __ll_highpart (__x1); \
(w0) = (__x1 << W_TYPE_SIZE / 2) + __ll_lowpart (__x0); \
} while (0)
#endif
#if !defined udiv_qrnnd || defined UDIV_NEEDS_NORMALIZATION
/* Define our own, not needing normalization. This function is
currently not performance critical, so keep it simple. Similar to
the mod macro below. */
# undef udiv_qrnnd
# define udiv_qrnnd(q, r, n1, n0, d) \
do { \
uint64_t __d1, __d0, __q, __r1, __r0; \
\
assert ((n1) < (d)); \
__d1 = (d); __d0 = 0; \
__r1 = (n1); __r0 = (n0); \
__q = 0; \
for (unsigned int __i = W_TYPE_SIZE; __i > 0; __i--) \
{ \
rsh2 (__d1, __d0, __d1, __d0, 1); \
__q <<= 1; \
if (ge2 (__r1, __r0, __d1, __d0)) \
{ \
__q++; \
sub_ddmmss (__r1, __r0, __r1, __r0, __d1, __d0); \
} \
} \
(r) = __r0; \
(q) = __q; \
} while (0)
#endif
#if !defined add_ssaaaa
# define add_ssaaaa(sh, sl, ah, al, bh, bl) \
do { \
uint64_t _add_x; \
_add_x = (al) + (bl); \
(sh) = (ah) + (bh) + (_add_x < (al)); \
(sl) = _add_x; \
} while (0)
#endif
#define rsh2(rh, rl, ah, al, cnt) \
do { \
(rl) = ((ah) << (W_TYPE_SIZE - (cnt))) | ((al) >> (cnt)); \
(rh) = (ah) >> (cnt); \
} while (0)
#define lsh2(rh, rl, ah, al, cnt) \
do { \
(rh) = ((ah) << cnt) | ((al) >> (W_TYPE_SIZE - (cnt))); \
(rl) = (al) << (cnt); \
} while (0)
#define ge2(ah, al, bh, bl) \
((ah) > (bh) || ((ah) == (bh) && (al) >= (bl)))
#define gt2(ah, al, bh, bl) \
((ah) > (bh) || ((ah) == (bh) && (al) > (bl)))
#ifndef sub_ddmmss
# define sub_ddmmss(rh, rl, ah, al, bh, bl) \
do { \
uint64_t _cy; \
_cy = (al) < (bl); \
(rl) = (al) - (bl); \
(rh) = (ah) - (bh) - _cy; \
} while (0)
#endif
#ifndef count_leading_zeros
# define count_leading_zeros(count, x) do { \
uint64_t __clz_x = (x); \
unsigned int __clz_c; \
for (__clz_c = 0; \
(__clz_x & ((uintmax_t) 0xff << (W_TYPE_SIZE - 8))) == 0; \
__clz_c += 8) \
__clz_x <<= 8; \
for (; (intmax_t)__clz_x >= 0; __clz_c++) \
__clz_x <<= 1; \
(count) = __clz_c; \
} while (0)
#endif
#ifndef count_trailing_zeros
# define count_trailing_zeros(count, x) do { \
uint64_t __ctz_x = (x); \
unsigned int __ctz_c = 0; \
while ((__ctz_x & 1) == 0) \
{ \
__ctz_x >>= 1; \
__ctz_c++; \
} \
(count) = __ctz_c; \
} while (0)
#endif
/* Requires that a < n and b <= n */
#define submod(r,a,b,n) \
do { \
uint64_t _t = - (uintmax_t) (a < b); \
(r) = ((n) & _t) + (a) - (b); \
} while (0)
#define addmod(r,a,b,n) \
submod ((r), (a), ((n) - (b)), (n))
/* Modular two-word addition and subtraction. For performance reasons, the
most significant bit of n1 must be clear. The destination variables must be
distinct from the mod operand. */
#define addmod2(r1, r0, a1, a0, b1, b0, n1, n0) \
do { \
add_ssaaaa ((r1), (r0), (a1), (a0), (b1), (b0)); \
if (ge2 ((r1), (r0), (n1), (n0))) \
sub_ddmmss ((r1), (r0), (r1), (r0), (n1), (n0)); \
} while (0)
#define submod2(r1, r0, a1, a0, b1, b0, n1, n0) \
do { \
sub_ddmmss ((r1), (r0), (a1), (a0), (b1), (b0)); \
if ((intmax_t) (r1) < 0) \
add_ssaaaa ((r1), (r0), (r1), (r0), (n1), (n0)); \
} while (0)
#define HIGHBIT_TO_MASK(x) \
(((intmax_t)-1 >> 1) < 0 \
? (uintmax_t)((intmax_t)(x) >> (W_TYPE_SIZE - 1)) \
: ((x) & ((uintmax_t) 1 << (W_TYPE_SIZE - 1)) \
? UINTMAX_MAX : (uintmax_t) 0))
/* Compute r = a mod d, where r = <*t1,retval>, a = <a1,a0>, d = <d1,d0>.
Requires that d1 != 0. */
static uintmax_t
mod2 (uint64_t *r1, uint64_t a1, uint64_t a0, uint64_t d1, uint64_t d0)
{
int cntd, cnta;
assert (d1 != 0);
if (a1 == 0)
{
*r1 = 0;
return a0;
}
count_leading_zeros (cntd, d1);
count_leading_zeros (cnta, a1);
int cnt = cntd - cnta;
lsh2 (d1, d0, d1, d0, cnt);
for (int i = 0; i < cnt; i++)
{
if (ge2 (a1, a0, d1, d0))
sub_ddmmss (a1, a0, a1, a0, d1, d0);
rsh2 (d1, d0, d1, d0, 1);
}
*r1 = a1;
return a0;
}
uint64_t
gcd_odd (uint64_t a, uint64_t b)
{
if ( (b & 1) == 0)
{
uint64_t t = b;
b = a;
a = t;
}
if (a == 0)
return b;
/* Take out least significant one bit, to make room for sign */
b >>= 1;
for (;;)
{
uint64_t t;
uint64_t bgta;
while ((a & 1) == 0)
a >>= 1;
a >>= 1;
t = a - b;
if (t == 0)
return (a << 1) + 1;
bgta = HIGHBIT_TO_MASK (t);
/* b <-- min (a, b) */
b += (bgta & t);
/* a <-- |a - b| */
a = (t ^ bgta) - bgta;
}
}
static uintmax_t
gcd2_odd (uint64_t *r1, uint64_t a1, uint64_t a0, uint64_t b1, uint64_t b0)
{
assert (b0 & 1);
if ( (a0 | a1) == 0)
{
*r1 = b1;
return b0;
}
while ((a0 & 1) == 0)
rsh2 (a1, a0, a1, a0, 1);
for (;;)
{
if ((b1 | a1) == 0)
{
*r1 = 0;
return gcd_odd (b0, a0);
}
if (gt2 (a1, a0, b1, b0))
{
sub_ddmmss (a1, a0, a1, a0, b1, b0);
do
rsh2 (a1, a0, a1, a0, 1);
while ((a0 & 1) == 0);
}
else if (gt2 (b1, b0, a1, a0))
{
sub_ddmmss (b1, b0, b1, b0, a1, a0);
do
rsh2 (b1, b0, b1, b0, 1);
while ((b0 & 1) == 0);
}
else
break;
}
*r1 = a1;
return a0;
}
static void
factor_insert_multiplicity (struct factors *factors,
uint64_t prime, unsigned int m)
{
unsigned int nfactors = factors->nfactors;
uint64_t *p = factors->p;
unsigned char *e = factors->e;
/* Locate position for insert new or increment e. */
int i;
for (i = nfactors - 1; i >= 0; i--)
{
if (p[i] <= prime)
break;
}
if (i < 0 || p[i] != prime)
{
for (int j = nfactors - 1; j > i; j--)
{
p[j + 1] = p[j];
e[j + 1] = e[j];
}
p[i + 1] = prime;
e[i + 1] = m;
factors->nfactors = nfactors + 1;
}
else
{
e[i] += m;
}
}
#define factor_insert(f, p) factor_insert_multiplicity (f, p, 1)
static void
factor_insert_large (struct factors *factors,
uint64_t p1, uint64_t p0)
{
if (p1 > 0)
{
assert (factors->plarge[1] == 0);
factors->plarge[0] = p0;
factors->plarge[1] = p1;
}
else
factor_insert (factors, p0);
}
/* Number of bits in an uintmax_t. */
enum { W = sizeof (uintmax_t) * 8 };
/* Verify that uint64_t does not have holes in its representation. */
#define P(a,b,c,d) a,
static const unsigned char primes_diff[] = {
#include "primes.h"
0,0,0,0,0,0,0 /* 7 sentinels for 8-way loop */
};
#undef P
#define PRIMES_PTAB_ENTRIES \
(sizeof (primes_diff) / sizeof (primes_diff[0]) - 8 + 1)
#define P(a,b,c,d) b,
static const unsigned char primes_diff8[] = {
#include "primes.h"
0,0,0,0,0,0,0 /* 7 sentinels for 8-way loop */
};
#undef P
struct primes_dtab
{
uint64_t binv, lim;
};
#define P(a,b,c,d) {c,d},
static const struct primes_dtab primes_dtab[] = {
#include "primes.h"
{1,0},{1,0},{1,0},{1,0},{1,0},{1,0},{1,0} /* 7 sentinels for 8-way loop */
};
#undef P
/* Verify that uint64_t is not wider than
the integers used to generate primes.h. */
/* Prove primality or run probabilistic tests. */
static bool flag_prove_primality = PROVE_PRIMALITY;
/* Number of Miller-Rabin tests to run when not proving primality. */
#define MR_REPS 25
static void
factor_insert_refind (struct factors *factors, uint64_t p, unsigned int i,
unsigned int off)
{
for (unsigned int j = 0; j < off; j++)
p += primes_diff[i + j];
factor_insert (factors, p);
}
/* Trial division with odd primes uses the following trick.
Let p be an odd prime, and B = 2^{W_TYPE_SIZE}. For simplicity,
consider the case t < B (this is the second loop below).
From our tables we get
binv = p^{-1} (mod B)
lim = floor ( (B-1) / p ).
First assume that t is a multiple of p, t = q * p. Then 0 <= q <= lim
(and all quotients in this range occur for some t).
Then t = q * p is true also (mod B), and p is invertible we get
q = t * binv (mod B).
Next, assume that t is *not* divisible by p. Since multiplication
by binv (mod B) is a one-to-one mapping,
t * binv (mod B) > lim,
because all the smaller values are already taken.
This can be summed up by saying that the function
q(t) = binv * t (mod B)
is a permutation of the range 0 <= t < B, with the curious property
that it maps the multiples of p onto the range 0 <= q <= lim, in
order, and the non-multiples of p onto the range lim < q < B.
*/
static uintmax_t
factor_using_division (uint64_t *t1p, uint64_t t1, uint64_t t0,
struct factors *factors)
{
if (t0 % 2 == 0)
{
unsigned int cnt;
if (t0 == 0)
{
count_trailing_zeros (cnt, t1);
t0 = t1 >> cnt;
t1 = 0;
cnt += W_TYPE_SIZE;
}
else
{
count_trailing_zeros (cnt, t0);
rsh2 (t1, t0, t1, t0, cnt);
}
factor_insert_multiplicity (factors, 2, cnt);
}
uint64_t p = 3;
unsigned int i;
for (i = 0; t1 > 0 && i < PRIMES_PTAB_ENTRIES; i++)
{
for (;;)
{
uint64_t q1, q0, hi, lo;
q0 = t0 * primes_dtab[i].binv;
umul_ppmm (hi, lo, q0, p);
if (hi > t1)
break;
hi = t1 - hi;
q1 = hi * primes_dtab[i].binv;
if (LIKELY (q1 > primes_dtab[i].lim))
break;
t1 = q1; t0 = q0;
factor_insert (factors, p);
}
p += primes_diff[i + 1];
}
if (t1p)
*t1p = t1;
#define DIVBLOCK(I) \
do { \
for (;;) \
{ \
q = t0 * pd[I].binv; \
if (LIKELY (q > pd[I].lim)) \
break; \
t0 = q; \
factor_insert_refind (factors, p, i + 1, I); \
} \
} while (0)
for (; i < PRIMES_PTAB_ENTRIES; i += 8)
{
uint64_t q;
const struct primes_dtab *pd = &primes_dtab[i];
DIVBLOCK (0);
DIVBLOCK (1);
DIVBLOCK (2);
DIVBLOCK (3);
DIVBLOCK (4);
DIVBLOCK (5);
DIVBLOCK (6);
DIVBLOCK (7);
p += primes_diff8[i];
if (p * p > t0)
break;
}
return t0;
}
/* Entry i contains (2i+1)^(-1) mod 2^8. */
static const unsigned char binvert_table[128] =
{
0x01, 0xAB, 0xCD, 0xB7, 0x39, 0xA3, 0xC5, 0xEF,
0xF1, 0x1B, 0x3D, 0xA7, 0x29, 0x13, 0x35, 0xDF,
0xE1, 0x8B, 0xAD, 0x97, 0x19, 0x83, 0xA5, 0xCF,
0xD1, 0xFB, 0x1D, 0x87, 0x09, 0xF3, 0x15, 0xBF,
0xC1, 0x6B, 0x8D, 0x77, 0xF9, 0x63, 0x85, 0xAF,
0xB1, 0xDB, 0xFD, 0x67, 0xE9, 0xD3, 0xF5, 0x9F,
0xA1, 0x4B, 0x6D, 0x57, 0xD9, 0x43, 0x65, 0x8F,
0x91, 0xBB, 0xDD, 0x47, 0xC9, 0xB3, 0xD5, 0x7F,
0x81, 0x2B, 0x4D, 0x37, 0xB9, 0x23, 0x45, 0x6F,
0x71, 0x9B, 0xBD, 0x27, 0xA9, 0x93, 0xB5, 0x5F,
0x61, 0x0B, 0x2D, 0x17, 0x99, 0x03, 0x25, 0x4F,
0x51, 0x7B, 0x9D, 0x07, 0x89, 0x73, 0x95, 0x3F,
0x41, 0xEB, 0x0D, 0xF7, 0x79, 0xE3, 0x05, 0x2F,
0x31, 0x5B, 0x7D, 0xE7, 0x69, 0x53, 0x75, 0x1F,
0x21, 0xCB, 0xED, 0xD7, 0x59, 0xC3, 0xE5, 0x0F,
0x11, 0x3B, 0x5D, 0xC7, 0x49, 0x33, 0x55, 0xFF
};
/* Compute n^(-1) mod B, using a Newton iteration. */
#define binv(inv,n) \
do { \
uint64_t __n = (n); \
uint64_t __inv; \
\
__inv = binvert_table[(__n / 2) & 0x7F]; /* 8 */ \
if (W_TYPE_SIZE > 8) __inv = 2 * __inv - __inv * __inv * __n; \
if (W_TYPE_SIZE > 16) __inv = 2 * __inv - __inv * __inv * __n; \
if (W_TYPE_SIZE > 32) __inv = 2 * __inv - __inv * __inv * __n; \
\
if (W_TYPE_SIZE > 64) \
{ \
int __invbits = 64; \
do { \
__inv = 2 * __inv - __inv * __inv * __n; \
__invbits *= 2; \
} while (__invbits < W_TYPE_SIZE); \
} \
\
(inv) = __inv; \
} while (0)
/* q = u / d, assuming d|u. */
#define divexact_21(q1, q0, u1, u0, d) \
do { \
uint64_t _di, _q0; \
binv (_di, (d)); \
_q0 = (u0) * _di; \
if ((u1) >= (d)) \
{ \
uint64_t _p1, _p0; \
umul_ppmm (_p1, _p0, _q0, d); \
(q1) = ((u1) - _p1) * _di; \
(q0) = _q0; \
} \
else \
{ \
(q0) = _q0; \
(q1) = 0; \
} \
} while (0)
/* x B (mod n). */
#define redcify(r_prim, r, n) \
do { \
uint64_t _redcify_q; \
udiv_qrnnd (_redcify_q, r_prim, r, 0, n); \
} while (0)
/* x B^2 (mod n). Requires x > 0, n1 < B/2 */
#define redcify2(r1, r0, x, n1, n0) \
do { \
uint64_t _r1, _r0, _i; \
if ((x) < (n1)) \
{ \
_r1 = (x); _r0 = 0; \
_i = W_TYPE_SIZE; \
} \
else \
{ \
_r1 = 0; _r0 = (x); \
_i = 2*W_TYPE_SIZE; \
} \
while (_i-- > 0) \
{ \
lsh2 (_r1, _r0, _r1, _r0, 1); \
if (ge2 (_r1, _r0, (n1), (n0))) \
sub_ddmmss (_r1, _r0, _r1, _r0, (n1), (n0)); \
} \
(r1) = _r1; \
(r0) = _r0; \
} while (0)
/* Modular two-word multiplication, r = a * b mod m, with mi = m^(-1) mod B.
Both a and b must be in redc form, the result will be in redc form too. */
static inline uintmax_t
mulredc (uint64_t a, uint64_t b, uint64_t m, uint64_t mi)
{
uint64_t rh, rl, q, th, tl, xh;
umul_ppmm (rh, rl, a, b);
q = rl * mi;
umul_ppmm (th, tl, q, m);
xh = rh - th;
if (rh < th)
xh += m;
return xh;
}
/* Modular two-word multiplication, r = a * b mod m, with mi = m^(-1) mod B.
Both a and b must be in redc form, the result will be in redc form too.
For performance reasons, the most significant bit of m must be clear. */
static uintmax_t
mulredc2 (uint64_t *r1p,
uint64_t a1, uint64_t a0, uint64_t b1, uint64_t b0,
uint64_t m1, uint64_t m0, uint64_t mi)
{
uint64_t r1, r0, q, p1, p0, t1, t0, s1, s0;
mi = -mi;
assert ( (a1 >> (W_TYPE_SIZE - 1)) == 0);
assert ( (b1 >> (W_TYPE_SIZE - 1)) == 0);
assert ( (m1 >> (W_TYPE_SIZE - 1)) == 0);
/* First compute a0 * <b1, b0> B^{-1}
+-----+
|a0 b0|
+--+--+--+
|a0 b1|
+--+--+--+
|q0 m0|
+--+--+--+
|q0 m1|
-+--+--+--+
|r1|r0| 0|
+--+--+--+
*/
umul_ppmm (t1, t0, a0, b0);
umul_ppmm (r1, r0, a0, b1);
q = mi * t0;
umul_ppmm (p1, p0, q, m0);
umul_ppmm (s1, s0, q, m1);
r0 += (t0 != 0); /* Carry */
add_ssaaaa (r1, r0, r1, r0, 0, p1);
add_ssaaaa (r1, r0, r1, r0, 0, t1);
add_ssaaaa (r1, r0, r1, r0, s1, s0);
/* Next, (a1 * <b1, b0> + <r1, r0> B^{-1}
+-----+
|a1 b0|
+--+--+
|r1|r0|
+--+--+--+
|a1 b1|
+--+--+--+
|q1 m0|
+--+--+--+
|q1 m1|
-+--+--+--+
|r1|r0| 0|
+--+--+--+
*/
umul_ppmm (t1, t0, a1, b0);
umul_ppmm (s1, s0, a1, b1);
add_ssaaaa (t1, t0, t1, t0, 0, r0);
q = mi * t0;
add_ssaaaa (r1, r0, s1, s0, 0, r1);
umul_ppmm (p1, p0, q, m0);
umul_ppmm (s1, s0, q, m1);
r0 += (t0 != 0); /* Carry */
add_ssaaaa (r1, r0, r1, r0, 0, p1);
add_ssaaaa (r1, r0, r1, r0, 0, t1);
add_ssaaaa (r1, r0, r1, r0, s1, s0);
if (ge2 (r1, r0, m1, m0))
sub_ddmmss (r1, r0, r1, r0, m1, m0);
*r1p = r1;
return r0;
}
static uint64_t
powm (uint64_t b, uint64_t e, uint64_t n, uint64_t ni, uint64_t one)
{
uint64_t y = one;
if (e & 1)
y = b;
while (e != 0)
{
b = mulredc (b, b, n, ni);
e >>= 1;
if (e & 1)
y = mulredc (y, b, n, ni);
}
return y;
}
static uintmax_t
powm2 (uint64_t *r1m,
const uint64_t *bp, const uint64_t *ep, const uint64_t *np,
uint64_t ni, const uint64_t *one)
{
uint64_t r1, r0, b1, b0, n1, n0;
unsigned int i;
uint64_t e;
b0 = bp[0];
b1 = bp[1];
n0 = np[0];
n1 = np[1];
r0 = one[0];
r1 = one[1];
for (e = ep[0], i = W_TYPE_SIZE; i > 0; i--, e >>= 1)
{
if (e & 1)
{
r0 = mulredc2 (r1m, r1, r0, b1, b0, n1, n0, ni);
r1 = *r1m;
}
b0 = mulredc2 (r1m, b1, b0, b1, b0, n1, n0, ni);
b1 = *r1m;
}
for (e = ep[1]; e > 0; e >>= 1)
{
if (e & 1)
{
r0 = mulredc2 (r1m, r1, r0, b1, b0, n1, n0, ni);
r1 = *r1m;
}
b0 = mulredc2 (r1m, b1, b0, b1, b0, n1, n0, ni);
b1 = *r1m;
}
*r1m = r1;
return r0;
}
static bool
millerrabin (uint64_t n, uint64_t ni, uint64_t b, uint64_t q,
unsigned int k, uint64_t one)
{
uint64_t y = powm (b, q, n, ni, one);
uint64_t nm1 = n - one; /* -1, but in redc representation. */
if (y == one || y == nm1)
return true;
for (unsigned int i = 1; i < k; i++)
{
y = mulredc (y, y, n, ni);
if (y == nm1)
return true;
if (y == one)
return false;
}
return false;
}
static bool
millerrabin2 (const uint64_t *np, uint64_t ni, const uint64_t *bp,
const uint64_t *qp, unsigned int k, const uint64_t *one)
{
uint64_t y1, y0, nm1_1, nm1_0, r1m;
y0 = powm2 (&r1m, bp, qp, np, ni, one);
y1 = r1m;
if (y0 == one[0] && y1 == one[1])
return true;
sub_ddmmss (nm1_1, nm1_0, np[1], np[0], one[1], one[0]);
if (y0 == nm1_0 && y1 == nm1_1)
return true;
for (unsigned int i = 1; i < k; i++)
{
y0 = mulredc2 (&r1m, y1, y0, y1, y0, np[1], np[0], ni);
y1 = r1m;
if (y0 == nm1_0 && y1 == nm1_1)
return true;
if (y0 == one[0] && y1 == one[1])
return false;
}
return false;
}
/* Lucas' prime test. The number of iterations vary greatly, up to a few dozen
have been observed. The average seem to be about 2. */
static bool
prime_p (uint64_t n)
{
int k;
bool is_prime;
uint64_t a_prim, one, ni;
struct factors factors;
if (n <= 1)
return false;
/* We have already casted out small primes. */
if (n < (uintmax_t) FIRST_OMITTED_PRIME * FIRST_OMITTED_PRIME)
return true;
/* Precomputation for Miller-Rabin. */
uint64_t q = n - 1;
for (k = 0; (q & 1) == 0; k++)
q >>= 1;
uint64_t a = 2;
binv (ni, n); /* ni <- 1/n mod B */
redcify (one, 1, n);
addmod (a_prim, one, one, n); /* i.e., redcify a = 2 */
/* Perform a Miller-Rabin test, finds most composites quickly. */
if (!millerrabin (n, ni, a_prim, q, k, one))
return false;
if (flag_prove_primality)
{
/* Factor n-1 for Lucas. */
factor (n - 1, &factors);
}
/* Loop until Lucas proves our number prime, or Miller-Rabin proves our
number composite. */
for (unsigned int r = 0; r < PRIMES_PTAB_ENTRIES; r++)
{
if (flag_prove_primality)
{
is_prime = true;
for (unsigned int i = 0; i < factors.nfactors && is_prime; i++)
{
is_prime
= powm (a_prim, (n - 1) / factors.p[i], n, ni, one) != one;
}
}
else
{
/* After enough Miller-Rabin runs, be content. */
is_prime = (r == MR_REPS - 1);
}
if (is_prime)
return true;
a += primes_diff[r]; /* Establish new base. */
/* The following is equivalent to redcify (a_prim, a, n). It runs faster
on most processors, since it avoids udiv_qrnnd. If we go down the
udiv_qrnnd_preinv path, this code should be replaced. */
{
uint64_t s1, s0;
umul_ppmm (s1, s0, one, a);
if (LIKELY (s1 == 0))
a_prim = s0 % n;
else
{
uint64_t dummy;
udiv_qrnnd (dummy, a_prim, s1, s0, n);
}
}
if (!millerrabin (n, ni, a_prim, q, k, one))
return false;
}
error (0, 0, ("Lucas prime test failure. This should not happen"));
abort ();
}
static bool
prime2_p (uint64_t n1, uint64_t n0)
{
uint64_t q[2], nm1[2];
uint64_t a_prim[2];
uint64_t one[2];
uint64_t na[2];
uint64_t ni;
unsigned int k;
struct factors factors;
if (n1 == 0)
return prime_p (n0);
nm1[1] = n1 - (n0 == 0);
nm1[0] = n0 - 1;
if (nm1[0] == 0)
{
count_trailing_zeros (k, nm1[1]);
q[0] = nm1[1] >> k;
q[1] = 0;
k += W_TYPE_SIZE;
}
else
{
count_trailing_zeros (k, nm1[0]);
rsh2 (q[1], q[0], nm1[1], nm1[0], k);
}
uint64_t a = 2;
binv (ni, n0);
redcify2 (one[1], one[0], 1, n1, n0);
addmod2 (a_prim[1], a_prim[0], one[1], one[0], one[1], one[0], n1, n0);
/* FIXME: Use scalars or pointers in arguments? Some consistency needed. */
na[0] = n0;
na[1] = n1;
if (!millerrabin2 (na, ni, a_prim, q, k, one))
return false;
if (flag_prove_primality)
{
/* Factor n-1 for Lucas. */
factor (nm1[0], &factors);
}
/* Loop until Lucas proves our number prime, or Miller-Rabin proves our
number composite. */
for (unsigned int r = 0; r < PRIMES_PTAB_ENTRIES; r++)
{
bool is_prime;
uint64_t e[2], y[2];
if (flag_prove_primality)
{
is_prime = true;
if (factors.plarge[1])
{
uint64_t pi;
binv (pi, factors.plarge[0]);
e[0] = pi * nm1[0];
e[1] = 0;
y[0] = powm2 (&y[1], a_prim, e, na, ni, one);
is_prime = (y[0] != one[0] || y[1] != one[1]);
}
for (unsigned int i = 0; i < factors.nfactors && is_prime; i++)
{
/* FIXME: We always have the factor 2. Do we really need to
handle it here? We have done the same powering as part
of millerrabin. */
if (factors.p[i] == 2)
rsh2 (e[1], e[0], nm1[1], nm1[0], 1);
else
divexact_21 (e[1], e[0], nm1[1], nm1[0], factors.p[i]);
y[0] = powm2 (&y[1], a_prim, e, na, ni, one);
is_prime = (y[0] != one[0] || y[1] != one[1]);
}
}
else
{
/* After enough Miller-Rabin runs, be content. */
is_prime = (r == MR_REPS - 1);
}
if (is_prime)
return true;
a += primes_diff[r]; /* Establish new base. */
redcify2 (a_prim[1], a_prim[0], a, n1, n0);
if (!millerrabin2 (na, ni, a_prim, q, k, one))
return false;
}
error (0, 0, ("Lucas prime test failure. This should not happen"));
abort ();
}
static void
factor_using_pollard_rho (uint64_t n, unsigned long int a,
struct factors *factors)
{
uint64_t x, z, y, P, t, ni, g;
unsigned long int k = 1;
unsigned long int l = 1;
redcify (P, 1, n);
addmod (x, P, P, n); /* i.e., redcify(2) */
y = z = x;
while (n != 1)
{
assert (a < n);
binv (ni, n); /* FIXME: when could we use old 'ni' value? */
for (;;)
{
do
{
x = mulredc (x, x, n, ni);
addmod (x, x, a, n);
submod (t, z, x, n);
P = mulredc (P, t, n, ni);
if (k % 32 == 1)
{
if (gcd_odd (P, n) != 1)
goto factor_found;
y = x;
}
}
while (--k != 0);
z = x;
k = l;
l = 2 * l;
for (unsigned long int i = 0; i < k; i++)
{
x = mulredc (x, x, n, ni);
addmod (x, x, a, n);
}
y = x;
}
factor_found:
do
{
y = mulredc (y, y, n, ni);
addmod (y, y, a, n);
submod (t, z, y, n);
g = gcd_odd (t, n);
}
while (g == 1);
if (n == g)
{
/* Found n itself as factor. Restart with different params. */
factor_using_pollard_rho (n, a + 1, factors);
return;
}
n = n / g;
if (!prime_p (g))
factor_using_pollard_rho (g, a + 1, factors);
else
factor_insert (factors, g);
if (prime_p (n))
{
factor_insert (factors, n);
break;
}
x = x % n;
z = z % n;
y = y % n;
}
}
static void
factor_using_pollard_rho2 (uint64_t n1, uint64_t n0, unsigned long int a,
struct factors *factors)
{
uint64_t x1, x0, z1, z0, y1, y0, P1, P0, t1, t0, ni, g1, g0, r1m;
unsigned long int k = 1;
unsigned long int l = 1;
redcify2 (P1, P0, 1, n1, n0);
addmod2 (x1, x0, P1, P0, P1, P0, n1, n0); /* i.e., redcify(2) */
y1 = z1 = x1;
y0 = z0 = x0;
while (n1 != 0 || n0 != 1)
{
binv (ni, n0);
for (;;)
{
do
{
x0 = mulredc2 (&r1m, x1, x0, x1, x0, n1, n0, ni);
x1 = r1m;
addmod2 (x1, x0, x1, x0, 0, (uintmax_t) a, n1, n0);
submod2 (t1, t0, z1, z0, x1, x0, n1, n0);
P0 = mulredc2 (&r1m, P1, P0, t1, t0, n1, n0, ni);
P1 = r1m;
if (k % 32 == 1)
{
g0 = gcd2_odd (&g1, P1, P0, n1, n0);
if (g1 != 0 || g0 != 1)
goto factor_found;
y1 = x1; y0 = x0;
}
}
while (--k != 0);
z1 = x1; z0 = x0;
k = l;
l = 2 * l;
for (unsigned long int i = 0; i < k; i++)
{
x0 = mulredc2 (&r1m, x1, x0, x1, x0, n1, n0, ni);
x1 = r1m;
addmod2 (x1, x0, x1, x0, 0, (uintmax_t) a, n1, n0);
}
y1 = x1; y0 = x0;
}
factor_found:
do
{
y0 = mulredc2 (&r1m, y1, y0, y1, y0, n1, n0, ni);
y1 = r1m;
addmod2 (y1, y0, y1, y0, 0, (uintmax_t) a, n1, n0);
submod2 (t1, t0, z1, z0, y1, y0, n1, n0);
g0 = gcd2_odd (&g1, t1, t0, n1, n0);
}
while (g1 == 0 && g0 == 1);
if (g1 == 0)
{
/* The found factor is one word, and > 1. */
divexact_21 (n1, n0, n1, n0, g0); /* n = n / g */
if (!prime_p (g0))
factor_using_pollard_rho (g0, a + 1, factors);
else
factor_insert (factors, g0);
}
else
{
/* The found factor is two words. This is highly unlikely, thus hard
to trigger. Please be careful before you change this code! */
uint64_t ginv;
if (n1 == g1 && n0 == g0)
{
/* Found n itself as factor. Restart with different params. */
factor_using_pollard_rho2 (n1, n0, a + 1, factors);
return;
}
binv (ginv, g0); /* Compute n = n / g. Since the result will */
n0 = ginv * n0; /* fit one word, we can compute the quotient */
n1 = 0; /* modulo B, ignoring the high divisor word. */
if (!prime2_p (g1, g0))
factor_using_pollard_rho2 (g1, g0, a + 1, factors);
else
factor_insert_large (factors, g1, g0);
}
if (n1 == 0)
{
if (prime_p (n0))
{
factor_insert (factors, n0);
break;
}
factor_using_pollard_rho (n0, a, factors);
return;
}
if (prime2_p (n1, n0))
{
factor_insert_large (factors, n1, n0);
break;
}
x0 = mod2 (&x1, x1, x0, n1, n0);
z0 = mod2 (&z1, z1, z0, n1, n0);
y0 = mod2 (&y1, y1, y0, n1, n0);
}
}
/* Compute the prime factors of the 128-bit number (T1,T0), and put the
results in FACTORS. */
void factor (uint64_t t0, struct factors *factors)
{
std::uint64_t t1 = 0;
factors->nfactors = 0;
factors->plarge[1] = 0;
if (t1 == 0 && t0 < 2)
return;
t0 = factor_using_division (&t1, t1, t0, factors);
if (t1 == 0 && t0 < 2)
return;
if (prime2_p (t1, t0))
factor_insert_large (factors, t1, t0);
else
{
if (t1 == 0)
factor_using_pollard_rho (t0, 1, factors);
else
factor_using_pollard_rho2 (t1, t0, 1, factors);
}
}
| [
"[email protected]"
] | |
832c1d713f4b1f0654da9ffe4ebc0c336eb3c10e | 1d35dcedaa739a38ad8e9d2cb3a811be759e16e4 | /3/VP/Lab2/startdialog_vetrinskiy_martasov.h | 3fd23bf8abf783442c684479597fb1d3e0ee1f89 | [] | no_license | makisto/VPChMV | cdf50a03ee506eca9fffc4f3ae9864549a5deda3 | eaf1b5375971d1fe071eec327618a1c3e0884675 | refs/heads/master | 2022-04-19T12:22:27.647038 | 2020-04-10T17:36:56 | 2020-04-10T17:36:56 | 254,692,889 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,135 | h | #ifndef STARTDIALOG_VETRINSKIY_MARTASOV_H
#define STARTDIALOG_VETRINSKIY_MARTASOV_H
#include <QWidget>
#include <QPushButton>
#include <QMessageBox>
#include "inputdialog_vetrinskiy_martasov.h"
class StartDialog_Vetrinskiy_Martasov:public QPushButton
{
Q_OBJECT
public:
StartDialog_Vetrinskiy_Martasov(QWidget *pwgt = 0) : QPushButton("Нажми", pwgt)
{
connect(this, SIGNAL(clicked()), SLOT(slotButtonClicked()));
}
public slots:
void slotButtonClicked()
{
inputdialog_Vetrinskiy_Martasov *pInputDialog = new inputdialog_Vetrinskiy_Martasov;
if(pInputDialog->exec()==QDialog::Accepted)
{
QMessageBox::information(0,
"Ваша информация: ",
"Имя: "
+ pInputDialog->firstName()
+"\nФамилия: "
+ pInputDialog->lastName()
);
}
delete pInputDialog;
}
};
#endif // STARTDIALOG_VETRINSKIY_MARTASOV_H
| [
"[email protected]"
] | |
6ba9a5eabc604678ccf7461c887952077486b8c2 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/squid/gumtree/squid_repos_function_967_last_repos.cpp | 2e635792fdf7b43fbc5a93d20f71d264efbc3e76 | [] | 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 | 288 | cpp | Http::StreamPointer
Pipeline::back() const
{
if (requests.empty()) {
debugs(33, 3, "Pipeline " << (void*)this << " empty");
return Http::StreamPointer();
}
debugs(33, 3, "Pipeline " << (void*)this << " back " << requests.back());
return requests.back();
} | [
"[email protected]"
] | |
a6f049e83b51adc7aed99f7a25da91598bd41429 | f41dba42b2aaf9df9b52e09e47cdc25da2e6e0e9 | /Graphs/Possible_Path_between_2_vertices.cpp | cbccceacb9a6ce7c0655bb2a6a238ff511ecd1e7 | [] | no_license | Satzyakiz/CP | 5c9642fdede7fbe213fb98f259deda978712ef49 | e869dfd2bd6f3fc692e9223c2d370b5c95904701 | refs/heads/master | 2023-03-02T11:52:52.472154 | 2021-02-03T06:50:32 | 2021-02-03T06:50:32 | 258,285,110 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,120 | cpp | // Count the total number of ways or paths that exist between two vertices
// in a directed graph. These paths doesn’t contain a cycle.
//
// Input:
// 1
// 5 7
// 1 2 1 3 1 5 2 4 2 5 3 5 4 3
// 1 5
// Output:
// 4
//
// Explanation:
// Testcase 1 : There are 4 paths from 1 to 5.
// 1 -> 5
// 1 -> 2 -> 5
// 1 -> 3 -> 5
// 1 -> 2 -> 4 -> 3 -> 5
#include<bits/stdc++.h>
using namespace std;
int countV;
void ways(vector<vector<int>> &adj, int s, int e,vector<int> &visited){
if(s == e){
countV++;
return;
}
visited[s] = 1;
for(int &v: adj[s]){
if(!visited[v])
ways(adj,v,e,visited);
}
visited[s] = 0;
}
void solve(){
int V,e,x,y;
cin>>V>>e;
vector<vector<int>> adj(V+1);
for(int i=0; i<e; i++){
cin>>x>>y;
adj[x].push_back(y);
}
cin>>x>>y;
countV = 0;
vector<int> visited(V+1);
ways(adj,x,y,visited);
cout<<countV<<endl;
}
int main(){
int t;
cin>>t;
while(t--)
solve();
return 0;
}
| [
"[email protected]"
] | |
4a77424895887850aecbd0a66ce34a024452014b | 11722aac2e9f24f995c8431637cda216d609d174 | /src/Interface/Modules/DataIO/ReadFieldDialog.cc | 8fead0c6e90117577444447c80d03ec3a9915e2b | [
"MIT"
] | permissive | mhansen1/SCIRun | 476024eabc940a10a6513f9da354659710f63881 | 9719c570a6d6911a9eb8df584bd2c4ad8b8cd2ba | refs/heads/master | 2021-01-09T07:01:19.121963 | 2015-04-21T19:13:36 | 2015-04-21T19:13:36 | 26,781,585 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,136 | cc | /*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2015 Scientific Computing and Imaging Institute,
University of Utah.
License for the specific language governing rights and limitations under
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 <Interface/Modules/DataIO/ReadFieldDialog.h>
#include <Modules/DataIO/ReadField.h>
#include <Core/Algorithms/Base/AlgorithmVariableNames.h>
#include <Dataflow/Network/ModuleStateInterface.h> //TODO: extract into intermediate
#include <Core/ImportExport/GenericIEPlugin.h>
#include <iostream>
#include <QFileDialog>
using namespace SCIRun::Gui;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Core::Algorithms;
ReadFieldDialog::ReadFieldDialog(const std::string& name, ModuleStateHandle state,
QWidget* parent /* = 0 */)
: ModuleDialogGeneric(state, parent)
{
setupUi(this);
setWindowTitle(QString::fromStdString(name));
fixSize();
connect(openFileButton_, SIGNAL(clicked()), this, SLOT(openFile()));
connect(fileNameLineEdit_, SIGNAL(editingFinished()), this, SLOT(pushFileNameToState()));
connect(fileNameLineEdit_, SIGNAL(returnPressed()), this, SLOT(pushFileNameToState()));
buttonBox->setVisible(false);
}
void ReadFieldDialog::pull()
{
fileNameLineEdit_->setText(QString::fromStdString(state_->getValue(Variables::Filename).toString()));
}
void ReadFieldDialog::pushFileNameToState()
{
auto file = fileNameLineEdit_->text().trimmed().toStdString();
state_->setValue(Variables::Filename, file);
}
void ReadFieldDialog::openFile()
{
auto types = Modules::DataIO::ReadFieldModule::fileTypeList();
QString typesQ(QString::fromStdString(types));
auto file = QFileDialog::getOpenFileName(this, "Open Field File", dialogDirectory(), typesQ, &selectedFilter_);
if (file.length() > 0)
{
auto typeName = SCIRun::fileTypeDescriptionFromDialogBoxFilter(selectedFilter_.toStdString());
state_->setValue(Variables::FileTypeName, typeName);
fileNameLineEdit_->setText(file);
updateRecentFile(file);
pushFileNameToState();
}
}
| [
"[email protected]"
] | |
d509c0fedb47d2546e73fe073f30870026a8f710 | c32ee8ade268240a8064e9b8efdbebfbaa46ddfa | /Libraries/m2sdk/ue/sys/core/C_LightTypeDesc.h | 8513b6dbbf1171932c0686647a43c28bfe67eab8 | [] | no_license | hopk1nz/maf2mp | 6f65bd4f8114fdeb42f9407a4d158ad97f8d1789 | 814cab57dc713d9ff791dfb2a2abeb6af0e2f5a8 | refs/heads/master | 2021-03-12T23:56:24.336057 | 2015-08-22T13:53:10 | 2015-08-22T13:53:10 | 41,209,355 | 19 | 21 | null | 2015-08-31T05:28:13 | 2015-08-22T13:56:04 | C++ | UTF-8 | C++ | false | false | 496 | h | // auto-generated file (rttidump-exporter by h0pk1nz)
#pragma once
#include <ue/sys/core/I_FrameTypeDesc.h>
namespace ue
{
namespace sys
{
namespace core
{
/** ue::sys::core::C_LightTypeDesc (VTable=0x01E86108) */
class C_LightTypeDesc : public I_FrameTypeDesc
{
public:
virtual void vfn_0001_AACDBB5B() = 0;
virtual void vfn_0002_AACDBB5B() = 0;
virtual void vfn_0003_AACDBB5B() = 0;
virtual void vfn_0004_AACDBB5B() = 0;
};
} // namespace core
} // namespace sys
} // namespace ue
| [
"[email protected]"
] | |
7bd4c1d955f87f41b87072b25b54e42685f957d1 | 398a24f3843165ac95d12863991e98de3125b49d | /Trees/ReviewLater/FloorAndCeilFromBST.cpp | b8495ba027a5c9c0ade489d3823d4e8ffffc5179 | [] | no_license | cvora23/CodingInterviewQ | a1a3ec6b97702f6ae907878ff0594f6f31804e0f | c4596a5a564109b4f68449ee59dcd8f928aa47c0 | refs/heads/master | 2021-05-16T02:02:00.784600 | 2018-03-02T17:03:04 | 2018-03-02T17:03:04 | 23,085,792 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,561 | cpp | /*
* FloorAndCeilFromBST.cpp
*
* Created on: Sep 8, 2013
* Author: cvora
*/
// Program to find ceil of a given value in BST
#include <stdio.h>
#include <stdlib.h>
/* A binary tree node has key, left child and right child */
struct node
{
int key;
struct node* left;
struct node* right;
};
/* Helper function that allocates a new node with the given key and
NULL left and right pointers.*/
struct node* newNode(int key)
{
struct node* node = (struct node*)malloc(sizeof(struct node));
node->key = key;
node->left = NULL;
node->right = NULL;
return(node);
}
// Function to find ceil of a given input in BST. If input is more
// than the max key in BST, return -1
int Ceil(node *root, int input)
{
// Base case
if( root == NULL )
return -1;
// We found equal key
if( root->key == input )
return root->key;
// If root's key is smaller, ceil must be in right subtree
if( root->key < input )
return Ceil(root->right, input);
// Else, either left subtree or root has the ceil value
int ceil = Ceil(root->left, input);
return (ceil >= input) ? ceil : root->key;
}
// Driver program to test above function
int main()
{
node *root = newNode(8);
root->left = newNode(4);
root->right = newNode(12);
root->left->left = newNode(2);
root->left->right = newNode(6);
root->right->left = newNode(10);
root->right->right = newNode(14);
for(int i = 0; i < 16; i++)
printf("%d %d\n", i, Ceil(root, i));
return 0;
}
| [
"[email protected]"
] | |
f8d2110bafb5a52bc904d5767c5d297f10366ba2 | 0644a6f38361da1a25722003b8e059bfe1a019ed | /orbslam/hw4/src/utils.h | 94d8ac5a3b40a00c4a0dc8a89d81c56a4fd7b72a | [] | no_license | Alvintang6/slam_course | 7ae0aec23947ddfb2d3aef0cfdb8e8bf45bf9758 | 4f437272b7d2b6d148d87fad3d381c80ba7a6a59 | refs/heads/master | 2022-11-30T06:14:51.060137 | 2020-08-19T14:23:44 | 2020-08-19T14:23:44 | 247,200,236 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 619 | h | #ifndef __UTILS_H__
#define __UTILS_H__
#include <vector>
#include <opencv2/opencv.hpp>
#include <Eigen/Geometry>
#include <Eigen/StdVector>
void saveTrajectoryTUM(const std::string &file_name, const std::vector<Eigen::Matrix4d> &v_Twc);
void createLandmarks(std::vector<Eigen::Vector3d> &points);
void loadMeshAndPerprocess(cv::viz::Mesh &mesh, const std::string &ply_file);
void createLandmarksFromMesh(const cv::viz::Mesh &mesh, std::vector<Eigen::Vector3d> &points, std::vector<Eigen::Vector3d> &normals);
void createCameraPose(std::vector<Eigen::Matrix4d> &v_Twc, const Eigen::Vector3d &point_focus);
#endif | [
"[email protected]"
] | |
36442b662c5933515b6460dcb9d93f27f8802fae | ccff7aaeed433797305b83b4aa36b0aa5ac39a12 | /rsbench/CUDA/dpct_output/simulation.cpp | 17af15b7d2404b8fc757a9e87265916dc1037229 | [
"BSD-3-Clause"
] | permissive | zjin-lcf/DPCT | e0a8560385073de1406a7d41c171a29ffbb14d23 | 98f9df5cc60772e30347ef8b478acb7c7156206f | refs/heads/master | 2022-12-27T02:42:06.217884 | 2020-09-16T20:00:24 | 2020-09-16T20:00:24 | 276,102,390 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 18,541 | cpp | #include <CL/sycl.hpp>
#include <dpct/dpct.hpp>
#include "rsbench.h"
////////////////////////////////////////////////////////////////////////////////////
// BASELINE FUNCTIONS
////////////////////////////////////////////////////////////////////////////////////
// All "baseline" code is at the top of this file. The baseline code is a simple
// implementation of the algorithm, with only minor CPU optimizations in place.
// Following these functions are a number of optimized variants,
// which each deploy a different combination of optimizations strategies. By
// default, RSBench will only run the baseline implementation. Optimized variants
// must be specifically selected using the "-k <optimized variant ID>" command
// line argument.
////////////////////////////////////////////////////////////////////////////////////
void lookup (
int* num_nucs,
double* concs,
int* mats,
int* verification,
int* n_windows,
double* pseudo_K0RS,
Window* windows,
Pole* poles,
int n_lookups,
int input_doppler,
int input_numL,
int max_num_windows,
int max_num_poles,
int max_num_nucs ,
sycl::nd_item<3> item_ct1) {
// get the index to operate on, first dimemsion
size_t i = item_ct1.get_local_id(2) +
item_ct1.get_group(2) * item_ct1.get_local_range().get(2);
if (i < n_lookups) {
// Set the initial seed value
uint64_t seed = STARTING_SEED;
// Forward seed to lookup index (we need 2 samples per lookup)
seed = fast_forward_LCG(seed, 2*i);
// Randomly pick an energy and material for the particle
double p_energy = LCG_random_double(&seed);
int mat = pick_mat(&seed);
// debugging
//printf("E = %lf mat = %d\n", p_energy, mat);
double macro_xs_vector[4] = {0};
// Perform macroscopic Cross Section Lookup
calculate_macro_xs( macro_xs_vector, mat, p_energy,
input_doppler, //in,
input_numL,
num_nucs, mats,
max_num_nucs, concs, n_windows, pseudo_K0RS, windows, poles,
max_num_windows, max_num_poles );
// For verification, and to prevent the compiler from optimizing
// all work out, we interrogate the returned macro_xs_vector array
// to find its maximum value index, then increment the verification
// value by that index. In this implementation, we store to a global
// array that will get tranferred back and reduced on the host.
double max = -DBL_MAX;
int max_idx = 0;
for(int j = 0; j < 4; j++ )
{
if( macro_xs_vector[j] > max )
{
max = macro_xs_vector[j];
max_idx = j;
}
}
verification[i] = max_idx+1;
}
}
void run_event_based_simulation(Input in, SimulationData SD, unsigned long * vhash_result, double * kernel_init_time )
{
dpct::device_ext &dev_ct1 = dpct::get_current_device();
sycl::queue &q_ct1 = dev_ct1.default_queue();
// Let's create an extra verification array to reduce manually later on
printf("Allocating an additional %.1lf MB of memory for verification arrays...\n", in.lookups * sizeof(int) /1024.0/1024.0);
int * verification_host = (int *) malloc(in.lookups * sizeof(int));
// Timers
double start = get_time();
double stop;
// Scope here is important, as when we exit this blocl we will automatically sync with device
// to ensure all work is done and that we can read from verification_host array.
{
// create a queue using the default device for the platform (cpu, gpu)
dpct::device_info devProp;
dpct::dev_mgr::instance().get_device(0).get_device_info(devProp);
printf("Running on: %s\n", devProp.get_name());
printf("Initializing device buffers and JIT compiling kernel...\n");
////////////////////////////////////////////////////////////////////////////////
// Create Device Buffers
////////////////////////////////////////////////////////////////////////////////
int *verification_d = nullptr;
int *mats_d = nullptr ;
int *num_nucs_d = nullptr;
int *n_windows_d = nullptr;
double *concs_d = nullptr;
double *pseudo_K0RS_d = nullptr;
Window *windows_d = nullptr;
Pole *poles_d = nullptr;
// assign SYCL buffer to existing memory
//buffer<int, 1> num_nucs_d(SD.num_nucs,SD.length_num_nucs);
num_nucs_d = sycl::malloc_device<int>(SD.length_num_nucs, q_ct1);
q_ct1.memcpy(num_nucs_d, SD.num_nucs, sizeof(int) * SD.length_num_nucs)
.wait();
//buffer<double, 1> concs_d(SD.concs, SD.length_concs);
concs_d = sycl::malloc_device<double>(SD.length_concs, q_ct1);
q_ct1.memcpy(concs_d, SD.concs, sizeof(double) * SD.length_concs).wait();
//buffer<int, 1> mats_d(SD.mats, SD.length_mats);
mats_d = sycl::malloc_device<int>(SD.length_mats, q_ct1);
q_ct1.memcpy(mats_d, SD.mats, sizeof(int) * SD.length_mats).wait();
//buffer<int, 1> n_windows_d(SD.n_windows, SD.length_n_windows);
n_windows_d = sycl::malloc_device<int>(SD.length_n_windows, q_ct1);
q_ct1.memcpy(n_windows_d, SD.n_windows, sizeof(int) * SD.length_n_windows)
.wait();
//buffer<Pole, 1> poles_d(SD.poles, SD.length_poles);
poles_d = sycl::malloc_device<Pole>(SD.length_poles, q_ct1);
q_ct1.memcpy(poles_d, SD.poles, sizeof(Pole) * SD.length_poles).wait();
//buffer<Window, 1> windows_d(SD.windows, SD.length_windows);
windows_d = sycl::malloc_device<Window>(SD.length_windows, q_ct1);
q_ct1.memcpy(windows_d, SD.windows, sizeof(Window) * SD.length_windows)
.wait();
//buffer<double, 1> pseudo_K0RS_d(SD.pseudo_K0RS, SD.length_pseudo_K0RS);
pseudo_K0RS_d = sycl::malloc_device<double>(SD.length_pseudo_K0RS, q_ct1);
q_ct1
.memcpy(pseudo_K0RS_d, SD.pseudo_K0RS,
sizeof(double) * SD.length_pseudo_K0RS)
.wait();
//buffer<int, 1> verification_d(verification_host, in.lookups);
verification_d = sycl::malloc_device<int>(in.lookups, q_ct1);
q_ct1.memcpy(verification_d, verification_host, sizeof(int) * in.lookups)
.wait();
////////////////////////////////////////////////////////////////////////////////
// XS Lookup Simulation Loop
////////////////////////////////////////////////////////////////////////////////
q_ct1.submit([&](sycl::handler &cgh) {
cgh.parallel_for(
sycl::nd_range<3>(sycl::range<3>(1, 1, (in.lookups + 255) / 256) *
sycl::range<3>(1, 1, 256),
sycl::range<3>(1, 1, 256)),
[=](sycl::nd_item<3> item_ct1) {
lookup(num_nucs_d, concs_d, mats_d, verification_d, n_windows_d,
pseudo_K0RS_d, windows_d, poles_d, in.lookups, in.doppler,
in.numL, SD.max_num_windows, SD.max_num_poles, SD.max_num_nucs,
item_ct1);
});
});
stop = get_time();
printf("Kernel initialization, compilation, and launch took %.2lf seconds.\n", stop-start);
printf("Beginning event based simulation...\n");
q_ct1.memcpy(verification_host, verification_d, sizeof(int) * in.lookups)
.wait();
sycl::free(verification_d, q_ct1);
sycl::free(mats_d, q_ct1);
sycl::free(num_nucs_d, q_ct1);
sycl::free(concs_d, q_ct1);
sycl::free(n_windows_d, q_ct1);
sycl::free(windows_d, q_ct1);
sycl::free(poles_d, q_ct1);
sycl::free(pseudo_K0RS_d, q_ct1);
sycl::free(windows_d, q_ct1);
}
// Host reduces the verification array
unsigned long long verification_scalar = 0;
for( int i = 0; i < in.lookups; i++ )
verification_scalar += verification_host[i];
*vhash_result = verification_scalar;
*kernel_init_time = stop-start;
}
template <class INT_T, class DOUBLE_T, class WINDOW_T, class POLE_T >
void calculate_macro_xs( double * macro_xs, int mat, double E, int input_doppler, int input_numL, INT_T num_nucs, INT_T mats, int max_num_nucs, DOUBLE_T concs, INT_T n_windows, DOUBLE_T pseudo_K0Rs, WINDOW_T windows, POLE_T poles, int max_num_windows, int max_num_poles )
{
// zero out macro vector
for( int i = 0; i < 4; i++ )
macro_xs[i] = 0;
// for nuclide in mat
for( int i = 0; i < num_nucs[mat]; i++ )
{
double micro_xs[4];
int nuc = mats[mat * max_num_nucs + i];
if( input_doppler == 1 )
calculate_micro_xs_doppler( micro_xs, nuc, E, input_numL, n_windows, pseudo_K0Rs, windows, poles, max_num_windows, max_num_poles);
else
calculate_micro_xs( micro_xs, nuc, E, input_numL, n_windows, pseudo_K0Rs, windows, poles, max_num_windows, max_num_poles);
for( int j = 0; j < 4; j++ )
{
macro_xs[j] += micro_xs[j] * concs[mat * max_num_nucs + i];
}
// Debug
/*
printf("E = %.2lf, mat = %d, macro_xs[0] = %.2lf, macro_xs[1] = %.2lf, macro_xs[2] = %.2lf, macro_xs[3] = %.2lf\n",
E, mat, macro_xs[0], macro_xs[1], macro_xs[2], macro_xs[3] );
*/
}
// Debug
/*
printf("E = %.2lf, mat = %d, macro_xs[0] = %.2lf, macro_xs[1] = %.2lf, macro_xs[2] = %.2lf, macro_xs[3] = %.2lf\n",
E, mat, macro_xs[0], macro_xs[1], macro_xs[2], macro_xs[3] );
*/
}
// No Temperature dependence (i.e., 0K evaluation)
template <class INT_T, class DOUBLE_T, class WINDOW_T, class POLE_T >
void calculate_micro_xs( double * micro_xs, int nuc, double E, int input_numL, INT_T n_windows, DOUBLE_T pseudo_K0RS, WINDOW_T windows, POLE_T poles, int max_num_windows, int max_num_poles)
{
// MicroScopic XS's to Calculate
double sigT;
double sigA;
double sigF;
double sigE;
// Calculate Window Index
double spacing = 1.0 / n_windows[nuc];
int window = (int) ( E / spacing );
if( window == n_windows[nuc] )
window--;
// Calculate sigTfactors
RSComplex sigTfactors[4]; // Of length input.numL, which is always 4
calculate_sig_T(nuc, E, input_numL, pseudo_K0RS, sigTfactors );
// Calculate contributions from window "background" (i.e., poles outside window (pre-calculated)
Window w = windows[nuc * max_num_windows + window];
sigT = E * w.T;
sigA = E * w.A;
sigF = E * w.F;
// Loop over Poles within window, add contributions
for( int i = w.start; i < w.end; i++ )
{
RSComplex PSIIKI;
RSComplex CDUM;
Pole pole = poles[nuc * max_num_poles + i];
RSComplex t1 = {0, 1};
RSComplex t2 = {sycl::sqrt(E), 0};
PSIIKI = c_div( t1 , c_sub(pole.MP_EA,t2) );
RSComplex E_c = {E, 0};
CDUM = c_div(PSIIKI, E_c);
sigT += (c_mul(pole.MP_RT, c_mul(CDUM, sigTfactors[pole.l_value])) ).r;
sigA += (c_mul( pole.MP_RA, CDUM)).r;
sigF += (c_mul(pole.MP_RF, CDUM)).r;
}
sigE = sigT - sigA;
micro_xs[0] = sigT;
micro_xs[1] = sigA;
micro_xs[2] = sigF;
micro_xs[3] = sigE;
}
// Temperature Dependent Variation of Kernel
// (This involves using the Complex Faddeeva function to
// Doppler broaden the poles within the window)
template <class INT_T, class DOUBLE_T, class WINDOW_T, class POLE_T >
void calculate_micro_xs_doppler( double * micro_xs, int nuc, double E, int input_numL, INT_T n_windows, DOUBLE_T pseudo_K0RS, WINDOW_T windows, POLE_T poles, int max_num_windows, int max_num_poles )
{
// MicroScopic XS's to Calculate
double sigT;
double sigA;
double sigF;
double sigE;
// Calculate Window Index
double spacing = 1.0 / n_windows[nuc];
int window = (int) ( E / spacing );
if( window == n_windows[nuc] )
window--;
// Calculate sigTfactors
RSComplex sigTfactors[4]; // Of length input.numL, which is always 4
calculate_sig_T(nuc, E, input_numL, pseudo_K0RS, sigTfactors );
// Calculate contributions from window "background" (i.e., poles outside window (pre-calculated)
Window w = windows[nuc * max_num_windows + window];
sigT = E * w.T;
sigA = E * w.A;
sigF = E * w.F;
double dopp = 0.5;
// Loop over Poles within window, add contributions
for( int i = w.start; i < w.end; i++ )
{
Pole pole = poles[nuc * max_num_poles + i];
// Prep Z
RSComplex E_c = {E, 0};
RSComplex dopp_c = {dopp, 0};
RSComplex Z = c_mul(c_sub(E_c, pole.MP_EA), dopp_c);
// Evaluate Fadeeva Function
RSComplex faddeeva = fast_nuclear_W( Z );
// Update W
sigT += (c_mul( pole.MP_RT, c_mul(faddeeva, sigTfactors[pole.l_value]) )).r;
sigA += (c_mul( pole.MP_RA , faddeeva)).r;
sigF += (c_mul( pole.MP_RF , faddeeva)).r;
}
sigE = sigT - sigA;
micro_xs[0] = sigT;
micro_xs[1] = sigA;
micro_xs[2] = sigF;
micro_xs[3] = sigE;
}
// picks a material based on a probabilistic distribution
int pick_mat( uint64_t * seed )
{
// I have a nice spreadsheet supporting these numbers. They are
// the fractions (by volume) of material in the core. Not a
// *perfect* approximation of where XS lookups are going to occur,
// but this will do a good job of biasing the system nonetheless.
double dist[12];
dist[0] = 0.140; // fuel
dist[1] = 0.052; // cladding
dist[2] = 0.275; // cold, borated water
dist[3] = 0.134; // hot, borated water
dist[4] = 0.154; // RPV
dist[5] = 0.064; // Lower, radial reflector
dist[6] = 0.066; // Upper reflector / top plate
dist[7] = 0.055; // bottom plate
dist[8] = 0.008; // bottom nozzle
dist[9] = 0.015; // top nozzle
dist[10] = 0.025; // top of fuel assemblies
dist[11] = 0.013; // bottom of fuel assemblies
double roll = LCG_random_double(seed);
// makes a pick based on the distro
for( int i = 0; i < 12; i++ )
{
double running = 0;
for( int j = i; j > 0; j-- )
running += dist[j];
if( roll < running )
return i;
}
return 0;
}
template <class DOUBLE_T>
void calculate_sig_T( int nuc, double E, int input_numL, DOUBLE_T pseudo_K0RS, RSComplex * sigTfactors )
{
double phi;
for( int i = 0; i < 4; i++ )
{
phi = pseudo_K0RS[nuc * input_numL + i] * sycl::sqrt(E);
if( i == 1 )
phi -= -sycl::atan(phi);
else if( i == 2 )
phi -= sycl::atan(3.0 * phi / (3.0 - phi * phi));
else if( i == 3 )
phi -= sycl::atan(phi * (15.0 - phi * phi) / (15.0 - 6.0 * phi * phi));
phi *= 2.0;
sigTfactors[i].r = sycl::cos(phi);
sigTfactors[i].i = -sycl::sin(phi);
}
}
// This function uses a combination of the Abrarov Approximation
// and the QUICK_W three term asymptotic expansion.
// Only expected to use Abrarov ~0.5% of the time.
RSComplex fast_nuclear_W( RSComplex Z )
{
// Abrarov
if( c_abs(Z) < 6.0 )
{
// Precomputed parts for speeding things up
// (N = 10, Tm = 12.0)
RSComplex prefactor = {0, 8.124330e+01};
double an[10] = {
2.758402e-01,
2.245740e-01,
1.594149e-01,
9.866577e-02,
5.324414e-02,
2.505215e-02,
1.027747e-02,
3.676164e-03,
1.146494e-03,
3.117570e-04
};
double neg_1n[10] = {
-1.0,
1.0,
-1.0,
1.0,
-1.0,
1.0,
-1.0,
1.0,
-1.0,
1.0
};
double denominator_left[10] = {
9.869604e+00,
3.947842e+01,
8.882644e+01,
1.579137e+02,
2.467401e+02,
3.553058e+02,
4.836106e+02,
6.316547e+02,
7.994380e+02,
9.869604e+02
};
RSComplex t1 = {0, 12};
RSComplex t2 = {12, 0};
RSComplex i = {0,1};
RSComplex one = {1, 0};
RSComplex W = c_div(c_mul(i, ( c_sub(one, fast_cexp(c_mul(t1, Z))) )) , c_mul(t2, Z));
RSComplex sum = {0,0};
for( int n = 0; n < 10; n++ )
{
RSComplex t3 = {neg_1n[n], 0};
RSComplex top = c_sub(c_mul(t3, fast_cexp(c_mul(t1, Z))), one);
RSComplex t4 = {denominator_left[n], 0};
RSComplex t5 = {144, 0};
RSComplex bot = c_sub(t4, c_mul(t5,c_mul(Z,Z)));
RSComplex t6 = {an[n], 0};
sum = c_add(sum, c_mul(t6, c_div(top,bot)));
}
W = c_add(W, c_mul(prefactor, c_mul(Z, sum)));
return W;
}
else
{
// QUICK_2 3 Term Asymptotic Expansion (Accurate to O(1e-6)).
// Pre-computed parameters
RSComplex a = {0.512424224754768462984202823134979415014943561548661637413182,0};
RSComplex b = {0.275255128608410950901357962647054304017026259671664935783653, 0};
RSComplex c = {0.051765358792987823963876628425793170829107067780337219430904, 0};
RSComplex d = {2.724744871391589049098642037352945695982973740328335064216346, 0};
RSComplex i = {0,1};
RSComplex Z2 = c_mul(Z, Z);
// Three Term Asymptotic Expansion
RSComplex W = c_mul(c_mul(Z,i), (c_add(c_div(a,(c_sub(Z2, b))) , c_div(c,(c_sub(Z2, d))))));
return W;
}
}
double LCG_random_double(uint64_t * seed)
{
const uint64_t m = 9223372036854775808ULL; // 2^63
const uint64_t a = 2806196910506780709ULL;
const uint64_t c = 1ULL;
*seed = (a * (*seed) + c) % m;
return (double) (*seed) / (double) m;
}
uint64_t LCG_random_int(uint64_t * seed)
{
const uint64_t m = 9223372036854775808ULL; // 2^63
const uint64_t a = 2806196910506780709ULL;
const uint64_t c = 1ULL;
*seed = (a * (*seed) + c) % m;
return *seed;
}
uint64_t fast_forward_LCG(uint64_t seed, uint64_t n)
{
const uint64_t m = 9223372036854775808ULL; // 2^63
uint64_t a = 2806196910506780709ULL;
uint64_t c = 1ULL;
n = n % m;
uint64_t a_new = 1;
uint64_t c_new = 0;
while(n > 0)
{
if(n & 1)
{
a_new *= a;
c_new = c_new * a + c;
}
c *= (a + 1);
a *= a;
n >>= 1;
}
return (a_new * seed + c_new) % m;
}
// Complex arithmetic functions
RSComplex c_add( RSComplex A, RSComplex B)
{
RSComplex C;
C.r = A.r + B.r;
C.i = A.i + B.i;
return C;
}
RSComplex c_sub( RSComplex A, RSComplex B)
{
RSComplex C;
C.r = A.r - B.r;
C.i = A.i - B.i;
return C;
}
RSComplex c_mul( RSComplex A, RSComplex B)
{
double a = A.r;
double b = A.i;
double c = B.r;
double d = B.i;
RSComplex C;
C.r = (a*c) - (b*d);
C.i = (a*d) + (b*c);
return C;
}
RSComplex c_div( RSComplex A, RSComplex B)
{
double a = A.r;
double b = A.i;
double c = B.r;
double d = B.i;
RSComplex C;
double denom = c*c + d*d;
C.r = ( (a*c) + (b*d) ) / denom;
C.i = ( (b*c) - (a*d) ) / denom;
return C;
}
double c_abs( RSComplex A)
{ return sycl::sqrt(A.r * A.r + A.i * A.i); }
// Fast (but inaccurate) exponential function
// Written By "ACMer":
// https://codingforspeed.com/using-faster-exponential-approximation/
// We use our own to avoid small differences in compiler specific
// exp() intrinsic implementations that make it difficult to verify
// if the code is working correctly or not.
double fast_exp(double x)
{
x = 1.0 + x * 0.000244140625;
x *= x; x *= x; x *= x; x *= x;
x *= x; x *= x; x *= x; x *= x;
x *= x; x *= x; x *= x; x *= x;
return x;
}
// Implementation based on:
// z = x + iy
// cexp(z) = e^x * (cos(y) + i * sin(y))
RSComplex fast_cexp( RSComplex z )
{
double x = z.r;
double y = z.i;
// For consistency across architectures, we
// will use our own exponetial implementation
//double t1 = exp(x);
double t1 = fast_exp(x);
double t2 = sycl::cos(y);
double t3 = sycl::sin(y);
RSComplex t4 = {t2, t3};
RSComplex t5 = {t1, 0};
RSComplex result = c_mul(t5, (t4));
return result;
}
| [
"[email protected]"
] | |
8cb02ca239f2910cae2b5d75e810bb7270fddd03 | 36966f89541220e4802461fde73884330e1c3716 | /CyberSoftMedicine/NeuralProcess.cpp | 2c291556e35ef5b7df092ee2486837ec2125974a | [
"MIT"
] | permissive | snowdence/ContestScience_DetectCancer | 740b6bc881a7544f921370c803f0be297bc54388 | a50a1bf0130ce0fd099f3424ce4c9c9a8bfaf137 | refs/heads/master | 2021-06-19T13:11:08.727366 | 2017-07-21T08:48:06 | 2017-07-21T08:48:06 | 97,615,179 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,502 | cpp | /******************************************************************************************/
/*********** Author : Tran Minh Duc (Snowdence) *******************/
/*********** Email : [email protected] *******************/
/*********** Phone : 0982 259 245 *******************
/*********** Project: CyberSoftMedicine - CyberCorp Inc. *******************/
/*********** Date : 9:51 09/04/2017 *******************/
/*********** Compile: Visual Studio 2017 *******************/
/******************************************************************************************/
#include <iostream>
#include <fstream>
#include <math.h>
#include "NeuralProcess.h"
using namespace std;
NeuralProcess::NeuralProcess(NeuralLayer* architectneuralLayer) :neuralLayer(architectneuralLayer),
epoch(0),
learningRate(0.001), momentum(0.9), desiredAccuracy(70), trainingSetAccuracy(0), validationSetAccuracy(0), generalizationSetAccuracy(0), trainingSetMSE(0), validationSetMSE(0), generalizationSetMSE(0)
{
deltaInputToHidden = new(double*[neuralLayer->numInputLayer + 1]);
for (int i = 0; i <= neuralLayer->numInputLayer; i++)
{
deltaInputToHidden[i] = new (double[neuralLayer->numHiddenLayer]);
for (int j = 0; j < neuralLayer->numHiddenLayer; j++) {
deltaInputToHidden[i][j] = 0;
}
}
deltaHiddenToOutput = new(double*[neuralLayer->numHiddenLayer + 1]);
for (int i = 0; i <= neuralLayer->numHiddenLayer; i++)
{
deltaHiddenToOutput[i] = new (double[neuralLayer->numOutputLayer]);
for (int j = 0; j < neuralLayer->numOutputLayer; j++) {
deltaHiddenToOutput[i][j] = 0;
}
}
//create error gradient vector
//--------------------------------------------------------------------------------------------------------
hiddenErrorGradients = new(double[neuralLayer->numHiddenLayer + 1]);
for (int i = 0; i <= neuralLayer->numHiddenLayer; i++) {
hiddenErrorGradients[i] = 0;
}
outputErrorGradients = new(double[neuralLayer->numOutputLayer + 1]);
for (int i = 0; i <= neuralLayer->numOutputLayer; i++) {
outputErrorGradients[i] = 0;
}
}
NeuralProcess::~NeuralProcess()
{
// release all if necessary
}
void NeuralProcess::setTrainingParameters(double lR, double m, bool batch)
{
learningRate = lR;
momentum = m;
BatchMode = batch;
}
void NeuralProcess::setStoppingConditions(int mEpochs, double dAccuracy)
{
maxEpochs = mEpochs;
desiredAccuracy = dAccuracy;
}
void NeuralProcess::trainNetwork(NeuralDataPackage * dataPackage)
{
cout << endl << " Neural Network For Dectect Cancer [CyBerMedicine] System: " << endl
<< "==========================================================================" << endl
<< " Author : Snowdence " << endl
<< " LearningRate: " << learningRate << ", Momen: " << momentum << ", Epoch: " << maxEpochs << endl
<< " " << neuralLayer->numInputLayer << " Input Neurons, " << neuralLayer->numHiddenLayer << " Hidden Neurons, " << neuralLayer->numOutputLayer << " Output Neurons" << endl
<< "==========================================================================" << endl << endl;
// default value of epoch
epoch = 0;
// Train my network
//--------------------------------------------------------------------------------------------------------
while ((trainingSetAccuracy < desiredAccuracy || generalizationSetAccuracy < desiredAccuracy) && epoch < maxEpochs)
{
// store previous epoch
double previousTAccuracy = trainingSetAccuracy;
double previousGAccuracy = generalizationSetAccuracy;
//use training set to train
runTrainingEpoch(dataPackage->trainingSet);
//get ERROR
generalizationSetAccuracy = neuralLayer->getAccuracy(dataPackage->generalizationSet);
generalizationSetMSE = neuralLayer->getMSE(dataPackage->generalizationSet);
// IF this Greater, update into screen
if (ceil(previousTAccuracy) != ceil(trainingSetAccuracy) || ceil(previousGAccuracy) != ceil(generalizationSetAccuracy))
{
cout << "Epoch [The he] :" << epoch;
cout << " Training [Tap huan luyen]:" << trainingSetAccuracy << "%, MSE [SAI SO]: " << trainingSetMSE;
cout << " Generation [Tap thu nghiem]:" << generalizationSetAccuracy << "%, MSE [SAI SO]: " << generalizationSetMSE << endl;
}
//increase epoch
epoch++;
}
//ERROR
validationSetAccuracy = neuralLayer->getAccuracy(dataPackage->validationSet);
validationSetMSE = neuralLayer->getMSE(dataPackage->validationSet);
//REsult error
cout << endl << "[CyBerMedicine] Dao tao hoan thanh voi the he: " << epoch << endl;
cout << " Accuracy (Do chinh xac): " << validationSetAccuracy << endl;
cout << " MSE (SAI SO HAM BINH PHUONG LOI): " << validationSetMSE << endl << endl;
}
inline double NeuralProcess::getOutputErrorGradient(double desiredValue, double outputValue)
{
return outputValue * (1 - outputValue) * (desiredValue - outputValue);
}
double NeuralProcess::getHiddenErrorGradient(int j)
{
double weightedSum = 0;
for (int k = 0; k < neuralLayer->numOutputLayer; k++) {
weightedSum += neuralLayer->weightHiddenToOutput[j][k] * outputErrorGradients[k];
}
//ERROR gradient
return neuralLayer->hiddenLayer[j] * (1 - neuralLayer->hiddenLayer[j]) * weightedSum;
}
void NeuralProcess::runTrainingEpoch(std::vector<DataEntry*> trainingDataSet)
{
//incorrect Pattern
double incorrectPatterns = 0;
double mse = 0;
for (int tp = 0; tp < (int)trainingDataSet.size(); tp++)
{
neuralLayer->feedForward(trainingDataSet[tp]->pattern);
backpropagate(trainingDataSet[tp]->target);
bool patternCorrect = true;
// Kiem tra so voi gia tri ky vong
for (int k = 0; k < neuralLayer->numOutputLayer; k++)
{
if (neuralLayer->transferOutput(neuralLayer->outputLayer[k]) != trainingDataSet[tp]->target[k]) { patternCorrect = false; }
//tinh toan loi
mse += pow((neuralLayer->outputLayer[k] - trainingDataSet[tp]->target[k]), 2);
}
//count ++
if (!patternCorrect) incorrectPatterns++;
}
// Batch learning update weight
if (BatchMode) updateWeights();
//update MSE
trainingSetAccuracy = 100 - (incorrectPatterns / trainingDataSet.size() * 100);
trainingSetMSE = mse / (neuralLayer->numOutputLayer * trainingDataSet.size());
}
void NeuralProcess::backpropagate(double * desiredOutputs)
{
// lan truyen nguoc
//--------------------------------------------------------------------------------------------------------
for (int k = 0; k < neuralLayer->numOutputLayer; k++)
{
//output neuron
outputErrorGradients[k] = getOutputErrorGradient(desiredOutputs[k], neuralLayer->outputLayer[k]);
//hidden neuron
for (int j = 0; j <= neuralLayer->numHiddenLayer; j++)
{
// tinh toan do sai khac trong so
if (!BatchMode) {
deltaHiddenToOutput[j][k] = learningRate * neuralLayer->hiddenLayer[j] * outputErrorGradients[k] + momentum * deltaHiddenToOutput[j][k];
}
else {
deltaHiddenToOutput[j][k] += learningRate * neuralLayer->hiddenLayer[j] * outputErrorGradients[k];
}
}
}
// EDIT
//--------------------------------------------------------------------------------------------------------
for (int j = 0; j < neuralLayer->numHiddenLayer; j++)
{
//error hidden
hiddenErrorGradients[j] = getHiddenErrorGradient(j);
//input + bias to hidden
for (int i = 0; i <= neuralLayer->numInputLayer; i++)
{
//tinh toan thay doi
if (!BatchMode) deltaInputToHidden[i][j] = learningRate * neuralLayer->inputLayer[i] * hiddenErrorGradients[j] + momentum * deltaInputToHidden[i][j];
else deltaInputToHidden[i][j] += learningRate * neuralLayer->inputLayer[i] * hiddenErrorGradients[j];
}
}
if (!BatchMode) updateWeights();
}
void NeuralProcess::updateWeights()
{
//input -> hidden weights
//--------------------------------------------------------------------------------------------------------
for (int i = 0; i <= neuralLayer->numInputLayer; i++)
{
for (int j = 0; j < neuralLayer->numHiddenLayer; j++)
{
//update weight
neuralLayer->weightInputToHidden[i][j] += deltaInputToHidden[i][j];
//batchmode clear previous
if (BatchMode) deltaInputToHidden[i][j] = 0;
}
}
//hidden -> output weights
//--------------------------------------------------------------------------------------------------------
for (int j = 0; j <= neuralLayer->numHiddenLayer; j++)
{
for (int k = 0; k < neuralLayer->numOutputLayer; k++)
{
//update weight
neuralLayer->weightHiddenToOutput[j][k] += deltaHiddenToOutput[j][k];
//clear if batch mode
if (BatchMode)deltaHiddenToOutput[j][k] = 0;
}
}
} | [
"[email protected]"
] | |
675f8c203466fb30d1651363e1e511c0acfc633e | f31c0986ebc80731362a136f99bb6be461690440 | /src/UILayer/SearchDlg.h | d2910b1071c5e6b2a34e6045d2d861536db63f8e | [] | no_license | witeyou/easyMule | 9c3e0af72c49f754704f029a6c3c609f7300811a | ac91abd9cdf35dd5bb697e175e8d07a89c496944 | refs/heads/master | 2023-03-30T16:19:27.200126 | 2021-03-26T12:22:52 | 2021-03-26T12:22:52 | 351,774,027 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,879 | h | /*
* $Id: SearchDlg.h 4483 2008-01-02 09:19:06Z soarchin $
*
* this file is part of easyMule
* Copyright (C)2002-2008 VeryCD Dev Team ( strEmail.Format("%s@%s", "emuledev", "verycd.com") / http: * www.easymule.org )
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#pragma once
struct SSearchParams;
class CSearchResultsWnd;
class CSearchParamsWnd;
class CSearchFile;
class CClosableTabCtrl;
///////////////////////////////////////////////////////////////////////////////
// CSearchDlg frame
class CSearchDlg : public CFrameWnd
{
DECLARE_DYNCREATE(CSearchDlg)
public:
CSearchDlg(); // protected constructor used by dynamic creation
virtual ~CSearchDlg();
CSearchResultsWnd* m_pwndResults;
BOOL Create(CWnd* pParent);
void Localize();
void CreateMenus();
void RemoveResult(const CSearchFile* toremove);
bool DoNewEd2kSearch(SSearchParams* pParams);
bool DoNewKadSearch(SSearchParams* pParams);
void CancelEd2kSearch();
void CancelKadSearch(UINT uSearchID);
bool CanSearchRelatedFiles() const;
void SearchRelatedFiles(const CAbstractFile* file);
void DownloadSelected();
void DownloadSelected(bool paused);
bool CanDeleteSearch(uint32 nSearchID) const;
bool CanDeleteAllSearches() const;
void DeleteSearch(uint32 nSearchID);
void DeleteAllSearches();
void LocalEd2kSearchEnd(UINT count, bool bMoreResultsAvailable);
void AddGlobalEd2kSearchResults(UINT count);
bool CreateNewTab(SSearchParams* pParams);
void ShowSearchSelector(bool visible);
CClosableTabCtrl& GetSearchSelector();
int GetSelectedCat();
void UpdateCatTabs();
void SaveAllSettings();
BOOL SaveSearchStrings();
void ResetHistory();
void SetToolTipsDelay(UINT uDelay);
void DeleteAllSearchListCtrlItems();
BOOL IsSearchParamsWndVisible() const;
void OpenParametersWnd();
void DockParametersWnd();
void UpdateSearch(CSearchFile* pSearchFile);
protected:
//CSearchParamsWnd* m_pwndParams;
virtual BOOL PreTranslateMessage(MSG* pMsg);
DECLARE_MESSAGE_MAP()
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
afx_msg void OnShowWindow(BOOL bShow, UINT nStatus);
afx_msg void OnSetFocus(CWnd* pOldWnd);
afx_msg void OnClose();
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
};
| [
"[email protected]"
] | |
292bd4e100d6ea330503dd0af64df18cb2745553 | f84270021ecb23d4879c542acf1682b085b2d1e4 | /BmpButton.h | 228dc636234018865c2d5032572df90280a060a0 | [] | no_license | nietoperz809/OxoMemory | 04c3ba5eb529a570661ca84c3ca917a9e7cba9cd | 65714564fe32276cb1170595f373ec94cc97ad39 | refs/heads/master | 2021-01-18T17:26:31.346050 | 2017-03-31T09:13:47 | 2017-03-31T09:13:47 | 86,800,534 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,058 | h | // BmpButton.h : header file
//
/////////////////////////////////////////////////////////////////////////////
// CBmpButton window
class CBmpButton : public CButton
{
// Construction
public:
CBmpButton();
// Attributes
public:
// Operations
public:
void Create (CWnd *parent, int id);
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CBmpButton)
//}}AFX_VIRTUAL
// Implementation
public:
virtual ~CBmpButton();
BOOL m_paintflag;
void ShowBitmap (BOOL show_or_hide);
void SetBitmap (LPCTSTR bmpid);
CBitmap m_bitmap;
CString m_bmpid;
HCURSOR m_hcursor;
// Generated message map functions
protected:
//{{AFX_MSG(CBmpButton)
afx_msg void OnPaint();
afx_msg void OnLButtonDown(UINT nFlags, CPoint point);
afx_msg void OnLButtonDblClk(UINT nFlags, CPoint point);
afx_msg BOOL OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message);
afx_msg void OnLButtonUp(UINT nFlags, CPoint point);
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
| [
"[email protected]"
] | |
1f426733e9821cf7ddea155acfff1bb6f65fdb68 | 4c9df8b884f736c56ca535d1adbcd0cd01181796 | /C++ code/GpBCS_S.C.CPMC/SC_afqmcConstraintPathBP_4.1_ChargeContinuous_afqmclab_icf_ExactDensityinput/source/afqmcConstraintPathBackPropagation.cpp | ea572d253ddb76b2b01aa95f36cf6ed6c136fcb6 | [] | no_license | icf/Code | 1f52725f961791cb00e9632149854f47c82f0992 | 10e968a9172334b0ba36865dceed43081c1d907d | refs/heads/master | 2021-05-16T00:43:26.665642 | 2019-08-02T21:13:51 | 2019-08-02T21:13:51 | 106,960,448 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,076 | cpp | //
// Created by Hao Shi on 2/10/19.
//
#include "../include/afqmcConstraintPath.h"
#include "../include/afqmcBackPropagationPop.h"
using namespace std;
using namespace tensor_hao;
void AfqmcConstraintPath::prepareBackPropagation()
{
isBP = true;
BPIndex = 0;
for (int i = 0; i < method.walkerSizePerThread; ++i)
{
walkerBackup[i] = walker[i];
}
}
void AfqmcConstraintPath::prepareBackPropagationMeasAndNextBackup()
{
swap(walkerBPMeasure, walkerBackup);
if( method.backPropagationStep>=method.measureSkipStep)
{
twoBodyAuxBPMeasure = twoBodyAuxBackup;
reWeightBPMeasure = reWeightBackup;
}
else
{
swap(twoBodyAuxBPMeasure, twoBodyAuxBackup);
swap(reWeightBPMeasure, reWeightBackup);
}
vector<int> table;
for (size_t i = 0; i < method.backPropagationStep; ++i)
{
if( tablePerThreadBackup[i].size() != 0 )
{
#ifdef MPI_HAO
if( MPIRank()==0 ) table.resize( method.walkerSize );
MPI_Gather( tablePerThreadBackup[i].data(), method.walkerSizePerThread, MPI_INT,
table.data(), method.walkerSizePerThread, MPI_INT, 0, MPI_COMM_WORLD );
#else
table = tablePerThreadBackup[i];
#endif
vector<AfqmcBackPropagationPop> BPPop;
BPPop.reserve( method.walkerSizePerThread );
for(int j=0; j<method.walkerSizePerThread; j++)
{
BPPop.push_back( AfqmcBackPropagationPop( i+1, twoBodyAuxBPMeasure[j], reWeightBPMeasure[j], walkerBPMeasure[j] ) );
}
populationControl(BPPop, table);
}
if( (i+1) == method.measureSkipStep )
{
generateWalkerBackupFromWalkerBPMeasure();
}
}
if( method.backPropagationStep >= method.measureSkipStep )
{
BPIndex = method.backPropagationStep-method.measureSkipStep;
for (size_t i = 0; i < method.backPropagationStep-method.measureSkipStep; ++i)
{
tablePerThreadBackup[i] = move( tablePerThreadBackup[i+method.measureSkipStep] );
for (int j = 0; j < method.walkerSizePerThread; ++j)
{
twoBodyAuxBackup[j][i] = move( twoBodyAuxBackup[j][i+method.measureSkipStep] );
reWeightBackup[j][i] = reWeightBackup[j][i+method.measureSkipStep];
}
}
}
else
{
isBP = false;
}
}
void AfqmcConstraintPath::generateWalkerBackupFromWalkerBPMeasure()
{
WalkerRight walkerTemp;
for(int i=0; i<method.walkerSizePerThread; i++)
{
walkerBackup[i] = walkerBPMeasure[i];
for (size_t j = 0; j < method.measureSkipStep; ++j)
{
if( twoBodyAuxBPMeasure[i][j].size() == model.getL() ) //model.getCholeskyNumber() )
{
twoBodySample = expMinusDtV.getTwoBodySampleFromAux( twoBodyAuxBPMeasure[i][j] );
twoBodySampleWalkerRightOperation.applyToRight(twoBodySample, walkerBackup[i], walkerTemp);
oneBodyWalkerRightOperation.applyToRight(expMinusDtK, walkerTemp, walkerBackup[i] );
}
if( j%method.mgsStep==0 ) walkerBackup[i].normalize();
}
}
}
vector<complex<double>> AfqmcConstraintPath::returnSumReWeight()
{
vector<complex<double> > sumReWeight(method.walkerSizePerThread);
for(int i = 0; i < method.walkerSizePerThread; ++i)
{
sumReWeight[i] = 0.0;
if(walkerIsAlive[i])
{
for(size_t j = 0; j < method.backPropagationStep; ++j)
{
sumReWeight[i] += reWeightBPMeasure[i][j];
}
}
}
complex<double> sumPerThread(0,0); for(int i = 0; i < method.walkerSizePerThread; ++i) sumPerThread += sumReWeight[i];
complex<double> sumAllThread(0,0); sumAllThread = MPISum(sumPerThread);
complex<double> average = sumAllThread/( method.walkerSize * 1.0 );
MPIBcast(average);
for(int i = 0; i < method.walkerSizePerThread; ++i) sumReWeight[i] -= average;
return sumReWeight;
}
| [
"[email protected]"
] | |
a17d7b2ac30f326422c6b77e08618efb0e1ab510 | d89112aa7026073b1a64bb8064a3e85ada773cfb | /ddmj/client/build/jsb-default/frameworks/cocos2d-x/cocos/scripting/js-bindings/auto/jsb_cocos2dx_audioengine_auto.hpp | 94216eff35014abd4b74a7ac64d89d25d91b91d0 | [
"MIT"
] | permissive | 010513/js_mj | 140b726a9f605900eee92e5da3f1e1852ac5f299 | 6243c3f97ef12b4074ef616aface817a3060bab0 | refs/heads/master | 2022-02-07T12:56:35.546498 | 2019-05-18T08:18:18 | 2019-05-18T08:18:18 | 177,548,847 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,663 | hpp | #pragma once
#include "base/ccConfig.h"
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT || CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_MAC || CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
#include "cocos/scripting/js-bindings/jswrapper/SeApi.h"
extern se::Object* __jsb_cocos2d_experimental_AudioProfile_proto;
extern se::Class* __jsb_cocos2d_experimental_AudioProfile_class;
bool js_register_cocos2d_experimental_AudioProfile(se::Object* obj);
bool register_all_audioengine(se::Object* obj);
SE_DECLARE_FUNC(js_audioengine_AudioProfile_AudioProfile);
extern se::Object* __jsb_cocos2d_experimental_AudioEngine_proto;
extern se::Class* __jsb_cocos2d_experimental_AudioEngine_class;
bool js_register_cocos2d_experimental_AudioEngine(se::Object* obj);
bool register_all_audioengine(se::Object* obj);
SE_DECLARE_FUNC(js_audioengine_AudioEngine_lazyInit);
SE_DECLARE_FUNC(js_audioengine_AudioEngine_setCurrentTime);
SE_DECLARE_FUNC(js_audioengine_AudioEngine_getVolume);
SE_DECLARE_FUNC(js_audioengine_AudioEngine_uncache);
SE_DECLARE_FUNC(js_audioengine_AudioEngine_resumeAll);
SE_DECLARE_FUNC(js_audioengine_AudioEngine_stopAll);
SE_DECLARE_FUNC(js_audioengine_AudioEngine_pause);
SE_DECLARE_FUNC(js_audioengine_AudioEngine_end);
SE_DECLARE_FUNC(js_audioengine_AudioEngine_getMaxAudioInstance);
SE_DECLARE_FUNC(js_audioengine_AudioEngine_isEnabled);
SE_DECLARE_FUNC(js_audioengine_AudioEngine_getCurrentTime);
SE_DECLARE_FUNC(js_audioengine_AudioEngine_setMaxAudioInstance);
SE_DECLARE_FUNC(js_audioengine_AudioEngine_isLoop);
SE_DECLARE_FUNC(js_audioengine_AudioEngine_pauseAll);
SE_DECLARE_FUNC(js_audioengine_AudioEngine_uncacheAll);
SE_DECLARE_FUNC(js_audioengine_AudioEngine_setVolume);
SE_DECLARE_FUNC(js_audioengine_AudioEngine_preload);
SE_DECLARE_FUNC(js_audioengine_AudioEngine_setEnabled);
SE_DECLARE_FUNC(js_audioengine_AudioEngine_play2d);
SE_DECLARE_FUNC(js_audioengine_AudioEngine_getState);
SE_DECLARE_FUNC(js_audioengine_AudioEngine_resume);
SE_DECLARE_FUNC(js_audioengine_AudioEngine_stop);
SE_DECLARE_FUNC(js_audioengine_AudioEngine_getDuration);
SE_DECLARE_FUNC(js_audioengine_AudioEngine_setLoop);
SE_DECLARE_FUNC(js_audioengine_AudioEngine_getDefaultProfile);
SE_DECLARE_FUNC(js_audioengine_AudioEngine_setFinishCallback);
SE_DECLARE_FUNC(js_audioengine_AudioEngine_getProfile);
SE_DECLARE_FUNC(js_audioengine_AudioEngine_getPlayingAudioCount);
#endif //#if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT || CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_MAC || CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
| [
"[email protected]"
] | |
03796a8d609907acc692968be98393550e15d1a1 | 59179e4f655a40b421fa9aeda9c90736b8c11b1b | /compiler/lab1/little_test.cpp | d18cccf5261af142bee94bec92988c7ef1aa5e7c | [] | no_license | wjw136/course_designing_project | ccd39da420f0de22b39fa2fea032054f4cbe8bfd | 2614928bd779bc0d996857b123e2862836d81333 | refs/heads/master | 2023-06-04T12:52:40.501335 | 2021-06-17T13:19:23 | 2021-06-17T13:19:23 | 374,384,252 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 928 | cpp | #include <iostream>
#include <windows.h>
#include <string.h>
#include <queue>
#include <math.h>
#include <map>
#include "stdio.h"
#define ll long long
#define inf 100000
#define clr1(a) memset(a, -1, sizeof(a))
#define clr(a) memset(a, 0, sizeof(a))
using namespace std;
class EE
{
public:
int a;
string b;
EE(int a)
{
this->a = a;
}
bool operator<(const EE &b) const
{
//严格弱比较 严格是说在判断的时候会用"<",而不是"<=",弱排序是因为,一旦"<"成立便认为存在"<"关系,返回ture,而忽略了"="关系和">"区别,把它们归结为false。
return this->a < b.a;
}
};
int main()
{
cout << ":111" << endl;
map<EE, string> test_set;
test_set[EE(4)] = "1";
test_set[EE(3)] = "2";
for (auto &i : test_set)
{
cout << i.first.a << " " << i.second << endl;
}
system("pause");
return 0;
}
| [
"[email protected]"
] | |
dbe8a518549a7e22734fb674115de988d21c748d | 9c81a923cd23bc169b85fd921f5de51f2acd584b | /swagger/sdrangel/code/qt5/client/SWGAirspyReport.cpp | ce054720261e9c03e1275964abfba8b65699c790 | [] | no_license | n8ohu/sdrangel | ac7c1bba387e91e32c56cb9f174f17841e54ab7c | 62e1a5f4daa502ccde0da14813b27dfe97160cdf | refs/heads/master | 2020-04-18T00:53:40.690291 | 2019-01-20T08:54:06 | 2019-01-20T08:54:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,601 | cpp | /**
* SDRangel
* This is the web REST/JSON API of SDRangel SDR software. SDRangel is an Open Source Qt5/OpenGL 3.0+ (4.3+ in Windows) GUI and server Software Defined Radio and signal analyzer in software. It supports Airspy, BladeRF, HackRF, LimeSDR, PlutoSDR, RTL-SDR, SDRplay RSP1 and FunCube --- Limitations and specifcities: * In SDRangel GUI the first Rx device set cannot be deleted. Conversely the server starts with no device sets and its number of device sets can be reduced to zero by as many calls as necessary to /sdrangel/deviceset with DELETE method. * Preset import and export from/to file is a server only feature. * Device set focus is a GUI only feature. * The following channels are not implemented (status 501 is returned): ATV and DATV demodulators, Channel Analyzer NG, LoRa demodulator * The device settings and report structures contains only the sub-structure corresponding to the device type. The DeviceSettings and DeviceReport structures documented here shows all of them but only one will be or should be present at a time * The channel settings and report structures contains only the sub-structure corresponding to the channel type. The ChannelSettings and ChannelReport structures documented here shows all of them but only one will be or should be present at a time ---
*
* OpenAPI spec version: 4.4.1
* Contact: [email protected]
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
#include "SWGAirspyReport.h"
#include "SWGHelpers.h"
#include <QJsonDocument>
#include <QJsonArray>
#include <QObject>
#include <QDebug>
namespace SWGSDRangel {
SWGAirspyReport::SWGAirspyReport(QString* json) {
init();
this->fromJson(*json);
}
SWGAirspyReport::SWGAirspyReport() {
sample_rates = nullptr;
m_sample_rates_isSet = false;
}
SWGAirspyReport::~SWGAirspyReport() {
this->cleanup();
}
void
SWGAirspyReport::init() {
sample_rates = new QList<SWGSampleRate*>();
m_sample_rates_isSet = false;
}
void
SWGAirspyReport::cleanup() {
if(sample_rates != nullptr) {
auto arr = sample_rates;
for(auto o: *arr) {
delete o;
}
delete sample_rates;
}
}
SWGAirspyReport*
SWGAirspyReport::fromJson(QString &json) {
QByteArray array (json.toStdString().c_str());
QJsonDocument doc = QJsonDocument::fromJson(array);
QJsonObject jsonObject = doc.object();
this->fromJsonObject(jsonObject);
return this;
}
void
SWGAirspyReport::fromJsonObject(QJsonObject &pJson) {
::SWGSDRangel::setValue(&sample_rates, pJson["sampleRates"], "QList", "SWGSampleRate");
}
QString
SWGAirspyReport::asJson ()
{
QJsonObject* obj = this->asJsonObject();
QJsonDocument doc(*obj);
QByteArray bytes = doc.toJson();
delete obj;
return QString(bytes);
}
QJsonObject*
SWGAirspyReport::asJsonObject() {
QJsonObject* obj = new QJsonObject();
if(sample_rates->size() > 0){
toJsonArray((QList<void*>*)sample_rates, obj, "sampleRates", "SWGSampleRate");
}
return obj;
}
QList<SWGSampleRate*>*
SWGAirspyReport::getSampleRates() {
return sample_rates;
}
void
SWGAirspyReport::setSampleRates(QList<SWGSampleRate*>* sample_rates) {
this->sample_rates = sample_rates;
this->m_sample_rates_isSet = true;
}
bool
SWGAirspyReport::isSet(){
bool isObjectUpdated = false;
do{
if(sample_rates->size() > 0){ isObjectUpdated = true; break;}
}while(false);
return isObjectUpdated;
}
}
| [
"[email protected]"
] | |
be8bd2dfd3d08b6ec0ee947675b2df29552c636d | cee83e8f6585c20d4444ddc12492e42a6b3412d5 | /dep/libopenmpt/soundlib/WAVTools.h | 57456be0a24c5fe2ea31621b17da61b71a35682d | [
"BSD-3-Clause"
] | permissive | fgenesis/tyrsound | 95b93afb71fa80a6d95b8c6771f29aea6333afd2 | a032eaf8a3a8212a764bf6c801325e67ab02473e | refs/heads/master | 2021-01-22T10:08:35.576908 | 2014-08-31T01:54:17 | 2014-08-31T01:54:17 | 10,146,874 | 4 | 0 | null | 2014-02-02T02:42:25 | 2013-05-18T20:40:23 | C | UTF-8 | C++ | false | false | 12,741 | h | /*
* WAVTools.h
* ----------
* Purpose: Definition of WAV file structures and helper functions
* Notes : (currently none)
* Authors: OpenMPT Devs
* The OpenMPT source code is released under the BSD license. Read LICENSE for more details.
*/
#pragma once
#include "ChunkReader.h"
#include "Tagging.h"
OPENMPT_NAMESPACE_BEGIN
#ifdef NEEDS_PRAGMA_PACK
#pragma pack(push, 1)
#endif
// RIFF header
struct PACKED RIFFHeader
{
// 32-Bit chunk identifiers
enum RIFFMagic
{
idRIFF = 0x46464952, // magic for WAV files
idLIST = 0x5453494C, // magic for samples in DLS banks
idWAVE = 0x45564157, // type for WAV files
idwave = 0x65766177, // type for samples in DLS banks
};
uint32 magic; // RIFF (in WAV files) or LIST (in DLS banks)
uint32 length; // Size of the file, not including magic and length
uint32 type; // WAVE (in WAV files) or wave (in DLS banks)
// Convert all multi-byte numeric values to current platform's endianness or vice versa.
void ConvertEndianness()
{
SwapBytesLE(magic);
SwapBytesLE(length);
SwapBytesLE(type);
}
};
STATIC_ASSERT(sizeof(RIFFHeader) == 12);
// General RIFF Chunk header
struct PACKED RIFFChunk
{
// 32-Bit chunk identifiers
enum ChunkIdentifiers
{
idfmt_ = 0x20746D66, // "fmt "
iddata = 0x61746164, // "data"
idpcm_ = 0x206d6370, // "pcm " (IMA ADPCM samples)
idfact = 0x74636166, // "fact" (compressed samples)
idsmpl = 0x6C706D73, // "smpl"
idLIST = 0x5453494C, // "LIST"
idxtra = 0x61727478, // "xtra"
idcue_ = 0x20657563, // "cue "
idwsmp = 0x706D7377, // "wsmp" (DLS bank samples)
id____ = 0x00000000, // Found when loading buggy MPT samples
// Identifiers in "LIST" chunk
idINAM = 0x4D414E49, // title
idISFT = 0x54465349, // software
idICOP = 0x504F4349, // copyright
idIART = 0x54524149, // artist
idIPRD = 0x44525049, // product (album)
idICMT = 0x544D4349, // comment
idIENG = 0x474E4549, // engineer
idISBJ = 0x4A425349, // subject
idIGNR = 0x524E4749, // genre
idICRD = 0x44524349, // date created
idYEAR = 0x52414559, // year
idTRCK = 0x4B435254, // track number
idTURL = 0x4C535554, // url
};
typedef ChunkIdentifiers id_type;
uint32 id; // See ChunkIdentifiers
uint32 length; // Chunk size without header
size_t GetLength() const
{
return SwapBytesReturnLE(length);
}
id_type GetID() const
{
return static_cast<id_type>(SwapBytesReturnLE(id));
}
// Convert all multi-byte numeric values to current platform's endianness or vice versa.
void ConvertEndianness()
{
SwapBytesLE(id);
SwapBytesLE(length);
}
};
STATIC_ASSERT(sizeof(RIFFChunk) == 8);
// Format Chunk
struct PACKED WAVFormatChunk
{
// Sample formats
enum SampleFormats
{
fmtPCM = 1,
fmtFloat = 3,
fmtIMA_ADPCM = 17,
fmtMP3 = 85,
fmtExtensible = 0xFFFE,
};
uint16 format; // Sample format, see SampleFormats
uint16 numChannels; // Number of audio channels
uint32 sampleRate; // Sample rate in Hz
uint32 byteRate; // Bytes per second (should be freqHz * blockAlign)
uint16 blockAlign; // Size of a sample, in bytes (do not trust this value, it's incorrect in some files)
uint16 bitsPerSample; // Bits per sample
// Convert all multi-byte numeric values to current platform's endianness or vice versa.
void ConvertEndianness()
{
SwapBytesLE(format);
SwapBytesLE(numChannels);
SwapBytesLE(sampleRate);
SwapBytesLE(byteRate);
SwapBytesLE(blockAlign);
SwapBytesLE(bitsPerSample);
}
};
STATIC_ASSERT(sizeof(WAVFormatChunk) == 16);
// Extension of the WAVFormatChunk structure, used if format == formatExtensible
struct PACKED WAVFormatChunkExtension
{
uint16 size;
uint16 validBitsPerSample;
uint32 channelMask;
uint16 subFormat;
uint8 guid[14];
// Convert all multi-byte numeric values to current platform's endianness or vice versa.
void ConvertEndianness()
{
SwapBytesLE(size);
SwapBytesLE(validBitsPerSample);
SwapBytesLE(channelMask);
SwapBytesLE(subFormat);
}
};
STATIC_ASSERT(sizeof(WAVFormatChunkExtension) == 24);
// Sample information chunk
struct PACKED WAVSampleInfoChunk
{
uint32 manufacturer;
uint32 product;
uint32 samplePeriod; // 1000000000 / sampleRate
uint32 baseNote; // MIDI base note of sample
uint32 pitchFraction;
uint32 SMPTEFormat;
uint32 SMPTEOffset;
uint32 numLoops; // number of loops
uint32 samplerData;
// Convert all multi-byte numeric values to current platform's endianness or vice versa.
void ConvertEndianness()
{
SwapBytesLE(manufacturer);
SwapBytesLE(product);
SwapBytesLE(samplePeriod);
SwapBytesLE(baseNote);
SwapBytesLE(pitchFraction);
SwapBytesLE(SMPTEFormat);
SwapBytesLE(SMPTEOffset);
SwapBytesLE(numLoops);
SwapBytesLE(samplerData);
}
// Set up information
void ConvertToWAV(uint32 freq)
{
manufacturer = 0;
product = 0;
samplePeriod = 1000000000 / freq;
baseNote = NOTE_MIDDLEC - NOTE_MIN;
pitchFraction = 0;
SMPTEFormat = 0;
SMPTEOffset = 0;
numLoops = 0;
samplerData = 0;
}
};
STATIC_ASSERT(sizeof(WAVSampleInfoChunk) == 36);
// Sample loop information chunk (found after WAVSampleInfoChunk in "smpl" chunk)
struct PACKED WAVSampleLoop
{
// Sample Loop Types
enum LoopType
{
loopForward = 0,
loopBidi = 1,
loopBackward = 2,
};
uint32 identifier;
uint32 loopType; // See LoopType
uint32 loopStart; // Loop start in samples
uint32 loopEnd; // Loop end in samples
uint32 fraction;
uint32 playCount; // Loop Count, 0 = infinite
// Convert all multi-byte numeric values to current platform's endianness or vice versa.
void ConvertEndianness()
{
SwapBytesLE(identifier);
SwapBytesLE(loopType);
SwapBytesLE(loopStart);
SwapBytesLE(loopEnd);
SwapBytesLE(fraction);
SwapBytesLE(playCount);
}
// Apply WAV loop information to a mod sample.
void ApplyToSample(SmpLength &start, SmpLength &end, SmpLength sampleLength, FlagSet<ChannelFlags, uint16> &flags, ChannelFlags enableFlag, ChannelFlags bidiFlag, bool mptLoopFix) const;
// Convert internal loop information into a WAV loop.
void ConvertToWAV(SmpLength start, SmpLength end, bool bidi);
};
STATIC_ASSERT(sizeof(RIFFHeader) == 12);
// MPT-specific "xtra" chunk
struct PACKED WAVExtraChunk
{
enum Flags
{
setPanning = 0x20,
};
uint32 flags;
uint16 defaultPan;
uint16 defaultVolume;
uint16 globalVolume;
uint16 reserved;
uint8 vibratoType;
uint8 vibratoSweep;
uint8 vibratoDepth;
uint8 vibratoRate;
// Convert all multi-byte numeric values to current platform's endianness or vice versa.
void ConvertEndianness()
{
SwapBytesLE(flags);
SwapBytesLE(defaultPan);
SwapBytesLE(defaultVolume);
SwapBytesLE(globalVolume);
}
// Set up sample information
void ConvertToWAV(const ModSample &sample, MODTYPE modType)
{
if(sample.uFlags[CHN_PANNING])
{
flags = WAVExtraChunk::setPanning;
} else
{
flags = 0;
}
defaultPan = sample.nPan;
defaultVolume = sample.nVolume;
globalVolume = sample.nGlobalVol;
vibratoType = sample.nVibType;
vibratoSweep = sample.nVibSweep;
vibratoDepth = sample.nVibDepth;
vibratoRate = sample.nVibRate;
if((modType & MOD_TYPE_XM) && (vibratoDepth | vibratoRate))
{
// XM vibrato is upside down
vibratoSweep = 255 - vibratoSweep;
}
}
};
STATIC_ASSERT(sizeof(WAVExtraChunk) == 16);
// Sample cue point structure for the "cue " chunk
struct PACKED WAVCuePoint
{
uint32 id; // Unique identification value
uint32 position; // Play order position
uint32 riffChunkID; // RIFF ID of corresponding data chunk
uint32 chunkStart; // Byte Offset of Data Chunk
uint32 blockStart; // Byte Offset to sample of First Channel
uint32 offset; // Byte Offset to sample byte of First Channel
// Convert all multi-byte numeric values to current platform's endianness or vice versa.
void ConvertEndianness()
{
SwapBytesLE(id);
SwapBytesLE(position);
SwapBytesLE(riffChunkID);
SwapBytesLE(chunkStart);
SwapBytesLE(blockStart);
SwapBytesLE(offset);
}
};
STATIC_ASSERT(sizeof(WAVCuePoint) == 24);
#ifdef NEEDS_PRAGMA_PACK
#pragma pack(pop)
#endif
//=============
class WAVReader
//=============
{
protected:
ChunkReader file;
FileReader sampleData, smplChunk, xtraChunk, wsmpChunk;
ChunkReader::ChunkList<RIFFChunk> infoChunk;
FileReader::off_t sampleLength;
bool isDLS;
WAVFormatChunk formatInfo;
uint16 extFormat;
bool mayBeCoolEdit16_8;
public:
WAVReader(FileReader &inputFile);
bool IsValid() const { return sampleData.IsValid(); }
void FindMetadataChunks(ChunkReader::ChunkList<RIFFChunk> &chunks);
// Self-explanatory getters.
WAVFormatChunk::SampleFormats GetSampleFormat() const { return IsExtensibleFormat() ? static_cast<WAVFormatChunk::SampleFormats>(extFormat) : static_cast<WAVFormatChunk::SampleFormats>(formatInfo.format); }
uint16 GetNumChannels() const { return formatInfo.numChannels; }
uint16 GetBitsPerSample() const { return formatInfo.bitsPerSample; }
uint32 GetSampleRate() const { return formatInfo.sampleRate; }
uint16 GetBlockAlign() const { return formatInfo.blockAlign; }
FileReader GetSampleData() const { return sampleData; }
FileReader GetWsmpChunk() const { return wsmpChunk; }
bool IsExtensibleFormat() const { return formatInfo.format == WAVFormatChunk::fmtExtensible; }
bool MayBeCoolEdit16_8() const { return mayBeCoolEdit16_8; }
// Get size of a single sample point, in bytes.
uint16 GetSampleSize() const { return ((GetNumChannels() * GetBitsPerSample()) + 7) / 8; }
// Get sample length (in samples)
SmpLength GetSampleLength() const { return sampleLength; }
// Apply sample settings from file (loop points, MPT extra settings, ...) to a sample.
void ApplySampleSettings(ModSample &sample, char (&sampleName)[MAX_SAMPLENAME]);
};
#ifndef MODPLUG_NO_FILESAVE
//=============
class WAVWriter
//=============
{
protected:
// When writing to file: File handle
FILE *f;
bool fileOwned;
// When writing to a stream: Stream pointer
std::ostream *s;
// When writing to memory: Memory address + length
uint8 *memory;
size_t memSize;
// Cursor position
size_t position;
// Total number of bytes written to file / memory
size_t totalSize;
// Currently written chunk
size_t chunkStartPos;
RIFFChunk chunkHeader;
public:
// Output to file: Initialize with filename. The created FILE* is owned by this instance.
WAVWriter(const mpt::PathString &filename);
// Output to file: Initialize with FILE*.
WAVWriter(FILE *file);
// Output to stream: Initialize with std::ostream*.
WAVWriter(std::ostream *stream);
// Output to clipboard: Initialize with pointer to memory and size of reserved memory.
WAVWriter(void *mem, size_t size);
~WAVWriter();
// Check if anything can be written to the file.
bool IsValid() const { return f != nullptr || s != nullptr || memory != nullptr; }
// Finalize the file by closing the last open chunk and updating the file header. Returns total size of file.
size_t Finalize();
// Begin writing a new chunk to the file.
void StartChunk(RIFFChunk::id_type id);
// Skip some bytes... For example after writing sample data.
void Skip(size_t numBytes) { Seek(position + numBytes); }
// Get file handle
FILE *GetFile() { return f; }
// Get position in file (not counting any changes done to the file from outside this class, i.e. through GetFile())
size_t GetPosition() const { return position; }
// Shrink file size to current position.
void Truncate() { totalSize = position; }
// Write some data to the file.
template<typename T>
void Write(const T &data)
{
Write(&data, sizeof(T));
}
// Write a buffer to the file.
void WriteBuffer(const char *data, size_t size)
{
Write(data, size);
}
// Write an array to the file.
template<typename T, size_t size>
void WriteArray(const T (&data)[size])
{
Write(data, sizeof(T) * size);
}
// Write the WAV format to the file.
void WriteFormat(uint32 sampleRate, uint16 bitDepth, uint16 numChannels, WAVFormatChunk::SampleFormats encoding);
// Write text tags to the file.
void WriteMetatags(const FileTags &tags);
// Write a sample loop information chunk to the file.
void WriteLoopInformation(const ModSample &sample);
// Write MPT's sample information chunk to the file.
void WriteExtraInformation(const ModSample &sample, MODTYPE modType, const char *sampleName = nullptr);
protected:
void Init();
// Seek to a position in file.
void Seek(size_t pos);
// End current chunk by updating the chunk header and writing a padding byte if necessary.
void FinalizeChunk();
// Write some data to the file.
void Write(const void *data, size_t numBytes);
// Write a single tag into a open idLIST chunk
void WriteTag(RIFFChunk::id_type id, const std::wstring &wideText);
};
#endif // MODPLUG_NO_FILESAVE
OPENMPT_NAMESPACE_END
| [
"[email protected]"
] | |
6a43ecbfe626bfbb2daf1281a902fe73cade35a2 | c94fae6bc7779ce06e05b60a0753e82430f830b8 | /MFC窗口文档视图/浏览网址/MainFrm.h | 31fc9f00901c6e5bd81a996d266875d68869dce0 | [] | no_license | MrsZ/MFC_VS2012 | f4bbfc56f2b89c4c99c2ddc55d77e4138d3db4d0 | bc623f1d13cf2fa0eb18b4f2b4f20cb5a762ad96 | refs/heads/master | 2021-05-29T06:00:47.703364 | 2015-08-19T13:16:52 | 2015-08-19T13:16:52 | 110,326,425 | 0 | 1 | null | 2017-11-11T07:19:09 | 2017-11-11T07:19:09 | null | GB18030 | C++ | false | false | 875 | h |
// MainFrm.h : CMainFrame 类的接口
//
#pragma once
class CMainFrame : public CFrameWnd
{
protected: // 仅从序列化创建
CMainFrame();
DECLARE_DYNCREATE(CMainFrame)
// 特性
public:
CDialogBar m_wndDlgBar;
CBitmapButton w_MyBitmapButton1,
w_MyBitmapButton2,
w_MyBitmapButton3,
w_MyBitmapButton4,
w_MyBitmapButton5,
w_MyBitmapButton6;
// 操作
public:
// 重写
public:
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
// 实现
public:
virtual ~CMainFrame();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
protected: // 控件条嵌入成员
CToolBar m_wndToolBar;
CStatusBar m_wndStatusBar;
// 生成的消息映射函数
protected:
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
DECLARE_MESSAGE_MAP()
};
| [
"[email protected]"
] | |
1f38d9f62d562f3c2f69d67ecda07d92fff6fec2 | f52f707ec84d92d6dba89c7727dd1ac04a39751e | /branches/VAST-0.3.4/ACE_wrappers/ace/Hash_Map_With_Allocator_T.h | b4910a00c98abe7e771be8d2ff7ec2626345ae1d | [] | no_license | jonathlela/vast | aaf280cbe022a3aba9d74e2a23be5b3440c62b83 | 85f32b246e9d22011bd2b18554fef4005ab354b3 | refs/heads/master | 2020-06-07T23:41:46.051207 | 2011-04-12T18:35:00 | 2011-04-12T18:35:00 | 1,603,636 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,448 | h | // -*- C++ -*-
//=============================================================================
/**
* @file Hash_Map_With_Allocator_T.h
*
* Hash_Map_With_Allocator_T.h,v 4.14 2006/02/10 09:59:26 jwillemsen Exp
*
* @author Marina Spivak <[email protected]>
* @author Irfan Pyarali <[email protected]>
*/
//=============================================================================
#ifndef ACE_HASH_MAP_WITH_ALLOCATOR_T_H
#define ACE_HASH_MAP_WITH_ALLOCATOR_T_H
#include /**/ "ace/pre.h"
#include "ace/Hash_Map_Manager_T.h"
#include "ace/Null_Mutex.h"
#if !defined (ACE_LACKS_PRAGMA_ONCE)
# pragma once
#endif /* ACE_LACKS_PRAGMA_ONCE */
ACE_BEGIN_VERSIONED_NAMESPACE_DECL
/**
* @class ACE_Hash_Map_With_Allocator
*
* @brief This class is a thin wrapper around ACE_Hash_Map_Manager,
* which comes handy when ACE_Hash_Map_Manager is to be used with a
* non-nil ACE_Allocator. This wrapper insures that the appropriate
* allocator is in place for every operation that accesses or
* updates the hash map.
*
* If we use ACE_Hash_Map_Manager with a shared memory allocator
* (or memory-mapped file allocator, for example), the allocator
* pointer used by ACE_Hash_Map_Manager gets stored with it, in
* shared memory (or memory-mapped file). Naturally, this will
* cause horrible problems, since only the first process to set
* that pointer will be guaranteed the address of the allocator
* is meaningful! That is why we need this wrapper, which
* insures that appropriate allocator pointer is in place for
* each call.
*/
template <class EXT_ID, class INT_ID>
class ACE_Hash_Map_With_Allocator :
public ACE_Hash_Map_Manager_Ex<EXT_ID, INT_ID, ACE_Hash<EXT_ID>, ACE_Equal_To<EXT_ID>, ACE_Null_Mutex>
{
public:
/// Constructor.
ACE_Hash_Map_With_Allocator (ACE_Allocator *alloc);
/// Constructor that specifies hash table size.
ACE_Hash_Map_With_Allocator (size_t size,
ACE_Allocator *alloc);
// = The following methods are Proxies to the corresponding methods
// in ACE_Hash_Map_Manager. Each method sets the allocator to
// the one specified by the invoking entity, and then calls the
// corresponding method in ACE_Hash_Map_Manager to do the
// actual work.
int bind (const EXT_ID &,
const INT_ID &,
ACE_Allocator *alloc);
int unbind (const EXT_ID &,
INT_ID &,
ACE_Allocator *alloc);
int unbind (const EXT_ID &,
ACE_Allocator *alloc);
int rebind (const EXT_ID &,
const INT_ID &,
EXT_ID &,
INT_ID &,
ACE_Allocator *alloc);
int find (const EXT_ID &,
INT_ID &,
ACE_Allocator *alloc);
/// Returns 0 if the @a ext_id is in the mapping, otherwise -1.
int find (const EXT_ID &ext_id,
ACE_Allocator *alloc);
int close (ACE_Allocator *alloc);
};
ACE_END_VERSIONED_NAMESPACE_DECL
#if defined (__ACE_INLINE__)
#include "ace/Hash_Map_With_Allocator_T.inl"
#endif /* __ACE_INLINE__ */
#if defined (ACE_TEMPLATES_REQUIRE_SOURCE)
#include "ace/Hash_Map_With_Allocator_T.cpp"
#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */
#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA)
#pragma implementation ("Hash_Map_With_Allocator_T.cpp")
#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */
#include /**/ "ace/post.h"
#endif /* ACE_HASH_MAP_WITH_ALLOCATOR_T_H */
| [
"cavour@e31416da-b748-0410-9b4e-cac2f8189b79"
] | cavour@e31416da-b748-0410-9b4e-cac2f8189b79 |
4e3f0b7aeb52affbf1749babf33b88f31d97467c | 29288023bde7829066f810540963a7b35573fa31 | /Square_free numbers.cpp | 78c8f6b1ab08e183142cdeab6b829670f46e4eb6 | [] | no_license | Sohail-khan786/Competitve-Programming | 6e56bdd8fb7b3660edec50c72f680b6ed2c41a0f | e90dcf557778a4c0310e03539e4f3c1c939bb3a1 | refs/heads/master | 2022-10-08T06:55:46.637560 | 2020-06-07T18:39:20 | 2020-06-07T18:39:20 | 254,899,456 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 732 | cpp | # include <bits/stdc++.h>
using namespace std;
bool isSquareFree(int n)
{
if (n % 2 == 0)
n = n/2;
if (n % 2 == 0)
return false;
for (int i = 3; i <= sqrt(n); i = i+2)
{
if (n % i == 0)
{
n = n/i;
if (n % i == 0)
return false;
}
}
return true;
}
int main()
{
long n;
cin>>n;
long i, j=1,count=0;
long factors[10^9];
for(i=1;i<=n;i++)
{
if(n%i==0)
{
factors[j]=i;
j++;
}
}
for(i=1;i<j;i++)
{
if (isSquareFree(factors[i]))
count++;
}
cout<<count;
return 0;
}
| [
"[email protected]"
] | |
feba087550da2a03f7cf506afa6b67edd05615a1 | 47e8320b8152711cd5c0318fc62dc24f010adebc | /phi-GPU-v3.0/hermite4.h | 055164adb6f2e41da743eee42654e1f8a49caca0 | [] | no_license | alessioghio/proyectoParalela | af895598d575535626f954cb017c5fbfb75dc4b3 | ffaa86429c36a0d41e33547311711ba57db1bd99 | refs/heads/main | 2023-02-01T15:19:51.346750 | 2020-12-12T03:31:38 | 2020-12-12T03:31:38 | 314,607,135 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,532 | h | #include <cassert>
#include <cmath>
#include "vector3.h"
#include "taylor.h"
extern double wtime();
struct Force{
enum{
nword = 7,
};
dvec3 acc;
dvec3 jrk;
double pot;
};
struct Particle{
enum{
order = 4,
flops = 60,
init_iter = 1,
};
dvec3 pos;
dvec3 vel;
dvec3 acc;
dvec3 jrk;
double mass;
double pot;
double t;
float dt;
int id;
Particle(){
pos = vel = acc = jrk = dvec3(0.0);
mass = pot = t = dt = 0.0;
}
void prefetch() {}
void init(double tsys, double dtmin, double dtmax, double eta, const Force &fo){
acc = fo.acc;
jrk = fo.jrk;
pot = fo.pot;
t = tsys;
double dt0 = 0.1 * eta * sqrt(acc.norm2()/jrk.norm2());
assert(dt0 > dtmin);
dt0 = std::max(dt0, dtmin);
dt = dtmax;
while(dt >= dt0) dt *= 0.5;
}
void correct(double dtmin, double dtmax, double eta, const Force &fo){
double h = 0.5 * dt;
double hi = 1.0 / h;
dvec3 Ap = (fo.acc + acc);
dvec3 Am = (fo.acc - acc);
dvec3 Jp = (fo.jrk + jrk)*h;
dvec3 Jm = (fo.jrk - jrk)*h;
dvec3 vel1 = vel + h*(Ap - (1./3.)*Jm);
dvec3 Vp = (vel1 + vel)*hi;
dvec3 pos1 = pos + h*h*(Vp - (1./3.)*Am);
pos = pos1;
vel = vel1;
acc = fo.acc;
jrk = fo.jrk;
pot = fo.pot;
t += dt;
dvec3 snp = (0.5*hi*hi) * Jm;
dvec3 crk = (1.5*hi*hi*hi) * (Jp - Am);
snp += h * crk;
double aa = acc.norm2();
double jj = jrk.norm2();
double ss = snp.norm2();
double cc = crk.norm2();
double t1 = sqrt(aa*ss) + jj;
double t2 = sqrt(jj*cc) + ss;
double dt0 = eta * sqrt(t1/t2);
assert(dt0 > dtmin);
dt0 = std::max(dt0, dtmin);
dt = dtmax;
while(dt >= dt0) dt *= 0.5;
while(fmod(t, dt) != 0.0) dt *= 0.5;
}
};
typedef Particle Jparticle;
struct Predictor{
dvec3 pos;
dvec3 vel;
double mass;
Predictor(){}
Predictor(double tnow, const Particle &p){
Taylor <double, dvec3> taylor;
double dt = tnow - p.t;
pos = taylor(dt, p.pos, p.vel, p.acc, p.jrk);
vel = taylor(dt, p.vel, p.acc, p.jrk);
mass = p.mass;
}
static Predictor *allocate(size_t n){
return new Predictor[n];
}
};
void calc_force(
int ni,
int nj,
double eps2,
Predictor ipred[],
Predictor jpred[],
Force force[],
double &,
double &,
double &);
#if 1
void calc_force(
int ni,
int nj,
double eps2,
Predictor ipred[],
Predictor jpred[],
Force force[],
double &t1,
double &,
double &){
t1 = wtime();
int i;
#pragma omp parallel for schedule(dynamic) shared(jpred, ipred, eps2, ni, nj, force) private(i) num_threads(2)
for(i=0; i<ni; i++){
double ax=0, ay=0, az=0;
double jx=0, jy=0, jz=0;
double pot=0;
for(int j=0; j<nj; j++){
double dx = jpred[j].pos.x - ipred[i].pos.x;
double dy = jpred[j].pos.y - ipred[i].pos.y;
double dz = jpred[j].pos.z - ipred[i].pos.z;
double dvx = jpred[j].vel.x - ipred[i].vel.x;
double dvy = jpred[j].vel.y - ipred[i].vel.y;
double dvz = jpred[j].vel.z - ipred[i].vel.z;
double r2 = eps2 + dx*dx + dy*dy + dz*dz;
double rv = dx*dvx + dy*dvy + dz*dvz;
if(r2 == eps2) continue;
double rinv2 = 1.0 / r2;
double rinv1 = sqrt(rinv2);
rv *= -3.0 * rinv2;
rinv1 *= jpred[j].mass;
double rinv3 = rinv1 * rinv2;
pot += rinv1;
ax += rinv3 * dx;
ay += rinv3 * dy;
az += rinv3 * dz;
jx += rinv3 * (dvx + rv * dx);
jy += rinv3 * (dvy + rv * dy);
jz += rinv3 * (dvz + rv * dz);
}
force[i].acc.x = ax;
force[i].acc.y = ay;
force[i].acc.z = az;
force[i].jrk.x = jx;
force[i].jrk.y = jy;
force[i].jrk.z = jz;
force[i].pot = -pot;
}
}
#endif
| [
"[email protected]"
] | |
7703622ea10f5dc4e1cb91a50e7053521d1fefdf | 3c0e8e27ee12b6488c901e611b1d5a3c4c3f9b6a | /DeepSpace KCMT/src/main/cpp/commands/Drive.cpp | 7d92bc03fbcbfeeb9487944d1f8ca9e1d36f727e | [] | no_license | FRC1410/DeepSpace | 99fd908c3089154e9b63791802638e84bbaf9f0e | abec2c0e50962d159ddcff7a8d685224f685f00a | refs/heads/master | 2020-04-16T06:01:11.887258 | 2019-09-28T06:39:34 | 2019-09-28T06:39:34 | 165,330,216 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,306 | cpp | /*----------------------------------------------------------------------------*/
/* Copyright (c) 2017-2018 FIRST. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
#include "commands/Drive.h"
#include "Robot.h"
Drive::Drive() {
Requires(&Robot::m_drivetrain);
}
// Called just before this Command runs the first time
void Drive::Initialize() {
previous_distance = Robot::m_drivetrain.GetDistance();
previous_angle = Robot::m_drivetrain.GetAngle();
m_timer.Reset();
m_timer.Start();
previous_timer = -0.02;
Robot::m_limelight.SetTargetFound(false);
turn_left_was_pressed = false;
turn_right_was_pressed = false;
invert_driving = true;
invert_button_was_pressed = false;
invert_timer = 0;
dpad_left_was_pressed = false;
dpad_right_was_pressed = false;
}
// Called repeatedly when this Command is scheduled to run
void Drive::Execute() {
Robot::m_drivetrain.IncrementX((Robot::m_drivetrain.GetDistance() - previous_distance) * sin((Robot::m_drivetrain.GetAngle() + previous_angle) * pi / 360));
Robot::m_drivetrain.IncrementZ((Robot::m_drivetrain.GetDistance() - previous_distance) * cos((Robot::m_drivetrain.GetAngle() + previous_angle) * pi / 360));
Robot::m_limelight.SetPIDConstants();
Robot::m_drivetrain.SetPIDConstants();
if (Robot::m_macro_superstructure.GetAuto() == false) {
if (Robot::m_oi.GetDriverButton(invert_driving_button) == true) {
if (invert_button_was_pressed == false) {
invert_timer = m_timer.Get();
invert_driving = !invert_driving;
}
invert_button_was_pressed = true;
} else {
invert_button_was_pressed = false;
}
//if (Robot::m_oi.GetDriverAxis(vision_align_axis) >= trigger_threshold) {
if (Robot::m_oi.GetDriverButton(vision_align_button) == true) {
//if (Robot::m_limelight.GetTargetFound() == false) {
Robot::m_limelight.SetPipeline(limelight_vision_pipeline);
//}
if (vision_button_was_pressed == false) {
Robot::m_limelight.ResetAngleIntegral();
Robot::m_limelight.ResetAreaIntegral();
}
vision_button_was_pressed = true;
if (Robot::m_limelight.GetTarget() == false) {
Robot::m_oi.SetDriverRumble(0.5, 0.5);
//if (Robot::m_oi.GetDriverAxis(invert_driving_axis) >= trigger_threshold) {
if (invert_driving == true) {
Robot::m_drivetrain.SetCurvedSpeed(Robot::m_oi.GetAverageDriverInput(), Robot::m_oi.GetAverageDriverInput());
} else {
Robot::m_drivetrain.SetCurvedSpeed(-Robot::m_oi.GetAverageDriverInput(), -Robot::m_oi.GetAverageDriverInput());
}
} else {
Robot::m_oi.SetDriverRumble(0, 0);
if (Robot::m_limelight.GetTargetArea() < limelight_large_area) {
PID_value = Robot::m_limelight.GetAnglePID(limelight_target_offset_offset + Robot::m_limelight.GetAreaPID(limelight_large_area, m_timer.Get() - previous_timer), m_timer.Get() - previous_timer);
} else {
// Robot::m_limelight.SetTargetFound(true);
PID_value = 0;
}
/*if (Robot::m_limelight.GetTargetFound() == true) {
Robot::m_limelight.SetPipeline(limelight_driver_pipeline);
}*/
//if (Robot::m_oi.GetDriverAxis(invert_driving_axis) > trigger_threshold) {
if (invert_driving == true) {
Robot::m_drivetrain.SetCurvedSpeed(Robot::m_oi.GetAverageDriverInput() - PID_value, Robot::m_oi.GetAverageDriverInput() + PID_value);
} else {
Robot::m_drivetrain.SetCurvedSpeed(-Robot::m_oi.GetAverageDriverInput() - PID_value, -Robot::m_oi.GetAverageDriverInput() + PID_value);
}
}
} else {
Robot::m_limelight.SetPipeline(limelight_driver_pipeline);
vision_button_was_pressed = false;
Robot::m_limelight.SetTargetFound(false);
Robot::m_oi.SetDriverRumble(0, 0);
/*if (Robot::m_oi.GetDriverButton(drivetrain_turn_left_button) == true) {
if (turn_left_was_pressed == false) {
Robot::m_drivetrain.ResetGyroIntegral();
reference_angle = Robot::m_drivetrain.GetAngle();
}
goto turn_left;
turn_left_was_pressed = true;
} else {
turn_left_was_pressed = false;
}
if (Robot::m_oi.GetDriverButton(drivetrain_turn_right_button) == true) {
if (turn_right_was_pressed == false) {
Robot::m_drivetrain.ResetGyroIntegral();
reference_angle = Robot::m_drivetrain.GetAngle();
}
goto turn_right;
} else {
turn_right_was_pressed = false;
}*/
//if (Robot::m_oi.GetDriverAxis(invert_driving_axis) >= trigger_threshold) {
if (invert_driving == true) {
if (Robot::m_oi.GetDriverButton(drivetrain_straight_drive_button) == true) {
Robot::m_drivetrain.SetCurvedSpeed(Robot::m_oi.GetAverageDriverInput(), Robot::m_oi.GetAverageDriverInput());
} else {
Robot::m_drivetrain.SetCurvedSpeed(Robot::m_oi.GetDriverAxis(drivetrain_right_axis), Robot::m_oi.GetDriverAxis(drivetrain_left_axis));
}
} else {
if (Robot::m_oi.GetDriverButton(drivetrain_straight_drive_button) == true) {
Robot::m_drivetrain.SetCurvedSpeed(-Robot::m_oi.GetAverageDriverInput(), -Robot::m_oi.GetAverageDriverInput());
} else {
Robot::m_drivetrain.SetCurvedSpeed(-Robot::m_oi.GetDriverAxis(drivetrain_left_axis), -Robot::m_oi.GetDriverAxis(drivetrain_right_axis));
}
}
if (false) {
turn_left:
PID_value = Robot::m_drivetrain.GetGyroPID(reference_angle - 90, m_timer.Get() - previous_timer);
Robot::m_drivetrain.SetCurvedSpeed(PID_value, -PID_value);
} else if (false) {
turn_right:
PID_value = Robot::m_drivetrain.GetGyroPID(reference_angle + 90, m_timer.Get() - previous_timer);
Robot::m_drivetrain.SetCurvedSpeed(PID_value, -PID_value);
}
if ((invert_driving == true && ((m_timer.Get() - invert_timer) < double_rumble_time || ((m_timer.Get() - invert_timer) > (2 * double_rumble_time) && (m_timer.Get() - invert_timer) < (3 * double_rumble_time)))) || (invert_driving == false && (m_timer.Get() - invert_timer) < single_rumble_time)) {
Robot::m_oi.SetDriverRumble(1, 1);
}
}
}
Robot::m_drivetrain.DisplayData((Robot::m_drivetrain.GetDistance() - previous_distance) / (m_timer.Get() - previous_timer), ((Robot::m_drivetrain.GetAngle() - previous_angle) / (m_timer.Get() - previous_timer)) * pi / 180, Robot::m_oi.GetDriverAxis(invert_driving_axis) >= trigger_threshold);
Robot::m_limelight.GetTarget();
Robot::m_limelight.GetTargetX();
Robot::m_limelight.GetTargetArea();
previous_distance = Robot::m_drivetrain.GetDistance();
previous_angle = Robot::m_drivetrain.GetAngle();
previous_timer = m_timer.Get();
/*if (Robot::m_oi.GetOperatorAxis(limelight_offset_increase_trigger) >= trigger_threshold){
limelight_target_offset_offset += 0.0254;
} else if (Robot::m_oi.GetOperatorAxis(limelight_offset_decrease_trigger) >= trigger_threshold) {
limelight_target_offset_offset -= 0.0254;
}
if (Robot::m_oi.GetDriverDPad() == 90) {
if (dpad_left_was_pressed == false) {
limelight_target_offset_offset += 0.148;
}
dpad_left_was_pressed = true;
} else {
dpad_left_was_pressed = false;
}
if (Robot::m_oi.GetDriverDPad() == 270) {
if (dpad_right_was_pressed == false) {
limelight_target_offset_offset -= 0.148;
}
dpad_right_was_pressed = true;
} else {
dpad_right_was_pressed = false;
}*/
frc::SmartDashboard::PutNumber("target offset offset" , limelight_target_offset_offset);
}
// Make this return true when this Command no longer needs to run execute()
bool Drive::IsFinished() {
return false;
}
// Called once after isFinished returns true
void Drive::End() {}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
void Drive::Interrupted() {} | [
"[email protected]"
] | |
ed8786bbd9a5f6bb98b4986435660998985a3e56 | 53eeb9b648dd22314aac58a4f91d5563e26e18b9 | /Divinity/Classes/MainCharcter.h | e25c0d25b615498ec05cf6c59e00badffc59c226 | [] | no_license | william-xian/workspace | e5e4cd7c0a41f368c9b4aaa731bba10be15c9640 | 71525e84230ba854e02e8555e454948e3717e070 | refs/heads/master | 2021-01-10T19:34:32.049649 | 2015-01-28T05:01:45 | 2015-01-28T05:01:45 | 29,800,024 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 323 | h | #ifndef __MAINCHARCTER__
#define __MAINCHARCTER__
#include "Animal.h"
#include "cocos2d.h"
class MainCharcter : public Animal
{
public:
MainCharcter();
virtual ~MainCharcter();
static MainCharcter* create(const std::string& filename, int cntWidth, int cntHeight);
void logicUpdate();
};
#endif /* __MAINCHARCTER__ */
| [
"[email protected]"
] | |
58377b5e8cc03fbe00345b0c3618bf6222e164e3 | 3358f4e1ffbe93cf03731399763d5a30fee2de8c | /src/qt/receivecoinsdialog.h | 8f8ac12f3bfc5d552c460eafe1fb8a4b43155589 | [
"MIT"
] | permissive | sombeProject/sombe | 80634ee6254cf228c4b68c42ec36496890ced4f1 | 3cd30f1789b11130a9c897a22bc8130f40275407 | refs/heads/master | 2021-08-17T08:33:49.770614 | 2020-06-06T15:14:43 | 2020-06-06T15:14:43 | 163,437,726 | 6 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,141 | h | // Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2017 The PIVX developers
// Copyright (c) 2019 The SOMBE developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_QT_RECEIVECOINSDIALOG_H
#define BITCOIN_QT_RECEIVECOINSDIALOG_H
#include "guiutil.h"
#include <QDialog>
#include <QHeaderView>
#include <QItemSelection>
#include <QKeyEvent>
#include <QMenu>
#include <QPoint>
#include <QVariant>
class OptionsModel;
class WalletModel;
namespace Ui
{
class ReceiveCoinsDialog;
}
QT_BEGIN_NAMESPACE
class QModelIndex;
QT_END_NAMESPACE
/** Dialog for requesting payment of bitcoins */
class ReceiveCoinsDialog : public QDialog
{
Q_OBJECT
public:
enum ColumnWidths {
DATE_COLUMN_WIDTH = 130,
LABEL_COLUMN_WIDTH = 120,
AMOUNT_MINIMUM_COLUMN_WIDTH = 160,
MINIMUM_COLUMN_WIDTH = 130
};
explicit ReceiveCoinsDialog(QWidget* parent = 0);
~ReceiveCoinsDialog();
void setModel(WalletModel* model);
public slots:
void clear();
void reject();
void accept();
protected:
virtual void keyPressEvent(QKeyEvent* event);
private:
Ui::ReceiveCoinsDialog* ui;
GUIUtil::TableViewLastColumnResizingFixer* columnResizingFixer;
WalletModel* model;
QMenu* contextMenu;
QString address;
QString getAddress(QString label = "");
void copyColumnToClipboard(int column);
virtual void resizeEvent(QResizeEvent* event);
private slots:
void on_receiveButton_clicked();
void on_receivingAddressesButton_clicked();
void on_showRequestButton_clicked();
void on_removeRequestButton_clicked();
void on_recentRequestsView_doubleClicked(const QModelIndex& index);
void recentRequestsView_selectionChanged(const QItemSelection& selected, const QItemSelection& deselected);
void updateDisplayUnit();
void showMenu(const QPoint& point);
void copyLabel();
void copyMessage();
void copyAmount();
void copyAddress();
void receiveAddressUsed();
};
#endif // BITCOIN_QT_RECEIVECOINSDIALOG_H
| [
"[email protected]"
] | |
f56d144295cc71671d0ea8560ec18350c39a0b82 | 53f07e256f1e34fa821df47cab0f90e85cd050a2 | /test/RapidJSONAdapterTest/Tests/JSONDocumentParseTest.cpp | afd7742af90aa785abc7bf495b888e2b45f6d2db | [
"MIT"
] | permissive | joancarreras/cpp-rapidjson-json-adapter | 2676da28c0ecfcf3f36e5b4ebb66720dd898306f | 9545277276f342f6b688e7d8a23da66f9132d2dd | refs/heads/master | 2023-08-22T12:43:39.341253 | 2021-09-30T15:04:21 | 2021-09-30T15:04:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,193 | cpp | #include "stdafx.h"
#include "RapidJSONAdapter/JSONAdapter.h"
#include "RapidJSONAdapter/JSONDocument.h"
#include "RapidJSONAdapter/JSONValue.h"
using namespace testing;
namespace systelab { namespace json { namespace rapidjson { namespace unit_test {
class JSONDocumentParseTest : public testing::Test
{
public:
void SetUp()
{
m_jsonAdapter = std::make_unique<JSONAdapter>();
}
protected:
std::unique_ptr<JSONAdapter> m_jsonAdapter;
};
TEST_F(JSONDocumentParseTest, testBuildDocumentFromEmptyString)
{
auto jsonDocument = m_jsonAdapter->buildDocumentFromString("");
ASSERT_TRUE(jsonDocument == NULL);
}
TEST_F(JSONDocumentParseTest, testBuildDocumentFromInvalidJSON)
{
auto jsonDocument = m_jsonAdapter->buildDocumentFromString("This is not a JSON");
ASSERT_TRUE(jsonDocument == NULL);
}
TEST_F(JSONDocumentParseTest, testBuildDocumentFromEmptyObjectJSON)
{
auto jsonDocument = m_jsonAdapter->buildDocumentFromString("{}");
ASSERT_TRUE(jsonDocument != NULL);
systelab::json::IJSONValue& jsonRootValue = jsonDocument->getRootValue();
ASSERT_EQ(systelab::json::OBJECT_TYPE, jsonRootValue.getType());
ASSERT_EQ(0u, jsonRootValue.getObjectMemberCount());
}
TEST_F(JSONDocumentParseTest, testBuildDocumentFromSingleIntegerAttributeObjectJSON)
{
auto jsonDocument = m_jsonAdapter->buildDocumentFromString("{ \"attInt\": 1234 }");
ASSERT_TRUE(jsonDocument != NULL);
systelab::json::IJSONValue& jsonRootValue = jsonDocument->getRootValue();
ASSERT_EQ(systelab::json::OBJECT_TYPE, jsonRootValue.getType());
ASSERT_EQ(1u, jsonRootValue.getObjectMemberCount());
ASSERT_THAT(jsonRootValue.getObjectMemberNames(), ElementsAreArray({ "attInt" }));
systelab::json::IJSONValue& jsonIntValue = jsonRootValue.getObjectMemberValue("attInt");
ASSERT_EQ(systelab::json::NUMBER_TYPE, jsonIntValue.getType());
ASSERT_TRUE(jsonIntValue.isInteger());
ASSERT_EQ(1234, jsonIntValue.getInteger());
}
TEST_F(JSONDocumentParseTest, testBuildDocumentFromSingleDoubleAttributeObjectJSON)
{
auto jsonDocument = m_jsonAdapter->buildDocumentFromString("{ \"attDouble\": 1.2345 }");
ASSERT_TRUE(jsonDocument != NULL);
systelab::json::IJSONValue& jsonRootValue = jsonDocument->getRootValue();
ASSERT_EQ(systelab::json::OBJECT_TYPE, jsonRootValue.getType());
ASSERT_EQ(1u, jsonRootValue.getObjectMemberCount());
ASSERT_THAT(jsonRootValue.getObjectMemberNames(), ElementsAreArray({ "attDouble" }));
systelab::json::IJSONValue& jsonDoubleValue = jsonRootValue.getObjectMemberValue("attDouble");
ASSERT_EQ(systelab::json::NUMBER_TYPE, jsonDoubleValue.getType());
ASSERT_FALSE(jsonDoubleValue.isInteger());
ASSERT_NEAR(1.2345, jsonDoubleValue.getDouble(), 1e-6);
}
TEST_F(JSONDocumentParseTest, testBuildDocumentFromSingleTrueBooleanAttributeObjectJSON)
{
auto jsonDocument = m_jsonAdapter->buildDocumentFromString("{ \"attBoolean\": true }");
ASSERT_TRUE(jsonDocument != NULL);
systelab::json::IJSONValue& jsonRootValue = jsonDocument->getRootValue();
ASSERT_EQ(systelab::json::OBJECT_TYPE, jsonRootValue.getType());
ASSERT_EQ(1u, jsonRootValue.getObjectMemberCount());
ASSERT_THAT(jsonRootValue.getObjectMemberNames(), ElementsAreArray({ "attBoolean" }));
systelab::json::IJSONValue& jsonBooleanValue = jsonRootValue.getObjectMemberValue("attBoolean");
ASSERT_EQ(systelab::json::BOOLEAN_TYPE, jsonBooleanValue.getType());
ASSERT_TRUE(jsonBooleanValue.getBoolean());
}
TEST_F(JSONDocumentParseTest, testBuildDocumentFromSingleFalseBooleanAttributeObjectJSON)
{
auto jsonDocument = m_jsonAdapter->buildDocumentFromString("{ \"attBoolean\": false }");
ASSERT_TRUE(jsonDocument != NULL);
systelab::json::IJSONValue& jsonRootValue = jsonDocument->getRootValue();
ASSERT_EQ(systelab::json::OBJECT_TYPE, jsonRootValue.getType());
ASSERT_EQ(1u, jsonRootValue.getObjectMemberCount());
ASSERT_THAT(jsonRootValue.getObjectMemberNames(), ElementsAreArray({ "attBoolean" }));
systelab::json::IJSONValue& jsonBooleanValue = jsonRootValue.getObjectMemberValue("attBoolean");
ASSERT_EQ(systelab::json::BOOLEAN_TYPE, jsonBooleanValue.getType());
ASSERT_FALSE(jsonBooleanValue.getBoolean());
}
TEST_F(JSONDocumentParseTest, testBuildDocumentFromSingleStringAttributeObjectJSON)
{
auto jsonDocument = m_jsonAdapter->buildDocumentFromString("{ \"attString\": \"ABCDEF\" }");
ASSERT_TRUE(jsonDocument != NULL);
systelab::json::IJSONValue& jsonRootValue = jsonDocument->getRootValue();
ASSERT_EQ(systelab::json::OBJECT_TYPE, jsonRootValue.getType());
ASSERT_EQ(1u, jsonRootValue.getObjectMemberCount());
ASSERT_THAT(jsonRootValue.getObjectMemberNames(), ElementsAreArray({ "attString" }));
systelab::json::IJSONValue& jsonStringValue = jsonRootValue.getObjectMemberValue("attString");
ASSERT_EQ(systelab::json::STRING_TYPE, jsonStringValue.getType());
ASSERT_EQ("ABCDEF", jsonStringValue.getString());
}
TEST_F(JSONDocumentParseTest, testBuildDocumentFromSingleNullAttributeObjectJSON)
{
auto jsonDocument = m_jsonAdapter->buildDocumentFromString("{ \"attNull\": null }");
ASSERT_TRUE(jsonDocument != NULL);
systelab::json::IJSONValue& jsonRootValue = jsonDocument->getRootValue();
ASSERT_EQ(systelab::json::OBJECT_TYPE, jsonRootValue.getType());
ASSERT_EQ(1u, jsonRootValue.getObjectMemberCount());
ASSERT_THAT(jsonRootValue.getObjectMemberNames(), ElementsAreArray({ "attNull" }));
systelab::json::IJSONValue& jsonNullValue = jsonRootValue.getObjectMemberValue("attNull");
ASSERT_EQ(systelab::json::NULL_TYPE, jsonNullValue.getType());
ASSERT_TRUE(jsonNullValue.isNull());
}
TEST_F(JSONDocumentParseTest, testBuildDocumentFromSingleEmptyObjectAttributeObjectJSON)
{
auto jsonDocument = m_jsonAdapter->buildDocumentFromString("{ \"attObject\": {} }");
ASSERT_TRUE(jsonDocument != NULL);
systelab::json::IJSONValue& jsonRootValue = jsonDocument->getRootValue();
ASSERT_EQ(systelab::json::OBJECT_TYPE, jsonRootValue.getType());
ASSERT_EQ(1u, jsonRootValue.getObjectMemberCount());
ASSERT_THAT(jsonRootValue.getObjectMemberNames(), ElementsAreArray({ "attObject" }));
systelab::json::IJSONValue& jsonObjectValue = jsonRootValue.getObjectMemberValue("attObject");
ASSERT_EQ(systelab::json::OBJECT_TYPE, jsonObjectValue.getType());
ASSERT_EQ(0u, jsonObjectValue.getObjectMemberCount());
}
TEST_F(JSONDocumentParseTest, testBuildDocumentFromSingleNonEmptyObjectAttributeObjectJSON)
{
auto jsonDocument = m_jsonAdapter->buildDocumentFromString("{ \"attObject\": { \"attSubObject\": true } }");
ASSERT_TRUE(jsonDocument != NULL);
systelab::json::IJSONValue& jsonRootValue = jsonDocument->getRootValue();
ASSERT_EQ(systelab::json::OBJECT_TYPE, jsonRootValue.getType());
ASSERT_EQ(1u, jsonRootValue.getObjectMemberCount());
ASSERT_THAT(jsonRootValue.getObjectMemberNames(), ElementsAreArray({ "attObject" }));
systelab::json::IJSONValue& jsonObjectValue = jsonRootValue.getObjectMemberValue("attObject");
ASSERT_EQ(systelab::json::OBJECT_TYPE, jsonObjectValue.getType());
ASSERT_EQ(1u, jsonObjectValue.getObjectMemberCount());
ASSERT_THAT(jsonObjectValue.getObjectMemberNames(), ElementsAreArray({ "attSubObject" }));
systelab::json::IJSONValue& jsonSubObjectValue = jsonObjectValue.getObjectMemberValue("attSubObject");
ASSERT_EQ(systelab::json::BOOLEAN_TYPE, jsonSubObjectValue.getType());
ASSERT_TRUE(jsonSubObjectValue.getBoolean());
}
TEST_F(JSONDocumentParseTest, testBuildDocumentFromSingleArrayAttributeObjectJSON)
{
auto jsonDocument = m_jsonAdapter->buildDocumentFromString("{ \"attArray\": [9, 8, 7] }");
ASSERT_TRUE(jsonDocument != NULL);
systelab::json::IJSONValue& jsonRootValue = jsonDocument->getRootValue();
ASSERT_EQ(systelab::json::OBJECT_TYPE, jsonRootValue.getType());
ASSERT_EQ(1u, jsonRootValue.getObjectMemberCount());
ASSERT_THAT(jsonRootValue.getObjectMemberNames(), ElementsAreArray({ "attArray" }));
systelab::json::IJSONValue& jsonArrayValue = jsonRootValue.getObjectMemberValue("attArray");
ASSERT_EQ(systelab::json::ARRAY_TYPE, jsonArrayValue.getType());
ASSERT_EQ(3, jsonArrayValue.getArrayValueCount());
ASSERT_EQ(9, jsonArrayValue.getArrayValue(0).getInteger());
ASSERT_EQ(8, jsonArrayValue.getArrayValue(1).getInteger());
ASSERT_EQ(7, jsonArrayValue.getArrayValue(2).getInteger());
}
TEST_F(JSONDocumentParseTest, testBuildDocumentFromComplexJSON)
{
std::stringstream ss;
ss << "{";
ss << " \"attInt\": 1234,";
ss << " \"attDouble\": 2.345,";
ss << " \"attTrue\": true,";
ss << " \"attFalse\": false,";
ss << " \"attString\": \"ABC XYZ\",";
ss << " \"attArray\": [\"A\", \"B\", \"C\"],";
ss << " \"attObject\": { \"attNull\": null }";
ss << "}";
auto jsonDocument = m_jsonAdapter->buildDocumentFromString(ss.str());
ASSERT_TRUE(jsonDocument != NULL);
systelab::json::IJSONValue& jsonRootValue = jsonDocument->getRootValue();
ASSERT_EQ(systelab::json::OBJECT_TYPE, jsonRootValue.getType());
ASSERT_EQ(7u, jsonRootValue.getObjectMemberCount());
ASSERT_THAT(jsonRootValue.getObjectMemberNames(),
UnorderedElementsAreArray({ "attInt", "attDouble", "attTrue", "attFalse",
"attString", "attArray", "attObject" }));
ASSERT_EQ(systelab::json::NUMBER_TYPE, jsonRootValue.getObjectMemberValue("attInt").getType());
ASSERT_EQ(1234, jsonRootValue.getObjectMemberValue("attInt").getInteger());
ASSERT_EQ(systelab::json::NUMBER_TYPE, jsonRootValue.getObjectMemberValue("attDouble").getType());
ASSERT_NEAR(2.345, jsonRootValue.getObjectMemberValue("attDouble").getDouble(), 1e-8);
ASSERT_EQ(systelab::json::BOOLEAN_TYPE, jsonRootValue.getObjectMemberValue("attTrue").getType());
ASSERT_TRUE(jsonRootValue.getObjectMemberValue("attTrue").getBoolean());
ASSERT_EQ(systelab::json::BOOLEAN_TYPE, jsonRootValue.getObjectMemberValue("attFalse").getType());
ASSERT_FALSE(jsonRootValue.getObjectMemberValue("attFalse").getBoolean());
ASSERT_EQ(systelab::json::STRING_TYPE, jsonRootValue.getObjectMemberValue("attString").getType());
ASSERT_EQ("ABC XYZ", jsonRootValue.getObjectMemberValue("attString").getString());
systelab::json::IJSONValue& jsonArrayValue = jsonRootValue.getObjectMemberValue("attArray");
ASSERT_EQ(systelab::json::ARRAY_TYPE, jsonArrayValue.getType());
ASSERT_EQ(3, jsonArrayValue.getArrayValueCount());
ASSERT_EQ("A", jsonArrayValue.getArrayValue(0).getString());
ASSERT_EQ("B", jsonArrayValue.getArrayValue(1).getString());
ASSERT_EQ("C", jsonArrayValue.getArrayValue(2).getString());
systelab::json::IJSONValue& jsonObjectValue = jsonRootValue.getObjectMemberValue("attObject");
ASSERT_EQ(systelab::json::OBJECT_TYPE, jsonObjectValue.getType());
ASSERT_EQ(1, jsonObjectValue.getObjectMemberCount());
ASSERT_THAT(jsonObjectValue.getObjectMemberNames(), UnorderedElementsAreArray({"attNull"}));
ASSERT_EQ(systelab::json::NULL_TYPE, jsonObjectValue.getObjectMemberValue("attNull").getType());
jsonArrayValue.clearArray();
ASSERT_EQ(0, jsonArrayValue.getArrayValueCount());
jsonRootValue.removeMember("attString");
ASSERT_THROW(jsonRootValue.getObjectMemberValue("attString"), std::runtime_error);
}
}}}}
| [
"[email protected]"
] | |
a1b842add4a69e550912a7dcb8f8af13f4246a09 | d515ceafa5ae2d187ab6315e1b66cdfee615dabc | /homeworks/Ani_Papyan/2_introduction__functions/1_reverse_number/main.cpp | a77789e630dcecc21e70386af8b930f2ff435533 | [] | no_license | Internal-Trainings-Vanadzor/Internal-Trainings | 9e08f8901d467c6e57e1da18de4a349cd6def6dc | b37ec79c352dfba06e6bed9b3bed95cd175616c9 | refs/heads/master | 2021-01-10T17:55:19.724266 | 2015-10-20T19:34:04 | 2015-10-20T19:34:04 | 36,315,296 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 643 | cpp | #include <iostream>
/**
* This function will be called in another function which reverses the given iteger
*/
static int reverse (int number, int step, int& max) {
if (0 == number / 10) {
return number;
}
max *= 10;
return reverse(number / 10, step * 10, max) + (number%10) * max / step;
}
/**
* This function reverses the given integer
*/
static int reverse (int number) {
int ref = 1;
return reverse(number, 1, ref);
}
int main () {
unsigned int n;
std::cout << "Please input an integer:" << std::endl;
std::cin >> n;
std::cout << "RESULT: " << reverse(n) << std::endl;
return 0;
}
| [
"[email protected]"
] | |
07aeca243e63c5538aeeab303670d3c8e4742a11 | 4aca9b78661380594e25a4c9d2c1c6014d885d72 | /util/wraps.cpp | e8a9a693c0cd3ec51ec2b9f84036acb0a283c4d6 | [] | no_license | danilkolikov/proxy | 6eecf1e52a949868d357446bcd5832bb9c83cc99 | f9b221262fd766c4cef4bfc0c37731d02d358922 | refs/heads/master | 2021-01-10T12:45:06.013131 | 2016-02-20T12:27:04 | 2016-02-20T12:27:04 | 50,244,198 | 0 | 1 | null | 2016-01-30T11:56:11 | 2016-01-23T15:27:09 | C++ | UTF-8 | C++ | false | false | 14,478 | cpp | #include "wraps.h"
file_descriptor::file_descriptor() :
fd(0) {
}
file_descriptor::file_descriptor(int fd) :
fd(fd) {
if (fd == -1) {
int err = errno;
throw annotated_exception("fd", err);
}
}
file_descriptor::file_descriptor(file_descriptor &&other) : fd() {
swap(*this, other);
}
file_descriptor &file_descriptor::operator=(file_descriptor &&other) {
swap(*this, other);
return *this;
}
file_descriptor::~file_descriptor() {
if (fd != 0) {
close(fd);
}
}
int file_descriptor::get() const {
return fd;
}
int file_descriptor::can_read() const {
int bytes = 0;
if (ioctl(fd, FIONREAD, &bytes) == -1) {
int err = errno;
throw annotated_exception("can_read", err);
}
return bytes;
}
long file_descriptor::read(void *message, size_t message_size) const {
long read = ::read(fd, message, message_size);
if (read == -1) {
int err = errno;
throw annotated_exception("read", err);
}
return read;
}
long file_descriptor::write(void const *message, size_t message_size) const {
long written = ::write(fd, message, message_size);
if (written == -1) {
int err = errno;
throw annotated_exception("write", err);
}
return written;
}
void swap(file_descriptor &first, file_descriptor &second) {
std::swap(first.fd, second.fd);
}
std::string to_string(file_descriptor const& fd) {
return "file descriptor " + std::to_string(fd.get());
}
timer_fd::timer_fd() : file_descriptor() {
}
timer_fd::timer_fd(clock_mode cmode, fd_mode mode) : timer_fd(cmode, {mode}) {
}
timer_fd::timer_fd(clock_mode cmode, std::initializer_list<fd_mode> mode) {
int clock_mode = (cmode == MONOTONIC) ? CLOCK_MONOTONIC : CLOCK_REALTIME;
if ((fd = timerfd_create(clock_mode, value_of(mode))) == -1) {
int err = errno;
throw annotated_exception("timerfd", err);
}
}
void timer_fd::set_interval(long interval_sec, long start_after_sec) const {
itimerspec spec;
memset(&spec, 0, sizeof spec);
spec.it_value.tv_sec = start_after_sec;
spec.it_interval.tv_sec = interval_sec;
if (timerfd_settime(fd, 0, &spec, 0) == -1) {
int err = errno;
throw annotated_exception("timerfd", err);
}
}
int timer_fd::value_of(std::initializer_list<fd_mode> mode) {
int res = 0;
for (auto it = mode.begin(); it != mode.end(); it++) {
switch (*it) {
case NONBLOCK:
res |= TFD_NONBLOCK;
break;
case CLOEXEC:
res |= TFD_CLOEXEC;
break;
case SIMPLE:
res |= 0;
break;
}
}
return res;
}
event_fd::event_fd() : file_descriptor() { }
event_fd::event_fd(unsigned int initial, fd_mode mode) : event_fd(initial, {mode}) { }
event_fd::event_fd(unsigned int initial, std::initializer_list<fd_mode> mode) {
if ((fd = eventfd(initial, value_of(mode))) == -1) {
int err = errno;
throw annotated_exception("eventfd", err);
}
}
int event_fd::value_of(std::initializer_list<fd_mode> mode) {
int res = 0;
for (auto it = mode.begin(); it != mode.end(); it++) {
switch (*it) {
case NONBLOCK:
res |= EFD_NONBLOCK;
break;
case CLOEXEC:
res |= EFD_CLOEXEC;
break;
case SEMAPHORE:
res |= EFD_SEMAPHORE;
break;
case SIMPLE:
res |= 0;
break;
}
}
return res;
}
signal_fd::signal_fd() : file_descriptor() { }
signal_fd::signal_fd(int handle, fd_mode mode) : signal_fd({handle}, {mode}) {
}
signal_fd::signal_fd(std::initializer_list<int> handle, std::initializer_list<fd_mode> mode) {
sigset_t mask;
sigemptyset(&mask);
for (auto it = handle.begin(); it != handle.end(); it++) {
sigaddset(&mask, *it);
}
sigprocmask(SIG_BLOCK, &mask, NULL);
if ((fd = signalfd(-1, &mask, value_of(mode))) == -1) {
int err = errno;
throw annotated_exception("signalfd", err);
}
}
int signal_fd::value_of(std::initializer_list<fd_mode> mode) {
int res = 0;
for (auto it = mode.begin(); it != mode.end(); it++) {
switch (*it) {
case NONBLOCK:
res |= SFD_NONBLOCK;
break;
case CLOEXEC:
res |= SFD_CLOEXEC;
break;
case SIMPLE:
res |= 0;
break;
}
}
return res;
}
socket_wrap::socket_wrap() :
file_descriptor() {
}
socket_wrap::socket_wrap(int fd) :
file_descriptor(fd) {
}
socket_wrap::socket_wrap(socket_mode mode) : socket_wrap({mode}) { }
socket_wrap::socket_wrap(std::initializer_list<socket_mode> mode) :
file_descriptor() {
int type = SOCK_STREAM | value_of(mode);
fd = socket(AF_INET, type, 0);
if (fd == -1) {
int err = errno;
throw annotated_exception("socket", err);
}
}
socket_wrap::socket_wrap(socket_wrap &&other) {
swap(*this, other);
}
int socket_wrap::value_of(std::initializer_list<socket_mode> modes) const {
int mode = 0;
for (auto it = modes.begin(); it != modes.end(); it++) {
switch (*it) {
case SIMPLE:
mode |= 0;
break;
case NONBLOCK:
mode |= O_NONBLOCK;
break;
case CLOEXEC:
mode |= O_CLOEXEC;
break;
default:
mode |= 0;
break;
}
}
return mode;
}
socket_wrap socket_wrap::accept(socket_mode mode) const {
int new_fd = ::accept4(fd, 0, 0, value_of({mode}));
if (new_fd == -1) {
int err = errno;
throw annotated_exception("accept", err);
}
return socket_wrap(new_fd);
}
socket_wrap socket_wrap::accept(std::initializer_list<socket_mode> mode) const {
int new_fd = ::accept4(fd, 0, 0, value_of(mode));
if (new_fd == -1) {
int err = errno;
throw annotated_exception("accept", err);
}
return socket_wrap(new_fd);
}
void socket_wrap::bind(uint16_t port) const {
sockaddr_in addr = {};
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = INADDR_ANY;
if (::bind(fd, reinterpret_cast<struct sockaddr *>(&addr), sizeof(addr))) {
int err = errno;
throw annotated_exception("bind", err);
}
}
void socket_wrap::connect(endpoint address) const {
sockaddr_in addr;
memset(&addr, 0, sizeof addr);
addr.sin_family = AF_INET;
addr.sin_port = address.port;
addr.sin_addr.s_addr = address.ip;
if (::connect(fd, (struct sockaddr *) (&addr), sizeof(addr))) {
int err = errno;
throw annotated_exception("connect", err);
}
}
void socket_wrap::listen(int max_queue_size) const {
if (max_queue_size == -1) {
max_queue_size = SOMAXCONN;
}
if (::listen(fd, max_queue_size)) {
int err = errno;
throw annotated_exception("listen", err);
}
}
void socket_wrap::get_option(int name, void *res, socklen_t *res_len) const {
if (getsockopt(fd, SOL_SOCKET, name, res, res_len) < 0) {
int err = errno;
throw annotated_exception("get_option", err);
}
}
std::string to_string(socket_wrap &wrap) {
return "socket " + std::to_string(wrap.get());
}
fd_state::fd_state() :
fd_st(0) {
}
fd_state::fd_state(uint32_t st) :
fd_st(st) {
}
fd_state::fd_state(state st) :
fd_state({st}) {
}
fd_state::fd_state(std::initializer_list<state> st) : fd_st(value_of(st)) {
}
fd_state::fd_state(fd_state const &other) :
fd_st(other.fd_st) {
}
fd_state::fd_state(fd_state &&other) {
swap(*this, other);
}
fd_state &fd_state::operator=(fd_state other) {
swap(*this, other);
return *this;
}
bool fd_state::operator!=(fd_state other) const {
return fd_st != other.fd_st;
}
bool fd_state::is(fd_state st) const {
return (fd_st & st.fd_st) != 0;
}
uint32_t fd_state::get() const {
return fd_st;
}
fd_state operator^(fd_state first, fd_state second) {
return fd_state(first.get() ^ second.get());
}
fd_state operator|(fd_state first, fd_state second) {
return fd_state(first.get() | second.get());
}
uint32_t fd_state::value_of(std::initializer_list<state> st) {
uint32_t res = 0;
for (auto it = st.begin(); it != st.end(); it++) {
switch (*it) {
case IN:
res |= EPOLLIN;
break;
case OUT:
res |= EPOLLOUT;
break;
case ERROR:
res |= EPOLLERR;
break;
case HUP:
res |= EPOLLHUP;
break;
case RDHUP:
res |= EPOLLRDHUP;
break;
default:
res |= 0;
}
}
return res;
}
bool operator==(fd_state const &first, fd_state const &second) {
return first.fd_st == second.fd_st;
}
fd_state epoll_registration::get_state() const {
return events;
}
void swap(fd_state &first, fd_state &second) {
std::swap(first.fd_st, second.fd_st);
}
epoll_wrap::epoll_wrap(int max_queue_size) :
file_descriptor(), queue_size(max_queue_size), events(
new epoll_event[max_queue_size]), handlers{}, started{false}, stopped{
true} {
fd = epoll_create(1);
if (fd == -1) {
int err = errno;
throw annotated_exception("epoll_create", err);
}
}
epoll_wrap::epoll_wrap(epoll_wrap &&other) {
swap(*this, other);
}
epoll_event epoll_wrap::create_event(int fd,
fd_state const &st) {
epoll_event event;
memset(&event, 0, sizeof event);
event.data.fd = fd;
event.events = st.get();
return event;
}
void epoll_wrap::register_fd(const file_descriptor &fd, fd_state events) {
epoll_event event = create_event(fd.get(), events);
if (epoll_ctl(this->fd, EPOLL_CTL_ADD, fd.get(), &event)) {
int err = errno;
throw annotated_exception("epoll register", err);
}
}
void epoll_wrap::register_fd(const file_descriptor &fd, fd_state events,
handler_t handler) {
register_fd(fd, events);
handlers.insert({fd.get(), handler});
}
void epoll_wrap::unregister_fd(const file_descriptor &fd) {
if (epoll_ctl(this->fd, EPOLL_CTL_DEL, fd.get(), 0)) {
int err = errno;
throw annotated_exception("epoll_unregister", err);
}
handlers.erase(fd.get());
}
void epoll_wrap::update_fd(const file_descriptor &fd, fd_state events) {
epoll_event event = create_event(fd.get(), events);
if (epoll_ctl(this->fd, EPOLL_CTL_MOD, fd.get(), &event)) {
int err = errno;
throw annotated_exception("epoll_update", err);
}
}
void epoll_wrap::update_fd_handler(const file_descriptor &fd, epoll_wrap::handler_t handler) {
handlers.erase(fd.get());
handlers.insert({fd.get(), handler});
}
void epoll_wrap::start_wait() {
if (started) {
return;
}
started = true;
stopped = false;
while (!stopped) {
int events_number = epoll_wait(fd, events.get(), queue_size, -1);
if (events_number == -1) {
int err = errno;
if (err == EINTR) {
break;
}
throw annotated_exception("epoll_wait", err);
}
for (int i = 0; i < events_number; i++) {
int fd = events[i].data.fd;
uint32_t state = events[i].events;
handlers_t::iterator it = handlers.find(fd);
if (it != handlers.end()) {
handler_t handler = it->second;
handler(fd_state(state));
}
if (stopped) {
break;
}
}
}
started = false;
}
void epoll_wrap::stop_wait() {
stopped = true;
}
void swap(epoll_wrap &first, epoll_wrap &second) {
using std::swap;
swap(first.fd, second.fd);
swap(first.queue_size, second.queue_size);
swap(first.started, second.started);
swap(first.stopped, second.stopped);
swap(first.events, second.events);
swap(first.handlers, second.handlers);
}
void swap(endpoint &first, endpoint &second) {
std::swap(first.ip, second.ip);
std::swap(first.port, second.port);
}
std::string to_string(endpoint const &ep) {
using std::to_string;
return to_string(ep.ip) + ":" + to_string(ep.port);
}
epoll_registration::epoll_registration() : epoll(0), fd(0) { }
epoll_registration::epoll_registration(epoll_wrap &epoll, file_descriptor&& fd, fd_state state) :
epoll(&epoll), fd(std::move(fd)), events(state)
{
this->epoll->register_fd(this->fd, state);
}
epoll_registration::epoll_registration(epoll_wrap &epoll, file_descriptor&& fd, fd_state state,
epoll_wrap::handler_t handler) : epoll(&epoll), fd(std::move(fd)),
events(state) {
this->epoll->register_fd(this->fd, state, handler);
}
epoll_registration::epoll_registration(epoll_registration &&other) : epoll_registration() {
swap(*this, other);
}
epoll_registration &epoll_registration::operator=(epoll_registration &&other) {
swap(*this, other);
return *this;
}
epoll_registration::~epoll_registration() {
if (epoll != 0 && fd.get() != 0) {
epoll->unregister_fd(fd);
}
}
void epoll_registration::update(fd_state state) {
if (events != state) {
events = state;
epoll->update_fd(fd, state);
}
}
void epoll_registration::update(epoll_wrap::handler_t handler) {
epoll->update_fd_handler(fd, handler);
}
void epoll_registration::update(fd_state state, epoll_wrap::handler_t handler) {
update(state);
update(handler);
}
file_descriptor &epoll_registration::get_fd() {
return fd;
}
file_descriptor const &epoll_registration::get_fd() const {
return fd;
}
void swap(epoll_registration &first, epoll_registration &other) {
using std::swap;
swap(first.epoll, other.epoll);
swap(first.fd, other.fd);
swap(first.events, other.events);
}
std::string to_string(epoll_registration &er) {
return "registration " + std::to_string(er.get_fd().get());
}
| [
"[email protected]"
] | |
21e48a697e4e248b063c23ef93781b2a6b1ced52 | 94000d447528bd85d2c2abe4a787c370b00f7229 | /projects/katobobr/KatobobrHk/Katobobrhk.cpp | 258d24da995fc419cb6e67e12f9f4de6edd0e22d | [] | no_license | elrinor/chaos-devices | 72ea8c55a2a8a77300d3dba402b316e0801d8338 | 40d30e059c8b9a2d80f28048e39634934c1d1f0b | refs/heads/master | 2023-08-05T01:39:38.908343 | 2021-09-17T18:33:16 | 2021-09-17T18:33:16 | 33,127,293 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,765 | cpp | // Katobobrhk.cpp : Defines the entry point for the DLL application.
//
#include "stdafx.h"
#ifdef _MANAGED
#pragma managed(push, off)
#endif
HHOOK hMsgHook;
HHOOK hCBTHook;
HMODULE hInstance;
BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
hInstance = hModule;
return TRUE;
}
LRESULT CALLBACK CBTProc(int code, WPARAM wParam, LPARAM lParam)
{
switch(code)
{
case HCBT_ACTIVATE:
return 1; //prevent
case HCBT_MINMAX:
switch(lParam & 0xFFFF)
{
case SW_MAXIMIZE:
case SW_RESTORE:
case SW_SHOW:
case SW_SHOWDEFAULT:
// case SW_SHOWMAXIMIZED:
case SW_SHOWMINIMIZED:
case SW_SHOWMINNOACTIVE:
case SW_SHOWNA:
case SW_SHOWNOACTIVATE:
case SW_SHOWNORMAL:
return 1; //prevent
}
}
return 0; // allow
}
LRESULT CALLBACK GetMsgProc(int code, WPARAM wParam, LPARAM lParam)
{
MSG* pMsg = (MSG*)lParam;
//MessageBox(pMsg->hwnd, "Aaaa", "Aaaa", 0);
switch(pMsg->message)
{
case WM_SHOWWINDOW:
case WM_SETFOCUS:
case WM_ACTIVATE:
case WM_NCACTIVATE:
pMsg->message = WM_SHOWWINDOW;
pMsg->wParam = FALSE;
pMsg->lParam = 0;
break;
}
return CallNextHookEx(hMsgHook, code, wParam, lParam);
}
BOOL APIENTRY InstallHook(HWND hWnd)
{
DWORD dwThreadID;
if((dwThreadID = GetWindowThreadProcessId(hWnd, NULL)) == NULL)
return FALSE;
if((hMsgHook = SetWindowsHookEx(WH_GETMESSAGE, GetMsgProc, hInstance, dwThreadID)) == NULL)
return FALSE;
if((hCBTHook = SetWindowsHookEx(WH_CBT, CBTProc, hInstance, dwThreadID)) == NULL)
return FALSE;
return TRUE;
}
BOOL APIENTRY RemoveHook()
{
UnhookWindowsHookEx(hMsgHook);
UnhookWindowsHookEx(hCBTHook);
return TRUE;
}
#ifdef _MANAGED
#pragma managed(pop)
#endif
| [
"[email protected]"
] | |
f76cd8ee57285f6587a3bbfa8611023e41b05fa1 | 149b8627c7de2c3d0f8b9bb1175ab4d43cf4426b | /src/memento.cpp | 274e45f434908b303f109e23f4a21db21c764700 | [] | no_license | DJVantsuman/Chess | 8ccc3d5e62ad585c51b4782aa592b5bc7e0f8777 | 8590906e2fcf0bb6a240095f2a0a9bd812fcbbb4 | refs/heads/master | 2021-08-20T09:32:07.448499 | 2017-11-28T20:26:53 | 2017-11-28T20:26:53 | 112,065,948 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,038 | cpp | #include "memento.h"
Memento::Memento() {
}
Memento::~Memento() {
}
bool Memento::loadHistory() {
if (!_state.isEmpty())
_state.clear();
QFile in("history.bin");
if( in.open( QIODevice::ReadOnly ) ) {
int t, x, y;
QDataStream stream( &in );
for (int i = 0; !in.atEnd(); i += 3) {
stream >> t >> x >> y;
_state << t;
_state << x;
_state << y;
}
in.close();
return true;
}
return false;
}
void Memento::setState(QList<int> log, int playerNamber) {
QFile file("history.bin");
if(file.open(QIODevice::WriteOnly)) {
QDataStream stream(&file);
stream. setVersion(QDataStream::Qt_5_6);
for (int i = 0; i < log.size(); i++)
stream << log[i];
stream << playerNamber << playerNamber << playerNamber;
}
file.close();
}
bool Memento::getState(QList<int> & log) {
if(loadHistory()) {
log = _state;
return true;
}
return false;
}
| [
"[email protected]"
] | |
2538592cb010b0ba6bdb043cafc8bcf46474de05 | 561dbe8e4fe106fb817782e1b41ba087a6a709ea | /src/addr_map.hpp | e387763c1e7a86f3da34e20c62f99709ffbdb967 | [] | no_license | mamadcamzis/Network-Project | fe695afdd66f909826276c1afe980d825fa3a780 | e43edbf244a5c05e22f04677ca966f4a56eb85be | refs/heads/master | 2021-05-30T21:09:29.325796 | 2015-12-13T18:48:37 | 2015-12-13T18:48:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 699 | hpp | #ifndef ADDR_MAP
#define ADDR_MAP
//Attention à compiler avec le flag -std=c++0x
#include <unordered_map>
#include "AddrStorage.hpp"
#include "State.hpp"
class Equal
{
public :
bool operator() (const AddrStorage &lhs, const AddrStorage &rhs) const
{
bool addr = (lhs.paddr().compare(rhs.paddr()) == 0);
bool port = (lhs.pport().compare(rhs.pport()) == 0);
return addr && port;
};
};
class Hash
{
public :
unsigned long operator()(const AddrStorage &key) const
{
unsigned long h1 = hash<string>()(key.paddr());
unsigned long h2 = hash<string>()(key.pport());
return h1 ^ (h2 << 1);
};
};
typedef unordered_map<AddrStorage,State,Hash,Equal> addr_map;
#endif
| [
"[email protected]"
] | |
0e340b794fc847c7874054fa19d3e0a7e685537d | 6dad6531181e56efe6dd233ebfd41059876acefb | /RyEngine/src/Platform/DirectX/IndexBuffer.cpp | af3888d28c35016c8b1f712a0ba17ceaeede2f65 | [] | no_license | RyanCochlin/RyEngine | dd11cc58736642c4a25ac4f9eda8b9814acfefac | 35f424d2d8219bb791fece45d7ab23f2a6a42155 | refs/heads/master | 2023-01-12T09:40:12.621524 | 2022-12-28T07:18:06 | 2022-12-28T07:18:06 | 196,784,310 | 0 | 1 | null | 2022-01-11T08:03:53 | 2019-07-14T02:16:09 | C++ | UTF-8 | C++ | false | false | 878 | cpp | #include "pch.h"
#include "IndexBuffer.h"
#include "DirectXCore.h"
namespace RE
{
IndexBuffer::IndexBuffer(std::vector<RE_INDEX>& indicies)
{
_mIndicies = indicies;
_mIndexStride = sizeof(RE_INDEX);
_mCount = _mIndicies.size();
Create();
}
IndexBuffer::IndexBuffer(std::vector<RE_INDEX>&& indicies)
{
_mIndicies = indicies;
_mIndexStride = sizeof(RE_INDEX);
_mCount = _mIndicies.size();
Create();
}
void IndexBuffer::Create()
{
UINT byteSize = _mIndexStride * _mCount;
ThrowIfFailed(DirectXCore::GetDevice()->CreateCommittedResource(
&CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT),
D3D12_HEAP_FLAG_NONE,
&CD3DX12_RESOURCE_DESC::Buffer(byteSize),
D3D12_RESOURCE_STATE_COMMON,
nullptr,
IID_PPV_ARGS(&_mResource)));
}
D3D12_GPU_VIRTUAL_ADDRESS IndexBuffer::GetGpuAddress()
{
return _mResource->GetGPUVirtualAddress();
}
} | [
"[email protected]"
] | |
2d3b2535b886b1173d6c1dab3bb78ee35cb86884 | 1c51d07dbf227bfeb940ed4b9491ad44dd01a1d7 | /include/HashTable.hpp | 6e54560883bd516f59004c941d9a8a19e13eaf6e | [] | no_license | quebin31/qaedlib | 274f65899c334fe925013673fd2d87010804873b | cf5bfe6f8e07d7dafcd7465bffa542e8b0371cb7 | refs/heads/master | 2021-10-09T20:14:57.698167 | 2019-01-03T02:48:59 | 2019-01-03T02:48:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,515 | hpp | #ifndef QAED_HASH_TABLE_H
#define QAED_HASH_TABLE_H
#include <set>
#include <vector>
#include <iostream>
#include <functional>
#include "tools/Sfinae.hpp"
namespace qaed {
/// Consider using Size with an prime number
/// remember that hash uses modulo, if we use
/// an prime number as modulo, chances for
/// collisions in the same place are lowest,
/// and said that collisions are equally
/// distributed
template <class Type, std::size_t Size>
class Hash {
private:
using HashTable = typename std::vector<std::set<Type>>;
using HashFunction = typename std::function<std::size_t (const Type&)>;
HashTable mHash;
HashFunction mHf;
public:
Hash() : mHash(Size) {
static_assert(
std::is_arithmetic<Type>::value ||
std::is_enum<Type>::value ||
std::is_pointer<Type>::value ||
std::is_same<Type, std::string>::value ||
is_comparable<Type>::value ,
"Type is not an arithmetic, enum, pointer type nor string nor comparable object."
);
}
Hash(const HashFunction& f): mHash(Size), mHf(f) {
static_assert(
std::is_arithmetic<Type>::value ||
std::is_enum<Type>::value ||
std::is_pointer<Type>::value ||
std::is_same<Type, std::string>::value ||
is_comparable<Type>::value ,
"Type is not an arithmetic, enum, pointer type nor string nor comparable object."
);
}
/// Elements need to be comparable between them
/// Operators ==, !=, >, < should be overloaded
bool add(const Type& data) {
if (!mHf) throw std::runtime_error("Hash function was not defined");
auto result = mHash[mHf(data) % Size].insert(data);
return std::get<1>(result);
}
bool remove(const Type& data) {
if (!mHf) throw std::runtime_error("Hash function was not defined");
auto& cont = mHash[mHf(data) % Size];
auto elem = cont.find(data);
if (elem == cont.end())
return false;
cont.erase(elem);
return true;
}
/// Note how this method seems to be useless
/// but, it's powerful when using Type like
/// Records, pairs, tuples, etc, any kind of
/// object that only needs a primary key.
/// Here you pass data, like an object only
/// with the primary key you are searching for
/// (if you overloaded operators to compare, and
/// you did it) you will get the original object
/// in the Hash Table with all the data that you want
/// to query, the object returned is not
/// mutable at least that you explicitly declare
/// other member data mutable, except primary key
const Type& find(const Type& data) {
if (!mHf) throw std::runtime_error("Hash function was not defined");
auto& cont = mHash[mHf(data) % Size];
auto elem = cont.find(data);
if (elem == cont.end())
throw std::runtime_error("Element was not found");
return *elem;
}
/// Dark magic
bool update(const Type& oldest, const Type& newest) {
if (!remove(oldest)) return false;
if (!add(newest)) {
add(oldest);
return false;
}
return true;
}
void print(std::ostream& os = std::cout) {
for (std::size_t ii = 0; ii < Size; ++ii) {
std::cout << "[" << ii << "] => { ";
for (auto jj = mHash[ii].begin(); jj != mHash[ii].end(); ++jj) {
std::cout << *jj;
if (std::next(jj) != mHash[ii].end())
std::cout << ", ";
}
std::cout << " }\n";
}
}
std::size_t get_size() { return Size; }
};
}
#endif
| [
"[email protected]"
] | |
eabb6ef4cc0badd151e340bca03d8a7f55a5e18a | a98f6ac9c6395ab73ecc12533b2f6271243753de | /PersistenciaDaRede.cpp | 5257f1cb6ebc485e69f8f2cb43660f2afde2e889 | [] | no_license | henriquefalconer/ep2pcs | 7273c2c2a436c9ceca7b2908ff7ae35878bcf9da | 53f55d85c863f83e554a999915e9e5fa81075b9d | refs/heads/master | 2023-06-17T18:36:58.646641 | 2021-07-16T00:23:27 | 2021-07-16T00:23:27 | 386,443,694 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,984 | cpp | #include "PersistenciaDaRede.h"
#include <fstream>
#include "trycatch.h"
#include "Pagina.h"
#include "PessoaVerificada.h"
PersistenciaDaRede::PersistenciaDaRede(string arquivo): arquivo(arquivo) {}
PersistenciaDaRede::~PersistenciaDaRede() {}
// Methods
void PersistenciaDaRede::salvar(RedeSocial* r) {
ofstream output;
output.open(arquivo);
if (!output) // output.bad() || output.fail()
throw new logic_error("Erro ao escrever");
auto pessoasVerificadas = new vector<PessoaVerificada*>();
auto pessoas = new vector<Pessoa*>();
auto paginas = new vector<Pagina*>();
for (auto p : *r->getPerfis()) {
if (auto pv = dynamic_cast<PessoaVerificada*>(p))
pessoasVerificadas->push_back(pv);
else if (auto pg = dynamic_cast<Pagina*>(p))
paginas->push_back(pg);
else if (auto pnv = dynamic_cast<Pessoa*>(p))
pessoas->push_back(pnv);
}
output << Perfil::getUltimoId() << endl;
output << pessoas->size() << endl;
for (auto pnv : *pessoas)
output << pnv->getId() << " " << pnv->getNome() << " " << endl;
output << pessoasVerificadas->size() << endl;
for (auto pv : *pessoasVerificadas)
output << pv->getId() << " " << pv->getNome() << " " << pv->getEmail()
<< endl;
output << paginas->size() << endl;
for (auto pg : *paginas)
output << pg->getId() << " " << pg->getNome() << " "
<< pg->getProprietario()->getId() << endl;
for (auto perfil : *r->getPerfis())
for (auto contato : *perfil->getContatos())
output << perfil->getId() << " " << contato->getId() << endl;
delete pessoasVerificadas;
delete pessoas;
delete paginas;
}
RedeSocial* PersistenciaDaRede::carregar() {
auto r = new RedeSocial();
ifstream input;
input.open(arquivo);
if (!input.good()) return r;
string nome, email;
int ultimoId, id, idProprietario, idContato;
int qntdPessoas, qntdPessoasVerificadas, qntdPaginas;
input >> ultimoId >> qntdPessoas;
Perfil::setUltimoId(ultimoId);
for (int i = 0; i < qntdPessoas; i++) {
input >> id >> nome;
r->adicionar(new Pessoa(nome, id));
}
input >> qntdPessoasVerificadas;
for (int i = 0; i < qntdPessoasVerificadas; i++) {
input >> id >> nome >> email;
r->adicionar(new PessoaVerificada(nome, email, id));
}
input >> qntdPaginas;
for (int i = 0; i < qntdPaginas; i++) {
input >> id >> nome >> idProprietario;
auto p = dynamic_cast<PessoaVerificada*>(r->getPerfil(idProprietario));
r->adicionar(new Pagina(nome, p, id));
}
while (true) {
input >> id >> idContato;
if (!input) break;
auto p = r->getPerfil(id);
auto c = r->getPerfil(idContato);
tryCatch([=]() { p->adicionar(c); });
}
if (!input.eof()) throw new logic_error("Erro de leitura");
return r;
}
| [
"[email protected]"
] | |
8e9181e0df37eb2d0be92c765d8f91da8ea18632 | a6b698105aec67701cdd509cb9a48528786049d2 | /RegainEarthCheat/SDK/EDamageForceAndVisualEffectType_structs.h | 7d09a6a855d56ba2bab63d88cd690527e3aed2fa | [] | no_license | ejiaogl/RegainEarth-Cheat | 859d44d8400a3694b4e946061b20d30561c6304f | 4136c2c11e78e9dbb305e55556928dfba7f4f620 | refs/heads/master | 2023-08-29T09:39:45.222291 | 2021-10-19T19:56:05 | 2021-10-19T19:56:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 870 | h | #pragma once
// Name: RegainEart-FirtstStrike, Version: Version-1
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Enums
//---------------------------------------------------------------------------
// UserDefinedEnum EDamageForceAndVisualEffectType.EDamageForceAndVisualEffectType
enum class EDamageForceAndVisualEffectType_EDamageForceAndVisualEffectType : uint8_t
{
EDamageForceAndVisualEffectType__NewEnumerator0 = 0,
EDamageForceAndVisualEffectType__NewEnumerator1 = 1,
EDamageForceAndVisualEffectType__NewEnumerator2 = 2,
EDamageForceAndVisualEffectType__NewEnumerator3 = 3,
EDamageForceAndVisualEffectType__EDamageForceAndVisualEffectType_MAX = 4,
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"[email protected]"
] | |
3310e446aaf6da82a136476859939f83574993d1 | 2c1164c3172a69f277ab8ff56402d7eec78063f7 | /src/libs/com/server/eitServer.h | 8ef1da726025ffe0d5e7683ef77c2785685902e1 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | kamranshamaei/tarsim | 6daf28ffa717902b16586ef29acc95611a1d6404 | dcb0f28f7b1422ba125c85cd53a1420d69d466eb | refs/heads/development | 2021-09-14T12:56:45.503776 | 2021-09-02T14:15:30 | 2021-09-02T14:15:30 | 172,392,574 | 26 | 7 | Apache-2.0 | 2021-07-15T20:31:09 | 2019-02-24T21:29:49 | C++ | UTF-8 | C++ | false | false | 1,119 | h | /**
*
* @file: node.h
*
* @Created on: March 31, 2018
* @Author: Kamran Shamaei
*
*
* @brief -
* <Requirement Doc Reference>
* <Design Doc Reference>
*
* @copyright Copyright [2017-2018] Kamran Shamaei .
* All Rights Reserved.
*
* This file is subject to the terms and conditions defined in
* file 'LICENSE', which is part of this source code package.
*
*/
// IFNDEF
#ifndef EIT_SERVER_H
#define EIT_SERVER_H
//INCLUDES
#include "eitOsMsgServerReceiver.h"
#include "eitOsMsgServerSender.h"
namespace tarsim {
// FORWARD DECLARATIONS
// TYPEDEFS AND DEFINES
// ENUMS
// NAMESPACES AND STRUCTS
// CLASS DEFINITION
class EitServer
{
public:
// FUNCTIONS
EitServer(ConfigParser* cp, Kinematics* kin, Gui* gui,
int policy, int priority, unsigned int msgPriority);
virtual ~EitServer();
EitOsMsgServerReceiver* getEitOsMsgServerReceiver();
// MEMBERS
private:
// FUNCTIONS
// MEMBERS
//#if (EIT_COM_TYPE == "OsMsg")
EitOsMsgServerReceiver* m_eitOsMsgServerReceiver = nullptr;
//#endif
};
} // end of namespace tarsim
// ENDIF
#endif /* EIT_SERVER_H */
| [
"[email protected]"
] | |
c60c3f8eb5b3e47b6709d10a77d641a00fd38ffb | 2830251f3364a3ba87f7ac0e8ac8af386836bc49 | /myproj/Shader.cpp | 2ee36d0988aee794a362a8f2d3b7e801494f2461 | [] | no_license | iaomw/GLAB | 3ca7b8636e623dcba8e79743f753c916535ab338 | 78e855be3db7a49c4be4c98b06e41e9e4e4d77a4 | refs/heads/master | 2023-06-08T05:13:51.724038 | 2023-06-05T15:28:35 | 2023-06-05T15:28:35 | 115,146,338 | 1 | 0 | null | 2023-06-05T15:28:36 | 2017-12-22T19:57:16 | C++ | UTF-8 | C++ | false | false | 6,209 | cpp | #include "Shader.h"
#include <fstream>
#include <iostream>
#include <filesystem>
const static std::string shaderURI = "shaders/";
Shader::Shader(const std::string& key) {
text_to_id.clear();
auto vs = shaderURI + key + ".vs.glsl";
auto gs = shaderURI + key + ".gs.glsl";
auto fs = shaderURI + key + ".fs.glsl";
if (std::filesystem::exists(vs)) {
vertex_shader = _initShader(GL_VERTEX_SHADER, vs);
}
if (std::filesystem::exists(gs)) {
geometry_shader = _initShader(GL_GEOMETRY_SHADER, gs);
}
if (std::filesystem::exists(fs)) {
fragment_shader = _initShader(GL_FRAGMENT_SHADER, fs);
}
if (!_initProgram())
std::cout << "Error: shader not initialized properly.\n";
}
Shader::Shader(const std::string& file_vertexshader, const std::string& file_fragmentshader)
{
text_to_id.clear();
vertex_shader = _initShader(GL_VERTEX_SHADER, file_vertexshader);
fragment_shader = _initShader(GL_FRAGMENT_SHADER, file_fragmentshader);
if (!_initProgram())
std::cout << "Error: shader not initialized properly.\n";
}
Shader::Shader(const std::string& file_vertexshader, const std::string& file_geometryshader, const std::string& file_fragmentshader)
{
text_to_id.clear();
vertex_shader = _initShader(GL_VERTEX_SHADER, file_vertexshader);
geometry_shader = _initShader(GL_GEOMETRY_SHADER, file_geometryshader);
fragment_shader = _initShader(GL_FRAGMENT_SHADER, file_fragmentshader);
if (!_initProgram())
std::cout << "Error: shader not initialized properly.\n";
}
Shader::~Shader()
{
clear();
}
GLuint Shader::_initShader(GLenum type, const std::string& filename)
{
std::ifstream fin(filename);
if (!fin)
{
std::cerr << "Unable to Open File " << filename << "\n";
throw 2;
}
std::string shadertext = std::string((std::istreambuf_iterator<char>(fin)), (std::istreambuf_iterator<char>()));
const GLchar* shadertext_cstr = shadertext.c_str();
GLuint shader = glCreateShader(type);
glShaderSource(shader, 1, &shadertext_cstr, NULL);
glCompileShader(shader);
GLint compiled;
glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled);
if (!compiled) {
_shaderErrors(shader);
throw 3;
}
return shader;
}
bool Shader::_initProgram()
{
shaderprogram = glCreateProgram();
if (vertex_shader != 0) {
glAttachShader(shaderprogram, vertex_shader);
}
if (geometry_shader != 0) {
glAttachShader(shaderprogram, geometry_shader);
}
if (fragment_shader != 0) {
glAttachShader(shaderprogram, fragment_shader);
}
glLinkProgram(shaderprogram);
GLint linked;
glGetProgramiv(shaderprogram, GL_LINK_STATUS, &linked);
if (linked) glUseProgram(shaderprogram);
else {
_programErrors(shaderprogram);
return false;
}
return true;
}
void Shader::_programErrors(const GLint program) {
GLint length;
GLchar * log;
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &length);
log = new GLchar[(size_t)1 + length];
glGetProgramInfoLog(program, length, &length, log);
std::cout << "Compile Error, Log Below\n" << log << "\n";
delete[] log;
}
void Shader::_shaderErrors(const GLint shader) {
GLint length;
GLchar * log;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &length);
log = new GLchar[(size_t)1 + length];
glGetShaderInfoLog(shader, length, &length, log);
std::cout << "Compile Error, Log Below\n" << log << "\n";
delete[] log;
}
void Shader::clear()
{
glDeleteShader(vertex_shader);
glDeleteShader(geometry_shader);
glDeleteShader(fragment_shader);
glDeleteProgram(shaderprogram);
}
void Shader::start() const
{
glUseProgram(shaderprogram);
}
void Shader::stop() const
{
glUseProgram(0);
}
GLint Shader::getUniformLocation(const std::string& text)
{
if (text_to_id.find(text) == text_to_id.end())
{
int location = glGetUniformLocation(shaderprogram, text.c_str());
if (location == -1)
{
//cerr << "Error: unable to get location of variable with name: " << text << endl;
text_to_id[text] = -1;
return -1;
}
else text_to_id[text] = location;
}
return text_to_id[text];
}
void Shader::setUniform(const std::string& name, glm::mat4 & mat)
{
auto location = getUniformLocation(name);
if (-1 == location) { return; }
glUniformMatrix4fv(location, 1, GL_FALSE, glm::value_ptr(mat));
}
void Shader::setUniform(const std::string& name, glm::mat3 &mat)
{
auto location = getUniformLocation(name);
if (-1 == location) { return; }
glUniformMatrix3fv(location, 1, GL_FALSE, glm::value_ptr(mat));
}
void Shader::setUniform(const std::string& name, float val)
{
auto location = getUniformLocation(name);
if (-1 == location) { return; }
glUniform1f(location, val);
}
void Shader::setUniform(const std::string& name, int val)
{
auto location = getUniformLocation(name);
if (-1 == location) { return; }
glUniform1i(location, val);
}
void Shader::setUniform(const std::string& name, glm::vec2 vec)
{
auto location = getUniformLocation(name);
if (-1 == location) { return; }
glUniform2fv(location, 1, glm::value_ptr(vec));
}
void Shader::setUniform(const std::string& name, glm::vec3& vec)
{
auto location = getUniformLocation(name);
if (-1 == location) { return; }
glUniform3fv(location, 1, glm::value_ptr(vec));
}
void Shader::setUniform(const std::string& name, glm::vec4& vec)
{
auto location = getUniformLocation(name);
if (-1 == location) { return; }
glUniform4fv(location, 1, glm::value_ptr(vec));
}
void Shader::setUniform(const std::string& name, std::vector<glm::vec3>& input_array)
{
for (unsigned int i = 0; i < input_array.size(); ++i) {
auto location = getUniformLocation(name + "[" + std::to_string(i) + "]");
if (-1 == location) { continue; }
glUniform3fv(location, 1, &input_array[i][0]);
}
}
void Shader::setUniform(const std::string& name, std::vector<glm::vec4>& input_array)
{
//glUniform4fv(getUniformLocation(name), input_array.size(), &input_array[0][0]);
for (unsigned int i = 0; i < input_array.size(); ++i) {
auto location = getUniformLocation(name + "[" + std::to_string(i) + "]");
if (-1 == location) { return; }
glUniform4fv(location, 1, &input_array[i][0]);
}
}
void Shader::setTex(const std::string& name, GLuint texture_id, GLuint texture_offset)
{
glBindTextureUnit(texture_offset, texture_id);
this->setUniform(name, static_cast<int>(texture_offset));
}
| [
"[email protected]"
] | |
e1b4fc83630cd2b436bc4d29cba9e1e0e429ab84 | 503db631ebb3e10427d586a1f5608700aa19a3f2 | /src/qt/messagepage.cpp | 2241a9f7e09a3ef86d2933af7b838f043afb8358 | [
"MIT"
] | permissive | cryptocointalkdev/cryptotalkcoin | 1ccd3d07cdb7c415320eac2e6ded11b73cfe7277 | e9f311e2a8f39b4bb7d2136bb891c72800fb6dff | refs/heads/master | 2020-06-10T20:35:02.940159 | 2019-07-10T23:54:43 | 2019-07-10T23:54:43 | 193,737,568 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 7,601 | cpp | #include <qt/messagepage.h>
#include <qt/forms/ui_messagepage.h>
#include <qt/sendmessagesdialog.h>
#include <qt/messagemodel.h>
#include <qt/cryptotalkcoingui.h>
#include <qt/csvmodelwriter.h>
#include <qt/guiutil.h>
#include <qt/platformstyle.h>
#include <QSortFilterProxyModel>
#include <QClipboard>
#include <QMessageBox>
#include <QMenu>
MessagePage::MessagePage(const PlatformStyle *_platformStyle, QWidget *parent) :
QWidget(parent),
ui(new Ui::MessagePage),
model(nullptr),
platformStyle(_platformStyle)
{
ui->setupUi(this);
#ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac
ui->deleteButton->setIcon(QIcon());
#endif
// Context menu actions
replyAction = new QAction(ui->replyButton->text(), this);
copyFromAddressAction = new QAction(ui->copyFromAddressButton->text(), this);
copyToAddressAction = new QAction(ui->copyToAddressButton->text(), this);
deleteAction = new QAction(ui->deleteButton->text(), this);
// Build context menu
contextMenu = new QMenu();
contextMenu->addAction(replyAction);
contextMenu->addAction(copyFromAddressAction);
contextMenu->addAction(copyToAddressAction);
contextMenu->addAction(deleteAction);
connect(replyAction, SIGNAL(triggered()), this, SLOT(on_replyButton_clicked()));
connect(copyFromAddressAction, SIGNAL(triggered()), this, SLOT(on_copyFromAddressButton_clicked()));
connect(copyToAddressAction, SIGNAL(triggered()), this, SLOT(on_copyToAddressButton_clicked()));
connect(deleteAction, SIGNAL(triggered()), this, SLOT(on_deleteButton_clicked()));
connect(ui->tableView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextualMenu(QPoint)));
}
MessagePage::~MessagePage()
{
delete ui;
}
void MessagePage::setModel(MessageModel *model)
{
this->model = model;
if(!model)
return;
proxyModel = new QSortFilterProxyModel(this);
proxyModel->setSourceModel(model);
proxyModel->setDynamicSortFilter(true);
proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive);
proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive);
ui->tableView->setModel(proxyModel);
ui->tableView->sortByColumn(2, Qt::DescendingOrder);
// Set column widths
ui->tableView->horizontalHeader()->resizeSection(MessageModel::Type, 100);
ui->tableView->horizontalHeader()->resizeSection(MessageModel::Label, 100);
#if QT_VERSION < 0x050000
ui->tableView->horizontalHeader()->setResizeMode(MessageModel::Label, QHeaderView::Stretch);
#else
ui->tableView->horizontalHeader()->setSectionResizeMode(MessageModel::Label, QHeaderView::Stretch);
#endif
ui->tableView->horizontalHeader()->resizeSection(MessageModel::FromAddress, 320);
ui->tableView->horizontalHeader()->resizeSection(MessageModel::ToAddress, 320);
ui->tableView->horizontalHeader()->resizeSection(MessageModel::SentDateTime, 170);
ui->tableView->horizontalHeader()->resizeSection(MessageModel::ReceivedDateTime, 170);
// Hidden columns
ui->tableView->setColumnHidden(MessageModel::Message, true);
connect(ui->tableView->selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)),
this, SLOT(selectionChanged()));
selectionChanged();
}
void MessagePage::on_replyButton_clicked()
{
if(!model)
return;
if(!ui->tableView->selectionModel())
return;
QModelIndexList indexes = ui->tableView->selectionModel()->selectedRows();
if(indexes.isEmpty())
return;
SendMessagesDialog dlg(platformStyle,this);
dlg.setModel(model);
QModelIndex origIndex = proxyModel->mapToSource(indexes.at(0));
dlg.loadRow(origIndex.row());
dlg.exec();
}
void MessagePage::on_copyFromAddressButton_clicked()
{
GUIUtil::copyEntryData(ui->tableView, MessageModel::FromAddress, Qt::DisplayRole);
}
void MessagePage::on_copyToAddressButton_clicked()
{
GUIUtil::copyEntryData(ui->tableView, MessageModel::ToAddress, Qt::DisplayRole);
}
void MessagePage::on_deleteButton_clicked()
{
QTableView *table = ui->tableView;
if(!table->selectionModel())
return;
QModelIndexList indexes = table->selectionModel()->selectedRows();
if(!indexes.isEmpty())
{
table->model()->removeRow(indexes.at(0).row());
}
}
void MessagePage::selectionChanged()
{
// Set button states based on selected tab and selection
QTableView *table = ui->tableView;
if(!table->selectionModel())
return;
if(table->selectionModel()->hasSelection())
{
replyAction->setEnabled(true);
copyFromAddressAction->setEnabled(true);
copyToAddressAction->setEnabled(true);
deleteAction->setEnabled(true);
ui->copyFromAddressButton->setEnabled(true);
ui->copyToAddressButton->setEnabled(true);
ui->replyButton->setEnabled(true);
ui->deleteButton->setEnabled(true);
ui->messageDetails->show();
// Figure out which message was selected, and return it
QModelIndexList messageColumn = table->selectionModel()->selectedRows(MessageModel::Message);
QModelIndexList labelColumn = table->selectionModel()->selectedRows(MessageModel::Label);
QModelIndexList typeColumn = table->selectionModel()->selectedRows(MessageModel::Type);
for (QModelIndex index: messageColumn)
{
ui->message->setPlainText(table->model()->data(index).toString());
}
for (QModelIndex index: typeColumn)
{
ui->labelType->setText(table->model()->data(index).toString());
}
for(QModelIndex index: labelColumn)
{
ui->contactLabel->setText(table->model()->data(index).toString());
}
}
else
{
ui->replyButton->setEnabled(false);
ui->copyFromAddressButton->setEnabled(false);
ui->copyToAddressButton->setEnabled(false);
ui->deleteButton->setEnabled(false);
ui->messageDetails->hide();
ui->message->clear();
}
}
void MessagePage::exportClicked()
{
// CSV is currently the only supported format
QString filename = GUIUtil::getSaveFileName(
this,
tr("Export Messages"), QString(),
tr("Comma separated file (*.csv)"), NULL);
if (filename.isNull()) return;
CSVModelWriter writer(filename);
// name, column, role
writer.setModel(proxyModel);
writer.addColumn("Type", MessageModel::Type, Qt::DisplayRole);
writer.addColumn("Label", MessageModel::Label, Qt::DisplayRole);
writer.addColumn("FromAddress", MessageModel::FromAddress, Qt::DisplayRole);
writer.addColumn("ToAddress", MessageModel::ToAddress, Qt::DisplayRole);
writer.addColumn("SentDateTime", MessageModel::SentDateTime, Qt::DisplayRole);
writer.addColumn("ReceivedDateTime", MessageModel::ReceivedDateTime, Qt::DisplayRole);
writer.addColumn("Message", MessageModel::Message, Qt::DisplayRole);
if(!writer.write())
{
QMessageBox::critical(this, tr("Error exporting"), tr("Could not write to file %1.").arg(filename),
QMessageBox::Abort, QMessageBox::Abort);
}
}
void MessagePage::contextualMenu(const QPoint &point)
{
QModelIndex index = ui->tableView->indexAt(point);
if(index.isValid())
{
contextMenu->exec(QCursor::pos());
}
}
| [
"[email protected]"
] | |
0beeb1700ebcb1d2e294dee05d5d23f06ccbe50e | 5ecc04d0d5055f90e5900d6c923ffca19d4fe1db | /IRelectra.h | fcfab677e14123bdcf3c48461c9fa16147f1c1d5 | [
"MIT"
] | permissive | legopart/Alonf_UniversalACRemote | bd33d773f5030a11cdfd74fbd251a002ec2ad8d5 | 6d4bb6e475a5f71e264a4b48a757ae182df796aa | refs/heads/master | 2023-03-15T21:02:57.211220 | 2020-08-25T00:01:41 | 2020-08-25T00:01:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,302 | h | /*
* IRelectra
* Thanks to Barak Weiss and Chris from AnalysIR
*/
#pragma once
#ifndef IRelectra_h
#define IRelectra_h
//#include <IRremoteInt.h>
#include <IRsend.h>
enum class IRElectraMode : uint8_t
{
Cool = 0b001,
Heat = 0b010,
Fan = 0b101,
Dry = 0b100,
Auto = 0b011
};
enum class IRElectraFan : uint8_t
{
Low = 0b00,
Medium = 0b01,
High = 0b10,
Auto = 0b11
};
enum class IRElectraSwing : uint8_t
{
Off = 0b0,
On = 0b1
};
enum class IRElectraSleep : uint8_t
{
Off = 0b0,
On = 0b1
};
enum class IRElectraIFeel : uint8_t
{
Off = 0b0,
On = 0b1
};
enum class IRElectraPower : uint8_t
{
None = 0b0,
OnOffToggle = 0b1
};
class IRelectra
{
public:
// Ctor, remote will be used to send the raw IR data
IRelectra(IRsend* remote);
// Sends the specified configuration to the IR led using IRremote
bool SendElectra(IRElectraPower power, IRElectraMode mode, IRElectraFan fan, int temperature, IRElectraSwing swing, IRElectraSleep sleep, IRElectraIFeel iFeel);
private:
IRsend* _remote;
uint64_t EncodeElectra(IRElectraPower power, IRElectraMode mode, IRElectraFan fan, int temperature, IRElectraSwing swing, IRElectraSleep sleep, IRElectraIFeel iFeel);
static void AddBit(uint16_t* p, int* i, char b);
};
#endif | [
"[email protected]"
] | |
fed25bcb4412055a83a8bc026380d41a5eaf5365 | 64e4fabf9b43b6b02b14b9df7e1751732b30ad38 | /src/chromium/services/network/resource_scheduler_unittest.cc | 519990c105d6b0a0361e84ba8863ed085327b31c | [
"BSD-3-Clause"
] | permissive | ivan-kits/skia-opengl-emscripten | 8a5ee0eab0214c84df3cd7eef37c8ba54acb045e | 79573e1ee794061bdcfd88cacdb75243eff5f6f0 | refs/heads/master | 2023-02-03T16:39:20.556706 | 2020-12-25T14:00:49 | 2020-12-25T14:00:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 78,596 | 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 "services/network/resource_scheduler.h"
#include <map>
#include <memory>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include "base/bind.h"
#include "base/memory/ref_counted.h"
#include "base/message_loop/message_loop.h"
#include "base/metrics/field_trial.h"
#include "base/metrics/field_trial_param_associator.h"
#include "base/metrics/field_trial_params.h"
#include "base/run_loop.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/mock_entropy_provider.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/simple_test_tick_clock.h"
#include "base/test/test_mock_time_task_runner.h"
#include "base/timer/timer.h"
#include "net/base/host_port_pair.h"
#include "net/base/load_timing_info.h"
#include "net/base/request_priority.h"
#include "net/http/http_server_properties_impl.h"
#include "net/nqe/network_quality_estimator_test_util.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_test_util.h"
#include "services/network/public/cpp/features.h"
#include "services/network/public/mojom/network_context.mojom.h"
#include "services/network/resource_scheduler_params_manager.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/scheme_host_port.h"
using std::string;
namespace network {
namespace {
// Verifies that (i) Exactly one sample is recorded in |histogram_name|; and,
// (ii) The sample value is at least |min_value|.
void ExpectSampleIsAtLeastSpecifiedValue(
const base::HistogramTester& histogram_tester,
const std::string& histogram_name,
int min_value) {
histogram_tester.ExpectTotalCount(histogram_name, 1);
// Verify if the recorded unique sample is in the same bucket to which
// |min_value| belongs to.
if (histogram_tester.GetBucketCount(histogram_name, min_value) == 1) {
return;
}
// Verify if the recorded unique sample is in a bucket that contains samples
// larger than |min_value|.
const std::vector<base::Bucket> buckets =
histogram_tester.GetAllSamples(histogram_name);
EXPECT_EQ(1u, buckets.size());
bool sample_found = false;
for (const auto& bucket : buckets) {
if (bucket.count > 0) {
// Verify that the sample is at least |min_value|.
EXPECT_GE(bucket.min, min_value);
sample_found = true;
}
}
EXPECT_TRUE(sample_found);
}
class TestRequestFactory;
const int kChildId = 30;
const int kRouteId = 75;
const int kChildId2 = 43;
const int kRouteId2 = 67;
const int kBackgroundChildId = 35;
const int kBackgroundRouteId = 43;
const int kBrowserChildId = mojom::kBrowserProcessId;
const int kBrowserRouteId = 1;
const size_t kMaxNumDelayableRequestsPerHostPerClient = 6;
class TestRequest {
public:
TestRequest(std::unique_ptr<net::URLRequest> url_request,
std::unique_ptr<ResourceScheduler::ScheduledResourceRequest>
scheduled_request,
ResourceScheduler* scheduler)
: started_(false),
url_request_(std::move(url_request)),
scheduled_request_(std::move(scheduled_request)),
scheduler_(scheduler) {
scheduled_request_->set_resume_callback(
base::BindRepeating(&TestRequest::Resume, base::Unretained(this)));
}
virtual ~TestRequest() {
// The URLRequest must still be valid when the ScheduledResourceRequest is
// destroyed, so that it can unregister itself.
scheduled_request_.reset();
}
bool started() const { return started_; }
void Start() {
bool deferred = false;
scheduled_request_->WillStartRequest(&deferred);
started_ = !deferred;
}
void ChangePriority(net::RequestPriority new_priority, int intra_priority) {
scheduler_->ReprioritizeRequest(url_request_.get(), new_priority,
intra_priority);
}
const net::URLRequest* url_request() const { return url_request_.get(); }
virtual void Resume() { started_ = true; }
private:
bool started_;
std::unique_ptr<net::URLRequest> url_request_;
std::unique_ptr<ResourceScheduler::ScheduledResourceRequest>
scheduled_request_;
ResourceScheduler* scheduler_;
};
class CancelingTestRequest : public TestRequest {
public:
CancelingTestRequest(
std::unique_ptr<net::URLRequest> url_request,
std::unique_ptr<ResourceScheduler::ScheduledResourceRequest>
scheduled_request,
ResourceScheduler* scheduler)
: TestRequest(std::move(url_request),
std::move(scheduled_request),
scheduler) {}
void set_request_to_cancel(std::unique_ptr<TestRequest> request_to_cancel) {
request_to_cancel_ = std::move(request_to_cancel);
}
private:
void Resume() override {
TestRequest::Resume();
request_to_cancel_.reset();
}
std::unique_ptr<TestRequest> request_to_cancel_;
};
class ResourceSchedulerTest : public testing::Test {
protected:
ResourceSchedulerTest() : field_trial_list_(nullptr) {
base::FieldTrialParamAssociator::GetInstance()->ClearAllParamsForTesting();
InitializeScheduler();
context_.set_http_server_properties(&http_server_properties_);
context_.set_network_quality_estimator(&network_quality_estimator_);
}
~ResourceSchedulerTest() override { CleanupScheduler(); }
// Done separately from construction to allow for modification of command
// line flags in tests.
void InitializeScheduler(bool enabled = true) {
CleanupScheduler();
// Destroys previous scheduler.
scheduler_.reset(new ResourceScheduler(enabled, &tick_clock_));
scheduler()->SetResourceSchedulerParamsManagerForTests(
resource_scheduler_params_manager_);
scheduler_->OnClientCreated(kChildId, kRouteId,
&network_quality_estimator_);
scheduler_->OnClientCreated(kBackgroundChildId, kBackgroundRouteId,
&network_quality_estimator_);
scheduler_->OnClientCreated(kBrowserChildId, kBrowserRouteId,
&network_quality_estimator_);
}
ResourceSchedulerParamsManager FixedParamsManager(
size_t max_delayable_requests) const {
ResourceSchedulerParamsManager::ParamsForNetworkQualityContainer c;
for (int i = 0; i != net::EFFECTIVE_CONNECTION_TYPE_LAST; ++i) {
auto type = static_cast<net::EffectiveConnectionType>(i);
c[type] = ResourceSchedulerParamsManager::ParamsForNetworkQuality(
max_delayable_requests, 0.0, false, base::nullopt);
}
return ResourceSchedulerParamsManager(std::move(c));
}
void SetMaxDelayableRequests(size_t max_delayable_requests) {
scheduler()->SetResourceSchedulerParamsManagerForTests(
ResourceSchedulerParamsManager(
FixedParamsManager(max_delayable_requests)));
}
void CleanupScheduler() {
if (scheduler_) {
scheduler_->OnClientDeleted(kChildId, kRouteId);
scheduler_->OnClientDeleted(kBackgroundChildId, kBackgroundRouteId);
scheduler_->OnClientDeleted(kBrowserChildId, kBrowserRouteId);
}
}
std::unique_ptr<net::URLRequest> NewURLRequestWithChildAndRoute(
const char* url,
net::RequestPriority priority,
int child_id,
int route_id) {
std::unique_ptr<net::URLRequest> url_request(context_.CreateRequest(
GURL(url), priority, nullptr, TRAFFIC_ANNOTATION_FOR_TESTS));
return url_request;
}
std::unique_ptr<net::URLRequest> NewURLRequest(
const char* url,
net::RequestPriority priority) {
return NewURLRequestWithChildAndRoute(url, priority, kChildId, kRouteId);
}
std::unique_ptr<TestRequest> NewRequestWithRoute(
const char* url,
net::RequestPriority priority,
int route_id) {
return NewRequestWithChildAndRoute(url, priority, kChildId, route_id);
}
std::unique_ptr<TestRequest> NewRequestWithChildAndRoute(
const char* url,
net::RequestPriority priority,
int child_id,
int route_id) {
return GetNewTestRequest(url, priority, child_id, route_id, true);
}
std::unique_ptr<TestRequest> NewRequest(const char* url,
net::RequestPriority priority) {
return NewRequestWithChildAndRoute(url, priority, kChildId, kRouteId);
}
std::unique_ptr<TestRequest> NewBackgroundRequest(
const char* url,
net::RequestPriority priority) {
return NewRequestWithChildAndRoute(url, priority, kBackgroundChildId,
kBackgroundRouteId);
}
std::unique_ptr<TestRequest> NewBrowserRequest(
const char* url,
net::RequestPriority priority) {
return NewRequestWithChildAndRoute(url, priority, kBrowserChildId,
kBrowserRouteId);
}
std::unique_ptr<TestRequest> NewSyncRequest(const char* url,
net::RequestPriority priority) {
return NewSyncRequestWithChildAndRoute(url, priority, kChildId, kRouteId);
}
std::unique_ptr<TestRequest> NewBackgroundSyncRequest(
const char* url,
net::RequestPriority priority) {
return NewSyncRequestWithChildAndRoute(url, priority, kBackgroundChildId,
kBackgroundRouteId);
}
std::unique_ptr<TestRequest> NewSyncRequestWithChildAndRoute(
const char* url,
net::RequestPriority priority,
int child_id,
int route_id) {
return GetNewTestRequest(url, priority, child_id, route_id, false);
}
std::unique_ptr<TestRequest> GetNewTestRequest(const char* url,
net::RequestPriority priority,
int child_id,
int route_id,
bool is_async) {
std::unique_ptr<net::URLRequest> url_request(
NewURLRequestWithChildAndRoute(url, priority, child_id, route_id));
auto scheduled_request = scheduler_->ScheduleRequest(
child_id, route_id, is_async, url_request.get());
auto request = std::make_unique<TestRequest>(
std::move(url_request), std::move(scheduled_request), scheduler());
request->Start();
return request;
}
void ChangeRequestPriority(TestRequest* request,
net::RequestPriority new_priority,
int intra_priority = 0) {
request->ChangePriority(new_priority, intra_priority);
}
void RequestLimitOverrideConfigTestHelper(bool experiment_status) {
InitializeThrottleDelayableExperiment(experiment_status, 0.0);
// Set the effective connection type to Slow-2G, which is slower than the
// threshold configured in |InitializeThrottleDelayableExperiment|. Needs
// to be done before initializing the scheduler because the client is
// created on the call to |InitializeScheduler|, which is where the initial
// limits for the delayable requests in flight are computed.
network_quality_estimator_.SetAndNotifyObserversOfEffectiveConnectionType(
net::EFFECTIVE_CONNECTION_TYPE_SLOW_2G);
// Initialize the scheduler.
InitializeScheduler();
// Throw in one high priority request to ensure that high priority requests
// do not depend on anything.
std::unique_ptr<TestRequest> high2(
NewRequest("http://host/high2", net::HIGHEST));
EXPECT_TRUE(high2->started());
// Should match the configuration set by
// |InitializeThrottleDelayableExperiment|
const int kOverriddenNumRequests = 2;
std::vector<std::unique_ptr<TestRequest>> lows_singlehost;
// Queue the maximum number of delayable requests that should be started
// before the resource scheduler starts throttling delayable requests.
for (int i = 0; i < kOverriddenNumRequests; ++i) {
std::string url = "http://host/low" + base::NumberToString(i);
lows_singlehost.push_back(NewRequest(url.c_str(), net::LOWEST));
EXPECT_TRUE(lows_singlehost[i]->started());
}
std::unique_ptr<TestRequest> second_last_singlehost(
NewRequest("http://host/s_last", net::LOWEST));
std::unique_ptr<TestRequest> last_singlehost(
NewRequest("http://host/last", net::LOWEST));
if (experiment_status) {
// Experiment enabled, hence requests should be limited.
// Second last should not start because there are |kOverridenNumRequests|
// delayable requests already in-flight.
EXPECT_FALSE(second_last_singlehost->started());
// Completion of a delayable request must result in starting of the
// second-last request.
lows_singlehost.erase(lows_singlehost.begin());
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(second_last_singlehost->started());
EXPECT_FALSE(last_singlehost->started());
// Completion of another delayable request must result in starting of the
// last request.
lows_singlehost.erase(lows_singlehost.begin());
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(last_singlehost->started());
} else {
// Requests should start because the default limit is 10.
EXPECT_TRUE(second_last_singlehost->started());
EXPECT_TRUE(last_singlehost->started());
}
}
void ConfigureDelayRequestsOnMultiplexedConnectionsFieldTrial() {
std::map<net::EffectiveConnectionType,
ResourceSchedulerParamsManager::ParamsForNetworkQuality>
params_for_network_quality_container;
ResourceSchedulerParamsManager::ParamsForNetworkQuality params_slow_2g(
8, 3.0, true, base::nullopt);
ResourceSchedulerParamsManager::ParamsForNetworkQuality params_2g(
8, 3.0, true, base::nullopt);
params_for_network_quality_container
[net::EFFECTIVE_CONNECTION_TYPE_SLOW_2G] = params_slow_2g;
params_for_network_quality_container[net::EFFECTIVE_CONNECTION_TYPE_2G] =
params_2g;
resource_scheduler_params_manager_.Reset(
params_for_network_quality_container);
}
void InitializeThrottleDelayableExperiment(bool lower_delayable_count_enabled,
double non_delayable_weight) {
std::map<net::EffectiveConnectionType,
ResourceSchedulerParamsManager::ParamsForNetworkQuality>
params_for_network_quality_container;
ResourceSchedulerParamsManager::ParamsForNetworkQuality params_slow_2g(
8, 3.0, false, base::nullopt);
ResourceSchedulerParamsManager::ParamsForNetworkQuality params_3g(
10, 0.0, false, base::nullopt);
if (lower_delayable_count_enabled) {
params_slow_2g.max_delayable_requests = 2;
params_slow_2g.non_delayable_weight = 0.0;
params_3g.max_delayable_requests = 4;
params_3g.non_delayable_weight = 0.0;
}
if (non_delayable_weight > 0.0) {
if (!lower_delayable_count_enabled)
params_slow_2g.max_delayable_requests = 8;
params_slow_2g.non_delayable_weight = non_delayable_weight;
}
params_for_network_quality_container
[net::EFFECTIVE_CONNECTION_TYPE_SLOW_2G] = params_slow_2g;
params_for_network_quality_container[net::EFFECTIVE_CONNECTION_TYPE_3G] =
params_3g;
resource_scheduler_params_manager_.Reset(
params_for_network_quality_container);
}
void InitializeMaxQueuingDelayExperiment(base::TimeDelta max_queuing_time) {
std::map<net::EffectiveConnectionType,
ResourceSchedulerParamsManager::ParamsForNetworkQuality>
params_for_network_quality_container;
ResourceSchedulerParamsManager::ParamsForNetworkQuality params_slow_2g(
8, 3.0, true, base::nullopt);
params_slow_2g.max_queuing_time = max_queuing_time;
params_for_network_quality_container
[net::EFFECTIVE_CONNECTION_TYPE_SLOW_2G] = params_slow_2g;
resource_scheduler_params_manager_.Reset(
params_for_network_quality_container);
}
void NonDelayableThrottlesDelayableHelper(double non_delayable_weight) {
// Should be in sync with .cc for ECT SLOW_2G,
const int kDefaultMaxNumDelayableRequestsPerClient = 8;
// Initialize the experiment.
InitializeThrottleDelayableExperiment(false, non_delayable_weight);
network_quality_estimator_.SetAndNotifyObserversOfEffectiveConnectionType(
net::EFFECTIVE_CONNECTION_TYPE_SLOW_2G);
InitializeScheduler();
// Start one non-delayable request.
std::unique_ptr<TestRequest> non_delayable_request(
NewRequest("http://host/medium", net::MEDIUM));
// Start |kDefaultMaxNumDelayableRequestsPerClient - 1 *
// |non_delayable_weight| delayable requests. They should all start.
std::vector<std::unique_ptr<TestRequest>> delayable_requests;
for (int i = 0;
i < kDefaultMaxNumDelayableRequestsPerClient - non_delayable_weight;
++i) {
delayable_requests.push_back(NewRequest(
base::StringPrintf("http://host%d/low", i).c_str(), net::LOWEST));
EXPECT_TRUE(delayable_requests.back()->started());
}
// The next delayable request should not start.
std::unique_ptr<TestRequest> last_low(
NewRequest("http://lasthost/low", net::LOWEST));
EXPECT_FALSE(last_low->started());
}
ResourceScheduler* scheduler() { return scheduler_.get(); }
base::MessageLoop message_loop_;
std::unique_ptr<ResourceScheduler> scheduler_;
net::HttpServerPropertiesImpl http_server_properties_;
net::TestNetworkQualityEstimator network_quality_estimator_;
net::TestURLRequestContext context_;
ResourceSchedulerParamsManager resource_scheduler_params_manager_;
base::FieldTrialList field_trial_list_;
base::SimpleTestTickClock tick_clock_;
};
TEST_F(ResourceSchedulerTest, OneIsolatedLowRequest) {
std::unique_ptr<TestRequest> request(
NewRequest("http://host/1", net::LOWEST));
EXPECT_TRUE(request->started());
}
TEST_F(ResourceSchedulerTest, OneLowLoadsUntilCriticalComplete) {
base::HistogramTester histogram_tester;
SetMaxDelayableRequests(1);
std::unique_ptr<TestRequest> high(
NewRequest("http://host/high", net::HIGHEST));
std::unique_ptr<TestRequest> low(NewRequest("http://host/low", net::LOWEST));
std::unique_ptr<TestRequest> low2(NewRequest("http://host/low", net::LOWEST));
EXPECT_TRUE(high->started());
EXPECT_TRUE(low->started());
EXPECT_FALSE(low2->started());
SetMaxDelayableRequests(10);
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(low2->started());
high.reset();
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(low2->started());
histogram_tester.ExpectTotalCount(
"ResourceScheduler.RequestQueuingDuration.Priority" +
base::NumberToString(net::HIGHEST),
1);
histogram_tester.ExpectTotalCount(
"ResourceScheduler.RequestQueuingDuration.Priority" +
base::NumberToString(net::LOWEST),
2);
}
TEST_F(ResourceSchedulerTest, MaxRequestsPerHostForSpdyWhenNotDelayable) {
base::test::ScopedFeatureList scoped_feature_list;
InitializeScheduler();
http_server_properties_.SetSupportsSpdy(
url::SchemeHostPort("https", "spdyhost", 443), true);
// Add more than max-per-host low-priority requests.
std::vector<std::unique_ptr<TestRequest>> requests;
for (size_t i = 0; i < kMaxNumDelayableRequestsPerHostPerClient + 1; ++i)
requests.push_back(NewRequest("https://spdyhost/low", net::LOWEST));
// No throttling.
for (const auto& request : requests)
EXPECT_TRUE(request->started());
}
TEST_F(ResourceSchedulerTest, BackgroundRequestStartsImmediately) {
const int route_id = 0; // Indicates a background request.
std::unique_ptr<TestRequest> request(
NewRequestWithRoute("http://host/1", net::LOWEST, route_id));
EXPECT_TRUE(request->started());
}
TEST_F(ResourceSchedulerTest, CancelOtherRequestsWhileResuming) {
SetMaxDelayableRequests(1);
std::unique_ptr<TestRequest> high(
NewRequest("http://host/high", net::HIGHEST));
std::unique_ptr<TestRequest> low1(
NewRequest("http://host/low1", net::LOWEST));
std::unique_ptr<net::URLRequest> url_request(
NewURLRequest("http://host/low2", net::LOWEST));
auto scheduled_request =
scheduler()->ScheduleRequest(kChildId, kRouteId, true, url_request.get());
std::unique_ptr<CancelingTestRequest> low2(new CancelingTestRequest(
std::move(url_request), std::move(scheduled_request), scheduler()));
low2->Start();
std::unique_ptr<TestRequest> low3(
NewRequest("http://host/low3", net::LOWEST));
low2->set_request_to_cancel(std::move(low3));
std::unique_ptr<TestRequest> low4(
NewRequest("http://host/low4", net::LOWEST));
EXPECT_TRUE(high->started());
EXPECT_FALSE(low2->started());
SetMaxDelayableRequests(10);
high.reset();
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(low1->started());
EXPECT_TRUE(low2->started());
EXPECT_TRUE(low4->started());
}
TEST_F(ResourceSchedulerTest, LimitedNumberOfDelayableRequestsInFlight) {
// Throw in one high priority request to make sure that's not a factor.
std::unique_ptr<TestRequest> high(
NewRequest("http://host/high", net::HIGHEST));
EXPECT_TRUE(high->started());
const int kDefaultMaxNumDelayableRequestsPerClient =
10; // Should match the .cc.
const int kMaxNumDelayableRequestsPerHost = 6;
std::vector<std::unique_ptr<TestRequest>> lows_singlehost;
// Queue up to the per-host limit (we subtract the current high-pri request).
for (int i = 0; i < kMaxNumDelayableRequestsPerHost - 1; ++i) {
string url = "http://host/low" + base::NumberToString(i);
lows_singlehost.push_back(NewRequest(url.c_str(), net::LOWEST));
EXPECT_TRUE(lows_singlehost[i]->started());
}
std::unique_ptr<TestRequest> second_last_singlehost(
NewRequest("http://host/last", net::LOWEST));
std::unique_ptr<TestRequest> last_singlehost(
NewRequest("http://host/s_last", net::LOWEST));
EXPECT_FALSE(second_last_singlehost->started());
high.reset();
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(second_last_singlehost->started());
EXPECT_FALSE(last_singlehost->started());
lows_singlehost.erase(lows_singlehost.begin());
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(last_singlehost->started());
// Queue more requests from different hosts until we reach the total limit.
int expected_slots_left = kDefaultMaxNumDelayableRequestsPerClient -
kMaxNumDelayableRequestsPerHost;
EXPECT_GT(expected_slots_left, 0);
std::vector<std::unique_ptr<TestRequest>> lows_different_host;
base::RunLoop().RunUntilIdle();
for (int i = 0; i < expected_slots_left; ++i) {
string url = "http://host" + base::NumberToString(i) + "/low";
lows_different_host.push_back(NewRequest(url.c_str(), net::LOWEST));
EXPECT_TRUE(lows_different_host[i]->started());
}
std::unique_ptr<TestRequest> last_different_host(
NewRequest("http://host_new/last", net::LOWEST));
EXPECT_FALSE(last_different_host->started());
}
TEST_F(ResourceSchedulerTest, RaisePriorityAndStart) {
// Dummies to enforce scheduling.
SetMaxDelayableRequests(1);
std::unique_ptr<TestRequest> high(
NewRequest("http://host/high", net::HIGHEST));
std::unique_ptr<TestRequest> low(NewRequest("http://host/req", net::LOWEST));
std::unique_ptr<TestRequest> request(
NewRequest("http://host/req", net::LOWEST));
EXPECT_FALSE(request->started());
ChangeRequestPriority(request.get(), net::HIGHEST);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(request->started());
}
TEST_F(ResourceSchedulerTest, RaisePriorityInQueue) {
// Dummies to enforce scheduling.
SetMaxDelayableRequests(1);
std::unique_ptr<TestRequest> high(
NewRequest("http://host/high", net::HIGHEST));
std::unique_ptr<TestRequest> low(NewRequest("http://host/low", net::LOWEST));
std::unique_ptr<TestRequest> request(
NewRequest("http://host/req", net::IDLE));
std::unique_ptr<TestRequest> idle(NewRequest("http://host/idle", net::IDLE));
EXPECT_FALSE(request->started());
EXPECT_FALSE(idle->started());
ChangeRequestPriority(request.get(), net::LOWEST);
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(request->started());
EXPECT_FALSE(idle->started());
const int kDefaultMaxNumDelayableRequestsPerClient = 10;
std::vector<std::unique_ptr<TestRequest>> lows;
for (int i = 0; i < kDefaultMaxNumDelayableRequestsPerClient - 1; ++i) {
string url = "http://host/low" + base::NumberToString(i);
lows.push_back(NewRequest(url.c_str(), net::LOWEST));
}
SetMaxDelayableRequests(kDefaultMaxNumDelayableRequestsPerClient);
high.reset();
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(request->started());
EXPECT_FALSE(idle->started());
}
TEST_F(ResourceSchedulerTest, LowerPriority) {
SetMaxDelayableRequests(1);
// Dummies to enforce scheduling.
std::unique_ptr<TestRequest> high(
NewRequest("http://host/high", net::HIGHEST));
std::unique_ptr<TestRequest> low(NewRequest("http://host/low", net::LOWEST));
std::unique_ptr<TestRequest> request(
NewRequest("http://host/req", net::LOWEST));
std::unique_ptr<TestRequest> idle(NewRequest("http://host/idle", net::IDLE));
EXPECT_FALSE(request->started());
EXPECT_FALSE(idle->started());
ChangeRequestPriority(request.get(), net::IDLE);
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(request->started());
EXPECT_FALSE(idle->started());
const int kDefaultMaxNumDelayableRequestsPerClient =
10; // Should match the .cc.
// 2 fewer filler requests: 1 for the "low" dummy at the start, and 1 for the
// one at the end, which will be tested.
const int kNumFillerRequests = kDefaultMaxNumDelayableRequestsPerClient - 2;
std::vector<std::unique_ptr<TestRequest>> lows;
for (int i = 0; i < kNumFillerRequests; ++i) {
string url = "http://host" + base::NumberToString(i) + "/low";
lows.push_back(NewRequest(url.c_str(), net::LOWEST));
}
SetMaxDelayableRequests(10);
high.reset();
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(request->started());
EXPECT_TRUE(idle->started());
}
// Verify that browser requests are not throttled by the resource scheduler.
TEST_F(ResourceSchedulerTest, LowerPriorityBrowserRequestsNotThrottled) {
SetMaxDelayableRequests(1);
// Dummies to enforce scheduling.
std::unique_ptr<TestRequest> high(
NewBrowserRequest("http://host/high", net::HIGHEST));
std::unique_ptr<TestRequest> low(
NewBrowserRequest("http://host/low", net::LOWEST));
std::unique_ptr<TestRequest> request(
NewBrowserRequest("http://host/req", net::LOWEST));
std::unique_ptr<TestRequest> idle(
NewBrowserRequest("http://host/idle", net::IDLE));
EXPECT_TRUE(request->started());
EXPECT_TRUE(idle->started());
const int kDefaultMaxNumDelayableRequestsPerClient =
10; // Should match the .cc.
// Create more requests than kDefaultMaxNumDelayableRequestsPerClient. All
// requests should be started immediately.
std::vector<std::unique_ptr<TestRequest>> lows;
for (int i = 0; i < kDefaultMaxNumDelayableRequestsPerClient + 1; ++i) {
string url = "http://host" + base::NumberToString(i) + "/low";
lows.push_back(NewBrowserRequest(url.c_str(), net::LOWEST));
EXPECT_TRUE(lows.back()->started());
}
}
TEST_F(ResourceSchedulerTest, ReprioritizedRequestGoesToBackOfQueue) {
// Dummies to enforce scheduling.
SetMaxDelayableRequests(1);
std::unique_ptr<TestRequest> high(
NewRequest("http://host/high", net::HIGHEST));
std::unique_ptr<TestRequest> low(NewRequest("http://host/low", net::LOWEST));
std::unique_ptr<TestRequest> request(
NewRequest("http://host/req", net::LOWEST));
std::unique_ptr<TestRequest> idle(NewRequest("http://host/idle", net::IDLE));
EXPECT_FALSE(request->started());
EXPECT_FALSE(idle->started());
const int kDefaultMaxNumDelayableRequestsPerClient = 0;
std::vector<std::unique_ptr<TestRequest>> lows;
for (int i = 0; i < kDefaultMaxNumDelayableRequestsPerClient; ++i) {
string url = "http://host/low" + base::NumberToString(i);
lows.push_back(NewRequest(url.c_str(), net::LOWEST));
}
SetMaxDelayableRequests(kDefaultMaxNumDelayableRequestsPerClient);
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(request->started());
EXPECT_FALSE(idle->started());
ChangeRequestPriority(request.get(), net::LOWEST);
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(request->started());
EXPECT_FALSE(idle->started());
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(request->started());
EXPECT_FALSE(idle->started());
}
TEST_F(ResourceSchedulerTest, HigherIntraPriorityGoesToFrontOfQueue) {
// Dummies to enforce scheduling.
std::unique_ptr<TestRequest> high(
NewRequest("http://host/high", net::HIGHEST));
std::unique_ptr<TestRequest> low(NewRequest("http://host/low", net::LOWEST));
const int kDefaultMaxNumDelayableRequestsPerClient =
10; // Should match the .cc.
std::vector<std::unique_ptr<TestRequest>> lows;
for (int i = 0; i < kDefaultMaxNumDelayableRequestsPerClient; ++i) {
string url = "http://host/low" + base::NumberToString(i);
lows.push_back(NewRequest(url.c_str(), net::IDLE));
}
std::unique_ptr<TestRequest> request(
NewRequest("http://host/req", net::IDLE));
EXPECT_FALSE(request->started());
ChangeRequestPriority(request.get(), net::IDLE, 1);
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(request->started());
high.reset();
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(request->started());
}
TEST_F(ResourceSchedulerTest, NonHTTPSchedulesImmediately) {
// Dummies to enforce scheduling.
SetMaxDelayableRequests(1);
std::unique_ptr<TestRequest> high(
NewRequest("http://host/high", net::HIGHEST));
std::unique_ptr<TestRequest> low(NewRequest("http://host/low", net::LOWEST));
std::unique_ptr<TestRequest> low2(
NewRequest("http://host/low2", net::LOWEST));
std::unique_ptr<TestRequest> request(
NewRequest("chrome-extension://req", net::LOWEST));
EXPECT_TRUE(low->started());
EXPECT_FALSE(low2->started());
EXPECT_TRUE(request->started());
}
TEST_F(ResourceSchedulerTest, SpdyProxySchedulesImmediately) {
base::test::ScopedFeatureList scoped_feature_list;
InitializeScheduler();
SetMaxDelayableRequests(1);
std::unique_ptr<TestRequest> high(
NewRequest("http://host/high", net::HIGHEST));
std::unique_ptr<TestRequest> low(NewRequest("http://host/low", net::LOWEST));
std::unique_ptr<TestRequest> request(
NewRequest("http://host/req", net::IDLE));
EXPECT_FALSE(request->started());
}
TEST_F(ResourceSchedulerTest, NewSpdyHostInDelayableRequests) {
base::test::ScopedFeatureList scoped_feature_list;
InitializeScheduler();
const int kDefaultMaxNumDelayableRequestsPerClient =
10; // Should match the .cc.
std::unique_ptr<TestRequest> low1_spdy(
NewRequest("http://spdyhost1:8080/low", net::LOWEST));
// Cancel a request after we learn the server supports SPDY.
std::vector<std::unique_ptr<TestRequest>> lows;
for (int i = 0; i < kDefaultMaxNumDelayableRequestsPerClient - 1; ++i) {
string url = "http://host" + base::NumberToString(i) + "/low";
lows.push_back(NewRequest(url.c_str(), net::LOWEST));
}
std::unique_ptr<TestRequest> low1(NewRequest("http://host/low", net::LOWEST));
EXPECT_FALSE(low1->started());
http_server_properties_.SetSupportsSpdy(
url::SchemeHostPort("http", "spdyhost1", 8080), true);
low1_spdy.reset();
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(low1->started());
low1.reset();
base::RunLoop().RunUntilIdle();
std::unique_ptr<TestRequest> low2_spdy(
NewRequest("http://spdyhost2:8080/low", net::IDLE));
// Reprioritize a request after we learn the server supports SPDY.
EXPECT_TRUE(low2_spdy->started());
http_server_properties_.SetSupportsSpdy(
url::SchemeHostPort("http", "spdyhost2", 8080), true);
ChangeRequestPriority(low2_spdy.get(), net::LOWEST);
base::RunLoop().RunUntilIdle();
std::unique_ptr<TestRequest> low2(NewRequest("http://host/low", net::LOWEST));
EXPECT_TRUE(low2->started());
}
// Similar to NewSpdyHostInDelayableRequests test above, but tests the behavior
// when |delay_requests_on_multiplexed_connections| is true.
TEST_F(ResourceSchedulerTest,
NewDelayableSpdyHostInDelayableRequestsSlowConnection) {
ConfigureDelayRequestsOnMultiplexedConnectionsFieldTrial();
network_quality_estimator_.SetAndNotifyObserversOfEffectiveConnectionType(
net::EFFECTIVE_CONNECTION_TYPE_2G);
InitializeScheduler();
// Maximum number of delayable requests allowed when effective connection type
// is 2G.
const int max_delayable_requests_per_client_ect_2g = 8;
std::unique_ptr<TestRequest> low1_spdy(
NewRequest("http://spdyhost1:8080/low", net::LOWEST));
EXPECT_TRUE(low1_spdy->started());
// Cancel a request after we learn the server supports SPDY.
std::vector<std::unique_ptr<TestRequest>> lows;
for (int i = 0; i < max_delayable_requests_per_client_ect_2g - 1; ++i) {
string url = "http://host" + base::NumberToString(i) + "/low";
lows.push_back(NewRequest(url.c_str(), net::LOWEST));
EXPECT_TRUE(lows.back()->started());
}
std::unique_ptr<TestRequest> low1(NewRequest("http://host/low", net::LOWEST));
EXPECT_FALSE(low1->started());
http_server_properties_.SetSupportsSpdy(
url::SchemeHostPort("http", "spdyhost1", 8080), true);
low1_spdy.reset();
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(low1->started());
low1.reset();
base::RunLoop().RunUntilIdle();
std::unique_ptr<TestRequest> low2_spdy(
NewRequest("http://spdyhost2:8080/low", net::IDLE));
// Reprioritize a request after we learn the server supports SPDY.
EXPECT_TRUE(low2_spdy->started());
http_server_properties_.SetSupportsSpdy(
url::SchemeHostPort("http", "spdyhost2", 8080), true);
ChangeRequestPriority(low2_spdy.get(), net::LOWEST);
base::RunLoop().RunUntilIdle();
std::unique_ptr<TestRequest> low2(NewRequest("http://host/low", net::LOWEST));
EXPECT_FALSE(low2->started());
// SPDY requests are not started either.
std::unique_ptr<TestRequest> low3_spdy(
NewRequest("http://spdyhost1:8080/low", net::LOWEST));
EXPECT_FALSE(low3_spdy->started());
}
// Async revalidations which are not started when the tab is closed must be
// started at some point, or they will hang around forever and prevent other
// async revalidations to the same URL from being issued.
TEST_F(ResourceSchedulerTest, RequestStartedAfterClientDeleted) {
SetMaxDelayableRequests(1);
scheduler_->OnClientCreated(kChildId2, kRouteId2,
&network_quality_estimator_);
std::unique_ptr<TestRequest> high(NewRequestWithChildAndRoute(
"http://host/high", net::HIGHEST, kChildId2, kRouteId2));
std::unique_ptr<TestRequest> lowest1(NewRequestWithChildAndRoute(
"http://host/lowest", net::LOWEST, kChildId2, kRouteId2));
std::unique_ptr<TestRequest> lowest2(NewRequestWithChildAndRoute(
"http://host/lowest", net::LOWEST, kChildId2, kRouteId2));
EXPECT_FALSE(lowest2->started());
scheduler_->OnClientDeleted(kChildId2, kRouteId2);
high.reset();
lowest1.reset();
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(lowest2->started());
}
// The ResourceScheduler::Client destructor calls
// LoadAnyStartablePendingRequests(), which may start some pending requests.
// This test is to verify that requests will be started at some point
// even if they were not started by the destructor.
TEST_F(ResourceSchedulerTest, RequestStartedAfterClientDeletedManyDelayable) {
scheduler_->OnClientCreated(kChildId2, kRouteId2,
&network_quality_estimator_);
std::unique_ptr<TestRequest> high(NewRequestWithChildAndRoute(
"http://host/high", net::HIGHEST, kChildId2, kRouteId2));
const int kDefaultMaxNumDelayableRequestsPerClient = 10;
std::vector<std::unique_ptr<TestRequest>> delayable_requests;
for (int i = 0; i < kDefaultMaxNumDelayableRequestsPerClient + 1; ++i) {
delayable_requests.push_back(NewRequestWithChildAndRoute(
"http://host/lowest", net::LOWEST, kChildId2, kRouteId2));
}
std::unique_ptr<TestRequest> lowest(NewRequestWithChildAndRoute(
"http://host/lowest", net::LOWEST, kChildId2, kRouteId2));
EXPECT_FALSE(lowest->started());
scheduler_->OnClientDeleted(kChildId2, kRouteId2);
high.reset();
delayable_requests.clear();
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(lowest->started());
}
// Tests that the maximum number of delayable requests is overridden when the
// experiment is enabled.
TEST_F(ResourceSchedulerTest, RequestLimitOverrideEnabled) {
RequestLimitOverrideConfigTestHelper(true);
}
// Tests that the maximum number of delayable requests is not overridden when
// the experiment is disabled.
TEST_F(ResourceSchedulerTest, RequestLimitOverrideDisabled) {
RequestLimitOverrideConfigTestHelper(false);
}
// Test that the limit is not overridden when the effective connection type is
// not equal to any of the values provided in the experiment configuration.
TEST_F(ResourceSchedulerTest, RequestLimitOverrideOutsideECTRange) {
base::test::ScopedFeatureList scoped_feature_list;
InitializeThrottleDelayableExperiment(true, 0.0);
InitializeScheduler();
for (net::EffectiveConnectionType ect :
{net::EFFECTIVE_CONNECTION_TYPE_UNKNOWN,
net::EFFECTIVE_CONNECTION_TYPE_OFFLINE,
net::EFFECTIVE_CONNECTION_TYPE_4G}) {
// Set the effective connection type to a value for which the experiment
// should not be run.
network_quality_estimator_.SetAndNotifyObserversOfEffectiveConnectionType(
ect);
// Throw in one high priority request to ensure that high priority requests
// do not depend on anything.
std::unique_ptr<TestRequest> high(
NewRequest("http://host/high", net::HIGHEST));
EXPECT_TRUE(high->started());
// Should be in sync with resource_scheduler.cc.
const int kDefaultMaxNumDelayableRequestsPerClient = 10;
std::vector<std::unique_ptr<TestRequest>> lows_singlehost;
// Queue up to the maximum limit. Use different host names to prevent the
// per host limit from kicking in.
for (int i = 0; i < kDefaultMaxNumDelayableRequestsPerClient; ++i) {
// Keep unique hostnames to prevent the per host limit from kicking in.
std::string url = "http://host" + base::NumberToString(i) + "/low";
lows_singlehost.push_back(NewRequest(url.c_str(), net::LOWEST));
EXPECT_TRUE(lows_singlehost[i]->started());
}
std::unique_ptr<TestRequest> last_singlehost(
NewRequest("http://host/last", net::LOWEST));
// Last should not start because the maximum requests that can be in-flight
// have already started.
EXPECT_FALSE(last_singlehost->started());
}
}
// Test that a change in network conditions midway during loading does not
// change the behavior of the resource scheduler.
TEST_F(ResourceSchedulerTest, RequestLimitOverrideFixedForPageLoad) {
base::test::ScopedFeatureList scoped_feature_list;
InitializeThrottleDelayableExperiment(true, 0.0);
// ECT value is in range for which the limit is overridden to 2.
network_quality_estimator_.SetAndNotifyObserversOfEffectiveConnectionType(
net::EFFECTIVE_CONNECTION_TYPE_SLOW_2G);
InitializeScheduler();
// Throw in one high priority request to ensure that high priority requests
// do not depend on anything.
std::unique_ptr<TestRequest> high(
NewRequest("http://host/high", net::HIGHEST));
EXPECT_TRUE(high->started());
// Should be based on the value set by
// |InitializeThrottleDelayableExperiment| for the given range.
const int kOverriddenNumRequests = 2;
std::vector<std::unique_ptr<TestRequest>> lows_singlehost;
// Queue up to the overridden limit.
for (int i = 0; i < kOverriddenNumRequests; ++i) {
// Keep unique hostnames to prevent the per host limit from kicking in.
std::string url = "http://host" + base::NumberToString(i) + "/low";
lows_singlehost.push_back(NewRequest(url.c_str(), net::LOWEST));
EXPECT_TRUE(lows_singlehost[i]->started());
}
std::unique_ptr<TestRequest> second_last_singlehost(
NewRequest("http://host/slast", net::LOWEST));
// This new request should not start because the limit has been reached.
EXPECT_FALSE(second_last_singlehost->started());
lows_singlehost.erase(lows_singlehost.begin());
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(second_last_singlehost->started());
// Change the ECT to go outside the experiment buckets and change the network
// type to 4G. This should affect the limit calculated at the beginning of
// the page load.
network_quality_estimator_.SetAndNotifyObserversOfEffectiveConnectionType(
net::EFFECTIVE_CONNECTION_TYPE_4G);
base::RunLoop().RunUntilIdle();
std::unique_ptr<TestRequest> last_singlehost(
NewRequest("http://host/last", net::LOWEST));
// Last should start because the limit should have changed.
EXPECT_TRUE(last_singlehost->started());
}
// Test that when the network quality changes such that the new limit is lower,
// the new delayable requests don't start until the number of requests in
// flight have gone below the new limit.
TEST_F(ResourceSchedulerTest, RequestLimitReducedAcrossPageLoads) {
base::test::ScopedFeatureList scoped_feature_list;
InitializeThrottleDelayableExperiment(true, 0.0);
// ECT value is in range for which the limit is overridden to 4.
network_quality_estimator_.SetAndNotifyObserversOfEffectiveConnectionType(
net::EFFECTIVE_CONNECTION_TYPE_3G);
InitializeScheduler();
// Throw in one high priority request to ensure that high priority requests
// do not depend on anything.
std::unique_ptr<TestRequest> high(
NewRequest("http://host/high", net::HIGHEST));
EXPECT_TRUE(high->started());
// The number of delayable requests allowed for the first page load.
const int kNumDelayableHigh = 4;
// The number of delayable requests allowed for the second page load.
const int kNumDelayableLow = 2;
std::vector<std::unique_ptr<TestRequest>> delayable_first_page;
// Queue up to the overridden limit.
for (int i = 0; i < kNumDelayableHigh; ++i) {
// Keep unique hostnames to prevent the per host limit from kicking in.
std::string url = "http://host" + base::NumberToString(i) + "/low1";
delayable_first_page.push_back(NewRequest(url.c_str(), net::LOWEST));
EXPECT_TRUE(delayable_first_page[i]->started());
}
// Change the network quality so that the ECT value is in range for which the
// limit is overridden to 2. The effective connection type is set to
// Slow-2G.
network_quality_estimator_.SetAndNotifyObserversOfEffectiveConnectionType(
net::EFFECTIVE_CONNECTION_TYPE_SLOW_2G);
// Ensure that high priority requests still start.
std::unique_ptr<TestRequest> high2(
NewRequest("http://host/high2", net::HIGHEST));
EXPECT_TRUE(high->started());
// Generate requests from second page. None of them should start because the
// new limit is |kNumDelayableLow| and there are already |kNumDelayableHigh|
// requests in flight.
std::vector<std::unique_ptr<TestRequest>> delayable_second_page;
for (int i = 0; i < kNumDelayableLow; ++i) {
// Keep unique hostnames to prevent the per host limit from kicking in.
std::string url = "http://host" + base::NumberToString(i) + "/low2";
delayable_second_page.push_back(NewRequest(url.c_str(), net::LOWEST));
EXPECT_FALSE(delayable_second_page[i]->started());
}
// Finish 2 requests from first page load.
for (int i = 0; i < kNumDelayableHigh - kNumDelayableLow; ++i) {
delayable_first_page.pop_back();
}
base::RunLoop().RunUntilIdle();
// Nothing should start because there are already |kNumDelayableLow| requests
// in flight.
for (int i = 0; i < kNumDelayableLow; ++i) {
EXPECT_FALSE(delayable_second_page[i]->started());
}
// Remove all requests from the first page.
delayable_first_page.clear();
base::RunLoop().RunUntilIdle();
// Check that the requests from page 2 have started, since now there are 2
// empty slots.
for (int i = 0; i < kNumDelayableLow; ++i) {
EXPECT_TRUE(delayable_second_page[i]->started());
}
// No new delayable request should start since there are already
// |kNumDelayableLow| requests in flight.
std::string url =
"http://host" + base::NumberToString(kNumDelayableLow) + "/low3";
delayable_second_page.push_back(NewRequest(url.c_str(), net::LOWEST));
EXPECT_FALSE(delayable_second_page.back()->started());
}
TEST_F(ResourceSchedulerTest, ThrottleDelayableDisabled) {
base::FieldTrialParamAssociator::GetInstance()->ClearAllParamsForTesting();
const char kTrialName[] = "TrialName";
const char kGroupName[] = "GroupName";
base::FieldTrial* field_trial =
base::FieldTrialList::CreateFieldTrial(kTrialName, kGroupName);
base::test::ScopedFeatureList scoped_feature_list;
std::unique_ptr<base::FeatureList> feature_list(
std::make_unique<base::FeatureList>());
feature_list->RegisterFieldTrialOverride(
"ThrottleDelayable", base::FeatureList::OVERRIDE_DISABLE_FEATURE,
field_trial);
scoped_feature_list.InitWithFeatureList(std::move(feature_list));
InitializeScheduler();
network_quality_estimator_.SetAndNotifyObserversOfEffectiveConnectionType(
net::EFFECTIVE_CONNECTION_TYPE_2G);
// Insert one non-delayable request. This should not affect the number of
// delayable requests started.
std::unique_ptr<TestRequest> medium(
NewRequest("http://host/medium", net::MEDIUM));
ASSERT_TRUE(medium->started());
// Start |kDefaultMaxNumDelayableRequestsPerClient| delayable requests and
// verify that they all started.
// When one high priority request is in flight, the number of low priority
// requests allowed in flight are |max_delayable_requests| -
// |non_delayable_weight| = 8 - 3 = 5.
std::vector<std::unique_ptr<TestRequest>> delayable_requests;
for (int i = 0; i < 5; ++i) {
delayable_requests.push_back(NewRequest(
base::StringPrintf("http://host%d/low", i).c_str(), net::LOWEST));
EXPECT_TRUE(delayable_requests.back()->started());
}
delayable_requests.push_back(
NewRequest("http://host/low-blocked", net::LOWEST));
EXPECT_FALSE(delayable_requests.back()->started());
}
// Test that the default limit is used for delayable requests when the
// experiment is enabled, but the current effective connection type is higher
// than the maximum effective connection type set in the experiment
// configuration.
TEST_F(ResourceSchedulerTest, NonDelayableThrottlesDelayableOutsideECT) {
base::test::ScopedFeatureList scoped_feature_list;
const double kNonDelayableWeight = 2.0;
const int kDefaultMaxNumDelayableRequestsPerClient =
10; // Should be in sync with cc.
// Initialize the experiment with |kNonDelayableWeight| as the weight of
// non-delayable requests.
InitializeThrottleDelayableExperiment(false, kNonDelayableWeight);
// Experiment should not run when the effective connection type is faster
// than 2G.
network_quality_estimator_.SetAndNotifyObserversOfEffectiveConnectionType(
net::EFFECTIVE_CONNECTION_TYPE_3G);
InitializeScheduler();
// Insert one non-delayable request. This should not affect the number of
// delayable requests started.
std::unique_ptr<TestRequest> medium(
NewRequest("http://host/medium", net::MEDIUM));
ASSERT_TRUE(medium->started());
// Start |kDefaultMaxNumDelayableRequestsPerClient| delayable requests and
// verify that they all started.
std::vector<std::unique_ptr<TestRequest>> delayable_requests;
for (int i = 0; i < kDefaultMaxNumDelayableRequestsPerClient; ++i) {
delayable_requests.push_back(NewRequest(
base::StringPrintf("http://host%d/low", i).c_str(), net::LOWEST));
EXPECT_TRUE(delayable_requests.back()->started());
}
}
// Test that delayable requests are throttled by the right amount as the number
// of non-delayable requests in-flight change.
TEST_F(ResourceSchedulerTest, NonDelayableThrottlesDelayableVaryNonDelayable) {
base::test::ScopedFeatureList scoped_feature_list;
const double kNonDelayableWeight = 2.0;
const int kDefaultMaxNumDelayableRequestsPerClient =
8; // Should be in sync with cc.
// Initialize the experiment with |kNonDelayableWeight| as the weight of
// non-delayable requests.
InitializeThrottleDelayableExperiment(false, kNonDelayableWeight);
network_quality_estimator_.SetAndNotifyObserversOfEffectiveConnectionType(
net::EFFECTIVE_CONNECTION_TYPE_SLOW_2G);
InitializeScheduler();
for (int num_non_delayable = 0; num_non_delayable < 10; ++num_non_delayable) {
base::RunLoop().RunUntilIdle();
// Start the non-delayable requests.
std::vector<std::unique_ptr<TestRequest>> non_delayable_requests;
for (int i = 0; i < num_non_delayable; ++i) {
non_delayable_requests.push_back(NewRequest(
base::StringPrintf("http://host%d/medium", i).c_str(), net::MEDIUM));
ASSERT_TRUE(non_delayable_requests.back()->started());
}
// Start |kDefaultMaxNumDelayableRequestsPerClient| - |num_non_delayable| *
// |kNonDelayableWeight| delayable requests. They should all start.
std::vector<std::unique_ptr<TestRequest>> delayable_requests;
for (int i = 0; i < kDefaultMaxNumDelayableRequestsPerClient -
num_non_delayable * kNonDelayableWeight;
++i) {
delayable_requests.push_back(NewRequest(
base::StringPrintf("http://host%d/low", i).c_str(), net::LOWEST));
EXPECT_TRUE(delayable_requests.back()->started());
}
// The next delayable request should not start.
std::unique_ptr<TestRequest> last_low(
NewRequest("http://lasthost/low", net::LOWEST));
EXPECT_FALSE(last_low->started());
}
}
// Test that each non-delayable request in-flight results in the reduction of
// one in the limit of delayable requests in-flight when the non-delayable
// request weight is 1.
TEST_F(ResourceSchedulerTest, NonDelayableThrottlesDelayableWeight1) {
NonDelayableThrottlesDelayableHelper(1.0);
}
// Test that each non-delayable request in-flight results in the reduction of
// three in the limit of delayable requests in-flight when the non-delayable
// request weight is 3.
TEST_F(ResourceSchedulerTest, NonDelayableThrottlesDelayableWeight3) {
NonDelayableThrottlesDelayableHelper(3.0);
}
// Test that UMA counts are recorded for the number of delayable requests
// in-flight when a non-delayable request starts.
TEST_F(ResourceSchedulerTest, NumDelayableAtStartOfNonDelayableUMA) {
std::unique_ptr<base::HistogramTester> histogram_tester(
new base::HistogramTester);
// Check that 0 is recorded when a non-delayable request starts and there are
// no delayable requests in-flight.
std::unique_ptr<TestRequest> high(
NewRequest("http://host/high", net::HIGHEST));
EXPECT_TRUE(high->started());
histogram_tester->ExpectUniqueSample(
"ResourceScheduler.NumDelayableRequestsInFlightAtStart.NonDelayable", 0,
1);
histogram_tester.reset(new base::HistogramTester);
// Check that nothing is recorded when delayable request is started in the
// presence of a non-delayable request.
std::unique_ptr<TestRequest> low1(
NewRequest("http://host/low1", net::LOWEST));
EXPECT_TRUE(low1->started());
histogram_tester->ExpectTotalCount(
"ResourceScheduler.NumDelayableRequestsInFlightAtStart.NonDelayable", 0);
// Check that nothing is recorded when a delayable request is started in the
// presence of another delayable request.
std::unique_ptr<TestRequest> low2(
NewRequest("http://host/low2", net::LOWEST));
histogram_tester->ExpectTotalCount(
"ResourceScheduler.NumDelayableRequestsInFlightAtStart.NonDelayable", 0);
// Check that UMA is recorded when a non-delayable startes in the presence of
// delayable requests and that the correct value is recorded.
std::unique_ptr<TestRequest> high2(
NewRequest("http://host/high2", net::HIGHEST));
histogram_tester->ExpectUniqueSample(
"ResourceScheduler.NumDelayableRequestsInFlightAtStart.NonDelayable", 2,
1);
}
TEST_F(ResourceSchedulerTest, SchedulerEnabled) {
SetMaxDelayableRequests(1);
std::unique_ptr<TestRequest> high(
NewRequest("http://host/high", net::HIGHEST));
std::unique_ptr<TestRequest> low(NewRequest("http://host/req", net::LOWEST));
std::unique_ptr<TestRequest> request(
NewRequest("http://host/req", net::LOWEST));
EXPECT_FALSE(request->started());
}
TEST_F(ResourceSchedulerTest, SchedulerDisabled) {
InitializeScheduler(false);
std::unique_ptr<TestRequest> high(
NewRequest("http://host/high", net::HIGHEST));
std::unique_ptr<TestRequest> low(NewRequest("http://host/req", net::LOWEST));
std::unique_ptr<TestRequest> request(
NewRequest("http://host/req", net::LOWEST));
// Normally |request| wouldn't start immediately due to the |high| priority
// request, but when the scheduler is disabled it starts immediately.
EXPECT_TRUE(request->started());
}
TEST_F(ResourceSchedulerTest, MultipleInstances_1) {
SetMaxDelayableRequests(1);
// In some circumstances there may exist multiple instances.
ResourceScheduler another_scheduler(false,
base::DefaultTickClock::GetInstance());
std::unique_ptr<TestRequest> high(
NewRequest("http://host/high", net::HIGHEST));
std::unique_ptr<TestRequest> low(NewRequest("http://host/req", net::LOWEST));
std::unique_ptr<TestRequest> request(
NewRequest("http://host/req", net::LOWEST));
// Though |another_scheduler| is disabled, this request should be throttled
// as it's handled by |scheduler_| which is active.
EXPECT_FALSE(request->started());
}
TEST_F(ResourceSchedulerTest, MultipleInstances_2) {
SetMaxDelayableRequests(1);
ResourceScheduler another_scheduler(true,
base::DefaultTickClock::GetInstance());
another_scheduler.OnClientCreated(kChildId, kRouteId,
&network_quality_estimator_);
std::unique_ptr<TestRequest> high(
NewRequest("http://host/high", net::HIGHEST));
std::unique_ptr<TestRequest> low(NewRequest("http://host/req", net::LOWEST));
std::unique_ptr<TestRequest> request(NewRequestWithChildAndRoute(
"http://host/req", net::LOWEST, kChildId, kRouteId));
EXPECT_FALSE(request->started());
{
another_scheduler.SetResourceSchedulerParamsManagerForTests(
FixedParamsManager(1));
std::unique_ptr<net::URLRequest> url_request(NewURLRequestWithChildAndRoute(
"http://host/another", net::LOWEST, kChildId, kRouteId));
auto scheduled_request = another_scheduler.ScheduleRequest(
kChildId, kRouteId, true, url_request.get());
auto another_request = std::make_unique<TestRequest>(
std::move(url_request), std::move(scheduled_request),
&another_scheduler);
another_request->Start();
// This should not be throttled as it's handled by |another_scheduler|.
EXPECT_TRUE(another_request->started());
}
another_scheduler.OnClientDeleted(kChildId, kRouteId);
}
// Verify that when |delay_requests_on_multiplexed_connections| is true, spdy
// hosts are not subject to kMaxNumDelayableRequestsPerHostPerClient limit, but
// are still subject to kDefaultMaxNumDelayableRequestsPerClient limit.
TEST_F(ResourceSchedulerTest,
MaxRequestsPerHostForSpdyWhenDelayableSlowConnections) {
ConfigureDelayRequestsOnMultiplexedConnectionsFieldTrial();
network_quality_estimator_.SetAndNotifyObserversOfEffectiveConnectionType(
net::EFFECTIVE_CONNECTION_TYPE_2G);
InitializeScheduler();
http_server_properties_.SetSupportsSpdy(
url::SchemeHostPort("https", "spdyhost", 443), true);
// Should be in sync with resource_scheduler.cc for effective connection type
// of 2G.
const size_t kDefaultMaxNumDelayableRequestsPerClient = 8;
ASSERT_LT(kMaxNumDelayableRequestsPerHostPerClient,
kDefaultMaxNumDelayableRequestsPerClient);
// Add more than kMaxNumDelayableRequestsPerHostPerClient low-priority
// requests. They should all be allowed.
std::vector<std::unique_ptr<TestRequest>> requests;
for (size_t i = 0; i < kMaxNumDelayableRequestsPerHostPerClient + 1; ++i) {
requests.push_back(NewRequest("https://spdyhost/low", net::LOWEST));
EXPECT_TRUE(requests[i]->started());
}
// Requests to SPDY servers should not be subject to
// kMaxNumDelayableRequestsPerHostPerClient limit. They should only be subject
// to kDefaultMaxNumDelayableRequestsPerClient limit.
for (size_t i = kMaxNumDelayableRequestsPerHostPerClient + 1;
i < kDefaultMaxNumDelayableRequestsPerClient + 1; i++) {
EXPECT_EQ(i, requests.size());
requests.push_back(NewRequest("https://spdyhost/low", net::LOWEST));
EXPECT_EQ(i < kDefaultMaxNumDelayableRequestsPerClient,
requests[i]->started());
}
}
// Verify that when |delay_requests_on_multiplexed_connections| is false, spdy
// hosts are not subject to kMaxNumDelayableRequestsPerHostPerClient or
// kDefaultMaxNumDelayableRequestsPerClient limits.
TEST_F(ResourceSchedulerTest,
MaxRequestsPerHostForSpdyWhenDelayableFastConnections) {
ConfigureDelayRequestsOnMultiplexedConnectionsFieldTrial();
network_quality_estimator_.SetAndNotifyObserversOfEffectiveConnectionType(
net::EFFECTIVE_CONNECTION_TYPE_4G);
InitializeScheduler();
http_server_properties_.SetSupportsSpdy(
url::SchemeHostPort("https", "spdyhost", 443), true);
// Should be in sync with resource_scheduler.cc for effective connection type
// of 4G.
const size_t kDefaultMaxNumDelayableRequestsPerClient = 10;
ASSERT_LT(kMaxNumDelayableRequestsPerHostPerClient,
kDefaultMaxNumDelayableRequestsPerClient);
// Add more than kDefaultMaxNumDelayableRequestsPerClient low-priority
// requests. They should all be allowed.
std::vector<std::unique_ptr<TestRequest>> requests;
for (size_t i = 0; i < kDefaultMaxNumDelayableRequestsPerClient + 1; ++i) {
requests.push_back(NewRequest("https://spdyhost/low", net::LOWEST));
EXPECT_TRUE(requests[i]->started());
}
}
// Verify that when |delay_requests_on_multiplexed_connections| is true,
// non-spdy hosts are still subject to kMaxNumDelayableRequestsPerHostPerClient
// limit.
TEST_F(ResourceSchedulerTest,
MaxRequestsPerHostForNonSpdyWhenDelayableSlowConnections) {
ConfigureDelayRequestsOnMultiplexedConnectionsFieldTrial();
network_quality_estimator_.SetAndNotifyObserversOfEffectiveConnectionType(
net::EFFECTIVE_CONNECTION_TYPE_2G);
InitializeScheduler();
// Add more than kMaxNumDelayableRequestsPerHostPerClient delayable requests.
// They should not all be allowed.
std::vector<std::unique_ptr<TestRequest>> requests;
for (size_t i = 0; i < kMaxNumDelayableRequestsPerHostPerClient + 1; ++i)
requests.push_back(NewRequest("https://non_spdyhost/low", net::LOWEST));
// kMaxNumDelayableRequestsPerHostPerClient should apply for non-spdy host.
for (size_t i = 0; i < requests.size(); ++i) {
EXPECT_EQ(i < kMaxNumDelayableRequestsPerHostPerClient,
requests[i]->started());
}
}
// Verify that when |delay_requests_on_multiplexed_connections| is true,
// non-spdy requests are still subject to
// kDefaultMaxNumDelayableRequestsPerClient limit.
TEST_F(ResourceSchedulerTest,
DelayableRequestLimitSpdyDelayableSlowConnections) {
ConfigureDelayRequestsOnMultiplexedConnectionsFieldTrial();
network_quality_estimator_.SetAndNotifyObserversOfEffectiveConnectionType(
net::EFFECTIVE_CONNECTION_TYPE_2G);
InitializeScheduler();
// Throw in one high priority request to ensure that high priority requests
// do not depend on anything.
std::unique_ptr<TestRequest> high(
NewRequest("http://host/high", net::HIGHEST));
EXPECT_TRUE(high->started());
// Should be in sync with resource_scheduler.cc for effective connection type
// (ECT) 2G. For ECT of 2G, number of low priority requests allowed are:
// 8 - 3 * count of high priority requests in flight. That expression computes
// to 8 - 3 * 1 = 5.
const int max_low_priority_requests_allowed = 5;
std::vector<std::unique_ptr<TestRequest>> lows_singlehost;
// Queue up to the maximum limit. Use different host names to prevent the
// per host limit from kicking in.
for (int i = 0; i < max_low_priority_requests_allowed; ++i) {
// Keep unique hostnames to prevent the per host limit from kicking in.
std::string url = "http://host" + base::NumberToString(i) + "/low";
lows_singlehost.push_back(NewRequest(url.c_str(), net::LOWEST));
EXPECT_TRUE(lows_singlehost[i]->started()) << i;
}
std::unique_ptr<TestRequest> last_singlehost(
NewRequest("http://host/last", net::LOWEST));
// Last should not start because the maximum requests that can be in-flight
// have already started.
EXPECT_FALSE(last_singlehost->started());
}
// Verify that when |max_queuing_time| is set, requests queued for too long
// duration are dispatched to the network.
TEST_F(ResourceSchedulerTest, MaxQueuingDelaySet) {
base::HistogramTester histogram_tester;
base::TimeDelta max_queuing_time = base::TimeDelta::FromSeconds(15);
InitializeMaxQueuingDelayExperiment(max_queuing_time);
network_quality_estimator_.SetAndNotifyObserversOfEffectiveConnectionType(
net::EFFECTIVE_CONNECTION_TYPE_SLOW_2G);
InitializeScheduler();
// Throw in one high priority request to ensure that high priority requests
// do not depend on anything.
std::unique_ptr<TestRequest> high(
NewRequest("http://host/high", net::HIGHEST));
EXPECT_TRUE(high->started());
// Should be in sync with resource_scheduler.cc for effective connection type
// (ECT) 2G. For ECT of 2G, number of low priority requests allowed are:
// 8 - 3 * count of high priority requests in flight. That expression computes
// to 8 - 3 * 1 = 5.
const int max_low_priority_requests_allowed = 5;
std::vector<std::unique_ptr<TestRequest>> lows_singlehost;
// Queue up to the maximum limit. Use different host names to prevent the
// per host limit from kicking in.
for (int i = 0; i < max_low_priority_requests_allowed + 10; ++i) {
// Keep unique hostnames to prevent the per host limit from kicking in.
std::string url = "http://host" + base::NumberToString(i) + "/low";
lows_singlehost.push_back(NewRequest(url.c_str(), net::LOWEST));
EXPECT_EQ(i < max_low_priority_requests_allowed,
lows_singlehost[i]->started());
}
// Advance the clock by more than |max_queuing_time|.
tick_clock_.SetNowTicks(base::DefaultTickClock::GetInstance()->NowTicks() +
max_queuing_time + base::TimeDelta::FromSeconds(1));
// Since the requests have been queued for too long, they should now be
// dispatched. Trigger the calculation of queuing time by Triggering the
// finish of a single request.
lows_singlehost[0].reset();
base::RunLoop().RunUntilIdle();
for (int i = 1; i < max_low_priority_requests_allowed + 10; ++i) {
EXPECT_TRUE(lows_singlehost[i]->started());
}
histogram_tester.ExpectUniqueSample(
"ResourceScheduler.DelayableRequests."
"WaitTimeToAvoidContentionWithNonDelayableRequest",
0, 1);
// Delete the requests. This should trigger the end of the requests which in
// turn would trigger recording of the metrics.
for (int i = 1; i < max_low_priority_requests_allowed + 10; ++i)
lows_singlehost[i].reset();
// No non-delayable request started after the start of the delayable request.
// Metric should be recorded as 0 milliseconds.
histogram_tester.ExpectUniqueSample(
"ResourceScheduler.DelayableRequests."
"WaitTimeToAvoidContentionWithNonDelayableRequest",
0, max_low_priority_requests_allowed + 10);
}
// Verify that when |max_queuing_time| is not set, requests queued for too long
// duration are not dispatched to the network.
TEST_F(ResourceSchedulerTest, MaxQueuingDelayNotSet) {
base::TimeDelta max_queuing_time = base::TimeDelta::FromSeconds(15);
network_quality_estimator_.SetAndNotifyObserversOfEffectiveConnectionType(
net::EFFECTIVE_CONNECTION_TYPE_SLOW_2G);
InitializeScheduler();
// Throw in one high priority request to ensure that high priority requests
// do not depend on anything.
std::unique_ptr<TestRequest> high(
NewRequest("http://host/high", net::HIGHEST));
EXPECT_TRUE(high->started());
// Should be in sync with resource_scheduler.cc for effective connection type
// (ECT) 2G. For ECT of 2G, number of low priority requests allowed are:
// 8 - 3 * count of high priority requests in flight. That expression computes
// to 8 - 3 * 1 = 5.
const int max_low_priority_requests_allowed = 5;
std::vector<std::unique_ptr<TestRequest>> lows_singlehost;
// Queue up to the maximum limit. Use different host names to prevent the
// per host limit from kicking in.
for (int i = 0; i < max_low_priority_requests_allowed + 10; ++i) {
// Keep unique hostnames to prevent the per host limit from kicking in.
std::string url = "http://host" + base::NumberToString(i) + "/low";
lows_singlehost.push_back(NewRequest(url.c_str(), net::LOWEST));
EXPECT_EQ(i < max_low_priority_requests_allowed,
lows_singlehost[i]->started());
}
// Advance the clock by more than |max_queuing_time|.
tick_clock_.SetNowTicks(base::DefaultTickClock::GetInstance()->NowTicks() +
max_queuing_time + base::TimeDelta::FromSeconds(1));
// Triggering the finish of a single request should not trigger dispatch of
// requests that have been queued for too long.
lows_singlehost[0].reset();
base::RunLoop().RunUntilIdle();
// Starting at i=1 since the request at index 0 has been deleted.
for (int i = 1; i < max_low_priority_requests_allowed + 10; ++i) {
EXPECT_EQ(i < max_low_priority_requests_allowed + 1,
lows_singlehost[i]->started());
}
}
// Verify that when the timer for dispatching long queued requests is fired,
// then the long queued requests are dispatched to the network.
TEST_F(ResourceSchedulerTest, MaxQueuingDelayTimerFires) {
base::TimeDelta max_queuing_time = base::TimeDelta::FromSeconds(15);
InitializeMaxQueuingDelayExperiment(max_queuing_time);
network_quality_estimator_.SetAndNotifyObserversOfEffectiveConnectionType(
net::EFFECTIVE_CONNECTION_TYPE_SLOW_2G);
InitializeScheduler();
// Throw in one high priority request to ensure that high priority requests
// do not depend on anything.
std::unique_ptr<TestRequest> high(
NewRequest("http://host/high", net::HIGHEST));
EXPECT_TRUE(high->started());
// Should be in sync with resource_scheduler.cc for effective connection type
// (ECT) 2G. For ECT of 2G, number of low priority requests allowed are:
// 8 - 3 * count of high priority requests in flight. That expression computes
// to 8 - 3 * 1 = 5.
const int max_low_priority_requests_allowed = 5;
std::vector<std::unique_ptr<TestRequest>> lows_singlehost;
// Queue up to the maximum limit. Use different host names to prevent the
// per host limit from kicking in.
for (int i = 0; i < max_low_priority_requests_allowed + 10; ++i) {
// Keep unique hostnames to prevent the per host limit from kicking in.
std::string url = "http://host" + base::NumberToString(i) + "/low";
lows_singlehost.push_back(NewRequest(url.c_str(), net::LOWEST));
EXPECT_EQ(i < max_low_priority_requests_allowed,
lows_singlehost[i]->started());
}
// Advance the clock by more than |max_queuing_time|.
tick_clock_.SetNowTicks(base::DefaultTickClock::GetInstance()->NowTicks() +
max_queuing_time + base::TimeDelta::FromSeconds(1));
// Since the requests have been queued for too long, they should now be
// dispatched. Trigger the calculation of queuing time by calling
// DispatchLongQueuedRequestsForTesting().
scheduler()->DispatchLongQueuedRequestsForTesting();
base::RunLoop().RunUntilIdle();
for (int i = 0; i < max_low_priority_requests_allowed + 10; ++i) {
EXPECT_TRUE(lows_singlehost[i]->started());
}
}
// Verify that when the timer for dispatching long queued requests is not fired,
// then the long queued requests are not dispatched to the network.
TEST_F(ResourceSchedulerTest, MaxQueuingDelayTimerNotFired) {
base::TimeDelta max_queuing_time = base::TimeDelta::FromSeconds(15);
InitializeMaxQueuingDelayExperiment(max_queuing_time);
network_quality_estimator_.SetAndNotifyObserversOfEffectiveConnectionType(
net::EFFECTIVE_CONNECTION_TYPE_SLOW_2G);
InitializeScheduler();
// Throw in one high priority request to ensure that high priority requests
// do not depend on anything.
std::unique_ptr<TestRequest> high(
NewRequest("http://host/high", net::HIGHEST));
EXPECT_TRUE(high->started());
// Should be in sync with resource_scheduler.cc for effective connection type
// (ECT) 2G. For ECT of 2G, number of low priority requests allowed are:
// 8 - 3 * count of high priority requests in flight. That expression computes
// to 8 - 3 * 1 = 5.
const int max_low_priority_requests_allowed = 5;
std::vector<std::unique_ptr<TestRequest>> lows_singlehost;
// Queue up to the maximum limit. Use different host names to prevent the
// per host limit from kicking in.
for (int i = 0; i < max_low_priority_requests_allowed + 10; ++i) {
// Keep unique hostnames to prevent the per host limit from kicking in.
std::string url = "http://host" + base::NumberToString(i) + "/low";
lows_singlehost.push_back(NewRequest(url.c_str(), net::LOWEST));
EXPECT_EQ(i < max_low_priority_requests_allowed,
lows_singlehost[i]->started());
}
// Advance the clock by more than |max_queuing_time|.
tick_clock_.SetNowTicks(base::DefaultTickClock::GetInstance()->NowTicks() +
max_queuing_time + base::TimeDelta::FromSeconds(1));
// Since the requests have been queued for too long, they are now eligible for
// disptaching. However, since the timer is not fired, the requests would not
// be dispatched.
base::RunLoop().RunUntilIdle();
for (int i = 0; i < max_low_priority_requests_allowed + 10; ++i) {
EXPECT_EQ(i < max_low_priority_requests_allowed,
lows_singlehost[i]->started());
}
}
// Verify that the timer to dispatch long queued requests starts only when there
// are requests in-flight.
TEST_F(ResourceSchedulerTest, MaxQueuingDelayTimerRunsOnRequestSchedule) {
base::TimeDelta max_queuing_time = base::TimeDelta::FromSeconds(15);
InitializeMaxQueuingDelayExperiment(max_queuing_time);
network_quality_estimator_.SetAndNotifyObserversOfEffectiveConnectionType(
net::EFFECTIVE_CONNECTION_TYPE_SLOW_2G);
// Should be in sync with resource_scheduler.cc for effective connection type
// (ECT) 2G. For ECT of 2G, number of low priority requests allowed are:
// 8 - 3 * count of high priority requests in flight. That expression computes
// to 8 - 3 * 1 = 5.
const int max_low_priority_requests_allowed = 5;
std::vector<std::unique_ptr<TestRequest>> lows_singlehost;
InitializeScheduler();
EXPECT_FALSE(scheduler()->IsLongQueuedRequestsDispatchTimerRunning());
// Throw in one high priority request to ensure that high priority requests
// do not depend on anything.
std::unique_ptr<TestRequest> high(
NewRequest("http://host/high", net::HIGHEST));
EXPECT_TRUE(high->started());
for (int i = 0; i < max_low_priority_requests_allowed + 10; ++i) {
// Keep unique hostnames to prevent the per host limit from kicking in.
std::string url = "http://host" + base::NumberToString(i) + "/low";
lows_singlehost.push_back(NewRequest(url.c_str(), net::LOWEST));
EXPECT_EQ(i < max_low_priority_requests_allowed,
lows_singlehost[i]->started());
}
// Timer should be running since there are pending requests.
EXPECT_TRUE(scheduler()->IsLongQueuedRequestsDispatchTimerRunning());
// Simulate firing of timer. The timer should restart since there is at least
// one request in flight.
scheduler()->DispatchLongQueuedRequestsForTesting();
EXPECT_TRUE(scheduler()->IsLongQueuedRequestsDispatchTimerRunning());
// Simulate firing of timer. The timer should not restart since there is no
// request in flight.
high.reset();
for (auto& request : lows_singlehost) {
request.reset();
}
scheduler()->DispatchLongQueuedRequestsForTesting();
EXPECT_FALSE(scheduler()->IsLongQueuedRequestsDispatchTimerRunning());
// Start a new set of requests, and verify timer still works correctly.
std::unique_ptr<TestRequest> high2(
NewRequest("http://host/high", net::HIGHEST));
EXPECT_TRUE(high2->started());
// Timer not started because there is no pending requests.
EXPECT_FALSE(scheduler()->IsLongQueuedRequestsDispatchTimerRunning());
// Start some requests which end up pending.
for (int i = 0; i < max_low_priority_requests_allowed + 10; ++i) {
// Keep unique hostnames to prevent the per host limit from kicking in.
std::string url = "http://host" + base::NumberToString(i) + "/low";
lows_singlehost.push_back(NewRequest(url.c_str(), net::LOWEST));
}
EXPECT_TRUE(scheduler()->IsLongQueuedRequestsDispatchTimerRunning());
}
// Starts a delayable request followed by a non-delayable request. The delayable
// request finishes after the start of the non-delayable request. Verifies that
// the histogram that records the time difference between the start of delayable
// requests and the start of non-delayable requests is recorded properly.
TEST_F(ResourceSchedulerTest, NonDelayableRequestArrivesAfterDelayableStarts) {
base::HistogramTester histogram_tester;
base::TimeDelta max_queuing_time = base::TimeDelta::FromSeconds(15);
InitializeMaxQueuingDelayExperiment(max_queuing_time);
InitializeScheduler();
// Throw in one low priority request. When the request finishes histograms
// should be recorded.
std::unique_ptr<TestRequest> low(NewRequest("http://host/low", net::LOWEST));
EXPECT_TRUE(low->started());
const base::TimeDelta delay = base::TimeDelta::FromSeconds(5);
tick_clock_.SetNowTicks(base::TimeTicks::Now() + delay);
// Start a high priority request before |low| finishes.
std::unique_ptr<TestRequest> high(
NewRequest("http://host/high", net::HIGHEST));
EXPECT_TRUE(high->started());
histogram_tester.ExpectTotalCount(
"ResourceScheduler.DelayableRequests."
"WaitTimeToAvoidContentionWithNonDelayableRequest",
0);
// When the delayable request finishes, metrics should be recorded.
low.reset();
ExpectSampleIsAtLeastSpecifiedValue(
histogram_tester,
"ResourceScheduler.DelayableRequests."
"WaitTimeToAvoidContentionWithNonDelayableRequest",
delay.InMilliseconds());
}
// Starts and ends non-delayable requests to verify that the duration between
// non-delayable requests is recorded correctly.
TEST_F(ResourceSchedulerTest, NonDelayableToNonDelayableMetrics) {
base::HistogramTester histogram_tester_1;
base::TimeDelta max_queuing_time = base::TimeDelta::FromSeconds(15);
InitializeMaxQueuingDelayExperiment(max_queuing_time);
InitializeScheduler();
// Throw in one low priority request. When the request finishes histograms
// should be recorded.
std::unique_ptr<TestRequest> high_1(
NewRequest("http://host/high_1", net::HIGHEST));
EXPECT_TRUE(high_1->started());
const base::TimeDelta high1_start_to_high2_start =
base::TimeDelta::FromSeconds(5);
tick_clock_.SetNowTicks(base::TimeTicks::Now() + high1_start_to_high2_start);
// Start a high priority request before |high_1| finishes.
std::unique_ptr<TestRequest> high_2(
NewRequest("http://host/high_2", net::HIGHEST));
EXPECT_TRUE(high_2->started());
ExpectSampleIsAtLeastSpecifiedValue(
histogram_tester_1,
"ResourceScheduler.NonDelayableLastStartToNonDelayableStart",
high1_start_to_high2_start.InMilliseconds());
ExpectSampleIsAtLeastSpecifiedValue(
histogram_tester_1,
"ResourceScheduler.NonDelayableLastStartToNonDelayableStart."
"NonDelayableInFlight",
high1_start_to_high2_start.InMilliseconds());
ExpectSampleIsAtLeastSpecifiedValue(
histogram_tester_1,
"ResourceScheduler.NonDelayableLastStartOrEndToNonDelayableStart",
high1_start_to_high2_start.InMilliseconds());
// No non-delayable request has ended yet.
histogram_tester_1.ExpectTotalCount(
"ResourceScheduler.NonDelayableLastEndToNonDelayableStart", 0);
const base::TimeDelta high2_start_to_high2_end =
base::TimeDelta::FromSeconds(7);
tick_clock_.Advance(high2_start_to_high2_end);
high_1.reset();
high_2.reset();
base::HistogramTester histogram_tester_2;
const base::TimeDelta high2_end_to_high3_start =
base::TimeDelta::FromSeconds(2);
tick_clock_.Advance(high2_end_to_high3_start);
// Start a high priority request after |high_1| and |high_2| finishes.
std::unique_ptr<TestRequest> high_3(
NewRequest("http://host/high_3", net::HIGHEST));
EXPECT_TRUE(high_3->started());
ExpectSampleIsAtLeastSpecifiedValue(
histogram_tester_2,
"ResourceScheduler.NonDelayableLastStartToNonDelayableStart",
(high2_start_to_high2_end + high2_end_to_high3_start).InMilliseconds());
ExpectSampleIsAtLeastSpecifiedValue(
histogram_tester_2,
"ResourceScheduler.NonDelayableLastEndToNonDelayableStart",
high2_end_to_high3_start.InMilliseconds());
ExpectSampleIsAtLeastSpecifiedValue(
histogram_tester_2,
"ResourceScheduler.NonDelayableLastEndToNonDelayableStart."
"NonDelayableNotInFlight",
high2_end_to_high3_start.InMilliseconds());
ExpectSampleIsAtLeastSpecifiedValue(
histogram_tester_2,
"ResourceScheduler.NonDelayableLastStartOrEndToNonDelayableStart",
high2_end_to_high3_start.InMilliseconds());
}
} // unnamed namespace
} // namespace network
| [
"[email protected]"
] | |
cb9363a833ce7da7f813364aab847ea7e7bd3135 | b44250e01cf3528f79e4b0969cf598bee6341840 | /src/include/cutlass-ori/transform/threadblock/regular_tile_iterator_tensor_op.h | c35f131437f6c389fd3d73402a1f38822b01ea64 | [] | no_license | xzgz/cuda-study | c821322ba3101883766fe8d256ba8137ecdf609f | 37a88d80be6a3bf121cd4d769e6f1dc37c3ae038 | refs/heads/master | 2023-08-05T22:16:54.191302 | 2023-07-24T10:04:48 | 2023-07-24T10:04:48 | 211,104,935 | 0 | 0 | null | 2023-05-03T10:27:26 | 2019-09-26T14:09:26 | C++ | UTF-8 | C++ | false | false | 36,003 | h | /***************************************************************************************************
* Copyright (c) 2017-2021, NVIDIA CORPORATION. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the NVIDIA CORPORATION 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 NVIDIA CORPORATION 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 TOR (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
**************************************************************************************************/
/*! \file
\brief Templates implementing storing of tiles from pitch-linear rank=2 tensors.
*/
#pragma once
#include "cutlass/transform/threadblock/regular_tile_iterator.h"
#include "cutlass/transform/threadblock/regular_tile_access_iterator_tensor_op.h"
////////////////////////////////////////////////////////////////////////////////
namespace cutlass {
namespace transform {
namespace threadblock {
////////////////////////////////////////////////////////////////////////////////
/// Tile iterator specialized for congruous arrangements for TensorOps
///
///
/// Satisfies: ForwardTileIteratorConcept |
/// ReadableContiguousTileIteratorConcept |
/// WriteableContiguousTileIteratorConcept
///
template <typename Shape_, typename Element_, int AdvanceRank,
typename ThreadMap_, int Alignment>
class RegularTileIterator<
Shape_, Element_,
layout::TensorOpMultiplicandCongruous<sizeof_bits<Element_>::value,
int(128 / sizeof(Element_))>,
AdvanceRank, ThreadMap_, Alignment> {
public:
static_assert(AdvanceRank == 0 || AdvanceRank == 1,
"Specialization for pitch-linear iterator may along advance along the "
"contiguous(rank=0) or strided(rank=1) dimension.");
using Shape = Shape_;
using Element = Element_;
using Layout =
layout::TensorOpMultiplicandCongruous<sizeof_bits<Element_>::value,
int(128 / sizeof(Element))>;
static int const kAdvanceRank = AdvanceRank;
static int const kAlignment = Alignment;
using Index = typename Layout::Index;
using LongIndex = typename Layout::LongIndex;
using TensorRef = TensorRef<Element, Layout>;
using TensorCoord = typename Layout::TensorCoord;
using ThreadMap = ThreadMap_;
/// Internal details made public to facilitate introspection
struct Detail {
/// This iterator is specialized for an access size that is 128 bits in length.
static int const kAccessSizeInBits = 128;
static_assert(
sizeof_bits<Element_>::value * ThreadMap::kElementsPerAccess == kAccessSizeInBits,
"This iterator requires a policy whose access size is 128bs");
};
private:
/// Element type per access
using AccessType = Array<Element, Layout::kElementsPerAccess>;
public:
/// Fragment object to be loaded or stored
using Fragment = Array<Element, ThreadMap::Iterations::kCount * Layout::kElementsPerAccess>;
/// Underlying iterator to compute the addresses
using TileAccessIterator = RegularTileAccessIterator<Shape, Element, Layout,
kAdvanceRank, ThreadMap>;
private:
//
// Data members
//
/// Data member to the tile access iterator
TileAccessIterator address_iterator_;
public:
/// Construct a TileIterator with zero threadblock offset
CUTLASS_HOST_DEVICE
RegularTileIterator(TensorRef ref, ///< Pointer to start of tensor
int thread_id ///< ID of each participating thread
)
: address_iterator_(ref, thread_id) {}
/// Adds a pointer offset in units of Element
CUTLASS_HOST_DEVICE
void add_pointer_offset(LongIndex pointer_offset) {
address_iterator_.add_pointer_offset(pointer_offset);
}
/// Advances to the next tile in memory.
CUTLASS_HOST_DEVICE
RegularTileIterator &operator++() {
address_iterator_.add_tile_offset({0, 1});
return *this;
}
/// Advances to the next tile in memory.
CUTLASS_HOST_DEVICE
RegularTileIterator operator++(int) {
RegularTileIterator prev(*this);
this->operator++();
return prev;
}
/// Adds a tile offset
CUTLASS_DEVICE
void add_tile_offset(TensorCoord const &coord) {
address_iterator_.add_tile_offset(coord);
}
/// Loads a fragment from memory
CUTLASS_DEVICE
void load_with_pointer_offset(Fragment &frag, Index pointer_offset) {
load_with_byte_offset(frag, pointer_offset * sizeof_bits<Element>::value / 8);
}
/// Loads a fragment from memory
CUTLASS_DEVICE
void load_with_byte_offset(Fragment &frag, Index byte_offset) {
address_iterator_.set_iteration_index(0);
AccessType *frag_ptr = reinterpret_cast<AccessType *>(&frag);
CUTLASS_PRAGMA_UNROLL
for (int s = 0; s < ThreadMap::Iterations::kStrided; ++s) {
CUTLASS_PRAGMA_UNROLL
for (int c = 0; c < ThreadMap::Iterations::kContiguous; ++c) {
int access_idx = c + s * ThreadMap::Iterations::kContiguous;
char const *byte_ptr = reinterpret_cast<char const *>(address_iterator_.get()) + byte_offset;
AccessType const *access_ptr = reinterpret_cast<AccessType const *>(byte_ptr);
frag_ptr[access_idx] = *access_ptr;
++address_iterator_;
}
}
}
/// Loads a fragment from memory
CUTLASS_DEVICE
void load(Fragment &frag) {
load_with_pointer_offset(frag, 0);
}
/// Store a fragment to memory
CUTLASS_DEVICE
void store_with_pointer_offset(Fragment const &frag, Index pointer_offset) {
store_with_byte_offset(frag, pointer_offset * sizeof_bits<Element>::value / 8);
}
CUTLASS_DEVICE
void store_with_byte_offset(Fragment const &frag, Index byte_offset) {
address_iterator_.set_iteration_index(0);
AccessType const *frag_ptr = reinterpret_cast<AccessType const *>(&frag);
CUTLASS_PRAGMA_UNROLL
for (int s = 0; s < ThreadMap::Iterations::kStrided; ++s) {
CUTLASS_PRAGMA_UNROLL
for (int c = 0; c < ThreadMap::Iterations::kContiguous; ++c) {
int access_idx = c + s * ThreadMap::Iterations::kContiguous;
char *byte_ptr = reinterpret_cast<char *>(address_iterator_.get()) + byte_offset;
AccessType *access_ptr = reinterpret_cast<AccessType *>(byte_ptr);
*access_ptr = frag_ptr[access_idx];
++address_iterator_;
}
}
}
/// Store a fragment to memory
CUTLASS_DEVICE
void store(Fragment const &frag) {
store_with_byte_offset(frag, 0);
}
};
////////////////////////////////////////////////////////////////////////////////
/// Tile Iterator specialized for column-major congruous TensorOp formats.
///
///
/// Satisfies: ForwardTileIteratorConcept |
/// ReadableContiguousTileIteratorConcept |
/// WriteableContiguousTileIteratorConcept
///
template <typename Shape_, typename Element_, int AdvanceRank,
typename ThreadMap_, int Alignment>
class RegularTileIterator<
Shape_, Element_,
layout::ColumnMajorTensorOpMultiplicandCongruous<
sizeof_bits<Element_>::value, int(128 / sizeof(Element_))>,
AdvanceRank, ThreadMap_, Alignment> {
public:
static_assert(AdvanceRank == 0 || AdvanceRank == 1,
"Specialization for column-major iterator may along advance along the "
"columns(rank=0) or rows(rank=1) dimension.");
using Shape = Shape_;
using Element = Element_;
using Layout = layout::ColumnMajorTensorOpMultiplicandCongruous<
sizeof_bits<Element_>::value, int(128 / sizeof(Element))>;
static int const kAdvanceRank = AdvanceRank;
static int const kAlignment = Alignment;
using Index = typename Layout::Index;
using LongIndex = typename Layout::LongIndex;
using TensorRef = TensorRef<Element, Layout>;
using TensorCoord = typename Layout::TensorCoord;
using ThreadMap = ThreadMap_;
/// Underlying iterator type
using UnderlyingIterator = RegularTileIterator<
layout::PitchLinearShape<Shape::kRow, Shape::kColumn>, Element,
layout::TensorOpMultiplicandCongruous<sizeof_bits<Element_>::value,
int(128 / sizeof(Element))>,
(kAdvanceRank == 0 ? 0 : 1), ThreadMap_>;
public:
/// Fragment object to be loaded or stored
using Fragment = Array<Element, UnderlyingIterator::Fragment::kElements>;
private:
/// Underlying iterator
UnderlyingIterator iterator_;
public:
/// Construct a TileIterator with zero threadblock offset
CUTLASS_HOST_DEVICE
RegularTileIterator(
TensorRef ref, ///< Pointer to start of tensor
int thread_id ///< ID of each participating thread
): iterator_({ref.data(), ref.stride()}, thread_id) {
}
/// Adds a pointer offset in units of Element
CUTLASS_HOST_DEVICE
void add_pointer_offset(LongIndex pointer_offset) {
iterator_.add_pointer_offset(pointer_offset);
}
/// Adds a tile offset
CUTLASS_DEVICE
void add_tile_offset(TensorCoord const &coord) {
iterator_.add_tile_offset({coord.row(), coord.column()});
}
/// Advances to the next tile in memory.
CUTLASS_HOST_DEVICE
RegularTileIterator &operator++() {
++iterator_;
return *this;
}
/// Advances to the next tile in memory.
CUTLASS_HOST_DEVICE
RegularTileIterator operator++(int) {
RegularTileIterator prev(*this);
++iterator_;
return prev;
}
/// Loads a fragment from memory
CUTLASS_DEVICE
void load_with_pointer_offset(Fragment &frag, Index pointer_offset) {
iterator_.load_with_pointer_offset(frag, pointer_offset);
}
/// Loads a fragment from memory
CUTLASS_DEVICE
void load(Fragment &frag) {
load_with_pointer_offset(frag, 0);
}
/// Store a fragment to memory
CUTLASS_DEVICE
void store_with_pointer_offset(
Fragment const &frag,
Index pointer_offset) {
iterator_.store_with_pointer_offset(frag, pointer_offset);
}
/// Store a fragment to memory
CUTLASS_DEVICE
void store(Fragment const &frag) {
store_with_pointer_offset(frag, 0);
}
};
////////////////////////////////////////////////////////////////////////////////
/// Tile Iterator specialized for row-major congruous TensorOp formats.
///
///
/// Satisfies: ForwardTileIteratorConcept |
/// ReadableContiguousTileIteratorConcept |
/// WriteableContiguousTileIteratorConcept
///
template <typename Shape_, typename Element_, int AdvanceRank,
typename ThreadMap_, int Alignment>
class RegularTileIterator<
Shape_, Element_,
layout::RowMajorTensorOpMultiplicandCongruous<sizeof_bits<Element_>::value,
int(128 / sizeof(Element_))>,
AdvanceRank, ThreadMap_, Alignment> {
public:
static_assert(AdvanceRank == 0 || AdvanceRank == 1,
"Specialization for row-major iterator may along advance along the "
"columns(rank=0) or rows(rank=1) dimension.");
using Shape = Shape_;
using Element = Element_;
using Layout = layout::RowMajorTensorOpMultiplicandCongruous<
sizeof_bits<Element_>::value, int(128 / sizeof(Element))>;
static int const kAdvanceRank = AdvanceRank;
static int const kAlignment = Alignment;
using Index = typename Layout::Index;
using LongIndex = typename Layout::LongIndex;
using TensorRef = TensorRef<Element, Layout>;
using TensorCoord = typename Layout::TensorCoord;
using ThreadMap = ThreadMap_;
/// Underlying iterator type
using UnderlyingIterator = RegularTileIterator<
layout::PitchLinearShape<Shape::kColumn, Shape::kRow>, Element,
layout::TensorOpMultiplicandCongruous<sizeof_bits<Element_>::value,
int(128 / sizeof(Element))>,
(kAdvanceRank == 0 ? 1 : 0), ThreadMap_>;
public:
/// Fragment object to be loaded or stored
using Fragment = Array<Element, UnderlyingIterator::Fragment::kElements>;
private:
/// Underlying iterator
UnderlyingIterator iterator_;
public:
/// Construct a TileIterator with zero threadblock offset
CUTLASS_HOST_DEVICE
RegularTileIterator(
TensorRef ref, ///< Pointer to start of tensor
int thread_id ///< ID of each participating thread
): iterator_({ref.data(), ref.stride()}, thread_id) {
}
/// Adds a pointer offset in units of Element
CUTLASS_HOST_DEVICE
void add_pointer_offset(LongIndex pointer_offset) {
iterator_.add_pointer_offset(pointer_offset);
}
/// Adds a tile offset
CUTLASS_DEVICE
void add_tile_offset(TensorCoord const &coord) {
iterator_.add_tile_offset({coord.column(), coord.row()});
}
/// Advances to the next tile in memory.
CUTLASS_HOST_DEVICE
RegularTileIterator &operator++() {
++iterator_;
return *this;
}
/// Advances to the next tile in memory.
CUTLASS_HOST_DEVICE
RegularTileIterator operator++(int) {
RegularTileIterator prev(*this);
++iterator_;
return prev;
}
/// Loads a fragment from memory
CUTLASS_DEVICE
void load_with_pointer_offset(Fragment &frag, Index pointer_offset) {
iterator_.load_with_pointer_offset(frag, pointer_offset);
}
/// Loads a fragment from memory
CUTLASS_DEVICE
void load(Fragment &frag) {
load_with_pointer_offset(frag, 0);
}
/// Store a fragment to memory
CUTLASS_DEVICE
void store_with_pointer_offset(
Fragment const &frag,
Index pointer_offset) {
iterator_.store_with_pointer_offset(frag, pointer_offset);
}
/// Store a fragment to memory
CUTLASS_DEVICE
void store(Fragment const &frag) {
store_with_pointer_offset(frag, 0);
}
};
////////////////////////////////////////////////////////////////////////////////
/// Tile iterator specialized for crosswise arrangements for TensorOps
///
///
/// Satisfies: ForwardTileIteratorConcept |
/// ReadableContiguousTileIteratorConcept |
/// WriteableContiguousTileIteratorConcept
///
template <typename Shape_, typename Element_, int AdvanceRank,
typename ThreadMap_, int Alignment, int Crosswise>
class RegularTileIterator<Shape_, Element_,
layout::TensorOpMultiplicandCrosswise<
sizeof_bits<Element_>::value, Crosswise>,
AdvanceRank, ThreadMap_, Alignment> {
public:
static_assert(
AdvanceRank == 0 || AdvanceRank == 1,
"Specialization for pitch-linear iterator may along advance along the "
"contiguous(rank=0) or strided(rank=1) dimension.");
using Shape = Shape_;
using Element = Element_;
using Layout =
layout::TensorOpMultiplicandCrosswise<sizeof_bits<Element_>::value,
Crosswise>;
static int const kAdvanceRank = AdvanceRank;
static int const kAlignment = Alignment;
using Index = typename Layout::Index;
using LongIndex = typename Layout::LongIndex;
using TensorRef = TensorRef<Element, Layout>;
using TensorCoord = typename Layout::TensorCoord;
using ThreadMap = ThreadMap_;
/// Internal details made public to facilitate introspection
struct Detail {
/// This iterator is specialized for an access size that is 128 bits in
/// length.
static int const kAccessSizeInBits = 128;
static_assert(sizeof_bits<Element_>::value * ThreadMap::kElementsPerAccess ==
kAccessSizeInBits,
"This iterator requires a policy whose access size is 128bs");
};
private:
/// Element type per access
using AccessType = Array<Element, Layout::kElementsPerAccess>;
public:
/// Fragment object to be loaded or stored
using Fragment =
Array<Element, ThreadMap::Iterations::kCount * Layout::kElementsPerAccess>;
/// Underlying iterator to compute the addresses
using TileAccessIterator = RegularTileAccessIterator<Shape, Element, Layout,
kAdvanceRank, ThreadMap>;
private:
//
// Data members
//
/// Data member to the tile access iterator
TileAccessIterator address_iterator_;
public:
/// Construct a TileIterator with zero threadblock offset
CUTLASS_HOST_DEVICE
RegularTileIterator(TensorRef ref, ///< Pointer to start of tensor
int thread_id ///< ID of each participating thread
)
: address_iterator_(ref, thread_id) {}
/// Adds a pointer offset in units of Element
CUTLASS_HOST_DEVICE
void add_pointer_offset(LongIndex pointer_offset) {
address_iterator_.add_pointer_offset(pointer_offset);
}
/// Advances to the next tile in memory.
CUTLASS_HOST_DEVICE
RegularTileIterator &operator++() {
address_iterator_.add_tile_offset({1, 0});
return *this;
}
/// Advances to the next tile in memory.
CUTLASS_HOST_DEVICE
RegularTileIterator operator++(int) {
RegularTileIterator prev(*this);
this->operator++();
return prev;
}
/// Adds a tile offset
CUTLASS_DEVICE
void add_tile_offset(TensorCoord const &coord) {
address_iterator_.add_tile_offset(coord);
}
/// Loads a fragment from memory
CUTLASS_DEVICE
void load_with_pointer_offset(Fragment &frag, Index pointer_offset) {
address_iterator_.set_iteration_index(0);
AccessType *frag_ptr = reinterpret_cast<AccessType *>(&frag);
CUTLASS_PRAGMA_UNROLL
for (int s = 0; s < ThreadMap::Iterations::kStrided; ++s) {
CUTLASS_PRAGMA_UNROLL
for (int c = 0; c < ThreadMap::Iterations::kContiguous; ++c) {
int access_idx = c + s * ThreadMap::Iterations::kContiguous;
frag_ptr[access_idx] = *(address_iterator_.get() + pointer_offset);
++address_iterator_;
}
}
}
/// Loads a fragment from memory
CUTLASS_DEVICE
void load(Fragment &frag) { load_with_pointer_offset(frag, 0); }
/// Store a fragment to memory
CUTLASS_DEVICE
void store_with_pointer_offset(Fragment const &frag, Index pointer_offset) {
store_with_byte_offset(frag, pointer_offset * sizeof_bits<Element>::value / 8);
}
CUTLASS_DEVICE
void store_with_byte_offset(Fragment const &frag, Index byte_offset) {
address_iterator_.set_iteration_index(0);
AccessType const *frag_ptr = reinterpret_cast<AccessType const *>(&frag);
CUTLASS_PRAGMA_UNROLL
for (int s = 0; s < ThreadMap::Iterations::kStrided; ++s) {
CUTLASS_PRAGMA_UNROLL
for (int c = 0; c < ThreadMap::Iterations::kContiguous; ++c) {
int access_idx = c + s * ThreadMap::Iterations::kContiguous;
char *byte_ptr = reinterpret_cast<char *>(address_iterator_.get()) + byte_offset;
AccessType *access_ptr = reinterpret_cast<AccessType *>(byte_ptr);
*access_ptr = frag_ptr[access_idx];
++address_iterator_;
}
}
}
/// Store a fragment to memory
CUTLASS_DEVICE
void store(Fragment const &frag) { store_with_pointer_offset(frag, 0); }
};
////////////////////////////////////////////////////////////////////////////////
/// Tile Iterator specialized for column-major crosswise TensorOp formats.
///
///
/// Satisfies: ForwardTileIteratorConcept |
/// ReadableContiguousTileIteratorConcept |
/// WriteableContiguousTileIteratorConcept
///
template <typename Shape_, typename Element_, int AdvanceRank,
typename ThreadMap_, int Alignment, int Crosswise>
class RegularTileIterator<Shape_, Element_,
layout::ColumnMajorTensorOpMultiplicandCrosswise<
sizeof_bits<Element_>::value, Crosswise>,
AdvanceRank, ThreadMap_, Alignment> {
public:
static_assert(
AdvanceRank == 0 || AdvanceRank == 1,
"Specialization for column-major iterator may along advance along the "
"columns(rank=0) or rows(rank=1) dimension.");
using Shape = Shape_;
using Element = Element_;
using Layout = layout::ColumnMajorTensorOpMultiplicandCrosswise<
sizeof_bits<Element_>::value, Crosswise>;
static int const kAdvanceRank = AdvanceRank;
static int const kAlignment = Alignment;
using Index = typename Layout::Index;
using LongIndex = typename Layout::LongIndex;
using TensorRef = TensorRef<Element, Layout>;
using TensorCoord = typename Layout::TensorCoord;
using ThreadMap = ThreadMap_;
/// Underlying iterator type
using UnderlyingIterator = RegularTileIterator<
layout::PitchLinearShape<Shape::kRow, Shape::kColumn>, Element,
layout::TensorOpMultiplicandCrosswise<sizeof_bits<Element_>::value,
Crosswise>,
(kAdvanceRank == 0 ? 0 : 1), ThreadMap_>;
public:
/// Fragment object to be loaded or stored
using Fragment = Array<Element, UnderlyingIterator::Fragment::kElements>;
private:
/// Underlying iterator
UnderlyingIterator iterator_;
public:
/// Construct a TileIterator with zero threadblock offset
CUTLASS_HOST_DEVICE
RegularTileIterator(TensorRef ref, ///< Pointer to start of tensor
int thread_id ///< ID of each participating thread
)
: iterator_({ref.data(), ref.stride()}, thread_id) {}
/// Adds a pointer offset in units of Element
CUTLASS_HOST_DEVICE
void add_pointer_offset(LongIndex pointer_offset) {
iterator_.add_pointer_offset(pointer_offset);
}
/// Adds a tile offset
CUTLASS_DEVICE
void add_tile_offset(TensorCoord const &coord) {
iterator_.add_tile_offset({coord.row(), coord.column()});
}
/// Advances to the next tile in memory.
CUTLASS_HOST_DEVICE
RegularTileIterator &operator++() {
++iterator_;
return *this;
}
/// Advances to the next tile in memory.
CUTLASS_HOST_DEVICE
RegularTileIterator operator++(int) {
RegularTileIterator prev(*this);
++iterator_;
return prev;
}
/// Loads a fragment from memory
CUTLASS_DEVICE
void load_with_pointer_offset(Fragment &frag, Index pointer_offset) {
iterator_.load_with_pointer_offset(frag, pointer_offset);
}
/// Loads a fragment from memory
CUTLASS_DEVICE
void load(Fragment &frag) { load_with_pointer_offset(frag, 0); }
/// Store a fragment to memory
CUTLASS_DEVICE
void store_with_pointer_offset(Fragment const &frag, Index pointer_offset) {
iterator_.store_with_pointer_offset(frag, pointer_offset);
}
/// Store a fragment to memory
CUTLASS_DEVICE
void store(Fragment const &frag) { store_with_pointer_offset(frag, 0); }
};
////////////////////////////////////////////////////////////////////////////////
/// Tile Iterator specialized for row-major crosswise TensorOp formats.
///
///
/// Satisfies: ForwardTileIteratorConcept |
/// ReadableContiguousTileIteratorConcept |
/// WriteableContiguousTileIteratorConcept
///
template <typename Shape_, typename Element_, int AdvanceRank,
typename ThreadMap_, int Alignment, int Crosswise>
class RegularTileIterator<Shape_, Element_,
layout::RowMajorTensorOpMultiplicandCrosswise<
sizeof_bits<Element_>::value, Crosswise>,
AdvanceRank, ThreadMap_, Alignment> {
public:
static_assert(
AdvanceRank == 0 || AdvanceRank == 1,
"Specialization for row-major iterator may along advance along the "
"columns(rank=0) or rows(rank=1) dimension.");
using Shape = Shape_;
using Element = Element_;
using Layout = layout::RowMajorTensorOpMultiplicandCrosswise<
sizeof_bits<Element_>::value, Crosswise>;
static int const kAdvanceRank = AdvanceRank;
static int const kAlignment = Alignment;
using Index = typename Layout::Index;
using LongIndex = typename Layout::LongIndex;
using TensorRef = TensorRef<Element, Layout>;
using TensorCoord = typename Layout::TensorCoord;
using ThreadMap = ThreadMap_;
/// Underlying iterator type
using UnderlyingIterator = RegularTileIterator<
layout::PitchLinearShape<Shape::kColumn, Shape::kRow>, Element,
layout::TensorOpMultiplicandCrosswise<sizeof_bits<Element_>::value,
Crosswise>,
(kAdvanceRank == 0 ? 1 : 0), ThreadMap_>;
public:
/// Fragment object to be loaded or stored
using Fragment = Array<Element, UnderlyingIterator::Fragment::kElements>;
private:
/// Underlying iterator
UnderlyingIterator iterator_;
public:
/// Construct a TileIterator with zero threadblock offset
CUTLASS_HOST_DEVICE
RegularTileIterator(TensorRef ref, ///< Pointer to start of tensor
int thread_id ///< ID of each participating thread
)
: iterator_({ref.data(), ref.stride()}, thread_id) {}
/// Adds a pointer offset in units of Element
CUTLASS_HOST_DEVICE
void add_pointer_offset(LongIndex pointer_offset) {
iterator_.add_pointer_offset(pointer_offset);
}
/// Adds a tile offset
CUTLASS_DEVICE
void add_tile_offset(TensorCoord const &coord) {
iterator_.add_tile_offset({coord.column(), coord.row()});
}
/// Advances to the next tile in memory.
CUTLASS_HOST_DEVICE
RegularTileIterator &operator++() {
++iterator_;
return *this;
}
/// Advances to the next tile in memory.
CUTLASS_HOST_DEVICE
RegularTileIterator operator++(int) {
RegularTileIterator prev(*this);
++iterator_;
return prev;
}
/// Loads a fragment from memory
CUTLASS_DEVICE
void load_with_pointer_offset(Fragment &frag, Index pointer_offset) {
iterator_.load_with_pointer_offset(frag, pointer_offset);
}
/// Loads a fragment from memory
CUTLASS_DEVICE
void load(Fragment &frag) { load_with_pointer_offset(frag, 0); }
/// Store a fragment to memory
CUTLASS_DEVICE
void store_with_pointer_offset(Fragment const &frag, Index pointer_offset) {
iterator_.store_with_pointer_offset(frag, pointer_offset);
}
/// Store a fragment to memory
CUTLASS_DEVICE
void store(Fragment const &frag) { store_with_pointer_offset(frag, 0); }
};
////////////////////////////////////////////////////////////////////////////////
/// Tile iterator specialized for k interleaved arrangements for TensorOps
///
///
/// Satisfies: ForwardTileIteratorConcept |
/// ReadableContiguousTileIteratorConcept |
/// WriteableContiguousTileIteratorConcept
///
template <typename Shape_, typename Element_, int AdvanceRank, typename ThreadMap_, int InterleavedK, int Alignment>
class RegularTileIterator<
Shape_, Element_,
layout::TensorOpMultiplicandRowMajorInterleaved<sizeof_bits<Element_>::value,
InterleavedK>,
AdvanceRank, ThreadMap_, Alignment> {
public:
static_assert(
AdvanceRank == 0 || AdvanceRank == 1,
"Specialization for pitch-linear iterator may along advance along the "
"contiguous(rank=0) or strided(rank=1) dimension.");
using Shape = Shape_;
using Element = Element_;
using Layout =
layout::TensorOpMultiplicandRowMajorInterleaved<sizeof_bits<Element_>::value,
InterleavedK>;
static int const kAdvanceRank = AdvanceRank;
static int const kAlignment = Alignment;
using Index = typename Layout::Index;
using LongIndex = typename Layout::LongIndex;
using TensorRef = TensorRef<Element, Layout>;
using TensorCoord = typename Layout::TensorCoord;
using ThreadMap = ThreadMap_;
/// Internal details made public to facilitate introspection
struct Detail {
/// This iterator is specialized for an access size that is 128 bits in
/// length.
static int const kAccessSizeInBits = 128;
static_assert(sizeof_bits<Element_>::value * ThreadMap::kElementsPerAccess ==
kAccessSizeInBits,
"This iterator requires a policy whose access size is 128bs");
};
private:
/// Element type per access
using AccessType = Array<Element, Layout::kElementsPerAccess>;
public:
/// Fragment object to be loaded or stored
using Fragment =
Array<Element, ThreadMap::Iterations::kCount * Layout::kElementsPerAccess>;
/// Underlying iterator to compute the addresses
using TileAccessIterator = RegularTileAccessIterator<Shape, Element, Layout,
kAdvanceRank, ThreadMap>;
private:
//
// Data members
//
/// Data member to the tile access iterator
TileAccessIterator address_iterator_;
public:
/// Construct a TileIterator with zero threadblock offset
CUTLASS_HOST_DEVICE
RegularTileIterator(TensorRef ref, ///< Pointer to start of tensor
int thread_id ///< ID of each participating thread
)
: address_iterator_(ref, thread_id) {}
/// Adds a pointer offset in units of Element
CUTLASS_HOST_DEVICE
void add_pointer_offset(LongIndex pointer_offset) {
address_iterator_.add_pointer_offset(pointer_offset);
}
/// Advances to the next tile in memory.
CUTLASS_HOST_DEVICE
RegularTileIterator &operator++() {
address_iterator_.add_pointer_offset(Shape::kCount);
return *this;
}
/// Advances to the next tile in memory.
CUTLASS_HOST_DEVICE
RegularTileIterator operator++(int) {
RegularTileIterator prev(*this);
this->operator++();
return prev;
}
/// Adds a tile offset
CUTLASS_DEVICE
void add_tile_offset(TensorCoord const &coord) {
address_iterator_.add_pointer_offset(coord.contiguous() * Shape::kCount);
}
/// Loads a fragment from memory
CUTLASS_DEVICE
void load_with_pointer_offset(Fragment &frag, Index pointer_offset) {
address_iterator_.set_iteration_index(0);
AccessType *frag_ptr = reinterpret_cast<AccessType *>(&frag);
CUTLASS_PRAGMA_UNROLL
for (int s = 0; s < ThreadMap::Iterations::kStrided; ++s) {
CUTLASS_PRAGMA_UNROLL
for (int c = 0; c < ThreadMap::Iterations::kContiguous; ++c) {
int access_idx = c + s * ThreadMap::Iterations::kContiguous;
frag_ptr[access_idx] = *(address_iterator_.get() + pointer_offset);
++address_iterator_;
}
}
}
/// Loads a fragment from memory
CUTLASS_DEVICE
void load(Fragment &frag) { load_with_pointer_offset(frag, 0); }
/// Store a fragment to memory
CUTLASS_DEVICE
void store_with_pointer_offset(Fragment const &frag, Index pointer_offset) {
AccessType const *frag_ptr = reinterpret_cast<AccessType const *>(&frag);
CUTLASS_PRAGMA_UNROLL
for (int s = 0; s < ThreadMap::Iterations::kStrided; ++s) {
CUTLASS_PRAGMA_UNROLL
for (int c = 0; c < ThreadMap::Iterations::kContiguous; ++c) {
int access_idx = c + s * ThreadMap::Iterations::kContiguous;
*(address_iterator_.get() + pointer_offset) = frag_ptr[access_idx];
++address_iterator_;
}
}
}
/// Store a fragment to memory
CUTLASS_DEVICE
void store(Fragment const &frag) { store_with_pointer_offset(frag, 0); }
};
////////////////////////////////////////////////////////////////////////////////
/// Tile iterator specialized for k interleaved arrangements for TensorOps
///
///
/// Satisfies: ForwardTileIteratorConcept |
/// ReadableContiguousTileIteratorConcept |
/// WriteableContiguousTileIteratorConcept
///
template <typename Shape_, typename Element_, int AdvanceRank, typename ThreadMap_, int InterleavedK, int Alignment>
class RegularTileIterator<
Shape_, Element_,
layout::TensorOpMultiplicandColumnMajorInterleaved<sizeof_bits<Element_>::value,
InterleavedK>,
AdvanceRank, ThreadMap_, Alignment> {
public:
static_assert(
AdvanceRank == 0 || AdvanceRank == 1,
"Specialization for pitch-linear iterator may along advance along the "
"contiguous(rank=0) or strided(rank=1) dimension.");
using Shape = Shape_;
using Element = Element_;
using Layout =
layout::TensorOpMultiplicandColumnMajorInterleaved<sizeof_bits<Element_>::value,
InterleavedK>;
static int const kAdvanceRank = AdvanceRank;
static int const kAlignment = Alignment;
using Index = typename Layout::Index;
using LongIndex = typename Layout::LongIndex;
using TensorRef = TensorRef<Element, Layout>;
using TensorCoord = typename Layout::TensorCoord;
using ThreadMap = ThreadMap_;
/// Underlying iterator type
using UnderlyingIterator = RegularTileIterator<
cutlass::MatrixShape<Shape::kColumn, Shape::kRow>,
Element,
layout::TensorOpMultiplicandRowMajorInterleaved<sizeof_bits<Element_>::value, InterleavedK>,
(kAdvanceRank == 1 ? 0 : 1),
ThreadMap
>;
public:
/// Fragment object to be loaded or stored
using Fragment = Array<Element, UnderlyingIterator::Fragment::kElements>;
private:
/// Underlying iterator
UnderlyingIterator iterator_;
public:
/// Construct a TileIterator with zero threadblock offset
CUTLASS_HOST_DEVICE
RegularTileIterator(TensorRef ref, ///< Pointer to start of tensor
int thread_id ///< ID of each participating thread
)
: iterator_({ref.data(), ref.stride()}, thread_id) {}
/// Adds a pointer offset in units of Element
CUTLASS_HOST_DEVICE
void add_pointer_offset(LongIndex pointer_offset) {
iterator_.add_pointer_offset(pointer_offset);
}
/// Advances to the next tile in memory.
CUTLASS_HOST_DEVICE
RegularTileIterator &operator++() {
++iterator_;
return *this;
}
/// Advances to the next tile in memory.
CUTLASS_HOST_DEVICE
RegularTileIterator operator++(int) {
RegularTileIterator prev(*this);
++iterator_;
return prev;
}
/// Adds a tile offset
CUTLASS_DEVICE
void add_tile_offset(TensorCoord const &coord) {
iterator_.add_tile_offset({coord.strided(), coord.contiguous()});
}
/// Loads a fragment from memory
CUTLASS_DEVICE
void load_with_pointer_offset(Fragment &frag, Index pointer_offset) {
iterator_.load_with_pointer_offset(frag, pointer_offset);
}
/// Loads a fragment from memory
CUTLASS_DEVICE
void load(Fragment &frag) { load_with_pointer_offset(frag, 0); }
/// Store a fragment to memory
CUTLASS_DEVICE
void store_with_pointer_offset(Fragment const &frag, Index pointer_offset) {
iterator_.store_with_pointer_offset(frag, pointer_offset);
}
/// Store a fragment to memory
CUTLASS_DEVICE
void store(Fragment const &frag) { store_with_pointer_offset(frag, 0); }
};
/////////////////////////////////////////////////////////////////////////////////////////////////
} // namespace threadblock
} // namespace transform
} // namespace cutlass
/////////////////////////////////////////////////////////////////////////////////////////////////
| [
"[email protected]"
] | |
b924f1ec9209a454b9d755897bd2a55984a74951 | 89d2087816be31d25d0f147384bd02016598d139 | /Battle Game with Teams/Vampire.cpp | 36e1f8b174215665998c902d29915600a1b2b6f6 | [] | no_license | mveregge23/Cpp-Projects | fc38dd734c56b1649c6e79e4f3f1b9cbd387ddec | ac5ea877ce83ede92bc34eba094e726b165ba5a6 | refs/heads/master | 2021-02-16T19:52:10.147581 | 2020-04-02T18:52:54 | 2020-04-02T18:52:54 | 245,040,151 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,756 | cpp | // Program name: Vampire.cpp
// Date: 11/7/19
// Author: Max Veregge
// Description: Vampire.cpp contains an implementation for the Vampire subclass of Character. Vampire
// inherits data members for attacking, defending, armor, and strength from Character and defines
// them in its constructor. Vampire implements an attack function and a defense function with the
// Charm ability.
#include "Vampire.hpp"
//constructor inherits behavior from parent class Character, then dynamically defines strength, armor, and name of the character
Vampire::Vampire(int numAttackDice, int attackDiceSides, int numDefenseDice, std::string name) : Character(numAttackDice, attackDiceSides, numDefenseDice, name) {
this->strength = 18;
this->maxStrength = 18;
this->armor = 1;
this->type = "Vampire";
}
//attack() rolls the characters attack dice, printing out the total of their roll and returning it to the caller
int Vampire::attack() {
int attackRoll = 0;
for (int i = 0; i < this->numAttackDice; i++) {
attackRoll += this->attackDice[i]->roll();
}
return attackRoll;
}
//defend() rolls the characters defense dice, printing out the total of their roll and armor and returning it to the caller
//defend() also implements the Charm ability for Vampire, which returns a max value defense roll that negates all possible attack rolls
int Vampire::defend() {
//calculate charmChance
double charmChance = double(rand()) / RAND_MAX;
int defenseRoll = 0;
for (int i = 0; i < this->numDefenseDice; i++) {
defenseRoll += this->defenseDice[i]->roll();
}
//if charmChance > 0.5, notify user and return max defense roll
if (charmChance > 0.5) {
return 32;
}
//otherwise return regular defense roll
else {
return defenseRoll + this->armor;
}
}
| [
"[email protected]"
] | |
7c159dc425f677dc227846e899b6a16b75764b73 | 765fa8281770e0f8263cbb7bd62ba5d0631a4306 | /main.cpp | cc0133710e15615013c90bceb8933c061fe610cd | [] | no_license | luiscf1226/P3Lab3_LuisFlores | dbd599fa299f0f40ee372a23042019c06d02e1e8 | 705af95030cf4a1f6c8456f072023ad5e4ffcd55 | refs/heads/master | 2023-04-20T22:42:50.989129 | 2021-05-08T00:18:12 | 2021-05-08T00:18:12 | 336,367,429 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,260 | cpp | #include <iostream>
#include <cstdlib>
#include <math.h>
#include <cmath>
#include <stdlib.h>
#include <time.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
void pasos(char*,char**,int,int,int,int,int ,int,int);
char** create(int,int);
void free(char**&,int);
char** game(int,int,int);
char* uno(char*,int);
void print2 (char**,int,int);
void print(char*,int);
int menu(){
while(true){
cout<<"MENU"<<endl;
cout<<"1. Ejercicio 1 "<<endl<<"2. Ejercicio 2 "<<endl<<"3. Ejercicio 3"<<endl<<"4. Salir"<<endl;
int valor;
cin>>valor;
if(valor > 0&& valor < 5)
return valor;
}
}
int main(int argc, char** argv) {
int main=0;
while(main!=4){
switch(main=menu()){
case 1:{
int size;
char*array;
cout<<"ingrese el size: "<<endl;
cin>>size;
array=new char[size];
for(int i=0;i<size;i++){
cout<<"ingrese letra por letra: "<<endl;
cin>>array[i];
}
for(int i=0;i<size;i++){
cout<<array[i]<<" ";
}
cout<<endl;
char* imp=uno(array,size) ;
print(imp,100);
delete[]array;
delete[]imp;
}
case 2:{
int n,m,k;
cout<<"ingrese cantidad filas: "<<endl;
cin>>n;
cout<<"ingrese cantidad columnas: "<<endl;
cin>>m;
cout<<"ingrese cantidad obstaculos: "<<endl;
cin>>k;
char** matriz=game(n,m,k);
print2(matriz,n,m);
free(matriz,n);
}
case 3:{
int size;
int steps;
cout<<"ingrese cantidad de pasos: "<<endl;
cin>>steps;
cout<<"ingrese tamano de array: "<<endl;
cin>>size;
char* pasos1=new char[size];
for(int i=0;i<size;i++){
cout<<" ingrese paso por paso (char) : " <<endl;
cin>>pasos1[i];
}
int n,m,k;
cout<<"ingrese cantidad filas: "<<endl;
cin>>n;
cout<<"ingrese cantidad columnas: "<<endl;
cin>>m;
cout<<"ingrese cantidad obstaculos: "<<endl;
cin>>k;
char** matriz=game(n,m,k);
int filas,columnas;
cout<<"ingrese fila donde va a empezar: "<<endl;
cin>>filas;
cout<<"ingrese columna donde va a empezar: "<<endl;
cin>>columnas;
char* array=uno(pasos1,size) ;
print(array,size);
cout<<size<<endl;
pasos(array,matriz,n,m,k,size,filas,columnas,steps);
delete[]array;
delete[]pasos1;
free(matriz,n);
break;
}
case 4:{
cout<<"el programa se acabara "<<endl;
break;
}
}//sitwch
}//while
return 0;
}
void pasos(char*array,char**matriz,int n,int m,int k,int size,int filas,int columnas,int steps){
//cout<<size<<endl;
//cout<<steps;
print2(matriz,n,m);
int cont=0;
char move;
while(steps>0){
for(int i=0;i<size;i++){
for(int i2=0;i2<n;i2++){
for(int j=0;j<m;j++){
while(matriz[i2][j]!='#'){
if(array[i]=='U'){
if(steps==0){
break;
}
move=186;
matriz[filas][columnas]=move;
filas-=1;
columnas=columnas;
cont++;
cout<<"enter y mire el proximo "<<endl<<flush;
system ("PAUSE");
print2(matriz,n,m);
steps--;
cout<<"paso: "<<steps<<endl;
if(matriz[n-n][columnas]==move){
//cout<<filas<<" "<<columnas<<endl;
columnas+=1;
filas=0;
steps--;
}
steps--;
}
if(array[i]=='R'){
if(steps==0){
break;
}
move=205;
matriz[filas][columnas]=move;
filas=filas;
columnas+=1;
cout<<"enter y mire el proximo "<<endl<<flush;
system ("PAUSE");
steps--;
cout<<"paso: "<<steps<<endl;
print2(matriz,n,m);
if(matriz[filas-1][columnas-1]==move){
columnas=columnas;
filas
=n-1;
steps--;
}
}
if(array[i]=='D'){
if(steps==0){
break;
}
move=186;
matriz[filas][columnas]=move;
filas+=1;
columnas=columnas;
cout<<"enter y mire el proximo "<<endl<<flush;
system ("PAUSE");
steps--;
cout<<"paso: "<<steps<<endl;
print2(matriz,n,m);
if(matriz[n-1][columnas]==move){
filas=filas;
columnas+=1;
steps--;
}
}
if(array[i]=='L'){
if(steps==0){
break;
}
move=205;
matriz[filas][columnas]=move;
filas=filas;
columnas-=1;
cout<<"enter y mire el proximo "<<endl<<flush;
system ("PAUSE");
steps--;
cout<<"paso: "<<steps<<endl;
print2(matriz,n,m);
}
}
}
}
}
steps--;
}
}
void free(char**& matriz,int size){
if(matriz!=NULL){
for(int i=0;i<size;i++){
if(matriz[i]!=NULL){
delete []matriz[i];
matriz[i]=NULL;//null
}
}
delete[]matriz;
matriz=NULL;
}
}
char* uno(char* array,int size){
char *ret=new char[1000];
int cont2=0;
int value;
for(int i=0;i<size;i++ ){
int digit=array[i]- '0';
//cout<<"DIGITO: "<<digit<<endl;
if(digit>=1&&digit<=9){
int cantveces=digit;
int exp=1;
int cont=i+1;
while(array[cont]-'0'<=9&&array[cont]>=1){
cantveces=cantveces*pow(10,exp);
cantveces+=array[cont]-'0';
exp+=1;
cont+=1;
}
i=cont;
for(int h=0;h<cantveces;h++){
//cout<<"LETRA: "<<array[i]<<endl;
ret[cont2]=array[i];
cont2++;
}
}
}
ret[cont2]='\n';
cout<<endl;
return ret;
}
char** create(int size,int size2){
char** retVal=new char*[size];
for(int i=0;i<size;i++){
retVal[i]=new char[size2];
}
return retVal;
}
char** game(int n,int m,int k){
char** matriz=create(n,m);
int c=0;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
matriz[i][j]='-';
}
}
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
int cont=0;
while(k>0){
srand (time(NULL));
int n2=1+(rand()%n-1);
srand (time(NULL));
int m2=1+(rand()%m-1);
if(matriz[n2][m2]=='-'){
matriz[n2][m2]='#';
k--;
}
}
}
}
return matriz;
}
void print2(char**matriz,int size,int size2){
for(int i=0;i<size;i++){
for(int j=0;j<size2;j++){
cout<<matriz[i][j]<<" ";
}
cout<<endl;
}
}
void print(char* a,int size){
for(int i=0;i<size;i++){
cout<<a[i]<<" ";
}
cout<<endl;
} | [
"[email protected]"
] | |
d42b10a276886663565f723a737d3ea95eb74830 | 8f4faf47d46d87991329d6499a3eb9e2688301b7 | /Lists/Circular Singly Linked List/Header.h | e2cb911f4d67466d6a6727199187ac5801b12e4e | [] | no_license | kirisanm/CppCollection | e65799b22bec40c971893b2add904a517d0e550d | baee9f2e70703eceb85180aeafeac1fc9296ffb5 | refs/heads/master | 2020-03-11T08:18:37.948341 | 2018-05-24T19:37:51 | 2018-05-24T19:37:51 | 129,880,512 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 460 | h |
// Coded & developed by Kirisan Manivannan
#include <iostream>
using namespace std;
class Node {
public:
Node(int d, Node* n);
int get_data();
Node* get_next();
void set_next(Node*);
private:
int data;
Node* next;
};
class Linkedlist {
public:
Linkedlist();
~Linkedlist();
bool is_empty();
void add_front(int);
void add_back(int);
void remove_front();
void print_all();
void print_loop();
private:
Node* head;
Node* tail;
int size;
}; | [
"[email protected]"
] | |
dc0069ff306f1f331f7d460df5ecbe8efc1e0681 | 10f67f9503e52ed4a8bb757d470f2c3b8fe0cea1 | /2021_Team3_Project/2021_Team3_Project/enemy_attack_arrow_polygon.h | 61c4552277464e5cc5510f743a99d9d01562358d | [] | no_license | Mesarthim-14/2021_Team3_Project | 6e7a73a90c3e790d965fbdaa0f9fddebf5895ee7 | f0b62a48edb1b4476c1f0ebaa4b96afb44962c80 | refs/heads/master | 2023-08-24T09:54:27.694543 | 2021-10-04T03:07:43 | 2021-10-04T03:07:48 | 373,224,774 | 3 | 0 | null | 2021-10-01T08:20:39 | 2021-06-02T15:54:25 | C++ | SHIFT_JIS | C++ | false | false | 1,599 | h | //=============================================================================
// 敵の攻撃矢印 [enemy_attack_arrow_polygon.h]
// Author : Sugawara Tsukasa
//=============================================================================
#ifndef _ENEMY_ATTACK_ARROW_POLYGON_H_
#define _ENEMY_ATTACK_ARROW_POLYGON_H_
//=============================================================================
// インクルード
// Author : Sugawara Tsukasa
//=============================================================================
#include "billboard.h"
#include "bullet.h"
//=============================================================================
// マップクラス
// Author : Sugawara Tsukasa
//=============================================================================
class CEnemy_Attack_Arrow_Polygon : public CBillboard
{
public:
CEnemy_Attack_Arrow_Polygon(PRIORITY Priority = PRIORITY_UI); // コンストラクタ
~CEnemy_Attack_Arrow_Polygon(); // デストラクタ
static CEnemy_Attack_Arrow_Polygon *Create(D3DXVECTOR3 pos, D3DXVECTOR3 size, CBullet *pBullet); // 生成処理
HRESULT Init(D3DXVECTOR3 pos, D3DXVECTOR3 size); // 初期化処理
void Uninit(void); // 終了処理
void Update(void); // 更新処理
void Draw(void); // 描画処理
private:
void Collision(void); // 当たり判定
void Move(void); // 移動
CBullet *m_pBullet; // CBulletのポインタ
int m_nCount; // カウント
bool m_bCollision; // 当たり判定
};
#endif | [
"[email protected]"
] | |
0ba38a4b34d11a8d2845db54255f5038d0f99709 | 1c68cdc7773fe45342fe61dad9acddd33da9197a | /common/common.cpp | ba911baafdcfb06fba6a75eef2e2c350992be82e | [
"MIT"
] | permissive | wheltz/GraphicsEditor | a30b6e12eea7f2db0e0166ebd88f2c21034665e3 | 371af0acd8e01dec417b06699362f6d42bf8d981 | refs/heads/master | 2022-03-01T08:12:09.591972 | 2019-10-28T05:21:57 | 2019-10-28T05:21:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 728 | cpp | #include "common.h"
QImage Mat2QImage(cv::Mat const& src)
{
cv::Mat temp; // make the same cv::Mat
cvtColor(src, temp,CV_BGR2RGB); // cvtColor Makes a copt, that what i need
QImage dest((const uchar *) temp.data, temp.cols, temp.rows, temp.step, QImage::Format_RGB888);
dest.bits(); // enforce deep copy, see documentation
// of QImage::QImage ( const uchar * data, int width, int height, Format format )
return dest;
}
cv::Mat QImage2Mat(QImage const& src)
{
cv::Mat tmp(src.height(),src.width(),CV_8UC3,(uchar*)src.bits(),src.bytesPerLine());
cv::Mat result; // deep copy just in case (my lack of knowledge with open cv)
cvtColor(tmp, result,CV_BGR2RGB);
return result;
}
| [
"yanghan9826@gmail"
] | yanghan9826@gmail |
137cd9cee43091af3b5fabaee873e25f30149f11 | 2397726c8d472266869fef711b86da26c58a1f02 | /behavior_tree_core/src/condition_node.cpp | d81831b61a584feda7b5773b788088241cb9b477 | [
"MIT"
] | permissive | iSaran/ROS-Behavior-Tree | 63710bd9b81c875657df68d8b77fe9a19df2d7f2 | a38431dd8165149b4d3bcac41ee3037de3489b03 | refs/heads/master | 2021-01-18T20:49:48.297099 | 2017-04-02T21:52:32 | 2017-04-02T21:52:32 | 86,991,925 | 0 | 0 | null | 2017-04-02T14:33:56 | 2017-04-02T14:33:56 | null | UTF-8 | C++ | false | false | 308 | cpp | #include <condition_node.h>
BT::ConditionNode::ConditionNode(std::string name) : LeafNode::LeafNode(name)
{
type_ = BT::CONDITION_NODE;
}
BT::ConditionNode::~ConditionNode() {}
void BT::ConditionNode::Halt() {}
int BT::ConditionNode::DrawType()
{
// Lock acquistion
return BT::CONDITION;
}
| [
"[email protected]"
] | |
f5dc860129916e819f62816ad6dda3726edb8dcc | a064569a273accdd58d24c8c569e54ef2ef6fbf1 | /21天学通C++(第7版)源代码/9780672335679_TYCPP-7E_Code/Chapter 17/17.8 DequeInsertionsDeletions/17.8 DequeInsertionsDeletions/17.8 DequeInsertionsDeletions.cpp | 288957031c3d6a6f3dafe43313ec5bf6bb71e3b8 | [] | no_license | bangiao/C_plus_plus | 52a00b689b62df45079cfb7bfb3e3df464310ffa | 6a6decaeacb10b6de4233cfe9c5f3765743c7054 | refs/heads/master | 2021-01-01T15:42:27.015650 | 2017-07-19T05:41:25 | 2017-07-19T05:41:25 | 97,676,912 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,400 | cpp | #include <deque>
#include <iostream>
#include <algorithm>
int main ()
{
using namespace std;
// Define a deque of integers
deque <int> dqIntegers;
// Insert integers at the bottom of the array
dqIntegers.push_back (3);
dqIntegers.push_back (4);
dqIntegers.push_back (5);
// Insert integers at the top of the array
dqIntegers.push_front (2);
dqIntegers.push_front (1);
dqIntegers.push_front (0);
cout << "The contents of the deque after inserting elements ";
cout << "at the top and bottom are:" << endl;
// Display contents on the screen
for ( size_t nCount = 0
; nCount < dqIntegers.size ()
; ++ nCount )
{
cout << "Element [" << nCount << "] = ";
cout << dqIntegers [nCount] << endl;
}
cout << endl;
// Erase an element at the top
dqIntegers.pop_front ();
// Erase an element at the bottom
dqIntegers.pop_back ();
cout << "The contents of the deque after erasing an element ";
cout << "from the top and bottom are:" << endl;
// Display contents again: this time using iterators
// deque <int>::iterator iElementLocator; // uncomment if using older compilers and remove auto below
for (auto iElementLocator = dqIntegers.begin ()
; iElementLocator != dqIntegers.end ()
; ++ iElementLocator )
{
size_t Offset = distance (dqIntegers.begin (), iElementLocator);
cout << "Element [" << Offset << "] = " << *iElementLocator << endl;
}
return 0;
} | [
"[email protected]"
] | |
f6c72e955921309e455a0072a06b57feba4d4ebc | 16f63d6f656ee3ad32f428c031709658a1d08915 | /ExpressionManager/ExpressionManager.cpp | 34e350618dee30c1d62ff0d43443a1b5cb8d46de | [] | no_license | petertaoyang/lab-2 | 509e5d9c94348117d13b8b983ed4ffcab1d8d1da | d303f9d74b103e63289041dc239cd7888d876ba2 | refs/heads/master | 2021-01-08T14:08:08.129025 | 2020-02-21T03:59:31 | 2020-02-21T03:59:31 | 242,049,186 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,107 | cpp | #include "ExpressionManager.h"
#include <iostream>
int ExpressionManager::value(void)
{
infix();
postFix_ = postfix();
std::stack<int> operand_stack;
std::istringstream iss(postFix_);
string next_token;
while (iss >> next_token)
{
//push all the digits
if (isdigit(next_token[0]))
{
int value = std::stoi(next_token);
operand_stack.push(value);
}
//calculate the result of the previous two digits when an operator is encountered. Push the result.
else
{
int leftOperand = operand_stack.top();
operand_stack.pop();
int rightOperand = operand_stack.top();
operand_stack.pop();
int result = 0;
switch (next_token[0])
{
case '+':
result = rightOperand + leftOperand;
break;
case '-':
result = rightOperand - leftOperand;
break;
case '*':
result = rightOperand * leftOperand;
break;
case '/':
result = rightOperand / leftOperand;
break;
case '%':
result = rightOperand % leftOperand;
break;
}
operand_stack.push(result);
}
}
return operand_stack.top();
}
string ExpressionManager::infix(void)
{
std::stack<string> string_stack;
std::istringstream iss(expression_);
string next_token;
while (iss >> next_token)
{
//push open paren
if (OPEN.find(next_token) != string::npos)
{
string_stack.push(next_token);
}
else if (CLOSE.find(next_token) != string::npos)
{
//check extra close paren
if (string_stack.empty())
{
throw std::string("Unbalanced");
}
else
{
string top_string = string_stack.top();
string_stack.pop();
// check if the open paren and the close paren match
if (OPEN.find(top_string) != CLOSE.find(next_token)) { throw std::string("Unbalanced"); }
}
}
}
//check if extra open paren
if (!string_stack.empty())
{
throw std::string("Unbalanced");
}
const string OPERATORS_WITHOUT_PAREN = "-+*/%";
while (!string_stack.empty())
{
string_stack.pop();
}
std::istringstream iss_two(expression_);
while (iss_two >> next_token)
{
//check if there's an illegal operator
if ((!isdigit(next_token[0])) && (ALL_OPERATORS.find(next_token) == string::npos))
{
throw std::string("Illegal Operator");
}
if (isdigit(next_token[0]))
{
//check if there are two adjacent digits
if (!string_stack.empty())
{
throw std::string("Missing Operator");
}
string_stack.push(next_token);
}
else if (OPERATORS_WITHOUT_PAREN.find(next_token) != string::npos)
{
//check extra operator
if (string_stack.empty())
{
throw std::string("Missing Operand");
}
string_stack.pop();
}
}
//check if there is a digit left in the stack
if (string_stack.empty())
{
throw std::string("Missing Operand");
}
return expression_;
}
string ExpressionManager::postfix(void)
{
infix();
postFix_ = "";
while (!operatorStack.empty())
{
operatorStack.pop();
}
std::istringstream iss(expression_);
string next_token;
while (iss >> next_token)
{
//append digits to the postfix string
if (isdigit(next_token[0]))
{
postFix_ += next_token;
postFix_ += " ";
}
//process operators
else if (ALL_OPERATORS.find(next_token) != string::npos)
{
if (operatorStack.empty() || OPEN.find(next_token) != string::npos)
{
operatorStack.push(next_token);
}
else
{
if (precedence(next_token) > precedence(operatorStack.top()))
{
operatorStack.push(next_token);
}
else
{
/*append operators to the postfix string until the stack is empty or
the current operator precedence is higher or there is an open paren*/
while (!operatorStack.empty() && (precedence(next_token) <= precedence(operatorStack.top()))
&& OPEN.find(operatorStack.top()) == string::npos)
{
postFix_ += operatorStack.top();
postFix_ += " ";
operatorStack.pop();
}
//pop the open paren if the next token is a close paren
if (CLOSE.find(next_token) != string::npos) { operatorStack.pop(); }
else { operatorStack.push(next_token); }
}
}
}
}
//append operators in the stack to the postfix string
while (!operatorStack.empty())
{
string op = operatorStack.top();
operatorStack.pop();
postFix_ += op;
postFix_ += " ";
}
return postFix_;
}
string ExpressionManager::prefix(void)
{
infix();
string next_token;
/* Step one: call reverse function - use a string stack to store strings (Open paren will become close paren, and close paren will become
open paren) to get the reversed expression */
string reversedExpression = reverseExpression(expression_);
/* Step two: same method used in postfix except that the operator stack will push the current operator if it has
the same precedence as the top operator in the stack */
postFix_ = "";
while (!operatorStack.empty())
{
operatorStack.pop();
}
std::istringstream iss(reversedExpression);
while (iss >> next_token)
{
//append digits to the postfix string
if (isdigit(next_token[0]))
{
postFix_ += next_token;
postFix_ += " ";
}
//process operators
else if (ALL_OPERATORS.find(next_token) != string::npos)
{
if (operatorStack.empty() || OPEN.find(next_token) != string::npos)
{
operatorStack.push(next_token);
}
else
{
if (precedence(next_token) >= precedence(operatorStack.top()) && CLOSE.find(next_token) == string::npos)
{
operatorStack.push(next_token);
}
else
{
/*append operators to the postfix string until the stack is empty or
the current operator precedence is higher or there is an open paren*/
while (!operatorStack.empty() && (precedence(next_token) < precedence(operatorStack.top()))
&& OPEN.find(operatorStack.top()) == string::npos)
{
postFix_ += operatorStack.top();
postFix_ += " ";
operatorStack.pop();
}
//pop the open paren if the next token is a close paren
if (CLOSE.find(next_token) != string::npos) { operatorStack.pop(); }
else { operatorStack.push(next_token); }
}
}
}
}
//append operators in the stack to the postfix string
while (!operatorStack.empty())
{
string op = operatorStack.top();
operatorStack.pop();
postFix_ += op;
postFix_ += " ";
}
//Final step: call reverse function - reverse the postfix expression that's been converted from the reversed expression to get prefix
preFix_ = reverseExpression(postFix_);
return preFix_;
}
string ExpressionManager::reverseExpression(string expression)
{
string reversedExpression = "";
std::stack<string> string_stack;
std::istringstream iss(expression);
string next_token;
while (iss >> next_token)
{
if (CLOSE.find(next_token) != string::npos)
{
string_stack.push(OPEN.substr(CLOSE.find(next_token), 1));
}
else if (OPEN.find(next_token) != string::npos)
{
string_stack.push(CLOSE.substr(OPEN.find(next_token), 1));
}
else
{
string_stack.push(next_token);
}
}
//get the reversed string
while (!string_stack.empty())
{
reversedExpression += string_stack.top();
reversedExpression += " ";
string_stack.pop();
}
return reversedExpression;
} | [
"[email protected]"
] | |
61db474d154a0c9fe4653c241b439d656b99137c | 24f26275ffcd9324998d7570ea9fda82578eeb9e | /chrome/browser/sharing/click_to_call/click_to_call_context_menu_observer_unittest.cc | 5906829a2a715f5114cb6c6944c57ca1c1afc1f2 | [
"BSD-3-Clause"
] | permissive | Vizionnation/chromenohistory | 70a51193c8538d7b995000a1b2a654e70603040f | 146feeb85985a6835f4b8826ad67be9195455402 | refs/heads/master | 2022-12-15T07:02:54.461083 | 2019-10-25T15:07:06 | 2019-10-25T15:07:06 | 217,557,501 | 2 | 1 | BSD-3-Clause | 2022-11-19T06:53:07 | 2019-10-25T14:58:54 | null | UTF-8 | C++ | false | false | 8,745 | cc | // Copyright 2019 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/sharing/click_to_call/click_to_call_context_menu_observer.h"
#include <memory>
#include <string>
#include <vector>
#include "base/macros.h"
#include "base/strings/strcat.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/time/time.h"
#include "chrome/app/chrome_command_ids.h"
#include "chrome/browser/renderer_context_menu/mock_render_view_context_menu.h"
#include "chrome/browser/sharing/click_to_call/click_to_call_utils.h"
#include "chrome/browser/sharing/click_to_call/feature.h"
#include "chrome/browser/sharing/mock_sharing_service.h"
#include "chrome/browser/sharing/sharing_constants.h"
#include "chrome/browser/sharing/sharing_service_factory.h"
#include "components/sync_device_info/device_info.h"
#include "content/public/common/context_menu_params.h"
#include "content/public/test/browser_task_environment.h"
#include "content/public/test/web_contents_tester.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"
using ::testing::_;
using ::testing::ByMove;
using ::testing::Eq;
using ::testing::NiceMock;
using ::testing::Return;
using SharingMessage = chrome_browser_sharing::SharingMessage;
namespace {
const char kPhoneNumber[] = "+9876543210";
constexpr int kSeparatorCommandId = -1;
class ClickToCallContextMenuObserverTest : public testing::Test {
public:
ClickToCallContextMenuObserverTest() = default;
~ClickToCallContextMenuObserverTest() override = default;
void SetUp() override {
web_contents_ = content::WebContentsTester::CreateTestWebContents(
menu_.GetBrowserContext(), nullptr);
menu_.set_web_contents(web_contents_.get());
SharingServiceFactory::GetInstance()->SetTestingFactory(
menu_.GetBrowserContext(),
base::BindRepeating([](content::BrowserContext* context)
-> std::unique_ptr<KeyedService> {
return std::make_unique<NiceMock<MockSharingService>>();
}));
observer_ = std::make_unique<ClickToCallContextMenuObserver>(&menu_);
menu_.SetObserver(observer_.get());
}
void BuildMenu(const std::string& phone_number) {
observer_->BuildMenu(phone_number,
SharingClickToCallEntryPoint::kRightClickLink);
sharing_message.mutable_click_to_call_message()->set_phone_number(
phone_number);
}
std::vector<std::unique_ptr<syncer::DeviceInfo>> CreateMockDevices(
int count) {
std::vector<std::unique_ptr<syncer::DeviceInfo>> devices;
for (int i = 0; i < count; i++) {
devices.emplace_back(std::make_unique<syncer::DeviceInfo>(
base::StrCat({"guid", base::NumberToString(i)}), "name",
"chrome_version", "user_agent",
sync_pb::SyncEnums_DeviceType_TYPE_PHONE, "device_id",
base::SysInfo::HardwareInfo(),
/*last_updated_timestamp=*/base::Time::Now(),
/*send_tab_to_self_receiving_enabled=*/false,
/*sharing_info=*/base::nullopt));
}
return devices;
}
protected:
NiceMock<MockSharingService>* service() {
return static_cast<NiceMock<MockSharingService>*>(
SharingServiceFactory::GetForBrowserContext(menu_.GetBrowserContext()));
}
content::BrowserTaskEnvironment task_environment_;
MockRenderViewContextMenu menu_{/* incognito= */ false};
std::unique_ptr<content::WebContents> web_contents_;
std::unique_ptr<ClickToCallContextMenuObserver> observer_;
SharingMessage sharing_message;
DISALLOW_COPY_AND_ASSIGN(ClickToCallContextMenuObserverTest);
};
} // namespace
MATCHER_P(ProtoEquals, message, "") {
std::string expected_serialized, actual_serialized;
message.SerializeToString(&expected_serialized);
arg.SerializeToString(&actual_serialized);
return expected_serialized == actual_serialized;
}
TEST_F(ClickToCallContextMenuObserverTest, NoDevices_DoNotShowMenu) {
auto devices = CreateMockDevices(0);
EXPECT_CALL(*service(), GetDeviceCandidates(_))
.WillOnce(Return(ByMove(std::move(devices))));
BuildMenu(kPhoneNumber);
EXPECT_EQ(0U, menu_.GetMenuSize());
}
TEST_F(ClickToCallContextMenuObserverTest, SingleDevice_ShowMenu) {
auto devices = CreateMockDevices(1);
auto guid = devices[0]->guid();
EXPECT_CALL(*service(), GetDeviceCandidates(_))
.WillOnce(Return(ByMove(std::move(devices))));
BuildMenu(kPhoneNumber);
// Assert item ordering.
MockRenderViewContextMenu::MockMenuItem item;
int item_id = 0;
ASSERT_TRUE(menu_.GetMenuItem(item_id++, &item));
EXPECT_EQ(kSeparatorCommandId, item.command_id);
ASSERT_TRUE(menu_.GetMenuItem(item_id++, &item));
EXPECT_EQ(IDC_CONTENT_CONTEXT_SHARING_CLICK_TO_CALL_SINGLE_DEVICE,
item.command_id);
ASSERT_TRUE(menu_.GetMenuItem(item_id++, &item));
EXPECT_EQ(kSeparatorCommandId, item.command_id);
EXPECT_EQ(item_id, static_cast<int>(menu_.GetMenuSize()));
// Emulate click on the device.
EXPECT_CALL(*service(), SendMessageToDevice(Eq(guid), Eq(kSharingMessageTTL),
ProtoEquals(sharing_message), _))
.Times(1);
menu_.ExecuteCommand(IDC_CONTENT_CONTEXT_SHARING_CLICK_TO_CALL_SINGLE_DEVICE,
0);
}
TEST_F(ClickToCallContextMenuObserverTest, MultipleDevices_ShowMenu) {
constexpr int device_count = 3;
auto devices = CreateMockDevices(device_count);
std::vector<std::string> guids;
for (auto& device : devices)
guids.push_back(device->guid());
EXPECT_CALL(*service(), GetDeviceCandidates(_))
.WillOnce(Return(ByMove(std::move(devices))));
BuildMenu(kPhoneNumber);
// Assert item ordering.
MockRenderViewContextMenu::MockMenuItem item;
int item_id = 0;
ASSERT_TRUE(menu_.GetMenuItem(item_id++, &item));
EXPECT_EQ(kSeparatorCommandId, item.command_id);
ASSERT_TRUE(menu_.GetMenuItem(item_id++, &item));
EXPECT_EQ(IDC_CONTENT_CONTEXT_SHARING_CLICK_TO_CALL_MULTIPLE_DEVICES,
item.command_id);
for (int i = 0; i < device_count; i++) {
ASSERT_TRUE(menu_.GetMenuItem(item_id++, &item));
EXPECT_EQ(kSubMenuFirstDeviceCommandId + i, item.command_id);
}
ASSERT_TRUE(menu_.GetMenuItem(item_id++, &item));
EXPECT_EQ(kSeparatorCommandId, item.command_id);
EXPECT_EQ(item_id, static_cast<int>(menu_.GetMenuSize()));
// Emulate clicks on all commands to check for commands with no device
// assigned.
for (int i = 0; i < kMaxDevicesShown; i++) {
if (i < device_count) {
EXPECT_CALL(*service(),
SendMessageToDevice(Eq(guids[i]), Eq(kSharingMessageTTL),
ProtoEquals(sharing_message), _))
.Times(1);
} else {
EXPECT_CALL(*service(), SendMessageToDevice(_, _, _, _)).Times(0);
}
observer_->sub_menu_delegate_.ExecuteCommand(
kSubMenuFirstDeviceCommandId + i, 0);
}
}
TEST_F(ClickToCallContextMenuObserverTest,
MultipleDevices_MoreThanMax_ShowMenu) {
int device_count = kMaxDevicesShown + 1;
auto devices = CreateMockDevices(device_count);
std::vector<std::string> guids;
for (auto& device : devices)
guids.push_back(device->guid());
EXPECT_CALL(*service(), GetDeviceCandidates(_))
.WillOnce(Return(ByMove(std::move(devices))));
BuildMenu(kPhoneNumber);
// Assert item ordering.
MockRenderViewContextMenu::MockMenuItem item;
int item_id = 0;
ASSERT_TRUE(menu_.GetMenuItem(item_id++, &item));
EXPECT_EQ(kSeparatorCommandId, item.command_id);
ASSERT_TRUE(menu_.GetMenuItem(item_id++, &item));
EXPECT_EQ(IDC_CONTENT_CONTEXT_SHARING_CLICK_TO_CALL_MULTIPLE_DEVICES,
item.command_id);
for (int i = 0; i < kMaxDevicesShown; i++) {
ASSERT_TRUE(menu_.GetMenuItem(item_id++, &item));
EXPECT_EQ(kSubMenuFirstDeviceCommandId + i, item.command_id);
}
ASSERT_TRUE(menu_.GetMenuItem(item_id++, &item));
EXPECT_EQ(kSeparatorCommandId, item.command_id);
EXPECT_EQ(item_id, static_cast<int>(menu_.GetMenuSize()));
// Emulate clicks on all device commands to check for commands outside valid
// range too.
for (int i = 0; i < device_count; i++) {
if (i < kMaxDevicesShown) {
EXPECT_CALL(*service(),
SendMessageToDevice(Eq(guids[i]), Eq(kSharingMessageTTL),
ProtoEquals(sharing_message), _))
.Times(1);
} else {
EXPECT_CALL(*service(), SendMessageToDevice(_, _, _, _)).Times(0);
}
observer_->sub_menu_delegate_.ExecuteCommand(
kSubMenuFirstDeviceCommandId + i, 0);
}
}
| [
"[email protected]"
] | |
4d599dbe533e86e91e73580d2b004fc26943d77a | 3dda745e0ca7b9995c4b017f353aeebe84ce0d54 | /Praktikum 1/main.cpp | 3ed7f6c60baaabeb9f57c7ed2e97c476eef17478 | [] | no_license | aminulloh/ComputerVision | 8cfd3c8c3b4a1d9b35664d6fb496021536781f4f | 0fc6e7175bb2ccade2e65fbfe69888851b4827a7 | refs/heads/master | 2020-08-03T19:34:03.931638 | 2019-12-03T00:12:52 | 2019-12-03T00:12:52 | 211,861,998 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,790 | cpp | #include<stdlib.h>
#include<math.h>
#include<string.h>
#include<iostream>
#include<opencv2\opencv.hpp>
#include<opencv2\core\core.hpp>
#include<opencv2\highgui\highgui.hpp>
#include<opencv2\imgproc\imgproc.hpp>
#include<opencv2\ml\ml.hpp>
#include<opencv2\objdetect\objdetect.hpp>
#include<opencv2\videoio.hpp>
using namespace std;
using namespace cv;
Mat img; Mat templ, dst; Mat result; char* image_window = "Source Image";
char* result_window = "Result window";
int match_method;
int max_Trackbar = 5;
/// Function Headers
void MatchingMethod(int, void*);
int main() {
/// Load image and template
img = imread("1_800.png", 1);
templ = imread("1a.png", 1);
//cv::resize(img, img, cv::Size(512, 512));
//cv::resize(templ, templ, cv::Size(512, 512));
//cv::resize(templ, templ, cv::Size(254, 254));
/// Create windows
/// Create Trackbar
char* trackbar_label = "Method: \n 0: SQDIFF \n 1: SQDIFF NORMED \n 2: TM CCORR \n 3: TM CCORR NORMED \n 4: TM COEFF \n 5: TM COEFF NORMED";
//waitKey(0);
while (true)
{
printf("input");
char c = (char)waitKey(0);
if ((char)c == 27)
{
break;
}
if ((char)c == 'u')
{
pyrUp(templ, templ, Size(templ.cols * 1.2, templ.rows * 1.2));
//printf("** Zoom In: Image x 2 \n");
}
else if ((char)c == 'd')
{
pyrDown(templ, templ, Size(templ.cols / 1.2, templ.rows / 1.2));
//printf("** Zoom Out: Image / 2 \n");
}
imshow("test", templ);
createTrackbar(trackbar_label, image_window, &match_method, max_Trackbar, MatchingMethod);
MatchingMethod(0, 0);
templ = templ;
}
return 0;
}
void MatchingMethod(int, void*)
{
Mat img_display; img.copyTo(img_display);
/// Create the result matrix
int result_cols = img.cols - templ.cols + 1; int result_rows = img.rows - templ.rows + 1;
result.create(result_rows, result_cols, CV_32FC1);
/// Do the Matching and Normalize
matchTemplate(img, templ, result, match_method);
normalize(result, result, 0, 1, NORM_MINMAX, -1, Mat());
/// Localizing the best match with minMaxLoc
double minVal; double maxVal;
Point minLoc;
Point maxLoc;
Point matchLoc;
minMaxLoc(result, &minVal, &maxVal, &minLoc, &maxLoc, Mat());
/// For SQDIFF and SQDIFF_NORMED, the best matches are lower values.for all the other methods, the higher the better
if (match_method == CV_TM_SQDIFF || match_method == CV_TM_SQDIFF_NORMED)
{
matchLoc = minLoc;
}
else
{
matchLoc = maxLoc;
}
/// Show me what you got
rectangle(img_display, matchLoc, Point(matchLoc.x + templ.cols, matchLoc.y + templ.rows), Scalar::all(0), 2, 8, 0);
rectangle(result, matchLoc, Point(matchLoc.x + templ.cols, matchLoc.y + templ.rows), Scalar::all(0), 2, 8, 0);
imshow(image_window, img_display);
imshow("result_window", result);
//imshow( "templ", templ );
return;
}
| [
"[email protected]"
] | |
39d13e71790988305f07da1a2f4ee74ec780838a | 880387c837ed0a6e0002bb0e549413d892fd432c | /src/kernel.cpp | 174c5becbda9c8f6f571f3b4abca68f60b0d149f | [
"MIT"
] | permissive | bitcoin-token/Bitcoin-Turbo-Koin-Core | 442bd64d7488487bffb15b6611ca4c85ee4ca2ff | 4dcfed3192bb1085f685c86211ed08c68c20c7a3 | refs/heads/master | 2020-04-27T10:14:32.071751 | 2019-03-06T00:52:29 | 2019-03-06T00:52:29 | 174,245,608 | 5 | 6 | null | null | null | null | UTF-8 | C++ | false | false | 18,523 | cpp | // Copyright (c) 2012-2013 The PPCoin developers
// Copyright (c) 2015-2018 The PIVX developers
// Copyright (c) 2019 The BTK developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <boost/assign/list_of.hpp>
#include "db.h"
#include "kernel.h"
#include "script/interpreter.h"
#include "timedata.h"
#include "util.h"
#include "stakeinput.h"
#include "zbtkchain.h"
using namespace std;
bool fTestNet = false; //Params().NetworkID() == CBaseChainParams::TESTNET;
// Modifier interval: time to elapse before new modifier is computed
// Set to 3-hour for production network and 20-minute for test network
unsigned int nModifierInterval;
int nStakeTargetSpacing = 60;
unsigned int getIntervalVersion(bool fTestNet)
{
if (fTestNet)
return MODIFIER_INTERVAL_TESTNET;
else
return MODIFIER_INTERVAL;
}
// Hard checkpoints of stake modifiers to ensure they are deterministic.
static std::map<int, unsigned int> mapStakeModifierCheckpoints =
boost::assign::map_list_of(0, 0xfd11f4e7u);
// Get time weight.
int64_t GetWeight(int64_t nIntervalBeginning, int64_t nIntervalEnd)
{
return nIntervalEnd - nIntervalBeginning - nStakeMinAge;
}
// Get the last stake modifier and its generation time from a given block.
static bool GetLastStakeModifier(const CBlockIndex* pindex, uint64_t& nStakeModifier, int64_t& nModifierTime)
{
if (!pindex)
return error("GetLastStakeModifier: null pindex");
while (pindex && pindex->pprev && !pindex->GeneratedStakeModifier())
pindex = pindex->pprev;
if (!pindex->GeneratedStakeModifier())
return error("GetLastStakeModifier: no generation at genesis block");
nStakeModifier = pindex->nStakeModifier;
nModifierTime = pindex->GetBlockTime();
return true;
}
// Get selection interval section (in seconds).
static int64_t GetStakeModifierSelectionIntervalSection(int nSection)
{
assert(nSection >= 0 && nSection < 64);
int64_t a = getIntervalVersion(fTestNet) * 63 / (63 + ((63 - nSection) * (MODIFIER_INTERVAL_RATIO - 1)));
return a;
}
// Get stake modifier selection interval (in seconds).
static int64_t GetStakeModifierSelectionInterval()
{
int64_t nSelectionInterval = 0;
for (int nSection = 0; nSection < 64; nSection++) {
nSelectionInterval += GetStakeModifierSelectionIntervalSection(nSection);
}
return nSelectionInterval;
}
// select a block from the candidate blocks in vSortedByTimestamp, excluding
// already selected blocks in vSelectedBlocks, and with timestamp up to
// nSelectionIntervalStop.
static bool SelectBlockFromCandidates(
vector<pair<int64_t, uint256> >& vSortedByTimestamp,
map<uint256, const CBlockIndex*>& mapSelectedBlocks,
int64_t nSelectionIntervalStop,
uint64_t nStakeModifierPrev,
const CBlockIndex** pindexSelected)
{
bool fModifierV2 = false;
bool fFirstRun = true;
bool fSelected = false;
uint256 hashBest = 0;
*pindexSelected = (const CBlockIndex*)0;
BOOST_FOREACH (const PAIRTYPE(int64_t, uint256) & item, vSortedByTimestamp) {
if (!mapBlockIndex.count(item.second))
return error("SelectBlockFromCandidates: failed to find block index for candidate block %s", item.second.ToString().c_str());
const CBlockIndex* pindex = mapBlockIndex[item.second];
if (fSelected && pindex->GetBlockTime() > nSelectionIntervalStop)
break;
// If the lowest block height (vSortedByTimestamp[0]) is >= switch height, use new modifier calc.
if (fFirstRun){
fModifierV2 = pindex->nHeight >= Params().ModifierUpgradeBlock();
fFirstRun = false;
}
if (mapSelectedBlocks.count(pindex->GetBlockHash()) > 0)
continue;
// Compute the selection hash by hashing an input that is unique to that block.
uint256 hashProof;
if(fModifierV2)
hashProof = pindex->GetBlockHash();
else
hashProof = pindex->IsProofOfStake() ? 0 : pindex->GetBlockHash();
CDataStream ss(SER_GETHASH, 0);
ss << hashProof << nStakeModifierPrev;
uint256 hashSelection = Hash(ss.begin(), ss.end());
// the selection hash is divided by 2**32 so that proof-of-stake block
// is always favored over proof-of-work block. this is to preserve
// the energy efficiency property
if (pindex->IsProofOfStake())
hashSelection >>= 32;
if (fSelected && hashSelection < hashBest) {
hashBest = hashSelection;
*pindexSelected = (const CBlockIndex*)pindex;
} else if (!fSelected) {
fSelected = true;
hashBest = hashSelection;
*pindexSelected = (const CBlockIndex*)pindex;
}
}
if (GetBoolArg("-printstakemodifier", false))
LogPrintf("SelectBlockFromCandidates: selection hash=%s\n", hashBest.ToString().c_str());
return fSelected;
}
// Stake Modifier (hash modifier of proof-of-stake):
// The purpose of stake modifier is to prevent a txout (coin) owner from
// computing future proof-of-stake generated by this txout at the time
// of transaction confirmation. To meet kernel protocol, the txout
// must hash with a future stake modifier to generate the proof.
// Stake modifier consists of bits each of which is contributed from a
// selected block of a given block group in the past.
// The selection of a block is based on a hash of the block's proof-hash and
// the previous stake modifier.
// Stake modifier is recomputed at a fixed time interval instead of every
// block. This is to make it difficult for an attacker to gain control of
// additional bits in the stake modifier, even after generating a chain of
// blocks.
bool ComputeNextStakeModifier(const CBlockIndex* pindexPrev, uint64_t& nStakeModifier, bool& fGeneratedStakeModifier)
{
nStakeModifier = 0;
fGeneratedStakeModifier = false;
if (!pindexPrev) {
fGeneratedStakeModifier = true;
return true; // Genesis block's modifier is 0.
}
if (pindexPrev->nHeight == 0) {
// Give a stake modifier to the first block.
fGeneratedStakeModifier = true;
nStakeModifier = uint64_t("stakemodifier");
return true;
}
// First find current stake modifier and its generation block time
// if it's not old enough, return the same stake modifier.
int64_t nModifierTime = 0;
if (!GetLastStakeModifier(pindexPrev, nStakeModifier, nModifierTime))
return error("ComputeNextStakeModifier: unable to get last modifier");
if (GetBoolArg("-printstakemodifier", false))
LogPrintf("ComputeNextStakeModifier: prev modifier= %s time=%s\n", std::to_string(nStakeModifier).c_str(), DateTimeStrFormat("%Y-%m-%d %H:%M:%S", nModifierTime).c_str());
if (nModifierTime / getIntervalVersion(fTestNet) >= pindexPrev->GetBlockTime() / getIntervalVersion(fTestNet))
return true;
// Sort candidate blocks by timestamp
vector<pair<int64_t, uint256> > vSortedByTimestamp;
vSortedByTimestamp.reserve(64 * getIntervalVersion(fTestNet) / nStakeTargetSpacing);
int64_t nSelectionInterval = GetStakeModifierSelectionInterval();
int64_t nSelectionIntervalStart = (pindexPrev->GetBlockTime() / getIntervalVersion(fTestNet)) * getIntervalVersion(fTestNet) - nSelectionInterval;
const CBlockIndex* pindex = pindexPrev;
while (pindex && pindex->GetBlockTime() >= nSelectionIntervalStart) {
vSortedByTimestamp.push_back(make_pair(pindex->GetBlockTime(), pindex->GetBlockHash()));
pindex = pindex->pprev;
}
int nHeightFirstCandidate = pindex ? (pindex->nHeight + 1) : 0;
reverse(vSortedByTimestamp.begin(), vSortedByTimestamp.end());
sort(vSortedByTimestamp.begin(), vSortedByTimestamp.end());
// Select 64 blocks from candidate blocks to generate stake modifier
uint64_t nStakeModifierNew = 0;
int64_t nSelectionIntervalStop = nSelectionIntervalStart;
map<uint256, const CBlockIndex*> mapSelectedBlocks;
for (int nRound = 0; nRound < min(64, (int)vSortedByTimestamp.size()); nRound++) {
// add an interval section to the current selection round
nSelectionIntervalStop += GetStakeModifierSelectionIntervalSection(nRound);
// Slect a block from the candidates of current round.
if (!SelectBlockFromCandidates(vSortedByTimestamp, mapSelectedBlocks, nSelectionIntervalStop, nStakeModifier, &pindex))
return error("ComputeNextStakeModifier: unable to select block at round %d", nRound);
// Write the entropy bit of the selected block.
nStakeModifierNew |= (((uint64_t)pindex->GetStakeEntropyBit()) << nRound);
// Add the selected block from candidates to selected list.
mapSelectedBlocks.insert(make_pair(pindex->GetBlockHash(), pindex));
if (GetBoolArg("-printstakemodifier", false))
LogPrintf("ComputeNextStakeModifier: selected round %d stop=%s height=%d bit=%d\n",
nRound, DateTimeStrFormat("%Y-%m-%d %H:%M:%S", nSelectionIntervalStop).c_str(), pindex->nHeight, pindex->GetStakeEntropyBit());
}
// Print selection map for visualization of the selected blocks.
if (GetBoolArg("-printstakemodifier", false)) {
string strSelectionMap = "";
// '-' indicates proof-of-work blocks not selected
strSelectionMap.insert(0, pindexPrev->nHeight - nHeightFirstCandidate + 1, '-');
pindex = pindexPrev;
while (pindex && pindex->nHeight >= nHeightFirstCandidate) {
// '=' indicates proof-of-stake blocks not selected
if (pindex->IsProofOfStake())
strSelectionMap.replace(pindex->nHeight - nHeightFirstCandidate, 1, "=");
pindex = pindex->pprev;
}
BOOST_FOREACH (const PAIRTYPE(uint256, const CBlockIndex*) & item, mapSelectedBlocks) {
// 'S' indicates selected proof-of-stake blocks
// 'W' indicates selected proof-of-work blocks
strSelectionMap.replace(item.second->nHeight - nHeightFirstCandidate, 1, item.second->IsProofOfStake() ? "S" : "W");
}
LogPrintf("ComputeNextStakeModifier: selection height [%d, %d] map %s\n", nHeightFirstCandidate, pindexPrev->nHeight, strSelectionMap.c_str());
}
if (GetBoolArg("-printstakemodifier", false)) {
LogPrintf("ComputeNextStakeModifier: new modifier=%s time=%s\n", std::to_string(nStakeModifierNew).c_str(), DateTimeStrFormat("%Y-%m-%d %H:%M:%S", pindexPrev->GetBlockTime()).c_str());
}
nStakeModifier = nStakeModifierNew;
fGeneratedStakeModifier = true;
return true;
}
// The stake modifier used to hash for a stake kernel is chosen as the stake
// modifier about a selection interval later than the coin generating the kernel
bool GetKernelStakeModifier(uint256 hashBlockFrom, uint64_t& nStakeModifier, int& nStakeModifierHeight, int64_t& nStakeModifierTime, bool fPrintProofOfStake)
{
nStakeModifier = 0;
if (!mapBlockIndex.count(hashBlockFrom))
return error("GetKernelStakeModifier() : block not indexed");
const CBlockIndex* pindexFrom = mapBlockIndex[hashBlockFrom];
nStakeModifierHeight = pindexFrom->nHeight;
nStakeModifierTime = pindexFrom->GetBlockTime();
int64_t nStakeModifierSelectionInterval = GetStakeModifierSelectionInterval();
const CBlockIndex* pindex = pindexFrom;
CBlockIndex* pindexNext = chainActive[pindexFrom->nHeight + 1];
// Loop to find the stake modifier later by a selection interval.
while (nStakeModifierTime < pindexFrom->GetBlockTime() + nStakeModifierSelectionInterval) {
if (!pindexNext) {
// Should never happen.
return error("Null pindexNext\n");
}
pindex = pindexNext;
pindexNext = chainActive[pindexNext->nHeight + 1];
if (pindex->GeneratedStakeModifier()) {
nStakeModifierHeight = pindex->nHeight;
nStakeModifierTime = pindex->GetBlockTime();
}
}
nStakeModifier = pindex->nStakeModifier;
return true;
}
// Test hash vs target.
bool stakeTargetHit(uint256 hashProofOfStake, int64_t nValueIn, uint256 bnTargetPerCoinDay)
{
// Get the stake weight - weight is equal to coin amount.
uint256 bnCoinDayWeight = uint256(nValueIn) / 100;
// Now check if proof-of-stake hash meets target protocol.
return hashProofOfStake < (bnCoinDayWeight * bnTargetPerCoinDay);
}
bool CheckStake(const CDataStream& ssUniqueID, CAmount nValueIn, const uint64_t nStakeModifier, const uint256& bnTarget,
unsigned int nTimeBlockFrom, unsigned int& nTimeTx, uint256& hashProofOfStake)
{
CDataStream ss(SER_GETHASH, 0);
ss << nStakeModifier << nTimeBlockFrom << ssUniqueID << nTimeTx;
hashProofOfStake = Hash(ss.begin(), ss.end());
return stakeTargetHit(hashProofOfStake, nValueIn, bnTarget);
}
bool Stake(CStakeInput* stakeInput, unsigned int nBits, unsigned int nTimeBlockFrom, unsigned int& nTimeTx, uint256& hashProofOfStake)
{
if (nTimeTx < nTimeBlockFrom)
return error("CheckStakeKernelHash() : nTime violation");
if (nTimeBlockFrom + nStakeMinAge > nTimeTx) // Min age requirement
return error("CheckStakeKernelHash() : min age violation - nTimeBlockFrom=%d nStakeMinAge=%d nTimeTx=%d",
nTimeBlockFrom, nStakeMinAge, nTimeTx);
// Grab difficulty.
uint256 bnTargetPerCoinDay;
bnTargetPerCoinDay.SetCompact(nBits);
// Grab stake modifier.
uint64_t nStakeModifier = 0;
if (!stakeInput->GetModifier(nStakeModifier))
return error("failed to get kernel stake modifier");
bool fSuccess = false;
unsigned int nTryTime = 0;
int nHeightStart = chainActive.Height();
int nHashDrift = 30;
CDataStream ssUniqueID = stakeInput->GetUniqueness();
CAmount nValueIn = stakeInput->GetValue();
for (int i = 0; i < nHashDrift; i++) //Iterate the hashing.
{
// New block came in, move on.
if (chainActive.Height() != nHeightStart)
break;
// Hash this iteration.
nTryTime = nTimeTx + nHashDrift - i;
// If stake hash does not meet the target then continue to next iteration.
if (!CheckStake(ssUniqueID, nValueIn, nStakeModifier, bnTargetPerCoinDay, nTimeBlockFrom, nTryTime, hashProofOfStake))
continue;
fSuccess = true; // If we make it this far then we have successfully created a stake hash.
nTimeTx = nTryTime;
break;
}
mapHashedBlocks.clear();
mapHashedBlocks[chainActive.Tip()->nHeight] = GetTime(); //store a time stamp of when we last hashed on this block
return fSuccess;
}
// Check kernel hash target and coinstake signature.
bool CheckProofOfStake(const CBlock block, uint256& hashProofOfStake, std::unique_ptr<CStakeInput>& stake)
{
const CTransaction tx = block.vtx[1];
if (!tx.IsCoinStake())
return error("CheckProofOfStake() : called on non-coinstake %s", tx.GetHash().ToString().c_str());
// Kernel (input 0) must match the stake hash target per coin age (nBits).
const CTxIn& txin = tx.vin[0];
// Construct the stakeinput object.
if (tx.IsZerocoinSpend()) {
libzerocoin::CoinSpend spend = TxInToZerocoinSpend(txin);
if (spend.getSpendType() != libzerocoin::SpendType::STAKE)
return error("%s: spend is using the wrong SpendType (%d)", __func__, (int)spend.getSpendType());
stake = std::unique_ptr<CStakeInput>(new CZBTKStake(spend));
} else {
// First try finding the previous transaction in database.
uint256 hashBlock;
CTransaction txPrev;
if (!GetTransaction(txin.prevout.hash, txPrev, hashBlock, true))
return error("CheckProofOfStake() : INFO: read txPrev failed");
// Verify signature and script.
if (!VerifyScript(txin.scriptSig, txPrev.vout[txin.prevout.n].scriptPubKey, STANDARD_SCRIPT_VERIFY_FLAGS, TransactionSignatureChecker(&tx, 0)))
return error("CheckProofOfStake() : VerifySignature failed on coinstake %s", tx.GetHash().ToString().c_str());
CBTKStake* btkInput = new CBTKStake();
btkInput->SetInput(txPrev, txin.prevout.n);
stake = std::unique_ptr<CStakeInput>(btkInput);
}
CBlockIndex* pindex = stake->GetIndexFrom();
if (!pindex)
return error("%s: Failed to find the block index", __func__);
// Read block header.
CBlock blockprev;
if (!ReadBlockFromDisk(blockprev, pindex->GetBlockPos()))
return error("CheckProofOfStake(): INFO: failed to find block");
uint256 bnTargetPerCoinDay;
bnTargetPerCoinDay.SetCompact(block.nBits);
uint64_t nStakeModifier = 0;
if (!stake->GetModifier(nStakeModifier))
return error("%s failed to get modifier for stake input\n", __func__);
unsigned int nBlockFromTime = blockprev.nTime;
unsigned int nTxTime = block.nTime;
if (!CheckStake(stake->GetUniqueness(), stake->GetValue(), nStakeModifier, bnTargetPerCoinDay, nBlockFromTime,
nTxTime, hashProofOfStake)) {
return error("CheckProofOfStake() : INFO: check kernel failed on coinstake %s, hashProof=%s \n",
tx.GetHash().GetHex(), hashProofOfStake.GetHex());
}
return true;
}
// Check whether the coinstake timestamp meets protocol
bool CheckCoinStakeTimestamp(int64_t nTimeBlock, int64_t nTimeTx)
{
// v0.3 protocol
return (nTimeBlock == nTimeTx);
}
// Get stake modifier checksum
unsigned int GetStakeModifierChecksum(const CBlockIndex* pindex)
{
assert(pindex->pprev || pindex->GetBlockHash() == Params().HashGenesisBlock());
// Hash previous checksum with flags, hashProofOfStake and nStakeModifier
CDataStream ss(SER_GETHASH, 0);
if (pindex->pprev)
ss << pindex->pprev->nStakeModifierChecksum;
ss << pindex->nFlags << pindex->hashProofOfStake << pindex->nStakeModifier;
uint256 hashChecksum = Hash(ss.begin(), ss.end());
hashChecksum >>= (256 - 32);
return hashChecksum.Get64();
}
// Check stake modifier hard checkpoints
bool CheckStakeModifierCheckpoints(int nHeight, unsigned int nStakeModifierChecksum)
{
if (fTestNet) return true; // Testnet has no checkpoints
if (mapStakeModifierCheckpoints.count(nHeight)) {
return nStakeModifierChecksum == mapStakeModifierCheckpoints[nHeight];
}
return true;
}
| [
"[email protected]"
] | |
52a00cb8cf290d285f47e843a932bb602389540f | 0af35580335a896cc61ee9214deeedb0f0620424 | /URI/1104/1104.cpp | cd6948a5116f771193b8b2d660a8e9e171613ee2 | [] | no_license | ktakanopy/Competitive-Programming | 59d4c73ffbed0affdc85a2454b5c454841a092bf | 7d976f972947601f988969ae7c335b1d824352dd | refs/heads/master | 2022-12-01T07:55:27.499787 | 2019-03-16T19:13:35 | 2019-03-16T19:13:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 978 | cpp | #include <cstdio>
#include <cstring>
#include <set>
#define DBUG1 printf("DBUG 1\n");
#define DBUG2 printf("DBUG 2\n");
#define DBUG3 printf("DBUG 3\n");
using namespace std;
void print_set(set<int> pset)
{
for(auto &it : pset)
{
printf("[%d]",it);
}
printf("\n");
}
int main()
{
int A,B;
scanf("%d %d",&A,&B);
do
{
set<int> a_cards;
set<int> b_cards;
set<int> intersection_cards;
for(int i = 0 ;i < A;i++)
{
int value;
scanf("%d",&value);
a_cards.insert(value);
}
for(int i = 0 ;i < B;i++)
{
int value;
scanf("%d",&value);
b_cards.insert(value);
auto it = a_cards.find(value);
if(it != a_cards.end())
{
intersection_cards.insert(value);
}
}
int size_a = a_cards.size() - intersection_cards.size();
int size_b = b_cards.size() - intersection_cards.size();
printf("%d\n", (size_a < size_b)? size_a : size_b ) ;
scanf("%d %d",&A,&B);
}while(A != 0 && B != 0);
return 0;
}
| [
"[email protected]"
] | |
ada88583525c9839373359e7de5179e1850cb214 | 34b041e96a817021957b4b46f961a5d74edb1ea9 | /Motors.ino | 7a2abb64a3f60ce564d90454bb5804b6ef36ac2b | [] | no_license | zlite/MVBlimp | b1ed8c0802f231da3238a933c257a5b030bc3fb6 | 143d8211f6cea488d00fc993a7192214dadb34b9 | refs/heads/master | 2021-01-13T08:01:56.834879 | 2016-10-24T03:48:08 | 2016-10-24T03:48:08 | 71,611,654 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,973 | ino | /**************************************************************
* Subroutine to control right motor = motorRight(Speed, direction);
***************************************************************/
void motorRight(byte PWM, boolean dir)
{
byte oldPWM;
if(PWM==0) //If Speed = 0, shut down the motors
{
<<<<<<< HEAD
analogWrite(MotorPin1, 0);
analogWrite(MotorPin2, 0);
=======
digitalWrite(MotorPin1, LOW);
digitalWrite(MotorPin2, LOW);
>>>>>>> origin/master
static_friction_breaker_right=0; //And restart the state of the motor to indicate that it's stopped..
}
else{
restart_right:
PWM= constrain(PWM, minSpeed, maxSpeed); //Change higher values to the specified ranges
if(static_friction_breaker_right == 0)//Verify if the static friction is 0, if so that means that the motor was stopped so pulse harder
{
oldPWM=PWM; //Storing the original PWM value...
PWM=anti_static_friction_breaker; //This value is defined at the begining, pulsing the motor
}
if(dir == true) //If direction is 1 or true or HIGH, the motor will go forward
{
<<<<<<< HEAD
analogWrite(MotorPin1, 0);
=======
digitalWrite(MotorPin1, LOW);
>>>>>>> origin/master
analogWrite(MotorPin2, PWM);
}
if(dir == false) //If direction is 0 or false or LOW, the motor will go backwards
{
<<<<<<< HEAD
analogWrite(MotorPin1, PWM);
analogWrite(MotorPin2, 0); //Trick to regulate speed in reverse direction
=======
digitalWrite(MotorPin1, HIGH);
analogWrite(MotorPin2, 250-PWM); //Trick to regulate speed in reverse direction
>>>>>>> origin/master
}
if(static_friction_breaker_right == 0)//Then verify again if the motor was stopped. If yes...
{
smart_delay(50); //Delay for 10 milliseconds
static_friction_breaker_right=1; //and then change the state to 1, to indicate to the system that the motor is running
PWM=oldPWM; //Restoring desired speed...
goto restart_right; //Jumping to "restart_right:" defined above...
}
}
}
/**************************************************************
* Sub-rutine to control left motor
***************************************************************/
void motorLeft(byte PWM, boolean dir)
{
byte oldPWM;
if(PWM==0)//If Speed = 0, shut down the motor
{
<<<<<<< HEAD
analogWrite(MotorPin3, 0);
analogWrite(MotorPin4, 0);
=======
digitalWrite(MotorPin3, LOW);
digitalWrite(MotorPin4, LOW);
>>>>>>> origin/master
static_friction_breaker_left=0; //And restart the state of the motor to indicate it's stopped..
}
else{
restart_left:
PWM= constrain(PWM, minSpeed, maxSpeed);//Change higher values to the specified ranges
if(static_friction_breaker_left == 0)//Verify if the static friction is 0. If so, that means that the motor has stopped so pulse harder
{
oldPWM=PWM; //Storing the original PWM value...
PWM=anti_static_friction_breaker; //This value is defined at the begining
}
if(dir == true)//If direction is 1 or true or HIGH, the motor will go forward
{
<<<<<<< HEAD
analogWrite(MotorPin3, 0);
=======
digitalWrite(MotorPin3, LOW);
>>>>>>> origin/master
analogWrite(MotorPin4, PWM);
}
if(dir == false)//If direction is 0 or false or LOW, the motor will go backwards
{
<<<<<<< HEAD
analogWrite(MotorPin3, PWM);
analogWrite(MotorPin4, 0);
=======
digitalWrite(MotorPin3, HIGH);
analogWrite(MotorPin4, 250-PWM);
>>>>>>> origin/master
}
if(static_friction_breaker_left == 0)
{
smart_delay(50);//Change higher values to the specified ranges
static_friction_breaker_left=1; //and then change the state to 1, to indicate to the system that the motor is running
PWM=oldPWM; //Restoring desired speed...
goto restart_left; //Jumping to "restart_left:" defined above...
}
}
<<<<<<< HEAD
}
=======
}
>>>>>>> origin/master
| [
"[email protected]"
] | |
e1ba3a4a39733f01fae78acf7cc53cb86d29889e | 3ac59b74eef4ecf77acb4c35e739a7cbe3d19c51 | /phpdesktop-msie/msie/external_dispatch.cpp | 88a0103bf287d0503e88b7a3ff0ba367cfbbe4c8 | [] | no_license | sandeshg/madeforfrens-phpdesktop | ddd93fe34bdc772fdbb91c5a299db089c7223a48 | 9ef92370e300a9bc34b4725dd97c360606f673af | refs/heads/master | 2020-04-27T00:19:00.427574 | 2013-02-22T22:57:35 | 2013-02-22T22:57:35 | 32,137,887 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,884 | cpp | // Copyright (c) 2012-2013 PHP Desktop Authors. All rights reserved.
// License: New BSD License.
// Website: http://code.google.com/p/phpdesktop/
#include "../defines.h"
#include "external_dispatch.h"
#include "browser_window.h"
#include <MsHtmdid.h>
#include "../log.h"
#include "../debug.h"
#include "INITGUID.H"
// 30510406-98b5-11cf-bb82-00aa00bdce0b
DEFINE_GUID(IID_IMyUnknown1, 0x30510406, 0x98b5, 0x11cf,
0xbb, 0x82, 0x00, 0xaa, 0x00, 0xbd, 0xce, 0x0b);
// 9bcb0016-bc2a-47b7-8154-8580a15c3ff0
DEFINE_GUID(IID_IMyUnknown2, 0x9bcb0016, 0xbc2a, 0x47b7,
0x81, 0x54, 0x85, 0x80, 0xa1, 0x5c, 0x3f, 0xf0);
// 719c3050-f9d3-11cf-a493-00400523a8a0
DEFINE_GUID(IID_IMyUnknown3, 0x719c3050, 0xf9d3, 0x11cf,
0xa4, 0x93, 0x00, 0x40, 0x05, 0x23, 0xa8, 0xa0);
// a0aac450-a77b-11cf-91d0-00aa00c14a7c
DEFINE_GUID(IID_IMyUnknown4, 0xa0aac450, 0xa77b, 0x11cf,
0x91, 0xd0, 0x00, 0xaa, 0x00, 0xc1, 0x4a, 0x7c);
ExternalDispatch::ExternalDispatch(BrowserWindow* inBrowserWindow)
: browserWindow_(inBrowserWindow) {
}
HRESULT STDMETHODCALLTYPE ExternalDispatch::QueryInterface(
/* [in] */ REFIID riid,
/* [out] */ void **ppvObject) {
// Asking for:
// 00000008-0000-0000-c000-000000000046 - IProxyManager
//
// a6ef9860-c720-11d0-9337-00a0c90dcaa9 - IDispatchEx
if (ppvObject == 0)
return E_POINTER;
if (riid == IID_IUnknown) {
*ppvObject = static_cast<IUnknown*>(this);
static bool logged = false;
if (!logged) {
LOG_DEBUG << "ExternalDispatch::QueryInterface(): IUnknown";
logged = true;
}
} else if (riid == IID_IDispatch) {
*ppvObject = static_cast<IDispatch*>(this);
static bool logged = false;
if (!logged) {
LOG_DEBUG << "ExternalDispatch::QueryInterface(): IUnknown";
logged = true;
}
} else if ( riid == IID_IProxyManager
|| riid == IID_IDispatchEx
|| riid == IID_IMyUnknown1
|| riid == IID_IMyUnknown2
|| riid == IID_IMyUnknown3
|| riid == IID_IMyUnknown4) {
*ppvObject = 0;
return E_NOINTERFACE;
} else {
if (FILELog::ReportingLevel() >= logDEBUG) {
char riid_name[128];
GUID_TO_CHAR(&riid, riid_name, _countof(riid_name));
LOG_DEBUG << "ExternalDispatch::QueryInterface(): "
"unknown interface, riid = " << riid_name;
}
*ppvObject = 0;
return E_NOINTERFACE;
}
return S_OK;
}
ULONG STDMETHODCALLTYPE ExternalDispatch::AddRef(void) {
return 1;
}
ULONG STDMETHODCALLTYPE ExternalDispatch::Release(void) {
return 1;
}
HRESULT STDMETHODCALLTYPE ExternalDispatch::GetTypeInfoCount(
/* [out] */ UINT *pctinfo) {
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE ExternalDispatch::GetTypeInfo(
/* [in] */ UINT iTInfo,
/* [in] */ LCID lcid,
/* [out] */ ITypeInfo **ppTInfo) {
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE ExternalDispatch::GetIDsOfNames(
/* [in] */ REFIID riid,
/* [in] */ LPOLESTR *rgszNames,
/* [in] */ UINT cNames,
/* [in] */ LCID lcid,
/* [out] */ DISPID *rgDispId) {
if (riid != IID_NULL)
return DISP_E_UNKNOWNINTERFACE;
if (cNames == 1) {
int id = browserWindow_->ExternalIdentifier(rgszNames[0]);
if (id) {
rgDispId[0] = id;
return S_OK;
}
}
for (UINT i = 0; i < cNames; i++) {
rgDispId[i] = DISPID_UNKNOWN;
}
return DISP_E_UNKNOWNNAME;
}
HRESULT STDMETHODCALLTYPE ExternalDispatch::Invoke(
/* [in] */ DISPID dispId,
/* [in] */ REFIID riid,
/* [in] */ LCID lcid,
/* [in] */ WORD wFlags,
/* [out][in] */ DISPPARAMS *pDispParams,
/* [out] */ VARIANT *pVarResult,
/* [out] */ EXCEPINFO *pExcepInfo,
/* [out] */ UINT *puArgErr) {
// When returning a result, you must check whether pVarResult
// is not NULL and initialize it using VariantInit(). If it's
// NULL then it doesn't expect a result.
if (riid != IID_NULL)
return DISP_E_UNKNOWNINTERFACE;
pExcepInfo = 0;
puArgErr = 0;
if (wFlags & (DISPATCH_PROPERTYGET | DISPATCH_PROPERTYPUT
| DISPATCH_PROPERTYPUTREF)) {
return DISP_E_MEMBERNOTFOUND;
}
if (wFlags & DISPATCH_METHOD) {
if (pDispParams->cArgs != 0) {
// Currently no support for arguments, only simple function
// call. See BrowserEvents2::Invoke() on how to fetch
// arguments or return a value.
return DISP_E_BADPARAMCOUNT;
}
if (browserWindow_->ExternalCall(dispId))
return S_OK;
}
return DISP_E_MEMBERNOTFOUND;
}
| [
"[email protected]"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.