blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
8895034b15beaffb89ed1093cf34e9be86e97424
b80aae3e7c99e6eb7b292f7197ecbc896a4ad16c
/liber_shader/lightmap_baker.cpp
83f1c17b70068d9df04e05e93082e618b7bc5700
[]
no_license
ElaraFX/OpenElara
8a132ac35d6dc8fe266ae7f5f03f2efcd3446534
7f414c6952186e27cb08ddd4d68109c36282a508
refs/heads/master
2020-04-12T03:55:36.770432
2018-08-29T08:23:07
2018-08-29T08:23:07
63,928,126
14
5
null
null
null
null
UTF-8
C++
false
false
18,182
cpp
/************************************************************************** * Copyright (C) 2016 Rendease Co., Ltd. * All rights reserved. * * This program is commercial software: you must not redistribute it * and/or modify it without written permission from Rendease Co., Ltd. * * 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 * End User License Agreement for more details. * * You should have received a copy of the End User License Agreement along * with this program. If not, see <http://www.rendease.com/licensing/> *************************************************************************/ #include <ei_shaderx.h> #include <ei_fixed_pool.h> #include <ei_pool.h> #include <vector> #define NODE_POOL_BANK_SIZE 4096 inline eiVector calc_tri_bary( eiScalar x, eiScalar y, eiVector a, eiVector b, eiVector c) { eiVector bary; eiVector p = ei_vector(x, y, 1.0f); a.z = b.z = c.z = 1.0f; const eiVector n = cross(b - a, c - a); const eiVector na = cross(c - b, p - b); const eiVector nb = cross(a - c, p - c); const eiVector nc = cross(b - a, p - a); const eiScalar nn = dot(n, n); bary.x = dot(n, na) / nn; bary.y = dot(n, nb) / nn; bary.z = dot(n, nc) / nn; return bary; } /** Utility for planar bounding box */ struct BBox2 { eiVector2 min; eiVector2 max; inline void init() { min = EI_BIG_SCALAR; max = -EI_BIG_SCALAR; } inline void setv(const eiVector & v) { min.x = v.x; min.y = v.y; max = min; } inline void setv(const eiVector2 & v) { min = v; max = v; } inline void addv(const eiVector & v) { if (min.x > v.x) { min.x = v.x; } if (max.x < v.x) { max.x = v.x; } if (min.y > v.y) { min.y = v.y; } if (max.y < v.y) { max.y = v.y; } } inline void addv(const eiVector2 & v) { if (min.x > v.x) { min.x = v.x; } if (max.x < v.x) { max.x = v.x; } if (min.y > v.y) { min.y = v.y; } if (max.y < v.y) { max.y = v.y; } } inline void addb(const BBox2 & b) { if (min.x > b.min.x) { min.x = b.min.x; } if (max.x < b.max.x) { max.x = b.max.x; } if (min.y > b.min.y) { min.y = b.min.y; } if (max.y < b.max.y) { max.y = b.max.y; } } inline eiBool contains(eiScalar x, eiScalar y) const { return ( x >= min.x && x <= max.x && y >= min.y && y <= max.y); } inline void extends(eiScalar rhs) { min.x -= rhs; min.y -= rhs; max.x += rhs; max.y += rhs; } }; /** Reference to the source triangle */ struct Triangle { eiVector v1, v2, v3; eiIndex poly_inst_index; eiIndex tri_index; }; /** Information of a planar intersection */ struct HitInfo { eiIndex poly_inst_index; eiIndex tri_index; eiVector bary, bary_dx, bary_dy; }; /** Options for building 2D quad BVH */ struct BuildOptions { ei_fixed_pool *node_pool; ei_pool *triangle_pool; eiUint max_size; eiUint max_depth; inline BuildOptions( ei_fixed_pool *_node_pool, ei_pool *_triangle_pool, eiUint _max_size, eiUint _max_depth) : node_pool(_node_pool), triangle_pool(_triangle_pool), max_size(_max_size), max_depth(_max_depth) { } }; /** A cached instance of polygon mesh */ struct PolyInstance { eiTag poly_inst_tag; eiTag poly_obj_tag; eiTag pos_list_tag; eiTag tri_list_tag; eiTag uv_list_tag; eiTag uv_idxs_tag; eiMatrix transform; eiVector2 uvScale; eiVector2 uvOffset; eiBool flipBakeNormal; eiScalar bakeRayBias; }; /** Options for 2D ray-tracing (rasterization) */ struct TraceOptions { PolyInstance *poly_insts; eiVector2 pixel_size; inline TraceOptions( PolyInstance *_poly_insts, const eiVector2 & _pixel_size) : poly_insts(_poly_insts), pixel_size(_pixel_size) { } }; /** Quad BVH node in 2D */ struct BVHNode { BVHNode *child[4]; BBox2 bbox; eiUint is_leaf; eiUint num_triangles; Triangle *triangles; inline void init() { for (eiUint i = 0; i < 4; ++i) { child[i] = NULL; } bbox.init(); is_leaf = EI_TRUE; num_triangles = 0; triangles = NULL; } inline void subdiv( const BuildOptions & opt, eiUint depth) { if (depth == opt.max_depth || num_triangles <= opt.max_size) { is_leaf = EI_TRUE; return; } is_leaf = EI_FALSE; eiVector2 split = (bbox.min + bbox.max) * 0.5f; eiUint triangle_count[4]; for (eiUint i = 0; i < 4; ++i) { triangle_count[i] = 0; child[i] = NULL; } for (eiUint i = 0; i < num_triangles; ++i) { const Triangle & tri = triangles[i]; BBox2 tri_bbox; tri_bbox.setv(tri.v1); tri_bbox.addv(tri.v2); tri_bbox.addv(tri.v3); eiVector2 centroid = (tri_bbox.min + tri_bbox.max) * 0.5f; if (centroid.x < split.x) { if (centroid.y < split.y) { ++ triangle_count[2]; } else { ++ triangle_count[1]; } } else { if (centroid.y < split.y) { ++ triangle_count[3]; } else { ++ triangle_count[0]; } } } for (eiUint i = 0; i < 4; ++i) { if (triangle_count[i] > 0) { child[i] = (BVHNode *)ei_fixed_pool_allocate(opt.node_pool); child[i]->init(); child[i]->num_triangles = triangle_count[i]; child[i]->triangles = (Triangle *)ei_pool_allocate(opt.triangle_pool, sizeof(Triangle) * triangle_count[i]); triangle_count[i] = 0; } } for (eiUint i = 0; i < num_triangles; ++i) { const Triangle & tri = triangles[i]; BBox2 tri_bbox; tri_bbox.setv(tri.v1); tri_bbox.addv(tri.v2); tri_bbox.addv(tri.v3); eiVector2 centroid = (tri_bbox.min + tri_bbox.max) * 0.5f; if (centroid.x < split.x) { if (centroid.y < split.y) { child[2]->bbox.addb(tri_bbox); child[2]->triangles[triangle_count[2]] = tri; ++ triangle_count[2]; } else { child[1]->bbox.addb(tri_bbox); child[1]->triangles[triangle_count[1]] = tri; ++ triangle_count[1]; } } else { if (centroid.y < split.y) { child[3]->bbox.addb(tri_bbox); child[3]->triangles[triangle_count[3]] = tri; ++ triangle_count[3]; } else { child[0]->bbox.addb(tri_bbox); child[0]->triangles[triangle_count[0]] = tri; ++ triangle_count[0]; } } } if (triangles != NULL) { ei_pool_free(opt.triangle_pool, triangles); num_triangles = 0; triangles = NULL; } if (child[0] != NULL) { child[0]->subdiv( opt, depth + 1); } if (child[1] != NULL) { child[1]->subdiv( opt, depth + 1); } if (child[2] != NULL) { child[2]->subdiv( opt, depth + 1); } if (child[3] != NULL) { child[3]->subdiv( opt, depth + 1); } } inline eiBool intersect( TraceOptions & opt, eiScalar x, eiScalar y, HitInfo & hit) { if (is_leaf) { for (eiUint i = 0; i < num_triangles; ++i) { const Triangle & tri = triangles[i]; const eiVector & v1 = tri.v1; const eiVector & v2 = tri.v2; const eiVector & v3 = tri.v3; const eiScalar det = (v2.y - v3.y) * (v1.x - v3.x) + (v3.x - v2.x) * (v1.y - v3.y); if (det == 0.0f) { continue; } const eiScalar b1 = ((v2.y - v3.y) * (x - v3.x) + (v3.x - v2.x) * (y - v3.y)) / det; if (b1 < 0.0f || b1 > 1.0f) { continue; } const eiScalar b2 = ((v3.y - v1.y) * (x - v3.x) + (v1.x - v3.x) * (y - v3.y)) / det; if (b2 < 0.0f || b2 > 1.0f) { continue; } const eiScalar b3 = 1.0f - b1 - b2; if (b3 < 0.0f || b3 > 1.0f) { continue; } hit.poly_inst_index = tri.poly_inst_index; hit.tri_index = tri.tri_index; hit.bary = ei_vector(b1, b2, b3); hit.bary_dx = calc_tri_bary(x + opt.pixel_size.x, y, v1, v2, v3); hit.bary_dy = calc_tri_bary(x, y + opt.pixel_size.y, v1, v2, v3); return EI_TRUE; } } else { if (child[0] != NULL && child[0]->bbox.contains(x, y)) { if (child[0]->intersect(opt, x, y, hit)) { return EI_TRUE; } } if (child[1] != NULL && child[1]->bbox.contains(x, y)) { if (child[1]->intersect(opt, x, y, hit)) { return EI_TRUE; } } if (child[2] != NULL && child[2]->bbox.contains(x, y)) { if (child[2]->intersect(opt, x, y, hit)) { return EI_TRUE; } } if (child[3] != NULL && child[3]->bbox.contains(x, y)) { if (child[3]->intersect(opt, x, y, hit)) { return EI_TRUE; } } } return EI_FALSE; } }; /** Serves as the intersector for UV space geometry */ struct LightmapGlobals { eiDataTableAccessor<eiTag> poly_insts_accessor; std::vector<PolyInstance> poly_insts; const char *uv_name; eiVector2 bbox_min, bbox_max; eiScalar ray_bias; BVHNode *root_node; ei_fixed_pool node_pool; ei_pool triangle_pool; eiUint max_size, max_depth; eiInt res_x, res_y; inline LightmapGlobals( eiTag poly_insts_tag, const char *_uv_name, eiScalar _ray_bias, eiUint _max_size, eiUint _max_depth) : poly_insts_accessor(poly_insts_tag), uv_name(_uv_name), ray_bias(_ray_bias), max_size(_max_size), max_depth(_max_depth), res_x(1), res_y(1) { ei_fixed_pool_init(&node_pool, sizeof(BVHNode), NODE_POOL_BANK_SIZE); ei_pool_init(&triangle_pool); std::string uv_name_idx(uv_name); uv_name_idx += "_idx"; poly_insts.resize(poly_insts_accessor.size()); for (eiInt i = 0; i < poly_insts_accessor.size(); ++i) { eiTag poly_inst_tag = poly_insts_accessor.get(i); eiDataAccessor<eiNode> poly_inst(poly_inst_tag); eiTag poly_obj_tag = ei_node_get_node(poly_inst.get(), ei_node_find_param(poly_inst.get(), "element")); eiDataAccessor<eiNode> poly_obj(poly_obj_tag); eiTag pos_list_tag = ei_node_get_array(poly_obj.get(), ei_node_find_param(poly_obj.get(), "pos_list")); eiTag tri_list_tag = ei_node_get_array(poly_obj.get(), ei_node_find_param(poly_obj.get(), "triangle_list")); eiTag uv_list_tag = ei_node_get_array(poly_obj.get(), ei_node_find_param(poly_obj.get(), uv_name)); eiTag uv_idxs_tag = ei_node_get_array(poly_obj.get(), ei_node_find_param(poly_obj.get(), uv_name_idx.c_str())); const eiMatrix & transform = (*ei_node_get_matrix(poly_inst.get(), ei_node_find_param(poly_inst.get(), "transform"))); poly_insts[i].poly_inst_tag = poly_inst_tag; poly_insts[i].poly_obj_tag = poly_obj_tag; poly_insts[i].pos_list_tag = pos_list_tag; poly_insts[i].tri_list_tag = tri_list_tag; poly_insts[i].uv_list_tag = uv_list_tag; poly_insts[i].uv_idxs_tag = uv_idxs_tag; poly_insts[i].uvScale = 1.0f; poly_insts[i].uvOffset = 0.0f; poly_insts[i].flipBakeNormal = EI_FALSE; poly_insts[i].bakeRayBias = 0.0f; eiIndex uvScale_pid = ei_node_find_param(poly_inst.get(), "uvScale"); if (uvScale_pid != EI_NULL_INDEX) { poly_insts[i].uvScale = *ei_node_get_vector2(poly_inst.get(), uvScale_pid); } eiIndex uvOffset_pid = ei_node_find_param(poly_inst.get(), "uvOffset"); if (uvOffset_pid != EI_NULL_INDEX) { poly_insts[i].uvOffset = *ei_node_get_vector2(poly_inst.get(), uvOffset_pid); } eiIndex flipBakeNormal_pid = ei_node_find_param(poly_inst.get(), "flipBakeNormal"); if (flipBakeNormal_pid != EI_NULL_INDEX) { poly_insts[i].flipBakeNormal = ei_node_get_bool(poly_inst.get(), flipBakeNormal_pid); } eiIndex bakeRayBias_pid = ei_node_find_param(poly_inst.get(), "bakeRayBias"); if (bakeRayBias_pid != EI_NULL_INDEX) { poly_insts[i].bakeRayBias = ei_node_get_scalar(poly_inst.get(), bakeRayBias_pid); } poly_insts[i].transform = transform; } } inline ~LightmapGlobals() { ei_fixed_pool_clear(&node_pool); ei_pool_clear(&triangle_pool); } inline void reset() { ei_fixed_pool_clear(&node_pool); ei_pool_clear(&triangle_pool); ei_fixed_pool_init(&node_pool, sizeof(BVHNode), NODE_POOL_BANK_SIZE); ei_pool_init(&triangle_pool); } inline void subdiv(eiScalar pixel_padding) { eiUint num_vertices = 0; eiUint num_triangles = 0; for (size_t i = 0; i < poly_insts.size(); ++i) { const PolyInstance & poly_inst = poly_insts[i]; eiDataTableAccessor<eiVector> uv_list(poly_inst.uv_list_tag); eiDataTableAccessor<eiIndex> uv_idxs(poly_inst.uv_idxs_tag); eiUint cur_vertices = (eiUint)uv_list.size(); eiUint cur_triangles = (eiUint)uv_idxs.size() / 3; num_vertices += cur_vertices; num_triangles += cur_triangles; } root_node = (BVHNode *)ei_fixed_pool_allocate(&node_pool); root_node->init(); if (num_vertices > 0 && num_triangles > 0) { root_node->num_triangles = num_triangles; root_node->triangles = (Triangle *)ei_pool_allocate(&triangle_pool, sizeof(Triangle) * num_triangles); eiUint triangle_offset = 0; for (eiInt i = 0; i < poly_insts.size(); ++i) { const PolyInstance & poly_inst = poly_insts[i]; eiVector2 uvScale = poly_inst.uvScale; eiVector2 uvOffset = poly_inst.uvOffset; eiDataTableAccessor<eiVector> uv_list(poly_inst.uv_list_tag); eiDataTableAccessor<eiIndex> uv_idxs(poly_inst.uv_idxs_tag); eiUint cur_vertices = (eiUint)uv_list.size(); eiUint cur_triangles = (eiUint)uv_idxs.size() / 3; std::vector<eiVector> conservative_uv_list(cur_vertices); for (eiUint j = 0; j < cur_vertices; ++j) { eiVector & v = uv_list.get(j); v.x *= uvScale[0]; v.y *= uvScale[1]; v.x += uvOffset[0]; v.y += uvOffset[1]; conservative_uv_list[j] = v; } for (eiUint j = 0; j < cur_triangles; ++j) { eiIndex i1 = uv_idxs.get(j * 3 + 0); eiIndex i2 = uv_idxs.get(j * 3 + 1); eiIndex i3 = uv_idxs.get(j * 3 + 2); eiVector v1 = uv_list.get(i1); eiVector v2 = uv_list.get(i2); eiVector v3 = uv_list.get(i3); eiVector normal = cross(v2 - v1, v3 - v1); eiVector d1 = normalize(cross(v2 - v1, normal)); eiVector d2 = normalize(cross(v3 - v2, normal)); eiVector d3 = normalize(cross(v1 - v3, normal)); conservative_uv_list[i1] += ((d3 + d1) * pixel_padding); conservative_uv_list[i2] += ((d1 + d2) * pixel_padding); conservative_uv_list[i3] += ((d2 + d3) * pixel_padding); } for (eiUint j = 0; j < cur_triangles; ++j) { Triangle & tri = root_node->triangles[triangle_offset + j]; eiIndex i1 = uv_idxs.get(j * 3 + 0); eiIndex i2 = uv_idxs.get(j * 3 + 1); eiIndex i3 = uv_idxs.get(j * 3 + 2); tri.v1 = conservative_uv_list[i1]; tri.v2 = conservative_uv_list[i2]; tri.v3 = conservative_uv_list[i3]; tri.poly_inst_index = i; tri.tri_index = j; } for (eiUint j = 0; j < cur_vertices; ++j) { eiVector & v = conservative_uv_list[j]; root_node->bbox.addv(v); } triangle_offset += cur_triangles; } BuildOptions opt( &node_pool, &triangle_pool, max_size, max_depth); root_node->subdiv(opt, 1); } } }; /** Built-in lens shader for baking lightmaps */ lens (lightmap_baker) enum { e_poly_instances = 0, e_uv_name, e_ray_bias, e_pixel_padding, e_max_size, e_max_depth, }; static void parameters() { declare_array(poly_instances, EI_TYPE_TAG_NODE, EI_NULL_TAG); declare_token(uv_name, "uv1"); declare_scalar(ray_bias, 0.0001f); declare_scalar(pixel_padding, 0.5f); declare_int(max_size, 10); declare_int(max_depth, 30); } static void init() { } static void exit() { } void init_node() { glob = NULL; eiTag poly_insts_tag = eval_array(poly_instances); eiToken uv_name = eval_token(uv_name); eiScalar ray_bias = eval_scalar(ray_bias); eiUint max_size = (eiUint)eval_int(max_size); eiUint max_depth = (eiUint)eval_int(max_depth); if (poly_insts_tag != EI_NULL_TAG && uv_name.str != NULL) { glob = new LightmapGlobals( poly_insts_tag, uv_name.str, ray_bias, max_size, max_depth); } } void exit_node() { if (glob != NULL) { delete ((LightmapGlobals *)glob); glob = NULL; } } eiBool support( eiNode *cam, eiInt feature, void *feature_params) { return (feature != EI_FEATURE_VIEWDEP_DISPLACEMENT); } eiBool object_to_screen( eiNode *cam, eiVector *rpos, const eiVector *opos, const eiMatrix *object_to_view) { return EI_FALSE; } void update_world_bbox( eiNode *cam, const eiBBox *world_bbox) { LightmapGlobals *g = (LightmapGlobals *)glob; if (g == NULL) { return; } g->res_x = ei_node_get_int(cam, EI_CAMERA_res_x); g->res_y = ei_node_get_int(cam, EI_CAMERA_res_y); eiScalar pixel_padding = eval_scalar(pixel_padding); pixel_padding /= (eiScalar)min(g->res_x, g->res_y); g->reset(); g->subdiv(pixel_padding); } eiBool generate_ray( eiNode *cam, eiCameraOutput *out) { LightmapGlobals *g = (LightmapGlobals *)glob; if (g == NULL) { return EI_FALSE; } eiVector2 raster = raster_pos(); raster.x = clamp(raster.x / (eiScalar)g->res_x, 0.0f, 1.0f); raster.y = clamp(1.0f - raster.y / (eiScalar)g->res_y, 0.0f, 1.0f); eiVector2 pixel_size = ei_vector2(1.0f / (eiScalar)g->res_x, 1.0f / (eiScalar)g->res_y); TraceOptions opt(&(g->poly_insts[0]), pixel_size); HitInfo hit; if (!g->root_node->intersect(opt, raster.x, raster.y, hit)) { return EI_FALSE; } const PolyInstance & poly_inst = opt.poly_insts[hit.poly_inst_index]; eiDataTableAccessor<eiVector> pos_list(poly_inst.pos_list_tag); eiDataTableAccessor<eiIndex> tri_list(poly_inst.tri_list_tag); eiIndex wi0 = tri_list.get(hit.tri_index * 3 + 0); eiIndex wi1 = tri_list.get(hit.tri_index * 3 + 1); eiIndex wi2 = tri_list.get(hit.tri_index * 3 + 2); const eiMatrix & transform = poly_inst.transform; eiVector w0 = point_transform(pos_list.get(wi0), transform); eiVector w1 = point_transform(pos_list.get(wi1), transform); eiVector w2 = point_transform(pos_list.get(wi2), transform); eiVector wPos = hit.bary.x * w0 + hit.bary.y * w1 + hit.bary.z * w2; eiVector wNormal = normalize(cross(w1 - w0, w2 - w0)); if (poly_inst.flipBakeNormal) { wNormal = -wNormal; } out->E = wPos + wNormal * max(g->ray_bias, poly_inst.bakeRayBias); out->dEdx = (hit.bary_dx.x * w0 + hit.bary_dx.y * w1 + hit.bary_dx.z * w2) - wPos; out->dEdy = (hit.bary_dy.x * w0 + hit.bary_dy.y * w1 + hit.bary_dy.z * w2) - wPos; out->I = -wNormal; return EI_TRUE; } end_lens (lightmap_baker)
[ "43492276@qq.com" ]
43492276@qq.com
e2bcee7651bbb080d1eb4dadc74569a9878bfdf9
f6582741d4999660850606c11d7299476bff74cc
/example/engines/mock.h
bda5aaf4e85186b0cda2bb30912949e23193ce3f
[]
no_license
mezdej/cpp
6f72faf02a7e8a4c35607003ebd170281829f8cb
89856d3872864d1cbc78b69624da95cc24daf378
refs/heads/master
2021-06-10T20:03:55.789827
2021-04-06T19:39:46
2021-04-06T19:39:46
172,216,990
1
0
null
null
null
null
UTF-8
C++
false
false
523
h
#ifndef INTERFACE_MOCK_HEADER #define INTERFACE_MOCK_HEADER #pragma once #include "interface.h" namespace example { namespace engine { class Mock : public Interface { public: Mock( const string & endpoint, const string & login, const string & password ); virtual void getDevices( Device::Map & result, set<Device::Type> types = {} ) override; virtual RefreshResult refreshStates( Device::Map & devices ) override; private: string endpoint; string login; string password; }; } } #endif
[ "mezdej@wp.pl" ]
mezdej@wp.pl
5c41d5f363892445022f714e99a071997f137224
c6fa53212eb03017f9e72fad36dbf705b27cc797
/RecoParticleFlow/PFClusterProducer/plugins/energy_calcs/PFClusterEMEnergyCorrector.cc
3cf5b565c3544e57d14f8dfd1f955ac9abd0616a
[]
no_license
gem-sw/cmssw
a31fc4ef2233b2157e1e7cbe9a0d9e6c2795b608
5893ef29c12b2718b3c1385e821170f91afb5446
refs/heads/CMSSW_6_2_X_SLHC
2022-04-29T04:43:51.786496
2015-12-16T16:09:31
2015-12-16T16:09:31
12,892,177
2
4
null
2018-11-22T13:40:31
2013-09-17T10:10:26
C++
UTF-8
C++
false
false
1,225
cc
#include "RecoParticleFlow/PFClusterProducer/interface/PFClusterEMEnergyCorrector.h" namespace { typedef reco::PFCluster::EEtoPSAssociation::value_type EEPSPair; bool sortByKey(const EEPSPair& a, const EEPSPair& b) { return a.first < b.first; } } void PFClusterEMEnergyCorrector:: correctEnergyActual(reco::PFCluster& cluster, unsigned idx) const { std::vector<double> ps1_energies,ps2_energies; double ePS1=0, ePS2=0; if( cluster.layer() == PFLayer::ECAL_ENDCAP && _assoc ) { auto ee_key_val = std::make_pair(idx,edm::Ptr<reco::PFCluster>()); const auto clustops = std::equal_range(_assoc->begin(), _assoc->end(), ee_key_val, sortByKey); for( auto i_ps = clustops.first; i_ps != clustops.second; ++i_ps) { edm::Ptr<reco::PFCluster> psclus(i_ps->second); switch( psclus->layer() ) { case PFLayer::PS1: ps1_energies.push_back(psclus->energy()); break; case PFLayer::PS2: ps2_energies.push_back(psclus->energy()); break; default: break; } } } const double eCorr= _calibrator->energyEm(cluster, ps1_energies,ps2_energies, ePS1,ePS2, _applyCrackCorrections); cluster.setCorrectedEnergy(eCorr); }
[ "bachtis@cern.ch" ]
bachtis@cern.ch
509d16740e5dd56e618023ccb66b42022089d106
fcdea24e6466d4ec8d7798555358a9af8acf9b35
/Tools/XEditor/XEditor.cpp
afc5c5b233c32aa32b3c89640f381ef2e113813b
[]
no_license
yingzhang536/mrayy-Game-Engine
6634afecefcb79c2117cecf3e4e635d3089c9590
6b6fcbab8674a6169e26f0f20356d0708620b828
refs/heads/master
2021-01-17T07:59:30.135446
2014-11-30T16:10:54
2014-11-30T16:10:54
27,630,181
2
0
null
null
null
null
UTF-8
C++
false
false
3,162
cpp
// XEditor.cpp : Defines the class behaviors for the application. // #include "stdafx.h" #include "XEditor.h" #include "MainFrm.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CXEditorApp BEGIN_MESSAGE_MAP(CXEditorApp, CWinApp) ON_COMMAND(ID_APP_ABOUT, &CXEditorApp::OnAppAbout) END_MESSAGE_MAP() // CXEditorApp construction CXEditorApp::CXEditorApp() { // TODO: add construction code here, // Place all significant initialization in InitInstance } // The one and only CXEditorApp object CXEditorApp theApp; // CXEditorApp initialization BOOL CXEditorApp::InitInstance() { // InitCommonControlsEx() is required on Windows XP if an application // manifest specifies use of ComCtl32.dll version 6 or later to enable // visual styles. Otherwise, any window creation will fail. INITCOMMONCONTROLSEX InitCtrls; InitCtrls.dwSize = sizeof(InitCtrls); // Set this to include all the common control classes you want to use // in your application. InitCtrls.dwICC = ICC_WIN95_CLASSES; InitCommonControlsEx(&InitCtrls); CWinApp::InitInstance(); // Initialize OLE libraries if (!AfxOleInit()) { AfxMessageBox(IDP_OLE_INIT_FAILED); return FALSE; } AfxEnableControlContainer(); // Standard initialization // If you are not using these features and wish to reduce the size // of your final executable, you should remove from the following // the specific initialization routines you do not need // Change the registry key under which our settings are stored // TODO: You should modify this string to be something appropriate // such as the name of your company or organization SetRegistryKey(_T("Local AppWizard-Generated Applications")); // To create the main window, this code creates a new frame window // object and then sets it as the application's main window object CMainFrame* pFrame = new CMainFrame; if (!pFrame) return FALSE; m_pMainWnd = pFrame; // create and load the frame with its resources pFrame->LoadFrame(IDR_MAINFRAME, WS_OVERLAPPEDWINDOW | FWS_ADDTOTITLE, NULL, NULL); // The one and only window has been initialized, so show and update it pFrame->ShowWindow(SW_SHOW); pFrame->UpdateWindow(); // call DragAcceptFiles only if there's a suffix // In an SDI app, this should occur after ProcessShellCommand return TRUE; } // CXEditorApp message handlers // CAboutDlg dialog used for App About class CAboutDlg : public CDialog { public: CAboutDlg(); // Dialog Data enum { IDD = IDD_ABOUTBOX }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support // Implementation protected: DECLARE_MESSAGE_MAP() public: CXTColorPicker OkBtn; }; CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Control(pDX, IDOK, OkBtn); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) END_MESSAGE_MAP() // App command to run the dialog void CXEditorApp::OnAppAbout() { CAboutDlg aboutDlg; aboutDlg.DoModal(); } // CXEditorApp message handlers
[ "mrayyamen@gmail.com" ]
mrayyamen@gmail.com
10fe1f6f95ea3ac57925122ae02116390099d604
625752aa8b7bda45524a8999f7a51a3610c0056c
/dev/g++/projects/embedded/gps/src/nmea2000.cpp
18443431107d149f797e98d77ae62f5b248fc4ee
[ "MIT" ]
permissive
PT0140PT0141/repo
f42e16b017fb37738b917224d9c94fc038387731
bcbab5212ec6eec3e4a03932a0826fc327732b1b
refs/heads/master
2021-04-30T17:25:51.820010
2017-01-09T08:58:53
2017-01-09T08:58:53
80,207,200
0
0
null
2017-01-27T12:53:50
2017-01-27T12:53:50
null
UTF-8
C++
false
false
13,074
cpp
/** * @File nmea2000.h * @brief Implementation file for the lightweight nmea2000 library. * @author garciay.yann@gmail.com * @copyright Copyright (c) 2015 ygarcia. All rights reserved * @license This project is released under the MIT License * @version 0.1 */ #include <iostream> #include <sstream> #include <cstring> // Used for std::strerror #include "nmea2000.h" namespace gps { namespace parsers { std::string nmea2000::cmd_pattern( "\\$GP([[:alpha:]]{3})," "(.*)" "\r\n$" ); std::string nmea2000::gga_pattern( "([[:digit:]]+\\.[[:digit:]]+){0,1}," // UTC time of the fix: hhmmssdd "([[:digit:]]+\\.[[:digit:]]+){0,1}," // Latitude coordinates: xxmm.dddd "([NS]){0,1}," // North or South "([[:digit:]]+\\.[[:digit:]]+){0,1}," // Longitude coordinates: yyymm.dddd "([WE]){0,1}," // West or Est "([[:digit:]]*)," // Fix valid indicator (0=no fix, 1=GPS fix, 2=Dif. GPS fix) "([[:digit:]]*)," // Number of satellites in use: ss "([[:digit:]]+\\.[[:digit:]]+){0,1}," // Horizontal dilution of precision: d.d "([[:digit:]]+\\.[[:digit:]]+){0,1}," // Antenna altitude above mean-sea-level: h.h "([M]){0,1}," // Units of antenna altitude, meters "([[:digit:]]+\\.[[:digit:]]+){0,1}," // Difference between the WGS-84 reference ellipsoid surface and the mean-sea-level altitude: g.g "([M]){0,1}," // Units of geoidal separation, meters "([[:digit:]]+\\.[[:digit:]]+){0,1}," // Age of Differential GPS data (seconds) "([[:xdigit:]]*)\\*([[:xdigit:]]{2})" // Checksum ); std::string nmea2000::rmc_pattern( "([[:digit:]]+\\.[[:digit:]]+){0,1}," // Fix taken UTC time: hhmmss.dd "([AV]){0,1}," // Status: Data Active or V (void) "([[:digit:]]+\\.[[:digit:]]+){0,1}," // Latitude coordinate: xxmm.dddd "([NS]){0,1}," // North or South "([[:digit:]]+\\.[[:digit:]]+){0,1}," // Longitude coordinate: yyymm.dddd "([WE]){0,1}," // West or Est "([[:digit:]]+\\.[[:digit:]]+){0,1}," // Speed over the ground in knots: s.s "([[:digit:]]+\\.[[:digit:]]+){0,1}," // Heading: h.h "([[:digit:]]+){0,1}," // UTC Date of the fix: ddmmyy "([[:digit:]]+\\.[[:digit:]]+){0,1}," // Magnetic Variation: d.d "([WE]){0,1}," // Direction of magnetic variation: West or Est "([[:xdigit:]]*)\\*([[:xdigit:]]{2})" // Checksum ); nmea2000::nmea2000() : gps_parser(), _buffer(), _result_code(0), _error_msg(), _regex_command(), _matches(NULL), _regex_gga(), _regex_rmc() { // Compile regular expressions if (regcomp(&_regex_command, nmea2000::cmd_pattern.c_str(), REG_EXTENDED | REG_NEWLINE) != 0) { std::ostringstream os; os << "nmea2000::nmea2000: Could not compile command regex: " << std::strerror(errno) << std::endl; throw new std::runtime_error(os.str()); } if (regcomp(&_regex_gga, nmea2000::gga_pattern.c_str(), REG_EXTENDED | REG_NEWLINE) != 0) { std::ostringstream os; os << "nmea2000::nmea2000: Could not compile GGA regex: " << std::strerror(errno) << std::endl; throw new std::runtime_error(os.str()); } if (regcomp(&_regex_rmc, nmea2000::rmc_pattern.c_str(), REG_EXTENDED | REG_NEWLINE) != 0) { std::ostringstream os; os << "nmea2000::nmea2000: Could not compile RMC regex: " << std::strerror(errno) << std::endl; throw new std::runtime_error(os.str()); } } // End of Constructor const int32_t nmea2000::process(const std::vector<uint8_t> & p_gps_frame) { // Sanity check if (p_gps_frame.size() == 0) { // Nothing to do return 0; } // Append to the buffer _buffer.append(std::string(p_gps_frame.begin(), p_gps_frame.end())); // Process current buffer return process_buffer(); } const int32_t nmea2000::process(const std::string & p_gps_frame) { // Sanity check if (p_gps_frame.empty()) { // Nothing to do return 0; } // Reset current values for (std::map<uint8_t, std::string>::iterator it = _values.begin(); it != _values.end(); ++it) { it->second.assign(""); } // End of 'for' statement // Append to the buffer _buffer.append(p_gps_frame); // Process current buffer return process_buffer(); } const int32_t nmea2000::process_buffer() { // std::clog << ">>> nmea2000::process_buffer" << std::endl; // std::clog << "nmea2000::process: current buffer: '" << _buffer << "'" << std::endl; size_t start_command = _buffer.find("$"); size_t end_command = _buffer.find("\r\n"); // Validate the content of the buffer if (start_command == std::string::npos) { // std::clog << "Clear buffer" << std::endl; _buffer.clear(); // No valid command into the buffer return 0; } else if (end_command == std::string::npos) { if (start_command != 0) { _buffer = _buffer.substr(start_command); // std::clog << "New buffer(0): '" << _buffer << "'" << std::endl; } else { size_t reverse_start_command = _buffer.rfind("$"); if (reverse_start_command != start_command) { _buffer = _buffer.substr(reverse_start_command); // std::clog << "New buffer(1): '" << _buffer << "'" << std::endl; } else { // std::clog << "Nothing to do" << std::endl; } } return 0; } else if (end_command < start_command) { // Remove invalid part _buffer = _buffer.substr(end_command + 2); // std::clog << "New buffer(2): '" << _buffer << "'" << std::endl; start_command = _buffer.find("$"); end_command = _buffer.find("\r\n"); } if (end_command != std::string::npos) { // Extract the line from the buffer std::string line = _buffer.substr(start_command, end_command + 2); // std::clog << "New command: '" << line << "'" << std::endl; _buffer = _buffer.substr(end_command + 2); // std::clog << "New buffer: '" << _buffer << "'" << std::endl; // Extract the command _matches = (regmatch_t *)new uint8_t[sizeof(regmatch_t) * (1 + _regex_command.re_nsub)]; if ((_result_code = regexec(&_regex_command, line.c_str(), 1 + _regex_command.re_nsub, _matches, 0)) != 0) { delete [] _matches; regerror(_result_code, &_regex_command, _error_msg, sizeof(_error_msg)); std::cerr << "nmea2000::process: regexec command failed: " << _error_msg << std::endl; return -1; } if (_matches->rm_eo != -1) { // Matching std::string cmd; char *pstr = (char *)line.c_str(); size_t match_len = (_matches + 1)->rm_eo - (_matches + 1)->rm_so; cmd.assign(pstr + (_matches + 1)->rm_so, match_len); // std::clog << "nmea2000::process: cmd = '" << cmd << "'" << std::endl; std::string payload = line.substr((_matches + 2)->rm_so); // std::clog << "payload ='" << payload << "'" << std::endl; delete [] _matches; // Process the command if (cmd.compare("GGA") == 0) { return process_gga(payload); } else if (cmd.compare("RMC") == 0) { return process_rmc(payload); } else { // Unsupported command // std::cerr << "Unsupported NMEA command='" << cmd << "'" << std::endl; return -1; } } else { delete [] _matches; } } else if (_buffer.length() >= 2048) { _buffer.clear(); } return -1; } // End of method process const int32_t nmea2000::process_gga(const std::string & p_gps_frame) { // Extract fields _matches = (regmatch_t *)new uint8_t[sizeof(regmatch_t) * (1 + _regex_gga.re_nsub)]; if ((_result_code = regexec(&_regex_gga, p_gps_frame.c_str(), 1 + _regex_gga.re_nsub, _matches, 0)) != 0) { delete [] _matches; regerror(_result_code, &_regex_gga, _error_msg, sizeof(_error_msg)); std::cerr << "nmea2000::process_gga: regexec GGA failed: " << _error_msg << std::endl; return -1; } // Match // std::cout << "nmea2000::process_gga: # of matching items: " << _matches->rm_eo << std::endl; // 1. Extract data if (_matches->rm_eo != -1) { // Matching std::string str, ind; char *pstr = (char *)p_gps_frame.c_str(); /* // UTC time size_t match_len = (_matches + 1)->rm_eo - (_matches + 1)->rm_so; str.assign(pstr + (_matches + 1)->rm_so, match_len); std::cout << "nmea2000::process_gga: utcTime = '" << str << "'" << std::endl; // Update UTC time //_values[utc_time_idx] = std::stof(); // UTC of position // Latitude coordinate. match_len = (_matches + 2)->rm_eo - (_matches + 2)->rm_so; str.assign(pstr + (_matches + 2)->rm_so, match_len); match_len = (_matches + 3)->rm_eo - (_matches + 3)->rm_so; ind.assign(pstr + (_matches + 3)->rm_so, match_len); std::cout << "nmea2000::process_gga: Latitude coordinate = '" << str << " " << ind << "'" << std::endl; _values[latitude_idx] = ind + str; // Longitude coordinate. match_len = (_matches + 4)->rm_eo - (_matches + 4)->rm_so; str.assign(pstr + (_matches + 4)->rm_so, match_len); match_len = (_matches + 5)->rm_eo - (_matches + 5)->rm_so; ind.assign(pstr + (_matches + 5)->rm_so, match_len); std::cout << "nmea2000::process_gga: Longitude coordinate = '" << str << " " << ind << "'" << std::endl; _values[longitude_idx] = ind + str; */ // Altitude. size_t match_len = (_matches + 9)->rm_eo - (_matches + 9)->rm_so; str.assign(pstr + (_matches + 9)->rm_so, match_len); // std::cout << "nmea2000::process_gga: Altitude = '" << str << "'" << std::endl; _values[altitude_idx].assign(str); delete [] _matches; } // no matches return 0; } // End of method process_gga const int32_t nmea2000::process_rmc(const std::string & p_gps_frame) { // Extract fields _matches = (regmatch_t *)new uint8_t[sizeof(regmatch_t) * (1 + _regex_rmc.re_nsub)]; if ((_result_code = regexec(&_regex_rmc, p_gps_frame.c_str(), 1 + _regex_rmc.re_nsub, _matches, 0)) != 0) { regerror(_result_code, &_regex_rmc, _error_msg, sizeof(_error_msg)); delete [] _matches; std::cerr << "nmea2000::process_rmc: regexec RMC failed: " << _error_msg << std::endl; return -1; } // Match // std::cout << "nmea2000::process_rmc: # of matching items: " << _matches->rm_eo << std::endl; // 1. Extract data if (_matches->rm_eo != -1) { // Matching std::string str, ind; char *pstr = (char *)p_gps_frame.c_str(); // Status indicator size_t match_len = (_matches + 2)->rm_eo - (_matches + 2)->rm_so; ind.assign(pstr + (_matches + 2)->rm_so, match_len); // std::cout << "nmea2000::process_rmc: Valid data = '" << ind << "'" << std::endl; if (ind.compare("A") == 0) { // Valida data, std::ostringstream os; // Update UTC time match_len = (_matches + 1)->rm_eo - (_matches + 1)->rm_so; str.assign(pstr + (_matches + 1)->rm_so, match_len); // std::cout << "nmea2000::process_rmc: utcTime = '" << str << "'" << std::endl; _values[utc_time_idx] = str; // UTC of position // Latitude coordinate. match_len = (_matches + 3)->rm_eo - (_matches + 3)->rm_so; str.assign(pstr + (_matches + 3)->rm_so, match_len); match_len = (_matches + 4)->rm_eo - (_matches + 4)->rm_so; ind.assign(pstr + (_matches + 4)->rm_so, match_len); os << str << " " << ind; _values[latitude_idx] = os.str(); // Latitude // std::cout << "nmea2000::process_rmc: Latitude coordinate = '" << _values[latitude_idx] << "'" << std::endl; // Longitude coordinate. match_len = (_matches + 5)->rm_eo - (_matches + 5)->rm_so; str.assign(pstr + (_matches + 5)->rm_so, match_len); match_len = (_matches + 6)->rm_eo - (_matches + 6)->rm_so; ind.assign(pstr + (_matches + 6)->rm_so, match_len); os.str(""); os << str << " " << ind; _values[longitude_idx] = os.str(); // Longitude // std::cout << "nmea2000::process_rmc: Longitude coordinate = '" << _values[longitude_idx] << "'" << std::endl; // Speed. match_len = (_matches + 7)->rm_eo - (_matches + 7)->rm_so; str.assign(pstr + (_matches + 7)->rm_so, match_len); // std::cout << "nmea2000::process_rmc: Speed = '" << str << "'" << std::endl; _values[speed_idx] = str; // Speed // Heading. match_len = (_matches + 8)->rm_eo - (_matches + 8)->rm_so; str.assign(pstr + (_matches + 8)->rm_so, match_len); // std::cout << "nmea2000::process_rmc: Heading = '" << str << "'" << std::endl; _values[heading_idx] = str; // Heading. // Date match_len = (_matches + 9)->rm_eo - (_matches + 9)->rm_so; str.assign(pstr + (_matches + 9)->rm_so, match_len); os.str(""); os << str << " " << _values[utc_time_idx]; _values[utc_time_idx] = os.str(); // std::cout << "nmea2000::process_rmc: UTC date/time = '" << _values[utc_time_idx] << "'" << std::endl; } // else, discard the frame delete [] _matches; } // no matches return 0; } // End of method process_rmc } // End of namespace parsers } // End of namespace gps
[ "garcia.yann@gmail.com" ]
garcia.yann@gmail.com
566fe9c84c94a2cf9a70b44342a4fae90a9b0786
d956e1eac80a0b739e650eac4eaded3d06027b26
/DeshBz.h
f37a82d956f2caadea30e4821d444647650cf930
[]
no_license
Justliangzhu/gitskills
b42457126a945986bad62b84bc9cb21382efb10d
957e796bcf5cffa1c6171a1acb1393d38930711f
refs/heads/master
2023-05-30T22:57:30.523134
2021-06-22T02:12:50
2021-06-22T02:12:50
377,092,494
0
0
null
null
null
null
GB18030
C++
false
false
2,071
h
// DeshBz.h: interface for the DeshBz class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_DESHBZ_H__49D639F3_5437_4CFF_A695_B9486BABEFE4__INCLUDED_) #define AFX_DESHBZ_H__49D639F3_5437_4CFF_A695_B9486BABEFE4__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "dbmain.h" #include "rxboiler.h" #include <stdlib.h> #include <rxobject.h> #include <rxregsvc.h> #include <aced.h> #include <dbsymtb.h> //#include <dbapserv.h> #include <adslib.h> #include <dbxrecrd.h> #include <string.h> #include <dbents.h> #include <geassign.h> #include <dbgroup.h> #include <gearc2d.h > #include <dbpl.h> #include <dbjig.h> #include <acgi.h> #include <math.h> #include <assert.h> //#include <iostream.h> #include "rxdefs.h" #include "ol_errno.h" #include "STDIO.h" #include "malloc.h" #include "time.h" #include "GTZDM.h" #include "BAS_DRAW_FUN.H" class DeshBz_ROAD : public AcDbEntity,public BAS_DRAW_FUN { public: DeshBz_ROAD(); virtual ~DeshBz_ROAD(); GTZDM_ROAD *pzdm; double texth; double HBVScale; int m_Frame_Index; //图框号 20190712添加 Adesk::Boolean G_maketext(AcGiWorldDraw* pWd,AcGePoint3d& Pt, ACHAR* ctext,double ang,double texth ,int icolor,int mode); AcDbObjectId CreateLayer(ACHAR *LayerName, ACHAR *LineType); virtual Adesk::Boolean subWorldDraw(AcGiWorldDraw* pWd); virtual Acad::ErrorStatus dwgInFields(AcDbDwgFiler*); virtual Acad::ErrorStatus dwgOutFields(AcDbDwgFiler*) const; virtual Acad::ErrorStatus dxfInFields(AcDbDxfFiler*); virtual Acad::ErrorStatus dxfOutFields(AcDbDxfFiler*) const; void set_HScale_ori(); Adesk::Boolean G_make2dline(AcGiWorldDraw* pWd,AcGePoint3dArray ptarray, int icolor); double cmltosx (double cml); ACRX_DECLARE_MEMBERS(DeshBz_ROAD); private: double High;//栏高 double x_ori,y_ori;//startpoint坐标 double m_HScale, m_VScale; //地面线图纵横比例 //20190709 修改采用双轴比例尺 AcDbObjectId DeshId; }; #endif // !defined(AFX_DESHBZ_H__49D639F3_5437_4CFF_A695_B9486BABEFE4__INCLUDED_)
[ "liangzhu_st@csu.edu.cn" ]
liangzhu_st@csu.edu.cn
b6835df57acbb6ee0c3458947fa87a94653ccaa1
c66cd255f5fbc0b0ba532197d82e7b1eab213333
/CngWrapper/CngWrapperIntegrated/testintegration.h
887bac3c2d1c081b4b469518953ee4316e9fb413
[ "MIT" ]
permissive
ekussa/CngWrapper
5efea31a3e9951c87478f360f54056d30287cc66
732508fda5e2c373c536890d65509025e96bed97
refs/heads/main
2023-01-04T14:39:06.978258
2020-10-27T16:43:17
2020-10-27T16:43:17
307,765,161
0
0
null
null
null
null
UTF-8
C++
false
false
246
h
#ifndef TESTINTEGRATION_H #define TESTINTEGRATION_H #include <QObject> class TestIntegration : public QObject { Q_OBJECT private Q_SLOTS: void shouldRunIntegrated_data(); void shouldRunIntegrated(); }; #endif // TESTINTEGRATION_H
[ "eduardomk@outlook.com" ]
eduardomk@outlook.com
8f4e52a8f3a5a393085cb705848b4e44b174d018
1cc4727469951710751e9c46d4e578cacc0ec141
/jp2_pc/Source/Lib/Std/BlockArray.hpp
b82e2636c60d6d3876b703f7e72e65525107c9fe
[]
no_license
FabulaM24/JurassicParkTrespasserAIrip
60036b6a0196f33b42bdc7f6e4c984ef39a813f4
081c826b723a5fef2b318009fdaf13a27af908a5
refs/heads/master
2023-07-15T20:49:47.505140
2020-05-13T12:57:52
2020-05-13T12:57:52
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
5,784
hpp
/*********************************************************************************************** * * Copyright © DreamWorks Interactive, 1997. * * Contents: * CBArray A block allocated array. * * Bugs: * * To do: * *********************************************************************************************** * * $Log:: /JP2_PC/Source/Lib/Std/BlockArray.hpp $ * * 3 98/02/11 16:49 Speter * Oops. Allocated memory twice. Now derive from CAArray, and do not new/delete myself. * * 2 98/02/10 12:59 Speter * Update for new CArray template. * * 1 97/09/29 5:04p Pkeet * Initial implementation. * **********************************************************************************************/ #ifndef HEADER_LIB_STD_BLOCKARRAY_HPP #define HEADER_LIB_STD_BLOCKARRAY_HPP // // Required includes. // // #include "Array.hpp" // // Defines. // // Value representing a non-element. #define iNO_FREE_ELEMENTS (-1) // // Class definitions. // //********************************************************************************************** // template<class T> class CBArray : public CAArray<T> // // A block allocated array. // // Prefix: ba // // Notes: // This array allow memory to be allocated as a block for a number of discrete elements, // an then is able to allow these elements to be accessed through an index value. // The use of an index value can allow a savings in memory compared with the block // allocator class which is pointer based -- indexes can be less than 32 bit values. // // This class should be employed with caution: random access to the array without using // the 'iNewElement' and 'DeleteElement' functions will cause the array to become invalid. // //************************************** { int iNextFree; // Index to the next free element. uint uNumFree; // Number of free elements in the array. public: //****************************************************************************************** // // Constructors and destructor. // // Construct and array of a given maximum. CBArray(uint u_len) : CAArray<T>(u_len), iNextFree(0), uNumFree(u_len) { Assert(uLen > 0); // Initialize array. Reset(); } //****************************************************************************************** // // Member functions. // //****************************************************************************************** // int iNewElement() // // Allocates memory for a new data element from the array. // // Returns: // The index of the new data value or returns 'iNO_FREE_ELEMENTS' to indicate that no // free memory was available. // //********************************** { // If there are no free elements, return an error message. if (uNumFree == 0) return iNO_FREE_ELEMENTS; // Decrement the free element count. --uNumFree; // If there is only one free element, return it. if (uNumFree == 0) { return iNextFree; } // If there is more than one free element, use the element after the next free element. int i_retval = riIndex(iNextFree); riIndex(iNextFree) = riIndex(i_retval); // Return the element's index value. return i_retval; } //****************************************************************************************** // int iNewElement(const T& t) // // Allocates memory for a new data element from the array and copies a value into the new // element. // // Returns: // The index of the new data value or returns 'iNO_FREE_ELEMENTS' to indicate that no // free memory was available. // //********************************** { // Get a new element. int i_new_element = iNewElement(); // Do nothing if the new element is not valid. if (i_new_element == iNO_FREE_ELEMENTS) return iNO_FREE_ELEMENTS; // Copy the data. atArray[i_new_element] = t; // Return the element's index value. return i_new_element; } //****************************************************************************************** // void DeleteElement(int i_element) // // Removes an element from the array and adds it to the free list. // //********************************** { Assert(i_element != iNO_FREE_ELEMENTS); Assert(i_element >= 0); Assert(i_element < (int)uLen); // If there are no free elements, make this the sole free element. if (uNumFree == 0) { ++uNumFree; iNextFree = i_element; riIndex(i_element) = iNO_FREE_ELEMENTS; return; } // If there is one free element, chain the two elements together. if (uNumFree == 1) { ++uNumFree; riIndex(i_element) = iNextFree; riIndex(iNextFree) = i_element; return; } // Indicate that the element is released. ++uNumFree; // Insert the freed element between the next free element and the element after it. riIndex(i_element) = riIndex(iNextFree); riIndex(iNextFree) = i_element; } //****************************************************************************************** // void Reset() // // Adds all array elements to the free list. // //********************************** { Assert(atArray); // Initialize array with index values indicating an empty array. atArray[uLen - 1] = reinterpret_cast<T>(0); for (uint u = 0; u < uLen - 1; ++u) { atArray[u] = reinterpret_cast<T>(u + 1); } } private: //****************************************************************************************** // int& riIndex(int i) // // Returns a reference to the array element in the form of a reference to an integer. // //********************************** { Assert(i >= 0); Assert(i < (int)uLen); Assert(atArray); return *(reinterpret_cast<int*>(&atArray[i])); } }; #endif // HEADER_LIB_STD_BLOCKARRAY_HPP
[ "crackedcomputerstudios@gmail.com" ]
crackedcomputerstudios@gmail.com
622f1f9b9371ae350a4c137f31b591e6ab94e533
43db097127c291414f1dabb858a822daa63e32e4
/source/Ide2/AdamoSynPage.cpp
18fae7479fba1dfcf72a24a03d591149f2bb54b5
[]
no_license
Spritutu/AdamoIDE
c7e0188b72846c154192692e77a123727f5d7865
d6f6e785a56526f22dc8a86e53abf56b180e808d
refs/heads/master
2023-02-05T09:57:59.621114
2020-12-29T10:44:38
2020-12-29T10:44:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
50,205
cpp
// AdamoSynage.cpp : implementation file // /* include files */ #include "stdafx.h" #include "AdamoSynContainer.h" #include "AdamoSynPage.h" #include "StdGrfx.h" // CAdamoSynPage extern CString GetXMLProperty (const char* sz, const char* szProp); extern COLORREF TranslateRGB (char* p); IMPLEMENT_DYNAMIC(CAdamoSynPage, CWnd) CAdamoSynPage::CAdamoSynPage() : m_bBackgroundEnabled (false), m_bKilling (false) { } CAdamoSynPage::~CAdamoSynPage() { m_bKilling = true; ClearCtrls (); } BEGIN_MESSAGE_MAP(CAdamoSynPage, CWnd) ON_WM_PAINT() ON_WM_ERASEBKGND() ON_CONTROL_RANGE (BN_CLICKED, 1000, 5000, OnClick) ON_CONTROL_RANGE (LBN_SELCHANGE, 1000, 5000, OnSelChange) END_MESSAGE_MAP() // CAdamoSynPage message handlers int CAdamoSynPage::Load (CString strXML) { if (!LoadXMLCtrls (strXML)) ; return 0; } int CAdamoSynPage::LoadXMLCtrls (CString strXML) { HRESULT hr = m_pDocXml.CreateInstance( __uuidof(MSXML2::DOMDocument60)); if (SUCCEEDED(hr)) { m_pDocXml->async = false; if (m_pDocXml->loadXML(strXML.AllocSysString ())) { ParseXMLString (); hr=S_OK; } m_pDocXml.Release (); } return hr == S_OK ? 0 : -1; } int CAdamoSynPage::ParseXMLString () { ElementXmlPtr p=m_pDocXml->documentElement; NodeListXmlPtr pRootChild; if (p->hasChildNodes()) { pRootChild = p->childNodes; COleVariant v=pRootChild->Getitem (0)->nodeName; if (CString (v.bstrVal) == "form") { v=((ElementXmlPtr)pRootChild->Getitem(0))->getAttribute("name"); if (v.vt==VT_BSTR) { CString strFormName=CString (v.bstrVal); CreateFormXML (pRootChild->Getitem (0)); CreateXMLControls (pRootChild->Getitem (0)); CreateWndCtrls (); } } } return 0; } /* ** CreateFormXML : */ int CAdamoSynPage::CreateFormXML (ElementXmlPtr p) { COleVariant v; CString strFormName, strFormPosition, strImageName; v=p->getAttribute("name"); if (v.vt==VT_BSTR) { strFormPosition=CString (v.bstrVal); SetFormPosition (strFormPosition); } v=p->getAttribute("formname"); if (v.vt==VT_BSTR) { strFormName=CString (v.bstrVal); SetName (strFormName); } v=p->getAttribute("src"); if (v.vt==VT_BSTR) { strImageName = CString (v.bstrVal); SetBackgroundImage (strImageName); } return 0; } /* ** CreateXMLControls : */ int CAdamoSynPage::CreateXMLControls (ElementXmlPtr p) { NodeListXmlPtr pRootChild; int nB=-1; if (p->hasChildNodes()) { pRootChild = p->childNodes; int n=pRootChild->length, i=0; while (n>0) { COleVariant v=pRootChild->Getitem (i)->nodeName; CString str=CString (v.bstrVal); if (str=="input") nB=CreateXMLInput (pRootChild->Getitem (i)); else if (str=="select") nB=CreateXMLComboList (pRootChild->Getitem (i)); else if (str=="fieldset") nB=CreateXMLGroupBox (pRootChild->Getitem (i)); else if (str=="button") nB=CreateXMLButton (pRootChild->Getitem (i)); else if (str=="label") nB=CreateXMLLabel (pRootChild->Getitem (i)); else if (str=="img") nB=CreateXMLInputImage (pRootChild->Getitem (i)); else if (str=="grid") nB=CreateXMLGrid (pRootChild->Getitem (i)); else if (str=="ax") nB=CreateXMLAx (pRootChild->Getitem (i)); else if (str=="led") nB=CreateXMLLed (pRootChild->Getitem (i)); else if (str=="angulargauge") nB=CreateXMLAngularGauge (pRootChild->Getitem (i)); else if (str=="lineargauge") nB=CreateXMLLinearGauge (pRootChild->Getitem (i)); else if (str=="display") nB=CreateXMLDisplay (pRootChild->Getitem (i)); else if (str=="static") nB=CreateXMLILabel (pRootChild->Getitem (i)); else if (str=="picture") nB=CreateXMLIPicture (pRootChild->Getitem (i)); n--; i++; } } return nB; } /* ** CreateXMLButton : */ int CAdamoSynPage::CreateXMLButton (ElementXmlPtr p) { CAdamoSynButton *pBtn=new CAdamoSynButton; COleVariant v=p->getAttribute("name"); pBtn->SetName (CString (v.bstrVal)); v=p->getAttribute("value"); pBtn->SetValue (CString (v.bstrVal)); v=p->getAttribute("id"); pBtn->SetID (atoi (CString (v.bstrVal))); v=p->getAttribute("tabindex"); pBtn->SetTabIndex (atoi (CString (v.bstrVal))); v=p->getAttribute("style"); pBtn->GetObjStyle().Load (CString (v.bstrVal)); v=p->getAttribute("src"); pBtn->SetButtonImage (CString (v.bstrVal)); v=p->getAttribute("type"); CString str = CString (v.bstrVal); if (str == "standard") pBtn->SetButtonType (eStandard); else if (str == "bitmap") pBtn->SetButtonType (eBitmap); v=p->getAttribute("transparency"); str = CString (v.bstrVal); pBtn->SetTransparency (atoi ((const char *)str) != 0); v=p->getAttribute("action"); str = CString (v.bstrVal); DWORD dwAction = atoi ((const char *)str); if (bittest (dwAction, 0)) pBtn->EnableDownloadAction (); if (bittest (dwAction, 1)) pBtn->EnableLoadAction (); if (bittest (dwAction, 2)) pBtn->EnableSaveAction (); if (bittest (dwAction, 3)) pBtn->EnableChangePageAction (); v=p->getAttribute("nextpage"); pBtn->SetNextPage (CString (v.bstrVal)); pBtn->SetParentWnd (this); AddCtrl (pBtn); return 0; } /* ** CreateXMLGroupBox : */ int CAdamoSynPage::CreateXMLGroupBox (ElementXmlPtr p) { CAdamoSynGroupBox *pGB=new CAdamoSynGroupBox; COleVariant v=p->getAttribute("id"); pGB->SetID (atoi (CString (v.bstrVal))); v=p->getAttribute("style"); pGB->GetObjStyle().Load (CString (v.bstrVal)); if (p->hasChildNodes()) { ElementXmlPtr pLegend = p->childNodes->Getitem (0); COleVariant v=pLegend->nodeName; if (CString (v.bstrVal)=="legend") { v=pLegend->text; pGB->SetValue (CString (v.bstrVal)); } } pGB->SetParentWnd (this); AddCtrl (pGB); return 0; } /* ** CreateXMLLabel : */ int CAdamoSynPage::CreateXMLLabel (ElementXmlPtr p) { CAdamoSynLabel *pIT=new CAdamoSynLabel; COleVariant v=p->getAttribute("name"); pIT->SetName (CString (v.bstrVal)); v=p->getAttribute("value"); pIT->SetValue (CString (v.bstrVal)); v=p->getAttribute("id"); pIT->SetID (atoi (CString (v.bstrVal))); v=p->getAttribute("tabindex"); pIT->SetTabIndex (atoi (CString (v.bstrVal))); v=p->getAttribute("style"); pIT->GetObjStyle().Load (CString (v.bstrVal)); pIT->SetParentWnd (this); AddCtrl (pIT); return 0; } /* ** CreateXMLGrid : */ int CAdamoSynPage::CreateXMLGrid (ElementXmlPtr p) { int nRows, nCols; char *pC; CAdamoSynGrid *pGrid=new CAdamoSynGrid; COleVariant v=p->getAttribute("name"); pGrid->SetName (CString (v.bstrVal)); v=p->getAttribute("id"); pGrid->SetID (atoi (CString (v.bstrVal))); v=p->getAttribute("tabindex"); pGrid->SetTabIndex (atoi (CString (v.bstrVal))); v=p->getAttribute("rows"); nRows = strtol (CString (v.bstrVal), &pC, 10); v=p->getAttribute("cols"); nCols = strtol (CString (v.bstrVal), &pC, 10); pGrid->SetGridData (nRows, nCols); v=p->getAttribute("style"); pGrid->GetObjStyle().Load (CString (v.bstrVal)); LoadXMLColumns (p, pGrid); LoadXMLVariable (p, &pGrid->GetObjVar ()); pGrid->SetParentWnd (this); AddCtrl (pGrid); return 0; } /* ** CreateXMLAx : */ int CAdamoSynPage::CreateXMLAx (ElementXmlPtr p) { CAdamoSynContainer *pSynContainer = GETSYNCONT(); CAdamoMachine *pMachine; CAdamoSynRTAx *pAx=new CAdamoSynRTAx; COleVariant v=p->getAttribute("name"); pAx->SetName (CString (v.bstrVal)); v=p->getAttribute("id"); pAx->SetID (atoi (CString (v.bstrVal))); v=p->getAttribute("tabindex"); pAx->SetTabIndex (atoi (CString (v.bstrVal))); v=p->getAttribute("style"); pAx->GetObjStyle().Load (CString (v.bstrVal)); v=p->getAttribute("path"); pAx->SetPath (CString (v.bstrVal)); v=p->getAttribute("address"); pAx->SetID (atoi (CString (v.bstrVal))); pAx->SetParentWnd (this); pMachine = pSynContainer->GetMachine (); pAx->SetMachine (pMachine); AddCtrl (pAx); return 0; } /* ** CreateXMLLed : */ int CAdamoSynPage::CreateXMLLed (ElementXmlPtr p) { CAdamoSynContainer *pSynContainer = GETSYNCONT(); CAdamoMachine *pMachine; CAdamoSynILed *pLed=new CAdamoSynILed; CString strPath, str; enDispositivi eDev; char *pColor; int nData, nLogicAddress; COleVariant v=p->getAttribute("name"); pLed->SetName (CString (v.bstrVal)); v=p->getAttribute("id"); pLed->SetID (atoi (CString (v.bstrVal))); v=p->getAttribute("tabindex"); pLed->SetTabIndex (atoi (CString (v.bstrVal))); v=p->getAttribute("path"); strPath = CString (v.bstrVal); pLed->SetPath (strPath); v=p->getAttribute("device"); eDev = (enDispositivi)atoi (CString (v.bstrVal)); pLed->SetDeviceType (eDev); v=p->getAttribute("address"); nLogicAddress = atoi (CString (v.bstrVal)); pLed->SetLogicAddress (nLogicAddress); v=p->getAttribute("data"); nData = atoi (CString (v.bstrVal)); pLed->SetData (nData); /* general */ v=p->getAttribute("L_G_Type"); pLed->SetLedType ((eLedType)atoi (CString (v.bstrVal))); v=p->getAttribute("L_G_Transparent"); pLed->SetTransparent (atoi (CString (v.bstrVal))!=0); v=p->getAttribute("L_G_ShowReflection"); pLed->SetShowReflection (atoi (CString (v.bstrVal)) != 0); v=p->getAttribute("L_G_ActiveColor"); str = CString (v.bstrVal); pColor = str.GetBuffer (); if (pColor[0] == '#') pLed->SetActiveColor (TranslateRGB (pColor + 1)); v=p->getAttribute("L_G_BevelStyle"); pLed->SetBevelStyle ((eLedStyle)atoi (CString (v.bstrVal))); v=p->getAttribute("L_A_SpacingHorizontal"); pLed->SetHorizontalSpacing (atoi (CString (v.bstrVal))); v=p->getAttribute("L_A_SpacingVertical"); pLed->SetVerticalSpacing (atoi (CString (v.bstrVal))); v=p->getAttribute("L_A_RowCount"); pLed->SetRowCount (atoi (CString (v.bstrVal))); v=p->getAttribute("L_A_ColCount"); pLed->SetColCount (atoi (CString (v.bstrVal))); v=p->getAttribute("L_A_BorderStyle"); pLed->SetBorderStyle ((eLedStyle)atoi (CString (v.bstrVal))); v=p->getAttribute("L_A_BackgroundColor"); str = CString (v.bstrVal); pColor = str.GetBuffer (); if (pColor[0] == '#') pLed->SetBackgroundColor (TranslateRGB (pColor + 1)); v=p->getAttribute("style"); pLed->GetObjStyle().Load (CString (v.bstrVal)); LoadXMLVariable (p, &pLed->GetObjVar ()); pLed->SetParentWnd (this); pMachine = pSynContainer->GetMachine (); pLed->SetMachine (pMachine); AddCtrl (pLed); return 0; } /* ** CreateXMLAngularGauge : */ int CAdamoSynPage::CreateXMLAngularGauge (ElementXmlPtr p) { CAdamoSynContainer *pSynContainer = GETSYNCONT(); CAdamoMachine *pMachine; CAdamoSynIAngularGauge *pAngGauge=new CAdamoSynIAngularGauge; CString strPath, str; enDispositivi eDev; char *pColor; int nLogicAddress, nData; COleVariant v=p->getAttribute("name"); pAngGauge->SetName (CString (v.bstrVal)); v=p->getAttribute("id"); pAngGauge->SetID (atoi (CString (v.bstrVal))); v=p->getAttribute("tabindex"); pAngGauge->SetTabIndex (atoi (CString (v.bstrVal))); v=p->getAttribute("path"); strPath = CString (v.bstrVal); pAngGauge->SetPath (strPath); v=p->getAttribute("device"); eDev = (enDispositivi)atoi (CString (v.bstrVal)); pAngGauge->SetDeviceType (eDev); v=p->getAttribute("address"); nLogicAddress = atoi (CString (v.bstrVal)); pAngGauge->SetLogicAddress (nLogicAddress); v=p->getAttribute("data"); nData = atoi (CString (v.bstrVal)); pAngGauge->SetData (nData); /* caratteristiche generali */ v=p->getAttribute("G_G_Transparent"); pAngGauge->SetTransparent (atoi (CString (v.bstrVal))!=0); v=p->getAttribute("G_G_PosMin"); pAngGauge->SetPosMin (atoi (CString (v.bstrVal))); v=p->getAttribute("G_G_PosMax"); pAngGauge->SetPosMax (atoi (CString (v.bstrVal))); v=p->getAttribute("G_G_ShowInArcR"); pAngGauge->ShowInnerRadius (atoi (CString (v.bstrVal))!=0); v=p->getAttribute("G_G_ShowOutArcR"); pAngGauge->ShowOuterRadius (atoi (CString (v.bstrVal))!=0); v=p->getAttribute("G_G_RevScale"); pAngGauge->SetReverseScale (atoi (CString (v.bstrVal))!=0); v=p->getAttribute("G_G_BorderStyle"); pAngGauge->SetBorderStyle ((eBorderStyle)atoi (CString (v.bstrVal))); v=p->getAttribute("G_G_BackColor"); str = CString (v.bstrVal); pColor = str.GetBuffer (); if (pColor[0] == '#') pAngGauge->SetBackGroundColor (TranslateRGB (pColor + 1)); /* pointers */ v=p->getAttribute("G_P_Type"); pAngGauge->SetPointerStyle ((ePointerStyle)atoi (CString (v.bstrVal))); v=p->getAttribute("G_P_Size"); pAngGauge->SetPointerSize (atoi (CString (v.bstrVal))); v=p->getAttribute("G_P_Margin"); pAngGauge->SetPointerMargin (atoi (CString (v.bstrVal))); v=p->getAttribute("G_P_Color"); str = CString (v.bstrVal); pColor = str.GetBuffer (); if (pColor[0] == '#') pAngGauge->SetPointerColor (TranslateRGB (pColor + 1)); /* arc */ v=p->getAttribute("G_A_Radius"); pAngGauge->SetArcRadius (atoi (CString (v.bstrVal))); v=p->getAttribute("G_A_Angle"); pAngGauge->SetArcAngle (atoi (CString (v.bstrVal))); v=p->getAttribute("G_A_StartAngle"); pAngGauge->SetArcStartAngle (atoi (CString (v.bstrVal))); /* hub */ v=p->getAttribute("G_H_Show"); pAngGauge->ShowHub (atoi (CString (v.bstrVal))!=0); v=p->getAttribute("G_H_Show3D"); pAngGauge->ShowHub3D (atoi (CString (v.bstrVal))!=0); v=p->getAttribute("G_H_Size"); pAngGauge->SetHubSize (atoi (CString (v.bstrVal))); v=p->getAttribute("G_H_Color"); str = CString (v.bstrVal); pColor = str.GetBuffer (); if (pColor[0] == '#') pAngGauge->SetHubColor (TranslateRGB (pColor + 1)); /* face */ v=p->getAttribute("G_F_Show"); pAngGauge->ShowFace (atoi (CString (v.bstrVal))!=0); v=p->getAttribute("G_F_Type"); pAngGauge->SetFaceStyle ((eStyle)atoi (CString (v.bstrVal))); v=p->getAttribute("G_B_Type"); pAngGauge->SetBevelStyle ((eStyle)atoi (CString (v.bstrVal))); v=p->getAttribute("G_B_Size"); pAngGauge->SetBevelSize (atoi (CString (v.bstrVal))); v=p->getAttribute("G_F_Color"); str = CString (v.bstrVal); pColor = str.GetBuffer (); if (pColor[0] == '#') pAngGauge->SetFaceColor (TranslateRGB (pColor + 1)); /* tick */ v=p->getAttribute("G_T_Margin"); pAngGauge->SetTickMargin (atoi (CString (v.bstrVal))); /* tick label */ v=p->getAttribute("G_TL_Margin"); pAngGauge->SetTickLabelMargin (atoi (CString (v.bstrVal))); /* tick major */ v=p->getAttribute("G_TMA_Show"); pAngGauge->ShowTickMajor (atoi (CString (v.bstrVal))!=0); v=p->getAttribute("G_TMA_Number"); pAngGauge->SetTickMajorNumber (atoi (CString (v.bstrVal))); v=p->getAttribute("G_TMA_Lenght"); pAngGauge->SetTickMajorLenght (atoi (CString (v.bstrVal))); v=p->getAttribute("G_TMA_Color"); str = CString (v.bstrVal); pColor = str.GetBuffer (); if (pColor[0] == '#') pAngGauge->SetTickMajorColor (TranslateRGB (pColor + 1)); /* tick minor */ v=p->getAttribute("G_TMI_Show"); pAngGauge->ShowTickMinor (atoi (CString (v.bstrVal))!=0); v=p->getAttribute("G_TMI_Number"); pAngGauge->SetTickMinorNumber (atoi (CString (v.bstrVal))); v=p->getAttribute("G_TMI_Lenght"); pAngGauge->SetTickMinorLenght (atoi (CString (v.bstrVal))); v=p->getAttribute("G_TMI_Color"); str = CString (v.bstrVal); pColor = str.GetBuffer (); if (pColor[0] == '#') pAngGauge->SetTickMinorColor (TranslateRGB (pColor + 1)); /* sections */ v=p->getAttribute("G_S_Count"); pAngGauge->SetSectionsNumber (atoi (CString (v.bstrVal))); v=p->getAttribute("G_S_Color1"); str = CString (v.bstrVal); pColor = str.GetBuffer (); if (pColor[0] == '#') pAngGauge->SetSection1Color (TranslateRGB (pColor + 1)); v=p->getAttribute("G_S_Color2"); str = CString (v.bstrVal); pColor = str.GetBuffer (); if (pColor[0] == '#') pAngGauge->SetSection2Color (TranslateRGB (pColor + 1)); v=p->getAttribute("G_S_Color3"); str = CString (v.bstrVal); pColor = str.GetBuffer (); if (pColor[0] == '#') pAngGauge->SetSection3Color (TranslateRGB (pColor + 1)); v=p->getAttribute("G_S_Color4"); str = CString (v.bstrVal); pColor = str.GetBuffer (); if (pColor[0] == '#') pAngGauge->SetSection4Color (TranslateRGB (pColor + 1)); v=p->getAttribute("G_S_Color5"); str = CString (v.bstrVal); pColor = str.GetBuffer (); if (pColor[0] == '#') pAngGauge->SetSection5Color (TranslateRGB (pColor + 1)); v=p->getAttribute("G_S_End1"); pAngGauge->SetEndSection1 (atoi (CString (v.bstrVal))); v=p->getAttribute("G_S_End2"); pAngGauge->SetEndSection2 (atoi (CString (v.bstrVal))); v=p->getAttribute("G_S_End3"); pAngGauge->SetEndSection3 (atoi (CString (v.bstrVal))); v=p->getAttribute("G_S_End4"); pAngGauge->SetEndSection4 (atoi (CString (v.bstrVal))); v=p->getAttribute("style"); pAngGauge->GetObjStyle().Load (CString (v.bstrVal)); LoadXMLVariable (p, &pAngGauge->GetObjVar ()); pAngGauge->SetParentWnd (this); pMachine = pSynContainer->GetMachine (); pAngGauge->SetMachine (pMachine); AddCtrl (pAngGauge); return 0; } /* ** CreateXMLLinearGauge : */ int CAdamoSynPage::CreateXMLLinearGauge (ElementXmlPtr p) { CAdamoSynContainer *pSynContainer = GETSYNCONT(); CAdamoMachine *pMachine; CAdamoSynILinearGauge *pLinGauge=new CAdamoSynILinearGauge; CString strPath, str; enDispositivi eDev; char *pColor; int nData, nLogicAddress; COleVariant v=p->getAttribute("name"); pLinGauge->SetName (CString (v.bstrVal)); v=p->getAttribute("id"); pLinGauge->SetID (atoi (CString (v.bstrVal))); v=p->getAttribute("tabindex"); pLinGauge->SetTabIndex (atoi (CString (v.bstrVal))); v=p->getAttribute("path"); strPath = CString (v.bstrVal); pLinGauge->SetPath (strPath); v=p->getAttribute("device"); eDev = (enDispositivi)atoi (CString (v.bstrVal)); pLinGauge->SetDeviceType (eDev); v=p->getAttribute("address"); nLogicAddress = atoi (CString (v.bstrVal)); pLinGauge->SetLogicAddress (nLogicAddress); v=p->getAttribute("data"); nData = atoi (CString (v.bstrVal)); pLinGauge->SetData (nData); /* general */ v=p->getAttribute("LI_G_Transparent"); pLinGauge->SetTransparent (atoi (CString (v.bstrVal))!=0); v=p->getAttribute("LI_G_PosMin"); pLinGauge->SetPosMin (atoi (CString (v.bstrVal))); v=p->getAttribute("LI_G_PosMax"); pLinGauge->SetPosMax (atoi (CString (v.bstrVal))); v=p->getAttribute("LI_G_RevScale"); pLinGauge->SetReverseScale (atoi (CString (v.bstrVal))!=0); v=p->getAttribute("LI_G_Orientation"); pLinGauge->SetOrientation ((eOrientation)atoi (CString (v.bstrVal))); v=p->getAttribute("LI_G_OrientationTicks"); pLinGauge->SetOrientationTicks ((eOrientationTicks)atoi (CString (v.bstrVal))); v=p->getAttribute("LI_G_BorderStyle"); pLinGauge->SetBorderStyle ((eLinearGaugeStyle)atoi (CString (v.bstrVal))); v=p->getAttribute("LI_G_BackColor"); str = CString (v.bstrVal); pColor = str.GetBuffer (); if (pColor[0] == '#') pLinGauge->SetBackGroundColor (TranslateRGB (pColor + 1)); /* pointers */ v=p->getAttribute("LI_P_Style"); pLinGauge->SetPointerStyle ((eLinearGaugePointerStyle)atoi (CString (v.bstrVal))); v=p->getAttribute("LI_P_Size"); pLinGauge->SetPointerSize (atoi (CString (v.bstrVal))); v=p->getAttribute("LI_P_Margin"); pLinGauge->SetPointerOffset (atoi (CString (v.bstrVal))); v=p->getAttribute("LI_P_Color"); str = CString (v.bstrVal); pColor = str.GetBuffer (); if (pColor[0] == '#') pLinGauge->SetPointerColor (TranslateRGB (pColor + 1)); v=p->getAttribute("LI_P_3D"); pLinGauge->SetPointer3D (atoi (CString (v.bstrVal))!=0); v=p->getAttribute("LI_P_DrawScaleSide"); pLinGauge->SetDrawScaleSide (atoi (CString (v.bstrVal))!=0); /* ticks */ v=p->getAttribute("LI_T_Show"); pLinGauge->ShowTickAxes (atoi (CString (v.bstrVal))!=0); v=p->getAttribute("LI_T_Margin"); pLinGauge->SetTickMargin (atoi (CString (v.bstrVal))); v=p->getAttribute("LI_T_ShowLabels"); pLinGauge->ShowLabels (atoi (CString (v.bstrVal))!=0); v=p->getAttribute("LI_T_LabelMargin"); pLinGauge->SetLabelMargin (atoi (CString (v.bstrVal))); v=p->getAttribute("LI_TMA_Show"); pLinGauge->ShowTickMajor (atoi (CString (v.bstrVal))!=0); v=p->getAttribute("LI_TMA_Number"); pLinGauge->SetTickMajorNumber (atoi (CString (v.bstrVal))); v=p->getAttribute("LI_TMA_Lenght"); pLinGauge->SetTickMajorLenght (atoi (CString (v.bstrVal))); v=p->getAttribute("LI_TMA_Color"); str = CString (v.bstrVal); pColor = str.GetBuffer (); if (pColor[0] == '#') pLinGauge->SetTickMajorColor (TranslateRGB (pColor + 1)); v=p->getAttribute("LI_TMI_Show"); pLinGauge->ShowTickMinor (atoi (CString (v.bstrVal))!=0); v=p->getAttribute("LI_TMI_Number"); pLinGauge->SetTickMinorNumber (atoi (CString (v.bstrVal))); v=p->getAttribute("LI_TMI_Lenght"); pLinGauge->SetTickMinorLenght (atoi (CString (v.bstrVal))); v=p->getAttribute("LI_TMI_Color"); str = CString (v.bstrVal); pColor = str.GetBuffer (); if (pColor[0] == '#') pLinGauge->SetTickMinorColor (TranslateRGB (pColor + 1)); /* sections */ v=p->getAttribute("LI_S_Count"); pLinGauge->SetSectionsNumber (atoi (CString (v.bstrVal))); v=p->getAttribute("LI_S_Color1"); str = CString (v.bstrVal); pColor = str.GetBuffer (); if (pColor[0] == '#') pLinGauge->SetSection1Color (TranslateRGB (pColor + 1)); v=p->getAttribute("LI_S_Color2"); str = CString (v.bstrVal); pColor = str.GetBuffer (); if (pColor[0] == '#') pLinGauge->SetSection2Color (TranslateRGB (pColor + 1)); v=p->getAttribute("LI_S_Color3"); str = CString (v.bstrVal); pColor = str.GetBuffer (); if (pColor[0] == '#') pLinGauge->SetSection3Color (TranslateRGB (pColor + 1)); v=p->getAttribute("LI_S_Color4"); str = CString (v.bstrVal); pColor = str.GetBuffer (); if (pColor[0] == '#') pLinGauge->SetSection4Color (TranslateRGB (pColor + 1)); v=p->getAttribute("LI_S_Color5"); str = CString (v.bstrVal); pColor = str.GetBuffer (); if (pColor[0] == '#') pLinGauge->SetSection5Color (TranslateRGB (pColor + 1)); v=p->getAttribute("LI_S_End1"); pLinGauge->SetEndSection1 (atoi (CString (v.bstrVal))); v=p->getAttribute("LI_S_End2"); pLinGauge->SetEndSection2 (atoi (CString (v.bstrVal))); v=p->getAttribute("LI_S_End3"); pLinGauge->SetEndSection3 (atoi (CString (v.bstrVal))); v=p->getAttribute("LI_S_End4"); pLinGauge->SetEndSection4 (atoi (CString (v.bstrVal))); v=p->getAttribute("style"); pLinGauge->GetObjStyle().Load (CString (v.bstrVal)); LoadXMLVariable (p, &pLinGauge->GetObjVar ()); pLinGauge->SetParentWnd (this); pMachine = pSynContainer->GetMachine (); pLinGauge->SetMachine (pMachine); AddCtrl (pLinGauge); return 0; } /* ** CreateXMLDisplay : */ int CAdamoSynPage::CreateXMLDisplay (ElementXmlPtr p) { CAdamoSynContainer *pSynContainer = GETSYNCONT(); CAdamoMachine *pMachine; CAdamoSynIDisplay *pDisplay=new CAdamoSynIDisplay; CString strPath, str; enDispositivi eDev; char *pColor; int nData, nLogicAddress; COleVariant v=p->getAttribute("name"); pDisplay->SetName (CString (v.bstrVal)); v=p->getAttribute("id"); pDisplay->SetID (atoi (CString (v.bstrVal))); v=p->getAttribute("tabindex"); pDisplay->SetTabIndex (atoi (CString (v.bstrVal))); v=p->getAttribute("path"); strPath = CString (v.bstrVal); pDisplay->SetPath (strPath); v=p->getAttribute("device"); eDev = (enDispositivi)atoi (CString (v.bstrVal)); pDisplay->SetDeviceType (eDev); v=p->getAttribute("address"); nLogicAddress = atoi (CString (v.bstrVal)); pDisplay->SetLogicAddress (nLogicAddress); v=p->getAttribute("data"); nData = atoi (CString (v.bstrVal)); pDisplay->SetData (nData); /* general */ v=p->getAttribute("D_G_ShowOffsement"); pDisplay->ShowOffSegment (atoi (CString (v.bstrVal))!=0); v=p->getAttribute("D_G_Transparent"); pDisplay->SetTransparent (atoi (CString (v.bstrVal))!=0); v=p->getAttribute("D_G_ShowSign"); pDisplay->ShowSign (atoi (CString (v.bstrVal))!=0); v=p->getAttribute("D_G_AutosegmentColor"); pDisplay->SetAutoSegmentOffColor (atoi (CString (v.bstrVal))!=0); v=p->getAttribute("D_G_Precision"); pDisplay->SetPrecision (atoi (CString (v.bstrVal))); v=p->getAttribute("D_G_BorderStyle"); pDisplay->SetDisplayStyle ((eDisplayStyle)atoi (CString (v.bstrVal))); v=p->getAttribute("D_G_LeadingStyle"); pDisplay->SetLeadingStyle ((eDisplayLeadingStyle)atoi (CString (v.bstrVal))); v=p->getAttribute("D_G_BackColor"); str = CString (v.bstrVal); pColor = str.GetBuffer (); if (pColor[0] == '#') pDisplay->SetBackGroundColor (TranslateRGB (pColor + 1)); /* display */ v=p->getAttribute("D_D_Count"); pDisplay->SetDisplayCount (atoi (CString (v.bstrVal))); v=p->getAttribute("D_D_Spacing"); pDisplay->SetDisplaySpacing (atoi (CString (v.bstrVal))); v=p->getAttribute("D_D_Size"); pDisplay->SetDisplaySize (atoi (CString (v.bstrVal))); v=p->getAttribute("D_D_Separation"); pDisplay->SetDisplaySeparation (atoi (CString (v.bstrVal))); v=p->getAttribute("D_D_Margin"); pDisplay->SetDisplayMargin (atoi (CString (v.bstrVal))); v=p->getAttribute("D_D_Color"); str = CString (v.bstrVal); pColor = str.GetBuffer (); if (pColor[0] == '#') pDisplay->SetDisplayColor (TranslateRGB (pColor + 1)); v=p->getAttribute("D_D_OffColor"); str = CString (v.bstrVal); pColor = str.GetBuffer (); if (pColor[0] == '#') pDisplay->SetDisplayOffColor (TranslateRGB (pColor + 1)); v=p->getAttribute("style"); pDisplay->GetObjStyle().Load (CString (v.bstrVal)); LoadXMLVariable (p, &pDisplay->GetObjVar ()); pDisplay->SetParentWnd (this); pMachine = pSynContainer->GetMachine (); pDisplay->SetMachine (pMachine); AddCtrl (pDisplay); return 0; } /* ** CreateXMLILabel : */ int CAdamoSynPage::CreateXMLILabel (ElementXmlPtr p) { CAdamoSynContainer *pSynContainer = GETSYNCONT(); CAdamoMachine *pMachine; CAdamoSynILabel *pLabel=new CAdamoSynILabel; CString strPath, str; enDispositivi eDev; char *pColor; int nData, nLogicAddress; COleVariant v=p->getAttribute("name"); pLabel->SetName (CString (v.bstrVal)); v=p->getAttribute("id"); pLabel->SetID (atoi (CString (v.bstrVal))); v=p->getAttribute("tabindex"); pLabel->SetTabIndex (atoi (CString (v.bstrVal))); v=p->getAttribute("path"); strPath = CString (v.bstrVal); pLabel->SetPath (strPath); v=p->getAttribute("device"); eDev = (enDispositivi)atoi (CString (v.bstrVal)); pLabel->SetDeviceType (eDev); v=p->getAttribute("address"); nLogicAddress = atoi (CString (v.bstrVal)); pLabel->SetLogicAddress (nLogicAddress); v=p->getAttribute("data"); nData = atoi (CString (v.bstrVal)); pLabel->SetData (nData); v=p->getAttribute("value"); pLabel->SetValue (CString (v.bstrVal)); /* general */ v=p->getAttribute("L_G_Transparent"); pLabel->SetTransparent (atoi (CString (v.bstrVal))!=0); v=p->getAttribute("L_G_AutoSize"); pLabel->SetAutoSize (atoi (CString (v.bstrVal))!=0); v=p->getAttribute("L_G_BorderStyle"); pLabel->SetStyle ((eLabelStyle)atoi (CString (v.bstrVal))); v=p->getAttribute("L_G_Alignment"); pLabel->SetAlignment ((eLabelAlignment)atoi (CString (v.bstrVal))); v=p->getAttribute("L_G_Shadow"); pLabel->ShowShadow (atoi (CString (v.bstrVal))!=0); v=p->getAttribute("L_G_OffsetX"); pLabel->SetOffsetX (atoi (CString (v.bstrVal))); v=p->getAttribute("L_G_OffsetY"); pLabel->SetOffsetY (atoi (CString (v.bstrVal))); v=p->getAttribute("L_G_Color"); str = CString (v.bstrVal); pColor = str.GetBuffer (); if (pColor[0] == '#') pLabel->SetColor (TranslateRGB (pColor + 1)); v=p->getAttribute("L_G_BackColor"); str = CString (v.bstrVal); pColor = str.GetBuffer (); if (pColor[0] == '#') pLabel->SetBackColor (TranslateRGB (pColor + 1)); v=p->getAttribute("L_G_ShadowColor"); str = CString (v.bstrVal); pColor = str.GetBuffer (); if (pColor[0] == '#') pLabel->SetShadowColor (TranslateRGB (pColor + 1)); v=p->getAttribute("style"); pLabel->GetObjStyle().Load (CString (v.bstrVal)); LoadXMLVariable (p, &pLabel->GetObjVar ()); pLabel->SetParentWnd (this); pMachine = pSynContainer->GetMachine (); pLabel->SetMachine (pMachine); AddCtrl (pLabel); return 0; } /* ** CreateXMLILabel : */ int CAdamoSynPage::CreateXMLIPicture (ElementXmlPtr p) { CAdamoSynContainer *pSynContainer = GETSYNCONT(); CAdamoMachine *pMachine; CAdamoSynIPicture *pPicture=new CAdamoSynIPicture; CString strPath, str; enDispositivi eDev; char *pColor; int nData, nLogicAddress; COleVariant v=p->getAttribute("name"); pPicture->SetName (CString (v.bstrVal)); v=p->getAttribute("id"); pPicture->SetID (atoi (CString (v.bstrVal))); v=p->getAttribute("tabindex"); pPicture->SetTabIndex (atoi (CString (v.bstrVal))); v=p->getAttribute("path"); strPath = CString (v.bstrVal); pPicture->SetPath (strPath); v=p->getAttribute("device"); eDev = (enDispositivi)atoi (CString (v.bstrVal)); pPicture->SetDeviceType (eDev); v=p->getAttribute("address"); nLogicAddress = atoi (CString (v.bstrVal)); pPicture->SetLogicAddress (nLogicAddress); v=p->getAttribute("data"); nData = atoi (CString (v.bstrVal)); pPicture->SetData (nData); v=p->getAttribute("checked"); pPicture->SetStretch (CString (v.bstrVal)=="true"); v=p->getAttribute("transparent"); pPicture->SetTransparent (CString (v.bstrVal)=="true"); v=p->getAttribute("transparentcolor"); str = CString (v.bstrVal); pColor = str.GetBuffer (); if (pColor[0] == '#') pPicture->SetTransparentColor (TranslateRGB (pColor + 1)); v=p->getAttribute("picture1"); pPicture->SetImageID (0, CString (v.bstrVal)); v=p->getAttribute("picture2"); pPicture->SetImageID (1, CString (v.bstrVal)); v=p->getAttribute("picture3"); pPicture->SetImageID (2, CString (v.bstrVal)); v=p->getAttribute("picture4"); pPicture->SetImageID (3, CString (v.bstrVal)); v=p->getAttribute("picture5"); pPicture->SetImageID (4, CString (v.bstrVal)); v=p->getAttribute("picture6"); pPicture->SetImageID (5, CString (v.bstrVal)); v=p->getAttribute("picture7"); pPicture->SetImageID (6, CString (v.bstrVal)); v=p->getAttribute("picture8"); pPicture->SetImageID (7, CString (v.bstrVal)); v=p->getAttribute("style"); pPicture->GetObjStyle().Load (CString (v.bstrVal)); LoadXMLVariable (p, &pPicture->GetObjVar ()); pPicture->SetParentWnd (this); pMachine = pSynContainer->GetMachine (); pPicture->SetMachine (pMachine); AddCtrl (pPicture); return 0; } /* ** AddCtrl : */ void CAdamoSynPage::AddCtrl (CAdamoSynCtrl* pCtrl) { /* se il controllo che dobbiamo inserire e' un gruppo, inseriamolo per primo */ if (pCtrl->KindOf()==RSGroup) m_listCtrls.AddHead (pCtrl); else m_listCtrls.AddTail (pCtrl); } /* ** LoadXMLColumns : */ int CAdamoSynPage::LoadXMLColumns (ElementXmlPtr p, CAdamoSynGrid *pCtrl) { NodeListXmlPtr pRootChild; ElementXmlPtr pChild; COleVariant v; CString strType, strImage; stGridColumnData gcd; if (p->hasChildNodes()) { pRootChild = p->childNodes; int n=pRootChild->length, i=0; while (n>0) { pChild=pRootChild->Getitem (i); v=pChild->nodeName; if (CString (v.bstrVal)=="column") { v=pChild->getAttribute("type"); strType = CString (v.bstrVal); if (strType == "number") gcd.m_nType = LUA_TNUMBER; else if (strType == "boolean") gcd.m_nType = LUA_TBOOLEAN; else if (strType == "string") gcd.m_nType = LUA_TSTRING; v=pChild->getAttribute("image"); strImage = CString (v.bstrVal); if (v.vt!=VT_NULL) gcd.m_strImage = CString (v.bstrVal); v=pChild->text; gcd.m_strName=CString (v.bstrVal); pCtrl->SetColumnData (i, &gcd); } n--; i++; } } return 0; } /* ** LoadXMLVariable : */ int CAdamoSynPage::LoadXMLVariable (ElementXmlPtr p, CAdamoRSVarControl *pCtrl) { NodeListXmlPtr pRootChild; if (p->hasChildNodes()) { pRootChild = p->childNodes; int n=pRootChild->length, i=0; while (n>0) { ElementXmlPtr pVar = p->childNodes->Getitem (i); COleVariant v=pVar->nodeName; if (CString (v.bstrVal)=="Variable") { v=pVar->getAttribute("VariableName"); if (v.vt==VT_BSTR) { /* e' una variabile semplice */ pCtrl->GetObjVar ().m_strName=CString (v.bstrVal); v=pVar->getAttribute("VariableIndex"); pCtrl->GetObjVar ().Load (CString (v.bstrVal)); } v=pVar->getAttribute("Table"); if (v.vt==VT_BSTR) { /* e' una tabella */ pCtrl->GetObjVar ().m_strTable=CString (v.bstrVal); v=pVar->getAttribute("Field"); if (v.vt==VT_BSTR) pCtrl->GetObjVar ().m_strField=CString (v.bstrVal); v=pVar->getAttribute("KeyName"); if (v.vt==VT_BSTR) pCtrl->GetObjVar ().m_strKeyName=CString (v.bstrVal); v=pVar->getAttribute("KeyValue"); if (v.vt==VT_BSTR) pCtrl->GetObjVar ().m_strKeyValue=CString (v.bstrVal); } } n--; i++; } } return 0; } /* ** SetFormPosition : */ void CAdamoSynPage::SetFormPosition (CString strFormPosition) { CString str=GetXMLProperty (strFormPosition, "left"); str.TrimRight ("px"); m_rc.left=atoi (str); str=GetXMLProperty (strFormPosition, "top"); str.TrimRight ("px"); m_rc.top=atoi (str); str=GetXMLProperty (strFormPosition, "width"); str.TrimRight ("px"); m_rc.right=m_rc.left+atoi (str); str=GetXMLProperty (strFormPosition, "height"); str.TrimRight ("px"); m_rc.bottom=m_rc.top+atoi (str); } /* ** SetBackgroundImage : */ void CAdamoSynPage::SetBackgroundImage (CString strImageName) { m_strImageName = strImageName; if (m_strImageName != "") m_bBackgroundEnabled = true; } /* ** Resize : */ void CAdamoSynPage::Resize () { MoveWindow (m_rc.left, m_rc.top, m_rc.Width (), m_rc.Height (), true); CreateBackground (); } /* ** OnPaint : */ void CAdamoSynPage::OnPaint() { CPaintDC dc (this); CRect rect; GetClientRect( &rect ); CStdGrfx::draw3dFrame( &dc, rect ); } /* ** CreateBackground : */ int CAdamoSynPage::CreateBackground () { COLORREF m_nonClientBkgndCol = ::GetSysColor( COLOR_3DFACE ); CAdamoSynContainer *pSynContainer = GETSYNCONT(); BITMAP csBitmapSize; if (pSynContainer && m_bBackgroundEnabled) { pSynContainer->CaricaImmagine (m_strImageName, &m_hBckGround); ::GetObject(m_hBckGround, sizeof(csBitmapSize), &csBitmapSize); m_dwWidth = (DWORD)csBitmapSize.bmWidth; m_dwHeight = (DWORD)csBitmapSize.bmHeight; } return 0; } /* ** CreateWndCtrls : */ int CAdamoSynPage::CreateWndCtrls () { for (POSITION pos = m_listCtrls.GetHeadPosition (); pos; ) { CAdamoSynCtrl *pCtrl = (CAdamoSynCtrl *) m_listCtrls.GetNext (pos); switch (pCtrl->KindOf ()) { case RSButton : ((CAdamoSynButton *) pCtrl)->Create (); break; case RSInputText : ((CAdamoSynEdit *) pCtrl)->Create (); break; case RSInputCheck : ((CAdamoSynCheckBox *) pCtrl)->Create (); break; case RSInputRadio : ((CAdamoSynRadioButton *) pCtrl)->Create (); break; case RSGrid : ((CAdamoSynGrid *) pCtrl)->Create (); break; case RSGroup : ((CAdamoSynGroupBox *) pCtrl)->Create (); break; case RSLabel : ((CAdamoSynLabel *) pCtrl)->Create (); break; case RSList : ((CAdamoSynListBox *) pCtrl)->Create (); break; case RSCombo : ((CAdamoSynComboBox *) pCtrl)->Create (); break; case RSImage : ((CAdamoSynImage *) pCtrl)->Create (); break; case RSAx : ((CAdamoSynRTAx *) pCtrl)->Create (); break; case RSILed : ((CAdamoSynILed *) pCtrl)->Create (); break; case RSIAngularGauge : ((CAdamoSynIAngularGauge *) pCtrl)->Create (); break; case RSILinearGauge : ((CAdamoSynILinearGauge *) pCtrl)->Create (); break; case RSIDisplay : ((CAdamoSynIDisplay *) pCtrl)->Create (); break; case RSILabel : ((CAdamoSynILabel *) pCtrl)->Create (); break; case RSIPicture : ((CAdamoSynIPicture *) pCtrl)->Create (); break; } } return 0; } /* ** OnClick : */ void CAdamoSynPage::OnClick (UINT nID) { POSITION pos; bool bReturn = false; /* andiamo a cercare il bottone che ha cliccato */ for (pos = m_listCtrls.GetHeadPosition (); pos; ) { CAdamoSynCtrl *pCtrl = (CAdamoSynCtrl *) m_listCtrls.GetNext (pos); if (pCtrl->GetID () == nID) { switch (pCtrl->KindOf ()) { case RSButton : if (GestioneButtonClick (pCtrl)) bReturn = true; break; case RSInputCheck : GestioneCheckBoxClick (pCtrl); break; case RSInputRadio : GestioneRadioButtonClick (pCtrl); break; } } if (bReturn) break; } } /* ** OnSelChange : */ void CAdamoSynPage::OnSelChange (UINT nID) { POSITION pos; bool bReturn = false; /* andiamo a cercare il bottone che ha cliccato */ for (pos = m_listCtrls.GetHeadPosition (); pos; ) { CAdamoSynCtrl *pCtrl = (CAdamoSynCtrl *) m_listCtrls.GetNext (pos); if (pCtrl->GetID () == nID) { switch (pCtrl->KindOf ()) { case RSList : GestioneListBoxSelection (pCtrl); break; case RSCombo : GestioneComboBoxSelection (pCtrl); break; } } if (bReturn) break; } } /* ** GestioneListBoxSelection : */ void CAdamoSynPage::GestioneListBoxSelection (CAdamoSynCtrl* pCtrl) { CAdamoSynListBox *pListBox = (CAdamoSynListBox *) pCtrl; if (pListBox->IsAutoUpdate ()) pListBox->OnDownload (); } /* ** GestioneComboBoxSelection : */ void CAdamoSynPage::GestioneComboBoxSelection (CAdamoSynCtrl* pCtrl) { CAdamoSynComboBox *pComboBox = (CAdamoSynComboBox *) pCtrl; if (pComboBox->IsAutoUpdate ()) pComboBox->OnDownload (); } /* ** GestioneButtonClick : */ int CAdamoSynPage::GestioneButtonClick (CAdamoSynCtrl *pCtrl) { CAdamoSynButton *pBtn = (CAdamoSynButton *) pCtrl; int nR = 0; for (POSITION pos = m_listCtrls.GetHeadPosition (); pos; ) { CAdamoSynCtrl *pCtrl = (CAdamoSynCtrl *) m_listCtrls.GetNext (pos); if (pBtn->IsLoadActionEnabled ()) pCtrl->OnLoad (); if (pBtn->IsSaveActionEnabled ()) pCtrl->OnSave (); } if (pBtn->IsDownloadActionEnabled ()) OnDownload (); if (pBtn->IsChangePageActionEnabled ()) { OnChangePage (pBtn->GetNextPage ()); nR = -1; } return nR; } /* ** GestioneCheckBoxClick : */ int CAdamoSynPage::GestioneCheckBoxClick (CAdamoSynCtrl *pCtrl) { CAdamoSynCheckBox *pCheck = (CAdamoSynCheckBox *) pCtrl; pCheck->SetCheck (!pCheck->GetCheck ()); if (pCheck->IsAutoUpdate ()) pCheck->OnDownload (); return 0; } /* ** GestioneCheckBoxClick : */ int CAdamoSynPage::GestioneRadioButtonClick (CAdamoSynCtrl *pCtrl) { CAdamoSynRadioButton *pRadio = (CAdamoSynRadioButton *) pCtrl; pRadio->SetCheck (TRUE); if (pRadio->IsAutoUpdate ()) pRadio->OnDownload (); UnCheckRadioButton (pRadio); return 0; } /* ** UnCheckRadioButton : */ void CAdamoSynPage::UnCheckRadioButton (CAdamoSynCtrl *pRadioChecked) { for (POSITION pos = m_listCtrls.GetHeadPosition (); pos; ) { CAdamoSynCtrl *pCtrl = (CAdamoSynCtrl *) m_listCtrls.GetNext (pos); if (pCtrl->KindOf () == RSInputRadio) { CAdamoSynRadioButton *pRadio = (CAdamoSynRadioButton *) pCtrl; if (pRadio->GetID () != pRadioChecked->GetID ()) { if (pRadio->GetName () == pRadioChecked->GetName ()) { pRadio->SetCheck (FALSE); if (pRadio->IsAutoUpdate ()) pRadio->OnDownload (); } } } } } /* ** OnDownload : */ void CAdamoSynPage::OnDownload () { CAdamoSynContainer *pSynContainer = GETSYNCONT(); pSynContainer->OnDownload (); } /* ** CreateXMLInput : */ int CAdamoSynPage::CreateXMLInput (ElementXmlPtr p) { COleVariant v=p->getAttribute("type"); if (v.vt==VT_BSTR) { CString strType=CString (v.bstrVal); /* if (strType=="password") return CreateXMLInputText (p); else */ if (strType=="text") return CreateXMLInputText (p); else if (strType=="radio") return CreateXMLInputRadio (p); else if (strType=="checkbox") return CreateXMLInputCheckBox (p); } return 0; } /* ** CreateXMLInputCheckBox : */ int CAdamoSynPage::CreateXMLInputCheckBox (ElementXmlPtr p) { CAdamoSynCheckBox *pCheck=new CAdamoSynCheckBox; COleVariant v=p->getAttribute("name"); pCheck->SetName (CString (v.bstrVal)); v=p->getAttribute("value"); pCheck->SetValue (CString (v.bstrVal)); v=p->getAttribute("id"); pCheck->SetID (atoi (CString (v.bstrVal))); v=p->getAttribute("tabindex"); pCheck->SetTabIndex (atoi (CString (v.bstrVal))); v=p->getAttribute("style"); pCheck->GetObjStyle().Load (CString (v.bstrVal)); v=p->getAttribute("checked"); pCheck->SetChecked (CString (v.bstrVal)=="true"); v=p->getAttribute("autoupdate"); pCheck->SetAutoUpdate(CString (v.bstrVal)=="true"); LoadXMLVariable (p, &pCheck->GetObjVar ()); pCheck->SetParentWnd (this); AddCtrl (pCheck); return 0; } /* ** CreateXMLInputImage : */ int CAdamoSynPage::CreateXMLInputImage (ElementXmlPtr p) { CString str; char *pColor; CAdamoSynImage *pIT=new CAdamoSynImage; COleVariant v=p->getAttribute("src"); pIT->SetIDImage (CString (v.bstrVal)); v=p->getAttribute("checked"); pIT->SetStretch (CString (v.bstrVal)=="true"); v=p->getAttribute("transparent"); pIT->SetTransparent (CString (v.bstrVal)=="true"); v=p->getAttribute("transparentcolor"); str = CString (v.bstrVal); pColor = str.GetBuffer (); if (pColor[0] == '#') pIT->SetTransparentColor (TranslateRGB (pColor + 1)); v=p->getAttribute("id"); pIT->SetID (atoi (CString (v.bstrVal))); v=p->getAttribute("tabindex"); pIT->SetTabIndex (atoi (CString (v.bstrVal))); v=p->getAttribute("style"); pIT->GetObjStyle().Load (CString (v.bstrVal)); pIT->SetParentWnd (this); AddCtrl (pIT); return 0; } /* ** CreateXMLInputRadio : */ int CAdamoSynPage::CreateXMLInputRadio (ElementXmlPtr p) { CAdamoSynRadioButton *pRadio=new CAdamoSynRadioButton; COleVariant v=p->getAttribute("name"); pRadio->SetName (CString (v.bstrVal)); v=p->getAttribute("value"); pRadio->SetValue (CString (v.bstrVal)); v=p->getAttribute("id"); pRadio->SetID (atoi (CString (v.bstrVal))); v=p->getAttribute("tabindex"); pRadio->SetTabIndex (atoi (CString (v.bstrVal))); v=p->getAttribute("style"); pRadio->GetObjStyle().Load (CString (v.bstrVal)); v=p->getAttribute("group"); pRadio->SetGroup (CString (v.bstrVal)); v=p->getAttribute("checked"); pRadio->SetChecked (CString (v.bstrVal)=="true"); v=p->getAttribute("autoupdate"); pRadio->SetAutoUpdate(CString (v.bstrVal)=="true"); LoadXMLVariable (p, &pRadio->GetObjVar ()); pRadio->SetParentWnd (this); AddCtrl (pRadio); return 0; } /* ** ClearCtrls : */ void CAdamoSynPage::ClearCtrls () { CAdamoSynCtrl* pCtrl; for (POSITION pos = m_listCtrls.GetHeadPosition (); pos; ) { pCtrl = (CAdamoSynCtrl*) m_listCtrls.GetNext (pos); delete pCtrl; } m_listCtrls.RemoveAll (); } /* ** OnChangePage : */ void CAdamoSynPage::OnChangePage (CString strPage) { if (strPage != "" && strPage != m_strName) { CAdamoSynContainer *pSynContainer = GETSYNCONT(); pSynContainer->LoadPage (strPage); } } /* ** InitialLoad : */ void CAdamoSynPage::OnLoad () { for (POSITION pos = m_listCtrls.GetHeadPosition (); pos; ) { CAdamoSynCtrl *pCtrl = (CAdamoSynCtrl *) m_listCtrls.GetNext (pos); pCtrl->OnLoad (); } } /* ** CreateXMLInputText : */ int CAdamoSynPage::CreateXMLInputText (ElementXmlPtr p) { eEditType e = eLetters; CAdamoSynEdit *pEdit=new CAdamoSynEdit; COleVariant v=p->getAttribute("name"); pEdit->SetName (CString (v.bstrVal)); v=p->getAttribute("value"); pEdit->SetValue (CString (v.bstrVal)); v=p->getAttribute("id"); pEdit->SetID (atoi (CString (v.bstrVal))); v=p->getAttribute("tabindex"); pEdit->SetTabIndex (atoi (CString (v.bstrVal))); v=p->getAttribute("style"); pEdit->GetObjStyle().Load (CString (v.bstrVal)); v=p->getAttribute("autoupdate"); pEdit->SetAutoUpdate(CString (v.bstrVal)=="true"); LoadXMLVariable (p, &pEdit->GetObjVar ()); v=p->getAttribute("mode"); CString str = CString (v.bstrVal); if (str == "numbers") e = eNumbers; else if (str == "float") e = eFloat; else if (str == "hex") e = eHex; else if (str == "letters") e = eLetters; pEdit->SetType (e); pEdit->SetParentWnd (this); AddCtrl (pEdit); return 0; } /* ** CreateXMLComboList : */ int CAdamoSynPage::CreateXMLComboList (ElementXmlPtr p) { COleVariant v=p->getAttribute("size"); int nSize=atoi (CString (v.bstrVal)); if (nSize==1) CreateXMLCombo (p); else CreateXMLList (p); return 0; } /* ** CreateXMLCombo : */ int CAdamoSynPage::CreateXMLCombo (ElementXmlPtr p) { CAdamoSynComboBox *pIT=new CAdamoSynComboBox; COleVariant v=p->getAttribute("name"); pIT->SetName (CString (v.bstrVal)); v=p->getAttribute("id"); pIT->SetID (atoi (CString (v.bstrVal))); v=p->getAttribute("tabindex"); pIT->SetTabIndex (atoi (CString (v.bstrVal))); v=p->getAttribute("style"); pIT->GetObjStyle().Load (CString (v.bstrVal)); LoadXMLOptions (p, pIT, true); LoadXMLVariable (p, &pIT->GetObjVar ()); pIT->SetParentWnd (this); AddCtrl (pIT); return 0; } /* ** CreateXMLList : */ int CAdamoSynPage::CreateXMLList (ElementXmlPtr p) { CAdamoSynListBox *pIT=new CAdamoSynListBox; COleVariant v=p->getAttribute("name"); pIT->SetName (CString (v.bstrVal)); v=p->getAttribute("id"); pIT->SetID (atoi (CString (v.bstrVal))); v=p->getAttribute("tabindex"); pIT->SetTabIndex (atoi (CString (v.bstrVal))); v=p->getAttribute("size"); pIT->SetSize (atoi (CString (v.bstrVal))); v=p->getAttribute("style"); pIT->GetObjStyle().Load (CString (v.bstrVal)); LoadXMLOptions (p, pIT, false); LoadXMLVariable (p, &pIT->GetObjVar ()); pIT->SetParentWnd (this); AddCtrl (pIT); return 0; } /* ** LoadXMLOptions : */ int CAdamoSynPage::LoadXMLOptions (ElementXmlPtr p, CAdamoSynCtrl *pCtrl, bool bIsCombo) { NodeListXmlPtr pRootChild; ElementXmlPtr pChild; struct stRSOpzioni stOpzioni; COleVariant v; if (p->hasChildNodes()) { pRootChild = p->childNodes; int n=pRootChild->length, i=0; while (n>0) { pChild=pRootChild->Getitem (i); v=pChild->nodeName; if (CString (v.bstrVal)=="option") { v=pChild->getAttribute("selected"); stOpzioni.m_bSelected=CString (v.bstrVal)=="true"; v=pChild->getAttribute("value"); if (v.vt!=VT_NULL) stOpzioni.strValue=CString (v.bstrVal); v=pChild->text; stOpzioni.strOpzione=CString (v.bstrVal); bIsCombo ? ((CAdamoSynComboBox *)pCtrl)->AddRSOption (&stOpzioni, -1) : ((CAdamoSynListBox *)pCtrl)->AddRSOption (&stOpzioni, -1); } n--; i++; } } return 0; } /* ** OnTimer : */ int CAdamoSynPage::OnTimer () { for (POSITION pos = m_listCtrls.GetHeadPosition (); pos; ) { CAdamoSynCtrl *pCtrl = (CAdamoSynCtrl *) m_listCtrls.GetNext (pos); pCtrl->OnTimer (); } return 0; } /* ** OnEraseBkgnd : */ BOOL CAdamoSynPage::OnEraseBkgnd(CDC* pDC) { CRect rWnd; int nX = 0; int nY = 0; BOOL bRetValue = CWnd::OnEraseBkgnd(pDC); // If there is a bitmap loaded if (m_hBckGround.GetSafeHandle ()) { GetClientRect(rWnd); CDC dcMemoryDC; CBitmap bmpMemoryBitmap; CBitmap* pbmpOldMemoryBitmap = NULL; dcMemoryDC.CreateCompatibleDC(pDC); bmpMemoryBitmap.CreateCompatibleBitmap(pDC, rWnd.Width(), rWnd.Height()); pbmpOldMemoryBitmap = (CBitmap*)dcMemoryDC.SelectObject(&bmpMemoryBitmap); // Fill background dcMemoryDC.FillSolidRect(rWnd, pDC->GetBkColor()); CDC dcTempDC; HBITMAP hbmpOldTempBitmap = NULL; dcTempDC.CreateCompatibleDC(pDC); hbmpOldTempBitmap = (HBITMAP)::SelectObject(dcTempDC.m_hDC, m_hBckGround); dcMemoryDC.BitBlt(0, 0, m_dwWidth, m_dwHeight, &dcTempDC, 0, 0, SRCCOPY); if (!m_bKilling) OnEraseBackGround (&dcMemoryDC); pDC->BitBlt(0, 0, rWnd.Width(), rWnd.Height(), &dcMemoryDC, 0, 0, SRCCOPY); ::SelectObject(dcTempDC.m_hDC, hbmpOldTempBitmap); dcMemoryDC.SelectObject(pbmpOldMemoryBitmap); } // if return bRetValue; } /* ** OnEraseBackGround : */ void CAdamoSynPage::OnEraseBackGround (CDC* pDC) { POSITION pos; bool bReturn = false; /* andiamo a cercare il bottone che ha cliccato */ for (pos = m_listCtrls.GetHeadPosition (); pos; ) { CAdamoSynCtrl *pCtrl = (CAdamoSynCtrl *) m_listCtrls.GetNext (pos); switch (pCtrl->KindOf ()) { case RSButton : ((CAdamoSynButton *)pCtrl)->OnEraseBackGround (pDC); break; case RSImage : ((CAdamoSynImage *)pCtrl)->OnEraseBackGround (pDC); break; case RSIPicture : ((CAdamoSynIPicture *)pCtrl)->OnEraseBackGround (pDC); break; } } }
[ "maurizio.mottarella@kinemanet.it" ]
maurizio.mottarella@kinemanet.it
eb636e8cd0f1d7e7ef19d000cc688b7c5ccfc6ff
8262a782e189aed545a805ac67809a141f75a669
/ALLIZZWELL .cpp
358751f85d902e57b2b9ca8aadf296afb39ce208
[]
no_license
rjrks/Spoj
7e245e877a9924a0bb4661be39121832ddda1fc7
a3236ee6a773d08078f13e46f5eee40b638d461b
refs/heads/master
2020-04-06T04:55:36.584359
2015-07-13T19:23:55
2015-07-13T19:24:17
35,376,048
0
0
null
null
null
null
UTF-8
C++
false
false
3,488
cpp
// // Created by Rohan on 30/08/14. // Copyright (c) 2014 Rohan. All rights reserved. // #include <math.h> #include <iostream> #include <vector> #include <string.h> #include <sstream> #include <stdio.h> #include <stdlib.h> #include <stack> #include <list> #include <algorithm> #include <queue> class node{ public: char data; int xcord; int ycord; bool visited; node(){ visited=false; } }; char str[]={'L','L','I','Z','Z','W','E','L','L'}; node in[110][110]; std::stack<int>cnt; std::stack<node>q; bool found=false; void dfs(int rx,int ry){ if(cnt.top()==9 || found){found=true; return;} else if(q.empty())return; int k=cnt.top(); if(in[rx+1][ry].data==str[k] && !in[rx+1][ry].visited){ q.push(in[rx+1][ry]);cnt.push(1+k); in[rx+1][ry].visited=true; dfs(rx+1,ry);} if(in[rx+1][ry-1].data==str[k] && !in[rx+1][ry-1].visited){ q.push(in[rx+1][ry-1]);cnt.push(1+k); in[rx+1][ry-1].visited=true;dfs(rx+1,ry-1);} if(in[rx][ry-1].data==str[k] && !in[rx][ry-1].visited){ q.push(in[rx][ry-1]);cnt.push(1+k); in[rx][ry-1].visited=true;dfs(rx,ry-1);} if(in[rx-1][ry-1].data==str[k] && !in[rx-1][ry-1].visited){q.push(in[rx-1][ry-1]);cnt.push(1+k); in[rx-1][ry-1].visited=true;dfs(rx-1,ry-1);} if(in[rx-1][ry].data==str[k] && !in[rx-1][ry].visited){q.push(in[rx-1][ry]);cnt.push(1+k); in[rx-1][ry].visited=true;dfs(rx-1,ry);} if(in[rx-1][ry+1].data==str[k] && !in[rx-1][ry+1].visited){q.push(in[rx-1][ry+1]);cnt.push(1+k); in[rx-1][ry+1].visited=true;dfs(rx-1,ry+1);} if(in[rx][ry+1].data==str[k] && !in[rx][ry+1].visited){q.push(in[rx][ry+1]);cnt.push(1+k); in[rx][ry+1].visited=true;dfs(rx,ry+1);} if(in[rx+1][ry+1].data==str[k] && !in[rx+1][ry+1].visited){q.push(in[rx+1][ry+1]);cnt.push(1+k); in[rx+1][ry+1].visited=true;dfs(rx+1,ry+1);} cnt.pop(); int x=q.top().xcord; int y=q.top().ycord; in[x][y].visited=false; q.pop(); if(q.empty())return; } using namespace std; int main(){ int tc; cin>>tc; for(int i=0;i<tc;i++){ int r,c; cin>>r>>c; for(int i=0;i<=c+1;i++){in[0][i].data=0; in[r+1][i].data=0; in[0][i].xcord=0; in[0][i].ycord=i; in[r+1][i].xcord=r+1; in[r+1][i].ycord=i; } for(int i=0;i<=r+1;i++){in[i][0].data=0; in[i][c+1].data=0; in[i][0].xcord=i; in[i][0].ycord=0; in[i][c+1].xcord=i; in[i][c+1].ycord=c+1;} for(int i=1;i<=r;i++){ for(int j=1;j<=c;j++){ cin>>in[i][j].data; in[i][j].xcord=i; in[i][j].ycord=j; in[i][j].visited=false; } } //--------INPUT COMPLETE---------- while(!cnt.empty())cnt.pop(); while(!q.empty())q.pop(); int rx,ry; for(int i=1;i<=r;i++){ for(int j=1;j<=c;j++){ rx=i; ry=j; if(in[rx][ry].data=='A'){ q.push(in[rx][ry]); cnt.push(0); dfs(rx,ry); } if(found)break; } if(found)break; } if(found)cout<<"YES"; else cout<<"NO"; cout<<endl; found=false; } }
[ "rohanjain.2209@gmail.com" ]
rohanjain.2209@gmail.com
8a6fac2a801a1ca4988399dd77407b20779273d2
86c63c9a4861b429fbca39accd95741a30f137af
/src/gui/clifstoreview.cpp
17e1460fff3e5cae0df479276a16b94bad6134fc
[]
no_license
cgarbe/clif
968eb1ca41856c454aa97631c848a71d80db08df
d05dc97771101e249e42bd18ec12a58799aef156
refs/heads/master
2021-01-21T00:30:09.530203
2016-02-24T09:02:15
2016-02-24T09:02:15
52,428,564
0
0
null
2016-02-24T09:02:59
2016-02-24T09:02:59
null
UTF-8
C++
false
false
5,311
cpp
#include "clifstoreview.hpp" #include <QtGui/QtGui> #include <QApplication> #include <QSplitter> #include <QTimer> #include <QSlider> #include <QVBoxLayout> #include <QHBoxLayout> #include <QComboBox> #include <QCheckBox> #include <QDoubleSpinBox> #include "clifscaledimageview.hpp" #include "clifepiview.hpp" #include "clif_qt.hpp" #include "dataset.hpp" #include "subset3d.hpp" #include "preproc.hpp" namespace clif { clifStoreView::clifStoreView(Datastore *store, QWidget* parent) : QWidget(parent) { QHBoxLayout *hbox; QVBoxLayout *_vbox; QWidget *w; QSlider *_slider; _store = store; _vbox = new QVBoxLayout(this); setLayout(_vbox); _view = new clifScaledImageView(this); _vbox->addWidget(_view); ///////////////////// SLIDER ///////////////////// hbox = new QHBoxLayout(this); w = new QWidget(this); _vbox ->addWidget(w); w->setLayout(hbox); _sel = new QComboBox(this); _sel->addItem("raw", QVariant(0)); _sel->addItem("demosaic", QVariant(Improc::DEMOSAIC)); _sel->addItem("gray", QVariant(Improc::CVT_GRAY)); _sel->addItem("undistort", QVariant(Improc::UNDISTORT)); _sel->setCurrentIndex(0); hbox->addWidget(_sel); _slider = new QSlider(Qt::Horizontal, this); _slider->setTickInterval(1); _slider->setTickPosition(QSlider::TicksBelow); _slider->setMaximum(_store->imgCount()-1); hbox->addWidget(_slider); ///////////////////// RANGE ///////////////////// hbox = new QHBoxLayout(this); w = new QWidget(this); _vbox ->addWidget(w); w->setLayout(hbox); _try_out_new_reader = new QCheckBox("experimental flexibel reader", this); connect(_try_out_new_reader, SIGNAL(stateChanged(int)), this, SLOT(rangeStateChanged(int))); hbox->addWidget(_try_out_new_reader); _range_ck = new QCheckBox("scale for range", this); connect(_range_ck, SIGNAL(stateChanged(int)), this, SLOT(rangeStateChanged(int))); hbox->addWidget(_range_ck); _sp_min = new QDoubleSpinBox(this); _sp_min->setRange(-4.2949673e9,4.2949673e9); _sp_min->setDisabled(true); connect(_sp_min, SIGNAL(valueChanged(double)), this, SLOT(queue_load_img())); hbox->addWidget(_sp_min); _sp_max = new QDoubleSpinBox(this); _sp_max->setRange(-4.2949673e9,4.2949673e9); _sp_max->setDisabled(true); connect(_sp_max, SIGNAL(valueChanged(double)), this, SLOT(queue_load_img())); hbox->addWidget(_sp_max); _qimg = new QImage(); _show_idx = 0; load_img(); connect(_slider, SIGNAL(valueChanged(int)), this, SLOT(queue_sel_img(int))); connect(_sel, SIGNAL(currentIndexChanged(int)), this, SLOT(queue_load_img())); ///////////////////// DEPTH SLIDER ///////////////////// _depth_slider = new QSlider(Qt::Horizontal, this); _vbox->addWidget(_depth_slider); _depth_slider->setTickInterval(50); _depth_slider->setTickPosition(QSlider::TicksBelow); _depth_slider->setMinimum(50); _depth_slider->setMaximum(2000); _depth_slider->setValue(2000); connect(_depth_slider, SIGNAL(valueChanged(int)), this, SLOT(queue_load_img())); } clifStoreView::~clifStoreView() { delete _qimg; } void clifStoreView::queue_sel_img(int n) { _show_idx = n; queue_load_img(); } void clifStoreView::rangeStateChanged(int s) { if (s == Qt::Checked) { _sp_min->setDisabled(false); _sp_max->setDisabled(false); } else { _sp_min->setDisabled(true); _sp_max->setDisabled(true); } queue_load_img(); } void clifStoreView::queue_load_img() { if (!_timer) { _timer = new QTimer(this); connect(_timer, SIGNAL(timeout()), this, SLOT(load_img())); _timer->setSingleShot(true); if (!_rendering) _timer->start(0); } } void clifStoreView::load_img() { if (_timer) _timer = NULL; //FIXME disable for now - add flexibel read configuration to check! //if (_curr_idx == _show_idx && _curr_flags == _sel->itemData(_sel->currentIndex()).value<int>() && _range_ck->checkState() != Qt::Checked) //return; _curr_flags = _sel->itemData(_sel->currentIndex()).value<int>(); _curr_idx = _show_idx; //FIXME make this option! _curr_flags |= NO_DISK_CACHE; if (_try_out_new_reader->checkState() == Qt::Checked) { Idx pos(_store->dims()); Idx sub = {0, 3}; //x and imgs -> an epi :-) pos[1] = _curr_idx; clif::Mat m; _store->read_full_subdims(m, pos, sub); *_qimg = clifMatToQImage(cvMat(m)); } else { std::vector<int> n_idx(_store->dims(),0); n_idx[3] = _curr_idx; //FIXME hack to access additional dimensions for(int i = 3;i<n_idx.size()-1;i++) { n_idx[i+1] += n_idx[i] / _store->extent()[i]; n_idx[i] = n_idx[i] % _store->extent()[i]; } double d = std::numeric_limits<float>::quiet_NaN(); if (_depth_slider) { d = _depth_slider->value(); _curr_flags |= NO_MEM_CACHE; } else _curr_flags &= ~NO_MEM_CACHE; if (_range_ck->checkState() == Qt::Checked) readQImage(_store, n_idx, *_qimg, _curr_flags, d, _sp_min->value(), _sp_max->value()); else readQImage(_store, n_idx, *_qimg, _curr_flags, d); } _view->setImage(*_qimg); //force results of this slow operation to be displayed _rendering = true; qApp->processEvents(); _rendering = false; if (_timer) _timer->start(0); } }
[ "hendrik.siedelmann@googlemail.com" ]
hendrik.siedelmann@googlemail.com
5dd1154cfc8a28aae3300d8e1518a78ccd59a4d4
818bad8591d3212ebc6284f2f49e06a06263f3b7
/ccc/NetAssistant/NetToolFrameWnd.h
24df90207aaf86b45f1b51fac3a1435ab400278d
[]
no_license
wanxianyao/hello-world
781b85eeef571ee97ced832bf5797bbc5ce35592
dda7cf50daa19ae9af95f0010f870ca94fa30c60
refs/heads/master
2020-12-25T16:55:02.973660
2018-11-26T15:28:33
2018-11-26T15:28:33
36,845,044
0
0
null
2015-06-04T05:31:28
2015-06-04T03:11:55
null
UTF-8
C++
false
false
1,911
h
#pragma once #include "NetManage.h" #include "TcpClient.h" #include "TcpServer.h" #include <mutex> #define RECVLEN 1024 class CNetToolFrameWnd : public CWindowWnd, public INotifyUI { public: CNetToolFrameWnd(); ~CNetToolFrameWnd(); LPCTSTR GetWindowClassName() const { return _T("UIMainFrame"); }; UINT GetClassStyle() const { return CS_DBLCLKS; }; void OnFinalMessage(HWND /*hWnd*/) { delete this; }; void Init(); void OnPrepare(); void Notify(TNotifyUI& msg); LRESULT OnCreate(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled); LRESULT OnClose(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled); LRESULT OnDestroy(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled); LRESULT OnNcActivate(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled); LRESULT OnNcCalcSize(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled); LRESULT OnNcPaint(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled); LRESULT OnNcHitTest(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled); LRESULT OnSize(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled); LRESULT OnGetMinMaxInfo(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled); LRESULT OnSysCommand(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled); LRESULT HandleMessage(UINT uMsg, WPARAM wParam, LPARAM lParam); static int CALLBACK RecvCliCb(SOCKET fd, char* sRecv, int len, void* pParma); static int CALLBACK ExitCb(SOCKET fd, void* pParma); static int CALLBACK RecvCb(SOCKET fd, char* sRecv, int len, void* pParma); static int CALLBACK AcceptCb(SOCKET fd, void* pParma); public: CPaintManagerUI m_pm; private: CButtonUI* m_pCloseBtn; CButtonUI* m_pMaxBtn; CButtonUI* m_pRestoreBtn; CButtonUI* m_pMinBtn; std::mutex m_combLock; bool m_bVisible; CNetManage m_Net; CTcpServer* m_pTcpServer; CTcpClient* m_pTcpClient; char* m_pRecvbuf; int m_nTotalRecv; int m_nSend; };
[ "humphreywan@etekcity.com.cn" ]
humphreywan@etekcity.com.cn
a7859a69735ac8758027aa360c4a51d183af267a
162424b68a0e5a2a8521a992b40d8ba2d5e8c742
/tensorflow_serving/servables/tensorflow/session_bundle_factory.cc
b537251fc67720f0c646dad46ea6e17d785be02a
[ "Apache-2.0" ]
permissive
gvanhorn38/serving
4bdefdc08139e25280a7f79f994272d90103da30
38775b2c266d2a00de5e4b2099975d2fc3296be4
refs/heads/master
2021-01-21T03:45:23.194726
2016-08-03T15:37:09
2016-08-03T15:37:09
63,703,052
1
0
null
2016-07-19T14:53:37
2016-07-19T14:53:37
null
UTF-8
C++
false
false
6,843
cc
/* Copyright 2016 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow_serving/servables/tensorflow/session_bundle_factory.h" #include "google/protobuf/wrappers.pb.h" #include "tensorflow/core/lib/core/status.h" #include "tensorflow/core/lib/io/path.h" #include "tensorflow/core/platform/regexp.h" #include "tensorflow/core/platform/types.h" #include "tensorflow/core/public/session_options.h" #include "tensorflow_serving/resources/resource_values.h" #include "tensorflow_serving/servables/tensorflow/serving_session.h" #include "tensorflow_serving/servables/tensorflow/session_bundle_config.pb.h" namespace tensorflow { namespace serving { namespace { SessionOptions GetSessionOptions(const SessionBundleConfig& config) { SessionOptions options; options.target = config.session_target(); options.config = config.session_config(); return options; } } // namespace constexpr double SessionBundleFactory::kResourceEstimateRAMMultiplier; constexpr int SessionBundleFactory::kResourceEstimateRAMPadBytes; Status SessionBundleFactory::Create( const SessionBundleConfig& config, std::unique_ptr<SessionBundleFactory>* factory) { std::shared_ptr<Batcher> batcher; // Populate 'batcher' if batching is configured. if (config.has_batching_parameters()) { const BatchingParameters& batching_config = config.batching_parameters(); if (!batching_config.allowed_batch_sizes().empty()) { // Verify that the last allowed batch size matches the max batch size. const int last_allowed_size = batching_config.allowed_batch_sizes( batching_config.allowed_batch_sizes().size() - 1); const int max_size = batching_config.has_max_batch_size() ? batching_config.max_batch_size().value() : Batcher::QueueOptions().max_batch_size; if (last_allowed_size != max_size) { return errors::InvalidArgument( "Last entry in allowed_batch_sizes must match max_batch_size; last " "entry was ", last_allowed_size, "; expected ", max_size); } } Batcher::Options options; if (batching_config.has_num_batch_threads()) { options.num_batch_threads = batching_config.num_batch_threads().value(); } if (batching_config.has_thread_pool_name()) { options.thread_pool_name = batching_config.thread_pool_name().value(); } TF_RETURN_IF_ERROR(Batcher::Create(options, &batcher)); } factory->reset(new SessionBundleFactory(config, batcher)); return Status::OK(); } Status SessionBundleFactory::EstimateResourceRequirement( const string& path, ResourceAllocation* estimate) const { const char kVariablesFilenameRegexp[] = "export(-[0-9]+-of-[0-9]+)?"; if (!Env::Default()->FileExists(path)) { return errors::NotFound("Nonexistent export path: ", path); } uint64 total_variable_file_size = 0; std::vector<string> files; TF_RETURN_IF_ERROR(Env::Default()->GetChildren(path, &files)); for (const string& file : files) { if (!RE2::FullMatch(file, kVariablesFilenameRegexp)) { continue; } const string file_path = io::JoinPath(path, file); uint64 file_size; TF_RETURN_IF_ERROR(Env::Default()->GetFileSize(file_path, &file_size)); total_variable_file_size += file_size; } const uint64 ram_requirement = total_variable_file_size * kResourceEstimateRAMMultiplier + kResourceEstimateRAMPadBytes; ResourceAllocation::Entry* ram_entry = estimate->add_resource_quantities(); Resource* ram_resource = ram_entry->mutable_resource(); ram_resource->set_device(device_types::kMain); ram_resource->set_kind(resource_kinds::kRamBytes); ram_entry->set_quantity(ram_requirement); return Status::OK(); } Status SessionBundleFactory::CreateSessionBundle( const string& path, std::unique_ptr<SessionBundle>* bundle) { bundle->reset(new SessionBundle); TF_RETURN_IF_ERROR(LoadSessionBundleFromPath(GetSessionOptions(this->config_), path, bundle->get())); if (this->config_.has_batching_parameters()) { TF_RETURN_IF_ERROR(this->WrapSessionForBatching(bundle->get())); } else { (*bundle)->session.reset( new ServingSessionWrapper(std::move((*bundle)->session))); } return Status::OK(); } SessionBundleFactory::SessionBundleFactory( const SessionBundleConfig& config, std::shared_ptr<Batcher> batch_scheduler) : config_(config), batch_scheduler_(batch_scheduler) {} Status SessionBundleFactory::WrapSessionForBatching(SessionBundle* bundle) { LOG(INFO) << "Wrapping SessionBundle session to perform batch processing"; if (batch_scheduler_ == nullptr) { return errors::Internal("batch_scheduler_ not set"); } if (!config_.has_batching_parameters()) { return errors::Internal("No batching parameters"); } const BatchingParameters& batching_config = config_.batching_parameters(); Batcher::QueueOptions queue_options; if (batching_config.has_max_batch_size()) { queue_options.max_batch_size = batching_config.max_batch_size().value(); } if (batching_config.has_batch_timeout_micros()) { queue_options.batch_timeout_micros = batching_config.batch_timeout_micros().value(); } if (batching_config.has_max_enqueued_batches()) { queue_options.max_enqueued_batches = batching_config.max_enqueued_batches().value(); } BatchingSessionOptions batching_session_options; for (int allowed_batch_size : batching_config.allowed_batch_sizes()) { batching_session_options.allowed_batch_sizes.push_back(allowed_batch_size); } auto create_queue = [this, queue_options]( std::function<void(std::unique_ptr<Batch<BatchingSessionTask>>)> process_batch_callback, std::unique_ptr<BatchScheduler<BatchingSessionTask>>* batch_scheduler) { TF_RETURN_IF_ERROR(this->batch_scheduler_->AddQueue( queue_options, process_batch_callback, batch_scheduler)); return Status::OK(); }; TF_RETURN_IF_ERROR( CreateBatchingSession(batching_session_options, create_queue, std::move(bundle->session), &bundle->session)); return Status::OK(); } } // namespace serving } // namespace tensorflow
[ "gardener@tensorflow.org" ]
gardener@tensorflow.org
cdb65c03ce9a911dd090ff8081b33160c9fcaf6c
7ef4e3c493a566c3625f8e7216be88bdd7a7d6db
/visual studio/Prime Factor Generator/Prime Factor Generator/menu.cpp
0147f277f81325bf74c9ab7ff52440f7940a9f3d
[]
no_license
Nodrokov/prime_number_generator
df37de81bfba665ce657a7b39b99832731b634b8
6a96620e4ddac403dd54c3849be5680a616307f3
refs/heads/master
2020-05-25T09:44:31.242784
2014-08-21T19:11:27
2014-08-21T19:11:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
523
cpp
#include <iostream> #include "prime.h" int main() { using std::cout; using std::cin; int userChoice=0; cout<<"What would you like to do?\n\n"<<"list Mersenne primes [1] or list all primes [2]\n"; cin>>userChoice; if(userChoice==1) { /*cout<<"\nI'm sorry, this mode is not yet finished. Please select another mode.\n\n\n"; main();*/ mersenne(); return 0; } if(userChoice==2) { allPrimes(); return 0; } else { cout<<"\n"<<userChoice<<" is not a valid choice. Please choose again."; main(); } }
[ "nodrokov@gmail.com" ]
nodrokov@gmail.com
c3aab78e0d232b00a51a10a6d923adf9f3ca4994
2063e69c14037ecab5d318f952cec9ffbee71929
/RobonautsLibrary/src/RSpeedControllerSparkMaxCan.cpp
0aaefad38aed7a168177e81ade852eae64d1a2ee
[]
no_license
xKIAxMaDDoG/everyBotReference
4dc8c883f92a9856ae016593b19a519ad30b76bc
1e532be3e7a2292f1564403d370f7235bee9e80a
refs/heads/master
2021-02-14T03:37:47.358837
2020-03-03T23:30:54
2020-03-03T23:30:54
244,763,767
0
0
null
null
null
null
UTF-8
C++
false
false
9,747
cpp
/******************************************************************************* * * File: RAbsPosSensor.cpp * * This file contains the definition of a class for interacting with an * Absolute Position Sensor. * * Written by: * The Robonauts * FRC Team 118 * NASA, Johnson Space Center * Clear Creek Independent School District * ******************************************************************************/ #include "frc/shuffleboard/Shuffleboard.h" #include "RobonautsLibrary/RSpeedControllerSparkMaxCan.h" #include "gsu/Advisory.h" #include "RobonautsLibrary/RobotUtil.h" /****************************************************************************** * * Create an interface of RSpeedControllerCan, get an APS plugged into the specified channel. * * @param channel the channel or port that the pot is in * ******************************************************************************/ RSpeedControllerSparkMaxCan::RSpeedControllerSparkMaxCan(int port_device) : RSpeedController(port_device) , m_controller(port_device, rev::CANSparkMaxLowLevel::MotorType::kBrushless) , m_device_id(port_device) , m_pidController(m_controller.GetPIDController()) , m_encoder(m_controller.GetEncoder()) { m_pidController.SetOutputRange(-1.0, 1.0); } RSpeedControllerSparkMaxCan::~RSpeedControllerSparkMaxCan() {} void RSpeedControllerSparkMaxCan::ProcessXML(tinyxml2::XMLElement *xml) { tinyxml2::XMLElement *elem; elem = xml->FirstChildElement("encoder"); if (elem != nullptr) { //SetFeedbackDevice(RSpeedControllerSparkMaxCan :: ); double scale = 1.0; elem->QueryDoubleAttribute("scale", &scale); SensorOutputPerCount(scale); } double kf = 0.001; double kp = 0.0; double ki = 0.0; double kd = 0.0; double iz = 0.0; double cruise_velocity = 0.0; double acceleration = 0.0; elem = xml->FirstChildElement("pid"); if (elem != nullptr) { elem->QueryDoubleAttribute("kf", &kf); elem->QueryDoubleAttribute("kp", &kp); elem->QueryDoubleAttribute("ki", &ki); elem->QueryDoubleAttribute("kd", &kd); elem->QueryDoubleAttribute("iz", &iz); elem->QueryDoubleAttribute("cruise_velocity", &cruise_velocity); elem->QueryDoubleAttribute("acceleration", &acceleration); SetF(kf); SetP(kp); SetI(ki); SetD(kd); if (iz != 0.0) { SetIZone(iz); } if (cruise_velocity != 0.0) { SetCruiseVelocity(cruise_velocity); } if (acceleration != 0.0) { SetAcceleration(acceleration); } } bool invert_motor = false; bool brake_mode = false; xml->QueryBoolAttribute("invert", &invert_motor); InvertMotor(invert_motor); xml->QueryBoolAttribute("brake_mode", &brake_mode); SetBrakeMode(brake_mode); } /****************************************************************************** * * * If sensor_type is INTERNAL_POTENTIOMETER: * port_a==0 means no sensor wrap, port_a!=0 means sensor wrap * ******************************************************************************/ bool RSpeedControllerSparkMaxCan::SetFeedbackDevice(FeedbackDeviceType sensor_type, int ticks_per_rev, int port_b) { bool ret_val = false; switch(sensor_type) { case INTERNAL_BRUSHLESS_HALL: // SparkMax "encoder" generated using hall effect sensors m_encoder = m_controller.GetEncoder(); m_pidController.SetFeedbackDevice(m_encoder); ret_val = true; break; case INTERNAL_ENCODER: // alternate encoder wired into limit switch ports m_encoder = m_controller.GetAlternateEncoder(rev::CANEncoder::AlternateEncoderType::kQuadrature, ticks_per_rev); m_pidController.SetFeedbackDevice(m_encoder); ret_val = true; break; case EXTERNAL_ENCODER: // create encoder using A/B, set duty cycle mode break; case EXTERNAL_POTENTIOMETER: // create rpot break; default: ret_val = false; } return(ret_val); } bool RSpeedControllerSparkMaxCan::InvertMotor(bool invert) { m_controller.SetInverted(invert); return(true); } void RSpeedControllerSparkMaxCan::SetBrakeMode(bool brake_mode) { if (brake_mode) { m_controller.SetIdleMode(rev::CANSparkMax::IdleMode::kBrake); } else { m_controller.SetIdleMode(rev::CANSparkMax::IdleMode::kCoast); } } bool RSpeedControllerSparkMaxCan::SetControlMode(ControlModeType type, int device_id) { bool ret_val = true; m_mode = type; switch(type) { case DUTY_CYCLE: case POSITION: case VELOCITY: //m_controller.SetSelectedSensorPosition(m_controller.GetSelectedSensorPosition(0),0,kTimeout); break; case FOLLOWER: break; default: m_mode = DUTY_CYCLE; ret_val = false; break; } return(ret_val); } bool RSpeedControllerSparkMaxCan::SetControlMode(ControlModeType type, rev::CANSparkMax * toFollow) { bool ret_val = true; m_mode = type; switch(type) { case DUTY_CYCLE: case POSITION: case VELOCITY: //m_controller.SetSelectedSensorPosition(m_controller.GetSelectedSensorPosition(0),0,kTimeout); break; case FOLLOWER: m_controller.Follow(*toFollow); break; default: m_mode = DUTY_CYCLE; ret_val = false; break; } return(ret_val); } void RSpeedControllerSparkMaxCan::InvertSensor(bool invert, bool is_drv) { if(false == is_drv) { m_sensor_invert = 1.0; m_controller.SetInverted(invert); } else { m_sensor_invert = invert ? -1.0 : 1.0 ; } } // Change: was +/-12V, now +/-1.0 (percent) void RSpeedControllerSparkMaxCan::SetClosedLoopOutputLimits(float fwd_nom, float rev_nom, float fwd_peak, float rev_peak) { float fwd_peak_limit = RobotUtil::limit(-1, 1, fwd_peak); float rev_peak_limit = RobotUtil::limit(-1, 1, rev_peak); m_pidController.SetOutputRange(rev_peak_limit, fwd_peak_limit); } void RSpeedControllerSparkMaxCan::Set(double val) // can be duty cycle, position or velocity or device to follow { m_controller.Set(val); // is this necessary? if(m_mode == ControlModeType::VELOCITY) { m_pidController.SetReference(val/m_output_per_count,rev::ControlType::kVelocity); // TODO fix when units better understood } else if (m_mode == ControlModeType::POSITION) { Advisory::pinfo("Setting position = %f (%f)", val, (val-m_output_offset)/m_output_per_count); m_pidController.SetReference((val-m_output_offset)/m_output_per_count,rev::ControlType::kPosition); } else { m_pidController.SetReference(val, rev::ControlType::kDutyCycle); } } // Return The current set speed. Value is between -1.0 and 1.0. double RSpeedControllerSparkMaxCan::Get() { return m_controller.Get(); } void RSpeedControllerSparkMaxCan::SetPosition(double pos) { m_encoder.SetPosition(((pos-m_output_offset)/m_output_per_count)); } double RSpeedControllerSparkMaxCan::GetPosition() { return ( ((m_encoder.GetPosition() * m_output_per_count) + m_output_offset) ); } int32_t RSpeedControllerSparkMaxCan::GetRawPosition(void) { return m_encoder.GetPosition(); } double RSpeedControllerSparkMaxCan::GetSpeed() { return (m_encoder.GetVelocity() * m_sensor_invert * m_output_per_count); } int32_t RSpeedControllerSparkMaxCan::GetRawSpeed() { return m_encoder.GetVelocity(); } int RSpeedControllerSparkMaxCan::GetDeviceID() { return (m_device_id); } void RSpeedControllerSparkMaxCan::SetCurrentLimit(uint32_t amps, uint32_t peak, uint32_t duration ) {} void RSpeedControllerSparkMaxCan::SetCurrentLimitEnabled(bool enabled) {} void RSpeedControllerSparkMaxCan::SetForwardLimitSwitch (bool normally_open, bool enabled, bool zero_position) {} void RSpeedControllerSparkMaxCan::SetReverseLimitSwitch (bool normally_open, bool enabled, bool zero_position) {} double RSpeedControllerSparkMaxCan::GetBusVoltage() { return 0.0; } double RSpeedControllerSparkMaxCan::GetOutputVoltage() { return 0.0; } double RSpeedControllerSparkMaxCan::GetMotorOutputPercent() { return 0.0; } double RSpeedControllerSparkMaxCan::GetOutputCurrent() { return 0.0; } double RSpeedControllerSparkMaxCan::GetActiveTrajectoryPosition() { return 0.0; } double RSpeedControllerSparkMaxCan::GetActiveTrajectoryVelocity() { return 0.0; } void RSpeedControllerSparkMaxCan::SetP(double p) { m_pidController.SetP(p,0); } void RSpeedControllerSparkMaxCan::SetI(double i) { m_pidController.SetI(i,0); } void RSpeedControllerSparkMaxCan::SetD(double d) { m_pidController.SetD(d,0); } void RSpeedControllerSparkMaxCan::SetF(double f) { m_pidController.SetFF(f,0); } void RSpeedControllerSparkMaxCan::SetIZone(double i_zone) { m_pidController.SetIZone(i_zone, 0); } void RSpeedControllerSparkMaxCan::SetCruiseVelocity(double vel) {} void RSpeedControllerSparkMaxCan::SetAcceleration(double accel) {} double RSpeedControllerSparkMaxCan::GetP() { return m_pidController.GetP(); } double RSpeedControllerSparkMaxCan::GetI() { return m_pidController.GetI(); } double RSpeedControllerSparkMaxCan::GetD() { return m_pidController.GetD(); } double RSpeedControllerSparkMaxCan::GetF() { return m_pidController.GetFF(); } void RSpeedControllerSparkMaxCan::shuffleboardPublish(std::string tab, std::string motor_name) { /*frc::Shuffleboard::GetTab(tab).Add(motor_name, m_controller);*/ }
[ "thetimebenow12@gmail.com" ]
thetimebenow12@gmail.com
7419ef568105c1441072faab9e7b086d88cb1f0b
6041348e6979b1cd4a80f0a829d0ac9bd9ed0050
/MiniSTL/Deque.h
d9b3fea4b6f73fa2b11f6378b999e2ae87f73ec5
[]
no_license
whuisser115/MiniSTL
2c2ce4b67bf1ac540eb3a6ebd347cfe27404636c
28034e2cdae59ba10604346f4f40830b7c13a37b
refs/heads/master
2021-01-18T00:45:11.461011
2015-04-26T13:48:25
2015-04-26T13:48:25
null
0
0
null
null
null
null
GB18030
C++
false
false
16,527
h
/* ** Deque.h ** Created by Rayn on 2015/04/25 */ #ifndef _DEQUE_H_ #define _DEQUE_H_ #include "Allocator.h" #include "Uninitialized.h" #include "TypeTraits.h" #include "Iterator.h" #include "ReverseIterator.h" namespace rayn { /* ** if n == 0, 表示bufsize使用默认值 ** if sz < 512, 传回 512/sz ** if sz >= 512, 传回 1 */ inline size_t __deque_buf_size(size_t n, size_t sz) { return n != 0 ? n : (sz < 512 ? size_t(512 / sz) : size_t(1)); } template <class T, class Ref, class Ptr, size_t BufSize> struct __deque_iterator { typedef __deque_iterator self; typedef __deque_iterator<T, T&, T*, BufSize> iterator; typedef __deque_iterator<T, const T&, const T*, BufSize> const_iterator; static size_t buffer_size() { return __deque_buf_size(BufSize, sizeof(T)); } typedef random_access_iterator_tag iterator_category; typedef T value_type; typedef Ptr pointer; typedef Ref reference; typedef ptrdiff_t difference_type; typedef size_t size_type; typedef T* ele_pointer; typedef T** map_pointer; ele_pointer cur; //所指缓存区当前元素 ele_pointer first; //所指缓冲区头部 ele_pointer last; //所指缓冲区尾后 (含备用空间) map_pointer node; //指向管控中心 __deque_iterator() : cur(), first(), last(), node() {} __deque_iterator(ele_pointer x, map_pointer y) : cur(x), first(*y), last(*y + difference_type(buffer_size())), node(y) {} __deque_iterator(const iterator& other) : cur(other.cur), first(other.first), last(other.last), node(other.node) {} iterator _const_cast() const { return iterator(cur, node); } void set_node(map_pointer new_node) { node = new_node; first = *new_node; last = first + difference_type(buffer_size()); } reference operator* () const { return *cur; } pointer operator-> () const { return cur; } self& operator++ () { ++cur; if (cur == last) { set_node(node + 1); cur = first; } return *this; } self operator++ (int) { self tmp = *this; ++*this; return tmp; } self& operator-- () { if (cur == first) { set_node(node - 1); cur = last; } --cur; return *this; } self operator-- (int) { self tmp = *this; --*this; return tmp; } self& operator+= (difference_type n) { difference_type offset = n + (cur - first); if (offset >= 0 && offset < difference_type(buffer_size())) { //目标在同一缓冲区中 cur += n; } else { difference_type node_offset = offset > 0 ? offset / difference_type(buffer_size()) : -difference_type((-offset - 1) / buffer_size()) - 1; set_node(node + node_offset); cur = first + (offset - node_offset * difference_type(buffer_size())); } return *this; } self operator+ (difference_type n) const { self tmp = *this; return tmp += n; } self& operator-= (difference_type n) { return *this += -n; } self operator- (difference_type n) const { self tmp = *this; return tmp -= n; } difference_type operator- (const self& other) const { return difference_type(buffer_size()) * (node - other.node - 1) + (cur - first) + (other.last - other.cur); } reference operator[] (difference_type n) const { return *(*this + n) } bool operator== (const self& other) const { return cur == other.cur; } bool operator!= (const self& other) const { return !(*this == other); } bool operator< (const self& other) const { return (node == other.node) ? (cur < other.cur) : (node < other.node); } bool operator> (const self& other) const { return other < *this; } }; template <class T, size_t BufSize = 0> class deque { public: typedef T value_type; typedef T* pointer; typedef T& reference; typedef const T* const_pointer; typedef const T& const_reference; typedef size_t size_type; typedef __deque_iterator<T, reference, pointer, BufSize> iterator; typedef __deque_iterator<T, const_reference, const_pointer, BufSize> const_iterator; typedef reverse_iterator_t<iterator> reverse_iterator; typedef reverse_iterator_t<const_iterator> const_reverse_iterator; protected: // pointer of pointer of T typedef pointer* map_pointer; typedef allocator<value_type> data_allocator; typedef allocator<pointer> map_allocator; enum { __initial_map_size = 8 }; protected: //Data member iterator _start; //头部迭代器 iterator _finish; //尾后迭代器 map_pointer map; //指向map, map是块连续空间,每个元素是一个指针,指向一块缓存区 size_type map_size; //map内可以容纳多少指针 public: // Default Contructor deque() : _start(), _finish(), map(0), map_size(0) {} // Constructor with count copies of elements. explicit deque(size_type count) { this->fill_initialize(count, value_type()); } // Constructor with count copies of elements with value value. deque(size_type count, const value_type& value) { this->fill_initialize(count, value); } // Constructor with the contents of the range [first, last). template <class InputIterator> deque(InputIterator first, InputIterator last); // Copy Contructor deque(const deque& other); // Move Contructor deque(deque&& other); // Destructor ~deque(); // Copy Assignment operator deque& operator= (const deque& other); // Move Assignment operator deque& operator= (deque&& other); // Replaces the contents with count copies of value. void assign(size_type count, const value_type& value); // Replaces the contents with copies of those in the range [first, last). template <class InputIterator> void assign(InputIterator first, InputIterator last); // Element access // Returns a reference to the element at specified location pos. reference at(size_type pos); const_reference at(size_type pos) const; // Returns a reference to the element at specified location pos. reference operator[] (size_type n) { return _start[difference_type(n)]; } const_reference operator[] (size_type n) const { return _start[difference_type(n)]; } // Returns a reference to the first element in the container. reference front() { return *begin(); } const_reference front() const { return *begin(); } // Returns reference to the last element in the container. reference back() { iterator tmp = end(); --tmp; return *tmp; } const_reference back() const { iterator tmp = end(); --tmp; return *tmp; } // Iterators // Returns an iterator to the first element of the container. iterator begin() { return this->_start; } const_iterator begin() const { return this->_start; } const_iterator cbegin() const { return this->_start; } // Returns an iterator to the element following the last element of the container. iterator end() { return this->_finish; } const_iterator end() const { return this->_finish; } const_iterator cend() const { return this->_finish; } // Returns a reverse iterator to the first element of the reversed container. reverse_iterator rbegin() { return reverse_iterator(this->_finish); } const_reverse_iterator rbegin() const { return const_reverse_iterator(this->_finish); } const_reverse_iterator crbegin() const { return const_reverse_iterator(this->_finish); } // Returns a reverse iterator to the element following the last element of the reversed container. reverse_iterator rend() { return reverse_iterator(this->_start); } const_reverse_iterator rend() const { return const_reverse_iterator(this->_start); } const_reverse_iterator crend() const { return const_reverse_iterator(this->_start); } // Capacity // Checks if the container has no elements bool empty() { return _finish == _start; } // Returns the number of elements in the container. size_type size() const { return _finish - _start; } // Returns the maximum number of elements the container is // able to hold due to system or library implementation limitations size_type max_size() const { return size_type(-1); } // Requests the removal of unused capacity. void shrink_to_fit(); // Modifiers // Removes all elements from the container. void clear(); // inserts value before pos iterator insert(const_iterator pos, const value_type& value); // inserts count copies of the value before pos iterator insert(const_iterator pos, size_type count, const value_type& value); // inserts elements from range [first, last) before pos. template <class InputIterator> iterator insert(const_iterator pos, InputIterator first, InputIterator last); // Removes the element at pos. iterator erase(const_iterator pos); // Removes the elements in the range [first, last). iterator erase(const_iterator first, const_iterator last); // Appends the given element value to the end of the container. void push_back(const value_type& value); // Removes the last element of the container. void pop_back(); // Prepends the given element value to the beginning of the container. void push_front(const value_type& value); // Removes the first element of the container. void pop_front(); // Resizes the container to contain count elements. void resize(size_type count); void resize(size_type count, const value_type& value); // Exchanges the contents of the container with those of other. void swap(deque& other); private: //private member and method static size_t buffer_size() { return __deque_buf_size(BufSize, sizeof(T)); } void create_nodes(map_pointer start, map_pointer finish) { map_pointer cur = start; try { for (; cur != finish; ++cur) { *cur = data_allocator::allocate(buffer_size()); } } catch (...) { destroy_nodes(start, cur); } } void destroy_nodes(map_pointer start, map_pointer finish) { for (map_pointer cur = start; cur != finish; ++cur) { data_allocator::deallocate(*cur, buffer_size()); } } void fill_initialize(size_type count, const value_type& value) { initialize_map(count); map_pointer cur = _start.node; try { for (_start.node; cur != _finish.node; ++cur) { rayn::uninitialized_fill(*cur, *cur + buffer_size(), value); } uninitialized_fill(_finish.first + _finish.cur, value); } catch (...) { for (map_pointer mp = _start.node; mp != cur; ++mp) { data_allocator::destroy(*mp, *mp + buffer_size()); } //TODO 留待改善 } } void initialize_map(size_type num_elements) { size_type num_nodes = num_elements / buffer_size() + 1; // 最多是所需节点数 + 2, 前后各预留一个 this->map_size = max(size_type(__initial_map_size), num_nodes + 2); this->map = map_allocator::allocate(map_size); map_pointer nstart = map + (map_size - num_nodes) / 2; map_pointer nfinish = nstart + num_nodes; try { create_nodes(nstart, nfinish); } catch (...) { map_allocator::deallocate(this->map, this->map_size); this->map = 0; this->map_size = 0; } _start.set_node(nstart); _finish.set_node(nfinish - 1); _start.cur = _start.first; _finish.cur = _finish.first + num_elements % buffer_size(); } void reallocate_map(size_type nodes_to_add, bool add_at_front); void push_back_aux(const value_type& value); void push_front_aux(const value_type& value); void reserve_map_at_back(); void reserve_map_at_front(); }; template <class T, size_t BufSize> void deque<T, BufSize>::push_back(const value_type& value) { if (_finish.cur != _finish.last - 1) { rayn::construct(_finish.cur, value); ++_finish.cur; } else { push_back_aux(value); } } template <class T, size_t BufSize> void deque<T, BufSize>::push_front(const value_type& value) { if (_start.cur != _start.first) { rayn::construct(_start.cur - 1, value); --_start.cur; } else { push_front_aux(value); } } // Helper functions template <class T, size_t BufSize> void deque<T, BufSize>::push_back_aux(const value_type& value) { value_type v_copy = value; reserve_map_at_back(); *(_finish.node + 1) = data_allocator::allocate(buffer_size()); try { rayn::construct(_finish.cur, v_copy); _finish.set_node(_finish.node + 1); _finish.cur = _finish.first; } catch (...) { _finish.set_node(_finish.node - 1); _finish.cur = _finish.last - 1; data_allocator::deallocate(*(_finish.node + 1), buffer_size); throw; } } template <class T, size_t BufSize> void deque<T, BufSize>::push_front_aux(const value_type& value) { value_type v_copy = value; reserve_map_at_front(); *(_start.node - 1) = data_allocator::allocate(buffer_size()); try { _start.set_node(_start.node - 1); _start.cur = _start.last - 1; rayn::construct(_start.cur, v_copy); } catch (...) { _start.set_node(_start.node + 1); _start.cur = _start.first; data_allocator::deallocate(*(_start.node - 1), buffer_size()); throw; } } template <class T> inline bool operator== (const deque<T>& lhs, const deque<T>& rhs); template <class T> inline bool operator!= (const deque<T>& lhs, const deque<T>& rhs); template <class T> inline bool operator< (const deque<T>& lhs, const deque<T>& rhs); template <class T> inline bool operator<= (const deque<T>& lhs, const deque<T>& rhs); template <class T> inline bool operator> (const deque<T>& lhs, const deque<T>& rhs); template <class T> inline bool operator>= (const deque<T>& lhs, const deque<T>& rhs); template <class T> inline void swap(const deque<T>& lhs, const deque<T>& rhs); } #endif
[ "rayn1027@outlook.com" ]
rayn1027@outlook.com
4d55223162a5b1be8b3aea01ac63d66dc4f798f4
603cb1e8962093aaaa08edd3b4d5a7541cd876ac
/Circle Testings/src/ofApp.h
5488c2d1f44425f31a2a5661e9ac994e9058f6f0
[]
no_license
The-Chanman/OFExperiments
7e5d66919f8f560d7caac9cfc00ebc330d8b5b19
65a219fb3109ac98241a4ca78c5a70fbf6a1a331
refs/heads/master
2021-05-14T18:14:52.249517
2018-01-02T23:36:52
2018-01-02T23:36:52
116,066,799
0
0
null
null
null
null
UTF-8
C++
false
false
887
h
#pragma once #include "ofMain.h" #include "ofxGui.h" class ofApp : public ofBaseApp{ public: void setup(); void update(); void draw(); void keyPressed(int key); void keyReleased(int key); void mouseMoved(int x, int y ); void mouseDragged(int x, int y, int button); void mousePressed(int x, int y, int button); void mouseReleased(int x, int y, int button); void mouseEntered(int x, int y); void mouseExited(int x, int y); void windowResized(int w, int h); void dragEvent(ofDragInfo dragInfo); void gotMessage(ofMessage msg); ofxIntSlider radius; ofxIntSlider resolution; ofxIntSlider normalLength; ofxFloatSlider rate; ofParameter<float> tornadoFactor; ofEasyCam camera; ofxPanel gui; float count; ofMesh mesh; ofPoint drawPoint; float circleX, circleY, circleZ; };
[ "ecphylo@gmail.com" ]
ecphylo@gmail.com
d6aa09cea10f31168efc466490809c4108197553
9f3d0bad72a5a0bfa23ace7af8dbf63093be9c86
/vendor/assimp/4.1.0/code/DefaultLogger.cpp
b69e18ea9389d37ab623023149da110845ff088d
[ "BSD-3-Clause", "LGPL-2.0-or-later", "Zlib" ]
permissive
0xc0dec/solo
ec700066951f7ef5c90aee4ae505bb5e85154da2
6c7f78da49beb09b51992741df3e47067d1b7e10
refs/heads/master
2023-04-27T09:23:15.554730
2023-02-26T11:46:16
2023-02-26T11:46:16
28,027,226
37
2
Zlib
2023-04-19T19:39:31
2014-12-15T08:19:32
C++
UTF-8
C++
false
false
13,147
cpp
/* --------------------------------------------------------------------------- Open Asset Import Library (assimp) --------------------------------------------------------------------------- Copyright (c) 2006-2017, assimp team All rights reserved. Redistribution and use of this software 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 assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --------------------------------------------------------------------------- */ /** @file DefaultLogger.cpp * @brief Implementation of DefaultLogger (and Logger) */ // Default log streams #include "Win32DebugLogStream.h" #include "StdOStreamLogStream.h" #include "FileLogStream.h" #include "StringUtils.h" #include <assimp/DefaultIOSystem.h> #include <assimp/NullLogger.hpp> #include <assimp/DefaultLogger.hpp> #include <assimp/ai_assert.h> #include <iostream> #include <stdio.h> #ifndef ASSIMP_BUILD_SINGLETHREADED # include <thread> # include <mutex> std::mutex loggerMutex; #endif namespace Assimp { // ---------------------------------------------------------------------------------- NullLogger DefaultLogger::s_pNullLogger; Logger *DefaultLogger::m_pLogger = &DefaultLogger::s_pNullLogger; static const unsigned int SeverityAll = Logger::Info | Logger::Err | Logger::Warn | Logger::Debugging; // ---------------------------------------------------------------------------------- // Represents a log-stream + its error severity struct LogStreamInfo { unsigned int m_uiErrorSeverity; LogStream *m_pStream; // Constructor LogStreamInfo( unsigned int uiErrorSev, LogStream *pStream ) : m_uiErrorSeverity( uiErrorSev ), m_pStream( pStream ) { // empty } // Destructor ~LogStreamInfo() { delete m_pStream; } }; // ---------------------------------------------------------------------------------- // Construct a default log stream LogStream* LogStream::createDefaultStream(aiDefaultLogStream streams, const char* name /*= "AssimpLog.txt"*/, IOSystem* io /*= NULL*/) { switch (streams) { // This is a platform-specific feature case aiDefaultLogStream_DEBUGGER: #ifdef WIN32 return new Win32DebugLogStream(); #else return NULL; #endif // Platform-independent default streams case aiDefaultLogStream_STDERR: return new StdOStreamLogStream(std::cerr); case aiDefaultLogStream_STDOUT: return new StdOStreamLogStream(std::cout); case aiDefaultLogStream_FILE: return (name && *name ? new FileLogStream(name,io) : NULL); default: // We don't know this default log stream, so raise an assertion ai_assert(false); }; // For compilers without dead code path detection return NULL; } // ---------------------------------------------------------------------------------- // Creates the only singleton instance Logger *DefaultLogger::create(const char* name /*= "AssimpLog.txt"*/, LogSeverity severity /*= NORMAL*/, unsigned int defStreams /*= aiDefaultLogStream_DEBUGGER | aiDefaultLogStream_FILE*/, IOSystem* io /*= NULL*/) { // enter the mutex here to avoid concurrency problems #ifndef ASSIMP_BUILD_SINGLETHREADED std::lock_guard<std::mutex> lock(loggerMutex); #endif if (m_pLogger && !isNullLogger() ) delete m_pLogger; m_pLogger = new DefaultLogger( severity ); // Attach default log streams // Stream the log to the MSVC debugger? if (defStreams & aiDefaultLogStream_DEBUGGER) m_pLogger->attachStream( LogStream::createDefaultStream(aiDefaultLogStream_DEBUGGER)); // Stream the log to COUT? if (defStreams & aiDefaultLogStream_STDOUT) m_pLogger->attachStream( LogStream::createDefaultStream(aiDefaultLogStream_STDOUT)); // Stream the log to CERR? if (defStreams & aiDefaultLogStream_STDERR) m_pLogger->attachStream( LogStream::createDefaultStream(aiDefaultLogStream_STDERR)); // Stream the log to a file if (defStreams & aiDefaultLogStream_FILE && name && *name) m_pLogger->attachStream( LogStream::createDefaultStream(aiDefaultLogStream_FILE,name,io)); return m_pLogger; } // ---------------------------------------------------------------------------------- void Logger::debug(const char* message) { // SECURITY FIX: otherwise it's easy to produce overruns since // sometimes importers will include data from the input file // (i.e. node names) in their messages. if (strlen(message)>MAX_LOG_MESSAGE_LENGTH) { return; } return OnDebug(message); } // ---------------------------------------------------------------------------------- void Logger::info(const char* message) { // SECURITY FIX: see above if (strlen(message)>MAX_LOG_MESSAGE_LENGTH) { return; } return OnInfo(message); } // ---------------------------------------------------------------------------------- void Logger::warn(const char* message) { // SECURITY FIX: see above if (strlen(message)>MAX_LOG_MESSAGE_LENGTH) { return; } return OnWarn(message); } // ---------------------------------------------------------------------------------- void Logger::error(const char* message) { // SECURITY FIX: see above if (strlen(message)>MAX_LOG_MESSAGE_LENGTH) { return; } return OnError(message); } // ---------------------------------------------------------------------------------- void DefaultLogger::set( Logger *logger ) { // enter the mutex here to avoid concurrency problems #ifndef ASSIMP_BUILD_SINGLETHREADED std::lock_guard<std::mutex> lock(loggerMutex); #endif if (!logger)logger = &s_pNullLogger; if (m_pLogger && !isNullLogger() ) delete m_pLogger; DefaultLogger::m_pLogger = logger; } // ---------------------------------------------------------------------------------- bool DefaultLogger::isNullLogger() { return m_pLogger == &s_pNullLogger; } // ---------------------------------------------------------------------------------- Logger *DefaultLogger::get() { return m_pLogger; } // ---------------------------------------------------------------------------------- // Kills the only instance void DefaultLogger::kill() { // enter the mutex here to avoid concurrency problems #ifndef ASSIMP_BUILD_SINGLETHREADED std::lock_guard<std::mutex> lock(loggerMutex); #endif if ( m_pLogger == &s_pNullLogger ) { return; } delete m_pLogger; m_pLogger = &s_pNullLogger; } // ---------------------------------------------------------------------------------- // Debug message void DefaultLogger::OnDebug( const char* message ) { if ( m_Severity == Logger::NORMAL ) return; static const size_t Size = MAX_LOG_MESSAGE_LENGTH + 16; char msg[Size]; ai_snprintf(msg, Size, "Debug, T%u: %s", GetThreadID(), message); WriteToStreams( msg, Logger::Debugging ); } // ---------------------------------------------------------------------------------- // Logs an info void DefaultLogger::OnInfo( const char* message ) { static const size_t Size = MAX_LOG_MESSAGE_LENGTH + 16; char msg[Size]; ai_snprintf(msg, Size, "Info, T%u: %s", GetThreadID(), message ); WriteToStreams( msg , Logger::Info ); } // ---------------------------------------------------------------------------------- // Logs a warning void DefaultLogger::OnWarn( const char* message ) { static const size_t Size = MAX_LOG_MESSAGE_LENGTH + 16; char msg[Size]; ai_snprintf(msg, Size, "Warn, T%u: %s", GetThreadID(), message ); WriteToStreams( msg, Logger::Warn ); } // ---------------------------------------------------------------------------------- // Logs an error void DefaultLogger::OnError( const char* message ) { static const size_t Size = MAX_LOG_MESSAGE_LENGTH + 16; char msg[ Size ]; ai_snprintf(msg, Size, "Error, T%u: %s", GetThreadID(), message ); WriteToStreams( msg, Logger::Err ); } // ---------------------------------------------------------------------------------- // Will attach a new stream bool DefaultLogger::attachStream( LogStream *pStream, unsigned int severity ) { if (!pStream) return false; if (0 == severity) { severity = Logger::Info | Logger::Err | Logger::Warn | Logger::Debugging; } for ( StreamIt it = m_StreamArray.begin(); it != m_StreamArray.end(); ++it ) { if ( (*it)->m_pStream == pStream ) { (*it)->m_uiErrorSeverity |= severity; return true; } } LogStreamInfo *pInfo = new LogStreamInfo( severity, pStream ); m_StreamArray.push_back( pInfo ); return true; } // ---------------------------------------------------------------------------------- // Detach a stream bool DefaultLogger::detatchStream( LogStream *pStream, unsigned int severity ) { if (!pStream) return false; if (0 == severity) { severity = SeverityAll; } for ( StreamIt it = m_StreamArray.begin(); it != m_StreamArray.end(); ++it ) { if ( (*it)->m_pStream == pStream ) { (*it)->m_uiErrorSeverity &= ~severity; if ( (*it)->m_uiErrorSeverity == 0 ) { // don't delete the underlying stream 'cause the caller gains ownership again (**it).m_pStream = NULL; delete *it; m_StreamArray.erase( it ); break; } return true; } } return false; } // ---------------------------------------------------------------------------------- // Constructor DefaultLogger::DefaultLogger(LogSeverity severity) : Logger ( severity ) , noRepeatMsg (false) , lastLen( 0 ) { lastMsg[0] = '\0'; } // ---------------------------------------------------------------------------------- // Destructor DefaultLogger::~DefaultLogger() { for ( StreamIt it = m_StreamArray.begin(); it != m_StreamArray.end(); ++it ) { // also frees the underlying stream, we are its owner. delete *it; } } // ---------------------------------------------------------------------------------- // Writes message to stream void DefaultLogger::WriteToStreams(const char *message, ErrorSeverity ErrorSev ) { ai_assert(NULL != message); // Check whether this is a repeated message if (! ::strncmp( message,lastMsg, lastLen-1)) { if (!noRepeatMsg) { noRepeatMsg = true; message = "Skipping one or more lines with the same contents\n"; } else return; } else { // append a new-line character to the message to be printed lastLen = ::strlen(message); ::memcpy(lastMsg,message,lastLen+1); ::strcat(lastMsg+lastLen,"\n"); message = lastMsg; noRepeatMsg = false; ++lastLen; } for ( ConstStreamIt it = m_StreamArray.begin(); it != m_StreamArray.end(); ++it) { if ( ErrorSev & (*it)->m_uiErrorSeverity ) (*it)->m_pStream->write( message); } } // ---------------------------------------------------------------------------------- // Returns thread id, if not supported only a zero will be returned. unsigned int DefaultLogger::GetThreadID() { // fixme: we can get this value via std::threads // std::this_thread::get_id().hash() returns a (big) size_t, not sure if this is useful in this case. #ifdef WIN32 return (unsigned int)::GetCurrentThreadId(); #else return 0; // not supported #endif } // ---------------------------------------------------------------------------------- } // !namespace Assimp
[ "aleksey.fedotov@gmail.com" ]
aleksey.fedotov@gmail.com
03888208f5079161d2b2b8d3cd98bfa03c6039d1
a6f310cf733ed582b89258ac9e36dd60dd8e772b
/util/GLlib.cpp
05ac21cd96b30b321a7366f8de2db556d5c2437a
[]
no_license
MarcellMissura/polygonalperception
30c42f503649aaae35f43c0444412dcbc92d0663
da8dc43c9bcd58d094e5139da746f4403c2ddba4
refs/heads/master
2022-12-18T23:03:13.280711
2020-09-23T07:40:44
2020-09-23T07:40:44
292,268,127
7
3
null
null
null
null
UTF-8
C++
false
false
9,996
cpp
#include "GLlib.h" #include <math.h> #include <GL/glu.h> namespace GLlib { // 1: top left front // 2: bottom left front // 3: top right front // 4: bottom right front // 5: top right back // 6: bottom right back // 7: top left back // 8: bottom left back void drawBox( double x1, double y1, double z1, double x2, double y2, double z2, double x3, double y3, double z3, double x4, double y4, double z4, double x5, double y5, double z5, double x6, double y6, double z6, double x7, double y7, double z7, double x8, double y8, double z8 ) { glBegin(GL_QUAD_STRIP); glVertex3f(x1, y1, z1); glVertex3f(x2, y2, z2); glVertex3f(x3, y3, z3); glVertex3f(x4, y4, z4); glVertex3f(x5, y5, z5); glVertex3f(x6, y6, z6); glVertex3f(x7, y7, z7); glVertex3f(x8, y8, z8); glVertex3f(x1, y1, z1); glVertex3f(x2, y2, z2); glEnd(); glBegin(GL_QUADS); glVertex3f(x1, y1, z1); glVertex3f(x3, y3, z3); glVertex3f(x5, y5, z5); glVertex3f(x7, y7, z7); glVertex3f(x2, y2, z2); glVertex3f(x4, y4, z4); glVertex3f(x6, y6, z6); glVertex3f(x8, y8, z8); glEnd(); glColor3f(0.3, 0.3, 0.3); glLineWidth(2); glBegin( GL_LINE_STRIP ); glVertex3f(x1, y1, z1); glVertex3f(x2, y2, z2); glVertex3f(x4, y4, z4); glVertex3f(x3, y3, z3); glVertex3f(x1, y1, z1); glVertex3f(x7, y7, z7); glVertex3f(x8, y8, z8); glVertex3f(x6, y6, z6); glVertex3f(x5, y5, z5); glVertex3f(x7, y7, z7); glEnd(); glBegin(GL_LINES); glVertex3f(x3, y3, z3); glVertex3f(x5, y5, z5); glVertex3f(x4, y4, z4); glVertex3f(x6, y6, z6); glVertex3f(x2, y2, z2); glVertex3f(x8, y8, z8); glEnd(); } // Draws a cuboid with half extents x, y and z. void drawBox(float x, float y, float z) { glBegin( GL_QUAD_STRIP ); glVertex3f(x, y, z); glVertex3f(x, y, -z); glVertex3f(x, -y, z); glVertex3f(x, -y, -z); glVertex3f(-x, -y, z); glVertex3f(-x, -y, -z); glVertex3f(-x, y, z); glVertex3f(-x, y, -z); glVertex3f(x, y, z); glVertex3f(x, y, -z); glEnd(); glBegin( GL_QUADS ); glVertex3f(x, y, z); glVertex3f(x, -y, z); glVertex3f(-x, -y, z); glVertex3f(-x, y, z); glVertex3f(x, y, -z); glVertex3f(x, -y, -z); glVertex3f(-x, -y, -z); glVertex3f(-x, y, -z); glEnd(); glColor3f(0, 0, 0); glLineWidth(2); glBegin( GL_LINE_STRIP ); glVertex3f(x, y, z); glVertex3f(x, y, -z); glVertex3f(x, -y, -z); glVertex3f(x, -y, z); glVertex3f(x, y, z); glVertex3f(-x, y, z); glVertex3f(-x, y, -z); glVertex3f(-x, -y, -z); glVertex3f(-x, -y, z); glVertex3f(-x, y, z); glEnd(); glBegin( GL_LINES ); glVertex3f(x, -y, z); glVertex3f(-x, -y, z); glVertex3f(x, -y, -z); glVertex3f(-x, -y, -z); glVertex3f(x, y, -z); glVertex3f(-x, y, -z); glEnd(); } // Draws a cuboid with half extents x, y and z. void drawWireFrame(float x, float y, float z) { glColor3f(0.3, 0.3, 0.3); glLineWidth(1); glBegin( GL_LINE_STRIP ); glVertex3f(x, y, z); glVertex3f(x, y, -z); glVertex3f(x, -y, -z); glVertex3f(x, -y, z); glVertex3f(x, y, z); glVertex3f(-x, y, z); glVertex3f(-x, y, -z); glVertex3f(-x, -y, -z); glVertex3f(-x, -y, z); glVertex3f(-x, y, z); glEnd(); glBegin( GL_LINES ); glVertex3f(x, -y, z); glVertex3f(-x, -y, z); glVertex3f(x, -y, -z); glVertex3f(-x, -y, -z); glVertex3f(x, y, -z); glVertex3f(-x, y, -z); glEnd(); } // Draws a quad with x,y top left corner and width and height. void drawQuad(float x, float y, float w, float h) { glBegin( GL_QUADS ); glVertex3f(x, y, 0.001); glVertex3f(x+w, y, 0.001); glVertex3f(x+w, y-h, 0.001); glVertex3f(x, y-h, 0.001); glEnd(); glColor3f(0.3, 0.3, 0.3); glLineWidth(2); glBegin( GL_LINE_STRIP ); glVertex3f(x, y, 0.001); glVertex3f(x+w, y, 0.001); glVertex3f(x+w, y-h, 0.001); glVertex3f(x, y-h, 0.001); glEnd(); } // Draws a sphere. void drawSphere(float radius) { static GLUquadric* quadric = gluNewQuadric(); gluSphere(quadric, radius, 32, 32); } // Draws a sphere with a camera plane aligned border around it (you wish). void drawBorderedSphere(float radius) { static GLUquadric* quadric = gluNewQuadric(); gluSphere(quadric, radius, 32, 32); } // Draws a circle in the xy plane. // http://slabode.exofire.net/circle_draw.shtml void drawCircle(float radius) { int slices = 32; float theta = 2 * 3.1415926 / float(slices); float c = cos(theta); float s = sin(theta); float t; float x = radius; //we start at angle = 0 float y = 0; glLineWidth(2); glColor3f(0, 0 , 0); glBegin(GL_LINE_LOOP); for(int ii = 0; ii < slices; ii++) { glVertex3f(x, y, 0); //apply the rotation matrix t = x; x = c * x - s * y; y = s * t + c * y; } glEnd(); } // Draws a filled circle in the xy plane. // http://slabode.exofire.net/circle_draw.shtml void drawFilledCircle(float radius) { int slices = 32; float theta = 2 * 3.1415926 / float(slices); float c = cos(theta); float s = sin(theta); float t; float x = radius; // start at angle = 0 float y = 0; glBegin(GL_TRIANGLE_FAN); //glColor3f(r,g,b); glVertex3f(0, 0, 0); for(int ii = 0; ii <= slices; ii++) { glVertex3f(x, y, 0); t = x; x = c*x-s*y; // rotation matrix y = s*t+c*y; // rotation matrix } glEnd(); } // Draws a filled circle in the xy plane. // http://slabode.exofire.net/circle_draw.shtml void drawFilledCircleStack(float radius) { drawFilledCircle(radius); glPushMatrix(); glRotated(90, 1, 0, 0); drawFilledCircle(radius); glPopMatrix(); glPushMatrix(); glRotated(90, 0, 1, 0); drawFilledCircle(radius); glPopMatrix(); } // Draws a coordinate frame. void drawFrame(float size, int lw) { glLineWidth(lw); glBegin( GL_LINES ); glColor3f(1.0, 0.0, 0.0); glVertex3f(0.0f, 0.0f, 0.0f); glVertex3f(size, 0.0f, 0.0f); glColor3f(0.0, 1.0, 0.0); glVertex3f(0.0f, 0.0f, 0.0f); glVertex3f(0.0f, size, 0.0f); glColor3f(0.0, 0.0, 1.0); glVertex3f(0.0f, 0.0f, 0.0f); glVertex3f(0.0f, 0.0f, size); glEnd(); } // Draws a coordinate frame. void drawFrame(float sx, float sy, float sz) { glLineWidth(2); glBegin( GL_LINES ); glColor3f(1.0, 0.0, 0.0); glVertex3f(0.0f, 0.0f, 0.0f); glVertex3f(sx, 0.0f, 0.0f); glColor3f(0.0, 1.0, 0.0); glVertex3f(0.0f, 0.0f, 0.0f); glVertex3f(0.0f, sy, 0.0f); glColor3f(0.0, 0.0, 1.0); glVertex3f(0.0f, 0.0f, 0.0f); glVertex3f(0.0f, 0.0f, sz); glEnd(); } // Draws an arrow that points along the x axis. void drawArrow(float length, float radius) { static GLUquadric* quadric = gluNewQuadric(); if (radius < 0.0) radius = 0.05 * length; double headLength = 0.4*length < 0.15 ? 0.4*length : 0.15; double arrowLength = length - headLength; glPushMatrix(); glRotated(90, 0, 1.0, 0); gluCylinder(quadric, radius, radius, arrowLength, 32, 1); glTranslatef(0.0, 0.0, arrowLength); gluCylinder(quadric, 1.5*radius, 0.0, headLength, 32, 1); glPopMatrix(); } // Draws a cross. void drawCross(float size) { glTranslatef(0, 0, 0.001); glBegin( GL_QUADS ); glVertex3f(size, 0.35*size, 0); glVertex3f(-size, 0.35*size, 0); glVertex3f(-size, -0.35*size, 0); glVertex3f(size, -0.35*size, 0); glEnd(); glTranslatef(0, 0, 0.001); glBegin( GL_QUADS ); glVertex3f(0.35*size, size, 0); glVertex3f(-0.35*size, size, 0); glVertex3f(-0.35*size, -size, 0); glVertex3f(0.35*size, -size, 0); glEnd(); glTranslatef(0, 0, -0.002); } void drawCone(float bottomRadius, float topRadius, float height) { static GLUquadric* quadric = gluNewQuadric(); gluCylinder(quadric, bottomRadius, topRadius, height, 32, 32); drawFilledCircle(bottomRadius); glTranslated(0, 0, height); drawFilledCircle(topRadius); drawCircle(topRadius); glTranslated(0, 0, -height); drawCircle(bottomRadius); } void drawCyclinder(float radius, float height) { static GLUquadric* quadric = gluNewQuadric(); gluCylinder(quadric, radius, radius, height, 32, 32); drawFilledCircle(radius); glTranslated(0, 0, height); drawFilledCircle(radius); drawCircle(radius); glTranslated(0, 0, -height); drawCircle(radius); } }
[ "missura@cs.uni-bonn.de" ]
missura@cs.uni-bonn.de
c8e16de61b4f41234b8061fffdf404ead9feb338
9f1c325406154036f9f5b3cc7254adf0d4e9a37f
/ctdlgt_thay_phuong-master/stack2.cpp
8eb85b20ec0d01a739f353806739dfe2506b74d3
[]
no_license
levietanh189/ctdlgt_thayphuong
3a4323456a199044810ac7ea41fe6fd5a5782c24
78b03ca670d61f1944cdd38595f202ebe078365d
refs/heads/main
2023-06-16T10:46:58.928666
2021-07-15T15:53:58
2021-07-15T15:53:58
386,344,258
0
0
null
null
null
null
UTF-8
C++
false
false
510
cpp
#include<iostream> #include<algorithm> #include<vector> #include<stack> #include<string.h> using namespace std; int main( ){ string s; int n,q; cin>>q; stack <int> ck; while(q--){ cin>>s; if(s=="PUSH"){ cin>>n; ck.push(n); } else if(s=="POP" && ck.size( )>0) ck.pop( ); else if(s=="PRINT"){ if(ck.size( )==0) cout<<"NONE\n"; else cout<<ck.top( )<<"\n"; } } return 0; }
[ "noreply@github.com" ]
noreply@github.com
ad266790798a64a50155fc69c762aad831132bf2
4a55ebb8c147f7d5bf55860c96b1ac24845dd671
/src/threads/async_handle.h
5299fc0f62cf08d98b971fed2fe50e67e7e889e6
[ "Apache-2.0" ]
permissive
tarickb/s3fuse
0e0b43c9d3c5e43b6d652d78add6bdfc02b1a9ad
ec92ae6007e02857c258ba3114e133a7df0b74de
refs/heads/master
2023-09-01T17:47:42.786442
2023-08-12T18:08:31
2023-08-12T18:08:31
15,924,713
9
5
null
2017-03-07T19:50:28
2014-01-15T04:12:48
C++
UTF-8
C++
false
false
1,549
h
/* * threads/async_handle.h * ------------------------------------------------------------------------- * Asynchronous event handle. * ------------------------------------------------------------------------- * * Copyright (c) 2012, Tarick Bedeir. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef S3_THREADS_ASYNC_HANDLE_H #define S3_THREADS_ASYNC_HANDLE_H #include <condition_variable> #include <mutex> namespace s3 { namespace threads { class AsyncHandle { public: inline AsyncHandle() = default; inline ~AsyncHandle() = default; inline void Complete(int return_code) { std::lock_guard<std::mutex> lock(mutex_); return_code_ = return_code; done_ = true; condition_.notify_all(); } inline int Wait() { std::unique_lock<std::mutex> lock(mutex_); while (!done_) condition_.wait(lock); return return_code_; } private: std::mutex mutex_; std::condition_variable condition_; int return_code_ = 0; bool done_ = false; }; } // namespace threads } // namespace s3 #endif
[ "tarick@bedeir.com" ]
tarick@bedeir.com
f84fade785e4c0d3f5c474320e6869d1434db7c5
8fddc3b98945045dc4163296d20fcb44b600a539
/basics/thecherno/72_precompiled_headers.cpp
d9633910463048cf891b40ea7bf32c629e54786d
[]
no_license
vkresch/cppknowledge
25dd51ed230b4ca1945344016f5b8178b1a8e279
a7ff102a43c67b7890c5a22bf8415c3de65113e0
refs/heads/master
2023-06-24T11:37:51.168389
2021-07-25T20:45:28
2021-07-25T20:45:28
303,363,611
0
0
null
null
null
null
UTF-8
C++
false
false
477
cpp
// https://www.youtube.com/watch?v=eSI4wctZUto&list=PLlrATfBNZ98dudnM48yfGUldqGD0S4FFb&index=72 // Precompile headers *.pch // Do not put frequently changing files into the precompiled headers // Adds convenience #include "72_pch.h" // This needs to be recompiled every single time // Compile with "g++ -std=c++11 72_pch.h" // http://mochan.info/c++/2019/11/12/pre-compiled-headers-gcc-clang-cmake.html int main(){ std::cout << "Hello World" << std::endl; return 0; }
[ "viktor.kreschenski@altran.com" ]
viktor.kreschenski@altran.com
fb20bf6517560b997fa443caebb1beb48d03877e
e17c43db9488f57cb835129fa954aa2edfdea8d5
/Extended/OpenSeesInterface/Elements/RLinearShellElement.cpp
3728597add2758333d8de22dbc6855aaed315c42
[]
no_license
claudioperez/Rts
6e5868ab8d05ea194a276b8059730dbe322653a7
3609161c34f19f1649b713b09ccef0c8795f8fe7
refs/heads/master
2022-11-06T15:57:39.794397
2020-06-27T23:00:11
2020-06-27T23:00:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,408
cpp
/********************************************************************* * * * This file is posted by Dr. Stevan Gavrilovic (steva44@hotmail.com) * * as a result of work performed in the research group of Professor * * Terje Haukaas (terje@civil.ubc.ca) at the University of British * * Columbia in Vancouver. The code is part of the computer program * * Rts, which is an extension of the computer program Rt developed by * * Dr. Mojtaba Mahsuli (mahsuli@sharif.edu) in the same group. * * * * The content of this file is the product of thesis-related work * * performed at the University of British Columbia (UBC). Therefore, * * the Rights and Ownership are held by UBC. * * * * Please be cautious when using this code. It is provided “as is” * * without warranty of any kind, express or implied. * * * * Contributors to this file: * * - Stevan Gavrilovic * * - Terje Haukaas * * * *********************************************************************/ #include "RLinearShellElement.h" #include "RCoordinateTransformation.h" #include "RSectionForceDeformation.h" #include "RMathUtils.h" RLinearShellElement::RLinearShellElement(QObject *parent, QString &name) : RElement(parent, name) { theNode1 = nullptr; theNode2 = nullptr; theNode3 = nullptr; theNode4 = nullptr; theSectionForceDeformation = nullptr; } RLinearShellElement::~RLinearShellElement() { } int RLinearShellElement::getNumNodes() { return 4; } RNode * RLinearShellElement::getNode(int i) const { if (i==0) { return theNode1; } else if (i==1) { return theNode2; } else if (i==2) { return theNode3; } else if (i==3) { return theNode4; } else { return nullptr; } } int RLinearShellElement::setNode(int i, RNode *theNode) { if (i==0) { theNode1 = theNode; } else if (i==1) { theNode2 = theNode; } else if (i==2) { theNode3 = theNode; } else if (i==3) { theNode4 = theNode; } else { qCritical() << "The Quad4 element only has nodes associated with i=0, i=1, i=2, and i=3"; } return 0; } RSectionForceDeformation *RLinearShellElement::getTheSectionForceDeformation() const { return theSectionForceDeformation; } void RLinearShellElement::setTheSectionForceDeformation(RSectionForceDeformation *value) { theSectionForceDeformation = value; } double RLinearShellElement::getLength12() { auto xcoord1 = theNode1->getXCoordinateValue(); auto xcoord2 = theNode2->getXCoordinateValue(); auto ycoord1 = theNode1->getYCoordinateValue(); auto ycoord2 = theNode2->getYCoordinateValue(); auto zcoord1 = theNode1->getZCoordinateValue(); auto zcoord2 = theNode2->getZCoordinateValue(); // Length of vector from 1 to 2 auto length12 = sqrt( (xcoord2-xcoord1) * (xcoord2-xcoord1) + (ycoord2-ycoord1) * (ycoord2-ycoord1) + (zcoord2-zcoord1) * (zcoord2-zcoord1)); return length12; } double RLinearShellElement::getLength23() { QVector<double> vector23(3); auto xcoord2 = theNode2->getXCoordinateValue(); auto xcoord3 = theNode3->getXCoordinateValue(); auto ycoord2 = theNode2->getYCoordinateValue(); auto ycoord3 = theNode3->getYCoordinateValue(); auto zcoord2 = theNode2->getZCoordinateValue(); auto zcoord3 = theNode3->getZCoordinateValue(); // Length of vector from 2 to 3 auto length23 = sqrt( (xcoord3-xcoord2) * (xcoord3-xcoord2) + (ycoord3-ycoord2) * (ycoord3-ycoord2) + (zcoord3-zcoord2) * (zcoord3-zcoord2)); return length23; } double RLinearShellElement::getLength34() { QVector<double> vector34(3); auto xcoord3 = theNode3->getXCoordinateValue(); auto xcoord4 = theNode4->getXCoordinateValue(); auto ycoord3 = theNode3->getYCoordinateValue(); auto ycoord4 = theNode4->getYCoordinateValue(); auto zcoord3 = theNode3->getZCoordinateValue(); auto zcoord4 = theNode4->getZCoordinateValue(); // Length of vector from 3 to 4 auto length34 = sqrt( (xcoord4-xcoord3) * (xcoord4-xcoord3) + (ycoord4-ycoord3) * (ycoord4-ycoord3) + (zcoord4-zcoord3) * (zcoord4-zcoord3)); return length34; } double RLinearShellElement::getLength41() { QVector<double> vector14(3); auto xcoord1 = theNode1->getXCoordinateValue(); auto xcoord4 = theNode4->getXCoordinateValue(); auto ycoord1 = theNode1->getYCoordinateValue(); auto ycoord4 = theNode4->getYCoordinateValue(); auto zcoord1 = theNode1->getZCoordinateValue(); auto zcoord4 = theNode4->getZCoordinateValue(); // Length of vector from 1 to 4 auto length41 = sqrt( (xcoord4-xcoord1) * (xcoord4-xcoord1) + (ycoord4-ycoord1) * (ycoord4-ycoord1) + (zcoord4-zcoord1) * (zcoord4-zcoord1)); return length41; } double RLinearShellElement::getCharacteristicLength() { auto length1 = this->getLength11(); auto length2 = this->getLength22(); return (length1 < length2 ? length1 : length2); } double RLinearShellElement::getArea(void) { QVector<double> vector12(3); QVector<double> vector14(3); QVector<double> vector32(3); QVector<double> vector34(3); // Original nodal coordinates auto xcoord1 = theNode1->getXCoordinateValue(); auto xcoord2 = theNode2->getXCoordinateValue(); auto xcoord3 = theNode3->getXCoordinateValue(); auto xcoord4 = theNode4->getXCoordinateValue(); auto ycoord1 = theNode1->getYCoordinateValue(); auto ycoord2 = theNode2->getYCoordinateValue(); auto ycoord3 = theNode3->getYCoordinateValue(); auto ycoord4 = theNode4->getYCoordinateValue(); auto zcoord1 = theNode1->getZCoordinateValue(); auto zcoord2 = theNode2->getZCoordinateValue(); auto zcoord3 = theNode3->getZCoordinateValue(); auto zcoord4 = theNode4->getZCoordinateValue(); // Determine vectors shooting out from 1 and 3 vector12[0] = xcoord2-xcoord1; vector12[1] = ycoord2-ycoord1; vector12[2] = zcoord2-zcoord1; vector14[0] = xcoord4-xcoord1; vector14[1] = ycoord4-ycoord1; vector14[2] = zcoord4-zcoord1; vector32[0] = xcoord2-xcoord3; vector32[1] = ycoord2-ycoord3; vector32[2] = zcoord2-zcoord3; vector34[0] = xcoord4-xcoord3; vector34[1] = ycoord4-ycoord3; vector34[2] = zcoord4-zcoord3; // The area of each triangle is half the norm of the cross-product QVector<double> cross12by14(3); cross12by14[0] = vector12[1] * vector14[2] - vector12[2] * vector14[1]; cross12by14[1] = vector12[2] * vector14[0] - vector12[0] * vector14[2]; cross12by14[2] = vector12[0] * vector14[1] - vector12[1] * vector14[0]; QVector<double> cross34by32(3); cross34by32[0] = vector34[1] * vector32[2] - vector34[2] * vector32[1]; cross34by32[1] = vector34[2] * vector32[0] - vector34[0] * vector32[2]; cross34by32[2] = vector34[0] * vector32[1] - vector34[1] * vector32[0]; auto normLambda = [](QVector<double> const& vector) { auto theNorm = 0.0; for (auto&& it: vector) theNorm += it*it; // Take the square root of the sum of squares, namely the norm return sqrt(theNorm); }; auto area = 0.5*(normLambda(cross12by14) + normLambda(cross34by32)); return area; } std::vector<double> RLinearShellElement::getCentroid(void) { auto xcoord1 = theNode1->getXCoordinateValue(); auto xcoord2 = theNode2->getXCoordinateValue(); auto xcoord3 = theNode3->getXCoordinateValue(); auto xcoord4 = theNode4->getXCoordinateValue(); auto ycoord1 = theNode1->getYCoordinateValue(); auto ycoord2 = theNode2->getYCoordinateValue(); auto ycoord3 = theNode3->getYCoordinateValue(); auto ycoord4 = theNode4->getYCoordinateValue(); auto zcoord1 = theNode1->getZCoordinateValue(); auto zcoord2 = theNode2->getZCoordinateValue(); auto zcoord3 = theNode3->getZCoordinateValue(); auto zcoord4 = theNode4->getZCoordinateValue(); std::vector<double> point1{xcoord1,ycoord1,zcoord1}; std::vector<double> point2{xcoord2,ycoord2,zcoord2}; std::vector<double> point3{xcoord3,ycoord3,zcoord3}; std::vector<double> point4{xcoord4,ycoord4,zcoord4}; std::vector<std::vector<double>> points{point1,point2,point3,point4}; return RMathUtils::computePolygonCentroid<std::vector<double>>(points); } std::vector<double> RLinearShellElement::getNormalVector(void) { auto xcoord1 = theNode1->getXCoordinateValue(); auto xcoord2 = theNode2->getXCoordinateValue(); auto xcoord3 = theNode3->getXCoordinateValue(); auto ycoord1 = theNode1->getYCoordinateValue(); auto ycoord2 = theNode2->getYCoordinateValue(); auto ycoord3 = theNode3->getYCoordinateValue(); auto zcoord1 = theNode1->getZCoordinateValue(); auto zcoord2 = theNode2->getZCoordinateValue(); auto zcoord3 = theNode3->getZCoordinateValue(); std::vector<double> U(3); std::vector<double> V(3); std::vector<double> Normal(3); //(Triangle.p2 minus Triangle.p1) U[0] = xcoord2 - xcoord1; U[1] = ycoord2 - ycoord1; U[2] = zcoord2 - zcoord1; //(Triangle.p3 minus Triangle.p1) V[0] = xcoord3 - xcoord1; V[1] = ycoord3 - ycoord1; V[2] = zcoord3 - zcoord1; Normal[0] = ( U[1] * V[2]) - ( U[2] * V[1]); Normal[1] = ( U[2] * V[0]) - ( U[0] * V[2]); Normal[2] = ( U[0] * V[1]) - ( U[1] * V[0]); RMathUtils::normalizeVector(&Normal); return Normal; } double RLinearShellElement::getLength22() { // Length of vector from 1 to 2 double length23 = this->getLength23(); double length41 = this->getLength41(); auto length2 = 0.5*(length23+length41); return length2; } double RLinearShellElement::getLength11() { double length12 = this->getLength12(); double length34 = this->getLength34(); auto length1 = 0.5*(length12+length34); return length1; }
[ "steva44@hotmail.com" ]
steva44@hotmail.com
814c0fda71f904cd5eb0c15fda0a3820337ba65a
2eaf8fbfc07e5e1cd906a7146ad2a5ef7d2e6208
/Algorithm_TP6/lib/graph.cpp
d86b9cfb74c80f6d294d66da197086f76a6573ef
[]
no_license
LibertAntoine/Algorithmic_TP
3a5cd5d492aa535cddaff17ea1fdadd5b520081a
73e09833e0ddf455255313fbecadcd839daf218d
refs/heads/master
2022-12-23T23:01:08.147730
2020-10-08T11:24:07
2020-10-08T11:24:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,952
cpp
#include "graph.h" #include "mainwindow.h" #include <stdexcept> #include <sstream> #include <memory> #include <time.h> #include <chrono> #include <thread> #include <QString> Edge::Edge(GraphNode *source, GraphNode *destination, int distance) { this->next = nullptr; this->source = source; this->destination = destination; this->distance = distance; } Graph::Graph(int size) { this->allocatedSize = size; this->nodes = new GraphNode*[this->allocatedSize]; memset(this->nodes, 0, sizeof(GraphNode*) * this->allocatedSize); this->_nodesCount = 0; } int Graph::nodesCount() { return _nodesCount; } void Graph::appendNewNode(GraphNode* node) { this->nodes[_nodesCount] = node; this->_nodesCount++; if (this->_nodesCount >= this->allocatedSize) { GraphNode** old = this->nodes; this->allocatedSize *= 2; this->nodes = new GraphNode*[this->allocatedSize]; memcpy(this->nodes, old, sizeof(GraphNode*) * this->_nodesCount); delete old; } std::this_thread::sleep_for(std::chrono::milliseconds(MainWindow::instruction_duration*2)); } GraphNode &Graph::operator[](int index) { if (index >= _nodesCount) { QString error_msg("get(): Index out of bound -> index: %1, size: %2"); throw std::runtime_error(error_msg.arg(index).arg(_nodesCount) .toStdString()); } return *this->nodes[index]; } GraphNode::GraphNode(int value) { this->edges = nullptr; this->value = value; } GraphNode::GraphNode(const GraphNode &other) { this->edges = other.edges; this->value = other.value; } void GraphNode::appendNewEdge(GraphNode* destination, int distance) { Edge* oldFirst = this->edges; this->edges = new Edge(this, destination, distance); this->edges->next = oldFirst; std::this_thread::sleep_for(std::chrono::milliseconds(MainWindow::instruction_duration)); } std::string GraphNode::toString() const { std::ostringstream stringStream; stringStream << " Node<" << this->value << "> "; return stringStream.str(); }
[ "duncan-arrakis@hotmail.fr" ]
duncan-arrakis@hotmail.fr
ae85cca3525d9ac3a9cf898e83a11cc985b6d2ca
f67d0b2d8ecbc6c697cd122002b149866675f69b
/3-Pokemon/phase1/pokemon.cpp
213f2e1eea71b2d3eafc198993786838a23d5148
[]
no_license
PRAGMATISM-630/BUPT-project
e41e8588c67ae5aecbcc1df88d562b3df3e591d6
3934c1c5913abacfc06188d02e3657203f8fc17a
refs/heads/main
2023-05-28T18:23:41.749769
2021-06-11T06:48:08
2021-06-11T06:48:08
375,922,985
0
0
null
null
null
null
UTF-8
C++
false
false
1,789
cpp
#include"pokemon.h" pokemon::pokemon() //构造函数 { level=1; exp=0; } pokemon::~pokemon(){} //析构函数 int pokemon::gainExp(uint Exp) //获得经验函数 { bool levelUp=false; //判断是否升级的标志 exp+=Exp; while(exp>=levelUpExperience[level+1]) //升级后各属性提升 { level++; //升级时四项属性线性增加 atk+=5; maxHp+=60; def+=2; spd+=3; //主属性获得额外的10%的指数增幅 if(type=="highAtk") atk*=1.1; if(type=="highDef") def*=1.1; if(type=="highHp") maxHp*=1.1; if(type=="highSpd") spd*=1.1; //升级时生命值回复满 hp=maxHp; levelUp=true; } if(levelUp) return level; else return -1; //返回-1表示未升级 } int pokemon::takeDamage(uint dmg) //承受伤害函数 { int tmp=dmg-def; //敌方攻击值减去我方防御值 if(tmp>0) //敌人攻击值高于我方防御值,造成伤害 { if(hp<tmp) //我方死亡 tmp=hp; //造成的伤害只能为死亡前所剩生命值 hp-=tmp; } else //敌方攻击未能破防 tmp=0; return tmp; } bool pokemon::judgeDeath() //判断是否死亡 { if(hp==0) return true; else return false; } void pokemon::setAttributeValue(QString Type, QString Name, uint Atk, uint Def, uint MaxHp, int Hp, uint Spd) //设置属性值 { type=Type; name=Name; atk=Atk; def=Def; maxHp=MaxHp; hp=Hp; spd=Spd; }
[ "noreply@github.com" ]
noreply@github.com
252c9c757ee5f0232b58e109cdf8526be520c2b4
00e12f487319ee90c2d64ec312f61daf503773bd
/MyCppLearning/程序清单4.cpp
a5032b9a02aded08f490078b386b1c773fdc4739
[]
no_license
sk-timan/MyCppLearning
8e733a474b0122adbd85b8aac8274c479c427d6b
23715bb3a028ad042ce33a92fe434e0237483452
refs/heads/master
2022-07-21T15:05:44.159437
2022-06-24T10:15:49
2022-06-24T10:15:49
229,739,882
1
0
null
null
null
null
GB18030
C++
false
false
18,219
cpp
#include <iostream> #include <cstring> #include <string> #include <vector> #include <array> #include "pch.h" using namespace std; //4.1 arrayone.cpp -- small arrays of integers void ProgramList_4_1(void) { int yams[3]; yams[0] = 7; yams[1] = 8; yams[2] = 6; int yamcosts[3] = { 20,30,5 }; cout << "Total yams = "; cout << yams[0] + yams[1] + yams[2] << endl; cout << "The package with " << yams[1] << " yams costs "; cout << yamcosts[1] << " cents per yam.\n"; int total = yams[0] * yamcosts[0] + yams[1] * yamcosts[1]; total = total + yams[2] * yamcosts[2]; cout << "The total yam expense is " << total << " cents.\n"; cout << "\nSize of yams array = " << sizeof yams; cout << " bytes.\n"; cout << "Size of one element = " << sizeof yams[0]; cout << " bytes.\n"; } //4.2 strings.cpp -- storing strings in an array void ProgramList_4_2(void) { const int Size = 15; char name1[Size]; char name2[Size] = "C++owboy"; cout << "Howdy! I'm " << name2; cout << "! What's your name?\n"; cin >> name1; cout << "Well, " << name1 << ", your name has "; cout << strlen(name1) << " letters ans is stored\n"; cout << "in an array of " << sizeof name1 << " bytes.\n"; cout << "Your initial is " << name1[0] << ".\n"; name2[3] = '\0'; cout << "Here are the first 3 characters of my name: "; cout << name2 << endl; } //4.3 instr1.cpp -- reading more than one string void ProgramList_4_3(void) { const int ArSize = 20; char name[ArSize]; char dessert[ArSize]; cout << "Enter your name:\n"; cin >> name; //input "Alistair Dreeb",空格符将前面存储到name中,后面填入dessert中. cout << "Enter your favorite dessert:\n"; cin >> dessert; cout << "I have some delicious " << dessert; cout << " for you, " << name << ".\n"; } //4.4 instr2.cpp -- reading more than one word with getline void ProgramList_4_4(void) { const int ArSize = 20; char name[ArSize]; char dessert[ArSize]; cout << "Enter your name:\n"; cin.getline(name, ArSize); //getline以换行符作为字符串结尾,并将换行符替换为空字符. cout << "Enter your favorite dessert:\n"; cin.getline(dessert, ArSize); cout << "I have some delicious " << dessert; cout << " for you, " << name << ".\n"; cin.get(name, ArSize).get(); //get 保留换行符,留到输入队列; cin.get()读取下一个字符(即使换行符) cin.get(dessert, ArSize).get(); cout << name << "\n" << dessert << endl; } //4.6 numstr.cpp -- following number input with line input void ProgramList_4_6(void) { int year; char address[80]; cout << "What year was your house built?\n"; cin >> year; cout << "What is its street address?\n"; //cin.get(); //加一个get即可解决 cin.getline(address, 80); //前面cin 之后换行符保留,getline将认为此为空行, cout << "Year Built: " << year << endl; cout << "Address: " << address << endl; cout << "Done!\n"; } //4.7 strtype1.cpp -- using the C++ string class void ProgramList_4_7(void) { char charr1[20]; char charr2[20] = "jaguar"; string str1; string str2 = "panther"; cout << "Enter a kind of feline: "; cin >> charr1; cout << "Enter another kind of feline: "; cin >> str1; cout << "Here are some feline:\n"; cout << charr1 << " " << charr2 << " " << str1 << " " << str2 << endl; cout << "The third letter in " << charr2 << " is " << charr2[2] << endl; cout << "The third letter in " << str2 << " is " << str2[2] << endl; } //4.8 strtype2.cpp --assiging, adding, and appending void ProgramList_4_8(void) { string s1 = "penguin"; string s2, s3; cout << "You can assign one string object to another: s2 = s1\n"; s2 = s1; cout << "s1: " << s1 << ", s2: " << s2 << endl; cout << "You can assign a C-style string to a string object.\n"; cout << "s2 = \"buzzard\"\n"; s2 = "buzzard"; cout << "s2: " << s2 << endl; cout << "You can concatenate string: s3 = s1 + s2\n"; s3 = s1 + s2; cout << "s3: " << s3 << endl; cout << "You can append string.\n"; s1 += s2; cout << "s1 += s2 yields s1 = " << s1 << endl; s2 += " for a day"; cout << "s2 += \" for a day\" yields s2 = " << s2 << endl; } //4.9 strtype3.cpp -- more string class features void ProgramList_4_9(void) { char charr1[20]; char charr2[20] = "jaguar"; string str1; string str2 = "panther"; str1 = str2; strcpy_s(charr1, charr2); //C-style复制,将后者复制给前者 str1 += " paste"; strcat_s(charr1, " juice"); //C-style组合 int len1 = str1.size(); int len2 = strlen(charr1); cout << "The string " << str1 << " contains " << len1 << " characters.\n"; cout << "The string " << charr1 << " contains " << len2 << " characters.\n"; cout << "Enter a Line: "; cin.getline(charr1, 20); cout << "Enter anoher Line: "; getline(cin, str1); //将一行输入读取到string中 cout << charr1 << ", " << str1 << endl; } //4.11 structur.cpp -- a simple structure struct inflatable //structure declaration 定义需要放在声明前 { char name[20]; double volume; double price; }; void ProgramList_4_11(void) { inflatable guest = { "Glorious Gloria", 1.88, 29.99 }; inflatable pal //init in C++11 { "Audacious Arthur", 3.12, 32.99 }; cout << "Expand your guest list with " << guest.name; cout << " and " << pal.name << "!\n"; cout << "You can have both for $"; cout << guest.price + pal.price << "!\n"; inflatable guests[2] //initialing an array of structs { {"Bambi", 0.5, 21.99}, {"Godzilla", 2000, 565.99} }; cout << "The guests " << guests[0].name << " and " << guests[1].name << "\nhave a combined volume of " << guests[0].volume + guests[1].volume << " cubic feet.\n"; } //4.14 address.cpp -- using the & operator to find addresses void ProgramList_4_14(void) { int donuts = 6; double cups = 4.5; cout << "donuts value = " << donuts; cout << " and donuts address = " << &donuts << endl; cout << "cups value = " << cups; cout << " and cups address = " << &cups << endl; } //4.15 pointer.cpp -- our first pointer variable void ProgramList_4_15(void) { int updates = 6; int* p_updates; p_updates = &updates; cout << "Value: updates = " << updates; cout << ", *p_updates = " << *p_updates << endl; cout << "Addresses: &updates = " << &updates; cout << ", p_updates = " << p_updates << endl; *p_updates = *p_updates + 1; cout << "Now updates = " << updates << endl; } //4.17 use_new.cpp -- using the new operator void ProgramList_4_17(void) { int nights = 1001; int* pt = new int; //创建new类型指针 *pt = 1001; cout << "nights value = "; cout << nights << ": location " << &nights << endl; cout << "int "; cout << "value = " << *pt << ": location = " << pt << endl; double* pd = new double; *pd = 10000001.0; cout << "double "; cout << "value = " << *pd << ": location = " << pd << endl; cout << "location of pointer pd: " << &pd << endl; cout << "size of pt = " << sizeof(pt); cout << ": size of *pt = " << sizeof(*pt) << endl; cout << "size of pd = " << sizeof(pd); cout << "size of *pd = " << sizeof(*pd) << endl; } //4.18 arraynew.cpp -- using the new operator for arrays void ProgramList_4_18(void) { double* p3 = new double[3]; p3[0] = 0.2; p3[1] = 0.5; p3[2] = 0.8; cout << "p3[1] is " << p3[1] << ".\n"; p3 = p3 + 1; //指针+1后,它将指向下一个元素的地址. cout << "Now p3[0] is " << p3[0] << " and "; cout << "p3[1] is " << p3[1] << ".\n"; p3 = p3 - 1; delete[] p3; } //4.19 addpntrs.cpp -- pointer addition void ProgramList_4_19(void) { double wages[3] = { 1000.0, 2000.0, 3000.0 }; short stacks[3] = { 3, 2, 1 }; //Here are two ways to get the address of an array double* pw = wages; //name of an array = address; wages = &wages[0] short* ps = &stacks[0]; //or use address operator cout << "pw = " << pw << ", *pw = " << *pw << endl; pw++; cout << "add 1 to the pw pointer:\n"; cout << "pw = " << pw << ", *pw = " << *pw << "\n\n"; cout << "ps = " << ps << ", *ps = " << *ps << endl; ps++; cout << "add 1 to the ps pointer:\n"; cout << "ps = " << ps << ", *ps = " << *ps << "\n\n"; cout << "access two elements with array notation\n"; cout << "stacks[0] = " << stacks[0] << ", stacks[1] = " << stacks[1] << endl; cout << "access two elements with pointer notation\n"; cout << "*stacks = " << *stacks << ", *(stacks + 1) = " << *(stacks + 1) << endl; //数组名实为第一个元素地址 cout << sizeof(wages) << " = size of wages array\n"; cout << sizeof(pw) << " = size of pw pointer\n"; //地址为16进制int } //4.20 ptrstr.cpp -- using pointers to string void ProgramList_4_20(void) { char animal[20] = "bear"; //char 大小为 1 bytes const char* bird = "wren"; //bird holds address of string char* ps; cout << animal << " and "; //cout 将打出完整地址数组的元素直到遇到空字符 cout << bird << "\n"; cout << "Enter a kind of animal: "; cin >> animal; // input < 20 is okay ps = animal; cout << ps << "!\n"; cout << "before using strcpy():\n"; cout << animal << " at " << (int*)animal << endl; cout << ps << " at " << (int*)ps << endl; ps = new char[strlen(animal) + 1]; //指针指向新地址 +1适应空终止符 cout << "Size of animal = " << sizeof(animal) << endl; cout << "Size of char = " << sizeof(char) << endl; strcpy_s(ps, strlen(animal) + 1, animal); //向ps 植入输入字数 + 1 再乘个1的字节的字符串 cout << "After using strcpy():\n"; cout << animal << " at " << (int*)animal << endl; //(int*)为指针类型强制转换符,char*类型指针需转化为int才能cout出地址 cout << animal << " at " << &animal << endl; cout << ps << " at " << (int*)ps << endl; char test = '6'; char* ptest = &test; cout << "address of " << test << "(test) = " << (int*)&test << endl; cout << "value of " << test << "(test) = " << (int*)test << endl; //字符串6对应的值为ASCII码 cout << "address of ptest = " << &ptest << endl; //指针ptest自己的地址与test不同 cout << "value of ptest = " << (int*)ptest << endl; //指针ptest存储的值为指向的test的地址 test = animal[0]; ptest = animal; cout << "Now, address of " << test << "(test) = " << (int*)&test << endl; cout << "value of " << test << "(test) = " << (int*)test << endl; cout << "address of ptest = " << &ptest << endl; //由此看出,操作的只是存储值,变量本身地址没有变 cout << "value of ptest = " << (int*)ptest << endl; delete[]ps; //释放数组内存 } //4.21 newstrct.cpp -- using new with a structure void ProgramList_4_21(void) { struct inflatable { char name[20]; float volume; double price; }; inflatable* ps = new inflatable; cout << "Enter a name for inflatable item: "; //cin >> (*ps).volume; cin.get(ps->name, 20).get(); //初始状态下,缓冲区为非空,cin.get()工作正常,单个保留回车符 cout << "Enter volume in cubic feet: "; //cin.get((*ps).name, 20); cin >> (*ps).volume; //cin将回车转换为换行符,并保留在输入队列中,并在目标数组中添加空字符 cout << "Enter a name for inflatable item: "; cin.get(); //读取换行符,并继续 cin.get((*ps).name, 20); //若无上步骤,此时cin.get()读到换行符,以为结束,遂跳过并继续保留回车符 cout << "Enter price: $"; cin >> ps->price; //继续读到回车符转换行符,所以一直回车就一直换行 cout << "Name: " << (*ps).name << endl; cout << "Volume: " << ps->volume << " cubic feet\n"; cout << "Price: $" << ps->price << endl; delete ps; } //4.22 delete.cpp -- using the delete operator void ProgramList_4_22(void) { char* getname(void); //function prototype 返回一个char型指针 char* name; name = getname(); cout << name << " at " << (int*)name << "\n"; delete[]name; name = getname(); cout << name << " at " << (int*)name << "\n"; delete[]name; } char* getname(void) { char temp[80]; //函数变量为自动变量,仅在调用函数时产生内存,在结束时消亡; //如果返回的是temp地址,则将很快得到重新应用 cout << "Enter last name: "; cin >> temp; char* pn = new char[strlen(temp) + 1]; //new 另起地址提供给name可以重复访问 strcpy_s(pn, strlen(temp) + 1, temp); return pn; } //4.23 mixtypes.cpp -- some type combinations void ProgramList_4_23(void) { struct antarctica_year_end { int year; }; antarctica_year_end s01, s02, s03; s01.year = 1998; antarctica_year_end* pa = &s02; pa->year = 1999; antarctica_year_end trio[3]; trio[0].year = 2003; cout << trio->year << endl; const antarctica_year_end* arp[3] = { &s01, &s02, &s03 }; //arp为指向结构体类型的指针数组 cout << arp[1]->year << endl; const antarctica_year_end** ppa = arp; //ppa为指针&arp[0]的指针 auto ppb = arp; //C++11 automatic type deduction cout << (*ppa)->year << endl; cout << (*(ppa + 1))->year << endl; } //4.24 choices.cpp -- array variations void ProgramList_4_24(void) { //C, original C++ double a1[4] = { 1.2, 2.4, 3.6, 4.8 }; //C++98 STL vector<double> a2(4); //no simple way to initialize in C98 a2[0] = 1.0 / 3.0; a2[1] = 1.0 / 5.0; a2[2] = 1.0 / 7.0; a2[3] = 1.0 / 9.0; //C++11 --create and initialize array object array<double, 4> a3 = { 3.14, 2.72, 1.62, 1.14 }; //array和数组都存储在栈中 array<double, 4> a4; a4 = a3; //array可以将一个array赋给另一个array,数组必须逐元素复制 cout << "a1[2]: " << a1[2] << " at " << &a1[2] << endl; cout << "a2[2]: " << a2[2] << " at " << &a2[2] << endl; cout << "a3[2]: " << a3[2] << " at " << &a3[2] << endl; cout << "a4[2]: " << a4[2] << " at " << &a4[2] << endl; //a1[-2] = 20.2; //*(a1 - 2) 易出错但合法 a2.at(2) = 2.3; //使用array 和 vector的成员函数at()赋值 //cout << "a1[-2]: " << a1[-2] << " at " << &a1[-2] << endl; cout << "a2[2]: " << a2[2] << " at " << &a2[2] << endl; cout << "a3[2]: " << a3[2] << " at " << &a3[2] << endl; cout << "a4[2]: " << a4[2] << " at " << &a4[2] << endl; } enum num { Yes = 1, No = 0, Maybe = 2 }; /*练习题*/ /*--------------------------------------------*/ //4.13.1 void Exam_4_1(void) { char firstname[20], lastname[20]; char grade; int age; cout << "What is your first name? "; cin.getline(firstname, 20); //cout << firstname << endl; cout << "What is your last name? "; cin.getline(lastname, 20); cout << "What letter grade do you deserve? "; cin >> grade; cout << "What is your age? "; cin >> age; cout << "Name: " << lastname << ", " << firstname << endl; cout << "Grade: " << grade << "\n"; cout << "Age: " << age << endl; } //4.13.2 void Exam_4_2(void) { string name, dessert; cout << "Enter your name:\n"; getline(cin, name); cout << "Enter your favorite dessert:\n"; cin >> dessert; cout << "I have some delicious " << dessert; cout << " for you, " << name << ".\n"; } //4.13.3 void Exam_4_3(void) { char firstname[20], lastname[20], combine[20]; cout << "Enter your first name: "; cin.getline(firstname, 20); cout << "Enter your last name: "; cin.getline(lastname, 20); strcpy_s(combine, lastname); strcat_s(combine, ", "); strcat_s(combine, firstname); cout << "Here's the information in a single string: " << combine << endl; } //4.13.4 void Exam_4_4(void) { string firstname, lastname, combine; cout << "Enter your first name: "; getline(cin, firstname); cout << "Enter your last name: "; getline(cin, lastname); combine = lastname + ", " + firstname; cout << "Here is the information in a single string: " << combine << endl; } //4.13.5 struct CandyBar { char brand[20]; double weight; int caloryie; }; void Exam_4_5(void) { CandyBar snack = { "Mocha Munch", 2.3, 350 }; cout << "snack's brand: " << snack.brand << ".\n"; cout << "snack's weight = " << snack.weight << " g.\n"; cout << "snack's surger = " << snack.caloryie << " cal." << endl; } //4.13.6 void Exam_4_6(void) { CandyBar mycandy[3] = { {"Doveo", 2.0, 300}, {"Beturce", 5.5, 600}, {"Lione", 4.3, 500} }; cout << mycandy[1].brand << "'s calories = " << mycandy[1].caloryie << " cal.\n"; } //4.13.7 struct Pizza { char company[20]; double diameter; double weight; }; void Exam_4_7(void) { Pizza newpizza; cout << "Enter Company's name: "; cin.getline(newpizza.company, 20); cout << "Enter pizza's diameter: "; cin >> newpizza.diameter; cout << "Enter pizza's weight: "; cin >> newpizza.weight; cout << newpizza.company << "'s pizza: " << newpizza.diameter << " cm; " << newpizza.weight << " g." << endl; } //4.13.8 void Exam_4_8(void) { Pizza* newpizza = new Pizza; cout << "Enter pizza's diameter: "; cin >> newpizza->diameter; cin.get(); cout << "Enter pizza's company: "; cin.getline(newpizza->company, 20); cout << "Enter pizza's weight: "; cin >> newpizza->weight; cout << newpizza->company << "'s pizza: " << newpizza->diameter << " cm; " << newpizza->weight << " g." << endl; delete newpizza; } //4.13.9 void Exam_4_9(void) { CandyBar* mycandy = new CandyBar[3]; mycandy[0] = { "Doveo", 2.0, 300 }; mycandy[1] = { "Beturce", 5.5, 600 }; mycandy[2] = { "Lione", 4.3, 500 }; cout << mycandy[1].brand << "'s calories = " << mycandy[1].caloryie << " cal.\n"; delete[]mycandy; } //4.13.10 void Exam_4_10(void) { array<double, 3> score; double average; cout << "Enter first score: "; cin >> score[0]; cout << "Enter second score: "; cin >> score[1]; cout << "Enter third score: "; cin >> score[2]; average = (score[0] + score[1] + score[2]) / 3; cout << "Your average score = " << average << endl; }
[ "1596120742@qq.com" ]
1596120742@qq.com
2800cdb80b940a1300c6b83aababf17cfe53d590
f2fc267da5581dbd80041e3be4f5b006706c2266
/bindings/python/swig/generic_objectPYTHON_wrap.h
1a9bc15190d147c1a36f5ed06edaa4f2f8af4a9b
[]
no_license
nimishb/refractor_framework
08c9ef78109f8a8abc0306b99e370ff2ff6e59e2
09ed81b25b2a3fb6034dd50e147b282ce1359ba7
refs/heads/master
2021-01-21T01:16:27.667104
2017-07-27T18:42:43
2017-07-27T18:42:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
633
h
/* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 3.0.8 * * This file is not intended to be easily readable and contains a number of * coding conventions designed to improve portability and efficiency. Do not make * changes to this file unless you know what you are doing--modify the SWIG * interface file instead. * ----------------------------------------------------------------------------- */ #ifndef SWIG_generic_object_WRAP_H_ #define SWIG_generic_object_WRAP_H_ #include <map> #include <string> #endif
[ "James.McDuffie@jpl.nasa.gov" ]
James.McDuffie@jpl.nasa.gov
5ff550bf1bbb356fa1033274636b01d41a7f2624
896bdcc5ae1baf3eae5e1581224d355b029c2983
/drivers/TARGET_DISCO_F769NI/LCD_DISCO_F769NI/LCD_DISCO_F769NI.h
92747cecba7d4b1a93d8810fb853ca0757ab9500
[]
no_license
JojoS62/testSTM32F407VE_BLACK_ETH
03b83163b3509b11675231a54b9f7f06f7ce5618
16d0583055a531283670c30254959c468e5451d3
refs/heads/master
2020-09-26T04:43:26.049233
2019-12-07T17:26:38
2019-12-07T17:26:38
226,168,316
1
0
null
null
null
null
UTF-8
C++
false
false
14,772
h
/* Copyright (c) 2010-2011 mbed.org, MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef __LCD_DISCO_F769NI_H #define __LCD_DISCO_F769NI_H #ifdef TARGET_DISCO_F769NI #include "mbed.h" #include "stm32f769i_discovery_lcd.h" /* This class drives the LCD display (4-inch 800x472 LCD-TFT) present on STM32F769I-DISCO board. Usage: #include "mbed.h" #include "LCD_DISCO_F769NI.h" LCD_DISCO_F769NI lcd; int main() { lcd.DisplayStringAt(0, LINE(1), (uint8_t *)"MBED EXAMPLE", CENTER_MODE); wait(1); lcd.Clear(LCD_COLOR_BLUE); lcd.SetBackColor(LCD_COLOR_BLUE); lcd.SetTextColor(LCD_COLOR_WHITE); lcd.DisplayStringAt(0, LINE(5), (uint8_t *)"DISCOVERY STM32F769NI", CENTER_MODE); while(1) { } } */ class LCD_DISCO_F769NI { public: //! Constructor LCD_DISCO_F769NI(); //! Destructor ~LCD_DISCO_F769NI(); /** * @brief Initializes the DSI LCD. * @param None * @retval LCD state */ uint8_t Init(void); /** * @brief Initializes the DSI LCD. * The ititialization is done as below: * - DSI PLL ititialization * - DSI ititialization * - LTDC ititialization * - OTM8009A LCD Display IC Driver ititialization * @param None * @retval LCD state */ uint8_t InitEx(LCD_OrientationTypeDef orientation); /** * @brief Initializes the DSI for HDMI monitor. * The ititialization is done as below: * - DSI PLL ititialization * - DSI ititialization * - LTDC ititialization * - DSI-HDMI ADV7533 adapter device ititialization * @param format : HDMI format could be HDMI_FORMAT_720_480 or HDMI_FORMAT_720_576 * @retval LCD state */ uint8_t HDMIInitEx(uint8_t format); /** * @brief BSP LCD Reset * Hw reset the LCD DSI activating its XRES signal (active low for some time); * and desactivating it later. */ void Reset(void); /** * @brief Gets the LCD X size. * @retval Used LCD X size */ uint32_t GetXSize(void); /** * @brief Gets the LCD Y size. * @retval Used LCD Y size */ uint32_t GetYSize(void); /** * @brief Set the LCD X size. * @param imageWidthPixels : uint32_t image width in pixels unit * @retval None */ void SetXSize(uint32_t imageWidthPixels); /** * @brief Set the LCD Y size. * @param imageHeightPixels : uint32_t image height in lines unit */ void SetYSize(uint32_t imageHeightPixels); /** * @brief Initializes the LCD layers. * @param LayerIndex: Layer foreground or background * @param FB_Address: Layer frame buffer * @retval None */ void LayerDefaultInit(uint16_t LayerIndex, uint32_t FB_Address); /** * @brief Selects the LCD Layer. * @param LayerIndex: Layer foreground or background */ void SelectLayer(uint32_t LayerIndex); /** * @brief Sets an LCD Layer visible * @param LayerIndex: Visible Layer * @param State: New state of the specified layer * This parameter can be one of the following values: * @arg ENABLE * @arg DISABLE */ void SetLayerVisible(uint32_t LayerIndex, FunctionalState State); /** * @brief Configures the transparency. * @param LayerIndex: Layer foreground or background. * @param Transparency: Transparency * This parameter must be a number between Min_Data = 0x00 and Max_Data = 0xFF */ void SetTransparency(uint32_t LayerIndex, uint8_t Transparency); /** * @brief Sets an LCD layer frame buffer address. * @param LayerIndex: Layer foreground or background * @param Address: New LCD frame buffer value */ void SetLayerAddress(uint32_t LayerIndex, uint32_t Address); /** * @brief Sets display window. * @param LayerIndex: Layer index * @param Xpos: LCD X position * @param Ypos: LCD Y position * @param Width: LCD window width * @param Height: LCD window height */ void SetLayerWindow(uint16_t LayerIndex, uint16_t Xpos, uint16_t Ypos, uint16_t Width, uint16_t Height); /** * @brief Configures and sets the color keying. * @param LayerIndex: Layer foreground or background * @param RGBValue: Color reference */ void SetColorKeying(uint32_t LayerIndex, uint32_t RGBValue); /** * @brief Disables the color keying. * @param LayerIndex: Layer foreground or background */ void ResetColorKeying(uint32_t LayerIndex); /** * @brief Sets the LCD text color. * @param Color: Text color code ARGB(8-8-8-8); */ void SetTextColor(uint32_t Color); /** * @brief Gets the LCD text color. * @retval Used text color. */ uint32_t GetTextColor(void); /** * @brief Sets the LCD background color. * @param Color: Layer background color code ARGB(8-8-8-8); */ void SetBackColor(uint32_t Color); /** * @brief Gets the LCD background color. * @retval Used background color */ uint32_t GetBackColor(void); /** * @brief Sets the LCD text font. * @param fonts: Layer font to be used */ void SetFont(sFONT *fonts); /** * @brief Gets the LCD text font. * @retval Used layer font */ sFONT *GetFont(void); /** * @brief Reads an LCD pixel. * @param Xpos: X position * @param Ypos: Y position * @retval RGB pixel color */ uint32_t ReadPixel(uint16_t Xpos, uint16_t Ypos); /** * @brief Clears the whole currently active layer of LTDC. * @param Color: Color of the background */ void Clear(uint32_t Color); /** * @brief Clears the selected line in currently active layer. * @param Line: Line to be cleared */ void ClearStringLine(uint32_t Line); /** * @brief Displays one character in currently active layer. * @param Xpos: Start column address * @param Ypos: Line where to display the character shape. * @param Ascii: Character ascii code * This parameter must be a number between Min_Data = 0x20 and Max_Data = 0x7E */ void DisplayChar(uint16_t Xpos, uint16_t Ypos, uint8_t Ascii); /** * @brief Displays characters in currently active layer. * @param Xpos: X position (in pixel); * @param Ypos: Y position (in pixel); * @param Text: Pointer to string to display on LCD * @param Mode: Display mode * This parameter can be one of the following values: * @arg CENTER_MODE * @arg RIGHT_MODE * @arg LEFT_MODE */ void DisplayStringAt(uint16_t Xpos, uint16_t Ypos, uint8_t *Text, Text_AlignModeTypdef Mode); /** * @brief Displays a maximum of 60 characters on the LCD. * @param Line: Line where to display the character shape * @param ptr: Pointer to string to display on LCD */ void DisplayStringAtLine(uint16_t Line, uint8_t *ptr); /** * @brief Draws an horizontal line in currently active layer. * @param Xpos: X position * @param Ypos: Y position * @param Length: Line length */ void DrawHLine(uint16_t Xpos, uint16_t Ypos, uint16_t Length); /** * @brief Draws a vertical line in currently active layer. * @param Xpos: X position * @param Ypos: Y position * @param Length: Line length */ void DrawVLine(uint16_t Xpos, uint16_t Ypos, uint16_t Length); /** * @brief Draws an uni-line (between two points); in currently active layer. * @param x1: Point 1 X position * @param y1: Point 1 Y position * @param x2: Point 2 X position * @param y2: Point 2 Y position */ void DrawLine(uint16_t x1, uint16_t y1, uint16_t x2, uint16_t y2); /** * @brief Draws a rectangle in currently active layer. * @param Xpos: X position * @param Ypos: Y position * @param Width: Rectangle width * @param Height: Rectangle height */ void DrawRect(uint16_t Xpos, uint16_t Ypos, uint16_t Width, uint16_t Height); /** * @brief Draws a circle in currently active layer. * @param Xpos: X position * @param Ypos: Y position * @param Radius: Circle radius */ void DrawCircle(uint16_t Xpos, uint16_t Ypos, uint16_t Radius); /** * @brief Draws an poly-line (between many points); in currently active layer. * @param Points: Pointer to the points array * @param PointCount: Number of points */ void DrawPolygon(pPoint Points, uint16_t PointCount); /** * @brief Draws an ellipse on LCD in currently active layer. * @param Xpos: X position * @param Ypos: Y position * @param XRadius: Ellipse X radius * @param YRadius: Ellipse Y radius */ void DrawEllipse(int Xpos, int Ypos, int XRadius, int YRadius); /** * @brief Draws a bitmap picture loaded in the internal Flash (32 bpp); in currently active layer. * @param Xpos: Bmp X position in the LCD * @param Ypos: Bmp Y position in the LCD * @param pbmp: Pointer to Bmp picture address in the internal Flash */ void DrawBitmap(uint32_t Xpos, uint32_t Ypos, uint8_t *pbmp); /** * @brief Draws a full rectangle in currently active layer. * @param Xpos: X position * @param Ypos: Y position * @param Width: Rectangle width * @param Height: Rectangle height */ void FillRect(uint16_t Xpos, uint16_t Ypos, uint16_t Width, uint16_t Height); /** * @brief Draws a full circle in currently active layer. * @param Xpos: X position * @param Ypos: Y position * @param Radius: Circle radius */ void FillCircle(uint16_t Xpos, uint16_t Ypos, uint16_t Radius); /** * @brief Draws a full poly-line (between many points); in currently active layer. * @param Points: Pointer to the points array * @param PointCount: Number of points */ void FillPolygon(pPoint Points, uint16_t PointCount); /** * @brief Draws a full ellipse in currently active layer. * @param Xpos: X position * @param Ypos: Y position * @param XRadius: Ellipse X radius * @param YRadius: Ellipse Y radius */ void FillEllipse(int Xpos, int Ypos, int XRadius, int YRadius); /** * @brief Switch back on the display if was switched off by previous call of DisplayOff();. * Exit DSI ULPM mode if was allowed and configured in Dsi Configuration. */ void DisplayOn(void); /** * @brief Switch Off the display. * Enter DSI ULPM mode if was allowed and configured in Dsi Configuration. */ void DisplayOff(void); /** * @brief Set the brightness value * @param BrightnessValue: [00: Min (black);, 100 Max] */ void SetBrightness(uint8_t BrightnessValue); /** * @brief Returns the ID of connected screen by checking the HDMI * (adv7533 component); ID or LCD DSI (via TS ID) ID. * @param None * @retval LCD ID */ static uint16_t LCD_IO_GetID(void); /** * @brief De-Initializes the BSP LCD Msp * Application can surcharge if needed this function implementation. */ __weak void MspDeInit(void); /** * @brief Initialize the BSP LCD Msp. * Application can surcharge if needed this function implementation */ __weak void MspInit(void); /** * @brief Draws a pixel on LCD. * @param Xpos: X position * @param Ypos: Y position * @param RGB_Code: Pixel color in ARGB mode (8-8-8-8); */ void DrawPixel(uint16_t Xpos, uint16_t Ypos, uint32_t RGB_Code); /** * @brief Draws a character on LCD. * @param Xpos: Line where to display the character shape * @param Ypos: Start column address * @param c: Pointer to the character data */ static void DrawChar(uint16_t Xpos, uint16_t Ypos, const uint8_t *c); /** * @brief Fills a triangle (between 3 points);. * @param x1: Point 1 X position * @param y1: Point 1 Y position * @param x2: Point 2 X position * @param y2: Point 2 Y position * @param x3: Point 3 X position * @param y3: Point 3 Y position */ static void FillTriangle(uint16_t x1, uint16_t x2, uint16_t x3, uint16_t y1, uint16_t y2, uint16_t y3); /** * @brief Fills a buffer. * @param LayerIndex: Layer index * @param pDst: Pointer to destination buffer * @param xSize: Buffer width * @param ySize: Buffer height * @param OffLine: Offset * @param ColorIndex: Color index */ static void LL_FillBuffer(uint32_t LayerIndex, void *pDst, uint32_t xSize, uint32_t ySize, uint32_t OffLine, uint32_t ColorIndex); /** * @brief Converts a line to an ARGB8888 pixel format. * @param pSrc: Pointer to source buffer * @param pDst: Output color * @param xSize: Buffer width * @param ColorMode: Input color mode */ static void LL_ConvertLineToARGB8888(void *pSrc, void *pDst, uint32_t xSize, uint32_t ColorMode); private: }; #else #error "This class must be used with DISCO_F746NG board only." #endif // TARGET_DISCO_F746NG #endif
[ "sn2010@onlinehome.de" ]
sn2010@onlinehome.de
ce64c7825a0f85c5d3d62d6202afad55660c0e13
31965d3125b23e955a45230b89e17a8bb96377e5
/moon/MoonDb/gameDb/LocalDBType.hpp
ba6dc919b6a0f3edaea84435a62e2ac563d47c4f
[]
no_license
jiyahan/moon
18e5a955c66fbb7251d6b7d67159bdf7c13d99a9
363072cdf3c3d0378b41a0c3237f4e604c7572ab
refs/heads/master
2021-06-04T21:26:13.436132
2016-05-10T06:41:35
2016-05-10T06:41:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,334
hpp
#pragma once namespace GameDBType { /** ????????? ??????????洢??CharDesc??????У??洢???н????????????????? ?洢?????????????????С????濪??????????Ч??????????????? ?ж????????????????????б???????????????????????????? ??????????????????????????????????????????? **/ typedef struct CharDesc { const INT64 nCharId; //???ID????const??????????? const INT64 nUserId; //???ID????const??????????? const CHAR sCharName[48]; //??????????const??????????? const CHAR sAccount[64]; //???????????????????const??????????? WORD wState; //?????1???????CharDescState?е????????? WORD wLevel; //??? BYTE btGender; //??? BYTE btJob; //?? BYTE btReserve0[2]; //----reserve INT nCreateTime; //???????MiniDateTime?? INT nUpdateTime; //??θ??????MiniDateTime?? INT nLoginIP; //??ε??IP WORD wServerId; //?????????ID BYTE btReserve1[42]; //???????С?192??? }CHARDESC, *PCHARDESC; /** ????????? **/ enum CharDescState { CHARSTATE_DELETED = 0x4000, //??????????? CHARSTATE_DISABLED = 0x8000, //?????????????? }; /** ???ID??????? ???????????????????ID???κ?Ψ???ID? **/ inline static common::STDGUID makeCharId(WORD wServerId) { static WORD wXSeries = (WORD)_getTickCount(); common::STDGUID cid; cid.time = CMiniDateTime::now(); cid.server = wServerId; cid.series = wXSeries++; return cid; } //??????ID??????????б??? //?б??????ID???? struct CharIdSortedDesc { CharDesc *pCharDesc; public: inline INT_PTR compare (const CharIdSortedDesc & another) const { if (pCharDesc->nCharId < another.pCharDesc->nCharId) return -1; else if (pCharDesc->nCharId > another.pCharDesc->nCharId) return 1; //????????????б??д洢???????????????????? else { Assert(pCharDesc == another.pCharDesc); return 0; } } inline INT_PTR compareKey(const INT64 nId) const { if (pCharDesc->nCharId < nId) return -1; else if (pCharDesc->nCharId > nId) return 1; else return 0; } }; //???????????????????б??? //?б????????????? struct CharNameSortedDesc { CharDesc *pCharDesc; public: inline INT_PTR compare (const CharNameSortedDesc & another) const { INT_PTR nRet = strcmp(pCharDesc->sCharName, another.pCharDesc->sCharName); //????????????б??д洢???????????????????? if (nRet == 0) Assert(pCharDesc == another.pCharDesc); return nRet; } inline INT_PTR compareKey(const LPCSTR sName) const { return strcmp(pCharDesc->sCharName, sName); } }; //???????ID??????????б??? //?б????????ID?????????????????????????? struct UserIdSortedDesc { CharDesc *pCharDesc; public: inline INT_PTR compare (const UserIdSortedDesc & another) const { if (pCharDesc->nUserId < another.pCharDesc->nUserId) return -1; else if (pCharDesc->nUserId > another.pCharDesc->nUserId) return 1; else return 0; } inline INT_PTR compareKey(const INT64 nId) const { if (pCharDesc->nUserId < nId) return -1; else if (pCharDesc->nUserId > nId) return 1; else return 0; } }; /** ??????ID????????????б? **/ typedef CCustomSortList<CharIdSortedDesc, INT64> CharIdSortList; /** ??????????????????????б? **/ typedef CCustomSortList<CharNameSortedDesc, LPCSTR> CharNameSortList; /** ???????ID????????????б? **/ typedef CCustomSortList<UserIdSortedDesc, INT64> UserIdSortList; }
[ "chenjiayi_china@126.com" ]
chenjiayi_china@126.com
5bd23b0467eb42cf90c94af138fdc5e8390d683b
c53eb8bca022c20dbdf4194c9c4eccfbf3e6ae89
/firmware/src/sys/stdlib.cpp
b1190164fc9613f46a9294ed9831b024c57371bb
[ "MIT" ]
permissive
lavallc/ion
d0fca39f602356e942377106eb06a21eaaee4724
c9292e832309a14f0725ab8794be75c0a9f10cef
refs/heads/master
2020-04-06T03:32:28.861124
2015-07-22T01:11:32
2015-07-22T01:11:32
39,477,562
5
1
null
null
null
null
UTF-8
C++
false
false
1,363
cpp
/* tinynew.cpp Overrides operators new and delete globally to reduce code size. Public domain, use however you wish. If you really need a license, consider it MIT: http://www.opensource.org/licenses/mit-license.php - Eric Agan Elegant Invention */ #include <new> #include <malloc.h> void* operator new(std::size_t size) { return malloc(size); } void* operator new[](std::size_t size) { return malloc(size); } void operator delete(void* ptr) { free(ptr); } void operator delete[](void* ptr) { free(ptr); } /* Optionally you can override the 'nothrow' versions as well. This is useful if you want to catch failed allocs with your own debug code, or keep track of heap usage for example, rather than just eliminate exceptions. */ void* operator new(std::size_t size, const std::nothrow_t&) { return malloc(size); } void* operator new[](std::size_t size, const std::nothrow_t&) { return malloc(size); } void operator delete(void* ptr, const std::nothrow_t&) { free(ptr); } void operator delete[](void* ptr, const std::nothrow_t&) { free(ptr); } extern "C"{ void __cxa_pure_virtual() { while(1); } } //eof
[ "ericb@ericbarch.com" ]
ericb@ericbarch.com
48941612600ece842911bc42bd97a17a6c3d92f6
4b53a32dc0a1a474e4991a9d4c65a1c5dd0a17c5
/bench/extract-timing-function.h
bf3eb19cac39c9ac1a5afad309bc62be66014bab
[]
no_license
pkhuong/set-covering-decomposition
d58e3cb727422d2035027314b171b318fa322449
4bc2c98176cc41791c55cf7ec1b68b3261e5d93f
refs/heads/master
2022-09-04T02:30:09.892118
2019-08-01T23:53:10
2019-08-02T00:08:44
190,045,252
0
0
null
null
null
null
UTF-8
C++
false
false
1,495
h
#ifndef BENCH_EXTRACT_TIMING_FUNCTION_H #define BENCH_EXTRACT_TIMING_FUNCTION_H #include "absl/base/casts.h" #include "absl/strings/string_view.h" #include "bench/internal/dynamic-loading.h" #include "bench/timing-function.h" namespace bench { // Attempts to dlopen `shared_open_path`, and calls `function_name()` // (which must be appropriately mangled, or simply declared `extern // "C"`) to obtain a `TimingFunction<ResultType, ..., Genresult>`, // i.e., an // `internal::ExplicitFunction<internal::TimedResult<ResultType>, // GenResult>`. // // This type does its own consistency checking internally, so obvious // type mismatches should be detected that way, at runtime. // // This function dies noisily on error. template <typename ResultType, typename GenResult> std::pair<TimingFunction<ResultType, void, GenResult>, internal::DLCloser> ExtractTimingFunction(const std::string& shared_object_path, const std::string& function_name) { using FnRet = TimingFunction<ResultType, void, GenResult>; static constexpr bool kIsProbablyABISafe = FnRet::kIsProbablyABISafe; std::pair<void*, internal::DLCloser> opened = internal::OpenOrDie<kIsProbablyABISafe>()(shared_object_path, function_name); auto timing_fn_generator = absl::bit_cast<FnRet (*)()>(opened.first); return std::make_pair(timing_fn_generator(), std::move(opened.second)); } } // namespace bench #endif /*!BENCH_EXTRACT_TIMING_FUNCTION_H */
[ "pvk@pvk.ca" ]
pvk@pvk.ca
2c2c98b2e5c5462da6fbc82626f6265d9da2b862
d371e974386b3be6c535b761e5fac3d34cafe8c7
/hd-search/ionic-euclidean-dist.cc
0529473f35030c77de00dcb1cfe9a7fd76e00eca
[ "Apache-2.0" ]
permissive
l-nic/lnic-apps
cf961b5ee70f84f4ce19c1a098524ff3a2ddc6a7
1f39855dbde5f195ee8e5c48ec10bea1c8d883cd
refs/heads/main
2023-01-29T01:22:24.115334
2020-12-10T17:27:16
2020-12-10T17:27:16
320,200,644
2
0
null
null
null
null
UTF-8
C++
false
false
3,444
cc
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> #include "ionic.h" #define VECTOR_COUNT 10000 #define VECTOR_SIZE 64 #define VECTOR_SIZE_BYTES (VECTOR_SIZE * sizeof(uint16_t)) #define VECTOR_SIZE_WORDS (VECTOR_SIZE_BYTES / 8) #include "euclidean-distance.c" #define PRINT_TIMING 0 #define NCORES 1 #define USE_ONE_CONTEXT 1 // Expected address of the load generator uint64_t load_gen_ip = 0x0a000001; uint16_t vectors[VECTOR_COUNT][VECTOR_SIZE]; void send_startup_msg(int cid, uint64_t context_id) { uint64_t app_hdr = (load_gen_ip << 32) | (0 << 16) | (2*8); uint64_t cid_to_send = cid; ionic_write_r(app_hdr); ionic_write_r(cid_to_send); ionic_write_r(context_id); } int run_server(int cid, uint64_t context_id) { #if PRINT_TIMING uint64_t t0, t1, t2, t3; #endif // PRINT_TIMING uint64_t app_hdr; uint64_t service_time, sent_time; uint64_t query_vector[VECTOR_SIZE_WORDS]; printf("[%d] Server listenning on context_id=%ld.\n", cid, context_id); send_startup_msg(cid, context_id); while (1) { ionic_wait(); #if PRINT_TIMING t0 = rdcycle(); #endif // PRINT_TIMING app_hdr = ionic_read(); //printf("[%d] --> Received msg of length: %u bytes\n", cid, (uint16_t)app_hdr); service_time = ionic_read(); sent_time = ionic_read(); for (unsigned i = 0; i < VECTOR_SIZE_WORDS; i++) query_vector[i] = ionic_read(); uint64_t haystack_vector_cnt = ionic_read(); uint64_t closest_vector_id = 0, closest_vector_dist = 0; #if PRINT_TIMING t1 = rdcycle(); #endif // PRINT_TIMING for (unsigned i = 0; i < haystack_vector_cnt; i++) { uint64_t vector_id = ionic_read(); if (vector_id > VECTOR_COUNT) printf("Invalid vector_id=%lu\n", vector_id); uint64_t dist = compute_dist_squared((uint16_t *)query_vector, vectors[vector_id-1]); if (closest_vector_id == 0 || dist < closest_vector_dist) { closest_vector_id = vector_id; closest_vector_dist = dist; } } #if PRINT_TIMING t2 = rdcycle(); #endif // PRINT_TIMING uint64_t msg_len = 8 + 8 + 8; ionic_write_r((app_hdr & (IP_MASK | CONTEXT_MASK)) | msg_len); ionic_write_r(service_time); ionic_write_r(sent_time); ionic_write_r(closest_vector_id); ionic_msg_done(); #if PRINT_TIMING t3 = rdcycle(); printf("[%d] haystack_vectors=%lu closest=%lu Load lat: %ld Compute lat: %ld Send lat: %ld Total lat: %ld\n", cid, haystack_vector_cnt, closest_vector_id, t1-t0, t2-t1, t3-t2, t3-t0); #endif // PRINT_TIMING } return EXIT_SUCCESS; } extern "C" { bool is_single_core() { return false; } int core_main(int argc, char** argv, int cid, int nc) { (void)argc; (void)argv; (void)nc; uint64_t priority = 0; uint64_t context_id = USE_ONE_CONTEXT ? 0 : cid; if (cid == 0) { #if 1 for (unsigned i = 0; i < VECTOR_COUNT; i++) for (unsigned j = 0; j < VECTOR_SIZE; j+=8) { vectors[i][j+0] = 1; vectors[i][j+1] = 1; vectors[i][j+2] = 1; vectors[i][j+3] = 1; vectors[i][j+4] = 1; vectors[i][j+5] = 1; vectors[i][j+6] = 1; vectors[i][j+7] = 1; } //memset(vectors, 1, sizeof(vectors)); #endif } if (cid > (NCORES-1)) { //ionic_add_context(context_id, priority); //send_startup_msg(cid, context_id); return EXIT_SUCCESS; } else { ionic_add_context(context_id, priority); } int ret = run_server(cid, context_id); return ret; } }
[ "theojepsen@g-m-a-i-l-dotcom" ]
theojepsen@g-m-a-i-l-dotcom
3526085593dbf10d5bfdaef6f14093c09ff535b9
cdd33e81ec5b203b1e0d34eb1522629d027cd911
/Version 1.9.1/test/ESP8266_I2C_DHT_OTA_VOLT_SLEEP.ino
1705489f3a1a05a20986c8a92adefba839b442bf
[]
no_license
OzolsTheusz/Feinstaubsensor
c86f20c5bd5aa1482a0fd01b72d28417ba0e13ba
74b60a1b888ff90d9c309ac797230b8d6d8ed3c9
refs/heads/master
2020-06-20T17:36:51.892094
2019-10-14T15:18:06
2019-10-14T15:18:06
197,194,516
1
0
null
null
null
null
UTF-8
C++
false
false
7,798
ino
#include <ESP8266WiFi.h> #include <PubSubClient.h> #include <Wire.h> #include "Adafruit_MCP9808.h" #include <ESP8266mDNS.h> #include <WiFiUdp.h> #include <ArduinoOTA.h> #include "DHTesp.h" #ifdef ESP32 #pragma message(THIS EXAMPLE IS FOR ESP8266 ONLY!) #error Select ESP8266 board. #endif #include <NDIRZ16.h> #include <SoftwareSerial.h> // Topics to Subscribe and to Publish #define MQTT_INTOPIC "42nibbles/MQTT/SENSOR/TEMPERATUR" #define MQTT_WINKEL "42nibbles/MQTT/SENSOR/WINKEL" #define MQTT_TEMP "42nibbles/MQTT/SENSOR/AUSSEN/TEMP" #define MQTT_TEMP2 "42nibbles/MQTT/SENSOR/AUSSEN/TEMP2" #define MQTT_HUM "42nibbles/MQTT/SENSOR/AUSSEN/HUM" #define MQTT_VOLT "42nibbles/MQTT/SENSOR/AUSSEN/VOLT" #define MQTT_STATUS "42nibbles/MQTT/SENSOR/AUSSEN/STATUS" #define MQTT_WILL "42nibbles/MQTT/SENSOR/WILL" #define MQTT_OTA "42nibbles/MQTT/SENSOR/AUSSEN/OTA" #define MQTT_CO2 "42nibbles/MQTT/SENSOR/AUSSEN/CO2" #define MQTT_SLEEP "42nibbles/MQTT/SLEEP" // definition of DHT-sensor #define DHTTYPE DHT11 // DHT 11 #define DHTPIN 13 // what digital pin we're connected to SoftwareSerial s_serial(14, 12); // TX, RX for the CO2-Sensor #define sensor s_serial const unsigned char cmd_get_sensor[] = { 0xff, 0x01, 0x86, 0x00, 0x00, 0x00, 0x00, 0x00, 0x79 }; unsigned char dataRevice[9]; int temperature; int CO2PPM; DHTesp dht; // Update these with values suitable for your network. /* Credentials Wulfen Dimker Allee Achtung!!! für Campuswoche anpassen */ // const char* ssid = "FRITZ!Box 7490"; /* Credentials FH-Dortmund FB4 Informatik Hardware 1 Labor */ const char* ssid = "hw1_gast"; const char* password = "KeineAhnung"; const char* mqtt_server = "dz-pi.hw1.fb4.fh"; /* Variables */ char msg[50]; long lastMsg = 0; int value = 0; bool sleep = true; /* Create Instances */ Adafruit_MCP9808 tempsensor = Adafruit_MCP9808(); ADC_MODE(ADC_VCC); // internal VCC to ESP WiFiClient espClient; PubSubClient client(espClient); void callback(char* topic, byte* payload, unsigned int length) { Serial.print("Message arrived ["); Serial.print(topic); Serial.print("] "); for (uint8_t i = 0; i < length; i++) { Serial.print((char)payload[i]); } Serial.println(); if ( (String)topic == (String) MQTT_SLEEP) { // Switch on the LED if an 1 was received as first character Serial.println("Sleep! "); if ((char)payload[0] == '1') { sleep = true; } else { sleep = false; } } } bool dataRecieve(void) { byte data[9]; uint8_t i=0; //transmit command data for(i=0; i<sizeof(cmd_get_sensor); i++) { sensor.write(cmd_get_sensor[i]); } delay(10); //begin reveiceing data if(sensor.available()) { while(sensor.available()) { for(i=0; i<9; i++) { data[i] = sensor.read(); Serial.print(data[i]); Serial.print(" "); } Serial.println(""); } } for(uint8_t j=0; j<9; j++) { Serial.print(data[j]); Serial.print(" "); } Serial.println(""); if((i != 9) || (1 + (0xFF ^ (byte)(data[1] + data[2] + data[3] + data[4] + data[5] + data[6] + data[7]))) != data[8]) { CO2PPM = (int)data[2] * 256 + (int)data[3]; temperature = (int)data[4] - 40; return false; } CO2PPM = (int)data[2] * 256 + (int)data[3]; temperature = (int)data[4] - 40; Serial.print("CO2-Konzentration: "); Serial.print(CO2PPM); Serial.println(" ppm"); return true; } void setup_wifi(void) { delay(10); WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); Serial.print("Try to connect to: "); Serial.println(ssid); while (WiFi.status() != WL_CONNECTED) { Serial.print("."); delay(500); } } void reconnect() { while (!client.connected()) { Serial.print("Attempting MQTT connection..."); String clientId = "ESP8266_Sensor1"; if (client.connect(clientId.c_str())) { Serial.print(clientId); Serial.println(" connected"); // client.subscribe(MQTT_OTA); client.subscribe(MQTT_SLEEP); } else { Serial.print("failed, rc="); Serial.print(client.state()); Serial.println(" try again in 5 seconds"); delay(5000); } } } void setup_ota() { // Port defaults to 8266 ArduinoOTA.setPort(8266); // Hostname defaults to esp8266-[ChipID] // ArduinoOTA.setHostname("myesp8266"); ArduinoOTA.setHostname("ESP8266-Aussen"); // No authentication by default ArduinoOTA.setPassword((const char *)"12345"); ArduinoOTA.onStart([]() { Serial.println("Start"); }); ArduinoOTA.onEnd([]() { Serial.println("\nEnd"); }); ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { Serial.printf("Progress: %u%%\r", (progress / (total / 100))); }); ArduinoOTA.onError([](ota_error_t error) { Serial.printf("Error[%u]: ", error); if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed"); else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed"); else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed"); else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed"); else if (error == OTA_END_ERROR) Serial.println("End Failed"); }); ArduinoOTA.begin(); Serial.println("OTA Ready"); } void setup() { sensor.begin(9600); Serial.begin(115200); Serial.println(); Serial.setTimeout(25); setup_wifi(); setup_ota(); Serial.println(""); Serial.print("MAC: "); Serial.print(WiFi.macAddress()); Serial.print("/topcis"); Serial.println(); // Wire.begin(4,5); // start I2C, define PINs // while (!tempsensor.begin()) { // Serial.println("Couldn't find MCP9808!"); // delay(500); // } client.setServer(mqtt_server, 1883); client.setCallback(callback); // Serial.println("\tRun = 0, \r\n\tConfig = 1!"); delay(1000); lastMsg = millis(); dht.setup(DHTPIN, DHTesp::DHTTYPE); // Connect DHT sensor to GPIO defined } void loop() { // ArduinoOTA.handle(); delay(dht.getMinimumSamplingPeriod()); if (!client.connected()) { reconnect(); } client.loop(); long now = millis(); // if ((now - lastMsg) > 5000) // { lastMsg = now; delay(250); // float celsius = tempsensor.readTempC(); // MCP9808 Temp-Sensor float humidity = dht.getHumidity(); float temperature = dht.getTemperature(); if(dataRecieve()) { Serial.print("Temperature: "); Serial.print(temperature); Serial.print(" CO2: "); Serial.print(CO2PPM); Serial.println(""); snprintf (msg, 75, "%d", CO2PPM); client.publish(MQTT_CO2, msg, true); } int espVcc = ESP.getVcc(); client.publish(MQTT_STATUS,"ALIVE", true); Serial.print("Voltage = "); Serial.print(espVcc); Serial.println(" mV"); snprintf (msg, 75, "%d", espVcc); client.publish(MQTT_VOLT, msg, true); Serial.print("Feuchte = "); Serial.println(humidity, 1); snprintf (msg, 75, "%d", (int)(humidity + 0.5)); client.publish(MQTT_HUM, msg, true); Serial.print("Temperature 1 = "); Serial.println(temperature, 1); // Serial.print("Temperature 2 = "); // Serial.println(celsius, 1); // snprintf (msg, 75, "%d", (int) (temperature + 0.5)); // client.publish(MQTT_TEMP, msg, true); snprintf (msg, 75, "%d", (int)(temperature + 0.5)); client.publish(MQTT_TEMP2, msg, true); if (sleep) { Serial.println("Deepsleep for 120 seconds"); client.publish(MQTT_STATUS,"SLEEP", true); delay(100); ESP.deepSleep(120e6); } // } }
[ "noreply@github.com" ]
noreply@github.com
3ca627ebe5d01aff5007d9d565f74c7449f2861f
1ca93975e2bee5026d61f539176d606547891252
/Structural/Adapter/HelloWorldAdapter.h
fd3d5c72d35ffb91864c06d3b40cffd06fb59fa4
[ "MIT" ]
permissive
dodaydream/hello_world_in_design_patterns
7a7d0027eded953090ecc41798a4e5bd3738ef38
525de263bf7b75cdaf2450a760ccc118ca0cddfd
refs/heads/master
2021-07-18T17:33:34.509939
2020-05-05T14:51:38
2020-05-05T14:51:38
148,476,875
0
0
null
null
null
null
UTF-8
C++
false
false
215
h
#include "HelloWorld.h" class HelloWorldAdapter { private: HelloWorld &hw; std::ostream& os; public: HelloWorldAdapter(std::ostream &os, HelloWorld &hw): os(os), hw(hw) { } void sayHelloWorld(); };
[ "daydream2013@live.com" ]
daydream2013@live.com
a55e59370378f801f429aca9e0260844e6c1a408
c7df87c952e9f1b397bbca3a1b87f97e78c43244
/src/sender/connections.h
fab817ef042b352f5564f26db2069e85156f988c
[]
no_license
void-/bless
9dfa878e0bf5d97855dfdaf19aab0fa4383e501f
6abe6d072bc3214e1c05fd003abecfa649ab3b82
refs/heads/master
2021-01-10T01:28:33.103971
2016-03-12T08:55:19
2016-03-12T08:55:19
44,029,927
1
0
null
null
null
null
UTF-8
C++
false
false
3,506
h
/** * @file * @brief manage network connections between the Sender and the Server. */ #ifndef CONNECTIONS_H #define CONNECTIONS_H #include "auth.h" #include <botan/pubkey.h> #include <botan/tls_client.h> #include <botan/tls_session_manager.h> #include <botan/credentials_manager.h> #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <arpa/inet.h> #include <bless/message.h> namespace Bless { /** * @class Channel * @brief connection to the Server. * * This is the secure channel from the Sender to the Server. * * Call init(), connect(), then sendMessage(). * * @var Botan::TLS::Client *Channel::client * @brief TLS client that holds state about the connection to the Server * * @var Botan::TLS::Policy *Channel::policy * @brief the policy used when negotiating the TLS connection * * @var Botan::TLS::Session_Manager *Channel::sessionManager * @brief nop session manager used to manage saved TLS sessions; does * nothing * * @var Botan::TLS::Credentials_Manager *Channel::credentialsManager * @brief store credentials for TLS connection; interfaces AuthKeys for TLS * * @var Botan::TLS::Server_Information *Channel::serverInformation * @brief information about the Server, of which there is none * * @var size_t Channel::bufferSize * @brief the size, in bytes, used for stack-allocated buffers * * @var int Channel::handshakeTimeout * @brief the number of milliseconds to timeout at when handshaking the DTLS * connection * * @var int Channel::channelTimeout * @brief the maximum length of time, in milliseconds, to wait between * channel messages before the message channel is considered stale * * @var Channel::recvCallback * @brief callback when an authenticated message comes in. * * @var AuthKeys *Channel::authKeys * @brief keys used to authenticate the TLS channel. * * @var int Channel::connection * @brief socket descriptor for the connection to the Server. * * @var sockaddr_in Channel::connectionInfo * @brief socket structure information about Channel::connection * * @var Botan::RandomNumberGenerator Channel::rng * @brief random number generator used to connect and send messages. */ class Channel { public: Channel(); ~Channel(); int init(AuthKeys *keys, const std::string &server, unsigned short port, Botan::RandomNumberGenerator *rng_); int connect(); int recvKey(EphemeralKey &out, Botan::Public_Key const &verify); int sendMessage(Message const &message); protected: Botan::TLS::Client *client; Botan::TLS::Policy *policy; Botan::TLS::Session_Manager *sessionManager; Botan::Credentials_Manager *credentialsManager; Botan::TLS::Server_Information *serverInformation; void send(const Botan::byte *const payload, size_t len); void recvData(const Botan::byte *const payload, size_t len); void alert(Botan::TLS::Alert alert, const Botan::byte *const payload, size_t len); bool handshake(const Botan::TLS::Session &session); static const size_t bufferSize = 4096; static const int handshakeTimeout = 1 * 1000; static const int channelTimeout = 120 * 1000; OpaqueEphemeralKey tempKey; private: AuthKeys *authKeys; int connection; sockaddr_in connectionInfo; Botan::RandomNumberGenerator *rng; }; } #endif //CONNECTIONS_H
[ "mr.alex.guy@gmail.com" ]
mr.alex.guy@gmail.com
aa95bc646ee21cdfe6580974776d6a8e442b4896
d584de52cfae0291943c3a8374e8a707571db4d7
/1154.cpp
11f71e81742616a9144ed7d2494deb4a841b2e62
[]
no_license
iamyeasin/URI
99987faaafe808c975b667a1bd7e411d1101db59
23fd8013571f19885ffbd910545164019d2398d6
refs/heads/master
2020-12-03T02:03:18.470020
2017-09-11T14:54:29
2017-09-11T14:54:29
95,899,756
0
0
null
null
null
null
UTF-8
C++
false
false
371
cpp
#include<bits/stdc++.h> using namespace std; int main() { int x,counter=0; int sum =0; while(scanf("%d",&x)) { if(x >= 0) { sum += x; counter++; } else { printf("%.2lf\n",(sum*1.00)/counter*1.00); break; } } return 0; }
[ "noreply@github.com" ]
noreply@github.com
bb93432331ec2e677b0fe4698adc468477ad3e52
f279fa731406c5214b958e8070ee5664ea92c81f
/1914_HanoiTower/Main.cpp
6fc652cebebcbda22e103e972f125cd774d7b474
[]
no_license
93Hong/Algorithms
14a7ea2c8f402aaea6c76d7a83f795434bea26cc
b56512912131dc0149d4960b88aa76df6926119d
refs/heads/master
2020-12-31T00:02:12.959480
2017-12-05T13:02:59
2017-12-05T13:02:59
86,582,927
4
0
null
null
null
null
UTF-8
C++
false
false
427
cpp
#include <cstdio> #include <cmath> #pragma warning(disable:4996) using namespace std; int cnt = 0; void hanoi(int n, int s, int e, int temp) { if (n <= 1) { printf("%d -> %d\n", s, e); return; } cnt++; hanoi(n - 1, s, temp, e); hanoi(1, s, e, temp); hanoi(n - 1, temp, e, s); } int main() { int N; scanf("%d", &N); long long cnt = pow(2, N) - 1; printf("%lld\n", cnt); if (N < 20) hanoi(N, 1, 3, 2); }
[ "sk2rldnr@gmail.com" ]
sk2rldnr@gmail.com
f3577b6f90e37edd1af4f6b4cb0850cdb1f4fb37
f81b774e5306ac01d2c6c1289d9e01b5264aae70
/chrome/browser/nearby_sharing/incoming_frames_reader.h
8de1b854f013e43ed31f0898fb8c48354b68f0a4
[ "BSD-3-Clause" ]
permissive
waaberi/chromium
a4015160d8460233b33fe1304e8fd9960a3650a9
6549065bd785179608f7b8828da403f3ca5f7aab
refs/heads/master
2022-12-13T03:09:16.887475
2020-09-05T20:29:36
2020-09-05T20:29:36
293,153,821
1
1
BSD-3-Clause
2020-09-05T21:02:50
2020-09-05T21:02:49
null
UTF-8
C++
false
false
3,333
h
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_NEARBY_SHARING_INCOMING_FRAMES_READER_H_ #define CHROME_BROWSER_NEARBY_SHARING_INCOMING_FRAMES_READER_H_ #include <map> #include <vector> #include "base/callback_forward.h" #include "base/cancelable_callback.h" #include "base/memory/weak_ptr.h" #include "base/optional.h" #include "base/sequence_checker.h" #include "base/time/time.h" #include "chrome/browser/nearby_sharing/nearby_process_manager.h" #include "chrome/services/sharing/public/mojom/nearby_decoder_types.mojom.h" class NearbyConnection; class Profile; // Helper class to read incoming frames from Nearby devices. class IncomingFramesReader : public NearbyProcessManager::Observer { public: IncomingFramesReader(NearbyProcessManager* process_manager, Profile* profile, NearbyConnection* connection); ~IncomingFramesReader() override; // Reads an incoming frame from |connection|. |callback| is called // with the frame read from connection or nullopt if connection socket is // closed. // // Note: Callers are expected wait for |callback| to be run before scheduling // subsequent calls to ReadFrame(..). virtual void ReadFrame( base::OnceCallback<void(base::Optional<sharing::mojom::V1FramePtr>)> callback); // Reads a frame of type |frame_type| from |connection|. |callback| is called // with the frame read from connection or nullopt if connection socket is // closed or |timeout| units of time has passed. // // Note: Callers are expected wait for |callback| to be run before scheduling // subsequent calls to ReadFrame(..). virtual void ReadFrame( sharing::mojom::V1Frame::Tag frame_type, base::OnceCallback<void(base::Optional<sharing::mojom::V1FramePtr>)> callback, base::TimeDelta timeout); private: // NearbyProcessManager::Observer: void OnNearbyProfileChanged(Profile* profile) override; void OnNearbyProcessStarted() override; void OnNearbyProcessStopped() override; void ReadNextFrame(); void OnDataReadFromConnection(base::Optional<std::vector<uint8_t>> bytes); void OnFrameDecoded(sharing::mojom::FramePtr mojo_frame); void OnTimeout(); void Done(base::Optional<sharing::mojom::V1FramePtr> frame); base::Optional<sharing::mojom::V1FramePtr> GetCachedFrame( base::Optional<sharing::mojom::V1Frame::Tag> frame_type); NearbyProcessManager* process_manager_; Profile* profile_; NearbyConnection* connection_; base::Optional<sharing::mojom::V1Frame::Tag> frame_type_; base::OnceCallback<void(base::Optional<sharing::mojom::V1FramePtr>)> callback_; base::CancelableOnceClosure timeout_callback_; // Caches frames read from NearbyConnection which are not used immediately. std::map<sharing::mojom::V1Frame::Tag, sharing::mojom::V1FramePtr> cached_frames_; bool is_process_stopped_ = false; ScopedObserver<NearbyProcessManager, NearbyProcessManager::Observer> nearby_process_observer_{this}; SEQUENCE_CHECKER(sequence_checker_); base::WeakPtrFactory<IncomingFramesReader> weak_ptr_factory_{this}; }; #endif // CHROME_BROWSER_NEARBY_SHARING_INCOMING_FRAMES_READER_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
a5ae25efa45018b81e0655aa5427219c9d634c07
a840a5e110b71b728da5801f1f3e591f6128f30e
/debug/client/linux/misc.cpp
e923e12cbc395a9663b95a8f98a9300b3041ce4d
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
tpltnt/binnavi
0a25d2fde2c6029aeef4fcfec8eead5c8e51f4b4
598c361d618b2ca964d8eb319a686846ecc43314
refs/heads/master
2022-10-20T19:38:30.080808
2022-07-20T13:01:37
2022-07-20T13:01:37
107,143,332
0
0
Apache-2.0
2023-08-20T11:22:53
2017-10-16T15:02:35
Java
UTF-8
C++
false
false
1,520
cpp
// Copyright 2011-2016 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <iostream> void printStartMessage() { std::cout << "BinNavi debug client for Linux32 applications" << std::endl; std::cout << "Build date: " << __TIME__ << " " << __DATE__ << std::endl; std::cout << std::endl; } char szUsage[] = { "=============================================================================\n" " Usage: For regular, user-mode Linux debugging type:\n " " clientl32 [PID|PATH] [PORT] [OPTIONS]\n" " [ PID ] Process ID or name of the process to attach to\n" " [ PATH ] Path to the executable\n" " [ PORT ] TCP Port to bind to for communication (default is 2222)\n" " [ OPTIONS ] One of ...\n" " -v Verbose mode \n" " -vv Very verbose mode \n" " -lf filename Filename of the logfile\n" "=============================================================================\n" };
[ "cblichmann@google.com" ]
cblichmann@google.com
0fd0fa838cf016558f13f95d6ef2e0a4e9948927
c081da944564198439995b5ede33d8451a600971
/ortogonal.h
a589e35dfa88f927af6a62f036bbef8638ec19d5
[]
no_license
FreddyJRC/-EDD-Proyecto1
302ad97a838d53d562ac41f4108d0332874a31a9
a00fe88a6ea7d947fd28e8825e6f06a7e2f3d8dc
refs/heads/master
2020-03-29T06:57:55.390068
2017-06-29T15:27:38
2017-06-29T15:27:38
94,659,957
0
0
null
null
null
null
UTF-8
C++
false
false
1,411
h
#ifndef ORTOGONAL_H #define ORTOGONAL_H #include <vector> #include <string> typedef struct Nodo Nodo; typedef struct Encabezado Encabezado; typedef struct ListaEncabezados ListaEncabezados; typedef struct Matriz Matriz; struct Nodo { int fila; int columna; int nivel; char * valor; int color; bool isDrawable; Nodo * derecha; Nodo * izquierda; Nodo * arriba; Nodo * abajo; Nodo * enfrente; Nodo * atras; Nodo(int nivel, int fila, int columna, char * valor, int color); Nodo *hasMached(); }; struct Encabezado { int id; Encabezado * siguiente; Encabezado * anterior; Nodo * acceso; Encabezado(int id); }; struct ListaEncabezados { Encabezado * primero; void insertar(Encabezado * nuevo); Encabezado * getEncabezado(int id); }; struct Matriz { ListaEncabezados * eFilas; ListaEncabezados * eColumnas; ListaEncabezados * eNiveles; Matriz(); void insertar(int nivel, int fila, int columna, char * valor, int color); void eliminar(Nodo * actual); void recorrerFilas(); void recorrerColumnas(); void graficar(int nivel); void mover(std::vector<std::string> move, int turn); Nodo * getFloor(int fila, int columna); Nodo * getClosest(Nodo * floor, int nivel, int dir); Nodo * findNodo(int nivel, int fila, int columna); }; int idToInt(char id); #endif // ORTOGONAL_H
[ "fj.ram.contr@gmail.com" ]
fj.ram.contr@gmail.com
532fc0f3319e0c7f541919c5be7a975d06393126
9d0cfa52dc15cb529baf3ddfd83ead07c698ad55
/Graphics/Canvas.cpp
6dcd568261f3addd59f4acb9950d8df88bb4a259
[]
no_license
cha0s/avocado-cpp-core
4917fcbe0308f9af48607ef59197a63da1e66aa1
a206fdb2c78936dade9dc147ea394f4de4b6dd11
refs/heads/master
2016-08-11T18:06:07.536014
2014-06-12T23:48:50
2014-06-12T23:48:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
448
cpp
#include "../avocado-global.h" #include "Canvas.h" namespace avo { FactoryManager<Canvas> Canvas::factoryManager; Canvas::Canvas() { } Canvas::~Canvas() { } bool Canvas::isNull() const { return width() != 0 && height() != 0; } void Canvas::setUri(const boost::filesystem::path &uri) { m_uri = uri; } boost::filesystem::path Canvas::uri() const { return m_uri; } unsigned int Canvas::sizeInBytes() { return width() * height() * 4; } }
[ "cha0s@therealcha0s.net" ]
cha0s@therealcha0s.net
c0a41d814d2b5a9936eacde4fc79fd9a6eab6f24
5ec06dab1409d790496ce082dacb321392b32fe9
/clients/cpp-tizen/generated/src/ComAdobeCqSocialCommonsEmailreplyImplCommentEmailEventListenerInfo.h
84887467fafd2a9ba0e1ab85b6f57ce1ba53e405
[ "Apache-2.0" ]
permissive
shinesolutions/swagger-aem-osgi
e9d2385f44bee70e5bbdc0d577e99a9f2525266f
c2f6e076971d2592c1cbd3f70695c679e807396b
refs/heads/master
2022-10-29T13:07:40.422092
2021-04-09T07:46:03
2021-04-09T07:46:03
190,217,155
3
3
Apache-2.0
2022-10-05T03:26:20
2019-06-04T14:23:28
null
UTF-8
C++
false
false
2,057
h
/* * ComAdobeCqSocialCommonsEmailreplyImplCommentEmailEventListenerInfo.h * * */ #ifndef _ComAdobeCqSocialCommonsEmailreplyImplCommentEmailEventListenerInfo_H_ #define _ComAdobeCqSocialCommonsEmailreplyImplCommentEmailEventListenerInfo_H_ #include <string> #include "ComAdobeCqSocialCommonsEmailreplyImplCommentEmailEventListenerProperties.h" #include "Object.h" /** \defgroup Models Data Structures for API * Classes containing all the Data Structures needed for calling/returned by API endpoints * */ namespace Tizen { namespace ArtikCloud { /*! \brief * * \ingroup Models * */ class ComAdobeCqSocialCommonsEmailreplyImplCommentEmailEventListenerInfo : public Object { public: /*! \brief Constructor. */ ComAdobeCqSocialCommonsEmailreplyImplCommentEmailEventListenerInfo(); ComAdobeCqSocialCommonsEmailreplyImplCommentEmailEventListenerInfo(char* str); /*! \brief Destructor. */ virtual ~ComAdobeCqSocialCommonsEmailreplyImplCommentEmailEventListenerInfo(); /*! \brief Retrieve a string JSON representation of this class. */ char* toJson(); /*! \brief Fills in members of this class from JSON string representing it. */ void fromJson(char* jsonStr); /*! \brief Get */ std::string getPid(); /*! \brief Set */ void setPid(std::string pid); /*! \brief Get */ std::string getTitle(); /*! \brief Set */ void setTitle(std::string title); /*! \brief Get */ std::string getDescription(); /*! \brief Set */ void setDescription(std::string description); /*! \brief Get */ ComAdobeCqSocialCommonsEmailreplyImplCommentEmailEventListenerProperties getProperties(); /*! \brief Set */ void setProperties(ComAdobeCqSocialCommonsEmailreplyImplCommentEmailEventListenerProperties properties); private: std::string pid; std::string title; std::string description; ComAdobeCqSocialCommonsEmailreplyImplCommentEmailEventListenerProperties properties; void __init(); void __cleanup(); }; } } #endif /* _ComAdobeCqSocialCommonsEmailreplyImplCommentEmailEventListenerInfo_H_ */
[ "cliffano@gmail.com" ]
cliffano@gmail.com
15ad25db2d480c9dc4d729b634038d7235b3dd91
3b09cf62f1ab38791ec338adfb31351742e18efe
/VulkanEngine/VHCommand.cpp
c58d102ba6b76c19ee0148859fd484ed8e9d28b9
[ "MIT" ]
permissive
Clasc/ViennaVulkanEngine
d62576ca6db90f0247994c8fa4cae64bc1bedd58
47d8b2d9cff4d3c6c112e311561a6f2b9d3e707c
refs/heads/master
2023-06-04T05:45:15.210019
2021-01-29T07:16:36
2021-01-29T07:16:36
347,482,394
0
0
MIT
2021-05-12T07:17:21
2021-03-13T21:27:31
null
UTF-8
C++
false
false
9,347
cpp
/** * The Vienna Vulkan Engine * * (c) bei Helmut Hlavacs, University of Vienna * */ #include "VHHelper.h" namespace vh { //------------------------------------------------------------------------------------------------------- /** * * \brief Create a new command pool * * \param[in] physicalDevice Physical Vulkan device * \param[in] device Logical Vulkan device * \param[in] surface Window surface - Needed for finding the right queue families * \param[out] commandPool New command pool for allocating command bbuffers * \returns VK_SUCCESS or a Vulkan error code * */ VkResult vhCmdCreateCommandPool( VkPhysicalDevice physicalDevice, VkDevice device, VkSurfaceKHR surface, VkCommandPool *commandPool) { QueueFamilyIndices queueFamilyIndices = vhDevFindQueueFamilies(physicalDevice, surface); VkCommandPoolCreateInfo poolInfo = {}; poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; poolInfo.queueFamilyIndex = queueFamilyIndices.graphicsFamily; return vkCreateCommandPool(device, &poolInfo, nullptr, commandPool); } //------------------------------------------------------------------------------------------------------- /** * * \brief Create a number of command buffers * * \param[in] device Logical Vulkan device * \param[in] commandPool Command pool for allocating command bbuffers * \param[in] level Level can be primary or secondary * \param[in] count Number of buffers to create * \param[in] pBuffers Pointer to an array where the buffer handles should be stored * \returns VK_SUCCESS or a Vulkan error code * */ VkResult vhCmdCreateCommandBuffers( VkDevice device, VkCommandPool commandPool, VkCommandBufferLevel level, uint32_t count, VkCommandBuffer *pBuffers) { VkCommandBufferAllocateInfo allocInfo = {}; allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; allocInfo.level = level; allocInfo.commandPool = commandPool; allocInfo.commandBufferCount = count; return vkAllocateCommandBuffers(device, &allocInfo, pBuffers ); } /** * * \brief Start a command buffer for recording commands * * \param[in] device Logical Vulkan device * \param[in] renderPass The render pass that is inherited from the parent command buffer * \param[in] subpass Index of subpass * \param[in] frameBuffer The framebuffer that is rendered into * \param[in] commandBuffer The command buffer to start * \param[in] usageFlags Flags telling how the buffer will be used * \returns VK_SUCCESS or a Vulkan error code * */ VkResult vhCmdBeginCommandBuffer( VkDevice device, VkRenderPass renderPass, uint32_t subpass, VkFramebuffer frameBuffer, VkCommandBuffer commandBuffer, VkCommandBufferUsageFlagBits usageFlags) { VkCommandBufferInheritanceInfo inheritance = {}; inheritance.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_INFO; inheritance.framebuffer = frameBuffer; inheritance.renderPass = renderPass; inheritance.subpass = subpass; VkCommandBufferBeginInfo beginInfo = {}; beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; beginInfo.flags = usageFlags; beginInfo.pInheritanceInfo = &inheritance; return vkBeginCommandBuffer(commandBuffer, &beginInfo); } /** * * \brief Start a command buffer for recording commands * * \param[in] device Logical Vulkan device * \param[in] commandBuffer The command buffer to start * \param[in] usageFlags Flags telling how the buffer will be used * \returns VK_SUCCESS or a Vulkan error code * */ VkResult vhCmdBeginCommandBuffer(VkDevice device, VkCommandBuffer commandBuffer, VkCommandBufferUsageFlagBits usageFlags ) { VkCommandBufferBeginInfo beginInfo = {}; beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; beginInfo.flags = usageFlags; return vkBeginCommandBuffer(commandBuffer, &beginInfo) ; } /** * * \brief Submit a command buffer to a queue * * \param[in] device Logical Vulkan device * \param[in] queue The queue the buffer is sent to * \param[in] commandBuffer The command buffer that is sent to the queue * \param[in] waitSemaphore A semaphore to wait for before submitting * \param[in] signalSemaphore Signal this semaphore after buffer is done * \param[in] waitFence Signal to this fence after buffer is done * \returns VK_SUCCESS or a Vulkan error code * */ VkResult vhCmdSubmitCommandBuffer( VkDevice device, VkQueue queue, VkCommandBuffer commandBuffer, VkSemaphore waitSemaphore, VkSemaphore signalSemaphore, VkFence waitFence) { VkSubmitInfo submitInfo = {}; submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; VkSemaphore waitSemaphores[] = { waitSemaphore }; VkPipelineStageFlags waitStages[] = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT }; if (waitSemaphore != VK_NULL_HANDLE) { submitInfo.waitSemaphoreCount = 1; submitInfo.pWaitSemaphores = waitSemaphores; submitInfo.pWaitDstStageMask = waitStages; } submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &commandBuffer; VkSemaphore signalSemaphores[] = { signalSemaphore }; if (signalSemaphore != VK_NULL_HANDLE) { submitInfo.signalSemaphoreCount = 1; submitInfo.pSignalSemaphores = signalSemaphores; } if (waitFence != VK_NULL_HANDLE) { vkResetFences(device, 1, &waitFence); } return vkQueueSubmit(queue, 1, &submitInfo, waitFence); } /** * * \brief Begin submitting a single time command * * \param[in] device Logical Vulkan device * \param[in] commandPool Command pool for allocating command bbuffers * \returns a new VkCommandBuffer to record commands into * */ VkCommandBuffer vhCmdBeginSingleTimeCommands(VkDevice device, VkCommandPool commandPool ) { VkCommandBufferAllocateInfo allocInfo = {}; allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; allocInfo.commandPool = commandPool; allocInfo.commandBufferCount = 1; VkCommandBuffer commandBuffer; vkAllocateCommandBuffers(device, &allocInfo, &commandBuffer); VkCommandBufferBeginInfo beginInfo = {}; beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; if (vkBeginCommandBuffer(commandBuffer, &beginInfo) != VK_SUCCESS) return VK_NULL_HANDLE; return commandBuffer; } /** * * \brief End recording into a single time command buffer and submit it * * \param[in] device Logical Vulkan device * \param[in] graphicsQueue Queue to submit the buffer to * \param[in] commandPool Give back the command buffer to the pool * \param[in] commandBuffer The ready to be used command buffer * \returns VK_SUCCESS or a Vulkan error code * */ VkResult vhCmdEndSingleTimeCommands(VkDevice device, VkQueue graphicsQueue, VkCommandPool commandPool, VkCommandBuffer commandBuffer) { VkFence waitFence; VkFenceCreateInfo fenceInfo = {}; fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT; vkCreateFence(device, &fenceInfo, nullptr, &waitFence); VkResult result = vhCmdEndSingleTimeCommands( device, graphicsQueue, commandPool, commandBuffer, VK_NULL_HANDLE, VK_NULL_HANDLE, waitFence ); vkDestroyFence(device, waitFence, nullptr); return result; } /** * * \brief End recording into a single time command buffer and submit it * * \param[in] device Logical Vulkan device * \param[in] graphicsQueue Queue to submit the buffer to * \param[in] commandPool Give back the command buffer to the pool * \param[in] commandBuffer The ready to be used command buffer * \param[in] waitSemaphore A semaphore to wait for before submitting * \param[in] signalSemaphore Signal this semaphore after buffer is done * \param[in] waitFence Signal to this fence after buffer is done * \returns VK_SUCCESS or a Vulkan error code * */ VkResult vhCmdEndSingleTimeCommands(VkDevice device, VkQueue graphicsQueue, VkCommandPool commandPool, VkCommandBuffer commandBuffer, VkSemaphore waitSemaphore, VkSemaphore signalSemaphore, VkFence waitFence ) { VHCHECKRESULT( vkEndCommandBuffer(commandBuffer) ); VkSubmitInfo submitInfo = {}; submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; VkSemaphore waitSemaphores[] = { waitSemaphore }; VkPipelineStageFlags waitStages[] = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT }; if (waitSemaphore != VK_NULL_HANDLE) { submitInfo.waitSemaphoreCount = 1; submitInfo.pWaitSemaphores = waitSemaphores; submitInfo.pWaitDstStageMask = waitStages; } submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &commandBuffer; VkSemaphore signalSemaphores[] = { signalSemaphore }; if (signalSemaphore != VK_NULL_HANDLE) { submitInfo.signalSemaphoreCount = 1; submitInfo.pSignalSemaphores = signalSemaphores; } if (waitFence != VK_NULL_HANDLE) { vkResetFences(device, 1, &waitFence); } VHCHECKRESULT( vkQueueSubmit(graphicsQueue, 1, &submitInfo, waitFence) ); if (waitFence != VK_NULL_HANDLE) { VHCHECKRESULT(vkWaitForFences(device, 1, &waitFence, VK_TRUE, std::numeric_limits<uint64_t>::max())); } else VHCHECKRESULT(vkQueueWaitIdle(graphicsQueue)); vkFreeCommandBuffers(device, commandPool, 1, &commandBuffer); return VK_SUCCESS; } }
[ "helmut.hlavacs@univie.ac.at" ]
helmut.hlavacs@univie.ac.at
23d2c52695c89bb363b7f2af8870079b7aa2722e
78477e381ed49a97d0cf70e7c66d562ba585d481
/utilities/inc/loggingTypes.hpp
7ce5314a414cf25dce46fcb5ea53f8765e2b089f
[]
no_license
JusticeBoi/octree
cee1a71cd0d5ed7feded8115b981fb54b1ce5af4
6eaa165c334ec01a48ebd9f3edaf9f5c2b48560d
refs/heads/master
2020-03-30T18:03:01.426392
2019-08-16T07:58:23
2019-08-16T07:58:23
151,481,381
1
0
null
null
null
null
UTF-8
C++
false
false
1,372
hpp
/* ___ __ __ ______ * * / | ____/ // /_ ____ / ____/ __ __ * * / /| | / __ // __ \ / __ \ / / __/ /_ __/ /_ * * / ___ |/ /_/ // / / // /_/ // /___/_ __//_ __/ * * /_/ |_|\__,_//_/ /_/ \____/ \____/ /_/ /_/ * * * * AdhoC++, 2012 Chair for Computation in Engineering, All Rights Reserved. */ #ifndef UTILITIES_LOGGINGTYPES_HPP_ #define UTILITIES_LOGGINGTYPES_HPP_ // --- Internal Includes --- #include <memory> #include <string> #include <vector> namespace utilities { class Section; typedef std::shared_ptr<Section> SectionPtr; struct SectionResult; typedef std::shared_ptr<SectionResult> SectionResultPtr; typedef std::vector<SectionResultPtr> SectionResultVector; class TimeSpan; typedef std::shared_ptr<TimeSpan> TimeSpanPtr; class Scope; typedef std::shared_ptr<Scope> ScopePtr; class BasicScope; typedef std::shared_ptr<BasicScope> BasicScopePtr; class ScopeBehavior; typedef std::shared_ptr<ScopeBehavior> ScopeBehaviorPtr; struct LoopProgressState; typedef std::shared_ptr<LoopProgressState> LoopProgressStatePtr; } // namespace utilities #endif // UTILITIES_LOGGINGTYPES_HPP_
[ "oguzoztoprak@gmail.com" ]
oguzoztoprak@gmail.com
814a469a00ee62753a71b7e840183ca31932367d
4d1b36c9e26afc500fc9011a54b1f0f0b8840c99
/FreshCore/Platforms/Unix/TelnetServer_Unix.cpp
ff81dc5dee5b10606f28b115045b41a8cc6b8428
[ "Apache-2.0" ]
permissive
ElectricToyCo/Fresh
985200cc07bdd6949d9b3ebbd3bee94feccaac73
aea080d858d33f585a196658a5f595898ca35eac
refs/heads/main
2023-04-15T00:29:14.513999
2021-04-23T13:04:42
2021-04-23T13:04:42
343,223,542
0
0
null
null
null
null
UTF-8
C++
false
false
5,570
cpp
// // TelnetServer_Unix.cpp // Fresh // // Created by Jeff Wofford on 2/8/12. // Implementation guided by http://homepages.ius.edu/rwisman/C490/html/tcp.htm. // Copyright (c) 2012 jeffwofford.com. All rights reserved. // #include "FreshDebug.h" #include "TelnetServer.h" #include "Objects.h" #include <map> #include <errno.h> #include <fcntl.h> #include <sys/socket.h> #include <netinet/in.h> namespace { #ifndef SO_NOSIGPIPE # define SO_NOSIGPIPE MSG_NOSIGNAL #endif inline std::string stringForErrno( int errNo ) { const char* const errString = std::strerror( errNo ); return errString ? errString : "<unknown>"; } void setToNonBlock( int socket ) { // Set to non-blocking mode. // int flags = ::fcntl( socket, F_GETFL ); // Get the current flags. if( flags == -1 ) { // Server is failing. Bail out. dev_warning( "TelnetServer failed fcntl() call. Aborting listen." ); return; } if( ::fcntl( socket, F_SETFL, flags | O_NONBLOCK ) == -1 ) { dev_warning( "TelnetServer failed to set non-blocking mode. Telnet will block." ); } } } namespace fr { class TelnetServer_bsd : public TelnetServer { public: virtual void beginListening( const Callback& callback, int port, const std::string& welcomeMessage = "Connected.\n" ) override { ASSERT( !getCallbackOnDataReceived() ); ASSERT( callback ); TelnetServer::beginListening( callback, port, welcomeMessage ); // Attach the SIGPIPE handler to SIG_IGN to avoid exceptions when writing to a disconnected client. // ::signal( SIGPIPE, SIG_IGN ); m_socket = ::socket( PF_INET, SOCK_STREAM, IPPROTO_TCP ); if( m_socket < 0 ) { dev_warning( "TelnetServer failed socket() call. Aborting listen." ); return; } setToNonBlock( m_socket ); struct sockaddr_in socketAddress; ::memset( &socketAddress, 0, sizeof( socketAddress )); socketAddress.sin_family = AF_INET; socketAddress.sin_port = htons( portNumber() ); { int socketOption = 1; // A pigeon boolean: int === bool, 1 === true. ::setsockopt( m_socket, SOL_SOCKET, SO_REUSEADDR, &socketOption, sizeof( socketOption )); } { int socketOption = 1; ::setsockopt( m_socket, SOL_SOCKET, SO_NOSIGPIPE, &socketOption, sizeof( socketOption )); } int result = ::bind( m_socket, reinterpret_cast< sockaddr* >( &socketAddress ), sizeof( socketAddress )); if( result != 0 ) { release_trace( "bind error: " << stringForErrno( errno ) ); return; } result = ::listen( m_socket, 5 /* maximum connections */ ); if( result != 0 ) { release_trace( "listen error: " << stringForErrno( errno ) ); } } virtual bool isListening() const override { return m_socket >= 0; } virtual bool isConnected() const override { return !m_connections.empty(); } virtual void broadcast( const std::string& text ) override { // Send to all connections. // for( const auto& pair : m_connections ) { ::send( pair.first, text.data(), text.size(), 0 /* flags */ ); } } virtual ~TelnetServer_bsd() { ::close( m_socket ); } virtual void updateConnections() override { if( m_socket >= 0 ) { // Check for new connections. // int connectedSocket = ::accept( m_socket, nullptr, nullptr ); if( connectedSocket >= 0 ) { // Found a connection. Set up data transmission. // setToNonBlock( connectedSocket ); Connection connection; connection.m_callback = getCallbackOnDataReceived(); m_connections[ connectedSocket ] = connection; // Send welcome message. // const auto& welcome = welcomeMessage(); if( !welcome.empty() ) { ::send( connectedSocket, welcome.data(), welcome.size(), 0 /* flags */ ); } } // Update ongoing connections. // std::vector< unsigned char > bytes; for( auto iter = m_connections.begin(); iter != m_connections.end(); ) { const auto& connection = *iter; const size_t BUF_LEN = 256; bytes.resize( BUF_LEN ); const auto nBytes = ::recv( connection.first, bytes.data(), BUF_LEN, 0 ); if( nBytes == 0 || nBytes == ssize_t( -1 )) { // Error or just nothing to read (non-blocking)? // if( errno != EWOULDBLOCK ) { dev_warning( "TelnetServer received error " << errno << ". Closing connection " << connection.first << "." ); // Trouble. Close the connection. // ::close( connection.first ); iter = m_connections.erase( iter ); continue; } } else { // Send the buffer data over. // bytes.resize( nBytes ); onDataReceived( connection.first, bytes ); } ++iter; } } } void onDataReceived( int connectedSocket, const std::vector< unsigned char >& bytes ) { // Which connection? // const auto iter = m_connections.find( connectedSocket ); ASSERT( iter != m_connections.end() ); iter->second.onDataReceived( bytes ); } private: std::map< int, Connection > m_connections; int m_socket = -1; FRESH_DECLARE_CLASS( TelnetServer_bsd, TelnetServer ); }; FRESH_DEFINE_CLASS( TelnetServer_bsd ); FRESH_IMPLEMENT_STANDARD_CONSTRUCTORS( TelnetServer_bsd ); FRESH_IMPLEMENT_STANDARD_CONSTRUCTORS( TelnetServer ); TelnetServer::ptr TelnetServer::create( NameRef name ) { return createObject< TelnetServer_bsd >( name ); } }
[ "github@jeffwofford.com" ]
github@jeffwofford.com
3fb98a4bc9c87ef182154bd3b783cd65913ccca8
058e709bb25cc69e0f522921cd45e29abd3b6cb9
/MagicStick/MagicStick.ino
8feb3bb54df0eb2fad1ee4ef6eb92708227ef342
[]
no_license
KazukiHiraizumi/Arduino
a474d4c67c2c3ecc79c76c0f7dc469539c357114
13a778152b1f851efa41b8c47561657a71b5e395
refs/heads/master
2022-08-28T03:06:07.481871
2022-08-14T00:55:12
2022-08-14T00:55:12
202,513,799
0
0
null
null
null
null
UTF-8
C++
false
false
679
ino
#include <Timeout.h> #include <StreamCallback.h> void lighter(void *){ if(digitalRead(4)==LOW){ digitalWrite(8,HIGH); } else{ digitalWrite(8,LOW); } Timeout.set(NULL,lighter,100); } void logger(void *){ Serial.println(!digitalRead(4)); Timeout.set(NULL,logger,100); } void setup() { //Initializing IOs pinMode(4, INPUT_PULLUP); pinMode(8, OUTPUT); //Initializing Serial ports Serial.begin(115200); //Setting callback for Serial new StreamCallback(&Serial,[](char *s){ Serial.print("SER->"); Serial.println(s); }); //Setting callback for Constant scan with Timeout lighter(NULL); logger(NULL); } void loop(){ Timeout.spinOnce(); }
[ "ca-giken@c-able.ne.jp" ]
ca-giken@c-able.ne.jp
2faad35b017e92f83d4eb8be31ab23e556b4a941
e68c1f9134b44ddea144f7efa7523076f3f12d3a
/FinalCode/WizardArcaneOrbSlot.cpp
e442cb91f7bf0a0542b9fd6de1f6f2196e170ba0
[]
no_license
iso5930/Direct-3D-Team-Portfolio
4ac710ede0c9176702595cba5579af42887611cf
84e64eb4e91c7e5b4aed77212cd08cfee038fcd3
refs/heads/master
2021-08-23T08:15:00.128591
2017-12-04T06:14:39
2017-12-04T06:14:39
112,998,717
0
0
null
null
null
null
UHC
C++
false
false
2,875
cpp
#include "StdAfx.h" #include "WizardArcaneOrbSlot.h" CWizardArcaneOrbSlot::CWizardArcaneOrbSlot() { // SlotType m_eSlotType = SLOT_TYPE_WIZARD_SECONDARY; // SlotID m_eSlotID = SLOT_ID_WIZARD_ARCANE_ORB; // CooldownTime m_fCooldownTime = 0.0f; // Time m_fTime = m_fCooldownTime; // Range m_fRange = 9999.f; } CWizardArcaneOrbSlot::~CWizardArcaneOrbSlot() { } SLOT_RESULT CWizardArcaneOrbSlot::Begin(int _iMode) { // Check Enable if (!m_bEnable) { CUIMgr::GetInstance()->CreateTextMessage(_T("아직은 사용 할 수 없습니다.")); return SLOT_RESULT_COOLDOWN_TIEM; } // Check Vision if (m_pOwner->GetStat()->iVision < 30 * (1.0f - m_pOwner->GetReducedVisionConsumption())) { CUIMgr::GetInstance()->CreateTextMessage(_T("비전력이 부족합니다.")); return SLOT_RESULT_VISION_EMPTY; } // Check Pick D3DXVECTOR3 vPos; if(m_pOwner->GetPickObject() == NULL) { CObject* pFind = NULL; CMouse* pMouse = NULL; m_pOwner->GetLayer()->FindObject(pFind , _T("Mouse"), LAYER_TYPE_MOUSE); pMouse = (CMouse*)pFind; if (pMouse->GetMouseOverType() == MOUSE_OVER_TYPE_MONSTER) { CTransformCom* pTransformCom = (CTransformCom*)pMouse->GetOverObject() ->GetComponent(COM_TYPE_TRANSFORM); vPos = pTransformCom->m_vPos; } else if (CInputMgr::GetInstance()->GetPickPos() == NULL) { CUIMgr::GetInstance()->CreateTextMessage(_T("유효하지 않은 지역입니다.")); return SLOT_RESULT_ERROR_PICK; } else vPos = *CInputMgr::GetInstance()->GetPickPos(); } else { CTransformCom* pTransformCom = (CTransformCom*)m_pOwner->GetPickObject() ->GetComponent(COM_TYPE_TRANSFORM); vPos = pTransformCom->m_vPos; } // Begin CSlot::Begin(_iMode); // Dir D3DXVECTOR3 vDir = vPos - m_pTransformCom->m_vPos; D3DXVec3Normalize(&vDir, &vDir); // DotX float fDotX = D3DXVec3Dot(&-m_pTransformCom->m_vAxisX, &vDir); fDotX = RevisionDot(fDotX); // DotZ float fDotZ = D3DXVec3Dot(&-m_pTransformCom->m_vAxisZ, &vDir); fDotZ = RevisionDot(fDotZ); if(fDotX > 0.0f) m_pTransformCom->m_vAngle.y += acosf(fDotZ); else m_pTransformCom->m_vAngle.y -= acosf(fDotZ); CSoundMgr::GetInstance()->PlaySoundForPlayer(_T("ARCANE_ORB.ogg")); // Vision m_pOwner->GetStat()->iVision -= int(30 * (1.0f - m_pOwner->GetReducedVisionConsumption())); CWizard_ArcaneOrb_OrbEffect* pOrbEffect = new CWizard_ArcaneOrb_OrbEffect(NULL, OBJ_TYPE_DYNAMIC, m_pOwner, (vDir * 500.f)); m_pOwner->GetLayer()->AddObject(pOrbEffect, LAYER_TYPE_EFFECT); CTransformCom* pTransformCom = (CTransformCom*)pOrbEffect->GetComponent(COM_TYPE_TRANSFORM); pTransformCom->m_vPos = m_pTransformCom->m_vPos + D3DXVECTOR3(0.f, 70.f, 0.f); pOrbEffect->Initialize(); return SLOT_RESULT_NULL; } SLOT_RESULT CWizardArcaneOrbSlot::Action() { return SLOT_RESULT_NULL; } SLOT_RESULT CWizardArcaneOrbSlot::End() { return SLOT_RESULT_NULL; }
[ "iso5930@naver.com" ]
iso5930@naver.com
8cbf43169c19f89748951c8ba35ee8c6e13b6c71
6337958058108dbd20a521137e7b9833929dbbc6
/src/SpectrumRingBuffer.cpp
b21db3f201ee6b1b4a9eb0522f3d442b073edd02
[]
no_license
Venetian/PercussiveHarmonicDetectionFunction
1692ad1b323db77160d6c5b392d290cf5351c9ff
3dc99b9b1b8281f56fe7c8a124f397ee3739b0aa
refs/heads/master
2020-06-05T04:04:16.262864
2014-10-20T20:46:43
2014-10-20T20:46:43
24,963,721
1
0
null
null
null
null
UTF-8
C++
false
false
4,081
cpp
/* * SpectrumRingBuffer.cpp * BeatSeekerOF * * Created by Andrew on 20/02/2014. * Copyright 2014 QMUL. All rights reserved. * */ #include "SpectrumRingBuffer.h" #include "assert.h" SpectrumRingBuffer::SpectrumRingBuffer(){ bufferSize = 7; fftSize = 8; } SpectrumRingBuffer::~SpectrumRingBuffer(){ } void SpectrumRingBuffer::init(int bSize, int fSize){ //bufferSize is the number of magnitudes to hold printf("initialising buffersize to %i\n", bSize); bufferSize = bSize; fftSize = fSize; fftSizeOver2 = fftSize/2; for (int k = 0; k < bufferSize; k++){ COMPLEX_SPLIT split; split.realp = (float *) malloc(fftSize * sizeof(float)); split.imagp = (float *) malloc(fftSize * sizeof(float)); zapSplit(split); /*for (int i = 0; i < fftSize; i++){ split.realp[i] = 0; split.imagp[i] = 0; } */ splitBuffer.push_back(split); std::vector<float> v; v.assign(fftSizeOver2, 0.0); magnitudes.push_back(v); } fft = new accFFT(fftSize, 0);//0 for float type window = new float[fftSize]; setWindowHanning(window, fftSize); windowedBuffer = new float[fftSize]; } void SpectrumRingBuffer::zapSplit(COMPLEX_SPLIT split){ for (int i = 0; i < fftSize; i++){ split.realp[i] = 0; split.imagp[i] = 0; } } void SpectrumRingBuffer::processBuffer(float* buffer, int numSamples){ //printf("spec ring buf process called\n"); assert (numSamples == fftSize); splitBuffer.pop_front();//take one off the front //window audio input for fft setFFTinput(buffer); COMPLEX_SPLIT newSplit; newSplit.realp = (float *) malloc(fftSize * sizeof(float)); newSplit.imagp = (float *) malloc(fftSize * sizeof(float)); zapSplit(newSplit);//probably dont need to as we will replace all values anyway fft->forward_FFT_f(windowedBuffer, newSplit); // for (int i = 0; i < 15; i++){ // printf("real [%i] %.3f, imag[%i] %.3f\n", i, newSplit.realp[i], i, newSplit.imagp[i]); // } // printSplit(newSplit); splitBuffer.push_back(newSplit); // for (int k = 14; k < 17; k++){ // for (int i = 0; i < 15; i++){ // printf("B[%i] real [%i] %.3f, imag[%i] %.3f\n", k, i, splitBuffer[k].realp[i], i, splitBuffer[k].imagp[i]); // } // } //convert the split version from FFT (Apple way of storing data) to a straightforward magnitude vector std::vector<float> v; getMagnitude(v, newSplit); // magnitudes.erase(magnitudes.begin()); //add this to our deque of magnitudes magnitudes.pop_front(); magnitudes.push_back(v); } void SpectrumRingBuffer::getMagnitude(std::vector<float>& v, COMPLEX_SPLIT& split){ v.reserve(fftSizeOver2+1); v.assign(fftSizeOver2+1, 0.0); v[0] = fabs(split.realp[0]); //printf("SpecRing: mag[%i] %.3f\n", 0, v[0]); for (int i = 1; i < fftSizeOver2; i++){ v[i] = sqrt((split.realp[i]*split.realp[i]) + (split.imagp[i]*split.imagp[i])); } v[fftSizeOver2] = fabs(split.imagp[0]); if (DEBUG_MODE){ for (int i = 0; i < 6; i++) printf("SpecRing: mag[%i] %.5f\n", i, v[i]); } //printf("mag[%i] %.3f\n", fftSizeOver2, v[fftSizeOver2]); } void SpectrumRingBuffer::printBufferEnd(){ for (int k = max(0, bufferSize-3); k < bufferSize; k++){ for (int i = 0; i < 15; i++){ printf("B[%i] real [%i] %.3f, imag[%i] %.3f\n", k, i, splitBuffer[k].realp[i], i, splitBuffer[k].imagp[i]); } } } void SpectrumRingBuffer::printSplit(COMPLEX_SPLIT& split){ for (int i = 0; i < fftSize; i++){ printf("real [%i] %.3f, imag[%i] %.4f\n", i, split.realp[i], i, split.imagp[i]); } } void SpectrumRingBuffer::setFFTinput(float* buffer){ //copies the buffer to fft input with windowing for (int i = 0; i < fftSize; i++){ windowedBuffer[i] = buffer[i] * window[i]; } if (DEBUG_MODE){ for (int i = 0; i < 10; i++) printf("spoecring: buffer[%i] %.5f\n", i, buffer[i]); } } void SpectrumRingBuffer::setWindowHanning(float* window, const int framesize){ double N; // variable to store framesize minus 1 N = (double) (framesize-1); // framesize minus 1 // Hanning window calculation for (int n = 0;n < framesize;n++) { window[n] = 0.5*(1-cos(2*M_PI*(n/N))); } }
[ "andrewrobertson@Andrews-MacBook-Pro-2.local" ]
andrewrobertson@Andrews-MacBook-Pro-2.local
f6a4585ca6284ce5f3388fc45e791872ac8b8d48
19785aa178db01baf70309f83aa0cecd7beb9113
/src/ModuleNodeCluster.cpp
d750538d83f66960d07620700d3c3d03471a38ec
[]
no_license
Jergar92/SiSiMEX
3e0e583b785a02352a82b758ac57357b8ce73f69
3b6d2e368457ae1311b555bccdd939f5ec378517
refs/heads/master
2020-04-04T19:03:21.714386
2018-12-17T09:45:01
2018-12-17T09:45:01
156,189,976
0
0
null
null
null
null
UTF-8
C++
false
false
21,806
cpp
#include "ModuleNodeCluster.h" #include "ModuleNetworkManager.h" #include "ModuleAgentContainer.h" #include "Application.h" #include "Log.h" #include "Packets.h" #include "imgui/imgui.h" #include <sstream> #include <algorithm> #define MAX_ITEM_VALUE 8 #define MIN_ITEM_VALUE 1 enum State { STOPPED, STARTING, RUNNING, STOPPING }; bool ModuleNodeCluster::init() { state = STOPPED; return true; } bool ModuleNodeCluster::start() { state = STARTING; return true; } bool ModuleNodeCluster::update() { bool ret = true; switch (state) { case STARTING: if (startSystem()) { state = RUNNING; } else { state = STOPPED; ret = false; } break; case RUNNING: runSystem(); break; case STOPPING: stopSystem(); state = STOPPED; break; } return ret; } bool ModuleNodeCluster::updateGUI() { ImGui::Begin("Node cluster"); if (state == RUNNING) { // Number of sockets App->networkManager->drawInfoGUI(); // Number of agents App->agentContainer->drawInfoGUI(); ImGui::CollapsingHeader("ModuleNodeCluster", ImGuiTreeNodeFlags_DefaultOpen); int itemsCount = 0; for (auto node : _nodes) { itemsCount += (int)node->itemList().numItems(); } ImGui::TextWrapped("# items in the cluster: %d", itemsCount); int missingItemsCount = 0; for (auto node : _nodes) { missingItemsCount += (int)node->itemList().numMissingItems(); } ImGui::TextWrapped("# missing items in the cluster: %d", missingItemsCount); ImGui::Separator(); if (ImGui::Button("Create random MCCs")) { ClearAgent(); SpawnAgentMCC(); } if (ImGui::Button("Clear all agents")) { ClearAgent(); } ImGui::Separator(); int nodeId = 0; for (auto &node : _nodes) { ImGui::PushID(nodeId); ImGuiTreeNodeFlags flags = 0; std::string nodeLabel = StringUtils::Sprintf("Node %d", nodeId); if (ImGui::CollapsingHeader(nodeLabel.c_str(), flags)) { if (ImGui::TreeNodeEx("Items", flags)) { auto &itemList = node->itemList(); for (int itemId = 0; itemId < MAX_ITEMS; ++itemId) { unsigned int numItems = itemList.numItemsWithId(itemId); if (numItems == 1) { ImGui::Text("Item %d", itemId); } else if (numItems > 1) { ImGui::Text("Item %d (x%d)", itemId, numItems); } } ImGui::TreePop(); } if (ImGui::TreeNodeEx("MCCs", flags)) { for (auto agent : App->agentContainer->allAgents()) { MCC * mcc = agent->asMCC(); if (mcc != nullptr && mcc->node()->id() == nodeId) { ImGui::Text("MCC %d", mcc->id()); ImGui::Text(" - Contributed Item ID: %d", mcc->contributedItemId()); ImGui::Text(" - Constraint Item ID: %d", mcc->constraintItemId()); } } ImGui::TreePop(); } if (ImGui::TreeNodeEx("MCPs", flags)) { for (auto agent : App->agentContainer->allAgents()) { MCP * mcp = agent->asMCP(); if (mcp != nullptr && mcp->node()->id() == nodeId) { ImGui::Text("MCP %d", mcp->id()); ImGui::Text(" - Requested Item ID: %d", mcp->requestedItemId()); ImGui::Text(" - Contributed Item ID: %d", mcp->contributedItemId()); } } ImGui::TreePop(); } } ImGui::PopID(); nodeId++; } } ImGui::End(); if (state == RUNNING) { // NODES / ITEMS MATRIX ///////////////////////////////////////////////////////// ImGui::Begin("Nodes/Items Matrix"); static ItemId selectedItem = 0; ItemId itemId = 0U; static unsigned int selectedNode = 0; static int comboItem = 0; int counter = 0; ImGui::Text("Item ID "); //COMMON ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.5f, 0.5f, 0.5f, 0.5f)); ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(0.5f, 0.5f, 0.5f, 0.5f)); ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.5f, 0.5f, 0.5f, 0.5f)); while(counter < MAX_COMMON_ITEMS) { ImGui::SameLine(); std::ostringstream oss; oss << itemId; ImGui::Button(oss.str().c_str(), ImVec2(20, 20)); if (itemId < MAX_ITEMS - 1) ImGui::SameLine(); ++counter; ++itemId; } ImGui::PopStyleColor(3); counter = 0; //RARE ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.3f, 0.3f, 1.0f, 0.5f)); ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(0.3f, 0.3f, 1.0f, 0.5f)); ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.3f, 0.3f, 1.0f, 0.5f)); while (counter < MAX_RARE_ITEMS) { ImGui::SameLine(); std::ostringstream oss; oss << itemId; ImGui::Button(oss.str().c_str(), ImVec2(20, 20)); if (itemId < MAX_ITEMS - 1) ImGui::SameLine(); ++counter; ++itemId; } ImGui::PopStyleColor(3); counter = 0; //EPIC ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.6f, 0.0f, 1.0f, 0.5f)); ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(0.6f, 0.0f, 1.0f, 0.5f)); ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.6f, 0.0f, 1.0f, 0.5f)); while (counter < MAX_EPIC_ITEMS) { ImGui::SameLine(); std::ostringstream oss; oss << itemId; ImGui::Button(oss.str().c_str(), ImVec2(20, 20)); if (itemId < MAX_ITEMS - 1) ImGui::SameLine(); ++counter; ++itemId; } ImGui::PopStyleColor(3); counter = 0; //LEGEND ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.9f, 0.6f, 0.0f, 0.5f)); ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(0.9f, 0.6f, 0.0f, 0.5f)); ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.9f, 0.6f, 0.0f, 0.5f)); while(counter < MAX_LEGEND_ITEMS) { ImGui::SameLine(); std::ostringstream oss; oss << itemId; ImGui::Button(oss.str().c_str(), ImVec2(20, 20)); if (itemId < MAX_ITEMS - 1) ImGui::SameLine(); ++counter; ++itemId; } ImGui::PopStyleColor(3); ImGui::Separator(); for (auto nodeIndex = 0U; nodeIndex < _nodes.size(); ++nodeIndex) { ImGui::Text("Node %02u ", nodeIndex); ImGui::SameLine(); for (ItemId itemId = 0U; itemId < MAX_ITEMS; ++itemId) { unsigned int numItems = _nodes[nodeIndex]->itemList().numItemsWithId(itemId); if (numItems == 0) { ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.0f, 0.0f, 0.0f, 0.0f)); ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(1.0f, 0.0f, 0.0f, 0.3f)); ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(1.0f, 0.0f, 0.0f, 0.2f)); } else { ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.0f, 1.0f, 0.0f, 0.5f*numItems)); ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(.0f, 1.0f, 0.0f, 0.3f*numItems)); ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(.0f, 1.0f, 0.0f, 0.2f*numItems)); } const int buttonId = nodeIndex * MAX_ITEMS + itemId; std::ostringstream oss; oss << numItems; oss << "##" << buttonId; if (ImGui::Button(oss.str().c_str(), ImVec2(20, 20))) { if (numItems == 0) { selectedNode = nodeIndex; selectedItem = itemId; comboItem = 0; ImGui::OpenPopup("ItemOps"); } } ImGui::PopStyleColor(3); if (itemId < MAX_ITEMS - 1) ImGui::SameLine(); } } // Context menu to spawn agents ImGui::SetNextWindowSize(ImVec2(450, 200)); if (ImGui::BeginPopup("ItemOps")) { int numberOfItems = _nodes[selectedNode]->itemList().numItemsWithId(selectedItem); int contribution_quantity = 1; int petition_quantity = 1; bool validate = false; // If it is a missing item... if (numberOfItems == 0) { int requestedItem = selectedItem; // Check if we have spare items std::vector<std::string> comboStrings; std::vector<int> itemIds; for (ItemId itemId = 0; itemId < MAX_ITEMS; ++itemId) { if (_nodes[selectedNode]->itemList().numItemsWithId(itemId) > 1) { std::ostringstream oss; oss << itemId; comboStrings.push_back(oss.str()); itemIds.push_back(itemId); } } std::vector<const char *> comboCStrings; for (auto &s : comboStrings) { comboCStrings.push_back(s.c_str()); } if (itemIds.size() > 0) { ImGui::Text("Create MultiCastPetitioner?"); ImGui::Separator(); ImGui::Text("Node %d", selectedNode); ImGui::Text(" - Petition: %d", requestedItem); ImGui::Combo("Contribution", &comboItem, (const char **)&comboCStrings[0], (int)comboCStrings.size()); ShowDealProposition(requestedItem, itemIds[comboItem], petition_quantity, contribution_quantity); int actual_amount_contribution = _nodes[selectedNode]->itemList().numItemsWithId(itemIds[comboItem]); ShowValueExchange(itemIds[comboItem], requestedItem, contribution_quantity, petition_quantity); bool validate = ValidateSpawn(actual_amount_contribution, contribution_quantity); if (validate) { ImGui::TextColored(ImVec4(0.0f, 1.0f, 0.0f, 1.0f), "You can do this exchange"); } else { ImGui::TextColored(ImVec4(1.0f, 0.0f, 0.0f, 1.0f), "You can't do this exchange"); } if (ImGui::Button("Spawn MCP") && validate) { ClearAgent(); SpawnAgentMCC(); int contributedItem = itemIds[comboItem]; CleanNegotiation(); spawnMCP(selectedNode, requestedItem, petition_quantity, contributedItem, contribution_quantity, actual_amount_contribution); //spawnMCP(selectedNode, requestedItem, contributedItem); ImGui::CloseCurrentPopup(); } } else { ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1.0, 0.0, 0.0, 1.0)); ImGui::Text("No spare items available to create an MCP."); ImGui::PopStyleColor(1); } } ImGui::EndPopup(); } ImGui::End(); } return true; } bool ModuleNodeCluster::stop() { state = STOPPING; return true; } bool ModuleNodeCluster::validMCC(uint16_t agendtTD, uint16_t requested_item) { if (!current_negotiation[agendtTD].empty()) { if (std::find(current_negotiation[agendtTD].begin(), current_negotiation[agendtTD].end(), requested_item) != current_negotiation[agendtTD].end()) { return false; } } return true; } void ModuleNodeCluster::AddNegotation(uint16_t agendtTD, uint16_t requested_item) { current_negotiation[agendtTD].push_back(requested_item); } void ModuleNodeCluster::RemoveNegotiation(uint16_t agendtTD, uint16_t requested_item) { current_negotiation[agendtTD].erase(std::remove(current_negotiation[agendtTD].begin(), current_negotiation[agendtTD].end(), requested_item), current_negotiation[agendtTD].end()); } bool ModuleNodeCluster::cleanUp() { return true; } void ModuleNodeCluster::OnAccepted(TCPSocketPtr socket) { // Nothing to do } void ModuleNodeCluster::OnPacketReceived(TCPSocketPtr socket, InputMemoryStream & stream) { //iLog << "OnPacketReceived"; PacketHeader packetHead; packetHead.Read(stream); // Get the agent auto agentPtr = App->agentContainer->getAgent(packetHead.dstAgentId); if (agentPtr != nullptr) { agentPtr->OnPacketReceived(socket, packetHead, stream); } else { eLog << "Couldn't find agent: " << packetHead.dstAgentId; } } void ModuleNodeCluster::OnDisconnected(TCPSocketPtr socket) { // Nothing to do } void ModuleNodeCluster::SpawnAgentMCC() { for (NodePtr node : _nodes) { for (ItemId contributedItem = 0; contributedItem < MAX_ITEMS; ++contributedItem) { if (node->itemList().numItemsWithId(contributedItem) > 1) { unsigned int numItemsToContribute = node->itemList().numItemsWithId(contributedItem); for (ItemId constraintItem = 0; constraintItem < MAX_ITEMS; ++constraintItem) { if (node->itemList().numItemsWithId(constraintItem) == 0) { int num_to_contribute = numItemsToContribute; for (unsigned int i = 0; i < numItemsToContribute; i += MAX_ITEM_VALUE) { int send_to_contribute = 0; if (num_to_contribute >= MAX_ITEM_VALUE) { send_to_contribute = MAX_ITEM_VALUE; num_to_contribute -= MAX_ITEM_VALUE; } else { send_to_contribute = num_to_contribute; } spawnMCC(node->id(), contributedItem, num_to_contribute, constraintItem); } } } /* for (ItemId constraintItem = 0; constraintItem < MAX_ITEMS; ++constraintItem) { if (node->itemList().numItemsWithId(constraintItem) == 0) { for (unsigned int i = 0; i < numItemsToContribute; ++i) { spawnMCC(node->id(), contributedItem, constraintItem); } } } */ } } } } void ModuleNodeCluster::ClearAgent() { for (AgentPtr agent : App->agentContainer->allAgents()) { agent->stop(); } } bool ModuleNodeCluster::startSystem() { iLog << "--------------------------------------------"; iLog << " SiSiMEX: Node Cluster "; iLog << "--------------------------------------------"; iLog << ""; // Create listen socket TCPSocketPtr listenSocket = SocketUtil::CreateTCPSocket(SocketAddressFamily::INET); if (listenSocket == nullptr) { eLog << "SocketUtil::CreateTCPSocket() failed"; return false; } iLog << " - Server Listen socket created"; // Bind const int port = LISTEN_PORT_AGENTS; SocketAddress bindAddress(port); // localhost:LISTEN_PORT_AGENTS listenSocket->SetReuseAddress(true); int res = listenSocket->Bind(bindAddress); if (res != NO_ERROR) { return false; } iLog << " - Socket Bind to interface 127.0.0.1:" << LISTEN_PORT_AGENTS; // Listen mode res = listenSocket->Listen(); if (res != NO_ERROR) { return false; } iLog << " - Socket entered in Listen state..."; // Add the socket to the manager App->networkManager->SetDelegate(this); App->networkManager->AddSocket(listenSocket); #ifdef RANDOM_INITIALIZATION // Initialize nodes for (int i = 0; i < MAX_NODES; ++i) { // Create and intialize nodes NodePtr node = std::make_shared<Node>(i); node->itemList().initializeComplete(); _nodes.push_back(node); } // Randomize for (int j = 0; j < MAX_ITEMS; ++j) { for (int i = 0; i < MAX_NODES; ++i) { ItemId itemId = rand() % MAX_ITEMS; while (_nodes[i]->itemList().numItemsWithId(itemId) == 0) { itemId = rand() % MAX_ITEMS; } _nodes[i]->itemList().removeItem(itemId); _nodes[(i + 1) % MAX_NODES]->itemList().addItem(itemId, rand() % 5); } } #else _nodes.push_back(std::make_shared<Node>((int)_nodes.size())); _nodes.push_back(std::make_shared<Node>((int)_nodes.size())); _nodes.push_back(std::make_shared<Node>((int)_nodes.size())); _nodes.push_back(std::make_shared<Node>((int)_nodes.size())); _nodes[0]->itemList().addItem(ItemId(0)); _nodes[0]->itemList().addItem(ItemId(0)); _nodes[1]->itemList().addItem(ItemId(1)); _nodes[1]->itemList().addItem(ItemId(1)); _nodes[2]->itemList().addItem(ItemId(2)); _nodes[2]->itemList().addItem(ItemId(2)); _nodes[3]->itemList().addItem(ItemId(3)); _nodes[3]->itemList().addItem(ItemId(3)); // Defines to clarify the next lines # define NODE(x) x # define CONTRIBUTION(x) x # define CONSTRAINT(x) x spawnMCC(NODE(1), CONTRIBUTION(1), CONSTRAINT(2)); // Node 1 offers 1 but wants 2 spawnMCC(NODE(2), CONTRIBUTION(2), CONSTRAINT(3)); // Node 2 offers 2 but wants 3 spawnMCC(NODE(3), CONTRIBUTION(3), CONSTRAINT(0)); // Node 3 offers 3 but wants 0 //spawnMCC(0, 0); // Node 0 offers 0 //spawnMCP(0, 1); // Node 0 wants 1 #endif return true; } void ModuleNodeCluster::runSystem() { // Check the results of agents for (AgentPtr agent : App->agentContainer->allAgents()) { if (!agent->isValid()) { continue; } // Update ItemList with finalized MCCs MCC *mcc = agent->asMCC(); if (mcc != nullptr && mcc->negotiationFinished()) { if (mcc->negotiationAgreement()) { Node *node = mcc->node(); node->itemList().removeItem(mcc->contributedItemId(),mcc->contributed_quantity()); node->itemList().addItem(mcc->constraintItemId(),mcc->constrain_quantity()); iLog << "MCC exchange at Node " << node->id() << ":" << " -" << mcc->contributedItemId() << ":" << mcc->contributed_quantity() << " +" << mcc->constraintItemId() << ":" << mcc->constrain_quantity(); } else { wLog << "MCC exchange at Node " << mcc->id() << " not found:" << " -" << mcc->contributedItemId() << ":" << mcc->contributed_quantity() << " +" << mcc->constraintItemId() << ":" << mcc->constrain_quantity(); } mcc->stop(); } // Update ItemList with MCPs that found a solution MCP *mcp = agent->asMCP(); if (mcp != nullptr && mcp->negotiationFinished() && mcp->searchDepth() == 0) { Node *node = mcp->node(); if (mcp->negotiationAgreement()) { node->itemList().addItem(mcp->requestedItemId(),mcp->requested_quantity()); node->itemList().removeItem(mcp->contributedItemId(),mcp->contributed_quantity()); iLog << "MCP exchange at Node " << node->id() << ":" << " -" << mcp->contributedItemId() <<":"<< mcp->contributed_quantity() << " +" << mcp->requestedItemId() << ":" << mcp->requested_quantity(); } else { wLog << "MCP exchange at Node " << node->id() << " not found:" << " -" << mcp->contributedItemId() << ":" << mcp->contributed_quantity() << " +" << mcp->requestedItemId() << ":" << mcp->requested_quantity(); } mcp->stop(); } } // WARNING: // The list of items of each node can change at any moment if a multilateral exchange took place // The following lines looks for agents which, after an update of items, make sense no more, and stops them for (AgentPtr agent : App->agentContainer->allAgents()) { if (!agent->isValid()) { continue; } Node *node = agent->node(); MCC *mcc = agent->asMCC(); if (mcc != nullptr && mcc->isIdling()) { int numContributedItems = node->itemList().numItemsWithId(mcc->contributedItemId()); int numRequestedItems = node->itemList().numItemsWithId(mcc->constraintItemId()); if (numContributedItems < 2 || numRequestedItems > 0) { // if the contributed is not repeated at least once... or we already got the constraint mcc->stop(); } } } } void ModuleNodeCluster::stopSystem() { } void ModuleNodeCluster::CleanNegotiation() { current_negotiation.clear(); } void ModuleNodeCluster::ShowValueExchange(uint16_t contribution, uint16_t request, uint16_t contribution_quantity, uint16_t request_quantity) { std::string contribution_text = "You offert " + std::to_string(contribution_quantity); std::string request_text = "You request " + std::to_string(request_quantity); ImGui::Text(contribution_text.c_str()); ImGui::SameLine(); ShowBox(contribution); ImGui::Text(request_text.c_str()); ImGui::SameLine(); ShowBox(request); } void ModuleNodeCluster::ShowBox(uint16_t rarity_value) { switch (static_cast<ItemType>(GetItemType(rarity_value))) { case ItemType::COMMON: ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.5f, 0.5f, 0.5f, 0.5f)); ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(0.5f, 0.5f, 0.5f, 0.5f)); ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.5f, 0.5f, 0.5f, 0.5f)); break; case ItemType::RARE: ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.3f, 0.3f, 1.0f, 0.5f)); ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(0.3f, 0.3f, 1.0f, 0.5f)); ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.3f, 0.3f, 1.0f, 0.5f)); break; case ItemType::EPIC: ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.6f, 0.0f, 1.0f, 0.5f)); ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(0.6f, 0.0f, 1.0f, 0.5f)); ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.6f, 0.0f, 1.0f, 0.5f)); break; case ItemType::LEGEND: ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.9f, 0.6f, 0.0f, 0.5f)); ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(0.9f, 0.6f, 0.0f, 0.5f)); ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.9f, 0.6f, 0.0f, 0.5f)); break; default: break; } ImGui::Button("",ImVec2(20, 20)); ImGui::PopStyleColor(3); } void ModuleNodeCluster::spawnMCP(int nodeId, int requestedItemId, int requested_quantity, int contributedItemId, int contributed_quantity, int actual_amount_contribution) { dLog << "Spawn MCP - node " << nodeId << " - req. " << requestedItemId << " - contrib. " << contributedItemId; if (nodeId >= 0 && nodeId < (int)_nodes.size()) { NodePtr node = _nodes[nodeId]; App->agentContainer->createMCP(node.get(), requestedItemId, requested_quantity, contributedItemId, contributed_quantity, actual_amount_contribution, 0); } else { wLog << "Could not find node with ID " << nodeId; } } void ModuleNodeCluster::spawnMCP(int nodeId, int requestedItemId, int contributedItemId) { dLog << "Spawn MCP - node " << nodeId << " - req. " << requestedItemId << " - contrib. " << contributedItemId; if (nodeId >= 0 && nodeId < (int)_nodes.size()) { NodePtr node = _nodes[nodeId]; App->agentContainer->createMCP(node.get(), requestedItemId, contributedItemId, 0); } else { wLog << "Could not find node with ID " << nodeId; } } void ModuleNodeCluster::spawnMCC(int nodeId, int contributedItemId, int constraintItemId) { dLog << "Spawn MCC - node " << nodeId << " contrib. " << contributedItemId << " - constr. " << constraintItemId; if (nodeId >= 0 && nodeId < (int)_nodes.size()) { NodePtr node = _nodes[nodeId]; App->agentContainer->createMCC(node.get(), contributedItemId, constraintItemId); } else { wLog << "Could not find node with ID " << nodeId; } } void ModuleNodeCluster::spawnMCC(int nodeId, int contributedItemId, int contributed_cuantity, int constraintItemId) { dLog << "Spawn MCC - node " << nodeId << " contrib. " << contributedItemId << " - constr. " << constraintItemId; if (nodeId >= 0 && nodeId < (int)_nodes.size()) { NodePtr node = _nodes[nodeId]; App->agentContainer->createMCC(node.get(), contributedItemId, contributed_cuantity, constraintItemId); } else { wLog << "Could not find node with ID " << nodeId; } } bool ModuleNodeCluster::ValidateSpawn(int actual_quantity, int needed_quantity) { return actual_quantity >= needed_quantity; }
[ "Andreu.rbj@gmail.com" ]
Andreu.rbj@gmail.com
54047cf7dfea0abf84b952dff5ad6a9ab934cf18
b0b930d6a7698b1755f89a085b4a9e75dbc0d12b
/main.cpp
63d959045a23e6f52b3c0635ac515715ac578d92
[]
no_license
UsmanMaqbool/pdollar-edges-folder-processing
ed2ba13544af48c5d9e065d501329601c8e154b8
99e40460696a2ad59c93edcd1bf8c0d40a584b0b
refs/heads/master
2020-09-28T20:10:21.922007
2019-12-09T11:24:01
2019-12-09T11:24:01
226,854,413
1
0
null
null
null
null
UTF-8
C++
false
false
5,483
cpp
#include <iostream> #include <opencv2/opencv.hpp> #include <fstream> #include "model.h" #include <cstddef> // std::size_t #include <vector> #include <algorithm> #include <string> #include <boost/filesystem.hpp> #include "sys/types.h" #include "sys/stat.h" using namespace boost::system; namespace filesys = boost::filesystem; #ifndef USING_BOOST #define USING_BOOST #endif using namespace std; using namespace cv; tuple<Mat, Mat, Mat, Mat> edgesDetect(Mat, _model, int); void mkdirTree(string sub, string dir) { if (sub.length() == 0) return; int i=0; for (i; i < sub.length(); i++) { dir += sub[i]; if (sub[i] == '/') break; } mkdir(dir.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); if (i+1 < sub.length()) mkdirTree(sub.substr(i+1), dir); } std::vector<std::string> getAllFilesInDir(const std::string &dirPath, const std::vector<std::string> dirSkipList = { }) { // Create a vector of string std::vector<std::string> listOfFiles; try { // Check if given path exists and points to a directory if (filesys::exists(dirPath) && filesys::is_directory(dirPath)) { // Create a Recursive Directory Iterator object and points to the starting of directory filesys::recursive_directory_iterator iter(dirPath); // Create a Recursive Directory Iterator object pointing to end. filesys::recursive_directory_iterator end; // Iterate till end while (iter != end) { // Check if current entry is a directory and if exists in skip list if (filesys::is_directory(iter->path()) && (std::find(dirSkipList.begin(), dirSkipList.end(), iter->path().filename()) != dirSkipList.end())) { // Skip the iteration of current directory pointed by iterator #ifdef USING_BOOST // Boost Fileystsem API to skip current directory iteration iter.no_push(); #else // c++17 Filesystem API to skip current directory iteration iter.disable_recursion_pending(); #endif } else { // Add the name in vector listOfFiles.push_back(iter->path().string()); } boost::system::error_code ec; // Increment the iterator to point to next entry in recursive iteration iter.increment(ec); if (ec) { std::cerr << "Error While Accessing : " << iter->path().string() << " :: " << ec.message() << '\n'; } } } } catch (std::system_error & e) { std::cerr << "Exception :: " << e.what(); } return listOfFiles; } string GetDirectory (const std::string& path) { size_t found = path.find_last_of("/\\"); return(path.substr(0, found)); } _model loadmodel(); _para initial_para(); void edgebox(string, _model, _para); tuple<int, int> siftflow(Mat image, int option, int pin); int main() { std::string BasePath = "/home/leo/docker_ws/datasets/24tokyo"; std::size_t found = BasePath.size(); std::string SavePath = "/home/leo/docker_ws/datasets/24tokyo-edges"; //std::string dirPath = "img-test"; cout << "Please waiting for the model to load!" << endl; //load model and set opts _model model = loadmodel(); model.opts.sharpen = 2; //model.opts.sharpen = 2; model.opts.multiscale = 0; model.opts.nThreads = 4; model.opts.nTreesEval = 1; //model.opts.nTreesEval = 4; model.opts.showpic = 1;//set if show picture or not model.opts.showtime = 10;//in s model.opts.stride = 2; model.opts.showboxnum = 15; _para para = initial_para(); cout << "model loaded!" << endl; // Get recursive list of files in given directory and its sub directories std::vector<std::string> listOfFiles = getAllFilesInDir(BasePath); // Iterate over the vector and print all files for (auto str : listOfFiles){ if(str.substr(str.find_last_of(".") + 1) == "jpg"){ // std::string image_path = "/home/leo/docker_ws/datasets/24tokyo-edges/03814/381489.331_3946812.467/t3SQSc3FcyVyob-w52ds-g_012_150.jpg"; std::cout << str << std::endl; string file_dirs = GetDirectory(str); cout << "file_dirs = " << file_dirs << endl; // extract directroy after base path string file_dir = file_dirs.substr(found+1); cout << "file_dir " << file_dir << endl; // Extract file name std::size_t founds = str.find_last_of("/\\"); string file_name = str.substr(founds+1); cout << "file_name " << file_name << endl; string outputDir = SavePath + "/" + file_dir + "/"; mkdirTree(outputDir, ""); string save_img = outputDir + file_name ; clock_t begin = clock(); Mat I = imread(str); tuple<Mat, Mat, Mat, Mat> detect = edgesDetect(I, model, 4); Mat E, O, unuse1, unuse2; tie(E, O, unuse1, unuse2) = detect; Mat E_draw = E*255; cout << "time:" << ((double) clock() - begin) / CLOCKS_PER_SEC << "s" << endl; std::cout << save_img << std::endl; imwrite(save_img, E_draw); O.release(); unuse1.release(); unuse2.release(); E.release(); I.release(); E_draw.release(); } } std::cout << "**********************" << std::endl; std::cout << "Done!" << std::endl;//for test return 0; }
[ "usmanmaqbool@outlook.com" ]
usmanmaqbool@outlook.com
42268bd77aa7d24c6eb0dfd5a938efbedb6cdb0b
2a11fc79a295e9f79f2d60f348c8061b60735c1d
/viewer/pcl_visualizer.cpp
aedcad9dd193e279ac4df5b848bbb35d230d241b
[]
no_license
NakaharaJun/pcl_tutorial
ea6863a0379856fe8d0daf30ca90a1f47c7d434a
7c54c5cc6011621a1d45339aa49f7895e009ef04
refs/heads/master
2020-05-14T23:39:15.717208
2018-11-14T07:54:48
2018-11-14T07:54:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,055
cpp
#include <iostream> #include <pcl/io/pcd_io.h> #include <pcl/io/ply_io.h> #include <pcl/point_cloud.h> #include <pcl/console/parse.h> #include <pcl/visualization/pcl_visualizer.h> void show_help(char* program_name){ std::cout << std::endl; std::cout << "Usage: " << program_name << "cloud_file_name.[pcd|ply]" << std::endl; std::cout << "-h: Show this help" << std::endl; } int main(int argc, char** argv) { //Show help if (pcl::console::find_switch(argc, argv, "-h") || pcl::console::find_switch(argc, argv, "--help")) { std::cout << "HELP will be shown" << std::endl; show_help(argv[0]); return 0; } //Fetch point cloud file from args std::vector<int> file_names; bool file_is_pcd = false; file_names = pcl::console::parse_file_extension_argument(argc, argv, ".ply"); if (file_names.size() != 1) { std::cout << "Load pcd file" << std::endl; file_names = pcl::console::parse_file_extension_argument(argc, argv, ".pcd"); if (file_names.size() == 0) { std::cout << "Error No file [ply|pcd] was found" << std::endl; show_help(argv[0]); return -1; } else { file_is_pcd = true; } } //Load file pcl::PointCloud<pcl::PointXYZ>::Ptr source_cloud_prt(new pcl::PointCloud<pcl::PointXYZ>()); if (file_is_pcd) { if (pcl::io::loadPCDFile(argv[file_names[0]], *source_cloud_prt) < 0) { std::cout << "Error loading point cloud " << argv[file_names[0]] << std::endl; show_help(argv[file_names[0]]); return -1; } } else { if (pcl::io::loadPLYFile(argv[file_names[0]], *source_cloud_prt) < 0) { std::cout << "Error loading point cloud " << argv[file_names[0]] << std::endl; show_help(argv[file_names[0]]); return -1; } } pcl::visualization::PCLVisualizer viewer("point cloud viewer"); pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> viewer_color_hander(source_cloud_prt, 255, 255, 255); viewer.addPointCloud(source_cloud_prt, viewer_color_hander, "point_cloud"); viewer.addCoordinateSystem(); while (!viewer.wasStopped()) { viewer.spinOnce(); } return 0; }
[ "s_harumo@hotmail.co.jp" ]
s_harumo@hotmail.co.jp
a17eb71ca579391ef0e64f8eff31f08c998cc1c4
49f8c18b00b7b5fca889c96143361df6926986f9
/archive/Metropolis/Utilities/IOUtilities.h
e28a244daf6e3a9320452908a6d8c738b8f3858c
[]
no_license
franciszayek/MCGPU
7428cb805262eefead8bb25aa2d3d3faa7cde17a
fcfb3ee768e049a2e8694db7b33a639963b8c753
refs/heads/master
2021-01-16T17:42:41.558517
2015-05-06T22:58:28
2015-05-06T22:58:28
30,319,340
2
4
null
2015-05-06T22:58:28
2015-02-04T20:25:33
C++
UTF-8
C++
false
false
14,115
h
/*Intended goal: support read, parse, and extract operations on configuration files to properly initialize * a simulation environment. * [1] This file/class will, ideally, replace Config_Scan.cpp & will augment MetroUtil.cpp. (Started, 19 Feb. Beta completion, 28 Feb. -Albert) * [2] This file/class will, ideally, replace Opls_Scan and Zmatrix_Scan. (Started, 26 Feb. -Albert) *Created 19 February 2014. Authors: Albert Wallace */ /* --Changes made on: ->Sun, 23 Feb 2014 (Albert) ->Wed, 26 Feb (Albert) ->Thu, 27 Feb (Albert, then Tavis) ->Fri, 28 Feb (Albert) ->Mon, 03 Mar; Wed, 05 Mar; Thur, 06 Mar, Fri, 07 Mar; Mon, 10 Mar; Wed, 12 Mar; Thur, 13 Mar; (Albert) */ /*Based on work from earlier sessions by Alexander Luchs, Riley Spahn, Seth Wooten, and Orlando Acevedo*/ #ifndef IOUTILITIES_H #define IOUTILITIES_H //_________________________________________________________________________________________________________________ // INCLUDE statements //_________________________________________________________________________________________________________________ #include <assert.h> #include <errno.h> #include <exception> #include <fstream> #include <iostream> #include <map> #include <queue> #include <sstream> #include <stdexcept> #include <stdio.h> #include <stdlib.h> #include <string> #include <string.h> #include <vector> #include "StructLibrary.h" //#include "../../Utilities/geometricUtil.h" //#include "MathLibrary.cpp" //AlbertIncludes #include "MathLibrary.h" //AlbertExcludes //_________________________________________________________________________________________________________________ // Specific namespace/using requirements //_________________________________________________________________________________________________________________ //to avoid "using namespace std;" using std::vector; using std::string; using std::map; //_________________________________________________________________________________________________________________ //Actual IOUtilities class definition; handles most of the setup duties when it comes to parsing configuration files and the like. //_________________________________________________________________________________________________________________ class IOUtilities { public: //all things are allowed to be public during testing IOUtilities(std::string configPath); //this should be the constructor, which does very little on its own. ~IOUtilities(); //standard destructor for most of the important variables ///Calls the driver method after initializing *some* variables, and does nothing more. bool readInConfig(); //this represents the first of the chain of calls to configuration methods. //(Does *not* call the second in the chain, or in other words does not continue environment setup. // Look for the driver method for proper order of execution after this.) int ReadStateFile(char const* StateFile, Environment * destinationEnvironment, Molecule * destinationMoleculeCollection); int WriteStateFile(char const* StateFile, Environment * sourceEnvironment, Molecule * sourceMoleculeCollection); //int writePDB(char const* pdbFile); //this is the old version from SimBox, probably not useful or usable int writePDB(char const* pdbFile, Environment sourceEnvironment, Molecule * sourceMoleculeCollection); //this is a new version, possibly required for this implementation with IOUtilities void throwScanError(std::string message); //bool readInConfigAlreadyDone; //no longer preventing people from re-reading the config file, etc. bool criticalErrorEncountered; //From OPLS_Scan...... /* What used to be the old destructor for the OPLS_Scan object. */ void destructOpls_Scan(); /** Scans in the opls File calls sub-function addLineToTable @return - success code 0: successful 1: error */ int scanInOpls(); /** Parses out a line from the opls file and gets (sigma, epsilon, charge) adds an entry to the map at the hash number position, calls sub-function checkFormat() @param line - a line from the opls file @param numOflines - number of lines previously read in, used for error output */ void addLineToTable(std::string line, int numOfLines); /** Checks the format of the line being read in returns false if the format of the line is invalid @param line - a line from the opls file @return - Format code -1: Invalid Format 1: Normal OPLS format 2: Fourier Coefficent format */ int OPLScheckFormat(string line); /** Logs all the Errors found in the OPLS file to the output log. */ void logErrors(); /** Returns an Atom struct based on the hashNum (1st col) in Z matrix file The Atom struct has -1 for x,y,z and has the hashNum for an id. sigma, epsilon, charges @param hashNum - the hash number (1st col) in Z matrix file @return - the atom with that is the value to the hasNum key. */ Atom getAtom(string hashNum); /** Returns the sigma value based on the hashNum (1st col) in Z matrix file @param hashNum - the hash number (1st col) in Z matrix file @return - the sigma value of the atom that is the value associated with the hasNum key. */ double getSigma(string hashNum); /** Returns the epsilon value based on the hashNum (1st col) in Z matrix file @param hashNum - the hash number (1st col) in Z matrix file @return - the epsilon value of the atom that is the value associated with the hashNum key. */ double getEpsilon(string hashNum); /** Returns the charge value based on the hashNum (1st col) in Z matrix file @param hashNum - the hash number (1st col) in Z matrix file @return - the charge value of the atom that is the value associated with the hashNum key. */ double getCharge(string hashNum); /** Returns the V values value based on the hashNum (1st col) in Z matrix file @param hashNum - the hash number (1st col) in Z matrix file @return - TODO */ Fourier getFourier(string hashNum); //From OPLS_Scan /** OPLS scanning is required to assign sigma, epsilon and charge values. */ /** HashTable that holds all opls references */ map<string,Atom> oplsTable; /** HashTable that holds all the Fourier Coefficents stored */ map<string,Fourier> fourierTable; /** the path to the OPLS file. */ // //stored in the UtilitiesInfo struct! see also: filePathsEtc. /** Vector used to keep track of errors when lines in the OPLS file that don't match the correct format. */ vector<int> errLinesOPLS; /** Vector used to keep track of errors when the hashes in the OPLS file that exist more than once. */ vector<string> errHashes; /** Vector used to keep track of errors when the hashes in the fourier coefficent section of the OPLS file that exist more than once. */ vector<string> errHashesFourier; //From Zmatrix_Scan void destructZmatrix_Scan(); /** Scans in the z-matrix File calls sub-function parseLine @param filename - the name/path of the z-matrix file @return - success code 0: Valid z-matrix path 1: Invalid z-matrix path */ int scanInZmatrix(); /** Parses out a line from the zmatrix file and gets the atom from the OPLS hash Creates structs for bond, angle, dihedral, if applicable calls sub-function checkFormat() @param line - a line from the zmatrix file @param numOflines - number of lines previously read in, used for error output */ void parseLine(string line, int numOfLines); /** Checks the format of the line being read in returns false if the format of the line is invalid @param line - a line from the zmatrix file @param stringCount - number of strings in a line you're looking at @return - Format code 1: Base atom row listing 2: TERZ line 3: Geometry Variations 4: Variable Bonds 5: Additional Bonds 6: Harmonic Constraints 7: Variable Angles 8: Additional Angles 9: Variable Dihedrals 10: Additional Dihedrals 11: Domain Definitions -2: Final Blank Line -1: Invalid line format */ int ZMcheckFormat(string line); /** Handles the additional stuff listed at the bottom of the Z-matrix file @param line - a line from the zmatrix file @param cmdFormat- the int representing the format for which the line applies :see checkFormat */ void handleZAdditions(string line, int cmdFormat); /** Creates a vector containg the Hop distances of a molecule for all hops that have a distance greater than 3. @param molec - the molecule to check its bonds for valid hops @return - returns a vector of hops needed for energy calculations */ vector<Hop> calculateHops(Molecule molec); /** Checks if the int item is contained in the vector @param vect - the vector to search through @param item - the item to search for @return - true if the int is in the vector and false otherwise. */ bool contains(vector<int> &vect, int item); /** Returns the distance of the shortest path amongst bonds between two atoms @param atom1 - the id of the starting atom @param atom2 - the if of the ending atom @param size - number of atoms in molecule @param graph - a 2d array representing all the bonds in the molecule @return - returns the number of bonds seperating atom1 and atom2. */ int findHopDistance(int atom1,int atom2,int size, int **graph); /** Creates a 2d array representing all the bonds in the molecule the array is filled with 1 or 0 for a bond or no bond between atoms array is n*n where n is the number of atoms. @param graph - a 2d array representing all the bonds in the molecule @param molec - the molecule to check its bonds for valid hops */ void buildAdjacencyMatrix(int **&graph, Molecule molec); /** Creates a molecule(s) based on a starting unique ID and the pattern specified by the Z-matrix in the scan functions @param startingID - first ID for the molecule being built @return - vector of unique molecules that are copies of the molecules from the Z-matrix file. */ vector<Molecule> buildMolecule(int startingID); //The path to the Z-matrix file //Stored in the UtilitiesInfo structure. See also: filePathsEtc. /** Vector that holds example molecules. */ vector<Molecule> moleculePattern_ZM; /** Vector that holds the atoms contained in the molecule in the Z-matrix. */ vector<Atom> atomVector_ZM; /** Vector that holds the bonds contained in the molecule in the Z-matrix. */ vector<Bond> bondVector_ZM; /** Vector that holds the angles contained in the molecule in the Z-matrix. */ vector<Angle> angleVector_ZM; /** Vector that holds the dihedrals contained in the molecule in the Z-matrix. */ vector<Dihedral> dihedralVector_ZM; /** Vector of dummy atoms held seperately from the normal atoms. */ //vector<unsigned long> dummies_ZM; //potentially unused /** Global variable that determines if there are multiple molecules in a Z-matrix. */ bool startNewMolecule_ZM; /** Global variable used to store the format id of the last line scanned. needed to read the bottom sections of the Z-matrix file. */ int previousFormat_ZM; /********************************** *Path variables and the temporary environment ***************************************/ std::string configPath; //The path to the main configuration file read in for the simulation unsigned int numOfSteps; //The number of steps to run the simulation std::string oplsuaparPath; //The path to the opls files containing additional geometry data, to be used (eventually) during simulation std::string zmatrixPath; //The path to the Z-matrix files to be used during simulation std::string statePath; //The path to the state information file to be used in the simulation std::string stateOutputPath; //The path where we write the state output files after simulation std::string pdbOutputPath; //The path where we write the pdb output files after simulation unsigned int cutoff; //The nonbonded cutoff distance. Table * tables; bool configFileSuccessfullyRead; //private: //major organization must occur here before things are allowed to be private /*********************************** *Allows construction of a box, by holding all the information necessary to make one ************************************/ //the driver method used to control the proper flow of reading from file during setup void pullInDataToConstructSimBox(); //and some of the variables to be used for storage until the box itself is created Molecule changedmole; Molecule *molecules; Environment * currentEnvironment; //The current working environment for the simulation //Environment *enviro; //in the future, look at currentEnvironment for this Atom * atompool; Bond * bondpool; Angle * anglepool; Dihedral * dihedralpool; Hop * hoppool; int numberOfAtomsInAtomPool; int numberOfBondsInBondPool; int numberOfAnglesInAnglePool; int numberOfDihedralsInDihedralPool; int numberOfHopsInHopPool; }; void writeToLog(std::string text,int stamp); void writeToLog(std::stringstream& ss, int stamp); #endif
[ "tavis.maclellan@gmail.com" ]
tavis.maclellan@gmail.com
881561c5e2ae7c4ebc682aa5545a0239255c4212
3b78ed368e18ea9ab875637428b5e66e525b3528
/Lab04/buildingbuilder.cpp
32da7a723096366254eac392e2ba4830eb271929
[]
no_license
YAXo-O/OOP
c55dcfaf2a21b1bb3c7c39c183e1a54ff43f717f
72ae15c16cc09dfbcdfdd7f59a9ae10037ef36be
refs/heads/master
2021-01-23T10:47:34.692275
2017-06-09T07:57:47
2017-06-09T07:57:47
93,092,661
0
0
null
null
null
null
UTF-8
C++
false
false
668
cpp
#include "buildingbuilder.h" Floor *BuildingBuilder::getFloor(int floorNum, QColor wallColor, QWidget *parent) noexcept { return new Floor(floorNum, wallColor, parent); } LiftBase *BuildingBuilder::getLift(QColor backColor, QWidget *parent) noexcept { return new LiftBase(backColor, parent); } Tunnel *BuildingBuilder::getTunnel(LiftBase *lift, QColor bgColor, QWidget *parent) noexcept { return new Tunnel(lift, bgColor, parent); } LiftPanel *BuildingBuilder::getLiftPanel(int floors, QWidget *parent) { return new LiftPanel(floors, parent); } Building *BuildingBuilder::getBuilding(QWidget *parent) noexcept { return new Building(parent); }
[ "aaazzzx@mail.ru" ]
aaazzzx@mail.ru
d0492df3e297bb1e8366a1188de625a314241152
4bd97e7189c34fed6691e50600ff1faae23d73ad
/tools/diskWrite/Filesystems/FAT32/filename.hpp
9f573b452147df58a85f8c56f977e5ab9d72a5a8
[ "MIT" ]
permissive
Rohansi/LoonyOS
bc8e09f48f47b5654de4d216fc7457c1252def78
f29f81236c24e2f42c2e2c517eb5616647f0696b
refs/heads/master
2020-08-04T11:05:54.058816
2014-01-03T08:19:55
2014-01-03T08:19:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
360
hpp
/* * filename.hpp * Filename specific functions */ #ifndef __FILENAME_HPP #define __FILENAME_HPP #include <iostream> #include "common.hpp" inline unsigned char Dos83Checksum(unsigned char* name); void StripDos83IllegalCharacters(char* buffer); void ToDos83Name(const char* name, char* buffer); void ToTypicalName(const char* name, char* buffer); #endif
[ "rohan-singh@hotmail.com" ]
rohan-singh@hotmail.com
16cfd0aab9fa3cc333d1dfb07196dfb466bf72a6
73ef9a1df397cdfd101d57c28c4bcafc6d7ebc1e
/stringiter.cpp
6335499eaeaec0d90f30e61f0efb715d0ad5d181
[]
no_license
cthomasyeh/ioi3
1202ad2054e595b0f12bd58cd675595e55114e7d
49b2d77d871664db4a0dda6fed7a6c37eba686a1
refs/heads/master
2016-09-05T12:16:49.060683
2013-11-03T18:17:04
2013-11-03T18:17:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
339
cpp
#include <iostream> #include <vector> #include <iterator> using namespace std; int main() { vector<string> sv(5); sv[0] = "this"; sv[1] = "is"; sv[2] = "a"; sv[3] = "test"; vector<string>::const_iterator iter; for (auto iter = sv.cbegin(); iter != sv.cend(); iter++) cout << *iter << endl; cout << distance(sv.cbegin(), iter); }
[ "tyeh@broadwayedu.com" ]
tyeh@broadwayedu.com
d297094d0f254008d1cade2622ef957a333505b0
c08a26d662bd1df1b2beaa36a36d0e9fecc1ebac
/classicui_plat/lists_api/tsrc/inc/testsdklistsfclbdata.h
81ba0e85641ee5b76f91c84be4b529d99d2cc679
[]
no_license
SymbianSource/oss.FCL.sf.mw.classicui
9c2e2c31023256126bb2e502e49225d5c58017fe
dcea899751dfa099dcca7a5508cf32eab64afa7a
refs/heads/master
2021-01-11T02:38:59.198728
2010-10-08T14:24:02
2010-10-08T14:24:02
70,943,916
1
0
null
null
null
null
UTF-8
C++
false
false
2,353
h
/* * Copyright (c) 2002 - 2007 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: test protected for CFormattedCellListBoxData * */ #ifndef C_TESTSDKLISTSFCLBDATA_H #define C_TESTSDKLISTSFCLBDATA_H #include <eikfrlbd.h> class CTestSDKListsFCLBData : public CFormattedCellListBoxData { public: /** * C++ default constructor. */ CTestSDKListsFCLBData(); /** * Second phase constructor. Highlight animation will be * created by default (if it is provided by the skin). */ void ConstructLD(); /** * Second phase constructor for subclasses that want to override highlight * animation creation. * * @param aAnimationIID Skin ItemID of the constructed animation. Passing * @c KAknsIIDNone will disable highlight animation. */ void ConstructLD(const TAknsItemID& aAnimationIID); /** * Main drawing algorithm used for drawing S60 list item. * @c Draw() method should call this method after clearing the list item * area and drawing the highlight. * * @param aProperties Properties attached to the list item. * @param aGc Graphics Context used for drawing the list item. * @param aText A text string describing the list item cells. * @param aRect The area of the screen for the whole list item. * @param aHighlight Whether the list item is selected. * @param aColors The colors used for drawing the item. * @panic EAknPanicFormattedCellListInvalidBitmapIndex The defined bitmap * index is invalid. * @panic EAknPanicOutOfRange The defined index is out of the range. */ void DrawFormatted(TListItemProperties aProperties, CWindowGc& aGc, const TDesC* aText, const TRect& aRect, TBool aHighlight, const TColors& aColors) const; }; #endif /*C_TESTSDKLISTSFCLBDATA_H*/
[ "none@none" ]
none@none
808fab221208e1790af5eec04a319f7fcdbdf1db
e8e7749284ec38e06e06d342e76c2a2a091fa42e
/banking/credit-value-adjustment/cpp/src/main/cpp/include/exchange.pb.h
bb7e8b76994ca27c5a849f19f617a2e57a188585
[]
no_license
ssahadevan/hazelcast-platform-demos
3447a8d812e61bd87933186e2b148beb1bb85952
a6acd7be4f8c77b49fac61a44cbf1df666a4fcfa
refs/heads/master
2021-07-19T23:23:10.819394
2021-04-20T22:55:03
2021-04-20T22:55:03
246,892,778
1
0
null
2020-03-12T17:25:38
2020-03-12T17:25:38
null
UTF-8
C++
false
true
39,555
h
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: exchange.proto #ifndef GOOGLE_PROTOBUF_INCLUDED_exchange_2eproto #define GOOGLE_PROTOBUF_INCLUDED_exchange_2eproto #include <limits> #include <string> #include <google/protobuf/port_def.inc> #if PROTOBUF_VERSION < 3012000 #error This file was generated by a newer version of protoc which is #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif #if 3012002 < PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. #endif #include <google/protobuf/port_undef.inc> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/arena.h> #include <google/protobuf/arenastring.h> #include <google/protobuf/generated_message_table_driven.h> #include <google/protobuf/generated_message_util.h> #include <google/protobuf/inlined_string_field.h> #include <google/protobuf/metadata_lite.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/message.h> #include <google/protobuf/repeated_field.h> // IWYU pragma: export #include <google/protobuf/extension_set.h> // IWYU pragma: export #include <google/protobuf/unknown_field_set.h> // @@protoc_insertion_point(includes) #include <google/protobuf/port_def.inc> #define PROTOBUF_INTERNAL_EXPORT_exchange_2eproto PROTOBUF_NAMESPACE_OPEN namespace internal { class AnyMetadata; } // namespace internal PROTOBUF_NAMESPACE_CLOSE // Internal implementation detail -- do not use these members. struct TableStruct_exchange_2eproto { static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTableField entries[] PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::PROTOBUF_NAMESPACE_ID::internal::AuxillaryParseTableField aux[] PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTable schema[1] PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::PROTOBUF_NAMESPACE_ID::internal::FieldMetadata field_metadata[]; static const ::PROTOBUF_NAMESPACE_ID::internal::SerializationTable serialization_table[]; static const ::PROTOBUF_NAMESPACE_ID::uint32 offsets[]; }; extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_exchange_2eproto; namespace FlumaionQL { class DataExchange; class DataExchangeDefaultTypeInternal; extern DataExchangeDefaultTypeInternal _DataExchange_default_instance_; } // namespace FlumaionQL PROTOBUF_NAMESPACE_OPEN template<> ::FlumaionQL::DataExchange* Arena::CreateMaybeMessage<::FlumaionQL::DataExchange>(Arena*); PROTOBUF_NAMESPACE_CLOSE namespace FlumaionQL { // =================================================================== class DataExchange PROTOBUF_FINAL : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:FlumaionQL.DataExchange) */ { public: inline DataExchange() : DataExchange(nullptr) {}; virtual ~DataExchange(); DataExchange(const DataExchange& from); DataExchange(DataExchange&& from) noexcept : DataExchange() { *this = ::std::move(from); } inline DataExchange& operator=(const DataExchange& from) { CopyFrom(from); return *this; } inline DataExchange& operator=(DataExchange&& from) noexcept { if (GetArena() == from.GetArena()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return GetMetadataStatic().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return GetMetadataStatic().reflection; } static const DataExchange& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY static inline const DataExchange* internal_default_instance() { return reinterpret_cast<const DataExchange*>( &_DataExchange_default_instance_); } static constexpr int kIndexInFileMessages = 0; friend void swap(DataExchange& a, DataExchange& b) { a.Swap(&b); } inline void Swap(DataExchange* other) { if (other == this) return; if (GetArena() == other->GetArena()) { InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); } } void UnsafeArenaSwap(DataExchange* other) { if (other == this) return; GOOGLE_DCHECK(GetArena() == other->GetArena()); InternalSwap(other); } // implements Message ---------------------------------------------- inline DataExchange* New() const final { return CreateMaybeMessage<DataExchange>(nullptr); } DataExchange* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage<DataExchange>(arena); } void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const DataExchange& from); void MergeFrom(const DataExchange& from); PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; ::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: inline void SharedCtor(); inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(DataExchange* other); friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "FlumaionQL.DataExchange"; } protected: explicit DataExchange(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: static void ArenaDtor(void* object); inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); public: ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; private: static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_exchange_2eproto); return ::descriptor_table_exchange_2eproto.file_level_metadata[kIndexInFileMessages]; } public: // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- enum : int { kCurvefileFieldNumber = 1, kFixingfileFieldNumber = 2, kTradefileFieldNumber = 3, kEvaldateFieldNumber = 4, kResultsfileFieldNumber = 5, kScenarioidFieldNumber = 6, kTradeidFieldNumber = 7, }; // string curvefile = 1; void clear_curvefile(); const std::string& curvefile() const; void set_curvefile(const std::string& value); void set_curvefile(std::string&& value); void set_curvefile(const char* value); void set_curvefile(const char* value, size_t size); std::string* mutable_curvefile(); std::string* release_curvefile(); void set_allocated_curvefile(std::string* curvefile); GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") std::string* unsafe_arena_release_curvefile(); GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") void unsafe_arena_set_allocated_curvefile( std::string* curvefile); private: const std::string& _internal_curvefile() const; void _internal_set_curvefile(const std::string& value); std::string* _internal_mutable_curvefile(); public: // string fixingfile = 2; void clear_fixingfile(); const std::string& fixingfile() const; void set_fixingfile(const std::string& value); void set_fixingfile(std::string&& value); void set_fixingfile(const char* value); void set_fixingfile(const char* value, size_t size); std::string* mutable_fixingfile(); std::string* release_fixingfile(); void set_allocated_fixingfile(std::string* fixingfile); GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") std::string* unsafe_arena_release_fixingfile(); GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") void unsafe_arena_set_allocated_fixingfile( std::string* fixingfile); private: const std::string& _internal_fixingfile() const; void _internal_set_fixingfile(const std::string& value); std::string* _internal_mutable_fixingfile(); public: // string tradefile = 3; void clear_tradefile(); const std::string& tradefile() const; void set_tradefile(const std::string& value); void set_tradefile(std::string&& value); void set_tradefile(const char* value); void set_tradefile(const char* value, size_t size); std::string* mutable_tradefile(); std::string* release_tradefile(); void set_allocated_tradefile(std::string* tradefile); GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") std::string* unsafe_arena_release_tradefile(); GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") void unsafe_arena_set_allocated_tradefile( std::string* tradefile); private: const std::string& _internal_tradefile() const; void _internal_set_tradefile(const std::string& value); std::string* _internal_mutable_tradefile(); public: // string evaldate = 4; void clear_evaldate(); const std::string& evaldate() const; void set_evaldate(const std::string& value); void set_evaldate(std::string&& value); void set_evaldate(const char* value); void set_evaldate(const char* value, size_t size); std::string* mutable_evaldate(); std::string* release_evaldate(); void set_allocated_evaldate(std::string* evaldate); GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") std::string* unsafe_arena_release_evaldate(); GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") void unsafe_arena_set_allocated_evaldate( std::string* evaldate); private: const std::string& _internal_evaldate() const; void _internal_set_evaldate(const std::string& value); std::string* _internal_mutable_evaldate(); public: // string resultsfile = 5; void clear_resultsfile(); const std::string& resultsfile() const; void set_resultsfile(const std::string& value); void set_resultsfile(std::string&& value); void set_resultsfile(const char* value); void set_resultsfile(const char* value, size_t size); std::string* mutable_resultsfile(); std::string* release_resultsfile(); void set_allocated_resultsfile(std::string* resultsfile); GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") std::string* unsafe_arena_release_resultsfile(); GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") void unsafe_arena_set_allocated_resultsfile( std::string* resultsfile); private: const std::string& _internal_resultsfile() const; void _internal_set_resultsfile(const std::string& value); std::string* _internal_mutable_resultsfile(); public: // string scenarioid = 6; void clear_scenarioid(); const std::string& scenarioid() const; void set_scenarioid(const std::string& value); void set_scenarioid(std::string&& value); void set_scenarioid(const char* value); void set_scenarioid(const char* value, size_t size); std::string* mutable_scenarioid(); std::string* release_scenarioid(); void set_allocated_scenarioid(std::string* scenarioid); GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") std::string* unsafe_arena_release_scenarioid(); GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") void unsafe_arena_set_allocated_scenarioid( std::string* scenarioid); private: const std::string& _internal_scenarioid() const; void _internal_set_scenarioid(const std::string& value); std::string* _internal_mutable_scenarioid(); public: // string tradeid = 7; void clear_tradeid(); const std::string& tradeid() const; void set_tradeid(const std::string& value); void set_tradeid(std::string&& value); void set_tradeid(const char* value); void set_tradeid(const char* value, size_t size); std::string* mutable_tradeid(); std::string* release_tradeid(); void set_allocated_tradeid(std::string* tradeid); GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") std::string* unsafe_arena_release_tradeid(); GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") void unsafe_arena_set_allocated_tradeid( std::string* tradeid); private: const std::string& _internal_tradeid() const; void _internal_set_tradeid(const std::string& value); std::string* _internal_mutable_tradeid(); public: // @@protoc_insertion_point(class_scope:FlumaionQL.DataExchange) private: class _Internal; template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr curvefile_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr fixingfile_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr tradefile_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr evaldate_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr resultsfile_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr scenarioid_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr tradeid_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; friend struct ::TableStruct_exchange_2eproto; }; // =================================================================== // =================================================================== #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wstrict-aliasing" #endif // __GNUC__ // DataExchange // string curvefile = 1; inline void DataExchange::clear_curvefile() { curvefile_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } inline const std::string& DataExchange::curvefile() const { // @@protoc_insertion_point(field_get:FlumaionQL.DataExchange.curvefile) return _internal_curvefile(); } inline void DataExchange::set_curvefile(const std::string& value) { _internal_set_curvefile(value); // @@protoc_insertion_point(field_set:FlumaionQL.DataExchange.curvefile) } inline std::string* DataExchange::mutable_curvefile() { // @@protoc_insertion_point(field_mutable:FlumaionQL.DataExchange.curvefile) return _internal_mutable_curvefile(); } inline const std::string& DataExchange::_internal_curvefile() const { return curvefile_.Get(); } inline void DataExchange::_internal_set_curvefile(const std::string& value) { curvefile_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena()); } inline void DataExchange::set_curvefile(std::string&& value) { curvefile_.Set( &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena()); // @@protoc_insertion_point(field_set_rvalue:FlumaionQL.DataExchange.curvefile) } inline void DataExchange::set_curvefile(const char* value) { GOOGLE_DCHECK(value != nullptr); curvefile_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value), GetArena()); // @@protoc_insertion_point(field_set_char:FlumaionQL.DataExchange.curvefile) } inline void DataExchange::set_curvefile(const char* value, size_t size) { curvefile_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string( reinterpret_cast<const char*>(value), size), GetArena()); // @@protoc_insertion_point(field_set_pointer:FlumaionQL.DataExchange.curvefile) } inline std::string* DataExchange::_internal_mutable_curvefile() { return curvefile_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } inline std::string* DataExchange::release_curvefile() { // @@protoc_insertion_point(field_release:FlumaionQL.DataExchange.curvefile) return curvefile_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } inline void DataExchange::set_allocated_curvefile(std::string* curvefile) { if (curvefile != nullptr) { } else { } curvefile_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), curvefile, GetArena()); // @@protoc_insertion_point(field_set_allocated:FlumaionQL.DataExchange.curvefile) } inline std::string* DataExchange::unsafe_arena_release_curvefile() { // @@protoc_insertion_point(field_unsafe_arena_release:FlumaionQL.DataExchange.curvefile) GOOGLE_DCHECK(GetArena() != nullptr); return curvefile_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } inline void DataExchange::unsafe_arena_set_allocated_curvefile( std::string* curvefile) { GOOGLE_DCHECK(GetArena() != nullptr); if (curvefile != nullptr) { } else { } curvefile_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), curvefile, GetArena()); // @@protoc_insertion_point(field_unsafe_arena_set_allocated:FlumaionQL.DataExchange.curvefile) } // string fixingfile = 2; inline void DataExchange::clear_fixingfile() { fixingfile_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } inline const std::string& DataExchange::fixingfile() const { // @@protoc_insertion_point(field_get:FlumaionQL.DataExchange.fixingfile) return _internal_fixingfile(); } inline void DataExchange::set_fixingfile(const std::string& value) { _internal_set_fixingfile(value); // @@protoc_insertion_point(field_set:FlumaionQL.DataExchange.fixingfile) } inline std::string* DataExchange::mutable_fixingfile() { // @@protoc_insertion_point(field_mutable:FlumaionQL.DataExchange.fixingfile) return _internal_mutable_fixingfile(); } inline const std::string& DataExchange::_internal_fixingfile() const { return fixingfile_.Get(); } inline void DataExchange::_internal_set_fixingfile(const std::string& value) { fixingfile_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena()); } inline void DataExchange::set_fixingfile(std::string&& value) { fixingfile_.Set( &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena()); // @@protoc_insertion_point(field_set_rvalue:FlumaionQL.DataExchange.fixingfile) } inline void DataExchange::set_fixingfile(const char* value) { GOOGLE_DCHECK(value != nullptr); fixingfile_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value), GetArena()); // @@protoc_insertion_point(field_set_char:FlumaionQL.DataExchange.fixingfile) } inline void DataExchange::set_fixingfile(const char* value, size_t size) { fixingfile_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string( reinterpret_cast<const char*>(value), size), GetArena()); // @@protoc_insertion_point(field_set_pointer:FlumaionQL.DataExchange.fixingfile) } inline std::string* DataExchange::_internal_mutable_fixingfile() { return fixingfile_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } inline std::string* DataExchange::release_fixingfile() { // @@protoc_insertion_point(field_release:FlumaionQL.DataExchange.fixingfile) return fixingfile_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } inline void DataExchange::set_allocated_fixingfile(std::string* fixingfile) { if (fixingfile != nullptr) { } else { } fixingfile_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), fixingfile, GetArena()); // @@protoc_insertion_point(field_set_allocated:FlumaionQL.DataExchange.fixingfile) } inline std::string* DataExchange::unsafe_arena_release_fixingfile() { // @@protoc_insertion_point(field_unsafe_arena_release:FlumaionQL.DataExchange.fixingfile) GOOGLE_DCHECK(GetArena() != nullptr); return fixingfile_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } inline void DataExchange::unsafe_arena_set_allocated_fixingfile( std::string* fixingfile) { GOOGLE_DCHECK(GetArena() != nullptr); if (fixingfile != nullptr) { } else { } fixingfile_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), fixingfile, GetArena()); // @@protoc_insertion_point(field_unsafe_arena_set_allocated:FlumaionQL.DataExchange.fixingfile) } // string tradefile = 3; inline void DataExchange::clear_tradefile() { tradefile_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } inline const std::string& DataExchange::tradefile() const { // @@protoc_insertion_point(field_get:FlumaionQL.DataExchange.tradefile) return _internal_tradefile(); } inline void DataExchange::set_tradefile(const std::string& value) { _internal_set_tradefile(value); // @@protoc_insertion_point(field_set:FlumaionQL.DataExchange.tradefile) } inline std::string* DataExchange::mutable_tradefile() { // @@protoc_insertion_point(field_mutable:FlumaionQL.DataExchange.tradefile) return _internal_mutable_tradefile(); } inline const std::string& DataExchange::_internal_tradefile() const { return tradefile_.Get(); } inline void DataExchange::_internal_set_tradefile(const std::string& value) { tradefile_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena()); } inline void DataExchange::set_tradefile(std::string&& value) { tradefile_.Set( &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena()); // @@protoc_insertion_point(field_set_rvalue:FlumaionQL.DataExchange.tradefile) } inline void DataExchange::set_tradefile(const char* value) { GOOGLE_DCHECK(value != nullptr); tradefile_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value), GetArena()); // @@protoc_insertion_point(field_set_char:FlumaionQL.DataExchange.tradefile) } inline void DataExchange::set_tradefile(const char* value, size_t size) { tradefile_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string( reinterpret_cast<const char*>(value), size), GetArena()); // @@protoc_insertion_point(field_set_pointer:FlumaionQL.DataExchange.tradefile) } inline std::string* DataExchange::_internal_mutable_tradefile() { return tradefile_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } inline std::string* DataExchange::release_tradefile() { // @@protoc_insertion_point(field_release:FlumaionQL.DataExchange.tradefile) return tradefile_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } inline void DataExchange::set_allocated_tradefile(std::string* tradefile) { if (tradefile != nullptr) { } else { } tradefile_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), tradefile, GetArena()); // @@protoc_insertion_point(field_set_allocated:FlumaionQL.DataExchange.tradefile) } inline std::string* DataExchange::unsafe_arena_release_tradefile() { // @@protoc_insertion_point(field_unsafe_arena_release:FlumaionQL.DataExchange.tradefile) GOOGLE_DCHECK(GetArena() != nullptr); return tradefile_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } inline void DataExchange::unsafe_arena_set_allocated_tradefile( std::string* tradefile) { GOOGLE_DCHECK(GetArena() != nullptr); if (tradefile != nullptr) { } else { } tradefile_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), tradefile, GetArena()); // @@protoc_insertion_point(field_unsafe_arena_set_allocated:FlumaionQL.DataExchange.tradefile) } // string evaldate = 4; inline void DataExchange::clear_evaldate() { evaldate_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } inline const std::string& DataExchange::evaldate() const { // @@protoc_insertion_point(field_get:FlumaionQL.DataExchange.evaldate) return _internal_evaldate(); } inline void DataExchange::set_evaldate(const std::string& value) { _internal_set_evaldate(value); // @@protoc_insertion_point(field_set:FlumaionQL.DataExchange.evaldate) } inline std::string* DataExchange::mutable_evaldate() { // @@protoc_insertion_point(field_mutable:FlumaionQL.DataExchange.evaldate) return _internal_mutable_evaldate(); } inline const std::string& DataExchange::_internal_evaldate() const { return evaldate_.Get(); } inline void DataExchange::_internal_set_evaldate(const std::string& value) { evaldate_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena()); } inline void DataExchange::set_evaldate(std::string&& value) { evaldate_.Set( &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena()); // @@protoc_insertion_point(field_set_rvalue:FlumaionQL.DataExchange.evaldate) } inline void DataExchange::set_evaldate(const char* value) { GOOGLE_DCHECK(value != nullptr); evaldate_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value), GetArena()); // @@protoc_insertion_point(field_set_char:FlumaionQL.DataExchange.evaldate) } inline void DataExchange::set_evaldate(const char* value, size_t size) { evaldate_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string( reinterpret_cast<const char*>(value), size), GetArena()); // @@protoc_insertion_point(field_set_pointer:FlumaionQL.DataExchange.evaldate) } inline std::string* DataExchange::_internal_mutable_evaldate() { return evaldate_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } inline std::string* DataExchange::release_evaldate() { // @@protoc_insertion_point(field_release:FlumaionQL.DataExchange.evaldate) return evaldate_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } inline void DataExchange::set_allocated_evaldate(std::string* evaldate) { if (evaldate != nullptr) { } else { } evaldate_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), evaldate, GetArena()); // @@protoc_insertion_point(field_set_allocated:FlumaionQL.DataExchange.evaldate) } inline std::string* DataExchange::unsafe_arena_release_evaldate() { // @@protoc_insertion_point(field_unsafe_arena_release:FlumaionQL.DataExchange.evaldate) GOOGLE_DCHECK(GetArena() != nullptr); return evaldate_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } inline void DataExchange::unsafe_arena_set_allocated_evaldate( std::string* evaldate) { GOOGLE_DCHECK(GetArena() != nullptr); if (evaldate != nullptr) { } else { } evaldate_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), evaldate, GetArena()); // @@protoc_insertion_point(field_unsafe_arena_set_allocated:FlumaionQL.DataExchange.evaldate) } // string resultsfile = 5; inline void DataExchange::clear_resultsfile() { resultsfile_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } inline const std::string& DataExchange::resultsfile() const { // @@protoc_insertion_point(field_get:FlumaionQL.DataExchange.resultsfile) return _internal_resultsfile(); } inline void DataExchange::set_resultsfile(const std::string& value) { _internal_set_resultsfile(value); // @@protoc_insertion_point(field_set:FlumaionQL.DataExchange.resultsfile) } inline std::string* DataExchange::mutable_resultsfile() { // @@protoc_insertion_point(field_mutable:FlumaionQL.DataExchange.resultsfile) return _internal_mutable_resultsfile(); } inline const std::string& DataExchange::_internal_resultsfile() const { return resultsfile_.Get(); } inline void DataExchange::_internal_set_resultsfile(const std::string& value) { resultsfile_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena()); } inline void DataExchange::set_resultsfile(std::string&& value) { resultsfile_.Set( &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena()); // @@protoc_insertion_point(field_set_rvalue:FlumaionQL.DataExchange.resultsfile) } inline void DataExchange::set_resultsfile(const char* value) { GOOGLE_DCHECK(value != nullptr); resultsfile_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value), GetArena()); // @@protoc_insertion_point(field_set_char:FlumaionQL.DataExchange.resultsfile) } inline void DataExchange::set_resultsfile(const char* value, size_t size) { resultsfile_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string( reinterpret_cast<const char*>(value), size), GetArena()); // @@protoc_insertion_point(field_set_pointer:FlumaionQL.DataExchange.resultsfile) } inline std::string* DataExchange::_internal_mutable_resultsfile() { return resultsfile_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } inline std::string* DataExchange::release_resultsfile() { // @@protoc_insertion_point(field_release:FlumaionQL.DataExchange.resultsfile) return resultsfile_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } inline void DataExchange::set_allocated_resultsfile(std::string* resultsfile) { if (resultsfile != nullptr) { } else { } resultsfile_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), resultsfile, GetArena()); // @@protoc_insertion_point(field_set_allocated:FlumaionQL.DataExchange.resultsfile) } inline std::string* DataExchange::unsafe_arena_release_resultsfile() { // @@protoc_insertion_point(field_unsafe_arena_release:FlumaionQL.DataExchange.resultsfile) GOOGLE_DCHECK(GetArena() != nullptr); return resultsfile_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } inline void DataExchange::unsafe_arena_set_allocated_resultsfile( std::string* resultsfile) { GOOGLE_DCHECK(GetArena() != nullptr); if (resultsfile != nullptr) { } else { } resultsfile_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), resultsfile, GetArena()); // @@protoc_insertion_point(field_unsafe_arena_set_allocated:FlumaionQL.DataExchange.resultsfile) } // string scenarioid = 6; inline void DataExchange::clear_scenarioid() { scenarioid_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } inline const std::string& DataExchange::scenarioid() const { // @@protoc_insertion_point(field_get:FlumaionQL.DataExchange.scenarioid) return _internal_scenarioid(); } inline void DataExchange::set_scenarioid(const std::string& value) { _internal_set_scenarioid(value); // @@protoc_insertion_point(field_set:FlumaionQL.DataExchange.scenarioid) } inline std::string* DataExchange::mutable_scenarioid() { // @@protoc_insertion_point(field_mutable:FlumaionQL.DataExchange.scenarioid) return _internal_mutable_scenarioid(); } inline const std::string& DataExchange::_internal_scenarioid() const { return scenarioid_.Get(); } inline void DataExchange::_internal_set_scenarioid(const std::string& value) { scenarioid_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena()); } inline void DataExchange::set_scenarioid(std::string&& value) { scenarioid_.Set( &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena()); // @@protoc_insertion_point(field_set_rvalue:FlumaionQL.DataExchange.scenarioid) } inline void DataExchange::set_scenarioid(const char* value) { GOOGLE_DCHECK(value != nullptr); scenarioid_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value), GetArena()); // @@protoc_insertion_point(field_set_char:FlumaionQL.DataExchange.scenarioid) } inline void DataExchange::set_scenarioid(const char* value, size_t size) { scenarioid_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string( reinterpret_cast<const char*>(value), size), GetArena()); // @@protoc_insertion_point(field_set_pointer:FlumaionQL.DataExchange.scenarioid) } inline std::string* DataExchange::_internal_mutable_scenarioid() { return scenarioid_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } inline std::string* DataExchange::release_scenarioid() { // @@protoc_insertion_point(field_release:FlumaionQL.DataExchange.scenarioid) return scenarioid_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } inline void DataExchange::set_allocated_scenarioid(std::string* scenarioid) { if (scenarioid != nullptr) { } else { } scenarioid_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), scenarioid, GetArena()); // @@protoc_insertion_point(field_set_allocated:FlumaionQL.DataExchange.scenarioid) } inline std::string* DataExchange::unsafe_arena_release_scenarioid() { // @@protoc_insertion_point(field_unsafe_arena_release:FlumaionQL.DataExchange.scenarioid) GOOGLE_DCHECK(GetArena() != nullptr); return scenarioid_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } inline void DataExchange::unsafe_arena_set_allocated_scenarioid( std::string* scenarioid) { GOOGLE_DCHECK(GetArena() != nullptr); if (scenarioid != nullptr) { } else { } scenarioid_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), scenarioid, GetArena()); // @@protoc_insertion_point(field_unsafe_arena_set_allocated:FlumaionQL.DataExchange.scenarioid) } // string tradeid = 7; inline void DataExchange::clear_tradeid() { tradeid_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } inline const std::string& DataExchange::tradeid() const { // @@protoc_insertion_point(field_get:FlumaionQL.DataExchange.tradeid) return _internal_tradeid(); } inline void DataExchange::set_tradeid(const std::string& value) { _internal_set_tradeid(value); // @@protoc_insertion_point(field_set:FlumaionQL.DataExchange.tradeid) } inline std::string* DataExchange::mutable_tradeid() { // @@protoc_insertion_point(field_mutable:FlumaionQL.DataExchange.tradeid) return _internal_mutable_tradeid(); } inline const std::string& DataExchange::_internal_tradeid() const { return tradeid_.Get(); } inline void DataExchange::_internal_set_tradeid(const std::string& value) { tradeid_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena()); } inline void DataExchange::set_tradeid(std::string&& value) { tradeid_.Set( &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena()); // @@protoc_insertion_point(field_set_rvalue:FlumaionQL.DataExchange.tradeid) } inline void DataExchange::set_tradeid(const char* value) { GOOGLE_DCHECK(value != nullptr); tradeid_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value), GetArena()); // @@protoc_insertion_point(field_set_char:FlumaionQL.DataExchange.tradeid) } inline void DataExchange::set_tradeid(const char* value, size_t size) { tradeid_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string( reinterpret_cast<const char*>(value), size), GetArena()); // @@protoc_insertion_point(field_set_pointer:FlumaionQL.DataExchange.tradeid) } inline std::string* DataExchange::_internal_mutable_tradeid() { return tradeid_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } inline std::string* DataExchange::release_tradeid() { // @@protoc_insertion_point(field_release:FlumaionQL.DataExchange.tradeid) return tradeid_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } inline void DataExchange::set_allocated_tradeid(std::string* tradeid) { if (tradeid != nullptr) { } else { } tradeid_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), tradeid, GetArena()); // @@protoc_insertion_point(field_set_allocated:FlumaionQL.DataExchange.tradeid) } inline std::string* DataExchange::unsafe_arena_release_tradeid() { // @@protoc_insertion_point(field_unsafe_arena_release:FlumaionQL.DataExchange.tradeid) GOOGLE_DCHECK(GetArena() != nullptr); return tradeid_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } inline void DataExchange::unsafe_arena_set_allocated_tradeid( std::string* tradeid) { GOOGLE_DCHECK(GetArena() != nullptr); if (tradeid != nullptr) { } else { } tradeid_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), tradeid, GetArena()); // @@protoc_insertion_point(field_unsafe_arena_set_allocated:FlumaionQL.DataExchange.tradeid) } #ifdef __GNUC__ #pragma GCC diagnostic pop #endif // __GNUC__ // @@protoc_insertion_point(namespace_scope) } // namespace FlumaionQL // @@protoc_insertion_point(global_scope) #include <google/protobuf/port_undef.inc> #endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_exchange_2eproto
[ "noreply@github.com" ]
noreply@github.com
3bb1df5333f2502bdd5cf6eed01d0c335cf210f3
87dcc301f29042ebb3455403a015b9ba07d6a2dc
/Planewar/bullet.h
717cdd4f60e015db7738c9dc56573756b54f00f4
[]
no_license
lunlun0857/Planewar
57d45893796f1c9fb209b03aa866a071759e00da
70afd1755695f1d91eb8fe6b127df36f52fb7fee
refs/heads/main
2023-04-20T13:19:29.227833
2021-05-12T10:57:13
2021-05-12T10:57:13
363,356,342
0
0
null
null
null
null
GB18030
C++
false
false
439
h
#ifndef BULLET_H #define BULLET_H #include "config.h" #include <QPixmap> class Bullet { public: Bullet(); //更新子彈坐標 void updatePosition(); //子彈資源對象 QPixmap m_Bullet; //子弹坐标 int m_X; int m_Y; //子彈移動速度 int m_Speed; //子彈是否閒置 bool m_Free; //子彈的矩形邊框(用於碰撞檢測) QRect m_Rect; }; #endif // BULLET_H
[ "taso31609@gmail.com" ]
taso31609@gmail.com
3e935eadc408c872ca12525977c6c4c6021d2953
48e8d00debd2be1bbbfebd48de6e03c090a16649
/vod/src/v20180717/model/MediaInfo.cpp
00eafd6fe524da22d8a2da86ccd8496e9dd9142b
[ "Apache-2.0" ]
permissive
xuliangyu1991/tencentcloud-sdk-cpp
b3ef802c0aa5010e5af42d68de84080697f717d5
f4b057e66ddb1e8761df2152f1faaa10870cc5c7
refs/heads/master
2020-06-19T03:24:04.286285
2019-06-20T07:04:49
2019-06-20T07:04:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,871
cpp
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/vod/v20180717/model/MediaInfo.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Vod::V20180717::Model; using namespace rapidjson; using namespace std; MediaInfo::MediaInfo() : m_basicInfoHasBeenSet(false), m_metaDataHasBeenSet(false), m_transcodeInfoHasBeenSet(false), m_animatedGraphicsInfoHasBeenSet(false), m_sampleSnapshotInfoHasBeenSet(false), m_imageSpriteInfoHasBeenSet(false), m_snapshotByTimeOffsetInfoHasBeenSet(false), m_keyFrameDescInfoHasBeenSet(false), m_adaptiveDynamicStreamingInfoHasBeenSet(false), m_fileIdHasBeenSet(false) { } CoreInternalOutcome MediaInfo::Deserialize(const Value &value) { string requestId = ""; if (value.HasMember("BasicInfo") && !value["BasicInfo"].IsNull()) { if (!value["BasicInfo"].IsObject()) { return CoreInternalOutcome(Error("response `MediaInfo.BasicInfo` is not object type").SetRequestId(requestId)); } CoreInternalOutcome outcome = m_basicInfo.Deserialize(value["BasicInfo"]); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_basicInfoHasBeenSet = true; } if (value.HasMember("MetaData") && !value["MetaData"].IsNull()) { if (!value["MetaData"].IsObject()) { return CoreInternalOutcome(Error("response `MediaInfo.MetaData` is not object type").SetRequestId(requestId)); } CoreInternalOutcome outcome = m_metaData.Deserialize(value["MetaData"]); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_metaDataHasBeenSet = true; } if (value.HasMember("TranscodeInfo") && !value["TranscodeInfo"].IsNull()) { if (!value["TranscodeInfo"].IsObject()) { return CoreInternalOutcome(Error("response `MediaInfo.TranscodeInfo` is not object type").SetRequestId(requestId)); } CoreInternalOutcome outcome = m_transcodeInfo.Deserialize(value["TranscodeInfo"]); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_transcodeInfoHasBeenSet = true; } if (value.HasMember("AnimatedGraphicsInfo") && !value["AnimatedGraphicsInfo"].IsNull()) { if (!value["AnimatedGraphicsInfo"].IsObject()) { return CoreInternalOutcome(Error("response `MediaInfo.AnimatedGraphicsInfo` is not object type").SetRequestId(requestId)); } CoreInternalOutcome outcome = m_animatedGraphicsInfo.Deserialize(value["AnimatedGraphicsInfo"]); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_animatedGraphicsInfoHasBeenSet = true; } if (value.HasMember("SampleSnapshotInfo") && !value["SampleSnapshotInfo"].IsNull()) { if (!value["SampleSnapshotInfo"].IsObject()) { return CoreInternalOutcome(Error("response `MediaInfo.SampleSnapshotInfo` is not object type").SetRequestId(requestId)); } CoreInternalOutcome outcome = m_sampleSnapshotInfo.Deserialize(value["SampleSnapshotInfo"]); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_sampleSnapshotInfoHasBeenSet = true; } if (value.HasMember("ImageSpriteInfo") && !value["ImageSpriteInfo"].IsNull()) { if (!value["ImageSpriteInfo"].IsObject()) { return CoreInternalOutcome(Error("response `MediaInfo.ImageSpriteInfo` is not object type").SetRequestId(requestId)); } CoreInternalOutcome outcome = m_imageSpriteInfo.Deserialize(value["ImageSpriteInfo"]); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_imageSpriteInfoHasBeenSet = true; } if (value.HasMember("SnapshotByTimeOffsetInfo") && !value["SnapshotByTimeOffsetInfo"].IsNull()) { if (!value["SnapshotByTimeOffsetInfo"].IsObject()) { return CoreInternalOutcome(Error("response `MediaInfo.SnapshotByTimeOffsetInfo` is not object type").SetRequestId(requestId)); } CoreInternalOutcome outcome = m_snapshotByTimeOffsetInfo.Deserialize(value["SnapshotByTimeOffsetInfo"]); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_snapshotByTimeOffsetInfoHasBeenSet = true; } if (value.HasMember("KeyFrameDescInfo") && !value["KeyFrameDescInfo"].IsNull()) { if (!value["KeyFrameDescInfo"].IsObject()) { return CoreInternalOutcome(Error("response `MediaInfo.KeyFrameDescInfo` is not object type").SetRequestId(requestId)); } CoreInternalOutcome outcome = m_keyFrameDescInfo.Deserialize(value["KeyFrameDescInfo"]); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_keyFrameDescInfoHasBeenSet = true; } if (value.HasMember("AdaptiveDynamicStreamingInfo") && !value["AdaptiveDynamicStreamingInfo"].IsNull()) { if (!value["AdaptiveDynamicStreamingInfo"].IsObject()) { return CoreInternalOutcome(Error("response `MediaInfo.AdaptiveDynamicStreamingInfo` is not object type").SetRequestId(requestId)); } CoreInternalOutcome outcome = m_adaptiveDynamicStreamingInfo.Deserialize(value["AdaptiveDynamicStreamingInfo"]); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_adaptiveDynamicStreamingInfoHasBeenSet = true; } if (value.HasMember("FileId") && !value["FileId"].IsNull()) { if (!value["FileId"].IsString()) { return CoreInternalOutcome(Error("response `MediaInfo.FileId` IsString=false incorrectly").SetRequestId(requestId)); } m_fileId = string(value["FileId"].GetString()); m_fileIdHasBeenSet = true; } return CoreInternalOutcome(true); } void MediaInfo::ToJsonObject(Value &value, Document::AllocatorType& allocator) const { if (m_basicInfoHasBeenSet) { Value iKey(kStringType); string key = "BasicInfo"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(kObjectType).Move(), allocator); m_basicInfo.ToJsonObject(value[key.c_str()], allocator); } if (m_metaDataHasBeenSet) { Value iKey(kStringType); string key = "MetaData"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(kObjectType).Move(), allocator); m_metaData.ToJsonObject(value[key.c_str()], allocator); } if (m_transcodeInfoHasBeenSet) { Value iKey(kStringType); string key = "TranscodeInfo"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(kObjectType).Move(), allocator); m_transcodeInfo.ToJsonObject(value[key.c_str()], allocator); } if (m_animatedGraphicsInfoHasBeenSet) { Value iKey(kStringType); string key = "AnimatedGraphicsInfo"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(kObjectType).Move(), allocator); m_animatedGraphicsInfo.ToJsonObject(value[key.c_str()], allocator); } if (m_sampleSnapshotInfoHasBeenSet) { Value iKey(kStringType); string key = "SampleSnapshotInfo"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(kObjectType).Move(), allocator); m_sampleSnapshotInfo.ToJsonObject(value[key.c_str()], allocator); } if (m_imageSpriteInfoHasBeenSet) { Value iKey(kStringType); string key = "ImageSpriteInfo"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(kObjectType).Move(), allocator); m_imageSpriteInfo.ToJsonObject(value[key.c_str()], allocator); } if (m_snapshotByTimeOffsetInfoHasBeenSet) { Value iKey(kStringType); string key = "SnapshotByTimeOffsetInfo"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(kObjectType).Move(), allocator); m_snapshotByTimeOffsetInfo.ToJsonObject(value[key.c_str()], allocator); } if (m_keyFrameDescInfoHasBeenSet) { Value iKey(kStringType); string key = "KeyFrameDescInfo"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(kObjectType).Move(), allocator); m_keyFrameDescInfo.ToJsonObject(value[key.c_str()], allocator); } if (m_adaptiveDynamicStreamingInfoHasBeenSet) { Value iKey(kStringType); string key = "AdaptiveDynamicStreamingInfo"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(kObjectType).Move(), allocator); m_adaptiveDynamicStreamingInfo.ToJsonObject(value[key.c_str()], allocator); } if (m_fileIdHasBeenSet) { Value iKey(kStringType); string key = "FileId"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_fileId.c_str(), allocator).Move(), allocator); } } MediaBasicInfo MediaInfo::GetBasicInfo() const { return m_basicInfo; } void MediaInfo::SetBasicInfo(const MediaBasicInfo& _basicInfo) { m_basicInfo = _basicInfo; m_basicInfoHasBeenSet = true; } bool MediaInfo::BasicInfoHasBeenSet() const { return m_basicInfoHasBeenSet; } MediaMetaData MediaInfo::GetMetaData() const { return m_metaData; } void MediaInfo::SetMetaData(const MediaMetaData& _metaData) { m_metaData = _metaData; m_metaDataHasBeenSet = true; } bool MediaInfo::MetaDataHasBeenSet() const { return m_metaDataHasBeenSet; } MediaTranscodeInfo MediaInfo::GetTranscodeInfo() const { return m_transcodeInfo; } void MediaInfo::SetTranscodeInfo(const MediaTranscodeInfo& _transcodeInfo) { m_transcodeInfo = _transcodeInfo; m_transcodeInfoHasBeenSet = true; } bool MediaInfo::TranscodeInfoHasBeenSet() const { return m_transcodeInfoHasBeenSet; } MediaAnimatedGraphicsInfo MediaInfo::GetAnimatedGraphicsInfo() const { return m_animatedGraphicsInfo; } void MediaInfo::SetAnimatedGraphicsInfo(const MediaAnimatedGraphicsInfo& _animatedGraphicsInfo) { m_animatedGraphicsInfo = _animatedGraphicsInfo; m_animatedGraphicsInfoHasBeenSet = true; } bool MediaInfo::AnimatedGraphicsInfoHasBeenSet() const { return m_animatedGraphicsInfoHasBeenSet; } MediaSampleSnapshotInfo MediaInfo::GetSampleSnapshotInfo() const { return m_sampleSnapshotInfo; } void MediaInfo::SetSampleSnapshotInfo(const MediaSampleSnapshotInfo& _sampleSnapshotInfo) { m_sampleSnapshotInfo = _sampleSnapshotInfo; m_sampleSnapshotInfoHasBeenSet = true; } bool MediaInfo::SampleSnapshotInfoHasBeenSet() const { return m_sampleSnapshotInfoHasBeenSet; } MediaImageSpriteInfo MediaInfo::GetImageSpriteInfo() const { return m_imageSpriteInfo; } void MediaInfo::SetImageSpriteInfo(const MediaImageSpriteInfo& _imageSpriteInfo) { m_imageSpriteInfo = _imageSpriteInfo; m_imageSpriteInfoHasBeenSet = true; } bool MediaInfo::ImageSpriteInfoHasBeenSet() const { return m_imageSpriteInfoHasBeenSet; } MediaSnapshotByTimeOffsetInfo MediaInfo::GetSnapshotByTimeOffsetInfo() const { return m_snapshotByTimeOffsetInfo; } void MediaInfo::SetSnapshotByTimeOffsetInfo(const MediaSnapshotByTimeOffsetInfo& _snapshotByTimeOffsetInfo) { m_snapshotByTimeOffsetInfo = _snapshotByTimeOffsetInfo; m_snapshotByTimeOffsetInfoHasBeenSet = true; } bool MediaInfo::SnapshotByTimeOffsetInfoHasBeenSet() const { return m_snapshotByTimeOffsetInfoHasBeenSet; } MediaKeyFrameDescInfo MediaInfo::GetKeyFrameDescInfo() const { return m_keyFrameDescInfo; } void MediaInfo::SetKeyFrameDescInfo(const MediaKeyFrameDescInfo& _keyFrameDescInfo) { m_keyFrameDescInfo = _keyFrameDescInfo; m_keyFrameDescInfoHasBeenSet = true; } bool MediaInfo::KeyFrameDescInfoHasBeenSet() const { return m_keyFrameDescInfoHasBeenSet; } MediaAdaptiveDynamicStreamingInfo MediaInfo::GetAdaptiveDynamicStreamingInfo() const { return m_adaptiveDynamicStreamingInfo; } void MediaInfo::SetAdaptiveDynamicStreamingInfo(const MediaAdaptiveDynamicStreamingInfo& _adaptiveDynamicStreamingInfo) { m_adaptiveDynamicStreamingInfo = _adaptiveDynamicStreamingInfo; m_adaptiveDynamicStreamingInfoHasBeenSet = true; } bool MediaInfo::AdaptiveDynamicStreamingInfoHasBeenSet() const { return m_adaptiveDynamicStreamingInfoHasBeenSet; } string MediaInfo::GetFileId() const { return m_fileId; } void MediaInfo::SetFileId(const string& _fileId) { m_fileId = _fileId; m_fileIdHasBeenSet = true; } bool MediaInfo::FileIdHasBeenSet() const { return m_fileIdHasBeenSet; }
[ "jimmyzhuang@tencent.com" ]
jimmyzhuang@tencent.com
78d0fa1cf38561982fb101479f5ee0e4e0341ef3
db507912e598b291811a5a73db5f8ba33c8be2f9
/server/stklib/Src/TechKLine.cpp
0d0b3e5bf8b0d3b1b4a324f6a02ea111c5c71762
[]
no_license
biniyu/k-line-print
ab3ee023876adaa9de8dd98b14dbd362a0b2810a
d1e033f79044d6ae62f86e6116cc902b6a7eeb83
refs/heads/master
2016-09-06T14:19:55.887544
2013-08-25T14:59:21
2013-08-25T14:59:21
40,391,671
2
0
null
null
null
null
GB18030
C++
false
false
27,686
cpp
/* Cross Platform Core Code. Copyright(R) 2001-2002 Balang Software. All rights reserved. */ #include "StdAfx.h" #include "../Include/Stock.h" #include "../Include/Technique.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #ifdef _DEBUG #define new DEBUG_NEW #endif ////////////////////////////////////////////////////////////////////// // CKLine CKLine::CKLine( ) { SetDefaultParameters( ); } CKLine::CKLine( CKData * pKData ) : CTechnique( pKData ) { SetDefaultParameters( ); } CKLine::~CKLine() { Clear( ); } void CKLine::SetDefaultParameters( ) { } void CKLine::AttachParameters( CKLine & src ) { } BOOL CKLine::IsValidParameters( ) { return TRUE; } void CKLine::Clear( ) { CTechnique::Clear( ); } /*** 得到K线价格的从nStart到nEnd的最小值和最大值 */ BOOL CKLine::GetMinMaxInfo( int nStart, int nEnd, double *pdMin, double *pdMax ) { STT_ASSERT_GETMINMAXINFO( m_pKData, nStart, nEnd ); double dMin = -1; double dMax = 1; for( int k=nStart; k<=nEnd; k++ ) { KDATA & kd = m_pKData->ElementAt(k); if( nStart == k || dMin > kd.m_fLow ) dMin = (double)kd.m_fLow; if( nStart == k || dMax < kd.m_fHigh ) dMax = (double)kd.m_fHigh; } dMin -= fabs(dMin - dMax) * 0.1; dMax += fabs(dMin - dMax) * 0.1; if( dMin <= 0 ) dMin = 0; if( dMax - dMin < 0.03 ) dMax = dMin + 0.03; if( pdMin ) *pdMin = dMin; if( pdMax ) *pdMax = dMax; return TRUE; } ////////////////////////////////////////////////////////////////////// // CMA CMA::CMA( ) { SetDefaultParameters( ); } CMA::CMA( CKData * pKData ) : CTechnique( pKData ) { SetDefaultParameters( ); } CMA::~CMA() { Clear( ); } void CMA::SetDefaultParameters( ) { m_nType = typeMA; m_adwMADays.RemoveAll(); m_adwMADays.Add( 5 ); m_adwMADays.Add( 10 ); m_adwMADays.Add( 20 ); m_itsGoldenFork = ITS_BUYINTENSE; m_itsDeadFork = ITS_SELLINTENSE; m_itsLong = ITS_BUY; m_itsShort = ITS_SELL; } void CMA::AttachParameters( CMA & src ) { m_nType = src.m_nType; m_adwMADays.Copy( src.m_adwMADays ); m_itsGoldenFork = src.m_itsGoldenFork; m_itsDeadFork = src.m_itsDeadFork; m_itsLong = src.m_itsLong; m_itsShort = src.m_itsShort; } BOOL CMA::IsValidParameters( ) { STT_VALID_DAYSARRAY( m_adwMADays ); return ( (typeMA == m_nType || typeEXPMA == m_nType) && VALID_ITS(m_itsGoldenFork) && VALID_ITS(m_itsDeadFork) && VALID_ITS(m_itsLong) && VALID_ITS(m_itsShort) ); } void CMA::Clear( ) { CTechnique::Clear( ); } int CMA::GetSignal( int nIndex, UINT * pnCode ) { // 金叉或者死叉 int nSignal = GetForkSignal( nIndex, m_adwMADays, m_itsGoldenFork, m_itsDeadFork, pnCode ); if( ITS_ISBUY(nSignal) || ITS_ISSELL(nSignal) ) return nSignal; // 趋势 return GetTrendIntensity( nIndex, m_adwMADays, m_itsLong, m_itsShort, pnCode ); } BOOL CMA::GetMinMaxInfo(int nStart, int nEnd, double *pdMin, double *pdMax ) { return AfxGetMinMaxInfo( nStart, nEnd, pdMin, pdMax, this, m_adwMADays ); } /*** 两种: 1. MA MA = n日收盘价的平均值 2. EXPMA EXPMA(1) = CLOSE(1) EXPMA(i) = (1-α)EXPMA(i-1) + αCLOSE(i) 其中 α = 2 / (n+1) */ BOOL CMA::Calculate( double * pValue, int nIndex, int nDays, BOOL bUseLast ) { STT_ASSERT_CALCULATE( m_pKData, nIndex, nDays ); int nCount = 0; if( nDays > nIndex+1 ) return FALSE; double dResult = 0; int k = 0; switch( m_nType ) { case typeMA: return m_pKData->GetMA( pValue, nIndex, nDays ); break; case typeEXPMA: if( bUseLast && pValue ) { if( 0 == nIndex ) dResult = m_pKData->MaindataAt(nIndex); else dResult = (*pValue)*(nDays-1)/(nDays+1) + m_pKData->MaindataAt(nIndex) * 2./(nDays+1); } else { for( k=0; k<=nIndex; k++ ) { if( 0 == k ) dResult = m_pKData->MaindataAt(k); else dResult = dResult*(nDays-1)/(nDays+1) + m_pKData->MaindataAt(k) * 2./(nDays+1); } } if( pValue ) *pValue = dResult; break; default: SP_ASSERT( FALSE ); } return TRUE; } ////////////////////////////////////////////////////////////////////// // CBBI CBBI::CBBI( ) { SetDefaultParameters( ); } CBBI::CBBI( CKData * pKData ) : CTechnique( pKData ) { SetDefaultParameters( ); } CBBI::~CBBI() { Clear( ); } void CBBI::SetDefaultParameters( ) { m_nMA1Days = 3; m_nMA2Days = 6; m_nMA3Days = 12; m_nMA4Days = 24; m_itsGoldenFork = ITS_BUY; m_itsDeadFork = ITS_SELL; } void CBBI::AttachParameters( CBBI & src ) { m_nMA1Days = src.m_nMA1Days; m_nMA2Days = src.m_nMA2Days; m_nMA3Days = src.m_nMA3Days; m_nMA4Days = src.m_nMA4Days; m_itsGoldenFork = src.m_itsGoldenFork; m_itsDeadFork = src.m_itsDeadFork; } BOOL CBBI::IsValidParameters( ) { return ( VALID_DAYS( m_nMA1Days ) && VALID_DAYS( m_nMA2Days ) && VALID_DAYS( m_nMA3Days ) && VALID_DAYS( m_nMA4Days ) && VALID_ITS(m_itsGoldenFork) && VALID_ITS(m_itsDeadFork) ); } void CBBI::Clear( ) { CTechnique::Clear( ); } int CBBI::GetSignal( int nIndex, UINT * pnCode ) { if( pnCode ) *pnCode = ITSC_NOTHING; if( nIndex <= 0 ) return ITS_NOTHING; double dLiminalLow = 0, dLiminalHigh = 0; if( !IntensityPreparePrice( nIndex, pnCode, 0, ITS_GETMINMAXDAYRANGE, &dLiminalLow, &dLiminalHigh, 0.4, 0.6 ) ) return ITS_NOTHING; double dBBINow = 0, dBBILast = 0; if( !Calculate( &dBBILast, nIndex-1, FALSE ) || !Calculate( &dBBINow, nIndex, FALSE ) ) return ITS_NOTHING; double dNowHigh = m_pKData->ElementAt(nIndex).m_fHigh; double dNowLow = m_pKData->ElementAt(nIndex).m_fLow; double dNowClose = m_pKData->ElementAt(nIndex).m_fClose; double dLastHigh = m_pKData->ElementAt(nIndex-1).m_fHigh; double dLastLow = m_pKData->ElementAt(nIndex-1).m_fLow; double dLastClose = m_pKData->ElementAt(nIndex-1).m_fClose; if( dNowClose < dLiminalLow && dLastLow < dBBILast && dNowLow > dBBINow ) { // 低位趋势向上 if( pnCode ) *pnCode = ITSC_GOLDENFORK; return m_itsGoldenFork; } if( dNowClose > dLiminalHigh && dLastHigh > dBBILast && dNowHigh < dBBINow ) { // 高位趋势向下 if( pnCode ) *pnCode = ITSC_DEADFORK; return m_itsDeadFork; } return ITS_NOTHING; } BOOL CBBI::GetMinMaxInfo(int nStart, int nEnd, double *pdMin, double *pdMax ) { return AfxGetMinMaxInfo1( nStart, nEnd, pdMin, pdMax, this ); } /*** BBI = 4 个 不同日期的MA 的平均值 */ BOOL CBBI::Calculate( double * pValue, int nIndex, BOOL bUseLast ) { STT_ASSERT_CALCULATE1( m_pKData, nIndex ); if( LoadFromCache( nIndex, pValue ) ) return TRUE; double dResult = 0; double dTemp = 0; if( !m_pKData->GetMA( &dTemp, nIndex, m_nMA1Days ) ) return FALSE; dResult += dTemp; if( !m_pKData->GetMA( &dTemp, nIndex, m_nMA2Days ) ) return FALSE; dResult += dTemp; if( !m_pKData->GetMA( &dTemp, nIndex, m_nMA3Days ) ) return FALSE; dResult += dTemp; if( !m_pKData->GetMA( &dTemp, nIndex, m_nMA4Days ) ) return FALSE; dResult += dTemp; dResult = dResult / 4; if( pValue ) *pValue = dResult; StoreToCache( nIndex, pValue ); return TRUE; } ////////////////////////////////////////////////////////////////////// // CBOLL CBOLL::CBOLL( ) { SetDefaultParameters( ); } CBOLL::CBOLL( CKData * pKData ) : CTechnique( pKData ) { SetDefaultParameters( ); } CBOLL::~CBOLL() { Clear( ); } void CBOLL::SetDefaultParameters( ) { m_dMultiUp = 2; m_dMultiDown = 2; m_nMADays = 20; m_itsSupport = ITS_BUY; m_itsResistance = ITS_SELL; } void CBOLL::AttachParameters( CBOLL & src ) { m_dMultiUp = src.m_dMultiUp; m_dMultiDown = src.m_dMultiDown; m_nMADays = src.m_nMADays; m_itsSupport = src.m_itsSupport; m_itsResistance = src.m_itsResistance; } BOOL CBOLL::IsValidParameters( ) { return ( m_dMultiUp > 0 && m_dMultiDown > 0 && VALID_DAYS( m_nMADays ) && VALID_ITS(m_itsSupport) && VALID_ITS(m_itsResistance) ); } void CBOLL::Clear( ) { CTechnique::Clear( ); } int CBOLL::GetSignal( int nIndex, UINT * pnCode ) { if( pnCode ) *pnCode = ITSC_NOTHING; double dMA = 0, dUp = 0, dDown = 0; if( !Calculate( &dMA, &dUp, &dDown, nIndex, FALSE ) ) return ITS_NOTHING; double dClose = m_pKData->ElementAt(nIndex).m_fClose; if( dClose < dDown ) { // 跌破支撑位 if( pnCode ) *pnCode = ITSC_SUPPORT; return m_itsSupport; } if( dClose > dUp ) { // 涨过阻力位 if( pnCode ) *pnCode = ITSC_RESISTANCE; return m_itsResistance; } return ITS_NOTHING; } BOOL CBOLL::GetMinMaxInfo(int nStart, int nEnd, double *pdMin, double *pdMax ) { return AfxGetMinMaxInfo3( nStart, nEnd, pdMin, pdMax, this ); } /*** 布林带是以股价平均线MA为中心线,上方阻力线MA+αSn和下方支撑线MA-αSn之间的带状区域 其中 Sn为n日收盘价的标准差 */ BOOL CBOLL::Calculate( double * pdMA, double * pdUp, double * pdDown, int nIndex, BOOL bUseLast ) { STT_ASSERT_CALCULATE1( m_pKData, nIndex ); if( m_nMADays < 2 ) return FALSE; if( LoadFromCache( nIndex, pdMA, pdUp, pdDown ) ) return TRUE; double dMA = 0, dUp = 0, dDown = 0, dS = 0; if( !m_pKData->GetMA( &dMA, nIndex, m_nMADays ) ) return FALSE; int nCount = 0; for( int k=nIndex; k>=0; k-- ) { dS += (m_pKData->MaindataAt(k) - dMA) * (m_pKData->MaindataAt(k) - dMA); nCount ++; if( nCount == m_nMADays ) break; } dS = sqrt( dS / (m_nMADays-1) ); dUp = dMA + m_dMultiUp * dS; dDown = dMA - m_dMultiDown * dS; if( pdMA ) *pdMA = dMA; if( pdUp ) *pdUp = dUp; if( pdDown ) *pdDown = dDown; StoreToCache( nIndex, pdMA, pdUp, pdDown ); return TRUE; } ////////////////////////////////////////////////////////////////////// // CPV CPV::CPV( ) { SetDefaultParameters( ); } CPV::CPV( CKData * pKData ) : CTechnique( pKData ) { SetDefaultParameters( ); } CPV::~CPV() { Clear( ); } void CPV::SetDefaultParameters( ) { } void CPV::AttachParameters( CPV & src ) { } BOOL CPV::IsValidParameters( ) { return TRUE; } void CPV::Clear( ) { CTechnique::Clear( ); } int CPV::GetSignal( int nIndex, UINT * pnCode ) { if( pnCode ) *pnCode = ITSC_NOTHING; // 无买卖信号 return ITS_NOTHING; } BOOL CPV::GetMinMaxInfo(int nStart, int nEnd, double *pdMin, double *pdMax ) { return AfxGetMinMaxInfo1( nStart, nEnd, pdMin, pdMax, this ); } /*** PV就是当日成交均价,成交额除以成交量 */ BOOL CPV::Calculate( double * pValue, int nIndex, BOOL bUseLast ) { STT_ASSERT_CALCULATE1( m_pKData, nIndex ); if( LoadFromCache( nIndex, pValue ) ) return TRUE; KDATA kd = m_pKData->ElementAt(nIndex); if( kd.m_fVolume <= 1e-4 || kd.m_fAmount <= 1e-4 ) return FALSE; int nCount = 0; double average = ((double)(kd.m_fAmount)) / kd.m_fVolume; while( average < kd.m_fLow && nCount < 10 ) { average *= 10; nCount ++; } while( average > kd.m_fHigh && nCount < 20 ) { average /= 10; nCount ++; } if( average < kd.m_fLow ) // 说明是指数 average = (kd.m_fOpen+kd.m_fHigh+kd.m_fLow+kd.m_fClose)/4; double dPV = average; if( pValue ) *pValue = dPV; StoreToCache( nIndex, pValue ); return TRUE; } ////////////////////////////////////////////////////////////////////// // CSAR CSAR::CSAR( ) { SetDefaultParameters( ); } CSAR::CSAR( CKData * pKData ) : CTechnique( pKData ) { SetDefaultParameters( ); m_bCurUp = m_bFirstUp; m_bTurn = FALSE; m_dCurAF = m_dAFStep; m_dCurHigh = -1; m_dCurLow = -1; } CSAR::~CSAR() { Clear( ); } void CSAR::SetDefaultParameters( ) { m_nInitDays = 4; m_bFirstUp = TRUE; m_dAFStep = 0.02; m_dAFMax = 0.2; m_itsBuy = ITS_BUY; m_itsSell = ITS_SELL; } void CSAR::AttachParameters( CSAR & src ) { m_nInitDays = src.m_nInitDays; m_bFirstUp = src.m_bFirstUp; m_dAFStep = src.m_dAFStep; m_dAFMax = src.m_dAFMax; m_itsBuy = src.m_itsBuy; m_itsSell = src.m_itsSell; } BOOL CSAR::IsValidParameters( ) { return ( VALID_DAYS(m_nInitDays) && m_bFirstUp >= 0 && m_dAFStep > 0 && m_dAFMax > 0 && VALID_ITS(m_itsBuy) && VALID_ITS(m_itsSell) ); } void CSAR::Clear( ) { CTechnique::Clear( ); } BOOL CSAR::CalculateSAR( double * pValue, int nIndex, BOOL bUseLast ) { STT_ASSERT_CALCULATE1( m_pKData, nIndex ); if( m_nInitDays > nIndex + 1 ) return FALSE; double dResult = 0; if( bUseLast && pValue && nIndex > 0 && !m_bTurn ) { KDATA kd = m_pKData->ElementAt(nIndex-1); if( m_bCurUp ) { dResult = (*pValue) + m_dCurAF * (kd.m_fHigh - (*pValue) ); if( kd.m_fHigh > m_dCurHigh ) { m_dCurHigh = kd.m_fHigh; m_dCurAF = m_dCurAF + m_dAFStep; if( m_dCurAF > m_dAFMax ) m_dCurAF = m_dAFMax; } if( m_pKData->ElementAt(nIndex).m_fLow < dResult ) m_bTurn = TRUE; } else { dResult = (*pValue) - m_dCurAF * ((*pValue) - kd.m_fLow ); if( kd.m_fLow < m_dCurLow ) { m_dCurLow = kd.m_fLow; m_dCurAF = m_dCurAF + m_dAFStep; if( m_dCurAF > m_dAFMax ) m_dCurAF = m_dAFMax; } if( m_pKData->ElementAt(nIndex).m_fHigh > dResult ) m_bTurn = TRUE; } } else { for( int k=nIndex; k>=nIndex-m_nInitDays+1; k-- ) { KDATA kd = m_pKData->ElementAt(k); if( nIndex == k ) { m_dCurHigh = kd.m_fHigh; m_dCurLow = kd.m_fLow; } else if( kd.m_fHigh > m_dCurHigh ) m_dCurHigh = kd.m_fHigh; else if( kd.m_fLow < m_dCurLow ) m_dCurLow = kd.m_fLow; } if( m_bTurn ) m_bCurUp = ! m_bCurUp; else m_bCurUp = m_bFirstUp; m_bTurn = FALSE; m_dCurAF = m_dAFStep; if( m_bCurUp ) dResult = m_dCurLow; else dResult = m_dCurHigh; } if( pValue ) *pValue = dResult; return TRUE; } int CSAR::GetSignal( int nIndex, UINT * pnCode ) { if( pnCode ) *pnCode = ITSC_NOTHING; Clear( ); double dValue; if( !Calculate( &dValue, nIndex, FALSE ) ) return ITS_NOTHING; if( m_bTurn && !m_bCurUp ) { // 反转向上 if( pnCode ) *pnCode = ITSC_LONG; return m_itsBuy; } if( m_bTurn && m_bCurUp ) { // 反转向下 if( pnCode ) *pnCode = ITSC_SHORT; return m_itsSell; } return ITS_NOTHING; } BOOL CSAR::GetMinMaxInfo(int nStart, int nEnd, double *pdMin, double *pdMax ) { return AfxGetMinMaxInfo1( nStart, nEnd, pdMin, pdMax, this ); } /*** 计算SAR值 先选定时间,判断价格是在上涨还是在下跌。 若是看涨,则进场第一天的SAR必须是近期内的最低价,是看跌 则进场第一天的SAR必须是近期内的最高价。 本处为缺省定义为看涨。 进场第二天的SAR则为第一天的最高价(看涨时)或最低价(看跌时)与第一天的SAR的差距乘上调整系数, 再加上第一天的SAR就可求得。 按逐步递推的方法,每日的SAR可归纳如下: SAR(N)= SAR(N-1)+ AF * [ EP(N-1)-SAR(N-1)] 其中SAR(N)为第N日的SAR值,AF是调整系数,EP为极点价 第一个调整系数AF为0.02,若每隔一天的最高价比前一天的最高价还高,则AF递增0.02,若未创新高, 则AF沿用前一天的数值,但调整系数最高不超过0.2。 若是买进期间,计算出某日的SAR比当日或前一日的最低价还高,则应以当日或者前一日的最低价为某日之SAR, 卖出期间也对应服从类似原则。 */ BOOL CSAR::Calculate( double * pValue, int nIndex, BOOL bUseLast ) { if( LoadFromCache( nIndex, pValue ) ) return TRUE; if( bUseLast && pValue && nIndex > 0 ) { if( CalculateSAR( pValue, nIndex, bUseLast ) ) { StoreToCache( nIndex, pValue ); return TRUE; } return FALSE; } else { double dResult; BOOL bHasLast = FALSE; for( int k=0; k<=nIndex; k++ ) { if( CalculateSAR( &dResult, k, bHasLast ) ) { bHasLast = TRUE; StoreToCache( k, &dResult ); } } if( !bHasLast ) return FALSE; if( pValue ) *pValue = dResult; return TRUE; } } ////////////////////////////////////////////////////////////////////// // CDJ CStock CDJ::m_stockSha; CStock CDJ::m_stockSzn; CSPString CDJ::m_strCodeOrg; CDJ::CDJ( ) { SetDefaultParameters( ); } CDJ::CDJ( CKData * pKData ) : CTechnique( pKData ) { SetDefaultParameters( ); } CDJ::~CDJ() { Clear( ); } void CDJ::SetDefaultParameters( ) { m_strCodeSha = STKLIB_CODE_MAIN; m_strCodeSzn = STKLIB_CODE_MAINSZN; } void CDJ::AttachParameters( CDJ & src ) { m_strCodeSha = src.m_strCodeSha; m_strCodeSzn = src.m_strCodeSzn; } BOOL CDJ::IsValidParameters( ) { return ( m_strCodeSha.GetLength() > 0 && m_strCodeSzn.GetLength() > 0 ); } void CDJ::Clear( ) { CTechnique::Clear( ); } /*** K线叠加图,准备叠加K线的数据 */ BOOL CDJ::PrepareStockData(CStDatabase * pDatabase, const char * szCodeOrg, int nCurKType, int nCurKFormat, int nCurMaindataType, DWORD dwAutoResumeDRBegin, int nAutoResumeDRLimit ) { SP_ASSERT( pDatabase ); // bReload and kdayMain BOOL bReload = (NULL!=szCodeOrg && 0!=strncmp(szCodeOrg,m_strCodeOrg,m_strCodeOrg.GetLength()) ); m_strCodeOrg = szCodeOrg; // m_stockSha m_stockSha.SetStockCode( CStock::marketSHSE, m_strCodeSha ); AfxPrepareStockData( pDatabase, m_stockSha, nCurKType, nCurKFormat, nCurMaindataType, FALSE, bReload ); // m_stockSzn m_stockSzn.SetStockCode( CStock::marketSZSE, m_strCodeSzn ); AfxPrepareStockData( pDatabase, m_stockSzn, nCurKType, nCurKFormat, nCurMaindataType, FALSE, bReload ); return TRUE; } ////////////////////////////////////////////////////////////////////// // CCW CCW::CCW( ) { SetDefaultParameters( ); } CCW::CCW( CKData * pKData ) : CTechnique( pKData ) { SetDefaultParameters( ); } CCW::~CCW() { Clear( ); } void CCW::SetDefaultParameters( ) { m_dChangeHand = 1.5; } void CCW::AttachParameters( CCW & src ) { m_dChangeHand = src.m_dChangeHand; } BOOL CCW::IsValidParameters( ) { return ( m_dChangeHand > 0 ); } void CCW::Clear( ) { CTechnique::Clear( ); } /*** 根据换手率m_dChangeHand和终止日,计算起始日 */ BOOL CCW::GetRange( int & nStart, int & nEnd, CStockInfo & info ) { if( !m_pKData || m_pKData->GetSize() <= 0 ) return FALSE; if( nEnd < 0 || nEnd >= m_pKData->GetSize() ) nEnd = m_pKData->GetSize()-1; BOOL bIndex = FALSE; double dShareCurrency = 0; if( !info.GetShareCurrency( &dShareCurrency ) || dShareCurrency < 1e+6 ) bIndex = TRUE; if( bIndex ) dShareCurrency = 100 * m_dChangeHand; else dShareCurrency *= m_dChangeHand; double dVol = 0; int k; for( k=nEnd; k>=0; k-- ) { if( bIndex ) dVol += 1; else dVol += m_pKData->ElementAt(k).m_fVolume; if( dVol > dShareCurrency ) break; } nStart = k; if( nStart < 0 ) nStart = 0; return TRUE; } BOOL CCW::GetMinMaxInfo(int nStart, int nEnd, double dMinPrice, double dMaxPrice, double dStep, double *pdMinVolume, double *pdMaxVolume ) { STT_ASSERT_GETMINMAXINFO( m_pKData, nStart, nEnd ); if( dMinPrice >= dMaxPrice || dStep < 1e-4 ) return FALSE; double dMinVolume = 0, dMaxVolume = 0, dVolume = 0; BOOL bFirst = TRUE; for( double dPrice = dMinPrice; dPrice < dMaxPrice; dPrice += dStep ) { if( CalculateCW( &dVolume, nStart, nEnd, dPrice, dStep ) ) { if( bFirst || dVolume < dMinVolume ) dMinVolume = dVolume; if( bFirst || dVolume > dMaxVolume ) dMaxVolume = dVolume; bFirst = FALSE; } } dMinVolume -= fabs(dMinVolume)*0.01; dMaxVolume += fabs(dMaxVolume)*0.01; if( dMaxVolume - dMinVolume < 3 ) dMaxVolume = dMinVolume + 3; if( pdMinVolume ) *pdMinVolume = dMinVolume; if( pdMaxVolume ) *pdMaxVolume = dMaxVolume; return !bFirst; } /*** 筹码分布图,计算价格区间包括dPrice的日线的成交量 */ BOOL CCW::CalculateCW( double *pdVolume, int nStart, int nEnd, double dPrice, double dStep ) { STT_ASSERT_GETMINMAXINFO( m_pKData, nStart, nEnd ); double dVolume = 0; for( int k=nStart; k<=nEnd; k++ ) { KDATA kd = m_pKData->ElementAt(k); if( kd.m_fHigh-kd.m_fLow > 1e-4 && kd.m_fLow < dPrice && kd.m_fHigh > dPrice ) { // 均匀分布 dVolAve double dVolAve = kd.m_fVolume; if( dStep < kd.m_fHigh-kd.m_fLow ) dVolAve = kd.m_fVolume * dStep / (kd.m_fHigh-kd.m_fLow); // 三角分布 double dFactor = min(dPrice-kd.m_fLow, kd.m_fHigh-dPrice); dVolume += dVolAve * dFactor * 4 / (kd.m_fHigh-kd.m_fLow); } } if( pdVolume ) *pdVolume = dVolume; return TRUE; } /*** 筹码分布图计算,计算筹码分布 */ BOOL CCW::CalculateCW( int nStart, int nEnd, CStockInfo & info, double dStep, CSPDWordArray & adwPrice, CSPDWordArray & adwVolume, double * pdMinVolume, double * pdMaxVolume, double * pdTotalVolume, double * pdVolPercent ) { STT_ASSERT_GETMINMAXINFO( m_pKData, nStart, nEnd ); if( dStep < 1e-4 ) return FALSE; float dMinPrice = 0, dMaxPrice = 0; if( !m_pKData->GetMinMaxInfo( nStart, nEnd, &dMinPrice, &dMaxPrice ) ) return FALSE; // Calculate int nMaxCount = (int)((dMaxPrice-dMinPrice)/dStep) + 10; adwPrice.SetSize( 0, nMaxCount ); adwVolume.SetSize( 0, nMaxCount ); double dMinVolume = 0, dMaxVolume = 0, dTotalVolume = 0, dVolume = 0; BOOL bFirst = TRUE; for( double dPrice = dMinPrice; dPrice < dMaxPrice; dPrice += dStep ) { if( CalculateCW( &dVolume, nStart, nEnd, dPrice, dStep ) ) { if( bFirst || dVolume < dMinVolume ) dMinVolume = dVolume; if( bFirst || dVolume > dMaxVolume ) dMaxVolume = dVolume; adwPrice.Add( DWORD(dPrice * 1000) ); adwVolume.Add( DWORD(dVolume) ); dTotalVolume += dVolume; bFirst = FALSE; } } // Return // Min Max dMinVolume -= fabs(dMinVolume)*0.01; dMaxVolume += fabs(dMaxVolume)*0.01; if( dMaxVolume - dMinVolume < 3 ) dMaxVolume = dMinVolume + 3; if( pdMinVolume ) *pdMinVolume = dMinVolume; if( pdMaxVolume ) *pdMaxVolume = dMaxVolume; if( pdTotalVolume ) *pdTotalVolume = dTotalVolume; // VolPercent double dVolPercent = 1.0; double dShareCurrency = 0; if( (!info.GetShareCurrency( &dShareCurrency ) || dShareCurrency < 1e+6) && nEnd-nStart+1 > 0 ) dShareCurrency = dTotalVolume * 100 / (nEnd-nStart+1); if( dShareCurrency > 1e-4 ) dVolPercent = dTotalVolume / (dShareCurrency*m_dChangeHand); if( dVolPercent > 1.0 ) dVolPercent = 1.0; if( dVolPercent < 0.0 ) dVolPercent = 0.0; if( pdVolPercent ) *pdVolPercent = dVolPercent; return adwPrice.GetSize() > 0; } /*** 筹码分布图计算,计算最近nDays天内的筹码分布 */ BOOL CCW::CalculateRecentCW(int nEnd, int nDays, CStockInfo & info, double dStep, CSPDWordArray & adwPrice, CSPDWordArray & adwVolume, double * pdMinVolume, double * pdMaxVolume, double * pdTotalVolume, double * pdVolPercent ) { // Prepare if( !m_pKData || m_pKData->GetSize() <= 0 ) return FALSE; if( nEnd < 0 || nEnd >= m_pKData->GetSize() ) nEnd = m_pKData->GetSize()-1; int nStart = nEnd - nDays + 1; if( nStart < 0 || nStart >= m_pKData->GetSize() ) return FALSE; return CalculateCW( nStart, nEnd, info, dStep, adwPrice, adwVolume, pdMinVolume, pdMaxVolume, pdTotalVolume, pdVolPercent ); } /*** 筹码分布图计算,计算nDays天前内的筹码分布 */ BOOL CCW::CalculatePastCW(int nEnd, int nDays, CStockInfo & info, double dStep, CSPDWordArray & adwPrice, CSPDWordArray & adwVolume, double * pdMinVolume, double * pdMaxVolume, double * pdTotalVolume, double * pdVolPercent ) { // Prepare if( !m_pKData || m_pKData->GetSize() <= 0 ) return FALSE; if( nEnd < 0 || nEnd >= m_pKData->GetSize() ) nEnd = m_pKData->GetSize()-1; int nStart = nEnd - nDays; if( nStart < 0 || nStart >= m_pKData->GetSize() ) return FALSE; nEnd = nStart; if( !GetRange( nStart, nEnd, info ) ) return FALSE; BOOL bOK = CalculateCW( nStart, nEnd, info, dStep, adwPrice, adwVolume, pdMinVolume, pdMaxVolume, pdTotalVolume, pdVolPercent ); // TotalVolumeRecent double dTotalVolumeRecent = 0; for( int k=nEnd+1; k<=nEnd+nDays && k<m_pKData->GetSize(); k ++ ) dTotalVolumeRecent += m_pKData->ElementAt(k).m_fVolume; // VolPercent double dVolPercent = 1.0; double dShareCurrency = 0; if( (!info.GetShareCurrency( &dShareCurrency ) || dShareCurrency < 1e+6) && nDays > 0 ) dShareCurrency = dTotalVolumeRecent * 100 / nDays; if( dShareCurrency > 1e-4 ) dVolPercent = dTotalVolumeRecent / (dShareCurrency*m_dChangeHand); dVolPercent = 1.0 - dVolPercent; if( dVolPercent > 1.0 ) dVolPercent = 1.0; if( dVolPercent < 0.0 ) dVolPercent = 0.0; if( pdVolPercent ) *pdVolPercent = dVolPercent; return bOK; } /*** 筹码分布图统计,获利比例统计 */ BOOL CCW::StatGainPercent( double *pdGainPercent, CSPDWordArray &adwPrice, CSPDWordArray &adwVolume, double dPriceSel ) { double dTotalVolume = 0; double dGainVolume = 0; for( int k=0; k<adwPrice.GetSize() && k<adwVolume.GetSize(); k++ ) { dTotalVolume += adwVolume[k]; if( adwPrice[k] * 0.001 <= dPriceSel ) dGainVolume += adwVolume[k]; } double dGainPercent = 0; if( dTotalVolume > 1e-4 ) dGainPercent = dGainVolume / dTotalVolume; if( pdGainPercent ) *pdGainPercent = dGainPercent; return TRUE; } /*** 筹码分布图统计,平均成本统计 */ BOOL CCW::StatCostAverage( double *pdCostAve, CSPDWordArray &adwPrice, CSPDWordArray &adwVolume ) { double dTotalVolume = 0; double dTotalCost = 0; for( int k=0; k<adwPrice.GetSize() && k<adwVolume.GetSize(); k++ ) { dTotalVolume += adwVolume[k]; dTotalCost += 0.001 * adwPrice[k] * adwVolume[k]; } double dCostAve = 0; if( dTotalVolume > 1e-4 ) dCostAve = dTotalCost / dTotalVolume; if( pdCostAve ) *pdCostAve = dCostAve; return TRUE; } /*** 筹码分布图统计,集中度统计 */ BOOL CCW::StatMass( double *pdLower, double *pdUpper, double *pdMassPrice, CSPDWordArray &adwPrice, CSPDWordArray &adwVolume, double dMassVol ) { if( adwPrice.GetSize() != adwVolume.GetSize() || dMassVol < 0 || dMassVol > 1 ) return FALSE; double dTotalVolume = 0; int k; for( k=0; k<adwPrice.GetSize() && k<adwVolume.GetSize(); k++ ) dTotalVolume += adwVolume[k]; if( dTotalVolume > 1e-4 ) { double dUpperVolume = dTotalVolume * (1-dMassVol) * 0.5; double dLowerVolume = dUpperVolume; int nLower = 0, nUpper = adwPrice.GetSize()-1; for( k=0; k<adwPrice.GetSize(); k++ ) { dLowerVolume -= (double)adwVolume[k]; if( dLowerVolume < 0 ) break; } nLower = k; for( k=adwPrice.GetSize()-1; k>=0; k-- ) { dUpperVolume -= (double)adwVolume[k]; if( dUpperVolume < 0 ) break; } nUpper = k; if( nLower < 0 || nLower > nUpper || nUpper >= adwPrice.GetSize() ) return FALSE; double dLower = 0.001 * adwPrice[nLower]; double dUpper = 0.001 * adwPrice[nUpper]; if( pdLower ) *pdLower = dLower; if( pdUpper ) *pdUpper = dUpper; if( pdMassPrice && adwPrice.GetSize() >= 2 ) { double dPriceRange = 0.001 * ((double)adwPrice[adwPrice.GetSize()-1] - (double)adwPrice[0]); if( dPriceRange > 1e-4 ) *pdMassPrice = (dUpper-dLower)/dPriceRange; if( *pdMassPrice < 0 ) *pdMassPrice = 0; if( *pdMassPrice > 1 ) *pdMassPrice = 1; } } return TRUE; }
[ "osc_zju@163.com" ]
osc_zju@163.com
f8474162b59a101190cb99e78d7b92120e37ee81
81c06d0855b5208a3732c0c22d691b2c372315a0
/week4/164_eyan.cpp
562d830f9e3cdc91f77f497f9905ed6b960c5a8e
[]
no_license
wqs1989/LeetCode
ad1fd5a241b024a529076069be3ee917385dd98e
a3d86147bd0ae7a8be90b49bfab878dbe32315f5
refs/heads/master
2021-01-20T17:37:46.322201
2015-12-08T09:50:58
2015-12-08T09:50:58
47,611,265
2
0
null
2015-12-08T09:14:02
2015-12-08T09:14:02
null
UTF-8
C++
false
false
795
cpp
class Solution { public : int maximumGap(vector<int>& nums) { int n = nums.size(); if( n < 2 ) return 0; int maxE = *max_element(nums.begin(),nums.end()); int minE = *min_element(nums.begin(),nums.end()); int len = maxE - minE; if( len <= 1 ) return len; vector<int> buck_max(n, INT_MIN); vector<int> buck_min(n, INT_MAX); for(int i = 0; i < n; i++) { int index = (double)( nums[i] - minE ) / len * ( n - 1 ); buck_max[index] = max(buck_max[index], nums[i]); buck_min[index] = min(buck_min[index], nums[i]); } int gap = 0, pre = buck_max[0]; for(int i = 1; i < n; i++) { if( buck_max[i] == INT_MIN ) continue; gap = max(gap, buck_min[i] - pre); pre = buck_max[i]; } return gap; } };
[ "yankandda@gmail.com" ]
yankandda@gmail.com
4b6b7f060de3f598d3c3b0628da6152d61827c19
a95b9bcd3fde48e2109d044fe3b29e30b8efd577
/src/pvrec.cpp
d79482a0e67603c345a43b7a491558194a1e9040
[]
no_license
archord/pvrec
d30002eb2e39fcc255b8b637d554fee9b80bead4
2f3cae410b6f80b861e36beb38d500e0f8a2ed73
refs/heads/master
2021-01-11T20:14:14.922018
2017-01-16T02:00:51
2017-01-16T02:00:51
79,073,610
0
0
null
null
null
null
UTF-8
C++
false
false
6,128
cpp
//============================================================================ // Name : pvrec.cpp // Author : Xiaomeng Lu // Version : // Copyright : Your copyright notice // Description : 使用霍夫变换提取位置变化源 //============================================================================ #include <iostream> #include "APVRec.h" #include <sys/time.h> #include <errno.h> using namespace std; using namespace AstroUtil; /* void resolve_line(const char* line, pv_point& pt) { int hh, mm, skyid; double ss; // 格式要求(要求) sscanf(line, "%d %d/%d/%d %d:%d:%d %lf %lf %lf %lf %lf", &pt.fno, &pt.year, &pt.month, &pt.day, &hh, &mm, &ss, &pt.ra, &pt.dec, &pt.x, &pt.y, &pt.mag); pt.secs = hh * 3600 + mm * 60 + ss; } int main(int argc, char** argv) { FILE* fp = fopen(argv[1], "r"); char lnbuff[100]; pv_point pt1, pt2, pt; hough_point hpt; double r, dr; int npt(0); int n; while(!feof(fp)) {// 遍历文件, 解析行数据 if (fgets(lnbuff, 100, fp) == NULL) continue; resolve_line(lnbuff, pt); if (++npt == 1) pt1 = pt; else if (npt == 2) { pt2 = pt; n = pt2.fno - pt1.fno; hpt.line2hough(pt1.x, pt1.y, pt2.x, pt2.y); printf("(%6.1f, %6.1f; %6.1f, %6.1f) ==> (%6.1f, %6.1f), (%7.1f, %5.1f, %7.1f, %7.1f)\n", pt1.x, pt1.y, pt2.x, pt2.y, (pt2.x - pt1.x) / n, (pt2.y - pt1.y) / n, hpt.r, hpt.theta * RtoG, hpt.x, hpt.y); } else { r = pt.x * cos(hpt.theta) + pt.y * sin(hpt.theta); dr = r - hpt.r; pt1 = pt2; pt2 = pt; n = pt2.fno - pt1.fno; hpt.line2hough(pt1.x, pt1.y, pt2.x, pt2.y); printf("(%6.1f, %6.1f; %6.1f, %6.1f) ==> (%6.1f, %6.1f), (%7.1f, %5.1f, %7.1f, %7.1f), (%7.1f, %7.1f)\n", pt1.x, pt1.y, pt2.x, pt2.y, (pt2.x - pt1.x) / n, (pt2.y - pt1.y) / n, hpt.r, hpt.theta * RtoG, hpt.x, hpt.y, r, dr); } } fclose(fp); return 0; } */ ///* void resolve_line(const char* line, pv_point& pt) { int hh, mm, skyid; double ss; // 格式要求(要求) // X Y RA DEC YYYY/MM/DD HH:MM:SS.SSS Mag FrameNo SkyID sscanf(line, "%lf %lf %lf %lf %d/%d/%d %d:%d:%lf %lf %d %d", &pt.x, &pt.y, &pt.ra, &pt.dec, &pt.year, &pt.month, &pt.day, &hh, &mm, &ss, &pt.mag, &pt.fno, &skyid); pt.secs = hh * 3600 + mm * 60 + ss; pt.secs += 5; // 加曝光时间/2修正量, 14 Oct } //void SS2HMS(double seconds, int& hh, int& mm, int& ss, int& microsec) { void SS2HMS(double seconds, int& hh, int& mm, double& ss) { hh = (int) (seconds / 3600); seconds -= (hh * 3600); mm = (int) (seconds / 60); ss = seconds - mm * 60; // seconds -= (mm * 60); // ss = (int) seconds; // microsec = (int) ((seconds - ss) * 1E6); } int main(int argc, char** argv) { // if (argc != 3) { // cout << "Usgae: pvrec <path name of raw file> <directory name of result>" << endl; // return -1; // } char *pathraw = "/home/xy/gwac-data/170108/170108-8-30.txt"; char *dirrslt = "/home/xy/gwac-data/170108"; char pathrslt[200]; int n, i(0); FILE *fpraw; FILE *fprslt; char lnbuff[100]; pv_point pt; APVRec pvrec; // strcpy(pathraw, argv[1]); // strcpy(dirrslt, argv[2]); // n = strlen(dirrslt); // if (dirrslt[n - 1] != '/') { // dirrslt[n] = '/'; // dirrslt[n + 1] = 0; // } if (NULL == (fpraw = fopen(pathraw, "r"))) { cout << "Failed to open RAW file: " << strerror(errno) << endl; return -2; } int frmno(-1), nfrm(0); timeval tv; double t1, t2; gettimeofday(&tv, NULL); t1 = tv.tv_sec + tv.tv_usec * 1E-6; n = 0; pvrec.new_sequence(); while (!feof(fpraw)) {// 遍历文件, 解析行数据 if (fgets(lnbuff, 100, fpraw) == NULL) continue; resolve_line(lnbuff, pt); ++n; if (pt.fno != frmno) { pvrec.end_frame(); pvrec.new_frame(frmno, pt.secs); frmno = pt.fno; ++nfrm; } pvrec.add_point(&pt); } pvrec.end_frame(); pvrec.end_sequence(); gettimeofday(&tv, NULL); t2 = tv.tv_sec + tv.tv_usec * 1E-6; printf("%4d frames have %5d total points. Ellapsed %.3f seconds\n", nfrm, n, t2 - t1); fclose(fpraw); PPVOBJLNK objs = pvrec.get_object(); PPVPTLNK ptptr; PPVPT ppt; int hh, mm; double ss; n = 0; while ((objs = objs->next) != NULL) { ptptr = objs->object.pthead; sprintf(pathrslt, "%s/%04d.txt", dirrslt, ++i); if ((fprslt = fopen(pathrslt, "w")) == NULL) { cout << pathrslt << " : open failed < " << strerror(errno) << " >" << endl; continue; } // printf("object %4d : consists of %3d points\n", i, objs->object.npt); // fprintf(fprslt, "%4s %3s %4s %2s %2s %2s %2s %2s %6s %7s %7s %9s %9s %7s\n", // "f_no", "f_i", "YY", "MM", "DD", "hh", "mm", "ss", "mics", "X", "Y", "R.A.", "DEC.", "Mag"); while ((ptptr = ptptr->next) != NULL) { ++n; ppt = ptptr->pt; SS2HMS(ppt->secs, hh, mm, ss); fprintf(fprslt, "%4d %3d %4d %2d %2d %2d %2d %6.3f %7.2f %7.2f %9.5f %9.5f %7.3f\n", ppt->fno, ppt->fi, ppt->year, ppt->month, ppt->day, hh, mm, ss, ppt->x, ppt->y, ppt->ra, ppt->dec, ppt->mag); } fclose(fprslt); } printf("%4d points are totally correlated. %4d segments are recognized\n", n, i); // cout << n << " points are totally correlated" << endl; cout << "---------- Over ----------" << endl; return 0; } //*/
[ "xyag.902@163.com" ]
xyag.902@163.com
8ec92b774185160f1441a04badaba06d61973fc0
fc27a20bbb5589182a14ac7f60a9a81533c98987
/store.h
3afa4497de6435a14a31b5a7f71717df194d8a41
[]
no_license
ditsara/lru-cache
d181057dcd4dc2ad5fe90f5ba9e6bbd0491927a4
2fe872951aa0f22549cb0a3e12a25d9bc8c2efd5
refs/heads/master
2021-01-11T15:22:02.865161
2017-01-29T12:06:15
2017-01-29T12:06:15
80,341,846
0
0
null
null
null
null
UTF-8
C++
false
false
691
h
#ifndef STORE_H_INCLUDED #define STORE_H_INCLUDED #include <string> #include <unordered_map> #include "elements.h" namespace Cache { typedef std::unordered_map<std::string, Element*> map_t; struct Store { Cache::Element *head; Cache::Element *tail; map_t *lookup; int mem_limit; int size; }; namespace Actions { bool create(Store *store, const std::string &key, const std::string &val); bool store(Store *store, const std::string &key, const std::string &val); bool replace(Store *store, const std::string &key, const std::string &val); std::string* retrieve(const Store &store, const std::string &key); } } #endif // STORE_H_INCLUDED
[ "dan.itsara@gmail.com" ]
dan.itsara@gmail.com
f5ddcafed162bc2dd6b90155e2d03ba5def6a7ea
aca4f00c884e1d0e6b2978512e4e08e52eebd6e9
/2013/MUTC/9/proA.cpp
699930c296403003557d6916814e79ef9545921f
[]
no_license
jki14/competitive-programming
2d28f1ac8c7de62e5e82105ae1eac2b62434e2a4
ba80bee7827521520eb16a2d151fc0c3ca1f7454
refs/heads/master
2023-08-07T19:07:22.894480
2023-07-30T12:18:36
2023-07-30T12:18:36
166,743,930
2
0
null
2021-09-04T09:25:40
2019-01-21T03:40:47
C++
UTF-8
C++
false
false
7,529
cpp
#include<iostream> #include<sstream> #include<cstdio> #include<cstdlib> #include<cstring> #include<cmath> #include<ctime> #include<climits> #include<algorithm> #include<vector> #include<string> #include<queue> #include<list> #include<bitset> #include<set> #include<map> #include<functional> #include<numeric> #include<utility> #include<iomanip> using namespace std; //HEAD_OF_TEMPLATE_BY_JKI14 //TYPEDEF typedef long long lld; typedef double dou; typedef pair<int,int> pii; //COMPARE inline int min(const int &x, const int &y){ return x<y?x:y; } inline lld min(const lld &x, const lld &y){ return x<y?x:y; } inline dou min(const dou &x, const dou &y){ return x<y?x:y; } inline int max(const int &x, const int &y){ return x>y?x:y; } inline lld max(const lld &x, const lld &y){ return x>y?x:y; } inline dou max(const dou &x, const dou &y){ return x>y?x:y; } template<class T> inline void _updmin(T &x,const T &y){ if(x>y)x=y; } template<class T> inline void _updmax(T &x,const T &y){ if(x<y)x=y; } //STL #define _size(x) ((int)(x.size())) #define _mkpr(x,y) make_pair(x,y) //BIT #define _ni(x) (1<<(x)) #define _niL(x) (1LL<<(x)) #define _has(s,x) ((s&(_ni(x)))!=0) #define _hasL(s,x) ((s&(_niL(x)))!=0LL) template<class T> inline T _lowbit(const T &x){ return (x^(x-1))&x; } template<class T> inline int _bitsize(const T &x){ return (x==0)?0:(1+_bitsize(x&(x-1))); } //CONST VALUE const dou _pi=acos(-1.0); const dou _eps=1e-5; //CALCULATE template<class T> inline T _sqr(const T &x){ return x*x; } //NUMBERIC template<class T> inline T _gcd(const T &x,const T &y){ if(x<0)return _gcd(-x,y); if(y<0)return _gcd(x,-y); return (y==0)?x:_gcd(y,x%y); } template<class T> inline T _lcm(const T &x,const T &y){ if(x<0)return _lcm(-x,y); if(y<0)return _lcm(x,-y); return x*(y/_gcd(x,y)); } template<class T> inline T _euc(const T &a,const T &b,T &x,T &y){ /* a*x+b*y == _euc(); */ if(a<0){T d=_euc(-a,b,x,y);x=-x;return d;} if(b<0){T d=_euc(a,-b,x,y);y=-y;return d;} if(b==0){ x=1;y=0;return a; }else{ T d=_euc(b,a%b,x,y);T t=x;x=y;y=t-(a/b)*y; return d; } } template<class T> inline vector<pair<T,int> > _fac(T n){ vector<pair<T,int> > ret;for (T i=2;n>1;){ if (n%i==0){int cnt=0;for (;n%i==0;cnt++,n/=i);ret.push_back(_mkpr(i,cnt));} i++;if (i>n/i) i=n; } if (n>1) ret.push_back(_mkpr(n,1));return ret; } template<class T> inline int _prm(const T &x){ if(x<=1)return 0; for(T i=2;sqr(i)<=x;i++)if(x%i==0)return 0; return 1; } template<class T> inline T _phi(T x){ /* EularFunction:return the number of integers which are the relatively prime number of x and less than x. */ vector<pair<T,int> > f=_fac(x);T ret=x; for(int i=0;i<_size(f);i++)ret=ret/f[i].first*(f[i].first-1); return ret; } template<class T> inline T _inv(T a,T b){ /* if(k%a==0) (k/a)%b==((k%b)*(_inv()%b))%b */ /* original code begin T x0=1,y0=0,x1=0,y1=1; for(T r=a%b;r!=0;r=a%b){ T k=a/b,dx=x0-k*x1,dy=y0-k*y1;x0=x1;y0=y1;x1=dx;y1=dy;a=b;b=r; } if(x1==0)x1=1;return x1; original code end */ T x,y;_euc(a,b,x,y); if(x==0)x=1;return x; } template<class T> inline T _cmod(T x,T m){ return (x%m+m)%m; } template<class T> inline T _amod(T x,T y,T m){ return x=((x+y)%m+m)%m; } template<class T> inline T _mmod(T x,T y,T m){ return (T)((((lld)x)*((lld)y)%((lld)m)+((lld)m))%((lld)m)); } template<class T> inline T _pmod(T x,T y,T m){ if(y==0)return 1%m;else if((y&1)==0){ T z=_pmod(x,y>>1,m);return _mmod(z,z,m); }else return _mmod(_pmod(x,y^1,m),x,m); } #define _cmd(x) _cmod(x,mod) #define _amd(x,y) _amod(x,y,mod) #define _mmd(x,y) _mmod(x,y,mod) #define _pmd(x,y) _pmod(x,y,mod) //MATRIX OPERATIONS const int _MTRXSIZE = 40; template<class T> inline void _shwMTRX(int n,T A[_MTRXSIZE][_MTRXSIZE]){ for(int i=0;i<n;i++){ for(int j=0;j<n;j++)cout<<A[i][j]<<" ";cout<<endl; } } template<class T> inline void _stdMTRX(int n,T A[_MTRXSIZE][_MTRXSIZE]){ for(int i=0;i<n;i++)for(int j=0;j<n;j++) A[i][j]=(i==j)?1:0; } template<class T> inline void _addMTRX(int n,T C[_MTRXSIZE][_MTRXSIZE],T A[_MTRXSIZE][_MTRXSIZE],T B[_MTRXSIZE][_MTRXSIZE]){ for(int i=0;i<n;i++)for(int j=0;j<n;j++) C[i][j]=A[i][j]+B[i][j]; } template<class T> inline void _subMTRX(int n,T C[_MTRXSIZE][_MTRXSIZE],T A[_MTRXSIZE][_MTRXSIZE],T B[_MTRXSIZE][_MTRXSIZE]){ for(int i=0;i<n;i++)for(int j=0;j<n;j++) C[i][j]=A[i][j]-B[i][j]; } template<class T> inline void _mulMTRX(int n,T C[_MTRXSIZE][_MTRXSIZE],T _A[_MTRXSIZE][_MTRXSIZE],T _B[_MTRXSIZE][_MTRXSIZE]){ T A[_MTRXSIZE][_MTRXSIZE],B[_MTRXSIZE][_MTRXSIZE]; for(int i=0;i<n;i++)for(int j=0;j<n;j++){ A[i][j]=_A[i][j];B[i][j]=_B[i][j];C[i][j]=0; } for(int i=0;i<n;i++)for(int j=0;j<n;j++)for(int k=0;k<n;k++)C[i][j]+=A[i][k]*B[k][j]; } template<class T> inline void _addModMTRX(int n,T m,T C[_MTRXSIZE][_MTRXSIZE],T A[_MTRXSIZE][_MTRXSIZE],T B[_MTRXSIZE][_MTRXSIZE]){ for(int i=0;i<n;i++)for(int j=0;j<n;j++) C[i][j]=_cmod(A[i][j]+B[i][j],m); } template<class T> inline void _subModMTRX(int n,T m,T C[_MTRXSIZE][_MTRXSIZE],T A[_MTRXSIZE][_MTRXSIZE],T B[_MTRXSIZE][_MTRXSIZE]){ for(int i=0;i<n;i++)for(int j=0;j<n;j++) C[i][j]=_cmod(A[i][j]-B[i][j],m); } template<class T> inline void _mulModMTRX(int n,T m,T C[_MTRXSIZE][_MTRXSIZE],T _A[_MTRXSIZE][_MTRXSIZE],T _B[_MTRXSIZE][_MTRXSIZE]){ T A[_MTRXSIZE][_MTRXSIZE],B[_MTRXSIZE][_MTRXSIZE]; for(int i=0;i<n;i++)for(int j=0;j<n;j++){ A[i][j]=_A[i][j];B[i][j]=_B[i][j];C[i][j]=0; } for(int i=0;i<n;i++)for(int j=0;j<n;j++)for(int k=0;k<n;k++)C[i][j]=(C[i][j]+_mmod(A[i][k],B[k][j],m))%m; } template<class T> inline void _powModMTRX(int n,T y,T m,T C[_MTRXSIZE][_MTRXSIZE],T X[_MTRXSIZE][_MTRXSIZE]){ T R[_MTRXSIZE][_MTRXSIZE];for(int i=0;i<n;i++)for(int j=0;j<n;j++)R[i][j]=X[i][j];_stdMTRX(n,C); if(y>0)for(T i=1;;i<<=1){ if(y&i)_mulModMTRX(n,m,C,C,R); _mulModMTRX(n,m,R,R,R); if(i>(y>>1))break; } } //FRACTION template<class T> struct _frct{T a,b;_frct(T a=0,T b=1);string toString();}; template<class T> _frct<T>::_frct(T a,T b){T d=_gcd(a,b);a/=d;b/=d;if (b<0) a=-a,b=-b;this->a=a;this->b=b;} template<class T> string _frct<T>::toString(){ostringstream tout;tout<<a<<"/"<<b;return tout.str();} template<class T> _frct<T> operator+(_frct<T> p,_frct<T> q){return _frct<T>(p.a*q.b+q.a*p.b,p.b*q.b);} template<class T> _frct<T> operator-(_frct<T> p,_frct<T> q){return _frct<T>(p.a*q.b-q.a*p.b,p.b*q.b);} template<class T> _frct<T> operator*(_frct<T> p,_frct<T> q){return _frct<T>(p.a*q.a,p.b*q.b);} template<class T> _frct<T> operator/(_frct<T> p,_frct<T> q){return _frct<T>(p.a*q.b,p.b*q.a);} //TAIL_OF_TEMPLATE_BY_JKI14 const lld mod=1000000007LL; lld n,a0,ax,ay,b0,bx,by; lld a[_MTRXSIZE][_MTRXSIZE],b[_MTRXSIZE][_MTRXSIZE]; int main(){ ios::sync_with_stdio(false); while(cin>>n){n--; cin>>a0>>ax>>ay>>b0>>bx>>by; if(n<0LL){ cout<<"0"<<endl;continue; } b[0][0]=ax*bx%mod;b[0][1]=0LL;b[0][2]=0LL;b[0][3]=0LL;b[0][4]=1LL; b[1][0]=ax*by%mod;b[1][1]=ax ;b[1][2]=0LL;b[1][3]=0LL;b[1][4]=0LL; b[2][0]=ay*bx%mod;b[2][1]=0LL;b[2][2]=bx ;b[2][3]=0LL;b[2][4]=0LL; b[3][0]=ay*by%mod;b[3][1]=ay ;b[3][2]=by ;b[3][3]=1LL;b[3][4]=0LL; b[4][0]=0LL ;b[4][1]=0LL;b[4][2]=0LL;b[4][3]=0LL;b[4][4]=1LL; for(int i=0;i<5;i++)for(int j=0;j<5;j++)a[i][j]=0LL; a[0][0]=a0*b0%mod;a[0][1]=a0 ;a[0][2]=b0 ;a[0][3]=1LL;a[0][4]=0LL; _powModMTRX(5,n,mod,b,b); _mulModMTRX(5,mod,a,a,b); cout<<_cmd(a[0][0]+a[0][4])<<endl; } return 0; }
[ "jki14wz@gmail.com" ]
jki14wz@gmail.com
43ad131059ed53ff575a894fea4b602c51627c37
ad6304b713fab3ca8ff018aad2df0d057e194300
/URI/AD-HOC/2322 - Peça Perdida.cpp
cbdaf7f970d2dfbfd2bb2da3ef208e071e9bbfd4
[]
no_license
nicowxd/Competitive-Programming
d3f63b6eac4ccd508d194c8e6244f3d18bdca518
de92532f753f6eeebe5dff18da8b10f3186bf107
refs/heads/master
2022-01-11T20:07:34.149034
2019-06-06T23:40:15
2019-06-06T23:40:15
115,149,544
1
0
null
null
null
null
UTF-8
C++
false
false
509
cpp
// Autor: CarlosJunior<carloserratojr@gmail.com> // Nome: Peça Perdida // Nível: 5 // Categoria: AD-HOC // URL: https://www.urionlinejudge.com.br/judge/pt/problems/view/2322 #include <bits/stdc++.h> using namespace std; int main() { int n; scanf("%d", &n); set<int> p; set<int>::iterator it; for (int i = 1; i <= n; i++) p.insert(i); int x; for (int i = 0; i < n-1; i++) { scanf("%d", &x); p.erase(x); } it = p.begin(); cout << (*it) << endl; return 0; }
[ "carlos.serrato@itec.ufpa.br" ]
carlos.serrato@itec.ufpa.br
38ea744bff4f2052d90951fe444952656f2787ab
0ba2e5061577f6286ff9265ef1df9aca96769445
/data_structures/Graphs/Minimum-Spanning-Tree/TRYTOBE8TME_mst.cpp
812ec81956478ee88bfc4453d88fc1a05910233f
[ "CC0-1.0" ]
permissive
ZoranPandovski/al-go-rithms
68d5d02f80a61de9baf8e50a81a52e7d0b3983a0
4ae6ba54e90af14af236e03e435eb0402dcac787
refs/heads/master
2023-09-04T16:04:04.321676
2023-06-06T15:22:16
2023-06-06T15:22:16
93,438,176
1,421
2,445
CC0-1.0
2023-06-15T14:24:28
2017-06-05T19:20:20
Jupyter Notebook
UTF-8
C++
false
false
701
cpp
#include<bits/stdc++.h> using namespace std; #define ll long long int #define pb push_back #define mp make_pair #define ff first #define ss second #define FIO ios::sync_with_stdio(0); int main() { FIO; ll i,c=0,n,m,x,y,z; cin>>n>>m; vector<pair<ll,ll>> a[100001]; vector<ll> vis(100001,0); priority_queue<pair<ll,ll>,vector<pair<ll,ll>>,greater<pair<ll,ll>>> q; pair<ll,ll> p; for(i=0;i<m;i++) { cin>>x>>y>>z; a[x].pb(mp(z,y)); a[y].pb(mp(z,x)); } q.push(mp(0,1)); while(!q.empty()) { p=q.top(); q.pop(); x=p.ss; if(vis[x]==1) continue; vis[x]=1; c+=p.ff; for(i=0;i<a[x].size();i++) { if(vis[a[x][i].ss]==0) q.push(a[x][i]); } } cout<<c; return 0; }
[ "kapandya@redhat.com" ]
kapandya@redhat.com
128f3366ef6ca63413be8e6b1552f40417c8f347
df804edeee2cfbb842d106fbe1b691ecce704eab
/Bus Reservation System/Bus Reservation System.cpp
bf5a66f0d1387a918f5201427fd7d6c81c69772b
[]
no_license
nipunm1/Bus-Reservation-System
73645176601fb012e6f6bc37663fd6ed77b8946d
70ff72731debd1dfc6b441b4e80d74d13555a93f
refs/heads/master
2022-10-08T18:22:56.208823
2020-06-12T12:32:57
2020-06-12T12:32:57
271,793,622
0
0
null
null
null
null
UTF-8
C++
false
false
4,330
cpp
#include <iostream> #include <string.h> using namespace std; static int p=0; class bus{ char bus_no[10], driver_name[30], arrival_time[10], depart_time[10], from[20], to[20], seat[8][4][10]; public: void install(); void available(); void allotment(); void vacant(); void show(); void position(int l); }; bus b[10]; void bus::install(){ cout<<"Enter Bus Number \n"; cin>>b[p].bus_no; cout<<"Enter Drivers Name \n"; cin>>b[p].driver_name; cout << "From \n"; cin >> b[p].from; cout << "To \n"; cin >> b[p].to; cout<<"Enter Arrival Time \n"; cin>>b[p].arrival_time; cout<<"Enter Departure Time \n"; cin>>b[p].depart_time; b[p].vacant(); p++; } void bus::available() { int i; for(i=0;i<p;i++) { printf("---------------------------------------------------------------------------\n"); cout<<"Bus number : "<<b[i].bus_no<<" Driver Name : "<<b[i].driver_name<<" From : "<<b[i].from<<" To : "<<b[i].to<<" Arrival Time : "<<b[i].arrival_time<<" Departure Time : "<<b[i].depart_time<<endl; printf("---------------------------------------------------------------------------\n"); } } void bus::allotment(){ int seat,i; char num[10]; cout<<"Enter Bus Number : "; cin>>num; for(i=0;i<=p;i++){ if(strcmp(b[i].bus_no, num)==0){ break; } } if(i<=p){ cout<<"Enter Seat Number : "; cin>>seat; if(seat>32){ cout<<"There is only 32 seats in this bus.\n"; } else{ if(strcmp(b[i].seat[seat/4][(seat%4)-1],"Vacant")==0){ cout<<"Enter Passengers Name : "; cin>>b[i].seat[seat/4][(seat%4)-1]; } else{ cout<<"This seat is already reserved \n"; } } } if(i>p){ cout<<"Enter correct bus number \n"; } } void bus::show(){ int n,a=1,i,j; char number[10]; cout<<"Enter Bus Number \n"; cin>>number; for(n=0;n<=p;n++){ if(strcmp(b[n].bus_no, number)==0){ break; } } while(n<=p){ cout << "Bus number : " << b[n].bus_no << " Driver Name : " << b[n].driver_name << " From : " << b[n].from << " To : " << b[n].to <<endl; b[n].position(n); for(i=0;i<8;i++){ for(j=0;j<4;j++){ a++; if(strcmp(b[n].seat[i][j],"Vacant")!=0) { cout<< "The seat number "<<(a - 1)<<" is reserved \n"; } } } break; } if(n>p){ cout<<"Enter correct Bus number \n"; } } void bus::position(int l){ int seats=0, vac_seats=0; int i, j; for(i=0;i<8;i++){ for(j=0;j<4;j++){ seats++; if(strcmp(b[l].seat[i][j],"Vacant")==0){ cout<<seats<<"."<< b[l].seat[i][j]<<"\t"; vac_seats++; } else { cout<<seats<<"."<<b[l].seat[i][j]<<"\t"; } } } cout<<endl<<"There are "<<vac_seats<<" seats are empty in Bus no: "<<b[l].bus_no<<endl; } void bus::vacant(){ int i,j; for(i = 0; i < 8; i++){ for (j = 0; j < 4; j++){ strcpy_s(b[p].seat[i][j], "Vacant"); } } } int main(){ system("cls"); int choice; do { cout<<"********************************************************************* \n"; cout<<"1. For Install New Bus Details \n"; cout<<"2. Buses Available \n"; cout<<"3. Show seats \n"; cout<<"4. For Seat Reservation \n"; cout<<"5. For Exit \n"; cout<<"Enter your choice : "; cin>>choice; cout<<"********************************************************************* \n"; switch(choice){ case 1:b[p].install();break; case 2:b[p].available();break; case 3:b[p].show(); break; case 4:b[p].allotment(); break; case 5: exit(1); default:cout<<"Invalid choice \n"; } } while (choice!=5); system("pause"); return 0; }
[ "noreply@github.com" ]
noreply@github.com
6a88dbb18089d07d1dcb82c12ef11d35b65539d4
c8b64ec67fd12fbbdb033f309c10eb37c6d88ac7
/src/lib/display3d/Texture.cpp
d11200f1d181e575966c69da717e13d43fa24c2e
[ "MIT" ]
permissive
Ibujah/minimalOpenGL
14de476893aaf3e091b246a387bf5e402193f731
474e5fc96afda899108dcfee446c16b56427e067
refs/heads/master
2022-09-20T20:13:56.785247
2020-06-02T11:29:01
2020-06-02T11:29:01
268,627,543
0
0
null
null
null
null
UTF-8
C++
false
false
1,841
cpp
#include <GL/glew.h> #include "Texture.h" #include <iostream> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> Texture::Texture(const std::string& imageFile) : m_id(0), m_imageFile(imageFile), m_width(0), m_height(0), m_format(0), m_internalFormat(0) { if(!m_imageFile.empty()) if(!load()) throw std::logic_error("Texture could not be loaded correctly"); } Texture::Texture(const Texture& tex) : Texture(tex.m_imageFile) {} Texture::~Texture() { glDeleteTextures(1, &m_id); m_id = 0; } const Texture& Texture::operator=(const Texture& tex) { if(m_id != 0) glDeleteTextures(1, &m_id); m_id = 0; m_imageFile = tex.m_imageFile; m_width = 0; m_height = 0; m_format = 0; m_internalFormat = 0; if(!m_imageFile.empty()) if(!load()) throw std::logic_error("Texture could not be loaded correctly"); return *this; } void Texture::setImageFile(const std::string& imageFile) { m_imageFile = imageFile; load(); } GLuint Texture::getID() const { return m_id; } bool Texture::load() { if(m_id != 0) glDeleteTextures(1, &m_id); cv::Mat img = cv::imread(m_imageFile.c_str(),cv::IMREAD_COLOR); if(!img.data) { std::cout << "Could not open or find the image" << std::endl ; return false; } glGenTextures(1, &m_id); glBindTexture(GL_TEXTURE_2D, m_id); GLenum internalFormat(GL_RGB); GLenum format(GL_BGR); glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, img.cols, img.rows, 0, format, GL_UNSIGNED_BYTE, img.data); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glGenerateMipmap(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, 0); return true; }
[ "dbastien71@gmail.com" ]
dbastien71@gmail.com
ed76b4a9aec441b499f7b1429052a600fb038cd4
615f6b2370ee24d85bf2e47b0beecd0ff852aab0
/arduino/IoTkit/IoTkit.cpp
e900a7af6549bb040fdad11101a2710b78046304
[ "BSD-3-Clause" ]
permissive
hnischith/iotkit-samples
015c06a376a98ad70df2ea9b3643f18687b9541d
1f575bcf0e5c32456efebf9fbe4e43ebfa199548
refs/heads/master
2021-01-22T12:21:19.668688
2014-02-28T14:31:54
2014-02-28T14:31:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,249
cpp
/* Copyright (c) 2013, Intel Corporation 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 Intel 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 THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <IoTkit.h> #include <EthernetUdp.h> IoTkit::IoTkit() { _udp = new EthernetUDP(); _ip = IPAddress(127, 0, 0, 1); } int IoTkit::setDateTimeUtc(int year, int month, int day, int hour, int minute, int second) { char buffer[128]; snprintf(buffer, 1024, "date %d.%d.%d-%d:%d:%d", year, month, day, hour, minute, second); system(buffer); } void IoTkit::begin(unsigned int localport) { _udp->begin(localport); } // A (very) partial JSON encoder. if this becomes any more complex, // consider a JSON library such as https://github.com/interactive-matter/aJson int IoTkit::registerMetric(const char* metric, const char* type, const char * uom) { _udp->beginPacket(_ip, 41234); _udp->write("{\"s\":\""); _udp->write(metric); _udp->write("\",\"t\":\""); _udp->write(type); _udp->write("\",\"u\":\""); _udp->write(uom); _udp->write("\"}"); _udp->endPacket(); } int IoTkit::send(const char* metric, int value) { char buffer[128]; int len = snprintf(buffer, 128, "%d", value); psend(metric, buffer); } int IoTkit::send(const char* metric, double value) { char buffer[128]; int len = snprintf(buffer, 128, "%f", value); psend(metric, buffer); } int IoTkit::send(const char* metric, const char * value) { psend(metric, value, 1); } int IoTkit::psend(const char* metric, const char * value, bool emitQuotes) { // since the value could be any length, don't use the buffer. // Instead use udp.write to write the value. _udp->beginPacket(_ip, 41234); _udp->write("{\"s\":\""); _udp->write(metric); _udp->write("\",\"v\":"); if (emitQuotes) _udp->write('"'); _udp->write(value); if (emitQuotes) _udp->write('"'); _udp->write("}"); _udp->endPacket(); }
[ "patrick.j.holmes@gmail.com" ]
patrick.j.holmes@gmail.com
4b8bfee76dfb0cffdec6eec6493883519cf51679
b121fd1b8e8025b3d70b567a6cb1d9eab27544da
/src/bloom.h
6411d970964aeb0cb87e904b125364706199123f
[ "MIT" ]
permissive
szenekonzept/ethan
e304ceecb4288b08c43f9e3a51d3021859252f1a
ee16a7dcf93cee28d76c7a046b4b0abee0e373ba
refs/heads/master
2021-01-18T10:34:04.438996
2014-08-01T19:00:16
2014-08-01T19:00:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,425
h
// Copyright (c) 2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef ETHAN_BLOOM_H #define ETHAN_BLOOM_H #include <vector> #include "uint256.h" #include "serialize.h" class COutPoint; class CTransaction; // 20,000 items with fp rate < 0.1% or 10,000 items and <0.0001% static const unsigned int MAX_BLOOM_FILTER_SIZE = 36000; // bytes static const unsigned int MAX_HASH_FUNCS = 50; // First two bits of nFlags control how much IsRelevantAndUpdate actually updates // The remaining bits are reserved enum bloomflags { BLOOM_UPDATE_NONE = 0, BLOOM_UPDATE_ALL = 1, // Only adds outpoints to the filter if the output is a pay-to-pubkey/pay-to-multisig script BLOOM_UPDATE_P2PUBKEY_ONLY = 2, BLOOM_UPDATE_MASK = 3, }; /** * BloomFilter is a probabilistic filter which SPV clients provide * so that we can filter the transactions we sends them. * * This allows for significantly more efficient transaction and block downloads. * * Because bloom filters are probabilistic, an SPV node can increase the false- * positive rate, making us send them transactions which aren't actually theirs, * allowing clients to trade more bandwidth for more privacy by obfuscating which * keys are owned by them. */ class CBloomFilter { private: std::vector<unsigned char> vData; bool isFull; bool isEmpty; unsigned int nHashFuncs; unsigned int nTweak; unsigned char nFlags; unsigned int Hash(unsigned int nHashNum, const std::vector<unsigned char>& vDataToHash) const; public: // Creates a new bloom filter which will provide the given fp rate when filled with the given number of elements // Note that if the given parameters will result in a filter outside the bounds of the protocol limits, // the filter created will be as close to the given parameters as possible within the protocol limits. // This will apply if nFPRate is very low or nElements is unreasonably high. // nTweak is a constant which is added to the seed value passed to the hash function // It should generally always be a random value (and is largely only exposed for unit testing) // nFlags should be one of the BLOOM_UPDATE_* enums (not _MASK) CBloomFilter(unsigned int nElements, double nFPRate, unsigned int nTweak, unsigned char nFlagsIn); CBloomFilter() : isFull(true) {} IMPLEMENT_SERIALIZE ( READWRITE(vData); READWRITE(nHashFuncs); READWRITE(nTweak); READWRITE(nFlags); ) void insert(const std::vector<unsigned char>& vKey); void insert(const COutPoint& outpoint); void insert(const uint256& hash); bool contains(const std::vector<unsigned char>& vKey) const; bool contains(const COutPoint& outpoint) const; bool contains(const uint256& hash) const; // True if the size is <= MAX_BLOOM_FILTER_SIZE and the number of hash functions is <= MAX_HASH_FUNCS // (catch a filter which was just deserialized which was too big) bool IsWithinSizeConstraints() const; // Also adds any outputs which match the filter to the filter (to match their spending txes) bool IsRelevantAndUpdate(const CTransaction& tx, const uint256& hash); // Checks for empty and full filters to avoid wasting cpu void UpdateEmptyFull(); }; #endif /* ETHAN_BLOOM_H */
[ "ethancoin@mail.com" ]
ethancoin@mail.com
0eaa97d52290fd3860e0b922a22372a675f9ee36
786de89be635eb21295070a6a3452f3a7fe6712c
/MsgLogger/tags/V00-01-09/include/MsgLogRecord.h
af15d4eda548066d69e2c5750d0bb1eff9868bae
[]
no_license
connectthefuture/psdmrepo
85267cfe8d54564f99e17035efe931077c8f7a37
f32870a987a7493e7bf0f0a5c1712a5a030ef199
refs/heads/master
2021-01-13T03:26:35.494026
2015-09-03T22:22:11
2015-09-03T22:22:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,186
h
#ifndef MSGLOGRECORD_HH #define MSGLOGRECORD_HH //-------------------------------------------------------------------------- // File and Version Information: // $Id$ // // Description: // Class MsgLogRecord. // // Environment: // This software was developed for the BaBar collaboration. If you // use all or part of it, please give an appropriate acknowledgement. // // Author List: // Andy Salnikov // // Copyright Information: // Copyright (C) 2005 SLAC // //------------------------------------------------------------------------ //------------- // C Headers -- //------------- extern "C" { } //--------------- // C++ Headers -- //--------------- #include <iostream> #include <string> //---------------------- // Base Class Headers -- //---------------------- //------------------------------- // Collaborating Class Headers -- //------------------------------- #include "MsgLogger/MsgLogger.h" //------------------------------------ // Collaborating Class Declarations -- //------------------------------------ // --------------------- // -- Class Interface -- // --------------------- namespace MsgLogger { class MsgLoggerImpl ; /** * @ingroup MsgLogger * * Class which defines a single logging message (record.) It has such attributes * as message itself, logging level, corresponding logger name, file/line where * the message originated. For performance optimization purposes the message is * passed as a pointer to the streambuf. This complicates things a bit, you have * to be careful when extracting message test from the streambuf, but avoids * copying of the strings. Also for optimization reasons the timestamp is not a part * of the message, but is added to the formatted message only during formatting * (only if needed.) * * This software was developed for the BaBar collaboration. If you * use all or part of it, please give an appropriate acknowledgement. * * Copyright (C) 2005 SLAC * * @see MsgLogRecordMsgLogRecord * * @version $Id$ * * @author Andy Salnikov */ class MsgLogRecord { public: // Construct root logger MsgLogRecord( const std::string& logger, MsgLogLevel level, const char* fileName, int linenum, std::streambuf* msgbuf ) : _logger(logger), _level(level), _fileName(fileName), _lineNum(linenum), _msgbuf(msgbuf) {} // Destructor ~MsgLogRecord() {} /// get logger name const std::string& logger() const { return _logger ; } /// get message log level MsgLogLevel level() const { return _level ; } /// get message location const char* fileName() const { return _fileName ; } int lineNum() const { return _lineNum ; } /// get the stream for the specified log level std::streambuf* msgbuf() const { return _msgbuf ; } protected: // Helper functions private: // Friends // Data members const std::string& _logger ; const MsgLogLevel _level ; const char* _fileName ; int _lineNum ; std::streambuf* _msgbuf ; MsgLogRecord( const MsgLogRecord& ); MsgLogRecord& operator= ( const MsgLogRecord& ); }; } // namespace MsgLogger #endif // MSGLOGRECORD_HH
[ "dubrovin@SLAC.STANFORD.EDU@b967ad99-d558-0410-b138-e0f6c56caec7" ]
dubrovin@SLAC.STANFORD.EDU@b967ad99-d558-0410-b138-e0f6c56caec7
76f66806f9d0d0ab432fb074d9fe21dad2ccdad7
20b2af5e275469261d95d4441303d567b5c03bba
/src/tuhhsdk/Data/CycleInfo.hpp
679c5278d3f0e48a7559c2cacaadd2649de60c95
[ "BSD-2-Clause" ]
permissive
humanoid-robotics-htl-leonding/robo-ducks-core
efd513dedf58377dadc6a3094dd5c01f13c32eb1
1644b8180214b95ad9ce8fa97318a51748b5fe3f
refs/heads/master
2022-04-26T17:19:00.073468
2020-04-23T07:05:25
2020-04-23T07:05:25
181,146,731
7
0
NOASSERTION
2022-04-08T13:25:14
2019-04-13T09:07:29
C++
UTF-8
C++
false
false
1,171
hpp
#pragma once #include "Framework/DataType.hpp" #include "Tools/Time.hpp" class CycleInfo : public DataType<CycleInfo> { public: /// the name of this DataType DataTypeName name = "CycleInfo"; /** * @brief getTimeDiff calculates the time difference from this cycle to some other time point * @param rhs the other time point * @param type the unit in which the time difference should be returned * @return the elapsed time in the requested unit */ float getTimeDiff(const TimePoint rhs, const TDT type = TDT::SECS) const { return ::getTimeDiff(startTime, rhs, type); } /// the time when the cycle started TimePoint startTime; /// the duration of a cycle [s] float cycleTime; /// whether the content is valid bool valid = false; /** * @brief reset does nothing */ void reset() { valid = false; } virtual void toValue(Uni::Value& value) const { value = Uni::Value(Uni::ValueType::OBJECT); value["startTime"] << startTime; value["cycleTime"] << cycleTime; } virtual void fromValue(const Uni::Value& value) { value["startTime"] >> startTime; value["cycleTime"] >> cycleTime; } };
[ "rene.kost.951@gmail.com" ]
rene.kost.951@gmail.com
be2d9b90d38c7f30ad95151e4ce6c24aeb80e531
82881e9012ea9034b36443c1e794fd7fec54484a
/plane.h
a19bf22119c47a047aafd6d44d0bbd1dff77d784
[]
no_license
henu/hpp
2e8397dfbeaec1625d5ebb4440eaa35786b3d510
744a7eb15013b85b2e3e984b3de8511fc0a032d1
refs/heads/master
2021-01-18T22:34:25.965603
2017-10-19T19:16:44
2017-10-19T19:16:44
37,479,054
0
0
null
null
null
null
UTF-8
C++
false
false
5,568
h
#ifndef HPP_PLANE_H #define HPP_PLANE_H #include "vector3.h" #include "ray.h" #include <vector> #include <string> namespace Hpp { class Plane { public: typedef std::vector< Plane > Vec; inline Plane(void); inline Plane(Vector3 const& normal, Real distance_from_origin); inline Plane(Vector3 const& normal, Vector3 const& pos_at_plane); inline Plane(Vector3 const& v0, Vector3 const& v1, Vector3 const& v2); inline Vector3 getNormal(void) const { return normal; } inline Vector3 getPosition(void) const { return normal * distance_from_origin; } inline void swapNormal(void); // "result_dir_mult" tells how many times dir // must be added to begin so hitpos is reached. inline bool hitsLine(Vector3 const& begin, Vector3 const& dir, Vector3* result_hitpos = NULL, Real* result_dir_mult = NULL) const; // "result_dir_mult" tells how many times dir // must be added to begin so hitpos is reached. inline bool hitsRay(Ray const& ray, Vector3* result_hitpos = NULL, Real* result_dir_mult = NULL) const; // In case of hit, result_hitline_dir will be normalized inline bool hitsPlane(Plane const& plane2, Vector3* result_hitline_pos = NULL, Vector3* result_hitline_dir = NULL) const; inline bool isPositionAtFront(Vector3 const& pos) const; inline Vector3 posToPlane(Vector3 const& pos) const; inline Vector3 posToPlane(Vector3 const& pos, Vector3 const& moving_dir) const; // Gives negative result if position is at back of the Plane inline Real distanceToPosition(Vector3 const& pos) const; inline std::string toString(void) const; private: Vector3 normal; // Normalized always, except when not initialized Real distance_from_origin; // Normal must be normalized when this is called inline void calculateDistanceToOrigin(Vector3 const& pos_at_plane); }; inline Plane::Plane(void) { } inline Plane::Plane(Vector3 const& normal, Real distance_from_origin) : normal(normal), distance_from_origin(distance_from_origin) { HppAssert(normal.length() > 0, "Unable to form Plane from given normal!"); this->normal.normalize(); } inline Plane::Plane(Vector3 const& v0, Vector3 const& v1, Vector3 const& v2) { // Calculate normal Vector3 edge0 = v1 - v0; Vector3 edge1 = v2 - v0; normal = crossProduct(edge0, edge1); HppAssert(normal.length() > 0, "Unable to form Plane from given triangle!"); normal.normalize(); calculateDistanceToOrigin(v0); } inline Plane::Plane(Vector3 const& normal, Vector3 const& pos_at_plane) : normal(normal) { HppAssert(normal.length() > 0, "Unable to form Plane from given normal!"); this->normal.normalize(); calculateDistanceToOrigin(pos_at_plane); } inline void Plane::swapNormal(void) { normal = -normal; distance_from_origin = -distance_from_origin; } inline bool Plane::hitsLine(Vector3 const& begin, Vector3 const& dir, Vector3* result_hitpos, Real* result_dir_mult) const { // If direction and plane normal are perpendicular // to each others, then hit cannot occure. Real dir_len = dir.length(); Real dp_n_d = dotProduct(normal, dir); if (dir_len < 0.00001) { return false; } Real radians = static_cast< Real >(::asin(dp_n_d / dir_len)); if (::finite(radians) && fabs(radians) < 0.0002) { return false; } Vector3 pos_at_plane = getPosition(); Real dir_m = (dotProduct(normal, pos_at_plane) - dotProduct(normal, begin)) / dp_n_d; if (result_hitpos) { *result_hitpos = begin + dir * dir_m; } if (result_dir_mult) { *result_dir_mult = dir_m; } return true; } bool Plane::hitsRay(Ray const& ray, Vector3* result_hitpos, Real* result_dir_mult) const { Hpp::Real result_dir_mult2; bool hits_line = hitsLine(ray.begin, ray.dir, result_hitpos, &result_dir_mult2); // If it does not hit plane if (!hits_line) return false; if (result_dir_mult2 < 0) return false; // If it hits if (result_dir_mult) *result_dir_mult = result_dir_mult2; return true; } inline bool Plane::hitsPlane(Plane const& plane2, Vector3* result_hitline_pos, Vector3* result_hitline_dir) const { Vector3 hitline_dir = crossProduct(normal, plane2.normal); Real hitline_dir_len = hitline_dir.length(); // If cutplanes would hit only at far // away, then do not consider as hit. if (hitline_dir_len < 0.00001) { return false; } hitline_dir /= hitline_dir_len; if (result_hitline_pos) { Vector3 finder = crossProduct(plane2.normal, hitline_dir); *result_hitline_pos = posToPlane(plane2.getPosition(), finder); } if (result_hitline_dir) { *result_hitline_dir = hitline_dir; } return true; } inline bool Plane::isPositionAtFront(Vector3 const& pos) const { Vector3 pos_relative_to_plane = pos - getPosition(); return dotProduct(pos_relative_to_plane, normal) > 0; } inline Vector3 Plane::posToPlane(Vector3 const& pos) const { return posToPlane(pos, normal); } inline Vector3 Plane::posToPlane(Vector3 const& pos, Vector3 const& moving_dir) const { Vector3 result; if (!hitsLine(pos, moving_dir, &result)) { throw Exception("Unable to project position to plane!"); } return result; } inline Real Plane::distanceToPosition(Vector3 const& pos) const { Real dp_n_n = dotProduct(normal, normal); return dotProduct(normal, pos) / dp_n_n - distance_from_origin; } inline std::string Plane::toString(void) const { return normal.toString() + ":" + floatToStr(distance_from_origin); } inline void Plane::calculateDistanceToOrigin(Vector3 const& pos_at_plane) { Real dp_nn = dotProduct(normal, normal); HppAssert(dp_nn != 0, "Division by zero! Normal is not normalized!"); distance_from_origin = dotProduct(normal, pos_at_plane) / dp_nn; } } #endif
[ "henu@henu.fi" ]
henu@henu.fi
becec09f979421ae88797ba2a65586c6ad948ea7
a52eb0652ab3f18c76019c0ebc090a07cb5e9dd4
/src/server/scripts/Kalimdor/CavernsOfTime/WellofEternity/boss_mannoroth.cpp
54cc57b7c9831263b71be4d78f9f83a1a71152a2
[]
no_license
szhxjt1334/WoWCircle434
b0531ec16b76e4430d718620477d3532566188aa
de3fa2b4be52a7a683b0427269c51801fc0df062
refs/heads/master
2021-01-12T11:03:08.102883
2016-10-11T22:05:13
2016-10-11T22:05:13
72,802,348
0
1
null
2016-11-04T01:24:11
2016-11-04T01:24:10
null
UTF-8
C++
false
false
26,778
cpp
#include "ScriptPCH.h" #include "well_of_eternity.h" #include "Group.h" enum ScriptedTextMannoroth { SAY_MANNOROTH_AGGRO = 0, SAY_MANNOROTH_DEATH = 1, SAY_MANNOROTH_SARGERAS = 3, SAY_MANNOROTH_SWORD = 4, SAY_MANNOROTH_VAROTHEN = 5, SAY_MANNOROTH_EVENT = 6, SAY_MANNOROTH_KILL = 7, SAY_MANNOROTH_SPELL = 8, SAY_VAROTHEN_AGGRO = 0, SAY_VAROTHEN_DEATH = 1, SAY_VAROTHEN_KILL = 2, }; enum Spells { // Mannoroth SPELL_FEL_FIRESTORM = 103888, SPELL_FEL_FIRESTORM_SUMMON = 103889, SPELL_FEL_FLAMES_AURA = 103892, SPELL_FEL_FLAMES_DMG = 103891, SPELL_FELBLADE = 103966, SPELL_FELBURN = 103972, SPELL_EMBEDDED_BLADE_1 = 104820, SPELL_EMBEDDED_BLADE_2 = 109542, SPELL_EMBEDDED_BLADE_DUMMY = 104823, SPELL_FEL_FIRE_NOVA = 105093, SPELL_NETHER_PORTAL = 104625, SPELL_NETHER_TEAR = 105041, SPELL_FEL_DRAIN = 104961, SPELL_SUMMON_FELHOUND_AURA = 105053, SPELL_SUMMON_FELHOUND = 105054, SPELL_SUMMON_FELGUARD_AURA = 105057, SPELL_SUMMON_FELGUARD = 105058, SPELL_SUMMON_DEVASTATOR_AURA = 105061, SPELL_SUMMON_DEVASTATOR = 105059, SPELL_INFERNAL = 105141, SPELL_INFERNAL_MISSILE = 105145, // Captain Varo'then SPELL_MAGNISTRIKE = 103669, // Doomguard Debilitator SPELL_DEBILITATING_FLAY = 104678, SPELL_COMPLETE_ENCOUNTER = 105576, // Illidan 2 SPELL_WATERS_OF_ETERNITY = 103952, SPELL_TAUNT = 104461, SPELL_DEMON_RUSH = 104205, SPELL_DARKLANCE = 104394, SPELL_AURA_OF_IMMOLATION = 104379, SPELL_GIFT_OF_SARGERAS = 104998, SPELL_GIFT_OF_SARGERAS_AOE = 105009, // Tyrande SPELL_BLESSING_OF_ELUNE = 103917, SPELL_HAND_OF_ELUNE = 105072, SPELL_WRATH_OF_ELUNE_1 = 105073, // 30k damage SPELL_WRATH_OF_ELUNE_2 = 105075, // 300k damage SPELL_LUNAR_SHOT_1 = 104214, // 30k damage, single SPELL_LUNAR_SHOT_2 = 104313, // 300k damage, single SPELL_LUNAR_SHOT_3 = 104688, // 300k damage, aoe }; enum Events { EVENT_MAGNISTRIKE = 1, EVENT_MANNOROTH_AGGRO = 2, EVENT_FEL_FIRESTORM = 3, EVENT_SUMMON_DEBILITATOR = 4, EVENT_SUMMON_DEBILITATOR_1 = 5, EVENT_FELBLADE = 6, EVENT_SUMMON_DEVASTATOR = 7, EVENT_EMBEDDED_BLADE = 8, EVENT_EMBEDDED_BLADE_1 = 9, EVENT_DEBILITATING_FLAY = 10, EVENT_CHECK_PLAYERS = 12, EVENT_MANNOROTH_SARGERAS_1 = 13, // Illidan says EVENT_MANNOROTH_SARGERAS_2 = 14, // Tyrande says EVENT_INFERNAL = 15, // Tyrande says EVENT_GIFT_OF_SARGERAS_1 = 16, // Illidan says EVENT_GIFT_OF_SARGERAS_2 = 17, // Tyrande says EVENT_GIFT_OF_SARGERAS_3 = 18, // Illidan says EVENT_GIFT_OF_SARGERAS_4 = 19, // Tyrande says EVENT_GIFT_OF_SARGERAS_5 = 20, // Illidan says EVENT_DESPAWN = 21, }; enum Adds { NPC_FEL_FLAMES = 55502, NPC_INFERNAL = 56036, NPC_FELGUARD = 56002, NPC_FELHOUND = 56001, NPC_DOOMGUARD_DEVASTATOR = 57410, NPC_DOOMGUARD_DEBILITATOR = 55762, NPC_VAROTHEN_MAGICAL_BLADE = 55837, NPC_EMBEDDED_BLADE = 55838, NPC_PURPOSE_BUNNY_1 = 45979, NPC_PURPOSE_BUNNY_2 = 54020, }; enum Actions { ACTION_VAROTHEN_DIED = 1, ACTION_DEBILITATING_OFF = 2, }; const Position portalPos = {3338.699951f, -5699.775879f, 13.01f, 3.87f}; const Position varothenPos = {3319.669922f, -5716.470215f, 16.18f, 2.68f}; const Position debilitatorPos[2] = { {3295.439941f, -5687.229980f, 14.19f, 5.74f}, // left dreadlord {3324.479980f, -5694.270020f, 13.97f, 3.17f} // right dreadlord }; const Position devastatorPos[3] = { {3302.872803f, -5676.763672f, 12.53f, 4.74f}, {3326.123047f, -5690.420410f, 13.14f, 3.81f}, {3316.755127f, -5686.553711f, 14.03f, 4.26f} }; const Position stalkerPos[3] = { {3295.44f, -5687.23f, 14.19f, 5.74213f}, {3324.48f, -5694.27f, 13.97f, 3.1765f}, {3339.81f, -5698.5f, 15.5043f, 3.97935f}, }; class boss_mannoroth : public CreatureScript { public: boss_mannoroth() : CreatureScript("boss_mannoroth") { } CreatureAI* GetAI(Creature* pCreature) const { return new boss_mannorothAI(pCreature); } struct boss_mannorothAI : public BossAI { boss_mannorothAI(Creature* pCreature) : BossAI(pCreature, DATA_MANNOROTH) { me->ApplySpellImmune(0, IMMUNITY_EFFECT, SPELL_EFFECT_KNOCK_BACK, true); me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_GRIP, true); me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_STUN, true); me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_FEAR, true); me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_ROOT, true); me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_FREEZE, true); me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_POLYMORPH, true); me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_HORROR, true); me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_SAPPED, true); me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_CHARM, true); me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_DISORIENTED, true); me->ApplySpellImmune(0, IMMUNITY_STATE, SPELL_AURA_MOD_CONFUSE, true); me->setActive(true); me->SetReactState(REACT_PASSIVE); } void InitializeAI() { if (!instance || static_cast<InstanceMap*>(me->GetMap())->GetScriptId() != sObjectMgr->GetScriptId(WoEScriptName)) me->IsAIEnabled = false; else if (!me->isDead()) Reset(); } void Reset() { _Reset(); me->SummonCreature(NPC_VAROTHEN, varothenPos, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 3000); phase = 0; bVarothen = false; bAchieve = false; bDebilitating = false; bEndEncounter = false; } void JustReachedHome() { if (Creature* pTyrande = me->FindNearestCreature(NPC_TYRANDE, 150.0f)) pTyrande->AI()->DoAction(7); // ACTION_MANNOROTH_RESET if (Creature* pIllidan = me->FindNearestCreature(NPC_ILLIDAN_2, 150.0f)) pIllidan->AI()->DoAction(7); // ACTION_MANNOROTH_RESET } void AttackStart(Unit* who) { if (!who) return; me->Attack(who, false); } void EnterCombat(Unit* attacker) { if (Creature* pVarothen = ObjectAccessor::GetCreature(*me, instance->GetData64(DATA_VAROTHEN))) if (!pVarothen->isInCombat()) DoZoneInCombat(pVarothen); if (Creature* pIllidan = me->FindNearestCreature(NPC_ILLIDAN_2, 150.0f)) pIllidan->AI()->DoAction(6); // ACTION_MANNOROTH_AGGRO phase = 0; bVarothen = false; bAchieve = false; bDebilitating = false; bEndEncounter = false; events.ScheduleEvent(EVENT_MANNOROTH_AGGRO, 5000); //events.ScheduleEvent(EVENT_FEL_FIRESTORM, 20000); events.ScheduleEvent(EVENT_SUMMON_DEBILITATOR, 65000); events.ScheduleEvent(EVENT_SUMMON_DEVASTATOR, urand(5000, 8000)); events.ScheduleEvent(EVENT_SUMMON_DEVASTATOR, urand(5000, 8000)); events.ScheduleEvent(EVENT_SUMMON_DEVASTATOR, urand(5000, 8000)); events.ScheduleEvent(EVENT_CHECK_PLAYERS, 3000); for (uint8 i = 0; i < 2; ++i) if (Creature* pStalker = me->SummonCreature(NPC_PURPOSE_BUNNY_1, stalkerPos[i])) pStalker->RemoveAllAuras(); if (Creature* pStalker = me->SummonCreature(NPC_PURPOSE_BUNNY_2, stalkerPos[2])) pStalker->RemoveAllAuras(); DoZoneInCombat(); instance->SetBossState(DATA_MANNOROTH, IN_PROGRESS); } void KilledUnit(Unit* who) { if (who && who->GetTypeId() == TYPEID_PLAYER) Talk(SAY_MANNOROTH_KILL); } bool AllowAchieve() { return bAchieve; } void DoAction(const int32 action) { if (action == ACTION_VAROTHEN_DIED) { bVarothen = true; events.ScheduleEvent(EVENT_EMBEDDED_BLADE, 5000); } else if (action == ACTION_DEBILITATING_OFF) { bDebilitating = true; } } void DamageTaken(Unit* /*who*/, uint32 &damage) { if (!bDebilitating) if (me->HealthBelowPctDamaged(88, damage)) damage = 0; if (damage >= me->GetHealth()) damage = 0; } void UpdateAI(const uint32 diff) { if (!UpdateVictim()) return; events.Update(diff); if (me->HasUnitState(UNIT_STATE_CASTING)) return; if (me->HealthBelowPct(90) && !bVarothen) { Talk(SAY_MANNOROTH_VAROTHEN); DoCast(me, SPELL_FEL_DRAIN); bVarothen = true; bAchieve = true; return; } if (me->HealthBelowPct(85) && (phase == 0)) { phase = 1; events.CancelEvent(EVENT_SUMMON_DEVASTATOR); Talk(SAY_MANNOROTH_SARGERAS); DoCast(me, SPELL_NETHER_TEAR); events.ScheduleEvent(EVENT_MANNOROTH_SARGERAS_1, 15000); events.ScheduleEvent(EVENT_MANNOROTH_SARGERAS_2, 23000); return; } else if (me->HealthBelowPct(70) && (phase == 1)) { phase = 2; DoCast(me, SPELL_SUMMON_FELGUARD_AURA, true); } else if (me->HealthBelowPct(60) && (phase == 2)) { phase = 3; DoCast(me, SPELL_SUMMON_DEVASTATOR_AURA, true); } else if (me->HealthBelowPct(50) && (phase == 3)) { phase = 4; Talk(SAY_MANNOROTH_EVENT); DoCast(me, SPELL_INFERNAL); events.ScheduleEvent(EVENT_INFERNAL, 20000); return; } else if (me->HealthBelowPct(25) && (phase == 4)) { phase = 5; bEndEncounter = true; CompleteEncounter(); return; } if (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_CHECK_PLAYERS: if (!SelectTarget(SELECT_TARGET_RANDOM, 0, 100.0f, true)) { events.Reset(); EnterEvadeMode(); return; } else events.ScheduleEvent(EVENT_CHECK_PLAYERS, 3000); break; case EVENT_MANNOROTH_AGGRO: Talk(SAY_MANNOROTH_AGGRO); break; case EVENT_FEL_FIRESTORM: //DoCast(me, SPELL_FEL_FIRESTORM); //events.ScheduleEvent(EVENT_FEL_FIRESTORM, urand(25000, 35000)); break; case EVENT_FELBLADE: DoCast(me, SPELL_FELBLADE); events.ScheduleEvent(EVENT_FELBLADE, urand(15000, 25000)); break; case EVENT_SUMMON_DEBILITATOR: DoCast(me, SPELL_NETHER_PORTAL); events.ScheduleEvent(EVENT_SUMMON_DEBILITATOR_1, 7000); break; case EVENT_SUMMON_DEBILITATOR_1: for (uint8 i = 0; i < 2; ++i) me->SummonCreature(NPC_DOOMGUARD_DEBILITATOR, debilitatorPos[i], TEMPSUMMON_CORPSE_TIMED_DESPAWN, 3000); break; case EVENT_SUMMON_DEVASTATOR: { uint32 i = urand(0, 2); me->SummonCreature(NPC_DOOMGUARD_DEVASTATOR, devastatorPos[i], TEMPSUMMON_CORPSE_TIMED_DESPAWN, 5000); events.ScheduleEvent(EVENT_SUMMON_DEVASTATOR, urand(4000, 7000)); break; } case EVENT_EMBEDDED_BLADE: Talk(SAY_MANNOROTH_SWORD); DoCast(me, SPELL_EMBEDDED_BLADE_2, true); DoCast(me, SPELL_EMBEDDED_BLADE_DUMMY, true); events.ScheduleEvent(EVENT_EMBEDDED_BLADE_1, 3000); break; case EVENT_EMBEDDED_BLADE_1: if (Creature* pIllidan = me->FindNearestCreature(NPC_ILLIDAN_2, 100.0f)) pIllidan->AI()->Talk(15); // SAY_ILLIDAN_2_SWORD //events.RescheduleEvent(EVENT_FEL_FIRESTORM, urand(25000, 30000)); //events.RescheduleEvent(EVENT_FELBLADE, urand(10000, 55000)); break; case EVENT_MANNOROTH_SARGERAS_1: if (Creature* pIllidan = me->FindNearestCreature(NPC_ILLIDAN_2, 100.0f)) pIllidan->AI()->Talk(19); // SAY_ILLIDAN_2_SPELL DoCast(me, SPELL_SUMMON_FELHOUND_AURA, true); break; case EVENT_MANNOROTH_SARGERAS_2: if (Creature* pTyrande = me->FindNearestCreature(NPC_TYRANDE, 150.0f)) { pTyrande->AI()->Talk(10); // SAY_TYRANDE_ARROWS pTyrande->AI()->DoAction(9); // ACTION_MANNOROTH_SARGERAS } break; case EVENT_INFERNAL: if (Creature* pTyrande = me->FindNearestCreature(NPC_TYRANDE, 150.0f)) { pTyrande->AI()->Talk(14); // SAY_TYRANDE_MANY_DEMONS pTyrande->AI()->DoAction(10); // ACTION_MANNOROTH_INFERNO } //events.RescheduleEvent(EVENT_FEL_FIRESTORM, urand(40000, 50000)); //events.RescheduleEvent(EVENT_FELBLADE, urand(45000, 55000)); events.ScheduleEvent(EVENT_GIFT_OF_SARGERAS_1, 5000); break; case EVENT_GIFT_OF_SARGERAS_1: if (Creature* pIllidan = me->FindNearestCreature(NPC_ILLIDAN_2, 100.0f)) { pIllidan->AI()->Talk(16); // SAY_ILLIDAN_2_BUFF_1 pIllidan->CastSpell(me, SPELL_GIFT_OF_SARGERAS); } events.ScheduleEvent(EVENT_GIFT_OF_SARGERAS_2, 8000); break; case EVENT_GIFT_OF_SARGERAS_2: if (Creature* pTyrande = me->FindNearestCreature(NPC_TYRANDE, 150.0f)) pTyrande->AI()->Talk(11); // SAY_TYRANDE_NO_1 events.ScheduleEvent(EVENT_GIFT_OF_SARGERAS_3, 2000); break; case EVENT_GIFT_OF_SARGERAS_3: if (Creature* pIllidan = me->FindNearestCreature(NPC_ILLIDAN_2, 100.0f)) pIllidan->AI()->Talk(17); // SAY_ILLIDAN_2_BUFF_2 events.ScheduleEvent(EVENT_GIFT_OF_SARGERAS_4, 8000); break; case EVENT_GIFT_OF_SARGERAS_4: if (Creature* pTyrande = me->FindNearestCreature(NPC_TYRANDE, 150.0f)) pTyrande->AI()->Talk(12); // SAY_TYRANDE_NO_2 events.ScheduleEvent(EVENT_GIFT_OF_SARGERAS_5, 2000); break; case EVENT_GIFT_OF_SARGERAS_5: if (Creature* pIllidan = me->FindNearestCreature(NPC_ILLIDAN_2, 100.0f)) pIllidan->AI()->Talk(18); // SAY_ILLIDAN_2_BUFF_3 break; case EVENT_DESPAWN: instance->DoRespawnGameObject(instance->GetData64(DATA_MINOR_CACHE), DAY); me->DespawnOrUnsummon(); break; default: break; } } //DoMeleeAttackIfReady(); } private: uint8 phase; bool bVarothen; bool bAchieve; bool bDebilitating; bool bEndEncounter; void CompleteEncounter() { Talk(SAY_MANNOROTH_DEATH); events.Reset(); summons.DespawnAll(2000); me->InterruptNonMeleeSpells(true); if (instance) { // Achievement instance->DoUpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET, SPELL_COMPLETE_ENCOUNTER, 0, 0, me); // Guild Achievement Map::PlayerList const &PlayerList = instance->instance->GetPlayers(); if (!PlayerList.isEmpty()) { for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i) { if (Player* pPlayer = i->getSource()) if (Group* pGroup = pPlayer->GetGroup()) if (pPlayer->GetGuildId() && pGroup->IsGuildGroup(pPlayer->GetGuildId(), true, true)) { pGroup->UpdateGuildAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET, SPELL_COMPLETE_ENCOUNTER, 0, 0, NULL, me); break; } } } instance->DoKilledMonsterKredit(QUEST_THE_PATH_TO_THE_DRAGON_SOUL, NPC_MANNOROTH, 0); instance->UpdateEncounterState(ENCOUNTER_CREDIT_CAST_SPELL, SPELL_COMPLETE_ENCOUNTER, me); instance->SetBossState(DATA_MANNOROTH, DONE); instance->DoModifyPlayerCurrencies(CURRENCY_TYPE_JUSTICE_POINTS, 7000); } if (Creature* pTyrande = me->FindNearestCreature(NPC_TYRANDE, 150.0f)) pTyrande->AI()->DoAction(11); // ACTION_MANNOROTH_END events.ScheduleEvent(EVENT_DESPAWN, 5000); } }; }; class npc_mannoroth_varothen : public CreatureScript { public: npc_mannoroth_varothen() : CreatureScript("npc_mannoroth_varothen") { } CreatureAI* GetAI(Creature* pCreature) const { return new npc_mannoroth_varothenAI(pCreature); } struct npc_mannoroth_varothenAI : public ScriptedAI { npc_mannoroth_varothenAI(Creature* pCreature) : ScriptedAI(pCreature) { me->ApplySpellImmune(0, IMMUNITY_EFFECT, SPELL_EFFECT_KNOCK_BACK, true); me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_GRIP, true); me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_STUN, true); me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_FEAR, true); me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_ROOT, true); me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_FREEZE, true); me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_POLYMORPH, true); me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_HORROR, true); me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_SAPPED, true); me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_CHARM, true); me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_DISORIENTED, true); me->ApplySpellImmune(0, IMMUNITY_STATE, SPELL_AURA_MOD_CONFUSE, true); me->setActive(true); pInstance = me->GetInstanceScript(); } void Reset() { events.Reset(); if (!me->FindNearestCreature(NPC_ILLIDAN_2, 100.0f)) me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC); } void EnterCombat(Unit* attacker) { Talk(SAY_VAROTHEN_AGGRO); events.ScheduleEvent(EVENT_MAGNISTRIKE, urand(3000, 7000)); if (pInstance) if (Creature* pMannoroth = ObjectAccessor::GetCreature(*me, pInstance->GetData64(DATA_MANNOROTH))) if (!pMannoroth->isInCombat()) DoZoneInCombat(pMannoroth); } void KilledUnit(Unit* who) { if (who && who->GetTypeId() == TYPEID_PLAYER) Talk(SAY_VAROTHEN_KILL); } void SpellHit(Unit* who, const SpellInfo* spellInfo) { if (spellInfo->Id == SPELL_ARCHIVED_VAROTHEN_1) DoCast(who, SPELL_ARCHIVED_VAROTHEN_2, true); } void JustDied(Unit* /*killer*/) { Talk(SAY_VAROTHEN_DEATH); if (pInstance) { if (Creature* pMannoroth = ObjectAccessor::GetCreature(*me, pInstance->GetData64(DATA_MANNOROTH))) pMannoroth->AI()->DoAction(ACTION_VAROTHEN_DIED); Map::PlayerList const &PlayerList = pInstance->instance->GetPlayers(); if (!PlayerList.isEmpty()) for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i) if (Player* pPlayer = i->getSource()) if (me->GetDistance(pPlayer) <= 50.0f && pPlayer->GetQuestStatus(QUEST_DOCUMENTING_THE_TIMEWAYS) == QUEST_STATUS_INCOMPLETE) pPlayer->CastSpell(me, SPELL_ARCHIVED_VAROTHEN_1, true); } } void UpdateAI(const uint32 diff) { if (!UpdateVictim()) return; events.Update(diff); if (me->HasUnitState(UNIT_STATE_CASTING)) return; if (uint32 eventId = events.ExecuteEvent()) { if (eventId == EVENT_MAGNISTRIKE) { DoCastVictim(SPELL_MAGNISTRIKE); events.ScheduleEvent(EVENT_MAGNISTRIKE, urand(10000, 15000)); } } DoMeleeAttackIfReady(); } private: EventMap events; InstanceScript* pInstance; }; }; class npc_mannoroth_doomguard_debilitator : public CreatureScript { public: npc_mannoroth_doomguard_debilitator() : CreatureScript("npc_mannoroth_doomguard_debilitator") { } CreatureAI* GetAI(Creature* pCreature) const { return new npc_mannoroth_doomguard_debilitatorAI(pCreature); } struct npc_mannoroth_doomguard_debilitatorAI : public ScriptedAI { npc_mannoroth_doomguard_debilitatorAI(Creature* pCreature) : ScriptedAI(pCreature) { me->ApplySpellImmune(0, IMMUNITY_EFFECT, SPELL_EFFECT_KNOCK_BACK, true); me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_GRIP, true); me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_STUN, true); me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_FEAR, true); me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_ROOT, true); me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_FREEZE, true); me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_POLYMORPH, true); me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_HORROR, true); me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_SAPPED, true); me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_CHARM, true); me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_DISORIENTED, true); me->ApplySpellImmune(0, IMMUNITY_STATE, SPELL_AURA_MOD_CONFUSE, true); me->setActive(true); me->SetReactState(REACT_PASSIVE); } void Reset() { events.Reset(); } void IsSummonedBy(Unit* /*owner*/) { events.ScheduleEvent(EVENT_DEBILITATING_FLAY, 1000); } void JustDied(Unit* /*killer*/) { if (Creature* pTyrande = me->FindNearestCreature(NPC_TYRANDE, 100.0f)) pTyrande->AI()->DoAction(8); // ACTION_DEBILITATING_OFF } void UpdateAI(const uint32 diff) { events.Update(diff); if (uint32 eventId = events.ExecuteEvent()) { if (eventId == EVENT_DEBILITATING_FLAY) { DoCast(me, SPELL_DEBILITATING_FLAY); } } } private: EventMap events; }; }; class spell_mannoroth_gift_of_sargeras : public SpellScriptLoader { public: spell_mannoroth_gift_of_sargeras() : SpellScriptLoader("spell_mannoroth_gift_of_sargeras") { } class spell_mannoroth_gift_of_sargeras_SpellScript : public SpellScript { PrepareSpellScript(spell_mannoroth_gift_of_sargeras_SpellScript); void HandleAfterHit() { if (!GetCaster()) return; GetCaster()->CastSpell(GetCaster(), SPELL_GIFT_OF_SARGERAS_AOE, true); } void Register() { AfterHit += SpellHitFn(spell_mannoroth_gift_of_sargeras_SpellScript::HandleAfterHit); } }; SpellScript* GetSpellScript() const { return new spell_mannoroth_gift_of_sargeras_SpellScript(); } }; typedef boss_mannoroth::boss_mannorothAI MannorothAI; class achievement_thats_not_cannon : public AchievementCriteriaScript { public: achievement_thats_not_cannon() : AchievementCriteriaScript("achievement_thats_not_cannon") { } bool OnCheck(Player* source, Unit* target) { if (!target) return false; if (MannorothAI* mannorothAI = CAST_AI(MannorothAI, target->GetAI())) return mannorothAI->AllowAchieve(); return false; } }; void AddSC_boss_mannoroth() { new boss_mannoroth(); new npc_mannoroth_varothen(); new npc_mannoroth_doomguard_debilitator(); new spell_mannoroth_gift_of_sargeras(); new achievement_thats_not_cannon(); }
[ "Tobias Pohlmann" ]
Tobias Pohlmann
7100f2f4ba13ef0e8b06ea0eb1e53a28b34f51c4
a008b112837ba18b5a3325bf559a78a1993d0717
/courses/phone-book/v6(socket)/client/src/book.h
119632dd37c26fa55b14d40b7d7b760089dfe61b
[]
no_license
jokerlee/college
4509aadc180ad2a4e11dc19e56af2b9f4cd6ba03
3fbbb79d86b25e55a68141c3ee1292af0b48af1a
refs/heads/master
2020-12-24T16:49:24.656255
2014-01-31T04:19:45
2014-01-31T04:19:45
16,399,338
1
0
null
null
null
null
UTF-8
C++
false
false
1,080
h
#ifndef __BOOK_PHONEBOOK_H_INCLUDE__ #define __BOOK_PHONEBOOK_H_INCLUDE__ #include "my_utils.h" #include <iostream> #include <string> #include <vector> #include <list> #include <map> using namespace std; typedef map<string, string> FieldMap; typedef FieldMap::iterator MapIter; typedef FieldMap::const_iterator cMapIter; typedef map<string, string>::value_type MapType; class Record { private: map<string, string> _data; long _index; vector<string> _labels; public: Record(const string = ""); operator bool()const; bool operator==(const Record &)const; bool operator!=(const Record &)const; string & operator[](const string &); const string & operator[](const string &)const; const long index()const { return _index; } const long size()const { return _data.size(); } void clear(); void setIndex(long index) { _index = index; } void setField(const string &, const string &); }; typedef list<Record> RecordList; typedef RecordList::iterator ListIter; typedef RecordList::const_iterator cListIter; #endif
[ "lijie@hortorgames.com" ]
lijie@hortorgames.com
c616616bccb4f9fdd1701b7b33d140a92a859b54
f77ee068b83c1a35baf0330eed56cb25ce091527
/lib/include/pldl/netlist.hpp
40bf112a47e488308a76764bf8624d88f67d76e4
[ "MIT" ]
permissive
yjg361/primal-dual-approx-cpp
67795c8005d5c3280212ab936810a353a8c68b8b
a3c2e53fb64d200925ecfb512af8a777ee1d3ac6
refs/heads/main
2023-04-04T05:38:37.938101
2021-04-20T10:16:07
2021-04-20T10:16:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,575
hpp
#pragma once // import networkx as nx #include <algorithm> #include <iterator> #include <py2cpp/py2cpp.hpp> #include <utility> #include <vector> #include <xnetwork/classes/graph.hpp> // using node_t = int; // struct PartInfo // { // std::vector<std::uint8_t> part; // py::set<node_t> extern_nets; // }; /*! * @brief Netlist * * Netlist is implemented by xn::Graph, which is a networkx-like graph. * */ template <typename graph_t> struct Netlist { using nodeview_t = typename graph_t::nodeview_t; using node_t = typename graph_t::node_t; using index_t = typename nodeview_t::key_type; // using graph_t = xn::Graph<graph_t>; graph_t G; nodeview_t modules; nodeview_t nets; size_t num_modules {}; size_t num_nets {}; size_t num_pads = 0U; size_t max_degree {}; size_t max_net_degree {}; // std::uint8_t cost_model = 0; std::vector<int> module_weight; std::vector<int> net_weight; bool has_fixed_modules {}; py::set<node_t> module_fixed; /* For multi-level algorithms */ const Netlist<graph_t>* parent; py::dict<node_t, index_t> node_up_map; py::dict<index_t, node_t> node_down_map; py::dict<index_t, node_t> cluster_down_map; public: /*! * @brief Construct a new Netlist object * * @param[in] G * @param[in] module_list * @param[in] net_list * @param[in] module_fixed */ Netlist(graph_t G, const nodeview_t& modules, const nodeview_t& nets); /** * @brief Construct a new Netlist object * * @param[in] G * @param[in] num_modules * @param[in] num_nets */ Netlist(graph_t G, int numModules, int numNets); /** * @brief Get the number of modules * * @return size_t */ [[nodiscard]] auto number_of_modules() const -> size_t { return this->num_modules; } /*! * @brief Get the number of nets * * @return size_t */ [[nodiscard]] auto number_of_nets() const -> size_t { return this->num_nets; } /*! * @brief Get the number of nodes * * @return size_t */ [[nodiscard]] auto number_of_nodes() const -> size_t { return this->G.number_of_nodes(); } // /*! // * @brief // * // * @return index_t // */ // auto number_of_pins() const -> index_t { return // this->G.number_of_edges(); } /*! * @brief Get the max degree * * @return size_t */ [[nodiscard]] auto get_max_degree() const -> size_t { return this->max_degree; } /*! * @brief Get the max net degree * * @return index_t */ [[nodiscard]] auto get_max_net_degree() const -> size_t { return this->max_net_degree; } /** * @brief Get the module weight * * @param[in] v * @return int */ auto get_module_weight(const node_t& v) const -> int { return this->module_weight.empty() ? 1 : this->module_weight[v]; } /** * @brief Get the net weight * * @return int */ auto get_net_weight(const node_t& /*net*/) const -> int { // return this->net_weight.empty() ? 1 // : // this->net_weight[this->net_map[net]]; return 1; } }; /** * @brief Construct a new Netlist object * * @tparam nodeview_t * @tparam nodemap_t * @param[in] G * @param[in] modules * @param[in] nets */ template <typename graph_t> Netlist<graph_t>::Netlist( graph_t G, const nodeview_t& modules, const nodeview_t& nets) : G {std::move(G)} , modules {modules} , nets {nets} , num_modules(modules.size()) , num_nets(nets.size()) { this->has_fixed_modules = (!this->module_fixed.empty()); // Some compilers does not accept py::range()->iterator as a forward // iterator auto deg_cmp = [this](const node_t& v, const node_t& w) -> // index_t { // return this->G.degree(v) < this->G.degree(w); // }; // const auto result1 = // std::max_element(this->modules.begin(), this->modules.end(), // deg_cmp); // this->max_degree = this->G.degree(*result1); // const auto result2 = // std::max_element(this->nets.begin(), this->nets.end(), deg_cmp); // this->max_net_degree = this->G.degree(*result2); this->max_degree = 0U; for (const auto& v : this->modules) { if (this->max_degree < this->G.degree(v)) { this->max_degree = this->G.degree(v); } } this->max_net_degree = 0U; for (const auto& net : this->nets) { if (this->max_net_degree < this->G.degree(net)) { this->max_net_degree = this->G.degree(net); } } } template <typename graph_t> Netlist<graph_t>::Netlist(graph_t G, int numModules, int numNets) : Netlist {std::move(G), py::range<int>(numModules), py::range<int>(numModules, numModules + numNets)} { } // using RngIter = decltype(py::range<int>(0, 1)); using graph_t = xn::SimpleGraph; using index_t = int; using SimpleNetlist = Netlist<graph_t>; template <typename Node> struct MoveInfo { Node net; Node v; std::uint8_t fromPart; std::uint8_t toPart; }; template <typename Node> struct MoveInfoV { Node v; std::uint8_t fromPart; std::uint8_t toPart; // node_t v; }; template <typename Node> struct Snapshot { py::set<Node> extern_nets; py::dict<index_t, std::uint8_t> extern_modules; };
[ "luk036@gmail.com" ]
luk036@gmail.com
1d3ba48237f5a9b7ef172d127be73a8c6a50b0f1
1798ba59a187a8868e32b4d4f5f54ec81efbf807
/devel/include/f1tenth_msgs/ArmorDetectionAction.h
0ec3fa637f4e5568c6eb75ee34472232d589aae8
[]
no_license
chalkchalk/fl1oth_ws
60d17ee4d9206c436a221b82e2f92d0eedd78eb0
4c53588c129ad206ebc1354cc55ff6d2d88863d4
refs/heads/master
2022-12-11T11:15:58.773602
2020-09-13T04:04:24
2020-09-13T04:04:24
294,903,878
0
0
null
null
null
null
UTF-8
C++
false
false
12,628
h
// Generated by gencpp from file f1tenth_msgs/ArmorDetectionAction.msg // DO NOT EDIT! #ifndef F1TENTH_MSGS_MESSAGE_ARMORDETECTIONACTION_H #define F1TENTH_MSGS_MESSAGE_ARMORDETECTIONACTION_H #include <string> #include <vector> #include <map> #include <ros/types.h> #include <ros/serialization.h> #include <ros/builtin_message_traits.h> #include <ros/message_operations.h> #include <f1tenth_msgs/ArmorDetectionActionGoal.h> #include <f1tenth_msgs/ArmorDetectionActionResult.h> #include <f1tenth_msgs/ArmorDetectionActionFeedback.h> namespace f1tenth_msgs { template <class ContainerAllocator> struct ArmorDetectionAction_ { typedef ArmorDetectionAction_<ContainerAllocator> Type; ArmorDetectionAction_() : action_goal() , action_result() , action_feedback() { } ArmorDetectionAction_(const ContainerAllocator& _alloc) : action_goal(_alloc) , action_result(_alloc) , action_feedback(_alloc) { (void)_alloc; } typedef ::f1tenth_msgs::ArmorDetectionActionGoal_<ContainerAllocator> _action_goal_type; _action_goal_type action_goal; typedef ::f1tenth_msgs::ArmorDetectionActionResult_<ContainerAllocator> _action_result_type; _action_result_type action_result; typedef ::f1tenth_msgs::ArmorDetectionActionFeedback_<ContainerAllocator> _action_feedback_type; _action_feedback_type action_feedback; typedef boost::shared_ptr< ::f1tenth_msgs::ArmorDetectionAction_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::f1tenth_msgs::ArmorDetectionAction_<ContainerAllocator> const> ConstPtr; }; // struct ArmorDetectionAction_ typedef ::f1tenth_msgs::ArmorDetectionAction_<std::allocator<void> > ArmorDetectionAction; typedef boost::shared_ptr< ::f1tenth_msgs::ArmorDetectionAction > ArmorDetectionActionPtr; typedef boost::shared_ptr< ::f1tenth_msgs::ArmorDetectionAction const> ArmorDetectionActionConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::f1tenth_msgs::ArmorDetectionAction_<ContainerAllocator> & v) { ros::message_operations::Printer< ::f1tenth_msgs::ArmorDetectionAction_<ContainerAllocator> >::stream(s, "", v); return s; } } // namespace f1tenth_msgs namespace ros { namespace message_traits { // BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': False} // {'nav_msgs': ['/opt/ros/kinetic/share/nav_msgs/cmake/../msg'], 'f1tenth_msgs': ['/home/ycz/f1tenth_ws/devel/share/f1tenth_msgs/msg', '/home/ycz/f1tenth_ws/src/f1tenth_msgs/msg', '/home/ycz/f1tenth_ws/src/f1tenth_msgs/msg/referee_system'], 'actionlib_msgs': ['/opt/ros/kinetic/share/actionlib_msgs/cmake/../msg'], 'std_msgs': ['/opt/ros/kinetic/share/std_msgs/cmake/../msg'], 'geometry_msgs': ['/opt/ros/kinetic/share/geometry_msgs/cmake/../msg']} // !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types'] template <class ContainerAllocator> struct IsFixedSize< ::f1tenth_msgs::ArmorDetectionAction_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct IsFixedSize< ::f1tenth_msgs::ArmorDetectionAction_<ContainerAllocator> const> : FalseType { }; template <class ContainerAllocator> struct IsMessage< ::f1tenth_msgs::ArmorDetectionAction_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::f1tenth_msgs::ArmorDetectionAction_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::f1tenth_msgs::ArmorDetectionAction_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct HasHeader< ::f1tenth_msgs::ArmorDetectionAction_<ContainerAllocator> const> : FalseType { }; template<class ContainerAllocator> struct MD5Sum< ::f1tenth_msgs::ArmorDetectionAction_<ContainerAllocator> > { static const char* value() { return "2b6876a7f1d21ca8c4f85162a49d48f1"; } static const char* value(const ::f1tenth_msgs::ArmorDetectionAction_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0x2b6876a7f1d21ca8ULL; static const uint64_t static_value2 = 0xc4f85162a49d48f1ULL; }; template<class ContainerAllocator> struct DataType< ::f1tenth_msgs::ArmorDetectionAction_<ContainerAllocator> > { static const char* value() { return "f1tenth_msgs/ArmorDetectionAction"; } static const char* value(const ::f1tenth_msgs::ArmorDetectionAction_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::f1tenth_msgs::ArmorDetectionAction_<ContainerAllocator> > { static const char* value() { return "# ====== DO NOT MODIFY! AUTOGENERATED FROM AN ACTION DEFINITION ======\n\ \n\ ArmorDetectionActionGoal action_goal\n\ ArmorDetectionActionResult action_result\n\ ArmorDetectionActionFeedback action_feedback\n\ \n\ ================================================================================\n\ MSG: f1tenth_msgs/ArmorDetectionActionGoal\n\ # ====== DO NOT MODIFY! AUTOGENERATED FROM AN ACTION DEFINITION ======\n\ \n\ Header header\n\ actionlib_msgs/GoalID goal_id\n\ ArmorDetectionGoal goal\n\ \n\ ================================================================================\n\ MSG: std_msgs/Header\n\ # Standard metadata for higher-level stamped data types.\n\ # This is generally used to communicate timestamped data \n\ # in a particular coordinate frame.\n\ # \n\ # sequence ID: consecutively increasing ID \n\ uint32 seq\n\ #Two-integer timestamp that is expressed as:\n\ # * stamp.sec: seconds (stamp_secs) since epoch (in Python the variable is called 'secs')\n\ # * stamp.nsec: nanoseconds since stamp_secs (in Python the variable is called 'nsecs')\n\ # time-handling sugar is provided by the client library\n\ time stamp\n\ #Frame this data is associated with\n\ # 0: no frame\n\ # 1: global frame\n\ string frame_id\n\ \n\ ================================================================================\n\ MSG: actionlib_msgs/GoalID\n\ # The stamp should store the time at which this goal was requested.\n\ # It is used by an action server when it tries to preempt all\n\ # goals that were requested before a certain time\n\ time stamp\n\ \n\ # The id provides a way to associate feedback and\n\ # result message with specific goal requests. The id\n\ # specified must be unique.\n\ string id\n\ \n\ \n\ ================================================================================\n\ MSG: f1tenth_msgs/ArmorDetectionGoal\n\ # ====== DO NOT MODIFY! AUTOGENERATED FROM AN ACTION DEFINITION ======\n\ #Send a flag to server to control the thread start, pause, restart and stop\n\ #command == 1 start\n\ #command == 2 pause\n\ #command == 3 stop\n\ int32 command\n\ \n\ ================================================================================\n\ MSG: f1tenth_msgs/ArmorDetectionActionResult\n\ # ====== DO NOT MODIFY! AUTOGENERATED FROM AN ACTION DEFINITION ======\n\ \n\ Header header\n\ actionlib_msgs/GoalStatus status\n\ ArmorDetectionResult result\n\ \n\ ================================================================================\n\ MSG: actionlib_msgs/GoalStatus\n\ GoalID goal_id\n\ uint8 status\n\ uint8 PENDING = 0 # The goal has yet to be processed by the action server\n\ uint8 ACTIVE = 1 # The goal is currently being processed by the action server\n\ uint8 PREEMPTED = 2 # The goal received a cancel request after it started executing\n\ # and has since completed its execution (Terminal State)\n\ uint8 SUCCEEDED = 3 # The goal was achieved successfully by the action server (Terminal State)\n\ uint8 ABORTED = 4 # The goal was aborted during execution by the action server due\n\ # to some failure (Terminal State)\n\ uint8 REJECTED = 5 # The goal was rejected by the action server without being processed,\n\ # because the goal was unattainable or invalid (Terminal State)\n\ uint8 PREEMPTING = 6 # The goal received a cancel request after it started executing\n\ # and has not yet completed execution\n\ uint8 RECALLING = 7 # The goal received a cancel request before it started executing,\n\ # but the action server has not yet confirmed that the goal is canceled\n\ uint8 RECALLED = 8 # The goal received a cancel request before it started executing\n\ # and was successfully cancelled (Terminal State)\n\ uint8 LOST = 9 # An action client can determine that a goal is LOST. This should not be\n\ # sent over the wire by an action server\n\ \n\ #Allow for the user to associate a string with GoalStatus for debugging\n\ string text\n\ \n\ \n\ ================================================================================\n\ MSG: f1tenth_msgs/ArmorDetectionResult\n\ # ====== DO NOT MODIFY! AUTOGENERATED FROM AN ACTION DEFINITION ======\n\ float32 result\n\ \n\ ================================================================================\n\ MSG: f1tenth_msgs/ArmorDetectionActionFeedback\n\ # ====== DO NOT MODIFY! AUTOGENERATED FROM AN ACTION DEFINITION ======\n\ \n\ Header header\n\ actionlib_msgs/GoalStatus status\n\ ArmorDetectionFeedback feedback\n\ \n\ ================================================================================\n\ MSG: f1tenth_msgs/ArmorDetectionFeedback\n\ # ====== DO NOT MODIFY! AUTOGENERATED FROM AN ACTION DEFINITION ======\n\ #feedback\n\ bool detected\n\ int32 error_code\n\ string error_msg\n\ geometry_msgs/PoseStamped enemy_pos\n\ \n\ \n\ ================================================================================\n\ MSG: geometry_msgs/PoseStamped\n\ # A Pose with reference coordinate frame and timestamp\n\ Header header\n\ Pose pose\n\ \n\ ================================================================================\n\ MSG: geometry_msgs/Pose\n\ # A representation of pose in free space, composed of position and orientation. \n\ Point position\n\ Quaternion orientation\n\ \n\ ================================================================================\n\ MSG: geometry_msgs/Point\n\ # This contains the position of a point in free space\n\ float64 x\n\ float64 y\n\ float64 z\n\ \n\ ================================================================================\n\ MSG: geometry_msgs/Quaternion\n\ # This represents an orientation in free space in quaternion form.\n\ \n\ float64 x\n\ float64 y\n\ float64 z\n\ float64 w\n\ "; } static const char* value(const ::f1tenth_msgs::ArmorDetectionAction_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::f1tenth_msgs::ArmorDetectionAction_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m) { stream.next(m.action_goal); stream.next(m.action_result); stream.next(m.action_feedback); } ROS_DECLARE_ALLINONE_SERIALIZER }; // struct ArmorDetectionAction_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::f1tenth_msgs::ArmorDetectionAction_<ContainerAllocator> > { template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::f1tenth_msgs::ArmorDetectionAction_<ContainerAllocator>& v) { s << indent << "action_goal: "; s << std::endl; Printer< ::f1tenth_msgs::ArmorDetectionActionGoal_<ContainerAllocator> >::stream(s, indent + " ", v.action_goal); s << indent << "action_result: "; s << std::endl; Printer< ::f1tenth_msgs::ArmorDetectionActionResult_<ContainerAllocator> >::stream(s, indent + " ", v.action_result); s << indent << "action_feedback: "; s << std::endl; Printer< ::f1tenth_msgs::ArmorDetectionActionFeedback_<ContainerAllocator> >::stream(s, indent + " ", v.action_feedback); } }; } // namespace message_operations } // namespace ros #endif // F1TENTH_MSGS_MESSAGE_ARMORDETECTIONACTION_H
[ "1261677461@qq.com" ]
1261677461@qq.com
b96582bb97d09eb475f4983a85ae9d1caffb1649
f97ce0a588e023675eaa980f2f105f0a9c25ce18
/UVa/v104/10462.CPP
3576126aae237ce602d43b39f60c69e148509819
[]
no_license
anindya028/Programming-Contest-Problems
a5c49653d990391a6e2003f2ec9d951222cabbe2
7038b6267432189de72539ef5ad046d38e730ee8
refs/heads/master
2023-03-17T06:27:38.339049
2021-02-23T22:58:06
2021-02-23T22:58:06
277,399,320
0
0
null
null
null
null
UTF-8
C++
false
false
2,022
cpp
//MST #include<stdio.h> #include<math.h> #include<string.h> #include<stdlib.h> #include<algorithm> #include<queue> using namespace std; #define inf 1<<29 struct edge { int source,dest,cost; int taken; }e[205]; int rank[105],parent[105]; void link(int a,int b) { if(rank[a]>rank[b]) parent[b]=a; else { parent[a]=b; if(rank[a]==rank[b]) rank[b]=rank[b]+1; } return; } int find_set(int a) { if(a!=parent[a]) parent[a]=find_set(parent[a]); return parent[a]; } bool operator<(edge a,edge b) { return a.cost<b.cost; } int main() { int cs,t,i,j,k,n,m,u,v,sum,secsum,c; edge mst[105],secmst[105]; scanf("%d",&t); for(cs=0;cs<t;cs++) { scanf("%d%d",&n,&m); for(i=0;i<m;i++) { scanf("%d%d%d",&e[i].source,&e[i].dest,&e[i].cost); e[i].taken=0; } if(!m) { if(n==1)printf("Case #%d : No second way\n",cs+1); else printf("Case #%d : No way\n",cs+1); continue; } for(i=1;i<=n;i++) { parent[i]=i; rank[i]=0; } sort(e,e+m); for(i=j=0;i<m;i++) { u=find_set(e[i].source); v=find_set(e[i].dest); if(u!=v) { mst[j]=e[i]; e[i].taken=1; j++; link(u,v); } } if(j!=(n-1)) { printf("Case #%d : No way\n",cs+1); continue; } if(m==1) { printf("Case #%d : No second way\n",cs+1); continue; } secsum=inf; for(i=j=0;i<m;i++) if(e[i].taken) { for(k=1;k<=n;k++) { rank[k]=0; parent[k]=k; } for(k=c=0;k<m;k++) if(k!=i) { u=find_set(e[k].source); v=find_set(e[k].dest); if(u!=v) { secmst[c]=e[k]; c++; link(u,v); } } if(c==(n-1)) { for(k=sum=0;k<c;k++) sum+=secmst[k].cost; if(sum<secsum) secsum=sum; } } if(secsum==inf) printf("Case #%d : No second way\n",cs+1); else printf("Case #%d : %d\n",cs+1,secsum); } return 0; }
[ "anindya@Anindyas-MacBook-Pro.local" ]
anindya@Anindyas-MacBook-Pro.local
acaf528d343ec281c498ee6f03293bcf7affa94e
85a60704b2db0f56c22b7ebfef71095fe2cd5f15
/src/Component/UserDataComp.h
64223a3b301e07f8087ab8c6e5b3642c923d9336
[]
no_license
FrancisLaiLD/francislai-01
e77caf13bfd3a593bd785adf970e23a88cd62f00
7bea841d686f26441db9031f48881a97052fdb20
refs/heads/master
2020-03-23T18:08:19.686706
2018-09-26T14:25:58
2018-09-26T14:25:58
141,891,523
0
0
null
null
null
null
UTF-8
C++
false
false
646
h
#ifndef USERDATACOMP_H #define USERDATACOMP_H #include <QObject> #include <QDateTime> class UserDataComponent { public: UserDataComponent() {} UserDataComponent(float c_temp, int c_Height, int c_Weight, QDateTime c_time); ~UserDataComponent() {} float temp() const; void setTemp(float temp); QDateTime timeGetData() const; void setTimeGetData(const QDateTime &timeGetData); int weight() const; void setWeight(int weight); int height() const; void setHeight(int height); private: float m_temp; int m_height; int m_weight; QDateTime m_timeGetData; }; #endif // USERDATACOMP_H
[ "laidanghungptit@gmail.com" ]
laidanghungptit@gmail.com
316ac2751b64f62166ec6378d36d55389368141a
0e42fc5436061b46d44249edd0f9da0750d51bde
/Assessment One & Two/source/mage.cpp
e483f6a57f85d5647eb6b7c3f396f5295fbd45ed
[]
no_license
cazBlue/AIEYearOneProjects
53602a0f8d61a3693c41ad8f705e8514e3b87ee5
0b30535441b95e4e35015639d1b731f8d0311e0a
refs/heads/master
2021-01-21T08:01:36.101292
2015-08-24T11:19:53
2015-08-24T11:19:53
41,294,959
0
0
null
null
null
null
UTF-8
C++
false
false
2,678
cpp
#include "mage.h" #include "fireball.h" #include "level.h" Mage::Mage(Level *level, DrawEngine *de, int s_index, float x, float y , int lives, char spell_key, char up_key, char down_key, char left_key, char right_key) : Character(level, de, s_index, x, y, lives, up_key, down_key, left_key, right_key) { spellKey = spell_key; classID = MAGE_CLASSID; score = 0; } bool Mage::keyPress(char c) { //returns false if not a movement key bool val = Character::keyPress(c); //if it's not a movement key check if it's a spell cast if(!val) { if (c == spellKey) { castSpell(); return true; } } if(Mage::checkForCheese()) { //increase the players score addScore(20); } return val; } bool Mage::checkForCheese() { list <Sprite *>::iterator Iter; for (Iter = level->npc.begin(); Iter != level->npc.end(); Iter++) { if ((*Iter)->classID == CHEESE_CLASSID && int((*Iter)->getX()) == int(pos.x) && int((*Iter)->getY()) == int(pos.y)) { //destroy the cheese (*Iter)->addLives(-1); return true; } } return false; } void Mage::castSpell(void) { //the problem with the original is that it can cast into walls //updated to check is the cast position would be a valid move for the player vector newMove; newMove.x = (int)pos.x + facingDirection.x; newMove.y = (int)pos.y + facingDirection.y; if(isValidLevelMove(newMove.x, newMove.y)) { Fireball *temp = new Fireball(level, drawArea, SPRITE_FIREBALL, (int)pos.x + facingDirection.x, (int)pos.y + facingDirection.y, facingDirection.x, facingDirection.y); level->addNPC((Sprite *) temp); } } bool Mage::move(float x, float y) { Sprite::move( x, y); //to do //add checks for powerups/cheese level->gameLevel[int(x)][int(y)]; return false; } bool Mage::addPowerUp(int PowerUp) { int temp; return false; } bool Mage::checkGameOver(int *arg_endtype) { if(getLives() <= 0) { //TODO //add in return to high score screen //TODO go to lose screen *arg_endtype = ENDTYPE_LOSE; return true; } if(getMouseCount() <= 0 && getLives() > 0) { //TODO go to win screen *arg_endtype = ENDTYPE_WIN; return true; } else if(getMouseCount() <= 0) { *arg_endtype = ENDTYPE_LOSE; return true; } return false; } int Mage::getMouseCount() { return level->countMice(); } void Mage::addLives(int arg_lives) { /* overrides the character addlives as we don't want to reset the players position call the sprites function as it meets the current need */ Sprite::addLives(arg_lives); //checkGameOver(); } int Mage::getScore() { return score; } void Mage::addScore(int arg_scoreToAdd) { score += arg_scoreToAdd; }
[ "callan@callanw.com" ]
callan@callanw.com
0af1a603f8d8682dd172baa14503836d29c8692a
a692fe17e0c96a713ccb89ad36f0348cbc4b361f
/osiris/BaseClassLib/ltoa.cpp
ca87562fec0422b16e849f6c7ac28f0fcdcf0245
[]
no_license
Rajesh35hsp/osiris
9c249633745d0730c96132a58bfd95e0aeaa1148
c9b22d74881472b43f2c0e5619aa53341c709d19
refs/heads/master
2023-08-27T00:50:03.242581
2021-11-05T13:26:29
2021-11-05T13:26:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,611
cpp
/* * =========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * * FileName: ltoa.cpp * */ #include <stdio.h> static inline char CHAR(int nDigit) { char cRtn; if(nDigit > 9) { cRtn = ('A' + nDigit - 10); } else { cRtn = ('0' + nDigit); } return cRtn; } char *_ultoa(unsigned long value, char *buffer, int radix) { if(value == 0) { *buffer = '0'; buffer[1] = 0; } else if(radix == 10) { sprintf(buffer,"%lu",value); } else if(radix == 16) { sprintf(buffer,"%lX",value); } else if(radix > 1 && radix <= 36) { int nDigit; char xx[64]; char *pxx = xx; char *pBuffer = buffer; *pxx = 0; // set up digits in reverse order while(value > radix) { nDigit = value % radix; value /= radix; *pxx++ = CHAR(nDigit); *pxx = 0; } if(value > 0) { *pxx = CHAR(value); } else { // make pxx point to last digit pxx--; } while(pxx >= xx) { *pBuffer = *pxx; pBuffer++; pxx--; } *pBuffer = (char)0; } else { *buffer = 0; } return buffer; } char *_ltoa(long value, char *buffer, int radix) { char *rtn = buffer; if(value < 0) { *buffer = '-'; buffer++; value = -value; } _ultoa((unsigned long) value, buffer,radix); return rtn; } char *itoa(int value, char *buffer, int radix) { return _ltoa((long)value,buffer,radix); }
[ "hoffman@ncbi.nlm.nih.gov" ]
hoffman@ncbi.nlm.nih.gov
5f7e4b4fb2e82afe273a97e47ee360c27c107721
1d2705c9be9ee0f974c224eb794f2f8a9e9a3d50
/look_for_face/center_face/main_prova.cpp
25cd1271a125705d45d9c5657940e9bb8f8f85fe
[]
no_license
llvllrbreeze/alcorapp
dfe2551f36d346d73d998f59d602c5de46ef60f7
3ad24edd52c19f0896228f55539aa8bbbb011aac
refs/heads/master
2021-01-10T07:36:01.058011
2008-12-16T12:51:50
2008-12-16T12:51:50
47,865,136
0
0
null
null
null
null
UTF-8
C++
false
false
6,284
cpp
#include "cv.h" #include "highgui.h" #include "PTU46.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <math.h> #include <float.h> #include <limits.h> #include <time.h> #include <ctype.h> #define M_PI 3.14159265358979323846 // MARLIN focal length #define F_X 611.1584754728662600 #define F_Y 614.2198182542969100 #ifdef _EiC #define WIN32 #endif static CvMemStorage* storage = 0; static CvHaarClassifierCascade* cascade = 0; CvVideoWriter* writer = 0; void detect_and_draw( IplImage* image ); int write2file = 0; PTU46 ptu(wxCOM8,wxBAUD_9600); int cx, cy; const char* cascade_name = "haarcascade_frontalface_alt.xml"; /* "haarcascade_profileface.xml";*/ int main( int argc, char** argv ) { CvCapture* capture = 0; IplImage *frame, *frame_copy = 0; int optlen = strlen("--cascade="); const char* input_name; if( argc > 1 && strncmp( argv[1], "--cascade=", optlen ) == 0 ) { cascade_name = argv[1] + optlen; input_name = argc > 2 ? argv[2] : 0; } else { cascade_name = "haarcascade_frontalface_alt2.xml"; //cascade_name = "haarcascade_eye.xml"; input_name = argc > 1 ? argv[1] : 0; } cascade = (CvHaarClassifierCascade*)cvLoad( cascade_name, 0, 0, 0 ); //cascade = cvLoadHaarClassifierCascade("Mouth32_norm", cvSize(32, 28)); if( !cascade ) { fprintf( stderr, "ERROR: Could not load classifier cascade\n" ); fprintf( stderr, "Usage: facedetect --cascade=\"<cascade_path>\" [filename|camera_index]\n" ); return -1; } storage = cvCreateMemStorage(0); if( !input_name || (isdigit(input_name[0]) && input_name[1] == '\0') ) capture = cvCaptureFromCAM( !input_name ? 0 : input_name[0] - '0' ); else capture = cvCaptureFromAVI( input_name ); cvNamedWindow( "result", 1 ); if( capture ) { cvGrabFrame( capture ); frame = cvRetrieveFrame( capture ); cx = frame->width / 2; cy = frame->height / 2; writer = cvCreateVideoWriter( "facce.avi", -1, 10, cvSize(frame->width, frame->height), 1 ); for(;;) { if( !cvGrabFrame( capture )) break; frame = cvRetrieveFrame( capture ); if( !frame ) break; if( !frame_copy ) frame_copy = cvCreateImage( cvSize(frame->width,frame->height), IPL_DEPTH_8U, frame->nChannels ); if( frame->origin == IPL_ORIGIN_TL ) cvCopy( frame, frame_copy, 0 ); else cvFlip( frame, frame_copy, 0 ); detect_and_draw( frame_copy ); if( cvWaitKey( 5 ) >= 0 ) break; } cvReleaseImage( &frame_copy ); cvReleaseCapture( &capture ); cvReleaseVideoWriter( &writer ); } else { const char* filename = input_name ? input_name : (char*)"lena.jpg"; IplImage* image = cvLoadImage( filename, 1 ); if( image ) { detect_and_draw( image ); cvWaitKey(0); cvReleaseImage( &image ); } else { /* assume it is a text file containing the list of the image filenames to be processed - one per line */ FILE* f = fopen( filename, "rt" ); if( f ) { char buf[1000+1]; while( fgets( buf, 1000, f ) ) { int len = (int)strlen(buf); while( len > 0 && isspace(buf[len-1]) ) len--; buf[len] = '\0'; image = cvLoadImage( buf, 1 ); if( image ) { detect_and_draw( image ); cvWaitKey(10); cvReleaseImage( &image ); } } fclose(f); } } } cvDestroyWindow("result"); return 0; } void detect_and_draw( IplImage* img ) { static CvScalar colors[] = { {{0,0,255}}, {{0,128,255}}, {{0,255,255}}, {{0,255,0}}, {{255,128,0}}, {{255,255,0}}, {{255,0,0}}, {{255,0,255}} }; double scale = 1.3; IplImage* gray = cvCreateImage( cvSize(img->width,img->height), 8, 1 ); IplImage* small_img = cvCreateImage( cvSize( cvRound (img->width/scale), cvRound (img->height/scale)), 8, 1 ); int i; cvCvtColor( img, gray, CV_BGR2GRAY ); cvResize( gray, small_img, CV_INTER_LINEAR ); cvEqualizeHist( small_img, small_img ); cvClearMemStorage( storage ); if( cascade ) { double t = (double)cvGetTickCount(); CvSeq* faces = cvHaarDetectObjects( small_img, cascade, storage, 1.1, 20, CV_HAAR_FIND_BIGGEST_OBJECT | CV_HAAR_DO_ROUGH_SEARCH/*CV_HAAR_DO_CANNY_PRUNING*/, cvSize(30, 30) ); t = (double)cvGetTickCount() - t; printf( "detection time = %gms\n", t/((double)cvGetTickFrequency()*1000.) ); for( i = 0; i < (faces ? faces->total : 0); i++ ) { CvRect* r = (CvRect*)cvGetSeqElem( faces, i ); CvPoint center; int radius; center.x = cvRound((r->x + r->width*0.5)*scale); center.y = cvRound((r->y + r->height*0.5)*scale); radius = cvRound((r->width + r->height)*0.25*scale); cvCircle( img, center, radius, colors[i%8], 3, 8, 0 ); //printf("%d\n",(center.x-cx)*(center.x-cx)+(center.y-cy)*(center.y-cy)); if((center.x-cx)*(center.x-cx)+(center.y-cy)*(center.y-cy)>5000) { float dp = ( atan2f(center.x - cx, F_X) * 180 ) / M_PI; float dt = ( atan2f(center.y - cy, F_Y) * 180 ) / M_PI; ptu.setPanTilt(ptu.getPos(PTU46_PAN) - dp, ptu.getPos(PTU46_TILT) - dt, true); } } } cvShowImage( "result", img ); if(write2file) cvWriteFrame( writer, img ); cvReleaseImage( &gray ); cvReleaseImage( &small_img ); }
[ "matia.pizzoli@1ffd000b-a628-0410-9a29-793f135cad17" ]
matia.pizzoli@1ffd000b-a628-0410-9a29-793f135cad17
729863cc66bd7d27ea15b185e1c9124f1fa3951b
4c6574534cc8dd7f582ee98603116b46ab608160
/PhaseJump/Xcode/PhaseJump/PhaseJumpTests/Mocks/MockRenderer.h
df8aa618d74a67b535282e718b06d0eb9db6534f
[ "MIT" ]
permissive
coinbump/PhaseJumpPro
01b1805aac4a8dd0a17feb3ae9a06d76fbf63926
52f806cc7db9ef134a5e1786347c350cb8e2e4c3
refs/heads/main
2023-06-27T13:30:37.192977
2023-06-18T03:25:38
2023-06-18T03:25:38
127,684,651
50
5
null
null
null
null
UTF-8
C++
false
false
362
h
#ifndef PJTESTMOCKRENDERER_H #define PJTESTMOCKRENDERER_H #include "SomeRenderer.h" #include "VectorList.h" namespace PJTest { class MockRenderer : public SomeRenderer { public: VectorList<RenderIntoModel> renderHistory; virtual void RenderInto(RenderIntoModel model) { renderHistory.Add(model); } }; } #endif
[ "coinbump@gmail.com" ]
coinbump@gmail.com
f8e903ebed562b9a934847c0a4b0a89a1e663c58
701b9c3c9dda6fc0ddd49d9b8396b4b4951d565c
/GazeTracker/GazeTracker_Qt/GazeDataProcessing.hpp
2587bb5a222a065dccb7f209fb73225627b1b3ed
[ "MIT" ]
permissive
bernhardrieder/Gaze-Tracker
925b35b27dba0cfe21ada75a24616f4f531a0c39
b468a03cb986a4950ee1d2a49df759e17a80c5cc
refs/heads/master
2020-03-18T13:38:08.471907
2018-05-25T04:12:12
2018-05-25T04:12:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,452
hpp
#pragma once #include "ProcessingUI.hpp" namespace gt { class GazeDataProcessing; enum class GazeDataProcessingState : int { OpenFile = 0, ReadData, CreateVideo, FinishedWithSuccess, FinishedWithError }; class GazeTrackerVideoCreator : public QObject { Q_OBJECT public: GazeTrackerVideoCreator(GazeDataProcessing* parent) : m_Parent(parent), m_StopProcess(false) { } ~GazeTrackerVideoCreator() { }; public slots: void process(); void stop(); signals: void finished(); private: GazeDataProcessing* m_Parent; bool m_StopProcess; void drawCircles(cv::Mat& frame, std::list<std::tuple<int, cv::Point>>& list, int activeFrameCount) const; }; class GazeDataProcessing : public QObject { Q_OBJECT friend class GazeTrackerVideoCreator; public: GazeDataProcessing(QObject* parent = Q_NULLPTR); ~GazeDataProcessing(); void show(); std::string InputFilename; std::string InputFrameDirectory; std::string OutputFilePath = "C:/GazeTracker/Output"; signals: void stateChanged(int); void progress(double); private slots: void stopProcessing() const; private: ProcessingUI* m_processingUI; cv::FileStorage m_fileStorage; std::map<std::string, cv::Point> m_dataMap; gt::DataTrackingXML m_xmlData; GazeTrackerVideoCreator* m_VideoCreator; QThread* m_VideoCreatorThread; void startProcessing(); void openFile(); void readFile(); void createVideo(); }; }
[ "bernhard.rieder@live.at" ]
bernhard.rieder@live.at
752cbd38c7927d06c541b7ae1f2dfeb5d61e4022
b5ddfcaacd7dda7c9e0f68c5ac3f835d423de409
/source/mORMot/SynopseCommit.inc
3a8cf4a13ebb46f0c38425c06be6a1057307632c
[]
no_license
Yang-Ya-Chao/YxDServer
e93f12a201d1a94256658eea258ff65f3c70e8bb
af320e1d8246cb8df40b13f8dd1af6e177efe7f5
refs/heads/master
2023-06-19T07:19:13.119813
2021-07-13T05:59:39
2021-07-13T05:59:39
375,569,546
1
2
null
null
null
null
UTF-8
C++
false
false
12
inc
'1.18.6249'
[ "yyc@yx.com" ]
yyc@yx.com
fdab9d0813203d4e3b429a71d5629aa0d084d0c7
37c502120aba6e719a2977d8ce78c44846adeb63
/C Programs/STAR.CPP
564e8ea893e1507fbab841c4363db837e592ee2d
[]
no_license
Girrajjangid/Computer-Science-Programs
66cdccb1f17bc74893614eb5e02acba7bde14885
8d8c2be72661e42aa12f78fbb6eafdce0f18fe55
refs/heads/master
2020-06-09T23:10:04.027394
2019-11-03T17:24:23
2019-11-03T17:24:23
193,525,230
3
0
null
null
null
null
UTF-8
C++
false
false
245
cpp
#include<stdio.h> #include<conio.h> void main() { int i,j,n; clrscr(); printf("enter the value of n\n "); scanf("%d",&n); for(i=1;i<=n;i++) { for(j=1;j<=n-i;j++) {printf(" ");} for(j=1;j<=2*i-1;j++) {printf("*");} printf("\n"); } getch(); }
[ "girraj.jangid.14581@gmail.com" ]
girraj.jangid.14581@gmail.com
64684310d7da0e137a429c20295770e11f7f824f
b8b0417c21e71ae3fc59498c8a9963ee306d2dbf
/Algorithm/Huffman.cpp
bcb3363defd5d71e485e224521116e84c9f14527
[]
no_license
YanB25/MyToyCode
27149bb0d099b75189d9a9dfc4b2034b1c57a014
fdb9db2b9158bc856c19d23228260f33e8c1ff5b
refs/heads/master
2021-01-17T21:03:47.801402
2018-01-10T03:55:57
2018-01-10T03:55:57
84,158,175
1
0
null
null
null
null
UTF-8
C++
false
false
898
cpp
#include <iostream> #include <set> #include <utility> #include <string> #include <vector> using namespace std; vector<string> codes; bool min(int l, int r) { return l < r ? l : r;} int main() { int n; cin >> n; codes.resize(256); set<pair<int, string>> s; for (int i = 0; i < n; ++i) { char c; int f; cin >> c >> f; s.insert(pair<int, string>(f, string(1, c))); } while (s.size() != 1) { auto t1 = s.begin(); s.erase(s.begin()); auto t2 = s.begin(); s.erase(s.begin()); for (auto i : t1->second) { codes[i] = "0" + codes[i]; } for (auto i : t2->second) { codes[i] = "1" + codes[i]; } s.insert(pair<int, string>(t1->first+t2->first, t1->second + t2->second)); } for (int i = 'a'; i <= 'z'; ++i) { cout << char(i) << "\t" << codes[i] << endl; } }
[ "442826556@qq.con" ]
442826556@qq.con
296714fef02756889e2a33b2e0adafe3844672b9
72f2515c4cef9e02c27452b32269ca403f76c69a
/src/modules/MeasureTool/MeasureToolCore/OverlayUI.h
5f1b7be39d303c06c185a7b29ddb263b35acc517
[ "LicenseRef-scancode-generic-cla", "MIT", "BSL-1.0", "Unlicense" ]
permissive
microsoft/PowerToys
4625ffc4c513265094bf9e0f490753a54aabeaa0
3244ba989921dd26dd32be75021ed68c9cfcdda9
refs/heads/main
2023-08-17T00:10:06.645243
2023-08-16T16:31:10
2023-08-16T16:31:10
184,456,251
103,306
7,187
MIT
2023-09-14T16:52:26
2019-05-01T17:44:02
C#
UTF-8
C++
false
false
2,142
h
#pragma once #include "DxgiAPI.h" #include "D2DState.h" #include "ToolState.h" #include <common/display/monitors.h> #include <common/utils/serialized.h> class OverlayUIState final { template<typename StateT, typename TickFuncT> OverlayUIState(const DxgiAPI* dxgiAPI, StateT& toolState, TickFuncT tickFunc, const CommonState& commonState, HWND window); Box _monitorArea; HWND _window = {}; const CommonState& _commonState; D2DState _d2dState; std::function<void()> _tickFunc; std::thread _uiThread; template<typename ToolT, typename TickFuncT> static std::unique_ptr<OverlayUIState> CreateInternal(const DxgiAPI* dxgi, ToolT& toolState, TickFuncT tickFunc, CommonState& commonState, const wchar_t* toolWindowClassName, void* windowParam, const MonitorInfo& monitor, const bool excludeFromCapture); public: OverlayUIState(OverlayUIState&&) noexcept = default; ~OverlayUIState(); static std::unique_ptr<OverlayUIState> Create(const DxgiAPI* dxgi, BoundsToolState& toolState, CommonState& commonState, const MonitorInfo& monitor); static std::unique_ptr<OverlayUIState> Create(const DxgiAPI* dxgi, Serialized<MeasureToolState>& toolState, CommonState& commonState, const MonitorInfo& monitor); inline HWND overlayWindowHandle() const { return _window; } void RunUILoop(); };
[ "noreply@github.com" ]
noreply@github.com
8f730c3410d99867510c6334ea82e31d690bfd7e
2fa880c8a06d635eb11ccf9e64b77382e3e825fa
/FIBONASI.cpp
956cb1e9c4059f4a3c60aa3865f33b789270c0c2
[]
no_license
AtomicOrbital/SPOJ_PTIT
469e2acf66d4cd8851cc653c0df78f7c5f9d2625
d80395a87a13b564bfa370bb299e1216b3781a9e
refs/heads/main
2023-06-06T04:53:27.359301
2021-06-21T17:27:03
2021-06-21T17:27:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,215
cpp
#include<bits/stdc++.h> #include<string> #include<vector> #define alphaa "abcdefghijklmnopqrstuvwxyz" #define ALPHAA "ABCDEFGHIJKLMNOPQRSTUVWXYZ" #define f(i,a,b) for(int i=a;i<=b;i++) #define f1(i,n) for(int i=1;i<=n;i++) #define f0(i,n) for(int i=0;i<n;i++) #define sp(x) cout<<x<<" "; #define en(x) cout<<x<<endl; using namespace std; typedef long long ll; const int N=1e6+3; const int MOD=1000000007; struct mtrx { ll c[2][2]; mtrx() { c[0][0]=0; c[0][1]=1; c[1][0]=1; c[1][1]=1; } }; mtrx operator*(mtrx a,mtrx b) { mtrx res; for(int i=0;i<=1;i++) { for(int j=0;j<=1;j++) { res.c[i][j]=0; for(int k=0;k<=1;k++) { res.c[i][j]=(res.c[i][j]+a.c[i][k]*b.c[k][j])%MOD; } } } return res; } mtrx poww(mtrx a,ll n) { if(n==1) return a; if(n%2==1) return poww(a,n-1)*a; mtrx res=poww(a,n/2); return res*res; } void xuly() { ll n; cin>>n; mtrx a; a=poww(a,n); cout<<a.c[0][1]; } int main() { ios::sync_with_stdio(false); cin.tie(0); int t=1; //cin>>t; while(t--) xuly(); return 0; }
[ "noreply@github.com" ]
noreply@github.com
eb7d52d9a86656bddcbe143af5f3afa2c28b636c
718adecdaead55fa20126e273e4401a33a139e84
/LeetCode/FindtheMostCompetitiveSubsequence/main.cxx
3cea989cd32adc914a01390b51c82139baac3e8e
[]
no_license
hjw21century/Algorithm
b3b6f3c8ab3272a75eb27fdbfb0f259e5e54c218
415ee942770924bb7a80935bdd7345eda03975b8
refs/heads/master
2023-05-03T00:36:22.802855
2021-05-20T08:40:17
2021-05-20T08:40:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,375
cxx
#include <bits/stdc++.h> #include <gtest/gtest.h> using namespace std; class Solution { public: vector<int> mostCompetitive(vector<int> &nums, int k) { // 0 1 2 3 4 5 size-k-1,size-k,size-k+1, ..., size-2 ,size-1 memo = vector<int>(nums.size()); { if (nums.size() > k) { memo[nums.size() - k - 1] = nums.size() - k - 1; int minL = nums[nums.size() - k - 1]; for (int i = nums.size() - k - 2; i >= 0; i--) { if (nums[i] <= minL) { minL = nums[i]; memo[i] = i; } else { memo[i] = memo[i + 1]; } } } } { memo[nums.size() - k] = nums.size() - k; int minR = nums[nums.size() - k]; for (int i = nums.size() - k + 1; i < nums.size(); i++) { if (nums[i] < minR) { minR = nums[i]; memo[i] = i; } else { memo[i] = memo[i - 1]; } } } vector<int> ret(k); int left = 0, right = nums.size() - k; for (int i = 0; i < k; i++, right++) { int idx = pick(nums, left, right, k); ret[i] = nums[idx]; left = idx + 1; } return ret; } private: vector<int> memo; int min_id(const vector<int> &nums, const int &left, const int &right) { int id = left; int min_n = nums[left]; for (int i = left; i <= right; i++) { if (nums[i] < min_n) { min_n = nums[i]; id = i; } } return id; } int pick(const vector<int> &nums, const int &left, const int &right, const int &k) { int mid = nums.size() - k; if (left <= mid - 1 && right >= mid) { int id_l = memo[left]; int id_r = memo[right]; return nums[id_l] <= nums[id_r] ? id_l : id_r; } return min_id(nums, left, right); } }; struct T { }; TEST(Solution, test) { T ts[] = { { }, }; Solution solution; for (T t : ts) { } } int main() { testing::InitGoogleTest(); return RUN_ALL_TESTS(); }
[ "slarsar@yandex.com" ]
slarsar@yandex.com
b7b9d67b98f5899e2f9a99410b13f93c2d83a18b
0cfd073faa8dd5afc96373e1b1db29586fb70d20
/GaUpdater/stdafx.cpp
996660f6c5203c20d86b0e238de55cfd5015ccbe
[ "MIT" ]
permissive
ha11owed/gaupdater
4f7f5ada7521bd28955388b364e4e5733f76fb9a
449b9f0a7079f4f8478696d5982a14ae3a70dddc
refs/heads/master
2021-05-02T07:37:20.932279
2016-09-22T14:00:41
2016-09-22T14:00:41
33,974,296
1
0
null
null
null
null
UTF-8
C++
false
false
203
cpp
// stdafx.cpp : source file that includes just the standard includes // GaUpdater.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h"
[ "slaninacuceapa@gmail.com" ]
slaninacuceapa@gmail.com
dd5d44b1335fa07830916c8939734161fa65b67d
ed997b3a8723cc9e77787c1d868f9300b0097473
/boost/test/data/generators.hpp
8ebfb06b52161299ccbca8dc3aa1f2352b0c5927
[ "BSL-1.0" ]
permissive
juslee/boost-svn
7ddb99e2046e5153e7cb5680575588a9aa8c79b2
6d5a03c1f5ed3e2b23bd0f3ad98d13ff33d4dcbb
refs/heads/master
2023-04-13T11:00:16.289416
2012-11-16T11:14:39
2012-11-16T11:14:39
6,734,455
0
0
BSL-1.0
2023-04-03T23:13:08
2012-11-17T11:21:17
C++
UTF-8
C++
false
false
729
hpp
// (C) Copyright Gennadiy Rozental 2011-2012. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org/libs/test for the library home page. // // File : $RCSfile$ // // Version : $Revision$ // // Description : defines specific generators // *************************************************************************** #ifndef BOOST_TEST_DATA_MONOMORPHIC_GENERATORS_HPP_112011GER #define BOOST_TEST_DATA_MONOMORPHIC_GENERATORS_HPP_112011GER // Boost.Test #include <boost/test/data/monomorphic/generators/xrange.hpp> #endif // BOOST_TEST_DATA_MONOMORPHIC_GENERATORS_HPP_112011GER
[ "rogeeff@b8fc166d-592f-0410-95f2-cb63ce0dd405" ]
rogeeff@b8fc166d-592f-0410-95f2-cb63ce0dd405
3dec7f41519bfb446e8e4a1cb28538cf2fdae3fb
71f393f8b98f8212d2a657b92720b6d5ddc42a32
/src/perf/lib/quicmain.cpp
8ec863849a64b92da36a63721254713617c3fcad
[ "MIT" ]
permissive
flying1314/msquic
510da948b19655142de92ae18ae9d18d0bde9b46
d05bfe77e83524e9b019e3560469db4478506b5d
refs/heads/master
2022-11-30T19:54:47.626895
2020-08-05T20:57:35
2020-08-05T20:57:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,248
cpp
/*++ Copyright (c) Microsoft Corporation. Licensed under the MIT License. Abstract: QUIC Perf Main execution engine. --*/ #include "PerfHelpers.h" #include "ThroughputServer.h" #include "ThroughputClient.h" #ifdef QUIC_CLOG #include "quicmain.cpp.clog.h" #endif const QuicApiTable* MsQuic; PerfBase* TestToRun; static void PrintHelp( ) { WriteOutput("Usage: quicperf -TestName:[Throughput|] [options]\n" \ "\n" \ " -ServerMode:<1:0> default: '0'\n" \ "\n\n" \ "Run a test without arguments to see it's specific help\n" ); } QUIC_STATUS QuicMainStart( _In_ int argc, _In_reads_(argc) _Null_terminated_ char* argv[], _In_ QUIC_EVENT StopEvent, _In_ PerfSelfSignedConfiguration* SelfSignedConfig ) { const char* TestName = GetValue(argc, argv, "TestName"); if (!TestName) { WriteOutput("Must have a TestName specified. Ex: -TestName:Throughput\n"); PrintHelp(); return QUIC_STATUS_INVALID_PARAMETER; } uint8_t ServerMode = 0; TryGetValue(argc, argv, "ServerMode", &ServerMode); QUIC_STATUS Status; MsQuic = new QuicApiTable; if (QUIC_FAILED(Status = MsQuic->InitStatus())) { delete MsQuic; MsQuic = nullptr; return Status; } if (IsValue(TestName, "Throughput")) { if (ServerMode) { TestToRun = new ThroughputServer(SelfSignedConfig); } else { TestToRun = new ThroughputClient; } } else { delete MsQuic; return QUIC_STATUS_INVALID_PARAMETER; } if (TestToRun != nullptr) { Status = TestToRun->Init(argc, argv); if (QUIC_SUCCEEDED(Status)) { Status = TestToRun->Start(StopEvent); if (QUIC_SUCCEEDED(Status)) { return QUIC_STATUS_SUCCESS; } } } else { Status = QUIC_STATUS_OUT_OF_MEMORY; } delete TestToRun; delete MsQuic; return Status; } QUIC_STATUS QuicMainStop( _In_ int Timeout ) { if (TestToRun == nullptr) { return QUIC_STATUS_SUCCESS; } QUIC_STATUS Status = TestToRun->Wait(Timeout); delete TestToRun; delete MsQuic; return Status; }
[ "noreply@github.com" ]
noreply@github.com
1f4f188225319281482f26b50047342054ee8061
282dce13f4c01540bb5c926d62b3bdb1ca9a0250
/Data Structures/Tree_huffman_decoding.cpp
8031a0676dffd9e3f5c56a0f6682413cb307de33
[]
no_license
Mayank-44/Data-Structures
4e48fe5cb98fe387c2e94184c9e2febcb6cd365b
cc91705015c9a72f5cda1c34ebdc7c104707b149
refs/heads/master
2021-04-03T04:23:16.570144
2019-05-21T05:35:28
2019-05-21T05:35:28
124,723,189
0
1
null
2018-03-20T23:01:11
2018-03-11T04:31:49
C++
UTF-8
C++
false
false
593
cpp
#include <string.h> /* The structure of the node is typedef struct node { int freq; char data; node * left; node * right; }node; */ void decode_huff(node * root,string s) { int i=0; node *tmp=root; while(i<=s.length()) { if(tmp->data!='\0') { cout<<tmp->data; tmp=root; } else { if(s[i]=='0') tmp=tmp->left; else tmp=tmp->right; i++; } } }
[ "37243315+Mayank-44@users.noreply.github.com" ]
37243315+Mayank-44@users.noreply.github.com
1ec217390cece762a4104f65f5c35620fc78e894
aed64c91a1428e2a2910def471c4ea1413e66b2f
/ReactCommon/react/renderer/graphics/conversions.h
8ce4f341f79696e9f82e10c8f8dea76f6a321d27
[ "MIT", "CC-BY-4.0", "CC-BY-SA-4.0", "CC-BY-NC-SA-4.0" ]
permissive
mikaoelitiana/react-native
e631a9ffe956ab57570ebcdaca0d24d34ff40b0d
7f2dd1d49cc3c0bf5e24fdb37f6457151c1f06c4
refs/heads/master
2023-02-11T11:36:37.056518
2023-02-05T14:49:08
2023-02-05T14:49:08
130,375,540
1
0
MIT
2023-02-04T22:56:11
2018-04-20T14:47:12
JavaScript
UTF-8
C++
false
false
8,091
h
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #pragma once #include <butter/map.h> #include <glog/logging.h> #include <react/debug/react_native_assert.h> #include <react/renderer/core/PropsParserContext.h> #include <react/renderer/core/RawProps.h> #include <react/renderer/graphics/Color.h> #include <react/renderer/graphics/PlatformColorParser.h> #include <react/renderer/graphics/Point.h> #include <react/renderer/graphics/Rect.h> #include <react/renderer/graphics/RectangleCorners.h> #include <react/renderer/graphics/RectangleEdges.h> #include <react/renderer/graphics/Size.h> namespace facebook { namespace react { #pragma mark - Color inline void fromRawValue( const PropsParserContext &context, const RawValue &value, SharedColor &result) { ColorComponents colorComponents = {0, 0, 0, 0}; if (value.hasType<int>()) { auto argb = (int64_t)value; auto ratio = 255.f; colorComponents.alpha = ((argb >> 24) & 0xFF) / ratio; colorComponents.red = ((argb >> 16) & 0xFF) / ratio; colorComponents.green = ((argb >> 8) & 0xFF) / ratio; colorComponents.blue = (argb & 0xFF) / ratio; } else if (value.hasType<std::vector<float>>()) { auto items = (std::vector<float>)value; auto length = items.size(); react_native_assert(length == 3 || length == 4); colorComponents.red = items.at(0); colorComponents.green = items.at(1); colorComponents.blue = items.at(2); colorComponents.alpha = length == 4 ? items.at(3) : 1.0f; } else { colorComponents = parsePlatformColor(context, value); } result = colorFromComponents(colorComponents); } #ifdef ANDROID inline int toAndroidRepr(const SharedColor &color) { return *color; } #endif inline std::string toString(const SharedColor &value) { ColorComponents components = colorComponentsFromColor(value); auto ratio = 255.f; return "rgba(" + folly::to<std::string>(round(components.red * ratio)) + ", " + folly::to<std::string>(round(components.green * ratio)) + ", " + folly::to<std::string>(round(components.blue * ratio)) + ", " + folly::to<std::string>(round(components.alpha * ratio)) + ")"; } #pragma mark - Geometry inline void fromRawValue( const PropsParserContext &context, const RawValue &value, Point &result) { if (value.hasType<butter::map<std::string, Float>>()) { auto map = (butter::map<std::string, Float>)value; for (const auto &pair : map) { if (pair.first == "x") { result.x = pair.second; } else if (pair.first == "y") { result.y = pair.second; } } return; } react_native_assert(value.hasType<std::vector<Float>>()); if (value.hasType<std::vector<Float>>()) { auto array = (std::vector<Float>)value; react_native_assert(array.size() == 2); if (array.size() >= 2) { result = {array.at(0), array.at(1)}; } else { result = {0, 0}; LOG(ERROR) << "Unsupported Point vector size: " << array.size(); } } else { LOG(ERROR) << "Unsupported Point type"; } } inline void fromRawValue( const PropsParserContext &context, const RawValue &value, Size &result) { if (value.hasType<butter::map<std::string, Float>>()) { auto map = (butter::map<std::string, Float>)value; for (const auto &pair : map) { if (pair.first == "width") { result.width = pair.second; } else if (pair.first == "height") { result.height = pair.second; } else { LOG(ERROR) << "Unsupported Size map key: " << pair.first; react_native_assert(false); } } return; } react_native_assert(value.hasType<std::vector<Float>>()); if (value.hasType<std::vector<Float>>()) { auto array = (std::vector<Float>)value; react_native_assert(array.size() == 2); if (array.size() >= 2) { result = {array.at(0), array.at(1)}; } else { result = {0, 0}; LOG(ERROR) << "Unsupported Size vector size: " << array.size(); } } else { LOG(ERROR) << "Unsupported Size type"; } } inline void fromRawValue( const PropsParserContext &context, const RawValue &value, EdgeInsets &result) { if (value.hasType<Float>()) { auto number = (Float)value; result = {number, number, number, number}; return; } if (value.hasType<butter::map<std::string, Float>>()) { auto map = (butter::map<std::string, Float>)value; for (const auto &pair : map) { if (pair.first == "top") { result.top = pair.second; } else if (pair.first == "left") { result.left = pair.second; } else if (pair.first == "bottom") { result.bottom = pair.second; } else if (pair.first == "right") { result.right = pair.second; } else { LOG(ERROR) << "Unsupported EdgeInsets map key: " << pair.first; react_native_assert(false); } } return; } react_native_assert(value.hasType<std::vector<Float>>()); if (value.hasType<std::vector<Float>>()) { auto array = (std::vector<Float>)value; react_native_assert(array.size() == 4); if (array.size() >= 4) { result = {array.at(0), array.at(1), array.at(2), array.at(3)}; } else { result = {0, 0, 0, 0}; LOG(ERROR) << "Unsupported EdgeInsets vector size: " << array.size(); } } else { LOG(ERROR) << "Unsupported EdgeInsets type"; } } inline void fromRawValue( const PropsParserContext &context, const RawValue &value, CornerInsets &result) { if (value.hasType<Float>()) { auto number = (Float)value; result = {number, number, number, number}; return; } if (value.hasType<butter::map<std::string, Float>>()) { auto map = (butter::map<std::string, Float>)value; for (const auto &pair : map) { if (pair.first == "topLeft") { result.topLeft = pair.second; } else if (pair.first == "topRight") { result.topRight = pair.second; } else if (pair.first == "bottomLeft") { result.bottomLeft = pair.second; } else if (pair.first == "bottomRight") { result.bottomRight = pair.second; } else { LOG(ERROR) << "Unsupported CornerInsets map key: " << pair.first; react_native_assert(false); } } return; } react_native_assert(value.hasType<std::vector<Float>>()); if (value.hasType<std::vector<Float>>()) { auto array = (std::vector<Float>)value; react_native_assert(array.size() == 4); if (array.size() >= 4) { result = {array.at(0), array.at(1), array.at(2), array.at(3)}; } else { LOG(ERROR) << "Unsupported CornerInsets vector size: " << array.size(); } } // Error case - we should only here if all other supported cases fail // In dev we would crash on assert before this point result = {0, 0, 0, 0}; LOG(ERROR) << "Unsupported CornerInsets type"; } inline std::string toString(const Point &point) { return "{" + folly::to<std::string>(point.x) + ", " + folly::to<std::string>(point.y) + "}"; } inline std::string toString(const Size &size) { return "{" + folly::to<std::string>(size.width) + ", " + folly::to<std::string>(size.height) + "}"; } inline std::string toString(const Rect &rect) { return "{" + toString(rect.origin) + ", " + toString(rect.size) + "}"; } inline std::string toString(const EdgeInsets &edgeInsets) { return "{" + folly::to<std::string>(edgeInsets.left) + ", " + folly::to<std::string>(edgeInsets.top) + ", " + folly::to<std::string>(edgeInsets.right) + ", " + folly::to<std::string>(edgeInsets.bottom) + "}"; } inline std::string toString(const CornerInsets &cornerInsets) { return "{" + folly::to<std::string>(cornerInsets.topLeft) + ", " + folly::to<std::string>(cornerInsets.topRight) + ", " + folly::to<std::string>(cornerInsets.bottomLeft) + ", " + folly::to<std::string>(cornerInsets.bottomRight) + "}"; } } // namespace react } // namespace facebook
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
254c0387a1d87958df70c9f49ae805dc0a1cf243
9f14621793a39a930c0831db84c9309dcc793e20
/library/src/Global.cpp
f7feaa4f5ae80f59d7a300c0777e90433ecd5004
[]
no_license
huanghao870620/myproj
3d8d75d30a630b33b86b65e354407d0c98731d8b
b2a5aa33a93312399a71a7869376d27e181689ee
refs/heads/master
2020-04-04T05:40:24.350288
2017-02-25T06:17:52
2017-02-25T06:17:52
52,357,318
0
0
null
null
null
null
UTF-8
C++
false
false
173
cpp
#include "Global.h" Global::Global(int weight, std::string & name) { this->weight = weight; this->name = name; } Global::~Global() { std::cout << "1" << std::endl; }
[ "huanghao870620@hotmail.com" ]
huanghao870620@hotmail.com
0dd2833e4a436ef236db85d06c61029614e9cb8d
c78dbaaf5301ae5380a06745d2017891eda5c9ff
/src/wallet/rpcwallet.cpp
ab996261e4d3e4df8e8cf3964e4863203f7a11e5
[ "MIT" ]
permissive
superdigitalcoin-project/superdigitalcoin
6c49746707a26d6e945c6c6efe245ccf1ec3b4c9
f77a76bb74bd38be58db10a1635bdaa017f5baa0
refs/heads/master
2020-06-25T17:26:44.593043
2019-07-29T07:43:56
2019-07-29T07:43:56
199,377,237
0
0
null
null
null
null
UTF-8
C++
false
false
147,212
cpp
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "amount.h" #include "base58.h" #include "chain.h" #include "consensus/validation.h" #include "core_io.h" #include "init.h" #include "validation.h" #include "net.h" #include "policy/policy.h" #include "policy/rbf.h" #include "rpc/server.h" #include "script/sign.h" #include "timedata.h" #include "util.h" #include "utilmoneystr.h" #include "wallet.h" #include "walletdb.h" #include <stdint.h> #include <boost/assign/list_of.hpp> #include <univalue.h> using namespace std; int64_t nWalletUnlockTime; static CCriticalSection cs_nWalletUnlockTime; std::string HelpRequiringPassphrase() { return pwalletMain && pwalletMain->IsCrypted() ? "\nRequires wallet passphrase to be set with walletpassphrase call." : ""; } bool EnsureWalletIsAvailable(bool avoidException) { if (!pwalletMain) { if (!avoidException) throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (disabled)"); else return false; } return true; } 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, UniValue& 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", mapBlockIndex[wtx.hashBlock]->GetBlockTime())); } else { entry.push_back(Pair("trusted", wtx.IsTrusted())); } uint256 hash = wtx.GetHash(); entry.push_back(Pair("txid", hash.GetHex())); UniValue conflicts(UniValue::VARR); BOOST_FOREACH(const uint256& conflict, wtx.GetConflicts()) conflicts.push_back(conflict.GetHex()); entry.push_back(Pair("walletconflicts", conflicts)); entry.push_back(Pair("time", wtx.GetTxTime())); entry.push_back(Pair("timereceived", (int64_t)wtx.nTimeReceived)); // Add opt-in RBF status std::string rbfStatus = "no"; if (confirms <= 0) { LOCK(mempool.cs); RBFTransactionState rbfState = IsRBFOptIn(wtx, mempool); if (rbfState == RBF_TRANSACTIONSTATE_UNKNOWN) rbfStatus = "unknown"; else if (rbfState == RBF_TRANSACTIONSTATE_REPLACEABLE_BIP125) rbfStatus = "yes"; } entry.push_back(Pair("bip125-replaceable", rbfStatus)); BOOST_FOREACH(const PAIRTYPE(string,string)& item, wtx.mapValue) entry.push_back(Pair(item.first, item.second)); } string AccountFromValue(const UniValue& value) { string strAccount = value.get_str(); if (strAccount == "*") throw JSONRPCError(RPC_WALLET_INVALID_ACCOUNT_NAME, "Invalid account name"); return strAccount; } UniValue getnewaddress(const JSONRPCRequest& request) { if (!EnsureWalletIsAvailable(request.fHelp)) return NullUniValue; if (request.fHelp || request.params.size() > 1) throw runtime_error( "getnewaddress ( \"account\" )\n" "\nReturns a new SuperDigitalCoin address for receiving payments.\n" "If 'account' is specified (DEPRECATED), it is added to the address book \n" "so payments received with the address will be credited to 'account'.\n" "\nArguments:\n" "1. \"account\" (string, optional) DEPRECATED. The account name for the address to be linked to. If not provided, the default account \"\" is used. It can also be set to the empty string \"\" to represent the default account. The account does not need to exist, it will be created if there is no account by the given name.\n" "\nResult:\n" "\"address\" (string) The new superdigitalcoin address\n" "\nExamples:\n" + HelpExampleCli("getnewaddress", "") + HelpExampleRpc("getnewaddress", "") ); LOCK2(cs_main, pwalletMain->cs_wallet); // Parse the account first so we don't generate a key if there's an error string strAccount; if (request.params.size() > 0) strAccount = AccountFromValue(request.params[0]); if (!pwalletMain->IsLocked()) pwalletMain->TopUpKeyPool(); // Generate a new key that is added to wallet CPubKey newKey; if (!pwalletMain->GetKeyFromPool(newKey)) throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first"); CKeyID keyID = newKey.GetID(); pwalletMain->SetAddressBook(keyID, strAccount, "receive"); return CBitcoinAddress(keyID).ToString(); } CBitcoinAddress GetAccountAddress(string strAccount, bool bForceNew=false) { CPubKey pubKey; if (!pwalletMain->GetAccountPubkey(pubKey, strAccount, bForceNew)) { throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first"); } return CBitcoinAddress(pubKey.GetID()); } UniValue getaccountaddress(const JSONRPCRequest& request) { if (!EnsureWalletIsAvailable(request.fHelp)) return NullUniValue; if (request.fHelp || request.params.size() != 1) throw runtime_error( "getaccountaddress \"account\"\n" "\nDEPRECATED. Returns the current SuperDigitalCoin address for receiving payments to this account.\n" "\nArguments:\n" "1. \"account\" (string, required) The account name for the address. It can also be set to the empty string \"\" to represent the default account. The account does not need to exist, it will be created and a new address created if there is no account by the given name.\n" "\nResult:\n" "\"address\" (string) The account superdigitalcoin address\n" "\nExamples:\n" + HelpExampleCli("getaccountaddress", "") + HelpExampleCli("getaccountaddress", "\"\"") + HelpExampleCli("getaccountaddress", "\"myaccount\"") + HelpExampleRpc("getaccountaddress", "\"myaccount\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); // Parse the account first so we don't generate a key if there's an error string strAccount = AccountFromValue(request.params[0]); UniValue ret(UniValue::VSTR); ret = GetAccountAddress(strAccount).ToString(); return ret; } UniValue getrawchangeaddress(const JSONRPCRequest& request) { if (!EnsureWalletIsAvailable(request.fHelp)) return NullUniValue; if (request.fHelp || request.params.size() > 1) throw runtime_error( "getrawchangeaddress\n" "\nReturns a new SuperDigitalCoin address, for receiving change.\n" "This is for use with raw transactions, NOT normal use.\n" "\nResult:\n" "\"address\" (string) The address\n" "\nExamples:\n" + HelpExampleCli("getrawchangeaddress", "") + HelpExampleRpc("getrawchangeaddress", "") ); LOCK2(cs_main, pwalletMain->cs_wallet); if (!pwalletMain->IsLocked()) pwalletMain->TopUpKeyPool(); CReserveKey reservekey(pwalletMain); CPubKey vchPubKey; if (!reservekey.GetReservedKey(vchPubKey)) throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first"); reservekey.KeepKey(); CKeyID keyID = vchPubKey.GetID(); return CBitcoinAddress(keyID).ToString(); } UniValue setaccount(const JSONRPCRequest& request) { if (!EnsureWalletIsAvailable(request.fHelp)) return NullUniValue; if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) throw runtime_error( "setaccount \"address\" \"account\"\n" "\nDEPRECATED. Sets the account associated with the given address.\n" "\nArguments:\n" "1. \"address\" (string, required) The superdigitalcoin address to be associated with an account.\n" "2. \"account\" (string, required) The account to assign the address to.\n" "\nExamples:\n" + HelpExampleCli("setaccount", "\"SJuet69CPrXJV48v2AsjQWmcF3pmWVkB55\" \"tabby\"") + HelpExampleRpc("setaccount", "\"SJuet69CPrXJV48v2AsjQWmcF3pmWVkB55\", \"tabby\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); CBitcoinAddress address(request.params[0].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid SuperDigitalCoin address"); string strAccount; if (request.params.size() > 1) strAccount = AccountFromValue(request.params[1]); // Only add the account if the address is yours. if (IsMine(*pwalletMain, address.Get())) { // 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()].name; if (address == GetAccountAddress(strOldAccount)) GetAccountAddress(strOldAccount, true); } pwalletMain->SetAddressBook(address.Get(), strAccount, "receive"); } else throw JSONRPCError(RPC_MISC_ERROR, "setaccount can only be used with own address"); return NullUniValue; } UniValue getaccount(const JSONRPCRequest& request) { if (!EnsureWalletIsAvailable(request.fHelp)) return NullUniValue; if (request.fHelp || request.params.size() != 1) throw runtime_error( "getaccount \"address\"\n" "\nDEPRECATED. Returns the account associated with the given address.\n" "\nArguments:\n" "1. \"address\" (string, required) The superdigitalcoin address for account lookup.\n" "\nResult:\n" "\"accountname\" (string) the account address\n" "\nExamples:\n" + HelpExampleCli("getaccount", "\"SJuet69CPrXJV48v2AsjQWmcF3pmWVkB55\"") + HelpExampleRpc("getaccount", "\"SJuet69CPrXJV48v2AsjQWmcF3pmWVkB55\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); CBitcoinAddress address(request.params[0].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid SuperDigitalCoin address"); string strAccount; map<CTxDestination, CAddressBookData>::iterator mi = pwalletMain->mapAddressBook.find(address.Get()); if (mi != pwalletMain->mapAddressBook.end() && !(*mi).second.name.empty()) strAccount = (*mi).second.name; return strAccount; } UniValue getaddressesbyaccount(const JSONRPCRequest& request) { if (!EnsureWalletIsAvailable(request.fHelp)) return NullUniValue; if (request.fHelp || request.params.size() != 1) throw runtime_error( "getaddressesbyaccount \"account\"\n" "\nDEPRECATED. Returns the list of addresses for the given account.\n" "\nArguments:\n" "1. \"account\" (string, required) The account name.\n" "\nResult:\n" "[ (json array of string)\n" " \"address\" (string) a superdigitalcoin address associated with the given account\n" " ,...\n" "]\n" "\nExamples:\n" + HelpExampleCli("getaddressesbyaccount", "\"tabby\"") + HelpExampleRpc("getaddressesbyaccount", "\"tabby\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); string strAccount = AccountFromValue(request.params[0]); // Find all addresses that have the given account UniValue ret(UniValue::VARR); BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, CAddressBookData)& item, pwalletMain->mapAddressBook) { const CBitcoinAddress& address = item.first; const string& strName = item.second.name; if (strName == strAccount) ret.push_back(address.ToString()); } return ret; } static void SendMoney(const CTxDestination &address, CAmount nValue, bool fSubtractFeeFromAmount, CWalletTx& wtxNew) { CAmount curBalance = pwalletMain->GetBalance(); // Check amount if (nValue <= 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid amount"); if (nValue > curBalance) throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Insufficient funds"); if (pwalletMain->GetBroadcastTransactions() && !g_connman) throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); // Parse Bitcoin address CScript scriptPubKey = GetScriptForDestination(address); // Create and send the transaction CReserveKey reservekey(pwalletMain); CAmount nFeeRequired; std::string strError; vector<CRecipient> vecSend; int nChangePosRet = -1; CRecipient recipient = {scriptPubKey, nValue, fSubtractFeeFromAmount}; vecSend.push_back(recipient); if (!pwalletMain->CreateTransaction(vecSend, wtxNew, reservekey, nFeeRequired, nChangePosRet, strError)) { if (!fSubtractFeeFromAmount && nValue + nFeeRequired > curBalance) strError = strprintf("Error: This transaction requires a transaction fee of at least %s", FormatMoney(nFeeRequired)); throw JSONRPCError(RPC_WALLET_ERROR, strError); } CValidationState state; if (!pwalletMain->CommitTransaction(wtxNew, reservekey, g_connman.get(), state)) { strError = strprintf("Error: The transaction was rejected! Reason given: %s", state.GetRejectReason()); throw JSONRPCError(RPC_WALLET_ERROR, strError); } } UniValue sendtoaddress(const JSONRPCRequest& request) { if (!EnsureWalletIsAvailable(request.fHelp)) return NullUniValue; if (request.fHelp || request.params.size() < 2 || request.params.size() > 5) throw runtime_error( "sendtoaddress \"address\" amount ( \"comment\" \"comment_to\" subtractfeefromamount )\n" "\nSend an amount to a given address.\n" + HelpRequiringPassphrase() + "\nArguments:\n" "1. \"address\" (string, required) The superdigitalcoin address to send to.\n" "2. \"amount\" (numeric or string, required) The amount in " + CURRENCY_UNIT + " to send. eg 0.1\n" "3. \"comment\" (string, optional) A comment used to store what the transaction is for. \n" " This is not part of the transaction, just kept in your wallet.\n" "4. \"comment_to\" (string, optional) A comment to store the name of the person or organization \n" " to which you're sending the transaction. This is not part of the \n" " transaction, just kept in your wallet.\n" "5. subtractfeefromamount (boolean, optional, default=false) The fee will be deducted from the amount being sent.\n" " The recipient will receive less superdigitalcoins than you enter in the amount field.\n" "\nResult:\n" "\"txid\" (string) The transaction id.\n" "\nExamples:\n" + HelpExampleCli("sendtoaddress", "\"SJuet69CPrXJV48v2AsjQWmcF3pmWVkB55\" 0.1") + HelpExampleCli("sendtoaddress", "\"SJuet69CPrXJV48v2AsjQWmcF3pmWVkB55\" 0.1 \"donation\" \"seans outpost\"") + HelpExampleCli("sendtoaddress", "\"SJuet69CPrXJV48v2AsjQWmcF3pmWVkB55\" 0.1 \"\" \"\" true") + HelpExampleRpc("sendtoaddress", "\"SJuet69CPrXJV48v2AsjQWmcF3pmWVkB55\", 0.1, \"donation\", \"seans outpost\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); CBitcoinAddress address(request.params[0].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid SuperDigitalCoin address"); // Amount CAmount nAmount = AmountFromValue(request.params[1]); if (nAmount <= 0) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send"); // Wallet comments CWalletTx wtx; if (request.params.size() > 2 && !request.params[2].isNull() && !request.params[2].get_str().empty()) wtx.mapValue["comment"] = request.params[2].get_str(); if (request.params.size() > 3 && !request.params[3].isNull() && !request.params[3].get_str().empty()) wtx.mapValue["to"] = request.params[3].get_str(); bool fSubtractFeeFromAmount = false; if (request.params.size() > 4) fSubtractFeeFromAmount = request.params[4].get_bool(); EnsureWalletIsUnlocked(); SendMoney(address.Get(), nAmount, fSubtractFeeFromAmount, wtx); return wtx.GetHash().GetHex(); } UniValue listaddressgroupings(const JSONRPCRequest& request) { if (!EnsureWalletIsAvailable(request.fHelp)) return NullUniValue; if (request.fHelp) throw runtime_error( "listaddressgroupings\n" "\nLists 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\n" "\nResult:\n" "[\n" " [\n" " [\n" " \"address\", (string) The superdigitalcoin address\n" " amount, (numeric) The amount in " + CURRENCY_UNIT + "\n" " \"account\" (string, optional) DEPRECATED. The account\n" " ]\n" " ,...\n" " ]\n" " ,...\n" "]\n" "\nExamples:\n" + HelpExampleCli("listaddressgroupings", "") + HelpExampleRpc("listaddressgroupings", "") ); LOCK2(cs_main, pwalletMain->cs_wallet); UniValue jsonGroupings(UniValue::VARR); map<CTxDestination, CAmount> balances = pwalletMain->GetAddressBalances(); BOOST_FOREACH(set<CTxDestination> grouping, pwalletMain->GetAddressGroupings()) { UniValue jsonGrouping(UniValue::VARR); BOOST_FOREACH(CTxDestination address, grouping) { UniValue addressInfo(UniValue::VARR); addressInfo.push_back(CBitcoinAddress(address).ToString()); addressInfo.push_back(ValueFromAmount(balances[address])); { if (pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get()) != pwalletMain->mapAddressBook.end()) addressInfo.push_back(pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get())->second.name); } jsonGrouping.push_back(addressInfo); } jsonGroupings.push_back(jsonGrouping); } return jsonGroupings; } UniValue signmessage(const JSONRPCRequest& request) { if (!EnsureWalletIsAvailable(request.fHelp)) return NullUniValue; if (request.fHelp || request.params.size() != 2) throw runtime_error( "signmessage \"address\" \"message\"\n" "\nSign a message with the private key of an address" + HelpRequiringPassphrase() + "\n" "\nArguments:\n" "1. \"address\" (string, required) The superdigitalcoin address to use for the private key.\n" "2. \"message\" (string, required) The message to create a signature of.\n" "\nResult:\n" "\"signature\" (string) The signature of the message encoded in base 64\n" "\nExamples:\n" "\nUnlock the wallet for 30 seconds\n" + HelpExampleCli("walletpassphrase", "\"mypassphrase\" 30") + "\nCreate the signature\n" + HelpExampleCli("signmessage", "\"SJuet69CPrXJV48v2AsjQWmcF3pmWVkB55\" \"my message\"") + "\nVerify the signature\n" + HelpExampleCli("verifymessage", "\"SJuet69CPrXJV48v2AsjQWmcF3pmWVkB55\" \"signature\" \"my message\"") + "\nAs json rpc\n" + HelpExampleRpc("signmessage", "\"SJuet69CPrXJV48v2AsjQWmcF3pmWVkB55\", \"my message\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); EnsureWalletIsUnlocked(); string strAddress = request.params[0].get_str(); string strMessage = request.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()); } UniValue getreceivedbyaddress(const JSONRPCRequest& request) { if (!EnsureWalletIsAvailable(request.fHelp)) return NullUniValue; if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) throw runtime_error( "getreceivedbyaddress \"address\" ( minconf )\n" "\nReturns the total amount received by the given address in transactions with at least minconf confirmations.\n" "\nArguments:\n" "1. \"address\" (string, required) The superdigitalcoin address for transactions.\n" "2. minconf (numeric, optional, default=1) Only include transactions confirmed at least this many times.\n" "\nResult:\n" "amount (numeric) The total amount in " + CURRENCY_UNIT + " received at this address.\n" "\nExamples:\n" "\nThe amount from transactions with at least 1 confirmation\n" + HelpExampleCli("getreceivedbyaddress", "\"SJuet69CPrXJV48v2AsjQWmcF3pmWVkB55\"") + "\nThe amount including unconfirmed transactions, zero confirmations\n" + HelpExampleCli("getreceivedbyaddress", "\"SJuet69CPrXJV48v2AsjQWmcF3pmWVkB55\" 0") + "\nThe amount with at least 6 confirmation, very safe\n" + HelpExampleCli("getreceivedbyaddress", "\"SJuet69CPrXJV48v2AsjQWmcF3pmWVkB55\" 6") + "\nAs a json rpc call\n" + HelpExampleRpc("getreceivedbyaddress", "\"SJuet69CPrXJV48v2AsjQWmcF3pmWVkB55\", 6") ); LOCK2(cs_main, pwalletMain->cs_wallet); // Bitcoin address CBitcoinAddress address = CBitcoinAddress(request.params[0].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid SuperDigitalCoin address"); CScript scriptPubKey = GetScriptForDestination(address.Get()); if (!IsMine(*pwalletMain, scriptPubKey)) return ValueFromAmount(0); // Minimum confirmations int nMinDepth = 1; if (request.params.size() > 1) nMinDepth = request.params[1].get_int(); // Tally CAmount nAmount = 0; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (wtx.IsCoinBase() || !CheckFinalTx(*wtx.tx)) continue; BOOST_FOREACH(const CTxOut& txout, wtx.tx->vout) if (txout.scriptPubKey == scriptPubKey) if (wtx.GetDepthInMainChain() >= nMinDepth) nAmount += txout.nValue; } return ValueFromAmount(nAmount); } UniValue getreceivedbyaccount(const JSONRPCRequest& request) { if (!EnsureWalletIsAvailable(request.fHelp)) return NullUniValue; if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) throw runtime_error( "getreceivedbyaccount \"account\" ( minconf )\n" "\nDEPRECATED. Returns the total amount received by addresses with <account> in transactions with at least [minconf] confirmations.\n" "\nArguments:\n" "1. \"account\" (string, required) The selected account, may be the default account using \"\".\n" "2. minconf (numeric, optional, default=1) Only include transactions confirmed at least this many times.\n" "\nResult:\n" "amount (numeric) The total amount in " + CURRENCY_UNIT + " received for this account.\n" "\nExamples:\n" "\nAmount received by the default account with at least 1 confirmation\n" + HelpExampleCli("getreceivedbyaccount", "\"\"") + "\nAmount received at the tabby account including unconfirmed amounts with zero confirmations\n" + HelpExampleCli("getreceivedbyaccount", "\"tabby\" 0") + "\nThe amount with at least 6 confirmation, very safe\n" + HelpExampleCli("getreceivedbyaccount", "\"tabby\" 6") + "\nAs a json rpc call\n" + HelpExampleRpc("getreceivedbyaccount", "\"tabby\", 6") ); LOCK2(cs_main, pwalletMain->cs_wallet); // Minimum confirmations int nMinDepth = 1; if (request.params.size() > 1) nMinDepth = request.params[1].get_int(); // Get the set of pub keys assigned to account string strAccount = AccountFromValue(request.params[0]); set<CTxDestination> setAddress = pwalletMain->GetAccountAddresses(strAccount); // Tally CAmount nAmount = 0; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (wtx.IsCoinBase() || !CheckFinalTx(*wtx.tx)) continue; BOOST_FOREACH(const CTxOut& txout, wtx.tx->vout) { CTxDestination address; if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*pwalletMain, address) && setAddress.count(address)) if (wtx.GetDepthInMainChain() >= nMinDepth) nAmount += txout.nValue; } } return ValueFromAmount(nAmount); } UniValue getbalance(const JSONRPCRequest& request) { if (!EnsureWalletIsAvailable(request.fHelp)) return NullUniValue; if (request.fHelp || request.params.size() > 3) throw runtime_error( "getbalance ( \"account\" minconf include_watchonly )\n" "\nIf account is not specified, returns the server's total available balance.\n" "If account is specified (DEPRECATED), returns the balance in the account.\n" "Note that the account \"\" is not the same as leaving the parameter out.\n" "The server total may be different to the balance in the default \"\" account.\n" "\nArguments:\n" "1. \"account\" (string, optional) DEPRECATED. The account string may be given as a\n" " specific account name to find the balance associated with wallet keys in\n" " a named account, or as the empty string (\"\") to find the balance\n" " associated with wallet keys not in any named account, or as \"*\" to find\n" " the balance associated with all wallet keys regardless of account.\n" " When this option is specified, it calculates the balance in a different\n" " way than when it is not specified, and which can count spends twice when\n" " there are conflicting pending transactions (such as those created by\n" " the bumpfee command), temporarily resulting in low or even negative\n" " balances. In general, account balance calculation is not considered\n" " reliable and has resulted in confusing outcomes, so it is recommended to\n" " avoid passing this argument.\n" "2. minconf (numeric, optional, default=1) Only include transactions confirmed at least this many times.\n" "3. include_watchonly (bool, optional, default=false) Also include balance in watch-only addresses (see 'importaddress')\n" "\nResult:\n" "amount (numeric) The total amount in " + CURRENCY_UNIT + " received for this account.\n" "\nExamples:\n" "\nThe total amount in the wallet\n" + HelpExampleCli("getbalance", "") + "\nThe total amount in the wallet at least 5 blocks confirmed\n" + HelpExampleCli("getbalance", "\"*\" 6") + "\nAs a json rpc call\n" + HelpExampleRpc("getbalance", "\"*\", 6") ); LOCK2(cs_main, pwalletMain->cs_wallet); if (request.params.size() == 0) return ValueFromAmount(pwalletMain->GetBalance()); int nMinDepth = 1; if (request.params.size() > 1) nMinDepth = request.params[1].get_int(); isminefilter filter = ISMINE_SPENDABLE; if(request.params.size() > 2) if(request.params[2].get_bool()) filter = filter | ISMINE_WATCH_ONLY; if (request.params[0].get_str() == "*") { // Calculate total balance in a very different way from GetBalance(). // The biggest difference is that GetBalance() sums up all unspent // TxOuts paying to the wallet, while this sums up both spent and // unspent TxOuts paying to the wallet, and then subtracts the values of // TxIns spending from the wallet. This also has fewer restrictions on // which unconfirmed transactions are considered trusted. CAmount nBalance = 0; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (!CheckFinalTx(wtx) || wtx.GetBlocksToMaturity() > 0 || wtx.GetDepthInMainChain() < 0) continue; CAmount allFee; string strSentAccount; list<COutputEntry> listReceived; list<COutputEntry> listSent; wtx.GetAmounts(listReceived, listSent, allFee, strSentAccount, filter); if (wtx.GetDepthInMainChain() >= nMinDepth) { BOOST_FOREACH(const COutputEntry& r, listReceived) nBalance += r.amount; } BOOST_FOREACH(const COutputEntry& s, listSent) nBalance -= s.amount; nBalance -= allFee; } return ValueFromAmount(nBalance); } string strAccount = AccountFromValue(request.params[0]); CAmount nBalance = pwalletMain->GetAccountBalance(strAccount, nMinDepth, filter); return ValueFromAmount(nBalance); } UniValue getunconfirmedbalance(const JSONRPCRequest &request) { if (!EnsureWalletIsAvailable(request.fHelp)) return NullUniValue; if (request.fHelp || request.params.size() > 0) throw runtime_error( "getunconfirmedbalance\n" "Returns the server's total unconfirmed balance\n"); LOCK2(cs_main, pwalletMain->cs_wallet); return ValueFromAmount(pwalletMain->GetUnconfirmedBalance()); } UniValue movecmd(const JSONRPCRequest& request) { if (!EnsureWalletIsAvailable(request.fHelp)) return NullUniValue; if (request.fHelp || request.params.size() < 3 || request.params.size() > 5) throw runtime_error( "move \"fromaccount\" \"toaccount\" amount ( minconf \"comment\" )\n" "\nDEPRECATED. Move a specified amount from one account in your wallet to another.\n" "\nArguments:\n" "1. \"fromaccount\" (string, required) The name of the account to move funds from. May be the default account using \"\".\n" "2. \"toaccount\" (string, required) The name of the account to move funds to. May be the default account using \"\".\n" "3. amount (numeric) Quantity of " + CURRENCY_UNIT + " to move between accounts.\n" "4. (dummy) (numeric, optional) Ignored. Remains for backward compatibility.\n" "5. \"comment\" (string, optional) An optional comment, stored in the wallet only.\n" "\nResult:\n" "true|false (boolean) true if successful.\n" "\nExamples:\n" "\nMove 0.01 " + CURRENCY_UNIT + " from the default account to the account named tabby\n" + HelpExampleCli("move", "\"\" \"tabby\" 0.01") + "\nMove 0.01 " + CURRENCY_UNIT + " timotei to akiko with a comment and funds have 6 confirmations\n" + HelpExampleCli("move", "\"timotei\" \"akiko\" 0.01 6 \"happy birthday!\"") + "\nAs a json rpc call\n" + HelpExampleRpc("move", "\"timotei\", \"akiko\", 0.01, 6, \"happy birthday!\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); string strFrom = AccountFromValue(request.params[0]); string strTo = AccountFromValue(request.params[1]); CAmount nAmount = AmountFromValue(request.params[2]); if (nAmount <= 0) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send"); if (request.params.size() > 3) // unused parameter, used to be nMinDepth, keep type-checking it though (void)request.params[3].get_int(); string strComment; if (request.params.size() > 4) strComment = request.params[4].get_str(); if (!pwalletMain->AccountMove(strFrom, strTo, nAmount, strComment)) throw JSONRPCError(RPC_DATABASE_ERROR, "database error"); return true; } UniValue sendfrom(const JSONRPCRequest& request) { if (!EnsureWalletIsAvailable(request.fHelp)) return NullUniValue; if (request.fHelp || request.params.size() < 3 || request.params.size() > 6) throw runtime_error( "sendfrom \"fromaccount\" \"toaddress\" amount ( minconf \"comment\" \"comment_to\" )\n" "\nDEPRECATED (use sendtoaddress). Sent an amount from an account to a superdigitalcoin address." + HelpRequiringPassphrase() + "\n" "\nArguments:\n" "1. \"fromaccount\" (string, required) The name of the account to send funds from. May be the default account using \"\".\n" " Specifying an account does not influence coin selection, but it does associate the newly created\n" " transaction with the account, so the account's balance computation and transaction history can reflect\n" " the spend.\n" "2. \"toaddress\" (string, required) The superdigitalcoin address to send funds to.\n" "3. amount (numeric or string, required) The amount in " + CURRENCY_UNIT + " (transaction fee is added on top).\n" "4. minconf (numeric, optional, default=1) Only use funds with at least this many confirmations.\n" "5. \"comment\" (string, optional) A comment used to store what the transaction is for. \n" " This is not part of the transaction, just kept in your wallet.\n" "6. \"comment_to\" (string, optional) An optional comment to store the name of the person or organization \n" " to which you're sending the transaction. This is not part of the transaction, \n" " it is just kept in your wallet.\n" "\nResult:\n" "\"txid\" (string) The transaction id.\n" "\nExamples:\n" "\nSend 0.01 " + CURRENCY_UNIT + " from the default account to the address, must have at least 1 confirmation\n" + HelpExampleCli("sendfrom", "\"\" \"SJuet69CPrXJV48v2AsjQWmcF3pmWVkB55\" 0.01") + "\nSend 0.01 from the tabby account to the given address, funds must have at least 6 confirmations\n" + HelpExampleCli("sendfrom", "\"tabby\" \"SJuet69CPrXJV48v2AsjQWmcF3pmWVkB55\" 0.01 6 \"donation\" \"seans outpost\"") + "\nAs a json rpc call\n" + HelpExampleRpc("sendfrom", "\"tabby\", \"SJuet69CPrXJV48v2AsjQWmcF3pmWVkB55\", 0.01, 6, \"donation\", \"seans outpost\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); string strAccount = AccountFromValue(request.params[0]); CBitcoinAddress address(request.params[1].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid SuperDigitalCoin address"); CAmount nAmount = AmountFromValue(request.params[2]); if (nAmount <= 0) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send"); int nMinDepth = 1; if (request.params.size() > 3) nMinDepth = request.params[3].get_int(); CWalletTx wtx; wtx.strFromAccount = strAccount; if (request.params.size() > 4 && !request.params[4].isNull() && !request.params[4].get_str().empty()) wtx.mapValue["comment"] = request.params[4].get_str(); if (request.params.size() > 5 && !request.params[5].isNull() && !request.params[5].get_str().empty()) wtx.mapValue["to"] = request.params[5].get_str(); EnsureWalletIsUnlocked(); // Check funds CAmount nBalance = pwalletMain->GetAccountBalance(strAccount, nMinDepth, ISMINE_SPENDABLE); if (nAmount > nBalance) throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds"); SendMoney(address.Get(), nAmount, false, wtx); return wtx.GetHash().GetHex(); } UniValue sendmany(const JSONRPCRequest& request) { if (!EnsureWalletIsAvailable(request.fHelp)) return NullUniValue; if (request.fHelp || request.params.size() < 2 || request.params.size() > 5) throw runtime_error( "sendmany \"fromaccount\" {\"address\":amount,...} ( minconf \"comment\" [\"address\",...] )\n" "\nSend multiple times. Amounts are double-precision floating point numbers." + HelpRequiringPassphrase() + "\n" "\nArguments:\n" "1. \"fromaccount\" (string, required) DEPRECATED. The account to send the funds from. Should be \"\" for the default account\n" "2. \"amounts\" (string, required) A json object with addresses and amounts\n" " {\n" " \"address\":amount (numeric or string) The superdigitalcoin address is the key, the numeric amount (can be string) in " + CURRENCY_UNIT + " is the value\n" " ,...\n" " }\n" "3. minconf (numeric, optional, default=1) Only use the balance confirmed at least this many times.\n" "4. \"comment\" (string, optional) A comment\n" "5. subtractfeefrom (array, optional) A json array with addresses.\n" " The fee will be equally deducted from the amount of each selected address.\n" " Those recipients will receive less superdigitalcoins than you enter in their corresponding amount field.\n" " If no addresses are specified here, the sender pays the fee.\n" " [\n" " \"address\" (string) Subtract fee from this address\n" " ,...\n" " ]\n" "\nResult:\n" "\"txid\" (string) The transaction id for the send. Only 1 transaction is created regardless of \n" " the number of addresses.\n" "\nExamples:\n" "\nSend two amounts to two different addresses:\n" + HelpExampleCli("sendmany", "\"\" \"{\\\"SJuet69CPrXJV48v2AsjQWmcF3pmWVkB55\\\":0.01,\\\"LbhhnrHHVFP1eUjP1tdNIYeEVsNHfN9FCw\\\":0.02}\"") + "\nSend two amounts to two different addresses setting the confirmation and comment:\n" + HelpExampleCli("sendmany", "\"\" \"{\\\"SJuet69CPrXJV48v2AsjQWmcF3pmWVkB55\\\":0.01,\\\"LbhhnrHHVFP1eUjP1tdNIYeEVsNHfN9FCw\\\":0.02}\" 6 \"testing\"") + "\nSend two amounts to two different addresses, subtract fee from amount:\n" + HelpExampleCli("sendmany", "\"\" \"{\\\"SJuet69CPrXJV48v2AsjQWmcF3pmWVkB55\\\":0.01,\\\"LbhhnrHHVFP1eUjP1tdNIYeEVsNHfN9FCw\\\":0.02}\" 1 \"\" \"[\\\"SJuet69CPrXJV48v2AsjQWmcF3pmWVkB55\\\",\\\"LbhhnrHHVFP1eUjP1tdNIYeEVsNHfN9FCw\\\"]\"") + "\nAs a json rpc call\n" + HelpExampleRpc("sendmany", "\"\", \"{\\\"SJuet69CPrXJV48v2AsjQWmcF3pmWVkB55\\\":0.01,\\\"LbhhnrHHVFP1eUjP1tdNIYeEVsNHfN9FCw\\\":0.02}\", 6, \"testing\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); if (pwalletMain->GetBroadcastTransactions() && !g_connman) throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); string strAccount = AccountFromValue(request.params[0]); UniValue sendTo = request.params[1].get_obj(); int nMinDepth = 1; if (request.params.size() > 2) nMinDepth = request.params[2].get_int(); CWalletTx wtx; wtx.strFromAccount = strAccount; if (request.params.size() > 3 && !request.params[3].isNull() && !request.params[3].get_str().empty()) wtx.mapValue["comment"] = request.params[3].get_str(); UniValue subtractFeeFromAmount(UniValue::VARR); if (request.params.size() > 4) subtractFeeFromAmount = request.params[4].get_array(); set<CBitcoinAddress> setAddress; vector<CRecipient> vecSend; CAmount totalAmount = 0; vector<string> keys = sendTo.getKeys(); BOOST_FOREACH(const string& name_, keys) { CBitcoinAddress address(name_); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid SuperDigitalCoin address: ")+name_); if (setAddress.count(address)) throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+name_); setAddress.insert(address); CScript scriptPubKey = GetScriptForDestination(address.Get()); CAmount nAmount = AmountFromValue(sendTo[name_]); if (nAmount <= 0) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send"); totalAmount += nAmount; bool fSubtractFeeFromAmount = false; for (unsigned int idx = 0; idx < subtractFeeFromAmount.size(); idx++) { const UniValue& addr = subtractFeeFromAmount[idx]; if (addr.get_str() == name_) fSubtractFeeFromAmount = true; } CRecipient recipient = {scriptPubKey, nAmount, fSubtractFeeFromAmount}; vecSend.push_back(recipient); } EnsureWalletIsUnlocked(); // Check funds CAmount nBalance = pwalletMain->GetAccountBalance(strAccount, nMinDepth, ISMINE_SPENDABLE); if (totalAmount > nBalance) throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds"); // Send CReserveKey keyChange(pwalletMain); CAmount nFeeRequired = 0; int nChangePosRet = -1; string strFailReason; bool fCreated = pwalletMain->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired, nChangePosRet, strFailReason); if (!fCreated) throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, strFailReason); CValidationState state; if (!pwalletMain->CommitTransaction(wtx, keyChange, g_connman.get(), state)) { strFailReason = strprintf("Transaction commit failed:: %s", state.GetRejectReason()); throw JSONRPCError(RPC_WALLET_ERROR, strFailReason); } return wtx.GetHash().GetHex(); } // Defined in rpc/misc.cpp extern CScript _createmultisig_redeemScript(const UniValue& params); UniValue addmultisigaddress(const JSONRPCRequest& request) { if (!EnsureWalletIsAvailable(request.fHelp)) return NullUniValue; if (request.fHelp || request.params.size() < 2 || request.params.size() > 3) { string msg = "addmultisigaddress nrequired [\"key\",...] ( \"account\" )\n" "\nAdd a nrequired-to-sign multisignature address to the wallet.\n" "Each key is a SuperDigitalCoin address or hex-encoded public key.\n" "If 'account' is specified (DEPRECATED), assign address to that account.\n" "\nArguments:\n" "1. nrequired (numeric, required) The number of required signatures out of the n keys or addresses.\n" "2. \"keys\" (string, required) A json array of superdigitalcoin addresses or hex-encoded public keys\n" " [\n" " \"address\" (string) superdigitalcoin address or hex-encoded public key\n" " ...,\n" " ]\n" "3. \"account\" (string, optional) DEPRECATED. An account to assign the addresses to.\n" "\nResult:\n" "\"address\" (string) A superdigitalcoin address associated with the keys.\n" "\nExamples:\n" "\nAdd a multisig address from 2 addresses\n" + HelpExampleCli("addmultisigaddress", "2 \"[\\\"SJuet69CPrXJV48v2AsjQWmcF3pmWVkB55\\\",\\\"LYKr1oaPSqShthukmLDhdZsqUJgzVnQiAQ\\\"]\"") + "\nAs json rpc call\n" + HelpExampleRpc("addmultisigaddress", "2, \"[\\\"SJuet69CPrXJV48v2AsjQWmcF3pmWVkB55\\\",\\\"LYKr1oaPSqShthukmLDhdZsqUJgzVnQiAQ\\\"]\"") ; throw runtime_error(msg); } LOCK2(cs_main, pwalletMain->cs_wallet); string strAccount; if (request.params.size() > 2) strAccount = AccountFromValue(request.params[2]); // Construct using pay-to-script-hash: CScript inner = _createmultisig_redeemScript(request.params); CScriptID innerID(inner); pwalletMain->AddCScript(inner); pwalletMain->SetAddressBook(innerID, strAccount, "send"); return CBitcoinAddress(innerID).ToString(); } class Witnessifier : public boost::static_visitor<bool> { public: CScriptID result; bool operator()(const CNoDestination &dest) const { return false; } bool operator()(const CKeyID &keyID) { CPubKey pubkey; if (pwalletMain) { CScript basescript = GetScriptForDestination(keyID); isminetype typ; typ = IsMine(*pwalletMain, basescript, SIGVERSION_WITNESS_V0); if (typ != ISMINE_SPENDABLE && typ != ISMINE_WATCH_SOLVABLE) return false; CScript witscript = GetScriptForWitness(basescript); pwalletMain->AddCScript(witscript); result = CScriptID(witscript); return true; } return false; } bool operator()(const CScriptID &scriptID) { CScript subscript; if (pwalletMain && pwalletMain->GetCScript(scriptID, subscript)) { int witnessversion; std::vector<unsigned char> witprog; if (subscript.IsWitnessProgram(witnessversion, witprog)) { result = scriptID; return true; } isminetype typ; typ = IsMine(*pwalletMain, subscript, SIGVERSION_WITNESS_V0); if (typ != ISMINE_SPENDABLE && typ != ISMINE_WATCH_SOLVABLE) return false; CScript witscript = GetScriptForWitness(subscript); pwalletMain->AddCScript(witscript); result = CScriptID(witscript); return true; } return false; } }; UniValue addwitnessaddress(const JSONRPCRequest& request) { if (!EnsureWalletIsAvailable(request.fHelp)) return NullUniValue; if (request.fHelp || request.params.size() < 1 || request.params.size() > 1) { string msg = "addwitnessaddress \"address\"\n" "\nAdd a witness address for a script (with pubkey or redeemscript known).\n" "It returns the witness script.\n" "\nArguments:\n" "1. \"address\" (string, required) An address known to the wallet\n" "\nResult:\n" "\"witnessaddress\", (string) The value of the new address (P2SH of witness script).\n" "}\n" ; throw runtime_error(msg); } { LOCK(cs_main); if (!IsWitnessEnabled(chainActive.Tip(), Params().GetConsensus()) && !GetBoolArg("-walletprematurewitness", false)) { throw JSONRPCError(RPC_WALLET_ERROR, "Segregated witness not enabled on network"); } } CBitcoinAddress address(request.params[0].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid SuperDigitalCoin address"); Witnessifier w; CTxDestination dest = address.Get(); bool ret = boost::apply_visitor(w, dest); if (!ret) { throw JSONRPCError(RPC_WALLET_ERROR, "Public key or redeemscript not known to wallet, or the key is uncompressed"); } pwalletMain->SetAddressBook(w.result, "", "receive"); return CBitcoinAddress(w.result).ToString(); } struct tallyitem { CAmount nAmount; int nConf; vector<uint256> txids; bool fIsWatchonly; tallyitem() { nAmount = 0; nConf = std::numeric_limits<int>::max(); fIsWatchonly = false; } }; UniValue ListReceived(const UniValue& 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(); isminefilter filter = ISMINE_SPENDABLE; if(params.size() > 2) if(params[2].get_bool()) filter = filter | ISMINE_WATCH_ONLY; // 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() || !CheckFinalTx(*wtx.tx)) continue; int nDepth = wtx.GetDepthInMainChain(); if (nDepth < nMinDepth) continue; BOOST_FOREACH(const CTxOut& txout, wtx.tx->vout) { CTxDestination address; if (!ExtractDestination(txout.scriptPubKey, address)) continue; isminefilter mine = IsMine(*pwalletMain, address); if(!(mine & filter)) continue; tallyitem& item = mapTally[address]; item.nAmount += txout.nValue; item.nConf = min(item.nConf, nDepth); item.txids.push_back(wtx.GetHash()); if (mine & ISMINE_WATCH_ONLY) item.fIsWatchonly = true; } } // Reply UniValue ret(UniValue::VARR); map<string, tallyitem> mapAccountTally; BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, CAddressBookData)& item, pwalletMain->mapAddressBook) { const CBitcoinAddress& address = item.first; const string& strAccount = item.second.name; map<CBitcoinAddress, tallyitem>::iterator it = mapTally.find(address); if (it == mapTally.end() && !fIncludeEmpty) continue; CAmount nAmount = 0; int nConf = std::numeric_limits<int>::max(); bool fIsWatchonly = false; if (it != mapTally.end()) { nAmount = (*it).second.nAmount; nConf = (*it).second.nConf; fIsWatchonly = (*it).second.fIsWatchonly; } if (fByAccounts) { tallyitem& _item = mapAccountTally[strAccount]; _item.nAmount += nAmount; _item.nConf = min(_item.nConf, nConf); _item.fIsWatchonly = fIsWatchonly; } else { UniValue obj(UniValue::VOBJ); if(fIsWatchonly) obj.push_back(Pair("involvesWatchonly", true)); 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))); if (!fByAccounts) obj.push_back(Pair("label", strAccount)); UniValue transactions(UniValue::VARR); 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) { CAmount nAmount = (*it).second.nAmount; int nConf = (*it).second.nConf; UniValue obj(UniValue::VOBJ); if((*it).second.fIsWatchonly) obj.push_back(Pair("involvesWatchonly", true)); 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; } UniValue listreceivedbyaddress(const JSONRPCRequest& request) { if (!EnsureWalletIsAvailable(request.fHelp)) return NullUniValue; if (request.fHelp || request.params.size() > 3) throw runtime_error( "listreceivedbyaddress ( minconf include_empty include_watchonly)\n" "\nList balances by receiving address.\n" "\nArguments:\n" "1. minconf (numeric, optional, default=1) The minimum number of confirmations before payments are included.\n" "2. include_empty (bool, optional, default=false) Whether to include addresses that haven't received any payments.\n" "3. include_watchonly (bool, optional, default=false) Whether to include watch-only addresses (see 'importaddress').\n" "\nResult:\n" "[\n" " {\n" " \"involvesWatchonly\" : true, (bool) Only returned if imported addresses were involved in transaction\n" " \"address\" : \"receivingaddress\", (string) The receiving address\n" " \"account\" : \"accountname\", (string) DEPRECATED. The account of the receiving address. The default account is \"\".\n" " \"amount\" : x.xxx, (numeric) The total amount in " + CURRENCY_UNIT + " received by the address\n" " \"confirmations\" : n, (numeric) The number of confirmations of the most recent transaction included\n" " \"label\" : \"label\", (string) A comment for the address/transaction, if any\n" " \"txids\": [\n" " n, (numeric) The ids of transactions received with the address \n" " ...\n" " ]\n" " }\n" " ,...\n" "]\n" "\nExamples:\n" + HelpExampleCli("listreceivedbyaddress", "") + HelpExampleCli("listreceivedbyaddress", "6 true") + HelpExampleRpc("listreceivedbyaddress", "6, true, true") ); LOCK2(cs_main, pwalletMain->cs_wallet); return ListReceived(request.params, false); } UniValue listreceivedbyaccount(const JSONRPCRequest& request) { if (!EnsureWalletIsAvailable(request.fHelp)) return NullUniValue; if (request.fHelp || request.params.size() > 3) throw runtime_error( "listreceivedbyaccount ( minconf include_empty include_watchonly)\n" "\nDEPRECATED. List balances by account.\n" "\nArguments:\n" "1. minconf (numeric, optional, default=1) The minimum number of confirmations before payments are included.\n" "2. include_empty (bool, optional, default=false) Whether to include accounts that haven't received any payments.\n" "3. include_watchonly (bool, optional, default=false) Whether to include watch-only addresses (see 'importaddress').\n" "\nResult:\n" "[\n" " {\n" " \"involvesWatchonly\" : true, (bool) Only returned if imported addresses were involved in transaction\n" " \"account\" : \"accountname\", (string) The account name of the receiving account\n" " \"amount\" : x.xxx, (numeric) The total amount received by addresses with this account\n" " \"confirmations\" : n, (numeric) The number of confirmations of the most recent transaction included\n" " \"label\" : \"label\" (string) A comment for the address/transaction, if any\n" " }\n" " ,...\n" "]\n" "\nExamples:\n" + HelpExampleCli("listreceivedbyaccount", "") + HelpExampleCli("listreceivedbyaccount", "6 true") + HelpExampleRpc("listreceivedbyaccount", "6, true, true") ); LOCK2(cs_main, pwalletMain->cs_wallet); return ListReceived(request.params, true); } static void MaybePushAddress(UniValue & 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, UniValue& ret, const isminefilter& filter) { CAmount nFee; string strSentAccount; list<COutputEntry> listReceived; list<COutputEntry> listSent; wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount, filter); bool fAllAccounts = (strAccount == string("*")); bool involvesWatchonly = wtx.IsFromMe(ISMINE_WATCH_ONLY); // Sent if ((!listSent.empty() || nFee != 0) && (fAllAccounts || strAccount == strSentAccount)) { BOOST_FOREACH(const COutputEntry& s, listSent) { UniValue entry(UniValue::VOBJ); if(involvesWatchonly || (::IsMine(*pwalletMain, s.destination) & ISMINE_WATCH_ONLY)) entry.push_back(Pair("involvesWatchonly", true)); entry.push_back(Pair("account", strSentAccount)); MaybePushAddress(entry, s.destination); entry.push_back(Pair("category", "send")); entry.push_back(Pair("amount", ValueFromAmount(-s.amount))); if (pwalletMain->mapAddressBook.count(s.destination)) entry.push_back(Pair("label", pwalletMain->mapAddressBook[s.destination].name)); entry.push_back(Pair("vout", s.vout)); entry.push_back(Pair("fee", ValueFromAmount(-nFee))); if (fLong) WalletTxToJSON(wtx, entry); entry.push_back(Pair("abandoned", wtx.isAbandoned())); ret.push_back(entry); } } // Received if (listReceived.size() > 0 && wtx.GetDepthInMainChain() >= nMinDepth) { BOOST_FOREACH(const COutputEntry& r, listReceived) { string account; if (pwalletMain->mapAddressBook.count(r.destination)) account = pwalletMain->mapAddressBook[r.destination].name; if (fAllAccounts || (account == strAccount)) { UniValue entry(UniValue::VOBJ); if(involvesWatchonly || (::IsMine(*pwalletMain, r.destination) & ISMINE_WATCH_ONLY)) entry.push_back(Pair("involvesWatchonly", true)); entry.push_back(Pair("account", account)); MaybePushAddress(entry, r.destination); 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.amount))); if (pwalletMain->mapAddressBook.count(r.destination)) entry.push_back(Pair("label", account)); entry.push_back(Pair("vout", r.vout)); if (fLong) WalletTxToJSON(wtx, entry); ret.push_back(entry); } } } } void AcentryToJSON(const CAccountingEntry& acentry, const string& strAccount, UniValue& ret) { bool fAllAccounts = (strAccount == string("*")); if (fAllAccounts || acentry.strAccount == strAccount) { UniValue entry(UniValue::VOBJ); entry.push_back(Pair("account", acentry.strAccount)); entry.push_back(Pair("category", "move")); entry.push_back(Pair("time", 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); } } UniValue listtransactions(const JSONRPCRequest& request) { if (!EnsureWalletIsAvailable(request.fHelp)) return NullUniValue; if (request.fHelp || request.params.size() > 4) throw runtime_error( "listtransactions ( \"account\" count skip include_watchonly)\n" "\nReturns up to 'count' most recent transactions skipping the first 'from' transactions for account 'account'.\n" "\nArguments:\n" "1. \"account\" (string, optional) DEPRECATED. The account name. Should be \"*\".\n" "2. count (numeric, optional, default=10) The number of transactions to return\n" "3. skip (numeric, optional, default=0) The number of transactions to skip\n" "4. include_watchonly (bool, optional, default=false) Include transactions to watch-only addresses (see 'importaddress')\n" "\nResult:\n" "[\n" " {\n" " \"account\":\"accountname\", (string) DEPRECATED. The account name associated with the transaction. \n" " It will be \"\" for the default account.\n" " \"address\":\"address\", (string) The superdigitalcoin address of the transaction. Not present for \n" " move transactions (category = move).\n" " \"category\":\"send|receive|move\", (string) The transaction category. 'move' is a local (off blockchain)\n" " transaction between accounts, and not associated with an address,\n" " transaction id or block. 'send' and 'receive' transactions are \n" " associated with an address, transaction id and block details\n" " \"amount\": x.xxx, (numeric) The amount in " + CURRENCY_UNIT + ". This is negative for the 'send' category, and for the\n" " 'move' category for moves outbound. It is positive for the 'receive' category,\n" " and for the 'move' category for inbound funds.\n" " \"label\": \"label\", (string) A comment for the address/transaction, if any\n" " \"vout\": n, (numeric) the vout value\n" " \"fee\": x.xxx, (numeric) The amount of the fee in " + CURRENCY_UNIT + ". This is negative and only available for the \n" " 'send' category of transactions.\n" " \"confirmations\": n, (numeric) The number of confirmations for the transaction. Available for 'send' and \n" " 'receive' category of transactions. Negative confirmations indicate the\n" " transaction conflicts with the block chain\n" " \"trusted\": xxx, (bool) Whether we consider the outputs of this unconfirmed transaction safe to spend.\n" " \"blockhash\": \"hashvalue\", (string) The block hash containing the transaction. Available for 'send' and 'receive'\n" " category of transactions.\n" " \"blockindex\": n, (numeric) The index of the transaction in the block that includes it. Available for 'send' and 'receive'\n" " category of transactions.\n" " \"blocktime\": xxx, (numeric) The block time in seconds since epoch (1 Jan 1970 GMT).\n" " \"txid\": \"transactionid\", (string) The transaction id. Available for 'send' and 'receive' category of transactions.\n" " \"time\": xxx, (numeric) The transaction time in seconds since epoch (midnight Jan 1 1970 GMT).\n" " \"timereceived\": xxx, (numeric) The time received in seconds since epoch (midnight Jan 1 1970 GMT). Available \n" " for 'send' and 'receive' category of transactions.\n" " \"comment\": \"...\", (string) If a comment is associated with the transaction.\n" " \"otheraccount\": \"accountname\", (string) DEPRECATED. For the 'move' category of transactions, the account the funds came \n" " from (for receiving funds, positive amounts), or went to (for sending funds,\n" " negative amounts).\n" " \"bip125-replaceable\": \"yes|no|unknown\", (string) Whether this transaction could be replaced due to BIP125 (replace-by-fee);\n" " may be unknown for unconfirmed transactions not in the mempool\n" " \"abandoned\": xxx (bool) 'true' if the transaction has been abandoned (inputs are respendable). Only available for the \n" " 'send' category of transactions.\n" " }\n" "]\n" "\nExamples:\n" "\nList the most recent 10 transactions in the systems\n" + HelpExampleCli("listtransactions", "") + "\nList transactions 100 to 120\n" + HelpExampleCli("listtransactions", "\"*\" 20 100") + "\nAs a json rpc call\n" + HelpExampleRpc("listtransactions", "\"*\", 20, 100") ); LOCK2(cs_main, pwalletMain->cs_wallet); string strAccount = "*"; if (request.params.size() > 0) strAccount = request.params[0].get_str(); int nCount = 10; if (request.params.size() > 1) nCount = request.params[1].get_int(); int nFrom = 0; if (request.params.size() > 2) nFrom = request.params[2].get_int(); isminefilter filter = ISMINE_SPENDABLE; if(request.params.size() > 3) if(request.params[3].get_bool()) filter = filter | ISMINE_WATCH_ONLY; if (nCount < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative count"); if (nFrom < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative from"); UniValue ret(UniValue::VARR); const CWallet::TxItems & txOrdered = pwalletMain->wtxOrdered; // iterate backwards until we have nCount items to return: for (CWallet::TxItems::const_reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) { CWalletTx *const pwtx = (*it).second.first; if (pwtx != 0) ListTransactions(*pwtx, strAccount, 0, true, ret, filter); 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; vector<UniValue> arrTmp = ret.getValues(); vector<UniValue>::iterator first = arrTmp.begin(); std::advance(first, nFrom); vector<UniValue>::iterator last = arrTmp.begin(); std::advance(last, nFrom+nCount); if (last != arrTmp.end()) arrTmp.erase(last, arrTmp.end()); if (first != arrTmp.begin()) arrTmp.erase(arrTmp.begin(), first); std::reverse(arrTmp.begin(), arrTmp.end()); // Return oldest to newest ret.clear(); ret.setArray(); ret.push_backV(arrTmp); return ret; } UniValue listaccounts(const JSONRPCRequest& request) { if (!EnsureWalletIsAvailable(request.fHelp)) return NullUniValue; if (request.fHelp || request.params.size() > 2) throw runtime_error( "listaccounts ( minconf include_watchonly)\n" "\nDEPRECATED. Returns Object that has account names as keys, account balances as values.\n" "\nArguments:\n" "1. minconf (numeric, optional, default=1) Only include transactions with at least this many confirmations\n" "2. include_watchonly (bool, optional, default=false) Include balances in watch-only addresses (see 'importaddress')\n" "\nResult:\n" "{ (json object where keys are account names, and values are numeric balances\n" " \"account\": x.xxx, (numeric) The property name is the account name, and the value is the total balance for the account.\n" " ...\n" "}\n" "\nExamples:\n" "\nList account balances where there at least 1 confirmation\n" + HelpExampleCli("listaccounts", "") + "\nList account balances including zero confirmation transactions\n" + HelpExampleCli("listaccounts", "0") + "\nList account balances for 6 or more confirmations\n" + HelpExampleCli("listaccounts", "6") + "\nAs json rpc call\n" + HelpExampleRpc("listaccounts", "6") ); LOCK2(cs_main, pwalletMain->cs_wallet); int nMinDepth = 1; if (request.params.size() > 0) nMinDepth = request.params[0].get_int(); isminefilter includeWatchonly = ISMINE_SPENDABLE; if(request.params.size() > 1) if(request.params[1].get_bool()) includeWatchonly = includeWatchonly | ISMINE_WATCH_ONLY; map<string, CAmount> mapAccountBalances; BOOST_FOREACH(const PAIRTYPE(CTxDestination, CAddressBookData)& entry, pwalletMain->mapAddressBook) { if (IsMine(*pwalletMain, entry.first) & includeWatchonly) // This address belongs to me mapAccountBalances[entry.second.name] = 0; } for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; CAmount nFee; string strSentAccount; list<COutputEntry> listReceived; list<COutputEntry> listSent; int nDepth = wtx.GetDepthInMainChain(); if (wtx.GetBlocksToMaturity() > 0 || nDepth < 0) continue; wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount, includeWatchonly); mapAccountBalances[strSentAccount] -= nFee; BOOST_FOREACH(const COutputEntry& s, listSent) mapAccountBalances[strSentAccount] -= s.amount; if (nDepth >= nMinDepth) { BOOST_FOREACH(const COutputEntry& r, listReceived) if (pwalletMain->mapAddressBook.count(r.destination)) mapAccountBalances[pwalletMain->mapAddressBook[r.destination].name] += r.amount; else mapAccountBalances[""] += r.amount; } } const list<CAccountingEntry> & acentries = pwalletMain->laccentries; BOOST_FOREACH(const CAccountingEntry& entry, acentries) mapAccountBalances[entry.strAccount] += entry.nCreditDebit; UniValue ret(UniValue::VOBJ); BOOST_FOREACH(const PAIRTYPE(string, CAmount)& accountBalance, mapAccountBalances) { ret.push_back(Pair(accountBalance.first, ValueFromAmount(accountBalance.second))); } return ret; } UniValue listsinceblock(const JSONRPCRequest& request) { if (!EnsureWalletIsAvailable(request.fHelp)) return NullUniValue; if (request.fHelp) throw runtime_error( "listsinceblock ( \"blockhash\" target_confirmations include_watchonly)\n" "\nGet all transactions in blocks since block [blockhash], or all transactions if omitted\n" "\nArguments:\n" "1. \"blockhash\" (string, optional) The block hash to list transactions since\n" "2. target_confirmations: (numeric, optional) The confirmations required, must be 1 or more\n" "3. include_watchonly: (bool, optional, default=false) Include transactions to watch-only addresses (see 'importaddress')" "\nResult:\n" "{\n" " \"transactions\": [\n" " \"account\":\"accountname\", (string) DEPRECATED. The account name associated with the transaction. Will be \"\" for the default account.\n" " \"address\":\"address\", (string) The superdigitalcoin address of the transaction. Not present for move transactions (category = move).\n" " \"category\":\"send|receive\", (string) The transaction category. 'send' has negative amounts, 'receive' has positive amounts.\n" " \"amount\": x.xxx, (numeric) The amount in " + CURRENCY_UNIT + ". This is negative for the 'send' category, and for the 'move' category for moves \n" " outbound. It is positive for the 'receive' category, and for the 'move' category for inbound funds.\n" " \"vout\" : n, (numeric) the vout value\n" " \"fee\": x.xxx, (numeric) The amount of the fee in " + CURRENCY_UNIT + ". This is negative and only available for the 'send' category of transactions.\n" " \"confirmations\": n, (numeric) The number of confirmations for the transaction. Available for 'send' and 'receive' category of transactions.\n" " When it's < 0, it means the transaction conflicted that many blocks ago.\n" " \"blockhash\": \"hashvalue\", (string) The block hash containing the transaction. Available for 'send' and 'receive' category of transactions.\n" " \"blockindex\": n, (numeric) The index of the transaction in the block that includes it. Available for 'send' and 'receive' category of transactions.\n" " \"blocktime\": xxx, (numeric) The block time in seconds since epoch (1 Jan 1970 GMT).\n" " \"txid\": \"transactionid\", (string) The transaction id. Available for 'send' and 'receive' category of transactions.\n" " \"time\": xxx, (numeric) The transaction time in seconds since epoch (Jan 1 1970 GMT).\n" " \"timereceived\": xxx, (numeric) The time received in seconds since epoch (Jan 1 1970 GMT). Available for 'send' and 'receive' category of transactions.\n" " \"bip125-replaceable\": \"yes|no|unknown\", (string) Whether this transaction could be replaced due to BIP125 (replace-by-fee);\n" " may be unknown for unconfirmed transactions not in the mempool\n" " \"abandoned\": xxx, (bool) 'true' if the transaction has been abandoned (inputs are respendable). Only available for the 'send' category of transactions.\n" " \"comment\": \"...\", (string) If a comment is associated with the transaction.\n" " \"label\" : \"label\" (string) A comment for the address/transaction, if any\n" " \"to\": \"...\", (string) If a comment to is associated with the transaction.\n" " ],\n" " \"lastblock\": \"lastblockhash\" (string) The hash of the last block\n" "}\n" "\nExamples:\n" + HelpExampleCli("listsinceblock", "") + HelpExampleCli("listsinceblock", "\"2c5a0ff9e4d8a7cdece6cc0f11d8f949a0c58b2028fab79b90485a811253e217\" 6") + HelpExampleRpc("listsinceblock", "\"2c5a0ff9e4d8a7cdece6cc0f11d8f949a0c58b2028fab79b90485a811253e217\", 6") ); LOCK2(cs_main, pwalletMain->cs_wallet); const CBlockIndex *pindex = NULL; int target_confirms = 1; isminefilter filter = ISMINE_SPENDABLE; if (request.params.size() > 0) { uint256 blockId; blockId.SetHex(request.params[0].get_str()); BlockMap::iterator it = mapBlockIndex.find(blockId); if (it != mapBlockIndex.end()) { pindex = it->second; if (chainActive[pindex->nHeight] != pindex) { // the block being asked for is a part of a deactivated chain; // we don't want to depend on its perceived height in the block // chain, we want to instead use the last common ancestor pindex = chainActive.FindFork(pindex); } } } if (request.params.size() > 1) { target_confirms = request.params[1].get_int(); if (target_confirms < 1) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter"); } if (request.params.size() > 2 && request.params[2].get_bool()) { filter = filter | ISMINE_WATCH_ONLY; } int depth = pindex ? (1 + chainActive.Height() - pindex->nHeight) : -1; UniValue transactions(UniValue::VARR); 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, filter); } CBlockIndex *pblockLast = chainActive[chainActive.Height() + 1 - target_confirms]; uint256 lastblock = pblockLast ? pblockLast->GetBlockHash() : uint256(); UniValue ret(UniValue::VOBJ); ret.push_back(Pair("transactions", transactions)); ret.push_back(Pair("lastblock", lastblock.GetHex())); return ret; } UniValue gettransaction(const JSONRPCRequest& request) { if (!EnsureWalletIsAvailable(request.fHelp)) return NullUniValue; if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) throw runtime_error( "gettransaction \"txid\" ( include_watchonly )\n" "\nGet detailed information about in-wallet transaction <txid>\n" "\nArguments:\n" "1. \"txid\" (string, required) The transaction id\n" "2. \"include_watchonly\" (bool, optional, default=false) Whether to include watch-only addresses in balance calculation and details[]\n" "\nResult:\n" "{\n" " \"amount\" : x.xxx, (numeric) The transaction amount in " + CURRENCY_UNIT + "\n" " \"fee\": x.xxx, (numeric) The amount of the fee in " + CURRENCY_UNIT + ". This is negative and only available for the \n" " 'send' category of transactions.\n" " \"confirmations\" : n, (numeric) The number of confirmations\n" " \"blockhash\" : \"hash\", (string) The block hash\n" " \"blockindex\" : xx, (numeric) The index of the transaction in the block that includes it\n" " \"blocktime\" : ttt, (numeric) The time in seconds since epoch (1 Jan 1970 GMT)\n" " \"txid\" : \"transactionid\", (string) The transaction id.\n" " \"time\" : ttt, (numeric) The transaction time in seconds since epoch (1 Jan 1970 GMT)\n" " \"timereceived\" : ttt, (numeric) The time received in seconds since epoch (1 Jan 1970 GMT)\n" " \"bip125-replaceable\": \"yes|no|unknown\", (string) Whether this transaction could be replaced due to BIP125 (replace-by-fee);\n" " may be unknown for unconfirmed transactions not in the mempool\n" " \"details\" : [\n" " {\n" " \"account\" : \"accountname\", (string) DEPRECATED. The account name involved in the transaction, can be \"\" for the default account.\n" " \"address\" : \"address\", (string) The superdigitalcoin address involved in the transaction\n" " \"category\" : \"send|receive\", (string) The category, either 'send' or 'receive'\n" " \"amount\" : x.xxx, (numeric) The amount in " + CURRENCY_UNIT + "\n" " \"label\" : \"label\", (string) A comment for the address/transaction, if any\n" " \"vout\" : n, (numeric) the vout value\n" " \"fee\": x.xxx, (numeric) The amount of the fee in " + CURRENCY_UNIT + ". This is negative and only available for the \n" " 'send' category of transactions.\n" " \"abandoned\": xxx (bool) 'true' if the transaction has been abandoned (inputs are respendable). Only available for the \n" " 'send' category of transactions.\n" " }\n" " ,...\n" " ],\n" " \"hex\" : \"data\" (string) Raw data for transaction\n" "}\n" "\nExamples:\n" + HelpExampleCli("gettransaction", "\"c1700d6dd3e690866de56686e893cbe4e637eb5d84e3591cdfbbdbb0fcee49f8\"") + HelpExampleCli("gettransaction", "\"c1700d6dd3e690866de56686e893cbe4e637eb5d84e3591cdfbbdbb0fcee49f8\" true") + HelpExampleRpc("gettransaction", "\"c1700d6dd3e690866de56686e893cbe4e637eb5d84e3591cdfbbdbb0fcee49f8\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); uint256 hash; hash.SetHex(request.params[0].get_str()); isminefilter filter = ISMINE_SPENDABLE; if(request.params.size() > 1) if(request.params[1].get_bool()) filter = filter | ISMINE_WATCH_ONLY; UniValue entry(UniValue::VOBJ); if (!pwalletMain->mapWallet.count(hash)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid or non-wallet transaction id"); const CWalletTx& wtx = pwalletMain->mapWallet[hash]; CAmount nCredit = wtx.GetCredit(filter); CAmount nDebit = wtx.GetDebit(filter); CAmount nNet = nCredit - nDebit; CAmount nFee = (wtx.IsFromMe(filter) ? wtx.tx->GetValueOut() - nDebit : 0); entry.push_back(Pair("amount", ValueFromAmount(nNet - nFee))); if (wtx.IsFromMe(filter)) entry.push_back(Pair("fee", ValueFromAmount(nFee))); WalletTxToJSON(wtx, entry); UniValue details(UniValue::VARR); ListTransactions(wtx, "*", 0, false, details, filter); entry.push_back(Pair("details", details)); string strHex = EncodeHexTx(static_cast<CTransaction>(wtx), RPCSerializationFlags()); entry.push_back(Pair("hex", strHex)); return entry; } UniValue abandontransaction(const JSONRPCRequest& request) { if (!EnsureWalletIsAvailable(request.fHelp)) return NullUniValue; if (request.fHelp || request.params.size() != 1) throw runtime_error( "abandontransaction \"txid\"\n" "\nMark in-wallet transaction <txid> as abandoned\n" "This will mark this transaction and all its in-wallet descendants as abandoned which will allow\n" "for their inputs to be respent. It can be used to replace \"stuck\" or evicted transactions.\n" "It only works on transactions which are not included in a block and are not currently in the mempool.\n" "It has no effect on transactions which are already conflicted or abandoned.\n" "\nArguments:\n" "1. \"txid\" (string, required) The transaction id\n" "\nResult:\n" "\nExamples:\n" + HelpExampleCli("abandontransaction", "\"c1700d6dd3e690866de56686e893cbe4e637eb5d84e3591cdfbbdbb0fcee49f8\"") + HelpExampleRpc("abandontransaction", "\"c1700d6dd3e690866de56686e893cbe4e637eb5d84e3591cdfbbdbb0fcee49f8\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); uint256 hash; hash.SetHex(request.params[0].get_str()); if (!pwalletMain->mapWallet.count(hash)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid or non-wallet transaction id"); if (!pwalletMain->AbandonTransaction(hash)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not eligible for abandonment"); return NullUniValue; } UniValue backupwallet(const JSONRPCRequest& request) { if (!EnsureWalletIsAvailable(request.fHelp)) return NullUniValue; if (request.fHelp || request.params.size() != 1) throw runtime_error( "backupwallet \"destination\"\n" "\nSafely copies current wallet file to destination, which can be a directory or a path with filename.\n" "\nArguments:\n" "1. \"destination\" (string) The destination directory or file\n" "\nExamples:\n" + HelpExampleCli("backupwallet", "\"backup.dat\"") + HelpExampleRpc("backupwallet", "\"backup.dat\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); string strDest = request.params[0].get_str(); if (!pwalletMain->BackupWallet(strDest)) throw JSONRPCError(RPC_WALLET_ERROR, "Error: Wallet backup failed!"); return NullUniValue; } UniValue keypoolrefill(const JSONRPCRequest& request) { if (!EnsureWalletIsAvailable(request.fHelp)) return NullUniValue; if (request.fHelp || request.params.size() > 1) throw runtime_error( "keypoolrefill ( newsize )\n" "\nFills the keypool." + HelpRequiringPassphrase() + "\n" "\nArguments\n" "1. newsize (numeric, optional, default=100) The new keypool size\n" "\nExamples:\n" + HelpExampleCli("keypoolrefill", "") + HelpExampleRpc("keypoolrefill", "") ); LOCK2(cs_main, pwalletMain->cs_wallet); // 0 is interpreted by TopUpKeyPool() as the default keypool size given by -keypool unsigned int kpSize = 0; if (request.params.size() > 0) { if (request.params[0].get_int() < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected valid size."); kpSize = (unsigned int)request.params[0].get_int(); } EnsureWalletIsUnlocked(); pwalletMain->TopUpKeyPool(kpSize); if (pwalletMain->GetKeyPoolSize() < kpSize) throw JSONRPCError(RPC_WALLET_ERROR, "Error refreshing keypool."); return NullUniValue; } static void LockWallet(CWallet* pWallet) { LOCK(cs_nWalletUnlockTime); nWalletUnlockTime = 0; pWallet->Lock(); } UniValue walletpassphrase(const JSONRPCRequest& request) { if (!EnsureWalletIsAvailable(request.fHelp)) return NullUniValue; if (pwalletMain->IsCrypted() && (request.fHelp || request.params.size() != 2)) throw runtime_error( "walletpassphrase \"passphrase\" timeout\n" "\nStores the wallet decryption key in memory for 'timeout' seconds.\n" "This is needed prior to performing transactions related to private keys such as sending superdigitalcoins\n" "\nArguments:\n" "1. \"passphrase\" (string, required) The wallet passphrase\n" "2. timeout (numeric, required) The time to keep the decryption key in seconds.\n" "\nNote:\n" "Issuing the walletpassphrase command while the wallet is already unlocked will set a new unlock\n" "time that overrides the old one.\n" "\nExamples:\n" "\nunlock the wallet for 60 seconds\n" + HelpExampleCli("walletpassphrase", "\"my pass phrase\" 60") + "\nLock the wallet again (before 60 seconds)\n" + HelpExampleCli("walletlock", "") + "\nAs json rpc call\n" + HelpExampleRpc("walletpassphrase", "\"my pass phrase\", 60") ); LOCK2(cs_main, pwalletMain->cs_wallet); if (request.fHelp) return true; if (!pwalletMain->IsCrypted()) throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrase was called."); // Note that the walletpassphrase is stored in request.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 request.params[0] mlock()'d to begin with. strWalletPass = request.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."); pwalletMain->TopUpKeyPool(); int64_t nSleepTime = request.params[1].get_int64(); LOCK(cs_nWalletUnlockTime); nWalletUnlockTime = GetTime() + nSleepTime; RPCRunLater("lockwallet", boost::bind(LockWallet, pwalletMain), nSleepTime); return NullUniValue; } UniValue walletpassphrasechange(const JSONRPCRequest& request) { if (!EnsureWalletIsAvailable(request.fHelp)) return NullUniValue; if (pwalletMain->IsCrypted() && (request.fHelp || request.params.size() != 2)) throw runtime_error( "walletpassphrasechange \"oldpassphrase\" \"newpassphrase\"\n" "\nChanges the wallet passphrase from 'oldpassphrase' to 'newpassphrase'.\n" "\nArguments:\n" "1. \"oldpassphrase\" (string) The current passphrase\n" "2. \"newpassphrase\" (string) The new passphrase\n" "\nExamples:\n" + HelpExampleCli("walletpassphrasechange", "\"old one\" \"new one\"") + HelpExampleRpc("walletpassphrasechange", "\"old one\", \"new one\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); if (request.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 request.params[0] mlock()'d to begin with. SecureString strOldWalletPass; strOldWalletPass.reserve(100); strOldWalletPass = request.params[0].get_str().c_str(); SecureString strNewWalletPass; strNewWalletPass.reserve(100); strNewWalletPass = request.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 NullUniValue; } UniValue walletlock(const JSONRPCRequest& request) { if (!EnsureWalletIsAvailable(request.fHelp)) return NullUniValue; if (pwalletMain->IsCrypted() && (request.fHelp || request.params.size() != 0)) throw runtime_error( "walletlock\n" "\nRemoves 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.\n" "\nExamples:\n" "\nSet the passphrase for 2 minutes to perform a transaction\n" + HelpExampleCli("walletpassphrase", "\"my pass phrase\" 120") + "\nPerform a send (requires passphrase set)\n" + HelpExampleCli("sendtoaddress", "\"SJuet69CPrXJV48v2AsjQWmcF3pmWVkB55\" 1.0") + "\nClear the passphrase since we are done before 2 minutes is up\n" + HelpExampleCli("walletlock", "") + "\nAs json rpc call\n" + HelpExampleRpc("walletlock", "") ); LOCK2(cs_main, pwalletMain->cs_wallet); if (request.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 NullUniValue; } UniValue encryptwallet(const JSONRPCRequest& request) { if (!EnsureWalletIsAvailable(request.fHelp)) return NullUniValue; if (!pwalletMain->IsCrypted() && (request.fHelp || request.params.size() != 1)) throw runtime_error( "encryptwallet \"passphrase\"\n" "\nEncrypts the wallet with 'passphrase'. This is for first time encryption.\n" "After this, any calls that interact with private keys such as sending or signing \n" "will require the passphrase to be set prior the making these calls.\n" "Use the walletpassphrase call for this, and then walletlock call.\n" "If the wallet is already encrypted, use the walletpassphrasechange call.\n" "Note that this will shutdown the server.\n" "\nArguments:\n" "1. \"passphrase\" (string) The pass phrase to encrypt the wallet with. It must be at least 1 character, but should be long.\n" "\nExamples:\n" "\nEncrypt you wallet\n" + HelpExampleCli("encryptwallet", "\"my pass phrase\"") + "\nNow set the passphrase to use the wallet, such as for signing or sending superdigitalcoin\n" + HelpExampleCli("walletpassphrase", "\"my pass phrase\"") + "\nNow we can so something like sign\n" + HelpExampleCli("signmessage", "\"address\" \"test message\"") + "\nNow lock the wallet again by removing the passphrase\n" + HelpExampleCli("walletlock", "") + "\nAs a json rpc call\n" + HelpExampleRpc("encryptwallet", "\"my pass phrase\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); if (request.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 request.params[0] mlock()'d to begin with. SecureString strWalletPass; strWalletPass.reserve(100); strWalletPass = request.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; SuperDigitalCoin server stopping, restart to run with encrypted wallet. The keypool has been flushed and a new HD seed was generated (if you are using HD). You need to make a new backup."; } UniValue lockunspent(const JSONRPCRequest& request) { if (!EnsureWalletIsAvailable(request.fHelp)) return NullUniValue; if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) throw runtime_error( "lockunspent unlock ([{\"txid\":\"txid\",\"vout\":n},...])\n" "\nUpdates list of temporarily unspendable outputs.\n" "Temporarily lock (unlock=false) or unlock (unlock=true) specified transaction outputs.\n" "If no transaction outputs are specified when unlocking then all current locked transaction outputs are unlocked.\n" "A locked transaction output will not be chosen by automatic coin selection, when spending superdigitalcoins.\n" "Locks are stored in memory only. Nodes start with zero locked outputs, and the locked output list\n" "is always cleared (by virtue of process exit) when a node stops or fails.\n" "Also see the listunspent call\n" "\nArguments:\n" "1. unlock (boolean, required) Whether to unlock (true) or lock (false) the specified transactions\n" "2. \"transactions\" (string, optional) A json array of objects. Each object the txid (string) vout (numeric)\n" " [ (json array of json objects)\n" " {\n" " \"txid\":\"id\", (string) The transaction id\n" " \"vout\": n (numeric) The output number\n" " }\n" " ,...\n" " ]\n" "\nResult:\n" "true|false (boolean) Whether the command was successful or not\n" "\nExamples:\n" "\nList the unspent transactions\n" + HelpExampleCli("listunspent", "") + "\nLock an unspent transaction\n" + HelpExampleCli("lockunspent", "false \"[{\\\"txid\\\":\\\"daaf44ec1e64e66ffda4a7e195ea60d5c8c8b602fc6bf22928582d3ff2530462\\\",\\\"vout\\\":1}]\"") + "\nList the locked transactions\n" + HelpExampleCli("listlockunspent", "") + "\nUnlock the transaction again\n" + HelpExampleCli("lockunspent", "true \"[{\\\"txid\\\":\\\"daaf44ec1e64e66ffda4a7e195ea60d5c8c8b602fc6bf22928582d3ff2530462\\\",\\\"vout\\\":1}]\"") + "\nAs a json rpc call\n" + HelpExampleRpc("lockunspent", "false, \"[{\\\"txid\\\":\\\"daaf44ec1e64e66ffda4a7e195ea60d5c8c8b602fc6bf22928582d3ff2530462\\\",\\\"vout\\\":1}]\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); if (request.params.size() == 1) RPCTypeCheck(request.params, boost::assign::list_of(UniValue::VBOOL)); else RPCTypeCheck(request.params, boost::assign::list_of(UniValue::VBOOL)(UniValue::VARR)); bool fUnlock = request.params[0].get_bool(); if (request.params.size() == 1) { if (fUnlock) pwalletMain->UnlockAllCoins(); return true; } UniValue outputs = request.params[1].get_array(); for (unsigned int idx = 0; idx < outputs.size(); idx++) { const UniValue& output = outputs[idx]; if (!output.isObject()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected object"); const UniValue& o = output.get_obj(); RPCTypeCheckObj(o, { {"txid", UniValueType(UniValue::VSTR)}, {"vout", UniValueType(UniValue::VNUM)}, }); string txid = find_value(o, "txid").get_str(); if (!IsHex(txid)) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected hex txid"); int nOutput = find_value(o, "vout").get_int(); if (nOutput < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive"); COutPoint outpt(uint256S(txid), nOutput); if (fUnlock) pwalletMain->UnlockCoin(outpt); else pwalletMain->LockCoin(outpt); } return true; } UniValue listlockunspent(const JSONRPCRequest& request) { if (!EnsureWalletIsAvailable(request.fHelp)) return NullUniValue; if (request.fHelp || request.params.size() > 0) throw runtime_error( "listlockunspent\n" "\nReturns list of temporarily unspendable outputs.\n" "See the lockunspent call to lock and unlock transactions for spending.\n" "\nResult:\n" "[\n" " {\n" " \"txid\" : \"transactionid\", (string) The transaction id locked\n" " \"vout\" : n (numeric) The vout value\n" " }\n" " ,...\n" "]\n" "\nExamples:\n" "\nList the unspent transactions\n" + HelpExampleCli("listunspent", "") + "\nLock an unspent transaction\n" + HelpExampleCli("lockunspent", "false \"[{\\\"txid\\\":\\\"daaf44ec1e64e66ffda4a7e195ea60d5c8c8b602fc6bf22928582d3ff2530462\\\",\\\"vout\\\":1}]\"") + "\nList the locked transactions\n" + HelpExampleCli("listlockunspent", "") + "\nUnlock the transaction again\n" + HelpExampleCli("lockunspent", "true \"[{\\\"txid\\\":\\\"daaf44ec1e64e66ffda4a7e195ea60d5c8c8b602fc6bf22928582d3ff2530462\\\",\\\"vout\\\":1}]\"") + "\nAs a json rpc call\n" + HelpExampleRpc("listlockunspent", "") ); LOCK2(cs_main, pwalletMain->cs_wallet); vector<COutPoint> vOutpts; pwalletMain->ListLockedCoins(vOutpts); UniValue ret(UniValue::VARR); BOOST_FOREACH(COutPoint &outpt, vOutpts) { UniValue o(UniValue::VOBJ); o.push_back(Pair("txid", outpt.hash.GetHex())); o.push_back(Pair("vout", (int)outpt.n)); ret.push_back(o); } return ret; } UniValue settxfee(const JSONRPCRequest& request) { if (!EnsureWalletIsAvailable(request.fHelp)) return NullUniValue; if (request.fHelp || request.params.size() < 1 || request.params.size() > 1) throw runtime_error( "settxfee amount\n" "\nSet the transaction fee per kB. Overwrites the paytxfee parameter.\n" "\nArguments:\n" "1. amount (numeric or string, required) The transaction fee in " + CURRENCY_UNIT + "/kB\n" "\nResult\n" "true|false (boolean) Returns true if successful\n" "\nExamples:\n" + HelpExampleCli("settxfee", "0.00001") + HelpExampleRpc("settxfee", "0.00001") ); LOCK2(cs_main, pwalletMain->cs_wallet); // Amount CAmount nAmount = AmountFromValue(request.params[0]); payTxFee = CFeeRate(nAmount, 1000); return true; } UniValue getwalletinfo(const JSONRPCRequest& request) { if (!EnsureWalletIsAvailable(request.fHelp)) return NullUniValue; if (request.fHelp || request.params.size() != 0) throw runtime_error( "getwalletinfo\n" "Returns an object containing various wallet state info.\n" "\nResult:\n" "{\n" " \"walletversion\": xxxxx, (numeric) the wallet version\n" " \"balance\": xxxxxxx, (numeric) the total confirmed balance of the wallet in " + CURRENCY_UNIT + "\n" " \"unconfirmed_balance\": xxx, (numeric) the total unconfirmed balance of the wallet in " + CURRENCY_UNIT + "\n" " \"immature_balance\": xxxxxx, (numeric) the total immature balance of the wallet in " + CURRENCY_UNIT + "\n" " \"txcount\": xxxxxxx, (numeric) the total number of transactions in the wallet\n" " \"keypoololdest\": xxxxxx, (numeric) the timestamp (seconds since Unix epoch) of the oldest pre-generated key in the key pool\n" " \"keypoolsize\": xxxx, (numeric) how many new keys are pre-generated\n" " \"unlocked_until\": ttt, (numeric) the timestamp in seconds since epoch (midnight Jan 1 1970 GMT) that the wallet is unlocked for transfers, or 0 if the wallet is locked\n" " \"paytxfee\": x.xxxx, (numeric) the transaction fee configuration, set in " + CURRENCY_UNIT + "/kB\n" " \"hdmasterkeyid\": \"<hash160>\" (string) the Hash160 of the HD master pubkey\n" "}\n" "\nExamples:\n" + HelpExampleCli("getwalletinfo", "") + HelpExampleRpc("getwalletinfo", "") ); LOCK2(cs_main, pwalletMain->cs_wallet); UniValue obj(UniValue::VOBJ); obj.push_back(Pair("walletversion", pwalletMain->GetVersion())); obj.push_back(Pair("balance", ValueFromAmount(pwalletMain->GetBalance()))); obj.push_back(Pair("unconfirmed_balance", ValueFromAmount(pwalletMain->GetUnconfirmedBalance()))); obj.push_back(Pair("immature_balance", ValueFromAmount(pwalletMain->GetImmatureBalance()))); obj.push_back(Pair("txcount", (int)pwalletMain->mapWallet.size())); obj.push_back(Pair("keypoololdest", pwalletMain->GetOldestKeyPoolTime())); obj.push_back(Pair("keypoolsize", (int)pwalletMain->GetKeyPoolSize())); if (pwalletMain->IsCrypted()) obj.push_back(Pair("unlocked_until", nWalletUnlockTime)); obj.push_back(Pair("paytxfee", ValueFromAmount(payTxFee.GetFeePerK()))); CKeyID masterKeyID = pwalletMain->GetHDChain().masterKeyID; if (!masterKeyID.IsNull()) obj.push_back(Pair("hdmasterkeyid", masterKeyID.GetHex())); return obj; } UniValue resendwallettransactions(const JSONRPCRequest& request) { if (!EnsureWalletIsAvailable(request.fHelp)) return NullUniValue; if (request.fHelp || request.params.size() != 0) throw runtime_error( "resendwallettransactions\n" "Immediately re-broadcast unconfirmed wallet transactions to all peers.\n" "Intended only for testing; the wallet code periodically re-broadcasts\n" "automatically.\n" "Returns array of transaction ids that were re-broadcast.\n" ); if (!g_connman) throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); LOCK2(cs_main, pwalletMain->cs_wallet); std::vector<uint256> txids = pwalletMain->ResendWalletTransactionsBefore(GetTime(), g_connman.get()); UniValue result(UniValue::VARR); BOOST_FOREACH(const uint256& txid, txids) { result.push_back(txid.ToString()); } return result; } UniValue listunspent(const JSONRPCRequest& request) { if (!EnsureWalletIsAvailable(request.fHelp)) return NullUniValue; if (request.fHelp || request.params.size() > 4) throw runtime_error( "listunspent ( minconf maxconf [\"addresses\",...] [include_unsafe] )\n" "\nReturns array of unspent transaction outputs\n" "with between minconf and maxconf (inclusive) confirmations.\n" "Optionally filter to only include txouts paid to specified addresses.\n" "\nArguments:\n" "1. minconf (numeric, optional, default=1) The minimum confirmations to filter\n" "2. maxconf (numeric, optional, default=9999999) The maximum confirmations to filter\n" "3. \"addresses\" (string) A json array of superdigitalcoin addresses to filter\n" " [\n" " \"address\" (string) superdigitalcoin address\n" " ,...\n" " ]\n" "4. include_unsafe (bool, optional, default=true) Include outputs that are not safe to spend\n" " because they come from unconfirmed untrusted transactions or unconfirmed\n" " replacement transactions (cases where we are less sure that a conflicting\n" " transaction won't be mined).\n" "\nResult\n" "[ (array of json object)\n" " {\n" " \"txid\" : \"txid\", (string) the transaction id \n" " \"vout\" : n, (numeric) the vout value\n" " \"address\" : \"address\", (string) the superdigitalcoin address\n" " \"account\" : \"account\", (string) DEPRECATED. The associated account, or \"\" for the default account\n" " \"scriptPubKey\" : \"key\", (string) the script key\n" " \"amount\" : x.xxx, (numeric) the transaction output amount in " + CURRENCY_UNIT + "\n" " \"confirmations\" : n, (numeric) The number of confirmations\n" " \"redeemScript\" : n (string) The redeemScript if scriptPubKey is P2SH\n" " \"spendable\" : xxx, (bool) Whether we have the private keys to spend this output\n" " \"solvable\" : xxx (bool) Whether we know how to spend this output, ignoring the lack of keys\n" " }\n" " ,...\n" "]\n" "\nExamples\n" + HelpExampleCli("listunspent", "") + HelpExampleCli("listunspent", "6 9999999 \"[\\\"LGPYcOdyoBnraaWX5tknkJZZWafjRAGVzx\\\",\\\"LLmraTr3qBjE2YseA3CnZ55la4TQmWnRY3\\\"]\"") + HelpExampleRpc("listunspent", "6, 9999999 \"[\\\"LGPYcOdyoBnraaWX5tknkJZZWafjRAGVzx\\\",\\\"LLmraTr3qBjE2YseA3CnZ55la4TQmWnRY3\\\"]\"") ); int nMinDepth = 1; if (request.params.size() > 0 && !request.params[0].isNull()) { RPCTypeCheckArgument(request.params[0], UniValue::VNUM); nMinDepth = request.params[0].get_int(); } int nMaxDepth = 9999999; if (request.params.size() > 1 && !request.params[1].isNull()) { RPCTypeCheckArgument(request.params[1], UniValue::VNUM); nMaxDepth = request.params[1].get_int(); } set<CBitcoinAddress> setAddress; if (request.params.size() > 2 && !request.params[2].isNull()) { RPCTypeCheckArgument(request.params[2], UniValue::VARR); UniValue inputs = request.params[2].get_array(); for (unsigned int idx = 0; idx < inputs.size(); idx++) { const UniValue& input = inputs[idx]; CBitcoinAddress address(input.get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid SuperDigitalCoin address: ")+input.get_str()); if (setAddress.count(address)) throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+input.get_str()); setAddress.insert(address); } } bool include_unsafe = true; if (request.params.size() > 3 && !request.params[3].isNull()) { RPCTypeCheckArgument(request.params[3], UniValue::VBOOL); include_unsafe = request.params[3].get_bool(); } UniValue results(UniValue::VARR); vector<COutput> vecOutputs; assert(pwalletMain != NULL); LOCK2(cs_main, pwalletMain->cs_wallet); pwalletMain->AvailableCoins(vecOutputs, !include_unsafe, NULL, true); BOOST_FOREACH(const COutput& out, vecOutputs) { if (out.nDepth < nMinDepth || out.nDepth > nMaxDepth) continue; CTxDestination address; const CScript& scriptPubKey = out.tx->tx->vout[out.i].scriptPubKey; bool fValidAddress = ExtractDestination(scriptPubKey, address); if (setAddress.size() && (!fValidAddress || !setAddress.count(address))) continue; UniValue entry(UniValue::VOBJ); entry.push_back(Pair("txid", out.tx->GetHash().GetHex())); entry.push_back(Pair("vout", out.i)); if (fValidAddress) { entry.push_back(Pair("address", CBitcoinAddress(address).ToString())); if (pwalletMain->mapAddressBook.count(address)) entry.push_back(Pair("account", pwalletMain->mapAddressBook[address].name)); if (scriptPubKey.IsPayToScriptHash()) { const CScriptID& hash = boost::get<CScriptID>(address); CScript redeemScript; if (pwalletMain->GetCScript(hash, redeemScript)) entry.push_back(Pair("redeemScript", HexStr(redeemScript.begin(), redeemScript.end()))); } } entry.push_back(Pair("scriptPubKey", HexStr(scriptPubKey.begin(), scriptPubKey.end()))); entry.push_back(Pair("amount", ValueFromAmount(out.tx->tx->vout[out.i].nValue))); entry.push_back(Pair("confirmations", out.nDepth)); entry.push_back(Pair("spendable", out.fSpendable)); entry.push_back(Pair("solvable", out.fSolvable)); results.push_back(entry); } return results; } UniValue fundrawtransaction(const JSONRPCRequest& request) { if (!EnsureWalletIsAvailable(request.fHelp)) return NullUniValue; if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) throw runtime_error( "fundrawtransaction \"hexstring\" ( options )\n" "\nAdd inputs to a transaction until it has enough in value to meet its out value.\n" "This will not modify existing inputs, and will add at most one change output to the outputs.\n" "No existing outputs will be modified unless \"subtractFeeFromOutputs\" is specified.\n" "Note that inputs which were signed may need to be resigned after completion since in/outputs have been added.\n" "The inputs added will not be signed, use signrawtransaction for that.\n" "Note that all existing inputs must have their previous output transaction be in the wallet.\n" "Note that all inputs selected must be of standard form and P2SH scripts must be\n" "in the wallet using importaddress or addmultisigaddress (to calculate fees).\n" "You can see whether this is the case by checking the \"solvable\" field in the listunspent output.\n" "Only pay-to-pubkey, multisig, and P2SH versions thereof are currently supported for watch-only\n" "\nArguments:\n" "1. \"hexstring\" (string, required) The hex string of the raw transaction\n" "2. options (object, optional)\n" " {\n" " \"changeAddress\" (string, optional, default pool address) The superdigitalcoin address to receive the change\n" " \"changePosition\" (numeric, optional, default random) The index of the change output\n" " \"includeWatching\" (boolean, optional, default false) Also select inputs which are watch only\n" " \"lockUnspents\" (boolean, optional, default false) Lock selected unspent outputs\n" " \"reserveChangeKey\" (boolean, optional, default true) Reserves the change output key from the keypool\n" " \"feeRate\" (numeric, optional, default not set: makes wallet determine the fee) Set a specific feerate (" + CURRENCY_UNIT + " per KB)\n" " \"subtractFeeFromOutputs\" (array, optional) A json array of integers.\n" " The fee will be equally deducted from the amount of each specified output.\n" " The outputs are specified by their zero-based index, before any change output is added.\n" " Those recipients will receive less superdigitalcoins than you enter in their corresponding amount field.\n" " If no outputs are specified here, the sender pays the fee.\n" " [vout_index,...]\n" " }\n" " for backward compatibility: passing in a true instead of an object will result in {\"includeWatching\":true}\n" "\nResult:\n" "{\n" " \"hex\": \"value\", (string) The resulting raw transaction (hex-encoded string)\n" " \"fee\": n, (numeric) Fee in " + CURRENCY_UNIT + " the resulting transaction pays\n" " \"changepos\": n (numeric) The position of the added change output, or -1\n" "}\n" "\nExamples:\n" "\nCreate a transaction with no inputs\n" + HelpExampleCli("createrawtransaction", "\"[]\" \"{\\\"myaddress\\\":0.01}\"") + "\nAdd sufficient unsigned inputs to meet the output value\n" + HelpExampleCli("fundrawtransaction", "\"rawtransactionhex\"") + "\nSign the transaction\n" + HelpExampleCli("signrawtransaction", "\"fundedtransactionhex\"") + "\nSend the transaction\n" + HelpExampleCli("sendrawtransaction", "\"signedtransactionhex\"") ); RPCTypeCheck(request.params, boost::assign::list_of(UniValue::VSTR)); CTxDestination changeAddress = CNoDestination(); int changePosition = -1; bool includeWatching = false; bool lockUnspents = false; bool reserveChangeKey = true; CFeeRate feeRate = CFeeRate(0); bool overrideEstimatedFeerate = false; UniValue subtractFeeFromOutputs; set<int> setSubtractFeeFromOutputs; if (request.params.size() > 1) { if (request.params[1].type() == UniValue::VBOOL) { // backward compatibility bool only fallback includeWatching = request.params[1].get_bool(); } else { RPCTypeCheck(request.params, boost::assign::list_of(UniValue::VSTR)(UniValue::VOBJ)); UniValue options = request.params[1]; RPCTypeCheckObj(options, { {"changeAddress", UniValueType(UniValue::VSTR)}, {"changePosition", UniValueType(UniValue::VNUM)}, {"includeWatching", UniValueType(UniValue::VBOOL)}, {"lockUnspents", UniValueType(UniValue::VBOOL)}, {"reserveChangeKey", UniValueType(UniValue::VBOOL)}, {"feeRate", UniValueType()}, // will be checked below {"subtractFeeFromOutputs", UniValueType(UniValue::VARR)}, }, true, true); if (options.exists("changeAddress")) { CBitcoinAddress address(options["changeAddress"].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_PARAMETER, "changeAddress must be a valid superdigitalcoin address"); changeAddress = address.Get(); } if (options.exists("changePosition")) changePosition = options["changePosition"].get_int(); if (options.exists("includeWatching")) includeWatching = options["includeWatching"].get_bool(); if (options.exists("lockUnspents")) lockUnspents = options["lockUnspents"].get_bool(); if (options.exists("reserveChangeKey")) reserveChangeKey = options["reserveChangeKey"].get_bool(); if (options.exists("feeRate")) { feeRate = CFeeRate(AmountFromValue(options["feeRate"])); overrideEstimatedFeerate = true; } if (options.exists("subtractFeeFromOutputs")) subtractFeeFromOutputs = options["subtractFeeFromOutputs"].get_array(); } } // parse hex string from parameter CMutableTransaction tx; if (!DecodeHexTx(tx, request.params[0].get_str(), true)) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed"); if (tx.vout.size() == 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "TX must have at least one output"); if (changePosition != -1 && (changePosition < 0 || (unsigned int)changePosition > tx.vout.size())) throw JSONRPCError(RPC_INVALID_PARAMETER, "changePosition out of bounds"); for (unsigned int idx = 0; idx < subtractFeeFromOutputs.size(); idx++) { int pos = subtractFeeFromOutputs[idx].get_int(); if (setSubtractFeeFromOutputs.count(pos)) throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid parameter, duplicated position: %d", pos)); if (pos < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid parameter, negative position: %d", pos)); if (pos >= int(tx.vout.size())) throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid parameter, position too large: %d", pos)); setSubtractFeeFromOutputs.insert(pos); } CAmount nFeeOut; string strFailReason; if(!pwalletMain->FundTransaction(tx, nFeeOut, overrideEstimatedFeerate, feeRate, changePosition, strFailReason, includeWatching, lockUnspents, setSubtractFeeFromOutputs, reserveChangeKey, changeAddress)) throw JSONRPCError(RPC_INTERNAL_ERROR, strFailReason); UniValue result(UniValue::VOBJ); result.push_back(Pair("hex", EncodeHexTx(tx))); result.push_back(Pair("changepos", changePosition)); result.push_back(Pair("fee", ValueFromAmount(nFeeOut))); return result; } // Calculate the size of the transaction assuming all signatures are max size // Use DummySignatureCreator, which inserts 72 byte signatures everywhere. // TODO: re-use this in CWallet::CreateTransaction (right now // CreateTransaction uses the constructed dummy-signed tx to do a priority // calculation, but we should be able to refactor after priority is removed). // NOTE: this requires that all inputs must be in mapWallet (eg the tx should // be IsAllFromMe). int64_t CalculateMaximumSignedTxSize(const CTransaction &tx) { CMutableTransaction txNew(tx); std::vector<pair<CWalletTx *, unsigned int>> vCoins; // Look up the inputs. We should have already checked that this transaction // IsAllFromMe(ISMINE_SPENDABLE), so every input should already be in our // wallet, with a valid index into the vout array. for (auto& input : tx.vin) { const auto mi = pwalletMain->mapWallet.find(input.prevout.hash); assert(mi != pwalletMain->mapWallet.end() && input.prevout.n < mi->second.tx->vout.size()); vCoins.emplace_back(make_pair(&(mi->second), input.prevout.n)); } if (!pwalletMain->DummySignTx(txNew, vCoins)) { // This should never happen, because IsAllFromMe(ISMINE_SPENDABLE) // implies that we can sign for every input. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction contains inputs that cannot be signed"); } return GetVirtualTransactionSize(txNew); } UniValue bumpfee(const JSONRPCRequest& request) { if (!EnsureWalletIsAvailable(request.fHelp)) { return NullUniValue; } if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) { throw runtime_error( "bumpfee \"txid\" ( options ) \n" "\nBumps the fee of an opt-in-RBF transaction T, replacing it with a new transaction B.\n" "An opt-in RBF transaction with the given txid must be in the wallet.\n" "The command will pay the additional fee by decreasing (or perhaps removing) its change output.\n" "If the change output is not big enough to cover the increased fee, the command will currently fail\n" "instead of adding new inputs to compensate. (A future implementation could improve this.)\n" "The command will fail if the wallet or mempool contains a transaction that spends one of T's outputs.\n" "By default, the new fee will be calculated automatically using estimatefee.\n" "The user can specify a confirmation target for estimatefee.\n" "Alternatively, the user can specify totalFee, or use RPC setpaytxfee to set a higher fee rate.\n" "At a minimum, the new fee rate must be high enough to pay an additional new relay fee (incrementalfee\n" "returned by getnetworkinfo) to enter the node's mempool.\n" "\nArguments:\n" "1. txid (string, required) The txid to be bumped\n" "2. options (object, optional)\n" " {\n" " \"confTarget\" (numeric, optional) Confirmation target (in blocks)\n" " \"totalFee\" (numeric, optional) Total fee (NOT feerate) to pay, in satoshis.\n" " In rare cases, the actual fee paid might be slightly higher than the specified\n" " totalFee if the tx change output has to be removed because it is too close to\n" " the dust threshold.\n" " \"replaceable\" (boolean, optional, default true) Whether the new transaction should still be\n" " marked bip-125 replaceable. If true, the sequence numbers in the transaction will\n" " be left unchanged from the original. If false, any input sequence numbers in the\n" " original transaction that were less than 0xfffffffe will be increased to 0xfffffffe\n" " so the new transaction will not be explicitly bip-125 replaceable (though it may\n" " still be replacable in practice, for example if it has unconfirmed ancestors which\n" " are replaceable).\n" " }\n" "\nResult:\n" "{\n" " \"txid\": \"value\", (string) The id of the new transaction\n" " \"origfee\": n, (numeric) Fee of the replaced transaction\n" " \"fee\": n, (numeric) Fee of the new transaction\n" " \"errors\": [ str... ] (json array of strings) Errors encountered during processing (may be empty)\n" "}\n" "\nExamples:\n" "\nBump the fee, get the new transaction\'s txid\n" + HelpExampleCli("bumpfee", "<txid>")); } RPCTypeCheck(request.params, boost::assign::list_of(UniValue::VSTR)(UniValue::VOBJ)); uint256 hash; hash.SetHex(request.params[0].get_str()); // retrieve the original tx from the wallet LOCK2(cs_main, pwalletMain->cs_wallet); EnsureWalletIsUnlocked(); if (!pwalletMain->mapWallet.count(hash)) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid or non-wallet transaction id"); } CWalletTx& wtx = pwalletMain->mapWallet[hash]; if (pwalletMain->HasWalletSpend(hash)) { throw JSONRPCError(RPC_MISC_ERROR, "Transaction has descendants in the wallet"); } { LOCK(mempool.cs); auto it = mempool.mapTx.find(hash); if (it != mempool.mapTx.end() && it->GetCountWithDescendants() > 1) { throw JSONRPCError(RPC_MISC_ERROR, "Transaction has descendants in the mempool"); } } if (wtx.GetDepthInMainChain() != 0) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction has been mined, or is conflicted with a mined transaction"); } if (!SignalsOptInRBF(wtx)) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction is not BIP 125 replaceable"); } if (wtx.mapValue.count("replaced_by_txid")) { throw JSONRPCError(RPC_INVALID_REQUEST, strprintf("Cannot bump transaction %s which was already bumped by transaction %s", hash.ToString(), wtx.mapValue.at("replaced_by_txid"))); } // check that original tx consists entirely of our inputs // if not, we can't bump the fee, because the wallet has no way of knowing the value of the other inputs (thus the fee) if (!pwalletMain->IsAllFromMe(wtx, ISMINE_SPENDABLE)) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction contains inputs that don't belong to this wallet"); } // figure out which output was change // if there was no change output or multiple change outputs, fail int nOutput = -1; for (size_t i = 0; i < wtx.tx->vout.size(); ++i) { if (pwalletMain->IsChange(wtx.tx->vout[i])) { if (nOutput != -1) { throw JSONRPCError(RPC_MISC_ERROR, "Transaction has multiple change outputs"); } nOutput = i; } } if (nOutput == -1) { throw JSONRPCError(RPC_MISC_ERROR, "Transaction does not have a change output"); } // Calculate the expected size of the new transaction. int64_t txSize = GetVirtualTransactionSize(*(wtx.tx)); const int64_t maxNewTxSize = CalculateMaximumSignedTxSize(*wtx.tx); // optional parameters bool specifiedConfirmTarget = false; int newConfirmTarget = nTxConfirmTarget; CAmount totalFee = 0; bool replaceable = true; if (request.params.size() > 1) { UniValue options = request.params[1]; RPCTypeCheckObj(options, { {"confTarget", UniValueType(UniValue::VNUM)}, {"totalFee", UniValueType(UniValue::VNUM)}, {"replaceable", UniValueType(UniValue::VBOOL)}, }, true, true); if (options.exists("confTarget") && options.exists("totalFee")) { throw JSONRPCError(RPC_INVALID_PARAMETER, "confTarget and totalFee options should not both be set. Please provide either a confirmation target for fee estimation or an explicit total fee for the transaction."); } else if (options.exists("confTarget")) { specifiedConfirmTarget = true; newConfirmTarget = options["confTarget"].get_int(); if (newConfirmTarget <= 0) { // upper-bound will be checked by estimatefee/smartfee throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid confTarget (cannot be <= 0)"); } } else if (options.exists("totalFee")) { totalFee = options["totalFee"].get_int64(); CAmount requiredFee = CWallet::GetRequiredFee(maxNewTxSize); if (totalFee < requiredFee ) { throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Insufficient totalFee (cannot be less than required fee %s)", FormatMoney(requiredFee))); } } if (options.exists("replaceable")) { replaceable = options["replaceable"].get_bool(); } } // calculate the old fee and fee-rate CAmount nOldFee = wtx.GetDebit(ISMINE_SPENDABLE) - wtx.tx->GetValueOut(); CFeeRate nOldFeeRate(nOldFee, txSize); CAmount nNewFee; CFeeRate nNewFeeRate; // The wallet uses a conservative WALLET_INCREMENTAL_RELAY_FEE value to // future proof against changes to network wide policy for incremental relay // fee that our node may not be aware of. CFeeRate walletIncrementalRelayFee = CFeeRate(WALLET_INCREMENTAL_RELAY_FEE); if (::incrementalRelayFee > walletIncrementalRelayFee) { walletIncrementalRelayFee = ::incrementalRelayFee; } if (totalFee > 0) { CAmount minTotalFee = nOldFeeRate.GetFee(maxNewTxSize) + ::incrementalRelayFee.GetFee(maxNewTxSize); if (totalFee < minTotalFee) { throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Insufficient totalFee, must be at least %s (oldFee %s + incrementalFee %s)", FormatMoney(minTotalFee), FormatMoney(nOldFeeRate.GetFee(maxNewTxSize)), FormatMoney(::incrementalRelayFee.GetFee(maxNewTxSize)))); } nNewFee = totalFee; nNewFeeRate = CFeeRate(totalFee, maxNewTxSize); } else { // if user specified a confirm target then don't consider any global payTxFee if (specifiedConfirmTarget) { nNewFee = CWallet::GetMinimumFee(maxNewTxSize, newConfirmTarget, mempool, CAmount(0)); } // otherwise use the regular wallet logic to select payTxFee or default confirm target else { nNewFee = CWallet::GetMinimumFee(maxNewTxSize, newConfirmTarget, mempool); } nNewFeeRate = CFeeRate(nNewFee, maxNewTxSize); // New fee rate must be at least old rate + minimum incremental relay rate // walletIncrementalRelayFee.GetFeePerK() should be exact, because it's initialized // in that unit (fee per kb). // However, nOldFeeRate is a calculated value from the tx fee/size, so // add 1 satoshi to the result, because it may have been rounded down. if (nNewFeeRate.GetFeePerK() < nOldFeeRate.GetFeePerK() + 1 + walletIncrementalRelayFee.GetFeePerK()) { nNewFeeRate = CFeeRate(nOldFeeRate.GetFeePerK() + 1 + walletIncrementalRelayFee.GetFeePerK()); nNewFee = nNewFeeRate.GetFee(maxNewTxSize); } } // Check that in all cases the new fee doesn't violate maxTxFee if (nNewFee > maxTxFee) { throw JSONRPCError(RPC_MISC_ERROR, strprintf("Specified or calculated fee %s is too high (cannot be higher than maxTxFee %s)", FormatMoney(nNewFee), FormatMoney(maxTxFee))); } // check that fee rate is higher than mempool's minimum fee // (no point in bumping fee if we know that the new tx won't be accepted to the mempool) // This may occur if the user set TotalFee or paytxfee too low, if fallbackfee is too low, or, perhaps, // in a rare situation where the mempool minimum fee increased significantly since the fee estimation just a // moment earlier. In this case, we report an error to the user, who may use totalFee to make an adjustment. CFeeRate minMempoolFeeRate = mempool.GetMinFee(GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000); if (nNewFeeRate.GetFeePerK() < minMempoolFeeRate.GetFeePerK()) { throw JSONRPCError(RPC_MISC_ERROR, strprintf("New fee rate (%s) is less than the minimum fee rate (%s) to get into the mempool. totalFee value should to be at least %s or settxfee value should be at least %s to add transaction.", FormatMoney(nNewFeeRate.GetFeePerK()), FormatMoney(minMempoolFeeRate.GetFeePerK()), FormatMoney(minMempoolFeeRate.GetFee(maxNewTxSize)), FormatMoney(minMempoolFeeRate.GetFeePerK()))); } // Now modify the output to increase the fee. // If the output is not large enough to pay the fee, fail. CAmount nDelta = nNewFee - nOldFee; assert(nDelta > 0); CMutableTransaction tx(*(wtx.tx)); CTxOut* poutput = &(tx.vout[nOutput]); if (poutput->nValue < nDelta) { throw JSONRPCError(RPC_MISC_ERROR, "Change output is too small to bump the fee"); } // If the output would become dust, discard it (converting the dust to fee) poutput->nValue -= nDelta; if (poutput->nValue <= poutput->GetDustThreshold(::dustRelayFee)) { LogPrint("rpc", "Bumping fee and discarding dust output\n"); nNewFee += poutput->nValue; tx.vout.erase(tx.vout.begin() + nOutput); } // Mark new tx not replaceable, if requested. if (!replaceable) { for (auto& input : tx.vin) { if (input.nSequence < 0xfffffffe) input.nSequence = 0xfffffffe; } } // sign the new tx CTransaction txNewConst(tx); int nIn = 0; for (auto& input : tx.vin) { std::map<uint256, CWalletTx>::const_iterator mi = pwalletMain->mapWallet.find(input.prevout.hash); assert(mi != pwalletMain->mapWallet.end() && input.prevout.n < mi->second.tx->vout.size()); const CScript& scriptPubKey = mi->second.tx->vout[input.prevout.n].scriptPubKey; const CAmount& amount = mi->second.tx->vout[input.prevout.n].nValue; SignatureData sigdata; if (!ProduceSignature(TransactionSignatureCreator(pwalletMain, &txNewConst, nIn, amount, SIGHASH_ALL), scriptPubKey, sigdata)) { throw JSONRPCError(RPC_WALLET_ERROR, "Can't sign transaction."); } UpdateTransaction(tx, nIn, sigdata); nIn++; } // commit/broadcast the tx CReserveKey reservekey(pwalletMain); CWalletTx wtxBumped(pwalletMain, MakeTransactionRef(std::move(tx))); wtxBumped.mapValue = wtx.mapValue; wtxBumped.mapValue["replaces_txid"] = hash.ToString(); wtxBumped.vOrderForm = wtx.vOrderForm; wtxBumped.strFromAccount = wtx.strFromAccount; wtxBumped.fTimeReceivedIsTxTime = true; wtxBumped.fFromMe = true; CValidationState state; if (!pwalletMain->CommitTransaction(wtxBumped, reservekey, g_connman.get(), state)) { // NOTE: CommitTransaction never returns false, so this should never happen. throw JSONRPCError(RPC_WALLET_ERROR, strprintf("Error: The transaction was rejected! Reason given: %s", state.GetRejectReason())); } UniValue vErrors(UniValue::VARR); if (state.IsInvalid()) { // This can happen if the mempool rejected the transaction. Report // what happened in the "errors" response. vErrors.push_back(strprintf("Error: The transaction was rejected: %s", FormatStateMessage(state))); } // mark the original tx as bumped if (!pwalletMain->MarkReplaced(wtx.GetHash(), wtxBumped.GetHash())) { // TODO: see if JSON-RPC has a standard way of returning a response // along with an exception. It would be good to return information about // wtxBumped to the caller even if marking the original transaction // replaced does not succeed for some reason. vErrors.push_back("Error: Created new bumpfee transaction but could not mark the original transaction as replaced."); } UniValue result(UniValue::VOBJ); result.push_back(Pair("txid", wtxBumped.GetHash().GetHex())); result.push_back(Pair("origfee", ValueFromAmount(nOldFee))); result.push_back(Pair("fee", ValueFromAmount(nNewFee))); result.push_back(Pair("errors", vErrors)); return result; } extern UniValue dumpprivkey(const JSONRPCRequest& request); // in rpcdump.cpp extern UniValue importprivkey(const JSONRPCRequest& request); extern UniValue importaddress(const JSONRPCRequest& request); extern UniValue importpubkey(const JSONRPCRequest& request); extern UniValue dumpwallet(const JSONRPCRequest& request); extern UniValue importwallet(const JSONRPCRequest& request); extern UniValue importprunedfunds(const JSONRPCRequest& request); extern UniValue removeprunedfunds(const JSONRPCRequest& request); extern UniValue importmulti(const JSONRPCRequest& request); static const CRPCCommand commands[] = { // category name actor (function) okSafeMode // --------------------- ------------------------ ----------------------- ---------- { "rawtransactions", "fundrawtransaction", &fundrawtransaction, false, {"hexstring","options"} }, { "hidden", "resendwallettransactions", &resendwallettransactions, true, {} }, { "wallet", "abandontransaction", &abandontransaction, false, {"txid"} }, { "wallet", "addmultisigaddress", &addmultisigaddress, true, {"nrequired","keys","account"} }, { "wallet", "addwitnessaddress", &addwitnessaddress, true, {"address"} }, { "wallet", "backupwallet", &backupwallet, true, {"destination"} }, { "wallet", "bumpfee", &bumpfee, true, {"txid", "options"} }, { "wallet", "dumpprivkey", &dumpprivkey, true, {"address"} }, { "wallet", "dumpwallet", &dumpwallet, true, {"filename"} }, { "wallet", "encryptwallet", &encryptwallet, true, {"passphrase"} }, { "wallet", "getaccountaddress", &getaccountaddress, true, {"account"} }, { "wallet", "getaccount", &getaccount, true, {"address"} }, { "wallet", "getaddressesbyaccount", &getaddressesbyaccount, true, {"account"} }, { "wallet", "getbalance", &getbalance, false, {"account","minconf","include_watchonly"} }, { "wallet", "getnewaddress", &getnewaddress, true, {"account"} }, { "wallet", "getrawchangeaddress", &getrawchangeaddress, true, {} }, { "wallet", "getreceivedbyaccount", &getreceivedbyaccount, false, {"account","minconf"} }, { "wallet", "getreceivedbyaddress", &getreceivedbyaddress, false, {"address","minconf"} }, { "wallet", "gettransaction", &gettransaction, false, {"txid","include_watchonly"} }, { "wallet", "getunconfirmedbalance", &getunconfirmedbalance, false, {} }, { "wallet", "getwalletinfo", &getwalletinfo, false, {} }, { "wallet", "importmulti", &importmulti, true, {"requests","options"} }, { "wallet", "importprivkey", &importprivkey, true, {"privkey","label","rescan"} }, { "wallet", "importwallet", &importwallet, true, {"filename"} }, { "wallet", "importaddress", &importaddress, true, {"address","label","rescan","p2sh"} }, { "wallet", "importprunedfunds", &importprunedfunds, true, {"rawtransaction","txoutproof"} }, { "wallet", "importpubkey", &importpubkey, true, {"pubkey","label","rescan"} }, { "wallet", "keypoolrefill", &keypoolrefill, true, {"newsize"} }, { "wallet", "listaccounts", &listaccounts, false, {"minconf","include_watchonly"} }, { "wallet", "listaddressgroupings", &listaddressgroupings, false, {} }, { "wallet", "listlockunspent", &listlockunspent, false, {} }, { "wallet", "listreceivedbyaccount", &listreceivedbyaccount, false, {"minconf","include_empty","include_watchonly"} }, { "wallet", "listreceivedbyaddress", &listreceivedbyaddress, false, {"minconf","include_empty","include_watchonly"} }, { "wallet", "listsinceblock", &listsinceblock, false, {"blockhash","target_confirmations","include_watchonly"} }, { "wallet", "listtransactions", &listtransactions, false, {"account","count","skip","include_watchonly"} }, { "wallet", "listunspent", &listunspent, false, {"minconf","maxconf","addresses","include_unsafe"} }, { "wallet", "lockunspent", &lockunspent, true, {"unlock","transactions"} }, { "wallet", "move", &movecmd, false, {"fromaccount","toaccount","amount","minconf","comment"} }, { "wallet", "sendfrom", &sendfrom, false, {"fromaccount","toaddress","amount","minconf","comment","comment_to"} }, { "wallet", "sendmany", &sendmany, false, {"fromaccount","amounts","minconf","comment","subtractfeefrom"} }, { "wallet", "sendtoaddress", &sendtoaddress, false, {"address","amount","comment","comment_to","subtractfeefromamount"} }, { "wallet", "setaccount", &setaccount, true, {"address","account"} }, { "wallet", "settxfee", &settxfee, true, {"amount"} }, { "wallet", "signmessage", &signmessage, true, {"address","message"} }, { "wallet", "walletlock", &walletlock, true, {} }, { "wallet", "walletpassphrasechange", &walletpassphrasechange, true, {"oldpassphrase","newpassphrase"} }, { "wallet", "walletpassphrase", &walletpassphrase, true, {"passphrase","timeout"} }, { "wallet", "removeprunedfunds", &removeprunedfunds, true, {"txid"} }, }; void RegisterWalletRPCCommands(CRPCTable &t) { if (GetBoolArg("-disablewallet", false)) return; for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++) t.appendCommand(commands[vcidx].name, &commands[vcidx]); }
[ "lun1109@hotmail.com" ]
lun1109@hotmail.com
ed4f6629c6f0ac53e199ddd261b192631f389ce8
7c1a1e5a726cb5889bff26399e7590fd45cca123
/Animations/exploringSoundStream/src/ofApp.cpp
c99e2576ba9bc9399f07bf7c91cbca26759e3a36
[]
no_license
jkmingwen/CapstoneProject
85d08d3006ef54c03cad7d8d0c94c4d9564233c3
fd7fb6563b603711385d48709bcc9afc9da2064c
refs/heads/master
2020-04-16T19:52:08.692296
2019-04-13T14:49:28
2019-04-13T14:49:28
165,877,283
1
0
null
null
null
null
UTF-8
C++
false
false
5,200
cpp
#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup(){ int bufferSize = 256; // set buffer size ofSoundStreamSettings settings; // create ofSoundStreamSettings object ofBackground(0, 0, 0); bufferCounter = 0; drawCounter = 0; smoothedVol = 0.0; scaledVol = 0.0; left.assign(bufferSize, 0.0); right.assign(bufferSize, 0.0); volHistory.assign(400, 0.0); // initialising ofSoundStreamSettings auto devices = soundStream.getMatchingDevices("UR22"); // <- name of input device if (!devices.empty()) { settings.setInDevice(devices[0]); } settings.setInListener(this); // current ofSoundStream as listener settings.sampleRate = 44100; settings.numOutputChannels = 0; settings.numInputChannels = 2; // stereo settings.bufferSize = bufferSize; soundStream.setup(settings); } //-------------------------------------------------------------- void ofApp::update() { scaledVol = ofMap(smoothedVol, 0.0, 0.17, 0.0, 1.0, true); // record the volume into an array volHistory.push_back(scaledVol); // if we are bigger the the size we want to record, we drop the oldest value if( volHistory.size() >= 400 ) { volHistory.erase(volHistory.begin(), volHistory.begin()+1); } } //-------------------------------------------------------------- void ofApp::draw(){ ofSetColor(255, 255, 255); //ofDrawBitmapString("Scaled average vol (0-100): " + ofToString(scaledVol * 100.0, 0), 4, 18); //ofDrawBitmapString("Smoothed average vol (0-100): " + ofToString(smoothedVol), 4, 30); //string reportString = "buffers received: "+ofToString(bufferCounter)+"\n"; //ofDrawBitmapString(reportString, 4, 60); // // left channel // ofPushStyle(); // isolates graphics changes (i.e. colour) // ofPushMatrix(); // isolates coordinate changes (i.e. translate) // ofSetColor(200); // ofTranslate(256, 385); // ofSetLineWidth(3); // ofNoFill(); // ofBeginShape(); // for (unsigned int i = 0; i < left.size(); i++) // { // ofDrawCircle(i*2, 100 - left[i]*300.0f, (scaledVol * scaledVol * 150)); // } // ofEndShape(false); // false arg tells it not to auto close shape // ofPopMatrix(); // ofPopStyle(); // right channel: use only right channel as that's where the audio interface is // feeding in input ofPushStyle(); // isolates graphics changes (i.e. colour) ofPushMatrix(); // isolates coordinate changes (i.e. translate) ofSetColor(200); ofTranslate(150, 385); ofSetLineWidth(1); ofNoFill(); ofBeginShape(); for (unsigned int i = 0; i < right.size(); i++) { ofDrawCircle(i*3 + ofGetWidth()/6, 50 - right[i]*300.0f, (scaledVol * scaledVol * 150)); } ofEndShape(false); // false arg tells it not to auto close shape ofPopMatrix(); ofPopStyle(); } //-------------------------------------------------------------- void ofApp::audioIn(ofSoundBuffer &input) { float currentVol = 0.0; int numCounted = 0; // calculate rms of sample volumes for (int i = 0; i < input.getNumFrames(); i++, numCounted+=2) { // samples are interleaved (L on even, R on odd) left[i] = input[i*2] * 0.5; right[i] = input[i*2+1] * 0.5; // square volumes on both channels and add them up currentVol += left[i] * left[i]; currentVol += right[i] * right[i]; } currentVol /= (float) numCounted; // mean currentVol = sqrt(currentVol); // square root smoothedVol *= 0.93; smoothedVol += 0.07 * currentVol; bufferCounter++; } //-------------------------------------------------------------- //-------------------------------------------------------------- void ofApp::keyPressed(int key) { if( key == 's' ){ soundStream.start(); } if( key == 'e' ){ soundStream.stop(); } } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseEntered(int x, int y){ } //-------------------------------------------------------------- void ofApp::mouseExited(int x, int y){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ }
[ "jkmingwen@gmail.com" ]
jkmingwen@gmail.com
a427afe3e55159074a059b88c7aa20866db6cfd2
542f103e5b3b36ee0aefa937d4128d0ca77dcfdf
/check anagram palindrome.cpp
ca9e2ddac4d04a267a6c037d46f18ba845121055
[]
no_license
muskan2099/Hashmaps-and-Heaps-Interview-Questions
3ae0ceb5518a5019d3d5a8d4277b542b9bb45264
aa81147ac143e4c7851c7b203a0b3a08b4519475
refs/heads/master
2022-11-08T12:20:23.230878
2020-06-25T12:58:56
2020-06-25T12:58:56
274,912,276
0
0
null
null
null
null
UTF-8
C++
false
false
683
cpp
#include <bits/stdc++.h> using namespace std; bool tell(string str){ unordered_map<char, int> hash; for(int i = 0; i < str.length(); i++){ if(hash.count(str[i]) == 0){ hash[str[i]] = 1; } else{ hash[str[i]]++; } } //unordered_map<int, int> freq; unordered_map<char, int> :: iterator it; int even = 0; int odd = 0; for(it = hash.begin(); it != hash.end(); it++){ if(it->second%2 == 0){ even++; } else{ odd++; } } if(odd == 0){ return true; } else if(odd == 1){ return true; } else{ return false; } } int main(){ string input = "geeksfgeeks"; cout << tell(input) << endl; return 0; }
[ "noreply@github.com" ]
noreply@github.com
10f6ecba580e54f3360a2bc1986123cd1ca51fae
f6d39d77abce980680114d533a1e22b5cce5fc7c
/orgeExample/Enemy.cpp
85027f3fed440dd8d19a20add006ad070a2f12f9
[]
no_license
tscheims1/ogre
42e7f5d5a6c8391c0ae4b25299ed3a47e1fcd746
83dd0e223e0fd0fd5bf8b024a4004980e3dec7c3
refs/heads/master
2020-05-15T15:30:04.627304
2015-06-09T13:34:35
2015-06-09T13:34:35
34,501,723
0
0
null
null
null
null
UTF-8
C++
false
false
1,170
cpp
#include "Enemy.h" Enemy::Enemy(Ogre::SceneManager** sceneManager,Ogre::Vector3 position,const Ogre::Vector3* targetPosition) { mTargetPosition = targetPosition; mEntity = (*sceneManager)->createEntity("RZR-002.mesh"); mNode = (*sceneManager)->getRootSceneNode()->createChildSceneNode(); mSceneManagerPtr = sceneManager; mNode->setPosition(position); mNode->attachObject(mEntity); //mNode->showBoundingBox(true); } void Enemy::die() { mNode->detachAllObjects(); (*mSceneManagerPtr)->destroySceneNode(mNode); } void Enemy::update(Ogre::Real deltaTime) { Ogre::Vector3 myPos =mNode->getPosition(); Ogre::Vector3 direction = (*mTargetPosition)-myPos; mCurrentMoveVector = direction; direction.y = 0; Ogre::Vector3 src = mNode->getOrientation() * Ogre::Vector3::UNIT_Z; src.y = 0; direction.y = 0; src.normalise(); direction.normalise(); mNode->setPosition(mNode->getPosition()+direction*2*GAME_UNIT*deltaTime); Ogre::Quaternion quat = src.getRotationTo(direction); mNode->rotate(quat); OutputDebugStringA(("enemy pos:"+Ogre::StringConverter::toString(mNode->getPosition())+"\n").c_str()); }
[ "james.schuepbach@gmail.com" ]
james.schuepbach@gmail.com