hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
77k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
653k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
1
e2f97cc2ae6712cf8bf511039949bd6b92a0ce39
111
cpp
C++
src/MileStone.cpp
arpit/Helios
433692e7ed8b4be2c7fe29781f18d0f9b68c5ee3
[ "MIT" ]
1
2017-10-21T04:27:19.000Z
2017-10-21T04:27:19.000Z
src/MileStone.cpp
arpit/Helios
433692e7ed8b4be2c7fe29781f18d0f9b68c5ee3
[ "MIT" ]
null
null
null
src/MileStone.cpp
arpit/Helios
433692e7ed8b4be2c7fe29781f18d0f9b68c5ee3
[ "MIT" ]
null
null
null
// // MileStone.cpp // StartupsViz // // Created by Mathur, Arpit on 7/18/13. // // #include "MileStone.h"
11.1
40
0.603604
e2fd2b9e121b52834370eaba288ccfb959c9505a
1,405
hpp
C++
source/oc/ocEngine/Components/ocComponentAllocator.hpp
mackron/openchernobyl
47c854ce37e1c361b184e29a59e4881a6faa387c
[ "BSD-3-Clause" ]
2
2021-05-24T21:18:13.000Z
2021-12-20T07:21:20.000Z
source/oc/ocEngine/Components/ocComponentAllocator.hpp
openchernobyl/openchernobyl
47c854ce37e1c361b184e29a59e4881a6faa387c
[ "BSD-3-Clause" ]
null
null
null
source/oc/ocEngine/Components/ocComponentAllocator.hpp
openchernobyl/openchernobyl
47c854ce37e1c361b184e29a59e4881a6faa387c
[ "BSD-3-Clause" ]
null
null
null
// Copyright (C) 2018 David Reid. See included LICENSE file. typedef ocComponent* (* ocCreateComponentProc)(ocEngineContext* pEngine, ocComponentType type, ocWorldObject* pObject, void* pUserData); typedef void (* ocDeleteComponentProc)(ocComponent* pComponent, void* pUserData); struct ocComponentAllocatorInstance { ocComponentType type; ocCreateComponentProc onCreate; ocDeleteComponentProc onDelete; void* pUserData; }; struct ocComponentAllocator { ocEngineContext* pEngine; ocComponentAllocatorInstance* pAllocators; }; // ocResult ocComponentAllocatorInit(ocEngineContext* pEngine, ocComponentAllocator* pAllocator); // void ocComponentAllocatorUninit(ocComponentAllocator* pAllocator); // Registers an allocator for a specific type of component. // // This will return OC_INVALID_ARGS if an allocator for the specified type has already been registered. ocResult ocComponentAllocatorRegister(ocComponentAllocator* pAllocator, ocComponentType type, ocCreateComponentProc onCreate, ocDeleteComponentProc onDelete, void* pUserData); // Creates an instance of a component of the given type. ocComponent* ocComponentAllocatorCreateComponent(ocComponentAllocator* pAllocator, ocComponentType type, ocWorldObject* pObject); // Deletes an instance of a component. void ocComponentAllocatorDeleteComponent(ocComponentAllocator* pAllocator, ocComponent* pComponent);
37.972973
175
0.814235
e2fd49c1a4ad988db34e8acb9d050ed78d2ee2bb
6,653
cpp
C++
book_samples/opencl_interop/my_vx_tensor_map_impl.cpp
jwinarske/openvx_tutorial
3b57b1c043c5e28e03b6c7121bad87f4ce67ea8c
[ "MIT" ]
220
2016-03-20T00:48:58.000Z
2022-03-31T09:46:21.000Z
book_samples/opencl_interop/my_vx_tensor_map_impl.cpp
jwinarske/openvx_tutorial
3b57b1c043c5e28e03b6c7121bad87f4ce67ea8c
[ "MIT" ]
28
2016-06-16T19:17:41.000Z
2021-09-16T16:19:18.000Z
book_samples/opencl_interop/my_vx_tensor_map_impl.cpp
jwinarske/openvx_tutorial
3b57b1c043c5e28e03b6c7121bad87f4ce67ea8c
[ "MIT" ]
84
2016-03-24T01:13:07.000Z
2022-03-22T04:37:03.000Z
/* * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and/or associated documentation files (the * "Materials"), to deal in the Materials without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Materials, and to * permit persons to whom the Materials are 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 Materials. * * THE MATERIALS ARE 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 * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. */ /*! * \file my_vx_tensor_map_impl.c * \brief This is a simple reference implementation (not optimized) * to demonstrate vxMapTensorPatch functionality, since it is * not yet available in KhronosGroup/OpenVX-sample-impl repo * \author Radhakrishna Giduthuri <radhakrishna.giduthuri@ieee.org> */ #include <VX/vx_khr_opencl_interop.h> #include "my_vx_tensor_map_impl.h" #include "common.h" //// // constants // #define MAX_TENSOR_DIMS 6 //// // local data structure to pass data between vxMapTensorPatch & vxUnmapTensorPatch // struct my_vx_tensor_map_id { vx_size number_of_dims; vx_size view_start[MAX_TENSOR_DIMS]; vx_size view_end[MAX_TENSOR_DIMS]; vx_size stride[MAX_TENSOR_DIMS]; void * ptr; vx_enum usage; vx_enum mem_type; }; //// // simple reference implementation (not optimized) for vxMapTensorPatch // this creates a temporary buffer and uses a copy, instead of returning // OpenVX internal buffer allocated for the tensor (so the copy overheads) // vx_status myVxMapTensorPatch( vx_tensor tensor, vx_size number_of_dims, const vx_size* view_start, const vx_size* view_end, vx_map_id* map_id, vx_size* stride, void** ptr, vx_enum usage, vx_enum mem_type) { //// // calculate output stride values // vx_enum data_type; vx_size dims[MAX_TENSOR_DIMS]; ERROR_CHECK_STATUS( vxQueryTensor(tensor, VX_TENSOR_DATA_TYPE, &data_type, sizeof(vx_enum)) ); ERROR_CHECK_STATUS( vxQueryTensor(tensor, VX_TENSOR_DIMS, &dims, sizeof(vx_size)*number_of_dims) ); switch(data_type) { case VX_TYPE_INT16: stride[0] = sizeof(vx_int16); break; case VX_TYPE_UINT8: stride[0] = sizeof(vx_uint8); break; default: return VX_ERROR_NOT_SUPPORTED; } for(size_t dim = 1; dim < number_of_dims; dim++) { stride[dim] = dims[dim-1] * stride[dim-1]; } vx_size size = dims[number_of_dims-1] * stride[number_of_dims-1]; //// // create map_id and allocate temporary buffers to return // my_vx_tensor_map_id * id = new my_vx_tensor_map_id; ERROR_CHECK_NOT_NULL( id ); id->number_of_dims = number_of_dims; id->usage = usage; id->mem_type = mem_type; if(id->mem_type == VX_MEMORY_TYPE_OPENCL_BUFFER) { vx_context context = vxGetContext((vx_reference)tensor); cl_context opencl_ctx; ERROR_CHECK_STATUS( vxQueryContext(context, VX_CONTEXT_CL_CONTEXT, &opencl_ctx, sizeof(cl_context)) ); cl_int err; id->ptr = clCreateBuffer(opencl_ctx, CL_MEM_READ_WRITE, size, NULL, &err); ERROR_CHECK_STATUS( err ); } else { id->ptr = new vx_uint8[size]; ERROR_CHECK_NOT_NULL( id->ptr ); } for(size_t dim = 0; dim < number_of_dims; dim++) { id->view_start[dim] = view_start ? view_start[dim] : 0; id->view_end[dim] = view_end ? view_end[dim] : dims[dim]; id->stride[dim] = stride[dim]; } *map_id = (vx_map_id)id; *ptr = id->ptr; //// // copy tensor patch into temporarily allocated map buffer if read requested // if(id->usage == VX_READ_ONLY || id->usage == VX_READ_AND_WRITE) { vx_status status = vxCopyTensorPatch(tensor, id->number_of_dims, id->view_start, id->view_end, id->stride, id->ptr, VX_READ_ONLY, id->mem_type); if(status != VX_SUCCESS) { // release resources in case or error if(id->mem_type == VX_MEMORY_TYPE_OPENCL_BUFFER) { ERROR_CHECK_STATUS( clReleaseMemObject((cl_mem)id->ptr) ); } else { delete (vx_uint8 *)id->ptr; } delete id; return status; } } return VX_SUCCESS; } //// // simple reference implementation (not optimized) for vxUnmapTensorPatch // this uses the temporary buffer used for mapping in myVxMapTensorPatch // vx_status myVxUnmapTensorPatch( vx_tensor tensor, const vx_map_id map_id) { //// // access mapped data // my_vx_tensor_map_id * id = (my_vx_tensor_map_id *)map_id; //// // copy tensor patch into temporarily allocated map buffer if read requested // if(id->usage == VX_WRITE_ONLY || id->usage == VX_READ_AND_WRITE) { vx_status status = vxCopyTensorPatch(tensor, id->number_of_dims, id->view_start, id->view_end, id->stride, id->ptr, VX_WRITE_ONLY, id->mem_type); if(status != VX_SUCCESS) { // release resources in case or error if(id->mem_type == VX_MEMORY_TYPE_OPENCL_BUFFER) { ERROR_CHECK_STATUS( clReleaseMemObject((cl_mem)id->ptr) ); } else { delete (vx_uint8 *)id->ptr; } delete id; return status; } } //// // release temporary buffers allocated for mapping // if(id->mem_type == VX_MEMORY_TYPE_OPENCL_BUFFER) { ERROR_CHECK_STATUS( clReleaseMemObject((cl_mem)id->ptr) ); } else { delete (vx_uint8 *)id->ptr; } delete id; return VX_SUCCESS; }
35.57754
110
0.620171
c3b3be02cd5e6b18b4c670130f18b31ae9fcae99
20,235
cxx
C++
test/unit/config/config_test.cxx
ANSAKsoftware/ansak-lib
93eff12a50464f3071b27c8eb16336f93d0d04c6
[ "BSD-2-Clause" ]
null
null
null
test/unit/config/config_test.cxx
ANSAKsoftware/ansak-lib
93eff12a50464f3071b27c8eb16336f93d0d04c6
[ "BSD-2-Clause" ]
null
null
null
test/unit/config/config_test.cxx
ANSAKsoftware/ansak-lib
93eff12a50464f3071b27c8eb16336f93d0d04c6
[ "BSD-2-Clause" ]
null
null
null
/////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2015, Arthur N. Klassen // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////// // // 2015.01.02 - First Version // // May you do good and not evil. // May you find forgiveness for yourself and forgive others. // May you share freely, never taking more than you give. // /////////////////////////////////////////////////////////////////////////// // // configTest.cxx -- unit tests for the configuration collection // /////////////////////////////////////////////////////////////////////////// #include <gtest/gtest.h> #include <config.hxx> #include <config_atom.hxx> #include <config_types.hxx> #include <runtime_exception.hxx> #include <ansak/string.hxx> #include <string> #include <vector> using namespace std; using namespace ansak; using namespace ansak::internal; using namespace testing; //=========================================================================== TEST(ConfigTest, testSimpleInit) { Config simple; EXPECT_TRUE(simple.getValueNames().empty()); simple.initValue("foo", true); EXPECT_FALSE(simple.getValueNames().empty()); } //=========================================================================== TEST(ConfigTest, testUnchangeableInitValues) { Config un; un.initValue("b", true, Config::immutable); un.initValue("i", 23, Config::immutable); un.initValue("f", 3.1415926535f, Config::immutable); un.initValue("d", 4.222333344444555555, Config::immutable); un.initValue("s", string("Now is the time"), Config::immutable); un.initValue("cp", "for all good men to come", Config::immutable); un.initValue("pt", toPoint(3, 4), Config::immutable); un.initValue("r", toRect(100, 60, 50, 30), Config::immutable); bool b, changed; int i; float f; double d; string s, cp; Point pt; Rect r; changed = true; EXPECT_TRUE(un.get("b", b, &changed)); EXPECT_FALSE(changed); EXPECT_FALSE(un.get("bb", b, &changed)); changed = true; EXPECT_TRUE(un.get("i", i, &changed)); EXPECT_FALSE(changed); EXPECT_FALSE(un.get("ii", i, &changed)); changed = true; EXPECT_TRUE(un.get("f", f, &changed)); EXPECT_FALSE(changed); EXPECT_FALSE(un.get("ff", f, &changed)); changed = false; // retrieving a double value -- officially, we only store floats in settings, // so retrieving a double is always a change from the original EXPECT_TRUE(un.get("d", d, &changed)); EXPECT_TRUE(changed); EXPECT_FALSE(un.get("dd", d, &changed)); changed = true; EXPECT_TRUE(un.get("s", s, &changed)); EXPECT_FALSE(changed); EXPECT_FALSE(un.get("ss", s, &changed)); changed = true; EXPECT_TRUE(un.get("cp", cp, &changed)); EXPECT_FALSE(changed); EXPECT_FALSE(un.get("ccp", cp, &changed)); changed = true; EXPECT_TRUE(un.get("pt", pt, &changed)); EXPECT_FALSE(changed); EXPECT_FALSE(un.get("ppt", pt, &changed)); changed = true; EXPECT_TRUE(un.get("r", r, &changed)); EXPECT_FALSE(changed); EXPECT_FALSE(un.get("rr", r, &changed)); changed = true; EXPECT_TRUE(b); EXPECT_EQ(23, i); EXPECT_TRUE(floatEqual(3.1415926535f, f)); EXPECT_TRUE(floatEqual(4.222333344444555555, d)); EXPECT_EQ(string("Now is the time"), s); EXPECT_EQ(string("for all good men to come"), cp); EXPECT_EQ(3, x(pt)); EXPECT_EQ(4, y(pt)); EXPECT_EQ(100, left(r)); EXPECT_EQ(60, top(r)); EXPECT_EQ(50, width(r)); EXPECT_EQ(30, height(r)); EXPECT_THROW(un.put("b", false), RuntimeException); } //=========================================================================== TEST(ConfigTest, testChangeableInitValues) { Config ch; ch.initValue("b", true); ch.initValue("i", 23); ch.initValue("f", 3.1415926535f); ch.initValue("d", 4.222333344444555555); ch.initValue("s", string("Now is the time")); ch.initValue("cp", "for all good men to come"); ch.initValue("pt", toPoint(3, 4)); ch.initValue("r", toRect(100, 60, 50, 30)); bool b, changed; int i; float f, d; string s, cp; Point pt; Rect r; changed = true; EXPECT_TRUE(ch.get("b", b, &changed)); EXPECT_FALSE(changed); changed = true; EXPECT_TRUE(ch.get("i", i, &changed)); EXPECT_FALSE(changed); changed = true; EXPECT_TRUE(ch.get("f", f, &changed)); EXPECT_FALSE(changed); changed = true; EXPECT_TRUE(ch.get("d", d, &changed)); EXPECT_FALSE(changed); changed = true; EXPECT_TRUE(ch.get("s", s, &changed)); EXPECT_FALSE(changed); changed = true; EXPECT_TRUE(ch.get("cp", cp, &changed)); EXPECT_FALSE(changed); changed = true; EXPECT_TRUE(ch.get("pt", pt, &changed)); EXPECT_FALSE(changed); changed = true; EXPECT_TRUE(ch.get("r", r, &changed)); EXPECT_FALSE(changed); changed = true; EXPECT_TRUE(b); EXPECT_EQ(23, i); EXPECT_TRUE(floatEqual(3.1415926535f, f)); EXPECT_TRUE(floatEqual(4.222333344444555555, d)); EXPECT_EQ(string("Now is the time"), s); EXPECT_EQ(string("for all good men to come"), cp); EXPECT_EQ(3, x(pt)); EXPECT_EQ(4, y(pt)); EXPECT_EQ(100, left(r)); EXPECT_EQ(60, top(r)); EXPECT_EQ(50, width(r)); EXPECT_EQ(30, height(r)); ch.put("b", false); ch.put("i", 32); ch.put("f", 2.7182818301f); ch.put("d", 5.6677788889999900000111111); ch.put("s", "Et Earello Endorenna utulien."); ch.put("cp", "Sinome maruvan ar Hildinyar tenn' ambar metta."); ch.put("pt", toPoint(5, 6)); ch.put("r", toRect(500, 300, 20, 20)); changed = false; EXPECT_TRUE(ch.get("b", b, &changed)); EXPECT_TRUE(changed); changed = false; EXPECT_TRUE(ch.get("i", i, &changed)); EXPECT_TRUE(changed); changed = false; EXPECT_TRUE(ch.get("f", f, &changed)); EXPECT_TRUE(changed); changed = false; EXPECT_TRUE(ch.get("d", d, &changed)); EXPECT_TRUE(changed); changed = false; EXPECT_TRUE(ch.get("s", s, &changed)); EXPECT_TRUE(changed); changed = false; EXPECT_TRUE(ch.get("cp", cp, &changed)); EXPECT_TRUE(changed); changed = false; EXPECT_TRUE(ch.get("pt", pt, &changed)); EXPECT_TRUE(changed); changed = false; EXPECT_TRUE(ch.get("r", r, &changed)); EXPECT_TRUE(changed); changed = false; EXPECT_FALSE(b); EXPECT_EQ(32, i); EXPECT_TRUE(floatEqual(2.7182818301f, f)); EXPECT_TRUE(floatEqual(5.6677788889999900000111111, d)); EXPECT_EQ(string("Et Earello Endorenna utulien."), s); EXPECT_EQ(string("Sinome maruvan ar Hildinyar tenn' ambar metta."), cp); EXPECT_EQ(5, x(pt)); EXPECT_EQ(6, y(pt)); EXPECT_EQ(500, left(r)); EXPECT_EQ(300, top(r)); EXPECT_EQ(20, width(r)); EXPECT_EQ(20, height(r)); } //=========================================================================== TEST(ConfigTest, testGetValueNames) { Config ch; ch.initValue("b", true); ch.initValue("i", 23); ch.initValue("f", 3.1415926535f); ch.initValue("d", 4.222333344444555555); ch.initValue("s", string("Now is the time")); ch.initValue("cp", "for all good men to come"); ch.initValue("pt", toPoint(3, 4)); ch.initValue("r", toRect(100, 60, 50, 30)); bool gotB = false; bool gotI = false; bool gotF = false; bool gotD = false; bool gotS = false; bool gotCP = false; bool gotPT = false; bool gotR = false; auto names = ch.getValueNames(); EXPECT_EQ(static_cast<size_t>(8), names.size()); for (auto n : names) { if (n == "b") gotB = true; else if (n == "i") gotI = true; else if (n == "f") gotF = true; else if (n == "d") gotD = true; else if (n == "s") gotS = true; else if (n == "cp") gotCP = true; else if (n == "pt") gotPT = true; else if (n == "r") gotR = true; } EXPECT_TRUE(gotB); EXPECT_TRUE(gotI); EXPECT_TRUE(gotF); EXPECT_TRUE(gotD); EXPECT_TRUE(gotS); EXPECT_TRUE(gotCP); EXPECT_TRUE(gotPT); EXPECT_TRUE(gotR); } //=========================================================================== TEST(ConfigTest, testTemplatedConstructor) { const vector<string> utf8v{ "b=true", "i=23", "f=3.14159265", "d=5.66777888899999", "s=ash nazg durbatuluk", "pt=3,4", "", "r=(100,40),(60,20)", "q=v=w" }; Config c0(utf8v); bool b, changed; int i; float f, d; string s,q; Point pt; Rect r; changed = true; EXPECT_TRUE(c0.get("b", b, &changed)); EXPECT_FALSE(changed); changed = true; EXPECT_TRUE(c0.get("i", i, &changed)); EXPECT_FALSE(changed); changed = true; EXPECT_TRUE(c0.get("f", f, &changed)); EXPECT_FALSE(changed); changed = true; EXPECT_TRUE(c0.get("d", d, &changed)); EXPECT_FALSE(changed); changed = true; EXPECT_TRUE(c0.get("s", s, &changed)); EXPECT_FALSE(changed); changed = true; EXPECT_TRUE(c0.get("pt", pt, &changed)); EXPECT_FALSE(changed); changed = true; EXPECT_TRUE(c0.get("r", r, &changed)); EXPECT_FALSE(changed); changed = true; EXPECT_TRUE(c0.get("q", q, &changed)); EXPECT_FALSE(changed); changed = true; EXPECT_TRUE(b); EXPECT_EQ(23, i); EXPECT_TRUE(floatEqual(3.14159265f, f)); EXPECT_TRUE(floatEqual(5.66777888899999, d)); EXPECT_EQ(string("ash nazg durbatuluk"), s); EXPECT_EQ(3, x(pt)); EXPECT_EQ(4, y(pt)); EXPECT_EQ(100, left(r)); EXPECT_EQ(40, top(r)); EXPECT_EQ(60, width(r)); EXPECT_EQ(20, height(r)); EXPECT_EQ(string("v=w"), q); } //=========================================================================== TEST(ConfigTest, testGetValues) { Config ch; ch.initValue("b", true); ch.initValue("i", 23); ch.initValue("f", 3.1415926535f); ch.initValue("d", 4.222333344444555555); ch.initValue("s", string("Now is the time")); ch.initValue("cp", "for all good men to come"); ch.initValue("pt", toPoint(3, 4)); ch.initValue("r", toRect(100, 60, 50, 30)); bool b; int i; float f; double d; string s; Point pt; Rect r; EXPECT_TRUE(ch.get("b", b)); EXPECT_TRUE(b); EXPECT_TRUE(ch.get("b", i)); EXPECT_EQ(1, i); EXPECT_TRUE(ch.get("b", f)); EXPECT_TRUE(floatEqual(1.0f, f)); EXPECT_TRUE(ch.get("b", d)); EXPECT_TRUE(floatEqual(1.0, d)); EXPECT_TRUE(ch.get("b", s)); EXPECT_EQ(string("true"), s); EXPECT_FALSE(ch.get("b", pt)); EXPECT_FALSE(ch.get("b", r)); EXPECT_TRUE(ch.get("i", b)); EXPECT_TRUE(b); EXPECT_TRUE(ch.get("i", i)); EXPECT_EQ(23, i); EXPECT_TRUE(ch.get("i", f)); EXPECT_TRUE(floatEqual(23.0f, f)); EXPECT_TRUE(ch.get("i", d)); EXPECT_TRUE(floatEqual(23.0, d)); EXPECT_TRUE(ch.get("i", s)); EXPECT_EQ(string("23"), s); EXPECT_FALSE(ch.get("i", pt)); EXPECT_FALSE(ch.get("i", r)); EXPECT_TRUE(ch.get("f", b)); EXPECT_TRUE(b); EXPECT_FALSE(ch.get("f", i)); EXPECT_TRUE(ch.get("f", f)); EXPECT_TRUE(floatEqual(3.1415926535f, f)); EXPECT_TRUE(ch.get("f", d)); EXPECT_TRUE(floatEqual(3.1415926535, d)); EXPECT_TRUE(ch.get("f", s)); EXPECT_EQ(string("3.14159"), s); EXPECT_FALSE(ch.get("f", pt)); EXPECT_FALSE(ch.get("f", r)); EXPECT_TRUE(ch.get("d", b)); EXPECT_TRUE(b); EXPECT_FALSE(ch.get("d", i)); EXPECT_TRUE(ch.get("d", f)); EXPECT_TRUE(floatEqual(4.2223333444f, f)); EXPECT_TRUE(ch.get("d", d)); EXPECT_TRUE(floatEqual(4.2223333444, d)); EXPECT_TRUE(ch.get("d", s)); EXPECT_EQ(string("4.22233"), s); EXPECT_FALSE(ch.get("d", pt)); EXPECT_FALSE(ch.get("d", r)); EXPECT_FALSE(ch.get("s", b)); EXPECT_FALSE(ch.get("s", i)); EXPECT_FALSE(ch.get("s", f)); EXPECT_FALSE(ch.get("s", d)); EXPECT_TRUE(ch.get("s", s)); EXPECT_EQ(string("Now is the time"), s); EXPECT_FALSE(ch.get("s", pt)); EXPECT_FALSE(ch.get("s", r)); EXPECT_FALSE(ch.get("cp", b)); EXPECT_FALSE(ch.get("cp", i)); EXPECT_FALSE(ch.get("cp", f)); EXPECT_FALSE(ch.get("cp", d)); EXPECT_TRUE(ch.get("cp", s)); EXPECT_EQ(string("for all good men to come"), s); EXPECT_FALSE(ch.get("cp", pt)); EXPECT_FALSE(ch.get("cp", r)); EXPECT_FALSE(ch.get("pt", b)); EXPECT_FALSE(ch.get("pt", i)); EXPECT_FALSE(ch.get("pt", f)); EXPECT_FALSE(ch.get("pt", d)); EXPECT_TRUE(ch.get("pt", s)); EXPECT_EQ(string("3,4"), s); EXPECT_TRUE(ch.get("pt", pt)); EXPECT_EQ(3, x(pt)); EXPECT_EQ(4, y(pt)); EXPECT_FALSE(ch.get("pt", r)); EXPECT_FALSE(ch.get("r", b)); EXPECT_FALSE(ch.get("r", i)); EXPECT_FALSE(ch.get("r", f)); EXPECT_FALSE(ch.get("r", d)); EXPECT_TRUE(ch.get("r", s)); EXPECT_EQ(string("(100,60),(50,30)"), s); EXPECT_FALSE(ch.get("r", pt)); EXPECT_TRUE(ch.get("r", r)); EXPECT_EQ(100, left(r)); EXPECT_EQ(60, top(r)); EXPECT_EQ(50, width(r)); EXPECT_EQ(30, height(r)); } // these two "case" ideas are being tested in testChangeableInitValues // TEST(ConfigTest, testPutValues); // TEST(ConfigTest, testGetChangedValues); //=========================================================================== TEST(ConfigTest, testPutForceTypeValues) { Config ch; ch.initValue("b", true); ch.initValue("i", 23); ch.initValue("pi", 3.1415926535f, Config::immutable); ch.initValue("d", 4.222333344444555555); ch.initValue("s", string("Now is the time")); ch.initValue("cp", "for all good men to come"); ch.initValue("pt", toPoint(3, 4)); ch.initValue("r", toRect(100, 60, 50, 30)); ch.put("b", 34, Config::forceTypeChange); ch.put("i", 2.71828301, Config::forceTypeChange); EXPECT_THROW(ch.put("pi", 3.14, Config::forceTypeChange), RuntimeException); ch.put("d", "Sorry, Murphy, no real constants are variable.", Config::forceTypeChange); ch.put("s", toPoint(16,22), Config::forceTypeChange); ch.put("pt", toRect(1,4,9,16), Config::forceTypeChange); ch.put("r", false, Config::forceTypeChange); bool b, changed; int i; float pi, d; string s; Point pt; Rect r; changed = false; EXPECT_TRUE(ch.get("b", i, &changed)); EXPECT_TRUE(changed); changed = false; EXPECT_EQ(34, i); EXPECT_TRUE(ch.get("i", d, &changed)); EXPECT_TRUE(changed); changed = true; EXPECT_TRUE(floatEqual(2.71828301, d)); EXPECT_TRUE(ch.get("pi", pi, &changed)); EXPECT_FALSE(changed); changed = false; EXPECT_TRUE(floatEqual(3.1415926, pi)); EXPECT_TRUE(ch.get("d", s, &changed)); EXPECT_TRUE(changed); changed = false; EXPECT_EQ(string("Sorry, Murphy, no real constants are variable."), s); EXPECT_TRUE(ch.get("s", pt, &changed)); EXPECT_TRUE(changed); changed = false; EXPECT_EQ(16, x(pt)); EXPECT_EQ(22, y(pt)); EXPECT_TRUE(ch.get("pt", r, &changed)); EXPECT_TRUE(changed); changed = false; EXPECT_EQ(1, left(r)); EXPECT_EQ(4, top(r)); EXPECT_EQ(9, width(r)); EXPECT_EQ(16, height(r)); EXPECT_TRUE(ch.get("r", b, &changed)); EXPECT_TRUE(changed); changed = false; EXPECT_FALSE(b); ch.put("b", 1.618f, Config::forceTypeChange); EXPECT_TRUE(ch.get("b", d, &changed)); EXPECT_TRUE(changed); changed = true; EXPECT_TRUE(floatEqual(1.618, d)); } //=========================================================================== TEST(ConfigTest, testDefaultWith) { Config s; s.initValue("a", 3); s.initValue("b", 4); Config q; q.initValue("c", 5); s.defaultWith(q); int a, b, c; bool changed = true; EXPECT_TRUE(s.get("a", a, &changed)); EXPECT_FALSE(changed); changed = true; EXPECT_TRUE(s.get("b", b, &changed)); EXPECT_FALSE(changed); changed = true; EXPECT_TRUE(s.get("c", c, &changed)); EXPECT_FALSE(changed); EXPECT_EQ(3, a); EXPECT_EQ(4, b); EXPECT_EQ(5, c); } //=========================================================================== TEST(ConfigTest, testOverrideWith) { Config s; s.initValue("a", "33"); s.initValue("b", 4); s.initValue("pi", 3.141592653, Config::immutable); Config q; q.initValue("c", 5); q.initValue("a", 3); q.initValue("pi", "3.14"); s.overrideWith(q); int a, b, c; float f; bool changed = true; EXPECT_TRUE(s.get("a", a, &changed)); EXPECT_FALSE(changed); changed = true; EXPECT_TRUE(s.get("b", b, &changed)); EXPECT_FALSE(changed); changed = true; EXPECT_TRUE(s.get("c", c, &changed)); EXPECT_FALSE(changed); changed = true; EXPECT_TRUE(s.get("pi", f, &changed)); EXPECT_FALSE(changed); EXPECT_EQ(3, a); EXPECT_EQ(4, b); EXPECT_EQ(5, c); EXPECT_TRUE(floatEqual(3.1415926, f)); } //=========================================================================== TEST(ConfigTest, testKeepOverridesOf) { Config s; s.initValue("a", 3); s.initValue("b", 4); s.initValue("c", 55); Config q; q.initValue("c", 5); Config savedQ(q); EXPECT_EQ(q, savedQ); q.defaultWith(s); EXPECT_NE(q, savedQ); q.keepOverridesOf(s); EXPECT_EQ(q, savedQ); } //=========================================================================== TEST(ConfigTest, testAtomTransaction) { const vector<string> utf8v{ "b= true ", "i=23", "f=3.14159265", "d=5.66777888899999", "s=ash nazg durbatuluk", "pt=3,4", "", "r=(100,40),(60,20)", "q=v=w" }; Config c0(utf8v); vector<ConfigAtomPair> atomPairs; atomPairs.push_back(ConfigAtomPair(string("b"), c0.getAtom("b"))); atomPairs.push_back(ConfigAtomPair(string("i"), c0.getAtom("i"))); atomPairs.push_back(ConfigAtomPair(string("f"), c0.getAtom("f"))); atomPairs.push_back(ConfigAtomPair(string("d"), c0.getAtom("d"))); atomPairs.push_back(ConfigAtomPair(string("s"), c0.getAtom("s"))); atomPairs.push_back(ConfigAtomPair(string("pt"), c0.getAtom("pt"))); atomPairs.push_back(ConfigAtomPair(string("r"), c0.getAtom("r"))); atomPairs.push_back(ConfigAtomPair(string("q"), c0.getAtom("q"))); EXPECT_EQ(ConfigAtom(), c0.getAtom("notThere")); Config c1(atomPairs); EXPECT_EQ(c0, c1); Config c2 = c1; c2.put("b", false); EXPECT_NE(c2, c1); c1.put("b", false); EXPECT_EQ(c2, c1); Config c3; c3 = c2; EXPECT_EQ(c3, c1); } //=========================================================================== TEST(ConfigTest, manualAdd) { const vector<string> utf8v{ "b=true", "i=23", "f=3.14159265", "d=5.66777888899999", "s=ash nazg durbatuluk", "pt=3,4", "r=(100,40),(60,20)" }; Config c0(utf8v); Config c1; c1.put("r", toRect(100,40,60,20)); c1.put("pt", toPoint(3,4)); c1.put("s", "ash nazg durbatuluk"); c1.put("d", 5.66777888899999); c1.put("f", 3.14159265f); c1.put("i", 23); c1.put("b", true); EXPECT_EQ(c0, c1); }
35.437828
91
0.586064
c3b63176a0f1f33169a106afa3ff6f16cfedada4
1,770
hpp
C++
modules/sdk/include/nt2/sdk/config/compiler/report.hpp
brycelelbach/nt2
73d7e8dd390fa4c8d251c6451acdae65def70e0b
[ "BSL-1.0" ]
1
2022-03-24T03:35:10.000Z
2022-03-24T03:35:10.000Z
modules/sdk/include/nt2/sdk/config/compiler/report.hpp
brycelelbach/nt2
73d7e8dd390fa4c8d251c6451acdae65def70e0b
[ "BSL-1.0" ]
null
null
null
modules/sdk/include/nt2/sdk/config/compiler/report.hpp
brycelelbach/nt2
73d7e8dd390fa4c8d251c6451acdae65def70e0b
[ "BSL-1.0" ]
null
null
null
/******************************************************************************* * Copyright 2003 & onward LASMEA UMR 6602 CNRS/Univ. Clermont II * Copyright 2009 & onward LRI UMR 8623 CNRS/Univ Paris Sud XI * * Distributed under the Boost Software License, Version 1.0. * See accompanying file LICENSE.txt or copy at * http://www.boost.org/LICENSE_1_0.txt ******************************************************************************/ #ifndef NT2_SDK_CONFIG_COMPILER_REPORT_HPP_INCLUDED #define NT2_SDK_CONFIG_COMPILER_REPORT_HPP_INCLUDED //////////////////////////////////////////////////////////////////////////////// // Architecture configuration headers // Defines architecture symbols for architecture related variation point. // Documentation: http://nt2.lri.fr/sdk/config/compiler.html //////////////////////////////////////////////////////////////////////////////// #include <nt2/sdk/config/compiler.hpp> #include <nt2/sdk/config/details/reporter.hpp> namespace nt2 { namespace config { ////////////////////////////////////////////////////////////////////////////// // Status header reporter - Head for the reporter list ////////////////////////////////////////////////////////////////////////////// inline void compiler() { puts(" Compiler : " NT2_COMPILER_STRING); puts(" Rvalue references : " #if defined(BOOST_NO_RVALUE_REFERENCES) "unsupported" #else "supported" #endif ); puts(" Variadic templates : " #if defined(BOOST_NO_VARIADIC_TEMPLATES) "unsupported" #else "supported" #endif "\n" ); } NT2_REGISTER_STATUS(compiler); } } #endif
35.4
80
0.472881
c3b899b877daa6a822136cf309b6e165c4c3e3dc
2,820
cpp
C++
sources/Renderer/Direct3D12/Command/D3D12CommandContext.cpp
wirx6/LLGL
2fc63aa5ddf4f5bd006c496cd9bbf6b40c2133ee
[ "BSD-3-Clause" ]
null
null
null
sources/Renderer/Direct3D12/Command/D3D12CommandContext.cpp
wirx6/LLGL
2fc63aa5ddf4f5bd006c496cd9bbf6b40c2133ee
[ "BSD-3-Clause" ]
null
null
null
sources/Renderer/Direct3D12/Command/D3D12CommandContext.cpp
wirx6/LLGL
2fc63aa5ddf4f5bd006c496cd9bbf6b40c2133ee
[ "BSD-3-Clause" ]
null
null
null
/* * D3D12CommandContext.cpp * * This file is part of the "LLGL" project (Copyright (c) 2015-2018 by Lukas Hermanns) * See "LICENSE.txt" for license information. */ #include "D3D12CommandContext.h" #include "../D3D12Resource.h" #include "../../DXCommon/DXCore.h" namespace LLGL { void D3D12CommandContext::SetCommandList(ID3D12GraphicsCommandList* commandList) { if (commandList_ != commandList) { FlushResourceBarrieres(); commandList_ = commandList; } } void D3D12CommandContext::TransitionResource(D3D12Resource& resource, D3D12_RESOURCE_STATES newState, bool flushBarrieres) { auto oldState = resource.transitionState; if (oldState != newState) { auto& barrier = NextResourceBarrier(); /* Initialize resource barrier for resource transition */ barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; barrier.Transition.pResource = resource.native.Get(); barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; barrier.Transition.StateBefore = oldState; barrier.Transition.StateAfter = newState; /* Store new state in resource */ resource.transitionState = newState; /* Flush resource barrieres if required */ if (flushBarrieres) FlushResourceBarrieres(); } } void D3D12CommandContext::FlushResourceBarrieres() { if (numResourceBarriers_ > 0) { commandList_->ResourceBarrier(numResourceBarriers_, resourceBarriers_); numResourceBarriers_ = 0; } } void D3D12CommandContext::ResolveRenderTarget( D3D12Resource& dstResource, UINT dstSubresource, D3D12Resource& srcResource, UINT srcSubresource, DXGI_FORMAT format) { /* Transition both resources */ TransitionResource(dstResource, D3D12_RESOURCE_STATE_RESOLVE_DEST, false); TransitionResource(srcResource, D3D12_RESOURCE_STATE_RESOLVE_SOURCE); /* Resolve multi-sampled render targets */ commandList_->ResolveSubresource( dstResource.native.Get(), dstSubresource, srcResource.native.Get(), srcSubresource, format ); /* Transition both resources */ TransitionResource(dstResource, dstResource.usageState, false); TransitionResource(srcResource, srcResource.usageState); } /* * ======= Private: ======= */ D3D12_RESOURCE_BARRIER& D3D12CommandContext::NextResourceBarrier() { if (numResourceBarriers_ == g_maxNumResourceBarrieres) FlushResourceBarrieres(); return resourceBarriers_[numResourceBarriers_++]; } } // /namespace LLGL // ================================================================================
27.647059
122
0.669149
c3b9a85b1d2b939baf36f5aa43b50e021a7dc906
115
hpp
C++
gtrc_vehicles/CfgAmmo.hpp
kzfoxx/GTRC-Framework
e60b1f6d7c5d594e22ef6c2d95c0db61d7d3d0f6
[ "MIT" ]
null
null
null
gtrc_vehicles/CfgAmmo.hpp
kzfoxx/GTRC-Framework
e60b1f6d7c5d594e22ef6c2d95c0db61d7d3d0f6
[ "MIT" ]
null
null
null
gtrc_vehicles/CfgAmmo.hpp
kzfoxx/GTRC-Framework
e60b1f6d7c5d594e22ef6c2d95c0db61d7d3d0f6
[ "MIT" ]
null
null
null
class CfgAmmo { class BulletBase; class Gatling_30mm_HE_Plane_CAS_01_F: BulletBase { caliber = 6; }; };
16.428571
52
0.695652
c3bba75286889988256e08f90493166842347443
7,911
cpp
C++
src/Mesh.cpp
akoylasar/PBR
17e6197fb5357220e2f1454898a18f8890844d4d
[ "MIT" ]
null
null
null
src/Mesh.cpp
akoylasar/PBR
17e6197fb5357220e2f1454898a18f8890844d4d
[ "MIT" ]
null
null
null
src/Mesh.cpp
akoylasar/PBR
17e6197fb5357220e2f1454898a18f8890844d4d
[ "MIT" ]
null
null
null
/* * Copyright (c) Fouad Valadbeigi (akoylasar@gmail.com) */ #include "Mesh.hpp" #include <cmath> #include "Debug.hpp" namespace Akoylasar { constexpr double kTwoPi = Neon::kPi * 2.0; std::unique_ptr<Mesh> Mesh::buildSphere(double radius, unsigned int hSegments, unsigned int vSegments) { std::unique_ptr<Mesh> mesh = std::make_unique<Mesh>(); const int numVerts = (hSegments + 1) * (vSegments + 1); mesh->vertices.reserve(numVerts); for (int h = 0; h <= hSegments; ++h) { const double phi = static_cast<double>(h) / hSegments; const double y = radius * std::cos(phi * Neon::kPi); const double r = radius * std::sin(phi * Neon::kPi); for (int v = 0; v <= vSegments; ++v) { Vertex vert; const double theta = static_cast<double>(v) / vSegments; const double x = -std::cos(theta * kTwoPi) * r; const double z = std::sin(theta * kTwoPi) * r; vert.position.x = x; vert.position.y = y; vert.position.z = z; vert.normal = Neon::normalize(vert.position); vert.uv.x = theta; vert.uv.y = phi; mesh->vertices.push_back(vert); } } // Generate indices. TRIANGLE topology. unsigned int indexCount = 6 * vSegments * (hSegments - 1); mesh->indices.reserve(indexCount); for (int h = 0; h < hSegments; ++h) { for (int v = 0; v < vSegments; ++v) { const unsigned int s = vSegments + 1; const unsigned int a = h * s + (v + 1); const unsigned int b = h * s + v; const unsigned int c = (h + 1) * s + v; const unsigned int d = (h + 1) * s + (v + 1); // Avoid degenerate triangles in the caps. if (h != 0) { mesh->indices.push_back(a); mesh->indices.push_back(b); mesh->indices.push_back(d); } if (h != hSegments - 1) { mesh->indices.push_back(b); mesh->indices.push_back(c); mesh->indices.push_back(d); } } } return mesh; } std::unique_ptr<Mesh> Mesh::buildQuad() { std::unique_ptr<Mesh> mesh = std::make_unique<Mesh>(); std::vector<Vertex> vertices = { {Neon::Vec3f{-1, 1, 0.0}, Neon::Vec3f{0, 0, 1.0}, Neon::Vec2f{0, 0}}, // top left {Neon::Vec3f{1, 1, 0.0}, Neon::Vec3f{0, 0, 1.0}, Neon::Vec2f{1, 0}}, // top right {Neon::Vec3f{1, -1, 0.0}, Neon::Vec3f{0, 0, 1.0}, Neon::Vec2f{1, 1}}, // bottom right {Neon::Vec3f{-1, -1, 0.0}, Neon::Vec3f{0, 0, 1.0}, Neon::Vec2f{0, 1}} // bottom left }; std::vector<unsigned int> indices { 3, 1, 0, 3, 2, 1 }; mesh->vertices.assign(vertices.begin(), vertices.end()); mesh->indices.assign(indices.begin(), indices.end()); return mesh; } std::unique_ptr<Mesh> Mesh::buildCube() { std::unique_ptr<Mesh> mesh = std::make_unique<Mesh>(); std::vector<Vertex> vertices = { // Front face {Neon::Vec3f{-1, 1, 1.0}, Neon::Vec3f{0, 0, 1.0}, Neon::Vec2f{0, 0}}, {Neon::Vec3f{1, 1, 1.0}, Neon::Vec3f{0, 0, 1.0}, Neon::Vec2f{1, 0}}, {Neon::Vec3f{1, -1, 1.0}, Neon::Vec3f{0, 0, 1.0}, Neon::Vec2f{1, 1}}, {Neon::Vec3f{-1, -1, 1.0}, Neon::Vec3f{0, 0, 1.0}, Neon::Vec2f{0, 1}}, // Back face {Neon::Vec3f{-1, 1, -1.0}, Neon::Vec3f{0, 0, -1.0}, Neon::Vec2f{1, 0}}, {Neon::Vec3f{1, 1, -1.0}, Neon::Vec3f{0, 0, -1.0}, Neon::Vec2f{0, 0}}, {Neon::Vec3f{1, -1, -1.0}, Neon::Vec3f{0, 0, -1.0}, Neon::Vec2f{0, 1}}, {Neon::Vec3f{-1, -1, -1.0}, Neon::Vec3f{0, 0, -1.0}, Neon::Vec2f{1, 1}}, // Left face {Neon::Vec3f{-1, 1, -1.0}, Neon::Vec3f{-1, 0, 0}, Neon::Vec2f{0, 0}}, {Neon::Vec3f{-1, 1, 1.0}, Neon::Vec3f{-1, 0, 0}, Neon::Vec2f{1, 0}}, {Neon::Vec3f{-1, -1, 1.0}, Neon::Vec3f{-1, 0, 0}, Neon::Vec2f{1, 1}}, {Neon::Vec3f{-1, -1, -1.0}, Neon::Vec3f{-1, 0, 0}, Neon::Vec2f{0, 1}}, // Right face {Neon::Vec3f{1, 1, -1.0}, Neon::Vec3f{1, 0, 0}, Neon::Vec2f{1, 0}}, {Neon::Vec3f{1, 1, 1.0}, Neon::Vec3f{1, 0, 0}, Neon::Vec2f{0, 0}}, {Neon::Vec3f{1, -1, 1.0}, Neon::Vec3f{1, 0, 0}, Neon::Vec2f{0, 1}}, {Neon::Vec3f{1, -1, -1.0}, Neon::Vec3f{1, 0, 0}, Neon::Vec2f{1, 1}}, // Top face {Neon::Vec3f{-1, 1, -1.0}, Neon::Vec3f{0, 1, 0}, Neon::Vec2f{0, 0}}, {Neon::Vec3f{1, 1, -1.0}, Neon::Vec3f{0, 1, 0}, Neon::Vec2f{1, 0}}, {Neon::Vec3f{1, 1, 1.0}, Neon::Vec3f{0, 1, 0}, Neon::Vec2f{1, 1}}, {Neon::Vec3f{-1, 1, 1.0}, Neon::Vec3f{0, 1, 0}, Neon::Vec2f{0, 1}}, // Bottom face {Neon::Vec3f{-1, -1, -1.0}, Neon::Vec3f{0, -1, 0}, Neon::Vec2f{1, 0}}, {Neon::Vec3f{1, -1, -1.0}, Neon::Vec3f{0, -1, 0}, Neon::Vec2f{0, 0}}, {Neon::Vec3f{1, -1, 1.0}, Neon::Vec3f{0, -1, 0}, Neon::Vec2f{0, 1}}, {Neon::Vec3f{-1, -1, 1.0}, Neon::Vec3f{0, -1, 0}, Neon::Vec2f{1, 1}}, }; std::vector<unsigned int> indices { 3, 1, 0, 3, 2, 1, 4, 5, 7, 5, 6, 7, 11, 9, 8, 11, 10, 9, 12, 13, 15, 13, 14, 15, 19, 17, 16, 19, 18, 17, 20, 21, 23, 21, 22, 23 }; mesh->vertices.assign(vertices.begin(), vertices.end()); mesh->indices.assign(indices.begin(), indices.end()); return mesh; } GpuMesh GpuMesh::createGpuMesh(const Mesh& mesh, GLuint positionAttribuIndex, GLuint normalAttribuIndex, GLuint uvAttribuIndex) { GpuMesh gpuMesh; // Vao setup. CHECK_GL_ERROR(glGenVertexArrays(1, &gpuMesh.vao)); CHECK_GL_ERROR(glBindVertexArray(gpuMesh.vao)); // Setup vertex buffer. CHECK_GL_ERROR(glGenBuffers(1, &gpuMesh.vbo)); CHECK_GL_ERROR(glBindBuffer(GL_ARRAY_BUFFER, gpuMesh.vbo)); const auto vertexBufferSize = mesh.vertices.size() * sizeof(Vertex); CHECK_GL_ERROR(glBufferData(GL_ARRAY_BUFFER, vertexBufferSize, &mesh.vertices.at(0), GL_STATIC_DRAW)); // Setup index buffer. CHECK_GL_ERROR(glGenBuffers(1, &gpuMesh.ebo)); CHECK_GL_ERROR(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, gpuMesh.ebo)); const auto indexBufferSize = mesh.indices.size() * sizeof(std::uint32_t); CHECK_GL_ERROR(glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexBufferSize, &mesh.indices.at(0), GL_STATIC_DRAW)); // Specify vertex format. CHECK_GL_ERROR(glBindBuffer(GL_ARRAY_BUFFER, gpuMesh.vbo)); CHECK_GL_ERROR(glVertexAttribPointer(positionAttribuIndex, 3, GL_FLOAT, false, sizeof(Vertex), (void*)(offsetof(Vertex, position)))); CHECK_GL_ERROR(glEnableVertexAttribArray(0)); CHECK_GL_ERROR(glVertexAttribPointer(normalAttribuIndex, 3, GL_FLOAT, false, sizeof(Vertex), (void*)(offsetof(Vertex, normal)))); CHECK_GL_ERROR(glEnableVertexAttribArray(1)); CHECK_GL_ERROR(glVertexAttribPointer(uvAttribuIndex, 2, GL_FLOAT, false, sizeof(Vertex), (void*)(offsetof(Vertex, uv)))); CHECK_GL_ERROR(glEnableVertexAttribArray(2)); CHECK_GL_ERROR(glBindVertexArray(0)); gpuMesh.indexCount = mesh.indices.size(); gpuMesh.drawMode = GL_TRIANGLES; return gpuMesh; } void GpuMesh::releaseGpuMesh(GpuMesh& gpuMesh) { CHECK_GL_ERROR(glDeleteBuffers(1, &gpuMesh.vbo)); CHECK_GL_ERROR(glDeleteBuffers(1, &gpuMesh.ebo)); CHECK_GL_ERROR(glDeleteVertexArrays(1, &gpuMesh.vao)); gpuMesh.vbo = 0; gpuMesh.ebo = 0; gpuMesh.vao = 0; } void GpuMesh::draw() const { CHECK_GL_ERROR(glBindVertexArray(vao)); CHECK_GL_ERROR(glDrawElements(drawMode, indexCount, GL_UNSIGNED_INT, nullptr)); } }
36.456221
137
0.551511
c3bc07d4fdcc84118cefbbc09dcf758bd40f825b
2,567
cpp
C++
NaoTHSoccer/Source/Cognition/Modules/Behavior/XABSLBehaviorControl/Symbols/PathSymbols.cpp
BerlinUnited/NaoTH
02848ac10c16a5349f1735da8122a64d601a5c75
[ "ECL-2.0", "Apache-2.0" ]
15
2015-01-12T10:46:29.000Z
2022-03-28T05:13:14.000Z
NaoTHSoccer/Source/Cognition/Modules/Behavior/XABSLBehaviorControl/Symbols/PathSymbols.cpp
BerlinUnited/NaoTH
02848ac10c16a5349f1735da8122a64d601a5c75
[ "ECL-2.0", "Apache-2.0" ]
2
2019-01-20T21:07:50.000Z
2020-01-22T14:00:28.000Z
NaoTHSoccer/Source/Cognition/Modules/Behavior/XABSLBehaviorControl/Symbols/PathSymbols.cpp
BerlinUnited/NaoTH
02848ac10c16a5349f1735da8122a64d601a5c75
[ "ECL-2.0", "Apache-2.0" ]
5
2018-02-07T18:18:10.000Z
2019-10-15T17:01:41.000Z
/** * @file PathSymbols.cpp * * @author <a href="mailto:akcayyig@hu-berlin.de">Yigit Can Akcay</a> */ #include "PathSymbols.h" void PathSymbols::registerSymbols(xabsl::Engine& engine) { // PathPlanner2018Routine engine.registerEnumElement("path2018.routine", "path2018.routine.none", static_cast<int>(PathModel::PathPlanner2018Routine::NONE)); engine.registerEnumElement("path2018.routine", "path2018.routine.move_around_ball2", static_cast<int>(PathModel::PathPlanner2018Routine::MOVE_AROUND_BALL2)); engine.registerEnumElement("path2018.routine", "path2018.routine.forwardkick", static_cast<int>(PathModel::PathPlanner2018Routine::FORWARDKICK)); engine.registerEnumElement("path2018.routine", "path2018.routine.sidekick_left", static_cast<int>(PathModel::PathPlanner2018Routine::SIDEKICK_LEFT)); engine.registerEnumElement("path2018.routine", "path2018.routine.sidekick_right", static_cast<int>(PathModel::PathPlanner2018Routine::SIDEKICK_RIGHT)); engine.registerEnumElement("path2018.routine", "path2018.routine.sidestep", static_cast<int>(PathModel::PathPlanner2018Routine::SIDESTEP)); engine.registerEnumeratedOutputSymbol("path2018.routine", "path2018.routine", &setPathRoutine2018, &getPathRoutine2018); // go to ball: distance and yOffset engine.registerDecimalOutputSymbol("path.distance", &getPathModel().distance); engine.registerDecimalOutputSymbol("path.yOffset", &getPathModel().yOffset); //TODO delete me // move around ball: direction and radius //engine.registerDecimalOutputSymbol("path.direction", &getPathModel().direction); // TODO this is in degrees should be converted here somehow engine.registerDecimalOutputSymbol("path.direction", &setDirection, &getDirection); engine.registerDecimalOutputSymbol("path.radius", &getPathModel().radius); engine.registerBooleanOutputSymbol("path.stable", &getPathModel().stable); engine.registerBooleanInputSymbol("path.kick_executed", &getPathModel().kick_executed); } PathSymbols* PathSymbols::theInstance = NULL; void PathSymbols::execute() { } void PathSymbols::setPathRoutine2018(int id) { theInstance->getPathModel().path2018_routine = static_cast<PathModel::PathPlanner2018Routine>(id); } int PathSymbols::getPathRoutine2018() { return static_cast<int>(theInstance->getPathModel().path2018_routine); } void PathSymbols::setDirection(double rot) { theInstance->getPathModel().direction = Math::fromDegrees(rot); } double PathSymbols::getDirection() { return Math::toDegrees(theInstance->getPathModel().direction); }
45.035088
160
0.781457
c3c0b8d89474801267ed5e37059dfe1f44fc8778
730
cpp
C++
src/utils/InetUtils.cpp
GbaLog/wad_packer
212af80a8e1e475221be4b5ec241bd77ec126899
[ "MIT" ]
4
2021-09-12T00:13:04.000Z
2022-02-19T11:18:33.000Z
src/utils/InetUtils.cpp
GbaLog/wad_packer
212af80a8e1e475221be4b5ec241bd77ec126899
[ "MIT" ]
null
null
null
src/utils/InetUtils.cpp
GbaLog/wad_packer
212af80a8e1e475221be4b5ec241bd77ec126899
[ "MIT" ]
null
null
null
#include "InetUtils.h" //----------------------------------------------------------------------------- #ifdef _WIN32 #include <winsock2.h> #else #include <arpa/inet.h> #endif //----------------------------------------------------------------------------- namespace ratel { //----------------------------------------------------------------------------- uint16_t htons(uint16_t val) { return ::htons(val); } //----------------------------------------------------------------------------- uint32_t htonl(uint32_t val) { return ::htonl(val); } //----------------------------------------------------------------------------- } //-----------------------------------------------------------------------------
30.416667
80
0.217808
c3c2d1148cb620429b9719256d6d9f3ddf63bfaa
3,800
hpp
C++
src/decoders/novatel/api/separator.hpp
novatel/novatel_edie
d212681f1952704e50e9c8977891dd024c3338ae
[ "MIT" ]
3
2021-05-04T21:14:18.000Z
2021-07-23T17:19:54.000Z
src/decoders/novatel/api/separator.hpp
novatel/novatel_edie
d212681f1952704e50e9c8977891dd024c3338ae
[ "MIT" ]
1
2022-03-07T18:04:18.000Z
2022-03-07T18:04:18.000Z
src/decoders/novatel/api/separator.hpp
novatel/novatel_edie
d212681f1952704e50e9c8977891dd024c3338ae
[ "MIT" ]
2
2021-05-04T21:18:25.000Z
2021-06-24T08:51:43.000Z
//////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2020 NovAtel Inc. // // 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. // //////////////////////////////////////////////////////////////////////////////// /*! \file separator.hpp * \brief To extact the ASCII field separators (, or ;. * Ascii field separator in message ',' * Ascii header end ';' * Ascii bosy and CRC separator '*' * Ascii string terminator '\0' * Quote '"' * Carriage return '0x0d' * */ //----------------------------------------------------------------------- // Recursive Inclusion //----------------------------------------------------------------------- #ifndef SEPARATOR_H #define SEPARATOR_H //----------------------------------------------------------------------- // Includes //----------------------------------------------------------------------- #include "decoders/common/api/common.hpp" //const char VT = 0x9; // Vertical Tab //const char HT = 0xB; // Horizontal Tab /*! \def CR_HEX * \brief A macro that returns the hex value of Carriage Return(CR) * */ #define CR_HEX (0x0D) /*! \def LF_HEX * \brief A macro that returns the hex value of Line Feed(LF) * */ #define LF_HEX (0x0A) /*! \class Separator * \brief Return Ascii filed separators in a message. * */ class Separator { public: /*! A constructor * */ Separator(); /*! A destructor * \brief Set Ascii separator set array */ ~Separator(); /*! \fn SeparatorEnum FindNext(const Format eFormat_, CHAR** psFieldStart_, CHAR** psFieldEnd_, const CHAR* pcBufferEnd_) * \brief It will return ascii field separator * \param [in] eFormat_ Message Format(Currently Supports ASCII) * \param [in] psFieldStart_ Start of the field address * \param [in] psFieldEnd_ of the field address * \param [in] pcBufferEnd_ Buffer end point * \return Ascii field separator Enumaration * \sa SeparatorEnum */ SeparatorEnum FindNext(const Format eFormat_, CHAR** psFieldStart_, CHAR** psFieldEnd_, const CHAR* pcBufferEnd_); private: /*! Private Copy Constructor * * A copy constructor is a member function which initializes an object using another object of the same class. */ Separator(const Separator& Source_); /*! Private assignment operator * * The copy assignment operator is called whenever selected by overload resolution, * e.g. when an object appears on the left side of an assignment expression. */ const Separator& operator= (const Separator& Source_); /*! Array of Ascii field separator */ CHAR acMyASCIISeparatorSet[6]; /*! String of Ascii field separators */ CHAR* sMyASCIISeparators; /*! string of Ascii filed set */ std::string strSeparatorSet; }; #endif //SEPARATOR_H
34.862385
122
0.629737
c3c872072f41504807f429c006e910bd912f2276
7,574
cpp
C++
without_vtk.cpp
Harold2017/texture_mapping
c8aca1e9d30fd53e1f15be937aec2c53993bc371
[ "MIT" ]
1
2022-01-10T07:51:40.000Z
2022-01-10T07:51:40.000Z
without_vtk.cpp
Harold2017/texture_mapping
c8aca1e9d30fd53e1f15be937aec2c53993bc371
[ "MIT" ]
null
null
null
without_vtk.cpp
Harold2017/texture_mapping
c8aca1e9d30fd53e1f15be937aec2c53993bc371
[ "MIT" ]
null
null
null
// // Created by Harold on 2021/11/17. // #pragma warning(disable : 4996) #pragma warning(disable : 4819) #include <boost/filesystem.hpp> #include <boost/thread/thread.hpp> #include <pcl/common/transforms.h> #include <pcl/features/normal_3d.h> #include <pcl/io/obj_io.h> #include <pcl/io/ply_io.h> #include <pcl/kdtree/kdtree_flann.h> #include <pcl/surface/texture_mapping.h> #include <pcl/common/io.h> // for concatenateFields #include "stopwatch.h" //#define DEBUG_PRINT #include "read_cam_file_hololens2.h" #define SAVE_CAM #ifdef SAVE_CAM // save camera pose lines for future plotting void SaveCameraPoints(pcl::texture_mapping::Camera const& cam); #endif // argv[1]: input mesh file // argv[2]: output obj file // argv[3]: input texture.png / camera.txt folder int main(int argc, char **argv) { pcl::PolygonMesh triangles; { TIME_BLOCK("- load mesh"); auto mesh_ext = boost::filesystem::extension(argv[1]); if (mesh_ext == ".ply") pcl::io::loadPLYFile(argv[1], triangles); else if (mesh_ext == ".obj") pcl::io::loadOBJFile(argv[1], triangles); else { std::cerr << "only support .ply or .obj mesh file" << std::endl; exit(0); } } pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>); pcl::fromPCLPointCloud2(triangles.cloud, *cloud); // Create the texturemesh object that will contain our UV-mapped mesh pcl::TextureMesh mesh; mesh.cloud = triangles.cloud; std::vector<pcl::Vertices> polygon_1; // push faces into the texturemesh object { TIME_BLOCK("- push faces into the texturemesh object"); polygon_1.resize(triangles.polygons.size()); for (size_t i = 0; i < triangles.polygons.size(); ++i) { polygon_1[i] = triangles.polygons[i]; } mesh.tex_polygons.push_back(polygon_1); } const boost::filesystem::path base_dir(argv[3]); // Load textures and cameras poses and intrinsics pcl::texture_mapping::CameraVector my_cams; { TIME_BLOCK("- load textures and cameras poses and intrinsics"); std::string extension(".txt"); std::vector<boost::filesystem::path> filenames; try { for (boost::filesystem::directory_iterator it(base_dir); it != boost::filesystem::directory_iterator(); ++it) { if (boost::filesystem::is_regular_file(it->status()) && boost::filesystem::extension(it->path()) == extension) { filenames.push_back(it->path()); } } } catch (const boost::filesystem::filesystem_error &e) { std::cerr << e.what() << std::endl; } std::sort(filenames.begin(), filenames.end()); for (int i = 0; i < filenames.size(); ++i) { std::cout << filenames[i].string() << std::endl; pcl::TextureMapping<pcl::PointXYZ>::Camera cam; read_cam_pose_file(filenames[i].string(), cam); auto texture_path = filenames[i]; texture_path.replace_extension(".png"); if (boost::filesystem::exists(texture_path)) cam.texture_file = texture_path.string(); else { texture_path.replace_extension(".jpg"); if (boost::filesystem::exists(texture_path)) cam.texture_file = texture_path.string(); else std::cerr << "no corresponding texture img for camera " << texture_path << std::endl; } my_cams.push_back(cam); } } // Create materials for each texture (and one extra for occluded faces) { TIME_BLOCK("- create materials for each texture (and one extra for occluded faces)"); mesh.tex_materials.resize(my_cams.size() + 1); for (int i = 0; i <= my_cams.size(); ++i) { pcl::TexMaterial mesh_material; mesh_material.tex_Ka.r = 0.2f; mesh_material.tex_Ka.g = 0.2f; mesh_material.tex_Ka.b = 0.2f; mesh_material.tex_Kd.r = 0.8f; mesh_material.tex_Kd.g = 0.8f; mesh_material.tex_Kd.b = 0.8f; mesh_material.tex_Ks.r = 1.0f; mesh_material.tex_Ks.g = 1.0f; mesh_material.tex_Ks.b = 1.0f; mesh_material.tex_d = 1.0f; mesh_material.tex_Ns = 75.0f; mesh_material.tex_illum = 2; std::stringstream tex_name; tex_name << "material_" << i; tex_name >> mesh_material.tex_name; if (i < my_cams.size()) { mesh_material.tex_file = my_cams[i].texture_file; #ifdef SAVE_CAM SaveCameraPoints(my_cams[i]); #endif } else mesh_material.tex_file = (base_dir / boost::filesystem::path("occluded.jpg")).string(); mesh.tex_materials[i] = mesh_material; } } std::cout << "polygon mesh size: " << mesh.tex_polygons.size() << ", material size: " << mesh.tex_materials.size() << ", texture coordinate size: " << mesh.tex_coordinates.size() << std::endl; // FIXME: texture mapping works under release mode but not under debug mode // Sort faces { TIME_BLOCK("- sort faces"); pcl::TextureMapping<pcl::PointXYZ> tm; // TextureMapping object that will perform the sort tm.textureMeshwithMultipleCameras(mesh, my_cams); } for (std::size_t i = 0; i <= my_cams.size(); ++i) { PCL_INFO("\tSub mesh %zu contains %zu faces and %zu UV coordinates.\n", i, mesh.tex_polygons[i].size(), mesh.tex_coordinates[i].size()); } // compute normals for the mesh pcl::PointCloud<pcl::Normal>::Ptr normals(new pcl::PointCloud<pcl::Normal>); { TIME_BLOCK("- compute normals"); pcl::NormalEstimation<pcl::PointXYZ, pcl::Normal> n; pcl::search::KdTree<pcl::PointXYZ>::Ptr tree(new pcl::search::KdTree<pcl::PointXYZ>); tree->setInputCloud(cloud); n.setInputCloud(cloud); n.setSearchMethod(tree); n.setKSearch(20); n.compute(*normals); } // Concatenate XYZ and normal fields pcl::PointCloud<pcl::PointNormal>::Ptr cloud_with_normals(new pcl::PointCloud<pcl::PointNormal>); { TIME_BLOCK("- concatenate xyz and normal fields"); pcl::concatenateFields(*cloud, *normals, *cloud_with_normals); pcl::toPCLPointCloud2(*cloud_with_normals, mesh.cloud); } { TIME_BLOCK("- save mesh"); pcl::io::saveOBJFile(argv[2], mesh, 5); } std::cout << "Done" << std::endl; return 0; } #ifdef SAVE_CAM void SaveCameraPoints(pcl::texture_mapping::Camera const& cam) { double focal_x = cam.focal_length_w; double focal_y = cam.focal_length_h; double height = cam.height; double width = cam.width; // create a 5-point visual for each camera pcl::PointXYZ p1, p2, p3, p4, p5; p1.x = 0; p1.y = 0; p1.z = 0; double angleX = RAD2DEG(2.0 * atan(width / (2.0 * focal_x))); double angleY = RAD2DEG(2.0 * atan(height / (2.0 * focal_y))); double dist = 0.75; double minX, minY, maxX, maxY; maxX = dist * tan(atan(width / (2.0 * focal_x))); minX = -maxX; maxY = dist * tan(atan(height / (2.0 * focal_y))); minY = -maxY; p2.x = minX; p2.y = minY; p2.z = dist; p3.x = maxX; p3.y = minY; p3.z = dist; p4.x = maxX; p4.y = maxY; p4.z = dist; p5.x = minX; p5.y = maxY; p5.z = dist; p1 = pcl::transformPoint(p1, cam.pose); p2 = pcl::transformPoint(p2, cam.pose); p3 = pcl::transformPoint(p3, cam.pose); p4 = pcl::transformPoint(p4, cam.pose); p5 = pcl::transformPoint(p5, cam.pose); auto camera_file = boost::filesystem::path(cam.texture_file).replace_extension(".cam").string(); std::ofstream ss(camera_file); ss << p1 << p2 << '\n' << p1 << p3 << '\n' << p1 << p4 << '\n' << p1 << p5 << '\n' << p2 << p5 << '\n' << p5 << p4 << '\n' << p4 << p3 << '\n' << p3 << p2; } #endif
30.175299
194
0.632691
c3cb58cdc2d1f73b3dd9d6d5ca786bdfef916b08
2,134
hxx
C++
main/vcl/inc/unx/salstd.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/vcl/inc/unx/salstd.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/vcl/inc/unx/salstd.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #ifndef _SALSTD_HXX #define _SALSTD_HXX // -=-= includes -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= #include <tools/ref.hxx> #include <tools/string.hxx> #include <tools/gen.hxx> #include <vcl/sv.h> // -=-= X-Lib forwards -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= #ifndef _SVUNX_H typedef unsigned long Pixel; typedef unsigned long XID; typedef unsigned long XLIB_Time; typedef unsigned long XtIntervalId; typedef XID Colormap; typedef XID Drawable; typedef XID Pixmap; typedef XID XLIB_Cursor; typedef XID XLIB_Font; typedef XID XLIB_Window; typedef struct _XDisplay Display; typedef struct _XGC *GC; typedef struct _XImage XImage; typedef struct _XRegion *XLIB_Region; typedef union _XEvent XEvent; typedef struct _XConfigureEvent XConfigureEvent; typedef struct _XReparentEvent XReparentEvent; typedef struct _XClientMessageEvent XClientMessageEvent; typedef struct _XErrorEvent XErrorEvent; struct Screen; struct Visual; struct XColormapEvent; struct XFocusChangeEvent; struct XFontStruct; struct XKeyEvent; struct XPropertyEvent; struct XTextItem; struct XWindowChanges; #define None 0L #endif #endif
28.837838
79
0.676664
c3cd2c2feb1535207804a141f2d25998822e240a
993
cpp
C++
src/homework/tic_tac_toe/tic_tac_toe_manager.cpp
acc-cosc-1337-spring-2020/acc-cosc-1337-spring-2020-OMTut
aabedb5cb108513173951a5fc86ad589e7c8ccbc
[ "MIT" ]
null
null
null
src/homework/tic_tac_toe/tic_tac_toe_manager.cpp
acc-cosc-1337-spring-2020/acc-cosc-1337-spring-2020-OMTut
aabedb5cb108513173951a5fc86ad589e7c8ccbc
[ "MIT" ]
null
null
null
src/homework/tic_tac_toe/tic_tac_toe_manager.cpp
acc-cosc-1337-spring-2020/acc-cosc-1337-spring-2020-OMTut
aabedb5cb108513173951a5fc86ad589e7c8ccbc
[ "MIT" ]
null
null
null
#include "tic_tac_toe_manager.h" TicTacToeManager::TicTacToeManager(TicTacToeData & data) { games = data.get_games(); for (auto& game : games) { update_winner_count(game->get_winner()); } } void TicTacToeManager::save_game(unique_ptr<TicTacToe> & game) { update_winner_count(game->get_winner()); games.push_back(std::move(game)); } void TicTacToeManager::update_winner_count(string winner) { if (winner == "X") { x_win++; } if (winner == "O") { o_win++; } if (winner == "C") { ties++; } } void TicTacToeManager::get_winner_total(int & o, int & x, int & c) { x = x_win; o = o_win; c = ties; } TicTacToeManager::~TicTacToeManager() { data.save_games(games); } ostream & operator<<(ostream & out, const TicTacToeManager & manager) { for (auto &game : manager.games) { out << *game << "\n"; } out << "\nX Win Count: " << manager.x_win << "\n"; out << "O Win Count: " << manager.o_win << "\n"; out << "Tie Count: " << manager.ties << "\n"; return out; }
16.55
69
0.632427
c3ce1e2623ad89e78d9d3b8d43b3f82b4a3530b8
1,809
cpp
C++
src/res/animation.cpp
crockeo/cpp-whatisthisgame
90fe2f69f380635050aa746f280288aa0b7c5f54
[ "MIT" ]
null
null
null
src/res/animation.cpp
crockeo/cpp-whatisthisgame
90fe2f69f380635050aa746f280288aa0b7c5f54
[ "MIT" ]
1
2015-02-02T02:08:02.000Z
2015-02-02T04:48:27.000Z
src/res/animation.cpp
crockeo/cpp-whatisthisgame
90fe2f69f380635050aa746f280288aa0b7c5f54
[ "MIT" ]
null
null
null
#include "animation.hpp" ////////// // Code // // Calculating the current frame index. unsigned int Animation::calcCurrentFrameIndex() const { int frame = this->timer->getTime() / frameLength; if (frame >= this->textures.size()) return this->textures.size() - 1; return frame; } // Creating a new animation with its frames, its frame length, and if it // ought to loop. Animation::Animation(std::vector<Texture> textures, float frameLength, bool doesLoop) { this->textures = textures; this->frameLength = frameLength; this->isOriginal = true; this->doesLoop = doesLoop; if (this->doesLoop) this->timer = std::make_shared<Timer>(this->textures.size() * this->frameLength); else this->timer = std::make_shared<Timer>(); } // Creating a new animation with all of the above, assuming that it will // want to loop. Animation::Animation(std::vector<Texture> textures, float frameLength) : Animation(textures, frameLength, true) { } // Overriding the default copy constructor. Animation::Animation(const Animation& anim) { this->textures = anim.textures; this->frameLength = anim.frameLength; this->isOriginal = false; this->doesLoop = anim.doesLoop; this->timer = anim.timer; } // Getting the timer that exists std::shared_ptr<Timer> Animation::getTimer() { return this->timer; } // Getting the current frame of an animation. Texture Animation::getCurrentFrame() const { return this->textures.at(this->calcCurrentFrameIndex()); } // Getting the current texture ID. GLuint Animation::getID() const { return this->getCurrentFrame().getID(); } // Getting the texture coordinates. std::vector<GLfloat> Animation::getTextureCoords() const { return this->getCurrentFrame().getTextureCoords(); }
31.736842
89
0.688778
c3cf5d9e6bcddc9dd28be593bfab79b214d31f3a
885
cpp
C++
src/LWM2MObject.cpp
Tanganelli/LWM2MEmbedded
19a2c5d4edc84a0d91e388b5a789fda8e6142956
[ "MIT" ]
1
2018-04-03T14:58:12.000Z
2018-04-03T14:58:12.000Z
src/LWM2MObject.cpp
Tanganelli/LWM2MEmbedded
19a2c5d4edc84a0d91e388b5a789fda8e6142956
[ "MIT" ]
1
2017-03-21T14:58:16.000Z
2017-03-23T12:28:09.000Z
src/LWM2MObject.cpp
Tanganelli/LWM2MEmbedded
19a2c5d4edc84a0d91e388b5a789fda8e6142956
[ "MIT" ]
null
null
null
// // Created by jacko on 20/01/17. // #include "LWM2MObject.h" char *LWM2MObject::getObjectName() const { return ObjectName; } void LWM2MObject::setObjectName(char *ObjectName) { LWM2MObject::ObjectName = ObjectName; } ObjectIDType LWM2MObject::getObjectID() const { return ObjectID; } void LWM2MObject::setObjectID(ObjectIDType ObjectID) { LWM2MObject::ObjectID = ObjectID; } const std::list<LWM2MResource> &LWM2MObject::getResources() const { return Resources; } void LWM2MObject::setResources(const std::list<LWM2MResource> &Resources) { LWM2MObject::Resources = Resources; } void *const *LWM2MObject::getHandlers() const { return handlers; } const std::list<LWM2MObject> &LWM2MObject::getChildren() const { return children; } void LWM2MObject::setChildren(const std::list<LWM2MObject> &children) { LWM2MObject::children = children; }
21.071429
75
0.728814
c3d326ab78155934dfa9180a0789d3b8f2f6b7c6
1,139
cpp
C++
src/erhe/scene/viewport.cpp
tksuoran/erhe
07d1ea014e1675f6b09bff0d9d4f3568f187e0d8
[ "Apache-2.0" ]
36
2021-05-03T10:47:49.000Z
2022-03-19T12:54:03.000Z
src/erhe/scene/viewport.cpp
tksuoran/erhe
07d1ea014e1675f6b09bff0d9d4f3568f187e0d8
[ "Apache-2.0" ]
29
2020-05-17T08:26:31.000Z
2022-03-27T08:52:47.000Z
src/erhe/scene/viewport.cpp
tksuoran/erhe
07d1ea014e1675f6b09bff0d9d4f3568f187e0d8
[ "Apache-2.0" ]
2
2022-01-24T09:24:37.000Z
2022-01-31T20:45:36.000Z
#include "erhe/scene/viewport.hpp" #include "erhe/scene/log.hpp" #include "erhe/toolkit/math_util.hpp" namespace erhe::scene { auto Viewport::unproject( const glm::mat4 world_from_clip, const glm::vec3 window, const float depth_range_near, const float depth_range_far ) const -> std::optional<glm::vec3> { return erhe::toolkit::unproject( world_from_clip, window, depth_range_near, depth_range_far, static_cast<float>(x), static_cast<float>(y), static_cast<float>(width), static_cast<float>(height) ); } auto Viewport::project_to_screen_space( const glm::mat4 clip_from_world, const glm::vec3 position_in_world, const float depth_range_near, const float depth_range_far ) const -> glm::vec3 { return erhe::toolkit::project_to_screen_space( clip_from_world, position_in_world, depth_range_near, depth_range_far, static_cast<float>(x), static_cast<float>(y), static_cast<float>(width), static_cast<float>(height) ); } } // namespace erhe::scene
24.234043
50
0.653205
c3d4c33e716e4cdf985d257ad205ba50d2611cf5
14,473
cxx
C++
PROPOSAL/private/PROPOSAL/scattering/Coefficients.cxx
hschwane/offline_production
e14a6493782f613b8bbe64217559765d5213dc1e
[ "MIT" ]
1
2020-12-24T22:00:01.000Z
2020-12-24T22:00:01.000Z
PROPOSAL/private/PROPOSAL/scattering/Coefficients.cxx
hschwane/offline_production
e14a6493782f613b8bbe64217559765d5213dc1e
[ "MIT" ]
null
null
null
PROPOSAL/private/PROPOSAL/scattering/Coefficients.cxx
hschwane/offline_production
e14a6493782f613b8bbe64217559765d5213dc1e
[ "MIT" ]
3
2020-07-17T09:20:29.000Z
2021-03-30T16:44:18.000Z
#include "PROPOSAL/scattering/Coefficients.h" //----------------------------------------------------------------------------// //-----------------------------Coefficients-----------------------------------// //---for calculating the power series approximation of the moliere function---// //----------------------------------------------------------------------------// const double PROPOSAL::c1[100] = { 0.01824498698928826, -1.054734960967865, 1.378945800806554, -0.8101747070430586, 0.3020799653590784, -0.08217510264333025, 0.01757489395499939, -0.003095373240445565, 0.0004633127963647091, -6.029130794154548e-05, 6.939349333147516e-06, -7.159829943698265e-07, 6.694120779750297e-08, -5.721860009237694e-09, 4.504494235551189e-10, -3.286570977596057e-11, 2.234424657611573e-12, -1.422140651267253e-13, 8.50844668823957e-15, -4.80239726059346e-16, 2.56544019782712e-17, -1.3008032373069e-18, 6.276721156927733e-20, -2.888980198088948e-21, 1.271082178072295e-22, -5.356321836042788e-24, 2.165708913690074e-25, -8.415665707369898e-27, 3.14768814769592e-28, -1.134804220079789e-29, 3.948607075433194e-31, -1.327667573801528e-32, 4.318678128634822e-34, -1.360474072770111e-35, 4.154710513947732e-37, -1.231145280289021e-38, 3.543063949967192e-40, -9.910855129282805e-42, 2.69678926347067e-43, -7.143475307428035e-45, 1.843336870282648e-46, -4.636847647068766e-48, 1.137731434272442e-49, -2.724695331159021e-51, 6.372463895718094e-53, -1.4562852800865e-54, 3.253589567012378e-56, -7.110068913054863e-58, 1.520504345733737e-59, -3.183490667084008e-61, 6.528486713873094e-63, -1.311890818170701e-64, 2.584252665251881e-66, -4.99221608462446e-68, 9.460964789499932e-70, -1.759614514252362e-71, 3.212849154606866e-73, -5.761014854313268e-75, 1.014807133464239e-76, -1.756624689658179e-78, 2.98893079441324e-80, -5.000577728087579e-82, 8.228369765510281e-84, -1.332031746609897e-85, 2.121957008008998e-87, -3.327287074593805e-89, 5.136681841644386e-91, -7.809396838908658e-93, 1.169486848348948e-94, -1.72549543381347e-96, 2.508809249655915e-98, -3.595413291827729e-100, 5.079801219388072e-102, -7.076983722567338e-104, 9.723837840810993e-106, -1.317945326279369e-107, 1.762410958111165e-109, -2.325652802263962e-111, 3.028909076825982e-113, -3.89408163088736e-115, 4.942802177984765e-117, -6.195278874139763e-119, 7.668956698453442e-121, -9.377048488608183e-123, 1.132701624601603e-124, -1.351910188741138e-126, 1.594502032991125e-128, -1.858693324663112e-130, 2.141681719707223e-132, -2.43963241933955e-134, 2.747720630653711e-136, -3.060234006823078e-138, 3.370734378882746e-140, -3.672273506135163e-142, 3.957653085865992e-144, -4.219715312480803e-146, 4.451647266046611e-148, -4.647280664772496e-150, 4.80136823945151e-152, -4.909819238915968e-154 }; const double PROPOSAL::c2[100] = { 0.3692951315189029, -2.901210618562379, 4.763691522462663, -3.668389620520657, 1.743233030563621, -0.5857757559172652, 0.1507057475725596, -0.03124919421553912, 0.005411101880491738, -0.0008029915660482544, 0.0001041435915389889, -1.198693445962836e-05, 1.239576100587234e-06, -1.163301889847139e-07, 9.990755927592503e-09, -7.907851249726336e-10, 5.803579436334176e-11, -3.969886777147483e-12, 2.542633424164171e-13, -1.530925400639093e-14, 8.696260972023862e-16, -4.675164455450479e-17, 2.385523336370255e-18, -1.158267999875986e-19, 5.363958217246529e-21, -2.374296161332396e-22, 1.006470730715194e-23, -4.093159567679296e-25, 1.5996354171463e-26, -6.016551229383919e-28, 2.180970406636743e-29, -7.629492110705818e-31, 2.578781877602269e-32, -8.431429670892704e-34, 2.669429048218415e-35, -8.192196123057652e-37, 2.439244055889828e-38, -7.052895752459682e-40, 1.98198110121125e-41, -5.417437723374357e-43, 1.441367960601787e-44, -3.735506587014256e-46, 9.436466002585026e-48, -2.325045788414374e-49, 5.590871105668466e-51, -1.312817566476688e-52, 3.011935532920134e-54, -6.755103130065185e-56, 1.481773486168858e-57, -3.180564595352823e-59, 6.683429378680969e-61, -1.375495310358957e-62, 2.773751380431616e-64, -5.482786499876722e-66, 1.062748090934042e-67, -2.020774364918115e-69, 3.770691103605001e-71, -6.907025753601122e-73, 1.242436024375922e-74, -2.195383992072398e-76, 3.811853327900785e-78, -6.505522184103775e-80, 1.091628995757091e-81, -1.801512577182476e-83, 2.924740086946532e-85, -4.672395489277705e-87, 7.346918415137358e-89, -1.137343481536269e-90, 1.733816262095051e-92, -2.603397903194606e-94, 3.851253561734265e-96, -5.61413579760181e-98, 8.066318236042616e-100, -1.142534156297296e-101, 1.595701569049596e-103, -2.197898380015261e-105, 2.986204180183809e-107, -4.002834291275826e-109, 5.294562476317114e-111, -6.911669661645124e-113, 8.906363201403711e-115, -1.133064328971227e-116, 1.423363576915385e-118, -1.765846157643044e-120, 2.163876866238606e-122, -2.619510733347758e-124, 3.133137855471063e-126, -3.703162047314654e-128, 4.325741534530339e-130, -4.994619251572251e-132, 5.701067045150251e-134, -6.433962204999298e-136, 7.180006537985007e-138, -7.924088243222738e-140, 8.649775953179418e-142, -9.339923463142228e-144, 9.977353925282273e-146, -1.054558462375476e-147, 1.102954869090941e-149, -1.141626881676896e-151 }; const double PROPOSAL::c2large[50] = { 0, 0, 5.317361552716548, 39.88021164537411, 279.1614815176188, 2093.711111382141, 17273.11666890266, 157185.3616870142, 1571853.616870142, 17178114.5272237, 203990110.0107814, 2617873078.471694, 36126648482.90939, 533689125315.7068, 8405603723722.382, 140632216146893.7, 2491199257459260, 4.658542611448816e+16, 9.171505766289856e+17, 1.896343692265226e+19, 4.108744666574657e+20, 9.309550415580998e+21, 2.201708673284906e+23, 5.425639230594947e+24, 1.390936602752523e+26, 3.704124648634435e+27, 1.023264434185263e+29, 2.928582810638222e+30, 8.673110631505504e+31, 2.65493553219974e+33, 8.39149266427418e+34, 2.735915970369392e+36, 9.192677660441157e+37, 3.180369932523594e+39, 1.132012922857617e+41, 4.142138195001734e+42, 1.55695665094477e+44, 6.007628448859746e+45, 2.378019594340316e+47, 9.65026059703239e+48, 4.012476774555574e+50, 1.708389149781931e+52, 7.444305720174763e+53, 3.318163098443751e+55, 1.512134326290795e+57, 7.041974391621668e+58, 3.349739182196398e+60, 1.626856662820051e+62, 8.063550415716772e+63, 4.077239907010832e+65 }; const double PROPOSAL::s2large[50] = { 0, 0, -0.3515783203226215, -0.5515783203226214, -0.6944354631797642, -0.8055465742908754, -0.8964556651999662, -0.9733787421230431, -1.04004540878971, -1.098868938201474, -1.151500517148843, -1.19911956476789, -1.242597825637456, -1.282597825637456, -1.319634862674493, -1.354117621295182, -1.386375685811311, -1.416678716114342, -1.44525014468577, -1.472277171712797, -1.497918197353823, -1.522308441256262, -1.54556425520975, -1.567786477431973, -1.589063073176654, -1.609471236441959, -1.629079079579214, -1.647947004107516, -1.666128822289334, -1.683672681938457, -1.70062183448083, -1.717015277103781, -1.732888292976797, -1.748272908361412, -1.76319828149574, -1.777691035118929, -1.791775542161182, -1.805474172298168, -1.818807505631502, -1.831794518618515, -1.844452746466616, -1.856798425478962, -1.868846618250046, -1.880611324132399, -1.892105577005962, -1.903341532062142, -1.914330543051153, -1.925083231223196, -1.93560954701267, -1.945918825363185 }; const double PROPOSAL::C1large[50] = { 0, -0.443113462726379, -0.6646701940895685, -1.661675485223921, -5.815864198283724, -26.17138889227676, -143.9426389075222, -935.6271528988941, -7017.203646741706, -59646.2309973045, -566639.1944743927, -5949711.541981123, -68421682.73278293, -855271034.1597866, -11546158961.15712, -167419304936.7782, -2594999226520.062, -42817487237581.03, -749306026657668, -1.386216149316686e+16, -2.703121491167537e+17, -5.541399056893451e+18, -1.191400797232092e+20, -2.680651793772207e+21, -6.299531715364686e+22, -1.543385270264348e+24, -3.935632439174088e+25, -1.042942596381133e+27, -2.868092140048117e+28, -8.174062599137132e+29, -2.411348466745454e+31, -7.354612823573634e+32, -2.316703039425695e+34, -7.529284878133508e+35, -2.522310434174725e+37, -8.701970997902803e+38, -3.089199704255495e+40, -1.127557892053256e+42, -4.228342095199709e+43, -1.627911706651888e+45, -6.430251241274957e+46, -2.604251752716358e+48, -1.080764477377288e+50, -4.593249028853476e+51, -1.998063327551262e+53, -8.891381807603116e+54, -4.045578722459418e+56, -1.881194105943629e+58, -8.935672003232238e+59, -4.333800921567636e+61 };
66.695853
101
0.453396
c3d5eccc073a19a5adb856e00c78d3e4d7a410af
8,567
cpp
C++
LMS7002M/lms7suite/controlPanelGUI/fft/PlotUpdateThread.cpp
myriadrf/lms-suite
41c3e7e40a76d2520478e9f57bcd01d904907425
[ "Apache-2.0" ]
14
2015-01-16T17:01:05.000Z
2020-10-31T17:52:53.000Z
LMS7002M/lms7suite/controlPanelGUI/fft/PlotUpdateThread.cpp
serojik91/lms-suite
41c3e7e40a76d2520478e9f57bcd01d904907425
[ "Apache-2.0" ]
null
null
null
LMS7002M/lms7suite/controlPanelGUI/fft/PlotUpdateThread.cpp
serojik91/lms-suite
41c3e7e40a76d2520478e9f57bcd01d904907425
[ "Apache-2.0" ]
12
2015-02-01T23:32:31.000Z
2021-01-09T16:34:51.000Z
/** @file PlotUpdateThread.cpp @author Lime Microsystems @brief Class for updating fft data plots */ #include "PlotUpdateThread.h" #include <stdio.h> #include "pnlFFTviewer.h" #include "CommonUtilities.h" #include "SamplesCollector.h" #include <vector> #include <wx/time.h> using namespace std; const int CHANNEL_COUNT = 2; PlotUpdateThread::PlotUpdateThread(pnlFFTviewer* mainFrame) : wxThread(wxTHREAD_JOINABLE) { m_mainframe = mainFrame; m_running = false; m_FFTsize = 0; m_samplingFreq = 1000; } PlotUpdateThread::~PlotUpdateThread() { } /** @brief Plots drawing procedure */ void* PlotUpdateThread::Entry() { float *amplitudes = new float[m_FFTsize]; FFTPacket *results = new FFTPacket(2*m_FFTsize); memset(results->iqsamples, 0, sizeof(float)*results->samplesCount); memset(results->amplitudes, 0, sizeof(float)*results->amplitudesCount); float *ftempI = new float[m_FFTsize]; float *ftempQ = new float[m_FFTsize]; memset(ftempI, 0, sizeof(float)*m_FFTsize); memset(ftempQ, 0, sizeof(float)*m_FFTsize); m_running = true; vector<float> timeVector; timeVector.reserve(m_FFTsize); for(int i=0; i<m_FFTsize; ++i) { timeVector.push_back(i); } vector<float> freqVector; freqVector.resize(m_FFTsize); for(int i=0; i<m_FFTsize; ++i) { float freq = i*(m_samplingFreq/m_FFTsize); int output_index = i+m_FFTsize/2-1; if(output_index >= m_FFTsize) { output_index -= m_FFTsize; freq -= m_samplingFreq; } freqVector[output_index] = freq; } long t1, t2; t2 = t1 = getMilis(); long minUpdateIntervalMs = 30; long t1measure, t2measure; t1measure = t2measure = getMilis(); int ch = 0; //reset plots to default data for(int i = 0; i<CHANNEL_COUNT; ++i) { wxCriticalSectionLocker lock(m_mainframe->m_dataCS); m_mainframe->m_gltimePlot->series[2*i+0]->AssignValues(&timeVector[0], ftempI, m_FFTsize); m_mainframe->m_gltimePlot->series[2*i+1]->AssignValues(&timeVector[0], ftempQ, m_FFTsize); m_mainframe->m_glconstellationPlot->series[i]->AssignValues(results->iqsamples, results->samplesCount); m_mainframe->m_glFFTplot->series[i]->AssignValues(&freqVector[0], results->amplitudes, results->amplitudesCount-1); m_mainframe->m_glFFTplot->Refresh(); m_mainframe->m_gltimePlot->Refresh(); m_mainframe->m_glconstellationPlot->Refresh(); } CalculationResults measurements; while(m_running) { t2 = getMilis(); if(t2 - t1 >= minUpdateIntervalMs) { t2measure = t2; bool updateMeasurements = false; if(t2measure-t1measure > 500) { updateMeasurements = true; t1measure = t2measure; } t1 = t2; memset(amplitudes, 0, sizeof(float)*m_FFTsize); bool newData = m_mainframe->m_fftOutputs->pop_front(results, 100); if( newData == true) { ch = results->channel; int i=0; int j=0; while(i<results->samplesCount) { ftempI[j] = results->iqsamples[i]; ++i; ftempQ[j] = results->iqsamples[i]; ++i; ++j; } } if(newData) { wxCriticalSectionLocker lock(m_mainframe->m_dataCS); if(m_mainframe->chkFreezeIQtime->IsChecked() == false) { if(updateMeasurements) { float sumI = 0; float sumQ = 0; for(int i=0; i<m_FFTsize; ++i) { sumI += ftempI[i]; sumQ += ftempQ[i]; } float meanI = sumI/m_FFTsize; float meanQ = sumQ/m_FFTsize; float tempMag = 0; float averageMag = 0; float peakMag = sqrt((ftempI[0] - meanI)*(ftempI[0] - meanI) + (ftempQ[0] - meanQ)*(ftempQ[0] - meanQ)); for(int i=0; i<m_FFTsize; ++i) { tempMag = sqrt((ftempI[i] - meanI)*(ftempI[i] - meanI) + (ftempQ[i] - meanQ)*(ftempQ[i] - meanQ)); averageMag += tempMag*tempMag; if (tempMag > peakMag) peakMag = tempMag; } averageMag = sqrt(averageMag/m_FFTsize); if (averageMag != 0) { measurements.iqPeakToAvgRatio = 20 * log10(peakMag / averageMag); } else measurements.iqPeakToAvgRatio = 0; } m_mainframe->m_gltimePlot->series[2*ch+0]->AssignValues(&timeVector[0], ftempI, m_FFTsize); m_mainframe->m_gltimePlot->series[2*ch+1]->AssignValues(&timeVector[0], ftempQ, m_FFTsize); } if(m_mainframe->chkFreezeIversusQ->IsChecked() == false) { m_mainframe->m_glconstellationPlot->series[ch]->AssignValues(results->iqsamples, results->samplesCount); } if(m_mainframe->chkFreezeDrawing->IsChecked() == false) { if(updateMeasurements) { float chPwr[2]; double cFreq[2] = {0, 2000000}; m_mainframe->txtCFreq1->GetValue().ToDouble(&cFreq[0]); cFreq[0] *= 1000000; m_mainframe->txtCFreq2->GetValue().ToDouble(&cFreq[1]); cFreq[1] *= 1000000; double bw[2] = {2000000, 3000000}; m_mainframe->txtBW1->GetValue().ToDouble(&bw[0]); bw[0] *= 1000000; m_mainframe->txtBW2->GetValue().ToDouble(&bw[1]); bw[1] *= 1000000; char ctemp[512]; for(int c=0; c<2; ++c) { float f0 = cFreq[c]-bw[c]/2; float fn = cFreq[c]+bw[c]/2; float sum = 0; int bins = 0; for(int i=0; i<results->amplitudesCount; ++i) if(f0 <= freqVector[i] && freqVector[i] <= fn) { sum += pow(10, results->amplitudes_dbFS[i]/10); ++bins; } chPwr[c] = sum; } measurements.pwrCh1 = 10*log10(chPwr[0]); measurements.pwrCh2 = 10*log10(chPwr[1]); measurements.dbc = 10*log10(chPwr[1]/chPwr[0]); } m_mainframe->m_glFFTplot->series[ch]->AssignValues(&freqVector[0], results->amplitudes_dbFS, results->amplitudesCount); } m_mainframe->m_redrawsDone++; wxThreadEvent tevt(wxEVT_THREAD, wxEVT_COMMAND_THREAD_UPDATE); tevt.SetPayload<CalculationResults>(measurements); m_mainframe->GetEventHandler()->AddPendingEvent(tevt); //post event for gui thread to update } else { wxThreadEvent tevt(wxEVT_THREAD, wxEVT_COMMAND_THREAD_UPDATE); tevt.SetPayload<CalculationResults>(measurements); m_mainframe->GetEventHandler()->AddPendingEvent(tevt); //post event for gui thread to update } } else milSleep(minUpdateIntervalMs-(t2-t1)); } delete []ftempI; delete []ftempQ; delete results; delete []amplitudes; printf("plot thread stopped\n"); return 0; } /** @brief Stops plot updating */ void PlotUpdateThread::Stop() { m_running = false; Wait(); } /** */ bool PlotUpdateThread::SetFFTsize(int size) { if(m_running) return false; m_FFTsize = size; return true; } /** @brief Sets sampling frequency for display @param freq sampling frequency in Hz */ bool PlotUpdateThread::SetSamplingFrequency(double freq) { m_samplingFreq = freq; return true; }
34.967347
159
0.514883
c3da584fa3177cd7bd55731b103e77f0e22114c9
2,299
cpp
C++
contents/graham_scan/code/c++/graham_scan.cpp
Iinguistics/algorithm-archivists.github.io
3759b22a9c21b8b7a9bf075ca880e02ec524abc5
[ "MIT" ]
1,975
2018-04-28T13:46:56.000Z
2022-03-29T13:14:47.000Z
contents/graham_scan/code/c++/graham_scan.cpp
Iinguistics/algorithm-archivists.github.io
3759b22a9c21b8b7a9bf075ca880e02ec524abc5
[ "MIT" ]
632
2018-04-28T10:27:13.000Z
2022-03-28T20:38:53.000Z
contents/graham_scan/code/c++/graham_scan.cpp
Iinguistics/algorithm-archivists.github.io
3759b22a9c21b8b7a9bf075ca880e02ec524abc5
[ "MIT" ]
433
2018-04-27T22:50:22.000Z
2022-03-22T06:16:03.000Z
#include <algorithm> #include <cmath> #include <iostream> #include <vector> struct point { double x; double y; }; std::ostream& operator<<(std::ostream& os, const std::vector<point>& points) { for (auto p : points) { os << "(" << p.x << ", " << p.y << ")\n"; } return os; } double ccw(const point& a, const point& b, const point& c) { return (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x); } double polar_angle(const point& origin, const point& p) { return std::atan2(p.y - origin.y, p.x - origin.x); } std::vector<point> graham_scan(std::vector<point>& points) { // selecting lowest point as pivot size_t low_index = 0; for (size_t i = 1; i < points.size(); i++) { if (points[i].y < points[low_index].y) { low_index = i; } } std::swap(points[0], points[low_index]); point pivot = points[0]; // sorting points by polar angle std::sort( points.begin() + 1, points.end(), [&pivot](const point& pa, const point& pb) { return polar_angle(pivot, pa) < polar_angle(pivot, pb); }); // creating convex hull size_t m = 1; for (size_t i = 2; i < points.size(); i++) { while (ccw(points[m - 1], points[m], points[i]) <= 0) { if (m > 1) { m--; continue; } else if (i == points.size()) { break; } else { i++; } } m++; std::swap(points[i], points[m]); } return std::vector<point>(points.begin(), points.begin() + m + 1); } int main() { std::vector<point> points = {{-5, 2}, {5, 7}, {-6, -12}, {-14, -14}, {9, 9}, {-1, -1}, {-10, 11}, {-6, 15}, {-6, -8}, {15, -9}, {7, -7}, {-2, -9}, {6, -5}, {0, 14}, {2, 8}}; std::cout << "original points are as follows:\n" << points; const std::vector<point> hull = graham_scan(points); std::cout << "points in hull are as follows:\n" << hull; return 0; }
27.047059
78
0.433232
c3daccd7cb4ce0df04859e39032c133934ccc4d2
77,794
cpp
C++
src/vm/vm8051.cpp
koalajack/koalachain
84b5d5351072947f79f982ca24666047e955df3d
[ "MIT" ]
null
null
null
src/vm/vm8051.cpp
koalajack/koalachain
84b5d5351072947f79f982ca24666047e955df3d
[ "MIT" ]
null
null
null
src/vm/vm8051.cpp
koalajack/koalachain
84b5d5351072947f79f982ca24666047e955df3d
[ "MIT" ]
null
null
null
// ComDirver.cpp: implementation of the CComDirver class. // ////////////////////////////////////////////////////////////////////// #include "vm8051.h" #include <stdio.h> #include <string.h> #include <assert.h> #include "hash.h" #include "key.h" #include "main.h" #include <openssl/des.h> #include <vector> #include "vmrunevn.h" #include "tx.h" //#include "Typedef.h" ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// void CVm8051::InitalReg() { memset(m_ChipRam, 0, sizeof(m_ChipRam)); memset(m_ChipSfr, 0, sizeof(m_ChipSfr)); memset(m_ExRam, 0, sizeof(m_ExRam)); memset(m_ExeFile, 0, sizeof(m_ExeFile)); Sys.a.SetAddr(a_addr); Sys.b.SetAddr(b_addr); Sys.dptr.SetAddr(dptrl); Sys.psw.SetAddr(psw_addr); Sys.sp.SetAddr(sp_addr); Rges.R0.SetAddr(0x00); Rges.R1.SetAddr(0x01); Rges.R2.SetAddr(0x02); Rges.R3.SetAddr(0x03); Rges.R4.SetAddr(0x04); Rges.R5.SetAddr(0x05); Rges.R6.SetAddr(0x06); Rges.R7.SetAddr(0x07); SetRamData(0x80, 0xFF); SetRamData(0x90, 0xFF); SetRamData(0xa0, 0xFF); SetRamData(0xb0, 0xFF); Sys.sp = 0x07; } CVm8051::CVm8051(const vector<unsigned char> & vRom, const vector<unsigned char> &InputData) : Sys(this), Rges(this) { InitalReg(); //INT16U addr = 0xFC00; memcpy(m_ExeFile, &vRom[0], vRom.size()); unsigned char *ipara = (unsigned char *) GetExRamAddr(VM_SHARE_ADDR); int count = InputData.size(); memcpy(ipara, &count, 2); memcpy(&ipara[2], &InputData[0],count); } CVm8051::~CVm8051() { } typedef tuple<int,int64_t,std::shared_ptr < std::vector< vector<unsigned char> > > > RET_DEFINE; typedef tuple<int,int64_t,std::shared_ptr < std::vector< vector<unsigned char> > > > (*pFun)(unsigned char *,void *); struct __MapExterFun { INT16U method; pFun fun; }; static bool GetKeyId(const CAccountViewCache &view, vector<unsigned char> &ret, CKeyID &KeyId) { if (ret.size() == 6) { CRegID reg(ret); KeyId = reg.getKeyID(view); } else if (ret.size() == 34) { string addr(ret.begin(), ret.end()); KeyId = CKeyID(addr); }else{ return false; } if (KeyId.IsEmpty()) return false; return true; } static inline RET_DEFINE RetFalse(const string reason ) { auto tem = std::make_shared<std::vector< vector<unsigned char> > >(); return std::make_tuple (false,0, tem); } static unsigned short GetParaLen(unsigned char * &pbuf) { unsigned short ret = 0; memcpy(&ret, pbuf, 2); pbuf += 2; return ret; } static bool GetData(unsigned char * ipara, vector<std::shared_ptr < std::vector<unsigned char> > > &ret) { int totallen = GetParaLen(ipara); //assert(totallen >= 0); if(totallen <= 0) { return false; } if(totallen>= CVm8051::MAX_SHARE_RAM) { LogPrint("vm","%s\r\n","data over flaw"); return false; } while (totallen > 0) { unsigned short length = GetParaLen(ipara); if ((length <= 0) || (length + 2 > totallen)) { LogPrint("vm","%s\r\n","data over flaw"); return false; } totallen -= (length + 2); ret.insert(ret.end(),std::make_shared<vector<unsigned char>>(ipara, ipara + length)); ipara += length; } return true; } static RET_DEFINE ExInt64CompFunc(unsigned char *ipara,void * pVmScriptRun) { vector<std::shared_ptr < vector<unsigned char> > > retdata; if(!GetData(ipara,retdata) || retdata.size() != 2|| retdata.at(0).get()->size() != sizeof(int64_t)||retdata.at(1).get()->size() != sizeof(int64_t)) { return RetFalse(string(__FUNCTION__)+"para err !"); } int64_t m1, m2; unsigned char rslt; memcpy(&m1, &retdata.at(0).get()->at(0), sizeof(m1)); memcpy(&m2, &retdata.at(1).get()->at(0), sizeof(m2)); if (m1 > m2) { rslt = 2; } else if (m1 == m2) { rslt = 0; } else { rslt = 1; } auto tem = std::make_shared<std::vector< vector<unsigned char> > >(); CDataStream tep(SER_DISK, CLIENT_VERSION); tep << rslt; vector<unsigned char> tep1(tep.begin(),tep.end()); (*tem.get()).push_back(tep1); return std::make_tuple (true,0, tem); } static RET_DEFINE ExInt64MullFunc(unsigned char *ipara,void * pVmScriptRun) { vector<std::shared_ptr < vector<unsigned char> > > retdata; if(!GetData(ipara,retdata) ||retdata.size() != 2|| retdata.at(0).get()->size() != sizeof(int64_t)||retdata.at(1).get()->size() != sizeof(int64_t)) { return RetFalse(string(__FUNCTION__)+"para err !"); } int64_t m1, m2, m3; memcpy(&m1, &retdata.at(0).get()->at(0), sizeof(m1)); memcpy(&m2, &retdata.at(1).get()->at(0), sizeof(m2)); m3 = m1 * m2; auto tem = std::make_shared<std::vector< vector<unsigned char> > >(); CDataStream tep(SER_DISK, CLIENT_VERSION); tep << m3; vector<unsigned char> tep1(tep.begin(),tep.end()); (*tem.get()).push_back(tep1); return std::make_tuple (true,0, tem); } static RET_DEFINE ExInt64AddFunc(unsigned char *ipara,void * pVmScriptRun) { vector<std::shared_ptr < vector<unsigned char> > > retdata; if(!GetData(ipara,retdata) ||retdata.size() != 2|| retdata.at(0).get()->size() != sizeof(int64_t)||retdata.at(1).get()->size() != sizeof(int64_t)) { return RetFalse(string(__FUNCTION__)+"para err !"); } int64_t m1, m2, m3; memcpy(&m1, &retdata.at(0).get()->at(0), sizeof(m1)); memcpy(&m2, &retdata.at(1).get()->at(0), sizeof(m2)); m3 = m1 + m2; auto tem = std::make_shared<std::vector< vector<unsigned char> > >(); CDataStream tep(SER_DISK, CLIENT_VERSION); tep << m3; vector<unsigned char> tep1(tep.begin(),tep.end()); (*tem.get()).push_back(tep1); return std::make_tuple (true,0, tem); } static RET_DEFINE ExInt64SubFunc(unsigned char *ipara,void * pVmScriptRun) { vector<std::shared_ptr < vector<unsigned char> > > retdata; if(!GetData(ipara,retdata) ||retdata.size() != 2|| retdata.at(0).get()->size() != sizeof(int64_t)||retdata.at(1).get()->size() != sizeof(int64_t)) { return RetFalse(string(__FUNCTION__)+"para err !"); } int64_t m1, m2, m3; memcpy(&m1, &retdata.at(0).get()->at(0), sizeof(m1)); memcpy(&m2, &retdata.at(1).get()->at(0), sizeof(m2)); m3 = m1 - m2; auto tem = std::make_shared<std::vector< vector<unsigned char> > >(); CDataStream tep(SER_DISK, CLIENT_VERSION); tep << m3; vector<unsigned char> tep1(tep.begin(),tep.end()); (*tem.get()).push_back(tep1); return std::make_tuple (true,0, tem); } static RET_DEFINE ExInt64DivFunc(unsigned char *ipara,void * pVmScriptRun) { vector<std::shared_ptr < vector<unsigned char> > > retdata; if(!GetData(ipara,retdata) ||retdata.size() != 2|| retdata.at(0).get()->size() != sizeof(int64_t)||retdata.at(1).get()->size() != sizeof(int64_t)) { return RetFalse(string(__FUNCTION__)+"para err !"); } int64_t m1, m2, m3; memcpy(&m1, &retdata.at(0).get()->at(0), sizeof(m1)); memcpy(&m2, &retdata.at(1).get()->at(0), sizeof(m2)); auto tem = std::make_shared<std::vector< vector<unsigned char> > >(); if( m2 == 0) { return std::make_tuple (false,0, tem); } m3 = m1 / m2; CDataStream tep(SER_DISK, CLIENT_VERSION); tep << m3; vector<unsigned char> tep1(tep.begin(),tep.end()); (*tem.get()).push_back(tep1); return std::make_tuple (true,0, tem); } static RET_DEFINE ExSha256Func(unsigned char *ipara,void * pVmScriptRun) { vector<std::shared_ptr < vector<unsigned char> > > retdata; if(!GetData(ipara,retdata) ||retdata.size() != 1) { return RetFalse(string(__FUNCTION__)+"para err !"); } uint256 rslt = Hash(&retdata.at(0).get()->at(0), &retdata.at(0).get()->at(0) + retdata.at(0).get()->size()); auto tem = std::make_shared<std::vector< vector<unsigned char> > >(); CDataStream tep(SER_DISK, CLIENT_VERSION); tep << rslt; vector<unsigned char> tep1(tep.begin(),tep.end()); (*tem.get()).push_back(tep1); return std::make_tuple (true,0, tem); } static RET_DEFINE ExDesFunc(unsigned char *ipara,void * pVmScriptRun) { vector<std::shared_ptr < vector<unsigned char> > > retdata; if(!GetData(ipara,retdata) ||retdata.size() != 3) { return RetFalse(string(__FUNCTION__)+"para err !"); } DES_key_schedule deskey1, deskey2, deskey3; vector<unsigned char> desdata; vector<unsigned char> desout; unsigned char datalen_rest = retdata.at(0).get()->size() % sizeof(DES_cblock); desdata.assign(retdata.at(0).get()->begin(), retdata.at(0).get()->end()); if (datalen_rest) { desdata.insert(desdata.end(), sizeof(DES_cblock) - datalen_rest, 0); } const_DES_cblock in; DES_cblock out, key; desout.resize(desdata.size()); unsigned char flag = retdata.at(2).get()->at(0); if (flag == 1) { if (retdata.at(1).get()->size() == 8) { // printf("the des encrypt\r\n"); memcpy(key, &retdata.at(1).get()->at(0), sizeof(DES_cblock)); DES_set_key_unchecked(&key, &deskey1); for (unsigned int ii = 0; ii < desdata.size() / sizeof(DES_cblock); ii++) { memcpy(&in, &desdata[ii * sizeof(DES_cblock)], sizeof(in)); // printf("in :%s\r\n", HexStr(in, in + 8, true).c_str()); DES_ecb_encrypt(&in, &out, &deskey1, DES_ENCRYPT); // printf("out :%s\r\n", HexStr(out, out + 8, true).c_str()); memcpy(&desout[ii * sizeof(DES_cblock)], &out, sizeof(out)); } } else if(retdata.at(1).get()->size() == 16) { // printf("the 3 des encrypt\r\n"); memcpy(key, &retdata.at(1).get()->at(0), sizeof(DES_cblock)); DES_set_key_unchecked(&key, &deskey1); DES_set_key_unchecked(&key, &deskey3); memcpy(key, &retdata.at(1).get()->at(0) + sizeof(DES_cblock), sizeof(DES_cblock)); DES_set_key_unchecked(&key, &deskey2); for (unsigned int ii = 0; ii < desdata.size() / sizeof(DES_cblock); ii++) { memcpy(&in, &desdata[ii * sizeof(DES_cblock)], sizeof(in)); DES_ecb3_encrypt(&in, &out, &deskey1, &deskey2, &deskey3, DES_ENCRYPT); memcpy(&desout[ii * sizeof(DES_cblock)], &out, sizeof(out)); } } else { //error auto tem = std::make_shared<std::vector< vector<unsigned char> > >(); return std::make_tuple (false,0, tem); } } else { if (retdata.at(1).get()->size() == 8) { // printf("the des decrypt\r\n"); memcpy(key, &retdata.at(1).get()->at(0), sizeof(DES_cblock)); DES_set_key_unchecked(&key, &deskey1); for (unsigned int ii = 0; ii < desdata.size() / sizeof(DES_cblock); ii++) { memcpy(&in, &desdata[ii * sizeof(DES_cblock)], sizeof(in)); // printf("in :%s\r\n", HexStr(in, in + 8, true).c_str()); DES_ecb_encrypt(&in, &out, &deskey1, DES_DECRYPT); // printf("out :%s\r\n", HexStr(out, out + 8, true).c_str()); memcpy(&desout[ii * sizeof(DES_cblock)], &out, sizeof(out)); } } else if(retdata.at(1).get()->size() == 16) { // printf("the 3 des decrypt\r\n"); memcpy(key, &retdata.at(1).get()->at(0), sizeof(DES_cblock)); DES_set_key_unchecked(&key, &deskey1); DES_set_key_unchecked(&key, &deskey3); memcpy(key, &retdata.at(1).get()->at(0) + sizeof(DES_cblock), sizeof(DES_cblock)); DES_set_key_unchecked(&key, &deskey2); for (unsigned int ii = 0; ii < desdata.size() / sizeof(DES_cblock); ii++) { memcpy(&in, &desdata[ii * sizeof(DES_cblock)], sizeof(in)); DES_ecb3_encrypt(&in, &out, &deskey1, &deskey2, &deskey3, DES_DECRYPT); memcpy(&desout[ii * sizeof(DES_cblock)], &out, sizeof(out)); } } else { //error return RetFalse(string(__FUNCTION__)+"para err !"); } } auto tem = std::make_shared<std::vector< vector<unsigned char> > >(); (*tem.get()).push_back(desout); return std::make_tuple (true,0, tem); } static RET_DEFINE ExVerifySignatureFunc(unsigned char *ipara,void * pVmScriptRun) { vector<std::shared_ptr < vector<unsigned char> > > retdata; if(!GetData(ipara,retdata) ||retdata.size() != 3|| retdata.at(1).get()->size() != 33|| retdata.at(2).get()->size() !=32) { return RetFalse(string(__FUNCTION__)+"para err !"); } CPubKey pk(retdata.at(1).get()->begin(), retdata.at(1).get()->end()); uint256 hash(*retdata.at(2).get()); auto tem = std::make_shared<std::vector<vector<unsigned char> > >(); bool rlt = CheckSignScript(hash, *retdata.at(0), pk); if (!rlt) { LogPrint("INFO", "ExVerifySignatureFunc call CheckSignScript verify signature failed!\n"); return std::make_tuple(false, 0, tem); } CDataStream tep(SER_DISK, CLIENT_VERSION); tep << rlt; vector<unsigned char> tep1(tep.begin(), tep.end()); (*tem.get()).push_back(tep1); return std::make_tuple(true, 0, tem); } static RET_DEFINE ExSignatureFunc(unsigned char *ipara,void * pVmScriptRun) { auto tem = std::make_shared<std::vector< vector<unsigned char> > >(); return std::make_tuple (true,0, tem); } static RET_DEFINE ExLogPrintFunc(unsigned char *ipara,void * pVmScriptRun) { vector<std::shared_ptr < vector<unsigned char> > > retdata; if(!GetData(ipara,retdata) ||retdata.size() != 2) { return RetFalse(string(__FUNCTION__)+"para err !"); } CDataStream tep1(*retdata.at(0), SER_DISK, CLIENT_VERSION); bool flag ; tep1 >> flag; string pdata((*retdata[1]).begin(), (*retdata[1]).end()); if(flag) { LogPrint("vm","%s\r\n", HexStr(pdata).c_str()); // LogPrint("INFO","%s\r\n", HexStr(pdata).c_str()); }else { LogPrint("vm","%s\r\n",pdata.c_str()); // LogPrint("INFO","%s\r\n",pdata.c_str()); } auto tem = std::make_shared<std::vector< vector<unsigned char> > >(); return std::make_tuple (true, 0,tem); } static RET_DEFINE ExGetTxContractsFunc(unsigned char * ipara,void * pVmScriptRun) { CVmRunEvn *pVmScript = (CVmRunEvn *)pVmScriptRun; vector<std::shared_ptr < vector<unsigned char> > > retdata; if(!GetData(ipara,retdata) ||retdata.size() != 1 || retdata.at(0).get()->size() != 32) { return RetFalse(string(__FUNCTION__)+"para err !"); } uint256 hash1(*retdata.at(0)); // LogPrint("vm","ExGetTxContractsFunc1:%s\n",hash1.GetHex().c_str()); bool flag = false; std::shared_ptr<CBaseTransaction> pBaseTx; auto tem = std::make_shared<std::vector< vector<unsigned char> > >(); if (GetTransaction(pBaseTx, hash1, *pVmScript->GetScriptDB(), false)) { CTransaction *tx = static_cast<CTransaction*>(pBaseTx.get()); (*tem.get()).push_back(tx->vContract); flag = true; } return std::make_tuple (flag, 0,tem); } static RET_DEFINE ExGetTxAccountsFunc(unsigned char * ipara, void * pVmScriptRun) { CVmRunEvn *pVmScript = (CVmRunEvn *)pVmScriptRun; vector<std::shared_ptr<vector<unsigned char> > > retdata; if(!GetData(ipara,retdata) ||retdata.size() != 1|| retdata.at(0).get()->size() != 32) { return RetFalse(string(__FUNCTION__)+"para err !"); } CDataStream tep1(*retdata.at(0), SER_DISK, CLIENT_VERSION); uint256 hash1; tep1 >>hash1; // LogPrint("vm","ExGetTxAccountsFunc:%s",hash1.GetHex().c_str()); bool flag = false; std::shared_ptr<CBaseTransaction> pBaseTx; auto tem = std::make_shared<std::vector<vector<unsigned char> > >(); if (GetTransaction(pBaseTx, hash1, *pVmScript->GetScriptDB(), false)) { CTransaction *tx = static_cast<CTransaction*>(pBaseTx.get()); vector<unsigned char> item = boost::get<CRegID>(tx->srcRegId).GetVec6(); (*tem.get()).push_back(item); flag = true; } return std::make_tuple(flag,0, tem); } static RET_DEFINE ExGetAccountPublickeyFunc(unsigned char * ipara,void * pVmScriptRun) { CVmRunEvn *pVmScript = (CVmRunEvn *)pVmScriptRun; vector<std::shared_ptr < vector<unsigned char> > > retdata; if(!GetData(ipara,retdata) ||retdata.size() != 1 || !(retdata.at(0).get()->size() == 6 || retdata.at(0).get()->size() == 34)) { return RetFalse(string(__FUNCTION__)+"para err !"); } CKeyID addrKeyId; if (!GetKeyId(*(pVmScript->GetCatchView()),*retdata.at(0).get(), addrKeyId)) { return RetFalse(string(__FUNCTION__)+"para err !"); } CUserID userid(addrKeyId); CAccount aAccount; if (!pVmScript->GetCatchView()->GetAccount(userid, aAccount)) { return RetFalse(string(__FUNCTION__)+"GetAccount err !"); } auto tem = std::make_shared<std::vector< vector<unsigned char> > >(); CDataStream tep(SER_DISK, CLIENT_VERSION); vector<char> te; tep << aAccount.PublicKey; assert(aAccount.PublicKey.IsFullyValid()); tep >>te; vector<unsigned char> tep1(te.begin(),te.end()); (*tem.get()).push_back(tep1); return std::make_tuple (true,0, tem); } static RET_DEFINE ExQueryAccountBalanceFunc(unsigned char * ipara,void * pVmScriptRun) { CVmRunEvn *pVmScript = (CVmRunEvn *)pVmScriptRun; vector<std::shared_ptr < vector<unsigned char> > > retdata; if(!GetData(ipara,retdata) ||retdata.size() != 1 || !(retdata.at(0).get()->size() == 6 || retdata.at(0).get()->size() == 34)) { return RetFalse(string(__FUNCTION__)+"para err !"); } bool flag = true; CKeyID addrKeyId; if (!GetKeyId(*pVmScript->GetCatchView(),*retdata.at(0).get(), addrKeyId)) { return RetFalse(string(__FUNCTION__)+"para err !"); } CUserID userid(addrKeyId); CAccount aAccount; auto tem = std::make_shared<std::vector< vector<unsigned char> > >(); if (!pVmScript->GetCatchView()->GetAccount(userid, aAccount)) { flag = false; } else { uint64_t nbalance = aAccount.GetRawBalance(); CDataStream tep(SER_DISK, CLIENT_VERSION); tep << nbalance; vector<unsigned char> tep1(tep.begin(),tep.end()); (*tem.get()).push_back(tep1); } return std::make_tuple (flag ,0, tem); } static RET_DEFINE ExGetTxConFirmHeightFunc(unsigned char * ipara,void * pVmScriptRun) { CVmRunEvn *pVmScript = (CVmRunEvn *)pVmScriptRun; vector<std::shared_ptr < vector<unsigned char> > > retdata; if(!GetData(ipara,retdata) ||retdata.size() != 1|| retdata.at(0).get()->size() != 32) { return RetFalse(string(__FUNCTION__)+"para err !"); } uint256 hash1(*retdata.at(0)); // LogPrint("vm","ExGetTxContractsFunc1:%s",hash1.GetHex().c_str()); auto tem = std::make_shared<std::vector< vector<unsigned char> > >(); int nHeight = GetTxComfirmHigh(hash1, *pVmScript->GetScriptDB()); if(-1 == nHeight) { return std::make_tuple (false,0, tem); } CDataStream tep(SER_DISK, CLIENT_VERSION); tep << nHeight; vector<unsigned char> tep1(tep.begin(),tep.end()); (*tem.get()).push_back(tep1); return std::make_tuple (true,0, tem); } static RET_DEFINE ExGetBlockHashFunc(unsigned char * ipara,void * pVmScriptRun) { vector<std::shared_ptr < vector<unsigned char> > > retdata; CVmRunEvn *pVmScript = (CVmRunEvn *)pVmScriptRun; if(!GetData(ipara,retdata) ||retdata.size() != 1 || retdata.at(0).get()->size() != sizeof(int)) { return RetFalse(string(__FUNCTION__)+"para err !"); } int height = 0; memcpy(&height, &retdata.at(0).get()->at(0), sizeof(int)); auto tem = std::make_shared<std::vector< vector<unsigned char> > >(); if (height <= 0 || height >= pVmScript->GetComfirHeight()) { return std::make_tuple (false,0, tem); } if(chainActive.Height() < height){ return std::make_tuple (false, 0,tem); } CBlockIndex *pindex = chainActive[height]; uint256 blockHash = pindex->GetBlockHash(); // LogPrint("vm","ExGetBlockHashFunc:%s",HexStr(blockHash).c_str()); CDataStream tep(SER_DISK, CLIENT_VERSION); tep << blockHash; vector<unsigned char> tep1(tep.begin(),tep.end()); (*tem.get()).push_back(tep1); return std::make_tuple (true,0, tem); } static RET_DEFINE ExGetCurRunEnvHeightFunc(unsigned char * ipara,void * pVmEvn) { CVmRunEvn *pVmRunEvn = (CVmRunEvn *)pVmEvn; int height = pVmRunEvn->GetComfirHeight(); auto tem = std::make_shared<std::vector< vector<unsigned char> > >(); CDataStream tep(SER_DISK, CLIENT_VERSION); tep << height; vector<unsigned char> tep1(tep.begin(),tep.end()); (*tem.get()).push_back(tep1); return std::make_tuple (true,0, tem); } static RET_DEFINE ExWriteDataDBFunc(unsigned char * ipara,void * pVmEvn) { CVmRunEvn *pVmRunEvn = (CVmRunEvn *)pVmEvn; vector<std::shared_ptr < vector<unsigned char> > > retdata; if(!GetData(ipara,retdata) ||retdata.size() != 2) { return RetFalse(string(__FUNCTION__)+"para err !"); } const CRegID scriptid = pVmRunEvn->GetScriptRegID(); bool flag = true; CScriptDBViewCache* scriptDB = pVmRunEvn->GetScriptDB(); CScriptDBOperLog operlog; int64_t step = (*retdata.at(1)).size() -1; if (!scriptDB->SetScriptData(scriptid, *retdata.at(0), *retdata.at(1),operlog)) { flag = false; } else { shared_ptr<vector<CScriptDBOperLog> > m_dblog = pVmRunEvn->GetDbLog(); (*m_dblog.get()).push_back(operlog); } auto tem = std::make_shared<std::vector< vector<unsigned char> > >(); CDataStream tep(SER_DISK, CLIENT_VERSION); tep << flag; vector<unsigned char> tep1(tep.begin(),tep.end()); (*tem.get()).push_back(tep1); return std::make_tuple (true,step, tem); } static RET_DEFINE ExDeleteDataDBFunc(unsigned char * ipara,void * pVmEvn) { CVmRunEvn *pVmRunEvn = (CVmRunEvn *)pVmEvn; vector<std::shared_ptr < vector<unsigned char> > > retdata; if(!GetData(ipara,retdata) ||retdata.size() != 1) { LogPrint("vm", "GetData return error!\n"); return RetFalse(string(__FUNCTION__)+"para err !"); } CRegID scriptid = pVmRunEvn->GetScriptRegID(); bool flag = true; CScriptDBViewCache* scriptDB = pVmRunEvn->GetScriptDB(); CScriptDBOperLog operlog; int64_t nstep = 0; vector<unsigned char> vValue; if(scriptDB->GetScriptData(pVmRunEvn->GetComfirHeight(),scriptid, *retdata.at(0), vValue)){ nstep = nstep - (int64_t)(vValue.size()+1); } if (!scriptDB->EraseScriptData(scriptid, *retdata.at(0), operlog)) { LogPrint("vm", "ExDeleteDataDBFunc error key:%s!\n",HexStr(*retdata.at(0))); flag = false; } else { shared_ptr<vector<CScriptDBOperLog> > m_dblog = pVmRunEvn->GetDbLog(); m_dblog.get()->push_back(operlog); } auto tem = std::make_shared<std::vector< vector<unsigned char> > >(); CDataStream tep(SER_DISK, CLIENT_VERSION); tep << flag; vector<unsigned char> tep1(tep.begin(),tep.end()); (*tem.get()).push_back(tep1); return std::make_tuple (true,nstep, tem); } static RET_DEFINE ExReadDataValueDBFunc(unsigned char * ipara,void * pVmEvn) { CVmRunEvn *pVmRunEvn = (CVmRunEvn *)pVmEvn; vector<std::shared_ptr < vector<unsigned char> > > retdata; if(!GetData(ipara,retdata) ||retdata.size() != 1) { return RetFalse(string(__FUNCTION__)+"para err !"); } CRegID scriptid = pVmRunEvn->GetScriptRegID(); vector_unsigned_char vValue; CScriptDBViewCache* scriptDB = pVmRunEvn->GetScriptDB(); bool flag =true; // LogPrint("INFO", "script run read data:%s\n", HexStr(*retdata.at(0))); auto tem = std::make_shared<std::vector< vector<unsigned char> > >(); if(!scriptDB->GetScriptData(pVmRunEvn->GetComfirHeight(),scriptid, *retdata.at(0), vValue)) { flag = false; } else { (*tem.get()).push_back(vValue); } return std::make_tuple (flag,0, tem); } static RET_DEFINE ExGetDBSizeFunc(unsigned char * ipara,void * pVmEvn) { CVmRunEvn *pVmRunEvn = (CVmRunEvn *)pVmEvn; CRegID scriptid = pVmRunEvn->GetScriptRegID(); int count = 0; bool flag = true; CScriptDBViewCache* scriptDB = pVmRunEvn->GetScriptDB(); auto tem = std::make_shared<std::vector< vector<unsigned char> > >(); if(!scriptDB->GetScriptDataCount(scriptid,count)) { flag = false; } else { CDataStream tep(SER_DISK, CLIENT_VERSION); tep << count; vector<unsigned char> tep1(tep.begin(),tep.end()); (*tem.get()).push_back(tep1); } return std::make_tuple (flag,0, tem); } static RET_DEFINE ExGetDBValueFunc(unsigned char * ipara,void * pVmEvn) { if (SysCfg().GetArg("-isdbtraversal", 0) == 0) { LogPrint("INFO","%s","ExGetDBValueFunc can't use\n"); return RetFalse(string(__FUNCTION__)+"para err !"); } CVmRunEvn *pVmRunEvn = (CVmRunEvn *)pVmEvn; vector<std::shared_ptr < vector<unsigned char> > > retdata; if(!GetData(ipara,retdata) ||(retdata.size() != 2 && retdata.size() != 1)) { return RetFalse(string(__FUNCTION__)+"para err !"); } int index = 0; bool flag = true; auto tem = std::make_shared<std::vector< vector<unsigned char> > >(); memcpy(&index,&retdata.at(0).get()->at(0),sizeof(int)); if(!(index == 0 ||(index == 1 && retdata.size() == 2))) { flag = false; return std::make_tuple (flag,0, tem); } CRegID scriptid = pVmRunEvn->GetScriptRegID(); vector_unsigned_char vValue; vector<unsigned char> vScriptKey; if(index == 1) { vScriptKey.assign(retdata.at(1).get()->begin(),retdata.at(1).get()->end()); } CScriptDBViewCache* scriptDB = pVmRunEvn->GetScriptDB(); flag = scriptDB->GetScriptData(pVmRunEvn->GetComfirHeight(),scriptid,index,vScriptKey,vValue); if(flag){ LogPrint("vm", "Read key:%s,value:%s!\n",HexStr(vScriptKey),HexStr(vValue)); (*tem.get()).push_back(vScriptKey); (*tem.get()).push_back(vValue); } return std::make_tuple (flag,0, tem); } static RET_DEFINE ExGetCurTxHash(unsigned char * ipara,void * pVmEvn) { CVmRunEvn *pVmRunEvn = (CVmRunEvn *)pVmEvn; uint256 hash = pVmRunEvn->GetCurTxHash(); auto tem = std::make_shared<std::vector< vector<unsigned char> > >(); CDataStream tep(SER_DISK, CLIENT_VERSION); tep << hash; vector<unsigned char> tep1(tep.begin(),tep.end()); (*tem.get()).push_back(tep1); // LogPrint("vm","ExGetCurTxHash:%s",HexStr(hash).c_str()); return std::make_tuple (true,0, tem); } static RET_DEFINE ExModifyDataDBVavleFunc(unsigned char * ipara,void * pVmEvn) { CVmRunEvn *pVmRunEvn = (CVmRunEvn *)pVmEvn; vector<std::shared_ptr < vector<unsigned char> > > retdata; if(!GetData(ipara,retdata) ||retdata.size() != 2 ) { return RetFalse(string(__FUNCTION__)+"para err !"); } CRegID scriptid = pVmRunEvn->GetScriptRegID(); vector_unsigned_char vValue; bool flag = false; CScriptDBViewCache* scriptDB = pVmRunEvn->GetScriptDB(); int64_t step = 0; CScriptDBOperLog operlog; vector_unsigned_char vTemp; if(scriptDB->GetScriptData(pVmRunEvn->GetComfirHeight(),scriptid, *retdata.at(0), vTemp)) { if(scriptDB->SetScriptData(scriptid,*retdata.at(0),*retdata.at(1).get(),operlog)) { shared_ptr<vector<CScriptDBOperLog> > m_dblog = pVmRunEvn->GetDbLog(); m_dblog.get()->push_back(operlog); flag = true; } } step =(((int64_t)(*retdata.at(1)).size())- (int64_t)(vTemp.size()) -1); auto tem = std::make_shared<std::vector< vector<unsigned char> > >(); CDataStream tep(SER_DISK, CLIENT_VERSION); tep << flag; vector<unsigned char> tep1(tep.begin(),tep.end()); (*tem.get()).push_back(tep1); return std::make_tuple (flag ,step, tem); } static RET_DEFINE ExWriteOutputFunc(unsigned char * ipara,void * pVmEvn) { CVmRunEvn *pVmRunEvn = (CVmRunEvn *)pVmEvn; vector<std::shared_ptr < vector<unsigned char> > > retdata; if(!GetData(ipara,retdata) ||retdata.size() != 1 ) { return RetFalse("para err"); } vector<CVmOperate> source; CVmOperate temp; int Size = ::GetSerializeSize(temp, SER_NETWORK, PROTOCOL_VERSION); int datadsize = retdata.at(0)->size(); int count = datadsize/Size; if(datadsize%Size != 0) { // assert(0); return RetFalse("para err"); } CDataStream ss(*retdata.at(0),SER_DISK, CLIENT_VERSION); while(count--) { ss >> temp; source.push_back(temp); } auto tem = std::make_shared<std::vector< vector<unsigned char> > >(); if(!pVmRunEvn->InsertOutputData(source)) { // return RetFalse("InsertOutput err"); return std::make_tuple (-1 ,0, tem); } return std::make_tuple (true ,0, tem); } static RET_DEFINE ExGetScriptDataFunc(unsigned char * ipara,void * pVmEvn) { vector<std::shared_ptr < vector<unsigned char> > > retdata; if(!GetData(ipara,retdata) ||retdata.size() != 2 || retdata.at(0).get()->size() != 6) { return RetFalse(string(__FUNCTION__)+"para err !"); } vector_unsigned_char vValue; bool flag =true; CVmRunEvn *pVmRunEvn = (CVmRunEvn *)pVmEvn; CScriptDBViewCache* scriptDB = pVmRunEvn->GetScriptDB(); CRegID scriptid(*retdata.at(0)); auto tem = std::make_shared<std::vector< vector<unsigned char> > >(); if(!scriptDB->GetScriptData(pVmRunEvn->GetComfirHeight(), scriptid, *retdata.at(1), vValue)) { flag = false; } else { (*tem.get()).push_back(vValue); } return std::make_tuple (flag,0, tem); } static RET_DEFINE ExGetScriptIDFunc(unsigned char * ipara,void * pVmEvn) { CVmRunEvn *pVmRunEvn = (CVmRunEvn *)pVmEvn; vector_unsigned_char scriptid = pVmRunEvn->GetScriptRegID().GetVec6(); auto tem = std::make_shared<std::vector< vector<unsigned char> > >(); (*tem.get()).push_back(scriptid); return std::make_tuple (true,0, tem); } static RET_DEFINE ExGetCurTxAccountFunc(unsigned char * ipara,void * pVmEvn) { CVmRunEvn *pVmRunEvn = (CVmRunEvn *)pVmEvn; vector_unsigned_char vUserId =pVmRunEvn->GetTxAccount().GetVec6(); auto tem = std::make_shared<std::vector< vector<unsigned char> > >(); (*tem.get()).push_back(vUserId); return std::make_tuple (true,0, tem); } static RET_DEFINE ExGetCurTxContactFunc(unsigned char * ipara, void *pVmEvn) { CVmRunEvn *pVmRunEvn = (CVmRunEvn *)pVmEvn; vector<unsigned char> contact =pVmRunEvn->GetTxContact(); auto tem = std::make_shared<std::vector< vector<unsigned char> > >(); (*tem.get()).push_back(contact); return std::make_tuple (true,0, tem); } enum COMPRESS_TYPE { U16_TYPE = 0, // U16_TYPE I16_TYPE = 1, // I16_TYPE U32_TYPE = 2, // U32_TYPE I32_TYPE = 3, // I32_TYPE U64_TYPE = 4, // U64_TYPE I64_TYPE = 5, // I64_TYPE NO_TYPE = 6, // NO_TYPE +n (tip char) }; static bool Decompress(vector<unsigned char>& format,vector<unsigned char> &contact,std::vector<unsigned char> &ret){ try { CDataStream ds(contact,SER_DISK, CLIENT_VERSION); CDataStream retdata(SER_DISK, CLIENT_VERSION); for (auto item = format.begin(); item != format.end();item++) { switch(*item) { case U16_TYPE: { unsigned short i = 0; ds >> VARINT(i); retdata<<i; break; } case I16_TYPE: { short i = 0; ds >> VARINT(i); retdata<<i; break; } case U32_TYPE: { short i = 0; ds >> VARINT(i); retdata<<i; break; } case I32_TYPE: { unsigned int i = 0; ds >> VARINT(i); retdata<<i; break; } case U64_TYPE: { uint64_t i = 0; ds >> VARINT(i); retdata<<i; break; } case I64_TYPE: { int64_t i = 0; ds >> VARINT(i); retdata<<i; break; } case NO_TYPE: { unsigned char temp = 0; item++; int te = *item; while (te--) { ds >> VARINT(temp); retdata<<temp; } break; } default: { return ERRORMSG("%s\r\n",__FUNCTION__); } } } ret.insert(ret.begin(),retdata.begin(),retdata.end()); } catch (...) { LogPrint("vm","seseril err in funciton:%s",__FUNCTION__); return false; } return true; } static RET_DEFINE ExCurDeCompressContactFunc(unsigned char *ipara,void *pVmEvn){ vector<std::shared_ptr < vector<unsigned char> > > retdata; if(!GetData(ipara,retdata) ||retdata.size() != 1 ) { return RetFalse(string(__FUNCTION__)+"para err !"); } vector<unsigned char> contact =((CVmRunEvn *)pVmEvn)->GetTxContact(); std::vector<unsigned char> outContact; if(!Decompress(*retdata.at(0),contact,outContact)) { return RetFalse(string(__FUNCTION__)+"para err !"); } auto tem = std::make_shared<std::vector< vector<unsigned char> > >(); (*tem.get()).push_back(outContact); return std::make_tuple (true,0, tem); } static RET_DEFINE ExDeCompressContactFunc(unsigned char *ipara,void *pVmEvn){ CVmRunEvn *pVmScript = (CVmRunEvn *)pVmEvn; vector<std::shared_ptr < vector<unsigned char> > > retdata; if(!GetData(ipara,retdata) ||retdata.size() != 2 || retdata.at(1).get()->size() != 32) { return RetFalse(string(__FUNCTION__)+"para err !"); } uint256 hash1(*retdata.at(1)); // LogPrint("vm","ExGetTxContractsFunc1:%s\n",hash1.GetHex().c_str()); bool flag = false; std::shared_ptr<CBaseTransaction> pBaseTx; auto tem = std::make_shared<std::vector< vector<unsigned char> > >(); if (GetTransaction(pBaseTx, hash1, *pVmScript->GetScriptDB(), false)) { CTransaction *tx = static_cast<CTransaction*>(pBaseTx.get()); std::vector<unsigned char> outContact; if (!Decompress(*retdata.at(0), tx->vContract, outContact)) { return RetFalse(string(__FUNCTION__) + "para err !"); } (*tem.get()).push_back(outContact); flag = true; } return std::make_tuple (flag,0, tem); } static RET_DEFINE GetCurTxPayAmountFunc(unsigned char *ipara,void *pVmEvn){ CVmRunEvn *pVmRunEvn = (CVmRunEvn *)pVmEvn; uint64_t lvalue =pVmRunEvn->GetValue(); auto tem = std::make_shared<std::vector< vector<unsigned char> > >(); CDataStream tep(SER_DISK, CLIENT_VERSION); tep << lvalue; vector<unsigned char> tep1(tep.begin(),tep.end()); (*tem.get()).push_back(tep1); return std::make_tuple (true,0, tem); } struct S_APP_ID { unsigned char idlen; //!the len of the tag unsigned char ID[CAppCFund::MAX_TAG_SIZE]; //! the ID for the const vector<unsigned char> GetIdV() const { assert(sizeof(ID) >= idlen); vector<unsigned char> Id(&ID[0], &ID[idlen]); return (Id); } }__attribute((aligned (1))); static RET_DEFINE GetUserAppAccValue(unsigned char * ipara,void * pVmScript){ CVmRunEvn *pVmScriptRun = (CVmRunEvn *)pVmScript; vector<std::shared_ptr < vector<unsigned char> > > retdata; if(!GetData(ipara,retdata) ||retdata.size() != 1 || retdata.at(0).get()->size() != sizeof(S_APP_ID)) { return RetFalse(string(__FUNCTION__)+"para err !"); } S_APP_ID accid; memcpy(&accid, &retdata.at(0).get()->at(0), sizeof(S_APP_ID)); bool flag = false; shared_ptr<CAppUserAccout> sptrAcc; uint64_t value = 0 ; auto tem = std::make_shared<std::vector< vector<unsigned char> > >(); if(pVmScriptRun->GetAppUserAccout(accid.GetIdV(),sptrAcc)) { value = sptrAcc->getllValues(); // cout<<"read:"<<endl; // cout<<sptrAcc->toString()<<endl; CDataStream tep(SER_DISK, CLIENT_VERSION); tep << value; vector<unsigned char> tep1(tep.begin(),tep.end()); (*tem.get()).push_back(tep1); flag = true; } return std::make_tuple (flag,0, tem); } static RET_DEFINE GetUserAppAccFoudWithTag(unsigned char * ipara,void * pVmScript){ CVmRunEvn *pVmScriptRun = (CVmRunEvn *)pVmScript; vector<std::shared_ptr < vector<unsigned char> > > retdata; unsigned int Size(0); CAppFundOperate temp; Size = ::GetSerializeSize(temp, SER_NETWORK, PROTOCOL_VERSION); if(!GetData(ipara,retdata) ||retdata.size() != 1 || retdata.at(0).get()->size() !=Size) { return RetFalse(string(__FUNCTION__)+"para err !"); } CDataStream ss(*retdata.at(0),SER_DISK, CLIENT_VERSION); CAppFundOperate userfund; ss>>userfund; shared_ptr<CAppUserAccout> sptrAcc; bool flag = false; auto tem = std::make_shared<std::vector< vector<unsigned char> > >(); CAppCFund fund; if(pVmScriptRun->GetAppUserAccout(userfund.GetAppUserV(),sptrAcc)) { if(!sptrAcc->GetAppCFund(fund,userfund.GetFundTagV(),userfund.outheight)) { return RetFalse(string(__FUNCTION__)+"tag err !"); } CDataStream tep(SER_DISK, CLIENT_VERSION); tep << fund.getvalue() ; vector<unsigned char> tep1(tep.begin(),tep.end()); (*tem.get()).push_back(tep1); flag = true; } return std::make_tuple (flag,0, tem); } static RET_DEFINE ExWriteOutAppOperateFunc(unsigned char * ipara,void * pVmEvn) { CVmRunEvn *pVmRunEvn = (CVmRunEvn *)pVmEvn; vector<std::shared_ptr < vector<unsigned char> > > retdata; CAppFundOperate temp; unsigned int Size = ::GetSerializeSize(temp, SER_NETWORK, PROTOCOL_VERSION); if(!GetData(ipara,retdata) ||retdata.size() != 1 || (retdata.at(0).get()->size()%Size) != 0 ) { return RetFalse("para err"); } int count = retdata.at(0).get()->size()/Size; CDataStream ss(*retdata.at(0),SER_DISK, CLIENT_VERSION); int64_t step =-1; while(count--) { ss >> temp; if(temp.mMoney < 0) { return RetFalse("para err"); } pVmRunEvn->InsertOutAPPOperte(temp.GetAppUserV(),temp); step +=Size; } auto tem = std::make_shared<std::vector< vector<unsigned char> > >(); return std::make_tuple (true ,step, tem); } static RET_DEFINE ExGetBase58AddrFunc(unsigned char * ipara,void * pVmEvn){ CVmRunEvn *pVmRunEvn = (CVmRunEvn *)pVmEvn; vector<std::shared_ptr < vector<unsigned char> > > retdata; if(!GetData(ipara,retdata) ||retdata.size() != 1 || retdata.at(0).get()->size() != 6) { return RetFalse(string(__FUNCTION__)+"para err !"); } CKeyID addrKeyId; if (!GetKeyId(*pVmRunEvn->GetCatchView(),*retdata.at(0).get(), addrKeyId)) { return RetFalse(string(__FUNCTION__)+"para err !"); } string addr = addrKeyId.ToAddress(); auto tem = std::make_shared<std::vector< vector<unsigned char> > >(); vector<unsigned char> vTemp; vTemp.assign(addr.c_str(),addr.c_str()+addr.length()); (*tem.get()).push_back(vTemp); return std::make_tuple (true,0, tem); } enum CALL_API_FUN { COMP_FUNC = 0, //!< COMP_FUNC MULL_MONEY, //!< MULL_MONEY ADD_MONEY, //!< ADD_MONEY SUB_MONEY, //!< SUB_MONEY DIV_MONEY, //!< DIV_MONEY SHA256_FUNC, //!< SHA256_FUNC DES_FUNC, //!< DES_FUNC VERFIY_SIGNATURE_FUNC, //!< VERFIY_SIGNATURE_FUNC SIGNATURE_FUNC, //!< SIGNATURE_FUNC PRINT_FUNC, //!< PRINT_FUNC GETTX_CONTRACT_FUNC, //!< GETTX_CONTRACT_FUNC GETTX_ACCOUNT_FUNC, //!< GETTX_ACCOUNT_FUNC GETACCPUB_FUNC, //!< GETACCPUB_FUNC QUEYACCBALANCE_FUNC, //!< QUEYACCBALANCE_FUNC GETTXCONFIRH_FUNC, //!< GETTXCONFIRH_FUNC GETBLOCKHASH_FUNC, //!< GETBLOCKHASH_FUNC //// tx api GETCTXCONFIRMH_FUNC, //!< GETCTXCONFIRMH_FUNC WRITEDB_FUNC, //!< WRITEDB_FUNC DELETEDB_FUNC, //!< DELETEDB_FUNC READDB_FUNC, //!< READDB_FUNC GETDBSIZE_FUNC, //!< GETDBSIZE_FUNC GETDBVALUE_FUNC, //!< GETDBVALUE_FUNC GetCURTXHASH_FUNC, //!< GetCURTXHASH_FUNC MODIFYDBVALUE_FUNC, //!< MODIFYDBVALUE_FUNC WRITEOUTPUT_FUNC, //!<WRITEOUTPUT_FUNC GETSCRIPTDATA_FUNC, //!<GETSCRIPTDATA_FUNC GETSCRIPTID_FUNC, //!<GETSCRIPTID_FUNC GETCURTXACCOUNT_FUNC, //!<GETCURTXACCOUNT_FUNC GETCURTXCONTACT_FUNC, //!<GETCURTXCONTACT_FUNC GETCURDECOMPRESSCONTACR_FUNC, //!<GETCURDECOMPRESSCONTACR_FUNC GETDECOMPRESSCONTACR_FUNC, //!<GETDECOMPRESSCONTACR_FUNC GETCURPAYMONEY_FUN, //!<GETCURPAYMONEY_FUN GET_APP_USER_ACC_VALUE_FUN, //!<GET_APP_USER_ACC_FUN GET_APP_USER_ACC_FUND_WITH_TAG_FUN, //!<GET_APP_USER_ACC_FUND_WITH_TAG_FUN GET_WIRITE_OUT_APP_OPERATE_FUN, //!<GET_WIRITE_OUT_APP_OPERATE_FUN GET_KOALA_ADDRESS_FUN, }; const static string API_METOHD[] = { "COMP_FUNC", "MULL_MONEY", "ADD_MONEY", "SUB_MONEY", "DIV_MONEY", "SHA256_FUNC", "DES_FUNC", "VERFIY_SIGNATURE_FUNC", "SIGNATURE_FUNC", "PRINT_FUNC", "GETTX_CONTRACT_FUNC", "GETTX_ACCOUNT_FUNC", "GETACCPUB_FUNC", "QUEYACCBALANCE_FUNC", "GETTXCONFIRH_FUNC", "GETBLOCKHASH_FUNC", "GETCTXCONFIRMH_FUNC", "WRITEDB_FUNC", "DELETEDB_FUNC", "READDB_FUNC", "GETDBSIZE_FUNC", "GETDBVALUE_FUNC", "GetCURTXHASH_FUNC", "MODIFYDBVALUE_FUNC", "WRITEOUTPUT_FUNC", "GETSCRIPTDATA_FUNC", "GETSCRIPTID_FUNC", "GETCURTXACCOUNT_FUNC", "GETCURTXCONTACT_FUNC", "GETCURDECOMPRESSCONTACR_FUNC", "GETDECOMPRESSCONTACR_FUNC", "GETCURPAYMONEY_FUN", "GET_APP_USER_ACC_VALUE_FUN", "GET_APP_USER_ACC_FUND_WITH_TAG_FUN", "GET_WIRITE_OUT_APP_OPERATE_FUN", "GET_KOALA_ADDRESS_FUN" }; const static struct __MapExterFun FunMap[] = { // { COMP_FUNC, ExInt64CompFunc }, // { MULL_MONEY, ExInt64MullFunc }, // { ADD_MONEY, ExInt64AddFunc }, // { SUB_MONEY, ExInt64SubFunc }, // { DIV_MONEY, ExInt64DivFunc }, // { SHA256_FUNC, ExSha256Func }, // { DES_FUNC, ExDesFunc }, // { VERFIY_SIGNATURE_FUNC, ExVerifySignatureFunc }, // { SIGNATURE_FUNC, ExSignatureFunc }, // { PRINT_FUNC, ExLogPrintFunc }, // {GETTX_CONTRACT_FUNC,ExGetTxContractsFunc}, // {GETTX_ACCOUNT_FUNC,ExGetTxAccountsFunc}, {GETACCPUB_FUNC,ExGetAccountPublickeyFunc}, {QUEYACCBALANCE_FUNC,ExQueryAccountBalanceFunc}, {GETTXCONFIRH_FUNC,ExGetTxConFirmHeightFunc}, {GETBLOCKHASH_FUNC,ExGetBlockHashFunc}, {GETCTXCONFIRMH_FUNC,ExGetCurRunEnvHeightFunc}, {WRITEDB_FUNC,ExWriteDataDBFunc}, {DELETEDB_FUNC,ExDeleteDataDBFunc}, {READDB_FUNC,ExReadDataValueDBFunc}, {GETDBSIZE_FUNC,ExGetDBSizeFunc}, {GETDBVALUE_FUNC,ExGetDBValueFunc}, {GetCURTXHASH_FUNC,ExGetCurTxHash}, {MODIFYDBVALUE_FUNC,ExModifyDataDBVavleFunc}, {WRITEOUTPUT_FUNC,ExWriteOutputFunc}, {GETSCRIPTDATA_FUNC,ExGetScriptDataFunc}, {GETSCRIPTID_FUNC,ExGetScriptIDFunc}, {GETCURTXACCOUNT_FUNC,ExGetCurTxAccountFunc }, {GETCURTXCONTACT_FUNC,ExGetCurTxContactFunc }, {GETCURDECOMPRESSCONTACR_FUNC,ExCurDeCompressContactFunc }, {GETDECOMPRESSCONTACR_FUNC,ExDeCompressContactFunc }, {GETCURPAYMONEY_FUN,GetCurTxPayAmountFunc}, {GET_APP_USER_ACC_VALUE_FUN,GetUserAppAccValue}, {GET_APP_USER_ACC_FUND_WITH_TAG_FUN,GetUserAppAccFoudWithTag}, {GET_WIRITE_OUT_APP_OPERATE_FUN,ExWriteOutAppOperateFunc}, {GET_KOALA_ADDRESS_FUN,ExGetBase58AddrFunc}, }; RET_DEFINE CallExternalFunc(INT16U method, unsigned char *ipara,CVmRunEvn *pVmEvn) { return FunMap[method].fun(ipara, pVmEvn); } int64_t CVm8051::run(uint64_t maxstep, CVmRunEvn *pVmEvn) { INT8U code = 0; int64_t step = 0; //uint64_t if((maxstep == 0) || (NULL == pVmEvn)){ return -1; } while (1) { code = GetOpcode(); StepRun(code); step++; //call func out of 8051 if (Sys.PC == 0x0012) { //get what func will be called INT16U methodID = ((INT16U) GetExRam(VM_FUN_CALL_ADDR) | ((INT16U) GetExRam(VM_FUN_CALL_ADDR+1) << 8)); unsigned char *ipara = (unsigned char *) GetExRamAddr(VM_SHARE_ADDR); //input para RET_DEFINE retdata = CallExternalFunc(methodID, ipara, pVmEvn); memset(ipara, 0, MAX_SHARE_RAM); step += std::get<1>(retdata) - 1; if (std::get<0>(retdata) == 1) { auto tem = std::get<2>(retdata); int pos = 0; int totalsize = 0; for (auto& it : *tem.get()) { totalsize += it.size() + 2; } if (totalsize + 2 < MAX_SHARE_RAM) { //if data not over for (auto& it : *tem.get()) { int size = it.size(); memcpy(&ipara[pos], &size, 2); memcpy(&ipara[pos + 2], &it.at(0), size); pos += size + 2; } } } else if(std::get<0>(retdata) == -1){ LogPrint("CONTRACT_TX", "call method id:%d methodName:%s\n", methodID, API_METOHD[methodID]); return -1; } else { } } else if (Sys.PC == 0x0008) { INT8U result = GetExRam(0xEFFD); if (result == 0x01) { return step; } return 0; } if (step >= (int64_t)MAX_BLOCK_RUN_STEP || step >= (int64_t)maxstep){ LogPrint("CONTRACT_TX", "failed step:%ld\n", step); return -1; //force return } } return 1; } bool CVm8051::run() { INT8U code = 0; // INT16U flag; while (1) { code = GetOpcode(); StepRun(code); // UpDataDebugInfo(); //call func out of 8051 if (Sys.PC == 0x0012) { //get what func will be called INT16U method = ((INT16U) GetExRam(VM_FUN_CALL_ADDR) | ((INT16U) GetExRam(VM_FUN_CALL_ADDR+1) << 8)); // flag = method; unsigned char *ipara = (unsigned char *) GetExRamAddr(VM_SHARE_ADDR); //input para CVmRunEvn *pVmScript = NULL; RET_DEFINE retdata = CallExternalFunc(method, ipara, pVmScript); //memset(ipara, 0, MAX_SHARE_RAM); memset(ipara, 0, 8); if (std::get<0>(retdata)) { auto tem = std::get<2>(retdata); int pos = 0; int totalsize = 0; for (auto& it : *tem.get()) { totalsize += it.size() + 2; } if (totalsize + 2 < MAX_SHARE_RAM) { for (auto& it : *tem.get()) { int size = it.size(); memcpy(&ipara[pos], &size, 2); memcpy(&ipara[pos + 2], &it.at(0), size); pos += size + 2; } } } }else if (Sys.PC == 0x0008) { INT8U result=GetExRam(0xEFFD); if(result == 0x01) { return 1; } return 0; } } return 1; } void CVm8051::SetExRamData(INT16U addr, const vector<unsigned char> data) { memcpy(&m_ExRam[addr], &data[0], data.size()); } void CVm8051::StepRun(INT8U code) { switch (code) { case 0x00: { Opcode_00_NOP(); break; } case 0x01: { Opcode_01_AJMP_Addr11(); break; } case 0x02: { Opcode_02_LJMP_Addr16(); break; } case 0x03: { Opcode_03_RR_A(); break; } case 0x04: { Opcode_04_INC_A(); break; } case 0x05: { Opcode_05_INC_Direct(); break; } case 0x06: { Opcode_06_INC_R0_1(); break; } case 0x07: { Opcode_07_INC_R1_1(); break; } case 0x08: { Opcode_08_INC_R0(); break; } case 0x09: { Opcode_09_INC_R1(); break; } case 0x0A: { Opcode_0A_INC_R2(); break; } case 0x0B: { Opcode_0B_INC_R3(); break; } case 0x0C: { Opcode_0C_INC_R4(); break; } case 0x0D: { Opcode_0D_INC_R5(); break; } case 0x0E: { Opcode_0E_INC_R6(); break; } case 0x0F: { Opcode_0F_INC_R7(); break; } case 0x10: { Opcode_10_JBC_Bit_Rel(); break; } case 0x11: { Opcode_11_ACALL_Addr11(); break; } case 0x12: { Opcode_12_LCALL_Addr16(); break; } case 0x13: { Opcode_13_RRC_A(); break; } case 0x14: { Opcode_14_DEC_A(); break; } case 0x15: { Opcode_15_DEC_Direct(); break; } case 0x16: { Opcode_16_DEC_R0_1(); break; } case 0x17: { Opcode_17_DEC_R1_1(); break; } case 0x18: { Opcode_18_DEC_R0(); break; } case 0x19: { Opcode_19_DEC_R1(); break; } case 0x1A: { Opcode_1A_DEC_R2(); break; } case 0x1B: { Opcode_1B_DEC_R3(); break; } case 0x1C: { Opcode_1C_DEC_R4(); break; } case 0x1D: { Opcode_1D_DEC_R5(); break; } case 0x1E: { Opcode_1E_DEC_R6(); break; } case 0x1F: { Opcode_1F_DEC_R7(); break; } case 0x20: { Opcode_20_JB_Bit_Rel(); break; } case 0x21: { Opcode_21_AJMP_Addr11(); break; } case 0x22: { Opcode_22_RET(); break; } case 0x23: { Opcode_23_RL_A(); break; } case 0x24: { Opcode_24_ADD_A_Data(); break; } case 0x25: { Opcode_25_ADD_A_Direct(); break; } case 0x26: { Opcode_26_ADD_A_R0_1(); break; } case 0x27: { Opcode_27_ADD_A_R1_1(); break; } case 0x28: { Opcode_28_ADD_A_R0(); break; } case 0x29: { Opcode_29_ADD_A_R1(); break; } case 0x2A: { Opcode_2A_ADD_A_R2(); break; } case 0x2B: { Opcode_2B_ADD_A_R3(); break; } case 0x2C: { Opcode_2C_ADD_A_R4(); break; } case 0x2D: { Opcode_2D_ADD_A_R5(); break; } case 0x2E: { Opcode_2E_ADD_A_R6(); break; } case 0x2F: { Opcode_2F_ADD_A_R7(); break; } case 0x30: { Opcode_30_JNB_Bit_Rel(); break; } case 0x31: { Opcode_31_ACALL_Addr11(); break; } case 0x32: { Opcode_32_RETI(); break; } case 0x33: { Opcode_33_RLC_A(); break; } case 0x34: { Opcode_34_ADDC_A_Data(); break; } case 0x35: { Opcode_35_ADDC_A_Direct(); break; } case 0x36: { Opcode_36_ADDC_A_R0_1(); break; } case 0x37: { Opcode_37_ADDC_A_R1_1(); break; } case 0x38: { Opcode_38_ADDC_A_R0(); break; } case 0x39: { Opcode_39_ADDC_A_R1(); break; } case 0x3A: { Opcode_3A_ADDC_A_R2(); break; } case 0x3B: { Opcode_3B_ADDC_A_R3(); break; } case 0x3C: { Opcode_3C_ADDC_A_R4(); break; } case 0x3D: { Opcode_3D_ADDC_A_R5(); break; } case 0x3E: { Opcode_3E_ADDC_A_R6(); break; } case 0x3F: { Opcode_3F_ADDC_A_R7(); break; } case 0x40: { Opcode_40_JC_Rel(); break; } case 0x41: { Opcode_41_AJMP_Addr11(); break; } case 0x42: { Opcode_42_ORL_Direct_A(); break; } case 0x43: { Opcode_43_ORL_Direct_Data(); break; } case 0x44: { Opcode_44_ORL_A_Data(); break; } case 0x45: { Opcode_45_ORL_A_Direct(); break; } case 0x46: { Opcode_46_ORL_A_R0_1(); break; } case 0x47: { Opcode_47_ORL_A_R1_1(); break; } case 0x48: { Opcode_48_ORL_A_R0(); break; } case 0x49: { Opcode_49_ORL_A_R1(); break; } case 0x4A: { Opcode_4A_ORL_A_R2(); break; } case 0x4B: { Opcode_4B_ORL_A_R3(); break; } case 0x4C: { Opcode_4C_ORL_A_R4(); break; } case 0x4D: { Opcode_4D_ORL_A_R5(); break; } case 0x4E: { Opcode_4E_ORL_A_R6(); break; } case 0x4F: { Opcode_4F_ORL_A_R7(); break; } case 0x50: { Opcode_50_JNC_Rel(); break; } case 0x51: { Opcode_51_ACALL_Addr11(); break; } case 0x52: { Opcode_52_ANL_Direct_A(); break; } case 0x53: { Opcode_53_ANL_Direct_Data(); break; } case 0x54: { Opcode_54_ANL_A_Data(); break; } case 0x55: { Opcode_55_ANL_A_Direct(); break; } case 0x56: { Opcode_56_ANL_A_R0_1(); break; } case 0x57: { Opcode_57_ANL_A_R1_1(); break; } case 0x58: { Opcode_58_ANL_A_R0(); break; } case 0x59: { Opcode_59_ANL_A_R1(); break; } case 0x5A: { Opcode_5A_ANL_A_R2(); break; } case 0x5B: { Opcode_5B_ANL_A_R3(); break; } case 0x5C: { Opcode_5C_ANL_A_R4(); break; } case 0x5D: { Opcode_5D_ANL_A_R5(); break; } case 0x5E: { Opcode_5E_ANL_A_R6(); break; } case 0x5F: { Opcode_5F_ANL_A_R7(); break; } case 0x60: { Opcode_60_JZ_Rel(); break; } case 0x61: { Opcode_61_AJMP_Addr11(); break; } case 0x62: { Opcode_62_XRL_Direct_A(); break; } case 0x63: { Opcode_63_XRL_Direct_Data(); break; } case 0x64: { Opcode_64_XRL_A_Data(); break; } case 0x65: { Opcode_65_XRL_A_Direct(); break; } case 0x66: { Opcode_66_XRL_A_R0_1(); break; } case 0x67: { Opcode_67_XRL_A_R1_1(); break; } case 0x68: { Opcode_68_XRL_A_R0(); break; } case 0x69: { Opcode_69_XRL_A_R1(); break; } case 0x6A: { Opcode_6A_XRL_A_R2(); break; } case 0x6B: { Opcode_6B_XRL_A_R3(); break; } case 0x6C: { Opcode_6C_XRL_A_R4(); break; } case 0x6D: { Opcode_6D_XRL_A_R5(); break; } case 0x6E: { Opcode_6E_XRL_A_R6(); break; } case 0x6F: { Opcode_6F_XRL_A_R7(); break; } case 0x70: { Opcode_70_JNZ_Rel(); break; } case 0x71: { Opcode_71_ACALL_Addr11(); break; } case 0x72: { Opcode_72_ORL_C_Direct(); break; } case 0x73: { Opcode_73_JMP_A_DPTR(); break; } case 0x74: { Opcode_74_MOV_A_Data(); break; } case 0x75: { Opcode_75_MOV_Direct_Data(); break; } case 0x76: { Opcode_76_MOV_R0_1_Data(); break; } case 0x77: { Opcode_77_MOV_R1_1_Data(); break; } case 0x78: { Opcode_78_MOV_R0_Data(); break; } case 0x79: { Opcode_79_MOV_R1_Data(); break; } case 0x7A: { Opcode_7A_MOV_R2_Data(); break; } case 0x7B: { Opcode_7B_MOV_R3_Data(); break; } case 0x7C: { Opcode_7C_MOV_R4_Data(); break; } case 0x7D: { Opcode_7D_MOV_R5_Data(); break; } case 0x7E: { Opcode_7E_MOV_R6_Data(); break; } case 0x7F: { Opcode_7F_MOV_R7_Data(); break; } case 0x80: { Opcode_80_SJMP_Rel(); break; } case 0x81: { Opcode_81_AJMP_Addr11(); break; } case 0x82: { Opcode_82_ANL_C_Bit(); break; } case 0x83: { Opcode_83_MOVC_A_PC(); break; } case 0x84: { Opcode_84_DIV_AB(); break; } case 0x85: { Opcode_85_MOV_Direct_Direct(); break; } case 0x86: { Opcode_86_MOV_Direct_R0_1(); break; } case 0x87: { Opcode_87_MOV_Direct_R1_1(); break; } case 0x88: { Opcode_88_MOV_Direct_R0(); break; } case 0x89: { Opcode_89_MOV_Direct_R1(); break; } case 0x8A: { Opcode_8A_MOV_Direct_R2(); break; } case 0x8B: { Opcode_8B_MOV_Direct_R3(); break; } case 0x8C: { Opcode_8C_MOV_Direct_R4(); break; } case 0x8D: { Opcode_8D_MOV_Direct_R5(); break; } case 0x8E: { Opcode_8E_MOV_Direct_R6(); break; } case 0x8F: { Opcode_8F_MOV_Direct_R7(); break; } case 0x90: { Opcode_90_MOV_DPTR_Data(); break; } case 0x91: { Opcode_91_ACALL_Addr11(); break; } case 0x92: { Opcode_92_MOV_Bit_C(); break; } case 0x93: { Opcode_93_MOVC_A_DPTR(); break; } case 0x94: { Opcode_94_SUBB_A_Data(); break; } case 0x95: { Opcode_95_SUBB_A_Direct(); break; } case 0x96: { Opcode_96_SUBB_A_R0_1(); break; } case 0x97: { Opcode_97_SUBB_A_R1_1(); break; } case 0x98: { Opcode_98_SUBB_A_R0(); break; } case 0x99: { Opcode_99_SUBB_A_R1(); break; } case 0x9A: { Opcode_9A_SUBB_A_R2(); break; } case 0x9B: { Opcode_9B_SUBB_A_R3(); break; } case 0x9C: { Opcode_9C_SUBB_A_R4(); break; } case 0x9D: { Opcode_9D_SUBB_A_R5(); break; } case 0x9E: { Opcode_9E_SUBB_A_R6(); break; } case 0x9F: { Opcode_9F_SUBB_A_R7(); break; } case 0xA0: { Opcode_A0_ORL_C_Bit(); break; } case 0xA1: { Opcode_A1_AJMP_Addr11(); break; } case 0xA2: { Opcode_A2_MOV_C_Bit(); break; } case 0xA3: { Opcode_A3_INC_DPTR(); break; } case 0xA4: { Opcode_A4_MUL_AB(); break; } case 0xA5: { Opcode_A5(); break; } case 0xA6: { Opcode_A6_MOV_R0_1_Direct(); break; } case 0xA7: { Opcode_A7_MOV_R1_1_Direct(); break; } case 0xA8: { Opcode_A8_MOV_R0_Direct(); break; } case 0xA9: { Opcode_A9_MOV_R1_Direct(); break; } case 0xAA: { Opcode_AA_MOV_R2_Direct(); break; } case 0xAB: { Opcode_AB_MOV_R3_Direct(); break; } case 0xAC: { Opcode_AC_MOV_R4_Direct(); break; } case 0xAD: { Opcode_AD_MOV_R5_Direct(); break; } case 0xAE: { Opcode_AE_MOV_R6_Direct(); break; } case 0xAF: { Opcode_AF_MOV_R7_Direct(); break; } case 0xB0: { Opcode_B0_ANL_C_Bit_1(); break; } case 0xB1: { Opcode_B1_ACALL_Addr11(); break; } case 0xB2: { Opcode_B2_CPL_Bit(); break; } case 0xB3: { Opcode_B3_CPL_C(); break; } case 0xB4: { Opcode_B4_CJNE_A_Data_Rel(); break; } case 0xB5: { Opcode_B5_CJNE_A_Direct_Rel(); break; } case 0xB6: { Opcode_B6_CJNE_R0_1_Data_Rel(); break; } case 0xB7: { Opcode_B7_CJNE_R1_1_Data_Rel(); break; } case 0xB8: { Opcode_B8_CJNE_R0_Data_Rel(); break; } case 0xB9: { Opcode_B9_CJNE_R1_Data_Rel(); break; } case 0xBA: { Opcode_BA_CJNE_R2_Data_Rel(); break; } case 0xBB: { Opcode_BB_CJNE_R3_Data_Rel(); break; } case 0xBC: { Opcode_BC_CJNE_R4_Data_Rel(); break; } case 0xBD: { Opcode_BD_CJNE_R5_Data_Rel(); break; } case 0xBE: { Opcode_BE_CJNE_R6_Data_Rel(); break; } case 0xBF: { Opcode_BF_CJNE_R7_Data_Rel(); break; } case 0xC0: { Opcode_C0_PUSH_Direct(); break; } case 0xC1: { Opcode_C1_AJMP_Addr11(); break; } case 0xC2: { Opcode_C2_CLR_Bit(); break; } case 0xC3: { Opcode_C3_CLR_C(); break; } case 0xC4: { Opcode_C4_SWAP_A(); break; } case 0xC5: { Opcode_C5_XCH_A_Direct(); break; } case 0xC6: { Opcode_C6_XCH_A_R0_1(); break; } case 0xC7: { Opcode_C7_XCH_A_R1_1(); break; } case 0xC8: { Opcode_C8_XCH_A_R0(); break; } case 0xC9: { Opcode_C9_XCH_A_R1(); break; } case 0xCA: { Opcode_CA_XCH_A_R2(); break; } case 0xCB: { Opcode_CB_XCH_A_R3(); break; } case 0xCC: { Opcode_CC_XCH_A_R4(); break; } case 0xCD: { Opcode_CD_XCH_A_R5(); break; } case 0xCE: { Opcode_CE_XCH_A_R6(); break; } case 0xCF: { Opcode_CF_XCH_A_R7(); break; } case 0xD0: { Opcode_D0_POP_Direct(); break; } case 0xD1: { Opcode_D1_ACALL_Addr11(); break; } case 0xD2: { Opcode_D2_SETB_Bit(); break; } case 0xD3: { Opcode_D3_SETB_C(); break; } case 0xD4: { Opcode_D4_DA_A(); break; } case 0xD5: { Opcode_D5_DJNZ_Direct_Rel(); break; } case 0xD6: { Opcode_D6_XCHD_A_R0_1(); break; } case 0xD7: { Opcode_D7_XCHD_A_R1_1(); break; } case 0xD8: { Opcode_D8_DJNZ_R0_Rel(); break; } case 0xD9: { Opcode_D9_DJNZ_R1_Rel(); break; } case 0xDA: { Opcode_DA_DJNZ_R2_Rel(); break; } case 0xDB: { Opcode_DB_DJNZ_R3_Rel(); break; } case 0xDC: { Opcode_DC_DJNZ_R4_Rel(); break; } case 0xDD: { Opcode_DD_DJNZ_R5_Rel(); break; } case 0xDE: { Opcode_DE_DJNZ_R6_Rel(); break; } case 0xDF: { Opcode_DF_DJNZ_R7_Rel(); break; } case 0xE0: { Opcode_E0_MOVX_A_DPTR(); break; } case 0xE1: { Opcode_E1_AJMP_Addr11(); break; } case 0xE2: { Opcode_E2_MOVX_A_R0_1(); break; } case 0xE3: { Opcode_E3_MOVX_A_R1_1(); break; } case 0xE4: { Opcode_E4_CLR_A(); break; } case 0xE5: { Opcode_E5_MOV_A_Direct(); break; } case 0xE6: { Opcode_E6_MOV_A_R0_1(); break; } case 0xE7: { Opcode_E7_MOV_A_R1_1(); break; } case 0xE8: { Opcode_E8_MOV_A_R0(); break; } case 0xE9: { Opcode_E9_MOV_A_R1(); break; } case 0xEA: { Opcode_EA_MOV_A_R2(); break; } case 0xEB: { Opcode_EB_MOV_A_R3(); break; } case 0xEC: { Opcode_EC_MOV_A_R4(); break; } case 0xED: { Opcode_ED_MOV_A_R5(); break; } case 0xEE: { Opcode_EE_MOV_A_R6(); break; } case 0xEF: { Opcode_EF_MOV_A_R7(); break; } case 0xF0: { Opcode_F0_MOVX_DPTR_A(); break; } case 0xF1: { Opcode_F1_ACALL_Addr11(); break; } case 0xF2: { Opcode_F2_MOVX_R0_1_A(); break; } case 0xF3: { Opcode_F3_MOVX_R1_1_A(); break; } case 0xF4: { Opcode_F4_CPL_A(); break; } case 0xF5: { Opcode_F5_MOV_Direct_A(); break; } case 0xF6: { Opcode_F6_MOV_R0_1_A(); break; } case 0xF7: { Opcode_F7_MOV_R1_1_A(); break; } case 0xF8: { Opcode_F8_MOV_R0_A(); break; } case 0xF9: { Opcode_F9_MOV_R1_A(); break; } case 0xFA: { Opcode_FA_MOV_R2_A(); break; } case 0xFB: { Opcode_FB_MOV_R3_A(); break; } case 0xFC: { Opcode_FC_MOV_R4_A(); break; } case 0xFD: { Opcode_FD_MOV_R5_A(); break; } case 0xFE: { Opcode_FE_MOV_R6_A(); break; } case 0xFF: { Opcode_FF_MOV_R7_A(); break; } default: // assert(0); break; } } bool CVm8051::GetBitFlag(INT8U addr) { return (GetBitRamRef(addr) & (BIT0 << (addr % 8))) != 0; } void CVm8051::SetBitFlag(INT8U addr) { GetBitRamRef(addr) |= (BIT0 << (addr % 8)); if (addr >= 0xe0 && addr <= 0xe7) { Updata_A_P_Flag(); } } void CVm8051::ClrBitFlag(INT8U addr) { GetBitRamRef(addr) &= (~(BIT0 << (addr % 8))); if (addr >= 0xe0 && addr <= 0xe7) { Updata_A_P_Flag(); } } INT8U CVm8051::GetOpcode(void) const { return m_ExeFile[Sys.PC]; } INT8U& CVm8051::GetRamRef(INT8U addr) { if (addr > 0x7F) { return m_ChipSfr[addr]; } else { return m_ChipRam[addr]; } } INT16U CVm8051::GetDebugOpcode(void) const { INT16U temp = 0; memcpy(&temp, &m_ExeFile[Sys.PC], 2); return temp; } bool CVm8051::GetDebugPC(INT16U pc) const { return (pc == Sys.PC); } void CVm8051::GetOpcodeData(void * const p, INT8U len) const { memcpy(p, &m_ExeFile[Sys.PC + 1], len); } void CVm8051::AJMP(INT8U opCode, INT8U data) { INT16U tmppc = Sys.PC + 2; tmppc &= 0xF800; tmppc |= ((((((INT16U) opCode) >> 5) & 0x7) << 8) | ((INT16U) data)); Sys.PC = tmppc; } void CVm8051::ACALL(INT8U opCode) { INT8U data = Get1Opcode(); Sys.PC += 2; Sys.sp = Sys.sp() + 1; SetRamDataAt(Sys.sp(), (INT8U) (Sys.PC & 0x00ff)); Sys.sp = Sys.sp() + 1; SetRamDataAt(Sys.sp(), (INT8U) (Sys.PC >> 8)); Sys.PC = ((Sys.PC & 0xF800) | (((((INT16U) opCode) >> 5) << 8) | (INT16U) data)); } void CVm8051::UpDataDebugInfo(void) { d_Rges.R0 = Rges.R0(); d_Rges.R1 = Rges.R1(); d_Rges.R2 = Rges.R2(); d_Rges.R3 = Rges.R3(); d_Rges.R4 = Rges.R4(); d_Rges.R5 = Rges.R5(); d_Rges.R6 = Rges.R6(); d_Rges.R7 = Rges.R7(); d_Sys.a = Sys.a(); d_Sys.b = Sys.b(); d_Sys.sp = Sys.sp(); d_Sys.dptr = Sys.dptr(); d_Sys.psw = Sys.psw(); d_Sys.PC = Sys.PC; } void * CVm8051::GetExRamAddr(INT16U addr) const { // Assert(addr < sizeof(m_ExRam)); return (void *) &m_ExRam[addr]; } INT8U CVm8051::GetExRam(INT16U addr) const { // Assert(addr < sizeof(m_ExRam)); return m_ExRam[addr]; } INT8U CVm8051::SetExRam(INT16U addr, INT8U data) { // Assert(addr < sizeof(m_ExRam)); return m_ExRam[addr] = data; } void * CVm8051::GetPointRamAddr(INT16U addr) const { // Assert(addr < sizeof(m_ChipRam)); return (void *) &m_ChipRam[addr]; } INT8U CVm8051::GetRamDataAt(INT8U addr) { return m_ChipRam[addr]; } INT8U CVm8051::SetRamDataAt(INT8U addr, INT8U data) { return m_ChipRam[addr] = data; } INT8U CVm8051::GetRamData(INT8U addr) { return GetRamRef(addr); } INT8U CVm8051::SetRamData(INT8U addr, INT8U data) { GetRamRef(addr) = data; return data; } void* CVm8051::GetPointFileAddr(INT16U addr) const { Assert(addr < sizeof(m_ExeFile)); return (void*) &m_ExeFile[addr]; } void CVm8051::Opcode_02_LJMP_Addr16(void) { INT8U temp[2]; INT16U data; GetOpcodeData(temp, 2); data = (((INT16U) (temp[0])) << 8); Sys.PC = data | temp[1]; } void CVm8051::Opcode_03_RR_A(void) { INT8U temp = (Sys.a() & 0x1); Sys.a = Sys.a() >> 1; Sys.a = Sys.a() | (temp << 7); ++Sys.PC; } void CVm8051::Opcode_05_INC_Direct(void) { INT8U temp = 0; INT8U addr = Get1Opcode(); temp = GetRamData(addr); ++temp; SetRamData(addr, temp); Sys.PC = Sys.PC + 2; } void CVm8051::Opcode_06_INC_R0_1(void) { INT8U data = 0; INT8U addr = Rges.R0(); data = GetRamDataAt(addr); ++data; SetRamDataAt(addr, data); ++Sys.PC; } void CVm8051::Opcode_07_INC_R1_1(void) { INT8U data = 0; INT8U addr = Rges.R1(); data = GetRamDataAt(addr); ++data; SetRamDataAt(addr, data); ++Sys.PC; } void CVm8051::Opcode_10_JBC_Bit_Rel(void) { INT8U temp[2]; char tem2; GetOpcodeData(&temp[0], sizeof(temp)); Sys.PC += 3; // Assert(temp[0]<=0xF7); // if (temp[0] <= 0x7F) { if (GetBitFlag((temp[0]))) { ClrBitFlag(temp[0]); memcpy(&tem2, &temp[1], sizeof(temp[1])); Sys.PC += tem2; } } INT16U CVm8051::GetLcallAddr(void) { INT16U addr = 0; GetOpcodeData((INT8U*) &addr, 2); Assert(GetOpcode() == 0x12); return (addr >> 8) | (addr << 8); } void CVm8051::Opcode_12_LCALL_Addr16(void) { // INT8U temp = 0; INT16U addr = 0; // void *p = NULL; GetOpcodeData((INT8U*) &addr, 2); Sys.PC += 3; Sys.sp = Sys.sp() + 1; SetRamDataAt(Sys.sp(), (INT8U) (Sys.PC & 0x00ff)); Sys.sp = Sys.sp() + 1; SetRamDataAt(Sys.sp(), (INT8U) (Sys.PC >> 8)); // GetOpcodeData(&Sys.PC,2); Sys.PC = (addr >> 8) | (addr << 8); } void CVm8051::Opcode_13_RRC_A(void) { INT8U temp = Sys.a() & BIT0; Sys.a = ((Sys.a() >> 1) | (Sys.psw().cy << 7)); Sys.psw().cy = (temp == 0) ? 0 : 1; ++Sys.PC; } void CVm8051::Opcode_14_DEC_A(void) { Sys.a = Sys.a() - 1; ++Sys.PC; } void CVm8051::Opcode_15_DEC_Direct(void) { INT8U temp = 0; INT8U addr = Get1Opcode(); temp = GetRamData(addr); --temp; SetRamData(addr, temp); Sys.PC = Sys.PC + 2; } void CVm8051::Opcode_16_DEC_R0_1(void) { INT8U temp = 0; INT8U addr = Rges.R0(); temp = GetRamDataAt(addr); --temp; SetRamDataAt(addr, temp); ++Sys.PC; } void CVm8051::Opcode_17_DEC_R1_1(void) { INT8U temp = 0; INT8U addr = Rges.R1(); temp = GetRamDataAt(addr); temp--; SetRamDataAt(addr, temp); ++Sys.PC; } void CVm8051::Opcode_20_JB_Bit_Rel(void) { INT8U temp[2]; GetOpcodeData(&temp[0], sizeof(temp)); Sys.PC += 3; if (GetBitFlag((temp[0]))) { char tem2; memcpy(&tem2, &temp[1], sizeof(temp[1])); Sys.PC += tem2; // Sys.PC = GetTargPC(temp[1]); } } void CVm8051::Opcode_22_RET(void) { INT8U temp = 0; temp = GetRamDataAt(Sys.sp()); Sys.PC = (Sys.PC & 0x00FF) | (((INT16U) temp) << 8); Sys.sp = Sys.sp() - 1; temp = GetRamDataAt(Sys.sp()); Sys.PC = (Sys.PC & 0xFF00) | temp; Sys.sp = Sys.sp() - 1; } void CVm8051::Opcode_23_RL_A(void) { INT8U temp = Sys.a() & 0x80; INT8U tem2 = Sys.a(); Sys.a = (INT8U) ((tem2 << 1) | (temp >> 7)); ++Sys.PC; } void CVm8051::MD_ADDC(INT8U data) { INT8U flagAC = Sys.psw().cy; if (flagAC > 1) { // assert(0); flagAC = 1; } INT16U tep = (INT16U) Sys.a() + (INT16U) data + flagAC; INT16U tep2 = ((INT16U) (Sys.a() & 0x7F) + (INT16U) (data & 0x7F)) + flagAC; if ((Sys.a() & 0x0f) + (data & 0x0f) + flagAC > 0x0F) { Sys.psw().ac = 1; } else { Sys.psw().ac = 0; } if (tep > 0xFF) { Sys.psw().cy = 1; } else { Sys.psw().cy = 0; } flagAC = 0; if (tep > 0xFF) { flagAC++; } if (tep2 > 0x7F) { flagAC++; } Sys.psw().ov = flagAC == 1 ? 1 : 0; Sys.a = (INT8U) tep; } void CVm8051::MD_SUBB(INT8U data) { INT16U tepa = Sys.a(); INT8U bcy = Sys.psw().cy; // data += Sys.psw().cy; if ((tepa & 0x0f) < (data & 0x0f) + Sys.psw().cy) { Sys.psw().ac = 1; } else { Sys.psw().ac = 0; } if (tepa < data + bcy) { Sys.psw().cy = 1; } else { Sys.psw().cy = 0; } INT8U flagac = 0; if (tepa < data + bcy) { flagac++; } if ((tepa & 0x7F) < (data & 0x7F) + bcy) { flagac++; } Sys.psw().ov = flagac == 1 ? 1 : 0; Sys.a = (INT8U) (tepa - data - bcy); } void CVm8051::MD_ADD(INT8U data) { INT16U tep = (INT16U) Sys.a() + (INT16U) data; INT16U tep2 = ((INT16U) (Sys.a() & 0x7F) + (INT16U) (data & 0x7F)); if ((Sys.a() & 0x0f) + (data & 0x0f) > 0x0F) { Sys.psw().ac = 1; } else { Sys.psw().ac = 0; } if (tep > 0xFF) { Sys.psw().cy = 1; } else { Sys.psw().cy = 0; } INT8U flagAC = 0; if (tep > 0xFF) { flagAC++; } if (tep2 > 0x7F) { flagAC++; } Sys.psw().ov = flagAC == 1 ? 1 : 0; Sys.a = (INT8U) tep; } void CVm8051::Opcode_30_JNB_Bit_Rel(void) { INT8U temp[2]; GetOpcodeData(&temp[0], sizeof(temp)); // Assert(temp[0]<0xF7); Sys.PC += 3; if (!GetBitFlag((temp[0]))) { char tem2; memcpy(&tem2, &temp[1], sizeof(temp[1])); Sys.PC += tem2; // Sys.PC = GetTargPC(temp[1]); } } void CVm8051::Opcode_32_RETI(void) { INT8U temp = 0; temp = GetRamData(Sys.sp()); Sys.PC = (Sys.PC & 0x00FF) | (((INT16U) temp) << 8); Sys.sp = Sys.sp() - 1; temp = GetRamData(Sys.sp()); Sys.PC = (Sys.PC & 0xFF00) | temp; Sys.sp = Sys.sp() - 1; ++Sys.PC; } void CVm8051::Opcode_33_RLC_A(void) { INT8U temp = Sys.a() & 0x80; Sys.a = ((Sys.a() << 1) | Sys.psw().cy); Sys.psw().cy = temp == 0 ? 0 : 1; ++Sys.PC; } void CVm8051::Opcode_40_JC_Rel(void) { char tem2= Get1Opcode(); // GetOpcodeData(&tem2, 1); Sys.PC += 2; if (Sys.psw().cy) { memcpy(&tem2, &tem2, sizeof(tem2)); Sys.PC += tem2; // Sys.PC = GetTargPC(temp); } } void CVm8051::Opcode_42_ORL_Direct_A(void) { INT8U temp; INT8U addr = Get1Opcode(); temp = GetRamData(addr); temp |= Sys.a(); SetRamData(addr, temp); Sys.PC += 2; } void CVm8051::Opcode_43_ORL_Direct_Data(void) { INT8U temp[2] = { 0 }; INT8U data; // void *p = NULL; GetOpcodeData(&temp[0], 2); //direct ~{JG~}1~{8vWV=Z~} data = GetRamData(temp[0]); data |= temp[1]; // memcpy(p, &data, 1); SetRamData(temp[0], data); Sys.PC += 3; } void CVm8051::Updata_A_P_Flag(void) { INT8U a = Sys.a(); a ^= a >> 4; a ^= a >> 2; a ^= a >> 1; Sys.psw().p = (a & 1); } void CVm8051::Opcode_44_ORL_A_Data(void) { INT8U temp = Get1Opcode(); Sys.a = Sys.a() | temp; Sys.PC += 2; } void CVm8051::Opcode_45_ORL_A_Direct(void) { INT8U data; INT8U addr = Get1Opcode(); // GetOpcodeData(&addr, 1); data = GetRamData(addr); Sys.a = Sys.a() | data; Sys.PC += 2; } void CVm8051::Opcode_50_JNC_Rel(void) { char tem2 = Get1Opcode(); // GetOpcodeData(&tem2, 1); Sys.PC += 2; if (Sys.psw().cy == 0) { Sys.PC += tem2; } } void CVm8051::Opcode_52_ANL_Direct_A(void) { INT8U temp; INT8U addr =Get1Opcode(); // void *p = NULL; GetOpcodeData(&addr, 1); temp = GetRamData(addr); temp &= Sys.a(); SetRamData(addr, temp); Sys.PC += 2; } void CVm8051::Opcode_53_ANL_Direct_Data(void) { INT8U temp[2] = { 0 }; INT8U data; GetOpcodeData(&temp[0], 2); data = GetRamData(temp[0]); data &= temp[1]; SetRamData(temp[0], data); Sys.PC += 3; } void CVm8051::Opcode_60_JZ_Rel(void) { char temp= Get1Opcode(); // GetOpcodeData(&temp, 1); Sys.PC += 2; if (Sys.a() == 0) { // Sys.PC = GetTargPC(temp); Sys.PC += temp; } } void CVm8051::Opcode_62_XRL_Direct_A(void) { INT8U temp; INT8U addr = Get1Opcode(); temp = GetRamData(addr); temp ^= Sys.a(); SetRamData(addr, temp); Sys.PC += 2; } void CVm8051::Opcode_63_XRL_Direct_Data(void) { INT8U temp[2] = { 0 }; INT8U data; GetOpcodeData(&temp[0], 2); data = GetRamData(temp[0]); data ^= temp[1]; SetRamData(temp[0], data); Sys.PC += 3; } void CVm8051::Opcode_70_JNZ_Rel(void) { char temp = Get1Opcode(); Sys.PC += 2; if (Sys.a() != 0) { Sys.PC += temp; } } void CVm8051::Opcode_75_MOV_Direct_Data(void) { INT8U temp[2] = { 0 }; GetOpcodeData(&temp[0], 2); SetRamData(temp[0], temp[1]); Sys.PC += 3; } void CVm8051::Opcode_80_SJMP_Rel(void) { char temp= Get1Opcode(); Sys.PC += 2; Sys.PC += temp; } void CVm8051::Opcode_83_MOVC_A_PC(void) { // INT8U temp; INT16U addr; // void*p = NULL; ++Sys.PC; addr = (INT16U) (Sys.PC + Sys.a()); Sys.a = (Sys.PC > CVm8051::MAX_ROM - Sys.a()) ? (0x00) : (m_ExeFile[addr]); } void CVm8051::Opcode_84_DIV_AB(void) { INT8U data1, data2; data1 = Sys.a(); data2 = Sys.b(); if (data2 == 0) { Sys.psw().ov = 1; goto Ret; } Sys.a = data1 / data2; Sys.b = data1 % data2; Sys.psw().ov = 0; Ret: Sys.psw().cy = 0; ++Sys.PC; } void CVm8051::Opcode_85_MOV_Direct_Direct(void) { INT8U temp[2]; INT8U tem; GetOpcodeData(&temp[0], 2); tem = GetRamData(temp[0]); SetRamData(temp[1], tem); Sys.PC += 3; } void CVm8051::Opcode_90_MOV_DPTR_Data(void) { INT16U temp; GetOpcodeData(&temp, 2); temp = (temp >> 8) | (temp << 8); Sys.dptr = temp; Sys.PC += 3; } void CVm8051::Opcode_92_MOV_Bit_C(void) { INT8U temp = Get1Opcode(); if (Sys.psw().cy) { SetBitFlag(temp); } else { ClrBitFlag(temp); } Sys.PC += 2; } void CVm8051::Opcode_93_MOVC_A_DPTR(void) { INT8U temp; void *p = NULL; p = GetPointFileAddr((INT16U) (Sys.a() + Sys.dptr())); memcpy(&temp, p, sizeof(temp)); Sys.a = (Sys.dptr() > CVm8051::MAX_ROM - Sys.a()) ? (0x00) : (temp); ++Sys.PC; } void CVm8051::Opcode_A4_MUL_AB(void) { INT16U temp; temp = (INT16U) Sys.a() * (INT16U) Sys.b(); Sys.psw().ov = (temp > 255) ? 1 : 0; Sys.a = (INT8U) temp; Sys.b = (INT8U) (temp >> 8); ++Sys.PC; } void CVm8051::Opcode_B2_CPL_Bit(void) { INT8U temp=Get1Opcode(); if (GetBitFlag(temp)) { ClrBitFlag(temp); } else { SetBitFlag(temp); } Sys.PC += 2; } void CVm8051::Opcode_B4_CJNE_A_Data_Rel(void) { INT8U temp[2]; GetOpcodeData(&temp[0], sizeof(temp)); Sys.PC += 3; if (Sys.a() != temp[0]) { char tem; memcpy(&tem, &temp[1], 1); Sys.PC += tem; } if ((Sys.a() < temp[0])) { Sys.psw().cy = 1; } else { Sys.psw().cy = 0; } } void CVm8051::Opcode_B5_CJNE_A_Direct_Rel(void) { INT8U temp[2]; INT8U data; GetOpcodeData(&temp[0], sizeof(temp)); Sys.PC += 3; data = GetRamData(temp[0]); if (Sys.a() != data) { char tem; memcpy(&tem, &temp[1], 1); Sys.PC += tem; } Sys.psw().cy = (Sys.a() < data) ? 1 : 0; } void CVm8051::Opcode_B6_CJNE_R0_1_Data_Rel(void) { INT8U temp[2]; INT8U data; GetOpcodeData(&temp[0], sizeof(temp)); data = GetRamDataAt(Rges.R0()); Sys.PC += 3; if (data != temp[0]) { char tem; memcpy(&tem, &temp[1], 1); Sys.PC += tem; } Sys.psw().cy = (data < temp[0]) ? 1 : 0; } void CVm8051::Opcode_B7_CJNE_R1_1_Data_Rel(void) { INT8U temp[2]; INT8U data; GetOpcodeData(&temp[0], sizeof(temp)); data = GetRamDataAt(Rges.R1()); Sys.PC += 3; if (data != temp[0]) { Sys.PC += (char)temp[1]; } Sys.psw().cy = (data < temp[0]) ? 1 : 0; } void CVm8051::Opcode_B8_CJNE_R0_Data_Rel(void) { INT8U temp[2]; GetOpcodeData(&temp[0], sizeof(temp)); Sys.PC += 3; if (Rges.R0() != temp[0]) { Sys.PC += (char)temp[1]; } Sys.psw().cy = (Rges.R0() < temp[0]) ? 1 : 0; } void CVm8051::Opcode_B9_CJNE_R1_Data_Rel(void) { INT8U temp[2]; GetOpcodeData(&temp[0], sizeof(temp)); Sys.PC += 3; if (Rges.R1() != temp[0]) { Sys.PC += (char)temp[1]; } Sys.psw().cy = (Rges.R1() < temp[0]) ? 1 : 0; } void CVm8051::Opcode_BA_CJNE_R2_Data_Rel(void) { INT8U temp[2]; GetOpcodeData(&temp[0], sizeof(temp)); Sys.PC += 3; if (Rges.R2() != temp[0]) { Sys.PC += (char)temp[1]; } Sys.psw().cy = (Rges.R2() < temp[0]) ? 1 : 0; } void CVm8051::Opcode_BB_CJNE_R3_Data_Rel(void) { INT8U temp[2]; GetOpcodeData(&temp[0], sizeof(temp)); Sys.PC += 3; if (Rges.R3() != temp[0]) { Sys.PC += (char)temp[1]; } Sys.psw().cy = (Rges.R3() < temp[0]) ? 1 : 0; } void CVm8051::Opcode_BC_CJNE_R4_Data_Rel(void) { INT8U temp[2]; GetOpcodeData(&temp[0], sizeof(temp)); Sys.PC += 3; if (Rges.R4() != temp[0]) { Sys.PC += (char)temp[1]; } Sys.psw().cy = (Rges.R4() < temp[0]) ? 1 : 0; } void CVm8051::Opcode_BD_CJNE_R5_Data_Rel(void) { INT8U temp[2]; GetOpcodeData(&temp[0], sizeof(temp)); Sys.PC += 3; if (Rges.R5() != temp[0]) { Sys.PC += (char)temp[1]; } Sys.psw().cy = (Rges.R5() < temp[0]) ? 1 : 0; } void CVm8051::Opcode_BE_CJNE_R6_Data_Rel(void) { INT8U temp[2]; GetOpcodeData(&temp[0], sizeof(temp)); Sys.PC += 3; if (Rges.R6() != temp[0]) { Sys.PC += (char)temp[1]; } Sys.psw().cy = (Rges.R6() < temp[0]) ? 1 : 0; } void CVm8051::Opcode_BF_CJNE_R7_Data_Rel(void) { INT8U temp[2]; GetOpcodeData(&temp[0], sizeof(temp)); Sys.PC += 3; if (Rges.R7() != temp[0]) { Sys.PC += (char)temp[1]; } Sys.psw().cy = (Rges.R7() < temp[0]) ? 1 : 0; } void CVm8051::Opcode_C5_XCH_A_Direct(void) { INT8U addr; INT8U data; INT8U TT; GetOpcodeData(&addr, sizeof(addr)); data = GetRamData(addr); TT = Sys.a(); Sys.a = data; SetRamData(addr, TT); Sys.PC += 2; } void CVm8051::Opcode_C6_XCH_A_R0_1(void) { INT8U TT; TT = Sys.a(); Sys.a = GetRamDataAt(Rges.R0()); SetRamDataAt(Rges.R0(), TT); ++Sys.PC; } void CVm8051::Opcode_C7_XCH_A_R1_1(void) { INT8U TT; TT = Sys.a(); Sys.a = GetRamDataAt(Rges.R1()); SetRamDataAt(Rges.R1(), TT); ++Sys.PC; } void CVm8051::Opcode_C8_XCH_A_R0(void) { INT8U temp; temp = Sys.a(); Sys.a = Rges.R0(); Rges.R0 = temp; ++Sys.PC; } void CVm8051::Opcode_C9_XCH_A_R1(void) { INT8U temp; temp = Sys.a(); Sys.a = Rges.R1(); Rges.R1 = temp; ++Sys.PC; } void CVm8051::Opcode_CA_XCH_A_R2(void) { INT8U temp; temp = Sys.a(); Sys.a = Rges.R2(); Rges.R2 = temp; ++Sys.PC; } void CVm8051::Opcode_CB_XCH_A_R3(void) { INT8U temp; temp = Sys.a(); Sys.a = Rges.R3(); Rges.R3 = temp; ++Sys.PC; } void CVm8051::Opcode_CC_XCH_A_R4(void) { INT8U temp; temp = Sys.a(); Sys.a = Rges.R4(); Rges.R4 = temp; ++Sys.PC; } void CVm8051::Opcode_CD_XCH_A_R5(void) { INT8U temp; temp = Sys.a(); Sys.a = Rges.R5(); Rges.R5 = temp; ++Sys.PC; } void CVm8051::Opcode_CE_XCH_A_R6(void) { INT8U temp; temp = Sys.a(); Sys.a = Rges.R6(); Rges.R6 = temp; ++Sys.PC; } void CVm8051::Opcode_CF_XCH_A_R7(void) { INT8U temp; temp = Sys.a(); Sys.a = Rges.R7(); Rges.R7 = temp; ++Sys.PC; } void CVm8051::Opcode_D0_POP_Direct(void) { SetRamData(Get1Opcode(), GetRamDataAt(Sys.sp())); Sys.sp = Sys.sp() - 1; Sys.PC += 2; } void CVm8051::Opcode_D4_DA_A(void) { INT8U temp; if (((Sys.a() & 0x0f) > 9) || (Sys.psw().ac == 1)) { temp = ((Sys.a() & 0x0f) + 6) % 16; Sys.a = Sys.a() & 0xF0; Sys.a = Sys.a() | temp; } temp = ((Sys.a() & 0xF0) >> 4); if ((temp > 9) || (Sys.psw().cy == 1)) { temp = (temp + 6) % 16; Sys.a = Sys.a() & 0x0F; Sys.a = Sys.a() | (temp << 4); } ++Sys.PC; } void CVm8051::Opcode_D5_DJNZ_Direct_Rel(void) { INT8U temp[2]; INT8U data; GetOpcodeData(&temp[0], sizeof(temp)); data = GetRamData(temp[0]); data--; SetRamData(temp[0], data); Sys.PC += 3; if (data != 0) { char tem; memcpy(&tem, &temp[1], 1); Sys.PC += tem; } } void CVm8051::Opcode_D6_XCHD_A_R0_1(void) { INT8U temp = 0; INT8U data = GetRamDataAt(Rges.R0()); temp = Sys.a() & 0x0F; Sys.a = Sys.a() & 0xF0; Sys.a = Sys.a() | (data & 0x0F); data &= 0xF0; data |= temp; SetRamDataAt(Rges.R0(), data); ++Sys.PC; } void CVm8051::Opcode_D7_XCHD_A_R1_1(void) { INT8U temp = 0; INT8U data; data = GetRamDataAt(Rges.R1()); temp = Sys.a() & 0x0F; Sys.a = Sys.a() & 0xF0; Sys.a = Sys.a() | (data & 0x0F); data &= 0xF0; data |= temp; SetRamDataAt(Rges.R1(), data); ++Sys.PC; } void CVm8051::Opcode_D8_DJNZ_R0_Rel(void) { char temp = Get1Opcode(); Sys.PC += 2; Rges.R0 = Rges.R0() - 1; if (Rges.R0() != 0) { Sys.PC += temp; } } void CVm8051::Opcode_D9_DJNZ_R1_Rel(void) { char temp = Get1Opcode(); Sys.PC += 2; Rges.R1 = Rges.R1() - 1; if (Rges.R1() != 0) { Sys.PC += temp; } } void CVm8051::Opcode_DA_DJNZ_R2_Rel(void) { char temp = Get1Opcode(); Sys.PC += 2; Rges.R2 = Rges.R2() - 1; if (Rges.R2() != 0) { Sys.PC += temp; } } void CVm8051::Opcode_DB_DJNZ_R3_Rel(void) { char temp = Get1Opcode(); Sys.PC += 2; Rges.R3 = Rges.R3() - 1; if (Rges.R3() != 0) { Sys.PC += temp; } } void CVm8051::Opcode_DC_DJNZ_R4_Rel(void) { char temp = Get1Opcode(); Sys.PC += 2; Rges.R4 = Rges.R4() - 1; if (Rges.R4() != 0) { Sys.PC += temp; } } void CVm8051::Opcode_DD_DJNZ_R5_Rel(void) { char temp = Get1Opcode(); Sys.PC += 2; Rges.R5 = Rges.R5() - 1; if (Rges.R5() != 0) { Sys.PC += temp; } } void CVm8051::Opcode_DE_DJNZ_R6_Rel(void) { char temp = Get1Opcode(); Sys.PC += 2; Rges.R6 = Rges.R6() - 1; if (Rges.R6() != 0) { Sys.PC += temp; } } void CVm8051::Opcode_DF_DJNZ_R7_Rel(void) { char temp = Get1Opcode(); Sys.PC += 2; Rges.R7 = Rges.R7() - 1; if (Rges.R7() != 0) { Sys.PC += temp; } } void CVm8051::Opcode_E0_MOVX_A_DPTR(void) { Sys.a = m_ExRam[Sys.dptr()]; ++Sys.PC; } shared_ptr<vector<unsigned char>> CVm8051::GetRetData(void) const { auto tem = std::make_shared<vector<unsigned char>>(); char buffer[1024] = { 0 }; memcpy(buffer, &m_ExRam[0xFC00], 1023); tem.get()->assign(buffer, buffer + 1023); return tem; } template<class T2> T2& CUPReg<T2>::GetRegRe(void) { assert(m_Addr != 255); return *((T2*) (&pmcu->m_ChipRam[m_Addr])); } INT8U& CUPReg_a::GetRegRe(void) { assert(m_Addr != 255); return pmcu->m_ChipSfr[m_Addr]; } INT8U& CUPSfr::GetRegRe(void) { assert(m_Addr != 255); return pmcu->m_ChipSfr[m_Addr]; } INT16U& CUPSfr16::GetRegRe(void) { assert(m_Addr != 255); return *((INT16U*) &pmcu->m_ChipSfr[m_Addr]); } template<class T2> T2 CUPReg<T2>::getValue() { return GetRegRe(); } void CUPReg_a::Updataflag() { pmcu->Updata_A_P_Flag(); } PSW& CUPPSW_8::operator()(void) { return *((PSW*) &(GetRegRe())); }
22.138304
117
0.639098
c3debfa947362fdc46cb23f328eb5e9f0e5ce3cf
3,561
cpp
C++
src/CoordinateAxes.cpp
sosswald/gpu-coverage
da36062272244573abd938996d8cb6ecd25a55e7
[ "BSD-3-Clause" ]
2
2018-09-17T15:21:06.000Z
2020-03-27T11:57:04.000Z
src/CoordinateAxes.cpp
sosswald/gpu-coverage
da36062272244573abd938996d8cb6ecd25a55e7
[ "BSD-3-Clause" ]
null
null
null
src/CoordinateAxes.cpp
sosswald/gpu-coverage
da36062272244573abd938996d8cb6ecd25a55e7
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2018, Stefan Osswald * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <gpu_coverage/CoordinateAxes.h> #include <gpu_coverage/Mesh.h> #include GLEXT_INCLUDE #ifndef GLM_FORCE_RADIANS #define GLM_FORCE_RADIANS true #endif #include <glm/gtc/type_ptr.hpp> namespace gpu_coverage { CoordinateAxes::CoordinateAxes() : modelMatrix(glm::mat4()) { const float points[] = { -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f }; const float colors[] = { 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f }; const unsigned int indices[] = { 0, 1, 2, 3, 4, 5 }; glGenBuffers(3, vbo); enum { POINTS = 0, COLORS = 1, INDICES = 2 }; vao = 0; glGenVertexArrays(1, &vao); glBindVertexArray(vao); glBindBuffer(GL_ARRAY_BUFFER, vbo[POINTS]); glBufferData(GL_ARRAY_BUFFER, sizeof(points), points, GL_STATIC_DRAW); glVertexAttribPointer(Mesh::VERTEX_BUFFER, 3, GL_FLOAT, GL_FALSE, 0, NULL); glEnableVertexAttribArray(Mesh::VERTEX_BUFFER); glBindBuffer(GL_ARRAY_BUFFER, vbo[COLORS]); glBufferData(GL_ARRAY_BUFFER, sizeof(colors), colors, GL_STATIC_DRAW); glVertexAttribPointer(Mesh::COLOR_BUFFER, 3, GL_FLOAT, GL_FALSE, 0, NULL); glEnableVertexAttribArray(Mesh::COLOR_BUFFER); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo[INDICES]); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(vbo[INDICES]), indices, GL_STATIC_DRAW); glVertexAttribPointer(Mesh::INDEX_BUFFER, 1, GL_UNSIGNED_INT, GL_FALSE, 0, NULL); glEnableVertexAttribArray(Mesh::INDEX_BUFFER); } CoordinateAxes::~CoordinateAxes() { glDeleteVertexArrays(1, &vao); glDeleteBuffers(3, vbo); } void CoordinateAxes::display() const { glBindVertexArray(vao); glDrawArrays(GL_LINES, 0, 6); } } /* namespace gpu_coverage */
35.969697
89
0.693906
c3e22d21312e99e2f44ae8bab67b83bd52ad148d
4,403
cpp
C++
plugin/plugin_guide/snippets/dicom_menus/milxQtDICOMPlugin.cpp
aneube/smili-spine
3cd8f95077d4bc1f5ac6146bc5356c3131f22e4b
[ "BSD-2-Clause" ]
17
2015-03-09T19:22:07.000Z
2021-05-24T20:25:08.000Z
plugin/plugin_guide/snippets/dicom_menus/milxQtDICOMPlugin.cpp
aneube/smili-spine
3cd8f95077d4bc1f5ac6146bc5356c3131f22e4b
[ "BSD-2-Clause" ]
16
2015-08-20T03:30:15.000Z
2019-10-22T12:21:14.000Z
plugin/plugin_guide/snippets/dicom_menus/milxQtDICOMPlugin.cpp
aneube/smili-spine
3cd8f95077d4bc1f5ac6146bc5356c3131f22e4b
[ "BSD-2-Clause" ]
11
2015-06-22T00:11:01.000Z
2021-12-26T21:29:52.000Z
#include "milxQtDICOMPlugin.h" #include <qplugin.h> milxQtDICOMPlugin::milxQtDICOMPlugin(QObject *theParent) : milxQtPluginInterface(theParent) { ///Up cast parent to milxQtMain MainWindow = qobject_cast<milxQtMain *>(theParent); //~ threaded = false; //~ dockable = false; //~ consoleWindow = false; //~ extension = true; pluginName = "DICOM"; //~ dataName = ""; createActions(); createMenu(); createConnections(); } milxQtDICOMPlugin::~milxQtDICOMPlugin() { if(isRunning() && threaded) quit(); cout << "DICOM Plugin Destroyed." << endl; } QString milxQtDICOMPlugin::name() { return pluginName; } QString milxQtDICOMPlugin::openFileSupport() { QString openPythonExt = ""; return openPythonExt; } QStringList milxQtDICOMPlugin::openExtensions() { QStringList exts; return exts; } QStringList milxQtDICOMPlugin::saveExtensions() { QStringList exts; return exts; } QString milxQtDICOMPlugin::saveFileSupport() { QString savePythonExt = ""; return savePythonExt; } void milxQtDICOMPlugin::SetInputCollection(vtkPolyDataCollection* collection, QStringList &filenames) { } void milxQtDICOMPlugin::open(QString filename) { } void milxQtDICOMPlugin::save(QString filename) { } milxQtRenderWindow* milxQtDICOMPlugin::genericResult() { return NULL; } //No image result milxQtModel* milxQtDICOMPlugin::modelResult() { //~ denoiseModel = new milxQtDICOMModel; return NULL; //~ return denoiseModel; } //No image result milxQtImage* milxQtDICOMPlugin::imageResult() { return NULL; } //No image result QDockWidget* milxQtDICOMPlugin::dockWidget() { return NULL; } //No Dock result bool milxQtDICOMPlugin::isPluginWindow(QWidget *window) { //~ if(pluginWindow(window) == 0) return false; //~ else //~ return true; } //~ milxQtDeNoiseModel* milxQtDeNoisePlugin::pluginWindow(QWidget *window) //~ { //~ if(window) //~ return qobject_cast<milxQtDeNoiseModel *>(window); //~ return 0; //~ } void milxQtDICOMPlugin::loadExtension() { //~ if(!MainWindow->isActiveModel()) //~ return; //~ milxQtModel *currentWin = MainWindow->activeModel(); //~ milxQtDeNoiseModel *denoiseModel = new milxQtDeNoiseModel(MainWindow); //hierarchical deletion //~ denoiseModel->setName(currentWin->getName()); //~ denoiseModel->SetInput(currentWin->GetOutput()); //~ denoiseModel->generateModel(); //~ MainWindow->display(denoiseModel); } //~ void milxQtDICOMPlugin::run() //~ { //~ QMutexLocker locker(&mutex); //Lock memory //~ ///Execute own thread work here //~ //exec(); //~ } //~ void milxQtDICOMPlugin::createConnections() //~ { //~ //QObject::connect(denoiseAct, SIGNAL(triggered(bool)), denoiseModel, SLOT(denoise())); //~ } void milxQtDICOMPlugin::convert() { cout << "Converting DICOMs" << endl; } void milxQtDICOMPlugin::anonymize() { cout << "Anonymizing DICOMs" << endl; } void milxQtDICOMPlugin::createActions() { actionConvert = new QAction(MainWindow); actionConvert->setText(QApplication::translate("DICOMPlugin", "Convert ...", 0, QApplication::UnicodeUTF8)); actionConvert->setShortcut(tr("Ctrl+Alt+c")); actionAnonymize = new QAction(MainWindow); actionAnonymize->setText(QApplication::translate("DICOMPlugin", "Anonymize ...", 0, QApplication::UnicodeUTF8)); actionAnonymize->setShortcut(tr("Ctrl+Alt+a")); } void milxQtDICOMPlugin::createMenu() { menuDICOM = new QMenu(MainWindow); menuDICOM->setTitle(QApplication::translate("DICOMPlugin", "DICOM", 0, QApplication::UnicodeUTF8)); menuDICOM->addAction(actionConvert); menuDICOM->addAction(actionAnonymize); menuToAdd.append(menuDICOM); } void milxQtDICOMPlugin::createConnections() { // connect(MainWindow, SIGNAL(windowActivated(QWidget*)), this, SLOT(updateManager(QWidget*))); connect(actionConvert, SIGNAL(activated()), this, SLOT(convert())); connect(actionAnonymize, SIGNAL(activated()), this, SLOT(anonymize())); // connect(btnAtlasName, SIGNAL(clicked()), this, SLOT(showAtlasFileDialog())); // connect(btnSurfaceNames, SIGNAL(clicked()), this, SLOT(showSurfacesFileDialog())); // connect(btnClearSurfaceNames, SIGNAL(clicked()), comboSurfaceNames, SLOT(clear())); } Q_EXPORT_PLUGIN2(DICOMPlugin, milxQtDICOMPluginFactory);
23.8
116
0.691801
c3e4981b41e0c9b7d965a3bbdabb4985ca86dbe3
548
cpp
C++
excercise_book/task_1_1/main.cpp
bartekpacia/cpp-training
ec0b6c3ca4d2590e05df647d597ced94fed922af
[ "MIT" ]
null
null
null
excercise_book/task_1_1/main.cpp
bartekpacia/cpp-training
ec0b6c3ca4d2590e05df647d597ced94fed922af
[ "MIT" ]
null
null
null
excercise_book/task_1_1/main.cpp
bartekpacia/cpp-training
ec0b6c3ca4d2590e05df647d597ced94fed922af
[ "MIT" ]
null
null
null
/** * Task 1.1 * Write a program calculating area of the rectangle. The * values of sides a and b are float, so is the area. Display * the result with precision of two decimal places. **/ #include <iomanip> #include <iostream> using namespace std; int main() { float a, b, area; cout << "Enter side a" << endl; cin >> a; cout << "Enter side b" << endl; cin >> b; cout << fixed; cout << setprecision(2); area = a * b; cout << "Area of this rectangle is " << area << endl; getchar(); return 0; }
19.571429
61
0.587591
c3ef135143b457c16bc80960ba3b059435f2efb5
6,127
cpp
C++
src/burner/win32/memcard.cpp
tt-arcade/fba-pi
10407847a98f0d315b05e44f0ecf01824f4558aa
[ "Apache-2.0" ]
null
null
null
src/burner/win32/memcard.cpp
tt-arcade/fba-pi
10407847a98f0d315b05e44f0ecf01824f4558aa
[ "Apache-2.0" ]
null
null
null
src/burner/win32/memcard.cpp
tt-arcade/fba-pi
10407847a98f0d315b05e44f0ecf01824f4558aa
[ "Apache-2.0" ]
null
null
null
// Memory card support module #include "burner.h" static TCHAR szMemoryCardFile[MAX_PATH]; int nMemoryCardStatus = 0; int nMemoryCardSize; static int nMinVersion; static bool bMemCardFC1Format; static int MakeOfn() { memset(&ofn, 0, sizeof(ofn)); ofn.lStructSize = sizeof(ofn); ofn.hwndOwner = hScrnWnd; ofn.lpstrFile = szMemoryCardFile; ofn.nMaxFile = sizeof(szMemoryCardFile); ofn.lpstrInitialDir = _T("."); ofn.Flags = OFN_NOCHANGEDIR | OFN_HIDEREADONLY; ofn.lpstrDefExt = _T("fc"); return 0; } static int MemCardRead(TCHAR* szFilename, unsigned char* pData, int nSize) { const char* szHeader = "FB1 FC1 "; // File + chunk identifier char szReadHeader[8] = ""; bMemCardFC1Format = false; FILE* fp = _tfopen(szFilename, _T("rb")); if (fp == NULL) { return 1; } fread(szReadHeader, 1, 8, fp); // Read identifiers if (memcmp(szReadHeader, szHeader, 8) == 0) { // FB Alpha memory card file int nChunkSize = 0; int nVersion = 0; bMemCardFC1Format = true; fread(&nChunkSize, 1, 4, fp); // Read chunk size if (nSize < nChunkSize - 32) { fclose(fp); return 1; } fread(&nVersion, 1, 4, fp); // Read version if (nVersion < nMinVersion) { fclose(fp); return 1; } fread(&nVersion, 1, 4, fp); #if 0 if (nVersion < nBurnVer) { fclose(fp); return 1; } #endif fseek(fp, 0x0C, SEEK_CUR); // Move file pointer to the start of the data block fread(pData, 1, nChunkSize - 32, fp); // Read the data } else { // MAME or old FB Alpha memory card file unsigned char* pTemp = (unsigned char*)malloc(nSize >> 1); memset(pData, 0, nSize); fseek(fp, 0x00, SEEK_SET); if (pTemp) { fread(pTemp, 1, nSize >> 1, fp); for (int i = 1; i < nSize; i += 2) { pData[i] = pTemp[i >> 1]; } free(pTemp); pTemp = NULL; } } fclose(fp); return 0; } static int MemCardWrite(TCHAR* szFilename, unsigned char* pData, int nSize) { FILE* fp = _tfopen(szFilename, _T("wb")); if (fp == NULL) { return 1; } if (bMemCardFC1Format) { // FB Alpha memory card file const char* szFileHeader = "FB1 "; // File identifier const char* szChunkHeader = "FC1 "; // Chunk identifier const int nZero = 0; int nChunkSize = nSize + 32; fwrite(szFileHeader, 1, 4, fp); fwrite(szChunkHeader, 1, 4, fp); fwrite(&nChunkSize, 1, 4, fp); // Chunk size fwrite(&nBurnVer, 1, 4, fp); // Version of FBA this was saved from fwrite(&nMinVersion, 1, 4, fp); // Min version of FBA data will work with fwrite(&nZero, 1, 4, fp); // Reserved fwrite(&nZero, 1, 4, fp); // fwrite(&nZero, 1, 4, fp); // fwrite(pData, 1, nSize, fp); } else { // MAME or old FB Alpha memory card file unsigned char* pTemp = (unsigned char*)malloc(nSize >> 1); if (pTemp) { for (int i = 1; i < nSize; i += 2) { pTemp[i >> 1] = pData[i]; } fwrite(pTemp, 1, nSize >> 1, fp); free(pTemp); pTemp = NULL; } } fclose(fp); return 0; } static int __cdecl MemCardDoGetSize(struct BurnArea* pba) { nMemoryCardSize = pba->nLen; return 0; } static int MemCardGetSize() { BurnAcb = MemCardDoGetSize; BurnAreaScan(ACB_MEMCARD, &nMinVersion); return 0; } int MemCardCreate() { TCHAR szFilter[1024]; int nRet; _stprintf(szFilter, FBALoadStringEx(hAppInst, IDS_DISK_FILE_CARD, true), _T(APP_TITLE)); memcpy(szFilter + _tcslen(szFilter), _T(" (*.fc)\0*.fc\0\0"), 14 * sizeof(TCHAR)); _stprintf (szMemoryCardFile, _T("memorycard")); MakeOfn(); ofn.lpstrTitle = FBALoadStringEx(hAppInst, IDS_MEMCARD_CREATE, true); ofn.lpstrFilter = szFilter; ofn.Flags |= OFN_OVERWRITEPROMPT; int bOldPause = bRunPause; bRunPause = 1; nRet = GetSaveFileName(&ofn); bRunPause = bOldPause; if (nRet == 0) { return 1; } { unsigned char* pCard; MemCardGetSize(); pCard = (unsigned char*)malloc(nMemoryCardSize); memset(pCard, 0, nMemoryCardSize); bMemCardFC1Format = true; if (MemCardWrite(szMemoryCardFile, pCard, nMemoryCardSize)) { return 1; } if (pCard) { free(pCard); pCard = NULL; } } nMemoryCardStatus = 1; MenuEnableItems(); return 0; } int MemCardSelect() { TCHAR szFilter[1024]; TCHAR* pszTemp = szFilter; int nRet; pszTemp += _stprintf(pszTemp, FBALoadStringEx(hAppInst, IDS_DISK_ALL_CARD, true)); memcpy(pszTemp, _T(" (*.fc, MEMCARD.\?\?\?)\0*.fc;MEMCARD.\?\?\?\0"), 38 * sizeof(TCHAR)); pszTemp += 38; pszTemp += _stprintf(pszTemp, FBALoadStringEx(hAppInst, IDS_DISK_FILE_CARD, true), _T(APP_TITLE)); memcpy(pszTemp, _T(" (*.fc)\0*.fc\0"), 13 * sizeof(TCHAR)); pszTemp += 13; pszTemp += _stprintf(pszTemp, FBALoadStringEx(hAppInst, IDS_DISK_FILE_CARD, true), _T("MAME")); memcpy(pszTemp, _T(" (MEMCARD.\?\?\?)\0MEMCARD.\?\?\?\0\0"), 28 * sizeof(TCHAR)); MakeOfn(); ofn.lpstrTitle = FBALoadStringEx(hAppInst, IDS_MEMCARD_SELECT, true); ofn.lpstrFilter = szFilter; int bOldPause = bRunPause; bRunPause = 1; nRet = GetOpenFileName(&ofn); bRunPause = bOldPause; if (nRet == 0) { return 1; } MemCardGetSize(); if (nMemoryCardSize <= 0) { return 1; } nMemoryCardStatus = 1; MenuEnableItems(); return 0; } static int __cdecl MemCardDoInsert(struct BurnArea* pba) { if (MemCardRead(szMemoryCardFile, (unsigned char*)pba->Data, pba->nLen)) { return 1; } nMemoryCardStatus |= 2; MenuEnableItems(); return 0; } int MemCardInsert() { if ((nMemoryCardStatus & 1) && (nMemoryCardStatus & 2) == 0) { BurnAcb = MemCardDoInsert; BurnAreaScan(ACB_WRITE | ACB_MEMCARD, &nMinVersion); } return 0; } static int __cdecl MemCardDoEject(struct BurnArea* pba) { if (MemCardWrite(szMemoryCardFile, (unsigned char*)pba->Data, pba->nLen) == 0) { nMemoryCardStatus &= ~2; MenuEnableItems(); return 0; } return 1; } int MemCardEject() { if ((nMemoryCardStatus & 1) && (nMemoryCardStatus & 2)) { BurnAcb = MemCardDoEject; nMinVersion = 0; BurnAreaScan(ACB_READ | ACB_MEMCARD, &nMinVersion); } return 0; } int MemCardToggle() { if (nMemoryCardStatus & 1) { if (nMemoryCardStatus & 2) { return MemCardEject(); } else { return MemCardInsert(); } } return 1; }
19.764516
99
0.651053
c3f115478d76be5a926b96e26b94ac3fae57330a
1,027
cpp
C++
Dataset/Leetcode/train/13/208.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/Leetcode/train/13/208.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/Leetcode/train/13/208.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
class Solution { public: int XXX(string s) { if(s.find("IV")!=s.npos) s = s.replace(s.find("IV"),2,"a"); if (s.find("IX") != s.npos) s = s.replace(s.find("IX"), 2, "b"); if (s.find("XL") != s.npos) s = s.replace(s.find("XL"), 2, "c"); if (s.find("XC") != s.npos) s = s.replace(s.find("XC"), 2, "d"); if (s.find("CD") != s.npos) s = s.replace(s.find("CD"), 2, "e"); if (s.find("CM") != s.npos) s = s.replace(s.find("CM"), 2, "f"); int ans = 0; for (int i = 0; i < s.size(); i++) { switch (s[i]) { case 'I': ans += 1; break; case 'V': ans += 5; break; case 'X': ans += 10; break; case 'L': ans += 50; break; case 'C': ans += 100; break; case 'D': ans += 500; break; case 'M': ans += 1000; break; case 'a': ans += 4; break; case 'b': ans += 9; break; case 'c': ans += 40; break; case 'd': ans += 90; break; case 'e': ans += 400; break; case 'f': ans += 900; break; } } return ans; } };
16.046875
38
0.447907
c3f73f9cba29aeb9b9bb27693805d0b332995276
2,933
hpp
C++
include/jbr/reg/var/perm/Rights.hpp
j-bruel/Register
4fa991ed86fedb3883514031e51dc62057d0abd0
[ "MIT" ]
null
null
null
include/jbr/reg/var/perm/Rights.hpp
j-bruel/Register
4fa991ed86fedb3883514031e51dc62057d0abd0
[ "MIT" ]
null
null
null
include/jbr/reg/var/perm/Rights.hpp
j-bruel/Register
4fa991ed86fedb3883514031e51dc62057d0abd0
[ "MIT" ]
1
2019-05-06T14:12:44.000Z
2019-05-06T14:12:44.000Z
//! //! @file jbr/reg/var/perm/Rights.hpp //! @author jbruel //! @date 30/07/19 //! #ifndef JBR_CREGISTER_REGISTER_VAR_PERM_RIGHTS_HPP # define JBR_CREGISTER_REGISTER_VAR_PERM_RIGHTS_HPP # include <jbr/reg/Permission.hpp> //! //! @namespace jbr::reg::var::perm //! namespace jbr::reg::var::perm { //! //! @struct Rights //! @brief All variables rights. //! struct Rights final : public jbr::reg::Permission { bool mUpdate; //!< Allow to update a variable. bool mRename; //!< Allow to rename a variable. bool mCopy; //!< Allow to copy a variable. bool mRemove; //!< Allow to remove a variable. //! //! @brief Structure initializer. All rights are true by default. //! Rights() : jbr::reg::Permission(), mUpdate(true), mRename(true), mCopy(true), mRemove(true) {} //! //! @brief Structure initializer with custom rights initialization. //! @param rd Reading rights. //! @param wr Writing rights. //! @param up Allow to update a variable. //! @param rn Allow to rename a variable. //! @param cp Allow to copy a variable. //! @param rm Allow to remove a variable. //! explicit Rights(bool rd, bool wr, bool up, bool rn, bool cp, bool rm) : jbr::reg::Permission(rd, wr), mUpdate(up), mRename(rn), mCopy(cp), mRemove(rm) {} //! //! @brief Equal operator overload. //! @param rights New rights to overload. //! @return New rights structure. //! Rights &operator=(const jbr::reg::var::perm::Rights &rights) noexcept { mRead = rights.mRead; mWrite = rights.mWrite; mUpdate = rights.mUpdate; mRename = rights.mRename; mCopy = rights.mCopy; mRemove = rights.mRemove; return (*this); } //! //! @brief Equality overload operator. //! @param rights Rights to check. //! @return Status if rights are equals. //! inline bool operator==(const jbr::reg::var::perm::Rights &rights) noexcept { return (mRead == rights.mRead && mWrite == rights.mWrite && mUpdate == rights.mUpdate && mRename == rights.mRename && mCopy == rights.mCopy && mRemove == rights.mRemove); } }; } #endif //JBR_CREGISTER_REGISTER_VAR_PERM_RIGHTS_HPP
38.592105
122
0.475963
c3f89122ab4097266af03703c46be22049244741
11,021
cpp
C++
src/matrix.cpp
admonkey/nnet
decfb531ebd753cb9777298b891319a262f95a6c
[ "CC0-1.0" ]
2
2019-05-23T15:34:40.000Z
2020-11-09T15:45:29.000Z
src/matrix.cpp
jpuck/neural-network
decfb531ebd753cb9777298b891319a262f95a6c
[ "CC0-1.0" ]
null
null
null
src/matrix.cpp
jpuck/neural-network
decfb531ebd753cb9777298b891319a262f95a6c
[ "CC0-1.0" ]
null
null
null
// ---------------------------------------------------------------- // The contents of this file are distributed under the CC0 license. // See http://creativecommons.org/publicdomain/zero/1.0/ // ---------------------------------------------------------------- #include "matrix.h" #include "rand.h" #include "error.h" #include "string.h" #include <fstream> #include <stdlib.h> #include <algorithm> using std::string; using std::ifstream; using std::map; using std::vector; Matrix::Matrix(const Matrix& other) { throw Ex("Big objects should generally be passed by reference, not by value"); } void Matrix::setSize(size_t rows, size_t cols) { // Make space for the data m_data.resize(rows); for(size_t i = 0; i < rows; i++) m_data[i].resize(cols); // Set the meta-data m_filename = ""; m_attr_name.resize(cols); m_str_to_enum.resize(cols); m_enum_to_str.resize(cols); for(size_t i = 0; i < cols; i++) { m_str_to_enum[i].clear(); m_enum_to_str[i].clear(); } } void Matrix::copyMetaData(const Matrix& that) { m_data.clear(); m_attr_name = that.m_attr_name; m_str_to_enum = that.m_str_to_enum; m_enum_to_str = that.m_enum_to_str; } void Matrix::newColumn(size_t vals) { m_data.clear(); size_t c = cols(); string name = "col_"; name += to_str(c); m_attr_name.push_back(name); map <string, size_t> temp_str_to_enum; map <size_t, string> temp_enum_to_str; for(size_t i = 0; i < vals; i++) { string sVal = "val_"; sVal += to_str(i); temp_str_to_enum[sVal] = i; temp_enum_to_str[i] = sVal; } m_str_to_enum.push_back(temp_str_to_enum); m_enum_to_str.push_back(temp_enum_to_str); } std::vector<double>& Matrix::newRow() { size_t c = cols(); if(c == 0) throw Ex("You must add some columns before you add any rows."); size_t rc = rows(); m_data.resize(rc + 1); std::vector<double>& newrow = m_data[rc]; newrow.resize(c); return newrow; } void Matrix::newRows(size_t n) { for(size_t i = 0; i < n; i++) newRow(); } double Matrix::columnMean(size_t col) const { double sum = 0.0; size_t count = 0; std::vector< std::vector<double> >::const_iterator it; for(it = m_data.begin(); it != m_data.end(); it++) { double val = (*it)[col]; if(val != UNKNOWN_VALUE) { sum += val; count++; } } return sum / count; } double Matrix::columnMin(size_t col) const { double m = 1e300; std::vector< std::vector<double> >::const_iterator it; for(it = m_data.begin(); it != m_data.end(); it++) { double val = (*it)[col]; if(val != UNKNOWN_VALUE) m = std::min(m, val); } return m; } double Matrix::columnMax(size_t col) const { double m = -1e300; std::vector< std::vector<double> >::const_iterator it; for(it = m_data.begin(); it != m_data.end(); it++) { double val = (*it)[col]; if(val != UNKNOWN_VALUE) m = std::max(m, val); } return m; } double Matrix::mostCommonValue(size_t col) const { map<double, size_t> counts; vector< vector<double> >::const_iterator it; for(it = m_data.begin(); it != m_data.end(); it++) { double val = (*it)[col]; if(val != UNKNOWN_VALUE) { map<double, size_t>::iterator pair = counts.find(val); if(pair == counts.end()) counts[val] = 1; else pair->second++; } } size_t valueCount = 0; double value = 0; for(map<double, size_t>::iterator i = counts.begin(); i != counts.end(); i++) { if(i->second > valueCount) { value = i->first; valueCount = i->second; } } return value; } void Matrix::copyPart(const Matrix& that, size_t rowBegin, size_t colBegin, size_t rowCount, size_t colCount) { if(rowBegin + rowCount > that.rows() || colBegin + colCount > that.cols()) throw Ex("out of range"); // Copy the specified region of meta-data if(cols() != colCount) setSize(0, colCount); for(size_t i = 0; i < colCount; i++) { m_attr_name[i] = that.m_attr_name[colBegin + i]; m_str_to_enum[i] = that.m_str_to_enum[colBegin + i]; m_enum_to_str[i] = that.m_enum_to_str[colBegin + i]; } // Copy the specified region of data size_t rowsBefore = m_data.size(); m_data.resize(rowsBefore + rowCount); for(size_t i = 0; i < rowCount; i++) { vector<double>::const_iterator itIn = that[rowBegin + i].begin() + colBegin; m_data[rowsBefore + i].resize(colCount); vector<double>::iterator itOut = m_data[rowsBefore + i].begin(); for(size_t j = 0; j < colCount; j++) *itOut++ = *itIn++; } } string toLower(string strToConvert) { //change each element of the string to lower case for(size_t i = 0; i < strToConvert.length(); i++) strToConvert[i] = tolower(strToConvert[i]); return strToConvert;//return the converted string } void Matrix::saveARFF(string filename) const { std::ofstream s; s.exceptions(std::ios::failbit|std::ios::badbit); try { s.open(filename.c_str(), std::ios::binary); } catch(const std::exception&) { throw Ex("Error creating file: ", filename); } s.precision(10); s << "@RELATION " << m_filename << "\n"; for(size_t i = 0; i < m_attr_name.size(); i++) { s << "@ATTRIBUTE " << m_attr_name[i]; if(m_attr_name[i].size() == 0) s << "x"; size_t vals = valueCount(i); if(vals == 0) s << " REAL\n"; else { s << " {"; for(size_t j = 0; j < vals; j++) { s << attrValue(i, j); if(j + 1 < vals) s << ","; } s << "}\n"; } } s << "@DATA\n"; for(size_t i = 0; i < rows(); i++) { const std::vector<double>& r = (*this)[i]; for(size_t j = 0; j < cols(); j++) { if(r[j] == UNKNOWN_VALUE) s << "?"; else { size_t vals = valueCount(j); if(vals == 0) s << to_str(r[j]); else { size_t val = (size_t)r[j]; if(val >= vals) throw Ex("value out of range"); s << attrValue(j, val); } } if(j + 1 < cols()) s << ","; } s << "\n"; } } void Matrix::loadARFF(string fileName) { size_t lineNum = 0; string line; //line of input from the arff file ifstream inputFile; //input stream map <string, size_t> tempMap; //temp map for int->string map (attrInts) map <size_t, string> tempMapS; //temp map for string->int map (attrString) size_t attrCount = 0; //Count number of attributes inputFile.open ( fileName.c_str() ); if ( !inputFile ) throw Ex ( "failed to open the file: ", fileName ); while ( !inputFile.eof() && inputFile ) { //Iterate through each line of the file getline ( inputFile, line ); lineNum++; if ( toLower ( line ).find ( "@relation" ) == 0 ) m_filename = line.substr ( line.find_first_of ( " " ) ); else if ( toLower ( line ).find ( "@attribute" ) == 0 ) { line = line.substr ( line.find_first_of ( " \t" ) + 1 ); string attrName; // If the attribute name is delimited by '' if ( line.find_first_of( "'" ) == 0 ) { attrName = line.substr ( 1 ); attrName = attrName.substr ( 0, attrName.find_first_of( "'" ) ); line = line.substr ( attrName.size() + 2 ); } else { attrName = line.substr( 0, line.find_first_of( " \t" ) ); line = line.substr ( attrName.size() ); } m_attr_name.push_back ( attrName ); string value = line.substr ( line.find_first_not_of ( " \t" ) ); tempMap.clear(); tempMapS.clear(); //If the attribute is nominal if ( value.find_first_of ( "{" ) == 0 ) { size_t firstComma; size_t firstSpace; size_t firstLetter; value = value.substr ( 1, value.find_last_of ( "}" ) - 1 ); size_t valCount = 0; string tempValue; //Parse the attributes--push onto the maps while ( ( firstComma = value.find_first_of ( "," ) ) != string::npos ) { firstLetter = value.find_first_not_of ( " \t," ); value = value.substr ( firstLetter ); firstComma = value.find_first_of ( "," ); firstSpace = value.find_first_of ( " \t" ); tempMapS[valCount] = value.substr ( 0, firstComma ); string valName = value.substr ( 0, firstComma ); valName = valName.substr ( 0, valName.find_last_not_of(" \t") + 1); tempMap[valName] = valCount++; firstComma = ( firstComma < firstSpace && firstSpace < ( firstComma + 2 ) ) ? firstSpace : firstComma; value = value.substr ( firstComma + 1 ); } //Push final attribute onto the maps firstLetter = value.find_first_not_of ( " \t," ); value = value.substr ( firstLetter ); string valName = value.substr ( 0, value.find_last_not_of(" \t") + 1); tempMapS[valCount] = valName; tempMap[valName] = valCount++; m_str_to_enum.push_back ( tempMap ); m_enum_to_str.push_back ( tempMapS ); } else { //The attribute is continuous m_str_to_enum.push_back ( tempMap ); m_enum_to_str.push_back ( tempMapS ); } attrCount++; } else if ( toLower ( line ).find ( "@data" ) == 0 ) { vector<double> temp; //Holds each line of data temp.resize(attrCount); m_data.clear(); while ( !inputFile.eof() ) { getline ( inputFile, line ); lineNum++; if(line.length() == 0 || line[0] == '%' || line[0] == '\n' || line[0] == '\r') continue; size_t pos = 0; for ( size_t i = 0; i < attrCount; i++ ) { size_t vals = valueCount ( i ); size_t valStart = line.find_first_not_of ( " \t", pos ); if(valStart == string::npos) throw Ex("Expected more elements on line ", to_str(lineNum)); size_t valEnd = line.find_first_of ( ",\n\r", valStart ); string val; if(valEnd == string::npos) { if(i + 1 == attrCount) val = line.substr( valStart ); else throw Ex("Expected more elements on line ", to_str(lineNum)); } else val = line.substr ( valStart, valEnd - valStart ); pos = valEnd + 1; if ( vals > 0 ) //if the attribute is nominal... { if ( val == "?" ) temp[i] = UNKNOWN_VALUE; else { map<string, size_t>::iterator it = m_str_to_enum[i].find ( val ); if(it == m_str_to_enum[i].end()) throw Ex("Unrecognized enumeration value, \"", val, "\" on line ", to_str(lineNum), ", attr ", to_str(i)); temp[i] = (double)m_str_to_enum[i][val]; } } else { // The attribute is continuous if ( val == "?" ) temp[i] = UNKNOWN_VALUE; else temp[i] = atof( val.c_str() ); } } m_data.push_back ( temp ); } } } } const std::string& Matrix::attrValue(size_t attr, size_t val) const { std::map<size_t, std::string>::const_iterator it = m_enum_to_str[attr].find(val); if(it == m_enum_to_str[attr].end()) throw Ex("no name"); return it->second; } void Matrix::setAll(double val) { size_t c = cols(); std::vector< std::vector<double> >::iterator it; for(it = m_data.begin(); it != m_data.end(); it++) it->assign(c, val); } void Matrix::checkCompatibility(const Matrix& that) const { size_t c = cols(); if(that.cols() != c) throw Ex("Matrices have different number of columns"); for(size_t i = 0; i < c; i++) { if(valueCount(i) != that.valueCount(i)) throw Ex("Column ", to_str(i), " has mis-matching number of values"); } }
25.335632
115
0.599673
c3fa4e6d355882e36d018d2516c3c7c54a46fb84
13,345
cpp
C++
src-cpp/shoal.cpp
theJasonFan/shoal
0b081c7a90c826d739581b965b9bb0f4da119225
[ "BSD-2-Clause" ]
21
2016-11-02T13:26:42.000Z
2020-09-16T01:16:21.000Z
src-cpp/shoal.cpp
theJasonFan/shoal
0b081c7a90c826d739581b965b9bb0f4da119225
[ "BSD-2-Clause" ]
3
2016-11-03T11:23:56.000Z
2017-09-20T15:03:48.000Z
src-cpp/shoal.cpp
theJasonFan/shoal
0b081c7a90c826d739581b965b9bb0f4da119225
[ "BSD-2-Clause" ]
3
2016-12-07T07:43:53.000Z
2020-08-06T17:27:20.000Z
#include <fstream> #include <iostream> #include <stack> #include <unordered_set> #include "EquivCollection.hpp" #include "Optimizer.hpp" #include "csv.h" #include "eigen3/Eigen/Dense" #include "filesystem/path.h" #include "popl.hpp" #include "sparsepp.h" #include "spdlog/spdlog.h" #include "spdlog/fmt/ostr.h" struct PriorEntry { double factor; double mean; double stddev; }; struct QuantEntry { uint32_t len; double efflen; double tpm; double numReads; }; void writeSFFile(std::string fname, std::vector<std::string>& names, Eigen::VectorXd& counts, Eigen::VectorXd& lengths, Eigen::VectorXd& effLens) { double million = 1000000.0; size_t M = counts.size(); Eigen::VectorXd tpm(M); tpm.setZero(); double denom{0.0}; for (size_t i = 0; i < M; ++i) { denom += counts[i] / effLens[i]; } for (size_t i = 0; i < M; ++i) { tpm[i] += million * (counts[i] / effLens[i]) / denom; } std::ofstream ofile(fname); ofile << "Name\tLength\tEffectiveLength\tTPM\tNumReads\n"; for (size_t i = 0; i < M; ++i) { ofile << names[i] << '\t' << lengths[i] << '\t' << effLens[i] << '\t' << tpm[i] << '\t' << counts[i] << '\n'; } ofile.close(); } template <typename VecT> void EMUpdate_(std::vector<std::vector<uint32_t>>& txpGroupLabels, std::vector<std::vector<double>>& txpGroupCombinedWeights, std::vector<size_t>& txpGroupCounts, const VecT& alphaIn, VecT& alphaOut); template <typename VecT> double truncateCountVector(VecT& alphas, double cutoff); Eigen::VectorXd optAdaptEst(EquivCollection& ec, spp::sparse_hash_map<std::string, QuantEntry>& quantMap, spp::sparse_hash_map<std::string, PriorEntry>& priorMap, double weight) { auto console = spdlog::get("console"); size_t N = quantMap.size(); Eigen::VectorXd prior(N); Eigen::VectorXd priorInform(N); Eigen::VectorXd alphas(N); Eigen::VectorXd effLens(N); Eigen::VectorXd lengths(N); Eigen::VectorXd tpms(N); Eigen::VectorXd estCounts(N); Eigen::VectorXd factors(N); Eigen::VectorXd factorsInform(N); size_t i{0}; for (auto& tname : ec.tnames_) { auto& quantEnt = quantMap[tname]; lengths[i] = static_cast<double>(quantEnt.len); effLens[i] = quantEnt.efflen; tpms[i] = quantEnt.tpm; estCounts[i] = quantEnt.numReads; alphas[i] = 1.0 / N; auto& priorEnt = priorMap[tname]; prior[i] = 1e-3 * effLens[i]; priorInform[i] = (weight * priorEnt.mean); factors[i] = 1.0; factorsInform[i] = priorEnt.factor; ++i; } console->info("num txps = {}", priorMap.size()); Optimizer opt; Eigen::VectorXd alphaOptInform; alphaOptInform = opt.optimize(ec, alphas, lengths, effLens, priorInform, prior, factorsInform, estCounts, OptimizationType::VBEM); auto alphaOpt = opt.optimize(ec, alphas, lengths, effLens, prior, prior, factors, estCounts, OptimizationType::VBEM); Eigen::VectorXd merged(N); for (size_t i = 0; i < N; ++i) { auto& priorEnt = priorMap[ec.tnames_[i]]; merged[i] = (1.0 - priorEnt.factor) * alphaOpt[i] + (priorEnt.factor * alphaOptInform[i]); } Eigen::VectorXd mergedOut(N); mergedOut.setZero(); EMUpdate_(ec.labels_, ec.auxProbs_, ec.counts_, merged, mergedOut); truncateCountVector(merged, 1e-8); return mergedOut; } Eigen::VectorXd optAdaptPrior(EquivCollection& ec, spp::sparse_hash_map<std::string, QuantEntry>& quantMap, spp::sparse_hash_map<std::string, PriorEntry>& priorMap, double weight) { auto console = spdlog::get("console"); size_t N = quantMap.size(); Eigen::VectorXd prior(N); prior.setZero(); Eigen::VectorXd flatPrior(N); flatPrior.setZero(); Eigen::VectorXd alphas(N); Eigen::VectorXd effLens(N); Eigen::VectorXd lengths(N); Eigen::VectorXd estCounts(N); estCounts.setZero(); Eigen::VectorXd factors(N); auto numEQClasses = ec.labels_.size(); for (size_t eqID = 0; eqID < numEQClasses; ++eqID) { uint64_t count = ec.counts_[eqID]; const std::vector<uint32_t>& txps = ec.labels_[eqID]; size_t groupSize = txps.size(); // If this is a single-transcript group, // then it gets the full count. Otherwise, // update according to our VBEM rule. if (groupSize == 1) { estCounts[txps.front()] = count; } } size_t i{0}; double flatSum = 0.0; double infoSum = 0.0; for (auto& tname : ec.tnames_) { auto& quantEnt = quantMap[tname]; lengths[i] = static_cast<double>(quantEnt.len); effLens[i] = quantEnt.efflen; estCounts[i] += 1e-3 * effLens[i];//quantEnt.numReads; alphas[i] = 1.0/N;//estCounts[i]; auto& priorEnt = priorMap[tname]; factors[i] = priorEnt.factor; ++i; } /* alphas = Eigen::VectorXd::Random(N); double mc = alphas.minCoeff(); alphas = alphas.array() + MC; */ std::unordered_set<uint32_t> active; for (size_t eqID = 0; eqID < numEQClasses; ++eqID) { const std::vector<uint32_t>& txps = ec.labels_[eqID]; size_t groupSize = txps.size(); for (size_t i = 0; i < groupSize; ++i) { active.insert(txps[i]); } } //std::ofstream fsr("ratios.txt"); //std::ofstream fsf("flat.txt"); //std::ofstream fsi("info.txt"); double mf{0.0}; double mi{0.0}; std::vector<double> ratios; for (auto t : active) { auto& priorEnt = priorMap[ec.tnames_[t]]; auto f = 1e-3 * effLens[t]; auto info = priorEnt.mean; flatSum += f; infoSum += info; if (f >= mf) { mf = f; } if (info >= mi) { mi = info; } double r = (info > 0.0) ? (f / info) : ((f > 0.0) ? 1.0 : 0.0); //fsr << r << '\t'; //fsf << 1e-3 * effLens[t] << '\t'; //fsi << info << '\t'; ratios.push_back(r); } //fsr.close(); //fsf.close(); //fsi.close(); console->info("flatSum = {}, infoSum = {}, ratio = {}", flatSum, infoSum, flatSum / infoSum); console->info("num txps = {}", priorMap.size()); auto autoWeight = 0.15 * (flatSum / infoSum); //autoWeight = (flatSum / infoSum); //autoWeight = 1.0;//mf / mi; //double dfact = 0.1; //std::nth_element(ratios.begin(), ratios.begin() + (dfact * ratios.size()), ratios.end()); //autoWeight = ratios[(dfact * ratios.size())]; for (auto t : active ) { auto& tname = ec.tnames_[t]; auto& priorEnt = priorMap[tname]; auto& quantEnt = quantMap[tname]; prior[t] = autoWeight * (priorEnt.mean); flatPrior[t] = 1e-3 * effLens[t]; } Optimizer opt; auto alphaOpt = opt.optimize(ec, alphas, lengths, effLens, prior, flatPrior, factors, estCounts, OptimizationType::VBEM_ADAPTIVE); /* i = 0; for (auto& tname : ec.tnames_) { auto& quantEnt = quantMap[tname]; if (alphaOpt[i] <= 1e-8 and quantEnt.numReads >= 1e-8) { alphaOpt[i] = 1e-3 * quantEnt.efflen; } ++i; } */ return alphaOpt; } Eigen::VectorXd optNoPrior(EquivCollection& ec, spp::sparse_hash_map<std::string, QuantEntry>& quantMap, double weight, std::string optBaseStr) { auto console = spdlog::get("console"); size_t N = quantMap.size(); Eigen::VectorXd prior(N); Eigen::VectorXd alphas(N); Eigen::VectorXd effLens(N); Eigen::VectorXd lengths(N); Eigen::VectorXd tpms(N); Eigen::VectorXd estCounts(N); Eigen::VectorXd factors(N); size_t i{0}; for (auto& tname : ec.tnames_) { auto& quantEnt = quantMap[tname]; lengths[i] = static_cast<double>(quantEnt.len); effLens[i] = quantEnt.efflen; tpms[i] = quantEnt.tpm; estCounts[i] = quantEnt.numReads; alphas[i] = 1.0 / N; prior[i] = weight * effLens[i]; factors[i] = 1.0; ++i; } console->info("num txps = {}", quantMap.size()); Optimizer opt; if (optBaseStr == "em"){ return opt.optimize(ec, alphas, lengths, effLens, prior, prior, factors, estCounts, OptimizationType::EM); } else{ return opt.optimize(ec, alphas, lengths, effLens, prior, prior, factors, estCounts, OptimizationType::VBEM); } } namespace spd = spdlog; int main(int argc, char* argv[]) { using namespace popl; std::string priorFile; std::string sampleDir; std::string outFile; std::string optStr; std::string optBaseStr; double weight{0.001}; Switch helpOption("h", "help", "produce help message"); Value<std::string> optBaseType("b", "optBaseType", "The type of base level optimization to perform one of {vbem, or em}", "vbem", &optBaseStr); Value<std::string> optType("t", "optType", "The type of optimization to perform one of {adapt-prior, or adapt-est}", "adapt-prior", &optStr); Value<std::string> priorOpt("p", "prior", "file containing prior", "", &priorFile); Value<std::string> sampleOpt("s", "sample", "file containing quantifications", "", &sampleDir); Value<std::string> outOpt("o", "output", "output file", "", &outFile); Value<double> weightOpt("w", "weight", "informative prior weight", 0.001, &weight); OptionParser op("Options"); op.add(helpOption) .add(optType) .add(optBaseType) .add(priorOpt) .add(sampleOpt) .add(outOpt) .add(weightOpt); try { // Console logger with color auto console = spd::stdout_color_mt("console"); op.parse(argc, argv); if (helpOption.isSet()) { std::cout << op << "\n"; std::exit(0); } std::unordered_set<std::string> validOptTypes = {"adapt-prior", "adapt-est"}; if (validOptTypes.find(optStr) == validOptTypes.end()) { console->critical("Do not recognize optType {}!", optStr); std::exit(1); } std::unordered_set<std::string> validOptBaseTypes = {"em", "vbem"}; if (validOptBaseTypes.find(optBaseStr) == validOptBaseTypes.end()) { console->critical("Do not recognize optBaseType {}!", optBaseStr); std::exit(1); } std::string sampleFile = sampleDir + "/quant.sf"; auto sampleFilePath = filesystem::path(sampleFile); if (!sampleOpt.isSet() || !sampleFilePath.exists()) { console->critical("Could not find the \"quant.sf\" file. Give the path to " "parent directory containing the \"quant.sf\" file"); std::exit(0); } auto outpath = filesystem::path(outFile).parent_path(); std::stack<filesystem::path> createStack; while (!outpath.exists() and !outpath.empty()) { createStack.push(outpath); outpath = outpath.parent_path(); } while (!createStack.empty()) { filesystem::create_directory(createStack.top()); console->info("creating directory: {}", createStack.top()); createStack.pop(); } std::string eqFile = sampleDir + "/aux_info/eq_classes.txt"; if (!filesystem::path(eqFile).exists()){ console->critical("Could not find the \"eq_classes.txt\" file." "Make sure you ran right version of salmon"); std::exit(0); } EquivCollection ec; ec.fromFile(eqFile); console->info("num txp names = {}", ec.tnames_.size()); spp::sparse_hash_map<std::string, PriorEntry> priorMap; spp::sparse_hash_map<std::string, QuantEntry> quantMap; std::string name; bool havePrior{priorOpt.isSet()}; if (havePrior) { io::CSVReader<4, io::trim_chars<' '>, io::no_quote_escape<'\t'>> in( priorFile); in.read_header(io::ignore_missing_column, "Name", "factor", "mean", "stddev"); double factor, mean, stddev; while (in.read_row(name, factor, mean, stddev)) { priorMap[name] = {factor, mean, stddev}; } } io::CSVReader<5, io::trim_chars<' '>, io::no_quote_escape<'\t'>> quant( sampleFile); quant.read_header(io::ignore_missing_column, "Name", "Length", "EffectiveLength", "TPM", "NumReads"); uint32_t len; double efflen, tpm, numReads; while (quant.read_row(name, len, efflen, tpm, numReads)) { quantMap[name] = {len, efflen, tpm, numReads}; } size_t N = quantMap.size(); Eigen::VectorXd effLens(N); Eigen::VectorXd lengths(N); size_t i{0}; for (auto& tname : ec.tnames_) { auto& quantEnt = quantMap[tname]; lengths[i] = static_cast<double>(quantEnt.len); effLens[i] = quantEnt.efflen; ++i; } Eigen::VectorXd merged; if (havePrior) { if (optStr == "adapt-prior") { merged = optAdaptPrior(ec, quantMap, priorMap, weight); } else if (optStr == "adapt-est") { merged = optAdaptEst(ec, quantMap, priorMap, weight); } } else { merged = optNoPrior(ec, quantMap, weight, optBaseStr); } writeSFFile(outFile, ec.tnames_, merged, lengths, effLens); // Release and close all loggers spdlog::drop_all(); } catch (const spd::spdlog_ex& ex) { std::cout << "Log init failed: " << ex.what() << std::endl; return 1; } }
33.032178
145
0.596328
c3fa7a9f74907ae5ec230fd9742c729e637b4c31
446
cpp
C++
solutions/leetcode/944. Delete Columns to Make Sorted.cpp
MohanedAshraf/competitive-programming
234dc6113b39462c64a2719cd1071f3d99655508
[ "MIT" ]
1
2021-08-12T14:53:37.000Z
2021-08-12T14:53:37.000Z
solutions/leetcode/944. Delete Columns to Make Sorted.cpp
MohanedAshraf/competitive-programming
234dc6113b39462c64a2719cd1071f3d99655508
[ "MIT" ]
null
null
null
solutions/leetcode/944. Delete Columns to Make Sorted.cpp
MohanedAshraf/competitive-programming
234dc6113b39462c64a2719cd1071f3d99655508
[ "MIT" ]
null
null
null
static int __=[](){std::ios::sync_with_stdio(false);return 1000;}(); class Solution { public: int minDeletionSize(vector<string>& strs) { int c = 0 , n = strs.size() , m = strs[0].size() ; for(int i= 0 ; i<m ; i++) for(int j = 0; j<n-1 ; j++ ) if(strs[j][i] > strs[j+1][i]){ c++; break; } return c ; } };
24.777778
68
0.392377
c3fda5be2ec43ef70ebf0cce3ebacee46910d9d6
4,450
cpp
C++
sts_behavior_tree_client/src/BehaviorTreeNodeInterface.cpp
Autonomous-Logistics/sts_behavior_tree_testing
3c9fecf3b2ea69289ca95b426182cb250ba4ba27
[ "MIT" ]
4
2020-04-01T11:03:03.000Z
2021-05-30T01:23:50.000Z
sts_behavior_tree_client/src/BehaviorTreeNodeInterface.cpp
Autonomous-Logistics/sts_behavior_tree_testing
3c9fecf3b2ea69289ca95b426182cb250ba4ba27
[ "MIT" ]
null
null
null
sts_behavior_tree_client/src/BehaviorTreeNodeInterface.cpp
Autonomous-Logistics/sts_behavior_tree_testing
3c9fecf3b2ea69289ca95b426182cb250ba4ba27
[ "MIT" ]
2
2020-04-08T14:21:54.000Z
2021-10-06T08:42:30.000Z
#include "sts_behavior_tree_testing/BehaviorTreeNodeInterface.h" namespace sts_behavior_tree_testing { /// ************************** /// Constructors /// ************************** BehaviorTreeNodeInterface::BehaviorTreeNodeInterface(ros::NodeHandle* nodeHandlePtr) : sts_core::sts_interfaces::StsBehaviorTreeInterface(nodeHandlePtr) { //this->currentResult_ = false; //declare com if with callback //this->createBtIfCom("bt_topic", sts_bt_types::TOPIC, false, std::bind(&BehaviorTreeNodeInterface::publishCallback, this, std::placeholders::_1)); this->createBtIfCom("topic1", sts_behavior_tree_if_types::FLAG, false); this->createBtIfCom("service1", sts_behavior_tree_if_types::SERVICE, false, std::bind(&BehaviorTreeNodeInterface::serviceCallback, this, std::placeholders::_1)); this->createBtIfCom("action1", sts_behavior_tree_if_types::ACTION, false, std::bind(&BehaviorTreeNodeInterface::actionCallback, this, std::placeholders::_1)); this->createBtIfCom("action2", sts_behavior_tree_if_types::ACTION, false, std::bind(&BehaviorTreeNodeInterface::actionCallback2, this, std::placeholders::_1)); if(this->isOk()) this->PRINT_NOTIFY("Node launched Successfully"); else this->PRINT_ERROR("Node initialization failed"); /// do other important things } /// ************************** /// Destructor /// ************************** BehaviorTreeNodeInterface::~BehaviorTreeNodeInterface() { } /// ************************** /// Methods /// ************************** bool BehaviorTreeNodeInterface::readParameters() { if (!this->getNodeHandle()->getParam("subscriber_topic", subscriberTopic_)) return false; return true; } void BehaviorTreeNodeInterface::publishCallback(sts_behavior_tree_if_types::StsBehaviorTreeParam* resultPtr) { std::cout << "conditionCallback1, updating to " << this->getCurrentResult() << std::endl; resultPtr->getResultObj()->setResult(this->getCurrentResult()); return; } void BehaviorTreeNodeInterface::serviceCallback(sts_behavior_tree_if_types::StsBehaviorTreeParam* resultPtr) { std::cout << "serviceCallback" << std::endl; resultPtr->getResultObj()->setResult(true); return; } void BehaviorTreeNodeInterface::actionCallback(sts_behavior_tree_if_types::StsBehaviorTreeParam* resultPtr) { std::cout << "actionCallback1" << std::endl; std::this_thread::sleep_for(std::chrono::seconds(3)); if (resultPtr->getArgsObj()->getPreemptRequestReference() == false) { //this->setCurrentResult(true); this->sendAsync("topic1", true); /// do a little sleep before returning from teh action , just for the lolz std::this_thread::sleep_for(std::chrono::seconds(1)); resultPtr->getResultObj()->setResult(true); std::cout << "actionCallback1 returned POSITIVE" << std::endl; } else { resultPtr->getResultObj()->setResult(false); std::cout << "actionCallback1 PREEMPTED" << std::endl; } return; } void BehaviorTreeNodeInterface::actionCallback2(sts_behavior_tree_if_types::StsBehaviorTreeParam* resultPtr) { std::cout << "actionCallback2" << std::endl; std::this_thread::sleep_for(std::chrono::seconds(3)); if (resultPtr->getArgsObj()->getPreemptRequestReference() == false) { //this->setCurrentResult(false); this->sendAsync("topic1", false); /// do a little sleep before returning from teh action , just for the lolz std::this_thread::sleep_for(std::chrono::seconds(1)); resultPtr->getResultObj()->setResult(true); std::cout << "actionCallback2 returned POSITIVE" << std::endl; } else { resultPtr->getResultObj()->setResult(false); std::cout << "actionCallback2 PREEMPTED" << std::endl; } return; } //Showcase method void BehaviorTreeNodeInterface::resetConditionResult() { std::string tmp; while (true) { std::cin >> tmp; if(tmp[0] == '1') { std::cout << "Set condition result(1)" << std::endl; //this->setCurrentResult(true); this->sendAsync("topic1", true); } else if(tmp[0] == '0') { std::cout << "Reset condition result(0)" << std::endl; //this->setCurrentResult(false); this->sendAsync("topic1", false); } else { } } } } /* namespace */
32.720588
165
0.646292
c3ff4561c82896407cd33ef4b603f6fbcf689245
601
cc
C++
pressureCtrlAlg/bagSimModel.cc
gerth2/piUserInterface
9b79cbe71654c404894eac511e54581d4d9cf8ab
[ "MIT" ]
null
null
null
pressureCtrlAlg/bagSimModel.cc
gerth2/piUserInterface
9b79cbe71654c404894eac511e54581d4d9cf8ab
[ "MIT" ]
null
null
null
pressureCtrlAlg/bagSimModel.cc
gerth2/piUserInterface
9b79cbe71654c404894eac511e54581d4d9cf8ab
[ "MIT" ]
null
null
null
#include "bagSimModel.h" #define Ts 0.01 #define PWM_TO_POS_SCALE 0.01 #define BAG_MAX_VOL 1.0 #define BAG_MIN_VOL 0.25 //Expected flow vs. Pressure // PSI 2 5 10 15 20 25 30 // kPa 13.7 34.5 68.9 103 138 172 206 // Flow (CFM) 40.5 63.5 79.6 108 126 144 162 BagSimModel::BagSimModel(double Ts_in){ armPctCompression = 0; } double BagSimModel::update(double motorPWM){ armPctCompression += motorPWM * Ts * PWM_TO_POS_SCALE; double bagVol = (BAG_MAX_VOL - BAG_MIN_VOL) * armPctCompression + BAG_MIN_VOL; }
22.259259
83
0.625624
7f010c257f9e8d50c312d8d5dd31661136ac1ee7
243
cpp
C++
Basic/Check Whether a Number is Even or Odd/SolutionByRegi.cpp
Mdanish777/Programmers-Community
b5ca9582fc1cd4337baa7077ff62130a1052583f
[ "MIT" ]
2
2019-09-21T21:18:13.000Z
2019-09-28T14:26:56.000Z
Basic/Check Whether a Number is Even or Odd/SolutionByRegi.cpp
Mdanish777/Programmers-Community
b5ca9582fc1cd4337baa7077ff62130a1052583f
[ "MIT" ]
14
2019-09-23T07:25:27.000Z
2019-09-30T09:35:01.000Z
Basic/Check Whether a Number is Even or Odd/SolutionByRegi.cpp
Mdanish777/Programmers-Community
b5ca9582fc1cd4337baa7077ff62130a1052583f
[ "MIT" ]
13
2019-09-21T16:43:56.000Z
2019-09-30T15:28:33.000Z
#include <iostream> #include <string> bool IsEven(int num) { return (num % 2 == 0); } int main() { int num; std::cout << "Enter a number: "; std::cin >> num; std::cout << num << " is " << (IsEven(num) ? "Even" : "Odd") << "\n"; }
16.2
71
0.514403
7f016362cc0d9f086ec0a4838d2dbe0579de879f
905
cpp
C++
Week13/natsia_and_good_arrays.cpp
princesinghtomar/Competitive-Programming
a0df818dfa56267fdde59bd1862d0b78f6e069c4
[ "MIT" ]
3
2020-11-11T13:45:40.000Z
2021-07-20T11:53:34.000Z
Week13/natsia_and_good_arrays.cpp
princesinghtomar/Competitive-Programming
a0df818dfa56267fdde59bd1862d0b78f6e069c4
[ "MIT" ]
11
2020-10-03T14:26:35.000Z
2021-10-30T15:26:40.000Z
Week13/natsia_and_good_arrays.cpp
princesinghtomar/Competitive-Programming
a0df818dfa56267fdde59bd1862d0b78f6e069c4
[ "MIT" ]
12
2020-05-12T08:39:54.000Z
2021-10-30T14:56:27.000Z
#include <bits/stdc++.h> using namespace std; int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); int t; cin>>t; while(t--){ int n; cin >> n; int sindex = 0,k=0; long int arr[n]; long int brr[n][4]; for(int i=0;i<n;i++){ cin>>arr[i]; if(arr[i] < arr[sindex]){ sindex = i; } } for(int i = 0;i < n; i++){ if(i == sindex){ continue; } brr[k][0] = sindex; brr[k][1] = i; brr[k][2] = arr[sindex]; brr[k][3] = arr[sindex] + abs(i-sindex); k++; } cout<<k<<endl; if(k>0){ for(int i=0;i<k;i++){ cout<<brr[i][0]+1 << " " << brr[i][1]+1 << " " << brr[i][2] << " " << brr[i][3] << endl; } } } }
23.815789
104
0.345856
7f01e39e372fa6f8e3ab3974e174acbe05393132
904
cc
C++
fake_landsatz_2d/random.cc
DotStarMoney/NBD
7a6b76b84cc35de7825ede55c4c89a391a5dff7f
[ "Apache-2.0" ]
1
2021-09-27T00:15:50.000Z
2021-09-27T00:15:50.000Z
fake_landsatz_2d/random.cc
DotStarMoney/NBD
7a6b76b84cc35de7825ede55c4c89a391a5dff7f
[ "Apache-2.0" ]
null
null
null
fake_landsatz_2d/random.cc
DotStarMoney/NBD
7a6b76b84cc35de7825ede55c4c89a391a5dff7f
[ "Apache-2.0" ]
null
null
null
#include "random.h" #include <stdint.h> #include <functional> #include <limits> #include <thread> namespace nbd { namespace util { struct XorShiftP { XorShiftP() { srnd(std::hash<std::thread::id>{}(std::this_thread::get_id())); } uint64_t state[2]; uint64_t Step() { uint64_t x = state[0]; const uint64_t y = state[1]; state[0] = y; x ^= x << 23; x ^= x >> 17; x ^= y ^ (y >> 26); state[1] = x; return x + y; } void Seed(uint64_t s) { state[0] = s; state[1] = 0x5ea34222ef71888b; for (uint32_t i = 0; i < 16; ++i) rnd(); } }; thread_local XorShiftP prng; uint64_t rnd() { return prng.Step(); } double rndd() { return static_cast<double>(rnd()) / std::numeric_limits<uint64_t>::max(); } void srnd(uint64_t s) { prng.Seed(s); } bool TrueWithChance(double prob) { return rndd() < prob; } } // namespace util } // namespace nbd
17.384615
75
0.589602
7f06520e6ab72bc5a6ba0be605f7cf45659bac4f
4,414
cpp
C++
statusd.cpp
vonj/minidisplay_statusd
07ff51f41a2ff5d14dc4567970a281885b10aa9a
[ "MIT" ]
3
2016-08-20T20:00:40.000Z
2020-05-16T03:10:18.000Z
statusd.cpp
vonj/minidisplay_statusd
07ff51f41a2ff5d14dc4567970a281885b10aa9a
[ "MIT" ]
1
2016-08-20T11:57:26.000Z
2016-08-20T11:57:26.000Z
statusd.cpp
vonj/minidisplay_statusd
07ff51f41a2ff5d14dc4567970a281885b10aa9a
[ "MIT" ]
null
null
null
#include <arpa/inet.h> #include <sys/socket.h> #include <netdb.h> #include <ifaddrs.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include "ArduiPi_OLED_lib.h" #include "Adafruit_GFX.h" #include "ArduiPi_OLED.h" #include <time.h> #include <getopt.h> #include <sys/time.h> // Instantiate the display ArduiPi_OLED display; // Config Option struct s_opts { int oled; int verbose; }; // default options values s_opts opts = { OLED_ADAFRUIT_I2C_128x64, // Default oled false // Not verbose }; static void init_oled() { // SPI change parameters to fit to your LCD if (display.oled_is_spi_proto(opts.oled)) { if (!display.init(OLED_SPI_DC, OLED_SPI_RESET, OLED_SPI_CS, opts.oled)) { exit(EXIT_FAILURE); } } else { if (!display.init(OLED_I2C_RESET, opts.oled)) { exit(EXIT_FAILURE); } } } static void get_ip_address(char ip[16]) { struct ifaddrs *ifaddr, *ifa; int s; char host[NI_MAXHOST]; if (getifaddrs(&ifaddr) == -1) { perror("getifaddrs"); return; } for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) { if (ifa->ifa_addr == NULL) { continue; } s = getnameinfo(ifa->ifa_addr, sizeof (struct sockaddr_in), host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST); if ((0 == strcmp(ifa->ifa_name, "eth0")) && (ifa->ifa_addr->sa_family == AF_INET)) { if (s != 0) { printf("getnameinfo() failed: %s\n", gai_strerror(s)); return; } strcpy(ip, host); freeifaddrs(ifaddr); return; } } freeifaddrs(ifaddr); } static bool read_internet_status() { return !system("nc -w 10 -z 10.8.0.1 22"); } static int read_mails_received() { const char* filename = "/var/tmp/mails_received.txt"; int mails_received = 0; struct stat buf; if (stat(filename, &buf)) { return -1; } if ((time(NULL) - buf.st_mtim.tv_sec) > (24*3600)) { return -1; // Status file is unreasonably old } FILE* fp = fopen(filename, "r"); if (!fp) { return -1; } fscanf(fp, "%d", &mails_received); fclose(fp); return mails_received; } static void show_status() { time_t now; static time_t last_time; struct tm * timeinfo; double percent = 0; struct timespec tp; static bool up = true; const double cycle = 2; // seconds double half_cycle = cycle / 2.0; static bool internet_up = false; static int mails_received = -99; char ip[16]; usleep(70000); get_ip_address(ip); display.clearDisplay(); display.setCursor(0, 0); time(&now); timeinfo = localtime(&now); clock_gettime(CLOCK_REALTIME, &tp); double secs_fraction = (double)(tp.tv_nsec) / 1000000000.0; int where_in_cycle = tp.tv_sec % (int)cycle; up = where_in_cycle < half_cycle; double where_in_cycle_d = (double)where_in_cycle + secs_fraction; if (up) { percent = 100.0 * (where_in_cycle_d / half_cycle); } else { percent = 100.0 - 100.0 * ((double)(where_in_cycle_d - half_cycle) / half_cycle); } display.setTextSize(2); display.printf("%2.2d:%2.2d:%2.2d\n", timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec); display.setTextSize(1); // Only do "expensive" stuff every minute if ((now - last_time) > 60) { last_time = now; internet_up = read_internet_status(); mails_received = read_mails_received(); } display.printf("IP: %s\n", ip); display.printf("Network %s\n", internet_up ? "UP" : "DOWN"); display.printf("%d mails today.\n", mails_received); display.drawVerticalBargraph(121, 0, 6, (int16_t)display.height(), WHITE, (int)percent); display.display(); } static void close_display() { // Free PI GPIO ports display.close(); } // Free PI GPIO ports int main(int argc, char **argv) { if (argc > 1 && !strcmp("-d", argv[1])) { if (daemon(0, 0)) { fprintf(stderr, "Daemon call failed.\n"); return 1; } } atexit(close_display); init_oled(); display.begin(); display.setTextColor(WHITE); while (1) { show_status(); } return 0; }
21.637255
111
0.589941
7f074d834191471a61d7643bb518b3420de42043
10,520
cpp
C++
qtdeclarative/src/quick/designer/qquickdesignercustomobjectdata.cpp
wgnet/wds_qt
8db722fd367d2d0744decf99ac7bafaba8b8a3d3
[ "Apache-2.0" ]
1
2020-04-30T15:47:35.000Z
2020-04-30T15:47:35.000Z
qtdeclarative/src/quick/designer/qquickdesignercustomobjectdata.cpp
wgnet/wds_qt
8db722fd367d2d0744decf99ac7bafaba8b8a3d3
[ "Apache-2.0" ]
null
null
null
qtdeclarative/src/quick/designer/qquickdesignercustomobjectdata.cpp
wgnet/wds_qt
8db722fd367d2d0744decf99ac7bafaba8b8a3d3
[ "Apache-2.0" ]
null
null
null
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the QtQuick module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL21$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see http://www.qt.io/terms-conditions. For further ** information use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** As a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qquickdesignersupportmetainfo_p.h" #include "qquickdesignersupportproperties_p.h" #include "qquickdesignercustomobjectdata_p.h" #include <QGlobalStatic> #include <QQmlContext> #include <QQmlEngine> #include <private/qqmlbinding_p.h> QT_BEGIN_NAMESPACE typedef QHash<QObject*, QQuickDesignerCustomObjectData*> CustomObjectDataHash; Q_GLOBAL_STATIC(CustomObjectDataHash, s_designerObjectToDataHash) struct HandleDestroyedFunctor { QQuickDesignerCustomObjectData *data; void operator()() { data->handleDestroyed(); } }; QQuickDesignerCustomObjectData::QQuickDesignerCustomObjectData(QObject *object) : m_object(object) { if (object) { populateResetHashes(); s_designerObjectToDataHash()->insert(object, this); HandleDestroyedFunctor functor; functor.data = this; QObject::connect(object, &QObject::destroyed, functor); } } void QQuickDesignerCustomObjectData::registerData(QObject *object) { new QQuickDesignerCustomObjectData(object); } QQuickDesignerCustomObjectData *QQuickDesignerCustomObjectData::get(QObject *object) { return s_designerObjectToDataHash()->value(object); } QVariant QQuickDesignerCustomObjectData::getResetValue(QObject *object, const QQuickDesignerSupport::PropertyName &propertyName) { QQuickDesignerCustomObjectData* data = get(object); if (data) return data->getResetValue(propertyName); return QVariant(); } void QQuickDesignerCustomObjectData::doResetProperty(QObject *object, QQmlContext *context, const QQuickDesignerSupport::PropertyName &propertyName) { QQuickDesignerCustomObjectData* data = get(object); if (data) data->doResetProperty(context, propertyName); } bool QQuickDesignerCustomObjectData::hasValidResetBinding(QObject *object, const QQuickDesignerSupport::PropertyName &propertyName) { QQuickDesignerCustomObjectData* data = get(object); if (data) return data->hasValidResetBinding(propertyName); return false; } bool QQuickDesignerCustomObjectData::hasBindingForProperty(QObject *object, QQmlContext *context, const QQuickDesignerSupport::PropertyName &propertyName, bool *hasChanged) { QQuickDesignerCustomObjectData* data = get(object); if (data) return data->hasBindingForProperty(context, propertyName, hasChanged); return false; } void QQuickDesignerCustomObjectData::setPropertyBinding(QObject *object, QQmlContext *context, const QQuickDesignerSupport::PropertyName &propertyName, const QString &expression) { QQuickDesignerCustomObjectData* data = get(object); if (data) data->setPropertyBinding(context, propertyName, expression); } void QQuickDesignerCustomObjectData::keepBindingFromGettingDeleted(QObject *object, QQmlContext *context, const QQuickDesignerSupport::PropertyName &propertyName) { QQuickDesignerCustomObjectData* data = get(object); if (data) data->keepBindingFromGettingDeleted(context, propertyName); } void QQuickDesignerCustomObjectData::populateResetHashes() { QQuickDesignerSupport::PropertyNameList propertyNameList = QQuickDesignerSupportProperties::propertyNameListForWritableProperties(object()); Q_FOREACH (const QQuickDesignerSupport::PropertyName &propertyName, propertyNameList) { QQmlProperty property(object(), QString::fromUtf8(propertyName), QQmlEngine::contextForObject(object())); QQmlAbstractBinding::Ptr binding = QQmlAbstractBinding::Ptr(QQmlPropertyPrivate::binding(property)); if (binding) { m_resetBindingHash.insert(propertyName, binding); } else if (property.isWritable()) { m_resetValueHash.insert(propertyName, property.read()); } } } QObject *QQuickDesignerCustomObjectData::object() const { return m_object; } QVariant QQuickDesignerCustomObjectData::getResetValue(const QQuickDesignerSupport::PropertyName &propertyName) const { return m_resetValueHash.value(propertyName); } void QQuickDesignerCustomObjectData::doResetProperty(QQmlContext *context, const QQuickDesignerSupport::PropertyName &propertyName) { QQmlProperty property(object(), QString::fromUtf8(propertyName), context); if (!property.isValid()) return; QQmlAbstractBinding *binding = QQmlPropertyPrivate::binding(property); if (binding && !(hasValidResetBinding(propertyName) && getResetBinding(propertyName) == binding)) { binding->setEnabled(false, 0); } if (hasValidResetBinding(propertyName)) { QQmlAbstractBinding *binding = getResetBinding(propertyName); #if defined(QT_NO_DYNAMIC_CAST) QQmlBinding *qmlBinding = static_cast<QQmlBinding*>(binding); #else QQmlBinding *qmlBinding = dynamic_cast<QQmlBinding*>(binding); #endif if (qmlBinding) qmlBinding->setTarget(property); QQmlPropertyPrivate::setBinding(binding, QQmlPropertyPrivate::None, QQmlPropertyPrivate::DontRemoveBinding); if (qmlBinding) qmlBinding->update(); } else if (property.isResettable()) { property.reset(); } else if (property.propertyTypeCategory() == QQmlProperty::List) { QQmlListReference list = qvariant_cast<QQmlListReference>(property.read()); if (!QQuickDesignerSupportProperties::hasFullImplementedListInterface(list)) { qWarning() << "Property list interface not fully implemented for Class " << property.property().typeName() << " in property " << property.name() << "!"; return; } list.clear(); } else if (property.isWritable()) { if (property.read() == getResetValue(propertyName)) return; property.write(getResetValue(propertyName)); } } bool QQuickDesignerCustomObjectData::hasValidResetBinding(const QQuickDesignerSupport::PropertyName &propertyName) const { return m_resetBindingHash.contains(propertyName) && m_resetBindingHash.value(propertyName).data(); } QQmlAbstractBinding *QQuickDesignerCustomObjectData::getResetBinding(const QQuickDesignerSupport::PropertyName &propertyName) const { return m_resetBindingHash.value(propertyName).data(); } bool QQuickDesignerCustomObjectData::hasBindingForProperty(QQmlContext *context, const QQuickDesignerSupport::PropertyName &propertyName, bool *hasChanged) const { if (QQuickDesignerSupportProperties::isPropertyBlackListed(propertyName)) return false; QQmlProperty property(object(), QString::fromUtf8(propertyName), context); bool hasBinding = QQmlPropertyPrivate::binding(property); if (hasChanged) { *hasChanged = hasBinding != m_hasBindingHash.value(propertyName, false); if (*hasChanged) m_hasBindingHash.insert(propertyName, hasBinding); } return QQmlPropertyPrivate::binding(property); } void QQuickDesignerCustomObjectData::setPropertyBinding(QQmlContext *context, const QQuickDesignerSupport::PropertyName &propertyName, const QString &expression) { QQmlProperty property(object(), QString::fromUtf8(propertyName), context); if (!property.isValid()) return; if (property.isProperty()) { QQmlBinding *binding = new QQmlBinding(expression, object(), context); binding->setTarget(property); binding->setNotifyOnValueChanged(true); QQmlPropertyPrivate::setBinding(binding, QQmlPropertyPrivate::None, QQmlPropertyPrivate::DontRemoveBinding); //Refcounting is taking take care of deletion binding->update(); if (binding->hasError()) { if (property.property().userType() == QVariant::String) property.write(QVariant(QLatin1Char('#') + expression + QLatin1Char('#'))); } } else { qWarning() << Q_FUNC_INFO << ": Cannot set binding for property" << propertyName << ": property is unknown for type"; } } void QQuickDesignerCustomObjectData::keepBindingFromGettingDeleted(QQmlContext *context, const QQuickDesignerSupport::PropertyName &propertyName) { //Refcounting is taking care Q_UNUSED(context) Q_UNUSED(propertyName) } void QQuickDesignerCustomObjectData::handleDestroyed() { s_designerObjectToDataHash()->remove(m_object); delete this; } QT_END_NAMESPACE
36.655052
164
0.684411
7f0adede716cb763e559b3e8d4533efb7a003b74
524
cpp
C++
Payoffs.cpp
ThibaultLacharme/tddc_pde_solver
c735ff4aff8a9cba33ed86c59b1fcd569745b74f
[ "BSD-3-Clause" ]
null
null
null
Payoffs.cpp
ThibaultLacharme/tddc_pde_solver
c735ff4aff8a9cba33ed86c59b1fcd569745b74f
[ "BSD-3-Clause" ]
null
null
null
Payoffs.cpp
ThibaultLacharme/tddc_pde_solver
c735ff4aff8a9cba33ed86c59b1fcd569745b74f
[ "BSD-3-Clause" ]
null
null
null
#include "Payoffs.hpp" #include <algorithm> namespace dauphine { Payoffs::Payoffs() { } // For other products add the corresponding function at maturity, if there are more arguments than the spot and strike adjust the function in Boundaries too double Payoffs::call(double spot, double strike) { return std::max(spot - strike, 0.); }; double Payoffs::put(double spot, double strike) { return std::max(strike - spot, 0.); }; Payoffs::~Payoffs() { } }
22.782609
160
0.627863
7f0baa544b7b060deb320c8cf061d5094f8be324
1,026
cpp
C++
src/tools/character_padding.cpp
bidfx/bidfx-api-cpp
9f178178a90355f57477f27277f470c910263696
[ "Apache-2.0" ]
5
2020-06-13T08:26:53.000Z
2022-02-25T19:32:55.000Z
src/tools/character_padding.cpp
bidfx/bidfx-api-cpp
9f178178a90355f57477f27277f470c910263696
[ "Apache-2.0" ]
2
2020-03-08T16:07:46.000Z
2020-04-15T08:26:08.000Z
src/tools/character_padding.cpp
bidfx/bidfx-api-cpp
9f178178a90355f57477f27277f470c910263696
[ "Apache-2.0" ]
1
2020-06-13T10:52:46.000Z
2020-06-13T10:52:46.000Z
/** Copyright 2019 BidFX 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 <sstream> #include "character_padding.h" namespace bidfx_public_api::tools { CharacterPadding::CharacterPadding(char pad_char, unsigned int len) : pad_char_{pad_char}, length_{len < 0 ? 0 : len} { std::stringstream ss; for (int i = 0; i < length_; i++) { ss << pad_char_; } constructed_padding_ = ss.str(); } std::string CharacterPadding::ToString() { return constructed_padding_; } }
27
117
0.703704
7f17e6c64789dd102403d3119f4f4374d892b6c0
250
cpp
C++
Programs/14 Recursion/basics/power.cpp
Lord-Lava/DSA-CPP-Apna-College
077350c2aa900bb0cdb137ece2b95be58ccd76a8
[ "MIT" ]
5
2021-04-04T18:39:14.000Z
2021-12-18T09:31:55.000Z
Programs/14 Recursion/basics/power.cpp
Lord-Lava/DSA-CPP-Apna-College
077350c2aa900bb0cdb137ece2b95be58ccd76a8
[ "MIT" ]
null
null
null
Programs/14 Recursion/basics/power.cpp
Lord-Lava/DSA-CPP-Apna-College
077350c2aa900bb0cdb137ece2b95be58ccd76a8
[ "MIT" ]
1
2021-09-26T11:01:26.000Z
2021-09-26T11:01:26.000Z
#include<iostream> using namespace std; int power(int n, int p){ if(p==0){ return 1; } int prevPower= power(n,p-1); return n*prevPower; } int main(){ int n,p; cin>>n>>p; cout<<power(n,p)<<endl; return 0; }
12.5
32
0.536
7f18fbfcc1328db12e9a61606cc699f7a6e45aa8
1,909
cpp
C++
DirectXGame/DirectXCore/Sprite.cpp
nguyenlamlll/DirectX-11-Game
560ae6d9b44cef7882c5fc93192160fae7da791d
[ "MIT" ]
2
2018-09-13T06:15:57.000Z
2021-09-08T02:32:11.000Z
DirectXGame/DirectXCore/Sprite.cpp
nguyenlamlll/DirectX-11-Game
560ae6d9b44cef7882c5fc93192160fae7da791d
[ "MIT" ]
17
2018-09-11T09:37:22.000Z
2018-12-04T07:56:49.000Z
DirectXGame/DirectXCore/Sprite.cpp
nguyenlamlll/DirectX-11-Game
560ae6d9b44cef7882c5fc93192160fae7da791d
[ "MIT" ]
1
2021-11-29T05:12:48.000Z
2021-11-29T05:12:48.000Z
#include "stdafx.h" #include "Sprite.h" using Microsoft::WRL::ComPtr; using namespace DirectXCore; Sprite::Sprite() { } Sprite::Sprite(DirectXCore::DeviceResources * _deviceResource, const wchar_t * _charPath, float _scale) { //pivot.x = float(spriteDesc.Width / 2); pivot.x = 0; //pivot.y = float(spriteDesc.Height / 2); pivot.y = 0; //transform = new Transform(Vector3(_deviceResource->GetOutputSize().right / 2, _deviceResource->GetOutputSize().bottom / 2, 0), Vector3(0, 0, 0), Vector3(1, 1, 1)); //spriterect = new RECT(); //transform->SetRotation(Vector3(0,0,0)); //transform->SetScale(SimpleMath::Vector3(_scale, _scale, 1)); //if (!GetComponent<Renderer>()) { // AddComponent<Renderer>(new Renderer(_deviceResource, _charPath, this)); // SetSpriteRect(GetComponent<Renderer>()->GetRECT()); // spriterect = GetComponent<Renderer>()->GetRECT(); //} //transform->SetScreenScale(SimpleMath::Vector3(spriterect->right, spriterect->bottom, 1)); } Sprite::~Sprite() { } void DirectXCore::Sprite::LoadTexture(const wchar_t * _charPath) { } void Sprite::Update(float _deltaTime) { /*for (size_t i = 0; i < componentList->size(); i++) { componentList->at(i)->Update(); } Collider *collider = GetComponent<Collider>(); if (collider) { collider->SetColliderScale(Vector3(transform->GetScale().x * (spriterect->right - spriterect->left), transform->GetScale().y * (spriterect->bottom - spriterect->top), 1)); collider->SetColliderPosition(transform->GetPosition()); }*/ } void Sprite::Render() { /*for (size_t i = 0; i < componentList->size(); i++) { componentList->at(i)->Render(); }*/ } void Sprite::SetSpriteRect(RECT * _newSpriteRect) { //GetComponent<Renderer>()->SetRECT(*_newSpriteRect); spriterect->top = _newSpriteRect->top; spriterect->bottom = _newSpriteRect->bottom; spriterect->left = _newSpriteRect->left; spriterect->right = _newSpriteRect->right; }
26.887324
173
0.698271
7f191646403c7c058cf767d25184395b8d0a7d88
6,270
cpp
C++
build/cpp/src/verb/core/SurfacePoint.cpp
harmanpa/verb
f18a6db8d9e47b65d7cbf2d954a9dc42f611abd9
[ "MIT" ]
null
null
null
build/cpp/src/verb/core/SurfacePoint.cpp
harmanpa/verb
f18a6db8d9e47b65d7cbf2d954a9dc42f611abd9
[ "MIT" ]
null
null
null
build/cpp/src/verb/core/SurfacePoint.cpp
harmanpa/verb
f18a6db8d9e47b65d7cbf2d954a9dc42f611abd9
[ "MIT" ]
null
null
null
// Generated by Haxe 4.1.4 #include <hxcpp.h> #ifndef INCLUDED_verb_core_SurfacePoint #include <verb/core/SurfacePoint.h> #endif HX_DEFINE_STACK_FRAME(_hx_pos_959611cb896c5e6e_146_new,"verb.core.SurfacePoint","new",0xb12daa55,"verb.core.SurfacePoint.new","verb/core/Intersections.hx",146,0x2e2a0454) HX_LOCAL_STACK_FRAME(_hx_pos_959611cb896c5e6e_155_fromUv,"verb.core.SurfacePoint","fromUv",0x63cbab96,"verb.core.SurfacePoint.fromUv","verb/core/Intersections.hx",155,0x2e2a0454) namespace verb{ namespace core{ void SurfacePoint_obj::__construct(::Array< Float > point,::Array< Float > normal,::Array< Float > uv,::hx::Null< int > __o_id,::hx::Null< bool > __o_degen){ int id = __o_id.Default(-1); bool degen = __o_degen.Default(false); HX_STACKFRAME(&_hx_pos_959611cb896c5e6e_146_new) HXLINE( 147) this->uv = uv; HXLINE( 148) this->point = point; HXLINE( 149) this->normal = normal; HXLINE( 150) this->id = id; HXLINE( 151) this->degen = degen; } Dynamic SurfacePoint_obj::__CreateEmpty() { return new SurfacePoint_obj; } void *SurfacePoint_obj::_hx_vtable = 0; Dynamic SurfacePoint_obj::__Create(::hx::DynamicArray inArgs) { ::hx::ObjectPtr< SurfacePoint_obj > _hx_result = new SurfacePoint_obj(); _hx_result->__construct(inArgs[0],inArgs[1],inArgs[2],inArgs[3],inArgs[4]); return _hx_result; } bool SurfacePoint_obj::_hx_isInstanceOf(int inClassId) { return inClassId==(int)0x00000001 || inClassId==(int)0x16f19b2d; } ::verb::core::SurfacePoint SurfacePoint_obj::fromUv(Float u,Float v){ HX_GC_STACKFRAME(&_hx_pos_959611cb896c5e6e_155_fromUv) HXDLIN( 155) return ::verb::core::SurfacePoint_obj::__alloc( HX_CTX ,null(),null(),::Array_obj< Float >::__new(2)->init(0,u)->init(1,v),null(),null()); } STATIC_HX_DEFINE_DYNAMIC_FUNC2(SurfacePoint_obj,fromUv,return ) SurfacePoint_obj::SurfacePoint_obj() { } void SurfacePoint_obj::__Mark(HX_MARK_PARAMS) { HX_MARK_BEGIN_CLASS(SurfacePoint); HX_MARK_MEMBER_NAME(uv,"uv"); HX_MARK_MEMBER_NAME(point,"point"); HX_MARK_MEMBER_NAME(normal,"normal"); HX_MARK_MEMBER_NAME(id,"id"); HX_MARK_MEMBER_NAME(degen,"degen"); HX_MARK_END_CLASS(); } void SurfacePoint_obj::__Visit(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(uv,"uv"); HX_VISIT_MEMBER_NAME(point,"point"); HX_VISIT_MEMBER_NAME(normal,"normal"); HX_VISIT_MEMBER_NAME(id,"id"); HX_VISIT_MEMBER_NAME(degen,"degen"); } ::hx::Val SurfacePoint_obj::__Field(const ::String &inName,::hx::PropertyAccess inCallProp) { switch(inName.length) { case 2: if (HX_FIELD_EQ(inName,"uv") ) { return ::hx::Val( uv ); } if (HX_FIELD_EQ(inName,"id") ) { return ::hx::Val( id ); } break; case 5: if (HX_FIELD_EQ(inName,"point") ) { return ::hx::Val( point ); } if (HX_FIELD_EQ(inName,"degen") ) { return ::hx::Val( degen ); } break; case 6: if (HX_FIELD_EQ(inName,"normal") ) { return ::hx::Val( normal ); } } return super::__Field(inName,inCallProp); } bool SurfacePoint_obj::__GetStatic(const ::String &inName, Dynamic &outValue, ::hx::PropertyAccess inCallProp) { switch(inName.length) { case 6: if (HX_FIELD_EQ(inName,"fromUv") ) { outValue = fromUv_dyn(); return true; } } return false; } ::hx::Val SurfacePoint_obj::__SetField(const ::String &inName,const ::hx::Val &inValue,::hx::PropertyAccess inCallProp) { switch(inName.length) { case 2: if (HX_FIELD_EQ(inName,"uv") ) { uv=inValue.Cast< ::Array< Float > >(); return inValue; } if (HX_FIELD_EQ(inName,"id") ) { id=inValue.Cast< int >(); return inValue; } break; case 5: if (HX_FIELD_EQ(inName,"point") ) { point=inValue.Cast< ::Array< Float > >(); return inValue; } if (HX_FIELD_EQ(inName,"degen") ) { degen=inValue.Cast< bool >(); return inValue; } break; case 6: if (HX_FIELD_EQ(inName,"normal") ) { normal=inValue.Cast< ::Array< Float > >(); return inValue; } } return super::__SetField(inName,inValue,inCallProp); } void SurfacePoint_obj::__GetFields(Array< ::String> &outFields) { outFields->push(HX_("uv",61,66,00,00)); outFields->push(HX_("point",50,b4,8f,c6)); outFields->push(HX_("normal",27,72,69,30)); outFields->push(HX_("id",db,5b,00,00)); outFields->push(HX_("degen",af,0f,23,d7)); super::__GetFields(outFields); }; #ifdef HXCPP_SCRIPTABLE static ::hx::StorageInfo SurfacePoint_obj_sMemberStorageInfo[] = { {::hx::fsObject /* ::Array< Float > */ ,(int)offsetof(SurfacePoint_obj,uv),HX_("uv",61,66,00,00)}, {::hx::fsObject /* ::Array< Float > */ ,(int)offsetof(SurfacePoint_obj,point),HX_("point",50,b4,8f,c6)}, {::hx::fsObject /* ::Array< Float > */ ,(int)offsetof(SurfacePoint_obj,normal),HX_("normal",27,72,69,30)}, {::hx::fsInt,(int)offsetof(SurfacePoint_obj,id),HX_("id",db,5b,00,00)}, {::hx::fsBool,(int)offsetof(SurfacePoint_obj,degen),HX_("degen",af,0f,23,d7)}, { ::hx::fsUnknown, 0, null()} }; static ::hx::StaticInfo *SurfacePoint_obj_sStaticStorageInfo = 0; #endif static ::String SurfacePoint_obj_sMemberFields[] = { HX_("uv",61,66,00,00), HX_("point",50,b4,8f,c6), HX_("normal",27,72,69,30), HX_("id",db,5b,00,00), HX_("degen",af,0f,23,d7), ::String(null()) }; ::hx::Class SurfacePoint_obj::__mClass; static ::String SurfacePoint_obj_sStaticFields[] = { HX_("fromUv",6b,9e,c6,b5), ::String(null()) }; void SurfacePoint_obj::__register() { SurfacePoint_obj _hx_dummy; SurfacePoint_obj::_hx_vtable = *(void **)&_hx_dummy; ::hx::Static(__mClass) = new ::hx::Class_obj(); __mClass->mName = HX_("verb.core.SurfacePoint",e3,db,72,fc); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &SurfacePoint_obj::__GetStatic; __mClass->mSetStaticField = &::hx::Class_obj::SetNoStaticField; __mClass->mStatics = ::hx::Class_obj::dupFunctions(SurfacePoint_obj_sStaticFields); __mClass->mMembers = ::hx::Class_obj::dupFunctions(SurfacePoint_obj_sMemberFields); __mClass->mCanCast = ::hx::TCanCast< SurfacePoint_obj >; #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = SurfacePoint_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = SurfacePoint_obj_sStaticStorageInfo; #endif ::hx::_hx_RegisterClass(__mClass->mName, __mClass); } } // end namespace verb } // end namespace core
35.423729
178
0.713397
7f19a37e3cf8de7fe7a3b62fee806693ff9a9037
7,847
cpp
C++
src/chainparams.cpp
ohtayoshida/lux-coin-qt-update
e7827cc1d72ce686df29a29c05f2e891d9f75731
[ "MIT" ]
null
null
null
src/chainparams.cpp
ohtayoshida/lux-coin-qt-update
e7827cc1d72ce686df29a29c05f2e891d9f75731
[ "MIT" ]
null
null
null
src/chainparams.cpp
ohtayoshida/lux-coin-qt-update
e7827cc1d72ce686df29a29c05f2e891d9f75731
[ "MIT" ]
null
null
null
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-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. // Masternode initilized & modified by 216k155. Used at your own risk. #include "assert.h" #include "chainparams.h" #include "main.h" #include "util.h" #include <boost/assign/list_of.hpp> using namespace boost::assign; struct SeedSpec6 { uint8_t addr[16]; uint16_t port; }; #include "chainparamsseeds.h" // Main network // Follow my guide to generate new genesis block // Convert the pnSeeds6 array into usable address objects. static void convertSeed6(std::vector<CAddress> &vSeedsOut, const SeedSpec6 *data, unsigned int count) { // It'll only connect to one or two seed nodes because once it connects, // it'll get a pile of addresses with newer timestamps. // Seed nodes are given a random 'last seen time' of between one and two // weeks ago. const int64_t nOneWeek = 7*24*60*60; for (unsigned int i = 0; i < count; i++) { struct in6_addr ip; memcpy(&ip, data[i].addr, sizeof(ip)); CAddress addr(CService(ip, data[i].port)); addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek; vSeedsOut.push_back(addr); } } class CMainParams : public CChainParams { public: CMainParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. pchMessageStart[0] = 0x64; // Modified pch messagestart by 216k155. pchMessageStart[1] = 0x1a; pchMessageStart[2] = 0x84; pchMessageStart[3] = 0x3l; vAlertPubKey = ParseHex("042d13c016ed91528241bcff222989769417eb10cdb679228c91e26e26900eb9fd053cd9f16a9a2894ad5ebbd551be1a4bd23bd55023679be17f0bd3a16e6fbeba"); // Lux coin modified pubkey nDefaultPort = 28666; nRPCPort = 9888; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20); // Build the genesis block. Note that the output of the genesis coinbase cannot // be spent as it did not originally exist in the database. const char* pszTimestamp = "Lux - Implemented New PHI Algo PoW/PoS Hybird - Parallel Masternode - ThankYou - 216k155"; // Input Activation code to activate blockchain std::vector<CTxIn> vin; vin.resize(1); vin[0].scriptSig = CScript() << 0 << CBigNum(42) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); std::vector<CTxOut> vout; vout.resize(1); vout[0].SetEmpty(); CTransaction txNew(1, 1507656633, vin, vout, 0); // epochtime 15:00:00 oct/10/2017 genesis.vtx.push_back(txNew); genesis.hashPrevBlock = 0; genesis.hashMerkleRoot = genesis.BuildMerkleTree(); genesis.nVersion = 1; genesis.nTime = 1507656633; // epochtime 15:00:00 oct/10/2017 genesis.nBits = 0x1e0fffff; // Generated nBits. Input right nBits to prevent nBits below minimum works error genesis.nNonce = 986946; // Input nNonce 0 // Generate genesis hash should take a while as exploit protection active in main.cpp // Anti exploitation activated. Note: need to wait until the generation finished for the right genesis block generated. Otherwise none of them are valid hashGenesisBlock = genesis.GetHash(); assert(hashGenesisBlock == uint256("0x00000759bb3da130d7c9aedae170da8335f5a0d01a9007e4c8d3ccd08ace6a42")); assert(genesis.hashMerkleRoot == uint256("0xe08ae0cfc35a1d70e6764f347fdc54355206adeb382446dd54c32cd0201000d3")); vSeeds.push_back(CDNSSeedData("sd1", "45.32.245.217")); vSeeds.push_back(CDNSSeedData("sd2", "45.63.25.110")); vSeeds.push_back(CDNSSeedData("sd3", "45.76.118.90")); vSeeds.push_back(CDNSSeedData("sd4", "136.243.89.142")); base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,48); // LUX Start letter L base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,48); base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,155); base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x07)(0x28)(0xA2)(0x4E).convert_to_container<std::vector<unsigned char> >(); base58Prefixes[EXT_SECRET_KEY] = list_of(0x03)(0xD8)(0xA1)(0xE5).convert_to_container<std::vector<unsigned char> >(); convertSeed6(vFixedSeeds, pnSeed6_main, ARRAYLEN(pnSeed6_main)); nLastPOWBlock = 6000000; // PoW end at block 6m } virtual const CBlock& GenesisBlock() const { return genesis; } virtual Network NetworkID() const { return CChainParams::MAIN; } virtual const vector<CAddress>& FixedSeeds() const { return vFixedSeeds; } protected: CBlock genesis; vector<CAddress> vFixedSeeds; }; static CMainParams mainParams; // Testnet // Dont need to configure anything under this line //------------------------------------------------// class CTestNetParams : public CMainParams { public: CTestNetParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. pchMessageStart[0] = 0xe1; pchMessageStart[1] = 0xc4; pchMessageStart[2] = 0xf8; pchMessageStart[3] = 0x21; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 16); vAlertPubKey = ParseHex("04cc24ab003c828cdd9cf4db2ebbde8e1cecb3bbfa8b3127fcb9dd9b84d44112080827ed7c49a648af9fe788ff42e316aee665879c553f099e55299d6b54edd7e0"); // input pubkey for later start nDefaultPort = 18065; nRPCPort = 9777; strDataDir = "testnet"; // Modify the testnet genesis block so the timestamp is valid for a later start. genesis.nBits = 0x1e0fffff; //504365055 Decimal Number genesis.nTime = 1504344001; genesis.nNonce = 1454059; // nNonce testnet should be 0 //assert(hashGenesisBlock == uint256("0x")); // need to generate new genesis block for later start vFixedSeeds.clear(); vSeeds.clear(); base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,77); // random letter input for testnet base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,192); base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,239); base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x35)(0x87)(0xCF).convert_to_container<std::vector<unsigned char> >(); base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x35)(0x83)(0x94).convert_to_container<std::vector<unsigned char> >(); convertSeed6(vFixedSeeds, pnSeed6_test, ARRAYLEN(pnSeed6_test)); nLastPOWBlock = 0x7fffffff; } virtual Network NetworkID() const { return CChainParams::TESTNET; } }; static CTestNetParams testNetParams; static CChainParams *pCurrentParams = &mainParams; const CChainParams &Params() { return *pCurrentParams; } void SelectParams(CChainParams::Network network) { switch (network) { case CChainParams::MAIN: pCurrentParams = &mainParams; break; case CChainParams::TESTNET: pCurrentParams = &testNetParams; break; default: assert(false && "Unimplemented network"); return; } } bool SelectParamsFromCommandLine() { bool fTestNet = GetBoolArg("-testnet", false); if (fTestNet) { SelectParams(CChainParams::TESTNET); } else { SelectParams(CChainParams::MAIN); } return true; }
40.448454
198
0.676309
7f1be9275d460561032e326da3d1e606d6dc1290
967
cpp
C++
src/Calibrate.cpp
kontramind/zivid-python
b18582c0cdef261d42fb737c7eee71e350048569
[ "BSD-3-Clause" ]
null
null
null
src/Calibrate.cpp
kontramind/zivid-python
b18582c0cdef261d42fb737c7eee71e350048569
[ "BSD-3-Clause" ]
null
null
null
src/Calibrate.cpp
kontramind/zivid-python
b18582c0cdef261d42fb737c7eee71e350048569
[ "BSD-3-Clause" ]
null
null
null
#include <Zivid/HandEye/Calibrate.h> #include <ZividPython/Calibrate.h> #include <ZividPython/CalibrationResidual.h> #include <ZividPython/Matrix.h> #include <pybind11/pybind11.h> #include <pybind11/stl.h> namespace py = pybind11; namespace ZividPython { void wrapClass(pybind11::class_<Zivid::HandEye::CalibrationOutput> pyClass) { pyClass.def("valid", &Zivid::HandEye::CalibrationOutput::valid) .def("handEyeTransform", [](const Zivid::HandEye::CalibrationOutput &calibrationOutput) { return Conversion::toPy(calibrationOutput.handEyeTransform()); }) .def("perPoseCalibrationResiduals", &Zivid::HandEye::CalibrationOutput::perPoseCalibrationResiduals); } void wrapClass(pybind11::class_<Zivid::HandEye::CalibrationInput> pyClass) { pyClass.def(py::init<Zivid::HandEye::Pose, Zivid::HandEye::DetectionResult>()); } } // namespace ZividPython
33.344828
113
0.68666
7f1e039ff387c51c40d914d25c573aef36a51a2b
24,259
cpp
C++
Source/AllProjects/CQCIGKit/CQCIGKit_DriverClient.cpp
MarkStega/CQC
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
[ "MIT" ]
51
2020-12-26T18:17:16.000Z
2022-03-15T04:29:35.000Z
Source/AllProjects/CQCIGKit/CQCIGKit_DriverClient.cpp
MarkStega/CQC
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
[ "MIT" ]
null
null
null
Source/AllProjects/CQCIGKit/CQCIGKit_DriverClient.cpp
MarkStega/CQC
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
[ "MIT" ]
4
2020-12-28T07:24:39.000Z
2021-12-29T12:09:37.000Z
// // FILE NAME: CQCIGKit_DriverClient.cpp // // AUTHOR: Dean Roddey // // CREATED: 11/16/2001 // // COPYRIGHT: Charmed Quark Systems, Ltd @ 2020 // // This software is copyrighted by 'Charmed Quark Systems, Ltd' and // the author (Dean Roddey.) It is licensed under the MIT Open Source // license: // // https://opensource.org/licenses/MIT // // DESCRIPTION: // // Implements the standard CQC client side driver window, from which all // client drivers derive. // // CAVEATS/GOTCHAS: // // LOG: // // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include "CQCIGKit_.hpp" // ---------------------------------------------------------------------------- // Do our RTTI macros // ---------------------------------------------------------------------------- RTTIDecls(TCQCDriverClient,TGenericWnd) // --------------------------------------------------------------------------- // CLASS: TCQCDriverClient // PREFIX: wnd // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- // TCQCDriverClient: Constructors and Destructor // --------------------------------------------------------------------------- TCQCDriverClient::TCQCDriverClient( const TCQCDriverObjCfg& cqcdcThis , const TString& strDriverClass , const tCQCKit::EActLevels eActivityLevel , const TCQCUserCtx& cuctxToUse) : TGenericWnd() , m_bCleanupDone(kCIDLib::False) , m_bFirstTimer(kCIDLib::True) , m_c4PollChanges(0) , m_cuctxToUse(cuctxToUse) , m_eActivityLevel(eActivityLevel) , m_eConnState(tCQCGKit::EConnStates::SrvOffline) , m_ePrevState(tCQCGKit::EConnStates::SrvOffline) , m_cqcdcThis(cqcdcThis) , m_thrPoll ( facCIDLib().strNextThreadName(strDriverClass + TString(L"Poll")) , TMemberFunc<TCQCDriverClient>(this, &TCQCDriverClient::ePollThread) ) , m_tmidUpdate(kCIDCtrls::tmidInvalid) { } TCQCDriverClient::~TCQCDriverClient() { } // --------------------------------------------------------------------------- // TCQCDriverClient: Public, non-virtual methods // --------------------------------------------------------------------------- const TCQCDriverObjCfg& TCQCDriverClient::cqcdcThis() const { return m_cqcdcThis; } const TCQCUserCtx& TCQCDriverClient::cuctxToUse() const { return m_cuctxToUse; } tCIDLib::TVoid TCQCDriverClient::CreateClDrvWnd(const TWindow& wndParent , const TArea& areaInit , const tCIDCtrls::TWndId widToUse) { // // And now call down to create the window. We are initially invisible and our parent // will show us once he's got us sized/positioned appropriately. // TWindow::CreateWnd ( wndParent.hwndSafe() , kCIDCtrls::pszCustClass , L"" , areaInit , tCIDCtrls::EWndStyles::ClippingChild , tCIDCtrls::EExWndStyles::ControlParent , widToUse ); } tCQCGKit::EConnStates TCQCDriverClient::eConnState() const { return m_eConnState; } // Just a convenience wrapper that we pass on to the user context tCQCKit::EUserRoles TCQCDriverClient::eUserRole() const { return m_cuctxToUse.eUserRole(); } tCQCKit::TCQCSrvProxy& TCQCDriverClient::orbcServer() { return m_orbcServer; } TMutex* TCQCDriverClient::pmtxSync() const { return &m_mtxSync; } const TCQCSecToken& TCQCDriverClient::sectUser() const { return m_cuctxToUse.sectUser(); } const TString& TCQCDriverClient::strMoniker() const { return m_cqcdcThis.strMoniker(); } // The client program will call this after the windows are all created and ready tCIDLib::TVoid TCQCDriverClient::StartDriver() { // If we have already been run and stopped, then that's an error if (m_bCleanupDone) { facCQCGKit().LogMsg ( CID_FILE , CID_LINE , kIGKitErrs::errcDrv_AlreadyStopped , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Already , m_cqcdcThis.strMoniker() ); } // Start the poll thread m_thrPoll.Start(); // // Start the update timer. Initially we set a kind of long time, to // give the client time to come up and get displayed. The first time // the timer gets called, he will reset the period to the appropriate // period. // // <TBD> Later on, we can use the m_eActivityLevel setting to adjust // these to optimize overhead to match the rate that the device's data // is likely to change. // m_tmidUpdate = tmidStartTimer(3000); } // // The client program will call this top stop the driver (before it destroys our // parent window of course!) // tCIDLib::TVoid TCQCDriverClient::StopDriver() { // Stop our update time if running try { if (m_tmidUpdate != kCIDCtrls::tmidInvalid) { StopTimer(m_tmidUpdate); m_tmidUpdate = kCIDCtrls::tmidInvalid; } } catch(TError& errToCatch) { if (facCQCGKit().bShouldLog(errToCatch)) { errToCatch.AddStackLevel(CID_FILE, CID_LINE); TModule::LogEventObj(errToCatch); } if (facCQCGKit().bLogFailures()) { facCQCGKit().LogMsg ( CID_FILE , CID_LINE , kGKitMsgs::midStatus_StopTimer , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Internal , m_cqcdcThis.strMoniker() ); } } catch(...) { if (facCQCGKit().bLogFailures()) { facCQCGKit().LogMsg ( CID_FILE , CID_LINE , kGKitMsgs::midStatus_StopTimer , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Internal , m_cqcdcThis.strMoniker() ); } } // Stop the poll thread try { if (m_thrPoll.bIsRunning()) { m_thrPoll.ReqShutdownSync(10000); m_thrPoll.eWaitForDeath(5000); } } catch(TError& errToCatch) { if (facCQCGKit().bShouldLog(errToCatch)) { errToCatch.AddStackLevel(CID_FILE, CID_LINE); TModule::LogEventObj(errToCatch); } if (facCQCGKit().bLogFailures()) { facCQCGKit().LogMsg ( CID_FILE , CID_LINE , kGKitMsgs::midStatus_StopClientDrvPollThr , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Internal , m_cqcdcThis.strMoniker() ); } } catch(...) { if (facCQCGKit().bLogFailures()) { facCQCGKit().LogMsg ( CID_FILE , CID_LINE , kGKitMsgs::midStatus_StopClientDrvPollThr , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Internal , m_cqcdcThis.strMoniker() ); } } // Let the derived class do its cleanup try { if (!m_bCleanupDone) { m_bCleanupDone = kCIDLib::True; DoCleanup(); } } catch(TError& errToCatch) { errToCatch.AddStackLevel(CID_FILE, CID_LINE); TModule::LogEventObj(errToCatch); } // Drop the server admin client proxy, if we have one try { m_orbcServer.DropRef(); } catch(TError& errToCatch) { if (facCQCGKit().bShouldLog(errToCatch)) { errToCatch.AddStackLevel(CID_FILE, CID_LINE); TModule::LogEventObj(errToCatch); } if (facCQCGKit().bLogFailures()) { facCQCGKit().LogMsg ( CID_FILE , CID_LINE , kGKitMsgs::midStatus_CleanupProxy , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Internal , m_cqcdcThis.strMoniker() ); } } catch(...) { if (facCQCGKit().bLogFailures()) { facCQCGKit().LogMsg ( CID_FILE , CID_LINE , kGKitMsgs::midStatus_CleanupProxy , tCIDLib::ESeverities::Status , tCIDLib::EErrClasses::Internal , m_cqcdcThis.strMoniker() ); } } } // --------------------------------------------------------------------------- // TCQCDriverClient: Protected, inherited methods // --------------------------------------------------------------------------- // Do it all in the paint, where we are clipped to our children tCIDLib::TBoolean TCQCDriverClient::bEraseBgn(TGraphDrawDev&) { return kCIDLib::True; } tCIDLib::TBoolean TCQCDriverClient::bPaint(TGraphDrawDev& gdevToUse, const TArea& areaUpdate) { gdevToUse.Fill(areaUpdate, rgbBgnFill()); return kCIDLib::True; } tCIDLib::TVoid TCQCDriverClient::Destroyed() { // Just in case... StopDriver(); TParent::Destroyed(); } tCIDLib::TVoid TCQCDriverClient::Timer(const tCIDCtrls::TTimerId tmidToDo) { // If the first timer, reset the period now if (m_bFirstTimer) { m_bFirstTimer = kCIDLib::False; ResetTimer(m_tmidUpdate, 1000); } // // We have to lock out the poll thread during this. Use the form that let's us // conditionally lock. If the poll thread should hang up for some reason, we // don't want to lock up the interface. We use a short timeout so that, if the // poll thread is straining because the remote servers are down, we won't make // the interface overly spongy. // TLocker lockrSync(&m_mtxSync, kCIDLib::False); if (!lockrSync.bLock(1)) return; try { // // If we have no changes, then just return, cause there is nothing to do. // Else, reset the counter and let the derived class update itself with this // new data. // if (!m_c4PollChanges) return; m_c4PollChanges = 0; // // See if the connection state has changed from the last one the bgn thread // left us. // if (m_eConnState != m_ePrevState) { // // Remember the previous state, then get it into sync with the current state. // We want to do this before we make any call, in case it throws. // const tCQCGKit::EConnStates eOldState = m_ePrevState; m_ePrevState = m_eConnState; // // If we have connected or disconnected, then let the derived class know so // that he can update current status display stuff. // if ((eOldState != tCQCGKit::EConnStates::Connected) && (m_eConnState == tCQCGKit::EConnStates::Connected)) { // Tell the parent tab window that we are not in error state TTabWindow* pwndPar = dynamic_cast<TTabWindow*>(pwndParent()); if (pwndPar) pwndPar->SetState(tCIDCtrls::ETabStates::Normal, kCIDLib::True); Connected(); } else if ((eOldState == tCQCGKit::EConnStates::Connected) && (m_eConnState != tCQCGKit::EConnStates::Connected)) { // Tell the parent tab window that we are in error state TTabWindow* pwndPar = dynamic_cast<TTabWindow*>(pwndParent()); if (pwndPar) pwndPar->SetState(tCIDCtrls::ETabStates::Errors, kCIDLib::True); LostConnection(); } } else if (m_eConnState == tCQCGKit::EConnStates::Connected) { // // Its just a normal scenario. We are connected so let the driver display // new data if it has any, left for it by the polling thread. // UpdateDisplayData(); } } catch(TError& errToCatch) { // // Eat it, since there isn't much we can do, but log a message if // debugging is on. // #if CID_DEBUG_ON if (facCQCGKit().bShouldLog(errToCatch)) { errToCatch.AddStackLevel(CID_FILE, CID_LINE); TModule::LogEventObj(errToCatch); } #endif } catch(...) { // // Eat it, since there isn't much we can do, but log a message if // debugging is on. // #if CID_DEBUG_ON #endif } } // --------------------------------------------------------------------------- // Private, non-virtual methods // --------------------------------------------------------------------------- // // This method is called from the poll thread when its time to do another poll cycle. // We just break it out in order to keep that method from getting messy and bloated. // tCIDLib::TVoid TCQCDriverClient::DoPollCycle() { // Lock during this TLocker lockrSync(&m_mtxSync); // // Ok, we get called here from the poll thread (and once from the main thread on // startup to kickstart things.) We are responsible for either getting ourself up // to the 'connected' state, or if already there for polling data and backing our // state off if something goes awry. // try { // // We'll start with being completely disconnected from the server, in which case // we need to try to get a client proxy. If this fails, it'll throw and we'll // catch below and stay off line. If it works ok, then update to assuming the // device is offline, and indicate that state changes have happened. // if (m_eConnState == tCQCGKit::EConnStates::SrvOffline) { // Drop any old reference if we have one if (m_orbcServer.pobjData()) m_orbcServer.DropRef(); // // Try to get a new client proxy. If it works, then move our state up. // Catch exceptions since we are going to get them if the server isn't up, // and we just want to eat those and stay offline. // try { m_orbcServer = facCQCKit().orbcCQCSrvAdminProxy(m_cqcdcThis.strMoniker()); m_eConnState = tCQCGKit::EConnStates::DevOffline; m_c4PollChanges++; } catch(TError& errToCatch) { // If it anything besides the driver not being loaded, rethrow if (!errToCatch.bCheckEvent(facCQCKit().strName() , kKitErrs::errcRem_DrvNotFound)) { errToCatch.AddStackLevel(CID_FILE, CID_LINE); throw; } } } // // Ok, we are now connected to the server, but it might not be connected to // its device. So if we last saw it offline, let's ask it for status. If it // now shows connected, we get tell the driver to do one time on connect // stuff, and move to connected state. We bump our changes counter to make // sure the GUI thread updates in responses. // if (m_eConnState == tCQCGKit::EConnStates::DevOffline) { tCIDLib::TCard4 c4ThreadId; tCQCKit::EDrvStates eState; tCQCKit::EVerboseLvls eVerbose; m_orbcServer->QueryDriverState ( m_cqcdcThis.strMoniker(), eState, eVerbose, c4ThreadId ); if (eState == tCQCKit::EDrvStates::Connected) { // // Ask the derived class to get any 'one time' info that it gets from // it's server driver upon connect. If the driver class doesn't throw // an error, we'll update our status. // if (bGetConnectData(m_orbcServer)) { m_eConnState = tCQCGKit::EConnStates::Connected; m_c4PollChanges++; } } } // // And if we are current fully connected, we just want to ask the derived class // to poll for data. Its return value tells us if new data has showed up, or if // he cannot talk to his device or server, in which case we update the status // accordingly. // if (m_eConnState == tCQCGKit::EConnStates::Connected) { if (bDoPoll(m_orbcServer)) m_c4PollChanges++; } } catch(const TError& errToCatch) { if (!m_orbcServer.pobjData() || m_orbcServer->bCheckForLostConnection()) { // We lost connection to the server m_eConnState = tCQCGKit::EConnStates::SrvOffline; m_c4PollChanges++; m_orbcServer.DropRef(); } else if (errToCatch.bCheckEvent(facCQCKit().strName(), kKitErrs::errcDrv_NotOnline) || errToCatch.bCheckEvent(facCQCKit().strName(), kKitErrs::errcDrv_NotFound)) { if (m_eConnState != tCQCGKit::EConnStates::DevOffline) { // The device isn't there for some reason m_eConnState = tCQCGKit::EConnStates::DevOffline; m_c4PollChanges++; } } else if (errToCatch.bCheckEvent(facCIDOrbUC().strName() , kOrbUCErrs::errcSrv_NSNotFound)) { // We couldn't find the server in the name server if (m_eConnState != tCQCGKit::EConnStates::SrvOffline) { m_eConnState = tCQCGKit::EConnStates::SrvOffline; m_c4PollChanges++; } } else { // Not something obvious, so log it if logging warnings if (facCQCGKit().bLogWarnings() && !errToCatch.bLogged()) TModule::LogEventObj(errToCatch); if (m_eConnState == tCQCGKit::EConnStates::Connected) { // We think we are connected, so try to make a call to the driver try { tCIDLib::TCard4 c4Tmp; m_orbcServer->c4QueryDriverId(m_cqcdcThis.strMoniker(), c4Tmp); // // It worked, so just assume it was some dumb error in the // driver's GUI code. // } catch(const TError& errToCatch) { // // If it's not found, then we just lost the device, // else assume we lost the server. // if (errToCatch.eClass() == tCIDLib::EErrClasses::NotFound) m_eConnState = tCQCGKit::EConnStates::DevOffline; else m_eConnState = tCQCGKit::EConnStates::SrvOffline; m_c4PollChanges++; } catch(...) { // Assume we lost the connection m_eConnState = tCQCGKit::EConnStates::SrvOffline; m_c4PollChanges++; } } else if (m_eConnState != tCQCGKit::EConnStates::SrvOffline) { m_eConnState = tCQCGKit::EConnStates::SrvOffline; m_c4PollChanges++; } } } catch(...) { // // We don't have an exception to go by, so we have to just manually // try the link and see if this happened becasue we lost the // connection or not. We'll just try to get the driver id, which // is a simple call that will check for out driver being there. // // If we aren't connected, just assume the worst case and say the // server is offline and force us to completely reconnect. // if (m_eConnState == tCQCGKit::EConnStates::Connected) { try { tCIDLib::TCard4 c4Tmp; m_orbcServer->c4QueryDriverId(m_cqcdcThis.strMoniker(), c4Tmp); // // It worked, so just assume it was some dumb error in the // driver's GUI code. // } catch(const TError& errToCatch) { // // If it's not found, then we just lost the device, // else assume we lost the server. // if (errToCatch.eClass() == tCIDLib::EErrClasses::NotFound) m_eConnState = tCQCGKit::EConnStates::DevOffline; else m_eConnState = tCQCGKit::EConnStates::SrvOffline; m_c4PollChanges++; } catch(...) { // Assume we lost the connection m_eConnState = tCQCGKit::EConnStates::SrvOffline; m_c4PollChanges++; } } else if (m_eConnState != tCQCGKit::EConnStates::SrvOffline) { m_eConnState = tCQCGKit::EConnStates::SrvOffline; m_c4PollChanges++; } } } // // This is the polling thread. This is started up when the window is created, // and runs until the window is closed. It keeps up with our current connect // state and does what is necessary to run the show wrt to staying connected // to the server and polling it for new data. // tCIDLib::EExitCodes TCQCDriverClient::ePollThread(TThread& thrThis, tCIDLib::TVoid*) { // Let the thread that started us go now thrThis.Sync(); // // To avoid setting a try block on every round, we use a double loop. // That lets us catch exceptions and restart. // tCIDLib::TBoolean bExit = kCIDLib::False; while (!bExit) { try { while (!bExit) { if (m_eConnState == tCQCGKit::EConnStates::Connected) { if (!thrThis.bSleep(2000)) { bExit = kCIDLib::True; continue; } } else { if (!thrThis.bSleep(4000)) { bExit = kCIDLib::True; continue; } } // // Call our method that does a standard poll cycle. According // to our current connect status, this guy does what is // necessary to keep things moving along and will update our // state accordingly. // DoPollCycle(); } } catch(TError& errToCatch) { if (facCQCGKit().bLogWarnings()) { errToCatch.AddStackLevel(CID_FILE, CID_LINE); TModule::LogEventObj(errToCatch); } } catch(...) { if (facCQCGKit().bLogFailures()) { facCQCGKit().LogMsg ( CID_FILE , CID_LINE , kGKitMsgs::midStatus_PollThreadExcept , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Internal , m_cqcdcThis.strMoniker() ); } } } return tCIDLib::EExitCodes::Normal; }
30.668774
93
0.513294
7f205320f9c7145eca5fbd3fc58c41693d413567
20,948
cpp
C++
libraries/plugins/chain/chain_plugin_full.cpp
SophiaTX/SophiaTx-Blockchain
c964691c020962ad1aba8263c0d8a78a9fa27e45
[ "MIT" ]
8
2018-07-25T20:42:43.000Z
2019-03-11T03:14:09.000Z
libraries/plugins/chain/chain_plugin_full.cpp
SophiaTX/SophiaTx-Blockchain
c964691c020962ad1aba8263c0d8a78a9fa27e45
[ "MIT" ]
13
2018-07-25T17:41:28.000Z
2019-01-25T13:38:11.000Z
libraries/plugins/chain/chain_plugin_full.cpp
SophiaTX/SophiaTx-Blockchain
c964691c020962ad1aba8263c0d8a78a9fa27e45
[ "MIT" ]
11
2018-07-25T14:34:13.000Z
2019-05-03T13:29:37.000Z
#include <sophiatx/chain/database/database_exceptions.hpp> #include <sophiatx/chain/genesis_state.hpp> #include <sophiatx/plugins/chain/chain_plugin_full.hpp> #include <sophiatx/chain/database/database.hpp> #include <sophiatx/utilities/benchmark_dumper.hpp> #include <sophiatx/chain/get_config.hpp> #include <sophiatx/egenesis/egenesis.hpp> #include <fc/string_utils.hpp> #include <fc/io/fstream.hpp> #include <boost/asio.hpp> #include <boost/optional.hpp> #include <boost/bind.hpp> #include <boost/preprocessor/stringize.hpp> #include <boost/thread/future.hpp> #include <thread> #include <memory> #include <iostream> namespace sophiatx { namespace plugins { namespace chain { using namespace sophiatx; using fc::flat_map; using sophiatx::chain::block_id_type; namespace asio = boost::asio; chain_plugin_full::chain_plugin_full() : write_queue( 64 ) { db_ = std::make_shared<database>(); } chain_plugin_full::~chain_plugin_full() { stop_write_processing(); } struct write_request_visitor { write_request_visitor() {} std::shared_ptr<database> db; uint32_t skip = 0; std::optional< fc::exception >* except; typedef bool result_type; bool operator()( const signed_block* block ) { bool result = false; try { result = db->push_block( *block, skip ); } catch( fc::exception& e ) { *except = e; } catch( ... ) { *except = fc::unhandled_exception( FC_LOG_MESSAGE( warn, "Unexpected exception while pushing block." ), std::current_exception() ); } return result; } bool operator()( const signed_transaction* trx ) { bool result = false; try { db->push_transaction( *trx ); result = true; } catch( fc::exception& e ) { *except = e; } catch( ... ) { *except = fc::unhandled_exception( FC_LOG_MESSAGE( warn, "Unexpected exception while pushing block." ), std::current_exception() ); } return result; } bool operator()( generate_block_request* req ) { bool result = false; try{ req->block = db->generate_block( req->when, req->witness_owner, req->block_signing_private_key, req->skip ); result = true; }catch( fc::exception& e ){ *except = e; } catch( ... ) { *except = fc::unhandled_exception( FC_LOG_MESSAGE( warn, "Unexpected exception while pushing block." ), std::current_exception() ); } return result; } }; struct request_promise_visitor { request_promise_visitor(){} typedef void result_type; template< typename T > void operator()( T* t ) { t->set_value(); } }; void chain_plugin_full::start_write_processing() { write_processor_thread = std::make_shared< std::thread >( [&](){ bool is_syncing = true; write_context* cxt; fc::time_point_sec start = fc::time_point::now(); write_request_visitor req_visitor; req_visitor.db = std::static_pointer_cast<database>(db_); request_promise_visitor prom_visitor; /* This loop monitors the write request queue and performs writes to the database. These * can be blocks or pending transactions. Because the caller needs to know the success of * the write and any exceptions that are thrown, a write context is passed in the queue * to the processing thread which it will use to store the results of the write. It is the * caller's responsibility to ensure the pointer to the write context remains valid until * the contained promise is complete. * * The loop has two modes, sync mode and live mode. In sync mode we want to process writes * as quickly as possible with minimal overhead. The outer loop busy waits on the queue * and the inner loop drains the queue as quickly as possible. We exit sync mode when the * head block is within 1 minute of system time. * * Live mode needs to balance between processing pending writes and allowing readers access * to the database. It will batch writes together as much as possible to minimize lock * overhead but will willingly give up the write lock after 500ms. The thread then sleeps for * 10ms. This allows time for readers to access the database as well as more writes to come * in. When the node is live the rate at which writes come in is slower and busy waiting is * not an optimal use of system resources when we could give CPU time to read threads. */ while( running ) { if( !is_syncing ) start = fc::time_point::now(); if( write_queue.pop( cxt ) ) { db_->with_write_lock( [&](){ while( true ) { req_visitor.skip = cxt->skip; req_visitor.except = &(cxt->except); cxt->success = cxt->req_ptr.visit( req_visitor ); cxt->prom_ptr.visit( prom_visitor ); if( is_syncing && start - db_->head_block_time() < fc::minutes(1) ) { start = fc::time_point::now(); is_syncing = false; } if( !is_syncing && write_lock_hold_time >= 0 && fc::time_point::now() - start > fc::milliseconds( write_lock_hold_time ) ) { break; } if( !write_queue.pop( cxt ) ) { break; } } }); } if( !is_syncing ) { boost::this_thread::sleep_for(boost::chrono::milliseconds(10)); } else boost::this_thread::sleep_for(boost::chrono::milliseconds(1)); } }); } void chain_plugin_full::stop_write_processing() { running = false; if( write_processor_thread ) write_processor_thread->join(); write_processor_thread.reset(); } void chain_plugin_full::set_program_options(options_description& cli, options_description& cfg) { cfg.add_options() ("genesis-json", bpo::value<bfs::path>(), "the location of the genesis file in JSON format") ("shared-file-size", bpo::value<string>()->default_value("24G"), "Size of the shared memory file. Default: 24G. If running a full node, increase this value to 200G.") ("shared-file-full-threshold", bpo::value<uint16_t>()->default_value(0), "A 2 precision percentage (0-10000) that defines the threshold for when to autoscale the shared memory file. Setting this to 0 disables autoscaling. Recommended value for consensus node is 9500 (95%). Full node is 9900 (99%)" ) ("shared-file-scale-rate", bpo::value<uint16_t>()->default_value(0), "A 2 precision percentage (0-10000) that defines how quickly to scale the shared memory file. When autoscaling occurs the file's size will be increased by this percent. Setting this to 0 disables autoscaling. Recommended value is between 1000-2000 (10-20%)" ) ("checkpoint,c", bpo::value<vector<string>>()->composing(), "Pairs of [BLOCK_NUM,BLOCK_ID] that should be enforced as checkpoints.") ("flush-state-interval", bpo::value<uint32_t>(), "flush shared memory changes to disk every N blocks") ; cli.add_options() ("replay-blockchain", bpo::bool_switch()->default_value(false), "clear chain database and replay all blocks" ) ("resync-blockchain", bpo::bool_switch()->default_value(false), "clear chain database and block log" ) ("stop-replay-at-block", bpo::value<uint32_t>(), "Stop and exit after reaching given block number") ("set-benchmark-interval", bpo::value<uint32_t>(), "Print time and memory usage every given number of blocks") ("dump-memory-details", bpo::bool_switch()->default_value(false), "Dump database objects memory usage info. Use set-benchmark-interval to set dump interval.") ("check-locks", bpo::bool_switch()->default_value(false), "Check correctness of chainbase locking" ) ("validate-database-invariants", bpo::bool_switch()->default_value(false), "Validate all supply invariants check out" ) ("initminer-mining-pubkey", bpo::value<std::string>(), "initminer public key for mining. Used only for private nets.") ("initminer-account-pubkey", bpo::value<std::string>(), "initminer public key for account operations. Used only for private nets.") ; } void chain_plugin_full::plugin_initialize(const variables_map& options) { shared_memory_size = fc::parse_size( options.at( "shared-file-size" ).as< string >() ); if( options.count( "shared-file-full-threshold" ) ) shared_file_full_threshold = options.at( "shared-file-full-threshold" ).as< uint16_t >(); if( options.count( "shared-file-scale-rate" ) ) shared_file_scale_rate = options.at( "shared-file-scale-rate" ).as< uint16_t >(); bool private_net = false; if (options.count("initminer-mining-pubkey") ) { private_net = true; } auto initial_state = [&] { if( (private_net && options.count("initminer-account-pubkey")) || (private_net && options.count("genesis-json") == 0 ) ){ genesis_state_type genesis; genesis.genesis_time = time_point_sec::from_iso_string("2018-01-01T08:00:00"); genesis.initial_balace = 0; genesis.initial_public_key = options.count("initminer-account-pubkey") ? public_key_type(options.at( "initminer-account-pubkey" ).as< std::string >()) : public_key_type(options.at( "initminer-mining-pubkey" ).as< std::string >()); genesis.initial_public_mining_key = public_key_type(options.at( "initminer-mining-pubkey" ).as< std::string >()); genesis.is_private_net = true; fc::sha256::encoder enc; fc::raw::pack( enc, genesis ); genesis.initial_chain_id = enc.result(); return genesis; } if( options.count("genesis-json") ) { std::string genesis_str; fc::read_file_contents( options.at("genesis-json").as<boost::filesystem::path>(), genesis_str ); genesis_state_type genesis = fc::json::from_string( genesis_str ).as<genesis_state_type>(); genesis.initial_chain_id = fc::sha256::hash( genesis_str); genesis.is_private_net = private_net; return genesis; } else { std::string egenesis_json; sophiatx::egenesis::compute_egenesis_json( egenesis_json ); FC_ASSERT( !egenesis_json.empty() ); FC_ASSERT( sophiatx::egenesis::get_egenesis_json_hash() == fc::sha256::hash( egenesis_json ) ); auto genesis = fc::json::from_string( egenesis_json ).as<genesis_state_type>(); genesis.initial_chain_id = fc::sha256::hash( egenesis_json ); return genesis; } }; genesis = initial_state(); chain::sophiatx_config::init(genesis); replay = options.at( "replay-blockchain").as<bool>(); resync = options.at( "resync-blockchain").as<bool>(); stop_replay_at = options.count( "stop-replay-at-block" ) ? options.at( "stop-replay-at-block" ).as<uint32_t>() : 0; benchmark_interval = options.count( "set-benchmark-interval" ) ? options.at( "set-benchmark-interval" ).as<uint32_t>() : 0; check_locks = options.at( "check-locks" ).as< bool >(); validate_invariants = options.at( "validate-database-invariants" ).as<bool>(); dump_memory_details = options.at( "dump-memory-details" ).as<bool>(); if( options.count( "flush-state-interval" ) ) flush_interval = options.at( "flush-state-interval" ).as<uint32_t>(); else flush_interval = 10000; if(options.count("checkpoint")) { auto cps = options.at("checkpoint").as<vector<string>>(); loaded_checkpoints.reserve(cps.size()); for(const auto& cp : cps) { auto item = fc::json::from_string(cp).as<std::pair<uint32_t,block_id_type>>(); loaded_checkpoints[item.first] = item.second; } } } #define BENCHMARK_FILE_NAME "replay_benchmark.json" void chain_plugin_full::plugin_startup() { ilog( "Starting chain with shared_file_size: ${n} bytes", ("n", shared_memory_size) ); chain_id_type chain_id = genesis.compute_chain_id(); shared_memory_dir = app().data_dir() / chain_id.str() / "blockchain"; // correct directories, TODO can be removed after next HF2 if( ! genesis.is_private_net && bfs::exists( app().data_dir() / "blockchain" ) ){ bfs::create_directories ( shared_memory_dir ); bfs::rename( app().data_dir() / "blockchain", shared_memory_dir ); } ilog("Starting node with chain id ${i}", ("i", chain_id)); start_write_processing(); if(resync) { wlog("resync requested: deleting block log and shared memory"); db_->wipe( shared_memory_dir, true ); } db_->set_flush_interval( flush_interval ); db_->add_checkpoints( loaded_checkpoints ); db_->set_require_locking( check_locks ); bool dump_memory_details_ = dump_memory_details; sophiatx::utilities::benchmark_dumper dumper; const auto& abstract_index_cntr = db_->get_abstract_index_cntr(); typedef sophiatx::utilities::benchmark_dumper::index_memory_details_cntr_t index_memory_details_cntr_t; auto get_indexes_memory_details = [dump_memory_details_, &abstract_index_cntr] (index_memory_details_cntr_t& index_memory_details_cntr, bool onlyStaticInfo) { if (!dump_memory_details_) return; for (auto idx : abstract_index_cntr) { auto info = idx->get_statistics(onlyStaticInfo); index_memory_details_cntr.emplace_back(std::move(info._value_type_name), info._item_count, info._item_sizeof, info._item_additional_allocation, info._additional_container_allocation); } }; database::open_args db_open_args; db_open_args.shared_mem_dir = shared_memory_dir; db_open_args.shared_file_size = shared_memory_size; db_open_args.shared_file_full_threshold = shared_file_full_threshold; db_open_args.shared_file_scale_rate = shared_file_scale_rate; db_open_args.do_validate_invariants = validate_invariants; db_open_args.stop_replay_at = stop_replay_at; auto benchmark_lambda = [&dumper, &get_indexes_memory_details, dump_memory_details_] ( uint32_t current_block_number, const chainbase::database::abstract_index_cntr_t& abstract_index_cntr ) { if( current_block_number == 0 ) // initial call { typedef sophiatx::utilities::benchmark_dumper::database_object_sizeof_cntr_t database_object_sizeof_cntr_t; auto get_database_objects_sizeofs = [dump_memory_details_, &abstract_index_cntr] (database_object_sizeof_cntr_t& database_object_sizeof_cntr) { if (!dump_memory_details_) return; for (auto idx : abstract_index_cntr) { auto info = idx->get_statistics(true); database_object_sizeof_cntr.emplace_back(std::move(info._value_type_name), info._item_sizeof); } }; dumper.initialize(get_database_objects_sizeofs, BENCHMARK_FILE_NAME); return; } const sophiatx::utilities::benchmark_dumper::measurement& measure = dumper.measure(current_block_number, get_indexes_memory_details); ilog( "Performance report at block ${n}. Elapsed time: ${rt} ms (real), ${ct} ms (cpu). Memory usage: ${cm} (current), ${pm} (peak) kilobytes.", ("n", current_block_number) ("rt", measure.real_ms) ("ct", measure.cpu_ms) ("cm", measure.current_mem) ("pm", measure.peak_mem) ); }; if(replay) { ilog("Replaying blockchain on user request."); uint32_t last_block_number = 0; db_open_args.benchmark = sophiatx::chain::database::TBenchmark(benchmark_interval, benchmark_lambda); last_block_number = db_->reindex( db_open_args, genesis); if( benchmark_interval > 0 ) { const sophiatx::utilities::benchmark_dumper::measurement& total_data = dumper.dump(true, get_indexes_memory_details); ilog( "Performance report (total). Blocks: ${b}. Elapsed time: ${rt} ms (real), ${ct} ms (cpu). Memory usage: ${cm} (current), ${pm} (peak) kilobytes.", ("b", total_data.block_number) ("rt", total_data.real_ms) ("ct", total_data.cpu_ms) ("cm", total_data.current_mem) ("pm", total_data.peak_mem) ); } if( stop_replay_at > 0 && stop_replay_at == last_block_number ) { ilog("Stopped blockchain replaying on user request. Last applied block number: ${n}.", ("n", last_block_number)); appbase::app().quit(); return; } } else { db_open_args.benchmark = sophiatx::chain::database::TBenchmark(dump_memory_details_, benchmark_lambda); try { ilog("Opening shared memory from ${path}", ("path",shared_memory_dir.generic_string())); db_->open( db_open_args, genesis); if( dump_memory_details_ ) dumper.dump( true, get_indexes_memory_details ); } catch( const fc::exception& e ) { wlog("Error opening database, attempting to replay blockchain. Error: ${e}", ("e", e)); try { db_->reindex( db_open_args, genesis); } catch( sophiatx::chain::block_log_exception& ) { wlog( "Error opening block log. Having to resync from network..." ); db_->open( db_open_args, genesis); } } } ilog( "Started on blockchain with ${n} blocks", ("n", db_->head_block_num()) ); on_sync(); } void chain_plugin_full::plugin_shutdown() { ilog("closing chain database"); stop_write_processing(); db_->close(); ilog("database closed successfully"); } bool chain_plugin_full::accept_block( const sophiatx::chain::signed_block& block, bool currently_syncing, uint32_t skip ) { if (currently_syncing && block.block_num() % 10000 == 0) { ilog("Syncing Blockchain --- Got block: #${n} time: ${t} producer: ${p}", ("t", block.timestamp) ("n", block.block_num()) ("p", block.witness) ); } check_time_in_block( block ); boost::promise< void > prom; write_context cxt; cxt.req_ptr = &block; cxt.skip = currently_syncing? skip | database::skip_validate_invariants : skip; cxt.prom_ptr = &prom; write_queue.push( &cxt ); prom.get_future().get(); if( cxt.except ) throw *(cxt.except); return cxt.success; } void chain_plugin_full::accept_transaction( const sophiatx::chain::signed_transaction& trx ) { boost::promise< void > prom; write_context cxt; cxt.req_ptr = &trx; cxt.prom_ptr = &prom; write_queue.push( &cxt ); prom.get_future().get(); if( cxt.except ) throw *(cxt.except); return; } void chain_plugin_full::check_time_in_block( const sophiatx::chain::signed_block& block ) { time_point_sec now = fc::time_point::now(); uint64_t max_accept_time = now.sec_since_epoch(); max_accept_time += allow_future_time; FC_ASSERT( block.timestamp.sec_since_epoch() <= max_accept_time ); } sophiatx::chain::signed_block chain_plugin_full::generate_block( const fc::time_point_sec& when, const account_name_type& witness_owner, const fc::ecc::private_key& block_signing_private_key, uint32_t skip ) { generate_block_request req( when, witness_owner, block_signing_private_key, skip ); boost::promise< void > prom; write_context cxt; cxt.req_ptr = &req; cxt.prom_ptr = &prom; write_queue.push( &cxt ); prom.get_future().get(); if( cxt.except ) throw *(cxt.except); FC_ASSERT( cxt.success, "Block could not be generated" ); return req.block; } int16_t chain_plugin_full::set_write_lock_hold_time( int16_t new_time ) { FC_ASSERT( get_state() == appbase::abstract_plugin::state::initialized, "Can only change write_lock_hold_time while chain_plugin_full is initialized." ); int16_t old_time = write_lock_hold_time; write_lock_hold_time = new_time; return old_time; } } } } // namespace sophiatx::plugis::chain::chain_apis
36.880282
271
0.634142
7f2672a9bfddd5ff0a2e8882dce80949e5b10ef8
3,419
cc
C++
Unittests/DictTest.cc
ianloic/unladen-swallow
28148f4ddbb3d519042de1f9fc9f1356fdd31e31
[ "PSF-2.0" ]
5
2020-06-30T05:06:40.000Z
2021-05-24T08:38:33.000Z
Unittests/DictTest.cc
ianloic/unladen-swallow
28148f4ddbb3d519042de1f9fc9f1356fdd31e31
[ "PSF-2.0" ]
null
null
null
Unittests/DictTest.cc
ianloic/unladen-swallow
28148f4ddbb3d519042de1f9fc9f1356fdd31e31
[ "PSF-2.0" ]
2
2015-10-01T18:28:20.000Z
2020-09-09T16:25:27.000Z
#include "Python.h" #include "gtest/gtest.h" class DictWatcherTest : public testing::Test { protected: DictWatcherTest() { Py_NoSiteFlag = true; Py_Initialize(); this->globals_ = PyDict_New(); this->builtins_ = PyDict_New(); } ~DictWatcherTest() { Py_DECREF(this->globals_); Py_DECREF(this->builtins_); Py_Finalize(); } // Satisfying all the inputs to PyCode_New() is hard, so we fake it. // You will need to PyMem_DEL the result manually. PyCodeObject *FakeCodeObject() { PyCodeObject *code = PyMem_NEW(PyCodeObject, 1); assert(code != NULL); // We only initialize the fields related to dict watchers. code->co_assumed_globals = NULL; code->co_assumed_builtins = NULL; code->co_use_llvm = 0; code->co_fatalbailcount = 0; return code; } PyObject *globals_; PyObject *builtins_; }; TEST_F(DictWatcherTest, AddWatcher) { PyCodeObject *code = this->FakeCodeObject(); _PyDict_AddWatcher(this->globals_, code); PyDictObject *dict = (PyDictObject *)this->globals_; EXPECT_EQ(dict->ma_watchers_used, 1); EXPECT_EQ(dict->ma_watchers_allocated, 64); // Drop the watcher to prevent the dict's dealloc from referencing freed // memory. _PyDict_DropWatcher(this->globals_, code); PyMem_DEL(code); } // _PyDict_DropWatcher() used to leave holes in the watcher array. This test // verifies that DropWatcher() compacts the array. TEST_F(DictWatcherTest, DropWatcherAddWatcherSequence) { PyCodeObject *code1 = this->FakeCodeObject(); PyCodeObject *code2 = this->FakeCodeObject(); _PyDict_AddWatcher(this->globals_, code1); _PyDict_AddWatcher(this->globals_, code2); _PyDict_DropWatcher(this->globals_, code1); PyDictObject *dict = (PyDictObject *)this->globals_; EXPECT_EQ(dict->ma_watchers_used, 1); EXPECT_EQ(dict->ma_watchers[0], code2); _PyDict_DropWatcher(this->globals_, code2); PyMem_DEL(code1); PyMem_DEL(code2); } TEST_F(DictWatcherTest, DictDealloc) { PyObject *globals = PyDict_New(); PyObject *builtins = PyDict_New(); PyCodeObject *code1 = this->FakeCodeObject(); code1->co_use_llvm = 1; EXPECT_EQ(_PyCode_WatchGlobals(code1, globals, builtins), 0); Py_DECREF(globals); EXPECT_EQ(code1->co_use_llvm, 0); EXPECT_EQ(code1->co_assumed_globals, (PyObject *)NULL); EXPECT_EQ(code1->co_assumed_builtins, (PyObject *)NULL); PyDictObject *dict = (PyDictObject *)builtins; EXPECT_EQ(dict->ma_watchers_used, 0); Py_DECREF(builtins); PyMem_DEL(code1); } TEST_F(DictWatcherTest, NotifyWatcher) { PyCodeObject *code1 = this->FakeCodeObject(); code1->co_use_llvm = 1; EXPECT_EQ(_PyCode_WatchGlobals(code1, this->globals_, this->builtins_), 0); EXPECT_EQ(code1->co_use_llvm, 1); // This should notify the watchers. PyDict_SetItemString(this->globals_, "hello", Py_None); EXPECT_EQ(code1->co_use_llvm, 0); PyDictObject *globals_dict = (PyDictObject *)this->globals_; EXPECT_EQ(globals_dict->ma_watchers_used, 0); PyDictObject *builtins_dict = (PyDictObject *)this->builtins_; EXPECT_EQ(builtins_dict->ma_watchers_used, 0); EXPECT_EQ(code1->co_assumed_builtins, (PyObject *)NULL); EXPECT_EQ(code1->co_assumed_globals, (PyObject *)NULL); PyMem_DEL(code1); }
29.222222
79
0.687335
7f26a584009c9e5e484626852f8a51d27adebacd
958
cpp
C++
C++/problem0922.cpp
1050669722/LeetCode-Answers
c8f4d1ccaac09cda63b60d75144335347b06dc81
[ "MIT" ]
null
null
null
C++/problem0922.cpp
1050669722/LeetCode-Answers
c8f4d1ccaac09cda63b60d75144335347b06dc81
[ "MIT" ]
null
null
null
C++/problem0922.cpp
1050669722/LeetCode-Answers
c8f4d1ccaac09cda63b60d75144335347b06dc81
[ "MIT" ]
null
null
null
#include <iostream> #include <iomanip> #include <vector> #include <map> #include <set> #include <algorithm> #include <cmath> #include <ctime> #include <cstdlib> #include <windows.h> #include <string> #include <numeric> using namespace std; class Solution { public: vector<int> sortArrayByParityII(vector<int>& A) { int j = 1; for (int i = 0; i < A.size(); i += 2) { if (A[i]%2 == 1) { while (A[j]%2 == 1) { j += 2; } int tmp = A[i]; A[i] = A[j]; A[j] = tmp; } } return A; } }; int main() { vector<int> A {4,2,5,7}; Solution solu; vector<int> ans = solu.sortArrayByParityII(A); vector<int>::iterator it; for (it = ans.begin(); it < ans.end(); ++it) { cout << *it << '\t'; } cout << endl; return 0; }
19.16
53
0.44572
7f2b8949ecb55a42e2a90caccb8bb55269b7af1e
2,486
cpp
C++
test/channel/main_channel_udp1.cpp
oudream/ccxx
7746ef93b48bf44157048a43c4878152fe6a4d2b
[ "MIT" ]
39
2015-12-09T09:28:46.000Z
2021-11-16T12:57:25.000Z
test/channel/main_channel_udp1.cpp
oudream/ccxx
7746ef93b48bf44157048a43c4878152fe6a4d2b
[ "MIT" ]
1
2020-10-17T02:23:42.000Z
2020-10-17T02:23:42.000Z
test/channel/main_channel_udp1.cpp
oudream/ccxx
7746ef93b48bf44157048a43c4878152fe6a4d2b
[ "MIT" ]
8
2018-05-29T12:48:13.000Z
2022-02-27T01:45:57.000Z
/* cxtest_channel_udp1 -lip 10.32.50.57 -lport 5555 -rip 10.32.50.57 -rport 5556 cxtest_channel_udp1 -lip 10.32.50.57 -lport 5556 -rip 10.32.50.57 -rport 5555 /**/ #include <ccxx/ccxx.h> using namespace std; class UdpSubject : public CxIChannelSubject { public: UdpSubject(){ mRecvTotalTimes = 0; mRecvTotalLen = 0; } ~UdpSubject(){ } int mRecvTotalTimes; int mRecvTotalLen; protected: void channel_receivedData(const uchar* pData, int iLength, void * oSource) { mRecvTotalTimes++; mRecvTotalLen += iLength; cout << "Recv " << iLength << " Byte, mRecvTotalTimes " << mRecvTotalTimes << " Byte, mRecvTotalLen " << mRecvTotalLen << endl; } }; CxChannelUdp f_mUdp; UdpSubject f_mUdpSubject; #define GM_TEST_UDP_DATA_LEN 14000 int mSendTotalTimes = 0; int mSendTotalLen = 0; void fn_timer_timeout1(int iInterval) { cout << CxTime::currentSystemTimeString() << endl; if (!f_mUdp.isOpen()) { cout << "Udp Client Is Not Open!"; return; } char data[GM_TEST_UDP_DATA_LEN]; f_mUdp.sendData(data, GM_TEST_UDP_DATA_LEN); int iResult = f_mUdp.sendData(data, sizeof(data)); mSendTotalTimes ++; mSendTotalLen += iResult; cout << "Udp Client sendData Result=" << iResult << " Byte, mSendTotalTimes " << mSendTotalTimes << " Byte, mSendTotalLen " << mSendTotalLen << endl; } int main(int argc, const char * argv[]) { cout << "Udp Client Test Begin: " << endl; CxApplication::init(argc, argv); string sLocalIp = CxAppEnv::findArgument("lip"); if (! CxString::isValidIp(sLocalIp)) sLocalIp = "127.0.0.1"; int iLocalPort = CxString::toInt32(CxAppEnv::findArgument("lport")); if (! CxString::isValidPort(iLocalPort)) iLocalPort = 5555; string sRemoteIp = CxAppEnv::findArgument("rip"); if (! CxString::isValidIp(sRemoteIp)) sRemoteIp = "127.0.0.1"; int iRemotePort = CxString::toInt32(CxAppEnv::findArgument("rport")); if (! CxString::isValidPort(iRemotePort)) iRemotePort = 5556; f_mUdp.addObserver(&f_mUdpSubject); f_mUdp.setLocalIp(sLocalIp); f_mUdp.setLocalPort(iLocalPort); f_mUdp.setRemoteIp(sRemoteIp); f_mUdp.setRemotePort(iRemotePort); f_mUdp.open(); cout << "Udp Client Open. port=" << iLocalPort << ", status=" << f_mUdp.isOpen()<< endl; CxThread::sleep(5000); CxTimerManager::startTimer(fn_timer_timeout1, 100); return CxApplication::exec(); }
28.906977
153
0.662912
7f2ce710398c6aa5fc53cac0665671b65a6e8174
1,648
cc
C++
src/Gateway.cc
Swair/Function-Distributed-Network
55c2c9caa2b6de6c06c99009b2063703601e7956
[ "Apache-2.0" ]
null
null
null
src/Gateway.cc
Swair/Function-Distributed-Network
55c2c9caa2b6de6c06c99009b2063703601e7956
[ "Apache-2.0" ]
null
null
null
src/Gateway.cc
Swair/Function-Distributed-Network
55c2c9caa2b6de6c06c99009b2063703601e7956
[ "Apache-2.0" ]
null
null
null
#include "Gateway.h" Gateway& Gateway::getInstance() { static Gateway gw; return gw; } Gateway::Gateway() {} Gateway::~Gateway() {} void Gateway::reg(const std::string& method, std::function<void(std::string&, const std::string&)> func) { routeTable_[method] = func; } void Gateway::route(std::string& response, const std::string& request) { std::string failCode; //log_write("%s\n", request.c_str()); std::string uri; if(0 == getContent(uri, request, "POST", 1, " HTTP")) { failCode = R"({"code":400, "msg":"fail in get uri"})"; throw ExceptionPanic(failCode); } int ix = uri.rfind("/"); if(ix > 0) { std::string method = uri.substr(ix + 1); //log_write("Gateway::route, %s\n", method.c_str()); try { auto f = routeTable_[method]; f(response, request); } catch(nlohmann::detail::exception& e) { std::string msg = e.what(); failCode = R"({"code":430, "msg":")" + msg + R"("})"; throw ExceptionPanic(failCode); } catch(std::exception& e) { failCode = R"({"code":431, "msg":"fail in route, check the web api"})"; throw ExceptionPanic(failCode); } catch(ExceptionPanic& e) { std::string msg = e.what(); failCode = R"({"code":432, "msg":")" + msg + R"("})"; throw ExceptionPanic(failCode); } catch(...) { failCode = R"({"code":433, "msg":"fail in route"})"; throw ExceptionPanic(failCode); } } }
24.969697
105
0.508495
b526587f2318c6c9d871d46e423e6b483563a1b5
326
cpp
C++
Dataset/Leetcode/test/110/451.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/Leetcode/test/110/451.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/Leetcode/test/110/451.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
class Solution { public: bool flag=true; bool XXX(TreeNode* root) { int l=dfs(root); return flag; } int dfs(TreeNode* root){ if(root==NULL) return 0; int l=dfs(root->left); int r=dfs(root->right); if(abs(l-r)>1) flag=false; return max(l,r)+1; } };
19.176471
35
0.509202
b5290f40d62908ad95681d974cbce979eb8641f5
252
cpp
C++
Game/Client/WXClient/Network/PacketHandler/GCMySelfEquipmentListHandler.cpp
hackerlank/SourceCode
b702c9e0a9ca5d86933f3c827abb02a18ffc9a59
[ "MIT" ]
4
2021-07-31T13:56:01.000Z
2021-11-13T02:55:10.000Z
Game/Client/WXClient/Network/PacketHandler/GCDetailEquipmentListHandler.cpp
shacojx/SourceCodeGameTLBB
e3cea615b06761c2098a05427a5f41c236b71bf7
[ "MIT" ]
null
null
null
Game/Client/WXClient/Network/PacketHandler/GCDetailEquipmentListHandler.cpp
shacojx/SourceCodeGameTLBB
e3cea615b06761c2098a05427a5f41c236b71bf7
[ "MIT" ]
7
2021-08-31T14:34:23.000Z
2022-01-19T08:25:58.000Z
#include "StdAfx.h" #include "GCDetailEquipmentList.h" uint GCDetailEquipmentListHandler :: Execute( GCDetailEquipmentList* pPacket, Player* pPlayer ) { __ENTER_FUNCTION return PACKET_EXE_CONTINUE ; __LEAVE_FUNCTION return PACKET_EXE_ERROR ; }
16.8
96
0.801587
b529f379479b6a73c191611f277d3980470cabd8
1,091
cpp
C++
usaco_practice/bronze/bronze_A/A4_array_two/Roll_cake.cpp
juneharold/USACO
a96b54f68e7247c61044f3c0d9e7260952c508e2
[ "MIT" ]
null
null
null
usaco_practice/bronze/bronze_A/A4_array_two/Roll_cake.cpp
juneharold/USACO
a96b54f68e7247c61044f3c0d9e7260952c508e2
[ "MIT" ]
null
null
null
usaco_practice/bronze/bronze_A/A4_array_two/Roll_cake.cpp
juneharold/USACO
a96b54f68e7247c61044f3c0d9e7260952c508e2
[ "MIT" ]
null
null
null
// 롤 케이크 #include <iostream> #include <algorithm> #include <string> using namespace std; int main() { int L, N; cin >> L; cin >> N; int ranges[2000] = {}; for (int i=0; i<2*N; i++) { cin >> ranges[i]; } // number of cake int max_expected=0; int max_received=0; // number of person int num_ex=-1; int num_re=-1; int status[1000]={}; for (int j=0; j<N; j++) { int start=ranges[2*j], end=ranges[2*j+1]; // finding expectations int range = end-start+1; if (range>max_expected) { max_expected=range; num_ex=j+1; } // looping through the range int cake_received=0; for (int c=start; c<=end; c++) { if (status[c]==0) { cake_received += 1; status[c]=1; } } if (cake_received>max_received) { max_received=cake_received; num_re=j+1; } } cout << num_ex << endl; cout << num_re << endl; }
20.584906
49
0.463795
b52d3581cedf7fffe7a94047630d9129e71c264c
137
hh
C++
Include/Luce/AI/Configuration.hh
kmc7468/luce
6f71407f250dbc0428ceba33aeef345cc601db34
[ "MIT" ]
23
2017-02-09T11:48:01.000Z
2017-04-08T10:19:21.000Z
Include/Luce/AI/Configuration.hh
kmc7468/luce
6f71407f250dbc0428ceba33aeef345cc601db34
[ "MIT" ]
null
null
null
Include/Luce/AI/Configuration.hh
kmc7468/luce
6f71407f250dbc0428ceba33aeef345cc601db34
[ "MIT" ]
null
null
null
#ifndef LUCE_HEADER_AI_CONFIGURATION_HH #define LUCE_HEADER_AI_CONFIGURATION_HH #include <Luce/AI/Configuration/ComputeByCpu.hh> #endif
22.833333
48
0.868613
b52e9446ef1467cbc1e66fbabf752e1a26e6ef91
4,119
cpp
C++
Tests/BasicsTest/TestAVX2.cpp
mfkiwl/RayRenderer-dp4a
b57696b23c795f0ca1199e8f009b7a12b88da13a
[ "MIT" ]
18
2018-10-22T10:30:20.000Z
2021-12-10T06:29:39.000Z
Tests/BasicsTest/TestAVX2.cpp
mfkiwl/RayRenderer-dp4a
b57696b23c795f0ca1199e8f009b7a12b88da13a
[ "MIT" ]
null
null
null
Tests/BasicsTest/TestAVX2.cpp
mfkiwl/RayRenderer-dp4a
b57696b23c795f0ca1199e8f009b7a12b88da13a
[ "MIT" ]
4
2019-06-04T14:04:43.000Z
2021-07-16T01:41:48.000Z
#include "pch.h" #if COMMON_COMPILER_GCC # pragma GCC push_options # pragma GCC target("avx2") #elif COMMON_COMPILER_CLANG # pragma clang attribute push (__attribute__((target("avx2"))), apply_to=function) #endif namespace avx2 { using namespace common; #define COMMON_SIMD_LV 200 #include "common/simd/SIMD.hpp" #if COMMON_SIMD_LV_ >= 200 # include "common/simd/SIMD128.hpp" # include "common/simd/SIMD256.hpp" using namespace common::simd; # include "SIMDBaseTest.h" # include "ShuffleTest.h" RegisterSIMDBaseTest(I64x4, 200, SWE, SEL, Add, Sub, SatAdd, SatSub, MulLo, Neg, Abs, Min, Max, SLL, SRL, SRA, And, Or, Xor, AndNot, Not); RegisterSIMDBaseTest(U64x4, 200, SWE, SEL, Add, Sub, SatAdd, SatSub, MulLo, Abs, Min, Max, SLL, SRL, SRA); RegisterSIMDBaseTest(I32x8, 200, SWE, SEL, Add, Sub, SatAdd, SatSub, MulLo, MulX, Neg, Abs, Min, Max, SLL, SRL, SRA); RegisterSIMDBaseTest(U32x8, 200, SWE, SEL, Add, Sub, SatAdd, SatSub, MulLo, MulX, Abs, Min, Max, SLL, SRL, SRA); RegisterSIMDBaseTest(I16x16, 200, SWE, SEL, Add, Sub, SatAdd, SatSub, MulLo, MulHi, MulX, Neg, Abs, Min, Max, SLL, SRL, SRA); RegisterSIMDBaseTest(U16x16, 200, SWE, SEL, Add, Sub, SatAdd, SatSub, MulLo, MulHi, MulX, Abs, Min, Max, SLL, SRL, SRA); RegisterSIMDBaseTest(I8x32, 200, SEL, Add, Sub, SatAdd, SatSub, MulLo, MulHi, MulX, Neg, Abs, Min, Max, SLL, SRL, SRA); RegisterSIMDBaseTest(U8x32, 200, SEL, Add, Sub, SatAdd, SatSub, MulLo, MulHi, MulX, Abs, Min, Max, SLL, SRL, SRA); RegisterSIMDCastTest(F32x8, 200, F64x4); RegisterSIMDCastTest(F64x4, 200, F32x8); RegisterSIMDCastTest(I64x4, 200, I8x32, I16x16, I32x8 ); RegisterSIMDCastTest(U64x4, 200, U8x32, U16x16, U32x8 ); RegisterSIMDCastTest(I32x8, 200, I8x32, I16x16, I64x4, U64x4, F32x8, F64x4); RegisterSIMDCastTest(U32x8, 200, U8x32, U16x16, I64x4, U64x4, F32x8, F64x4); RegisterSIMDCastTest(I16x16, 200, I8x32, I32x8, U32x8, I64x4, U64x4, F32x8, F64x4); RegisterSIMDCastTest(U16x16, 200, U8x32, I32x8, U32x8, I64x4, U64x4, F32x8, F64x4); RegisterSIMDCastTest(I8x32, 200, I16x16, U16x16, I32x8, U32x8, I64x4, U64x4, F32x8, F64x4); RegisterSIMDCastTest(U8x32, 200, I16x16, U16x16, I32x8, U32x8, I64x4, U64x4, F32x8, F64x4); RegisterSIMDCastModeTest(F32x8, 200, RangeSaturate, I16x16, U16x16, I8x32, U8x32); RegisterSIMDCastModeTest(I32x8, 200, RangeSaturate, I16x16, U16x16); RegisterSIMDCastModeTest(U32x8, 200, RangeSaturate, U16x16); RegisterSIMDCastModeTest(I16x16, 200, RangeSaturate, I8x32, U8x32); RegisterSIMDCastModeTest(U16x16, 200, RangeSaturate, U8x32); RegisterSIMDCmpTest(200, I64x4, U64x4, I32x8, U32x8, I16x16, U16x16, I8x32, U8x32) RegisterSIMDZipTest(200, F64x4, F32x8, I64x4, U64x4, I32x8, U32x8, I16x16, U16x16, I8x32, U8x32) RegisterSIMDZipLaneTest(200, F64x4, F32x8, I64x4, U64x4, I32x8, U32x8, I16x16, U16x16, I8x32, U8x32) RegisterSIMDTest(F64x4, 200, shuftest::ShuffleTest<F64x4>); RegisterSIMDTest(I64x4, 200, shuftest::ShuffleTest<I64x4>); RegisterSIMDTest(F64x2, 200, shuftest::ShuffleTest<F64x2>); RegisterSIMDTest(I64x2, 200, shuftest::ShuffleTest<I64x2>); RegisterSIMDTest(F32x4, 200, shuftest::ShuffleTest<F32x4>); RegisterSIMDTest(I32x4, 200, shuftest::ShuffleTest<I32x4>); RegisterSIMDTest(F64x4, 200, shuftest::ShuffleVarTest<F64x4>); RegisterSIMDTest(I64x4, 200, shuftest::ShuffleVarTest<I64x4>); RegisterSIMDTest(F32x8, 200, shuftest::ShuffleVarTest<F32x8>); RegisterSIMDTest(I32x8, 200, shuftest::ShuffleVarTest<I32x8>); RegisterSIMDTest(F64x2, 200, shuftest::ShuffleVarTest<F64x2>); RegisterSIMDTest(I64x2, 200, shuftest::ShuffleVarTest<I64x2>); RegisterSIMDTest(F32x4, 200, shuftest::ShuffleVarTest<F32x4>); RegisterSIMDTest(I32x4, 200, shuftest::ShuffleVarTest<I32x4>); #endif } #if COMMON_COMPILER_GCC # pragma GCC pop_options #elif COMMON_COMPILER_CLANG # pragma clang attribute pop #endif
48.458824
152
0.70017
b531574b7fbbf60c47356dc23f1ef5ad56585873
5,537
cpp
C++
src/TowerEntity.cpp
Smokey1105/Strife.SingleplayerDemo
586865f66e7b08a6e16385fe400c3dd2fe886489
[ "NCSA" ]
null
null
null
src/TowerEntity.cpp
Smokey1105/Strife.SingleplayerDemo
586865f66e7b08a6e16385fe400c3dd2fe886489
[ "NCSA" ]
null
null
null
src/TowerEntity.cpp
Smokey1105/Strife.SingleplayerDemo
586865f66e7b08a6e16385fe400c3dd2fe886489
[ "NCSA" ]
null
null
null
#include "TowerEntity.hpp" #include "Engine.hpp" #include "PlayerEntity.hpp" #include "FireballEntity.hpp" #include "CastleEntity.hpp" #include "ObstacleComponent.hpp" #include "Components/RigidBodyComponent.hpp" #include "Components/SpriteComponent.hpp" #include "Physics/PathFinding.hpp" #include "Net/ReplicationManager.hpp" void TowerEntity::DoSerialize(EntitySerializer& serializer) { } void TowerEntity::OnAdded() { spriteComponent = AddComponent<SpriteComponent>("towerSprite"); spriteComponent->scale = Vector2(5.0f); Vector2 size{ 11 * 5, 32 * 5 }; SetDimensions(size); obstacle = AddComponent<ObstacleComponent>(); auto rigidBody = AddComponent<RigidBodyComponent>(b2_staticBody); rigidBody->CreateBoxCollider(size); auto health = AddComponent<HealthBarComponent>(); health->offsetFromCenter = -size.YVector() / 2 - Vector2(0, 5); health->maxHealth = 500; health->health = 500; team = AddComponent<TeamComponent>(); auto offset = size / 2 + Vector2(40, 40); _light = AddComponent<LightComponent<PointLight>>(); _light->position = Center(); _light->intensity = 0.5; _light->maxDistance = 500; _light->maxDistance = 500; region = rigidBody->CreateCircleCollider(reach, true); } void TowerEntity::Update(float deltaTime) { _light->color = playerId == 0 ? Color::Green() : Color::White(); if (_currentTarget.IsValid()) { _fireballTimeout -= deltaTime; } OnUpdateState(); } void TowerEntity::OnDestroyed() { for (auto base : scene->GetEntitiesOfType<CastleEntity>()) { if (base->team->teamId == team->teamId) { base->SendEvent(TowerDestroyedEvent()); } } } void TowerEntity::ReceiveEvent(const IEntityEvent& ev) { if (ev.Is<OutOfHealthEvent>()) { Destroy(); } else if (auto damageDealtEvent = ev.Is<DamageDealtEvent>()) { Entity* currentTarget = nullptr; if (_currentTarget.TryGetValue(currentTarget)) { if (currentTarget != damageDealtEvent->dealer) { ChangeState( { TowerEntityAiState::AttackSelectedTarget, EntityReference<Entity>(damageDealtEvent->dealer) }); } } } else if (auto contactBeginEvent = ev.Is<ContactBeginEvent>()) { if (contactBeginEvent->OtherIs<FireballEntity>()) { return; } if (contactBeginEvent->self.GetFixture() == region && !contactBeginEvent->other.IsTrigger()) { _targets.PushBackUniqueIfRoom(contactBeginEvent->other.OwningEntity()); } } else if (auto contactEndEvent = ev.Is<ContactEndEvent>()) { auto other = contactEndEvent->other; if (contactEndEvent->self.GetFixture() == region && !other.IsTrigger()) { _targets.RemoveSingle(other.OwningEntity()); } } } void TowerEntity::ChangeState(TowerEntityState state) { OnExitState(); OnEnterState(state); _state = state; } void TowerEntity::OnEnterState(TowerEntityState& newState) { switch (newState.state) { case TowerEntityAiState::DoNothing: case TowerEntityAiState::SearchForTarget: break; case TowerEntityAiState::AttackSelectedTarget: { _currentTarget = newState.newTarget; } break; } } void TowerEntity::OnUpdateState() { switch (_state.state) { case TowerEntityAiState::DoNothing: ChangeState({ TowerEntityAiState::SearchForTarget }); break; case TowerEntityAiState::SearchForTarget: { float closestTargetDistance = reach * 2; Entity* closestTarget = nullptr; for (auto& target : _targets) { if (target == nullptr || target->isDestroyed) { continue; } TeamComponent* teamComponent; if (target->TryGetComponent(teamComponent)) { if (teamComponent->teamId == team->teamId) { continue; } if ((target->Center() - Center()).Length() <= closestTargetDistance) { closestTarget = target; } } } if (closestTarget != nullptr) { ChangeState({ TowerEntityAiState::AttackSelectedTarget, EntityReference<Entity>(closestTarget) }); } } break; case TowerEntityAiState::AttackSelectedTarget: { Entity* target = _currentTarget.GetValueOrNull(); if (target == nullptr || (target->Center() - Center()).Length() >= reach) { _currentTarget.Invalidate(); ChangeState({ TowerEntityAiState::SearchForTarget }); } else if (_fireballTimeout <= 0) { _fireballTimeout = FireballTimeoutLength; ShootFireball(target); } } break; } } void TowerEntity::OnExitState() { switch (_state.state) { case TowerEntityAiState::DoNothing: case TowerEntityAiState::SearchForTarget: break; case TowerEntityAiState::AttackSelectedTarget: { _currentTarget.Invalidate(); } break; } } void TowerEntity::ShootFireball(Entity* target) { auto direction = (target->Center() - Center()).Normalize(); auto fireball = scene->CreateEntity<FireballEntity>(Center(), direction * 400); fireball->playerId = playerId; }
25.753488
110
0.609536
b5367526a850ce69445f5e2e3ae88b3cc0395ba2
444
cpp
C++
partners_api/ads/google_ads.cpp
vicpopov/omim
664b458998fb0f2405f68ae830c2798e027b2dcc
[ "Apache-2.0" ]
4,879
2015-09-30T10:56:36.000Z
2022-03-31T18:43:03.000Z
partners_api/ads/google_ads.cpp
mbrukman/omim
d22fe2b6e0beee697f096e931df97a64f9db9dc1
[ "Apache-2.0" ]
7,549
2015-09-30T10:52:53.000Z
2022-03-31T22:04:22.000Z
partners_api/ads/google_ads.cpp
mbrukman/omim
d22fe2b6e0beee697f096e931df97a64f9db9dc1
[ "Apache-2.0" ]
1,493
2015-09-30T10:43:06.000Z
2022-03-21T09:16:49.000Z
#include "partners_api/ads/google_ads.hpp" namespace { #if defined(OMIM_OS_IPHONE) auto const kSearchbannerId = "mobile-app-mapsme"; #elif defined(OMIM_OS_ANDROID) auto const kSearchbannerId = "mobile-app-mapsme"; #else auto const kSearchbannerId = "dummy"; #endif } // namespace namespace ads { std::string Google::GetBanner() const { return kSearchbannerId; } bool Google::HasBanner() const { return true; } } // namespace ads
17.076923
51
0.734234
b5400e1794ee4d2bbfcf0b5fba231f428da08d3b
4,401
cpp
C++
ilwiscoreui/models/workspacemodel.cpp
ridoo/IlwisCore
9d9837507d804a4643545a03fd40d9b4d0eaee45
[ "Apache-2.0" ]
null
null
null
ilwiscoreui/models/workspacemodel.cpp
ridoo/IlwisCore
9d9837507d804a4643545a03fd40d9b4d0eaee45
[ "Apache-2.0" ]
null
null
null
ilwiscoreui/models/workspacemodel.cpp
ridoo/IlwisCore
9d9837507d804a4643545a03fd40d9b4d0eaee45
[ "Apache-2.0" ]
null
null
null
#include <QSqlQuery> #include <QSqlRecord> #include <QSqlError> #include "kernel.h" #include "ilwiscontext.h" #include "workspacemodel.h" WorkSpaceModel::WorkSpaceModel(const QString &name, QObject *parent) : CatalogModel( Ilwis::Resource("ilwis://internalcatalog/workspaces/" + name,itWORKSPACE),parent) { } WorkSpaceModel::~WorkSpaceModel() { } void WorkSpaceModel::addItems(const QString& ids) { auto putInConfig = [&](quint64 id, int count) { QString basekey = "users/" + Ilwis::context()->currentUser() + "/workspace-" + name(); Ilwis::Resource res = Ilwis::mastercatalog()->id2Resource(id); if ( res.isValid()){ QString key; if ( res.ilwisType() & itOPERATIONMETADATA){ key = QString("%1/operation-%2").arg(basekey).arg(count); Ilwis::context()->configurationRef().addValue(QString("%1/operation-count").arg(basekey),QString::number(count + 1)); } else{ key = QString("%1/data-%2").arg(basekey).arg(count); Ilwis::context()->configurationRef().addValue(QString("%1/data-count").arg(basekey),QString::number(count + 1)); } Ilwis::context()->configurationRef().addValue(key + "/url", res.url().toString()); Ilwis::context()->configurationRef().addValue(key + "/type", QString::number(res.ilwisType())); } }; QSqlQuery stmt(Ilwis::kernel()->database()); int count = 0; if (_view.fixedItemCount() == 0) { QString query = QString("Insert into workspaces (workspaceid) values(%1)").arg(_view.id()); if(!stmt.exec(query)) return; } // we dont want to add ids that are already in the list so we collect all ids that we have laready added std::set<QString> presentids; for(auto item : _operations){ presentids.insert(item->id()); } for(auto item : _data){ presentids.insert(item->id()); } QStringList idlist = ids.split("|"); for(auto id : idlist){ if ( presentids.find(id) != presentids.end()) continue; quint64 idn = id.toULongLong(); putInConfig(idn, count); _view.addFixedItem(idn); ++count; QString query = QString("Select workspaceid from workspace where workspaceid=%1 and itemid=%2").arg(_view.id()).arg(idn); if (stmt.exec(query)) { // already there if ( stmt.next()) { continue; }else{ query = QString("Insert into workspace (workspaceid, itemid) values(%1,%2)").arg(_view.id()).arg(idn); if(!stmt.exec(query)) return; } } } QString availableWorkspaces = Ilwis::ilwisconfig("users/" + Ilwis::context()->currentUser() + "/workspaces",QString("")); if ( availableWorkspaces.indexOf(name()) == -1){ if ( availableWorkspaces.size() > 0){ availableWorkspaces += "|"; } availableWorkspaces += name(); Ilwis::context()->configurationRef().addValue("users/" + Ilwis::context()->currentUser() + "/workspaces",availableWorkspaces); } refresh(true); emit dataChanged(); } void WorkSpaceModel::removeItems(const QString& ids) { QStringList idlist = ids.split("|"); for(auto id : idlist){ _view.removeFixedItem(id.toULongLong()); } } bool WorkSpaceModel::isDefault() const { return resource().url().toString() == Ilwis::Catalog::DEFAULT_WORKSPACE; } void WorkSpaceModel::gatherItems() { bool needRefresh = _refresh; CatalogModel::gatherItems(); if ( needRefresh){ _operations.clear(); _data.clear(); for(auto iter=_currentItems.begin(); iter != _currentItems.end(); ++iter){ if ( (*iter)->type() & itOPERATIONMETADATA){ _operations.push_back(new OperationModel((*iter)->resource(),this)); }else if ( hasType((*iter)->type(), itILWISOBJECT)){ _data.push_back(*iter); } } } refresh(false); } QQmlListProperty<OperationModel> WorkSpaceModel::operations() { refresh(true); gatherItems(); return QQmlListProperty<OperationModel>(this, _operations); } QQmlListProperty<ResourceModel> WorkSpaceModel::data() { refresh(true); gatherItems(); return QQmlListProperty<ResourceModel>(this, _data); }
32.843284
134
0.601
b540a7da19f87979c62edb01e97ca03fe259f786
4,445
cc
C++
gnuradio-3.7.13.4/gr-blocks/lib/udp_sink_impl.cc
v1259397/cosmic-gnuradio
64c149520ac6a7d44179c3f4a38f38add45dd5dc
[ "BSD-3-Clause" ]
1
2021-03-09T07:32:37.000Z
2021-03-09T07:32:37.000Z
gnuradio-3.7.13.4/gr-blocks/lib/udp_sink_impl.cc
v1259397/cosmic-gnuradio
64c149520ac6a7d44179c3f4a38f38add45dd5dc
[ "BSD-3-Clause" ]
null
null
null
gnuradio-3.7.13.4/gr-blocks/lib/udp_sink_impl.cc
v1259397/cosmic-gnuradio
64c149520ac6a7d44179c3f4a38f38add45dd5dc
[ "BSD-3-Clause" ]
null
null
null
/* -*- c++ -*- */ /* * Copyright 2007-2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "udp_sink_impl.h" #include <gnuradio/io_signature.h> #include <boost/array.hpp> #include <boost/asio.hpp> #include <boost/format.hpp> #include <gnuradio/thread/thread.h> #include <stdexcept> #include <stdio.h> #include <string.h> namespace gr { namespace blocks { udp_sink::sptr udp_sink::make(size_t itemsize, const std::string &host, int port, int payload_size, bool eof) { return gnuradio::get_initial_sptr (new udp_sink_impl(itemsize, host, port, payload_size, eof)); } udp_sink_impl::udp_sink_impl(size_t itemsize, const std::string &host, int port, int payload_size, bool eof) : sync_block("udp_sink", io_signature::make(1, 1, itemsize), io_signature::make(0, 0, 0)), d_itemsize(itemsize), d_payload_size(payload_size), d_eof(eof), d_connected(false) { // Get the destination address connect(host, port); } // public constructor that returns a shared_ptr udp_sink_impl::~udp_sink_impl() { if(d_connected) disconnect(); } void udp_sink_impl::connect(const std::string &host, int port) { if(d_connected) disconnect(); std::string s_port = (boost::format("%d")%port).str(); if(host.size() > 0) { boost::asio::ip::udp::resolver resolver(d_io_service); boost::asio::ip::udp::resolver::query query(host, s_port, boost::asio::ip::resolver_query_base::passive); d_endpoint = *resolver.resolve(query); d_socket = new boost::asio::ip::udp::socket(d_io_service); d_socket->open(d_endpoint.protocol()); boost::asio::socket_base::reuse_address roption(true); d_socket->set_option(roption); d_connected = true; } } void udp_sink_impl::disconnect() { if(!d_connected) return; gr::thread::scoped_lock guard(d_mutex); // protect d_socket from work() // Send a few zero-length packets to signal receiver we are done boost::array<char, 0> send_buf; if(d_eof) { int i; for(i = 0; i < 3; i++) d_socket->send_to(boost::asio::buffer(send_buf), d_endpoint); } d_socket->close(); delete d_socket; d_connected = false; } int udp_sink_impl::work (int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const char *in = (const char *) input_items[0]; ssize_t r=0, bytes_sent=0, bytes_to_send=0; ssize_t total_size = noutput_items*d_itemsize; gr::thread::scoped_lock guard(d_mutex); // protect d_socket while(bytes_sent < total_size) { bytes_to_send = std::min((ssize_t)d_payload_size, (total_size-bytes_sent)); if(d_connected) { try { r = d_socket->send_to(boost::asio::buffer((void*)(in+bytes_sent), bytes_to_send), d_endpoint); } catch(std::exception& e) { GR_LOG_ERROR(d_logger, boost::format("send error: %s") % e.what()); return -1; } } else r = bytes_to_send; // discarded for lack of connection bytes_sent += r; } return noutput_items; } } /* namespace blocks */ } /* namespace gr */
29.633333
99
0.59775
b540c007a1b8eae68ab5d008e6367ee34bc0f2f1
874
cpp
C++
tests/test_postgres.cpp
shakfu/prolog
9d6621e3e723b0bd899bd963fe4a4125cf57671c
[ "Unlicense" ]
null
null
null
tests/test_postgres.cpp
shakfu/prolog
9d6621e3e723b0bd899bd963fe4a4125cf57671c
[ "Unlicense" ]
null
null
null
tests/test_postgres.cpp
shakfu/prolog
9d6621e3e723b0bd899bd963fe4a4125cf57671c
[ "Unlicense" ]
null
null
null
#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN #include <iostream> #include <pqxx/pqxx> #include "doctest.h" int test_db() { // Connect to the database. pqxx::connection c{"postgresql://sa@localhost/sa"}; std::cout << "Connected to " << c.dbname() << '\n'; // Start a transaction. pqxx::work W{c}; // Perform a query and retrieve all results. pqxx::result R{W.exec("SELECT name FROM employee")}; // Iterate over results. std::cout << "Found " << R.size() << "employees:\n"; for (auto row: R) std::cout << row[0].c_str() << '\n'; // Perform a query and check that it returns no result. std::cout << "Doubling all employees' salaries...\n"; W.exec0("UPDATE employee SET salary = salary*2"); // Commit the transaction. std::cout << "Making changes definite: "; W.commit(); std::cout << "OK.\n"; }
25.705882
59
0.606407
b5411852752a697187ec98f85ca8f93b27502af6
297
cpp
C++
Demos3/BasicDemoConsole/main.cpp
jackoalan/bullet3
4276b2f06aa652a00b798666ae68013fc6c950e3
[ "Zlib" ]
5
2015-07-28T09:07:57.000Z
2020-09-24T16:49:45.000Z
Demos3/BasicDemoConsole/main.cpp
jackoalan/bullet3
4276b2f06aa652a00b798666ae68013fc6c950e3
[ "Zlib" ]
null
null
null
Demos3/BasicDemoConsole/main.cpp
jackoalan/bullet3
4276b2f06aa652a00b798666ae68013fc6c950e3
[ "Zlib" ]
null
null
null
#include <stdio.h> #include "../../Demos/BasicDemo/BasicDemoPhysicsSetup.h" int main(int argc, char* argv[]) { BasicDemoPhysicsSetup physicsSetup; GraphicsPhysicsBridge br; physicsSetup.initPhysics(br); physicsSetup.stepSimulation(1./60.); physicsSetup.exitPhysics(); printf("hello\n"); }
21.214286
56
0.750842
b542c209363518732ebf5fa53cb22732a7b7bb82
521
cpp
C++
oop/hw4/main.cpp
vMihtarska/fmi
3a3413ff410648ea9dcc00ba394dc216b1ba5df3
[ "MIT" ]
null
null
null
oop/hw4/main.cpp
vMihtarska/fmi
3a3413ff410648ea9dcc00ba394dc216b1ba5df3
[ "MIT" ]
null
null
null
oop/hw4/main.cpp
vMihtarska/fmi
3a3413ff410648ea9dcc00ba394dc216b1ba5df3
[ "MIT" ]
1
2016-01-20T19:02:10.000Z
2016-01-20T19:02:10.000Z
#include <iostream> #include "Employee.h" #include "Specialist.h" int main() { Employee g; g.SetName("VASI"); g.SetAddress("JK ZAPAD"); g.SetEGN("9508110056"); g.SetDepartment("IT"); g.SetSalary(100); g.Print(); Employee c(g); c.Print(); Employee m; m = g; m.Print(); Specialist x; x.SetName("VASI"); x.SetAddress("JK ZAPAD"); x.SetEGN("9508110056"); x.SetDepartment("IT"); x.SetSalary(100); x.SetDescription("PENCHO"); x.Print(); Specialist l(x); l.Print(); Specialist y; y = l; y.Print(); }
14.885714
28
0.635317
b5471770a3d009f4980cce0666488fe6b57f0b3d
1,080
hpp
C++
include/gui/slider.hpp
MartinKondor/Rule
1e5b7f611a2252112d091f27952fa5180e5fad19
[ "BSD-3-Clause" ]
null
null
null
include/gui/slider.hpp
MartinKondor/Rule
1e5b7f611a2252112d091f27952fa5180e5fad19
[ "BSD-3-Clause" ]
null
null
null
include/gui/slider.hpp
MartinKondor/Rule
1e5b7f611a2252112d091f27952fa5180e5fad19
[ "BSD-3-Clause" ]
null
null
null
#ifndef SLIDER_HPP #define SLIDER_HPP #include <SFML/Graphics.hpp> #include "config.hpp" #include "utils.hpp" extern Config CONFIG; class Slider { /** A Slider. Example usage: ``` Slider slider(100, 100, gameFont); slider.create(20, 450); slider.setSliderValue(235); ... slider.draw(window); ... ``` */ public: unsigned int xPos; unsigned int yPos; unsigned int minValue; unsigned int maxValue; unsigned int axisWidth; unsigned int axisHeight; unsigned int sliderWidth; unsigned int sliderHeight; float sliderValue; sf::RectangleShape slider; sf::RectangleShape axis; sf::Text text; Slider(); Slider(const unsigned int xPos, const unsigned int yPos, const unsigned int min, const unsigned int max); sf::Text returnText(const unsigned int x, const unsigned int y, const std::string z); void setSliderValue(const float newValue); void setSliderPercentValue(const float newPercentValue); void display(sf::RenderWindow &window); }; #endif // SLIDER_HPP
20.377358
109
0.675926
b551b82b7cfd1c3bd1322d08423e3d745eff3f89
1,284
hpp
C++
libraries/chain/include/graphene/chain/is_authorized_asset.hpp
EDCBlockchain/blockchain
41c74b981658d79d770b075191cfb14faeb84dab
[ "MIT" ]
12
2019-10-31T13:24:21.000Z
2021-12-29T22:02:22.000Z
libraries/chain/include/graphene/chain/is_authorized_asset.hpp
DONOVA28/blockchain
41c74b981658d79d770b075191cfb14faeb84dab
[ "MIT" ]
null
null
null
libraries/chain/include/graphene/chain/is_authorized_asset.hpp
DONOVA28/blockchain
41c74b981658d79d770b075191cfb14faeb84dab
[ "MIT" ]
11
2019-07-24T12:46:29.000Z
2021-11-27T04:41:48.000Z
// see LICENSE.txt #pragma once #include <map> #include <typeindex> #include <typeinfo> namespace graphene { namespace chain { class account_object; class asset_object; class database; namespace detail { bool _is_authorized_asset(const database& d, const account_object& acct, const asset_object& asset_obj); } // ns detail enum directionality_type { receiver = 0x2, payer = 0x4, }; inline bool not_restricted_account(const database& d, const account_object& acct, uint8_t type) { const auto& idx = d.get_index_type<restricted_account_index>().indices().get<by_acc_id>(); auto itr = idx.find(acct.id); if (itr == idx.end()) { return true; } if (itr->restriction_type && (type & *itr->restriction_type)) { return false; } return true; } /** * @return true if the account is whitelisted and not blacklisted to transact in the provided asset; false * otherwise. */ inline bool is_authorized_asset(const database& d, const account_object& acct, const asset_object& asset_obj) { bool fast_check = !(asset_obj.options.flags & white_list); fast_check &= !(acct.allowed_assets.valid()); if( fast_check ) return true; bool slow_check = detail::_is_authorized_asset( d, acct, asset_obj ); return slow_check; } } }
21.04918
109
0.707165
b551f72109fe10ceb9b8a4495fa3bdc20b116af0
181
cpp
C++
apps/src/videostitch-studio-gui/src/videostitcher/globalpostprodcontroller.cpp
tlalexander/stitchEm
cdff821ad2c500703e6cb237ec61139fce7bf11c
[ "MIT" ]
182
2019-04-19T12:38:30.000Z
2022-03-20T16:48:20.000Z
apps/src/videostitch-studio-gui/src/videostitcher/globalpostprodcontroller.cpp
doymcc/stitchEm
20693a55fa522d7a196b92635e7a82df9917c2e2
[ "MIT" ]
107
2019-04-23T10:49:35.000Z
2022-03-02T18:12:28.000Z
apps/src/videostitch-studio-gui/src/videostitcher/globalpostprodcontroller.cpp
doymcc/stitchEm
20693a55fa522d7a196b92635e7a82df9917c2e2
[ "MIT" ]
59
2019-06-04T11:27:25.000Z
2022-03-17T23:49:49.000Z
// Copyright (c) 2012-2017 VideoStitch SAS // Copyright (c) 2018 stitchEm #include "globalpostprodcontroller.hpp" template class GlobalControllerImpl<PostProdStitcherController>;
25.857143
64
0.812155
b5540a76ef968039f9bb0b1b4f004503836c27c4
1,127
hpp
C++
main_server/src/entities/parking_slot/parking_slot.hpp
GrassoMichele/uPark
d96310c165c3efa9b0251c51ababe06639c4570a
[ "MIT" ]
null
null
null
main_server/src/entities/parking_slot/parking_slot.hpp
GrassoMichele/uPark
d96310c165c3efa9b0251c51ababe06639c4570a
[ "MIT" ]
null
null
null
main_server/src/entities/parking_slot/parking_slot.hpp
GrassoMichele/uPark
d96310c165c3efa9b0251c51ababe06639c4570a
[ "MIT" ]
null
null
null
#ifndef PARKING_SLOT #define PARKING_SLOT #include <iostream> class ParkingSlot{ private: int id; int number; int id_parking_lot; int id_vehicle_type; bool reserved_disability; public: ParkingSlot(); ParkingSlot(int id); ParkingSlot(int id, int number, int id_parking_lot, int id_vehicle_type, bool reserved_disability); void setId(int); // void setNumber(int); // void setIdParkingLot(int); void setIdVehicleType(int); void setReservedDisability(bool); int getId() const; int getNumber() const; int getIdParkingLot() const; int getIdVehicleType() const; bool getReservedDisability() const; friend bool operator== (const ParkingSlot&, const ParkingSlot&); friend std::ostream& operator<<(std::ostream& os, const ParkingSlot&); }; // class ParkingSlotException : public std::exception { // std::string _message; // public: // ParkingSlotException(const std::string & message); // const char * what() const throw(); // }; #endif
26.209302
107
0.628217
b557c25ffa9d5306eaaaeb39bee702d02cacda66
6,834
hpp
C++
include/pkmn/types/class_with_attributes.hpp
ncorgan/libpkmn
c683bf8b85b03eef74a132b5cfdce9be0969d523
[ "MIT" ]
4
2017-06-10T13:21:44.000Z
2019-10-30T21:20:19.000Z
include/pkmn/types/class_with_attributes.hpp
PMArkive/libpkmn
c683bf8b85b03eef74a132b5cfdce9be0969d523
[ "MIT" ]
12
2017-04-05T11:13:34.000Z
2018-06-03T14:31:03.000Z
include/pkmn/types/class_with_attributes.hpp
PMArkive/libpkmn
c683bf8b85b03eef74a132b5cfdce9be0969d523
[ "MIT" ]
2
2019-01-22T21:02:31.000Z
2019-10-30T21:20:20.000Z
/* * Copyright (c) 2017-2018 Nicholas Corgan (n.corgan@gmail.com) * * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt * or copy at http://opensource.org/licenses/MIT) */ #ifndef PKMN_CLASS_WITH_ATTRIBUTES_HPP #define PKMN_CLASS_WITH_ATTRIBUTES_HPP #include <pkmn/types/attribute_engine.hpp> namespace pkmn { /*! * @brief A base class that gives derived classes the ability to get and * set numeric, string, and boolean attributes. * * Note that some attributes are read-only. */ class class_with_attributes { public: #ifndef __DOXYGEN__ class_with_attributes() {} ~class_with_attributes () {} #endif /*! * @brief Query the numeric attribute with the given name. * * \param attribute_name The name of the attribute to query * \throws std::invalid_argument If the given attribute name doesn't exist */ inline int get_numeric_attribute( const std::string& attribute_name ) { return _numeric_attribute_engine.get_attribute(attribute_name); } /*! * @brief Sets the numeric attribute with the given name to the given * value. * * Along with the errors listed below, the attribute setter can throw * any of its own errors based on value range, etc. * * \param attribute_name The name of the attribute whose value to set * \param value The new value for the attribute * \throws std::invalid_argument If the given attribute name doesn't exist * \throws std::invalid_argument If the given attribute is valid but read-only */ inline void set_numeric_attribute( const std::string& attribute_name, int value ) { _numeric_attribute_engine.set_attribute(attribute_name, value); } /*! * @brief Returns the full list of numeric attributes. * * All attributes can be read, so all values returned from this * function are valid inputs for get_numeric_attribute(). Some * attributes are read-only and are thus invalid inputs for * set_numeric_attribute(). */ inline std::vector<std::string> get_numeric_attribute_names() { return _numeric_attribute_engine.get_attribute_names(); } /*! * @brief Query the string attribute with the given name. * * \param attribute_name The name of the attribute to query * \throws std::invalid_argument If the given attribute name doesn't exist */ inline std::string get_string_attribute( const std::string& attribute_name ) { return _string_attribute_engine.get_attribute(attribute_name); } /*! * @brief Sets the string attribute with the given name to the given * value. * * Along with the errors listed below, the attribute setter can throw * any of its own errors based on value range, etc. * * \param attribute_name The name of the attribute whose value to set * \param value The new value for the attribute * \throws std::invalid_argument If the given attribute name doesn't exist * \throws std::invalid_argument If the given attribute is valid but read-only */ inline void set_string_attribute( const std::string& attribute_name, const std::string& value ) { _string_attribute_engine.set_attribute(attribute_name, value); } /*! * @brief Returns the full list of string attributes. * * All attributes can be read, so all values returned from this * function are valid inputs for get_string_attribute(). Some * attributes are read-only and are thus invalid inputs for * set_string_attribute(). */ inline std::vector<std::string> get_string_attribute_names() { return _string_attribute_engine.get_attribute_names(); } /*! * @brief Query the boolean attribute with the given name. * * \param attribute_name The name of the attribute to query * \throws std::invalid_argument If the given attribute name doesn't exist */ inline bool get_boolean_attribute( const std::string& attribute_name ) { return _boolean_attribute_engine.get_attribute(attribute_name); } /*! * @brief Sets the boolean attribute with the given name to the given * value. * * Along with the errors listed below, the attribute setter can throw * any of its own errors based on value range, etc. * * \param attribute_name The name of the attribute whose value to set * \param value The new value for the attribute * \throws std::invalid_argument If the given attribute name doesn't exist * \throws std::invalid_argument If the given attribute is valid but read-only */ inline void set_boolean_attribute( const std::string& attribute_name, bool value ) { _boolean_attribute_engine.set_attribute(attribute_name, value); } /*! * @brief Returns the full list of boolean attributes. * * All attributes can be read, so all values returned from this * function are valid inputs for get_boolean_attribute(). Some * attributes are read-only and are thus invalid inputs for * set_boolean_attribute(). */ inline std::vector<std::string> get_boolean_attribute_names() { return _boolean_attribute_engine.get_attribute_names(); } protected: pkmn::attribute_engine<int> _numeric_attribute_engine; pkmn::attribute_engine<std::string> _string_attribute_engine; pkmn::attribute_engine<bool> _boolean_attribute_engine; }; } #endif /* PKMN_CLASS_WITH_ATTRIBUTES_HPP */
39.275862
90
0.567603
b55996a5dcbe09175c97dccc3a46f70f57def379
1,491
cpp
C++
cpp/test/test_prefix128.cpp
0xflotus/ipaddress
0d53ff453ec901e408ef28435802318282e43ccc
[ "MIT" ]
11
2017-09-28T09:14:28.000Z
2021-11-01T07:24:41.000Z
cpp/test/test_prefix128.cpp
0xflotus/ipaddress
0d53ff453ec901e408ef28435802318282e43ccc
[ "MIT" ]
1
2016-08-31T06:55:54.000Z
2016-08-31T06:55:54.000Z
cpp/test/test_prefix128.cpp
0xflotus/ipaddress
0d53ff453ec901e408ef28435802318282e43ccc
[ "MIT" ]
4
2016-08-31T06:45:32.000Z
2021-05-13T10:31:03.000Z
#include <cascara/cascara.hpp> using namespace cascara; #include "../src/prefix128.hpp" #include "../src/crunchy.hpp" using namespace ipaddress; class Prefix128Test { public: std::vector<std::pair<size_t, Crunchy>> u128_hash; }; Prefix128Test setup() { Prefix128Test p128t; p128t.u128_hash.push_back({32, Crunchy::parse("340282366841710300949110269838224261120").unwrap()}); p128t.u128_hash.push_back({64, Crunchy::parse("340282366920938463444927863358058659840").unwrap()}); p128t.u128_hash.push_back({96, Crunchy::parse("340282366920938463463374607427473244160").unwrap()}); p128t.u128_hash.push_back({126, Crunchy::parse("340282366920938463463374607431768211452").unwrap()}); return p128t; } int main() { describe("prefix128", []() { it("test_initialize", []() { assert.isTrue(Prefix128::create(129).isErr()); assert.isTrue(Prefix128::create(64).isOk()); }); it("test_method_bits", []() { auto prefix = Prefix128::create(64).unwrap(); std::stringstream str; for (auto i = 0; i < 64; ++i) { str << "1"; } for (auto i = 0; i < 64; ++i) { str << "0"; } assert.equal(str.str(), prefix.bits()); }); it("test_method_to_u32", []() { for (auto hash : setup().u128_hash) { assert.isTrue(hash.second.eq(Prefix128::create(hash.first)->netmask())); } }); }); return exit(); }
29.235294
109
0.60161
b559f6970bb54e4e750405f64b34fb16553d1021
8,652
cpp
C++
Socket/IncomingMessageHandler.cpp
Kaptnik/CIS-687-RemoteTestHarness
3a1466d4b71cef7bee2791020a2902d3e658fb64
[ "MIT" ]
null
null
null
Socket/IncomingMessageHandler.cpp
Kaptnik/CIS-687-RemoteTestHarness
3a1466d4b71cef7bee2791020a2902d3e658fb64
[ "MIT" ]
null
null
null
Socket/IncomingMessageHandler.cpp
Kaptnik/CIS-687-RemoteTestHarness
3a1466d4b71cef7bee2791020a2902d3e658fb64
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////////////////// // IncomingMessageHandler.cpp - A class that handles incoming messages // // ver 1.0 // // Karthik Umashankar, CSE687 - Object Oriented Design, Summer 2018 // //////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "IncomingMessageHandler.h" #include "..\Utilities\Credentials.h" #include "..\Utilities\Converter.h" #include "..\Utilities\Directory.h" #include "..\Utilities\File.h" #include "..\Utilities\Logger.h" #include <objbase.h> #include <fstream> using namespace Sockets; const int BLOCK_SIZE = 102400; // Set the test request queue void IncomingMessageHandler::SetTestRequestQueue(BlockingQueue<Message>* queuePointer) { _testRequestQPtr = queuePointer; } // Set the ready worker queue void IncomingMessageHandler::SetReadyWorkerQueue(BlockingQueue<Sockets::Message>* queuePointer) { _readyWorkerQPtr = queuePointer; } // Set the sender queue void IncomingMessageHandler::SetSendMessageQueue(BlockingQueue<Sockets::Message>* queuePointer) { _sendMessageQPtr = queuePointer; } void IncomingMessageHandler::SetRecvMessageQueue(BlockingQueue<Sockets::Message>* queuePointer) { _recvMessageQPtr = queuePointer; } void IncomingMessageHandler::SetContext(Sockets::CONTEXT context) { _context = context; } // Read a message from a socket as a string std::string IncomingMessageHandler::ReadMessage() { std::string temp, message; char* buffer = new char[BLOCK_SIZE]; size_t blockSize; if (_socketPointer->IsValidState()) { blockSize = _socketPointer->ReceiveStream(BLOCK_SIZE, buffer); if (blockSize > 0) { temp = buffer; message += temp.substr(0, blockSize); } } delete(buffer); return message; } // Receive a file if send on the socket bool IncomingMessageHandler::ReceiveFile(Message message) { size_t filesize = message.GetContentLength(); if (filesize == 0) return false; std::string downloadLocation; downloadLocation = message.GetFilename(); // If acting as the server, prefix the repository if (_context == Sockets::CONTEXT::SERVER) { if (downloadLocation.substr(0, 12) == "TestResults_") downloadLocation = "TESTRESULTS/" + downloadLocation; else downloadLocation = "REPOSITORY/" + downloadLocation; } std::ofstream outstream(downloadLocation, std::ios::binary); if (!outstream.good()) { return false; } std::string body = message.GetBody(); std::string decodedBody = Utilities::Convert::Base64Decode(body); outstream.write(decodedBody.c_str(), decodedBody.length()); outstream.flush(); outstream.close(); return true; } Message* IncomingMessageHandler::BuildResponse(Message& incomingMessage) { Message *response = new Message(); response->SetSource(incomingMessage.GetDestination()); response->SetDestination(incomingMessage.GetSource()); return response; } // Overloading the () operator to make this a functor void IncomingMessageHandler::operator()(Socket socket) { std::string logMessage; _socketPointer = &socket; while (_socketPointer->IsValidState()) { // Read a message from the socket std::string messageString = ReadMessage(); if (messageString.length() == 0 || messageString.length() >= BLOCK_SIZE) break; // Deserialize it to a message object Message *message = new Message(messageString); std::string body = message->GetBody(); body.erase(std::remove(body.begin(), body.end(), '\n'), body.end()); message->SetBody(body); // If message type is to get a file, respond with one. if (message->GetType() == MessageType::FILE_GET) { std::string filepath = "REPOSITORY" + message->GetBody(); std::string fileContents = Utilities::File::GetFileContents(filepath); Message* file = BuildResponse(*message); file->SetType(MessageType::FILE_POST); file->SetBody(fileContents); file->SetContentLength(fileContents.length()); file->SetFilename(message->GetFilename()); logMessage = "Sending file " + filepath + " to " + message->GetSource().AsString(); Utilities::Logger::Log(logMessage.c_str()); _sendMessageQPtr->EnQueue(*file); continue; } // If it's a mkdir request, create a directory else if (message->GetType() == MessageType::FILE_MKDIR) { std::string directory = "REPOSITORY" + message->GetBody(); CreateDirectory(directory.c_str(), NULL); continue; } // If it's a posted file, download it else if (message->GetType() == MessageType::FILE_POST) { logMessage = "Received a file (" + message->GetFilename() + ") with MessageID (" + message->GetMessageId() + ") from " + message->GetSource().AsString(); Utilities::Logger::Log(logMessage.c_str()); ReceiveFile(*message); continue; } // If it's a request to list a directory else if (message->GetType() == MessageType::FILE_LIST) { if (_context == Sockets::CONTEXT::SERVER) { std::string directory = "REPOSITORY" + message->GetBody(); Message* list = BuildResponse(*message); list->SetType(MessageType::FILE_LIST); list->SetBody(Utilities::Convert::ListToString(Utilities::Directory::GetFileSystemEntries(directory), ",")); list->SetContentLength(0); _sendMessageQPtr->EnQueue(*list); continue; } } // If it's a test request, queue it up in the // TestRequestQ, and send an acknowledgement back // to the client else if (message->GetType() == MessageType::TEST_REQUEST) { if (message->GetSource().GetUriHost() == "") break; logMessage = "Received a test request (" + message->GetMessageId() + ") from " + message->GetSource().AsString(); Utilities::Logger::Log(logMessage.c_str()); _testRequestQPtr->EnQueue(*message); Message *ack = BuildResponse(*message); ack->SetType(MessageType::TEST_ACKNOWLEDGE); ack->SetBody(message->GetMessageId()); logMessage = "Sending acknowledgement of test request to " + message->GetSource().AsString(); Utilities::Logger::Log(logMessage.c_str()); _sendMessageQPtr->EnQueue(*ack); continue; } // If it's a worker signaling they're ready, // Queue them up in the ReadyWorkerQ else if (message->GetType() == MessageType::SIGNAL_READY) { logMessage = "Worker process on " + message->GetSource().AsString() + " is ready"; Utilities::Logger::Log(logMessage.c_str()); _readyWorkerQPtr->EnQueue(*message); continue; } // If it's a SHUTDOWN message from self, stop else if (message->GetType() == MessageType::SIGNAL_SHUTDOWN) break; else if (message->GetType() == MessageType::USER_AUTHENTICATE) { if (_context == Sockets::CONTEXT::SERVER) { std::vector<std::string> credentials = Utilities::Convert::StringToList(message->GetBody()); std::string username, password; for (std::string kvp : credentials) { size_t index = kvp.find_first_of(':'); if (index == kvp.length()) continue; std::string key = kvp.substr(0, index), value = kvp.substr(index + 1, kvp.length() - index); if (key == "username") username = value; if (key == "password") password = value; } Utilities::User *user = Utilities::Credentials::Login("authentication.txt", username, password); Message *response = BuildResponse(*message); response->SetType(MessageType::USER_AUTHENTICATE); if (user != nullptr) { std::string body = "authenticated:1,fullname:" + user->Fullname; if (user->IsAdmin) body += ",isadmin:1"; response->SetBody(body); } _sendMessageQPtr->EnQueue(*response); continue; } } else if (message->GetType() == MessageType::USER_REGISTER) { Utilities::User user; for (std::string kvp : Utilities::Convert::StringToList(message->GetBody())) { size_t index = kvp.find_first_of(':'); if (index == kvp.length()) continue; std::string key = kvp.substr(0, index), value = kvp.substr(index + 1, kvp.length() - index); if (key == "username") user.Username = value; else if (key == "password") user.Password = value; else if (key == "isadmin") { if (value == "0") user.IsAdmin = false; else user.IsAdmin = true; } else if (key == "fullname") user.Fullname = value; } Utilities::Credentials::RegisterUser("authentication.txt", user); continue; } if (_context != Sockets::CONTEXT::SERVER) _recvMessageQPtr->EnQueue(*message); } }
32.526316
157
0.654877
b55bbe41b23916a348b6e2d5146b9e5a83197e9d
8,360
cpp
C++
Engine/Source/Runtime/ApplicationCore/Private/Mac/MacConsoleOutputDevice.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
1
2022-01-29T18:36:12.000Z
2022-01-29T18:36:12.000Z
Engine/Source/Runtime/ApplicationCore/Private/Mac/MacConsoleOutputDevice.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
Engine/Source/Runtime/ApplicationCore/Private/Mac/MacConsoleOutputDevice.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #include "MacConsoleOutputDevice.h" #include "Misc/App.h" #include "Misc/CoreDelegates.h" #include "Misc/ConfigCacheIni.h" #include "MacApplication.h" #include "MacPlatformApplicationMisc.h" #include "Misc/OutputDeviceHelper.h" #include "Misc/ScopeLock.h" #include "CocoaThread.h" #include "HAL/PlatformApplicationMisc.h" FMacConsoleOutputDevice::FMacConsoleOutputDevice() : ConsoleHandle(NULL) , TextView(NULL) , ScrollView(NULL) , TextViewTextColor(NULL) , OutstandingTasks(0) { } FMacConsoleOutputDevice::~FMacConsoleOutputDevice() { DestroyConsole(); } void FMacConsoleOutputDevice::SaveToINI() { if (GConfig && IniFilename.Len()) { NSRect Frame = [ConsoleHandle frame]; GConfig->SetInt(TEXT("DebugMac"), TEXT("ConsoleWidth"), Frame.size.width, IniFilename); GConfig->SetInt(TEXT("DebugMac"), TEXT("ConsoleHeight"), Frame.size.height, IniFilename); GConfig->SetInt(TEXT("DebugMac"), TEXT("ConsoleX"), Frame.origin.x, IniFilename); GConfig->SetInt(TEXT("DebugMac"), TEXT("ConsoleY"), Frame.origin.y, IniFilename); } } void FMacConsoleOutputDevice::CreateConsole() { if (ConsoleHandle || GIsBuildMachine) { return; } SCOPED_AUTORELEASE_POOL; int32 ConsoleWidth = 800; int32 ConsoleHeight = 600; int32 ConsolePosX = 0; int32 ConsolePosY = 0; bool bHasX = false; bool bHasY = false; if(GConfig) { GConfig->GetInt(TEXT("DebugMac"), TEXT("ConsoleWidth"), ConsoleWidth, GGameIni); GConfig->GetInt(TEXT("DebugMac"), TEXT("ConsoleHeight"), ConsoleHeight, GGameIni); bHasX = GConfig->GetInt(TEXT("DebugMac"), TEXT("ConsoleX"), ConsolePosX, GGameIni); bHasY = GConfig->GetInt(TEXT("DebugMac"), TEXT("ConsoleY"), ConsolePosY, GGameIni); } MainThreadCall(^{ ConsoleHandle = [[FMacConsoleWindow alloc] initWithContentRect: NSMakeRect(ConsolePosX, ConsolePosY, ConsoleWidth, ConsoleHeight) styleMask: (NSTitledWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask | NSResizableWindowMask) backing: NSBackingStoreBuffered defer: NO]; [ConsoleHandle setDelegate:ConsoleHandle]; ScrollView = [[NSScrollView alloc] initWithFrame:[[ConsoleHandle contentView] frame]]; NSSize ContentSize = [ScrollView contentSize]; [ScrollView setBorderType:NSNoBorder]; [ScrollView setHasVerticalScroller:YES]; [ScrollView setHasHorizontalScroller:NO]; [ScrollView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable]; TextView = [[NSTextView alloc] initWithFrame:NSMakeRect( 0, 0, ContentSize.width, ContentSize.height )]; [TextView setMinSize:NSMakeSize( 0.0, ContentSize.height ) ]; [TextView setMaxSize:NSMakeSize( FLT_MAX, FLT_MAX )]; [TextView setVerticallyResizable:YES]; [TextView setHorizontallyResizable:NO]; [TextView setAutoresizingMask:NSViewWidthSizable]; [TextView setBackgroundColor: [NSColor blackColor]]; [[TextView textContainer] setContainerSize:NSMakeSize( ContentSize.width, FLT_MAX )]; [[TextView textContainer] setWidthTracksTextView:YES]; [ScrollView setDocumentView:TextView]; [ConsoleHandle setContentView:ScrollView]; if (!bHasX || !bHasY) { [ConsoleHandle center]; } [ConsoleHandle setOpaque:YES]; [ConsoleHandle makeKeyAndOrderFront:nil]; if(!MacApplication) { do { FMacPlatformApplicationMisc::PumpMessages( true ); } while(ConsoleHandle && ![ConsoleHandle isVisible]); } SetDefaultTextColor(); }, UE4NilEventMode, true); } void FMacConsoleOutputDevice::DestroyConsole() { if (ConsoleHandle) { do { FMacPlatformApplicationMisc::PumpMessages( true ); } while(OutstandingTasks); SaveToINI(); MainThreadCall(^{ SCOPED_AUTORELEASE_POOL; if( TextViewTextColor ) [TextViewTextColor release]; [ConsoleHandle close]; ConsoleHandle = NULL; TextViewTextColor = NULL; }, UE4NilEventMode, true); } } void FMacConsoleOutputDevice::Show( bool ShowWindow ) { if( ShowWindow ) { CreateConsole(); } else { DestroyConsole(); } } bool FMacConsoleOutputDevice::IsShown() { return ConsoleHandle != NULL; } void FMacConsoleOutputDevice::Serialize( const TCHAR* Data, ELogVerbosity::Type Verbosity, const class FName& Category ) { if( ConsoleHandle ) { FScopeLock ScopeLock( &CriticalSection ); static bool Entry=0; if( !GIsCriticalError || Entry ) { // here we can change the color of the text to display, it's in the format: // ForegroundRed | ForegroundGreen | ForegroundBlue | ForegroundBright | BackgroundRed | BackgroundGreen | BackgroundBlue | BackgroundBright // where each value is either 0 or 1 (can leave off trailing 0's), so // blue on bright yellow is "00101101" and red on black is "1" // An empty string reverts to the normal gray on black if (Verbosity == ELogVerbosity::SetColor) { if (FCString::Stricmp(Data, TEXT("")) == 0) { SetDefaultTextColor(); } else { SCOPED_AUTORELEASE_POOL; // turn the string into a bunch of 0's and 1's TCHAR String[9]; FMemory::Memset(String, 0, sizeof(TCHAR) * ARRAY_COUNT(String)); FCString::Strncpy(String, Data, ARRAY_COUNT(String)); for (TCHAR* S = String; *S; S++) { *S -= '0'; } NSMutableArray* Colors = [[NSMutableArray alloc] init]; NSMutableArray* AttributeKeys = [[NSMutableArray alloc] init]; // Get FOREGROUND_INTENSITY and calculate final color CGFloat Intensity = String[3] ? 1.0 : 0.5; [Colors addObject:[NSColor colorWithSRGBRed:(String[0] ? 1.0 * Intensity : 0.0) green:(String[1] ? 1.0 * Intensity : 0.0) blue:(String[2] ? 1.0 * Intensity : 0.0) alpha:1.0]]; // Get BACKGROUND_INTENSITY and calculate final color Intensity = String[7] ? 1.0 : 0.5; [Colors addObject:[NSColor colorWithSRGBRed:(String[4] ? 1.0 * Intensity : 0.0) green:(String[5] ? 1.0 * Intensity : 0.0) blue:(String[6] ? 1.0 * Intensity : 0.0) alpha:1.0]]; [AttributeKeys addObject:NSForegroundColorAttributeName]; [AttributeKeys addObject:NSBackgroundColorAttributeName]; OutstandingTasks++; MainThreadCall(^{ if( TextViewTextColor ) [TextViewTextColor release]; TextViewTextColor = [[NSDictionary alloc] initWithObjects:Colors forKeys:AttributeKeys]; [Colors release]; [AttributeKeys release]; OutstandingTasks--; }, NSDefaultRunLoopMode, false); } } else { SCOPED_AUTORELEASE_POOL; TCHAR OutputString[MAX_SPRINTF]=TEXT(""); //@warning: this is safe as FCString::Sprintf only use 1024 characters max FCString::Sprintf(OutputString,TEXT("%s%s"),*FOutputDeviceHelper::FormatLogLine(Verbosity, Category, Data, GPrintLogTimes),LINE_TERMINATOR); CFStringRef CocoaText = FPlatformString::TCHARToCFString(OutputString); OutstandingTasks++; MainThreadCall(^{ NSAttributedString *AttributedString = [[NSAttributedString alloc] initWithString:(NSString*)CocoaText attributes:TextViewTextColor]; [[TextView textStorage] appendAttributedString:AttributedString]; [TextView scrollRangeToVisible:NSMakeRange([[TextView string] length], 0)]; [AttributedString release]; CFRelease(CocoaText); OutstandingTasks--; }, NSDefaultRunLoopMode, false); if(!MacApplication) { FMacPlatformApplicationMisc::PumpMessages( true ); } } } else { Entry=1; try { // Ignore errors to prevent infinite-recursive exception reporting. Serialize( Data, Verbosity, Category ); } catch( ... ) {} Entry=0; } } } void FMacConsoleOutputDevice::SetDefaultTextColor() { SCOPED_AUTORELEASE_POOL; FScopeLock ScopeLock( &CriticalSection ); NSMutableArray* Colors = [[NSMutableArray alloc] init]; NSMutableArray* AttributeKeys = [[NSMutableArray alloc] init]; [Colors addObject:[NSColor grayColor]]; [Colors addObject:[NSColor blackColor]]; [AttributeKeys addObject:NSForegroundColorAttributeName]; [AttributeKeys addObject:NSBackgroundColorAttributeName]; OutstandingTasks++; MainThreadCall(^{ if( TextViewTextColor ) [TextViewTextColor release]; TextViewTextColor = [[NSDictionary alloc] initWithObjects:Colors forKeys:AttributeKeys]; [Colors release]; [AttributeKeys release]; OutstandingTasks--; }, NSDefaultRunLoopMode, false); }
29.75089
180
0.71244
b55be79846204fcc7725da9029f1c2ecec9edf9a
1,029
cpp
C++
C++/dnf_sort.cpp
ayushyado/HACKTOBERFEST2021-2
b63d568fd7f33023ca0b0dbd91325444c70c4d10
[ "MIT" ]
125
2021-10-01T19:05:26.000Z
2021-10-03T13:32:42.000Z
C++/dnf_sort.cpp
ayushyado/HACKTOBERFEST2021-2
b63d568fd7f33023ca0b0dbd91325444c70c4d10
[ "MIT" ]
201
2021-10-30T20:40:01.000Z
2022-03-22T17:26:28.000Z
C++/dnf_sort.cpp
ayushyado/HACKTOBERFEST2021-2
b63d568fd7f33023ca0b0dbd91325444c70c4d10
[ "MIT" ]
294
2021-10-01T18:46:05.000Z
2021-10-03T14:25:07.000Z
#include <bits/stdc++.h> using namespace std; //this sorting algorithm is for sorting 0s,1s and 2s //we have to traverse the whole array or vector //so the time complexity becomes O(n) void dnfsort(vector<int>&v){ int n = v.size(); //here we will be having three pointers //forb iterating through the vector int low =0; int mid = 0; int high = n-1; while(mid<=high){ if(v[mid]==0){ swap(v[mid],v[low]); low++; mid++; } else if(v[mid]==1){ mid++; } else{ swap(v[mid],v[high]); high--; } } } int main(){ cout<<"Enter the size of the vector :"; int n; cin>>n; vector<int> v; cout<<"\n"; cout<<"Enter the vector elemnts :"<<"\n"; while(n--){ int x; cin>>x; v.push_back(x); } dnfsort(v); cout<<"\n"; cout<<"Now the sorted vector is : "<<"\n"; for(int i : v ){ cout<<i<<" "; } return 0; }
19.788462
52
0.47619
b55f75814e6ddfa4e911f9b69ec6adf31340e725
7,949
cpp
C++
src/MD5/MD5.cpp
mykhailok01/RS5_Implementation
4fd3e00ae74c4c8d143112e1a9bf01cb423b0cd1
[ "MIT" ]
null
null
null
src/MD5/MD5.cpp
mykhailok01/RS5_Implementation
4fd3e00ae74c4c8d143112e1a9bf01cb423b0cd1
[ "MIT" ]
null
null
null
src/MD5/MD5.cpp
mykhailok01/RS5_Implementation
4fd3e00ae74c4c8d143112e1a9bf01cb423b0cd1
[ "MIT" ]
null
null
null
#include "MD5.hpp" #include <climits> #include <cassert> #include <sstream> #include <vector> #include <iostream> #include <limits> #include <bitset> using Chunk = std::array<std::uint32_t, 16>;// 512 bit constexpr size_t CHUNK_SIZE = sizeof(Chunk::value_type) * 16; constexpr auto BITS_CHUNK_SIZE = static_cast<std::uint64_t>(CHUNK_SIZE) * CHAR_BIT; constexpr uint64_t BITS_SIZE_PART_SIZE = sizeof(uint64_t) * CHAR_BIT; constexpr size_t BITS_CHUNK_PART_SIZE = sizeof(Chunk::value_type) * CHAR_BIT; template <typename I> std::string toString(I val, size_t hexLen = sizeof(I)<<1) { static const char* digits = "0123456789ABCDEF"; std::string result(hexLen,'0'); for (size_t i=0, j=(hexLen-1)*4 ; i<hexLen; ++i,j-=4) result[i] = digits[(val>>j) & 0x0f]; return result; } template <typename I, uint64_t binLen = sizeof(I) * CHAR_BIT> std::string toBinaryStr(I val) { return std::bitset<binLen>(val).to_string(); } std::string toString(const Chunk &chunk) { std::string result; for(size_t i = 0; i < chunk.size() - 1; ++i) result += toString(chunk[i]) + " "; result += toString(chunk.back()); return result; } std::uint32_t convert(const std::string &data, std::size_t begin) { assert(begin < data.size()); std::uint32_t value = 0; size_t i = begin, end = begin + 4; for (; i < end && i < data.size(); ++i) { value <<=CHAR_BIT; value += static_cast<std::uint32_t>(data[i]); } return value << (end - i) * CHAR_BIT; } std::vector<Chunk> toChunks(const std::string& data) { std::vector<Chunk> result; for(size_t chunckBeginning = 0; chunckBeginning < data.size(); chunckBeginning += 64) { Chunk chunk = {}; for (size_t index32Bit = 0, dataIndex = chunckBeginning; index32Bit < chunk.size() && dataIndex < data.size(); index32Bit++) { chunk[index32Bit] = convert(data, dataIndex); dataIndex += sizeof(chunk[index32Bit]); } result.push_back(chunk); } if (result.empty()) result.push_back(Chunk()); return result; } void alignSizeTo448Mod512(std::vector<Chunk> &chunks, std::uint64_t bitsDataSize) { if (bitsDataSize >= BITS_CHUNK_SIZE * chunks.size() - BITS_SIZE_PART_SIZE) chunks.push_back(Chunk()); } Chunk::value_type revertBytes(Chunk::value_type value) { auto selectByte = [] (Chunk::value_type val, size_t i)->Chunk::value_type { size_t firstBit = i * CHAR_BIT; val = val << firstBit >> firstBit; size_t bitsToEnd = BITS_CHUNK_PART_SIZE - firstBit - CHAR_BIT; val = val >> bitsToEnd << bitsToEnd; return val; }; return selectByte(value, 0) >> (BITS_CHUNK_PART_SIZE - CHAR_BIT) | selectByte(value, 1) >> CHAR_BIT | selectByte(value, 2) << CHAR_BIT | selectByte(value, 3) << (BITS_CHUNK_PART_SIZE - CHAR_BIT); } void insertLeadingBit(std::vector<Chunk> &chunks, std::uint64_t bitsDataSize) { auto lastDataChunkIndex = bitsDataSize / BITS_CHUNK_SIZE; Chunk &lastDataChunk = chunks[lastDataChunkIndex]; auto bitsDataSizeRest = (bitsDataSize % BITS_CHUNK_SIZE); auto &lastDataChunkPart = lastDataChunk[bitsDataSizeRest / BITS_CHUNK_PART_SIZE]; bitsDataSizeRest %= BITS_CHUNK_PART_SIZE; lastDataChunkPart |= (1ul << (BITS_CHUNK_PART_SIZE - bitsDataSizeRest - 1)); } void insertDataSize(std::vector<Chunk> &chunks, std::uint64_t bitsDataSize) { auto &lastChunk = chunks.back(); auto &lastChunkPart = lastChunk.back(); lastChunkPart = revertBytes(bitsDataSize >> BITS_CHUNK_PART_SIZE); auto &penultimateChunkPart = lastChunk[lastChunk.size() - 2]; penultimateChunkPart = revertBytes(bitsDataSize << BITS_CHUNK_PART_SIZE >> BITS_CHUNK_PART_SIZE); } Chunk::value_type leftRotate(Chunk::value_type value, size_t amount) { assert(amount <= 31); Chunk::value_type mask = (1u << amount) - 1; Chunk::value_type left = value << amount; Chunk::value_type right = value >> (BITS_CHUNK_PART_SIZE - amount); return (left & ~mask) | (right & mask); } MD5Hash calculateMD5Hash(const std::vector<Chunk> &chunks) { constexpr std::array<std::size_t, 64> s = { 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21 }; constexpr std::array<std::uint32_t, 64> K = { 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8, 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391 }; MD5Hash hash = { 0x67452301,// A 0xefcdab89,// B 0x98badcfe,// C 0x10325476 // D }; for (const auto& chunk : chunks) { MD5Hash tmpHash = hash; for (size_t i = 0; i < K.size(); ++i) { MD5Hash::value_type F = 0; size_t g = 0; if (0 <= i && i <= 15) { F = (tmpHash[1] & tmpHash[2]) | (~tmpHash[1] & tmpHash[3]); g = i; } else if (16 <= i && i <= 31) { F = (tmpHash[3] & tmpHash[1]) | (~tmpHash[3] & tmpHash[2]); g = (5 * i + 1) % 16; } else if (32 <= i && i <= 47) { F = tmpHash[1] ^ tmpHash[2] ^ tmpHash[3]; g = (3 * i + 5) % 16; } else if (48 <= i && i <= 63) { F = tmpHash[2] ^ (tmpHash[1] | (~tmpHash[3])); g = (7 * i) % 16; } F = (F + tmpHash[0] + K[i] + chunk[g]) & ~std::uint32_t(0); tmpHash[0] = tmpHash[3]; tmpHash[3] = tmpHash[2]; tmpHash[2] = tmpHash[1]; tmpHash[1] = tmpHash[1] + leftRotate(F, s[i]); } for (size_t i = 0; i < hash.size(); ++i) { hash[i] += tmpHash[i]; } } for (auto& val : hash) val = revertBytes(val); return hash; } void revertBytesInEachChunk(std::vector<Chunk>& chunks) { for(auto &chunk: chunks) for(auto & word: chunk) word = revertBytes(word); } std::array<std::uint32_t, 4> generateMD5Hash(const std::string &data) { static_assert(CHAR_BIT == 8, "generateMD5Hash requires byte to be 8 bit long"); static_assert(sizeof(size_t) == 8 || sizeof(size_t) == 4, "generateMD5Hash requires size_t to be 8 or 4 bytes "); std::uint64_t bitsDataSize = static_cast<std::uint64_t>(data.size()) * sizeof(std::string::value_type) * CHAR_BIT; assert(bitsDataSize != std::numeric_limits<std::uint64_t>::max()); auto chunks = toChunks(data); alignSizeTo448Mod512(chunks, bitsDataSize); insertLeadingBit(chunks, bitsDataSize); insertDataSize(chunks, bitsDataSize); revertBytesInEachChunk(chunks); return calculateMD5Hash(chunks); } std::string toString(const MD5Hash &hash) { std::string result; for(size_t i = 0; i < hash.size(); ++i) result += toString(hash[i]); return result; }
34.71179
118
0.602592
b55fbdbfacd906739e63e2851b93ebfc455b8733
1,443
cpp
C++
cpp/opendnp3/src/opendnp3/objects/Group51.cpp
tarm/dnp3_orig
87c639b3462c980fba255e85793f6ec663abe981
[ "Apache-2.0" ]
null
null
null
cpp/opendnp3/src/opendnp3/objects/Group51.cpp
tarm/dnp3_orig
87c639b3462c980fba255e85793f6ec663abe981
[ "Apache-2.0" ]
null
null
null
cpp/opendnp3/src/opendnp3/objects/Group51.cpp
tarm/dnp3_orig
87c639b3462c980fba255e85793f6ec663abe981
[ "Apache-2.0" ]
3
2016-07-13T18:54:13.000Z
2021-04-12T13:30:39.000Z
// // _ _ ______ _ _ _ _ _ _ _ // | \ | | | ____| | (_) | (_) | | | | // | \| | ___ | |__ __| |_| |_ _ _ __ __ _| | | | // | . ` |/ _ \ | __| / _` | | __| | '_ \ / _` | | | | // | |\ | (_) | | |___| (_| | | |_| | | | | (_| |_|_|_| // |_| \_|\___/ |______\__,_|_|\__|_|_| |_|\__, (_|_|_) // __/ | // |___/ // Copyright 2013 Automatak LLC // // Automatak LLC (www.automatak.com) licenses this file // to you under the the Apache License Version 2.0 (the "License"): // // http://www.apache.org/licenses/LICENSE-2.0.html // #include "Group51.h" #include <openpal/Serialization.h> using namespace openpal; namespace opendnp3 { const GroupVariationID Group51Var1::ID(51,1); Group51Var1 Group51Var1::Read(ReadOnlyBuffer& buffer) { Group51Var1 obj; obj.time = UInt48::Read(buffer); buffer.Advance(6); return obj; } void Group51Var1::Write(const Group51Var1& arg, openpal::WriteBuffer& buffer) { UInt48::Write(buffer, arg.time); buffer.Advance(6); } const GroupVariationID Group51Var2::ID(51,2); Group51Var2 Group51Var2::Read(ReadOnlyBuffer& buffer) { Group51Var2 obj; obj.time = UInt48::Read(buffer); buffer.Advance(6); return obj; } void Group51Var2::Write(const Group51Var2& arg, openpal::WriteBuffer& buffer) { UInt48::Write(buffer, arg.time); buffer.Advance(6); } }
24.05
77
0.559252
b5623319810028e4069c7445e0129611ab599b5a
11,007
hpp
C++
src/core/utils/maybe.hpp
lowkey42/BanishedBlaze
71e66f444a84bea1eca3639de3f3ff1f79e385d1
[ "MIT" ]
null
null
null
src/core/utils/maybe.hpp
lowkey42/BanishedBlaze
71e66f444a84bea1eca3639de3f3ff1f79e385d1
[ "MIT" ]
null
null
null
src/core/utils/maybe.hpp
lowkey42/BanishedBlaze
71e66f444a84bea1eca3639de3f3ff1f79e385d1
[ "MIT" ]
null
null
null
/** simple wrapper for optional values or references ************************* * * * Copyright (c) 2014 Florian Oetke * * This file is distributed under the MIT License * * See LICENSE file for details. * \*****************************************************************************/ #pragma once #include "log.hpp" #include "func_traits.hpp" #include <stdexcept> #include <functional> #include <memory> #include <type_traits> namespace lux { namespace util { namespace details { struct maybe_else_callable { bool is_nothing; template<typename Func> void on_nothing(Func f) { if(is_nothing) f(); } }; } template<typename T> class maybe { public: maybe()noexcept : _valid(false) {} /*implicit*/ maybe(T&& data)noexcept : _valid(true), _data(std::move(data)) {} /*implicit*/ maybe(const T& data)noexcept : _valid(true), _data(data) {} maybe(const maybe& o)noexcept : _valid(o._valid), _data(o._data) {} maybe(maybe&& o)noexcept : _valid(o._valid), _data(std::move(o._data)) { o._valid = false; } ~maybe()noexcept { if(is_some()) _data.~T(); } operator maybe<const T>()const noexcept { return is_some() ? maybe<const T>(_data) : maybe<const T>::nothing(); } bool operator!()const noexcept { return is_nothing(); } maybe& operator=(const maybe& o)noexcept { _valid = o._valid; _data = o._data; return *this; } maybe& operator=(maybe&& o)noexcept { if(o._valid) { if(_valid) _data = std::move(o._data); else new(&_data) T(std::move(o._data)); o._data.~T(); } _valid = o._valid; o._valid = false; return *this; } static maybe nothing() noexcept { return maybe(); } bool is_some()const noexcept { return _valid; } bool is_nothing()const noexcept { return !is_some(); } T& get_or_throw() { INVARIANT(is_some(), "Called getOrThrow on nothing."); return _data; } const T& get_or_throw()const { INVARIANT(is_some(), "Called getOrThrow on nothing."); return _data; } T& get_ref_or_other(T& other)noexcept { return is_some() ? _data : other; } const T& get_ref_or_other(const T& other)const noexcept { return is_some() ? _data : other; } T get_or_other(T other)const noexcept { return is_some() ? _data : other; } template<typename Func, class=std::enable_if_t<std::is_same<std::result_of_t<Func(T&)>, void>::value>> void process(Func&& f)const { if(is_some()) f(_data); } template<typename Func, class=std::enable_if_t<not std::is_same<std::result_of_t<Func(T&)>, void>::value>> auto process(Func&& f)const -> maybe<std::result_of_t<Func(const T&)>> { if(is_some()) return f(_data); else return nothing(); } template<typename Func, class=std::enable_if_t<std::is_same<std::result_of_t<Func(T&)>, void>::value>> void process(Func&& f) { if(is_some()) f(_data); } template<typename Func, class=std::enable_if_t<not std::is_same<std::result_of_t<Func(T&)>, void>::value>> auto process(Func&& f) -> maybe<std::result_of_t<Func(T&)>> { if(is_some()) return f(_data); else return nothing(); } template<typename RT, typename Func> auto process(RT def, Func&& f) -> RT { if(is_some()) return f(_data); return def; } template<typename RT, typename Func> auto process(RT def, Func&& f)const -> RT { if(is_some()) return f(_data); return def; } private: bool _valid; union { T _data; }; }; // TODO: change to nothing_t struct nothing { template<typename T> operator maybe<T>()const noexcept { return maybe<T>::nothing(); } }; template<typename T> maybe<std::remove_reference_t<T>> just(T&& inst) { return maybe<std::remove_reference_t<T>>(std::forward<T>(inst)); } template<typename T> maybe<T> justCopy(const T& inst) { return maybe<T>(inst); } template<typename T> maybe<T&> justPtr(T* inst) { return inst!=nullptr ? maybe<T&>(*inst) : nothing(); } template<typename T, typename Func> auto operator>>(const maybe<T>& t, Func f) -> std::enable_if_t<!std::is_same<void,decltype(f(t.get_or_throw()))>::value, maybe<decltype(f(t.get_or_throw()))>> { return t.is_some() ? just(f(t.get_or_throw())) : nothing(); } template<typename T, typename Func> auto operator>>(const maybe<T>& t, Func f) -> std::enable_if_t<std::is_same<void,decltype(f(t.get_or_throw()))>::value, void> { if(t.is_some()) f(t.get_or_throw()); } template<typename T> bool operator! (const maybe<T>& m) { return !m.is_some(); } template<typename T> class maybe<T&> { public: maybe() : _ref(nullptr) {} /*implicit*/ maybe(T& data)noexcept : _ref(&data) {} template<typename U, class = std::enable_if_t<std::is_convertible<U*, T*>::value> > maybe(U& o)noexcept : _ref(&o) {} maybe(const maybe& o)noexcept : _ref(o._ref) {} maybe(maybe&& o)noexcept : _ref(o._ref) { o._ref = nullptr; } template<typename U, class = std::enable_if_t<std::is_convertible<U*, T*>::value> > maybe(const maybe<U>& o)noexcept : _ref(o._ref) {} ~maybe()noexcept = default; operator maybe<const T&>()const noexcept { return is_some() ? maybe<const T&>(*_ref) : maybe<const T&>::nothing(); } bool operator!()const noexcept { return is_nothing(); } maybe& operator=(const maybe& o)noexcept { _ref = o._ref; return *this; } maybe& operator=(maybe&& o)noexcept { std::swap(_ref=nullptr, o._ref); return *this; } static maybe nothing() noexcept { return maybe(); } bool is_some()const noexcept { return _ref!=nullptr; } bool is_nothing()const noexcept { return !is_some(); } T& get_or_throw()const { INVARIANT(is_some(), "Called getOrThrow on nothing."); return *_ref; } T& get_or_other(std::remove_const_t<T>& other)const noexcept { return is_some() ? *_ref : other; } const T& get_or_other(const T& other)const noexcept { return is_some() ? *_ref : other; } template<typename Func, class=std::enable_if_t<std::is_same<std::result_of_t<Func(T&)>, void>::value>> void process(Func&& f)const { if(is_some()) f(*_ref); } template<typename Func, class=std::enable_if_t<not std::is_same<std::result_of_t<Func(T&)>, void>::value>> auto process(Func&& f)const -> maybe<std::result_of_t<Func(const T&)>> { if(is_some()) return f(*_ref); else return nothing(); } template<typename Func, class=std::enable_if_t<std::is_same<std::result_of_t<Func(T&)>, void>::value>> void process(Func&& f) { if(is_some()) f(*_ref); } template<typename Func, class=std::enable_if_t<not std::is_same<std::result_of_t<Func(T&)>, void>::value>> auto process(Func&& f) -> maybe<std::result_of_t<Func(T&)>> { if(is_some()) return f(*_ref); else return nothing(); } template<typename RT, typename Func> auto process(RT def, Func&& f) -> RT { if(is_some()) return f(get_or_throw()); return def; } template<typename RT, typename Func> auto process(RT def, Func&& f)const -> RT { if(is_some()) return f(get_or_throw()); return def; } private: T* _ref; }; namespace details { template<int ...> struct seq { }; template<int N, int ...S> struct gens : gens<N-1, N-1, S...> { }; template<int ...S> struct gens<0, S...> { typedef seq<S...> type; }; template<typename... T> struct processor { std::tuple<T&&...> args; template<typename Func> void operator>>(Func&& f) { call(std::forward<Func>(f), typename gens<sizeof...(T)>::type()); } private: template<typename Func, int ...S> void call(Func&& f, seq<S...>) { call(std::forward<Func>(f), std::forward<decltype(std::get<S>(args))>(std::get<S>(args))...); } template<typename Func, typename... Args> void call(Func&& f, Args&&... m) { for(bool b : {m.is_some()...}) if(!b) return; f(m.get_or_throw()...); } }; } /* * Usage: * maybe<bool> b = true; * maybe<int> i = nothing(); * maybe<float> f = 1.0f; * * process(b,i,f)>> [](bool b, int i, float& f){ * // ... * }; */ template<typename... T> auto process(T&&... m) -> details::processor<T...> { return details::processor<T...>{std::tuple<decltype(m)...>(std::forward<T>(m)...)}; } template<class Map, class Key> auto find_maybe(Map& map, const Key& key) -> auto { auto iter = map.find(key); return iter!=map.end() ? justPtr(&iter->second) : nothing(); } template<typename T> class lazy { public: using source_t = std::function<T()>; /*implicit*/ lazy(source_t s) : _source(s){} operator T(){ return _source; } private: source_t _source; }; template<typename T> inline lazy<T> later(typename lazy<T>::source_t f) { return lazy<T>(f); } template <class F> struct return_type; template <class R, class T, class... A> struct return_type<R (T::*)(A...)> { typedef R type; }; template <class R, class... A> struct return_type<R (*)(A...)> { typedef R type; }; template<typename S, typename T> inline lazy<T> later(S* s, T (S::*f)()) { std::weak_ptr<S> weak_s = s->shared_from_this(); return lazy<T>([weak_s, f](){ auto shared_s = weak_s.lock(); if(shared_s) { auto s = shared_s.get(); return (s->*f)(); } else { return T{}; } }); } } } #ifdef LUX_DEFINE_MAYBE_MACROS #define LUX_NARGS_SEQ(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,N,...) N #define LUX_NARGS(...) LUX_NARGS_SEQ(__VA_ARGS__, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0) /* This will let macros expand before concating them */ #define LUX_PRIMITIVE_CAT(x, y) x ## y #define LUX_CAT(x, y) LUX_PRIMITIVE_CAT(x, y) #define LUX_APPLY(macro, ...) LUX_CAT(LUX_APPLY_, LUX_NARGS(__VA_ARGS__))(macro, __VA_ARGS__) #define LUX_APPLY_1(m, x1) m(x1) #define LUX_APPLY_2(m, x, ...) m(x), LUX_APPLY_1(m,__VA_ARGS__) #define LUX_APPLY_3(m, x, ...) m(x), LUX_APPLY_2(m,__VA_ARGS__) #define LUX_APPLY_4(m, x, ...) m(x), LUX_APPLY_3(m,__VA_ARGS__) #define LUX_APPLY_5(m, x, ...) m(x), LUX_APPLY_4(m,__VA_ARGS__) #define LUX_APPLY_6(m, x, ...) m(x), LUX_APPLY_5(m,__VA_ARGS__) #define LUX_APPLY_7(m, x, ...) m(x), LUX_APPLY_6(m,__VA_ARGS__) #define LUX_APPLY_8(m, x, ...) m(x), LUX_APPLY_7(m,__VA_ARGS__) #define LUX_APPLY_9(m, x, ...) m(x), LUX_APPLY_8(m,__VA_ARGS__) #define LUX_APPLY_10(m, x, ...) m(x), LUX_APPLY_9(m,__VA_ARGS__) #define LUX_PROCESS_MAYBE_ARG_EXP(name) decltype(name.get_or_throw()) name #define LUX_PROCESS_MAYBE(...) ::lux::util::process(__VA_ARGS__) >> [&](LUX_APPLY(LUX_PROCESS_MAYBE_ARG_EXP, __VA_ARGS__)) #endif
25.187643
123
0.600073
b5630a7c5a980b93057022c640b102796a94a44f
8,802
cpp
C++
src/mesh/store/nodestore.cpp
It4innovations/mesio
de966f2a13e1e301be818485815d43ceff1e7094
[ "BSD-3-Clause" ]
1
2021-09-16T10:15:50.000Z
2021-09-16T10:15:50.000Z
src/mesh/store/nodestore.cpp
It4innovations/mesio
de966f2a13e1e301be818485815d43ceff1e7094
[ "BSD-3-Clause" ]
null
null
null
src/mesh/store/nodestore.cpp
It4innovations/mesio
de966f2a13e1e301be818485815d43ceff1e7094
[ "BSD-3-Clause" ]
null
null
null
#include "store.h" #include "nodestore.h" #include "statisticsstore.h" #include "mesh/mesh.h" #include "esinfo/mpiinfo.h" #include "esinfo/meshinfo.h" #include "basis/containers/point.h" #include "basis/containers/serializededata.h" #include "basis/utilities/packing.h" using namespace mesio; NodeStore::NodeStore() : size(0), distribution({0, 0}), IDs(NULL), elements(NULL), originCoordinates(NULL), coordinates(NULL), ranks(NULL), domains(NULL) { } size_t NodeStore::packedFullSize() const { size_t packedSize = 0; packedSize += utils::packedSize(size); packedSize += utils::packedSize(uniqInfo.nhalo); packedSize += utils::packedSize(uniqInfo.offset); packedSize += utils::packedSize(uniqInfo.size); packedSize += utils::packedSize(uniqInfo.totalSize); packedSize += utils::packedSize(uniqInfo.position); packedSize += utils::packedSize(distribution); packedSize += utils::packedSize(IDs); packedSize += utils::packedSize(elements); packedSize += utils::packedSize(originCoordinates); packedSize += utils::packedSize(coordinates); packedSize += utils::packedSize(ranks); packedSize += utils::packedSize(domains); packedSize += utils::packedSize(data.size()); for (size_t i = 0; i < data.size(); i++) { packedSize += data[i]->packedSize(); } return packedSize; } void NodeStore::packFull(char* &p) const { utils::pack(size, p); utils::pack(uniqInfo.nhalo, p); utils::pack(uniqInfo.offset, p); utils::pack(uniqInfo.size, p); utils::pack(uniqInfo.totalSize, p); utils::pack(uniqInfo.position, p); utils::pack(distribution, p); utils::pack(IDs, p); utils::pack(elements, p); utils::pack(originCoordinates, p); utils::pack(coordinates, p); utils::pack(ranks, p); utils::pack(domains, p); utils::pack(data.size(), p); for (size_t i = 0; i < data.size(); i++) { data[i]->pack(p); } } void NodeStore::unpackFull(const char* &p) { utils::unpack(size, p); utils::unpack(uniqInfo.nhalo, p); utils::unpack(uniqInfo.offset, p); utils::unpack(uniqInfo.size, p); utils::unpack(uniqInfo.totalSize, p); utils::unpack(uniqInfo.position, p); utils::unpack(distribution, p); utils::unpack(IDs, p); utils::unpack(elements, p); utils::unpack(originCoordinates, p); utils::unpack(coordinates, p); utils::unpack(ranks, p); utils::unpack(domains, p); size_t size; utils::unpack(size, p); for (size_t i = 0; i < size; i++) { data.push_back(new NodeData(p)); } } size_t NodeStore::packedSize() const { return utils::packedSize(size) + utils::packedSize(uniqInfo.nhalo) + utils::packedSize(uniqInfo.offset) + utils::packedSize(uniqInfo.size) + utils::packedSize(uniqInfo.totalSize) + utils::packedSize(uniqInfo.position) + IDs->packedSize() + coordinates->packedSize(); } void NodeStore::pack(char* &p) const { utils::pack(size, p); utils::pack(uniqInfo.nhalo, p); utils::pack(uniqInfo.offset, p); utils::pack(uniqInfo.size, p); utils::pack(uniqInfo.totalSize, p); utils::pack(uniqInfo.position, p); IDs->pack(p); coordinates->pack(p); } void NodeStore::unpack(const char* &p) { if (IDs == NULL) { IDs = new serializededata<esint, esint>(1, tarray<esint>(1, 0)); } if (coordinates == NULL) { coordinates = new serializededata<esint, Point>(1, tarray<Point>(1, 0)); } utils::unpack(size, p); utils::unpack(uniqInfo.nhalo, p); utils::unpack(uniqInfo.offset, p); utils::unpack(uniqInfo.size, p); utils::unpack(uniqInfo.totalSize, p); utils::unpack(uniqInfo.position, p); IDs->unpack(p); coordinates->unpack(p); } size_t NodeStore::packedDataHeaderSize() const { size_t size = sizeof(size_t); for (size_t i = 0; i < data.size(); i++) { if (data[i]->name.size()) { size += utils::packedSize(data[i]->dimension); size += utils::packedSize(data[i]->dataType); size += utils::packedSize(data[i]->name); } } return size; } void NodeStore::packDataHeader(char* &p) const { size_t size = 0; for (size_t i = 0; i < data.size(); i++) { if (data[i]->name.size()) { size += 1; } } utils::pack(size, p); for (size_t i = 0; i < data.size(); i++) { if (data[i]->name.size()) { utils::pack(data[i]->dimension, p); utils::pack(data[i]->dataType, p); utils::pack(data[i]->name, p); } } } void NodeStore::unpackDataHeader(const char* &p) { size_t size; utils::unpack(size, p); for (size_t i = 0; i < size; i++) { data.push_back(new NodeData(0, NamedData::DataType::VECTOR, {})); utils::unpack(data[i]->dimension, p); utils::unpack(data[i]->dataType, p); utils::unpack(data[i]->name, p); } } size_t NodeStore::packedDataSize() const { size_t size = 0; for (size_t i = 0; i < data.size(); i++) { if (data[i]->name.size()) { size += utils::packedSize(data[i]->data); } } return size; } void NodeStore::packData(char* &p) const { for (size_t i = 0; i < data.size(); i++) { if (data[i]->name.size()) { utils::pack(data[i]->data, p); } } } void NodeStore::unpackData(const char* &p) { for (size_t i = 0; i < data.size(); i++) { utils::unpack(data[i]->data, p); } } NodeStore::~NodeStore() { if (IDs != NULL) { delete IDs; } if (elements != NULL) { delete elements; } if (originCoordinates != NULL) { delete originCoordinates; } if (coordinates != NULL) { delete coordinates; } if (ranks != NULL) { delete ranks; } if (domains != NULL) { delete domains; } for (size_t i = 0; i < data.size(); i++) { delete data[i]; } } void NodeStore::store(const std::string &file) { std::ofstream os(file + std::to_string(info::mpi::rank) + ".txt"); Store::storedata(os, "IDs", IDs); Store::storedata(os, "elements", elements); Store::storedata(os, "coordinates", coordinates); Store::storedata(os, "ranks", ranks); Store::storedata(os, "domains", domains); } void NodeStore::permute(const std::vector<esint> &permutation, const std::vector<size_t> &distribution) { this->distribution = distribution; if (IDs != NULL) { IDs->permute(permutation, distribution); } if (elements != NULL) { elements->permute(permutation, distribution); } if (originCoordinates != NULL) { originCoordinates->permute(permutation, distribution); } if (coordinates != NULL) { coordinates->permute(permutation, distribution); } if (ranks != NULL) { ranks->permute(permutation, distribution); } if (domains != NULL) { domains->permute(permutation, distribution); } } std::vector<esint> NodeStore::gatherNodeDistribution() { return Store::gatherDistribution(size); } std::vector<esint> NodeStore::gatherUniqueNodeDistribution() { return Store::gatherDistribution(uniqInfo.size); } NodeData* NodeStore::appendData(int dimension, NamedData::DataType datatype, const std::string &name) { data.push_back(new NodeData(dimension, datatype, name)); data.back()->data.resize(dimension * size); return data.back(); } void NodeData::statistics(const tarray<esint> &nodes, esint totalsize, Statistics *statistics) const { for (int d = 0; d < nstatistics(); d++) { (statistics + d)->reset(); } auto nranks = info::mesh->nodes->ranks->begin(); esint prev = 0; esint doffset = nstatistics() != dimension ? 1 : 0; for (auto n = nodes.begin(); n != nodes.end(); prev = *n++) { nranks += *n - prev; if (*nranks->begin() == info::mpi::rank) { double value = 0; for (int d = 0; d < dimension; d++) { value += store[*n * dimension + d] * store[*n * dimension + d]; (statistics + d + doffset)->min = std::min((statistics + d + doffset)->min, store[*n * dimension + d]); (statistics + d + doffset)->max = std::max((statistics + d + doffset)->max, store[*n * dimension + d]); (statistics + d + doffset)->avg += store[*n * dimension + d]; (statistics + d + doffset)->norm += store[*n * dimension + d] * store[*n * dimension + d]; (statistics + d + doffset)->absmin = std::min((statistics + d + doffset)->absmin, std::fabs(store[*n * dimension + d])); (statistics + d + doffset)->absmax = std::max((statistics + d + doffset)->absmax, std::fabs(store[*n * dimension + d])); } if (dataType == DataType::VECTOR) { value = std::sqrt(value); statistics->min = std::min(statistics->min, value); statistics->max = std::max(statistics->max, value); statistics->avg += value; statistics->norm += value * value; statistics->absmin = std::min(statistics->absmin, std::fabs(value)); statistics->absmax = std::max(statistics->absmax, std::fabs(value)); } } } std::vector<Statistics> global(nstatistics()); Communication::allReduce(statistics, global.data(), nstatistics(), MPITools::operations->STATISTICS, MPITools::operations->mergeStatistics); memcpy(statistics, global.data(), sizeof(Statistics) * nstatistics()); for (int i = 0; i < nstatistics(); i++) { (statistics + i)->avg /= totalsize; (statistics + i)->norm = std::sqrt((statistics + i)->norm); } }
27.592476
141
0.658828
b56965082b5113142dd9d4e0dc2e936303a05c20
2,054
hpp
C++
falcon/utility/temporary_set.hpp
jonathanpoelen/falcon
5b60a39787eedf15b801d83384193a05efd41a89
[ "MIT" ]
2
2018-02-02T14:19:59.000Z
2018-05-13T02:48:24.000Z
falcon/utility/temporary_set.hpp
jonathanpoelen/falcon
5b60a39787eedf15b801d83384193a05efd41a89
[ "MIT" ]
null
null
null
falcon/utility/temporary_set.hpp
jonathanpoelen/falcon
5b60a39787eedf15b801d83384193a05efd41a89
[ "MIT" ]
null
null
null
#ifndef FALCON_UTILITYTEMPORARY_SET_HPP #define FALCON_UTILITYTEMPORARY_SET_HPP #include <falcon/utility/move.hpp> #include <falcon/c++/noexcept.hpp> #include <falcon/c++/reference.hpp> #include <falcon/functional/operators.hpp> #if __cplusplus >= 201103L # include <type_traits> #endif namespace falcon { ///\brief Modifies the value passed during the lifetime of the object template<class T, class Assigner = assign<T, T> > class temporary_set { T * value_; T old_value_; Assigner assign_; public: typedef T type; public: template<class U> temporary_set(T& oldvalue_, U CPP_RVALUE_OR_CONST_REFERENCE newvalue_) : value_(&oldvalue_) , old_value_(FALCON_MOVE(oldvalue_)) { assign_(*value_, FALCON_FORWARD(U, newvalue_)); } template<class U> temporary_set(T& oldvalue_, U CPP_RVALUE_OR_CONST_REFERENCE newvalue_, Assigner fun) : value_(&oldvalue_) , old_value_(FALCON_MOVE(oldvalue_)) , assign_(fun) { assign_(*value_, FALCON_FORWARD(U, newvalue_)); } #if __cplusplus >= 201103L temporary_set(temporary_set &&) = default; temporary_set(temporary_set const &) = delete; temporary_set& operator=(temporary_set &&) = default; temporary_set& operator=(temporary_set const &) = delete; #endif ~temporary_set() { assign_(*value_, FALCON_MOVE(old_value_)); } const T& old() const CPP_NOEXCEPT { return old_value_; } void old(const T & new_old) { old_value_ = new_old; } #if __cplusplus >= 201103L void old(T && new_old) { old_value_ = std::move(new_old); } #endif }; ///\brief make a temporary_set template<class T, class U> temporary_set<T> temporary_value(T& oldvalue_, U CPP_RVALUE_OR_CONST_REFERENCE newvalue_) { return temporary_set<T>(oldvalue_, FALCON_FORWARD(U, newvalue_)); } template<class T, class U, class Assigner> temporary_set<T, Assigner> temporary_value(T& oldvalue_, U CPP_RVALUE_OR_CONST_REFERENCE newvalue_, Assigner CPP_RVALUE fun) { return temporary_set<T, Assigner>(oldvalue_ , FALCON_FORWARD(U, newvalue_), FALCON_FORWARD(Assigner, fun)); } } #endif
25.04878
97
0.74148
b56a3466b5195036e43924f472b337d6a6b914a6
4,071
hpp
C++
qubus/include/qubus/pattern/binary_operator.hpp
qubusproject/Qubus
0feb8d6df00459c5af402545dbe7c82ee3ec4b7c
[ "BSL-1.0" ]
null
null
null
qubus/include/qubus/pattern/binary_operator.hpp
qubusproject/Qubus
0feb8d6df00459c5af402545dbe7c82ee3ec4b7c
[ "BSL-1.0" ]
null
null
null
qubus/include/qubus/pattern/binary_operator.hpp
qubusproject/Qubus
0feb8d6df00459c5af402545dbe7c82ee3ec4b7c
[ "BSL-1.0" ]
null
null
null
#ifndef QUBUS_PATTERN_BINARY_OPERATOR_HPP #define QUBUS_PATTERN_BINARY_OPERATOR_HPP #include <qubus/IR/binary_operator_expr.hpp> #include <qubus/pattern/variable.hpp> #include <qubus/pattern/any.hpp> #include <qubus/pattern/value.hpp> #include <utility> #include <functional> namespace qubus { namespace pattern { template <typename Tag, typename LHS, typename RHS> class binary_operator_pattern { public: binary_operator_pattern(Tag tag_, LHS lhs_, RHS rhs_) :tag_(std::move(tag_)), lhs_(std::move(lhs_)), rhs_(std::move(rhs_)) { } template <typename BaseType> bool match(const BaseType& value, const variable<const binary_operator_expr&>* var = nullptr) const { if (auto concret_value = value.template try_as<binary_operator_expr>()) { if (tag_.match(concret_value->tag())) { if (lhs_.match(concret_value->left()) && rhs_.match(concret_value->right())) { if (var) { var->set(*concret_value); } return true; } } } return false; } void reset() const { tag_.reset(); lhs_.reset(); rhs_.reset(); } private: Tag tag_; LHS lhs_; RHS rhs_; }; template <typename Tag, typename LHS, typename RHS> binary_operator_pattern<Tag, LHS, RHS> binary_operator(Tag tag, LHS lhs, RHS rhs) { return binary_operator_pattern<Tag, LHS, RHS>(tag, lhs, rhs); } template <typename LHS, typename RHS> binary_operator_pattern<any, LHS, RHS> binary_operator(LHS lhs, RHS rhs) { return binary_operator_pattern<any, LHS, RHS>(_, lhs, rhs); } template<typename LHS, typename RHS> auto operator+(LHS lhs, RHS rhs) { return binary_operator(value(binary_op_tag::plus), lhs, rhs); } template<typename LHS, typename RHS> auto operator-(LHS lhs, RHS rhs) { return binary_operator(value(binary_op_tag::minus), lhs, rhs); } template<typename LHS, typename RHS> auto operator*(LHS lhs, RHS rhs) { return binary_operator(value(binary_op_tag::multiplies), lhs, rhs); } template<typename LHS, typename RHS> auto operator/(LHS lhs, RHS rhs) { return binary_operator(value(binary_op_tag::divides), lhs, rhs); } template<typename LHS, typename RHS> auto operator%(LHS lhs, RHS rhs) { return binary_operator(value(binary_op_tag::modulus), lhs, rhs); } template<typename LHS, typename RHS> auto div_floor(LHS lhs, RHS rhs) { return binary_operator(value(binary_op_tag::div_floor), lhs, rhs); } template<typename LHS, typename RHS> auto assign(LHS lhs, RHS rhs) { return binary_operator(value(binary_op_tag::assign), lhs, rhs); } template<typename LHS, typename RHS> auto plus_assign(LHS lhs, RHS rhs) { return binary_operator(value(binary_op_tag::plus_assign), lhs, rhs); } template<typename LHS, typename RHS> auto equal_to(LHS lhs, RHS rhs) { return binary_operator(value(binary_op_tag::equal_to), lhs, rhs); } template<typename LHS, typename RHS> auto not_equal_to(LHS lhs, RHS rhs) { return binary_operator(value(binary_op_tag::not_equal_to), lhs, rhs); } template<typename LHS, typename RHS> auto less(LHS lhs, RHS rhs) { return binary_operator(value(binary_op_tag::less), lhs, rhs); } template<typename LHS, typename RHS> auto greater(LHS lhs, RHS rhs) { return binary_operator(value(binary_op_tag::greater), lhs, rhs); } template<typename LHS, typename RHS> auto less_equal(LHS lhs, RHS rhs) { return binary_operator(value(binary_op_tag::less_equal), lhs, rhs); } template<typename LHS, typename RHS> auto greater_equal(LHS lhs, RHS rhs) { return binary_operator(value(binary_op_tag::greater_equal), lhs, rhs); } template<typename LHS, typename RHS> auto logical_and(LHS lhs, RHS rhs) { return binary_operator(value(binary_op_tag::logical_and), lhs, rhs); } template<typename LHS, typename RHS> auto logical_or(LHS lhs, RHS rhs) { return binary_operator(value(binary_op_tag::logical_or), lhs, rhs); } } } #endif
23.807018
103
0.688529
b56d896e4139c6fd4fa5337d66ec4dd83567bef5
3,142
hpp
C++
include/cppgit2/fetch.hpp
jhasse/cppgit2
7c069680bcfa70686053bc1f573524813c1f206f
[ "MIT" ]
84
2020-03-22T14:03:37.000Z
2022-01-04T05:51:55.000Z
include/cppgit2/fetch.hpp
jhasse/cppgit2
7c069680bcfa70686053bc1f573524813c1f206f
[ "MIT" ]
7
2020-03-27T21:36:13.000Z
2020-12-05T23:41:25.000Z
include/cppgit2/fetch.hpp
jhasse/cppgit2
7c069680bcfa70686053bc1f573524813c1f206f
[ "MIT" ]
18
2020-04-25T09:55:17.000Z
2022-03-06T23:20:43.000Z
#pragma once #include <cppgit2/libgit2_api.hpp> #include <cppgit2/proxy.hpp> #include <cppgit2/strarray.hpp> #include <git2.h> #include <string> #include <vector> namespace cppgit2 { class fetch : public libgit2_api { public: class options : public libgit2_api { public: options() : c_ptr_(nullptr) { auto ret = git_fetch_init_options(&default_options_, GIT_FETCH_OPTIONS_VERSION); c_ptr_ = &default_options_; if (ret != 0) throw git_exception(); } options(git_fetch_options *c_ptr) : c_ptr_(c_ptr) {} // Version unsigned int version() const { return c_ptr_->version; } void set_version(unsigned int version) { c_ptr_->version = version; } // TODO: Add callbacks to use for this fetch operation // Acceptable prune settings when fetching enum class prune { // Use the setting from the configuration unspecified, // Force pruning on prune, // Force pruning off no_prune }; // Prune - Whether to perform a prune after the fetch prune prune_option() const { return static_cast<fetch::options::prune>(c_ptr_->prune); } void set_prune_option(prune option) { c_ptr_->prune = static_cast<git_fetch_prune_t>(option); } // Update fetchhead // Whether to write the results to FETCH_HEAD. Defaults to on. Leave this // default in order to behave like git. bool update_fetchhead() const { return c_ptr_->update_fetchhead; } void set_update_fetchhead(bool value) { c_ptr_->update_fetchhead = value; } // Automatic tag following option // Lets us select the --tags option to use. enum class autotag { // Use the setting from the configuration unspecified = 0, // Ask the server for tags pointing to objects we're already downloading. auto_, // Don't ask for any tags beyond the refspecs. none, // Ask for the all the tags. all }; // Download tags // Determines how to behave regarding tags on the remote, such as // auto-downloading tags for objects we're downloading or downloading all of // them. The default is to auto-follow tags. autotag download_tags_option() const { return static_cast<autotag>(c_ptr_->download_tags); } void set_download_tags_option(autotag download_tags) { c_ptr_->download_tags = static_cast<git_remote_autotag_option_t>(download_tags); } // Proxy options proxy::options proxy_options() const { return proxy::options(&c_ptr_->proxy_opts); } void set_proxy_options(const proxy::options &options) { c_ptr_->proxy_opts = *(options.c_ptr()); } // Custom headers strarray custom_headers() const { return strarray(&c_ptr_->custom_headers); } void set_custom_headers(const std::vector<std::string> &headers) { c_ptr_->custom_headers = *(strarray(headers).c_ptr()); } // Access libgit2 C ptr const git_fetch_options *c_ptr() const { return c_ptr_; } private: git_fetch_options *c_ptr_; git_fetch_options default_options_; }; }; } // namespace cppgit2
29.364486
80
0.669955
b56f1995d8b993312a57a37084c760cfcd038b1c
740
cpp
C++
src/SpectatorView.Native/SpectatorView.WinRTExtensions/SpectatorView.WinRTExtensions.cpp
sereilly/MixedReality-SpectatorView
a4f58e25bbe6c002cbf7b134c4babe5e4d7bc9b9
[ "MIT" ]
165
2019-06-19T18:41:20.000Z
2022-03-16T12:17:02.000Z
src/SpectatorView.Native/SpectatorView.WinRTExtensions/SpectatorView.WinRTExtensions.cpp
sereilly/MixedReality-SpectatorView
a4f58e25bbe6c002cbf7b134c4babe5e4d7bc9b9
[ "MIT" ]
297
2019-06-18T19:01:43.000Z
2022-03-31T00:11:07.000Z
src/SpectatorView.Native/SpectatorView.WinRTExtensions/SpectatorView.WinRTExtensions.cpp
sereilly/MixedReality-SpectatorView
a4f58e25bbe6c002cbf7b134c4babe5e4d7bc9b9
[ "MIT" ]
108
2019-06-17T22:44:08.000Z
2022-03-18T05:44:57.000Z
#include "pch.h" #include "SpectatorView.WinRTExtensions.h" // Because Marshal.GetObjectForIUnknown does not work when using the .NET Native compiler with IInspectable // objects, this method allows managed code to explicitly specify a type for the marshaller to query for. // Example usage from managed code for marshalling a SpatialCoordinateSystem using this method: // // [DllImport("SpectatorView.WinRTExtensions.dll", EntryPoint = "MarshalIInspectable")] // private static extern void GetSpatialCoordinateSystem(IntPtr nativePtr, out SpatialCoordinateSystem coordinateSystem); extern "C" __declspec(dllexport) void __stdcall MarshalIInspectable(IUnknown* nativePtr, IUnknown** inspectable) { *inspectable = nativePtr; }
52.857143
125
0.797297
b56f2717aed76d154ee127ce312df2b746e5e23c
836
cpp
C++
POSAND.cpp
durgajaswanth/ADSA-Semester-Assignments
b95410c2d6ee874f331d1128c72b54c7defaa26e
[ "MIT" ]
null
null
null
POSAND.cpp
durgajaswanth/ADSA-Semester-Assignments
b95410c2d6ee874f331d1128c72b54c7defaa26e
[ "MIT" ]
null
null
null
POSAND.cpp
durgajaswanth/ADSA-Semester-Assignments
b95410c2d6ee874f331d1128c72b54c7defaa26e
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; typedef unsigned long long int ull; typedef long long int ll; #define FIO ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define mod 1000000007 int main() { FIO; int t; cin >> t; while(t--) { int n; cin>>n; if(n==1) { cout<<"1"<<endl; continue; } if(n==3) { cout<<"2 3 1"<<endl; continue; } int tmp=n; while(tmp%2==0) tmp/=2; if(tmp==1) { cout<<"-1"<<endl; continue; } int p=3,pw; pw=pow(2,p); cout<<"2 3 1 5 4 "; for(int i=6;i<=n;i++) { if(i+1==pw && i!=n) { cout<<i<<" "<<pw+1<<" "<<pw<<" "; i+=2; p+=1; pw = pow(2,p); } else cout<<i<<" "; } cout<<endl; } return 0; }
15.481481
61
0.419856
b5704f6293dea12047ce0271d638fae94aac3a22
4,707
cc
C++
solver_bank.cc
frenebo/SOAX
c6aacd1ce9d919a205a712a4db8f0ab8a1ecacd1
[ "BSD-3-Clause" ]
8
2015-09-14T00:37:59.000Z
2020-12-30T22:47:34.000Z
solver_bank.cc
frenebo/SOAX
c6aacd1ce9d919a205a712a4db8f0ab8a1ecacd1
[ "BSD-3-Clause" ]
3
2015-05-14T15:48:50.000Z
2020-12-30T17:46:14.000Z
solver_bank.cc
frenebo/SOAX
c6aacd1ce9d919a205a712a4db8f0ab8a1ecacd1
[ "BSD-3-Clause" ]
9
2015-09-14T11:35:51.000Z
2021-12-14T23:38:47.000Z
/** * Copyright (c) 2015, Lehigh University * All rights reserved. * See COPYING for license. * * This file implements the solvers for linear system for SOAX. */ #include "./solver_bank.h" namespace soax { SolverBank::SolverBank() : alpha_(0.01), beta_(0.1), gamma_(2.0) {} SolverBank::~SolverBank() { this->ClearSolvers(open_solvers_); this->ClearSolvers(closed_solvers_); } void SolverBank::ClearSolvers(SolverContainer &solvers) { if (solvers.empty()) return; for (SolverContainer::iterator it = solvers.begin(); it != solvers.end(); ++it) { if (*it) { (*it)->DestroyMatrix(0); (*it)->DestroyVector(0); (*it)->DestroySolution(0); delete *it; } } solvers.clear(); } void SolverBank::Reset(bool reset_matrix) { if (reset_matrix) { this->ClearSolvers(open_solvers_); this->ClearSolvers(closed_solvers_); } else { this->ResetSolutionAndVector(open_solvers_); this->ResetSolutionAndVector(closed_solvers_); } } void SolverBank::ResetSolutionAndVector(SolverContainer &solvers) { if (solvers.empty()) return; for (SolverContainer::iterator it = solvers.begin(); it != solvers.end(); ++it) { if (*it) { (*it)->InitializeSolution(0); (*it)->InitializeVector(0); } } } void SolverBank::SolveSystem(const VectorContainer &vectors, unsigned dim, bool open) { SolverContainer &solvers = open ? open_solvers_ : closed_solvers_; unsigned position = vectors.size() - kMinimumEvolvingSize; if (position >= solvers.size()) { this->ExpandSolverContainer(solvers, position); } if (!solvers[position]) { solvers[position] = new SolverType; this->InitializeSolver(solvers[position], vectors.size(), open); } for (unsigned i = 0; i < vectors.size(); ++i) { solvers[position]->SetVectorValue(i, vectors[i][dim], 0); } solvers[position]->Solve(); } void SolverBank::ExpandSolverContainer(SolverContainer &solvers, unsigned position) { unsigned num_added_solvers = position - solvers.size() + 1; for (unsigned i = 0; i < num_added_solvers; ++i) { solvers.push_back(NULL); } } void SolverBank::InitializeSolver(SolverType *solver, unsigned order, bool open) { solver->SetNumberOfMatrices(1); solver->SetNumberOfVectors(1); solver->SetNumberOfSolutions(1); solver->SetMaximumNonZeroValuesInMatrix(kMinimumEvolvingSize * order); solver->SetSystemOrder(order); solver->InitializeMatrix(0); solver->InitializeVector(0); solver->InitializeSolution(0); if (open) this->FillMatrixOpen(solver, order); else this->FillMatrixClosed(solver, order); } void SolverBank::FillMatrixOpen(SolverType *solver, unsigned order) { /* alpha_0 = 0; alpha_{N-1} = alpha; beta_0 = beta_{N-1} = 0 */ const double diag0 = 2 * alpha_ + 6 * beta_ + gamma_; const double diag1 = -alpha_ - 4 * beta_; // main diagonal solver->SetMatrixValue(0, 0, alpha_ + beta_ + gamma_, 0); solver->SetMatrixValue(1, 1, 2 * alpha_ + 5 * beta_ + gamma_, 0); for (unsigned i = 2; i < order - 2; i++) solver->SetMatrixValue(i, i, diag0, 0); solver->SetMatrixValue(order - 2, order - 2, 2 * alpha_ + 5 * beta_ + gamma_, 0); solver->SetMatrixValue(order - 1, order - 1, alpha_ + beta_ + gamma_, 0); // +1/-1 diagonal solver->SetMatrixValue(0, 1, -alpha_ - 2 * beta_, 0); solver->SetMatrixValue(1, 0, -alpha_ - 2 * beta_, 0); for (unsigned i = 1; i < order - 2; i++) { solver->SetMatrixValue(i, i + 1, diag1, 0); solver->SetMatrixValue(i + 1, i, diag1, 0); } solver->SetMatrixValue(order - 2, order - 1, -alpha_ - 2 * beta_, 0); solver->SetMatrixValue(order - 1, order - 2, -alpha_ - 2 * beta_, 0); // +2/-2 diagonal for (unsigned i = 2; i < order; ++i) { solver->SetMatrixValue(i, i-2, beta_, 0); solver->SetMatrixValue(i-2, i, beta_, 0); } } void SolverBank::FillMatrixClosed(SolverType *solver, unsigned order) { const double diag0 = 2 * alpha_ + 6 * beta_ + gamma_; const double diag1 = -alpha_ - 4 * beta_; for (unsigned i = 0; i < order; ++i) { solver->SetMatrixValue(i, (i+order-2)%order, beta_, 0); solver->SetMatrixValue(i, (i+order-1)%order, diag1, 0); solver->SetMatrixValue(i, i, diag0, 0); solver->SetMatrixValue(i, (i+order+1)%order, diag1, 0); solver->SetMatrixValue(i, (i+order+2)%order, beta_, 0); } } double SolverBank::GetSolution(unsigned order, unsigned index, bool open) { SolverContainer &solvers = open? open_solvers_ : closed_solvers_; return solvers[order - kMinimumEvolvingSize]->GetSolutionValue(index, 0); } } // namespace soax
31.172185
75
0.647546
b5722f716ca8c1cf400982c86e5c78912e13ed10
2,776
cpp
C++
src/ofxNode.cpp
lpestl/ofxGraphVisualization
218e67b2519eed5050f09f51e31260690fe4eacc
[ "MIT" ]
null
null
null
src/ofxNode.cpp
lpestl/ofxGraphVisualization
218e67b2519eed5050f09f51e31260690fe4eacc
[ "MIT" ]
null
null
null
src/ofxNode.cpp
lpestl/ofxGraphVisualization
218e67b2519eed5050f09f51e31260690fe4eacc
[ "MIT" ]
null
null
null
#include "ofxNode.h" #include <random> #include "ofxTweener.h" void ofxNode::setup(std::shared_ptr<ofRectangle> boundRect, std::shared_ptr<ofxTrueTypeFontUC> font) { captureFont_ = font; boundRect_ = boundRect; position_.set(ofRandom(boundRect_->getMinX(), boundRect_->getMaxX()), ofRandom(boundRect_->getMinY(), boundRect_->getMaxY())/*xRange(generator), yRange(generator)*/); speed_.set(0, 0); } void ofxNode::update() { updatePosition(); } void ofxNode::draw(bool isNameVisible) { ofDrawCircle(position_.x, position_.y, radius_); if (isNameVisible) { ofPushStyle(); ofSetColor(ofColor::black); const auto capture = ofToString(id_); if ((captureFont_ != nullptr) && (captureFont_->isLoaded())) { const auto textRect = captureFont_->getStringBoundingBox(capture, position_.x, position_.y); captureFont_->drawString(ofToString(id_), position_.x - textRect.width / 2, position_.y + textRect.height / 2); } else { ofDrawBitmapString(capture, position_.x, position_.y); } ofPopStyle(); } } void ofxNode::setPosition(ofVec2f newPos) { if (boundRect_->inside(newPos)) { position_.set(newPos); } } ofVec2f ofxNode::getPosition() const { return position_; } void ofxNode::setSpeed(ofVec2f newSpeed) { speed_.set(newSpeed); } ofVec2f ofxNode::getSpeed() const { return speed_; } void ofxNode::setRadius(float radius) { targetRadius_ = radius; //radius_ = radius; Tweener.addTween(radius_, targetRadius_, 0.5); } float ofxNode::getRadius() const { return radius_; } float ofxNode::getTargetRadius() const { return targetRadius_; } void ofxNode::updatePosition() { if (!((speed_.x == 0) && (speed_.y == 0))) { const auto deltaTime = ofGetLastFrameTime(); ofVec2f deltaPos(speed_.x * deltaTime, speed_.y * deltaTime); if (!boundRect_->inside(position_.x + deltaPos.x, position_.y)) { if ((position_.x + deltaPos.x) < boundRect_->getMinX()) { position_.x = boundRect_->getMinX() - position_.x - deltaPos.x + boundRect_->getMinX(); speed_.x = speed_.x * -1; } if ((position_.x + deltaPos.x) >= boundRect_->getMaxX()) { position_.x = boundRect_->getMaxX() - position_.x - deltaPos.x + boundRect_->getMaxX(); speed_.x = speed_.x * -1; } } else position_.x += deltaPos.x; if (!boundRect_->inside(position_.x, position_.y + deltaPos.y)) { if ((position_.y + deltaPos.y) < boundRect_->getMinY()) { position_.y = boundRect_->getMinY() - position_.y - deltaPos.y + boundRect_->getMinY(); speed_.y = speed_.y * -1; } if ((position_.y + deltaPos.y) >= boundRect_->getMaxY()) { position_.y = boundRect_->getMaxY() - position_.y - deltaPos.y + boundRect_->getMaxY(); speed_.y = speed_.y * -1; } } else position_.y += deltaPos.y; } }
22.208
167
0.674352
b5729bc51e2f1e778024289cec93bc0e1651c438
639
cc
C++
system_info/system_info_cellular_network_desktop.cc
sstolinski/tizen-extensions-crosswalk
749cf5285bf1c9c04a4ce9f3880a744dcf221a69
[ "Apache-2.0", "BSD-3-Clause" ]
1
2016-11-21T21:21:19.000Z
2016-11-21T21:21:19.000Z
system_info/system_info_cellular_network_desktop.cc
sstolinski/tizen-extensions-crosswalk
749cf5285bf1c9c04a4ce9f3880a744dcf221a69
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
system_info/system_info_cellular_network_desktop.cc
sstolinski/tizen-extensions-crosswalk
749cf5285bf1c9c04a4ce9f3880a744dcf221a69
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2013 Intel Corporation. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "system_info/system_info_cellular_network.h" const std::string SysInfoCellularNetwork::name_ = "CELLULAR_NETWORK"; void SysInfoCellularNetwork::Get(picojson::value& error, picojson::value& data) { system_info::SetPicoJsonObjectValue(error, "message", picojson::value("Cellular Network is not supported on desktop.")); } void SysInfoCellularNetwork::StartListening() { } void SysInfoCellularNetwork::StopListening() { }
37.588235
73
0.730829
b57442bec007ffc6c7f2cb92d52dffcd43e3c08c
2,574
hpp
C++
engine/include/ph/sdl/Mouse.hpp
PetorSFZ/PhantasyEngine
befe8e9499b7fd93d8765721b6841337a57b0dd6
[ "Zlib" ]
null
null
null
engine/include/ph/sdl/Mouse.hpp
PetorSFZ/PhantasyEngine
befe8e9499b7fd93d8765721b6841337a57b0dd6
[ "Zlib" ]
null
null
null
engine/include/ph/sdl/Mouse.hpp
PetorSFZ/PhantasyEngine
befe8e9499b7fd93d8765721b6841337a57b0dd6
[ "Zlib" ]
null
null
null
// Copyright (c) Peter Hillerström (skipifzero.com, peter@hstroem.se) // For other contributors see Contributors.txt // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. #pragma once #include <SDL.h> #include <sfz/containers/DynArray.hpp> #include <sfz/geometry/AABB2D.hpp> #include <sfz/math/Vector.hpp> #include "ph/sdl/ButtonState.hpp" namespace ph { namespace sdl { using sfz::DynArray; using sfz::AABB2D; using sfz::vec2; // Mouse structs // ------------------------------------------------------------------------------------------------ struct Mouse final { // Public members // -------------------------------------------------------------------------------------------- ButtonState leftButton = ButtonState::NOT_PRESSED; ButtonState rightButton = ButtonState::NOT_PRESSED; ButtonState middleButton = ButtonState::NOT_PRESSED; /// A raw position should be in the range [0, 1] where (0,0) is the bottom left corner. /// In a scaled mouse from "scaleMouse()" the position should be in the specified coordinate /// system. vec2 position; vec2 motion; // Positive-x: right, Positive-y: up vec2 wheel; // Constructors & destructors // -------------------------------------------------------------------------------------------- Mouse() noexcept = default; Mouse(const Mouse&) noexcept = default; Mouse& operator= (const Mouse&) noexcept = default; // Public methods // -------------------------------------------------------------------------------------------- void update(int windowWidth, int windowHeight, const DynArray<SDL_Event>& events) noexcept; Mouse scaleMouse(vec2 camPos, vec2 camDim) const noexcept; Mouse scaleMouse(const AABB2D& camera) const noexcept; }; } // namespace sdl } // namespace ph
34.783784
99
0.628205
b57989b723bd246a6624c126ca4f3f2acf401fcf
1,125
cpp
C++
IGC/AdaptorOCL/cif/cif/import/cif_main.cpp
kurapov-peter/intel-graphics-compiler
98f7c938df0617912288385d243d6918135f0713
[ "Intel", "MIT" ]
440
2018-01-30T00:43:22.000Z
2022-03-24T17:28:37.000Z
IGC/AdaptorOCL/cif/cif/import/cif_main.cpp
kurapov-peter/intel-graphics-compiler
98f7c938df0617912288385d243d6918135f0713
[ "Intel", "MIT" ]
225
2018-02-02T03:10:47.000Z
2022-03-31T10:50:37.000Z
IGC/AdaptorOCL/cif/cif/import/cif_main.cpp
kurapov-peter/intel-graphics-compiler
98f7c938df0617912288385d243d6918135f0713
[ "Intel", "MIT" ]
138
2018-01-30T08:15:11.000Z
2022-03-22T14:16:39.000Z
/*========================== begin_copyright_notice ============================ Copyright (C) 2017-2021 Intel Corporation SPDX-License-Identifier: MIT ============================= end_copyright_notice ===========================*/ #include "cif/common/cif.h" #include "cif/import/library_api.h" #include "cif/import/cif_main.h" namespace CIF { CIF::RAII::UPtr_t<CIFMain> OpenLibraryInterface(LibraryHandle &lib) { CIFMain *ret = nullptr; void *createMainFuncPtr = lib.GetFuncPointer(CIF::CreateCIFMainFuncName); if (createMainFuncPtr == nullptr) { return CIF::RAII::UPtr(ret = nullptr); } auto CreateCIFFunc = reinterpret_cast<CIF::CreateCIFMainFunc_t>(createMainFuncPtr); auto main = (*CreateCIFFunc)(); return CIF::RAII::UPtr(main); } std::unique_ptr<CIFPackage> OpenLibraryInterface(std::unique_ptr<CIF::LibraryHandle> &&lib) { if (lib.get() == nullptr) { return std::unique_ptr<CIFPackage>(nullptr); } auto entryPoint = OpenLibraryInterface(*lib.get()); CIFPackage *pckg = new CIFPackage(std::move(entryPoint), std::move(lib)); return std::unique_ptr<CIFPackage>(pckg); } }
30.405405
80
0.657778
b579e2c62547c27f052a384b37705400e2b6f822
507
hpp
C++
osc-seq-cpp/src/ui_elements/text_elt.hpp
Acaruso/osc-seq-cpp
14d2d5ce0fdad8d183e19781a279f9442db9c79f
[ "MIT" ]
null
null
null
osc-seq-cpp/src/ui_elements/text_elt.hpp
Acaruso/osc-seq-cpp
14d2d5ce0fdad8d183e19781a279f9442db9c79f
[ "MIT" ]
null
null
null
osc-seq-cpp/src/ui_elements/text_elt.hpp
Acaruso/osc-seq-cpp
14d2d5ce0fdad8d183e19781a279f9442db9c79f
[ "MIT" ]
null
null
null
#pragma once #include <functional> #include <string> #include <SDL.h> #include <SDL_ttf.h> #include "../store/coord.hpp" #include "../store/store.hpp" void text_elt(std::string text, Coord& coord, Store& store, int z_coord = 1); void text_elt(std::string text, FC_Font* font, Coord& coord, Store& store, int z_coord = 1); void text_elt_draggable( std::string id, std::string text, Coord& coord, Store& store, std::function<void()> on_click, std::function<void(int)> on_drag );
21.125
92
0.676529
b57ab05c3f3f7779b0c026b6c4d7c7243c79daf9
1,430
cpp
C++
uhk/acm5624.cpp
Hyyyyyyyyyy/acm
d7101755b2c2868d51bb056f094e024d0333b56f
[ "MIT" ]
null
null
null
uhk/acm5624.cpp
Hyyyyyyyyyy/acm
d7101755b2c2868d51bb056f094e024d0333b56f
[ "MIT" ]
null
null
null
uhk/acm5624.cpp
Hyyyyyyyyyy/acm
d7101755b2c2868d51bb056f094e024d0333b56f
[ "MIT" ]
null
null
null
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; typedef long long ll; const int maxn = 15000 + 10; const int MAX = 100000000; struct node { int u; int v; ll w; }; node edge[maxn]; int N, M, cnt; ll res; int F[maxn]; bool comp(const node& a, const node& b) { return a.w < b.w; } void addedge(int u, int v, ll w) { edge[cnt].u = u; edge[cnt].v = v; edge[cnt++].w = w; } int find(int x) { if (F[x] == -1) return x; else return F[x] = find(F[x]); } ll kruskal(int f) { int i, j, k, count = 0; ll ans = 0; memset(F, -1, sizeof(F)); for (i = f; i < cnt; i++) { int u = edge[i].u; int v = edge[i].v; ll w = edge[i].w; int t1 = find(u); int t2 = find(v); if (t1 != t2) { F[t2] = t1; ans += w; count++; } if (count == N - 1) break; } if (count < N - 1) return -1; else return edge[i].w - edge[f].w; } int main() { int i, j, k, n, m, a, b; ll c; while (scanf("%d", &n) != EOF) { for (m = 1; m <= n; m++) { cnt = 0; res = MAX; scanf("%d %d", &N, &M); for (i = 1; i <= M; i++) { scanf("%d %d %lld", &a, &b, &c); addedge(a, b, c); } sort(edge, edge + cnt, comp); res = kruskal(0); if (res == -1) { printf("-1\n"); continue; } for (i = 1; i <= cnt-N+1; i++) { ll t = kruskal(i); if (t < 0) continue; if (res > t) res = t; } printf("%lld\n", res); } } return 0; }
14.742268
39
0.479021
b58004d3527ba76f6a550c910f2c61f558ca6db7
4,151
cc
C++
UA_BlackJack_Server/DBServer/test/test_RedisService.cc
lsxk-jwj/gRPC_demo
4a772dbb68726f2f253e6023271fd7b629006853
[ "Apache-2.0" ]
null
null
null
UA_BlackJack_Server/DBServer/test/test_RedisService.cc
lsxk-jwj/gRPC_demo
4a772dbb68726f2f253e6023271fd7b629006853
[ "Apache-2.0" ]
null
null
null
UA_BlackJack_Server/DBServer/test/test_RedisService.cc
lsxk-jwj/gRPC_demo
4a772dbb68726f2f253e6023271fd7b629006853
[ "Apache-2.0" ]
null
null
null
#include "../RedisService.h" #include <gtest/gtest.h> #include <unordered_set> using ua_black_jack_server::data_base_server::RedisService; RedisService* service; const char* nickname = "owen1"; const int64_t uid = 2345; const char* password = "ASIKrgubhy"; int main() { acl::redis_client client("127.0.0.1:6379"); acl::redis conn(&client); conn.set("UID", "2345"); conn.set("MID", "1234"); service = new RedisService(client); ::testing::InitGoogleTest(); auto ret = RUN_ALL_TESTS(); getchar(); delete service; client.close(); } TEST(RedisService, nicknameToUID) { // const char* nickname = "owen1"; // constexpr int64_t uid = 2345; EXPECT_TRUE(service->SetUid(nickname, uid)); EXPECT_TRUE(service->NameExists(nickname)); EXPECT_EQ(service->GetUid(nickname), acl::string("2345")); } TEST(RedisService, nextUID) { EXPECT_EQ(service->NextUid(), 2346); EXPECT_EQ(service->NextUid(), 2347); EXPECT_EQ(service->NextUid(), 2348); EXPECT_EQ(service->NextUid(), 2349); EXPECT_EQ(service->NextUid(), 2350); } TEST(RedisService, nextMatchId) { EXPECT_EQ(service->NextMatchId(), 1235); EXPECT_EQ(service->NextMatchId(), 1236); EXPECT_EQ(service->NextMatchId(), 1237); EXPECT_EQ(service->NextMatchId(), 1238); EXPECT_EQ(service->NextMatchId(), 1239); EXPECT_EQ(service->NextMatchId(), 1240); } TEST(RedisService, UIDToPassword) { // ; // const int64_t uid = 2234; EXPECT_TRUE(service->setPassword(uid, password)); EXPECT_EQ(service->GetPassword(uid), acl::string(password)); } TEST(RedisService, UIDToNickname) { // const char* nickname = "owen1"; // const int64_t uid = 2345; EXPECT_TRUE(service->SetNickname(uid, nickname)); EXPECT_EQ(service->GetNickname(uid), acl::string(nickname)); } TEST(RedisService, UIDToScore) { EXPECT_TRUE(service->SetScore(uid, 1000)); EXPECT_EQ(service->GetScore(uid), 1000); EXPECT_TRUE(service->AddScore(uid, 1000)); EXPECT_EQ(service->GetScore(uid), 2000); EXPECT_TRUE(service->AddScore(uid, -1000)); EXPECT_EQ(service->GetScore(uid), 1000); } TEST(RedisService, UIDToFriendList) { EXPECT_TRUE(service->InsertFriendList(uid, 1234)); EXPECT_TRUE(service->InsertFriendList(uid, 1235)); EXPECT_TRUE(service->InsertFriendList(uid, 1236)); EXPECT_TRUE(service->InsertFriendList(uid, 1237)); auto ret = service->GetFriendList(uid); EXPECT_EQ(ret.size(), 4); std::unordered_set<std::string> set1; set1.insert("1234"); set1.insert("1235"); set1.insert("1236"); set1.insert("1237"); for(const auto str : ret) { set1.erase(std::string(str.c_str())); } EXPECT_TRUE(set1.empty()); EXPECT_TRUE(service->RemoveFriendList(uid, 1234)); EXPECT_EQ(service->GetFriendList(uid).size(), 3); } TEST(RedisService, UIDToRank) { EXPECT_TRUE(service->UpdateRank(uid, 1000)); EXPECT_TRUE(service->UpdateRank(uid + 1, 2000)); EXPECT_TRUE(service->UpdateRank(uid + 2, 3000)); EXPECT_EQ(service->GetRank(uid), 3); EXPECT_EQ(service->GetRank(uid + 1), 2); EXPECT_EQ(service->GetRank(uid + 2), 1); EXPECT_TRUE(service->AddRankScore(uid, 3000)); EXPECT_EQ(service->GetRank(uid), 1); auto ret = service->GetTopPlayer(2); EXPECT_EQ(ret.size(), 2); decltype(ret) rank = { "2345", "2347" }; EXPECT_EQ(rank, ret); } TEST(RedisService, MatchList) { EXPECT_TRUE(service->InsertMatchList(uid, 1000)); EXPECT_TRUE(service->InsertMatchList(uid, 1200)); EXPECT_TRUE(service->InsertMatchList(uid, 1300)); EXPECT_TRUE(service->InsertMatchList(uid, 1400)); const std::vector<acl::string> vec = {"1400", "1300", "1200", "1000"}; EXPECT_EQ(service->GetMatchList(uid), vec); } TEST(RedisService, MatchInfo) { EXPECT_TRUE(service->InsertMatchInfo(1000, "time", "12000")); EXPECT_TRUE(service->InsertMatchInfo(1000, "2345", "+12")); EXPECT_TRUE(service->InsertMatchInfo(1000, "2346", "-24")); EXPECT_TRUE(service->InsertMatchInfo(1000, "2347", "+12")); EXPECT_EQ(service->GetMatchInfo(1000).size(), 4); }
30.977612
74
0.669718
b58022bbd3bbacc3c23f06777eb67a41f8982771
16,261
hpp
C++
core/src/cogs/io/net/telnet.hpp
cogmine/cogs
ef1c369a36a4f811704e0ced0493c3a6f8eca821
[ "MIT" ]
5
2019-02-08T15:59:14.000Z
2022-01-22T19:12:33.000Z
core/src/cogs/io/net/telnet.hpp
cogmine/cogs
ef1c369a36a4f811704e0ced0493c3a6f8eca821
[ "MIT" ]
1
2019-12-03T03:11:34.000Z
2019-12-03T03:11:34.000Z
core/src/cogs/io/net/telnet.hpp
cogmine/cogs
ef1c369a36a4f811704e0ced0493c3a6f8eca821
[ "MIT" ]
null
null
null
// // Copyright (C) 2000-2020 - Colen M. Garoutte-Carson <colen at cogmine.com>, Cog Mine LLC // // Status: Good, NeedsTesting #ifndef COGS_HEADER_IO_NET_TELNET #define COGS_HEADER_IO_NET_TELNET #include "cogs/collections/container_queue.hpp" #include "cogs/collections/string.hpp" #include "cogs/env.hpp" #include "cogs/io/datastream_protocol.hpp" namespace cogs { namespace io { namespace net { // Adapts a datastream, usually TCP at remote port 23 /// @ingroup Net /// @brief Implements the telnet protocol. class telnet : public datastream_protocol { public: // Interface for terminal emulation that supports telnet options class terminal { private: weak_rcptr<telnet> m_telnet; friend class telnet; public: // notifications/requests // NOP by default virtual void telnet_are_you_there() {} // Called when remote party sends an AYT req. // This party needs to respond with something to prove they are there. virtual void telnet_interrupt_process() {} // Received an Interrupt Process (IP) message from remote party virtual void telnet_abort_output() {} // Received an Abort Output (AO) message from remote party virtual void telnet_erase_char() {} // Received an Erase Character (EC) message from remote party virtual void telnet_erase_line() {} // Received an Erase Line (EL) message from remote party virtual void telnet_break() {} // Received a Break message from remote party virtual bool telnet_request_echo(bool) { return false; } // received request to set echo state virtual bool telnet_notify_echo(bool echoOn) { return echoOn; } // received request to set echo state virtual cstring get_telnet_terminal_type() { return cstring::literal("UNKNOWN"); } virtual void get_window_size(uint16_t& width, uint16_t& height) { (void)width; (void)height; } // Terminal utils void send_window_size(uint16_t width, uint16_t height) { rcptr<telnet> t = m_telnet; if (!!t) t->send_window_size(width, height); } }; private: weak_rcptr<terminal> m_terminal; volatile buffer m_recvBuffer; static constexpr unsigned char IAC = 255; static constexpr unsigned char DONT = 254; static constexpr unsigned char DO = 253; static constexpr unsigned char WONT = 252; static constexpr unsigned char WILL = 251; static constexpr unsigned char SB = 250; static constexpr unsigned char GA = 249; static constexpr unsigned char EL = 248; static constexpr unsigned char EC = 247; static constexpr unsigned char AYT = 246; static constexpr unsigned char AO = 245; static constexpr unsigned char IP = 244; static constexpr unsigned char BRK = 243; static constexpr unsigned char DATAMARK =242; static constexpr unsigned char NOP = 241; static constexpr unsigned char SE = 240; static constexpr unsigned char SEND = 1; static constexpr unsigned char IS = 0; static constexpr unsigned char TELOPT_BINARY = 0; static constexpr unsigned char TELOPT_ECHO = 1; static constexpr unsigned char TELOPT_SGA = 3; // Suppress Go Ahead. static constexpr unsigned char TELOPT_STATUS = 5; static constexpr unsigned char TELOPT_TIMING = 6; static constexpr unsigned char TELOPT_RCTE = 7; static constexpr unsigned char TELOPT_NAOCRD = 10; static constexpr unsigned char TELOPT_NAOHTS = 11; static constexpr unsigned char TELOPT_NAOHTD = 12; static constexpr unsigned char TELOPT_NAOFFD = 13; static constexpr unsigned char TELOPT_NAOVTS = 14; static constexpr unsigned char TELOPT_NAOVTD = 15; static constexpr unsigned char TELOPT_NAOLFD = 16; static constexpr unsigned char TELOPT_EXTEND_ASCII = 17; // WILL, DO static constexpr unsigned char TELOPT_LOGOUT = 18; // static constexpr unsigned char TELOPT_BM = 19; // Byte Macro static constexpr unsigned char TELOPT_DET = 20; // Data Entry Terminal static constexpr unsigned char TELOPT_SUPDUP = 21; // SUPDUP terminal? RFC734 static constexpr unsigned char TELOPT_SUPDUPOUTPUT = 22; // SUPDUP terminal within existing term? RFC749 static constexpr unsigned char TELOPT_SENDLOCATION = 23; // Send location string static constexpr unsigned char TELOPT_TTYPE = 24; // Terminal Type - RFC1091 static constexpr unsigned char TELOPT_EOR = 25; // Necessary? static constexpr unsigned char TELOPT_TUID = 26; // TAC? - Anyone still use this? static constexpr unsigned char TELOPT_OUTMRK = 27; // RFC933 static constexpr unsigned char TELOPT_TTYLOC = 28; // Terminal ID number static constexpr unsigned char TELOPT_3270REGIME = 29; // 3270 terminal? static constexpr unsigned char TELOPT_X3PAD = 30; // Support X.3-PAD static constexpr unsigned char TELOPT_NAWS = 31; // Negotiate about window size. static constexpr unsigned char TELOPT_TERMSPEED = 32; // Not meaningful anymore static constexpr unsigned char TELOPT_FLOWCONTROL = 33; // Not meaningful anymore static constexpr unsigned char TELOPT_LINEMODE = 34; // Line edit mode - Lots to do there static constexpr unsigned char TELOPT_XDISPLOC = 35; // X-Windows display addr static constexpr unsigned char TELOPT_AUTHENTICATION=37; // RFC2941 static constexpr unsigned char TELOPT_ENCRYPT = 38; // RFC2946 static constexpr unsigned char TELOPT_NEWENVIRON = 39; // Environment options static constexpr unsigned char TELOPT_TN3270E = 40; // TN3270 Enchancements RFC2355 static constexpr unsigned char TELOPT_XAUTH = 41; // XAUTH? static constexpr unsigned char TELOPT_CHARSET = 42; // RFC2066 static constexpr unsigned char TELOPT_RSP = 42; // Remote Serial Port static constexpr unsigned char TELOPT_COMPORTOPTION= 44; // Not meaningful anymore static constexpr unsigned char TELOPT_SLE = 45; // Suppress Local Echo static constexpr unsigned char TELOPT_STARTTLS = 46; // Start TLS static constexpr unsigned char TELOPT_KERMIT = 47; // Kermit static constexpr unsigned char TELOPT_SENDURL = 48; // Send URL static constexpr unsigned char TELOPT_FORWARDX = 49; // Forward X? static constexpr unsigned char TELOPT_EXOPL = 255; int m_parserState = 0; unsigned char m_optionVerb; unsigned char m_myNegotiationState[256]; // A negotiation state per option unsigned char m_theirNegotiationState[256]; // A negotiation state per option // negotiation state values: // // 0 = news to me, I assume they wouldn't use it (6) // 1 = just sent DO/WILL without provocation, waiting // 2 = just sent DONT/WONT without provocation, waiting // 3 = just sent DONT/WONT response to WILL/DO, waiting // 4 = just sent DO/WILL response to WONT/DONT, waiting // 5 = We've decided that I/they WILL/DO // 6 = We've decided that I/they WONT/DONT cstring m_incomingSB; char m_option; bool m_sendNAWS = true; void handle_option(bool response) { unsigned char msg[3]; msg[0] = IAC; msg[2] = m_option; bool pos = (m_optionVerb == DO) || (m_optionVerb == WILL); bool asking = (m_optionVerb == DO) || (m_optionVerb == DONT); unsigned char* state; if (asking) { state = m_myNegotiationState; msg[1] = WONT; if (response) msg[1] = WILL; } else { state = m_theirNegotiationState; msg[1] = DONT; if (response) msg[1] = DO; } if (pos) { switch (*state) { case 0: // unsolicited case 6: // unsolicited, but already discussed case 2: // I just said no, and they are disagreeing. case 3: // I just said no, and they are disagreeing. get_sink_filter()->bypass(buffer((char*)&msg[0], 3)); case 1: // Said I would, this must be the response case 4: // They came around. *state = response ? 6 : 3; case 5: // must not respond when already in this mode break; default: COGS_ASSERT(false); break; } } else { switch (*state) { case 0: // unsolicitied case 1: // Was going to, but was just told not to. Confirm. case 4: // I just said I would, and they are disagreeing. case 5: // Already agreed I would, they changed their mind. get_sink_filter()->bypass(buffer((char*)&msg[0], 3)); case 2: // Already said I wont, this was a response. case 3: // They came around *state = response ? 5 : 4; case 6: // We already discussed this, no change, ignored. break; default: COGS_ASSERT(false); break; } } } virtual composite_buffer filtering_source(composite_buffer& src) { composite_buffer result; composite_buffer::const_iterator itor = src.get_first_const_iterator(); while (!!itor) { unsigned char c = *itor; switch (m_parserState) { case 0: // Normal state { if (c == IAC) { // always eat the first IAC. result.append(src.split_off_before(itor.get_position())); itor = src.get_first_const_iterator(); m_parserState = 1; } else ++itor; break; } case 5: // SB content { if (c == IAC) // Two in a row means the value itself { m_incomingSB.append(IAC); m_parserState = 4; ++itor; break; } if (c == SE) // sub neg is over { // I suppose once we support some options that have SBs, that could go here m_parserState = 0; ++itor; src.set_to_subrange(itor.get_position()); itor = src.get_first_const_iterator(); break; } // Looks like SB was interrupt with a new IAC. // Fall through to state 1 } case 1: // Got an IAC { switch (c) { case IAC: // second IAC indicates it's intended to be passed through. { m_parserState = 0; ++itor; break; } case DO: case DONT: case WILL: case WONT: { m_optionVerb = c; m_parserState = 2; ++itor; break; } case SB: { m_optionVerb = c; m_parserState = 3; ++itor; break; } case AYT: { rcptr<terminal> term = m_terminal; if (!!term) term->telnet_are_you_there(); m_parserState = 0; ++itor; src.set_to_subrange(itor.get_position()); itor = src.get_first_const_iterator(); break; } case AO: { rcptr<terminal> term = m_terminal; if (!!term) term->telnet_abort_output(); m_parserState = 0; ++itor; src.set_to_subrange(itor.get_position()); itor = src.get_first_const_iterator(); break; } case EC: { rcptr<terminal> term = m_terminal; if (!!term) term->telnet_erase_char(); m_parserState = 0; ++itor; src.set_to_subrange(itor.get_position()); itor = src.get_first_const_iterator(); break; } case EL: { rcptr<terminal> term = m_terminal; if (!!term) term->telnet_erase_line(); m_parserState = 0; ++itor; src.set_to_subrange(itor.get_position()); itor = src.get_first_const_iterator(); break; } case BRK: { rcptr<terminal> term = m_terminal; if (!!term) term->telnet_break(); m_parserState = 0; ++itor; src.set_to_subrange(itor.get_position()); itor = src.get_first_const_iterator(); break; } case IP: { rcptr<terminal> term = m_terminal; if (!!term) term->telnet_interrupt_process(); m_parserState = 0; ++itor; src.set_to_subrange(itor.get_position()); itor = src.get_first_const_iterator(); break; } case GA: // Go-Ahead is unnecessary. We won't ever be using any half-duplex connections. case NOP: default: { m_parserState = 0; ++itor; src.set_to_subrange(itor.get_position()); itor = src.get_first_const_iterator(); } } break; } case 2: // Receive option name - Pass option on to handler { m_option = c; switch (m_option) { case TELOPT_BINARY: // always binary on case TELOPT_SGA: // always SGA { handle_option(true); break; } case TELOPT_ECHO: // ask terminal { rcptr<terminal> term = m_terminal; if (!!term) { bool b; if ((m_optionVerb == DO) || (m_optionVerb == DONT)) b = term->telnet_request_echo(m_optionVerb == DO); else b = term->telnet_notify_echo(m_optionVerb == WILL); handle_option(b); } break; } case TELOPT_TTYPE: { if (m_optionVerb == DO) { handle_option(true); rcptr<terminal> term = m_terminal; cstring termType = (!!term) ? term->get_telnet_terminal_type() : cstring::literal("UNKNOWN"); unsigned char msg[4] = { IAC, SB, TELOPT_TTYPE, IS }; get_sink_filter()->bypass(buffer((char*)&msg[0], 4)); get_sink_filter()->bypass(encode_buffer_const(buffer(&termType[0], termType.get_length()))); //msg[0] = IAC; msg[1] = SE; get_sink_filter()->bypass(buffer((char*)&msg[0], 2)); } else handle_option(m_optionVerb == WILL); break; } case TELOPT_NAWS: { if (m_optionVerb == DONT) { m_sendNAWS = false; handle_option(false); } else if (m_optionVerb == DO) { m_sendNAWS = true; handle_option(true); rcptr<terminal> term = m_terminal; if (!!term) { uint16_t width = 80; uint16_t height = 24; term->get_window_size(width, height); send_window_size(width, height); } } else handle_option(m_optionVerb == WILL); break; } default: handle_option(false); break; } m_parserState = 0; src.set_to_subrange(itor.get_position()); itor = src.get_first_const_iterator(); break; } case 3: // Receive option name, then wait for content, plus IAC SE { m_option = c; m_incomingSB.clear(); m_parserState = 4; ++itor; break; } case 4: { // Do IAC's need escaping in an SB sequence? // We're supposed to receive one right before an SE. // But, what if we get one and something other than SE if after it? if (c == IAC) m_parserState = 5; else m_incomingSB.append(c); ++itor; break; } default: { COGS_ASSERT(false); break; } } } return result; } const buffer iacBuf{ 1, (char)IAC }; virtual composite_buffer filtering_sink(composite_buffer& src) { return encode_buffer(src); } composite_buffer encode_buffer_const(const composite_buffer& src) { composite_buffer src2(src); return encode_buffer(src2); } composite_buffer encode_buffer(composite_buffer& src) { composite_buffer result; composite_buffer::const_iterator itor = src.get_first_const_iterator(); while (!!itor) { bool foundIAC = ((unsigned char)*itor == IAC); ++itor; if (!foundIAC) continue; result.append(src.split_off_before(itor.get_position())); result.append(iacBuf); itor = src.get_first_const_iterator(); continue; } return result; } public: explicit telnet(const rcref<datastream>& ds, const rcptr<terminal>& term = 0) : datastream_protocol(ds), m_terminal(term) { if (!!term) term->m_telnet = this_rcref; memset(m_myNegotiationState, 0, 256); memset(m_theirNegotiationState, 0, 256); unsigned char msg[3]; msg[0] = IAC; msg[1] = WILL; msg[2] = TELOPT_SGA; get_sink_filter()->bypass(buffer((char*)&msg[0], 3)); m_myNegotiationState[TELOPT_SGA] = 1; //msg[0] = IAC; msg[1] = DO; //msg[2] = TELOPT_SGA; get_sink_filter()->bypass(buffer((char*)&msg[0], 3)); m_theirNegotiationState[TELOPT_SGA] = 1; //msg[0] = IAC; //msg[1] = DO; msg[2] = TELOPT_BINARY; get_sink_filter()->bypass(buffer((char*)&msg[0], 3)); m_theirNegotiationState[TELOPT_BINARY] = 1; //msg[0] = IAC; msg[1] = WILL; //msg[2] = TELOPT_BINARY; get_sink_filter()->bypass(buffer((char*)&msg[0], 3)); m_myNegotiationState[TELOPT_BINARY] = 1; //msg[0] = IAC; //msg[1] = WILL; msg[2] = TELOPT_TTYPE; get_sink_filter()->bypass(buffer((char*)&msg[0], 3)); m_myNegotiationState[TELOPT_TTYPE] = 1; } void send_window_size(uint16_t width, uint16_t height) { if (m_sendNAWS) { unsigned char msg[4] = { IAC, SB, TELOPT_NAWS }; get_sink_filter()->bypass(buffer((char*)&msg[0], 3)); msg[0] = (char)(width >> 8); msg[1] = (char)width; msg[2] = (char)(height >> 8); msg[3] = (char)height; get_sink_filter()->bypass(encode_buffer_const(buffer((char*)&msg[0], 4))); msg[0] = IAC; msg[1] = SE; get_sink_filter()->bypass(buffer((char*)&msg[0], 2)); } } }; } } } #endif
27.939863
108
0.665703
b5869a966c858be6c802aeed55b10dba98576bc4
7,147
hpp
C++
tests/vex_tests.hpp
LIBHALA/hala
ff3950aef18b6cede48b45669be275b174f362a5
[ "BSD-3-Clause" ]
1
2021-02-25T16:21:42.000Z
2021-02-25T16:21:42.000Z
tests/vex_tests.hpp
mkstoyanov/hala
ff3950aef18b6cede48b45669be275b174f362a5
[ "BSD-3-Clause" ]
9
2020-09-03T23:31:22.000Z
2020-10-21T23:40:11.000Z
tests/vex_tests.hpp
mkstoyanov/hala
ff3950aef18b6cede48b45669be275b174f362a5
[ "BSD-3-Clause" ]
2
2020-03-03T17:39:37.000Z
2020-11-05T16:01:28.000Z
/* * Code Author: Miroslav Stoyanov * * Copyright (C) 2018 Miroslav Stoyanov * * This file is part of * Hardware Accelerated Linear Algebra (HALA) * */ #include "testing_common.hpp" template<typename T> T mabs2(T a){ return a * a; } template<typename T> std::complex<T> mabs2(std::complex<T> a){ T r = std::abs(a)*std::abs(a); return {r, r}; } template<typename T> T mabs(T a){ return std::abs(a); } template<typename T> std::complex<T> mabs(std::complex<T> a){ T r = std::abs(a); return {r, r}; } template<typename T, hala::regtype reg> void test_extended_registers(){ current_test<T> tests(regname(reg)); hala_rnd = 0; size_t N = 128; auto x = make_vector<T>(N); auto y = make_vector<T>(N); auto y2 = y; auto y_ref = y; T alpha = static_cast<T>(2.0); for(size_t i=0; i<N; i++) y_ref[i] += alpha * x[i]; // using vectorization, test multiply hala::mmpack<T, reg> scalar(alpha); for(size_t i=0; i<N; i+=scalar.stride){ hala::mmpack<T, reg> chunky = &y[i]; chunky += scalar * hala::mmload<reg>(&x[i]); chunky.put(&y[i]); } hassert(testvec(y, y_ref)); // test multiply add (fmadd) for(size_t i=0; i<N; i+=scalar.stride){ hala::mmpack<T, reg> chunky = &y2[i]; chunky.fmadd(scalar, &x[i]); chunky.put(&y2[i]); } hassert(testvec(y2, y_ref)); y = y_ref; auto vv = hala::mmzero<T, reg>(); std::stringstream ss; ss << vv; // covers the << overwrites // test divide scalar = static_cast<T>(4.0); hala::mmpack<T, reg> vexx; for(size_t i=0; i<N; i+=scalar.stride) hala::mmbind<reg>(&y[i]) /= scalar; for(size_t i=0; i<N; i++) y_ref[i] /= static_cast<T>(4.0); hassert(testvec(y, y_ref)); // test scale by mmpack y = y_ref; scalar -= hala::mmload<reg>(static_cast<T>(2.0)); for(size_t i=0; i<N; i+=scalar.stride){ auto v = hala::mmbind<reg>(&y[i]); v *= scalar; } for(size_t i=0; i<N; i++) y_ref[i] *= static_cast<T>(2.0); hassert(testvec(y, y_ref)); // test scale by value for(size_t i=0; i<N; i+=scalar.stride) hala::mmbind<reg>(&y[i]) *= scalar; for(size_t i=0; i<N; i++) y_ref[i] *= static_cast<T>(2.0); hassert(testvec(y, y_ref)); // test square-root x = y; y_ref = y; for(size_t i=0; i<N; i+=scalar.stride) hala::mmload<reg>(&x[i]).sqrt().put(&y[i]); for(size_t i=0; i<N; i+=scalar.stride) hala::mmbind<reg>(&x[i]).set_sqrt(); for(size_t i=0; i<N; i++) y_ref[i] = std::sqrt(y_ref[i]); hassert(testvec(y, y_ref, 5.E+01)); hassert(testvec(x, y_ref, 5.E+01)); // test abs() and abs2() hala_rnd = -20; y = make_vector<T>(N); y_ref = y; auto y_ref2 = y; auto nrm = hala::hala_abs(y[0]); for(auto v : y) nrm = std::max(nrm, hala::hala_abs(v)); for(size_t i=0; i<N; i+=scalar.stride) hala::mmload<reg>(&y[i]).abs().put(&x[i]); for(size_t i=0; i<N; i+=scalar.stride) hala::mmload<reg>(&y[i]).abs2().put(&y[i]); for(size_t i=0; i<N; i++) y_ref2[i] = mabs2(y_ref2[i]); for(size_t i=0; i<N; i++) y_ref[i] = mabs(y_ref[i]); hassert(testvec(x, y_ref)); hassert(testvec(y, y_ref2, nrm * nrm)); // test real and imag hala_rnd = 1; y = make_vector<T>(hala::mmpack<T, reg>::stride); for(size_t i=0; i<hala::mmpack<T, reg>::stride; i++){ auto yr = hala::mmload<reg>(&y[0]).real(i); auto yrr = std::real(y[i]); hassert(testnum(yr, yrr)); yr = hala::mmload<reg>(&y[0]).imag(i); yrr = std::imag(y[i]); hassert(testnum(yr, yrr)); } // test simple copy hala_rnd = 3; y = make_vector<T>(hala::mmpack<T, reg>::stride); hala::mmpack<T, reg> ytemp; for(size_t i=0; i<hala::mmpack<T, reg>::stride; i++) ytemp[i] = y[i]; y_ref = make_vector<T>(hala::mmpack<T, reg>::stride); ytemp.put(y_ref.data()); hassert(testvec(y, y_ref)); } template<typename T, template<typename, typename> class vclass, hala::regtype reg> void test_type_aligned_allocator(){ current_test<T> tests(std::string("alloc-") + regname(reg)); std::vector<T> x_ref, x_test; vclass<T, hala::aligned_allocator<T, reg>> x = {1.0, 2.0, 3.0}; hala::vcopy(x, x_ref); auto y = x; y.resize(11); std::swap(x, y); x = y; hala::vcopy(x, x_test); hassert(testvec(x_test, x_ref)); { auto t = std::move(x); x = vclass<T, hala::aligned_allocator<T, reg>>(2); x = std::move(t); } hala::vcopy(x, x_test); hassert(testvec(x_test, x_ref)); std::vector<vclass<T, hala::aligned_allocator<T, reg>>> fake_matrix(11, {17}); for(auto const& r : fake_matrix){ size_t pval = reinterpret_cast<size_t>(hala::get_data(r)); constexpr size_t alignment = hala::mmpack<T, reg>::stride * sizeof(T); hassert(pval % alignment == 0); // proper alignment } hala_rnd = 3; hala::aligned_vector<T, reg> vv, ww, rref; hala::vcopy( make_vector<T>(hala::mmpack<T, reg>::stride * 3), vv ); hala::vcopy( make_vector<T>(hala::mmpack<T, reg>::stride * 3), ww ); hala::vcopy(vv, rref); hala::axpy(1, ww, rref); for(auto iv = vv.begin(), iw = ww.begin(); iv != vv.end(); iv += hala::mmpack<T, reg>::stride, iw += hala::mmpack<T, reg>::stride) { hala::mmpack<T, reg> mm = &*iv; mm += &*iw; mm.put(&*iv); } hassert(testvec(vv, rref)); } template<template<typename, typename> class vclass, hala::regtype reg> void test_aligned_allocator(){ test_type_aligned_allocator<float, vclass, reg>(); test_type_aligned_allocator<double, vclass, reg>(); test_type_aligned_allocator<std::complex<float>, vclass, reg>(); test_type_aligned_allocator<std::complex<double>, vclass, reg>(); } template<typename T> void test_default(){ current_test<T> tests(std::string("alloc-default")); size_t num_entries = 256; hala_rnd = 3; // get some semi-random numbers auto rndx = make_vector<T>(num_entries); auto rndy = make_vector<T>(num_entries); // define two vectors aligned to the default register type hala::aligned_vector<T> x, y; // fill the vectors with the random data hala::vcopy(rndx, x); hala::vcopy(rndy, y); // perform operations using iterators for(auto ix = hala::mmbegin(x), iy = hala::mmbegin(y); ix < hala::mmend(x) && iy <= hala::mmend(y); hala::mmadvance(ix, iy)) { auto mmx = hala::mmbind(ix); // tests mmbind(iterator) mmx += iy; // tests += iterator auto mmy = hala::mmload(iy); // tests mmload(iterator) mmx *= mmy; // tests *= mmpack() } // on exit, mmx will sync back with ix // perform the same operations using the simple vectors for(size_t i=0; i<num_entries; i++) rndx[i] = (rndx[i] + rndy[i]) * rndy[i]; // copy the result to the rndy hala::vcopy(x, rndy); // compare the result computed with mmpack vs the regular one hassert(testvec(rndx, rndy)); }
30.156118
118
0.577165
b58bd59f08a69d9871df8ccb02f407adcc23138c
5,461
cpp
C++
VISUALC/source/repos/Project10/main.cpp
giljr/c
b8058423f9feda06f05e67af617a1e2f5089f9e8
[ "MIT" ]
null
null
null
VISUALC/source/repos/Project10/main.cpp
giljr/c
b8058423f9feda06f05e67af617a1e2f5089f9e8
[ "MIT" ]
null
null
null
VISUALC/source/repos/Project10/main.cpp
giljr/c
b8058423f9feda06f05e67af617a1e2f5089f9e8
[ "MIT" ]
1
2021-06-29T08:26:40.000Z
2021-06-29T08:26:40.000Z
/* #Project 10 - Visual C++ 2019 - Exercise 1 - Homework - Snack Bar Description This program calculates how much each customer spends in a snack bar. In essence, this program initializes 3 matrices: p[1][7] - Price of the Snack bar Products q[7][1] - Quantity of each item asked t[1][7] - Total price to pay Then, Make the math matrices multiplication: p[1][7] * q[7][1] = t[1][7] _ _ _ _ | 5.00 | | 5.00 | | 8.79 | | 8.79 | | 9.99 | * [1,1,1,1,1,1,1] = | 9.99 | | 6.89 | | 6.89 | | 4.80 | | 4.80 | | 3.49 | | 3.49 | |_ 4.99_| |_ 4.99_| Total = $ 43.95 Other matrices, like 'seq', 'code' and 'menu' serves only for presentation purpose; The user enter Code + Product + Space serially; The user can accumulate the products; When done, type 'q' to get the Receipt; It is for the academy's elegant solution of Project 31:) Printing on the screen a test of the program using the first 3 digits for products and the last 3 digits for quantity of the RU identifier: *********************** Output: (RU 333 6 662) ------------------------------- :::::::JayThree Snack Bar:::::: Welcome!! ------------------------------- --------------MENU------------- Code Product Price ------------------------------- 1 Hot_Dog 5.00 2 X_Salad 8.79 3 X_Bacon 9.99 4 Mix 6.89 5 Salad 4.80 6 Water 3.49 7 Soda 4.99 ------------------------------- Please Choose your Combo:) Type:Code>Space>Quant>Enter: To Quit, type 'q':) 3 6 You chose: 6 x X-Bacon 3 6 You chose: 6 x X-Bacon 3 2 You chose: 2 x X-Bacon q Good Choice! Here you have the ticket: ___________Receipt:____________ Quant Price Product Total ------------------------------- 14 x 9.99 X_Bacon 139.86 ------------------------------- Total = 139.86 ------------------------------- Thank you for your visit and have a good appetite! *********************** Editor J3 Date: Jul, 15/2020 I'd like to thank Prof. Borin, Me.(https://br.linkedin.com/in/borinvini) o/ */ #include <stdio.h> int main() { int seq[1][7] = { 1, 2, 3, 4, 5, 6, 7 }; int code[1][7] = { 100, 101, 102, 103, 104, 105, 106 }; char menu[7][10] = { "Hot_Dog", "X_Salad", "X_Bacon", "Mix", "Salad", "Water", "Soda" }; float p[1][7] = { 5.00, 8.79, 9.99, 6.89, 4.80, 3.49, 4.99 }, t[1][7] = { 0 }, debit; int q[7][1] = { 0,0,0,0,0,0,0 }; int prows = 1, pcolumns = 7, qrows = 7, qcolumns = 1, trows = 1, tcolumns = 7; int i, j, k; float res = 0, sum = 0; int prod = 0; int quant = 0; /* Menu on screen splash */ printf("\n-------------------------------"); printf("\n:::::::JayThree Snack Bar::::::"); printf("\n\t Welcome!!"); printf("\n-------------------------------"); printf("\n--------------MENU-------------\n"); printf("Code\tProduct\t\tPrice\n"); printf("-------------------------------\n"); for (int i = 0; i < 1; i++) { for (int j = 0; j < 7; j++) { printf("%i\t", seq[i][j]); printf("%s\t\t", menu[j]); printf("%.2f\t\n", p[i][j]); } printf("-------------------------------"); } printf("\n\nPlease Choose your Combo:)\nType:Code>Space>Quant>Enter:\n"); printf("To Quit, type 'q':)\n"); scanf_s("%i %i", &prod, &quant); /* Populating 'q' matrix - quantity of each product indexed */ /* While loop exit by typing 'q' - Quit */ /* Product can be accumulated in a single bid */ while (getchar() != 'q') { switch (prod) { case 1: printf("You chose: %d x Hot Dog\n", quant); q[0][0] += quant; break; case 2: printf("You chose: %d x X-Salad\n", quant); q[1][0] += quant; break; case 3: printf("You chose: %d x X-Bacon\n", quant); q[2][0] += quant; break; case 4: printf("You chose: %d x Mix\n", quant); q[3][0] += quant; break; case 5: printf("You chose: %d x Salad\n", quant); q[4][0] += quant; break; case 6: printf("You chose: %d x Water\n", quant); q[5][0] += quant; break; case 7: printf("You chose: %d x Soda\n", quant); q[6][0] += quant; break; default: printf("Invalid Product:/\n"); break; } scanf_s("%i %i", &prod, &quant); } printf("\tGood Choice!\n"); /* Calculating all 't' matrix - total to pay = debit */ int m = 0; for (i = 0; i < prows; i++) { for (j = 0; j < qcolumns; j++) { for (k = 0; k < qrows; k++) { res += p[i][k] * q[k][j]; t[i][m] = res; m++; sum += res; res = 0; } debit = sum; sum = 0; } } /* Printing the receipt - print when there is value on 't' index */ printf("\n Here you have the ticket:\n\n"); printf("___________Receipt:____________\n"); printf("Quant\tPrice\tProduct\tTotal\n"); printf("-------------------------------\n"); for (i = 0; i < trows; i++) { for (j = 0; j < tcolumns; j++) { if (t[i][j] != 0) { printf("%d x\t", q[i][j]); printf("%.2f\t", p[i][j]); printf("%s\t", menu[j]); printf("%.2f\t\n", t[i][j]); } } printf("-------------------------------\n"); printf("\t\tTotal = %.2f\t", debit); printf("\t\t\n-------------------------------"); printf("\t\t\n"); } printf("\nThank you for your visit\nand have a good appetite!\n"); //system("pause"); return 0; }
24.271111
90
0.478301
b590fd34fdece371bdfa3668cfc75fdf0b20a1a4
10,537
cpp
C++
MCUME/teensycastaway41/mem.cpp
DigiTorus86/Teensy-R4ge-Pro
d94a73f4f60957b3f28a27b7d6f74b01a61121fa
[ "MIT" ]
1
2022-01-13T02:00:52.000Z
2022-01-13T02:00:52.000Z
MCUME/teensycastaway41/mem.cpp
DigiTorus86/Teensy-R4ge-Pro
d94a73f4f60957b3f28a27b7d6f74b01a61121fa
[ "MIT" ]
null
null
null
MCUME/teensycastaway41/mem.cpp
DigiTorus86/Teensy-R4ge-Pro
d94a73f4f60957b3f28a27b7d6f74b01a61121fa
[ "MIT" ]
1
2022-01-11T12:55:50.000Z
2022-01-11T12:55:50.000Z
/* * Castaway * (C) 1994 - 2002 Martin Doering, Joachim Hoenig * * $File$ - memory read/write * * This file is distributed under the GPL, version 2 or at your * option any later version. See doc/license.txt for details. * * revision history * 23.05.2002 JH FAST1.0.1 code import: KR -> ANSI, restructuring * 30.05.2002 JH Discontinued using mmap and mprotect, now using * Martin's memory access jump table. * 12.06.2002 JH Correct bus error/address error exception stack frame * 14.06.2002 JH LowRamSetX() functions improved. * 09.07.2002 JH Now loads any 192k ROM file * 10.07.2002 MAD Now loads any ROM file * 16.09.2002 JH Bugfix: Word access on unmapped I/O address stacked * two bus error stack frames. Fault address corrected. * 08.10.2002 JH Fixed integer types. * 27.10.2002 AG Trashed everything for more speed! mwuhahaha! */ #include <stdio.h> #include <stdlib.h> #include <malloc.h> #ifndef DREAMCAST #else #include <string.h> #endif #include "dcastaway.h" #include "st.h" #include "mem.h" #include "m68k_intrf.h" #include <Arduino.h> static unsigned rombase_pos=0; char rom[80]; // = ROM; #ifdef DREAMCAST void reinit_sdcard(void); char rom_sd[24] = ROM_SD; #endif static int samvol[16]={0,0,0,1,1,1,2,3,5,7,11,17,25,38,57,85}; extern uint32 psg[26]; #define lastpsg psg[25] #define sampos psg[24] PROGMEM char GetMemB(unsigned long address) { address &= MEMADDRMASK; if (address<MEMSIZE) return ReadB(address + membase); else if (address<ROMBASE2) return -1; else if (address<IOBASE) return ReadB(address + rombase); else if (address<IOBASE+IOSIZE) return DoIORB(address); return -1; } /* Fetch word, address may not be word-aligned */ PROGMEM short GetMemW(unsigned long address) { #ifdef CHKADDRESSERR address &= MEMADDRMASK; if (address & 0x1){ ExceptionGroup0(ADDRESSERR, address, 1); return -1; } #else address &= MEMADDRMASKS; #endif if (address<MEMSIZE) return ReadW(address + membase); else if (address<ROMBASE2) return -1; else if (address<IOBASE) return ReadW(address + rombase); else if (address<IOBASE+IOSIZE) return DoIORW(address); return -1; } /* Fetch dword, address may not be dword-aligned */ PROGMEM long GetMemL(unsigned long address) { #ifdef CHKADDRESSERR address &= MEMADDRMASK; if (address & 0x1){ ExceptionGroup0(ADDRESSERR, address, 1); return -1; } #else address &= MEMADDRMASKS; #endif if (address<MEMSIZE) return ReadL(address + membase); else if (address<ROMBASE2) return -1; if (address<IOBASE) return ReadL(address + rombase); if (address<IOBASE+IOSIZE) return DoIORL(address); return -1; } /* Write byte to address */ PROGMEM void SetMemB (unsigned long address, unsigned char value) { address &= MEMADDRMASK; ON_WRITE(address, value); if (address<MEMSIZE) { //RAM if (address<SVADDR && !GetFC2()){ ExceptionGroup0(BUSERR, address, 0); return; } WriteB(address + membase, value); return; } if (address>=IOBASE && address<IOBASE+IOSIZE) { //IO DoIOWB(address, value); return; } //Unmapped ON_UNMAPPED(address, value); } /* Write word, address may not be word-aligned */ PROGMEM void SetMemW(unsigned long address, unsigned short value) { #ifdef CHKADDRESSERR address &= MEMADDRMASK; if (address & 0x1){ ExceptionGroup0(ADDRESSERR, address, 1); return; } #else address &= MEMADDRMASKS; #endif ON_WRITE(address, value); if (address<MEMSIZE) { //RAM if (address<SVADDR ){ if (!GetFC2()||address<8){ ExceptionGroup0(BUSERR, address, 0); return; } } WriteW(address + membase, value); return; } if (address>=IOBASE && address<IOBASE+IOSIZE) { //IO DoIOWW(address, value); return; } //Unmapped ON_UNMAPPED(address, value); } /* Write dword, address may not be dword-aligned */ PROGMEM void SetMemL(unsigned long address, unsigned long value) { #ifdef CHKADDRESSERR address &= MEMADDRMASK; if (address & 0x1){ ExceptionGroup0(ADDRESSERR, address, 1); return; } #else address &= MEMADDRMASKS; #endif ON_WRITE(address, value); if (address<MEMSIZE) { //RAM if (address<SVADDR){ if (!GetFC2()||address<8){ ExceptionGroup0(BUSERR, address, 0); return; } } #ifdef OPTIMIZE_VMEM if ( (address >= vid_mem) && (address < (vid_mem+32768) ) ) { printf("vwlmem\n"); WriteL(&videobuf[address-vid_mem], value); } else #endif WriteL(address + membase, value); return; } if (address>=IOBASE && address<IOBASE+IOSIZE) { //IO DoIOWL(address, value); return; } //Unmapped ON_UNMAPPED(address, value); } #ifdef UNUSED //Simplifed versions of memory access commands used for instructions fetch //Instruction fetch is likely only to be from ram or rom, otherwise the //program will surely have crashed anyway! char GetMemBpc(unsigned long address) { address &= MEMADDRMASK; if (address<MEMSIZE) return ReadB(address + membase); else return ReadB(address + rombase); } short GetMemWpc(unsigned long address) { address &= MEMADDRMASK; if (address<MEMSIZE) return ReadW(address + membase); else return ReadW(address + rombase); } /* Fetch dword, address may not be dword-aligned */ long GetMemLpc(unsigned long address) { address &= MEMADDRMASK; if (address<MEMSIZE) return ReadL(address + membase); else return ReadL(address + rombase); } //Movep support //------------- void SetMemPW(unsigned long address, unsigned long value) { // int8 psgctrl1,value1; if (address&0xffff03==0xff8800) { uint32 psgctrl1=(value>>8)&15; uint32 value1=value&255; psg[psgctrl1]=value1; if (psgctrl1==lastpsg) sample[sampos++]=samvol[psg[8]]+samvol[psg[9]]+samvol[value1]; else if (psgctrl1==13 || psgctrl1==12) psg_epos=0; return; } address &= MEMADDRMASK; if (address>=IOBASE && address<IOBASE+IOSIZE) { //IO DoIOWB(address, (int8)(value>>8)); DoIOWB(address+2, (int8)value); return; } if (address<MEMSIZE) { //RAM if (address<SVADDR && !GetFC2()) ExceptionGroup0(BUSERR, address, 0); address+=(uint32)membase; WriteB(address, (int8)(value>>8)); WriteB(address+2, (int8)value); return; } } void SetMemPL(unsigned long address, unsigned long value) {// int8 psgctrl1,psgctrl2,value1,value2; if (address&0xffff03==0xff8800) { uint32 psgctrl1=(value>>24)&15; uint32 value1=(value>>16)&255; psg[psgctrl1]=value1; if (psgctrl1==lastpsg) sample[sampos++]=samvol[psg[8]]+samvol[psg[9]]+samvol[value1]; else if (psgctrl1==13 || psgctrl1==12) psg_epos=0; psgctrl1=(value>>8)&15; value1=value&255; if (psgctrl1==lastpsg) sample[sampos++]=samvol[psg[8]]+samvol[psg[9]]+samvol[value1]; else if (psgctrl1==13 || psgctrl1==12) psg_epos=0; return; } address &= MEMADDRMASK; if (address>=IOBASE && address<IOBASE+IOSIZE) { //IO DoIOWB(address, (int8)(value>>24)); DoIOWB(address+2, (int8)(value>>16)); DoIOWB(address+4, (int8)(value>>8)); DoIOWB(address+6, (int8)value); return; } if (address<MEMSIZE) { //RAM if (address<SVADDR && !GetFC2()) ExceptionGroup0(BUSERR, address, 0); address+=(uint32)membase; WriteB(address, (int8)(value>>24)); WriteB(address+2, (int8)(value>>16)); WriteB(address+4, (int8)(value>>8)); WriteB(address+6, (int8)value); return; } } static void *__rombase=NULL, *__membase=NULL; void MemQuit(void) { if (__membase) free(__membase); __membase=NULL; if (__rombase) free(__rombase); __rombase=NULL; } static void _set_dword(void *buf,unsigned dat) { unsigned short *b=(unsigned short *)buf; *b++=dat&0xffff; *b=dat>>16; } void MemClean(void) { membase=(int8*)__membase; memset(membase,0,MEMSIZE); //savestate_init(); memcpy (membase, ((int8*)__rombase)+rombase_pos, 8); _set_dword(membase+0x420,0x752019f3); _set_dword(membase+0x43a,0x237698aa); _set_dword(membase+0x51a,0x5555aaaa); #if MEMSIZE==0x00080000 _set_dword(membase+0x436,0x80000-0x8000); _set_dword(membase+0x42e,0x80000); WriteB(membase+0x425,1); WriteB(rombase+0xff8000,1); memconf=1; #else #if MEMSIZE==0x00100000 _set_dword(membase+0x436,0x100000-0x8000); _set_dword(membase+0x42e,0x100000); WriteB(membase+0x425,5); WriteB(rombase+0xff8000,5); memconf=5; #else #if MEMSIZE==0x00200000 _set_dword(membase+0x436,0x200000-0x8000); _set_dword(membase+0x42e,0x200000); WriteB(membase+0x425,2); WriteB(rombase+0xff8000,2); memconf=2; #else #if MEMSIZE==0x00400000 _set_dword(membase+0x436,0x400000-0x8000); _set_dword(membase+0x42e,0x400000); WriteB(membase+0x425,0xA); WriteB(rombase+0xff8000,0xA); memconf=0xA; #else #error DCaSTaway ERROR: MEMSIZE incorrect. #endif #endif #endif #endif _set_dword(membase+0x4c2,3); WriteW(membase+0x4a6,2); //if (TosCountry) // vid_syncmode=2; //else // vid_syncmode=0; } static unsigned actual_rom_crc=0; static unsigned rom_checksum(void) { int n; unsigned crc=0; for(n=ROMBASE2;n<MEMADDRSIZE;n++) crc+=(n+1)*rombase[n]; return crc; } void MemReInit(void) { unsigned crc=rom_checksum(); if (crc!=actual_rom_crc) MemInit(); else MemClean(); } PROGMEM int MemInit(void) { int n; uint8 val1,val2; unsigned long len; FILE *roms; //Load ROM if (NULL == (roms = fopen (rom, "rb"))) { #ifdef DREAMCAST reinit_sdcard(); if (NULL == (roms = fopen (rom_sd, "rb"))) #endif { if (__membase) memset(__membase,0,MEMSIZE); return 1; } } MemQuit(); fseek(roms,0,SEEK_END); len=(unsigned long)ftell(roms); fseek(roms,0,SEEK_SET); if (len>(MEMADDRSIZE-ROMBASE2)) len=(MEMADDRSIZE-ROMBASE2); if (len<=(192*1024)) rombase_pos=ROMBASE-ROMBASE2; else rombase_pos=0; if (!__rombase) __rombase = calloc(1,MEMADDRSIZE-ROMBASE2); rombase=(int8*)__rombase; for(n=0;n<(MEMADDRSIZE-ROMBASE2);n+=2) { rombase[n]=0x4e; rombase[n+1]=0x71; } if (len != fread(rombase+rombase_pos,1,len,roms)) { fclose(roms); return 2; } fclose (roms); #ifdef BYTES_SWAP for (n=0; n<(MEMADDRSIZE-ROMBASE2); n+=2) { val1 = rombase[n]; val2 = rombase[n+1]; rombase[n] = val2; rombase[n+1] =val1; } #endif /* precalculate rombase - now just address-adding happens later */ if (rombase_pos) { rombase -= ROMBASE2+rombase_pos-(ROMBASE-ROMBASE2); memcpy(rombase+ROMBASE2,rombase+ROMBASE,(MEMADDRSIZE-ROMBASE)); } else { rombase -= ROMBASE2; memcpy(rombase+ROMBASE,rombase+ROMBASE2,(MEMADDRSIZE-ROMBASE)); } TOS_FixRom((uint8 *)(((int8*)__rombase)+rombase_pos)); //Allocate and clear RAM if (!__membase) __membase = (int8*)calloc(1,MEMSIZE+0x10); MemClean(); actual_rom_crc=rom_checksum(); initialize_memmap(); return 0; } #endif
21.63655
86
0.692892
b59205c22fb73cbd3f92597ed12c7ff49f7d821c
730
cpp
C++
hw5/src/test_Country.cpp
Rytheking/OOP-refleming
db81b3efe7e99b00f84ca116287f6510c9e77493
[ "MIT" ]
null
null
null
hw5/src/test_Country.cpp
Rytheking/OOP-refleming
db81b3efe7e99b00f84ca116287f6510c9e77493
[ "MIT" ]
null
null
null
hw5/src/test_Country.cpp
Rytheking/OOP-refleming
db81b3efe7e99b00f84ca116287f6510c9e77493
[ "MIT" ]
null
null
null
#include "Country.h" #include "gtest/gtest.h" using namespace std; using namespace france; TEST(Country, Constructor) { float GDP = 314000000000; string continent("europe"); Country Country(GDP,continent); ASSERT_EQ(Country.GDP(),GDP); ASSERT_EQ(Country.continent(),continent); float newGDP = 130000; Country.GDP(newGDP); ASSERT_EQ(Country.GDP(),newGDP); } TEST(Country, Constness) { float GDP = 999999; string continent("africa"); const Country Country(GDP,continent); ASSERT_EQ(Country.GDP(),GDP); ASSERT_EQ(Country.continent(),continent); } int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
24.333333
47
0.664384
b594a909f22095675ae48fd2966ef8f1bb73403e
417
hpp
C++
libctrpf/include/CTRPluginFramework/System/Clock.hpp
MirayXS/Vapecord-ACNL-Plugin
247eb270dfe849eda325cc0c6adc5498d51de3ef
[ "MIT" ]
null
null
null
libctrpf/include/CTRPluginFramework/System/Clock.hpp
MirayXS/Vapecord-ACNL-Plugin
247eb270dfe849eda325cc0c6adc5498d51de3ef
[ "MIT" ]
null
null
null
libctrpf/include/CTRPluginFramework/System/Clock.hpp
MirayXS/Vapecord-ACNL-Plugin
247eb270dfe849eda325cc0c6adc5498d51de3ef
[ "MIT" ]
null
null
null
#ifndef CTRPLUGINFRAMREWORK_CLOCK_HPP #define CTRPLUGINFRAMREWORK_CLOCK_HPP #include "CTRPluginFramework/System/Time.hpp" namespace CTRPluginFramework { class Clock { public: Clock(void); Clock(Time time); Time GetElapsedTime(void) const; bool HasTimePassed(Time time) const; Time Restart(void); private: Time _startTime; }; } #endif
18.954545
47
0.64988
b59d7c70c5f754130b39ba2fe863763260c080e6
992
hpp
C++
src/gui.hpp
MisterIsmed/PhotoStick
9383a0b86409f4c1f398eb3b913b32adb9762070
[ "MIT" ]
null
null
null
src/gui.hpp
MisterIsmed/PhotoStick
9383a0b86409f4c1f398eb3b913b32adb9762070
[ "MIT" ]
null
null
null
src/gui.hpp
MisterIsmed/PhotoStick
9383a0b86409f4c1f398eb3b913b32adb9762070
[ "MIT" ]
null
null
null
#ifndef GUI_HPP #define GUI_HPP #include "GUIslice.h" #include "GUIslice_drv.h" #include "GUIslice_ex.h" #include "SdFat.h" #include "util.hpp" enum Animation { ANIM_LIGHT, ANIM_BLINK, ANIM_MARQUEE, }; struct StickConfig { const char *fileToLoad; Animation animation; CRGB animationColor; uint8_t brightness; uint8_t speed; uint8_t countdown; uint8_t repetitions; }; namespace Gui { // Initialize GUI. Needs SD access to enumerate BMP files. void init(SdFat &sd); // Update GUI, must be called periodically. If enableWarning is true, sets // background color to red (to warn about low battery voltage). // If is Running is true, will update status text void update(bool enableWarning, bool isRunning); // Return true if user has requested to launch IMAGE or CREATIVE mode. // In this case, cfg will be updated to carry all user-configured settings. // Otherwise, return false. bool readyToGo(StickConfig &cfg); } #endif // vim: et ts=2
21.106383
75
0.721774
b59edf51969128b8b7bbed720ce96ae262d8068c
723
cpp
C++
learncpp/average.cpp
ignaciop/c-varios
c8ef033485efd19a01fbc43658be36473eb1d08d
[ "MIT" ]
null
null
null
learncpp/average.cpp
ignaciop/c-varios
c8ef033485efd19a01fbc43658be36473eb1d08d
[ "MIT" ]
null
null
null
learncpp/average.cpp
ignaciop/c-varios
c8ef033485efd19a01fbc43658be36473eb1d08d
[ "MIT" ]
null
null
null
#include <iostream> #include <cstdint> class Average { private: int32_t m_total = 0; int8_t m_numbers = 0; public: Average() {} friend std::ostream& operator<<(std::ostream &out, const Average &average) { out << static_cast<double>(average.m_total) / average.m_numbers; return out; } Average& operator+=(int num) { m_total += num; ++m_numbers; return *this; } }; int main() { Average avg; avg += 4; std::cout << avg << '\n'; avg += 8; std::cout << avg << '\n'; avg += 24; std::cout << avg << '\n'; avg += -10; std::cout << avg << '\n'; (avg += 6) += 10; // 2 calls chained together std::cout << avg << '\n'; Average copy = avg; std::cout << copy << '\n'; return 0; }
15.0625
77
0.562932
b27158435fe44061b11bd04087b322d571542b30
4,017
hpp
C++
ConvertTours/Data/Tour_File.hpp
kravitz/transims4
ea0848bf3dc71440d54724bb3ecba3947b982215
[ "NASA-1.3" ]
2
2018-04-27T11:07:02.000Z
2020-04-24T06:53:21.000Z
ConvertTours/Data/Tour_File.hpp
idkravitz/transims4
ea0848bf3dc71440d54724bb3ecba3947b982215
[ "NASA-1.3" ]
null
null
null
ConvertTours/Data/Tour_File.hpp
idkravitz/transims4
ea0848bf3dc71440d54724bb3ecba3947b982215
[ "NASA-1.3" ]
null
null
null
//******************************************************** // Tour_File.hpp - Tour File Input/Output //******************************************************** #ifndef TOUR_FILE_HPP #define TOUR_FILE_HPP #include "Ext_Header.hpp" //--------------------------------------------------------- // Tour_File Class definition //--------------------------------------------------------- class Tour_File : public Ext_Header { public: Tour_File (Access_Type access = READ, Format_Type format = DEFAULT_FORMAT); Tour_File (char *filename, Access_Type access = READ, Format_Type format = DEFAULT_FORMAT); virtual ~Tour_File (void); int Household (void) { Get_Field (hhold, &lvalue); return (lvalue); } int Person (void) { Get_Field (person, &lvalue); return (lvalue); } int Tour (void) { Get_Field (tour, &lvalue); return (lvalue); } int Purpose (void) { Get_Field (purpose, &lvalue); return (lvalue); } int Mode (void) { Get_Field (mode, &lvalue); return (lvalue); } int Origin (void) { Get_Field (origin, &lvalue); return (lvalue); } int Destination (void) { Get_Field (destination, &lvalue); return (lvalue); } int Stop_Out (void) { Get_Field (stop_out, &lvalue); return (lvalue); } int Stop_In (void) { Get_Field (stop_in, &lvalue); return (lvalue); } int Start (void) { Get_Field (start, &lvalue); return (lvalue); } int Return (void) { Get_Field (end, &lvalue); return (lvalue); } int Group (void) { Get_Field (group, &lvalue); return (lvalue); } void Household (int value) { Put_Field (hhold, value); } void Person (int value) { Put_Field (person, value); } void Tour (int value) { Put_Field (tour, value); } void Purpose (int value) { Put_Field (purpose, value); } void Mode (int value) { Put_Field (mode, value); } void Origin (int value) { Put_Field (origin, value); } void Destination (int value) { Put_Field (destination, value); } void Stop_Out (int value) { Put_Field (stop_out, value); } void Stop_In (int value) { Put_Field (stop_in, value); } void Start (int value) { Put_Field (start, value); } void Return (int value) { Put_Field (end, value); } void Group (int value) { Put_Field (group, value); } virtual bool Create_Fields (void); int HHold_Field (void) { return (hhold); } int Person_Field (void) { return (person); } int Tour_Field (void) { return (tour); } int Purpose_Field (void) { return (purpose); } int Mode_Field (void) { return (mode); } int Origin_Field (void) { return (origin); } int Dest_Field (void) { return (destination); } int Stop_Out_Field (void) { return (stop_out); } int Stop_In_Field (void) { return (stop_in); } int Start_Field (void) { return (start); } int Return_Field (void) { return (end); } int Group_Field (void) { return (group); } int HHold_Field (char *name) { return ((hhold = Required_Field (name))); } int Person_Field (char *name) { return ((person = Required_Field (name))); } int Tour_Field (char *name) { return ((tour = Required_Field (name))); } int Purpose_Field (char *name) { return ((purpose = Required_Field (name))); } int Mode_Field (char *name) { return ((mode = Required_Field (name))); } int Origin_Field (char *name) { return ((origin = Required_Field (name))); } int Dest_Field (char *name) { return ((destination = Required_Field (name))); } int Stop_Out_Field (char *name) { return ((stop_out = Required_Field (name))); } int Stop_In_Field (char *name) { return ((stop_in = Required_Field (name))); } int Start_Field (char *name) { return ((start = Required_Field (name))); } int Return_Field (char *name) { return ((end = Required_Field (name))); } int Group_Field (char *name) { return ((group = Required_Field (name))); } protected: virtual bool Set_Field_Numbers (void); private: void Setup (void); int lvalue; int hhold, person, tour, purpose, mode, origin, destination, stop_out, stop_in, start, end, group; }; #endif
45.647727
99
0.620861
b2737351348c9f7cb0d5f94dba20b4ebc9c1a5dc
619
cpp
C++
src/RollerTile.cpp
witczenko/jackpot
e82ced83eb7b8fd72ef27680de06178f4ebc5edc
[ "MIT" ]
null
null
null
src/RollerTile.cpp
witczenko/jackpot
e82ced83eb7b8fd72ef27680de06178f4ebc5edc
[ "MIT" ]
null
null
null
src/RollerTile.cpp
witczenko/jackpot
e82ced83eb7b8fd72ef27680de06178f4ebc5edc
[ "MIT" ]
null
null
null
#include "RollerTile.h" RollerTile::RollerTile(int id, SDL_Rect destination, SDL_Renderer * renderer, SDL_Texture * texture): renderer(nullptr), texture(nullptr), destination({0,0,0,0}), id(NONE_ID) { this->destination = destination; this->renderer = renderer; this->texture = texture; this->id = id; } RollerTile::~RollerTile() { } void RollerTile::SetDestination(SDL_Rect dest) { this->destination = dest; } SDL_Rect RollerTile::GetDestination() { return destination; } int RollerTile::GetId() { return id; } void RollerTile::Render() { SDL_RenderCopy(renderer, texture, nullptr, &destination); }
15.475
101
0.720517
b27440fa42855642dba8775c9d2c8585dcb325a5
5,999
hpp
C++
inc/goo_bitset.hpp
CrankOne/Goo
b909c72a5c87cd11d9c27d42b8332c1b5694cfe0
[ "MIT" ]
null
null
null
inc/goo_bitset.hpp
CrankOne/Goo
b909c72a5c87cd11d9c27d42b8332c1b5694cfe0
[ "MIT" ]
2
2017-12-28T10:09:43.000Z
2018-02-21T13:34:02.000Z
inc/goo_bitset.hpp
CrankOne/Goo
b909c72a5c87cd11d9c27d42b8332c1b5694cfe0
[ "MIT" ]
null
null
null
# include <cstdint> # include <cstddef> # include <ostream> # include <cassert> # include <cstring> # include <stdexcept> # include <bitset> # include <iostream> // XXX # pragma once namespace goo { /**@class Bitset * @brief A dynamic bitset implementaation. * * We want some nice features of bitsets which length may be parameterised * once during the runtime (or supposed to undergo rare resizes in non-critical * sections). We don't want to bring the boost dependencies, however. * * It has to be similar to std::vector<>, but optimized rather for single * allocation, rather than utilize some pro-active allocating strategies. * * We also want some synctactic sugar, like in std::bitset<N> (all(), none(), * binary operators, etc.). * * It may be wiped in future, if STL will introduce such a thing... Perhaps, * for the time being the bitset is a nice container to study for novice. * * Bits layout scheme * * For bitset of size N, the M words will be allocated, where M is computed as: * M = N/sizeof(Word_t) ; if N%sizeof(Word_t) == 0 * M = N/sizeof(Word_t) + 1 ; otherwise * Bits the will be placed in member Word_t * _data: * * | 0100 ... | 1100 ... | ... | 1010 .. | * Word #0 Word #1 ... Word #M * * In each word, the bits are numerated from right to left. For case when * _size%sizeof(Word_t) != 0, there is a last Word_t block which is * used only partially. Generally, we do not care about its content. To get rid * of it there is a special `_tailMask' member containing a bitmask disabling * those insignificant bits. * * @TODO: profile, study performance against different Word_t types * @TODO: allocators * @TODO: bitshift operators (<<. <<=, >>, >>=). * @TODO: check for big-endian platforms */ class Bitset { protected: typedef uint32_t Word_t; constexpr static size_t nBiW = 8*sizeof(Word_t); private: size_t _size; Word_t * _data; size_t _nWords; // real physical size of the _data Word_t _tailMask; protected: virtual Word_t * _alloc( size_t ); virtual void _delete( Word_t * ); void _free(); public: /// Empty set ctr. Bitset(); /// Bitset copy ctr. Bitset( const Bitset & ); /// Allocates set of size N. Bitset(size_t length); /// Allocates set of size N and sets to value. Bitset(size_t length, unsigned long v); /// Frees allocated memory. ~Bitset(); /// Assignment operator. Bitset & operator=(const Bitset&); /// Sets all bits to true. void set(); /// Sets n-th bit to `value'. void set(size_t n, bool value=true); /// Sets all bits to false. void reset(); /// Sets n-th bit to false. void reset(size_t n); /// Re-allocates the bitset. New bits will be appended to the back in /// undefined state. void resize(size_t); /// Inverts n-th bit in set, returns *this ref. Bitset & flip(size_t); /// Returns true if bitset is empty (of zero size). inline bool empty() const { return !_size; } // todo: suboptimal? /// Returns number of bits stored. inline size_t size() const { return _size; } /// Returns value of n-th bit. inline bool test(size_t n) const { assert( size() > n ); return _data[n/nBiW] & (Word_t{1} << (n%nBiW)); } /// Returns true, if all bits are set to truth. bool all() const; operator bool() const { return any(); } /// Returns true if any of bits is set to truth. bool any() const; /// Returns true if none of bits is set to truth. bool none() const; /// Inverts all bits in set, returns *this ref. Bitset & flip(); Bitset operator~() const; /// Computes bitwise-and with given bitset, writing result to current set. Bitset & bitwise_and( const Bitset & ); inline Bitset & operator&=( const Bitset & bs) { return bitwise_and(bs); } Bitset operator&( const Bitset & ) const; /// Computes bitwise-or with givine bitset, writing result to current set. Bitset & bitwise_or( const Bitset & ); inline Bitset & operator|=( const Bitset & bs) { return bitwise_or(bs); } Bitset operator|( const Bitset & ) const; /// Computes bitwise-exclusive-or with givine bitset, writing result to /// current set. Bitset & bitwise_xor( const Bitset & ); inline Bitset & operator^=( const Bitset & bs) { return bitwise_xor(bs); } Bitset operator^( const Bitset & ) const; /// Template method performing bitwise conversion to certain type. template<typename T> T to() const; /// Returns textual representation of the bitset as a sequence of 1 and 0. std::string to_string() const; /// Returns unsigned long representation of bitset. inline unsigned long to_ulong() const { return to<unsigned long>(); } /// Returns unsigned long long representation of bitset. inline unsigned long long to_ullong() const { return to<unsigned long long>(); } friend std::ostream & operator<<( std::ostream & os, const Bitset & bs ) { os << bs.to_string(); return os; } //void dump( std::ostream &); // XXX: for debugging }; template<typename T> T Bitset::to() const { // Note: to follow strict aliasing rule, we have to create a temporary copy // of words array. Violating this rule causes optimized code to mess up the // copying logic yielding malformed results. if( sizeof(T)*8 < _size ) throw std::overflow_error("Bitset is too large."); Word_t result[ sizeof(T) > sizeof(Word_t) ? sizeof(T)/sizeof(Word_t) : 1 ]; bzero( result, sizeof(result) ); for( size_t nw = 0; nw < _nWords; ++nw ) { memcpy( result + nw , _data + nw , sizeof(Word_t) ); } *result &= _tailMask; T r; memcpy( &r, result, sizeof(T) ); return r; } template<> std::string Bitset::to<std::string>() const; # if 0 template<size_t N> std::bitset<N> Bitset::to<std::bitset<N>>() const { // ... } # endif } // namespace goo
34.28
84
0.643441
b27646379e7355c5d70bb819fe7d05851993e12d
951
cpp
C++
src/dev/memory_dev.cpp
RupertAvery/et3400
243c0ed407bee20f43e2f1c528f10cc6ffb12664
[ "BSD-3-Clause" ]
3
2020-11-06T22:30:32.000Z
2021-12-24T06:30:32.000Z
src/dev/memory_dev.cpp
RupertAvery/et3400
243c0ed407bee20f43e2f1c528f10cc6ffb12664
[ "BSD-3-Clause" ]
null
null
null
src/dev/memory_dev.cpp
RupertAvery/et3400
243c0ed407bee20f43e2f1c528f10cc6ffb12664
[ "BSD-3-Clause" ]
1
2021-12-24T06:30:38.000Z
2021-12-24T06:30:38.000Z
#include "stdlib.h" #include "memory_dev.h" #include "string.h" memory_device::memory_device(offs_t start, size_t size, bool readonly) { this->readonly = readonly; this->start = start; this->size = size; end = start + size - 1; memory = (uint8_t *)malloc(size); next = NULL; }; memory_device::~memory_device() { free(memory); } uint8_t memory_device::read(offs_t addr) { return memory[addr - start]; }; void memory_device::write(offs_t addr, uint8_t data) { if (!readonly) { memory[addr - start] = data; } }; bool memory_device::is_mapped(offs_t addr) { return addr >= start && addr <= end; } uint8_t *memory_device::get_mapped_memory() { return memory; }; offs_t memory_device::get_start() { return start; }; offs_t memory_device::get_end() { return end; }; void memory_device::load(offs_t addr, uint8_t *data, int size) { memcpy(&memory[addr - start], data, size); }
16.396552
70
0.648791